code stringlengths 31 1.05M | apis list | extract_api stringlengths 97 1.91M |
|---|---|---|
#!/usr/bin/env python
"""stereo_rgb.py: Python functions for interacting with stereo RGB Camera sensor data in TERRA-REF project."""
__author__ = "<NAME>, <NAME>"
import logging
import numpy as np
from scipy.ndimage.filters import convolve
from PIL import Image, ImageFilter
from terrautils.formats import create_geotiff
log = logging.getLogger(__name__)
# bin2tif utilities
def get_image_shape(metadata, side):
"""Extract height/width information from metadata JSON.
Arguments:
metadata (dict): cleaned metadata
side (string): 'right' or 'left'
Throws:
RuntimeError: the image format is not 'BayerGR8'
KeyError: metadata is missing necessary fields
ValueError: when width and height string can't be cast to int
Returns:
(tuple of ints): width and height as tuple
"""
try:
im_meta = metadata['sensor_variable_metadata']
fmt = im_meta['image_format'][side]
if fmt != 'BayerGR8':
log.error('Unknown image format %s' % fmt)
raise RuntimeError('Unknown image format', fmt)
width = im_meta['width_image_pixels'][side]
height = im_meta['height_image_pixels'][side]
except KeyError as err:
log.error('Metadata file missing key: %s (has it been cleaned using terrautils.metadata.clean_metadata()?)' % err.args[0])
raise
try:
width = int(width)
height = int(height)
except ValueError as err:
log.error('Corrupt image dimension in metadata file')
raise
return (width, height)
def process_raw(shape, bin_file, out_file=None):
"""Read image file into array, demosaic, rotate into output image.
Arguments:
shape (tuple of ints): the width, height of the bin_file
bin_file (string): filepath to .bin file to be processed
out_file (string): filepath where image will be saved (optional)
Throws:
various: unable to read .bin file, unable to write image or
problems with demosaicing
Returns:
(numpy array): rotated, demosaiced image
"""
try:
im = np.fromfile(bin_file, dtype='uint8').reshape(shape[::-1])
im_color = demosaic(im)
im_color = (np.rot90(im_color))
if out_file:
Image.fromarray(im_color).save(out_file)
except Exception as ex:
log.error('Error creating "%s" from "%s": %s' % \
(out_file, bin_file, str(ex)))
raise
return im_color
def demosaic(im):
"""Demosaic the BayerGR8 image.
Arguments:
im (numpy array): BayerGR8 image with shape (height, width)
Returns:
(numpy array): RGB image with shape (height, width)
"""
# Assuming GBRG ordering.
B = np.zeros_like(im)
R = np.zeros_like(im)
G = np.zeros_like(im)
R[0::2, 1::2] = im[0::2, 1::2]
B[1::2, 0::2] = im[1::2, 0::2]
G[0::2, 0::2] = im[0::2, 0::2]
G[1::2, 1::2] = im[1::2, 1::2]
fG = np.asarray(
[[0, 1, 0],
[1, 4, 1],
[0, 1, 0]]) / 4.0
fRB = np.asarray(
[[1, 2, 1],
[2, 4, 2],
[1, 2, 1]]) / 4.0
im_color = np.zeros(im.shape+(3,), dtype='uint8') #RGB
im_color[:, :, 0] = convolve(R, fRB)
im_color[:, :, 1] = convolve(G, fG)
im_color[:, :, 2] = convolve(B, fRB)
return im_color
def bin2tif(inbin, outtif, shape, bounds, metadata):
"""
:param inbin: a left or right stereoRGB bin file
:param outtif: output GeoTIFF file
:param shape: (width, height) of image in pixels derived from sensor_variable_metadata
:param bounds: bounding box of image derived from spatial_metadata bounding_box
:param metadata: any metadata to embed inside created geotiff
"""
img = process_raw(shape, inbin, None)
create_geotiff(img, bounds, outtif, None, False, extra_metadata=metadata)
# canopycover utilities
def calculate_canopycover(pxarray):
"""Return greenness percentage of given numpy array of pixels.
Arguments:
pxarray (numpy array): rgb image
Returns:
(float): greenness percentage
"""
r = pxarray[:, :, 0]
g = pxarray[:, :, 1]
b = pxarray[:, :, 2]
sub_img = (g.astype('int') - r.astype('int') - 2) > 0
mask = np.zeros_like(b)
mask[sub_img] = 255
im = Image.fromarray(mask)
blur = im.filter(ImageFilter.BLUR)
blur_pix = np.array(blur)
sub_mask = blur_pix > 128
c = np.count_nonzero(sub_mask)
ratio = c/float(b.size)
# Scale ratio from 0-1 to 0-100
ratio *= 100.0
return ratio
| [
"logging.getLogger",
"PIL.Image.fromarray",
"numpy.fromfile",
"terrautils.formats.create_geotiff",
"numpy.asarray",
"numpy.count_nonzero",
"numpy.array",
"numpy.zeros",
"scipy.ndimage.filters.convolve",
"numpy.rot90",
"numpy.zeros_like"
] | [((333, 360), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (350, 360), False, 'import logging\n'), ((2746, 2763), 'numpy.zeros_like', 'np.zeros_like', (['im'], {}), '(im)\n', (2759, 2763), True, 'import numpy as np\n'), ((2772, 2789), 'numpy.zeros_like', 'np.zeros_like', (['im'], {}), '(im)\n', (2785, 2789), True, 'import numpy as np\n'), ((2798, 2815), 'numpy.zeros_like', 'np.zeros_like', (['im'], {}), '(im)\n', (2811, 2815), True, 'import numpy as np\n'), ((3174, 3214), 'numpy.zeros', 'np.zeros', (['(im.shape + (3,))'], {'dtype': '"""uint8"""'}), "(im.shape + (3,), dtype='uint8')\n", (3182, 3214), True, 'import numpy as np\n'), ((3242, 3258), 'scipy.ndimage.filters.convolve', 'convolve', (['R', 'fRB'], {}), '(R, fRB)\n', (3250, 3258), False, 'from scipy.ndimage.filters import convolve\n'), ((3283, 3298), 'scipy.ndimage.filters.convolve', 'convolve', (['G', 'fG'], {}), '(G, fG)\n', (3291, 3298), False, 'from scipy.ndimage.filters import convolve\n'), ((3323, 3339), 'scipy.ndimage.filters.convolve', 'convolve', (['B', 'fRB'], {}), '(B, fRB)\n', (3331, 3339), False, 'from scipy.ndimage.filters import convolve\n'), ((3812, 3885), 'terrautils.formats.create_geotiff', 'create_geotiff', (['img', 'bounds', 'outtif', 'None', '(False)'], {'extra_metadata': 'metadata'}), '(img, bounds, outtif, None, False, extra_metadata=metadata)\n', (3826, 3885), False, 'from terrautils.formats import create_geotiff\n'), ((4274, 4290), 'numpy.zeros_like', 'np.zeros_like', (['b'], {}), '(b)\n', (4287, 4290), True, 'import numpy as np\n'), ((4325, 4346), 'PIL.Image.fromarray', 'Image.fromarray', (['mask'], {}), '(mask)\n', (4340, 4346), False, 'from PIL import Image, ImageFilter\n'), ((4401, 4415), 'numpy.array', 'np.array', (['blur'], {}), '(blur)\n', (4409, 4415), True, 'import numpy as np\n'), ((4455, 4481), 'numpy.count_nonzero', 'np.count_nonzero', (['sub_mask'], {}), '(sub_mask)\n', (4471, 4481), True, 'import numpy as np\n'), ((2225, 2243), 'numpy.rot90', 'np.rot90', (['im_color'], {}), '(im_color)\n', (2233, 2243), True, 'import numpy as np\n'), ((2966, 3011), 'numpy.asarray', 'np.asarray', (['[[0, 1, 0], [1, 4, 1], [0, 1, 0]]'], {}), '([[0, 1, 0], [1, 4, 1], [0, 1, 0]])\n', (2976, 3011), True, 'import numpy as np\n'), ((3067, 3112), 'numpy.asarray', 'np.asarray', (['[[1, 2, 1], [2, 4, 2], [1, 2, 1]]'], {}), '([[1, 2, 1], [2, 4, 2], [1, 2, 1]])\n', (3077, 3112), True, 'import numpy as np\n'), ((2115, 2151), 'numpy.fromfile', 'np.fromfile', (['bin_file'], {'dtype': '"""uint8"""'}), "(bin_file, dtype='uint8')\n", (2126, 2151), True, 'import numpy as np\n'), ((2278, 2303), 'PIL.Image.fromarray', 'Image.fromarray', (['im_color'], {}), '(im_color)\n', (2293, 2303), False, 'from PIL import Image, ImageFilter\n')] |
import os.path as osp
import mmcv
import numpy as np
import pycocotools.mask as maskUtils
from mmdet.core import BitmapMasks, PolygonMasks
from ..builder import PIPELINES
@PIPELINES.register_module()
class Stack:
def __init__(self):
pass
def __call__(self, results):
"""Call functions to load image and get image meta information.
Args:
results (dict): Result dict from :obj:`mmdet.CustomDataset`.
Returns:
dict: The dict contains loaded image and meta information.
"""
img = results['img'][..., np.newaxis]
img = np.concatenate([img, img, img], axis=2)
results['img'] = img
return results
def __repr__(self):
repr_str = (f'{self.__class__.__name__}('
f'stack grayscale image into three channels')
return repr_str | [
"numpy.concatenate"
] | [((610, 649), 'numpy.concatenate', 'np.concatenate', (['[img, img, img]'], {'axis': '(2)'}), '([img, img, img], axis=2)\n', (624, 649), True, 'import numpy as np\n')] |
#!/usr/bin/python2
try:
import gi
gi.require_version('NumCosmo', '1.0')
gi.require_version('NumCosmoMath', '1.0')
except:
pass
import math
import numpy as np
import matplotlib.pyplot as plt
from gi.repository import GObject
from gi.repository import NumCosmo as Nc
from gi.repository import NumCosmoMath as Ncm
#
# Initializing the library objects, this must be called before
# any other library function.
#
Ncm.cfg_init ()
#
# Script parameters
#
# Maximum multipole
lmax = 2500
#
# Creating a new instance of HIPrimPowerLaw
#
prim = Nc.HIPrimPowerLaw.new ()
prim.props.T_SA_ratio = 2.0e-1
#
# New CLASS backend precision object
# Lets also increase k_per_decade_primordial since we are
# dealing with a modified spectrum.
#
cbe_prec = Nc.CBEPrecision.new ()
cbe_prec.props.k_per_decade_primordial = 50.0
#
# New CLASS backend object
#
cbe = Nc.CBE.prec_new (cbe_prec)
#
# New CLASS backend object
#
Bcbe = Nc.HIPertBoltzmannCBE.full_new (cbe)
Bcbe.set_TT_lmax (lmax)
# Setting which CMB data to use
Bcbe.set_target_Cls (Nc.DataCMBDataType.TT)
# Setting if the lensed Cl's are going to be used or not.
Bcbe.set_lensed_Cls (True)
# Setting if the tensor contribution is going to be used or not.
Bcbe.set_tensor (True)
#
# New homogeneous and isotropic cosmological model NcHICosmoDEXcdm
#
cosmo = Nc.HICosmo.new_from_name (Nc.HICosmo, "NcHICosmoDEXcdm")
cosmo.omega_x2omega_k ()
cosmo.param_set_by_name ("Omegak", 0.0)
#
# New homogeneous and isotropic reionization object
#
reion = Nc.HIReionCamb.new ()
#
# Adding submodels to the main cosmological model.
#
cosmo.add_submodel (reion)
cosmo.add_submodel (prim)
#
# Preparing the Class backend object
#
Bcbe.prepare (cosmo)
Cls1 = Ncm.Vector.new (lmax + 1)
Cls2 = Ncm.Vector.new (lmax + 1)
Bcbe.get_TT_Cls (Cls1)
prim.props.T_SA_ratio = 1.0e-15
Bcbe.prepare (cosmo)
Bcbe.get_TT_Cls (Cls2)
Cls1_a = Cls1.dup_array ()
Cls2_a = Cls2.dup_array ()
Cls1_a = np.array (Cls1_a[2:])
Cls2_a = np.array (Cls2_a[2:])
ell = np.array (range (2, lmax + 1))
Cls1_a = ell * (ell + 1.0) * Cls1_a
Cls2_a = ell * (ell + 1.0) * Cls2_a
#
# Ploting the TT angular power spcetrum
#
plt.title (r'With and without tensor contribution to $C_\ell$')
plt.xscale('log')
plt.plot (ell, Cls1_a, 'r', label="with-T")
plt.plot (ell, Cls2_a, 'b--', label="without-T")
plt.xlabel(r'$\ell$')
plt.ylabel(r'$C_\ell$')
plt.legend(loc=2)
plt.savefig ("hiprim_tensor_Cls.svg")
plt.clf ()
| [
"gi.repository.NumCosmo.HIReionCamb.new",
"gi.repository.NumCosmoMath.cfg_init",
"matplotlib.pyplot.savefig",
"gi.repository.NumCosmo.HICosmo.new_from_name",
"gi.repository.NumCosmo.CBE.prec_new",
"gi.repository.NumCosmoMath.Vector.new",
"matplotlib.pyplot.ylabel",
"gi.repository.NumCosmo.HIPrimPowerL... | [((422, 436), 'gi.repository.NumCosmoMath.cfg_init', 'Ncm.cfg_init', ([], {}), '()\n', (434, 436), True, 'from gi.repository import NumCosmoMath as Ncm\n'), ((551, 574), 'gi.repository.NumCosmo.HIPrimPowerLaw.new', 'Nc.HIPrimPowerLaw.new', ([], {}), '()\n', (572, 574), True, 'from gi.repository import NumCosmo as Nc\n'), ((757, 778), 'gi.repository.NumCosmo.CBEPrecision.new', 'Nc.CBEPrecision.new', ([], {}), '()\n', (776, 778), True, 'from gi.repository import NumCosmo as Nc\n'), ((865, 890), 'gi.repository.NumCosmo.CBE.prec_new', 'Nc.CBE.prec_new', (['cbe_prec'], {}), '(cbe_prec)\n', (880, 890), True, 'from gi.repository import NumCosmo as Nc\n'), ((932, 967), 'gi.repository.NumCosmo.HIPertBoltzmannCBE.full_new', 'Nc.HIPertBoltzmannCBE.full_new', (['cbe'], {}), '(cbe)\n', (962, 967), True, 'from gi.repository import NumCosmo as Nc\n'), ((1324, 1379), 'gi.repository.NumCosmo.HICosmo.new_from_name', 'Nc.HICosmo.new_from_name', (['Nc.HICosmo', '"""NcHICosmoDEXcdm"""'], {}), "(Nc.HICosmo, 'NcHICosmoDEXcdm')\n", (1348, 1379), True, 'from gi.repository import NumCosmo as Nc\n'), ((1512, 1532), 'gi.repository.NumCosmo.HIReionCamb.new', 'Nc.HIReionCamb.new', ([], {}), '()\n', (1530, 1532), True, 'from gi.repository import NumCosmo as Nc\n'), ((1714, 1738), 'gi.repository.NumCosmoMath.Vector.new', 'Ncm.Vector.new', (['(lmax + 1)'], {}), '(lmax + 1)\n', (1728, 1738), True, 'from gi.repository import NumCosmoMath as Ncm\n'), ((1747, 1771), 'gi.repository.NumCosmoMath.Vector.new', 'Ncm.Vector.new', (['(lmax + 1)'], {}), '(lmax + 1)\n', (1761, 1771), True, 'from gi.repository import NumCosmoMath as Ncm\n'), ((1939, 1959), 'numpy.array', 'np.array', (['Cls1_a[2:]'], {}), '(Cls1_a[2:])\n', (1947, 1959), True, 'import numpy as np\n'), ((1970, 1990), 'numpy.array', 'np.array', (['Cls2_a[2:]'], {}), '(Cls2_a[2:])\n', (1978, 1990), True, 'import numpy as np\n'), ((2150, 2212), 'matplotlib.pyplot.title', 'plt.title', (['"""With and without tensor contribution to $C_\\\\ell$"""'], {}), "('With and without tensor contribution to $C_\\\\ell$')\n", (2159, 2212), True, 'import matplotlib.pyplot as plt\n'), ((2214, 2231), 'matplotlib.pyplot.xscale', 'plt.xscale', (['"""log"""'], {}), "('log')\n", (2224, 2231), True, 'import matplotlib.pyplot as plt\n'), ((2232, 2274), 'matplotlib.pyplot.plot', 'plt.plot', (['ell', 'Cls1_a', '"""r"""'], {'label': '"""with-T"""'}), "(ell, Cls1_a, 'r', label='with-T')\n", (2240, 2274), True, 'import matplotlib.pyplot as plt\n'), ((2276, 2323), 'matplotlib.pyplot.plot', 'plt.plot', (['ell', 'Cls2_a', '"""b--"""'], {'label': '"""without-T"""'}), "(ell, Cls2_a, 'b--', label='without-T')\n", (2284, 2323), True, 'import matplotlib.pyplot as plt\n'), ((2326, 2347), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""$\\\\ell$"""'], {}), "('$\\\\ell$')\n", (2336, 2347), True, 'import matplotlib.pyplot as plt\n'), ((2348, 2371), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""$C_\\\\ell$"""'], {}), "('$C_\\\\ell$')\n", (2358, 2371), True, 'import matplotlib.pyplot as plt\n'), ((2372, 2389), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '(2)'}), '(loc=2)\n', (2382, 2389), True, 'import matplotlib.pyplot as plt\n'), ((2391, 2427), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""hiprim_tensor_Cls.svg"""'], {}), "('hiprim_tensor_Cls.svg')\n", (2402, 2427), True, 'import matplotlib.pyplot as plt\n'), ((2430, 2439), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (2437, 2439), True, 'import matplotlib.pyplot as plt\n'), ((39, 76), 'gi.require_version', 'gi.require_version', (['"""NumCosmo"""', '"""1.0"""'], {}), "('NumCosmo', '1.0')\n", (57, 76), False, 'import gi\n'), ((79, 120), 'gi.require_version', 'gi.require_version', (['"""NumCosmoMath"""', '"""1.0"""'], {}), "('NumCosmoMath', '1.0')\n", (97, 120), False, 'import gi\n')] |
#!/usr/bin/env python3
import pickle
import os
import numpy as np
def get_sweep_parameters(parameters, env_config, index):
"""
Gets the parameters for the hyperparameter sweep defined by the index.
Each hyperparameter setting has a specific index number, and this function
will get the appropriate parameters for the argument index. In addition,
this the indices will wrap around, so if there are a total of 10 different
hyperparameter settings, then the indices 0 and 10 will return the same
hyperparameter settings. This is useful for performing loops.
For example, if you had 10 hyperparameter settings and you wanted to do
10 runs, the you could just call this for indices in range(0, 10*10). If
you only wanted to do runs for hyperparameter setting i, then you would
use indices in range(i, 10, 10*10)
Parameters
----------
parameters : dict
The dictionary of parameters, as found in the agent's json
configuration file
env_config : dict
The environment configuration dictionary, as found in the environment's
json configuration file
index : int
The index of the hyperparameters configuration to return
Returns
-------
dict, int
The dictionary of hyperparameters to use for the agent and the total
number of combinations of hyperparameters (highest possible unique
index)
"""
out_params = {}
out_params["gamma"] = env_config["gamma"]
accum = 1
for key in parameters:
num = len(parameters[key])
out_params[key] = parameters[key][(index // accum) % num]
accum *= num
return (out_params, accum)
def get_sweep_num(parameters):
"""
Similar to get_sweep_parameters but only returns the total number of
hyperparameter combinations. This number is the total number of distinct
hyperparameter settings. If this function returns k, then there are k
distinct hyperparameter settings, and indices 0 and k refer to the same
distinct hyperparameter setting.
Parameters
----------
parameters : dict
The dictionary of parameters, as found in the agent's json
configuration file
Returns
-------
int
The number of distinct hyperparameter settings
"""
accum = 1
for key in parameters:
num = len(parameters[key])
accum *= num
return accum
def get_hyperparam_indices(data, hp_name, hp_value):
"""
Gets all hyperparameter indices that have the hyperparameter hp_name
having the value hp_value.
Parameters
----------
data : dict
The data dictionary generated from running main.py
hp_name : str
The name of the hyperparameter to check the value of
hp_value : object
The value that the hyperparameter should have in each hyperparameter
settings index
Returns
-------
list of int
The hyperparameter settings that have the argument hyperparameter
hp_name having the argument value hp_value
"""
agent_param = data["experiment"]["agent"]["parameters"]
env_config = data["experiment"]["environment"]
hp_indices = []
for i in range(get_sweep_num(agent_param)):
# Get the hyperparameters for each hyperparameter setting
hp_setting = get_sweep_parameters(agent_param, env_config, i)[0]
if hp_setting[hp_name] == hp_value:
hp_indices.append(i)
return hp_indices
def get_varying_single_hyperparam(data, hp_name):
"""
Gets the hyperparameter indices where only a single hyperparameter is
varying and all other hyperparameters remain constant.
Parameters
----------
data : dict
The data dictionary generated from running main.py
hp_name : str
The name of the hyperparameter to vary
Returns
-------
n-tuple of m-tuple of int
Gets and returns the hyperparameter indices where only a single
hyperparameter is varying and all others remain constant. The
total number of values that the varying hyperparameter can take on
is m; n is the total number of hyperparameter combinations // m.
For example, if the hyperparameter is the decay rate and it can take
on values in [0.0, 0.1, 0.5] and there are a total of 81 hyperparameter
settings combinations, then m = 3 and n = 81 // 3 = 27
"""
agent_param = data["experiment"]["agent"]["parameters"]
hps = [] # set(range(exp.get_sweep_num(agent_param)))
for hp_value in agent_param[hp_name]:
hps.append(get_hyperparam_indices(data, hp_name, hp_value))
return tuple(zip(*hps))
def get_best_hp(data, type_, after=0):
"""
Gets and returns a list of the hyperparameter settings, sorted by average
return.
Parameters
----------
data : dict
They Python data dictionary generated from running main.py
type_ : str
The type of return by which to compare hyperparameter settings, one of
"train" or "eval"
after : int, optional
Hyperparameters will only be compared by their performance after
training for this many episodes (in continuing tasks, this is the
number of times the task is restarted). For example, if after = -10,
then only the last 10 returns from training/evaluation are taken
into account when comparing the hyperparameters. As usual, positive
values index from the front, and negative values index from the back.
Returns
-------
n-tuple of 2-tuple(int, float)
A tuple with the number of elements equal to the total number of
hyperparameter combinations. Each sub-tuple is a tuple of (hyperparameter
setting number, mean return over all runs and episodes)
"""
if type_ not in ("train", "eval"):
raise ValueError("type_ should be one of 'train', 'eval'")
return_type = "train_episode_rewards" if type_ == "train" \
else "eval_episode_rewards"
mean_returns = []
hp_settings = sorted(list(data["experiment_data"].keys()))
for hp_setting in hp_settings:
hp_returns = []
for run in data["experiment_data"][hp_setting]["runs"]:
hp_returns.append(run[return_type])
hp_returns = np.stack(hp_returns)
# If evaluating, use the mean return over all episodes for each
# evaluation interval. That is, if 10 eval episodes for each evaluation
# the take the average return over all these eval episodes
if type_ == "eval":
hp_returns = hp_returns.mean(axis=-1)
# Calculate the average return over all runs
hp_returns = hp_returns[after:, :].mean(axis=0)
# Calculate the average return over all "episodes"
hp_returns = hp_returns.mean(axis=0)
# Save mean return
mean_returns.append(hp_returns)
# Return the best hyperparam settings in order with the
# mean returns sorted by hyperparmater setting performance
best_hp_settings = np.argsort(mean_returns)
mean_returns = np.array(mean_returns)[best_hp_settings]
return tuple(zip(best_hp_settings, mean_returns))
def combine_runs(data1, data2):
"""
Adds the runs for each hyperparameter setting in data2 to the runs for the
corresponding hyperparameter setting in data1.
Given two data dictionaries, this function will get each hyperparameter
setting and extend the runs done on this hyperparameter setting and saved
in data1 by the runs of this hyperparameter setting and saved in data2.
In short, this function extends the lists
data1["experiment_data"][i]["runs"] by the lists
data2["experiment_data"][i]["runs"] for all i. This is useful if
multiple runs are done at different times, and the two data files need
to be combined.
Parameters
----------
data1 : dict
A data dictionary as generated by main.py
data2 : dict
A data dictionary as generated by main.py
Raises
------
KeyError
If a hyperparameter setting exists in data2 but not in data1. This
signals that the hyperparameter settings indices are most likely
different, so the hyperparameter index i in data1 does not correspond
to the same hyperparameter index in data2. In addition, all other
functions expect the number of runs to be consistent for each
hyperparameter setting, which would be violated in this case.
"""
for hp_setting in data1["experiment_data"]:
if hp_setting not in data2.keys():
# Ensure consistent hyperparam settings indices
raise KeyError("hyperparameter settings are different " +
"between the two experiments")
extra_runs = data2["experiment_data"][hp_setting]["runs"]
data1["experiment_data"][hp_setting]["runs"].extend(extra_runs)
def get_returns(data, type_, ind):
"""
Gets the returns seen by an agent
Gets the online or offline returns seen by an agent trained with
hyperparameter settings index ind.
Parameters
----------
data : dict
The Python data dictionary generated from running main.py
type_ : str
Whether to get the training or evaluation returns, one of 'train',
'eval'
ind : int
Gets the returns of the agent trained with this hyperparameter
settings index
Returns
-------
array_like
The array of returns of the form (N, R, C) where N is the number of
runs, R is the number of times a performance was measured, and C is the
number of returns generated each time performance was measured
(offline >= 1; online = 1). For the online setting, N is the number of
runs, and R is the number of episodes and C = 1. For the offline
setting, N is the number of runs, R is the number of times offline
evaluation was performed, and C is the number of episodes run each
time performance was evaluated offline.
"""
returns = []
if type_ == "eval":
# Get the offline evaluation episode returns per run
for run in data["experiment_data"][ind]["runs"]:
returns.append(run["eval_episode_rewards"])
returns = np.stack(returns)
elif type_ == "train":
# Get the returns per episode per run
for run in data["experiment_data"][ind]["runs"]:
returns.append(run["train_episode_rewards"])
returns = np.expand_dims(np.stack(returns), axis=2)
return returns
def get_hyperparams(data, ind):
"""
Gets the hyperparameters for hyperparameter settings index ind
data : dict
The Python data dictionary generated from running main.py
ind : int
Gets the returns of the agent trained with this hyperparameter
settings index
Returns
-------
dict
The dictionary of hyperparameters
"""
return data["experiment_data"][ind]["agent_params"]
def get_mean_returns_with_stderr_hp_varying(data, type_, hp_name, combo,
after=0):
"""
Calculate mean and standard error of return for each hyperparameter value.
Gets the mean returns for each variation of a single hyperparameter,
with all other hyperparameters remaining constant. Since there are
many different ways this can happen (the hyperparameter can vary
with all other remaining constant, but there are many combinations
of these constant hyperparameters), the combo argument cycles through
the combinations of constant hyperparameters.
Given hyperparameters a, b, and c, let's say we want to get all
hyperparameter settings indices where a varies, and b and c are constant.
if a, b, and c can each be 1 or 2, then there are four ways that a can
vary with b and c remaining constant:
[
((a=1, b=1, c=1), (a=2, b=1, c=1)), combo = 0
((a=1, b=2, c=1), (a=2, b=2, c=1)), combo = 1
((a=1, b=1, c=2), (a=2, b=1, c=2)), combo = 2
((a=1, b=2, c=2), (a=2, b=2, c=2)) combo = 3
]
The combo argument indexes into this list of hyperparameter settings
Parameters
----------
data : dict
The Python data dictionary generated from running main.py
type_ : str
Which type of data to plot, one of "eval" or "train"
combo : int
Determines the values of the constant hyperparameters. Given that
only one hyperparameter may vary, there are many different sets
having this hyperparameter varying with all others remaining constant
since each constant hyperparameter may take on many values. This
argument cycles through all sets of hyperparameter settings indices
that have only one hyperparameter varying and all others constant.
"""
hp_combo = get_varying_single_hyperparam(data, hp_name)[combo]
mean_returns = []
stderr_returns = []
for hp in hp_combo:
mean_return = get_returns(data, type_, hp)
# If evaluating, use the mean return over all episodes for each
# evaluation interval. That is, if 10 eval episodes for each evaluation
# the take the average return over all these eval episodes.
# If online returns, this axis has a length of 1 so we reduce it
mean_return = mean_return.mean(axis=-1)
# Calculate the average return over all "episodes"
# print(mean_return[:, after:].shape)
mean_return = mean_return[:, after:].mean(axis=1)
# Calculate the average return over all runs
stderr_return = np.std(mean_return, axis=0) / \
np.sqrt(mean_return.shape[0])
mean_return = mean_return.mean(axis=0)
mean_returns.append(mean_return)
stderr_returns.append(stderr_return)
# Get each hp value and sort all results by hp value
hp_values = np.array(data["experiment"]["agent"]["parameters"][hp_name])
indices = np.argsort(hp_values)
mean_returns = np.array(mean_returns)[indices]
stderr_returns = np.array(stderr_returns)[indices]
hp_values = hp_values[indices]
return hp_values, mean_returns, stderr_returns
def get_mean_stderr(data, type_, ind, smooth_over):
"""
Gets the timesteps, mean, and standard error to be plotted for
a given hyperparameter settings index
Parameters
----------
data : dict
The Python data dictionary generated from running main.py
type_ : str
Which type of data to plot, one of "eval" or "train"
ind : int
The hyperparameter settings index to plot
smooth_over : int
The number of previous data points to smooth over. Note that this
is *not* the number of timesteps to smooth over, but rather the number
of data points to smooth over. For example, if you save the return
every 1,000 timesteps, then setting this value to 15 will smooth
over the last 15 readings, or 15,000 timesteps.
Returns
-------
3-tuple of list(int), list(float), list(float)
The timesteps, mean episodic returns, and standard errors of the
episodic returns
"""
timesteps = None # So the linter doesn't have a temper tantrum
# Determine the timesteps to plot at
if type_ == "eval":
timesteps = \
data["experiment_data"][ind]["runs"][0]["timesteps_at_eval"]
elif type_ == "train":
timesteps_per_ep = \
data["experiment_data"][ind]["runs"][0]["train_episode_steps"]
timesteps = get_cumulative_timesteps(timesteps_per_ep)
# Get the mean over all episodes per evaluation step (for online
# returns, this axis will have length 1 so we squeeze it)
returns = get_returns(data, type_, ind)
mean = returns.mean(axis=-1)
# Get the standard deviation of mean episodes per evaluation
# step over all runs
runs = returns.shape[0]
std = np.std(mean, axis=0) / np.sqrt(runs)
# Get the mean over all runs
mean = mean.mean(axis=0)
# Smooth of last k returns if applicable, convolve will initially only
# start sliding from the beginning, so we need to cut off the initial
# averages which are incomplete
if smooth_over > 1:
mean = np.convolve(mean, np.ones(smooth_over) /
smooth_over, mode="valid") #[smooth_over:mean.shape[0]]
std = np.convolve(std, np.ones(smooth_over) /
smooth_over, mode="valid") #[smooth_over:std.shape[0]]
# np.convolve only goes until the last element of the convolution
# lines up with the last element of the data, so smooth_over elements
# will be lost
timesteps = timesteps[:-smooth_over + 1]
return timesteps, mean, std
def get_cumulative_timesteps(timesteps_per_episode):
"""
Creates an array of cumulative timesteps.
Creates an array of timesteps, where each timestep is the cumulative
number of timesteps up until that point. This is needed for plotting the
training data, where the training timesteps are stored for each episode,
and we need to plot on the x-axis the cumulative timesteps, not the
timesteps per episode.
Parameters
----------
timesteps_per_episode : list
A list where each element in the list denotes the amount of timesteps
for the corresponding episode.
Returns
-------
array_like
An array where each element is the cumulative number of timesteps up
until that point.
"""
timesteps_per_episode = np.array(timesteps_per_episode)
cumulative_timesteps = [timesteps_per_episode[:i].sum()
for i in range(timesteps_per_episode.shape[0])]
return np.array(cumulative_timesteps)
def combine_data_dictionaries(files, save=True, save_dir=".", filename="data"):
"""
Combine data dictionaries given a list of filenames
Given a list of paths to data dictionaries, combines each data dictionary
into a single one.
Parameters
----------
files : list of str
A list of the paths to data dictionary files to combine
save : bool
Whether or not to save the data
save_dir : str, optional
The directory containing the saved dictionaries
filename : str, optional
The name of the file to save which stores the combined data, by default
'data'
Returns
-------
dict
The combined dictionary
"""
# Use first dictionary as base dictionary
with open(os.path.join(save_dir, files[0]), "rb") as in_file:
data = pickle.load(in_file)
# Add data from all other dictionaries
for file in files[1:]:
with open(os.path.join(save_dir, file), "rb") as in_file:
# Read in the new dictionary
in_data = pickle.load(in_file)
# Add experiment data to running dictionary
for key in in_data["experiment_data"]:
# Check if key exists
if key in data["experiment_data"]:
# Append data if existing
data["experiment_data"][key]["runs"] \
.extend(in_data["experiment_data"][key]["runs"])
else:
# Key doesn't exist - add data to dictionary
data["experiment_data"][key] = \
in_data["experiment_data"][key]
if save:
with open(os.path.join(save_dir, f"{filename}.pkl"), "wb") as out_file:
pickle.dump(data, out_file)
return data
| [
"numpy.sqrt",
"pickle.dump",
"numpy.ones",
"pickle.load",
"os.path.join",
"numpy.argsort",
"numpy.array",
"numpy.stack",
"numpy.std"
] | [((7054, 7078), 'numpy.argsort', 'np.argsort', (['mean_returns'], {}), '(mean_returns)\n', (7064, 7078), True, 'import numpy as np\n'), ((13995, 14055), 'numpy.array', 'np.array', (["data['experiment']['agent']['parameters'][hp_name]"], {}), "(data['experiment']['agent']['parameters'][hp_name])\n", (14003, 14055), True, 'import numpy as np\n'), ((14070, 14091), 'numpy.argsort', 'np.argsort', (['hp_values'], {}), '(hp_values)\n', (14080, 14091), True, 'import numpy as np\n'), ((17674, 17705), 'numpy.array', 'np.array', (['timesteps_per_episode'], {}), '(timesteps_per_episode)\n', (17682, 17705), True, 'import numpy as np\n'), ((17854, 17884), 'numpy.array', 'np.array', (['cumulative_timesteps'], {}), '(cumulative_timesteps)\n', (17862, 17884), True, 'import numpy as np\n'), ((6305, 6325), 'numpy.stack', 'np.stack', (['hp_returns'], {}), '(hp_returns)\n', (6313, 6325), True, 'import numpy as np\n'), ((7098, 7120), 'numpy.array', 'np.array', (['mean_returns'], {}), '(mean_returns)\n', (7106, 7120), True, 'import numpy as np\n'), ((10304, 10321), 'numpy.stack', 'np.stack', (['returns'], {}), '(returns)\n', (10312, 10321), True, 'import numpy as np\n'), ((14112, 14134), 'numpy.array', 'np.array', (['mean_returns'], {}), '(mean_returns)\n', (14120, 14134), True, 'import numpy as np\n'), ((14165, 14189), 'numpy.array', 'np.array', (['stderr_returns'], {}), '(stderr_returns)\n', (14173, 14189), True, 'import numpy as np\n'), ((16034, 16054), 'numpy.std', 'np.std', (['mean'], {'axis': '(0)'}), '(mean, axis=0)\n', (16040, 16054), True, 'import numpy as np\n'), ((16057, 16070), 'numpy.sqrt', 'np.sqrt', (['runs'], {}), '(runs)\n', (16064, 16070), True, 'import numpy as np\n'), ((18719, 18739), 'pickle.load', 'pickle.load', (['in_file'], {}), '(in_file)\n', (18730, 18739), False, 'import pickle\n'), ((13713, 13740), 'numpy.std', 'np.std', (['mean_return'], {'axis': '(0)'}), '(mean_return, axis=0)\n', (13719, 13740), True, 'import numpy as np\n'), ((13757, 13786), 'numpy.sqrt', 'np.sqrt', (['mean_return.shape[0]'], {}), '(mean_return.shape[0])\n', (13764, 13786), True, 'import numpy as np\n'), ((18652, 18684), 'os.path.join', 'os.path.join', (['save_dir', 'files[0]'], {}), '(save_dir, files[0])\n', (18664, 18684), False, 'import os\n'), ((18940, 18960), 'pickle.load', 'pickle.load', (['in_file'], {}), '(in_file)\n', (18951, 18960), False, 'import pickle\n'), ((19639, 19666), 'pickle.dump', 'pickle.dump', (['data', 'out_file'], {}), '(data, out_file)\n', (19650, 19666), False, 'import pickle\n'), ((10543, 10560), 'numpy.stack', 'np.stack', (['returns'], {}), '(returns)\n', (10551, 10560), True, 'import numpy as np\n'), ((16377, 16397), 'numpy.ones', 'np.ones', (['smooth_over'], {}), '(smooth_over)\n', (16384, 16397), True, 'import numpy as np\n'), ((16514, 16534), 'numpy.ones', 'np.ones', (['smooth_over'], {}), '(smooth_over)\n', (16521, 16534), True, 'import numpy as np\n'), ((18829, 18857), 'os.path.join', 'os.path.join', (['save_dir', 'file'], {}), '(save_dir, file)\n', (18841, 18857), False, 'import os\n'), ((19565, 19606), 'os.path.join', 'os.path.join', (['save_dir', 'f"""{filename}.pkl"""'], {}), "(save_dir, f'{filename}.pkl')\n", (19577, 19606), False, 'import os\n')] |
"""
Plot figure 4A, the results of swapping tissue types between cancer types
and the effect on the performance of svMIL2.
"""
## for eah cancer type, get the performance from all swap folders
import os
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
#Names of the cancer types
cancerTypes = ['Breast', 'Colorectal', 'Esophagus', 'Lung', 'Kidney', 'NervousSystem', 'Ovary',
'Pancreas', 'Prostate', 'Skin', 'UrinaryTract', 'Uterus']
#the names of the tissue we used for them, these should be in the same order as
#the cancer types, so that we know what the 'original' run is to compare the
#performance to
baselines = ['hmec', 'coad', 'esophagus', 'luad', 'kidney', 'nervousSystem', 'ov',
'pancreas', 'prostate', 'skin', 'urinaryTract', 'uterus']
#these are all types that we made the swaps with.
allTypes = ['hmec', 'coad', 'esophagus', 'luad', 'kidney', 'nervousSystem', 'ov', 'pancreas',
'prostate', 'skin', 'urinaryTract', 'uterus', 'gm12878']
svTypes = ['DEL', 'DUP', 'INV', 'ITX']
differencesAcrossCancerTypes = []
for cancerTypeInd in range(0, len(cancerTypes)):
cancerType = cancerTypes[cancerTypeInd]
baseline = baselines[cancerTypeInd]
aucs = dict()
for swapType in allTypes:
swapFolder = 'HMF_' + cancerType + '_' + swapType
aucs[swapFolder] = []
for svType in svTypes:
outFile = 'output/' + swapFolder + '/multipleInstanceLearning/leaveOnePatientOutCV/leaveOnePatientOutCV_' + svType + '_FINAL_AUC.txt'
#skip runs for which there was no output due to e.g. no SVs
if os.path.isfile(outFile) == True:
aucData = np.loadtxt(outFile, dtype='object')
aucData = aucData[0]
svAuc = float(aucData[0])
aucs[swapFolder].append(svAuc)
else:
aucs[swapFolder].append(0)
#compare the performance to the baseline
baseData = 'HMF_' + cancerType + '_' + baseline
baseAUCs = aucs[baseData]
allDifferences = []
for swapType in allTypes:
swapFolder = 'HMF_' + cancerType + '_' + swapType
#compute the total difference from the baseline
differenceFromBase = 0
for svTypeInd in range(0, len(svTypes)):
baseAUC = baseAUCs[svTypeInd]
swapAUC = aucs[swapFolder][svTypeInd]
#avoid failed runs that will give a huge difference (e.g. no pathogenic SVs with swap)
if swapAUC == 0:
continue
differenceFromBase += (swapAUC - baseAUC)
allDifferences.append(differenceFromBase)
#compute a z-score from the swap - original difference to the mean and std
#of ALL the other swaps made for that cancer type, and assess if the
#difference is really significant.
zDifferences = []
for difference in allDifferences:
if np.mean(allDifferences) == 0 or np.std(allDifferences) == 0:
zDifferences.append(0)
continue
z = (difference - np.mean(allDifferences)) / np.std(allDifferences)
if z >= 1 and z < 2:
zDifferences.append(1)
elif z >= 2:
zDifferences.append(2)
elif z <= -1 and z > -2:
zDifferences.append(-1)
elif z <= -2:
zDifferences.append(-2)
else:
zDifferences.append(0)
differencesAcrossCancerTypes.append(zDifferences)
#make a plot showing the differences
fig =plt.figure(figsize=(5,5))
data = pd.DataFrame(differencesAcrossCancerTypes)
g=sns.heatmap(data,annot=False,square=True, linewidths=0.5,
xticklabels=cancerTypes + ['GM12878'], yticklabels=cancerTypes,
cmap="vlag", center=0, vmin=-2, vmax=2)
plt.tight_layout()
plt.savefig('output/figures/figure5.svg') | [
"numpy.mean",
"matplotlib.pyplot.savefig",
"seaborn.heatmap",
"os.path.isfile",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.tight_layout",
"numpy.std",
"pandas.DataFrame",
"numpy.loadtxt"
] | [((3141, 3167), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(5, 5)'}), '(figsize=(5, 5))\n', (3151, 3167), True, 'import matplotlib.pyplot as plt\n'), ((3175, 3217), 'pandas.DataFrame', 'pd.DataFrame', (['differencesAcrossCancerTypes'], {}), '(differencesAcrossCancerTypes)\n', (3187, 3217), True, 'import pandas as pd\n'), ((3220, 3393), 'seaborn.heatmap', 'sns.heatmap', (['data'], {'annot': '(False)', 'square': '(True)', 'linewidths': '(0.5)', 'xticklabels': "(cancerTypes + ['GM12878'])", 'yticklabels': 'cancerTypes', 'cmap': '"""vlag"""', 'center': '(0)', 'vmin': '(-2)', 'vmax': '(2)'}), "(data, annot=False, square=True, linewidths=0.5, xticklabels=\n cancerTypes + ['GM12878'], yticklabels=cancerTypes, cmap='vlag', center\n =0, vmin=-2, vmax=2)\n", (3231, 3393), True, 'import seaborn as sns\n'), ((3392, 3410), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (3408, 3410), True, 'import matplotlib.pyplot as plt\n'), ((3411, 3452), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""output/figures/figure5.svg"""'], {}), "('output/figures/figure5.svg')\n", (3422, 3452), True, 'import matplotlib.pyplot as plt\n'), ((2800, 2822), 'numpy.std', 'np.std', (['allDifferences'], {}), '(allDifferences)\n', (2806, 2822), True, 'import numpy as np\n'), ((1567, 1590), 'os.path.isfile', 'os.path.isfile', (['outFile'], {}), '(outFile)\n', (1581, 1590), False, 'import os\n'), ((1614, 1649), 'numpy.loadtxt', 'np.loadtxt', (['outFile'], {'dtype': '"""object"""'}), "(outFile, dtype='object')\n", (1624, 1649), True, 'import numpy as np\n'), ((2653, 2676), 'numpy.mean', 'np.mean', (['allDifferences'], {}), '(allDifferences)\n', (2660, 2676), True, 'import numpy as np\n'), ((2685, 2707), 'numpy.std', 'np.std', (['allDifferences'], {}), '(allDifferences)\n', (2691, 2707), True, 'import numpy as np\n'), ((2773, 2796), 'numpy.mean', 'np.mean', (['allDifferences'], {}), '(allDifferences)\n', (2780, 2796), True, 'import numpy as np\n')] |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import common_fn as cf
plt.rcParams["svg.hashsalt"]=0
#Input parms
test_lim_arr=np.empty([0,2])
for llim in np.arange(0,1,0.2):
for ulim in np.arange(llim+0.1,1,0.2):
test_lim_arr=np.append(test_lim_arr,[[llim,ulim]],axis=0)
parm_format='{:.1f}'
# Tp
## OG Equation
parm_name='l_lim_testTpro-u_lim_testTpro'
parm_name_array=np.array(['l_lim_testTpro','u_lim_testTpro'])
pre_path='EnvEq/singlecelltype/Tpro/'
cf.mkdirs(pre_path=pre_path,parm_name=parm_name)
### celleq=1E4: rho s.t T- at equilibrium is 10^4
cf.timeseries(pre_path=pre_path,parm_name=parm_name,parm_array=test_lim_arr,parm_format=parm_format,plot_Tpos=False,plot_Tneg=False)
df=cf.eq_values(pre_path=pre_path,parm_name=parm_name,parm_array=test_lim_arr,parm_format=parm_format,parm_name_array=parm_name_array)
df['l_lim_testTpro']=df['l_lim_testTpro'].round(1)
df['u_lim_testTpro']=df['u_lim_testTpro'].round(1)
cf.heatmap_eqvparm(df,pre_path=pre_path,parm_name=parm_name,parm_name_array=parm_name_array,plot_Tpos=False,plot_Tneg=False)
| [
"common_fn.mkdirs",
"common_fn.eq_values",
"common_fn.timeseries",
"numpy.array",
"numpy.append",
"numpy.empty",
"common_fn.heatmap_eqvparm",
"numpy.arange"
] | [((152, 168), 'numpy.empty', 'np.empty', (['[0, 2]'], {}), '([0, 2])\n', (160, 168), True, 'import numpy as np\n'), ((180, 200), 'numpy.arange', 'np.arange', (['(0)', '(1)', '(0.2)'], {}), '(0, 1, 0.2)\n', (189, 200), True, 'import numpy as np\n'), ((409, 455), 'numpy.array', 'np.array', (["['l_lim_testTpro', 'u_lim_testTpro']"], {}), "(['l_lim_testTpro', 'u_lim_testTpro'])\n", (417, 455), True, 'import numpy as np\n'), ((493, 542), 'common_fn.mkdirs', 'cf.mkdirs', ([], {'pre_path': 'pre_path', 'parm_name': 'parm_name'}), '(pre_path=pre_path, parm_name=parm_name)\n', (502, 542), True, 'import common_fn as cf\n'), ((593, 735), 'common_fn.timeseries', 'cf.timeseries', ([], {'pre_path': 'pre_path', 'parm_name': 'parm_name', 'parm_array': 'test_lim_arr', 'parm_format': 'parm_format', 'plot_Tpos': '(False)', 'plot_Tneg': '(False)'}), '(pre_path=pre_path, parm_name=parm_name, parm_array=\n test_lim_arr, parm_format=parm_format, plot_Tpos=False, plot_Tneg=False)\n', (606, 735), True, 'import common_fn as cf\n'), ((729, 869), 'common_fn.eq_values', 'cf.eq_values', ([], {'pre_path': 'pre_path', 'parm_name': 'parm_name', 'parm_array': 'test_lim_arr', 'parm_format': 'parm_format', 'parm_name_array': 'parm_name_array'}), '(pre_path=pre_path, parm_name=parm_name, parm_array=\n test_lim_arr, parm_format=parm_format, parm_name_array=parm_name_array)\n', (741, 869), True, 'import common_fn as cf\n'), ((963, 1096), 'common_fn.heatmap_eqvparm', 'cf.heatmap_eqvparm', (['df'], {'pre_path': 'pre_path', 'parm_name': 'parm_name', 'parm_name_array': 'parm_name_array', 'plot_Tpos': '(False)', 'plot_Tneg': '(False)'}), '(df, pre_path=pre_path, parm_name=parm_name,\n parm_name_array=parm_name_array, plot_Tpos=False, plot_Tneg=False)\n', (981, 1096), True, 'import common_fn as cf\n'), ((216, 245), 'numpy.arange', 'np.arange', (['(llim + 0.1)', '(1)', '(0.2)'], {}), '(llim + 0.1, 1, 0.2)\n', (225, 245), True, 'import numpy as np\n'), ((264, 311), 'numpy.append', 'np.append', (['test_lim_arr', '[[llim, ulim]]'], {'axis': '(0)'}), '(test_lim_arr, [[llim, ulim]], axis=0)\n', (273, 311), True, 'import numpy as np\n')] |
import torch
import numpy as np
from bc.dataset.dataset_lmdb import DatasetReader
from sim2real.augmentation import Augmentation
from sim2real.transformations import ImageTransform
CHANNEL2SPAN = {'depth': 1, 'rgb': 3, 'mask': 1}
class Frames:
def __init__(self,
path,
channels=('depth', ),
limit='',
max_demos=None,
augmentation='',
output_size=224):
"""
Args:
path: path of the dataset
channels: channels to load - rgb, depth, mask
limit: critera to limit first and last idx of getitem
based of the set index of reference
mode: type of array returned by frames
max_demos: maximum number of demos to load frames from
augmentation: augmentation to be applied to frames
"""
assert isinstance(channels, (list, tuple))
for channel in channels:
assert channel in CHANNEL2SPAN.keys()
self.channels = tuple(sorted(channels))
self._dataset = DatasetReader(path, self.channels)
self.infos = self._dataset.infos
self.keys = self._dataset.keys
self._limit = limit
self.keys.set_query_limit(limit)
assert isinstance(augmentation, str)
self._augmentation = Augmentation(augmentation)
self._im_keys = ['rgb', 'depth', 'mask']
self._output_size = output_size
channels_no_mask = [c for c in channels if c != 'mask']
self._num_channels = self.sum_channels(channels_no_mask)
if max_demos is not None:
self.keys.set_max_demos(max_demos)
self._seed_augmentation = None
def __len__(self):
return len(self._dataset)
def __getitem__(self, idx):
db = self._dataset
channels = self.channels
num_channels = self._num_channels
augmentation = self._augmentation
output_size = self._output_size
idx_min, idx_max = self._user2dbidx(idx)
frames = db[idx_min:idx_max]
# convert dic of observation to homogeneous array
frames, masks = self.dict_cat(frames, channels, num_channels)
# convert to tensor
frames = torch.tensor(frames)
masks = torch.tensor(masks)
# map array from [0, 255] to [0, 1]
frames = self.unit_range(frames)
# augment images, works only for depth images
# each sample_sequence generates a new augmentation sequence
# the transformation is consistent across frames
img_size = frames.size()[1:]
augmentation.sample_sequence(img_size=img_size)
if 'rgb' not in channels:
frames = augmentation(frames, masks)
# crop the image to fixed size
# if name is not '', do a random crop else do a center crop
centered_crop = augmentation.name == ''
params_crop = ImageTransform.sample_params(
name_transformation='cropping',
magn=(output_size, output_size),
img_size=img_size)
frames = Augmentation.crop(frames, params_crop, centered_crop)
# maps array from [0, 1] to [-1, 1]
frames = self.normalize(frames)
return frames
@staticmethod
def dict_cat(frames, channels, num_channels):
"""
Concatenate dictionnary of frames split by channels into an array
frames: list of dictionnary containing depth, rgb, mask keys
channels: channels to be concatenated
num_channels: number of channels per frame
"""
channels = [c for c in channels if 'mask' not in c]
size = frames[0][channels[0]].shape[0]
stack_frames = np.zeros((num_channels * len(frames), size, size),
dtype=np.uint8)
stack_masks = np.zeros((len(frames), size, size), dtype=int)
idx_stack = 0
for idx_frame, frame in enumerate(frames):
for channel in channels:
channel_span = CHANNEL2SPAN[channel]
channel_im = frame[channel]
if channel_span > 1:
# put the last dimension of rgb image (numpy way) to the first one (torch way)
channel_im = np.swapaxes(
np.swapaxes(channel_im, 2, 1), 1, 0)
stack_frames[idx_stack:idx_stack + channel_span] = channel_im
idx_stack += channel_span
if 'mask' in frame:
stack_masks[idx_frame] = frame['mask']
return stack_frames, stack_masks
def set_augmentation(self, path):
self._augmentation.set_augmentation(path)
@staticmethod
def unit_range(frames):
"""
frames: uint8 array or torch tensor in [0, 255]
return: float array in [0, 1]
"""
if type(frames) is np.ndarray:
unit_frames = frames.astype(float)
elif type(frames) is torch.Tensor:
unit_frames = frames.float()
# inplace operations
unit_frames /= 255
return unit_frames
@staticmethod
def normalize(frames):
"""
frames: uint8 array in [0, 1]
return: float array in [-1, 1]
"""
# inplace operations
frames -= 0.5
frames /= 0.5
return frames
@staticmethod
def dict_to_tensor(frames,
channels,
num_channels,
output_size=(224, 224),
augmentation_str='',
augmentation=None):
"""
Convert dictionnary of observation to normalized tensor,
augment the images on the way if an augmentation is passed
frames: dictionnary of observations (mime, mujoco, ...)
return: torch tensor in [-1, 1]
"""
frames, masks = Frames.dict_cat(frames, channels, num_channels)
frames = torch.tensor(frames)
masks = torch.tensor(masks)
frames = Frames.unit_range(frames)
if augmentation is None:
augmentation = Augmentation(augmentation_str)
augmentation.sample_sequence(frames.size()[1:])
if 'rgb' not in channels:
frames = augmentation(frames, masks)
# crop is centered if there are not augmentation set
centered_crop = augmentation_str == ''
img_size = frames.size()[1:]
params_crop = ImageTransform.sample_params(
name_transformation='cropping',
magn=output_size,
img_size=img_size)
frames = Augmentation.crop(frames, params_crop, centered_crop)
frames = Frames.normalize(frames)
return frames
@staticmethod
def adjust_shape(x, num_frames, channels):
"""
x: torch tensor with potentially missing num_frames
return: array where first frame is repeated to match num_frames size
"""
assert isinstance(channels, (tuple, list))
channels2num = {'depth': 1, 'rgb': 3, 'mask': 0}
num_channels = 0
for channel in channels:
num_channels += channels2num[channel]
x_chan = x.shape[0]
assert x_chan % num_channels == 0
if x_chan != num_frames * num_channels:
missing_frames = int(num_frames - x_chan / num_channels)
m = x[:num_channels].repeat(missing_frames, 1, 1)
x = torch.cat((m, x), dim=0)
return x
@staticmethod
def sum_channels(channels):
"""Sum of the span of channels"""
num_channels = 0
for channel in channels:
num_channels += CHANNEL2SPAN[channel]
return num_channels
def set_camera(self, camera_idx):
self._dataset.set_camera(camera_idx)
def get_num_demos(self):
return self.keys.get_num_demos()
def get_demo_indices(self, demo_idx):
"""Return (t, t+T) if demo starts at timestep"""
return self.keys.get_demo_indices(demo_idx)
def get_mask(self, idx):
assert 'mask' in self.channels
assert isinstance(idx, int)
frames = self._dataset[idx]
return frames['mask']
def _user2dbidx(self, idx):
"""convert user index to idx_min, idx_max within dataset range"""
keys = self.keys
if isinstance(idx, slice):
start, end, step = idx.indices(len(self))
# step bigger than 1 not handled
assert step == 1
# make sure all the frames come from the same demo
idx_min, idx_max = keys.get_idx_min_max(start, end)
elif isinstance(idx, int):
idx_min, idx_max = idx, idx + 1
else:
raise TypeError('{} is an unvalid index type.'.format(type(idx)))
return idx_min, idx_max
| [
"numpy.swapaxes",
"torch.tensor",
"sim2real.augmentation.Augmentation.crop",
"bc.dataset.dataset_lmdb.DatasetReader",
"sim2real.augmentation.Augmentation",
"sim2real.transformations.ImageTransform.sample_params",
"torch.cat"
] | [((1069, 1103), 'bc.dataset.dataset_lmdb.DatasetReader', 'DatasetReader', (['path', 'self.channels'], {}), '(path, self.channels)\n', (1082, 1103), False, 'from bc.dataset.dataset_lmdb import DatasetReader\n'), ((1327, 1353), 'sim2real.augmentation.Augmentation', 'Augmentation', (['augmentation'], {}), '(augmentation)\n', (1339, 1353), False, 'from sim2real.augmentation import Augmentation\n'), ((2230, 2250), 'torch.tensor', 'torch.tensor', (['frames'], {}), '(frames)\n', (2242, 2250), False, 'import torch\n'), ((2267, 2286), 'torch.tensor', 'torch.tensor', (['masks'], {}), '(masks)\n', (2279, 2286), False, 'import torch\n'), ((2908, 3025), 'sim2real.transformations.ImageTransform.sample_params', 'ImageTransform.sample_params', ([], {'name_transformation': '"""cropping"""', 'magn': '(output_size, output_size)', 'img_size': 'img_size'}), "(name_transformation='cropping', magn=(\n output_size, output_size), img_size=img_size)\n", (2936, 3025), False, 'from sim2real.transformations import ImageTransform\n'), ((3075, 3128), 'sim2real.augmentation.Augmentation.crop', 'Augmentation.crop', (['frames', 'params_crop', 'centered_crop'], {}), '(frames, params_crop, centered_crop)\n', (3092, 3128), False, 'from sim2real.augmentation import Augmentation\n'), ((5920, 5940), 'torch.tensor', 'torch.tensor', (['frames'], {}), '(frames)\n', (5932, 5940), False, 'import torch\n'), ((5957, 5976), 'torch.tensor', 'torch.tensor', (['masks'], {}), '(masks)\n', (5969, 5976), False, 'import torch\n'), ((6421, 6523), 'sim2real.transformations.ImageTransform.sample_params', 'ImageTransform.sample_params', ([], {'name_transformation': '"""cropping"""', 'magn': 'output_size', 'img_size': 'img_size'}), "(name_transformation='cropping', magn=\n output_size, img_size=img_size)\n", (6449, 6523), False, 'from sim2real.transformations import ImageTransform\n'), ((6573, 6626), 'sim2real.augmentation.Augmentation.crop', 'Augmentation.crop', (['frames', 'params_crop', 'centered_crop'], {}), '(frames, params_crop, centered_crop)\n', (6590, 6626), False, 'from sim2real.augmentation import Augmentation\n'), ((6080, 6110), 'sim2real.augmentation.Augmentation', 'Augmentation', (['augmentation_str'], {}), '(augmentation_str)\n', (6092, 6110), False, 'from sim2real.augmentation import Augmentation\n'), ((7400, 7424), 'torch.cat', 'torch.cat', (['(m, x)'], {'dim': '(0)'}), '((m, x), dim=0)\n', (7409, 7424), False, 'import torch\n'), ((4282, 4311), 'numpy.swapaxes', 'np.swapaxes', (['channel_im', '(2)', '(1)'], {}), '(channel_im, 2, 1)\n', (4293, 4311), True, 'import numpy as np\n')] |
"""
This code is modified by <NAME> from <NAME>'s repository.
https://github.com/linjieli222/VQA_ReGAT
"""
from __future__ import print_function
import os
import sys
import json
import numpy as np
from utils import find_unicode
import argparse
def create_w2v_embedding_init(idx2word, w2v_file):
word2emb = {}
with open(w2v_file, 'r') as f:
entries = f.readlines()
entry = entries[0].split(' ')
#print(entries[0].split(' '))
num_words = int(entry[0])
emb_dim = int(entry[1])
print('there are', num_words, 'words', 'the embedding dim is', emb_dim)
weights = np.zeros((len(idx2word), emb_dim), dtype=np.float32)
#print(weights.shape)
for entry in entries[1:]:
vals = entry.split(' ')
word = vals[0]
vals = list(map(float, vals[1:]))
word2emb[word] = np.array(vals)
count=0
count_=0
for idx, word in idx2word.items():
if word not in word2emb:
count+=1
#print(count,'not found word', word)
flag = 0
ws = word.split('-')
if '' in ws:
for iw in range(len(ws)):
if ws[iw] != '':
w = ws[iw]
if w in word2emb:
weights[int(idx)] = word2emb[w]
#print(word, w)
count_+=1
flag = 1
break
if flag == 0:
w = find_unicode(word)
if w in word2emb:
weights[int(idx)] = word2emb[w]
#print(word, w)
count_+=1
flag = 1
if flag == 0:
weights[int(idx)] = np.random.uniform(-0.1, 0.1)
'''
if (flag ==0) and (word not in ['<start>','<unk>','<end>','<pad>']):
weights[int(idx)] = np.random.uniform(-0.1, 0.1)
'''
continue
weights[int(idx)] = word2emb[word]
#print(count, count_)
return weights, word2emb
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--data_path', default='../vocab/')
parser.add_argument('--data_name', default='kdd2020_caps')
opt = parser.parse_args()
vocab_path = os.path.join(opt.data_path,opt.data_name+'_vocab.json')
dictionary_f = open(vocab_path,'r')
#print(vocab_path)
dictionary = json.load(dictionary_f)
idx2word = dictionary['idx2word']
#w2v_file = '/home/ubuntu/cvs/pengying/KDD2020/word2vec/word2vec300d_all3.txt'
w2v_file = os.path.join(opt.data_path,'w2v_300d.txt')
weights, word2emb = create_w2v_embedding_init(idx2word, w2v_file)
save_path = os.path.join(opt.data_path,'word2vec300d_init_threshold4.npy')
np.save(save_path, weights)
| [
"utils.find_unicode",
"argparse.ArgumentParser",
"os.path.join",
"numpy.array",
"numpy.random.uniform",
"json.load",
"numpy.save"
] | [((2105, 2130), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (2128, 2130), False, 'import argparse\n'), ((2303, 2361), 'os.path.join', 'os.path.join', (['opt.data_path', "(opt.data_name + '_vocab.json')"], {}), "(opt.data_path, opt.data_name + '_vocab.json')\n", (2315, 2361), False, 'import os\n'), ((2439, 2462), 'json.load', 'json.load', (['dictionary_f'], {}), '(dictionary_f)\n', (2448, 2462), False, 'import json\n'), ((2600, 2643), 'os.path.join', 'os.path.join', (['opt.data_path', '"""w2v_300d.txt"""'], {}), "(opt.data_path, 'w2v_300d.txt')\n", (2612, 2643), False, 'import os\n'), ((2731, 2794), 'os.path.join', 'os.path.join', (['opt.data_path', '"""word2vec300d_init_threshold4.npy"""'], {}), "(opt.data_path, 'word2vec300d_init_threshold4.npy')\n", (2743, 2794), False, 'import os\n'), ((2798, 2825), 'numpy.save', 'np.save', (['save_path', 'weights'], {}), '(save_path, weights)\n', (2805, 2825), True, 'import numpy as np\n'), ((830, 844), 'numpy.array', 'np.array', (['vals'], {}), '(vals)\n', (838, 844), True, 'import numpy as np\n'), ((1474, 1492), 'utils.find_unicode', 'find_unicode', (['word'], {}), '(word)\n', (1486, 1492), False, 'from utils import find_unicode\n'), ((1737, 1765), 'numpy.random.uniform', 'np.random.uniform', (['(-0.1)', '(0.1)'], {}), '(-0.1, 0.1)\n', (1754, 1765), True, 'import numpy as np\n')] |
# fileio_backends.py
#
# This file is part of scqubits.
#
# Copyright (c) 2019, <NAME> and <NAME>
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
############################################################################
"""
Helper routines for writing data to h5 files.
"""
import ast
import csv
import os
import re
from abc import ABC, abstractmethod
import numpy as np
try:
import h5py
except ImportError:
_HAS_H5PY = False
else:
_HAS_H5PY = True
import scqubits.io_utils.fileio as io
import scqubits.utils.misc as utils
class IOWriter(ABC):
"""
ABC for writing class instance data to file.
Parameters
----------
filename: str
file_handle: h5.Group, optional
"""
def __init__(self, filename, file_handle=None):
self.filename = filename
self.io_data = None
self.file_handle = file_handle
@abstractmethod
def to_file(self, io_data, **kwargs):
pass
@abstractmethod
def write_attributes(self, *args, **kwargs):
pass
@abstractmethod
def write_ndarrays(self, *args, **kwargs):
pass
@abstractmethod
def write_objects(self, *args, **kwargs):
pass
class H5Writer(IOWriter):
"""Writes IOData to a custom-format h5 file"""
def write_attributes(self, h5file_group):
"""
Attribute data consists of
1. `__init__` parameters that are of type str or numerical. These are directly written into `h5py.Group.attrs`
2. lists are stored under `<h5py.Group>/__lists`
3. dicts are stored under `<h5py.Group>/__dicts`
Parameters
----------
h5file_group: h5py.Group
"""
h5file_group.attrs.create("__type", self.io_data.typename) # Record the type of the current class instance
attributes = self.io_data.attributes
for attr_name, attr_value in attributes.items():
if isinstance(attr_value, dict): # h5py does not serialize dicts automatically, so have to do it manually
group_name = "__dicts/" + attr_name
h5file_group.create_group(group_name)
io.write(attr_value, self.filename, file_handle=h5file_group[group_name])
elif isinstance(attr_value, (list, tuple)):
group_name = "__lists/" + attr_name
h5file_group.create_group(group_name)
io.write(attr_value, self.filename, file_handle=h5file_group[group_name])
else:
h5file_group.attrs[attr_name] = attr_value
def write_ndarrays(self, h5file_group):
"""
Writes ndarray (float or complex) data contained in `self.iodata` to the provided `h5py.Group` as a
`h5py.Dataset`, using gzip compression.
Parameters
----------
h5file_group: h5py.Group
"""
for name, array in self.io_data.ndarrays.items():
h5file_group.create_dataset(name, data=array, dtype=array.dtype, compression="gzip")
def write_objects(self, h5file_group):
"""
Writes data representing a Python object other than ndarray, list and dict, contained in `self.iodata` to the
provided `h5py.Group` und `<h5py.Group>/__objects`.
Parameters
----------
h5file_group: h5py.Group
"""
h5file_group = h5file_group.create_group("__objects")
for obj_name in self.io_data.objects.keys():
new_h5group = h5file_group.create_group(obj_name)
io.write(self.io_data.objects[obj_name], self.filename, file_handle=new_h5group)
@utils.Required(h5py=_HAS_H5PY)
def to_file(self, io_data, file_handle=None):
"""
Takes the serialized IOData and writes it either to a new h5 file with file name given by `self.filename` to to
the given h5py.Group of an open h5 file.
Parameters
----------
io_data: IOData
file_handle: h5py.Group, optional
"""
self.io_data = io_data
if file_handle is None:
h5file_group = h5py.File(self.filename, 'w')
else:
h5file_group = file_handle
self.write_attributes(h5file_group)
self.write_ndarrays(h5file_group)
self.write_objects(h5file_group)
class H5Reader:
"""
Enables reading h5 files generated with scqubits.
Parameters
----------
filename: str
file_handle: h5py.Group, optional
"""
def __init__(self, filename, file_handle=None):
self.filename = filename
self.io_data = None
self.file_handle = file_handle
@staticmethod
def h5_attrs_to_dict(h5_attrs):
"""
Converts h5 attribute data to a Python dictionary.
Parameters
----------
h5_attrs: h5py.AttributeManager
as obtained by accessing `<h5py.Group>.attrs`
Returns
-------
dict [str, str or Number]
"""
return {attr_name: attr_value for attr_name, attr_value in h5_attrs.items()}
def read_attributes(self, h5file_group):
"""
Read data from h5 file group that is stored directly as `<h5py.Group>.attrs`, or saved in subgroups titled
`<h5py.Group>/__lists` and `<h5py.Group>/__dicts`.
Parameters
----------
h5file_group: h5py.Group
Returns
-------
dict [str, dict or list]
"""
attributes = self.h5_attrs_to_dict(h5file_group.attrs)
if '__dicts' in h5file_group:
for dict_name in h5file_group['__dicts']:
attributes[dict_name] = io.read(self.filename, h5file_group['__dicts/' + dict_name])
if '__lists' in h5file_group:
for list_name in h5file_group['__lists']:
attributes[list_name] = io.read(self.filename, h5file_group['__lists/' + list_name])
return attributes
def read_ndarrays(self, h5file_group):
"""
Read numpy array data from h5 file group.
Parameters
----------
h5file_group: h5py.Group
Returns
-------
dict [str, ndarray]
"""
ndarrays = {name: array[:] for name, array in h5file_group.items() if isinstance(array, h5py.Dataset)}
return ndarrays
def read_objects(self, h5file_group):
"""
Read data from the given h5 file group that represents a Python object other than an ndarray, list, or dict.
Parameters
----------
h5file_group: h5py.Group
Returns
-------
dict [str, IOData]
"""
inner_objects = {}
h5file_group = h5file_group["__objects"]
for obj_name in h5file_group:
inner_objects[obj_name] = io.read(self.filename, h5file_group[obj_name])
return inner_objects
@utils.Required(h5py=_HAS_H5PY)
def from_file(self, filename, file_handle=None):
"""
Either opens a new h5 file for reading or accesses an already opened file via the given h5.Group handle. Reads
all data from the three categories of attributes (incl. lists and dicts), ndarrays, and objects.
Parameters
----------
filename: str
file_handle: h5.Group, optional
Returns
-------
IOData
"""
if file_handle is None:
h5file_group = h5py.File(filename, 'r')
else:
h5file_group = file_handle
attributes = self.read_attributes(h5file_group)
typename = attributes['__type']
del attributes['__type']
ndarrays = self.read_ndarrays(h5file_group)
inner_objects = self.read_objects(h5file_group)
return io.IOData(typename, attributes, ndarrays, inner_objects)
class CSVWriter(IOWriter):
"""
Given filename='somename.csv', write initdata into somename.csv
Then, additional csv files are written for each dataset, with filenames: 'somename_' + dataname0 + '.csv' etc.
"""
def append_ndarray_info(self, attributes):
"""Add data set information to attributes, so that dataset names and dimensions are available
in attributes CSV file."""
for index, dataname in enumerate(self.io_data.ndarrays.keys()):
data = self.io_data.ndarrays[dataname]
attributes['dataset' + str(index)] = dataname
if data.ndim == 3:
slice_count = len(data)
else:
slice_count = 1
attributes['dataset' + str(index) + '.slices'] = slice_count
return attributes
def write_attributes(self, filename):
attributes = self.io_data.attributes
attributes["__type"] = self.io_data.typename
attributes = self.append_ndarray_info(attributes)
with open(filename, mode='w', newline='') as meta_file:
file_writer = csv.writer(meta_file, delimiter=',')
file_writer.writerow(attributes.keys())
file_writer.writerow(attributes.values())
def write_ndarrays(self, filename):
filename_stub, _ = os.path.splitext(filename)
for dataname, dataset in self.io_data.ndarrays.items():
filename = filename_stub + '_' + dataname + '.csv'
self.write_data(filename, dataset)
def write_data(self, filename, dataset):
if dataset.ndim <= 2:
np.savetxt(filename, dataset)
elif dataset.ndim == 3:
np_savetxt_3d(dataset, filename)
else:
raise Exception("Dataset has dimensions > 3. Cannot write to CSV file.")
def write_objects(self, *args, **kwargs):
raise NotImplementedError
def to_file(self, io_data, **kwargs):
self.io_data = io_data
self.write_attributes(self.filename)
self.write_ndarrays(self.filename)
# no support for write_objects in CSV format
class CSVReader:
@staticmethod
def read_attributes(filename):
with open(filename, mode='r') as meta_file:
file_reader = csv.reader(meta_file, delimiter=',')
meta_keys = file_reader.__next__()
meta_values = file_reader.__next__()
return dict(zip(meta_keys, meta_values))
def process_metadict(self, meta_dict):
attributes = {
attr_name: utils.to_expression_or_string(attr_value) for attr_name, attr_value in meta_dict.items()
if not re.match(r'dataset\d+', attr_name)
}
data_names = [dataname for datalabel, dataname in meta_dict.items() if re.match(r'dataset\d+$', datalabel)]
data_slices = [ast.literal_eval(value) for key, value in meta_dict.items()
if re.match(r'dataset\d+.slices', key)]
return attributes, data_names, data_slices
@staticmethod
def read_data(filename, slices):
try:
data_array = np.loadtxt(filename)
except ValueError:
data_array = np.loadtxt(filename, dtype=np.complex_)
if slices > 1:
nrows, ncols = data_array.shape
return data_array.reshape((slices, nrows//slices, ncols))
return data_array
def from_file(self, filename, **kwargs):
"""
Parameters
----------
filename: str
Returns
-------
class instance generated from file data
"""
ext_attributes = self.read_attributes(filename)
typename = ext_attributes['__type']
del ext_attributes['__type']
attributes, data_names, data_slices = self.process_metadict(ext_attributes)
filename_stub, _ = os.path.splitext(filename)
ndarrays = {}
for index, dataname in enumerate(data_names):
data_filename = filename_stub + '_' + dataname + '.csv'
slices = data_slices[index]
ndarrays[dataname] = self.read_data(data_filename, slices)
return io.IOData(typename, attributes, ndarrays, objects=None)
def np_savetxt_3d(array3d, filename):
"""
Helper function that splits a 3d numpy array into 2d slices for writing as csv data to a new file. Slices are
separated by a comment row `# New slice`.
Parameters
----------
array3d: ndarray with ndim = 3
filename: str
"""
with open(filename, mode='w', newline='') as datafile:
datafile.write('# Array shape: {0}\n'.format(array3d.shape))
for data_slice in array3d:
np.savetxt(datafile, data_slice)
datafile.write('# New slice\n')
| [
"scqubits.utils.misc.Required",
"scqubits.io_utils.fileio.read",
"scqubits.utils.misc.to_expression_or_string",
"csv.writer",
"os.path.splitext",
"re.match",
"h5py.File",
"scqubits.io_utils.fileio.IOData",
"ast.literal_eval",
"scqubits.io_utils.fileio.write",
"numpy.savetxt",
"numpy.loadtxt",
... | [((3709, 3739), 'scqubits.utils.misc.Required', 'utils.Required', ([], {'h5py': '_HAS_H5PY'}), '(h5py=_HAS_H5PY)\n', (3723, 3739), True, 'import scqubits.utils.misc as utils\n'), ((6936, 6966), 'scqubits.utils.misc.Required', 'utils.Required', ([], {'h5py': '_HAS_H5PY'}), '(h5py=_HAS_H5PY)\n', (6950, 6966), True, 'import scqubits.utils.misc as utils\n'), ((7807, 7863), 'scqubits.io_utils.fileio.IOData', 'io.IOData', (['typename', 'attributes', 'ndarrays', 'inner_objects'], {}), '(typename, attributes, ndarrays, inner_objects)\n', (7816, 7863), True, 'import scqubits.io_utils.fileio as io\n'), ((9178, 9204), 'os.path.splitext', 'os.path.splitext', (['filename'], {}), '(filename)\n', (9194, 9204), False, 'import os\n'), ((11688, 11714), 'os.path.splitext', 'os.path.splitext', (['filename'], {}), '(filename)\n', (11704, 11714), False, 'import os\n'), ((11986, 12041), 'scqubits.io_utils.fileio.IOData', 'io.IOData', (['typename', 'attributes', 'ndarrays'], {'objects': 'None'}), '(typename, attributes, ndarrays, objects=None)\n', (11995, 12041), True, 'import scqubits.io_utils.fileio as io\n'), ((3622, 3707), 'scqubits.io_utils.fileio.write', 'io.write', (['self.io_data.objects[obj_name]', 'self.filename'], {'file_handle': 'new_h5group'}), '(self.io_data.objects[obj_name], self.filename, file_handle=new_h5group\n )\n', (3630, 3707), True, 'import scqubits.io_utils.fileio as io\n'), ((4178, 4207), 'h5py.File', 'h5py.File', (['self.filename', '"""w"""'], {}), "(self.filename, 'w')\n", (4187, 4207), False, 'import h5py\n'), ((6854, 6900), 'scqubits.io_utils.fileio.read', 'io.read', (['self.filename', 'h5file_group[obj_name]'], {}), '(self.filename, h5file_group[obj_name])\n', (6861, 6900), True, 'import scqubits.io_utils.fileio as io\n'), ((7476, 7500), 'h5py.File', 'h5py.File', (['filename', '"""r"""'], {}), "(filename, 'r')\n", (7485, 7500), False, 'import h5py\n'), ((8967, 9003), 'csv.writer', 'csv.writer', (['meta_file'], {'delimiter': '""","""'}), "(meta_file, delimiter=',')\n", (8977, 9003), False, 'import csv\n'), ((9467, 9496), 'numpy.savetxt', 'np.savetxt', (['filename', 'dataset'], {}), '(filename, dataset)\n', (9477, 9496), True, 'import numpy as np\n'), ((10119, 10155), 'csv.reader', 'csv.reader', (['meta_file'], {'delimiter': '""","""'}), "(meta_file, delimiter=',')\n", (10129, 10155), False, 'import csv\n'), ((10391, 10432), 'scqubits.utils.misc.to_expression_or_string', 'utils.to_expression_or_string', (['attr_value'], {}), '(attr_value)\n', (10420, 10432), True, 'import scqubits.utils.misc as utils\n'), ((10683, 10706), 'ast.literal_eval', 'ast.literal_eval', (['value'], {}), '(value)\n', (10699, 10706), False, 'import ast\n'), ((10951, 10971), 'numpy.loadtxt', 'np.loadtxt', (['filename'], {}), '(filename)\n', (10961, 10971), True, 'import numpy as np\n'), ((12517, 12549), 'numpy.savetxt', 'np.savetxt', (['datafile', 'data_slice'], {}), '(datafile, data_slice)\n', (12527, 12549), True, 'import numpy as np\n'), ((2259, 2332), 'scqubits.io_utils.fileio.write', 'io.write', (['attr_value', 'self.filename'], {'file_handle': 'h5file_group[group_name]'}), '(attr_value, self.filename, file_handle=h5file_group[group_name])\n', (2267, 2332), True, 'import scqubits.io_utils.fileio as io\n'), ((5720, 5780), 'scqubits.io_utils.fileio.read', 'io.read', (['self.filename', "h5file_group['__dicts/' + dict_name]"], {}), "(self.filename, h5file_group['__dicts/' + dict_name])\n", (5727, 5780), True, 'import scqubits.io_utils.fileio as io\n'), ((5913, 5973), 'scqubits.io_utils.fileio.read', 'io.read', (['self.filename', "h5file_group['__lists/' + list_name]"], {}), "(self.filename, h5file_group['__lists/' + list_name])\n", (5920, 5973), True, 'import scqubits.io_utils.fileio as io\n'), ((10623, 10658), 're.match', 're.match', (['"""dataset\\\\d+$"""', 'datalabel'], {}), "('dataset\\\\d+$', datalabel)\n", (10631, 10658), False, 'import re\n'), ((10769, 10804), 're.match', 're.match', (['"""dataset\\\\d+.slices"""', 'key'], {}), "('dataset\\\\d+.slices', key)\n", (10777, 10804), False, 'import re\n'), ((11024, 11063), 'numpy.loadtxt', 'np.loadtxt', (['filename'], {'dtype': 'np.complex_'}), '(filename, dtype=np.complex_)\n', (11034, 11063), True, 'import numpy as np\n'), ((2511, 2584), 'scqubits.io_utils.fileio.write', 'io.write', (['attr_value', 'self.filename'], {'file_handle': 'h5file_group[group_name]'}), '(attr_value, self.filename, file_handle=h5file_group[group_name])\n', (2519, 2584), True, 'import scqubits.io_utils.fileio as io\n'), ((10499, 10533), 're.match', 're.match', (['"""dataset\\\\d+"""', 'attr_name'], {}), "('dataset\\\\d+', attr_name)\n", (10507, 10533), False, 'import re\n')] |
import torch
import torch.nn as nn
import sys
import json2
import numpy as np
def get_flops(model, input_shape=(3, 224, 224)):
list_conv = []
def conv_hook(self, input, output):
batch_size, input_channels, input_height, input_width = input[0].size()
output_channels, output_height, output_width = output[0].size()
assert self.in_channels % self.groups == 0
kernel_ops = self.kernel_size[0] * self.kernel_size[
1] * (self.in_channels // self.groups)
params = output_channels * kernel_ops
flops = batch_size * params * output_height * output_width
list_conv.append(flops)
list_linear = []
def linear_hook(self, input, output):
batch_size = input[0].size(0) if input[0].dim() == 2 else 1
weight_ops = self.weight.nelement()
flops = batch_size * weight_ops
list_linear.append(flops)
def foo(net):
childrens = list(net.children())
if not childrens:
if isinstance(net, torch.nn.Conv2d):
net.register_forward_hook(conv_hook)
if isinstance(net, torch.nn.Linear):
net.register_forward_hook(linear_hook)
return
for c in childrens:
foo(c)
foo(model)
input = torch.autograd.Variable(
torch.rand(*input_shape).unsqueeze(0), requires_grad=True)
out = model(input)
total_flops = sum(sum(i) for i in [list_conv, list_linear])
return total_flops
def parse_darts_log(log_path, key_point='ea_acc'):
'''
report vaild
'''
collect = []
for l in open(log_path).readlines():
l = l.strip('/n')
if 'args = Namespace' in l:
collect = []
# if 'epoch ' in l and 'lr 'in l:
# epoch_num = int(l.split('epoch ')[-1].split(' lr')[0])
# if epoch_num == 0:
# print(l)
# print(epoch_num)
# collect = []
if key_point in l:
metirc = float(l.split(key_point)[-1])
print(metirc)
collect.append(metirc)
print(collect)
def parse_vs(log_path):
'''
report vaild
'''
previous = []
current = []
for l in open(log_path).readlines():
l = l.strip('/n')
if 'args = Namespace' in l:
previous = []
current = []
if 'previous_vs_current' in l:
import pdb;pdb.set_trace()
p = float(l.split('previous_vs_current')[0].split(' ')[-1])
c = float(l.split('previous_vs_current')[-1].split(' ')[0])
print(metirc)
collect.append(metirc)
print(collect)
def get_lantacy(arch=None, l_limit=8000, h_limit=15000):
'''
only support sfn1 oneshot
'''
if arch is None:
arch = tuple(np.random.randint(4) for i in range(16))
assert len(arch) == 16
#lantacy_map = json2.read('/share5/ics/guyang/dataset/shufflent_oneshot_latency/shufflent_oneshot_latency.json')['map']
lantacy_map = [[581.0, 741.0, 832.0, 1373.0], [450.0, 549.0, 781.0, 877.0], [402.0, 499.0, 515.0, 742.0], [473.0, 673.0, 647.0, 772.0], [550.0, 553.0, 739.0, 821.0], [450.0, 428.0, 551.0, 472.0], [271.0, 408.0, 405.0, 519.0], [342.0, 388.0, 472.0, 437.0], [347.0, 429.0, 483.0, 446.0], [309.0, 365.0, 481.0, 451.0], [425.0, 461.0, 495.0, 502.0], [276.0, 377.0, 434.0, 452.0], [391.0, 415.0, 413.0, 594.0], [197.0, 289.0, 274.0, 363.0], [148.0, 149.0, 301.0, 350.0], [238.0, 272.0, 221.0, 457.0]]
stem = 4282
classifer = 408
limit = 12000
arch_lantacy = stem + classifer
for layer_id, ops_id in enumerate(arch):
arch_lantacy += lantacy_map[layer_id][ops_id]
return arch_lantacy, (arch_lantacy<h_limit and arch_lantacy>l_limit)
if __name__ == '__main__':
log_path = sys.argv[1]
parse_darts_log(log_path)
| [
"torch.rand",
"numpy.random.randint",
"pdb.set_trace"
] | [((2432, 2447), 'pdb.set_trace', 'pdb.set_trace', ([], {}), '()\n', (2445, 2447), False, 'import pdb\n'), ((1323, 1347), 'torch.rand', 'torch.rand', (['*input_shape'], {}), '(*input_shape)\n', (1333, 1347), False, 'import torch\n'), ((2818, 2838), 'numpy.random.randint', 'np.random.randint', (['(4)'], {}), '(4)\n', (2835, 2838), True, 'import numpy as np\n')] |
'''
This File Provides the Funktions for the Montecarlo simulation
To start use MLG.Start
'''
from MLG import path,default_table, message_folder, Version,Subversion
from MLG.Simulation import RawData
from MLG.Simulation import RealData
from MLG.Modeling import fitting_micro , fitting_motion
from MLG.Math import percentile
from joblib import Parallel, delayed
import numpy as np
import time
import pickle
import datetime
import glob
import os
__all__ = ['StartMC','loadPkl', 'calcParallel']
def StartMC(EventList, namelist = None, keywords = {}, **kwargs):
'''------------------------------------------------------------
Description:
This Function distribute the calculation for the MonteCarlo
simulation on multiple CPU_Cores and stors the results in an PKL file
uses the joblib package for parallel computing
---------------------------------------------------------------
Input:
EventList: String of the input table or
List of Lens source paris for each event or
MC_results for vary the mass also
namelist: List of names for each event (for ploting routine, if None use of the index)
---------------------------------------------------------------
Output:
MC_result: Dictnary of the results. Contains:
'Header': List of all control imputs, and Code Version
'Results': List of the fit parameters
'Input_parameter': List of the input parameters
'Results_ext_obs': List of the fit parameters with external_obs if ext_obs > 0
'Chi2': List of the reduced CHI2
'Eventlist': (see Input)
'Names': (see Input)
------------------------------------------------------------'''
#--------------------------------------------------------------
#Update controle keywords
keywords.update(kwargs)
num_core = keywords.get('num_core', 6) # Number of cores
instring = keywords.get('instring', '') # string for the save files
message = keywords.get('message', False) # write the process of the computation to an file
DR3 = keywords.get('DR3', False) # Use of the Data of DR3 only
extended = keywords.get('extended', False) # Use of the 10 years data of the extended mission
vary_eta = keywords.get('vary_eta', False) # Use an new scaninglaw for 2020.5-2024.5
ext_obs = keywords.get('ext_obs', False) # include external observations
n_error_picks = keywords.get('n_error_picks', 500) # Number of pickt Observation from the error ellips
n_par_picks = keywords.get('n_par_picks', 1) # Number of pickt input Parameters from the error ellips
namelist = keywords.get('namelist', namelist) # Check if namelist is given in the keyword dictionary
#--------------------------------------------------------------
#--------------------------------------------------------------
#Create random seeds for the calculation
seed = []
for i in range(num_core):
seed.append((int(time.time()*10**9))**4 %4294967295)
keywords['seed']=seed
#--------------------------------------------------------------
#--------------------------------------------------------------
#Load Table if EventList is an string
if isinstance(EventList, str) == True:
if EventList == '':
EventList,_ = RealData.loadRealData(default_table)
else:
EventList,_ = RealData.loadRealData(EventList)
#--------------------------------------------------------------
#--------------------------------------------------------------
# start calculations with varing the mass if a dict is given
if isinstance(EventList, dict) == True:
print('vary mass')
#--------------------------------------------------------------
# extract lists from Dictionary
MC_Results = EventList
res_all_events = MC_Results['Results']
par_all_events = MC_Results['Input_parameter']
EventList = MC_Results['Eventlist']
namelist = MC_Results['Names']
header = MC_Results['Header']
#--------------------------------------------------------------
#--------------------------------------------------------------
# only consider the events with an error < 100%
EventList = [EventList[i] for i in range(len(res_all_events)) \
if (percentile(res_all_events[i][:,0])[0]> 0)]
if namelist is None:
namelist_good = None
else:
namelist_good = [namelist[i] for i in range(len(res_all_events)) \
if (percentile(res_all_events[i][:,0])[0]> 0)]
#--------------------------------------------------------------
#--------------------------------------------------------------
# update control keywords
keywords['Good']=True # indication calculation of the good events only
goodstr = 'Good_' # string for indication calculation of the good events only
keywords['vary_par']=5 # vary all parameters
n_error_picks = keywords.get('n_error_picks', 500) #check if value is given in keywords else set to defaut
keywords['n_par_picks']=n_par_picks
n_par_picks = keywords.get('n_par_picks', 100) #check if value is given in keywords else set to defaut
keywords['n_error_picks']=n_error_picks
#--------------------------------------------------------------
#--------------------------------------------------------------
# start first calculation
elif isinstance(EventList, list) == True:
#--------------------------------------------------------------
# update control keywords
keywords['n_par_picks']=n_par_picks # Update keyword
keywords['n_error_picks']=n_error_picks # Update keyword
keywords['vary_par']=keywords.get('vary_par', 1) # vary only non given parameters
keywords['Good']=False # indication calculation of the good events only
goodstr=''
#--------------------------------------------------------------
#--------------------------------------------------------------
#set default namelist to integer (not comparable within different inputs)
if namelist == None:
namelist == [str(i) for i in range(len(EventList))]
#--------------------------------------------------------------
#--------------------------------------------------------------
# exclude different filetypes
else:
print ('Input Error!')
return
#--------------------------------------------------------------
#--------------------------------------------------------------
# create header
if instring is not '':
instring = instring + '_'
if DR3:
#use only events before 2019.5 for DR3
EventList = [EventList[kkk] for kkk in range(len(EventList)) if EventList[kkk][0].getTca() < 2019.5 ]
header = len(EventList),3,n_error_picks,n_par_picks, keywords,Version+'.'+Subversion
elif extended or vary_eta or ext_obs:
#use the data of the extended mission
header = len(EventList),10,n_error_picks,n_par_picks,keywords, Version+'.'+Subversion
else:
header = len(EventList),5,n_error_picks,n_par_picks,keywords, Version+'.'+Subversion
print(time.ctime())
print(header)
#--------------------------------------------------------------
#--------------------------------------------------------------
# Distribute on different cores
num_events = len(EventList)
events_per_core = num_events/num_core
#calculation of multiple events (proxima centauri tend to take as much computation time as all other events)
if len(EventList[0]) > 10 and num_core > 2:
events_per_core = (num_events-1)/(num_core -1)
for core in range(num_core):
partstring = path+'Simulation/evpart/eventlist_'+goodstr+instring+'part_%i.pkl' % core
if core == 0:
f = open(partstring, 'wb')
pickle.dump([EventList[0],], f)
f.close()
elif core == num_core -1:
f = open(partstring, 'wb')
pickle.dump(EventList[1 + round(events_per_core * (core - 1)):], f)
f.close()
else:
f = open(partstring, 'wb')
pickle.dump(EventList[1 + round(events_per_core * (core - 1)) : 1 + round(events_per_core * (core))], f)
f.close()
#distribute events equaly
else:
for core in range(num_core):
partstring = path+'Simulation/evpart/eventlist_'+goodstr+instring+'part_%i.pkl' % core
if core == num_core -1:
f = open(partstring, 'wb')
pickle.dump(EventList[round(events_per_core * core):], f)
f.close()
else:
f = open(partstring, 'wb')
pickle.dump(EventList[round(events_per_core * core) : round(events_per_core * (core + 1))], f)
f.close()
#--------------------------------------------------------------
#--------------------------------------------------------------
#start calculations parallel
if num_core != 1:
res_par = Parallel(n_jobs=num_core)(delayed(calcParallel)(i,instring, keywords) for i in range(num_core))
else:
res_par = [calcParallel(0,instring, keywords),]
#--------------------------------------------------------------
#--------------------------------------------------------------
#merge the results for the parallel computations
res_all_events = []
par_all_events = []
res_no_ML_events = []
chi2_events = []
for res_par_core in res_par:
for par_event in res_par_core[1]:
par_all_events.append(par_event)
for res_event in res_par_core[0]:
res_all_events.append(res_event)
for res_no_event in res_par_core[2]:
res_no_ML_events.append(res_no_event)
for res_no_event in res_par_core[3]:
chi2_events.append(res_no_event)
if ext_obs:
MC_Results = {'Header': header,'Results':res_all_events,'Input_parameter':par_all_events,\
'Results_ext_obs':res_no_ML_events, 'Chi2':chi2_events,'Eventlist':EventList,'Names':namelist}
else:
MC_Results = {'Header': header,'Results':res_all_events,'Input_parameter':par_all_events,\
'Results_no_ML':res_no_ML_events, 'Chi2':chi2_events,'Eventlist':EventList,'Names':namelist}
#--------------------------------------------------------------
#--------------------------------------------------------------
# save results as pkl file
string = path + 'Data/MC'+goodstr[:-1] +'_'+ instring + datetime.datetime.today().strftime('%d-%m-%Y')\
+ '_%.f_%.f_%.f_%.f.pkl' % (header[:4])
f = open(string, 'wb')
pickle.dump(MC_Results, f)
print(string)
if message:
os.system('cp ' + string + ' ' + message_folder)
return MC_Results
def loadPkl(filename = '',Good = False, extended = False, n_error_picks = False, n_par_picks=False):
'''------------------------------------------------------------
Load the MC_results PKL files ()
---------------------------------------------------------------
Input:
filename: filename expected in the MLG/Data Folder
---------------------------------------------------------------
Output:
MC_Results: Dictonary containg results from StartMC
------------------------------------------------------------'''
if len(glob.glob(filename)) == 0:
if Good: good = 'Good'
else: good = ''
if extended: ex = string(extended) + '_'
else: ex = '*_'
if n_error_picks: er = string(extended) + '_'
else: er = '*_'
if n_par_picks: pa = string(extended) + '.pkl'
else: pa = '*.pkl'
gstring= (path + 'Data/MC' + good + '*_' + ex + er + pa)
g = glob.glob(gstring)
string = g[-1]
if filename != '':
if len(glob.glob(path + 'Data/' + filename)) == 0:
print('File not found! Using standard file')
else:
string = glob.glob(path + 'Data/' + filename)[0]
else:
print('Using standard file')
else: string = glob.glob(filename)[0]
print(string)
f = open(string,'rb')
pkl = pickle.load(f)
f.close()
if isinstance(pkl,dict): #from Version 3.1
if 'Results_comp' in pkl.keys():
pkl['Results_ext_obs'] = pkl.pop('Results')
pkl['Results'] = pkl.pop('Results_comp')
MC_Results = pkl
else:
#until Version 3.1
if len(pkl) == 6:
chi2_events = None
EventList, res_all_events, par_all_events,res_no_ML_events,namelist,header = pkl
try:
par_all_events[0].x
print(1)
except AttributeError: pass
else:
qq = par_all_events
par_all_events = res_no_ML_events
res_no_ML_events = par_all_events
elif len(pkl) == 7:
EventList, res_all_events, par_all_events,res_no_ML_events,\
chi2_events,namelist,header = pkl
try:
par_all_events[0].x
print(1)
except AttributeError: pass
else:
qq = par_all_events
par_all_events = res_no_ML_events
res_no_ML_events = qq
# Transform format to 3.1
MC_Results = {'Header': header,'Results':res_all_events,'Input_parameter':par_all_events,\
'Results_no_ML':res_no_ML_events, 'Chi2':chi2_events,'Eventlist':EventList,'Names':namelist}
return MC_Results
def calcParallel(part, instring, keywords = {} ,**kwargs):
'''------------------------------------------------------------
Description:
creats sets of observations for a part of the Eventlist
and fits the data
---------------------------------------------------------------
Input:
part: which part of the EventList
instring: file string of the EventList
keywords/kwargs: setup values for the simulation (see below)
---------------------------------------------------------------
Output:
res_part: results of the individual fits (contains a separate list for each events)
par_part: Inputparameters of the indiciual fits (contains a separate list for each events)
res_no_ML: result without microlensing
chi2_red_part: Chi2 values of the individual fits (contains a separate list for each events)
------------------------------------------------------------'''
#---------------------------------------------------------------
#extract keywords
keywords.update(kwargs)
seed = keywords.get('seed', None) # seed's for the randomised process
Good = keywords.get('Good', False) # Second loop with variation of the mass
extended = keywords.get('extended', False) # Use of the data for extended Mission
ext_obs = keywords.get('ext_obs', False) # ext_obs include external observations
DR3 = keywords.get('DR3', False) # Use of the data for DR3 only
exact = keywords.get('exact', False) # Use the exact astrometric shift or the approximation
n_error_picks= keywords.get('n_error_picks', 500) # number of picks from the error elips of the measurements
n_par_picks = keywords.get('n_par_picks', 1) # number of different picks of input parameters
vary_par = keywords.get('vary_par', 1) # which parameters should be varied for n_par_picks
prefit_motion= keywords.get('prefit_motion', False) # fit the propermotion with out microlensing as preput
vary_eta = keywords.get('vary_eta', False) #Use data while vary eta
onlysource = keywords.get('onlysource', False) # use the data of the source only
timer = keywords.get('timer', False) # print computing-time for different steps
message = keywords.get('message', False) # save messeage file for keeping track of the process
silent = keywords.get('silent', True) # boolen if information shoul not be printed
#---------------------------------------------------------------
#---------------------------------------------------------------
# computationtime tracker
cputt = [0.,0.,0.,0.,0.,0.,0]
cputt[0] -= time.time()
# update seed for the randomised process
if seed is not None:
np.random.seed(seed[part])
#---------------------------------------------------------------
#---------------------------------------------------------------
# initilise arrays for storing the results
# fit results
res_part = []
# fit results without microlensing
res_no_ML = []
# input parameters
par_part = []
# Chi2_reduced value
chi2_red_part = []
chi2_red_mot_part = []
#---------------------------------------------------------------
#---------------------------------------------------------------
# load part of the Eventlist
if Good:
partstring = path+'Simulation/evpart/eventlist_Good_'+instring+'part_%i.pkl' % part
f = open(partstring,'rb')
EventList = pickle.load(f)
f.close
os.remove(path+'Simulation/evpart/eventlist_Good_'+instring+'part_%i.pkl' % part)
else:
partstring = path+'Simulation/evpart/eventlist_'+instring+'part_%i.pkl' % part
f = open(partstring,'rb')
EventList = pickle.load(f)
f.close
os.remove(path+'Simulation/evpart/eventlist_'+instring+'part_%i.pkl' % part)
cputt[0] += time.time()
#---------------------------------------------------------------
for i1 in range(len(EventList)):
#---------------------------------------------------------------
# updat process tracker
if message:
os.system('touch %s.%s-%s-0.message'%(message_folder+instring[:-1],part,i1))
#---------------------------------------------------------------
cputt[1] -= time.time()
#---------------------------------------------------------------
# initilise list for each event
# fit results
res_single = []
res_external_obs = [] #for comparison (test)
# input parameters
par_single = []
# Observations (for fitting without microlensing)
Obs_save = []
# Chi2_reduced value
chi2_red_single = []
#---------------------------------------------------------------
#get Stars
Stars = EventList[i1]
#---------------------------------------------------------------
# create observations from real scanning law
RealObs = RealData.getRealObs(Stars[0],Stars[1],**keywords)
Data = RawData.Data(Stars,*RealObs,**keywords)
Obs,Starnumber,Epoch,Obs_err, sc_scandir = Data.Observations(**keywords)
#---------------------------------------------------------------
cputt[1] += time.time()
for i2 in range(n_par_picks):
#loop over each set of differen input parameters
par = Data.par[i2]
for i3 in range(n_error_picks):
#loop over each set of differen picks from the error ellips of the Observation
cputt[6] = -time.time()
cputt[2] -= time.time()
# include outliers 5% chance
if ext_obs:
outliers = np.random.uniform(0,1,len(Starnumber[i2]))
outliers[-4*ext_obs:] = 1 #keep the external observations
n = np.where(outliers > 0.05)
else:
n = np.where(np.random.uniform(0,1,len(Starnumber[i2])) > 0.05)
#---------------------------------------------------------------
# get the right set of observations
Obs_i = Obs[i2][i3][n]
if len(Obs_i) < 11+4*ext_obs:
# not enought observation
re = -999* np.ones(len(Stars)*5+1)
res_single.append(re)
chi2_red_single.append(-999.)
par_single.append(par)
cputt[2] += time.time()
res_external_obs.append(re)
else:
# get the right set of observations
# (identical within each set of input parameters)
Starnumber_i = Starnumber[i2][n]
Epoch_i = Epoch[i2][n]
Obs_err_i = Obs_err[i2][n]
sc_scandir_i = sc_scandir[i2][n]
#---------------------------------------------------------------
#---------------------------------------------------------------
#compare with external observations (test)
if ext_obs:
res_ext= fitting_micro.Fit_Micro(Obs_i,Starnumber_i,Epoch_i,Obs_err_i, sc_scandir_i,\
bounds = True, **keywords)
res_external_obs.append(res_ext.x)
# remove external observations
Obs_i=Obs_i[:-4*ext_obs]
Obs_err_i = Obs_err_i[:-4*ext_obs]
Starnumber_i = Starnumber_i[:-4*ext_obs]
Epoch_i = Epoch_i[:-4*ext_obs]
sc_scandir_i = sc_scandir_i[:-4*ext_obs]
#---------------------------------------------------------------
#---------------------------------------------------------------
# store observations
Obs_save.append([Obs_i, Starnumber_i,Epoch_i, Obs_err_i, sc_scandir_i])
cputt[2] += time.time()
#---------------------------------------------------------------
#---------------------------------------------------------------
# Fit model to the observational data
cputt[3] -= time.time()
res= fitting_micro.Fit_Micro(Obs_i,Starnumber_i,Epoch_i,Obs_err_i, sc_scandir_i,\
bounds = True, **keywords)
cputt[3] -= time.time()
#---------------------------------------------------------------
#---------------------------------------------------------------
#store results
cputt[4] -= time.time()
if len(res.x) != len(Stars)*5+1:
#Check if all stars have observations
re = -999* np.ones(len(Stars)*5+1)
re[:len(res.x)] = res.x
re[len(res.x):] = None
if len(res.x) == 6 : re[0] = -999
res_single.append(re)
else:
res_single.append(res.x)
chi2_red_single.append(res.cost * 2 / (len(res.fun) - 11))
par_single.append(par)
cputt[4] += time.time()
#---------------------------------------------------------------
#---------------------------------------------------------------
#print computing time (for optimisation)
if timer:
if not (i3 % 100):
cputt[5] += time.time()
print('Part %i-%i Step %i %.2f' % (part,i1,i3,cputt[6]))
if time.time() - ti > 10: return 0
#---------------------------------------------------------------
#---------------------------------------------------------------
# updat process tracker
if message:
os.system('mv %s.%s-%s-%s.message %s.%s-%s-%s.message'%\
(message_folder + instring[:-1], part, i1, i2,\
message_folder + instring[:-1], part, i1, i2+1))
#---------------------------------------------------------------
if not silent: print(i3, time.time() - ti)
#---------------------------------------------------------------
# sort results
cputt[5] -= time.time()
res_single = np.stack(res_single)
res_part.append(res_single)
par_single = np.stack(par_single)
par_part.append(par_single)
chi2_red_single = np.stack(chi2_red_single)
chi2_red_part.append(chi2_red_single)
#---------------------------------------------------------------
#compare without external observations (test)
if ext_obs:
res_external_obs = np.stack(res_external_obs)
res_no_ML.append(res_external_obs)
#---------------------------------------------------------------
#---------------------------------------------------------------
# fit mean result also without microlensing
if len(res_single[:,0]) > 1:
if ext_obs:
chi2_red_micro_best = 0
chi2_red_motion = 0
else:
p50 = percentile(res_single[:,0])[1]
if p50 == -999:
chi2_red_mot_part.append(-999)
chi2_red_micro_best = -999
res_no_ML.append(-999*np.ones(5*len(Stars)))
chi2_red_motion = -999
else:
best = np.where(res_single[:,0] == p50)[0][0]
res_motion = fitting_motion.Fit_Motion(*Obs_save[best],**keywords)
res_no_ML.append(res_motion.x)
chi2_red_micro_best = chi2_red_single[best]
chi2_red_motion= res_motion.cost * 2 / (len(Obs_save[best][1]) - 10)
chi2_red_mot_part.append(chi2_red_motion)
cputt[5] += time.time()
#---------------------------------------------------------------
#---------------------------------------------------------------
# print computing time (for optimisation)
if timer:
print('MC %.0f-%.0f: %.3f, %.3f, %.3f, %.3f, %.3f, %.3f, %.3f' % (part,i1,*tuple(cputt)))
#---------------------------------------------------------------
else:
#---------------------------------------------------------------
# print statistics
if len(res_single[:,0]) > 1:
print('%.0f-%.0f: %.3f, %.3f, %.3f, %.3f, %.3f, %.3f, %.3f, %.3f, %s'\
% (part,i1, Stars[0].mass,*percentile(res_single[:,0]), chi2_red_micro_best,chi2_red_motion, time.ctime().split(' ')[3]))
#---------------------------------------------------------------
if not silent: print('Part {} done!'.format(part))
#---------------------------------------------------------------
# updat process tracker
if message:
os.system('rm %s.%s*.message'%(message_folder+instring[:-1],part))
os.system('touch %s.%s.Done.message'%(message_folder+instring[:-1],part))
#---------------------------------------------------------------
return res_part, par_part, res_no_ML,chi2_red_part
| [
"MLG.Simulation.RealData.loadRealData",
"MLG.Math.percentile",
"datetime.datetime.today",
"os.remove",
"time.ctime",
"numpy.where",
"numpy.stack",
"numpy.random.seed",
"os.system",
"glob.glob",
"pickle.load",
"time.time",
"MLG.Simulation.RawData.Data",
"MLG.Modeling.fitting_micro.Fit_Micro... | [((9901, 9927), 'pickle.dump', 'pickle.dump', (['MC_Results', 'f'], {}), '(MC_Results, f)\n', (9912, 9927), False, 'import pickle\n'), ((11251, 11265), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (11262, 11265), False, 'import pickle\n'), ((14880, 14891), 'time.time', 'time.time', ([], {}), '()\n', (14889, 14891), False, 'import time\n'), ((16011, 16022), 'time.time', 'time.time', ([], {}), '()\n', (16020, 16022), False, 'import time\n'), ((6774, 6786), 'time.ctime', 'time.ctime', ([], {}), '()\n', (6784, 6786), False, 'import time\n'), ((9959, 10007), 'os.system', 'os.system', (["('cp ' + string + ' ' + message_folder)"], {}), "('cp ' + string + ' ' + message_folder)\n", (9968, 10007), False, 'import os\n'), ((10902, 10920), 'glob.glob', 'glob.glob', (['gstring'], {}), '(gstring)\n', (10911, 10920), False, 'import glob\n'), ((14958, 14984), 'numpy.random.seed', 'np.random.seed', (['seed[part]'], {}), '(seed[part])\n', (14972, 14984), True, 'import numpy as np\n'), ((15652, 15666), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (15663, 15666), False, 'import pickle\n'), ((15679, 15771), 'os.remove', 'os.remove', (["(path + 'Simulation/evpart/eventlist_Good_' + instring + 'part_%i.pkl' % part)"], {}), "(path + 'Simulation/evpart/eventlist_Good_' + instring + \n 'part_%i.pkl' % part)\n", (15688, 15771), False, 'import os\n'), ((15894, 15908), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (15905, 15908), False, 'import pickle\n'), ((15921, 16007), 'os.remove', 'os.remove', (["(path + 'Simulation/evpart/eventlist_' + instring + 'part_%i.pkl' % part)"], {}), "(path + 'Simulation/evpart/eventlist_' + instring + 'part_%i.pkl' %\n part)\n", (15930, 16007), False, 'import os\n'), ((16394, 16405), 'time.time', 'time.time', ([], {}), '()\n', (16403, 16405), False, 'import time\n'), ((16979, 17030), 'MLG.Simulation.RealData.getRealObs', 'RealData.getRealObs', (['Stars[0]', 'Stars[1]'], {}), '(Stars[0], Stars[1], **keywords)\n', (16998, 17030), False, 'from MLG.Simulation import RealData\n'), ((17039, 17080), 'MLG.Simulation.RawData.Data', 'RawData.Data', (['Stars', '*RealObs'], {}), '(Stars, *RealObs, **keywords)\n', (17051, 17080), False, 'from MLG.Simulation import RawData\n'), ((17238, 17249), 'time.time', 'time.time', ([], {}), '()\n', (17247, 17249), False, 'import time\n'), ((21254, 21265), 'time.time', 'time.time', ([], {}), '()\n', (21263, 21265), False, 'import time\n'), ((21281, 21301), 'numpy.stack', 'np.stack', (['res_single'], {}), '(res_single)\n', (21289, 21301), True, 'import numpy as np\n'), ((21347, 21367), 'numpy.stack', 'np.stack', (['par_single'], {}), '(par_single)\n', (21355, 21367), True, 'import numpy as np\n'), ((21418, 21443), 'numpy.stack', 'np.stack', (['chi2_red_single'], {}), '(chi2_red_single)\n', (21426, 21443), True, 'import numpy as np\n'), ((23483, 23554), 'os.system', 'os.system', (["('rm %s.%s*.message' % (message_folder + instring[:-1], part))"], {}), "('rm %s.%s*.message' % (message_folder + instring[:-1], part))\n", (23492, 23554), False, 'import os\n'), ((23552, 23630), 'os.system', 'os.system', (["('touch %s.%s.Done.message' % (message_folder + instring[:-1], part))"], {}), "('touch %s.%s.Done.message' % (message_folder + instring[:-1], part))\n", (23561, 23630), False, 'import os\n'), ((3173, 3209), 'MLG.Simulation.RealData.loadRealData', 'RealData.loadRealData', (['default_table'], {}), '(default_table)\n', (3194, 3209), False, 'from MLG.Simulation import RealData\n'), ((3235, 3267), 'MLG.Simulation.RealData.loadRealData', 'RealData.loadRealData', (['EventList'], {}), '(EventList)\n', (3256, 3267), False, 'from MLG.Simulation import RealData\n'), ((8417, 8442), 'joblib.Parallel', 'Parallel', ([], {'n_jobs': 'num_core'}), '(n_jobs=num_core)\n', (8425, 8442), False, 'from joblib import Parallel, delayed\n'), ((10564, 10583), 'glob.glob', 'glob.glob', (['filename'], {}), '(filename)\n', (10573, 10583), False, 'import glob\n'), ((11183, 11202), 'glob.glob', 'glob.glob', (['filename'], {}), '(filename)\n', (11192, 11202), False, 'import glob\n'), ((16235, 16321), 'os.system', 'os.system', (["('touch %s.%s-%s-0.message' % (message_folder + instring[:-1], part, i1))"], {}), "('touch %s.%s-%s-0.message' % (message_folder + instring[:-1],\n part, i1))\n", (16244, 16321), False, 'import os\n'), ((21635, 21661), 'numpy.stack', 'np.stack', (['res_external_obs'], {}), '(res_external_obs)\n', (21643, 21661), True, 'import numpy as np\n'), ((22555, 22566), 'time.time', 'time.time', ([], {}), '()\n', (22564, 22566), False, 'import time\n'), ((7415, 7445), 'pickle.dump', 'pickle.dump', (['[EventList[0]]', 'f'], {}), '([EventList[0]], f)\n', (7426, 7445), False, 'import pickle\n'), ((17521, 17532), 'time.time', 'time.time', ([], {}), '()\n', (17530, 17532), False, 'import time\n'), ((20875, 21038), 'os.system', 'os.system', (["('mv %s.%s-%s-%s.message %s.%s-%s-%s.message' % (message_folder + instring[\n :-1], part, i1, i2, message_folder + instring[:-1], part, i1, i2 + 1))"], {}), "('mv %s.%s-%s-%s.message %s.%s-%s-%s.message' % (message_folder +\n instring[:-1], part, i1, i2, message_folder + instring[:-1], part, i1, \n i2 + 1))\n", (20884, 21038), False, 'import os\n'), ((8443, 8464), 'joblib.delayed', 'delayed', (['calcParallel'], {}), '(calcParallel)\n', (8450, 8464), False, 'from joblib import Parallel, delayed\n'), ((9784, 9809), 'datetime.datetime.today', 'datetime.datetime.today', ([], {}), '()\n', (9807, 9809), False, 'import datetime\n'), ((10969, 11005), 'glob.glob', 'glob.glob', (["(path + 'Data/' + filename)"], {}), "(path + 'Data/' + filename)\n", (10978, 11005), False, 'import glob\n'), ((11085, 11121), 'glob.glob', 'glob.glob', (["(path + 'Data/' + filename)"], {}), "(path + 'Data/' + filename)\n", (11094, 11121), False, 'import glob\n'), ((17493, 17504), 'time.time', 'time.time', ([], {}), '()\n', (17502, 17504), False, 'import time\n'), ((17720, 17745), 'numpy.where', 'np.where', (['(outliers > 0.05)'], {}), '(outliers > 0.05)\n', (17728, 17745), True, 'import numpy as np\n'), ((18175, 18186), 'time.time', 'time.time', ([], {}), '()\n', (18184, 18186), False, 'import time\n'), ((19347, 19358), 'time.time', 'time.time', ([], {}), '()\n', (19356, 19358), False, 'import time\n'), ((19560, 19571), 'time.time', 'time.time', ([], {}), '()\n', (19569, 19571), False, 'import time\n'), ((19582, 19689), 'MLG.Modeling.fitting_micro.Fit_Micro', 'fitting_micro.Fit_Micro', (['Obs_i', 'Starnumber_i', 'Epoch_i', 'Obs_err_i', 'sc_scandir_i'], {'bounds': '(True)'}), '(Obs_i, Starnumber_i, Epoch_i, Obs_err_i,\n sc_scandir_i, bounds=True, **keywords)\n', (19605, 19689), False, 'from MLG.Modeling import fitting_micro, fitting_motion\n'), ((19710, 19721), 'time.time', 'time.time', ([], {}), '()\n', (19719, 19721), False, 'import time\n'), ((19900, 19911), 'time.time', 'time.time', ([], {}), '()\n', (19909, 19911), False, 'import time\n'), ((20314, 20325), 'time.time', 'time.time', ([], {}), '()\n', (20323, 20325), False, 'import time\n'), ((21138, 21149), 'time.time', 'time.time', ([], {}), '()\n', (21147, 21149), False, 'import time\n'), ((22001, 22029), 'MLG.Math.percentile', 'percentile', (['res_single[:, 0]'], {}), '(res_single[:, 0])\n', (22011, 22029), False, 'from MLG.Math import percentile\n'), ((22277, 22331), 'MLG.Modeling.fitting_motion.Fit_Motion', 'fitting_motion.Fit_Motion', (['*Obs_save[best]'], {}), '(*Obs_save[best], **keywords)\n', (22302, 22331), False, 'from MLG.Modeling import fitting_micro, fitting_motion\n'), ((4103, 4138), 'MLG.Math.percentile', 'percentile', (['res_all_events[i][:, 0]'], {}), '(res_all_events[i][:, 0])\n', (4113, 4138), False, 'from MLG.Math import percentile\n'), ((18689, 18796), 'MLG.Modeling.fitting_micro.Fit_Micro', 'fitting_micro.Fit_Micro', (['Obs_i', 'Starnumber_i', 'Epoch_i', 'Obs_err_i', 'sc_scandir_i'], {'bounds': '(True)'}), '(Obs_i, Starnumber_i, Epoch_i, Obs_err_i,\n sc_scandir_i, bounds=True, **keywords)\n', (18712, 18796), False, 'from MLG.Modeling import fitting_micro, fitting_motion\n'), ((20570, 20581), 'time.time', 'time.time', ([], {}), '()\n', (20579, 20581), False, 'import time\n'), ((2864, 2875), 'time.time', 'time.time', ([], {}), '()\n', (2873, 2875), False, 'import time\n'), ((4279, 4314), 'MLG.Math.percentile', 'percentile', (['res_all_events[i][:, 0]'], {}), '(res_all_events[i][:, 0])\n', (4289, 4314), False, 'from MLG.Math import percentile\n'), ((22220, 22253), 'numpy.where', 'np.where', (['(res_single[:, 0] == p50)'], {}), '(res_single[:, 0] == p50)\n', (22228, 22253), True, 'import numpy as np\n'), ((20654, 20665), 'time.time', 'time.time', ([], {}), '()\n', (20663, 20665), False, 'import time\n'), ((23159, 23187), 'MLG.Math.percentile', 'percentile', (['res_single[:, 0]'], {}), '(res_single[:, 0])\n', (23169, 23187), False, 'from MLG.Math import percentile\n'), ((23225, 23237), 'time.ctime', 'time.ctime', ([], {}), '()\n', (23235, 23237), False, 'import time\n')] |
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
import numpy as np
setup(
cmdclass = {'build_ext': build_ext},
ext_modules = [Extension("rf_classify_parallel", ["rf_classify_parallel.pyx"])],
extra_compile_args=['/openmp'],
include_dirs = [np.get_include()]
) | [
"distutils.extension.Extension",
"numpy.get_include"
] | [((201, 264), 'distutils.extension.Extension', 'Extension', (['"""rf_classify_parallel"""', "['rf_classify_parallel.pyx']"], {}), "('rf_classify_parallel', ['rf_classify_parallel.pyx'])\n", (210, 264), False, 'from distutils.extension import Extension\n'), ((323, 339), 'numpy.get_include', 'np.get_include', ([], {}), '()\n', (337, 339), True, 'import numpy as np\n')] |
import numpy as np
import os
import cv2
class VideoStartOrEndOutOfBoundsException(RuntimeError):
'''Invalid start or end location in VideoFile'''
class VideoNotFoundException(RuntimeError):
'''Raise when local video file could not be found'''
class VideoCouldNotBeOpenedException(RuntimeError):
'''Raise when the local video file could not be properly read or opened'''
"""
Behaviour notes:
0 indexed. len(x) gives 1 over the max possible frame index (kinda like how max index of an array of length 10 is 9)
When accessing data, please use accessors rather than getting the fields directly
Check VideoFile.is_open() before calling next.
If reached the end of the file, the last frame will be repeatedly returned
If turning to numpy array, note the dimensions
Example:
while vf.is_open():
cv2.imshow('windowName', vf.next())
"""
class VideoFile(object):
def __init__(self, file_loc, start: int = None, end: int = None):
self.file_loc = file_loc
if not (os.path.isfile(file_loc)):
raise VideoNotFoundException("Requested video file does not exist")
self.source = cv2.VideoCapture(file_loc)
self.true_length = int(self.source.get(cv2.CAP_PROP_FRAME_COUNT))
start = start or 0
end = end or self.true_length
self._start = start
self._end = end
if type(start) != int or type(end) != int \
or end > self.true_length \
or start < 0 \
or end <= start:
raise VideoStartOrEndOutOfBoundsException("Invalid range {0}-{1} for file of length {2}".format(
start, end, self.true_length
))
# Get properties
self.frame_count = end - start
self.frame_width = int(self.source.get(cv2.CAP_PROP_FRAME_WIDTH))
self.frame_height = int(self.source.get(cv2.CAP_PROP_FRAME_HEIGHT))
self.capture = None
self._index = None
self.set_index(0)
def __alter_index(self, index: int) -> int:
if not (self._start <= self._start + index < self._end):
raise VideoStartOrEndOutOfBoundsException("Invalid index {0} for VideoFile of length {1}".format(
index, self.frame_count))
index = self._start + index
return index
def __revert_index(self, index: int) -> int:
return index - self._start
def __set_capture(self, skip_n: int = 0):
if self.capture is not None:
self.capture.release()
skip_n = int(skip_n)
self.capture = cv2.VideoCapture(self.file_loc)
if not (self.is_open()):
raise VideoCouldNotBeOpenedException("Video format could not be read by opencv")
if skip_n > 0:
self.capture.set(cv2.CAP_PROP_POS_FRAMES, skip_n)
ret, self.current_frame = self.capture.read()
self.current_time = self.capture.get(cv2.CAP_PROP_POS_MSEC)
def set_index(self, location: int = None):
self.__set_capture(self.__alter_index(location))
def get_index(self) -> int:
return self.__revert_index(int(self.capture.get(cv2.CAP_PROP_POS_FRAMES)) - 1)
def clear(self):
self.capture.release()
def next(self) -> np.ndarray:
if self.is_open() and self.get_index()+1 < self.frame_count:
ret, frame = self.capture.read()
if ret:
self.current_frame = frame
self.current_time = self.capture.get(cv2.CAP_PROP_POS_MSEC)
return self.current_frame
def current(self):
return self.current_frame
def get_timeframe_range(self, frame_end):
timeframes = [ ]
while self.get_index() < frame_end:
timeframes.append(self.current_time)
self.next()
return timeframes
def get_frame_count(self) -> int:
return self.frame_count
def get_fps(self) -> float:
return self.capture.get(cv2.CAP_PROP_FPS)
def get_frame_width(self) -> int:
return self.capture.get(cv2.CAP_PROP_FRAME_WIDTH)
def get_frame_height(self) -> int:
return self.capture.get(cv2.CAP_PROP_FRAME_HEIGHT)
def __len__(self):
return self.get_frame_count()
def is_open(self) -> bool:
return self.capture.isOpened() and self.get_index() < self.frame_count
# Returns array with dimensions (frame_num, height, width, rgb)
def as_numpy(self, start=None, end=None):
start = start if start is not None else 0
end = end if end is not None else self.get_frame_count()
vf = VideoFile(self.file_loc, self._start, self._end)
vf.set_index(start)
ret = []
while vf.is_open() and vf.get_index() < end:
ret.append(vf.next())
return np.array(ret)
def get_width(self):
return self.frame_width
def get_height(self):
return self.frame_height
def get_time_delta(self, frame_begin, frame_end):
current_frame = self.capture.get(cv2.CAP_PROP_POS_FRAMES)
self.capture.set(cv2.CAP_PROP_POS_FRAMES, frame_begin)
self.capture.grab()
time_at_begin = self.capture.get(cv2.CAP_PROP_POS_MSEC)
self.capture.set(cv2.CAP_PROP_POS_FRAMES, frame_end)
self.capture.grab()
time_at_end = self.capture.get(cv2.CAP_PROP_POS_MSEC)
self.capture.set(cv2.CAP_PROP_POS_FRAMES, current_frame)
self.capture.grab()
return time_at_end - time_at_begin
def get_frame_after_time_elapsed(self, frame, timedelta):
current_frame = self.capture.get(cv2.CAP_PROP_POS_FRAMES)
self.capture.set(cv2.CAP_PROP_POS_FRAMES, frame)
self.capture.grab()
self.capture.set(cv2.CAP_PROP_POS_MSEC, self.capture.get(cv2.CAP_PROP_POS_MSEC) + timedelta)
self.capture.grab()
frame_at_rewind = self.capture.get(cv2.CAP_PROP_POS_FRAMES)
self.capture.set(cv2.CAP_PROP_POS_FRAMES, current_frame)
self.capture.grab()
return frame_at_rewind
def release(self):
self.capture.release()
| [
"os.path.isfile",
"numpy.array",
"cv2.VideoCapture"
] | [((1127, 1153), 'cv2.VideoCapture', 'cv2.VideoCapture', (['file_loc'], {}), '(file_loc)\n', (1143, 1153), False, 'import cv2\n'), ((2552, 2583), 'cv2.VideoCapture', 'cv2.VideoCapture', (['self.file_loc'], {}), '(self.file_loc)\n', (2568, 2583), False, 'import cv2\n'), ((4764, 4777), 'numpy.array', 'np.array', (['ret'], {}), '(ret)\n', (4772, 4777), True, 'import numpy as np\n'), ((997, 1021), 'os.path.isfile', 'os.path.isfile', (['file_loc'], {}), '(file_loc)\n', (1011, 1021), False, 'import os\n')] |
import numpy
import pandas
from nltk.tag import StanfordNERTagger
# from nltk.tag.corenlp import CoreNLPNERTagger
import os
java_path = "C:/Program Files/Java/jdk-13.0.1/bin/java.exe"
os.environ['JAVAHOME'] = java_path
# TODO: configure these paths!
a1 = 'C:\\Users\\MainUser\\OneDrive\\RAMP-EXTERNAL\\IP-02\\OSTRTA\\models\\stanford-ner-2018-10-16\\classifiers\\english.all.3class.distsim.crf.ser.gz'
a2 = 'C:\\Users\\MainUser\\OneDrive\\RAMP-EXTERNAL\\IP-02\\OSTRTA\\models\\stanford-ner-2018-10-16\\classifiers\\english.all.3class.distsim.prop'
b = 'C:\\Users\\MainUser\\OneDrive\\RAMP-EXTERNAL\\IP-02\\OSTRTA\\models\\stanford-ner-2018-10-16\\stanford-ner.jar'
in_data = pandas.read_excel('./data/source.xlsx')
array = in_data['Text'].values
st = StanfordNERTagger(a1, b)
# st = CoreNLPNERTagger(a1, b)
# Step 1. We need a global vocabulary
"""
# STRAIGHT
general = {}
general_columns = []
for x in array:
resu = st.tag(x.split())
enha = {}
for x in resu:
token = x[0]
code = x[1]
if code != 'O':
if token in list(enha.keys()):
if code not in enha[token]:
enha[token].append(code)
else:
enha[token] = [code]
for key in enha.keys():
for value in enha[key]:
if key in general.keys():
if value in general[key].keys():
pass
else:
named = '[{}]_{}'.format(key, value)
general[key][value] = named
general_columns.append(named)
else:
named = '[{}]_{}'.format(key, value)
general[key] = {}
general[key][value] = named
general_columns.append(named)
"""
"""
# POOLED # does not work: some NERs are not recognised at step 1, but are at step 2 => causing a KeyError
print('step 1')
general = {}
general_columns = []
ge = '. '.join(array)
print(ge)
resu = st.tag(ge.split())
enha = {}
for x in resu:
token = x[0]
code = x[1]
if code != 'O':
if token in list(enha.keys()):
if code not in enha[token]:
enha[token].append(code)
else:
enha[token] = [code]
for key in enha.keys():
for value in enha[key]:
if key in general.keys():
if value in general[key].keys():
pass
else:
named = '[{}]_{}'.format(key, value)
general[key][value] = named
general_columns.append(named)
else:
named = '[{}]_{}'.format(key, value)
general[key] = {}
general[key][value] = named
general_columns.append(named)
print(general)
print('Tams' in general.keys())
"""
# HYBRID
general = {}
general_columns = []
for x in array:
resu = st.tag(x.split())
enha = {}
for x in resu:
token = x[0]
code = x[1]
if code != 'O':
if token in list(enha.keys()):
if code not in enha[token]:
enha[token].append(code)
else:
enha[token] = [code]
for key in enha.keys():
for value in enha[key]:
if key in general.keys():
if value in general[key].keys():
pass
else:
named = '[{}]_{}'.format(key, value)
general[key][value] = named
general_columns.append(named)
else:
named = '[{}]_{}'.format(key, value)
general[key] = {}
general[key][value] = named
general_columns.append(named)
# Step 2. Make our data (with the vocabulary navigating columns)
print('step 2')
result = []
for x in array:
resu = st.tag(x.split())
enha = {}
for x in resu:
token = x[0]
code = x[1]
if code != 'O':
if token in list(enha.keys()):
if code not in enha[token]:
enha[token].append(code)
else:
enha[token] = [code]
#print(enha)
values = numpy.zeros(shape=(1, len(general_columns)))
for key in enha.keys():
#print(key)
for value in enha[key]:
ix = general_columns.index(general[key][value])
values[0, ix] = 1
result.append(values)
result = numpy.concatenate(result, axis=0)
data = pandas.DataFrame(data=result, columns=general_columns)
print('saved')
data.to_excel('./data/gained.xlsx', index=False)
| [
"pandas.DataFrame",
"nltk.tag.StanfordNERTagger",
"numpy.concatenate",
"pandas.read_excel"
] | [((679, 718), 'pandas.read_excel', 'pandas.read_excel', (['"""./data/source.xlsx"""'], {}), "('./data/source.xlsx')\n", (696, 718), False, 'import pandas\n'), ((756, 780), 'nltk.tag.StanfordNERTagger', 'StanfordNERTagger', (['a1', 'b'], {}), '(a1, b)\n', (773, 780), False, 'from nltk.tag import StanfordNERTagger\n'), ((4420, 4453), 'numpy.concatenate', 'numpy.concatenate', (['result'], {'axis': '(0)'}), '(result, axis=0)\n', (4437, 4453), False, 'import numpy\n'), ((4464, 4518), 'pandas.DataFrame', 'pandas.DataFrame', ([], {'data': 'result', 'columns': 'general_columns'}), '(data=result, columns=general_columns)\n', (4480, 4518), False, 'import pandas\n')] |
from os import path as osp
import cv2
import numpy as np
import matplotlib.pyplot as plt
from scipy.linalg import lstsq
from scipy.ndimage import gaussian_filter
from scipy import interpolate
import argparse
import sys
sys.path.append("..")
import Basics.params as pr
import Basics.sensorParams as psp
from Basics.Geometry import Circle
parser = argparse.ArgumentParser()
parser.add_argument("-data_path", nargs='?', default='../data/calib_ball/',
help="Path to the folder with data pack.")
args = parser.parse_args()
class PolyTable:
""" each list contains the N*N tables for one (x,y,v) pair"""
value_list = []
locx_list = []
locy_list = []
class Grads:
"""each grad contains the N*N*params table for one (normal_mag, normal_dir) pair"""
grad_r = None
grad_g = None
grad_b = None
countmap = None
class polyCalibration:
"""
Calibrate the polynomial table from the data pack
"""
def __init__(self,fn):
self.fn = osp.join(fn, "dataPack.npz")
data_file = np.load(self.fn,allow_pickle=True)
self.f0 = data_file['f0']
self.BallRad = psp.ball_radius
self.Pixmm = psp.pixmm
self.imgs = data_file['imgs']
self.radius_record = data_file['touch_radius']
self.touchCenter_record = data_file['touch_center']
self.bg_proc = self.processInitialFrame()
self.grads = Grads()
self.poly_table = PolyTable()
self.img_data_dir = fn
def processInitialFrame(self):
# gaussian filtering with square kernel with
# filterSize : kscale*2+1
# sigma : kscale
kscale = pr.kscale
img_d = self.f0.astype('float')
convEachDim = lambda in_img : gaussian_filter(in_img, kscale)
f0 = self.f0.copy()
for ch in range(img_d.shape[2]):
f0[:,:, ch] = convEachDim(img_d[:,:,ch])
frame_ = img_d
# Checking the difference between original and filtered image
diff_threshold = pr.diffThreshold
dI = np.mean(f0-frame_, axis=2)
idx = np.nonzero(dI<diff_threshold)
# Mixing image based on the difference between original and filtered image
frame_mixing_per = pr.frameMixingPercentage
h,w,ch = f0.shape
pixcount = h*w
for ch in range(f0.shape[2]):
f0[:,:,ch][idx] = frame_mixing_per*f0[:,:,ch][idx] + (1-frame_mixing_per)*frame_[:,:,ch][idx]
return f0
def calibrate_all(self):
num_img = np.shape(self.imgs)[0]
# loop through all the data points
for idx in range(num_img):
print("# iter " + str(idx))
self.calibrate_single(idx)
# final interpolation
grad_r, grad_g, grad_b = self.lookuptable_smooth()
# save the calibrated file
out_fn_path = osp.join(self.img_data_dir, "polycalib.npz")
np.savez(out_fn_path,\
bins=psp.numBins,
grad_r = grad_r,
grad_g = grad_g,
grad_b = grad_b)
print("Saved!")
def calibrate_single(self,idx):
# keep adding items
frame = self.imgs[idx,:,:,:]
# remove background
dI = frame.astype("float") - self.bg_proc
circle = Circle(int(self.touchCenter_record[idx,0]), int(self.touchCenter_record[idx,1]),int(self.radius_record[idx]))
bins = psp.numBins
ball_radius_pix = psp.ball_radius/psp.pixmm
center = circle.center
radius = circle.radius
sizey, sizex = dI.shape[:2]
[xqq, yqq] = np.meshgrid(range(sizex), range(sizey))
xq = xqq - center[0]
yq = yqq - center[1]
rsqcoord = xq*xq + yq*yq
rad_sq = radius*radius
# get the contact area
valid_rad = min(rad_sq, int(ball_radius_pix*ball_radius_pix))
valid_mask = rsqcoord < (valid_rad)
validId = np.nonzero(valid_mask)
xvalid = xq[validId]; yvalid = yq[validId]
rvalid = np.sqrt( xvalid*xvalid + yvalid*yvalid)
# get gradients
gradxseq = np.arcsin(rvalid/ball_radius_pix)
gradyseq = np.arctan2(-yvalid, -xvalid)
binm = bins - 1
x_binr = 0.5*np.pi/binm # x [0,pi/2]
y_binr = 2*np.pi/binm # y [-pi, pi]
# discritize the gradients
idx_x = np.floor(gradxseq/x_binr).astype('int')
idx_y = np.floor((gradyseq+np.pi)/y_binr).astype('int')
# r channel
value_map = np.zeros((bins,bins,3))
loc_x_map = np.zeros((bins,bins))
loc_y_map = np.zeros((bins,bins))
valid_r = dI[:,:,0][validId]
valid_x = xqq[validId]
valid_y = yqq[validId]
value_map[idx_x, idx_y, 0] += valid_r
# g channel
valid_g = dI[:,:,1][validId]
value_map[idx_x, idx_y, 1] += valid_g
# b channel
valid_b = dI[:,:,2][validId]
value_map[idx_x, idx_y, 2] += valid_b
loc_x_map[idx_x, idx_y] += valid_x
loc_y_map[idx_x, idx_y] += valid_y
loc_x_map = self.interpolate(loc_x_map)
loc_y_map = self.interpolate(loc_y_map)
value_map[:,:,0] = self.interpolate(value_map[:,:,0])
value_map[:,:,1] = self.interpolate(value_map[:,:,1])
value_map[:,:,2] = self.interpolate(value_map[:,:,2])
self.poly_table.value_list.append(value_map)
self.poly_table.locx_list.append(loc_x_map)
self.poly_table.locy_list.append(loc_y_map)
def interpolate(self,img):
# here we assume there are some zero value holes in the image,
# and we hope to fill these holes with interpolation
x = np.arange(0, img.shape[1])
y = np.arange(0, img.shape[0])
#mask invalid values
array = np.ma.masked_where(img == 0, img)
xx, yy = np.meshgrid(x, y)
#get only the valid values
x1 = xx[~array.mask]
y1 = yy[~array.mask]
newarr = img[~array.mask]
GD1 = interpolate.griddata((x1, y1), newarr.ravel(),
(xx, yy),
method='nearest', fill_value = 0) # cubic # nearest
return GD1
def lookuptable_smooth(self):
# final refine
[h,w,c] = self.bg_proc.shape
xx,yy = np.meshgrid(np.arange(w),np.arange(h))
xf = xx.flatten()
yf = yy.flatten()
A = np.array([xf*xf,yf*yf,xf*yf,xf,yf,np.ones(h*w)]).T
table_v = np.array(self.poly_table.value_list)
table_x = np.array(self.poly_table.locx_list)
table_y = np.array(self.poly_table.locy_list)
bins = psp.numBins
self.grads.grad_r = np.zeros((bins,bins,6))
self.grads.grad_g = np.zeros((bins,bins,6))
self.grads.grad_b = np.zeros((bins,bins,6))
for i in range(table_v.shape[1]):
for j in range(table_v.shape[2]):
params_r = self.fitPolyParams(table_x[:,i,j],table_y[:,i,j],table_v[:,i,j,0])
params_g = self.fitPolyParams(table_x[:,i,j],table_y[:,i,j],table_v[:,i,j,1])
params_b = self.fitPolyParams(table_x[:,i,j],table_y[:,i,j],table_v[:,i,j,2])
self.grads.grad_r[i,j,:] = params_r
self.grads.grad_g[i,j,:] = params_g
self.grads.grad_b[i,j,:] = params_b
return self.grads.grad_r, self.grads.grad_g, self.grads.grad_b
def fitPolyParams(self,xf,yf,b):
A = np.array([xf*xf,yf*yf,xf*yf,xf,yf,np.ones(xf.shape)]).T
params, res, rnk, s = lstsq(A, b)
return params
if __name__ == "__main__":
polyCalib = polyCalibration(args.data_path)
polyCalib.calibrate_all()
| [
"numpy.sqrt",
"numpy.array",
"numpy.arctan2",
"scipy.ndimage.gaussian_filter",
"sys.path.append",
"numpy.arange",
"numpy.mean",
"numpy.savez",
"scipy.linalg.lstsq",
"argparse.ArgumentParser",
"numpy.ma.masked_where",
"numpy.meshgrid",
"numpy.ones",
"numpy.floor",
"numpy.nonzero",
"nump... | [((220, 241), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (235, 241), False, 'import sys\n'), ((348, 373), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (371, 373), False, 'import argparse\n'), ((988, 1016), 'os.path.join', 'osp.join', (['fn', '"""dataPack.npz"""'], {}), "(fn, 'dataPack.npz')\n", (996, 1016), True, 'from os import path as osp\n'), ((1037, 1072), 'numpy.load', 'np.load', (['self.fn'], {'allow_pickle': '(True)'}), '(self.fn, allow_pickle=True)\n', (1044, 1072), True, 'import numpy as np\n'), ((2045, 2073), 'numpy.mean', 'np.mean', (['(f0 - frame_)'], {'axis': '(2)'}), '(f0 - frame_, axis=2)\n', (2052, 2073), True, 'import numpy as np\n'), ((2087, 2118), 'numpy.nonzero', 'np.nonzero', (['(dI < diff_threshold)'], {}), '(dI < diff_threshold)\n', (2097, 2118), True, 'import numpy as np\n'), ((2839, 2883), 'os.path.join', 'osp.join', (['self.img_data_dir', '"""polycalib.npz"""'], {}), "(self.img_data_dir, 'polycalib.npz')\n", (2847, 2883), True, 'from os import path as osp\n'), ((2892, 2980), 'numpy.savez', 'np.savez', (['out_fn_path'], {'bins': 'psp.numBins', 'grad_r': 'grad_r', 'grad_g': 'grad_g', 'grad_b': 'grad_b'}), '(out_fn_path, bins=psp.numBins, grad_r=grad_r, grad_g=grad_g,\n grad_b=grad_b)\n', (2900, 2980), True, 'import numpy as np\n'), ((3891, 3913), 'numpy.nonzero', 'np.nonzero', (['valid_mask'], {}), '(valid_mask)\n', (3901, 3913), True, 'import numpy as np\n'), ((3982, 4024), 'numpy.sqrt', 'np.sqrt', (['(xvalid * xvalid + yvalid * yvalid)'], {}), '(xvalid * xvalid + yvalid * yvalid)\n', (3989, 4024), True, 'import numpy as np\n'), ((4065, 4100), 'numpy.arcsin', 'np.arcsin', (['(rvalid / ball_radius_pix)'], {}), '(rvalid / ball_radius_pix)\n', (4074, 4100), True, 'import numpy as np\n'), ((4118, 4146), 'numpy.arctan2', 'np.arctan2', (['(-yvalid)', '(-xvalid)'], {}), '(-yvalid, -xvalid)\n', (4128, 4146), True, 'import numpy as np\n'), ((4457, 4482), 'numpy.zeros', 'np.zeros', (['(bins, bins, 3)'], {}), '((bins, bins, 3))\n', (4465, 4482), True, 'import numpy as np\n'), ((4501, 4523), 'numpy.zeros', 'np.zeros', (['(bins, bins)'], {}), '((bins, bins))\n', (4509, 4523), True, 'import numpy as np\n'), ((4543, 4565), 'numpy.zeros', 'np.zeros', (['(bins, bins)'], {}), '((bins, bins))\n', (4551, 4565), True, 'import numpy as np\n'), ((5624, 5650), 'numpy.arange', 'np.arange', (['(0)', 'img.shape[1]'], {}), '(0, img.shape[1])\n', (5633, 5650), True, 'import numpy as np\n'), ((5663, 5689), 'numpy.arange', 'np.arange', (['(0)', 'img.shape[0]'], {}), '(0, img.shape[0])\n', (5672, 5689), True, 'import numpy as np\n'), ((5735, 5768), 'numpy.ma.masked_where', 'np.ma.masked_where', (['(img == 0)', 'img'], {}), '(img == 0, img)\n', (5753, 5768), True, 'import numpy as np\n'), ((5786, 5803), 'numpy.meshgrid', 'np.meshgrid', (['x', 'y'], {}), '(x, y)\n', (5797, 5803), True, 'import numpy as np\n'), ((6429, 6465), 'numpy.array', 'np.array', (['self.poly_table.value_list'], {}), '(self.poly_table.value_list)\n', (6437, 6465), True, 'import numpy as np\n'), ((6484, 6519), 'numpy.array', 'np.array', (['self.poly_table.locx_list'], {}), '(self.poly_table.locx_list)\n', (6492, 6519), True, 'import numpy as np\n'), ((6538, 6573), 'numpy.array', 'np.array', (['self.poly_table.locy_list'], {}), '(self.poly_table.locy_list)\n', (6546, 6573), True, 'import numpy as np\n'), ((6630, 6655), 'numpy.zeros', 'np.zeros', (['(bins, bins, 6)'], {}), '((bins, bins, 6))\n', (6638, 6655), True, 'import numpy as np\n'), ((6682, 6707), 'numpy.zeros', 'np.zeros', (['(bins, bins, 6)'], {}), '((bins, bins, 6))\n', (6690, 6707), True, 'import numpy as np\n'), ((6734, 6759), 'numpy.zeros', 'np.zeros', (['(bins, bins, 6)'], {}), '((bins, bins, 6))\n', (6742, 6759), True, 'import numpy as np\n'), ((7493, 7504), 'scipy.linalg.lstsq', 'lstsq', (['A', 'b'], {}), '(A, b)\n', (7498, 7504), False, 'from scipy.linalg import lstsq\n'), ((1740, 1771), 'scipy.ndimage.gaussian_filter', 'gaussian_filter', (['in_img', 'kscale'], {}), '(in_img, kscale)\n', (1755, 1771), False, 'from scipy.ndimage import gaussian_filter\n'), ((2513, 2532), 'numpy.shape', 'np.shape', (['self.imgs'], {}), '(self.imgs)\n', (2521, 2532), True, 'import numpy as np\n'), ((6268, 6280), 'numpy.arange', 'np.arange', (['w'], {}), '(w)\n', (6277, 6280), True, 'import numpy as np\n'), ((6281, 6293), 'numpy.arange', 'np.arange', (['h'], {}), '(h)\n', (6290, 6293), True, 'import numpy as np\n'), ((4312, 4339), 'numpy.floor', 'np.floor', (['(gradxseq / x_binr)'], {}), '(gradxseq / x_binr)\n', (4320, 4339), True, 'import numpy as np\n'), ((4368, 4405), 'numpy.floor', 'np.floor', (['((gradyseq + np.pi) / y_binr)'], {}), '((gradyseq + np.pi) / y_binr)\n', (4376, 4405), True, 'import numpy as np\n'), ((6393, 6407), 'numpy.ones', 'np.ones', (['(h * w)'], {}), '(h * w)\n', (6400, 6407), True, 'import numpy as np\n'), ((7441, 7458), 'numpy.ones', 'np.ones', (['xf.shape'], {}), '(xf.shape)\n', (7448, 7458), True, 'import numpy as np\n')] |
"""
Implements the Perception & Adaline Learning Algorithm
Author: <NAME>
Created: May 18, 2010
"""
import numpy as np
import matplotlib.pyplot as plt
class Perception:
"""first artifical neural classifier
Args:
eta: Learning rate (between 0.0 and 1.0)
n_iter: passees over the training set
random_state: Random Number Generator seed
for random weight initilization
Attributes:
w: Weights after fitting
errors: Number of misclassifications(updates) in each epoch
"""
def __init__(self, eta: float = 0.01, n_iter: int = 50, random_state: int = 1):
self.eta = eta
self.n_iter = n_iter
self.random_state = random_state
def fit(self, X: np.ndarray, y: np.ndarray) -> 'Perception':
"""fits training data
Args:
X: shape = {n_samples, p_features}
n_samples is number of instances i.e rows
p_features is number of features (the dimension of dataset)
y: shape = {n_samples, 1}
Target values
Returns:
object
"""
# random number gen seed to reproduce values if needed
rgen = np.random.RandomState(self.random_state)
# initialize weights from normal distribution
self.w = rgen.normal(loc=0.0, scale=0.01, size=1+X.shape[1])
self.errors = []
for _ in range(self.n_iter):
errors = 0
# for each instance in training set
for xi, target in zip(X, y):
# calculate the weight update by perception rule
delta_wj = self.eta * (target - self.predict(xi))
# update all weights simultaneously
# given by wj := wj + delta_wj
self.w[1:] += + delta_wj * xi
# since x0 = 1 by construction
self.w[0] += delta_wj
# calculate number of misclassifications
errors += int(delta_wj != 0)
self.errors.append(errors)
return self
def net_input(self, X: np.ndarray) -> np.ndarray:
"""computes the net input vector
z = w1x1 + w2x2 + ... + wpXp
Args:
X: shape = {n_samples, p_features}
n_samples is # of instances
p_features is number of features (dimension of dataset)
Returns:
z: shape = {n_samples, 1}
net input vector
"""
return np.dot(X, self.w[1:]) + self.w[0]
def predict(self, X: np.ndarray) -> float:
"""
computes the classifier phi(z)
where phi(z) = 1 if z:= w'x >=0, -1 otherwise
Args:
X: shape {n_samples, p_features}
Returns:
classifier with value +1 or -1
"""
return np.where(self.net_input(X) > 0, 1, -1)
def plot_misclassifications(self) -> None:
"""plots the misclassifications given the number of epoochs
requires to call the fit() first
"""
try:
plt.plot(range(1, self.n_iter + 1), self.errors, marker='o');
plt.xlabel("epoch")
plt.ylabel("# of misclassifications")
except AttributeError as e:
print("must call fit() first before plotting misclassifications")
else:
return
class AdalineGD:
"""artificial neural classifier
implemented with gradient descent
Args:
eta: Learning rate (between 0.0 and 1.0)
n_iter: passees over the training set
random_state: Random Number Generator seed
for random weight initilization
Attributes:
w: Weights after fitting
errors: Number of misclassifications(updates) in each epoch
"""
def __init__(self, eta: float = 0.01, n_iter: int = 50, random_state: int = 1):
self.eta = eta
self.n_iter = n_iter
self.random_state = random_state
def fit(self, X: np.ndarray, y: np.ndarray) -> 'AdalineGD':
"""fits training data
Args:
X: shape = {n_samples, p_features}
n_samples is number of instances i.e rows
p_features is number of features (the dimension of dataset)
y: shape = {n_samples, 1}
Target values
Returns:
object
"""
# random number gen seed to reproduce values if needed
rgen = np.random.RandomState(self.random_state)
# initialize weights from normal distribution
self.w = rgen.normal(loc=0.0, scale=0.01, size=1+X.shape[1])
self.cost = []
for _ in range(self.n_iter):
# calculate net input
net_input = self.net_input(X)
# calculate the linear activation function phi(z) = w'x = z
output = self.activation(net_input)
errors = y - output
# update the weights
self.w[1:] += eta * X.T.dot(errors)
self.w[0] += eta * errors.sum()
# sse based on J(w) = 1/2 sum(yi - yhat)**2
cost = (errors**2).sum() / 2.0
self.cost.append(cost)
return self
def net_input(self, X: np.ndarray) -> np.ndarray:
"""computes the net input vector
z = w1x1 + w2x2 + ... + wpXp
Args:
X: shape = {n_samples, p_features}
n_samples is # of instances
p_features is number of features (dimension of dataset)
Returns:
z: shape = {n_samples, 1}
net input vector
"""
return np.dot(X, self.w[1:]) + self.w[0]
def activation(self, X: np.ndarray) -> np.ndarray:
"""compute linear activation z = w'x = phi(z)
Args:
X: shape = {n_samples, n_features}
Returns:
the input by itself
"""
return X
def predict(self, X: np.ndarray) -> float:
"""
computes the classifier phi(z)
where phi(z) = 1 if z:= w'x >=0, -1 otherwise
Args:
X: shape {n_samples, p_features}
Returns:
classifier with value +1 or -1
"""
return np.where(self.activation(self.net_input(X)) > 0, 1, -1) | [
"numpy.dot",
"matplotlib.pyplot.xlabel",
"numpy.random.RandomState",
"matplotlib.pyplot.ylabel"
] | [((1270, 1310), 'numpy.random.RandomState', 'np.random.RandomState', (['self.random_state'], {}), '(self.random_state)\n', (1291, 1310), True, 'import numpy as np\n'), ((4578, 4618), 'numpy.random.RandomState', 'np.random.RandomState', (['self.random_state'], {}), '(self.random_state)\n', (4599, 4618), True, 'import numpy as np\n'), ((2565, 2586), 'numpy.dot', 'np.dot', (['X', 'self.w[1:]'], {}), '(X, self.w[1:])\n', (2571, 2586), True, 'import numpy as np\n'), ((3204, 3223), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""epoch"""'], {}), "('epoch')\n", (3214, 3223), True, 'import matplotlib.pyplot as plt\n'), ((3236, 3273), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""# of misclassifications"""'], {}), "('# of misclassifications')\n", (3246, 3273), True, 'import matplotlib.pyplot as plt\n'), ((5747, 5768), 'numpy.dot', 'np.dot', (['X', 'self.w[1:]'], {}), '(X, self.w[1:])\n', (5753, 5768), True, 'import numpy as np\n')] |
from __future__ import division
import numpy as np
from random import shuffle
class Model(object):
def fit(self, data):
raise NotImplementedError
def distance(self, samples):
raise NotImplementedError
class LineModel(Model):
"""
A 2D line model.
"""
def fit(self, data):
"""
Fits the model to the data, minimizing the sum of absolute
errors.
The fitting is done in the simplest manner possible; drawing a
line through two of the samples instead of the more common
least squares method.
"""
X = data[:,0]
Y = data[:,1]
denom = (X[-1] - X[0])
if denom == 0:
raise ZeroDivisionError
k = (Y[-1] - Y[0]) / denom
m = Y[0] - k * X[0]
self.params = [k, m]
self.residual = sum(abs(k * X + m - Y))
def distance(self, samples):
"""
Calculates the vertical distances from the samples to the model.
"""
X = samples[:,0]
Y = samples[:,1]
k = self.params[0]
m = self.params[1]
dists = abs(k * X + m - Y)
return dists
def ransac(data, model, min_samples, min_inliers, iterations=100, eps=1e-10):
"""
Fits a model to observed data.
Uses the RANSAC iterative method of fitting a model to observed
data. The method is robust as it ignores outlier data.
Parameters
----------
data : numpy.ndarray
The data that the model should be fitted to.
model : Model
The model that is used to describe the data.
min_samples : int
The minimum number of samples needed to fit the model.
min_inliers : number
The number of inliers required to assert that the model
is a good fit. If 0 < min_inliers < 1 then min_inliers
is considered a percentage of the number of samples in
the data.
iterations : int
The number of iterations that the algorithm should run.
eps : float
The maximum allowed distance from the model that a sample is
allowed to be to be counted as an inlier.
Returns
-------
best_params : list
The parameters of the model with the best fit.
best_inliers : numpy.ndarray
A list of the inliers belonging to the model with the best fit.
best_residual : float
The residual of the inliers.
Raises
------
ValueError
If the algorithm could not find a good fit for the data.
"""
if len(data) <= min_samples:
raise ValueError("Not enough input data to fit the model.")
if 0 < min_inliers < 1:
min_inliers = int(min_inliers * len(data))
best_params = None
best_inliers = None
best_residual = np.inf
for i in xrange(iterations):
indices = range(len(data))
shuffle(indices)
inliers = np.asarray([data[i] for i in indices[:min_samples]])
shuffled_data = np.asarray([data[i] for i in indices[min_samples:]])
try:
model.fit(inliers)
dists = model.distance(shuffled_data)
more_inliers = shuffled_data[np.where(dists <= eps)[0]]
inliers = np.concatenate((inliers, more_inliers))
if len(inliers) >= min_inliers:
model.fit(inliers)
if model.residual < best_residual:
best_params = model.params
best_inliers = inliers
best_residual = model.residual
except ZeroDivisionError:
pass
if not best_params:
raise ValueError("RANSAC failed to find a sufficiently good fit for "
"the data. Check that input data has sufficient rank.")
return (best_params, best_inliers, best_residual)
| [
"numpy.where",
"numpy.asarray",
"random.shuffle",
"numpy.concatenate"
] | [((2860, 2876), 'random.shuffle', 'shuffle', (['indices'], {}), '(indices)\n', (2867, 2876), False, 'from random import shuffle\n'), ((2907, 2959), 'numpy.asarray', 'np.asarray', (['[data[i] for i in indices[:min_samples]]'], {}), '([data[i] for i in indices[:min_samples]])\n', (2917, 2959), True, 'import numpy as np\n'), ((2990, 3042), 'numpy.asarray', 'np.asarray', (['[data[i] for i in indices[min_samples:]]'], {}), '([data[i] for i in indices[min_samples:]])\n', (3000, 3042), True, 'import numpy as np\n'), ((3228, 3267), 'numpy.concatenate', 'np.concatenate', (['(inliers, more_inliers)'], {}), '((inliers, more_inliers))\n', (3242, 3267), True, 'import numpy as np\n'), ((3179, 3201), 'numpy.where', 'np.where', (['(dists <= eps)'], {}), '(dists <= eps)\n', (3187, 3201), True, 'import numpy as np\n')] |
#encoding=utf-8
#
import os,cv2,sys
from basicFun import XML,FILES,COCO
from tqdm import tqdm
import numpy as np
class info_count():
def init(self, txt=None):
self.info={}
self.num=0
print('init')
if txt:
with open(txt, 'r') as f:
lines = f.readlines()
for line in lines:
k, v = line.split()[0], int(line.split()[1])
self.info[k]=v
print('load data')
def count(self):
self.num=self.num+1
def addtag(self, name):
self.info[name]=1
def update(self, name):
num = self.info[name]
num += 1
self.info[name] = num
def print(self):
for key in self.info:
print(key, self.info[key])
print('--')
def get_labels(self):
labels=[]
for key in self.info:
labels.append(key)
print(labels)
return labels
def get_values(self):
values=[]
for key in self.info:
values.append(self.info[key])
print(values)
return values
def analyze_xml(path):
objs = XML.read_objects(path)
#print(objs)
for obj in objs:
name = obj['name']
'''
if name in ['、', 'microbus_foreign\n', 'micorbus_foreign', 'car_pickup', 'truck_foregin', 'suv_foreign']:
print(path)
print(obj)
exit()
'''
if name not in count.info:
count.addtag(name)
else:
count.update(name)
count.count()
xmin = int(obj['xmin'])
ymin = int(obj['ymin'])
xmax = int(obj['xmax'])
ymax = int(obj['ymax'])
w = xmax - xmin
h = ymax - ymin
scale = round(np.sqrt(w*h))
nn=int(scale/25)+1
scale = nn*25
'''
if scale >2000:
print(path)
print(obj)
exit()
'''
if scale not in count2.info:
count2.addtag(scale)
else:
count2.update(scale)
count2.count()
if __name__=="__main__":
global count, scale_list, count2
scale_list = []
count = info_count()
count.init()
count2 = info_count()
count2.init()
imgDir=r'/media/kevin/娱乐/xizang_database/testdata/1125/JPEGImages'
xmlDir=r'/media/kevin/娱乐/xizang_database/testdata/1125/all_Annotations_no_change_label'
print(xmlDir)
allXmls=[x for x in FILES.get_sorted_files(xmlDir) if ".xml" in x]
for xml in tqdm(allXmls):
xmlPath=os.path.join(xmlDir,xml)
imgPath=os.path.join(imgDir,xml.replace('.xml','.jpg'))
analyze_xml(xmlPath)
count.print()
print('Totally count {} targets'.format(count.num))
# -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
import sys
#reload(sys)
#sys.setdefaultencoding('utf8')
# from pylab import *
#mpl.rcParams['font.sans-serif'] = ['Microsoft YaHei']#指定默认字体
#mpl.rcParams['axes.unicode_minus'] =False # 解决保存图像是负号'-'显示为方块的问题
#from sqlalchemy import create_engine
import seaborn as sns
import matplotlib.pyplot as plt
#count.init('src.txt')
#count.print()
labels = count.get_labels()
values = count.get_values()
df = pd.DataFrame({'labels': labels,
'values': values})#生成
print(df)
plt.figure(figsize = (18, 8))
ax = sns.barplot(x=df['labels'], y=df["values"], data=df)
# 旋转轴刻度上文字方向
ax.set_xticklabels(ax.get_xticklabels(), rotation=-30)
plt.show()
labels = count2.get_labels()
values = count2.get_values()
df = pd.DataFrame({'labels': labels,
'values': values})#生成
print(df)
plt.figure(figsize = (18, 8))
ax = sns.barplot(x=df['labels'], y=df["values"], data=df)
plt.xlim(-5,50)
# 旋转轴刻度上文字方向
ax.set_xticklabels(ax.get_xticklabels(), rotation=-30)
plt.show()
| [
"basicFun.FILES.get_sorted_files",
"numpy.sqrt",
"matplotlib.pyplot.xlim",
"tqdm.tqdm",
"os.path.join",
"basicFun.XML.read_objects",
"matplotlib.pyplot.figure",
"pandas.DataFrame",
"seaborn.barplot",
"matplotlib.pyplot.show"
] | [((1232, 1254), 'basicFun.XML.read_objects', 'XML.read_objects', (['path'], {}), '(path)\n', (1248, 1254), False, 'from basicFun import XML, FILES, COCO\n'), ((2717, 2730), 'tqdm.tqdm', 'tqdm', (['allXmls'], {}), '(allXmls)\n', (2721, 2730), False, 'from tqdm import tqdm\n'), ((3517, 3567), 'pandas.DataFrame', 'pd.DataFrame', (["{'labels': labels, 'values': values}"], {}), "({'labels': labels, 'values': values})\n", (3529, 3567), True, 'import pandas as pd\n'), ((3621, 3648), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(18, 8)'}), '(figsize=(18, 8))\n', (3631, 3648), True, 'import matplotlib.pyplot as plt\n'), ((3661, 3713), 'seaborn.barplot', 'sns.barplot', ([], {'x': "df['labels']", 'y': "df['values']", 'data': 'df'}), "(x=df['labels'], y=df['values'], data=df)\n", (3672, 3713), True, 'import seaborn as sns\n'), ((3799, 3809), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3807, 3809), True, 'import matplotlib.pyplot as plt\n'), ((3913, 3963), 'pandas.DataFrame', 'pd.DataFrame', (["{'labels': labels, 'values': values}"], {}), "({'labels': labels, 'values': values})\n", (3925, 3963), True, 'import pandas as pd\n'), ((4017, 4044), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(18, 8)'}), '(figsize=(18, 8))\n', (4027, 4044), True, 'import matplotlib.pyplot as plt\n'), ((4057, 4109), 'seaborn.barplot', 'sns.barplot', ([], {'x': "df['labels']", 'y': "df['values']", 'data': 'df'}), "(x=df['labels'], y=df['values'], data=df)\n", (4068, 4109), True, 'import seaborn as sns\n'), ((4115, 4131), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(-5)', '(50)'], {}), '(-5, 50)\n', (4123, 4131), True, 'import matplotlib.pyplot as plt\n'), ((4214, 4224), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4222, 4224), True, 'import matplotlib.pyplot as plt\n'), ((2749, 2774), 'os.path.join', 'os.path.join', (['xmlDir', 'xml'], {}), '(xmlDir, xml)\n', (2761, 2774), False, 'import os, cv2, sys\n'), ((1888, 1902), 'numpy.sqrt', 'np.sqrt', (['(w * h)'], {}), '(w * h)\n', (1895, 1902), True, 'import numpy as np\n'), ((2652, 2682), 'basicFun.FILES.get_sorted_files', 'FILES.get_sorted_files', (['xmlDir'], {}), '(xmlDir)\n', (2674, 2682), False, 'from basicFun import XML, FILES, COCO\n')] |
# Author: Copyright (c) 2021 <NAME>
# License: MIT License
"""
Test normla_factor against standard tables of tolerance factors
as published in ISO 16269-6:2014 Annex F.
A sampling of values from the tables is included here for brevity.
"""
import numpy as np
import toleranceinterval.twoside as ts
import unittest
def decimal_ceil(x, places):
"""
Apply ceiling function at a decimal place.
The tables of tolerance factors in ISO 16269-6:2014 provide
the tolerance factors to a certain number of decimal places. The values
at that final decimal place reflect the application of the ceiling function
at that decimal place.
"""
x *= 10 ** places
x = np.ceil(x)
x /= 10 ** places
return x
class BaseTestIso:
class TestIsoTableF(unittest.TestCase):
def test_tolerance_factor(self):
for row_idx, row in enumerate(self.factor_k5):
for col_idx, k5 in enumerate(row):
k = ts.normal_factor(
self.sample_size[row_idx],
self.coverage,
self.confidence,
method='exact',
m=self.number_of_samples[col_idx])
k = decimal_ceil(k, places=4)
self.assertAlmostEqual(k, k5, places=4)
class TestIsoF1(BaseTestIso.TestIsoTableF):
coverage = 0.90
confidence = 0.90
# This is n from the table.
sample_size = np.array([
2, 8, 16, 35, 100, 300, 1000, np.inf,
])
# This is m from the table.
number_of_samples = np.arange(1, 11)
factor_k5 = np.array([
# n = 2
15.5124, 6.0755, 4.5088, 3.8875, 3.5544,
3.3461, 3.2032, 3.0989, 3.0193, 2.9565,
# n = 8
2.7542, 2.3600, 2.2244, 2.1530, 2.1081,
2.0769, 2.0539, 2.0361, 2.0220, 2.0104,
# n = 16
2.2537, 2.0574, 1.9833, 1.9426, 1.9163,
1.8977, 1.8837, 1.8727, 1.8638, 1.8564,
# n = 35
1.9906, 1.8843, 1.8417, 1.8176, 1.8017,
1.7902, 1.7815, 1.7747, 1.7690, 1.7643,
# n = 100
1.8232, 1.7697, 1.7473, 1.7343, 1.7256,
1.7193, 1.7144, 1.7105, 1.7073, 1.7047,
# n = 300
1.7401, 1.7118, 1.6997, 1.6925, 1.6877,
1.6842, 1.6815, 1.6793, 1.6775, 1.6760,
# n = 1000
1.6947, 1.6800, 1.6736, 1.6698, 1.6672,
1.6653, 1.6639, 1.6627, 1.6617, 1.6609,
# n = infinity
1.6449, 1.6449, 1.6449, 1.6449, 1.6449,
1.6449, 1.6449, 1.6449, 1.6449, 1.6449,
])
factor_k5 = factor_k5.reshape(sample_size.size, number_of_samples.size)
class TestIsoF2(BaseTestIso.TestIsoTableF):
coverage = 0.95
confidence = 0.90
# This is n from the table.
sample_size = np.array([
3, 9, 15, 30, 90, 150, 400, 1000, np.inf,
])
# This is m from the table.
number_of_samples = np.arange(1, 11)
factor_k5 = np.array([
# n = 3
6.8233, 4.3320, 3.7087, 3.4207, 3.2528,
3.1420, 3.0630, 3.0038, 2.9575, 2.9205,
# n = 9
3.1323, 2.7216, 2.5773, 2.5006, 2.4521,
2.4182, 2.3931, 2.3737, 2.3581, 2.3454,
# n = 15
2.7196, 2.4718, 2.3789, 2.3280, 2.2951,
2.2719, 2.2545, 2.2408, 2.2298, 2.2206,
# n = 30
2.4166, 2.2749, 2.2187, 2.1870, 2.1662,
2.1513, 2.1399, 2.1309, 2.1236, 2.1175,
# n = 90
2.1862, 2.1182, 2.0898, 2.0733, 2.0624,
2.0544, 2.0482, 2.0433, 2.0393, 2.0360,
# n = 150
2.1276, 2.0775, 2.0563, 2.0439, 2.0356,
2.0296, 2.0249, 2.0212, 2.0181, 2.0155,
# n = 400
2.0569, 2.0282, 2.0158, 2.0085, 2.0035,
1.9999, 1.9971, 1.9949, 1.9930, 1.9915,
# n = 1000
2.0193, 2.0018, 1.9942, 1.9897, 1.9866,
1.9844, 1.9826, 1.9812, 1.9800, 1.9791,
# n = infinity
1.9600, 1.9600, 1.9600, 1.9600, 1.9600,
1.9600, 1.9600, 1.9600, 1.9600, 1.9600,
])
factor_k5 = factor_k5.reshape(sample_size.size, number_of_samples.size)
class TestIsoF3(BaseTestIso.TestIsoTableF):
coverage = 0.99
confidence = 0.90
# This is n from the table.
sample_size = np.array([
4, 8, 17, 28, 100, 300, 1000, np.inf,
])
# This is m from the table.
number_of_samples = np.arange(1, 11)
factor_k5 = np.array([
# n = 4
6.3722, 4.6643, 4.1701, 3.9277, 3.7814,
3.6825, 3.6108, 3.5562, 3.5131, 3.4782,
# n = 8
4.2707, 3.6541, 3.4408, 3.3281, 3.2572,
3.2078, 3.1712, 3.1428, 3.1202, 3.1016,
# n = 17
3.4741, 3.1819, 3.0708, 3.0095, 2.9698,
2.9416, 2.9204, 2.9037, 2.8902, 2.8791,
# n = 28
3.2023, 3.0062, 2.9286, 2.8850, 2.8564,
2.8358, 2.8203, 2.8080, 2.7980, 2.7896,
# n = 100
2.8548, 2.7710, 2.7358, 2.7155, 2.7018,
2.6919, 2.6843, 2.6782, 2.6732, 2.6690,
# n = 300
2.7249, 2.6806, 2.6616, 2.6504, 2.6429,
2.6374, 2.6331, 2.6297, 2.6269, 2.6245,
# n = 1000
2.6538, 2.6308, 2.6208, 2.6148, 2.6108,
2.6079, 2.6056, 2.6037, 2.6022, 2.6009,
# n = infinity
2.5759, 2.5759, 2.5759, 2.5759, 2.5759,
2.5759, 2.5759, 2.5759, 2.5759, 2.5759,
])
factor_k5 = factor_k5.reshape(sample_size.size, number_of_samples.size)
class TestIsoF4(BaseTestIso.TestIsoTableF):
coverage = 0.90
confidence = 0.95
# This is n from the table.
sample_size = np.array([
2, 8, 16, 35, 150, 500, 1000, np.inf,
])
# This is m from the table.
number_of_samples = np.arange(1, 11)
factor_k5 = np.array([
# n = 2
31.0923, 8.7252, 5.8380, 4.7912, 4.2571,
3.9341, 3.7179, 3.5630, 3.4468, 3.3565,
# n = 8
3.1561, 2.5818, 2.3937, 2.2974, 2.2381,
2.1978, 2.1685, 2.1463, 2.1289, 2.1149,
# n = 16
2.4486, 2.1771, 2.0777, 2.0241, 1.9899,
1.9661, 1.9483, 1.9346, 1.9237, 1.9147,
# n = 35
2.0943, 1.9515, 1.8953, 1.8638, 1.8432,
1.8285, 1.8174, 1.8087, 1.8016, 1.7957,
# n = 150
1.8260, 1.7710, 1.7478, 1.7344, 1.7254,
1.7188, 1.7137, 1.7097, 1.7064, 1.7036,
# n = 500
1.7374, 1.7098, 1.6979, 1.6908, 1.6861,
1.6826, 1.6799, 1.6777, 1.6760, 1.6744,
# n = 1000
1.7088, 1.6898, 1.6816, 1.6767, 1.6734,
1.6709, 1.6690, 1.6675, 1.6663, 1.6652,
# n = infinity
1.6449, 1.6449, 1.6449, 1.6449, 1.6449,
1.6449, 1.6449, 1.6449, 1.6449, 1.6449,
])
factor_k5 = factor_k5.reshape(sample_size.size, number_of_samples.size)
class TestIsoF5(BaseTestIso.TestIsoTableF):
coverage = 0.95
confidence = 0.95
# This is n from the table.
sample_size = np.array([
5, 10, 26, 90, 200, 1000, np.inf,
])
# This is m from the table.
number_of_samples = np.arange(1, 11)
factor_k5 = np.array([
# n = 5
5.0769, 3.6939, 3.2936, 3.0986, 2.9820,
2.9041, 2.8482, 2.8062, 2.7734, 2.7472,
# n = 10
3.3935, 2.8700, 2.6904, 2.5964, 2.5377,
2.4973, 2.4677, 2.4450, 2.4271, 2.4125,
# n = 26
2.6188, 2.4051, 2.3227, 2.2771, 2.2476,
2.2266, 2.2108, 2.1985, 2.1886, 2.1803,
# n = 90
2.2519, 2.1622, 2.1251, 2.1037, 2.0895,
2.0792, 2.0713, 2.0650, 2.0598, 2.0555,
# n = 200
2.1430, 2.0877, 2.0642, 2.0505, 2.0413,
2.0346, 2.0294, 2.0253, 2.0219, 2.0190,
# n = 1000
2.0362, 2.0135, 2.0037, 1.9979, 1.9939,
1.9910, 1.9888, 1.9870, 1.9855, 1.9842,
# n = infinity
1.9600, 1.9600, 1.9600, 1.9600, 1.9600,
1.9600, 1.9600, 1.9600, 1.9600, 1.9600,
])
factor_k5 = factor_k5.reshape(sample_size.size, number_of_samples.size)
class TestIsoF6(BaseTestIso.TestIsoTableF):
coverage = 0.99
confidence = 0.95
# This is n from the table.
sample_size = np.array([
3, 9, 17, 35, 100, 500, np.inf,
])
# This is m from the table.
number_of_samples = np.arange(1, 11)
factor_k5 = np.array([
# n = 3
12.6472, 6.8474, 5.5623, 4.9943, 4.6711,
4.4612, 4.3133, 4.2032, 4.1180, 4.0500,
# n = 9
4.6329, 3.8544, 3.5909, 3.4534, 3.3677,
3.3085, 3.2651, 3.2317, 3.2052, 3.1837,
# n = 17
3.7606, 3.3572, 3.2077, 3.1264, 3.0743,
3.0377, 3.0104, 2.9892, 2.9722, 2.9582,
# n = 35
3.2762, 3.0522, 2.9638, 2.9143, 2.8818,
2.8586, 2.8411, 2.8273, 2.8161, 2.8068,
# n = 100
2.9356, 2.8253, 2.7794, 2.7529, 2.7352,
2.7224, 2.7126, 2.7048, 2.6984, 2.6930,
# n = 500
2.7208, 2.6775, 2.6588, 2.6478, 2.6403,
2.6349, 2.6307, 2.6273, 2.6245, 2.6221,
# n = infinity
2.5759, 2.5759, 2.5759, 2.5759, 2.5759,
2.5759, 2.5759, 2.5759, 2.5759, 2.5759,
])
factor_k5 = factor_k5.reshape(sample_size.size, number_of_samples.size)
class TestIsoF7(BaseTestIso.TestIsoTableF):
coverage = 0.90
confidence = 0.99
# This is n from the table.
sample_size = np.array([
4, 10, 22, 80, 200, 1000, np.inf,
])
# This is m from the table.
number_of_samples = np.arange(1, 11)
factor_k5 = np.array([
# n = 4
9.4162, 4.9212, 3.9582, 3.5449, 3.3166,
3.1727, 3.0742, 3.0028, 2.9489, 2.9068,
# n = 10
3.6167, 2.8193, 2.5709, 2.4481, 2.3748,
2.3265, 2.2923, 2.2671, 2.2477, 2.2324,
# n = 22
2.5979, 2.2631, 2.1429, 2.0791, 2.0393,
2.0120, 1.9921, 1.9770, 1.9652, 1.9558,
# n = 80
2.0282, 1.9056, 1.8562, 1.8281, 1.8097,
1.7964, 1.7864, 1.7785, 1.7721, 1.7668,
# n = 200
1.8657, 1.7973, 1.7686, 1.7520, 1.7409,
1.7328, 1.7266, 1.7216, 1.7176, 1.7142,
# n = 1000
1.7359, 1.7086, 1.6967, 1.6897, 1.6850,
1.6815, 1.6788, 1.6767, 1.6749, 1.6734,
# n = infinity
1.6449, 1.6449, 1.6449, 1.6449, 1.6449,
1.6449, 1.6449, 1.6449, 1.6449, 1.6449,
])
factor_k5 = factor_k5.reshape(sample_size.size, number_of_samples.size)
class TestIsoF8(BaseTestIso.TestIsoTableF):
coverage = 0.95
confidence = 0.99
# This is n from the table.
sample_size = np.array([
2, 9, 17, 40, 150, 500, np.inf,
])
# This is m from the table.
number_of_samples = np.arange(1, 11)
factor_k5 = np.array([
# n = 2
182.7201, 23.1159, 11.9855, 8.7010, 7.1975,
6.3481, 5.8059, 5.4311, 5.1573, 4.9489,
# n = 9
4.5810, 3.4807, 3.1443, 2.9784, 2.8793,
2.8136, 2.7670, 2.7324, 2.7057, 2.6846,
# n = 17
3.3641, 2.8501, 2.6716, 2.5784, 2.5207,
2.4814, 2.4529, 2.4314, 2.4147, 2.4013,
# n = 40
2.6836, 2.4425, 2.3498, 2.2987, 2.2658,
2.2427, 2.2254, 2.2120, 2.2013, 2.1926,
# n = 150
2.2712, 2.1740, 2.1336, 2.1103, 2.0948,
2.0835, 2.0749, 2.0681, 2.0625, 2.0578,
# n = 500
2.1175, 2.0697, 2.0492, 2.0372, 2.0291,
2.0231, 2.0185, 2.0149, 2.0118, 2.0093,
# n = infinity
1.9600, 1.9600, 1.9600, 1.9600, 1.9600,
1.9600, 1.9600, 1.9600, 1.9600, 1.9600,
])
factor_k5 = factor_k5.reshape(sample_size.size, number_of_samples.size)
class TestIsoF9(BaseTestIso.TestIsoTableF):
coverage = 0.99
confidence = 0.99
# This is n from the table.
sample_size = np.array([
3, 7, 15, 28, 70, 200, 1000, np.inf,
])
# This is m from the table.
number_of_samples = np.arange(1, 11)
factor_k5 = np.array([
# n = 3
28.5857, 10.6204, 7.6599, 6.4888, 5.8628,
5.4728, 5.2065, 5.0131, 4.8663, 4.7512,
# n = 7
7.1908, 5.0656, 4.4559, 4.1605, 3.9847,
3.8678, 3.7844, 3.7220, 3.6736, 3.6350,
# n = 15
4.6212, 3.8478, 3.5825, 3.4441, 3.3581,
3.2992, 3.2564, 3.2238, 3.1983, 3.1777,
# n = 28
3.8042, 3.3792, 3.2209, 3.1350, 3.0801,
3.0418, 3.0135, 2.9916, 2.9742, 2.9600,
# n = 70
3.2284, 3.0179, 2.9334, 2.8857, 2.8544,
2.8319, 2.8150, 2.8016, 2.7908, 2.7818,
# n = 200
2.9215, 2.8144, 2.7695, 2.7434, 2.7260,
2.7133, 2.7036, 2.6958, 2.6894, 2.6841,
# n = 1000
2.7184, 2.6756, 2.6570, 2.6461, 2.6387,
2.6332, 2.6290, 2.6257, 2.6229, 2.6205,
# n = infinity
2.5759, 2.5759, 2.5759, 2.5759, 2.5759,
2.5759, 2.5759, 2.5759, 2.5759, 2.5759,
])
factor_k5 = factor_k5.reshape(sample_size.size, number_of_samples.size)
| [
"numpy.array",
"numpy.ceil",
"toleranceinterval.twoside.normal_factor",
"numpy.arange"
] | [((691, 701), 'numpy.ceil', 'np.ceil', (['x'], {}), '(x)\n', (698, 701), True, 'import numpy as np\n'), ((1478, 1526), 'numpy.array', 'np.array', (['[2, 8, 16, 35, 100, 300, 1000, np.inf]'], {}), '([2, 8, 16, 35, 100, 300, 1000, np.inf])\n', (1486, 1526), True, 'import numpy as np\n'), ((1599, 1615), 'numpy.arange', 'np.arange', (['(1)', '(11)'], {}), '(1, 11)\n', (1608, 1615), True, 'import numpy as np\n'), ((1633, 2313), 'numpy.array', 'np.array', (['[15.5124, 6.0755, 4.5088, 3.8875, 3.5544, 3.3461, 3.2032, 3.0989, 3.0193, \n 2.9565, 2.7542, 2.36, 2.2244, 2.153, 2.1081, 2.0769, 2.0539, 2.0361, \n 2.022, 2.0104, 2.2537, 2.0574, 1.9833, 1.9426, 1.9163, 1.8977, 1.8837, \n 1.8727, 1.8638, 1.8564, 1.9906, 1.8843, 1.8417, 1.8176, 1.8017, 1.7902,\n 1.7815, 1.7747, 1.769, 1.7643, 1.8232, 1.7697, 1.7473, 1.7343, 1.7256, \n 1.7193, 1.7144, 1.7105, 1.7073, 1.7047, 1.7401, 1.7118, 1.6997, 1.6925,\n 1.6877, 1.6842, 1.6815, 1.6793, 1.6775, 1.676, 1.6947, 1.68, 1.6736, \n 1.6698, 1.6672, 1.6653, 1.6639, 1.6627, 1.6617, 1.6609, 1.6449, 1.6449,\n 1.6449, 1.6449, 1.6449, 1.6449, 1.6449, 1.6449, 1.6449, 1.6449]'], {}), '([15.5124, 6.0755, 4.5088, 3.8875, 3.5544, 3.3461, 3.2032, 3.0989, \n 3.0193, 2.9565, 2.7542, 2.36, 2.2244, 2.153, 2.1081, 2.0769, 2.0539, \n 2.0361, 2.022, 2.0104, 2.2537, 2.0574, 1.9833, 1.9426, 1.9163, 1.8977, \n 1.8837, 1.8727, 1.8638, 1.8564, 1.9906, 1.8843, 1.8417, 1.8176, 1.8017,\n 1.7902, 1.7815, 1.7747, 1.769, 1.7643, 1.8232, 1.7697, 1.7473, 1.7343, \n 1.7256, 1.7193, 1.7144, 1.7105, 1.7073, 1.7047, 1.7401, 1.7118, 1.6997,\n 1.6925, 1.6877, 1.6842, 1.6815, 1.6793, 1.6775, 1.676, 1.6947, 1.68, \n 1.6736, 1.6698, 1.6672, 1.6653, 1.6639, 1.6627, 1.6617, 1.6609, 1.6449,\n 1.6449, 1.6449, 1.6449, 1.6449, 1.6449, 1.6449, 1.6449, 1.6449, 1.6449])\n', (1641, 2313), True, 'import numpy as np\n'), ((2782, 2834), 'numpy.array', 'np.array', (['[3, 9, 15, 30, 90, 150, 400, 1000, np.inf]'], {}), '([3, 9, 15, 30, 90, 150, 400, 1000, np.inf])\n', (2790, 2834), True, 'import numpy as np\n'), ((2907, 2923), 'numpy.arange', 'np.arange', (['(1)', '(11)'], {}), '(1, 11)\n', (2916, 2923), True, 'import numpy as np\n'), ((2941, 3684), 'numpy.array', 'np.array', (['[6.8233, 4.332, 3.7087, 3.4207, 3.2528, 3.142, 3.063, 3.0038, 2.9575, \n 2.9205, 3.1323, 2.7216, 2.5773, 2.5006, 2.4521, 2.4182, 2.3931, 2.3737,\n 2.3581, 2.3454, 2.7196, 2.4718, 2.3789, 2.328, 2.2951, 2.2719, 2.2545, \n 2.2408, 2.2298, 2.2206, 2.4166, 2.2749, 2.2187, 2.187, 2.1662, 2.1513, \n 2.1399, 2.1309, 2.1236, 2.1175, 2.1862, 2.1182, 2.0898, 2.0733, 2.0624,\n 2.0544, 2.0482, 2.0433, 2.0393, 2.036, 2.1276, 2.0775, 2.0563, 2.0439, \n 2.0356, 2.0296, 2.0249, 2.0212, 2.0181, 2.0155, 2.0569, 2.0282, 2.0158,\n 2.0085, 2.0035, 1.9999, 1.9971, 1.9949, 1.993, 1.9915, 2.0193, 2.0018, \n 1.9942, 1.9897, 1.9866, 1.9844, 1.9826, 1.9812, 1.98, 1.9791, 1.96, \n 1.96, 1.96, 1.96, 1.96, 1.96, 1.96, 1.96, 1.96, 1.96]'], {}), '([6.8233, 4.332, 3.7087, 3.4207, 3.2528, 3.142, 3.063, 3.0038, \n 2.9575, 2.9205, 3.1323, 2.7216, 2.5773, 2.5006, 2.4521, 2.4182, 2.3931,\n 2.3737, 2.3581, 2.3454, 2.7196, 2.4718, 2.3789, 2.328, 2.2951, 2.2719, \n 2.2545, 2.2408, 2.2298, 2.2206, 2.4166, 2.2749, 2.2187, 2.187, 2.1662, \n 2.1513, 2.1399, 2.1309, 2.1236, 2.1175, 2.1862, 2.1182, 2.0898, 2.0733,\n 2.0624, 2.0544, 2.0482, 2.0433, 2.0393, 2.036, 2.1276, 2.0775, 2.0563, \n 2.0439, 2.0356, 2.0296, 2.0249, 2.0212, 2.0181, 2.0155, 2.0569, 2.0282,\n 2.0158, 2.0085, 2.0035, 1.9999, 1.9971, 1.9949, 1.993, 1.9915, 2.0193, \n 2.0018, 1.9942, 1.9897, 1.9866, 1.9844, 1.9826, 1.9812, 1.98, 1.9791, \n 1.96, 1.96, 1.96, 1.96, 1.96, 1.96, 1.96, 1.96, 1.96, 1.96])\n', (2949, 3684), True, 'import numpy as np\n'), ((4202, 4250), 'numpy.array', 'np.array', (['[4, 8, 17, 28, 100, 300, 1000, np.inf]'], {}), '([4, 8, 17, 28, 100, 300, 1000, np.inf])\n', (4210, 4250), True, 'import numpy as np\n'), ((4323, 4339), 'numpy.arange', 'np.arange', (['(1)', '(11)'], {}), '(1, 11)\n', (4332, 4339), True, 'import numpy as np\n'), ((4357, 5038), 'numpy.array', 'np.array', (['[6.3722, 4.6643, 4.1701, 3.9277, 3.7814, 3.6825, 3.6108, 3.5562, 3.5131, \n 3.4782, 4.2707, 3.6541, 3.4408, 3.3281, 3.2572, 3.2078, 3.1712, 3.1428,\n 3.1202, 3.1016, 3.4741, 3.1819, 3.0708, 3.0095, 2.9698, 2.9416, 2.9204,\n 2.9037, 2.8902, 2.8791, 3.2023, 3.0062, 2.9286, 2.885, 2.8564, 2.8358, \n 2.8203, 2.808, 2.798, 2.7896, 2.8548, 2.771, 2.7358, 2.7155, 2.7018, \n 2.6919, 2.6843, 2.6782, 2.6732, 2.669, 2.7249, 2.6806, 2.6616, 2.6504, \n 2.6429, 2.6374, 2.6331, 2.6297, 2.6269, 2.6245, 2.6538, 2.6308, 2.6208,\n 2.6148, 2.6108, 2.6079, 2.6056, 2.6037, 2.6022, 2.6009, 2.5759, 2.5759,\n 2.5759, 2.5759, 2.5759, 2.5759, 2.5759, 2.5759, 2.5759, 2.5759]'], {}), '([6.3722, 4.6643, 4.1701, 3.9277, 3.7814, 3.6825, 3.6108, 3.5562, \n 3.5131, 3.4782, 4.2707, 3.6541, 3.4408, 3.3281, 3.2572, 3.2078, 3.1712,\n 3.1428, 3.1202, 3.1016, 3.4741, 3.1819, 3.0708, 3.0095, 2.9698, 2.9416,\n 2.9204, 2.9037, 2.8902, 2.8791, 3.2023, 3.0062, 2.9286, 2.885, 2.8564, \n 2.8358, 2.8203, 2.808, 2.798, 2.7896, 2.8548, 2.771, 2.7358, 2.7155, \n 2.7018, 2.6919, 2.6843, 2.6782, 2.6732, 2.669, 2.7249, 2.6806, 2.6616, \n 2.6504, 2.6429, 2.6374, 2.6331, 2.6297, 2.6269, 2.6245, 2.6538, 2.6308,\n 2.6208, 2.6148, 2.6108, 2.6079, 2.6056, 2.6037, 2.6022, 2.6009, 2.5759,\n 2.5759, 2.5759, 2.5759, 2.5759, 2.5759, 2.5759, 2.5759, 2.5759, 2.5759])\n', (4365, 5038), True, 'import numpy as np\n'), ((5505, 5553), 'numpy.array', 'np.array', (['[2, 8, 16, 35, 150, 500, 1000, np.inf]'], {}), '([2, 8, 16, 35, 150, 500, 1000, np.inf])\n', (5513, 5553), True, 'import numpy as np\n'), ((5626, 5642), 'numpy.arange', 'np.arange', (['(1)', '(11)'], {}), '(1, 11)\n', (5635, 5642), True, 'import numpy as np\n'), ((5660, 6341), 'numpy.array', 'np.array', (['[31.0923, 8.7252, 5.838, 4.7912, 4.2571, 3.9341, 3.7179, 3.563, 3.4468, \n 3.3565, 3.1561, 2.5818, 2.3937, 2.2974, 2.2381, 2.1978, 2.1685, 2.1463,\n 2.1289, 2.1149, 2.4486, 2.1771, 2.0777, 2.0241, 1.9899, 1.9661, 1.9483,\n 1.9346, 1.9237, 1.9147, 2.0943, 1.9515, 1.8953, 1.8638, 1.8432, 1.8285,\n 1.8174, 1.8087, 1.8016, 1.7957, 1.826, 1.771, 1.7478, 1.7344, 1.7254, \n 1.7188, 1.7137, 1.7097, 1.7064, 1.7036, 1.7374, 1.7098, 1.6979, 1.6908,\n 1.6861, 1.6826, 1.6799, 1.6777, 1.676, 1.6744, 1.7088, 1.6898, 1.6816, \n 1.6767, 1.6734, 1.6709, 1.669, 1.6675, 1.6663, 1.6652, 1.6449, 1.6449, \n 1.6449, 1.6449, 1.6449, 1.6449, 1.6449, 1.6449, 1.6449, 1.6449]'], {}), '([31.0923, 8.7252, 5.838, 4.7912, 4.2571, 3.9341, 3.7179, 3.563, \n 3.4468, 3.3565, 3.1561, 2.5818, 2.3937, 2.2974, 2.2381, 2.1978, 2.1685,\n 2.1463, 2.1289, 2.1149, 2.4486, 2.1771, 2.0777, 2.0241, 1.9899, 1.9661,\n 1.9483, 1.9346, 1.9237, 1.9147, 2.0943, 1.9515, 1.8953, 1.8638, 1.8432,\n 1.8285, 1.8174, 1.8087, 1.8016, 1.7957, 1.826, 1.771, 1.7478, 1.7344, \n 1.7254, 1.7188, 1.7137, 1.7097, 1.7064, 1.7036, 1.7374, 1.7098, 1.6979,\n 1.6908, 1.6861, 1.6826, 1.6799, 1.6777, 1.676, 1.6744, 1.7088, 1.6898, \n 1.6816, 1.6767, 1.6734, 1.6709, 1.669, 1.6675, 1.6663, 1.6652, 1.6449, \n 1.6449, 1.6449, 1.6449, 1.6449, 1.6449, 1.6449, 1.6449, 1.6449, 1.6449])\n', (5668, 6341), True, 'import numpy as np\n'), ((6809, 6853), 'numpy.array', 'np.array', (['[5, 10, 26, 90, 200, 1000, np.inf]'], {}), '([5, 10, 26, 90, 200, 1000, np.inf])\n', (6817, 6853), True, 'import numpy as np\n'), ((6926, 6942), 'numpy.arange', 'np.arange', (['(1)', '(11)'], {}), '(1, 11)\n', (6935, 6942), True, 'import numpy as np\n'), ((6960, 7534), 'numpy.array', 'np.array', (['[5.0769, 3.6939, 3.2936, 3.0986, 2.982, 2.9041, 2.8482, 2.8062, 2.7734, \n 2.7472, 3.3935, 2.87, 2.6904, 2.5964, 2.5377, 2.4973, 2.4677, 2.445, \n 2.4271, 2.4125, 2.6188, 2.4051, 2.3227, 2.2771, 2.2476, 2.2266, 2.2108,\n 2.1985, 2.1886, 2.1803, 2.2519, 2.1622, 2.1251, 2.1037, 2.0895, 2.0792,\n 2.0713, 2.065, 2.0598, 2.0555, 2.143, 2.0877, 2.0642, 2.0505, 2.0413, \n 2.0346, 2.0294, 2.0253, 2.0219, 2.019, 2.0362, 2.0135, 2.0037, 1.9979, \n 1.9939, 1.991, 1.9888, 1.987, 1.9855, 1.9842, 1.96, 1.96, 1.96, 1.96, \n 1.96, 1.96, 1.96, 1.96, 1.96, 1.96]'], {}), '([5.0769, 3.6939, 3.2936, 3.0986, 2.982, 2.9041, 2.8482, 2.8062, \n 2.7734, 2.7472, 3.3935, 2.87, 2.6904, 2.5964, 2.5377, 2.4973, 2.4677, \n 2.445, 2.4271, 2.4125, 2.6188, 2.4051, 2.3227, 2.2771, 2.2476, 2.2266, \n 2.2108, 2.1985, 2.1886, 2.1803, 2.2519, 2.1622, 2.1251, 2.1037, 2.0895,\n 2.0792, 2.0713, 2.065, 2.0598, 2.0555, 2.143, 2.0877, 2.0642, 2.0505, \n 2.0413, 2.0346, 2.0294, 2.0253, 2.0219, 2.019, 2.0362, 2.0135, 2.0037, \n 1.9979, 1.9939, 1.991, 1.9888, 1.987, 1.9855, 1.9842, 1.96, 1.96, 1.96,\n 1.96, 1.96, 1.96, 1.96, 1.96, 1.96, 1.96])\n', (6968, 7534), True, 'import numpy as np\n'), ((7995, 8037), 'numpy.array', 'np.array', (['[3, 9, 17, 35, 100, 500, np.inf]'], {}), '([3, 9, 17, 35, 100, 500, np.inf])\n', (8003, 8037), True, 'import numpy as np\n'), ((8110, 8126), 'numpy.arange', 'np.arange', (['(1)', '(11)'], {}), '(1, 11)\n', (8119, 8126), True, 'import numpy as np\n'), ((8144, 8742), 'numpy.array', 'np.array', (['[12.6472, 6.8474, 5.5623, 4.9943, 4.6711, 4.4612, 4.3133, 4.2032, 4.118, \n 4.05, 4.6329, 3.8544, 3.5909, 3.4534, 3.3677, 3.3085, 3.2651, 3.2317, \n 3.2052, 3.1837, 3.7606, 3.3572, 3.2077, 3.1264, 3.0743, 3.0377, 3.0104,\n 2.9892, 2.9722, 2.9582, 3.2762, 3.0522, 2.9638, 2.9143, 2.8818, 2.8586,\n 2.8411, 2.8273, 2.8161, 2.8068, 2.9356, 2.8253, 2.7794, 2.7529, 2.7352,\n 2.7224, 2.7126, 2.7048, 2.6984, 2.693, 2.7208, 2.6775, 2.6588, 2.6478, \n 2.6403, 2.6349, 2.6307, 2.6273, 2.6245, 2.6221, 2.5759, 2.5759, 2.5759,\n 2.5759, 2.5759, 2.5759, 2.5759, 2.5759, 2.5759, 2.5759]'], {}), '([12.6472, 6.8474, 5.5623, 4.9943, 4.6711, 4.4612, 4.3133, 4.2032, \n 4.118, 4.05, 4.6329, 3.8544, 3.5909, 3.4534, 3.3677, 3.3085, 3.2651, \n 3.2317, 3.2052, 3.1837, 3.7606, 3.3572, 3.2077, 3.1264, 3.0743, 3.0377,\n 3.0104, 2.9892, 2.9722, 2.9582, 3.2762, 3.0522, 2.9638, 2.9143, 2.8818,\n 2.8586, 2.8411, 2.8273, 2.8161, 2.8068, 2.9356, 2.8253, 2.7794, 2.7529,\n 2.7352, 2.7224, 2.7126, 2.7048, 2.6984, 2.693, 2.7208, 2.6775, 2.6588, \n 2.6478, 2.6403, 2.6349, 2.6307, 2.6273, 2.6245, 2.6221, 2.5759, 2.5759,\n 2.5759, 2.5759, 2.5759, 2.5759, 2.5759, 2.5759, 2.5759, 2.5759])\n', (8152, 8742), True, 'import numpy as np\n'), ((9178, 9222), 'numpy.array', 'np.array', (['[4, 10, 22, 80, 200, 1000, np.inf]'], {}), '([4, 10, 22, 80, 200, 1000, np.inf])\n', (9186, 9222), True, 'import numpy as np\n'), ((9295, 9311), 'numpy.arange', 'np.arange', (['(1)', '(11)'], {}), '(1, 11)\n', (9304, 9311), True, 'import numpy as np\n'), ((9329, 9928), 'numpy.array', 'np.array', (['[9.4162, 4.9212, 3.9582, 3.5449, 3.3166, 3.1727, 3.0742, 3.0028, 2.9489, \n 2.9068, 3.6167, 2.8193, 2.5709, 2.4481, 2.3748, 2.3265, 2.2923, 2.2671,\n 2.2477, 2.2324, 2.5979, 2.2631, 2.1429, 2.0791, 2.0393, 2.012, 1.9921, \n 1.977, 1.9652, 1.9558, 2.0282, 1.9056, 1.8562, 1.8281, 1.8097, 1.7964, \n 1.7864, 1.7785, 1.7721, 1.7668, 1.8657, 1.7973, 1.7686, 1.752, 1.7409, \n 1.7328, 1.7266, 1.7216, 1.7176, 1.7142, 1.7359, 1.7086, 1.6967, 1.6897,\n 1.685, 1.6815, 1.6788, 1.6767, 1.6749, 1.6734, 1.6449, 1.6449, 1.6449, \n 1.6449, 1.6449, 1.6449, 1.6449, 1.6449, 1.6449, 1.6449]'], {}), '([9.4162, 4.9212, 3.9582, 3.5449, 3.3166, 3.1727, 3.0742, 3.0028, \n 2.9489, 2.9068, 3.6167, 2.8193, 2.5709, 2.4481, 2.3748, 2.3265, 2.2923,\n 2.2671, 2.2477, 2.2324, 2.5979, 2.2631, 2.1429, 2.0791, 2.0393, 2.012, \n 1.9921, 1.977, 1.9652, 1.9558, 2.0282, 1.9056, 1.8562, 1.8281, 1.8097, \n 1.7964, 1.7864, 1.7785, 1.7721, 1.7668, 1.8657, 1.7973, 1.7686, 1.752, \n 1.7409, 1.7328, 1.7266, 1.7216, 1.7176, 1.7142, 1.7359, 1.7086, 1.6967,\n 1.6897, 1.685, 1.6815, 1.6788, 1.6767, 1.6749, 1.6734, 1.6449, 1.6449, \n 1.6449, 1.6449, 1.6449, 1.6449, 1.6449, 1.6449, 1.6449, 1.6449])\n', (9337, 9928), True, 'import numpy as np\n'), ((10364, 10406), 'numpy.array', 'np.array', (['[2, 9, 17, 40, 150, 500, np.inf]'], {}), '([2, 9, 17, 40, 150, 500, np.inf])\n', (10372, 10406), True, 'import numpy as np\n'), ((10479, 10495), 'numpy.arange', 'np.arange', (['(1)', '(11)'], {}), '(1, 11)\n', (10488, 10495), True, 'import numpy as np\n'), ((10513, 11093), 'numpy.array', 'np.array', (['[182.7201, 23.1159, 11.9855, 8.701, 7.1975, 6.3481, 5.8059, 5.4311, 5.1573,\n 4.9489, 4.581, 3.4807, 3.1443, 2.9784, 2.8793, 2.8136, 2.767, 2.7324, \n 2.7057, 2.6846, 3.3641, 2.8501, 2.6716, 2.5784, 2.5207, 2.4814, 2.4529,\n 2.4314, 2.4147, 2.4013, 2.6836, 2.4425, 2.3498, 2.2987, 2.2658, 2.2427,\n 2.2254, 2.212, 2.2013, 2.1926, 2.2712, 2.174, 2.1336, 2.1103, 2.0948, \n 2.0835, 2.0749, 2.0681, 2.0625, 2.0578, 2.1175, 2.0697, 2.0492, 2.0372,\n 2.0291, 2.0231, 2.0185, 2.0149, 2.0118, 2.0093, 1.96, 1.96, 1.96, 1.96,\n 1.96, 1.96, 1.96, 1.96, 1.96, 1.96]'], {}), '([182.7201, 23.1159, 11.9855, 8.701, 7.1975, 6.3481, 5.8059, 5.4311,\n 5.1573, 4.9489, 4.581, 3.4807, 3.1443, 2.9784, 2.8793, 2.8136, 2.767, \n 2.7324, 2.7057, 2.6846, 3.3641, 2.8501, 2.6716, 2.5784, 2.5207, 2.4814,\n 2.4529, 2.4314, 2.4147, 2.4013, 2.6836, 2.4425, 2.3498, 2.2987, 2.2658,\n 2.2427, 2.2254, 2.212, 2.2013, 2.1926, 2.2712, 2.174, 2.1336, 2.1103, \n 2.0948, 2.0835, 2.0749, 2.0681, 2.0625, 2.0578, 2.1175, 2.0697, 2.0492,\n 2.0372, 2.0291, 2.0231, 2.0185, 2.0149, 2.0118, 2.0093, 1.96, 1.96, \n 1.96, 1.96, 1.96, 1.96, 1.96, 1.96, 1.96, 1.96])\n', (10521, 11093), True, 'import numpy as np\n'), ((11550, 11597), 'numpy.array', 'np.array', (['[3, 7, 15, 28, 70, 200, 1000, np.inf]'], {}), '([3, 7, 15, 28, 70, 200, 1000, np.inf])\n', (11558, 11597), True, 'import numpy as np\n'), ((11670, 11686), 'numpy.arange', 'np.arange', (['(1)', '(11)'], {}), '(1, 11)\n', (11679, 11686), True, 'import numpy as np\n'), ((11704, 12385), 'numpy.array', 'np.array', (['[28.5857, 10.6204, 7.6599, 6.4888, 5.8628, 5.4728, 5.2065, 5.0131, 4.8663, \n 4.7512, 7.1908, 5.0656, 4.4559, 4.1605, 3.9847, 3.8678, 3.7844, 3.722, \n 3.6736, 3.635, 4.6212, 3.8478, 3.5825, 3.4441, 3.3581, 3.2992, 3.2564, \n 3.2238, 3.1983, 3.1777, 3.8042, 3.3792, 3.2209, 3.135, 3.0801, 3.0418, \n 3.0135, 2.9916, 2.9742, 2.96, 3.2284, 3.0179, 2.9334, 2.8857, 2.8544, \n 2.8319, 2.815, 2.8016, 2.7908, 2.7818, 2.9215, 2.8144, 2.7695, 2.7434, \n 2.726, 2.7133, 2.7036, 2.6958, 2.6894, 2.6841, 2.7184, 2.6756, 2.657, \n 2.6461, 2.6387, 2.6332, 2.629, 2.6257, 2.6229, 2.6205, 2.5759, 2.5759, \n 2.5759, 2.5759, 2.5759, 2.5759, 2.5759, 2.5759, 2.5759, 2.5759]'], {}), '([28.5857, 10.6204, 7.6599, 6.4888, 5.8628, 5.4728, 5.2065, 5.0131,\n 4.8663, 4.7512, 7.1908, 5.0656, 4.4559, 4.1605, 3.9847, 3.8678, 3.7844,\n 3.722, 3.6736, 3.635, 4.6212, 3.8478, 3.5825, 3.4441, 3.3581, 3.2992, \n 3.2564, 3.2238, 3.1983, 3.1777, 3.8042, 3.3792, 3.2209, 3.135, 3.0801, \n 3.0418, 3.0135, 2.9916, 2.9742, 2.96, 3.2284, 3.0179, 2.9334, 2.8857, \n 2.8544, 2.8319, 2.815, 2.8016, 2.7908, 2.7818, 2.9215, 2.8144, 2.7695, \n 2.7434, 2.726, 2.7133, 2.7036, 2.6958, 2.6894, 2.6841, 2.7184, 2.6756, \n 2.657, 2.6461, 2.6387, 2.6332, 2.629, 2.6257, 2.6229, 2.6205, 2.5759, \n 2.5759, 2.5759, 2.5759, 2.5759, 2.5759, 2.5759, 2.5759, 2.5759, 2.5759])\n', (11712, 12385), True, 'import numpy as np\n'), ((979, 1109), 'toleranceinterval.twoside.normal_factor', 'ts.normal_factor', (['self.sample_size[row_idx]', 'self.coverage', 'self.confidence'], {'method': '"""exact"""', 'm': 'self.number_of_samples[col_idx]'}), "(self.sample_size[row_idx], self.coverage, self.confidence,\n method='exact', m=self.number_of_samples[col_idx])\n", (995, 1109), True, 'import toleranceinterval.twoside as ts\n')] |
#!/usr/bin/env python
# coding: utf-8
import matplotlib.pyplot as plt
import matplotlib.pylab as pylab
import requests
from io import BytesIO
from PIL import Image
import numpy as np
from maskrcnn_benchmark.config import cfg
from predictor import COCODemo
config_file = "../configs/e2e_mask_rcnn_R_50_FPN_1x_synthia.yaml"
# update the config options with the config file
cfg.merge_from_file(config_file)
# manual override some options
cfg.merge_from_list(["MODEL.DEVICE", "cuda"])
# Now we create the `COCODemo` object. It contains a few extra options for conveniency, such as the confidence threshold for detections to be shown.
# In[5]:
coco_demo = COCODemo(
cfg,
min_image_size=720,
confidence_threshold=0.7,
)
# Let's define a few helper functions for loading images from a URL
# In[6]:
def load(url):
"""
Given an url of an image, downloads the image and
returns a PIL image
"""
response = requests.get(url)
pil_image = Image.open(BytesIO(response.content)).convert("RGB")
# convert to BGR format
image = np.array(pil_image)[:, :, [2, 1, 0]]
return image
def imshow(img):
plt.imshow(img[:, :, [2, 1, 0]])
plt.axis("off")
plt.show()
# Let's now load an image from the COCO dataset. It's reference is in the comment
# In[11]:
# from http://cocodataset.org/#explore?id=345434
# ### Computing the predictions
#
# We provide a `run_on_opencv_image` function, which takes an image as it was loaded by OpenCV (in `BGR` format), and computes the predictions on them, returning an image with the predictions overlayed on the image.
# In[8]:
import cv2
image = cv2.imread('000010.png')
# In[12]:
#image = load("http://farm3.staticflickr.com/2469/3915380994_2e611b1779_z.jpg")
#imshow(image)
# compute predictions
predictions = coco_demo.run_on_opencv_image(image)
imshow(predictions)
| [
"matplotlib.pyplot.imshow",
"maskrcnn_benchmark.config.cfg.merge_from_file",
"io.BytesIO",
"maskrcnn_benchmark.config.cfg.merge_from_list",
"requests.get",
"numpy.array",
"predictor.COCODemo",
"matplotlib.pyplot.axis",
"cv2.imread",
"matplotlib.pyplot.show"
] | [((376, 408), 'maskrcnn_benchmark.config.cfg.merge_from_file', 'cfg.merge_from_file', (['config_file'], {}), '(config_file)\n', (395, 408), False, 'from maskrcnn_benchmark.config import cfg\n'), ((440, 485), 'maskrcnn_benchmark.config.cfg.merge_from_list', 'cfg.merge_from_list', (["['MODEL.DEVICE', 'cuda']"], {}), "(['MODEL.DEVICE', 'cuda'])\n", (459, 485), False, 'from maskrcnn_benchmark.config import cfg\n'), ((661, 720), 'predictor.COCODemo', 'COCODemo', (['cfg'], {'min_image_size': '(720)', 'confidence_threshold': '(0.7)'}), '(cfg, min_image_size=720, confidence_threshold=0.7)\n', (669, 720), False, 'from predictor import COCODemo\n'), ((1644, 1668), 'cv2.imread', 'cv2.imread', (['"""000010.png"""'], {}), "('000010.png')\n", (1654, 1668), False, 'import cv2\n'), ((942, 959), 'requests.get', 'requests.get', (['url'], {}), '(url)\n', (954, 959), False, 'import requests\n'), ((1145, 1177), 'matplotlib.pyplot.imshow', 'plt.imshow', (['img[:, :, [2, 1, 0]]'], {}), '(img[:, :, [2, 1, 0]])\n', (1155, 1177), True, 'import matplotlib.pyplot as plt\n'), ((1182, 1197), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (1190, 1197), True, 'import matplotlib.pyplot as plt\n'), ((1202, 1212), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1210, 1212), True, 'import matplotlib.pyplot as plt\n'), ((1069, 1088), 'numpy.array', 'np.array', (['pil_image'], {}), '(pil_image)\n', (1077, 1088), True, 'import numpy as np\n'), ((987, 1012), 'io.BytesIO', 'BytesIO', (['response.content'], {}), '(response.content)\n', (994, 1012), False, 'from io import BytesIO\n')] |
import cv2
import numpy as np
import os
import random
# Mars surface image (Curiosity rover) labeled data set
def ffzk(input_dir):
imgname_array=[];input_dir=input_dir.strip("\"\'")
for fd_path, _, sb_file in os.walk(input_dir):
for fil in sb_file:imgname_array.append(fd_path.replace('\\','/') + '/' + fil)
if os.path.isfile(input_dir):imgname_array.append(input_dir.replace('\\','/'))
return imgname_array
lfw=ffzk(os.path.join("./datasets/calibrated"))
os.makedirs("./datasets/mls",exist_ok=True)
os.makedirs("./datasets/mls",exist_ok=True)
for i,v in enumerate(lfw):
myimg = cv2.imread(v)
_height, _width, _channels =myimg.shape[:3]
if(_height<129 or _width<129):
continue
avg_color = np.average( np.average(myimg, axis=0), axis=0)
if(avg_color[2]>avg_color[1]*1.2 and avg_color[2]>avg_color[0]*1.2 and avg_color[2]>120):
cv2.imwrite("./datasets/mls/"+str(random.randrange(0, 1000000))+".png",myimg)
else:
cv2.imwrite("./datasets/mls/"+str(i)+".png",myimg)
| [
"os.makedirs",
"numpy.average",
"random.randrange",
"os.path.join",
"os.path.isfile",
"cv2.imread",
"os.walk"
] | [((483, 527), 'os.makedirs', 'os.makedirs', (['"""./datasets/mls"""'], {'exist_ok': '(True)'}), "('./datasets/mls', exist_ok=True)\n", (494, 527), False, 'import os\n'), ((527, 571), 'os.makedirs', 'os.makedirs', (['"""./datasets/mls"""'], {'exist_ok': '(True)'}), "('./datasets/mls', exist_ok=True)\n", (538, 571), False, 'import os\n'), ((218, 236), 'os.walk', 'os.walk', (['input_dir'], {}), '(input_dir)\n', (225, 236), False, 'import os\n'), ((332, 357), 'os.path.isfile', 'os.path.isfile', (['input_dir'], {}), '(input_dir)\n', (346, 357), False, 'import os\n'), ((443, 480), 'os.path.join', 'os.path.join', (['"""./datasets/calibrated"""'], {}), "('./datasets/calibrated')\n", (455, 480), False, 'import os\n'), ((610, 623), 'cv2.imread', 'cv2.imread', (['v'], {}), '(v)\n', (620, 623), False, 'import cv2\n'), ((762, 787), 'numpy.average', 'np.average', (['myimg'], {'axis': '(0)'}), '(myimg, axis=0)\n', (772, 787), True, 'import numpy as np\n'), ((933, 961), 'random.randrange', 'random.randrange', (['(0)', '(1000000)'], {}), '(0, 1000000)\n', (949, 961), False, 'import random\n')] |
#!/usr/bin/env python
# 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.
# pylint: skip-file
import sys
sys.path.insert(0, "../../python/")
import mxnet as mx
import numpy as np
import numpy.random as rnd
import time
def check_diff_to_scalar(A, x, rank=None):
""" assert A == x"""
assert(np.sum(np.abs((A - x).asnumpy())) == 0), (rank, A.asnumpy(), x)
# setup
keys = ['3', '5', '7']
rsp_keys = ['9', '11', '13']
rate = 2
shape = (2, 3)
big_shape = (1200, 1200) # bigger than BIGARRAY_BOUND
def init_kv():
kv = mx.kv.create('dist_sync')
# init kv dns keys
kv.init(keys, [mx.nd.ones(shape)] * len(keys))
kv.init('99', mx.nd.ones(big_shape))
# init kv row_sparse keys
kv.init(rsp_keys, [mx.nd.ones(shape).tostype('row_sparse')] * len(rsp_keys))
kv.init('100', mx.nd.ones(big_shape).tostype('row_sparse'))
# worker info
my_rank = kv.rank
nworker = kv.num_workers
# init updater on servers
kv.set_optimizer(mx.optimizer.create('test', rescale_grad=rate))
return kv, my_rank, nworker
def test_sync_push_pull():
kv, my_rank, nworker = init_kv()
def check_default_keys(kv, my_rank, nworker):
nrepeat = 3
for i in range(nrepeat):
kv.push('3', mx.nd.ones(shape)*(my_rank+1))
kv.push('99', mx.nd.ones(big_shape)*(my_rank+1))
num = (nworker + 1) * nworker * rate / 2 * nrepeat + 1
val = mx.nd.zeros(shape)
kv.pull('3', out=val)
check_diff_to_scalar(val, num)
val2 = mx.nd.zeros(big_shape)
kv.pull('99', out=val2)
check_diff_to_scalar(val2, num)
def check_row_sparse_keys(kv, my_rank, nworker):
nrepeat = 3
# prepare gradient
v = mx.nd.zeros(shape)
my_row = my_rank % shape[0]
v[my_row] = my_rank + 1
# push
for i in range(nrepeat):
kv.push('9', v.tostype('row_sparse'))
# select a random subset of rows this worker is interested in
num_rows = shape[0]
row_ids_np = np.random.randint(num_rows, size=num_rows)
row_ids = mx.nd.array(row_ids_np, dtype='int64')
# perform pull
val = mx.nd.zeros(shape, stype='row_sparse')
kv.row_sparse_pull('9', out=val, row_ids=row_ids)
# prepare updated values
updated_val = mx.nd.ones(shape)
for rank in range(nworker):
row = rank % shape[0]
updated_val[row] += (rank + 1) * rate * nrepeat
# verify subset of updated values
expected = mx.nd.zeros(shape)
for row in row_ids_np:
expected[row] = updated_val[row]
check_diff_to_scalar(val, expected)
def check_row_sparse_keys_with_zeros(kv, my_rank, nworker):
nrepeat = 3
# prepare gradient
v = mx.nd.zeros(shape)
big_v = mx.nd.zeros(big_shape)
# push
for i in range(nrepeat):
kv.push('11', v.tostype('row_sparse'))
kv.push('100', big_v.tostype('row_sparse'))
# pull a subset of rows this worker is interested in
all_row_ids = np.arange(shape[0])
val = mx.nd.ones(shape).tostype('row_sparse')
big_val = mx.nd.ones(big_shape).tostype('row_sparse')
kv.row_sparse_pull('11', out=val, row_ids=mx.nd.array(all_row_ids, dtype='int64'))
big_num_rows = shape[0]
big_all_row_ids = np.arange(big_shape[0])
kv.row_sparse_pull('100', out=big_val, row_ids=mx.nd.array(big_all_row_ids, dtype='int64'))
# verify results
check_diff_to_scalar(val, mx.nd.ones(shape))
check_diff_to_scalar(big_val, mx.nd.ones(big_shape))
def check_big_row_sparse_keys(kv, my_rank, nworker):
mx.random.seed(123)
rnd.seed(123)
density = 0.3
nrepeat = 3
# prepare gradient
v = mx.nd.zeros(big_shape)
idx_sample = rnd.rand(big_shape[0])
indices = np.argwhere(idx_sample < density).flatten()
# each worker chooses a subset of the indices to update
update_rows = []
for rank in range(nworker):
rows = []
i = 0
step = (rank + 1) * 2
while i < len(indices):
rows.append(indices[i])
i += step
update_rows.append(np.array(rows))
# rows to update for this worker
for row in update_rows[my_rank]:
v[row] = my_rank + 1
# push
for i in range(nrepeat):
kv.push('100', v.tostype('row_sparse'))
# select a random subset of rows this worker is interested in
mx.random.seed(my_rank)
rnd.seed(my_rank)
num_rows = big_shape[0]
row_ids_np = np.random.randint(num_rows, size=num_rows)
row_ids = mx.nd.array(row_ids_np, dtype='int64')
# perform pull
val = mx.nd.zeros(big_shape, stype='row_sparse')
kv.row_sparse_pull('100', out=val, row_ids=row_ids)
# prepare expected result
updated_val = mx.nd.ones(big_shape)
# apply updates from each worker
for rank in range(nworker):
for row in update_rows[rank]:
updated_val[row] += (rank + 1) * rate * nrepeat
expected = mx.nd.zeros(big_shape)
for row in row_ids_np:
expected[row] = updated_val[row]
check_diff_to_scalar(val, expected, rank=my_rank)
check_default_keys(kv, my_rank, nworker)
check_row_sparse_keys(kv, my_rank, nworker)
check_row_sparse_keys_with_zeros(kv, my_rank, nworker)
check_big_row_sparse_keys(kv, my_rank, nworker)
print('worker ' + str(my_rank) + ' is done')
if __name__ == "__main__":
test_sync_push_pull()
| [
"sys.path.insert",
"numpy.random.rand",
"mxnet.nd.zeros",
"mxnet.nd.ones",
"numpy.arange",
"numpy.array",
"numpy.random.randint",
"numpy.argwhere",
"mxnet.kv.create",
"numpy.random.seed",
"mxnet.random.seed",
"mxnet.optimizer.create",
"mxnet.nd.array"
] | [((840, 875), 'sys.path.insert', 'sys.path.insert', (['(0)', '"""../../python/"""'], {}), "(0, '../../python/')\n", (855, 875), False, 'import sys\n'), ((1270, 1295), 'mxnet.kv.create', 'mx.kv.create', (['"""dist_sync"""'], {}), "('dist_sync')\n", (1282, 1295), True, 'import mxnet as mx\n'), ((1388, 1409), 'mxnet.nd.ones', 'mx.nd.ones', (['big_shape'], {}), '(big_shape)\n', (1398, 1409), True, 'import mxnet as mx\n'), ((1706, 1752), 'mxnet.optimizer.create', 'mx.optimizer.create', (['"""test"""'], {'rescale_grad': 'rate'}), "('test', rescale_grad=rate)\n", (1725, 1752), True, 'import mxnet as mx\n'), ((2149, 2167), 'mxnet.nd.zeros', 'mx.nd.zeros', (['shape'], {}), '(shape)\n', (2160, 2167), True, 'import mxnet as mx\n'), ((2253, 2275), 'mxnet.nd.zeros', 'mx.nd.zeros', (['big_shape'], {}), '(big_shape)\n', (2264, 2275), True, 'import mxnet as mx\n'), ((2461, 2479), 'mxnet.nd.zeros', 'mx.nd.zeros', (['shape'], {}), '(shape)\n', (2472, 2479), True, 'import mxnet as mx\n'), ((2765, 2807), 'numpy.random.randint', 'np.random.randint', (['num_rows'], {'size': 'num_rows'}), '(num_rows, size=num_rows)\n', (2782, 2807), True, 'import numpy as np\n'), ((2826, 2864), 'mxnet.nd.array', 'mx.nd.array', (['row_ids_np'], {'dtype': '"""int64"""'}), "(row_ids_np, dtype='int64')\n", (2837, 2864), True, 'import mxnet as mx\n'), ((2902, 2940), 'mxnet.nd.zeros', 'mx.nd.zeros', (['shape'], {'stype': '"""row_sparse"""'}), "(shape, stype='row_sparse')\n", (2913, 2940), True, 'import mxnet as mx\n'), ((3054, 3071), 'mxnet.nd.ones', 'mx.nd.ones', (['shape'], {}), '(shape)\n', (3064, 3071), True, 'import mxnet as mx\n'), ((3263, 3281), 'mxnet.nd.zeros', 'mx.nd.zeros', (['shape'], {}), '(shape)\n', (3274, 3281), True, 'import mxnet as mx\n'), ((3526, 3544), 'mxnet.nd.zeros', 'mx.nd.zeros', (['shape'], {}), '(shape)\n', (3537, 3544), True, 'import mxnet as mx\n'), ((3561, 3583), 'mxnet.nd.zeros', 'mx.nd.zeros', (['big_shape'], {}), '(big_shape)\n', (3572, 3583), True, 'import mxnet as mx\n'), ((3823, 3842), 'numpy.arange', 'np.arange', (['shape[0]'], {}), '(shape[0])\n', (3832, 3842), True, 'import numpy as np\n'), ((4108, 4131), 'numpy.arange', 'np.arange', (['big_shape[0]'], {}), '(big_shape[0])\n', (4117, 4131), True, 'import numpy as np\n'), ((4437, 4456), 'mxnet.random.seed', 'mx.random.seed', (['(123)'], {}), '(123)\n', (4451, 4456), True, 'import mxnet as mx\n'), ((4465, 4478), 'numpy.random.seed', 'rnd.seed', (['(123)'], {}), '(123)\n', (4473, 4478), True, 'import numpy.random as rnd\n'), ((4560, 4582), 'mxnet.nd.zeros', 'mx.nd.zeros', (['big_shape'], {}), '(big_shape)\n', (4571, 4582), True, 'import mxnet as mx\n'), ((4604, 4626), 'numpy.random.rand', 'rnd.rand', (['big_shape[0]'], {}), '(big_shape[0])\n', (4612, 4626), True, 'import numpy.random as rnd\n'), ((5331, 5354), 'mxnet.random.seed', 'mx.random.seed', (['my_rank'], {}), '(my_rank)\n', (5345, 5354), True, 'import mxnet as mx\n'), ((5363, 5380), 'numpy.random.seed', 'rnd.seed', (['my_rank'], {}), '(my_rank)\n', (5371, 5380), True, 'import numpy.random as rnd\n'), ((5434, 5476), 'numpy.random.randint', 'np.random.randint', (['num_rows'], {'size': 'num_rows'}), '(num_rows, size=num_rows)\n', (5451, 5476), True, 'import numpy as np\n'), ((5495, 5533), 'mxnet.nd.array', 'mx.nd.array', (['row_ids_np'], {'dtype': '"""int64"""'}), "(row_ids_np, dtype='int64')\n", (5506, 5533), True, 'import mxnet as mx\n'), ((5571, 5613), 'mxnet.nd.zeros', 'mx.nd.zeros', (['big_shape'], {'stype': '"""row_sparse"""'}), "(big_shape, stype='row_sparse')\n", (5582, 5613), True, 'import mxnet as mx\n'), ((5730, 5751), 'mxnet.nd.ones', 'mx.nd.ones', (['big_shape'], {}), '(big_shape)\n', (5740, 5751), True, 'import mxnet as mx\n'), ((5955, 5977), 'mxnet.nd.zeros', 'mx.nd.zeros', (['big_shape'], {}), '(big_shape)\n', (5966, 5977), True, 'import mxnet as mx\n'), ((4291, 4308), 'mxnet.nd.ones', 'mx.nd.ones', (['shape'], {}), '(shape)\n', (4301, 4308), True, 'import mxnet as mx\n'), ((4348, 4369), 'mxnet.nd.ones', 'mx.nd.ones', (['big_shape'], {}), '(big_shape)\n', (4358, 4369), True, 'import mxnet as mx\n'), ((1338, 1355), 'mxnet.nd.ones', 'mx.nd.ones', (['shape'], {}), '(shape)\n', (1348, 1355), True, 'import mxnet as mx\n'), ((1541, 1562), 'mxnet.nd.ones', 'mx.nd.ones', (['big_shape'], {}), '(big_shape)\n', (1551, 1562), True, 'import mxnet as mx\n'), ((3857, 3874), 'mxnet.nd.ones', 'mx.nd.ones', (['shape'], {}), '(shape)\n', (3867, 3874), True, 'import mxnet as mx\n'), ((3915, 3936), 'mxnet.nd.ones', 'mx.nd.ones', (['big_shape'], {}), '(big_shape)\n', (3925, 3936), True, 'import mxnet as mx\n'), ((4009, 4048), 'mxnet.nd.array', 'mx.nd.array', (['all_row_ids'], {'dtype': '"""int64"""'}), "(all_row_ids, dtype='int64')\n", (4020, 4048), True, 'import mxnet as mx\n'), ((4187, 4230), 'mxnet.nd.array', 'mx.nd.array', (['big_all_row_ids'], {'dtype': '"""int64"""'}), "(big_all_row_ids, dtype='int64')\n", (4198, 4230), True, 'import mxnet as mx\n'), ((4645, 4678), 'numpy.argwhere', 'np.argwhere', (['(idx_sample < density)'], {}), '(idx_sample < density)\n', (4656, 4678), True, 'import numpy as np\n'), ((5021, 5035), 'numpy.array', 'np.array', (['rows'], {}), '(rows)\n', (5029, 5035), True, 'import numpy as np\n'), ((1979, 1996), 'mxnet.nd.ones', 'mx.nd.ones', (['shape'], {}), '(shape)\n', (1989, 1996), True, 'import mxnet as mx\n'), ((2036, 2057), 'mxnet.nd.ones', 'mx.nd.ones', (['big_shape'], {}), '(big_shape)\n', (2046, 2057), True, 'import mxnet as mx\n'), ((1464, 1481), 'mxnet.nd.ones', 'mx.nd.ones', (['shape'], {}), '(shape)\n', (1474, 1481), True, 'import mxnet as mx\n')] |
import numpy as np
import torch
from PIL import Image
from skimage import exposure, morphology
from skimage.filters import threshold_otsu
from torch import nn
from torchvision import transforms
import inferno
from inferno.extensions.layers import ConvReLU2D
from inferno.extensions import model as inf_model
class AllInOneModel(nn.Module):
def __init__(self, focus_frame_idx):
super(AllInOneModel, self).__init__()
self.num_channels = 7
self.model = build_standart_model(self.num_channels, 1, no_sigm=False)
self.model.eval()
self.focus_frame_idx = focus_frame_idx
def forward(self, image): # BxCxHxW
input = []
for i in range(len(image)):
cur_image = image[i].cpu().data.numpy()
cur_image = self.filter_channels(cur_image, self.focus_frame_idx) #[i]
cur_image = self.image_preprocessing(cur_image)
input.append(cur_image)
input = np.stack(input, axis=0)
input = torch.Tensor(input).float()
result = []
pred_mask = self.tta(self.model, input.to(next(self.model.parameters()).device))
for i in range(pred_mask.shape[0]):
cur_pred = pred_mask[i][0].data.cpu().numpy()
cur_pred = self.prediction_postprocessing(cur_pred)
result.append(cur_pred[None])
result = np.stack(result, axis=0)
result = torch.Tensor(result).float()
return result
def filter_channels(self, image, focus_frame_idx):
return image[
focus_frame_idx
- self.num_channels // 2 : focus_frame_idx
+ self.num_channels // 2
+ self.num_channels % 2
]
def image_preprocessing(self, image):
for idx in range(image.shape[0]):
image[idx] = self.normalize_img(image[idx])
return image
def prediction_postprocessing(self, all_pred):
global_thresh = threshold_otsu(all_pred)
all_pred = all_pred >= global_thresh
all_pred = morphology.binary_opening(all_pred).astype("float32")
return all_pred
def normalize_img(self, image):
p2, p98 = np.percentile(image, (2, 98))
new_imarray = exposure.rescale_intensity(image, in_range=(p2, p98))
new_imarray = self.data_norm(new_imarray, new_imarray.min(), new_imarray.max())
return new_imarray
def data_norm(self, x, cur_min, cur_max):
return (x - cur_min) / (cur_max - cur_min)
def tta(self, model, image):
"""Test-time augmentation for image classification that averages predictions
of all D4 augmentations applied to input image.
For segmentation we need to reverse the augmentation after making a prediction
on augmented input.
:param model: Model to use for making predictions.
:param image: Model input.
:return: Arithmetically averaged predictions
"""
output = model(image).data.cpu()
for aug, deaug in zip(
[self.torch_rot90, self.torch_rot180, self.torch_rot270],
[self.torch_rot270, self.torch_rot180, self.torch_rot90],
):
x = deaug(model(aug(image)).data.cpu())
output = output + x
image = self.torch_transpose(image)
for aug, deaug in zip(
[self.torch_none, self.torch_rot90, self.torch_rot180, self.torch_rot270],
[self.torch_none, self.torch_rot270, self.torch_rot180, self.torch_rot90],
):
x = deaug(model(aug(image)).data.cpu())
output = output + self.torch_transpose(x)
one_over_8 = float(1.0 / 8.0)
return output * one_over_8
def torch_none(self, x):
return x
def torch_rot90_(self, x):
return x.transpose_(2, 3).flip(2)
def torch_rot90(self, x):
return x.transpose(2, 3).flip(2)
def torch_rot180(self, x):
return x.flip(2).flip(3)
def torch_rot270(self, x):
return x.transpose(2, 3).flip(3)
def torch_flipud(self, x):
"""
Flip image tensor vertically
:param x:
:return:
"""
return x.flip(2)
def torch_fliplr(self, x):
"""
Flip image tensor horizontally
:param x:
:return:
"""
return x.flip(3)
def torch_transpose(self, x):
return x.transpose(2, 3)
def torch_transpose_(self, x):
return x.transpose_(2, 3)
def torch_transpose2(self, x):
return x.transpose(3, 2)
def build_standart_model(image_channels, pred_channels=1, no_sigm=False):
if no_sigm:
return torch.nn.Sequential(
inf_model.ResBlockUNet(dim=2, in_channels=image_channels, out_channels=pred_channels, activated=False),
)
else:
return torch.nn.Sequential(
inf_model.ResBlockUNet(dim=2, in_channels=image_channels, out_channels=pred_channels, activated=False),
torch.nn.Sigmoid()
) | [
"torch.nn.Sigmoid",
"skimage.filters.threshold_otsu",
"inferno.extensions.model.ResBlockUNet",
"torch.Tensor",
"numpy.stack",
"skimage.exposure.rescale_intensity",
"numpy.percentile",
"skimage.morphology.binary_opening"
] | [((956, 979), 'numpy.stack', 'np.stack', (['input'], {'axis': '(0)'}), '(input, axis=0)\n', (964, 979), True, 'import numpy as np\n'), ((1360, 1384), 'numpy.stack', 'np.stack', (['result'], {'axis': '(0)'}), '(result, axis=0)\n', (1368, 1384), True, 'import numpy as np\n'), ((1935, 1959), 'skimage.filters.threshold_otsu', 'threshold_otsu', (['all_pred'], {}), '(all_pred)\n', (1949, 1959), False, 'from skimage.filters import threshold_otsu\n'), ((2157, 2186), 'numpy.percentile', 'np.percentile', (['image', '(2, 98)'], {}), '(image, (2, 98))\n', (2170, 2186), True, 'import numpy as np\n'), ((2209, 2262), 'skimage.exposure.rescale_intensity', 'exposure.rescale_intensity', (['image'], {'in_range': '(p2, p98)'}), '(image, in_range=(p2, p98))\n', (2235, 2262), False, 'from skimage import exposure, morphology\n'), ((4661, 4768), 'inferno.extensions.model.ResBlockUNet', 'inf_model.ResBlockUNet', ([], {'dim': '(2)', 'in_channels': 'image_channels', 'out_channels': 'pred_channels', 'activated': '(False)'}), '(dim=2, in_channels=image_channels, out_channels=\n pred_channels, activated=False)\n', (4683, 4768), True, 'from inferno.extensions import model as inf_model\n'), ((4833, 4940), 'inferno.extensions.model.ResBlockUNet', 'inf_model.ResBlockUNet', ([], {'dim': '(2)', 'in_channels': 'image_channels', 'out_channels': 'pred_channels', 'activated': '(False)'}), '(dim=2, in_channels=image_channels, out_channels=\n pred_channels, activated=False)\n', (4855, 4940), True, 'from inferno.extensions import model as inf_model\n'), ((4949, 4967), 'torch.nn.Sigmoid', 'torch.nn.Sigmoid', ([], {}), '()\n', (4965, 4967), False, 'import torch\n'), ((996, 1015), 'torch.Tensor', 'torch.Tensor', (['input'], {}), '(input)\n', (1008, 1015), False, 'import torch\n'), ((1402, 1422), 'torch.Tensor', 'torch.Tensor', (['result'], {}), '(result)\n', (1414, 1422), False, 'import torch\n'), ((2024, 2059), 'skimage.morphology.binary_opening', 'morphology.binary_opening', (['all_pred'], {}), '(all_pred)\n', (2049, 2059), False, 'from skimage import exposure, morphology\n')] |
# Copyright (C) 2019-2022, <NAME>.
# This program is licensed under the Apache License version 2.
# See LICENSE or go to <https://www.apache.org/licenses/LICENSE-2.0.txt> for full license details.
"""
Training script for semantic segmentation
"""
import datetime
import os
import time
import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.nn as nn
import torch.utils.data
import wandb
from torch.utils.data import RandomSampler, SequentialSampler
from torchvision import transforms as T
from torchvision.datasets import VOCSegmentation
from torchvision.models import segmentation as tv_segmentation
from torchvision.transforms.functional import InterpolationMode, to_pil_image
from transforms import Compose, ImageTransform, RandomCrop, RandomHorizontalFlip, RandomResize, Resize, ToTensor
import holocron
from holocron.models import segmentation
from holocron.trainer import SegmentationTrainer
VOC_CLASSES = [
"background",
"aeroplane",
"bicycle",
"bird",
"boat",
"bottle",
"bus",
"car",
"cat",
"chair",
"cow",
"diningtable",
"dog",
"horse",
"motorbike",
"person",
"pottedplant",
"sheep",
"sofa",
"train",
"tvmonitor",
]
def worker_init_fn(worker_id: int) -> None:
np.random.seed((worker_id + torch.initial_seed()) % np.iinfo(np.int32).max)
def plot_samples(images, targets, ignore_index=None):
# Unnormalize image
nb_samples = 4
_, axes = plt.subplots(2, nb_samples, figsize=(20, 5))
for idx in range(nb_samples):
img = images[idx]
img *= torch.tensor([0.229, 0.224, 0.225]).view(-1, 1, 1)
img += torch.tensor([0.485, 0.456, 0.406]).view(-1, 1, 1)
img = to_pil_image(img)
target = targets[idx]
if isinstance(ignore_index, int):
target[target == ignore_index] = 0
axes[0][idx].imshow(img)
axes[0][idx].axis("off")
axes[0][idx].set_title("Input image")
axes[1][idx].imshow(target)
axes[1][idx].axis("off")
axes[1][idx].set_title("Target")
plt.show()
def plot_predictions(images, preds, targets, ignore_index=None):
# Unnormalize image
nb_samples = 4
_, axes = plt.subplots(3, nb_samples, figsize=(20, 5))
for idx in range(nb_samples):
img = images[idx]
img *= torch.tensor([0.229, 0.224, 0.225]).view(-1, 1, 1)
img += torch.tensor([0.485, 0.456, 0.406]).view(-1, 1, 1)
img = to_pil_image(img)
# Target
target = targets[idx]
if isinstance(ignore_index, int):
target[target == ignore_index] = 0
# Prediction
pred = preds[idx].detach().cpu().argmax(dim=0)
axes[0][idx].imshow(img)
axes[0][idx].axis("off")
axes[0][idx].set_title("Input image")
axes[1][idx].imshow(target)
axes[1][idx].axis("off")
axes[1][idx].set_title("Target")
axes[2][idx].imshow(pred)
axes[2][idx].axis("off")
axes[2][idx].set_title("Prediction")
plt.show()
def main(args):
print(args)
torch.backends.cudnn.benchmark = True
# Data loading
normalize = T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
base_size = 320
crop_size = 256
min_size, max_size = int(0.5 * base_size), int(2.0 * base_size)
interpolation_mode = InterpolationMode.BILINEAR
train_loader, val_loader = None, None
if not args.test_only:
st = time.time()
train_set = VOCSegmentation(
args.data_path,
image_set="train",
download=True,
transforms=Compose(
[
RandomResize(min_size, max_size, interpolation_mode),
RandomCrop(crop_size),
RandomHorizontalFlip(0.5),
ImageTransform(T.ColorJitter(brightness=0.3, contrast=0.3, saturation=0.1, hue=0.02)),
ToTensor(),
ImageTransform(normalize),
]
),
)
train_loader = torch.utils.data.DataLoader(
train_set,
batch_size=args.batch_size,
drop_last=True,
sampler=RandomSampler(train_set),
num_workers=args.workers,
pin_memory=True,
worker_init_fn=worker_init_fn,
)
print(
f"Training set loaded in {time.time() - st:.2f}s "
f"({len(train_set)} samples in {len(train_loader)} batches)"
)
if args.show_samples:
x, target = next(iter(train_loader))
plot_samples(x, target, ignore_index=255)
return
if not (args.find_lr or args.check_setup):
st = time.time()
val_set = VOCSegmentation(
args.data_path,
image_set="val",
download=True,
transforms=Compose(
[Resize((crop_size, crop_size), interpolation_mode), ToTensor(), ImageTransform(normalize)]
),
)
val_loader = torch.utils.data.DataLoader(
val_set,
batch_size=args.batch_size,
drop_last=False,
sampler=SequentialSampler(val_set),
num_workers=args.workers,
pin_memory=True,
worker_init_fn=worker_init_fn,
)
print(f"Validation set loaded in {time.time() - st:.2f}s ({len(val_set)} samples in {len(val_loader)} batches)")
if args.source.lower() == "holocron":
model = segmentation.__dict__[args.arch](args.pretrained, num_classes=len(VOC_CLASSES))
elif args.source.lower() == "torchvision":
model = tv_segmentation.__dict__[args.arch](args.pretrained, num_classes=len(VOC_CLASSES))
# Loss setup
loss_weight = None
if isinstance(args.bg_factor, float) and args.bg_factor != 1:
loss_weight = torch.ones(len(VOC_CLASSES))
loss_weight[0] = args.bg_factor
if args.loss == "crossentropy":
criterion = nn.CrossEntropyLoss(weight=loss_weight, ignore_index=255, label_smoothing=args.label_smoothing)
elif args.loss == "focal":
criterion = holocron.nn.FocalLoss(weight=loss_weight, ignore_index=255)
elif args.loss == "mc":
criterion = holocron.nn.MutualChannelLoss(weight=loss_weight, ignore_index=255, xi=3)
# Optimizer setup
model_params = [p for p in model.parameters() if p.requires_grad]
if args.opt == "sgd":
optimizer = torch.optim.SGD(model_params, args.lr, momentum=0.9, weight_decay=args.weight_decay)
elif args.opt == "radam":
optimizer = holocron.optim.RAdam(
model_params, args.lr, betas=(0.95, 0.99), eps=1e-6, weight_decay=args.weight_decay
)
elif args.opt == "adamp":
optimizer = holocron.optim.AdamP(
model_params, args.lr, betas=(0.95, 0.99), eps=1e-6, weight_decay=args.weight_decay
)
elif args.opt == "adabelief":
optimizer = holocron.optim.AdaBelief(
model_params, args.lr, betas=(0.95, 0.99), eps=1e-6, weight_decay=args.weight_decay
)
log_wb = lambda metrics: wandb.log(metrics) if args.wb else None
trainer = SegmentationTrainer(
model,
train_loader,
val_loader,
criterion,
optimizer,
args.device,
args.output_file,
num_classes=len(VOC_CLASSES),
amp=args.amp,
on_epoch_end=log_wb,
)
if args.resume:
print(f"Resuming {args.resume}")
checkpoint = torch.load(args.resume, map_location="cpu")
trainer.load(checkpoint)
if args.show_preds:
x, target = next(iter(train_loader))
with torch.no_grad():
if isinstance(args.device, int):
x = x.cuda()
trainer.model.eval()
preds = trainer.model(x)
plot_predictions(x.cpu(), preds.cpu(), target, ignore_index=255)
return
if args.test_only:
print("Running evaluation")
eval_metrics = trainer.evaluate()
print(f"Validation loss: {eval_metrics['val_loss']:.4} (Mean IoU: {eval_metrics['mean_iou']:.2%})")
return
if args.find_lr:
print("Looking for optimal LR")
trainer.find_lr(args.freeze_until, norm_weight_decay=args.norm_weight_decay, num_it=min(len(train_loader), 100))
trainer.plot_recorder()
return
if args.check_setup:
print("Checking batch overfitting")
is_ok = trainer.check_setup(
args.freeze_until, args.lr, norm_weight_decay=args.norm_weight_decay, num_it=min(len(train_loader), 100)
)
print(is_ok)
return
# Training monitoring
current_time = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
exp_name = f"{args.arch}-{current_time}" if args.name is None else args.name
# W&B
if args.wb:
run = wandb.init(
name=exp_name,
project="holocron-semantic-segmentation",
config={
"learning_rate": args.lr,
"scheduler": args.sched,
"weight_decay": args.weight_decay,
"epochs": args.epochs,
"batch_size": args.batch_size,
"architecture": args.arch,
"source": args.source,
"input_size": 256,
"optimizer": args.opt,
"dataset": "Pascal VOC2012 Segmentation",
"loss": args.loss,
},
)
print("Start training")
start_time = time.time()
trainer.fit_n_epochs(args.epochs, args.lr, args.freeze_until, args.sched, norm_weight_decay=args.norm_weight_decay)
total_time_str = str(datetime.timedelta(seconds=int(time.time() - start_time)))
print(f"Training time {total_time_str}")
if args.wb:
run.finish()
def get_parser():
import argparse
parser = argparse.ArgumentParser(
description="Holocron Segmentation Training", formatter_class=argparse.ArgumentDefaultsHelpFormatter
)
parser.add_argument("data_path", type=str, help="path to dataset folder")
parser.add_argument("--name", type=str, default=None, help="Name of your training experiment")
parser.add_argument("--arch", type=str, default="unet3p", help="architecture to use")
parser.add_argument("--source", type=str, default="holocron", help="where should the architecture be taken from")
parser.add_argument("--freeze-until", default=None, type=str, help="Last layer to freeze")
parser.add_argument("--device", default=None, type=int, help="device")
parser.add_argument("-b", "--batch-size", default=32, type=int, help="batch size")
parser.add_argument("--epochs", default=20, type=int, help="number of total epochs to run")
parser.add_argument(
"-j", "--workers", default=min(os.cpu_count(), 16), type=int, help="number of data loading workers"
)
parser.add_argument("--loss", default="crossentropy", type=str, help="loss")
parser.add_argument("--label-smoothing", default=0.1, type=float, help="label smoothing")
parser.add_argument("--bg-factor", default=1, type=float, help="Class weight of background in the loss")
parser.add_argument("--opt", default="adam", type=str, help="optimizer")
parser.add_argument("--sched", default="onecycle", type=str, help="scheduler")
parser.add_argument("--lr", default=0.1, type=float, help="initial learning rate")
parser.add_argument("--wd", "--weight-decay", default=0, type=float, help="weight decay", dest="weight_decay")
parser.add_argument("--norm-wd", default=None, type=float, help="weight decay of norm parameters")
parser.add_argument("--find-lr", action="store_true", help="Should you run LR Finder")
parser.add_argument("--check-setup", action="store_true", help="Check your training setup")
parser.add_argument("--output-file", default="./model.pth", help="path where to save")
parser.add_argument("--resume", default="", help="resume from checkpoint")
parser.add_argument("--show-samples", action="store_true", help="Whether training samples should be displayed")
parser.add_argument("--show-preds", action="store_true", help="Whether one batch predictions should be displayed")
parser.add_argument("--test-only", action="store_true", help="Only test the model")
parser.add_argument("--pretrained", action="store_true", help="Use pre-trained models from the model zoo")
parser.add_argument("--amp", action="store_true", help="Use Automatic Mixed Precision")
parser.add_argument("--wb", action="store_true", help="Log to Weights & Biases")
return parser
if __name__ == "__main__":
args = get_parser().parse_args()
main(args)
| [
"wandb.log",
"torch.nn.CrossEntropyLoss",
"torchvision.transforms.functional.to_pil_image",
"torch.initial_seed",
"holocron.optim.AdamP",
"numpy.iinfo",
"wandb.init",
"torchvision.transforms.ColorJitter",
"holocron.nn.MutualChannelLoss",
"transforms.Resize",
"os.cpu_count",
"transforms.ImageTr... | [((1475, 1519), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)', 'nb_samples'], {'figsize': '(20, 5)'}), '(2, nb_samples, figsize=(20, 5))\n', (1487, 1519), True, 'import matplotlib.pyplot as plt\n'), ((2090, 2100), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2098, 2100), True, 'import matplotlib.pyplot as plt\n'), ((2225, 2269), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(3)', 'nb_samples'], {'figsize': '(20, 5)'}), '(3, nb_samples, figsize=(20, 5))\n', (2237, 2269), True, 'import matplotlib.pyplot as plt\n'), ((3045, 3055), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3053, 3055), True, 'import matplotlib.pyplot as plt\n'), ((3170, 3236), 'torchvision.transforms.Normalize', 'T.Normalize', ([], {'mean': '[0.485, 0.456, 0.406]', 'std': '[0.229, 0.224, 0.225]'}), '(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n', (3181, 3236), True, 'from torchvision import transforms as T\n'), ((9521, 9532), 'time.time', 'time.time', ([], {}), '()\n', (9530, 9532), False, 'import time\n'), ((9874, 10003), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Holocron Segmentation Training"""', 'formatter_class': 'argparse.ArgumentDefaultsHelpFormatter'}), "(description='Holocron Segmentation Training',\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n", (9897, 10003), False, 'import argparse\n'), ((1726, 1743), 'torchvision.transforms.functional.to_pil_image', 'to_pil_image', (['img'], {}), '(img)\n', (1738, 1743), False, 'from torchvision.transforms.functional import InterpolationMode, to_pil_image\n'), ((2476, 2493), 'torchvision.transforms.functional.to_pil_image', 'to_pil_image', (['img'], {}), '(img)\n', (2488, 2493), False, 'from torchvision.transforms.functional import InterpolationMode, to_pil_image\n'), ((3481, 3492), 'time.time', 'time.time', ([], {}), '()\n', (3490, 3492), False, 'import time\n'), ((4729, 4740), 'time.time', 'time.time', ([], {}), '()\n', (4738, 4740), False, 'import time\n'), ((5995, 6095), 'torch.nn.CrossEntropyLoss', 'nn.CrossEntropyLoss', ([], {'weight': 'loss_weight', 'ignore_index': '(255)', 'label_smoothing': 'args.label_smoothing'}), '(weight=loss_weight, ignore_index=255, label_smoothing=\n args.label_smoothing)\n', (6014, 6095), True, 'import torch.nn as nn\n'), ((6463, 6552), 'torch.optim.SGD', 'torch.optim.SGD', (['model_params', 'args.lr'], {'momentum': '(0.9)', 'weight_decay': 'args.weight_decay'}), '(model_params, args.lr, momentum=0.9, weight_decay=args.\n weight_decay)\n', (6478, 6552), False, 'import torch\n'), ((7514, 7557), 'torch.load', 'torch.load', (['args.resume'], {'map_location': '"""cpu"""'}), "(args.resume, map_location='cpu')\n", (7524, 7557), False, 'import torch\n'), ((8867, 9257), 'wandb.init', 'wandb.init', ([], {'name': 'exp_name', 'project': '"""holocron-semantic-segmentation"""', 'config': "{'learning_rate': args.lr, 'scheduler': args.sched, 'weight_decay': args.\n weight_decay, 'epochs': args.epochs, 'batch_size': args.batch_size,\n 'architecture': args.arch, 'source': args.source, 'input_size': 256,\n 'optimizer': args.opt, 'dataset': 'Pascal VOC2012 Segmentation', 'loss':\n args.loss}"}), "(name=exp_name, project='holocron-semantic-segmentation', config=\n {'learning_rate': args.lr, 'scheduler': args.sched, 'weight_decay':\n args.weight_decay, 'epochs': args.epochs, 'batch_size': args.batch_size,\n 'architecture': args.arch, 'source': args.source, 'input_size': 256,\n 'optimizer': args.opt, 'dataset': 'Pascal VOC2012 Segmentation', 'loss':\n args.loss})\n", (8877, 9257), False, 'import wandb\n'), ((6142, 6201), 'holocron.nn.FocalLoss', 'holocron.nn.FocalLoss', ([], {'weight': 'loss_weight', 'ignore_index': '(255)'}), '(weight=loss_weight, ignore_index=255)\n', (6163, 6201), False, 'import holocron\n'), ((6598, 6708), 'holocron.optim.RAdam', 'holocron.optim.RAdam', (['model_params', 'args.lr'], {'betas': '(0.95, 0.99)', 'eps': '(1e-06)', 'weight_decay': 'args.weight_decay'}), '(model_params, args.lr, betas=(0.95, 0.99), eps=1e-06,\n weight_decay=args.weight_decay)\n', (6618, 6708), False, 'import holocron\n'), ((7120, 7138), 'wandb.log', 'wandb.log', (['metrics'], {}), '(metrics)\n', (7129, 7138), False, 'import wandb\n'), ((7674, 7689), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (7687, 7689), False, 'import torch\n'), ((8694, 8717), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (8715, 8717), False, 'import datetime\n'), ((1314, 1334), 'torch.initial_seed', 'torch.initial_seed', ([], {}), '()\n', (1332, 1334), False, 'import torch\n'), ((1338, 1356), 'numpy.iinfo', 'np.iinfo', (['np.int32'], {}), '(np.int32)\n', (1346, 1356), True, 'import numpy as np\n'), ((1595, 1630), 'torch.tensor', 'torch.tensor', (['[0.229, 0.224, 0.225]'], {}), '([0.229, 0.224, 0.225])\n', (1607, 1630), False, 'import torch\n'), ((1661, 1696), 'torch.tensor', 'torch.tensor', (['[0.485, 0.456, 0.406]'], {}), '([0.485, 0.456, 0.406])\n', (1673, 1696), False, 'import torch\n'), ((2345, 2380), 'torch.tensor', 'torch.tensor', (['[0.229, 0.224, 0.225]'], {}), '([0.229, 0.224, 0.225])\n', (2357, 2380), False, 'import torch\n'), ((2411, 2446), 'torch.tensor', 'torch.tensor', (['[0.485, 0.456, 0.406]'], {}), '([0.485, 0.456, 0.406])\n', (2423, 2446), False, 'import torch\n'), ((4223, 4247), 'torch.utils.data.RandomSampler', 'RandomSampler', (['train_set'], {}), '(train_set)\n', (4236, 4247), False, 'from torch.utils.data import RandomSampler, SequentialSampler\n'), ((5186, 5212), 'torch.utils.data.SequentialSampler', 'SequentialSampler', (['val_set'], {}), '(val_set)\n', (5203, 5212), False, 'from torch.utils.data import RandomSampler, SequentialSampler\n'), ((6250, 6323), 'holocron.nn.MutualChannelLoss', 'holocron.nn.MutualChannelLoss', ([], {'weight': 'loss_weight', 'ignore_index': '(255)', 'xi': '(3)'}), '(weight=loss_weight, ignore_index=255, xi=3)\n', (6279, 6323), False, 'import holocron\n'), ((6776, 6886), 'holocron.optim.AdamP', 'holocron.optim.AdamP', (['model_params', 'args.lr'], {'betas': '(0.95, 0.99)', 'eps': '(1e-06)', 'weight_decay': 'args.weight_decay'}), '(model_params, args.lr, betas=(0.95, 0.99), eps=1e-06,\n weight_decay=args.weight_decay)\n', (6796, 6886), False, 'import holocron\n'), ((10817, 10831), 'os.cpu_count', 'os.cpu_count', ([], {}), '()\n', (10829, 10831), False, 'import os\n'), ((6958, 7073), 'holocron.optim.AdaBelief', 'holocron.optim.AdaBelief', (['model_params', 'args.lr'], {'betas': '(0.95, 0.99)', 'eps': '(1e-06)', 'weight_decay': 'args.weight_decay'}), '(model_params, args.lr, betas=(0.95, 0.99), eps=\n 1e-06, weight_decay=args.weight_decay)\n', (6982, 7073), False, 'import holocron\n'), ((3686, 3738), 'transforms.RandomResize', 'RandomResize', (['min_size', 'max_size', 'interpolation_mode'], {}), '(min_size, max_size, interpolation_mode)\n', (3698, 3738), False, 'from transforms import Compose, ImageTransform, RandomCrop, RandomHorizontalFlip, RandomResize, Resize, ToTensor\n'), ((3760, 3781), 'transforms.RandomCrop', 'RandomCrop', (['crop_size'], {}), '(crop_size)\n', (3770, 3781), False, 'from transforms import Compose, ImageTransform, RandomCrop, RandomHorizontalFlip, RandomResize, Resize, ToTensor\n'), ((3803, 3828), 'transforms.RandomHorizontalFlip', 'RandomHorizontalFlip', (['(0.5)'], {}), '(0.5)\n', (3823, 3828), False, 'from transforms import Compose, ImageTransform, RandomCrop, RandomHorizontalFlip, RandomResize, Resize, ToTensor\n'), ((3957, 3967), 'transforms.ToTensor', 'ToTensor', ([], {}), '()\n', (3965, 3967), False, 'from transforms import Compose, ImageTransform, RandomCrop, RandomHorizontalFlip, RandomResize, Resize, ToTensor\n'), ((3989, 4014), 'transforms.ImageTransform', 'ImageTransform', (['normalize'], {}), '(normalize)\n', (4003, 4014), False, 'from transforms import Compose, ImageTransform, RandomCrop, RandomHorizontalFlip, RandomResize, Resize, ToTensor\n'), ((4423, 4434), 'time.time', 'time.time', ([], {}), '()\n', (4432, 4434), False, 'import time\n'), ((4909, 4959), 'transforms.Resize', 'Resize', (['(crop_size, crop_size)', 'interpolation_mode'], {}), '((crop_size, crop_size), interpolation_mode)\n', (4915, 4959), False, 'from transforms import Compose, ImageTransform, RandomCrop, RandomHorizontalFlip, RandomResize, Resize, ToTensor\n'), ((4961, 4971), 'transforms.ToTensor', 'ToTensor', ([], {}), '()\n', (4969, 4971), False, 'from transforms import Compose, ImageTransform, RandomCrop, RandomHorizontalFlip, RandomResize, Resize, ToTensor\n'), ((4973, 4998), 'transforms.ImageTransform', 'ImageTransform', (['normalize'], {}), '(normalize)\n', (4987, 4998), False, 'from transforms import Compose, ImageTransform, RandomCrop, RandomHorizontalFlip, RandomResize, Resize, ToTensor\n'), ((5377, 5388), 'time.time', 'time.time', ([], {}), '()\n', (5386, 5388), False, 'import time\n'), ((9709, 9720), 'time.time', 'time.time', ([], {}), '()\n', (9718, 9720), False, 'import time\n'), ((3865, 3934), 'torchvision.transforms.ColorJitter', 'T.ColorJitter', ([], {'brightness': '(0.3)', 'contrast': '(0.3)', 'saturation': '(0.1)', 'hue': '(0.02)'}), '(brightness=0.3, contrast=0.3, saturation=0.1, hue=0.02)\n', (3878, 3934), True, 'from torchvision import transforms as T\n')] |
# THIS IS A TESTING FILE AND IS NOT PART OF THE PROJECT
# The code below can be called from a diffrerent file with import face_recon
# and webcam_detection(numpy_array_image, user_name)
# If you want to test this file on your own make sure you install face_recognition lib (tutorial found on Trello board)
# and also opencv-python and numpy
import face_recognition
import cv2
import numpy as np
def webcam_detection(known_image, display_name):
# Get a reference to webcam #0 (the default one)
video_capture = cv2.VideoCapture(0)
# Load a sample picture and learn how to recognize it.
known_face_encoding = face_recognition.face_encodings(known_image)[0]
# Create arrays of known face encodings and their names
known_face_encodings = [
known_face_encoding
]
known_face_names = [
display_name
]
# Initialize some variables
face_locations = []
face_encodings = []
face_names = []
process_this_frame = True
while True:
# Grab a single frame of video
ret, frame = video_capture.read()
# Resize frame of video to 1/4 size for faster face recognition processing
small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)
# Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses)
rgb_small_frame = small_frame[:, :, ::-1]
# Only process every other frame of video to save time
if process_this_frame:
# Find all the faces and face encodings in the current frame of video
face_locations = face_recognition.face_locations(rgb_small_frame)
face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)
face_names = []
for face_encoding in face_encodings:
# See if the face is a match for the known face(s)
matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
name = "Unknown user"
# # If a match was found in known_face_encodings, just use the first one.
# if True in matches:
# first_match_index = matches.index(True)
# name = known_face_names[first_match_index]
# Or instead, use the known face with the smallest distance to the new face
face_distances = face_recognition.face_distance(known_face_encodings, face_encoding)
best_match_index = np.argmin(face_distances)
if matches[best_match_index]:
name = known_face_names[best_match_index]
return True
face_names.append(name)
process_this_frame = not process_this_frame
# Display the resulting image
# cv2.imshow('SindiAI-Detector', frame)
# Hit 'q' on the keyboard to quit!
if cv2.waitKey(1) & 0xFF == ord('q'):
break
video_capture.release()
cv2.destroyAllWindows()
| [
"face_recognition.face_locations",
"face_recognition.face_distance",
"cv2.destroyAllWindows",
"cv2.VideoCapture",
"face_recognition.compare_faces",
"face_recognition.face_encodings",
"numpy.argmin",
"cv2.resize",
"cv2.waitKey"
] | [((533, 552), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\n', (549, 552), False, 'import cv2\n'), ((3061, 3084), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (3082, 3084), False, 'import cv2\n'), ((642, 686), 'face_recognition.face_encodings', 'face_recognition.face_encodings', (['known_image'], {}), '(known_image)\n', (673, 686), False, 'import face_recognition\n'), ((1222, 1265), 'cv2.resize', 'cv2.resize', (['frame', '(0, 0)'], {'fx': '(0.25)', 'fy': '(0.25)'}), '(frame, (0, 0), fx=0.25, fy=0.25)\n', (1232, 1265), False, 'import cv2\n'), ((1637, 1685), 'face_recognition.face_locations', 'face_recognition.face_locations', (['rgb_small_frame'], {}), '(rgb_small_frame)\n', (1668, 1685), False, 'import face_recognition\n'), ((1716, 1780), 'face_recognition.face_encodings', 'face_recognition.face_encodings', (['rgb_small_frame', 'face_locations'], {}), '(rgb_small_frame, face_locations)\n', (1747, 1780), False, 'import face_recognition\n'), ((1957, 2024), 'face_recognition.compare_faces', 'face_recognition.compare_faces', (['known_face_encodings', 'face_encoding'], {}), '(known_face_encodings, face_encoding)\n', (1987, 2024), False, 'import face_recognition\n'), ((2454, 2521), 'face_recognition.face_distance', 'face_recognition.face_distance', (['known_face_encodings', 'face_encoding'], {}), '(known_face_encodings, face_encoding)\n', (2484, 2521), False, 'import face_recognition\n'), ((2558, 2583), 'numpy.argmin', 'np.argmin', (['face_distances'], {}), '(face_distances)\n', (2567, 2583), True, 'import numpy as np\n'), ((2971, 2985), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (2982, 2985), False, 'import cv2\n')] |
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm, t
np.random.seed(1)
#%%
N = 1_0
mu = 5
sd = 2
#%%
x = np.random.randn(N)*sd + mu
#%% Z-CI
mu_hat = x.mean()
sigma_hat = x.std(ddof=1)
z_left = norm.ppf(0.0250)
z_right = norm.ppf(0.9750)
left_ci = mu_hat + z_left*sigma_hat/np.sqrt(N)
right_ci = mu_hat + z_right*sigma_hat/np.sqrt(N)
print(f"Mean: {mu_hat}")
print(f"Confidence Interval is [{left_ci}, {right_ci}]")
#%% t-CI
mu_hat = x.mean()
sigma_hat = x.std(ddof=1)
t_left = t.ppf(0.0250, df=N-1)
t_right = t.ppf(0.9750, df=N-1)
left_ci = mu_hat + t_left*sigma_hat/np.sqrt(N)
right_ci = mu_hat + t_right*sigma_hat/np.sqrt(N)
print(f"Mean: {mu_hat}")
print(f"Confidence Interval is [{left_ci}, {right_ci}]")
#%%
def experiment():
x = np.random.randn(N) * sd + mu
mu_hat = x.mean()
sigma_hat = x.std(ddof=1)
t_left = t.ppf(0.0250, df=N - 1)
t_right = t.ppf(0.9750, df=N - 1)
left_ci = mu_hat + t_left * sigma_hat / np.sqrt(N)
right_ci = mu_hat + t_right * sigma_hat / np.sqrt(N)
return mu<right_ci and mu>left_ci
def multi_experiment(n):
results = [experiment() for _ in range(n)]
return np.mean(results)
#%%
result = multi_experiment(10_000)
print(result)
| [
"numpy.mean",
"numpy.sqrt",
"scipy.stats.norm.ppf",
"numpy.random.seed",
"numpy.random.randn",
"scipy.stats.t.ppf"
] | [((83, 100), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (97, 100), True, 'import numpy as np\n'), ((227, 242), 'scipy.stats.norm.ppf', 'norm.ppf', (['(0.025)'], {}), '(0.025)\n', (235, 242), False, 'from scipy.stats import norm, t\n'), ((254, 269), 'scipy.stats.norm.ppf', 'norm.ppf', (['(0.975)'], {}), '(0.975)\n', (262, 269), False, 'from scipy.stats import norm, t\n'), ((512, 534), 'scipy.stats.t.ppf', 't.ppf', (['(0.025)'], {'df': '(N - 1)'}), '(0.025, df=N - 1)\n', (517, 534), False, 'from scipy.stats import norm, t\n'), ((544, 566), 'scipy.stats.t.ppf', 't.ppf', (['(0.975)'], {'df': '(N - 1)'}), '(0.975, df=N - 1)\n', (549, 566), False, 'from scipy.stats import norm, t\n'), ((869, 891), 'scipy.stats.t.ppf', 't.ppf', (['(0.025)'], {'df': '(N - 1)'}), '(0.025, df=N - 1)\n', (874, 891), False, 'from scipy.stats import norm, t\n'), ((907, 929), 'scipy.stats.t.ppf', 't.ppf', (['(0.975)'], {'df': '(N - 1)'}), '(0.975, df=N - 1)\n', (912, 929), False, 'from scipy.stats import norm, t\n'), ((1165, 1181), 'numpy.mean', 'np.mean', (['results'], {}), '(results)\n', (1172, 1181), True, 'import numpy as np\n'), ((137, 155), 'numpy.random.randn', 'np.random.randn', (['N'], {}), '(N)\n', (152, 155), True, 'import numpy as np\n'), ((307, 317), 'numpy.sqrt', 'np.sqrt', (['N'], {}), '(N)\n', (314, 317), True, 'import numpy as np\n'), ((356, 366), 'numpy.sqrt', 'np.sqrt', (['N'], {}), '(N)\n', (363, 366), True, 'import numpy as np\n'), ((602, 612), 'numpy.sqrt', 'np.sqrt', (['N'], {}), '(N)\n', (609, 612), True, 'import numpy as np\n'), ((651, 661), 'numpy.sqrt', 'np.sqrt', (['N'], {}), '(N)\n', (658, 661), True, 'import numpy as np\n'), ((775, 793), 'numpy.random.randn', 'np.random.randn', (['N'], {}), '(N)\n', (790, 793), True, 'import numpy as np\n'), ((975, 985), 'numpy.sqrt', 'np.sqrt', (['N'], {}), '(N)\n', (982, 985), True, 'import numpy as np\n'), ((1032, 1042), 'numpy.sqrt', 'np.sqrt', (['N'], {}), '(N)\n', (1039, 1042), True, 'import numpy as np\n')] |
import numpy as np
# Creating vectors (unidimensional arrays)
vector_a = np.arange(5) # 0 to 4 array
vector_b = np.arange(start=3, stop=7, step=1) # start, stop, step
vector_c = np.arange(11, 1, -2)
vector_d = np.linspace(start=0, stop=1, num=11) # Automatic step calculation with explicit array length definition (third parameter)
print(f'\nVector A:\n', vector_a)
print(f'\nVector B:\n', vector_b)
print(f'\nVector C:\n', vector_c)
print(f'\nVector D:\n', vector_d)
# Creating matrix (bidimensional arrays)
matrix_a = np.arange(9).reshape(3, 3) # Array of 3 arrays each one with 3 ascendent numbers from 0 to reach 8
# for index, array in enumerate(matrix_a):
# print(f'{index} array:', array)
# for element in array:
# print(element)
print(f'\nMatrix:\n', matrix_a)
# Creating tensors (+3 dimensional arrays)
tensor_a = np.arange(12).reshape(3, 2, 2)
print(f'\nTensor:\n', tensor_a)
# Creating an array from a list
my_list = [1, 2, 3, 4, 5]
vector_from_list_a = np.array(my_list)
vector_from_list_b = np.array([1, 2, 3, 4, 5])
print(f'\nVector from list A:\n', vector_from_list_a)
print(f'\nVector from list B:\n', vector_from_list_b)
matrix_from_list = np.array([[1, 2, 3], [4, 5, 6]])
print(f'\nMatrix from list:\n', matrix_from_list)
tensor_from_list = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]])
print(f'\nTensor from list:\n', tensor_from_list)
# Creating empty arrays
empty_array_a = np.zeros(5)
empty_array_b = np.zeros((2, 2))
empty_array_c = np.ones((2, 2))
print(f'\nEmpty array A:\n{empty_array_a}')
print(f'\nEmpty array B:\n{empty_array_b}')
print(f'\nEmpty array C:\n{empty_array_c}')
# Filled arrays
filled_array_a = np.full(shape=(2, 2), fill_value=7)
filled_array_b = np.full(shape=(2, 2), fill_value='a')
print(f'\nFilled array A:\n{filled_array_a}')
print(f'\nFilled array B:\n{filled_array_b}')
# Reusing the structure of an array to construct another array
base = np.linspace(2, 6, 4)
reuse_array_a = np.full_like(base, np.pi)
print(f'\nReusing an array:\nBase: {base}\nTo: {reuse_array_a}\n')
| [
"numpy.ones",
"numpy.full_like",
"numpy.array",
"numpy.linspace",
"numpy.zeros",
"numpy.full",
"numpy.arange"
] | [((75, 87), 'numpy.arange', 'np.arange', (['(5)'], {}), '(5)\n', (84, 87), True, 'import numpy as np\n'), ((114, 148), 'numpy.arange', 'np.arange', ([], {'start': '(3)', 'stop': '(7)', 'step': '(1)'}), '(start=3, stop=7, step=1)\n', (123, 148), True, 'import numpy as np\n'), ((180, 200), 'numpy.arange', 'np.arange', (['(11)', '(1)', '(-2)'], {}), '(11, 1, -2)\n', (189, 200), True, 'import numpy as np\n'), ((212, 248), 'numpy.linspace', 'np.linspace', ([], {'start': '(0)', 'stop': '(1)', 'num': '(11)'}), '(start=0, stop=1, num=11)\n', (223, 248), True, 'import numpy as np\n'), ((993, 1010), 'numpy.array', 'np.array', (['my_list'], {}), '(my_list)\n', (1001, 1010), True, 'import numpy as np\n'), ((1032, 1057), 'numpy.array', 'np.array', (['[1, 2, 3, 4, 5]'], {}), '([1, 2, 3, 4, 5])\n', (1040, 1057), True, 'import numpy as np\n'), ((1186, 1218), 'numpy.array', 'np.array', (['[[1, 2, 3], [4, 5, 6]]'], {}), '([[1, 2, 3], [4, 5, 6]])\n', (1194, 1218), True, 'import numpy as np\n'), ((1289, 1356), 'numpy.array', 'np.array', (['[[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]]'], {}), '([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]])\n', (1297, 1356), True, 'import numpy as np\n'), ((1449, 1460), 'numpy.zeros', 'np.zeros', (['(5)'], {}), '(5)\n', (1457, 1460), True, 'import numpy as np\n'), ((1477, 1493), 'numpy.zeros', 'np.zeros', (['(2, 2)'], {}), '((2, 2))\n', (1485, 1493), True, 'import numpy as np\n'), ((1510, 1525), 'numpy.ones', 'np.ones', (['(2, 2)'], {}), '((2, 2))\n', (1517, 1525), True, 'import numpy as np\n'), ((1694, 1729), 'numpy.full', 'np.full', ([], {'shape': '(2, 2)', 'fill_value': '(7)'}), '(shape=(2, 2), fill_value=7)\n', (1701, 1729), True, 'import numpy as np\n'), ((1747, 1784), 'numpy.full', 'np.full', ([], {'shape': '(2, 2)', 'fill_value': '"""a"""'}), "(shape=(2, 2), fill_value='a')\n", (1754, 1784), True, 'import numpy as np\n'), ((1950, 1970), 'numpy.linspace', 'np.linspace', (['(2)', '(6)', '(4)'], {}), '(2, 6, 4)\n', (1961, 1970), True, 'import numpy as np\n'), ((1987, 2012), 'numpy.full_like', 'np.full_like', (['base', 'np.pi'], {}), '(base, np.pi)\n', (1999, 2012), True, 'import numpy as np\n'), ((525, 537), 'numpy.arange', 'np.arange', (['(9)'], {}), '(9)\n', (534, 537), True, 'import numpy as np\n'), ((847, 860), 'numpy.arange', 'np.arange', (['(12)'], {}), '(12)\n', (856, 860), True, 'import numpy as np\n')] |
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# PYTHON VERSION OF MATTHEW LEONAWICZ's DOF/DOT/LOGS R Script
# --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
# Author: <NAME> -- 2019 -- <EMAIL>
# LICENSE: MIT
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
def tfg_days( x, err='off' ):
''' calculate DOF/DOT/LOGS for a vector of 12 chronological monthly values '''
import itertools
import numpy as np
# filter the div by zero and comparison with np.nan warnings from numpy
if err == 'off':
np.warnings.filterwarnings( "ignore", category=RuntimeWarning )
x[ x == 0 ] = -0.0001 # need to treat zero as freezing (working with signs)
# positive or negative monthly temps
s1 = np.sign( x )
# products of consecutive months' signs: positive indicates no change; negative indicates a potential freeze or thaw transition
s = s1[:11] * s1[1:]
idx, = np.where( s < 0 )
# may be length zero (no transitions)
ind = np.sort( np.concatenate( [idx, idx+1] ) )
if np.any( np.isnan( x ) == True ): # ignore cells with missing data
dot, dof, grow = itertools.repeat( np.array([np.nan]), 3 )
case = 1
elif (len(ind) == 0) & (s1[0] > 0): # no transitions: all positive temps means no freeze day
dot = 0
dof, grow = itertools.repeat( np.array([365]), 2 )
case = 2
elif (len(ind) == 0) & (s1[0] < 0): # no transitions: all negative temps means no thaw day
dot = np.array([365])
dof, grow = itertools.repeat( np.array([0]), 2 )
case = 3
# [ML FIXED]
elif len(ind) == 2: # only one transition during the year, thawing or freezing
# places where we know the ground freezes and thaws,
# but during a specific 12 months we just don't happen to witness both
# only thaw occurs
if x[ ind[0] ] < 0:
# [ml] note:((ind[0]+1)-1) is ind[0]+1 is the month number and minus 1 is to get to previous month
# we could make that a call to a months array -- months = range(1, 12+1)
dot = 15 + 30 * ((ind[0]+1)-1) - np.round( x[ ind[0] ] / (np.diff( x[ ind[:2] ] ) / 30.0), decimals=0 )
dof = np.array([350]) # 350: we know the ground freezes so we use 350 rather than the special 365
grow = dof - dot
case = 4
# only freeze occurs
if x[ ind[0] ] > 0:
dof = 350 - 30 * (12-ind[1]-1) - np.round( x[ ind[1] ] / (np.diff( x[ ind[:2] ] ) / 30.0), decimals=0 )
dot = np.array([15]) # 15: we know the ground thaws so we use 15 rather than the special 0
grow = dof - dot
case = 5
# [ML FIXED]
elif (len(ind) == 4 ) & (s1[0] < 0): # two transitions occur: thaw, then freeze (this is the ideal case; everything else is an idiosyncratic edge case)
# [ml] note:((ind[0]+1)-1) is ind[0]+1 is the month number and minus 1 is to get to previous month
# we could make that a call to a months array -- months = range(1, 12+1)
dot = 15 + 30 * ((ind[0]+1)-1) - np.round( x[ ind[0] ] / (np.diff( x[ ind[:2] ] ) / 30.0), decimals=0 )
dof = 350 - 30 * (12-ind[3]-1) - np.round( x[ ind[3] ] / (np.diff( x[ ind[2:4] ] ) / 30.0), decimals=0 )
grow = dof - dot
case = 0
# [ML FIXED]
elif (len(ind) == 4) & (s1[0] > 0): # two transitions occur but backward to what is expected; freeze, then thaw
if( ind[0] >= 7 ): # freeze occurs in second half of year as expected; late thaw is spurious
# dof = 350 - 30 * (12-ind[1]-1) - np.round( x[ ind[1] ] / (np.diff( x[ ind[:2] ] ) / 30.0), decimals=0 )
dof = 350 - 30 * (12-ind[1]-1) - np.round( x[ ind[1] ] / (np.diff( x[ ind[:2] ] ) / 30.0), decimals=0 )
dot = np.array([15]) # ignore spurious post-freeze thaw; treat as early, unobserved thaw
grow = dof - dot
case = 6
if ind[0] <= 6: # spurious freeze occurs in first half of year; thaw probably fine
dot = 15 + 30 * ((ind[2]+1)-1) - np.round( x[ ind[2] ] / (np.diff( x[ ind[2:4] ]) / 30.0), decimals=0 )
dof = np.array([350]) # ignore spurious early freeze; treat as late, unobserved freeze
grow = dof - dot
case = 7
# [ML FIXED]
elif len(ind) > 4: # more than two transitions; at least one definitely spurious
# [MATT Q]:
# what is the prepending 0 below? and what is its intention?
# what do u do if there is a use-case where idx-0 is already chosen? Py is ZERO-anchored...
ind2, = np.where( s < 0 )
ind2 = ind2 + 1
ind2 = np.insert( ind2, 0, np.array([0]) )
# [ml] m1, m2 are month indexes
m1, = np.where( np.diff( ind2 ) == np.max( np.diff( ind2 ) ) )
m1 = m1[-1] + 1
m2, = np.where( np.delete(np.diff( ind2 ), (m1-1)-1) == max( np.delete(np.diff( ind2 ), (m1-1)-1)) )
m2, = np.where( np.delete(np.diff( ind2 ), (m1-1)) == max( np.delete(np.diff( ind2 ), (m1-1))) )
m2 = m2[-1] + 1
if m1 == m2:
m2 = m2 - 1
ind2 = ind2[ np.sort( np.append( m1, m2 ) ) ]
ind = np.sort( np.append(ind2, ind2+1) ) - 1
dot = 15 + 30 * (ind[1]-1) - np.round( x[ind[1]-1] / (np.diff( x[ ind[:2] ] ) / 30.0), 0) # [ml] SOME WEIRD -1's here...
dof = 350 - 30 * (12-ind[3]-1) - np.round( x[ind[3]] / (np.diff( x[ ind[2:4] ] ) / 30.0), 0)
grow = dof - dot
case = 8
else:
dot, dof, grow = itertools.repeat( np.array([np.nan]), 3 )
# print( "Condition unconsidered: {}".format( x.strip() ) )
return np.array([dof, dot, grow])
def open_raster( fn ):
''' cleanly open the raster '''
with rasterio.open( fn ) as rst:
arr = rst.read(1).copy()
return arr
def run_tfg_days( x ):
'''wrapper to run the tfg days using the apply_along_axis mechanics'''
out = np.full( 3, np.nan )
if not np.isnan(x).any():
vals = tfg_days( x ).squeeze()
out[[0,1,2]] = vals
return out
def run( x ):
''' run it '''
# unpack
x, out_base_fn = x
year, sub_df = x
nodata = -9999 # hardwired for SNAP data
files = sub_df.fn.tolist()
arr = np.array([ open_raster(fn) for fn in files ])
arr[ arr == nodata ] = np.nan
out_arr = np.apply_along_axis( run_tfg_days, axis=0, arr=arr )
out_arr = out_arr[:3,...] # slice it back
for idx,metric in enumerate(['dof','dot','logs']):
out_fn = out_base_fn.format(metric, metric, str(year))
dirname = os.path.dirname( out_fn )
try:
if not os.path.exists( dirname ):
_ = os.makedirs( dirname )
except:
pass
# get meta and mask for output arr and GTiff generation
with rasterio.open(files[0]) as rst:
meta = rst.meta.copy()
meta.update( compress='lzw', dtype=np.int32 )
mask = rst.read(1) == rst.nodata
# write to GTiff
with rasterio.open( out_fn, 'w', **meta ) as out:
cur_arr = out_arr[ idx, ... ]
cur_arr[ mask ] = -9999
out.write( cur_arr.astype(np.int32) , 1 )
return out_fn
def run_par_update_arr( idx ):
tmp_out = np.ctypeslib.as_array(out_shared)
i,j = idx
tmp_out[:,i,j] = run_tfg_days( arr[:,i,j] )
if __name__ == '__main__':
import os, glob, rasterio, itertools
import numpy as np
import pandas as pd
import xarray as xr
import multiprocessing as mp
from multiprocessing import sharedctypes
ncpus = 64
models = ['GFDL-CM3','GISS-E2-R','IPSL-CM5A-LR','MRI-CGCM3','NCAR-CCSM4','5ModelAvg',]
# models = ['CRU-TS40',]
scenarios = ['historical','rcp26','rcp45','rcp60','rcp85',]
# scenarios = ['historical']
for model, scenario in itertools.product( models, scenarios ):
print(model, scenario)
base_path = '/workspace/Shared/Tech_Projects/DeltaDownscaling/project_data/downscaled/{}/{}/tas'.format(model,scenario)
out_path = '/workspace/Shared/Tech_Projects/DeltaDownscaling/project_data/derived_v2_parallel/{}/{}'.format(model,scenario)
files = glob.glob(os.path.join(base_path, '*.tif'))
colnames = ['variable', 'metric', 'units', 'project', 'model', 'scenario', 'month', 'year']
df = pd.DataFrame([ os.path.basename(fn).split('.')[0].split('_')for fn in files ], columns=colnames)
df['fn'] = files
df.month = df.month.astype(int)
df.year = df.year.astype(int)
df = df.sort_values(['year', 'month']).reset_index( drop=True )
df['decade'] = df.year.apply(lambda x: str(x)[:3]+'0s')
args = list(df.groupby('decade'))
args = [ ((year,sub_df),os.path.join(out_path,'{}','{}_'+model+'_'+scenario+'_{}.tif' )) for year,sub_df in args ]
# get template file information
with rasterio.open(files[0]) as tmp:
meta = tmp.meta.copy()
shape = tmp.shape
rows,cols = shape
arr = tmp.read(1)
arr[arr == tmp.nodata] = np.nan
for arg in args:
x, out_base_fn = arg
year, sub_df = x
nodata = -9999 # hardwired for SNAP data
files = sub_df.fn.tolist()
times = pd.DatetimeIndex([ pd.Timestamp.strptime('{1}-{0}-15'.format(*os.path.basename(fn).split('.')[0].split('_')[-2:]), '%Y-%m-%d') for fn in files ])
arr = np.array([ open_raster(fn) for fn in files ])
arr[ arr == nodata ] = np.nan
# make xarray dset
ds = xr.Dataset({'dat':(['time','yc', 'xc'], arr.copy())},
coords={'xc': ('xc', np.arange(cols)),
'yc': ('yc', np.arange(rows)),
'time':times })
# groupby and average to decadal series (12 values)
da = ds.dat.groupby('time.month').mean(axis=0)
arr = da.values.copy()
del da, ds # cleanup
indexes = list(zip(*np.where(~np.isnan(arr[0]))))
# indexes = list(np.ndindex(arr.shape[-2:])) # old way
# make the output arrays?
count = 3
out = np.ctypeslib.as_ctypes(np.zeros((count,rows,cols), dtype=np.float))
out_shared = sharedctypes.RawArray(out._type_, out)
p = mp.Pool(ncpus)
p.map( run_par_update_arr, indexes )
p.close()
p.join()
# bring these c-types arrays back to numpy arrays.
out = np.ctypeslib.as_array(out_shared).astype(np.float32)
# update the np.nans to something more useable and SNAP-ish
for i in out:
i[np.isnan(arr[0])] = -9999
# dump to disk
for idx,metric in enumerate(['dof','dot','logs']):
out_fn = out_base_fn.format(metric, metric, str(year))
dirname = os.path.dirname( out_fn )
try:
if not os.path.exists( dirname ):
_ = os.makedirs( dirname )
except:
pass
# write to GTiff
meta.update( compress='lzw', dtype=np.int32, count=1, nodata=-9999 )
with rasterio.open( out_fn, 'w', **meta ) as out_rst:
cur_arr = out[ idx, ... ]
out_rst.write( cur_arr.astype(np.int32), 1 )
| [
"numpy.array",
"numpy.arange",
"os.path.exists",
"numpy.where",
"itertools.product",
"numpy.ctypeslib.as_array",
"numpy.diff",
"numpy.concatenate",
"rasterio.open",
"numpy.warnings.filterwarnings",
"os.path.dirname",
"numpy.isnan",
"numpy.sign",
"multiprocessing.sharedctypes.RawArray",
"... | [((765, 775), 'numpy.sign', 'np.sign', (['x'], {}), '(x)\n', (772, 775), True, 'import numpy as np\n'), ((946, 961), 'numpy.where', 'np.where', (['(s < 0)'], {}), '(s < 0)\n', (954, 961), True, 'import numpy as np\n'), ((5722, 5748), 'numpy.array', 'np.array', (['[dof, dot, grow]'], {}), '([dof, dot, grow])\n', (5730, 5748), True, 'import numpy as np\n'), ((6003, 6021), 'numpy.full', 'np.full', (['(3)', 'np.nan'], {}), '(3, np.nan)\n', (6010, 6021), True, 'import numpy as np\n'), ((6414, 6464), 'numpy.apply_along_axis', 'np.apply_along_axis', (['run_tfg_days'], {'axis': '(0)', 'arr': 'arr'}), '(run_tfg_days, axis=0, arr=arr)\n', (6433, 6464), True, 'import numpy as np\n'), ((7357, 7390), 'numpy.ctypeslib.as_array', 'np.ctypeslib.as_array', (['out_shared'], {}), '(out_shared)\n', (7378, 7390), True, 'import numpy as np\n'), ((7942, 7978), 'itertools.product', 'itertools.product', (['models', 'scenarios'], {}), '(models, scenarios)\n', (7959, 7978), False, 'import os, glob, rasterio, itertools\n'), ((569, 630), 'numpy.warnings.filterwarnings', 'np.warnings.filterwarnings', (['"""ignore"""'], {'category': 'RuntimeWarning'}), "('ignore', category=RuntimeWarning)\n", (595, 630), True, 'import numpy as np\n'), ((1025, 1055), 'numpy.concatenate', 'np.concatenate', (['[idx, idx + 1]'], {}), '([idx, idx + 1])\n', (1039, 1055), True, 'import numpy as np\n'), ((5818, 5835), 'rasterio.open', 'rasterio.open', (['fn'], {}), '(fn)\n', (5831, 5835), False, 'import os, glob, rasterio, itertools\n'), ((6650, 6673), 'os.path.dirname', 'os.path.dirname', (['out_fn'], {}), '(out_fn)\n', (6665, 6673), False, 'import os, glob, rasterio, itertools\n'), ((1074, 1085), 'numpy.isnan', 'np.isnan', (['x'], {}), '(x)\n', (1082, 1085), True, 'import numpy as np\n'), ((1175, 1193), 'numpy.array', 'np.array', (['[np.nan]'], {}), '([np.nan])\n', (1183, 1193), True, 'import numpy as np\n'), ((6898, 6921), 'rasterio.open', 'rasterio.open', (['files[0]'], {}), '(files[0])\n', (6911, 6921), False, 'import os, glob, rasterio, itertools\n'), ((7115, 7149), 'rasterio.open', 'rasterio.open', (['out_fn', '"""w"""'], {}), "(out_fn, 'w', **meta)\n", (7128, 7149), False, 'import os, glob, rasterio, itertools\n'), ((8308, 8340), 'os.path.join', 'os.path.join', (['base_path', '"""*.tif"""'], {}), "(base_path, '*.tif')\n", (8320, 8340), False, 'import os, glob, rasterio, itertools\n'), ((9018, 9041), 'rasterio.open', 'rasterio.open', (['files[0]'], {}), '(files[0])\n', (9031, 9041), False, 'import os, glob, rasterio, itertools\n'), ((10456, 10494), 'multiprocessing.sharedctypes.RawArray', 'sharedctypes.RawArray', (['out._type_', 'out'], {}), '(out._type_, out)\n', (10477, 10494), False, 'from multiprocessing import sharedctypes\n'), ((10511, 10525), 'multiprocessing.Pool', 'mp.Pool', (['ncpus'], {}), '(ncpus)\n', (10518, 10525), True, 'import multiprocessing as mp\n'), ((1368, 1383), 'numpy.array', 'np.array', (['[365]'], {}), '([365])\n', (1376, 1383), True, 'import numpy as np\n'), ((1516, 1531), 'numpy.array', 'np.array', (['[365]'], {}), '([365])\n', (1524, 1531), True, 'import numpy as np\n'), ((6035, 6046), 'numpy.isnan', 'np.isnan', (['x'], {}), '(x)\n', (6043, 6046), True, 'import numpy as np\n'), ((6717, 6740), 'os.path.exists', 'os.path.exists', (['dirname'], {}), '(dirname)\n', (6731, 6740), False, 'import os, glob, rasterio, itertools\n'), ((6764, 6784), 'os.makedirs', 'os.makedirs', (['dirname'], {}), '(dirname)\n', (6775, 6784), False, 'import os, glob, rasterio, itertools\n'), ((8865, 8937), 'os.path.join', 'os.path.join', (['out_path', '"""{}"""', "('{}_' + model + '_' + scenario + '_{}.tif')"], {}), "(out_path, '{}', '{}_' + model + '_' + scenario + '_{}.tif')\n", (8877, 8937), False, 'import os, glob, rasterio, itertools\n'), ((10386, 10431), 'numpy.zeros', 'np.zeros', (['(count, rows, cols)'], {'dtype': 'np.float'}), '((count, rows, cols), dtype=np.float)\n', (10394, 10431), True, 'import numpy as np\n'), ((11084, 11107), 'os.path.dirname', 'os.path.dirname', (['out_fn'], {}), '(out_fn)\n', (11099, 11107), False, 'import os, glob, rasterio, itertools\n'), ((1570, 1583), 'numpy.array', 'np.array', (['[0]'], {}), '([0])\n', (1578, 1583), True, 'import numpy as np\n'), ((10700, 10733), 'numpy.ctypeslib.as_array', 'np.ctypeslib.as_array', (['out_shared'], {}), '(out_shared)\n', (10721, 10733), True, 'import numpy as np\n'), ((10870, 10886), 'numpy.isnan', 'np.isnan', (['arr[0]'], {}), '(arr[0])\n', (10878, 10886), True, 'import numpy as np\n'), ((11442, 11476), 'rasterio.open', 'rasterio.open', (['out_fn', '"""w"""'], {}), "(out_fn, 'w', **meta)\n", (11455, 11476), False, 'import os, glob, rasterio, itertools\n'), ((2239, 2254), 'numpy.array', 'np.array', (['[350]'], {}), '([350])\n', (2247, 2254), True, 'import numpy as np\n'), ((2574, 2588), 'numpy.array', 'np.array', (['[15]'], {}), '([15])\n', (2582, 2588), True, 'import numpy as np\n'), ((11175, 11198), 'os.path.exists', 'os.path.exists', (['dirname'], {}), '(dirname)\n', (11189, 11198), False, 'import os, glob, rasterio, itertools\n'), ((11230, 11250), 'os.makedirs', 'os.makedirs', (['dirname'], {}), '(dirname)\n', (11241, 11250), False, 'import os, glob, rasterio, itertools\n'), ((9825, 9840), 'numpy.arange', 'np.arange', (['cols'], {}), '(cols)\n', (9834, 9840), True, 'import numpy as np\n'), ((9892, 9907), 'numpy.arange', 'np.arange', (['rows'], {}), '(rows)\n', (9901, 9907), True, 'import numpy as np\n'), ((3834, 3848), 'numpy.array', 'np.array', (['[15]'], {}), '([15])\n', (3842, 3848), True, 'import numpy as np\n'), ((4201, 4216), 'numpy.array', 'np.array', (['[350]'], {}), '([350])\n', (4209, 4216), True, 'import numpy as np\n'), ((4664, 4679), 'numpy.where', 'np.where', (['(s < 0)'], {}), '(s < 0)\n', (4672, 4679), True, 'import numpy as np\n'), ((10197, 10213), 'numpy.isnan', 'np.isnan', (['arr[0]'], {}), '(arr[0])\n', (10205, 10213), True, 'import numpy as np\n'), ((4741, 4754), 'numpy.array', 'np.array', (['[0]'], {}), '([0])\n', (4749, 4754), True, 'import numpy as np\n'), ((5619, 5637), 'numpy.array', 'np.array', (['[np.nan]'], {}), '([np.nan])\n', (5627, 5637), True, 'import numpy as np\n'), ((8470, 8490), 'os.path.basename', 'os.path.basename', (['fn'], {}), '(fn)\n', (8486, 8490), False, 'import os, glob, rasterio, itertools\n'), ((2175, 2194), 'numpy.diff', 'np.diff', (['x[ind[:2]]'], {}), '(x[ind[:2]])\n', (2182, 2194), True, 'import numpy as np\n'), ((2510, 2529), 'numpy.diff', 'np.diff', (['x[ind[:2]]'], {}), '(x[ind[:2]])\n', (2517, 2529), True, 'import numpy as np\n'), ((3142, 3161), 'numpy.diff', 'np.diff', (['x[ind[:2]]'], {}), '(x[ind[:2]])\n', (3149, 3161), True, 'import numpy as np\n'), ((3254, 3274), 'numpy.diff', 'np.diff', (['x[ind[2:4]]'], {}), '(x[ind[2:4]])\n', (3261, 3274), True, 'import numpy as np\n'), ((4822, 4835), 'numpy.diff', 'np.diff', (['ind2'], {}), '(ind2)\n', (4829, 4835), True, 'import numpy as np\n'), ((5208, 5225), 'numpy.append', 'np.append', (['m1', 'm2'], {}), '(m1, m2)\n', (5217, 5225), True, 'import numpy as np\n'), ((5255, 5280), 'numpy.append', 'np.append', (['ind2', '(ind2 + 1)'], {}), '(ind2, ind2 + 1)\n', (5264, 5280), True, 'import numpy as np\n'), ((4849, 4862), 'numpy.diff', 'np.diff', (['ind2'], {}), '(ind2)\n', (4856, 4862), True, 'import numpy as np\n'), ((4927, 4940), 'numpy.diff', 'np.diff', (['ind2'], {}), '(ind2)\n', (4934, 4940), True, 'import numpy as np\n'), ((5036, 5049), 'numpy.diff', 'np.diff', (['ind2'], {}), '(ind2)\n', (5043, 5049), True, 'import numpy as np\n'), ((3770, 3789), 'numpy.diff', 'np.diff', (['x[ind[:2]]'], {}), '(x[ind[:2]])\n', (3777, 3789), True, 'import numpy as np\n'), ((4137, 4157), 'numpy.diff', 'np.diff', (['x[ind[2:4]]'], {}), '(x[ind[2:4]])\n', (4144, 4157), True, 'import numpy as np\n'), ((4972, 4985), 'numpy.diff', 'np.diff', (['ind2'], {}), '(ind2)\n', (4979, 4985), True, 'import numpy as np\n'), ((5079, 5092), 'numpy.diff', 'np.diff', (['ind2'], {}), '(ind2)\n', (5086, 5092), True, 'import numpy as np\n'), ((5355, 5374), 'numpy.diff', 'np.diff', (['x[ind[:2]]'], {}), '(x[ind[:2]])\n', (5362, 5374), True, 'import numpy as np\n'), ((5486, 5506), 'numpy.diff', 'np.diff', (['x[ind[2:4]]'], {}), '(x[ind[2:4]])\n', (5493, 5506), True, 'import numpy as np\n'), ((9483, 9503), 'os.path.basename', 'os.path.basename', (['fn'], {}), '(fn)\n', (9499, 9503), False, 'import os, glob, rasterio, itertools\n')] |
import socket
import sys
import threading
import base64
import pytesseract as ocr
import numpy as np
import cv2
import struct
from PIL import Image
hostname = "redesb.space"
HOST = socket.gethostbyname(hostName) # Symbolic name meaning all available interfaces
PORT = 9666 # Arbitrary non-privileged port
HOST = socket.gethostbyname(HOST)
print(str(HOST))
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print ('Socket created')
#Bind socket to local host and port
try:
s.bind((HOST, PORT))
except socket.error as msg:
print ('Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1])
sys.exit()
print ('Socket bind complete')
# Start listening on socket
s.listen(10)
print ('Socket now listening')
# Receives base64 string and decode to jpg
def decodeImage(baseImage):
imgData = base64.b64decode(baseImage)
fileName = 'test_image.jpg'
with open(fileName, 'wb') as f:
f.write(imgData)
# Deep Learning to read the image (may be a call to other code file)
def readImage():
# tipando a leitura para os canais de ordem RGB
imagem = Image.open('test_image.jpg').convert('RGB')
# transformando pillow image para cv2 image
cimg = np.array(imagem)
cimg = cimg[:, :, ::-1].copy()
# # Visualizacaoo da imagem
# cv2.imshow('image',cimg)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
# convertendo em um array editavel de numpy[x, y, CANALS]
npimagem = np.asarray(imagem).astype(np.uint8)
# # Visualizacaoo da imagem
# cv2.imshow('image',npimagem)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
# diminuio dos ruidos antes da binarizao
npimagem[:, :, 0] = 0 # zerando o canal R (RED)
npimagem[:, :, 2] = 0 # zerando o canal B (BLUE)
# # Visualizao da imagem
# cv2.imshow('image',npimagem)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
# atribuio em escala de cinza
im = cv2.cvtColor(npimagem, cv2.COLOR_RGB2GRAY)
# # Visualizaaao da imagem
# cv2.imshow('image',im)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
# apla da truncagem binaria para a intensidade
# pixels de intensidade de cor abaixo de 127 aonvertidos para 0 (PRETO)
# pixels de intensidade de cor acima de 127 saonvertidos para 255 (BRANCO)
# A atrubiao do THRESH_OTSU incrementa uma anateligente dos nivels de truncagem
ret, thresh = cv2.threshold(im, 127, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
# Visualizaao da imagem
#cv2.imshow('image',thresh)
#cv2.waitKey(0)
#cv2.destroyAllWindows()
# reconvertendo o retorno do threshold em um objeto do tipo PIL.Image
binimagem = Image.fromarray(thresh)
# chamada ao tesseract OCR por meio de seu wrapper
phrase = ocr.image_to_string(binimagem, lang='por')
# imprao do resultado
return phrase
# Now keep talking with the client
while 1:
# Wait to accept a connection - blocking call
conn, addr = s.accept()
print ('Connected with ' + addr[0] + ':' + str(addr[1]))
final = ""
size = ""
data = conn.recv(1024)
size += data.decode('utf-8')
data = conn.recv(1024)
size += data.decode('utf-8')
size = int(size)
print(size)
# Infinite loop so that function do not terminate
while True:
#print("Looking for more")
dataImg = conn.recv(1024)
#print(data)
final += dataImg.decode('utf-8')
print(dataImg.decode('utf-8'))
size -= 1024
if size <= 0 :
print("Breaking")
break
print("Received all")
#print (final)
#print(size)
decodeImage(final)
reply = readImage()
print (reply)
#conn.sendall(str(len(reply.encode())).encode())
conn.sendall(reply.encode())
# End of Loop
conn.close()
s.close()
| [
"socket.gethostbyname",
"PIL.Image.fromarray",
"sys.exit",
"PIL.Image.open",
"socket.socket",
"cv2.threshold",
"numpy.asarray",
"base64.b64decode",
"numpy.array",
"cv2.cvtColor",
"pytesseract.image_to_string"
] | [((193, 223), 'socket.gethostbyname', 'socket.gethostbyname', (['hostName'], {}), '(hostName)\n', (213, 223), False, 'import socket\n'), ((326, 352), 'socket.gethostbyname', 'socket.gethostbyname', (['HOST'], {}), '(HOST)\n', (346, 352), False, 'import socket\n'), ((376, 425), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_STREAM'], {}), '(socket.AF_INET, socket.SOCK_STREAM)\n', (389, 425), False, 'import socket\n'), ((838, 865), 'base64.b64decode', 'base64.b64decode', (['baseImage'], {}), '(baseImage)\n', (854, 865), False, 'import base64\n'), ((1204, 1220), 'numpy.array', 'np.array', (['imagem'], {}), '(imagem)\n', (1212, 1220), True, 'import numpy as np\n'), ((1881, 1923), 'cv2.cvtColor', 'cv2.cvtColor', (['npimagem', 'cv2.COLOR_RGB2GRAY'], {}), '(npimagem, cv2.COLOR_RGB2GRAY)\n', (1893, 1923), False, 'import cv2\n'), ((2329, 2393), 'cv2.threshold', 'cv2.threshold', (['im', '(127)', '(255)', '(cv2.THRESH_BINARY | cv2.THRESH_OTSU)'], {}), '(im, 127, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)\n', (2342, 2393), False, 'import cv2\n'), ((2585, 2608), 'PIL.Image.fromarray', 'Image.fromarray', (['thresh'], {}), '(thresh)\n', (2600, 2608), False, 'from PIL import Image\n'), ((2675, 2717), 'pytesseract.image_to_string', 'ocr.image_to_string', (['binimagem'], {'lang': '"""por"""'}), "(binimagem, lang='por')\n", (2694, 2717), True, 'import pytesseract as ocr\n'), ((627, 637), 'sys.exit', 'sys.exit', ([], {}), '()\n', (635, 637), False, 'import sys\n'), ((1103, 1131), 'PIL.Image.open', 'Image.open', (['"""test_image.jpg"""'], {}), "('test_image.jpg')\n", (1113, 1131), False, 'from PIL import Image\n'), ((1437, 1455), 'numpy.asarray', 'np.asarray', (['imagem'], {}), '(imagem)\n', (1447, 1455), True, 'import numpy as np\n')] |
"""Module dedicated to framework testing."""
import pytest
import typing as t
import numpy as np
import sklearn.tree
from pymfe import _internal
from pymfe.mfe import MFE
from . import utils
GNAME = "framework-testing"
def summary_exception(values: np.ndarray,
raise_exception: bool = False) -> int:
"""Returns the length of ``values`` or raise a ValueError exception."""
if raise_exception:
raise ValueError("Summary exception raised.")
return len(values)
def summary_memory_error(values: np.ndarray,
raise_mem_err: bool = False) -> int:
"""Returns the length of ``values`` or raise a MemoryError exception."""
if raise_mem_err:
utils.raise_memory_error()
return len(values)
class MFETestClass:
"""Some generic methods for testing the MFE Framework."""
@classmethod
def postprocess_return_none(cls, **kwargs) -> None:
"""Postprocess: return None."""
return None
@classmethod
def postprocess_return_new_feature(
cls,
number_of_lists: int = 3,
**kwargs) -> t.Tuple[t.List, t.List, t.List]:
"""Postprocess: return Tuple of lists."""
return tuple(["test_value"] for _ in range(number_of_lists))
@classmethod
def postprocess_raise_exception(cls,
raise_exception: bool = False,
**kwargs) -> None:
"""Posprocess: raise exception."""
if raise_exception:
raise ValueError("Expected exception (postprocess).")
return None
@classmethod
def postprocess_memory_error(cls,
raise_mem_err: bool = False,
**kwargs) -> t.Optional[np.ndarray]:
"""Posprocess: memory error."""
if raise_mem_err:
return utils.raise_memory_error()
@classmethod
def precompute_return_empty(cls, **kwargs) -> t.Dict[str, t.Any]:
"""Precompute: return empty dictionary."""
precomp_vals = {}
return precomp_vals
@classmethod
def precompute_return_something(cls, **kwargs) -> t.Dict[str, t.Any]:
"""Precompute: return empty dictionary."""
precomp_vals = {
"test_param_1": 0,
"test_param_2": "euclidean",
"test_param_3": list,
"test_param_4": abs,
}
return precomp_vals
@classmethod
def precompute_raise_exception(cls,
raise_exception: bool = False,
**kwargs) -> t.Dict[str, t.Any]:
"""Precompute: raise exception."""
precomp_vals = {}
if raise_exception:
raise ValueError("Expected exception (precompute).")
return precomp_vals
@classmethod
def precompute_memory_error(cls,
raise_mem_err: bool = False,
**kwargs) -> None:
"""Precompute: memory error."""
precomp_vals = {}
if raise_mem_err:
precomp_vals["huge_array"] = utils.raise_memory_error()
return precomp_vals
@classmethod
def ft_valid_number(cls, X: np.ndarray, y: np.ndarray) -> float:
"""Metafeature: float type."""
return 0.0
@classmethod
def ft_valid_array(cls, X: np.ndarray, y: np.ndarray) -> np.ndarray:
"""Metafeature: float type."""
return np.zeros(5)
@classmethod
def ft_raise_exception(cls, X: np.ndarray, y: np.ndarray,
raise_exception: False) -> float:
"""Metafeature: float type."""
if raise_exception:
raise ValueError("Expected exception (feature).")
return -1.0
@classmethod
def ft_memory_error(cls,
raise_mem_err: bool = False,
**kwargs) -> np.ndarray:
"""Metafeature: memory error."""
if raise_mem_err:
return utils.raise_memory_error()
return np.array([1, 2, 3])
class TestArchitecture:
"""Tests for the framework architecture."""
def test_summary_valid1(self):
vals = np.arange(5)
res = _internal.summarize(features=vals,
callable_sum=summary_exception)
assert res == len(vals)
def test_summary_valid2(self):
vals = np.arange(5)
res = _internal.summarize(features=vals,
callable_sum=summary_memory_error)
assert res == len(vals)
def test_summary_invalid1(self):
res = _internal.summarize(features=np.arange(5),
callable_sum=summary_exception,
callable_args={"raise_exception": True})
assert np.isnan(res)
def test_summary_invalid2(self):
res = _internal.summarize(features=np.arange(5),
callable_sum=summary_memory_error,
callable_args={"raise_mem_err": True})
assert np.isnan(res)
def test_postprocessing_valid(self):
"""Test valid postprocessing and its automatic detection."""
results = [], [], []
_internal.post_processing(results=results,
groups=tuple(),
custom_class_=MFETestClass)
assert all(map(lambda l: len(l) > 0, results))
def test_preprocessing_valid(self):
"""Test valid precomputation and its automatic detection."""
precomp_args = _internal.process_precomp_groups(
precomp_groups=tuple(), groups=tuple(), custom_class_=MFETestClass)
assert len(precomp_args) > 0
def test_feature_detection(self):
"""Test automatic dectection of metafeature extraction method."""
name, mtd, groups = _internal.process_features(
features="all",
groups=tuple(),
suppress_warnings=True,
custom_class_=MFETestClass)
assert len(name) == 4 and len(mtd) == 4 and len(groups) == 1
def test_get_groups(self):
model = MFE()
res = model.valid_groups()
assert (len(res) == len(_internal.VALID_GROUPS)
and not set(res).symmetric_difference(_internal.VALID_GROUPS))
def test_metafeature_description(self):
desc, _ = MFE.metafeature_description(print_table=False)
groups = [d[0] for d in desc]
assert len(set(groups)) == len(_internal.VALID_GROUPS)
desc, _ = MFE.metafeature_description(sort_by_group=True,
sort_by_mtf=True,
print_table=False,
include_references=True)
mtf = [d[1] for d in desc]
assert mtf[1][0] < mtf[-1][0]
desc = MFE.metafeature_description()
assert desc is None
def test_metafeature_description_exceptions(self):
"""Test metafeature description exceptions"""
with pytest.raises(TypeError):
MFE.metafeature_description(print_table="False")
with pytest.raises(TypeError):
MFE.metafeature_description(sort_by_mtf=1)
with pytest.raises(TypeError):
MFE.metafeature_description(sort_by_group=[True])
def test_default_alias_groups(self):
model = MFE(groups="default")
res = model.valid_groups()
assert (len(res) == len(_internal.VALID_GROUPS)
and not set(res).symmetric_difference(_internal.VALID_GROUPS))
model = MFE(groups=["default"])
res = model.valid_groups()
assert (len(res) == len(_internal.VALID_GROUPS)
and not set(res).symmetric_difference(_internal.VALID_GROUPS))
model = MFE(groups=["general", "default"])
res = model.valid_groups()
assert (len(res) == len(_internal.VALID_GROUPS)
and not set(res).symmetric_difference(_internal.VALID_GROUPS))
@pytest.mark.parametrize("groups, summary", [
("statistical", "all"),
("general", "all"),
("landmarking", "all"),
("relative", "all"),
("model-based", "all"),
("info-theory", "all"),
("statistical", ("mean", "sd")),
("general", ("mean", "sd")),
("landmarking", ("mean", "sd")),
("model-based", ("mean", "sd")),
("general", ("mean", "histogram")),
("landmarking", ("mean", "histogram")),
("model-based", ("mean", "histogram")),
("general", ("quantiles", "histogram")),
("landmarking", ("quantiles", "histogram")),
("model-based", ("quantiles", "histogram")),
(["general", "relative"], ("mean", "sd")),
(["general", "relative"], ("quantiles", "histogram")),
(["landmarking", "relative"], ("mean", "sd")),
(["landmarking", "relative"], ("quantiles", "histogram")),
(["statistical", "landmarking", "relative"], ("mean", "sd")),
("all", "all"),
])
def test_extract_metafeature_names_supervised(self, groups, summary):
"""Test .extract_metafeature_names method."""
X, y = utils.load_xy(0)
mfe = MFE(groups=groups, summary=summary)
mtf_names_1 = mfe.extract_metafeature_names(supervised=True)
mtf_names_2 = mfe.fit(X.values, y.values).extract(suppress_warnings=True)[0]
assert mtf_names_1 == tuple(mtf_names_2)
@pytest.mark.parametrize("groups, summary", [
("statistical", "all"),
("general", "all"),
("landmarking", "all"),
("relative", "all"),
("model-based", "all"),
("info-theory", "all"),
("statistical", ("mean", "sd")),
("general", ("mean", "sd")),
("landmarking", ("mean", "sd")),
("model-based", ("mean", "sd")),
("general", ("mean", "histogram")),
("landmarking", ("mean", "histogram")),
("model-based", ("mean", "histogram")),
("general", ("quantiles", "histogram")),
("landmarking", ("quantiles", "histogram")),
("model-based", ("quantiles", "histogram")),
(["general", "relative"], ("mean", "sd")),
(["general", "relative"], ("quantiles", "histogram")),
(["landmarking", "relative"], ("mean", "sd")),
(["landmarking", "relative"], ("quantiles", "histogram")),
(["statistical", "landmarking", "relative"], ("mean", "sd")),
("all", "all"),
])
def test_extract_metafeature_names_unsupervised_01(self, groups, summary):
"""Test .extract_metafeature_names method."""
X, _ = utils.load_xy(0)
mfe = MFE(groups=groups, summary=summary)
mtf_names_1 = mfe.extract_metafeature_names(supervised=False)
mtf_names_2 = mfe.fit(X.values).extract(suppress_warnings=True)[0]
assert mtf_names_1 == tuple(mtf_names_2)
@pytest.mark.parametrize("groups, summary", [
("general", "all"),
("statistical", ("mean", "sd")),
(["general", "relative"], ("mean", "sd")),
(["general", "relative"], ("quantiles", "histogram")),
(["landmarking", "relative"], ("mean", "sd")),
(["landmarking", "relative"], ("quantiles", "histogram")),
(["statistical", "landmarking", "relative"], ("mean", "sd")),
("all", "all"),
])
def test_extract_metafeature_names_unsupervised_02(self, groups, summary):
"""Test .extract_metafeature_names method."""
X, _ = utils.load_xy(0)
mfe = MFE(groups=groups, summary=summary)
mtf_names_1 = mfe.fit(X.values).extract(suppress_warnings=True)[0]
# Note: by default, .extract_metafeature_names should check wether
# 'y' was fitted or not if .fit was called before. Therefore, here,
# supervised=True is expected to be ignored and behave like
# supervised=False.
mtf_names_2 = mfe.extract_metafeature_names(supervised=True)
mtf_names_3 = mfe.extract_metafeature_names(supervised=False)
assert tuple(mtf_names_1) == mtf_names_2 == mtf_names_3
@pytest.mark.parametrize("groups", [
"statistical",
"general",
"landmarking",
"relative",
"model-based",
"info-theory",
("statistical", "landmarking"),
("landmarking", "relative"),
("general", "model-based", "statistical"),
("statistical", "statistical"),
])
def test_parse_valid_metafeatures(self, groups):
"""Check the length of valid metafeatures per group."""
X, y = utils.load_xy(0)
mfe = MFE(groups="all",
summary=None,
lm_sample_frac=0.5,
random_state=1234)
mfe.fit(X.values, y.values)
res = mfe.extract()
target_mtf = mfe.valid_metafeatures(groups=groups)
names, _ = mfe.parse_by_group(groups, res)
assert not set(names).symmetric_difference(target_mtf)
def test_no_cat_transformation(self):
X, y = utils.load_xy(1)
mfe = MFE()
mfe.fit(X.values, y.values, transform_cat=None)
assert mfe._custom_args_ft["N"].size == 0
def test_gray_encoding_missing_value(self):
X, y = utils.load_xy(1)
mfe = MFE()
X = np.copy(X.values)
y = y.values
X[5, 0] = np.nan
with pytest.raises(ValueError):
mfe.fit(X, y, transform_cat="gray")
def test_one_hot_encoding_01(self):
X, y = utils.load_xy(1)
mfe = MFE()
mfe.fit(X.values, y.values, transform_cat="one-hot")
exp_value = np.sum([np.unique(attr).size - 1 for attr in X.values.T])
assert mfe._custom_args_ft["N"].shape[1] == exp_value
def test_one_hot_encoding_02(self):
X, y = utils.load_xy(1)
mfe = MFE()
mfe.fit(X.values, y.values, transform_cat="one-hot-full")
exp_value = np.sum([np.unique(attr).size for attr in X.values.T])
assert mfe._custom_args_ft["N"].shape[1] == exp_value
def test_one_hot_encoding_03(self):
X, y = utils.load_xy(2)
mfe = MFE()
mfe.fit(X.values, y.values, transform_cat="one-hot")
exp_value = X.values.shape[1]
assert mfe._custom_args_ft["N"].shape[1] == exp_value
def test_one_hot_encoding_04(self):
X, y = utils.load_xy(2)
mfe = MFE()
X = np.hstack((X.values, np.ones((y.size, 1), dtype=str)))
y = y.values
with pytest.raises(ValueError):
mfe.fit(X=X, y=y, transform_cat="one-hot")
@pytest.mark.parametrize("confidence", (0.95, 0.99))
def test_extract_with_confidence(self, confidence):
X, y = utils.load_xy(2)
mtf_names, mtf_vals, mtf_conf_int = MFE(
groups="all",
features=["mean", "best_node", "sil"],
random_state=1234).fit(
X=X.values, y=y.values, precomp_groups=None).extract_with_confidence(
sample_num=64,
return_avg_val=False,
confidence=confidence,
verbose=0)
in_range_prop = np.zeros(len(mtf_names), dtype=float)
for mtf_ind, cur_mtf_vals in enumerate(mtf_vals):
int_low, int_high = mtf_conf_int[mtf_ind, :]
in_range_prop[mtf_ind] = np.sum(np.logical_and(
int_low <= cur_mtf_vals, cur_mtf_vals <= int_high)) / len(cur_mtf_vals)
assert np.all(confidence - 0.05 <= in_range_prop)
def test_extract_with_confidence_invalid1(self):
with pytest.raises(TypeError):
MFE().extract_with_confidence()
def test_extract_with_confidence_invalid2(self):
X, y = utils.load_xy(2)
with pytest.raises(ValueError):
MFE().fit(
X.values, y.values).extract_with_confidence(confidence=-0.0001)
def test_extract_with_confidence_invalid3(self):
X, y = utils.load_xy(2)
with pytest.raises(ValueError):
MFE().fit(
X.values, y.values).extract_with_confidence(confidence=1.0001)
@pytest.mark.parametrize("return_avg_val", (True, False))
def test_extract_with_confidence_time(self, return_avg_val):
X, y = utils.load_xy(2)
res = MFE(
features=["mean", "nr_inst", "unknown"],
measure_time="avg").fit(
X=X.values, y=y.values).extract_with_confidence(
sample_num=3,
return_avg_val=return_avg_val)
mtf_names, mtf_vals, mtf_time, mtf_conf_int = res
assert (len(mtf_names) == len(mtf_vals) == len(mtf_time) == len(mtf_conf_int))
def test_extract_with_confidence_multiple_conf_level(self):
X, y = utils.load_xy(2)
confidence = [0.8, 0.9, 0.7]
mtf_conf_int = MFE(
features=["mean", "nr_inst", "unknown"]).fit(
X=X.values, y=y.values).extract_with_confidence(
sample_num=2,
confidence=confidence)[2]
assert 2 * len(confidence) == mtf_conf_int.shape[1]
def test_extract_with_confidence_random_state1(self):
X, y = utils.load_xy(2)
_, mtf_vals_1, mtf_conf_int_1 = MFE(
features=["mean", "sd"], random_state=16).fit(
X=X.values, y=y.values).extract_with_confidence(
sample_num=3)
_, mtf_vals_2, mtf_conf_int_2 = MFE(
features=["mean", "sd"], random_state=16).fit(
X=X.values, y=y.values).extract_with_confidence(
sample_num=3)
assert (np.allclose(mtf_vals_1, mtf_vals_2) and
np.allclose(mtf_conf_int_1, mtf_conf_int_2))
def test_extract_with_confidence_random_state2(self):
X, y = utils.load_xy(2)
_, mtf_vals_1, mtf_conf_int_1 = MFE(
features=["mean", "sd"], random_state=16).fit(
X=X.values, y=y.values).extract_with_confidence(
sample_num=3)
_, mtf_vals_2, mtf_conf_int_2 = MFE(
features=["mean", "sd"], random_state=17).fit(
X=X.values, y=y.values).extract_with_confidence(
sample_num=3)
assert (np.any(~np.isclose(mtf_vals_1, mtf_vals_2)) and
np.any(~np.isclose(mtf_conf_int_1, mtf_conf_int_2)))
def test_extract_with_confidence_random_state3(self):
X, y = utils.load_xy(2)
np.random.seed(1234)
_, mtf_vals_1, mtf_conf_int_1 = MFE(
features=["mean", "sd"]).fit(
X=X.values, y=y.values).extract_with_confidence(
sample_num=3)
np.random.seed(1234)
_, mtf_vals_2, mtf_conf_int_2 = MFE(
features=["mean", "sd"]).fit(
X=X.values, y=y.values).extract_with_confidence(
sample_num=3)
assert (np.any(~np.isclose(mtf_vals_1, mtf_vals_2)) and
np.any(~np.isclose(mtf_conf_int_1, mtf_conf_int_2)))
def test_extract_from_model(self):
X, y = utils.load_xy(2)
model = sklearn.tree.DecisionTreeClassifier(random_state=1234).fit(
X.values, y.values)
mtf_name, mtf_vals = MFE(random_state=1234).extract_from_model(model)
extractor = MFE(groups="model-based", random_state=1234)
extractor.fit(X=X.values, y=y.values, transform_num=False)
mtf_name2, mtf_vals2 = extractor.extract()
assert (np.all(mtf_name == mtf_name2)
and np.allclose(mtf_vals, mtf_vals2))
def test_extract_from_model_invalid1(self):
X, y = utils.load_xy(2)
model = sklearn.tree.DecisionTreeRegressor().fit(X.values, y.values)
with pytest.raises(TypeError):
MFE().extract_from_model(model)
def test_extract_from_model_invalid2(self):
X, y = utils.load_xy(2)
model = sklearn.tree.DecisionTreeClassifier(random_state=1234).fit(
X.values, y.values)
with pytest.raises(KeyError):
MFE().extract_from_model(model, arguments_fit={"dt_model": model})
def test_extract_from_model_invalid3(self):
model = sklearn.tree.DecisionTreeClassifier()
with pytest.raises(RuntimeError):
MFE().extract_from_model(model)
def test_extract_from_model_invalid4(self):
X, y = utils.load_xy(2)
model = sklearn.tree.DecisionTreeClassifier().fit(X, y)
with pytest.raises(ValueError):
MFE(groups="general").extract_from_model(model)
class TestArchitectureWarnings:
def test_feature_warning1(self):
"""Test exception handling of feature extraction."""
name, mtd, groups = map(
np.asarray,
_internal.process_features(features="raise_exception",
groups=tuple(),
suppress_warnings=True,
custom_class_=MFETestClass))
with pytest.warns(RuntimeWarning):
_internal.get_feat_value(mtd_name=name[0],
mtd_args={
"X": np.array([]),
"y": np.ndarray([]),
"raise_exception": True
},
mtd_callable=mtd[0][1],
suppress_warnings=False)
def test_feature_warning2(self):
"""Test memory error handling of feature extraction."""
name, mtd, groups = map(
np.asarray,
_internal.process_features(features="memory_error",
groups=tuple(),
suppress_warnings=True,
custom_class_=MFETestClass))
with pytest.warns(RuntimeWarning):
_internal.get_feat_value(mtd_name=name[0],
mtd_args={
"X": np.array([]),
"y": np.ndarray([]),
"raise_mem_err": True
},
mtd_callable=mtd[0][1],
suppress_warnings=False)
def test_mem_err_precompute(self):
with pytest.warns(UserWarning):
_internal.process_precomp_groups(precomp_groups=tuple(),
groups=tuple(),
custom_class_=MFETestClass,
raise_mem_err=True)
def test_mem_err_postprocess(self):
"""Test memory error in postprocessing methods."""
results = [], [], []
with pytest.warns(UserWarning):
_internal.post_processing(results=results,
groups=tuple(),
custom_class_=MFETestClass,
raise_mem_err=True)
def test_postprocessing_invalid1(self):
"""Test exception handling in invalid postprocessing."""
results = [], [], []
with pytest.warns(UserWarning):
_internal.post_processing(results=results,
groups=tuple(),
custom_class_=MFETestClass,
raise_exception=True)
def test_postprocessing_invalid2(self):
"""Test incorrect return value in postprocessing methods."""
results = [], [], []
with pytest.warns(UserWarning):
_internal.post_processing(results=results,
groups=tuple(),
custom_class_=MFETestClass,
number_of_lists=2)
def test_preprocessing_invalid(self):
"""Test exception handling of precomputation."""
with pytest.warns(UserWarning):
_internal.process_precomp_groups(precomp_groups=tuple(),
groups=tuple(),
custom_class_=MFETestClass,
raise_exception=True)
| [
"pymfe._internal.summarize",
"numpy.array",
"numpy.arange",
"numpy.random.seed",
"pymfe.mfe.MFE",
"numpy.allclose",
"numpy.ones",
"numpy.isnan",
"pytest.raises",
"numpy.copy",
"numpy.isclose",
"pymfe.mfe.MFE.metafeature_description",
"numpy.unique",
"numpy.logical_and",
"pytest.mark.para... | [((8086, 8979), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""groups, summary"""', "[('statistical', 'all'), ('general', 'all'), ('landmarking', 'all'), (\n 'relative', 'all'), ('model-based', 'all'), ('info-theory', 'all'), (\n 'statistical', ('mean', 'sd')), ('general', ('mean', 'sd')), (\n 'landmarking', ('mean', 'sd')), ('model-based', ('mean', 'sd')), (\n 'general', ('mean', 'histogram')), ('landmarking', ('mean', 'histogram'\n )), ('model-based', ('mean', 'histogram')), ('general', ('quantiles',\n 'histogram')), ('landmarking', ('quantiles', 'histogram')), (\n 'model-based', ('quantiles', 'histogram')), (['general', 'relative'], (\n 'mean', 'sd')), (['general', 'relative'], ('quantiles', 'histogram')),\n (['landmarking', 'relative'], ('mean', 'sd')), (['landmarking',\n 'relative'], ('quantiles', 'histogram')), (['statistical',\n 'landmarking', 'relative'], ('mean', 'sd')), ('all', 'all')]"], {}), "('groups, summary', [('statistical', 'all'), (\n 'general', 'all'), ('landmarking', 'all'), ('relative', 'all'), (\n 'model-based', 'all'), ('info-theory', 'all'), ('statistical', ('mean',\n 'sd')), ('general', ('mean', 'sd')), ('landmarking', ('mean', 'sd')), (\n 'model-based', ('mean', 'sd')), ('general', ('mean', 'histogram')), (\n 'landmarking', ('mean', 'histogram')), ('model-based', ('mean',\n 'histogram')), ('general', ('quantiles', 'histogram')), ('landmarking',\n ('quantiles', 'histogram')), ('model-based', ('quantiles', 'histogram')\n ), (['general', 'relative'], ('mean', 'sd')), (['general', 'relative'],\n ('quantiles', 'histogram')), (['landmarking', 'relative'], ('mean',\n 'sd')), (['landmarking', 'relative'], ('quantiles', 'histogram')), ([\n 'statistical', 'landmarking', 'relative'], ('mean', 'sd')), ('all', 'all')]\n )\n", (8109, 8979), False, 'import pytest\n'), ((9530, 10423), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""groups, summary"""', "[('statistical', 'all'), ('general', 'all'), ('landmarking', 'all'), (\n 'relative', 'all'), ('model-based', 'all'), ('info-theory', 'all'), (\n 'statistical', ('mean', 'sd')), ('general', ('mean', 'sd')), (\n 'landmarking', ('mean', 'sd')), ('model-based', ('mean', 'sd')), (\n 'general', ('mean', 'histogram')), ('landmarking', ('mean', 'histogram'\n )), ('model-based', ('mean', 'histogram')), ('general', ('quantiles',\n 'histogram')), ('landmarking', ('quantiles', 'histogram')), (\n 'model-based', ('quantiles', 'histogram')), (['general', 'relative'], (\n 'mean', 'sd')), (['general', 'relative'], ('quantiles', 'histogram')),\n (['landmarking', 'relative'], ('mean', 'sd')), (['landmarking',\n 'relative'], ('quantiles', 'histogram')), (['statistical',\n 'landmarking', 'relative'], ('mean', 'sd')), ('all', 'all')]"], {}), "('groups, summary', [('statistical', 'all'), (\n 'general', 'all'), ('landmarking', 'all'), ('relative', 'all'), (\n 'model-based', 'all'), ('info-theory', 'all'), ('statistical', ('mean',\n 'sd')), ('general', ('mean', 'sd')), ('landmarking', ('mean', 'sd')), (\n 'model-based', ('mean', 'sd')), ('general', ('mean', 'histogram')), (\n 'landmarking', ('mean', 'histogram')), ('model-based', ('mean',\n 'histogram')), ('general', ('quantiles', 'histogram')), ('landmarking',\n ('quantiles', 'histogram')), ('model-based', ('quantiles', 'histogram')\n ), (['general', 'relative'], ('mean', 'sd')), (['general', 'relative'],\n ('quantiles', 'histogram')), (['landmarking', 'relative'], ('mean',\n 'sd')), (['landmarking', 'relative'], ('quantiles', 'histogram')), ([\n 'statistical', 'landmarking', 'relative'], ('mean', 'sd')), ('all', 'all')]\n )\n", (9553, 10423), False, 'import pytest\n'), ((10970, 11372), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""groups, summary"""', "[('general', 'all'), ('statistical', ('mean', 'sd')), (['general',\n 'relative'], ('mean', 'sd')), (['general', 'relative'], ('quantiles',\n 'histogram')), (['landmarking', 'relative'], ('mean', 'sd')), ([\n 'landmarking', 'relative'], ('quantiles', 'histogram')), ([\n 'statistical', 'landmarking', 'relative'], ('mean', 'sd')), ('all', 'all')]"], {}), "('groups, summary', [('general', 'all'), (\n 'statistical', ('mean', 'sd')), (['general', 'relative'], ('mean', 'sd'\n )), (['general', 'relative'], ('quantiles', 'histogram')), ([\n 'landmarking', 'relative'], ('mean', 'sd')), (['landmarking',\n 'relative'], ('quantiles', 'histogram')), (['statistical',\n 'landmarking', 'relative'], ('mean', 'sd')), ('all', 'all')])\n", (10993, 11372), False, 'import pytest\n'), ((12170, 12437), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""groups"""', "['statistical', 'general', 'landmarking', 'relative', 'model-based',\n 'info-theory', ('statistical', 'landmarking'), ('landmarking',\n 'relative'), ('general', 'model-based', 'statistical'), ('statistical',\n 'statistical')]"], {}), "('groups', ['statistical', 'general', 'landmarking',\n 'relative', 'model-based', 'info-theory', ('statistical', 'landmarking'\n ), ('landmarking', 'relative'), ('general', 'model-based',\n 'statistical'), ('statistical', 'statistical')])\n", (12193, 12437), False, 'import pytest\n'), ((14644, 14695), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""confidence"""', '(0.95, 0.99)'], {}), "('confidence', (0.95, 0.99))\n", (14667, 14695), False, 'import pytest\n'), ((16172, 16228), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""return_avg_val"""', '(True, False)'], {}), "('return_avg_val', (True, False))\n", (16195, 16228), False, 'import pytest\n'), ((3489, 3500), 'numpy.zeros', 'np.zeros', (['(5)'], {}), '(5)\n', (3497, 3500), True, 'import numpy as np\n'), ((4070, 4089), 'numpy.array', 'np.array', (['[1, 2, 3]'], {}), '([1, 2, 3])\n', (4078, 4089), True, 'import numpy as np\n'), ((4214, 4226), 'numpy.arange', 'np.arange', (['(5)'], {}), '(5)\n', (4223, 4226), True, 'import numpy as np\n'), ((4242, 4308), 'pymfe._internal.summarize', '_internal.summarize', ([], {'features': 'vals', 'callable_sum': 'summary_exception'}), '(features=vals, callable_sum=summary_exception)\n', (4261, 4308), False, 'from pymfe import _internal\n'), ((4427, 4439), 'numpy.arange', 'np.arange', (['(5)'], {}), '(5)\n', (4436, 4439), True, 'import numpy as np\n'), ((4455, 4524), 'pymfe._internal.summarize', '_internal.summarize', ([], {'features': 'vals', 'callable_sum': 'summary_memory_error'}), '(features=vals, callable_sum=summary_memory_error)\n', (4474, 4524), False, 'from pymfe import _internal\n'), ((4844, 4857), 'numpy.isnan', 'np.isnan', (['res'], {}), '(res)\n', (4852, 4857), True, 'import numpy as np\n'), ((5111, 5124), 'numpy.isnan', 'np.isnan', (['res'], {}), '(res)\n', (5119, 5124), True, 'import numpy as np\n'), ((6189, 6194), 'pymfe.mfe.MFE', 'MFE', ([], {}), '()\n', (6192, 6194), False, 'from pymfe.mfe import MFE\n'), ((6428, 6474), 'pymfe.mfe.MFE.metafeature_description', 'MFE.metafeature_description', ([], {'print_table': '(False)'}), '(print_table=False)\n', (6455, 6474), False, 'from pymfe.mfe import MFE\n'), ((6595, 6708), 'pymfe.mfe.MFE.metafeature_description', 'MFE.metafeature_description', ([], {'sort_by_group': '(True)', 'sort_by_mtf': '(True)', 'print_table': '(False)', 'include_references': '(True)'}), '(sort_by_group=True, sort_by_mtf=True,\n print_table=False, include_references=True)\n', (6622, 6708), False, 'from pymfe.mfe import MFE\n'), ((6932, 6961), 'pymfe.mfe.MFE.metafeature_description', 'MFE.metafeature_description', ([], {}), '()\n', (6959, 6961), False, 'from pymfe.mfe import MFE\n'), ((7455, 7476), 'pymfe.mfe.MFE', 'MFE', ([], {'groups': '"""default"""'}), "(groups='default')\n", (7458, 7476), False, 'from pymfe.mfe import MFE\n'), ((7664, 7687), 'pymfe.mfe.MFE', 'MFE', ([], {'groups': "['default']"}), "(groups=['default'])\n", (7667, 7687), False, 'from pymfe.mfe import MFE\n'), ((7875, 7909), 'pymfe.mfe.MFE', 'MFE', ([], {'groups': "['general', 'default']"}), "(groups=['general', 'default'])\n", (7878, 7909), False, 'from pymfe.mfe import MFE\n'), ((9283, 9318), 'pymfe.mfe.MFE', 'MFE', ([], {'groups': 'groups', 'summary': 'summary'}), '(groups=groups, summary=summary)\n', (9286, 9318), False, 'from pymfe.mfe import MFE\n'), ((10732, 10767), 'pymfe.mfe.MFE', 'MFE', ([], {'groups': 'groups', 'summary': 'summary'}), '(groups=groups, summary=summary)\n', (10735, 10767), False, 'from pymfe.mfe import MFE\n'), ((11601, 11636), 'pymfe.mfe.MFE', 'MFE', ([], {'groups': 'groups', 'summary': 'summary'}), '(groups=groups, summary=summary)\n', (11604, 11636), False, 'from pymfe.mfe import MFE\n'), ((12676, 12746), 'pymfe.mfe.MFE', 'MFE', ([], {'groups': '"""all"""', 'summary': 'None', 'lm_sample_frac': '(0.5)', 'random_state': '(1234)'}), "(groups='all', summary=None, lm_sample_frac=0.5, random_state=1234)\n", (12679, 12746), False, 'from pymfe.mfe import MFE\n'), ((13131, 13136), 'pymfe.mfe.MFE', 'MFE', ([], {}), '()\n', (13134, 13136), False, 'from pymfe.mfe import MFE\n'), ((13338, 13343), 'pymfe.mfe.MFE', 'MFE', ([], {}), '()\n', (13341, 13343), False, 'from pymfe.mfe import MFE\n'), ((13357, 13374), 'numpy.copy', 'np.copy', (['X.values'], {}), '(X.values)\n', (13364, 13374), True, 'import numpy as np\n'), ((13598, 13603), 'pymfe.mfe.MFE', 'MFE', ([], {}), '()\n', (13601, 13603), False, 'from pymfe.mfe import MFE\n'), ((13894, 13899), 'pymfe.mfe.MFE', 'MFE', ([], {}), '()\n', (13897, 13899), False, 'from pymfe.mfe import MFE\n'), ((14191, 14196), 'pymfe.mfe.MFE', 'MFE', ([], {}), '()\n', (14194, 14196), False, 'from pymfe.mfe import MFE\n'), ((14447, 14452), 'pymfe.mfe.MFE', 'MFE', ([], {}), '()\n', (14450, 14452), False, 'from pymfe.mfe import MFE\n'), ((15527, 15569), 'numpy.all', 'np.all', (['(confidence - 0.05 <= in_range_prop)'], {}), '(confidence - 0.05 <= in_range_prop)\n', (15533, 15569), True, 'import numpy as np\n'), ((18511, 18531), 'numpy.random.seed', 'np.random.seed', (['(1234)'], {}), '(1234)\n', (18525, 18531), True, 'import numpy as np\n'), ((18727, 18747), 'numpy.random.seed', 'np.random.seed', (['(1234)'], {}), '(1234)\n', (18741, 18747), True, 'import numpy as np\n'), ((19349, 19393), 'pymfe.mfe.MFE', 'MFE', ([], {'groups': '"""model-based"""', 'random_state': '(1234)'}), "(groups='model-based', random_state=1234)\n", (19352, 19393), False, 'from pymfe.mfe import MFE\n'), ((7113, 7137), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (7126, 7137), False, 'import pytest\n'), ((7151, 7199), 'pymfe.mfe.MFE.metafeature_description', 'MFE.metafeature_description', ([], {'print_table': '"""False"""'}), "(print_table='False')\n", (7178, 7199), False, 'from pymfe.mfe import MFE\n'), ((7214, 7238), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (7227, 7238), False, 'import pytest\n'), ((7252, 7294), 'pymfe.mfe.MFE.metafeature_description', 'MFE.metafeature_description', ([], {'sort_by_mtf': '(1)'}), '(sort_by_mtf=1)\n', (7279, 7294), False, 'from pymfe.mfe import MFE\n'), ((7309, 7333), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (7322, 7333), False, 'import pytest\n'), ((7347, 7396), 'pymfe.mfe.MFE.metafeature_description', 'MFE.metafeature_description', ([], {'sort_by_group': '[True]'}), '(sort_by_group=[True])\n', (7374, 7396), False, 'from pymfe.mfe import MFE\n'), ((13436, 13461), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (13449, 13461), False, 'import pytest\n'), ((14556, 14581), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (14569, 14581), False, 'import pytest\n'), ((15637, 15661), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (15650, 15661), False, 'import pytest\n'), ((15807, 15832), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (15820, 15832), False, 'import pytest\n'), ((16037, 16062), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (16050, 16062), False, 'import pytest\n'), ((17677, 17712), 'numpy.allclose', 'np.allclose', (['mtf_vals_1', 'mtf_vals_2'], {}), '(mtf_vals_1, mtf_vals_2)\n', (17688, 17712), True, 'import numpy as np\n'), ((17733, 17776), 'numpy.allclose', 'np.allclose', (['mtf_conf_int_1', 'mtf_conf_int_2'], {}), '(mtf_conf_int_1, mtf_conf_int_2)\n', (17744, 17776), True, 'import numpy as np\n'), ((19529, 19558), 'numpy.all', 'np.all', (['(mtf_name == mtf_name2)'], {}), '(mtf_name == mtf_name2)\n', (19535, 19558), True, 'import numpy as np\n'), ((19579, 19611), 'numpy.allclose', 'np.allclose', (['mtf_vals', 'mtf_vals2'], {}), '(mtf_vals, mtf_vals2)\n', (19590, 19611), True, 'import numpy as np\n'), ((19786, 19810), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (19799, 19810), False, 'import pytest\n'), ((20060, 20083), 'pytest.raises', 'pytest.raises', (['KeyError'], {}), '(KeyError)\n', (20073, 20083), False, 'import pytest\n'), ((20281, 20308), 'pytest.raises', 'pytest.raises', (['RuntimeError'], {}), '(RuntimeError)\n', (20294, 20308), False, 'import pytest\n'), ((20514, 20539), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (20527, 20539), False, 'import pytest\n'), ((21057, 21085), 'pytest.warns', 'pytest.warns', (['RuntimeWarning'], {}), '(RuntimeWarning)\n', (21069, 21085), False, 'import pytest\n'), ((21963, 21991), 'pytest.warns', 'pytest.warns', (['RuntimeWarning'], {}), '(RuntimeWarning)\n', (21975, 21991), False, 'import pytest\n'), ((22497, 22522), 'pytest.warns', 'pytest.warns', (['UserWarning'], {}), '(UserWarning)\n', (22509, 22522), False, 'import pytest\n'), ((22935, 22960), 'pytest.warns', 'pytest.warns', (['UserWarning'], {}), '(UserWarning)\n', (22947, 22960), False, 'import pytest\n'), ((23348, 23373), 'pytest.warns', 'pytest.warns', (['UserWarning'], {}), '(UserWarning)\n', (23360, 23373), False, 'import pytest\n'), ((23767, 23792), 'pytest.warns', 'pytest.warns', (['UserWarning'], {}), '(UserWarning)\n', (23779, 23792), False, 'import pytest\n'), ((24139, 24164), 'pytest.warns', 'pytest.warns', (['UserWarning'], {}), '(UserWarning)\n', (24151, 24164), False, 'import pytest\n'), ((4673, 4685), 'numpy.arange', 'np.arange', (['(5)'], {}), '(5)\n', (4682, 4685), True, 'import numpy as np\n'), ((4939, 4951), 'numpy.arange', 'np.arange', (['(5)'], {}), '(5)\n', (4948, 4951), True, 'import numpy as np\n'), ((14487, 14518), 'numpy.ones', 'np.ones', (['(y.size, 1)'], {'dtype': 'str'}), '((y.size, 1), dtype=str)\n', (14494, 14518), True, 'import numpy as np\n'), ((19279, 19301), 'pymfe.mfe.MFE', 'MFE', ([], {'random_state': '(1234)'}), '(random_state=1234)\n', (19282, 19301), False, 'from pymfe.mfe import MFE\n'), ((13995, 14010), 'numpy.unique', 'np.unique', (['attr'], {}), '(attr)\n', (14004, 14010), True, 'import numpy as np\n'), ((15407, 15472), 'numpy.logical_and', 'np.logical_and', (['(int_low <= cur_mtf_vals)', '(cur_mtf_vals <= int_high)'], {}), '(int_low <= cur_mtf_vals, cur_mtf_vals <= int_high)\n', (15421, 15472), True, 'import numpy as np\n'), ((15675, 15680), 'pymfe.mfe.MFE', 'MFE', ([], {}), '()\n', (15678, 15680), False, 'from pymfe.mfe import MFE\n'), ((18302, 18336), 'numpy.isclose', 'np.isclose', (['mtf_vals_1', 'mtf_vals_2'], {}), '(mtf_vals_1, mtf_vals_2)\n', (18312, 18336), True, 'import numpy as np\n'), ((18366, 18408), 'numpy.isclose', 'np.isclose', (['mtf_conf_int_1', 'mtf_conf_int_2'], {}), '(mtf_conf_int_1, mtf_conf_int_2)\n', (18376, 18408), True, 'import numpy as np\n'), ((18959, 18993), 'numpy.isclose', 'np.isclose', (['mtf_vals_1', 'mtf_vals_2'], {}), '(mtf_vals_1, mtf_vals_2)\n', (18969, 18993), True, 'import numpy as np\n'), ((19023, 19065), 'numpy.isclose', 'np.isclose', (['mtf_conf_int_1', 'mtf_conf_int_2'], {}), '(mtf_conf_int_1, mtf_conf_int_2)\n', (19033, 19065), True, 'import numpy as np\n'), ((19824, 19829), 'pymfe.mfe.MFE', 'MFE', ([], {}), '()\n', (19827, 19829), False, 'from pymfe.mfe import MFE\n'), ((20097, 20102), 'pymfe.mfe.MFE', 'MFE', ([], {}), '()\n', (20100, 20102), False, 'from pymfe.mfe import MFE\n'), ((20322, 20327), 'pymfe.mfe.MFE', 'MFE', ([], {}), '()\n', (20325, 20327), False, 'from pymfe.mfe import MFE\n'), ((20553, 20574), 'pymfe.mfe.MFE', 'MFE', ([], {'groups': '"""general"""'}), "(groups='general')\n", (20556, 20574), False, 'from pymfe.mfe import MFE\n'), ((13694, 13709), 'numpy.unique', 'np.unique', (['attr'], {}), '(attr)\n', (13703, 13709), True, 'import numpy as np\n'), ((14829, 14904), 'pymfe.mfe.MFE', 'MFE', ([], {'groups': '"""all"""', 'features': "['mean', 'best_node', 'sil']", 'random_state': '(1234)'}), "(groups='all', features=['mean', 'best_node', 'sil'], random_state=1234)\n", (14832, 14904), False, 'from pymfe.mfe import MFE\n'), ((16341, 16405), 'pymfe.mfe.MFE', 'MFE', ([], {'features': "['mean', 'nr_inst', 'unknown']", 'measure_time': '"""avg"""'}), "(features=['mean', 'nr_inst', 'unknown'], measure_time='avg')\n", (16344, 16405), False, 'from pymfe.mfe import MFE\n'), ((17293, 17338), 'pymfe.mfe.MFE', 'MFE', ([], {'features': "['mean', 'sd']", 'random_state': '(16)'}), "(features=['mean', 'sd'], random_state=16)\n", (17296, 17338), False, 'from pymfe.mfe import MFE\n'), ((17497, 17542), 'pymfe.mfe.MFE', 'MFE', ([], {'features': "['mean', 'sd']", 'random_state': '(16)'}), "(features=['mean', 'sd'], random_state=16)\n", (17500, 17542), False, 'from pymfe.mfe import MFE\n'), ((17910, 17955), 'pymfe.mfe.MFE', 'MFE', ([], {'features': "['mean', 'sd']", 'random_state': '(16)'}), "(features=['mean', 'sd'], random_state=16)\n", (17913, 17955), False, 'from pymfe.mfe import MFE\n'), ((18114, 18159), 'pymfe.mfe.MFE', 'MFE', ([], {'features': "['mean', 'sd']", 'random_state': '(17)'}), "(features=['mean', 'sd'], random_state=17)\n", (18117, 18159), False, 'from pymfe.mfe import MFE\n'), ((18572, 18600), 'pymfe.mfe.MFE', 'MFE', ([], {'features': "['mean', 'sd']"}), "(features=['mean', 'sd'])\n", (18575, 18600), False, 'from pymfe.mfe import MFE\n'), ((18788, 18816), 'pymfe.mfe.MFE', 'MFE', ([], {'features': "['mean', 'sd']"}), "(features=['mean', 'sd'])\n", (18791, 18816), False, 'from pymfe.mfe import MFE\n'), ((21236, 21248), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (21244, 21248), True, 'import numpy as np\n'), ((21296, 21310), 'numpy.ndarray', 'np.ndarray', (['[]'], {}), '([])\n', (21306, 21310), True, 'import numpy as np\n'), ((22142, 22154), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (22150, 22154), True, 'import numpy as np\n'), ((22202, 22216), 'numpy.ndarray', 'np.ndarray', (['[]'], {}), '([])\n', (22212, 22216), True, 'import numpy as np\n'), ((15846, 15851), 'pymfe.mfe.MFE', 'MFE', ([], {}), '()\n', (15849, 15851), False, 'from pymfe.mfe import MFE\n'), ((16076, 16081), 'pymfe.mfe.MFE', 'MFE', ([], {}), '()\n', (16079, 16081), False, 'from pymfe.mfe import MFE\n'), ((16892, 16936), 'pymfe.mfe.MFE', 'MFE', ([], {'features': "['mean', 'nr_inst', 'unknown']"}), "(features=['mean', 'nr_inst', 'unknown'])\n", (16895, 16936), False, 'from pymfe.mfe import MFE\n')] |
"""This submodule handles all interaction with the LALSuite C API.
It provides a class for inputs and a class for outputs and functions for
reading/writing/comparing them. The inputs method has a 'run' method
for calling the C API.
"""
import numpy as np
import glob
import math
import lal_cuda
# Generate mocks for these if we are building for RTD
lal = lal_cuda.import_mock_RTD("lal")
lalsimulation = lal_cuda.import_mock_RTD("lalsimulation")
# Define a set of default model parameters. These are the ones in the
# 'default' fiducial inputs file in the 'data' directory.
chi1_default = 0.1
chi2_default = 0.2
m1_default = 30
m2_default = 30
chip_default = 0.34
thetaJ_default = 1.1
alpha0_default = 1.5
distance_default = 1000
phic_default = np.pi * 0.4
fref_default = 30
flow_default = 20
fhigh_default = 80
def to_string(inputs, outputs):
"""Convert a paired set of inputs/outputs to an ASCII table.
:param inputs: An instance of the inputs class.
:param outputs: An associated instance of the outputs class.
:return: A list of strings.
"""
r_val = '# Column 01: frequency\n'
r_val += '# 02: hp - real\n'
r_val += '# 03: hp - imaginary\n'
r_val += '# 04: hc - real\n'
r_val += '# 05: hc - imaginary\n'
for f_i, hp_i, hc_i in zip(inputs.freqs, outputs.hp, outputs.hc):
r_val += "%8.2f %12.5e %12.5e %12.5e %12.5e\n" % (f_i, hp_i.real, hp_i.imag, hc_i.real, hc_i.imag)
return r_val
def to_binary(inputs, outputs, filename_label=None):
"""Convert a paired set of inputs/outputs to binary files.
:param inputs: An instance of the inputs class.
:param outputs: An associated instance of the outputs class.
:param filename_label: An optional label for the output files.
:return: None
"""
inputs.write(filename_label, filename_label=filename_label)
outputs.write(filename_label, filename_label=filename_label)
def calc_frac_diff(x, y):
"""Calculate the fractional difference between two numbers.
If the reference value is 0 and the value to check is not, returns 1.
:param x: Value to check
:param y: Reference value
:return: Value
"""
if(y != 0):
return math.fabs((x - y) / y)
elif(x != 0.):
return 1.
else:
return 0.
def calc_difference_from_reference(inputs, outputs, verbose=True):
"""Look for a match between the given inputs and the stored reference
inputs. If found return a dictionary with absolute differences from the
given outputs, otherwise print a warning to stdout if verbose=True.
All reference inputs/outputs were computed by running the
PhenomPCore script of this package against a version of LALSuite
compiled from the commit with hash "3494e18e6d".
:param inputs: An instance of the inputs class
:param outputs: An associated instance of the outputs class
:param verbose: Boolean controlling whether logging information is reported
:return: None
"""
# Get a list of reference input/output files
filename_ref_inputs = glob.glob(lal_cuda.full_path_datafile("inputs.dat*"))
filename_ref_outputs = [
filename_ref_input_i.replace(
"inputs.dat",
"outputs.dat") for filename_ref_input_i in filename_ref_inputs]
# Look to see if the given inputs are in the stored reference inputs
filename_ref_output = None
for filename_ref_input_i, filename_ref_output_i in zip(filename_ref_inputs, filename_ref_outputs):
inputs_i = inputs.read(filename_ref_input_i)
# Check to see if this set of inputs matches the set that has been passed
if(inputs_i == inputs):
inputs_ref = inputs_i
filename_ref_output = filename_ref_output_i
break
# Perform check if a match has been found
if(not filename_ref_output):
lal_cuda.log.warning(
"Checking could not be performed: reference data set with given inputs (%s) not found." %
(inputs))
else:
if(verbose):
lal_cuda.log.open('Performing test...')
# Read reference dataset's outputs
outputs_ref = outputs.read(filename_ref_output)
# Compute statistics of difference from test reference
hpval_real_diff_avg = 0.
hpval_imag_diff_avg = 0.
hcval_real_diff_avg = 0.
hcval_imag_diff_avg = 0.
hpval_real_diff_max = 0.
hpval_imag_diff_max = 0.
hcval_real_diff_max = 0.
hcval_imag_diff_max = 0.
for (hp_i, hc_i, hp_ref_i, hc_ref_i) in zip(outputs.hp, outputs.hc, outputs_ref.hp, outputs_ref.hc):
hpval_real_diff_i = calc_frac_diff(hp_i.real, hp_ref_i.real)
hpval_imag_diff_i = calc_frac_diff(hp_i.imag, hp_ref_i.imag)
hcval_real_diff_i = calc_frac_diff(hc_i.real, hc_ref_i.real)
hcval_imag_diff_i = calc_frac_diff(hc_i.imag, hc_ref_i.imag)
hpval_real_diff_avg += hpval_real_diff_i
hpval_imag_diff_avg += hpval_imag_diff_i
hcval_real_diff_avg += hcval_real_diff_i
hcval_imag_diff_avg += hcval_imag_diff_i
hpval_real_diff_max = max([hpval_real_diff_max, hpval_real_diff_i])
hpval_imag_diff_max = max([hpval_imag_diff_max, hpval_imag_diff_i])
hcval_real_diff_max = max([hcval_real_diff_max, hcval_real_diff_i])
hcval_imag_diff_max = max([hcval_imag_diff_max, hcval_imag_diff_i])
hpval_real_diff_avg /= float(len(outputs.hp))
hpval_imag_diff_avg /= float(len(outputs.hp))
hcval_real_diff_avg /= float(len(outputs.hc))
hcval_imag_diff_avg /= float(len(outputs.hc))
# Report results
if(verbose):
lal_cuda.log.comment(' Average/maximum real(hp) fractional difference: %.2e/%.2e' %
(hpval_real_diff_avg, hpval_real_diff_max))
lal_cuda.log.comment(' Average/maximum imag(hp) fractional difference: %.2e/%.2e' %
(hpval_imag_diff_avg, hpval_imag_diff_max))
lal_cuda.log.comment(' Average/maximum real(hc) fractional difference: %.2e/%.2e' %
(hcval_real_diff_avg, hcval_real_diff_max))
lal_cuda.log.comment(' Average/maximum imag(hc) fractional difference: %.2e/%.2e' %
(hcval_imag_diff_avg, hcval_imag_diff_max))
lal_cuda.log.close("Done.")
return {
'hpval_real_diff_avg': hpval_real_diff_avg,
'hpval_real_diff_max': hpval_real_diff_max,
'hpval_imag_diff_avg': hpval_imag_diff_avg,
'hpval_imag_diff_max': hpval_imag_diff_max,
'hcval_real_diff_avg': hcval_real_diff_avg,
'hcval_real_diff_max': hcval_real_diff_max,
'hcval_imag_diff_avg': hcval_imag_diff_avg,
'hcval_imag_diff_max': hcval_imag_diff_max}
class outputs(object):
"""This class manages the output (hp and hc complex arrays) from a LALSUite
model call.
An instance can be created using the default constructor or the
:func:`read` method. An instance can be written using the
:func:`write` method. Equivalence of two instances is defined by
the element-wise equivalence of their hp and hc arrays.
"""
def __init__(self, return_from_SimIMRPhenomPFrequencySequence=None, hp=None, hc=None):
"""Create an instance of the outputs class. Optionally pass complex
arrays hp and hc to initialize from.
:param return_from_SimIMRPhenomPFrequencySequence: The data structure returned from the LALSUite C API.
:param hp: Complex floating point array
:param hc: Complex floating point array
"""
if((isinstance(hp, np.ndarray)) and (isinstance(hc, np.ndarray)) and (isinstance(return_from_SimIMRPhenomPFrequencySequence, type(None)))):
self.hp = hp
self.hc = hc
elif((isinstance(hp, type(None))) and (isinstance(hc, type(None))) and not (isinstance(return_from_SimIMRPhenomPFrequencySequence, type(None)))):
self.hp = return_from_SimIMRPhenomPFrequencySequence[0].data.data
self.hc = return_from_SimIMRPhenomPFrequencySequence[1].data.data
else:
lal_cuda.log.error("Invalid inputs to SimIMRPhenomPFrequencySequence outputs constructor.")
exit(1)
@classmethod
def read(cls, filename_datafile_in):
"""Create an instance of the outputs class from a binary file.
:param filename_datafile_in: Filename to read from.
:return: An instance of the outputs class.
"""
with open(lal_cuda.full_path_datafile(filename_datafile_in), "rb") as outputs_file:
n_freqs = np.asscalar(np.fromfile(outputs_file, dtype=np.int32, count=1))
hp = np.fromfile(outputs_file, dtype=np.complex128, count=n_freqs)
hc = np.fromfile(outputs_file, dtype=np.complex128, count=n_freqs)
return(cls(hp=hp, hc=hc))
def write(self, filename_outputs_out, filename_label=None, verbose=True):
"""Write the instance of the output class to a binary file.
:param filename_outputs_out: Filename to write to.
:param filename_label: Filename modifier.
:param verbose: Boolean flag indicating whether to write activity to the log.
:return: None
"""
# Set filename
if(filename_label):
filename_outputs_out = "outputs.dat." + filename_label
else:
filename_outputs_out = "outputs.dat"
if(verbose):
lal_cuda.log.open("Writing outputs to '%s'..." % (filename_outputs_out), end='')
with open(filename_outputs_out, "wb") as outputs_file:
np.array([len(self.hp)], dtype=np.int32).tofile(outputs_file)
self.hp.tofile(outputs_file)
self.hc.tofile(outputs_file)
if(verbose):
lal_cuda.log.close("Done.")
def __eq__(self, other):
"""Test for equivalence of two sets of outputs."""
return np.array_equal(self.hp, other.hp) and np.array_equal(self.hc, other.hc)
def __ne__(self, other):
"""Overrides the default implementation (unnecessary in Python 3)"""
return not self.__eq__(other)
class inputs(object):
def __init__(
self,
chi1=chi1_default,
chi2=chi2_default,
m1=m1_default,
m2=m2_default,
chip=chip_default,
thetaJ=thetaJ_default,
alpha0=alpha0_default,
distance=distance_default,
phic=phic_default,
fref=fref_default,
mode=1,
freqs=[
flow_default,
fhigh_default,
-1],
freqs_from_range=True,
convert_units=True):
"""Create an instance of the inputs class, for a given set of model
parameters.
:param chi1: See LALSuite documentation for a description of this model parameter.
:param chi2: See LALSuite documentation for a description of this model parameter.
:param m1: See LALSuite documentation for a description of this model parameter.
:param m2: See LALSuite documentation for a description of this model parameter.
:param chip: See LALSuite documentation for a description of this model parameter.
:param thetaJ: See LALSuite documentation for a description of this model parameter.
:param alpha0: See LALSuite documentation for a description of this model parameter.
:param distance: See LALSuite documentation for a description of this model parameter.
:param phic: See LALSuite documentation for a description of this model parameter.
:param fref: See LALSuite documentation for a description of this model parameter.
:param mode: See LALSuite documentation for a description of this model parameter.
:param freqs: Frequency array (either an element-wise array, or a 3-element description of range)
:param freqs_from_range: Set to True if the freqs describes a range, rather than an element-wise array
:param convert_units:
"""
self.chi1 = chi1
self.chi2 = chi2
self.m1 = m1
self.m2 = m2
self.distance = distance
self.thetaJ = thetaJ
self.alpha0 = alpha0
self.chip = chip
self.phic = phic
self.fref = fref
self.mode = mode
# Perform unit conversions, if requested
if(convert_units):
self.m1 = self.m1 * lal.lal.MSUN_SI
self.m2 = self.m2 * lal.lal.MSUN_SI
self.distance = self.distance * lal.lal.PC_SI * 100 * 1e6
# Generate frequency array
if(freqs_from_range):
flow = freqs[0]
fhigh = freqs[1]
n_freqs = freqs[2]
# If n_freqs<1, then assum dfreq=1.
if(n_freqs < 1):
self.freqs = np.linspace(flow, fhigh, (fhigh - flow) + 1)
self.n_freqs = len(self.freqs)
else:
self.n_freqs = n_freqs
self.freqs = np.linspace(flow, fhigh, self.n_freqs)
# If freqs_from_range is false, then assume that freqs specifies a list of frequencies
else:
self.freqs = freqs
self.n_freqs = len(self.freqs)
def np_floats(self):
"""A numpy array of all floating-point inputs.
:return: A numpy array of floats.
"""
# A numpy-array packaging of the floating-point input parameters
return np.array([self.chi1, self.chi2, self.chip, self.thetaJ, self.m1, self.m2,
self.distance, self.alpha0, self.phic, self.fref], dtype=np.float64)
def np_ints(self):
"""A numpy array of all integer inputs.
:return: A numpy array of integers.
"""
# A numpy-array packaging of the integer input parameters
return np.array([self.mode, self.n_freqs], dtype=np.int32)
@classmethod
def read(cls, filename_datafile_in):
"""Create an instance of a inputs method from a binary file.
:param filename_datafile_in: Filename storing inputs.
:return: A object of class inputs
"""
with open(lal_cuda.full_path_datafile(filename_datafile_in), "rb") as inputs_file:
# Read floating-point parameters
inputs_np_floats = np.fromfile(inputs_file, dtype=np.float64, count=len(cls().np_floats()))
chi1 = inputs_np_floats[0]
chi2 = inputs_np_floats[1]
chip = inputs_np_floats[2]
thetaJ = inputs_np_floats[3]
m1 = inputs_np_floats[4]
m2 = inputs_np_floats[5]
distance = inputs_np_floats[6]
alpha0 = inputs_np_floats[7]
phic = inputs_np_floats[8]
fref = inputs_np_floats[9]
# Read integer-type parameters
inputs_np_ints = np.fromfile(inputs_file, dtype=np.int32, count=len(cls().np_ints()))
mode = int(inputs_np_ints[0])
n_freqs = int(inputs_np_ints[1])
# Read frequency array
freqs = np.fromfile(inputs_file, dtype=np.float64, count=n_freqs)
return(cls(chi1=chi1, chi2=chi2, m1=m1, m2=m2, chip=chip, thetaJ=thetaJ, alpha0=alpha0, distance=distance, phic=phic, fref=fref, mode=mode, freqs=freqs, freqs_from_range=False, convert_units=False))
def write(self, filename_inputs_out, filename_label=None, verbose=True):
"""Write an instance of an object of class inputs to a binary file.
:param filename_inputs_out: Filename to write to
:param filename_label: Filename modifier.
:param verbose: Boolean flag indicating whether to write activity to the log.
:return:
"""
# Set filename
if(filename_label):
filename_inputs_out = "inputs.dat." + filename_label
else:
filename_inputs_out = "inputs.dat"
if(verbose):
lal_cuda.log.open("Writing inputs to '%s'..." % (filename_inputs_out), end='')
with open(filename_inputs_out, "wb") as inputs_file:
self.np_floats().tofile(inputs_file)
self.np_ints().tofile(inputs_file)
self.freqs.tofile(inputs_file)
if(verbose):
lal_cuda.log.close("Done.")
def run(self, buf=None, legacy=False):
"""Call the C-compiled model in lalsuite.
If legacy is true, then assume that the compiled version of
lalsuite we are using does not have PhenomP buffer support.
:param buf: A buffer, as generated by the ADACS version of LALSuite
:param legacy: True if using a version of LALSuite not compiled with the ADACS GPU buffer support
:return: An instance of the outputs class
"""
if(legacy):
return(outputs(return_from_SimIMRPhenomPFrequencySequence=lalsimulation.SimIMRPhenomPFrequencySequence(
self.freqs,
self.chi1,
self.chi2,
self.chip,
self.thetaJ,
self.m1,
self.m2,
self.distance,
self.alpha0,
self.phic,
self.fref,
self.mode,
None)))
# ... else, assume that we are working with a version of PhenomP that does have buffer support
else:
return(outputs(return_from_SimIMRPhenomPFrequencySequence=lalsimulation.SimIMRPhenomPFrequencySequence(
self.freqs,
self.chi1,
self.chi2,
self.chip,
self.thetaJ,
self.m1,
self.m2,
self.distance,
self.alpha0,
self.phic,
self.fref,
self.mode,
None,
buf)))
def __str__(self):
"""Return a string representation of the parameter set."""
return "chi1=%e chi2=%e m1=%e m2=%e distance=%e thetaJ=%e alpha0=%e chip=%e phic=%e fref=%e mode=%d freqs=[%e...%e]" % (
self.chi1, self.chi2, self.m1 / lal.lal.MSUN_SI, self.m2 / lal.lal.MSUN_SI, self.distance / (lal.lal.PC_SI * 100 * 1e6), self.thetaJ, self.alpha0, self.chip, self.phic, self.fref, self.mode, self.freqs[0], self.freqs[-1])
def __eq__(self, other):
"""Test for equivalence of two sets of inputs."""
return np.array_equal(
self.np_floats(),
other.np_floats()) and np.array_equal(
self.np_ints(),
other.np_ints()) and np.array_equal(
self.freqs,
other.freqs)
def __ne__(self, other):
"""Overrides the default implementation (unnecessary in Python 3)"""
return not self.__eq__(other)
| [
"numpy.fromfile",
"lal_cuda.log.error",
"lal_cuda.import_mock_RTD",
"lal_cuda.log.warning",
"numpy.array",
"lal_cuda.log.comment",
"lal_cuda.log.open",
"math.fabs",
"numpy.array_equal",
"numpy.linspace",
"lal_cuda.log.close",
"lal_cuda.full_path_datafile"
] | [((360, 391), 'lal_cuda.import_mock_RTD', 'lal_cuda.import_mock_RTD', (['"""lal"""'], {}), "('lal')\n", (384, 391), False, 'import lal_cuda\n'), ((408, 449), 'lal_cuda.import_mock_RTD', 'lal_cuda.import_mock_RTD', (['"""lalsimulation"""'], {}), "('lalsimulation')\n", (432, 449), False, 'import lal_cuda\n'), ((2221, 2243), 'math.fabs', 'math.fabs', (['((x - y) / y)'], {}), '((x - y) / y)\n', (2230, 2243), False, 'import math\n'), ((3094, 3136), 'lal_cuda.full_path_datafile', 'lal_cuda.full_path_datafile', (['"""inputs.dat*"""'], {}), "('inputs.dat*')\n", (3121, 3136), False, 'import lal_cuda\n'), ((3879, 4007), 'lal_cuda.log.warning', 'lal_cuda.log.warning', (["('Checking could not be performed: reference data set with given inputs (%s) not found.'\n % inputs)"], {}), "(\n 'Checking could not be performed: reference data set with given inputs (%s) not found.'\n % inputs)\n", (3899, 4007), False, 'import lal_cuda\n'), ((13648, 13794), 'numpy.array', 'np.array', (['[self.chi1, self.chi2, self.chip, self.thetaJ, self.m1, self.m2, self.\n distance, self.alpha0, self.phic, self.fref]'], {'dtype': 'np.float64'}), '([self.chi1, self.chi2, self.chip, self.thetaJ, self.m1, self.m2,\n self.distance, self.alpha0, self.phic, self.fref], dtype=np.float64)\n', (13656, 13794), True, 'import numpy as np\n'), ((14026, 14077), 'numpy.array', 'np.array', (['[self.mode, self.n_freqs]'], {'dtype': 'np.int32'}), '([self.mode, self.n_freqs], dtype=np.int32)\n', (14034, 14077), True, 'import numpy as np\n'), ((4068, 4107), 'lal_cuda.log.open', 'lal_cuda.log.open', (['"""Performing test..."""'], {}), "('Performing test...')\n", (4085, 4107), False, 'import lal_cuda\n'), ((5744, 5883), 'lal_cuda.log.comment', 'lal_cuda.log.comment', (["(' Average/maximum real(hp) fractional difference: %.2e/%.2e' % (\n hpval_real_diff_avg, hpval_real_diff_max))"], {}), "(\n ' Average/maximum real(hp) fractional difference: %.2e/%.2e' % (\n hpval_real_diff_avg, hpval_real_diff_max))\n", (5764, 5883), False, 'import lal_cuda\n'), ((5919, 6058), 'lal_cuda.log.comment', 'lal_cuda.log.comment', (["(' Average/maximum imag(hp) fractional difference: %.2e/%.2e' % (\n hpval_imag_diff_avg, hpval_imag_diff_max))"], {}), "(\n ' Average/maximum imag(hp) fractional difference: %.2e/%.2e' % (\n hpval_imag_diff_avg, hpval_imag_diff_max))\n", (5939, 6058), False, 'import lal_cuda\n'), ((6094, 6233), 'lal_cuda.log.comment', 'lal_cuda.log.comment', (["(' Average/maximum real(hc) fractional difference: %.2e/%.2e' % (\n hcval_real_diff_avg, hcval_real_diff_max))"], {}), "(\n ' Average/maximum real(hc) fractional difference: %.2e/%.2e' % (\n hcval_real_diff_avg, hcval_real_diff_max))\n", (6114, 6233), False, 'import lal_cuda\n'), ((6269, 6408), 'lal_cuda.log.comment', 'lal_cuda.log.comment', (["(' Average/maximum imag(hc) fractional difference: %.2e/%.2e' % (\n hcval_imag_diff_avg, hcval_imag_diff_max))"], {}), "(\n ' Average/maximum imag(hc) fractional difference: %.2e/%.2e' % (\n hcval_imag_diff_avg, hcval_imag_diff_max))\n", (6289, 6408), False, 'import lal_cuda\n'), ((6444, 6471), 'lal_cuda.log.close', 'lal_cuda.log.close', (['"""Done."""'], {}), "('Done.')\n", (6462, 6471), False, 'import lal_cuda\n'), ((8859, 8920), 'numpy.fromfile', 'np.fromfile', (['outputs_file'], {'dtype': 'np.complex128', 'count': 'n_freqs'}), '(outputs_file, dtype=np.complex128, count=n_freqs)\n', (8870, 8920), True, 'import numpy as np\n'), ((8938, 8999), 'numpy.fromfile', 'np.fromfile', (['outputs_file'], {'dtype': 'np.complex128', 'count': 'n_freqs'}), '(outputs_file, dtype=np.complex128, count=n_freqs)\n', (8949, 8999), True, 'import numpy as np\n'), ((9626, 9704), 'lal_cuda.log.open', 'lal_cuda.log.open', (['("Writing outputs to \'%s\'..." % filename_outputs_out)'], {'end': '""""""'}), '("Writing outputs to \'%s\'..." % filename_outputs_out, end=\'\')\n', (9643, 9704), False, 'import lal_cuda\n'), ((9959, 9986), 'lal_cuda.log.close', 'lal_cuda.log.close', (['"""Done."""'], {}), "('Done.')\n", (9977, 9986), False, 'import lal_cuda\n'), ((10091, 10124), 'numpy.array_equal', 'np.array_equal', (['self.hp', 'other.hp'], {}), '(self.hp, other.hp)\n', (10105, 10124), True, 'import numpy as np\n'), ((10129, 10162), 'numpy.array_equal', 'np.array_equal', (['self.hc', 'other.hc'], {}), '(self.hc, other.hc)\n', (10143, 10162), True, 'import numpy as np\n'), ((15240, 15297), 'numpy.fromfile', 'np.fromfile', (['inputs_file'], {'dtype': 'np.float64', 'count': 'n_freqs'}), '(inputs_file, dtype=np.float64, count=n_freqs)\n', (15251, 15297), True, 'import numpy as np\n'), ((16093, 16169), 'lal_cuda.log.open', 'lal_cuda.log.open', (['("Writing inputs to \'%s\'..." % filename_inputs_out)'], {'end': '""""""'}), '("Writing inputs to \'%s\'..." % filename_inputs_out, end=\'\')\n', (16110, 16169), False, 'import lal_cuda\n'), ((16405, 16432), 'lal_cuda.log.close', 'lal_cuda.log.close', (['"""Done."""'], {}), "('Done.')\n", (16423, 16432), False, 'import lal_cuda\n'), ((18720, 18759), 'numpy.array_equal', 'np.array_equal', (['self.freqs', 'other.freqs'], {}), '(self.freqs, other.freqs)\n', (18734, 18759), True, 'import numpy as np\n'), ((8298, 8394), 'lal_cuda.log.error', 'lal_cuda.log.error', (['"""Invalid inputs to SimIMRPhenomPFrequencySequence outputs constructor."""'], {}), "(\n 'Invalid inputs to SimIMRPhenomPFrequencySequence outputs constructor.')\n", (8316, 8394), False, 'import lal_cuda\n'), ((8682, 8731), 'lal_cuda.full_path_datafile', 'lal_cuda.full_path_datafile', (['filename_datafile_in'], {}), '(filename_datafile_in)\n', (8709, 8731), False, 'import lal_cuda\n'), ((8790, 8840), 'numpy.fromfile', 'np.fromfile', (['outputs_file'], {'dtype': 'np.int32', 'count': '(1)'}), '(outputs_file, dtype=np.int32, count=1)\n', (8801, 8840), True, 'import numpy as np\n'), ((13024, 13066), 'numpy.linspace', 'np.linspace', (['flow', 'fhigh', '(fhigh - flow + 1)'], {}), '(flow, fhigh, fhigh - flow + 1)\n', (13035, 13066), True, 'import numpy as np\n'), ((13202, 13240), 'numpy.linspace', 'np.linspace', (['flow', 'fhigh', 'self.n_freqs'], {}), '(flow, fhigh, self.n_freqs)\n', (13213, 13240), True, 'import numpy as np\n'), ((14341, 14390), 'lal_cuda.full_path_datafile', 'lal_cuda.full_path_datafile', (['filename_datafile_in'], {}), '(filename_datafile_in)\n', (14368, 14390), False, 'import lal_cuda\n')] |
import numpy as np
import gym
from gym.spaces import Discrete
from gym import utils
from gym.utils import seeding
class State:
ZERO = 0
ONE = 1
TWO = 2
THREE = 3
FOUR = 4
class Action:
A = 0
B = 1
class Chain(gym.Env, utils.EzPickle):
def __init__(self, random_slip_prob=True,
slip_prob_a=0.2, slip_prob_b=0.2,
slip_prob_low=0.0, slip_prob_high=1.0, semitied=False):
self.nS = 5
self.nA = 2
self.semitied = semitied
self.slip_prob = dict()
# Default
self.slip_prob[Action.A] = slip_prob_a
self.slip_prob[Action.B] = slip_prob_b
self.random_slip_prob = random_slip_prob
self.slip_prob_low = slip_prob_low
self.slip_prob_high = slip_prob_high
self.action_space = Discrete(self.nA)
self.observation_space = Discrete(self.nS)
self.horizon = 100
self.t = 0
self.seed()
self.reset()
def render(self, mode='human'):
pass
def seed(self, seed=None):
self.np_random, seed = seeding.np_random(seed)
return [seed]
def reset(self):
self.t = 0
if self.random_slip_prob:
# if self.semitied:
# for key in self.slip_prob:
# self.slip_prob[key] = self.np_random.uniform(
# self.slip_prob_low, self.slip_prob_high)
# else:
# prob = self.np_random.uniform(
# self.slip_prob_low, self.slip_prob_high)
# for key in self.slip_prob:
# self.slip_prob[key] = prob
slip_prob = np.random.choice(np.array([0.1,0.2,0.3,0.4,0.5]))
for key in self.slip_prob:
self.slip_prob[key] = slip_prob
# for key in self.slip_prob:
# self.slip_prob[key] = 0.2
self.state = State.ZERO
return self.state
def step(self, action):
self.t += 1
if self.t == self.horizon:
done = True
else:
done = False
if action != Action.A and action != Action.B:
raise ValueError("Unknown action {}".format(action))
r = self.np_random.uniform(0, 1)
slip = False
if action == Action.A:
if r <= self.slip_prob[Action.A]:
action = Action.B
slip = True
elif action == Action.B:
if r < self.slip_prob[Action.B]:
action = Action.A
slip = True
else:
raise ValueError
if action == Action.A:
reward = 0
state = self.state + 1
if state == self.nS:
state = State.FOUR
reward = 1
elif action == Action.B:
reward = 0.2
state = State.ZERO
self.state = state
return state, reward, done, {"slip":slip}
if __name__ == "__main__":
env = Chain()
state = env.reset()
import IPython; IPython.embed()
| [
"numpy.array",
"IPython.embed",
"gym.spaces.Discrete",
"gym.utils.seeding.np_random"
] | [((3025, 3040), 'IPython.embed', 'IPython.embed', ([], {}), '()\n', (3038, 3040), False, 'import IPython\n'), ((807, 824), 'gym.spaces.Discrete', 'Discrete', (['self.nA'], {}), '(self.nA)\n', (815, 824), False, 'from gym.spaces import Discrete\n'), ((858, 875), 'gym.spaces.Discrete', 'Discrete', (['self.nS'], {}), '(self.nS)\n', (866, 875), False, 'from gym.spaces import Discrete\n'), ((1078, 1101), 'gym.utils.seeding.np_random', 'seeding.np_random', (['seed'], {}), '(seed)\n', (1095, 1101), False, 'from gym.utils import seeding\n'), ((1674, 1709), 'numpy.array', 'np.array', (['[0.1, 0.2, 0.3, 0.4, 0.5]'], {}), '([0.1, 0.2, 0.3, 0.4, 0.5])\n', (1682, 1709), True, 'import numpy as np\n')] |
import cv2
import numpy as np
import scipy
from scipy import fftpack, signal
from sklearn.neighbors import ball_tree
from scipy.sparse import spdiags
import matplotlib.pyplot as plt
def sinc_psf(window_size=15, edge=15/4):
x = np.expand_dims(np.linspace(-edge, edge, window_size),axis=0)
s = np.sinc(x.T @ x)
s = s / s.sum()
return s
# based on tutorial 2
def gaussian_psf(size, std=1):
edge = size // 2
ax = np.linspace(-edge, edge, num=size)
xx, yy = np.meshgrid(ax, ax)
kernel = np.exp(-(xx ** 2 + yy ** 2) / (2 * std **2))
return kernel / kernel.sum()
# extracting patches based on tutorial 8
def make_patches(image, patch_size, step_size=1):
radius = patch_size // 2
height, width = image.shape
padded_image = np.pad(image, radius, mode='reflect')
patches = []
for i in range(radius, height + radius, step_size):
for j in range(radius, width + radius, step_size):
patch = padded_image[i - radius:i + radius + 1, j - radius:j + radius + 1]
patches.append(patch.flatten())
return np.array(patches)
def create_laplacian(patch_size):
# create laplacian kernel
data = np.array([[4]*(patch_size**2), [-1]*(patch_size**2), [-1]*(patch_size**2), [-1]*(patch_size**2), [-1]*(patch_size**2)])
# create the diagonalized matrix of the laplacian kernel for matrix multiplication
diags = np.array([0, -1, 1, patch_size, -patch_size])
spd = spdiags(data, diags, patch_size**2, patch_size**2).toarray()
for i in range(1, patch_size):
spd[patch_size * i - 1][patch_size * i] = 0
spd[patch_size * i][patch_size * i - 1] = 0
return spd
def compute_weights_numerator(q_patches, r_alphas, sigma):
return np.exp(-0.5 * (np.linalg.norm(q_patches-r_alphas, axis=1)**2) / (sigma**2))
def compute_k(downsampled_image, alpha, iter_num, patch_size=5, num_neighbours=5, sigma=0.06):
# create r and q patches
step_size_factor = 1
r_patch_size = patch_size * alpha
q_patches = make_patches(downsampled_image, patch_size, step_size=step_size_factor)
r_patches = make_patches(downsampled_image, r_patch_size, step_size=step_size_factor * alpha)
# initialize k with a delta function
k = np.expand_dims(signal.unit_impulse((r_patch_size,r_patch_size), idx='mid').flatten(), axis=1) #changed backwards
# create laplacian matrix
C = create_laplacian(r_patch_size) #changed. was patch_size instead
CTC = C.T @ C
# create Rj matrices for each patch rj
Rs = create_R_mats(r_patches, r_patch_size, alpha**2)
Rs_np = np.array(Rs)
Rs_np_T = np.swapaxes(Rs_np, 1, 2) # transpose each Rj
Rs_T_Rs_np = Rs_np_T @ Rs_np
for _ in range(iter_num):
# compute patches in the coarse image
r_alphas = (Rs @ k).squeeze()
# find nearest neighbours for each qi (NLM trick)
tree = ball_tree.BallTree(r_alphas, leaf_size=2)
_, neighbors_idxs = tree.query(q_patches, k=num_neighbours)
# compute weights of nearest neighbours
weights = np.zeros((q_patches.shape[0], r_alphas.shape[0]))
for i in range(q_patches.shape[0]):
weights[i, neighbors_idxs[i]] = compute_weights_numerator(q_patches[i], r_alphas[neighbors_idxs[i]], sigma)
weights_sum = weights.sum(axis=1)
# normalize weights
weights = np.nan_to_num(np.divide(weights , np.expand_dims(weights_sum, -1)))
# compute the components of the next k
sum_wRTR_CTC = np.zeros((k.shape[0],k.shape[0]))
sum_wRTq = np.zeros(k.shape)
for i in range(weights.shape[0]):
for j in range(weights.shape[1]):
if weights[i, j]:
sum_wRTR_CTC += weights[i,j] * Rs_T_Rs_np[j]
sum_wRTq += weights[i,j] * Rs_np_T[j] @ np.expand_dims(q_patches[i],-1)
# compute the next k
inv_wRTR_CTC = np.linalg.inv(sum_wRTR_CTC + CTC) # CTC is outside the sum
k = inv_wRTR_CTC @ sum_wRTq
print(f'mean: {k.mean()} std: {k.std()}')
# return as a 2D kernel
return k.reshape((r_patch_size, r_patch_size))
# based on tutorial 7
def wiener_filter(image, psf, k=0.1):
image_dft = fftpack.fft2(image)
psf_dft = fftpack.fft2(fftpack.ifftshift(psf), shape=image_dft.shape)
filter_dft = np.conj(psf_dft) / (np.abs(psf_dft) ** 2 + k)
recovered_dft = image_dft * filter_dft
return np.real(fftpack.ifft2(recovered_dft))
def create_R_mats(r_patches, r_patch_size, downsampling_scale):
# create the R matrices for the r patches for matrix multiplication
Rs = []
for patch_i in range(r_patches.shape[0]):
# refer to each one of the kernel's row as a small toeplitz
toeplitz_list = []
# add zeroed matrices for the indices that should be zeroed out below the diagonal
ghost_toeplitz = np.zeros((r_patch_size,r_patch_size))
for _ in range(r_patch_size//2):
toeplitz_list.append(ghost_toeplitz)
# create the small toeplitz matrices for each of the rows
r_kernel = np.copy(r_patches[patch_i]).reshape([r_patch_size, r_patch_size])
for i in range(r_patch_size):
tiled = np.tile(r_kernel[i,:], (r_patch_size,1)).T
diags = np.arange(-(r_patch_size//2),r_patch_size//2+1,1)
small_toeplitz = spdiags(tiled, diags, r_patch_size, r_patch_size).toarray()
toeplitz_list.append(small_toeplitz)
# add zeroed matrices for the indices that should be zeroed out above the diagonal
for _ in range(r_patch_size//2):
toeplitz_list.append(ghost_toeplitz)
# construct the big diagonalized matrix R that will correspond to the kernel r
R_mat = np.zeros((r_patch_size**2, r_patch_size**2))
for i in range(r_patch_size):
for j in range(r_patch_size):
toeplitz_small = toeplitz_list[r_patch_size-(i-j)-1]
R_mat[i*r_patch_size:(i+1)*r_patch_size, j*r_patch_size: (j+1)*r_patch_size] = toeplitz_small
# add and downscale it
Rs.append(R_mat[::downsampling_scale,:])
return Rs
if __name__ == "__main__":
# read the given image from file
image_tank = cv2.imread('DIPSourceHW2.png', cv2.IMREAD_GRAYSCALE)
image_tank = image_tank / 255.0
# create PSFs
s_psf = sinc_psf()
# 0.1 or 1 std might be better
g_psf = gaussian_psf(size=16, std=1.)
# init size, alpha and num of iterations
alpha = 3
iter_num = 15
original_img_size = (image_tank.shape[1], image_tank.shape[0])
new_img_size = (int(image_tank.shape[1]/alpha),int(image_tank.shape[0]/alpha))
# use gaussian PSF to create downsampled and upsampled images
blurred_image_gaussian = signal.convolve2d(image_tank, g_psf, mode='same', boundary='wrap')
downsampled_image_gaussian = cv2.resize(blurred_image_gaussian, new_img_size, interpolation=cv2.INTER_NEAREST)
upsampled_image_gaussian = cv2.resize(downsampled_image_gaussian, original_img_size, interpolation=cv2.INTER_CUBIC)
# use sinc PSF to create downsampled and upsampled images
blurred_image_sinc = signal.convolve2d(image_tank, s_psf, mode='same', boundary='wrap')
downsampled_image_sinc = cv2.resize(blurred_image_sinc, new_img_size, interpolation=cv2.INTER_NEAREST)
upsampled_image_sinc = cv2.resize(downsampled_image_sinc, original_img_size, interpolation=cv2.INTER_CUBIC)
# compute k by each PSF
k_gaussian = compute_k(downsampled_image_gaussian, alpha, iter_num)
k_sinc = compute_k(downsampled_image_sinc, alpha, iter_num)
# restore with wiener filter for each k for each PSF
restored_gaussian_with_gaussian = wiener_filter(upsampled_image_gaussian, k_gaussian)
restored_gaussian_with_sinc = wiener_filter(upsampled_image_gaussian, k_sinc)
restored_sinc_with_sinc = wiener_filter(upsampled_image_sinc, k_sinc)
restored_sinc_with_gaussian = wiener_filter(upsampled_image_sinc, k_gaussian)
# restore with wiener filter for the true kernel
restored_gaussian_with_true_kernel = wiener_filter(upsampled_image_sinc, g_psf)
restored_sinc_with_true_kernel = wiener_filter(upsampled_image_gaussian, s_psf)
# store low res images
plt.imshow(downsampled_image_gaussian, cmap='gray')
plt.savefig('downsampled_image_gaussian_plt.png')
plt.cla()
plt.imshow(downsampled_image_sinc, cmap='gray')
plt.savefig('downsampled_image_sinc_plt.png')
plt.cla()
# store results and compute PSNR
plt.imshow(restored_gaussian_with_gaussian, cmap='gray')
plt.savefig('restored_gaussian_with_gaussian_plt.png')
plt.cla()
plt.imshow(restored_gaussian_with_sinc, cmap='gray')
plt.savefig('restored_gaussian_with_sinc_plt.png')
plt.cla()
plt.imshow(restored_sinc_with_sinc, cmap='gray')
plt.savefig('restored_sinc_with_sinc_plt.png')
plt.cla()
plt.imshow(restored_sinc_with_gaussian, cmap='gray')
plt.savefig('restored_sinc_with_gaussian_plt.png')
plt.cla()
plt.imshow(restored_gaussian_with_true_kernel, cmap='gray')
plt.savefig('restored_gaussian_with_true_kernel_plt.png')
plt.cla()
plt.imshow(restored_sinc_with_true_kernel, cmap='gray')
plt.savefig('restored_sinc_with_true_kernel_plt.png')
print("PSNR for gaussian on gaussian: {}".format(cv2.PSNR(np.float64(restored_gaussian_with_gaussian), np.float64(image_tank))))
print("PSNR for sinc on gaussian: {}".format(cv2.PSNR(np.float64(restored_gaussian_with_sinc), np.float64(image_tank))))
print("PSNR for sinc on sinc: {}".format(cv2.PSNR(np.float64(restored_sinc_with_sinc), np.float64(image_tank))))
print("PSNR for gaussian on sinc: {}".format(cv2.PSNR(np.float64(restored_sinc_with_gaussian), np.float64(image_tank)))) | [
"numpy.array",
"numpy.linalg.norm",
"numpy.arange",
"matplotlib.pyplot.imshow",
"numpy.float64",
"numpy.exp",
"scipy.fftpack.fft2",
"numpy.linspace",
"numpy.meshgrid",
"matplotlib.pyplot.cla",
"scipy.signal.convolve2d",
"numpy.abs",
"numpy.tile",
"matplotlib.pyplot.savefig",
"sklearn.nei... | [((302, 318), 'numpy.sinc', 'np.sinc', (['(x.T @ x)'], {}), '(x.T @ x)\n', (309, 318), True, 'import numpy as np\n'), ((442, 476), 'numpy.linspace', 'np.linspace', (['(-edge)', 'edge'], {'num': 'size'}), '(-edge, edge, num=size)\n', (453, 476), True, 'import numpy as np\n'), ((490, 509), 'numpy.meshgrid', 'np.meshgrid', (['ax', 'ax'], {}), '(ax, ax)\n', (501, 509), True, 'import numpy as np\n'), ((523, 568), 'numpy.exp', 'np.exp', (['(-(xx ** 2 + yy ** 2) / (2 * std ** 2))'], {}), '(-(xx ** 2 + yy ** 2) / (2 * std ** 2))\n', (529, 568), True, 'import numpy as np\n'), ((775, 812), 'numpy.pad', 'np.pad', (['image', 'radius'], {'mode': '"""reflect"""'}), "(image, radius, mode='reflect')\n", (781, 812), True, 'import numpy as np\n'), ((1092, 1109), 'numpy.array', 'np.array', (['patches'], {}), '(patches)\n', (1100, 1109), True, 'import numpy as np\n'), ((1188, 1321), 'numpy.array', 'np.array', (['[[4] * patch_size ** 2, [-1] * patch_size ** 2, [-1] * patch_size ** 2, [-1\n ] * patch_size ** 2, [-1] * patch_size ** 2]'], {}), '([[4] * patch_size ** 2, [-1] * patch_size ** 2, [-1] * patch_size **\n 2, [-1] * patch_size ** 2, [-1] * patch_size ** 2])\n', (1196, 1321), True, 'import numpy as np\n'), ((1408, 1453), 'numpy.array', 'np.array', (['[0, -1, 1, patch_size, -patch_size]'], {}), '([0, -1, 1, patch_size, -patch_size])\n', (1416, 1453), True, 'import numpy as np\n'), ((2619, 2631), 'numpy.array', 'np.array', (['Rs'], {}), '(Rs)\n', (2627, 2631), True, 'import numpy as np\n'), ((2646, 2670), 'numpy.swapaxes', 'np.swapaxes', (['Rs_np', '(1)', '(2)'], {}), '(Rs_np, 1, 2)\n', (2657, 2670), True, 'import numpy as np\n'), ((4246, 4265), 'scipy.fftpack.fft2', 'fftpack.fft2', (['image'], {}), '(image)\n', (4258, 4265), False, 'from scipy import fftpack, signal\n'), ((6279, 6331), 'cv2.imread', 'cv2.imread', (['"""DIPSourceHW2.png"""', 'cv2.IMREAD_GRAYSCALE'], {}), "('DIPSourceHW2.png', cv2.IMREAD_GRAYSCALE)\n", (6289, 6331), False, 'import cv2\n'), ((6811, 6877), 'scipy.signal.convolve2d', 'signal.convolve2d', (['image_tank', 'g_psf'], {'mode': '"""same"""', 'boundary': '"""wrap"""'}), "(image_tank, g_psf, mode='same', boundary='wrap')\n", (6828, 6877), False, 'from scipy import fftpack, signal\n'), ((6911, 6997), 'cv2.resize', 'cv2.resize', (['blurred_image_gaussian', 'new_img_size'], {'interpolation': 'cv2.INTER_NEAREST'}), '(blurred_image_gaussian, new_img_size, interpolation=cv2.\n INTER_NEAREST)\n', (6921, 6997), False, 'import cv2\n'), ((7024, 7117), 'cv2.resize', 'cv2.resize', (['downsampled_image_gaussian', 'original_img_size'], {'interpolation': 'cv2.INTER_CUBIC'}), '(downsampled_image_gaussian, original_img_size, interpolation=cv2\n .INTER_CUBIC)\n', (7034, 7117), False, 'import cv2\n'), ((7201, 7267), 'scipy.signal.convolve2d', 'signal.convolve2d', (['image_tank', 's_psf'], {'mode': '"""same"""', 'boundary': '"""wrap"""'}), "(image_tank, s_psf, mode='same', boundary='wrap')\n", (7218, 7267), False, 'from scipy import fftpack, signal\n'), ((7297, 7374), 'cv2.resize', 'cv2.resize', (['blurred_image_sinc', 'new_img_size'], {'interpolation': 'cv2.INTER_NEAREST'}), '(blurred_image_sinc, new_img_size, interpolation=cv2.INTER_NEAREST)\n', (7307, 7374), False, 'import cv2\n'), ((7402, 7491), 'cv2.resize', 'cv2.resize', (['downsampled_image_sinc', 'original_img_size'], {'interpolation': 'cv2.INTER_CUBIC'}), '(downsampled_image_sinc, original_img_size, interpolation=cv2.\n INTER_CUBIC)\n', (7412, 7491), False, 'import cv2\n'), ((8296, 8347), 'matplotlib.pyplot.imshow', 'plt.imshow', (['downsampled_image_gaussian'], {'cmap': '"""gray"""'}), "(downsampled_image_gaussian, cmap='gray')\n", (8306, 8347), True, 'import matplotlib.pyplot as plt\n'), ((8352, 8401), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""downsampled_image_gaussian_plt.png"""'], {}), "('downsampled_image_gaussian_plt.png')\n", (8363, 8401), True, 'import matplotlib.pyplot as plt\n'), ((8406, 8415), 'matplotlib.pyplot.cla', 'plt.cla', ([], {}), '()\n', (8413, 8415), True, 'import matplotlib.pyplot as plt\n'), ((8420, 8467), 'matplotlib.pyplot.imshow', 'plt.imshow', (['downsampled_image_sinc'], {'cmap': '"""gray"""'}), "(downsampled_image_sinc, cmap='gray')\n", (8430, 8467), True, 'import matplotlib.pyplot as plt\n'), ((8472, 8517), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""downsampled_image_sinc_plt.png"""'], {}), "('downsampled_image_sinc_plt.png')\n", (8483, 8517), True, 'import matplotlib.pyplot as plt\n'), ((8522, 8531), 'matplotlib.pyplot.cla', 'plt.cla', ([], {}), '()\n', (8529, 8531), True, 'import matplotlib.pyplot as plt\n'), ((8574, 8630), 'matplotlib.pyplot.imshow', 'plt.imshow', (['restored_gaussian_with_gaussian'], {'cmap': '"""gray"""'}), "(restored_gaussian_with_gaussian, cmap='gray')\n", (8584, 8630), True, 'import matplotlib.pyplot as plt\n'), ((8635, 8689), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""restored_gaussian_with_gaussian_plt.png"""'], {}), "('restored_gaussian_with_gaussian_plt.png')\n", (8646, 8689), True, 'import matplotlib.pyplot as plt\n'), ((8694, 8703), 'matplotlib.pyplot.cla', 'plt.cla', ([], {}), '()\n', (8701, 8703), True, 'import matplotlib.pyplot as plt\n'), ((8708, 8760), 'matplotlib.pyplot.imshow', 'plt.imshow', (['restored_gaussian_with_sinc'], {'cmap': '"""gray"""'}), "(restored_gaussian_with_sinc, cmap='gray')\n", (8718, 8760), True, 'import matplotlib.pyplot as plt\n'), ((8765, 8815), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""restored_gaussian_with_sinc_plt.png"""'], {}), "('restored_gaussian_with_sinc_plt.png')\n", (8776, 8815), True, 'import matplotlib.pyplot as plt\n'), ((8820, 8829), 'matplotlib.pyplot.cla', 'plt.cla', ([], {}), '()\n', (8827, 8829), True, 'import matplotlib.pyplot as plt\n'), ((8834, 8882), 'matplotlib.pyplot.imshow', 'plt.imshow', (['restored_sinc_with_sinc'], {'cmap': '"""gray"""'}), "(restored_sinc_with_sinc, cmap='gray')\n", (8844, 8882), True, 'import matplotlib.pyplot as plt\n'), ((8887, 8933), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""restored_sinc_with_sinc_plt.png"""'], {}), "('restored_sinc_with_sinc_plt.png')\n", (8898, 8933), True, 'import matplotlib.pyplot as plt\n'), ((8938, 8947), 'matplotlib.pyplot.cla', 'plt.cla', ([], {}), '()\n', (8945, 8947), True, 'import matplotlib.pyplot as plt\n'), ((8952, 9004), 'matplotlib.pyplot.imshow', 'plt.imshow', (['restored_sinc_with_gaussian'], {'cmap': '"""gray"""'}), "(restored_sinc_with_gaussian, cmap='gray')\n", (8962, 9004), True, 'import matplotlib.pyplot as plt\n'), ((9009, 9059), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""restored_sinc_with_gaussian_plt.png"""'], {}), "('restored_sinc_with_gaussian_plt.png')\n", (9020, 9059), True, 'import matplotlib.pyplot as plt\n'), ((9064, 9073), 'matplotlib.pyplot.cla', 'plt.cla', ([], {}), '()\n', (9071, 9073), True, 'import matplotlib.pyplot as plt\n'), ((9078, 9137), 'matplotlib.pyplot.imshow', 'plt.imshow', (['restored_gaussian_with_true_kernel'], {'cmap': '"""gray"""'}), "(restored_gaussian_with_true_kernel, cmap='gray')\n", (9088, 9137), True, 'import matplotlib.pyplot as plt\n'), ((9142, 9199), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""restored_gaussian_with_true_kernel_plt.png"""'], {}), "('restored_gaussian_with_true_kernel_plt.png')\n", (9153, 9199), True, 'import matplotlib.pyplot as plt\n'), ((9204, 9213), 'matplotlib.pyplot.cla', 'plt.cla', ([], {}), '()\n', (9211, 9213), True, 'import matplotlib.pyplot as plt\n'), ((9218, 9273), 'matplotlib.pyplot.imshow', 'plt.imshow', (['restored_sinc_with_true_kernel'], {'cmap': '"""gray"""'}), "(restored_sinc_with_true_kernel, cmap='gray')\n", (9228, 9273), True, 'import matplotlib.pyplot as plt\n'), ((9278, 9331), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""restored_sinc_with_true_kernel_plt.png"""'], {}), "('restored_sinc_with_true_kernel_plt.png')\n", (9289, 9331), True, 'import matplotlib.pyplot as plt\n'), ((248, 285), 'numpy.linspace', 'np.linspace', (['(-edge)', 'edge', 'window_size'], {}), '(-edge, edge, window_size)\n', (259, 285), True, 'import numpy as np\n'), ((2921, 2962), 'sklearn.neighbors.ball_tree.BallTree', 'ball_tree.BallTree', (['r_alphas'], {'leaf_size': '(2)'}), '(r_alphas, leaf_size=2)\n', (2939, 2962), False, 'from sklearn.neighbors import ball_tree\n'), ((3097, 3146), 'numpy.zeros', 'np.zeros', (['(q_patches.shape[0], r_alphas.shape[0])'], {}), '((q_patches.shape[0], r_alphas.shape[0]))\n', (3105, 3146), True, 'import numpy as np\n'), ((3540, 3574), 'numpy.zeros', 'np.zeros', (['(k.shape[0], k.shape[0])'], {}), '((k.shape[0], k.shape[0]))\n', (3548, 3574), True, 'import numpy as np\n'), ((3593, 3610), 'numpy.zeros', 'np.zeros', (['k.shape'], {}), '(k.shape)\n', (3601, 3610), True, 'import numpy as np\n'), ((3943, 3976), 'numpy.linalg.inv', 'np.linalg.inv', (['(sum_wRTR_CTC + CTC)'], {}), '(sum_wRTR_CTC + CTC)\n', (3956, 3976), True, 'import numpy as np\n'), ((4293, 4315), 'scipy.fftpack.ifftshift', 'fftpack.ifftshift', (['psf'], {}), '(psf)\n', (4310, 4315), False, 'from scipy import fftpack, signal\n'), ((4357, 4373), 'numpy.conj', 'np.conj', (['psf_dft'], {}), '(psf_dft)\n', (4364, 4373), True, 'import numpy as np\n'), ((4465, 4493), 'scipy.fftpack.ifft2', 'fftpack.ifft2', (['recovered_dft'], {}), '(recovered_dft)\n', (4478, 4493), False, 'from scipy import fftpack, signal\n'), ((4904, 4942), 'numpy.zeros', 'np.zeros', (['(r_patch_size, r_patch_size)'], {}), '((r_patch_size, r_patch_size))\n', (4912, 4942), True, 'import numpy as np\n'), ((5779, 5827), 'numpy.zeros', 'np.zeros', (['(r_patch_size ** 2, r_patch_size ** 2)'], {}), '((r_patch_size ** 2, r_patch_size ** 2))\n', (5787, 5827), True, 'import numpy as np\n'), ((1464, 1518), 'scipy.sparse.spdiags', 'spdiags', (['data', 'diags', '(patch_size ** 2)', '(patch_size ** 2)'], {}), '(data, diags, patch_size ** 2, patch_size ** 2)\n', (1471, 1518), False, 'from scipy.sparse import spdiags\n'), ((5305, 5362), 'numpy.arange', 'np.arange', (['(-(r_patch_size // 2))', '(r_patch_size // 2 + 1)', '(1)'], {}), '(-(r_patch_size // 2), r_patch_size // 2 + 1, 1)\n', (5314, 5362), True, 'import numpy as np\n'), ((2286, 2346), 'scipy.signal.unit_impulse', 'signal.unit_impulse', (['(r_patch_size, r_patch_size)'], {'idx': '"""mid"""'}), "((r_patch_size, r_patch_size), idx='mid')\n", (2305, 2346), False, 'from scipy import fftpack, signal\n'), ((3435, 3466), 'numpy.expand_dims', 'np.expand_dims', (['weights_sum', '(-1)'], {}), '(weights_sum, -1)\n', (3449, 3466), True, 'import numpy as np\n'), ((4377, 4392), 'numpy.abs', 'np.abs', (['psf_dft'], {}), '(psf_dft)\n', (4383, 4392), True, 'import numpy as np\n'), ((5118, 5145), 'numpy.copy', 'np.copy', (['r_patches[patch_i]'], {}), '(r_patches[patch_i])\n', (5125, 5145), True, 'import numpy as np\n'), ((5242, 5284), 'numpy.tile', 'np.tile', (['r_kernel[i, :]', '(r_patch_size, 1)'], {}), '(r_kernel[i, :], (r_patch_size, 1))\n', (5249, 5284), True, 'import numpy as np\n'), ((9395, 9438), 'numpy.float64', 'np.float64', (['restored_gaussian_with_gaussian'], {}), '(restored_gaussian_with_gaussian)\n', (9405, 9438), True, 'import numpy as np\n'), ((9440, 9462), 'numpy.float64', 'np.float64', (['image_tank'], {}), '(image_tank)\n', (9450, 9462), True, 'import numpy as np\n'), ((9524, 9563), 'numpy.float64', 'np.float64', (['restored_gaussian_with_sinc'], {}), '(restored_gaussian_with_sinc)\n', (9534, 9563), True, 'import numpy as np\n'), ((9565, 9587), 'numpy.float64', 'np.float64', (['image_tank'], {}), '(image_tank)\n', (9575, 9587), True, 'import numpy as np\n'), ((9645, 9680), 'numpy.float64', 'np.float64', (['restored_sinc_with_sinc'], {}), '(restored_sinc_with_sinc)\n', (9655, 9680), True, 'import numpy as np\n'), ((9682, 9704), 'numpy.float64', 'np.float64', (['image_tank'], {}), '(image_tank)\n', (9692, 9704), True, 'import numpy as np\n'), ((9766, 9805), 'numpy.float64', 'np.float64', (['restored_sinc_with_gaussian'], {}), '(restored_sinc_with_gaussian)\n', (9776, 9805), True, 'import numpy as np\n'), ((9807, 9829), 'numpy.float64', 'np.float64', (['image_tank'], {}), '(image_tank)\n', (9817, 9829), True, 'import numpy as np\n'), ((1775, 1819), 'numpy.linalg.norm', 'np.linalg.norm', (['(q_patches - r_alphas)'], {'axis': '(1)'}), '(q_patches - r_alphas, axis=1)\n', (1789, 1819), True, 'import numpy as np\n'), ((5384, 5433), 'scipy.sparse.spdiags', 'spdiags', (['tiled', 'diags', 'r_patch_size', 'r_patch_size'], {}), '(tiled, diags, r_patch_size, r_patch_size)\n', (5391, 5433), False, 'from scipy.sparse import spdiags\n'), ((3858, 3890), 'numpy.expand_dims', 'np.expand_dims', (['q_patches[i]', '(-1)'], {}), '(q_patches[i], -1)\n', (3872, 3890), True, 'import numpy as np\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 2 10:49:13 2020
@author: becker
"""
import numpy as np
import scipy
k = 3
d = 1
def sums(length, total_sum):
if length == 1:
yield (total_sum,)
else:
for value in range(total_sum + 1):
for permutation in sums(length - 1, total_sum - value):
yield (value,) + permutation
for i in sums(d+1,k):
print(f"{i=} {scipy.special.factorial(np.array(i, dtype=int))}")
L = list(sums(d+1,k))
print('total permutations:',len(L))
print(f"{L=}")
| [
"numpy.array"
] | [((462, 484), 'numpy.array', 'np.array', (['i'], {'dtype': 'int'}), '(i, dtype=int)\n', (470, 484), True, 'import numpy as np\n')] |
import numpy as np
import pandas as pd
import os
from features import *
from util import *
# Handle datasets
def merge_data(key_list, array_list):
all_keys = np.array([kl[i] for kl in key_list for i in range(len(kl))])
all_keys_idxs = np.argsort(all_keys)
all_keys_sorted = np.sort(all_keys)
all_arrays = np.array([al[i] for al in array_list for i in range(len(al))])
all_arrays_shape = all_arrays.shape
n = len(all_arrays)
sorted_arrays = np.empty(all_arrays_shape)
for j in all_keys_idxs:
this_idx = all_keys_idxs[j]
sorted_arrays[j] = all_arrays[this_idx]
return all_keys_sorted, sorted_arrays
def merge_data_LOO(key_list, array_list):
num_sets = len(key_list)
key_list_LOO = []
array_list_LOO = []
for i in range(num_sets):
remaining_keys = [key_list[j] for j in range(num_sets) if j!=i]
remaining_arrays = [array_list[j] for j in range(num_sets) if j!=i]
a,b = merge_data(remaining_keys, remaining_arrays)
key_list_LOO.append(a)
array_list_LOO.append(b)
return key_list_LOO, array_list_LOO
if __name__ == '__main__':
# base_dir = os.path.abspath('.')
base_dir = '/data/lauzierean/Untwisting'
home = os.path.join(base_dir, 'exacthgm')
data_dir = os.path.join(home, 'Data')
resources = os.path.join(home, 'Resources')
resources_QAP = os.path.join(resources,'QAP')
resources_Pairs = os.path.join(resources,'Pairs')
resources_Full = os.path.join(resources,'Full')
# twitches = [5, 8, 23] + [11, 52, 50] + [15, 12, 11] + [37] + [9, 15, 13] + [1, 4, 1]
# hatches = [85, 106, 136] + [102, 138, 140] + [104, 101, 126] + [114] + [93, 96, 93] + [86, 95, 95]
# twitches = np.array(twitches)
# hatches = np.array(hatches)
# twitch_hatch = np.vstack([twitches, hatches])
# out_path_twitch_hatch = os.path.join(resources, 'twitch_hatch.npy')
# np.save(out_path_twitch_hatch, twitch_hatch)
step = .05
# First do the n=20 nuclei case:
num_cells = 20
num_pairs = int(num_cells/2)
tl = [(i,i+1) for i in range(0,num_cells,2)][::-1]
key_list = np.load(os.path.join(data_dir, 'keys_20.npy'), allow_pickle=True)
array_list = np.load(os.path.join(data_dir, 'arrays_20.npy'), allow_pickle=True)
# Get LOO arrays to get statistics
keys_LOO, arrays_LOO = merge_data_LOO(key_list, array_list)
# QAP
widths = get_pair_arrays(keys_LOO, arrays_LOO)
widths_pairs = [a[:,1:] for a in widths]
side_lens = get_side_lens(keys_LOO, arrays_LOO)
left_sides, right_sides = side_lens
feature_list_widths = [widths]
means_widths, sigma_invs_widths = get_doubles_statistics_QAP(keys_LOO, feature_list_widths, step)
feature_list_pairs = [widths_pairs, left_sides, right_sides]
means_pairs, sigma_invs_pairs = get_doubles_statistics_QAP(keys_LOO, feature_list_pairs, step)
op_means_widths = os.path.join(resources_QAP, 'means_widths.npy')
op_sigma_invs_widths = os.path.join(resources_QAP, 'sigma_invs_widths.npy')
op_means_pairs = os.path.join(resources_QAP, 'means_pairs.npy')
op_sigma_invs_pairs = os.path.join(resources_QAP, 'sigma_invs_pairs.npy')
np.save(op_means_widths, means_widths)
np.save(op_sigma_invs_widths, sigma_invs_widths)
np.save(op_means_pairs, means_pairs)
np.save(op_sigma_invs_pairs, sigma_invs_pairs)
# Pairs
# Degree 4 features:
pair_dist_ratios = get_pair_ratio_arrays(keys_LOO, arrays_LOO)
pair_dist_ratios = [a[:,1:] for a in pair_dist_ratios]
cos_sims = get_cos_sims(keys_LOO, arrays_LOO)
lateral_axial_twists = get_lateral_axial_twists(keys_LOO, arrays_LOO)
axial_twists = get_axial_twists(keys_LOO, arrays_LOO)
feature_list_pairs = [cos_sims, lateral_axial_twists, axial_twists]
means_pairs, sigma_invs_pairs = get_doubles_statistics(keys_LOO, feature_list_pairs, step)
# Degree 6 features:
midpoints, midpoint_distances, bend_angles, bend_angle_sums = get_bend_angles(keys_LOO, arrays_LOO)
midpoint_distances = [a[:,1:] for a in midpoint_distances]
plane_angles = get_plane_intersection_angles(keys_LOO, arrays_LOO)
feature_list_triples = [pair_dist_ratios, midpoint_distances, bend_angles, plane_angles]
means_triples, sigma_invs_triples = get_doubles_statistics(keys_LOO, feature_list_triples, step)
op_means_pairs = os.path.join(resources_Pairs, 'means_pairs.npy')
op_sigma_invs_pairs = os.path.join(resources_Pairs, 'sigma_invs_pairs.npy')
op_means_triples = os.path.join(resources_Pairs, 'means_triples.npy')
op_sigma_invs_triples = os.path.join(resources_Pairs, 'sigma_invs_triples.npy')
np.save(op_means_pairs, means_pairs)
np.save(op_sigma_invs_pairs, sigma_invs_pairs)
np.save(op_means_triples, means_triples)
np.save(op_sigma_invs_triples, sigma_invs_triples)
# Full
means_partial_sequence, sigma_invs_partial_sequence = get_partial_sequence_statistics(keys_LOO, feature_list_pairs, feature_list_triples, step, num_pairs)
mean_cost_estimates, sigma_inv_cost_estimates = get_sequence_cost_estimate_statistics(key_list, array_list, step, means_partial_sequence, sigma_invs_partial_sequence, tl)
op_means_seq = os.path.join(resources_Full, 'means_sequence.npy')
op_sigma_invs_seq = os.path.join(resources_Full, 'sigma_invs_sequence.npy')
op_mean_cost_estimates = os.path.join(resources_Full, 'mean_cost_estimates.npy')
op_sigma_cost_estimates = os.path.join(resources_Full, 'sigma_inv_cost_estimates.npy')
np.save(op_means_seq, means_partial_sequence)
np.save(op_sigma_invs_seq, sigma_invs_partial_sequence)
np.save(op_mean_cost_estimates, mean_cost_estimates)
np.save(op_sigma_cost_estimates, sigma_inv_cost_estimates)
# Now 22 cell case:
num_cells = 22
num_pairs = int(num_cells/2)
tl = [(i,i+1) for i in range(0,num_cells,2)][::-1]
key_list = np.load(os.path.join(data_dir, 'keys_22.npy'), allow_pickle=True)
array_list = np.load(os.path.join(data_dir, 'arrays_22.npy'), allow_pickle=True)
# Get LOO arrays to get statistics
keys_LOO, arrays_LOO = merge_data_LOO(key_list, array_list)
# QAP
widths = get_pair_arrays(keys_LOO, arrays_LOO)
widths_pairs = [a[:,1:] for a in widths]
side_lens = get_side_lens(keys_LOO, arrays_LOO)
left_sides, right_sides = side_lens
feature_list_widths = [widths]
means_widths, sigma_invs_widths = get_doubles_statistics_QAP(keys_LOO, feature_list_widths, step)
feature_list_pairs = [widths_pairs, left_sides, right_sides]
means_pairs, sigma_invs_pairs = get_doubles_statistics_QAP(keys_LOO, feature_list_pairs, step)
op_means_widths = os.path.join(resources_QAP, 'means_widths_Q.npy')
op_sigma_invs_widths = os.path.join(resources_QAP, 'sigma_invs_widths_Q.npy')
op_means_pairs = os.path.join(resources_QAP, 'means_pairs_Q.npy')
op_sigma_invs_pairs = os.path.join(resources_QAP, 'sigma_invs_pairs_Q.npy')
np.save(op_means_widths, means_widths)
np.save(op_sigma_invs_widths, sigma_invs_widths)
np.save(op_means_pairs, means_pairs)
np.save(op_sigma_invs_pairs, sigma_invs_pairs)
# Pairs
# Degree 4 features:
pair_dist_ratios = get_pair_ratio_arrays(keys_LOO, arrays_LOO)
pair_dist_ratios = [a[:,1:] for a in pair_dist_ratios]
cos_sims = get_cos_sims(keys_LOO, arrays_LOO)
lateral_axial_twists = get_lateral_axial_twists(keys_LOO, arrays_LOO)
axial_twists = get_axial_twists(keys_LOO, arrays_LOO)
feature_list_pairs = [cos_sims, lateral_axial_twists, axial_twists]
means_pairs, sigma_invs_pairs = get_doubles_statistics(keys_LOO, feature_list_pairs, step)
# Degree 6 features:
midpoints, midpoint_distances, bend_angles, bend_angle_sums = get_bend_angles(keys_LOO, arrays_LOO)
midpoint_distances = [a[:,1:] for a in midpoint_distances]
plane_angles = get_plane_intersection_angles(keys_LOO, arrays_LOO)
feature_list_triples = [pair_dist_ratios, midpoint_distances, bend_angles, plane_angles]
means_triples, sigma_invs_triples = get_doubles_statistics(keys_LOO, feature_list_triples, step)
op_means_pairs = os.path.join(resources_Pairs, 'means_pairs_Q.npy')
op_sigma_invs_pairs = os.path.join(resources_Pairs, 'sigma_invs_pairs_Q.npy')
op_means_triples = os.path.join(resources_Pairs, 'means_triples_Q.npy')
op_sigma_invs_triples = os.path.join(resources_Pairs, 'sigma_invs_triples_Q.npy')
np.save(op_means_pairs, means_pairs)
np.save(op_sigma_invs_pairs, sigma_invs_pairs)
np.save(op_means_triples, means_triples)
np.save(op_sigma_invs_triples, sigma_invs_triples)
# Full
means_partial_sequence, sigma_invs_partial_sequence = get_partial_sequence_statistics(keys_LOO, feature_list_pairs, feature_list_triples, step, num_pairs)
mean_cost_estimates, sigma_inv_cost_estimates = get_sequence_cost_estimate_statistics(key_list, array_list, step, means_partial_sequence, sigma_invs_partial_sequence, tl)
op_means_seq = os.path.join(resources_Full, 'means_sequence_Q.npy')
op_sigma_invs_seq = os.path.join(resources_Full, 'sigma_invs_sequence_Q.npy')
op_mean_cost_estimates = os.path.join(resources_Full, 'mean_cost_estimates_Q.npy')
op_sigma_cost_estimates = os.path.join(resources_Full, 'sigma_inv_cost_estimates_Q.npy')
np.save(op_means_seq, means_partial_sequence)
np.save(op_sigma_invs_seq, sigma_invs_partial_sequence)
np.save(op_mean_cost_estimates, mean_cost_estimates)
np.save(op_sigma_cost_estimates, sigma_inv_cost_estimates) | [
"numpy.sort",
"os.path.join",
"numpy.argsort",
"numpy.empty",
"numpy.save"
] | [((263, 283), 'numpy.argsort', 'np.argsort', (['all_keys'], {}), '(all_keys)\n', (273, 283), True, 'import numpy as np\n'), ((307, 324), 'numpy.sort', 'np.sort', (['all_keys'], {}), '(all_keys)\n', (314, 324), True, 'import numpy as np\n'), ((505, 531), 'numpy.empty', 'np.empty', (['all_arrays_shape'], {}), '(all_arrays_shape)\n', (513, 531), True, 'import numpy as np\n'), ((1374, 1408), 'os.path.join', 'os.path.join', (['base_dir', '"""exacthgm"""'], {}), "(base_dir, 'exacthgm')\n", (1386, 1408), False, 'import os\n'), ((1425, 1451), 'os.path.join', 'os.path.join', (['home', '"""Data"""'], {}), "(home, 'Data')\n", (1437, 1451), False, 'import os\n'), ((1471, 1502), 'os.path.join', 'os.path.join', (['home', '"""Resources"""'], {}), "(home, 'Resources')\n", (1483, 1502), False, 'import os\n'), ((1524, 1554), 'os.path.join', 'os.path.join', (['resources', '"""QAP"""'], {}), "(resources, 'QAP')\n", (1536, 1554), False, 'import os\n'), ((1577, 1609), 'os.path.join', 'os.path.join', (['resources', '"""Pairs"""'], {}), "(resources, 'Pairs')\n", (1589, 1609), False, 'import os\n'), ((1631, 1662), 'os.path.join', 'os.path.join', (['resources', '"""Full"""'], {}), "(resources, 'Full')\n", (1643, 1662), False, 'import os\n'), ((3105, 3152), 'os.path.join', 'os.path.join', (['resources_QAP', '"""means_widths.npy"""'], {}), "(resources_QAP, 'means_widths.npy')\n", (3117, 3152), False, 'import os\n'), ((3181, 3233), 'os.path.join', 'os.path.join', (['resources_QAP', '"""sigma_invs_widths.npy"""'], {}), "(resources_QAP, 'sigma_invs_widths.npy')\n", (3193, 3233), False, 'import os\n'), ((3256, 3302), 'os.path.join', 'os.path.join', (['resources_QAP', '"""means_pairs.npy"""'], {}), "(resources_QAP, 'means_pairs.npy')\n", (3268, 3302), False, 'import os\n'), ((3330, 3381), 'os.path.join', 'os.path.join', (['resources_QAP', '"""sigma_invs_pairs.npy"""'], {}), "(resources_QAP, 'sigma_invs_pairs.npy')\n", (3342, 3381), False, 'import os\n'), ((3389, 3427), 'numpy.save', 'np.save', (['op_means_widths', 'means_widths'], {}), '(op_means_widths, means_widths)\n', (3396, 3427), True, 'import numpy as np\n'), ((3433, 3481), 'numpy.save', 'np.save', (['op_sigma_invs_widths', 'sigma_invs_widths'], {}), '(op_sigma_invs_widths, sigma_invs_widths)\n', (3440, 3481), True, 'import numpy as np\n'), ((3487, 3523), 'numpy.save', 'np.save', (['op_means_pairs', 'means_pairs'], {}), '(op_means_pairs, means_pairs)\n', (3494, 3523), True, 'import numpy as np\n'), ((3529, 3575), 'numpy.save', 'np.save', (['op_sigma_invs_pairs', 'sigma_invs_pairs'], {}), '(op_sigma_invs_pairs, sigma_invs_pairs)\n', (3536, 3575), True, 'import numpy as np\n'), ((4596, 4644), 'os.path.join', 'os.path.join', (['resources_Pairs', '"""means_pairs.npy"""'], {}), "(resources_Pairs, 'means_pairs.npy')\n", (4608, 4644), False, 'import os\n'), ((4672, 4725), 'os.path.join', 'os.path.join', (['resources_Pairs', '"""sigma_invs_pairs.npy"""'], {}), "(resources_Pairs, 'sigma_invs_pairs.npy')\n", (4684, 4725), False, 'import os\n'), ((4750, 4800), 'os.path.join', 'os.path.join', (['resources_Pairs', '"""means_triples.npy"""'], {}), "(resources_Pairs, 'means_triples.npy')\n", (4762, 4800), False, 'import os\n'), ((4830, 4885), 'os.path.join', 'os.path.join', (['resources_Pairs', '"""sigma_invs_triples.npy"""'], {}), "(resources_Pairs, 'sigma_invs_triples.npy')\n", (4842, 4885), False, 'import os\n'), ((4893, 4929), 'numpy.save', 'np.save', (['op_means_pairs', 'means_pairs'], {}), '(op_means_pairs, means_pairs)\n', (4900, 4929), True, 'import numpy as np\n'), ((4935, 4981), 'numpy.save', 'np.save', (['op_sigma_invs_pairs', 'sigma_invs_pairs'], {}), '(op_sigma_invs_pairs, sigma_invs_pairs)\n', (4942, 4981), True, 'import numpy as np\n'), ((4987, 5027), 'numpy.save', 'np.save', (['op_means_triples', 'means_triples'], {}), '(op_means_triples, means_triples)\n', (4994, 5027), True, 'import numpy as np\n'), ((5033, 5083), 'numpy.save', 'np.save', (['op_sigma_invs_triples', 'sigma_invs_triples'], {}), '(op_sigma_invs_triples, sigma_invs_triples)\n', (5040, 5083), True, 'import numpy as np\n'), ((5456, 5506), 'os.path.join', 'os.path.join', (['resources_Full', '"""means_sequence.npy"""'], {}), "(resources_Full, 'means_sequence.npy')\n", (5468, 5506), False, 'import os\n'), ((5532, 5587), 'os.path.join', 'os.path.join', (['resources_Full', '"""sigma_invs_sequence.npy"""'], {}), "(resources_Full, 'sigma_invs_sequence.npy')\n", (5544, 5587), False, 'import os\n'), ((5618, 5673), 'os.path.join', 'os.path.join', (['resources_Full', '"""mean_cost_estimates.npy"""'], {}), "(resources_Full, 'mean_cost_estimates.npy')\n", (5630, 5673), False, 'import os\n'), ((5705, 5765), 'os.path.join', 'os.path.join', (['resources_Full', '"""sigma_inv_cost_estimates.npy"""'], {}), "(resources_Full, 'sigma_inv_cost_estimates.npy')\n", (5717, 5765), False, 'import os\n'), ((5773, 5818), 'numpy.save', 'np.save', (['op_means_seq', 'means_partial_sequence'], {}), '(op_means_seq, means_partial_sequence)\n', (5780, 5818), True, 'import numpy as np\n'), ((5824, 5879), 'numpy.save', 'np.save', (['op_sigma_invs_seq', 'sigma_invs_partial_sequence'], {}), '(op_sigma_invs_seq, sigma_invs_partial_sequence)\n', (5831, 5879), True, 'import numpy as np\n'), ((5885, 5937), 'numpy.save', 'np.save', (['op_mean_cost_estimates', 'mean_cost_estimates'], {}), '(op_mean_cost_estimates, mean_cost_estimates)\n', (5892, 5937), True, 'import numpy as np\n'), ((5943, 6001), 'numpy.save', 'np.save', (['op_sigma_cost_estimates', 'sigma_inv_cost_estimates'], {}), '(op_sigma_cost_estimates, sigma_inv_cost_estimates)\n', (5950, 6001), True, 'import numpy as np\n'), ((6958, 7007), 'os.path.join', 'os.path.join', (['resources_QAP', '"""means_widths_Q.npy"""'], {}), "(resources_QAP, 'means_widths_Q.npy')\n", (6970, 7007), False, 'import os\n'), ((7036, 7090), 'os.path.join', 'os.path.join', (['resources_QAP', '"""sigma_invs_widths_Q.npy"""'], {}), "(resources_QAP, 'sigma_invs_widths_Q.npy')\n", (7048, 7090), False, 'import os\n'), ((7113, 7161), 'os.path.join', 'os.path.join', (['resources_QAP', '"""means_pairs_Q.npy"""'], {}), "(resources_QAP, 'means_pairs_Q.npy')\n", (7125, 7161), False, 'import os\n'), ((7189, 7242), 'os.path.join', 'os.path.join', (['resources_QAP', '"""sigma_invs_pairs_Q.npy"""'], {}), "(resources_QAP, 'sigma_invs_pairs_Q.npy')\n", (7201, 7242), False, 'import os\n'), ((7250, 7288), 'numpy.save', 'np.save', (['op_means_widths', 'means_widths'], {}), '(op_means_widths, means_widths)\n', (7257, 7288), True, 'import numpy as np\n'), ((7294, 7342), 'numpy.save', 'np.save', (['op_sigma_invs_widths', 'sigma_invs_widths'], {}), '(op_sigma_invs_widths, sigma_invs_widths)\n', (7301, 7342), True, 'import numpy as np\n'), ((7348, 7384), 'numpy.save', 'np.save', (['op_means_pairs', 'means_pairs'], {}), '(op_means_pairs, means_pairs)\n', (7355, 7384), True, 'import numpy as np\n'), ((7390, 7436), 'numpy.save', 'np.save', (['op_sigma_invs_pairs', 'sigma_invs_pairs'], {}), '(op_sigma_invs_pairs, sigma_invs_pairs)\n', (7397, 7436), True, 'import numpy as np\n'), ((8457, 8507), 'os.path.join', 'os.path.join', (['resources_Pairs', '"""means_pairs_Q.npy"""'], {}), "(resources_Pairs, 'means_pairs_Q.npy')\n", (8469, 8507), False, 'import os\n'), ((8535, 8590), 'os.path.join', 'os.path.join', (['resources_Pairs', '"""sigma_invs_pairs_Q.npy"""'], {}), "(resources_Pairs, 'sigma_invs_pairs_Q.npy')\n", (8547, 8590), False, 'import os\n'), ((8615, 8667), 'os.path.join', 'os.path.join', (['resources_Pairs', '"""means_triples_Q.npy"""'], {}), "(resources_Pairs, 'means_triples_Q.npy')\n", (8627, 8667), False, 'import os\n'), ((8697, 8754), 'os.path.join', 'os.path.join', (['resources_Pairs', '"""sigma_invs_triples_Q.npy"""'], {}), "(resources_Pairs, 'sigma_invs_triples_Q.npy')\n", (8709, 8754), False, 'import os\n'), ((8762, 8798), 'numpy.save', 'np.save', (['op_means_pairs', 'means_pairs'], {}), '(op_means_pairs, means_pairs)\n', (8769, 8798), True, 'import numpy as np\n'), ((8804, 8850), 'numpy.save', 'np.save', (['op_sigma_invs_pairs', 'sigma_invs_pairs'], {}), '(op_sigma_invs_pairs, sigma_invs_pairs)\n', (8811, 8850), True, 'import numpy as np\n'), ((8856, 8896), 'numpy.save', 'np.save', (['op_means_triples', 'means_triples'], {}), '(op_means_triples, means_triples)\n', (8863, 8896), True, 'import numpy as np\n'), ((8902, 8952), 'numpy.save', 'np.save', (['op_sigma_invs_triples', 'sigma_invs_triples'], {}), '(op_sigma_invs_triples, sigma_invs_triples)\n', (8909, 8952), True, 'import numpy as np\n'), ((9325, 9377), 'os.path.join', 'os.path.join', (['resources_Full', '"""means_sequence_Q.npy"""'], {}), "(resources_Full, 'means_sequence_Q.npy')\n", (9337, 9377), False, 'import os\n'), ((9403, 9460), 'os.path.join', 'os.path.join', (['resources_Full', '"""sigma_invs_sequence_Q.npy"""'], {}), "(resources_Full, 'sigma_invs_sequence_Q.npy')\n", (9415, 9460), False, 'import os\n'), ((9491, 9548), 'os.path.join', 'os.path.join', (['resources_Full', '"""mean_cost_estimates_Q.npy"""'], {}), "(resources_Full, 'mean_cost_estimates_Q.npy')\n", (9503, 9548), False, 'import os\n'), ((9580, 9642), 'os.path.join', 'os.path.join', (['resources_Full', '"""sigma_inv_cost_estimates_Q.npy"""'], {}), "(resources_Full, 'sigma_inv_cost_estimates_Q.npy')\n", (9592, 9642), False, 'import os\n'), ((9650, 9695), 'numpy.save', 'np.save', (['op_means_seq', 'means_partial_sequence'], {}), '(op_means_seq, means_partial_sequence)\n', (9657, 9695), True, 'import numpy as np\n'), ((9701, 9756), 'numpy.save', 'np.save', (['op_sigma_invs_seq', 'sigma_invs_partial_sequence'], {}), '(op_sigma_invs_seq, sigma_invs_partial_sequence)\n', (9708, 9756), True, 'import numpy as np\n'), ((9762, 9814), 'numpy.save', 'np.save', (['op_mean_cost_estimates', 'mean_cost_estimates'], {}), '(op_mean_cost_estimates, mean_cost_estimates)\n', (9769, 9814), True, 'import numpy as np\n'), ((9820, 9878), 'numpy.save', 'np.save', (['op_sigma_cost_estimates', 'sigma_inv_cost_estimates'], {}), '(op_sigma_cost_estimates, sigma_inv_cost_estimates)\n', (9827, 9878), True, 'import numpy as np\n'), ((2312, 2349), 'os.path.join', 'os.path.join', (['data_dir', '"""keys_20.npy"""'], {}), "(data_dir, 'keys_20.npy')\n", (2324, 2349), False, 'import os\n'), ((2396, 2435), 'os.path.join', 'os.path.join', (['data_dir', '"""arrays_20.npy"""'], {}), "(data_dir, 'arrays_20.npy')\n", (2408, 2435), False, 'import os\n'), ((6165, 6202), 'os.path.join', 'os.path.join', (['data_dir', '"""keys_22.npy"""'], {}), "(data_dir, 'keys_22.npy')\n", (6177, 6202), False, 'import os\n'), ((6249, 6288), 'os.path.join', 'os.path.join', (['data_dir', '"""arrays_22.npy"""'], {}), "(data_dir, 'arrays_22.npy')\n", (6261, 6288), False, 'import os\n')] |
# -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
import os
from PIL import Image
import imghdr
import base64
from io import BytesIO
import dash
from dash.dependencies import Input,Output,State
import dash_table
import dash_core_components as dcc
import dash_html_components as html
from dash.exceptions import PreventUpdate
# ~ print('data/')
# ~ print('rank.npy')
file_list = []
label_list = []
character_list = []
current_label=None
font_type_dict={}
font_type_list=[]
font_type_list_count_dict={}
only_font_name_list=[]
single_font_name_list=[]
#filename,label,character--->list
for (dir,subs,files) in os.walk('data/'):
for file in files:
target=os.path.join(dir,file)
if os.path.isfile(target):
if imghdr.what(target)!=None:
file_list.append(target)
if os.path.basename(os.path.dirname(target))!=current_label:
current_label=os.path.basename(os.path.dirname(target))
label_list.append(os.path.basename(os.path.dirname(target)))
if len(label_list)<2:
character_list.append(os.path.splitext(os.path.basename(target))[0].split('_')[1])
file_list.sort()
label_list.sort()
character_list.sort()
#fontname-weight--->font_type_list,fontname--->single_font_name_list
for i in range(len(label_list)):
if current_label!=label_list[i].split('-')[0]:
c=0
current_label=label_list[i].split('-')[0]
font_type_list_count_dict[current_label]=0
font_type_list_count_dict[current_label]+=1
if len(label_list[i].split('-'))>1:
if c==0:
font_type_dict[current_label]=[label_list[i].split('-')[1]]
c=1
else:
font_type_dict[current_label].append(label_list[i].split('-')[1])
if not label_list[i].split('-')[1] in font_type_list:
font_type_list.append(label_list[i].split('-')[1])
else:
single_font_name_list.append(label_list[i])
only_font_name_list=list(font_type_list_count_dict.keys())
# ~ print(len(only_font_name_list))
# ~ print(len(single_font_name_list))
# ~ print('single check')
#display single font name
for i in range(len(single_font_name_list)):
if not single_font_name_list[i] in only_font_name_list:
print(i)
print(single_font_name_list[i])
# ~ print('check over')
current_result_nd=np.load('rank.npy')
# ~ print(current_result_nd)
current_result_df=pd.DataFrame(current_result_nd).rank()
# ~ print(current_result_df)
#image display function
def numpy_to_b64(array):
im_pil = Image.fromarray(array)
buff = BytesIO()
im_pil.save(buff, format="png")
im_b64 = base64.b64encode(buff.getvalue()).decode("utf-8")
return im_b64
#Dash app
app = dash.Dash(__name__)
server=app.server
app.layout = html.Div([
html.A(html.Div('What fonts are similar?',style={'fontSize':30}),href='https://fontcomparisonsystem.herokuapp.com/'),
html.Br(),
html.Div('Select Font',style={'fontSize':20}),
dcc.Dropdown(
id='labels',
options=[
{ 'label': x,'value': x} for x in label_list
],multi=True,value=[]
),
html.Div(id='output-labels',children='labels'),
html.Br(),
html.Div('Input Character 0〜9',style={'fontSize':20}),
html.Div(dcc.Input(id='input-box',type='text')),
html.Br(),
html.Div('Display Number',style={'fontSize':20}),
html.Div(dcc.Input(id='display-box',type='number',value='10')),
html.Button('Generate Images',id='images-button'),
html.Div(id='output-container-images'),
])
#labels_number
@app.callback(
Output('output-labels', 'children'),
[Input('labels', 'value')])
def update_output_methods(value):
now_labels=value
labels_number=len(now_labels)
return f'Labels:{labels_number}'
#image_generate
generate_count=0
@app.callback(
Output('output-container-images', 'children'),
[Input('labels','value'),
Input('input-box', 'value'),
Input('display-box','value'),
Input('images-button', 'n_clicks')])
def path_to_images(compare_labels,input_text,display_number,n_clicks):
global generate_count
global current_result_df
global label_list
global character_list
if n_clicks==None:
raise PreventUpdate
if generate_count<n_clicks:
generate_count+=1
# ~ print(compare_labels)
# ~ print(input_text)
# ~ print(display_number)
# ~ print(n_clicks)
# ~ print(generate_count)
temp_df=[]
ret_list=[]
flag=''
display_number=int(display_number)
if input_text==None:
return html.Div('Input text, please.',style={'fontSize':20}),
elif len(list(input_text))==0:
return html.Div('Input text, please.',style={'fontSize':20}),
else:
input_char=list(input_text)
# ~ print(input_char)
for h in range(len(input_char)):
if not input_char[h] in character_list:
flag='ex_char'
if flag=='ex_char':
return html.Div('Input 0〜9, please.',style={'fontSize':20}),
if len(compare_labels)==0:
return html.Div('Select font, please.',style={'fontSize':20}),
else:
for i in range(len(compare_labels)):
for j in range(len(input_char)):
image_temp=Image.open('data/'+f'{compare_labels[i]}/{compare_labels[i]}_{input_char[j]}.png')
if image_temp.mode!="L":
image=image_temp.convert("L")
else:
image=image_temp
img=np.array(image)
if j==0:
con_img=img
else:
con_img=np.hstack((con_img,img))
ret_list.append(html.Div(f'target{i+1}\'s name :',style={'fontSize':20}),)
font_name_char_list=list(compare_labels[i].split('-')[0])
for k in range(len(font_name_char_list)):
if k==0:
temp_name=font_name_char_list[k]
continue
else:
if font_name_char_list[k].isupper():
if not font_name_char_list[k-1].isupper():
temp_name+='+'
temp_name+=font_name_char_list[k]
ret_list.append(html.A(html.Div(f'{compare_labels[i]}',style={'fontSize':20}),href=f'https://fonts.google.com/specimen/{temp_name}'),)
# ~ print(f'target{i+1}\'s name : {compare_labels[i]} ok')
ret_list.append(html.Img(src='data:image/png;base64, ' + numpy_to_b64(con_img),style={'height': 'auto','display': 'block','margin': 'auto'}),)
if i==0:
temp_df=pd.DataFrame(current_result_df.iloc[:,label_list.index(compare_labels[i])])
else:
temp_df+=pd.DataFrame(current_result_df.iloc[:,label_list.index(compare_labels[i])]).values
temp_df/=len(compare_labels)
temp_df=temp_df.rank()
# ~ print(temp_df)
temp_df.sort_values(temp_df.columns.values[0],inplace=True)
# ~ print(temp_df)
font_index_list=temp_df.index.values
# ~ print(font_index_list)
count=0
font_count=0
for i in range(display_number):
for j in range(len(input_char)):
image_temp=Image.open('data/'+f'{label_list[font_index_list[i]]}/{label_list[font_index_list[i]]}_{input_char[j]}.png')
if image_temp.mode!="L":
image=image_temp.convert("L")
else:
image=image_temp
img=np.array(image)
if j==0:
con_img=img
else:
con_img=np.hstack((con_img,img))
ret_list.append(html.Div('Font\'s name :',style={'fontSize':20}),)
font_name_char_list=list(label_list[font_index_list[i]].split('-')[0])
for k in range(len(font_name_char_list)):
if k==0:
temp_name=font_name_char_list[k]
continue
else:
if font_name_char_list[k].isupper():
if not font_name_char_list[k-1].isupper():
temp_name+='+'
temp_name+=font_name_char_list[k]
ret_list.append(html.A(html.Div(f'{label_list[font_index_list[i]]}',style={'fontSize':20}),href=f'https://fonts.google.com/specimen/{temp_name}'),)
# ~ print(f'Font\'s name : {label_list[font_index_list[i]]} ok')
ret_list.append(html.Img(src='data:image/png;base64, ' + numpy_to_b64(con_img),style={'height': 'auto','display': 'block','margin': 'auto'}),)
ret_div=html.Div(ret_list),
return ret_div
elif n_clicks==1:
generate_count=n_clicks-1
if __name__ == '__main__':
app.run_server(debug=True)
| [
"numpy.hstack",
"dash_html_components.Button",
"io.BytesIO",
"dash.dependencies.Input",
"numpy.array",
"dash_html_components.Div",
"dash.Dash",
"os.walk",
"dash.dependencies.Output",
"dash_html_components.Br",
"pandas.DataFrame",
"os.path.isfile",
"os.path.dirname",
"PIL.Image.fromarray",
... | [((624, 640), 'os.walk', 'os.walk', (['"""data/"""'], {}), "('data/')\n", (631, 640), False, 'import os\n'), ((2181, 2200), 'numpy.load', 'np.load', (['"""rank.npy"""'], {}), "('rank.npy')\n", (2188, 2200), True, 'import numpy as np\n'), ((2542, 2561), 'dash.Dash', 'dash.Dash', (['__name__'], {}), '(__name__)\n', (2551, 2561), False, 'import dash\n'), ((2376, 2398), 'PIL.Image.fromarray', 'Image.fromarray', (['array'], {}), '(array)\n', (2391, 2398), False, 'from PIL import Image\n'), ((2407, 2416), 'io.BytesIO', 'BytesIO', ([], {}), '()\n', (2414, 2416), False, 'from io import BytesIO\n'), ((3326, 3361), 'dash.dependencies.Output', 'Output', (['"""output-labels"""', '"""children"""'], {}), "('output-labels', 'children')\n", (3332, 3361), False, 'from dash.dependencies import Input, Output, State\n'), ((3559, 3604), 'dash.dependencies.Output', 'Output', (['"""output-container-images"""', '"""children"""'], {}), "('output-container-images', 'children')\n", (3565, 3604), False, 'from dash.dependencies import Input, Output, State\n'), ((671, 694), 'os.path.join', 'os.path.join', (['dir', 'file'], {}), '(dir, file)\n', (683, 694), False, 'import os\n'), ((699, 721), 'os.path.isfile', 'os.path.isfile', (['target'], {}), '(target)\n', (713, 721), False, 'import os\n'), ((2248, 2279), 'pandas.DataFrame', 'pd.DataFrame', (['current_result_nd'], {}), '(current_result_nd)\n', (2260, 2279), True, 'import pandas as pd\n'), ((2726, 2735), 'dash_html_components.Br', 'html.Br', ([], {}), '()\n', (2733, 2735), True, 'import dash_html_components as html\n'), ((2738, 2785), 'dash_html_components.Div', 'html.Div', (['"""Select Font"""'], {'style': "{'fontSize': 20}"}), "('Select Font', style={'fontSize': 20})\n", (2746, 2785), True, 'import dash_html_components as html\n'), ((2786, 2893), 'dash_core_components.Dropdown', 'dcc.Dropdown', ([], {'id': '"""labels"""', 'options': "[{'label': x, 'value': x} for x in label_list]", 'multi': '(True)', 'value': '[]'}), "(id='labels', options=[{'label': x, 'value': x} for x in\n label_list], multi=True, value=[])\n", (2798, 2893), True, 'import dash_core_components as dcc\n'), ((2904, 2951), 'dash_html_components.Div', 'html.Div', ([], {'id': '"""output-labels"""', 'children': '"""labels"""'}), "(id='output-labels', children='labels')\n", (2912, 2951), True, 'import dash_html_components as html\n'), ((2953, 2962), 'dash_html_components.Br', 'html.Br', ([], {}), '()\n', (2960, 2962), True, 'import dash_html_components as html\n'), ((2965, 3020), 'dash_html_components.Div', 'html.Div', (['"""Input Character 0〜9"""'], {'style': "{'fontSize': 20}"}), "('Input Character 0〜9', style={'fontSize': 20})\n", (2973, 3020), True, 'import dash_html_components as html\n'), ((3071, 3080), 'dash_html_components.Br', 'html.Br', ([], {}), '()\n', (3078, 3080), True, 'import dash_html_components as html\n'), ((3083, 3133), 'dash_html_components.Div', 'html.Div', (['"""Display Number"""'], {'style': "{'fontSize': 20}"}), "('Display Number', style={'fontSize': 20})\n", (3091, 3133), True, 'import dash_html_components as html\n'), ((3199, 3249), 'dash_html_components.Button', 'html.Button', (['"""Generate Images"""'], {'id': '"""images-button"""'}), "('Generate Images', id='images-button')\n", (3210, 3249), True, 'import dash_html_components as html\n'), ((3251, 3289), 'dash_html_components.Div', 'html.Div', ([], {'id': '"""output-container-images"""'}), "(id='output-container-images')\n", (3259, 3289), True, 'import dash_html_components as html\n'), ((3365, 3389), 'dash.dependencies.Input', 'Input', (['"""labels"""', '"""value"""'], {}), "('labels', 'value')\n", (3370, 3389), False, 'from dash.dependencies import Input, Output, State\n'), ((3608, 3632), 'dash.dependencies.Input', 'Input', (['"""labels"""', '"""value"""'], {}), "('labels', 'value')\n", (3613, 3632), False, 'from dash.dependencies import Input, Output, State\n'), ((3634, 3661), 'dash.dependencies.Input', 'Input', (['"""input-box"""', '"""value"""'], {}), "('input-box', 'value')\n", (3639, 3661), False, 'from dash.dependencies import Input, Output, State\n'), ((3664, 3693), 'dash.dependencies.Input', 'Input', (['"""display-box"""', '"""value"""'], {}), "('display-box', 'value')\n", (3669, 3693), False, 'from dash.dependencies import Input, Output, State\n'), ((3695, 3729), 'dash.dependencies.Input', 'Input', (['"""images-button"""', '"""n_clicks"""'], {}), "('images-button', 'n_clicks')\n", (3700, 3729), False, 'from dash.dependencies import Input, Output, State\n'), ((2614, 2673), 'dash_html_components.Div', 'html.Div', (['"""What fonts are similar?"""'], {'style': "{'fontSize': 30}"}), "('What fonts are similar?', style={'fontSize': 30})\n", (2622, 2673), True, 'import dash_html_components as html\n'), ((3030, 3068), 'dash_core_components.Input', 'dcc.Input', ([], {'id': '"""input-box"""', 'type': '"""text"""'}), "(id='input-box', type='text')\n", (3039, 3068), True, 'import dash_core_components as dcc\n'), ((3143, 3197), 'dash_core_components.Input', 'dcc.Input', ([], {'id': '"""display-box"""', 'type': '"""number"""', 'value': '"""10"""'}), "(id='display-box', type='number', value='10')\n", (3152, 3197), True, 'import dash_core_components as dcc\n'), ((729, 748), 'imghdr.what', 'imghdr.what', (['target'], {}), '(target)\n', (740, 748), False, 'import imghdr\n'), ((4222, 4277), 'dash_html_components.Div', 'html.Div', (['"""Input text, please."""'], {'style': "{'fontSize': 20}"}), "('Input text, please.', style={'fontSize': 20})\n", (4230, 4277), True, 'import dash_html_components as html\n'), ((4320, 4375), 'dash_html_components.Div', 'html.Div', (['"""Input text, please."""'], {'style': "{'fontSize': 20}"}), "('Input text, please.', style={'fontSize': 20})\n", (4328, 4375), True, 'import dash_html_components as html\n'), ((809, 832), 'os.path.dirname', 'os.path.dirname', (['target'], {}), '(target)\n', (824, 832), False, 'import os\n'), ((886, 909), 'os.path.dirname', 'os.path.dirname', (['target'], {}), '(target)\n', (901, 909), False, 'import os\n'), ((4573, 4627), 'dash_html_components.Div', 'html.Div', (['"""Input 0〜9, please."""'], {'style': "{'fontSize': 20}"}), "('Input 0〜9, please.', style={'fontSize': 20})\n", (4581, 4627), True, 'import dash_html_components as html\n'), ((4668, 4724), 'dash_html_components.Div', 'html.Div', (['"""Select font, please."""'], {'style': "{'fontSize': 20}"}), "('Select font, please.', style={'fontSize': 20})\n", (4676, 4724), True, 'import dash_html_components as html\n'), ((7643, 7661), 'dash_html_components.Div', 'html.Div', (['ret_list'], {}), '(ret_list)\n', (7651, 7661), True, 'import dash_html_components as html\n'), ((951, 974), 'os.path.dirname', 'os.path.dirname', (['target'], {}), '(target)\n', (966, 974), False, 'import os\n'), ((4829, 4917), 'PIL.Image.open', 'Image.open', (["('data/' + f'{compare_labels[i]}/{compare_labels[i]}_{input_char[j]}.png')"], {}), "('data/' +\n f'{compare_labels[i]}/{compare_labels[i]}_{input_char[j]}.png')\n", (4839, 4917), False, 'from PIL import Image\n'), ((5026, 5041), 'numpy.array', 'np.array', (['image'], {}), '(image)\n', (5034, 5041), True, 'import numpy as np\n'), ((5149, 5208), 'dash_html_components.Div', 'html.Div', (['f"""target{i + 1}\'s name :"""'], {'style': "{'fontSize': 20}"}), '(f"target{i + 1}\'s name :", style={\'fontSize\': 20})\n', (5157, 5208), True, 'import dash_html_components as html\n'), ((6497, 6616), 'PIL.Image.open', 'Image.open', (["('data/' +\n f'{label_list[font_index_list[i]]}/{label_list[font_index_list[i]]}_{input_char[j]}.png'\n )"], {}), "('data/' +\n f'{label_list[font_index_list[i]]}/{label_list[font_index_list[i]]}_{input_char[j]}.png'\n )\n", (6507, 6616), False, 'from PIL import Image\n'), ((6720, 6735), 'numpy.array', 'np.array', (['image'], {}), '(image)\n', (6728, 6735), True, 'import numpy as np\n'), ((6843, 6892), 'dash_html_components.Div', 'html.Div', (['"""Font\'s name :"""'], {'style': "{'fontSize': 20}"}), '("Font\'s name :", style={\'fontSize\': 20})\n', (6851, 6892), True, 'import dash_html_components as html\n'), ((5103, 5128), 'numpy.hstack', 'np.hstack', (['(con_img, img)'], {}), '((con_img, img))\n', (5112, 5128), True, 'import numpy as np\n'), ((5589, 5645), 'dash_html_components.Div', 'html.Div', (['f"""{compare_labels[i]}"""'], {'style': "{'fontSize': 20}"}), "(f'{compare_labels[i]}', style={'fontSize': 20})\n", (5597, 5645), True, 'import dash_html_components as html\n'), ((6797, 6822), 'numpy.hstack', 'np.hstack', (['(con_img, img)'], {}), '((con_img, img))\n', (6806, 6822), True, 'import numpy as np\n'), ((7288, 7357), 'dash_html_components.Div', 'html.Div', (['f"""{label_list[font_index_list[i]]}"""'], {'style': "{'fontSize': 20}"}), "(f'{label_list[font_index_list[i]]}', style={'fontSize': 20})\n", (7296, 7357), True, 'import dash_html_components as html\n'), ((1047, 1071), 'os.path.basename', 'os.path.basename', (['target'], {}), '(target)\n', (1063, 1071), False, 'import os\n')] |
from xfit.fitting import fit_dataArray, fit_dataArray_models, fit_dataset
import numpy as np
import xarray as xr
from xarray.testing import assert_equal, assert_allclose
bs = xr.DataArray(np.linspace(0,10,6), coords={'b_true': np.linspace(0,10,6)}, dims='b_true')
xs = xr.DataArray(np.linspace(0,10,11), coords={'x': np.linspace(0,10,11)}, dims='x')
data = xr.DataArray(
np.ones((1,10))*np.arange(5).reshape(5,1),
dims=['b_true','x'],
coords={
'b_true': np.arange(5),
'x': np.arange(10)
}
)
data_ds = xr.Dataset({'data': data})
expected_popt = xr.DataArray(np.arange(5).reshape(1,5),
coords={'param': ['b'], 'b_true': np.arange(5)},
dims=['param', 'b_true'])
expected_perr = xr.DataArray(np.zeros((1,5)),
coords={'param': ['b'], 'b_true': np.arange(5)},
dims=['param', 'b_true'])
expected_pcov = xr.DataArray(np.zeros((1,1,5)),
coords={'param_cov': ['b'], 'param': ['b'], 'b_true': np.arange(5)},
dims=['param_cov', 'param', 'b_true'])
expected_xda = data.coords['x']
expected_yda = data
expected_yerr_da = xr.full_like(expected_yda, np.nan, float)
def const(x, b):
return b
def const_guess(x, y, **kwargs):
return np.mean(y)
const_params = ['b']
def test_basic_fit_dataArray():
actual = fit_dataArray(data, const, const_guess, const_params, 'x')
expected = xr.Dataset(
{
'popt': expected_popt,
'perr': expected_perr,
'pcov': expected_pcov,
'xda': expected_xda,
'yda': expected_yda,
'yerr_da': expected_yerr_da
},
attrs={'fit_func': const, 'param_names': ['b'], 'xname': 'x', 'yname': None})
assert_equal(expected, actual)
def test_basic_fit_dataset():
actual = fit_dataset(data_ds, const, const_guess, const_params, 'x', 'data')
expected = xr.Dataset(
{
'popt': expected_popt,
'perr': expected_perr,
'pcov': expected_pcov,
'xda': expected_xda,
'yda': expected_yda,
'yerr_da': expected_yerr_da
},
attrs={'fit_func': const, 'param_names': ['b'], 'xname': 'x', 'yname': None})
assert_equal(expected, actual) | [
"numpy.mean",
"numpy.ones",
"xfit.fitting.fit_dataset",
"xarray.Dataset",
"numpy.linspace",
"numpy.zeros",
"xarray.full_like",
"xfit.fitting.fit_dataArray",
"xarray.testing.assert_equal",
"numpy.arange"
] | [((544, 570), 'xarray.Dataset', 'xr.Dataset', (["{'data': data}"], {}), "({'data': data})\n", (554, 570), True, 'import xarray as xr\n'), ((1231, 1272), 'xarray.full_like', 'xr.full_like', (['expected_yda', 'np.nan', 'float'], {}), '(expected_yda, np.nan, float)\n', (1243, 1272), True, 'import xarray as xr\n'), ((191, 212), 'numpy.linspace', 'np.linspace', (['(0)', '(10)', '(6)'], {}), '(0, 10, 6)\n', (202, 212), True, 'import numpy as np\n'), ((285, 307), 'numpy.linspace', 'np.linspace', (['(0)', '(10)', '(11)'], {}), '(0, 10, 11)\n', (296, 307), True, 'import numpy as np\n'), ((792, 808), 'numpy.zeros', 'np.zeros', (['(1, 5)'], {}), '((1, 5))\n', (800, 808), True, 'import numpy as np\n'), ((973, 992), 'numpy.zeros', 'np.zeros', (['(1, 1, 5)'], {}), '((1, 1, 5))\n', (981, 992), True, 'import numpy as np\n'), ((1349, 1359), 'numpy.mean', 'np.mean', (['y'], {}), '(y)\n', (1356, 1359), True, 'import numpy as np\n'), ((1428, 1486), 'xfit.fitting.fit_dataArray', 'fit_dataArray', (['data', 'const', 'const_guess', 'const_params', '"""x"""'], {}), "(data, const, const_guess, const_params, 'x')\n", (1441, 1486), False, 'from xfit.fitting import fit_dataArray, fit_dataArray_models, fit_dataset\n'), ((1507, 1749), 'xarray.Dataset', 'xr.Dataset', (["{'popt': expected_popt, 'perr': expected_perr, 'pcov': expected_pcov, 'xda':\n expected_xda, 'yda': expected_yda, 'yerr_da': expected_yerr_da}"], {'attrs': "{'fit_func': const, 'param_names': ['b'], 'xname': 'x', 'yname': None}"}), "({'popt': expected_popt, 'perr': expected_perr, 'pcov':\n expected_pcov, 'xda': expected_xda, 'yda': expected_yda, 'yerr_da':\n expected_yerr_da}, attrs={'fit_func': const, 'param_names': ['b'],\n 'xname': 'x', 'yname': None})\n", (1517, 1749), True, 'import xarray as xr\n'), ((1846, 1876), 'xarray.testing.assert_equal', 'assert_equal', (['expected', 'actual'], {}), '(expected, actual)\n', (1858, 1876), False, 'from xarray.testing import assert_equal, assert_allclose\n'), ((1921, 1988), 'xfit.fitting.fit_dataset', 'fit_dataset', (['data_ds', 'const', 'const_guess', 'const_params', '"""x"""', '"""data"""'], {}), "(data_ds, const, const_guess, const_params, 'x', 'data')\n", (1932, 1988), False, 'from xfit.fitting import fit_dataArray, fit_dataArray_models, fit_dataset\n'), ((2005, 2247), 'xarray.Dataset', 'xr.Dataset', (["{'popt': expected_popt, 'perr': expected_perr, 'pcov': expected_pcov, 'xda':\n expected_xda, 'yda': expected_yda, 'yerr_da': expected_yerr_da}"], {'attrs': "{'fit_func': const, 'param_names': ['b'], 'xname': 'x', 'yname': None}"}), "({'popt': expected_popt, 'perr': expected_perr, 'pcov':\n expected_pcov, 'xda': expected_xda, 'yda': expected_yda, 'yerr_da':\n expected_yerr_da}, attrs={'fit_func': const, 'param_names': ['b'],\n 'xname': 'x', 'yname': None})\n", (2015, 2247), True, 'import xarray as xr\n'), ((2340, 2370), 'xarray.testing.assert_equal', 'assert_equal', (['expected', 'actual'], {}), '(expected, actual)\n', (2352, 2370), False, 'from xarray.testing import assert_equal, assert_allclose\n'), ((379, 395), 'numpy.ones', 'np.ones', (['(1, 10)'], {}), '((1, 10))\n', (386, 395), True, 'import numpy as np\n'), ((230, 251), 'numpy.linspace', 'np.linspace', (['(0)', '(10)', '(6)'], {}), '(0, 10, 6)\n', (241, 251), True, 'import numpy as np\n'), ((320, 342), 'numpy.linspace', 'np.linspace', (['(0)', '(10)', '(11)'], {}), '(0, 10, 11)\n', (331, 342), True, 'import numpy as np\n'), ((480, 492), 'numpy.arange', 'np.arange', (['(5)'], {}), '(5)\n', (489, 492), True, 'import numpy as np\n'), ((507, 520), 'numpy.arange', 'np.arange', (['(10)'], {}), '(10)\n', (516, 520), True, 'import numpy as np\n'), ((601, 613), 'numpy.arange', 'np.arange', (['(5)'], {}), '(5)\n', (610, 613), True, 'import numpy as np\n'), ((692, 704), 'numpy.arange', 'np.arange', (['(5)'], {}), '(5)\n', (701, 704), True, 'import numpy as np\n'), ((873, 885), 'numpy.arange', 'np.arange', (['(5)'], {}), '(5)\n', (882, 885), True, 'import numpy as np\n'), ((1076, 1088), 'numpy.arange', 'np.arange', (['(5)'], {}), '(5)\n', (1085, 1088), True, 'import numpy as np\n'), ((395, 407), 'numpy.arange', 'np.arange', (['(5)'], {}), '(5)\n', (404, 407), True, 'import numpy as np\n')] |
from os import path
import numpy as np
from vision.domain.iCameraCalibration import ICameraCalibration
from vision.domain.iCameraCalibrationFactory import ICameraCalibrationFactory
from vision.infrastructure.fallbackCameraCalibration import FallBackCameraCalibration
from vision.infrastructure.openCvCameraCalibration import OpenCvCameraCalibration
class OpenCvCameraCalibrationFactory(ICameraCalibrationFactory):
def load_calibration_from_file(self, calibration_file_path: path, image_width: int,
image_height: int) -> ICameraCalibration:
if calibration_file_path is None:
return FallBackCameraCalibration()
arrays = np.load(calibration_file_path)
camera_matrix = arrays['camera_matrix']
distortion_coefficients = arrays['distortion_coefficients']
return OpenCvCameraCalibration(camera_matrix, distortion_coefficients, image_width, image_height)
| [
"vision.infrastructure.fallbackCameraCalibration.FallBackCameraCalibration",
"vision.infrastructure.openCvCameraCalibration.OpenCvCameraCalibration",
"numpy.load"
] | [((690, 720), 'numpy.load', 'np.load', (['calibration_file_path'], {}), '(calibration_file_path)\n', (697, 720), True, 'import numpy as np\n'), ((853, 947), 'vision.infrastructure.openCvCameraCalibration.OpenCvCameraCalibration', 'OpenCvCameraCalibration', (['camera_matrix', 'distortion_coefficients', 'image_width', 'image_height'], {}), '(camera_matrix, distortion_coefficients, image_width,\n image_height)\n', (876, 947), False, 'from vision.infrastructure.openCvCameraCalibration import OpenCvCameraCalibration\n'), ((644, 671), 'vision.infrastructure.fallbackCameraCalibration.FallBackCameraCalibration', 'FallBackCameraCalibration', ([], {}), '()\n', (669, 671), False, 'from vision.infrastructure.fallbackCameraCalibration import FallBackCameraCalibration\n')] |
"""
Test script for the ReplayMemory
"""
import unittest
from models.utils.replay_memory import ReplayMemory
import numpy as np
class DummyTupleGenerator:
def __init__(self, input_shape, action_space):
self.state_number = 0
self.last_action = 0
self.input_shape = input_shape
self.action_space = action_space
def get_next_tuple(self):
next_tuple = (self._get_state(self.state_number),
self._get_action(),
self._get_reward(self.state_number),
self._get_state(self.state_number + 1),
self._get_done(self.state_number))
self.state_number += 1
return next_tuple
def _get_action(self):
if self.last_action + 1 > self.action_space:
self.last_action = 0
else:
self.last_action += 1
return self.last_action
def _get_state(self, state_nr):
return state_nr * np.ones(self.input_shape)
@staticmethod
def _get_reward(state_nr):
return state_nr
@staticmethod
def _get_done(state_nr):
return state_nr % 100 == 0
class TestReplayMemory(unittest.TestCase):
"""
Testing class for the InsertCoin class.
"""
def setUp(self):
"""
Set-up for data fixtures per test .
"""
memory_length = 500
input_shape = (20, 20, 1)
action_space = 4
self.dummy_agent = DummyTupleGenerator(input_shape, action_space)
self.memory = ReplayMemory(memory_length, input_shape, action_space)
def test_remember(self):
""""
Test if the remember function works correctly.
"""
self.memory.remember(*self.dummy_agent.get_next_tuple())
self.memory.remember(*self.dummy_agent.get_next_tuple())
self.memory.remember(*self.dummy_agent.get_next_tuple())
def test_get(self):
""""
Test if the correct items are returned.
"""
first_tuple = self.dummy_agent.get_next_tuple()
self.memory.remember(*first_tuple)
# Store a tuple inside the memory to check later.
second_tuple = self.dummy_agent.get_next_tuple()
self.memory.remember(*second_tuple)
# Add another tuple
last_tuple = self.dummy_agent.get_next_tuple()
self.memory.remember(*last_tuple)
self.assertEqual(self.memory[0], first_tuple)
self.assertEqual(self.memory[1], second_tuple)
self.assertEqual(self.memory[2], last_tuple)
self.assertEqual(self.memory[-1], last_tuple)
def test_set(self):
""""
Test if the correct items are set.
"""
self.memory.remember(*self.dummy_agent.get_next_tuple())
self.memory.remember(*self.dummy_agent.get_next_tuple())
self.memory.remember(*self.dummy_agent.get_next_tuple())
self.memory[1] = (0, 1, 2, 3, 4)
self.assertEqual(self.memory[1], (0, 1, 2, 3, 4))
def test_length(self):
""""
Test if the correct length is shown.
"""
self.memory.remember(*self.dummy_agent.get_next_tuple())
self.memory.remember(*self.dummy_agent.get_next_tuple())
self.memory.remember(*self.dummy_agent.get_next_tuple())
self.assertEqual(len(self.memory), 3)
def test_fifo(self):
""""
Test if the first in first out principle holds for the memory.
"""
for _ in range(505):
self.memory.remember(*self.dummy_agent.get_next_tuple())
self.assertEqual(self.memory[0][2], 5)
self.assertEqual(self.memory[499][2], 504)
def test_next_prev(self):
""""
Test if the next state item in tuple x corresponds to state in tuple x+1
"""
for _ in range(500):
self.memory.remember(*self.dummy_agent.get_next_tuple())
for idx in range(490):
self.assertTrue(np.all(self.memory[idx][3] == self.memory[idx + 1][0]))
def test_random_sample(self):
""""
Test if the random sample function returns the correct number of tuples, and whether these tuples exists.
"""
pass
def test_load(self):
""""
Test the load function for the ReplayMemory.
"""
pass
def test_save(self):
""""
Test the save function for the ReplayMemory.
"""
pass
| [
"numpy.ones",
"numpy.all",
"models.utils.replay_memory.ReplayMemory"
] | [((1534, 1588), 'models.utils.replay_memory.ReplayMemory', 'ReplayMemory', (['memory_length', 'input_shape', 'action_space'], {}), '(memory_length, input_shape, action_space)\n', (1546, 1588), False, 'from models.utils.replay_memory import ReplayMemory\n'), ((973, 998), 'numpy.ones', 'np.ones', (['self.input_shape'], {}), '(self.input_shape)\n', (980, 998), True, 'import numpy as np\n'), ((3936, 3990), 'numpy.all', 'np.all', (['(self.memory[idx][3] == self.memory[idx + 1][0])'], {}), '(self.memory[idx][3] == self.memory[idx + 1][0])\n', (3942, 3990), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
#
# Helper functions for frontend test design
#
# The runner signatures take a callable,
# the `method_call`, as 1st argument
#
# 3rd party imports
import itertools
import numpy as np
from syncopy.shared.errors import SPYValueError, SPYTypeError
# fix random generators
np.random.seed(40203)
def run_padding_test(method_call, pad_length):
"""
The callable should test a solution and support
a single keyword argument `pad_to_length`
"""
pad_options = [pad_length, 'nextpow2', None]
for pad in pad_options:
method_call(pad_to_length=pad)
# test invalid pads
try:
method_call(pad_to_length=2)
except SPYValueError as err:
assert 'pad_to_length' in str(err)
assert 'expected value to be greater' in str(err)
try:
method_call(pad_to_length='IamNoPad')
except SPYValueError as err:
assert 'Invalid value of `pad_to_length`' in str(err)
assert 'nextpow2' in str(err)
try:
method_call(pad_to_length=np.array([1000]))
except SPYValueError as err:
assert 'Invalid value of `pad_to_length`' in str(err)
assert 'nextpow2' in str(err)
def run_polyremoval_test(method_call):
"""
The callable should test a solution and support
a single keyword argument `polyremoval`
"""
poly_options = [0, 1]
for poly in poly_options:
method_call(polyremoval=poly)
# test invalid polyremoval options
try:
method_call(polyremoval=2)
except SPYValueError as err:
assert 'polyremoval' in str(err)
assert 'expected value to be greater' in str(err)
try:
method_call(polyremoval='IamNoPad')
except SPYTypeError as err:
assert 'Wrong type of `polyremoval`' in str(err)
try:
method_call(polyremoval=np.array([1000]))
except SPYTypeError as err:
assert 'Wrong type of `polyremoval`' in str(err)
def run_foi_test(method_call, foilim, positivity=True):
# only positive frequencies
assert np.min(foilim) >= 0
assert np.max(foilim) <= 500
# fois
foi1 = np.arange(foilim[0], foilim[1]) # 1Hz steps
foi2 = np.arange(foilim[0], foilim[1], 0.25) # 0.5Hz steps
foi3 = 'all'
fois = [foi1, foi2, foi3, None]
for foi in fois:
result = method_call(foi=foi, foilim=None)
# check here just for finiteness and positivity
assert np.all(np.isfinite(result.data))
if positivity:
assert np.all(result.data[0, ...] >= -1e-10)
# 2 foilims
foilims = [[2, 60], [7.65, 45.1234], None]
for foil in foilims:
result = method_call(foilim=foil, foi=None)
# check here just for finiteness and positivity
assert np.all(np.isfinite(result.data))
if positivity:
assert np.all(result.data[0, ...] >= -1e-10)
# make sure specification of both foi and foilim triggers a
# Syncopy ValueError
try:
result = method_call(foi=foi, foilim=foil)
except SPYValueError as err:
assert 'foi/foilim' in str(err)
# make sure out-of-range foi selections are detected
try:
result = method_call(foilim=[-1, 70], foi=None)
except SPYValueError as err:
assert 'foilim' in str(err)
assert 'bounded by' in str(err)
try:
result = method_call(foi=np.arange(550, 700), foilim=None)
except SPYValueError as err:
assert 'foi' in str(err)
assert 'bounded by' in str(err)
def mk_selection_dicts(nTrials, nChannels, toi_min, toi_max, min_len=0.25):
"""
Takes 4 numbers, the last two descibing a time-interval
Returns
-------
selections : list
The list of dicts holding the keys and values for
Syncopy selections.
"""
# at least 10 trials
assert nTrials > 9
# at least 2 channels
assert nChannels > 1
# at least 250ms
assert (toi_max - toi_min) > 0.25
# create 3 random trial and channel selections
trials, channels = [], []
for _ in range(3):
sizeTr = np.random.randint(10, nTrials + 1)
trials.append(list(np.random.choice(
nTrials, size=sizeTr
)
))
sizeCh = np.random.randint(2, nChannels + 1)
channels.append(['channel' + str(i + 1)
for i in
np.random.choice(
nChannels, size=sizeCh, replace=False)])
# create toi selections, signal length is toi_max
# with -1s as offset (from synthetic data instantiation)
# subsampling does NOT WORK due to precision issues :/
# toi1 = np.linspace(-.4, 2, 100)
tois = [None, 'all']
toi_combinations = itertools.product(trials,
channels,
tois)
# 2 random toilims
toilims = []
while len(toilims) < 2:
toil = np.sort(np.random.rand(2)) * (toi_max - toi_min) + toi_min
# at least min_len (250ms)
if np.diff(toil) < min_len:
continue
else:
toilims.append(toil)
# combinatorics of all selection options
# order matters to assign the selection dict keys!
toilim_combinations = itertools.product(trials,
channels,
toilims)
selections = []
# digest generators to create all selection dictionaries
for comb in toi_combinations:
sel_dct = {}
sel_dct['trials'] = comb[0]
sel_dct['channel'] = comb[1]
sel_dct['toi'] = comb[2]
selections.append(sel_dct)
for comb in toilim_combinations:
sel_dct = {}
sel_dct['trials'] = comb[0]
sel_dct['channel'] = comb[1]
sel_dct['toilim'] = comb[2]
selections.append(sel_dct)
return selections
| [
"numpy.random.rand",
"numpy.random.choice",
"itertools.product",
"numpy.diff",
"numpy.max",
"numpy.array",
"numpy.random.randint",
"numpy.isfinite",
"numpy.random.seed",
"numpy.min",
"numpy.all",
"numpy.arange"
] | [((297, 318), 'numpy.random.seed', 'np.random.seed', (['(40203)'], {}), '(40203)\n', (311, 318), True, 'import numpy as np\n'), ((2122, 2153), 'numpy.arange', 'np.arange', (['foilim[0]', 'foilim[1]'], {}), '(foilim[0], foilim[1])\n', (2131, 2153), True, 'import numpy as np\n'), ((2178, 2215), 'numpy.arange', 'np.arange', (['foilim[0]', 'foilim[1]', '(0.25)'], {}), '(foilim[0], foilim[1], 0.25)\n', (2187, 2215), True, 'import numpy as np\n'), ((4718, 4759), 'itertools.product', 'itertools.product', (['trials', 'channels', 'tois'], {}), '(trials, channels, tois)\n', (4735, 4759), False, 'import itertools\n'), ((5252, 5296), 'itertools.product', 'itertools.product', (['trials', 'channels', 'toilims'], {}), '(trials, channels, toilims)\n', (5269, 5296), False, 'import itertools\n'), ((2046, 2060), 'numpy.min', 'np.min', (['foilim'], {}), '(foilim)\n', (2052, 2060), True, 'import numpy as np\n'), ((2077, 2091), 'numpy.max', 'np.max', (['foilim'], {}), '(foilim)\n', (2083, 2091), True, 'import numpy as np\n'), ((4074, 4108), 'numpy.random.randint', 'np.random.randint', (['(10)', '(nTrials + 1)'], {}), '(10, nTrials + 1)\n', (4091, 4108), True, 'import numpy as np\n'), ((4226, 4261), 'numpy.random.randint', 'np.random.randint', (['(2)', '(nChannels + 1)'], {}), '(2, nChannels + 1)\n', (4243, 4261), True, 'import numpy as np\n'), ((2435, 2459), 'numpy.isfinite', 'np.isfinite', (['result.data'], {}), '(result.data)\n', (2446, 2459), True, 'import numpy as np\n'), ((2503, 2540), 'numpy.all', 'np.all', (['(result.data[0, ...] >= -1e-10)'], {}), '(result.data[0, ...] >= -1e-10)\n', (2509, 2540), True, 'import numpy as np\n'), ((2760, 2784), 'numpy.isfinite', 'np.isfinite', (['result.data'], {}), '(result.data)\n', (2771, 2784), True, 'import numpy as np\n'), ((2828, 2865), 'numpy.all', 'np.all', (['(result.data[0, ...] >= -1e-10)'], {}), '(result.data[0, ...] >= -1e-10)\n', (2834, 2865), True, 'import numpy as np\n'), ((5032, 5045), 'numpy.diff', 'np.diff', (['toil'], {}), '(toil)\n', (5039, 5045), True, 'import numpy as np\n'), ((1037, 1053), 'numpy.array', 'np.array', (['[1000]'], {}), '([1000])\n', (1045, 1053), True, 'import numpy as np\n'), ((1837, 1853), 'numpy.array', 'np.array', (['[1000]'], {}), '([1000])\n', (1845, 1853), True, 'import numpy as np\n'), ((3364, 3383), 'numpy.arange', 'np.arange', (['(550)', '(700)'], {}), '(550, 700)\n', (3373, 3383), True, 'import numpy as np\n'), ((4136, 4174), 'numpy.random.choice', 'np.random.choice', (['nTrials'], {'size': 'sizeTr'}), '(nTrials, size=sizeTr)\n', (4152, 4174), True, 'import numpy as np\n'), ((4369, 4424), 'numpy.random.choice', 'np.random.choice', (['nChannels'], {'size': 'sizeCh', 'replace': '(False)'}), '(nChannels, size=sizeCh, replace=False)\n', (4385, 4424), True, 'import numpy as np\n'), ((4935, 4952), 'numpy.random.rand', 'np.random.rand', (['(2)'], {}), '(2)\n', (4949, 4952), True, 'import numpy as np\n')] |
import sys
sys.path.append('./PyScr/')
import numpy as np
import matplotlib.pyplot as plt
import cmath
import math
import copy
import pfprint
import primefac
from scipy.special import comb as choose
_ = None
def ppprint(arg):
global _
pfprint.pfprint(arg)
_ = arg
def frac():
pfprint.frac = not pfprint.frac
return _
def denom_lim(n):
pfprint.denom_lim = n
def num_dec(n):
pfprint.num_dec = n
def pltclr():
plt.cla()
plt.clf()
plt.close()
def fact(n):
return math.factorial(n)
def primesS(n):
return primefac.primes_to_string(primefac.primes(n))
def primes(n):
return primefac.primes(n)
sys.displayhook = ppprint
pi = np.pi
e = np.exp(1)
sqrt = np.sqrt
predef_globals = len(globals()) + 1
def loc():
return dict(list(globals().items())[predef_globals:])
| [
"math.factorial",
"matplotlib.pyplot.clf",
"numpy.exp",
"matplotlib.pyplot.close",
"primefac.primes",
"sys.path.append",
"matplotlib.pyplot.cla",
"pfprint.pfprint"
] | [((11, 38), 'sys.path.append', 'sys.path.append', (['"""./PyScr/"""'], {}), "('./PyScr/')\n", (26, 38), False, 'import sys\n'), ((652, 661), 'numpy.exp', 'np.exp', (['(1)'], {}), '(1)\n', (658, 661), True, 'import numpy as np\n'), ((239, 259), 'pfprint.pfprint', 'pfprint.pfprint', (['arg'], {}), '(arg)\n', (254, 259), False, 'import pfprint\n'), ((421, 430), 'matplotlib.pyplot.cla', 'plt.cla', ([], {}), '()\n', (428, 430), True, 'import matplotlib.pyplot as plt\n'), ((432, 441), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (439, 441), True, 'import matplotlib.pyplot as plt\n'), ((443, 454), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (452, 454), True, 'import matplotlib.pyplot as plt\n'), ((477, 494), 'math.factorial', 'math.factorial', (['n'], {}), '(n)\n', (491, 494), False, 'import math\n'), ((590, 608), 'primefac.primes', 'primefac.primes', (['n'], {}), '(n)\n', (605, 608), False, 'import primefac\n'), ((546, 564), 'primefac.primes', 'primefac.primes', (['n'], {}), '(n)\n', (561, 564), False, 'import primefac\n')] |
import tensorflow as tf
import tensorflow.compat.v2 as v2
import tensorflow.neuron as tfn
import shutil
import numpy as np
import unittest
from tensorflow.neuron.python.unittest_base import TestV1Only
class TestEarlyExit(TestV1Only):
def test_sequential(self):
with self.assertRaises(NotImplementedError):
model = v2.keras.models.Sequential([
v2.keras.layers.Flatten(input_shape=(28,28)),
v2.keras.layers.Dense(28, activation='relu'),
v2.keras.layers.Dropout(0.2),
v2.keras.layers.Dense(1)])
model_dir = './keras_flatten_dense_dropout'
test_input = {'input0' :np.random.rand(1, 28, 28)}
tf.saved_model.save(model, model_dir)
compiled_model_dir = model_dir + '_neuron'
shutil.rmtree(compiled_model_dir, ignore_errors=True)
tfn.saved_model.compile(
model_dir, compiled_model_dir,
model_feed_dict=test_input)
def test_functional(self):
with self.assertRaises(NotImplementedError):
num_tags = 12 # Number of unique issue tags
num_words = 10000 # Size of vocabulary obtained when preprocessing text data
num_departments = 4 # Number of departments for predictions
title_input = v2.keras.Input(
shape=(None,), name="title"
) # Variable-length sequence of ints
body_input = v2.keras.Input(shape=(None,), name="body") # Variable-length sequence of ints
tags_input = v2.keras.Input(
shape=(num_tags,), name="tags"
) # Binary vectors of size `num_tags`
# Embed each word in the title into a 64-dimensional vector
title_features = v2.keras.layers.Embedding(num_words, 64)(title_input)
# Embed each word in the text into a 64-dimensional vector
body_features = v2.keras.layers.Embedding(num_words, 64)(body_input)
# Reduce sequence of embedded words in the title into a single 128-dimensional vector
title_features = v2.keras.layers.LSTM(128)(title_features)
# Reduce sequence of embedded words in the body into a single 32-dimensional vector
body_features = v2.keras.layers.LSTM(32)(body_features)
# Merge all available features into a single large vector via concatenation
x = v2.keras.layers.concatenate([title_features, body_features, tags_input])
# Stick a logistic regression for priority prediction on top of the features
priority_pred = v2.keras.layers.Dense(1, name="priority")(x)
# Stick a department classifier on top of the features
department_pred = v2.keras.layers.Dense(num_departments, name="department")(x)
# Instantiate an end-to-end model predicting both priority and department
model = v2.keras.Model(
inputs=[title_input, body_input, tags_input],
outputs=[priority_pred, department_pred],
)
model_dir = './keras_multiple_io'
tf.saved_model.save(model, model_dir)
compiled_model_dir = model_dir + '_neuron'
shutil.rmtree(compiled_model_dir, ignore_errors=True)
# Dummy input data
title_data = np.random.randint(num_words, size=(1280, 10))
body_data = np.random.randint(num_words, size=(1280, 100))
tags_data = np.random.randint(2, size=(1280, num_tags)).astype("float32")
test_input = {'input0' : title_data, 'input1' : body_data, 'input2' : tags_data}
tfn.saved_model.compile(
model_dir, compiled_model_dir,
model_feed_dict=test_input)
| [
"tensorflow.compat.v2.keras.Input",
"tensorflow.compat.v2.keras.layers.Dense",
"numpy.random.rand",
"tensorflow.compat.v2.keras.layers.concatenate",
"tensorflow.saved_model.save",
"tensorflow.compat.v2.keras.Model",
"numpy.random.randint",
"tensorflow.compat.v2.keras.layers.Embedding",
"tensorflow.c... | [((699, 736), 'tensorflow.saved_model.save', 'tf.saved_model.save', (['model', 'model_dir'], {}), '(model, model_dir)\n', (718, 736), True, 'import tensorflow as tf\n'), ((805, 858), 'shutil.rmtree', 'shutil.rmtree', (['compiled_model_dir'], {'ignore_errors': '(True)'}), '(compiled_model_dir, ignore_errors=True)\n', (818, 858), False, 'import shutil\n'), ((872, 959), 'tensorflow.neuron.saved_model.compile', 'tfn.saved_model.compile', (['model_dir', 'compiled_model_dir'], {'model_feed_dict': 'test_input'}), '(model_dir, compiled_model_dir, model_feed_dict=\n test_input)\n', (895, 959), True, 'import tensorflow.neuron as tfn\n'), ((1344, 1387), 'tensorflow.compat.v2.keras.Input', 'v2.keras.Input', ([], {'shape': '(None,)', 'name': '"""title"""'}), "(shape=(None,), name='title')\n", (1358, 1387), True, 'import tensorflow.compat.v2 as v2\n'), ((1479, 1521), 'tensorflow.compat.v2.keras.Input', 'v2.keras.Input', ([], {'shape': '(None,)', 'name': '"""body"""'}), "(shape=(None,), name='body')\n", (1493, 1521), True, 'import tensorflow.compat.v2 as v2\n'), ((1583, 1629), 'tensorflow.compat.v2.keras.Input', 'v2.keras.Input', ([], {'shape': '(num_tags,)', 'name': '"""tags"""'}), "(shape=(num_tags,), name='tags')\n", (1597, 1629), True, 'import tensorflow.compat.v2 as v2\n'), ((2444, 2516), 'tensorflow.compat.v2.keras.layers.concatenate', 'v2.keras.layers.concatenate', (['[title_features, body_features, tags_input]'], {}), '([title_features, body_features, tags_input])\n', (2471, 2516), True, 'import tensorflow.compat.v2 as v2\n'), ((2945, 3052), 'tensorflow.compat.v2.keras.Model', 'v2.keras.Model', ([], {'inputs': '[title_input, body_input, tags_input]', 'outputs': '[priority_pred, department_pred]'}), '(inputs=[title_input, body_input, tags_input], outputs=[\n priority_pred, department_pred])\n', (2959, 3052), True, 'import tensorflow.compat.v2 as v2\n'), ((3167, 3204), 'tensorflow.saved_model.save', 'tf.saved_model.save', (['model', 'model_dir'], {}), '(model, model_dir)\n', (3186, 3204), True, 'import tensorflow as tf\n'), ((3273, 3326), 'shutil.rmtree', 'shutil.rmtree', (['compiled_model_dir'], {'ignore_errors': '(True)'}), '(compiled_model_dir, ignore_errors=True)\n', (3286, 3326), False, 'import shutil\n'), ((3384, 3429), 'numpy.random.randint', 'np.random.randint', (['num_words'], {'size': '(1280, 10)'}), '(num_words, size=(1280, 10))\n', (3401, 3429), True, 'import numpy as np\n'), ((3454, 3500), 'numpy.random.randint', 'np.random.randint', (['num_words'], {'size': '(1280, 100)'}), '(num_words, size=(1280, 100))\n', (3471, 3500), True, 'import numpy as np\n'), ((3694, 3781), 'tensorflow.neuron.saved_model.compile', 'tfn.saved_model.compile', (['model_dir', 'compiled_model_dir'], {'model_feed_dict': 'test_input'}), '(model_dir, compiled_model_dir, model_feed_dict=\n test_input)\n', (3717, 3781), True, 'import tensorflow.neuron as tfn\n'), ((659, 684), 'numpy.random.rand', 'np.random.rand', (['(1)', '(28)', '(28)'], {}), '(1, 28, 28)\n', (673, 684), True, 'import numpy as np\n'), ((1799, 1839), 'tensorflow.compat.v2.keras.layers.Embedding', 'v2.keras.layers.Embedding', (['num_words', '(64)'], {}), '(num_words, 64)\n', (1824, 1839), True, 'import tensorflow.compat.v2 as v2\n'), ((1952, 1992), 'tensorflow.compat.v2.keras.layers.Embedding', 'v2.keras.layers.Embedding', (['num_words', '(64)'], {}), '(num_words, 64)\n', (1977, 1992), True, 'import tensorflow.compat.v2 as v2\n'), ((2133, 2158), 'tensorflow.compat.v2.keras.layers.LSTM', 'v2.keras.layers.LSTM', (['(128)'], {}), '(128)\n', (2153, 2158), True, 'import tensorflow.compat.v2 as v2\n'), ((2299, 2323), 'tensorflow.compat.v2.keras.layers.LSTM', 'v2.keras.layers.LSTM', (['(32)'], {}), '(32)\n', (2319, 2323), True, 'import tensorflow.compat.v2 as v2\n'), ((2635, 2676), 'tensorflow.compat.v2.keras.layers.Dense', 'v2.keras.layers.Dense', (['(1)'], {'name': '"""priority"""'}), "(1, name='priority')\n", (2656, 2676), True, 'import tensorflow.compat.v2 as v2\n'), ((2777, 2834), 'tensorflow.compat.v2.keras.layers.Dense', 'v2.keras.layers.Dense', (['num_departments'], {'name': '"""department"""'}), "(num_departments, name='department')\n", (2798, 2834), True, 'import tensorflow.compat.v2 as v2\n'), ((381, 426), 'tensorflow.compat.v2.keras.layers.Flatten', 'v2.keras.layers.Flatten', ([], {'input_shape': '(28, 28)'}), '(input_shape=(28, 28))\n', (404, 426), True, 'import tensorflow.compat.v2 as v2\n'), ((439, 483), 'tensorflow.compat.v2.keras.layers.Dense', 'v2.keras.layers.Dense', (['(28)'], {'activation': '"""relu"""'}), "(28, activation='relu')\n", (460, 483), True, 'import tensorflow.compat.v2 as v2\n'), ((497, 525), 'tensorflow.compat.v2.keras.layers.Dropout', 'v2.keras.layers.Dropout', (['(0.2)'], {}), '(0.2)\n', (520, 525), True, 'import tensorflow.compat.v2 as v2\n'), ((539, 563), 'tensorflow.compat.v2.keras.layers.Dense', 'v2.keras.layers.Dense', (['(1)'], {}), '(1)\n', (560, 563), True, 'import tensorflow.compat.v2 as v2\n'), ((3525, 3568), 'numpy.random.randint', 'np.random.randint', (['(2)'], {'size': '(1280, num_tags)'}), '(2, size=(1280, num_tags))\n', (3542, 3568), True, 'import numpy as np\n')] |
import itertools
import random
import numpy as np
class Sudoku:
"""Class for creating and solving Sudoku puzzles"""
def _get_square(self, row, col):
"""
Returns coordinates for the square where the row,col coordinate is
"""
top = int(row / 3) * 3 # (0 or 1 or 2) * 3
left = int(col / 3) * 3 # (0 or 1 or 2) * 3
return {
'top': top,
'left': left,
'bottom': top + 3, # slicing high bound is exclusive
'right': left + 3}
def _flip_sqrs_and_rows(self):
"""
Moves squares to rows and rows to squares.
Running twice returns original state.
[:,0,0:3]->[:,0,0:3], [:,1,0:3]->[:,0,3:6], [:,2,0:3]->[:,0,6:9],
[:,0,3:6]->[:,1,0:3], [:,1,3:6]->[:,1,3:6], [:,2,3:6]->[:,1,6:9],
...
[:,6,6:9]->[:,8,0:3], [:,7,6:9]->[:,8,3:6], [:,8,6:9]->[:,8,6:9]
"""
flipped = np.copy(self.positions)
for i, j in np.ndindex(3, 9):
flipped[:, int(j/3)+i*3, (j % 3)*3:(j % 3)*3+3] = \
self.positions[:, (j % 3)+i*3, int(j/3)*3:int(j/3)*3+3]
self.positions = flipped
def _search_locked(self, sqr, possibilities):
"""
Searches locked positions
Searches for squares where all possible positions for a number
are on a same row or col. Positions outside the square on the same
row / col can be eliminated.
"""
top = int(sqr / 3) * 3 # row of top left corner of sqr
left = sqr % 3 * 3 # col of top left corner of sqr
# numbers that have 2 or 3 possible positions in a square
numbers = [i for i in range(9) if 2 <= possibilities[i] <= 3]
for n in numbers:
coords = np.where(self.positions[n, top:top+3, left:left+3])
# put row coords to left column and col coords to right
coords = np.transpose(coords)
# check if all row or col coords are the same
# (all values in the coords columns are the same
# as the value on the first row)
row, col = np.all(coords == coords[0, :], axis=0)
if row:
# eliminate positions on the same row outside of sqr
outside_of_sqr = [i for i in range(9)
if i not in range(left, left + 3)]
self.positions[n, top + coords[0, 0], outside_of_sqr] = False
elif col:
# eliminate positions on the same col outside of sqr
outside_of_sqr = [i for i in range(9)
if i not in range(top, top + 3)]
self.positions[n, outside_of_sqr, left + coords[0, 1]] = False
def _search_hidden_and_naked(self, row, col):
"""
Searches for naked/hidden pairs/triples/quads
Hidden:
If the number of possible positions for a number matches with another
number (on the same row/col/sqr) with the same possible positions and
there are e.g. only three possible positions for the three numbers, a
hidden triple has been found. It is important to note that not all
three numbers must be in all three positions, but there must not be
more than three positions for the three numbers all together.
Naked:
If the number of possible numbers in a position matches with another
position (on the same row/col/sqr) with the same possible numbers, and
there are e.g. only three possible numbers and three positions, a
naked triple has been found. It is important to note that not all
three positions must contain all three numbers, but there must not be
more than three numbers in the three positions all together.
Pair and quads are searched the same way, but there must be two
or four allowed positions/numbers for the same numbers/positions.
After finding a pair/triple/quad, other numbers in the same
position / positions for the same numbers, can be set False.
Finally transposes numbers and rows/cols each time to search for
hidden/naked alternately.
"""
# how many possible positions/numbers for the given number/position
possibilities = np.sum(self.positions[:, row, col], axis=1)
# only search up to quads
numbers = np.array([i for i in range(9) if 2 <= possibilities[i] <= 4])
for n in numbers:
equal = np.all( # find equal (or subset) rows/cols/sqrs
np.logical_xor( # check for change after masking
self.positions[numbers, row, col],
self.positions[n, row, col] *
self.positions[numbers, row, col]
) == 0,
axis=1)
if np.sum(equal) == possibilities[n]: # pair/triple/quad found
self.positions[
[i for i in range(9) if i not in numbers[equal]],
row, col] *= np.invert(self.positions[n, row, col])
# search for hidden/naked by transposing numbers and cols/rows
if isinstance(row, int): # rows -> transpose numbers and cols
self.positions = np.transpose(self.positions, (2, 1, 0))
else: # cols -> transpose numbers and rows
self.positions = np.transpose(self.positions, (1, 0, 2))
def _set_number(self, number, row, col):
"""
Sets number at row,col position
Sets positions False for the given number on the same row, col and
square, and for all other numbers with the same row,col coordinate
(e.g. if 2,3 is 4 then 5 can't be at 2,3).
Number must be given in 1-9
"""
if number == 0:
return False
self.puzzle[row, col] = number
number -= 1 # from sudoku board numbers (1-9) to 0-based index
sqr = self._get_square(row, col)
# eliminate positions on same axes and square
self.positions[number, row, :] = False
self.positions[number, :, col] = False
self.positions[number, sqr['top']:sqr['bottom'],
sqr['left']:sqr['right']] = False
self.positions[:, row, col] = False
self.positions[number, row, col] = True
# eliminate naked/hidden/locked pairs/triples/quads
for x in range(9): # row / col / sqr
self._search_hidden_and_naked(x, slice(9)) # rows (hidden)
self._search_hidden_and_naked(x, slice(9)) # rows (naked)
self._search_hidden_and_naked(slice(9), x) # cols (hidden)
self._search_hidden_and_naked(slice(9), x) # cols (naked)
self._flip_sqrs_and_rows()
self._search_hidden_and_naked(x, slice(9)) # sqrs (hidden)
self._search_hidden_and_naked(x, slice(9)) # sqrs (naked)
# possible positions available for each number in a square
possibilities = np.sum(self.positions[:, x, :], axis=1)
self._flip_sqrs_and_rows()
self._search_locked(x, possibilities) # sqrs (locked)
return True
def _init_positions(self):
"""Sets positions for puzzle cells"""
self.positions = np.full((9, 9, 9), True)
non_zero_coords = zip(*np.where(self.puzzle != 0))
for row, col in non_zero_coords:
self._set_number(self.puzzle[row, col], row, col)
def _get_number(self, row, col):
"""
Gets number at row,col position
Checks positions, if row,col has a True value and that it's the only
True value on the same row / col / square. Also checks, if only one
number is possible based on the board.
Returns a number 1-9 or 0 (=empty)
"""
sqr = self._get_square(row, col)
for number in range(9):
if self.positions[number, row, col] and \
(np.sum(self.positions[:, row, col]) == 1 or
np.sum(self.positions[number, row, :]) == 1 or
np.sum(self.positions[number, :, col]) == 1 or
np.sum(self.positions[number, sqr['top']:sqr['bottom'],
sqr['left']:sqr['right']]) == 1):
return number + 1 # from 0-index to board numbers (1-9)
return 0
def _solve(self):
"""
Iterates Sudoku board until all positions are solved or no more
numbers are solvable
"""
numbers_solved = np.count_nonzero(self.puzzle)
zero_coords = zip(*np.where(self.puzzle == 0))
for row, col in zero_coords:
# get number by deducing it from other numbers and then set it
self._set_number(self._get_number(row, col), row, col)
if numbers_solved < np.count_nonzero(self.puzzle) < 9 * 9:
self._solve()
def solve(self, puzzle, solve=True):
"""Solves the given Sudoku puzzle"""
self.puzzle = np.copy(puzzle) # preserve puzzle given in arguments
self._init_positions()
if solve:
self._solve()
return self.puzzle
def get_random_number(self, puzzle, row, col):
"""
Gives "Random" number for the given row / col position
Returns:
1. the correct number (if only one)
2. one of the possibilities (if many)
3. 0 if no possible numbers
"""
number = self._get_number(row, col) # 1-9 or 0
if not number:
possible_numbers = np.where(self.positions[:, row, col])[0]
if possible_numbers.size == 0: # impossible position
return 0
number = np.random.choice(possible_numbers) + 1 # 0-8 -> 1-9
return number
def create_puzzle(self):
"""Creates a new sudoku puzzle"""
while True:
self.puzzle = np.zeros((9, 9), int)
self.positions = np.full((9, 9, 9), True)
non_deduced_values = []
# create list of board coordinates
coords = list(itertools.product(range(9), range(9)))
while coords:
# pop random coordinate
row, col = coords.pop(np.random.randint(len(coords)))
# put random number from possible numbers to the coordinate
possible_numbers = np.where(self.positions[:, row, col])[0]
if possible_numbers.size == 0: # impossible position -> retry
break
number = np.random.choice(possible_numbers)
self._set_number(number+1, row, col)
non_deduced_values.append((row, col))
# start solving after setting 8 numbers
if len(coords) <= 81 - 8:
self._solve()
# update coordinates with non-solved positions
coords = list(zip(*np.where(self.puzzle == 0)))
# try again if puzzle became unsolvable
if np.count_nonzero(self.puzzle) == 9 * 9:
break
# remove deduced values from puzzle
deduced = self.puzzle.copy()
deduced[tuple(zip(*non_deduced_values))] = 0
self.puzzle -= deduced
return self.puzzle
| [
"numpy.copy",
"numpy.where",
"numpy.random.choice",
"numpy.ndindex",
"numpy.logical_xor",
"numpy.invert",
"numpy.count_nonzero",
"numpy.sum",
"numpy.zeros",
"numpy.full",
"numpy.all",
"numpy.transpose"
] | [((939, 962), 'numpy.copy', 'np.copy', (['self.positions'], {}), '(self.positions)\n', (946, 962), True, 'import numpy as np\n'), ((983, 999), 'numpy.ndindex', 'np.ndindex', (['(3)', '(9)'], {}), '(3, 9)\n', (993, 999), True, 'import numpy as np\n'), ((4305, 4348), 'numpy.sum', 'np.sum', (['self.positions[:, row, col]'], {'axis': '(1)'}), '(self.positions[:, row, col], axis=1)\n', (4311, 4348), True, 'import numpy as np\n'), ((7265, 7289), 'numpy.full', 'np.full', (['(9, 9, 9)', '(True)'], {}), '((9, 9, 9), True)\n', (7272, 7289), True, 'import numpy as np\n'), ((8524, 8553), 'numpy.count_nonzero', 'np.count_nonzero', (['self.puzzle'], {}), '(self.puzzle)\n', (8540, 8553), True, 'import numpy as np\n'), ((8990, 9005), 'numpy.copy', 'np.copy', (['puzzle'], {}), '(puzzle)\n', (8997, 9005), True, 'import numpy as np\n'), ((1775, 1830), 'numpy.where', 'np.where', (['self.positions[n, top:top + 3, left:left + 3]'], {}), '(self.positions[n, top:top + 3, left:left + 3])\n', (1783, 1830), True, 'import numpy as np\n'), ((1916, 1936), 'numpy.transpose', 'np.transpose', (['coords'], {}), '(coords)\n', (1928, 1936), True, 'import numpy as np\n'), ((2124, 2162), 'numpy.all', 'np.all', (['(coords == coords[0, :])'], {'axis': '(0)'}), '(coords == coords[0, :], axis=0)\n', (2130, 2162), True, 'import numpy as np\n'), ((5253, 5292), 'numpy.transpose', 'np.transpose', (['self.positions', '(2, 1, 0)'], {}), '(self.positions, (2, 1, 0))\n', (5265, 5292), True, 'import numpy as np\n'), ((5374, 5413), 'numpy.transpose', 'np.transpose', (['self.positions', '(1, 0, 2)'], {}), '(self.positions, (1, 0, 2))\n', (5386, 5413), True, 'import numpy as np\n'), ((6995, 7034), 'numpy.sum', 'np.sum', (['self.positions[:, x, :]'], {'axis': '(1)'}), '(self.positions[:, x, :], axis=1)\n', (7001, 7034), True, 'import numpy as np\n'), ((8816, 8845), 'numpy.count_nonzero', 'np.count_nonzero', (['self.puzzle'], {}), '(self.puzzle)\n', (8832, 8845), True, 'import numpy as np\n'), ((9896, 9917), 'numpy.zeros', 'np.zeros', (['(9, 9)', 'int'], {}), '((9, 9), int)\n', (9904, 9917), True, 'import numpy as np\n'), ((9947, 9971), 'numpy.full', 'np.full', (['(9, 9, 9)', '(True)'], {}), '((9, 9, 9), True)\n', (9954, 9971), True, 'import numpy as np\n'), ((4846, 4859), 'numpy.sum', 'np.sum', (['equal'], {}), '(equal)\n', (4852, 4859), True, 'import numpy as np\n'), ((5042, 5080), 'numpy.invert', 'np.invert', (['self.positions[n, row, col]'], {}), '(self.positions[n, row, col])\n', (5051, 5080), True, 'import numpy as np\n'), ((7321, 7347), 'numpy.where', 'np.where', (['(self.puzzle != 0)'], {}), '(self.puzzle != 0)\n', (7329, 7347), True, 'import numpy as np\n'), ((8581, 8607), 'numpy.where', 'np.where', (['(self.puzzle == 0)'], {}), '(self.puzzle == 0)\n', (8589, 8607), True, 'import numpy as np\n'), ((9550, 9587), 'numpy.where', 'np.where', (['self.positions[:, row, col]'], {}), '(self.positions[:, row, col])\n', (9558, 9587), True, 'import numpy as np\n'), ((9703, 9737), 'numpy.random.choice', 'np.random.choice', (['possible_numbers'], {}), '(possible_numbers)\n', (9719, 9737), True, 'import numpy as np\n'), ((10538, 10572), 'numpy.random.choice', 'np.random.choice', (['possible_numbers'], {}), '(possible_numbers)\n', (10554, 10572), True, 'import numpy as np\n'), ((11014, 11043), 'numpy.count_nonzero', 'np.count_nonzero', (['self.puzzle'], {}), '(self.puzzle)\n', (11030, 11043), True, 'import numpy as np\n'), ((4574, 4692), 'numpy.logical_xor', 'np.logical_xor', (['self.positions[numbers, row, col]', '(self.positions[n, row, col] * self.positions[numbers, row, col])'], {}), '(self.positions[numbers, row, col], self.positions[n, row,\n col] * self.positions[numbers, row, col])\n', (4588, 4692), True, 'import numpy as np\n'), ((10367, 10404), 'numpy.where', 'np.where', (['self.positions[:, row, col]'], {}), '(self.positions[:, row, col])\n', (10375, 10404), True, 'import numpy as np\n'), ((7943, 7978), 'numpy.sum', 'np.sum', (['self.positions[:, row, col]'], {}), '(self.positions[:, row, col])\n', (7949, 7978), True, 'import numpy as np\n'), ((8004, 8042), 'numpy.sum', 'np.sum', (['self.positions[number, row, :]'], {}), '(self.positions[number, row, :])\n', (8010, 8042), True, 'import numpy as np\n'), ((8068, 8106), 'numpy.sum', 'np.sum', (['self.positions[number, :, col]'], {}), '(self.positions[number, :, col])\n', (8074, 8106), True, 'import numpy as np\n'), ((8132, 8219), 'numpy.sum', 'np.sum', (["self.positions[number, sqr['top']:sqr['bottom'], sqr['left']:sqr['right']]"], {}), "(self.positions[number, sqr['top']:sqr['bottom'], sqr['left']:sqr[\n 'right']])\n", (8138, 8219), True, 'import numpy as np\n'), ((10918, 10944), 'numpy.where', 'np.where', (['(self.puzzle == 0)'], {}), '(self.puzzle == 0)\n', (10926, 10944), True, 'import numpy as np\n')] |
from unittest import TestCase, skipIf
from ...examples import get_path
from ..alpha_shapes import alpha_shape, alpha_shape_auto
import numpy as np
import os
try:
import geopandas
from shapely import geometry
GEOPANDAS_EXTINCT = False
except ImportError:
GEOPANDAS_EXTINCT = True
this_directory = os.path.dirname(__file__)
@skipIf(GEOPANDAS_EXTINCT, "Geopandas is missing, so test will not run.")
class Test_Alpha_Shapes(TestCase):
def setUp(self):
eberly = geopandas.read_file(get_path("eberly_net.shp"))
eberly_vertices = eberly.geometry.apply(
lambda x: np.hstack(x.xy).reshape(2, 2).T
).values
eberly_vertices = np.vstack(eberly_vertices)
self.vertices = eberly_vertices
self.a05 = (
geopandas.read_file(os.path.join(this_directory, "data/alpha_05.gpkg"))
.geometry.to_numpy()
.item()
)
self.a10 = (
geopandas.read_file(os.path.join(this_directory, "data/alpha_tenth.gpkg"))
.geometry.to_numpy()
.item()
)
self.a2 = (
geopandas.read_file(os.path.join(this_directory, "data/alpha_fifth.gpkg"))
.geometry.to_numpy()
.item()
)
self.a25 = (
geopandas.read_file(os.path.join(this_directory, "data/alpha_fourth.gpkg"))
.geometry.to_numpy()
.item()
)
self.a25 = (
geopandas.read_file(os.path.join(this_directory, "data/alpha_fourth.gpkg"))
.geometry.to_numpy()
.item()
)
circles = geopandas.read_file(
os.path.join(this_directory, "data/eberly_bounding_circles.gpkg")
)
self.circle_radii = circles.radius.iloc[0]
self.circle_verts = np.column_stack(
(circles.geometry.x.values, circles.geometry.y.values)
)
self.autoalpha = geopandas.read_file(
os.path.join(this_directory, "data/alpha_auto.gpkg")
).geometry[0]
def test_alpha_shapes(self):
new_a05 = alpha_shape(self.vertices, 0.05).to_numpy().item()
new_a10 = alpha_shape(self.vertices, 0.10).to_numpy().item()
new_a2 = alpha_shape(self.vertices, 0.2).to_numpy().item()
new_a25 = alpha_shape(self.vertices, 0.25).to_numpy().item()
assert new_a05.equals(self.a05)
assert new_a10.equals(self.a10)
assert new_a2.equals(self.a2)
assert new_a25.equals(self.a25)
def test_auto(self):
auto_alpha = alpha_shape_auto(self.vertices, 5)
assert self.autoalpha.equals(auto_alpha)
def test_small_n(self):
new_singleton = alpha_shape(self.vertices[0].reshape(1, -1), 0.5)
assert isinstance(new_singleton, geometry.Polygon)
new_duo = alpha_shape(self.vertices[:1], 0.5)
assert isinstance(new_duo, geometry.Polygon)
new_triple = alpha_shape(self.vertices[:2], 0.5)
assert isinstance(new_triple, geometry.Polygon)
new_triple = alpha_shape_auto(
self.vertices[0].reshape(1, -1), return_circles=True
)
assert isinstance(new_triple[0], geometry.Polygon)
new_triple = alpha_shape_auto(self.vertices[:1], return_circles=True)
assert isinstance(new_triple[0], geometry.Polygon)
new_triple = alpha_shape_auto(self.vertices[:2], return_circles=True)
assert isinstance(new_triple[0], geometry.Polygon)
def test_circles(self):
ashape, radius, centers = alpha_shape_auto(self.vertices, return_circles=True)
np.testing.assert_allclose(radius, self.circle_radii)
np.testing.assert_allclose(centers, self.circle_verts)
| [
"numpy.hstack",
"numpy.testing.assert_allclose",
"unittest.skipIf",
"os.path.join",
"numpy.column_stack",
"os.path.dirname",
"numpy.vstack"
] | [((315, 340), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (330, 340), False, 'import os\n'), ((344, 416), 'unittest.skipIf', 'skipIf', (['GEOPANDAS_EXTINCT', '"""Geopandas is missing, so test will not run."""'], {}), "(GEOPANDAS_EXTINCT, 'Geopandas is missing, so test will not run.')\n", (350, 416), False, 'from unittest import TestCase, skipIf\n'), ((684, 710), 'numpy.vstack', 'np.vstack', (['eberly_vertices'], {}), '(eberly_vertices)\n', (693, 710), True, 'import numpy as np\n'), ((1811, 1882), 'numpy.column_stack', 'np.column_stack', (['(circles.geometry.x.values, circles.geometry.y.values)'], {}), '((circles.geometry.x.values, circles.geometry.y.values))\n', (1826, 1882), True, 'import numpy as np\n'), ((3591, 3644), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['radius', 'self.circle_radii'], {}), '(radius, self.circle_radii)\n', (3617, 3644), True, 'import numpy as np\n'), ((3653, 3707), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['centers', 'self.circle_verts'], {}), '(centers, self.circle_verts)\n', (3679, 3707), True, 'import numpy as np\n'), ((1656, 1721), 'os.path.join', 'os.path.join', (['this_directory', '"""data/eberly_bounding_circles.gpkg"""'], {}), "(this_directory, 'data/eberly_bounding_circles.gpkg')\n", (1668, 1721), False, 'import os\n'), ((1964, 2016), 'os.path.join', 'os.path.join', (['this_directory', '"""data/alpha_auto.gpkg"""'], {}), "(this_directory, 'data/alpha_auto.gpkg')\n", (1976, 2016), False, 'import os\n'), ((609, 624), 'numpy.hstack', 'np.hstack', (['x.xy'], {}), '(x.xy)\n', (618, 624), True, 'import numpy as np\n'), ((805, 855), 'os.path.join', 'os.path.join', (['this_directory', '"""data/alpha_05.gpkg"""'], {}), "(this_directory, 'data/alpha_05.gpkg')\n", (817, 855), False, 'import os\n'), ((973, 1026), 'os.path.join', 'os.path.join', (['this_directory', '"""data/alpha_tenth.gpkg"""'], {}), "(this_directory, 'data/alpha_tenth.gpkg')\n", (985, 1026), False, 'import os\n'), ((1143, 1196), 'os.path.join', 'os.path.join', (['this_directory', '"""data/alpha_fifth.gpkg"""'], {}), "(this_directory, 'data/alpha_fifth.gpkg')\n", (1155, 1196), False, 'import os\n'), ((1314, 1368), 'os.path.join', 'os.path.join', (['this_directory', '"""data/alpha_fourth.gpkg"""'], {}), "(this_directory, 'data/alpha_fourth.gpkg')\n", (1326, 1368), False, 'import os\n'), ((1486, 1540), 'os.path.join', 'os.path.join', (['this_directory', '"""data/alpha_fourth.gpkg"""'], {}), "(this_directory, 'data/alpha_fourth.gpkg')\n", (1498, 1540), False, 'import os\n')] |
import cv2
import math
import torch
import torchvision
import numpy as np
from copy import deepcopy
class AffineTransform(object):
def __init__(self, input_res=256, output_res=64, rotation_prob=0.6):
self.input_res = input_res
self.output_res = output_res
self.rotation_prob = rotation_prob
def get_translation_matrix(self, pt):
"Translate the points to the given point pt"
T = np.float32([
[1, 0, pt[0]],
[0, 1, pt[1]],
[0, 0, 1]
])
return T
def get_rotation_matrix(self, rot_angle):
"Rotate the points with rot_angle around the center"
rot_rad = - rot_angle * np.pi / 180
sn, cs = np.sin(rot_rad), np.cos(rot_rad)
T = np.float32([
[cs, -sn, 0],
[sn, cs, 0],
[0 , 0, 1]
])
return T
def get_scale_matrix(self, scale_x, scale_y):
"Scale the points along x & y directions with scale_x & scale_y"
T = np.float32([
[scale_x, 0 , 0],
[0 , scale_y, 0],
[0 , 0 , 1]
])
return T
def get_affine_matrix(self, center, scale, res, rot_angle):
# First translate all the image points to the center of the image
# We want to scale the image from the center portion
T1 = self.get_translation_matrix(-center)
# Scale the image along x & y with values scale_x & scale_y
# Numpy arrays and image axes are flipped
scale_x, scale_y = res[1] / scale, res[0] / scale
T2 = self.get_scale_matrix(scale_x, scale_y)
# Rotate the image around the center with angle rot_angle
T3 = self.get_rotation_matrix(rot_angle)
# Translate the image points to the new origin point
# Numpy arrays and image axes are flipped
T4 = self.get_translation_matrix([res[1] / 2, res[0] / 2])
T_final = np.dot(T4, np.dot(T3, np.dot(T2, T1)))
return T_final
def get_random_range(self, xmin, xmax):
return np.random.random() * (xmax - xmin) + xmin
def get_keypoints(self, keypoints, T_keypoints):
new_keypoints = np.c_[keypoints, np.ones(len(keypoints))]
return np.dot(new_keypoints, T_keypoints.T).reshape(keypoints.shape)
def update_visible_keypoints(self, res, keypoints, visible_keypoints):
for i, point in enumerate(keypoints):
# Axes of image and keypoints are interchanged
x, y = np.round(point[0]), np.round(point[1])
if x < 0 or x >= res[1] or y < 0 or y >= res[0]:
visible_keypoints[i] = 0
return visible_keypoints
def __call__(self, sample):
img = deepcopy(sample.get("image"))
keypoints = deepcopy(sample.get("keypoints"))
visible_keypoints = deepcopy(sample.get("visible_keypoints"))
scale = deepcopy(sample.get("scale"))
center = deepcopy(sample.get("center"))
# Scale and rotate by a random value in given range
scale = scale * self.get_random_range(xmin=0.75, xmax=1.25)
rot_angle = 0
if np.random.uniform() >= self.rotation_prob:
rot_angle = self.get_random_range(xmin=-30, xmax=30)
# Get affine transforms for image and keypoints respectively
T_img = self.get_affine_matrix(center, scale, (self.input_res, self.input_res), rot_angle)[:2]
T_keypoints = self.get_affine_matrix(center, scale, (self.output_res, self.output_res), rot_angle)[:2]
new_img = cv2.warpAffine(img, T_img, (self.input_res, self.input_res))
new_keypoints = self.get_keypoints(keypoints, T_keypoints)
new_visible_keypoints = self.update_visible_keypoints((self.output_res, self.output_res), new_keypoints, visible_keypoints)
updated_sample = {
"image": new_img,
"keypoints": new_keypoints,
"visible_keypoints": new_visible_keypoints,
"scale": scale,
"center": center
}
return updated_sample | [
"cv2.warpAffine",
"numpy.random.random",
"numpy.dot",
"numpy.cos",
"numpy.random.uniform",
"numpy.sin",
"numpy.float32",
"numpy.round"
] | [((430, 483), 'numpy.float32', 'np.float32', (['[[1, 0, pt[0]], [0, 1, pt[1]], [0, 0, 1]]'], {}), '([[1, 0, pt[0]], [0, 1, pt[1]], [0, 0, 1]])\n', (440, 483), True, 'import numpy as np\n'), ((761, 811), 'numpy.float32', 'np.float32', (['[[cs, -sn, 0], [sn, cs, 0], [0, 0, 1]]'], {}), '([[cs, -sn, 0], [sn, cs, 0], [0, 0, 1]])\n', (771, 811), True, 'import numpy as np\n'), ((1015, 1072), 'numpy.float32', 'np.float32', (['[[scale_x, 0, 0], [0, scale_y, 0], [0, 0, 1]]'], {}), '([[scale_x, 0, 0], [0, scale_y, 0], [0, 0, 1]])\n', (1025, 1072), True, 'import numpy as np\n'), ((3556, 3616), 'cv2.warpAffine', 'cv2.warpAffine', (['img', 'T_img', '(self.input_res, self.input_res)'], {}), '(img, T_img, (self.input_res, self.input_res))\n', (3570, 3616), False, 'import cv2\n'), ((716, 731), 'numpy.sin', 'np.sin', (['rot_rad'], {}), '(rot_rad)\n', (722, 731), True, 'import numpy as np\n'), ((733, 748), 'numpy.cos', 'np.cos', (['rot_rad'], {}), '(rot_rad)\n', (739, 748), True, 'import numpy as np\n'), ((3145, 3164), 'numpy.random.uniform', 'np.random.uniform', ([], {}), '()\n', (3162, 3164), True, 'import numpy as np\n'), ((1975, 1989), 'numpy.dot', 'np.dot', (['T2', 'T1'], {}), '(T2, T1)\n', (1981, 1989), True, 'import numpy as np\n'), ((2075, 2093), 'numpy.random.random', 'np.random.random', ([], {}), '()\n', (2091, 2093), True, 'import numpy as np\n'), ((2252, 2288), 'numpy.dot', 'np.dot', (['new_keypoints', 'T_keypoints.T'], {}), '(new_keypoints, T_keypoints.T)\n', (2258, 2288), True, 'import numpy as np\n'), ((2514, 2532), 'numpy.round', 'np.round', (['point[0]'], {}), '(point[0])\n', (2522, 2532), True, 'import numpy as np\n'), ((2534, 2552), 'numpy.round', 'np.round', (['point[1]'], {}), '(point[1])\n', (2542, 2552), True, 'import numpy as np\n')] |
"""[summary]
Returns:
[type]: [description]
"""
import pickle
import sys
import numpy as np
def gen_label(x):
"""[summary]
Args:
x ([type]): [description]
Returns:
[type]: [description]
"""
if 1 <= x <= 10:
return 2
if 11 <= x <= 100:
return 1
return 0
def load_only(src_path):
"""[summary]
Args:
src_path ([type]): [description]
Returns:
[type]: [description]
"""
f = open(src_path)
line = f.readline()
ext_label_id_features = []
real_label_id_features = []
cnt = 0
while line:
cnt += 1
if cnt % 10000 == 0:
print(cnt)
pure_line, comm = line.split('#') # 去除行尾注释
pure_line = pure_line.strip()
comm = comm.strip()
relevance_id_features = pure_line.split(' ')
label_id_feature = [
gen_label(int(relevance_id_features[0])) \
if comm in ("rel", "non") \
else int(relevance_id_features[0])
]
for i in range(1, len(relevance_id_features)):
label_id_feature.append(float(relevance_id_features[i].split(':')[1]))
if comm in ("non", "rel"):
real_label_id_features.append(label_id_feature)
else:
ext_label_id_features.append(label_id_feature)
line = f.readline()
f.close()
return real_label_id_features, ext_label_id_features
def main():
"""[summary]
"""
try:
fed_no = int(sys.argv[1])
except ValueError:
fed_no = 0
print(fed_no)
real_label_id_features, ext_label_id_features = load_only(
"/data/icde_data/fed_with_sh_(5_30_200)ext%d.txt" % fed_no)
pickle.dump([np.array(real_label_id_features), np.array(ext_label_id_features)], open(
"/data/icde_data/fed_with_sh_(5_30_200)ext%d.pkl" % fed_no, "wb"))
if __name__ == "__main__":
main()
| [
"numpy.array"
] | [((1723, 1755), 'numpy.array', 'np.array', (['real_label_id_features'], {}), '(real_label_id_features)\n', (1731, 1755), True, 'import numpy as np\n'), ((1757, 1788), 'numpy.array', 'np.array', (['ext_label_id_features'], {}), '(ext_label_id_features)\n', (1765, 1788), True, 'import numpy as np\n')] |
# MIT License
#
# 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.
import pandas as pd
import numpy as np
from torch.utils.data import Dataset
import utility as ut
import os
import torch
from glob import glob
from tqdm import tqdm
class EmoMatchDataset(Dataset):
"""EmoMatch dataset using VoxCeleb v2"""
def __init__(self, directory, map_correct=True, n_video_samples=16, image_transform=None, stft_transform=None, size=None, number_of_videos=10000):
self._directory = directory
self._map_correct = map_correct
self._n_video_samples = n_video_samples
self._image_transform = image_transform
self._stft_transform = stft_transform
if size > 0:
_h5_video_names = sorted(list(glob(os.path.join(directory, 'h5/**/*'))))[:size]
_wav_video_names = sorted(list(glob(os.path.join(directory, 'wav/**/*'))))[:size]
else:
_h5_video_names = sorted(list(glob(os.path.join(directory, 'h5/**/*'))))[:number_of_videos][size:]
_wav_video_names = sorted(list(glob(os.path.join(directory, 'wav/**/*'))))[:number_of_videos][size:]
self._utterance_names = dict()
for name in tqdm(_h5_video_names):
if name.replace('/h5/', '/wav/') in _wav_video_names:
self._utterance_names[name] = [os.path.splitext(os.path.splitext(os.sep.join(os.path.normpath(x).split(os.sep)[-3:]))[0])[0] for x in list(glob(os.path.join(name, '*.mp4.h5')))]
self._video_names = sorted(list(self._utterance_names.keys()))
self._cumsum = np.cumsum([len(self._utterance_names[x]) for x in self._video_names])
def __len__(self):
return self._cumsum[-1]
@staticmethod
def _next_smallest(value, array):
nearest = np.argmax(array > value)
return nearest, value - array[nearest]
@property
def map_correct(self):
return self._map_correct
@map_correct.setter
def map_correct(self, value):
self._map_correct = value
def __getitem__(self, video_idx):
try:
audio_idx = video_idx
if not self._map_correct:
while EmoMatchDataset._next_smallest(audio_idx, self._cumsum)[0] == EmoMatchDataset._next_smallest(video_idx, self._cumsum)[0]:
audio_idx = np.random.randint(self.__len__())
video_id, video_utterance_id = EmoMatchDataset._next_smallest(video_idx, self._cumsum)
audio_id, audio_utterance_id = EmoMatchDataset._next_smallest(audio_idx, self._cumsum)
mp4_video_name = self._video_names[video_id]
wav_video_name = self._video_names[audio_id]
video_utterance_name = self._utterance_names[mp4_video_name][video_utterance_id] + '.mp4' + '.h5'
audio_utterance_name = self._utterance_names[wav_video_name][audio_utterance_id] + '.wav'
# create audio sample
try:
wav_data = ut.load_audio_sample(os.path.join(self._directory, 'wav', audio_utterance_name))
wav_data = ut.create_audio_sample(wav_data)
except:
print('Error in:', os.path.join(self._directory, 'wav', audio_utterance_name))
return None
audio_stft = ut.extract_spectrum(wav_data)
audio_stft = np.abs(audio_stft)
audio_stft = np.log(audio_stft + 1e-10)
if self._stft_transform:
audio_stft = self._stft_transform(audio_stft)
audio_stft = audio_stft.reshape((1, *audio_stft.shape))
try:
video_features = ut.create_video_sample_hdf5(os.path.join(self._directory, 'h5', video_utterance_name), self._n_video_samples)
except Exception as ex:
import traceback
print('Error in:', os.path.join(self._directory, 'h5', video_utterance_name), ex)
traceback.print_exc()
return None
try:
if self._image_transform:
video_features = self._image_transform(video_features)
except Exception as ex:
import traceback
print('Error in processing:', os.path.join(self._directory, 'mp4', video_utterance_name), ex)
traceback.print_exc()
return None
audio_stft = torch.from_numpy(audio_stft.astype(dtype=np.float32))
video_features = torch.from_numpy(video_features.astype(dtype=np.float32))
video_features = video_features.permute(0, 3, 1, 2)
targets = torch.zeros((1,), dtype=torch.long)
targets[0] = int(self._map_correct)
return ((audio_stft, video_features), targets)
except Exception as ex:
import traceback
print('Error __getitem__:', ex)
traceback.print_exc()
return None
| [
"numpy.abs",
"numpy.log",
"tqdm.tqdm",
"numpy.argmax",
"utility.extract_spectrum",
"os.path.join",
"os.path.normpath",
"traceback.print_exc",
"utility.create_audio_sample",
"torch.zeros"
] | [((2225, 2246), 'tqdm.tqdm', 'tqdm', (['_h5_video_names'], {}), '(_h5_video_names)\n', (2229, 2246), False, 'from tqdm import tqdm\n'), ((2805, 2829), 'numpy.argmax', 'np.argmax', (['(array > value)'], {}), '(array > value)\n', (2814, 2829), True, 'import numpy as np\n'), ((4295, 4324), 'utility.extract_spectrum', 'ut.extract_spectrum', (['wav_data'], {}), '(wav_data)\n', (4314, 4324), True, 'import utility as ut\n'), ((4350, 4368), 'numpy.abs', 'np.abs', (['audio_stft'], {}), '(audio_stft)\n', (4356, 4368), True, 'import numpy as np\n'), ((4394, 4420), 'numpy.log', 'np.log', (['(audio_stft + 1e-10)'], {}), '(audio_stft + 1e-10)\n', (4400, 4420), True, 'import numpy as np\n'), ((5618, 5653), 'torch.zeros', 'torch.zeros', (['(1,)'], {'dtype': 'torch.long'}), '((1,), dtype=torch.long)\n', (5629, 5653), False, 'import torch\n'), ((4093, 4125), 'utility.create_audio_sample', 'ut.create_audio_sample', (['wav_data'], {}), '(wav_data)\n', (4115, 4125), True, 'import utility as ut\n'), ((5879, 5900), 'traceback.print_exc', 'traceback.print_exc', ([], {}), '()\n', (5898, 5900), False, 'import traceback\n'), ((4006, 4064), 'os.path.join', 'os.path.join', (['self._directory', '"""wav"""', 'audio_utterance_name'], {}), "(self._directory, 'wav', audio_utterance_name)\n", (4018, 4064), False, 'import os\n'), ((4669, 4726), 'os.path.join', 'os.path.join', (['self._directory', '"""h5"""', 'video_utterance_name'], {}), "(self._directory, 'h5', video_utterance_name)\n", (4681, 4726), False, 'import os\n'), ((4934, 4955), 'traceback.print_exc', 'traceback.print_exc', ([], {}), '()\n', (4953, 4955), False, 'import traceback\n'), ((5314, 5335), 'traceback.print_exc', 'traceback.print_exc', ([], {}), '()\n', (5333, 5335), False, 'import traceback\n'), ((4181, 4239), 'os.path.join', 'os.path.join', (['self._directory', '"""wav"""', 'audio_utterance_name'], {}), "(self._directory, 'wav', audio_utterance_name)\n", (4193, 4239), False, 'import os\n'), ((4855, 4912), 'os.path.join', 'os.path.join', (['self._directory', '"""h5"""', 'video_utterance_name'], {}), "(self._directory, 'h5', video_utterance_name)\n", (4867, 4912), False, 'import os\n'), ((5234, 5292), 'os.path.join', 'os.path.join', (['self._directory', '"""mp4"""', 'video_utterance_name'], {}), "(self._directory, 'mp4', video_utterance_name)\n", (5246, 5292), False, 'import os\n'), ((1787, 1821), 'os.path.join', 'os.path.join', (['directory', '"""h5/**/*"""'], {}), "(directory, 'h5/**/*')\n", (1799, 1821), False, 'import os\n'), ((1880, 1915), 'os.path.join', 'os.path.join', (['directory', '"""wav/**/*"""'], {}), "(directory, 'wav/**/*')\n", (1892, 1915), False, 'import os\n'), ((1987, 2021), 'os.path.join', 'os.path.join', (['directory', '"""h5/**/*"""'], {}), "(directory, 'h5/**/*')\n", (1999, 2021), False, 'import os\n'), ((2099, 2134), 'os.path.join', 'os.path.join', (['directory', '"""wav/**/*"""'], {}), "(directory, 'wav/**/*')\n", (2111, 2134), False, 'import os\n'), ((2474, 2504), 'os.path.join', 'os.path.join', (['name', '"""*.mp4.h5"""'], {}), "(name, '*.mp4.h5')\n", (2486, 2504), False, 'import os\n'), ((2407, 2426), 'os.path.normpath', 'os.path.normpath', (['x'], {}), '(x)\n', (2423, 2426), False, 'import os\n')] |
import os
import pytest
@pytest.fixture
def test_data():
import numpy as np
test_data_file = os.path.join(os.path.dirname(os.path.realpath(__file__)),
'data', 'laserembeddings-test-data.npz')
return np.load(test_data_file) if os.path.isfile(test_data_file) else None
| [
"os.path.isfile",
"numpy.load",
"os.path.realpath"
] | [((276, 306), 'os.path.isfile', 'os.path.isfile', (['test_data_file'], {}), '(test_data_file)\n', (290, 306), False, 'import os\n'), ((249, 272), 'numpy.load', 'np.load', (['test_data_file'], {}), '(test_data_file)\n', (256, 272), True, 'import numpy as np\n'), ((133, 159), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (149, 159), False, 'import os\n')] |
# U-Net Model Construction
import unittest
import numpy as np
import keras
from keras.models import *
from keras.layers import *
from keras.optimizers import *
from keras.regularizers import l1, l2
from keras import backend as K
def sagittal_spine_unet(input_size, num_classes, filter_multiplier=10, regularization_rate=0.):
input_ = Input((input_size, input_size, 1))
skips = []
output = input_
num_layers = int(np.floor(np.log2(input_size)))
down_conv_kernel_sizes = np.zeros([num_layers], dtype=int)
down_filter_numbers = np.zeros([num_layers], dtype=int)
up_conv_kernel_sizes = np.zeros([num_layers], dtype=int)
up_filter_numbers = np.zeros([num_layers], dtype=int)
for layer_index in range(num_layers):
down_conv_kernel_sizes[layer_index] = int(3)
down_filter_numbers[layer_index] = int((layer_index + 1) * filter_multiplier + num_classes)
up_conv_kernel_sizes[layer_index] = int(4)
up_filter_numbers[layer_index] = int((num_layers - layer_index - 1) * filter_multiplier + num_classes)
for shape, filters in zip(down_conv_kernel_sizes, down_filter_numbers):
skips.append(output)
output = Conv2D(filters, (shape, shape), strides=2, padding="same", activation="relu",
bias_regularizer=l1(regularization_rate))(output)
for shape, filters in zip(up_conv_kernel_sizes, up_filter_numbers):
output = keras.layers.UpSampling2D()(output)
skip_output = skips.pop()
output = concatenate([output, skip_output], axis=3)
if filters != num_classes:
output = Conv2D(filters, (shape, shape), activation="relu", padding="same",
bias_regularizer=l1(regularization_rate))(output)
output = BatchNormalization(momentum=.9)(output)
else:
output = Conv2D(filters, (shape, shape), activation="softmax", padding="same",
bias_regularizer=l1(regularization_rate))(output)
assert len(skips) == 0
return Model([input_], [output])
def dice_coef(y_true, y_pred, smooth=1):
"""
Dice = (2*|X & Y|)/ (|X|+ |Y|)
= 2*sum(|A*B|)/(sum(A^2)+sum(B^2))
ref: https://arxiv.org/pdf/1606.04797v1.pdf
"""
intersection = K.sum(K.abs(y_true * y_pred), axis=-1)
return (2. * intersection + smooth) / (K.sum(K.square(y_true), -1) + K.sum(K.square(y_pred), -1) + smooth)
def weighted_categorical_crossentropy(weights):
"""
A weighted version of keras.objectives.categorical_crossentropy
Variables:
weights: numpy array of shape (C,) where C is the number of classes
"""
weights = K.variable(weights)
def loss(y_true, y_pred):
# scale predictions so that the class probas of each sample sum to 1
y_pred /= K.sum(y_pred, axis=-1, keepdims=True)
# clip to prevent NaN's and Inf's
y_pred = K.clip(y_pred, K.epsilon(), 1 - K.epsilon())
# calc
loss = y_true * K.log(y_pred) * weights
loss = -K.sum(loss, -1)
return loss
return loss
class SagittalSpineUnetTest(unittest.TestCase):
def test_create_model(self):
model = sagittal_spine_unet(128, 2)
if __name__ == '__main__':
unittest.main() | [
"keras.backend.sum",
"keras.layers.UpSampling2D",
"keras.backend.square",
"numpy.zeros",
"keras.backend.log",
"keras.regularizers.l1",
"unittest.main",
"keras.backend.variable",
"numpy.log2",
"keras.backend.abs",
"keras.backend.epsilon"
] | [((496, 529), 'numpy.zeros', 'np.zeros', (['[num_layers]'], {'dtype': 'int'}), '([num_layers], dtype=int)\n', (504, 529), True, 'import numpy as np\n'), ((556, 589), 'numpy.zeros', 'np.zeros', (['[num_layers]'], {'dtype': 'int'}), '([num_layers], dtype=int)\n', (564, 589), True, 'import numpy as np\n'), ((617, 650), 'numpy.zeros', 'np.zeros', (['[num_layers]'], {'dtype': 'int'}), '([num_layers], dtype=int)\n', (625, 650), True, 'import numpy as np\n'), ((675, 708), 'numpy.zeros', 'np.zeros', (['[num_layers]'], {'dtype': 'int'}), '([num_layers], dtype=int)\n', (683, 708), True, 'import numpy as np\n'), ((2669, 2688), 'keras.backend.variable', 'K.variable', (['weights'], {}), '(weights)\n', (2679, 2688), True, 'from keras import backend as K\n'), ((3249, 3264), 'unittest.main', 'unittest.main', ([], {}), '()\n', (3262, 3264), False, 'import unittest\n'), ((2284, 2306), 'keras.backend.abs', 'K.abs', (['(y_true * y_pred)'], {}), '(y_true * y_pred)\n', (2289, 2306), True, 'from keras import backend as K\n'), ((2815, 2852), 'keras.backend.sum', 'K.sum', (['y_pred'], {'axis': '(-1)', 'keepdims': '(True)'}), '(y_pred, axis=-1, keepdims=True)\n', (2820, 2852), True, 'from keras import backend as K\n'), ((445, 464), 'numpy.log2', 'np.log2', (['input_size'], {}), '(input_size)\n', (452, 464), True, 'import numpy as np\n'), ((1432, 1459), 'keras.layers.UpSampling2D', 'keras.layers.UpSampling2D', ([], {}), '()\n', (1457, 1459), False, 'import keras\n'), ((2927, 2938), 'keras.backend.epsilon', 'K.epsilon', ([], {}), '()\n', (2936, 2938), True, 'from keras import backend as K\n'), ((3036, 3051), 'keras.backend.sum', 'K.sum', (['loss', '(-1)'], {}), '(loss, -1)\n', (3041, 3051), True, 'from keras import backend as K\n'), ((2944, 2955), 'keras.backend.epsilon', 'K.epsilon', ([], {}), '()\n', (2953, 2955), True, 'from keras import backend as K\n'), ((2996, 3009), 'keras.backend.log', 'K.log', (['y_pred'], {}), '(y_pred)\n', (3001, 3009), True, 'from keras import backend as K\n'), ((1309, 1332), 'keras.regularizers.l1', 'l1', (['regularization_rate'], {}), '(regularization_rate)\n', (1311, 1332), False, 'from keras.regularizers import l1, l2\n'), ((2367, 2383), 'keras.backend.square', 'K.square', (['y_true'], {}), '(y_true)\n', (2375, 2383), True, 'from keras import backend as K\n'), ((2397, 2413), 'keras.backend.square', 'K.square', (['y_pred'], {}), '(y_pred)\n', (2405, 2413), True, 'from keras import backend as K\n'), ((1730, 1753), 'keras.regularizers.l1', 'l1', (['regularization_rate'], {}), '(regularization_rate)\n', (1732, 1753), False, 'from keras.regularizers import l1, l2\n'), ((1974, 1997), 'keras.regularizers.l1', 'l1', (['regularization_rate'], {}), '(regularization_rate)\n', (1976, 1997), False, 'from keras.regularizers import l1, l2\n')] |
import numpy as np
data= get_pricing("SPY", start_date="2003-1-1", end_date="2018-1-1")
prices= data['price']
import matplotlib.pyplot as pyplot
uppers= []
lowers= []
stat1=0
stat2=0
statN1=0
stat0=0
limit= 180
prevStat=1
print(len(prices))
for i in range(0, len(prices)):
if i < limit:
uppers.append(prices[i])
lowers.append(prices[i])
else:
upper=(np.max(prices[(i-limit+1):i]))*0.98
lower=(np.min(prices[(i-limit+1):i]))*1.05
current= prices[i]
uppers.append(upper)
lowers.append(lower)
if prices[i] > upper:
stat2 += 1
prevStat=2
elif prices[i] < lower:
stat0 += 1
prevStat=0
elif lower <= prices[i] <= upper:
if prevStat==0 or prevStat==1:
stat1 += 1
prevStat=1
elif prevStat==2 or prevStat==-1:
statN1 += 1
prevStat=-1
print('Instances where t was in 0 status:',stat0)
print('Instances where t was in 1 status:',stat1)
print('Instances where t was in 2 status:',stat2)
print('Instances where t was in -1 status:',statN1)
print(stat0+stat1+statN1+stat2)
pyplot.plot(prices.index, prices.values, label="prices")
pyplot.plot(prices.index, uppers, label="upper")
pyplot.plot(prices.index, lowers, label="lower")
pyplot.legend(loc="best") | [
"matplotlib.pyplot.plot",
"numpy.min",
"matplotlib.pyplot.legend",
"numpy.max"
] | [((1294, 1350), 'matplotlib.pyplot.plot', 'pyplot.plot', (['prices.index', 'prices.values'], {'label': '"""prices"""'}), "(prices.index, prices.values, label='prices')\n", (1305, 1350), True, 'import matplotlib.pyplot as pyplot\n'), ((1351, 1399), 'matplotlib.pyplot.plot', 'pyplot.plot', (['prices.index', 'uppers'], {'label': '"""upper"""'}), "(prices.index, uppers, label='upper')\n", (1362, 1399), True, 'import matplotlib.pyplot as pyplot\n'), ((1400, 1448), 'matplotlib.pyplot.plot', 'pyplot.plot', (['prices.index', 'lowers'], {'label': '"""lower"""'}), "(prices.index, lowers, label='lower')\n", (1411, 1448), True, 'import matplotlib.pyplot as pyplot\n'), ((1449, 1474), 'matplotlib.pyplot.legend', 'pyplot.legend', ([], {'loc': '"""best"""'}), "(loc='best')\n", (1462, 1474), True, 'import matplotlib.pyplot as pyplot\n'), ((391, 422), 'numpy.max', 'np.max', (['prices[i - limit + 1:i]'], {}), '(prices[i - limit + 1:i])\n', (397, 422), True, 'import numpy as np\n'), ((442, 473), 'numpy.min', 'np.min', (['prices[i - limit + 1:i]'], {}), '(prices[i - limit + 1:i])\n', (448, 473), True, 'import numpy as np\n')] |
# Archivo: animaciones.py
# Basado en https://matplotlib.org/examples/animation/simple_anim.html
# Autor: <NAME>
# Fecha: 28 de diciembre de 2017
# Descripción: Ejemplo de animacion
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import random
PI = 3.1416
fig, ax = plt.subplots()
x = np.arange(0, 4*PI, 0.01)
line, = ax.plot(x, np.sin(x))
# Init only required for blitting to give a clean slate.
def init():
line.set_ydata(np.ma.array(x, mask=True))
return line,
def animate_sin_wave(i):
line.set_ydata(np.sin(x+ i/10.0)) # update the data
return line,
def animate_square_wave(i):
line.set_ydata(0.5*((4/PI)*np.sin(x+ i/10.0)+(4/(3*PI))*np.sin(3*(x+ i/10.0))+(4/(5*PI))*np.sin(5*(x+ i/10.0)))) # update the data
return line,
def animate_noisy_wave(i):
line.set_ydata(0.5*(np.sin(x+ i/10.0)+0.4*np.random.random(size=len(x)))) # update the data
return line,
speed = 20
frames = 200
# Quitar el comentario de ls función de onda que se representa: seno, seno con ruido gaussiano o 'cuadrada'
#funcion = animate_sin_wave
#funcion = animate_noisy_wave
funcion = animate_square_wave
ani = animation.FuncAnimation(fig, funcion, np.arange(1, frames), init_func=init,
interval=speed, blit=True)
plt.show()
funcion = animate_sin_wave
| [
"numpy.ma.array",
"numpy.sin",
"matplotlib.pyplot.subplots",
"numpy.arange",
"matplotlib.pyplot.show"
] | [((313, 327), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (325, 327), True, 'import matplotlib.pyplot as plt\n'), ((333, 359), 'numpy.arange', 'np.arange', (['(0)', '(4 * PI)', '(0.01)'], {}), '(0, 4 * PI, 0.01)\n', (342, 359), True, 'import numpy as np\n'), ((1304, 1314), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1312, 1314), True, 'import matplotlib.pyplot as plt\n'), ((377, 386), 'numpy.sin', 'np.sin', (['x'], {}), '(x)\n', (383, 386), True, 'import numpy as np\n'), ((1213, 1233), 'numpy.arange', 'np.arange', (['(1)', 'frames'], {}), '(1, frames)\n', (1222, 1233), True, 'import numpy as np\n'), ((478, 503), 'numpy.ma.array', 'np.ma.array', (['x'], {'mask': '(True)'}), '(x, mask=True)\n', (489, 503), True, 'import numpy as np\n'), ((568, 588), 'numpy.sin', 'np.sin', (['(x + i / 10.0)'], {}), '(x + i / 10.0)\n', (574, 588), True, 'import numpy as np\n'), ((856, 876), 'numpy.sin', 'np.sin', (['(x + i / 10.0)'], {}), '(x + i / 10.0)\n', (862, 876), True, 'import numpy as np\n'), ((745, 771), 'numpy.sin', 'np.sin', (['(5 * (x + i / 10.0))'], {}), '(5 * (x + i / 10.0))\n', (751, 771), True, 'import numpy as np\n'), ((683, 703), 'numpy.sin', 'np.sin', (['(x + i / 10.0)'], {}), '(x + i / 10.0)\n', (689, 703), True, 'import numpy as np\n'), ((712, 738), 'numpy.sin', 'np.sin', (['(3 * (x + i / 10.0))'], {}), '(3 * (x + i / 10.0))\n', (718, 738), True, 'import numpy as np\n')] |
import os
import csv
import numpy as np
import matplotlib.pyplot as plt
plt.switch_backend('agg')
from keras.models import *
from keras import metrics
from keras.layers import *
from keras import optimizers
from keras.preprocessing import text
from keras.utils import to_categorical
from keras.preprocessing import sequence
from keras.models import Model
from keras.callbacks import ModelCheckpoint
def train_save_model():
dic = 3
#------------------------------------------------------------------------------------------------------------------------------
# calculate the length of the files..
#subtract 1 if headers are present..
num_train = len(open('data/raw/Train.csv', 'r').readlines())
num_test = len(open('data/raw/Test.csv', 'r').readlines())
print('\nDataset statistics : ' + ' num_train : ' + str(num_train) + ', num_test : ' + str(num_test) + '\n')
#-------------------------------------------------------------------------------------------------------
#Loading lists..
train_ans, anslist = [], []
def ans_vec(data):
f = open('data/raw/' + data + '.csv')
lines = csv.reader(f)
#next(lines) #to skip the header of the csv
for line in lines:
source_uri = line[4]
anslist.append(source_uri)
if data == 'Train':
train_ans.append(source_uri)
f.close()
ans_vec('Train')
#-------------------------------------------------------------------------------------------------------
#Loading features..
train_title_feature = np.load('data/vectorized/Train_title.npy')
train_summary_feature = np.load('data/vectorized/Train_summary.npy')
tokenizer_a = text.Tokenizer(num_words=dic+1)
tokenizer_a.fit_on_texts(anslist)
trainans_feature = tokenizer_a.texts_to_sequences(train_ans)
trainans_feature = sequence.pad_sequences(trainans_feature, dic, padding='post', value=0, truncating='post')
trainans_hot = to_categorical(trainans_feature, dic+1) #one-hot
#-------------------------------------------------------------------------------------------------------
# model building..
print('\nBuilding model...\n')
#title model..
encode_title = Input(shape=(1,128,))
#Summary model..
encode_summary =Input(shape=(1,128,))
#Merge model..
merge_model = Concatenate()([encode_title, encode_summary])
merge_model = Activation('tanh')(merge_model)
batch_model = BatchNormalization()(merge_model)
batch_model = Dense(dic)(batch_model)
batch_model = Permute((2, 1))(batch_model)
#Output model..
output_model = Dense(dic+1, activation='softmax')(batch_model)
gate_model = Model(inputs=[encode_title, encode_summary], outputs=output_model)
gate_model.summary()
#Compile model..
nadam = optimizers.Nadam()
gate_model.compile(loss='categorical_crossentropy', optimizer='nadam', metrics=[metrics.categorical_accuracy])
#save model..
filepath = 'models/MODEL.hdf5'
checkpoint = ModelCheckpoint(filepath,verbose=1, save_best_only=True, mode='min')
callbacks_list = [checkpoint]
history = gate_model.fit([ train_title_feature,train_summary_feature], trainans_hot, epochs=100, batch_size=128, callbacks=callbacks_list, verbose=1)
# serialize model to JSON
model_json = gate_model.to_json()
with open('models/MODEL.json', "w") as json_file:
json_file.write(model_json)
# serialize weights to HDF5
gate_model.save_weights('models/MODEL.h5')
print("\nSaved model to disk...\n")
def main():
if os.path.exists('models') == False:
os.mkdir('models')
if os.path.isfile('models/MODEL.hdf5') == False:
print('\n\nTraining model...')
train_save_model()
print('\nTraining complete...\n\n')
if __name__ == "__main__":
main() | [
"os.path.exists",
"keras.preprocessing.text.Tokenizer",
"keras.callbacks.ModelCheckpoint",
"keras.utils.to_categorical",
"os.path.isfile",
"keras.optimizers.Nadam",
"keras.models.Model",
"os.mkdir",
"matplotlib.pyplot.switch_backend",
"keras.preprocessing.sequence.pad_sequences",
"numpy.load",
... | [((73, 98), 'matplotlib.pyplot.switch_backend', 'plt.switch_backend', (['"""agg"""'], {}), "('agg')\n", (91, 98), True, 'import matplotlib.pyplot as plt\n'), ((1608, 1650), 'numpy.load', 'np.load', (['"""data/vectorized/Train_title.npy"""'], {}), "('data/vectorized/Train_title.npy')\n", (1615, 1650), True, 'import numpy as np\n'), ((1679, 1723), 'numpy.load', 'np.load', (['"""data/vectorized/Train_summary.npy"""'], {}), "('data/vectorized/Train_summary.npy')\n", (1686, 1723), True, 'import numpy as np\n'), ((1743, 1776), 'keras.preprocessing.text.Tokenizer', 'text.Tokenizer', ([], {'num_words': '(dic + 1)'}), '(num_words=dic + 1)\n', (1757, 1776), False, 'from keras.preprocessing import text\n'), ((1902, 1995), 'keras.preprocessing.sequence.pad_sequences', 'sequence.pad_sequences', (['trainans_feature', 'dic'], {'padding': '"""post"""', 'value': '(0)', 'truncating': '"""post"""'}), "(trainans_feature, dic, padding='post', value=0,\n truncating='post')\n", (1924, 1995), False, 'from keras.preprocessing import sequence\n'), ((2011, 2052), 'keras.utils.to_categorical', 'to_categorical', (['trainans_feature', '(dic + 1)'], {}), '(trainans_feature, dic + 1)\n', (2025, 2052), False, 'from keras.utils import to_categorical\n'), ((2742, 2808), 'keras.models.Model', 'Model', ([], {'inputs': '[encode_title, encode_summary]', 'outputs': 'output_model'}), '(inputs=[encode_title, encode_summary], outputs=output_model)\n', (2747, 2808), False, 'from keras.models import Model\n'), ((2868, 2886), 'keras.optimizers.Nadam', 'optimizers.Nadam', ([], {}), '()\n', (2884, 2886), False, 'from keras import optimizers\n'), ((3073, 3142), 'keras.callbacks.ModelCheckpoint', 'ModelCheckpoint', (['filepath'], {'verbose': '(1)', 'save_best_only': '(True)', 'mode': '"""min"""'}), "(filepath, verbose=1, save_best_only=True, mode='min')\n", (3088, 3142), False, 'from keras.callbacks import ModelCheckpoint\n'), ((1161, 1174), 'csv.reader', 'csv.reader', (['f'], {}), '(f)\n', (1171, 1174), False, 'import csv\n'), ((3638, 3662), 'os.path.exists', 'os.path.exists', (['"""models"""'], {}), "('models')\n", (3652, 3662), False, 'import os\n'), ((3681, 3699), 'os.mkdir', 'os.mkdir', (['"""models"""'], {}), "('models')\n", (3689, 3699), False, 'import os\n'), ((3708, 3743), 'os.path.isfile', 'os.path.isfile', (['"""models/MODEL.hdf5"""'], {}), "('models/MODEL.hdf5')\n", (3722, 3743), False, 'import os\n')] |
import sys
import os
import numpy as np
sys.path.append(os.path.join(os.path.dirname(__file__), 'pathfind/build'))
from alphazero_general.Game import Game
from .QuoridorLogic import QuoridorBoard
class QuoridorGame(Game):
def __init__(self, n):
super().__init__()
self.n = n
self.action_size = 12 + 2 * (self.n - 1) ** 2
self.board_len = 2 * self.n - 1
def __str__(self):
return 'quoridor_n' + str(self.n) + '_v3'
def getInitBoard(self):
"""
Returns:
startBoard: a representation of the board (ideally this is the form
that will be the input to your neural network)
"""
return QuoridorBoard(self.n)
def getActionSize(self):
"""
Returns:
actionSize: number of all possible actions
"""
# 4 pawn moves, 8 jumps, 64 vertical walls, 64 horizontal walls
return self.action_size
def getBoardSize(self):
return (self.n, self.n, 2), (self.n - 1, self.n - 1, 2), 17
def getNextState(self, board, player, action):
"""
Input:
board: current board
player: current player (1 or -1)
action: action taken by current player
Returns:
nextBoard: board after applying action
nextPlayer: player who plays in the next turn (should be -player)
"""
next_board = QuoridorBoard(self.n, board=board)
next_board.executeAction(player, action)
return next_board, -player
def getValidActions(self, board, player):
"""
Input:
board: current board
player: current player
Returns:
validMoves: a binary vector of length self.getActionSize(), 1 for
moves that are valid from the current board and player,
0 for invalid moves
"""
return board.getValidActions(player)
def getGameEnded(self, board, player):
"""
Input:
board: current board
player: current player (1 or -1)
Returns:
r: 0 if game has not ended. 1 if player won, -1 if player lost,
small non-zero value for draw.
"""
return board.getGameEnded(player)
def getCanonicalForm(self, board, player):
"""
Input:
board: current board
player: current player (1 or -1)
Returns:
canonicalBoard: returns canonical form of board. The canonical form
should be independent of player. For e.g. in chess,
the canonical form can be chosen to be from the pov
of white. When the player is white, we can return
board as is. When the player is black, we can invert
the colors and return the board.
"""
next_board = QuoridorBoard(self.n, board=board)
return next_board.makeCanonical(player)
def getSymmetries(self, board, pi):
"""
Input:
board: current board
pi: policy vector of size self.getActionSize()
Returns:
symmForms: a list of [(board,pi)] where each tuple is a symmetrical
form of the board and the corresponding pi vector. This
is used when training the neural network from examples.
"""
pawn_moves = 12
vwa_size = pawn_moves + (self.n - 1) ** 2
vw_actions = list(np.flipud(np.array(pi[pawn_moves:vwa_size]).reshape(self.n - 1, self.n - 1)).flatten())
hw_actions = list(np.flipud(np.array(pi[vwa_size:]).reshape(self.n - 1, self.n - 1)).flatten())
pi2 = pi[:12] + vw_actions + hw_actions
pi2[2], pi2[3] = pi2[3], pi2[2]
pi2[6], pi2[7] = pi2[7], pi2[6]
pi2[8], pi2[10] = pi2[10], pi2[8]
pi2[9], pi2[11] = pi2[9], pi2[11]
return [(board.getBoard(), pi), (board.getBoardFlippedHorizontally(), pi2)]
def stringRepresentation(self, board):
"""
Input:
board: current board
Returns:
boardString: a quick conversion of board to a string format.
Required by MCTS for hashing.
"""
return board.getBoardHashable()
def display(self, board, name=None, save_folder=None, save=True):
board.plot(name=name, save_folder=save_folder, save=save)
| [
"os.path.dirname",
"numpy.array"
] | [((71, 96), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (86, 96), False, 'import os\n'), ((3608, 3641), 'numpy.array', 'np.array', (['pi[pawn_moves:vwa_size]'], {}), '(pi[pawn_moves:vwa_size])\n', (3616, 3641), True, 'import numpy as np\n'), ((3722, 3745), 'numpy.array', 'np.array', (['pi[vwa_size:]'], {}), '(pi[vwa_size:])\n', (3730, 3745), True, 'import numpy as np\n')] |
#-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: kol
#
# Created: 06.02.2020
# Copyright: (c) kol 2020
# Licence: <your licence>
#-------------------------------------------------------------------------------
import sys
import cv2
from skimage import draw, segmentation
import numpy as np
import matplotlib as plt
from pathlib import Path
import random
import copy
import itertools
import time
import simpleaudio as sa
from img_utils import rgba_to_rgb, rgb_to_rgba, apply_patch, color_to_cv_color
from img_utils import increase_brightness
sys.path.append('..\\gbr')
from gr.utils import resize3
def reversable_iter(src):
class __iter:
def __init__(self, src, fun=itertools.cycle):
self.__src = src
self.__fun=fun
self.__iter = self.__fun(self.__src)
self.direct = True
def __iter__(self):
return self
def __next__(self):
return next(self.__iter)
def reverse(self):
cur_val = next(self.__iter)
self.__src = [x for x in reversed(self.__src)]
self.__iter = self.__fun(self.__src)
self.direct = not self.direct
for v in self.__src:
next(self.__iter)
if v == cur_val:
next(self.__iter)
break
def reverse_if(self, direct):
if self.direct != direct:
self.reverse()
return __iter(src)
class Sprite:
def __init__(self, scene):
self.scene = scene
self.body, self.mask = None, None
self.x, self.y = 0, 0
self.loc = None
self.load()
def load(self):
pass
def set_loc(self, loc):
self.loc = loc
def one_frame(self, frame, n_frame, elapsed_time):
return frame
def move(self, n_frame, elapsed_time):
pass
def flip(self):
self.body = cv2.flip(self.body, 1)
self.mask = cv2.flip(self.mask, 1)
@property
def nested_sprites(self):
return []
@property
def is_outside(self):
return False
class Car(Sprite):
def __init__(self, scene):
super(Car, self).__init__(scene)
self.delay_start = 3
self.__moving = None
n = [-1, 0, 0, 0]
p = [1, 0, 0, 0]
self.shift_iter = itertools.cycle(n + p + p + n)
def load(self):
img = cv2.imread('animate\\body.png', -1)
if img is None:
raise Exception("Image not found: animate\\body.png")
self.scale = 1 - max(img.shape) / self.scene.frame_size
self.body, self.mask = \
rgba_to_rgb(cv2.resize(img, None,
fx=self.scale, fy=self.scale, interpolation=cv2.INTER_CUBIC))
self.wheels = [Wheel(self.scene, self, n, f) \
for n, f in enumerate(Path().cwd().joinpath('animate').glob('wheel*.png'))]
self.glass = Glass(self.scene, self)
self.sounds = [sa.WaveObject.from_wave_file(str(f)) \
for f in Path().cwd().joinpath('animate').glob('sound*.wav')]
self.cur_sound = None
def set_loc(self, loc):
self.loc = loc
if self.scene.dir < 0:
self.x = loc.road[1][0] - self.body.shape[1] - 20
self.y = loc.road[1][1] - self.body.shape[0] - 20
else:
self.x = loc.road[0][0] + 20
self.y = loc.road[1][1] - self.body.shape[0] - 20
def one_frame(self, frame, n_frame, elapsed_time):
if self.cur_sound is None or not self.cur_sound.is_playing():
n = 1 if self.moving else 0
self.cur_sound = self.sounds[n].play()
frame = apply_patch(frame, self.x, self.y, self.body, self.mask)
return frame
def move(self, n_frame, elapsed_time):
self.y += next(self.shift_iter)
if elapsed_time > self.delay_start and self.moving is None:
self.moving = True
if self.moving:
self.x = self.x + 5 * self.scene.dir
@property
def nested_sprites(self):
a = self.wheels
a.extend([self.glass])
return a
@property
def is_outside(self):
if scene.dir < 0:
return self.x < 0 or self.y < 0
else:
return self.x + self.body.shape[1] >= self.loc.body.shape[1] or \
self.y + self.body.shape[0] >= self.loc.body.shape[0]
@property
def moving(self):
return self.__moving
@moving.setter
def moving(self, m):
self.__moving = m
if self.cur_sound is not None:
self.cur_sound.stop()
self.cur_sound = None
class Wheel(Sprite):
def __init__(self, scene, car, n_wheel, fname):
self.fname = str(fname)
self.car = car
self.n_wheel = n_wheel
self.angle = 0
super(Wheel, self).__init__(scene)
def load(self):
img = cv2.imread(self.fname, -1)
if img is None:
raise Exception("Image not found: ", self.fname)
self.body, self.mask = \
rgba_to_rgb(cv2.resize(img, None, fx=self.car.scale, fy=self.car.scale,
interpolation=cv2.INTER_CUBIC))
def one_frame(self, frame, n_frame, elapsed_time):
if self.n_wheel == 0:
self.x = self.car.x + 20
self.y = self.car.y + int(self.car.body.shape[0] * 0.7)
else:
self.x = self.car.x + int(self.car.body.shape[1] * 0.7)
self.y = self.car.y + int(self.car.body.shape[0] * 0.65)
wy, wx = self.body.shape[0] // 2, self.body.shape[1] // 2
M = cv2.getRotationMatrix2D((wx, wy), self.angle, 1)
img = cv2.warpAffine(self.body, M, self.body.shape[:2] )
mask = cv2.warpAffine(self.mask, M, self.mask.shape[:2] )
frame = apply_patch(frame, self.x, self.y, img, mask)
return frame
def move(self, n_frame, elapsed_time):
if self.car.moving:
self.angle = self.angle - 10 * self.scene.dir
if self.angle >= 360:
self.angle = 0
class Glass(Sprite):
def __init__(self, scene, car):
self.car = car
super(Glass, self).__init__(scene)
def load(self):
img = cv2.imread("animate\\glass.png", -1)
if img is None:
raise Exception("Image not found: ", self.fname)
self.body, self.mask = \
rgba_to_rgb(cv2.resize(img, None, fx=self.car.scale, fy=self.car.scale,
interpolation=cv2.INTER_CUBIC))
def one_frame(self, frame, n_frame, elapsed_time):
self.x = self.car.x + int(self.car.body.shape[1] * 0.2) - 3
self.y = self.car.y + int(self.car.body.shape[0] * 0.1)
if self.scene.dir > 0:
self.x -= 19
frame = apply_patch(frame, self.x, self.y, self.body, self.mask, alpha=0.4)
return frame
class Sun(Sprite):
def load(self):
self.is_sun = True
self.y, self.x, self.r = 0, 0, 0
self.cy, self.cx, self.cr = 0, 0, 0
self.angle = -200
self.delay_start = 3
self.moving = None
def set_loc(self, loc):
self.loc = loc
self.cy = self.loc.horizon[0][1]
self.cx = loc.body.shape[1] // 2
self.cr = int(self.cx / 1.5)
def one_frame(self, frame, n_frame, elapsed_time):
if n_frame == 0:
self.cur_cx, self.cur_cy, self.cur_cr = self.cx, self.cy, self.cr
# Draw circle
sky_shape = [self.cy, frame.shape[1]]
yellow = color_to_cv_color('yellow')
self.x = self.cur_cx + int(self.cur_cr * np.cos(self.angle * np.pi / 180))
self.y = self.cur_cy + int(self.cur_cr * np.sin(self.angle * np.pi / 180))
self.r = 60
rr, cc = draw.circle(self.y, self.x, self.r, shape=sky_shape)
rr_n = rr[rr < self.cy]
if len(rr_n) > 0:
frame[rr_n, cc] = yellow
else:
self.cur_cx, self.cur_cy, self.cur_cr = self.cx, self.cy, self.cr
# Draw spikes
for a in range(10, 361, 10):
x1 = self.x + int(self.r * np.cos((a-5) * np.pi / 180))
y1 = self.y + int(self.r * np.sin((a-5) * np.pi / 180))
x2 = self.x + int((self.r + 30) * np.cos(a * np.pi / 180))
y2 = self.y + int((self.r + 30) * np.sin(a * np.pi / 180))
x3 = self.x + int(self.r * np.cos((a+5) * np.pi / 180))
y3 = self.y + int(self.r * np.sin((a+5) * np.pi / 180))
xc = self.x + int((self.r + 5) * np.cos(a * np.pi / 180))
yc = self.y + int((self.r + 5) * np.sin(a * np.pi / 180))
rr, cc = draw.bezier_curve(y1, x1, y2, x2, y3, x3, 8, shape=sky_shape)
frame[rr, cc] = yellow
# Brigtness
if self.y > self.loc.horizon[0][1]:
value = -30
else:
show_pct = float(self.loc.horizon[0][1] - self.y) / self.loc.horizon[0][1]
value = 60 * show_pct - 30
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
hsv[:,:,2] = cv2.add(hsv[:,:,2], int(value))
frame = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)
return frame
def move(self, n_frame, elapsed_time):
if elapsed_time > self.delay_start and self.moving is None:
self.moving = True
if self.moving and n_frame % 2 == 0:
self.angle += 0.5
class Location(Sprite):
def __init__(self, scene, n_loc, fname):
self.n_loc = n_loc
self.fname = str(fname)
self.elements = []
super(Location, self).__init__(scene)
def load(self):
img = cv2.imread(self.fname)
if img is None:
raise Exception("Image not found: ", self.fname)
self.body, self.scale, _ = resize3(img, self.scene.frame_size)
self.road = [[0, self.body.shape[0]-150], [self.body.shape[1], self.body.shape[0]-50]]
self.horizon = [[0, 310], [self.body.shape[1], 310]]
deltas = [[0, 0], [80, 20], [60, -20], [38, -40], [70, 30]]
for h in self.horizon:
h[1] += deltas[self.n_loc][0]
for r in self.road:
r[1] += deltas[self.n_loc][1]
self.elements = [LocElement(self.scene, self, n, str(f)) \
for n, f in enumerate(Path().cwd().joinpath('animate').glob( \
'elem' + str(self.n_loc+1) + '_*.png'))]
def flip(self):
pass
@property
def nested_sprites(self):
return self.elements
class LocElement(Sprite):
def __init__(self, scene, loc, n_elem, fname):
self.fname = str(fname)
self.parent_loc = loc
self.n_elem = n_elem
super(LocElement, self).__init__(scene)
def load(self):
img = cv2.imread(self.fname, -1)
if img is None:
raise Exception("Image not found: ", self.fname)
self.body, self.mask = \
rgba_to_rgb(cv2.resize(img, None, fx=self.parent_loc.scale[0],
fy=self.parent_loc.scale[1],
interpolation=cv2.INTER_CUBIC))
def one_frame(self, frame, n_frame, elapsed_time):
if self.loc == self.parent_loc:
if self.parent_loc.n_loc == 0:
self.x = 0
self.y = self.loc.horizon[0][1] - self.body.shape[0] + 8
elif self.parent_loc.n_loc == 1:
self.x = frame.shape[1] - self.body.shape[1] - 0
self.y = frame.shape[0] - self.body.shape[0] - 182
elif self.parent_loc.n_loc == 2:
self.x = 143
self.y = 95
elif self.parent_loc.n_loc == 3:
self.x = 0
self.y = self.parent_loc.horizon[0][1] - self.body.shape[0] + 10
elif self.parent_loc.n_loc == 4:
self.x = 0
self.y = self.parent_loc.horizon[0][1] - self.body.shape[0] + 35
frame = apply_patch(frame, self.x, self.y, self.body, self.mask)
return frame
def flip(self):
pass
class Scene:
def __init__(self):
self.frame_size = 1024
self.locations = [Location(self, n, f) \
for n, f in enumerate(Path().cwd().joinpath('animate').glob('back*.jpg'))]
self.sprites = [Sun(self)]
self.sprites.extend(self.locations)
self.sprites.extend([Car(self)])
self.car = self.sprites[-1]
self.loc_iter = reversable_iter(self.locations)
self.recorder = None
self.dir = -1
@property
def all_sprites(self):
sprites = []
for sprite in self.sprites:
sprites.extend([sprite])
sprites.extend(sprite.nested_sprites)
return sprites
def run(self, interactive=True, record=False):
start_time = time.time()
n_frame = 0
delay_iter = reversable_iter(list(np.linspace(5, stop=30, num=5).astype(int)))
delay = next(delay_iter)
recording = False
sprites = self.all_sprites
loc = next(self.loc_iter)
for sprite in sprites:
sprite.set_loc(loc)
if record:
recording = True
while(True):
frame = loc.body.copy()
tm = time.time() - start_time
for sprite in sprites:
frame = sprite.one_frame(frame, n_frame, tm)
cv2.imshow('Frame', frame)
if recording:
self.record(frame)
key = cv2.waitKey(delay)
if key > 0 and not interactive:
break
elif key & 0xFF == ord('-'):
delay_iter.reverse_if(True)
delay = next(delay_iter)
print('Delay set to', delay)
elif key & 0xFF == ord('+'):
delay_iter.reverse_if(False)
delay = next(delay_iter)
print('Delay set to', delay)
elif key & 0xFF == ord(' '):
self.car.moving = \
True if self.car.moving is None \
else not self.car.moving
elif key & 0xFF == ord('r'):
if not recording:
self.record(frame)
recording = True
else:
self.stop_recording()
recording = False
elif key & 0xFF == ord('q'):
print('Stopping...')
break
elif key & 0xFF == ord('/'):
self.dir = -1 if self.dir == 1 else 1
self.loc_iter.reverse_if(True)
for sprite in sprites:
sprite.flip()
for sprite in sprites:
sprite.move(n_frame, tm)
if self.car.is_outside:
loc = next(self.loc_iter)
if loc.n_loc == 0 and record:
break;
for sprite in sprites:
sprite.set_loc(loc)
sprites = [s for s in sprites if s == self.car or not sprite.is_outside]
n_frame += 1
self.stop_recording()
sa.stop_all()
cv2.waitKey()
def show_location(self, n_loc=0, highlight=False):
img = self.locations[n_loc].body.copy()
if highlight:
r = self.locations[n_loc].road
poly = [ [r[0][0], r[0][1]], [r[0][0], r[1][1]], [r[1][0], r[1][1]], [r[1][0], r[0][1]] ]
cv2.fillPoly(img, [np.array(poly)], [127, 127, 127])
h = self.locations[n_loc].horizon
cv2.line(img, tuple(h[0]), tuple(h[1]), (0,0,255), 2)
cv2.imshow('Location', img)
cv2.waitKey()
def show_frame(self, n_loc=0):
loc = self.locations[n_loc]
frame = loc.body.copy()
for sprite in self.all_sprites:
sprite.set_loc(loc)
frame = sprite.one_frame(frame, 0, 0)
cv2.imshow('Frame', frame)
sa.stop_all()
cv2.waitKey()
def record(self, frame):
if self.recorder is None:
file_name = 'animate\\car.avi'
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
self.recorder = cv2.VideoWriter(file_name, fourcc, 40.0, (frame.shape[1], frame.shape[0]))
print('Recoding started')
self.recorder.write(frame)
def stop_recording(self):
if self.recorder is not None:
self.recorder.release()
self.recorder = None
print('Recoding stopped')
scene = Scene()
##for n in range(len(scene.locations)):
## scene.show_location(n, highlight=True)
#scene.sprites[0].angle = -45
#scene.show_frame(0)
scene.run(record=False)
cv2.destroyAllWindows()
| [
"img_utils.color_to_cv_color",
"cv2.imshow",
"numpy.array",
"cv2.destroyAllWindows",
"numpy.sin",
"sys.path.append",
"skimage.draw.bezier_curve",
"simpleaudio.stop_all",
"pathlib.Path",
"cv2.VideoWriter",
"numpy.linspace",
"cv2.VideoWriter_fourcc",
"gr.utils.resize3",
"cv2.waitKey",
"ite... | [((636, 662), 'sys.path.append', 'sys.path.append', (['"""..\\\\gbr"""'], {}), "('..\\\\gbr')\n", (651, 662), False, 'import sys\n'), ((16723, 16746), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (16744, 16746), False, 'import cv2\n'), ((2010, 2032), 'cv2.flip', 'cv2.flip', (['self.body', '(1)'], {}), '(self.body, 1)\n', (2018, 2032), False, 'import cv2\n'), ((2053, 2075), 'cv2.flip', 'cv2.flip', (['self.mask', '(1)'], {}), '(self.mask, 1)\n', (2061, 2075), False, 'import cv2\n'), ((2428, 2458), 'itertools.cycle', 'itertools.cycle', (['(n + p + p + n)'], {}), '(n + p + p + n)\n', (2443, 2458), False, 'import itertools\n'), ((2494, 2529), 'cv2.imread', 'cv2.imread', (['"""animate\\\\body.png"""', '(-1)'], {}), "('animate\\\\body.png', -1)\n", (2504, 2529), False, 'import cv2\n'), ((3763, 3819), 'img_utils.apply_patch', 'apply_patch', (['frame', 'self.x', 'self.y', 'self.body', 'self.mask'], {}), '(frame, self.x, self.y, self.body, self.mask)\n', (3774, 3819), False, 'from img_utils import rgba_to_rgb, rgb_to_rgba, apply_patch, color_to_cv_color\n'), ((4995, 5021), 'cv2.imread', 'cv2.imread', (['self.fname', '(-1)'], {}), '(self.fname, -1)\n', (5005, 5021), False, 'import cv2\n'), ((5713, 5761), 'cv2.getRotationMatrix2D', 'cv2.getRotationMatrix2D', (['(wx, wy)', 'self.angle', '(1)'], {}), '((wx, wy), self.angle, 1)\n', (5736, 5761), False, 'import cv2\n'), ((5776, 5825), 'cv2.warpAffine', 'cv2.warpAffine', (['self.body', 'M', 'self.body.shape[:2]'], {}), '(self.body, M, self.body.shape[:2])\n', (5790, 5825), False, 'import cv2\n'), ((5842, 5891), 'cv2.warpAffine', 'cv2.warpAffine', (['self.mask', 'M', 'self.mask.shape[:2]'], {}), '(self.mask, M, self.mask.shape[:2])\n', (5856, 5891), False, 'import cv2\n'), ((5910, 5955), 'img_utils.apply_patch', 'apply_patch', (['frame', 'self.x', 'self.y', 'img', 'mask'], {}), '(frame, self.x, self.y, img, mask)\n', (5921, 5955), False, 'from img_utils import rgba_to_rgb, rgb_to_rgba, apply_patch, color_to_cv_color\n'), ((6331, 6367), 'cv2.imread', 'cv2.imread', (['"""animate\\\\glass.png"""', '(-1)'], {}), "('animate\\\\glass.png', -1)\n", (6341, 6367), False, 'import cv2\n'), ((6899, 6966), 'img_utils.apply_patch', 'apply_patch', (['frame', 'self.x', 'self.y', 'self.body', 'self.mask'], {'alpha': '(0.4)'}), '(frame, self.x, self.y, self.body, self.mask, alpha=0.4)\n', (6910, 6966), False, 'from img_utils import rgba_to_rgb, rgb_to_rgba, apply_patch, color_to_cv_color\n'), ((7639, 7666), 'img_utils.color_to_cv_color', 'color_to_cv_color', (['"""yellow"""'], {}), "('yellow')\n", (7656, 7666), False, 'from img_utils import rgba_to_rgb, rgb_to_rgba, apply_patch, color_to_cv_color\n'), ((7872, 7924), 'skimage.draw.circle', 'draw.circle', (['self.y', 'self.x', 'self.r'], {'shape': 'sky_shape'}), '(self.y, self.x, self.r, shape=sky_shape)\n', (7883, 7924), False, 'from skimage import draw, segmentation\n'), ((9089, 9127), 'cv2.cvtColor', 'cv2.cvtColor', (['frame', 'cv2.COLOR_BGR2HSV'], {}), '(frame, cv2.COLOR_BGR2HSV)\n', (9101, 9127), False, 'import cv2\n'), ((9197, 9233), 'cv2.cvtColor', 'cv2.cvtColor', (['hsv', 'cv2.COLOR_HSV2BGR'], {}), '(hsv, cv2.COLOR_HSV2BGR)\n', (9209, 9233), False, 'import cv2\n'), ((9711, 9733), 'cv2.imread', 'cv2.imread', (['self.fname'], {}), '(self.fname)\n', (9721, 9733), False, 'import cv2\n'), ((9855, 9890), 'gr.utils.resize3', 'resize3', (['img', 'self.scene.frame_size'], {}), '(img, self.scene.frame_size)\n', (9862, 9890), False, 'from gr.utils import resize3\n'), ((10816, 10842), 'cv2.imread', 'cv2.imread', (['self.fname', '(-1)'], {}), '(self.fname, -1)\n', (10826, 10842), False, 'import cv2\n'), ((12875, 12886), 'time.time', 'time.time', ([], {}), '()\n', (12884, 12886), False, 'import time\n'), ((15181, 15194), 'simpleaudio.stop_all', 'sa.stop_all', ([], {}), '()\n', (15192, 15194), True, 'import simpleaudio as sa\n'), ((15203, 15216), 'cv2.waitKey', 'cv2.waitKey', ([], {}), '()\n', (15214, 15216), False, 'import cv2\n'), ((15675, 15702), 'cv2.imshow', 'cv2.imshow', (['"""Location"""', 'img'], {}), "('Location', img)\n", (15685, 15702), False, 'import cv2\n'), ((15711, 15724), 'cv2.waitKey', 'cv2.waitKey', ([], {}), '()\n', (15722, 15724), False, 'import cv2\n'), ((15960, 15986), 'cv2.imshow', 'cv2.imshow', (['"""Frame"""', 'frame'], {}), "('Frame', frame)\n", (15970, 15986), False, 'import cv2\n'), ((15995, 16008), 'simpleaudio.stop_all', 'sa.stop_all', ([], {}), '()\n', (16006, 16008), True, 'import simpleaudio as sa\n'), ((16017, 16030), 'cv2.waitKey', 'cv2.waitKey', ([], {}), '()\n', (16028, 16030), False, 'import cv2\n'), ((2741, 2828), 'cv2.resize', 'cv2.resize', (['img', 'None'], {'fx': 'self.scale', 'fy': 'self.scale', 'interpolation': 'cv2.INTER_CUBIC'}), '(img, None, fx=self.scale, fy=self.scale, interpolation=cv2.\n INTER_CUBIC)\n', (2751, 2828), False, 'import cv2\n'), ((5165, 5260), 'cv2.resize', 'cv2.resize', (['img', 'None'], {'fx': 'self.car.scale', 'fy': 'self.car.scale', 'interpolation': 'cv2.INTER_CUBIC'}), '(img, None, fx=self.car.scale, fy=self.car.scale, interpolation=\n cv2.INTER_CUBIC)\n', (5175, 5260), False, 'import cv2\n'), ((6511, 6606), 'cv2.resize', 'cv2.resize', (['img', 'None'], {'fx': 'self.car.scale', 'fy': 'self.car.scale', 'interpolation': 'cv2.INTER_CUBIC'}), '(img, None, fx=self.car.scale, fy=self.car.scale, interpolation=\n cv2.INTER_CUBIC)\n', (6521, 6606), False, 'import cv2\n'), ((8748, 8809), 'skimage.draw.bezier_curve', 'draw.bezier_curve', (['y1', 'x1', 'y2', 'x2', 'y3', 'x3', '(8)'], {'shape': 'sky_shape'}), '(y1, x1, y2, x2, y3, x3, 8, shape=sky_shape)\n', (8765, 8809), False, 'from skimage import draw, segmentation\n'), ((10986, 11101), 'cv2.resize', 'cv2.resize', (['img', 'None'], {'fx': 'self.parent_loc.scale[0]', 'fy': 'self.parent_loc.scale[1]', 'interpolation': 'cv2.INTER_CUBIC'}), '(img, None, fx=self.parent_loc.scale[0], fy=self.parent_loc.scale\n [1], interpolation=cv2.INTER_CUBIC)\n', (10996, 11101), False, 'import cv2\n'), ((12012, 12068), 'img_utils.apply_patch', 'apply_patch', (['frame', 'self.x', 'self.y', 'self.body', 'self.mask'], {}), '(frame, self.x, self.y, self.body, self.mask)\n', (12023, 12068), False, 'from img_utils import rgba_to_rgb, rgb_to_rgba, apply_patch, color_to_cv_color\n'), ((13445, 13471), 'cv2.imshow', 'cv2.imshow', (['"""Frame"""', 'frame'], {}), "('Frame', frame)\n", (13455, 13471), False, 'import cv2\n'), ((13552, 13570), 'cv2.waitKey', 'cv2.waitKey', (['delay'], {}), '(delay)\n', (13563, 13570), False, 'import cv2\n'), ((16159, 16190), 'cv2.VideoWriter_fourcc', 'cv2.VideoWriter_fourcc', (["*'mp4v'"], {}), "(*'mp4v')\n", (16181, 16190), False, 'import cv2\n'), ((16219, 16293), 'cv2.VideoWriter', 'cv2.VideoWriter', (['file_name', 'fourcc', '(40.0)', '(frame.shape[1], frame.shape[0])'], {}), '(file_name, fourcc, 40.0, (frame.shape[1], frame.shape[0]))\n', (16234, 16293), False, 'import cv2\n'), ((13311, 13322), 'time.time', 'time.time', ([], {}), '()\n', (13320, 13322), False, 'import time\n'), ((7717, 7749), 'numpy.cos', 'np.cos', (['(self.angle * np.pi / 180)'], {}), '(self.angle * np.pi / 180)\n', (7723, 7749), True, 'import numpy as np\n'), ((7800, 7832), 'numpy.sin', 'np.sin', (['(self.angle * np.pi / 180)'], {}), '(self.angle * np.pi / 180)\n', (7806, 7832), True, 'import numpy as np\n'), ((15519, 15533), 'numpy.array', 'np.array', (['poly'], {}), '(poly)\n', (15527, 15533), True, 'import numpy as np\n'), ((8211, 8240), 'numpy.cos', 'np.cos', (['((a - 5) * np.pi / 180)'], {}), '((a - 5) * np.pi / 180)\n', (8217, 8240), True, 'import numpy as np\n'), ((8279, 8308), 'numpy.sin', 'np.sin', (['((a - 5) * np.pi / 180)'], {}), '((a - 5) * np.pi / 180)\n', (8285, 8308), True, 'import numpy as np\n'), ((8354, 8377), 'numpy.cos', 'np.cos', (['(a * np.pi / 180)'], {}), '(a * np.pi / 180)\n', (8360, 8377), True, 'import numpy as np\n'), ((8425, 8448), 'numpy.sin', 'np.sin', (['(a * np.pi / 180)'], {}), '(a * np.pi / 180)\n', (8431, 8448), True, 'import numpy as np\n'), ((8489, 8518), 'numpy.cos', 'np.cos', (['((a + 5) * np.pi / 180)'], {}), '((a + 5) * np.pi / 180)\n', (8495, 8518), True, 'import numpy as np\n'), ((8557, 8586), 'numpy.sin', 'np.sin', (['((a + 5) * np.pi / 180)'], {}), '((a + 5) * np.pi / 180)\n', (8563, 8586), True, 'import numpy as np\n'), ((8631, 8654), 'numpy.cos', 'np.cos', (['(a * np.pi / 180)'], {}), '(a * np.pi / 180)\n', (8637, 8654), True, 'import numpy as np\n'), ((8701, 8724), 'numpy.sin', 'np.sin', (['(a * np.pi / 180)'], {}), '(a * np.pi / 180)\n', (8707, 8724), True, 'import numpy as np\n'), ((12949, 12979), 'numpy.linspace', 'np.linspace', (['(5)'], {'stop': '(30)', 'num': '(5)'}), '(5, stop=30, num=5)\n', (12960, 12979), True, 'import numpy as np\n'), ((3123, 3129), 'pathlib.Path', 'Path', ([], {}), '()\n', (3127, 3129), False, 'from pathlib import Path\n'), ((2939, 2945), 'pathlib.Path', 'Path', ([], {}), '()\n', (2943, 2945), False, 'from pathlib import Path\n'), ((10361, 10367), 'pathlib.Path', 'Path', ([], {}), '()\n', (10365, 10367), False, 'from pathlib import Path\n'), ((12277, 12283), 'pathlib.Path', 'Path', ([], {}), '()\n', (12281, 12283), False, 'from pathlib import Path\n')] |
"""
Created on Tue Mar 27 14:34:40 2012
@author: <NAME>
Creates a table of low-pass filter coefficients for demodulating signal.
We design for a pass band of 1/2 the IF frequency and a stop-band of the IF frequency.
We arbitrarily accept 3dB of loss in the pass band and want 30dB of suppression in the stop band.
"""
import scipy.signal
import numpy as np
aCoeffList = []
bCoeffList = []
for IFFreq in np.arange(0.01, 1, 0.01):
(b,a) = scipy.signal.iirdesign(IFFreq/2, IFFreq, 3, 30, ftype='butter')
aCoeffList.append(a)
bCoeffList.append(b)
print('a = [...')
for tmpCoeffs in aCoeffList:
print('{0};...'.format(tmpCoeffs))
print('\n\nb = [...')
for tmpCoeffs in bCoeffList:
print('{0};...'.format(tmpCoeffs))
| [
"numpy.arange"
] | [((409, 433), 'numpy.arange', 'np.arange', (['(0.01)', '(1)', '(0.01)'], {}), '(0.01, 1, 0.01)\n', (418, 433), True, 'import numpy as np\n')] |
import argparse
from time import time
from xml.dom.minidom import parseString
from block import Block
from grid import Grid
from os.path import join
from pattern import Pattern
from pattern_utils import de_densify, measure_density, pattern_to_svg, shorten_jumps, \
remove_short
from stitch import Stitch
from svgutils import scan_lines, stack_paths, trace_image, sort_paths, overall_bbox, \
get_color, get_stroke_width, make_continuous, write_debug, remove_close_paths, \
path1_is_contained_in_path2, shorter_side, is_concave, draw_fill, posturize, \
make_equidistant, perpendicular, split_subpaths, get_pixel_from_string
from configure import PLOTTING, MINIMUM_STITCH_DISTANCE, OUTPUT_DIRECTORY
from svgwrite import rgb
from svgwrite.shapes import Circle
if PLOTTING:
from scipy.spatial.qhull import Voronoi
import matplotlib.pyplot as plt
else:
plt = None
try:
# potrace is wrapped in a try/except statement because the digitizer might sometimes
# be run on an environment where Ctypes are not allowed
import potrace
from potrace import BezierSegment, CornerSegment
except:
potrace = None
BezierSegment = None
CornerSegment = None
from numpy import argmax, average, ceil
from svgpathtools import svgdoc2paths, Line, Path
from brother import BrotherEmbroideryFile, pattern_to_csv, upload
from configure import MINIMUM_STITCH_LENGTH, MAXIMUM_STITCH, DEBUG
fill_method = "scan" #"grid"#"polygon"#"voronoi
parser = argparse.ArgumentParser(
description='Generate a pes file for brother sewing machines from an svg or png image')
parser.add_argument('--filename', type=str,
help='The filename of the input image.')
parser.add_argument('--fill', dest="fill", action="store_true",
help="Fill the shapes")
class Digitizer(object):
def __init__(self, filename=None, fill=False):
self.fill = fill
# stitches is the stitches that have yet to be added to the pattern
self.stitches = []
self.attributes = []
self.all_paths = []
self.fill_color = None
self.last_color = None
self.last_stitch = None
self.pattern = Pattern()
if not filename:
return
self.filecontents = open(join("workspace", filename), "r").read()
if filename.split(".")[-1] != "svg":
self.image_to_pattern()
else:
self.svg_to_pattern()
def image_to_pattern(self):
self.all_paths, self.attributes = stack_paths(*trace_image(self.filecontents))
self.scale = 2.64583333
self.generate_pattern()
def svg_to_pattern(self):
doc = parseString(self.filecontents)
# make sure the document size is appropriate
root = doc.getElementsByTagName('svg')[0]
root_width = root.attributes.getNamedItem('width')
viewbox = root.getAttribute('viewBox')
if viewbox:
lims = [float(i) for i in viewbox.split(" ")]
width = abs(lims[0] - lims[2])
height = abs(lims[1] - lims[3])
else:
# run through all the coordinates
bbox = overall_bbox(self.all_paths)
width = bbox[1] - bbox[0]
height = bbox[3] - bbox[2]
path_attributes = split_subpaths(*svgdoc2paths(doc))
if self.fill:
self.all_paths, self.attributes = sort_paths(*stack_paths(*path_attributes))
else:
self.all_paths, self.attributes = sort_paths(*path_attributes)
if root_width is not None:
root_width = get_pixel_from_string(root_width.value, width)
size = 4*25.4
# The maximum size is 4 inches - multiplied by 10 for scaling
if root_width:
size = root_width
size *= 10.0
if width > height:
self.scale = size / width
else:
self.scale = size / height
self.generate_pattern()
def add_block(self, clear=True):
if len(self.stitches) == 0:
print("got no stitches in add block!")
return
if self.last_color is not None:
block = Block(stitches=self.stitches, color=self.last_color)
self.pattern.add_block(block)
else:
print("last color was none, not adding the block")
if clear:
self.last_stitch = self.stitches[-1]
self.stitches = []
def generate_pattern(self):
# cut the paths by the paths above
if self.fill:
self.all_paths, self.attributes = stack_paths(self.all_paths, self.attributes)
for k, v in enumerate(self.attributes):
paths = self.all_paths[k]
# first, look for the color from the fill
# if fill is false, change the attributes so that the fill is none but the
# stroke is the fill (if not set)
self.fill_color = get_color(v, "fill")
self.stroke_color = get_color(v, "stroke")
stroke_width = get_stroke_width(v, self.scale)
if not self.fill:
if not self.stroke_color:
self.stroke_color = self.fill_color
stroke_width = stroke_width if stroke_width != MINIMUM_STITCH_LENGTH \
else MINIMUM_STITCH_LENGTH * 3.0
self.fill_color = None
if self.fill_color is None and self.stroke_color is None:
self.fill_color = [0, 0, 0]
# if both the fill color and stroke color are none,
if self.fill_color is not None:
if len(self.pattern.blocks) == 0 and self.fill_color is not None:
self.pattern.add_block(Block([Stitch(["JUMP"], 0, 0)], color=self.fill_color))
self.switch_color(self.fill_color)
if fill_method == "polygon":
full_path = Path(*paths)
if not full_path.iscontinuous():
self.fill_polygon(make_continuous(full_path))
else:
self.fill_polygon(paths)
elif fill_method == "grid":
self.fill_grid(paths)
elif fill_method == "scan":
self.fill_scan(paths)
elif fill_method == "voronoi":
self.fill_voronoi(paths)
self.last_color = self.fill_color
self.add_block()
# then do the stroke
if self.stroke_color is None:
continue
self.switch_color(self.stroke_color)
paths = self.generate_stroke_width(paths, stroke_width)
self.generate_straight_stroke(paths)
self.last_color = self.stroke_color
if len(self.pattern.blocks) == 0 and self.stroke_color is not None:
self.pattern.add_block(
Block([Stitch(["JUMP"], 0, 0)], color=self.stroke_color))
if self.stroke_color:
self.add_block()
if len(self.stitches) > 0:
self.last_color = self.stroke_color
# finally, move the stitches so that it is as close as possible to the next
# location
if len(self.pattern.blocks) > 0 and len(self.pattern.blocks[-1].stitches) > 0:
last_stitch = self.pattern.blocks[-1].stitches[-1]
self.pattern.add_block(
Block(stitches=[Stitch(["END"], last_stitch.x, last_stitch.y)],
color=self.pattern.blocks[-1].color))
def generate_stroke_width(self, paths, stroke_width):
new_paths = []
if stroke_width / MINIMUM_STITCH_DISTANCE <= 1.:
return paths
# how many times can the MINIMUM_STITCH_DISTANCE fit in the stroke width?
# if it is greater 1, duplicate the stitch offset by the minimum stitch
for i in range(0, int(stroke_width / MINIMUM_STITCH_DISTANCE)):
for path in paths:
if i == 0:
new_paths.append(path)
continue
# what is the broad angle of the path? (used to determine the
# perpendicular angle to translate the path by)
num_norm_samples = 10.0
diff = average([path.normal(t / num_norm_samples)
for t in range(int(num_norm_samples))])
diff *= -1 if i % 2 == 0 else 1
diff *= ceil(i / 2.0) * MINIMUM_STITCH_DISTANCE / 2.0
# if i is odd, translate up/left, if even, translate down/right
new_paths.append(path.translated(diff))
return new_paths
def switch_color(self, new_color):
if self.last_color is None or self.last_color == new_color \
or self.last_stitch is None:
return
to = self.last_stitch
block = Block(stitches=[Stitch(["TRIM"], to.x, to.y)],
color=self.last_color)
self.pattern.add_block(block)
block = Block(stitches=[Stitch(["COLOR"], to.x, to.y)],
color=new_color)
self.pattern.add_block(block)
self.stitches = []
def generate_straight_stroke(self, paths):
# sort the paths by the distance to the upper right corner
bbox = overall_bbox(paths)
write_debug("stroke_travel", [(Path(*paths), "none", (0, 0, 0)),
(Circle(center=(bbox[0], bbox[2]), r=1, fill=rgb(255, 0, 0)), "none", "none")])
# discretize the paths
points = []
for i, path in enumerate(paths):
if path.length() == 0:
continue
points.append(path.start*self.scale)
num_segments = ceil(path.length() / MINIMUM_STITCH_LENGTH)
for seg_i in range(int(num_segments + 1)):
points.append(path.point(seg_i / num_segments) * self.scale)
# if the next stitch doesn't start at the end of this stitch, add that one as
# well
end_stitch = path.end * self.scale
if i != len(paths) - 1:
if path.end != paths[i + 1].start:
points.append(end_stitch)
else:
points.append(end_stitch)
if len(points) == 0:
return
# find the point closest to the last stitch
if not self.last_stitch:
last_stitch = points[0]
else:
last_stitch = self.last_stitch.x+self.last_stitch.y*1j
closest = sorted([i for i in range(len(points))], key=lambda dist: abs(points[i]-last_stitch))[0]
points = points[closest:]+points[:closest]
for point in points:
to = Stitch(["STITCH"], point.real, point.imag, color=self.stroke_color)
self.stitches.append(to)
def fill_polygon(self, paths):
rotated = 0
fudge_factor = 0.03
while len(paths) > 2:
if len(paths) < 4:
self.fill_triangle(paths, color="red")
return
shapes = [[Path(*paths), "none", "blue"], [Path(*paths), "none", "green"]]
write_debug("close", shapes)
paths = remove_close_paths(paths)
if len(paths) <= 2:
return
# check whether the next triangle is concave
test_line1 = Line(start=paths[0].start, end=paths[1].end)
test_line1 = Line(start=test_line1.point(fudge_factor),
end=test_line1.point(1 - fudge_factor))
comparison_path = Path(*paths)
if test_line1.length() == 0:
has_intersection = True
else:
has_intersection = len(
[1 for line in paths if len(line.intersect(test_line1)) > 0]) > 0
if not path1_is_contained_in_path2(test_line1,
comparison_path) or has_intersection:
shapes = [[comparison_path, "none", "blue"],
[test_line1, "none", "black"]]
write_debug("anim", shapes)
# rotate the paths
paths = paths[1:] + [paths[0]]
rotated += 1
if rotated >= len(paths):
print("failed to rotate into a concave path -> ",
(test_line1.start.real, test_line1.start.imag),
(test_line1.end.real, test_line1.end.imag),
[(p.start.real, p.start.imag) for p in paths])
return
continue
side = shorter_side(paths)
test_line2 = Line(start=paths[1].start, end=paths[2].end)
test_line2 = Line(start=test_line2.point(fudge_factor),
end=test_line2.point(1 - fudge_factor))
test_line3 = Line(start=paths[-1 + side].end,
end=paths[(3 + side) % len(paths)].start)
test_line3 = Line(start=test_line3.point(fudge_factor),
end=test_line3.point(1 - fudge_factor))
num_intersections = []
for path in comparison_path:
if test_line3.length() == 0:
print("test line 3 is degenerate!")
num_intersections += test_line3.intersect(path)
num_intersections += test_line2.intersect(path)
rect_not_concave = not path1_is_contained_in_path2(test_line2,
comparison_path)
# test for concavity. If concave, fill as triangle
if is_concave(paths) or len(num_intersections) > 0 or rect_not_concave:
self.fill_triangle(paths, color="blue")
shapes = [[Path(*paths), "none", "black"]]
to_remove = []
to_remove.append(paths.pop(0))
to_remove.append(paths.pop(0))
for shape in to_remove:
shapes.append([shape, "none", "blue"])
closing_line = Line(start=paths[-1].end, end=paths[0].start)
shapes.append([closing_line, "none", "green"])
shapes.append([test_line1, "none", "red"])
write_debug("rem", shapes)
else:
# check whether the next triangle is concave
side, side2 = self.fill_trap(paths)
if side:
paths = paths[1:] + [paths[0]]
shapes = [[Path(*paths), "none", "black"]]
to_remove = []
to_remove.append(paths.pop(0))
to_remove.append(paths.pop(0))
to_remove.append(paths.pop(0))
# if the trap was stitched in the vertical (perpendicular to the
# stitches), don't remove that segment
linecolors = ["blue", "purple", "pink"]
for i, shape in enumerate(to_remove):
shapes.append([shape, "none", linecolors[i]])
closing_line = Line(start=paths[-1].end, end=paths[0].start)
shapes.append([closing_line, "none", "green"])
shapes.append([test_line2, "none", "purple"])
write_debug("rem", shapes)
delta = closing_line.length() - (
test_line3.length() / (1.0 - 2.0 * fudge_factor))
if abs(delta) > 1e-14:
print("closing line different than test!", side, test_line3,
closing_line)
rotated = 0
if paths[-1].end != paths[0].start:
# check for intersections
closing_line = Line(start=paths[-1].end, end=paths[0].start)
paths.insert(0, closing_line)
else:
print("removed paths but they connected anyway")
def fill_shape(self, side1, side2, paths, shapes):
if paths[side1].length() == 0:
return
increment = 3 * MINIMUM_STITCH_LENGTH / paths[side1].length()
current_t = 0
# make closed shape
filled_paths = [paths[side1], paths[side2]]
if filled_paths[0].end != filled_paths[1].start:
filled_paths.insert(1, Line(start=filled_paths[0].end,
end=filled_paths[1].start))
if filled_paths[0].start != filled_paths[-1].end:
filled_paths.append(Line(start=filled_paths[-1].end,
end=filled_paths[0].start))
while current_t < 1.0 - increment * 0.5:
point1 = paths[side1].point(current_t)
point2 = paths[side2].point(1 - (current_t + 0.5 * increment))
point3 = paths[side1].point(current_t + increment)
to = Stitch(["STITCH"], point1.real * self.scale,
point1.imag * self.scale,
color=self.fill_color)
self.stitches.append(to)
to = Stitch(["STITCH"], point2.real * self.scale,
point2.imag * self.scale,
color=self.fill_color)
self.stitches.append(to)
current_t += increment
to = Stitch(["STITCH"], point3.real * self.scale,
point3.imag * self.scale,
color=self.fill_color)
self.stitches.append(to)
shapes.append([paths[side1], "none", "orange"])
shapes.append([paths[side2], "none", "red"])
return shapes
def fill_grid(self, paths):
grid = Grid(paths)
draw_fill(grid, paths)
# need to find the next location to stitch to. It needs to zig-zag, so we need to
# keep a record of what direction it was going in
going_east = True
rounds = 1
num_empty = grid.count_empty()
while num_empty > 0:
curr_pos = grid.find_upper_corner()
to = Stitch(["STITCH"], curr_pos.real * self.scale,
curr_pos.imag * self.scale,
color=self.fill_color)
self.stitches.append(to)
blocks_covered = int(MAXIMUM_STITCH / MINIMUM_STITCH_LENGTH)
while grid.grid_available(curr_pos):
for i in range(0, blocks_covered):
sign = 1.0 if going_east else -1.0
test_pos = curr_pos + sign * i * MINIMUM_STITCH_LENGTH
if not grid.grid_available(test_pos):
break
else:
next_pos = test_pos + 1j * MINIMUM_STITCH_LENGTH
going_east = not going_east
to = Stitch(["STITCH"], next_pos.real * self.scale,
next_pos.imag * self.scale,
color=self.fill_color)
self.stitches.append(to)
curr_pos = next_pos
draw_fill(grid, paths)
new_num_empty = grid.count_empty()
if new_num_empty == num_empty:
print("fill was not able to fill any parts of the grid!")
break
else:
num_empty = new_num_empty
rounds += 1
def fill_scan(self, paths):
lines = scan_lines(paths)
self.attributes = [{"stroke": self.fill_color} for i in range(len(lines))]
lines, self.attributes = sort_paths(lines, self.attributes)
if isinstance(lines, list):
if len(lines) == 0:
return
start_point = lines[0].start
else:
start_point = lines.start
to = Stitch(["STITCH"], start_point.real * self.scale,
start_point.imag * self.scale, color=self.fill_color)
self.stitches.append(to)
for line in lines:
to = Stitch(["STITCH"], line.start.real * self.scale,
line.start.imag * self.scale, color=self.fill_color)
self.stitches.append(to)
to = Stitch(["STITCH"], line.end.real * self.scale,
line.end.imag * self.scale, color=self.fill_color)
self.stitches.append(to)
def cross_stitch_to_pattern(self, _image):
# this doesn't work well for images with more than 2-3 colors
max_dimension = max(_image.size)
pixel_ratio = int(max_dimension*MINIMUM_STITCH_LENGTH/(4*25.4))
if pixel_ratio != 0:
_image = _image.resize((_image.size[0]/pixel_ratio, _image.size[1]/pixel_ratio))
pixels = posturize(_image)
paths = []
attrs = []
for color in pixels:
for pixel in pixels[color]:
rgb = "#%02x%02x%02x" % (pixel[2][0], pixel[2][1], pixel[2][2])
x = pixel[0]
y = pixel[1]
attrs.append({"fill": "none", "stroke": rgb})
paths.append(Path(Line(start=x + 1j * y,
end=x + 0.5 * MINIMUM_STITCH_LENGTH + 1j * (y + MINIMUM_STITCH_LENGTH))))
debug_paths = [[path, attrs[i]["fill"], attrs[i]["stroke"]] for i, path in enumerate(paths)]
write_debug("png", debug_paths)
self.all_paths = paths
self.attributes = attrs
self.scale = 1.0
self.generate_pattern()
def fill_voronoi(self, paths):
points = []
for path in paths:
num_stitches = 100.0 * path.length() / MAXIMUM_STITCH
ppoints = [path.point(i / num_stitches) for i in range(int(num_stitches))]
for ppoint in ppoints:
points.append([ppoint.real, ppoint.imag])
points.append([path.end.real, path.end.imag])
vor = Voronoi(points)
vertices = vor.vertices
pxs = [x[0] for x in points]
pys = [-x[1] for x in points]
if PLOTTING:
plt.plot(pxs, pys)
# restrict the points to ones within the shape
vertices = [x for i, x in enumerate(vertices)
if path1_is_contained_in_path2(Line(end=x[0] + x[1] * 1j,
start=x[0] + 0.01 + x[
1] * 1j),
Path(*paths))]
# now sort the vertices. This is close but not quite what is being done in
# sort_paths
new_vertices = []
start_location = points[0]
while len(vertices) > 0:
vertices = sorted(vertices,
key=lambda x: (start_location[0] - x[0]) ** 2
+ (start_location[1] - x[1]) ** 2)
new_vertices.append(vertices.pop(0))
start_location = new_vertices[-1]
vertices = new_vertices
# now smooth out the vertices
vertices = [[[x[0] for x in vertices[i:i + 3]],
[x[1] for x in vertices[i:i + 3]]]
for i in range(0, len(vertices) - 3)]
vertices = [[average(x[0]), average(x[1])] for x in vertices]
# we want each vertice to be about equidistant
vertices = make_equidistant(vertices, MINIMUM_STITCH_LENGTH / 2.0)
xs = [x[0] for x in vertices]
ys = [-x[1] for x in vertices]
if PLOTTING:
plt.plot(xs, ys, 'r-')
stitchx = [vertices[0][0]]
stitchy = [vertices[0][1]]
# make spines
for i in range(len(vertices) - 1):
intersections = perpendicular(vertices[i][0] + vertices[i][1] * 1j,
vertices[i + 1][0] + vertices[i + 1][
1] * 1j,
Path(*paths))
diff = abs(intersections[0] - intersections[1])
if diff > 9:
continue
stitchx.append(intersections[0].real)
stitchy.append(-intersections[0].imag)
stitchx.append(intersections[1].real)
stitchy.append(-intersections[1].imag)
for i in range(len(stitchx)):
to = Stitch(["STITCH"], stitchx[i] * self.scale,
-stitchy[i] * self.scale, color=self.fill_color)
self.stitches.append(to)
if PLOTTING:
plt.plot(stitchx, stitchy, 'g-')
plt.xlim(min(pxs), max(pxs))
plt.ylim(min(pys), max(pys))
# plt.show()
def fill_trap(self, paths, color="gray"):
side = shorter_side(paths)
shapes = [[Path(*paths), "none", "black"],
[Path(*paths[side:side + 3]), color, "none"]]
side2 = side + 2
shapes = self.fill_shape(side, side2, paths, shapes)
write_debug("fill", shapes)
return side, side2
def fill_triangle(self, paths, color="green"):
triangle_sides = [paths[0], paths[1],
Line(start=paths[2].start, end=paths[0].start)]
shapes = [[Path(*paths), "none", "black"],
[Path(*triangle_sides), color, "none"]]
lengths = [p.length() for p in triangle_sides]
side1 = argmax(lengths)
lengths[side1] = 0
side2 = argmax(lengths)
shapes = self.fill_shape(side1, side2, triangle_sides, shapes)
write_debug("fill", shapes)
if __name__ == "__main__":
start = time()
args = parser.parse_args()
filename = args.filename
dig = Digitizer(filename=filename, fill=args.fill)
end = time()
filename += ".fill" if args.fill else ""
print("digitizer time: %s" % (end - start))
# remove previous density files
try:
measure_density(dig.pattern)
except ValueError as e:
pass
pattern = remove_short(dig.pattern)
pattern = de_densify(pattern)
measure_density(pattern)
shorten_jumps(dig.pattern)
pattern_to_csv(pattern, join(OUTPUT_DIRECTORY, filename + ".csv"))
pattern_to_svg(pattern, join(OUTPUT_DIRECTORY, filename + ".svg"))
pes_filename = join(OUTPUT_DIRECTORY, filename + ".pes")
bef = BrotherEmbroideryFile(pes_filename)
bef.write_pattern(pattern)
upload(pes_filename) | [
"brother.upload",
"pattern.Pattern",
"svgutils.posturize",
"pattern_utils.remove_short",
"stitch.Stitch",
"svgutils.make_equidistant",
"pattern_utils.shorten_jumps",
"svgutils.write_debug",
"pattern_utils.de_densify",
"svgpathtools.Line",
"argparse.ArgumentParser",
"svgwrite.rgb",
"matplotli... | [((1476, 1592), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Generate a pes file for brother sewing machines from an svg or png image"""'}), "(description=\n 'Generate a pes file for brother sewing machines from an svg or png image')\n", (1499, 1592), False, 'import argparse\n'), ((25467, 25473), 'time.time', 'time', ([], {}), '()\n', (25471, 25473), False, 'from time import time\n'), ((25599, 25605), 'time.time', 'time', ([], {}), '()\n', (25603, 25605), False, 'from time import time\n'), ((25836, 25861), 'pattern_utils.remove_short', 'remove_short', (['dig.pattern'], {}), '(dig.pattern)\n', (25848, 25861), False, 'from pattern_utils import de_densify, measure_density, pattern_to_svg, shorten_jumps, remove_short\n'), ((25876, 25895), 'pattern_utils.de_densify', 'de_densify', (['pattern'], {}), '(pattern)\n', (25886, 25895), False, 'from pattern_utils import de_densify, measure_density, pattern_to_svg, shorten_jumps, remove_short\n'), ((25900, 25924), 'pattern_utils.measure_density', 'measure_density', (['pattern'], {}), '(pattern)\n', (25915, 25924), False, 'from pattern_utils import de_densify, measure_density, pattern_to_svg, shorten_jumps, remove_short\n'), ((25929, 25955), 'pattern_utils.shorten_jumps', 'shorten_jumps', (['dig.pattern'], {}), '(dig.pattern)\n', (25942, 25955), False, 'from pattern_utils import de_densify, measure_density, pattern_to_svg, shorten_jumps, remove_short\n'), ((26117, 26158), 'os.path.join', 'join', (['OUTPUT_DIRECTORY', "(filename + '.pes')"], {}), "(OUTPUT_DIRECTORY, filename + '.pes')\n", (26121, 26158), False, 'from os.path import join\n'), ((26169, 26204), 'brother.BrotherEmbroideryFile', 'BrotherEmbroideryFile', (['pes_filename'], {}), '(pes_filename)\n', (26190, 26204), False, 'from brother import BrotherEmbroideryFile, pattern_to_csv, upload\n'), ((26240, 26260), 'brother.upload', 'upload', (['pes_filename'], {}), '(pes_filename)\n', (26246, 26260), False, 'from brother import BrotherEmbroideryFile, pattern_to_csv, upload\n'), ((2186, 2195), 'pattern.Pattern', 'Pattern', ([], {}), '()\n', (2193, 2195), False, 'from pattern import Pattern\n'), ((2673, 2703), 'xml.dom.minidom.parseString', 'parseString', (['self.filecontents'], {}), '(self.filecontents)\n', (2684, 2703), False, 'from xml.dom.minidom import parseString\n'), ((9337, 9356), 'svgutils.overall_bbox', 'overall_bbox', (['paths'], {}), '(paths)\n', (9349, 9356), False, 'from svgutils import scan_lines, stack_paths, trace_image, sort_paths, overall_bbox, get_color, get_stroke_width, make_continuous, write_debug, remove_close_paths, path1_is_contained_in_path2, shorter_side, is_concave, draw_fill, posturize, make_equidistant, perpendicular, split_subpaths, get_pixel_from_string\n'), ((17656, 17667), 'grid.Grid', 'Grid', (['paths'], {}), '(paths)\n', (17660, 17667), False, 'from grid import Grid\n'), ((17677, 17699), 'svgutils.draw_fill', 'draw_fill', (['grid', 'paths'], {}), '(grid, paths)\n', (17686, 17699), False, 'from svgutils import scan_lines, stack_paths, trace_image, sort_paths, overall_bbox, get_color, get_stroke_width, make_continuous, write_debug, remove_close_paths, path1_is_contained_in_path2, shorter_side, is_concave, draw_fill, posturize, make_equidistant, perpendicular, split_subpaths, get_pixel_from_string\n'), ((19350, 19367), 'svgutils.scan_lines', 'scan_lines', (['paths'], {}), '(paths)\n', (19360, 19367), False, 'from svgutils import scan_lines, stack_paths, trace_image, sort_paths, overall_bbox, get_color, get_stroke_width, make_continuous, write_debug, remove_close_paths, path1_is_contained_in_path2, shorter_side, is_concave, draw_fill, posturize, make_equidistant, perpendicular, split_subpaths, get_pixel_from_string\n'), ((19484, 19518), 'svgutils.sort_paths', 'sort_paths', (['lines', 'self.attributes'], {}), '(lines, self.attributes)\n', (19494, 19518), False, 'from svgutils import scan_lines, stack_paths, trace_image, sort_paths, overall_bbox, get_color, get_stroke_width, make_continuous, write_debug, remove_close_paths, path1_is_contained_in_path2, shorter_side, is_concave, draw_fill, posturize, make_equidistant, perpendicular, split_subpaths, get_pixel_from_string\n'), ((19716, 19824), 'stitch.Stitch', 'Stitch', (["['STITCH']", '(start_point.real * self.scale)', '(start_point.imag * self.scale)'], {'color': 'self.fill_color'}), "(['STITCH'], start_point.real * self.scale, start_point.imag * self.\n scale, color=self.fill_color)\n", (19722, 19824), False, 'from stitch import Stitch\n'), ((20627, 20644), 'svgutils.posturize', 'posturize', (['_image'], {}), '(_image)\n', (20636, 20644), False, 'from svgutils import scan_lines, stack_paths, trace_image, sort_paths, overall_bbox, get_color, get_stroke_width, make_continuous, write_debug, remove_close_paths, path1_is_contained_in_path2, shorter_side, is_concave, draw_fill, posturize, make_equidistant, perpendicular, split_subpaths, get_pixel_from_string\n'), ((21233, 21264), 'svgutils.write_debug', 'write_debug', (['"""png"""', 'debug_paths'], {}), "('png', debug_paths)\n", (21244, 21264), False, 'from svgutils import scan_lines, stack_paths, trace_image, sort_paths, overall_bbox, get_color, get_stroke_width, make_continuous, write_debug, remove_close_paths, path1_is_contained_in_path2, shorter_side, is_concave, draw_fill, posturize, make_equidistant, perpendicular, split_subpaths, get_pixel_from_string\n'), ((21786, 21801), 'scipy.spatial.qhull.Voronoi', 'Voronoi', (['points'], {}), '(points)\n', (21793, 21801), False, 'from scipy.spatial.qhull import Voronoi\n'), ((23256, 23311), 'svgutils.make_equidistant', 'make_equidistant', (['vertices', '(MINIMUM_STITCH_LENGTH / 2.0)'], {}), '(vertices, MINIMUM_STITCH_LENGTH / 2.0)\n', (23272, 23311), False, 'from svgutils import scan_lines, stack_paths, trace_image, sort_paths, overall_bbox, get_color, get_stroke_width, make_continuous, write_debug, remove_close_paths, path1_is_contained_in_path2, shorter_side, is_concave, draw_fill, posturize, make_equidistant, perpendicular, split_subpaths, get_pixel_from_string\n'), ((24608, 24627), 'svgutils.shorter_side', 'shorter_side', (['paths'], {}), '(paths)\n', (24620, 24627), False, 'from svgutils import scan_lines, stack_paths, trace_image, sort_paths, overall_bbox, get_color, get_stroke_width, make_continuous, write_debug, remove_close_paths, path1_is_contained_in_path2, shorter_side, is_concave, draw_fill, posturize, make_equidistant, perpendicular, split_subpaths, get_pixel_from_string\n'), ((24837, 24864), 'svgutils.write_debug', 'write_debug', (['"""fill"""', 'shapes'], {}), "('fill', shapes)\n", (24848, 24864), False, 'from svgutils import scan_lines, stack_paths, trace_image, sort_paths, overall_bbox, get_color, get_stroke_width, make_continuous, write_debug, remove_close_paths, path1_is_contained_in_path2, shorter_side, is_concave, draw_fill, posturize, make_equidistant, perpendicular, split_subpaths, get_pixel_from_string\n'), ((25244, 25259), 'numpy.argmax', 'argmax', (['lengths'], {}), '(lengths)\n', (25250, 25259), False, 'from numpy import argmax, average, ceil\n'), ((25303, 25318), 'numpy.argmax', 'argmax', (['lengths'], {}), '(lengths)\n', (25309, 25318), False, 'from numpy import argmax, average, ceil\n'), ((25398, 25425), 'svgutils.write_debug', 'write_debug', (['"""fill"""', 'shapes'], {}), "('fill', shapes)\n", (25409, 25425), False, 'from svgutils import scan_lines, stack_paths, trace_image, sort_paths, overall_bbox, get_color, get_stroke_width, make_continuous, write_debug, remove_close_paths, path1_is_contained_in_path2, shorter_side, is_concave, draw_fill, posturize, make_equidistant, perpendicular, split_subpaths, get_pixel_from_string\n'), ((25752, 25780), 'pattern_utils.measure_density', 'measure_density', (['dig.pattern'], {}), '(dig.pattern)\n', (25767, 25780), False, 'from pattern_utils import de_densify, measure_density, pattern_to_svg, shorten_jumps, remove_short\n'), ((25984, 26025), 'os.path.join', 'join', (['OUTPUT_DIRECTORY', "(filename + '.csv')"], {}), "(OUTPUT_DIRECTORY, filename + '.csv')\n", (25988, 26025), False, 'from os.path import join\n'), ((26055, 26096), 'os.path.join', 'join', (['OUTPUT_DIRECTORY', "(filename + '.svg')"], {}), "(OUTPUT_DIRECTORY, filename + '.svg')\n", (26059, 26096), False, 'from os.path import join\n'), ((3159, 3187), 'svgutils.overall_bbox', 'overall_bbox', (['self.all_paths'], {}), '(self.all_paths)\n', (3171, 3187), False, 'from svgutils import scan_lines, stack_paths, trace_image, sort_paths, overall_bbox, get_color, get_stroke_width, make_continuous, write_debug, remove_close_paths, path1_is_contained_in_path2, shorter_side, is_concave, draw_fill, posturize, make_equidistant, perpendicular, split_subpaths, get_pixel_from_string\n'), ((3497, 3525), 'svgutils.sort_paths', 'sort_paths', (['*path_attributes'], {}), '(*path_attributes)\n', (3507, 3525), False, 'from svgutils import scan_lines, stack_paths, trace_image, sort_paths, overall_bbox, get_color, get_stroke_width, make_continuous, write_debug, remove_close_paths, path1_is_contained_in_path2, shorter_side, is_concave, draw_fill, posturize, make_equidistant, perpendicular, split_subpaths, get_pixel_from_string\n'), ((3588, 3634), 'svgutils.get_pixel_from_string', 'get_pixel_from_string', (['root_width.value', 'width'], {}), '(root_width.value, width)\n', (3609, 3634), False, 'from svgutils import scan_lines, stack_paths, trace_image, sort_paths, overall_bbox, get_color, get_stroke_width, make_continuous, write_debug, remove_close_paths, path1_is_contained_in_path2, shorter_side, is_concave, draw_fill, posturize, make_equidistant, perpendicular, split_subpaths, get_pixel_from_string\n'), ((4156, 4208), 'block.Block', 'Block', ([], {'stitches': 'self.stitches', 'color': 'self.last_color'}), '(stitches=self.stitches, color=self.last_color)\n', (4161, 4208), False, 'from block import Block\n'), ((4570, 4614), 'svgutils.stack_paths', 'stack_paths', (['self.all_paths', 'self.attributes'], {}), '(self.all_paths, self.attributes)\n', (4581, 4614), False, 'from svgutils import scan_lines, stack_paths, trace_image, sort_paths, overall_bbox, get_color, get_stroke_width, make_continuous, write_debug, remove_close_paths, path1_is_contained_in_path2, shorter_side, is_concave, draw_fill, posturize, make_equidistant, perpendicular, split_subpaths, get_pixel_from_string\n'), ((4919, 4939), 'svgutils.get_color', 'get_color', (['v', '"""fill"""'], {}), "(v, 'fill')\n", (4928, 4939), False, 'from svgutils import scan_lines, stack_paths, trace_image, sort_paths, overall_bbox, get_color, get_stroke_width, make_continuous, write_debug, remove_close_paths, path1_is_contained_in_path2, shorter_side, is_concave, draw_fill, posturize, make_equidistant, perpendicular, split_subpaths, get_pixel_from_string\n'), ((4972, 4994), 'svgutils.get_color', 'get_color', (['v', '"""stroke"""'], {}), "(v, 'stroke')\n", (4981, 4994), False, 'from svgutils import scan_lines, stack_paths, trace_image, sort_paths, overall_bbox, get_color, get_stroke_width, make_continuous, write_debug, remove_close_paths, path1_is_contained_in_path2, shorter_side, is_concave, draw_fill, posturize, make_equidistant, perpendicular, split_subpaths, get_pixel_from_string\n'), ((5022, 5053), 'svgutils.get_stroke_width', 'get_stroke_width', (['v', 'self.scale'], {}), '(v, self.scale)\n', (5038, 5053), False, 'from svgutils import scan_lines, stack_paths, trace_image, sort_paths, overall_bbox, get_color, get_stroke_width, make_continuous, write_debug, remove_close_paths, path1_is_contained_in_path2, shorter_side, is_concave, draw_fill, posturize, make_equidistant, perpendicular, split_subpaths, get_pixel_from_string\n'), ((10756, 10823), 'stitch.Stitch', 'Stitch', (["['STITCH']", 'point.real', 'point.imag'], {'color': 'self.stroke_color'}), "(['STITCH'], point.real, point.imag, color=self.stroke_color)\n", (10762, 10823), False, 'from stitch import Stitch\n'), ((11183, 11211), 'svgutils.write_debug', 'write_debug', (['"""close"""', 'shapes'], {}), "('close', shapes)\n", (11194, 11211), False, 'from svgutils import scan_lines, stack_paths, trace_image, sort_paths, overall_bbox, get_color, get_stroke_width, make_continuous, write_debug, remove_close_paths, path1_is_contained_in_path2, shorter_side, is_concave, draw_fill, posturize, make_equidistant, perpendicular, split_subpaths, get_pixel_from_string\n'), ((11232, 11257), 'svgutils.remove_close_paths', 'remove_close_paths', (['paths'], {}), '(paths)\n', (11250, 11257), False, 'from svgutils import scan_lines, stack_paths, trace_image, sort_paths, overall_bbox, get_color, get_stroke_width, make_continuous, write_debug, remove_close_paths, path1_is_contained_in_path2, shorter_side, is_concave, draw_fill, posturize, make_equidistant, perpendicular, split_subpaths, get_pixel_from_string\n'), ((11396, 11440), 'svgpathtools.Line', 'Line', ([], {'start': 'paths[0].start', 'end': 'paths[1].end'}), '(start=paths[0].start, end=paths[1].end)\n', (11400, 11440), False, 'from svgpathtools import svgdoc2paths, Line, Path\n'), ((11609, 11621), 'svgpathtools.Path', 'Path', (['*paths'], {}), '(*paths)\n', (11613, 11621), False, 'from svgpathtools import svgdoc2paths, Line, Path\n'), ((12665, 12684), 'svgutils.shorter_side', 'shorter_side', (['paths'], {}), '(paths)\n', (12677, 12684), False, 'from svgutils import scan_lines, stack_paths, trace_image, sort_paths, overall_bbox, get_color, get_stroke_width, make_continuous, write_debug, remove_close_paths, path1_is_contained_in_path2, shorter_side, is_concave, draw_fill, posturize, make_equidistant, perpendicular, split_subpaths, get_pixel_from_string\n'), ((12711, 12755), 'svgpathtools.Line', 'Line', ([], {'start': 'paths[1].start', 'end': 'paths[2].end'}), '(start=paths[1].start, end=paths[2].end)\n', (12715, 12755), False, 'from svgpathtools import svgdoc2paths, Line, Path\n'), ((16871, 16968), 'stitch.Stitch', 'Stitch', (["['STITCH']", '(point1.real * self.scale)', '(point1.imag * self.scale)'], {'color': 'self.fill_color'}), "(['STITCH'], point1.real * self.scale, point1.imag * self.scale,\n color=self.fill_color)\n", (16877, 16968), False, 'from stitch import Stitch\n'), ((17067, 17164), 'stitch.Stitch', 'Stitch', (["['STITCH']", '(point2.real * self.scale)', '(point2.imag * self.scale)'], {'color': 'self.fill_color'}), "(['STITCH'], point2.real * self.scale, point2.imag * self.scale,\n color=self.fill_color)\n", (17073, 17164), False, 'from stitch import Stitch\n'), ((17298, 17395), 'stitch.Stitch', 'Stitch', (["['STITCH']", '(point3.real * self.scale)', '(point3.imag * self.scale)'], {'color': 'self.fill_color'}), "(['STITCH'], point3.real * self.scale, point3.imag * self.scale,\n color=self.fill_color)\n", (17304, 17395), False, 'from stitch import Stitch\n'), ((18027, 18128), 'stitch.Stitch', 'Stitch', (["['STITCH']", '(curr_pos.real * self.scale)', '(curr_pos.imag * self.scale)'], {'color': 'self.fill_color'}), "(['STITCH'], curr_pos.real * self.scale, curr_pos.imag * self.scale,\n color=self.fill_color)\n", (18033, 18128), False, 'from stitch import Stitch\n'), ((19008, 19030), 'svgutils.draw_fill', 'draw_fill', (['grid', 'paths'], {}), '(grid, paths)\n', (19017, 19030), False, 'from svgutils import scan_lines, stack_paths, trace_image, sort_paths, overall_bbox, get_color, get_stroke_width, make_continuous, write_debug, remove_close_paths, path1_is_contained_in_path2, shorter_side, is_concave, draw_fill, posturize, make_equidistant, perpendicular, split_subpaths, get_pixel_from_string\n'), ((19918, 20024), 'stitch.Stitch', 'Stitch', (["['STITCH']", '(line.start.real * self.scale)', '(line.start.imag * self.scale)'], {'color': 'self.fill_color'}), "(['STITCH'], line.start.real * self.scale, line.start.imag * self.\n scale, color=self.fill_color)\n", (19924, 20024), False, 'from stitch import Stitch\n'), ((20098, 20199), 'stitch.Stitch', 'Stitch', (["['STITCH']", '(line.end.real * self.scale)', '(line.end.imag * self.scale)'], {'color': 'self.fill_color'}), "(['STITCH'], line.end.real * self.scale, line.end.imag * self.scale,\n color=self.fill_color)\n", (20104, 20199), False, 'from stitch import Stitch\n'), ((21943, 21961), 'matplotlib.pyplot.plot', 'plt.plot', (['pxs', 'pys'], {}), '(pxs, pys)\n', (21951, 21961), True, 'import matplotlib.pyplot as plt\n'), ((23422, 23444), 'matplotlib.pyplot.plot', 'plt.plot', (['xs', 'ys', '"""r-"""'], {}), "(xs, ys, 'r-')\n", (23430, 23444), True, 'import matplotlib.pyplot as plt\n'), ((24219, 24316), 'stitch.Stitch', 'Stitch', (["['STITCH']", '(stitchx[i] * self.scale)', '(-stitchy[i] * self.scale)'], {'color': 'self.fill_color'}), "(['STITCH'], stitchx[i] * self.scale, -stitchy[i] * self.scale, color\n =self.fill_color)\n", (24225, 24316), False, 'from stitch import Stitch\n'), ((24406, 24438), 'matplotlib.pyplot.plot', 'plt.plot', (['stitchx', 'stitchy', '"""g-"""'], {}), "(stitchx, stitchy, 'g-')\n", (24414, 24438), True, 'import matplotlib.pyplot as plt\n'), ((25016, 25062), 'svgpathtools.Line', 'Line', ([], {'start': 'paths[2].start', 'end': 'paths[0].start'}), '(start=paths[2].start, end=paths[0].start)\n', (25020, 25062), False, 'from svgpathtools import svgdoc2paths, Line, Path\n'), ((2532, 2562), 'svgutils.trace_image', 'trace_image', (['self.filecontents'], {}), '(self.filecontents)\n', (2543, 2562), False, 'from svgutils import scan_lines, stack_paths, trace_image, sort_paths, overall_bbox, get_color, get_stroke_width, make_continuous, write_debug, remove_close_paths, path1_is_contained_in_path2, shorter_side, is_concave, draw_fill, posturize, make_equidistant, perpendicular, split_subpaths, get_pixel_from_string\n'), ((3307, 3324), 'svgpathtools.svgdoc2paths', 'svgdoc2paths', (['doc'], {}), '(doc)\n', (3319, 3324), False, 'from svgpathtools import svgdoc2paths, Line, Path\n'), ((12126, 12153), 'svgutils.write_debug', 'write_debug', (['"""anim"""', 'shapes'], {}), "('anim', shapes)\n", (12137, 12153), False, 'from svgutils import scan_lines, stack_paths, trace_image, sort_paths, overall_bbox, get_color, get_stroke_width, make_continuous, write_debug, remove_close_paths, path1_is_contained_in_path2, shorter_side, is_concave, draw_fill, posturize, make_equidistant, perpendicular, split_subpaths, get_pixel_from_string\n'), ((13504, 13560), 'svgutils.path1_is_contained_in_path2', 'path1_is_contained_in_path2', (['test_line2', 'comparison_path'], {}), '(test_line2, comparison_path)\n', (13531, 13560), False, 'from svgutils import scan_lines, stack_paths, trace_image, sort_paths, overall_bbox, get_color, get_stroke_width, make_continuous, write_debug, remove_close_paths, path1_is_contained_in_path2, shorter_side, is_concave, draw_fill, posturize, make_equidistant, perpendicular, split_subpaths, get_pixel_from_string\n'), ((13703, 13720), 'svgutils.is_concave', 'is_concave', (['paths'], {}), '(paths)\n', (13713, 13720), False, 'from svgutils import scan_lines, stack_paths, trace_image, sort_paths, overall_bbox, get_color, get_stroke_width, make_continuous, write_debug, remove_close_paths, path1_is_contained_in_path2, shorter_side, is_concave, draw_fill, posturize, make_equidistant, perpendicular, split_subpaths, get_pixel_from_string\n'), ((14142, 14187), 'svgpathtools.Line', 'Line', ([], {'start': 'paths[-1].end', 'end': 'paths[0].start'}), '(start=paths[-1].end, end=paths[0].start)\n', (14146, 14187), False, 'from svgpathtools import svgdoc2paths, Line, Path\n'), ((14326, 14352), 'svgutils.write_debug', 'write_debug', (['"""rem"""', 'shapes'], {}), "('rem', shapes)\n", (14337, 14352), False, 'from svgutils import scan_lines, stack_paths, trace_image, sort_paths, overall_bbox, get_color, get_stroke_width, make_continuous, write_debug, remove_close_paths, path1_is_contained_in_path2, shorter_side, is_concave, draw_fill, posturize, make_equidistant, perpendicular, split_subpaths, get_pixel_from_string\n'), ((15135, 15180), 'svgpathtools.Line', 'Line', ([], {'start': 'paths[-1].end', 'end': 'paths[0].start'}), '(start=paths[-1].end, end=paths[0].start)\n', (15139, 15180), False, 'from svgpathtools import svgdoc2paths, Line, Path\n'), ((15322, 15348), 'svgutils.write_debug', 'write_debug', (['"""rem"""', 'shapes'], {}), "('rem', shapes)\n", (15333, 15348), False, 'from svgutils import scan_lines, stack_paths, trace_image, sort_paths, overall_bbox, get_color, get_stroke_width, make_continuous, write_debug, remove_close_paths, path1_is_contained_in_path2, shorter_side, is_concave, draw_fill, posturize, make_equidistant, perpendicular, split_subpaths, get_pixel_from_string\n'), ((15774, 15819), 'svgpathtools.Line', 'Line', ([], {'start': 'paths[-1].end', 'end': 'paths[0].start'}), '(start=paths[-1].end, end=paths[0].start)\n', (15778, 15819), False, 'from svgpathtools import svgdoc2paths, Line, Path\n'), ((16328, 16386), 'svgpathtools.Line', 'Line', ([], {'start': 'filled_paths[0].end', 'end': 'filled_paths[1].start'}), '(start=filled_paths[0].end, end=filled_paths[1].start)\n', (16332, 16386), False, 'from svgpathtools import svgdoc2paths, Line, Path\n'), ((16518, 16577), 'svgpathtools.Line', 'Line', ([], {'start': 'filled_paths[-1].end', 'end': 'filled_paths[0].start'}), '(start=filled_paths[-1].end, end=filled_paths[0].start)\n', (16522, 16577), False, 'from svgpathtools import svgdoc2paths, Line, Path\n'), ((18765, 18866), 'stitch.Stitch', 'Stitch', (["['STITCH']", '(next_pos.real * self.scale)', '(next_pos.imag * self.scale)'], {'color': 'self.fill_color'}), "(['STITCH'], next_pos.real * self.scale, next_pos.imag * self.scale,\n color=self.fill_color)\n", (18771, 18866), False, 'from stitch import Stitch\n'), ((23133, 23146), 'numpy.average', 'average', (['x[0]'], {}), '(x[0])\n', (23140, 23146), False, 'from numpy import argmax, average, ceil\n'), ((23148, 23161), 'numpy.average', 'average', (['x[1]'], {}), '(x[1])\n', (23155, 23161), False, 'from numpy import argmax, average, ceil\n'), ((23838, 23850), 'svgpathtools.Path', 'Path', (['*paths'], {}), '(*paths)\n', (23842, 23850), False, 'from svgpathtools import svgdoc2paths, Line, Path\n'), ((24647, 24659), 'svgpathtools.Path', 'Path', (['*paths'], {}), '(*paths)\n', (24651, 24659), False, 'from svgpathtools import svgdoc2paths, Line, Path\n'), ((24698, 24725), 'svgpathtools.Path', 'Path', (['*paths[side:side + 3]'], {}), '(*paths[side:side + 3])\n', (24702, 24725), False, 'from svgpathtools import svgdoc2paths, Line, Path\n'), ((25083, 25095), 'svgpathtools.Path', 'Path', (['*paths'], {}), '(*paths)\n', (25087, 25095), False, 'from svgpathtools import svgdoc2paths, Line, Path\n'), ((25134, 25155), 'svgpathtools.Path', 'Path', (['*triangle_sides'], {}), '(*triangle_sides)\n', (25138, 25155), False, 'from svgpathtools import svgdoc2paths, Line, Path\n'), ((2274, 2301), 'os.path.join', 'join', (['"""workspace"""', 'filename'], {}), "('workspace', filename)\n", (2278, 2301), False, 'from os.path import join\n'), ((3406, 3435), 'svgutils.stack_paths', 'stack_paths', (['*path_attributes'], {}), '(*path_attributes)\n', (3417, 3435), False, 'from svgutils import scan_lines, stack_paths, trace_image, sort_paths, overall_bbox, get_color, get_stroke_width, make_continuous, write_debug, remove_close_paths, path1_is_contained_in_path2, shorter_side, is_concave, draw_fill, posturize, make_equidistant, perpendicular, split_subpaths, get_pixel_from_string\n'), ((5892, 5904), 'svgpathtools.Path', 'Path', (['*paths'], {}), '(*paths)\n', (5896, 5904), False, 'from svgpathtools import svgdoc2paths, Line, Path\n'), ((8925, 8953), 'stitch.Stitch', 'Stitch', (["['TRIM']", 'to.x', 'to.y'], {}), "(['TRIM'], to.x, to.y)\n", (8931, 8953), False, 'from stitch import Stitch\n'), ((9071, 9100), 'stitch.Stitch', 'Stitch', (["['COLOR']", 'to.x', 'to.y'], {}), "(['COLOR'], to.x, to.y)\n", (9077, 9100), False, 'from stitch import Stitch\n'), ((9396, 9408), 'svgpathtools.Path', 'Path', (['*paths'], {}), '(*paths)\n', (9400, 9408), False, 'from svgpathtools import svgdoc2paths, Line, Path\n'), ((11107, 11119), 'svgpathtools.Path', 'Path', (['*paths'], {}), '(*paths)\n', (11111, 11119), False, 'from svgpathtools import svgdoc2paths, Line, Path\n'), ((11139, 11151), 'svgpathtools.Path', 'Path', (['*paths'], {}), '(*paths)\n', (11143, 11151), False, 'from svgpathtools import svgdoc2paths, Line, Path\n'), ((11867, 11923), 'svgutils.path1_is_contained_in_path2', 'path1_is_contained_in_path2', (['test_line1', 'comparison_path'], {}), '(test_line1, comparison_path)\n', (11894, 11923), False, 'from svgutils import scan_lines, stack_paths, trace_image, sort_paths, overall_bbox, get_color, get_stroke_width, make_continuous, write_debug, remove_close_paths, path1_is_contained_in_path2, shorter_side, is_concave, draw_fill, posturize, make_equidistant, perpendicular, split_subpaths, get_pixel_from_string\n'), ((22122, 22183), 'svgpathtools.Line', 'Line', ([], {'end': '(x[0] + x[1] * 1.0j)', 'start': '(x[0] + 0.01 + x[1] * 1.0j)'}), '(end=x[0] + x[1] * 1.0j, start=x[0] + 0.01 + x[1] * 1.0j)\n', (22126, 22183), False, 'from svgpathtools import svgdoc2paths, Line, Path\n'), ((22369, 22381), 'svgpathtools.Path', 'Path', (['*paths'], {}), '(*paths)\n', (22373, 22381), False, 'from svgpathtools import svgdoc2paths, Line, Path\n'), ((8481, 8494), 'numpy.ceil', 'ceil', (['(i / 2.0)'], {}), '(i / 2.0)\n', (8485, 8494), False, 'from numpy import argmax, average, ceil\n'), ((13855, 13867), 'svgpathtools.Path', 'Path', (['*paths'], {}), '(*paths)\n', (13859, 13867), False, 'from svgpathtools import svgdoc2paths, Line, Path\n'), ((14588, 14600), 'svgpathtools.Path', 'Path', (['*paths'], {}), '(*paths)\n', (14592, 14600), False, 'from svgpathtools import svgdoc2paths, Line, Path\n'), ((20988, 21090), 'svgpathtools.Line', 'Line', ([], {'start': '(x + 1.0j * y)', 'end': '(x + 0.5 * MINIMUM_STITCH_LENGTH + 1.0j * (y + MINIMUM_STITCH_LENGTH))'}), '(start=x + 1.0j * y, end=x + 0.5 * MINIMUM_STITCH_LENGTH + 1.0j * (y +\n MINIMUM_STITCH_LENGTH))\n', (20992, 21090), False, 'from svgpathtools import svgdoc2paths, Line, Path\n'), ((6000, 6026), 'svgutils.make_continuous', 'make_continuous', (['full_path'], {}), '(full_path)\n', (6015, 6026), False, 'from svgutils import scan_lines, stack_paths, trace_image, sort_paths, overall_bbox, get_color, get_stroke_width, make_continuous, write_debug, remove_close_paths, path1_is_contained_in_path2, shorter_side, is_concave, draw_fill, posturize, make_equidistant, perpendicular, split_subpaths, get_pixel_from_string\n'), ((6911, 6933), 'stitch.Stitch', 'Stitch', (["['JUMP']", '(0)', '(0)'], {}), "(['JUMP'], 0, 0)\n", (6917, 6933), False, 'from stitch import Stitch\n'), ((7450, 7495), 'stitch.Stitch', 'Stitch', (["['END']", 'last_stitch.x', 'last_stitch.y'], {}), "(['END'], last_stitch.x, last_stitch.y)\n", (7456, 7495), False, 'from stitch import Stitch\n'), ((9513, 9527), 'svgwrite.rgb', 'rgb', (['(255)', '(0)', '(0)'], {}), '(255, 0, 0)\n', (9516, 9527), False, 'from svgwrite import rgb\n'), ((5715, 5737), 'stitch.Stitch', 'Stitch', (["['JUMP']", '(0)', '(0)'], {}), "(['JUMP'], 0, 0)\n", (5721, 5737), False, 'from stitch import Stitch\n')] |
#!/usr/bin/env python3
import argparse
import yaml
import logging
import math
from statistics import median
import numpy as np
import tator
if __name__=="__main__":
parser = argparse.ArgumentParser(description=__doc__)
tator.get_parser(parser)
parser.add_argument("--tracklet-type-id", type=int, required=True)
parser.add_argument("--version-id", type=int)
parser.add_argument("--attribute-name", type=str)
parser.add_argument("--strategy-config", type=str)
parser.add_argument('media_ids', type=int, nargs='+')
args = parser.parse_args()
# Weight methods
methods = ['mean', 'median']
api = tator.get_api(args.host, args.token)
tracklet_type = api.get_state_type(args.tracklet_type_id)
project = tracklet_type.project
version_id = args.version_id
attribute_name = args.attribute_name
default_strategy = {"method": "median",
"dimension": "both",
"scale-factor": 1.0,
"args": {}}
if args.strategy_config:
strategy = {**default_strategy}
with open(args.strategy_config, "r") as strategy_file:
strategy.update(yaml.load(strategy_file))
else:
strategy = default_strategy
dimension = strategy["dimension"]
method = strategy["method"]
transform = strategy["transform"]
medias = api.get_media_list_by_id(project, {'ids': args.media_ids})
medias = {media.id:media for media in medias}
tracks = api.get_state_list_by_id(project, {'media_ids': args.media_ids},
type=tracklet_type.id, version=[version_id])
for track in tracks:
locs = api.get_localization_list_by_id(project, {'ids': track.localizations})
media = medias[track.media[0]]
if dimension == "both":
sizes = [(loc.width * media.width + loc.height * media.height) / 2 for loc in locs]
elif dimension == "width":
sizes = [loc.width * media.width for loc in locs]
elif dimension == "height":
sizes = [loc.height * media.height for loc in locs]
else:
raise ValueError(f"Invalid dimension \'{dimension}\', must be one of "
"\'width\', \'height\', or \'both\'!")
if method == "median":
size = median(sizes)
elif method == "mean":
size = sum(sizes) / len(sizes)
elif method == "center":
centers = [(loc.x + loc.width / 2, loc.y + loc.height / 2) for loc in locs]
dists = [math.sqrt((x - 0.5) * (x - 0.5) + (y - 0.5) * (y - 0.5))
for x, y in centers]
nearest = np.argmin(dists)
size = sizes[nearest]
else:
raise ValueError(f"Invalid method \'{method}\', must be one of "
"\'median\', \'mean\', or \'center\'!")
size *= strategy['scale-factor']
if transform == "scallops":
size = ((0.1/120) * (size - 40) + 0.8) * size
elif transform == "none":
pass
else:
raise ValueError(f"Invalid transform \'{transform}\', must be one of "
"\'scallops\' or \'none\'!")
print(f"Updating track {track.id} with {attribute_name} = {size}...")
response = api.update_state(track.id, {'attributes': {attribute_name: size}})
assert(isinstance(response, tator.models.MessageResponse))
print(response.message)
| [
"argparse.ArgumentParser",
"math.sqrt",
"yaml.load",
"statistics.median",
"tator.get_api",
"numpy.argmin",
"tator.get_parser"
] | [((181, 225), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '__doc__'}), '(description=__doc__)\n', (204, 225), False, 'import argparse\n'), ((230, 254), 'tator.get_parser', 'tator.get_parser', (['parser'], {}), '(parser)\n', (246, 254), False, 'import tator\n'), ((640, 676), 'tator.get_api', 'tator.get_api', (['args.host', 'args.token'], {}), '(args.host, args.token)\n', (653, 676), False, 'import tator\n'), ((2337, 2350), 'statistics.median', 'median', (['sizes'], {}), '(sizes)\n', (2343, 2350), False, 'from statistics import median\n'), ((1182, 1206), 'yaml.load', 'yaml.load', (['strategy_file'], {}), '(strategy_file)\n', (1191, 1206), False, 'import yaml\n'), ((2688, 2704), 'numpy.argmin', 'np.argmin', (['dists'], {}), '(dists)\n', (2697, 2704), True, 'import numpy as np\n'), ((2567, 2623), 'math.sqrt', 'math.sqrt', (['((x - 0.5) * (x - 0.5) + (y - 0.5) * (y - 0.5))'], {}), '((x - 0.5) * (x - 0.5) + (y - 0.5) * (y - 0.5))\n', (2576, 2623), False, 'import math\n')] |
# coding=utf-8
# Copyright (c) Microsoft Corporation. Licensed under the MIT license.
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. 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.
""" Finetuning multi-lingual models on XNLI (Bert, DistilBERT, XLM).
Adapted from `examples/run_glue.py`"""
import argparse
import logging
import os
import random
import numpy as np
import torch
from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset, Dataset
from torch.utils.data.distributed import DistributedSampler
from tqdm import tqdm, trange
from transformers import (
AdamW,
BertConfig,
BertForSequenceClassification,BertForMaskedLM,XLMRobertaForMaskedLM,
BertTokenizer,
XLMConfig, XLMForSequenceClassification, XLMTokenizer,
XLMRobertaConfig, XLMRobertaForSequenceClassification, XLMRobertaTokenizer,
get_linear_schedule_with_warmup,AutoTokenizer, AutoModelForSequenceClassification,
DataCollatorForLanguageModeling, LineByLineTextDataset
)
from transformers import glue_convert_examples_to_features as convert_examples_to_features
from transformers import xnli_output_modes as output_modes
from transformers import xnli_processors as processors
NLI_PROB=0.6
class GLUECoSNLIProcessor(processors['xnli']):
def get_labels(self):
return ["contradiction", "entailment"]
try:
from torch.utils.tensorboard import SummaryWriter
except ImportError:
from tensorboardX import SummaryWriter
logger = logging.getLogger(__name__)
MODEL_CLASSES = {
"bert": (BertConfig, BertForMaskedLM, BertTokenizer),
"xlm": (XLMConfig, XLMForSequenceClassification, XLMTokenizer),
"xlm-roberta": (XLMRobertaConfig, XLMRobertaForMaskedLM, XLMRobertaTokenizer),
# "joeddav-xlm-roberta-large-xnli":()
}
def set_seed(args):
random.seed(args.seed)
np.random.seed(args.seed)
torch.manual_seed(args.seed)
if args.n_gpu > 0:
torch.cuda.manual_seed_all(args.seed)
class MaskedLMDataset(Dataset):
def __init__(self, file, tokenizer,max_len1):
self.tokenizer = tokenizer
self.max_len = max_len1
self.lines = self.load_lines(file)
self.dataset = self.encode_lines(self.lines)
def load_lines(self, file):
with open(file) as f:
lines = [
line
for line in f.read().splitlines()
if (len(line) > 0 and not line.isspace())
]
return lines
def encode_lines(self, lines):
batch_encoding = self.tokenizer.batch_encode_plus(
lines, add_special_tokens=True, truncation=True, max_length=self.max_len,pad_to_max_length=True)
# print(torch.tensor(batch_encoding)[:10])
# print([len(i) for i in batch_encoding["input_ids"]])
# print(torch.tensor(batch_encoding["token_type_ids"]).shape)
# print(torch.tensor(batch_encoding["attention_mask"]).shape)
return TensorDataset(torch.tensor(batch_encoding["input_ids"]),torch.tensor(batch_encoding["token_type_ids"]),\
torch.tensor(batch_encoding["attention_mask"]))
def __len__(self):
return len(self.lines)
def __getitem__(self, idx):
return self.dataset[idx]
# return torch.tensor(self.ids[idx], dtype=torch.long)
def train(args, nli_dataset, model, nli_layer,loss_nli_fn, tokenizer,mlm_dataset):
""" Train the model """
# if args.local_rank in [-1, 0]:
# tb_writer = SummaryWriter()
args.train_batch_size = args.per_gpu_train_batch_size * max(1, args.n_gpu)
args.mlm_batch_size = args.per_gpu_train_batch_size * max(1, args.n_gpu)
nli_sampler = RandomSampler(nli_dataset) if args.local_rank == -1 else DistributedSampler(nli_dataset)
mlm_sampler = RandomSampler(mlm_dataset) if args.local_rank == -1 else DistributedSampler(mlm_dataset)
nli_dataloader = DataLoader(nli_dataset, sampler=nli_sampler, batch_size=args.train_batch_size)
data_collator = DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm=True, mlm_probability=0.15)
mlm_dataloader = DataLoader(mlm_dataset, collate_fn=data_collator.collate_batch, batch_size=args.mlm_batch_size)
if args.max_steps > 0:
t_total = args.max_steps
args.num_train_epochs = args.max_steps // ((len(nli_dataloader)+len(mlm_dataloader)) // args.gradient_accumulation_steps) + 1
else:
t_total = (len(nli_dataloader)+len(mlm_dataloader)) // args.gradient_accumulation_steps * args.num_train_epochs
# m_total = len(mlm_dataloader) // args.gradient_accumulation_steps * args.num_train_epochs
t_total = ((2*len(nli_dataloader)+len(mlm_dataloader))// args.gradient_accumulation_steps * args.num_train_epochs)
if args.model_type=='xlm-roberta':
t_total*=4
# Prepare optimizer and schedule (linear warmup and decay)
no_decay = ["bias", "LayerNorm.weight"]
optimizer_grouped_parameters = [
{
"params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)],
"weight_decay": args.weight_decay,
},
# {"params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)], "weight_decay": 0.0},
{"params":[p for n,p in nli_layer.named_parameters()],"weight_decay":args.weight_decay},
# {"params":[p for n,p in mlm_layer.named_parameters()],"weight_decay":args.weight_decay},
]
optimizer = AdamW(optimizer_grouped_parameters, lr=args.learning_rate, eps=args.adam_epsilon)
scheduler = get_linear_schedule_with_warmup(
optimizer, num_warmup_steps=args.warmup_steps, num_training_steps=t_total
)
# multi-gpu training (should be after apex fp16 initialization)
if args.n_gpu > 1:
model = torch.nn.DataParallel(model)
# Distributed training (should be after apex fp16 initialization)
if args.local_rank != -1:
model = torch.nn.parallel.DistributedDataParallel(
model, device_ids=[args.local_rank], output_device=args.local_rank, find_unused_parameters=True
)
# Train!
print(t_total)
logger.info("***** Running training *****")
logger.info(" Num examples = %d", 2*len(nli_dataset)+len(mlm_dataset))
logger.info(" Num Epochs = %d", args.num_train_epochs)
logger.info(" Instantaneous batch size per GPU = %d", 2*args.per_gpu_train_batch_size)
logger.info(
" Total train batch size (w. parallel, distributed & accumulation) = %d",
2*args.train_batch_size
* args.gradient_accumulation_steps
* (torch.distributed.get_world_size() if args.local_rank != -1 else 1),
)
logger.info(" Gradient Accumulation steps = %d", args.gradient_accumulation_steps)
logger.info(" Total optimization steps = %d", t_total)
global_step = 0
epochs_trained = 0
steps_trained_in_current_epoch = 0
tr_loss, logging_loss = 0.0, 0.0
model.zero_grad()
train_iterator = trange(
epochs_trained, int(args.num_train_epochs), desc="Epoch", disable=args.local_rank not in [-1, 0]
)
set_seed(args) # Added here for reproductibility
best_val_acc=0
for _ in train_iterator:
steps_done=0
# nli_fin=False
# mlm_fin=False
drnli,nrnli,lossnli,lossmlm,iters,drmlm =0,0,0,0,0,0
# nli_epoch_iterator = iter(nli_dataloader, desc="Iteration", disable=args.local_rank not in [-1, 0])
# mlm_epoch_iterator = iter(mlm_dataloader, desc="Iteration", disable=args.local_rank not in [-1, 0])
nli_dataloader = DataLoader(nli_dataset, sampler=nli_sampler, batch_size=args.train_batch_size)
mlm_dataloader = DataLoader(mlm_dataset, collate_fn=data_collator.collate_batch, batch_size=args.mlm_batch_size)
nli_epoch_iterator = iter(nli_dataloader)
mlm_epoch_iterator = iter(mlm_dataloader)
pbar = tqdm(total=t_total)
nli_steps=0
while steps_done<t_total:
r = random.uniform(0, 1)
if r<NLI_PROB:
nli_steps+=1
# print(nli_steps)
for icnt in range(args.gradient_accumulation_steps):
batch_nli=next(nli_epoch_iterator,None)
if batch_nli==None:
# nli_epoch_iterator.close()
nli_dataloader = DataLoader(nli_dataset, sampler=nli_sampler, batch_size=args.train_batch_size)
nli_epoch_iterator = iter(nli_dataloader)
batch_nli=next(nli_epoch_iterator,None)
steps_done+=1
pbar.update(1)
# for step, batch in enumerate(epoch_iterator):
# # Skip past any already trained steps if resuming training
# if steps_trained_in_current_epoch > 0:
# steps_trained_in_current_epoch -= 1
# continue
model.train()
batch_nli = tuple(t.to(args.device) for t in batch_nli)
# print(batch_nli[0].shape)
# print(batch_nli[1].shape)
# inputs_nli = {"input_ids": batch_nli[0], "attention_mask": batch_nli[1]}#, "labels": batch[3]}
inputs_nli = {"input_ids": torch.cat((batch_nli[0],batch_nli[4]),0), "attention_mask": torch.cat((batch_nli[1],batch_nli[5]),0)}
#"labels": torch.cat((batch_nli[3],batch_nli[7]),0)}
# if args.model_type != "distilbert":
# inputs_nli["token_type_ids"] = (
# batch_nli[2] if args.model_type in ["bert"] else None
# ) # XLM and DistilBERT don't use segment_ids
if args.model_type != "distilbert":
inputs_nli["token_type_ids"] = (
# batch_nli[2] if args.model_type in ["bert"] else None
torch.cat((batch_nli[2],batch_nli[6]),0) if args.model_type in ["bert"] else None
) # XLM and DistilBERT don't use segment_ids
outputs_nli = model(**inputs_nli)
# print(len(outputs_nli[-1]))
hidden = outputs_nli[-1][-1] # model outputs are always tuple in transformers (see doc)
# print(hidden.shape)
nli_pred = nli_layer(hidden[:, 0, :])
_,nli_labels=torch.max(nli_pred,-1)
# nrnli+=torch.eq(nli_labels,batch_nli[3]).sum().item()
# drnli+=float(batch_nli[3].shape[0])
# loss_nli = loss_nli_fn(nli_pred, batch_nli[3])
nrnli+=torch.eq(nli_labels,torch.cat((batch_nli[3],batch_nli[7]),0)).sum().item()
drnli+=float(batch_nli[3].shape[0])+float(batch_nli[7].shape[0])
loss_nli = loss_nli_fn(nli_pred, torch.cat((batch_nli[3],batch_nli[7]),0))
lossnli+=loss_nli.item()
iters+=1
if args.n_gpu > 1:
loss_nli = loss_nli.mean() # mean() to average on multi-gpu parallel training
if args.gradient_accumulation_steps > 1:
loss_nli = loss_nli / args.gradient_accumulation_steps
loss_nli.backward()
tr_loss += loss_nli.item()
# if (step + 1) % args.gradient_accumulation_steps == 0:
torch.nn.utils.clip_grad_norm_(model.parameters(), args.max_grad_norm)
optimizer.step()
scheduler.step() # Update learning rate schedule
model.zero_grad()
nli_layer.zero_grad()
global_step += 1
# logging_loss = tr_loss
# if args.max_steps > 0 and global_step > args.max_steps:
# epoch_iterator.close()
# break
else:
# drnli,nrnli,lossnli,iters =0,0,0,0
for icnt in range(args.gradient_accumulation_steps):
batch=next(mlm_epoch_iterator,None)
if batch==None:
# mlm_epoch_iterator.close()
mlm_dataloader = DataLoader(mlm_dataset, collate_fn=data_collator.collate_batch, batch_size=args.mlm_batch_size)
mlm_epoch_iterator = iter(mlm_dataloader)
batch=next(mlm_epoch_iterator,None)
pbar.update(1)
steps_done+=1
# for step, batch in enumerate(epoch_iterator):
# # Skip past any already trained steps if resuming training
# if steps_trained_in_current_epoch > 0:
# steps_trained_in_current_epoch -= 1
# continue
model.train()
mlmsz=1
for i in batch.keys():
batch[i]=batch[i].to(args.device)
mlmsz=batch[i].shape[0]
# batch = tuple(t.to(args.device) for t in batch)
inputs=batch
# inputs = {"input_ids": batch[0], "attention_mask": batch[1]}#, "labels": batch[3]}
# inputs = {"input_ids": torch.cat((batch[0],batch[4]),0), "attention_mask": torch.cat((batch[1],batch[5]),0), "labels": torch.cat(\
# (batch[3],batch[7]),0)}
# if args.model_type != "distilbert":
# inputs["token_type_ids"] = (
# batch[2] if args.model_type in ["bert"] else None
# ) # XLM and DistilBERT don't use segment_ids
outputs = model(**inputs)
loss=outputs[0]
lossmlm+=loss.item()
drmlm+=mlmsz
iters+=1
if args.n_gpu > 1:
loss = loss.mean() # mean() to average on multi-gpu parallel training
if args.gradient_accumulation_steps > 1:
loss = loss / args.gradient_accumulation_steps
loss.backward()
tr_loss += loss.item()
torch.nn.utils.clip_grad_norm_(model.parameters(), args.max_grad_norm)
optimizer.step()
scheduler.step() # Update learning rate schedule
model.zero_grad()
global_step += 1
if (global_step)%args.logging_steps==0:
results,val_acc = evaluate(args, model, tokenizer, nli_layer, loss_nli_fn)
if val_acc>best_val_acc:
logger.info('new best val acc at %s',str(val_acc))
best_val_acc=val_acc
if args.save_model:
logger.info('saving model')
model.save_pretrained(args.save_folder)
tokenizer.save_pretrained(args.save_folder)
torch.save(nli_layer.state_dict(),os.path.join(args.save_folder,"nli_layer.bin"))
torch.save(args, os.path.join(args.save_folder, "training_args.bin"))
else:
logger.info('best val acc still at %s',str(best_val_acc))
logger.info('nli acc=%s ',str(nrnli/drnli))
logger.info('loss nli=%s',str(lossnli/iters))
logger.info('loss mlm=%s',str(lossmlm/drmlm))
# if args.local_rank in [-1, 0]:
# tb_writer.close()
return global_step, tr_loss / global_step
def evaluate(args, model, tokenizer, nli_classifier, loss_nli_fn, prefix=""):
eval_task_names = (args.task_name,)
eval_outputs_dirs = (args.output_dir,)
results = {}
for eval_task, eval_output_dir in zip(eval_task_names, eval_outputs_dirs):
eval_dataset = load_and_cache_examples(args, eval_task, tokenizer, evaluate=True)
if not os.path.exists(eval_output_dir) and args.local_rank in [-1, 0]:
os.makedirs(eval_output_dir)
args.eval_batch_size = args.per_gpu_eval_batch_size * max(1, args.n_gpu)
# Note that DistributedSampler samples randomly
eval_sampler = SequentialSampler(eval_dataset)
eval_dataloader = DataLoader(eval_dataset, sampler=eval_sampler, batch_size=args.eval_batch_size)
# multi-gpu eval
if args.n_gpu > 1:
model = torch.nn.DataParallel(model)
# Eval!
logger.info("***** Running evaluation {} *****".format(prefix))
logger.info(" Num examples = %d", len(eval_dataset))
logger.info(" Batch size = %d", args.eval_batch_size)
eval_loss = 0.0
nb_eval_steps = 0
eval_preds = None
out_label_ids = None
actual_labels=None
for eval_batch in tqdm(eval_dataloader, desc="Evaluating"):
model.eval()
eval_batch = tuple(t.to(args.device) for t in eval_batch)
with torch.no_grad():
# eval_inputs = {"input_ids": eval_batch[0], "attention_mask": eval_batch[1]}
eval_inputs = {"input_ids": torch.cat((eval_batch[0],eval_batch[4]),0), "attention_mask": torch.cat((eval_batch[1],eval_batch[5]),0)}
# if args.model_type != "distilbert":
# eval_inputs["token_type_ids"] = (
# eval_batch[2] if args.model_type in ["bert"] else None
# ) # XLM and DistilBERT don't use segment_ids
if args.model_type != "distilbert":
eval_inputs["token_type_ids"] = (
torch.cat((eval_batch[2],eval_batch[6]),0) if args.model_type in ["bert"] else None
) # XLM and DistilBERT don't use segment_ids
eval_outputs = model(**eval_inputs)
eval_hidden = eval_outputs[-1][-1]
eval_nli_pred = nli_classifier(eval_hidden[:, 0, :])
#pos_pred = pos_pred.permute(0, 2, 1)
# eval_loss_pred = loss_nli_fn(eval_nli_pred, eval_batch[3])
eval_loss_pred = loss_nli_fn(eval_nli_pred, torch.cat((eval_batch[3],eval_batch[7]),0))
# print(pos_pred.shape)
logits = eval_nli_pred#.max(dim = 1)[1]
#tmp_eval_loss, logits = outputs[:2]
eval_loss += eval_loss_pred.item()
nb_eval_steps += 1
if eval_preds is None:
eval_preds = logits.detach().cpu().numpy()
out_label_ids = eval_batch[3].detach().cpu().numpy()
out_label_ids = np.append(out_label_ids, eval_batch[7].detach().cpu().numpy(), axis=0)
else:
eval_preds = np.append(eval_preds, logits.detach().cpu().numpy(), axis=0)
out_label_ids = np.append(out_label_ids, eval_batch[3].detach().cpu().numpy(), axis=0)
out_label_ids = np.append(out_label_ids, eval_batch[7].detach().cpu().numpy(), axis=0)
eval_loss = eval_loss / nb_eval_steps
if args.output_mode == "classification":
# preds[:,1]=-100
eval_preds = np.argmax(eval_preds, axis=1)
else:
raise ValueError("No other `output_mode` for XNLI.")
# print(preds.shape)
# print(out_label_ids.shape)
# print(preds[:10])
# print(out_label_ids[:10])
valacc=float(np.sum(np.equal(eval_preds,out_label_ids)))/float(eval_preds.shape[0])
logger.info("Validation set accuracy: %s", str(valacc))
# result = compute_metrics(eval_task, preds, out_label_ids)
# results.update(result)
logger.info("***** Eval results {} *****".format(prefix))
# for key in sorted(result.keys()):
# logger.info(" %s = %s", key, str(result[key]))
eval_label_list = GLUECoSNLIProcessor(language=args.language, train_language=args.train_language).get_labels()
# print(label_list)
eval_pred_labels = [eval_label_list[x] for x in eval_preds]
return eval_pred_labels,valacc
def load_and_cache_examples(args, task, tokenizer, evaluate=False):
if args.local_rank not in [-1, 0] and not evaluate:
torch.distributed.barrier() # Make sure only the first process in distributed training process the dataset, and the others will use the cache
processor = GLUECoSNLIProcessor(language=args.language, train_language=args.train_language)
output_mode = output_modes[task]
# Load data features from cache or dataset file
cached_features_file = os.path.join(
args.data_dir,
"cached_{}_{}_{}_{}_{}".format(
"test" if evaluate else "train",
list(filter(None, args.model_name_or_path.split("/"))).pop(),
str(args.max_seq_length),
str(task),
str(args.train_language if (not evaluate and args.train_language is not None) else args.language),
),
)
if os.path.exists(cached_features_file) and not args.overwrite_cache and False:
logger.info("Loading features from cached file %s", cached_features_file)
features = torch.load(cached_features_file)
else:
logger.info("Creating features from dataset file at %s", os.path.join(args.data_dir,'english_MNLI'))
# print("hey")
label_list = processor.get_labels()
examples1 = (
processor.get_test_examples(os.path.join(args.data_dir,'english_MNLI')) if evaluate else processor.get_train_examples(os.path.join(args.data_dir,'english_MNLI'))
)
# print(examples[0])
# print(len(examples[0].text_a.split(' '))+len(examples[0].text_b.split(' ')))
features1 = convert_examples_to_features(
examples1, tokenizer, max_length=args.max_seq_length, label_list=label_list, output_mode=output_mode,
)
# print(features[0])
# print(len(features[0].input_ids))
# if args.local_rank in [-1, 0]:
# logger.info("Saving features into cached file %s", cached_features_file)
# torch.save(features1, cached_features_file)
if args.local_rank == 0 and not evaluate:
torch.distributed.barrier() # Make sure only the first process in distributed training process the dataset, and the others will use the cache
# Convert to Tensors and build dataset
all_input_ids = torch.tensor([f.input_ids for f in features1], dtype=torch.long)
all_attention_mask = torch.tensor([f.attention_mask for f in features1], dtype=torch.long)
if args.model_type=='bert':
all_token_type_ids = torch.tensor([f.token_type_ids for f in features1], dtype=torch.long)
else:
all_token_type_ids = torch.tensor([tokenizer.create_token_type_ids_from_sequences(f.attention_mask) for f in features1], dtype=torch.long)
if output_mode == "classification":
all_labels = torch.tensor([f.label for f in features1], dtype=torch.long)
else:
raise ValueError("No other `output_mode` for XNLI.")
logger.info("Creating romanised features from dataset file at %s", os.path.join(args.data_dir,'romanised_hindi_MNLI'))
# print("hey")
# label_list = processor.get_labels()
examples2 = (
processor.get_test_examples(os.path.join(args.data_dir,'romanised_hindi_MNLI')) if evaluate else processor.get_train_examples(os.path.join(args.data_dir,'romanised_hindi_MNLI'))
)
# print(examples[0])
# print(len(examples[0].text_a.split(' '))+len(examples[0].text_b.split(' ')))
features2 = convert_examples_to_features(
examples2, tokenizer, max_length=args.max_seq_length, label_list=label_list, output_mode=output_mode,
)
# print(features[0])
# print(len(features[0].input_ids))
# if args.local_rank in [-1, 0]:
# logger.info("Saving features into cached file %s", cached_features_file)
# torch.save(features2, cached_features_file)
if args.local_rank == 0 and not evaluate:
torch.distributed.barrier() # Make sure only the first process in distributed training process the dataset, and the others will use the cache
# Convert to Tensors and build dataset
all_input_ids2 = torch.tensor([f.input_ids for f in features2], dtype=torch.long)
all_attention_mask2 = torch.tensor([f.attention_mask for f in features2], dtype=torch.long)
if args.model_type=='bert':
all_token_type_ids2 = torch.tensor([f.token_type_ids for f in features2], dtype=torch.long)
else:
all_token_type_ids2 = torch.tensor([tokenizer.create_token_type_ids_from_sequences(f.attention_mask) for f in features2], dtype=torch.long)
if output_mode == "classification":
all_labels2 = torch.tensor([f.label for f in features2], dtype=torch.long)
else:
raise ValueError("No other `output_mode` for XNLI.")
dataset = TensorDataset(all_input_ids, all_attention_mask, all_token_type_ids, all_labels,all_input_ids2, all_attention_mask2, all_token_type_ids2, all_labels2)
return dataset
def main():
parser = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"--save_folder",
default=None,
type=str,
required=False,
help="The location to save model.",
)
parser.add_argument(
"--data_dir",
default=None,
type=str,
required=True,
help="The input data dir. Should contain the .tsv files (or other data files) for the task.",
)
parser.add_argument(
"--model_type",
default=None,
type=str,
required=True,
help="Model type selected in the list: " + ", ".join(MODEL_CLASSES.keys()),
)
parser.add_argument(
"--model_name_or_path",
default=None,
type=str,
required=True,
help="Path to pre-trained model or shortcut name selected in the list: ",
)
parser.add_argument(
"--language",
default=None,
type=str,
required=True,
help="Evaluation language. Also train language if `train_language` is set to None.",
)
parser.add_argument(
"--train_language", default=None, type=str, help="Train language if is different of the evaluation language."
)
parser.add_argument(
"--output_dir",
default=None,
type=str,
required=True,
help="The output directory where the model predictions and checkpoints will be written.",
)
# Other parameters
parser.add_argument(
"--config_name", default="", type=str, help="Pretrained config name or path if not the same as model_name"
)
parser.add_argument(
"--tokenizer_name",
default="",
type=str,
help="Pretrained tokenizer name or path if not the same as model_name",
)
parser.add_argument(
"--cache_dir",
default="",
type=str,
help="Where do you want to store the pre-trained models downloaded from s3",
)
parser.add_argument(
"--max_seq_length",
default=512,
type=int,
help="The maximum total input sequence length after tokenization. Sequences longer "
"than this will be truncated, sequences shorter will be padded.",
)
parser.add_argument("--do_train", action="store_true", help="Whether to run training.")
parser.add_argument("--do_eval", action="store_true", help="Whether to run eval on the test set.")
parser.add_argument("--save_model", action="store_true", help="Whether to save current best model.")
parser.add_argument(
"--evaluate_during_training", action="store_true", help="Rul evaluation during training at each logging step."
)
parser.add_argument(
"--do_lower_case", action="store_true", help="Set this flag if you are using an uncased model."
)
parser.add_argument("--per_gpu_train_batch_size", default=8, type=int, help="Batch size per GPU/CPU for training.")
parser.add_argument(
"--per_gpu_eval_batch_size", default=8, type=int, help="Batch size per GPU/CPU for evaluation."
)
parser.add_argument(
"--gradient_accumulation_steps",
type=int,
default=1,
help="Number of updates steps to accumulate before performing a backward/update pass.",
)
parser.add_argument("--learning_rate", default=5e-5, type=float, help="The initial learning rate for Adam.")
parser.add_argument("--weight_decay", default=0.0, type=float, help="Weight decay if we apply some.")
parser.add_argument("--adam_epsilon", default=1e-8, type=float, help="Epsilon for Adam optimizer.")
parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.")
parser.add_argument(
"--num_train_epochs", default=3.0, type=float, help="Total number of training epochs to perform."
)
parser.add_argument(
"--max_steps",
default=-1,
type=int,
help="If > 0: set total number of training steps to perform. Override num_train_epochs.",
)
parser.add_argument("--warmup_steps", default=0, type=int, help="Linear warmup over warmup_steps.")
parser.add_argument("--logging_steps", type=int, default=500, help="Log every X updates steps.")
parser.add_argument("--save_steps", type=int, default=500, help="Save checkpoint every X updates steps.")
parser.add_argument(
"--eval_all_checkpoints",
action="store_true",
help="Evaluate all checkpoints starting with the same prefix as model_name ending and ending with step number",
)
parser.add_argument("--no_cuda", action="store_true", help="Avoid using CUDA when available")
parser.add_argument(
"--overwrite_output_dir", action="store_true", help="Overwrite the content of the output directory"
)
parser.add_argument(
"--overwrite_cache", action="store_true", help="Overwrite the cached training and evaluation sets"
)
parser.add_argument("--seed", type=int, default=42, help="random seed for initialization")
parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
parser.add_argument("--mlm_datapath",default=None,type=str,required=True,help="Path to data for mlm")
args = parser.parse_args()
if args.save_model and (not os.path.exists(args.save_folder)):
os.mkdir(args.save_folder)
if (
os.path.exists(args.output_dir)
and os.listdir(args.output_dir)
and args.do_train
and not args.overwrite_output_dir
):
raise ValueError(
"Output directory ({}) already exists and is not empty. Use --overwrite_output_dir to overcome.".format(
args.output_dir
)
)
# Setup CUDA, GPU & distributed training
if args.local_rank == -1 or args.no_cuda:
device = torch.device("cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu")
args.n_gpu = 0 if args.no_cuda else torch.cuda.device_count()
# print(args.n_gpu)
else: # Initializes the distributed backend which will take care of sychronizing nodes/GPUs
torch.cuda.set_device(args.local_rank)
device = torch.device("cuda", args.local_rank)
torch.distributed.init_process_group(backend="nccl")
args.n_gpu = 1
args.device = device
# Setup logging
logging.basicConfig(
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
datefmt="%m/%d/%Y %H:%M:%S",
level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN,
)
logger.warning(
"Process rank: %s, device: %s, n_gpu: %s, distributed training: %s",
args.local_rank,
device,
args.n_gpu,
bool(args.local_rank != -1),
)
# Set seed
set_seed(args)
# Prepare XNLI task
args.task_name = "xnli"
if args.task_name not in processors:
raise ValueError("Task not found: %s" % (args.task_name))
# processor = processors[args.task_name](language=args.language, train_language=args.train_language)
processor = GLUECoSNLIProcessor(language=args.language, train_language=args.train_language)
args.output_mode = output_modes[args.task_name]
label_list = processor.get_labels()
num_labels = len(label_list)
# Load pretrained model and tokenizer
if args.local_rank not in [-1, 0]:
torch.distributed.barrier() # Make sure only the first process in distributed training will download model & vocab
args.model_type = args.model_type.lower()
config_class, model_class, tokenizer_class = MODEL_CLASSES[args.model_type]
config = config_class.from_pretrained(
# './pretrainCS_bert_65k/config.json',
args.config_name if args.config_name else args.model_name_or_path,
output_hidden_states=True
# num_labels=num_labels,
# finetuning_task=args.task_name,
# cache_dir=args.cache_dir if args.cache_dir else None,
)
tokenizer = tokenizer_class.from_pretrained(
args.tokenizer_name if args.tokenizer_name else args.model_name_or_path,
do_lower_case=args.do_lower_case,
cache_dir=args.cache_dir if args.cache_dir else None,
)
# tokenizer = AutoTokenizer.from_pretrained("joeddav/xlm-roberta-large-xnli")
model=model_class.from_pretrained(
# './pretrainCS_bert_65k/pytorch_model.bin',
args.model_name_or_path,
from_tf=bool(".ckpt" in args.model_name_or_path),
config=config,
cache_dir=args.cache_dir if args.cache_dir else None,
)
# model = AutoModelForSequenceClassification.from_pretrained("joeddav/xlm-roberta-large-xnli")
if args.local_rank == 0:
torch.distributed.barrier() # Make sure only the first process in distributed training will download model & vocab
model.to(args.device)
nli_layer = torch.nn.Sequential(torch.nn.Linear(768,2), torch.nn.LogSoftmax(dim=1))
loss_nli_fn = torch.nn.NLLLoss()
nli_layer.to(args.device)
logger.info("Training/evaluation parameters %s", args)
# Training
if args.do_train:
nli_dataset = load_and_cache_examples(args, args.task_name, tokenizer, evaluate=False)
logger.info('Creating MLM features')
print(args.mlm_datapath)
mlm_dataset=LineByLineTextDataset(tokenizer=tokenizer, file_path=args.mlm_datapath, block_size=args.max_seq_length)
# mlm_dataset=MaskedLMDataset(args.mlm_datapath, tokenizer,args.max_seq_length)
global_step, tr_loss = train(args, nli_dataset, model,nli_layer,loss_nli_fn, tokenizer,mlm_dataset)
logger.info(" global_step = %s, average loss = %s", global_step, tr_loss)
# Evaluation
results = {}
if args.do_eval and args.local_rank in [-1, 0]:
pred_labels,_ = evaluate(args, model, tokenizer,nli_layer,loss_nli_fn)# prefix=global_step)
return results
if __name__ == "__main__":
print(os.environ["NVIDIA_VISIBLE_DEVICES"])
print(os.environ["CUDA_VISIBLE_DEVICES"])
main()
| [
"logging.getLogger",
"torch.max",
"torch.cuda.device_count",
"numpy.equal",
"torch.utils.data.distributed.DistributedSampler",
"torch.cuda.is_available",
"torch.distributed.barrier",
"transformers.DataCollatorForLanguageModeling",
"os.path.exists",
"transformers.glue_convert_examples_to_features",... | [((2079, 2106), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (2096, 2106), False, 'import logging\n'), ((2406, 2428), 'random.seed', 'random.seed', (['args.seed'], {}), '(args.seed)\n', (2417, 2428), False, 'import random\n'), ((2433, 2458), 'numpy.random.seed', 'np.random.seed', (['args.seed'], {}), '(args.seed)\n', (2447, 2458), True, 'import numpy as np\n'), ((2463, 2491), 'torch.manual_seed', 'torch.manual_seed', (['args.seed'], {}), '(args.seed)\n', (2480, 2491), False, 'import torch\n'), ((4461, 4539), 'torch.utils.data.DataLoader', 'DataLoader', (['nli_dataset'], {'sampler': 'nli_sampler', 'batch_size': 'args.train_batch_size'}), '(nli_dataset, sampler=nli_sampler, batch_size=args.train_batch_size)\n', (4471, 4539), False, 'from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset, Dataset\n'), ((4560, 4648), 'transformers.DataCollatorForLanguageModeling', 'DataCollatorForLanguageModeling', ([], {'tokenizer': 'tokenizer', 'mlm': '(True)', 'mlm_probability': '(0.15)'}), '(tokenizer=tokenizer, mlm=True,\n mlm_probability=0.15)\n', (4591, 4648), False, 'from transformers import AdamW, BertConfig, BertForSequenceClassification, BertForMaskedLM, XLMRobertaForMaskedLM, BertTokenizer, XLMConfig, XLMForSequenceClassification, XLMTokenizer, XLMRobertaConfig, XLMRobertaForSequenceClassification, XLMRobertaTokenizer, get_linear_schedule_with_warmup, AutoTokenizer, AutoModelForSequenceClassification, DataCollatorForLanguageModeling, LineByLineTextDataset\n'), ((4666, 4766), 'torch.utils.data.DataLoader', 'DataLoader', (['mlm_dataset'], {'collate_fn': 'data_collator.collate_batch', 'batch_size': 'args.mlm_batch_size'}), '(mlm_dataset, collate_fn=data_collator.collate_batch, batch_size=\n args.mlm_batch_size)\n', (4676, 4766), False, 'from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset, Dataset\n'), ((6022, 6108), 'transformers.AdamW', 'AdamW', (['optimizer_grouped_parameters'], {'lr': 'args.learning_rate', 'eps': 'args.adam_epsilon'}), '(optimizer_grouped_parameters, lr=args.learning_rate, eps=args.\n adam_epsilon)\n', (6027, 6108), False, 'from transformers import AdamW, BertConfig, BertForSequenceClassification, BertForMaskedLM, XLMRobertaForMaskedLM, BertTokenizer, XLMConfig, XLMForSequenceClassification, XLMTokenizer, XLMRobertaConfig, XLMRobertaForSequenceClassification, XLMRobertaTokenizer, get_linear_schedule_with_warmup, AutoTokenizer, AutoModelForSequenceClassification, DataCollatorForLanguageModeling, LineByLineTextDataset\n'), ((6120, 6231), 'transformers.get_linear_schedule_with_warmup', 'get_linear_schedule_with_warmup', (['optimizer'], {'num_warmup_steps': 'args.warmup_steps', 'num_training_steps': 't_total'}), '(optimizer, num_warmup_steps=args.\n warmup_steps, num_training_steps=t_total)\n', (6151, 6231), False, 'from transformers import AdamW, BertConfig, BertForSequenceClassification, BertForMaskedLM, XLMRobertaForMaskedLM, BertTokenizer, XLMConfig, XLMForSequenceClassification, XLMTokenizer, XLMRobertaConfig, XLMRobertaForSequenceClassification, XLMRobertaTokenizer, get_linear_schedule_with_warmup, AutoTokenizer, AutoModelForSequenceClassification, DataCollatorForLanguageModeling, LineByLineTextDataset\n'), ((23124, 23188), 'torch.tensor', 'torch.tensor', (['[f.input_ids for f in features1]'], {'dtype': 'torch.long'}), '([f.input_ids for f in features1], dtype=torch.long)\n', (23136, 23188), False, 'import torch\n'), ((23214, 23283), 'torch.tensor', 'torch.tensor', (['[f.attention_mask for f in features1]'], {'dtype': 'torch.long'}), '([f.attention_mask for f in features1], dtype=torch.long)\n', (23226, 23283), False, 'import torch\n'), ((24289, 24424), 'transformers.glue_convert_examples_to_features', 'convert_examples_to_features', (['examples2', 'tokenizer'], {'max_length': 'args.max_seq_length', 'label_list': 'label_list', 'output_mode': 'output_mode'}), '(examples2, tokenizer, max_length=args.\n max_seq_length, label_list=label_list, output_mode=output_mode)\n', (24317, 24424), True, 'from transformers import glue_convert_examples_to_features as convert_examples_to_features\n'), ((24937, 25001), 'torch.tensor', 'torch.tensor', (['[f.input_ids for f in features2]'], {'dtype': 'torch.long'}), '([f.input_ids for f in features2], dtype=torch.long)\n', (24949, 25001), False, 'import torch\n'), ((25028, 25097), 'torch.tensor', 'torch.tensor', (['[f.attention_mask for f in features2]'], {'dtype': 'torch.long'}), '([f.attention_mask for f in features2], dtype=torch.long)\n', (25040, 25097), False, 'import torch\n'), ((25602, 25761), 'torch.utils.data.TensorDataset', 'TensorDataset', (['all_input_ids', 'all_attention_mask', 'all_token_type_ids', 'all_labels', 'all_input_ids2', 'all_attention_mask2', 'all_token_type_ids2', 'all_labels2'], {}), '(all_input_ids, all_attention_mask, all_token_type_ids,\n all_labels, all_input_ids2, all_attention_mask2, all_token_type_ids2,\n all_labels2)\n', (25615, 25761), False, 'from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset, Dataset\n'), ((25799, 25824), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (25822, 25824), False, 'import argparse\n'), ((32129, 32324), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""%(asctime)s - %(levelname)s - %(name)s - %(message)s"""', 'datefmt': '"""%m/%d/%Y %H:%M:%S"""', 'level': '(logging.INFO if args.local_rank in [-1, 0] else logging.WARN)'}), "(format=\n '%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt=\n '%m/%d/%Y %H:%M:%S', level=logging.INFO if args.local_rank in [-1, 0] else\n logging.WARN)\n", (32148, 32324), False, 'import logging\n'), ((34725, 34743), 'torch.nn.NLLLoss', 'torch.nn.NLLLoss', ([], {}), '()\n', (34741, 34743), False, 'import torch\n'), ((2523, 2560), 'torch.cuda.manual_seed_all', 'torch.cuda.manual_seed_all', (['args.seed'], {}), '(args.seed)\n', (2549, 2560), False, 'import torch\n'), ((4244, 4270), 'torch.utils.data.RandomSampler', 'RandomSampler', (['nli_dataset'], {}), '(nli_dataset)\n', (4257, 4270), False, 'from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset, Dataset\n'), ((4301, 4332), 'torch.utils.data.distributed.DistributedSampler', 'DistributedSampler', (['nli_dataset'], {}), '(nli_dataset)\n', (4319, 4332), False, 'from torch.utils.data.distributed import DistributedSampler\n'), ((4351, 4377), 'torch.utils.data.RandomSampler', 'RandomSampler', (['mlm_dataset'], {}), '(mlm_dataset)\n', (4364, 4377), False, 'from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset, Dataset\n'), ((4408, 4439), 'torch.utils.data.distributed.DistributedSampler', 'DistributedSampler', (['mlm_dataset'], {}), '(mlm_dataset)\n', (4426, 4439), False, 'from torch.utils.data.distributed import DistributedSampler\n'), ((6349, 6377), 'torch.nn.DataParallel', 'torch.nn.DataParallel', (['model'], {}), '(model)\n', (6370, 6377), False, 'import torch\n'), ((6495, 6638), 'torch.nn.parallel.DistributedDataParallel', 'torch.nn.parallel.DistributedDataParallel', (['model'], {'device_ids': '[args.local_rank]', 'output_device': 'args.local_rank', 'find_unused_parameters': '(True)'}), '(model, device_ids=[args.\n local_rank], output_device=args.local_rank, find_unused_parameters=True)\n', (6536, 6638), False, 'import torch\n'), ((8134, 8212), 'torch.utils.data.DataLoader', 'DataLoader', (['nli_dataset'], {'sampler': 'nli_sampler', 'batch_size': 'args.train_batch_size'}), '(nli_dataset, sampler=nli_sampler, batch_size=args.train_batch_size)\n', (8144, 8212), False, 'from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset, Dataset\n'), ((8238, 8338), 'torch.utils.data.DataLoader', 'DataLoader', (['mlm_dataset'], {'collate_fn': 'data_collator.collate_batch', 'batch_size': 'args.mlm_batch_size'}), '(mlm_dataset, collate_fn=data_collator.collate_batch, batch_size=\n args.mlm_batch_size)\n', (8248, 8338), False, 'from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset, Dataset\n'), ((8449, 8468), 'tqdm.tqdm', 'tqdm', ([], {'total': 't_total'}), '(total=t_total)\n', (8453, 8468), False, 'from tqdm import tqdm, trange\n'), ((16972, 17003), 'torch.utils.data.SequentialSampler', 'SequentialSampler', (['eval_dataset'], {}), '(eval_dataset)\n', (16989, 17003), False, 'from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset, Dataset\n'), ((17030, 17109), 'torch.utils.data.DataLoader', 'DataLoader', (['eval_dataset'], {'sampler': 'eval_sampler', 'batch_size': 'args.eval_batch_size'}), '(eval_dataset, sampler=eval_sampler, batch_size=args.eval_batch_size)\n', (17040, 17109), False, 'from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset, Dataset\n'), ((17584, 17624), 'tqdm.tqdm', 'tqdm', (['eval_dataloader'], {'desc': '"""Evaluating"""'}), "(eval_dataloader, desc='Evaluating')\n", (17588, 17624), False, 'from tqdm import tqdm, trange\n'), ((20962, 20989), 'torch.distributed.barrier', 'torch.distributed.barrier', ([], {}), '()\n', (20987, 20989), False, 'import torch\n'), ((21710, 21746), 'os.path.exists', 'os.path.exists', (['cached_features_file'], {}), '(cached_features_file)\n', (21724, 21746), False, 'import os\n'), ((21888, 21920), 'torch.load', 'torch.load', (['cached_features_file'], {}), '(cached_features_file)\n', (21898, 21920), False, 'import torch\n'), ((22449, 22584), 'transformers.glue_convert_examples_to_features', 'convert_examples_to_features', (['examples1', 'tokenizer'], {'max_length': 'args.max_seq_length', 'label_list': 'label_list', 'output_mode': 'output_mode'}), '(examples1, tokenizer, max_length=args.\n max_seq_length, label_list=label_list, output_mode=output_mode)\n', (22477, 22584), True, 'from transformers import glue_convert_examples_to_features as convert_examples_to_features\n'), ((22917, 22944), 'torch.distributed.barrier', 'torch.distributed.barrier', ([], {}), '()\n', (22942, 22944), False, 'import torch\n'), ((23345, 23414), 'torch.tensor', 'torch.tensor', (['[f.token_type_ids for f in features1]'], {'dtype': 'torch.long'}), '([f.token_type_ids for f in features1], dtype=torch.long)\n', (23357, 23414), False, 'import torch\n'), ((23633, 23693), 'torch.tensor', 'torch.tensor', (['[f.label for f in features1]'], {'dtype': 'torch.long'}), '([f.label for f in features1], dtype=torch.long)\n', (23645, 23693), False, 'import torch\n'), ((23838, 23889), 'os.path.join', 'os.path.join', (['args.data_dir', '"""romanised_hindi_MNLI"""'], {}), "(args.data_dir, 'romanised_hindi_MNLI')\n", (23850, 23889), False, 'import os\n'), ((24729, 24756), 'torch.distributed.barrier', 'torch.distributed.barrier', ([], {}), '()\n', (24754, 24756), False, 'import torch\n'), ((25165, 25234), 'torch.tensor', 'torch.tensor', (['[f.token_type_ids for f in features2]'], {'dtype': 'torch.long'}), '([f.token_type_ids for f in features2], dtype=torch.long)\n', (25177, 25234), False, 'import torch\n'), ((25455, 25515), 'torch.tensor', 'torch.tensor', (['[f.label for f in features2]'], {'dtype': 'torch.long'}), '([f.label for f in features2], dtype=torch.long)\n', (25467, 25515), False, 'import torch\n'), ((31118, 31144), 'os.mkdir', 'os.mkdir', (['args.save_folder'], {}), '(args.save_folder)\n', (31126, 31144), False, 'import os\n'), ((31162, 31193), 'os.path.exists', 'os.path.exists', (['args.output_dir'], {}), '(args.output_dir)\n', (31176, 31193), False, 'import os\n'), ((31206, 31233), 'os.listdir', 'os.listdir', (['args.output_dir'], {}), '(args.output_dir)\n', (31216, 31233), False, 'import os\n'), ((31901, 31939), 'torch.cuda.set_device', 'torch.cuda.set_device', (['args.local_rank'], {}), '(args.local_rank)\n', (31922, 31939), False, 'import torch\n'), ((31957, 31994), 'torch.device', 'torch.device', (['"""cuda"""', 'args.local_rank'], {}), "('cuda', args.local_rank)\n", (31969, 31994), False, 'import torch\n'), ((32003, 32055), 'torch.distributed.init_process_group', 'torch.distributed.init_process_group', ([], {'backend': '"""nccl"""'}), "(backend='nccl')\n", (32039, 32055), False, 'import torch\n'), ((33154, 33181), 'torch.distributed.barrier', 'torch.distributed.barrier', ([], {}), '()\n', (33179, 33181), False, 'import torch\n'), ((34476, 34503), 'torch.distributed.barrier', 'torch.distributed.barrier', ([], {}), '()\n', (34501, 34503), False, 'import torch\n'), ((34655, 34678), 'torch.nn.Linear', 'torch.nn.Linear', (['(768)', '(2)'], {}), '(768, 2)\n', (34670, 34678), False, 'import torch\n'), ((34679, 34705), 'torch.nn.LogSoftmax', 'torch.nn.LogSoftmax', ([], {'dim': '(1)'}), '(dim=1)\n', (34698, 34705), False, 'import torch\n'), ((35064, 35171), 'transformers.LineByLineTextDataset', 'LineByLineTextDataset', ([], {'tokenizer': 'tokenizer', 'file_path': 'args.mlm_datapath', 'block_size': 'args.max_seq_length'}), '(tokenizer=tokenizer, file_path=args.mlm_datapath,\n block_size=args.max_seq_length)\n', (35085, 35171), False, 'from transformers import AdamW, BertConfig, BertForSequenceClassification, BertForMaskedLM, XLMRobertaForMaskedLM, BertTokenizer, XLMConfig, XLMForSequenceClassification, XLMTokenizer, XLMRobertaConfig, XLMRobertaForSequenceClassification, XLMRobertaTokenizer, get_linear_schedule_with_warmup, AutoTokenizer, AutoModelForSequenceClassification, DataCollatorForLanguageModeling, LineByLineTextDataset\n'), ((3547, 3588), 'torch.tensor', 'torch.tensor', (["batch_encoding['input_ids']"], {}), "(batch_encoding['input_ids'])\n", (3559, 3588), False, 'import torch\n'), ((3589, 3635), 'torch.tensor', 'torch.tensor', (["batch_encoding['token_type_ids']"], {}), "(batch_encoding['token_type_ids'])\n", (3601, 3635), False, 'import torch\n'), ((3650, 3696), 'torch.tensor', 'torch.tensor', (["batch_encoding['attention_mask']"], {}), "(batch_encoding['attention_mask'])\n", (3662, 3696), False, 'import torch\n'), ((8539, 8559), 'random.uniform', 'random.uniform', (['(0)', '(1)'], {}), '(0, 1)\n', (8553, 8559), False, 'import random\n'), ((16782, 16810), 'os.makedirs', 'os.makedirs', (['eval_output_dir'], {}), '(eval_output_dir)\n', (16793, 16810), False, 'import os\n'), ((17183, 17211), 'torch.nn.DataParallel', 'torch.nn.DataParallel', (['model'], {}), '(model)\n', (17204, 17211), False, 'import torch\n'), ((19908, 19937), 'numpy.argmax', 'np.argmax', (['eval_preds'], {'axis': '(1)'}), '(eval_preds, axis=1)\n', (19917, 19937), True, 'import numpy as np\n'), ((21996, 22039), 'os.path.join', 'os.path.join', (['args.data_dir', '"""english_MNLI"""'], {}), "(args.data_dir, 'english_MNLI')\n", (22008, 22039), False, 'import os\n'), ((24009, 24060), 'os.path.join', 'os.path.join', (['args.data_dir', '"""romanised_hindi_MNLI"""'], {}), "(args.data_dir, 'romanised_hindi_MNLI')\n", (24021, 24060), False, 'import os\n'), ((24107, 24158), 'os.path.join', 'os.path.join', (['args.data_dir', '"""romanised_hindi_MNLI"""'], {}), "(args.data_dir, 'romanised_hindi_MNLI')\n", (24119, 24158), False, 'import os\n'), ((31075, 31107), 'os.path.exists', 'os.path.exists', (['args.save_folder'], {}), '(args.save_folder)\n', (31089, 31107), False, 'import os\n'), ((31743, 31768), 'torch.cuda.device_count', 'torch.cuda.device_count', ([], {}), '()\n', (31766, 31768), False, 'import torch\n'), ((7151, 7185), 'torch.distributed.get_world_size', 'torch.distributed.get_world_size', ([], {}), '()\n', (7183, 7185), False, 'import torch\n'), ((16706, 16737), 'os.path.exists', 'os.path.exists', (['eval_output_dir'], {}), '(eval_output_dir)\n', (16720, 16737), False, 'import os\n'), ((17739, 17754), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (17752, 17754), False, 'import torch\n'), ((22169, 22212), 'os.path.join', 'os.path.join', (['args.data_dir', '"""english_MNLI"""'], {}), "(args.data_dir, 'english_MNLI')\n", (22181, 22212), False, 'import os\n'), ((22259, 22302), 'os.path.join', 'os.path.join', (['args.data_dir', '"""english_MNLI"""'], {}), "(args.data_dir, 'english_MNLI')\n", (22271, 22302), False, 'import os\n'), ((11043, 11066), 'torch.max', 'torch.max', (['nli_pred', '(-1)'], {}), '(nli_pred, -1)\n', (11052, 11066), False, 'import torch\n'), ((17894, 17938), 'torch.cat', 'torch.cat', (['(eval_batch[0], eval_batch[4])', '(0)'], {}), '((eval_batch[0], eval_batch[4]), 0)\n', (17903, 17938), False, 'import torch\n'), ((17956, 18000), 'torch.cat', 'torch.cat', (['(eval_batch[1], eval_batch[5])', '(0)'], {}), '((eval_batch[1], eval_batch[5]), 0)\n', (17965, 18000), False, 'import torch\n'), ((18902, 18946), 'torch.cat', 'torch.cat', (['(eval_batch[3], eval_batch[7])', '(0)'], {}), '((eval_batch[3], eval_batch[7]), 0)\n', (18911, 18946), False, 'import torch\n'), ((20175, 20210), 'numpy.equal', 'np.equal', (['eval_preds', 'out_label_ids'], {}), '(eval_preds, out_label_ids)\n', (20183, 20210), True, 'import numpy as np\n'), ((31640, 31665), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (31663, 31665), False, 'import torch\n'), ((8914, 8992), 'torch.utils.data.DataLoader', 'DataLoader', (['nli_dataset'], {'sampler': 'nli_sampler', 'batch_size': 'args.train_batch_size'}), '(nli_dataset, sampler=nli_sampler, batch_size=args.train_batch_size)\n', (8924, 8992), False, 'from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset, Dataset\n'), ((9870, 9912), 'torch.cat', 'torch.cat', (['(batch_nli[0], batch_nli[4])', '(0)'], {}), '((batch_nli[0], batch_nli[4]), 0)\n', (9879, 9912), False, 'import torch\n'), ((9930, 9972), 'torch.cat', 'torch.cat', (['(batch_nli[1], batch_nli[5])', '(0)'], {}), '((batch_nli[1], batch_nli[5]), 0)\n', (9939, 9972), False, 'import torch\n'), ((11530, 11572), 'torch.cat', 'torch.cat', (['(batch_nli[3], batch_nli[7])', '(0)'], {}), '((batch_nli[3], batch_nli[7]), 0)\n', (11539, 11572), False, 'import torch\n'), ((12947, 13047), 'torch.utils.data.DataLoader', 'DataLoader', (['mlm_dataset'], {'collate_fn': 'data_collator.collate_batch', 'batch_size': 'args.mlm_batch_size'}), '(mlm_dataset, collate_fn=data_collator.collate_batch, batch_size=\n args.mlm_batch_size)\n', (12957, 13047), False, 'from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset, Dataset\n'), ((18389, 18433), 'torch.cat', 'torch.cat', (['(eval_batch[2], eval_batch[6])', '(0)'], {}), '((eval_batch[2], eval_batch[6]), 0)\n', (18398, 18433), False, 'import torch\n'), ((10545, 10587), 'torch.cat', 'torch.cat', (['(batch_nli[2], batch_nli[6])', '(0)'], {}), '((batch_nli[2], batch_nli[6]), 0)\n', (10554, 10587), False, 'import torch\n'), ((15825, 15872), 'os.path.join', 'os.path.join', (['args.save_folder', '"""nli_layer.bin"""'], {}), "(args.save_folder, 'nli_layer.bin')\n", (15837, 15872), False, 'import os\n'), ((15914, 15965), 'os.path.join', 'os.path.join', (['args.save_folder', '"""training_args.bin"""'], {}), "(args.save_folder, 'training_args.bin')\n", (15926, 15965), False, 'import os\n'), ((11337, 11379), 'torch.cat', 'torch.cat', (['(batch_nli[3], batch_nli[7])', '(0)'], {}), '((batch_nli[3], batch_nli[7]), 0)\n', (11346, 11379), False, 'import torch\n')] |
#!/usr/bin/env python
# coding: utf-8
# In[80]:
#Кластеризация Piplines
#1 only this implimented
# train BOF[:topN] 20k -> SentenceTransformer -> AgglomerativeClustering -> KNeighborsClassifier
# inference predict KNeighborsClassifier
#2 bs 700k sample -> SentenceTransformer -> BKmeans
#3 bs 50k sapmle -> SentenceTransformer -> AgglomerativeClustering
import sys
from itertools import chain
from typing import Dict
# sys.path.append("path/to/YandexCup")
import pandas as pd
import pickle
import torch
from torch.utils.data import DataLoader
from sklearn.decomposition import PCA
import numpy as np
from src.utils.Preprocessing_text import PreprocText,config_prep_text
from sentence_transformers import SentenceTransformer
config = {"path_model": "model/KnnClassif.pkl",
"name_embeder": "all-MiniLM-L6-v2",
"path_to_data": "Test.csv",
"preproc_data": False,
}
class ClasteringData:
def __init__(self,config:Dict,):
class Args:
def __init__(self,cfg):
for name,value in cfg.items():
setattr(self,name,value)
self.args = Args(config)
self.embedder = SentenceTransformer(self.args.name_embeder)
with open(self.args.path_model, "rb") as m:
self.clust_model = pickle.load(m)
if self.args.preproc_data:
config_prep_text["path_to_csv"]= config_prep_text["path_from_csv"] = self.args.path_to_data
PreprocText(config_prep_text).processing_from_csv()
self.data = pd.read_csv(self.args.path_to_data)
def _chunk_data(self,chunk):
df = self.data[chunk[0]:chunk[1]]
texts = list(chain.from_iterable([text.split("SEP") for text in df["text"]]))
class_count = [len(text.split("SEP")) for text in df["text"]]
return texts, class_count
def _mean_tensor(self,embedings,class_count):
step = [0,0]
new_emb = torch.zeros((len(class_count),embedings.shape[1]),)
for i, cl_c in enumerate(class_count):
if cl_c == 0:
continue
step[1] += cl_c
new_emb[i] = torch.mean(embedings[step[0]:step[1]], 0)
step[0] += cl_c
return new_emb
def cluster_data_pipline1(self,bs = 200000):
chunk = [0, 0]
cluster_assignment = []
for i in range(1,len(self.data)//bs+2):
chunk[1]+=bs
data, class_count = self._chunk_data(chunk)
# Corpus with example sentences
corpus_embeddings = self.embedder.encode(data)
# Normalize the embeddings to unit length
corpus_embeddings = corpus_embeddings / np.linalg.norm(corpus_embeddings, axis=1, keepdims=True)
#means tesor
corpus_embeddings = self._mean_tensor(torch.tensor(corpus_embeddings), class_count)
# Perform kmean clustering
cluster_assignment.append(self.clust_model.predict(corpus_embeddings))
chunk[0] = chunk[1]
cluster_assignment = list(chain.from_iterable(cluster_assignment))
assert(len(self.data)) == len(cluster_assignment)
self.data["id_claster"] = cluster_assignment
# In[84]:
| [
"sentence_transformers.SentenceTransformer",
"pandas.read_csv",
"torch.mean",
"pickle.load",
"itertools.chain.from_iterable",
"torch.tensor",
"src.utils.Preprocessing_text.PreprocText",
"numpy.linalg.norm"
] | [((1172, 1215), 'sentence_transformers.SentenceTransformer', 'SentenceTransformer', (['self.args.name_embeder'], {}), '(self.args.name_embeder)\n', (1191, 1215), False, 'from sentence_transformers import SentenceTransformer\n'), ((1572, 1607), 'pandas.read_csv', 'pd.read_csv', (['self.args.path_to_data'], {}), '(self.args.path_to_data)\n', (1583, 1607), True, 'import pandas as pd\n'), ((1308, 1322), 'pickle.load', 'pickle.load', (['m'], {}), '(m)\n', (1319, 1322), False, 'import pickle\n'), ((2175, 2216), 'torch.mean', 'torch.mean', (['embedings[step[0]:step[1]]', '(0)'], {}), '(embedings[step[0]:step[1]], 0)\n', (2185, 2216), False, 'import torch\n'), ((3082, 3121), 'itertools.chain.from_iterable', 'chain.from_iterable', (['cluster_assignment'], {}), '(cluster_assignment)\n', (3101, 3121), False, 'from itertools import chain\n'), ((2716, 2772), 'numpy.linalg.norm', 'np.linalg.norm', (['corpus_embeddings'], {'axis': '(1)', 'keepdims': '(True)'}), '(corpus_embeddings, axis=1, keepdims=True)\n', (2730, 2772), True, 'import numpy as np\n'), ((2848, 2879), 'torch.tensor', 'torch.tensor', (['corpus_embeddings'], {}), '(corpus_embeddings)\n', (2860, 2879), False, 'import torch\n'), ((1487, 1516), 'src.utils.Preprocessing_text.PreprocText', 'PreprocText', (['config_prep_text'], {}), '(config_prep_text)\n', (1498, 1516), False, 'from src.utils.Preprocessing_text import PreprocText, config_prep_text\n')] |
# @author lucasmiranda42
# encoding: utf-8
# module deepof
"""
Testing module for deepof.train_utils
"""
import os
import numpy as np
import tensorflow as tf
from hypothesis import HealthCheck
from hypothesis import given
from hypothesis import settings
from hypothesis import strategies as st
from hypothesis.extra.numpy import arrays
import deepof.data
import deepof.model_utils
import deepof.train_utils
def test_load_treatments():
assert deepof.train_utils.load_treatments("tests") is None
assert isinstance(
deepof.train_utils.load_treatments(
os.path.join("tests", "test_examples", "test_single_topview", "Others")
),
dict,
)
@given(
X_train=arrays(
shape=st.tuples(st.integers(min_value=1, max_value=1000), st.just(24)),
dtype=float,
elements=st.floats(
min_value=0.0,
max_value=1,
),
),
batch_size=st.integers(min_value=128, max_value=512),
loss=st.one_of(st.just("test_A"), st.just("test_B")),
next_sequence_prediction=st.floats(min_value=0.0, max_value=1.0),
phenotype_prediction=st.floats(min_value=0.0, max_value=1.0),
supervised_prediction=st.floats(min_value=0.0, max_value=1.0),
overlap_loss=st.floats(min_value=0.0, max_value=1.0),
)
def test_get_callbacks(
X_train,
batch_size,
next_sequence_prediction,
phenotype_prediction,
supervised_prediction,
overlap_loss,
loss,
):
callbacks = deepof.train_utils.get_callbacks(
X_train=X_train,
batch_size=batch_size,
phenotype_prediction=phenotype_prediction,
next_sequence_prediction=next_sequence_prediction,
supervised_prediction=supervised_prediction,
overlap_loss=overlap_loss,
loss=loss,
input_type=False,
cp=True,
reg_cat_clusters=False,
reg_cluster_variance=False,
logparam={"encoding": 2, "k": 15},
)
assert np.any([isinstance(i, str) for i in callbacks])
assert np.any(
[isinstance(i, tf.keras.callbacks.ModelCheckpoint) for i in callbacks]
)
assert np.any(
[isinstance(i, deepof.model_utils.one_cycle_scheduler) for i in callbacks]
)
@settings(max_examples=16, deadline=None, suppress_health_check=[HealthCheck.too_slow])
@given(
loss=st.one_of(st.just("ELBO"), st.just("MMD")),
next_sequence_prediction=st.one_of(st.just(0.0), st.just(1.0)),
phenotype_prediction=st.one_of(st.just(0.0), st.just(1.0)),
supervised_prediction=st.one_of(st.just(0.0), st.just(1.0)),
)
def test_autoencoder_fitting(
loss,
next_sequence_prediction,
supervised_prediction,
phenotype_prediction,
):
X_train = np.ones([20, 5, 6]).astype(float)
y_train = np.ones([20, 1]).astype(float)
if supervised_prediction:
y_train = np.concatenate([y_train, np.ones([20, 6]).astype(float)], axis=1)
if next_sequence_prediction:
y_train = y_train[1:]
preprocessed_data = (X_train, y_train, X_train, y_train)
prun = deepof.data.Project(
path=os.path.join(".", "tests", "test_examples", "test_single_topview"),
arena="circular",
arena_dims=380,
video_format=".mp4",
).run()
prun.deep_unsupervised_embedding(
preprocessed_data,
batch_size=10,
encoding_size=2,
epochs=1,
kl_warmup=1,
log_history=True,
log_hparams=True,
mmd_warmup=1,
n_components=2,
loss=loss,
overlap_loss=0.1,
next_sequence_prediction=next_sequence_prediction,
phenotype_prediction=phenotype_prediction,
supervised_prediction=supervised_prediction,
entropy_knn=5,
)
@settings(
max_examples=4,
deadline=None,
suppress_health_check=[HealthCheck.too_slow],
derandomize=True,
stateful_step_count=1,
)
@given(
hpt_type=st.one_of(st.just("bayopt"), st.just("hyperband")),
loss=st.one_of(st.just("ELBO"), st.just("MMD")),
)
def test_tune_search(
hpt_type,
loss,
):
overlap_loss = 0.1
next_sequence_prediction = 0.1
phenotype_prediction = 0.1
supervised_prediction = 0.1
X_train = np.ones([100, 5, 6]).astype(float)
y_train = np.ones([100, 1]).astype(float)
callbacks = list(
deepof.train_utils.get_callbacks(
X_train=X_train,
batch_size=25,
phenotype_prediction=phenotype_prediction,
next_sequence_prediction=next_sequence_prediction,
supervised_prediction=supervised_prediction,
loss=loss,
input_type=False,
cp=False,
reg_cat_clusters=True,
reg_cluster_variance=True,
overlap_loss=overlap_loss,
entropy_knn=5,
outpath="unsupervised_tuner_search",
logparam={"encoding": 2, "k": 5},
)
)[1:]
deepof.train_utils.tune_search(
data=[X_train, y_train, X_train, y_train],
batch_size=25,
encoding_size=2,
hpt_type=hpt_type,
hypertun_trials=1,
k=5,
kl_warmup_epochs=0,
loss=loss,
mmd_warmup_epochs=0,
overlap_loss=overlap_loss,
next_sequence_prediction=next_sequence_prediction,
phenotype_prediction=phenotype_prediction,
supervised_prediction=supervised_prediction,
project_name="test_run",
callbacks=callbacks,
n_epochs=1,
)
| [
"numpy.ones",
"hypothesis.strategies.integers",
"os.path.join",
"hypothesis.strategies.floats",
"hypothesis.strategies.just",
"hypothesis.settings"
] | [((2220, 2311), 'hypothesis.settings', 'settings', ([], {'max_examples': '(16)', 'deadline': 'None', 'suppress_health_check': '[HealthCheck.too_slow]'}), '(max_examples=16, deadline=None, suppress_health_check=[HealthCheck\n .too_slow])\n', (2228, 2311), False, 'from hypothesis import settings\n'), ((3724, 3855), 'hypothesis.settings', 'settings', ([], {'max_examples': '(4)', 'deadline': 'None', 'suppress_health_check': '[HealthCheck.too_slow]', 'derandomize': '(True)', 'stateful_step_count': '(1)'}), '(max_examples=4, deadline=None, suppress_health_check=[HealthCheck.\n too_slow], derandomize=True, stateful_step_count=1)\n', (3732, 3855), False, 'from hypothesis import settings\n'), ((932, 973), 'hypothesis.strategies.integers', 'st.integers', ([], {'min_value': '(128)', 'max_value': '(512)'}), '(min_value=128, max_value=512)\n', (943, 973), True, 'from hypothesis import strategies as st\n'), ((1062, 1101), 'hypothesis.strategies.floats', 'st.floats', ([], {'min_value': '(0.0)', 'max_value': '(1.0)'}), '(min_value=0.0, max_value=1.0)\n', (1071, 1101), True, 'from hypothesis import strategies as st\n'), ((1128, 1167), 'hypothesis.strategies.floats', 'st.floats', ([], {'min_value': '(0.0)', 'max_value': '(1.0)'}), '(min_value=0.0, max_value=1.0)\n', (1137, 1167), True, 'from hypothesis import strategies as st\n'), ((1195, 1234), 'hypothesis.strategies.floats', 'st.floats', ([], {'min_value': '(0.0)', 'max_value': '(1.0)'}), '(min_value=0.0, max_value=1.0)\n', (1204, 1234), True, 'from hypothesis import strategies as st\n'), ((1253, 1292), 'hypothesis.strategies.floats', 'st.floats', ([], {'min_value': '(0.0)', 'max_value': '(1.0)'}), '(min_value=0.0, max_value=1.0)\n', (1262, 1292), True, 'from hypothesis import strategies as st\n'), ((585, 656), 'os.path.join', 'os.path.join', (['"""tests"""', '"""test_examples"""', '"""test_single_topview"""', '"""Others"""'], {}), "('tests', 'test_examples', 'test_single_topview', 'Others')\n", (597, 656), False, 'import os\n'), ((994, 1011), 'hypothesis.strategies.just', 'st.just', (['"""test_A"""'], {}), "('test_A')\n", (1001, 1011), True, 'from hypothesis import strategies as st\n'), ((1013, 1030), 'hypothesis.strategies.just', 'st.just', (['"""test_B"""'], {}), "('test_B')\n", (1020, 1030), True, 'from hypothesis import strategies as st\n'), ((2708, 2727), 'numpy.ones', 'np.ones', (['[20, 5, 6]'], {}), '([20, 5, 6])\n', (2715, 2727), True, 'import numpy as np\n'), ((2756, 2772), 'numpy.ones', 'np.ones', (['[20, 1]'], {}), '([20, 1])\n', (2763, 2772), True, 'import numpy as np\n'), ((2334, 2349), 'hypothesis.strategies.just', 'st.just', (['"""ELBO"""'], {}), "('ELBO')\n", (2341, 2349), True, 'from hypothesis import strategies as st\n'), ((2351, 2365), 'hypothesis.strategies.just', 'st.just', (['"""MMD"""'], {}), "('MMD')\n", (2358, 2365), True, 'from hypothesis import strategies as st\n'), ((2407, 2419), 'hypothesis.strategies.just', 'st.just', (['(0.0)'], {}), '(0.0)\n', (2414, 2419), True, 'from hypothesis import strategies as st\n'), ((2421, 2433), 'hypothesis.strategies.just', 'st.just', (['(1.0)'], {}), '(1.0)\n', (2428, 2433), True, 'from hypothesis import strategies as st\n'), ((2471, 2483), 'hypothesis.strategies.just', 'st.just', (['(0.0)'], {}), '(0.0)\n', (2478, 2483), True, 'from hypothesis import strategies as st\n'), ((2485, 2497), 'hypothesis.strategies.just', 'st.just', (['(1.0)'], {}), '(1.0)\n', (2492, 2497), True, 'from hypothesis import strategies as st\n'), ((2536, 2548), 'hypothesis.strategies.just', 'st.just', (['(0.0)'], {}), '(0.0)\n', (2543, 2548), True, 'from hypothesis import strategies as st\n'), ((2550, 2562), 'hypothesis.strategies.just', 'st.just', (['(1.0)'], {}), '(1.0)\n', (2557, 2562), True, 'from hypothesis import strategies as st\n'), ((4188, 4208), 'numpy.ones', 'np.ones', (['[100, 5, 6]'], {}), '([100, 5, 6])\n', (4195, 4208), True, 'import numpy as np\n'), ((4237, 4254), 'numpy.ones', 'np.ones', (['[100, 1]'], {}), '([100, 1])\n', (4244, 4254), True, 'import numpy as np\n'), ((3905, 3922), 'hypothesis.strategies.just', 'st.just', (['"""bayopt"""'], {}), "('bayopt')\n", (3912, 3922), True, 'from hypothesis import strategies as st\n'), ((3924, 3944), 'hypothesis.strategies.just', 'st.just', (['"""hyperband"""'], {}), "('hyperband')\n", (3931, 3944), True, 'from hypothesis import strategies as st\n'), ((3966, 3981), 'hypothesis.strategies.just', 'st.just', (['"""ELBO"""'], {}), "('ELBO')\n", (3973, 3981), True, 'from hypothesis import strategies as st\n'), ((3983, 3997), 'hypothesis.strategies.just', 'st.just', (['"""MMD"""'], {}), "('MMD')\n", (3990, 3997), True, 'from hypothesis import strategies as st\n'), ((836, 873), 'hypothesis.strategies.floats', 'st.floats', ([], {'min_value': '(0.0)', 'max_value': '(1)'}), '(min_value=0.0, max_value=1)\n', (845, 873), True, 'from hypothesis import strategies as st\n'), ((742, 782), 'hypothesis.strategies.integers', 'st.integers', ([], {'min_value': '(1)', 'max_value': '(1000)'}), '(min_value=1, max_value=1000)\n', (753, 782), True, 'from hypothesis import strategies as st\n'), ((784, 795), 'hypothesis.strategies.just', 'st.just', (['(24)'], {}), '(24)\n', (791, 795), True, 'from hypothesis import strategies as st\n'), ((3074, 3140), 'os.path.join', 'os.path.join', (['"""."""', '"""tests"""', '"""test_examples"""', '"""test_single_topview"""'], {}), "('.', 'tests', 'test_examples', 'test_single_topview')\n", (3086, 3140), False, 'import os\n'), ((2861, 2877), 'numpy.ones', 'np.ones', (['[20, 6]'], {}), '([20, 6])\n', (2868, 2877), True, 'import numpy as np\n')] |
import scipy.io as sio;
import numpy;
from numpy import sin, linspace, pi
from pylab import plot, show, title, xlabel, ylabel, subplot
from scipy import fft, arange
import time;
def getFFT(y, Fs):
L = len(y);
Y = numpy.fft.rfft(y);
freq = numpy.fft.fftfreq(L);
plot(freq, Y.real);
show();
x = sio.loadmat("Sub1_singletarget.mat");
eegData = x["Data"]["EEG"];
print(x["Data"])
eegData = numpy.asmatrix(eegData[0][0]);
d0 = eegData[:,2];
print(len(d0));
print (numpy.asarray(d0));
(Hz, dataFFT) = eeg.computeFFT(d0, 512);
plot(Hz, dataFFT);
show(); | [
"numpy.asmatrix",
"pylab.plot",
"scipy.io.loadmat",
"numpy.fft.fftfreq",
"numpy.asarray",
"numpy.fft.rfft",
"pylab.show"
] | [((316, 352), 'scipy.io.loadmat', 'sio.loadmat', (['"""Sub1_singletarget.mat"""'], {}), "('Sub1_singletarget.mat')\n", (327, 352), True, 'import scipy.io as sio\n'), ((409, 438), 'numpy.asmatrix', 'numpy.asmatrix', (['eegData[0][0]'], {}), '(eegData[0][0])\n', (423, 438), False, 'import numpy\n'), ((544, 561), 'pylab.plot', 'plot', (['Hz', 'dataFFT'], {}), '(Hz, dataFFT)\n', (548, 561), False, 'from pylab import plot, show, title, xlabel, ylabel, subplot\n'), ((563, 569), 'pylab.show', 'show', ([], {}), '()\n', (567, 569), False, 'from pylab import plot, show, title, xlabel, ylabel, subplot\n'), ((223, 240), 'numpy.fft.rfft', 'numpy.fft.rfft', (['y'], {}), '(y)\n', (237, 240), False, 'import numpy\n'), ((253, 273), 'numpy.fft.fftfreq', 'numpy.fft.fftfreq', (['L'], {}), '(L)\n', (270, 273), False, 'import numpy\n'), ((279, 297), 'pylab.plot', 'plot', (['freq', 'Y.real'], {}), '(freq, Y.real)\n', (283, 297), False, 'from pylab import plot, show, title, xlabel, ylabel, subplot\n'), ((303, 309), 'pylab.show', 'show', ([], {}), '()\n', (307, 309), False, 'from pylab import plot, show, title, xlabel, ylabel, subplot\n'), ((482, 499), 'numpy.asarray', 'numpy.asarray', (['d0'], {}), '(d0)\n', (495, 499), False, 'import numpy\n')] |
from .learning_curves import LearningCurve
import matplotlib.pyplot as plt
import numpy as np
class LearningCurveCombined():
""" Provide helper functions to plot, fit and extrapolate learning curve using multiple learning curves."""
def __init__(self, n):
""" Instantiante a LearningCurveCombined object.
Args:
n (int): Number of learning curves to use. More learning curves will result in a better estimation
of the extrapolation but will be longer to compute.
"""
self.lcs = [LearningCurve(name=f"cv_{i}") for i in range(n)]
def train(self, *args, **kwargs):
""" Train all learning curves using :meth:`LearningCurve.train` method. Parameters are forwarded to this method."""
for i, lc in enumerate(self.lcs):
if "verbose" in kwargs and kwargs["verbose"] > 0:
print(f"[LearningCurveCV] {i} / {len(self.lcs)}")
lc.train(*args, **kwargs)
def get_scores(self, train_sizes, predictor="best"):
""" Fit each learning curve and compute the scores for the given predictor.
Args:
train_sizes (list): array of train sizes.
predictor (string, Predictor): Predictor to use.
Returns:
List: list of size n containing arrays with the same length as train_sizes
"""
ret = []
for lc in self.lcs:
lc.fit_all()
ret.append(lc.get_predictor(predictor)(train_sizes))
return ret
def get_dist(self, scores):
""" Compute the mean and the standard deviation of the result of :meth:`LearningCurveCombined.get_scores` """
return np.mean(scores, axis=0), np.std(scores, axis=0)
def plot(self, target=None, figsize=(12, 6), close=True, legend=True):
""" Plot the combined learning curve.
Args:
target (int): Training size to reach. The training size axis will be extended and the fitted curve extrapolated until reaching this value.
figsize (2uple): Size of the figure
close (bool): If True, close the figure before returning it. This is usefull if a lot of plots are being created because Matplotlib won't close
them, potentially leading to warnings. If False, the plot will not be closed.
This can be desired when working on Jupyter notebooks, so that the plot will be rendered in the output of the cell.
legend (bool): Controls whether to show legend or not.
Returns:
fig (Matplotlib.figure): The resulting plot
"""
if len(self.lcs[0].recorder) == 0:
raise RuntimeError("recorder is empty. You must first compute learning curve data points using the train method.")
fig = plt.figure(figsize=figsize)
train_sizes = self.lcs[0].recorder["train_sizes"]
scores = self.get_scores(train_sizes)
scores_mean, scores_std = self.get_dist(scores)
plt.title(f"Combined learning curve (N={len(self.lcs)})")
plt.grid()
plt.xlabel(f"Training sizes")
plt.ylabel(f"Scores")
plt.plot(train_sizes, scores_mean, "o-", label="Averaged scores")
plt.fill_between(train_sizes, scores_mean - scores_std, scores_mean + scores_std, color="r", alpha=0.15, label="Standard deviation")
if target is not None:
y_target = self.target(target)
plt.errorbar(target, y_target[0], y_target[1], fmt="o-", label=f"target:{target}")
train_sizes = np.linspace(train_sizes[-1], target)
scores = self.get_scores(train_sizes)
scores_mean, scores_std = self.get_dist(scores)
plt.plot(train_sizes, scores_mean, "--", label="Averaged extrapolation")
plt.fill_between(train_sizes, scores_mean - scores_std, scores_mean + scores_std, color="r", alpha=0.15)
if legend is True:
plt.legend(loc=4)
if close is True:
plt.close(fig)
return fig
def plot_all(self, legend=True, **kwargs):
""" Calls :meth:`LearningCurve.compare` to plot the different learning curves.
Args:
legend (bool): Controls whether to show legend or not.
"""
fig = LearningCurve.compare(self.lcs, **kwargs)
if legend is False:
fig.axes[0].get_legend().remove()
return fig
def plot_times(self, **kwargs):
""" Calls :meth:`LearningCurve.compare_time` to plot the different learning curves times. """
return LearningCurve.compare_time(self.lcs, **kwargs)
def target(self, n):
""" Shorcut to get the mean and the standard deviation for one value. """
return self.get_dist(self.get_scores([n]))
def fit_all(self, **kwargs):
""" Fit each learning curve. """
for lc in self.lcs:
lc.fit_all(**kwargs) | [
"numpy.mean",
"matplotlib.pyplot.grid",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.errorbar",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.fill_between",
"matplotlib.pyplot.close",
"matplotlib.pyplot.figure",
"numpy.linspace",
"numpy.std",
"matplotlib.pyplot.leg... | [((2927, 2954), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': 'figsize'}), '(figsize=figsize)\n', (2937, 2954), True, 'import matplotlib.pyplot as plt\n'), ((3198, 3208), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (3206, 3208), True, 'import matplotlib.pyplot as plt\n'), ((3218, 3247), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['f"""Training sizes"""'], {}), "(f'Training sizes')\n", (3228, 3247), True, 'import matplotlib.pyplot as plt\n'), ((3257, 3278), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['f"""Scores"""'], {}), "(f'Scores')\n", (3267, 3278), True, 'import matplotlib.pyplot as plt\n'), ((3288, 3353), 'matplotlib.pyplot.plot', 'plt.plot', (['train_sizes', 'scores_mean', '"""o-"""'], {'label': '"""Averaged scores"""'}), "(train_sizes, scores_mean, 'o-', label='Averaged scores')\n", (3296, 3353), True, 'import matplotlib.pyplot as plt\n'), ((3363, 3499), 'matplotlib.pyplot.fill_between', 'plt.fill_between', (['train_sizes', '(scores_mean - scores_std)', '(scores_mean + scores_std)'], {'color': '"""r"""', 'alpha': '(0.15)', 'label': '"""Standard deviation"""'}), "(train_sizes, scores_mean - scores_std, scores_mean +\n scores_std, color='r', alpha=0.15, label='Standard deviation')\n", (3379, 3499), True, 'import matplotlib.pyplot as plt\n'), ((1766, 1789), 'numpy.mean', 'np.mean', (['scores'], {'axis': '(0)'}), '(scores, axis=0)\n', (1773, 1789), True, 'import numpy as np\n'), ((1791, 1813), 'numpy.std', 'np.std', (['scores'], {'axis': '(0)'}), '(scores, axis=0)\n', (1797, 1813), True, 'import numpy as np\n'), ((3587, 3674), 'matplotlib.pyplot.errorbar', 'plt.errorbar', (['target', 'y_target[0]', 'y_target[1]'], {'fmt': '"""o-"""', 'label': 'f"""target:{target}"""'}), "(target, y_target[0], y_target[1], fmt='o-', label=\n f'target:{target}')\n", (3599, 3674), True, 'import matplotlib.pyplot as plt\n'), ((3699, 3735), 'numpy.linspace', 'np.linspace', (['train_sizes[-1]', 'target'], {}), '(train_sizes[-1], target)\n', (3710, 3735), True, 'import numpy as np\n'), ((3861, 3933), 'matplotlib.pyplot.plot', 'plt.plot', (['train_sizes', 'scores_mean', '"""--"""'], {'label': '"""Averaged extrapolation"""'}), "(train_sizes, scores_mean, '--', label='Averaged extrapolation')\n", (3869, 3933), True, 'import matplotlib.pyplot as plt\n'), ((3947, 4055), 'matplotlib.pyplot.fill_between', 'plt.fill_between', (['train_sizes', '(scores_mean - scores_std)', '(scores_mean + scores_std)'], {'color': '"""r"""', 'alpha': '(0.15)'}), "(train_sizes, scores_mean - scores_std, scores_mean +\n scores_std, color='r', alpha=0.15)\n", (3963, 4055), True, 'import matplotlib.pyplot as plt\n'), ((4095, 4112), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '(4)'}), '(loc=4)\n', (4105, 4112), True, 'import matplotlib.pyplot as plt\n'), ((4155, 4169), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (4164, 4169), True, 'import matplotlib.pyplot as plt\n')] |
import pytest
tf = pytest.importorskip("tensorflow")
trt = pytest.importorskip("tensorrt")
uff = pytest.importorskip("uff")
engine_glob = ''
def create_dummy_engine(resourcepath):
global engine_glob
model = tf.placeholder(tf.float32, [None, 28, 28, 1], name='input')
model = tf.layers.conv2d(model, 64, 5, 2, padding='SAME', activation=None, name='conv1', reuse=tf.AUTO_REUSE)
model = tf.nn.relu(model, name='output')
sess = tf.Session()
sess.run(tf.global_variables_initializer())
graphdef = tf.get_default_graph().as_graph_def()
frozen_graph = tf.graph_util.convert_variables_to_constants(sess, graphdef,
['output'])
tf_model = tf.graph_util.remove_training_nodes(frozen_graph)
uff_model = uff.from_tensorflow(tf_model, ['output'])
uff_parser = trt.parsers.uffparser.create_uff_parser()
uff_parser.register_input('input', (1, 28, 28), 0)
uff_parser.register_output('output')
G_LOGGER = trt.infer.ConsoleLogger(trt.infer.LogSeverity.ERROR)
engine = trt.utils.uff_to_trt_engine(G_LOGGER, uff_model, uff_parser, 1, 1 << 20)
uff_parser.destroy()
engine_glob = engine
@pytest.mark.engine("theano_engine")
@pytest.mark.engine("numpy_engine")
def test_tensorrt_flowmodule(runtime, test_nodenet, resourcepath, default_world):
if engine_glob is '':
create_dummy_engine(resourcepath)
import os
os.makedirs(os.path.join(resourcepath, 'nodetypes'), exist_ok=True)
filename = os.path.join(resourcepath, 'nodetypes', 'dummy.engine')
trt.utils.write_engine_to_file(filename, engine_glob.serialize())
res, errors = runtime.reload_code()
assert res
assert 'dummy.engine' in runtime.native_modules
assert runtime.native_modules['flow_module']
assert runtime.native_modules['is_tensorrt_engine']
assert runtime.native_modules['name'] == ['dummy.engine']
assert runtime.native_modules['inputs'] == ['input']
assert runtime.native_modules['outputs'] == ['output']
assert runtime.native_modules['path'] == filename
assert runtime.native_modules['category'] == ''
assert 'dummy.engine' in runtime.nodenets[test_nodenet].native_modules
netapi = runtime.nodenets[test_nodenet].netapi
dummy = netapi.create_node('dummy.engine')
import numpy as np
dummy._initfunction(netapi, dummy, {})
res = dummy._flowfunction(np.zeros([1, 28, 28]), netapi, dummy)
assert res.shape == (64, 14, 14)
| [
"pytest.mark.engine",
"pytest.importorskip",
"os.path.join",
"numpy.zeros"
] | [((21, 54), 'pytest.importorskip', 'pytest.importorskip', (['"""tensorflow"""'], {}), "('tensorflow')\n", (40, 54), False, 'import pytest\n'), ((61, 92), 'pytest.importorskip', 'pytest.importorskip', (['"""tensorrt"""'], {}), "('tensorrt')\n", (80, 92), False, 'import pytest\n'), ((99, 125), 'pytest.importorskip', 'pytest.importorskip', (['"""uff"""'], {}), "('uff')\n", (118, 125), False, 'import pytest\n'), ((1206, 1241), 'pytest.mark.engine', 'pytest.mark.engine', (['"""theano_engine"""'], {}), "('theano_engine')\n", (1224, 1241), False, 'import pytest\n'), ((1243, 1277), 'pytest.mark.engine', 'pytest.mark.engine', (['"""numpy_engine"""'], {}), "('numpy_engine')\n", (1261, 1277), False, 'import pytest\n'), ((1529, 1584), 'os.path.join', 'os.path.join', (['resourcepath', '"""nodetypes"""', '"""dummy.engine"""'], {}), "(resourcepath, 'nodetypes', 'dummy.engine')\n", (1541, 1584), False, 'import os\n'), ((1458, 1497), 'os.path.join', 'os.path.join', (['resourcepath', '"""nodetypes"""'], {}), "(resourcepath, 'nodetypes')\n", (1470, 1497), False, 'import os\n'), ((2421, 2442), 'numpy.zeros', 'np.zeros', (['[1, 28, 28]'], {}), '([1, 28, 28])\n', (2429, 2442), True, 'import numpy as np\n')] |
import os
import glob
import csv
import pandas as pd
import numpy as np
from collections import deque
from itertools import chain
from utils import rotate_quat, rotate_cross_product
class Sensor(object):
def __init__(self, name, fieldnames, data):
self.name = name
self.fieldnames = fieldnames
self.raw_data = data
self.length = data[-1, 0] - data[0, 0]
def __str__(self):
return '<Sensor "{}">'.format(self.name)
def __repr__(self):
return str(self)
def __getitem__(self, key):
if isinstance(key, tuple):
keys = [self.fieldnames.index(k) for k in key]
else:
keys = self.fieldnames.index(key)
return self.raw_data[:, keys]
class Recording(object):
def __init__(self, path, step_stride_threshold=300):
self.path = path
self.sensors = []
self.subject = 'unknown'
sensors_i = (p for p in glob.iglob(os.path.join(path, '*.csv')) if '-extra' not in p)
for sensor_log in sensors_i:
sensor_name = os.path.splitext(os.path.split(sensor_log)[-1])[0]
with open(sensor_log) as f:
reader = csv.reader(f)
try:
fieldnames = next(reader)
except StopIteration:
continue
data = np.array([self._parse_line(fieldnames, l) for l in reader])
try:
sensor = Sensor(sensor_name, fieldnames, data)
except IndexError:
print('Error: Empty sensor {}'.format(sensor_log))
else:
setattr(self, sensor_name, sensor)
self.sensors.append(sensor)
if self.foot_sensors_available:
self.filter_steps(step_stride_threshold)
else:
print('Warning: Not all foot sensors available')
with open(os.path.join(path, 'meta.txt')) as f:
lines = f.readlines()
for l in lines:
if l.startswith('now'):
self.recording_start = int(l.split(' ')[-1]) * 1e-9
elif l.startswith('name'):
self.subject = l.split(' ')[-1].strip()
def _parse_line(self, fieldnames, l):
assert len(fieldnames) == len(l), f'_parse_line({fieldnames}, {l})'
for i in range(len(l)):
if fieldnames[i].endswith('_ts'):
value = int(l[i]) * 1e-9
elif fieldnames[i].startswith('is_') or fieldnames[i] == 'running':
value = l[i] == 'true'
else:
value = float(l[i])
l[i] = value
return l
def __str__(self):
return '<{} "{}" raw-sensors={}>'.format(
os.path.split(self.path)[-1],
self.condition,
[s.name for s in self.sensors])
def __repr__(self):
return str(self)
def write(self, file_name):
# sensors = {s.name: s.raw_data for s in self.sensors}
# sensors['merged'] = self.merged
# np.savez_compressed(os.path.join(self.path, file_name),
# **sensors)
self.merged.to_msgpack(os.path.join(self.path, file_name))
def merge(self, step_margin=1.):
data_sensors = self.data_sensors
arrivals = [s['arrival_ts'] for s in data_sensors]
idc = [0] * len(data_sensors)
qs = [deque(maxlen=1) for _ in data_sensors]
result = deque()
try:
while True:
# fill queues with newest data point
new_arr = [s[idc[i]] for i, s in enumerate(arrivals)]
newest = np.argmin(new_arr)
qs[newest].append(data_sensors[newest].raw_data[idc[newest]])
idc[newest] += 1
# check if all queues contain data
if all([len(q) > 0 for q in qs]):
# create new data point containing all sensor data
# assign average timestamp
avg_timestamp = np.mean([q[0][0] for q in qs])
label = self.label_for_timestamp(avg_timestamp, step_margin)
data = [avg_timestamp, label]
# append sensor data: data fields [2:6]
data += list(chain(*(q.popleft()[2:6] for q in qs)))
result.append(data)
except IndexError:
pass
cols = ['event_ts', 'label']
for s in data_sensors:
cols += ['{}_{}'.format(s.name, fn) for fn in s.fieldnames[2:6]]
self.merged = pd.DataFrame.from_records(list(result), columns=cols)
@property
def data_sensors(self):
label_sensor_names = ('RightFootSensor', 'LeftFootSensor')
return [s for s in self.sensors if s.name not in label_sensor_names and '-extra' not in s.name]
@property
def foot_sensors_available(self):
return hasattr(self, 'RightFootSensor') and hasattr(self, 'LeftFootSensor')
def label_for_timestamp(self, timestamp, step_margin=1.):
'''TODO DOCS'''
if not self.foot_sensors_available:
return False
for s in (self.RightFootSensor, self.LeftFootSensor):
arrivals = s['arrival_ts']
ts_idx = np.searchsorted(arrivals, timestamp)
step_durations = s['duration'] * 1e-3
if ts_idx < step_durations.shape[0]:
step_start_ts = arrivals[ts_idx] - step_durations[ts_idx] - step_margin
# print(arrivals[ts_idx + 1], step_durations[ts_idx + 1], step_start_ts, timestamp)
if timestamp >= step_start_ts:
# print('in')
# step_start_ts <= timestamp <= step_arrival
return True
return False
def rotate_accelerometer(self):
acc = self.merged.as_matrix(['Accelerometer_val_x',
'Accelerometer_val_y',
'Accelerometer_val_z'])
rot = self.merged.as_matrix(['GameRotationVector_val_w',
'GameRotationVector_val_x',
'GameRotationVector_val_y',
'GameRotationVector_val_z'])
if np.isnan(rot).any():
print('WARNING: GameRotationVector data unavailable. Fallback to RotationVector.')
rot = self.merged.as_matrix(['RotationVector_val_w',
'RotationVector_val_x',
'RotationVector_val_y',
'RotationVector_val_z'])
if np.isnan(rot).any():
raise ValueError('No RotationVector data available. Cannot rotate accelerometer.')
keys = 'Rotated_Accelerometer_val_x', 'Rotated_Accelerometer_val_y', 'Rotated_Accelerometer_val_z'
rot_acc = rotate_quat(acc, rot)
self.merged = self.merged.assign(**{keys[i]: rot_acc[:, i] for i in range(len(keys))})
def normalize_accelerometer(self, norm_reference):
acc = self.merged.as_matrix(['Accelerometer_val_x',
'Accelerometer_val_y',
'Accelerometer_val_z'])
rot = self.merged.as_matrix(['GameRotationVector_val_w',
'GameRotationVector_val_x',
'GameRotationVector_val_y',
'GameRotationVector_val_z'])
if np.isnan(rot).any():
print('WARNING: GameRotationVector data unavailable. Fallback to RotationVector.')
rot = self.merged.as_matrix(['RotationVector_val_w',
'RotationVector_val_x',
'RotationVector_val_y',
'RotationVector_val_z'])
if np.isnan(rot).any():
raise ValueError('No RotationVector data available. Cannot rotate accelerometer.')
keys = 'Normalized_Accelerometer_val_x', 'Normalized_Accelerometer_val_y', 'Normalized_Accelerometer_val_z'
rot_acc = rotate_quat(acc, rot)
rot_acc[:, 2] -= 9.8
rot_acc /= norm_reference
self.merged = self.merged.assign(**{keys[i]: rot_acc[:, i] for i in range(len(keys))})
def filter_steps(self, th):
for s in (self.RightFootSensor, self.LeftFootSensor):
step_data = s['stride_x', 'stride_y']
step_norm = np.linalg.norm(step_data, axis=1)
print('{}: {} steps detected as too small'.format(s.name, np.sum(step_norm < th)))
s.raw_data = s.raw_data[step_norm >= th]
| [
"numpy.mean",
"collections.deque",
"numpy.searchsorted",
"os.path.join",
"os.path.split",
"numpy.sum",
"numpy.isnan",
"utils.rotate_quat",
"numpy.linalg.norm",
"numpy.argmin",
"csv.reader"
] | [((3483, 3490), 'collections.deque', 'deque', ([], {}), '()\n', (3488, 3490), False, 'from collections import deque\n'), ((6937, 6958), 'utils.rotate_quat', 'rotate_quat', (['acc', 'rot'], {}), '(acc, rot)\n', (6948, 6958), False, 'from utils import rotate_quat, rotate_cross_product\n'), ((8201, 8222), 'utils.rotate_quat', 'rotate_quat', (['acc', 'rot'], {}), '(acc, rot)\n', (8212, 8222), False, 'from utils import rotate_quat, rotate_cross_product\n'), ((3201, 3235), 'os.path.join', 'os.path.join', (['self.path', 'file_name'], {}), '(self.path, file_name)\n', (3213, 3235), False, 'import os\n'), ((3427, 3442), 'collections.deque', 'deque', ([], {'maxlen': '(1)'}), '(maxlen=1)\n', (3432, 3442), False, 'from collections import deque\n'), ((5295, 5331), 'numpy.searchsorted', 'np.searchsorted', (['arrivals', 'timestamp'], {}), '(arrivals, timestamp)\n', (5310, 5331), True, 'import numpy as np\n'), ((8550, 8583), 'numpy.linalg.norm', 'np.linalg.norm', (['step_data'], {'axis': '(1)'}), '(step_data, axis=1)\n', (8564, 8583), True, 'import numpy as np\n'), ((1181, 1194), 'csv.reader', 'csv.reader', (['f'], {}), '(f)\n', (1191, 1194), False, 'import csv\n'), ((1919, 1949), 'os.path.join', 'os.path.join', (['path', '"""meta.txt"""'], {}), "(path, 'meta.txt')\n", (1931, 1949), False, 'import os\n'), ((2773, 2797), 'os.path.split', 'os.path.split', (['self.path'], {}), '(self.path)\n', (2786, 2797), False, 'import os\n'), ((3676, 3694), 'numpy.argmin', 'np.argmin', (['new_arr'], {}), '(new_arr)\n', (3685, 3694), True, 'import numpy as np\n'), ((6308, 6321), 'numpy.isnan', 'np.isnan', (['rot'], {}), '(rot)\n', (6316, 6321), True, 'import numpy as np\n'), ((6696, 6709), 'numpy.isnan', 'np.isnan', (['rot'], {}), '(rot)\n', (6704, 6709), True, 'import numpy as np\n'), ((7563, 7576), 'numpy.isnan', 'np.isnan', (['rot'], {}), '(rot)\n', (7571, 7576), True, 'import numpy as np\n'), ((7951, 7964), 'numpy.isnan', 'np.isnan', (['rot'], {}), '(rot)\n', (7959, 7964), True, 'import numpy as np\n'), ((951, 978), 'os.path.join', 'os.path.join', (['path', '"""*.csv"""'], {}), "(path, '*.csv')\n", (963, 978), False, 'import os\n'), ((4062, 4092), 'numpy.mean', 'np.mean', (['[q[0][0] for q in qs]'], {}), '([q[0][0] for q in qs])\n', (4069, 4092), True, 'import numpy as np\n'), ((8654, 8676), 'numpy.sum', 'np.sum', (['(step_norm < th)'], {}), '(step_norm < th)\n', (8660, 8676), True, 'import numpy as np\n'), ((1082, 1107), 'os.path.split', 'os.path.split', (['sensor_log'], {}), '(sensor_log)\n', (1095, 1107), False, 'import os\n')] |
"""!
Utilities for random number generators.
See isle.random.RNGWrapper for the common interface of wrappers.
"""
from abc import ABC, abstractmethod
import numpy as np
class RNGWrapper(ABC):
"""!
Base for all RNG wrappers.
"""
@property
def NAME(self):
"""!Unique name of the RNG."""
raise NotImplementedError
@abstractmethod
def seed(self, seed):
"""!Reseed the RNG."""
pass
@abstractmethod
def uniform(self, low=0.0, high=1.0, size=None, cmplx=False):
r"""!
Return uniformly distributed random numbers.
\param low Minimum value (inclusive).
\param high Maximum value (exclusive).
\param size Int or tuple of ints encoding the shape of the returned array.
If not given, a single number is returned.
\param cmplx Select whether to return real or complex numbers.
"""
pass
@abstractmethod
def normal(self, mean=0.0, std=1.0, size=None, cmplx=False):
r"""!
Return normally distributed random numbers.
\param mean Mean value of the distribution.
\param std Width of the destribution.
\param size Int or tuple of ints encoding the shape of the returned array.
If not given, a single number is returned.
\param cmplx Select whether to return real or complex numbers.
"""
pass
@abstractmethod
def choice(self, a, size=None, replace=True):
r"""!
Generate a random sample from a given 1-D array
\param a If an np.ndarray or equivalent, a random sample is generated from
its elements. If an int, the random sample is generated as if a were np.arange(a).
\param size Output shape. If the given shape is, e.g., (m, n, k), then m * n * k
samples are drawn. Default is None, in which case a single value is returned.
\param replace Whether the sample is with or without replacement.
\param p The probabilities associated with each entry in a. If not given the sample
assumes a uniform distribution over all entries in a.
"""
pass
@abstractmethod
def writeH5(self, group):
r"""!
Write the current state of the RNG into a HDF5 group.
\param group ´h5.Group` instance to write into. No new group is created inside of it.
"""
pass
@abstractmethod
def readH5(self, group):
r"""!
Read the RNG state from HDF5.
\param group `h5.Group` instance which contains all needed data.
"""
pass
class NumpyRNG(RNGWrapper):
"""!
Wrapper around numpy's Mersenne Twister random number generator.
"""
## Unique name of this RNG.
NAME = "np.MT19937"
def __init__(self, seed):
"""!Initialize from a seed."""
self._state = np.random.RandomState(seed)
def seed(self, seed):
"""!Reseed the RNG."""
self._state.seed(seed)
def uniform(self, low=0.0, high=1.0, size=None, cmplx=False):
r"""!
Return uniformly distributed random numbers.
\param low Minimum value (inclusive).
\param high Maximum value (exclusive).
\param size Int or tuple of ints encoding the shape of the returned array.
If not given, a single number is returned.
\param cmplx Select whether to return real or complex numbers.
"""
if cmplx:
return self._state.uniform(low, high, size) \
+ 1j*self._state.uniform(low, high, size)
return self._state.uniform(low, high, size)
def normal(self, mean=0.0, std=1.0, size=None, cmplx=False):
r"""!
Return normally distributed random numbers.
\param mean Mean value of the distribution.
\param std Width of the destribution.
\param size Int or tuple of ints encoding the shape of the returned array.
If not given, a single number is returned.
\param cmplx Select whether to return real or complex numbers.
"""
if cmplx:
return self._state.normal(mean, std, size) \
+ 1j*self._state.normal(mean, std, size)
return self._state.normal(mean, std, size)
def choice(self, a, size=None, replace=True, p=None):
r"""!
Generate a random sample from a given 1-D array
\param a If an np.ndarray or equivalent, a random sample is generated from
its elements. If an int, the random sample is generated as if a were np.arange(a).
\param size Output shape. If the given shape is, e.g., (m, n, k), then m * n * k
samples are drawn. Default is None, in which case a single value is returned.
\param replace Whether the sample is with or without replacement.
\param p The probabilities associated with each entry in a. If not given the sample
assumes a uniform distribution over all entries in a.
"""
return self._state.choice(a, size=size, replace=replace, p=p)
def writeH5(self, group):
r"""!
Write the current state of the RNG into a HDF5 group.
\param group ´h5.Group` instance to write into. No new group is created inside of it.
"""
stDat = self._state.get_state()
assert stDat[0] == self.NAME.rsplit(".")[-1]
# write state
group["name"] = self.NAME
group["keys"] = stDat[1]
group.attrs["pos"] = stDat[2]
group.attrs["has_gauss"] = stDat[3]
group.attrs["cached_gaussian"] = stDat[4]
def readH5(self, group):
r"""!
Read the RNG state from HDF5.
\param group `h5.Group` instance which contains all needed data.
"""
try:
# make sure this is the correct RNG
if group["name"][()] != self.NAME:
raise RuntimeError("Wrong kind of RNG. Expected {}, got {}"
.format(self.NAME, group["name"]))
# load state
self._state.set_state((self.NAME.rsplit(".")[-1],
np.array(group["keys"]),
group.attrs["pos"],
group.attrs["has_gauss"],
group.attrs["cached_gaussian"]))
except KeyError as err:
# add some info and throw it back at my face
err.args = ("Malformatted RNG group: {}".format(err), )
raise err
## Dictionary of all RNGs addressable through their names.
RNGS = {NumpyRNG.NAME: NumpyRNG}
def writeStateH5(rng, group):
r"""!
Write an RNG state to HDF5.
\param rng State to write.
\param group HDF5 group to write into.
"""
rng.writeH5(group)
def readStateH5(group):
r"""!
Construct a new RNG state from HDF5.
\param group HDF5 group that contains data for an RNG state. Must contain a dataset
called 'name' that indicates which RNG is stored. Other fields are
specific to the RNG that was stored.
\returns A new RNG state instance. The type is determined from HDF5.
"""
if "name" not in group:
raise ValueError("HDF5 group does not contain an RNG")
rng = RNGS[group["name"][()]](0) # instantiate new RNG
rng.readH5(group) # read state
return rng
| [
"numpy.array",
"numpy.random.RandomState"
] | [((2907, 2934), 'numpy.random.RandomState', 'np.random.RandomState', (['seed'], {}), '(seed)\n', (2928, 2934), True, 'import numpy as np\n'), ((6203, 6226), 'numpy.array', 'np.array', (["group['keys']"], {}), "(group['keys'])\n", (6211, 6226), True, 'import numpy as np\n')] |
"""
###################
Hammersley 2D-plane
###################
Hammersley points are a series of pseudo random points with a low discrepancy that are suitable for use in solid state NMR simulations where powder averaging is performed.
References
==========
- <NAME>.; <NAME>. (1964). Monte Carlo Methods. doi:10.1007/978-94-009-5819-7
- <NAME>, <NAME> & <NAME> (1997) Sampling with Hammersley and Halton Points, Journal of Graphics Tools, 2:2, 9-24, doi: 10.1080/10867651.1997.10487471
Examples of Hammersley points for tiling a 2-D plane
====================================================
"""
import numpy as np
from matplotlib import pyplot as plt
def return_point(m, n, p):
"""
m is the index number of the Hammersley point to calculate
n is the maximun number of points
p is the order of the Hammersley point, 1,2,3,4,... etc
l is the power of x to go out to and is hard coded to 10 in this example
:return type double
"""
if p == 1:
return m / n
v = 0.0
for j in range(10, -1, -1):
num = m // p ** j
if num > 0:
m -= num * p ** j
v += num / (p ** (j + 1))
return (v)
if __name__ == "__main__":
npts = 500
h_1 = np.zeros(npts)
h_2 = np.zeros(npts)
h_3 = np.zeros(npts)
h_4 = np.zeros(npts)
h_5 = np.zeros(npts)
h_7 = np.zeros(npts)
for m in range(npts):
h_1[m] = return_point(m, npts, 1)
h_2[m] = return_point(m, npts, 2)
h_3[m] = return_point(m, npts, 3)
h_4[m] = return_point(m, npts, 4)
h_5[m] = return_point(m, npts, 5)
h_7[m] = return_point(m, npts, 7)
fig, axs = plt.subplots(2, 2, figsize=(10, 10), sharey=True)
ax =axs.flatten()
ax[0].plot(h_1, h_2, '.')
ax[1].plot(h_1, h_2, '.')
ax[2].plot(h_1, h_4, '.')
ax[3].plot(h_1, h_5, '.')
ax[0].set_xlabel("p=1", fontsize=14)
ax[0].set_ylabel("p=2", fontsize=14)
ax[1].set_xlabel("p=1", fontsize=14)
ax[1].set_ylabel("p=3", fontsize=14)
ax[2].set_xlabel("p=1", fontsize=14)
ax[2].set_ylabel("p=4", fontsize=14);
ax[3].set_xlabel("p=1", fontsize=14)
ax[3].set_ylabel("p=5", fontsize=14);
plt.show() | [
"numpy.zeros",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.show"
] | [((1234, 1248), 'numpy.zeros', 'np.zeros', (['npts'], {}), '(npts)\n', (1242, 1248), True, 'import numpy as np\n'), ((1259, 1273), 'numpy.zeros', 'np.zeros', (['npts'], {}), '(npts)\n', (1267, 1273), True, 'import numpy as np\n'), ((1284, 1298), 'numpy.zeros', 'np.zeros', (['npts'], {}), '(npts)\n', (1292, 1298), True, 'import numpy as np\n'), ((1309, 1323), 'numpy.zeros', 'np.zeros', (['npts'], {}), '(npts)\n', (1317, 1323), True, 'import numpy as np\n'), ((1334, 1348), 'numpy.zeros', 'np.zeros', (['npts'], {}), '(npts)\n', (1342, 1348), True, 'import numpy as np\n'), ((1359, 1373), 'numpy.zeros', 'np.zeros', (['npts'], {}), '(npts)\n', (1367, 1373), True, 'import numpy as np\n'), ((1669, 1718), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)', '(2)'], {'figsize': '(10, 10)', 'sharey': '(True)'}), '(2, 2, figsize=(10, 10), sharey=True)\n', (1681, 1718), True, 'from matplotlib import pyplot as plt\n'), ((2199, 2209), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2207, 2209), True, 'from matplotlib import pyplot as plt\n')] |
import numpy as np
import random
from shapely.geometry import Point
from shapely.geometry import Polygon
class Mock(object):
"""
mock = Mock(**{'type':'int','low': 20, 'high': 40, 'size': 1})
mock.get()
"""
low = 0
size = 0
high = 0
polygon = None
minx = None
miny = None
maxx = None
maxy = None
coords = [(41.403596, 2.150574), (41.389173, 2.122335), (41.376937, 2.161388)]
randint = False
randcoords = False
def __init__(self, **config):
"""
:param low:
:param high:
:param size:
"""
if config.get('type') == 'int':
self.randint = True
self.set_params(config.get('low', 10), config.get('high', 20), config.get('size', 1))
elif config.get('type') == 'coords':
self.polygon = self.set_coords(config.get('coords', None))
self.minx, self.miny, self.maxx, self.maxy = self.polygon.bounds
self.randcoords = True
else:
raise ValueError('')
def set_coords(self, coords):
if coords:
polygon = Polygon(coords)
else:
polygon = Polygon(self.coords)
return polygon
def set_params(self, low, high, size):
"""
:param low:
:param high:
:param size:
:return:
"""
self.low = low
self.high = high
self.size = size
def generate(self):
"""
:param low: int 10
:param high: int 20
:param size: int 1
:return: 20
"""
if self.randint:
return self.random_int()
elif self.randcoords:
return self.random_coords()
else:
return None
def random_int(self):
data = np.random.randint(low=self.low, high=self.high, size=self.size)
if self.size == 1:
return data[0]
return data
def random_coords(self):
"""
:param number: 10
:param polygon: polygon = Polygon([(0, 0), (1, 1), (1, 0)])
:return:
"""
list_of_points = []
counter = 0
while counter < 10:
pnt = Point(random.uniform(self.minx, self.maxx), random.uniform(self.miny, self.maxy))
if self.polygon.contains(pnt):
list_of_points.append({'lat': pnt.x, 'long': pnt.y})
counter += 1
return list_of_points[random.randrange(0, 10)]
| [
"random.uniform",
"numpy.random.randint",
"shapely.geometry.Polygon",
"random.randrange"
] | [((1804, 1867), 'numpy.random.randint', 'np.random.randint', ([], {'low': 'self.low', 'high': 'self.high', 'size': 'self.size'}), '(low=self.low, high=self.high, size=self.size)\n', (1821, 1867), True, 'import numpy as np\n'), ((1125, 1140), 'shapely.geometry.Polygon', 'Polygon', (['coords'], {}), '(coords)\n', (1132, 1140), False, 'from shapely.geometry import Polygon\n'), ((1177, 1197), 'shapely.geometry.Polygon', 'Polygon', (['self.coords'], {}), '(self.coords)\n', (1184, 1197), False, 'from shapely.geometry import Polygon\n'), ((2454, 2477), 'random.randrange', 'random.randrange', (['(0)', '(10)'], {}), '(0, 10)\n', (2470, 2477), False, 'import random\n'), ((2207, 2243), 'random.uniform', 'random.uniform', (['self.minx', 'self.maxx'], {}), '(self.minx, self.maxx)\n', (2221, 2243), False, 'import random\n'), ((2245, 2281), 'random.uniform', 'random.uniform', (['self.miny', 'self.maxy'], {}), '(self.miny, self.maxy)\n', (2259, 2281), False, 'import random\n')] |
from pysc2.env import sc2_env
from pysc2.lib import actions, features, units
import numpy as np
import torch
from absl import flags
FLAGS = flags.FLAGS
FLAGS([''])
class Env:
metadata = {'render.modes': ['human']}
default_settings = {
'map_name': "FindAndDefeatZerglings",
'players': [sc2_env.Agent(sc2_env.Race.terran)],
'agent_interface_format': features.AgentInterfaceFormat(
feature_dimensions=features.Dimensions(screen=64, minimap=64),
action_space=actions.ActionSpace.RAW,
use_raw_units=True,
raw_resolution=64,
use_camera_position=True),
'step_mul': 4,
'game_steps_per_episode' : 0,
'visualize' : False,
'realtime': False
}
def __init__(self, **kwargs):
super().__init__()
self.kwargs = kwargs
self.env = None
self.marine1 = None
self.marine2 = None
self.marine3 = None
self.marine1_ID = None
self.marine2_ID = None
self.marine3_ID = None
self.last_target_pos = None
self.camera_pos = None
def reset(self):
if self.env is None:
self.init_env()
self.marine1 = None
self.marine2 = None
self.marine3 = None
raw_obs = self.env.reset()[0]
self.camera_pos = raw_obs.observation.camera_position
return self.get_state_from_obs(raw_obs, True)
def init_env(self):
args = {**self.default_settings, **self.kwargs}
self.env = sc2_env.SC2Env(**args)
def get_state_from_obs(self, raw_obs, reset):
marines = self.get_units_by_type(raw_obs, units.Terran.Marine)
if reset:
self.marine1_ID = marines[0].tag
self.marine2_ID = marines[1].tag
self.marine3_ID = marines[2].tag
self.marine1 = marines[0]
self.marine2 = marines[1]
self.marine3 = marines[2]
else:
mar_assigned = False
for marine in marines:
if marine.tag == self.marine1_ID:
mar_assigned = True
self.marine1 = marine
break
if not mar_assigned:
self.marine1 = None
mar_assigned = False
for marine in marines:
if marine.tag == self.marine2_ID:
mar_assigned = True
self.marine2 = marine
break
if not mar_assigned:
self.marine2 = None
mar_assigned = False
for marine in marines:
if marine.tag == self.marine3_ID:
mar_assigned = True
self.marine3 = marine
break
if not mar_assigned:
self.marine3 = None
entity_matrix = np.array(raw_obs.observation.feature_minimap.player_relative)
visibility_matrix = np.array(raw_obs.observation.feature_minimap.visibility_map)
camera_matrix = np.array(raw_obs.observation.feature_minimap.camera)
self.state = np.stack([entity_matrix, visibility_matrix, camera_matrix], axis=0)
return self.state
def step(self, action):
raw_obs = self.take_action(action)
new_state = self.get_state_from_obs(raw_obs, False)
self.camera_pos = raw_obs.observation.camera_position
return new_state, int(raw_obs.reward), raw_obs.last(), 0
def take_action(self, action):
x_axis_offset = 0
y_axis_offset = 0
if action % 8 == 0 :
x_axis_offset -= 3
y_axis_offset -= 3
elif action % 8 == 1 :
y_axis_offset -= 3
elif action % 8 == 2 :
x_axis_offset += 3
y_axis_offset -= 3
elif action % 8 == 3 :
x_axis_offset += 3
elif action % 8 == 4 :
x_axis_offset += 3
y_axis_offset += 3
elif action % 8 == 5 :
y_axis_offset += 3
elif action % 8 == 6 :
x_axis_offset -= 3
y_axis_offset += 3
elif action % 8 == 7 :
x_axis_offset -= 3
else:
assert False
if action < 8:
if self.marine1 is not None:
self.last_target_pos = [self.marine1.x + x_axis_offset, self.marine1.y + y_axis_offset]
mapped_action = actions.RAW_FUNCTIONS.Attack_pt("now", self.marine1.tag, self.last_target_pos)
else:
mapped_action = actions.RAW_FUNCTIONS.no_op()
elif 16 > action >= 8:
if self.marine2 is not None:
self.last_target_pos = [self.marine2.x + x_axis_offset, self.marine2.y + y_axis_offset]
mapped_action = actions.RAW_FUNCTIONS.Attack_pt("now", self.marine2.tag, self.last_target_pos)
else:
mapped_action = actions.RAW_FUNCTIONS.no_op()
elif 24 > action >= 16:
if self.marine3 is not None:
self.last_target_pos = [self.marine3.x + x_axis_offset, self.marine3.y + y_axis_offset]
mapped_action = actions.RAW_FUNCTIONS.Attack_pt("now", self.marine3.tag, self.last_target_pos)
else:
mapped_action = actions.RAW_FUNCTIONS.no_op()
elif 32 > action >= 24:
if self.last_target_pos is not None:
mapped_action = actions.RAW_FUNCTIONS.raw_move_camera(self.last_target_pos)
else:
mapped_action = actions.RAW_FUNCTIONS.no_op()
else:
assert False
raw_obs = self.env.step([mapped_action])[0]
return raw_obs
def get_units_by_type(self, obs, unit_type):
unit_list = []
for unit in obs.observation.raw_units:
if unit.unit_type == unit_type:
unit_list.append(unit)
return unit_list
def close(self):
if self.env is not None:
self.env.close()
super().close() | [
"pysc2.lib.features.Dimensions",
"pysc2.lib.actions.RAW_FUNCTIONS.raw_move_camera",
"pysc2.env.sc2_env.SC2Env",
"pysc2.lib.actions.RAW_FUNCTIONS.Attack_pt",
"numpy.array",
"numpy.stack",
"pysc2.lib.actions.RAW_FUNCTIONS.no_op",
"pysc2.env.sc2_env.Agent"
] | [((1584, 1606), 'pysc2.env.sc2_env.SC2Env', 'sc2_env.SC2Env', ([], {}), '(**args)\n', (1598, 1606), False, 'from pysc2.env import sc2_env\n'), ((2919, 2980), 'numpy.array', 'np.array', (['raw_obs.observation.feature_minimap.player_relative'], {}), '(raw_obs.observation.feature_minimap.player_relative)\n', (2927, 2980), True, 'import numpy as np\n'), ((3009, 3069), 'numpy.array', 'np.array', (['raw_obs.observation.feature_minimap.visibility_map'], {}), '(raw_obs.observation.feature_minimap.visibility_map)\n', (3017, 3069), True, 'import numpy as np\n'), ((3094, 3146), 'numpy.array', 'np.array', (['raw_obs.observation.feature_minimap.camera'], {}), '(raw_obs.observation.feature_minimap.camera)\n', (3102, 3146), True, 'import numpy as np\n'), ((3169, 3236), 'numpy.stack', 'np.stack', (['[entity_matrix, visibility_matrix, camera_matrix]'], {'axis': '(0)'}), '([entity_matrix, visibility_matrix, camera_matrix], axis=0)\n', (3177, 3236), True, 'import numpy as np\n'), ((314, 348), 'pysc2.env.sc2_env.Agent', 'sc2_env.Agent', (['sc2_env.Race.terran'], {}), '(sc2_env.Race.terran)\n', (327, 348), False, 'from pysc2.env import sc2_env\n'), ((455, 497), 'pysc2.lib.features.Dimensions', 'features.Dimensions', ([], {'screen': '(64)', 'minimap': '(64)'}), '(screen=64, minimap=64)\n', (474, 497), False, 'from pysc2.lib import actions, features, units\n'), ((4467, 4545), 'pysc2.lib.actions.RAW_FUNCTIONS.Attack_pt', 'actions.RAW_FUNCTIONS.Attack_pt', (['"""now"""', 'self.marine1.tag', 'self.last_target_pos'], {}), "('now', self.marine1.tag, self.last_target_pos)\n", (4498, 4545), False, 'from pysc2.lib import actions, features, units\n'), ((4596, 4625), 'pysc2.lib.actions.RAW_FUNCTIONS.no_op', 'actions.RAW_FUNCTIONS.no_op', ([], {}), '()\n', (4623, 4625), False, 'from pysc2.lib import actions, features, units\n'), ((4835, 4913), 'pysc2.lib.actions.RAW_FUNCTIONS.Attack_pt', 'actions.RAW_FUNCTIONS.Attack_pt', (['"""now"""', 'self.marine2.tag', 'self.last_target_pos'], {}), "('now', self.marine2.tag, self.last_target_pos)\n", (4866, 4913), False, 'from pysc2.lib import actions, features, units\n'), ((4964, 4993), 'pysc2.lib.actions.RAW_FUNCTIONS.no_op', 'actions.RAW_FUNCTIONS.no_op', ([], {}), '()\n', (4991, 4993), False, 'from pysc2.lib import actions, features, units\n'), ((5204, 5282), 'pysc2.lib.actions.RAW_FUNCTIONS.Attack_pt', 'actions.RAW_FUNCTIONS.Attack_pt', (['"""now"""', 'self.marine3.tag', 'self.last_target_pos'], {}), "('now', self.marine3.tag, self.last_target_pos)\n", (5235, 5282), False, 'from pysc2.lib import actions, features, units\n'), ((5333, 5362), 'pysc2.lib.actions.RAW_FUNCTIONS.no_op', 'actions.RAW_FUNCTIONS.no_op', ([], {}), '()\n', (5360, 5362), False, 'from pysc2.lib import actions, features, units\n'), ((5477, 5536), 'pysc2.lib.actions.RAW_FUNCTIONS.raw_move_camera', 'actions.RAW_FUNCTIONS.raw_move_camera', (['self.last_target_pos'], {}), '(self.last_target_pos)\n', (5514, 5536), False, 'from pysc2.lib import actions, features, units\n'), ((5587, 5616), 'pysc2.lib.actions.RAW_FUNCTIONS.no_op', 'actions.RAW_FUNCTIONS.no_op', ([], {}), '()\n', (5614, 5616), False, 'from pysc2.lib import actions, features, units\n')] |
#
# File:
# scatter1.py
#
# Synopsis:
# Draws a scatter visualization using polymarkers.
#
# Categories:
# Polymarkers
# Tickmarks
# Text
# XY plots
#
# Author:
# <NAME>
#
# Date of initial publication:
# October, 2004
#
# Description:
# This example reads in some dummy of XY coordinates and
# associated color indices in the range from 1 to 4. A
# scatter plot is drawn using markers colored and sized
# as per the color indices. A quadratic least squares fit
# is calculated.
#
# Effects illustrated:
# o Polymarkers.
# o Least squares fit.
# o XY plot.
# o Tickmark resource settings.
#
# Output:
# A single visualization is produced.
#
# Notes:
# 1.) This visualization is similar in appearance to one provided
# by Joel Norris of GFDL, but dummmy data are used.
from __future__ import print_function
# 2.) This example requires importing the Scientific package.
#
#
# Import numpy.
#
import numpy, os
#
# Import Nio for reading netCDF files.
#
import Nio
#
# Import Ngl.
#
import Ngl
#
# This plot is very similar to one done by Joel Norris of GFDL. The
# original data is no longer available, so dummy data is used in this
# case.
#
# Read the scattered data and extract the x, y, and color variables.
#
dirc = Ngl.pynglpath("data")
ncdf = Nio.open_file(os.path.join(dirc,"cdf","scatter1.nc"),"r")
x = ncdf.variables["x"][:]
y = ncdf.variables["y"][:]
colors = ncdf.variables["colors"][:]
color_index = colors.astype('i')
#
# Open an output workstation.
#
wks_type = "png"
wks = Ngl.open_wks(wks_type,"scatter1")
#
# Label the plot.
#
resources = Ngl.Resources()
resources.tiMainString = "2000 Mar 19 1040-1725Z"
resources.tiMainFont = "helvetica-bold"
resources.tiXAxisString = "Cloud Thickness (m)"
resources.tiXAxisFont = "helvetica-bold"
resources.tiYAxisString = "Liquid Water Path (mm)"
resources.tiYAxisFont = "helvetica-bold"
resources.tiXAxisFontHeightF = 0.025 # Change the font size.
resources.tiYAxisFontHeightF = 0.025
resources.xyLineColors = "black" # Set the line colors.
resources.xyMonoLineThickness = True # Set the line colors.
resources.xyLineThicknessF = 3.0 # Triple the width.
resources.tmXBMajorLengthF = 0.02 # Force tickmarks to point
resources.tmXBMajorOutwardLengthF = 0.02 # out by making the outward
resources.tmXBMinorLengthF = 0.01 # Force tickmarks to point
resources.tmXBMinorOutwardLengthF = 0.01 # out by making the outward
resources.tmXBLabelFont = "helvetica-bold"
resources.tmYLMajorLengthF = 0.02 # tick length equal to the
resources.tmYLMajorOutwardLengthF = 0.02 # total tick length
resources.tmYLMinorLengthF = 0.01
resources.tmYLMinorOutwardLengthF = 0.01
resources.tmYLLabelFont = "helvetica-bold"
resources.trXMaxF = 800. # Force the X-axis to run to 800.
resources.trYMaxF = 0.35 # Force the Y-axis to run to 0.35
txres = Ngl.Resources()
txres.txFont = "helvetica-bold"
txres.txFontHeightF = 0.02
txres.txJust = "CenterLeft"
Ngl.text_ndc(wks,"LWP=0.5 x 1.55 x 10~S~-6~N~ x Thickness~S1~2", \
0.24,0.85,txres)
xpos = 0.245
delx = 0.02
ypos = 0.78
dely = 0.035
gsres = Ngl.Resources()
gsres.gsMarkerIndex = 16 # Change marker type to a filled circle.
gsres.gsMarkerColor = "black" # Change marker color.
gsres.gsMarkerSizeF = 4.0 # Increase marker size.
Ngl.polymarker_ndc(wks,[xpos],[ypos],gsres) # Draw a polymarker.
txres.txFontColor = "black"
Ngl.text_ndc(wks,"20 sec",xpos+delx,ypos,txres)
gsres.gsMarkerColor = "red" # Change marker color.
gsres.gsMarkerSizeF = 7. # Increase marker size.
Ngl.polymarker_ndc(wks,[xpos],[ypos-dely],gsres) # Draw a polymarker.
txres.txFontColor = "red"
Ngl.text_ndc(wks,"1 min",xpos+delx,ypos-dely,txres)
gsres.gsMarkerColor = "blue" # Change marker color.
gsres.gsMarkerSizeF = 10. # Increase marker size.
Ngl.polymarker_ndc(wks,[xpos],[ypos-2*dely],gsres) # Draw a polymarker.
txres.txFontColor = "blue"
Ngl.text_ndc(wks,"5 min",xpos+delx,ypos-2*dely,txres)
gsres.gsMarkerColor = "green" # Change marker color.
gsres.gsMarkerSizeF = 13. # Increase marker size.
Ngl.polymarker_ndc(wks,[xpos],[ypos-3*dely],gsres) # Draw a polymarker.
txres.txFontColor = "green"
Ngl.text_ndc(wks,"20 min",xpos+delx,ypos-3*dely,txres)
#
# Suppress frame call.
#
resources.nglFrame = False
#
# Do a quadratic least squares fit.
#
npoints = len(x)
a = numpy.zeros([npoints,3],'f')
for m in range(npoints):
a[m,0] = 1.
for j in range(1,3):
a[m,j] = x[m]*a[m,j-1]
c = (numpy.linalg.lstsq(a,y,rcond=1.e-15))[0]
#
# Draw the least squares quadratic curve.
#
num = 301
delx = 1000./num
xp = numpy.zeros(num,'f')
yp = numpy.zeros(num,'f')
for i in range(num):
xp[i] = float(i)*delx
yp[i] = c[0]+c[1]*xp[i]+c[2]*xp[i]*xp[i]
plot = Ngl.xy(wks,xp,yp,resources) # Draw least squares quadratic.
#
# Draw a marker at each data point using the specified color index.
#
mres = Ngl.Resources()
mres.gsMarkerIndex = 1
for i in range(len(x)):
if (color_index[i] == 1):
mres.gsMarkerColor = "black"
mres.gsMarkerSizeF = 0.01 #Increase marker size by a factor of 10.
elif (color_index[i] == 2):
mres.gsMarkerColor = "red"
mres.gsMarkerSizeF = 0.02 #Increase marker size by a factor of 10.
elif (color_index[i] == 3):
mres.gsMarkerColor = "blue"
mres.gsMarkerSizeF = 0.04 #Increase marker size by a factor of 10.
elif (color_index[i] == 4):
mres.gsMarkerColor = "green"
mres.gsMarkerSizeF = 0.05 #Increase marker size by a factor of 10.
Ngl.polymarker(wks,plot,x[i],y[i],mres) # Draw polymarkers.
Ngl.frame(wks)
# Clean up and end.
del plot
del resources
Ngl.end()
| [
"Ngl.Resources",
"Ngl.xy",
"Ngl.end",
"Ngl.open_wks",
"os.path.join",
"Ngl.polymarker_ndc",
"Ngl.text_ndc",
"Ngl.pynglpath",
"numpy.zeros",
"Ngl.frame",
"Ngl.polymarker",
"numpy.linalg.lstsq"
] | [((1321, 1342), 'Ngl.pynglpath', 'Ngl.pynglpath', (['"""data"""'], {}), "('data')\n", (1334, 1342), False, 'import Ngl\n'), ((1591, 1625), 'Ngl.open_wks', 'Ngl.open_wks', (['wks_type', '"""scatter1"""'], {}), "(wks_type, 'scatter1')\n", (1603, 1625), False, 'import Ngl\n'), ((1663, 1678), 'Ngl.Resources', 'Ngl.Resources', ([], {}), '()\n', (1676, 1678), False, 'import Ngl\n'), ((3104, 3119), 'Ngl.Resources', 'Ngl.Resources', ([], {}), '()\n', (3117, 3119), False, 'import Ngl\n'), ((3207, 3296), 'Ngl.text_ndc', 'Ngl.text_ndc', (['wks', '"""LWP=0.5 x 1.55 x 10~S~-6~N~ x Thickness~S1~2"""', '(0.24)', '(0.85)', 'txres'], {}), "(wks, 'LWP=0.5 x 1.55 x 10~S~-6~N~ x Thickness~S1~2', 0.24, \n 0.85, txres)\n", (3219, 3296), False, 'import Ngl\n'), ((3368, 3383), 'Ngl.Resources', 'Ngl.Resources', ([], {}), '()\n', (3381, 3383), False, 'import Ngl\n'), ((3569, 3615), 'Ngl.polymarker_ndc', 'Ngl.polymarker_ndc', (['wks', '[xpos]', '[ypos]', 'gsres'], {}), '(wks, [xpos], [ypos], gsres)\n', (3587, 3615), False, 'import Ngl\n'), ((3670, 3723), 'Ngl.text_ndc', 'Ngl.text_ndc', (['wks', '"""20 sec"""', '(xpos + delx)', 'ypos', 'txres'], {}), "(wks, '20 sec', xpos + delx, ypos, txres)\n", (3682, 3723), False, 'import Ngl\n'), ((3830, 3883), 'Ngl.polymarker_ndc', 'Ngl.polymarker_ndc', (['wks', '[xpos]', '[ypos - dely]', 'gsres'], {}), '(wks, [xpos], [ypos - dely], gsres)\n', (3848, 3883), False, 'import Ngl\n'), ((3929, 3988), 'Ngl.text_ndc', 'Ngl.text_ndc', (['wks', '"""1 min"""', '(xpos + delx)', '(ypos - dely)', 'txres'], {}), "(wks, '1 min', xpos + delx, ypos - dely, txres)\n", (3941, 3988), False, 'import Ngl\n'), ((4093, 4150), 'Ngl.polymarker_ndc', 'Ngl.polymarker_ndc', (['wks', '[xpos]', '[ypos - 2 * dely]', 'gsres'], {}), '(wks, [xpos], [ypos - 2 * dely], gsres)\n', (4111, 4150), False, 'import Ngl\n'), ((4193, 4256), 'Ngl.text_ndc', 'Ngl.text_ndc', (['wks', '"""5 min"""', '(xpos + delx)', '(ypos - 2 * dely)', 'txres'], {}), "(wks, '5 min', xpos + delx, ypos - 2 * dely, txres)\n", (4205, 4256), False, 'import Ngl\n'), ((4359, 4416), 'Ngl.polymarker_ndc', 'Ngl.polymarker_ndc', (['wks', '[xpos]', '[ypos - 3 * dely]', 'gsres'], {}), '(wks, [xpos], [ypos - 3 * dely], gsres)\n', (4377, 4416), False, 'import Ngl\n'), ((4460, 4524), 'Ngl.text_ndc', 'Ngl.text_ndc', (['wks', '"""20 min"""', '(xpos + delx)', '(ypos - 3 * dely)', 'txres'], {}), "(wks, '20 min', xpos + delx, ypos - 3 * dely, txres)\n", (4472, 4524), False, 'import Ngl\n'), ((4635, 4665), 'numpy.zeros', 'numpy.zeros', (['[npoints, 3]', '"""f"""'], {}), "([npoints, 3], 'f')\n", (4646, 4665), False, 'import numpy, os\n'), ((4883, 4904), 'numpy.zeros', 'numpy.zeros', (['num', '"""f"""'], {}), "(num, 'f')\n", (4894, 4904), False, 'import numpy, os\n'), ((4912, 4933), 'numpy.zeros', 'numpy.zeros', (['num', '"""f"""'], {}), "(num, 'f')\n", (4923, 4933), False, 'import numpy, os\n'), ((5028, 5058), 'Ngl.xy', 'Ngl.xy', (['wks', 'xp', 'yp', 'resources'], {}), '(wks, xp, yp, resources)\n', (5034, 5058), False, 'import Ngl\n'), ((5170, 5185), 'Ngl.Resources', 'Ngl.Resources', ([], {}), '()\n', (5183, 5185), False, 'import Ngl\n'), ((5832, 5846), 'Ngl.frame', 'Ngl.frame', (['wks'], {}), '(wks)\n', (5841, 5846), False, 'import Ngl\n'), ((5892, 5901), 'Ngl.end', 'Ngl.end', ([], {}), '()\n', (5899, 5901), False, 'import Ngl\n'), ((1364, 1404), 'os.path.join', 'os.path.join', (['dirc', '"""cdf"""', '"""scatter1.nc"""'], {}), "(dirc, 'cdf', 'scatter1.nc')\n", (1376, 1404), False, 'import numpy, os\n'), ((4758, 4795), 'numpy.linalg.lstsq', 'numpy.linalg.lstsq', (['a', 'y'], {'rcond': '(1e-15)'}), '(a, y, rcond=1e-15)\n', (4776, 4795), False, 'import numpy, os\n'), ((5771, 5814), 'Ngl.polymarker', 'Ngl.polymarker', (['wks', 'plot', 'x[i]', 'y[i]', 'mres'], {}), '(wks, plot, x[i], y[i], mres)\n', (5785, 5814), False, 'import Ngl\n')] |
# -*- coding: utf-8 -*-
from __future__ import division
import os
import numpy as np
import torch
from cpprb import PrioritizedReplayBuffer
from utils import torchify
class ReplayMemory():
def __init__(self, args, capacity, env):
# Initial importance sampling weight β, annealed to 1 over course of training
self.priority_weight = args.priority_weight
self.n = args.multi_step
self.device = args.device
if args.mmap:
os.makedirs('memories/', exist_ok=True)
mmap_prefix = 'memories/mm'
else:
mmap_prefix = None
self.buffer = PrioritizedReplayBuffer(
capacity,
{
"obs": {
"shape": env.observation_space.shape, "dtype": env.observation_space.dtype
},
"next_obs": {
"shape": env.observation_space.shape, "dtype": env.observation_space.dtype
},
"act": {
"shape": 1, "dtype": env.action_space.dtype
},
"rew": {
"dtype": np.float32
},
"done": {
"dtype": np.uint8
},
},
Nstep={
"size": self.n,
"gamma": args.discount,
"rew": "rew",
"next": "next_obs",
},
mmap_prefix=mmap_prefix,
alpha=args.priority_exponent,
# next_of="obs",
# stack_compress="obs",
)
def append(self, state, next_state, action, reward, done):
self.buffer.add(**{
"obs": state,
"next_obs": next_state,
"act": action,
"rew": reward,
"done": done,
})
def sample(self, size):
s = self.buffer.sample(size, self.priority_weight)
s['indexes'] = s['indexes'].astype(np.int32)
return torchify((s['indexes'], torch.int32), (s['obs'], torch.float32),
(np.squeeze(s['act'], 1), torch.long),
(np.squeeze(s['rew'], 1), torch.float32), (s['next_obs'], torch.float32),
(s['done'], torch.bool), (s['weights'], torch.float32),
device=self.device)
def update_priorities(self, indexes, new_priorities):
indexes = indexes.cpu().numpy()
self.buffer.update_priorities(indexes, new_priorities)
| [
"cpprb.PrioritizedReplayBuffer",
"os.makedirs",
"numpy.squeeze"
] | [((624, 1112), 'cpprb.PrioritizedReplayBuffer', 'PrioritizedReplayBuffer', (['capacity', "{'obs': {'shape': env.observation_space.shape, 'dtype': env.\n observation_space.dtype}, 'next_obs': {'shape': env.observation_space.\n shape, 'dtype': env.observation_space.dtype}, 'act': {'shape': 1,\n 'dtype': env.action_space.dtype}, 'rew': {'dtype': np.float32}, 'done':\n {'dtype': np.uint8}}"], {'Nstep': "{'size': self.n, 'gamma': args.discount, 'rew': 'rew', 'next': 'next_obs'}", 'mmap_prefix': 'mmap_prefix', 'alpha': 'args.priority_exponent'}), "(capacity, {'obs': {'shape': env.observation_space.\n shape, 'dtype': env.observation_space.dtype}, 'next_obs': {'shape': env\n .observation_space.shape, 'dtype': env.observation_space.dtype}, 'act':\n {'shape': 1, 'dtype': env.action_space.dtype}, 'rew': {'dtype': np.\n float32}, 'done': {'dtype': np.uint8}}, Nstep={'size': self.n, 'gamma':\n args.discount, 'rew': 'rew', 'next': 'next_obs'}, mmap_prefix=\n mmap_prefix, alpha=args.priority_exponent)\n", (647, 1112), False, 'from cpprb import PrioritizedReplayBuffer\n'), ((477, 516), 'os.makedirs', 'os.makedirs', (['"""memories/"""'], {'exist_ok': '(True)'}), "('memories/', exist_ok=True)\n", (488, 516), False, 'import os\n'), ((2076, 2099), 'numpy.squeeze', 'np.squeeze', (["s['act']", '(1)'], {}), "(s['act'], 1)\n", (2086, 2099), True, 'import numpy as np\n'), ((2139, 2162), 'numpy.squeeze', 'np.squeeze', (["s['rew']", '(1)'], {}), "(s['rew'], 1)\n", (2149, 2162), True, 'import numpy as np\n')] |
import math
import matplotlib.pyplot as plt
import numpy as np
from pf import pf_localization
from ekf_1 import ekf_estimation
from leastsq import lsq_estimation
# Simulation parameter
# Q_sim = np.diag([0.2]) ** 2
# R_sim = np.diag([1.0, np.deg2rad(30.0)]) ** 2
Q_sim = np.diag([0.4]) ** 2
R_sim = np.diag([0.8, np.deg2rad(10.0)]) ** 2
count =0
DT = 0.1 # time tick [s]
SIM_TIME = 65.0 # simulation time [s]
MAX_RANGE = 200.0 # maximum observation range
show_animation = True
#constant velocity inuput
def calc_input():
v = 1.0 # [m/s]
yaw_rate = 0.1 # [rad/s]
u = np.array([[v, yaw_rate]]).T
return u
def observation(xTrue, xd, u, RF_ID):
xTrue = motion_model(xTrue, u)
# add noise to gps x-y
z = np.zeros((0, 3))
for i in range(len(RF_ID[:, 0])):
dx = xTrue[0, 0] - RF_ID[i, 0]
dy = xTrue[1, 0] - RF_ID[i, 1]
d = math.hypot(dx, dy)
if d <= MAX_RANGE:
dn = d + np.random.randn() * Q_sim[0, 0] ** 0.5 # add noise
zi = np.array([[dn, RF_ID[i, 0], RF_ID[i, 1]]])
z = np.vstack((z, zi))
# add noise to input
ud1 = u[0, 0] + np.random.randn() * R_sim[0, 0] ** 0.5
ud2 = u[1, 0] + np.random.randn() * R_sim[1, 1] ** 0.5
ud = np.array([[ud1, ud2]]).T
xd = motion_model(xd, ud)
return xTrue, z, xd, ud
def motion_model(x, u):
F = np.array([[1.0, 0, 0, 0],
[0, 1.0, 0, 0],
[0, 0, 1.0, 0],
[0, 0, 0, 0]])
B = np.array([[DT * math.cos(x[2, 0]), 0],
[DT * math.sin(x[2, 0]), 0],
[0.0, DT],
[1.0, 0.0]])
x = F.dot(x) + B.dot(u)
return x
def plot_covariance_ellipse(xEst, PEst): # pragma: no cover
Pxy = PEst[0:2, 0:2]
eig_val, eig_vec = np.linalg.eig(Pxy)
if eig_val[0] >= eig_val[1]:
big_ind = 0
small_ind = 1
else:
big_ind = 1
small_ind = 0
t = np.arange(0, 2 * math.pi + 0.1, 0.1)
# eig_val[big_ind] or eiq_val[small_ind] were occasionally negative numbers extremely
# close to 0 (~10^-20), catch these cases and set the respective variable to 0
try:
a = math.sqrt(eig_val[big_ind])
except ValueError:
a = 0
try:
b = math.sqrt(eig_val[small_ind])
except ValueError:
b = 0
x = [a * math.cos(it) for it in t]
y = [b * math.sin(it) for it in t]
angle = math.atan2(eig_vec[big_ind, 1], eig_vec[big_ind, 0])
Rot = np.array([[math.cos(angle), -math.sin(angle)],
[math.sin(angle), math.cos(angle)]])
fx = Rot.dot(np.array([[x, y]]))
px = np.array(fx[0, :] + xEst[0, 0]).flatten()
py = np.array(fx[1, :] + xEst[1, 0]).flatten()
plt.plot(px, py, "--r")
def main():
print(__file__ + " start!!")
count = 0.0
time = 0.0
# RF_ID positions [x, y]
RFi_ID = np.array([[15.0, 0.0],
[15.0, 20.0],
[-15.0, 0.0],
[-15.0, 20.0]])
# State Vector [x y yaw v]'
xEst_1 = np.zeros((4, 1))
xEst_2 = np.zeros((4, 1))
xEst_3 = np.zeros((4, 1))
xTrue = np.zeros((4, 1))
PEst_2 = np.eye(4)
# Particle filter parameter
NP = 100 # Number of Particle
NTh = NP / 2.0 # Number of particle for re-sampling
px = np.zeros((4, NP)) # Particle store
pw = np.zeros((1, NP)) + 1.0 / NP # Particle weight
xDR = np.zeros((4, 1)) # Dead reckoning
# history
hxEst_1 = np.zeros((4, 1))
hxEst_2 = np.zeros((4, 1))
hxEst_3 = np.zeros((4, 1))
hxTrue = xTrue
hxDR = np.zeros((4, 1))
hxcount = np.zeros((1, 1))
temp = np.zeros((1, 1))
while SIM_TIME >= time:
time += DT
u = calc_input()
xTrue, z, xDR, ud = observation(xTrue, xDR, u, RFi_ID)
xEst_1, PEst_1, px, pw = pf_localization(px, pw, z, ud) # particle filter
xEst_3 = lsq_estimation(xEst_3, z, ud) # least square filter
z_new = np.array([[ xEst_3[0,0] ], [xEst_3[1,0] ]])
xEst_2, PEst_2 = ekf_estimation(xEst_2,PEst_2, z_new, ud) # extended kalman filter
# store data history
hxEst_1 = np.hstack((hxEst_1, xEst_1))
hxEst_2 = np.hstack((hxEst_2, xEst_2))
hxEst_3 = np.hstack((hxEst_3, xEst_3))
hxDR = np.hstack((hxDR, xDR))
hxTrue = np.hstack((hxTrue, xTrue))
#For comparing the error between different filters
# count = count + 1
# temp[0,0] = math.hypot(xTrue[0,0]- xEst_1[0,0], xTrue[1,0]- xEst_1[1,0])
# hxEst_1 = np.hstack((hxEst_1,temp ))
# temp[0,0] = math.hypot(xTrue[0,0]- xEst_2[0,0], xTrue[1,0]- xEst_2[1,0])
# hxEst_2 = np.hstack((hxEst_2, temp))
# temp[0,0] = math.hypot(xTrue[0,0]- xEst_3[0,0], xTrue[1,0]- xEst_3[1,0])
# hxEst_3 = np.hstack((hxEst_3, temp))
# temp[0,0] = math.hypot(xTrue[0,0]- xDR[0,0], xTrue[1,0]- xDR[1,0])
# hxDR = np.hstack((hxDR, temp))
# temp[0,0] = count
# hxcount = np.hstack((hxcount, temp))
#print(hxcount.shape)
#print(hxEst.shape)
# print('\n')
#print('True '+str(xTrue[0,0])+' '+str(xEst_3[0,0])+' '+str(xTrue[1,0])+' '+str(xEst_3[1,0]))
if show_animation:
plt.cla()
# for stopping simulation with the esc key.
plt.gcf().canvas.mpl_connect('key_release_event',
lambda event: [exit(0) if event.key == 'escape' else None])
plt.gcf().set_size_inches(25, 25)
plt.axis(xlim=(-25, 25), ylim=(-10, 30))
for i in range(len(z[:, 0])):
plt.plot([xTrue[0, 0], z[i, 1]], [xTrue[1, 0], z[i, 2]], "-k")
plt.plot(RFi_ID[:, 0], RFi_ID[:, 1], "*k")
plt.plot(px[0, :], px[1, :], ".r")
plt.plot(np.array(hxTrue[0, :]).flatten(),
np.array(hxTrue[1, :]).flatten(), "-b",label='Original path')
plt.plot(np.array(hxDR[0, :]).flatten(),
np.array(hxDR[1, :]).flatten(), "k",label='Dead Reckoning')
plt.plot(np.array(hxEst_1[0, :]).flatten(),
np.array(hxEst_1[1, :]).flatten(), "-r",label='Particle filter')
plt.plot(np.array(hxEst_3[0, :]).flatten(),
np.array(hxEst_3[1, :]).flatten(), "y", label='Least square')
plt.plot(np.array(hxEst_2[0, :]).flatten(),
np.array(hxEst_2[1, :]).flatten(), "g", label='Extended Kalman filter')
#For comparing the total error
# plt.plot(hxcount[0],hxDR[0], "k",label='Dead Reckoning')
# plt.plot(hxcount[0, :],hxEst_1[0, :], "-r",label='Particle filter')
# plt.plot(hxcount[0, :],hxEst_3[0, :], "y", label='Least square')
# plt.plot(hxcount[0, :],hxEst_2[0, :], "g", label='Extended Kalman filter')
#plot_covariance_ellipse(xEst_1, PEst_1)
#plt.axis("equal")
plt.legend()
plt.grid(True)
plt.pause(0.001)
# if time == 59:
# plt.savefig('books_read.png')
# print('yes')
if __name__ == '__main__':
main() | [
"matplotlib.pyplot.grid",
"numpy.hstack",
"ekf_1.ekf_estimation",
"math.sqrt",
"math.cos",
"numpy.array",
"math.hypot",
"numpy.arange",
"matplotlib.pyplot.plot",
"numpy.vstack",
"matplotlib.pyplot.axis",
"matplotlib.pyplot.cla",
"numpy.eye",
"numpy.linalg.eig",
"pf.pf_localization",
"m... | [((276, 290), 'numpy.diag', 'np.diag', (['[0.4]'], {}), '([0.4])\n', (283, 290), True, 'import numpy as np\n'), ((746, 762), 'numpy.zeros', 'np.zeros', (['(0, 3)'], {}), '((0, 3))\n', (754, 762), True, 'import numpy as np\n'), ((1379, 1451), 'numpy.array', 'np.array', (['[[1.0, 0, 0, 0], [0, 1.0, 0, 0], [0, 0, 1.0, 0], [0, 0, 0, 0]]'], {}), '([[1.0, 0, 0, 0], [0, 1.0, 0, 0], [0, 0, 1.0, 0], [0, 0, 0, 0]])\n', (1387, 1451), True, 'import numpy as np\n'), ((1817, 1835), 'numpy.linalg.eig', 'np.linalg.eig', (['Pxy'], {}), '(Pxy)\n', (1830, 1835), True, 'import numpy as np\n'), ((1973, 2009), 'numpy.arange', 'np.arange', (['(0)', '(2 * math.pi + 0.1)', '(0.1)'], {}), '(0, 2 * math.pi + 0.1, 0.1)\n', (1982, 2009), True, 'import numpy as np\n'), ((2450, 2502), 'math.atan2', 'math.atan2', (['eig_vec[big_ind, 1]', 'eig_vec[big_ind, 0]'], {}), '(eig_vec[big_ind, 1], eig_vec[big_ind, 0])\n', (2460, 2502), False, 'import math\n'), ((2760, 2783), 'matplotlib.pyplot.plot', 'plt.plot', (['px', 'py', '"""--r"""'], {}), "(px, py, '--r')\n", (2768, 2783), True, 'import matplotlib.pyplot as plt\n'), ((2905, 2971), 'numpy.array', 'np.array', (['[[15.0, 0.0], [15.0, 20.0], [-15.0, 0.0], [-15.0, 20.0]]'], {}), '([[15.0, 0.0], [15.0, 20.0], [-15.0, 0.0], [-15.0, 20.0]])\n', (2913, 2971), True, 'import numpy as np\n'), ((3089, 3105), 'numpy.zeros', 'np.zeros', (['(4, 1)'], {}), '((4, 1))\n', (3097, 3105), True, 'import numpy as np\n'), ((3119, 3135), 'numpy.zeros', 'np.zeros', (['(4, 1)'], {}), '((4, 1))\n', (3127, 3135), True, 'import numpy as np\n'), ((3149, 3165), 'numpy.zeros', 'np.zeros', (['(4, 1)'], {}), '((4, 1))\n', (3157, 3165), True, 'import numpy as np\n'), ((3178, 3194), 'numpy.zeros', 'np.zeros', (['(4, 1)'], {}), '((4, 1))\n', (3186, 3194), True, 'import numpy as np\n'), ((3208, 3217), 'numpy.eye', 'np.eye', (['(4)'], {}), '(4)\n', (3214, 3217), True, 'import numpy as np\n'), ((3351, 3368), 'numpy.zeros', 'np.zeros', (['(4, NP)'], {}), '((4, NP))\n', (3359, 3368), True, 'import numpy as np\n'), ((3454, 3470), 'numpy.zeros', 'np.zeros', (['(4, 1)'], {}), '((4, 1))\n', (3462, 3470), True, 'import numpy as np\n'), ((3518, 3534), 'numpy.zeros', 'np.zeros', (['(4, 1)'], {}), '((4, 1))\n', (3526, 3534), True, 'import numpy as np\n'), ((3549, 3565), 'numpy.zeros', 'np.zeros', (['(4, 1)'], {}), '((4, 1))\n', (3557, 3565), True, 'import numpy as np\n'), ((3580, 3596), 'numpy.zeros', 'np.zeros', (['(4, 1)'], {}), '((4, 1))\n', (3588, 3596), True, 'import numpy as np\n'), ((3627, 3643), 'numpy.zeros', 'np.zeros', (['(4, 1)'], {}), '((4, 1))\n', (3635, 3643), True, 'import numpy as np\n'), ((3658, 3674), 'numpy.zeros', 'np.zeros', (['(1, 1)'], {}), '((1, 1))\n', (3666, 3674), True, 'import numpy as np\n'), ((3686, 3702), 'numpy.zeros', 'np.zeros', (['(1, 1)'], {}), '((1, 1))\n', (3694, 3702), True, 'import numpy as np\n'), ((592, 617), 'numpy.array', 'np.array', (['[[v, yaw_rate]]'], {}), '([[v, yaw_rate]])\n', (600, 617), True, 'import numpy as np\n'), ((893, 911), 'math.hypot', 'math.hypot', (['dx', 'dy'], {}), '(dx, dy)\n', (903, 911), False, 'import math\n'), ((1260, 1282), 'numpy.array', 'np.array', (['[[ud1, ud2]]'], {}), '([[ud1, ud2]])\n', (1268, 1282), True, 'import numpy as np\n'), ((2205, 2232), 'math.sqrt', 'math.sqrt', (['eig_val[big_ind]'], {}), '(eig_val[big_ind])\n', (2214, 2232), False, 'import math\n'), ((2292, 2321), 'math.sqrt', 'math.sqrt', (['eig_val[small_ind]'], {}), '(eig_val[small_ind])\n', (2301, 2321), False, 'import math\n'), ((2634, 2652), 'numpy.array', 'np.array', (['[[x, y]]'], {}), '([[x, y]])\n', (2642, 2652), True, 'import numpy as np\n'), ((3396, 3413), 'numpy.zeros', 'np.zeros', (['(1, NP)'], {}), '((1, NP))\n', (3404, 3413), True, 'import numpy as np\n'), ((3874, 3904), 'pf.pf_localization', 'pf_localization', (['px', 'pw', 'z', 'ud'], {}), '(px, pw, z, ud)\n', (3889, 3904), False, 'from pf import pf_localization\n'), ((3949, 3978), 'leastsq.lsq_estimation', 'lsq_estimation', (['xEst_3', 'z', 'ud'], {}), '(xEst_3, z, ud)\n', (3963, 3978), False, 'from leastsq import lsq_estimation\n'), ((4018, 4060), 'numpy.array', 'np.array', (['[[xEst_3[0, 0]], [xEst_3[1, 0]]]'], {}), '([[xEst_3[0, 0]], [xEst_3[1, 0]]])\n', (4026, 4060), True, 'import numpy as np\n'), ((4088, 4129), 'ekf_1.ekf_estimation', 'ekf_estimation', (['xEst_2', 'PEst_2', 'z_new', 'ud'], {}), '(xEst_2, PEst_2, z_new, ud)\n', (4102, 4129), False, 'from ekf_1 import ekf_estimation\n'), ((4203, 4231), 'numpy.hstack', 'np.hstack', (['(hxEst_1, xEst_1)'], {}), '((hxEst_1, xEst_1))\n', (4212, 4231), True, 'import numpy as np\n'), ((4250, 4278), 'numpy.hstack', 'np.hstack', (['(hxEst_2, xEst_2)'], {}), '((hxEst_2, xEst_2))\n', (4259, 4278), True, 'import numpy as np\n'), ((4297, 4325), 'numpy.hstack', 'np.hstack', (['(hxEst_3, xEst_3)'], {}), '((hxEst_3, xEst_3))\n', (4306, 4325), True, 'import numpy as np\n'), ((4341, 4363), 'numpy.hstack', 'np.hstack', (['(hxDR, xDR)'], {}), '((hxDR, xDR))\n', (4350, 4363), True, 'import numpy as np\n'), ((4381, 4407), 'numpy.hstack', 'np.hstack', (['(hxTrue, xTrue)'], {}), '((hxTrue, xTrue))\n', (4390, 4407), True, 'import numpy as np\n'), ((318, 334), 'numpy.deg2rad', 'np.deg2rad', (['(10.0)'], {}), '(10.0)\n', (328, 334), True, 'import numpy as np\n'), ((1029, 1071), 'numpy.array', 'np.array', (['[[dn, RF_ID[i, 0], RF_ID[i, 1]]]'], {}), '([[dn, RF_ID[i, 0], RF_ID[i, 1]]])\n', (1037, 1071), True, 'import numpy as np\n'), ((1088, 1106), 'numpy.vstack', 'np.vstack', (['(z, zi)'], {}), '((z, zi))\n', (1097, 1106), True, 'import numpy as np\n'), ((1153, 1170), 'numpy.random.randn', 'np.random.randn', ([], {}), '()\n', (1168, 1170), True, 'import numpy as np\n'), ((1212, 1229), 'numpy.random.randn', 'np.random.randn', ([], {}), '()\n', (1227, 1229), True, 'import numpy as np\n'), ((2373, 2385), 'math.cos', 'math.cos', (['it'], {}), '(it)\n', (2381, 2385), False, 'import math\n'), ((2412, 2424), 'math.sin', 'math.sin', (['it'], {}), '(it)\n', (2420, 2424), False, 'import math\n'), ((2663, 2694), 'numpy.array', 'np.array', (['(fx[0, :] + xEst[0, 0])'], {}), '(fx[0, :] + xEst[0, 0])\n', (2671, 2694), True, 'import numpy as np\n'), ((2714, 2745), 'numpy.array', 'np.array', (['(fx[1, :] + xEst[1, 0])'], {}), '(fx[1, :] + xEst[1, 0])\n', (2722, 2745), True, 'import numpy as np\n'), ((5312, 5321), 'matplotlib.pyplot.cla', 'plt.cla', ([], {}), '()\n', (5319, 5321), True, 'import matplotlib.pyplot as plt\n'), ((5579, 5619), 'matplotlib.pyplot.axis', 'plt.axis', ([], {'xlim': '(-25, 25)', 'ylim': '(-10, 30)'}), '(xlim=(-25, 25), ylim=(-10, 30))\n', (5587, 5619), True, 'import matplotlib.pyplot as plt\n'), ((5756, 5798), 'matplotlib.pyplot.plot', 'plt.plot', (['RFi_ID[:, 0]', 'RFi_ID[:, 1]', '"""*k"""'], {}), "(RFi_ID[:, 0], RFi_ID[:, 1], '*k')\n", (5764, 5798), True, 'import matplotlib.pyplot as plt\n'), ((5811, 5845), 'matplotlib.pyplot.plot', 'plt.plot', (['px[0, :]', 'px[1, :]', '""".r"""'], {}), "(px[0, :], px[1, :], '.r')\n", (5819, 5845), True, 'import matplotlib.pyplot as plt\n'), ((7015, 7027), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (7025, 7027), True, 'import matplotlib.pyplot as plt\n'), ((7040, 7054), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (7048, 7054), True, 'import matplotlib.pyplot as plt\n'), ((7067, 7083), 'matplotlib.pyplot.pause', 'plt.pause', (['(0.001)'], {}), '(0.001)\n', (7076, 7083), True, 'import matplotlib.pyplot as plt\n'), ((2524, 2539), 'math.cos', 'math.cos', (['angle'], {}), '(angle)\n', (2532, 2539), False, 'import math\n'), ((2581, 2596), 'math.sin', 'math.sin', (['angle'], {}), '(angle)\n', (2589, 2596), False, 'import math\n'), ((2598, 2613), 'math.cos', 'math.cos', (['angle'], {}), '(angle)\n', (2606, 2613), False, 'import math\n'), ((5679, 5741), 'matplotlib.pyplot.plot', 'plt.plot', (['[xTrue[0, 0], z[i, 1]]', '[xTrue[1, 0], z[i, 2]]', '"""-k"""'], {}), "([xTrue[0, 0], z[i, 1]], [xTrue[1, 0], z[i, 2]], '-k')\n", (5687, 5741), True, 'import matplotlib.pyplot as plt\n'), ((960, 977), 'numpy.random.randn', 'np.random.randn', ([], {}), '()\n', (975, 977), True, 'import numpy as np\n'), ((1531, 1548), 'math.cos', 'math.cos', (['x[2, 0]'], {}), '(x[2, 0])\n', (1539, 1548), False, 'import math\n'), ((1578, 1595), 'math.sin', 'math.sin', (['x[2, 0]'], {}), '(x[2, 0])\n', (1586, 1595), False, 'import math\n'), ((2542, 2557), 'math.sin', 'math.sin', (['angle'], {}), '(angle)\n', (2550, 2557), False, 'import math\n'), ((5533, 5542), 'matplotlib.pyplot.gcf', 'plt.gcf', ([], {}), '()\n', (5540, 5542), True, 'import matplotlib.pyplot as plt\n'), ((5390, 5399), 'matplotlib.pyplot.gcf', 'plt.gcf', ([], {}), '()\n', (5397, 5399), True, 'import matplotlib.pyplot as plt\n'), ((5867, 5889), 'numpy.array', 'np.array', (['hxTrue[0, :]'], {}), '(hxTrue[0, :])\n', (5875, 5889), True, 'import numpy as np\n'), ((5922, 5944), 'numpy.array', 'np.array', (['hxTrue[1, :]'], {}), '(hxTrue[1, :])\n', (5930, 5944), True, 'import numpy as np\n'), ((6005, 6025), 'numpy.array', 'np.array', (['hxDR[0, :]'], {}), '(hxDR[0, :])\n', (6013, 6025), True, 'import numpy as np\n'), ((6060, 6080), 'numpy.array', 'np.array', (['hxDR[1, :]'], {}), '(hxDR[1, :])\n', (6068, 6080), True, 'import numpy as np\n'), ((6141, 6164), 'numpy.array', 'np.array', (['hxEst_1[0, :]'], {}), '(hxEst_1[0, :])\n', (6149, 6164), True, 'import numpy as np\n'), ((6198, 6221), 'numpy.array', 'np.array', (['hxEst_1[1, :]'], {}), '(hxEst_1[1, :])\n', (6206, 6221), True, 'import numpy as np\n'), ((6284, 6307), 'numpy.array', 'np.array', (['hxEst_3[0, :]'], {}), '(hxEst_3[0, :])\n', (6292, 6307), True, 'import numpy as np\n'), ((6341, 6364), 'numpy.array', 'np.array', (['hxEst_3[1, :]'], {}), '(hxEst_3[1, :])\n', (6349, 6364), True, 'import numpy as np\n'), ((6424, 6447), 'numpy.array', 'np.array', (['hxEst_2[0, :]'], {}), '(hxEst_2[0, :])\n', (6432, 6447), True, 'import numpy as np\n'), ((6481, 6504), 'numpy.array', 'np.array', (['hxEst_2[1, :]'], {}), '(hxEst_2[1, :])\n', (6489, 6504), True, 'import numpy as np\n')] |
# <editor-fold desc="Manage Imports">
import tensorflow as tf
import numpy as np
import os
import math
import matplotlib.pyplot as plt
# </editor-fold>
# <editor-fold desc="Get / Prep Data">
#Get/Create Data
numUniqueStages = 4
numDataPoints = 1000
seq_len = 10
numRows, numCols = int(numDataPoints/(seq_len+1)), seq_len+1
stages = np.random.random_integers(low=1, high=numUniqueStages, size=(numRows, numCols))
print(stages[0:5,:])
print(stages.shape)
batch_size = 20
embedDim = 5
hid_dims = [3]
#Make sure the stages are indexed starting 0
minStageValue = np.min(stages)
if(minStageValue != 0): stages = stages - minStageValue
print(stages[0:5,:])
# </editor-fold>
Raw_In = tf.placeholder(name='raw_input_X', dtype=tf.int32, shape=[None, seq_len+1])
OneHot_X = tf.one_hot(name='one_hot_input_X', indices=Raw_In, depth=numUniqueStages)
Y = tf.placeholder(name='raw_input_Y', dtype=tf.int32, shape=[None])
OneHot_Y = tf.one_hot(name='one_hot_input_Y', indices=Y, depth=numUniqueStages)
W_Emb = tf.Variable(initial_value=tf.truncated_normal(shape=[numUniqueStages, embedDim]), dtype=tf.float32)
W_Ho = tf.Variable(initial_value=tf.truncated_normal(shape=[embedDim, numUniqueStages]), dtype=tf.float32)
B_Ho = tf.Variable(initial_value=0.01, dtype=tf.float32)
X = tf.unstack(OneHot_X, axis=1)
rnn_inputs = [tf.matmul(x, W_Emb) for x in X]
lstmCell_1 = tf.contrib.rnn.LSTMCell(num_units = embedDim, activation=tf.tanh)
temp_outputs, states = tf.contrib.rnn.static_rnn(cell=lstmCell_1, inputs=rnn_inputs, dtype=tf.float32)
final_output = tf.sigmoid(tf.add(tf.matmul(temp_outputs[-1], W_Ho), B_Ho))
loss = tf.losses.softmax_cross_entropy(logits=final_output, onehot_labels=OneHot_Y)
train_op = tf.train.AdamOptimizer(learning_rate=0.1).minimize(loss)
with tf.Session() as S:
S.run(tf.global_variables_initializer())
rawinput_X, rawinput_Y = stages[0:batch_size,:], stages[0:batch_size,-1]
rawIn, onehotIn, xInput, rnnInputs, tempOutputs, finalOuput, finalLoss = S.run([Raw_In, OneHot_X, X, rnn_inputs, temp_outputs,
final_output, loss],
feed_dict={Raw_In: rawinput_X, Y:rawinput_Y})
print('Shape of rawIn =', rawIn.shape)
print('Shape of onehotIn =', onehotIn.shape)
# print('Raw In ---->')
# #print(rawIn[0:2,:])
# print('')
# print('One Hot In ---->')
# #print(onehotIn[0:2,:])
print('Length and Shape of first xInput =', len(xInput), ': ', xInput[0].shape )
print('Shape of rnnInputs =', rnnInputs[0].shape)
print('type of tempOutputs =',type(tempOutputs))
print('Length and Shape of first tempOutputs =', len(tempOutputs), ': ', tempOutputs[0].shape)
print('Shape of final Output =', finalOuput.shape)
print('final loss =', finalLoss)
feedDict = {Raw_In: stages[0:batch_size,:], Y:stages[0:batch_size,-1]}
initLoss = S.run(loss, feed_dict=feedDict)
for i in range(20):
_ = S.run(train_op, feed_dict=feedDict)
postLoss = S.run(loss, feed_dict=feedDict)
print('Init Loss =', initLoss)
print('Final Loss =', postLoss) | [
"tensorflow.one_hot",
"tensorflow.unstack",
"tensorflow.contrib.rnn.static_rnn",
"tensorflow.Variable",
"numpy.random.random_integers",
"tensorflow.losses.softmax_cross_entropy",
"tensorflow.placeholder",
"tensorflow.Session",
"tensorflow.global_variables_initializer",
"tensorflow.contrib.rnn.LSTM... | [((333, 412), 'numpy.random.random_integers', 'np.random.random_integers', ([], {'low': '(1)', 'high': 'numUniqueStages', 'size': '(numRows, numCols)'}), '(low=1, high=numUniqueStages, size=(numRows, numCols))\n', (358, 412), True, 'import numpy as np\n'), ((561, 575), 'numpy.min', 'np.min', (['stages'], {}), '(stages)\n', (567, 575), True, 'import numpy as np\n'), ((680, 757), 'tensorflow.placeholder', 'tf.placeholder', ([], {'name': '"""raw_input_X"""', 'dtype': 'tf.int32', 'shape': '[None, seq_len + 1]'}), "(name='raw_input_X', dtype=tf.int32, shape=[None, seq_len + 1])\n", (694, 757), True, 'import tensorflow as tf\n'), ((767, 840), 'tensorflow.one_hot', 'tf.one_hot', ([], {'name': '"""one_hot_input_X"""', 'indices': 'Raw_In', 'depth': 'numUniqueStages'}), "(name='one_hot_input_X', indices=Raw_In, depth=numUniqueStages)\n", (777, 840), True, 'import tensorflow as tf\n'), ((845, 909), 'tensorflow.placeholder', 'tf.placeholder', ([], {'name': '"""raw_input_Y"""', 'dtype': 'tf.int32', 'shape': '[None]'}), "(name='raw_input_Y', dtype=tf.int32, shape=[None])\n", (859, 909), True, 'import tensorflow as tf\n'), ((921, 989), 'tensorflow.one_hot', 'tf.one_hot', ([], {'name': '"""one_hot_input_Y"""', 'indices': 'Y', 'depth': 'numUniqueStages'}), "(name='one_hot_input_Y', indices=Y, depth=numUniqueStages)\n", (931, 989), True, 'import tensorflow as tf\n'), ((1212, 1261), 'tensorflow.Variable', 'tf.Variable', ([], {'initial_value': '(0.01)', 'dtype': 'tf.float32'}), '(initial_value=0.01, dtype=tf.float32)\n', (1223, 1261), True, 'import tensorflow as tf\n'), ((1266, 1294), 'tensorflow.unstack', 'tf.unstack', (['OneHot_X'], {'axis': '(1)'}), '(OneHot_X, axis=1)\n', (1276, 1294), True, 'import tensorflow as tf\n'), ((1354, 1417), 'tensorflow.contrib.rnn.LSTMCell', 'tf.contrib.rnn.LSTMCell', ([], {'num_units': 'embedDim', 'activation': 'tf.tanh'}), '(num_units=embedDim, activation=tf.tanh)\n', (1377, 1417), True, 'import tensorflow as tf\n'), ((1443, 1522), 'tensorflow.contrib.rnn.static_rnn', 'tf.contrib.rnn.static_rnn', ([], {'cell': 'lstmCell_1', 'inputs': 'rnn_inputs', 'dtype': 'tf.float32'}), '(cell=lstmCell_1, inputs=rnn_inputs, dtype=tf.float32)\n', (1468, 1522), True, 'import tensorflow as tf\n'), ((1606, 1682), 'tensorflow.losses.softmax_cross_entropy', 'tf.losses.softmax_cross_entropy', ([], {'logits': 'final_output', 'onehot_labels': 'OneHot_Y'}), '(logits=final_output, onehot_labels=OneHot_Y)\n', (1637, 1682), True, 'import tensorflow as tf\n'), ((1309, 1328), 'tensorflow.matmul', 'tf.matmul', (['x', 'W_Emb'], {}), '(x, W_Emb)\n', (1318, 1328), True, 'import tensorflow as tf\n'), ((1758, 1770), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (1768, 1770), True, 'import tensorflow as tf\n'), ((1024, 1078), 'tensorflow.truncated_normal', 'tf.truncated_normal', ([], {'shape': '[numUniqueStages, embedDim]'}), '(shape=[numUniqueStages, embedDim])\n', (1043, 1078), True, 'import tensorflow as tf\n'), ((1131, 1185), 'tensorflow.truncated_normal', 'tf.truncated_normal', ([], {'shape': '[embedDim, numUniqueStages]'}), '(shape=[embedDim, numUniqueStages])\n', (1150, 1185), True, 'import tensorflow as tf\n'), ((1556, 1589), 'tensorflow.matmul', 'tf.matmul', (['temp_outputs[-1]', 'W_Ho'], {}), '(temp_outputs[-1], W_Ho)\n', (1565, 1589), True, 'import tensorflow as tf\n'), ((1695, 1736), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', ([], {'learning_rate': '(0.1)'}), '(learning_rate=0.1)\n', (1717, 1736), True, 'import tensorflow as tf\n'), ((1787, 1820), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (1818, 1820), True, 'import tensorflow as tf\n')] |
import abc
import csv
from curses import A_ATTRIBUTES
import typing
import numpy as np
from xbbo.core.trials import Trials
# from xbbo.surrogate.base import Surrogate
from xbbo.surrogate.gaussian_process import GPR_sklearn
from xbbo.surrogate.transfer.tst import BaseModel
from xbbo.utils.constants import VERY_SMALL_NUMBER
class ABCWeightStategy(metaclass=abc.ABCMeta):
def __init__(self,
cs,
base_models,
target_model,
rng,**kwargs):
self.space = cs
self.base_models = base_models
self.target_model = target_model
self.rng = rng
@abc.abstractclassmethod
def get_weight(self, trials: Trials):
raise NotImplementedError()
# class RGPE_mean_surrogate_(GP, GPyTorchModel):
# num_outputs = 1
# def __init__(self, models, weights):
# super().__init__()
# self.models = ModuleList(models)
# for m in models:
# if not hasattr(m, "likelihood"):
# raise ValueError(
# "RGPE currently only supports models that have a likelihood (e.g. ExactGPs)"
# )
# self.likelihood = LikelihoodList(*[m.likelihood for m in models])
# self.weights = weights
# self.to(weights)
# # self.candidates = None
# # self.bandwidth = bandwidth
# def forward(self, x):
# weighted_means = []
# non_zero_weight_indices = (self.weights ** 2 > 0).nonzero()
# non_zero_weights = self.weights[non_zero_weight_indices]
# for m_id in range(non_zero_weight_indices.shape[0]):
# model = self.models[non_zero_weight_indices[m_id]]
# posterior = model.posterior(x)
# # posterior_mean = posterior.mean.squeeze(-1) * model.Y_std + model.Y_mean
# posterior_mean = posterior.mean.squeeze(-1)
# # apply weight
# weight = non_zero_weights[m_id]
# weighted_means.append(weight * posterior_mean)
# mean_x = torch.stack(weighted_means).sum(dim=0)/non_zero_weights.sum()
# posterior_cov = posterior.mvn.lazy_covariance_matrix * model.Y_std.pow(2)
# return MultivariateNormal(-mean_x, posterior_cov) # convert to maximize problem
# class RGPE_surrogate_(GP, GPyTorchModel):
# num_outputs = 1
# def __init__(self, models, weights):
# super().__init__()
# self.models = ModuleList(models)
# for m in models:
# if not hasattr(m, "likelihood"):
# raise ValueError(
# "RGPE currently only supports models that have a likelihood (e.g. ExactGPs)"
# )
# self.likelihood = LikelihoodList(*[m.likelihood for m in models])
# self.weights = weights
# self.to(weights)
# # self.candidates = None
# # self.bandwidth = bandwidth
# def forward(self, x):
# weighted_means = []
# weighted_covs = []
# non_zero_weight_indices = (self.weights ** 2 > 0).nonzero()
# non_zero_weights = self.weights[non_zero_weight_indices]
# for m_id in range(non_zero_weight_indices.shape[0]):
# model = self.models[non_zero_weight_indices[m_id]]
# posterior = model.posterior(x)
# # posterior_mean = posterior.mean.squeeze(-1) * model.Y_std + model.Y_mean
# posterior_mean = posterior.mean.squeeze(-1)
# posterior_cov = posterior.mvn.lazy_covariance_matrix
# # apply weight
# weight = non_zero_weights[m_id]
# weighted_means.append(weight * posterior_mean)
# weighted_covs.append(weight*weight * posterior_cov)
# mean_x = torch.stack(weighted_means).sum(dim=0)/non_zero_weights.sum()
# posterior_cov = PsdSumLazyTensor(*weighted_covs)
# return MultivariateNormal(-mean_x, posterior_cov)
class RankingWeight(ABCWeightStategy):
def __init__(self,
cs,
base_models,
target_model,
rng,
budget,
rank_sample_num=256,
is_purn=False,alpha=0, **kwargs):
super().__init__(cs, base_models, target_model, rng, **kwargs)
self.rank_sample_num = rank_sample_num
# self.iter = 0
self.budget = budget
self.is_purn = is_purn
self.alpha = alpha
def _compute_ranking_loss(self, f_samples, f_target):
'''
f_samples 'n_samples x (n) x n' -dim
'''
if f_samples.ndim == 3: # for target model
rank_loss = ((f_samples.diagonal(axis1=-2, axis2=-1)[:, :, None] <
f_samples) ^
(np.expand_dims(f_target, axis=-1) < np.expand_dims(
f_target, axis=-2))).sum(axis=-1).sum(axis=-1)
else:
rank_loss = ((np.expand_dims(f_samples, axis=-1) < np.expand_dims(
f_samples, axis=-2)) ^
(np.expand_dims(f_target, axis=-1) < np.expand_dims(
f_target, axis=-2))).sum(axis=-1).sum(axis=-1)
return rank_loss
def _get_min_index(self, array):
best_model_idxs = np.zeros(array.shape[1], dtype=np.int64)
is_best_model = (array == array.min(axis=0))
# idxs = np.argwhere(is_best_model)
# mod, samp = idxs[:,0], idxs[:, 1]
# self.rng.randint(np.bincount())
for i in range(array.shape[1]):
if is_best_model[-1, i]:
best_model_idxs[i] = len(self.base_models)
else:
best_model_idxs[i] = self.rng.choice(
np.argwhere(is_best_model[:, i]).ravel().tolist())
return best_model_idxs
def get_weight(self, trials: Trials):
t_x = trials.get_array()
t_y = np.asarray(trials._his_observe_value)
self.try_num = len(t_y)
ranking_losses = []
for base_model in self.base_models:
mean, cov = base_model._predict(t_x, "full_cov")
ranking_losses.append(
self._compute_ranking_loss(
self.rng.multivariate_normal(mean,
cov,
size=self.rank_sample_num),
t_y))
ranking_losses.append(
self._compute_ranking_loss(self._get_loocv_preds(t_x, t_y), t_y))
ranking_losses = np.array(ranking_losses)
ranking_losses = self._delete_noise_knowledge(ranking_losses)
# TODO argmin 多个最小处理
# best_model_idxs = ranking_losses.argmin(axis=0) # per sample都有一个best idx
best_model_idxs = self._get_min_index(ranking_losses)
# rank_weight = np.bincount(best_model_idxs, minlength=ranking_losses.shape[0]) / self.rank_sample_num
rank_weight = np.bincount(best_model_idxs,
minlength=ranking_losses.shape[0])
return rank_weight #/ rank_weight.sum()
def _get_loocv_preds(self, x, y):
masks = ~np.eye(self.try_num, dtype=np.bool_)
x_cv = [x[m] for m in masks]
y_cv = [y[m] for m in masks]
samples = []
for i in range(self.try_num):
# kernel = self.new_gp.kernel.copy()
model = GPR_sklearn(self.space,
rng=self.rng,
kernel=self.target_model.kernel,
do_optimize=False)
model.train(x_cv[i], y_cv[i][:, None])
mean, cov = model.predict(x, "full_cov") # TODO 使用kernel子块
# model = GaussianProcessRegressor(self.dim)
# model.fit(x_cv[i], y_cv[i][:, None])
# mean, cov = model.predict_with_cov(x)
samples.append(
self.rng.multivariate_normal(np.squeeze(mean), cov,
self.rank_sample_num))
return np.stack(samples, axis=1)
# def predict_with_sigma(self, newX):
# models = [self.gps[d].cached_predict_with_sigma(newX) for d in range(self.old_D_num)]
# models.append(self.new_gp.predict_with_sigma(newX))
# models = np.asarray(models)
# mu = self.rank_weight.dot(models[:, 0])
# sigma = (self.rank_weight ** 2).dot(models[:, 1] ** 2)
# return mu, np.sqrt(sigma)
def __delete_noise_knowledge(self, ranking_losses):
if self.is_purn:
# p_drop = 1 - (1 - self.x.shape[0] / 30) * (ranking_losses[:-1, :] < ranking_losses[-1, :]).sum(axis=-1) / (
# self.rank_sample_num * (1 + self.alpha))
# mask_to_remove = self.rng.binomial(1, p_drop) == 1
target_loss = ranking_losses[-1]
threshold = np.percentile(target_loss, 95)
mask_to_remove = np.median(
ranking_losses,
axis=1) > threshold # 中位数样本loss 比 95% 的target model结果差
idx_to_remove = np.argwhere(mask_to_remove).ravel()
ranking_losses = np.delete(ranking_losses, idx_to_remove, axis=0)
# ranking_losses[idx_to_remove] = self.rank_sample_num
for idx in reversed(idx_to_remove): # TODO Remove permanent
self.base_models.pop(idx)
# self.old_D_num -= len(idx_to_remove)
return ranking_losses
def _delete_noise_knowledge(self, ranking_losses):
if self.is_purn:
p_drop = 1 - (1 - self.try_num / self.budget) * (ranking_losses[:-1, :] < ranking_losses[-1, :]).sum(axis=-1) / (
self.rank_sample_num * (1 + self.alpha))
mask_to_remove = self.rng.binomial(1, p_drop) == 1
idx_to_remove = np.argwhere(mask_to_remove).ravel()
# ranking_losses = np.delete(ranking_losses, idx_to_remove, axis=0)
ranking_losses[idx_to_remove] = self.rank_sample_num
# ranking_losses[idx_to_remove] = self.rank_sample_num
# for idx in reversed(idx_to_remove): # TODO Remove permanent
# self.base_models.pop(idx)
# self.old_D_num -= len(idx_to_remove)
return ranking_losses
class KernelRegress(ABCWeightStategy):
def __init__(self, cs, base_models, target_model, rng, bandwidth=0.1,**kwargs):
super().__init__(cs, base_models, target_model, rng, **kwargs)
self.bandwidth = bandwidth
# self.is_purn = is_purn
def get_weight(self, trials: Trials):
base_model_means = []
for model in self.base_models:
base_model_means.append(
model._predict_normalize(trials.get_sparse_array(), None)[0])
if not base_model_means:
return []
base_model_means = np.stack(base_model_means) # [model, obs_num, 1]
weight = self._naiveVersion(
base_model_means, np.asarray(trials._his_observe_value))
return weight #/ weight.sum()
def _kendallTauCorrelation(self, base_model_means, y):
if y is None or len(y) < 2:
return np.full(base_model_means.shape[0], 1)
rank_loss = (
(base_model_means[..., None] < base_model_means[..., None, :]) ^
(y[..., None] < y[..., None, :])).astype('float')
base_num, obs_num, _ = rank_loss.shape
# rank_loss = rank_loss
# rank_loss = (rank_loss < 1) * (1 - rank_loss**2) * 3 / 4
num = obs_num * (obs_num - 1) // 2
l = np.empty((base_num, num))
idxs = np.triu_indices(obs_num, 1)
for n in range(base_num):
l[n] = rank_loss[n][idxs]
l = np.linalg.norm(
l / num/2,
axis=1) / self.bandwidth # meta feature : |source-target| / b
l = (l < 1) * (1 - l * l) * 3 / 4
return np.append(l, 3/4)
# t = rank_loss.mean(axis=(-1, -2)) / self.bandwidth
# return (t < 1) * (1 - t * t) * 3 / 4
# return self.rho * (1 - t * t) if t < 1 else 0
def _naiveVersion(self, base_model_means, y):
meta_features = []
for model_predit in base_model_means:
meta_feature = []
for i in range(len(y)):
for j in range(i):
meta_feature.append((model_predit[i] > model_predit[j]) /
(len(y) * (len(y) - 1)))
meta_features.append(meta_feature)
meta_feature = []
for i in range(len(y)):
for j in range(i):
meta_feature.append((y[i] > y[j]) /
(len(y) * (len(y) - 1)))
meta_features.append(meta_feature)
meta_features = np.asarray(meta_features)
def kern(a, b, rho):
def gamma(x):
gamma = 3 / 4 * (1 - x ** 2) if x <= 1 else 0.0
return gamma
kern = gamma(np.linalg.norm(a - b) / rho)
return kern
weights = []
for meta_feature in meta_features:
weights.append(kern(meta_feature, meta_features[-1], self.bandwidth))
return np.asarray(weights)
# class ProductExpert():
# def __init__(self, cs, base_models, target_model, rng):
# self.space = cs
# self.base_models = base_models
# self.target_model = target_model
# # self.rank_sample_num = rank_sample_num
# # self.iter = 0
# self.rng = rng
# # self.is_purn = is_purn
# def get_weight(self, trials: Trials):
# base_model_vars = []
# for model in self.base_models:
# base_model_vars.append(
# model.predict(trials.get_sparse_array())[1])
# if not base_model_vars:
# return []
# base_model_vars = np.concatenate(base_model_vars) # [model, obs_num, 1]
# weight = self._naiveVersion(
# base_model_vars, self.target_model.target_model_predict(trials.get_sparse_array())[1])
# return weight #/ weight.sum()
# def _naiveVersion(self, base_model_vars, target_model_var):
# beta = 1. / (len(base_model_vars)+1)
# weights = [beta / var for var in base_model_vars]
# weights.append(beta / target_model_var)
# return np.array(weights)
class ZeroWeight(ABCWeightStategy):
def __init__(self, cs, base_models, target_model, rng, **kwargs):
super().__init__(cs, base_models, target_model, rng, **kwargs)
def get_weight(self, trials: Trials):
weight = np.zeros(len(self.base_models)+1)
weight[-1] = 1
return weight #/ weight.sum()
| [
"numpy.eye",
"numpy.median",
"numpy.triu_indices",
"numpy.full",
"numpy.delete",
"numpy.asarray",
"numpy.squeeze",
"numpy.append",
"numpy.array",
"numpy.zeros",
"numpy.stack",
"numpy.empty",
"xbbo.surrogate.gaussian_process.GPR_sklearn",
"numpy.argwhere",
"numpy.linalg.norm",
"numpy.ex... | [((5252, 5292), 'numpy.zeros', 'np.zeros', (['array.shape[1]'], {'dtype': 'np.int64'}), '(array.shape[1], dtype=np.int64)\n', (5260, 5292), True, 'import numpy as np\n'), ((5876, 5913), 'numpy.asarray', 'np.asarray', (['trials._his_observe_value'], {}), '(trials._his_observe_value)\n', (5886, 5913), True, 'import numpy as np\n'), ((6504, 6528), 'numpy.array', 'np.array', (['ranking_losses'], {}), '(ranking_losses)\n', (6512, 6528), True, 'import numpy as np\n'), ((6908, 6971), 'numpy.bincount', 'np.bincount', (['best_model_idxs'], {'minlength': 'ranking_losses.shape[0]'}), '(best_model_idxs, minlength=ranking_losses.shape[0])\n', (6919, 6971), True, 'import numpy as np\n'), ((7999, 8024), 'numpy.stack', 'np.stack', (['samples'], {'axis': '(1)'}), '(samples, axis=1)\n', (8007, 8024), True, 'import numpy as np\n'), ((10766, 10792), 'numpy.stack', 'np.stack', (['base_model_means'], {}), '(base_model_means)\n', (10774, 10792), True, 'import numpy as np\n'), ((11477, 11502), 'numpy.empty', 'np.empty', (['(base_num, num)'], {}), '((base_num, num))\n', (11485, 11502), True, 'import numpy as np\n'), ((11518, 11545), 'numpy.triu_indices', 'np.triu_indices', (['obs_num', '(1)'], {}), '(obs_num, 1)\n', (11533, 11545), True, 'import numpy as np\n'), ((11810, 11829), 'numpy.append', 'np.append', (['l', '(3 / 4)'], {}), '(l, 3 / 4)\n', (11819, 11829), True, 'import numpy as np\n'), ((12675, 12700), 'numpy.asarray', 'np.asarray', (['meta_features'], {}), '(meta_features)\n', (12685, 12700), True, 'import numpy as np\n'), ((13098, 13117), 'numpy.asarray', 'np.asarray', (['weights'], {}), '(weights)\n', (13108, 13117), True, 'import numpy as np\n'), ((7112, 7148), 'numpy.eye', 'np.eye', (['self.try_num'], {'dtype': 'np.bool_'}), '(self.try_num, dtype=np.bool_)\n', (7118, 7148), True, 'import numpy as np\n'), ((7351, 7444), 'xbbo.surrogate.gaussian_process.GPR_sklearn', 'GPR_sklearn', (['self.space'], {'rng': 'self.rng', 'kernel': 'self.target_model.kernel', 'do_optimize': '(False)'}), '(self.space, rng=self.rng, kernel=self.target_model.kernel,\n do_optimize=False)\n', (7362, 7444), False, 'from xbbo.surrogate.gaussian_process import GPR_sklearn\n'), ((8810, 8840), 'numpy.percentile', 'np.percentile', (['target_loss', '(95)'], {}), '(target_loss, 95)\n', (8823, 8840), True, 'import numpy as np\n'), ((9078, 9126), 'numpy.delete', 'np.delete', (['ranking_losses', 'idx_to_remove'], {'axis': '(0)'}), '(ranking_losses, idx_to_remove, axis=0)\n', (9087, 9126), True, 'import numpy as np\n'), ((10883, 10920), 'numpy.asarray', 'np.asarray', (['trials._his_observe_value'], {}), '(trials._his_observe_value)\n', (10893, 10920), True, 'import numpy as np\n'), ((11077, 11114), 'numpy.full', 'np.full', (['base_model_means.shape[0]', '(1)'], {}), '(base_model_means.shape[0], 1)\n', (11084, 11114), True, 'import numpy as np\n'), ((11630, 11665), 'numpy.linalg.norm', 'np.linalg.norm', (['(l / num / 2)'], {'axis': '(1)'}), '(l / num / 2, axis=1)\n', (11644, 11665), True, 'import numpy as np\n'), ((8870, 8903), 'numpy.median', 'np.median', (['ranking_losses'], {'axis': '(1)'}), '(ranking_losses, axis=1)\n', (8879, 8903), True, 'import numpy as np\n'), ((7893, 7909), 'numpy.squeeze', 'np.squeeze', (['mean'], {}), '(mean)\n', (7903, 7909), True, 'import numpy as np\n'), ((9013, 9040), 'numpy.argwhere', 'np.argwhere', (['mask_to_remove'], {}), '(mask_to_remove)\n', (9024, 9040), True, 'import numpy as np\n'), ((9745, 9772), 'numpy.argwhere', 'np.argwhere', (['mask_to_remove'], {}), '(mask_to_remove)\n', (9756, 9772), True, 'import numpy as np\n'), ((12884, 12905), 'numpy.linalg.norm', 'np.linalg.norm', (['(a - b)'], {}), '(a - b)\n', (12898, 12905), True, 'import numpy as np\n'), ((4749, 4782), 'numpy.expand_dims', 'np.expand_dims', (['f_target'], {'axis': '(-1)'}), '(f_target, axis=-1)\n', (4763, 4782), True, 'import numpy as np\n'), ((4785, 4818), 'numpy.expand_dims', 'np.expand_dims', (['f_target'], {'axis': '(-2)'}), '(f_target, axis=-2)\n', (4799, 4818), True, 'import numpy as np\n'), ((4917, 4951), 'numpy.expand_dims', 'np.expand_dims', (['f_samples'], {'axis': '(-1)'}), '(f_samples, axis=-1)\n', (4931, 4951), True, 'import numpy as np\n'), ((4954, 4988), 'numpy.expand_dims', 'np.expand_dims', (['f_samples'], {'axis': '(-2)'}), '(f_samples, axis=-2)\n', (4968, 4988), True, 'import numpy as np\n'), ((5035, 5068), 'numpy.expand_dims', 'np.expand_dims', (['f_target'], {'axis': '(-1)'}), '(f_target, axis=-1)\n', (5049, 5068), True, 'import numpy as np\n'), ((5071, 5104), 'numpy.expand_dims', 'np.expand_dims', (['f_target'], {'axis': '(-2)'}), '(f_target, axis=-2)\n', (5085, 5104), True, 'import numpy as np\n'), ((5704, 5736), 'numpy.argwhere', 'np.argwhere', (['is_best_model[:, i]'], {}), '(is_best_model[:, i])\n', (5715, 5736), True, 'import numpy as np\n')] |
import os
import codecs
import numpy as np
#class CoNLL_Sentence:
# def __init__(self, tokens):
# self.tokens = tokens
#class Simplified_CoNLL_Token:
# def __init__(self, token, token_label, sentence_label):
# self.token = token
# self.token_label = token_label
# self.sentence_label = sentence_label
def parse_conll_file(file, multiple=False):
tokens = []
sentences = []
for line in file.readlines():
if(line == "\n"):
if len(tokens) != 0:
#sentence = CoNLL_Sentence(tokens=tokens)
sentences.append(tokens)
tokens = []
else:
print("That should not happen.")
else:
parts = line.split("\t")
if multiple == False:
token = [parts[0], parts[1], parts[2]]#Simplified_CoNLL_Token(token=parts[0], token_label=parts[1], sentence_label=parts[2])
else:
token = [parts[0], parts[1], parts[2], parts[3], parts[4], parts[5]]
tokens.append(token)
return sentences
def parse_conll_files(path, multiple=False):
sentences = []
for subdir, dirs, files in os.walk(path):
for file in files:
with codecs.open(os.path.join(subdir, file), "r", "utf8") as f:
file_sentences = parse_conll_file(f, multiple=multiple)
sentences.append(file_sentences)
return sentences
def transform_to_model_input(sentences):
x = []
y_arg = []
y_rhet = []
for sentence in sentences:
x_sentence = []
y_sentence_arg = []
y_sentence_rhet = []
for token in sentence:
x_sentence.append(token[0])
y_sentence_arg.append(token[1])
y_sentence_rhet.append(token[2])
x.append(np.array(x_sentence))
y_arg.append(np.array(y_sentence_arg))
y_rhet.append(np.array(y_sentence_rhet))
return np.array(x), np.array(y_arg), np.array(y_rhet)
def transform_to_model_input_multiple(sentences):
x = []
y_arg = []
y_rhet = []
y_aspect = []
y_summary = []
y_citation = []
for sentence in sentences:
x_sentence = []
y_sentence_arg = []
y_sentence_rhet = []
y_sentence_aspect = []
y_sentence_summary = []
y_sentence_citation = []
for token in sentence:
x_sentence.append(token[0])
y_sentence_arg.append(token[1])
y_sentence_rhet.append(token[2])
y_sentence_aspect.append(token[3])
y_sentence_summary.append(token[4])
y_sentence_citation.append(token[5])
x.append(np.array(x_sentence))
y_arg.append(np.array(y_sentence_arg))
y_rhet.append(np.array(y_sentence_rhet))
y_aspect.append(np.array(y_sentence_aspect))
y_summary.append(np.array(y_sentence_summary))
y_citation.append(np.array(y_sentence_citation))
return np.array(x), np.array(y_arg), np.array(y_rhet), np.array(y_aspect), np.array(y_summary), np.array(y_citation)
def load_data(path="./../annotations_conll"):
sentences = parse_conll_files(path)
flat_sentences = [item for sublist in sentences for item in sublist]
x, y_arg, y_rhet = transform_to_model_input(flat_sentences)
print("Data size: " + str(len(x)))
return x, y_arg, y_rhet
def load_data_multiple(path=""):
sentences = parse_conll_files(path, multiple=True)
flat_sentences = [item for sublist in sentences for item in sublist]
x, y_arg, y_rhet, y_aspect, y_summary, y_citation = transform_to_model_input_multiple(flat_sentences)
print("Data size: " + str(len(x)))
return x, y_arg, y_rhet, y_aspect, y_summary, y_citation
def main():
print("Process started")
sentences = parse_conll_files("./annotations_conll")
flat_sentences = [item for sublist in sentences for item in sublist]
x, y_arg, y_rhet = transform_to_model_input(flat_sentences)
print("Process ended")
if __name__ == "__main__":
main() | [
"numpy.array",
"os.path.join",
"os.walk"
] | [((1184, 1197), 'os.walk', 'os.walk', (['path'], {}), '(path)\n', (1191, 1197), False, 'import os\n'), ((1947, 1958), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (1955, 1958), True, 'import numpy as np\n'), ((1960, 1975), 'numpy.array', 'np.array', (['y_arg'], {}), '(y_arg)\n', (1968, 1975), True, 'import numpy as np\n'), ((1977, 1993), 'numpy.array', 'np.array', (['y_rhet'], {}), '(y_rhet)\n', (1985, 1993), True, 'import numpy as np\n'), ((2968, 2979), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (2976, 2979), True, 'import numpy as np\n'), ((2981, 2996), 'numpy.array', 'np.array', (['y_arg'], {}), '(y_arg)\n', (2989, 2996), True, 'import numpy as np\n'), ((2998, 3014), 'numpy.array', 'np.array', (['y_rhet'], {}), '(y_rhet)\n', (3006, 3014), True, 'import numpy as np\n'), ((3016, 3034), 'numpy.array', 'np.array', (['y_aspect'], {}), '(y_aspect)\n', (3024, 3034), True, 'import numpy as np\n'), ((3036, 3055), 'numpy.array', 'np.array', (['y_summary'], {}), '(y_summary)\n', (3044, 3055), True, 'import numpy as np\n'), ((3057, 3077), 'numpy.array', 'np.array', (['y_citation'], {}), '(y_citation)\n', (3065, 3077), True, 'import numpy as np\n'), ((1818, 1838), 'numpy.array', 'np.array', (['x_sentence'], {}), '(x_sentence)\n', (1826, 1838), True, 'import numpy as np\n'), ((1861, 1885), 'numpy.array', 'np.array', (['y_sentence_arg'], {}), '(y_sentence_arg)\n', (1869, 1885), True, 'import numpy as np\n'), ((1909, 1934), 'numpy.array', 'np.array', (['y_sentence_rhet'], {}), '(y_sentence_rhet)\n', (1917, 1934), True, 'import numpy as np\n'), ((2674, 2694), 'numpy.array', 'np.array', (['x_sentence'], {}), '(x_sentence)\n', (2682, 2694), True, 'import numpy as np\n'), ((2717, 2741), 'numpy.array', 'np.array', (['y_sentence_arg'], {}), '(y_sentence_arg)\n', (2725, 2741), True, 'import numpy as np\n'), ((2765, 2790), 'numpy.array', 'np.array', (['y_sentence_rhet'], {}), '(y_sentence_rhet)\n', (2773, 2790), True, 'import numpy as np\n'), ((2816, 2843), 'numpy.array', 'np.array', (['y_sentence_aspect'], {}), '(y_sentence_aspect)\n', (2824, 2843), True, 'import numpy as np\n'), ((2870, 2898), 'numpy.array', 'np.array', (['y_sentence_summary'], {}), '(y_sentence_summary)\n', (2878, 2898), True, 'import numpy as np\n'), ((2926, 2955), 'numpy.array', 'np.array', (['y_sentence_citation'], {}), '(y_sentence_citation)\n', (2934, 2955), True, 'import numpy as np\n'), ((1255, 1281), 'os.path.join', 'os.path.join', (['subdir', 'file'], {}), '(subdir, file)\n', (1267, 1281), False, 'import os\n')] |
"""Prepares and verifies specific fcs text section parameters to be used in
data extraction.
Required FCS primary TEXT segment keywords:
$BEGINANALYSIS $BEGINDATA $BEGINSTEXT $BYTEORD $DATATYPE $ENDANALYSIS $ENDDATA
$ENDSTEXT $MODE $NEXTDATA $PAR $TOT $PnB $PnE $PnN $PnR
"""
from collections import namedtuple
import numpy as np
# ------------------------------------------------------------------------------
def x_endian(byte_ord, type_i=True):
"""Determines data byte order based on fcs file format specifications.
Args:
byte_ord: fcs text section value for $BYTEORD
type_i: bool - selects proper return value for $DATATYPE I or F/D
Returns:
str: little|big or <|> for use in converting bytes to numeric.
Raises:
ValueError - fcs documentation specifies only 2 options for this parameter.
"""
if byte_ord == '1,2,3,4':
return 'little' if type_i else '<'
elif byte_ord == '4,3,2,1':
return 'big' if type_i else '>'
else:
raise ValueError
def test_spill_format(spill):
"""Confirms $SPILLOVER value has correct format.
[# channels], [ch 1,...,ch n], [val 1, ..., val n**2]
"""
if ',' not in spill and not spill[0].isdigit():
return False
spill_sep = spill.split(',')
n_par = int(spill_sep[0])
if len(spill_sep) != (1 + n_par + n_par**2):
return False
for val in spill_sep[n_par + 1:]:
try:
float(val)
except ValueError:
return False
return True
def get_dtype_maxval(datatype, word_len):
dmap = {'I':'uint{}'.format(word_len), 'F':'float32', 'D':'float64'}
txt_dtype = dmap.get(datatype)
mode_dtype = np.dtype(txt_dtype)
n_info = np.iinfo if datatype == 'I' else np.finfo
max_value = n_info(mode_dtype).max + 1
return txt_dtype, max_value
# ------------------------------------------------------------------------------
class Metadata(object):
"""Instantiates an FCS Metadata object"""
def __init__(self, version, text):
"""Initialize metadata section for FCS File"""
self.version = version
self._text = text
self._data_spec = {}
self.__spec = None
self._load_keywords()
self._make_spec_pkg()
@property
def spec(self):
return self.__spec
def _add_to_spec(self, keyword, set_val=None, def_val=None, val_format=None):
spec_key = keyword.strip('$').lower()
if val_format:
val = val_format(self._text.get(keyword, def_val))
elif set_val:
val = set_val
else:
val = self._text.get(keyword, def_val)
self._data_spec[spec_key] = val
def _make_spec_pkg(self):
spec_keys = sorted(self._data_spec.keys())
spec_vals = [self._data_spec.get(k) for k in spec_keys]
DataSpec = namedtuple('spec', spec_keys)
self.__spec = DataSpec(*spec_vals)
# --------------------------------------------------------------------------
def _load_keywords(self):
self._required_keywords()
self._set_optional_keywords()
self._set_byteorder()
channels = self._load_channel_spec()
word_len = self._get_word_len(channels)
data_len = self._get_data_len(word_len)
txt_dtype, max_val = get_dtype_maxval(self._text['$DATATYPE'], word_len)
attr_names = ('channels', 'word_len', 'data_len', 'txt_dtype', 'max_val')
vals = (channels, word_len, data_len, txt_dtype, max_val)
for attr_name, val in zip(attr_names, vals):
self._add_to_spec(attr_name, set_val=val)
def _required_keywords(self):
_read_keys = ('$BEGINDATA', '$ENDDATA', '$PAR', '$TOT', '$DATATYPE')
for keyword in _read_keys:
self._add_to_spec(keyword)
def _set_optional_keywords(self):
self._add_to_spec('$TIMESTEP', def_val=1)
if self.version != 'FCS3.0' or '$SPILLOVER' in self._text:
self._add_to_spec('$SPILLOVER')
else:
v3_spill = None
sp_kws = ('$COMP', 'SPILL', 'SPILLOVER')
for kw in sp_kws:
spill = self._text.get(kw, None)
if spill and test_spill_format(spill):
v3_spill = spill
break
self._add_to_spec('$SPILLOVER', set_val=v3_spill)
def _set_byteorder(self):
type_i = self._text['$DATATYPE'] == 'I'
byteord = x_endian(self._text['$BYTEORD'], type_i)
self._add_to_spec('$BYTEORD', set_val=byteord)
self._add_to_spec('type_i', set_val=type_i)
def _get_word_len(self, channels):
all_word_len = set(ch_val['B'] for ch_val in channels.values())
if len(all_word_len) != 1:
return 0
else:
return all_word_len.pop()
def _get_data_len(self, word_len):
par, tot = self._text['$PAR'], self._text['$TOT']
return par * tot * word_len // 8
def _load_channel_spec(self):
"""self.channel['$P9'] = {'N':'long', 'S':'name', 'B':word_len, ...}
"""
n_parameters = self._data_spec['par']
param_attr = ('N', 'S', 'B', 'E', 'R', 'G')
channels = {}
for param_n in range(1, n_parameters + 1):
base = '$P{}'.format(param_n)
par_keywords = (base + attr for attr in param_attr)
vals = [self._text.get(keyword) for keyword in par_keywords]
channels[param_n] = dict(zip(param_attr, vals))
return channels
# ------------------------------------------------------------------------------
| [
"numpy.dtype",
"collections.namedtuple"
] | [((1736, 1755), 'numpy.dtype', 'np.dtype', (['txt_dtype'], {}), '(txt_dtype)\n', (1744, 1755), True, 'import numpy as np\n'), ((2904, 2933), 'collections.namedtuple', 'namedtuple', (['"""spec"""', 'spec_keys'], {}), "('spec', spec_keys)\n", (2914, 2933), False, 'from collections import namedtuple\n')] |
import matplotlib.pyplot as plt
import numpy as np
a1 = plt.subplot2grid((3,3),(0,0),colspan = 2)
a2 = plt.subplot2grid((3,3),(0,2), rowspan = 3)
a3 = plt.subplot2grid((3,3),(1,0),rowspan = 2, colspan = 2)
x = np.arange(1,10)
a2.plot(x, x*x)
a2.set_title('square')
a1.plot(x, np.exp(x))
a1.set_title('exp')
a3.plot(x, np.log(x))
a3.set_title('log')
plt.tight_layout()
plt.show() | [
"numpy.log",
"numpy.exp",
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.subplot2grid",
"numpy.arange",
"matplotlib.pyplot.show"
] | [((58, 101), 'matplotlib.pyplot.subplot2grid', 'plt.subplot2grid', (['(3, 3)', '(0, 0)'], {'colspan': '(2)'}), '((3, 3), (0, 0), colspan=2)\n', (74, 101), True, 'import matplotlib.pyplot as plt\n'), ((105, 148), 'matplotlib.pyplot.subplot2grid', 'plt.subplot2grid', (['(3, 3)', '(0, 2)'], {'rowspan': '(3)'}), '((3, 3), (0, 2), rowspan=3)\n', (121, 148), True, 'import matplotlib.pyplot as plt\n'), ((153, 207), 'matplotlib.pyplot.subplot2grid', 'plt.subplot2grid', (['(3, 3)', '(1, 0)'], {'rowspan': '(2)', 'colspan': '(2)'}), '((3, 3), (1, 0), rowspan=2, colspan=2)\n', (169, 207), True, 'import matplotlib.pyplot as plt\n'), ((214, 230), 'numpy.arange', 'np.arange', (['(1)', '(10)'], {}), '(1, 10)\n', (223, 230), True, 'import numpy as np\n'), ((353, 371), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (369, 371), True, 'import matplotlib.pyplot as plt\n'), ((372, 382), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (380, 382), True, 'import matplotlib.pyplot as plt\n'), ((280, 289), 'numpy.exp', 'np.exp', (['x'], {}), '(x)\n', (286, 289), True, 'import numpy as np\n'), ((322, 331), 'numpy.log', 'np.log', (['x'], {}), '(x)\n', (328, 331), True, 'import numpy as np\n')] |
import PySimpleGUI as sg
from PIL import Image
import os
import io
from typing import Literal, Tuple
import pandas as pd
import json
import numpy as np
CACHE = "cachefile.json"
ANNOTATION = "annotation/"
INDENT = 4
SPACE = " "
NEWLINE = "\n"
# This program includes software developed by jterrace and <NAME>
# in https://stackoverflow.com/questions/10097477/python-json-array-newlines
# Huge thanks to them!
# Changed basestring to str, and dict uses items() instead of iteritems().
def to_json(o, level=0):
ret = ""
if isinstance(o, dict):
ret += "{" + NEWLINE
comma = ""
for k, v in o.items():
ret += comma
comma = ",\n"
ret += SPACE * INDENT * (level + 1)
ret += '"' + str(k) + '":' + SPACE
ret += to_json(v, level + 1)
ret += NEWLINE + SPACE * INDENT * level + "}"
elif isinstance(o, str):
ret += '"' + o + '"'
elif isinstance(o, list):
ret += "[" + ",".join([to_json(e, level + 1) for e in o]) + "]"
# Tuples are interpreted as lists
elif isinstance(o, tuple):
ret += "[" + ",".join(to_json(e, level + 1) for e in o) + "]"
elif isinstance(o, bool):
ret += "true" if o else "false"
elif isinstance(o, int):
ret += str(o)
elif isinstance(o, float):
ret += '%.7g' % o
elif isinstance(o, np.ndarray) and np.issubdtype(o.dtype, np.integer):
ret += "[" + ','.join(map(str, o.flatten().tolist())) + "]"
elif isinstance(o, np.ndarray) and np.issubdtype(o.dtype, np.inexact):
ret += "[" + ','.join(map(lambda x: '%.7g' % x,
o.flatten().tolist())) + "]"
elif o is None:
ret += 'null'
else:
raise TypeError("Unknown type '%s' for json serialization" %
str(type(o)))
return ret
def inspect_annotation_json(
Dir, num_lm, WINDOW_LOC=(None, None)) -> Tuple[str, bool]:
annotation_csv = os.path.join(ANNOTATION, os.path.basename(Dir) + ".csv")
annotation_json = os.path.join(ANNOTATION, os.path.basename(Dir) + ".json")
if not os.path.isfile(annotation_json) or not os.path.isfile(
annotation_csv):
# Create empty json file
pretty_dump({}, annotation_json)
# If csv exist, load json from csv.
# Since we don't know window size yet, only load "xy".
# Will load "mouse_xy" once StateMachine is initiated.
if os.path.isfile(annotation_csv):
dic = {}
df = pd.read_csv(annotation_csv, header=0)
n = len(df)
for i in range(n):
row = df.iloc[i]
xy_data = []
j = 1
row_keys = list(row.keys())
while True:
if f"x{j}" not in row_keys or pd.isnull(row[f"x{j}"]):
break
xy_data.append([int(row[f"x{j}"]), int(row[f"y{j}"])])
j += 1
dic[row["image_name"]] = {"xy": xy_data}
pretty_dump(dic, annotation_json)
return annotation_json
def pretty_dump(data: dict, filename: str):
json_string = to_json(data)
with open(filename, "w") as f:
f.write(json_string)
| [
"pandas.isnull",
"pandas.read_csv",
"os.path.isfile",
"numpy.issubdtype",
"os.path.basename"
] | [((2449, 2479), 'os.path.isfile', 'os.path.isfile', (['annotation_csv'], {}), '(annotation_csv)\n', (2463, 2479), False, 'import os\n'), ((2511, 2548), 'pandas.read_csv', 'pd.read_csv', (['annotation_csv'], {'header': '(0)'}), '(annotation_csv, header=0)\n', (2522, 2548), True, 'import pandas as pd\n'), ((2002, 2023), 'os.path.basename', 'os.path.basename', (['Dir'], {}), '(Dir)\n', (2018, 2023), False, 'import os\n'), ((2081, 2102), 'os.path.basename', 'os.path.basename', (['Dir'], {}), '(Dir)\n', (2097, 2102), False, 'import os\n'), ((2126, 2157), 'os.path.isfile', 'os.path.isfile', (['annotation_json'], {}), '(annotation_json)\n', (2140, 2157), False, 'import os\n'), ((2165, 2195), 'os.path.isfile', 'os.path.isfile', (['annotation_csv'], {}), '(annotation_csv)\n', (2179, 2195), False, 'import os\n'), ((2778, 2801), 'pandas.isnull', 'pd.isnull', (["row[f'x{j}']"], {}), "(row[f'x{j}'])\n", (2787, 2801), True, 'import pandas as pd\n'), ((1390, 1424), 'numpy.issubdtype', 'np.issubdtype', (['o.dtype', 'np.integer'], {}), '(o.dtype, np.integer)\n', (1403, 1424), True, 'import numpy as np\n'), ((1533, 1567), 'numpy.issubdtype', 'np.issubdtype', (['o.dtype', 'np.inexact'], {}), '(o.dtype, np.inexact)\n', (1546, 1567), True, 'import numpy as np\n')] |
from PIL import Image
import numpy as np
from torchvision import transforms, models
import cv2
def load_image_or_video(img_path, shape=None):
in_transform = transforms.Compose([
transforms.Resize((256,256)),
transforms.ToTensor(),
])
vidObj = cv2.VideoCapture(img_path)
frames = []
success = 1
while success:
try:
success, image = vidObj.read()
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
frames.append(image)
except:
pass
return frames
def load_image(img_path):
image = Image.open(img_path).convert('RGB')
in_transform = transforms.Compose([
transforms.Resize((256,256)),
transforms.ToTensor(),
transforms.Normalize((0.485, 0.456, 0.406),
(0.229, 0.224, 0.225))])
image = in_transform(image)[:3,:,:].unsqueeze(0)
return image
def im_convert(tensor):
""" Display a tensor as an image. """
image = tensor.to("cpu").clone().detach()
image = image.numpy().squeeze()
image = image.transpose(1,2,0)
image = image * np.array((0.229, 0.224, 0.225)) + np.array((0.485, 0.456, 0.406))
image = image.clip(0, 1)
return image
| [
"PIL.Image.open",
"numpy.array",
"cv2.VideoCapture",
"cv2.cvtColor",
"torchvision.transforms.Normalize",
"torchvision.transforms.Resize",
"torchvision.transforms.ToTensor"
] | [((329, 355), 'cv2.VideoCapture', 'cv2.VideoCapture', (['img_path'], {}), '(img_path)\n', (345, 355), False, 'import cv2\n'), ((1281, 1312), 'numpy.array', 'np.array', (['(0.485, 0.456, 0.406)'], {}), '((0.485, 0.456, 0.406))\n', (1289, 1312), True, 'import numpy as np\n'), ((207, 236), 'torchvision.transforms.Resize', 'transforms.Resize', (['(256, 256)'], {}), '((256, 256))\n', (224, 236), False, 'from torchvision import transforms, models\n'), ((261, 282), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (280, 282), False, 'from torchvision import transforms, models\n'), ((483, 521), 'cv2.cvtColor', 'cv2.cvtColor', (['image', 'cv2.COLOR_BGR2RGB'], {}), '(image, cv2.COLOR_BGR2RGB)\n', (495, 521), False, 'import cv2\n'), ((646, 666), 'PIL.Image.open', 'Image.open', (['img_path'], {}), '(img_path)\n', (656, 666), False, 'from PIL import Image\n'), ((755, 784), 'torchvision.transforms.Resize', 'transforms.Resize', (['(256, 256)'], {}), '((256, 256))\n', (772, 784), False, 'from torchvision import transforms, models\n'), ((809, 830), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (828, 830), False, 'from torchvision import transforms, models\n'), ((856, 922), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['(0.485, 0.456, 0.406)', '(0.229, 0.224, 0.225)'], {}), '((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))\n', (876, 922), False, 'from torchvision import transforms, models\n'), ((1247, 1278), 'numpy.array', 'np.array', (['(0.229, 0.224, 0.225)'], {}), '((0.229, 0.224, 0.225))\n', (1255, 1278), True, 'import numpy as np\n')] |
# Auto-ML for predicting relational reasoning.
# The model is based on the auto-sklearn library.
import time
import collections
import numpy as np
import ccobra
import autosklearn.classification
# mapping of cardinal direction input
input_mppng = {"north-west": [1,0,0,1], "north":[1,0,0,0], "north-east":[1,1,0,0],
"west": [0,0,0,1], "east":[0,1,0,0],
"south-west": [0,0,1,1], "south":[0,0,1,0], "south-east":[0,1,1,0]}
# mapping of cardinal direction output
output_mppng = {"north-west": [1,0,0,0,0,0,0,0], "north":[0,1,0,0,0,0,0,0], "north-east":[0,0,1,0,0,0,0,0],
"west": [0,0,0,1,0,0,0,0], "east":[0,0,0,0,1,0,0,0],
"south-west": [0,0,0,0,0,1,0,0], "south":[0,0,0,0,0,0,1,0], "south-east":[0,0,0,0,0,0,0,1]}
# Reverse mapping of turning a class label into a cardinal direction.
output_mpp_reverse = {0:"north-west", 1:"north", 2: "north-east",
3:"west", 4:"east",
5:"south-west", 6:"south", 7:"south-east"}
class AutoMLModel(ccobra.CCobraModel):
def __init__(self, name='AutoML', k=1):
super(AutoMLModel, self).__init__(name, ["spatial-relational"], ["single-choice"])
self.automl = autosklearn.classification.AutoSklearnClassifier(time_left_for_this_task=40, per_run_time_limit=8)
self.n_epochs = 1
def pre_train(self, dataset):
x = []
y = []
for subj_train_data in dataset:
for seq_train_data in subj_train_data:
task = seq_train_data['item'].task
inp = input_mppng[task[0][0]] + input_mppng[task[1][0]]
target = output_mppng[seq_train_data['response'][0][0]]
x.append(inp)
y.append(target)
self.train_x = np.array(x)
self.train_y = np.array(y)
self.train_network(self.train_x, self.train_y, self.n_epochs, verbose=True)
def train_network(self, train_x, train_y, n_epochs, verbose=False):
print('Starting training...')
# Shuffle the training data
perm_idxs = np.random.permutation(np.arange(len(train_x)))
train_x = train_x[perm_idxs]
train_y = train_y[perm_idxs]
train_y = np.apply_along_axis(np.argmax,1,train_y)
self.automl.fit(train_x, train_y)
# Turns the predicted, one-hot encoded output into class-label, which is further turned into a cardinal direction.
def predict(self, item, **kwargs):
task = item.task
x = np.array(input_mppng[task[0][0]] + input_mppng[task[1][0]])
output = self.automl.predict(x.reshape(1, -1))
label = output[0]
self.prediction= [output_mpp_reverse[label], task[-1][-1], task[0][1]]
return self.prediction
| [
"numpy.array",
"numpy.apply_along_axis"
] | [((1804, 1815), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (1812, 1815), True, 'import numpy as np\n'), ((1839, 1850), 'numpy.array', 'np.array', (['y'], {}), '(y)\n', (1847, 1850), True, 'import numpy as np\n'), ((2246, 2288), 'numpy.apply_along_axis', 'np.apply_along_axis', (['np.argmax', '(1)', 'train_y'], {}), '(np.argmax, 1, train_y)\n', (2265, 2288), True, 'import numpy as np\n'), ((2535, 2594), 'numpy.array', 'np.array', (['(input_mppng[task[0][0]] + input_mppng[task[1][0]])'], {}), '(input_mppng[task[0][0]] + input_mppng[task[1][0]])\n', (2543, 2594), True, 'import numpy as np\n')] |
from tensorboardX import summary
import numpy as np
import pytest
import unittest
from tensorboardX.utils import make_grid
class UtilsTest(unittest.TestCase):
def test_to_HWC(self):
test_image = np.random.randint(0, 256, size=(3, 32, 32), dtype=np.uint8)
converted = convert_to_HWC(test_image, 'chw')
assert converted.shape == (32, 32, 3)
test_image = np.random.randint(0, 256, size=(16, 3, 32, 32), dtype=np.uint8)
converted = convert_to_HWC(test_image, 'nchw')
assert converted.shape == (64, 256, 3)
test_image = np.random.randint(0, 256, size=(32, 32), dtype=np.uint8)
converted = convert_to_HWC(test_image, 'hw')
assert converted.shape == (32, 32, 3)
def convert_to_HWC(tensor, input_format): # tensor: numpy array
assert(len(set(input_format)) == len(input_format)), "You can not use the same dimension shordhand twice."
assert(len(tensor.shape) == len(input_format)), "size of input tensor and input format are different"
input_format = input_format.upper()
if len(input_format) == 4:
index = [input_format.find(c) for c in 'NCHW']
tensor_NCHW = tensor.transpose(index)
tensor_CHW = make_grid(tensor_NCHW)
return tensor_CHW.transpose(1, 2, 0)
if len(input_format) == 3:
index = [input_format.find(c) for c in 'HWC']
return tensor.transpose(index)
if len(input_format) == 2:
index = [input_format.find(c) for c in 'HW']
tensor = tensor.transpose(index)
tensor = np.stack([tensor, tensor, tensor], 2)
return tensor
| [
"numpy.stack",
"numpy.random.randint",
"tensorboardX.utils.make_grid"
] | [((209, 268), 'numpy.random.randint', 'np.random.randint', (['(0)', '(256)'], {'size': '(3, 32, 32)', 'dtype': 'np.uint8'}), '(0, 256, size=(3, 32, 32), dtype=np.uint8)\n', (226, 268), True, 'import numpy as np\n'), ((390, 453), 'numpy.random.randint', 'np.random.randint', (['(0)', '(256)'], {'size': '(16, 3, 32, 32)', 'dtype': 'np.uint8'}), '(0, 256, size=(16, 3, 32, 32), dtype=np.uint8)\n', (407, 453), True, 'import numpy as np\n'), ((577, 633), 'numpy.random.randint', 'np.random.randint', (['(0)', '(256)'], {'size': '(32, 32)', 'dtype': 'np.uint8'}), '(0, 256, size=(32, 32), dtype=np.uint8)\n', (594, 633), True, 'import numpy as np\n'), ((1210, 1232), 'tensorboardX.utils.make_grid', 'make_grid', (['tensor_NCHW'], {}), '(tensor_NCHW)\n', (1219, 1232), False, 'from tensorboardX.utils import make_grid\n'), ((1546, 1583), 'numpy.stack', 'np.stack', (['[tensor, tensor, tensor]', '(2)'], {}), '([tensor, tensor, tensor], 2)\n', (1554, 1583), True, 'import numpy as np\n')] |
import numpy as np
import typing as t
class ProbRelation:
def __init__(self, probs: t.List[t.List[float]], shape:t.Tuple[int, int]):
self.distibution = np.array(probs)
self.shape = shape | [
"numpy.array"
] | [((165, 180), 'numpy.array', 'np.array', (['probs'], {}), '(probs)\n', (173, 180), True, 'import numpy as np\n')] |
from functools import reduce
from teacher.tree import ID3, FDT
from teacher.tree.tests.fdt_legacy_tree import FDT_Legacy
from teacher.tree.tests.id3_legacy_tree import ID3_Legacy
from pytest import fixture
from sklearn import datasets
from sklearn.model_selection import train_test_split
from teacher.fuzzy import get_fuzzy_variables, get_fuzzy_points, dataset_membership
from teacher.datasets import load_compas, load_beer
from teacher.explanation import FID3_factual, m_factual, mr_factual, c_factual
import numpy as np
import pandas as pd
import random
@fixture
def set_random():
seed = 0
random.seed(seed)
np.random.seed(seed)
return seed
@fixture
def prepare_iris_fdt(set_random):
iris = datasets.load_iris(as_frame=True)
df_numerical_columns = iris.feature_names
df_categorical_columns = []
X_train, X_test, y_train, y_test = train_test_split(iris.data,
iris.target,
test_size=0.33,
random_state=set_random)
X_num = X_train
num_cols = X_num.columns
fuzzy_points = get_fuzzy_points('entropy', num_cols, X_num, y_train)
discrete_fuzzy_values = {col: X_train[col].unique() for col in df_categorical_columns}
fuzzy_variables_order = {col: i for i, col in enumerate(X_train.columns)}
fuzzy_variables = get_fuzzy_variables(fuzzy_points, discrete_fuzzy_values, fuzzy_variables_order)
df_train_membership = dataset_membership(X_train, fuzzy_variables)
df_test_membership = dataset_membership(X_test, fuzzy_variables)
fuzzy_element_idx = 48
fuzzy_element = _get_fuzzy_element(df_test_membership, fuzzy_element_idx)
all_classes = np.unique(iris.target)
return [df_train_membership, df_test_membership, X_train, y_train,
X_test, y_test, fuzzy_element, fuzzy_element_idx, all_classes, df_numerical_columns, fuzzy_variables]
@fixture
def prepare_beer_fdt(set_random):
dataset = load_beer()
df = dataset['df']
class_name = dataset['class_name']
X = df.drop(class_name, axis=1)
y = df[class_name]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=set_random)
df_categorical_columns = dataset['discrete']
class_name = dataset['class_name']
df_categorical_columns.remove(class_name)
df_numerical_columns = dataset['continuous']
X_num = X_train[dataset['continuous']]
num_cols = X_num.columns
fuzzy_points = get_fuzzy_points('entropy', num_cols, X_num, y_train)
discrete_fuzzy_values = {col: df[col].unique() for col in df_categorical_columns}
fuzzy_variables_order = {col: i for i, col in enumerate(X.columns)}
fuzzy_variables = get_fuzzy_variables(fuzzy_points, discrete_fuzzy_values, fuzzy_variables_order)
df_train_membership = dataset_membership(X_train, fuzzy_variables)
df_test_membership = dataset_membership(X_test, fuzzy_variables)
fuzzy_element_idx = 73
fuzzy_element = _get_fuzzy_element(df_test_membership, fuzzy_element_idx)
all_classes = dataset['possible_outcomes']
return [df_train_membership, df_test_membership, X_train, y_train,
X_test, y_test, fuzzy_element, fuzzy_element_idx, all_classes, df_numerical_columns, fuzzy_variables]
def _get_fuzzy_element(fuzzy_X, idx):
element = {}
for feat in fuzzy_X:
element[feat] = {}
for fuzzy_set in fuzzy_X[feat]:
try:
element[feat][str(fuzzy_set)] = pd.to_numeric(fuzzy_X[feat][fuzzy_set][idx])
except ValueError:
element[feat][str(fuzzy_set)] = fuzzy_X[feat][fuzzy_set][idx]
return element
def _get_categorical_fuzzy(var):
x = [var[k] for k in var]
label = {i: j for i, j in enumerate(var)}
return np.array([label[elem] for elem in np.argmax(x, axis=0)])
def _fuzzify_dataset(dataframe, fuzzy_set, fuzzify_variable):
ndf = dataframe.copy()
for k in fuzzy_set:
try:
ndf[str(k)] = pd.to_numeric(fuzzify_variable(fuzzy_set[k]))
except ValueError:
ndf[str(k)] = fuzzify_variable(fuzzy_set[k])
return ndf
def _get_best_rule(rules, op, target=None):
best_rule = []
best_score = 0
for rule in rules:
rule_score = 1
if target is None or target == rule[1]:
for clause in rule[0]:
rule_score = op([rule_score, clause[2]])
if rule_score > best_score:
best_score = rule_score
best_rule = rule
return (best_rule, best_score)
def _alpha_factual_avg(explanations):
avg = reduce(lambda x, y: x + y[1], explanations, 0) / len(explanations)
first_class_dict, first_matching, first_rule = explanations[0]
alpha_factual = [(first_rule, first_matching)]
for class_dict, matching, rule in explanations[1:]:
if matching >= avg:
alpha_factual += [rule]
else:
break
return alpha_factual
def _alpha_factual_robust(explanations, threshold):
# This is the cummulative mu of the
# rules that will be selected
first_class_dict, first_matching, first_rule = explanations[0]
total_mu = first_matching
alpha_factual = [(first_rule, first_matching)]
for class_dict, matching, rule in explanations[1:]:
if total_mu >= threshold:
break
total_mu += matching
alpha_factual += [rule]
return alpha_factual
def _alpha_factual_factor(explanations, alpha):
first_class_dict, first_matching, first_rule = explanations[0]
alpha_factual = [first_rule]
prev_matching = first_matching
for class_dict, matching, rule in explanations[1:]:
factor = prev_matching / matching
if factor <= 1 + alpha:
prev_matching = matching
alpha_factual += [rule]
else:
break
return alpha_factual
def _alpha_factual_factor_sum(explanations, alpha, beta):
first_class_dict, first_matching, first_rule = explanations[0]
alpha_factual = [first_rule]
prev_matching = first_matching
total_mu = first_matching
for class_dict, matching, rule in explanations[1:]:
factor = prev_matching / matching
if total_mu < beta or factor <= 1 + alpha:
prev_matching = matching
total_mu += matching
alpha_factual += [rule]
else:
break
return alpha_factual
def test_explain_id3(set_random):
dataset = load_compas()
df = dataset['df']
class_name = dataset['class_name']
X = df.drop(class_name, axis=1)
y = df[class_name]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=set_random)
idx_record2explain = 1
fuzzy_labels = ['low', 'mid']
discrete = dataset['discrete']
discrete.remove(class_name)
# Dataset Preprocessing
instance = X_train.iloc[idx_record2explain]
X_num = X_train[dataset['continuous']]
num_cols = X_num.columns
fuzzy_points = get_fuzzy_points('equal_width', num_cols, X_num, sets=len(fuzzy_labels))
discrete_fuzzy_values = {col: df[col].unique() for col in discrete}
fuzzy_variables_order = {col: i for i, col in enumerate(X.columns)}
fuzzy_variables = get_fuzzy_variables(fuzzy_points, discrete_fuzzy_values, fuzzy_variables_order)
df_train_membership = dataset_membership(X_train, fuzzy_variables)
df_test_membership = dataset_membership(X_test, fuzzy_variables)
fuzzy_X = _fuzzify_dataset(X_train, df_train_membership, _get_categorical_fuzzy)
X_np = fuzzy_X.values
y_np = y_train.values
id3_class = ID3_Legacy(fuzzy_X.columns, X_np, y_np, max_depth=5, min_num_examples=10, prunning=True, th=0.00000001)
id3_class.fit(X_np, y_np)
explanation = id3_class.explainInstance(instance, idx_record2explain, df_test_membership, discrete, verbose=False)
operator = min
best_rule = _get_best_rule(explanation, operator)[0]
# CONVERTING DISCRETE VALUES TO STRING BECAUSE
# ID3 TREE CASTS TO INT IF IT CAN
for ante, conse in [best_rule]:
for i, clause in enumerate(ante):
if clause[0] in discrete:
ante[i] = (clause[0], str(clause[1]))
new_id3 = ID3(fuzzy_X.columns, max_depth=5, min_num_examples=10, prunning=True, th=0.00000001)
new_id3.fit(X_np, y_np)
f_instance = _get_fuzzy_element(df_train_membership, idx_record2explain)
rules = new_id3.to_rule_based_system()
# CONVERTING DISCRETE VALUES TO STRING BECAUSE
# ID3 TREE CASTS TO INT IF IT CAN
for rule in rules:
for i, ante in enumerate(rule.antecedent):
if ante[0] in discrete:
ante_list = list(rule.antecedent)
ante_list[i] = (ante[0], str(ante[1]))
rule.antecedent = tuple(ante_list)
factual = FID3_factual(f_instance, rules)
for exp_rule, fact_rule in zip([best_rule], [factual]):
for exp_ante, fact_ante in zip(exp_rule[0], fact_rule.antecedent):
assert exp_ante[0] == fact_ante[0]
assert exp_ante[1] == fact_ante[1]
assert fact_rule.consequent == exp_rule[1]
def test_m_factual_fdt(prepare_iris_fdt):
(df_train_membership, _, X_train, y_train,
X_test, _, fuzzy_element, fuzzy_element_idx, _, _, fuzzy_variables) = prepare_iris_fdt
fdt = FDT_Legacy(df_train_membership.keys(), df_train_membership)
fdt.fit(X_train, y_train)
new_fdt = FDT(fuzzy_variables)
new_fdt.fit(X_train, y_train)
fdt_predict = fdt.predict(fuzzy_element)[0]
predicted_best_rules = fdt.explain(fuzzy_element, fdt_predict)
expect_m_factual = _alpha_factual_avg(predicted_best_rules)
new_fdt_predict = new_fdt.predict(X_test.iloc[fuzzy_element_idx].to_numpy().reshape(1, -1))
rules = new_fdt.to_rule_based_system()
ob_m_factual = m_factual(fuzzy_element, rules, new_fdt_predict)
for exp_rule, fact_rule in zip(expect_m_factual, ob_m_factual):
for exp_ante, fact_ante in zip(exp_rule[0], fact_rule.antecedent):
assert exp_ante[0] == fact_ante[0]
assert exp_ante[1] == fact_ante[1]
def test_r_factual_fdt(prepare_beer_fdt):
(df_train_membership, _, X_train, y_train,
X_test, _, fuzzy_element, fuzzy_element_idx, all_classes, _, fuzzy_variables) = prepare_beer_fdt
fdt = FDT_Legacy(df_train_membership.keys(), df_train_membership)
fdt.fit(X_train, y_train)
new_fdt = FDT(fuzzy_variables)
new_fdt.fit(X_train, y_train)
fdt_predict = fdt.predict(fuzzy_element)[0]
predicted_best_rules = fdt.explain(fuzzy_element, fdt_predict)
other_classes = [cv for cv in all_classes if cv != fdt_predict]
fdt_rob_thres = fdt.robust_threshold(fuzzy_element, other_classes)
expect_r_factual = _alpha_factual_robust(predicted_best_rules, fdt_rob_thres)
new_fdt_predict = new_fdt.predict(X_test.iloc[fuzzy_element_idx].to_numpy().reshape(1, -1))
rules = new_fdt.to_rule_based_system()
ob_r_factual = mr_factual(fuzzy_element, rules, new_fdt_predict)
for exp_rule, fact_rule in zip(expect_r_factual, ob_r_factual):
for exp_ante, fact_ante in zip(exp_rule[0], fact_rule.antecedent):
assert exp_ante[0] == fact_ante[0]
assert exp_ante[1] == fact_ante[1]
def test_c_lambda_factual(prepare_iris_fdt):
(df_train_membership, _, X_train, y_train,
X_test, _, fuzzy_element, fuzzy_element_idx, _, _, fuzzy_variables) = prepare_iris_fdt
lam = 0.98
fdt = FDT_Legacy(df_train_membership.keys(), df_train_membership)
fdt.fit(X_train, y_train)
new_fdt = FDT(fuzzy_variables)
new_fdt.fit(X_train, y_train)
fdt_predict = fdt.predict(fuzzy_element)[0]
predicted_best_rules = fdt.explain(fuzzy_element, fdt_predict)
expect_c_factual = _alpha_factual_factor(predicted_best_rules, lam)
new_fdt_predict = new_fdt.predict(X_test.iloc[fuzzy_element_idx].to_numpy().reshape(1, -1))
rules = new_fdt.to_rule_based_system()
ob_c_factual = c_factual(fuzzy_element, rules, new_fdt_predict, lam)
for exp_rule, fact_rule in zip(expect_c_factual, ob_c_factual):
for exp_ante, fact_ante in zip(exp_rule, fact_rule.antecedent):
assert exp_ante[0] == fact_ante[0]
assert exp_ante[1] == fact_ante[1]
def test_c_lambda_factual_complex_fdt(prepare_beer_fdt):
(df_train_membership, _, X_train, y_train,
X_test, _, fuzzy_element, fuzzy_element_idx, _, _, fuzzy_variables) = prepare_beer_fdt
lam = 0
fdt = FDT_Legacy(df_train_membership.keys(), df_train_membership)
fdt.fit(X_train, y_train)
new_fdt = FDT(fuzzy_variables)
new_fdt.fit(X_train, y_train)
fdt_predict = fdt.predict(fuzzy_element)[0]
predicted_best_rules = fdt.explain(fuzzy_element, fdt_predict)
expect_c_factual = _alpha_factual_factor(predicted_best_rules, lam)
new_fdt_predict = new_fdt.predict(X_test.iloc[fuzzy_element_idx].to_numpy().reshape(1, -1))
rules = new_fdt.to_rule_based_system()
ob_c_factual = c_factual(fuzzy_element, rules, new_fdt_predict, lam)
for exp_rule, fact_rule in zip(expect_c_factual, ob_c_factual):
for exp_ante, fact_ante in zip(exp_rule, fact_rule.antecedent):
assert exp_ante[0] == fact_ante[0]
assert exp_ante[1] == fact_ante[1]
def test_c_lambda_beta_factual_fdt(prepare_iris_fdt):
(df_train_membership, _, X_train, y_train,
X_test, _, fuzzy_element, fuzzy_element_idx, _, _, fuzzy_variables) = prepare_iris_fdt
lam = 0.98
beta = 0.5
fdt = FDT_Legacy(df_train_membership.keys(), df_train_membership)
fdt.fit(X_train, y_train)
new_fdt = FDT(fuzzy_variables)
new_fdt.fit(X_train, y_train)
fdt_predict = fdt.predict(fuzzy_element)[0]
predicted_best_rules = fdt.explain(fuzzy_element, fdt_predict)
expect_c_factual = _alpha_factual_factor_sum(predicted_best_rules, lam, beta)
new_fdt_predict = new_fdt.predict(X_test.iloc[fuzzy_element_idx].to_numpy().reshape(1, -1))
rules = new_fdt.to_rule_based_system()
ob_c_factual = c_factual(fuzzy_element, rules, new_fdt_predict, lam, beta)
for exp_rule, fact_rule in zip(expect_c_factual, ob_c_factual):
for exp_ante, fact_ante in zip(exp_rule, fact_rule.antecedent):
assert exp_ante[0] == fact_ante[0]
assert exp_ante[1] == fact_ante[1]
| [
"teacher.explanation.m_factual",
"teacher.explanation.c_factual",
"teacher.explanation.mr_factual",
"numpy.random.seed",
"sklearn.datasets.load_iris",
"teacher.fuzzy.get_fuzzy_variables",
"sklearn.model_selection.train_test_split",
"functools.reduce",
"teacher.datasets.load_compas",
"numpy.argmax"... | [((604, 621), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (615, 621), False, 'import random\n'), ((626, 646), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (640, 646), True, 'import numpy as np\n'), ((719, 752), 'sklearn.datasets.load_iris', 'datasets.load_iris', ([], {'as_frame': '(True)'}), '(as_frame=True)\n', (737, 752), False, 'from sklearn import datasets\n'), ((872, 958), 'sklearn.model_selection.train_test_split', 'train_test_split', (['iris.data', 'iris.target'], {'test_size': '(0.33)', 'random_state': 'set_random'}), '(iris.data, iris.target, test_size=0.33, random_state=\n set_random)\n', (888, 958), False, 'from sklearn.model_selection import train_test_split\n'), ((1191, 1244), 'teacher.fuzzy.get_fuzzy_points', 'get_fuzzy_points', (['"""entropy"""', 'num_cols', 'X_num', 'y_train'], {}), "('entropy', num_cols, X_num, y_train)\n", (1207, 1244), False, 'from teacher.fuzzy import get_fuzzy_variables, get_fuzzy_points, dataset_membership\n'), ((1437, 1516), 'teacher.fuzzy.get_fuzzy_variables', 'get_fuzzy_variables', (['fuzzy_points', 'discrete_fuzzy_values', 'fuzzy_variables_order'], {}), '(fuzzy_points, discrete_fuzzy_values, fuzzy_variables_order)\n', (1456, 1516), False, 'from teacher.fuzzy import get_fuzzy_variables, get_fuzzy_points, dataset_membership\n'), ((1544, 1588), 'teacher.fuzzy.dataset_membership', 'dataset_membership', (['X_train', 'fuzzy_variables'], {}), '(X_train, fuzzy_variables)\n', (1562, 1588), False, 'from teacher.fuzzy import get_fuzzy_variables, get_fuzzy_points, dataset_membership\n'), ((1614, 1657), 'teacher.fuzzy.dataset_membership', 'dataset_membership', (['X_test', 'fuzzy_variables'], {}), '(X_test, fuzzy_variables)\n', (1632, 1657), False, 'from teacher.fuzzy import get_fuzzy_variables, get_fuzzy_points, dataset_membership\n'), ((1783, 1805), 'numpy.unique', 'np.unique', (['iris.target'], {}), '(iris.target)\n', (1792, 1805), True, 'import numpy as np\n'), ((2050, 2061), 'teacher.datasets.load_beer', 'load_beer', ([], {}), '()\n', (2059, 2061), False, 'from teacher.datasets import load_compas, load_beer\n'), ((2224, 2286), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'test_size': '(0.2)', 'random_state': 'set_random'}), '(X, y, test_size=0.2, random_state=set_random)\n', (2240, 2286), False, 'from sklearn.model_selection import train_test_split\n'), ((2563, 2616), 'teacher.fuzzy.get_fuzzy_points', 'get_fuzzy_points', (['"""entropy"""', 'num_cols', 'X_num', 'y_train'], {}), "('entropy', num_cols, X_num, y_train)\n", (2579, 2616), False, 'from teacher.fuzzy import get_fuzzy_variables, get_fuzzy_points, dataset_membership\n'), ((2798, 2877), 'teacher.fuzzy.get_fuzzy_variables', 'get_fuzzy_variables', (['fuzzy_points', 'discrete_fuzzy_values', 'fuzzy_variables_order'], {}), '(fuzzy_points, discrete_fuzzy_values, fuzzy_variables_order)\n', (2817, 2877), False, 'from teacher.fuzzy import get_fuzzy_variables, get_fuzzy_points, dataset_membership\n'), ((2905, 2949), 'teacher.fuzzy.dataset_membership', 'dataset_membership', (['X_train', 'fuzzy_variables'], {}), '(X_train, fuzzy_variables)\n', (2923, 2949), False, 'from teacher.fuzzy import get_fuzzy_variables, get_fuzzy_points, dataset_membership\n'), ((2975, 3018), 'teacher.fuzzy.dataset_membership', 'dataset_membership', (['X_test', 'fuzzy_variables'], {}), '(X_test, fuzzy_variables)\n', (2993, 3018), False, 'from teacher.fuzzy import get_fuzzy_variables, get_fuzzy_points, dataset_membership\n'), ((6562, 6575), 'teacher.datasets.load_compas', 'load_compas', ([], {}), '()\n', (6573, 6575), False, 'from teacher.datasets import load_compas, load_beer\n'), ((6738, 6800), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'test_size': '(0.2)', 'random_state': 'set_random'}), '(X, y, test_size=0.2, random_state=set_random)\n', (6754, 6800), False, 'from sklearn.model_selection import train_test_split\n'), ((7341, 7420), 'teacher.fuzzy.get_fuzzy_variables', 'get_fuzzy_variables', (['fuzzy_points', 'discrete_fuzzy_values', 'fuzzy_variables_order'], {}), '(fuzzy_points, discrete_fuzzy_values, fuzzy_variables_order)\n', (7360, 7420), False, 'from teacher.fuzzy import get_fuzzy_variables, get_fuzzy_points, dataset_membership\n'), ((7448, 7492), 'teacher.fuzzy.dataset_membership', 'dataset_membership', (['X_train', 'fuzzy_variables'], {}), '(X_train, fuzzy_variables)\n', (7466, 7492), False, 'from teacher.fuzzy import get_fuzzy_variables, get_fuzzy_points, dataset_membership\n'), ((7518, 7561), 'teacher.fuzzy.dataset_membership', 'dataset_membership', (['X_test', 'fuzzy_variables'], {}), '(X_test, fuzzy_variables)\n', (7536, 7561), False, 'from teacher.fuzzy import get_fuzzy_variables, get_fuzzy_points, dataset_membership\n'), ((7718, 7820), 'teacher.tree.tests.id3_legacy_tree.ID3_Legacy', 'ID3_Legacy', (['fuzzy_X.columns', 'X_np', 'y_np'], {'max_depth': '(5)', 'min_num_examples': '(10)', 'prunning': '(True)', 'th': '(1e-08)'}), '(fuzzy_X.columns, X_np, y_np, max_depth=5, min_num_examples=10,\n prunning=True, th=1e-08)\n', (7728, 7820), False, 'from teacher.tree.tests.id3_legacy_tree import ID3_Legacy\n'), ((8324, 8403), 'teacher.tree.ID3', 'ID3', (['fuzzy_X.columns'], {'max_depth': '(5)', 'min_num_examples': '(10)', 'prunning': '(True)', 'th': '(1e-08)'}), '(fuzzy_X.columns, max_depth=5, min_num_examples=10, prunning=True, th=1e-08)\n', (8327, 8403), False, 'from teacher.tree import ID3, FDT\n'), ((8928, 8959), 'teacher.explanation.FID3_factual', 'FID3_factual', (['f_instance', 'rules'], {}), '(f_instance, rules)\n', (8940, 8959), False, 'from teacher.explanation import FID3_factual, m_factual, mr_factual, c_factual\n'), ((9540, 9560), 'teacher.tree.FDT', 'FDT', (['fuzzy_variables'], {}), '(fuzzy_variables)\n', (9543, 9560), False, 'from teacher.tree import ID3, FDT\n'), ((9934, 9982), 'teacher.explanation.m_factual', 'm_factual', (['fuzzy_element', 'rules', 'new_fdt_predict'], {}), '(fuzzy_element, rules, new_fdt_predict)\n', (9943, 9982), False, 'from teacher.explanation import FID3_factual, m_factual, mr_factual, c_factual\n'), ((10530, 10550), 'teacher.tree.FDT', 'FDT', (['fuzzy_variables'], {}), '(fuzzy_variables)\n', (10533, 10550), False, 'from teacher.tree import ID3, FDT\n'), ((11081, 11130), 'teacher.explanation.mr_factual', 'mr_factual', (['fuzzy_element', 'rules', 'new_fdt_predict'], {}), '(fuzzy_element, rules, new_fdt_predict)\n', (11091, 11130), False, 'from teacher.explanation import FID3_factual, m_factual, mr_factual, c_factual\n'), ((11686, 11706), 'teacher.tree.FDT', 'FDT', (['fuzzy_variables'], {}), '(fuzzy_variables)\n', (11689, 11706), False, 'from teacher.tree import ID3, FDT\n'), ((12088, 12141), 'teacher.explanation.c_factual', 'c_factual', (['fuzzy_element', 'rules', 'new_fdt_predict', 'lam'], {}), '(fuzzy_element, rules, new_fdt_predict, lam)\n', (12097, 12141), False, 'from teacher.explanation import FID3_factual, m_factual, mr_factual, c_factual\n'), ((12703, 12723), 'teacher.tree.FDT', 'FDT', (['fuzzy_variables'], {}), '(fuzzy_variables)\n', (12706, 12723), False, 'from teacher.tree import ID3, FDT\n'), ((13105, 13158), 'teacher.explanation.c_factual', 'c_factual', (['fuzzy_element', 'rules', 'new_fdt_predict', 'lam'], {}), '(fuzzy_element, rules, new_fdt_predict, lam)\n', (13114, 13158), False, 'from teacher.explanation import FID3_factual, m_factual, mr_factual, c_factual\n'), ((13735, 13755), 'teacher.tree.FDT', 'FDT', (['fuzzy_variables'], {}), '(fuzzy_variables)\n', (13738, 13755), False, 'from teacher.tree import ID3, FDT\n'), ((14147, 14206), 'teacher.explanation.c_factual', 'c_factual', (['fuzzy_element', 'rules', 'new_fdt_predict', 'lam', 'beta'], {}), '(fuzzy_element, rules, new_fdt_predict, lam, beta)\n', (14156, 14206), False, 'from teacher.explanation import FID3_factual, m_factual, mr_factual, c_factual\n'), ((4694, 4740), 'functools.reduce', 'reduce', (['(lambda x, y: x + y[1])', 'explanations', '(0)'], {}), '(lambda x, y: x + y[1], explanations, 0)\n', (4700, 4740), False, 'from functools import reduce\n'), ((3571, 3615), 'pandas.to_numeric', 'pd.to_numeric', (['fuzzy_X[feat][fuzzy_set][idx]'], {}), '(fuzzy_X[feat][fuzzy_set][idx])\n', (3584, 3615), True, 'import pandas as pd\n'), ((3901, 3921), 'numpy.argmax', 'np.argmax', (['x'], {'axis': '(0)'}), '(x, axis=0)\n', (3910, 3921), True, 'import numpy as np\n')] |
import cv2
import numpy as np
def get_coarse_match(conf_matrix, input_height, input_width, resolution):
"""
Predicts coarse matches from conf_matrix
Args:
resolution: image
input_width:
input_height:
conf_matrix: [N, L, S]
Returns:
mkpts0_c: [M, 2]
mkpts1_c: [M, 2]
mconf: [M]
"""
hw0_i = (input_height, input_width)
hw0_c = (input_height // resolution, input_width // resolution)
hw1_c = hw0_c # input images have the same resolution
feature_num = hw0_c[0] * hw0_c[1]
# 3. find all valid coarse matches
# this only works when at most one `True` in each row
mask = conf_matrix
all_j_ids = mask.argmax(axis=2)
j_ids = all_j_ids.squeeze(0)
b_ids = np.zeros_like(j_ids, dtype=np.long)
i_ids = np.arange(feature_num, dtype=np.long)
mconf = conf_matrix[b_ids, i_ids, j_ids]
# 4. Update with matches in original image resolution
scale = hw0_i[0] / hw0_c[0]
mkpts0_c = np.stack(
[i_ids % hw0_c[1], np.trunc(i_ids / hw0_c[1])],
axis=1) * scale
mkpts1_c = np.stack(
[j_ids % hw1_c[1], np.trunc(j_ids / hw1_c[1])],
axis=1) * scale
return mkpts0_c, mkpts1_c, mconf
def make_query_image(frame, img_size):
# ratio preserving resize
img_h, img_w, _ = frame.shape
scale_h = img_size[1] / img_h
scale_w = img_size[0] / img_w
scale_max = max(scale_h, scale_w)
new_size = (int(img_w * scale_max), int(img_h * scale_max))
query_img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
query_img = cv2.resize(query_img, new_size, interpolation=cv2.INTER_LINEAR)
# center crop
x = new_size[0] // 2 - img_size[0] // 2
y = new_size[1] // 2 - img_size[1] // 2
query_img = query_img[y:y + img_size[1], x:x + img_size[0]]
return query_img
| [
"numpy.trunc",
"cv2.cvtColor",
"cv2.resize",
"numpy.zeros_like",
"numpy.arange"
] | [((772, 807), 'numpy.zeros_like', 'np.zeros_like', (['j_ids'], {'dtype': 'np.long'}), '(j_ids, dtype=np.long)\n', (785, 807), True, 'import numpy as np\n'), ((820, 857), 'numpy.arange', 'np.arange', (['feature_num'], {'dtype': 'np.long'}), '(feature_num, dtype=np.long)\n', (829, 857), True, 'import numpy as np\n'), ((1534, 1573), 'cv2.cvtColor', 'cv2.cvtColor', (['frame', 'cv2.COLOR_BGR2GRAY'], {}), '(frame, cv2.COLOR_BGR2GRAY)\n', (1546, 1573), False, 'import cv2\n'), ((1590, 1653), 'cv2.resize', 'cv2.resize', (['query_img', 'new_size'], {'interpolation': 'cv2.INTER_LINEAR'}), '(query_img, new_size, interpolation=cv2.INTER_LINEAR)\n', (1600, 1653), False, 'import cv2\n'), ((1047, 1073), 'numpy.trunc', 'np.trunc', (['(i_ids / hw0_c[1])'], {}), '(i_ids / hw0_c[1])\n', (1055, 1073), True, 'import numpy as np\n'), ((1152, 1178), 'numpy.trunc', 'np.trunc', (['(j_ids / hw1_c[1])'], {}), '(j_ids / hw1_c[1])\n', (1160, 1178), True, 'import numpy as np\n')] |
import numpy as np
import pandas as pd
from functools import reduce
from itertools import combinations_with_replacement
from amlearn.featurize.base import create_featurizer_backend
from amlearn.utils.packing import load_radii
from sklearn.base import BaseEstimator, TransformerMixin
try:
from amlearn.featurize.src import bp_symmfunc
except Exception:
print("import fortran file bp_symmfunc error!\n")
__author__ = "<NAME>"
__email__ = "<EMAIL>"
class BPRadialFunction(BaseEstimator, TransformerMixin):
def __init__(self, bds, atom_type_symbols, pbc=None,
delta_r=0.2, n_r=50, cutoff=6.5,
id_col='id', type_col='type', coords_cols=None,
backend=None, verbose=1, save=True, output_path=None,
output_file_prefix='feature_bp_radial_function',
print_freq=1000):
self.bds = bds
self.pbc = np.array([1, 1, 1]) if pbc is None else pbc
self.atom_type_symbols = atom_type_symbols
self.delta_r = delta_r
self.n_r = n_r
self.cutoff = cutoff
self.id_col = id_col
self.type_col = type_col
self.coords_cols = ["x", "y", "z"] if coords_cols is None \
else coords_cols
self.save = save
self.verbose = verbose
self.backend = backend if backend is not None \
else create_featurizer_backend(output_path=output_path)
self.output_file_prefix = output_file_prefix
self.print_freq = print_freq
@classmethod
def default_from_system(cls, bds, atom_type_symbols, ref_atom_number,
delta_r=0.1, n_r=50, cutoff=None, pbc=None,
sigma_AA=None, radii=None, radius_type="miracle_radius",
id_col='id', type_col='type', coords_cols=None,
backend=None, verbose=1, save=True, output_path=None,
output_file_prefix='feature_bp_radial_function',
print_freq=1000):
radii = load_radii() if radii is None else radii
if sigma_AA is None:
sigma_AA = \
radii[str(ref_atom_number)][radius_type] * 2
delta_r = sigma_AA * delta_r
cutoff = (2.5 * sigma_AA) if cutoff is None else cutoff
return cls(bds=bds, atom_type_symbols=atom_type_symbols, pbc=pbc,
delta_r=delta_r, n_r=n_r, cutoff=cutoff,
id_col=id_col, type_col=type_col, coords_cols=coords_cols,
backend=backend, verbose=verbose, save=save,
output_path=output_path,
output_file_prefix=output_file_prefix,
print_freq=print_freq)
def fit_transform(self, X, y=None, **fit_params):
return self.transform(X)
def transform(self, X):
n_atoms = len(X)
atom_ids = X[[self.id_col]].values
atom_types = X[[self.type_col]].values
atom_coords = X[self.coords_cols].values
radial_funcs = np.zeros(
(n_atoms, self.n_r * len(self.atom_type_symbols)), dtype=np.float)
radial_funcs = bp_symmfunc.bp_radial(
center_atom_ids=atom_ids, center_atom_coords=atom_coords,
atom_ids=atom_ids, atom_types=atom_types,
atom_type_symbols=self.atom_type_symbols,
atom_coords=atom_coords, pbc=self.pbc, bds=self.bds,
cutoff=self.cutoff, delta_r=self.delta_r, n_r=self.n_r,
radial_funcs=radial_funcs, print_freq=self.print_freq)
radial_funcs_df = pd.DataFrame(radial_funcs,
index=atom_ids.transpose().tolist()[0],
columns=self.get_feature_names())
if self.save:
self.backend.save_featurizer_as_dataframe(
output_df=radial_funcs_df, name=self.output_file_prefix)
return radial_funcs_df
def get_feature_names(self):
return reduce(list.__add__,
([["{}_{:.3f}".format(str(t), i)
for i in np.arange(0, self.n_r) * self.delta_r]
for t in self.atom_type_symbols]))
class BPAngularFunction(BaseEstimator, TransformerMixin):
def __init__(self, bds, atom_type_symbols, ksaais, lambdas,
zetas, pbc=None, cutoff=6.5,
id_col='id', type_col='type', coords_cols=None,
backend=None, verbose=1, save=True, output_path=None,
output_file_prefix='feature_bp_angular_function',
print_freq=1000):
self.bds = bds
self.atom_type_symbols = atom_type_symbols
self.ksaais = ksaais
self.lambdas = lambdas
self.zetas = zetas
self.pbc = np.array([1, 1, 1]) if pbc is None else pbc
self.cutoff = cutoff
self.id_col = id_col
self.type_col = type_col
self.coords_cols = ["x", "y", "z"] if coords_cols is None \
else coords_cols
self.save = save
self.verbose = verbose
self.backend = backend if backend is not None \
else create_featurizer_backend(output_path=output_path)
self.output_file_prefix = output_file_prefix
self.print_freq = print_freq
@classmethod
def default_from_system(cls, ref_atom_number, atom_type_symbols, ksaais,
lambdas, zetas, bds, cutoff=None, pbc=None, sigma_AA=None,
radii=None, radius_type="miracle_radius",
id_col='id', type_col='type', coords_cols=None,
backend=None, verbose=1, save=True, output_path=None,
output_file_prefix='feature_bp_angular_function',
print_freq=1000):
radii = load_radii() if radii is None else radii
sigma_AA = sigma_AA if sigma_AA is not None else \
radii[str(ref_atom_number)][radius_type] * 2
ksaais = ksaais * sigma_AA # in this case, ksaais are in the unit of sigma_AA
cutoff = (2.5 * sigma_AA) if cutoff is None else cutoff
return cls(bds=bds, atom_type_symbols=atom_type_symbols,
ksaais=ksaais, lambdas=lambdas, zetas=zetas,
pbc=pbc, cutoff=cutoff,
id_col=id_col, type_col=type_col, coords_cols=coords_cols,
backend=backend, verbose=verbose, save=save,
output_path=output_path,
output_file_prefix=output_file_prefix,
print_freq=print_freq)
def fit_transform(self, X, y=None, **fit_params):
return self.transform(X)
def transform(self, X):
n_atoms = len(X)
n_atom_types = len(self.atom_type_symbols)
atom_ids = X[[self.id_col]].values
atom_types = X[[self.type_col]].values
atom_coords = X[self.coords_cols].values
angular_funcs = \
np.zeros((n_atoms, int(n_atom_types * (n_atom_types + 1) /
2 * len(self.ksaais))),
dtype=np.float)
angular_funcs = bp_symmfunc.bp_angular(
center_atom_ids=atom_ids, center_atom_coords=atom_coords,
atom_ids=atom_ids, atom_types=atom_types,
atom_type_symbols=self.atom_type_symbols,
atom_coords=atom_coords, pbc=self.pbc, bds=self.bds,
ksaais=self.ksaais, lambdas=self.lambdas, zetas=self.zetas,
cutoff=self.cutoff, angular_funcs=angular_funcs,
print_freq=self.print_freq)
angular_funcs_df = pd.DataFrame(angular_funcs,
index=atom_ids.transpose().tolist()[0],
columns=self.get_feature_names())
if self.save:
self.backend.save_featurizer_as_dataframe(
output_df=angular_funcs_df, name=self.output_file_prefix)
return angular_funcs_df
def get_feature_names(self):
return reduce(list.__add__,
([["{}_{}_{:.3f}_{:.3f}_{:.3f}".format(
str(t1), str(t2), i, j, k)
for i, j, k in zip(self.ksaais,
self.lambdas, self.zetas)]
for t1, t2 in combinations_with_replacement(
self.atom_type_symbols, 2)]))
| [
"amlearn.featurize.src.bp_symmfunc.bp_radial",
"amlearn.featurize.src.bp_symmfunc.bp_angular",
"amlearn.featurize.base.create_featurizer_backend",
"itertools.combinations_with_replacement",
"numpy.array",
"amlearn.utils.packing.load_radii",
"numpy.arange"
] | [((3108, 3454), 'amlearn.featurize.src.bp_symmfunc.bp_radial', 'bp_symmfunc.bp_radial', ([], {'center_atom_ids': 'atom_ids', 'center_atom_coords': 'atom_coords', 'atom_ids': 'atom_ids', 'atom_types': 'atom_types', 'atom_type_symbols': 'self.atom_type_symbols', 'atom_coords': 'atom_coords', 'pbc': 'self.pbc', 'bds': 'self.bds', 'cutoff': 'self.cutoff', 'delta_r': 'self.delta_r', 'n_r': 'self.n_r', 'radial_funcs': 'radial_funcs', 'print_freq': 'self.print_freq'}), '(center_atom_ids=atom_ids, center_atom_coords=\n atom_coords, atom_ids=atom_ids, atom_types=atom_types,\n atom_type_symbols=self.atom_type_symbols, atom_coords=atom_coords, pbc=\n self.pbc, bds=self.bds, cutoff=self.cutoff, delta_r=self.delta_r, n_r=\n self.n_r, radial_funcs=radial_funcs, print_freq=self.print_freq)\n', (3129, 3454), False, 'from amlearn.featurize.src import bp_symmfunc\n'), ((7046, 7423), 'amlearn.featurize.src.bp_symmfunc.bp_angular', 'bp_symmfunc.bp_angular', ([], {'center_atom_ids': 'atom_ids', 'center_atom_coords': 'atom_coords', 'atom_ids': 'atom_ids', 'atom_types': 'atom_types', 'atom_type_symbols': 'self.atom_type_symbols', 'atom_coords': 'atom_coords', 'pbc': 'self.pbc', 'bds': 'self.bds', 'ksaais': 'self.ksaais', 'lambdas': 'self.lambdas', 'zetas': 'self.zetas', 'cutoff': 'self.cutoff', 'angular_funcs': 'angular_funcs', 'print_freq': 'self.print_freq'}), '(center_atom_ids=atom_ids, center_atom_coords=\n atom_coords, atom_ids=atom_ids, atom_types=atom_types,\n atom_type_symbols=self.atom_type_symbols, atom_coords=atom_coords, pbc=\n self.pbc, bds=self.bds, ksaais=self.ksaais, lambdas=self.lambdas, zetas\n =self.zetas, cutoff=self.cutoff, angular_funcs=angular_funcs,\n print_freq=self.print_freq)\n', (7068, 7423), False, 'from amlearn.featurize.src import bp_symmfunc\n'), ((901, 920), 'numpy.array', 'np.array', (['[1, 1, 1]'], {}), '([1, 1, 1])\n', (909, 920), True, 'import numpy as np\n'), ((1367, 1417), 'amlearn.featurize.base.create_featurizer_backend', 'create_featurizer_backend', ([], {'output_path': 'output_path'}), '(output_path=output_path)\n', (1392, 1417), False, 'from amlearn.featurize.base import create_featurizer_backend\n'), ((2012, 2024), 'amlearn.utils.packing.load_radii', 'load_radii', ([], {}), '()\n', (2022, 2024), False, 'from amlearn.utils.packing import load_radii\n'), ((4742, 4761), 'numpy.array', 'np.array', (['[1, 1, 1]'], {}), '([1, 1, 1])\n', (4750, 4761), True, 'import numpy as np\n'), ((5103, 5153), 'amlearn.featurize.base.create_featurizer_backend', 'create_featurizer_backend', ([], {'output_path': 'output_path'}), '(output_path=output_path)\n', (5128, 5153), False, 'from amlearn.featurize.base import create_featurizer_backend\n'), ((5728, 5740), 'amlearn.utils.packing.load_radii', 'load_radii', ([], {}), '()\n', (5738, 5740), False, 'from amlearn.utils.packing import load_radii\n'), ((8232, 8288), 'itertools.combinations_with_replacement', 'combinations_with_replacement', (['self.atom_type_symbols', '(2)'], {}), '(self.atom_type_symbols, 2)\n', (8261, 8288), False, 'from itertools import combinations_with_replacement\n'), ((4057, 4079), 'numpy.arange', 'np.arange', (['(0)', 'self.n_r'], {}), '(0, self.n_r)\n', (4066, 4079), True, 'import numpy as np\n')] |
import numpy as np
import matplotlib.pyplot as plt
# Returns a list of tuples representing points
def read_input(file_name: str):
with open(file_name, 'r') as input_file:
point_list = input_file.read().split('\n')
x_coords = []
y_coords = []
for point in point_list:
x_string, y_string = point.split(',')
x_coords.append(float(x_string))
y_coords.append(float(y_string))
return x_coords, y_coords
# Calculate hough space
def calculate_hough_space(x_coords, y_coords):
# Rho and Theta ranges
thetas = np.deg2rad(np.arange(-90, 90))
rhos = []
for x, y in zip(x_coords,y_coords):
line_list = []
for theta in thetas:
# Hesse normal form
r = x * np.cos(theta) + y * np.sin(theta)
line_list.append(r)
rhos.append(line_list)
rhos = np.asarray(rhos)
return thetas, rhos
# Get cross line between two points
def get_cross_line(x, y, theta):
index = np.argwhere(np.diff(np.sign(x - y)) != 0)
theta = theta[index]
rho = x[index]
x_list = np.arange(start=0, stop=7, step=0.5)
y_list = np.zeros(len(x_list))
for i, x in enumerate(x_list):
y_list[i] = ((-np.cos(theta)/np.sin(theta))*x) + (rho/np.sin(theta))
return x_list, y_list
# Display hough space
def show_hough_space(x_list_list, y_list_list, x_coords, y_coords, thetas, rhos):
fig , (ax1, ax2) = plt.subplots(1,2)
# Cartesian space dots
ax1.scatter(x_coords, y_coords)
# Cartesian space lines
for i in range(len(x_list_list)):
ax1.plot(x_list_list[i], y_list_list[i])
# Hough space graph
for rho in rhos:
ax2.plot(thetas, rho)
plt.show()
if __name__ == '__main__':
# Read coordinates from input file
x_coords, y_coords = read_input('input_points.txt')
# Calculate thetas and rhos
thetas, rhos = calculate_hough_space(x_coords, y_coords)
# Get cross lines
x_list_list = []
y_list_list = []
for first_point in range(len(x_coords)-1):
for second_point in range(first_point+1, len(x_coords)):
x_list, y_list = get_cross_line(rhos[first_point], rhos[second_point], thetas)
x_list_list.append(x_list)
y_list_list.append(y_list)
# Plot cartesian space and hough space
show_hough_space(x_list_list, y_list_list, x_coords, y_coords, thetas, rhos) | [
"numpy.asarray",
"numpy.sign",
"numpy.cos",
"numpy.sin",
"matplotlib.pyplot.subplots",
"numpy.arange",
"matplotlib.pyplot.show"
] | [((893, 909), 'numpy.asarray', 'np.asarray', (['rhos'], {}), '(rhos)\n', (903, 909), True, 'import numpy as np\n'), ((1116, 1152), 'numpy.arange', 'np.arange', ([], {'start': '(0)', 'stop': '(7)', 'step': '(0.5)'}), '(start=0, stop=7, step=0.5)\n', (1125, 1152), True, 'import numpy as np\n'), ((1456, 1474), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(2)'], {}), '(1, 2)\n', (1468, 1474), True, 'import matplotlib.pyplot as plt\n'), ((1742, 1752), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1750, 1752), True, 'import matplotlib.pyplot as plt\n'), ((604, 622), 'numpy.arange', 'np.arange', (['(-90)', '(90)'], {}), '(-90, 90)\n', (613, 622), True, 'import numpy as np\n'), ((1037, 1051), 'numpy.sign', 'np.sign', (['(x - y)'], {}), '(x - y)\n', (1044, 1051), True, 'import numpy as np\n'), ((1286, 1299), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (1292, 1299), True, 'import numpy as np\n'), ((784, 797), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (790, 797), True, 'import numpy as np\n'), ((804, 817), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (810, 817), True, 'import numpy as np\n'), ((1260, 1273), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (1266, 1273), True, 'import numpy as np\n'), ((1246, 1259), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (1252, 1259), True, 'import numpy as np\n')] |
import numpy as np
import pandas as pd
from stock.utils.symbol_util import get_stock_symbols, get_archived_trading_dates
from stock.marketdata.storefactory import get_store
from config import store_type
pd.set_option('display.max_rows', None)
store = get_store(store_type)
def get_equity_value(exsymbols, date):
closes = []
for exsymbol in exsymbols:
df = store.get(exsymbol)
if date in df.index:
closes.append(df.loc[date].close)
else:
close = df.loc[:date].iloc[-1].close
closes.append(close)
return np.mean(closes)
exsymbols = store.get_stock_exsymbols()
columns = ["exsymbol", "profit"]
df_date = pd.DataFrame(columns=columns)
for exsymbol in exsymbols:
df = store.get(exsymbol)
if len(df) < 400:
continue
close_min = df.close.iloc[-30:].min()
profit = df.iloc[-1].close / close_min - 1
df_date.loc[len(df_date)] = [exsymbol, profit]
df_date.dropna(how="any", inplace=True)
df_top = df_date.sort_values(["profit"]).tail(10)
df_bottom = df_date.sort_values(["profit"]).head(100)
print(df_top)
| [
"pandas.DataFrame",
"numpy.mean",
"stock.marketdata.storefactory.get_store",
"pandas.set_option"
] | [((204, 243), 'pandas.set_option', 'pd.set_option', (['"""display.max_rows"""', 'None'], {}), "('display.max_rows', None)\n", (217, 243), True, 'import pandas as pd\n'), ((252, 273), 'stock.marketdata.storefactory.get_store', 'get_store', (['store_type'], {}), '(store_type)\n', (261, 273), False, 'from stock.marketdata.storefactory import get_store\n'), ((675, 704), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': 'columns'}), '(columns=columns)\n', (687, 704), True, 'import pandas as pd\n'), ((575, 590), 'numpy.mean', 'np.mean', (['closes'], {}), '(closes)\n', (582, 590), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
"""
Helpers to make constructing features and labels easier.
"""
import numpy as np
from chess_py import color
from chess_py.pieces.piece_const import PieceValues
def extract_features_from_position(board):
"""
Converts board to 1D numpy array consisting of
piece values.
:type: board: Board
:rtype: np.array
"""
fit_values = PieceValues()
# Convert board to 1D numpy array
return np.array([fit_values.val(square, color.white) for square in board])
def classify_position_by_material(positions):
"""
Creates one hot vectors by materials
[0, 0, 1] if white has more material,
[1, 0, 0] if black has more material,
[0, 1, 0] if the material is even.
:param positions: list of all positions to create labels for
:return: features, labels
"""
advantages = np.zeros((len(positions)), dtype=int)
for i, position in enumerate(positions):
material_imbalance = np.sum(position)
if material_imbalance > 1:
print("white {}".format(material_imbalance))
advantages[i][0] = 1
elif material_imbalance < -1:
print("black {}".format(material_imbalance))
advantages[i][2] = 1
else:
print("Material even")
advantages[i][1] = 1
return advantages
| [
"numpy.sum",
"chess_py.pieces.piece_const.PieceValues"
] | [((382, 395), 'chess_py.pieces.piece_const.PieceValues', 'PieceValues', ([], {}), '()\n', (393, 395), False, 'from chess_py.pieces.piece_const import PieceValues\n'), ((973, 989), 'numpy.sum', 'np.sum', (['position'], {}), '(position)\n', (979, 989), True, 'import numpy as np\n')] |
"""
Returns an array of probability for each class at timepoints sampled at the specified rate.
e.g. event_detector(filename, model, 40) will sample the input file at 40 frame intervals
and concatenate
"""
import cv2
import numpy as np
from keras.models import load_model
def videoscan(filename, model_file, sampling_interval, resize=True, verbose=False):
"""Scans video files and performs inference using the provided model
Approach
--------
Inference is performed on clips of size specified by the input size
of the model. The entire video is sampled at the rate specified by
the parameter sampling_interval.
Usage
-----
arr = videoscan(video_filename, model, interval)
np.save(arr, 'labels.npy')
Parameters
----------
filename : str
Path of the video source to be scanned
model_file : serialized Keras model file (hdf5)
A serialized file containing Keras model definition and weights
sampling_interval : int
Number of frames to shift after each inference
resize : bool (default = True)
Toggles resize (set to False if spatial cropping has been used)
verbose : bool (default = False)
Flag to indicate whether to print progress
Returns
-------
A numpy array containing class inference result for each time interval
with the shape (number of time steps X number of classes)
"""
model = load_model(model_file) # Loads Keras model/weights for prediction
input_frames = int(model.input.shape[1]) # number of frames to collect
dim_h = int(model.input.shape[2]) # height of input frames
dim_w = int(model.input.shape[3]) # width of input frames
cap = cv2.VideoCapture(filename)
num_frames = cap.get(cv2.CAP_PROP_FRAME_COUNT)
steps_total = int(num_frames // sampling_interval)
frames = []
probs = []
count = 0
print("Starting scan...")
while True:
ret, frame = cap.read()
if ret == True:
if resize:
frame = cv2.resize(frame, (dim_w, dim_h), interpolation=cv2.INTER_AREA)
else:
# take a center crop of the video frame
center_crop = (frame.shape[1] - frame.shape[0])//2
frame = frame[:,center_crop:center_crop+frame.shape[0],:]
frames.append(frame)
else:
break
if len(frames) == input_frames: #replace with dimension 1 of model input
count += 1
if verbose:
print("Processed {} out of {}".format(count, steps_total))
example = np.array([frames])
example = (example / 255) * 2 - 1
prob = model.predict(example)
#print(prob[0])
# append probabilities and clear frames buffer by sampling interval
probs.append(prob[0])
if sampling_interval < 150:
frames = frames[sampling_interval:]
else:
frames = []
print("Scan completed.")
output = np.array(probs)
return output
| [
"numpy.array",
"cv2.resize",
"keras.models.load_model",
"cv2.VideoCapture"
] | [((1436, 1458), 'keras.models.load_model', 'load_model', (['model_file'], {}), '(model_file)\n', (1446, 1458), False, 'from keras.models import load_model\n'), ((1713, 1739), 'cv2.VideoCapture', 'cv2.VideoCapture', (['filename'], {}), '(filename)\n', (1729, 1739), False, 'import cv2\n'), ((3106, 3121), 'numpy.array', 'np.array', (['probs'], {}), '(probs)\n', (3114, 3121), True, 'import numpy as np\n'), ((2663, 2681), 'numpy.array', 'np.array', (['[frames]'], {}), '([frames])\n', (2671, 2681), True, 'import numpy as np\n'), ((2067, 2130), 'cv2.resize', 'cv2.resize', (['frame', '(dim_w, dim_h)'], {'interpolation': 'cv2.INTER_AREA'}), '(frame, (dim_w, dim_h), interpolation=cv2.INTER_AREA)\n', (2077, 2130), False, 'import cv2\n')] |
# -*- coding=utf8 -*-
# !/usr/bin/env python
try:
import cPickle
except:
import pickle as cPickle
import csv
import json
import random
from datetime import datetime
import dateutil
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pylab as plb
import scipy.stats
from sklearn.metrics import roc_curve, auc
import contingency as cy
# warnings.filterwarnings('ignore')
# import logging
# logging.basicConfig(level=logging.INFO)
# formatter = logging.Formatter('[%(asctime)s] %(name)s-%(levelname)s: %(message)s')
# log = logging.getLogger('dc')
# log.setLevel(logging.INFO)
# get IRR
def compute_irr(start_principal, cashflow):
tt = cashflow.copy()
tt[0] = tt[0] - start_principal
return np.irr(tt) * 12.0
# assign two-d woe
def assign_woe2(woes, bin1, bin2, values1, values2):
results = np.zeros(values1.shape[0])
for i in range(woes.shape[0]):
for j in range(woes.shape[1]):
ind = plb.find((values1>=bin1[i]) & (values1<bin1[i+1]) & \
(values2>=bin2[j]) & (values2<bin2[j+1]))
if ind.shape[0] > 0:
results[ind] = woes[i]
return results
# assign woe2
def assign_woe(woes, bins, values):
results = np.zeros(values.shape[0])
for i in range(woes.shape[0]):
ind = plb.find((values>=bins[i]) & (values<bins[i+1]))
if ind.shape[0] > 0:
results[ind] = woes[i]
return results
def assign_woe_discrete(woes, bins, values):
results = np.zeros(values.shape[0])
others = np.ones(values.shape[0])
for i in range(len(woes)-1):
inds = values==bins[i]
others[plb.find(inds==True)] = 0
if inds.shape[0] > 0:
results[inds] = woes[i]
results[plb.find(others==1)] = woes[-1]
return results
# compute 2-d woe
def woe2(x1, x2, y, bin1=[], bin2=[]):
l1 = len(bin1)
l2 = len(bin2)
woes = np.zeros((l1-1, l2-1))
counts = np.zeros((l1-1, l2-1))
targets = np.zeros((l1-1, l2-1))
for i in range(l1-1):
for j in range(l2-1):
inds = plb.find((x1>=bin1[i]) & (x1<bin1[i+1]) & \
(x2>=bin2[j]) & (x2<bin2[j+1]))
if inds.shape[0] > 0:
p = np.mean(y[inds])
woes[i,j] = np.log(p/(1.0-p))
counts[i,j] = int(inds.shape[0])
targets[i,j] = int(np.sum(y[inds]))
else:
woes[i,j] = 0
counts[i,j] = int(0)
targets[i,j] = int(0)
return woes, counts, targets
# compute woe
def bins2range(bins):
'''
Change
[ -inf, 5.25, 13. , inf, nan]
into
['[-inf, 5.25)', '[5.25, 13.00)', '[13.00, inf)', 'np.nan']
'''
xticks = []
for i in xrange(len(bins)-2):
xticks.append('[{:.2f}, {:.2f})'.format(bins[i], bins[i+1]))
if np.isnan(bins[-1]):
xticks.append('np.nan')
else:
xticks.append('[{:.2f}, {:.2f})'.format(bins[-2], bins[-1]))
return xticks
def woe(x, y, bin=5, auto=True, toplot=True):
if type(bin) != int:
auto = False
if auto:
bins = np.zeros(bin+1)
for i in range(bin+1):
bins[i] = np.percentile(x, np.maximum(0, np.minimum(100, round(100.0/bin*i))))
else:
bins = np.array(bin)
if type(bin) == int and np.unique(x).shape[0]<=10:
temp = np.sort(np.unique(x))
bin = temp.shape[0]
bins = np.zeros(bin+1)
bins[0:bin] = temp
bins[-1] = temp[-1]+1
bin = bins.shape[0]-1
binx = np.zeros(bin)
woes = np.zeros(bin)
counts = np.zeros(bin)
targets = np.zeros(bin)
iv = np.zeros(bin)
cnt_pos = sum(y)
cnt_neg = len(y) - cnt_pos
for i in range(bin):
inds = (x >= bins[i]) & (x < bins[i+1])
#p1 = np.mean(y[inds])+0.00000000000000001
#woes[i] = np.log(p1/(1.0-p1))
counts[i] = np.sum(inds)
targets[i] = np.sum(y[inds])
p1 = 1.0 * targets[i] / cnt_pos + 0.00000000000000001
p2 = 1.0 * (counts[i] - targets[i]) / cnt_neg
woes[i] = np.log(p1/p2)
iv[i] = (p1 - p2) * woes[i]
binx[i] = np.mean(x[inds])
has_na = False
if sum(pd.isnull(x)) > 0:
# Add bin for NA
counts = np.append(counts, [sum(pd.isnull(x))])
targets = np.append(targets,
[sum((y_t for y_t, b_na in zip(y, pd.isnull(x)) if b_na))])
p1 = 1.0 * targets[-1] / cnt_pos + 0.00000000000000001
p2 = 1.0 * (counts[-1] - targets[-1]) / cnt_neg
woes = np.append(woes, [np.log(p1/p2)])
iv = np.append(iv, [(p1 - p2) * woes[-1]])
bins = np.append(bins, [np.nan])
binx = np.append(binx, [np.nan])
has_na = True
if toplot:
plt.bar(np.arange(1,len(binx)+1), counts)
if has_na:
plt.bar(len(binx), counts[-1], alpha=.8, color='g')
plt.bar(np.arange(1,len(binx)+1), targets, color='r')
ax2 = plt.twinx()
plt.plot(np.arange(1,len(binx)+1)+0.5, woes, '.-k', linewidth=2, markersize=10)
plt.xticks(np.arange(1, len(binx)+1)+0.5, bins2range(bins))
for i, j in zip(np.arange(len(x))+1.5, woes):
ax2.annotate(str(round(j, 2)), xy=(i, j), va="center", ha="left",
bbox=dict(boxstyle="round", fc="w"))
return woes, bins, counts, targets, iv
def grouptest( data,factor,target,moderatiolow,moderatiohigh ):
#print('begin testing')
for f in factor:
#print('Testing factor',f)
# find the mode, special dealing
mode=data[f].mode()
data_mode=data.ix[data[f]==mode[0]]
print('Mode=',mode[0],'Mode count=',data_mode[target].count())
moderatio=float(data_mode[target].count())/float(len(data))
print('moderatio',format(moderatio,'5f'))
if moderatio>moderatiohigh :
print('Data Mode Error')
print(f,'test is over\n')
continue
elif ( moderatio>moderatiolow) :
ind10=data_mode[target].ix[data_mode[target]==1].count()
ind00=data_mode[target].ix[data_mode[target]==0].count()
print('Mode Default=',ind10,'Mode NonDefault=',ind00)
drate0=float(ind10)/float(data_mode[target].count())
print('Mode DefaultRate=',format(drate0,'5f'))
data_nonmode=data.ix[data[f] != mode[0]]
gt(data_nonmode,f,target)
else:
print('No special Mode')
gt(data,f,target)
def gt(data,f,target):
# grouptest nonmode data
x0=data[f].quantile(0.01)
x1=data[f].quantile(0.2)
x2=data[f].quantile(0.4)
x3=data[f].quantile(0.6)
x4=data[f].quantile(0.8)
x5=data[f].quantile(.99)
## x0=float(data[f].quantile(0))
## x1=float(data[f].quantile(0.2))
## x2=float(data[f].quantile(0.4))
## x3=float(data[f].quantile(0.6))
## x4=float(data[f].quantile(0.8))
## x5=float(data[f].quantile(1.0))
print('Five Group range',x0,x1,x2,x3,x4,x5)
c1=data[target].ix[(data[f]>=x0)&(data[f]<=x1)].count()
c2=data[target].ix[(data[f]>x1)&(data[f]<=x2)].count()
c3=data[target].ix[(data[f]>x2)&(data[f]<=x3)].count()
c4=data[target].ix[(data[f]>x3)&(data[f]<=x4)].count()
c5=data[target].ix[(data[f]-x4>0)&(data[f]-x5<=0)].count()
print('Five Group Count',c1,c2,c3,c4,c5)
data_default=data.ix[data[target]==1]
data_nondefault=data.ix[data[target]==0]
ind11=data_default[target].ix[(data_default[f]>=x0)&(data_default[f]<=x1)].count()
ind12=data_default[target].ix[(data_default[f]>x1)&(data_default[f]<=x2)].count()
ind13=data_default[target].ix[(data_default[f]>x2)&(data_default[f]<=x3)].count()
ind14=data_default[target].ix[(data_default[f]>x3)&(data_default[f]<=x4)].count()
ind15=data_default[target].ix[(data_default[f]>x4)&(data_default[f]<=x5)].count()
print('Five Group Default Count',ind11,ind12,ind13,ind14,ind15)
try:
drate1=float(ind11)/float(data[target].ix[(data[f]>=x0)&(data[f]<=x1)].count())
except ZeroDivisionError:
print('group1 error')
drate1=-1
try:
drate2=float(ind12)/float(data[target].ix[(data[f]>x1)&(data[f]<=x2)].count())
except ZeroDivisionError:
print('group2 error')
drate2=-1
try:
drate3=float(ind13)/float(data[target].ix[(data[f]>x2)&(data[f]<=x3)].count())
except ZeroDivisionError:
print('group3 error')
drate3=-1
try:
drate4=float(ind14)/float(data[target].ix[(data[f]>x3)&(data[f]<=x4)].count())
except ZeroDivisionError:
print('group4 error')
drate4=-1
try:
drate5=float(ind15)/float(data[target].ix[(data[f]>x4)&(data[f]<=x5)].count())
except ZeroDivisionError:
print('group5 error')
drate5=-1
print('Five Group DefaultRate',format(drate1,'5f'),format(drate2,'5f'),format(drate3,'5f'),format(drate4,'5f'),format(drate5,'5f'))
#print(f,'test is over\n)
plt.subplot(2,1,2)
plt.bar(np.array([x0, x1, x2, x3, x4]), np.log(np.maximum(0, np.array([drate1, drate2, drate3, drate4, drate5]))))
print('Five Group DefaultRate',format(drate1,'5f'),format(drate2,'5f'),format(drate3,'5f'),format(drate4,'5f'),format(drate5,'5f'))
print(f,'test is over\n\n')
return
def factordivide(data,f,point):
l=len(data[f])
v1=data[f].ix[data[f]>point]
v2=data[f].ix[data[f]<point]
v3=np.zeros(l)
data['v1']=v1
data['v2']=v2
data['v3']=v3
return data
# split data
# df -- dataframe
# split -- ratio to split out float (0, 1)
# seed -- random seed to use
def split_data(df, split, seed=1):
random.seed(seed)
rows = random.sample(df.index, int(round(split*(df.shape[0]))))
df_split = df.ix[rows]
df_remaining = df.drop(rows)
return df_split, df_remaining, rows
def hump_variable(df, variable, split_pt):
inds1 = df[variable] <= split_pt
inds2 = df[variable] > split_pt
df[variable+'_1'] = np.zeros(df.shape[0])
df[variable+'_2'] = np.zeros(df.shape[0])
df[variable+'_3'] = np.zeros(df.shape[0])
df[variable+'_1'][inds1] = split_pt - df[variable][inds1]
df[variable+'_2'][inds2] = df[variable][inds2] - split_pt
df[variable+'_3'][inds1] = 1.0
return df
# Turn a categorical series to a few columns of dummy variables
# each unique value will be a separate column
#
# s - a data series
def get_dummies_column(s):
vc = s.value_counts()
names = vc.index
length = vc.values.shape[0]
#print(names)
column_name = s.name;
row_num = s.shape[0]
#print(row_num)
data = np.zeros((row_num, length))
column_names = ['']*(length)
for i in xrange(length):
column_names [i] = column_name + '_' + names[i]
data[:, i] = (s == names[i]).astype(int)
return pd.DataFrame(data, s.index, columns=column_names)
# Turn a list of categorical series to dummy series, append them,
def process_dummies(data, columns):
df = data;
for i in xrange(len(columns)):
column = columns[i]
df[column] = df[column].astype(str)
dummy_series = get_dummies_column(df[column])
df = pd.concat([df, dummy_series], axis=1)
return df
# clean up, floor values to 2*p99 by default
def treat_floor(df, names):
for name in names:
temp = df[name].quantile(0.99)
if temp >= 0:
df[name] = np.minimum(2.0 * temp, df[name])
else:
df[name] = np.minimum(0.5 * temp, df[name])
return df
# clean up, ceiling values to p1*2 by default
def treat_ceiling(df, names):
for name in names:
temp = df[name].quantile(0.01)
if temp > 0:
df[name] = np.maximum(temp*0.5, df[name])
else:
df[name] = np.maximum(temp*2.0, df[name])
return df
# Evaluate output of a logit
# Plot appropriate figures: KS/AUC, score distribution/average score
def evaluate_performance(all_target, predicted, toplot=True):
fpr, tpr, thresholds = roc_curve(all_target, predicted)
roc_auc = auc(fpr, tpr)
ks = max(tpr-fpr)
maxind = plb.find(tpr-fpr == ks)
event_rate = sum(all_target) / 1.0 / all_target.shape[0]
cum_total = tpr * event_rate + fpr * (1-event_rate)
minind = plb.find(abs(cum_total - event_rate) == min(abs(cum_total - event_rate)))
if minind.shape[0] > 0:
minind = minind[0]
print('KS=' + str(round(ks, 3)) + ', AUC=' + str(round(roc_auc,2)) +', N='+str(predicted.shape[0]))
print('At threshold=' + str(round(event_rate, 3)) + ', TPR=' + str(round(tpr[minind],2)) + ', ' + str(int(round(tpr[minind]*event_rate*all_target.shape[0]))) + ' out of ' + str(int(round(event_rate*all_target.shape[0]))))
print('At threshold=' + str(round(event_rate, 3)) + ', FPR=' + str(round(fpr[minind],2)) + ', ' + str(int(round(fpr[minind]*(1.0-event_rate)*all_target.shape[0]))) + ' out of ' + str(int(round((1.0-event_rate)*all_target.shape[0]))) )
# Score average by percentile
binnum = 10
ave_predict = np.zeros((binnum))
ave_target = np.zeros((binnum))
indices = np.argsort(predicted)
binsize = int(round(predicted.shape[0]/1.0/binnum))
for i in range(binnum):
startind = i*binsize
endind = min(predicted.shape[0], (i+1)*binsize)
ave_predict[i] = np.mean(predicted[indices[startind:endind]])
ave_target[i] = np.mean(all_target[indices[startind:endind]])
print('Ave_target: ' + str(ave_target))
print('Ave_predicted: ' + str(ave_predict))
if toplot:
# KS plot
plt.figure(figsize=(20,6))
plt.subplot(1,3,1)
plt.plot(fpr, tpr)
#plt.hold
plt.plot([0,1],[0,1], color='k', linestyle='--', linewidth=2)
plt.title('KS='+str(round(ks,2))+ ' AUC='+str(round(roc_auc,2)), fontsize=20)
plt.plot([fpr[maxind], fpr[maxind]], [fpr[maxind], tpr[maxind]], linewidth=4, color='r')
plt.plot([fpr[minind]], [tpr[minind]], 'k.', markersize=10)
plt.xlim([0,1])
plt.ylim([0,1])
plt.xlabel('False positive', fontsize=20); plt.ylabel('True positive', fontsize=20);
#print('At threshold=' + str(round(event_rate, 3)))
#print(str(round(fpr[minind],2)))
#print(str(int(round(fpr[minind]*(1.0-event_rate)*all_target.shape[0]))))
#print(str(int(round((1.0-event_rate)*all_target.shape[0]))) )
# Score distribution score
plt.subplot(1,3,2)
#print(predicted.columns)
plt.hist(predicted, bins=20)
# plt.hold
plt.axvline(x=np.mean(predicted), linestyle='--')
plt.axvline(x=np.mean(all_target), linestyle='--', color='g')
plt.title('N='+str(all_target.shape[0])+' Tru='+str(round(np.mean(all_target),3))+' Pred='+str(round(np.mean(predicted),3)), fontsize=20)
plt.xlabel('Target rate', fontsize=20)
plt.ylabel('Count', fontsize=20)
plt.subplot(1,3,3)
plt.plot(ave_predict, 'b.-', label='Prediction', markersize=5)
#plt.hold
plt.plot(ave_target, 'r.-', label='Truth', markersize=5)
plt.legend(loc='lower right')
plt.xlabel('Percentile', fontsize=20)
plt.ylabel('Target rate', fontsize=20)
return ks
# Get header row of a file
def get_header(fi):
f = open(fi, 'r')
g = csv.reader(f)
head = g.next()
head = [x.replace('\xef\xbb\xbf', '') for x in head]
f.close()
return head
# Get string for columns to keep to pass to awk
def get_column_string(header, columns, marker='$'):
ss = marker + str(header.index(columns[0])+1)
for i in range(1, len(columns)):
ss = ss + ',' + marker + str(header.index(columns[i])+1)
return ss
# get dataframe that correspond to a unique field
def get_data(g, currentrow, header, fieldtomatch, tomatch):
if len(currentrow) == 0:
return [], []
index = header.index(fieldtomatch)
if currentrow[index] > tomatch:
return [], currentrow
elif currentrow[index] < tomatch:
while True:
try:
row = g.next()
currentrow = row
if row[index] > tomatch:
return [], currentrow
elif row[index] == tomatch:
break
except StopIteration:
return [], []
rows = [currentrow]
while True:
try:
row = g.next()
if row[index] == tomatch:
rows.append(row)
else:
return pd.DataFrame(rows, columns=header), row
except StopIteration:
return pd.DataFrame(rows, columns=header), []
# save an object to a file
def save_object(obj, filename):
with open(filename, 'wb') as output:
cPickle.dump(obj, output, -1)
# locate bins for numeric variables
def bin_loc(value,uvbucket):
if pd.isnull(value):
# NA bins
return (-np.inf, -np.inf)
bins = np.empty(0)
for i in range(len(uvbucket)-1):
if value >= uvbucket[i] and value < uvbucket[i+1]:
bins = (uvbucket[i],uvbucket[i+1])
break
return bins
def woe_calc(bad,good,goodfreq,badfreq):
target_rt = float(bad)/float(badfreq)
non_target_rt = float(good)/float(goodfreq)
if float(bad) != 0.0 and float(bad)/(float(bad) + float(good)) != 1.0:
woe = np.log(float(target_rt/non_target_rt))
elif target_rt == 0.0:
woe = -99999999.0
elif float(bad)/(float(bad) + float(good)) == 1.0:
woe = 99999999.0
return woe
def woe_calc_base(bad,good):
try:
woe = np.log(float(bad/float(bad+good))/float(good/float(bad+good)))
except:
woe = -999999
return woe
# main function: get the reference table for numeric variables
def main_get_numeric_ref_table(df,var,tgt,max_bins):
start_time = datetime.now()
'''
------- Initialize: create the numeric bins -------#
'''
# create bucket
if len(df[var].unique()) < max_bins:
# NA would be the last bin if exists
uvalue = np.sort(df[var].unique())
uvdiff = np.append(np.diff(uvalue).astype(float)/2,0)
uvbucket = np.append(np.nanmin(uvalue), uvalue + uvdiff)
else:
# uvalue = np.empty(0)
# for i in np.arange(max_bins+1):
# try:
# uvalue = np.unique((np.append(uvalue, df[var].quantile(float(i)/float(max_bins)))))
# except:
# pass
q = df.ix[~df[var].isnull(), [var]] \
.quantile(1.*np.arange(max_bins+1)/max_bins) \
.drop_duplicates()
uvalue = list(q[var])
uvdiff = np.append(np.diff(uvalue).astype(float)/2,0)
uvbucket = np.append(np.nanmin(uvalue), uvalue + uvdiff)
# Drop empty bucket
b_bc = np.bincount(np.digitize(df[var].values, uvbucket))
b_idx = np.where(b_bc == 0)
uvbucket = np.delete(uvbucket, b_idx[0][1:])
if df[var].isnull().sum() > 0:
# Append nan bin
uvbucket = np.append(uvbucket, np.nan)
uvbucket[0] = -np.inf
if np.isnan(uvbucket[-1]):
uvbucket[-2] = np.inf
else:
uvbucket[-1] = np.inf
df[var+'_bin'] = df[var].apply(lambda x: bin_loc(x,uvbucket))
col_t = [c for c in df.columns if c != var and c != tgt][0]
ds = df[[var+'_bin', tgt, col_t]].groupby([var+'_bin',tgt]).count().unstack().fillna(value=0)
#ds = df[[var+'_bin',tgt]].groupby([var+'_bin',tgt]).count().unstack()[var+'_bin'].fillna(value=0)
#ds['pop'] = ds[1] + ds[0]
ds['bin'] = [[str(i[0]),str(i[1])] for i in list(ds.index)]
ds = ds.reset_index(drop = True)
chisq = []
for i in range(ds.shape[0]-1):
chisq.append(cy.chi2_contingency(ds.iloc[[i,i+1]][[0,1]])[0])
chisq.append(9999999.0)
ds['chisq'] = chisq
ds.columns =ds.columns.swaplevel(0, 1).droplevel()
ds.columns=[0,1,'bin','chisq']
'''
#------- chimerge: merge the adjacent bins, except bin for NA (bin as ['-inf', '-inf']) -------#
'''
start_time = datetime.now()
inds_na = ds['bin'].apply(lambda b: b == ['-inf', '-inf'])
while (ds.shape[0] > 5) or (ds.shape[0] > 2 and ds.ix[~inds_na, 'chisq'].min() <= scipy.stats.chi2.ppf(0.95, 1)):
start_time = datetime.now()
# calculate chisquare statistic
chisq = []
for i in range(ds.shape[0]-1):
chisq.append(cy.chi2_contingency(ds.irow([i,i+1])[[0,1]])[0])
chisq.append(9999999.0)
ds['chisq'] = chisq
# locate the smallest chisq stat bin by index
#k = np.where(ds.chisq == ds.chisq.min())[0][0] ]
ds_idx_list = list(ds.index)
k = ds_idx_list.index(ds[ds['chisq'] == ds.ix[~inds_na, 'chisq'].min()].index[0])
#print(ds.ix[ds_idx_list[k:k+2]],ds.shape[0],k)
# merge the adjacent bins, drop the second bin
ds.ix[ds_idx_list[k],0:2] = ds.ix[ds_idx_list[k],0:2] + ds.ix[ds_idx_list[k+1],0:2]
ds['bin'].ix[ds_idx_list[k]] = [ds['bin'].ix[ds_idx_list[k]][0],ds['bin'].ix[ds_idx_list[k+1]][1]]
ds = ds.drop(ds_idx_list[k+1],axis=0)
ds=ds.reset_index(drop = True)
#print(ds.ix[ds_idx_list[k:k+2]],ds.shape[0],k)
ds_idx_list = list(ds.index)
if k != 0:
ds['chisq'].ix[ds_idx_list[k-1]] = cy.chi2_contingency(ds.ix[ds_idx_list[k-1:k+1],0:2])[0]
if k < ds.shape[0] - 1:
ds['chisq'].ix[ds_idx_list[k]] = cy.chi2_contingency(ds.ix[ds_idx_list[k:k+2],0:2])[0]
else:
ds['chisq'].ix[ds_idx_list[k]] = 9999999.0
inds_na = ds['bin'].apply(lambda b: b == ['-inf', '-inf'])
end_time = datetime.now()
#print(' Duration of merge bins for each iteration: {}'.format(end_time - start_time))
#if ds.chisq.min() > scipy.stats.chi2.ppf(0.95, 1):
# break
end_time = datetime.now()
print("\n #--------------- 3. Merge bins by chisq rules Done --------------#")
print(' Duration of merge bins by chisq rules: {}'.format(end_time - start_time))
print(" shape of the reduced table: {}".format(ds.shape))
'''
#-------- chimerge: control bin size, except bin for NA (bin as ['-inf', '-inf']) -------#
'''
inds_na = ds['bin'].apply(lambda b: b == ['-inf', '-inf'])
ds_na = ds[inds_na]
ds = ds[~inds_na]
pop_cut = df.shape[0] / 20
ds['pop'] = ds[0] + ds[1]
while ds['pop'].min() < pop_cut and ds.shape[0] > 2:
# calculate chisquare statistic
chisq = []
for i in range(ds.shape[0]-1):
chisq.append(cy.chi2_contingency(ds.irow([i,i+1])[[0,1]])[0])
chisq.append(9999999.0)
ds['chisq'] = chisq
# locate the smallest size by index
ds_idx_list = list(ds.index)
k = ds_idx_list.index(ds[ds['pop'] == ds['pop'].min()].index[0])
if k == len(ds_idx_list) - 1 :
k -= 1
elif ds['chisq'].ix[ds_idx_list[k]] > ds['chisq'].ix[ds_idx_list[k-1]]:
k -= 1
# merge the adjacent binsssss, drop the second bin
ds.ix[ds_idx_list[k],0:2] = ds.ix[ds_idx_list[k],0:2] + ds.ix[ds_idx_list[k+1],0:2]
ds['bin'].ix[ds_idx_list[k]] = [ds['bin'].ix[ds_idx_list[k]][0],ds['bin'].ix[ds_idx_list[k+1]][1]]
ds = ds.drop(ds_idx_list[k+1],axis=0)
ds['pop'] = ds[0] + ds[1]
# Add NaN bin back
ds = pd.concat([ds, ds_na])
ds['pop'] = ds[0] + ds[1]
ds['dft_rto'] = 1.0 * ds[1] / ds['pop']
print("\n #--------------- 4. Done: merge bins by bin size --------------#")
print(" shape of the reduced table: {}".format(ds.shape))
'''
#------- get the reference table -------#
'''
ds = ds.reset_index(drop=True)
ds['ref_table'] = None
goodfreq = ds[0].sum()
badfreq = ds[1].sum()
ds[var+'_nwoe'] = ds.apply(lambda x: woe_calc(x[1],x[0],goodfreq,badfreq), axis=1)
ds['ref_table'] = ds['bin'].apply(lambda x: x[0] + '_' + x[1])
# IVs
ds[var + '_IVs'] = ds.apply(lambda x: x[var+'_nwoe'] * (float(x[1])/badfreq - float(x[0])/goodfreq), axis=1)
# Set order of columns
ds = ds.reindex_axis([0, 1, 'bin', 'dft_rto', 'chisq', 'pop', 'ref_table', var+'_nwoe', var+'_IVs'], axis=1)
ref_table = {}
ref_table = dict(zip(ds['ref_table'],ds[var +'_nwoe']))
ref_table['base'] = woe_calc_base(ds[1].sum(),ds[0].sum())
end_time = datetime.now()
print("\n #--------------- get the reference table --------------#")
print(' Duration of getting the reference table: {}'.format(end_time - start_time))
# IV
# ref_table['IVs'] = ds[var + '_IVs']
ref_table['IV'] = sum(ds[var + '_IVs'])
return ref_table, ds[var + '_IVs'], ds
# reference table from bins
def main_get_numeric_ref_table_fr_bins(df, var, tgt, bins):
start_time = datetime.now()
uvbucket = bins
if df[var].isnull().sum() > 0 and np.nan not in uvbucket:
# Append nan bin
uvbucket = np.append(uvbucket, np.nan)
uvbucket[0] = -np.inf
if np.isnan(uvbucket[-1]):
uvbucket[-2] = np.inf
else:
uvbucket[-1] = np.inf
df[var+'_bin'] = df[var].apply(lambda x: bin_loc(x, uvbucket))
col_t = [c for c in df.columns if c != var and c != tgt][0]
ds = df[[var+'_bin', tgt, col_t]].groupby([var+'_bin',tgt]).count().unstack().fillna(value=0)
#ds = df[[var+'_bin',tgt]].groupby([var+'_bin',tgt]).count().unstack()[var+'_bin'].fillna(value=0)
#ds['pop'] = ds[1] + ds[0]
ds['bin'] = [[str(i[0]),str(i[1])] for i in list(ds.index)]
ds = ds.reset_index(drop = True)
chisq = []
for i in range(ds.shape[0]-1):
chisq.append(cy.chi2_contingency(ds.iloc[[i,i+1]][[0,1]])[0])
chisq.append(9999999.0)
ds['chisq'] = chisq
ds.columns =ds.columns.swaplevel(0, 1).droplevel()
ds.columns=[0, 1, 'bin', 'chisq']
# Add necessary columns
ds['pop'] = ds[0] + ds[1]
ds['dft_rto'] = 1.0 * ds[1] / ds['pop']
ds['ref_table'] = ds['bin'].apply(lambda x: x[0] + '_' + x[1])
goodfreq = ds[0].sum()
badfreq = ds[1].sum()
ds[var+'_nwoe'] = ds.apply(lambda x: woe_calc(x[1],x[0],goodfreq,badfreq), axis=1)
# IVs
ds[var+'_IVs'] = ds.apply(lambda x: x[var+'_nwoe'] * (float(x[1])/badfreq - float(x[0])/goodfreq), axis=1)
# Set order of columns
ds = ds.reindex_axis([0, 1, 'bin', 'dft_rto', 'chisq', 'pop', 'ref_table', var+'_nwoe', var+'_IVs'], axis=1)
# Reference table
ref_table = {}
ref_table = dict(zip(ds['ref_table'],ds[var +'_nwoe']))
ref_table['base'] = woe_calc_base(ds[1].sum(),ds[0].sum())
ref_table['IV'] = sum(ds[var + '_IVs'])
return ref_table, ds[var + '_IVs'], ds
# Update WOE reference table
def update_numeric_woe_info(ref_table, var, b_stat,
ref_table_f, b_stat_f, df_iv_f):
# Update WOE reference table
df_numeric_ref_table = pd.read_csv(ref_table_f)
df_numeric_ref_table.drop(df_numeric_ref_table.loc[df_numeric_ref_table['Var_Name'] == var].index,
inplace=True)
df_ref_table_tmp = pd.DataFrame(ref_table.items(), columns=['Var_Value', 'Ref_Value'])
df_ref_table_tmp['Var_Name'] = var
df_numeric_ref_table = pd.concat((df_numeric_ref_table, df_ref_table_tmp), axis=0)
df_numeric_ref_table.to_csv(ref_table_f, index=False)
def get_bin_range(ref_table, var=None):
'''
Get bin range from reference table.
Var_Value Ref_Value Var_Name
-inf_0.5 0.179195 count_phone
1.5_inf -0.096664 count_phone
0.5_1.5 0.049708 count_phone
base -3.933759 count_phone
IV 0.012190 count_phone
>>> get_bin_range(df_numeric_ref_table, 'count_phone')
[-inf, 0.5, 1.5, inf]
'''
if var is None:
# ref_table has only one variable, and no Var_Name
vv = ref_table['Var_Value']
else:
vv = ref_table.ix[ref_table['Var_Name'] == var, 'Var_Value']
b_lst = []
for v in vv:
if 'base' == v or 'iv' == v.lower():
continue
t_lst = v.split('_')
b_lst.extend([float(b) for b in t_lst])
b_lst = sorted(list(set(b_lst)))
b_lst[-1] += .1
return b_lst
# Bin stats
with open(b_stat_f, 'a') as bf:
# TODO
b_stat.to_csv(bf, sep='~', index=False, encoding='utf8')
bf.write(str(get_bin_range(df_numeric_ref_table, var)))
bf.write('\n')
# IV
df_iv = pd.read_csv(df_iv_f, encoding='utf8')
df_iv.ix[df_iv['var'] == var, 'iv'] = ref_table['IV']
df_iv.to_csv(df_iv_f, index=False, encoding='utf8')
#cvlookup function
def cvlookup(table,key):
if table.has_key(key):
if table[key] == '-99999999.0' :
value = table['base']
else:
value = table[key]
else:
value = table['base']
return value
#nvlookup function
def nvlookup(table,value):
# keylist = table.keys()
# keylist.sort()
# keymaxrange = keylist[-2]
# keyminrange = keylist[0]
# keymax = keylist[-2].split('_')
# keymin = keylist[0].split('_')
ref = None
for key in table.keys():
if key.lower() == 'base' or key.lower() == 'iv':
continue
krange = map(np.float, key.split('_'))
if pd.isnull(value) and krange[1] == -np.inf:
ref = table[key]
break
if value >= krange[0] and value < krange[1]:
if table[key] == '-99999999.0':
ref = table['base']
else:
ref = table[key]
break
# elif value > keymax[1]:
# ref = table[keymaxrange]
# elif value < keymin[1]):
# ref = table[keyminrange]
return ref
def calc_nominal_woe(df, var, tgt):
'''
Calculate woe for nominal variable.
Return: ref_table, IV, binned_df
'''
#
if df[var].count() == 0:
return None, None, None
# Make NA as a bin
vval_na = 'NA'
i = 0
while vval_na in df[var].values:
vval_na = 'NA_{:02d}'.format(i)
i += 1
df.fillna({var: vval_na}, inplace=True)
# ds = df[[var, tgt, 'userid']].groupby([var, tgt]).count().unstack().fillna(value=0)
col_t = [c for c in df.columns if c != var and c != tgt][0]
ds = df[[var, tgt, col_t]].groupby([var, tgt]).count().unstack().fillna(value=0)
ds.columns = ds.columns.droplevel(0)
ds.reset_index(inplace=True)
# Change to list
ds[var] = ds[var].apply(lambda v: [v])
# Merge small bins first
is_small = ((ds[0] + ds[1]) / df.shape[0]) < 0.02
while sum(is_small) > 0:
small_sum = ds.loc[is_small].sum()
ds.drop(ds[is_small].index, inplace=True)
ds = ds.append(pd.DataFrame(small_sum).transpose(), ignore_index=True)
# Population ratio after sum
pop_rto = ((ds[0] + ds[1]) / df.shape[0])
is_small = pop_rto < 0.02
if sum(is_small) == 1:
# To merge into 2nd least bin when merged bin is still too small
is_small[pop_rto[:-1].argmin()] = True
# dft_rto = df[[var, tgt]].groupby(var).mean().rename(columns={tgt: 'dft_rto'}).reset_index()
# ds = ds.merge(dft_rto, on=var).sort_values('dft_rto').reset_index(drop=True)
ds['dft_rto'] = ds[1] / ds[[0, 1]].sum(axis=1)
ds = ds.sort_values('dft_rto').reset_index(drop=True)
# Replace NA back
try:
df.replace({var: {vval_na: np.nan}}, inplace=True)
except TypeError:
# TypeError: Cannot compare types 'ndarray(dtype=float64)' and 'str'
# Only float in this column
pass
# Calc initial chisquare statistic
chisq = []
for i in range(ds.shape[0]-1):
chisq.append(cy.chi2_contingency(ds.iloc[[i,i+1]][[0,1]])[0])
chisq.append(9999999.0)
ds['chisq'] = chisq
'''
#------- chimerge: merge the adjacent bins -------#
'''
# min_bin = max(np.ceil(1.0 * ds.shape[0] / 3), 5)
# while (ds.shape[0] > min_bin) and (ds.chisq.min() <= scipy.stats.chi2.ppf(0.95, 1)):
while (ds.shape[0] > 5) or (ds.shape[0] > 2 and ds.chisq.min() <= scipy.stats.chi2.ppf(0.95, 1)):
# locate the smallest chisq stat bin by index
ds_idx_list = list(ds.index)
k = ds_idx_list.index(ds[ds.chisq == ds.chisq.min()].index[0])
# merge the adjacent bins, drop the second bin
ds.ix[ds_idx_list[k], [var, 0, 1]] = ds.ix[[ds_idx_list[k], ds_idx_list[k+1]], [var, 0, 1]].sum()
ds.ix[ds_idx_list[k], 'dft_rto'] = 1.0 * ds.ix[ds_idx_list[k], 1] / (ds.ix[ds_idx_list[k], 0] + ds.ix[ds_idx_list[k], 1])
ds = ds.drop(ds_idx_list[k+1], axis=0)
ds=ds.reset_index(drop=True)
if k != 0:
ds.ix[ds_idx_list[k-1], 'chisq'] = cy.chi2_contingency(ds.iloc[ds_idx_list[k-1:k+1]][[0, 1]])[0]
if k < ds.shape[0] - 1:
ds.ix[ds_idx_list[k], 'chisq'] = cy.chi2_contingency(ds.iloc[ds_idx_list[k:k+2]][[0, 1]])[0]
else:
ds.ix[ds_idx_list[k], 'chisq'] = 9999999.0
'''
#-------- chimerge: control bin size -------#
'''
pop_cut = float(ds[0].sum() + ds[1].sum())/20
ds['pop'] = ds[0] + ds[1]
# print(pop_cut)
while (ds.shape[0] > 2
and (ds['pop'].min() < pop_cut
or ds.chisq.min() <= scipy.stats.chi2.ppf(0.99, 1))) or ds[1].min() <= 0:
# calculate chisquare statistic
chisq = []
for i in range(ds.shape[0]-1):
chisq.append(cy.chi2_contingency(ds.iloc[[i,i+1]][[0,1]])[0])
chisq.append(9999999.0)
ds['chisq'] = chisq
# locate the smallest size by index
ds_idx_list = list(ds.index)
k = ds_idx_list.index(ds[ds['pop'] == ds['pop'].min()].index[0])
if k == len(ds_idx_list) - 1:
k -= 1
elif ds.ix[ds_idx_list[k], 'chisq'] > ds.ix[ds_idx_list[k-1], 'chisq']:
k -= 1
# merge the adjacent bins, drop the second bin
ds.ix[ds_idx_list[k], [var, 0, 1, 'pop']] = ds.ix[[ds_idx_list[k], ds_idx_list[k+1]], [var, 0, 1, 'pop']].sum()
ds.ix[ds_idx_list[k], 'dft_rto'] = 1.0 * ds.ix[ds_idx_list[k], 1] / (ds.ix[ds_idx_list[k], 0] + ds.ix[ds_idx_list[k], 1])
ds = ds.drop(ds_idx_list[k+1], axis=0)
ds = ds.reset_index(drop=True)
'''
#------- Calculate woe & IV -------#
'''
goodfreq = ds[0].sum()
badfreq = ds[1].sum()
ds[var+'_cwoe'] = ds.apply(lambda x: woe_calc(x[1], x[0], goodfreq, badfreq), axis=1)
# IVs
ds[var+'_IVs'] = ds.apply(lambda x: x[var+'_cwoe'] * (float(x[1])/badfreq - float(x[0])/goodfreq), axis=1)
IV = ds[var+'_IVs']
# Set stats of other's bin the same as that of the bin where least value locates
# For data has not appeared
vval_min = df[var].value_counts().argmin()
ds = pd.concat([ds, ds.loc[ds[var].apply(lambda v_lst: vval_min in v_lst)]], ignore_index=True)
ds.ix[ds.tail(1).index, var] = 'other'
# Set var column (1st) to the last (to be readable)
ds = ds.reindex_axis(list(ds.columns[1:])+[ds.columns[0]], axis=1)
'''
#------- get the reference table -------#
'''
def is_in_bin(v_lst, v_val, vval_na):
if 'other' == v_lst:
return False
if pd.isnull(v_val):
return vval_na in v_lst
else:
return v_val in v_lst
# ref_table = pd.DataFrame({'var_name': len(df[var].unique())})
uniq_val = df[var].unique()
ref_dict = {}
for v_val in uniq_val:
ref_dict[v_val] = ds.ix[ds[var].apply(lambda v_lst: is_in_bin(v_lst, v_val, vval_na)), var+'_cwoe'].values[0]
ref_dict['other'] = ds.ix[ds[var] == 'other', var+"_cwoe"].values[0]
ref_table = pd.DataFrame.from_dict(ref_dict, orient='index')
ref_table = ref_table.reset_index().rename(columns={'index': 'var_value', 0: 'woe'})
ref_table['var_name'] = var
ref_table = ref_table.reindex_axis(['var_name', 'var_value', 'woe'], axis=1)
return ref_table, IV, ds
def set_nominal_woe(df, ref_table):
for v in ref_table['var_name'].unique():
ref_tbl_v = ref_table.loc[ref_table['var_name'] == v]
try:
df[v]
except KeyError:
# log.info("No column \"{}\" found".format(v))
try:
print("No column \"{}\" found".format(v))
except UnicodeEncodeError:
print(u"No column \"{}\" found".format(v))
continue
df[v+'_cwoe'] = ref_tbl_v.ix[ref_tbl_v['var_value'] == 'other', 'woe'].values[0]
for vval in ref_tbl_v['var_value']:
if 'other' == vval:
continue
if pd.isnull(vval):
inds = pd.isnull(df[v])
df.ix[inds, v+'_cwoe'] = ref_tbl_v.ix[pd.isnull(ref_tbl_v['var_value']), 'woe'].values[0]
else:
try:
# It's float value
inds = df[v] == float(vval)
except (ValueError, UnicodeEncodeError):
# It's string
col_v = df[v].apply(lambda r: r.decode('utf8') if isinstance(r, str) else r if isinstance(r, unicode) else str(r).decode('utf8'))
inds = col_v == vval
df.ix[inds, v+'_cwoe'] = ref_tbl_v.ix[ref_tbl_v['var_value'] == vval, 'woe'].values[0]
# ## Update nominal woe needed
def calc_nominal_bin_stats_fr_reftable(df, ref_table, tgt):
# t0 = time.clock()
var = ref_table.ix[0, 'var_name']
tmp = pd.merge(df, ref_table[['woe', 'var_value']], how='left', left_on=var, right_on='var_value')
tmp.ix[tmp[var].isnull(), 'woe'] = ref_table.ix[ref_table['var_value'].isnull(), 'woe'].values
ds = tmp[['woe', tgt, var]].groupby(['woe', tgt]).agg(len).unstack().fillna(value=0)
# t1 = time.clock()
# print("{0}: {1}s elapsed".format(var, t1-t0))
ds.columns = ds.columns.droplevel(0)
ds.reset_index(inplace=True)
dft_rto = tmp[['woe', tgt]].groupby('woe').mean().rename(columns={tgt: 'dft_rto'}).reset_index()
ds = ds.merge(dft_rto, on='woe').sort_values('dft_rto').reset_index(drop=True)
ds['chisq'] = np.nan
ds['pop'] = ds[[0, 1]].sum(axis=1)
# Add values of variable
ds = ds.merge(pd.DataFrame(ref_table.groupby('woe')['var_value'].agg(lambda x: list(x))).rename(columns={0: var}), left_on='woe', right_index=True)
# Update and rename woe
goodfreq = ds[0].sum()
badfreq = ds[1].sum()
ds['woe'] = ds[[0, 1]].apply(lambda tgt: woe_calc(tgt[1], tgt[0], goodfreq, badfreq), axis=1)
ds.rename(columns={'woe': var+'_cwoe'}, inplace=True)
# IV
ds[var+'_IVs'] = ds.apply(lambda x: x[var+'_cwoe'] * (float(x[1])/badfreq - float(x[0])/goodfreq), axis=1)
# For data has not appeared
vval_min = df[var].value_counts().argmin()
ds = pd.concat([ds, ds.loc[ds[var].apply(lambda v_lst: vval_min in v_lst)]], ignore_index=True)
ds.ix[ds.tail(1).index, var] = 'other'
# Re-order columns
ds = ds.reindex_axis(list(ds.columns[1:6])+[var+'_cwoe', var+'_IVs', var], axis=1)
return ds
# def set_nominal_woe_by_dict(df, ref_dict):
# ref_table = pd.DataFrame()
# for k, v in ref_dict.iteritems():
# df_t = pd.DataFrame.from_dict({k: v}).reset_index().groupby('index')[k].apply(lambda x: pd.DataFrame(x.values[0])).reset_index(level=0).rename(columns={'index': 'woe', 0: 'var_value'})
# df_t['var_name'] = k
# ref_table = pd.concat([ref_table, df_t], axis=0)
# set_nominal_woe(df, ref_table)
# return ref_table
def calc_nominal_fr_dict_bin(df, ref_dict, tgt):
'''
var = 'studyLevel'
ref_dict = {'studyLevel': {0: [np.nan],
1: ["本科", "专升本", "博士", "硕士", "硕士研究生"],
2: ["专科(高职)", "专科(高职)", "专科"]}}
ref_table, IV, ds = dc.calc_nominal_fr_dict_bin(x_train, ref_dict, target)
dc.set_nominal_woe(x_train, ref_table)
dc.set_nominal_woe(x_test, ref_table)
dc.update_nominal_woe_info(ref_table, var, b_stat,
ref_table_cvar_f, b_stat_cvar_f, iv_cvar_f)
'''
k = ref_dict.keys()[0]
v = ref_dict.values()[0]
ref_table = pd.DataFrame.from_dict({k: v}).reset_index().groupby('index')[k].apply(lambda x: pd.DataFrame(x.values[0])).reset_index().drop(['level_1'], axis=1).rename(columns={'index': 'woe', 0: 'var_value'})
ref_table['var_name'] = k
t0 = datetime.now()
ds = calc_nominal_bin_stats_fr_reftable(df, ref_table, tgt)
print("{0}: {1}s elapsed".format(k, datetime.now()-t0))
IV = ds.ix[ds[k]!='other', k+'_IVs']
# ### Update reference table
def is_in_bin(v_lst, v_val, vval_na):
if 'other' == v_lst:
return False
if pd.isnull(v_val):
return vval_na in v_lst
else:
return v_val in v_lst
var = k
uniq_val = df[var].unique()
ref_dict2 = {}
for v_val in uniq_val:
ref_dict2[v_val] = ds.ix[ds[var].apply(lambda v_lst: is_in_bin(v_lst, v_val, vval_na=np.nan)), var+'_cwoe'].values[0]
ref_dict2['other'] = ds.ix[ds[var] == 'other', var+"_cwoe"].values[0]
ref_table = pd.DataFrame.from_dict(ref_dict2, orient='index')
ref_table = ref_table.reset_index().rename(columns={'index': 'var_value', 0: 'woe'})
ref_table['var_name'] = var
ref_table = ref_table.reindex_axis(['var_name', 'var_value', 'woe'], axis=1)
# set_nominal_woe(df, ref_table)
return ref_table, IV, ds
# Update WOE reference table
def update_nominal_woe_info(ref_table, var, b_stat,
ref_table_f, b_stat_f, df_iv_f):
# Update WOE reference table
nominal_ref_table = pd.read_csv(ref_table_f)
nominal_ref_table.drop(nominal_ref_table.loc[nominal_ref_table['var_name'] == var].index,
inplace=True)
nominal_ref_table = pd.concat((nominal_ref_table, ref_table), axis=0)
nominal_ref_table.to_csv(ref_table_f, index=False)
# Bin stats
with open(b_stat_f, 'aw') as bf:
# TODO
b_stat.to_csv(bf, sep='~', index=False, encoding='utf8')
bf.write('\n')
# IV
df_iv = pd.read_csv(df_iv_f, encoding='utf8')
df_iv.ix[df_iv['var'] == var, 'iv'] = b_stat.ix[b_stat[var]!='other', var+'_IVs'].sum()
df_iv.to_csv(df_iv_f, index=False)
def main_apply_ref_table(datain,ref_table,var):
datain['cwoe_' + var] = datain[var].apply(lambda x: cvlookup(ref_table,str(x)))
return datain
def main_apply_numeric_ref_table(datain,ref_table,var):
datain[var+'_nwoe'] = datain[var].apply(lambda x: nvlookup(ref_table,x))
return datain
class NumpyJSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.integer):
return int(obj)
elif isinstance(obj, np.floating):
return float(obj)
elif isinstance(obj, np.ndarray):
return obj.tolist()
else:
return super(NumpyJSONEncoder, self).default(obj)
''' ID number '''
def get_id_age(id_s, ref_date=None):
if ref_date is None:
ref_date = datetime.now()
age_birthdate = pd.to_datetime(id_s.apply(lambda i: str(i)[6:14]), errors='coerce')
age = pd.Series(len(age_birthdate)*[np.nan], index=age_birthdate.index)
age.loc[~pd.isnull(age_birthdate)] = age_birthdate.loc[~pd.isnull(age_birthdate)].apply(lambda bd: dateutil.relativedelta.relativedelta(ref_date, bd).years)
return age
def gender_fr_id(id_no):
try:
gender = int(id_no[-2]) % 2
if gender == 0:
gender = 2
except ValueError:
gender = 0
return gender
def get_id_gender(id_s):
return id_s.apply(gender_fr_id)
| [
"matplotlib.pyplot.hist",
"dateutil.relativedelta.relativedelta",
"pandas.read_csv",
"numpy.irr",
"matplotlib.pyplot.ylabel",
"sklearn.metrics.auc",
"numpy.log",
"numpy.argsort",
"numpy.array",
"sklearn.metrics.roc_curve",
"numpy.nanmin",
"numpy.arange",
"numpy.mean",
"pylab.find",
"nump... | [((848, 874), 'numpy.zeros', 'np.zeros', (['values1.shape[0]'], {}), '(values1.shape[0])\n', (856, 874), True, 'import numpy as np\n'), ((1235, 1260), 'numpy.zeros', 'np.zeros', (['values.shape[0]'], {}), '(values.shape[0])\n', (1243, 1260), True, 'import numpy as np\n'), ((1503, 1528), 'numpy.zeros', 'np.zeros', (['values.shape[0]'], {}), '(values.shape[0])\n', (1511, 1528), True, 'import numpy as np\n'), ((1542, 1566), 'numpy.ones', 'np.ones', (['values.shape[0]'], {}), '(values.shape[0])\n', (1549, 1566), True, 'import numpy as np\n'), ((1913, 1939), 'numpy.zeros', 'np.zeros', (['(l1 - 1, l2 - 1)'], {}), '((l1 - 1, l2 - 1))\n', (1921, 1939), True, 'import numpy as np\n'), ((1949, 1975), 'numpy.zeros', 'np.zeros', (['(l1 - 1, l2 - 1)'], {}), '((l1 - 1, l2 - 1))\n', (1957, 1975), True, 'import numpy as np\n'), ((1986, 2012), 'numpy.zeros', 'np.zeros', (['(l1 - 1, l2 - 1)'], {}), '((l1 - 1, l2 - 1))\n', (1994, 2012), True, 'import numpy as np\n'), ((2867, 2885), 'numpy.isnan', 'np.isnan', (['bins[-1]'], {}), '(bins[-1])\n', (2875, 2885), True, 'import numpy as np\n'), ((3592, 3605), 'numpy.zeros', 'np.zeros', (['bin'], {}), '(bin)\n', (3600, 3605), True, 'import numpy as np\n'), ((3617, 3630), 'numpy.zeros', 'np.zeros', (['bin'], {}), '(bin)\n', (3625, 3630), True, 'import numpy as np\n'), ((3644, 3657), 'numpy.zeros', 'np.zeros', (['bin'], {}), '(bin)\n', (3652, 3657), True, 'import numpy as np\n'), ((3672, 3685), 'numpy.zeros', 'np.zeros', (['bin'], {}), '(bin)\n', (3680, 3685), True, 'import numpy as np\n'), ((3695, 3708), 'numpy.zeros', 'np.zeros', (['bin'], {}), '(bin)\n', (3703, 3708), True, 'import numpy as np\n'), ((9330, 9350), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(1)', '(2)'], {}), '(2, 1, 2)\n', (9341, 9350), True, 'import matplotlib.pyplot as plt\n'), ((9790, 9801), 'numpy.zeros', 'np.zeros', (['l'], {}), '(l)\n', (9798, 9801), True, 'import numpy as np\n'), ((10024, 10041), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (10035, 10041), False, 'import random\n'), ((10351, 10372), 'numpy.zeros', 'np.zeros', (['df.shape[0]'], {}), '(df.shape[0])\n', (10359, 10372), True, 'import numpy as np\n'), ((10397, 10418), 'numpy.zeros', 'np.zeros', (['df.shape[0]'], {}), '(df.shape[0])\n', (10405, 10418), True, 'import numpy as np\n'), ((10443, 10464), 'numpy.zeros', 'np.zeros', (['df.shape[0]'], {}), '(df.shape[0])\n', (10451, 10464), True, 'import numpy as np\n'), ((10982, 11009), 'numpy.zeros', 'np.zeros', (['(row_num, length)'], {}), '((row_num, length))\n', (10990, 11009), True, 'import numpy as np\n'), ((11190, 11239), 'pandas.DataFrame', 'pd.DataFrame', (['data', 's.index'], {'columns': 'column_names'}), '(data, s.index, columns=column_names)\n', (11202, 11239), True, 'import pandas as pd\n'), ((12367, 12399), 'sklearn.metrics.roc_curve', 'roc_curve', (['all_target', 'predicted'], {}), '(all_target, predicted)\n', (12376, 12399), False, 'from sklearn.metrics import roc_curve, auc\n'), ((12414, 12427), 'sklearn.metrics.auc', 'auc', (['fpr', 'tpr'], {}), '(fpr, tpr)\n', (12417, 12427), False, 'from sklearn.metrics import roc_curve, auc\n'), ((12463, 12488), 'pylab.find', 'plb.find', (['(tpr - fpr == ks)'], {}), '(tpr - fpr == ks)\n', (12471, 12488), True, 'import pylab as plb\n'), ((13391, 13407), 'numpy.zeros', 'np.zeros', (['binnum'], {}), '(binnum)\n', (13399, 13407), True, 'import numpy as np\n'), ((13427, 13443), 'numpy.zeros', 'np.zeros', (['binnum'], {}), '(binnum)\n', (13435, 13443), True, 'import numpy as np\n'), ((13460, 13481), 'numpy.argsort', 'np.argsort', (['predicted'], {}), '(predicted)\n', (13470, 13481), True, 'import numpy as np\n'), ((15697, 15710), 'csv.reader', 'csv.reader', (['f'], {}), '(f)\n', (15707, 15710), False, 'import csv\n'), ((17244, 17260), 'pandas.isnull', 'pd.isnull', (['value'], {}), '(value)\n', (17253, 17260), True, 'import pandas as pd\n'), ((17330, 17341), 'numpy.empty', 'np.empty', (['(0)'], {}), '(0)\n', (17338, 17341), True, 'import numpy as np\n'), ((18239, 18253), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (18251, 18253), False, 'from datetime import datetime\n'), ((19525, 19547), 'numpy.isnan', 'np.isnan', (['uvbucket[-1]'], {}), '(uvbucket[-1])\n', (19533, 19547), True, 'import numpy as np\n'), ((20490, 20504), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (20502, 20504), False, 'from datetime import datetime\n'), ((22326, 22340), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (22338, 22340), False, 'from datetime import datetime\n'), ((23879, 23901), 'pandas.concat', 'pd.concat', (['[ds, ds_na]'], {}), '([ds, ds_na])\n', (23888, 23901), True, 'import pandas as pd\n'), ((24890, 24904), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (24902, 24904), False, 'from datetime import datetime\n'), ((25321, 25335), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (25333, 25335), False, 'from datetime import datetime\n'), ((25531, 25553), 'numpy.isnan', 'np.isnan', (['uvbucket[-1]'], {}), '(uvbucket[-1])\n', (25539, 25553), True, 'import numpy as np\n'), ((27420, 27444), 'pandas.read_csv', 'pd.read_csv', (['ref_table_f'], {}), '(ref_table_f)\n', (27431, 27444), True, 'import pandas as pd\n'), ((27750, 27809), 'pandas.concat', 'pd.concat', (['(df_numeric_ref_table, df_ref_table_tmp)'], {'axis': '(0)'}), '((df_numeric_ref_table, df_ref_table_tmp), axis=0)\n', (27759, 27809), True, 'import pandas as pd\n'), ((29095, 29132), 'pandas.read_csv', 'pd.read_csv', (['df_iv_f'], {'encoding': '"""utf8"""'}), "(df_iv_f, encoding='utf8')\n", (29106, 29132), True, 'import pandas as pd\n'), ((36439, 36487), 'pandas.DataFrame.from_dict', 'pd.DataFrame.from_dict', (['ref_dict'], {'orient': '"""index"""'}), "(ref_dict, orient='index')\n", (36461, 36487), True, 'import pandas as pd\n'), ((38253, 38349), 'pandas.merge', 'pd.merge', (['df', "ref_table[['woe', 'var_value']]"], {'how': '"""left"""', 'left_on': 'var', 'right_on': '"""var_value"""'}), "(df, ref_table[['woe', 'var_value']], how='left', left_on=var,\n right_on='var_value')\n", (38261, 38349), True, 'import pandas as pd\n'), ((41188, 41202), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (41200, 41202), False, 'from datetime import datetime\n'), ((41948, 41997), 'pandas.DataFrame.from_dict', 'pd.DataFrame.from_dict', (['ref_dict2'], {'orient': '"""index"""'}), "(ref_dict2, orient='index')\n", (41970, 41997), True, 'import pandas as pd\n'), ((42472, 42496), 'pandas.read_csv', 'pd.read_csv', (['ref_table_f'], {}), '(ref_table_f)\n', (42483, 42496), True, 'import pandas as pd\n'), ((42657, 42706), 'pandas.concat', 'pd.concat', (['(nominal_ref_table, ref_table)'], {'axis': '(0)'}), '((nominal_ref_table, ref_table), axis=0)\n', (42666, 42706), True, 'import pandas as pd\n'), ((42946, 42983), 'pandas.read_csv', 'pd.read_csv', (['df_iv_f'], {'encoding': '"""utf8"""'}), "(df_iv_f, encoding='utf8')\n", (42957, 42983), True, 'import pandas as pd\n'), ((743, 753), 'numpy.irr', 'np.irr', (['tt'], {}), '(tt)\n', (749, 753), True, 'import numpy as np\n'), ((1310, 1364), 'pylab.find', 'plb.find', (['((values >= bins[i]) & (values < bins[i + 1]))'], {}), '((values >= bins[i]) & (values < bins[i + 1]))\n', (1318, 1364), True, 'import pylab as plb\n'), ((3159, 3176), 'numpy.zeros', 'np.zeros', (['(bin + 1)'], {}), '(bin + 1)\n', (3167, 3176), True, 'import numpy as np\n'), ((3322, 3335), 'numpy.array', 'np.array', (['bin'], {}), '(bin)\n', (3330, 3335), True, 'import numpy as np\n'), ((3480, 3497), 'numpy.zeros', 'np.zeros', (['(bin + 1)'], {}), '(bin + 1)\n', (3488, 3497), True, 'import numpy as np\n'), ((3950, 3962), 'numpy.sum', 'np.sum', (['inds'], {}), '(inds)\n', (3956, 3962), True, 'import numpy as np\n'), ((3984, 3999), 'numpy.sum', 'np.sum', (['y[inds]'], {}), '(y[inds])\n', (3990, 3999), True, 'import numpy as np\n'), ((4143, 4158), 'numpy.log', 'np.log', (['(p1 / p2)'], {}), '(p1 / p2)\n', (4149, 4158), True, 'import numpy as np\n'), ((4220, 4236), 'numpy.mean', 'np.mean', (['x[inds]'], {}), '(x[inds])\n', (4227, 4236), True, 'import numpy as np\n'), ((4682, 4719), 'numpy.append', 'np.append', (['iv', '[(p1 - p2) * woes[-1]]'], {}), '(iv, [(p1 - p2) * woes[-1]])\n', (4691, 4719), True, 'import numpy as np\n'), ((4744, 4769), 'numpy.append', 'np.append', (['bins', '[np.nan]'], {}), '(bins, [np.nan])\n', (4753, 4769), True, 'import numpy as np\n'), ((4785, 4810), 'numpy.append', 'np.append', (['binx', '[np.nan]'], {}), '(binx, [np.nan])\n', (4794, 4810), True, 'import numpy as np\n'), ((5088, 5099), 'matplotlib.pyplot.twinx', 'plt.twinx', ([], {}), '()\n', (5097, 5099), True, 'import matplotlib.pyplot as plt\n'), ((9365, 9395), 'numpy.array', 'np.array', (['[x0, x1, x2, x3, x4]'], {}), '([x0, x1, x2, x3, x4])\n', (9373, 9395), True, 'import numpy as np\n'), ((11532, 11569), 'pandas.concat', 'pd.concat', (['[df, dummy_series]'], {'axis': '(1)'}), '([df, dummy_series], axis=1)\n', (11541, 11569), True, 'import pandas as pd\n'), ((13676, 13720), 'numpy.mean', 'np.mean', (['predicted[indices[startind:endind]]'], {}), '(predicted[indices[startind:endind]])\n', (13683, 13720), True, 'import numpy as np\n'), ((13745, 13790), 'numpy.mean', 'np.mean', (['all_target[indices[startind:endind]]'], {}), '(all_target[indices[startind:endind]])\n', (13752, 13790), True, 'import numpy as np\n'), ((13929, 13956), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(20, 6)'}), '(figsize=(20, 6))\n', (13939, 13956), True, 'import matplotlib.pyplot as plt\n'), ((13964, 13984), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(3)', '(1)'], {}), '(1, 3, 1)\n', (13975, 13984), True, 'import matplotlib.pyplot as plt\n'), ((13991, 14009), 'matplotlib.pyplot.plot', 'plt.plot', (['fpr', 'tpr'], {}), '(fpr, tpr)\n', (13999, 14009), True, 'import matplotlib.pyplot as plt\n'), ((14036, 14100), 'matplotlib.pyplot.plot', 'plt.plot', (['[0, 1]', '[0, 1]'], {'color': '"""k"""', 'linestyle': '"""--"""', 'linewidth': '(2)'}), "([0, 1], [0, 1], color='k', linestyle='--', linewidth=2)\n", (14044, 14100), True, 'import matplotlib.pyplot as plt\n'), ((14192, 14285), 'matplotlib.pyplot.plot', 'plt.plot', (['[fpr[maxind], fpr[maxind]]', '[fpr[maxind], tpr[maxind]]'], {'linewidth': '(4)', 'color': '"""r"""'}), "([fpr[maxind], fpr[maxind]], [fpr[maxind], tpr[maxind]], linewidth=\n 4, color='r')\n", (14200, 14285), True, 'import matplotlib.pyplot as plt\n'), ((14289, 14348), 'matplotlib.pyplot.plot', 'plt.plot', (['[fpr[minind]]', '[tpr[minind]]', '"""k."""'], {'markersize': '(10)'}), "([fpr[minind]], [tpr[minind]], 'k.', markersize=10)\n", (14297, 14348), True, 'import matplotlib.pyplot as plt\n'), ((14358, 14374), 'matplotlib.pyplot.xlim', 'plt.xlim', (['[0, 1]'], {}), '([0, 1])\n', (14366, 14374), True, 'import matplotlib.pyplot as plt\n'), ((14382, 14398), 'matplotlib.pyplot.ylim', 'plt.ylim', (['[0, 1]'], {}), '([0, 1])\n', (14390, 14398), True, 'import matplotlib.pyplot as plt\n'), ((14406, 14447), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""False positive"""'], {'fontsize': '(20)'}), "('False positive', fontsize=20)\n", (14416, 14447), True, 'import matplotlib.pyplot as plt\n'), ((14449, 14489), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""True positive"""'], {'fontsize': '(20)'}), "('True positive', fontsize=20)\n", (14459, 14489), True, 'import matplotlib.pyplot as plt\n'), ((14812, 14832), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(3)', '(2)'], {}), '(1, 3, 2)\n', (14823, 14832), True, 'import matplotlib.pyplot as plt\n'), ((14873, 14901), 'matplotlib.pyplot.hist', 'plt.hist', (['predicted'], {'bins': '(20)'}), '(predicted, bins=20)\n', (14881, 14901), True, 'import matplotlib.pyplot as plt\n'), ((15203, 15241), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Target rate"""'], {'fontsize': '(20)'}), "('Target rate', fontsize=20)\n", (15213, 15241), True, 'import matplotlib.pyplot as plt\n'), ((15250, 15282), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Count"""'], {'fontsize': '(20)'}), "('Count', fontsize=20)\n", (15260, 15282), True, 'import matplotlib.pyplot as plt\n'), ((15300, 15320), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(3)', '(3)'], {}), '(1, 3, 3)\n', (15311, 15320), True, 'import matplotlib.pyplot as plt\n'), ((15327, 15389), 'matplotlib.pyplot.plot', 'plt.plot', (['ave_predict', '"""b.-"""'], {'label': '"""Prediction"""', 'markersize': '(5)'}), "(ave_predict, 'b.-', label='Prediction', markersize=5)\n", (15335, 15389), True, 'import matplotlib.pyplot as plt\n'), ((15416, 15472), 'matplotlib.pyplot.plot', 'plt.plot', (['ave_target', '"""r.-"""'], {'label': '"""Truth"""', 'markersize': '(5)'}), "(ave_target, 'r.-', label='Truth', markersize=5)\n", (15424, 15472), True, 'import matplotlib.pyplot as plt\n'), ((15481, 15510), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""lower right"""'}), "(loc='lower right')\n", (15491, 15510), True, 'import matplotlib.pyplot as plt\n'), ((15519, 15556), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Percentile"""'], {'fontsize': '(20)'}), "('Percentile', fontsize=20)\n", (15529, 15556), True, 'import matplotlib.pyplot as plt\n'), ((15565, 15603), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Target rate"""'], {'fontsize': '(20)'}), "('Target rate', fontsize=20)\n", (15575, 15603), True, 'import matplotlib.pyplot as plt\n'), ((17141, 17170), 'pickle.dump', 'cPickle.dump', (['obj', 'output', '(-1)'], {}), '(obj, output, -1)\n', (17153, 17170), True, 'import pickle as cPickle\n'), ((19290, 19309), 'numpy.where', 'np.where', (['(b_bc == 0)'], {}), '(b_bc == 0)\n', (19298, 19309), True, 'import numpy as np\n'), ((19329, 19362), 'numpy.delete', 'np.delete', (['uvbucket', 'b_idx[0][1:]'], {}), '(uvbucket, b_idx[0][1:])\n', (19338, 19362), True, 'import numpy as np\n'), ((20708, 20722), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (20720, 20722), False, 'from datetime import datetime\n'), ((22114, 22128), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (22126, 22128), False, 'from datetime import datetime\n'), ((25470, 25497), 'numpy.append', 'np.append', (['uvbucket', 'np.nan'], {}), '(uvbucket, np.nan)\n', (25479, 25497), True, 'import numpy as np\n'), ((35978, 35994), 'pandas.isnull', 'pd.isnull', (['v_val'], {}), '(v_val)\n', (35987, 35994), True, 'import pandas as pd\n'), ((41513, 41529), 'pandas.isnull', 'pd.isnull', (['v_val'], {}), '(v_val)\n', (41522, 41529), True, 'import pandas as pd\n'), ((43908, 43922), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (43920, 43922), False, 'from datetime import datetime\n'), ((967, 1077), 'pylab.find', 'plb.find', (['((values1 >= bin1[i]) & (values1 < bin1[i + 1]) & (values2 >= bin2[j]) & (\n values2 < bin2[j + 1]))'], {}), '((values1 >= bin1[i]) & (values1 < bin1[i + 1]) & (values2 >= bin2[\n j]) & (values2 < bin2[j + 1]))\n', (975, 1077), True, 'import pylab as plb\n'), ((1646, 1668), 'pylab.find', 'plb.find', (['(inds == True)'], {}), '(inds == True)\n', (1654, 1668), True, 'import pylab as plb\n'), ((1754, 1775), 'pylab.find', 'plb.find', (['(others == 1)'], {}), '(others == 1)\n', (1762, 1775), True, 'import pylab as plb\n'), ((2084, 2173), 'pylab.find', 'plb.find', (['((x1 >= bin1[i]) & (x1 < bin1[i + 1]) & (x2 >= bin2[j]) & (x2 < bin2[j + 1]))'], {}), '((x1 >= bin1[i]) & (x1 < bin1[i + 1]) & (x2 >= bin2[j]) & (x2 <\n bin2[j + 1]))\n', (2092, 2173), True, 'import pylab as plb\n'), ((3423, 3435), 'numpy.unique', 'np.unique', (['x'], {}), '(x)\n', (3432, 3435), True, 'import numpy as np\n'), ((4276, 4288), 'pandas.isnull', 'pd.isnull', (['x'], {}), '(x)\n', (4285, 4288), True, 'import pandas as pd\n'), ((11766, 11798), 'numpy.minimum', 'np.minimum', (['(2.0 * temp)', 'df[name]'], {}), '(2.0 * temp, df[name])\n', (11776, 11798), True, 'import numpy as np\n'), ((11836, 11868), 'numpy.minimum', 'np.minimum', (['(0.5 * temp)', 'df[name]'], {}), '(0.5 * temp, df[name])\n', (11846, 11868), True, 'import numpy as np\n'), ((12066, 12098), 'numpy.maximum', 'np.maximum', (['(temp * 0.5)', 'df[name]'], {}), '(temp * 0.5, df[name])\n', (12076, 12098), True, 'import numpy as np\n'), ((12134, 12166), 'numpy.maximum', 'np.maximum', (['(temp * 2.0)', 'df[name]'], {}), '(temp * 2.0, df[name])\n', (12144, 12166), True, 'import numpy as np\n'), ((18568, 18585), 'numpy.nanmin', 'np.nanmin', (['uvalue'], {}), '(uvalue)\n', (18577, 18585), True, 'import numpy as np\n'), ((19135, 19152), 'numpy.nanmin', 'np.nanmin', (['uvalue'], {}), '(uvalue)\n', (19144, 19152), True, 'import numpy as np\n'), ((19235, 19272), 'numpy.digitize', 'np.digitize', (['df[var].values', 'uvbucket'], {}), '(df[var].values, uvbucket)\n', (19246, 19272), True, 'import numpy as np\n'), ((19463, 19490), 'numpy.append', 'np.append', (['uvbucket', 'np.nan'], {}), '(uvbucket, np.nan)\n', (19472, 19490), True, 'import numpy as np\n'), ((29938, 29954), 'pandas.isnull', 'pd.isnull', (['value'], {}), '(value)\n', (29947, 29954), True, 'import pandas as pd\n'), ((37393, 37408), 'pandas.isnull', 'pd.isnull', (['vval'], {}), '(vval)\n', (37402, 37408), True, 'import pandas as pd\n'), ((44105, 44129), 'pandas.isnull', 'pd.isnull', (['age_birthdate'], {}), '(age_birthdate)\n', (44114, 44129), True, 'import pandas as pd\n'), ((2230, 2246), 'numpy.mean', 'np.mean', (['y[inds]'], {}), '(y[inds])\n', (2237, 2246), True, 'import numpy as np\n'), ((2275, 2296), 'numpy.log', 'np.log', (['(p / (1.0 - p))'], {}), '(p / (1.0 - p))\n', (2281, 2296), True, 'import numpy as np\n'), ((4652, 4667), 'numpy.log', 'np.log', (['(p1 / p2)'], {}), '(p1 / p2)\n', (4658, 4667), True, 'import numpy as np\n'), ((9418, 9468), 'numpy.array', 'np.array', (['[drate1, drate2, drate3, drate4, drate5]'], {}), '([drate1, drate2, drate3, drate4, drate5])\n', (9426, 9468), True, 'import numpy as np\n'), ((14943, 14961), 'numpy.mean', 'np.mean', (['predicted'], {}), '(predicted)\n', (14950, 14961), True, 'import numpy as np\n'), ((15001, 15020), 'numpy.mean', 'np.mean', (['all_target'], {}), '(all_target)\n', (15008, 15020), True, 'import numpy as np\n'), ((20160, 20208), 'contingency.chi2_contingency', 'cy.chi2_contingency', (['ds.iloc[[i, i + 1]][[0, 1]]'], {}), '(ds.iloc[[i, i + 1]][[0, 1]])\n', (20179, 20208), True, 'import contingency as cy\n'), ((21763, 21820), 'contingency.chi2_contingency', 'cy.chi2_contingency', (['ds.ix[ds_idx_list[k - 1:k + 1], 0:2]'], {}), '(ds.ix[ds_idx_list[k - 1:k + 1], 0:2])\n', (21782, 21820), True, 'import contingency as cy\n'), ((21896, 21949), 'contingency.chi2_contingency', 'cy.chi2_contingency', (['ds.ix[ds_idx_list[k:k + 2], 0:2]'], {}), '(ds.ix[ds_idx_list[k:k + 2], 0:2])\n', (21915, 21949), True, 'import contingency as cy\n'), ((26167, 26215), 'contingency.chi2_contingency', 'cy.chi2_contingency', (['ds.iloc[[i, i + 1]][[0, 1]]'], {}), '(ds.iloc[[i, i + 1]][[0, 1]])\n', (26186, 26215), True, 'import contingency as cy\n'), ((32447, 32495), 'contingency.chi2_contingency', 'cy.chi2_contingency', (['ds.iloc[[i, i + 1]][[0, 1]]'], {}), '(ds.iloc[[i, i + 1]][[0, 1]])\n', (32466, 32495), True, 'import contingency as cy\n'), ((33477, 33539), 'contingency.chi2_contingency', 'cy.chi2_contingency', (['ds.iloc[ds_idx_list[k - 1:k + 1]][[0, 1]]'], {}), '(ds.iloc[ds_idx_list[k - 1:k + 1]][[0, 1]])\n', (33496, 33539), True, 'import contingency as cy\n'), ((33617, 33675), 'contingency.chi2_contingency', 'cy.chi2_contingency', (['ds.iloc[ds_idx_list[k:k + 2]][[0, 1]]'], {}), '(ds.iloc[ds_idx_list[k:k + 2]][[0, 1]])\n', (33636, 33675), True, 'import contingency as cy\n'), ((37433, 37449), 'pandas.isnull', 'pd.isnull', (['df[v]'], {}), '(df[v])\n', (37442, 37449), True, 'import pandas as pd\n'), ((41307, 41321), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (41319, 41321), False, 'from datetime import datetime\n'), ((44195, 44245), 'dateutil.relativedelta.relativedelta', 'dateutil.relativedelta.relativedelta', (['ref_date', 'bd'], {}), '(ref_date, bd)\n', (44231, 44245), False, 'import dateutil\n'), ((2377, 2392), 'numpy.sum', 'np.sum', (['y[inds]'], {}), '(y[inds])\n', (2383, 2392), True, 'import numpy as np\n'), ((3373, 3385), 'numpy.unique', 'np.unique', (['x'], {}), '(x)\n', (3382, 3385), True, 'import numpy as np\n'), ((4360, 4372), 'pandas.isnull', 'pd.isnull', (['x'], {}), '(x)\n', (4369, 4372), True, 'import pandas as pd\n'), ((16904, 16938), 'pandas.DataFrame', 'pd.DataFrame', (['rows'], {'columns': 'header'}), '(rows, columns=header)\n', (16916, 16938), True, 'import pandas as pd\n'), ((16993, 17027), 'pandas.DataFrame', 'pd.DataFrame', (['rows'], {'columns': 'header'}), '(rows, columns=header)\n', (17005, 17027), True, 'import pandas as pd\n'), ((31453, 31476), 'pandas.DataFrame', 'pd.DataFrame', (['small_sum'], {}), '(small_sum)\n', (31465, 31476), True, 'import pandas as pd\n'), ((34194, 34242), 'contingency.chi2_contingency', 'cy.chi2_contingency', (['ds.iloc[[i, i + 1]][[0, 1]]'], {}), '(ds.iloc[[i, i + 1]][[0, 1]])\n', (34213, 34242), True, 'import contingency as cy\n'), ((44152, 44176), 'pandas.isnull', 'pd.isnull', (['age_birthdate'], {}), '(age_birthdate)\n', (44161, 44176), True, 'import pandas as pd\n'), ((15158, 15176), 'numpy.mean', 'np.mean', (['predicted'], {}), '(predicted)\n', (15165, 15176), True, 'import numpy as np\n'), ((18504, 18519), 'numpy.diff', 'np.diff', (['uvalue'], {}), '(uvalue)\n', (18511, 18519), True, 'import numpy as np\n'), ((19071, 19086), 'numpy.diff', 'np.diff', (['uvalue'], {}), '(uvalue)\n', (19078, 19086), True, 'import numpy as np\n'), ((18928, 18951), 'numpy.arange', 'np.arange', (['(max_bins + 1)'], {}), '(max_bins + 1)\n', (18937, 18951), True, 'import numpy as np\n'), ((4475, 4487), 'pandas.isnull', 'pd.isnull', (['x'], {}), '(x)\n', (4484, 4487), True, 'import pandas as pd\n'), ((15115, 15134), 'numpy.mean', 'np.mean', (['all_target'], {}), '(all_target)\n', (15122, 15134), True, 'import numpy as np\n'), ((37504, 37537), 'pandas.isnull', 'pd.isnull', (["ref_tbl_v['var_value']"], {}), "(ref_tbl_v['var_value'])\n", (37513, 37537), True, 'import pandas as pd\n'), ((41028, 41053), 'pandas.DataFrame', 'pd.DataFrame', (['x.values[0]'], {}), '(x.values[0])\n', (41040, 41053), True, 'import pandas as pd\n'), ((40947, 40977), 'pandas.DataFrame.from_dict', 'pd.DataFrame.from_dict', (['{k: v}'], {}), '({k: v})\n', (40969, 40977), True, 'import pandas as pd\n')] |
import numpy as np
import math
from tf_convex_quad_iou import iou_matrix
sqrt2 = math.sqrt(2)
anchors = np.array([
[
[-1, -1],
[1, -1],
[1, 1],
[-1, 1],
],
[
[0, 0],
[2, 0],
[2, 2],
[0, 2],
],
[
[0, sqrt2],
[-sqrt2, 0],
[0, -sqrt2],
[sqrt2, 0],
],
[
[-1, 1],
[0, 0],
[1, 0],
[2, 1],
],
[
[1, 1],
[2, 1],
[2, 2],
[1, 2],
],
],
dtype=np.float32)
quads = np.array([
[
[-1, -1],
[1, -1],
[1, 1],
[-1, 1],
],
[
[100, 200],
[101, 200],
[101, 201],
[100, 201],
],
],
dtype=np.float32)
expected = np.array([
[1.0, 0.0],
[1 / 7, 0.0],
[(1 - (sqrt2 - 1)**2) / (1 + (sqrt2 - 1)**2), 0.0],
[(2 - 1 / 2) / (4 + 1 / 2), 0.0],
[0.0, 0.0],
])
def test_iou_matrix():
np.testing.assert_almost_equal(
iou_matrix(anchors=anchors, quads=quads).numpy(),
expected,
)
| [
"numpy.array",
"tf_convex_quad_iou.iou_matrix",
"math.sqrt"
] | [((82, 94), 'math.sqrt', 'math.sqrt', (['(2)'], {}), '(2)\n', (91, 94), False, 'import math\n'), ((106, 336), 'numpy.array', 'np.array', (['[[[-1, -1], [1, -1], [1, 1], [-1, 1]], [[0, 0], [2, 0], [2, 2], [0, 2]], [[\n 0, sqrt2], [-sqrt2, 0], [0, -sqrt2], [sqrt2, 0]], [[-1, 1], [0, 0], [1,\n 0], [2, 1]], [[1, 1], [2, 1], [2, 2], [1, 2]]]'], {'dtype': 'np.float32'}), '([[[-1, -1], [1, -1], [1, 1], [-1, 1]], [[0, 0], [2, 0], [2, 2], [0,\n 2]], [[0, sqrt2], [-sqrt2, 0], [0, -sqrt2], [sqrt2, 0]], [[-1, 1], [0, \n 0], [1, 0], [2, 1]], [[1, 1], [2, 1], [2, 2], [1, 2]]], dtype=np.float32)\n', (114, 336), True, 'import numpy as np\n'), ((574, 695), 'numpy.array', 'np.array', (['[[[-1, -1], [1, -1], [1, 1], [-1, 1]], [[100, 200], [101, 200], [101, 201],\n [100, 201]]]'], {'dtype': 'np.float32'}), '([[[-1, -1], [1, -1], [1, 1], [-1, 1]], [[100, 200], [101, 200], [\n 101, 201], [100, 201]]], dtype=np.float32)\n', (582, 695), True, 'import numpy as np\n'), ((809, 951), 'numpy.array', 'np.array', (['[[1.0, 0.0], [1 / 7, 0.0], [(1 - (sqrt2 - 1) ** 2) / (1 + (sqrt2 - 1) ** 2),\n 0.0], [(2 - 1 / 2) / (4 + 1 / 2), 0.0], [0.0, 0.0]]'], {}), '([[1.0, 0.0], [1 / 7, 0.0], [(1 - (sqrt2 - 1) ** 2) / (1 + (sqrt2 -\n 1) ** 2), 0.0], [(2 - 1 / 2) / (4 + 1 / 2), 0.0], [0.0, 0.0]])\n', (817, 951), True, 'import numpy as np\n'), ((1036, 1076), 'tf_convex_quad_iou.iou_matrix', 'iou_matrix', ([], {'anchors': 'anchors', 'quads': 'quads'}), '(anchors=anchors, quads=quads)\n', (1046, 1076), False, 'from tf_convex_quad_iou import iou_matrix\n')] |
#------------------------------------------------------------------------------
# Create side by side trajectories on video frame and sat image
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
# Settings and globals
import numpy as np
import pandas as pd
import copy as cp
from modules.utils import *
from modules.draw import *
from modules.homography import PixelMapper
# Load data
df = pd.read_csv('../output/2-sample-2020.csv')
# Load conflict frame
img_f = cv2.imread('../output/2-sample-2020-cnflct_frame.png')
# Load satellite image
img_s = cv2.imread('../data/2-sat.jpg')
#------------------------------------------------------------------------------
# Create conflict frame
# # video_file_name = '../data/2-sample-2020.mp4'
# video_file_name = os.path.join(RAW_DATA_PATH, filename + '.mp4')
# # Load video
# cap = cv2.VideoCapture(video_file_name)
# # Grab post conflict frame
# cap.set(cv2.CAP_PROP_POS_FRAMES, 143-1)
# _, img_c = cap.read()
#------------------------------------------------------------------------------
# Process data
#------------------------------------------------------------------------------
# Process data
# Replace Coco class ids with str labels
class_dict = {0: 'Person',
1: 'Bicycle',
2: 'Car',
3: 'Motorbyke',
5: 'Bus',
7: 'Truck'}
df['class'] = df['class'].map(class_dict)
# Set colors
# COLORS = np.random.uniform(0, 255, size=(len(class_dict), 3))
# class_dict.keys()
# Create centroids
df['cx'] = round(df['xi'] + (df['xj'] - df['xi'])/2).astype(int)
df['cy'] = round(df['yi'] + (df['yj'] - df['yi'])/2).astype(int)
#------------------------------------------------------------------------------
# Coordinates mapping
# Create one instance of PixelMapper to convert video frames to coordinates
quad_coords = {
# Check these!
"lonlat": np.array([
[9.020958, 38.511327], # top right
[9.020882, 38.511203], # top left
[9.020798, 38.511146], # bottom left
[9.020819, 38.511240] # bottom right
]),
"pixel": np.array([
[225, 40], # top right
[88, 78], # top left
[382, 327], # bottom left
[386, 108] # bottom right
]),
"pixel_sat": np.array([
[274, 79], # top right
[146, 138], # top left
[91, 201], # bottom left
[170, 179] # bottom right
])
}
# Create pixel maper instance to convert from video to lat long (and vice versa)
pm = PixelMapper(quad_coords["pixel"], quad_coords["lonlat"])
# Create pixel maper instance to convert from sat image to lat long (and vice versa)
pm_sat = PixelMapper(quad_coords["pixel_sat"], quad_coords["lonlat"])
#------------------------------------------------------------------------------
# Test a trajectory on video frame and sat image and longlat
# REWRITE THIS!
def draw_trajectory(img, trajectory_array, color):
img_cp = cp.deepcopy(img)
for p in range(1, len(trajectory_array)):
cv2.line(img_cp, tuple(trajectory_array[p-1]), tuple(trajectory_array[p]), color, 2)
return img_cp
# Create trajectory df
car_df = df[df['obj_id'] == 21]
per_df = df[df['obj_id'] == 22]
t_car = car_df[['cx', 'cy']].to_numpy()
t_per = per_df[['cx', 'cy']].to_numpy()
# Anotate trajectory on initial video frame
img_cf = img_f.copy()
img_cf = draw_trajectory(img_cf, t_car, (0, 0, 255))
img_cf = draw_trajectory(img_cf, t_per, (0, 255, 255))
ishow(img_cf)
# Transform trajectories to long lat
t_car_ll = pm.pixel_to_lonlat(t_car) # t_car created in draft-intersections.py
t_per_ll = pm.pixel_to_lonlat(t_per) # t_car created in draft-intersections.py
# Transform lat long trajectory into pixels of sat image
t_car_s = pm_sat.lonlat_to_pixel(t_car_ll).astype(int)
t_per_s = pm_sat.lonlat_to_pixel(t_per_ll).astype(int)
# Anotate trajectory on sat image
img_cs = img_s.copy()
img_cs = draw_trajectory(img_cs, t_car_s, (0, 0, 255))
img_cs = draw_trajectory(img_cs, t_per_s, (0, 255, 255))
# t_per_s
ishow(img_cs)
res = hstack_images(img_cf, img_cs)
ishow(res)
# Export
cv2.imwrite('../output/2-sample-2020-cnflct_frame_and_sat.png', res)
#----------------------
# Draf test homography
# Function to compare points on both images
# def show_hom_points(img, img_sat points_vdframe, points_sat ):
# """
# img and img_sat : numpy.ndarray of pixels
# points_vdframe and points_sat : two dictionaries with the structure below:5
# - points should go anti-clock-wise
# {
# "lonlat": np.array([
# [x1, y1], # top right
# [x2, y2], # top left
# [x3, y3], # bottom left
# [x4, y4] # bottom right]),
# "pixel": np.array([
# [x1, y1], # top right
# [x2, y2], # top left
# [x3, y3], # bottom left
# [x4, y4] # bottom right
# ])}
# """
# return 0
def draw_point(img, point, color, label = None):
img_cp = cp.deepcopy(img)
pcoords = tuple(point)
cv2.circle(img_cp, pcoords, 3, color, -1)
if label is not None:
tcoords = tuple(point + 5)
cv2.putText(img_cp, label, tcoords, cv2.FONT_HERSHEY_SIMPLEX, .5, color, 1, cv2.LINE_AA)
# ishow(img_cp)
return img_cp
def draw_hom_points(img, points_array):
img_cp = cp.deepcopy(img)
# Loop over points
i = 0
for p in points_array:
i += 1
label = 'p' + str(i)
img_cp = draw_point(img_cp, p, (0, 0, 255), label)
return img_cp
img_s_points = draw_hom_points(img_s, quad_coords['pixel_sat'])
img_f_points = draw_hom_points(img_f, quad_coords['pixel'])
vis = hstack_images(img_f_points, img_s_points)
# pm_sat = PixelMapper(quad_coords_sat["pixel"], quad_coords_sat["lonlat"])
# Create anothe pixel mapper instance to convert from lonlat to sat image
pm_sat = PixelMapper(quad_coords["pixel_sat"], quad_coords["lonlat"]) | [
"numpy.array",
"copy.deepcopy",
"pandas.read_csv",
"modules.homography.PixelMapper"
] | [((505, 547), 'pandas.read_csv', 'pd.read_csv', (['"""../output/2-sample-2020.csv"""'], {}), "('../output/2-sample-2020.csv')\n", (516, 547), True, 'import pandas as pd\n'), ((2616, 2672), 'modules.homography.PixelMapper', 'PixelMapper', (["quad_coords['pixel']", "quad_coords['lonlat']"], {}), "(quad_coords['pixel'], quad_coords['lonlat'])\n", (2627, 2672), False, 'from modules.homography import PixelMapper\n'), ((2768, 2828), 'modules.homography.PixelMapper', 'PixelMapper', (["quad_coords['pixel_sat']", "quad_coords['lonlat']"], {}), "(quad_coords['pixel_sat'], quad_coords['lonlat'])\n", (2779, 2828), False, 'from modules.homography import PixelMapper\n'), ((5924, 5984), 'modules.homography.PixelMapper', 'PixelMapper', (["quad_coords['pixel_sat']", "quad_coords['lonlat']"], {}), "(quad_coords['pixel_sat'], quad_coords['lonlat'])\n", (5935, 5984), False, 'from modules.homography import PixelMapper\n'), ((2002, 2108), 'numpy.array', 'np.array', (['[[9.020958, 38.511327], [9.020882, 38.511203], [9.020798, 38.511146], [\n 9.020819, 38.51124]]'], {}), '([[9.020958, 38.511327], [9.020882, 38.511203], [9.020798, \n 38.511146], [9.020819, 38.51124]])\n', (2010, 2108), True, 'import numpy as np\n'), ((2212, 2267), 'numpy.array', 'np.array', (['[[225, 40], [88, 78], [382, 327], [386, 108]]'], {}), '([[225, 40], [88, 78], [382, 327], [386, 108]])\n', (2220, 2267), True, 'import numpy as np\n'), ((2378, 2434), 'numpy.array', 'np.array', (['[[274, 79], [146, 138], [91, 201], [170, 179]]'], {}), '([[274, 79], [146, 138], [91, 201], [170, 179]])\n', (2386, 2434), True, 'import numpy as np\n'), ((3053, 3069), 'copy.deepcopy', 'cp.deepcopy', (['img'], {}), '(img)\n', (3064, 3069), True, 'import copy as cp\n'), ((5049, 5065), 'copy.deepcopy', 'cp.deepcopy', (['img'], {}), '(img)\n', (5060, 5065), True, 'import copy as cp\n'), ((5390, 5406), 'copy.deepcopy', 'cp.deepcopy', (['img'], {}), '(img)\n', (5401, 5406), True, 'import copy as cp\n')] |
import numpy as np
def compute_quantity (plan, stype):
if stype == 'stack':
return compute_quantity_stack (plan['packages']['children'])
elif stype == 'shelf':
return compute_quantity_shelf (plan['packages']['children'])
else:
return compute_quantity_apr (plan['packages']['children'])
def compute_quantity_stack (packages):
counter = 0
for row in packages:
for stack in row['children']:
if 'children' in stack :
for unit in stack['children']:
counter += (len(unit['children']))
return counter
def compute_quantity_apr (packages):
counter = 0
for row in packages:
for stack in row['children']:
if 'children' in stack :
for unit in stack['children']:
counter += (len(unit['children']))
return counter
def compute_quantity_shelf (packages):
counter = 0
for row in packages:
for stack in row['children']:
if 'children' in stack :
counter += (len(stack['children']))
return counter
def compute_rackspec (plan, stype):
rackspec = {}
if stype == 'stack':
return {}
uprights = plan['skeleton']['upright']
beams = plan['skeleton']['beam']
unit= uprights[0]
beam = beams[0]
rackspec['bay_depth'] = max( unit[1][1][0] - unit[0][0][0], unit[1][1][1] - unit[0][0][1])
rackspec['upright_counts'] = len( uprights )
rackspec['upright_width'] = min( unit[1][1][0] - unit[0][0][0], unit[1][1][1] - unit[0][0][1])
return rackspec
def compute_polygon_area ( polygon, type = ""):
pts = polygon
x = []
y = []
for id in range(len(pts)):
x.append(pts[id][0])
y.append(pts[id][1])
size = 0.5*np.abs(np.dot(x,np.roll(y,1))-np.dot(y,np.roll(x,1)))
return size
| [
"numpy.roll"
] | [((1847, 1860), 'numpy.roll', 'np.roll', (['y', '(1)'], {}), '(y, 1)\n', (1854, 1860), True, 'import numpy as np\n'), ((1870, 1883), 'numpy.roll', 'np.roll', (['x', '(1)'], {}), '(x, 1)\n', (1877, 1883), True, 'import numpy as np\n')] |
import time
import math
import tempfile
import operator
import os
import json
from typing import Union, List, Tuple
import unittest
import h5py
import numpy as np
from PythonExtras import numpy_extras as npe
from PythonExtras import patching_tools
from PythonExtras import volume_tools
from PythonExtras.CppWrapper import CppWrapper
from PythonExtras.BufferedNdArray import BufferedNdArray
# ---------------------------------------------------------
# Reference Python implementations of the methods reimplemented in C++.
def reference_extract_patches(data: Union[np.ndarray, h5py.Dataset], sourceAxes: Tuple, patchSize: Tuple,
patchStride: Tuple = None, verbose=False):
# By default, extract every patch.
if patchStride is None:
patchStride = (1,) * len(sourceAxes)
result = None
patchCenters = [] # Store geometrical center of each path. (Can be useful for the caller.)
patchNumber = reference_compute_patch_number(data.shape, sourceAxes, patchSize, patchStride)
patchNumberFlat = np.prod(np.asarray(patchNumber)) # type: int
i = 0
for patch, patchCenter, patchIndex in reference_extract_patches_gen(data, sourceAxes, patchSize, patchStride,
verbose):
if result is None:
resultShape = (patchNumberFlat,) + patch.shape
result = np.empty(resultShape, dtype=patch.dtype)
result[i, ...] = patch
patchCenters.append(patchCenter)
i += 1
return result, patchCenters, patchNumber
def reference_compute_patch_number(dataShape: Tuple, sourceAxes: Tuple, patchSize: Tuple,
patchStride: Tuple = None):
patchNumber = []
for i in sourceAxes:
totalPatchNumber = dataShape[i] - patchSize[sourceAxes.index(i)] + 1
stride = patchStride[sourceAxes.index(i)]
patchNumber.append(int(math.ceil(totalPatchNumber / stride)))
return patchNumber
def reference_extract_patches_gen(data: Union[np.ndarray, h5py.Dataset], sourceAxes: Tuple, patchSize: Tuple,
patchStride: Tuple = None, verbose=False):
# By default, extract every patch.
if patchStride is None:
patchStride = (1,) * len(sourceAxes)
patchNumber = reference_compute_patch_number(data.shape, sourceAxes, patchSize, patchStride)
patchNumberFlat = np.prod(np.asarray(patchNumber))
lastPrintTime = time.time()
# Since the number of traversed dimension is dynamically specified, we cannot use 'for' loops.
# Instead, iterate a flat index and unflatten it inside the loop. (Easier than recursion.)
for indexFlat in range(patchNumberFlat):
patchIndexNd = npe.unflatten_index(patchNumber, indexFlat)
# Since we skip some of the patches, scale the index accordingly.
dataIndexNd = tuple(np.asarray(patchIndexNd, dtype=np.int) * np.asarray(patchStride, dtype=np.int))
dataSelector = tuple()
patchCenter = tuple()
for axis in range(data.ndim):
if axis not in sourceAxes:
dataSelector += (slice(None),) # Take everything, if it's not a source axis.
else:
patchAxis = sourceAxes.index(axis)
# Take a slice along the axis.
dataSelector += (slice(dataIndexNd[patchAxis], dataIndexNd[patchAxis] + patchSize[patchAxis]),)
patchCenter += (dataIndexNd[patchAxis] + int(patchSize[patchAxis] / 2),)
yield (data[dataSelector], patchCenter, patchIndexNd)
if verbose and time.time() - lastPrintTime > 20:
lastPrintTime = time.time()
print("Extracting patches: {:02.2f}%".format(indexFlat / patchNumberFlat * 100))
def reference_extract_patched_all_data_without_empty_4d(data: np.ndarray,
patchSize: Tuple, patchStride: Tuple, emptyValue: int):
patchedData, patchCenters, *r = reference_extract_patches(data, (0, 1, 2, 3), patchSize, patchStride)
allDataX = patchedData[:, :-1, ...]
# The center of the last frame is the prediction target.
allDataY = patchedData[:, -1, patchSize[1] // 2, patchSize[2] // 2, patchSize[3] // 2]
nonemptyPatchMaskY = np.not_equal(allDataY, emptyValue)
nonemptyPatchMaskX = np.any(np.not_equal(allDataX, emptyValue), axis=tuple(range(1, allDataX.ndim)))
nonemptyPatchMask = np.logical_or(nonemptyPatchMaskX, nonemptyPatchMaskY)
allDataX = allDataX[nonemptyPatchMask]
allDataY = allDataY[nonemptyPatchMask, np.newaxis]
patchCenters = np.asarray(patchCenters, dtype=np.uint64)[nonemptyPatchMask]
patchIndices = patchCenters[:, :] - np.asarray(patchSize) // 2
return allDataX, allDataY, patchIndices
class NumpyExtrasTest(unittest.TestCase):
def test_slice_shape(self):
self.assertEqual(npe.slice_shape((10, 10), (slice(0, 5), slice(2, 5))), (5, 3))
self.assertEqual(npe.slice_shape((2, 10), (slice(0, 5), slice(2, 5))), (2, 3))
self.assertEqual(npe.slice_shape((2, 10), (slice(0, 5), slice(None))), (2, 10))
self.assertEqual(npe.slice_shape((10, 10), (slice(None), slice(None))), (10, 10))
self.assertEqual(npe.slice_shape((10, 10), (slice(0, 5, 2), slice(2, 5, 2))), (3, 2))
self.assertEqual(npe.slice_shape((10, 10), (slice(0, 5, 20), slice(2, 5, 1))), (1, 3))
self.assertEqual(npe.slice_shape((10, 10), (slice(20, 5), slice(2, 5, 1))), (0, 3))
def test_flatten_index_simple(self):
self.assertEqual(npe.flatten_index((1, 2, 3), (3, 4, 5)),
1 * 4 * 5 + 2 * 5 + 3)
def test_extract_patches_simple(self):
size = (3, 6, 5, 4)
volume = np.random.uniform(0, 255, size).astype(np.uint8)
patchSize = (2, 5, 3, 4)
patchStride = (1, 4, 2, 2)
patches, c, patchNumber = patching_tools.extract_patches(volume, (0, 1, 2, 3), patchSize, patchStride)
patchIndexNd = (1, 0, 1, 0)
patchIndex = npe.flatten_index(patchIndexNd, patchNumber)
correctPatch = volume[1:3, 0:5, 2:5, 0:4]
actualPatch = patches[patchIndex, ...]
self.assertTrue(np.equal(correctPatch, actualPatch).all())
def test_c_wrapper_test(self):
input = np.arange(0, 16).reshape((4, 4)) # type: np.ndarray
expectedOutput = input * 2
CppWrapper.test(input)
self.assertTrue(np.equal(input, expectedOutput).all())
def test_resize_array_point(self):
input = np.asarray([[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10, 11, 12],
[13, 14, 15],
[16, 17, 18]], dtype=np.float)
targetSize = (3, 2)
expectedOutput = np.asarray([[1, 3],
[10, 12],
[16, 18]], dtype=np.float)
actualOutput = volume_tools.resize_array_point(input, targetSize)
self.assertTrue(np.all(np.equal(expectedOutput, actualOutput)),
msg='\n {} \n <- expected, got -> \n {}'.format(expectedOutput, actualOutput))
actualOutput = volume_tools.resize_array_point(input.astype(np.uint8), targetSize)
self.assertTrue(np.all(np.equal(expectedOutput.astype(np.uint8), actualOutput)),
msg='\n {} \n <- expected, got -> \n {}'.format(expectedOutput, actualOutput))
def test_extract_patches(self):
# It's kind of stupid – testing against a reference implementation,
# but manually generating large test cases is fairly annoying.
# Also, we are testing the C++ implementation against the trusted Python code.
data = np.arange(0, 5 * 7 * 9, dtype=np.uint8).reshape((5, 7, 9))
patchesCorrect, centersCorrect, *r = reference_extract_patches(data, (0, 2), (2, 5), (1, 2))
patchesCpp, centersCpp, *r = patching_tools.extract_patches(data, (0, 2), (2, 5), (1, 2))
self.assertEqual(patchesCorrect.shape, patchesCpp.shape)
self.assertTrue(np.all(np.equal(patchesCorrect, patchesCpp)))
self.assertTrue(np.all(np.equal(centersCorrect, centersCpp)))
patchesCorrect, centersCorrect, *r = reference_extract_patches(data, (0, 1, 2), (1, 1, 1), (1, 1, 1))
patchesCpp, centersCpp, *r = patching_tools.extract_patches(data, (0, 1, 2), (1, 1, 1), (1, 1, 1))
self.assertEqual(patchesCorrect.shape, patchesCpp.shape)
self.assertTrue(np.all(np.equal(patchesCorrect, patchesCpp)))
self.assertTrue(np.all(np.equal(centersCorrect, centersCpp)))
patchesCorrect, centersCorrect, *r = reference_extract_patches(data, (1, 2), (1, 3), (5, 1))
patchesCpp, centersCpp, *r = patching_tools.extract_patches(data, (1, 2), (1, 3), (5, 1))
self.assertEqual(patchesCorrect.shape, patchesCpp.shape)
self.assertTrue(np.all(np.equal(patchesCorrect, patchesCpp)))
self.assertTrue(np.all(np.equal(centersCorrect, centersCpp)))
# --------------
data = np.arange(0, 2 * 3 * 4 * 5 * 6, dtype=np.uint8).reshape((2, 3, 4, 5, 6))
patchesCorrect, centersCorrect, *r = reference_extract_patches(data, (2, 4), (2, 2), (1, 3))
patchesCpp, centersCpp, *r = patching_tools.extract_patches(data, (2, 4), (2, 2), (1, 3))
self.assertEqual(patchesCorrect.shape, patchesCpp.shape)
self.assertTrue(np.all(np.equal(patchesCorrect, patchesCpp)))
self.assertTrue(np.all(np.equal(centersCorrect, centersCpp)))
# --------------
data = np.arange(0, 20, dtype=np.uint8).reshape((5, 4))
patchesCpp, *r = patching_tools.extract_patches(data, (0, 1), (2, 3), (2, 1))
manualResult = np.asarray([
[[0, 1, 2],
[4, 5, 6]],
[[1, 2, 3],
[5, 6, 7]],
[[8, 9, 10],
[12, 13, 14]],
[[9, 10, 11],
[13, 14, 15]],
], dtype=np.uint8)
self.assertEqual(manualResult.shape, patchesCpp.shape)
self.assertTrue(np.all(np.equal(manualResult, patchesCpp)))
# --------------
data = np.arange(0, 3 * 4 * 5, dtype=np.uint8).reshape((3, 4, 5))
patchesCpp, *r = patching_tools.extract_patches(data, (0, 2), (2, 2), (1, 3))
manualResult = np.asarray([
[
[[0, 1], [5, 6], [10, 11], [15, 16]],
[[20, 21], [25, 26], [30, 31], [35, 36]]
],
[
[[3, 4], [8, 9], [13, 14], [18, 19]],
[[23, 24], [28, 29], [33, 34], [38, 39]]
],
[
[[20, 21], [25, 26], [30, 31], [35, 36]],
[[40, 41], [45, 46], [50, 51], [55, 56]],
],
[
[[23, 24], [28, 29], [33, 34], [38, 39]],
[[43, 44], [48, 49], [53, 54], [58, 59]]
],
], dtype=np.uint8)
self.assertEqual(manualResult.shape, patchesCpp.shape)
self.assertTrue(np.all(np.equal(manualResult, patchesCpp)))
def test_extract_patches_batched(self):
# It's kind of stupid – testing against a reference implementation,
# but manually generating large test cases is fairly annoying.
data = np.arange(0, 2 * 3 * 4 * 5 * 6, dtype=np.uint8).reshape((2, 3, 4, 5, 6))
patchesCorrect, centersCorrect, *r = reference_extract_patches(data, (2, 4), (2, 2), (1, 3))
patchesCpp, centersCpp, *r = patching_tools.extract_patches_batch(data, (2, 4), (2, 2), (1, 3),
batchStart=4, batchSize=2)
self.assertEqual(patchesCorrect.shape[1:], patchesCpp.shape[1:])
self.assertTrue(np.all(np.equal(patchesCorrect[4:4 + 2], patchesCpp)))
self.assertTrue(np.all(np.equal(centersCorrect[4:4 + 2], centersCpp)))
# --------------
data = np.arange(0, 3 * 4 * 5, dtype=np.uint8).reshape((3, 4, 5))
patchesCpp, *r = patching_tools.extract_patches_batch(data, (0, 2), (2, 2), (1, 3),
batchStart=2, batchSize=2)
manualResult = np.asarray([
[
[[20, 21], [25, 26], [30, 31], [35, 36]],
[[40, 41], [45, 46], [50, 51], [55, 56]],
],
[
[[23, 24], [28, 29], [33, 34], [38, 39]],
[[43, 44], [48, 49], [53, 54], [58, 59]]
]
], dtype=np.uint8)
self.assertEqual(manualResult.shape, patchesCpp.shape)
self.assertTrue(np.all(np.equal(manualResult, patchesCpp)))
def test_extract_patched_training_data_without_empty_4d(self):
data = np.arange(0, 3 * 3 * 3 * 3, dtype=np.uint8).reshape((3, 3, 3, 3))
dataXActual, dataYActual, *r = \
patching_tools.extract_patched_all_data_without_empty_4d(data, (2, 2, 2, 2), (2, 1, 1, 1), 15,
batchSize=100)
manualResult = np.asarray(
[[[[[0, 1],
[3, 4]],
[[9, 10],
[12, 13]]]],
[[[[1, 2],
[4, 5]],
[[10, 11],
[13, 14]]]],
[[[[3, 4],
[6, 7]],
[[12, 13],
[15, 16]]]],
[[[[4, 5],
[7, 8]],
[[13, 14],
[16, 17]]]],
[[[[9, 10],
[12, 13]],
[[18, 19],
[21, 22]]]],
[[[[10, 11],
[13, 14]],
[[19, 20],
[22, 23]]]],
[[[[12, 13],
[15, 16]],
[[21, 22],
[24, 25]]]],
[[[[13, 14],
[16, 17]],
[[22, 23],
[25, 26]]]]]
, dtype=np.uint8)
self.assertEqual(manualResult.shape, dataXActual.shape)
self.assertTrue(np.all(np.equal(manualResult, dataXActual)))
# ------------------------------------------------------
# It's kind of stupid – testing against a reference implementation,
# but manually generating large test cases is fairly annoying.
# Also, we are testing the C++ implementation against the trusted Python code.
data = np.arange(0, 5 * 7 * 9 * 10, dtype=np.uint8).reshape((5, 7, 9, 10))
dataXCorrect, dataYCorrect, patchIndicesCorrect = \
reference_extract_patched_all_data_without_empty_4d(data, (3, 4, 3, 5), (1, 1, 2, 1), 15)
dataXActual, dataYActual, patchIndicesActual = \
patching_tools.extract_patched_all_data_without_empty_4d(data, (3, 4, 3, 5), (1, 1, 2, 1), 15,
batchSize=100)
self.assertEqual(dataXCorrect.shape, dataXActual.shape)
self.assertEqual(dataYCorrect.shape, dataYActual.shape)
self.assertEqual(patchIndicesCorrect.shape, patchIndicesActual.shape)
self.assertTrue(np.all(np.equal(dataXCorrect, dataXActual)))
self.assertTrue(np.all(np.equal(dataYCorrect, dataYActual)))
self.assertTrue(np.all(np.equal(patchIndicesCorrect, patchIndicesActual)))
# ------------------------------------------------------
# Stride of (1, 1, 1, 1).
data = np.arange(0, 5 * 7 * 9 * 10, dtype=np.uint8).reshape((5, 7, 9, 10))
dataXCorrect, dataYCorrect, patchIndicesCorrect = \
reference_extract_patched_all_data_without_empty_4d(data, (3, 4, 3, 5), (1, 1, 1, 1), 15)
dataXActual, dataYActual, patchIndicesActual = \
patching_tools.extract_patched_all_data_without_empty_4d(data, (3, 4, 3, 5), (1, 1, 1, 1), 15,
batchSize=100)
self.assertEqual(dataXCorrect.shape, dataXActual.shape)
self.assertEqual(dataYCorrect.shape, dataYActual.shape)
self.assertEqual(patchIndicesCorrect.shape, patchIndicesActual.shape)
self.assertTrue(np.all(np.equal(dataXCorrect, dataXActual)))
self.assertTrue(np.all(np.equal(dataYCorrect, dataYActual)))
self.assertTrue(np.all(np.equal(patchIndicesCorrect, patchIndicesActual)))
# ------------------------------------------------------
# The same thing, but with some empty patches
data = np.arange(0, 5 * 7 * 9 * 10, dtype=np.uint8).reshape((5, 7, 9, 10))
data[0:4, 0:6, 0:8, 1:9] = 15
dataXCorrect, dataYCorrect, patchIndicesCorrect = \
reference_extract_patched_all_data_without_empty_4d(data, (3, 4, 3, 5), (1, 1, 2, 1), 15)
dataXActual, dataYActual, patchIndicesActual = \
patching_tools.extract_patched_all_data_without_empty_4d(data, (3, 4, 3, 5), (1, 1, 2, 1), 15,
batchSize=100)
self.assertEqual(dataXCorrect.shape, dataXActual.shape)
self.assertEqual(dataYCorrect.shape, dataYActual.shape)
self.assertEqual(patchIndicesCorrect.shape, patchIndicesActual.shape)
self.assertTrue(np.all(np.equal(dataXCorrect, dataXActual)))
self.assertTrue(np.all(np.equal(dataYCorrect, dataYActual)))
self.assertTrue(np.all(np.equal(patchIndicesCorrect, patchIndicesActual)))
def test_shuffle_hdf_arrays_together(self):
shapeX = (1000, 25, 25)
shapeY = (1000, 25, 1)
tempDir = tempfile.mkdtemp()
file = h5py.File(os.path.join(tempDir, 'temp.h5py'))
dataX = file.create_dataset('tempX', shapeX, np.float32)
dataX[...] = np.random.uniform(0, 1000, shapeX)
dataY = file.create_dataset('tempY', shapeY, np.float32)
for i in range(0, shapeX[0]):
for j in range(0, shapeX[1]):
simpleHash = np.sum(dataX[i, j, :].astype(np.int32)) % 73
dataY[i, j] = simpleHash
firstColumnBefore = dataX[:, 0, 0]
dataYBefore = dataY[...].copy()
timeBefore = time.time()
npe.shuffle_hdf_arrays_together(dataX, dataY, blockSize=13)
print("Shuffled in {:.2f} s.".format(time.time() - timeBefore))
# Check that order has changed.
self.assertFalse(np.all(np.equal(firstColumnBefore, dataX[:, 0, 0])),
msg='If we are extremely unlucky, the order might not change')
# Check that the arrays are still in sync.
for i in range(0, shapeX[0]):
for j in range(0, shapeX[1]):
simpleHash = np.sum(dataX[i, j, :].astype(np.int32)) % 73
self.assertEqual(dataY[i, j], simpleHash)
# Check that arrays have the same content.
self.assertTrue(np.all(np.equal(np.sort(dataYBefore.flatten()),
np.sort(dataY[...].flatten()))))
def test_abs_diff_hdf_arrays(self):
shape = (10000, 25, 25)
tempDir = tempfile.mkdtemp()
file = h5py.File(os.path.join(tempDir, 'temp.h5py'))
dataA = file.create_dataset('tempA', shape, np.uint8)
dataB = file.create_dataset('tempB', shape, np.uint8)
out = file.create_dataset('out', shape, np.float32)
dataA[...] = np.random.uniform(0, 255, shape)
dataB[...] = np.random.uniform(0, 255, shape)
out[...] = np.random.uniform(0, 255, shape)
npe.abs_diff_hdf_arrays(dataA, dataB, out, np.float32, batchSizeFlat=3119)
trueDiff = np.abs(dataA[...].astype(np.float32) - dataB[...].astype(np.float32))
self.assertTrue(np.all(np.equal(out, trueDiff)))
def test_abs_diff_hdf_arrays_masked(self):
shape = (10000, 25, 25)
tempDir = tempfile.mkdtemp()
file = h5py.File(os.path.join(tempDir, 'temp.h5py'))
dataA = file.create_dataset('tempA', shape, np.uint8)
dataB = file.create_dataset('tempB', shape, np.uint8)
mask = file.create_dataset('mask', shape, np.bool)
out = file.create_dataset('out', shape, np.float32)
dataA[...] = np.random.uniform(0, 255, shape)
dataB[...] = np.random.uniform(0, 255, shape)
mask[...] = False
mask[:5000] = True
out[...] = np.random.uniform(0, 255, shape)
npe.abs_diff_hdf_arrays_masked(dataA, dataB, mask, out, np.float32, batchSizeFlat=3119)
trueDiff = np.abs(dataA[...].astype(np.float32) - dataB[...].astype(np.float32))
trueDiff[np.logical_not(mask)] = 0
self.assertTrue(np.all(np.equal(out, trueDiff)))
def test_mse_large_arrays_with_hdf(self):
shape = (10000, 25, 25)
tempDir = tempfile.mkdtemp()
file = h5py.File(os.path.join(tempDir, 'temp.h5py'))
dataA = file.create_dataset('tempA', shape, np.uint8)
dataB = file.create_dataset('tempB', shape, np.uint8)
dataA[...] = np.random.uniform(0, 255, shape)
dataB[...] = np.random.uniform(0, 255, shape)
# Test typical conditions.
mse = npe.mse_large_arrays(dataA, dataB, np.float64, batchSizeFlat=7119)
trueMse = np.mean(np.square(dataA[...].astype(np.float64) - dataB[...].astype(np.float64)), dtype=np.float64)
self.assertAlmostEqual(mse, trueMse)
# Test batches with an imbalanced number of elements.
mse = npe.mse_large_arrays(dataA, dataB, np.float64, batchSizeFlat=8000 * 25 * 25 * 4)
trueMse = np.mean(np.square(dataA[...].astype(np.float64) - dataB[...].astype(np.float64)), dtype=np.float64)
self.assertAlmostEqual(mse, trueMse)
def test_mse_large_arrays_with_bna(self):
shape = (10000, 25, 25)
dataA = BufferedNdArray(tempfile.mktemp(), BufferedNdArray.FileMode.rewrite, shape, np.uint8, int(1e8))
dataB = BufferedNdArray(tempfile.mktemp(), BufferedNdArray.FileMode.rewrite, shape, np.uint8, int(1e8))
dataA[...] = np.random.uniform(0, 255, shape).astype(np.uint8)
dataB[...] = np.random.uniform(0, 255, shape).astype(np.uint8)
# Test typical conditions.
mse = npe.mse_large_arrays(dataA, dataB, np.float64, batchSizeFlat=7119)
trueMse = np.mean(np.square(dataA[...].astype(np.float64) - dataB[...].astype(np.float64)), dtype=np.float64)
self.assertAlmostEqual(mse, trueMse)
# Test batches with an imbalanced number of elements.
mse = npe.mse_large_arrays(dataA, dataB, np.float64, batchSizeFlat=8000 * 25 * 25 * 4)
trueMse = np.mean(np.square(dataA[...].astype(np.float64) - dataB[...].astype(np.float64)), dtype=np.float64)
self.assertAlmostEqual(mse, trueMse)
def test_large_arrays_masked_with_hdf(self):
shape = (10000, 25, 25)
tempDir = tempfile.mkdtemp()
file = h5py.File(os.path.join(tempDir, 'temp.h5py'))
dataA = file.create_dataset('tempA', shape, np.uint8)
dataB = file.create_dataset('tempB', shape, np.uint8)
mask = file.create_dataset('mask', shape, np.bool)
dataA[...] = np.random.uniform(0, 255, shape)
dataB[...] = np.random.uniform(0, 255, shape)
mask[...] = False
mask[:5000] = True
# Test typical conditions.
mse = npe.mse_large_arrays_masked(dataA, dataB, mask, np.float64, batchSizeFlat=27119)
trueMse = np.mean(np.square(dataA[:5000].astype(np.float64) - dataB[:5000].astype(np.float64)),
dtype=np.float64)
self.assertAlmostEqual(mse, trueMse)
# Test batches with an imbalanced number of elements.
mse = npe.mse_large_arrays_masked(dataA, dataB, mask, np.float64, batchSizeFlat=8000 * 25 * 25 * 4)
trueMse = np.mean(np.square(dataA[:5000].astype(np.float64) - dataB[:5000].astype(np.float64)),
dtype=np.float64)
self.assertAlmostEqual(mse, trueMse)
def test_large_arrays_masked_with_bna(self):
shape = (10000, 25, 25)
dataA = BufferedNdArray(tempfile.mktemp(), BufferedNdArray.FileMode.rewrite, shape, np.uint8, int(1e8))
dataB = BufferedNdArray(tempfile.mktemp(), BufferedNdArray.FileMode.rewrite, shape, np.uint8, int(1e8))
mask = BufferedNdArray(tempfile.mktemp(), BufferedNdArray.FileMode.rewrite, shape, np.uint8, int(1e8))
dataA[...] = np.random.uniform(0, 255, shape).astype(np.uint8)
dataB[...] = np.random.uniform(0, 255, shape).astype(np.uint8)
mask[...] = np.zeros(shape, dtype=np.uint8)
for i in range(5000):
mask[i] = np.ones(shape[1:], dtype=np.uint8)
# Test typical conditions.
mse = npe.mse_large_arrays_masked(dataA, dataB, mask, np.float64, batchSizeFlat=27119)
trueMse = np.mean(np.square(dataA[:5000].astype(np.float64) - dataB[:5000].astype(np.float64)),
dtype=np.float64)
self.assertAlmostEqual(mse, trueMse)
# Test batches with an imbalanced number of elements.
mse = npe.mse_large_arrays_masked(dataA, dataB, mask, np.float64, batchSizeFlat=8000 * 25 * 25 * 4)
trueMse = np.mean(np.square(dataA[:5000].astype(np.float64) - dataB[:5000].astype(np.float64)),
dtype=np.float64)
self.assertAlmostEqual(mse, trueMse)
def test_var_large_array(self):
shape = (10000, 25, 25)
tempDir = tempfile.mkdtemp()
file = h5py.File(os.path.join(tempDir, 'temp.h5py'))
data = file.create_dataset('tempA', shape, np.uint8)
data[...] = np.random.uniform(0, 255, shape)
# Test typical conditions.
var = npe.var_large_array(data, np.float64, batchSizeFlat=7119)
trueVar = np.mean(np.square(data[...].astype(np.float64)), dtype=np.float64) - \
np.mean(data[...].astype(np.float64), dtype=np.float64) ** 2
self.assertAlmostEqual(var, trueVar)
# Test batches with an imbalanced number of elements.
var = npe.var_large_array(data, np.float64, batchSizeFlat=8000 * 25 * 25 * 4)
trueVar = np.mean(np.square(data[...].astype(np.float64)), dtype=np.float64) - \
np.mean(data[...].astype(np.float64), dtype=np.float64) ** 2
self.assertAlmostEqual(var, trueVar)
data = file.create_dataset('tempB', (10, 1), np.uint8)
data[...] = np.asarray([0, 0, 0, 0, 0, 10, 10, 10, 10, 10]).reshape(10, 1)
var = npe.var_large_array(data, np.float64, batchSizeFlat=3119)
self.assertAlmostEqual(var, 25.0)
def test_var_large_array_masked(self):
shape = (10000, 25, 15)
tempDir = tempfile.mkdtemp()
file = h5py.File(os.path.join(tempDir, 'temp.h5py'))
data = file.create_dataset('tempA', shape, np.uint8)
mask = file.create_dataset('maskA', shape, np.bool)
data[...] = np.random.uniform(0, 255, shape)
mask[...] = False
mask[:5000] = True
# Test typical conditions.
var = npe.var_large_array_masked(data, mask, np.float64, batchSizeFlat=7119)
trueVar = np.mean(np.square(data[:5000].astype(np.float64)), dtype=np.float64) - \
np.mean(data[:5000].astype(np.float64), dtype=np.float64) ** 2
numpyVar = np.var(data[:5000], dtype=np.float64)
self.assertAlmostEqual(var, trueVar)
self.assertAlmostEqual(var, numpyVar)
# Test batches with an imbalanced number of elements.
# The first batch has 4000 nonzero slices, the second - only 1000.
var = npe.var_large_array_masked(data, mask, np.float64, batchSizeFlat=4000 * 25 * 15 * 4)
trueVar = np.mean(np.square(data[:5000].astype(np.float64)), dtype=np.float64) - \
np.mean(data[:5000].astype(np.float64), dtype=np.float64) ** 2
self.assertAlmostEqual(var, trueVar)
# Test a small easy to understand case.
data = file.create_dataset('tempB', (10, 1), np.uint8)
mask = file.create_dataset('maskB', (10, 1), np.bool)
data[...] = np.asarray([0, 0, 0, 0, 66, 66, 10, 10, 10, 10]).reshape(10, 1)
mask[...] = True
mask[4:6] = False
var = npe.var_large_array_masked(data, mask, np.float64, batchSizeFlat=3119)
self.assertAlmostEqual(var, 25.0)
def test_get_batch_indices(self):
shape = (1000, 5, 7)
dtype = np.float32
batchSizeFlat = 32000
expectedBatchSize = 228 # 32000 / (5 * 7 * 4)
expectedIndices = [(0, 228), (228, 456), (456, 684), (684, 912), (912, 1000)]
actualIndices = list(npe.get_batch_indices(shape, dtype, batchSizeFlat=batchSizeFlat))
self.assertEqual(expectedIndices, actualIndices)
# Test a very large batch.
actualIndices = list(npe.get_batch_indices(shape, dtype, batchSizeFlat=1e10))
self.assertEqual([(0, 1000)], actualIndices)
# Test a batch that is too small.
with self.assertRaises(RuntimeError):
list(npe.get_batch_indices(shape, dtype, batchSizeFlat=10))
# todo: Test the fixed batch size parameter.
def test_numpy_json_encoder(self):
tempDir = tempfile.gettempdir()
tempPath = os.path.join(tempDir, 'test_json_encoder.json')
for dtype in [np.float32, np.float64, np.int32, np.int64, np.uint8]:
array = np.ones(5, dtype)
value = array[0]
with open(tempPath, 'w') as file: # Overwrite existing.
json.dump({'key': value}, file, cls=npe.JsonEncoder)
with open(tempPath, 'r') as file:
contents = json.load(file)
self.assertEqual(contents['key'], value)
def test_moving_average_nd(self):
data = np.array(
[[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
expected = np.array(
[[ 8, 15, 12],
[21, 36, 27],
[20, 33, 24]]) / 9.0
actual = npe.moving_average_nd(data, kernelSize=3)
self.assertTrue(np.all(np.less(np.abs(actual - expected), 1e-5)))
expected = np.array(
[[0, 1, 3],
[3, 8, 12],
[9, 20, 24]]) / 4.0
actual = npe.moving_average_nd(data, kernelSize=2)
self.assertTrue(np.all(np.less(np.abs(actual - expected), 1e-5)))
def test_sparse_insert_into_bna(self):
tempPath = self._get_temp_filepath('test_sparse_insert_into_bna.raw')
testCaseSize = 2000
shape = (10, 64, 64, 64)
dataSizeFlat = npe.multiply(shape)
np.random.seed(1771)
# Double the size, to test that the provided insert count is respected.
indices = np.random.randint(0, 10, size=(2 * testCaseSize, len(shape)), dtype=np.uint64)
values = np.random.randint(1, 255, size=(2 * testCaseSize, 1), dtype=np.uint8)
with BufferedNdArray(tempPath, BufferedNdArray.FileMode.rewrite, shape, np.uint8, int(1e5)) as array:
npe.sparse_insert_into_bna(array, indices, values, testCaseSize)
with open(tempPath, 'rb') as file:
rawData = np.fromfile(file, np.uint8, dataSizeFlat).reshape(shape)
correctData = np.zeros(shape, dtype=np.uint8)
# Repeat the same operations and compare the result, since some values may be overwritten.
for i in range(testCaseSize):
indexNd = tuple(indices[i, :])
correctData[indexNd] = values[i, 0]
for i in range(testCaseSize):
indexNd = tuple(indices[i, :])
self.assertEqual(correctData[indexNd], rawData[indexNd])
# This test relies on the file being zeroed before writing, which afaik isn't guaranteed.
self.assertEqual(np.count_nonzero(rawData), np.count_nonzero(correctData))
def test_sparse_insert_slices_into_bna(self):
tempPath = self._get_temp_filepath('test_sparse_insert_slices_into_bna.raw')
# Test slices of all possible ranks.
for sliceNdim in range(1, 5):
testCaseSize = 2000
shape = (10, 11, 12, 13, 14)
np.random.seed(1771)
sliceFlatSize = npe.multiply(shape[-sliceNdim:]) * np.dtype(np.float32()).itemsize
bufferFlatSize = int(sliceFlatSize * 1.9)
# Double the size, to test that the provided insert count is respected and we don't copy too much.
indices = np.random.randint(0, 10, size=(2 * testCaseSize, len(shape) - sliceNdim), dtype=np.uint64)
slices = np.random.uniform(0, 1000, size=(2 * testCaseSize, *shape[-sliceNdim:])).astype(np.float32).copy()
with BufferedNdArray(tempPath, BufferedNdArray.FileMode.rewrite, shape, np.float32, bufferFlatSize) as array:
npe.sparse_insert_slices_into_bna(array, indices, slices, sliceNdim, testCaseSize)
correctData = np.zeros(shape, dtype=np.float32)
# Repeat the same operations and compare the result, since some values may be overwritten.
for i in range(testCaseSize):
indexNd = tuple(indices[i, :])
correctData[indexNd] = slices[i]
for i in range(testCaseSize):
indexNd = tuple(int(x) for x in indices[i, :])
self.assertTrue(np.all(np.equal(correctData[indexNd], array[indexNd])))
def test_sparse_insert_patches_into_bna(self):
tempPath = self._get_temp_filepath('test_sparse_insert_patches_into_bna.raw')
volumeSize = (32, 32, 32, 32)
patchSize = (3, 3, 3, 3)
testCases = [
([0, 0, 0, 0], 1.1),
([29, 29, 29, 29], 2.2),
([0, 29, 29, 29], 3.3),
([29, 0, 0, 29], 3.3),
([10, 10, 10, 10], 4.4),
([4, 5, 6, 7], 5.5)
]
patchIndices = np.empty((len(testCases), len(volumeSize)), dtype=np.uint64)
patchValues = np.empty((len(testCases), *patchSize), dtype=np.float32)
maxBufferSize = int(6 * (32 ** 3) * 4)
with BufferedNdArray(tempPath, BufferedNdArray.FileMode.rewrite, volumeSize, np.float32, maxBufferSize) as array:
array.fill_box(0.0, (0, 0, 0, 0), volumeSize)
for i, (patchIndex, patchValue) in enumerate(testCases):
patchIndices[i, :] = patchIndex
patchValues[i, ...] = patchValue
npe.sparse_insert_patches_into_bna(array, patchIndices, patchValues, patchSize, len(testCases))
patchSizeMinusOne = tuple([x - 1 for x in patchSize])
for patchIndex, patchValue in testCases:
lastCoveredIndex = tuple(map(operator.add, patchIndex, patchSizeMinusOne))
outsideIndex = tuple(map(operator.add, patchIndex, patchSize))
self.assertAlmostEqual(array[tuple(patchIndex)], patchValue, places=5)
self.assertAlmostEqual(array[lastCoveredIndex], patchValue, places=5)
if all([outsideIndex[dim] < volumeSize[dim] for dim in range(len(volumeSize))]):
self.assertAlmostEqual(array[outsideIndex], 0, places=5)
def test_aggregate_attention_volume(self):
volumeShape = (12, 12, 12, 12)
patchXSize = (4, 4, 4, 4)
patchYSize = (2, 2, 2, 2)
patchNumber = patching_tools.compute_patch_number(volumeShape, patchXSize, patchYSize, patchYSize)
attentionShape = patchNumber + tuple(int(x / 3) for x in patchXSize)
attention = BufferedNdArray(tempfile.mktemp(suffix='.bna'),
BufferedNdArray.FileMode.rewrite,
shape=attentionShape, dtype=np.float32, maxBufferSize=int(1e9))
attention.fill_box(0.01, (0,) * attention.ndim, attention.shape)
# Use a smaller buffer to check that the results are flushed.
# Had a bug where I wasn't setting the dirty flag and results never hit the disk.
writeBufferSize = int(6 * 12 * 12 * 12 * 4)
attentionAgg = BufferedNdArray(tempfile.mktemp(suffix='.bna'),
BufferedNdArray.FileMode.rewrite,
shape=volumeShape, dtype=np.float32, maxBufferSize=writeBufferSize)
# C++ aggregation code assumes that the array is initialized to zeros.
attentionAgg.fill_box(0, (0,) * attentionAgg.ndim, attentionAgg.shape)
npe.aggregate_attention_volume(attention, volumeShape, patchXSize, patchYSize, attentionAgg)
self.assertAlmostEqual(attentionAgg[5, 5, 5, 5], 0.01 * (2 ** 4))
self.assertAlmostEqual(attentionAgg.max(), 0.01 * (2 ** 4))
self.assertAlmostEqual(attentionAgg.min(), 0.0) # Some zeros at the last frames not covered by X-patches.
self.assertAlmostEqual(attentionAgg[:10].min(), 0.01) # Single attention weight around edges.
attention.destruct()
attentionAgg.destruct()
@staticmethod
def _get_temp_filepath(filename: str):
tempDir = tempfile.gettempdir()
tempPath = os.path.join(tempDir, filename)
if os.path.exists(tempPath):
os.unlink(tempPath)
return tempPath
if __name__ == '__main__':
unittest.main()
| [
"PythonExtras.numpy_extras.var_large_array_masked",
"PythonExtras.numpy_extras.aggregate_attention_volume",
"PythonExtras.BufferedNdArray.BufferedNdArray",
"numpy.fromfile",
"PythonExtras.CppWrapper.CppWrapper.test",
"numpy.logical_not",
"numpy.equal",
"PythonExtras.numpy_extras.abs_diff_hdf_arrays_ma... | [((2484, 2495), 'time.time', 'time.time', ([], {}), '()\n', (2493, 2495), False, 'import time\n'), ((4303, 4337), 'numpy.not_equal', 'np.not_equal', (['allDataY', 'emptyValue'], {}), '(allDataY, emptyValue)\n', (4315, 4337), True, 'import numpy as np\n'), ((4467, 4520), 'numpy.logical_or', 'np.logical_or', (['nonemptyPatchMaskX', 'nonemptyPatchMaskY'], {}), '(nonemptyPatchMaskX, nonemptyPatchMaskY)\n', (4480, 4520), True, 'import numpy as np\n'), ((37202, 37217), 'unittest.main', 'unittest.main', ([], {}), '()\n', (37215, 37217), False, 'import unittest\n'), ((1061, 1084), 'numpy.asarray', 'np.asarray', (['patchNumber'], {}), '(patchNumber)\n', (1071, 1084), True, 'import numpy as np\n'), ((2438, 2461), 'numpy.asarray', 'np.asarray', (['patchNumber'], {}), '(patchNumber)\n', (2448, 2461), True, 'import numpy as np\n'), ((2759, 2802), 'PythonExtras.numpy_extras.unflatten_index', 'npe.unflatten_index', (['patchNumber', 'indexFlat'], {}), '(patchNumber, indexFlat)\n', (2778, 2802), True, 'from PythonExtras import numpy_extras as npe\n'), ((4370, 4404), 'numpy.not_equal', 'np.not_equal', (['allDataX', 'emptyValue'], {}), '(allDataX, emptyValue)\n', (4382, 4404), True, 'import numpy as np\n'), ((4639, 4680), 'numpy.asarray', 'np.asarray', (['patchCenters'], {'dtype': 'np.uint64'}), '(patchCenters, dtype=np.uint64)\n', (4649, 4680), True, 'import numpy as np\n'), ((5922, 5998), 'PythonExtras.patching_tools.extract_patches', 'patching_tools.extract_patches', (['volume', '(0, 1, 2, 3)', 'patchSize', 'patchStride'], {}), '(volume, (0, 1, 2, 3), patchSize, patchStride)\n', (5952, 5998), False, 'from PythonExtras import patching_tools\n'), ((6057, 6101), 'PythonExtras.numpy_extras.flatten_index', 'npe.flatten_index', (['patchIndexNd', 'patchNumber'], {}), '(patchIndexNd, patchNumber)\n', (6074, 6101), True, 'from PythonExtras import numpy_extras as npe\n'), ((6417, 6439), 'PythonExtras.CppWrapper.CppWrapper.test', 'CppWrapper.test', (['input'], {}), '(input)\n', (6432, 6439), False, 'from PythonExtras.CppWrapper import CppWrapper\n'), ((6560, 6668), 'numpy.asarray', 'np.asarray', (['[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15], [16, 17, 18]]'], {'dtype': 'np.float'}), '([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15], [\n 16, 17, 18]], dtype=np.float)\n', (6570, 6668), True, 'import numpy as np\n'), ((6858, 6914), 'numpy.asarray', 'np.asarray', (['[[1, 3], [10, 12], [16, 18]]'], {'dtype': 'np.float'}), '([[1, 3], [10, 12], [16, 18]], dtype=np.float)\n', (6868, 6914), True, 'import numpy as np\n'), ((7012, 7062), 'PythonExtras.volume_tools.resize_array_point', 'volume_tools.resize_array_point', (['input', 'targetSize'], {}), '(input, targetSize)\n', (7043, 7062), False, 'from PythonExtras import volume_tools\n'), ((8008, 8068), 'PythonExtras.patching_tools.extract_patches', 'patching_tools.extract_patches', (['data', '(0, 2)', '(2, 5)', '(1, 2)'], {}), '(data, (0, 2), (2, 5), (1, 2))\n', (8038, 8068), False, 'from PythonExtras import patching_tools\n'), ((8423, 8492), 'PythonExtras.patching_tools.extract_patches', 'patching_tools.extract_patches', (['data', '(0, 1, 2)', '(1, 1, 1)', '(1, 1, 1)'], {}), '(data, (0, 1, 2), (1, 1, 1), (1, 1, 1))\n', (8453, 8492), False, 'from PythonExtras import patching_tools\n'), ((8838, 8898), 'PythonExtras.patching_tools.extract_patches', 'patching_tools.extract_patches', (['data', '(1, 2)', '(1, 3)', '(5, 1)'], {}), '(data, (1, 2), (1, 3), (5, 1))\n', (8868, 8898), False, 'from PythonExtras import patching_tools\n'), ((9358, 9418), 'PythonExtras.patching_tools.extract_patches', 'patching_tools.extract_patches', (['data', '(2, 4)', '(2, 2)', '(1, 3)'], {}), '(data, (2, 4), (2, 2), (1, 3))\n', (9388, 9418), False, 'from PythonExtras import patching_tools\n'), ((9740, 9800), 'PythonExtras.patching_tools.extract_patches', 'patching_tools.extract_patches', (['data', '(0, 1)', '(2, 3)', '(2, 1)'], {}), '(data, (0, 1), (2, 3), (2, 1))\n', (9770, 9800), False, 'from PythonExtras import patching_tools\n'), ((9825, 9963), 'numpy.asarray', 'np.asarray', (['[[[0, 1, 2], [4, 5, 6]], [[1, 2, 3], [5, 6, 7]], [[8, 9, 10], [12, 13, 14]],\n [[9, 10, 11], [13, 14, 15]]]'], {'dtype': 'np.uint8'}), '([[[0, 1, 2], [4, 5, 6]], [[1, 2, 3], [5, 6, 7]], [[8, 9, 10], [\n 12, 13, 14]], [[9, 10, 11], [13, 14, 15]]], dtype=np.uint8)\n', (9835, 9963), True, 'import numpy as np\n'), ((10327, 10387), 'PythonExtras.patching_tools.extract_patches', 'patching_tools.extract_patches', (['data', '(0, 2)', '(2, 2)', '(1, 3)'], {}), '(data, (0, 2), (2, 2), (1, 3))\n', (10357, 10387), False, 'from PythonExtras import patching_tools\n'), ((10412, 10794), 'numpy.asarray', 'np.asarray', (['[[[[0, 1], [5, 6], [10, 11], [15, 16]], [[20, 21], [25, 26], [30, 31], [35,\n 36]]], [[[3, 4], [8, 9], [13, 14], [18, 19]], [[23, 24], [28, 29], [33,\n 34], [38, 39]]], [[[20, 21], [25, 26], [30, 31], [35, 36]], [[40, 41],\n [45, 46], [50, 51], [55, 56]]], [[[23, 24], [28, 29], [33, 34], [38, 39\n ]], [[43, 44], [48, 49], [53, 54], [58, 59]]]]'], {'dtype': 'np.uint8'}), '([[[[0, 1], [5, 6], [10, 11], [15, 16]], [[20, 21], [25, 26], [30,\n 31], [35, 36]]], [[[3, 4], [8, 9], [13, 14], [18, 19]], [[23, 24], [28,\n 29], [33, 34], [38, 39]]], [[[20, 21], [25, 26], [30, 31], [35, 36]], [\n [40, 41], [45, 46], [50, 51], [55, 56]]], [[[23, 24], [28, 29], [33, 34\n ], [38, 39]], [[43, 44], [48, 49], [53, 54], [58, 59]]]], dtype=np.uint8)\n', (10422, 10794), True, 'import numpy as np\n'), ((11573, 11670), 'PythonExtras.patching_tools.extract_patches_batch', 'patching_tools.extract_patches_batch', (['data', '(2, 4)', '(2, 2)', '(1, 3)'], {'batchStart': '(4)', 'batchSize': '(2)'}), '(data, (2, 4), (2, 2), (1, 3),\n batchStart=4, batchSize=2)\n', (11609, 11670), False, 'from PythonExtras import patching_tools\n'), ((12098, 12195), 'PythonExtras.patching_tools.extract_patches_batch', 'patching_tools.extract_patches_batch', (['data', '(0, 2)', '(2, 2)', '(1, 3)'], {'batchStart': '(2)', 'batchSize': '(2)'}), '(data, (0, 2), (2, 2), (1, 3),\n batchStart=2, batchSize=2)\n', (12134, 12195), False, 'from PythonExtras import patching_tools\n'), ((12278, 12487), 'numpy.asarray', 'np.asarray', (['[[[[20, 21], [25, 26], [30, 31], [35, 36]], [[40, 41], [45, 46], [50, 51],\n [55, 56]]], [[[23, 24], [28, 29], [33, 34], [38, 39]], [[43, 44], [48, \n 49], [53, 54], [58, 59]]]]'], {'dtype': 'np.uint8'}), '([[[[20, 21], [25, 26], [30, 31], [35, 36]], [[40, 41], [45, 46],\n [50, 51], [55, 56]]], [[[23, 24], [28, 29], [33, 34], [38, 39]], [[43, \n 44], [48, 49], [53, 54], [58, 59]]]], dtype=np.uint8)\n', (12288, 12487), True, 'import numpy as np\n'), ((12941, 13054), 'PythonExtras.patching_tools.extract_patched_all_data_without_empty_4d', 'patching_tools.extract_patched_all_data_without_empty_4d', (['data', '(2, 2, 2, 2)', '(2, 1, 1, 1)', '(15)'], {'batchSize': '(100)'}), '(data, (2, 2, 2, 2),\n (2, 1, 1, 1), 15, batchSize=100)\n', (12997, 13054), False, 'from PythonExtras import patching_tools\n'), ((13144, 13562), 'numpy.asarray', 'np.asarray', (['[[[[[0, 1], [3, 4]], [[9, 10], [12, 13]]]], [[[[1, 2], [4, 5]], [[10, 11],\n [13, 14]]]], [[[[3, 4], [6, 7]], [[12, 13], [15, 16]]]], [[[[4, 5], [7,\n 8]], [[13, 14], [16, 17]]]], [[[[9, 10], [12, 13]], [[18, 19], [21, 22]\n ]]], [[[[10, 11], [13, 14]], [[19, 20], [22, 23]]]], [[[[12, 13], [15, \n 16]], [[21, 22], [24, 25]]]], [[[[13, 14], [16, 17]], [[22, 23], [25, \n 26]]]]]'], {'dtype': 'np.uint8'}), '([[[[[0, 1], [3, 4]], [[9, 10], [12, 13]]]], [[[[1, 2], [4, 5]],\n [[10, 11], [13, 14]]]], [[[[3, 4], [6, 7]], [[12, 13], [15, 16]]]], [[[\n [4, 5], [7, 8]], [[13, 14], [16, 17]]]], [[[[9, 10], [12, 13]], [[18, \n 19], [21, 22]]]], [[[[10, 11], [13, 14]], [[19, 20], [22, 23]]]], [[[[\n 12, 13], [15, 16]], [[21, 22], [24, 25]]]], [[[[13, 14], [16, 17]], [[\n 22, 23], [25, 26]]]]], dtype=np.uint8)\n', (13154, 13562), True, 'import numpy as np\n'), ((14783, 14896), 'PythonExtras.patching_tools.extract_patched_all_data_without_empty_4d', 'patching_tools.extract_patched_all_data_without_empty_4d', (['data', '(3, 4, 3, 5)', '(1, 1, 2, 1)', '(15)'], {'batchSize': '(100)'}), '(data, (3, 4, 3, 5),\n (1, 1, 2, 1), 15, batchSize=100)\n', (14839, 14896), False, 'from PythonExtras import patching_tools\n'), ((15807, 15920), 'PythonExtras.patching_tools.extract_patched_all_data_without_empty_4d', 'patching_tools.extract_patched_all_data_without_empty_4d', (['data', '(3, 4, 3, 5)', '(1, 1, 1, 1)', '(15)'], {'batchSize': '(100)'}), '(data, (3, 4, 3, 5),\n (1, 1, 1, 1), 15, batchSize=100)\n', (15863, 15920), False, 'from PythonExtras import patching_tools\n'), ((16889, 17002), 'PythonExtras.patching_tools.extract_patched_all_data_without_empty_4d', 'patching_tools.extract_patched_all_data_without_empty_4d', (['data', '(3, 4, 3, 5)', '(1, 1, 2, 1)', '(15)'], {'batchSize': '(100)'}), '(data, (3, 4, 3, 5),\n (1, 1, 2, 1), 15, batchSize=100)\n', (16945, 17002), False, 'from PythonExtras import patching_tools\n'), ((17628, 17646), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), '()\n', (17644, 17646), False, 'import tempfile\n'), ((17794, 17828), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(1000)', 'shapeX'], {}), '(0, 1000, shapeX)\n', (17811, 17828), True, 'import numpy as np\n'), ((18195, 18206), 'time.time', 'time.time', ([], {}), '()\n', (18204, 18206), False, 'import time\n'), ((18215, 18274), 'PythonExtras.numpy_extras.shuffle_hdf_arrays_together', 'npe.shuffle_hdf_arrays_together', (['dataX', 'dataY'], {'blockSize': '(13)'}), '(dataX, dataY, blockSize=13)\n', (18246, 18274), True, 'from PythonExtras import numpy_extras as npe\n'), ((19107, 19125), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), '()\n', (19123, 19125), False, 'import tempfile\n'), ((19393, 19425), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(255)', 'shape'], {}), '(0, 255, shape)\n', (19410, 19425), True, 'import numpy as np\n'), ((19447, 19479), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(255)', 'shape'], {}), '(0, 255, shape)\n', (19464, 19479), True, 'import numpy as np\n'), ((19499, 19531), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(255)', 'shape'], {}), '(0, 255, shape)\n', (19516, 19531), True, 'import numpy as np\n'), ((19541, 19615), 'PythonExtras.numpy_extras.abs_diff_hdf_arrays', 'npe.abs_diff_hdf_arrays', (['dataA', 'dataB', 'out', 'np.float32'], {'batchSizeFlat': '(3119)'}), '(dataA, dataB, out, np.float32, batchSizeFlat=3119)\n', (19564, 19615), True, 'from PythonExtras import numpy_extras as npe\n'), ((19862, 19880), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), '()\n', (19878, 19880), False, 'import tempfile\n'), ((20207, 20239), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(255)', 'shape'], {}), '(0, 255, shape)\n', (20224, 20239), True, 'import numpy as np\n'), ((20261, 20293), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(255)', 'shape'], {}), '(0, 255, shape)\n', (20278, 20293), True, 'import numpy as np\n'), ((20366, 20398), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(255)', 'shape'], {}), '(0, 255, shape)\n', (20383, 20398), True, 'import numpy as np\n'), ((20408, 20499), 'PythonExtras.numpy_extras.abs_diff_hdf_arrays_masked', 'npe.abs_diff_hdf_arrays_masked', (['dataA', 'dataB', 'mask', 'out', 'np.float32'], {'batchSizeFlat': '(3119)'}), '(dataA, dataB, mask, out, np.float32,\n batchSizeFlat=3119)\n', (20438, 20499), True, 'from PythonExtras import numpy_extras as npe\n'), ((20784, 20802), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), '()\n', (20800, 20802), False, 'import tempfile\n'), ((21010, 21042), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(255)', 'shape'], {}), '(0, 255, shape)\n', (21027, 21042), True, 'import numpy as np\n'), ((21064, 21096), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(255)', 'shape'], {}), '(0, 255, shape)\n', (21081, 21096), True, 'import numpy as np\n'), ((21147, 21213), 'PythonExtras.numpy_extras.mse_large_arrays', 'npe.mse_large_arrays', (['dataA', 'dataB', 'np.float64'], {'batchSizeFlat': '(7119)'}), '(dataA, dataB, np.float64, batchSizeFlat=7119)\n', (21167, 21213), True, 'from PythonExtras import numpy_extras as npe\n'), ((21455, 21540), 'PythonExtras.numpy_extras.mse_large_arrays', 'npe.mse_large_arrays', (['dataA', 'dataB', 'np.float64'], {'batchSizeFlat': '(8000 * 25 * 25 * 4)'}), '(dataA, dataB, np.float64, batchSizeFlat=8000 * 25 * 25 * 4\n )\n', (21475, 21540), True, 'from PythonExtras import numpy_extras as npe\n'), ((22197, 22263), 'PythonExtras.numpy_extras.mse_large_arrays', 'npe.mse_large_arrays', (['dataA', 'dataB', 'np.float64'], {'batchSizeFlat': '(7119)'}), '(dataA, dataB, np.float64, batchSizeFlat=7119)\n', (22217, 22263), True, 'from PythonExtras import numpy_extras as npe\n'), ((22505, 22590), 'PythonExtras.numpy_extras.mse_large_arrays', 'npe.mse_large_arrays', (['dataA', 'dataB', 'np.float64'], {'batchSizeFlat': '(8000 * 25 * 25 * 4)'}), '(dataA, dataB, np.float64, batchSizeFlat=8000 * 25 * 25 * 4\n )\n', (22525, 22590), True, 'from PythonExtras import numpy_extras as npe\n'), ((22851, 22869), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), '()\n', (22867, 22869), False, 'import tempfile\n'), ((23136, 23168), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(255)', 'shape'], {}), '(0, 255, shape)\n', (23153, 23168), True, 'import numpy as np\n'), ((23190, 23222), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(255)', 'shape'], {}), '(0, 255, shape)\n', (23207, 23222), True, 'import numpy as np\n'), ((23326, 23411), 'PythonExtras.numpy_extras.mse_large_arrays_masked', 'npe.mse_large_arrays_masked', (['dataA', 'dataB', 'mask', 'np.float64'], {'batchSizeFlat': '(27119)'}), '(dataA, dataB, mask, np.float64, batchSizeFlat=27119\n )\n', (23353, 23411), True, 'from PythonExtras import numpy_extras as npe\n'), ((23678, 23776), 'PythonExtras.numpy_extras.mse_large_arrays_masked', 'npe.mse_large_arrays_masked', (['dataA', 'dataB', 'mask', 'np.float64'], {'batchSizeFlat': '(8000 * 25 * 25 * 4)'}), '(dataA, dataB, mask, np.float64, batchSizeFlat=\n 8000 * 25 * 25 * 4)\n', (23705, 23776), True, 'from PythonExtras import numpy_extras as npe\n'), ((24547, 24578), 'numpy.zeros', 'np.zeros', (['shape'], {'dtype': 'np.uint8'}), '(shape, dtype=np.uint8)\n', (24555, 24578), True, 'import numpy as np\n'), ((24716, 24801), 'PythonExtras.numpy_extras.mse_large_arrays_masked', 'npe.mse_large_arrays_masked', (['dataA', 'dataB', 'mask', 'np.float64'], {'batchSizeFlat': '(27119)'}), '(dataA, dataB, mask, np.float64, batchSizeFlat=27119\n )\n', (24743, 24801), True, 'from PythonExtras import numpy_extras as npe\n'), ((25068, 25166), 'PythonExtras.numpy_extras.mse_large_arrays_masked', 'npe.mse_large_arrays_masked', (['dataA', 'dataB', 'mask', 'np.float64'], {'batchSizeFlat': '(8000 * 25 * 25 * 4)'}), '(dataA, dataB, mask, np.float64, batchSizeFlat=\n 8000 * 25 * 25 * 4)\n', (25095, 25166), True, 'from PythonExtras import numpy_extras as npe\n'), ((25444, 25462), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), '()\n', (25460, 25462), False, 'import tempfile\n'), ((25606, 25638), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(255)', 'shape'], {}), '(0, 255, shape)\n', (25623, 25638), True, 'import numpy as np\n'), ((25689, 25746), 'PythonExtras.numpy_extras.var_large_array', 'npe.var_large_array', (['data', 'np.float64'], {'batchSizeFlat': '(7119)'}), '(data, np.float64, batchSizeFlat=7119)\n', (25708, 25746), True, 'from PythonExtras import numpy_extras as npe\n'), ((26038, 26109), 'PythonExtras.numpy_extras.var_large_array', 'npe.var_large_array', (['data', 'np.float64'], {'batchSizeFlat': '(8000 * 25 * 25 * 4)'}), '(data, np.float64, batchSizeFlat=8000 * 25 * 25 * 4)\n', (26057, 26109), True, 'from PythonExtras import numpy_extras as npe\n'), ((26486, 26543), 'PythonExtras.numpy_extras.var_large_array', 'npe.var_large_array', (['data', 'np.float64'], {'batchSizeFlat': '(3119)'}), '(data, np.float64, batchSizeFlat=3119)\n', (26505, 26543), True, 'from PythonExtras import numpy_extras as npe\n'), ((26682, 26700), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), '()\n', (26698, 26700), False, 'import tempfile\n'), ((26904, 26936), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(255)', 'shape'], {}), '(0, 255, shape)\n', (26921, 26936), True, 'import numpy as np\n'), ((27040, 27110), 'PythonExtras.numpy_extras.var_large_array_masked', 'npe.var_large_array_masked', (['data', 'mask', 'np.float64'], {'batchSizeFlat': '(7119)'}), '(data, mask, np.float64, batchSizeFlat=7119)\n', (27066, 27110), True, 'from PythonExtras import numpy_extras as npe\n'), ((27303, 27340), 'numpy.var', 'np.var', (['data[:5000]'], {'dtype': 'np.float64'}), '(data[:5000], dtype=np.float64)\n', (27309, 27340), True, 'import numpy as np\n'), ((27584, 27672), 'PythonExtras.numpy_extras.var_large_array_masked', 'npe.var_large_array_masked', (['data', 'mask', 'np.float64'], {'batchSizeFlat': '(4000 * 25 * 15 * 4)'}), '(data, mask, np.float64, batchSizeFlat=4000 * 25 *\n 15 * 4)\n', (27610, 27672), True, 'from PythonExtras import numpy_extras as npe\n'), ((28211, 28281), 'PythonExtras.numpy_extras.var_large_array_masked', 'npe.var_large_array_masked', (['data', 'mask', 'np.float64'], {'batchSizeFlat': '(3119)'}), '(data, mask, np.float64, batchSizeFlat=3119)\n', (28237, 28281), True, 'from PythonExtras import numpy_extras as npe\n'), ((29192, 29213), 'tempfile.gettempdir', 'tempfile.gettempdir', ([], {}), '()\n', (29211, 29213), False, 'import tempfile\n'), ((29233, 29280), 'os.path.join', 'os.path.join', (['tempDir', '"""test_json_encoder.json"""'], {}), "(tempDir, 'test_json_encoder.json')\n", (29245, 29280), False, 'import os\n'), ((29765, 29808), 'numpy.array', 'np.array', (['[[0, 1, 2], [3, 4, 5], [6, 7, 8]]'], {}), '([[0, 1, 2], [3, 4, 5], [6, 7, 8]])\n', (29773, 29808), True, 'import numpy as np\n'), ((29984, 30025), 'PythonExtras.numpy_extras.moving_average_nd', 'npe.moving_average_nd', (['data'], {'kernelSize': '(3)'}), '(data, kernelSize=3)\n', (30005, 30025), True, 'from PythonExtras import numpy_extras as npe\n'), ((30230, 30271), 'PythonExtras.numpy_extras.moving_average_nd', 'npe.moving_average_nd', (['data'], {'kernelSize': '(2)'}), '(data, kernelSize=2)\n', (30251, 30271), True, 'from PythonExtras import numpy_extras as npe\n'), ((30553, 30572), 'PythonExtras.numpy_extras.multiply', 'npe.multiply', (['shape'], {}), '(shape)\n', (30565, 30572), True, 'from PythonExtras import numpy_extras as npe\n'), ((30581, 30601), 'numpy.random.seed', 'np.random.seed', (['(1771)'], {}), '(1771)\n', (30595, 30601), True, 'import numpy as np\n'), ((30796, 30865), 'numpy.random.randint', 'np.random.randint', (['(1)', '(255)'], {'size': '(2 * testCaseSize, 1)', 'dtype': 'np.uint8'}), '(1, 255, size=(2 * testCaseSize, 1), dtype=np.uint8)\n', (30813, 30865), True, 'import numpy as np\n'), ((31200, 31231), 'numpy.zeros', 'np.zeros', (['shape'], {'dtype': 'np.uint8'}), '(shape, dtype=np.uint8)\n', (31208, 31231), True, 'import numpy as np\n'), ((35301, 35389), 'PythonExtras.patching_tools.compute_patch_number', 'patching_tools.compute_patch_number', (['volumeShape', 'patchXSize', 'patchYSize', 'patchYSize'], {}), '(volumeShape, patchXSize, patchYSize,\n patchYSize)\n', (35336, 35389), False, 'from PythonExtras import patching_tools\n'), ((36406, 36502), 'PythonExtras.numpy_extras.aggregate_attention_volume', 'npe.aggregate_attention_volume', (['attention', 'volumeShape', 'patchXSize', 'patchYSize', 'attentionAgg'], {}), '(attention, volumeShape, patchXSize,\n patchYSize, attentionAgg)\n', (36436, 36502), True, 'from PythonExtras import numpy_extras as npe\n'), ((37002, 37023), 'tempfile.gettempdir', 'tempfile.gettempdir', ([], {}), '()\n', (37021, 37023), False, 'import tempfile\n'), ((37043, 37074), 'os.path.join', 'os.path.join', (['tempDir', 'filename'], {}), '(tempDir, filename)\n', (37055, 37074), False, 'import os\n'), ((37086, 37110), 'os.path.exists', 'os.path.exists', (['tempPath'], {}), '(tempPath)\n', (37100, 37110), False, 'import os\n'), ((1413, 1453), 'numpy.empty', 'np.empty', (['resultShape'], {'dtype': 'patch.dtype'}), '(resultShape, dtype=patch.dtype)\n', (1421, 1453), True, 'import numpy as np\n'), ((3684, 3695), 'time.time', 'time.time', ([], {}), '()\n', (3693, 3695), False, 'import time\n'), ((4741, 4762), 'numpy.asarray', 'np.asarray', (['patchSize'], {}), '(patchSize)\n', (4751, 4762), True, 'import numpy as np\n'), ((5591, 5630), 'PythonExtras.numpy_extras.flatten_index', 'npe.flatten_index', (['(1, 2, 3)', '(3, 4, 5)'], {}), '((1, 2, 3), (3, 4, 5))\n', (5608, 5630), True, 'from PythonExtras import numpy_extras as npe\n'), ((17672, 17706), 'os.path.join', 'os.path.join', (['tempDir', '"""temp.h5py"""'], {}), "(tempDir, 'temp.h5py')\n", (17684, 17706), False, 'import os\n'), ((19151, 19185), 'os.path.join', 'os.path.join', (['tempDir', '"""temp.h5py"""'], {}), "(tempDir, 'temp.h5py')\n", (19163, 19185), False, 'import os\n'), ((19906, 19940), 'os.path.join', 'os.path.join', (['tempDir', '"""temp.h5py"""'], {}), "(tempDir, 'temp.h5py')\n", (19918, 19940), False, 'import os\n'), ((20603, 20623), 'numpy.logical_not', 'np.logical_not', (['mask'], {}), '(mask)\n', (20617, 20623), True, 'import numpy as np\n'), ((20828, 20862), 'os.path.join', 'os.path.join', (['tempDir', '"""temp.h5py"""'], {}), "(tempDir, 'temp.h5py')\n", (20840, 20862), False, 'import os\n'), ((21812, 21829), 'tempfile.mktemp', 'tempfile.mktemp', ([], {}), '()\n', (21827, 21829), False, 'import tempfile\n'), ((21924, 21941), 'tempfile.mktemp', 'tempfile.mktemp', ([], {}), '()\n', (21939, 21941), False, 'import tempfile\n'), ((22895, 22929), 'os.path.join', 'os.path.join', (['tempDir', '"""temp.h5py"""'], {}), "(tempDir, 'temp.h5py')\n", (22907, 22929), False, 'import os\n'), ((24081, 24098), 'tempfile.mktemp', 'tempfile.mktemp', ([], {}), '()\n', (24096, 24098), False, 'import tempfile\n'), ((24193, 24210), 'tempfile.mktemp', 'tempfile.mktemp', ([], {}), '()\n', (24208, 24210), False, 'import tempfile\n'), ((24304, 24321), 'tempfile.mktemp', 'tempfile.mktemp', ([], {}), '()\n', (24319, 24321), False, 'import tempfile\n'), ((24631, 24665), 'numpy.ones', 'np.ones', (['shape[1:]'], {'dtype': 'np.uint8'}), '(shape[1:], dtype=np.uint8)\n', (24638, 24665), True, 'import numpy as np\n'), ((25488, 25522), 'os.path.join', 'os.path.join', (['tempDir', '"""temp.h5py"""'], {}), "(tempDir, 'temp.h5py')\n", (25500, 25522), False, 'import os\n'), ((26726, 26760), 'os.path.join', 'os.path.join', (['tempDir', '"""temp.h5py"""'], {}), "(tempDir, 'temp.h5py')\n", (26738, 26760), False, 'import os\n'), ((28621, 28685), 'PythonExtras.numpy_extras.get_batch_indices', 'npe.get_batch_indices', (['shape', 'dtype'], {'batchSizeFlat': 'batchSizeFlat'}), '(shape, dtype, batchSizeFlat=batchSizeFlat)\n', (28642, 28685), True, 'from PythonExtras import numpy_extras as npe\n'), ((28809, 28873), 'PythonExtras.numpy_extras.get_batch_indices', 'npe.get_batch_indices', (['shape', 'dtype'], {'batchSizeFlat': '(10000000000.0)'}), '(shape, dtype, batchSizeFlat=10000000000.0)\n', (28830, 28873), True, 'from PythonExtras import numpy_extras as npe\n'), ((29379, 29396), 'numpy.ones', 'np.ones', (['(5)', 'dtype'], {}), '(5, dtype)\n', (29386, 29396), True, 'import numpy as np\n'), ((29868, 29919), 'numpy.array', 'np.array', (['[[8, 15, 12], [21, 36, 27], [20, 33, 24]]'], {}), '([[8, 15, 12], [21, 36, 27], [20, 33, 24]])\n', (29876, 29919), True, 'import numpy as np\n'), ((30120, 30166), 'numpy.array', 'np.array', (['[[0, 1, 3], [3, 8, 12], [9, 20, 24]]'], {}), '([[0, 1, 3], [3, 8, 12], [9, 20, 24]])\n', (30128, 30166), True, 'import numpy as np\n'), ((30989, 31053), 'PythonExtras.numpy_extras.sparse_insert_into_bna', 'npe.sparse_insert_into_bna', (['array', 'indices', 'values', 'testCaseSize'], {}), '(array, indices, values, testCaseSize)\n', (31015, 31053), True, 'from PythonExtras import numpy_extras as npe\n'), ((31735, 31760), 'numpy.count_nonzero', 'np.count_nonzero', (['rawData'], {}), '(rawData)\n', (31751, 31760), True, 'import numpy as np\n'), ((31762, 31791), 'numpy.count_nonzero', 'np.count_nonzero', (['correctData'], {}), '(correctData)\n', (31778, 31791), True, 'import numpy as np\n'), ((32098, 32118), 'numpy.random.seed', 'np.random.seed', (['(1771)'], {}), '(1771)\n', (32112, 32118), True, 'import numpy as np\n'), ((34041, 34144), 'PythonExtras.BufferedNdArray.BufferedNdArray', 'BufferedNdArray', (['tempPath', 'BufferedNdArray.FileMode.rewrite', 'volumeSize', 'np.float32', 'maxBufferSize'], {}), '(tempPath, BufferedNdArray.FileMode.rewrite, volumeSize, np.\n float32, maxBufferSize)\n', (34056, 34144), False, 'from PythonExtras.BufferedNdArray import BufferedNdArray\n'), ((35499, 35529), 'tempfile.mktemp', 'tempfile.mktemp', ([], {'suffix': '""".bna"""'}), "(suffix='.bna')\n", (35514, 35529), False, 'import tempfile\n'), ((36027, 36057), 'tempfile.mktemp', 'tempfile.mktemp', ([], {'suffix': '""".bna"""'}), "(suffix='.bna')\n", (36042, 36057), False, 'import tempfile\n'), ((37124, 37143), 'os.unlink', 'os.unlink', (['tempPath'], {}), '(tempPath)\n', (37133, 37143), False, 'import os\n'), ((1946, 1982), 'math.ceil', 'math.ceil', (['(totalPatchNumber / stride)'], {}), '(totalPatchNumber / stride)\n', (1955, 1982), False, 'import math\n'), ((2905, 2943), 'numpy.asarray', 'np.asarray', (['patchIndexNd'], {'dtype': 'np.int'}), '(patchIndexNd, dtype=np.int)\n', (2915, 2943), True, 'import numpy as np\n'), ((2946, 2983), 'numpy.asarray', 'np.asarray', (['patchStride'], {'dtype': 'np.int'}), '(patchStride, dtype=np.int)\n', (2956, 2983), True, 'import numpy as np\n'), ((5769, 5800), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(255)', 'size'], {}), '(0, 255, size)\n', (5786, 5800), True, 'import numpy as np\n'), ((6320, 6336), 'numpy.arange', 'np.arange', (['(0)', '(16)'], {}), '(0, 16)\n', (6329, 6336), True, 'import numpy as np\n'), ((7095, 7133), 'numpy.equal', 'np.equal', (['expectedOutput', 'actualOutput'], {}), '(expectedOutput, actualOutput)\n', (7103, 7133), True, 'import numpy as np\n'), ((7811, 7850), 'numpy.arange', 'np.arange', (['(0)', '(5 * 7 * 9)'], {'dtype': 'np.uint8'}), '(0, 5 * 7 * 9, dtype=np.uint8)\n', (7820, 7850), True, 'import numpy as np\n'), ((8166, 8202), 'numpy.equal', 'np.equal', (['patchesCorrect', 'patchesCpp'], {}), '(patchesCorrect, patchesCpp)\n', (8174, 8202), True, 'import numpy as np\n'), ((8236, 8272), 'numpy.equal', 'np.equal', (['centersCorrect', 'centersCpp'], {}), '(centersCorrect, centersCpp)\n', (8244, 8272), True, 'import numpy as np\n'), ((8590, 8626), 'numpy.equal', 'np.equal', (['patchesCorrect', 'patchesCpp'], {}), '(patchesCorrect, patchesCpp)\n', (8598, 8626), True, 'import numpy as np\n'), ((8660, 8696), 'numpy.equal', 'np.equal', (['centersCorrect', 'centersCpp'], {}), '(centersCorrect, centersCpp)\n', (8668, 8696), True, 'import numpy as np\n'), ((8996, 9032), 'numpy.equal', 'np.equal', (['patchesCorrect', 'patchesCpp'], {}), '(patchesCorrect, patchesCpp)\n', (9004, 9032), True, 'import numpy as np\n'), ((9066, 9102), 'numpy.equal', 'np.equal', (['centersCorrect', 'centersCpp'], {}), '(centersCorrect, centersCpp)\n', (9074, 9102), True, 'import numpy as np\n'), ((9146, 9193), 'numpy.arange', 'np.arange', (['(0)', '(2 * 3 * 4 * 5 * 6)'], {'dtype': 'np.uint8'}), '(0, 2 * 3 * 4 * 5 * 6, dtype=np.uint8)\n', (9155, 9193), True, 'import numpy as np\n'), ((9516, 9552), 'numpy.equal', 'np.equal', (['patchesCorrect', 'patchesCpp'], {}), '(patchesCorrect, patchesCpp)\n', (9524, 9552), True, 'import numpy as np\n'), ((9586, 9622), 'numpy.equal', 'np.equal', (['centersCorrect', 'centersCpp'], {}), '(centersCorrect, centersCpp)\n', (9594, 9622), True, 'import numpy as np\n'), ((9666, 9698), 'numpy.arange', 'np.arange', (['(0)', '(20)'], {'dtype': 'np.uint8'}), '(0, 20, dtype=np.uint8)\n', (9675, 9698), True, 'import numpy as np\n'), ((10165, 10199), 'numpy.equal', 'np.equal', (['manualResult', 'patchesCpp'], {}), '(manualResult, patchesCpp)\n', (10173, 10199), True, 'import numpy as np\n'), ((10243, 10282), 'numpy.arange', 'np.arange', (['(0)', '(3 * 4 * 5)'], {'dtype': 'np.uint8'}), '(0, 3 * 4 * 5, dtype=np.uint8)\n', (10252, 10282), True, 'import numpy as np\n'), ((11116, 11150), 'numpy.equal', 'np.equal', (['manualResult', 'patchesCpp'], {}), '(manualResult, patchesCpp)\n', (11124, 11150), True, 'import numpy as np\n'), ((11361, 11408), 'numpy.arange', 'np.arange', (['(0)', '(2 * 3 * 4 * 5 * 6)'], {'dtype': 'np.uint8'}), '(0, 2 * 3 * 4 * 5 * 6, dtype=np.uint8)\n', (11370, 11408), True, 'import numpy as np\n'), ((11846, 11891), 'numpy.equal', 'np.equal', (['patchesCorrect[4:4 + 2]', 'patchesCpp'], {}), '(patchesCorrect[4:4 + 2], patchesCpp)\n', (11854, 11891), True, 'import numpy as np\n'), ((11925, 11970), 'numpy.equal', 'np.equal', (['centersCorrect[4:4 + 2]', 'centersCpp'], {}), '(centersCorrect[4:4 + 2], centersCpp)\n', (11933, 11970), True, 'import numpy as np\n'), ((12014, 12053), 'numpy.arange', 'np.arange', (['(0)', '(3 * 4 * 5)'], {'dtype': 'np.uint8'}), '(0, 3 * 4 * 5, dtype=np.uint8)\n', (12023, 12053), True, 'import numpy as np\n'), ((12701, 12735), 'numpy.equal', 'np.equal', (['manualResult', 'patchesCpp'], {}), '(manualResult, patchesCpp)\n', (12709, 12735), True, 'import numpy as np\n'), ((12821, 12864), 'numpy.arange', 'np.arange', (['(0)', '(3 * 3 * 3 * 3)'], {'dtype': 'np.uint8'}), '(0, 3 * 3 * 3 * 3, dtype=np.uint8)\n', (12830, 12864), True, 'import numpy as np\n'), ((14128, 14163), 'numpy.equal', 'np.equal', (['manualResult', 'dataXActual'], {}), '(manualResult, dataXActual)\n', (14136, 14163), True, 'import numpy as np\n'), ((14483, 14527), 'numpy.arange', 'np.arange', (['(0)', '(5 * 7 * 9 * 10)'], {'dtype': 'np.uint8'}), '(0, 5 * 7 * 9 * 10, dtype=np.uint8)\n', (14492, 14527), True, 'import numpy as np\n'), ((15201, 15236), 'numpy.equal', 'np.equal', (['dataXCorrect', 'dataXActual'], {}), '(dataXCorrect, dataXActual)\n', (15209, 15236), True, 'import numpy as np\n'), ((15270, 15305), 'numpy.equal', 'np.equal', (['dataYCorrect', 'dataYActual'], {}), '(dataYCorrect, dataYActual)\n', (15278, 15305), True, 'import numpy as np\n'), ((15339, 15388), 'numpy.equal', 'np.equal', (['patchIndicesCorrect', 'patchIndicesActual'], {}), '(patchIndicesCorrect, patchIndicesActual)\n', (15347, 15388), True, 'import numpy as np\n'), ((15507, 15551), 'numpy.arange', 'np.arange', (['(0)', '(5 * 7 * 9 * 10)'], {'dtype': 'np.uint8'}), '(0, 5 * 7 * 9 * 10, dtype=np.uint8)\n', (15516, 15551), True, 'import numpy as np\n'), ((16224, 16259), 'numpy.equal', 'np.equal', (['dataXCorrect', 'dataXActual'], {}), '(dataXCorrect, dataXActual)\n', (16232, 16259), True, 'import numpy as np\n'), ((16293, 16328), 'numpy.equal', 'np.equal', (['dataYCorrect', 'dataYActual'], {}), '(dataYCorrect, dataYActual)\n', (16301, 16328), True, 'import numpy as np\n'), ((16362, 16411), 'numpy.equal', 'np.equal', (['patchIndicesCorrect', 'patchIndicesActual'], {}), '(patchIndicesCorrect, patchIndicesActual)\n', (16370, 16411), True, 'import numpy as np\n'), ((16549, 16593), 'numpy.arange', 'np.arange', (['(0)', '(5 * 7 * 9 * 10)'], {'dtype': 'np.uint8'}), '(0, 5 * 7 * 9 * 10, dtype=np.uint8)\n', (16558, 16593), True, 'import numpy as np\n'), ((17307, 17342), 'numpy.equal', 'np.equal', (['dataXCorrect', 'dataXActual'], {}), '(dataXCorrect, dataXActual)\n', (17315, 17342), True, 'import numpy as np\n'), ((17376, 17411), 'numpy.equal', 'np.equal', (['dataYCorrect', 'dataYActual'], {}), '(dataYCorrect, dataYActual)\n', (17384, 17411), True, 'import numpy as np\n'), ((17445, 17494), 'numpy.equal', 'np.equal', (['patchIndicesCorrect', 'patchIndicesActual'], {}), '(patchIndicesCorrect, patchIndicesActual)\n', (17453, 17494), True, 'import numpy as np\n'), ((18420, 18463), 'numpy.equal', 'np.equal', (['firstColumnBefore', 'dataX[:, 0, 0]'], {}), '(firstColumnBefore, dataX[:, 0, 0])\n', (18428, 18463), True, 'import numpy as np\n'), ((19737, 19760), 'numpy.equal', 'np.equal', (['out', 'trueDiff'], {}), '(out, trueDiff)\n', (19745, 19760), True, 'import numpy as np\n'), ((20660, 20683), 'numpy.equal', 'np.equal', (['out', 'trueDiff'], {}), '(out, trueDiff)\n', (20668, 20683), True, 'import numpy as np\n'), ((22026, 22058), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(255)', 'shape'], {}), '(0, 255, shape)\n', (22043, 22058), True, 'import numpy as np\n'), ((22097, 22129), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(255)', 'shape'], {}), '(0, 255, shape)\n', (22114, 22129), True, 'import numpy as np\n'), ((24406, 24438), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(255)', 'shape'], {}), '(0, 255, shape)\n', (24423, 24438), True, 'import numpy as np\n'), ((24477, 24509), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(255)', 'shape'], {}), '(0, 255, shape)\n', (24494, 24509), True, 'import numpy as np\n'), ((26408, 26455), 'numpy.asarray', 'np.asarray', (['[0, 0, 0, 0, 0, 10, 10, 10, 10, 10]'], {}), '([0, 0, 0, 0, 0, 10, 10, 10, 10, 10])\n', (26418, 26455), True, 'import numpy as np\n'), ((28081, 28129), 'numpy.asarray', 'np.asarray', (['[0, 0, 0, 0, 66, 66, 10, 10, 10, 10]'], {}), '([0, 0, 0, 0, 66, 66, 10, 10, 10, 10])\n', (28091, 28129), True, 'import numpy as np\n'), ((29025, 29078), 'PythonExtras.numpy_extras.get_batch_indices', 'npe.get_batch_indices', (['shape', 'dtype'], {'batchSizeFlat': '(10)'}), '(shape, dtype, batchSizeFlat=10)\n', (29046, 29078), True, 'from PythonExtras import numpy_extras as npe\n'), ((29512, 29564), 'json.dump', 'json.dump', (["{'key': value}", 'file'], {'cls': 'npe.JsonEncoder'}), "({'key': value}, file, cls=npe.JsonEncoder)\n", (29521, 29564), False, 'import json\n'), ((29638, 29653), 'json.load', 'json.load', (['file'], {}), '(file)\n', (29647, 29653), False, 'import json\n'), ((32148, 32180), 'PythonExtras.numpy_extras.multiply', 'npe.multiply', (['shape[-sliceNdim:]'], {}), '(shape[-sliceNdim:])\n', (32160, 32180), True, 'from PythonExtras import numpy_extras as npe\n'), ((32632, 32731), 'PythonExtras.BufferedNdArray.BufferedNdArray', 'BufferedNdArray', (['tempPath', 'BufferedNdArray.FileMode.rewrite', 'shape', 'np.float32', 'bufferFlatSize'], {}), '(tempPath, BufferedNdArray.FileMode.rewrite, shape, np.\n float32, bufferFlatSize)\n', (32647, 32731), False, 'from PythonExtras.BufferedNdArray import BufferedNdArray\n'), ((32753, 32839), 'PythonExtras.numpy_extras.sparse_insert_slices_into_bna', 'npe.sparse_insert_slices_into_bna', (['array', 'indices', 'slices', 'sliceNdim', 'testCaseSize'], {}), '(array, indices, slices, sliceNdim,\n testCaseSize)\n', (32786, 32839), True, 'from PythonExtras import numpy_extras as npe\n'), ((32867, 32900), 'numpy.zeros', 'np.zeros', (['shape'], {'dtype': 'np.float32'}), '(shape, dtype=np.float32)\n', (32875, 32900), True, 'import numpy as np\n'), ((3622, 3633), 'time.time', 'time.time', ([], {}), '()\n', (3631, 3633), False, 'import time\n'), ((6225, 6260), 'numpy.equal', 'np.equal', (['correctPatch', 'actualPatch'], {}), '(correctPatch, actualPatch)\n', (6233, 6260), True, 'import numpy as np\n'), ((6465, 6496), 'numpy.equal', 'np.equal', (['input', 'expectedOutput'], {}), '(input, expectedOutput)\n', (6473, 6496), True, 'import numpy as np\n'), ((18320, 18331), 'time.time', 'time.time', ([], {}), '()\n', (18329, 18331), False, 'import time\n'), ((30065, 30090), 'numpy.abs', 'np.abs', (['(actual - expected)'], {}), '(actual - expected)\n', (30071, 30090), True, 'import numpy as np\n'), ((30311, 30336), 'numpy.abs', 'np.abs', (['(actual - expected)'], {}), '(actual - expected)\n', (30317, 30336), True, 'import numpy as np\n'), ((31120, 31161), 'numpy.fromfile', 'np.fromfile', (['file', 'np.uint8', 'dataSizeFlat'], {}), '(file, np.uint8, dataSizeFlat)\n', (31131, 31161), True, 'import numpy as np\n'), ((32192, 32204), 'numpy.float32', 'np.float32', ([], {}), '()\n', (32202, 32204), True, 'import numpy as np\n'), ((32515, 32587), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(1000)'], {'size': '(2 * testCaseSize, *shape[-sliceNdim:])'}), '(0, 1000, size=(2 * testCaseSize, *shape[-sliceNdim:]))\n', (32532, 32587), True, 'import numpy as np\n'), ((33315, 33361), 'numpy.equal', 'np.equal', (['correctData[indexNd]', 'array[indexNd]'], {}), '(correctData[indexNd], array[indexNd])\n', (33323, 33361), True, 'import numpy as np\n')] |
import odespy
from vib_odespy import run_solvers_and_plot, RHS, \
VibSolverWrapper4Odespy, plt
from numpy import pi, sin
# Primary ODE: m=1, s(u)=(2*pi)**2*u, such that the period is 1.
# Then we add linear damping and a force term A*sin(w*t) where
# w is half and double of the frequency of the free oscillations.
ODEs = [
(RHS(b=0.1), 'Small damping, no forcing'),
(RHS(b=0.4), 'Medium damping, no forcing'),
(RHS(b=0.4, F=lambda t: 1*sin(0.5*pi*t)),
'Medium damping, medium forcing w/smaller frequency'),
(RHS(b=0.4, F=lambda t: 10*sin(0.5*pi*t)),
'Medium damping, large forcing w/smaller frequency'),
(RHS(b=1.2, F=lambda t: 10*sin(0.5*pi*t)),
'Strong damping, large forcing w/smaller frequency'),
(RHS(b=0.4, F=lambda t: 1*sin(2*pi*t)),
'Medium damping, medium forcing w/larger frequency'),
(RHS(b=0.4, F=lambda t: 10*sin(2*pi*t)),
'Medium damping, large forcing w/larger frequency'),
(RHS(b=1.2, F=lambda t: 10*sin(2*pi*t)),
'Strong damping, large forcing w/larger frequency'),
]
for rhs, title in ODEs:
solvers = [
odespy.ForwardEuler(rhs),
# Implicit methods must use Newton solver to converge
odespy.BackwardEuler(rhs, nonlinear_solver='Newton'),
odespy.CrankNicolson(rhs, nonlinear_solver='Newton'),
VibSolverWrapper4Odespy(rhs),
]
T = 20 # Period is 1
dt = 0.05 # 20 steps per period
filename = 'FEBNCN_' + title.replace(', ', '_').replace('w/', '')
title = title + ' (dt=%g)' % dt
plt.figure()
run_solvers_and_plot(solvers, rhs, T, dt, title=title,
filename=filename)
plt.show()
raw_input()
| [
"vib_odespy.VibSolverWrapper4Odespy",
"odespy.CrankNicolson",
"vib_odespy.plt.show",
"vib_odespy.RHS",
"odespy.BackwardEuler",
"vib_odespy.run_solvers_and_plot",
"odespy.ForwardEuler",
"numpy.sin",
"vib_odespy.plt.figure"
] | [((1672, 1682), 'vib_odespy.plt.show', 'plt.show', ([], {}), '()\n', (1680, 1682), False, 'from vib_odespy import run_solvers_and_plot, RHS, VibSolverWrapper4Odespy, plt\n'), ((1555, 1567), 'vib_odespy.plt.figure', 'plt.figure', ([], {}), '()\n', (1565, 1567), False, 'from vib_odespy import run_solvers_and_plot, RHS, VibSolverWrapper4Odespy, plt\n'), ((1572, 1645), 'vib_odespy.run_solvers_and_plot', 'run_solvers_and_plot', (['solvers', 'rhs', 'T', 'dt'], {'title': 'title', 'filename': 'filename'}), '(solvers, rhs, T, dt, title=title, filename=filename)\n', (1592, 1645), False, 'from vib_odespy import run_solvers_and_plot, RHS, VibSolverWrapper4Odespy, plt\n'), ((336, 346), 'vib_odespy.RHS', 'RHS', ([], {'b': '(0.1)'}), '(b=0.1)\n', (339, 346), False, 'from vib_odespy import run_solvers_and_plot, RHS, VibSolverWrapper4Odespy, plt\n'), ((383, 393), 'vib_odespy.RHS', 'RHS', ([], {'b': '(0.4)'}), '(b=0.4)\n', (386, 393), False, 'from vib_odespy import run_solvers_and_plot, RHS, VibSolverWrapper4Odespy, plt\n'), ((1108, 1132), 'odespy.ForwardEuler', 'odespy.ForwardEuler', (['rhs'], {}), '(rhs)\n', (1127, 1132), False, 'import odespy\n'), ((1204, 1256), 'odespy.BackwardEuler', 'odespy.BackwardEuler', (['rhs'], {'nonlinear_solver': '"""Newton"""'}), "(rhs, nonlinear_solver='Newton')\n", (1224, 1256), False, 'import odespy\n'), ((1266, 1318), 'odespy.CrankNicolson', 'odespy.CrankNicolson', (['rhs'], {'nonlinear_solver': '"""Newton"""'}), "(rhs, nonlinear_solver='Newton')\n", (1286, 1318), False, 'import odespy\n'), ((1328, 1356), 'vib_odespy.VibSolverWrapper4Odespy', 'VibSolverWrapper4Odespy', (['rhs'], {}), '(rhs)\n', (1351, 1356), False, 'from vib_odespy import run_solvers_and_plot, RHS, VibSolverWrapper4Odespy, plt\n'), ((456, 473), 'numpy.sin', 'sin', (['(0.5 * pi * t)'], {}), '(0.5 * pi * t)\n', (459, 473), False, 'from numpy import pi, sin\n'), ((563, 580), 'numpy.sin', 'sin', (['(0.5 * pi * t)'], {}), '(0.5 * pi * t)\n', (566, 580), False, 'from numpy import pi, sin\n'), ((669, 686), 'numpy.sin', 'sin', (['(0.5 * pi * t)'], {}), '(0.5 * pi * t)\n', (672, 686), False, 'from numpy import pi, sin\n'), ((774, 789), 'numpy.sin', 'sin', (['(2 * pi * t)'], {}), '(2 * pi * t)\n', (777, 789), False, 'from numpy import pi, sin\n'), ((878, 893), 'numpy.sin', 'sin', (['(2 * pi * t)'], {}), '(2 * pi * t)\n', (881, 893), False, 'from numpy import pi, sin\n'), ((981, 996), 'numpy.sin', 'sin', (['(2 * pi * t)'], {}), '(2 * pi * t)\n', (984, 996), False, 'from numpy import pi, sin\n')] |
from argparse import ArgumentParser
from pathlib import Path
import os
import time
import glob
import torch
import logging
import json
import random
import numpy as np
import pandas as pd
from contextlib import contextmanager
from collections import namedtuple, defaultdict
from tempfile import TemporaryDirectory
import numba.cuda as profile_cuda
from tqdm import tqdm
from tensorboardX import SummaryWriter
from torch.utils.data import DataLoader, Dataset, RandomSampler
from torch.utils.data.distributed import DistributedSampler
from pytorch_transformers.modeling_bert import BertForPreTraining
from pytorch_transformers.tokenization_bert import BertTokenizer
from pytorch_transformers.optimization import AdamW, WarmupLinearSchedule
try:
from apex.parallel import DistributedDataParallel as DDP
from apex.optimizers import FP16_Optimizer
from apex.optimizers import FusedAdam
except ImportError:
raise ImportError(
"Please install apex from https://www.github.com/nvidia/apex to use distributed and fp16 training.")
from utils import Timers
InputFeatures = namedtuple("InputFeatures", "input_ids input_mask segment_ids lm_label_ids is_next")
log_format = '%(asctime)-10s: %(message)s'
logging.basicConfig(level=logging.INFO, format=log_format)
def check_files(checkpoint_path, prefix, max_files=10):
"""
checkFiles
Check the number of checkpoints, if it exceeds max_files, delete the oldest ones,
return the latest checkpoint file path.
checkpoint_path: str, path to checkpoints
max_files: int, maximum number of checkpoints to retain
"""
try:
pattern = os.path.join(checkpoint_path, prefix + "*.tar")
checkpoint_files = glob.glob(pattern)
checkpoint_files.sort(key=lambda x: os.path.getmtime(x))
except FileNotFoundError:
return None
try:
latest_checkpoint = checkpoint_files[-1]
except IndexError:
# No checkpoint files, list is empty!
latest_checkpoint = None
print("CURRENTLY %d CHECKPOINTS" % len(checkpoint_files))
if len(checkpoint_files) > max_files:
logging.info("DELETE EXCESS CHECKPOINTS")
for idx, checkpoint_file in enumerate(checkpoint_files[:-max_files]):
if checkpoint_file=='training_checkpoint_most_recent.tar':continue
logging.info("DELETE %s" % checkpoint_file)
os.remove(checkpoint_file)
return latest_checkpoint
def save_checkpoint(model, optimizer, epoch, global_step, checkpoint_path, filename):
"""
saveCheckpoint
Save the model and optimizer state in a dictionary
model: [class], torch model instance
optimizer: [class], torch optimizer instance
epoch: int, current epoch
global_step: int, current global step
checkpoint_path: string, path
filename: string, name of the checkpoint file
"""
logging.info("** ** * Saving fine-tuned model ** ** * ")
if not os.path.exists(checkpoint_path):
os.makedirs(checkpoint_path, exist_ok=True)
torch.save({"epoch": epoch,
"model_state_dict": model.state_dict(),
"optimizer_state_dict": optimizer.state_dict(),
"global_step": global_step}, filename)
logging.info("** ** * Model saved! ** ** * ")
def restore_checkpoint(model, optimizer, checkpoint_file, device):
"""
Restores model and optimizer from a checkpoint file and returns checkpoint information.
Has side effect of loading the state_dict for model and optimizer (i.e. modifies the instances).
:param model: [class], torch model instance
:param optimizer: [class], torch optimizer instance
:param checkpoint_file: string, full file path
:param device: [class], torch device instance
:return: Tuple of the checkpoint values
"""
assert checkpoint_file
logging.info("** ** * Restore from checkpoint: %s" % checkpoint_file)
checkpoint_state = torch.load(checkpoint_file, map_location=device)
model.load_state_dict(checkpoint_state["model_state_dict"])
optimizer.load_state_dict(checkpoint_state["optimizer_state_dict"])
last_epoch = checkpoint_state["epoch"]
global_step = checkpoint_state["global_step"]
logging.info(" RESTORED AT epoch:%d-%s, global_step:%d" % (last_epoch, global_step))
logging.info("** ** * Model restored! ** ** * ")
# model.train() # Do this in calling code for now, maybe want model.eval() there instead
return last_epoch, global_step
def convert_example_to_features(example, tokenizer, max_seq_length):
tokens = example["tokens"]
segment_ids = example["segment_ids"]
is_random_next = example["is_random_next"]
masked_lm_positions = example["masked_lm_positions"]
masked_lm_labels = example["masked_lm_labels"]
assert len(tokens) == len(segment_ids) <= max_seq_length # The preprocessed data should be already truncated
input_ids = tokenizer.convert_tokens_to_ids(tokens)
masked_label_ids = tokenizer.convert_tokens_to_ids(masked_lm_labels)
input_array = np.zeros(max_seq_length, dtype=np.int)
input_array[:len(input_ids)] = input_ids
mask_array = np.zeros(max_seq_length, dtype=np.bool)
mask_array[:len(input_ids)] = 1
segment_array = np.zeros(max_seq_length, dtype=np.bool)
segment_array[:len(segment_ids)] = segment_ids
lm_label_array = np.full(max_seq_length, dtype=np.int, fill_value=-1)
lm_label_array[masked_lm_positions] = masked_label_ids
features = InputFeatures(input_ids=input_array,
input_mask=mask_array,
segment_ids=segment_array,
lm_label_ids=lm_label_array,
is_next=is_random_next)
return features
class PregeneratedDataset(Dataset):
def __init__(self, training_path, epoch, chunk, tokenizer, num_data_epochs, reduce_memory=False):
self.vocab = tokenizer.vocab
self.tokenizer = tokenizer
self.epoch = epoch
self.data_epoch = epoch % num_data_epochs
data_file = training_path / f"epoch_{self.data_epoch}-{chunk}.json"
data_zip = training_path / f"epoch_{self.data_epoch}-{chunk}.zip"
if not os.path.isfile(data_file):
# If file not there, then there should be a zip file that extracts to it
extract_zip(data_zip)
assert os.path.isfile(data_file)
logging.info('Training on: {}'.format(data_file))
metrics_file = training_path / f"metrics_epoch_{self.data_epoch}-{chunk}.json"
assert data_file.is_file() and metrics_file.is_file()
metrics = json.loads(metrics_file.read_text())
num_samples = metrics['num_training_examples']
seq_len = metrics['max_seq_len']
self.temp_dir = None
self.working_dir = None
if reduce_memory:
self.temp_dir = TemporaryDirectory()
self.working_dir = Path(self.temp_dir.name)
input_ids = np.memmap(filename=self.working_dir/'input_ids.memmap',
mode='w+', dtype=np.int32, shape=(num_samples, seq_len))
input_masks = np.memmap(filename=self.working_dir/'input_masks.memmap',
shape=(num_samples, seq_len), mode='w+', dtype=np.bool)
segment_ids = np.memmap(filename=self.working_dir/'segment_ids.memmap',
shape=(num_samples, seq_len), mode='w+', dtype=np.bool)
lm_label_ids = np.memmap(filename=self.working_dir/'lm_label_ids.memmap',
shape=(num_samples, seq_len), mode='w+', dtype=np.int32)
lm_label_ids[:] = -1
is_nexts = np.memmap(filename=self.working_dir/'is_nexts.memmap',
shape=(num_samples,), mode='w+', dtype=np.bool)
else:
input_ids = np.zeros(shape=(num_samples, seq_len), dtype=np.int32)
input_masks = np.zeros(shape=(num_samples, seq_len), dtype=np.bool)
segment_ids = np.zeros(shape=(num_samples, seq_len), dtype=np.bool)
lm_label_ids = np.full(shape=(num_samples, seq_len), dtype=np.int32, fill_value=-1)
is_nexts = np.zeros(shape=(num_samples,), dtype=np.bool)
logging.info(f"Loading training examples for epoch {epoch}")
with data_file.open() as f:
for i, line in enumerate(tqdm(f, total=num_samples, desc="Training examples")):
line = line.strip()
example = json.loads(line)
features = convert_example_to_features(example, tokenizer, seq_len)
input_ids[i] = features.input_ids
segment_ids[i] = features.segment_ids
input_masks[i] = features.input_mask
lm_label_ids[i] = features.lm_label_ids
is_nexts[i] = features.is_next
assert i == num_samples - 1 # Assert that the sample count metric was true
logging.info("Loading complete!")
self.num_samples = num_samples
self.seq_len = seq_len
self.input_ids = input_ids
self.input_masks = input_masks
self.segment_ids = segment_ids
self.lm_label_ids = lm_label_ids
self.is_nexts = is_nexts
def __len__(self):
return self.num_samples
def __getitem__(self, item):
return (torch.tensor(self.input_ids[item].astype(np.int64)),
torch.tensor(self.input_masks[item].astype(np.int64)),
torch.tensor(self.segment_ids[item].astype(np.int64)),
torch.tensor(self.lm_label_ids[item].astype(np.int64)),
torch.tensor(self.is_nexts[item].astype(np.int64)))
def get_chunks(dir_path, epoch):
"""
Look in the specified directory for files of the form epoch_0-000, epoch_0-001, ...etc.
and return a list of the chunks e.g. ['000', '001', '002', ...]
There could be a mix of .json and .zip files so sometimes we could get duplicates.
"""
if isinstance(dir_path, Path):
dir_path = str(dir_path)
chunks = [x.split('-')[-1].strip('.json').strip('.zip') for x in glob.glob("{}/epoch_{}-*".format(dir_path, epoch))]
chunks = list(set(chunks))
return sorted(chunks)
def get_args():
parser = ArgumentParser()
parser.add_argument('--pregenerated_data', type=Path, required=True)
parser.add_argument('--output_dir', type=Path, required=True)
parser.add_argument('--restore_dir', type=Path, help="Restore from a checkpoint file and continue training")
parser.add_argument("--bert_model", type=str, required=True,
help="Bert pre-trained model selected in the list: bert-base-uncased, "
"bert-large-uncased, bert-base-cased, bert-base-multilingual, bert-base-chinese.")
parser.add_argument("--do_lower_case", action="store_true")
parser.add_argument("--reduce_memory", action="store_true",
help="Store training data as on-disc memmaps to massively reduce memory usage")
parser.add_argument("--epochs", type=int,
default=3, help="Number of epochs to train for")
parser.add_argument("--no_cuda", action='store_true',
help="Whether not to use CUDA when available")
parser.add_argument("--num_workers", type=int,
default=0, help="Number of workers to load data")
# training config
parser.add_argument('--gradient_accumulation_steps', type=int, default=1,
help="Number of updates steps to accumulate before performing a backward/update pass.")
parser.add_argument("--batch_size", default=12, type=int,
help="Total batch size for training.")
parser.add_argument("--seq_length", default=128, type=int,
help="Seq length of each sample.")
parser.add_argument('--train_iters', type=int, default=2000,
help='number of iterations per epoch')
# distributed training config
parser.add_argument("--local_rank", type=int, default=-1,
help="local_rank for distributed training on gpus. Passed from distributed launcher")
# AMP config
parser.add_argument('--fp16', action='store_true',
help="Whether to use 16-bit float precision instead of 32-bit")
parser.add_argument('--loss_scale', type=float, default=0,
help="Loss scaling to improve fp16 numeric stability. Only used when fp16 set to True.\n"
"0 (default value): dynamic loss scaling.\n"
"Positive power of 2: static loss scaling value.\n")
# optimization
parser.add_argument("--warmup_steps", default=0, type=int,
help="Linear warmup over warmup_steps.")
parser.add_argument("--adam_epsilon", default=1e-8, type=float,
help="Epsilon for Adam optimizer.")
parser.add_argument("--learning_rate", default=5e-5, type=float,
help="The initial learning rate for Adam.")
parser.add_argument('--seed', type=int, default=42,
help="random seed for initialization")
# nvprof args
parser.add_argument('--nvprof', action='store_true',
help='profile this program')
parser.add_argument('--profile_start', type=int, default=200,
help="""Start iteration of nvidia profiler""")
parser.add_argument('--profile_stop', type=int, default=201,
help="""Stop iteration of nvidia profiler""")
parser.add_argument('--warmup_iter', type=int, default=200,
help="""Start iteration of nvidia profiler""")
# benchmarking args
parser.add_argument('--benchmark', action='store_true',
help='benchmark this program')
parser.add_argument('--benchmark_dir', type=str, default="benchmark_output",
help="""Dir to save benchmark output stats""")
parser.add_argument('--benchmark_start', type=int, default=1000,
help="""Start iteration of nvidia profiler""")
parser.add_argument('--benchmark_stop', type=int, default=2000,
help="""Stop iteration of nvidia profiler""")
parser.add_argument('--benchmark_partition', type=str, default="t4",
help="""Partition of gpus""")
parser.add_argument('--log_interval', type=int, default=100,
help='report interval')
args = parser.parse_args()
assert args.pregenerated_data.is_dir(), \
"--pregenerated_data should point to the folder of files made by pregenerate_training_data.py!"
args.rank = int(os.getenv('RANK', '0'))
args.world_size = int(os.getenv("WORLD_SIZE", '1'))
return args
def main():
args = get_args()
total_train_examples = 0
for i in range(args.epochs):
chunks = get_chunks(args.pregenerated_data, i)
if i == 0 and len(chunks) == 0:
exit("No training data was found!")
elif len(chunks) == 0:
print(f"Warning! There are fewer epochs of pregenerated data ({i}) than training epochs ({args.epochs}).")
print("This script will loop over the available data, but training diversity may be negatively impacted.")
num_data_epochs = i
break
for chunk in chunks:
epoch_file = args.pregenerated_data / f"epoch_{i}-{chunk}.json"
epoch_zip = args.pregenerated_data / f"epoch_{i}-{chunk}.zip"
metrics_file = args.pregenerated_data / f"metrics_epoch_{i}-{chunk}.json"
if (epoch_file.is_file() or epoch_zip.is_file()) and metrics_file.is_file():
metrics = json.loads(metrics_file.read_text())
total_train_examples += metrics['num_training_examples']
else:
num_data_epochs = args.epochs
if args.local_rank == -1 or args.no_cuda:
device = torch.device("cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu")
n_gpu = torch.cuda.device_count()
else:
torch.cuda.set_device(args.local_rank)
device = torch.device("cuda", args.local_rank)
n_gpu = 1
init_method = 'tcp://'
master_ip = os.getenv('MASTER_ADDR', 'localhost')
master_port = os.getenv('MASTER_PORT', '6000')
init_method += master_ip + ':' + master_port
torch.distributed.init_process_group(
backend='nccl',
world_size=args.world_size,
rank=args.rank,
init_method=init_method)
# Initializes the distributed backend which will take care of sychronizing nodes/GPUs
# torch.distributed.init_process_group(backend='nccl')
logging.info("device: {} n_gpu: {}, distributed training: {}, 16-bits training: {}".format(
device, n_gpu, bool(args.local_rank != -1), args.fp16))
if args.gradient_accumulation_steps < 1:
raise ValueError("Invalid gradient_accumulation_steps parameter: {}, should be >= 1".format(
args.gradient_accumulation_steps))
# args.batch_size = args.batch_size // args.gradient_accumulation_steps
print("CUDA device count: {}".format(torch.cuda.device_count()))
random.seed(args.seed)
np.random.seed(args.seed)
torch.manual_seed(args.seed)
if n_gpu > 0:
torch.cuda.manual_seed_all(args.seed)
if args.output_dir.is_dir() and list(args.output_dir.iterdir()):
logging.warning(f"Output directory ({args.output_dir}) already exists and is not empty!")
args.output_dir.mkdir(parents=True, exist_ok=True)
tokenizer = BertTokenizer.from_pretrained(args.bert_model, do_lower_case=args.do_lower_case)
num_train_optimization_steps = int(
total_train_examples / args.batch_size)
if args.local_rank != -1:
num_train_optimization_steps = num_train_optimization_steps // args.world_size
model = BertForPreTraining.from_pretrained(args.bert_model)
if args.fp16:
model.half()
model.to(device)
if args.local_rank != -1:
model = DDP(model)
elif n_gpu > 1:
model = torch.nn.DataParallel(model)
# Prepare optimizer
param_optimizer = list(model.named_parameters())
no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight']
optimizer_grouped_parameters = [
{'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)],
'weight_decay': 0.01},
{'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)], 'weight_decay': 0.0}
]
if args.fp16:
optimizer = FusedAdam(optimizer_grouped_parameters,
lr=args.learning_rate,
bias_correction=False,
max_grad_norm=1.0)
if args.loss_scale == 0:
optimizer = FP16_Optimizer(optimizer, dynamic_loss_scale=True)
else:
optimizer = FP16_Optimizer(optimizer, static_loss_scale=args.loss_scale)
else:
optimizer = AdamW(optimizer_grouped_parameters, lr=args.learning_rate, eps=args.adam_epsilon)
# scheduler not compatible with APEX::FP16_optimizer
scheduler = WarmupLinearSchedule(optimizer, warmup_steps=args.warmup_steps, t_total=num_train_optimization_steps)
if args.output_dir:
last_checkpoint = check_files(args.output_dir, args.bert_model)
last_epoch, global_step = restore_checkpoint(model, optimizer, last_checkpoint, device)
else:
last_epoch, global_step = 0, 0
logging.info("***** Running training *****")
logging.info(f" Num examples = {total_train_examples}")
logging.info(" Batch size = %d", args.batch_size)
logging.info(" Num steps = %d", num_train_optimization_steps)
iteration = 0
benchmark_stats = defaultdict(lambda: [])
grad_stats = defaultdict(lambda: [])
summary_writer = SummaryWriter() if args.rank == 0 else None
model.train()
for epoch in range(last_epoch, args.epochs):
shuffled_chunks = get_chunks(args.pregenerated_data, epoch)
random.shuffle(shuffled_chunks)
logging.info('New shuffled chunks: {}'.format(shuffled_chunks))
for chunk in shuffled_chunks:
epoch_dataset = PregeneratedDataset(epoch=epoch, chunk=chunk, training_path=args.pregenerated_data, tokenizer=tokenizer,
num_data_epochs=num_data_epochs, reduce_memory=args.reduce_memory)
if args.local_rank == -1:
train_sampler = RandomSampler(epoch_dataset)
else:
train_sampler = DistributedSampler(epoch_dataset)
train_dataloader = DataLoader(epoch_dataset, sampler=train_sampler, batch_size=args.batch_size, num_workers=args.num_workers)
data_iterator = iter(train_dataloader)
timers = Timers()
timers('interval time').start()
tr_loss = 0
nb_tr_examples, nb_tr_steps = 0, 0
for batch in data_iterator:
# while iteration < args.train_iters:
if args.nvprof:
if iteration == args.profile_start:
profile_cuda.profile_start()
print("CUDA profiling starts!")
if iteration == args.profile_stop:
profile_cuda.profile_stop()
print("CUDA profiling stops!")
iteration += 1
# benchmark dataloading time
# batch = next(data_iterator)
batch = tuple(t.to(device) for t in batch)
input_ids, input_mask, segment_ids, lm_label_ids, is_next = batch
outputs = model(input_ids, segment_ids, input_mask, lm_label_ids, is_next)
loss = outputs[0]
if n_gpu > 1:
loss = loss.mean() # mean() to average on multi-gpu.
if args.gradient_accumulation_steps > 1:
# loss = loss / args.gradient_accumulation_steps
if args.local_rank != -1:
if iteration % args.gradient_accumulation_steps == 0:
# we are using APEX DDP => enable_allreduce / disable_allreduce
# print("iteration {}, all reduce enabled!".format(iteration))
model.enable_allreduce()
else:
# print("iteration {}, all reduce disabled!".format(iteration))
model.disable_allreduce()
# note that loss.backward accumulates the gradient => gradient will be accumulated until we call zero_grad
if args.fp16:
optimizer.backward(loss)
else:
loss.backward()
tr_loss += loss.item()
nb_tr_examples += input_ids.size(0)
nb_tr_steps += 1
# mean_loss = tr_loss * args.gradient_accumulation_steps / nb_tr_steps
mean_loss = tr_loss / nb_tr_steps
if iteration % args.gradient_accumulation_steps == 0:
start = time.time()
scheduler.step() # Update learning rate schedule (commented as lr_scheduler not compatible with FP16_Optimizer)
optimizer.step()
optimizer.zero_grad()
benchmark_stats['weight_update_time'].append(time.time() - start) # unit in s
global_step += 1
if iteration % args.log_interval == 0:
elapsed_time = timers('interval time').elapsed()
log_string = ' epoch{:2d} |'.format(epoch)
log_string += ' iteration {:8d} |'.format(iteration)
log_string += ' elapsed time per iteration (ms): {:.1f} |'.format(elapsed_time * 1000.0 / args.log_interval)
log_string += ' mean loss {:.3E} |'.format(mean_loss)
if args.rank == 0:
summary_writer.add_scalar('mean_loss', mean_loss, iteration)
# args.rank == 0 => this is master process
if args.benchmark and args.rank == 0:
if args.benchmark_start < iteration <= args.benchmark_stop:
benchmark_stats['iteration'].append(iteration)
benchmark_stats['seq_length'].append(args.seq_length)
benchmark_stats['batch_size'].append(args.batch_size * args.world_size)
benchmark_stats['num_tokens'].append(args.seq_length * args.batch_size * args.world_size)
benchmark_stats['elapsed_time'].append(elapsed_time)
benchmark_stats['log_interval'].append(args.log_interval)
print(log_string, flush=True)
# Save a trained model
if n_gpu > 1 and torch.distributed.get_rank() or n_gpu <=1:
logging.info("** ** * Saving fine-tuned model ** ** * ")
model_to_save = model.module if hasattr(model, 'module') else model # Take care of distributed/parallel training
save_checkpoint(
model,
optimizer,
epoch,
global_step,
args.output_dir,
os.path.join(args.output_dir, "{}_{}.tar".format(args.bert_model, global_step))
)
model_to_save.save_pretrained(args.output_dir)
tokenizer.save_pretrained(args.output_dir)
# Save a trained model
if n_gpu > 1 and torch.distributed.get_rank() == 0 or n_gpu <=1:
logging.info("** ** * Saving fine-tuned model ** ** * ")
model_to_save = model.module if hasattr(model, 'module') else model # Take care of distributed/parallel training
save_checkpoint(
model,
optimizer,
epoch,
global_step,
args.output_dir,
os.path.join(args.output_dir, "{}_{}.tar".format(args.bert_model, global_step))
)
model_to_save.save_pretrained(args.output_dir)
tokenizer.save_pretrained(args.output_dir)
if args.rank == 0:
summary_writer.close()
if args.benchmark and args.rank == 0:
benchmark_csv = {
k: [np.mean(l)] for k,l in benchmark_stats.items()
}
benchmark_csv['weight_update_time'] = args.log_interval * np.array(benchmark_csv['weight_update_time'])
benchmark_csv['token_throughput'] = np.array(benchmark_csv['num_tokens']) * np.array(benchmark_csv['log_interval'])\
/ np.array(benchmark_csv['elapsed_time'])
benchmark_csv['precision'] = [ 'fp16' if args.fp16 else 'fp32' ]
save_dir = os.path.join(
args.benchmark_dir,
"{gpus}_gpus_{partition}_trials".format(
gpus=args.world_size,
partition=args.benchmark_partition
)
)
if not os.path.exists(save_dir):
os.mkdir(save_dir)
df = pd.DataFrame.from_dict(benchmark_csv)
df.to_csv(os.path.join(
save_dir,
"huggingface_benchmark_{partition}_batch_size_{batch_size}_seq_len_{seq_len}.csv".format(
partition=args.benchmark_partition,
batch_size=args.batch_size,
seq_len=args.seq_length
)
))
if __name__ == '__main__':
main()
| [
"torch.cuda.device_count",
"numpy.array",
"torch.utils.data.distributed.DistributedSampler",
"torch.cuda.is_available",
"pytorch_transformers.modeling_bert.BertForPreTraining.from_pretrained",
"utils.Timers",
"torch.distributed.get_rank",
"logging.info",
"os.remove",
"os.path.exists",
"numpy.mea... | [((1091, 1179), 'collections.namedtuple', 'namedtuple', (['"""InputFeatures"""', '"""input_ids input_mask segment_ids lm_label_ids is_next"""'], {}), "('InputFeatures',\n 'input_ids input_mask segment_ids lm_label_ids is_next')\n", (1101, 1179), False, 'from collections import namedtuple, defaultdict\n'), ((1220, 1278), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO', 'format': 'log_format'}), '(level=logging.INFO, format=log_format)\n', (1239, 1278), False, 'import logging\n'), ((2865, 2921), 'logging.info', 'logging.info', (['"""** ** * Saving fine-tuned model ** ** * """'], {}), "('** ** * Saving fine-tuned model ** ** * ')\n", (2877, 2921), False, 'import logging\n'), ((3231, 3276), 'logging.info', 'logging.info', (['"""** ** * Model saved! ** ** * """'], {}), "('** ** * Model saved! ** ** * ')\n", (3243, 3276), False, 'import logging\n'), ((3835, 3904), 'logging.info', 'logging.info', (["('** ** * Restore from checkpoint: %s' % checkpoint_file)"], {}), "('** ** * Restore from checkpoint: %s' % checkpoint_file)\n", (3847, 3904), False, 'import logging\n'), ((3928, 3976), 'torch.load', 'torch.load', (['checkpoint_file'], {'map_location': 'device'}), '(checkpoint_file, map_location=device)\n', (3938, 3976), False, 'import torch\n'), ((4211, 4300), 'logging.info', 'logging.info', (["(' RESTORED AT epoch:%d-%s, global_step:%d' % (last_epoch, global_step))"], {}), "(' RESTORED AT epoch:%d-%s, global_step:%d' % (last_epoch,\n global_step))\n", (4223, 4300), False, 'import logging\n'), ((4301, 4349), 'logging.info', 'logging.info', (['"""** ** * Model restored! ** ** * """'], {}), "('** ** * Model restored! ** ** * ')\n", (4313, 4349), False, 'import logging\n'), ((5042, 5080), 'numpy.zeros', 'np.zeros', (['max_seq_length'], {'dtype': 'np.int'}), '(max_seq_length, dtype=np.int)\n', (5050, 5080), True, 'import numpy as np\n'), ((5144, 5183), 'numpy.zeros', 'np.zeros', (['max_seq_length'], {'dtype': 'np.bool'}), '(max_seq_length, dtype=np.bool)\n', (5152, 5183), True, 'import numpy as np\n'), ((5241, 5280), 'numpy.zeros', 'np.zeros', (['max_seq_length'], {'dtype': 'np.bool'}), '(max_seq_length, dtype=np.bool)\n', (5249, 5280), True, 'import numpy as np\n'), ((5354, 5406), 'numpy.full', 'np.full', (['max_seq_length'], {'dtype': 'np.int', 'fill_value': '(-1)'}), '(max_seq_length, dtype=np.int, fill_value=-1)\n', (5361, 5406), True, 'import numpy as np\n'), ((10291, 10307), 'argparse.ArgumentParser', 'ArgumentParser', ([], {}), '()\n', (10305, 10307), False, 'from argparse import ArgumentParser\n'), ((17378, 17400), 'random.seed', 'random.seed', (['args.seed'], {}), '(args.seed)\n', (17389, 17400), False, 'import random\n'), ((17405, 17430), 'numpy.random.seed', 'np.random.seed', (['args.seed'], {}), '(args.seed)\n', (17419, 17430), True, 'import numpy as np\n'), ((17435, 17463), 'torch.manual_seed', 'torch.manual_seed', (['args.seed'], {}), '(args.seed)\n', (17452, 17463), False, 'import torch\n'), ((17768, 17853), 'pytorch_transformers.tokenization_bert.BertTokenizer.from_pretrained', 'BertTokenizer.from_pretrained', (['args.bert_model'], {'do_lower_case': 'args.do_lower_case'}), '(args.bert_model, do_lower_case=args.do_lower_case\n )\n', (17797, 17853), False, 'from pytorch_transformers.tokenization_bert import BertTokenizer\n'), ((18068, 18119), 'pytorch_transformers.modeling_bert.BertForPreTraining.from_pretrained', 'BertForPreTraining.from_pretrained', (['args.bert_model'], {}), '(args.bert_model)\n', (18102, 18119), False, 'from pytorch_transformers.modeling_bert import BertForPreTraining\n'), ((19342, 19448), 'pytorch_transformers.optimization.WarmupLinearSchedule', 'WarmupLinearSchedule', (['optimizer'], {'warmup_steps': 'args.warmup_steps', 't_total': 'num_train_optimization_steps'}), '(optimizer, warmup_steps=args.warmup_steps, t_total=\n num_train_optimization_steps)\n', (19362, 19448), False, 'from pytorch_transformers.optimization import AdamW, WarmupLinearSchedule\n'), ((19691, 19735), 'logging.info', 'logging.info', (['"""***** Running training *****"""'], {}), "('***** Running training *****')\n", (19703, 19735), False, 'import logging\n'), ((19740, 19796), 'logging.info', 'logging.info', (['f""" Num examples = {total_train_examples}"""'], {}), "(f' Num examples = {total_train_examples}')\n", (19752, 19796), False, 'import logging\n'), ((19801, 19851), 'logging.info', 'logging.info', (['""" Batch size = %d"""', 'args.batch_size'], {}), "(' Batch size = %d', args.batch_size)\n", (19813, 19851), False, 'import logging\n'), ((19856, 19918), 'logging.info', 'logging.info', (['""" Num steps = %d"""', 'num_train_optimization_steps'], {}), "(' Num steps = %d', num_train_optimization_steps)\n", (19868, 19918), False, 'import logging\n'), ((19961, 19985), 'collections.defaultdict', 'defaultdict', (['(lambda : [])'], {}), '(lambda : [])\n', (19972, 19985), False, 'from collections import namedtuple, defaultdict\n'), ((20002, 20026), 'collections.defaultdict', 'defaultdict', (['(lambda : [])'], {}), '(lambda : [])\n', (20013, 20026), False, 'from collections import namedtuple, defaultdict\n'), ((1630, 1677), 'os.path.join', 'os.path.join', (['checkpoint_path', "(prefix + '*.tar')"], {}), "(checkpoint_path, prefix + '*.tar')\n", (1642, 1677), False, 'import os\n'), ((1705, 1723), 'glob.glob', 'glob.glob', (['pattern'], {}), '(pattern)\n', (1714, 1723), False, 'import glob\n'), ((2113, 2154), 'logging.info', 'logging.info', (['"""DELETE EXCESS CHECKPOINTS"""'], {}), "('DELETE EXCESS CHECKPOINTS')\n", (2125, 2154), False, 'import logging\n'), ((2934, 2965), 'os.path.exists', 'os.path.exists', (['checkpoint_path'], {}), '(checkpoint_path)\n', (2948, 2965), False, 'import os\n'), ((2975, 3018), 'os.makedirs', 'os.makedirs', (['checkpoint_path'], {'exist_ok': '(True)'}), '(checkpoint_path, exist_ok=True)\n', (2986, 3018), False, 'import os\n'), ((8278, 8338), 'logging.info', 'logging.info', (['f"""Loading training examples for epoch {epoch}"""'], {}), "(f'Loading training examples for epoch {epoch}')\n", (8290, 8338), False, 'import logging\n'), ((8982, 9015), 'logging.info', 'logging.info', (['"""Loading complete!"""'], {}), "('Loading complete!')\n", (8994, 9015), False, 'import logging\n'), ((14806, 14828), 'os.getenv', 'os.getenv', (['"""RANK"""', '"""0"""'], {}), "('RANK', '0')\n", (14815, 14828), False, 'import os\n'), ((14856, 14884), 'os.getenv', 'os.getenv', (['"""WORLD_SIZE"""', '"""1"""'], {}), "('WORLD_SIZE', '1')\n", (14865, 14884), False, 'import os\n'), ((16166, 16191), 'torch.cuda.device_count', 'torch.cuda.device_count', ([], {}), '()\n', (16189, 16191), False, 'import torch\n'), ((16210, 16248), 'torch.cuda.set_device', 'torch.cuda.set_device', (['args.local_rank'], {}), '(args.local_rank)\n', (16231, 16248), False, 'import torch\n'), ((16266, 16303), 'torch.device', 'torch.device', (['"""cuda"""', 'args.local_rank'], {}), "('cuda', args.local_rank)\n", (16278, 16303), False, 'import torch\n'), ((16373, 16410), 'os.getenv', 'os.getenv', (['"""MASTER_ADDR"""', '"""localhost"""'], {}), "('MASTER_ADDR', 'localhost')\n", (16382, 16410), False, 'import os\n'), ((16433, 16465), 'os.getenv', 'os.getenv', (['"""MASTER_PORT"""', '"""6000"""'], {}), "('MASTER_PORT', '6000')\n", (16442, 16465), False, 'import os\n'), ((16527, 16653), 'torch.distributed.init_process_group', 'torch.distributed.init_process_group', ([], {'backend': '"""nccl"""', 'world_size': 'args.world_size', 'rank': 'args.rank', 'init_method': 'init_method'}), "(backend='nccl', world_size=args.\n world_size, rank=args.rank, init_method=init_method)\n", (16563, 16653), False, 'import torch\n'), ((17490, 17527), 'torch.cuda.manual_seed_all', 'torch.cuda.manual_seed_all', (['args.seed'], {}), '(args.seed)\n', (17516, 17527), False, 'import torch\n'), ((17606, 17700), 'logging.warning', 'logging.warning', (['f"""Output directory ({args.output_dir}) already exists and is not empty!"""'], {}), "(\n f'Output directory ({args.output_dir}) already exists and is not empty!')\n", (17621, 17700), False, 'import logging\n'), ((18226, 18236), 'apex.parallel.DistributedDataParallel', 'DDP', (['model'], {}), '(model)\n', (18229, 18236), True, 'from apex.parallel import DistributedDataParallel as DDP\n'), ((18755, 18863), 'apex.optimizers.FusedAdam', 'FusedAdam', (['optimizer_grouped_parameters'], {'lr': 'args.learning_rate', 'bias_correction': '(False)', 'max_grad_norm': '(1.0)'}), '(optimizer_grouped_parameters, lr=args.learning_rate,\n bias_correction=False, max_grad_norm=1.0)\n', (18764, 18863), False, 'from apex.optimizers import FusedAdam\n'), ((19187, 19273), 'pytorch_transformers.optimization.AdamW', 'AdamW', (['optimizer_grouped_parameters'], {'lr': 'args.learning_rate', 'eps': 'args.adam_epsilon'}), '(optimizer_grouped_parameters, lr=args.learning_rate, eps=args.\n adam_epsilon)\n', (19192, 19273), False, 'from pytorch_transformers.optimization import AdamW, WarmupLinearSchedule\n'), ((20047, 20062), 'tensorboardX.SummaryWriter', 'SummaryWriter', ([], {}), '()\n', (20060, 20062), False, 'from tensorboardX import SummaryWriter\n'), ((20235, 20266), 'random.shuffle', 'random.shuffle', (['shuffled_chunks'], {}), '(shuffled_chunks)\n', (20249, 20266), False, 'import random\n'), ((27515, 27552), 'pandas.DataFrame.from_dict', 'pd.DataFrame.from_dict', (['benchmark_csv'], {}), '(benchmark_csv)\n', (27537, 27552), True, 'import pandas as pd\n'), ((2324, 2367), 'logging.info', 'logging.info', (["('DELETE %s' % checkpoint_file)"], {}), "('DELETE %s' % checkpoint_file)\n", (2336, 2367), False, 'import logging\n'), ((2380, 2406), 'os.remove', 'os.remove', (['checkpoint_file'], {}), '(checkpoint_file)\n', (2389, 2406), False, 'import os\n'), ((6214, 6239), 'os.path.isfile', 'os.path.isfile', (['data_file'], {}), '(data_file)\n', (6228, 6239), False, 'import os\n'), ((6379, 6404), 'os.path.isfile', 'os.path.isfile', (['data_file'], {}), '(data_file)\n', (6393, 6404), False, 'import os\n'), ((6880, 6900), 'tempfile.TemporaryDirectory', 'TemporaryDirectory', ([], {}), '()\n', (6898, 6900), False, 'from tempfile import TemporaryDirectory\n'), ((6932, 6956), 'pathlib.Path', 'Path', (['self.temp_dir.name'], {}), '(self.temp_dir.name)\n', (6936, 6956), False, 'from pathlib import Path\n'), ((6981, 7100), 'numpy.memmap', 'np.memmap', ([], {'filename': "(self.working_dir / 'input_ids.memmap')", 'mode': '"""w+"""', 'dtype': 'np.int32', 'shape': '(num_samples, seq_len)'}), "(filename=self.working_dir / 'input_ids.memmap', mode='w+', dtype=\n np.int32, shape=(num_samples, seq_len))\n", (6990, 7100), True, 'import numpy as np\n'), ((7154, 7274), 'numpy.memmap', 'np.memmap', ([], {'filename': "(self.working_dir / 'input_masks.memmap')", 'shape': '(num_samples, seq_len)', 'mode': '"""w+"""', 'dtype': 'np.bool'}), "(filename=self.working_dir / 'input_masks.memmap', shape=(\n num_samples, seq_len), mode='w+', dtype=np.bool)\n", (7163, 7274), True, 'import numpy as np\n'), ((7330, 7450), 'numpy.memmap', 'np.memmap', ([], {'filename': "(self.working_dir / 'segment_ids.memmap')", 'shape': '(num_samples, seq_len)', 'mode': '"""w+"""', 'dtype': 'np.bool'}), "(filename=self.working_dir / 'segment_ids.memmap', shape=(\n num_samples, seq_len), mode='w+', dtype=np.bool)\n", (7339, 7450), True, 'import numpy as np\n'), ((7507, 7629), 'numpy.memmap', 'np.memmap', ([], {'filename': "(self.working_dir / 'lm_label_ids.memmap')", 'shape': '(num_samples, seq_len)', 'mode': '"""w+"""', 'dtype': 'np.int32'}), "(filename=self.working_dir / 'lm_label_ids.memmap', shape=(\n num_samples, seq_len), mode='w+', dtype=np.int32)\n", (7516, 7629), True, 'import numpy as np\n'), ((7716, 7825), 'numpy.memmap', 'np.memmap', ([], {'filename': "(self.working_dir / 'is_nexts.memmap')", 'shape': '(num_samples,)', 'mode': '"""w+"""', 'dtype': 'np.bool'}), "(filename=self.working_dir / 'is_nexts.memmap', shape=(num_samples\n ,), mode='w+', dtype=np.bool)\n", (7725, 7825), True, 'import numpy as np\n'), ((7890, 7944), 'numpy.zeros', 'np.zeros', ([], {'shape': '(num_samples, seq_len)', 'dtype': 'np.int32'}), '(shape=(num_samples, seq_len), dtype=np.int32)\n', (7898, 7944), True, 'import numpy as np\n'), ((7971, 8024), 'numpy.zeros', 'np.zeros', ([], {'shape': '(num_samples, seq_len)', 'dtype': 'np.bool'}), '(shape=(num_samples, seq_len), dtype=np.bool)\n', (7979, 8024), True, 'import numpy as np\n'), ((8051, 8104), 'numpy.zeros', 'np.zeros', ([], {'shape': '(num_samples, seq_len)', 'dtype': 'np.bool'}), '(shape=(num_samples, seq_len), dtype=np.bool)\n', (8059, 8104), True, 'import numpy as np\n'), ((8132, 8200), 'numpy.full', 'np.full', ([], {'shape': '(num_samples, seq_len)', 'dtype': 'np.int32', 'fill_value': '(-1)'}), '(shape=(num_samples, seq_len), dtype=np.int32, fill_value=-1)\n', (8139, 8200), True, 'import numpy as np\n'), ((8224, 8269), 'numpy.zeros', 'np.zeros', ([], {'shape': '(num_samples,)', 'dtype': 'np.bool'}), '(shape=(num_samples,), dtype=np.bool)\n', (8232, 8269), True, 'import numpy as np\n'), ((17345, 17370), 'torch.cuda.device_count', 'torch.cuda.device_count', ([], {}), '()\n', (17368, 17370), False, 'import torch\n'), ((18273, 18301), 'torch.nn.DataParallel', 'torch.nn.DataParallel', (['model'], {}), '(model)\n', (18294, 18301), False, 'import torch\n'), ((19007, 19057), 'apex.optimizers.FP16_Optimizer', 'FP16_Optimizer', (['optimizer'], {'dynamic_loss_scale': '(True)'}), '(optimizer, dynamic_loss_scale=True)\n', (19021, 19057), False, 'from apex.optimizers import FP16_Optimizer\n'), ((19096, 19156), 'apex.optimizers.FP16_Optimizer', 'FP16_Optimizer', (['optimizer'], {'static_loss_scale': 'args.loss_scale'}), '(optimizer, static_loss_scale=args.loss_scale)\n', (19110, 19156), False, 'from apex.optimizers import FP16_Optimizer\n'), ((20849, 20959), 'torch.utils.data.DataLoader', 'DataLoader', (['epoch_dataset'], {'sampler': 'train_sampler', 'batch_size': 'args.batch_size', 'num_workers': 'args.num_workers'}), '(epoch_dataset, sampler=train_sampler, batch_size=args.batch_size,\n num_workers=args.num_workers)\n', (20859, 20959), False, 'from torch.utils.data import DataLoader, Dataset, RandomSampler\n'), ((21028, 21036), 'utils.Timers', 'Timers', ([], {}), '()\n', (21034, 21036), False, 'from utils import Timers\n'), ((26034, 26090), 'logging.info', 'logging.info', (['"""** ** * Saving fine-tuned model ** ** * """'], {}), "('** ** * Saving fine-tuned model ** ** * ')\n", (26046, 26090), False, 'import logging\n'), ((26874, 26919), 'numpy.array', 'np.array', (["benchmark_csv['weight_update_time']"], {}), "(benchmark_csv['weight_update_time'])\n", (26882, 26919), True, 'import numpy as np\n'), ((27084, 27123), 'numpy.array', 'np.array', (["benchmark_csv['elapsed_time']"], {}), "(benchmark_csv['elapsed_time'])\n", (27092, 27123), True, 'import numpy as np\n'), ((27445, 27469), 'os.path.exists', 'os.path.exists', (['save_dir'], {}), '(save_dir)\n', (27459, 27469), False, 'import os\n'), ((27483, 27501), 'os.mkdir', 'os.mkdir', (['save_dir'], {}), '(save_dir)\n', (27491, 27501), False, 'import os\n'), ((8412, 8464), 'tqdm.tqdm', 'tqdm', (['f'], {'total': 'num_samples', 'desc': '"""Training examples"""'}), "(f, total=num_samples, desc='Training examples')\n", (8416, 8464), False, 'from tqdm import tqdm\n'), ((8529, 8545), 'json.loads', 'json.loads', (['line'], {}), '(line)\n', (8539, 8545), False, 'import json\n'), ((20705, 20733), 'torch.utils.data.RandomSampler', 'RandomSampler', (['epoch_dataset'], {}), '(epoch_dataset)\n', (20718, 20733), False, 'from torch.utils.data import DataLoader, Dataset, RandomSampler\n'), ((20784, 20817), 'torch.utils.data.distributed.DistributedSampler', 'DistributedSampler', (['epoch_dataset'], {}), '(epoch_dataset)\n', (20802, 20817), False, 'from torch.utils.data.distributed import DistributedSampler\n'), ((25295, 25351), 'logging.info', 'logging.info', (['"""** ** * Saving fine-tuned model ** ** * """'], {}), "('** ** * Saving fine-tuned model ** ** * ')\n", (25307, 25351), False, 'import logging\n'), ((26751, 26761), 'numpy.mean', 'np.mean', (['l'], {}), '(l)\n', (26758, 26761), True, 'import numpy as np\n'), ((26964, 27001), 'numpy.array', 'np.array', (["benchmark_csv['num_tokens']"], {}), "(benchmark_csv['num_tokens'])\n", (26972, 27001), True, 'import numpy as np\n'), ((27004, 27043), 'numpy.array', 'np.array', (["benchmark_csv['log_interval']"], {}), "(benchmark_csv['log_interval'])\n", (27012, 27043), True, 'import numpy as np\n'), ((1768, 1787), 'os.path.getmtime', 'os.path.getmtime', (['x'], {}), '(x)\n', (1784, 1787), False, 'import os\n'), ((16091, 16116), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (16114, 16116), False, 'import torch\n'), ((23376, 23387), 'time.time', 'time.time', ([], {}), '()\n', (23385, 23387), False, 'import time\n'), ((25236, 25264), 'torch.distributed.get_rank', 'torch.distributed.get_rank', ([], {}), '()\n', (25262, 25264), False, 'import torch\n'), ((25973, 26001), 'torch.distributed.get_rank', 'torch.distributed.get_rank', ([], {}), '()\n', (25999, 26001), False, 'import torch\n'), ((21354, 21382), 'numba.cuda.profile_start', 'profile_cuda.profile_start', ([], {}), '()\n', (21380, 21382), True, 'import numba.cuda as profile_cuda\n'), ((21518, 21545), 'numba.cuda.profile_stop', 'profile_cuda.profile_stop', ([], {}), '()\n', (21543, 21545), True, 'import numba.cuda as profile_cuda\n'), ((23665, 23676), 'time.time', 'time.time', ([], {}), '()\n', (23674, 23676), False, 'import time\n')] |
import pytest
import matplotlib.pyplot as plt
import astropy.units as u
import numpy as np
from ..skySurvey import SkySurvey
# Set up the random number generator.
np.random.seed(1234)
# Local directory:
# "/Users/dk/Data/WHAM/wham-ss-DR1-v161116-170912.fits"
survey = SkySurvey()
BASELINE_DIR = 'baseline'
@pytest.mark.mpl_image_compare(baseline_dir=BASELINE_DIR, tolerance = 20)
def test_basic():
"""
Basic intensity plot
"""
fig = survey.intensity_map()
return fig
@pytest.mark.mpl_image_compare(baseline_dir=BASELINE_DIR, tolerance = 20)
def test_fig_input():
"""
fig kwarg
"""
fig = plt.figure()
return survey.intensity_map(fig = fig)
@pytest.mark.mpl_image_compare(baseline_dir=BASELINE_DIR, tolerance = 20)
def test_ax_input():
"""
ax kwarrg
"""
fig = plt.figure()
ax = fig.add_subplot(111)
return survey.intensity_map(ax = ax)
@pytest.mark.mpl_image_compare(baseline_dir=BASELINE_DIR, tolerance = 20)
def test_ranges():
"""
lrange and brange
"""
lrange = [30,-30]
brange = [-30,30]
return survey.intensity_map(lrange = lrange * u.deg, brange = brange)
@pytest.mark.mpl_image_compare(baseline_dir=BASELINE_DIR, tolerance = 20)
def test_ranges_unit():
"""
lrange and brange
"""
lrange = [30,-30]
brange = [-30,30]
return survey.intensity_map(lrange = lrange, brange = brange*u.deg)
@pytest.mark.mpl_image_compare(baseline_dir=BASELINE_DIR, tolerance = 20)
def test_colorbar():
"""
colorbar
"""
return survey.intensity_map(colorbar = True,
cbar_kwargs = {"orientation":"horizontal"})
@pytest.mark.mpl_image_compare(baseline_dir=BASELINE_DIR, tolerance = 20)
def test_sc():
"""
return_sc test
"""
sc, fig = survey.intensity_map(return_sc = True)
cb = fig.colorbar(sc, orientation = "horizontal")
return fig
@pytest.mark.mpl_image_compare(baseline_dir=BASELINE_DIR, tolerance = 20)
def test_cartopy_stereo():
import cartopy.crs as ccrs
"""
test stereo projection with cartopy
"""
fig = plt.figure()
ax = fig.add_subplot(111, projection = ccrs.Stereographic())
fig = survey.intensity_map(ax = ax, fig = fig, s_factor=2,
lrange = [40,-40], brange = [-20,20])
return fig
@pytest.mark.mpl_image_compare(baseline_dir=BASELINE_DIR, tolerance = 20)
def test_vel_range():
"""
test velocity range input
"""
vel_range = [-20,20]
return survey.intensity_map(vel_range = vel_range)
@pytest.mark.mpl_image_compare(baseline_dir=BASELINE_DIR, tolerance = 20)
def test_vel_range_units():
"""
test velocity range input
"""
vel_range = [-20,20]*u.km/u.s
return survey.intensity_map(vel_range = vel_range)
@pytest.mark.mpl_image_compare(baseline_dir=BASELINE_DIR, tolerance = 20)
def test_basic_smooth():
"""
Basic intensity plot smooth
"""
fig = survey.intensity_map(smooth = True)
return fig
@pytest.mark.mpl_image_compare(baseline_dir=BASELINE_DIR, tolerance = 20)
def test_basic_smooth_lrange():
"""
Basic intensity plot smooth
"""
fig = survey.intensity_map(smooth = True, lrange = [50,-50])
return fig
| [
"cartopy.crs.Stereographic",
"pytest.mark.mpl_image_compare",
"matplotlib.pyplot.figure",
"numpy.random.seed"
] | [((165, 185), 'numpy.random.seed', 'np.random.seed', (['(1234)'], {}), '(1234)\n', (179, 185), True, 'import numpy as np\n'), ((313, 383), 'pytest.mark.mpl_image_compare', 'pytest.mark.mpl_image_compare', ([], {'baseline_dir': 'BASELINE_DIR', 'tolerance': '(20)'}), '(baseline_dir=BASELINE_DIR, tolerance=20)\n', (342, 383), False, 'import pytest\n'), ((495, 565), 'pytest.mark.mpl_image_compare', 'pytest.mark.mpl_image_compare', ([], {'baseline_dir': 'BASELINE_DIR', 'tolerance': '(20)'}), '(baseline_dir=BASELINE_DIR, tolerance=20)\n', (524, 565), False, 'import pytest\n'), ((688, 758), 'pytest.mark.mpl_image_compare', 'pytest.mark.mpl_image_compare', ([], {'baseline_dir': 'BASELINE_DIR', 'tolerance': '(20)'}), '(baseline_dir=BASELINE_DIR, tolerance=20)\n', (717, 758), False, 'import pytest\n'), ((908, 978), 'pytest.mark.mpl_image_compare', 'pytest.mark.mpl_image_compare', ([], {'baseline_dir': 'BASELINE_DIR', 'tolerance': '(20)'}), '(baseline_dir=BASELINE_DIR, tolerance=20)\n', (937, 978), False, 'import pytest\n'), ((1158, 1228), 'pytest.mark.mpl_image_compare', 'pytest.mark.mpl_image_compare', ([], {'baseline_dir': 'BASELINE_DIR', 'tolerance': '(20)'}), '(baseline_dir=BASELINE_DIR, tolerance=20)\n', (1187, 1228), False, 'import pytest\n'), ((1411, 1481), 'pytest.mark.mpl_image_compare', 'pytest.mark.mpl_image_compare', ([], {'baseline_dir': 'BASELINE_DIR', 'tolerance': '(20)'}), '(baseline_dir=BASELINE_DIR, tolerance=20)\n', (1440, 1481), False, 'import pytest\n'), ((1638, 1708), 'pytest.mark.mpl_image_compare', 'pytest.mark.mpl_image_compare', ([], {'baseline_dir': 'BASELINE_DIR', 'tolerance': '(20)'}), '(baseline_dir=BASELINE_DIR, tolerance=20)\n', (1667, 1708), False, 'import pytest\n'), ((1885, 1955), 'pytest.mark.mpl_image_compare', 'pytest.mark.mpl_image_compare', ([], {'baseline_dir': 'BASELINE_DIR', 'tolerance': '(20)'}), '(baseline_dir=BASELINE_DIR, tolerance=20)\n', (1914, 1955), False, 'import pytest\n'), ((2287, 2357), 'pytest.mark.mpl_image_compare', 'pytest.mark.mpl_image_compare', ([], {'baseline_dir': 'BASELINE_DIR', 'tolerance': '(20)'}), '(baseline_dir=BASELINE_DIR, tolerance=20)\n', (2316, 2357), False, 'import pytest\n'), ((2510, 2580), 'pytest.mark.mpl_image_compare', 'pytest.mark.mpl_image_compare', ([], {'baseline_dir': 'BASELINE_DIR', 'tolerance': '(20)'}), '(baseline_dir=BASELINE_DIR, tolerance=20)\n', (2539, 2580), False, 'import pytest\n'), ((2748, 2818), 'pytest.mark.mpl_image_compare', 'pytest.mark.mpl_image_compare', ([], {'baseline_dir': 'BASELINE_DIR', 'tolerance': '(20)'}), '(baseline_dir=BASELINE_DIR, tolerance=20)\n', (2777, 2818), False, 'import pytest\n'), ((2961, 3031), 'pytest.mark.mpl_image_compare', 'pytest.mark.mpl_image_compare', ([], {'baseline_dir': 'BASELINE_DIR', 'tolerance': '(20)'}), '(baseline_dir=BASELINE_DIR, tolerance=20)\n', (2990, 3031), False, 'import pytest\n'), ((630, 642), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (640, 642), True, 'import matplotlib.pyplot as plt\n'), ((822, 834), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (832, 834), True, 'import matplotlib.pyplot as plt\n'), ((2082, 2094), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (2092, 2094), True, 'import matplotlib.pyplot as plt\n'), ((2138, 2158), 'cartopy.crs.Stereographic', 'ccrs.Stereographic', ([], {}), '()\n', (2156, 2158), True, 'import cartopy.crs as ccrs\n')] |
"""
Reads in current year's Arctic sea ice extent from Sea Ice Index 2 (NSIDC)
Website : ftp://sidads.colorado.edu/DATASETS/NOAA/G02135/north/daily/data/
Author : <NAME>
Date : 5 September 2016
"""
### Import modules
import numpy as np
import datetime
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap, addcyclic, shiftgrid
from netCDF4 import Dataset
import cmocean
### Directory and time
directorydata = '/surtsey/zlabe/seaice_obs/PIOMAS/'
directoryfigure = '/home/zlabe/Documents/Projects/Tests/Utilities/Figures/'
now = datetime.datetime.now()
currentmn = str(now.month)
currentdy = str(now.day)
currentyr = str(now.year)
currenttime = currentmn + '_' + currentdy + '_' + currentyr
currentdoy = now.timetuple().tm_yday
### Time
years = np.arange(1979,2010+1,1)
directorydata = '/surtsey/zlabe/seaice_obs/seaice_reconstruct/'
directoryfigure = '/home/zlabe/Documents/Projects/Tests/Utilities/Figures/'
now = datetime.datetime.now()
month = now.month
years = np.arange(1914,2013+1,1)
data = Dataset(directorydata + 'G10010_SIBT1850_v1.1.nc')
lats = data.variables['latitude'][:]
lons = data.variables['longitude'][:]
sic = data.variables['seaice_conc'][768:,:,:]
data.close()
lon2,lat2 = np.meshgrid(lons,lats)
### Reshape concentration
sic = np.reshape(sic,(sic.shape[0]//12,12,lats.shape[0],lons.shape[0]))
### Slice month
sicmo = sic[:,2,:,:]
sicmo[np.where(sicmo < 0.01)] = np.nan
sicmo = sicmo/100.
#### Calculate 1981-2010 average
yearq = np.where((years>=1981) & (years<=2010))[0]
mean = np.nanmean(sicmo[yearq,:,:],axis=0)*100.
###############################################################################
###############################################################################
###############################################################################
### Plot Figure
plt.rc('text',usetex=True)
plt.rc('font',**{'family':'sans-serif','sans-serif':['Avant Garde']})
plt.rc('savefig',facecolor='black')
plt.rc('axes',edgecolor='white')
plt.rc('xtick',color='white')
plt.rc('ytick',color='white')
plt.rc('axes',labelcolor='white')
plt.rc('axes',facecolor='black')
def setcolor(x, color):
for m in x:
for t in x[m][1]:
t.set_color(color)
fig = plt.figure()
ax = fig.add_subplot(111)
m = Basemap(projection='npstere',boundinglat=43,lon_0=270,resolution='l',round =True)
m.drawcoastlines(color = 'k',linewidth=0.5)
m.drawmapboundary(color='k')
m.drawlsmask(land_color='k',ocean_color='k')
#parallels = np.arange(50,91,5)
#meridians = np.arange(-180,180,30)
#m.drawparallels(parallels,labels=[False,False,False,False],
# linewidth=0.2,color='w')
#par=m.drawmeridians(meridians,labels=[True,True,False,False],
# linewidth=0.2,fontsize=6,color='w')
#setcolor(par,'white')
cs = m.contourf(lon2,lat2,mean,50,latlon=True)
cs1 = m.contour(lon2,lat2,lat2,np.arange(80,100,10),latlon=True,colors='r',
linestyles='--',dashes=(1,0.2))
cs2 = m.contour(lon2,lat2,lat2,np.arange(67,77,10),latlon=True,colors='r',
linestyles='-',linewidths=2.5)
cs2 = m.contour(lon2,lat2,lat2,np.arange(50,60,10),latlon=True,colors='r',
linestyles='--',dashes=(1,0.2))
cs3 = m.plot(0,90,'ro',markersize=3.5,latlon=True)
cs.set_cmap(cmocean.cm.ice)
plt
m.fillcontinents(color='k')
plt.annotate(r'\textbf{80$^\circ$N}',xy=(0.51,0.55),
xycoords='figure fraction',color='r',fontsize=8.5,
ha='center',va='center')
plt.annotate(r'\textbf{67$^\circ$N}',xy=(0.51,0.65),
xycoords='figure fraction',color='r',fontsize=8.5,
ha='center',va='center')
plt.annotate(r'\textbf{50$^\circ$N}',xy=(0.51,0.79),
xycoords='figure fraction',color='r',fontsize=8.5,
ha='center',va='center')
plt.annotate(r'\textbf{GRAPHIC:} <NAME> (@ZLabe)',xy=(0.51,0.1),
xycoords='figure fraction',color='darkgrey',fontsize=6,
ha='center',va='center')
plt.annotate(r'\textbf{DATA:} March (1981-2010) SSMIS DMSP (NSIDC)',xy=(0.51,0.08),
xycoords='figure fraction',color='darkgrey',fontsize=6,
ha='center',va='center')
plt.annotate(r'\textbf{ARCTIC SEA ICE ANNUAL \underline{MAX}}',xy=(0.51,0.88),
xycoords='figure fraction',color='darkgrey',fontsize=24,
ha='center',va='center')
print('Completed: Figure plotted!')
plt.savefig(directoryfigure + 'seaiceMAX_climo.png',dpi=300)
print('Completed: Script done!') | [
"numpy.reshape",
"matplotlib.pyplot.savefig",
"numpy.where",
"netCDF4.Dataset",
"datetime.datetime.now",
"matplotlib.pyplot.figure",
"mpl_toolkits.basemap.Basemap",
"matplotlib.pyplot.annotate",
"matplotlib.pyplot.rc",
"numpy.nanmean",
"numpy.meshgrid",
"numpy.arange"
] | [((561, 584), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (582, 584), False, 'import datetime\n'), ((778, 806), 'numpy.arange', 'np.arange', (['(1979)', '(2010 + 1)', '(1)'], {}), '(1979, 2010 + 1, 1)\n', (787, 806), True, 'import numpy as np\n'), ((950, 973), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (971, 973), False, 'import datetime\n'), ((1001, 1029), 'numpy.arange', 'np.arange', (['(1914)', '(2013 + 1)', '(1)'], {}), '(1914, 2013 + 1, 1)\n', (1010, 1029), True, 'import numpy as np\n'), ((1034, 1084), 'netCDF4.Dataset', 'Dataset', (["(directorydata + 'G10010_SIBT1850_v1.1.nc')"], {}), "(directorydata + 'G10010_SIBT1850_v1.1.nc')\n", (1041, 1084), False, 'from netCDF4 import Dataset\n'), ((1232, 1255), 'numpy.meshgrid', 'np.meshgrid', (['lons', 'lats'], {}), '(lons, lats)\n', (1243, 1255), True, 'import numpy as np\n'), ((1288, 1359), 'numpy.reshape', 'np.reshape', (['sic', '(sic.shape[0] // 12, 12, lats.shape[0], lons.shape[0])'], {}), '(sic, (sic.shape[0] // 12, 12, lats.shape[0], lons.shape[0]))\n', (1298, 1359), True, 'import numpy as np\n'), ((1840, 1867), 'matplotlib.pyplot.rc', 'plt.rc', (['"""text"""'], {'usetex': '(True)'}), "('text', usetex=True)\n", (1846, 1867), True, 'import matplotlib.pyplot as plt\n'), ((1867, 1940), 'matplotlib.pyplot.rc', 'plt.rc', (['"""font"""'], {}), "('font', **{'family': 'sans-serif', 'sans-serif': ['Avant Garde']})\n", (1873, 1940), True, 'import matplotlib.pyplot as plt\n'), ((1938, 1974), 'matplotlib.pyplot.rc', 'plt.rc', (['"""savefig"""'], {'facecolor': '"""black"""'}), "('savefig', facecolor='black')\n", (1944, 1974), True, 'import matplotlib.pyplot as plt\n'), ((1974, 2007), 'matplotlib.pyplot.rc', 'plt.rc', (['"""axes"""'], {'edgecolor': '"""white"""'}), "('axes', edgecolor='white')\n", (1980, 2007), True, 'import matplotlib.pyplot as plt\n'), ((2007, 2037), 'matplotlib.pyplot.rc', 'plt.rc', (['"""xtick"""'], {'color': '"""white"""'}), "('xtick', color='white')\n", (2013, 2037), True, 'import matplotlib.pyplot as plt\n'), ((2037, 2067), 'matplotlib.pyplot.rc', 'plt.rc', (['"""ytick"""'], {'color': '"""white"""'}), "('ytick', color='white')\n", (2043, 2067), True, 'import matplotlib.pyplot as plt\n'), ((2067, 2101), 'matplotlib.pyplot.rc', 'plt.rc', (['"""axes"""'], {'labelcolor': '"""white"""'}), "('axes', labelcolor='white')\n", (2073, 2101), True, 'import matplotlib.pyplot as plt\n'), ((2101, 2134), 'matplotlib.pyplot.rc', 'plt.rc', (['"""axes"""'], {'facecolor': '"""black"""'}), "('axes', facecolor='black')\n", (2107, 2134), True, 'import matplotlib.pyplot as plt\n'), ((2242, 2254), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (2252, 2254), True, 'import matplotlib.pyplot as plt\n'), ((2285, 2373), 'mpl_toolkits.basemap.Basemap', 'Basemap', ([], {'projection': '"""npstere"""', 'boundinglat': '(43)', 'lon_0': '(270)', 'resolution': '"""l"""', 'round': '(True)'}), "(projection='npstere', boundinglat=43, lon_0=270, resolution='l',\n round=True)\n", (2292, 2373), False, 'from mpl_toolkits.basemap import Basemap, addcyclic, shiftgrid\n'), ((3355, 3494), 'matplotlib.pyplot.annotate', 'plt.annotate', (['"""\\\\textbf{80$^\\\\circ$N}"""'], {'xy': '(0.51, 0.55)', 'xycoords': '"""figure fraction"""', 'color': '"""r"""', 'fontsize': '(8.5)', 'ha': '"""center"""', 'va': '"""center"""'}), "('\\\\textbf{80$^\\\\circ$N}', xy=(0.51, 0.55), xycoords=\n 'figure fraction', color='r', fontsize=8.5, ha='center', va='center')\n", (3367, 3494), True, 'import matplotlib.pyplot as plt\n'), ((3510, 3649), 'matplotlib.pyplot.annotate', 'plt.annotate', (['"""\\\\textbf{67$^\\\\circ$N}"""'], {'xy': '(0.51, 0.65)', 'xycoords': '"""figure fraction"""', 'color': '"""r"""', 'fontsize': '(8.5)', 'ha': '"""center"""', 'va': '"""center"""'}), "('\\\\textbf{67$^\\\\circ$N}', xy=(0.51, 0.65), xycoords=\n 'figure fraction', color='r', fontsize=8.5, ha='center', va='center')\n", (3522, 3649), True, 'import matplotlib.pyplot as plt\n'), ((3665, 3804), 'matplotlib.pyplot.annotate', 'plt.annotate', (['"""\\\\textbf{50$^\\\\circ$N}"""'], {'xy': '(0.51, 0.79)', 'xycoords': '"""figure fraction"""', 'color': '"""r"""', 'fontsize': '(8.5)', 'ha': '"""center"""', 'va': '"""center"""'}), "('\\\\textbf{50$^\\\\circ$N}', xy=(0.51, 0.79), xycoords=\n 'figure fraction', color='r', fontsize=8.5, ha='center', va='center')\n", (3677, 3804), True, 'import matplotlib.pyplot as plt\n'), ((3823, 3978), 'matplotlib.pyplot.annotate', 'plt.annotate', (['"""\\\\textbf{GRAPHIC:} <NAME> (@ZLabe)"""'], {'xy': '(0.51, 0.1)', 'xycoords': '"""figure fraction"""', 'color': '"""darkgrey"""', 'fontsize': '(6)', 'ha': '"""center"""', 'va': '"""center"""'}), "('\\\\textbf{GRAPHIC:} <NAME> (@ZLabe)', xy=(0.51, 0.1), xycoords\n ='figure fraction', color='darkgrey', fontsize=6, ha='center', va='center')\n", (3835, 3978), True, 'import matplotlib.pyplot as plt\n'), ((3995, 4173), 'matplotlib.pyplot.annotate', 'plt.annotate', (['"""\\\\textbf{DATA:} March (1981-2010) SSMIS DMSP (NSIDC)"""'], {'xy': '(0.51, 0.08)', 'xycoords': '"""figure fraction"""', 'color': '"""darkgrey"""', 'fontsize': '(6)', 'ha': '"""center"""', 'va': '"""center"""'}), "('\\\\textbf{DATA:} March (1981-2010) SSMIS DMSP (NSIDC)', xy=(\n 0.51, 0.08), xycoords='figure fraction', color='darkgrey', fontsize=6,\n ha='center', va='center')\n", (4007, 4173), True, 'import matplotlib.pyplot as plt\n'), ((4186, 4362), 'matplotlib.pyplot.annotate', 'plt.annotate', (['"""\\\\textbf{ARCTIC SEA ICE ANNUAL \\\\underline{MAX}}"""'], {'xy': '(0.51, 0.88)', 'xycoords': '"""figure fraction"""', 'color': '"""darkgrey"""', 'fontsize': '(24)', 'ha': '"""center"""', 'va': '"""center"""'}), "('\\\\textbf{ARCTIC SEA ICE ANNUAL \\\\underline{MAX}}', xy=(0.51, \n 0.88), xycoords='figure fraction', color='darkgrey', fontsize=24, ha=\n 'center', va='center')\n", (4198, 4362), True, 'import matplotlib.pyplot as plt\n'), ((4411, 4472), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(directoryfigure + 'seaiceMAX_climo.png')"], {'dpi': '(300)'}), "(directoryfigure + 'seaiceMAX_climo.png', dpi=300)\n", (4422, 4472), True, 'import matplotlib.pyplot as plt\n'), ((1398, 1420), 'numpy.where', 'np.where', (['(sicmo < 0.01)'], {}), '(sicmo < 0.01)\n', (1406, 1420), True, 'import numpy as np\n'), ((1492, 1535), 'numpy.where', 'np.where', (['((years >= 1981) & (years <= 2010))'], {}), '((years >= 1981) & (years <= 2010))\n', (1500, 1535), True, 'import numpy as np\n'), ((1542, 1580), 'numpy.nanmean', 'np.nanmean', (['sicmo[yearq, :, :]'], {'axis': '(0)'}), '(sicmo[yearq, :, :], axis=0)\n', (1552, 1580), True, 'import numpy as np\n'), ((2879, 2901), 'numpy.arange', 'np.arange', (['(80)', '(100)', '(10)'], {}), '(80, 100, 10)\n', (2888, 2901), True, 'import numpy as np\n'), ((3003, 3024), 'numpy.arange', 'np.arange', (['(67)', '(77)', '(10)'], {}), '(67, 77, 10)\n', (3012, 3024), True, 'import numpy as np\n'), ((3125, 3146), 'numpy.arange', 'np.arange', (['(50)', '(60)', '(10)'], {}), '(50, 60, 10)\n', (3134, 3146), True, 'import numpy as np\n')] |
# #####################################################################################################################
'''
This file is a scratchpad of code used for preparing the folders of the dataset, including:
- Inverting a greyscale image, so that all cells are on a black background
- Pulling a random subset of images into a holdout group
'''
# #####################################################################################################################
# Data science tools
import os
import sys
from PIL import Image, ImageOps
import numpy as np
import image_slicer
import random
import torchvision.transforms.functional as F
import pandas
# local libraries
from dataset_prep import clean
class Invert(object):
""" Inverting a greyscale image """
def invert(self, img):
if not F._is_pil_image(img):
raise TypeError('img should be PIL Image. Got {}'.format(type(img)))
if img.mode == 'RGBA':
r, g, b, a = img.split()
rgb = Image.merge('RGB', (r, g, b))
inv = ImageOps.invert(rgb)
r, g, b = inv.split()
inv = Image.merge('RGBA', (r, g, b, a))
elif img.mode == 'LA':
l, a = img.split()
l = ImageOps.invert(l)
inv = Image.merge('LA', (l, a))
else:
inv = ImageOps.invert(img)
return inv
def __call__(self, img):
return self.invert(img)
def __repr__(self):
return self.__class__.__name__ + '()'
def invert(file_dir):
""" Inverts all the images in the specified directory (so you can change cells to be on a black background,
instead of white background, for example) """
inv = Invert()
files = os.listdir(file_dir)
print("starting conversion...")
ctr = 0
for f in files:
print(ctr)
ctr += 1
try:
gr = Image.open(file_dir + f)
inverse = inv(gr)
inverse.save(file_dir + f)
except:
print(f)
print("...finished conversion")
#invert("/home/kdobolyi/cellnet/malaria_cell_images/Parasitized/")
def createRandomSubset(root, size):
""" Places random files into a new folder, <root>_subset_<size>
Arguments:
root: the source folder of all the images, which has a subfolder for each label (like ImageFolder)
size: what the size of the random subset should be
"""
mini = root + "_subset_" + str(size)
if os.path.exists(mini):
os.system("rm -r " + mini)
os.system("mkdir " + mini)
labels = clean(os.listdir(root))
# go through each sub-folder for each type of class, and create it in the TRAIN and TEST dirs
for label in labels:
files_dirty = clean(os.listdir(root + "/" + label))
holdout = clean(os.listdir('HOLDOUT_' + root))
files = []
for file in files_dirty:
if file not in holdout:
files.append(file)
# randomly select the files for the folds, using a cap as requested
indicies = list(range(len(files)))
random.shuffle(indicies)
indicies = indicies[:size]
os.system("mkdir " + mini + "/" + label)
for i in indicies:
os.system("cp " + root + "/" + label + "/" + files[i] + " " + mini + "/" + label + "/" + files[i])
#createRandomSubset("malaria_cell_images", 500)
def createTiles(root, dest, subfolders, centerCropSize, numTiles):
""" slices a folder (assumed to be all of the same label) into tiles, called <root>_tiles
Arguments:
root: the source folder of all the images, which has a subfolder for each label (absolute path)
subfolders: list of names of subfolders you want to tile (relative path folder name only)
centerCropSize: to what size should the raw image be center-cropped to (or None)
numTiles: how many tiles you want to create out of the (cropped) raw image
"""
if os.path.exists(dest):
os.system("rm -r " + dest)
os.system("mkdir " + dest)
# process all the subfolders
for label in subfolders:
os.system("mkdir " + dest + "/" + label)
# process individual image
files = os.listdir(root + "/" + label)
for f in files:
if f.startswith('.'):
continue
# center-crop the image (or not) and create and save tiles
if centerCropSize != None:
# crop the image
im = Image.open(root + "/" + label + "/" + f)
width, height = im.size
left = (width - centerCropSize)/2
top = (height - centerCropSize)/2
right = (width + centerCropSize)/2
bottom = (height + centerCropSize)/2
im = im.crop((left, top, right, bottom))
im.save(dest + "/" + label + "/cropped_" + f)
tiles = image_slicer.slice(dest + "/" + label + "/cropped_" + f, numTiles, save=False)
os.system("rm " + dest + "/" + label + "/cropped_" + f)
else:
tiles = image_slicer.slice(root + "/" + label + "/" + f, numTiles, save=False)
image_slicer.save_tiles(tiles, directory= dest + "/" + label + "/", prefix='tile_' + f)
print("finished tiling " + label + " to " + dest)
#createTiles("/Users/kdobolyi/Downloads/Labeled_Images_color", "/Users/kdobolyi/Downloads/Labeled_Images_color_tiles",
# ['good', 'bad'], 1200, 2)
def makeImageFolders(csv, file_dir_source, file_dir_dest, labels):
""" takes a directory of raw images, and a csv in Image_Name,label format, and turns it into ImageFolder style
Arguments:
csv: the csv with the file names and labels. Must have columns called "Image_Name" and "label". Image
names should be relative paths to file_dir_source.
file_dir_source: the directory containing all the images references by your CSV (absolute path)
file_dir_dest: the root where you want it to create a subfolder for each label (absolute path)
labels: list of labels you want to use (should match labels in your csv)
"""
key = pandas.read_csv(csv)
print(key['label'].value_counts())
# overwrites any old dest files, making new folders
if os.path.exists(file_dir_dest):
os.system("rm -r " + file_dir_dest)
os.system("mkdir " + file_dir_dest)
for i in labels:
os.system("mkdir " + file_dir_dest + "/" + i)
# makes a copy of all images in the correct folder
def processRow(img, label, file_dir_source, file_dir_dest):
os.system("cp " + file_dir_source + "/" + img + " " + file_dir_dest + "/" + label + "/" + img)
key[['Image_Name', "label"]].apply(lambda x: processRow(*x, file_dir_source, file_dir_dest), axis=1)
print("fininshed splitting raw image folder into ImageFolder style folder at " + file_dir_dest)
#makeImageFolders('/Users/kdobolyi/Downloads/Labeled_Images_2ndSet/Image_Label_association.csv',
# '/Users/kdobolyi/Downloads/Labeled_Images_color_split', '/Users/kdobolyi/Downloads/Labeled_Images_color/', ['good', 'bad'])
def getAverageImage(directory, name):
""" Places random files into a new folder, <root>_subset_<size>
Arguments:
root: the source folder of all the images, which has a subfolder for each label (like ImageFolder)
size: what the size of the random subset should be
"""
imlist = clean(os.listdir(directory))
width, height =Image.open(directory + imlist[0]).size
arr = np.zeros((height, width, 3),np.float)
# Build up average pixel intensities, casting each image as an array of floats
for im in imlist:
print(im)
imarr = np.array(Image.open(directory + im), dtype=np.float)
arr = arr + imarr / (len(imlist) * 1.0)
# Round values in array and cast as 8-bit integer, save average image
arr = np.array(np.round(arr), dtype=np.uint8)
out = Image.fromarray(arr, mode="RGB")
out.save("average" + name + ".png")
getAverageImage("/Users/kdobolyi/Downloads/Labeled_Images_color/bad/", "bad")
getAverageImage("/Users/kdobolyi/Downloads/Labeled_Images_color/good/", "good")
| [
"os.path.exists",
"PIL.Image.fromarray",
"os.listdir",
"PIL.Image.open",
"random.shuffle",
"pandas.read_csv",
"PIL.Image.merge",
"image_slicer.slice",
"image_slicer.save_tiles",
"numpy.zeros",
"torchvision.transforms.functional._is_pil_image",
"PIL.ImageOps.invert",
"os.system",
"numpy.rou... | [((1576, 1596), 'os.listdir', 'os.listdir', (['file_dir'], {}), '(file_dir)\n', (1586, 1596), False, 'import os\n'), ((2217, 2237), 'os.path.exists', 'os.path.exists', (['mini'], {}), '(mini)\n', (2231, 2237), False, 'import os\n'), ((2269, 2295), 'os.system', 'os.system', (["('mkdir ' + mini)"], {}), "('mkdir ' + mini)\n", (2278, 2295), False, 'import os\n'), ((3559, 3579), 'os.path.exists', 'os.path.exists', (['dest'], {}), '(dest)\n', (3573, 3579), False, 'import os\n'), ((3611, 3637), 'os.system', 'os.system', (["('mkdir ' + dest)"], {}), "('mkdir ' + dest)\n", (3620, 3637), False, 'import os\n'), ((5495, 5515), 'pandas.read_csv', 'pandas.read_csv', (['csv'], {}), '(csv)\n', (5510, 5515), False, 'import pandas\n'), ((5610, 5639), 'os.path.exists', 'os.path.exists', (['file_dir_dest'], {}), '(file_dir_dest)\n', (5624, 5639), False, 'import os\n'), ((5680, 5715), 'os.system', 'os.system', (["('mkdir ' + file_dir_dest)"], {}), "('mkdir ' + file_dir_dest)\n", (5689, 5715), False, 'import os\n'), ((6802, 6840), 'numpy.zeros', 'np.zeros', (['(height, width, 3)', 'np.float'], {}), '((height, width, 3), np.float)\n', (6810, 6840), True, 'import numpy as np\n'), ((7192, 7224), 'PIL.Image.fromarray', 'Image.fromarray', (['arr'], {'mode': '"""RGB"""'}), "(arr, mode='RGB')\n", (7207, 7224), False, 'from PIL import Image, ImageOps\n'), ((2241, 2267), 'os.system', 'os.system', (["('rm -r ' + mini)"], {}), "('rm -r ' + mini)\n", (2250, 2267), False, 'import os\n'), ((2313, 2329), 'os.listdir', 'os.listdir', (['root'], {}), '(root)\n', (2323, 2329), False, 'import os\n'), ((2751, 2775), 'random.shuffle', 'random.shuffle', (['indicies'], {}), '(indicies)\n', (2765, 2775), False, 'import random\n'), ((2808, 2848), 'os.system', 'os.system', (["('mkdir ' + mini + '/' + label)"], {}), "('mkdir ' + mini + '/' + label)\n", (2817, 2848), False, 'import os\n'), ((3583, 3609), 'os.system', 'os.system', (["('rm -r ' + dest)"], {}), "('rm -r ' + dest)\n", (3592, 3609), False, 'import os\n'), ((3697, 3737), 'os.system', 'os.system', (["('mkdir ' + dest + '/' + label)"], {}), "('mkdir ' + dest + '/' + label)\n", (3706, 3737), False, 'import os\n'), ((3778, 3808), 'os.listdir', 'os.listdir', (["(root + '/' + label)"], {}), "(root + '/' + label)\n", (3788, 3808), False, 'import os\n'), ((5643, 5678), 'os.system', 'os.system', (["('rm -r ' + file_dir_dest)"], {}), "('rm -r ' + file_dir_dest)\n", (5652, 5678), False, 'import os\n'), ((5736, 5781), 'os.system', 'os.system', (["('mkdir ' + file_dir_dest + '/' + i)"], {}), "('mkdir ' + file_dir_dest + '/' + i)\n", (5745, 5781), False, 'import os\n'), ((5898, 5996), 'os.system', 'os.system', (["('cp ' + file_dir_source + '/' + img + ' ' + file_dir_dest + '/' + label +\n '/' + img)"], {}), "('cp ' + file_dir_source + '/' + img + ' ' + file_dir_dest + '/' +\n label + '/' + img)\n", (5907, 5996), False, 'import os\n'), ((6717, 6738), 'os.listdir', 'os.listdir', (['directory'], {}), '(directory)\n', (6727, 6738), False, 'import os\n'), ((6756, 6789), 'PIL.Image.open', 'Image.open', (['(directory + imlist[0])'], {}), '(directory + imlist[0])\n', (6766, 6789), False, 'from PIL import Image, ImageOps\n'), ((7154, 7167), 'numpy.round', 'np.round', (['arr'], {}), '(arr)\n', (7162, 7167), True, 'import numpy as np\n'), ((811, 831), 'torchvision.transforms.functional._is_pil_image', 'F._is_pil_image', (['img'], {}), '(img)\n', (826, 831), True, 'import torchvision.transforms.functional as F\n'), ((968, 997), 'PIL.Image.merge', 'Image.merge', (['"""RGB"""', '(r, g, b)'], {}), "('RGB', (r, g, b))\n", (979, 997), False, 'from PIL import Image, ImageOps\n'), ((1007, 1027), 'PIL.ImageOps.invert', 'ImageOps.invert', (['rgb'], {}), '(rgb)\n', (1022, 1027), False, 'from PIL import Image, ImageOps\n'), ((1062, 1095), 'PIL.Image.merge', 'Image.merge', (['"""RGBA"""', '(r, g, b, a)'], {}), "('RGBA', (r, g, b, a))\n", (1073, 1095), False, 'from PIL import Image, ImageOps\n'), ((1696, 1720), 'PIL.Image.open', 'Image.open', (['(file_dir + f)'], {}), '(file_dir + f)\n', (1706, 1720), False, 'from PIL import Image, ImageOps\n'), ((2470, 2500), 'os.listdir', 'os.listdir', (["(root + '/' + label)"], {}), "(root + '/' + label)\n", (2480, 2500), False, 'import os\n'), ((2520, 2549), 'os.listdir', 'os.listdir', (["('HOLDOUT_' + root)"], {}), "('HOLDOUT_' + root)\n", (2530, 2549), False, 'import os\n'), ((2873, 2975), 'os.system', 'os.system', (["('cp ' + root + '/' + label + '/' + files[i] + ' ' + mini + '/' + label +\n '/' + files[i])"], {}), "('cp ' + root + '/' + label + '/' + files[i] + ' ' + mini + '/' +\n label + '/' + files[i])\n", (2882, 2975), False, 'import os\n'), ((4564, 4655), 'image_slicer.save_tiles', 'image_slicer.save_tiles', (['tiles'], {'directory': "(dest + '/' + label + '/')", 'prefix': "('tile_' + f)"}), "(tiles, directory=dest + '/' + label + '/', prefix=\n 'tile_' + f)\n", (4587, 4655), False, 'import image_slicer\n'), ((6977, 7003), 'PIL.Image.open', 'Image.open', (['(directory + im)'], {}), '(directory + im)\n', (6987, 7003), False, 'from PIL import Image, ImageOps\n'), ((1150, 1168), 'PIL.ImageOps.invert', 'ImageOps.invert', (['l'], {}), '(l)\n', (1165, 1168), False, 'from PIL import Image, ImageOps\n'), ((1178, 1203), 'PIL.Image.merge', 'Image.merge', (['"""LA"""', '(l, a)'], {}), "('LA', (l, a))\n", (1189, 1203), False, 'from PIL import Image, ImageOps\n'), ((1221, 1241), 'PIL.ImageOps.invert', 'ImageOps.invert', (['img'], {}), '(img)\n', (1236, 1241), False, 'from PIL import Image, ImageOps\n'), ((3990, 4030), 'PIL.Image.open', 'Image.open', (["(root + '/' + label + '/' + f)"], {}), "(root + '/' + label + '/' + f)\n", (4000, 4030), False, 'from PIL import Image, ImageOps\n'), ((4325, 4403), 'image_slicer.slice', 'image_slicer.slice', (["(dest + '/' + label + '/cropped_' + f)", 'numTiles'], {'save': '(False)'}), "(dest + '/' + label + '/cropped_' + f, numTiles, save=False)\n", (4343, 4403), False, 'import image_slicer\n'), ((4408, 4463), 'os.system', 'os.system', (["('rm ' + dest + '/' + label + '/cropped_' + f)"], {}), "('rm ' + dest + '/' + label + '/cropped_' + f)\n", (4417, 4463), False, 'import os\n'), ((4485, 4555), 'image_slicer.slice', 'image_slicer.slice', (["(root + '/' + label + '/' + f)", 'numTiles'], {'save': '(False)'}), "(root + '/' + label + '/' + f, numTiles, save=False)\n", (4503, 4555), False, 'import image_slicer\n')] |
import tensorflow
from PIL import Image
import numpy
import argparse
import os
import sys
import pandas
from ModelsEnum import Models
sys.path.insert(0, os.path.abspath(
os.path.join(os.path.dirname(__file__), '..')))
def predict(model, imgPath, imgHeight, imgWidth):
# 如果 imgPath 是数组
if isinstance(imgPath, list):
return [predict(model, img, imgHeight, imgWidth) for img in imgPath]
img = numpy.array(
Image.open(imgPath)
.convert('RGB')
.resize((imgHeight, imgWidth))
)
img = tensorflow.expand_dims(img, 0)
return tensorflow.nn.softmax(model.predict(img))
def main():
models = [Models.Model2Classi.value, Models.ModelMulClassi.value]
parser = argparse.ArgumentParser()
parser.add_argument("-i", "--input", help="Input image",
required=True, type=str, nargs='+')
parser.add_argument("-m", "--model", help="Model to use", required=False,
default='2classi', type=str, choices=models)
args = parser.parse_args()
import globalConfig.config as config
from models.model2Classi.modelDefinition import model as model2Classi
from models.modelMulClassi.modelDefinition import model as modelMulClassi
if args.model == Models.Model2Classi.value:
model = model2Classi
classNames = config.model2Classi.classNames
model.load_weights(config.model2Classi.savedPath)
imgHeight = config.model2Classi.imgHeight
imgWidth = config.model2Classi.imgWidth
elif args.model == Models.ModelMulClassi.value:
model = modelMulClassi
classNames = config.modelMulClassi.classNames
modelMulClassi.load_weights(config.modelMulClassi.savedPath)
imgHeight = config.modelMulClassi.imgHeight
imgWidth = config.modelMulClassi.imgWidth
else:
raise ValueError('Model not found')
# 检查输入的图片是否是存在
for img in args.input:
if not os.path.exists(img):
print(f"Error: Input img {img} not exists")
exit(1)
# 检查输入的图片是否是文件
for img in args.input:
if not os.path.isfile(img):
print(f"Error: Input img {img} is not a file")
exit(1)
scores = predict(model, args.input, imgHeight, imgWidth)
print()
for i, score in enumerate(scores):
print(f'{args.input[i]} probability: {score[0]}')
print(pandas.Series({classification: f'{str(float(score[0][i])*100)} %' for i, classification in enumerate(
classNames)}))
print(f'result: {classNames[numpy.argmax(score)]}')
print()
main()
| [
"os.path.exists",
"PIL.Image.open",
"argparse.ArgumentParser",
"numpy.argmax",
"os.path.isfile",
"os.path.dirname",
"models.modelMulClassi.modelDefinition.model.load_weights",
"tensorflow.expand_dims"
] | [((539, 569), 'tensorflow.expand_dims', 'tensorflow.expand_dims', (['img', '(0)'], {}), '(img, 0)\n', (561, 569), False, 'import tensorflow\n'), ((720, 745), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (743, 745), False, 'import argparse\n'), ((188, 213), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (203, 213), False, 'import os\n'), ((1669, 1729), 'models.modelMulClassi.modelDefinition.model.load_weights', 'modelMulClassi.load_weights', (['config.modelMulClassi.savedPath'], {}), '(config.modelMulClassi.savedPath)\n', (1696, 1729), True, 'from models.modelMulClassi.modelDefinition import model as modelMulClassi\n'), ((1948, 1967), 'os.path.exists', 'os.path.exists', (['img'], {}), '(img)\n', (1962, 1967), False, 'import os\n'), ((2107, 2126), 'os.path.isfile', 'os.path.isfile', (['img'], {}), '(img)\n', (2121, 2126), False, 'import os\n'), ((440, 459), 'PIL.Image.open', 'Image.open', (['imgPath'], {}), '(imgPath)\n', (450, 459), False, 'from PIL import Image\n'), ((2558, 2577), 'numpy.argmax', 'numpy.argmax', (['score'], {}), '(score)\n', (2570, 2577), False, 'import numpy\n')] |
from mmseg.apis import inference_segmentor, init_segmentor
import mmcv
import os
import numpy as np
import tqdm
import argparse
def show_result(result,
palette=None):
seg = result[0]
palette = np.array(palette)
color_seg = np.zeros((seg.shape[0], seg.shape[1], 3), dtype=np.uint8)
for label, color in enumerate(palette):
color_seg[seg == label, :] = color
img = color_seg
img = img.astype(np.uint8)
return img
parser = argparse.ArgumentParser()
parser.add_argument("config")
parser.add_argument("pth")
parser.add_argument("input")
parser.add_argument("output")
args = parser.parse_args()
input_path = args.input
output_path = args.output
os.makedirs(output_path,exist_ok=True)
img_list = os.listdir(input_path)
# build the model from a config file and a checkpoint file
model = init_segmentor(args.config, args.pth, device="cuda:0")
for i in tqdm.tqdm(img_list):
img_path = os.path.join(input_path, i)
result = inference_segmentor(model, img_path)
img = show_result(result, palette=model.PALETTE)
# img = img[:, :, 0] / 255
mmcv.imwrite(img, os.path.join(output_path, i.split(".")[0] + ".jpg"))
| [
"os.listdir",
"os.makedirs",
"argparse.ArgumentParser",
"mmseg.apis.inference_segmentor",
"tqdm.tqdm",
"os.path.join",
"numpy.array",
"numpy.zeros",
"mmseg.apis.init_segmentor"
] | [((497, 522), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (520, 522), False, 'import argparse\n'), ((724, 763), 'os.makedirs', 'os.makedirs', (['output_path'], {'exist_ok': '(True)'}), '(output_path, exist_ok=True)\n', (735, 763), False, 'import os\n'), ((775, 797), 'os.listdir', 'os.listdir', (['input_path'], {}), '(input_path)\n', (785, 797), False, 'import os\n'), ((869, 923), 'mmseg.apis.init_segmentor', 'init_segmentor', (['args.config', 'args.pth'], {'device': '"""cuda:0"""'}), "(args.config, args.pth, device='cuda:0')\n", (883, 923), False, 'from mmseg.apis import inference_segmentor, init_segmentor\n'), ((934, 953), 'tqdm.tqdm', 'tqdm.tqdm', (['img_list'], {}), '(img_list)\n', (943, 953), False, 'import tqdm\n'), ((228, 245), 'numpy.array', 'np.array', (['palette'], {}), '(palette)\n', (236, 245), True, 'import numpy as np\n'), ((263, 320), 'numpy.zeros', 'np.zeros', (['(seg.shape[0], seg.shape[1], 3)'], {'dtype': 'np.uint8'}), '((seg.shape[0], seg.shape[1], 3), dtype=np.uint8)\n', (271, 320), True, 'import numpy as np\n'), ((971, 998), 'os.path.join', 'os.path.join', (['input_path', 'i'], {}), '(input_path, i)\n', (983, 998), False, 'import os\n'), ((1013, 1049), 'mmseg.apis.inference_segmentor', 'inference_segmentor', (['model', 'img_path'], {}), '(model, img_path)\n', (1032, 1049), False, 'from mmseg.apis import inference_segmentor, init_segmentor\n')] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.