code
stringlengths 31
1.05M
| apis
list | extract_api
stringlengths 97
1.91M
|
---|---|---|
'''
generate evaluation file for Cityscapes.
'''
import numpy as np
from PIL import Image
import utilities.get_default_palette as get_default_palette
BINS = [-0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5]
def get_mode(arr, num=1):
'''
get mode
'''
assert num <= 8
hist = np.histogram(arr, bins=BINS)
hist = hist[0]
cur_max = np.max(hist)
label_list = []
ratio = []
for _ in range(num):
max_value = np.max(hist)
max_index = np.argmax(hist)
if max_value > cur_max*0.2:
label_list.append(max_index)
ratio.append(max_value/cur_max)
hist[max_index] = 0
else:
break
return label_list, ratio
def gen_evaluation_file(semantic_mask, instance_mask, confidence_array,
instance_mask_path, txt_path, file_name, additive=False,
slide_semantic=False, mask_label=None, mask_idx=0, result_path=None):
'''
generate evaluation file for cityscapes
'''
assert result_path, 'result_path must be specified'
result_path = result_path + '/'
_ids = np.array(['0', '24', '25', '26', '27', '28', '31', '32', '33'])
instance_list = np.unique(instance_mask)
refined_instance_mask = np.copy(instance_mask)
if slide_semantic:
semantic_part_idx = mask_label == (mask_idx + 1)
file_op = 'w'
ins_prefix = str(mask_idx)
if additive:
file_op = 'a'
with open(result_path + txt_path + file_name + '.txt', file_op) as file:
for i in range(instance_list.shape[0]):
if instance_list[i] == 0:
continue
ins_mask = instance_mask == instance_list[i]
instance_semantic_label = semantic_mask[ins_mask]
instance_semantic_label = instance_semantic_label[instance_semantic_label != 0]
if instance_semantic_label.size == 0:
continue
labels, ratios = get_mode(instance_semantic_label, 4)
for label_i, label in enumerate(labels):
if label == 0:
continue
_confidence = confidence_array[i] * ratios[label_i]
_id = _ids[label]
if slide_semantic:
if not np.isin(label, np.arange(9)[semantic_part_idx]):
refined_instance_mask[ins_mask] = 0
continue
curr_ins = ins_prefix + '_%d_%d.png' % (i, label_i)
_result_mask_path = instance_mask_path + file_name + curr_ins
_result_mask = ins_mask.astype('uint8')
_result_mask_image = Image.fromarray(_result_mask, mode='P')
mask_palette = get_default_palette.get_default_palette()
_result_mask_image.putpalette(mask_palette)
_result_mask_image.save(result_path + _result_mask_path)
file.write('.' + _result_mask_path)
file.write(' ')
file.write(_id)
file.write(' ')
file.write(str(_confidence))
file.write('\n')
return refined_instance_mask
|
[
"numpy.copy",
"numpy.argmax",
"utilities.get_default_palette.get_default_palette",
"numpy.histogram",
"numpy.max",
"numpy.array",
"numpy.arange",
"PIL.Image.fromarray",
"numpy.unique"
] |
[((292, 320), 'numpy.histogram', 'np.histogram', (['arr'], {'bins': 'BINS'}), '(arr, bins=BINS)\n', (304, 320), True, 'import numpy as np\n'), ((350, 362), 'numpy.max', 'np.max', (['hist'], {}), '(hist)\n', (356, 362), True, 'import numpy as np\n'), ((1057, 1120), 'numpy.array', 'np.array', (["['0', '24', '25', '26', '27', '28', '31', '32', '33']"], {}), "(['0', '24', '25', '26', '27', '28', '31', '32', '33'])\n", (1065, 1120), True, 'import numpy as np\n'), ((1139, 1163), 'numpy.unique', 'np.unique', (['instance_mask'], {}), '(instance_mask)\n', (1148, 1163), True, 'import numpy as np\n'), ((1191, 1213), 'numpy.copy', 'np.copy', (['instance_mask'], {}), '(instance_mask)\n', (1198, 1213), True, 'import numpy as np\n'), ((433, 445), 'numpy.max', 'np.max', (['hist'], {}), '(hist)\n', (439, 445), True, 'import numpy as np\n'), ((462, 477), 'numpy.argmax', 'np.argmax', (['hist'], {}), '(hist)\n', (471, 477), True, 'import numpy as np\n'), ((2400, 2439), 'PIL.Image.fromarray', 'Image.fromarray', (['_result_mask'], {'mode': '"""P"""'}), "(_result_mask, mode='P')\n", (2415, 2439), False, 'from PIL import Image\n'), ((2463, 2504), 'utilities.get_default_palette.get_default_palette', 'get_default_palette.get_default_palette', ([], {}), '()\n', (2502, 2504), True, 'import utilities.get_default_palette as get_default_palette\n'), ((2089, 2101), 'numpy.arange', 'np.arange', (['(9)'], {}), '(9)\n', (2098, 2101), True, 'import numpy as np\n')]
|
"""
Example script to do acquire a composite survey image using stage shift.
The script uses the center 50% of the image, shifts the stage by the appropriate amount
in x, y directions, and stitches the resulting images together into a larger super image.
To use:
Run Nion Swift and get a good image
Set the defocus value to a large number (positive or negative) such as 500000nm.
Ensure that the aperture is circular and centered.
Ensure that the aperture is large enough so that the center 50% of the image is exposed through aperture.
Decide how many images to acquire by setting the 'size' variable.
Decide how to reduce the acquired data by setting the 'reduce' variable.
Run the script from command line or PyCharm or another suitable Python interpreter.
TODO: SShft.x, SShft.y add rotation; need to fix this in AS2.
TODO: The size of the camera output is hardcoded to 1024, 1024. It should read from the camera object.
TODO: Update composite image live during acquisition. Requires improvements to nionlib.
"""
import math
import numpy
import time
import nionlib
def acquire_composite_survey_image(size, rotation=0, scale=1, reduce=4, print_fn=None):
print_fn = print_fn if print_fn is not None else lambda *args: None
document_controller = nionlib.api.application.document_controllers[0]
library = nionlib.api.library
camera = nionlib.api.get_hardware_source_by_id("nionccd1010", "1")
autostem = nionlib.api.get_instrument_by_id("autostem_controller", "1")
shift_x_control_name = "SShft.x"
shift_y_control_name = "SShft.y"
# grab stage original location
sx_m = autostem.get_control_output(shift_x_control_name)
sy_m = autostem.get_control_output(shift_y_control_name)
tv_pixel_angle_rad = autostem.get_control_output("TVPixelAngle")
defocus = autostem.get_control_output("C10")
print_fn("Acquiring composite survey image...")
print_fn("stage starting position (um) ", sx_m * 1e6, sy_m * 1e6)
print_fn("pixel angle (rad) ", tv_pixel_angle_rad)
print_fn("defocus (nm) ", defocus * 1e9)
image_size = 1024, 1024 # TODO: grab this from camera
image_dtype = numpy.float32
image_width_m = abs(defocus) * math.sin(tv_pixel_angle_rad * image_size[0])
master_sub_area_size = 512, 512
master_sub_area = (image_size[0]//2 - master_sub_area_size[0]//2, image_size[1]//2 - master_sub_area_size[1]//2), master_sub_area_size
reduce = max(1, reduce // (512 / master_sub_area_size[0]))
sub_area_shift_m = image_width_m * (master_sub_area[1][0] / image_size[0])
sub_area = (master_sub_area[0][0]//reduce,master_sub_area[0][1]//reduce), (master_sub_area[1][0]//reduce,master_sub_area[1][1]//reduce)
print_fn("image width (um) ", image_width_m * 1e6)
master_data = numpy.empty((sub_area[1][0] * size[0], sub_area[1][1] * size[1]), image_dtype)
print_fn("master size ", master_data.shape)
try:
for row in range(size[0]):
for column in range(size[1]):
delta_x_m, delta_y_m = sub_area_shift_m * (column - size[1]//2), sub_area_shift_m * (row - size[0]//2)
print_fn("offset (um) ", delta_x_m * 1e6, delta_y_m * 1e6)
start = time.time()
# when used below, we use the rotation rotated by 180 degrees since we are moving the stage, not the
# view. i.e. use -angle and subtract the delta's.
rotated_delta_x_m = (math.cos(rotation) * delta_x_m - math.sin(rotation) * delta_y_m) / scale
rotated_delta_y_m = (math.sin(rotation) * delta_x_m + math.cos(rotation) * delta_y_m) / scale
print_fn("rotated offset (um) ", rotated_delta_x_m * 1e6, rotated_delta_y_m * 1e6)
# set both values. be robust, retrying if set_control_output fails.
attempts = 0
while attempts < 4:
attempts += 1
try:
tolerance_factor = 0.02
autostem.set_control_output(shift_x_control_name, sx_m - rotated_delta_x_m, {"confirm": True, "confirm_tolerance_factor": tolerance_factor})
autostem.set_control_output(shift_y_control_name, sy_m - rotated_delta_y_m, {"confirm": True, "confirm_tolerance_factor": tolerance_factor})
except TimeoutError as e:
print("Timeout row=", row, " column=", column)
continue
break
print_fn("Time", time.time() - start, " row=", row, " column=", column)
supradata = camera.grab_next_to_start()[0]
data = supradata.data[master_sub_area[0][0]:master_sub_area[0][0] + master_sub_area[1][0]:reduce, master_sub_area[0][1]:master_sub_area[0][1] + master_sub_area[1][1]:reduce]
slice_row = row
slice_column = column
slice0 = slice(slice_row * sub_area[1][0], (slice_row + 1) * sub_area[1][0])
slice1 = slice(slice_column * sub_area[1][1], (slice_column + 1) * sub_area[1][1])
master_data[slice0, slice1] = data
data_item = library.create_data_item_from_data(master_data, "Composite Survey")
document_controller.display_data_item(data_item)
finally:
# restore stage to original location
autostem.set_control_output(shift_x_control_name, sx_m)
autostem.set_control_output(shift_y_control_name, sy_m)
# these measurements are determined by a line made from a feature before a shift to a feature after a
# shift. for instance, make a line starting on a feature. then add 100um to SShft.x and measure the
# length of the line and the angle. plug those in here.
rotation = math.radians(-23)
scale = 1.2
acquire_composite_survey_image(size=(5, 5), rotation=rotation, scale=scale, print_fn=print)
|
[
"nionlib.api.get_instrument_by_id",
"math.radians",
"numpy.empty",
"nionlib.api.get_hardware_source_by_id",
"math.sin",
"time.time",
"math.cos"
] |
[((5764, 5781), 'math.radians', 'math.radians', (['(-23)'], {}), '(-23)\n', (5776, 5781), False, 'import math\n'), ((1386, 1443), 'nionlib.api.get_hardware_source_by_id', 'nionlib.api.get_hardware_source_by_id', (['"""nionccd1010"""', '"""1"""'], {}), "('nionccd1010', '1')\n", (1423, 1443), False, 'import nionlib\n'), ((1459, 1519), 'nionlib.api.get_instrument_by_id', 'nionlib.api.get_instrument_by_id', (['"""autostem_controller"""', '"""1"""'], {}), "('autostem_controller', '1')\n", (1491, 1519), False, 'import nionlib\n'), ((2803, 2881), 'numpy.empty', 'numpy.empty', (['(sub_area[1][0] * size[0], sub_area[1][1] * size[1])', 'image_dtype'], {}), '((sub_area[1][0] * size[0], sub_area[1][1] * size[1]), image_dtype)\n', (2814, 2881), False, 'import numpy\n'), ((2223, 2267), 'math.sin', 'math.sin', (['(tv_pixel_angle_rad * image_size[0])'], {}), '(tv_pixel_angle_rad * image_size[0])\n', (2231, 2267), False, 'import math\n'), ((3235, 3246), 'time.time', 'time.time', ([], {}), '()\n', (3244, 3246), False, 'import time\n'), ((4544, 4555), 'time.time', 'time.time', ([], {}), '()\n', (4553, 4555), False, 'import time\n'), ((3467, 3485), 'math.cos', 'math.cos', (['rotation'], {}), '(rotation)\n', (3475, 3485), False, 'import math\n'), ((3500, 3518), 'math.sin', 'math.sin', (['rotation'], {}), '(rotation)\n', (3508, 3518), False, 'import math\n'), ((3577, 3595), 'math.sin', 'math.sin', (['rotation'], {}), '(rotation)\n', (3585, 3595), False, 'import math\n'), ((3610, 3628), 'math.cos', 'math.cos', (['rotation'], {}), '(rotation)\n', (3618, 3628), False, 'import math\n')]
|
# Author: <NAME>
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
try:
import cPickle as pickle
except:
import pickle
import os
import active_learners.helper as helper
import h5py
import numpy as np
from active_learners.active_learner import run_ActiveLearner
def gen_data(expid, exp, n_data, save_fnm):
'''
Generate initial data for a function associated the experiment.
Args:
expid: ID of the experiment; e.g. 0, 1, 2, ...
exp: name of the experiment; e.g. 'pour', 'scoop'.
n_data: number of data points to generate.
save_fnm: a file name string where the initial data will be
saved.
'''
print('Generating data...')
func = helper.get_func_from_exp(exp)
xx, yy = helper.gen_data(func, n_data)
pickle.dump((xx, yy), open(save_fnm, 'wb'))
def run_exp(expid, exp, method, n_init_data, iters):
'''
Run the active learning experiment.
Args:
expid: ID of the experiment; e.g. 0, 1, 2, ...
exp: name of the experiment; e.g. 'pour', 'scoop'.
method: learning method, including
'nn_classification': a classification neural network
based learning algorithm that queries the input that has
the largest output.
'nn_regression': a regression neural network based
learning algorithm that queries the input that has
the largest output.
'gp_best_prob': a Gaussian process based learning algorithm
that queries the input that has the highest probability of
having a positive function value.
'gp_lse': a Gaussian process based learning algorithm called
straddle algorithm. See <NAME>, <NAME>, <NAME>,
<NAME>, <NAME>, and <NAME>, "Active learning for
identifying function threshold boundaries," in NIPS, 2006.
'random': an algorithm that query uniformly random samples.
n_data: number of data points to generate.
save_fnm: a file name string where the initial data will be
saved.
'''
dirnm = 'data/'
if not os.path.isdir(dirnm):
os.mkdir(dirnm)
init_fnm = os.path.join(
dirnm, '{}_init_data_{}.pk'.format(exp, expid))
gen_data(expid, exp, n_init_data, init_fnm)
initx, inity = pickle.load(open(init_fnm, 'rb'))
func = helper.get_func_from_exp(exp)
active_learner = helper.get_learner_from_method(method, initx, inity, func)
# file name for saving the learning results
learn_fnm = os.path.join(
dirnm, '{}_{}_{}.pk'.format(exp, method, expid))
# get a context
context = helper.gen_context(func)
# start running the learner
print('Start running the learning experiment...')
run_ActiveLearner(active_learner, context, learn_fnm, iters)
def sample_exp(expid, exp, method, n_eps, n_timesteps_per_ep):
'''
Sample from the learned model.
Args:
expid: ID of the experiment; e.g. 0, 1, 2, ...
exp: name of the experiment; e.g. 'pour', 'scoop'.
method: see run_exp.
'''
func = helper.get_func_from_exp(exp)
xx, yy, c = helper.get_xx_yy(expid, method, exp=exp)
active_learner = helper.get_learner_from_method(method, xx, yy, func)
active_learner.retrain()
# Enable gui
func.do_gui = True
# while raw_input('Continue? [y/n]') == 'y':
all_ims = []
all_actions = []
for i in range(n_eps):
print("##### %s: %d ######" % (method, i))
x = active_learner.sample(c)
import ipdb
ipdb.set_trace()
ims, actions = func(x, n_timesteps_per_ep)
# func(x)
all_ims.append(ims)
all_actions.append(actions)
return np.array(all_ims), np.array(all_actions)
if __name__ == '__main__':
exp = 'pour'
methods = ['gp_lse']#, 'random']
expid = 0
n_eps = 500
n_timesteps_per_ep = 40
# n_init_data = 10
# iters = 50
save_data = True
dataset = h5py.File('/usr/local/google/home/thanard/data/pouring.hdf5', 'w')
sim_data = dataset.create_group('sim')
sim_data.create_dataset("ims", (n_eps, n_timesteps_per_ep, 64, 64, 3), dtype='f')
sim_data.create_dataset("actions", (n_eps, n_timesteps_per_ep, 3), dtype='f')
# run_exp(expid, exp, method, n_init_data, iters)
i = 0
for method in methods:
ims, actions = sample_exp(expid, exp, method, n_eps//len(methods), n_timesteps_per_ep)
# import ipdb
# ipdb.set_trace()
dataset['sim']['ims'][i:i+n_eps//len(methods)] = ims
dataset['sim']['actions'][i:i+n_eps//len(methods)] = actions
i += n_eps//len(methods)
|
[
"os.mkdir",
"active_learners.active_learner.run_ActiveLearner",
"h5py.File",
"ipdb.set_trace",
"os.path.isdir",
"active_learners.helper.get_func_from_exp",
"active_learners.helper.get_xx_yy",
"numpy.array",
"active_learners.helper.gen_data",
"active_learners.helper.get_learner_from_method",
"active_learners.helper.gen_context"
] |
[((758, 787), 'active_learners.helper.get_func_from_exp', 'helper.get_func_from_exp', (['exp'], {}), '(exp)\n', (782, 787), True, 'import active_learners.helper as helper\n'), ((801, 830), 'active_learners.helper.gen_data', 'helper.gen_data', (['func', 'n_data'], {}), '(func, n_data)\n', (816, 830), True, 'import active_learners.helper as helper\n'), ((2464, 2493), 'active_learners.helper.get_func_from_exp', 'helper.get_func_from_exp', (['exp'], {}), '(exp)\n', (2488, 2493), True, 'import active_learners.helper as helper\n'), ((2516, 2574), 'active_learners.helper.get_learner_from_method', 'helper.get_learner_from_method', (['method', 'initx', 'inity', 'func'], {}), '(method, initx, inity, func)\n', (2546, 2574), True, 'import active_learners.helper as helper\n'), ((2750, 2774), 'active_learners.helper.gen_context', 'helper.gen_context', (['func'], {}), '(func)\n', (2768, 2774), True, 'import active_learners.helper as helper\n'), ((2866, 2926), 'active_learners.active_learner.run_ActiveLearner', 'run_ActiveLearner', (['active_learner', 'context', 'learn_fnm', 'iters'], {}), '(active_learner, context, learn_fnm, iters)\n', (2883, 2926), False, 'from active_learners.active_learner import run_ActiveLearner\n'), ((3206, 3235), 'active_learners.helper.get_func_from_exp', 'helper.get_func_from_exp', (['exp'], {}), '(exp)\n', (3230, 3235), True, 'import active_learners.helper as helper\n'), ((3252, 3292), 'active_learners.helper.get_xx_yy', 'helper.get_xx_yy', (['expid', 'method'], {'exp': 'exp'}), '(expid, method, exp=exp)\n', (3268, 3292), True, 'import active_learners.helper as helper\n'), ((3314, 3366), 'active_learners.helper.get_learner_from_method', 'helper.get_learner_from_method', (['method', 'xx', 'yy', 'func'], {}), '(method, xx, yy, func)\n', (3344, 3366), True, 'import active_learners.helper as helper\n'), ((4083, 4149), 'h5py.File', 'h5py.File', (['"""/usr/local/google/home/thanard/data/pouring.hdf5"""', '"""w"""'], {}), "('/usr/local/google/home/thanard/data/pouring.hdf5', 'w')\n", (4092, 4149), False, 'import h5py\n'), ((2215, 2235), 'os.path.isdir', 'os.path.isdir', (['dirnm'], {}), '(dirnm)\n', (2228, 2235), False, 'import os\n'), ((2245, 2260), 'os.mkdir', 'os.mkdir', (['dirnm'], {}), '(dirnm)\n', (2253, 2260), False, 'import os\n'), ((3666, 3682), 'ipdb.set_trace', 'ipdb.set_trace', ([], {}), '()\n', (3680, 3682), False, 'import ipdb\n'), ((3827, 3844), 'numpy.array', 'np.array', (['all_ims'], {}), '(all_ims)\n', (3835, 3844), True, 'import numpy as np\n'), ((3846, 3867), 'numpy.array', 'np.array', (['all_actions'], {}), '(all_actions)\n', (3854, 3867), True, 'import numpy as np\n')]
|
from timeit import default_timer as timer
import numpy as np
start = timer()
class Link (object):
def __init__(self, data, next=None, previous=None):
self.data = data
self.next = next
self.previous = previous
class CircularList(object):
# Constructor
def __init__(self):
self.first = None
# Insert an element (value) in the list
def insert(self, data):
new_link = Link(data)
if self.first == None:
self.first = new_link
new_link.next = new_link
new_link.previous = new_link
else:
new_link.next = self.first
new_link.previous = self.first.previous
self.first.previous.next = new_link
self.first.previous = new_link
def sum(self):
first = self.first
current = first.next
total = first.data
while current != first:
total += current.data
current = current.next
return total
# Return a string representation of a Circular List
def __str__(self):
first = self.first
output = ''
output += str(first.data) + "\n"
current = first.next
while current != first:
output += str(current.data) + "\n"
current = current.next
return output
input = open("day_6_input.txt", "r")
raw = np.array([int(x) for x in input.readline().split(",")])
fish = np.concatenate([[0], np.unique(raw, return_counts=True)[1], [0, 0, 0]])
fishCircle = CircularList()
for i in fish:
fishCircle.insert(i)
readyFish = fishCircle.first
tiredFish = readyFish.previous.previous
for i in range(256):
tiredFish.data += readyFish.data
readyFish = readyFish.next
tiredFish = tiredFish.next
print(fishCircle.sum())
end = timer()
print(end-start)
|
[
"timeit.default_timer",
"numpy.unique"
] |
[((69, 76), 'timeit.default_timer', 'timer', ([], {}), '()\n', (74, 76), True, 'from timeit import default_timer as timer\n'), ((1808, 1815), 'timeit.default_timer', 'timer', ([], {}), '()\n', (1813, 1815), True, 'from timeit import default_timer as timer\n'), ((1470, 1504), 'numpy.unique', 'np.unique', (['raw'], {'return_counts': '(True)'}), '(raw, return_counts=True)\n', (1479, 1504), True, 'import numpy as np\n')]
|
import argparse
import os
import sys
import re
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
ROOT_DIR = os.path.dirname(BASE_DIR)
sys.path.append(BASE_DIR)
from model import *
import indoor3d_util
import time
import numpy as np
import get_instances
import project_inst
"python inference_online_all.py --path_data a/b/c --path_cls meta/class_or.txt --model_path RUNS/test_indoor --points_sub 128 --points_proj 512 --test_name test_name"
parser = argparse.ArgumentParser()
parser.add_argument('--path_data', help='folder with train test data')
parser.add_argument('--path_cls', help='path to classes txt.')
parser.add_argument('--model_path', required=True, help='model checkpoint file path')
parser.add_argument('--points_sub', type=int, default=128, help='Point number sub [default: 4096]')
parser.add_argument('--points_proj', type=int, default=0, help='Point number proj [default: 4096]')
parser.add_argument('--test_name', help='name of the test')
parser.add_argument('--down_pred', default = 0, help='downsample prediction')
parsed_args = parser.parse_args()
path_data = parsed_args.path_data
path_cls = parsed_args.path_cls
model_path = os.path.join(parsed_args.model_path, "model.ckpt")
points_sub = parsed_args.points_sub
points_proj = parsed_args.points_proj
down_pred = parsed_args.down_pred
test_name = parsed_args.test_name
dump_path = os.path.join(parsed_args.model_path, "dump_" + test_name)
if not os.path.exists(dump_path): os.mkdir(dump_path)
classes, labels, label2color = indoor3d_util.get_info_classes(path_cls)
num_classes = len(classes)
batch_size = 1
gpu_index = 0
block_sub = 0.1
stride_sub = 0.1
block_proj = 0.1
stride_proj = 0.1
minim_points = 37
def evaluate(data, label, xyz_max, sess, ops):
is_training = False
label = np.squeeze(label)
num_batches = data.shape[0] // batch_size
pred_label_list =list()
for batch_idx in range(num_batches):
start_idx = batch_idx * batch_size
end_idx = (batch_idx+1) * batch_size
feed_dict = {ops['pointclouds_pl']: data[start_idx:end_idx, :, :],
ops['labels_pl']: label[start_idx:end_idx],
ops['is_training_pl']: is_training}
loss_val, pred_val = sess.run([ops['loss'], ops['pred_softmax']],
feed_dict=feed_dict)
pred_label = np.argmax(pred_val, 2)
pred_label = pred_label.reshape(pred_label.shape[0]*pred_label.shape[1],1)
pred_label_list.append(pred_label)
pred_label_stacked = np.vstack(pred_label_list)
data = data.reshape((data.shape[0]*data.shape[1]), data.shape[2])
data = np.delete(data, [0,1,2], 1)
data[:, [0,1,2,3,4,5,]] = data[:, [3,4,5,0,1,2]]
data[:,0] *= xyz_max[0]
data[:,1] *= xyz_max[1]
data[:,2] *= xyz_max[2]
data[:,3:] *= 255.0
data = data[:pred_label_stacked.shape[0], :]
pred_sub = np.hstack([data,pred_label_stacked])
return pred_sub
if __name__=='__main__':
with tf.device('/gpu:'+str(gpu_index)):
pointclouds_pl, labels_pl = placeholder_inputs(batch_size, points_sub)
is_training_pl = tf.placeholder(tf.bool, shape=())
# simple model
pred = get_model(pointclouds_pl, is_training_pl)
loss = get_loss(pred, labels_pl)
pred_softmax = tf.nn.softmax(pred)
# Add ops to save and restore all the variables.
saver = tf.train.Saver()
# Create a session
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
config.allow_soft_placement = True
config.log_device_placement = True
sess = tf.Session(config=config)
# Restore variables from disk.
saver.restore(sess, model_path)
ops = {'pointclouds_pl': pointclouds_pl,
'labels_pl': labels_pl,
'is_training_pl': is_training_pl,
'pred': pred,
'pred_softmax': pred_softmax,
'loss': loss}
times_list = list()
while 1:
for root, dirs, files in os.walk(path_data): # for each folder
for file in enumerate(sorted(files)): # for each file # TODO AL FINAL FINAL LEER DE ROS
if re.search("\.(txt)$", file[1]): # if its a txt
print("working on: " + str(file[1]))
filepath = os.path.join(root, file[1])
data_label_full = np.loadtxt(filepath) # read from txt (not on xyz origin)
os.remove(filepath)
if data_label_full.shape[0]> 200000: # check pointcloud points, a good PC has ~ 480k points
# init times that may not be calculated
time_down_pred = 0
time_sub_proj = 0
time_proj = 0
# subsample data_label_full to match ros subscription
reduction = 0.1
n_idx_full_sub = int(data_label_full.shape[0] * reduction)
idx_full_sub = np.random.choice(data_label_full.shape[0], n_idx_full_sub, replace=False)
data_label_full_sub = data_label_full[idx_full_sub, 0:6]
start = time.time()
xyz_min = np.amin(data_label_full_sub, axis=0)[0:3] # get pointcloud mins
data_label_full_sub[:, 0:3] -= xyz_min # move pointcloud to origin
end = time.time()
time_min = end - start
start = time.time()
xyz_max = np.amax(data_label_full_sub, axis=0)[0:3] # get pointcloud maxs
end = time.time()
time_max = end - start
start = time.time()
data_sub, label_sub = indoor3d_util.room2blocks_plus_normalized_parsed(data_label_full_sub, xyz_max, points_sub, block_size=block_sub, stride=stride_sub, random_sample=False, sample_num=None, sample_aug=1) # subsample PC for evaluation
end = time.time()
time_sub_eval = end - start
start = time.time()
with tf.Graph().as_default():
pred_sub = evaluate(data_sub, label_sub, xyz_max, sess, ops) # evaluate PC
pred_sub[:, 0:3] += xyz_min # recover PC's original position
end = time.time()
time_eval = end - start
fout_sub = open(os.path.join(dump_path, os.path.basename(filepath)[:-4]+'_pred_sub.obj'), 'w')
fout_sub_col = open(os.path.join(dump_path, os.path.basename(filepath)[:-4]+'_pred_sub_col.obj'), 'w')
for i in range(pred_sub.shape[0]):
fout_sub.write('v %f %f %f %d %d %d %d\n' % (pred_sub[i,0], pred_sub[i,1], pred_sub[i,2], pred_sub[i,3], pred_sub[i,4], pred_sub[i,5], pred_sub[i,6]))
for i in range(pred_sub.shape[0]):
color = label2color[pred_sub[i,6]]
fout_sub_col.write('v %f %f %f %d %d %d %d\n' % (pred_sub[i,0], pred_sub[i,1], pred_sub[i,2], color[0], color[1], color[2], pred_sub[i,6]))
if down_pred != 0: # if subsampling of prediciton is wanted
start = time.time()
down = float(1/(2**down_pred)) # down_pred = 1, to go down 1, down_pred = 2, to go down 2, always staying in te same block stride
n_idx_pred_sub_down = int(pred_sub.shape[0] * down)
idx_pred_sub_down = np.random.choice(pred_sub.shape[0], n_idx_pred_sub_down, replace=False)
pred_sub = pred_sub[idx_pred_sub_down, 0:7] # downsample prediciton
end = time.time()
time_down_pred = end - start
col_inst = {
0: [255, 255, 0],
1: [255, 0, 255],
2: [0, 255, 255],
3: [0, 128, 0],
4: [0, 0, 128],
5: [128, 0, 0],
6: [0, 255, 0],
7: [0, 0, 255],
8: [255, 0, 0],
9: [0, 100, 0],
10: [0, 0, 100],
11: [100, 0, 0],
12: [100, 0, 255],
13: [0, 255, 100],
13: [255, 100, 0]
}
# init get_instances parameters
rad_p = 0.03
rad_v = 0.045
dim = 2
min_p = minim_points
start = time.time()
instances_noref = get_instances.get_instances(pred_sub, labels, dim, rad_p, dim, rad_v, min_p, ref=False) # get instances no ref
end = time.time()
time_inst_noref = end - start
start = time.time()
instances_ref = get_instances.get_instances(pred_sub, labels, dim, rad_p, dim, rad_v, min_p, ref=True) # get instances ref
end = time.time()
time_inst_ref = end - start
fout_inst = open(os.path.join(dump_path, os.path.basename(filepath)[:-4]+'_pred_inst_ref.obj'), 'w')
fout_inst_col = open(os.path.join(dump_path, os.path.basename(filepath)[:-4]+'_pred_inst_ref_col.obj'), 'w')
for i in range(instances_ref.shape[0]):
fout_inst.write('v %f %f %f %d %d %d %d %d\n' % (instances_ref[i,0], instances_ref[i,1], instances_ref[i,2], instances_ref[i,3], instances_ref[i,4], instances_ref[i,5], instances_ref[i,6], instances_ref[i,7]))
for i in range(instances_ref.shape[0]):
color = col_inst[instances_ref[i,7]]
fout_inst_col.write('v %f %f %f %d %d %d %d %d\n' % (instances_ref[i,0], instances_ref[i,1], instances_ref[i,2], color[0], color[1], color[2], instances_ref[i,6], instances_ref[i,7]))
if instances_ref is not None: # if instances were found
if points_proj != 0: # if projection is wanted
# determine projection number of points
if block_proj == 0.2:
start = 0.3333 # 0.03333 TODO x10 because reduced data_label_full by /10 into data_label_full_sub
by = 1024 / points_proj
reduction = start / by
else:
start = 0.5 # 0.05 TODO x10 because reduced data_label_full by /10 into data_label_full_sub
by = 512 / points_proj
reduction = start / by
# TODO USE FULL_SUB SO WE CAN REUSE XYZ MIN MAX
start = time.time()
n_idx_proj = int(data_label_full_sub.shape[0] * reduction)
idx_proj = np.random.choice(data_label_full_sub.shape[0], n_idx_proj, replace=False)
data_proj = data_label_full_sub[idx_proj, 0:6] # subsample projection
data_proj[:, 0:3] += xyz_min # move projection to original position (data_label_full is on origin)
end = time.time()
time_sub_proj = end - start
start = time.time()
projections = project_inst.project_inst(instances_ref, data_proj)
end = time.time()
time_proj = end - start
else:
projections = instances_ref
if projections is not None:
fout_proj = open(os.path.join(dump_path, os.path.basename(filepath)[:-4]+'_projections.obj'), 'w')
fout_proj_col = open(os.path.join(dump_path, os.path.basename(filepath)[:-4]+'_projections_col.obj'), 'w')
for i in range(projections.shape[0]):
fout_proj.write('v %f %f %f %d %d %d %d %d\n' % (projections[i,0], projections[i,1], projections[i,2], projections[i,3], projections[i,4], projections[i,5], projections[i,6], projections[i,7]))
for i in range(projections.shape[0]):
color = col_inst[projections[i,7]]
fout_proj_col.write('v %f %f %f %d %d %d %d %d\n' % (projections[i,0], projections[i,1], projections[i,2], color[0], color[1], color[2], projections[i,6], projections[i,7]))
if points_proj != 0:
fout_proj = open(os.path.join(dump_path, os.path.basename(filepath)[:-4]+'_base_proj.obj'), 'w')
for i in range(data_proj.shape[0]):
fout_proj.write('v %f %f %f %d %d %d\n' % (data_proj[i,0], data_proj[i,1], data_proj[i,2], data_proj[i,3], data_proj[i,4], data_proj[i,5]))
times = (time_min, time_max, time_sub_eval, time_eval, time_down_pred, time_inst_noref, time_inst_ref, time_sub_proj, time_proj)
times_list.append(times)
times_mean = np.mean(times_list,axis=0)
times_stack = np.vstack(times_list)
fout_times = open(os.path.join(dump_path, 'times.txt'), 'w')
for i in range(times_stack.shape[0]):
fout_times.write('%f %f %f %f %f %f %f %f %f\n' % (times_stack[i,0], times_stack[i,1], times_stack[i,2], times_stack[i,3], times_stack[i,4], times_stack[i,5], times_stack[i,6], times_stack[i,7], times_stack[i,8]))
fout_times.write('--------- MEAN ---------\n')
fout_times.write(' t_min t_max t_sub_eval t_eval t_down_pred t_inst_noref t_inst_ref t_sub_proj t_proj\n')
fout_times.write('%f %f %f %f %f %f %f %f %f\n' % (times_mean[0], times_mean[1], times_mean[2], times_mean[3], times_mean[4], times_mean[5], times_mean[6], times_mean[7], times_mean[8]))
fout_times.close()
else:
print("PC discarted as n_points < 200000")
|
[
"os.mkdir",
"os.remove",
"argparse.ArgumentParser",
"numpy.amin",
"numpy.argmax",
"os.walk",
"indoor3d_util.get_info_classes",
"numpy.mean",
"os.path.join",
"sys.path.append",
"os.path.abspath",
"indoor3d_util.room2blocks_plus_normalized_parsed",
"os.path.dirname",
"os.path.exists",
"project_inst.project_inst",
"numpy.loadtxt",
"numpy.random.choice",
"re.search",
"os.path.basename",
"numpy.hstack",
"get_instances.get_instances",
"numpy.squeeze",
"numpy.delete",
"numpy.vstack",
"time.time",
"numpy.amax"
] |
[((112, 137), 'os.path.dirname', 'os.path.dirname', (['BASE_DIR'], {}), '(BASE_DIR)\n', (127, 137), False, 'import os\n'), ((138, 163), 'sys.path.append', 'sys.path.append', (['BASE_DIR'], {}), '(BASE_DIR)\n', (153, 163), False, 'import sys\n'), ((455, 480), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (478, 480), False, 'import argparse\n'), ((1154, 1204), 'os.path.join', 'os.path.join', (['parsed_args.model_path', '"""model.ckpt"""'], {}), "(parsed_args.model_path, 'model.ckpt')\n", (1166, 1204), False, 'import os\n'), ((1359, 1416), 'os.path.join', 'os.path.join', (['parsed_args.model_path', "('dump_' + test_name)"], {}), "(parsed_args.model_path, 'dump_' + test_name)\n", (1371, 1416), False, 'import os\n'), ((1503, 1543), 'indoor3d_util.get_info_classes', 'indoor3d_util.get_info_classes', (['path_cls'], {}), '(path_cls)\n', (1533, 1543), False, 'import indoor3d_util\n'), ((74, 99), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (89, 99), False, 'import os\n'), ((1424, 1449), 'os.path.exists', 'os.path.exists', (['dump_path'], {}), '(dump_path)\n', (1438, 1449), False, 'import os\n'), ((1451, 1470), 'os.mkdir', 'os.mkdir', (['dump_path'], {}), '(dump_path)\n', (1459, 1470), False, 'import os\n'), ((1774, 1791), 'numpy.squeeze', 'np.squeeze', (['label'], {}), '(label)\n', (1784, 1791), True, 'import numpy as np\n'), ((2534, 2560), 'numpy.vstack', 'np.vstack', (['pred_label_list'], {}), '(pred_label_list)\n', (2543, 2560), True, 'import numpy as np\n'), ((2645, 2674), 'numpy.delete', 'np.delete', (['data', '[0, 1, 2]', '(1)'], {}), '(data, [0, 1, 2], 1)\n', (2654, 2674), True, 'import numpy as np\n'), ((2905, 2942), 'numpy.hstack', 'np.hstack', (['[data, pred_label_stacked]'], {}), '([data, pred_label_stacked])\n', (2914, 2942), True, 'import numpy as np\n'), ((2359, 2381), 'numpy.argmax', 'np.argmax', (['pred_val', '(2)'], {}), '(pred_val, 2)\n', (2368, 2381), True, 'import numpy as np\n'), ((4014, 4032), 'os.walk', 'os.walk', (['path_data'], {}), '(path_data)\n', (4021, 4032), False, 'import os\n'), ((4200, 4231), 're.search', 're.search', (['"""\\\\.(txt)$"""', 'file[1]'], {}), "('\\\\.(txt)$', file[1])\n", (4209, 4231), False, 'import re\n'), ((4372, 4399), 'os.path.join', 'os.path.join', (['root', 'file[1]'], {}), '(root, file[1])\n', (4384, 4399), False, 'import os\n'), ((4438, 4458), 'numpy.loadtxt', 'np.loadtxt', (['filepath'], {}), '(filepath)\n', (4448, 4458), True, 'import numpy as np\n'), ((4516, 4535), 'os.remove', 'os.remove', (['filepath'], {}), '(filepath)\n', (4525, 4535), False, 'import os\n'), ((5080, 5153), 'numpy.random.choice', 'np.random.choice', (['data_label_full.shape[0]', 'n_idx_full_sub'], {'replace': '(False)'}), '(data_label_full.shape[0], n_idx_full_sub, replace=False)\n', (5096, 5153), True, 'import numpy as np\n'), ((5269, 5280), 'time.time', 'time.time', ([], {}), '()\n', (5278, 5280), False, 'import time\n'), ((5515, 5526), 'time.time', 'time.time', ([], {}), '()\n', (5524, 5526), False, 'import time\n'), ((5607, 5618), 'time.time', 'time.time', ([], {}), '()\n', (5616, 5618), False, 'import time\n'), ((5747, 5758), 'time.time', 'time.time', ([], {}), '()\n', (5756, 5758), False, 'import time\n'), ((5839, 5850), 'time.time', 'time.time', ([], {}), '()\n', (5848, 5850), False, 'import time\n'), ((5897, 6088), 'indoor3d_util.room2blocks_plus_normalized_parsed', 'indoor3d_util.room2blocks_plus_normalized_parsed', (['data_label_full_sub', 'xyz_max', 'points_sub'], {'block_size': 'block_sub', 'stride': 'stride_sub', 'random_sample': '(False)', 'sample_num': 'None', 'sample_aug': '(1)'}), '(data_label_full_sub,\n xyz_max, points_sub, block_size=block_sub, stride=stride_sub,\n random_sample=False, sample_num=None, sample_aug=1)\n', (5945, 6088), False, 'import indoor3d_util\n'), ((6141, 6152), 'time.time', 'time.time', ([], {}), '()\n', (6150, 6152), False, 'import time\n'), ((6238, 6249), 'time.time', 'time.time', ([], {}), '()\n', (6247, 6249), False, 'import time\n'), ((6561, 6572), 'time.time', 'time.time', ([], {}), '()\n', (6570, 6572), False, 'import time\n'), ((9070, 9081), 'time.time', 'time.time', ([], {}), '()\n', (9079, 9081), False, 'import time\n'), ((9124, 9215), 'get_instances.get_instances', 'get_instances.get_instances', (['pred_sub', 'labels', 'dim', 'rad_p', 'dim', 'rad_v', 'min_p'], {'ref': '(False)'}), '(pred_sub, labels, dim, rad_p, dim, rad_v, min_p,\n ref=False)\n', (9151, 9215), False, 'import get_instances\n'), ((9265, 9276), 'time.time', 'time.time', ([], {}), '()\n', (9274, 9276), False, 'import time\n'), ((9364, 9375), 'time.time', 'time.time', ([], {}), '()\n', (9373, 9375), False, 'import time\n'), ((9416, 9506), 'get_instances.get_instances', 'get_instances.get_instances', (['pred_sub', 'labels', 'dim', 'rad_p', 'dim', 'rad_v', 'min_p'], {'ref': '(True)'}), '(pred_sub, labels, dim, rad_p, dim, rad_v, min_p,\n ref=True)\n', (9443, 9506), False, 'import get_instances\n'), ((9554, 9565), 'time.time', 'time.time', ([], {}), '()\n', (9563, 9565), False, 'import time\n'), ((14137, 14164), 'numpy.mean', 'np.mean', (['times_list'], {'axis': '(0)'}), '(times_list, axis=0)\n', (14144, 14164), True, 'import numpy as np\n'), ((14202, 14223), 'numpy.vstack', 'np.vstack', (['times_list'], {}), '(times_list)\n', (14211, 14223), True, 'import numpy as np\n'), ((5315, 5351), 'numpy.amin', 'np.amin', (['data_label_full_sub'], {'axis': '(0)'}), '(data_label_full_sub, axis=0)\n', (5322, 5351), True, 'import numpy as np\n'), ((5653, 5689), 'numpy.amax', 'np.amax', (['data_label_full_sub'], {'axis': '(0)'}), '(data_label_full_sub, axis=0)\n', (5660, 5689), True, 'import numpy as np\n'), ((7555, 7566), 'time.time', 'time.time', ([], {}), '()\n', (7564, 7566), False, 'import time\n'), ((7872, 7943), 'numpy.random.choice', 'np.random.choice', (['pred_sub.shape[0]', 'n_idx_pred_sub_down'], {'replace': '(False)'}), '(pred_sub.shape[0], n_idx_pred_sub_down, replace=False)\n', (7888, 7943), True, 'import numpy as np\n'), ((8078, 8089), 'time.time', 'time.time', ([], {}), '()\n', (8087, 8089), False, 'import time\n'), ((14267, 14303), 'os.path.join', 'os.path.join', (['dump_path', '"""times.txt"""'], {}), "(dump_path, 'times.txt')\n", (14279, 14303), False, 'import os\n'), ((11547, 11558), 'time.time', 'time.time', ([], {}), '()\n', (11556, 11558), False, 'import time\n'), ((11693, 11766), 'numpy.random.choice', 'np.random.choice', (['data_label_full_sub.shape[0]', 'n_idx_proj'], {'replace': '(False)'}), '(data_label_full_sub.shape[0], n_idx_proj, replace=False)\n', (11709, 11766), True, 'import numpy as np\n'), ((12039, 12050), 'time.time', 'time.time', ([], {}), '()\n', (12048, 12050), False, 'import time\n'), ((12152, 12163), 'time.time', 'time.time', ([], {}), '()\n', (12161, 12163), False, 'import time\n'), ((12210, 12261), 'project_inst.project_inst', 'project_inst.project_inst', (['instances_ref', 'data_proj'], {}), '(instances_ref, data_proj)\n', (12235, 12261), False, 'import project_inst\n'), ((12300, 12311), 'time.time', 'time.time', ([], {}), '()\n', (12309, 12311), False, 'import time\n'), ((6706, 6732), 'os.path.basename', 'os.path.basename', (['filepath'], {}), '(filepath)\n', (6722, 6732), False, 'import os\n'), ((6829, 6855), 'os.path.basename', 'os.path.basename', (['filepath'], {}), '(filepath)\n', (6845, 6855), False, 'import os\n'), ((9684, 9710), 'os.path.basename', 'os.path.basename', (['filepath'], {}), '(filepath)\n', (9700, 9710), False, 'import os\n'), ((9813, 9839), 'os.path.basename', 'os.path.basename', (['filepath'], {}), '(filepath)\n', (9829, 9839), False, 'import os\n'), ((12624, 12650), 'os.path.basename', 'os.path.basename', (['filepath'], {}), '(filepath)\n', (12640, 12650), False, 'import os\n'), ((12759, 12785), 'os.path.basename', 'os.path.basename', (['filepath'], {}), '(filepath)\n', (12775, 12785), False, 'import os\n'), ((13595, 13621), 'os.path.basename', 'os.path.basename', (['filepath'], {}), '(filepath)\n', (13611, 13621), False, 'import os\n')]
|
"""Module that contains the tools to open and retrieve raster properties and statistics.
Classes:
ImgManagerError.
ImgManager.
"""
import logging
import gettext
import numpy as np
from osgeo import gdal
from controls.imagery_controls.results import WorldFileData
class RasterManagerError(Exception):
"""Exception for RasterManager."""
class RasterManager:
"""Class to open and retrieve raster properties and statistics.
Attributes:
conn_params: PGDBConnection instance containing server host, port and database name.
cred_params: PGDBCredentials instance containing username and password.
logger: Logging object.
conn: Connection to database.
cursor: Cursor of connection to database.
"""
def __init__(self, raster=None, logger=None):
# internal
self._ = gettext.gettext
# parameters
self.logger = logger or logging.getLogger(__name__)
self.raster = raster
try:
self.dataset = gdal.Open(self.raster)
except RuntimeError:
msg = '{}'.format(self._('Cannot open image'))
self.logger.error(msg, exc_info=True)
raise RasterManagerError(msg)
self.geo_transform = self.dataset.GetGeoTransform()
self.wfd = WorldFileData(
pixel_size=[self.geo_transform[1], self.geo_transform[5]],
rotation=[self.geo_transform[4], self.geo_transform[2]]
)
def get_dataset(self):
"""Returns the raster dataset.
Returns:
Raster dataset.
Raises:
RasterManagerError
"""
return self.dataset
def get_raster_band(self, no_):
"""Returns a band of the raster dataset.
Returns:
Raster dataset band no_.
Raises:
RasterManagerError
"""
band = None
try:
band = self.dataset.GetRasterBand(no_)
except RuntimeError:
msg = '{}'.format(self._('Cannot retrieve raster band'))
self.logger.error(msg, exc_info=True)
raise RasterManagerError(msg)
return band
def get_raster_units_per_pixel(self):
"""Returns the units per pixel (cell size) of the raster.
Returns:
Two values list with width and height units.
Raises:
RasterManagerError
"""
return self.wfd.get_units_per_pixel()
def get_raster_bands_len(self):
"""Returns the number of bands of the raster.
Returns:
An integer.
Raises:
RasterManagerError
"""
bands_len = None
try:
bands_len = self.dataset.RasterCount
except RuntimeError:
msg = '{}'.format(self._('Cannot retrieve raster bands len'))
self.logger.error(msg, exc_info=True)
raise RasterManagerError(msg)
return bands_len
def get_raster_bands_datatype(self):
"""Returns the data type of the bands of the raster.
Returns:
List of integers.
Raises:
RasterManagerError
"""
bands_dt = []
try:
for r__ in range(self.dataset.RasterCount):
band = self.get_raster_band(r__ + 1)
bands_dt.append(band.DataType)
except RasterManagerError as err:
raise err
except RuntimeError:
msg = '{}'.format(self._('Cannot retrieve raster bands len'))
self.logger.error(msg, exc_info=True)
raise RasterManagerError(msg)
return bands_dt
def get_raster_bands_rad_balance(self, deviation):
"""Returns the statistics for the radiometric balace of the bands of the raster.
Returns:
List of list of integers.
Raises:
RasterManagerError
"""
bands_stats = []
try:
for r__ in range(self.dataset.RasterCount):
band = self.get_raster_band(r__ + 1)
stats = band.GetStatistics(True, True)
rmin = stats[0] * (1 + deviation)
rmax = stats[1] * (1 - deviation)
band_arr = band.ReadAsArray(
0,
0,
self.dataset.RasterXSize,
self.dataset.RasterYSize
).astype(np.float)
cmin = np.count_nonzero(band_arr < rmin)
cmax = np.count_nonzero(band_arr > rmax)
cval = self.dataset.RasterXSize * self.dataset.RasterYSize
bands_stats.append([
stats[0],
stats[1],
rmin,
rmax,
cmin,
cmax,
round(cmin/cval, 6) * 100,
round(cmax/cval, 6) * 100
])
except RasterManagerError as err:
raise err
except RuntimeError:
msg = '{}'.format(self._('Cannot retrieve raster bands len'))
self.logger.error(msg, exc_info=True)
raise RasterManagerError(msg)
return bands_stats
def get_raster_bands_nodata(self):
"""Returns the statistics for no data of the bands of the raster.
Returns:
List of list of integers.
Raises:
RasterManagerError
"""
bands_nodata = []
try:
for r__ in range(self.dataset.RasterCount):
band = self.get_raster_band(r__ + 1)
nodata = band.GetNoDataValue()
band_arr = band.ReadAsArray(
0,
0,
self.dataset.RasterXSize,
self.dataset.RasterYSize
).astype(np.float)
cnd = np.count_nonzero(band_arr == nodata)
cval = self.dataset.RasterXSize * self.dataset.RasterYSize
pnd = round(cnd/cval, 6)
bands_nodata.append(pnd*100)
except RasterManagerError as err:
raise err
except RuntimeError:
msg = '{}'.format(self._('Cannot retrieve raster bands len'))
self.logger.error(msg, exc_info=True)
raise RasterManagerError(msg)
return bands_nodata
|
[
"numpy.count_nonzero",
"osgeo.gdal.Open",
"controls.imagery_controls.results.WorldFileData",
"logging.getLogger"
] |
[((1198, 1331), 'controls.imagery_controls.results.WorldFileData', 'WorldFileData', ([], {'pixel_size': '[self.geo_transform[1], self.geo_transform[5]]', 'rotation': '[self.geo_transform[4], self.geo_transform[2]]'}), '(pixel_size=[self.geo_transform[1], self.geo_transform[5]],\n rotation=[self.geo_transform[4], self.geo_transform[2]])\n', (1211, 1331), False, 'from controls.imagery_controls.results import WorldFileData\n'), ((863, 890), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (880, 890), False, 'import logging\n'), ((946, 968), 'osgeo.gdal.Open', 'gdal.Open', (['self.raster'], {}), '(self.raster)\n', (955, 968), False, 'from osgeo import gdal\n'), ((3876, 3909), 'numpy.count_nonzero', 'np.count_nonzero', (['(band_arr < rmin)'], {}), '(band_arr < rmin)\n', (3892, 3909), True, 'import numpy as np\n'), ((3925, 3958), 'numpy.count_nonzero', 'np.count_nonzero', (['(band_arr > rmax)'], {}), '(band_arr > rmax)\n', (3941, 3958), True, 'import numpy as np\n'), ((5033, 5069), 'numpy.count_nonzero', 'np.count_nonzero', (['(band_arr == nodata)'], {}), '(band_arr == nodata)\n', (5049, 5069), True, 'import numpy as np\n')]
|
import numpy as np
import pandas as pd
from copy import deepcopy as dc
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.cm as cm
from tqdm import tqdm_notebook as tqdm
import XPyS
from .helper_functions import index_of, guess_from_data
import XPyS.config as cfg
import os
from sklearn.decomposition import PCA, NMF
from scipy.stats import pearsonr
from scipy.interpolate import interp1d
from scipy.optimize import curve_fit
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.model_selection import train_test_split
import matplotlib.patches as mpatches
import decimal
class HellaSpectra:
"""
Class for holding lots of spectra objects as well as their spectra in matrix and dataframe format. Used
for statistical analysis and data exploration.
"""
def __init__(self,spectra_objects, spectra=None):
self.info = []
self.spectra_objects = spectra_objects
"""
Parameters
----------
spectra_objects: dictionary
dictionary of spectra objects. Keys are sample names or any identifier and values are XPyS.spectra.spectra object insances
Notes
-----
Examples
--------
"""
def bgsuball(self,subpars):
"""
Calls bg_sub on all the spectra objects held in self.spectra_objects
Parameters
----------
subpars: list
list of the background subtraction parameters. See spectra.bg_sub
"""
for sample in self.spectra_objects.items():
try:
sample[1].bg_sub(subpars=subpars)
except:
print('Could Not bg_sub ',sample[0])
def _get_xnew(self,emin=None,emax=None,step = 0.1):
"""Get the interpolation positions of the energy
Parameters
----------
emin: int,float
minimum binding energy value
emax: int,float
maximum binding energy value
step: int, float
step between binding energies
"""
# print('2')
ynew = None
if self.spectra_type == 'raw':
if (emin == None) and (emax != None):
# print('2.1')
emin, _emax = self._auto_bounds()
elif (emin != None) and (emax == None):
# print('2.2')
_emin, emax = self._auto_bounds()
elif (emin == None) and (emax == None):
# print('2.3')
emin, emax = self._auto_bounds()
self._check_bounds(emin,emax)
xnew = np.arange(emin, emax, step)
elif self.spectra_type == 'sub':
# print('2.4')
emin,emax = self._auto_bounds()
self._check_bounds(emin,emax)
xnew = np.arange(emin, emax, step)
# round the interpolation Binding Energies off to the thousandth
xnew = np.round(xnew,3)
return xnew
# probably want to make the spacing even given by ev step 0.1 but fuck it for now.
# print(emin,emax)
# xnew = np.arange(emin, emax+step, step)
# d = decimal.Decimal(str(step)).as_tuple().exponent
# if d < 0:
# xnew = np.round(xnew,-1*d)
# print(np.min(xnew),np.max(xnew))
# try:
# first = True
def _interp_and_build(self,emin=None,emax=None,step = 0.1):
"""Interpolate the spectra to all have the same binding energies using _get_xnew then build the
spectra and the params dataframes.
Parameters
----------
emin: int,float
minimum binding energy value
emax: int,float
maximum binding energy value
step: int, float
step between binding energies
"""
ynew = None
self.energy = self._get_xnew(emin=emin,emax=emax,step = 0.1)
df_list = []
df_params_list = []
start_idx = 0
for name,spectra_obj in self.spectra_objects.items():
n_data = len(spectra_obj.__dict__[self.dset[1]])
idx_id = np.arange(start_idx,start_idx+n_data) # Need an index id to perform joins on different dataframes
start_idx = start_idx+n_data
first = True
# Spectra DataFrame
for i in range(n_data):
f = interp1d(spectra_obj.__dict__[self.dset[0]], spectra_obj.__dict__[self.dset[1]][i],kind = 'cubic')
if not first:
ynew = np.vstack((ynew,f(self.energy)))
else:
ynew = f(self.energy)
first = False
if self.target != None:
df_list.append(pd.DataFrame(ynew,index = [[self.target[name]]*n_data,[name]*n_data,idx_id]))
else:
df_list.append(pd.DataFrame(ynew,index = [[0]*n_data,[name]*n_data,idx_id]))
# Parameters DataFrame
if hasattr(spectra_obj,'fit_results'):
_dd = {key: [spectra_obj.fit_results[i].params.valuesdict()[key] \
for i in range(len(spectra_obj.fit_results))] \
for key in spectra_obj.fit_results[0].params.valuesdict().keys()}
if self.target != None:
df_params_list.append(pd.DataFrame(_dd,index = [[self.target[name]]*n_data,[name]*n_data,idx_id]))
else:
df_params_list.append(pd.DataFrame(_dd,index = [[0]*len(spectra_obj.fit_results),[name]*len(spectra_obj.fit_results),idx_id]))
df_spectra = pd.concat(df_list)
df_spectra.columns = self.energy
df_params = pd.concat(df_params_list)
# Add names to the indices
# if self.target != None:
df_spectra.index.set_names(['target', 'name','id'], inplace=True)
df_params.index.set_names(['target', 'name','id'], inplace=True)
# else:
# df_spectra.index.set_names(['id', 'name'], inplace=True)
# df_params.index.set_names(['id', 'name'], inplace=True)
return df_spectra, df_params
def _auto_bounds(self):
"""Search through the spectra to get bounds for the interpolation since some spectra have
different binding energy ranges
"""
largest_min_value = np.max([np.min(so[1].__dict__[self.dset[0]]) for so in self.spectra_objects.items()])
smallest_max_value = np.min([np.max(so[1].__dict__[self.dset[0]]) for so in self.spectra_objects.items()])
emin = (np.round(100*largest_min_value,2)+1)/100
emax = (np.round(100*smallest_max_value,2)-1)/100
return emin,emax
def _check_bounds(self,min_bnd,max_bnd):
"""check to make sure the bounds are not outside the binding energies of any of the spectra"""
check_min = [so[0] for so in self.spectra_objects.items() if not np.min(np.round(so[1].__dict__[self.dset[0]],2)) <= min_bnd <=np.max(np.round(so[1].__dict__[self.dset[0]],2))]
check_max = [so[0] for so in self.spectra_objects.items() if not np.min(np.round(so[1].__dict__[self.dset[0]],2)) <= max_bnd <=np.max(np.round(so[1].__dict__[self.dset[0]],2))]
if check_min !=[]:
raise ValueError('The specified bounds are outside the minimum values for', check_min )
if check_max != []:
raise ValueError('The specified bounds are outside the maximum values for', check_max )
def build_dataframes(self,emin=None,emax=None,spectra_type = 'raw',subpars = None,step = 0.1,target = None):
"""
Build a 2d array of all of the spectra from the spectra objects
Parameters
----------
emin: int,float
minimum binding energy value
emax: int,float
maximum binding energy value
spectra_type: str
Option to interpolate the raw data or backgroudn subtracted data. ('raw' or 'sub')
subpars: list
list of the background subtraction parameters. See spectra.bg_sub
step: int, float
step between binding energies
target: dict, None
Dictionary of the target
"""
self.spectra_type = spectra_type
self.target = target
if target != None:
if sorted(list(self.spectra_objects.keys())) != sorted(list(self.target.keys())):
raise KeyError('There is a spectra object that is not in the target dictionary')
if self.spectra_type == 'sub':
self.dset = ['esub','isub']
if subpars == None:
raise ValueError('You must specify subpars')
self.bgsuball(subpars = subpars)
elif self.spectra_type == 'raw':
self.dset = ['E','I']
self.spectra, self.params = self._interp_and_build(emin = emin, emax = emax,step = step)
self._spectra = self.spectra
def reset(self):
"""Reset spectra array and dataframe to initial loaded states"""
self.spectra = dc(self._spectra)
self.info = []
def normalize(self):
"""Normalize all of the spectra"""
_yN = np.empty(self.spectra.values.shape)
for i in range(len(_yN)):
_yN[i,:] = self.spectra.values[i,:]/np.trapz(self.spectra.values[i,:])
self.spectra = pd.DataFrame(_yN,columns = self.spectra.columns,index = self.spectra.index)
self._update_info('Normalized')
def plot_spectra(self,offset = 0,target = None, avg = False):
"""
Plot all the spectra
Parameters
----------
offset: int, float
offset each spectra by set amount or stacked display
avg: bool
Option to plot mean spectra. Default False
"""
if target == None:
spectra_to_plot = self.spectra.values
elif target != None:
if not target in self.spectra.index.levels[0]:
raise ValueError('target not in index')
spectra_to_plot = self.spectra.xs(target,level = 'target').values
fig, ax = plt.subplots()
if not avg:
for i in range(len(spectra_to_plot)):
ax.plot(self.energy,spectra_to_plot[i,:]+i*offset)
if avg:
ax.plot(self.energy,spectra_to_plot.mean(axis=0))
ax.set_xlabel('Binding Energy',fontsize = 15)
if 'Normalized' in self.info:
ax.set_ylabel('Counts/sec (N.U.)',fontsize = 15)
else:
ax.set_ylabel('Counts/sec',fontsize = 15)
def _update_info(self,message):
"""Update order of operations on the spectra array to keep track processing history"""
if self.info != []:
if self.info[-1] == message:
return
else:
self.info.append(message)
else:
self.info.append(message)
def peak_tracker(self,peak_pos,energy= None,spectra_matrix=None,plotflag = True,**kws):
"""
Get the peak positions for all the spectra using guess_from_data() in helper_functions module.
Then plot the differences in the peak positions from the peak_pos parameter
Parameters
----------
peak_pos: int, float
Guess position of the peak. guess_from_data() will search in vicinity for the maximum
"""
if energy ==None:
energy = self.energy
if spectra_matrix == None:
spectra_matrix = self.spectra.values
cen = np.empty(len(spectra_matrix))
amp = np.empty(len(spectra_matrix))
for i in range(len(spectra_matrix)):
amp[i],cen[i] = guess_from_data(energy,spectra_matrix[i],peakpos = peak_pos,**kws)
self.peaktrack = cen-peak_pos
if plotflag:
plt.plot(self.peaktrack,'o-')
def align_peaks(self,peak_pos,plotflag = True,**kws):
"""
Align all the peaks. Will search for maximum of peak aroudn peak_pos and then adjust spectra to peak_pos
Parameters
----------
peak_pos: int, float
Guess position of the peak. guess_from_data() will search in vicinity for the maximum
"""
spectra_matrix = self.spectra.values
cen = np.empty(len(spectra_matrix))
amp = np.empty(len(spectra_matrix))
mv_spec = np.empty([len(spectra_matrix),len(self.energy)])
for i in range(len(spectra_matrix)):
amp[i],cen[i] = guess_from_data(self.energy,spectra_matrix[i],peakpos = peak_pos,**kws)
mv_ev = np.round(cen[i] - peak_pos,2)
mv_pts = np.int(mv_ev*(len(self.energy)/(self.energy[-1] - self.energy[0])))
if mv_pts ==0:
mv_spec[i] = spectra_matrix[i]
elif mv_pts > 0:
mv_spec[i] = np.asarray(list(spectra_matrix[i][mv_pts:]) + [0]*mv_pts)
elif mv_pts < 0:
mv_spec[i] = np.asarray([0]*np.abs(mv_pts)+list(spectra_matrix[i][:mv_pts]))
if plotflag:
fig,ax = plt.subplots()
for i in range(len(spectra_matrix)):
ax.plot(self.energy,mv_spec[i])
ax.set_xlabel('Binding Energy',fontsize = 15)
if 'Normalized' in self.info:
ax.set_ylabel('Counts/sec (N.U.)',fontsize = 15)
else:
ax.set_ylabel('Counts/sec',fontsize = 15)
plt.axvline(self.energy[index_of(self.energy,peak_pos)])
self.aligned_pos = peak_pos
self.spectra = pd.DataFrame(mv_spec,columns = self.spectra.columns,index = self.spectra.index)
self._update_info('adjusted to '+str(peak_pos))
def par_histogram(self,pars):
"""
Create a histogram of the desired input parameters
Parameters
----------
pars: list
list of strings of the parameters to get histograms of distribution
"""
def gaussian(x, mean, amplitude, standard_deviation):
return amplitude * np.exp( - (x - mean)**2 / (2*standard_deviation ** 2))
fig,ax = plt.subplots(figsize = (12,8))
prefix = ['_'.join(p.split('_')[:-1])+'_' for p in pars]
# If the prefix is stored in gui_element_dicts use that color, otherwise create colors
if all(elem in list(cfg.element_color.keys()) for elem in prefix):
colors = [cfg.element_color[prefix[i]] for i in range(len(pars))]
else:
colormap = plt.cm.nipy_spectral
colors = [colormap(i) for i in np.linspace(0, 1,len(pars))]
ax.set_prop_cycle('color', colors)
center_stats = {}
for par in enumerate(pars):
bin_heights, bin_borders, _ = ax.hist(self.params[par[1]].values, bins='auto', label='histogram',color=colors[par[0]])
try:
bin_centers = bin_borders[:-1] + np.diff(bin_borders) / 2
center_stats[par[1]], _ = curve_fit(gaussian, bin_centers, bin_heights, p0=[self.params[par[1]].values.mean(), 40, 0.5])
x_interval_for_fit = np.linspace(bin_borders[0]-1, bin_borders[-1]+1, 10000)
ax.plot(x_interval_for_fit, gaussian(x_interval_for_fit, *center_stats[par[1]]), label='fit',color=colors[par[0]])
except:
print('Gaussian not good for ',par)
for item in ([ax.title, ax.xaxis.label, ax.yaxis.label] +
ax.get_xticklabels() + ax.get_yticklabels()):
item.set_fontsize(24)
ax.legend(pars,fontsize = '16')
leg_patches = []
for p in enumerate(pars):
leg_patches.append(mpatches.Patch(color=colors[p[0]], label=p[1]))
ax.legend(handles=leg_patches,bbox_to_anchor=(1.05, 0.5), loc='upper left',fontsize = 18)
return fig, ax
## Using dictionary
def make_spectra(self,spectra_model,number):
"""
Make a bunch of simulated spectra using the parameters in the dataframe as bounds. Useful for training
Machine Learning Models
Parameters
----------
params: lmfit Parameters object
Parameters object to be used to evaluate the model function
mod: lmfit Model object
Model object to be used to evaluate the parameters
pairlist: list of tuples
pairlist of prefixes in model object
number: int
number of spectra to create
"""
params = spectra_model.pars
mod = spectra_model.model
pairlist = spectra_model.pairlist
spec_train = []
par_train = []
par_train_row = []
pars = [pars for pars in [par for component_pars in [model_component._param_names for model_component in mod.components] \
for par in component_pars if any([p[0] in par for p in pairlist])] if not 'skew' in pars and not 'fraction' in pars]
randpar = {par:[] for par in pars}
for i in tqdm(range(number)):
for par in pars:
if ('amplitude' in par) or ('sigma' in par):
_randpar = np.min(self.df_params[par].values) + (np.max(self.df_params[par].values)-np.min(self.df_params[par].values))*np.random.rand()
randpar[par].append(_randpar)
params[par].set(_randpar)
if 'center' in par:
# if par == 'Nb_52_center':
# variation = 0.005
# else:
# variation = 0.01
# _randpar = center_stats[par][0] + 0.1*randn()
# _randpar = center_stats[par][0] + center_stats[par][2]*randn()
_randpar = np.min(self.df_params[par].values) + (np.max(self.df_params[par].values)-np.min(self.df_params[par].values))*np.random.rand()
randpar[par].append(_randpar)
params[par].set(_randpar)
spec_train.append(mod.eval(params = params,x= self.energy))
spec_train = np.asarray(spec_train)
return spec_train, randpar
# Dimensionality Reduction
def pca(self,n_pca = 3):
"""
Perform Principal Component Analysis on the spectra and plot the principal components
Parameters
----------
n_pca: int
number of principal components to evaluate
"""
self.n_pca = n_pca
pca = PCA(n_components=self.n_pca)
# PCA of raw signal
X_r = pca.fit(self.spectra.values)
X_tr = pca.fit_transform(self.spectra.values)
if self.info != []:
print(' '.join(self.info))
print('explained variance ratio: %s'
% str(pca.explained_variance_ratio_ *100 ) )
print('cumulative variance: %s'
% str(np.cumsum(pca.explained_variance_ratio_ *100) ) )
self.pc_names = ['pc{}'.format(i) for i in range(1,self.n_pca+1)]
# Build Dictionary of principal components
pc = {self.pc_names[i] : X_tr[:,i] for i in range(len(self.pc_names))}
self.pc = pd.DataFrame(pc,index = self.spectra.index)
self.pc_vec = X_r.components_
self._plotpcavecs()
def _plotpcavecs(self):
fig,ax = plt.subplots()
for i in range(self.n_pca):
ax.plot(self.pc_vec[i,:])
ax.legend(self.pc_names,bbox_to_anchor=(1.05, 1), loc='upper left',fontsize = 18)
ax.set_title('Raw Data',fontsize = 18)
for item in ([ax.title, ax.xaxis.label, ax.yaxis.label] +
ax.get_xticklabels() + ax.get_yticklabels()):
item.set_fontsize(18)
def plotpca(self,x = 'pc1',y = 'pc2',z=None):
if z is None:
self._plot_dimred_2D(x,y,self.pc)
else:
self._plot_dimred_3D(x,y,z,self.pc)
def _plot_dimred_2D(self,x,y,df):
"""
Plot 2d scatter plot of principal components
Parameters
----------
x: str 'pc1','pc2','nmf1','nmf2',...etc
dimensionality reduction component to plot on x-axis
y: str 'pc1','pc2','nmf1','nmf2',...etc
dimensionality reduction component to plot on y-axis
"""
fig,(ax1,ax2) = plt.subplots(1,2,figsize = (18,6))
sample_names = list(df.index.levels[1])
n_samples=len(sample_names)
n_targets = len(df.index.levels[0])
colormap = plt.cm.nipy_spectral
colors = [colormap(i) for i in np.linspace(0, 1,n_samples)]
colors_targets = [colormap(i) for i in np.linspace(0, 1,n_targets)]
ax1.set_prop_cycle('color', colors)
ax2.set_prop_cycle('color', colors_targets)
# First plot the principal components color coded by sample
for sample in sample_names:
ax1.plot(df.xs(sample,level = 'name')[x].values,df.xs(sample,level = 'name')[y].values,'o',markersize = 10)
# Next plot the principal components color coded by target
for target in df.index.levels[0]: # Level 0 is the target level
ax2.plot(df.xs(target,level = 'target')[x].values,df.xs(target,level = 'target')[y].values,'o',markersize = 10)
if 'pc' in x:
title = 'principal Components'
elif 'nmf' in x:
title = 'Non-Negative Matrix Factorization'
for ax in [ax1, ax2]:
ax.set_title(title)
ax.set_xlabel(x)
ax.set_ylabel(y)
ax.tick_params('x',labelrotation=80)
for item in ([ax.title, ax.xaxis.label, ax.yaxis.label] +\
ax.get_xticklabels() + ax.get_yticklabels()):
item.set_fontsize(20)
ax1.legend(list(self.spectra_objects.keys()),bbox_to_anchor=(1.05, 1.2), loc='upper left',fontsize = 18)
leg_patches = []
for tar in enumerate(df.index.levels[0]):
leg_patches.append(mpatches.Patch(color=colors_targets[tar[0]], label=tar[1]))
ax2.legend(handles=leg_patches,bbox_to_anchor=(1.05, 0.5), loc='upper left',fontsize = 18)
fig.tight_layout()
def _plot_dimred_3D(self,X, Y, Z, df):
"""
Plot 3d scatter plot of principal components
Parameters
----------
x: str 'P1','P2',...etc
principal component to plot on x-axis, Default 'P1'
y: str 'P1','P2',...etc
principal component to plot on y-axis, Default 'P2'
z: str 'P1','P2',...etc
principal component to plot on z-axis, Default 'P3'
"""
fig = plt.figure(figsize = (12,5))
ax1 = fig.add_subplot(1, 2, 1, projection='3d')
ax2 = fig.add_subplot(1, 2, 2, projection='3d')
sample_names = list(df.index.levels[1])
n_samples=len(sample_names)
n_targets = len(df.index.levels[0])
colormap = plt.cm.nipy_spectral
colors = [colormap(i) for i in np.linspace(0, 1,n_samples)]
colors_targets = [colormap(i) for i in np.linspace(0, 1,n_targets)]
ax1.set_prop_cycle('color', colors)
ax2.set_prop_cycle('color', colors_targets)
colormap = plt.cm.nipy_spectral
colors = [colormap(i) for i in np.linspace(0, 1,n_samples)]
colors_targets = [colormap(i) for i in np.linspace(0, 1,n_targets)]
ax1.set_prop_cycle('color', colors)
ax2.set_prop_cycle('color', colors_targets)
# First plot the principal components color coded by sample
for sample in sample_names:
ax1.plot(df.xs(sample,level = 'name')[X].values,df.xs(sample,level = 'name')[Y].values,df.xs(sample,level = 'name')[Z].values,'o',markersize = 10)
# Next plot the principal components color coded by target
for target in df.index.levels[0]: # Level 0 is the target level
ax2.plot(df.xs(target,level = 'target')[X].values,df.xs(target,level = 'target')[Y].values,df.xs(target,level = 'target')[Z].values,'o',markersize = 10)
for ax in [ax1,ax2]:
ax.set_xlabel(X,fontsize = 16)
ax.set_ylabel(Y,fontsize = 16)
ax.set_zlabel(Z,fontsize = 16)
# ax1.legend(list(self.spectra_objects.keys()),bbox_to_anchor=(1.05, 1.2), loc='upper left',fontsize = 18)
# leg_patches = []
# for tar in enumerate(self.pc.index.levels[0]):
# leg_patches.append(mpatches.Patch(color=colors_targets[tar[0]], label=tar[1]))
# ax2.legend(handles=leg_patches,bbox_to_anchor=(1.05, 0.5), loc='upper left',fontsize = 18)
fig.tight_layout()
def nmf(self,n_nmf = 3,**kws):
"""
Find Non-Negative Matrix Factorization of spectra
Parameters
----------
n_nmf: int
number of non-negative matrix components
nmf_kws: dict
keywords to pass to sklearn.decomposition.NMF
"""
self.n_nmf = n_nmf
if np.any(self.spectra.values < 0):
self.spectra.values[np.where(self.spectra.values < 0)] = 0
# Calculate NMF
model = NMF(n_components=self.n_nmf, random_state=0, **kws)
W = model.fit_transform(self.spectra)
self.H = model.components_
if self.info != []:
print(' '.join(self.info))
self.nmf_names = ['nmf{}'.format(i) for i in range(1,self.n_nmf+1)]
nmf = {self.nmf_names[i] : W[:,i] for i in range(len(self.nmf_names))}
self.W = pd.DataFrame(nmf,index = self.spectra.index)
self._plotnmfvecs()
def _plotnmfvecs(self):
fig,ax = plt.subplots()
for i in range(self.n_nmf):
ax.plot(self.H[i,:])
ax.legend(self.nmf_names,bbox_to_anchor=(1.05, 1), loc='upper left',fontsize = 18)
ax.set_title('Raw Data',fontsize = 18)
for item in ([ax.title, ax.xaxis.label, ax.yaxis.label] +
ax.get_xticklabels() + ax.get_yticklabels()):
item.set_fontsize(18)
def plotnmf(self,x = 'nmf1',y = 'nmf2',z=None):
if z is None:
self._plot_dimred_2D(x,y,self.W)
else:
self._plot_dimred_3D(x,y,z,self.W)
def be_corr(self,pars,plotflag = True):
"""
Find and plot correlation of a parameter against the Binding Energies for all the spectra
Parameters
----------
par: str
Parameter to correlate against Binding Energies
plotflag: bool
Option to plot. Default = True
"""
if not type(pars) is list:
raise TypeError('pars argument must be a list')
print(' '.join(self.info))
spec_and_params = self.spectra.join(self.params,how = 'inner')
self.BEcorrs = {}
for par in pars:
self.BEcorrs[par] = {}
self.BEcorrs[par]['pmax'] = spec_and_params.corr()[par].iloc[0:self.spectra.values.shape[1]].max()
self.BEcorrs[par]['emax'] = spec_and_params.corr()[par].iloc[0:self.spectra.values.shape[1]].idxmax()
# print('maximum correlation of',np.round(pmax,3),'at',np.round(emax,2))
if plotflag:
fig,axs = plt.subplots(len(self.BEcorrs.keys()),2,figsize = (12,4*len(self.BEcorrs.keys())))
axs = axs.ravel()
axi = 0
for par in self.BEcorrs.keys():
axs[axi].plot(self.energy,spec_and_params.corr()[par].iloc[0:self.spectra.values.shape[1]].values)
axs[axi].plot(self.BEcorrs[par]['emax'],self.BEcorrs[par]['pmax'],'x',marker = 'x',markersize = 15,mew = 5,color = 'black')
axs[axi].set_ylabel('p-value',fontsize = 14)
axs[axi].set_xlabel('B.E. (eV)',fontsize = 14)
axs[axi].set_title(par,fontsize = 14)
axi += 1
t = spec_and_params.corr()[par].iloc[0:self.spectra.values.shape[1]].values
sc = axs[axi].scatter(self.energy,self.spectra.values.mean(axis=0),c = t, cmap=cm.bwr, vmin=-1, vmax=1, s=100)
specmax_idx = index_of(self.energy,self.BEcorrs[par]['emax'])
axs[axi].plot(self.BEcorrs[par]['emax'],self.spectra.values.mean(axis=0)[specmax_idx],marker = 'x',markersize = 15,mew = 5,color = 'black')
axs[axi].set_ylabel('Counts/sec',fontsize = 14)
axs[axi].set_xlabel('B.E. (eV)',fontsize = 14)
fig.colorbar(sc,ax=axs[axi])
axi += 1
fig.tight_layout()
return fig, axs
def scattercorr(self,Xs,Ys):
"""
Plots the correllation scatter plots and finds the pearson p-number between the given parameters.
Parameters
----------
Xs: list
list of parameter names on x-axes
Ys: list
list of parameter names on y-axes
"""
fulldf = self.spectra.join(self.params,how = 'inner')
if hasattr(self,'pc'):
fulldf = fulldf.join(self.pc,how = 'inner')
if hasattr(self,'W'):
fulldf = fulldf.join(self.W,how = 'inner')
fig, axs = plt.subplots(len(Ys),len(Xs),figsize = (4*len(Xs),4*len(Ys)))
axs = axs.ravel()
ylabels = []
corrmat = np.empty([len(Ys),len(Xs)])
a = 0
for i in range(len(Ys)):
j =0
if type(Ys[i]) == float:
axs[a].set_ylabel(Ys[i],fontsize = 26)
else:
axs[a].set_ylabel(Ys[i],fontsize = 26)
for j in range(len(Xs)):
try:
axs[a].plot(fulldf[Xs[j]].values,fulldf[Ys[i]].values,'o')
corrmat[i][j], _ = pearsonr(fulldf[Xs[j]].values, fulldf[Ys[i]].values)
axs[a].set_title('Pearsons correlation: %.3f' % corrmat[i][j],fontsize = 16)
axs[a].set_xlabel(Xs[j],fontsize = 26)
axs[a].set_xticklabels('')
axs[a].set_yticklabels('')
a+=1
except:
pass
fig.tight_layout()
return fig, axs
def linfit(self,X,Y,plotflag = True):
"""
Linear regression of specified entries in self.df
Parameters
----------
Xs: list
list of x-axes df entries
Ys: list
list of y-axes df entries
"""
fulldf = self.spectra.join(self.params,how = 'inner')
if hasattr(self,'pc'):
fulldf = fulldf.join(self.pc,how = 'inner')
if hasattr(self,'W'):
fulldf = fulldf.join(self.W,how = 'inner')
# We can rewrite the line equation as y = Ap, where A = [[x 1]] and p = [[m], [b]]
autofitparlist = []
fig, axs = plt.subplots()
lfpars = {}
x = np.array(fulldf[X])
y = np.array(fulldf[Y])
A = np.hstack((x.reshape(-1,1), np.ones(len(x)).reshape(-1,1)))
lfpars['m'],lfpars['b'] = np.linalg.lstsq(A, y,rcond = None)[0]
# m = np.linalg.lstsq(x.reshape(-1,1), y,rcond = None)[0][0]
if plotflag == True:
axs.plot(x, y,'o')
axs.plot(x, lfpars['m']*x+lfpars['b'])
axs.set_xlabel(str(Y) + ' vs ' + str(X),fontsize = 14)
fig.tight_layout()
return lfpars, fig, axs
def split_spectra(self,test_size = 0.3):
"""
Split the spectra data into train and test arrays. Also create a target_array attribute
Parameters
----------
test_size: float
fraction of data to use to test the Decision boundary.
"""
self.target_array = self.spectra.index.get_level_values('target').values
return train_test_split(self.spectra.values, self.target_array, test_size=test_size)
def lda(self,test_size = 0.3):
"""
Perform Linear Discriminant Analysis on the spectra and plot the principal components
Parameters
----------
test_size: float
fraction of data to use to test the Decision boundary.
"""
self.spec_train, self.spec_test, self.target_train, self.target_test = self.split_spectra(test_size = test_size)
self.skit_lda = LinearDiscriminantAnalysis()
self.lda_trans = self.skit_lda.fit(self.spec_train, self.target_train).transform(self.spectra.values)
test_array = self.target_test == self.skit_lda.predict(self.spec_test)
test_array = test_array.astype(int)
self.lda_correct = test_array.sum()/len(test_array)
n_targets = len(self.spectra.index.levels[0])
colormap = plt.cm.nipy_spectral
colors_targets = [colormap(i) for i in np.linspace(0, 1,n_targets)]
fig,ax = plt.subplots(figsize = (12,8))
for tar in enumerate(self.spectra.index.levels[0]):
ax.hist(self.lda_trans[self.target_array==tar[1]], bins='auto', label=tar[1],color = colors_targets[tar[0]])
ax.legend(bbox_to_anchor=(1.05, 0.5), loc='upper left',fontsize = 18)
fig.tight_layout()
|
[
"numpy.abs",
"numpy.empty",
"sklearn.model_selection.train_test_split",
"matplotlib.pyplot.figure",
"numpy.arange",
"numpy.exp",
"scipy.interpolate.interp1d",
"matplotlib.patches.Patch",
"numpy.round",
"pandas.DataFrame",
"XPyS.config.element_color.keys",
"numpy.cumsum",
"numpy.max",
"numpy.linspace",
"matplotlib.pyplot.subplots",
"pandas.concat",
"sklearn.decomposition.NMF",
"copy.deepcopy",
"numpy.trapz",
"numpy.asarray",
"scipy.stats.pearsonr",
"numpy.min",
"sklearn.discriminant_analysis.LinearDiscriminantAnalysis",
"numpy.linalg.lstsq",
"matplotlib.pyplot.plot",
"numpy.any",
"numpy.where",
"sklearn.decomposition.PCA",
"numpy.array",
"numpy.diff",
"numpy.random.rand"
] |
[((2976, 2993), 'numpy.round', 'np.round', (['xnew', '(3)'], {}), '(xnew, 3)\n', (2984, 2993), True, 'import numpy as np\n'), ((5682, 5700), 'pandas.concat', 'pd.concat', (['df_list'], {}), '(df_list)\n', (5691, 5700), True, 'import pandas as pd\n'), ((5772, 5797), 'pandas.concat', 'pd.concat', (['df_params_list'], {}), '(df_params_list)\n', (5781, 5797), True, 'import pandas as pd\n'), ((9152, 9169), 'copy.deepcopy', 'dc', (['self._spectra'], {}), '(self._spectra)\n', (9154, 9169), True, 'from copy import deepcopy as dc\n'), ((9276, 9311), 'numpy.empty', 'np.empty', (['self.spectra.values.shape'], {}), '(self.spectra.values.shape)\n', (9284, 9311), True, 'import numpy as np\n'), ((9454, 9527), 'pandas.DataFrame', 'pd.DataFrame', (['_yN'], {'columns': 'self.spectra.columns', 'index': 'self.spectra.index'}), '(_yN, columns=self.spectra.columns, index=self.spectra.index)\n', (9466, 9527), True, 'import pandas as pd\n'), ((10221, 10235), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (10233, 10235), True, 'import matplotlib.pyplot as plt\n'), ((13703, 13780), 'pandas.DataFrame', 'pd.DataFrame', (['mv_spec'], {'columns': 'self.spectra.columns', 'index': 'self.spectra.index'}), '(mv_spec, columns=self.spectra.columns, index=self.spectra.index)\n', (13715, 13780), True, 'import pandas as pd\n'), ((14272, 14301), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(12, 8)'}), '(figsize=(12, 8))\n', (14284, 14301), True, 'import matplotlib.pyplot as plt\n'), ((18255, 18277), 'numpy.asarray', 'np.asarray', (['spec_train'], {}), '(spec_train)\n', (18265, 18277), True, 'import numpy as np\n'), ((18654, 18682), 'sklearn.decomposition.PCA', 'PCA', ([], {'n_components': 'self.n_pca'}), '(n_components=self.n_pca)\n', (18657, 18682), False, 'from sklearn.decomposition import PCA, NMF\n'), ((19312, 19354), 'pandas.DataFrame', 'pd.DataFrame', (['pc'], {'index': 'self.spectra.index'}), '(pc, index=self.spectra.index)\n', (19324, 19354), True, 'import pandas as pd\n'), ((19468, 19482), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (19480, 19482), True, 'import matplotlib.pyplot as plt\n'), ((20464, 20499), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(2)'], {'figsize': '(18, 6)'}), '(1, 2, figsize=(18, 6))\n', (20476, 20499), True, 'import matplotlib.pyplot as plt\n'), ((22769, 22796), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(12, 5)'}), '(figsize=(12, 5))\n', (22779, 22796), True, 'import matplotlib.pyplot as plt\n'), ((25125, 25156), 'numpy.any', 'np.any', (['(self.spectra.values < 0)'], {}), '(self.spectra.values < 0)\n', (25131, 25156), True, 'import numpy as np\n'), ((25271, 25322), 'sklearn.decomposition.NMF', 'NMF', ([], {'n_components': 'self.n_nmf', 'random_state': '(0)'}), '(n_components=self.n_nmf, random_state=0, **kws)\n', (25274, 25322), False, 'from sklearn.decomposition import PCA, NMF\n'), ((25647, 25690), 'pandas.DataFrame', 'pd.DataFrame', (['nmf'], {'index': 'self.spectra.index'}), '(nmf, index=self.spectra.index)\n', (25659, 25690), True, 'import pandas as pd\n'), ((25767, 25781), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (25779, 25781), True, 'import matplotlib.pyplot as plt\n'), ((30916, 30930), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (30928, 30930), True, 'import matplotlib.pyplot as plt\n'), ((30965, 30984), 'numpy.array', 'np.array', (['fulldf[X]'], {}), '(fulldf[X])\n', (30973, 30984), True, 'import numpy as np\n'), ((30997, 31016), 'numpy.array', 'np.array', (['fulldf[Y]'], {}), '(fulldf[Y])\n', (31005, 31016), True, 'import numpy as np\n'), ((31877, 31954), 'sklearn.model_selection.train_test_split', 'train_test_split', (['self.spectra.values', 'self.target_array'], {'test_size': 'test_size'}), '(self.spectra.values, self.target_array, test_size=test_size)\n', (31893, 31954), False, 'from sklearn.model_selection import train_test_split\n'), ((32387, 32415), 'sklearn.discriminant_analysis.LinearDiscriminantAnalysis', 'LinearDiscriminantAnalysis', ([], {}), '()\n', (32413, 32415), False, 'from sklearn.discriminant_analysis import LinearDiscriminantAnalysis\n'), ((32900, 32929), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(12, 8)'}), '(figsize=(12, 8))\n', (32912, 32929), True, 'import matplotlib.pyplot as plt\n'), ((2648, 2675), 'numpy.arange', 'np.arange', (['emin', 'emax', 'step'], {}), '(emin, emax, step)\n', (2657, 2675), True, 'import numpy as np\n'), ((4172, 4212), 'numpy.arange', 'np.arange', (['start_idx', '(start_idx + n_data)'], {}), '(start_idx, start_idx + n_data)\n', (4181, 4212), True, 'import numpy as np\n'), ((11942, 11972), 'matplotlib.pyplot.plot', 'plt.plot', (['self.peaktrack', '"""o-"""'], {}), "(self.peaktrack, 'o-')\n", (11950, 11972), True, 'import matplotlib.pyplot as plt\n'), ((12716, 12746), 'numpy.round', 'np.round', (['(cen[i] - peak_pos)', '(2)'], {}), '(cen[i] - peak_pos, 2)\n', (12724, 12746), True, 'import numpy as np\n'), ((13206, 13220), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (13218, 13220), True, 'import matplotlib.pyplot as plt\n'), ((31124, 31157), 'numpy.linalg.lstsq', 'np.linalg.lstsq', (['A', 'y'], {'rcond': 'None'}), '(A, y, rcond=None)\n', (31139, 31157), True, 'import numpy as np\n'), ((2851, 2878), 'numpy.arange', 'np.arange', (['emin', 'emax', 'step'], {}), '(emin, emax, step)\n', (2860, 2878), True, 'import numpy as np\n'), ((4425, 4527), 'scipy.interpolate.interp1d', 'interp1d', (['spectra_obj.__dict__[self.dset[0]]', 'spectra_obj.__dict__[self.dset[1]][i]'], {'kind': '"""cubic"""'}), "(spectra_obj.__dict__[self.dset[0]], spectra_obj.__dict__[self.dset\n [1]][i], kind='cubic')\n", (4433, 4527), False, 'from scipy.interpolate import interp1d\n'), ((6437, 6473), 'numpy.min', 'np.min', (['so[1].__dict__[self.dset[0]]'], {}), '(so[1].__dict__[self.dset[0]])\n', (6443, 6473), True, 'import numpy as np\n'), ((6552, 6588), 'numpy.max', 'np.max', (['so[1].__dict__[self.dset[0]]'], {}), '(so[1].__dict__[self.dset[0]])\n', (6558, 6588), True, 'import numpy as np\n'), ((6647, 6683), 'numpy.round', 'np.round', (['(100 * largest_min_value)', '(2)'], {}), '(100 * largest_min_value, 2)\n', (6655, 6683), True, 'import numpy as np\n'), ((6704, 6741), 'numpy.round', 'np.round', (['(100 * smallest_max_value)', '(2)'], {}), '(100 * smallest_max_value, 2)\n', (6712, 6741), True, 'import numpy as np\n'), ((9395, 9430), 'numpy.trapz', 'np.trapz', (['self.spectra.values[i, :]'], {}), '(self.spectra.values[i, :])\n', (9403, 9430), True, 'import numpy as np\n'), ((14191, 14247), 'numpy.exp', 'np.exp', (['(-(x - mean) ** 2 / (2 * standard_deviation ** 2))'], {}), '(-(x - mean) ** 2 / (2 * standard_deviation ** 2))\n', (14197, 14247), True, 'import numpy as np\n'), ((15269, 15328), 'numpy.linspace', 'np.linspace', (['(bin_borders[0] - 1)', '(bin_borders[-1] + 1)', '(10000)'], {}), '(bin_borders[0] - 1, bin_borders[-1] + 1, 10000)\n', (15280, 15328), True, 'import numpy as np\n'), ((15851, 15897), 'matplotlib.patches.Patch', 'mpatches.Patch', ([], {'color': 'colors[p[0]]', 'label': 'p[1]'}), '(color=colors[p[0]], label=p[1])\n', (15865, 15897), True, 'import matplotlib.patches as mpatches\n'), ((20708, 20736), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', 'n_samples'], {}), '(0, 1, n_samples)\n', (20719, 20736), True, 'import numpy as np\n'), ((20784, 20812), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', 'n_targets'], {}), '(0, 1, n_targets)\n', (20795, 20812), True, 'import numpy as np\n'), ((22116, 22174), 'matplotlib.patches.Patch', 'mpatches.Patch', ([], {'color': 'colors_targets[tar[0]]', 'label': 'tar[1]'}), '(color=colors_targets[tar[0]], label=tar[1])\n', (22130, 22174), True, 'import matplotlib.patches as mpatches\n'), ((23119, 23147), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', 'n_samples'], {}), '(0, 1, n_samples)\n', (23130, 23147), True, 'import numpy as np\n'), ((23195, 23223), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', 'n_targets'], {}), '(0, 1, n_targets)\n', (23206, 23223), True, 'import numpy as np\n'), ((23400, 23428), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', 'n_samples'], {}), '(0, 1, n_samples)\n', (23411, 23428), True, 'import numpy as np\n'), ((23476, 23504), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', 'n_targets'], {}), '(0, 1, n_targets)\n', (23487, 23504), True, 'import numpy as np\n'), ((25190, 25223), 'numpy.where', 'np.where', (['(self.spectra.values < 0)'], {}), '(self.spectra.values < 0)\n', (25198, 25223), True, 'import numpy as np\n'), ((32853, 32881), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', 'n_targets'], {}), '(0, 1, n_targets)\n', (32864, 32881), True, 'import numpy as np\n'), ((4779, 4864), 'pandas.DataFrame', 'pd.DataFrame', (['ynew'], {'index': '[[self.target[name]] * n_data, [name] * n_data, idx_id]'}), '(ynew, index=[[self.target[name]] * n_data, [name] * n_data,\n idx_id])\n', (4791, 4864), True, 'import pandas as pd\n'), ((4923, 4988), 'pandas.DataFrame', 'pd.DataFrame', (['ynew'], {'index': '[[0] * n_data, [name] * n_data, idx_id]'}), '(ynew, index=[[0] * n_data, [name] * n_data, idx_id])\n', (4935, 4988), True, 'import pandas as pd\n'), ((19038, 19084), 'numpy.cumsum', 'np.cumsum', (['(pca.explained_variance_ratio_ * 100)'], {}), '(pca.explained_variance_ratio_ * 100)\n', (19047, 19084), True, 'import numpy as np\n'), ((29832, 29884), 'scipy.stats.pearsonr', 'pearsonr', (['fulldf[Xs[j]].values', 'fulldf[Ys[i]].values'], {}), '(fulldf[Xs[j]].values, fulldf[Ys[i]].values)\n', (29840, 29884), False, 'from scipy.stats import pearsonr\n'), ((5401, 5486), 'pandas.DataFrame', 'pd.DataFrame', (['_dd'], {'index': '[[self.target[name]] * n_data, [name] * n_data, idx_id]'}), '(_dd, index=[[self.target[name]] * n_data, [name] * n_data, idx_id]\n )\n', (5413, 5486), True, 'import pandas as pd\n'), ((14493, 14517), 'XPyS.config.element_color.keys', 'cfg.element_color.keys', ([], {}), '()\n', (14515, 14517), True, 'import XPyS.config as cfg\n'), ((15069, 15089), 'numpy.diff', 'np.diff', (['bin_borders'], {}), '(bin_borders)\n', (15076, 15089), True, 'import numpy as np\n'), ((17315, 17349), 'numpy.min', 'np.min', (['self.df_params[par].values'], {}), '(self.df_params[par].values)\n', (17321, 17349), True, 'import numpy as np\n'), ((17921, 17955), 'numpy.min', 'np.min', (['self.df_params[par].values'], {}), '(self.df_params[par].values)\n', (17927, 17955), True, 'import numpy as np\n'), ((7002, 7043), 'numpy.round', 'np.round', (['so[1].__dict__[self.dset[0]]', '(2)'], {}), '(so[1].__dict__[self.dset[0]], 2)\n', (7010, 7043), True, 'import numpy as np\n'), ((7064, 7105), 'numpy.round', 'np.round', (['so[1].__dict__[self.dset[0]]', '(2)'], {}), '(so[1].__dict__[self.dset[0]], 2)\n', (7072, 7105), True, 'import numpy as np\n'), ((7187, 7228), 'numpy.round', 'np.round', (['so[1].__dict__[self.dset[0]]', '(2)'], {}), '(so[1].__dict__[self.dset[0]], 2)\n', (7195, 7228), True, 'import numpy as np\n'), ((7249, 7290), 'numpy.round', 'np.round', (['so[1].__dict__[self.dset[0]]', '(2)'], {}), '(so[1].__dict__[self.dset[0]], 2)\n', (7257, 7290), True, 'import numpy as np\n'), ((17424, 17440), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (17438, 17440), True, 'import numpy as np\n'), ((18030, 18046), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (18044, 18046), True, 'import numpy as np\n'), ((17353, 17387), 'numpy.max', 'np.max', (['self.df_params[par].values'], {}), '(self.df_params[par].values)\n', (17359, 17387), True, 'import numpy as np\n'), ((17388, 17422), 'numpy.min', 'np.min', (['self.df_params[par].values'], {}), '(self.df_params[par].values)\n', (17394, 17422), True, 'import numpy as np\n'), ((17959, 17993), 'numpy.max', 'np.max', (['self.df_params[par].values'], {}), '(self.df_params[par].values)\n', (17965, 17993), True, 'import numpy as np\n'), ((17994, 18028), 'numpy.min', 'np.min', (['self.df_params[par].values'], {}), '(self.df_params[par].values)\n', (18000, 18028), True, 'import numpy as np\n'), ((13114, 13128), 'numpy.abs', 'np.abs', (['mv_pts'], {}), '(mv_pts)\n', (13120, 13128), True, 'import numpy as np\n')]
|
"""
Command line interface to several manipulations of D-WAQ formatted
hydrodynamic data.
Typical invocation:
python -m stompy.model.delft.waq_hydro_editor -h
(to get help message).
python -m stompy.model.delft.waq_hydro_editor -i path/to/com-foo.hyd -a agg.shp -o output_agg/output
Read existing, serial DWAQ hydro, aggregate according to polygons in agg.shp, and write to output_agg/
python -m stompy.model.delft.waq_hydro_editor -i output_agg/com-output.hyd -c
Check DWAQ hydro for continuity. Relative errors are typically around 1e-8, which is machine precision
for the 32-bit floats that are used. Aggregated, spliced and low-pass hydro can accumulate larger errors,
especially in the presence of wetting and drying.
python -m stompy.model.delft.waq_hydro_editor -i path/com-input.hyd -l -o output_lp/output
Remove tides, write to output_lp. Currently the interval for the lowpass is not exposed on the command
line, and the filter is hard-wired to be a Butterworth IIR filter.
python -m stompy.model.delft.waq_hydro_editor -m path/to/flowfm.mdu -s -o output_splice/output
Splice a multiprocessor run into a single D-WAQ hydro dataset. Note that in the case of an MPI run,
the original D-Flow FM mdu file is specified with -m, instead of providing the hyd file.
Caveats:
* Lowpass loads the entire dataset into RAM, so it cannot handle large or very long simulations as input.
* While it should be possible to use this script with DFM output in MapFormat=1 or MapFormat=4, there are some
subtle differences. It was originally written for MapFormat=1, and more recently adapted to handle
MapFormat=4.
* There are some places where the code makes assumptions about undocumented details of the DFM output. It has
been developed against rev 53925, which is probably ca. late 2017.
"""
import logging as log
import argparse
import numpy as np
import matplotlib
import os
import datetime
from . import waq_scenario as waq
from . import dflow_model as dfm
from ...spatial import wkb2shp
# Clean inputs
def clean_shapefile(shp_in):
"""
Break multipolygons into individual polygons.
:param shp_in: path to aggregation polygon shapefile.
:type shp_in: str
:return: either shp_in, unchanged, if there were no changes needed, or
writes a new shapefile with suffix -cleaned.shp, which has edits
to shp_in.
"""
geoms=wkb2shp.shp2geom(shp_in)
multi_count=0
new_geoms=[]
for fi,feat in enumerate(geoms):
if feat['geom'].type=='Polygon':
new_geoms.append(feat['geom'])
else:
multi_count+=1
for g in feat['geom'].geoms:
new_geoms.append(g)
if multi_count:
cleaned=shp_in.replace('.shp','-cleaned.shp')
assert cleaned!=agg_grid_shp
wkb2shp.wkb2shp(cleaned,new_geoms,overwrite=True)
return cleaned
else:
return shp_in
def main(args=None):
parser=argparse.ArgumentParser(description='Manipulate transport data in D-WAQ format.')
one_of=parser.add_mutually_exclusive_group()
parser.add_argument("-i", "--hyd", help="Path to hyd file for input", default=None,type=str)
parser.add_argument("-m", "--mdu", help="Path to mdu file (for splicing)", default=None,type=str)
one_of.add_argument("-a", "--aggregate", help="Path to shapefile definining aggregation polygons",default=None,type=str)
one_of.add_argument("-c", "--continuity", help="Check continuity by comparing fluxes and volumes", action='store_true')
one_of.add_argument("-l", "--lowpass", help="Low-pass filter", action='store_true')
# TODO: splice output should default to mimicing what a serial run would use.
one_of.add_argument("-s", "--splice", help="Splice an MPI run into a single DWAQ hydro dataset",action='store_true')
parser.add_argument("-o", "--output", help="Path and run name for file output", default="output/output")
parser.add_argument("-p", "--pass-parameters",help="Pass parameters through without low-pass filter",action="store_true")
parser.add_argument("--keep-cells",
help=("When splicing skip regeneration of cells. DFM typically regenerates cells"
"on startup, which can introduce inconsistency between the net file and the"
"output. By default the same regeneration is applied here, but can be disabled"
"with this option"),
action='store_true')
# these options copied in from another script, here just for reference, and possible consistency
# in how arguments are named and described.
#parser.add_argument("-g", "--grid",help="Path to DWAQ grid geometry netcdf.",default=None,required=True)
#parser.add_argument("-r", "--reference", help="Reference date for DWAQ run (YYYY-MM-DDTHH:MM)", default=None, required=True)
#parser.add_argument("-s", "--start", help="Date of start of output (YYYY-MM-DDTTHH:MM)",default=None)
#parser.add_argument("-e", "--end", help="Date of end of output (YYYY-MM-DDTHH:MM)",default=None)
#parser.add_argument("-d", "--data",help="Input data",nargs='+')
#parser.add_argument("-i", "--interval",help="Time step in output, suffix 's' for seconds, 'D' for days", default='1D')
args=parser.parse_args(args=args)
# Most operations starts with reading the existing hydro:
if not args.splice:
hydro_orig=waq.HydroFiles(args.hyd)
else:
# splice code defines the input below
hydro_orig=None
# Only some actions produce new output
hydro_out=None
# both specifies that the operation is aggregation, and what the aggregation geometry
# is
if args.aggregate:
# split multipolygons to multiple polygons
agg_shp=clean_shapefile(args.aggregate)
# create object representing aggregated hydrodynamics
# sparse_layers: for z-layer inputs this can be True, in which cases cells are only output for the
# layers in which they are above the bed. Usually a bad idea. Parts of DWAQ assume
# each 2D cell exists across all layers
# agg_boundaries: if True, multiple boundary inputs entering a single aggregated cell will be
# merged into a single boundary input. Generally best to keep this as False.
hydro_out=waq.HydroAggregator(hydro_in=hydro_orig,
agg_shp=agg_shp,
sparse_layers=False,
agg_boundaries=False)
if args.splice:
assert args.mdu is not None,"Must specify MDU path"
# In theory it's possible to splice MPI and aggregate at the same time.
# for simplicity and to avoid nasty bugs, keep those steps separate.
# load the DFM run and specify its grid as the agg_shp (this is a short
# cut for just using the cells of an existing grid as the aggregation
# geometry).
model=dfm.DFlowModel.load(args.mdu)
run_prefix=model.mdu.name
run_dir=model.run_dir
dest_grid=model.grid
if not args.keep_cells:
dest_grid.make_cells_from_edges()
hydro_out=waq.HydroMultiAggregator(run_prefix=run_prefix,
path=run_dir,
agg_shp=dest_grid,
agg_boundaries=False)
if args.continuity:
def err_callback(time_index,summary):
log.info("Time index: %d: max volume error: %.3e relative error: %.3e"%( time_index,
np.abs(summary['vol_err']).max(),
summary['rel_err'].max()) )
hydro_orig.check_volume_conservation_incr(err_callback=err_callback)
if args.lowpass:
# TO-DO: expose these parameters on the command line
hydro_out=waq.FilterAll(original=hydro_orig,
filter_type='butter',
filter_parameters=(not args.pass_parameters),
lp_secs=86400*36./24)
# The code to write dwaq hydro is wrapped up in the code to write a dwaq model inp file,
# so we pretend to set up a dwaq simulation, even though the goal is just to write
# the hydro.
if hydro_out is not None:
if args.output is not None:
out_name=os.path.basename(args.output.replace('.hyd',''))
out_path=os.path.dirname(args.output)
assert out_path!='',"Must specify a path/name combination, like path/to/name"
# Define the subset of timesteps to write out, in this case the
# whole run.
sec=datetime.timedelta(seconds=1)
start_time=hydro_out.time0+hydro_out.t_secs[ 0]*sec
stop_time =hydro_out.time0+hydro_out.t_secs[-1]*sec
# probably would have been better to just pass name, desc, base_path in here,
# rather than using a shell subclass.
writer=waq.Scenario(name=out_name,
desc=(out_name,"n/a","n/a"), # not used for hydro output
hydro=hydro_out,
start_time=start_time,
stop_time=stop_time,
base_path=out_path)
# This step is super slow. Watch the output directory for progress.
# Takes ~20 hours on HPC for the full wy2013 run.
writer.cmd_write_hydro()
else:
log.info("No output file given -- will not write out results.")
if __name__ == '__main__':
main()
|
[
"numpy.abs",
"argparse.ArgumentParser",
"os.path.dirname",
"logging.info",
"datetime.timedelta"
] |
[((2953, 3039), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Manipulate transport data in D-WAQ format."""'}), "(description=\n 'Manipulate transport data in D-WAQ format.')\n", (2976, 3039), False, 'import argparse\n'), ((8664, 8692), 'os.path.dirname', 'os.path.dirname', (['args.output'], {}), '(args.output)\n', (8679, 8692), False, 'import os\n'), ((8901, 8930), 'datetime.timedelta', 'datetime.timedelta', ([], {'seconds': '(1)'}), '(seconds=1)\n', (8919, 8930), False, 'import datetime\n'), ((9752, 9815), 'logging.info', 'log.info', (['"""No output file given -- will not write out results."""'], {}), "('No output file given -- will not write out results.')\n", (9760, 9815), True, 'import logging as log\n'), ((7761, 7787), 'numpy.abs', 'np.abs', (["summary['vol_err']"], {}), "(summary['vol_err'])\n", (7767, 7787), True, 'import numpy as np\n')]
|
import os
import time
import numpy as np
from functools import reduce
import torch
import torch.nn as nn
import torch.nn.functional as F
from carle.env import CARLE
from carle.mcl import RND2D, AE2D
from game_of_carle.agents.agent import Agent
class CARLA(Agent):
def __init__(self, **kwargs):
super(CARLA, self).__init__(**kwargs)
self.use_grad = False
self.population_size = 4
self.generation = 0
self.episodes = 0
self.max_episodes = 1
self.ca_steps = 8
self.agents = []
self.fitness = []
self.save_path = kwargs["save_path"] if "save_path" in kwargs.keys() else ""
self.instances = kwargs["instances"] if "instances" in kwargs.keys() else 1
def initialize_policy(self):
self.perceive = nn.Conv2d(1, 9, 3, groups=1, padding=1, stride=1, \
padding_mode="circular", bias=False)
self.perceive.weight.requires_grad = False
self.perceive.weight.data.fill_(0)
for ii in range(9):
self.perceive.weight[ii, :, ii//3, ii%3].fill_(1)
self.perceive.to(self.my_device)
self.cellular_rules = nn.Sequential(nn.Conv2d(9, 32, 1, bias=False),\
nn.ReLU(),
nn.Conv2d(32, 1, 1, bias=True),
nn.Sigmoid()).to(self.my_device)
for param in self.cellular_rules.named_parameters():
param[1].requires_grad = False
if "bias" in param[0]:
param[1].data.fill_(param[1][0].item() - 0.05)
self.hallucinogen = torch.nn.Parameter(torch.rand(1)/10,\
requires_grad=False).to(self.my_device)
def hallucinate(self, obs):
obs = obs + (1.0 * (torch.rand_like(obs) < self.hallucinogen))\
.float().to(obs.device)
obs[obs>1.0] = 1.0
return obs
def forward(self, obs):
obs = self.hallucinate(obs)
for jj in range(self.ca_steps):
my_grid = self.perceive(obs)
my_grid = self.cellular_rules(my_grid)
#alive_mask = (my_grid[:,3:4,:,:] > 0.05).float()
#my_grid *= alive_mask
off_x = (obs.shape[2] - 64) // 2
off_y = (obs.shape[3] - 64) // 2
action_probabilities = my_grid[:,0:1,off_x:-off_x,off_y:-off_y]
action = (action_probabilities > 0.5).float()
return action
def get_params(self):
params = np.array([])
params = np.append(params, self.hallucinogen.cpu().numpy())
for param in self.cellular_rules.named_parameters():
params = np.append(params, param[1].detach().cpu().numpy().ravel())
return params
def set_params(self, my_params):
param_start = 0
self.hallucinogen = nn.Parameter(torch.Tensor(my_params[0:1]), \
requires_grad=False).to(self.my_device)
param_start += 1
for name, param in self.cellular_rules.named_parameters():
param_stop = param_start + reduce(lambda x,y: x*y, param.shape)
param[:] = torch.nn.Parameter(torch.tensor(\
my_params[param_start:param_stop].reshape(param.shape), \
requires_grad=self.use_grad), \
requires_grad=self.use_grad).to(param[:].device)
param_start = param_stop
|
[
"torch.nn.ReLU",
"torch.nn.Conv2d",
"torch.rand_like",
"torch.Tensor",
"numpy.array",
"torch.rand",
"functools.reduce",
"torch.nn.Sigmoid"
] |
[((807, 897), 'torch.nn.Conv2d', 'nn.Conv2d', (['(1)', '(9)', '(3)'], {'groups': '(1)', 'padding': '(1)', 'stride': '(1)', 'padding_mode': '"""circular"""', 'bias': '(False)'}), "(1, 9, 3, groups=1, padding=1, stride=1, padding_mode='circular',\n bias=False)\n", (816, 897), True, 'import torch.nn as nn\n'), ((2482, 2494), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (2490, 2494), True, 'import numpy as np\n'), ((3056, 3095), 'functools.reduce', 'reduce', (['(lambda x, y: x * y)', 'param.shape'], {}), '(lambda x, y: x * y, param.shape)\n', (3062, 3095), False, 'from functools import reduce\n'), ((1187, 1218), 'torch.nn.Conv2d', 'nn.Conv2d', (['(9)', '(32)', '(1)'], {'bias': '(False)'}), '(9, 32, 1, bias=False)\n', (1196, 1218), True, 'import torch.nn as nn\n'), ((1237, 1246), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (1244, 1246), True, 'import torch.nn as nn\n'), ((1264, 1294), 'torch.nn.Conv2d', 'nn.Conv2d', (['(32)', '(1)', '(1)'], {'bias': '(True)'}), '(32, 1, 1, bias=True)\n', (1273, 1294), True, 'import torch.nn as nn\n'), ((1312, 1324), 'torch.nn.Sigmoid', 'nn.Sigmoid', ([], {}), '()\n', (1322, 1324), True, 'import torch.nn as nn\n'), ((2834, 2862), 'torch.Tensor', 'torch.Tensor', (['my_params[0:1]'], {}), '(my_params[0:1])\n', (2846, 2862), False, 'import torch\n'), ((1597, 1610), 'torch.rand', 'torch.rand', (['(1)'], {}), '(1)\n', (1607, 1610), False, 'import torch\n'), ((1747, 1767), 'torch.rand_like', 'torch.rand_like', (['obs'], {}), '(obs)\n', (1762, 1767), False, 'import torch\n')]
|
import argparse
import os
from os.path import join
from tempfile import TemporaryDirectory
from collections import OrderedDict
import numpy as np
import torch
from sklearn.metrics import confusion_matrix, accuracy_score
from torch.utils.data import DataLoader
from torchvision import transforms
from torchvision.datasets import ImageFolder
import torchvision.models as models
import torch.nn.functional as F
import pytorch_lightning as pl
from pytorch_lightning.loggers import WandbLogger
from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint
import utils
from create_datasets import create_patches_dataset_icdar17, create_pages_dataset_icdar17, \
create_pages_dataset_firemaker, create_patches_dataset_firemaker, create_patches_dataset_iam
MODEL_NAMES = sorted(
name for name in models.__dict__
if name.islower() and not name.startswith("__") and callable(models.__dict__[name])
)
class WriterID(pl.LightningModule):
def __init__(self, hparams):
super().__init__()
self.hparams = hparams
self.dataset = hparams.dataset
if self.dataset == 'icdar17':
self.num_classes = 720
elif self.dataset == 'firemaker':
self.num_classes = 250
else:
self.num_classes = 657
self.model = models.__dict__[self.hparams.model](pretrained=hparams.pretrained)
# self.avgpool = nn.AdaptiveMaxPool2d((1, 1))
# Changing first layer
if hparams.binary:
name, layer = list(self.model.named_children())[0]
if type(layer) == torch.nn.modules.container.Sequential:
layer[0].apply(utils.squeeze_weights)
setattr(self.model, name, layer)
else:
setattr(self.model, name, layer.apply(utils.squeeze_weights))
# Changing last layer
name, layer = list(self.model.named_children())[-1]
if type(layer) == torch.nn.modules.container.Sequential:
utils.change_out_features(layer[-1], classes=self.num_classes)
setattr(self.model, name, layer)
else:
setattr(self.model, name, utils.change_out_features(layer, classes=self.num_classes))
def forward(self, x):
x = self.model(x)
return x
def training_step(self, batch, batch_idx):
x, y = batch
y_pred = self(x)
train_loss = F.cross_entropy(y_pred, y)
acc1, acc5, acc10 = self.__accuracy(y_pred, y, topk=(1, 5, 10))
logs = {'train_loss': train_loss}
output = OrderedDict({
'loss': train_loss,
'acc1': acc1,
'acc5': acc5,
'acc10': acc10,
'log': logs
})
return output
def validation_step(self, batch, batch_idx):
x, y = batch
y_pred = self(x)
val_loss = F.cross_entropy(y_pred, y)
y_pred = F.softmax(y_pred, dim=-1)
acc1, acc5, acc10 = self.__accuracy(y_pred, y, topk=(1, 5, 10))
output = OrderedDict({
'val_loss': val_loss,
'val_acc1': acc1,
'val_acc5': acc5,
'val_acc10': acc10,
'y_pred': y_pred,
'y': y,
})
return output
def validation_epoch_end(self, outputs):
logs = {}
for metric_name in ["val_loss", "val_acc1", "val_acc5", "val_acc10"]:
metric_total = 0
for output in outputs:
metric_value = output[metric_name]
# reduce manually when using dp
if self.trainer.use_dp or self.trainer.use_ddp2:
metric_value = torch.mean(metric_value)
metric_total += metric_value
logs[metric_name] = metric_total / len(outputs)
preds = []
targets = []
for output in outputs:
y_pred = output['y_pred']
y = output['y']
preds.append(y_pred.cpu())
targets.append(y.cpu())
targets = torch.cat(targets, dim=0)
preds = torch.cat(preds, dim=0)
class_acc = self.__conf_matrix(preds, targets, self.classes)
logs['class_acc'] = 100 * class_acc
result = {'log': logs, 'val_loss': logs["val_loss"]}
return result
def test_step(self, batch, batch_idx):
x, y = batch
y_pred = self(x)
test_loss = F.cross_entropy(y_pred, y)
y_pred = F.softmax(y_pred, dim=-1)
acc1, acc5, acc10 = self.__accuracy(y_pred, y, topk=(1, 5, 10))
output = OrderedDict({
'test_loss': test_loss,
'test_acc1': acc1,
'test_acc5': acc5,
'test_acc10': acc10,
'y_pred': y_pred,
'y': y,
})
return output
def test_epoch_end(self, outputs):
logs = {}
for metric_name in ["test_loss", "test_acc1", "test_acc5", "test_acc10"]:
metric_total = 0
for output in outputs:
metric_value = output[metric_name]
# reduce manually when using dp
if self.trainer.use_dp or self.trainer.use_ddp2:
metric_value = torch.mean(metric_value)
metric_total += metric_value
logs[metric_name] = metric_total / len(outputs)
preds = []
targets = []
for output in outputs:
y_pred = output['y_pred']
y = output['y']
preds.append(y_pred.cpu())
targets.append(y.cpu())
targets = torch.cat(targets, dim=0)
preds = torch.cat(preds, dim=0)
class_acc = self.__conf_matrix(preds, targets, self.classes)
logs['test_class_acc'] = 100 * class_acc
result = {'log': logs, 'test_loss': logs["test_loss"]}
return result
@classmethod
def __conf_matrix(cls, preds, targets, classes, topk=(1,)):
with torch.no_grad():
maxk = max(topk)
_, pred = preds.topk(maxk, 1, True, True)
conf_matrix = confusion_matrix(targets, pred)
print(len(conf_matrix))
max_pred = np.argmax(conf_matrix, axis=1)
print(len(classes))
class_acc = accuracy_score(np.array(classes)[max_pred], np.array(classes))
return class_acc
@classmethod
def __accuracy(cls, output, target, topk=(1,)):
"""Computes the accuracy over the k top predictions for the specified values of k"""
with torch.no_grad():
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
res = []
for k in topk:
correct_k = correct[:k].view(-1).float().sum(0, keepdim=True)
res.append(correct_k.mul_(100.0 / batch_size))
return res
def configure_optimizers(self):
# return torch.optim.AdamW(self.parameters(), lr=self.hparams.lr)
# return torch.optim.Adam(self.parameters(), lr=self.hparams.lr)
return torch.optim.SGD(self.parameters(), lr=self.hparams.lr, momentum=0.9)
# optimizer = torch.optim.SGD(self.parameters(), lr=self.hparams.lr, momentum=0.9)
# scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, 'min')
# return [optimizer], [scheduler]
def prepare_data(self):
if self.hparams.binary:
transform = transforms.Compose([
transforms.Grayscale(num_output_channels=1),
transforms.ToTensor()
])
else:
if self.dataset == 'icdar17':
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize([0.7993, 0.7404, 0.6438], [0.1168, 0.1198, 0.1186]), # icdar17 norm
])
elif self.dataset == 'firemaker':
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize([0.9706, 0.9706, 0.9706], [0.1448, 0.1448, 0.1448]), # firemaker norm
])
else:
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize([0.9496, 0.9406, 0.9406], [0.1076, 0.1076, 0.1076]), # iam norm
])
self.train_data = ImageFolder(self.hparams.train_path, transform=transform)
self.classes = self.train_data.classes
self.train_sampler = utils.ImbalancedDatasetSampler(self.train_data)
self.val_data = ImageFolder(self.hparams.val_path, transform=transform)
self.test_data = ImageFolder(self.hparams.test_path, transform=transform)
def train_dataloader(self):
return DataLoader(self.train_data, batch_size=self.hparams.batch_size, sampler=self.train_sampler,
num_workers=8, pin_memory=True)
def val_dataloader(self):
return DataLoader(self.val_data, batch_size=self.hparams.batch_size, num_workers=8, pin_memory=True)
def test_dataloader(self):
return DataLoader(self.test_data, batch_size=self.hparams.batch_size, num_workers=8, pin_memory=True)
@staticmethod
def add_model_specific_args(parent_parser):
parser = argparse.ArgumentParser(parents=[parent_parser])
parser.add_argument('-a', '--model', metavar='MODEL', default='resnet18', choices=MODEL_NAMES,
help='model architecture: ' +
' | '.join(MODEL_NAMES) +
' (default: )')
parser.add_argument('--epochs', default=20, type=int, metavar='N',
help='number of total epochs to run')
parser.add_argument('--seed', type=int, default=None,
help='seed for initializing training. ')
parser.add_argument('-b', '--batch-size', default=32, type=int,
metavar='N',
help='mini-batch size (default: 32), this is the total '
'batch size of all GPUs on the current node when '
'using Data Parallel or Distributed Data Parallel')
parser.add_argument('--lr', '--learning-rate', default=0.01, type=float,
metavar='LR', help='initial learning rate', dest='lr')
parser.add_argument('--pretrained', dest='pretrained', action='store_true',
help='use pre-trained model in imagenet')
return parser
def get_args():
parent_parser = argparse.ArgumentParser(add_help=False)
parent_parser.add_argument('--patch-height', default=256, type=int, metavar='H',
help='height of the patch')
parent_parser.add_argument('--patch-width', default=256, type=int, metavar='W',
help='width of the patch')
parent_parser.add_argument('--num-patches', default=None, type=int, metavar='N',
help='number of patches per image')
parent_parser.add_argument('--stride', default=1, type=int, metavar='B',
help='factor in which pixels are binarized')
parent_parser.add_argument('--split', default=[3, 1, 1], type=int, nargs='+', metavar='S',
help='number of images for train (first element), val (second element) and test (third)')
parent_parser.add_argument('--binary', dest='binary', action='store_true',
help='use binary photos')
parent_parser.add_argument('--data-path', metavar='T', type=str,
default='/home/punjabi/TFG/datasets/ScriptNet-HistoricalWI-2017-binarized/',
help='path to dataset')
parent_parser.add_argument('--dataset', metavar='D', type=str,
default='icdar17',
choices=('icdar17', 'firemaker', 'iam'),
help='three datasets: icdar17, firemaker, iam')
parent_parser.add_argument('--train-path', metavar='T', type=str,
default='/home/punjabi/TFG/datasets/patches-ScriptNet-HistoricalWI-2017-binarized/train',
help='path to train dataset')
parent_parser.add_argument('--val-path', metavar='V', type=str,
default='/home/punjabi/TFG/datasets/patches-ScriptNet-HistoricalWI-2017-binarized/validation',
help='path to validation dataset')
parent_parser.add_argument('--test-path', metavar='TST', type=str,
default='/home/punjabi/TFG/datasets/patches-ScriptNet-HistoricalWI-2017-binarized/test',
help='path to test dataset')
parent_parser.add_argument('--checkpoint-path', metavar='C', type=str,
default=None,
help='path to test dataset')
parent_parser.add_argument('--temp-path', metavar='TMP', default=os.getcwd(), type=str,
help='path to save data temporary')
parent_parser.add_argument('--use-temp-dir', dest='use_temp_dir', action='store_true',
help='create data on a temporary directory')
parent_parser.add_argument('--gpus', type=int, default=2,
help='how many gpus')
parent_parser.add_argument('--distributed-backend', type=str, default='dp', choices=('dp', 'ddp', 'ddp2'),
help='supports three options dp, ddp, ddp2')
parent_parser.add_argument('--use-16-bit', dest='use_16_bit', action='store_true',
help='if true uses 16 bit precision')
parent_parser.add_argument('-t', '--test', dest='test', action='store_true',
help='evaluate model on test set')
parent_parser.add_argument('--load-checkpoint', dest='load', action='store_true',
help='load model and evaluate on test set')
parser = WriterID.add_model_specific_args(parent_parser)
return parser.parse_args()
def main(hparams):
if hparams.use_temp_dir:
tmp_dir = TemporaryDirectory(dir=hparams.temp_path)
if hparams.dataset == 'icdar17':
create_patches_dataset_icdar17(hparams.data_path, tmp_dir.name, hparams.patch_height, hparams.patch_height,
hparams.num_patches,
seed=hparams.seed, binary=hparams.binary, stride=hparams.stride)
elif hparams.dataset == 'firemaker':
create_patches_dataset_firemaker(hparams.data_path, hparams.test_path, tmp_dir.name, hparams.patch_height,
hparams.patch_height, hparams.num_patches,
seed=hparams.seed, binary=hparams.binary, stride=hparams.stride)
else:
create_patches_dataset_iam(hparams.data_path, tmp_dir.name, hparams.patch_height, hparams.patch_height,
hparams.num_patches,
hparams.seed, hparams.binary, hparams.stride)
hparams.train_path = join(tmp_dir.name, 'train')
hparams.val_path = join(tmp_dir.name, 'validation')
hparams.test_path = join(tmp_dir.name, 'test')
model = WriterID(hparams)
# Loggers
logger = WandbLogger(project='TFG', tags=[hparams.dataset])
logger.watch(model) # Watch gradients
pl.seed_everything(hparams.seed)
# Callbacks
# early_stopping = EarlyStopping('val_loss', patience=30)
checkpoint_callback = ModelCheckpoint(
filepath=os.getcwd() + '/checkpoints/' + hparams.dataset + '_' + hparams.model + '_{epoch:02d}-{val_loss:.2f}',
)
# checkpoint_callback = False
trainer = pl.Trainer(
nb_sanity_val_steps=0,
train_path=hparams.train_path,
val_path=hparams.val_path,
test_path=hparams.test_path,
gpus=hparams.gpus,
batch_size=hparams.batch_size,
learning_rate=hparams.lr,
epochs=hparams.epochs,
model=hparams.model,
pretrained=hparams.pretrained,
logger=logger,
checkpoint_callback=checkpoint_callback,
# early_stop_callback=early_stopping,
distributed_backend=hparams.distributed_backend,
deterministic=True if hparams.seed is not None else False,
precision=16 if hparams.use_16_bit else 32,
max_epochs=15,
min_epochs=5,
# auto_scale_batch_size='binsearch',
# auto_lr_find=True,
)
if hparams.test:
trainer.fit(model)
trainer.test(model)
elif hparams.load:
model = WriterID.load_from_checkpoint(hparams.checkpoint_path, vars(hparams))
trainer.test(model)
else:
trainer.fit(model)
if hparams.use_temp_dir:
tmp_dir.cleanup()
if __name__ == '__main__':
main(get_args())
|
[
"pytorch_lightning.Trainer",
"pytorch_lightning.seed_everything",
"argparse.ArgumentParser",
"numpy.argmax",
"torch.cat",
"torchvision.transforms.Normalize",
"torch.no_grad",
"os.path.join",
"tempfile.TemporaryDirectory",
"torch.utils.data.DataLoader",
"create_datasets.create_patches_dataset_firemaker",
"create_datasets.create_patches_dataset_iam",
"torch.mean",
"torch.nn.functional.cross_entropy",
"torchvision.datasets.ImageFolder",
"utils.ImbalancedDatasetSampler",
"create_datasets.create_patches_dataset_icdar17",
"torchvision.transforms.Grayscale",
"utils.change_out_features",
"os.getcwd",
"torch.nn.functional.softmax",
"pytorch_lightning.loggers.WandbLogger",
"numpy.array",
"collections.OrderedDict",
"sklearn.metrics.confusion_matrix",
"torchvision.transforms.ToTensor"
] |
[((10699, 10738), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'add_help': '(False)'}), '(add_help=False)\n', (10722, 10738), False, 'import argparse\n'), ((15625, 15675), 'pytorch_lightning.loggers.WandbLogger', 'WandbLogger', ([], {'project': '"""TFG"""', 'tags': '[hparams.dataset]'}), "(project='TFG', tags=[hparams.dataset])\n", (15636, 15675), False, 'from pytorch_lightning.loggers import WandbLogger\n'), ((15724, 15756), 'pytorch_lightning.seed_everything', 'pl.seed_everything', (['hparams.seed'], {}), '(hparams.seed)\n', (15742, 15756), True, 'import pytorch_lightning as pl\n'), ((16054, 16595), 'pytorch_lightning.Trainer', 'pl.Trainer', ([], {'nb_sanity_val_steps': '(0)', 'train_path': 'hparams.train_path', 'val_path': 'hparams.val_path', 'test_path': 'hparams.test_path', 'gpus': 'hparams.gpus', 'batch_size': 'hparams.batch_size', 'learning_rate': 'hparams.lr', 'epochs': 'hparams.epochs', 'model': 'hparams.model', 'pretrained': 'hparams.pretrained', 'logger': 'logger', 'checkpoint_callback': 'checkpoint_callback', 'distributed_backend': 'hparams.distributed_backend', 'deterministic': '(True if hparams.seed is not None else False)', 'precision': '(16 if hparams.use_16_bit else 32)', 'max_epochs': '(15)', 'min_epochs': '(5)'}), '(nb_sanity_val_steps=0, train_path=hparams.train_path, val_path=\n hparams.val_path, test_path=hparams.test_path, gpus=hparams.gpus,\n batch_size=hparams.batch_size, learning_rate=hparams.lr, epochs=hparams\n .epochs, model=hparams.model, pretrained=hparams.pretrained, logger=\n logger, checkpoint_callback=checkpoint_callback, distributed_backend=\n hparams.distributed_backend, deterministic=True if hparams.seed is not\n None else False, precision=16 if hparams.use_16_bit else 32, max_epochs\n =15, min_epochs=5)\n', (16064, 16595), True, 'import pytorch_lightning as pl\n'), ((2392, 2418), 'torch.nn.functional.cross_entropy', 'F.cross_entropy', (['y_pred', 'y'], {}), '(y_pred, y)\n', (2407, 2418), True, 'import torch.nn.functional as F\n'), ((2551, 2645), 'collections.OrderedDict', 'OrderedDict', (["{'loss': train_loss, 'acc1': acc1, 'acc5': acc5, 'acc10': acc10, 'log': logs}"], {}), "({'loss': train_loss, 'acc1': acc1, 'acc5': acc5, 'acc10': acc10,\n 'log': logs})\n", (2562, 2645), False, 'from collections import OrderedDict\n'), ((2850, 2876), 'torch.nn.functional.cross_entropy', 'F.cross_entropy', (['y_pred', 'y'], {}), '(y_pred, y)\n', (2865, 2876), True, 'import torch.nn.functional as F\n'), ((2894, 2919), 'torch.nn.functional.softmax', 'F.softmax', (['y_pred'], {'dim': '(-1)'}), '(y_pred, dim=-1)\n', (2903, 2919), True, 'import torch.nn.functional as F\n'), ((3011, 3132), 'collections.OrderedDict', 'OrderedDict', (["{'val_loss': val_loss, 'val_acc1': acc1, 'val_acc5': acc5, 'val_acc10':\n acc10, 'y_pred': y_pred, 'y': y}"], {}), "({'val_loss': val_loss, 'val_acc1': acc1, 'val_acc5': acc5,\n 'val_acc10': acc10, 'y_pred': y_pred, 'y': y})\n", (3022, 3132), False, 'from collections import OrderedDict\n'), ((4008, 4033), 'torch.cat', 'torch.cat', (['targets'], {'dim': '(0)'}), '(targets, dim=0)\n', (4017, 4033), False, 'import torch\n'), ((4050, 4073), 'torch.cat', 'torch.cat', (['preds'], {'dim': '(0)'}), '(preds, dim=0)\n', (4059, 4073), False, 'import torch\n'), ((4382, 4408), 'torch.nn.functional.cross_entropy', 'F.cross_entropy', (['y_pred', 'y'], {}), '(y_pred, y)\n', (4397, 4408), True, 'import torch.nn.functional as F\n'), ((4426, 4451), 'torch.nn.functional.softmax', 'F.softmax', (['y_pred'], {'dim': '(-1)'}), '(y_pred, dim=-1)\n', (4435, 4451), True, 'import torch.nn.functional as F\n'), ((4542, 4668), 'collections.OrderedDict', 'OrderedDict', (["{'test_loss': test_loss, 'test_acc1': acc1, 'test_acc5': acc5, 'test_acc10':\n acc10, 'y_pred': y_pred, 'y': y}"], {}), "({'test_loss': test_loss, 'test_acc1': acc1, 'test_acc5': acc5,\n 'test_acc10': acc10, 'y_pred': y_pred, 'y': y})\n", (4553, 4668), False, 'from collections import OrderedDict\n'), ((5542, 5567), 'torch.cat', 'torch.cat', (['targets'], {'dim': '(0)'}), '(targets, dim=0)\n', (5551, 5567), False, 'import torch\n'), ((5584, 5607), 'torch.cat', 'torch.cat', (['preds'], {'dim': '(0)'}), '(preds, dim=0)\n', (5593, 5607), False, 'import torch\n'), ((8455, 8512), 'torchvision.datasets.ImageFolder', 'ImageFolder', (['self.hparams.train_path'], {'transform': 'transform'}), '(self.hparams.train_path, transform=transform)\n', (8466, 8512), False, 'from torchvision.datasets import ImageFolder\n'), ((8589, 8636), 'utils.ImbalancedDatasetSampler', 'utils.ImbalancedDatasetSampler', (['self.train_data'], {}), '(self.train_data)\n', (8619, 8636), False, 'import utils\n'), ((8662, 8717), 'torchvision.datasets.ImageFolder', 'ImageFolder', (['self.hparams.val_path'], {'transform': 'transform'}), '(self.hparams.val_path, transform=transform)\n', (8673, 8717), False, 'from torchvision.datasets import ImageFolder\n'), ((8743, 8799), 'torchvision.datasets.ImageFolder', 'ImageFolder', (['self.hparams.test_path'], {'transform': 'transform'}), '(self.hparams.test_path, transform=transform)\n', (8754, 8799), False, 'from torchvision.datasets import ImageFolder\n'), ((8848, 8976), 'torch.utils.data.DataLoader', 'DataLoader', (['self.train_data'], {'batch_size': 'self.hparams.batch_size', 'sampler': 'self.train_sampler', 'num_workers': '(8)', 'pin_memory': '(True)'}), '(self.train_data, batch_size=self.hparams.batch_size, sampler=\n self.train_sampler, num_workers=8, pin_memory=True)\n', (8858, 8976), False, 'from torch.utils.data import DataLoader\n'), ((9044, 9141), 'torch.utils.data.DataLoader', 'DataLoader', (['self.val_data'], {'batch_size': 'self.hparams.batch_size', 'num_workers': '(8)', 'pin_memory': '(True)'}), '(self.val_data, batch_size=self.hparams.batch_size, num_workers=8,\n pin_memory=True)\n', (9054, 9141), False, 'from torch.utils.data import DataLoader\n'), ((9185, 9284), 'torch.utils.data.DataLoader', 'DataLoader', (['self.test_data'], {'batch_size': 'self.hparams.batch_size', 'num_workers': '(8)', 'pin_memory': '(True)'}), '(self.test_data, batch_size=self.hparams.batch_size, num_workers=\n 8, pin_memory=True)\n', (9195, 9284), False, 'from torch.utils.data import DataLoader\n'), ((9364, 9412), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'parents': '[parent_parser]'}), '(parents=[parent_parser])\n', (9387, 9412), False, 'import argparse\n'), ((14381, 14422), 'tempfile.TemporaryDirectory', 'TemporaryDirectory', ([], {'dir': 'hparams.temp_path'}), '(dir=hparams.temp_path)\n', (14399, 14422), False, 'from tempfile import TemporaryDirectory\n'), ((15423, 15450), 'os.path.join', 'join', (['tmp_dir.name', '"""train"""'], {}), "(tmp_dir.name, 'train')\n", (15427, 15450), False, 'from os.path import join\n'), ((15478, 15510), 'os.path.join', 'join', (['tmp_dir.name', '"""validation"""'], {}), "(tmp_dir.name, 'validation')\n", (15482, 15510), False, 'from os.path import join\n'), ((15539, 15565), 'os.path.join', 'join', (['tmp_dir.name', '"""test"""'], {}), "(tmp_dir.name, 'test')\n", (15543, 15565), False, 'from os.path import join\n'), ((1987, 2049), 'utils.change_out_features', 'utils.change_out_features', (['layer[-1]'], {'classes': 'self.num_classes'}), '(layer[-1], classes=self.num_classes)\n', (2012, 2049), False, 'import utils\n'), ((5908, 5923), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (5921, 5923), False, 'import torch\n'), ((6036, 6067), 'sklearn.metrics.confusion_matrix', 'confusion_matrix', (['targets', 'pred'], {}), '(targets, pred)\n', (6052, 6067), False, 'from sklearn.metrics import confusion_matrix, accuracy_score\n'), ((6127, 6157), 'numpy.argmax', 'np.argmax', (['conf_matrix'], {'axis': '(1)'}), '(conf_matrix, axis=1)\n', (6136, 6157), True, 'import numpy as np\n'), ((6483, 6498), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (6496, 6498), False, 'import torch\n'), ((13195, 13206), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (13204, 13206), False, 'import os\n'), ((14476, 14679), 'create_datasets.create_patches_dataset_icdar17', 'create_patches_dataset_icdar17', (['hparams.data_path', 'tmp_dir.name', 'hparams.patch_height', 'hparams.patch_height', 'hparams.num_patches'], {'seed': 'hparams.seed', 'binary': 'hparams.binary', 'stride': 'hparams.stride'}), '(hparams.data_path, tmp_dir.name, hparams.\n patch_height, hparams.patch_height, hparams.num_patches, seed=hparams.\n seed, binary=hparams.binary, stride=hparams.stride)\n', (14506, 14679), False, 'from create_datasets import create_patches_dataset_icdar17, create_pages_dataset_icdar17, create_pages_dataset_firemaker, create_patches_dataset_firemaker, create_patches_dataset_iam\n'), ((2147, 2205), 'utils.change_out_features', 'utils.change_out_features', (['layer'], {'classes': 'self.num_classes'}), '(layer, classes=self.num_classes)\n', (2172, 2205), False, 'import utils\n'), ((6258, 6275), 'numpy.array', 'np.array', (['classes'], {}), '(classes)\n', (6266, 6275), True, 'import numpy as np\n'), ((14813, 15041), 'create_datasets.create_patches_dataset_firemaker', 'create_patches_dataset_firemaker', (['hparams.data_path', 'hparams.test_path', 'tmp_dir.name', 'hparams.patch_height', 'hparams.patch_height', 'hparams.num_patches'], {'seed': 'hparams.seed', 'binary': 'hparams.binary', 'stride': 'hparams.stride'}), '(hparams.data_path, hparams.test_path,\n tmp_dir.name, hparams.patch_height, hparams.patch_height, hparams.\n num_patches, seed=hparams.seed, binary=hparams.binary, stride=hparams.\n stride)\n', (14845, 15041), False, 'from create_datasets import create_patches_dataset_icdar17, create_pages_dataset_icdar17, create_pages_dataset_firemaker, create_patches_dataset_firemaker, create_patches_dataset_iam\n'), ((15144, 15323), 'create_datasets.create_patches_dataset_iam', 'create_patches_dataset_iam', (['hparams.data_path', 'tmp_dir.name', 'hparams.patch_height', 'hparams.patch_height', 'hparams.num_patches', 'hparams.seed', 'hparams.binary', 'hparams.stride'], {}), '(hparams.data_path, tmp_dir.name, hparams.\n patch_height, hparams.patch_height, hparams.num_patches, hparams.seed,\n hparams.binary, hparams.stride)\n', (15170, 15323), False, 'from create_datasets import create_patches_dataset_icdar17, create_pages_dataset_icdar17, create_pages_dataset_firemaker, create_patches_dataset_firemaker, create_patches_dataset_iam\n'), ((3643, 3667), 'torch.mean', 'torch.mean', (['metric_value'], {}), '(metric_value)\n', (3653, 3667), False, 'import torch\n'), ((5177, 5201), 'torch.mean', 'torch.mean', (['metric_value'], {}), '(metric_value)\n', (5187, 5201), False, 'import torch\n'), ((6229, 6246), 'numpy.array', 'np.array', (['classes'], {}), '(classes)\n', (6237, 6246), True, 'import numpy as np\n'), ((7549, 7592), 'torchvision.transforms.Grayscale', 'transforms.Grayscale', ([], {'num_output_channels': '(1)'}), '(num_output_channels=1)\n', (7569, 7592), False, 'from torchvision import transforms\n'), ((7610, 7631), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (7629, 7631), False, 'from torchvision import transforms\n'), ((7772, 7793), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (7791, 7793), False, 'from torchvision import transforms\n'), ((7815, 7887), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['[0.7993, 0.7404, 0.6438]', '[0.1168, 0.1198, 0.1186]'], {}), '([0.7993, 0.7404, 0.6438], [0.1168, 0.1198, 0.1186])\n', (7835, 7887), False, 'from torchvision import transforms\n'), ((8039, 8060), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (8058, 8060), False, 'from torchvision import transforms\n'), ((8082, 8154), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['[0.9706, 0.9706, 0.9706]', '[0.1448, 0.1448, 0.1448]'], {}), '([0.9706, 0.9706, 0.9706], [0.1448, 0.1448, 0.1448])\n', (8102, 8154), False, 'from torchvision import transforms\n'), ((8280, 8301), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (8299, 8301), False, 'from torchvision import transforms\n'), ((8323, 8395), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['[0.9496, 0.9406, 0.9406]', '[0.1076, 0.1076, 0.1076]'], {}), '([0.9496, 0.9406, 0.9406], [0.1076, 0.1076, 0.1076])\n', (8343, 8395), False, 'from torchvision import transforms\n'), ((15896, 15907), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (15905, 15907), False, 'import os\n')]
|
import torch.optim as optim # Import optim
import torchvision # Import torchvision
import h5py # import h5py
from torch.utils.data import dataset # import dataset
from torch.utils.data import DataLoader # Import Dataloader
import torchvision.transforms as transforms # Import Transform
import pandas as pd # Import Pnadas
import torch # Import Torch
import torch.nn as nn # Import NN module from Torch
# Import transform module from torchvision
from torchvision.transforms import transforms
from torch.utils.data import DataLoader # Import dataloader from torch
from torch.optim import Adam # import optimizer module from torch
from torch.autograd import Variable # Import autograd from torch
import numpy as np # Import numpy module
import torchvision.datasets as datasets # Import dataset from torch
from Attention import PAM_Module # import position attention module
# from Attention import CAM_Module # import channel attention module
# from Attention import SA_Module # Import Self attention module
from torch import optim, cuda # import optimizer and CUDA
import random # import random
import torch.nn.functional as F # Import nn.functional
import time # import time
import sys # Import System
import os # Import OS
from pytorchtools import EarlyStopping
from torchvision import models
import warnings
SEED = 1234 # Initialize seed
random.seed(SEED)
np.random.seed(SEED)
torch.manual_seed(SEED)
torch.cuda.manual_seed(SEED)
torch.backends.cudnn.deterministic = True
device = torch.device('cuda') # Define device type
num_classes = 2 # Define Number of classes
in_channel = 1 # Define Number of Input Channels
learning_rate = 0.0005 # Define Learning rate
batch_size = 128 # Define Batch Size
EPOCHS = 1000 # Define maximum Number of Epochs
FC_Size = 512
SFC_Size = 512
Temp = 3
alpha = 0.7
N_models = 6
num_classes = 2
warnings.filterwarnings("ignore")
train_transformations = transforms.Compose([ # Training Transform
transforms.Resize([224, 224]),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485], std=[0.229])])
test_transformations = transforms.Compose([ # Test Transform
transforms.Resize([224, 224]),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485], std=[0.229])])
# train_dataset=LAEData_Train(transform=train_transformations) # Create tensor of training data
# Test_Dataset=LAEData_Test(transform=test_transformations)# Create tensor of test dataset
train_dataset = datasets.ImageFolder(
'/home/AC Collab/COVID/training_set/', transform=train_transformations)
#Test_Dataset = datasets.ImageFolder(
# '/test_set', transform=transform)
# Compute size of training data using (70% As Training and 30% As Validation)
train_size = int(0.7 * len(train_dataset))
# Compute size of validation data using (70% As Training and 30% As Validation)
test_size = len(train_dataset) - train_size
Train_Dataset1, Test_Dataset = torch.utils.data.random_split(train_dataset, [
train_size, test_size]) # Training and Validation Data After (70%-30%)Data Split
Train_size = int(0.7 * len(Train_Dataset1))
# Compute size of validation data using (70% As Training and 30% As Validation)
valid_size = len(Train_Dataset1) - Train_size
Train_Dataset, Valid_Dataset = torch.utils.data.random_split(Train_Dataset1, [
Train_size, valid_size]) # Training and
# train_set,test_set=torch.utils.data.random_split(dataset,[6000,2639])
# Labels=pd.read_csv("Devlopment.csv")
# Create Training Dataloader
train_loader = DataLoader(dataset=Train_Dataset,
batch_size=batch_size, shuffle=True)
# Create Validation Dataloader
valid_loader = DataLoader(dataset=Valid_Dataset,
batch_size=batch_size, shuffle=True)
# Create Test Dataloader
test_loader = DataLoader(dataset=Test_Dataset,
batch_size=batch_size, shuffle=False)
print("Train ",str(len(train_loader)))
print("Valid ",str(len(valid_loader)))
print("Test ",str(len(test_loader)))
class Teacher(nn.Module): # Subband-1 Network using Pre-Trained Resent-34
def __init__(self):
super(Teacher, self).__init__()
Pre_Trained_Layers = nn.Sequential(
*list(models.resnet50(pretrained=True).children())[:-2])
#Pre_Trained_Layers = list(models.resnet34(pretrained=True).children())[:-4]
# Pre_Trained_Layers = models.resnet34(pretrained=True) # Initialize model layers and weights
# print(Pre_Trained_Layers)
self.features = Pre_Trained_Layers
# self.PAM=PAM_Module(2048)
# self.CAM=CAM_Module(512)
self.features[0] = nn.Conv2d(3, 64, kernel_size=(7, 7), stride=(
2, 2), padding=(3, 3), bias=False) # Set input channels as 2
self.avgpool = nn.AdaptiveAvgPool2d(output_size=(1, 1))
# self.features.Flat=nn.Flatten()
# Set output layer as an one output
self.fc = nn.Linear(2048, num_classes)
def forward(self, image):
x1 = self.features(image)
# x1=self.PAM(x1)
# x2=self.CAM(x1)
# x3=x1+x2
x4 = self.avgpool(x1)
# x4=x3.view(x3.shape[0],-1)
x4 = x4.view(x4.size(0), -1)
# x4=torch.flatten(x4)
# print(x4.shape)
# x4=torch.unsqueeze(x4,-1)
# print(x4.shape)
x5 = self.fc(x4)
return x5
Teacher_Model = Teacher()
# print(Teacher_Model)
Teacher_Model = Teacher_Model.to(device)
Teacher_optimizer = optim.Adam(Teacher_Model.parameters(), lr=learning_rate)
criterion = nn.CrossEntropyLoss() # Define Loss Function
def calculate_accuracy(fx, y): # caluate accuracy
preds = fx.max(1, keepdim=True)[1]
correct = preds.eq(y.view_as(preds)).sum()
acc = correct.float()/preds.shape[0]
return acc
def train(model, device, iterator, optimizer, criterion): # Define Training Function
early_stopping = EarlyStopping(patience=7, verbose=True)
#print("Training Starts")
epoch_loss = 0
epoch_acc = 0
count = 0
model.train() # call model object for training
for (x, y) in iterator:
x = x.float()
# print(x.type())
x = x.to(device)
y = y.to(device) # Transfer label to device
optimizer.zero_grad() # Initialize gredients as zeros
count = count+1
# print(x.shape)
Predicted_Train_Label = model(x)
loss = criterion(Predicted_Train_Label, y) # training loss
acc = calculate_accuracy(Predicted_Train_Label, y) # training accuracy
#print("Training Iteration Number=",count)
loss.backward() # backpropogation
optimizer.step() # optimize the model weights using an optimizer
epoch_loss += loss.item() # sum of training loss
epoch_acc += acc.item() # sum of training accuracy
return epoch_loss / len(iterator), epoch_acc / len(iterator)
def evaluate(model, device, iterator, criterion): # Evaluate Validation accuracy
#print("Validation Starts")
epoch_loss = 0
epoch_acc = 0
count = 0
model.eval() # call model object for evaluation
with torch.no_grad(): # Without computation of gredient
for (x, y) in iterator:
x = x.float()
x = x.to(device) # Transfer data to device
y = y.to(device) # Transfer label to device
count = count+1
Predicted_Label = model(x) # Predict claa label
loss = criterion(Predicted_Label, y) # Compute Loss
acc = calculate_accuracy(Predicted_Label, y) # compute Accuracy
#print("Validation Iteration Number=",count)
epoch_loss += loss.item() # Compute Sum of Loss
epoch_acc += acc.item() # Compute Sum of Accuracy
return epoch_loss / len(iterator), epoch_acc / len(iterator)
# Define Path to save the model
# MODEL_SAVE_PATH = os.path.join(
# "/home/mani/Desktop/AK/COVID19", 'FB_COVID19_CNN.pt')
MODEL_SAVE_PATH = os.path.join(
"/home/AC Collab/COVID/Model", 'FB_COVID19_CNN.pt')
best_valid_loss = float('inf')
# Temp Matrix to Store all model accuracy, loss and time parameters
Temp = np.zeros([EPOCHS, 6])
print("CNN Model is in Training Mode")
print("---------------------------------------------------------------------------------------------------------------------")
early_stopping = EarlyStopping(
patience=7, verbose=True) # early Stopping Criteria
for epoch in range(EPOCHS):
start_time = time.time() # Compute Start Time
train_loss, train_acc = train(
Teacher_Model, device, train_loader, Teacher_optimizer, criterion) # Call Training Process
train_loss = round(train_loss, 2) # Round training loss
train_acc = round(train_acc, 2) # Round training accuracy
valid_loss, valid_acc = evaluate(
Teacher_Model, device, valid_loader, criterion) # Call Validation Process
valid_loss = round(valid_loss, 4) # Round validation loss
valid_acc = round(valid_acc, 2) # Round accuracy
end_time = (time.time()-start_time) # Compute End time
end_time = round(end_time, 2) # Round End Time
print(" | Epoch=", epoch, " | Training Accuracy=", train_acc*100, " | Validation Accuracy=", valid_acc*100,
" | Training Loss=", train_loss, " | Validation_Loss=", valid_loss, "Time Taken(Seconds)=", end_time, "|")
print("---------------------------------------------------------------------------------------------------------------------")
Temp[epoch, 0] = epoch # Store Epoch Number
Temp[epoch, 1] = train_acc # Store Training Accuracy
Temp[epoch, 2] = valid_acc # Store Validation Accuracy
Temp[epoch, 3] = train_loss # Store Training Loss
Temp[epoch, 4] = valid_loss # Store Validation Loss
Temp[epoch, 5] = end_time # Store Running Time of One Epoch
# call Early Stopping to Prevent Overfitting
early_stopping(valid_loss, Teacher_Model)
if early_stopping.early_stop:
print("Early stopping")
break
Teacher_Model.load_state_dict(torch.load(MODEL_SAVE_PATH))
np.save('Clean_Model_Training_Parameters', Temp) # Save Temp Array as numpy array
Teacher_Model.load_state_dict(torch.load(
MODEL_SAVE_PATH)) # load the trained model
# Compute Test Accuracy on Unseen Signals
test_loss, test_acc = evaluate(Teacher_Model, device, test_loader, criterion)
# test_loss=round(test_loss,2)# Round test loss
# test_acc=round(test_acc,2) # Round test accuracy
print("|Test Loss=", test_loss, "Test Accuracy=",
test_acc*100) # print test accuracy
|
[
"numpy.random.seed",
"pytorchtools.EarlyStopping",
"torch.device",
"torch.no_grad",
"os.path.join",
"torch.utils.data.DataLoader",
"torch.load",
"random.seed",
"torch.utils.data.random_split",
"torch.nn.Linear",
"numpy.save",
"torch.manual_seed",
"torch.nn.Conv2d",
"torch.cuda.manual_seed",
"torchvision.transforms.transforms.ToTensor",
"torchvision.datasets.ImageFolder",
"torchvision.models.resnet50",
"torch.nn.AdaptiveAvgPool2d",
"warnings.filterwarnings",
"torch.nn.CrossEntropyLoss",
"numpy.zeros",
"time.time",
"torchvision.transforms.transforms.Normalize",
"torchvision.transforms.transforms.Resize"
] |
[((1361, 1378), 'random.seed', 'random.seed', (['SEED'], {}), '(SEED)\n', (1372, 1378), False, 'import random\n'), ((1379, 1399), 'numpy.random.seed', 'np.random.seed', (['SEED'], {}), '(SEED)\n', (1393, 1399), True, 'import numpy as np\n'), ((1400, 1423), 'torch.manual_seed', 'torch.manual_seed', (['SEED'], {}), '(SEED)\n', (1417, 1423), False, 'import torch\n'), ((1424, 1452), 'torch.cuda.manual_seed', 'torch.cuda.manual_seed', (['SEED'], {}), '(SEED)\n', (1446, 1452), False, 'import torch\n'), ((1504, 1524), 'torch.device', 'torch.device', (['"""cuda"""'], {}), "('cuda')\n", (1516, 1524), False, 'import torch\n'), ((1858, 1891), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (1881, 1891), False, 'import warnings\n'), ((2457, 2554), 'torchvision.datasets.ImageFolder', 'datasets.ImageFolder', (['"""/home/AC Collab/COVID/training_set/"""'], {'transform': 'train_transformations'}), "('/home/AC Collab/COVID/training_set/', transform=\n train_transformations)\n", (2477, 2554), True, 'import torchvision.datasets as datasets\n'), ((2909, 2978), 'torch.utils.data.random_split', 'torch.utils.data.random_split', (['train_dataset', '[train_size, test_size]'], {}), '(train_dataset, [train_size, test_size])\n', (2938, 2978), False, 'import torch\n'), ((3300, 3371), 'torch.utils.data.random_split', 'torch.utils.data.random_split', (['Train_Dataset1', '[Train_size, valid_size]'], {}), '(Train_Dataset1, [Train_size, valid_size])\n', (3329, 3371), False, 'import torch\n'), ((3607, 3677), 'torch.utils.data.DataLoader', 'DataLoader', ([], {'dataset': 'Train_Dataset', 'batch_size': 'batch_size', 'shuffle': '(True)'}), '(dataset=Train_Dataset, batch_size=batch_size, shuffle=True)\n', (3617, 3677), False, 'from torch.utils.data import DataLoader\n'), ((3750, 3820), 'torch.utils.data.DataLoader', 'DataLoader', ([], {'dataset': 'Valid_Dataset', 'batch_size': 'batch_size', 'shuffle': '(True)'}), '(dataset=Valid_Dataset, batch_size=batch_size, shuffle=True)\n', (3760, 3820), False, 'from torch.utils.data import DataLoader\n'), ((3886, 3956), 'torch.utils.data.DataLoader', 'DataLoader', ([], {'dataset': 'Test_Dataset', 'batch_size': 'batch_size', 'shuffle': '(False)'}), '(dataset=Test_Dataset, batch_size=batch_size, shuffle=False)\n', (3896, 3956), False, 'from torch.utils.data import DataLoader\n'), ((5616, 5637), 'torch.nn.CrossEntropyLoss', 'nn.CrossEntropyLoss', ([], {}), '()\n', (5635, 5637), True, 'import torch.nn as nn\n'), ((8027, 8091), 'os.path.join', 'os.path.join', (['"""/home/AC Collab/COVID/Model"""', '"""FB_COVID19_CNN.pt"""'], {}), "('/home/AC Collab/COVID/Model', 'FB_COVID19_CNN.pt')\n", (8039, 8091), False, 'import os\n'), ((8204, 8225), 'numpy.zeros', 'np.zeros', (['[EPOCHS, 6]'], {}), '([EPOCHS, 6])\n', (8212, 8225), True, 'import numpy as np\n'), ((8409, 8448), 'pytorchtools.EarlyStopping', 'EarlyStopping', ([], {'patience': '(7)', 'verbose': '(True)'}), '(patience=7, verbose=True)\n', (8422, 8448), False, 'from pytorchtools import EarlyStopping\n'), ((10111, 10159), 'numpy.save', 'np.save', (['"""Clean_Model_Training_Parameters"""', 'Temp'], {}), "('Clean_Model_Training_Parameters', Temp)\n", (10118, 10159), True, 'import numpy as np\n'), ((5966, 6005), 'pytorchtools.EarlyStopping', 'EarlyStopping', ([], {'patience': '(7)', 'verbose': '(True)'}), '(patience=7, verbose=True)\n', (5979, 6005), False, 'from pytorchtools import EarlyStopping\n'), ((8526, 8537), 'time.time', 'time.time', ([], {}), '()\n', (8535, 8537), False, 'import time\n'), ((10224, 10251), 'torch.load', 'torch.load', (['MODEL_SAVE_PATH'], {}), '(MODEL_SAVE_PATH)\n', (10234, 10251), False, 'import torch\n'), ((1963, 1992), 'torchvision.transforms.transforms.Resize', 'transforms.Resize', (['[224, 224]'], {}), '([224, 224])\n', (1980, 1992), False, 'from torchvision.transforms import transforms\n'), ((1998, 2019), 'torchvision.transforms.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (2017, 2019), False, 'from torchvision.transforms import transforms\n'), ((2025, 2072), 'torchvision.transforms.transforms.Normalize', 'transforms.Normalize', ([], {'mean': '[0.485]', 'std': '[0.229]'}), '(mean=[0.485], std=[0.229])\n', (2045, 2072), False, 'from torchvision.transforms import transforms\n'), ((2141, 2170), 'torchvision.transforms.transforms.Resize', 'transforms.Resize', (['[224, 224]'], {}), '([224, 224])\n', (2158, 2170), False, 'from torchvision.transforms import transforms\n'), ((2176, 2197), 'torchvision.transforms.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (2195, 2197), False, 'from torchvision.transforms import transforms\n'), ((2203, 2250), 'torchvision.transforms.transforms.Normalize', 'transforms.Normalize', ([], {'mean': '[0.485]', 'std': '[0.229]'}), '(mean=[0.485], std=[0.229])\n', (2223, 2250), False, 'from torchvision.transforms import transforms\n'), ((4715, 4794), 'torch.nn.Conv2d', 'nn.Conv2d', (['(3)', '(64)'], {'kernel_size': '(7, 7)', 'stride': '(2, 2)', 'padding': '(3, 3)', 'bias': '(False)'}), '(3, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False)\n', (4724, 4794), True, 'import torch.nn as nn\n'), ((4858, 4898), 'torch.nn.AdaptiveAvgPool2d', 'nn.AdaptiveAvgPool2d', ([], {'output_size': '(1, 1)'}), '(output_size=(1, 1))\n', (4878, 4898), True, 'import torch.nn as nn\n'), ((5004, 5032), 'torch.nn.Linear', 'nn.Linear', (['(2048)', 'num_classes'], {}), '(2048, num_classes)\n', (5013, 5032), True, 'import torch.nn as nn\n'), ((7177, 7192), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (7190, 7192), False, 'import torch\n'), ((9073, 9084), 'time.time', 'time.time', ([], {}), '()\n', (9082, 9084), False, 'import time\n'), ((10082, 10109), 'torch.load', 'torch.load', (['MODEL_SAVE_PATH'], {}), '(MODEL_SAVE_PATH)\n', (10092, 10109), False, 'import torch\n'), ((4300, 4332), 'torchvision.models.resnet50', 'models.resnet50', ([], {'pretrained': '(True)'}), '(pretrained=True)\n', (4315, 4332), False, 'from torchvision import models\n')]
|
# To add a new cell, type '# %%'
# To add a new markdown cell, type '# %% [markdown]'
# %%
import math
import numpy as np
import matplotlib.pyplot as plt
import struct
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.data as D
import os
import multiprocessing as mp
os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
# %%
def loadData(file):
try:
File = open(file, 'rb')
except IOError:
print("open error")
File.close()
return
# 读取文件头
label = {
'RECORD_BYTES':0,
'FILE_RECORDS':0,
'LABEL_RECORDS':0,
'^IMAGE':0,
'^IMAGE_PREFIX':0,
' ROWS':0,
' ROW_BYTES':0,
' LINES':0,
}
while True:
line = File.readline()
lbl = line.decode('utf8').replace('\t', '').strip('\n').split("=")
if lbl[0] == 'END':# 文件头读完了
break
if lbl[0] in label:
label[lbl[0]] = int(lbl[1])
# 跳过空行
skip = File.readline()
# 线阵数量
lines = label[' LINES']
# 每个像素由32*32个像素取平均构成,坐标取第一个像素的起始点的纬度经度跨越的四分点
height_pixels = 32
width_pixels = 32
height = int(lines/height_pixels)
width = int(128/width_pixels)
total = height*width
skip_lines = lines%height_pixels
# 读取经纬度列表,位置直接对应对应点的索引位置
inf = File.readline(67*lines)
inf = inf.decode('utf8').replace(' ', '').split("\t")# 整行经纬度表都在这里
pos_lon = np.empty((total))# 经度
pos_lat = np.empty((total))# 维度
# 每个线阵的数据格式:2008-12-04T05:04:01.420Z 0 121.2097 -77.4942 124.8695 -77.4382
for i in range(height):
for j in range(width):
pos_lon[i*width + j] = float(inf[6*height_pixels*i + 2]) + j*(float(inf[6*height_pixels*i + 4]) - float(inf[6*height_pixels*i + 2]))/width
pos_lat[i*width + j] = float(inf[6*height_pixels*i + 3])
# 经纬度表后面有部分补全符号,剔除
skip = File.readline(label[' ROWS']*label[' ROW_BYTES']-67*lines)
# 读图像
f = File.read()
iim_np = np.empty((total,21))# iim图像记录,total,21个波段连续记录
# print(iim_np)# test
# 使用的波段记录
useBand = [i for i in range(11,32)]
usepBand = tuple(useBand)
fmt = '>' + str(width_pixels) + 'f'
offset = 0
skipset = 4*128*lines# 对于不用的波段,全波段跳过一共n条线阵*128*4bytes的大小
# print(skipset) # test
for band in range(32):# test
if band not in useBand:
offset += skipset# 跳过整个波段
continue
# for line in range(label[' LINES']):
pixel = 0
while pixel < total:# 开始处理4个像素
temp = np.zeros(width)
# print(temp) # test
for line in range(height_pixels):
for unit in range(width):
temp[unit] += np.mean(struct.unpack_from(fmt, f, offset))
offset += struct.calcsize(fmt)
# # where is nan???
# if np.min(temp) == np.nan or np.max(temp) != np.nan:
# print('nan!',offset)
# raise NameError
for unit in range(width):
iim_np[pixel][band - 11] = temp[unit]/32.0
pixel += 1
offset += 4*128*skip_lines# 尾部用不到的线阵
print("load a file finished")# test
File.close()
# print(np.shape(iim_np))
# # 哪来的nan???
# if np.min(iim_np) == np.nan or np.max(iim_np) != np.nan:
# print('nan!')
# raise TypeError
return total, pos_lon, pos_lat, iim_np
# %%
def loadFileList(file):
files = open(file,'r')
f = files.readlines()
files.close()
return [item.replace('\n','').replace('\r','') for item in f]
# %%
class Network(nn.Module):
def __init__(self, n_feature, n_hidden, n_output):
super(Network, self).__init__()
self.fc = torch.nn.Linear(n_feature, n_hidden)
self.out = torch.nn.Linear(n_hidden, n_output)
def forward(self, x):
x = F.relu(self.fc(x))
x = self.out(x)
x = F.sigmoid(x)
x = 100*x
return x
# %%
# 初始化模型
filestr='./modelV'
network = torch.load(filestr)
# %%
# 载入2C文件路径
file = 'files400.txt'
fileList = loadFileList(file)
# fileList = ('/mnt/c/ShareCache/施朱鸣_1800011723/Expe/TrainingSet/CE1_IIM_2C_20081112091027_20081130231727_A/DATA/CE1_BMYK_IIM_SCI_N_20080702001309_20080702021955_2700_A.2C',)
# fileList = ('/mnt/c/ShareCache/施朱鸣_1800011723/Expe/TrainingSet/CE1_IIM_2C_20081112091027_20081130231727_A/DATA/CE1_BMYK_IIM_SCI_N_20081202154348_20081202175129_4439_A.2C',)
# %%
# 初始化图,全局变量!
# fig = np.zeros((8,900,1800))
# fig = mp.Array('f', 8*900*1800)
# %%
iim = np.zeros((21*900*1800))
iim = mp.Array('f',iim)
# %%
def runs(file):
Nnan = 0
Nillegal = 0
Nnum = 0
# global fig
# print('what happend')
try:
total_pixel, position_lon, position_lat, iim_np = loadData(file)
# except TypeError:
# print('nan in iim of ',file,'error!')
# return
# except NameError:
# print('nan in temp of ',file,'error!')
# return
except BaseException:
print('open file ',file,'error!')
return
# print(file)
# 记录抽取的数据
for band in range(21):
for i in range(total_pixel):
# fig[band][int(5*position_lat[i])+450][int(5*position_lon[i])+900] = figure[band][i]
if math.isnan(iim_np[i][band]):# 跳过nan
Nnan += 1
continue
elif iim_np[i][band]>1.0001 or iim_np[i][band]<-0.0001:
Nillegal += 1
continue
else :
Nnum += 1
iim[band*900*1800+(int(5*position_lat[i])+450)*1800+int(5*position_lon[i])+900] = iim_np[i][band]
# 喂给网络
# spec = torch.FloatTensor(iim_np)
# out = network(spec)
# figure = out.detach().numpy().T
# for band in range(8):
# for i in range(total_pixel):
# # fig[band][int(5*position_lat[i])+450][int(5*position_lon[i])+900] = figure[band][i]
# if math.isnan(figure[band][i]):
# Nnan += 1
# continue
# else :
# Nnum += 1
# fig[band*900*1800+(int(5*position_lat[i])+450) *
# 1800+int(5*position_lon[i])+900] = figure[band][i]
print(file[-10:-4],'nillegal:',Nillegal,'nan:',Nnan,'num:',Nnum)
# %%
# 多线程设定发
cores=mp.cpu_count()
pool=mp.Pool(processes=cores)
# 多线程读写图
pool.map(runs,fileList)
# %%
print('load data finished')
# %%
iim = np.array(list(iim)).reshape((21,900*1800))
np.save("nancatch400iim.np",iim)
spec = torch.FloatTensor(iim.T)
out = network(spec)
figure = out.detach().numpy().T
fig = figure.reshape(8, 900, 1800)
# %%
# 把压缩的数组恢复
# fig = np.array(list(fig)).reshape((8, 900, 1800))
# %% [markdown]
# 经度划分为1800个密位,维度划分为900个密位,转换公式:
#
# 经度 lon = int(5*lon) + 900
#
# 纬度 lat = int(5*lat) + 450
# %%
# %%
# # 存取图,避免重复读取大数据
np.save("nancatch400fig.np",fig)
# b = np.load("fig.np")
# %%
# 作图,先作一个维度看看
# plt.imshow(fig[0], cmap ='gray')
# plt.imsave('nancatch20.png', fig[0])
# plt.imsave('nancatch20gray.png', fig[0], cmap='gray')
# %%
for i in range(8):
plt.imsave('nancatch400gray'+str(i)+'.png', fig[i], cmap='gray')
|
[
"math.isnan",
"numpy.save",
"struct.unpack_from",
"multiprocessing.Array",
"numpy.empty",
"torch.load",
"numpy.zeros",
"torch.FloatTensor",
"struct.calcsize",
"torch.nn.Linear",
"torch.nn.functional.sigmoid",
"multiprocessing.Pool",
"multiprocessing.cpu_count"
] |
[((4021, 4040), 'torch.load', 'torch.load', (['filestr'], {}), '(filestr)\n', (4031, 4040), False, 'import torch\n'), ((4560, 4585), 'numpy.zeros', 'np.zeros', (['(21 * 900 * 1800)'], {}), '(21 * 900 * 1800)\n', (4568, 4585), True, 'import numpy as np\n'), ((4590, 4608), 'multiprocessing.Array', 'mp.Array', (['"""f"""', 'iim'], {}), "('f', iim)\n", (4598, 4608), True, 'import multiprocessing as mp\n'), ((6298, 6312), 'multiprocessing.cpu_count', 'mp.cpu_count', ([], {}), '()\n', (6310, 6312), True, 'import multiprocessing as mp\n'), ((6318, 6342), 'multiprocessing.Pool', 'mp.Pool', ([], {'processes': 'cores'}), '(processes=cores)\n', (6325, 6342), True, 'import multiprocessing as mp\n'), ((6467, 6500), 'numpy.save', 'np.save', (['"""nancatch400iim.np"""', 'iim'], {}), "('nancatch400iim.np', iim)\n", (6474, 6500), True, 'import numpy as np\n'), ((6508, 6532), 'torch.FloatTensor', 'torch.FloatTensor', (['iim.T'], {}), '(iim.T)\n', (6525, 6532), False, 'import torch\n'), ((6834, 6867), 'numpy.save', 'np.save', (['"""nancatch400fig.np"""', 'fig'], {}), "('nancatch400fig.np', fig)\n", (6841, 6867), True, 'import numpy as np\n'), ((1445, 1460), 'numpy.empty', 'np.empty', (['total'], {}), '(total)\n', (1453, 1460), True, 'import numpy as np\n'), ((1481, 1496), 'numpy.empty', 'np.empty', (['total'], {}), '(total)\n', (1489, 1496), True, 'import numpy as np\n'), ((2008, 2029), 'numpy.empty', 'np.empty', (['(total, 21)'], {}), '((total, 21))\n', (2016, 2029), True, 'import numpy as np\n'), ((3743, 3779), 'torch.nn.Linear', 'torch.nn.Linear', (['n_feature', 'n_hidden'], {}), '(n_feature, n_hidden)\n', (3758, 3779), False, 'import torch\n'), ((3799, 3834), 'torch.nn.Linear', 'torch.nn.Linear', (['n_hidden', 'n_output'], {}), '(n_hidden, n_output)\n', (3814, 3834), False, 'import torch\n'), ((3929, 3941), 'torch.nn.functional.sigmoid', 'F.sigmoid', (['x'], {}), '(x)\n', (3938, 3941), True, 'import torch.nn.functional as F\n'), ((2558, 2573), 'numpy.zeros', 'np.zeros', (['width'], {}), '(width)\n', (2566, 2573), True, 'import numpy as np\n'), ((5274, 5301), 'math.isnan', 'math.isnan', (['iim_np[i][band]'], {}), '(iim_np[i][band])\n', (5284, 5301), False, 'import math\n'), ((2805, 2825), 'struct.calcsize', 'struct.calcsize', (['fmt'], {}), '(fmt)\n', (2820, 2825), False, 'import struct\n'), ((2739, 2773), 'struct.unpack_from', 'struct.unpack_from', (['fmt', 'f', 'offset'], {}), '(fmt, f, offset)\n', (2757, 2773), False, 'import struct\n')]
|
'''
The proposed methoed: DynWalks
---------------------------------
scheme=3, # the final version of DynWalks presented and tested in our paper
limit=0.1, local_global=0.5 # DynWalks key hyper-parameters
# NOTE: limit i.e. $\alpha$, local_global i.e. $\beta$ in our paper
num_walks=20, walk_length=80, # random walk hyper-parameters
window=10, negative=5, # Skig-Gram hyper-parameters
seed=2019, workers=20, # others
G0 # graph at previous time step 't-1'
G1 # graph at current time step 't'
---------------------------------
by <NAME>
'''
import time
import random
import pickle
import warnings
warnings.filterwarnings(action='ignore', category=UserWarning, module='gensim')
import gensim
import logging
import numpy as np
import networkx as nx
from .utils import edge_s1_minus_s0, unique_nodes_from_edge_set
# ===============================================================================================================================
# =========================== CORE1: Overall framework to learn node embeddings in an online manner =============================
# ===============================================================================================================================
class DynWalks(object):
def __init__(self, G_dynamic, limit, local_global, num_walks, walk_length, window,
emb_dim, negative, workers, seed, scheme):
self.G_dynamic = G_dynamic.copy() # a series of dynamic graphs
self.emb_dim = emb_dim # node emb dimensionarity
self.num_walks = num_walks # num of walks start from each node
self.walk_length = walk_length # walk length for each walk
self.window = window # Skip-Gram parameter
self.workers = workers # Skip-Gram parameter
self.negative = negative # Skip-Gram parameter
self.seed = seed # Skip-Gram parameter
self.scheme = scheme
self.limit = limit
self.local_global = local_global # balancing factor for local changes and global topology
self.emb_dicts = [] # emb_dict @ t0, t1, ...; len(self.emb_dicts) == len(self.G_dynamic)
self.reservoir = {} # {nodeID: num of affected, ...}
def sampling_traning(self):
# SGNS and suggested parameters to be tuned: size, window, negative, workers, seed
# to tune other parameters, please read https://radimrehurek.com/gensim/models/word2vec.html#gensim.models.word2vec.Word2Vec
w2v = gensim.models.Word2Vec(sentences=None, size=self.emb_dim, window=self.window, sg=1, hs=0, negative=self.negative, ns_exponent=0.75,
alpha=0.025, min_alpha=0.0001, min_count=1, sample=0.001, iter=4, workers=self.workers, seed=self.seed,
corpus_file=None, sorted_vocab=1, batch_words=10000, compute_loss=False,
max_vocab_size=None, max_final_vocab=None, trim_rule=None) # w2v constructor, default parameters
for t in range(len(self.G_dynamic)):
t1 = time.time()
if t ==0: # offline ----------------------------
G0 = self.G_dynamic[t] # initial graph
sentences = simulate_walks(nx_graph=G0, num_walks=self.num_walks, walk_length=self.walk_length)
sentences = [[str(j) for j in i] for i in sentences]
w2v.build_vocab(sentences=sentences, update=False) # init traning, so update False
w2v.train(sentences=sentences, total_examples=w2v.corpus_count, epochs=w2v.iter) # follow w2v constructor
else: # online adapting --------------------
G0 = self.G_dynamic[t-1] # previous graph
G1 = self.G_dynamic[t] # current graph
node_update_list, self.reservoir = node_selecting_scheme(graph_t0=G0, graph_t1=G1, reservoir_dict=self.reservoir,
limit=self.limit, local_global=self.local_global, scheme=self.scheme)
# print(node_update_list)
# node_update_list_2_txt(node_update_list,'node_update_list.txt')
sentences = simulate_walks(nx_graph=G1, num_walks=self.num_walks, walk_length=self.walk_length, affected_nodes=node_update_list)
# sentences_2_pkl(sentences,'sentences.pkl')
# with open('sentences.pkl', 'rb') as f:
# any_object = pickle.load(f)
# print(any_object)
# exit(0)
sentences = [[str(j) for j in i] for i in sentences]
w2v.build_vocab(sentences=sentences, update=True) # online update
w2v.train(sentences=sentences, total_examples=w2v.corpus_count, epochs=w2v.iter)
emb_dict = {} # {nodeID: emb_vector, ...}
for node in self.G_dynamic[t].nodes():
emb_dict[node] = w2v.wv[str(node)]
self.emb_dicts.append(emb_dict)
t2 = time.time()
print(f'DynWalks sampling and traning time: {(t2-t1):.2f}s --> {t+1}/{len(self.G_dynamic)}')
return self.emb_dicts # To save memory useage, we can delete DynWalks model after training
def save_emb(self, path='unnamed_dyn_emb_dicts.pkl'):
''' save # emb_dict @ t0, t1, ... to a file using pickle
'''
with open(path, 'wb') as f:
pickle.dump(self.emb_dicts, f, protocol=pickle.HIGHEST_PROTOCOL)
def load_emb(self, path='unnamed_dyn_emb_dicts.pkl'):
''' load # emb_dict @ t0, t1, ... to a file using pickle
'''
with open(path, 'rb') as f:
any_object = pickle.load(f)
return any_object
# ================================================================================================================================
# ======================================= CORE2: online node selecting scheme ====================================================
# ================================================================================================================================
def node_selecting_scheme(graph_t0, graph_t1, reservoir_dict, limit=0.1, local_global=0.5, scheme=3):
''' select nodes to be updated
G0: previous graph @ t-1;
G1: current graph @ t;
reservoir_dict: will be always maintained in ROM
limit: fix the number of node --> the percentage of nodes of a network to be updated (exclude new nodes)
local_global: # of nodes from recent changes v.s. from random nodes
scheme 1: new nodes + most affected nodes
scheme 2: new nodes + diverse nodes
scheme 3: new nodes + most affected nodes + diverse nodes (the one we presented and tested in our paper)
'''
G0 = graph_t0.copy()
G1 = graph_t1.copy()
edge_add = edge_s1_minus_s0(s1=set(G1.edges()), s0=set(G0.edges())) # one may directly use streaming added edges if possible
edge_del = edge_s1_minus_s0(s1=set(G0.edges()), s0=set(G1.edges())) # one may directly use streaming added edges if possible
node_affected_by_edge_add = unique_nodes_from_edge_set(edge_add) # unique
node_affected_by_edge_del = unique_nodes_from_edge_set(edge_del) # unique
node_affected = list(set(node_affected_by_edge_add + node_affected_by_edge_del)) # unique
node_add = [node for node in node_affected_by_edge_add if node not in G0.nodes()]
node_del = [node for node in node_affected_by_edge_del if node not in G1.nodes()]
if len(node_del) !=0:
reservoir_key_list = list(reservoir_dict.keys())
for node in node_del:
if node in reservoir_key_list:
del reservoir_dict[node] # if node being deleted, also delete it from reservoir
exist_node_affected = list(set(node_affected) - set(node_add) - set(node_del)) # affected nodes are in both G0 and G1
t1 = time.time()
# for fair comparsion, the number of nodes to be updated are the same for schemes 1, 2, 3
num_limit = int(G1.number_of_nodes() * limit)
local_limit = int(local_global * num_limit)
global_limit = num_limit - local_limit
node_update_list = [] # all the nodes to be updated
if scheme == 1:
print('scheme == 1')
most_affected_nodes, reservoir_dict = select_most_affected_nodes(G0, G1, num_limit, reservoir_dict, exist_node_affected)
if len(most_affected_nodes) != 0:
if len(most_affected_nodes) < num_limit: # for fairness, resample until meets num_limit
temp_num = num_limit - len(most_affected_nodes)
temp_nodes = list(np.random.choice(most_affected_nodes+node_add, temp_num, replace=True))
most_affected_nodes.extend(temp_nodes)
node_update_list = node_add + most_affected_nodes
else:
print('nothing changed... For fairness, randomly update some as scheme 2 does')
all_nodes = [node for node in G1.nodes()]
random_nodes = list(np.random.choice(all_nodes, num_limit, replace=False))
node_update_list = node_add + random_nodes
if scheme == 2:
print('scheme == 2')
all_nodes = [node for node in G1.nodes()]
random_nodes = list(np.random.choice(all_nodes, num_limit, replace=False))
node_update_list = node_add + random_nodes
# node_update_list = ['1','1','1']
#-----------------------------------------------------------------------------------------------------------------
# scheme 3: new nodes + most affected nodes + diverse nodes (the one we presented and tested in our paper)
#-----------------------------------------------------------------------------------------------------------------
if scheme == 3: # trade-off between local recent changes and global topology by 'local_global' (defalt 0.5)
print('scheme == 3')
most_affected_nodes, reservoir_dict = select_most_affected_nodes(G0, G1, local_limit, reservoir_dict, exist_node_affected)
lack = local_limit - len(most_affected_nodes) # if the changes are relatively smaller than local_limit, sample some random nodes for compensation
tabu_nodes = set(node_add + most_affected_nodes)
other_nodes = list( set(G1.nodes()) - tabu_nodes )
random_nodes = list(np.random.choice(other_nodes, min(global_limit+lack, len(other_nodes)), replace=False))
node_update_list = node_add + most_affected_nodes + random_nodes
reservoir_key_list = list(reservoir_dict.keys())
node_update_set = set(node_update_list) # remove repeated nodes due to resample
for node in node_update_set:
if node in reservoir_key_list:
del reservoir_dict[node] # if updated, delete it
t2 = time.time()
print(f'--> node selecting time; time cost: {(t2-t1):.2f}s')
print(f'num_limit {num_limit}, local_limit {local_limit}, global_limit {global_limit}, # nodes updated {len(node_update_list)}')
print(f'# nodes added {len(node_add)}, # nodes deleted {len(node_del)}')
print(f'# nodes affected {len(node_affected)}, # nodes most affected {len(most_affected_nodes)}, # of random nodes {len(random_nodes)}')
print(f'num of nodes in reservoir with accumulated changes but not updated {len(list(reservoir_dict))}')
return node_update_list, reservoir_dict
# ==============================================================================================================================
# ========================================= CORE3: select the most affected nodes ==============================================
# ==============================================================================================================================
def select_most_affected_nodes(G0, G1, num_limit_return_nodes, reservoir_dict, exist_node_affected):
''' return num_limit_return_nodes to be updated
based on the ranking of the accumulated changes w.r.t. their local connectivity
'''
most_affected_nodes = []
for node in exist_node_affected:
nbrs_set1 = set(nx.neighbors(G=G1, n=node))
nbrs_set0 = set(nx.neighbors(G=G0, n=node))
changes = len( nbrs_set1.union(nbrs_set0) - nbrs_set1.intersection(nbrs_set0) )
if node in reservoir_dict.keys():
reservoir_dict[node] += changes # accumulated changes
else:
reservoir_dict[node] = changes # newly added changes
if len(exist_node_affected) > num_limit_return_nodes:
reservoir_dict_score = {}
for node in exist_node_affected:
reservoir_dict_score[node] = reservoir_dict[node] / G0.degree[node]
# worse case O(n) https://docs.scipy.org/doc/numpy/reference/generated/numpy.partition.html
# the largest change at num_limit_return_nodes will be returned
cutoff_score = np.partition(list(reservoir_dict_score.values()), -num_limit_return_nodes, kind='introselect')[-num_limit_return_nodes]
cnt = 0
for node in reservoir_dict_score.keys():
if reservoir_dict_score[node] >= cutoff_score: # fix bug: there might be multiple equal cutoff_score nodes...
if cnt == num_limit_return_nodes: # fix bug: we need exactly the number of limit return nodes...
break
most_affected_nodes.append(node)
cnt += 1
else: #NOTE: len(exist_node_affected) <= num_limit_return_nodes
most_affected_nodes = exist_node_affected
return most_affected_nodes, reservoir_dict
# =====================================================================================================================================
# ========================================= CORE4: random walk sampling, and other utils ==============================================
# =====================================================================================================================================
def simulate_walks(nx_graph, num_walks, walk_length, restart_prob=None, affected_nodes=None):
'''
Repeatedly simulate random walks from each node
'''
G = nx_graph
walks = []
if affected_nodes == None: # simulate walks on every node in the graph [offline]
nodes = list(G.nodes())
else: # simulate walks on affected nodes [online]
nodes = list(affected_nodes)
''' multi-processors; use it iff the # of nodes over 20k
if restart_prob == None: # naive random walk
t1 = time.time()
for walk_iter in range(num_walks):
random.shuffle(nodes)
from itertools import repeat
from multiprocessing import Pool, freeze_support
with Pool(processes=5) as pool:
# results = [pool.apply_async(random_walk, args=(G, node, walk_length)) for node in nodes]
# results = [p.get() for p in results]
results = pool.starmap(random_walk, zip(repeat(G), nodes, repeat(walk_length)))
for result in results:
walks.append(result)
t2 = time.time()
print('all walks',len(walks))
print(f'random walk sampling, time cost: {(t2-t1):.2f}')
'''
if restart_prob == None: # naive random walk
t1 = time.time()
for walk_iter in range(num_walks):
random.shuffle(nodes)
for node in nodes:
walks.append(random_walk(nx_graph=G, start_node=node, walk_length=walk_length))
t2 = time.time()
print(f'random walk sampling, time cost: {(t2-t1):.2f}')
else: # random walk with restart
t1 = time.time()
for walk_iter in range(num_walks):
random.shuffle(nodes)
for node in nodes:
walks.append(random_walk_restart(nx_graph=G, start_node=node, walk_length=walk_length, restart_prob=restart_prob))
t2 = time.time()
print(f'random walk sampling, time cost: {(t2-t1):.2f}')
return walks
def random_walk(nx_graph, start_node, walk_length):
'''
Simulate a random walk starting from start node
'''
G = nx_graph
walk = [start_node]
while len(walk) < walk_length:
cur = walk[-1]
cur_nbrs = list(G.neighbors(cur))
if len(cur_nbrs) > 0:
walk.append(random.choice(cur_nbrs))
else:
break
return walk
def random_walk_restart(nx_graph, start_node, walk_length, restart_prob):
'''
random walk with restart
restart if p < restart_prob
'''
G = nx_graph
walk = [start_node]
while len(walk) < walk_length:
p = random.uniform(0, 1)
if p < restart_prob:
cur = walk[0] # restart
walk.append(cur)
else:
cur = walk[-1]
cur_nbrs = list(G.neighbors(cur))
if len(cur_nbrs) > 0:
walk.append(random.choice(cur_nbrs))
else:
break
return walk
def node_update_list_2_txt(my_list, path):
with open(path, 'w') as f:
for item in my_list:
f.write("%s\n" % item)
def sentences_2_pkl(my_list, path):
import collections
new_list = []
for items in my_list:
for item in items:
new_list.append(item)
c = collections.Counter(new_list)
with open(path, 'wb') as f:
pickle.dump(c, f, protocol=pickle.HIGHEST_PROTOCOL)
def select_most_affected_nodes_nbrs(G1, most_affected_nodes):
most_affected_nbrs = []
for node in most_affected_nodes:
most_affected_nbrs.extend( list(nx.neighbors(G=G1, n=node)) )
return list(set(most_affected_nbrs))
|
[
"pickle.dump",
"random.uniform",
"warnings.filterwarnings",
"random.shuffle",
"gensim.models.Word2Vec",
"random.choice",
"time.time",
"networkx.neighbors",
"pickle.load",
"numpy.random.choice",
"collections.Counter"
] |
[((759, 838), 'warnings.filterwarnings', 'warnings.filterwarnings', ([], {'action': '"""ignore"""', 'category': 'UserWarning', 'module': '"""gensim"""'}), "(action='ignore', category=UserWarning, module='gensim')\n", (782, 838), False, 'import warnings\n'), ((8235, 8246), 'time.time', 'time.time', ([], {}), '()\n', (8244, 8246), False, 'import time\n'), ((11188, 11199), 'time.time', 'time.time', ([], {}), '()\n', (11197, 11199), False, 'import time\n'), ((17944, 17973), 'collections.Counter', 'collections.Counter', (['new_list'], {}), '(new_list)\n', (17963, 17973), False, 'import collections\n'), ((2652, 3042), 'gensim.models.Word2Vec', 'gensim.models.Word2Vec', ([], {'sentences': 'None', 'size': 'self.emb_dim', 'window': 'self.window', 'sg': '(1)', 'hs': '(0)', 'negative': 'self.negative', 'ns_exponent': '(0.75)', 'alpha': '(0.025)', 'min_alpha': '(0.0001)', 'min_count': '(1)', 'sample': '(0.001)', 'iter': '(4)', 'workers': 'self.workers', 'seed': 'self.seed', 'corpus_file': 'None', 'sorted_vocab': '(1)', 'batch_words': '(10000)', 'compute_loss': '(False)', 'max_vocab_size': 'None', 'max_final_vocab': 'None', 'trim_rule': 'None'}), '(sentences=None, size=self.emb_dim, window=self.\n window, sg=1, hs=0, negative=self.negative, ns_exponent=0.75, alpha=\n 0.025, min_alpha=0.0001, min_count=1, sample=0.001, iter=4, workers=\n self.workers, seed=self.seed, corpus_file=None, sorted_vocab=1,\n batch_words=10000, compute_loss=False, max_vocab_size=None,\n max_final_vocab=None, trim_rule=None)\n', (2674, 3042), False, 'import gensim\n'), ((15830, 15841), 'time.time', 'time.time', ([], {}), '()\n', (15839, 15841), False, 'import time\n'), ((16073, 16084), 'time.time', 'time.time', ([], {}), '()\n', (16082, 16084), False, 'import time\n'), ((16205, 16216), 'time.time', 'time.time', ([], {}), '()\n', (16214, 16216), False, 'import time\n'), ((16483, 16494), 'time.time', 'time.time', ([], {}), '()\n', (16492, 16494), False, 'import time\n'), ((17241, 17261), 'random.uniform', 'random.uniform', (['(0)', '(1)'], {}), '(0, 1)\n', (17255, 17261), False, 'import random\n'), ((18018, 18069), 'pickle.dump', 'pickle.dump', (['c', 'f'], {'protocol': 'pickle.HIGHEST_PROTOCOL'}), '(c, f, protocol=pickle.HIGHEST_PROTOCOL)\n', (18029, 18069), False, 'import pickle\n'), ((3222, 3233), 'time.time', 'time.time', ([], {}), '()\n', (3231, 3233), False, 'import time\n'), ((5279, 5290), 'time.time', 'time.time', ([], {}), '()\n', (5288, 5290), False, 'import time\n'), ((5697, 5761), 'pickle.dump', 'pickle.dump', (['self.emb_dicts', 'f'], {'protocol': 'pickle.HIGHEST_PROTOCOL'}), '(self.emb_dicts, f, protocol=pickle.HIGHEST_PROTOCOL)\n', (5708, 5761), False, 'import pickle\n'), ((5974, 5988), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (5985, 5988), False, 'import pickle\n'), ((9632, 9685), 'numpy.random.choice', 'np.random.choice', (['all_nodes', 'num_limit'], {'replace': '(False)'}), '(all_nodes, num_limit, replace=False)\n', (9648, 9685), True, 'import numpy as np\n'), ((12511, 12537), 'networkx.neighbors', 'nx.neighbors', ([], {'G': 'G1', 'n': 'node'}), '(G=G1, n=node)\n', (12523, 12537), True, 'import networkx as nx\n'), ((12565, 12591), 'networkx.neighbors', 'nx.neighbors', ([], {'G': 'G0', 'n': 'node'}), '(G=G0, n=node)\n', (12577, 12591), True, 'import networkx as nx\n'), ((15902, 15923), 'random.shuffle', 'random.shuffle', (['nodes'], {}), '(nodes)\n', (15916, 15923), False, 'import random\n'), ((16277, 16298), 'random.shuffle', 'random.shuffle', (['nodes'], {}), '(nodes)\n', (16291, 16298), False, 'import random\n'), ((9383, 9436), 'numpy.random.choice', 'np.random.choice', (['all_nodes', 'num_limit'], {'replace': '(False)'}), '(all_nodes, num_limit, replace=False)\n', (9399, 9436), True, 'import numpy as np\n'), ((16912, 16935), 'random.choice', 'random.choice', (['cur_nbrs'], {}), '(cur_nbrs)\n', (16925, 16935), False, 'import random\n'), ((18242, 18268), 'networkx.neighbors', 'nx.neighbors', ([], {'G': 'G1', 'n': 'node'}), '(G=G1, n=node)\n', (18254, 18268), True, 'import networkx as nx\n'), ((8984, 9056), 'numpy.random.choice', 'np.random.choice', (['(most_affected_nodes + node_add)', 'temp_num'], {'replace': '(True)'}), '(most_affected_nodes + node_add, temp_num, replace=True)\n', (9000, 9056), True, 'import numpy as np\n'), ((17528, 17551), 'random.choice', 'random.choice', (['cur_nbrs'], {}), '(cur_nbrs)\n', (17541, 17551), False, 'import random\n')]
|
#%%
import pandas as pd
import pickle
import numpy as np
import matplotlib.pyplot as plt
import gensim
import sklearn.decomposition
import sklearn.manifold
from sklearn.neural_network import MLPClassifier
#%%
#--Read in data
D2V_WOstop = gensim.models.Doc2Vec.load(r'..\data\process\D2V_WOstop')
df = pd.read_csv(r'..\data\df_cb_main_combined.csv', index_col=0, encoding='utf-8', error_bad_lines=False).dropna(subset=['Review']).drop_duplicates(['Author', 'Game'])
df_core = pickle.load(open(r'..\data\process\core_cluster.p', 'rb'))
#%%
#--Acquire game vecs and separate into core and other games
core_idTags = []
core_groups = []
core_vecs = []
other_idTags = []
other_groups = []
other_titles = []
other_vecs = []
for index, row in df.iterrows():
idTag = 'id_' + str(index)
vec = D2V_WOstop.docvecs[idTag]
title = row['Game']
if row['CoreID'] > 0:
group = (df_core[df_core['core_id'] == row['CoreID']])['group_label'].values[0]
core_idTags.append(idTag)
core_groups.append(group)
core_vecs.append(vec)
elif row['CoreID'] == 0:
other_idTags.append(idTag)
other_vecs.append(vec)
other_titles.append(title)
core_vec = np.array(core_vecs)
other_vec = np.array(other_vecs)
numOfCluster = len(df_core.group_label.unique())
#%%
#--Dimension reduction for visualization
#Reduce dimension to 2 by PCA
pcaDocs = sklearn.decomposition.PCA(n_components=2).fit(np.vstack((core_vec, other_vec)))
reducedPCA = pcaDocs.transform(other_vec)
x_other = reducedPCA[:, 0]
y_other = reducedPCA[:, 1]
#Reduce dimension to 2 by TSNE
tsneGames = sklearn.manifold.TSNE(n_components=2).fit_transform(other_vec)
x_other_tsne = tsneGames[:, 0]
y_other_tsne = tsneGames[:, 1]
#%%
#--Initialize and train the model
clf = MLPClassifier()
clf.fit(core_vec, core_groups)
#Acquire predicted labels
labels = clf.predict(other_vec)
labels.shape
#Acquire predicted probabilities
probs = pd.DataFrame(clf.predict_proba(other_vec))
probs.columns = np.arange(1, 8) #Rename column to conform to the predicted label
probs.shape
#%%
#Save the predicted clusters and scores
df_predicted = df.query('CoreID == 0').copy()
df_predicted['Predicted'] = labels
probs = probs.set_index(df_predicted.index)
df_predicted = pd.concat([df_predicted, probs], axis=1)
df_predicted.to_csv(r'..\data\output\df_predicted.csv', index=False, encoding='utf-8')
#%%
#Prepare games to be plotted
TARGET = pd.read_csv(r'..\data\target_for_elaborate.csv', encoding='utf-8', header=None)[0].tolist()
coor_target = []
coor_target_tsne = []
for game in TARGET:
index = other_titles.index(game)
coor_target.append(reducedPCA[index])
coor_target_tsne.append(tsneGames[index])
#%%
#--Color map for predicted labels
#Make color dictionary
colordict = {
0: '#d53e4f',
1: '#f46d43',
2: '#fdae61',
3: '#ffffbf',
4: '#abdda4',
5: '#66c2a5',
6: '#3288bd',
7: '#fee08b',
8: '#88ddaa',
9: '#71acbc',
10: '#e6f598',
11: 'chartreuse',
12: 'cornsilk',
13: 'darkcyan',
14: 'darkkhaki',
15: 'forestgreen',
16: 'goldenrod',
17: 'lawngreen',
18: 'lightgray',
19: 'linen',
20: 'mediumorchid',
}
#Plot by PCA
colors_p = [colordict[l] for l in labels]
fig = plt.figure(figsize = (10,6))
ax = fig.add_subplot(111)
ax.set_frame_on(False)
plt.scatter(x_other, y_other, color = colors_p, alpha = 0.5)
for i, word in enumerate(TARGET):
ax.annotate(word, (coor_target[i][0],coor_target[i][1]),
horizontalalignment='center', alpha=0.7)
plt.xticks(())
plt.yticks(())
plt.title('All games with color representing predicted cluster\n classification: Neural Nets (MLP)\n k = {}, n = 15,372, projection = PCA'.format(numOfCluster))
plt.savefig(r'..\img\2-3_PCA_' + str(numOfCluster))
plt.show()
plt.close()
#Plot by tsne
colors_p = [colordict[l] for l in labels]
fig = plt.figure(figsize = (10,6))
ax = fig.add_subplot(111)
ax.set_frame_on(False)
plt.scatter(x_other_tsne, y_other_tsne, color = colors_p, alpha = 0.5)
for i, word in enumerate(TARGET):
ax.annotate(word, (coor_target_tsne[i][0],coor_target_tsne[i][1]),
horizontalalignment='center', alpha=0.7)
plt.xticks(())
plt.yticks(())
plt.title('All games with color representing predicted cluster\n classification: Neural Nets (MLP) with document vector input\n k = {}, n = 15,372, projection = tsne'.format(numOfCluster))
plt.savefig(r'..\img\2-3_tsne_' + str(numOfCluster))
plt.show()
plt.close()
|
[
"matplotlib.pyplot.show",
"gensim.models.Doc2Vec.load",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.close",
"matplotlib.pyplot.yticks",
"pandas.read_csv",
"matplotlib.pyplot.figure",
"numpy.array",
"numpy.arange",
"sklearn.neural_network.MLPClassifier",
"matplotlib.pyplot.xticks",
"pandas.concat",
"numpy.vstack"
] |
[((241, 300), 'gensim.models.Doc2Vec.load', 'gensim.models.Doc2Vec.load', (['"""..\\\\data\\\\process\\\\D2V_WOstop"""'], {}), "('..\\\\data\\\\process\\\\D2V_WOstop')\n", (267, 300), False, 'import gensim\n'), ((1202, 1221), 'numpy.array', 'np.array', (['core_vecs'], {}), '(core_vecs)\n', (1210, 1221), True, 'import numpy as np\n'), ((1234, 1254), 'numpy.array', 'np.array', (['other_vecs'], {}), '(other_vecs)\n', (1242, 1254), True, 'import numpy as np\n'), ((1786, 1801), 'sklearn.neural_network.MLPClassifier', 'MLPClassifier', ([], {}), '()\n', (1799, 1801), False, 'from sklearn.neural_network import MLPClassifier\n'), ((2006, 2021), 'numpy.arange', 'np.arange', (['(1)', '(8)'], {}), '(1, 8)\n', (2015, 2021), True, 'import numpy as np\n'), ((2269, 2309), 'pandas.concat', 'pd.concat', (['[df_predicted, probs]'], {'axis': '(1)'}), '([df_predicted, probs], axis=1)\n', (2278, 2309), True, 'import pandas as pd\n'), ((3194, 3221), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 6)'}), '(figsize=(10, 6))\n', (3204, 3221), True, 'import matplotlib.pyplot as plt\n'), ((3272, 3328), 'matplotlib.pyplot.scatter', 'plt.scatter', (['x_other', 'y_other'], {'color': 'colors_p', 'alpha': '(0.5)'}), '(x_other, y_other, color=colors_p, alpha=0.5)\n', (3283, 3328), True, 'import matplotlib.pyplot as plt\n'), ((3473, 3487), 'matplotlib.pyplot.xticks', 'plt.xticks', (['()'], {}), '(())\n', (3483, 3487), True, 'import matplotlib.pyplot as plt\n'), ((3488, 3502), 'matplotlib.pyplot.yticks', 'plt.yticks', (['()'], {}), '(())\n', (3498, 3502), True, 'import matplotlib.pyplot as plt\n'), ((3716, 3726), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3724, 3726), True, 'import matplotlib.pyplot as plt\n'), ((3727, 3738), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (3736, 3738), True, 'import matplotlib.pyplot as plt\n'), ((3802, 3829), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 6)'}), '(figsize=(10, 6))\n', (3812, 3829), True, 'import matplotlib.pyplot as plt\n'), ((3880, 3946), 'matplotlib.pyplot.scatter', 'plt.scatter', (['x_other_tsne', 'y_other_tsne'], {'color': 'colors_p', 'alpha': '(0.5)'}), '(x_other_tsne, y_other_tsne, color=colors_p, alpha=0.5)\n', (3891, 3946), True, 'import matplotlib.pyplot as plt\n'), ((4102, 4116), 'matplotlib.pyplot.xticks', 'plt.xticks', (['()'], {}), '(())\n', (4112, 4116), True, 'import matplotlib.pyplot as plt\n'), ((4117, 4131), 'matplotlib.pyplot.yticks', 'plt.yticks', (['()'], {}), '(())\n', (4127, 4131), True, 'import matplotlib.pyplot as plt\n'), ((4374, 4384), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4382, 4384), True, 'import matplotlib.pyplot as plt\n'), ((4385, 4396), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (4394, 4396), True, 'import matplotlib.pyplot as plt\n'), ((1438, 1470), 'numpy.vstack', 'np.vstack', (['(core_vec, other_vec)'], {}), '((core_vec, other_vec))\n', (1447, 1470), True, 'import numpy as np\n'), ((2440, 2525), 'pandas.read_csv', 'pd.read_csv', (['"""..\\\\data\\\\target_for_elaborate.csv"""'], {'encoding': '"""utf-8"""', 'header': 'None'}), "('..\\\\data\\\\target_for_elaborate.csv', encoding='utf-8', header=None\n )\n", (2451, 2525), True, 'import pandas as pd\n'), ((304, 411), 'pandas.read_csv', 'pd.read_csv', (['"""..\\\\data\\\\df_cb_main_combined.csv"""'], {'index_col': '(0)', 'encoding': '"""utf-8"""', 'error_bad_lines': '(False)'}), "('..\\\\data\\\\df_cb_main_combined.csv', index_col=0, encoding=\n 'utf-8', error_bad_lines=False)\n", (315, 411), True, 'import pandas as pd\n')]
|
from collections import deque
import numpy as np
import pickle
import os
import cv2
import inspect
import functools
from ddpg_curiosity_mc_her import logger
try:
from mujoco_py import MujocoException
except Exception:
logger.warn("Mujoco could not be imported.")
def convert_episode_to_batch_major(episode):
"""Converts an episode to have the batch dimension in the major (first)
dimension.
"""
episode_batch = {}
for key in episode.keys():
val = np.array(episode[key]).copy()
# make inputs batch-major instead of time-major
episode_batch[key] = val.swapaxes(0, 1)
return episode_batch
def store_args(method):
"""Stores provided method args as instance attributes.
"""
argspec = inspect.getfullargspec(method)
defaults = {}
if argspec.defaults is not None:
defaults = dict(
zip(argspec.args[-len(argspec.defaults):], argspec.defaults))
if argspec.kwonlydefaults is not None:
defaults.update(argspec.kwonlydefaults)
arg_names = argspec.args[1:]
@functools.wraps(method)
def wrapper(*positional_args, **keyword_args):
self = positional_args[0]
# Get default arg values
args = defaults.copy()
# Add provided arg values
for name, value in zip(arg_names, positional_args[1:]):
args[name] = value
args.update(keyword_args)
self.__dict__.update(args)
return method(*positional_args, **keyword_args)
return wrapper
class RolloutWorker:
@store_args
def __init__(self, policy_fn, agents, dims, logger, make_env, T, use_her, rollout_batch_size=1,
compute_Q=False, render=False, history_len=100):
"""Rollout worker generates experience by interacting with one or many environments.
Args:
make_env (function): a factory function that creates a new instance of the environment
when called
policy (object): the policy that is used to act
dims (dict of ints): the dimensions for observations (o), goals (g), and actions (u)
logger (object): the logger that is used by the rollout worker
rollout_batch_size (int): the number of parallel rollouts that should be used
exploit (boolean): whether or not to exploit, i.e. to act optimally according to the
current policy without any exploration
use_target_net (boolean): whether or not to use the target net for rollouts
compute_Q (boolean): whether or not to compute the Q values alongside the actions
noise_eps (float): scale of the additive Gaussian noise
random_eps (float): probability of selecting a completely random action
history_len (int): length of history for statistics smoothing
render (boolean): whether or not to render the rollouts
"""
self.envs = [make_env() for _ in range(rollout_batch_size)]
assert (np.abs(self.envs[0].action_space.low) == self.envs[0].action_space.high).all() # we assume symmetric actions.
self.max_action = self.envs[0].action_space.high
logger.info('Scaling actions by {} before executing in env'.format(self.max_action))
assert self.T > 0
self.info_keys = [key.replace('info_', '') for key in dims.keys() if key.startswith('info_')]
if self.use_her:
self.success_history = deque(maxlen=history_len)
self.reward_per_episode_history = deque(maxlen=history_len)
self.Q_history = deque(maxlen=history_len)
self.n_episodes = 0
self.initial_o = np.empty((self.rollout_batch_size, self.dims['o']), np.float32) # observations
if self.use_her:
self.g = np.empty((self.rollout_batch_size, self.dims['g']), np.float32) # goals
self.initial_ag = np.empty((self.rollout_batch_size, self.dims['g']), np.float32) # achieved goals
self.total_reward_this_episode = np.zeros((self.rollout_batch_size,), np.float32)
self.reset_all(force_env_resets=True)
self.clear_history()
self.current_heatmap_prefix = None
self.recording = False
def reset_rollout(self, i):
"""Resets the `i`-th rollout environment, re-samples a new goal, and updates the `initial_o`
and `g` arrays accordingly.
"""
obs = self.envs[i].reset()
if self.use_her:
self.initial_o[i] = obs['observation']
self.initial_ag[i] = obs['achieved_goal']
self.g[i] = obs['desired_goal']
else:
self.initial_o[i] = obs
self.total_reward_this_episode[i] = 0.
def reset_all(self, force_env_resets=False):
"""Resets all `rollout_batch_size` rollout workers.
"""
if self.use_her or force_env_resets:
for i in range(self.rollout_batch_size):
self.reset_rollout(i)
for agent in self.agents.values():
agent.reset()
def generate_rollouts(self, render_override=False, reset_on_success_overrride=False, heatmap_prefix=None,
demo_video_recording_name=None):
"""Performs `rollout_batch_size` rollouts in parallel for time horizon `T` with the current
policy acting on it accordingly.
"""
if demo_video_recording_name is not None:
if not self.recording:
# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'XVID')
# fourcc = cv2.VideoWriter_fourcc(*'MJPG')
# fourcc = cv2.VideoWriter_fourcc(*'MP4V')
self.out = cv2.VideoWriter('{}.avi'.format(demo_video_recording_name), fourcc, 24.0, (2560, 1440))
self.recording = False
if heatmap_prefix != self.current_heatmap_prefix:
write_dir = os.path.join(logger.get_dir(), 'heatmaps')
self.envs[0].unwrapped.set_location_record_name(write_dir=write_dir, prefix=heatmap_prefix)
self.current_heatmap_prefix = heatmap_prefix
self.reset_all(force_env_resets=False)
# compute observations
o = np.empty((self.rollout_batch_size, self.dims['o']), np.float32) # observations
o[:] = self.initial_o
if self.use_her:
ag = np.empty((self.rollout_batch_size, self.dims['g']), np.float32) # achieved goals
ag[:] = self.initial_ag
# generate episodes
obs, actions, rewards = [], [], []
if self.use_her:
achieved_goals, goals, successes = [], [], []
else:
dones = []
info_values = [np.empty((self.T, self.rollout_batch_size, self.dims['info_' + key]), np.float32) for key in self.info_keys]
Qs = []
for t in range(self.T):
policy_output = self.policy_fn(
observation=o,
goal=self.g if self.use_her else None,
compute_Q=self.compute_Q
)
if self.compute_Q:
u, Q = policy_output
Qs.append(Q)
else:
u = policy_output
if u.ndim == 1:
# The non-batched case should still have a reasonable shape.
u = u.reshape(1, -1)
o_new = np.empty((self.rollout_batch_size, self.dims['o']))
rewards_new = np.empty((self.rollout_batch_size, 1))
if self.use_her:
ag_new = np.empty((self.rollout_batch_size, self.dims['g']))
success = np.zeros(self.rollout_batch_size)
else:
dones_new = np.empty((self.rollout_batch_size, 1))
# compute new states and observations
for i in range(self.rollout_batch_size):
try:
curr_o_new, curr_reward_new, curr_done_new, info = self.envs[i].step(u[i] * self.max_action)
# if shift_rewards_by_50:
# curr_reward_new = curr_reward_new * 50 + 50
# curr_reward_new = curr_reward_new / 1000.
# else:
# curr_reward_new = curr_reward_new * 50 + 50
rewards_new[i] = curr_reward_new
self.total_reward_this_episode[i] += curr_reward_new
if self.use_her:
if 'is_success' in info:
success[i] = info['is_success']
if reset_on_success_overrride and success[i]:
# raise Exception('SUCCESS affected rollout behavior')
# print("YOU SHOULD ONLY EVER REACH THIS IF CONDUCTING A DEMO")
self.reward_per_episode_history.append(self.total_reward_this_episode[i])
self.reset_rollout(i)
o_new[i] = curr_o_new['observation']
ag_new[i] = curr_o_new['achieved_goal']
else:
o_new[i] = curr_o_new
dones_new[i] = curr_done_new
if curr_done_new:
self.reward_per_episode_history.append(self.total_reward_this_episode[i])
self.reset_rollout(i)
for idx, key in enumerate(self.info_keys):
info_values[idx][t, i] = info[key]
if self.render or render_override:
if i == 0:
self.envs[0].render()
if demo_video_recording_name is not None:
frame = self.envs[i].render('rgb_array')[...,::-1]
cv2.imshow("recording {}".format(i), frame)
key = cv2.waitKey(1) & 0xFF
if key == ord('r'):
if not self.recording:
print("\n\n-------RECORDING---------\n\n")
self.recording = True
if self.recording:
print("rec {}".format(t))
self.out.write(frame)
if key == ord('q'):
self.out.release()
cv2.destroyAllWindows()
print('done')
exit()
except MujocoException as e:
return self.generate_rollouts()
if np.isnan(o_new).any():
self.logger.warning('NaN caught during rollout generation. Trying again...')
self.reset_all(force_env_resets=True)
return self.generate_rollouts()
obs.append(o.copy())
actions.append(u.copy())
rewards.append(rewards_new.copy())
o[...] = o_new
if self.use_her:
achieved_goals.append(ag.copy())
successes.append(success.copy())
goals.append(self.g.copy())
ag[...] = ag_new
else:
dones.append(dones_new.copy())
obs.append(o.copy())
self.initial_o[:] = o
if self.use_her:
achieved_goals.append(ag.copy())
episode = {'o': obs, 'u': actions}
episode['r'] = rewards
if self.use_her:
episode['g'] = goals
episode['ag'] = achieved_goals
else:
episode['t'] = dones
# print("goals shape: {}".format(np.shape( episode['g'])))
# print("obs shape: {}".format(np.shape(episode['o'])))
# print("ag shape: {}".format(np.shape(episode['ag'])))
for key, value in zip(self.info_keys, info_values):
episode['info_{}'.format(key)] = value
# stats
if self.use_her:
successful = np.array(successes)[-1, :]
assert successful.shape == (self.rollout_batch_size,)
success_rate = np.mean(successful)
self.success_history.append(success_rate)
self.reward_per_episode_history.append(self.total_reward_this_episode[i])
if self.compute_Q:
self.Q_history.append(np.mean(Qs))
self.n_episodes += self.rollout_batch_size
# print("goals shape: {}".format(np.shape( episode['g'])))
# print("obs shape: {}".format(np.shape(episode['o'])))
# print("ag shape: {}".format(np.shape(episode['ag'])))
return convert_episode_to_batch_major(episode)
def clear_history(self):
"""Clears all histories that are used for statistics
"""
if self.use_her:
self.success_history.clear()
self.reward_per_episode_history.clear()
self.Q_history.clear()
def flush_env_location_records(self):
self.envs[0].unwrapped.flush_location_record()
def current_success_rate(self):
return np.mean(self.success_history)
def current_mean_reward_per_episode(self):
return np.mean(self.reward_per_episode_history)
def current_score(self):
if self.use_her:
return self.current_success_rate()
else:
return self.current_mean_reward_per_episode()
def current_mean_Q(self):
return np.mean(self.Q_history)
def save_policy(self, path):
"""Pickles the current policy for later inspection.
"""
with open(path, 'wb') as f:
pickle.dump(self.agents, f)
def logs(self, prefix='worker'):
"""Generates a dictionary that contains all collected statistics.
"""
logs = []
if self.use_her:
logs += [('success_rate', np.mean(self.success_history))]
logs += [('reward_per_episode', np.mean(self.reward_per_episode_history))]
if self.compute_Q:
logs += [('mean_Q', np.mean(self.Q_history))]
logs += [('episode', self.n_episodes)]
if prefix is not '' and not prefix.endswith('/'):
return [(prefix + '/' + key, val) for key, val in logs]
else:
return logs
def seed(self, seed):
"""Seeds each environment with a distinct seed derived from the passed in global seed.
"""
for idx, env in enumerate(self.envs):
env.seed(seed + 1000 * idx)
def close(self):
for env in self.envs:
env.close()
|
[
"pickle.dump",
"numpy.abs",
"inspect.getfullargspec",
"cv2.VideoWriter_fourcc",
"cv2.waitKey",
"numpy.empty",
"numpy.zeros",
"numpy.isnan",
"numpy.mean",
"numpy.array",
"ddpg_curiosity_mc_her.logger.get_dir",
"functools.wraps",
"ddpg_curiosity_mc_her.logger.warn",
"cv2.destroyAllWindows",
"collections.deque"
] |
[((755, 785), 'inspect.getfullargspec', 'inspect.getfullargspec', (['method'], {}), '(method)\n', (777, 785), False, 'import inspect\n'), ((1070, 1093), 'functools.wraps', 'functools.wraps', (['method'], {}), '(method)\n', (1085, 1093), False, 'import functools\n'), ((229, 273), 'ddpg_curiosity_mc_her.logger.warn', 'logger.warn', (['"""Mujoco could not be imported."""'], {}), "('Mujoco could not be imported.')\n", (240, 273), False, 'from ddpg_curiosity_mc_her import logger\n'), ((3524, 3549), 'collections.deque', 'deque', ([], {'maxlen': 'history_len'}), '(maxlen=history_len)\n', (3529, 3549), False, 'from collections import deque\n'), ((3576, 3601), 'collections.deque', 'deque', ([], {'maxlen': 'history_len'}), '(maxlen=history_len)\n', (3581, 3601), False, 'from collections import deque\n'), ((3656, 3719), 'numpy.empty', 'np.empty', (["(self.rollout_batch_size, self.dims['o'])", 'np.float32'], {}), "((self.rollout_batch_size, self.dims['o']), np.float32)\n", (3664, 3719), True, 'import numpy as np\n'), ((4008, 4056), 'numpy.zeros', 'np.zeros', (['(self.rollout_batch_size,)', 'np.float32'], {}), '((self.rollout_batch_size,), np.float32)\n', (4016, 4056), True, 'import numpy as np\n'), ((6209, 6272), 'numpy.empty', 'np.empty', (["(self.rollout_batch_size, self.dims['o'])", 'np.float32'], {}), "((self.rollout_batch_size, self.dims['o']), np.float32)\n", (6217, 6272), True, 'import numpy as np\n'), ((13148, 13177), 'numpy.mean', 'np.mean', (['self.success_history'], {}), '(self.success_history)\n', (13155, 13177), True, 'import numpy as np\n'), ((13241, 13281), 'numpy.mean', 'np.mean', (['self.reward_per_episode_history'], {}), '(self.reward_per_episode_history)\n', (13248, 13281), True, 'import numpy as np\n'), ((13502, 13525), 'numpy.mean', 'np.mean', (['self.Q_history'], {}), '(self.Q_history)\n', (13509, 13525), True, 'import numpy as np\n'), ((3456, 3481), 'collections.deque', 'deque', ([], {'maxlen': 'history_len'}), '(maxlen=history_len)\n', (3461, 3481), False, 'from collections import deque\n'), ((3782, 3845), 'numpy.empty', 'np.empty', (["(self.rollout_batch_size, self.dims['g'])", 'np.float32'], {}), "((self.rollout_batch_size, self.dims['g']), np.float32)\n", (3790, 3845), True, 'import numpy as np\n'), ((3885, 3948), 'numpy.empty', 'np.empty', (["(self.rollout_batch_size, self.dims['g'])", 'np.float32'], {}), "((self.rollout_batch_size, self.dims['g']), np.float32)\n", (3893, 3948), True, 'import numpy as np\n'), ((6362, 6425), 'numpy.empty', 'np.empty', (["(self.rollout_batch_size, self.dims['g'])", 'np.float32'], {}), "((self.rollout_batch_size, self.dims['g']), np.float32)\n", (6370, 6425), True, 'import numpy as np\n'), ((6696, 6782), 'numpy.empty', 'np.empty', (["(self.T, self.rollout_batch_size, self.dims['info_' + key])", 'np.float32'], {}), "((self.T, self.rollout_batch_size, self.dims['info_' + key]), np.\n float32)\n", (6704, 6782), True, 'import numpy as np\n'), ((7353, 7404), 'numpy.empty', 'np.empty', (["(self.rollout_batch_size, self.dims['o'])"], {}), "((self.rollout_batch_size, self.dims['o']))\n", (7361, 7404), True, 'import numpy as np\n'), ((7431, 7469), 'numpy.empty', 'np.empty', (['(self.rollout_batch_size, 1)'], {}), '((self.rollout_batch_size, 1))\n', (7439, 7469), True, 'import numpy as np\n'), ((12213, 12232), 'numpy.mean', 'np.mean', (['successful'], {}), '(successful)\n', (12220, 12232), True, 'import numpy as np\n'), ((13680, 13707), 'pickle.dump', 'pickle.dump', (['self.agents', 'f'], {}), '(self.agents, f)\n', (13691, 13707), False, 'import pickle\n'), ((488, 510), 'numpy.array', 'np.array', (['episode[key]'], {}), '(episode[key])\n', (496, 510), True, 'import numpy as np\n'), ((5525, 5556), 'cv2.VideoWriter_fourcc', 'cv2.VideoWriter_fourcc', (["*'XVID'"], {}), "(*'XVID')\n", (5547, 5556), False, 'import cv2\n'), ((5926, 5942), 'ddpg_curiosity_mc_her.logger.get_dir', 'logger.get_dir', ([], {}), '()\n', (5940, 5942), False, 'from ddpg_curiosity_mc_her import logger\n'), ((7524, 7575), 'numpy.empty', 'np.empty', (["(self.rollout_batch_size, self.dims['g'])"], {}), "((self.rollout_batch_size, self.dims['g']))\n", (7532, 7575), True, 'import numpy as np\n'), ((7602, 7635), 'numpy.zeros', 'np.zeros', (['self.rollout_batch_size'], {}), '(self.rollout_batch_size)\n', (7610, 7635), True, 'import numpy as np\n'), ((7682, 7720), 'numpy.empty', 'np.empty', (['(self.rollout_batch_size, 1)'], {}), '((self.rollout_batch_size, 1))\n', (7690, 7720), True, 'import numpy as np\n'), ((12093, 12112), 'numpy.array', 'np.array', (['successes'], {}), '(successes)\n', (12101, 12112), True, 'import numpy as np\n'), ((12434, 12445), 'numpy.mean', 'np.mean', (['Qs'], {}), '(Qs)\n', (12441, 12445), True, 'import numpy as np\n'), ((13985, 14025), 'numpy.mean', 'np.mean', (['self.reward_per_episode_history'], {}), '(self.reward_per_episode_history)\n', (13992, 14025), True, 'import numpy as np\n'), ((3005, 3042), 'numpy.abs', 'np.abs', (['self.envs[0].action_space.low'], {}), '(self.envs[0].action_space.low)\n', (3011, 3042), True, 'import numpy as np\n'), ((10731, 10746), 'numpy.isnan', 'np.isnan', (['o_new'], {}), '(o_new)\n', (10739, 10746), True, 'import numpy as np\n'), ((13913, 13942), 'numpy.mean', 'np.mean', (['self.success_history'], {}), '(self.success_history)\n', (13920, 13942), True, 'import numpy as np\n'), ((14088, 14111), 'numpy.mean', 'np.mean', (['self.Q_history'], {}), '(self.Q_history)\n', (14095, 14111), True, 'import numpy as np\n'), ((9908, 9922), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (9919, 9922), False, 'import cv2\n'), ((10500, 10523), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (10521, 10523), False, 'import cv2\n')]
|
import matplotlib.pyplot as plt
import numpy as np
import random as r
import time
from drawnow import *
recipe = ["225 g flour",
"90 g sugar",
"1 egg",
"60 g butter",
"100 ml milk",
"1/2 package of yeast",
"225 g flour",
"90 g sugar",
"1 egg",
"60 g butter",
"225 g flour",
"90 g sugar",
"1 egg",
"60 g butter",
"100 ml milk"]
data = [277, 250, 267, 213, 274, 297]#[225, 90, 50, 60, 100, 5]
def gen_rand():
global data
data=[]
for i in range(15):
data.append(r.randint(50,300))
def plotme():
print(data)
#plt.subplots(figsize=(6, 3), subplot_kw=dict(aspect="equal"))
wedges, texts = plt.pie(data, wedgeprops=dict(width=0.5), startangle=-40)
bbox_props = dict(boxstyle="square,pad=0.3", fc="w", ec="k", lw=0.72)
kw = dict(arrowprops=dict(arrowstyle="-"),
bbox=bbox_props, zorder=0, va="center")
for i, p in enumerate(wedges):
ang = (p.theta2 - p.theta1)/2. + p.theta1
y = np.sin(np.deg2rad(ang))
x = np.cos(np.deg2rad(ang))
horizontalalignment = {-1: "right", 1: "left"}[int(np.sign(x))]
connectionstyle = "angle,angleA=0,angleB={}".format(ang)
kw["arrowprops"].update({"connectionstyle": connectionstyle})
plt.annotate(recipe[i], xy=(x, y), xytext=(np.sign(x),y),
horizontalalignment=horizontalalignment, **kw)
plt.title("Matplotlib bakery: A donut")
#plt.legend()
#plt.show()
def plotme_easy():
print(data)
#fig, ax = plt.subplots(figsize=(6, 3), subplot_kw=dict(aspect="equal"))
wedges, texts = plt.pie(data, wedgeprops=dict(width=0.5), startangle=-40, labels=recipe)
#bbox_props = dict(boxstyle="square,pad=0.3", fc="w", ec="k", lw=0.72)
#kw = dict(arrowprops=dict(arrowstyle="-"),
# bbox=bbox_props, zorder=0, va="center")
#for i, p in enumerate(wedges):
#ang = (p.theta2 - p.theta1)/2. + p.theta1
#y = np.sin(np.deg2rad(ang))
#x = np.cos(np.deg2rad(ang))
#horizontalalignment = {-1: "right", 1: "left"}[int(np.sign(x))]
#connectionstyle = "angle,angleA=0,angleB={}".format(ang)
#kw["arrowprops"].update({"connectionstyle": connectionstyle})
#plt.annotate(recipe[i], xy=(x, y), xytext=(np.sign(x),y)
# horizontalalignment=horizontalalignment, **kw)
plt.title("Matplotlib bakery: A donut")
#plt.legend()
#plt.show()
def main():
while True:
gen_rand()
drawnow(plotme_easy)
time.sleep(1)
main()
|
[
"matplotlib.pyplot.title",
"random.randint",
"numpy.deg2rad",
"time.sleep",
"numpy.sign"
] |
[((1502, 1541), 'matplotlib.pyplot.title', 'plt.title', (['"""Matplotlib bakery: A donut"""'], {}), "('Matplotlib bakery: A donut')\n", (1511, 1541), True, 'import matplotlib.pyplot as plt\n'), ((2475, 2514), 'matplotlib.pyplot.title', 'plt.title', (['"""Matplotlib bakery: A donut"""'], {}), "('Matplotlib bakery: A donut')\n", (2484, 2514), True, 'import matplotlib.pyplot as plt\n'), ((2634, 2647), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (2644, 2647), False, 'import time\n'), ((624, 642), 'random.randint', 'r.randint', (['(50)', '(300)'], {}), '(50, 300)\n', (633, 642), True, 'import random as r\n'), ((1105, 1120), 'numpy.deg2rad', 'np.deg2rad', (['ang'], {}), '(ang)\n', (1115, 1120), True, 'import numpy as np\n'), ((1141, 1156), 'numpy.deg2rad', 'np.deg2rad', (['ang'], {}), '(ang)\n', (1151, 1156), True, 'import numpy as np\n'), ((1217, 1227), 'numpy.sign', 'np.sign', (['x'], {}), '(x)\n', (1224, 1227), True, 'import numpy as np\n'), ((1416, 1426), 'numpy.sign', 'np.sign', (['x'], {}), '(x)\n', (1423, 1426), True, 'import numpy as np\n')]
|
# This example demonstrates how to regrid between a UGRID Mesh and a Grid.
# The data files can be retrieved from the ESMF data repository by uncommenting the
# following block of code:
#
# import os
# DD = os.path.join(os.getcwd(), "examples/data")
# if not os.path.isdir(DD):
# os.makedirs(DD)
# from ESMF.util.cache_data import cache_data_file
# cache_data_file(os.path.join(DD, "ll1deg_grid.nc"))
# cache_data_file(os.path.join(DD, "ne30np4-t2UGRID_nodual.nc"))
# cache_data_file(os.path.join(DD, "aggregAtlanticESTOFS.nc"))
import ESMF
import numpy
def plot_error(field1, field2, uninitval):
try:
import matplotlib
import matplotlib.pyplot as plt
except:
raise ImportError("matplotlib is not available on this machine")
colormap = "gist_stern"
lons = field2.grid.get_coords(0)
lats = field2.grid.get_coords(1)
fig = plt.figure(1, (15, 6))
fig.suptitle('ESMPy Regridding', fontsize=14, fontweight='bold')
ax = fig.add_subplot(1, 2, 1)
solution = numpy.copy(field2.data)
solution[numpy.where(field2.data == uninitval)] = 0
im = ax.imshow(solution, vmin=numpy.min(solution),
vmax=numpy.max(solution), cmap=colormap, aspect='auto',
extent=[numpy.min(lons), numpy.max(lons),
numpy.min(lats), numpy.max(lats)])
ax.set_xlabel("Longitude")
ax.set_ylabel("Latitude")
ax.set_title("Regrid Solution")
relerr = numpy.abs(field2.data - field1.data)/numpy.abs(field1.data)
relerr[numpy.where(field2.data == uninitval)] = 0
ax = fig.add_subplot(1, 2, 2)
im1 = ax.imshow(relerr, vmin=numpy.min(relerr),
vmax=numpy.max(relerr), cmap=colormap, aspect='auto',
extent=[numpy.min(lons), numpy.max(lons),
numpy.min(lats), numpy.max(lats)])
ax.set_xlabel("Longitude")
ax.set_ylabel("Latitude")
ax.set_title("Relative Error")
fig.subplots_adjust(right=0.8)
cbar_ax = fig.add_axes([0.9, 0.1, 0.01, 0.8])
fig.colorbar(im1, cax=cbar_ax)
plt.show()
def plot_field(field2, uninitval):
try:
import matplotlib
import matplotlib.pyplot as plt
except:
raise ImportError("matplotlib is not available on this machine")
colormap = "gist_stern"
lons = field2.grid.get_coords(0)
lats = field2.grid.get_coords(1)
fig = plt.figure(1, (15, 6))
fig.suptitle('ESMPy Regridding', fontsize=14, fontweight='bold')
solution = numpy.copy(field2.data)
solution[numpy.where(field2.data == uninitval)] = 0
im = plt.imshow(solution, vmin=numpy.min(solution),
vmax=numpy.max(solution), cmap=colormap, aspect='auto',
extent=[numpy.min(lons), numpy.max(lons),
numpy.min(lats), numpy.max(lats)])
ax = plt.gca()
ax.set_xlabel("Longitude")
ax.set_ylabel("Latitude")
ax.set_title("Regrid Solution")
fig.subplots_adjust(right=0.8)
cbar_ax = fig.add_axes([0.9, 0.1, 0.01, 0.8])
fig.colorbar(im, cax=cbar_ax)
plt.show()
# This call enables debug logging
# esmpy = ESMF.Manager(debug=True)
# these are for a new test using opendap, dataset has periodic failures..
# meshfile = "http://coastalmodeldev.data.noaa.gov/thredds/dodsC/aggregAtlanticESTOFS"
meshfile = "examples/data/aggregAtlanticESTOFS.nc"
mesh = ESMF.Mesh(filename=meshfile, filetype=ESMF.FileFormat.UGRID, meshname='adcirc_mesh')
# Create a global latlon grid from a SCRIP formatted file
gridfile = "examples/data/ll1deg_grid.nc"
grid = ESMF.Grid(filename=gridfile, filetype=ESMF.FileFormat.SCRIP,
add_corner_stagger=True, is_sphere=True)
# create a field on the element locations of the source mesh
srcfield = ESMF.Field(mesh, name='srcfield', meshloc=ESMF.MeshLoc.NODE)
# create a field on the centers of the destination grid
dstfield = ESMF.Field(grid, name='dstfield', staggerloc=ESMF.StaggerLoc.CENTER)
xctfield = ESMF.Field(grid, name='xctfield', staggerloc=ESMF.StaggerLoc.CENTER)
# initialize the fields
[lon,lat] = [0, 1]
srcgridXCoord = srcfield.grid.get_coords(lon, meshloc=ESMF.MeshLoc.NODE)
srcgridYCoord = srcfield.grid.get_coords(lat, meshloc=ESMF.MeshLoc.NODE)
srcfield.data[...] = 2.0 + numpy.cos(numpy.radians(srcgridYCoord)[...])**2 * \
numpy.cos(2.0*numpy.radians(srcgridXCoord)[...])
dstgridXCoord = xctfield.grid.get_coords(lon, ESMF.StaggerLoc.CENTER)
dstgridYCoord = xctfield.grid.get_coords(lat, ESMF.StaggerLoc.CENTER)
xctfield.data[...] = 2.0 + numpy.cos(numpy.radians(dstgridYCoord)[...])**2 * \
numpy.cos(2.0*numpy.radians(dstgridXCoord)[...])
uninitval = 1e20
dstfield.data[...] = uninitval
# create an object to regrid data from the source to the destination field
regrid = ESMF.Regrid(srcfield, dstfield,
regrid_method=ESMF.RegridMethod.BILINEAR,
unmapped_action=ESMF.UnmappedAction.IGNORE)
# do the regridding from source to destination field
dstfield = regrid(srcfield, dstfield, zero_region=ESMF.Region.SELECT)
# output the results from one processor only
if ESMF.local_pet() is 0:
print ("ESMPy UGRID to LatLon Regridding Example")
# plot_error(xctfield, dstfield, uninitval=uninitval)
# # now read some real data and give it a whirl
# try:
# import netCDF4 as nc
# # f = nc.Dataset('http://coastalmodeldev.data.noaa.gov/thredds/dodsC/aggregAtlanticESTOFS')
# f = nc.Dataset("examples/data/aggregAtlanticESTOFS.nc")
# zeta = f.variables["zeta"]
# srcfield.data[...] = zeta[0]
# f.close()
# except:
# raise ImportError("netCDF4 is not available on this machine")
# This call fails due to ESMF limitation that time be the file's unlimited dimension
# srcfield.data[...] = srcfield.read(meshfile, "zeta")
# dstfield.data[...] = uninitval
# # create an object to regrid data from the source to the destination field
# regrid = ESMF.Regrid(srcfield, dstfield,
# regrid_method=ESMF.RegridMethod.BILINEAR,
# unmapped_action=ESMF.UnmappedAction.IGNORE)
#
# # do the regridding from source to destination field
# dstfield = regrid(srcfield, dstfield, zero_region=ESMF.Region.SELECT)
#
# plot_field(dstfield, uninitval=uninitval)
|
[
"numpy.radians",
"matplotlib.pyplot.show",
"numpy.abs",
"numpy.copy",
"matplotlib.pyplot.gca",
"ESMF.Field",
"ESMF.Regrid",
"matplotlib.pyplot.figure",
"numpy.where",
"ESMF.Grid",
"numpy.min",
"numpy.max",
"ESMF.Mesh",
"ESMF.local_pet"
] |
[((3391, 3480), 'ESMF.Mesh', 'ESMF.Mesh', ([], {'filename': 'meshfile', 'filetype': 'ESMF.FileFormat.UGRID', 'meshname': '"""adcirc_mesh"""'}), "(filename=meshfile, filetype=ESMF.FileFormat.UGRID, meshname=\n 'adcirc_mesh')\n", (3400, 3480), False, 'import ESMF\n'), ((3584, 3689), 'ESMF.Grid', 'ESMF.Grid', ([], {'filename': 'gridfile', 'filetype': 'ESMF.FileFormat.SCRIP', 'add_corner_stagger': '(True)', 'is_sphere': '(True)'}), '(filename=gridfile, filetype=ESMF.FileFormat.SCRIP,\n add_corner_stagger=True, is_sphere=True)\n', (3593, 3689), False, 'import ESMF\n'), ((3776, 3836), 'ESMF.Field', 'ESMF.Field', (['mesh'], {'name': '"""srcfield"""', 'meshloc': 'ESMF.MeshLoc.NODE'}), "(mesh, name='srcfield', meshloc=ESMF.MeshLoc.NODE)\n", (3786, 3836), False, 'import ESMF\n'), ((3905, 3973), 'ESMF.Field', 'ESMF.Field', (['grid'], {'name': '"""dstfield"""', 'staggerloc': 'ESMF.StaggerLoc.CENTER'}), "(grid, name='dstfield', staggerloc=ESMF.StaggerLoc.CENTER)\n", (3915, 3973), False, 'import ESMF\n'), ((3985, 4053), 'ESMF.Field', 'ESMF.Field', (['grid'], {'name': '"""xctfield"""', 'staggerloc': 'ESMF.StaggerLoc.CENTER'}), "(grid, name='xctfield', staggerloc=ESMF.StaggerLoc.CENTER)\n", (3995, 4053), False, 'import ESMF\n'), ((4830, 4951), 'ESMF.Regrid', 'ESMF.Regrid', (['srcfield', 'dstfield'], {'regrid_method': 'ESMF.RegridMethod.BILINEAR', 'unmapped_action': 'ESMF.UnmappedAction.IGNORE'}), '(srcfield, dstfield, regrid_method=ESMF.RegridMethod.BILINEAR,\n unmapped_action=ESMF.UnmappedAction.IGNORE)\n', (4841, 4951), False, 'import ESMF\n'), ((878, 900), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)', '(15, 6)'], {}), '(1, (15, 6))\n', (888, 900), True, 'import matplotlib.pyplot as plt\n'), ((1020, 1043), 'numpy.copy', 'numpy.copy', (['field2.data'], {}), '(field2.data)\n', (1030, 1043), False, 'import numpy\n'), ((2085, 2095), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2093, 2095), True, 'import matplotlib.pyplot as plt\n'), ((2407, 2429), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)', '(15, 6)'], {}), '(1, (15, 6))\n', (2417, 2429), True, 'import matplotlib.pyplot as plt\n'), ((2515, 2538), 'numpy.copy', 'numpy.copy', (['field2.data'], {}), '(field2.data)\n', (2525, 2538), False, 'import numpy\n'), ((2858, 2867), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (2865, 2867), True, 'import matplotlib.pyplot as plt\n'), ((3090, 3100), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3098, 3100), True, 'import matplotlib.pyplot as plt\n'), ((5163, 5179), 'ESMF.local_pet', 'ESMF.local_pet', ([], {}), '()\n', (5177, 5179), False, 'import ESMF\n'), ((1057, 1094), 'numpy.where', 'numpy.where', (['(field2.data == uninitval)'], {}), '(field2.data == uninitval)\n', (1068, 1094), False, 'import numpy\n'), ((1464, 1500), 'numpy.abs', 'numpy.abs', (['(field2.data - field1.data)'], {}), '(field2.data - field1.data)\n', (1473, 1500), False, 'import numpy\n'), ((1501, 1523), 'numpy.abs', 'numpy.abs', (['field1.data'], {}), '(field1.data)\n', (1510, 1523), False, 'import numpy\n'), ((1535, 1572), 'numpy.where', 'numpy.where', (['(field2.data == uninitval)'], {}), '(field2.data == uninitval)\n', (1546, 1572), False, 'import numpy\n'), ((2552, 2589), 'numpy.where', 'numpy.where', (['(field2.data == uninitval)'], {}), '(field2.data == uninitval)\n', (2563, 2589), False, 'import numpy\n'), ((1134, 1153), 'numpy.min', 'numpy.min', (['solution'], {}), '(solution)\n', (1143, 1153), False, 'import numpy\n'), ((1179, 1198), 'numpy.max', 'numpy.max', (['solution'], {}), '(solution)\n', (1188, 1198), False, 'import numpy\n'), ((1645, 1662), 'numpy.min', 'numpy.min', (['relerr'], {}), '(relerr)\n', (1654, 1662), False, 'import numpy\n'), ((1689, 1706), 'numpy.max', 'numpy.max', (['relerr'], {}), '(relerr)\n', (1698, 1706), False, 'import numpy\n'), ((2630, 2649), 'numpy.min', 'numpy.min', (['solution'], {}), '(solution)\n', (2639, 2649), False, 'import numpy\n'), ((2675, 2694), 'numpy.max', 'numpy.max', (['solution'], {}), '(solution)\n', (2684, 2694), False, 'import numpy\n'), ((1257, 1272), 'numpy.min', 'numpy.min', (['lons'], {}), '(lons)\n', (1266, 1272), False, 'import numpy\n'), ((1274, 1289), 'numpy.max', 'numpy.max', (['lons'], {}), '(lons)\n', (1283, 1289), False, 'import numpy\n'), ((1318, 1333), 'numpy.min', 'numpy.min', (['lats'], {}), '(lats)\n', (1327, 1333), False, 'import numpy\n'), ((1335, 1350), 'numpy.max', 'numpy.max', (['lats'], {}), '(lats)\n', (1344, 1350), False, 'import numpy\n'), ((1766, 1781), 'numpy.min', 'numpy.min', (['lons'], {}), '(lons)\n', (1775, 1781), False, 'import numpy\n'), ((1783, 1798), 'numpy.max', 'numpy.max', (['lons'], {}), '(lons)\n', (1792, 1798), False, 'import numpy\n'), ((1828, 1843), 'numpy.min', 'numpy.min', (['lats'], {}), '(lats)\n', (1837, 1843), False, 'import numpy\n'), ((1845, 1860), 'numpy.max', 'numpy.max', (['lats'], {}), '(lats)\n', (1854, 1860), False, 'import numpy\n'), ((2753, 2768), 'numpy.min', 'numpy.min', (['lons'], {}), '(lons)\n', (2762, 2768), False, 'import numpy\n'), ((2770, 2785), 'numpy.max', 'numpy.max', (['lons'], {}), '(lons)\n', (2779, 2785), False, 'import numpy\n'), ((2814, 2829), 'numpy.min', 'numpy.min', (['lats'], {}), '(lats)\n', (2823, 2829), False, 'import numpy\n'), ((2831, 2846), 'numpy.max', 'numpy.max', (['lats'], {}), '(lats)\n', (2840, 2846), False, 'import numpy\n'), ((4282, 4310), 'numpy.radians', 'numpy.radians', (['srcgridYCoord'], {}), '(srcgridYCoord)\n', (4295, 4310), False, 'import numpy\n'), ((4365, 4393), 'numpy.radians', 'numpy.radians', (['srcgridXCoord'], {}), '(srcgridXCoord)\n', (4378, 4393), False, 'import numpy\n'), ((4578, 4606), 'numpy.radians', 'numpy.radians', (['dstgridYCoord'], {}), '(dstgridYCoord)\n', (4591, 4606), False, 'import numpy\n'), ((4661, 4689), 'numpy.radians', 'numpy.radians', (['dstgridXCoord'], {}), '(dstgridXCoord)\n', (4674, 4689), False, 'import numpy\n')]
|
from __future__ import print_function
import tensorflow as tf
from functools import partial
import os
from os import listdir
from os.path import isfile, join
import shutil
import sys
from glob import glob
import math
import json
import logging
import numpy as np
from PIL import Image
from datetime import datetime
from tensorflow.core.framework import summary_pb2
def make_summary(name, val):
return summary_pb2.Summary(value=[summary_pb2.Summary.Value(tag=name, simple_value=val)])
def summary_stats(name,tensor,collections=None,hist=False):
collections=collections or [tf.GraphKeys.SUMMARIES]
ave=tf.reduce_mean(tensor)
std=tf.sqrt(tf.reduce_mean(tf.square(ave-tensor)))
tf.summary.scalar(name+'_ave',ave,collections)
tf.summary.scalar(name+'_std',std,collections)
if hist:
tf.summary.histogram(name+'_hist',tensor,collections)
def prepare_dirs_and_logger(config):
if config.load_path:
strip_lp=config.load_path.strip('./')
if strip_lp.startswith(config.log_dir):
config.model_dir = config.load_path
else:
if config.load_path.startswith(config.dataset):
config.model_name = config.load_path
else:
config.model_name = "{}_{}".format(config.dataset, config.load_path)
else:#new model
config.model_name = "{}_{}".format(config.dataset, get_time())
if config.descrip:
config.model_name+='_'+config.descrip
if not hasattr(config, 'model_dir'):
config.model_dir = os.path.join(config.log_dir, config.model_name)
config.data_path = os.path.join(config.data_dir, config.dataset)
if not config.load_path:
config.log_code_dir=os.path.join(config.model_dir,'code')
for path in [config.log_dir, config.data_dir,
config.model_dir]:
if not os.path.exists(path):
os.makedirs(path)
#Copy python code in directory into model_dir/code for future reference:
#All python files in this directory are copied.
code_dir=os.path.dirname(os.path.realpath(sys.argv[0]))
##additionally, all python files in these directories are also copied. Also symlinks are copied. The idea is to allow easier model loading in the future
allowed_dirs=['causal_controller','causal_began','causal_dcgan','figure_scripts']
#ignore copy of all non-*.py except for these directories
#If you make another folder you want copied, you have to add it here
ignore_these=partial(ignore_except,allowed_dirs=allowed_dirs)
shutil.copytree(code_dir,config.log_code_dir,symlinks=True,ignore=ignore_these)
# model_files = [f for f in listdir(code_dir) if isfile(join(code_dir, f))]
# for f in model_files:
# if f.endswith('.py'):
# shutil.copy2(f,config.log_code_dir)
def ignore_except(src,contents,allowed_dirs):
files=filter(os.path.isfile,contents)
dirs=filter(os.path.isdir,contents)
ignored_files=[f for f in files if not f.endswith('.py')]
ignored_dirs=[d for d in dirs if not d in allowed_dirs]
return ignored_files+ignored_dirs
def get_time():
return datetime.now().strftime("%m%d_%H%M%S")
def save_configs(config,cc_config,dcgan_config,began_config):
model_dir=config.model_dir
print("[*] MODEL dir: %s" % model_dir)
save_config(config)
save_config(cc_config,'cc_params.json',model_dir)
save_config(dcgan_config,'dcgan_params.json',model_dir)
save_config(began_config,'began_params.json',model_dir)
def save_config(config,name="params.json",where=None):
where=where or config.model_dir
param_path = os.path.join(where, name)
print("[*] PARAM path: %s" % param_path)
with open(param_path, 'w') as fp:
json.dump(config.__dict__, fp, indent=4, sort_keys=True)
def get_available_gpus():
from tensorflow.python.client import device_lib
local_device_protos = device_lib.list_local_devices()
return [x.name for x in local_device_protos if x.device_type=='GPU']
def distribute_input_data(data_loader,num_gpu):
'''
data_loader is a dictionary of tensors that are fed into our model
This function takes that dictionary of n*batch_size dimension tensors
and breaks it up into n dictionaries with the same key of tensors with
dimension batch_size. One is given to each gpu
'''
if num_gpu==0:
return {'/cpu:0':data_loader}
gpus=get_available_gpus()
if num_gpu > len(gpus):
raise ValueError('number of gpus specified={}, more than gpus available={}'.format(num_gpu,len(gpus)))
gpus=gpus[:num_gpu]
data_by_gpu={g:{} for g in gpus}
for key,value in data_loader.items():
spl_vals=tf.split(value,num_gpu)
for gpu,val in zip(gpus,spl_vals):
data_by_gpu[gpu][key]=val
return data_by_gpu
def rank(array):
return len(array.shape)
def make_grid(tensor, nrow=8, padding=2,
normalize=False, scale_each=False):
"""Code based on https://github.com/pytorch/vision/blob/master/torchvision/utils.py
minor improvement, row/col was reversed"""
nmaps = tensor.shape[0]
ymaps = min(nrow, nmaps)
xmaps = int(math.ceil(float(nmaps) / ymaps))
height, width = int(tensor.shape[1] + padding), int(tensor.shape[2] + padding)
grid = np.zeros([height * ymaps + 1 + padding // 2, width * xmaps + 1 + padding // 2, 3], dtype=np.uint8)
k = 0
for y in range(ymaps):
for x in range(xmaps):
if k >= nmaps:
break
h, h_width = y * height + 1 + padding // 2, height - padding
w, w_width = x * width + 1 + padding // 2, width - padding
grid[h:h+h_width, w:w+w_width] = tensor[k]
k = k + 1
return grid
def save_image(tensor, filename, nrow=8, padding=2,
normalize=False, scale_each=False):
ndarr = make_grid(tensor, nrow=nrow, padding=padding,
normalize=normalize, scale_each=scale_each)
im = Image.fromarray(ndarr)
im.save(filename)
|
[
"functools.partial",
"json.dump",
"os.makedirs",
"tensorflow.summary.scalar",
"os.path.realpath",
"numpy.zeros",
"tensorflow.reduce_mean",
"datetime.datetime.now",
"tensorflow.core.framework.summary_pb2.Summary.Value",
"os.path.exists",
"tensorflow.python.client.device_lib.list_local_devices",
"tensorflow.summary.histogram",
"tensorflow.square",
"PIL.Image.fromarray",
"shutil.copytree",
"tensorflow.split",
"os.path.join"
] |
[((616, 638), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['tensor'], {}), '(tensor)\n', (630, 638), True, 'import tensorflow as tf\n'), ((698, 748), 'tensorflow.summary.scalar', 'tf.summary.scalar', (["(name + '_ave')", 'ave', 'collections'], {}), "(name + '_ave', ave, collections)\n", (715, 748), True, 'import tensorflow as tf\n'), ((749, 799), 'tensorflow.summary.scalar', 'tf.summary.scalar', (["(name + '_std')", 'std', 'collections'], {}), "(name + '_std', std, collections)\n", (766, 799), True, 'import tensorflow as tf\n'), ((1617, 1662), 'os.path.join', 'os.path.join', (['config.data_dir', 'config.dataset'], {}), '(config.data_dir, config.dataset)\n', (1629, 1662), False, 'import os\n'), ((3691, 3716), 'os.path.join', 'os.path.join', (['where', 'name'], {}), '(where, name)\n', (3703, 3716), False, 'import os\n'), ((3972, 4003), 'tensorflow.python.client.device_lib.list_local_devices', 'device_lib.list_local_devices', ([], {}), '()\n', (4001, 4003), False, 'from tensorflow.python.client import device_lib\n'), ((5366, 5468), 'numpy.zeros', 'np.zeros', (['[height * ymaps + 1 + padding // 2, width * xmaps + 1 + padding // 2, 3]'], {'dtype': 'np.uint8'}), '([height * ymaps + 1 + padding // 2, width * xmaps + 1 + padding //\n 2, 3], dtype=np.uint8)\n', (5374, 5468), True, 'import numpy as np\n'), ((6063, 6085), 'PIL.Image.fromarray', 'Image.fromarray', (['ndarr'], {}), '(ndarr)\n', (6078, 6085), False, 'from PIL import Image\n'), ((817, 874), 'tensorflow.summary.histogram', 'tf.summary.histogram', (["(name + '_hist')", 'tensor', 'collections'], {}), "(name + '_hist', tensor, collections)\n", (837, 874), True, 'import tensorflow as tf\n'), ((1546, 1593), 'os.path.join', 'os.path.join', (['config.log_dir', 'config.model_name'], {}), '(config.log_dir, config.model_name)\n', (1558, 1593), False, 'import os\n'), ((1722, 1760), 'os.path.join', 'os.path.join', (['config.model_dir', '"""code"""'], {}), "(config.model_dir, 'code')\n", (1734, 1760), False, 'import os\n'), ((2548, 2597), 'functools.partial', 'partial', (['ignore_except'], {'allowed_dirs': 'allowed_dirs'}), '(ignore_except, allowed_dirs=allowed_dirs)\n', (2555, 2597), False, 'from functools import partial\n'), ((2605, 2692), 'shutil.copytree', 'shutil.copytree', (['code_dir', 'config.log_code_dir'], {'symlinks': '(True)', 'ignore': 'ignore_these'}), '(code_dir, config.log_code_dir, symlinks=True, ignore=\n ignore_these)\n', (2620, 2692), False, 'import shutil\n'), ((3810, 3866), 'json.dump', 'json.dump', (['config.__dict__', 'fp'], {'indent': '(4)', 'sort_keys': '(True)'}), '(config.__dict__, fp, indent=4, sort_keys=True)\n', (3819, 3866), False, 'import json\n'), ((4763, 4787), 'tensorflow.split', 'tf.split', (['value', 'num_gpu'], {}), '(value, num_gpu)\n', (4771, 4787), True, 'import tensorflow as tf\n'), ((670, 693), 'tensorflow.square', 'tf.square', (['(ave - tensor)'], {}), '(ave - tensor)\n', (679, 693), True, 'import tensorflow as tf\n'), ((2100, 2129), 'os.path.realpath', 'os.path.realpath', (['sys.argv[0]'], {}), '(sys.argv[0])\n', (2116, 2129), False, 'import os\n'), ((3207, 3221), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (3219, 3221), False, 'from datetime import datetime\n'), ((435, 488), 'tensorflow.core.framework.summary_pb2.Summary.Value', 'summary_pb2.Summary.Value', ([], {'tag': 'name', 'simple_value': 'val'}), '(tag=name, simple_value=val)\n', (460, 488), False, 'from tensorflow.core.framework import summary_pb2\n'), ((1873, 1893), 'os.path.exists', 'os.path.exists', (['path'], {}), '(path)\n', (1887, 1893), False, 'import os\n'), ((1911, 1928), 'os.makedirs', 'os.makedirs', (['path'], {}), '(path)\n', (1922, 1928), False, 'import os\n')]
|
""" This module contains functions that return a new, single point in a given
parameter space. In general, these functions are not used to return
multi-dimensional arrays. These functions are intended to be called only a
few times.
"""
import numpy
from mystic import math
def uniform(lower_bounds, upper_bounds):
""" Returns a new, single point via uniform distribution.
Parameters
----------
lower_bounds : list
List of ``float`` that are lower bounds. List is indexed by parameter.
upper_bounds : list
List of ``float`` that are upper bounds. List is indexed by parameter.
Returns
-------
pts : numpy.array
An array with new point.
"""
ndim = len(lower_bounds)
pts = numpy.zeros(ndim)
for j in range(ndim):
lb = lower_bounds[j]
ub = upper_bounds[j]
pts[j] = numpy.random.uniform(lb, ub)
return pts
def tolerance(lower_bounds, upper_bounds, data=None):
""" Returns a new, single point some tolerence away from existing points.
Parameters
----------
lower_bounds : list
List of ``float`` that are lower bounds. List is indexed by parameter.
upper_bounds : list
List of ``float`` that are upper bounds. List is indexed by parameter.
data : {None, list}
List of tuples. Each tuple is a list of ``float`` that are previous
data points.
Returns
-------
pts : numpy.array
An array with new point.
"""
rtol = None
dist = None
n_new_pts = 1
data = [] if data == None else data
if len(data) == 0:
return uniform(lower_bounds, upper_bounds)
pts = math.fillpts(lower_bounds, upper_bounds, n_new_pts, data, rtol, dist)
return pts[0]
def linspace(lower_bounds, upper_bounds, step=0, nsteps=1):
""" Returns a new, single point linearlly-spaced ``i`` from the lower
boundary.
Parameters
----------
lower_bounds : list
List of ``float`` that are lower bounds. List is indexed by parameter.
upper_bounds : list
List of ``float`` that are upper bounds. List is indexed by parameter.
step : int
Index to select.
nsteps : int
Total number of steps.
Returns
-------
pts : numpy.array
An array with new point.
"""
ndim = len(lower_bounds)
pts = numpy.zeros(ndim)
for j in range(ndim):
step_size = (upper_bounds[j] - lower_bounds[j]) / (nsteps)
pts[j] = step * step_size + lower_bounds[j] + 0.5 * step_size
return pts
def midpoint(lower_bounds, upper_bounds):
""" Returns a new, single point at the center.
Parameters
----------
lower_bounds : list
List of ``float`` that are lower bounds. List is indexed by parameter.
upper_bounds : list
List of ``float`` that are upper bounds. List is indexed by parameter.
Returns
-------
pts : numpy.array
An array with new point.
"""
ndim = len(lower_bounds)
pts = numpy.zeros(ndim)
for j in range(ndim):
lb = lower_bounds[j]
ub = upper_bounds[j]
pts[j] = (ub - lb) / 2.0 + lb
return pts
# dict of sampling methods
sampling_methods = {
"linspace" : linspace,
"tolerance" : tolerance,
"uniform" : uniform,
}
|
[
"mystic.math.fillpts",
"numpy.random.uniform",
"numpy.zeros"
] |
[((742, 759), 'numpy.zeros', 'numpy.zeros', (['ndim'], {}), '(ndim)\n', (753, 759), False, 'import numpy\n'), ((1658, 1727), 'mystic.math.fillpts', 'math.fillpts', (['lower_bounds', 'upper_bounds', 'n_new_pts', 'data', 'rtol', 'dist'], {}), '(lower_bounds, upper_bounds, n_new_pts, data, rtol, dist)\n', (1670, 1727), False, 'from mystic import math\n'), ((2347, 2364), 'numpy.zeros', 'numpy.zeros', (['ndim'], {}), '(ndim)\n', (2358, 2364), False, 'import numpy\n'), ((3001, 3018), 'numpy.zeros', 'numpy.zeros', (['ndim'], {}), '(ndim)\n', (3012, 3018), False, 'import numpy\n'), ((861, 889), 'numpy.random.uniform', 'numpy.random.uniform', (['lb', 'ub'], {}), '(lb, ub)\n', (881, 889), False, 'import numpy\n')]
|
import plot_line
import numpy as np
import reader
import render_figure
class PlotAltitude(plot_line.LinePlot):
def __init__(self, fig_cluster, fig_name, fig):
self.fig = fig
self.fig_name = fig_name
self.fig_cluster = fig_cluster
self.config = self.get_config()
self.index_alt = self.get_column_index("altitude")
self.index_gps_alt = self.get_column_index("altitude_gps")
self.alt_x = self.alt_y = np.array([])
self.gps_alt_x = self.gps_alt_y = np.array([])
self.ax = self.fig.add_subplot(*self.config["dimensions"])
def set_fig_color(self,curr_value):
pass
def set_up(self):
"""Sets title , x and y label,
initializes the x and y limits
"""
self.h_alt, = self.ax.plot(self.alt_x, lw=3 , label="Altitude")
self.h_gps_alt, = self.ax.plot(self.gps_alt_x, lw=3 , label="GPS Altitude")
self.ax.legend(bbox_to_anchor=(1.05, 1), loc='lower center', borderaxespad=0.)
self.ax.set_ylim(0,100)
self.ax.set_xlim(0,100)
self.ax.title.set_text(self.config["title"])
self.ax.set_xlabel(self.config["x_label"])
self.ax.set_ylabel(self.config["y_label"])
def read_data(self,data_array):
"""Read data and appends em to dataset.
Arguments:
data_array {list} -- array with data from a row
"""
value_type = self.config['value_type']
try:
curr_value_alt = data_array[self.index_alt]
curr_value_gps_alt = data_array[self.index_gps_alt]
except:
curr_value_alt = np.nan
curr_value_gps_alt = np.nan
value_type = self.str_to_command(value_type)
if str(curr_value_alt).strip() == 'None':
curr_value_alt = np.nan
else:
curr_value_alt = value_type(curr_value_alt)
if str(curr_value_gps_alt).strip() == 'None':
curr_value_gps_alt = np.nan
else:
curr_value_gps_alt = value_type(curr_value_gps_alt)
# TODO: Read time and not log id
time = int(data_array[0])
self.alt_x = np.append(self.alt_x,time)
self.alt_y = np.append(self.alt_y,curr_value_alt)
self.gps_alt_x = np.append(self.gps_alt_x,time)
self.gps_alt_y = np.append(self.gps_alt_y,curr_value_gps_alt)
if(len(self.alt_x) > self.config["limit"]):
#delete old values
self.alt_x = np.delete(self.alt_x, 0)
self.alt_y = np.delete(self.alt_y, 0)
self.gps_alt_x = np.delete(self.gps_alt_x, 0)
self.gps_alt_y = np.delete(self.gps_alt_y, 0)
def set_data(self):
if(len(self.alt_x) > 0):
self.ax.set_xlim(self.alt_x[0] -1 , self.alt_x[-1] +1)
min_y = np.nanmin(np.array([np.nanmin(self.alt_y), np.nanmin(self.gps_alt_y)]))
if not np.isnan(min_y):
max_y = np.nanmax(np.array([np.nanmax(self.alt_y), np.nanmax(self.gps_alt_y)]))
self.ax.set_ylim(min_y - 10, max_y + 10)
self.h_alt.set_ydata(self.alt_y)
self.h_alt.set_xdata(self.alt_x)
self.h_gps_alt.set_ydata(self.gps_alt_y)
self.h_gps_alt.set_xdata(self.gps_alt_x)
if __name__ == '__main__':
render_figure.RenderFigure("altitudes",PlotAltitude).start()
|
[
"numpy.nanmax",
"numpy.isnan",
"numpy.nanmin",
"numpy.append",
"numpy.array",
"numpy.delete",
"render_figure.RenderFigure"
] |
[((461, 473), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (469, 473), True, 'import numpy as np\n'), ((516, 528), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (524, 528), True, 'import numpy as np\n'), ((2201, 2228), 'numpy.append', 'np.append', (['self.alt_x', 'time'], {}), '(self.alt_x, time)\n', (2210, 2228), True, 'import numpy as np\n'), ((2249, 2286), 'numpy.append', 'np.append', (['self.alt_y', 'curr_value_alt'], {}), '(self.alt_y, curr_value_alt)\n', (2258, 2286), True, 'import numpy as np\n'), ((2312, 2343), 'numpy.append', 'np.append', (['self.gps_alt_x', 'time'], {}), '(self.gps_alt_x, time)\n', (2321, 2343), True, 'import numpy as np\n'), ((2368, 2413), 'numpy.append', 'np.append', (['self.gps_alt_y', 'curr_value_gps_alt'], {}), '(self.gps_alt_y, curr_value_gps_alt)\n', (2377, 2413), True, 'import numpy as np\n'), ((2522, 2546), 'numpy.delete', 'np.delete', (['self.alt_x', '(0)'], {}), '(self.alt_x, 0)\n', (2531, 2546), True, 'import numpy as np\n'), ((2572, 2596), 'numpy.delete', 'np.delete', (['self.alt_y', '(0)'], {}), '(self.alt_y, 0)\n', (2581, 2596), True, 'import numpy as np\n'), ((2627, 2655), 'numpy.delete', 'np.delete', (['self.gps_alt_x', '(0)'], {}), '(self.gps_alt_x, 0)\n', (2636, 2655), True, 'import numpy as np\n'), ((2685, 2713), 'numpy.delete', 'np.delete', (['self.gps_alt_y', '(0)'], {}), '(self.gps_alt_y, 0)\n', (2694, 2713), True, 'import numpy as np\n'), ((3414, 3467), 'render_figure.RenderFigure', 'render_figure.RenderFigure', (['"""altitudes"""', 'PlotAltitude'], {}), "('altitudes', PlotAltitude)\n", (3440, 3467), False, 'import render_figure\n'), ((2981, 2996), 'numpy.isnan', 'np.isnan', (['min_y'], {}), '(min_y)\n', (2989, 2996), True, 'import numpy as np\n'), ((2897, 2918), 'numpy.nanmin', 'np.nanmin', (['self.alt_y'], {}), '(self.alt_y)\n', (2906, 2918), True, 'import numpy as np\n'), ((2920, 2945), 'numpy.nanmin', 'np.nanmin', (['self.gps_alt_y'], {}), '(self.gps_alt_y)\n', (2929, 2945), True, 'import numpy as np\n'), ((3042, 3063), 'numpy.nanmax', 'np.nanmax', (['self.alt_y'], {}), '(self.alt_y)\n', (3051, 3063), True, 'import numpy as np\n'), ((3065, 3090), 'numpy.nanmax', 'np.nanmax', (['self.gps_alt_y'], {}), '(self.gps_alt_y)\n', (3074, 3090), True, 'import numpy as np\n')]
|
# Copyright 2019, The Jelly Bean World Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy of
# the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.
"""Collection of JBW environments for OpenAI gym."""
from __future__ import absolute_import, division, print_function
import numpy as np
try:
from gym.envs.registration import register
modules_loaded = True
except:
modules_loaded = False
from .agent import Agent
from .direction import RelativeDirection
from .item import *
from .simulator import *
from .visualizer import MapVisualizer, pi
def make_config():
# specify the item types
items = []
items.append(Item("banana", [0.0, 1.0, 0.0], [0.0, 1.0, 0.0], [1, 0, 0, 0], [0, 0, 0, 0], False, 0.0,
intensity_fn=IntensityFunction.CONSTANT, intensity_fn_args=[-5.3],
interaction_fns=[
[InteractionFunction.PIECEWISE_BOX, 10.0, 200.0, 0.0, -6.0], # parameters for interaction between item 0 and item 0
[InteractionFunction.PIECEWISE_BOX, 200.0, 0.0, -6.0, -6.0], # parameters for interaction between item 0 and item 1
[InteractionFunction.PIECEWISE_BOX, 10.0, 200.0, 2.0, -100.0], # parameters for interaction between item 0 and item 2
[InteractionFunction.ZERO] # parameters for interaction between item 0 and item 3
]))
items.append(Item("onion", [1.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0, 1, 0, 0], [0, 0, 0, 0], False, 0.0,
intensity_fn=IntensityFunction.CONSTANT, intensity_fn_args=[-5.0],
interaction_fns=[
[InteractionFunction.PIECEWISE_BOX, 200.0, 0.0, -6.0, -6.0], # parameters for interaction between item 1 and item 0
[InteractionFunction.ZERO], # parameters for interaction between item 1 and item 1
[InteractionFunction.PIECEWISE_BOX, 200.0, 0.0, -100.0, -100.0], # parameters for interaction between item 1 and item 2
[InteractionFunction.ZERO] # parameters for interaction between item 1 and item 3
]))
items.append(Item("jellybean", [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0, 0, 0, 0], [0, 0, 0, 0], False, 0.0,
intensity_fn=IntensityFunction.CONSTANT, intensity_fn_args=[-5.3],
interaction_fns=[
[InteractionFunction.PIECEWISE_BOX, 10.0, 200.0, 2.0, -100.0], # parameters for interaction between item 2 and item 0
[InteractionFunction.PIECEWISE_BOX, 200.0, 0.0, -100.0, -100.0], # parameters for interaction between item 2 and item 1
[InteractionFunction.PIECEWISE_BOX, 10.0, 200.0, 0.0, -6.0], # parameters for interaction between item 2 and item 2
[InteractionFunction.ZERO] # parameters for interaction between item 2 and item 3
]))
items.append(Item("wall", [0.0, 0.0, 0.0], [0.5, 0.5, 0.5], [0, 0, 0, 1], [0, 0, 0, 0], True, 0.0,
intensity_fn=IntensityFunction.CONSTANT, intensity_fn_args=[0.0],
interaction_fns=[
[InteractionFunction.ZERO], # parameters for interaction between item 3 and item 0
[InteractionFunction.ZERO], # parameters for interaction between item 3 and item 1
[InteractionFunction.ZERO], # parameters for interaction between item 3 and item 2
[InteractionFunction.CROSS, 10.0, 15.0, 20.0, -200.0, -20.0, 1.0] # parameters for interaction between item 3 and item 3
]))
# construct the simulator configuration
return SimulatorConfig(max_steps_per_movement=1, vision_range=5,
allowed_movement_directions=[ActionPolicy.ALLOWED, ActionPolicy.DISALLOWED, ActionPolicy.DISALLOWED, ActionPolicy.DISALLOWED],
allowed_turn_directions=[ActionPolicy.DISALLOWED, ActionPolicy.DISALLOWED, ActionPolicy.ALLOWED, ActionPolicy.ALLOWED],
no_op_allowed=False, patch_size=32, mcmc_num_iter=4000, items=items, agent_color=[0.0, 0.0, 1.0], agent_field_of_view=2*pi,
collision_policy=MovementConflictPolicy.FIRST_COME_FIRST_SERVED, decay_param=0.4, diffusion_param=0.14, deleted_item_lifetime=2000)
def make_v1_config():
"""
This config file matches the config
"""
# specify the item types
items = []
# ANOTHER discrepancy in paper. Paper lists interaction with wall, whereas Configurations.swift
# lists interaction with tree. Maybe it's a wrong index? Maybe the paper is listed incorrectly?
items.append(Item("banana", [1.92, 1.76, 0.40], [0.96, 0.88, 0.20], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], False, 0.0,
intensity_fn=IntensityFunction.CONSTANT, intensity_fn_args=[1.5],
interaction_fns=[
[InteractionFunction.PIECEWISE_BOX, 10.0, 100.0, 0.0, -6.0],
[InteractionFunction.ZERO],
[InteractionFunction.PIECEWISE_BOX, 10.0, 100.0, 2.0, -100.0],
[InteractionFunction.ZERO],
[InteractionFunction.PIECEWISE_BOX, 50.0, 100.0, -100.0, -100.0],
[InteractionFunction.ZERO]
]))
# Onion has a discrepancy in intensity - in the paper it's listed as +1.5.
items.append(Item("onion", [0.68, 0.01, 0.99], [0.68, 0.01, 0.99], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], False, 0.0,
intensity_fn=IntensityFunction.CONSTANT, intensity_fn_args=[-3.0],
interaction_fns=[
[InteractionFunction.ZERO],
[InteractionFunction.ZERO],
[InteractionFunction.ZERO],
[InteractionFunction.ZERO],
[InteractionFunction.ZERO],
[InteractionFunction.ZERO]
]))
items.append(Item("jellybean", [1.64, 0.54, 0.40], [0.82, 0.27, 0.20], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], False, 0.0,
intensity_fn=IntensityFunction.CONSTANT, intensity_fn_args=[1.5],
interaction_fns=[
[InteractionFunction.PIECEWISE_BOX, 10.0, 100.0, 2.0, -100.0],
[InteractionFunction.ZERO],
[InteractionFunction.PIECEWISE_BOX, 10.0, 100.0, 0.0, -6.0],
[InteractionFunction.ZERO],
[InteractionFunction.PIECEWISE_BOX, 50.0, 100.0, -100.0, -100.0],
[InteractionFunction.ZERO]
]))
items.append(Item("wall", [0.0, 0.0, 0.0], [0.20, 0.47, 0.67], [0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0], True, 0.0,
intensity_fn=IntensityFunction.CONSTANT, intensity_fn_args=[-12.0],
interaction_fns=[
[InteractionFunction.ZERO],
[InteractionFunction.ZERO],
[InteractionFunction.ZERO],
[InteractionFunction.CROSS, 20.0, 40.0, 8.0, -1000.0, -1000.0, -1.0],
[InteractionFunction.ZERO],
[InteractionFunction.ZERO]
]))
items.append(Item("tree", [0.00, 0.47, 0.06], [0.00, 0.47, 0.06], [0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0], False, 0.0,
intensity_fn=IntensityFunction.CONSTANT, intensity_fn_args=[2.0],
interaction_fns=[
[InteractionFunction.ZERO],
[InteractionFunction.ZERO],
[InteractionFunction.ZERO],
[InteractionFunction.ZERO],
[InteractionFunction.PIECEWISE_BOX, 100.0, 500.0, 0.0, -0.1],
[InteractionFunction.ZERO]
]))
items.append(Item("truffle", [8.40, 4.80, 2.60], [0.42, 0.24, 0.13], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], False, 0.0,
intensity_fn=IntensityFunction.CONSTANT, intensity_fn_args=[0.0],
interaction_fns=[
[InteractionFunction.ZERO], # parameters for interaction between item 3 and item 0
[InteractionFunction.ZERO], # parameters for interaction between item 3 and item 1
[InteractionFunction.ZERO], # parameters for interaction between item 3 and item 2
[InteractionFunction.ZERO], # parameters for interaction between item 3 and item 2
[InteractionFunction.PIECEWISE_BOX, 4.0, 200.0, 2.0, 0.0],
[InteractionFunction.PIECEWISE_BOX, 30.0, 1000.0, -0.3, -1.0],
]))
# construct the simulator configuration
return SimulatorConfig(max_steps_per_movement=1, vision_range=5,
allowed_movement_directions=[ActionPolicy.ALLOWED, ActionPolicy.DISALLOWED, ActionPolicy.DISALLOWED, ActionPolicy.DISALLOWED],
allowed_turn_directions=[ActionPolicy.DISALLOWED, ActionPolicy.DISALLOWED, ActionPolicy.ALLOWED, ActionPolicy.ALLOWED],
no_op_allowed=False, patch_size=32, mcmc_num_iter=4000, items=items, agent_color=[0.0, 0.0, 1.0], agent_field_of_view=2*pi,
collision_policy=MovementConflictPolicy.FIRST_COME_FIRST_SERVED, decay_param=0.4, diffusion_param=0.14, deleted_item_lifetime=2000)
def case1_reward_fn(prev_items, items):
"""
Reference for item indicies:
0 - Banana: 0 reward
1 - Onion: -1 reward for every one collected
2 - JellyBean: +1 reward for every one collected
3 - Wall: 0 reward, cannot collect
4 - Tree: 0 reward, cannot collect
5 - Truffle: 0 reward
"""
reward_array = np.array([0, -1, 1, 0, 0, 0])
diff = items - prev_items
return (diff * reward_array).sum().astype(np.float32)
if modules_loaded:
# Construct the simulator configuration.
sim_config = make_config()
# Create a reward function.
reward_fn = lambda prev_items, items: len(items) - len(prev_items)
register(
id='JBW-v0',
entry_point='jbw.environment:JBWEnv',
kwargs={
'sim_config': sim_config,
'reward_fn': reward_fn,
'render': False})
register(
id='JBW-render-v0',
entry_point='jbw.environment:JBWEnv',
kwargs={
'sim_config': sim_config,
'reward_fn': reward_fn,
'render': True})
sim_v1_config = make_v1_config()
register(
id='JBW-v1',
entry_point='jbw.environment:JBWEnv',
kwargs={
'sim_config': sim_v1_config,
'reward_fn': case1_reward_fn,
'render': False})
register(
id='JBW-render-v1',
entry_point='jbw.environment:JBWEnv',
kwargs={
'sim_config': sim_v1_config,
'reward_fn': case1_reward_fn,
'render': True})
|
[
"numpy.array",
"gym.envs.registration.register"
] |
[((10444, 10473), 'numpy.array', 'np.array', (['[0, -1, 1, 0, 0, 0]'], {}), '([0, -1, 1, 0, 0, 0])\n', (10452, 10473), True, 'import numpy as np\n'), ((10758, 10898), 'gym.envs.registration.register', 'register', ([], {'id': '"""JBW-v0"""', 'entry_point': '"""jbw.environment:JBWEnv"""', 'kwargs': "{'sim_config': sim_config, 'reward_fn': reward_fn, 'render': False}"}), "(id='JBW-v0', entry_point='jbw.environment:JBWEnv', kwargs={\n 'sim_config': sim_config, 'reward_fn': reward_fn, 'render': False})\n", (10766, 10898), False, 'from gym.envs.registration import register\n'), ((10941, 11087), 'gym.envs.registration.register', 'register', ([], {'id': '"""JBW-render-v0"""', 'entry_point': '"""jbw.environment:JBWEnv"""', 'kwargs': "{'sim_config': sim_config, 'reward_fn': reward_fn, 'render': True}"}), "(id='JBW-render-v0', entry_point='jbw.environment:JBWEnv', kwargs={\n 'sim_config': sim_config, 'reward_fn': reward_fn, 'render': True})\n", (10949, 11087), False, 'from gym.envs.registration import register\n'), ((11166, 11320), 'gym.envs.registration.register', 'register', ([], {'id': '"""JBW-v1"""', 'entry_point': '"""jbw.environment:JBWEnv"""', 'kwargs': "{'sim_config': sim_v1_config, 'reward_fn': case1_reward_fn, 'render': False}"}), "(id='JBW-v1', entry_point='jbw.environment:JBWEnv', kwargs={\n 'sim_config': sim_v1_config, 'reward_fn': case1_reward_fn, 'render': False}\n )\n", (11174, 11320), False, 'from gym.envs.registration import register\n'), ((11364, 11519), 'gym.envs.registration.register', 'register', ([], {'id': '"""JBW-render-v1"""', 'entry_point': '"""jbw.environment:JBWEnv"""', 'kwargs': "{'sim_config': sim_v1_config, 'reward_fn': case1_reward_fn, 'render': True}"}), "(id='JBW-render-v1', entry_point='jbw.environment:JBWEnv', kwargs={\n 'sim_config': sim_v1_config, 'reward_fn': case1_reward_fn, 'render': True})\n", (11372, 11519), False, 'from gym.envs.registration import register\n')]
|
# Copyright 2020 Standard Cyborg
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
import numpy as np
from scsdk import scsdk_native as scsdk
from PIL import Image
# This script demonstrates a bunch of the different node types in a SceneGraph
root = scsdk.Node()
root.name = "root"
# geometry node, that repsents a geometry that is a single triangle.
child1 = scsdk.GeometryNode()
child1.name = "triangle1"
child1.geometry.positions = np.array([ [0,0,0], [1,0,0], [0,1,0] ])
child1.geometry.normals = np.array([ [0,0,1], [0,0,1], [0,0,1] ])
child1.geometry.colors = np.array([ [1,0,0], [1,0,0], [0,1,0] ])
child1.geometry.faces = np.array([ [0,1,2] ])
child1.transform = np.array([
[1,0,0,-3.0],
[0,1,0,0],
[0,0,1,0]])
root.appendChild(child1)
# geometry node, that repsents a geometry that is a point cloud.
# since no faces are specified, it is considered a point cloud.
pointcloud = scsdk.GeometryNode()
pointcloud.name = "point cloud"
N = 20
positions = np.zeros((N * N, 3))
colors = np.zeros((N * N, 3))
for y in range(N):
for x in range(N):
positions[y * N + x] = [float(x) / N, float(y) / N, 0.0]
colors[y * N + x] = [float(x) / N, float(y) / N, 0.0]
pointcloud.geometry.positions = positions
pointcloud.geometry.colors = colors
pointcloud.transform = np.array([
[1,0,0,2.99],
[0,1,0,0.19],
[0,0,1,0.39]])
root.appendChild(pointcloud)
# This node contains a RGBA image.
child3 = scsdk.ColorImageNode()
child3.name = "example image"
child3.colorImage = scsdk.ColorImage(width=2, height=2, rgba=np.array([
[0.0, 0.0, 0.0, 1.0], [0.0, 1.0, 0.0, 1.0],
[0.0, 0.0, 0.0, 1.0], [0.3, 0.9, 0.6, 1.0]]))
child3.transform = np.array([
[1,0,0,-2.0],
[0,1,0,2.6],
[0,0,1,0.01]])
root.appendChild(child3)
# This shows a geometry with a texture applied.
texturedGeo = scsdk.GeometryNode()
texturedGeo.name = "texturedGeo"
texturedGeo.geometry.positions = np.array([ [0,0,0], [1,0,0], [0,1,0] ])
# remember to add normals, or it will crash!
texturedGeo.geometry.normals = np.array([ [0,0,1], [0,0,1], [0,0,1] ])
texturedGeo.geometry.texCoords = np.array([ [0,0], [1,0], [0,1] ]) # texture coordinates are necessary for textured geometries.
texturedGeo.geometry.faces = np.array([ [0,1,2] ])
texturedGeo.transform = np.array([
[1,0,0,-3.0],
[0,1,0,5],
[0,0,1,0]])
RES = 16
rgba = np.zeros((RES * RES, 4))
# create the texture.
for i in range(RES * RES):
t = float(i) / float(RES * RES)
rgba[i, 0] = 0.3 + 0.5 * t
rgba[i, 1] = 0.8 - 0.7 *t
rgba[i, 2] = 1.0 * t
rgba[i, 3] = 1.0
texturedGeo.geometry.texture = scsdk.ColorImage(width=RES, height=RES, rgba=rgba)
root.appendChild(texturedGeo)
# A depth image, is an image with depth value stored for every pixel.
depthImageNode = scsdk.DepthImageNode()
depthImageNode.name = "example depth image"
depthImageNode.transform = np.array([
[1,0,0,0.31],
[0,1,0,-2.51],
[0,0,1,-0.29]])
RES = 16
depth = np.zeros((RES * RES))
for i in range(RES * RES):
depth[i] = float(i) / float(RES * RES)
depthImageNode.depthImage = scsdk.DepthImage(width=RES, height=RES, depth=depth)
root.appendChild(depthImageNode)
# Load a png, and put it in a ColorImageNode
chickenImageNode = scsdk.ColorImageNode()
chickenImageNode.name = "chicken.png"
chickenImageNode.transform = np.array([
[1,0,0,-5.0],
[0,1,0,0.32],
[0,0,1,0.09]])
im = Image.open("chicken.png")
rgba = np.zeros((im.size[1] * im.size[0], 4))
data = list(im.getdata())
for i in range(len(data)):
rgba[i, 0] = pow(data[i][0] / 255.0, 2.2)
rgba[i, 1] = pow(data[i][1] / 255.0, 2.2)
rgba[i, 2] = pow(data[i][2] / 255.0, 2.2)
rgba[i, 3] = 1.0
chickenImageNode.colorImage = scsdk.ColorImage(width=im.size[0], height=im.size[1], rgba=rgba)
root.appendChild(chickenImageNode)
# A polyline node, is a bunch of lines connected, specified by a list of points.
polylineNode = scsdk.PolylineNode()
polylineNode.name = "polyline"
polylineNode.polyline.positions = np.array([ [0,0,0], [1,0,0], [0,1,0], [0,1,1], [1,1,1] ])
polylineNode.transform = np.array([
[1,0,0,+3.0],
[0,1,0,1],
[0,0,1,1]])
polylineNode.material.objectColor = np.array([0.0,0.0,1.0])
polylineNode.material.materialModel = scsdk.MaterialModel.Unlit
root.appendChild(polylineNode)
# print the SceneGraph.
def printSceneGraph(node, indent):
typee = "node"
output = indent + node.name
misc = ""
if node.isGeometryNode():
typee = "geometry"
misc = misc + "vertexCount: " + str(node.geometry.positions.shape[0]) + ", "
misc = misc + "faceCount: " + str( node.geometry.faces.shape[0])
elif node.isColorImageNode():
typee = "colorImage"
misc = misc + "size: " + str(node.colorImage.width) + "x" + str(node.colorImage.height)
elif node.isDepthImageNode():
typee = "depthImage"
misc = misc + "size: " + str(node.depthImage.width) + "x" + str(node.depthImage.height)
elif node.isPolylineNode():
typee = "polyline"
misc = misc + "vertexCount: " + str(node.polyline.positions.shape[0])
output = output + ", type: " + typee + ", misc: " + misc
print(output)
for childNode in node.children():
printSceneGraph(childNode, indent + " ")
# write SceneGraph
scsdk.WriteSceneGraphToGltf(root, "./node_types.gltf")
# now read it, and print the SceneGraph
with open("./node_types.gltf", 'r') as file:
data = file.read().replace('\n', '')
readRoot = scsdk.ReadSceneGraphFromGltf(data)[0]
printSceneGraph(readRoot, "")
|
[
"scsdk.scsdk_native.Node",
"scsdk.scsdk_native.DepthImageNode",
"scsdk.scsdk_native.ColorImageNode",
"scsdk.scsdk_native.DepthImage",
"scsdk.scsdk_native.GeometryNode",
"scsdk.scsdk_native.WriteSceneGraphToGltf",
"numpy.zeros",
"scsdk.scsdk_native.ColorImage",
"PIL.Image.open",
"numpy.array",
"scsdk.scsdk_native.ReadSceneGraphFromGltf",
"scsdk.scsdk_native.PolylineNode"
] |
[((764, 776), 'scsdk.scsdk_native.Node', 'scsdk.Node', ([], {}), '()\n', (774, 776), True, 'from scsdk import scsdk_native as scsdk\n'), ((876, 896), 'scsdk.scsdk_native.GeometryNode', 'scsdk.GeometryNode', ([], {}), '()\n', (894, 896), True, 'from scsdk import scsdk_native as scsdk\n'), ((951, 994), 'numpy.array', 'np.array', (['[[0, 0, 0], [1, 0, 0], [0, 1, 0]]'], {}), '([[0, 0, 0], [1, 0, 0], [0, 1, 0]])\n', (959, 994), True, 'import numpy as np\n'), ((1017, 1060), 'numpy.array', 'np.array', (['[[0, 0, 1], [0, 0, 1], [0, 0, 1]]'], {}), '([[0, 0, 1], [0, 0, 1], [0, 0, 1]])\n', (1025, 1060), True, 'import numpy as np\n'), ((1082, 1125), 'numpy.array', 'np.array', (['[[1, 0, 0], [1, 0, 0], [0, 1, 0]]'], {}), '([[1, 0, 0], [1, 0, 0], [0, 1, 0]])\n', (1090, 1125), True, 'import numpy as np\n'), ((1146, 1167), 'numpy.array', 'np.array', (['[[0, 1, 2]]'], {}), '([[0, 1, 2]])\n', (1154, 1167), True, 'import numpy as np\n'), ((1187, 1242), 'numpy.array', 'np.array', (['[[1, 0, 0, -3.0], [0, 1, 0, 0], [0, 0, 1, 0]]'], {}), '([[1, 0, 0, -3.0], [0, 1, 0, 0], [0, 0, 1, 0]])\n', (1195, 1242), True, 'import numpy as np\n'), ((1502, 1522), 'scsdk.scsdk_native.GeometryNode', 'scsdk.GeometryNode', ([], {}), '()\n', (1520, 1522), True, 'from scsdk import scsdk_native as scsdk\n'), ((1574, 1594), 'numpy.zeros', 'np.zeros', (['(N * N, 3)'], {}), '((N * N, 3))\n', (1582, 1594), True, 'import numpy as np\n'), ((1604, 1624), 'numpy.zeros', 'np.zeros', (['(N * N, 3)'], {}), '((N * N, 3))\n', (1612, 1624), True, 'import numpy as np\n'), ((1895, 1956), 'numpy.array', 'np.array', (['[[1, 0, 0, 2.99], [0, 1, 0, 0.19], [0, 0, 1, 0.39]]'], {}), '([[1, 0, 0, 2.99], [0, 1, 0, 0.19], [0, 0, 1, 0.39]])\n', (1903, 1956), True, 'import numpy as np\n'), ((2121, 2143), 'scsdk.scsdk_native.ColorImageNode', 'scsdk.ColorImageNode', ([], {}), '()\n', (2141, 2143), True, 'from scsdk import scsdk_native as scsdk\n'), ((2420, 2480), 'numpy.array', 'np.array', (['[[1, 0, 0, -2.0], [0, 1, 0, 2.6], [0, 0, 1, 0.01]]'], {}), '([[1, 0, 0, -2.0], [0, 1, 0, 2.6], [0, 0, 1, 0.01]])\n', (2428, 2480), True, 'import numpy as np\n'), ((2658, 2678), 'scsdk.scsdk_native.GeometryNode', 'scsdk.GeometryNode', ([], {}), '()\n', (2676, 2678), True, 'from scsdk import scsdk_native as scsdk\n'), ((2745, 2788), 'numpy.array', 'np.array', (['[[0, 0, 0], [1, 0, 0], [0, 1, 0]]'], {}), '([[0, 0, 0], [1, 0, 0], [0, 1, 0]])\n', (2753, 2788), True, 'import numpy as np\n'), ((2861, 2904), 'numpy.array', 'np.array', (['[[0, 0, 1], [0, 0, 1], [0, 0, 1]]'], {}), '([[0, 0, 1], [0, 0, 1], [0, 0, 1]])\n', (2869, 2904), True, 'import numpy as np\n'), ((2934, 2968), 'numpy.array', 'np.array', (['[[0, 0], [1, 0], [0, 1]]'], {}), '([[0, 0], [1, 0], [0, 1]])\n', (2942, 2968), True, 'import numpy as np\n'), ((3058, 3079), 'numpy.array', 'np.array', (['[[0, 1, 2]]'], {}), '([[0, 1, 2]])\n', (3066, 3079), True, 'import numpy as np\n'), ((3104, 3159), 'numpy.array', 'np.array', (['[[1, 0, 0, -3.0], [0, 1, 0, 5], [0, 0, 1, 0]]'], {}), '([[1, 0, 0, -3.0], [0, 1, 0, 5], [0, 0, 1, 0]])\n', (3112, 3159), True, 'import numpy as np\n'), ((3266, 3290), 'numpy.zeros', 'np.zeros', (['(RES * RES, 4)'], {}), '((RES * RES, 4))\n', (3274, 3290), True, 'import numpy as np\n'), ((3518, 3568), 'scsdk.scsdk_native.ColorImage', 'scsdk.ColorImage', ([], {'width': 'RES', 'height': 'RES', 'rgba': 'rgba'}), '(width=RES, height=RES, rgba=rgba)\n', (3534, 3568), True, 'from scsdk import scsdk_native as scsdk\n'), ((3689, 3711), 'scsdk.scsdk_native.DepthImageNode', 'scsdk.DepthImageNode', ([], {}), '()\n', (3709, 3711), True, 'from scsdk import scsdk_native as scsdk\n'), ((3783, 3846), 'numpy.array', 'np.array', (['[[1, 0, 0, 0.31], [0, 1, 0, -2.51], [0, 0, 1, -0.29]]'], {}), '([[1, 0, 0, 0.31], [0, 1, 0, -2.51], [0, 0, 1, -0.29]])\n', (3791, 3846), True, 'import numpy as np\n'), ((3953, 3972), 'numpy.zeros', 'np.zeros', (['(RES * RES)'], {}), '(RES * RES)\n', (3961, 3972), True, 'import numpy as np\n'), ((4079, 4131), 'scsdk.scsdk_native.DepthImage', 'scsdk.DepthImage', ([], {'width': 'RES', 'height': 'RES', 'depth': 'depth'}), '(width=RES, height=RES, depth=depth)\n', (4095, 4131), True, 'from scsdk import scsdk_native as scsdk\n'), ((4232, 4254), 'scsdk.scsdk_native.ColorImageNode', 'scsdk.ColorImageNode', ([], {}), '()\n', (4252, 4254), True, 'from scsdk import scsdk_native as scsdk\n'), ((4322, 4383), 'numpy.array', 'np.array', (['[[1, 0, 0, -5.0], [0, 1, 0, 0.32], [0, 0, 1, 0.09]]'], {}), '([[1, 0, 0, -5.0], [0, 1, 0, 0.32], [0, 0, 1, 0.09]])\n', (4330, 4383), True, 'import numpy as np\n'), ((4511, 4536), 'PIL.Image.open', 'Image.open', (['"""chicken.png"""'], {}), "('chicken.png')\n", (4521, 4536), False, 'from PIL import Image\n'), ((4545, 4583), 'numpy.zeros', 'np.zeros', (['(im.size[1] * im.size[0], 4)'], {}), '((im.size[1] * im.size[0], 4))\n', (4553, 4583), True, 'import numpy as np\n'), ((4832, 4896), 'scsdk.scsdk_native.ColorImage', 'scsdk.ColorImage', ([], {'width': 'im.size[0]', 'height': 'im.size[1]', 'rgba': 'rgba'}), '(width=im.size[0], height=im.size[1], rgba=rgba)\n', (4848, 4896), True, 'from scsdk import scsdk_native as scsdk\n'), ((5032, 5052), 'scsdk.scsdk_native.PolylineNode', 'scsdk.PolylineNode', ([], {}), '()\n', (5050, 5052), True, 'from scsdk import scsdk_native as scsdk\n'), ((5118, 5183), 'numpy.array', 'np.array', (['[[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 1, 1], [1, 1, 1]]'], {}), '([[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 1, 1], [1, 1, 1]])\n', (5126, 5183), True, 'import numpy as np\n'), ((5202, 5257), 'numpy.array', 'np.array', (['[[1, 0, 0, +3.0], [0, 1, 0, 1], [0, 0, 1, 1]]'], {}), '([[1, 0, 0, +3.0], [0, 1, 0, 1], [0, 0, 1, 1]])\n', (5210, 5257), True, 'import numpy as np\n'), ((5384, 5409), 'numpy.array', 'np.array', (['[0.0, 0.0, 1.0]'], {}), '([0.0, 0.0, 1.0])\n', (5392, 5409), True, 'import numpy as np\n'), ((6505, 6559), 'scsdk.scsdk_native.WriteSceneGraphToGltf', 'scsdk.WriteSceneGraphToGltf', (['root', '"""./node_types.gltf"""'], {}), "(root, './node_types.gltf')\n", (6532, 6559), True, 'from scsdk import scsdk_native as scsdk\n'), ((6699, 6733), 'scsdk.scsdk_native.ReadSceneGraphFromGltf', 'scsdk.ReadSceneGraphFromGltf', (['data'], {}), '(data)\n', (6727, 6733), True, 'from scsdk import scsdk_native as scsdk\n'), ((2235, 2337), 'numpy.array', 'np.array', (['[[0.0, 0.0, 0.0, 1.0], [0.0, 1.0, 0.0, 1.0], [0.0, 0.0, 0.0, 1.0], [0.3, \n 0.9, 0.6, 1.0]]'], {}), '([[0.0, 0.0, 0.0, 1.0], [0.0, 1.0, 0.0, 1.0], [0.0, 0.0, 0.0, 1.0],\n [0.3, 0.9, 0.6, 1.0]])\n', (2243, 2337), True, 'import numpy as np\n')]
|
"""
Copyright (c) <2018> YoongiKim
See the file license.txt for copying permission.
"""
import tensorflow as tf
import random
import os
import numpy as np
# import matplotlib.pyplot as plt
import cv2
from tensorflow.examples.tutorials.mnist import input_data
tf.set_random_seed(777) # reproducibility
# This path is for ppo.py, this path won't work in the test.py
CHECK_POINT_DIR = './RiderEnvironment/mnist_model_custom'
TRAIN_DATA_DIR = './RiderEnvironment/score_train_data'
def allfiles(path):
names = []
for root, dirs, files in os.walk(path):
for file in files:
names.append(file.split('.')[0])
return names
def to_binary(img):
retval, threshold = cv2.threshold(img, 127, 1, cv2.THRESH_BINARY)
return np.array(threshold)
if __name__ == "__main__":
x = []
y = []
for i in range(10):
path = "{}/{}".format(TRAIN_DATA_DIR, i)
names = allfiles(path)
for name in names:
img = cv2.imread("{}/{}/{}.png".format(TRAIN_DATA_DIR, i, name), cv2.IMREAD_GRAYSCALE)
img = to_binary(img)
x.append(img.reshape(784))
y_one_hot = np.zeros(10)
y_one_hot[i] = 1
y.append(y_one_hot)
print(np.shape(x))
print(np.shape(y))
# hyper parameters
learning_rate = 0.0001
training_epochs = 1001
batch_size = 100
# dropout (keep_prob) rate 0.7~0.5 on training, but should be 1 for testing
keep_prob = tf.placeholder(tf.float32)
# input place holders
X = tf.placeholder(tf.float32, [None, 784])
X_img = tf.reshape(X, [-1, 28, 28, 1]) # img 28x28x1 (black/white)
Y = tf.placeholder(tf.float32, [None, 10])
# L1 ImgIn shape=(?, 28, 28, 1)
W1 = tf.Variable(tf.random_normal([3, 3, 1, 32], stddev=0.01))
# Conv -> (?, 28, 28, 32)
# Pool -> (?, 14, 14, 32)
L1 = tf.nn.conv2d(X_img, W1, strides=[1, 1, 1, 1], padding='SAME')
L1 = tf.nn.relu(L1)
L1 = tf.nn.max_pool(L1, ksize=[1, 2, 2, 1],
strides=[1, 2, 2, 1], padding='SAME')
L1 = tf.nn.dropout(L1, keep_prob=keep_prob)
'''
Tensor("Conv2D:0", shape=(?, 28, 28, 32), dtype=float32)
Tensor("Relu:0", shape=(?, 28, 28, 32), dtype=float32)
Tensor("MaxPool:0", shape=(?, 14, 14, 32), dtype=float32)
Tensor("dropout/mul:0", shape=(?, 14, 14, 32), dtype=float32)
'''
# L2 ImgIn shape=(?, 14, 14, 32)
W2 = tf.Variable(tf.random_normal([3, 3, 32, 64], stddev=0.01))
# Conv ->(?, 14, 14, 64)
# Pool ->(?, 7, 7, 64)
L2 = tf.nn.conv2d(L1, W2, strides=[1, 1, 1, 1], padding='SAME')
L2 = tf.nn.relu(L2)
L2 = tf.nn.max_pool(L2, ksize=[1, 2, 2, 1],
strides=[1, 2, 2, 1], padding='SAME')
L2 = tf.nn.dropout(L2, keep_prob=keep_prob)
'''
Tensor("Conv2D_1:0", shape=(?, 14, 14, 64), dtype=float32)
Tensor("Relu_1:0", shape=(?, 14, 14, 64), dtype=float32)
Tensor("MaxPool_1:0", shape=(?, 7, 7, 64), dtype=float32)
Tensor("dropout_1/mul:0", shape=(?, 7, 7, 64), dtype=float32)
'''
# L3 ImgIn shape=(?, 7, 7, 64)
W3 = tf.Variable(tf.random_normal([3, 3, 64, 128], stddev=0.01))
# Conv ->(?, 7, 7, 128)
# Pool ->(?, 4, 4, 128)
# Reshape ->(?, 4 * 4 * 128) # Flatten them for FC
L3 = tf.nn.conv2d(L2, W3, strides=[1, 1, 1, 1], padding='SAME')
L3 = tf.nn.relu(L3)
L3 = tf.nn.max_pool(L3, ksize=[1, 2, 2, 1], strides=[
1, 2, 2, 1], padding='SAME')
L3 = tf.nn.dropout(L3, keep_prob=keep_prob)
L3 = tf.reshape(L3, [-1, 128 * 4 * 4])
'''
Tensor("Conv2D_2:0", shape=(?, 7, 7, 128), dtype=float32)
Tensor("Relu_2:0", shape=(?, 7, 7, 128), dtype=float32)
Tensor("MaxPool_2:0", shape=(?, 4, 4, 128), dtype=float32)
Tensor("dropout_2/mul:0", shape=(?, 4, 4, 128), dtype=float32)
Tensor("Reshape_1:0", shape=(?, 2048), dtype=float32)
'''
# L4 FC 4x4x128 inputs -> 625 outputs
W4 = tf.get_variable("W4", shape=[128 * 4 * 4, 625],
initializer=tf.contrib.layers.xavier_initializer())
b4 = tf.Variable(tf.random_normal([625]))
L4 = tf.nn.relu(tf.matmul(L3, W4) + b4)
L4 = tf.nn.dropout(L4, keep_prob=keep_prob)
'''
Tensor("Relu_3:0", shape=(?, 625), dtype=float32)
Tensor("dropout_3/mul:0", shape=(?, 625), dtype=float32)
'''
# L5 Final FC 625 inputs -> 10 outputs
W5 = tf.get_variable("W5", shape=[625, 10],
initializer=tf.contrib.layers.xavier_initializer())
b5 = tf.Variable(tf.random_normal([10]))
hypothesis = tf.matmul(L4, W5) + b5
'''
Tensor("add_1:0", shape=(?, 10), dtype=float32)
'''
# define cost/loss & optimizer
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(
logits=hypothesis, labels=Y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
last_epoch = tf.Variable(0, name='last_epoch')
# initialize
#config = tf.ConfigProto(device_count = {'GPU': 0})
sess = tf.Session()
sess.run(tf.global_variables_initializer())
# Saver and Restore
saver = tf.train.Saver()
checkpoint = tf.train.get_checkpoint_state(CHECK_POINT_DIR)
if checkpoint and checkpoint.model_checkpoint_path:
try:
saver.restore(sess, checkpoint.model_checkpoint_path)
print("Successfully loaded:", checkpoint.model_checkpoint_path)
except:
print("Error on loading old network weights")
else:
print("Could not find old network weights")
start_from = sess.run(last_epoch)
if __name__ == "__main__":
# train my model
print('Start learning from:', start_from)
for epoch in range(training_epochs):
c, _, = sess.run([cost, optimizer], feed_dict={X: x, Y: y, keep_prob: 0.7})
if(epoch % 100 == 0):
print('Epoch:', '%04d' % (epoch + 1), 'cost =', '{:.9f}'.format(c))
if(epoch % 1000 == 0):
print("Saving network...")
sess.run(last_epoch.assign(epoch + 1))
if not os.path.exists(CHECK_POINT_DIR):
os.makedirs(CHECK_POINT_DIR)
saver.save(sess, CHECK_POINT_DIR + "/model", global_step=i)
print('Learning Finished!')
def mnist_predict(image):
x = image.reshape(1, 784)
return sess.run(tf.argmax(hypothesis, 1), feed_dict={X: x, keep_prob: 1})[0]
|
[
"tensorflow.contrib.layers.xavier_initializer",
"tensorflow.reshape",
"os.walk",
"numpy.shape",
"tensorflow.matmul",
"tensorflow.Variable",
"tensorflow.nn.conv2d",
"tensorflow.nn.relu",
"os.path.exists",
"tensorflow.set_random_seed",
"tensorflow.nn.softmax_cross_entropy_with_logits_v2",
"tensorflow.placeholder",
"tensorflow.train.get_checkpoint_state",
"tensorflow.train.Saver",
"tensorflow.global_variables_initializer",
"tensorflow.Session",
"tensorflow.nn.max_pool",
"tensorflow.random_normal",
"os.makedirs",
"tensorflow.argmax",
"cv2.threshold",
"numpy.zeros",
"numpy.array",
"tensorflow.train.AdamOptimizer",
"tensorflow.nn.dropout"
] |
[((264, 287), 'tensorflow.set_random_seed', 'tf.set_random_seed', (['(777)'], {}), '(777)\n', (282, 287), True, 'import tensorflow as tf\n'), ((1447, 1473), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {}), '(tf.float32)\n', (1461, 1473), True, 'import tensorflow as tf\n'), ((1501, 1540), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, 784]'], {}), '(tf.float32, [None, 784])\n', (1515, 1540), True, 'import tensorflow as tf\n'), ((1549, 1579), 'tensorflow.reshape', 'tf.reshape', (['X', '[-1, 28, 28, 1]'], {}), '(X, [-1, 28, 28, 1])\n', (1559, 1579), True, 'import tensorflow as tf\n'), ((1614, 1652), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, 10]'], {}), '(tf.float32, [None, 10])\n', (1628, 1652), True, 'import tensorflow as tf\n'), ((1820, 1881), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (['X_img', 'W1'], {'strides': '[1, 1, 1, 1]', 'padding': '"""SAME"""'}), "(X_img, W1, strides=[1, 1, 1, 1], padding='SAME')\n", (1832, 1881), True, 'import tensorflow as tf\n'), ((1887, 1901), 'tensorflow.nn.relu', 'tf.nn.relu', (['L1'], {}), '(L1)\n', (1897, 1901), True, 'import tensorflow as tf\n'), ((1907, 1983), 'tensorflow.nn.max_pool', 'tf.nn.max_pool', (['L1'], {'ksize': '[1, 2, 2, 1]', 'strides': '[1, 2, 2, 1]', 'padding': '"""SAME"""'}), "(L1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')\n", (1921, 1983), True, 'import tensorflow as tf\n'), ((2009, 2047), 'tensorflow.nn.dropout', 'tf.nn.dropout', (['L1'], {'keep_prob': 'keep_prob'}), '(L1, keep_prob=keep_prob)\n', (2022, 2047), True, 'import tensorflow as tf\n'), ((2455, 2513), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (['L1', 'W2'], {'strides': '[1, 1, 1, 1]', 'padding': '"""SAME"""'}), "(L1, W2, strides=[1, 1, 1, 1], padding='SAME')\n", (2467, 2513), True, 'import tensorflow as tf\n'), ((2519, 2533), 'tensorflow.nn.relu', 'tf.nn.relu', (['L2'], {}), '(L2)\n', (2529, 2533), True, 'import tensorflow as tf\n'), ((2539, 2615), 'tensorflow.nn.max_pool', 'tf.nn.max_pool', (['L2'], {'ksize': '[1, 2, 2, 1]', 'strides': '[1, 2, 2, 1]', 'padding': '"""SAME"""'}), "(L2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')\n", (2553, 2615), True, 'import tensorflow as tf\n'), ((2641, 2679), 'tensorflow.nn.dropout', 'tf.nn.dropout', (['L2'], {'keep_prob': 'keep_prob'}), '(L2, keep_prob=keep_prob)\n', (2654, 2679), True, 'import tensorflow as tf\n'), ((3146, 3204), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (['L2', 'W3'], {'strides': '[1, 1, 1, 1]', 'padding': '"""SAME"""'}), "(L2, W3, strides=[1, 1, 1, 1], padding='SAME')\n", (3158, 3204), True, 'import tensorflow as tf\n'), ((3210, 3224), 'tensorflow.nn.relu', 'tf.nn.relu', (['L3'], {}), '(L3)\n', (3220, 3224), True, 'import tensorflow as tf\n'), ((3230, 3306), 'tensorflow.nn.max_pool', 'tf.nn.max_pool', (['L3'], {'ksize': '[1, 2, 2, 1]', 'strides': '[1, 2, 2, 1]', 'padding': '"""SAME"""'}), "(L3, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')\n", (3244, 3306), True, 'import tensorflow as tf\n'), ((3333, 3371), 'tensorflow.nn.dropout', 'tf.nn.dropout', (['L3'], {'keep_prob': 'keep_prob'}), '(L3, keep_prob=keep_prob)\n', (3346, 3371), True, 'import tensorflow as tf\n'), ((3377, 3410), 'tensorflow.reshape', 'tf.reshape', (['L3', '[-1, 128 * 4 * 4]'], {}), '(L3, [-1, 128 * 4 * 4])\n', (3387, 3410), True, 'import tensorflow as tf\n'), ((3961, 3999), 'tensorflow.nn.dropout', 'tf.nn.dropout', (['L4'], {'keep_prob': 'keep_prob'}), '(L4, keep_prob=keep_prob)\n', (3974, 3999), True, 'import tensorflow as tf\n'), ((4630, 4663), 'tensorflow.Variable', 'tf.Variable', (['(0)'], {'name': '"""last_epoch"""'}), "(0, name='last_epoch')\n", (4641, 4663), True, 'import tensorflow as tf\n'), ((4737, 4749), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (4747, 4749), True, 'import tensorflow as tf\n'), ((4823, 4839), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), '()\n', (4837, 4839), True, 'import tensorflow as tf\n'), ((4853, 4899), 'tensorflow.train.get_checkpoint_state', 'tf.train.get_checkpoint_state', (['CHECK_POINT_DIR'], {}), '(CHECK_POINT_DIR)\n', (4882, 4899), True, 'import tensorflow as tf\n'), ((549, 562), 'os.walk', 'os.walk', (['path'], {}), '(path)\n', (556, 562), False, 'import os\n'), ((699, 744), 'cv2.threshold', 'cv2.threshold', (['img', '(127)', '(1)', 'cv2.THRESH_BINARY'], {}), '(img, 127, 1, cv2.THRESH_BINARY)\n', (712, 744), False, 'import cv2\n'), ((756, 775), 'numpy.array', 'np.array', (['threshold'], {}), '(threshold)\n', (764, 775), True, 'import numpy as np\n'), ((1703, 1747), 'tensorflow.random_normal', 'tf.random_normal', (['[3, 3, 1, 32]'], {'stddev': '(0.01)'}), '([3, 3, 1, 32], stddev=0.01)\n', (1719, 1747), True, 'import tensorflow as tf\n'), ((2339, 2384), 'tensorflow.random_normal', 'tf.random_normal', (['[3, 3, 32, 64]'], {'stddev': '(0.01)'}), '([3, 3, 32, 64], stddev=0.01)\n', (2355, 2384), True, 'import tensorflow as tf\n'), ((2973, 3019), 'tensorflow.random_normal', 'tf.random_normal', (['[3, 3, 64, 128]'], {'stddev': '(0.01)'}), '([3, 3, 64, 128], stddev=0.01)\n', (2989, 3019), True, 'import tensorflow as tf\n'), ((3891, 3914), 'tensorflow.random_normal', 'tf.random_normal', (['[625]'], {}), '([625])\n', (3907, 3914), True, 'import tensorflow as tf\n'), ((4289, 4311), 'tensorflow.random_normal', 'tf.random_normal', (['[10]'], {}), '([10])\n', (4305, 4311), True, 'import tensorflow as tf\n'), ((4326, 4343), 'tensorflow.matmul', 'tf.matmul', (['L4', 'W5'], {}), '(L4, W5)\n', (4335, 4343), True, 'import tensorflow as tf\n'), ((4459, 4530), 'tensorflow.nn.softmax_cross_entropy_with_logits_v2', 'tf.nn.softmax_cross_entropy_with_logits_v2', ([], {'logits': 'hypothesis', 'labels': 'Y'}), '(logits=hypothesis, labels=Y)\n', (4501, 4530), True, 'import tensorflow as tf\n'), ((4759, 4792), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (4790, 4792), True, 'import tensorflow as tf\n'), ((1238, 1249), 'numpy.shape', 'np.shape', (['x'], {}), '(x)\n', (1246, 1249), True, 'import numpy as np\n'), ((1261, 1272), 'numpy.shape', 'np.shape', (['y'], {}), '(y)\n', (1269, 1272), True, 'import numpy as np\n'), ((3834, 3872), 'tensorflow.contrib.layers.xavier_initializer', 'tf.contrib.layers.xavier_initializer', ([], {}), '()\n', (3870, 3872), True, 'import tensorflow as tf\n'), ((3932, 3949), 'tensorflow.matmul', 'tf.matmul', (['L3', 'W4'], {}), '(L3, W4)\n', (3941, 3949), True, 'import tensorflow as tf\n'), ((4232, 4270), 'tensorflow.contrib.layers.xavier_initializer', 'tf.contrib.layers.xavier_initializer', ([], {}), '()\n', (4268, 4270), True, 'import tensorflow as tf\n'), ((4549, 4600), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', ([], {'learning_rate': 'learning_rate'}), '(learning_rate=learning_rate)\n', (4571, 4600), True, 'import tensorflow as tf\n'), ((1153, 1165), 'numpy.zeros', 'np.zeros', (['(10)'], {}), '(10)\n', (1161, 1165), True, 'import numpy as np\n'), ((5984, 6008), 'tensorflow.argmax', 'tf.argmax', (['hypothesis', '(1)'], {}), '(hypothesis, 1)\n', (5993, 6008), True, 'import tensorflow as tf\n'), ((5724, 5755), 'os.path.exists', 'os.path.exists', (['CHECK_POINT_DIR'], {}), '(CHECK_POINT_DIR)\n', (5738, 5755), False, 'import os\n'), ((5773, 5801), 'os.makedirs', 'os.makedirs', (['CHECK_POINT_DIR'], {}), '(CHECK_POINT_DIR)\n', (5784, 5801), False, 'import os\n')]
|
from all_net_def import *
import os
import numpy as np
import torch
from torch import nn
from torch.utils.data import Dataset, DataLoader
import t1_audio_process
np.set_printoptions(threshold=np.inf)
class AudioDataset_test(Dataset):
def __init__(self, csv_file, transform=None):
self.data = np.load(csv_file)
self.transform = transform
def __len__(self):
return len(self.data)
def __getitem__(self, idx):
if torch.is_tensor(idx):
idx = idx.tolist()
data = np.reshape(self.data[idx, 0:], (4, 40, 1))
data = torch.tensor(data)
data = data.type(torch.FloatTensor)
return data
def test_rcnet(model, test_iter, device):
result = []
model.eval()
for X in test_iter:
X = X.to(device)
output = model(X)
_, preds = torch.max(output, 1)
obj = preds[0].item()
result.append(obj)
return result
def main(test_pth='./dataset/task1/test'):
batch_size = 1
# load model
model = torch.load('t1_cnn.pth')
data_name = 't1_test_feats.npy'
t1_audio_process.test()
test_dataset = AudioDataset_test(data_name)
test_dataloader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
result_list = test_rcnet(model, test_dataloader, device) # 返回所有判断结果的list
# 制成字典
result_dict = {}
counter = 0
for file_name in os.listdir(test_pth): # 测试集各音频文件名
result_dict.update({file_name: result_list[counter]})
counter += 1
return result_dict
if __name__ == '__main__':
main()
|
[
"t1_audio_process.test",
"numpy.set_printoptions",
"numpy.load",
"torch.utils.data.DataLoader",
"torch.load",
"torch.max",
"numpy.reshape",
"torch.cuda.is_available",
"torch.is_tensor",
"os.listdir",
"torch.tensor"
] |
[((163, 200), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'threshold': 'np.inf'}), '(threshold=np.inf)\n', (182, 200), True, 'import numpy as np\n'), ((1029, 1053), 'torch.load', 'torch.load', (['"""t1_cnn.pth"""'], {}), "('t1_cnn.pth')\n", (1039, 1053), False, 'import torch\n'), ((1095, 1118), 't1_audio_process.test', 't1_audio_process.test', ([], {}), '()\n', (1116, 1118), False, 'import t1_audio_process\n'), ((1190, 1252), 'torch.utils.data.DataLoader', 'DataLoader', (['test_dataset'], {'batch_size': 'batch_size', 'shuffle': '(False)'}), '(test_dataset, batch_size=batch_size, shuffle=False)\n', (1200, 1252), False, 'from torch.utils.data import Dataset, DataLoader\n'), ((1475, 1495), 'os.listdir', 'os.listdir', (['test_pth'], {}), '(test_pth)\n', (1485, 1495), False, 'import os\n'), ((307, 324), 'numpy.load', 'np.load', (['csv_file'], {}), '(csv_file)\n', (314, 324), True, 'import numpy as np\n'), ((458, 478), 'torch.is_tensor', 'torch.is_tensor', (['idx'], {}), '(idx)\n', (473, 478), False, 'import torch\n'), ((527, 569), 'numpy.reshape', 'np.reshape', (['self.data[idx, 0:]', '(4, 40, 1)'], {}), '(self.data[idx, 0:], (4, 40, 1))\n', (537, 569), True, 'import numpy as np\n'), ((585, 603), 'torch.tensor', 'torch.tensor', (['data'], {}), '(data)\n', (597, 603), False, 'import torch\n'), ((840, 860), 'torch.max', 'torch.max', (['output', '(1)'], {}), '(output, 1)\n', (849, 860), False, 'import torch\n'), ((1289, 1314), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (1312, 1314), False, 'import torch\n')]
|
""" Usage:
load_pretrained_word_embeddings [--glove=GLOVE_FN]
"""
from docopt import docopt
import numpy as np
from word_index import Word_index
import logging
logging.basicConfig(level = logging.DEBUG)
import sys
sys.path.append("./common")
from symbols import UNK_INDEX, UNK_SYMBOL, UNK_VALUE
from keras.layers import Embedding, SpatialDropout1D, Lambda, Multiply, RepeatVector, Reshape
from keras import backend as K
from keras_bert import load_trained_model_from_checkpoint
import codecs
import tokenization as bert_tokenization
class BertEmb:
'''
provide the same interface as Glove
'''
def __init__(self, bert_config_path, bert_checkpoint_path, bert_dict_path):
self.bert_config_path = bert_config_path
self.bert_checkpoint_path = bert_checkpoint_path
logging.debug('loading bert from {} ...'.format(bert_config_path))
self.model = load_trained_model_from_checkpoint(
bert_config_path, bert_checkpoint_path)
self._load_vocab(bert_dict_path)
logging.debug('done!')
self.tokenizer = bert_tokenization.FullTokenizer(
vocab_file=bert_dict_path, do_lower_case=True)
self.unk_count = 0
self.total_count = 0
self.unk_words = {} # word -> count
def _load_vocab(self, bert_dict_path):
self.word_index = {} # bert has [UNK] so we don't need define it
with codecs.open(bert_dict_path, 'r', 'utf8') as reader:
for line in reader:
token = line.strip()
self.word_index[token] = len(self.word_index)
def tokenize(self, tokens):
'''
tokenize token sequence using bert tokenizer
'''
bert_tokens = []
bert_mask = [] # the last token of the original token is 1, others are 0
for orig_token in tokens:
new_tokens = self.tokenizer.tokenize(orig_token)
bert_tokens.extend(new_tokens)
bert_mask.extend([0] * (len(new_tokens) - 1))
bert_mask.append(1)
return bert_tokens, bert_mask
def get_word_index(self, word, lower=True):
if lower:
word = word.lower()
if word not in self.word_index:
self.unk_count += 1
if word not in self.unk_words:
self.unk_words[word] = 0
self.unk_words[word] += 1
self.total_count += 1
return self.word_index[word] \
if (word in self.word_index) else self.word_index['[UNK]']
def get_keras_embedding(self, dropout=0, trainable=False, **kwargs):
# TODO: trainable is not used
def crop(dimension, start, end):
# Crops (or slices) a Tensor on a given dimension from start to end
# example : to crop tensor x[:, :, 5:10]
# call slice(2, 5, 10) as you want to crop on the second dimension
def func(x):
if dimension == 0:
return x[start: end]
if dimension == 1:
return x[:, start: end]
if dimension == 2:
return x[:, :, start: end]
if dimension == 3:
return x[:, :, :, start: end]
if dimension == 4:
return x[:, :, :, :, start: end]
return Lambda(func)
def emb(x):
self.bert_output = crop(1, 1, -1)(self.model(x))
return SpatialDropout1D(dropout)(self.bert_output)
return emb
#return lambda x: SpatialDropout1D(dropout)(crop(1, 1, -1)(self.model(x)))
def get_transformed_embedding(self, input_length, dropout=0):
def emb(x):
if not hasattr(self, 'bert_output'):
raise Exception('must run bert first')
cast_to_float32 = Lambda(lambda x: K.cast(x, 'float32'))
x = Multiply()([self.bert_output, cast_to_float32(Reshape((input_length, 1), input_shape=(input_length,))(x))])
mean_layer = Lambda(lambda x: K.mean(x, axis=1), output_shape=lambda in_shape: (in_shape[0],) + in_shape[2:])
x = mean_layer(x)
x = RepeatVector(input_length)(x)
#x = SpatialDropout1D(dropout)(x)
return x
return emb
class Glove:
"""
Stores pretrained word embeddings for GloVe, and
outputs a Keras Embeddings layer.
"""
def __init__(self, fn, dim = None):
"""
Load a GloVe pretrained embeddings model.
fn - Filename from which to load the embeddings
dim - Dimension of expected word embeddings, used as verficiation,
None avoids this check.
"""
self.fn = fn
self.dim = dim
logging.debug("Loading GloVe embeddings from: {} ...".format(self.fn))
self._load(self.fn)
logging.debug("Done!")
self.unk_count = 0
self.total_count = 0
self.unk_words = {} # word -> count
def _load(self, fn):
"""
Load glove embedding from a given filename
"""
self.word_index = {UNK_SYMBOL : UNK_INDEX}
emb = []
for line in open(fn):
values = line.split()
word = values[0]
coefs = np.asarray(values[1:], dtype='float32')
if self.dim:
assert(len(coefs) == self.dim)
else:
self.dim = len(coefs)
# Record mapping from word to index
self.word_index[word] = len(emb) + 1
emb.append(coefs)
# Add UNK at the first index in the table
self.emb = np.array([UNK_VALUE(self.dim)] + emb)
# Set the vobabulary size
self.vocab_size = len(self.emb)
def tokenize(self, tokens):
mask = [1] * len(tokens)
new_tokens = [token.lower() for token in tokens]
return new_tokens, mask
def get_word_index(self, word, lower = True):
"""
Get the index of a given word (int).
If word doesnt exists, returns UNK.
lower - controls whether the word should be lowered before checking map
"""
if lower:
word = word.lower()
if word not in self.word_index:
self.unk_count += 1
if word not in self.unk_words:
self.unk_words[word] = 0
self.unk_words[word] += 1
self.total_count += 1
return self.word_index[word] \
if (word in self.word_index) else UNK_INDEX
def get_embedding_matrix(self):
"""
Return an embedding matrix for use in a Keras Embeddding layer
https://blog.keras.io/using-pre-trained-word-embeddings-in-a-keras-model.html
word_index - Maps words in the dictionary to their index (one-hot encoding)
"""
return self.emb
def get_keras_embedding(self, **args):
"""
Get a Keras Embedding layer, loading this embedding as pretrained weights
The additional arguments given to this function are passed to the Keras Embbeding constructor.
"""
dp = 0 # no drop out
if 'dropout' in args:
dp = args['dropout']
del args['dropout']
emb = Embedding(self.vocab_size,self.dim, weights = [self.get_embedding_matrix()], **args)
return lambda x: SpatialDropout1D(dp)(emb(x))
'''
return Embedding(self.vocab_size,
self.dim,
weights = [self.get_embedding_matrix()],
**args)
'''
if __name__ == "__main__":
args = docopt(__doc__)
if args["--glove"] is not None:
glove_fn = args["--glove"]
g = Glove(glove_fn)
emb = g.get_keras_embedding()
else:
logging.info(__doc__)
exit
|
[
"sys.path.append",
"logging.debug",
"keras_bert.load_trained_model_from_checkpoint",
"logging.basicConfig",
"docopt.docopt",
"codecs.open",
"tokenization.FullTokenizer",
"numpy.asarray",
"keras.layers.SpatialDropout1D",
"logging.info",
"keras.layers.Lambda",
"keras.backend.mean",
"symbols.UNK_VALUE",
"keras.layers.Reshape",
"keras.layers.RepeatVector",
"keras.backend.cast",
"keras.layers.Multiply"
] |
[((165, 205), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.DEBUG'}), '(level=logging.DEBUG)\n', (184, 205), False, 'import logging\n'), ((219, 246), 'sys.path.append', 'sys.path.append', (['"""./common"""'], {}), "('./common')\n", (234, 246), False, 'import sys\n'), ((7553, 7568), 'docopt.docopt', 'docopt', (['__doc__'], {}), '(__doc__)\n', (7559, 7568), False, 'from docopt import docopt\n'), ((893, 967), 'keras_bert.load_trained_model_from_checkpoint', 'load_trained_model_from_checkpoint', (['bert_config_path', 'bert_checkpoint_path'], {}), '(bert_config_path, bert_checkpoint_path)\n', (927, 967), False, 'from keras_bert import load_trained_model_from_checkpoint\n'), ((1030, 1052), 'logging.debug', 'logging.debug', (['"""done!"""'], {}), "('done!')\n", (1043, 1052), False, 'import logging\n'), ((1078, 1156), 'tokenization.FullTokenizer', 'bert_tokenization.FullTokenizer', ([], {'vocab_file': 'bert_dict_path', 'do_lower_case': '(True)'}), '(vocab_file=bert_dict_path, do_lower_case=True)\n', (1109, 1156), True, 'import tokenization as bert_tokenization\n'), ((4807, 4829), 'logging.debug', 'logging.debug', (['"""Done!"""'], {}), "('Done!')\n", (4820, 4829), False, 'import logging\n'), ((7724, 7745), 'logging.info', 'logging.info', (['__doc__'], {}), '(__doc__)\n', (7736, 7745), False, 'import logging\n'), ((1400, 1440), 'codecs.open', 'codecs.open', (['bert_dict_path', '"""r"""', '"""utf8"""'], {}), "(bert_dict_path, 'r', 'utf8')\n", (1411, 1440), False, 'import codecs\n'), ((3317, 3329), 'keras.layers.Lambda', 'Lambda', (['func'], {}), '(func)\n', (3323, 3329), False, 'from keras.layers import Embedding, SpatialDropout1D, Lambda, Multiply, RepeatVector, Reshape\n'), ((5212, 5251), 'numpy.asarray', 'np.asarray', (['values[1:]'], {'dtype': '"""float32"""'}), "(values[1:], dtype='float32')\n", (5222, 5251), True, 'import numpy as np\n'), ((3430, 3455), 'keras.layers.SpatialDropout1D', 'SpatialDropout1D', (['dropout'], {}), '(dropout)\n', (3446, 3455), False, 'from keras.layers import Embedding, SpatialDropout1D, Lambda, Multiply, RepeatVector, Reshape\n'), ((3852, 3862), 'keras.layers.Multiply', 'Multiply', ([], {}), '()\n', (3860, 3862), False, 'from keras.layers import Embedding, SpatialDropout1D, Lambda, Multiply, RepeatVector, Reshape\n'), ((4128, 4154), 'keras.layers.RepeatVector', 'RepeatVector', (['input_length'], {}), '(input_length)\n', (4140, 4154), False, 'from keras.layers import Embedding, SpatialDropout1D, Lambda, Multiply, RepeatVector, Reshape\n'), ((7285, 7305), 'keras.layers.SpatialDropout1D', 'SpatialDropout1D', (['dp'], {}), '(dp)\n', (7301, 7305), False, 'from keras.layers import Embedding, SpatialDropout1D, Lambda, Multiply, RepeatVector, Reshape\n'), ((3814, 3834), 'keras.backend.cast', 'K.cast', (['x', '"""float32"""'], {}), "(x, 'float32')\n", (3820, 3834), True, 'from keras import backend as K\n'), ((4002, 4019), 'keras.backend.mean', 'K.mean', (['x'], {'axis': '(1)'}), '(x, axis=1)\n', (4008, 4019), True, 'from keras import backend as K\n'), ((5588, 5607), 'symbols.UNK_VALUE', 'UNK_VALUE', (['self.dim'], {}), '(self.dim)\n', (5597, 5607), False, 'from symbols import UNK_INDEX, UNK_SYMBOL, UNK_VALUE\n'), ((3898, 3953), 'keras.layers.Reshape', 'Reshape', (['(input_length, 1)'], {'input_shape': '(input_length,)'}), '((input_length, 1), input_shape=(input_length,))\n', (3905, 3953), False, 'from keras.layers import Embedding, SpatialDropout1D, Lambda, Multiply, RepeatVector, Reshape\n')]
|
from sensors.sensor import Sensor
from matplotlib import pyplot as plt
from PIL import Image
import numpy as np
import pygame
import io
class OverviewSensor(Sensor):
def __init__(self, **kwargs):
super(OverviewSensor, self).__init__(**kwargs)
self.name = 'overview'
def get_sensory_input(self, env):
height = env.height
width = env.width
data = pygame.image.tostring(env.screen, 'RGB')
pil_image = Image.frombytes('RGB', (width, height), data)
image = np.asarray(pil_image.convert('RGB'))
if self.display:
self.update_display(env, image)
env.agent.state[self.name] = image
return image
def update_display(self, env, image):
# Since what this sensor sees is the overview of the 2D environment, it be already displayed
if not env.display:
height = env.height
width = env.width
if self.figure is None:
self.matrix = np.zeros((height, width, 3))
plt.figure()
self.figure = plt.imshow(self.matrix, interpolation=None)
plt.show(block=False)
self.matrix = image / 255
self.figure.set_data(self.matrix)
plt.draw()
def shape(self, env):
return env.width, env.height, 3
|
[
"matplotlib.pyplot.show",
"matplotlib.pyplot.imshow",
"numpy.zeros",
"pygame.image.tostring",
"matplotlib.pyplot.draw",
"matplotlib.pyplot.figure",
"PIL.Image.frombytes"
] |
[((398, 438), 'pygame.image.tostring', 'pygame.image.tostring', (['env.screen', '"""RGB"""'], {}), "(env.screen, 'RGB')\n", (419, 438), False, 'import pygame\n'), ((459, 504), 'PIL.Image.frombytes', 'Image.frombytes', (['"""RGB"""', '(width, height)', 'data'], {}), "('RGB', (width, height), data)\n", (474, 504), False, 'from PIL import Image\n'), ((1263, 1273), 'matplotlib.pyplot.draw', 'plt.draw', ([], {}), '()\n', (1271, 1273), True, 'from matplotlib import pyplot as plt\n'), ((996, 1024), 'numpy.zeros', 'np.zeros', (['(height, width, 3)'], {}), '((height, width, 3))\n', (1004, 1024), True, 'import numpy as np\n'), ((1041, 1053), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1051, 1053), True, 'from matplotlib import pyplot as plt\n'), ((1084, 1127), 'matplotlib.pyplot.imshow', 'plt.imshow', (['self.matrix'], {'interpolation': 'None'}), '(self.matrix, interpolation=None)\n', (1094, 1127), True, 'from matplotlib import pyplot as plt\n'), ((1144, 1165), 'matplotlib.pyplot.show', 'plt.show', ([], {'block': '(False)'}), '(block=False)\n', (1152, 1165), True, 'from matplotlib import pyplot as plt\n')]
|
import numpy as np
from matplotlib import pyplot as plt
from ..Xfit.MCMC_straight_line import mcmc_sl
from ..Xfit.fit_basic import fit_basic
from ..Xfit.FitPoissonGamma import fit_pg
from ..Xplot.niceplot import niceplot
from matplotlib.offsetbox import AnchoredText
from matplotlib import ticker
from ..misc.running_mean import running_mean
from ..misc.resample import resample
from matplotlib.colors import LogNorm
from matplotlib import ticker
def rebin_array(arr, maxlen=500):
"""rebin array and reduce its length to maxlen for generating plots
"""
l = arr.shape
if l[0] > maxlen:
arr = arr[:-(l[0]%maxlen)]
arr = arr.reshape(maxlen, -1, *l[1:])
arr = arr.mean(1)
return arr
def plot_contrast_vs_images(x, y, ax, label=None, marker='o', color='b', ind_avr=False, alpha=0.5):
"""
"""
ax.plot(x, y, ms=3, label=label, linestyle='', marker=marker, color=color, alpha=alpha)
ax.set_xlabel('image number')
ax.set_ylabel(r'$\beta$')
if ind_avr:
arrow(x.max(), y.mean(), ax, color)
return True
def plot_contrast_histogram(x, ax, label=None, color='b', ind_avr=False):
"""
"""
ax.hist(x, bins=100, density=True, histtype='step', label=label, color=color,)
ax.set_xlabel(r'$\beta$')
ax.set_ylabel(r'$P(\beta)$')
if ind_avr:
xx = np.ones(2)*x.mean()
h = np.histogram(x, bins=100, density=True)
de = np.diff(h[1][:2])/2
e = h[1][:-1] + de
ymax = h[0][np.argmin(np.abs(xx[0]-h[1]+0.5*np.mean(np.diff(h[1]))))]
yy = np.array([0,ymax])
ax.plot(xx,yy,'--', color=color)
return True
def plot_contrast_running_average(x, y, dy, ax, label=None, marker='o', color='b', ind_avr=False, alpha=0.5):
"""
"""
ax.errorbar(x, y, dy, ms=3, label=label, fmt=marker, color=color, alpha=alpha)
ax.set_xlabel('image number')
ax.set_ylabel(r'$\beta$ (run. avr.)')
return True
def plot_kbar_vs_images(x, y, ax, label=None, marker='o', color='b', npix=False, ind_avr=False, alpha=0.5):
"""
"""
if npix:
y = y * npix
ylab = r'$k_{tot}$'
else:
ylab = r'$\langle k\rangle$'
ax.plot(x, y, label=label, linestyle='', markersize=3, marker=marker, color=color, alpha=alpha)
ax.set_xlabel('image number')
ax.set_ylabel(ylab)
ax.set_yscale('log')
if ind_avr:
arrow(x.max(), y.mean(), ax, color)
return True
def plot_poisson_gamma(x, y, dy, ax, label=None, marker='o', color='b', ind_avr=False):
"""
"""
ax.errorbar(x, y, yerr=dy, label=label, ms=3, ls='', marker=marker, color=color)
ax.set_xlabel('k')
ax.set_ylabel(r'$P(k)$')
ax.set_yscale('log')
return True
def plot_contrast_kbar_correlation(x, y, ax, label=None, cmap='inferno', npix=False, ind_avr=False, alpha=0.5):
"""
"""
if npix:
x = x * npix
xlab = r'$k_{tot}$'
else:
xlab = r'$\langle k\rangle$'
ax.hist2d(x, y, bins=50, density=True, norm=LogNorm(), cmap=cmap, label=label, alpha=alpha)
ax.set_xlabel(xlab)
ax.set_ylabel(r'$\beta$')
return True
def plot_contrast_vs_kbar(x, y, ax, label=None, marker='o', color='b', npix=False, ind_avr=False, alpha=0.5):
"""
"""
if npix:
x = x * npix
xlab = r'$k_{tot}$'
else:
xlab = r'$\langle k\rangle$'
ax.plot(x, y, linestyle='', marker=marker, markersize=2, color=color, label=label, alpha=alpha)
ax.set_xlabel(xlab)
ax.set_ylabel(r'$\beta$')
return True
def plot_prob_vs_kbar(x, y, ax, probk, label=None, marker='o', color='b', npix=False, ind_avr=False, alpha=0.5):
"""
"""
if npix:
x = x * npix
y = y * npix
xlab = r'$k_{tot}$'
ylab = r'n(%d)' % probk
else:
ylab = r'P(%d)' % probk
xlab = r'$\langle k\rangle$'
ax.plot(x, y, linestyle='', marker=marker, markersize=2, color=color, label=label, alpha=alpha)
ax.set_xlabel(xlab)
ax.set_ylabel(ylab)
return True
def arrow(x, y, ax, color):
c1 = (x,y)
c2 = (x*1.1,y)
arprp = dict(arrowstyle="-|>", connectionstyle='arc3', color=color,)
ax.annotate("", xy=c1, xycoords='data', xytext=c2, textcoords='data', arrowprops=arprp)
def plot_quicklook(obj, plot, idx, nq, ax=None, c0=0, ratio=0, maxlen=500, format_ticks=False,
ind_avr=True, lfs=10, total_counts=False, return_respfnc=False, probk=2,
fit_pg=True, alpha=0.5, **kwargs):
"""Plot quick overview of speckle contrast, mean photon counts and Probability Distribution
"""
contrast = obj.contrast[0][idx]
prob = obj.prob[0][idx][1:,1:]
for i,j in enumerate(nq):
ci = i + c0*len(nq) # index for colors and markers
color = obj.colors[ci]
marker = obj.markers[idx%len(obj.markers)]
if total_counts:
npix = obj.Xana.setup['gproi'][j]
else:
npix = False
if i == 0:
labstr = 't_exp: {:.2e}s'.format(obj.t_exposure[idx])
else:
labstr = None
b = contrast[j,ratio+1]
xv_b = np.where(~b.mask)[0]
x_b = rebin_array(xv_b, maxlen)
br = rebin_array(b[xv_b], maxlen)
bt = running_mean(b[xv_b])
bt = rebin_array(bt, maxlen)
kb = contrast[j,0]
xv_kb = np.where(~kb.mask)[0]
kb = rebin_array(kb[xv_b], maxlen)
p = prob[j,probk+1][xv_b]
pp = np.mean(prob[j,1:],-1)
ind = np.where(pp)[0]
dpp = np.std(prob[j,1:],-1)
k = np.arange(pp.size)
if plot == 'bvi':
labmean = '%.2f' % br.mean()
plot_contrast_vs_images(x_b, br, ax, labmean, marker, color, ind_avr, alpha)
elif plot == 'pbb':
plot_contrast_histogram(b[~b.mask], ax, labstr, color, ind_avr)
elif plot == 'brvi':
plot_contrast_running_average(x_b, bt[:,0], bt[:,1], ax, labstr, marker, color, alpha)
elif plot == 'kbvi':
labmean = '%.3g' % kb.mean()
plot_kbar_vs_images(x_b, kb, ax, labmean, marker, color, npix, ind_avr, alpha)
elif plot == 'bvkb':
plot_contrast_vs_kbar(kb, br, ax, labstr, marker, color, npix, alpha)
elif plot == 'pbk':
plot_poisson_gamma(k[ind], pp[ind], dpp[ind], ax, labstr, marker, color)
# if fit_pg:
# pb_pg = np.hstack((np.zeros(k[ind].size)))
# fitpg()
elif plot == 'pkvkb':
plot_prob_vs_kbar(kb, p, ax, probk, labstr, marker, color, npix, alpha)
if ind_avr:
ax.legend(loc='best')
niceplot(ax, autoscale=True, grid=False, lfs=lfs)
# def plot_poisson_gamma(obj, idx, nq, dofit=True):
# """Show the photon statistics by plotting the Poisson-Gamma distribution
# """
# if data == 'original' or self.corrFuncRescaled is None:
# corrFunc = list(self.corrFunc)
# elif data == 'rescaled':
# corrFunc = list(self.corrFuncRescaled)
# else:
# raise ValueError('No usable correlation data defined.')
# if nq is None:
# pass
# elif type(nq) == int:
# self.nq = np.arange(nq)
# else:
# self.nq = nq
# if color_mode == 0:
# color_multiplier, color_repeater = self.nq.size, len(corrFunc)
# elif color_mode == 1:
# color_multiplier, color_repeater = self.nq.size*len(corrFunc), 1
# self.update_colors(cmap, color_multiplier, color_repeater)
# self.update_markers( len(corrFunc), change_marker)
# self.g2plotl = [[]] * len(corrFunc)
# self.pars = [[]] * len(corrFunc)
# self.fit_result = [[[] for i in range(self.nq.size)]] * len(corrFunc) # possible bug: will cause
# # wrong references
# ci = 0
# for j, (cfi, dcfi) in enumerate(corrFunc):
# rates = np.zeros((self.nq.size, 3*nmodes+3, 2))
# ti = cfi[1:,0]
# for i,qi in enumerate(self.nq):
# if i == 0:
# cf_id = self.db_id[j]
# else:
# cf_id = None
# res = fitg2(ti, cfi[1:,qi+1], err=dcfi[1:,qi+1], qv=self.Xana.setup['qv'][qi],
# ax=ax, color=self.colors[ci], dofit=True,
# marker=self.markers[j%len(self.markers)], cf_id=cf_id,
# modes=nmodes, **kwargs)
# self.fit_result[j][i] = res[2:4]
# self.g2plotl[j].append(list(itertools.chain.from_iterable(res[4])))
# if dofit:
# if i == 0:
# db_tmp = self.init_pars(list(res[2].params.keys()))
# entry = [cfi[0,qi+1], *res[0].flatten(), *res[1]]
# db_tmp.loc[i] = entry
# else:
# db_tmp = 0
# ci += 1
# self.pars[j] = db_tmp
# plt.tight_layout()
# for j,ei in zip(tind,extf[tind]):
# nn = np.ceil(len(roi_list)/2)
# f, ax = plt.subplots(int(nn), 2, figsize=(9,nn*4))
# f.suptitle('exposure time = {:.2g}s'.format(ei))
# ax = ax.ravel()
# for l,roii in enumerate(roi_list):
# kv, kb, dkb, pba, dpba = selectdata(xsvs, ei, t_int=ext, dxsvs=xsvs_err, roi_idx=roii, **psel)
# out = fpg.fitpg_iterative(kb, pba, kv, pberr=1/pba, **pfit)
# M[roii,0,:] = qv[roii]
# M[roii,j+1,:3] = (out[0],out[1],np.mean(out[2]))
# plotpoissongamma(out[2], pba, kv, out[0], dkb, dpba*0, out[1],
# confint=(1/np.mean(cnorm[roii+2,np.where(cnorm[0,1:]==ei)]),),
# q=qv[roii], ax=ax[l], cmap='Set1',**pfit)
# if doplot:
# plt.tight_layout()
|
[
"numpy.std",
"numpy.ones",
"numpy.histogram",
"numpy.mean",
"numpy.array",
"numpy.arange",
"numpy.diff",
"matplotlib.colors.LogNorm",
"numpy.where"
] |
[((1376, 1415), 'numpy.histogram', 'np.histogram', (['x'], {'bins': '(100)', 'density': '(True)'}), '(x, bins=100, density=True)\n', (1388, 1415), True, 'import numpy as np\n'), ((1567, 1586), 'numpy.array', 'np.array', (['[0, ymax]'], {}), '([0, ymax])\n', (1575, 1586), True, 'import numpy as np\n'), ((5477, 5501), 'numpy.mean', 'np.mean', (['prob[j, 1:]', '(-1)'], {}), '(prob[j, 1:], -1)\n', (5484, 5501), True, 'import numpy as np\n'), ((5544, 5567), 'numpy.std', 'np.std', (['prob[j, 1:]', '(-1)'], {}), '(prob[j, 1:], -1)\n', (5550, 5567), True, 'import numpy as np\n'), ((5578, 5596), 'numpy.arange', 'np.arange', (['pp.size'], {}), '(pp.size)\n', (5587, 5596), True, 'import numpy as np\n'), ((1344, 1354), 'numpy.ones', 'np.ones', (['(2)'], {}), '(2)\n', (1351, 1354), True, 'import numpy as np\n'), ((1429, 1446), 'numpy.diff', 'np.diff', (['h[1][:2]'], {}), '(h[1][:2])\n', (1436, 1446), True, 'import numpy as np\n'), ((3007, 3016), 'matplotlib.colors.LogNorm', 'LogNorm', ([], {}), '()\n', (3014, 3016), False, 'from matplotlib.colors import LogNorm\n'), ((5144, 5161), 'numpy.where', 'np.where', (['(~b.mask)'], {}), '(~b.mask)\n', (5152, 5161), True, 'import numpy as np\n'), ((5364, 5382), 'numpy.where', 'np.where', (['(~kb.mask)'], {}), '(~kb.mask)\n', (5372, 5382), True, 'import numpy as np\n'), ((5514, 5526), 'numpy.where', 'np.where', (['pp'], {}), '(pp)\n', (5522, 5526), True, 'import numpy as np\n'), ((1536, 1549), 'numpy.diff', 'np.diff', (['h[1]'], {}), '(h[1])\n', (1543, 1549), True, 'import numpy as np\n')]
|
from typing import Optional
import numpy as np
from xarray import Dataset
from .api import create_genotype_call_dataset
from .utils import split_array_chunks
def simulate_genotype_call_dataset(
n_variant: int,
n_sample: int,
n_ploidy: int = 2,
n_allele: int = 2,
n_contig: int = 1,
seed: Optional[int] = None,
) -> Dataset:
"""Simulate genotype calls and variant/sample data.
Note that the data simulated by this function has no
biological interpretation and that summary statistics
or other methods applied to it will produce meaningless
results. This function is primarily a convenience on
generating `Dataset` containers so quantities of interest
should be overwritten, where appropriate, within the
context of a more specific application.
Parameters
----------
n_variant : int
Number of variants to simulate
n_sample : int
Number of samples to simulate
n_ploidy : int
Number of chromosome copies in each sample
n_allele: int
Number of alleles to simulate
n_contig : int, optional
Number of contigs to partition variants with,
controlling values in `variant_contig`. Values
will all be 0 by default with `n_contig` == 1.
seed : int, optional
Seed for random number generation
Returns
-------
Dataset
Dataset from `sgkit.create_genotype_call_dataset`.
"""
rs = np.random.RandomState(seed=seed)
call_genotype = rs.randint(
0, n_allele, size=(n_variant, n_sample, n_ploidy), dtype=np.int8
)
contig_size = split_array_chunks(n_variant, n_contig)
contig = np.repeat(np.arange(n_contig), contig_size)
contig_names = np.unique(contig)
position = np.concatenate([np.arange(contig_size[i]) for i in range(n_contig)])
assert position.size == contig.size
alleles = rs.choice(["A", "C", "G", "T"], size=(n_variant, n_allele)).astype("S")
sample_id = np.array([f"S{i}" for i in range(n_sample)])
return create_genotype_call_dataset(
variant_contig_names=list(contig_names),
variant_contig=contig,
variant_position=position,
variant_alleles=alleles,
sample_id=sample_id,
call_genotype=call_genotype,
)
|
[
"numpy.unique",
"numpy.arange",
"numpy.random.RandomState"
] |
[((1451, 1483), 'numpy.random.RandomState', 'np.random.RandomState', ([], {'seed': 'seed'}), '(seed=seed)\n', (1472, 1483), True, 'import numpy as np\n'), ((1729, 1746), 'numpy.unique', 'np.unique', (['contig'], {}), '(contig)\n', (1738, 1746), True, 'import numpy as np\n'), ((1676, 1695), 'numpy.arange', 'np.arange', (['n_contig'], {}), '(n_contig)\n', (1685, 1695), True, 'import numpy as np\n'), ((1778, 1803), 'numpy.arange', 'np.arange', (['contig_size[i]'], {}), '(contig_size[i])\n', (1787, 1803), True, 'import numpy as np\n')]
|
import numpy as np
import input_data
from sklearn.utils import shuffle
np.random.seed(9999)
mnist = input_data.read_data_sets('../MNIST_data', one_hot=True)
X_train = mnist.train.images
t_train = mnist.train.labels
X_test = mnist.test.images
t_test = mnist.test.labels
X_train, t_train = shuffle(X_train, t_train)
# Model
W1 = np.random.randn(784, 100) * 0.01
W2 = np.random.randn(100, 10) * 0.01
def softmax(x):
ex = np.exp(x - np.max(x, axis=1)[:, None])
return ex / ex.sum(axis=1)[:, None]
def NLL(z, t):
return -np.mean(np.sum(t*np.log(softmax(z) + eps), axis=1))
m = 200 # mb size
alpha = 0.001
rho1 = 0.9 # Decay for F
rho2 = 0.999 # Momentum
s1 = np.zeros_like(W1)
r1 = np.zeros_like(W1)
s2 = np.zeros_like(W2)
r2 = np.zeros_like(W2)
eps = 1e-8
# Visualization stuffs
losses = []
# Training
for i in range(1, 5000):
X_mb, t_mb = mnist.train.next_batch(m)
t_mb_idx = t_mb.argmax(axis=1)
# Forward
a = X_mb @ W1
h = np.maximum(a, 0)
z = h @ W2
loss = NLL(z, t_mb)
# Loss
if (i-1) % 100 == 0:
print(f'Iter-{i}; Loss: {loss:.3f}')
losses.append(loss if i == 1 else 0.99*losses[-1] + 0.01*loss)
m = z.shape[0]
# Gradients
dz = softmax(z)
dz[range(dz.shape[0]), t_mb_idx] -= 1 # m*10
dz /= m
dW2 = h.T @ dz # 100*10
dh = dz @ W2.T # m*100
dh[a < 0] = 0 # ReLU
dW1 = X_mb.T @ dh # 784*100
# Moments
s1 = rho1*s1 + (1-rho1)*dW1
r1 = rho2*r1 + (1-rho2)*(dW1*dW1)
s2 = rho1*s2 + (1-rho1)*dW2
r2 = rho2*r2 + (1-rho2)*(dW2*dW2)
# r = rho2*r + (1-rho2)*(m*g*g) # Corresponds to diagonal approx. of FIM
# Bias correction
s1_ = s1/(1-rho1**i)
r1_ = r1/(1-rho2**i)
s2_ = s2/(1-rho1**i)
r2_ = r2/(1-rho2**i)
# Step
delta1 = s1_ / (np.sqrt(r1_) + eps)
delta2 = s2_ / (np.sqrt(r2_) + eps)
# delta = s_ / (r_ + eps) # Inverse of diagonal FIM
# W = W - alpha * g # SGD update
W1 = W1 - alpha * delta1
W2 = W2 - alpha * delta2
y = softmax(np.maximum(X_test @ W1, 0) @ W2).argmax(axis=1)
acc = np.mean(y == t_test.argmax(axis=1))
print(f'Accuracy: {acc:.3f}')
np.save('adam_losses.npy', losses)
|
[
"input_data.read_data_sets",
"numpy.save",
"numpy.zeros_like",
"numpy.random.seed",
"numpy.maximum",
"numpy.random.randn",
"numpy.max",
"sklearn.utils.shuffle",
"numpy.sqrt"
] |
[((73, 93), 'numpy.random.seed', 'np.random.seed', (['(9999)'], {}), '(9999)\n', (87, 93), True, 'import numpy as np\n'), ((103, 159), 'input_data.read_data_sets', 'input_data.read_data_sets', (['"""../MNIST_data"""'], {'one_hot': '(True)'}), "('../MNIST_data', one_hot=True)\n", (128, 159), False, 'import input_data\n'), ((294, 319), 'sklearn.utils.shuffle', 'shuffle', (['X_train', 't_train'], {}), '(X_train, t_train)\n', (301, 319), False, 'from sklearn.utils import shuffle\n'), ((682, 699), 'numpy.zeros_like', 'np.zeros_like', (['W1'], {}), '(W1)\n', (695, 699), True, 'import numpy as np\n'), ((705, 722), 'numpy.zeros_like', 'np.zeros_like', (['W1'], {}), '(W1)\n', (718, 722), True, 'import numpy as np\n'), ((728, 745), 'numpy.zeros_like', 'np.zeros_like', (['W2'], {}), '(W2)\n', (741, 745), True, 'import numpy as np\n'), ((751, 768), 'numpy.zeros_like', 'np.zeros_like', (['W2'], {}), '(W2)\n', (764, 768), True, 'import numpy as np\n'), ((2151, 2185), 'numpy.save', 'np.save', (['"""adam_losses.npy"""', 'losses'], {}), "('adam_losses.npy', losses)\n", (2158, 2185), True, 'import numpy as np\n'), ((334, 359), 'numpy.random.randn', 'np.random.randn', (['(784)', '(100)'], {}), '(784, 100)\n', (349, 359), True, 'import numpy as np\n'), ((372, 396), 'numpy.random.randn', 'np.random.randn', (['(100)', '(10)'], {}), '(100, 10)\n', (387, 396), True, 'import numpy as np\n'), ((972, 988), 'numpy.maximum', 'np.maximum', (['a', '(0)'], {}), '(a, 0)\n', (982, 988), True, 'import numpy as np\n'), ((1802, 1814), 'numpy.sqrt', 'np.sqrt', (['r1_'], {}), '(r1_)\n', (1809, 1814), True, 'import numpy as np\n'), ((1842, 1854), 'numpy.sqrt', 'np.sqrt', (['r2_'], {}), '(r2_)\n', (1849, 1854), True, 'import numpy as np\n'), ((442, 459), 'numpy.max', 'np.max', (['x'], {'axis': '(1)'}), '(x, axis=1)\n', (448, 459), True, 'import numpy as np\n'), ((2030, 2056), 'numpy.maximum', 'np.maximum', (['(X_test @ W1)', '(0)'], {}), '(X_test @ W1, 0)\n', (2040, 2056), True, 'import numpy as np\n')]
|
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.collections import LineCollection
from koala import graph_color, plotting
from koala import graph_color
def rotate(vector, angle):
rm = np.array([
[np.cos(angle), -np.sin(angle)],
[np.sin(angle), np.cos(angle)]
])
return rm @ vector
def create_peterson_graph():
"""
Returns a peterson graph, one of the simplest (but non-planar) cubic graphs that is not three-colorable.
Returns:
vertices: np.array shape (nvertices, ndim) - A list of the positions of all the vertices that make up the graph
adjacency: np.array shape (nedges, 2) - A list of all edges in the graph, containing the indices of connected vertices
"""
points_outer = np.tile(np.array([0, 0.45]), (5, 1))
points_inner = np.tile(np.array([0, 0.27]), (5, 1))
angles = np.linspace(0, 2*np.pi, 5, endpoint=False)
for n, a in enumerate(angles):
points_outer[n, :] = rotate(points_outer[n, :], a)
points_inner[n, :] = rotate(points_inner[n, :], a)
vertices = np.concatenate((points_outer, points_inner))
vertices += 0.5
outer_ring_adj = np.concatenate((np.arange(0, 5), np.roll(
np.arange(0, 5), -1))).reshape((-1, 2), order='F')
between_ring_adj = np.concatenate((np.arange(0, 5),
np.arange(5, 10))).reshape((-1, 2), order='F')
inner_ring_adj = np.concatenate((np.arange(5, 10), np.roll(
np.arange(5, 10), -2))).reshape((-1, 2), order='F')
adjacency = np.concatenate(
(outer_ring_adj, between_ring_adj, inner_ring_adj))
return vertices, adjacency
def create_tutte_graph():
"""
Returns a tutte graph, a cubic graph with no Hamiltonian cycle, but is three-colorable.
Returns:
vertices: np.array shape (nvertices, ndim) - A list of the positions of all the vertices that make up the graph
adjacency: np.array shape (nedges, 2) - A list of all edges in the graph, containing the indices of connected vertices
"""
vertices = np.array([
[0.518, 0.586],
[0.294, 0.986],
[0.504, 0.99],
[0.69, 0.99],
[0.998, 0.616],
[0.872, 0.374],
[0.746, 0.152],
[0.024, 0.558],
[0.17, 0.382],
[0.334, 0.15],
[0.454, 0.54],
[0.518, 0.67],
[0.592, 0.53],
[0.35, 0.548],
[0.436, 0.484],
[0.342, 0.502],
[0.296, 0.478],
[0.336, 0.418],
[0.408, 0.404],
[0.332, 0.93],
[0.214, 0.502],
[0.138, 0.558],
[0.226, 0.43],
[0.282, 0.38],
[0.368, 0.272],
[0.394, 0.822],
[0.464, 0.732],
[0.638, 0.894],
[0.55, 0.734],
[0.696, 0.274],
[0.62, 0.482],
[0.658, 0.55],
[0.768, 0.568],
[0.906, 0.6],
[0.508, 0.774],
[0.674, 0.5],
[0.508, 0.83],
[0.728, 0.482],
[0.424, 0.864],
[0.556, 0.894],
[0.414, 0.922],
[0.506, 0.934],
[0.784, 0.506],
[0.842, 0.482],
[0.76, 0.376],
[0.824, 0.412]
])
avg_pos = np.sum(vertices, axis = 0)/vertices.shape[0]
vertices -= avg_pos - np.array([0.5,0.5])
adjacency = np.array([
[1 , 11],
[1 , 12],
[1 , 13],
[2 , 3],
[2 , 8],
[2 , 20],
[3 , 4],
[3 , 42],
[4 , 5],
[4 , 28],
[ 5 , 6],
[ 5 , 34],
[ 6 , 7],
[ 6 , 46],
[ 7 , 10],
[ 7 , 30],
[ 8 , 9],
[ 8 , 22],
[ 9 , 10],
[ 9 , 23],
[ 10 , 25],
[ 11 , 14],
[ 11 , 15],
[ 12 , 27],
[ 12 , 29],
[ 13 , 31],
[ 13 , 32],
[ 14 , 16],
[ 14 , 22],
[ 15 , 16],
[ 15 , 19],
[ 16 , 17],
[ 17 , 18],
[ 17 , 21],
[ 18 , 19],
[ 18 , 24],
[ 19 , 25],
[ 20 , 26],
[ 20 , 41],
[ 21 , 22],
[ 21 , 23],
[ 23 , 24],
[ 24 , 25],
[ 26 , 27],
[ 26 , 39],
[ 27 , 35],
[ 28 , 29],
[ 28 , 40],
[ 29 , 35],
[ 30 , 31],
[ 30 , 45],
[ 31 , 36],
[ 32 , 33],
[ 32 , 36],
[ 33 , 34],
[ 33 , 43],
[ 34 , 44],
[ 35 , 37],
[ 36 , 38],
[ 37 , 39],
[ 37 , 40],
[ 38 , 43],
[ 38 , 45],
[ 39 , 41],
[ 40 , 42],
[ 41 , 42],
[ 43 , 44],
[ 44 , 46],
[ 45 , 46]
])
adjacency -= 1
return vertices, adjacency
vertices, adjacency = create_tutte_graph()
#plotting.plot_lattice(vertices, adjacency, adjacency_crossing= np.zeros(adjacency.shape))
#plt.show()
out = graph_color.edge_color(adjacency, 3)
color_dict = {0: 'r', 1: 'y', 2: 'b'}
edgecolors = np.array([color_dict[c] for c in out])
plotting.plot_lattice(vertices, adjacency, adjacency_crossing=np.zeros(adjacency.shape), edge_colors=edgecolors)
plt.show()
|
[
"matplotlib.pyplot.show",
"numpy.sum",
"numpy.zeros",
"numpy.sin",
"numpy.array",
"numpy.arange",
"numpy.linspace",
"koala.graph_color.edge_color",
"numpy.cos",
"numpy.concatenate"
] |
[((4982, 5018), 'koala.graph_color.edge_color', 'graph_color.edge_color', (['adjacency', '(3)'], {}), '(adjacency, 3)\n', (5004, 5018), False, 'from koala import graph_color\n'), ((5070, 5108), 'numpy.array', 'np.array', (['[color_dict[c] for c in out]'], {}), '([color_dict[c] for c in out])\n', (5078, 5108), True, 'import numpy as np\n'), ((5222, 5232), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5230, 5232), True, 'from matplotlib import pyplot as plt\n'), ((878, 922), 'numpy.linspace', 'np.linspace', (['(0)', '(2 * np.pi)', '(5)'], {'endpoint': '(False)'}), '(0, 2 * np.pi, 5, endpoint=False)\n', (889, 922), True, 'import numpy as np\n'), ((1090, 1134), 'numpy.concatenate', 'np.concatenate', (['(points_outer, points_inner)'], {}), '((points_outer, points_inner))\n', (1104, 1134), True, 'import numpy as np\n'), ((1560, 1626), 'numpy.concatenate', 'np.concatenate', (['(outer_ring_adj, between_ring_adj, inner_ring_adj)'], {}), '((outer_ring_adj, between_ring_adj, inner_ring_adj))\n', (1574, 1626), True, 'import numpy as np\n'), ((2081, 2855), 'numpy.array', 'np.array', (['[[0.518, 0.586], [0.294, 0.986], [0.504, 0.99], [0.69, 0.99], [0.998, 0.616\n ], [0.872, 0.374], [0.746, 0.152], [0.024, 0.558], [0.17, 0.382], [\n 0.334, 0.15], [0.454, 0.54], [0.518, 0.67], [0.592, 0.53], [0.35, 0.548\n ], [0.436, 0.484], [0.342, 0.502], [0.296, 0.478], [0.336, 0.418], [\n 0.408, 0.404], [0.332, 0.93], [0.214, 0.502], [0.138, 0.558], [0.226, \n 0.43], [0.282, 0.38], [0.368, 0.272], [0.394, 0.822], [0.464, 0.732], [\n 0.638, 0.894], [0.55, 0.734], [0.696, 0.274], [0.62, 0.482], [0.658, \n 0.55], [0.768, 0.568], [0.906, 0.6], [0.508, 0.774], [0.674, 0.5], [\n 0.508, 0.83], [0.728, 0.482], [0.424, 0.864], [0.556, 0.894], [0.414, \n 0.922], [0.506, 0.934], [0.784, 0.506], [0.842, 0.482], [0.76, 0.376],\n [0.824, 0.412]]'], {}), '([[0.518, 0.586], [0.294, 0.986], [0.504, 0.99], [0.69, 0.99], [\n 0.998, 0.616], [0.872, 0.374], [0.746, 0.152], [0.024, 0.558], [0.17, \n 0.382], [0.334, 0.15], [0.454, 0.54], [0.518, 0.67], [0.592, 0.53], [\n 0.35, 0.548], [0.436, 0.484], [0.342, 0.502], [0.296, 0.478], [0.336, \n 0.418], [0.408, 0.404], [0.332, 0.93], [0.214, 0.502], [0.138, 0.558],\n [0.226, 0.43], [0.282, 0.38], [0.368, 0.272], [0.394, 0.822], [0.464, \n 0.732], [0.638, 0.894], [0.55, 0.734], [0.696, 0.274], [0.62, 0.482], [\n 0.658, 0.55], [0.768, 0.568], [0.906, 0.6], [0.508, 0.774], [0.674, 0.5\n ], [0.508, 0.83], [0.728, 0.482], [0.424, 0.864], [0.556, 0.894], [\n 0.414, 0.922], [0.506, 0.934], [0.784, 0.506], [0.842, 0.482], [0.76, \n 0.376], [0.824, 0.412]])\n', (2089, 2855), True, 'import numpy as np\n'), ((3348, 4065), 'numpy.array', 'np.array', (['[[1, 11], [1, 12], [1, 13], [2, 3], [2, 8], [2, 20], [3, 4], [3, 42], [4, 5\n ], [4, 28], [5, 6], [5, 34], [6, 7], [6, 46], [7, 10], [7, 30], [8, 9],\n [8, 22], [9, 10], [9, 23], [10, 25], [11, 14], [11, 15], [12, 27], [12,\n 29], [13, 31], [13, 32], [14, 16], [14, 22], [15, 16], [15, 19], [16, \n 17], [17, 18], [17, 21], [18, 19], [18, 24], [19, 25], [20, 26], [20, \n 41], [21, 22], [21, 23], [23, 24], [24, 25], [26, 27], [26, 39], [27, \n 35], [28, 29], [28, 40], [29, 35], [30, 31], [30, 45], [31, 36], [32, \n 33], [32, 36], [33, 34], [33, 43], [34, 44], [35, 37], [36, 38], [37, \n 39], [37, 40], [38, 43], [38, 45], [39, 41], [40, 42], [41, 42], [43, \n 44], [44, 46], [45, 46]]'], {}), '([[1, 11], [1, 12], [1, 13], [2, 3], [2, 8], [2, 20], [3, 4], [3, \n 42], [4, 5], [4, 28], [5, 6], [5, 34], [6, 7], [6, 46], [7, 10], [7, 30\n ], [8, 9], [8, 22], [9, 10], [9, 23], [10, 25], [11, 14], [11, 15], [12,\n 27], [12, 29], [13, 31], [13, 32], [14, 16], [14, 22], [15, 16], [15, \n 19], [16, 17], [17, 18], [17, 21], [18, 19], [18, 24], [19, 25], [20, \n 26], [20, 41], [21, 22], [21, 23], [23, 24], [24, 25], [26, 27], [26, \n 39], [27, 35], [28, 29], [28, 40], [29, 35], [30, 31], [30, 45], [31, \n 36], [32, 33], [32, 36], [33, 34], [33, 43], [34, 44], [35, 37], [36, \n 38], [37, 39], [37, 40], [38, 43], [38, 45], [39, 41], [40, 42], [41, \n 42], [43, 44], [44, 46], [45, 46]])\n', (3356, 4065), True, 'import numpy as np\n'), ((779, 798), 'numpy.array', 'np.array', (['[0, 0.45]'], {}), '([0, 0.45])\n', (787, 798), True, 'import numpy as np\n'), ((835, 854), 'numpy.array', 'np.array', (['[0, 0.27]'], {}), '([0, 0.27])\n', (843, 854), True, 'import numpy as np\n'), ((3240, 3264), 'numpy.sum', 'np.sum', (['vertices'], {'axis': '(0)'}), '(vertices, axis=0)\n', (3246, 3264), True, 'import numpy as np\n'), ((3311, 3331), 'numpy.array', 'np.array', (['[0.5, 0.5]'], {}), '([0.5, 0.5])\n', (3319, 3331), True, 'import numpy as np\n'), ((5171, 5196), 'numpy.zeros', 'np.zeros', (['adjacency.shape'], {}), '(adjacency.shape)\n', (5179, 5196), True, 'import numpy as np\n'), ((232, 245), 'numpy.cos', 'np.cos', (['angle'], {}), '(angle)\n', (238, 245), True, 'import numpy as np\n'), ((273, 286), 'numpy.sin', 'np.sin', (['angle'], {}), '(angle)\n', (279, 286), True, 'import numpy as np\n'), ((288, 301), 'numpy.cos', 'np.cos', (['angle'], {}), '(angle)\n', (294, 301), True, 'import numpy as np\n'), ((248, 261), 'numpy.sin', 'np.sin', (['angle'], {}), '(angle)\n', (254, 261), True, 'import numpy as np\n'), ((1193, 1208), 'numpy.arange', 'np.arange', (['(0)', '(5)'], {}), '(0, 5)\n', (1202, 1208), True, 'import numpy as np\n'), ((1317, 1332), 'numpy.arange', 'np.arange', (['(0)', '(5)'], {}), '(0, 5)\n', (1326, 1332), True, 'import numpy as np\n'), ((1372, 1388), 'numpy.arange', 'np.arange', (['(5)', '(10)'], {}), '(5, 10)\n', (1381, 1388), True, 'import numpy as np\n'), ((1456, 1472), 'numpy.arange', 'np.arange', (['(5)', '(10)'], {}), '(5, 10)\n', (1465, 1472), True, 'import numpy as np\n'), ((1227, 1242), 'numpy.arange', 'np.arange', (['(0)', '(5)'], {}), '(0, 5)\n', (1236, 1242), True, 'import numpy as np\n'), ((1491, 1507), 'numpy.arange', 'np.arange', (['(5)', '(10)'], {}), '(5, 10)\n', (1500, 1507), True, 'import numpy as np\n')]
|
from __future__ import print_function, absolute_import, division, unicode_literals
# Requirements:
import numpy as np, glob, os, sys
#from scipy import misc
import imageio
import tensorflow as tf
import pdb
from spit.utils import one_hot_encoded
sys.dont_write_bytecode = True
def load_linear_pngs(instr, data_type, label_dict, debug=False, single_copy=False,
spit_path=os.getenv('SPIT_DATA'),
subset=None, images_only=False):
""" Load PNGs
Parameters
----------
instr : str
Name of instrument, e.g. 'Kast'
data_type : str
Training type, e.g. 'train', 'valid'
label_dict : dict
Sets label values
single_copy : bool, optional
Only grab one copy (with flips) of each image
subset : int, optional
Only grab a subset of the full list, i.e. the number of files provided by this parameter
images_only : bool, optional
Return only the images?
Returns
----------
dset:
a Tensorflow Dataset Object containing the images and labels as numpy arrays
one_hot:
a Tensorflow one-hot encoded array for the label values
"""
image_data = {}
# Define the image locations
data_locations = []
for itype in ['flat', 'arc', 'bias','standard','science']:
if single_copy:
data_locations.append(spit_path+'/'+instr+'/PNG/{:s}/{:s}/0_*png'.format(data_type, itype))
else:
data_locations.append(spit_path+'/'+instr+'/PNG/{:s}/{:s}/*png'.format(data_type, itype))
'''
if data_type == "train_data":
load_batch_size = 504
data_locations = [ \
spit_path+"viktor_astroimage/linear_datasets/bias_train/*", \
spit_path+"viktor_astroimage/linear_datasets/science_train/*", \
spit_path+"viktor_astroimage/linear_datasets/standard_train/*", \
spit_path+"viktor_astroimage/linear_datasets/arc_train/*", \
spit_path+"viktor_astroimage/linear_datasets/flat_train/*", \
spit_path+"viktor_astroimage/linear_datasets/bias_validation/*", \
spit_path+"viktor_astroimage/linear_datasets/science_validation/*", \
spit_path+"viktor_astroimage/linear_datasets/standard_validation/*", \
img_path+"viktor_astroimage/linear_datasets/arc_validation/*", \
img_path+"viktor_astroimage/linear_datasets/flat_validation/*", \
img_path+"viktor_astroimage/linear_datasets/bias_test/*", \
img_path+"viktor_astroimage/linear_datasets/science_test/*", \
img_path+"viktor_astroimage/linear_datasets/science_enforced/*", \
img_path+"viktor_astroimage/linear_datasets/standard_test/*", \
img_path+"viktor_astroimage/linear_datasets/arc_test/*", \
img_path+"viktor_astroimage/linear_datasets/flat_test/*"]
elif data_type == "kast_test_data":
print("Loading the test data..")
load_batch_size = 160
data_locations = [ \
img_path+"viktor_astroimage/linear_datasets/real_bias_test/*", \
img_path+"viktor_astroimage/linear_datasets/real_science_test/*", \
img_path+"viktor_astroimage/linear_datasets/real_standard_test/*", \
img_path+"viktor_astroimage/linear_datasets/real_arc_test/*", \
img_path+"viktor_astroimage/linear_datasets/real_flat_test/*"]
'''
# Construct the dict arrays
raw_data = []
labels = []
filenames = []
for index, location in enumerate(data_locations):
images = glob.glob(location)
images.sort() # So that the ordering is the same each time
image_array = []
image_labels = []
image_filenames = []
for kk, image_file in enumerate(images):
if debug and (kk == 10):
break
if subset is not None:
if kk == subset:
break
# load image
image_data = imageio.imread(image_file, pilmode='L')
#padded_image = image_data.flatten()
#image_array.append(padded_image)
image_array.append(image_data)
# get image's type using long logic, could make faster
if "bias" in image_file:
image_label = label_dict['bias_label']
elif "science" in image_file:
image_label = label_dict['science_label']
elif "standard" in image_file:
image_label = label_dict['standard_label']
elif "arc" in image_file:
image_label = label_dict['arc_label']
elif "flat" in image_file:
image_label = label_dict['flat_label']
else:
pdb.set_trace()
image_labels.append(image_label)
image_filenames.append(image_file)
raw_data = raw_data + image_array
labels = labels + image_labels
filenames = filenames + image_filenames
print("Loaded!")
# Get the raw images.
raw_images = np.array(raw_data)
ishape = list(raw_images.shape)
raw_images = raw_images.reshape(ishape+[1])
assert len(raw_images.shape) == 4
# Get the class-numbers for each image. Convert to numpy-array.
lbl_array = np.array(labels) # might change cls to cls_nums cuz cls means something different
if images_only:
return raw_images, lbl_array
# cls needs to be one-hot!
# raise IOError
dset = tf.data.Dataset.from_tensor_slices((raw_images, lbl_array))
one_hot = tf.one_hot(indices=lbl_array, depth=len(label_dict), dtype=float)
return dset, one_hot, \
filenames
'''
def load_all_data():
data_locations = [ \
"images/bias/linear*", \
"images/science/linear*", \
"images/standard/linear*", \
"images/arc/linear*", \
"images/flat/linear*"]
raw_data = []
labels = []
filenames = []
for index, location in enumerate(data_locations):
images = glob.glob(location)
image_array = []
image_labels = []
image_filenames = []
for image_file in images:
image_data = misc.imread(image_file, mode='L')
padded_image = image_data.flatten()
image_array.append(padded_image)
image_labels.append(index)
image_filenames.append(image_file)
raw_data = raw_data + image_array
labels = labels + image_labels
filenames = filenames + image_filenames
data_locations = [ \
"/soe/vjankov/scratchdisk/viktor_astroimage/histequ_datasets/bias_train_histequ/*", \
"/soe/vjankov/scratchdisk/viktor_astroimage/histequ_datasets/science_train_histequ/*", \
"/soe/vjankov/scratchdisk/viktor_astroimage/histequ_datasets/standard_train_histequ/*", \
"/soe/vjankov/scratchdisk/viktor_astroimage/histequ_datasets/arc_train_histequ/*", \
"/soe/vjankov/scratchdisk/viktor_astroimage/histequ_datasets/flat_train_histequ/*"]
for index, location in enumerate(data_locations):
images = glob.glob(location)
image_array = []
image_labels = []
image_filenames = []
for image_file in images:
image_data = misc.imread(image_file, mode='L')
padded_image = image_data.flatten()
image_array.append(padded_image)
image_labels.append(index)
image_filenames.append(image_file)
raw_data = raw_data + image_array
labels = labels + image_labels
filenames = filenames + image_filenames
data_locations = [ \
"/soe/vjankov/scratchdisk/viktor_astroimage/histequ_datasets/bias_test_histequ/*", \
"/soe/vjankov/scratchdisk/viktor_astroimage/histequ_datasets/science_test_histequ/*", \
"/soe/vjankov/scratchdisk/viktor_astroimage/histequ_datasets/standard_test_histequ/*", \
"/soe/vjankov/scratchdisk/viktor_astroimage/histequ_datasets/arc_test_histequ/*", \
"/soe/vjankov/scratchdisk/viktor_astroimage/histequ_datasets/flat_test_histequ/*"]
for index, location in enumerate(data_locations):
images = glob.glob(location)
image_array = []
image_filenames = []
for image_file in images:
image_data = misc.imread(image_file, mode='L')
padded_image = image_data.flatten()
image_array.append(padded_image)
image_labels.append(index)
image_filenames.append(image_file)
raw_data = raw_data + image_array
labels = labels + image_labels
filenames = filenames + image_filenames
# Get the raw images.
raw_images = np.array(raw_data)
# Get the class-numbers for each image. Convert to numpy-array.
cls = np.array(labels)
return raw_images, cls, one_hot_encoded(class_numbers=cls, num_classes=num_classes), filenames
'''
'''
def load_images_arr(image_file, outfile=None):
""" Convert an input FITS file into 4 flattened arrays
having flipped it around
Parameters
----------
image_file : str
Name of the FITS file
Returns
-------
images_array : ndarray
nimgs (4) x flattened image
"""
#v1, server = get_viewer_and_server()
#set_viewer_prefs(v1)
# Paths
basename = os.path.basename(image_file)
names = basename.split(".")
file_root = names[0]
# Load FITS
image = spit_io.read_fits(image_file)
# Pre-process
zimage = spit_pre.process_image(image)
# PNG?
if outfile is not None:
spit_io.write_array_to_png(zimage, outfile)
return images_array
def load_data_cropped200x600(data_type, img_path='/soe/vjankov/scratchdisk/'):
image_data = {}
"""
a)
Load the data from the filenames stored in the data_locations
b)
Add 0 padding to each image. The padding is 2112 pixels width and height
The 2112 is the widest pixel form the dataset
c)
Add labels for each image based on the folder they are coming form
This is the label names and values
Bias = 0
Science = 1
Arc = 2
Flat = 3
d)
Construct a dictionary with the following properties:
raw_data = the flattened 2112 np array with raw pixel values
labels = the corresponding labels for each data element
filename = the corresponding filename
"""
# Define the image locations
if data_type == "train_data":
load_batch_size = 5400
data_locations = [ \
img_path + "viktor_astroimage/bias_train/*", \
img_path + "viktor_astroimage/science_train/*", \
img_path + "viktor_astroimage/standard_train/*", \
img_path + "viktor_astroimage/arc_train/*", \
img_path + "viktor_astroimage/flat_train/*"]
elif data_type == "test_data":
load_batch_size = 1650
data_locations = [ \
img_path + "viktor_astroimage/bias_test/*", \
img_path + "viktor_astroimage/science_test/*", \
img_path + "viktor_astroimage/standard_test/*", \
img_path + "viktor_astroimage/arc_test/*", \
img_path + "viktor_astroimage/flat_test/*"]
elif data_type == "validation_data":
load_batch_size = 1350
data_locations = [ \
img_path + "viktor_astroimage/bias_validation/*", \
img_path + "viktor_astroimage/science_validation/*", \
img_path + "viktor_astroimage/standard_validation/*", \
img_path + "viktor_astroimage/arc_validation/*", \
img_path + "viktor_astroimage/flat_validation/*"]
# Construct the dict arrays
raw_data = []
labels = []
filenames = []
for index, location in enumerate(data_locations):
images = glob.glob(location)
image_array = []
image_labels = []
image_filenames = []
for image_file in images:
hdulist = fits.open(image_file)
image_data = hdulist[0].data
padded_image = image_data.flatten()
image_array.append(padded_image)
image_labels.append(index)
image_filenames.append(image_file)
"""
while len(image_array) < load_batch_size:
image_array = image_array + image_array
image_labels = image_labels + image_labels
image_filenames = image_filenames + image_filenames
raw_data = raw_data + image_array[:load_batch_size]
labels = labels + image_labels[:load_batch_size]
filenames = filenames + image_filenames[:load_batch_size]
"""
raw_data = raw_data + image_array
labels = labels + image_labels
filenames = filenames + image_filenames
# Get the raw images.
raw_images = np.array(raw_data)
# Get the class-numbers for each image. Convert to numpy-array.
cls = np.array(labels)
return raw_images, cls, one_hot_encoded(class_numbers=cls, num_classes=num_classes), filenames
'''
|
[
"imageio.imread",
"tensorflow.data.Dataset.from_tensor_slices",
"numpy.array",
"pdb.set_trace",
"glob.glob",
"os.getenv"
] |
[((398, 420), 'os.getenv', 'os.getenv', (['"""SPIT_DATA"""'], {}), "('SPIT_DATA')\n", (407, 420), False, 'import numpy as np, glob, os, sys\n'), ((5059, 5077), 'numpy.array', 'np.array', (['raw_data'], {}), '(raw_data)\n', (5067, 5077), True, 'import numpy as np, glob, os, sys\n'), ((5285, 5301), 'numpy.array', 'np.array', (['labels'], {}), '(labels)\n', (5293, 5301), True, 'import numpy as np, glob, os, sys\n'), ((5488, 5547), 'tensorflow.data.Dataset.from_tensor_slices', 'tf.data.Dataset.from_tensor_slices', (['(raw_images, lbl_array)'], {}), '((raw_images, lbl_array))\n', (5522, 5547), True, 'import tensorflow as tf\n'), ((3577, 3596), 'glob.glob', 'glob.glob', (['location'], {}), '(location)\n', (3586, 3596), False, 'import numpy as np, glob, os, sys\n'), ((3996, 4035), 'imageio.imread', 'imageio.imread', (['image_file'], {'pilmode': '"""L"""'}), "(image_file, pilmode='L')\n", (4010, 4035), False, 'import imageio\n'), ((4755, 4770), 'pdb.set_trace', 'pdb.set_trace', ([], {}), '()\n', (4768, 4770), False, 'import pdb\n')]
|
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 19 19:33:17 2019
@author: Mysia
"""
import numpy as np
def nnloss(x,t,dzdy):
instanceWeights=np.ones(len(x))
res=x-t
if(dzdy==0):
y = (1/2) * instanceWeights * np.power(res,2)
else:
y = res
return y
|
[
"numpy.power"
] |
[((251, 267), 'numpy.power', 'np.power', (['res', '(2)'], {}), '(res, 2)\n', (259, 267), True, 'import numpy as np\n')]
|
import numpy as np
import torch
from torch.autograd import Variable
def data_generator(T, mem_length, b_size):
"""
Generate data for the copying memory task
:param T: The total blank time length
:param mem_length: The length of the memory to be recalled
:param b_size: The batch size
:return: Input and target data tensor
"""
seq = torch.from_numpy(np.random.randint(1, 9, size=(b_size, mem_length))).float()
zeros = torch.zeros((b_size, T))
marker = 9 * torch.ones((b_size, mem_length + 1))
placeholders = torch.zeros((b_size, mem_length))
X = torch.cat((seq, zeros[:, :-1], marker), 1)
Y = torch.cat((placeholders, zeros, seq), 1).long()
return X, Y
class CopyMemory(torch.utils.data.TensorDataset): # TODO: Documentation
def __init__(
self,
partition: str,
seq_length: int,
**kwargs,
):
memory_size = kwargs["memory_size"]
blank_length = seq_length
# total_seq_length = blank_length + (
# 2 * memory_size
# ) # Total size of sequence is blank space + 2 times the size of the string to memorize.
if partition == "train":
dataset_size = 10000
X, Y = data_generator(blank_length, memory_size, dataset_size)
elif partition == "test":
dataset_size = 1000
X, Y = data_generator(blank_length, memory_size, dataset_size)
else:
raise NotImplementedError(
"The dataset partition {} does not exist".format(partition)
)
super(CopyMemory, self).__init__(X, Y)
|
[
"torch.zeros",
"torch.ones",
"numpy.random.randint",
"torch.cat"
] |
[((455, 479), 'torch.zeros', 'torch.zeros', (['(b_size, T)'], {}), '((b_size, T))\n', (466, 479), False, 'import torch\n'), ((553, 586), 'torch.zeros', 'torch.zeros', (['(b_size, mem_length)'], {}), '((b_size, mem_length))\n', (564, 586), False, 'import torch\n'), ((596, 638), 'torch.cat', 'torch.cat', (['(seq, zeros[:, :-1], marker)', '(1)'], {}), '((seq, zeros[:, :-1], marker), 1)\n', (605, 638), False, 'import torch\n'), ((497, 533), 'torch.ones', 'torch.ones', (['(b_size, mem_length + 1)'], {}), '((b_size, mem_length + 1))\n', (507, 533), False, 'import torch\n'), ((647, 687), 'torch.cat', 'torch.cat', (['(placeholders, zeros, seq)', '(1)'], {}), '((placeholders, zeros, seq), 1)\n', (656, 687), False, 'import torch\n'), ((383, 433), 'numpy.random.randint', 'np.random.randint', (['(1)', '(9)'], {'size': '(b_size, mem_length)'}), '(1, 9, size=(b_size, mem_length))\n', (400, 433), True, 'import numpy as np\n')]
|
import numpy as np
x = np.array([1., 2.])
x /= np.sqrt(np.sum(x**2 ,axis=-1))[..., np.newaxis]
print(x)
print(x[0]+x[1])
|
[
"numpy.array",
"numpy.sum"
] |
[((24, 44), 'numpy.array', 'np.array', (['[1.0, 2.0]'], {}), '([1.0, 2.0])\n', (32, 44), True, 'import numpy as np\n'), ((56, 79), 'numpy.sum', 'np.sum', (['(x ** 2)'], {'axis': '(-1)'}), '(x ** 2, axis=-1)\n', (62, 79), True, 'import numpy as np\n')]
|
from classify_utils import setup_args, setup, get_basemodel, get_data, get_logger, setup_args_preprocessing, setup_args_getE
from util import Logger
import argparse
import torch
import numpy as np
from statsmodels.stats.proportion import proportion_confint
import scipy.stats as sps
from collections import Counter
import sys
from datetime import datetime
import time
import torchvision.transforms.functional as TF
import PIL, PIL.Image
import multiprocessing as mp
import os
import geometrictools as gt
parser = argparse.ArgumentParser()
parser = setup_args(parser)
parser = setup_args_preprocessing(parser)
parser = setup_args_getE(parser)
parser.add_argument('--betaSplit', type=int, default=-1, help='split beta in chunks for error bounding; higher numbers make the error computation faster; lower numbers more precise; -1 diables it and considers all errors together')
args = parser.parse_args()
setup(args)
model = get_basemodel(args)
data = get_data(args)
logger = get_logger(args, __file__)
print(args, file=logger)
print("index", "err", file=logger, flush=True)
for idx, d in enumerate(data):
print()
img, label = d
if args.resize > 0:
img = TF.resize(img, args.resize)
img = TF.center_crop(img, args.resize)
img = np.array(img)
if len(img.shape) == 2:
img = np.expand_dims(img, -1)
assert(img.dtype == np.uint8)
img = img.astype(dtype=np.float32)/255.0
if args.transformation == 'rot':
betas = np.random.normal(0, args.sigma_gamma, (1, args.nrBetas))
elif args.transformation == 'trans':
betas = np.random.normal(0, args.sigma_gamma, (2, args.nrBetas))
k = 0
errs, gamma = [], np.array([0] * betas.shape[0])
s = args.betaSplit if args.betaSplit > 0 else args.nrBetas
while len(errs) < args.nrBetas:
errs_, gamma_ = gt.getE(image=img,
transformation=args.transformation,
targetE=args.target_err,
stopE=args.stop_err,
gamma0=args.gamma0,
gamma1=args.gamma1,
betas=betas[:, k*s:(k+1)*s],
invertT=False,
resizePostTransform=args.resize_post_transform,
centerCropPostTranform=args.center_crop_post_transform,
filterSigma=args.filter_sigma,
filterSize=args.filter_size,
radiusDecrease=args.radiusDecrease,
initialSplits=args.initial_splits,
batchSize=args.gt_batch_size,
threads=args.threads,
gpu=args.use_cuda,
debug=args.debug,
doInt=args.intErr,
refinements=args.refinements,
timeout=120)
errs.extend(errs_)
for err in errs:
print(idx+args.Nstart, err, file=logger, flush=True)
|
[
"classify_utils.get_data",
"classify_utils.get_logger",
"torchvision.transforms.functional.center_crop",
"classify_utils.setup_args_getE",
"argparse.ArgumentParser",
"classify_utils.setup_args",
"torchvision.transforms.functional.resize",
"numpy.expand_dims",
"classify_utils.setup_args_preprocessing",
"geometrictools.getE",
"classify_utils.setup",
"numpy.array",
"classify_utils.get_basemodel",
"numpy.random.normal"
] |
[((516, 541), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (539, 541), False, 'import argparse\n'), ((551, 569), 'classify_utils.setup_args', 'setup_args', (['parser'], {}), '(parser)\n', (561, 569), False, 'from classify_utils import setup_args, setup, get_basemodel, get_data, get_logger, setup_args_preprocessing, setup_args_getE\n'), ((579, 611), 'classify_utils.setup_args_preprocessing', 'setup_args_preprocessing', (['parser'], {}), '(parser)\n', (603, 611), False, 'from classify_utils import setup_args, setup, get_basemodel, get_data, get_logger, setup_args_preprocessing, setup_args_getE\n'), ((621, 644), 'classify_utils.setup_args_getE', 'setup_args_getE', (['parser'], {}), '(parser)\n', (636, 644), False, 'from classify_utils import setup_args, setup, get_basemodel, get_data, get_logger, setup_args_preprocessing, setup_args_getE\n'), ((904, 915), 'classify_utils.setup', 'setup', (['args'], {}), '(args)\n', (909, 915), False, 'from classify_utils import setup_args, setup, get_basemodel, get_data, get_logger, setup_args_preprocessing, setup_args_getE\n'), ((924, 943), 'classify_utils.get_basemodel', 'get_basemodel', (['args'], {}), '(args)\n', (937, 943), False, 'from classify_utils import setup_args, setup, get_basemodel, get_data, get_logger, setup_args_preprocessing, setup_args_getE\n'), ((951, 965), 'classify_utils.get_data', 'get_data', (['args'], {}), '(args)\n', (959, 965), False, 'from classify_utils import setup_args, setup, get_basemodel, get_data, get_logger, setup_args_preprocessing, setup_args_getE\n'), ((975, 1001), 'classify_utils.get_logger', 'get_logger', (['args', '__file__'], {}), '(args, __file__)\n', (985, 1001), False, 'from classify_utils import setup_args, setup, get_basemodel, get_data, get_logger, setup_args_preprocessing, setup_args_getE\n'), ((1270, 1283), 'numpy.array', 'np.array', (['img'], {}), '(img)\n', (1278, 1283), True, 'import numpy as np\n'), ((1176, 1203), 'torchvision.transforms.functional.resize', 'TF.resize', (['img', 'args.resize'], {}), '(img, args.resize)\n', (1185, 1203), True, 'import torchvision.transforms.functional as TF\n'), ((1218, 1250), 'torchvision.transforms.functional.center_crop', 'TF.center_crop', (['img', 'args.resize'], {}), '(img, args.resize)\n', (1232, 1250), True, 'import torchvision.transforms.functional as TF\n'), ((1329, 1352), 'numpy.expand_dims', 'np.expand_dims', (['img', '(-1)'], {}), '(img, -1)\n', (1343, 1352), True, 'import numpy as np\n'), ((1495, 1551), 'numpy.random.normal', 'np.random.normal', (['(0)', 'args.sigma_gamma', '(1, args.nrBetas)'], {}), '(0, args.sigma_gamma, (1, args.nrBetas))\n', (1511, 1551), True, 'import numpy as np\n'), ((1698, 1728), 'numpy.array', 'np.array', (['([0] * betas.shape[0])'], {}), '([0] * betas.shape[0])\n', (1706, 1728), True, 'import numpy as np\n'), ((1852, 2466), 'geometrictools.getE', 'gt.getE', ([], {'image': 'img', 'transformation': 'args.transformation', 'targetE': 'args.target_err', 'stopE': 'args.stop_err', 'gamma0': 'args.gamma0', 'gamma1': 'args.gamma1', 'betas': 'betas[:, k * s:(k + 1) * s]', 'invertT': '(False)', 'resizePostTransform': 'args.resize_post_transform', 'centerCropPostTranform': 'args.center_crop_post_transform', 'filterSigma': 'args.filter_sigma', 'filterSize': 'args.filter_size', 'radiusDecrease': 'args.radiusDecrease', 'initialSplits': 'args.initial_splits', 'batchSize': 'args.gt_batch_size', 'threads': 'args.threads', 'gpu': 'args.use_cuda', 'debug': 'args.debug', 'doInt': 'args.intErr', 'refinements': 'args.refinements', 'timeout': '(120)'}), '(image=img, transformation=args.transformation, targetE=args.\n target_err, stopE=args.stop_err, gamma0=args.gamma0, gamma1=args.gamma1,\n betas=betas[:, k * s:(k + 1) * s], invertT=False, resizePostTransform=\n args.resize_post_transform, centerCropPostTranform=args.\n center_crop_post_transform, filterSigma=args.filter_sigma, filterSize=\n args.filter_size, radiusDecrease=args.radiusDecrease, initialSplits=\n args.initial_splits, batchSize=args.gt_batch_size, threads=args.threads,\n gpu=args.use_cuda, debug=args.debug, doInt=args.intErr, refinements=\n args.refinements, timeout=120)\n', (1859, 2466), True, 'import geometrictools as gt\n'), ((1609, 1665), 'numpy.random.normal', 'np.random.normal', (['(0)', 'args.sigma_gamma', '(2, args.nrBetas)'], {}), '(0, args.sigma_gamma, (2, args.nrBetas))\n', (1625, 1665), True, 'import numpy as np\n')]
|
'''
Created on 2018年3月28日
@author: <NAME>
'''
import numpy as np
import Lib.RFLib as RFLib
def kernalTransfrom(dataMatrix, vector, kTup):
if kTup[0] == "lin":
return vector * dataMatrix.transpose()
elif kTup[0] == "rbf":
delta = dataMatrix - vector
K = np.matrix(np.diag(delta * delta.transpose()), dtype=np.float)
K = np.exp(K / (-2 * kTup[1] ** 2))
return K
else:
raise NameError("Kernal Name Error")
class osStruct:
def __init__(self, dataMatIn, classlabels, C , toler, kTup):
self.dataMatrix = np.matrix(dataMatIn, dtype=np.float)
self.labelMatrix = np.matrix(classlabels, dtype=np.float).transpose()
self.C = C
self.toler = toler
self.m = self.dataMatrix.shape[0]
self.b = 0
self.alphas = np.matrix(np.zeros((self.m, 1)), dtype=np.float)
self.eCache = np.matrix(np.zeros((self.m, 2)), dtype=np.float)
self.K = np.matrix(np.zeros((self.m, self.m)), dtype=np.float)
for i in range(self.m):
self.K[i] = kernalTransfrom(self.dataMatrix, self.dataMatrix[i, :], kTup)
def selectJRand(i, m):
j = i
while j == i:
j = np.random.randint(0, m, 1)[0]
return j
def clipAlpha(alpha, L, H):
if alpha >= H:
return H
elif alpha <= L:
return L
else:
return alpha
def calEi(obj, i):
fxi = float(np.multiply(obj.alphas, obj.labelMatrix).transpose() * \
obj.K[:, i]) + obj.b
Ek = fxi - obj.labelMatrix[i, 0]
return float(Ek)
def updateEi(obj, i):
Ei = calEi(obj, i)
obj.eCache[i] = [1, Ei]
def selectJIndex(obj, i, Ei):
maxJ = -1
maxdelta = -1
Ek = -1
obj.eCache[i] = [1, Ei]
vaildEiList = np.nonzero(obj.eCache[:, 0].A)[0]
if len(vaildEiList) > 1:
for j in vaildEiList:
if j == i:
continue
Ej = calEi(obj, j)
delta = np.abs(Ei - Ej)
if delta > maxdelta:
maxdelta = delta
maxJ = j
Ek = Ej
else:
maxJ = selectJRand(i, obj.m)
Ek = calEi(obj, maxJ)
return Ek, maxJ
def innerLoop(obj, i):
Ei = calEi(obj, i)
if (obj.labelMatrix[i, 0] * Ei < -obj.toler and obj.alphas[i, 0] < obj.C) or \
(obj.labelMatrix[i, 0] * Ei > obj.toler and obj.alphas[i, 0] > 0):
Ej, j = selectJIndex(obj, i, Ei)
alphaIold = obj.alphas[i, 0].copy()
alphaJold = obj.alphas[j, 0].copy()
if obj.labelMatrix[i, 0] == obj.labelMatrix[j, 0]:
L = max(0, obj.alphas[i, 0] + obj.alphas[j, 0] - obj.C)
H = min(obj.C , obj.alphas[i, 0] + obj.alphas[j, 0])
else:
L = max(0, obj.alphas[j, 0] - obj.alphas[i, 0])
H = min(obj.C, obj.C - obj.alphas[i, 0] + obj.alphas[j, 0])
if L == H:
return 0
eta = obj.K[i, i] + obj.K[j, j] - 2 * obj.K[i, j]
if eta <= 0:
return 0
obj.alphas[j, 0] += obj.labelMatrix[j, 0] * (Ei - Ej) / eta
obj.alphas[j, 0] = clipAlpha(obj.alphas[j, 0], L, H)
updateEi(obj, j)
if np.abs(obj.alphas[j, 0] - alphaJold) < 0.00001:
return 0
obj.alphas[i, 0] += obj.labelMatrix[i, 0] * obj.labelMatrix[j, 0] * (alphaJold - obj.alphas[j, 0])
updateEi(obj, i)
b1 = -Ei - obj.labelMatrix[i, 0] * obj.K[i, i] * (obj.alphas[i, 0] - alphaIold) \
- obj.labelMatrix[j, 0] * obj.K[i, j] * (obj.alphas[j, 0] - alphaJold) + obj.b
b2 = -Ej - obj.labelMatrix[i, 0] * obj.K[i, j] * (obj.alphas[i, 0] - alphaIold) \
- obj.labelMatrix[j, 0] * obj.K[j, j] * (obj.alphas[j, 0] - alphaJold) + obj.b
if obj.alphas[i, 0] > 0 and obj.alphas[i, 0] < obj.C:
obj.b = b1
elif obj.alphas[j, 0] > 0 and obj.alphas[j, 0] < obj.C:
obj.b = b2
else:
obj.b = (b1 + b2) / 2.0
return 1
else:
return 0
def realSMO(trainSet, trainLabels, C, toler, kTup=('lin', 1.3), maxIter=40):
obj = osStruct(trainSet, trainLabels, C, toler, kTup)
entrySet = True
iterNum = 0
alphapairschanged = 0
while (iterNum < maxIter) and (alphapairschanged > 0 or entrySet):
print(iterNum)
alphapairschanged = 0
if entrySet:
for i in range(obj.m):
alphapairschanged += innerLoop(obj, i)
if i % 100 == 0:
print("full set loop, iter: %d, alphapairschanged: %d, iterNum: %d" % (i, alphapairschanged, iterNum))
iterNum += 1
else:
vaildalphsaList = np.nonzero((obj.alphas.A > 0) * (obj.alphas.A < C))[0]
for i in vaildalphsaList:
alphapairschanged += innerLoop(obj, i)
if i % 100 == 0:
print("non-bound set loop, iter: %d, alphapairschanged: %d, iterNum: %d" % (i, alphapairschanged, iterNum))
iterNum += 1
if entrySet:
entrySet = False
elif alphapairschanged == 0:
entrySet = True
print("iter num: %d" % (iterNum))
return obj.alphas, obj.b
def getSupportVectorandSupportLabel(trainSet, trainLabel, alphas):
vaildalphaList = np.nonzero(alphas.A)[0]
dataMatrix = np.matrix(trainSet, dtype=np.float)
labelMatrix = np.matrix(trainLabel, dtype=np.float).transpose()
sv = dataMatrix[vaildalphaList]#得到支持向量
svl = labelMatrix[vaildalphaList]
return sv, svl
def predictLabel(data, sv, svl, alphas, b, kTup):
kernal = kernalTransfrom(sv, np.matrix(data, dtype=np.float), kTup).transpose()
fxi = np.multiply(svl.T, alphas[alphas != 0]) * kernal + b
return np.sign(float(fxi))
|
[
"numpy.matrix",
"numpy.abs",
"numpy.multiply",
"numpy.zeros",
"numpy.nonzero",
"numpy.random.randint",
"numpy.exp"
] |
[((5294, 5329), 'numpy.matrix', 'np.matrix', (['trainSet'], {'dtype': 'np.float'}), '(trainSet, dtype=np.float)\n', (5303, 5329), True, 'import numpy as np\n'), ((573, 609), 'numpy.matrix', 'np.matrix', (['dataMatIn'], {'dtype': 'np.float'}), '(dataMatIn, dtype=np.float)\n', (582, 609), True, 'import numpy as np\n'), ((1750, 1780), 'numpy.nonzero', 'np.nonzero', (['obj.eCache[:, 0].A'], {}), '(obj.eCache[:, 0].A)\n', (1760, 1780), True, 'import numpy as np\n'), ((5253, 5273), 'numpy.nonzero', 'np.nonzero', (['alphas.A'], {}), '(alphas.A)\n', (5263, 5273), True, 'import numpy as np\n'), ((361, 392), 'numpy.exp', 'np.exp', (['(K / (-2 * kTup[1] ** 2))'], {}), '(K / (-2 * kTup[1] ** 2))\n', (367, 392), True, 'import numpy as np\n'), ((827, 848), 'numpy.zeros', 'np.zeros', (['(self.m, 1)'], {}), '((self.m, 1))\n', (835, 848), True, 'import numpy as np\n'), ((898, 919), 'numpy.zeros', 'np.zeros', (['(self.m, 2)'], {}), '((self.m, 2))\n', (906, 919), True, 'import numpy as np\n'), ((964, 990), 'numpy.zeros', 'np.zeros', (['(self.m, self.m)'], {}), '((self.m, self.m))\n', (972, 990), True, 'import numpy as np\n'), ((1190, 1216), 'numpy.random.randint', 'np.random.randint', (['(0)', 'm', '(1)'], {}), '(0, m, 1)\n', (1207, 1216), True, 'import numpy as np\n'), ((1942, 1957), 'numpy.abs', 'np.abs', (['(Ei - Ej)'], {}), '(Ei - Ej)\n', (1948, 1957), True, 'import numpy as np\n'), ((3151, 3187), 'numpy.abs', 'np.abs', (['(obj.alphas[j, 0] - alphaJold)'], {}), '(obj.alphas[j, 0] - alphaJold)\n', (3157, 3187), True, 'import numpy as np\n'), ((5348, 5385), 'numpy.matrix', 'np.matrix', (['trainLabel'], {'dtype': 'np.float'}), '(trainLabel, dtype=np.float)\n', (5357, 5385), True, 'import numpy as np\n'), ((5643, 5682), 'numpy.multiply', 'np.multiply', (['svl.T', 'alphas[alphas != 0]'], {}), '(svl.T, alphas[alphas != 0])\n', (5654, 5682), True, 'import numpy as np\n'), ((637, 675), 'numpy.matrix', 'np.matrix', (['classlabels'], {'dtype': 'np.float'}), '(classlabels, dtype=np.float)\n', (646, 675), True, 'import numpy as np\n'), ((4640, 4691), 'numpy.nonzero', 'np.nonzero', (['((obj.alphas.A > 0) * (obj.alphas.A < C))'], {}), '((obj.alphas.A > 0) * (obj.alphas.A < C))\n', (4650, 4691), True, 'import numpy as np\n'), ((5582, 5613), 'numpy.matrix', 'np.matrix', (['data'], {'dtype': 'np.float'}), '(data, dtype=np.float)\n', (5591, 5613), True, 'import numpy as np\n'), ((1403, 1443), 'numpy.multiply', 'np.multiply', (['obj.alphas', 'obj.labelMatrix'], {}), '(obj.alphas, obj.labelMatrix)\n', (1414, 1443), True, 'import numpy as np\n')]
|
import os
import copy
import pandas as pd
import numpy as np
import random
from sklearn.preprocessing import StandardScaler
# from imblearn.over_sampling import SMOTE
from sklearn.decomposition import PCA
from sklearn.metrics import mean_squared_error as mse
import matplotlib.pyplot as plt
from evaluation import heatmap, annotate_heatmap
"""
@relation vowel
@attribute TT integer [0, 1]
@attribute SpeakerNumber integer [0, 14]
@attribute Sex integer [0, 1]
@attribute F0 real [-5.211, -0.941]
@attribute F1 real [-1.274, 5.074]
@attribute F2 real [-2.487, 1.431]
@attribute F3 real [-1.409, 2.377]
@attribute F4 real [-2.127, 1.831]
@attribute F5 real [-0.836, 2.327]
@attribute F6 real [-1.537, 1.403]
@attribute F7 real [-1.293, 2.039]
@attribute F8 real [-1.613, 1.309]
@attribute F9 real [-1.68, 1.396]
@attribute Class {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, unlabeled}
@inputs TT, SpeakerNumber, Sex, F0, F1, F2, F3, F4, F5, F6, F7, F8, F9
@outputs Class
"""
class VowelDataset:
def __init__(self, data_dir, is_train=True, num_fold=10, label_percent=100, is_norm=False):
assert os.path.isdir(data_dir)
if is_train == True:
suffix = 'trs'
elif is_train == False:
suffix = 'tst'
else:
raise ValueError('Not Implemented.')
self.feat_list = []
self.label_list = []
self.orig_label_list = []
for i in range(num_fold):
idx = i + 1
file_dir = os.path.join(data_dir, 'vowel', 'vowel-{}-{}{}.dat'.format(num_fold, idx, suffix))
feat, label = self._parse_data(file_dir)
orig_label = copy.deepcopy(label)
if is_norm:
feat = self._norm_data(feat)
if is_train:
num_labeled = int(label_percent / 100 * feat.shape[0]) - 1
label[num_labeled:] = -1.
self.feat_list.append(feat)
self.label_list.append(label)
self.orig_label_list.append(orig_label)
def _parse_data(self, file_dir):
# TODO: need nicer method, hard code now
df = pd.read_table(file_dir)
df0 = df.iloc[17:,0]
df00 = df0.tolist()
data = []
for i in range(len(df00)):
data.append([])
l = df00[i].split(',')
for j in range(len(l)):
data[i].append(float(l[j]))
feature_all = np.array(data)[:, :-1]
label_all = np.array(data)[:,-1]
return feature_all, label_all
def _norm_data(self, feat):
# TODO
return feat
def _preprocessing(self):
'''data preprocessing'''
'''standardize'''
def standardscalar(X):
standardScaler = StandardScaler()
standardScaler.fit(X)
return standardScaler.transform(X)
'''PCA'''
def PCA_Data(X, n=5):
pca = PCA(n_components=n)
pca.fit(X)
X_reduction = pca.transform(X)
return X_reduction
# '''Smote'''
# def smote(X, y):
# sm = SMOTE(random_state=42)
# return sm.fit_resample(X, y)
if __name__ == '__main__':
dataset_tst = VowelDataset(data_dir='data/SSC_20labeled', is_train=False)
feat_all = []
for i in range(10):
feat_all.extend(dataset_tst.feat_list[i])
feat_all = np.stack(feat_all, axis=0)
attr_list = ['TT',
'SpeakerID',
'Sex',
'F0',
'F1',
'F2',
'F3',
'F4',
'F5',
'F6',
'F7',
'F8',
'F9',]
Pearson_mat = np.corrcoef(feat_all.T)
fig, ax = plt.subplots()
im, cbar = heatmap(Pearson_mat, attr_list, attr_list, ax=ax,
cmap="YlGn",)
# texts = annotate_heatmap(im, valfmt="{x:.1f} t")
fig.tight_layout()
fig.savefig('pearson_mat.pdf')
|
[
"numpy.stack",
"copy.deepcopy",
"sklearn.preprocessing.StandardScaler",
"os.path.isdir",
"numpy.corrcoef",
"pandas.read_table",
"numpy.array",
"sklearn.decomposition.PCA",
"evaluation.heatmap",
"matplotlib.pyplot.subplots"
] |
[((3364, 3390), 'numpy.stack', 'np.stack', (['feat_all'], {'axis': '(0)'}), '(feat_all, axis=0)\n', (3372, 3390), True, 'import numpy as np\n'), ((3719, 3742), 'numpy.corrcoef', 'np.corrcoef', (['feat_all.T'], {}), '(feat_all.T)\n', (3730, 3742), True, 'import numpy as np\n'), ((3757, 3771), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (3769, 3771), True, 'import matplotlib.pyplot as plt\n'), ((3788, 3850), 'evaluation.heatmap', 'heatmap', (['Pearson_mat', 'attr_list', 'attr_list'], {'ax': 'ax', 'cmap': '"""YlGn"""'}), "(Pearson_mat, attr_list, attr_list, ax=ax, cmap='YlGn')\n", (3795, 3850), False, 'from evaluation import heatmap, annotate_heatmap\n'), ((1099, 1122), 'os.path.isdir', 'os.path.isdir', (['data_dir'], {}), '(data_dir)\n', (1112, 1122), False, 'import os\n'), ((2103, 2126), 'pandas.read_table', 'pd.read_table', (['file_dir'], {}), '(file_dir)\n', (2116, 2126), True, 'import pandas as pd\n'), ((1636, 1656), 'copy.deepcopy', 'copy.deepcopy', (['label'], {}), '(label)\n', (1649, 1656), False, 'import copy\n'), ((2402, 2416), 'numpy.array', 'np.array', (['data'], {}), '(data)\n', (2410, 2416), True, 'import numpy as np\n'), ((2445, 2459), 'numpy.array', 'np.array', (['data'], {}), '(data)\n', (2453, 2459), True, 'import numpy as np\n'), ((2728, 2744), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (2742, 2744), False, 'from sklearn.preprocessing import StandardScaler\n'), ((2893, 2912), 'sklearn.decomposition.PCA', 'PCA', ([], {'n_components': 'n'}), '(n_components=n)\n', (2896, 2912), False, 'from sklearn.decomposition import PCA\n')]
|
import numpy as np
import cv2
from skimage.feature import hog
class FeatureExtractor():
def __init__(self, config):
self.conf = config
def calc_hog_features(self, img):
hog_features = []
for channel in range(img.shape[2]):
winSize = (img.shape[0], img.shape[1])
blockSize = (winSize[0] // self.conf['cell_per_block'],
winSize[1] // self.conf['cell_per_block'])
blockStride = (blockSize[0] // 2, blockSize[1] // 2)
pix_per_cell = (self.conf['pix_per_cell'], self.conf['pix_per_cell'])
USE_OPENCV = False
if USE_OPENCV:
hog_descr = cv2.HOGDescriptor(_winSize=winSize, _blockSize=blockSize, _blockStride=blockStride,
_cellSize=pix_per_cell, _nbins=self.conf['orient'], _signedGradient=False)
features = hog_descr.compute(img[:,:,channel])
else:
pix_per_cell = self.conf['pix_per_cell']
cell_per_block = self.conf['cell_per_block']
features = hog(img[:,:,channel], orientations=self.conf['orient'],
pixels_per_cell=(pix_per_cell, pix_per_cell),
cells_per_block=(cell_per_block, cell_per_block),
block_norm= 'L2-Hys',
transform_sqrt=False,
visualise=False, feature_vector=True)
hog_features.append(features)
hog_features = np.ravel(hog_features)
return hog_features
# Define a function to compute binned color features
def calc_spatial_features(self, img, size=(32, 32)):
# Use cv2.resize().ravel() to create the feature vector
features = cv2.resize(img, size).ravel()
# Return the feature vector
return features
# Define a function to compute color histogram features
def calc_color_features(self, img, nbins=32, bins_range=(0, 255)):
# Compute the histogram of the color channels separately
channel1_hist = np.histogram(img[:,:,0], bins=nbins, range=bins_range)
channel2_hist = np.histogram(img[:,:,1], bins=nbins, range=bins_range)
channel3_hist = np.histogram(img[:,:,2], bins=nbins, range=bins_range)
#print('Max {} {} {}'.format(channel1_hist[0],channel2_hist[0],channel3_hist[0]))
# Concatenate the histograms into a single feature vector
hist_features = np.concatenate((channel1_hist[0], channel2_hist[0], channel3_hist[0]))
# Return the individual histograms, bin_centers and feature vector
return hist_features
def calc_features(self, img):
features = []
# spatial features
if self.conf['spatial_feat']:
spatial_features = self.calc_spatial_features(img, size=self.conf['spatial_size'])
features.append(spatial_features)
# color histogram features
if self.conf['hist_feat']:
# Apply color_hist()
hist_features = self.calc_color_features(img, nbins=self.conf['hist_bins'])
features.append(hist_features)
# hog features
if self.conf['hog_feat']:
# Call get_hog_features() with vis=False, feature_vec=True
hog_features = self.calc_hog_features(img)
# Append the new feature vector to the features list
features.append(hog_features)
features = np.concatenate(features)
return features
|
[
"cv2.resize",
"numpy.ravel",
"skimage.feature.hog",
"numpy.histogram",
"cv2.HOGDescriptor",
"numpy.concatenate"
] |
[((1537, 1559), 'numpy.ravel', 'np.ravel', (['hog_features'], {}), '(hog_features)\n', (1545, 1559), True, 'import numpy as np\n'), ((2102, 2158), 'numpy.histogram', 'np.histogram', (['img[:, :, 0]'], {'bins': 'nbins', 'range': 'bins_range'}), '(img[:, :, 0], bins=nbins, range=bins_range)\n', (2114, 2158), True, 'import numpy as np\n'), ((2181, 2237), 'numpy.histogram', 'np.histogram', (['img[:, :, 1]'], {'bins': 'nbins', 'range': 'bins_range'}), '(img[:, :, 1], bins=nbins, range=bins_range)\n', (2193, 2237), True, 'import numpy as np\n'), ((2260, 2316), 'numpy.histogram', 'np.histogram', (['img[:, :, 2]'], {'bins': 'nbins', 'range': 'bins_range'}), '(img[:, :, 2], bins=nbins, range=bins_range)\n', (2272, 2316), True, 'import numpy as np\n'), ((2497, 2567), 'numpy.concatenate', 'np.concatenate', (['(channel1_hist[0], channel2_hist[0], channel3_hist[0])'], {}), '((channel1_hist[0], channel2_hist[0], channel3_hist[0]))\n', (2511, 2567), True, 'import numpy as np\n'), ((3482, 3506), 'numpy.concatenate', 'np.concatenate', (['features'], {}), '(features)\n', (3496, 3506), True, 'import numpy as np\n'), ((699, 866), 'cv2.HOGDescriptor', 'cv2.HOGDescriptor', ([], {'_winSize': 'winSize', '_blockSize': 'blockSize', '_blockStride': 'blockStride', '_cellSize': 'pix_per_cell', '_nbins': "self.conf['orient']", '_signedGradient': '(False)'}), "(_winSize=winSize, _blockSize=blockSize, _blockStride=\n blockStride, _cellSize=pix_per_cell, _nbins=self.conf['orient'],\n _signedGradient=False)\n", (716, 866), False, 'import cv2\n'), ((1101, 1349), 'skimage.feature.hog', 'hog', (['img[:, :, channel]'], {'orientations': "self.conf['orient']", 'pixels_per_cell': '(pix_per_cell, pix_per_cell)', 'cells_per_block': '(cell_per_block, cell_per_block)', 'block_norm': '"""L2-Hys"""', 'transform_sqrt': '(False)', 'visualise': '(False)', 'feature_vector': '(True)'}), "(img[:, :, channel], orientations=self.conf['orient'], pixels_per_cell=(\n pix_per_cell, pix_per_cell), cells_per_block=(cell_per_block,\n cell_per_block), block_norm='L2-Hys', transform_sqrt=False, visualise=\n False, feature_vector=True)\n", (1104, 1349), False, 'from skimage.feature import hog\n'), ((1789, 1810), 'cv2.resize', 'cv2.resize', (['img', 'size'], {}), '(img, size)\n', (1799, 1810), False, 'import cv2\n')]
|
import warnings
from typing import Dict, List, Union
import numpy as np
import pandas as pd
from loguru import logger
from sklearn.ensemble import RandomForestClassifier
from sklearn.exceptions import ConvergenceWarning
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import f1_score, matthews_corrcoef, roc_auc_score
from sklearn.model_selection import KFold
from sklearn.neural_network import MLPClassifier
from sklearn.preprocessing import StandardScaler
from sklearn.tree import DecisionTreeClassifier
from . import utils
from .patient_data import BOOL_FEATS_LIST, NUM_FEATS_LIST, TARGET_NAME, PatientData
# noinspection PyPep8Naming
class EnsembleModel:
"""
This class represents a dynamic ensemble model as average of probability predictions
of the following models:
[LogisticRegression, DecisionTreeClassifier, RandomForestClassifier, MLPClassifier]
"""
NUM_MODELS = 4
def __init__(self):
self.num_folds = None
self.seed = None
self.predict_threshold = None
self.scaler = None
self.models: List[
Union[
LogisticRegression,
DecisionTreeClassifier,
RandomForestClassifier,
MLPClassifier,
]
] = []
self._trained = False
def train(
self,
data_path: str,
num_folds: int = 5,
seed: int = 72,
) -> Dict[str, float]:
"""
Trains a simple ensemble model of [LogisticRegression, DecisionTreeClassifier,
RandomForestClassifier, MLPClassifier] classifiers.
Average of models probability predictions is used as an ensemble.
:param data_path: path to the training file
:param num_folds: number of folds to be trained in the cross-validation setting
:param seed: random state initialization seed
:return: Dict of s
"""
logger.info(f"Training Ensemble Model ...")
self.num_folds = num_folds
self.seed = seed
self.predict_threshold = None
self.scaler = None
self.models = []
self._trained = False
# ----------------------------
# LOADING AND PROCESSING DATA
# ----------------------------
df = pd.read_csv(data_path)
logger.info(f"Dataset shape: {df.shape}")
X, y = self.preprocess_training_data(df=df)
logger.info(f"Target distribution:")
utils.log_multiple_string_obj(df.groupby(TARGET_NAME).size())
"""
Setting predict threshold. Ideally, it should be optimized based on Out of Fold
predictions. For simplicity target ration is used.
"""
self.predict_threshold = y.sum() / y.shape[0]
# -----------------------
# TRAINING K-FOLD MODELS
# -----------------------
oof_predictions = np.zeros((X.shape[0], self.NUM_MODELS), dtype=np.float32)
kf = KFold(n_splits=self.num_folds, shuffle=True, random_state=self.seed)
for fold_inx, (trn_inx, val_inx) in enumerate(kf.split(y, y)):
logger.info(f"Training {fold_inx + 1} fold ...")
trn_X = X[trn_inx]
val_X = X[val_inx]
trn_y = y[trn_inx]
val_y = y[val_inx]
# Initializing and training models for the current fold
fold_models = [
LogisticRegression(random_state=self.seed),
DecisionTreeClassifier(random_state=self.seed),
RandomForestClassifier(random_state=self.seed),
MLPClassifier(random_state=self.seed),
]
for model_inx, model in enumerate(fold_models):
with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=ConvergenceWarning)
model = model.fit(X=trn_X, y=trn_y)
val_y_prob = model.predict_proba(X=val_X)[:, 1]
val_y_pred = val_y_prob >= self.predict_threshold
logger.info(
f"Fold {fold_inx + 1}, {model.__class__.__name__}: "
f"MCC={matthews_corrcoef(y_true=val_y, y_pred=val_y_pred):.4f}, "
f"F1={f1_score(y_true=val_y, y_pred=val_y_pred):.4f}, "
f"ROC_AUC={roc_auc_score(y_true=val_y, y_score=val_y_prob):.4f}"
)
oof_predictions[val_inx, model_inx] = val_y_prob
self.models.append(model)
# Computing Out of Fold validation metrics
y_prob = oof_predictions.mean(axis=-1)
y_pred = y_prob >= self.predict_threshold
oof_mcc_score = matthews_corrcoef(y_true=y, y_pred=y_pred)
oof_f1_score = f1_score(y_true=y, y_pred=y_pred)
oof_roc_auc_score = roc_auc_score(y_true=y, y_score=y_prob)
logger.info("######")
logger.info(
f"Out of Fold, EnsembleModel, "
f"MCC={oof_mcc_score:.4f}, "
f"F1={oof_f1_score:.4f}, "
f"ROC_AUC={oof_roc_auc_score:.4f}"
)
logger.info("######")
self._trained = True
return {
"MCC": oof_mcc_score,
"F1": oof_f1_score,
"ROC_AUC": oof_roc_auc_score,
}
def preprocess_training_data(self, df: pd.DataFrame) -> (np.ndarray, np.ndarray):
"""
Preprocesses training data with the following steps:
- Drops any rows that don't have a target value
- Fills nulls of numerical features with the average value
- Fills nulls of boolean features with the most common value
- Scales numerical features via StandardScaler
:param df: Training data in the Pandas DataFrame format
:return: Features and target numpy arrays ready to be used for training
"""
# -------------------
# PROCESS TARGET COL
# -------------------
target_na = df[TARGET_NAME].isna()
num_target_na = target_na.sum()
if num_target_na > 0:
logger.warning(
f"Target column {TARGET_NAME} has {num_target_na} missing values. "
f"Excluding rows with missing values from training."
)
df = df.loc[~target_na].reset_index(drop=True)
df[TARGET_NAME] = df[TARGET_NAME].astype(float)
# ------------------------
# PROCESS NUMERICAL FEATS
# ------------------------
for col_name in NUM_FEATS_LIST:
num_na = df[col_name].isna().sum()
if num_na > 0:
logger.warning(
f"Column {col_name} has {num_na} missing values. "
f"Replacing them with average value."
)
df[col_name].fillna(value=df[col_name].mean(), inplace=True)
df[col_name] = df[col_name].astype(float)
# ----------------------
# PROCESS BOOLEAN FEATS
# ----------------------
for col_name in BOOL_FEATS_LIST:
num_na = df[col_name].isna().sum()
if num_na > 0:
logger.warning(
f"Column {col_name} has {num_na} missing values. "
f"Replacing them with the most common value."
)
df[col_name].fillna(value=df[col_name].value_counts()[0], inplace=True)
df[col_name] = df[col_name].astype(dtype=float)
# ----------------------
# CONSTRUCT X,y MATRICES
# ----------------------
X = df[NUM_FEATS_LIST + BOOL_FEATS_LIST].values
y = df[TARGET_NAME].values
# ----------------------
# SCALING FEATURES
# ----------------------
"""
Fitting Standard Scaler. Ideally, it should be done within each validation fold,
but for simplicity fitting it on the whole dataset here.
Tree-based methods don't really require this scaling, but it won't harm their
performance.
"""
self.scaler = StandardScaler()
X[:, : len(NUM_FEATS_LIST)] = self.scaler.fit_transform(
X[:, : len(NUM_FEATS_LIST)]
)
return X, y
def data2feat_vector(self, data: PatientData) -> np.ndarray:
"""
Converts PatientData into feature vector suitable for model prediction
:param data: patient data
:return: patient feature vector in numpy format of shape (1, num_features)
"""
feat_vector = []
for feat_name in NUM_FEATS_LIST:
feat_vector.append(float(data[feat_name]))
for feat_name in BOOL_FEATS_LIST:
feat_vector.append(float(data[feat_name]))
feat_vector = np.asarray(feat_vector)[np.newaxis, :]
feat_vector[:, : len(NUM_FEATS_LIST)] = self.scaler.transform(
feat_vector[:, : len(NUM_FEATS_LIST)]
)
return feat_vector
def predict(self, data: PatientData) -> (float, bool):
"""
Makes ensemble model prediction on a new PatientData
Throws ValueError if models isn't trained yet.
:param data: patient data
:return: Death Event probability and prediction
"""
if not self._trained:
raise ValueError("Model isn't trained yet. Please, train model first.")
probs = np.empty(shape=len(self.models), dtype=np.float32)
feat_vector = self.data2feat_vector(data=data)
for model_inx, model in enumerate(self.models):
probs[model_inx] = model.predict_proba(X=feat_vector)[0, 1]
prob = probs.mean()
pred = prob >= self.predict_threshold
return prob, pred
|
[
"sklearn.ensemble.RandomForestClassifier",
"sklearn.preprocessing.StandardScaler",
"warnings.filterwarnings",
"pandas.read_csv",
"numpy.asarray",
"loguru.logger.warning",
"numpy.zeros",
"sklearn.model_selection.KFold",
"sklearn.metrics.roc_auc_score",
"sklearn.tree.DecisionTreeClassifier",
"loguru.logger.info",
"sklearn.metrics.f1_score",
"sklearn.metrics.matthews_corrcoef",
"sklearn.linear_model.LogisticRegression",
"warnings.catch_warnings",
"sklearn.neural_network.MLPClassifier"
] |
[((1938, 1981), 'loguru.logger.info', 'logger.info', (['f"""Training Ensemble Model ..."""'], {}), "(f'Training Ensemble Model ...')\n", (1949, 1981), False, 'from loguru import logger\n'), ((2292, 2314), 'pandas.read_csv', 'pd.read_csv', (['data_path'], {}), '(data_path)\n', (2303, 2314), True, 'import pandas as pd\n'), ((2323, 2364), 'loguru.logger.info', 'logger.info', (['f"""Dataset shape: {df.shape}"""'], {}), "(f'Dataset shape: {df.shape}')\n", (2334, 2364), False, 'from loguru import logger\n'), ((2427, 2463), 'loguru.logger.info', 'logger.info', (['f"""Target distribution:"""'], {}), "(f'Target distribution:')\n", (2438, 2463), False, 'from loguru import logger\n'), ((2889, 2946), 'numpy.zeros', 'np.zeros', (['(X.shape[0], self.NUM_MODELS)'], {'dtype': 'np.float32'}), '((X.shape[0], self.NUM_MODELS), dtype=np.float32)\n', (2897, 2946), True, 'import numpy as np\n'), ((2960, 3028), 'sklearn.model_selection.KFold', 'KFold', ([], {'n_splits': 'self.num_folds', 'shuffle': '(True)', 'random_state': 'self.seed'}), '(n_splits=self.num_folds, shuffle=True, random_state=self.seed)\n', (2965, 3028), False, 'from sklearn.model_selection import KFold\n'), ((4666, 4708), 'sklearn.metrics.matthews_corrcoef', 'matthews_corrcoef', ([], {'y_true': 'y', 'y_pred': 'y_pred'}), '(y_true=y, y_pred=y_pred)\n', (4683, 4708), False, 'from sklearn.metrics import f1_score, matthews_corrcoef, roc_auc_score\n'), ((4732, 4765), 'sklearn.metrics.f1_score', 'f1_score', ([], {'y_true': 'y', 'y_pred': 'y_pred'}), '(y_true=y, y_pred=y_pred)\n', (4740, 4765), False, 'from sklearn.metrics import f1_score, matthews_corrcoef, roc_auc_score\n'), ((4794, 4833), 'sklearn.metrics.roc_auc_score', 'roc_auc_score', ([], {'y_true': 'y', 'y_score': 'y_prob'}), '(y_true=y, y_score=y_prob)\n', (4807, 4833), False, 'from sklearn.metrics import f1_score, matthews_corrcoef, roc_auc_score\n'), ((4842, 4863), 'loguru.logger.info', 'logger.info', (['"""######"""'], {}), "('######')\n", (4853, 4863), False, 'from loguru import logger\n'), ((4872, 5005), 'loguru.logger.info', 'logger.info', (['f"""Out of Fold, EnsembleModel, MCC={oof_mcc_score:.4f}, F1={oof_f1_score:.4f}, ROC_AUC={oof_roc_auc_score:.4f}"""'], {}), "(\n f'Out of Fold, EnsembleModel, MCC={oof_mcc_score:.4f}, F1={oof_f1_score:.4f}, ROC_AUC={oof_roc_auc_score:.4f}'\n )\n", (4883, 5005), False, 'from loguru import logger\n'), ((5074, 5095), 'loguru.logger.info', 'logger.info', (['"""######"""'], {}), "('######')\n", (5085, 5095), False, 'from loguru import logger\n'), ((8026, 8042), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (8040, 8042), False, 'from sklearn.preprocessing import StandardScaler\n'), ((3112, 3160), 'loguru.logger.info', 'logger.info', (['f"""Training {fold_inx + 1} fold ..."""'], {}), "(f'Training {fold_inx + 1} fold ...')\n", (3123, 3160), False, 'from loguru import logger\n'), ((6055, 6197), 'loguru.logger.warning', 'logger.warning', (['f"""Target column {TARGET_NAME} has {num_target_na} missing values. Excluding rows with missing values from training."""'], {}), "(\n f'Target column {TARGET_NAME} has {num_target_na} missing values. Excluding rows with missing values from training.'\n )\n", (6069, 6197), False, 'from loguru import logger\n'), ((8708, 8731), 'numpy.asarray', 'np.asarray', (['feat_vector'], {}), '(feat_vector)\n', (8718, 8731), True, 'import numpy as np\n'), ((3399, 3441), 'sklearn.linear_model.LogisticRegression', 'LogisticRegression', ([], {'random_state': 'self.seed'}), '(random_state=self.seed)\n', (3417, 3441), False, 'from sklearn.linear_model import LogisticRegression\n'), ((3459, 3505), 'sklearn.tree.DecisionTreeClassifier', 'DecisionTreeClassifier', ([], {'random_state': 'self.seed'}), '(random_state=self.seed)\n', (3481, 3505), False, 'from sklearn.tree import DecisionTreeClassifier\n'), ((3523, 3569), 'sklearn.ensemble.RandomForestClassifier', 'RandomForestClassifier', ([], {'random_state': 'self.seed'}), '(random_state=self.seed)\n', (3545, 3569), False, 'from sklearn.ensemble import RandomForestClassifier\n'), ((3587, 3624), 'sklearn.neural_network.MLPClassifier', 'MLPClassifier', ([], {'random_state': 'self.seed'}), '(random_state=self.seed)\n', (3600, 3624), False, 'from sklearn.neural_network import MLPClassifier\n'), ((6588, 6698), 'loguru.logger.warning', 'logger.warning', (['f"""Column {col_name} has {num_na} missing values. Replacing them with average value."""'], {}), "(\n f'Column {col_name} has {num_na} missing values. Replacing them with average value.'\n )\n", (6602, 6698), False, 'from loguru import logger\n'), ((7113, 7231), 'loguru.logger.warning', 'logger.warning', (['f"""Column {col_name} has {num_na} missing values. Replacing them with the most common value."""'], {}), "(\n f'Column {col_name} has {num_na} missing values. Replacing them with the most common value.'\n )\n", (7127, 7231), False, 'from loguru import logger\n'), ((3721, 3746), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {}), '()\n', (3744, 3746), False, 'import warnings\n'), ((3768, 3830), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {'category': 'ConvergenceWarning'}), "('ignore', category=ConvergenceWarning)\n", (3791, 3830), False, 'import warnings\n'), ((4147, 4197), 'sklearn.metrics.matthews_corrcoef', 'matthews_corrcoef', ([], {'y_true': 'val_y', 'y_pred': 'val_y_pred'}), '(y_true=val_y, y_pred=val_y_pred)\n', (4164, 4197), False, 'from sklearn.metrics import f1_score, matthews_corrcoef, roc_auc_score\n'), ((4232, 4273), 'sklearn.metrics.f1_score', 'f1_score', ([], {'y_true': 'val_y', 'y_pred': 'val_y_pred'}), '(y_true=val_y, y_pred=val_y_pred)\n', (4240, 4273), False, 'from sklearn.metrics import f1_score, matthews_corrcoef, roc_auc_score\n'), ((4313, 4360), 'sklearn.metrics.roc_auc_score', 'roc_auc_score', ([], {'y_true': 'val_y', 'y_score': 'val_y_prob'}), '(y_true=val_y, y_score=val_y_prob)\n', (4326, 4360), False, 'from sklearn.metrics import f1_score, matthews_corrcoef, roc_auc_score\n')]
|
import random
from pathlib import Path
from typing import Iterator
import numpy as np
import torch.utils.data
from torch import nn
from torch.utils.data.dataset import T_co
from torch.nn import functional as F
class RandomShiftsAug(nn.Module):
def __init__(self, pad):
super().__init__()
self.pad = pad
def forward(self, x):
n, c, h, w = x.size()
assert h == w
padding = tuple([self.pad] * 4)
x = F.pad(x, padding, 'replicate')
eps = 1.0 / (h + 2 * self.pad)
arange = torch.linspace(-1.0 + eps,
1.0 - eps,
h + 2 * self.pad,
device=x.device,
dtype=x.dtype)[:h]
arange = arange.unsqueeze(0).repeat(h, 1).unsqueeze(2)
base_grid = torch.cat([arange, arange.transpose(1, 0)], dim=2)
base_grid = base_grid.unsqueeze(0).repeat(n, 1, 1, 1)
shift = torch.randint(0,
2 * self.pad + 1,
size=(n, 1, 1, 2),
device=x.device,
dtype=x.dtype)
shift *= 2.0 / (h + 2 * self.pad)
grid = base_grid + shift
return F.grid_sample(x,
grid,
padding_mode='zeros',
align_corners=False)
class CTVideoDataset(torch.utils.data.IterableDataset):
def __init__(self, root, episode_len, cam_ids, same_video=False):
self._root = Path(root)
self._files = list(self._root.iterdir())
self._episode_len = episode_len
self._same_video = same_video
self._cam_ids = cam_ids
def _sample(self):
if len(self._cam_ids) > 1:
cam1, cam2 = random.sample(self._cam_ids, k=2)
else:
cam1, cam2 = 0, 0
videos1, videos2 = random.choices(self._files, k=2)
video1 = np.load(videos1)[cam1, :self._episode_len]
video2 = np.load(videos1 if self._same_video else videos2)[cam2, :self._episode_len]
video1 = video1.transpose(0, 3, 1, 2).copy()
video2 = video2.transpose(0, 3, 1, 2).copy()
return video1, video2
def __iter__(self) -> Iterator[T_co]:
while True:
yield self._sample()
class ViRLVideoDataset(torch.utils.data.IterableDataset):
def __init__(self, root, episode_len, cam_ids):
self._root = Path(root)
self._num_classes = len(list(self._root.iterdir()))
self._files = []
for c in range(self._num_classes):
class_dir = self._root / str(c)
self._files.append(list(class_dir.iterdir()))
self._episode_len = episode_len
self._cam_ids = cam_ids
def _sample(self):
if len(self._cam_ids) > 1:
cam1, cam2, cam3 = random.sample(self._cam_ids, k=3)
else:
cam1, cam2, cam3 = 0, 0, 0
classes = list(range(self._num_classes))
class_1 = random.choice(classes)
classes.remove(class_1)
class_2 = random.choice(classes)
video_i, video_p = random.choices(self._files[class_1], k=2)
video_n = random.choice(self._files[class_2])
video_i = np.load(video_i)[cam1, :self._episode_len]
video_p = np.load(video_p)[cam2, :self._episode_len]
video_n = np.load(video_n)[cam3, :self._episode_len]
video_i = video_i.transpose(0, 3, 1, 2).copy()
video_p = video_p.transpose(0, 3, 1, 2).copy()
video_n = video_n.transpose(0, 3, 1, 2).copy()
return video_i, video_p, video_n
@staticmethod
def augment(video_i: torch.Tensor, video_p: torch.Tensor, video_n: torch.Tensor):
# video_i, video_p, video_n = ViRLVideoDataset.augment_images(video_i, video_p, video_n)
# video_i, video_p, video_n = ViRLVideoDataset.add_noise(video_i, video_p, video_n)
video_i, video_p, video_n = ViRLVideoDataset.random_shuffle(video_i, video_p, video_n)
video_i, video_p, video_n = ViRLVideoDataset.random_sequence_cropping(video_i, video_p, video_n)
return video_i, video_p, video_n
@staticmethod
def augment_images(video_i: torch.Tensor, video_p: torch.Tensor, video_n: torch.Tensor):
aug = RandomShiftsAug(pad=8)
T = video_i.shape[0]
video_1, video_2, video_3 = [], [], []
for t in range(T):
frame_1, frame_2, frame_3 = video_i[t], video_p[t], video_n[t]
frame_1, frame_2, frame_3 = aug(frame_1), aug(frame_2), aug(frame_3)
video_1.append(frame_1)
video_2.append(frame_2)
video_3.append(frame_3)
video_1 = torch.stack(video_1)
video_2 = torch.stack(video_2)
video_3 = torch.stack(video_3)
return video_1, video_2, video_3
@staticmethod
def add_noise(video_i: torch.Tensor, video_p: torch.Tensor, video_n: torch.Tensor, mean=128., std=0.02):
video_1 = video_i + torch.normal(mean, std, video_i.shape, device=video_i.device)
video_2 = video_p + torch.normal(mean, std, video_p.shape, device=video_p.device)
video_3 = video_n + torch.normal(mean, std, video_n.shape, device=video_n.device)
video_1 = torch.clip(video_1, 0., 255.)
video_2 = torch.clip(video_2, 0., 255.)
video_3 = torch.clip(video_3, 0., 255.)
return video_1, video_2, video_3
@staticmethod
def random_shuffle(video_i: torch.Tensor, video_p: torch.Tensor, video_n: torch.Tensor, p=0.5):
shuffle = np.random.rand() > p
if shuffle:
indx = torch.randperm(video_i.shape[0])
video_i = video_i[indx]
video_p = video_p[indx]
video_n = video_n[indx]
return video_i, video_p, video_n
@staticmethod
def random_sequence_cropping(video_i: torch.Tensor, video_p: torch.Tensor, video_n: torch.Tensor):
T = video_i.shape[0]
base = sum(list(range(T)))
p_list = [(T - i)/base for i in range(T)]
video_1, video_2, video_3 = [], [], []
for i in range(T):
keep = np.random.rand() > p_list[i]
if keep:
video_1.append(video_i[i])
video_2.append(video_p[i])
video_3.append(video_n[i])
video_1 = torch.stack(video_1)
video_2 = torch.stack(video_2)
video_3 = torch.stack(video_3)
return video_1, video_2, video_3
def __iter__(self) -> Iterator[T_co]:
while True:
yield self._sample()
|
[
"numpy.load",
"torch.nn.functional.grid_sample",
"random.sample",
"random.choices",
"random.choice",
"pathlib.Path",
"numpy.random.rand",
"torch.nn.functional.pad"
] |
[((457, 487), 'torch.nn.functional.pad', 'F.pad', (['x', 'padding', '"""replicate"""'], {}), "(x, padding, 'replicate')\n", (462, 487), True, 'from torch.nn import functional as F\n'), ((1274, 1339), 'torch.nn.functional.grid_sample', 'F.grid_sample', (['x', 'grid'], {'padding_mode': '"""zeros"""', 'align_corners': '(False)'}), "(x, grid, padding_mode='zeros', align_corners=False)\n", (1287, 1339), True, 'from torch.nn import functional as F\n'), ((1576, 1586), 'pathlib.Path', 'Path', (['root'], {}), '(root)\n', (1580, 1586), False, 'from pathlib import Path\n'), ((1937, 1969), 'random.choices', 'random.choices', (['self._files'], {'k': '(2)'}), '(self._files, k=2)\n', (1951, 1969), False, 'import random\n'), ((2491, 2501), 'pathlib.Path', 'Path', (['root'], {}), '(root)\n', (2495, 2501), False, 'from pathlib import Path\n'), ((3052, 3074), 'random.choice', 'random.choice', (['classes'], {}), '(classes)\n', (3065, 3074), False, 'import random\n'), ((3125, 3147), 'random.choice', 'random.choice', (['classes'], {}), '(classes)\n', (3138, 3147), False, 'import random\n'), ((3176, 3217), 'random.choices', 'random.choices', (['self._files[class_1]'], {'k': '(2)'}), '(self._files[class_1], k=2)\n', (3190, 3217), False, 'import random\n'), ((3236, 3271), 'random.choice', 'random.choice', (['self._files[class_2]'], {}), '(self._files[class_2])\n', (3249, 3271), False, 'import random\n'), ((1831, 1864), 'random.sample', 'random.sample', (['self._cam_ids'], {'k': '(2)'}), '(self._cam_ids, k=2)\n', (1844, 1864), False, 'import random\n'), ((1988, 2004), 'numpy.load', 'np.load', (['videos1'], {}), '(videos1)\n', (1995, 2004), True, 'import numpy as np\n'), ((2048, 2097), 'numpy.load', 'np.load', (['(videos1 if self._same_video else videos2)'], {}), '(videos1 if self._same_video else videos2)\n', (2055, 2097), True, 'import numpy as np\n'), ((2896, 2929), 'random.sample', 'random.sample', (['self._cam_ids'], {'k': '(3)'}), '(self._cam_ids, k=3)\n', (2909, 2929), False, 'import random\n'), ((3291, 3307), 'numpy.load', 'np.load', (['video_i'], {}), '(video_i)\n', (3298, 3307), True, 'import numpy as np\n'), ((3352, 3368), 'numpy.load', 'np.load', (['video_p'], {}), '(video_p)\n', (3359, 3368), True, 'import numpy as np\n'), ((3413, 3429), 'numpy.load', 'np.load', (['video_n'], {}), '(video_n)\n', (3420, 3429), True, 'import numpy as np\n'), ((5595, 5611), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (5609, 5611), True, 'import numpy as np\n'), ((6167, 6183), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (6181, 6183), True, 'import numpy as np\n')]
|
# Copyright (c) 2021, 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.
#
# author: <NAME> (<EMAIL>)
import tensorflow as tf
import os
import json
import numpy as np
from collections import namedtuple
np_type_to_tf_type = {np.int8: tf.int8, np.int16: tf.int16, np.int32: tf.int32}
def get_categorical_feature_type(size):
types = (np.int8, np.int16, np.int32)
for numpy_type in types:
if size < np.iinfo(numpy_type).max:
return numpy_type
raise RuntimeError(
f'Categorical feature of size {size} is too large for defined types'
)
def create_reader(filename, bytes_per_batch):
fd = os.open(filename, os.O_RDONLY)
file_len = os.fstat(fd).st_size
os.close(fd)
num_batches = int(file_len / bytes_per_batch)
file_len_patched = num_batches * bytes_per_batch
footer_bytes = file_len - file_len_patched
reader = tf.data.FixedLengthRecordDataset(
filenames=[filename],
record_bytes=bytes_per_batch,
footer_bytes=footer_bytes
)
return reader, num_batches
DatasetMetadata = namedtuple(
'DatasetMetadata', ['num_numerical_features', 'categorical_cardinalities']
)
class DummyDataset:
def __init__(
self, batch_size, num_numerical_features, num_categorical_features,
num_batches
):
self.num_batches = num_batches
self.num_numerical_features = num_numerical_features
self.num_categorical_features = num_categorical_features
self.batch_size = batch_size
def __len__(self):
return self.num_batches
def __iter__(self):
return self
def __next__(self):
with tf.device('/GPU:0'):
factor = tf.random.uniform(
shape=[1], minval=0, maxval=1, dtype=tf.int32
)
if self.num_numerical_features > 0:
numerical = tf.ones(
shape=[self.batch_size, self.num_numerical_features],
dtype=tf.float16
)
numerical = numerical * tf.cast(factor, tf.float16)
else:
numerical = None
categorical = []
for _ in range(self.num_categorical_features):
f = tf.ones(shape=[self.batch_size, 1], dtype=tf.int32)
f = f * factor
categorical.append(f)
labels = tf.ones(shape=[self.batch_size, 1], dtype=tf.int8)
labels = labels * tf.cast(factor, tf.int8)
return (numerical, categorical), labels
def get_next(self):
return self.__next__()
def op(self):
return self
@staticmethod
def get_metadata(FLAGS):
cardinalities = [int(d) for d in FLAGS.synthetic_dataset_cardinalities]
metadata = DatasetMetadata(
num_numerical_features=FLAGS.num_numerical_features,
categorical_cardinalities=cardinalities
)
return metadata
class TfRawBinaryDataset:
"""Dataset for reading labels, numerical and categorical features from
a set of binary files. Internally uses TensorFlow's FixedLengthRecordDataset
and decode_raw for best performance.
Args:
data_path (str): Full path to split binary file of dataset. It must contain numerical.bin, label.bin and
cat_0 ~ cat_25.bin
batch_size (int):
numerical_features(boolean): Number of numerical features to load, default=0 (don't load any)
categorical_features (list or None): categorical features used by the rank (IDs of the features)
prefetch_depth (int): How many samples to prefetch. Default 10.
"""
def __init__(
self,
data_path,
batch_size=1,
numerical_features=0,
categorical_features=None,
prefetch_depth=10
):
self._batch_size = batch_size
self._data_path = data_path
self._prefetch_depth = prefetch_depth
self._numerical_features = numerical_features
self._categorical_ids = categorical_features
self._initialize_label_reader()
self._initialize_numerical_reader()
self._initialize_categorical_reader()
@classmethod
def get_metadata(cls, path, num_numerical_features):
with open(os.path.join(path, 'model_size.json'), 'r') as f:
global_table_sizes = json.load(f)
global_table_sizes = list(global_table_sizes.values())
global_table_sizes = [s + 1 for s in global_table_sizes]
metadata = DatasetMetadata(
num_numerical_features=num_numerical_features,
categorical_cardinalities=global_table_sizes
)
return metadata
def __len__(self):
return self.num_batches
def _initialize_label_reader(self):
bytes_per_sample = np.dtype(np.bool).itemsize
label_filename = os.path.join(self._data_path, f'label.bin')
self._label, self.num_batches = create_reader(
label_filename, bytes_per_sample * self._batch_size
)
def _initialize_numerical_reader(self):
bytes_per_sample = self._numerical_features * np.dtype(
np.float16
).itemsize
if self._numerical_features > 0:
num_filename = os.path.join(self._data_path, 'numerical.bin')
self._numerical, batches = create_reader(
num_filename, bytes_per_sample * self._batch_size
)
if batches != self.num_batches:
raise ValueError(
f'Size mismatch. Expected: {self.num_batches}, got: {batches}'
)
else:
self._numerical = tuple()
def _load_feature_sizes(self):
sizes_path = os.path.join(self._data_path, '../model_size.json')
with open(sizes_path) as f:
all_table_sizes = json.load(f)
all_table_sizes = list(all_table_sizes.values())
all_table_sizes = [s + 1 for s in all_table_sizes]
self._categorical_sizes = [
all_table_sizes[cat_id] for cat_id in self._categorical_ids
]
def _initialize_categorical_reader(self):
self._load_feature_sizes()
categorical_types = [
get_categorical_feature_type(size)
for size in self._categorical_sizes
]
self._categorical = []
for cat_id, cat_type in zip(self._categorical_ids, categorical_types):
path = os.path.join(self._data_path, f'cat_{cat_id}.bin')
bytes_per_sample = np.dtype(cat_type).itemsize
reader, batches = create_reader(
path, bytes_per_sample * self._batch_size
)
if batches != self.num_batches:
raise ValueError(
f'Size mismatch. Expected: {self.num_batches}, got: {batches}'
)
self._categorical.append(reader)
self._categorical = tuple(self._categorical)
# memorize for decoding
self._categorical_types = [
np_type_to_tf_type[np_type] for np_type in categorical_types
]
self._categorical_types_numpy = categorical_types
def op(self):
pipeline = tf.data.Dataset.zip(
(self._label, self._numerical, self._categorical)
)
pipeline = pipeline.map(
self.decode_batch, num_parallel_calls=tf.data.AUTOTUNE
)
pipeline = pipeline.batch(batch_size=1)
pipeline = pipeline.apply(
tf.data.experimental.prefetch_to_device(f'/gpu:0')
)
pipeline = pipeline.unbatch()
return pipeline
@tf.function
def decode_batch(self, labels, numerical_features, categorical_features):
#labels, numerical_features, categorical_features = batch
labels = tf.io.decode_raw(labels, out_type=tf.int8)
if self._numerical_features > 0:
numerical_features = tf.io.decode_raw(
numerical_features, out_type=tf.float16
)
numerical_features = tf.reshape(
numerical_features, shape=[-1, self._numerical_features]
)
if self._categorical_ids:
temp = []
for dtype, feature in zip(self._categorical_types,
categorical_features):
feature = tf.io.decode_raw(feature, out_type=dtype)
feature = tf.cast(feature, dtype=tf.int32)
feature = tf.expand_dims(feature, axis=1)
temp.append(feature)
categorical_features = tf.concat(temp, axis=1)
return (numerical_features, categorical_features), labels
|
[
"tensorflow.reshape",
"numpy.iinfo",
"os.close",
"os.path.join",
"tensorflow.random.uniform",
"tensorflow.concat",
"tensorflow.io.decode_raw",
"tensorflow.cast",
"tensorflow.data.FixedLengthRecordDataset",
"tensorflow.ones",
"os.open",
"tensorflow.data.Dataset.zip",
"os.fstat",
"tensorflow.expand_dims",
"tensorflow.data.experimental.prefetch_to_device",
"json.load",
"tensorflow.device",
"numpy.dtype",
"collections.namedtuple"
] |
[((1613, 1703), 'collections.namedtuple', 'namedtuple', (['"""DatasetMetadata"""', "['num_numerical_features', 'categorical_cardinalities']"], {}), "('DatasetMetadata', ['num_numerical_features',\n 'categorical_cardinalities'])\n", (1623, 1703), False, 'from collections import namedtuple\n'), ((1172, 1202), 'os.open', 'os.open', (['filename', 'os.O_RDONLY'], {}), '(filename, os.O_RDONLY)\n', (1179, 1202), False, 'import os\n'), ((1243, 1255), 'os.close', 'os.close', (['fd'], {}), '(fd)\n', (1251, 1255), False, 'import os\n'), ((1420, 1536), 'tensorflow.data.FixedLengthRecordDataset', 'tf.data.FixedLengthRecordDataset', ([], {'filenames': '[filename]', 'record_bytes': 'bytes_per_batch', 'footer_bytes': 'footer_bytes'}), '(filenames=[filename], record_bytes=\n bytes_per_batch, footer_bytes=footer_bytes)\n', (1452, 1536), True, 'import tensorflow as tf\n'), ((1218, 1230), 'os.fstat', 'os.fstat', (['fd'], {}), '(fd)\n', (1226, 1230), False, 'import os\n'), ((5387, 5430), 'os.path.join', 'os.path.join', (['self._data_path', 'f"""label.bin"""'], {}), "(self._data_path, f'label.bin')\n", (5399, 5430), False, 'import os\n'), ((6250, 6301), 'os.path.join', 'os.path.join', (['self._data_path', '"""../model_size.json"""'], {}), "(self._data_path, '../model_size.json')\n", (6262, 6301), False, 'import os\n'), ((7717, 7787), 'tensorflow.data.Dataset.zip', 'tf.data.Dataset.zip', (['(self._label, self._numerical, self._categorical)'], {}), '((self._label, self._numerical, self._categorical))\n', (7736, 7787), True, 'import tensorflow as tf\n'), ((8317, 8359), 'tensorflow.io.decode_raw', 'tf.io.decode_raw', (['labels'], {'out_type': 'tf.int8'}), '(labels, out_type=tf.int8)\n', (8333, 8359), True, 'import tensorflow as tf\n'), ((2191, 2210), 'tensorflow.device', 'tf.device', (['"""/GPU:0"""'], {}), "('/GPU:0')\n", (2200, 2210), True, 'import tensorflow as tf\n'), ((2233, 2297), 'tensorflow.random.uniform', 'tf.random.uniform', ([], {'shape': '[1]', 'minval': '(0)', 'maxval': '(1)', 'dtype': 'tf.int32'}), '(shape=[1], minval=0, maxval=1, dtype=tf.int32)\n', (2250, 2297), True, 'import tensorflow as tf\n'), ((2913, 2963), 'tensorflow.ones', 'tf.ones', ([], {'shape': '[self.batch_size, 1]', 'dtype': 'tf.int8'}), '(shape=[self.batch_size, 1], dtype=tf.int8)\n', (2920, 2963), True, 'import tensorflow as tf\n'), ((4882, 4894), 'json.load', 'json.load', (['f'], {}), '(f)\n', (4891, 4894), False, 'import json\n'), ((5335, 5352), 'numpy.dtype', 'np.dtype', (['np.bool'], {}), '(np.bool)\n', (5343, 5352), True, 'import numpy as np\n'), ((5780, 5826), 'os.path.join', 'os.path.join', (['self._data_path', '"""numerical.bin"""'], {}), "(self._data_path, 'numerical.bin')\n", (5792, 5826), False, 'import os\n'), ((6368, 6380), 'json.load', 'json.load', (['f'], {}), '(f)\n', (6377, 6380), False, 'import json\n'), ((6963, 7013), 'os.path.join', 'os.path.join', (['self._data_path', 'f"""cat_{cat_id}.bin"""'], {}), "(self._data_path, f'cat_{cat_id}.bin')\n", (6975, 7013), False, 'import os\n'), ((8015, 8065), 'tensorflow.data.experimental.prefetch_to_device', 'tf.data.experimental.prefetch_to_device', (['f"""/gpu:0"""'], {}), "(f'/gpu:0')\n", (8054, 8065), True, 'import tensorflow as tf\n'), ((8434, 8491), 'tensorflow.io.decode_raw', 'tf.io.decode_raw', (['numerical_features'], {'out_type': 'tf.float16'}), '(numerical_features, out_type=tf.float16)\n', (8450, 8491), True, 'import tensorflow as tf\n'), ((8555, 8623), 'tensorflow.reshape', 'tf.reshape', (['numerical_features'], {'shape': '[-1, self._numerical_features]'}), '(numerical_features, shape=[-1, self._numerical_features])\n', (8565, 8623), True, 'import tensorflow as tf\n'), ((9092, 9115), 'tensorflow.concat', 'tf.concat', (['temp'], {'axis': '(1)'}), '(temp, axis=1)\n', (9101, 9115), True, 'import tensorflow as tf\n'), ((951, 971), 'numpy.iinfo', 'np.iinfo', (['numpy_type'], {}), '(numpy_type)\n', (959, 971), True, 'import numpy as np\n'), ((2404, 2483), 'tensorflow.ones', 'tf.ones', ([], {'shape': '[self.batch_size, self.num_numerical_features]', 'dtype': 'tf.float16'}), '(shape=[self.batch_size, self.num_numerical_features], dtype=tf.float16)\n', (2411, 2483), True, 'import tensorflow as tf\n'), ((2770, 2821), 'tensorflow.ones', 'tf.ones', ([], {'shape': '[self.batch_size, 1]', 'dtype': 'tf.int32'}), '(shape=[self.batch_size, 1], dtype=tf.int32)\n', (2777, 2821), True, 'import tensorflow as tf\n'), ((2994, 3018), 'tensorflow.cast', 'tf.cast', (['factor', 'tf.int8'], {}), '(factor, tf.int8)\n', (3001, 3018), True, 'import tensorflow as tf\n'), ((4799, 4836), 'os.path.join', 'os.path.join', (['path', '"""model_size.json"""'], {}), "(path, 'model_size.json')\n", (4811, 4836), False, 'import os\n'), ((5659, 5679), 'numpy.dtype', 'np.dtype', (['np.float16'], {}), '(np.float16)\n', (5667, 5679), True, 'import numpy as np\n'), ((7045, 7063), 'numpy.dtype', 'np.dtype', (['cat_type'], {}), '(cat_type)\n', (7053, 7063), True, 'import numpy as np\n'), ((8861, 8902), 'tensorflow.io.decode_raw', 'tf.io.decode_raw', (['feature'], {'out_type': 'dtype'}), '(feature, out_type=dtype)\n', (8877, 8902), True, 'import tensorflow as tf\n'), ((8929, 8961), 'tensorflow.cast', 'tf.cast', (['feature'], {'dtype': 'tf.int32'}), '(feature, dtype=tf.int32)\n', (8936, 8961), True, 'import tensorflow as tf\n'), ((8988, 9019), 'tensorflow.expand_dims', 'tf.expand_dims', (['feature'], {'axis': '(1)'}), '(feature, axis=1)\n', (9002, 9019), True, 'import tensorflow as tf\n'), ((2582, 2609), 'tensorflow.cast', 'tf.cast', (['factor', 'tf.float16'], {}), '(factor, tf.float16)\n', (2589, 2609), True, 'import tensorflow as tf\n')]
|
import os
import sys
sys.path.append("./")
sys.path.append("../")
sys.path.append("create_plots/")
import datetime as dt
import pandas as pd
import numpy as np
import matplotlib as mpl
from matplotlib.dates import num2date
import matplotlib.pyplot as plt
from scipy.stats import beta
import pickle
import pydarn
from pysolar.solar import get_altitude
import utils
import rad_fov
################################################
# Inputs date and radar name
################################################
Rad, Dn = "cvw", dt.datetime(2012,1,2)
LFS = "LFS/LFS_clustering_superdarn_data/"
gmm = True
a_name = "dbscan"
rads = [Rad]
dates = [Dn]
remove_file = False
maxGate = None
gate = 7
sza_thresh, wid = {"is":85., "gs":105.}, 1.
bin_thick = 1.
tag = False
scale = 1.
def get_data_pkl(rad, dn, conn):
local_file = "../data/%s_%s_scans.pickle"%(rad, dn.strftime("%Y-%m-%d"))
#utils.from_remote_FS(conn, local_file, LFS)
with open(local_file, "rb") as f: pkl = pickle.load(f)
dates, elvs = [], []
for d, e in zip(pkl["time"], pkl["elv"]):
dates.extend(num2date(d))
elvs.extend(e)
ox = pd.DataFrame()
ox["date"], ox["elevation"] = dates, elvs
return ox
def get_sza(row, lats, lons):
print(num2date(row.time), row.bmnum)
lat, lon = lats[int(row["bmnum"]), int(row["slist"])],\
lons[int(row["bmnum"]), int(row["slist"])]
dn = num2date(row["time"])
d = dn.replace(tzinfo=dt.timezone.utc)
sza = 90.-get_altitude(lat, lon, d)
return sza
def calculate_total_uncertainity(_is, _gs):
def calc_prob(m, l, th, low=True):
h, be = np.histogram(m, bins=l, density=True)
bc = np.diff(be)
idx = be[1:] < th if low else be[1:] > th
edges = (be[1:])[be[1:] < th] if low else (be[1:])[be[1:] > th]
pr = np.sum(h[idx]*bc[idx])
height = h[idx]
#return pr, h, be[1:], bc
return pr, height, edges, bc
L = len(np.unique(_is.sza)) if len(np.unique(_is.sza)) > len(np.unique(_gs.sza)) else len(np.unique(_gs.sza))
L = int(L/bin_thick)
pr_a, h_a, be_a, bc = calc_prob(_is.sza.tolist(), L, sza_thresh["is"], low=True)
pr_b, h_b, be_b, _ = calc_prob(_gs.sza.tolist(), L, sza_thresh["gs"], low=False)
out = []
for pa, pb, b in zip(h_a, h_b, bc):
if pa < pb: out.append(pa*b)
else: out.append(pb*b)
#prb = np.round(np.sum(out), 3)
prb = np.round(pr_a+pr_b, 3)
print("Total Uncertainty:", prb)
fig = plt.figure(figsize=(4, 4), dpi=100)
mpl.rcParams.update({"font.size": 10})
ax = fig.add_subplot(111)
ax.hist(_is.sza.tolist(), bins=L, histtype="step", color="red", density=True, alpha=0.5, label="IS")
ax.hist(_gs.sza.tolist(), bins=L, histtype="step", color="blue", density=True, alpha=0.5, label="GS")
ax.fill_between(be_a, y1=np.zeros(len(be_a)), y2=h_a, color="r", alpha=0.3, step="pre")
ax.fill_between(be_b, y1=np.zeros(len(be_b)), y2=h_b, color="b", alpha=0.3, step="pre")
#ax.fill_between(be_a, y1=np.zeros(len(be_a)), y2=out, color="violet", alpha=0.3, step="pre")
ax.legend(loc=1)
ax.axvline(sza_thresh["is"], color="r", ls="--", lw=0.6)
ax.axvline(sza_thresh["gs"], color="b", ls="--", lw=0.6)
ax.set_xlabel(r"SZA, $\chi$ ($^o$)")
ax.set_ylabel("Density of IS, GS")
ax.text(0.99, 1.03, r"$\theta$~ %.2f"%prb, ha="right", va="center", transform=ax.transAxes)
ax.text(0.01, 1.03, rads[0].upper()+", %s"%dates[0].strftime("%Y-%m-%d"), ha="left", va="center", transform=ax.transAxes)
png = "create_plots/images/detection_%s_%s.png"%(Rad, Dn.strftime("%Y%m%d"))
ax.set_ylim(0,.1)
if tag: png = png.replace(".png", ".missing.png")
fig.savefig(png, bbox_inches="tight")
return prb
def calculate_uq_elv(_is, _gs):
L = len(np.unique(_is.elv)) if len(np.unique(_is.elv)) > len(np.unique(_gs.elv)) else len(np.unique(_gs.elv))
L = int(L/5)
#pr_a, h_a, be_a, bc = calc_prob(_is.elv.tolist(), L, sza_thresh["is"], low=True)
#pr_b, h_b, be_b, _ = calc_prob(_gs.elv.tolist(), L, sza_thresh["gs"], low=False)
#out = []
#for pa, pb, b in zip(h_a, h_b, bc):
# if pa < pb: out.append(pa*b)
# else: out.append(pb*b)
#prb = np.round(np.sum(out), 3)
#prb = np.round(pr_a+pr_b, 3)
#print("Total Uncertainty:", prb)
fig = plt.figure(figsize=(4, 7), dpi=100)
mpl.rcParams.update({"font.size": 10})
ax = fig.add_subplot(211)
ax.set_xlabel(r"AoA, $\alpha$ ($^o$)")
ax.set_ylabel("Gate Location (IS)")
ax.hist2d(_is.elv.tolist(), _is.slist.tolist(), bins=(20,20), cmap=plt.cm.Greys, norm=mpl.colors.LogNorm())#, histtype="step", color="red", density=True, alpha=0.5, label="IS")
ax = fig.add_subplot(212)
ax.set_xlabel(r"AoA, $\alpha$ ($^o$)")
ax.set_ylabel("Gate Location (GS)")
ax.hist2d(_gs.elv.tolist(), _gs.slist.tolist(), bins=(20,20), cmap=plt.cm.Greys, norm=mpl.colors.LogNorm())#, histtype="step", color="blue", density=True, alpha=0.5, label="GS")
#ax.fill_between(be_a, y1=np.zeros(len(be_a)), y2=h_a, color="r", alpha=0.3, step="pre")
#ax.fill_between(be_b, y1=np.zeros(len(be_b)), y2=h_b, color="b", alpha=0.3, step="pre")
#ax.fill_between(be_a, y1=np.zeros(len(be_a)), y2=out, color="violet", alpha=0.3, step="pre")
#ax.legend(loc=1)
#ax.axvline(sza_thresh["is"], color="r", ls="--", lw=0.6)
#ax.axvline(sza_thresh["gs"], color="b", ls="--", lw=0.6)
ax.set_xlabel(r"AoA, $\alpha$ ($^o$)")
ax.set_ylabel("Gate Location")
#ax.text(0.99, 1.03, r"$\theta$~ %.2f"%prb, ha="right", va="center", transform=ax.transAxes)
#ax.text(0.01, 1.03, rads[0].upper()+", %s"%dates[0].strftime("%Y-%m-%d"), ha="left", va="center", transform=ax.transAxes)
png = "create_plots/images/uq_%s_%s.png"%(Rad, Dn.strftime("%Y%m%d"))
#ax.set_ylim(0,.1)
if tag: png = png.replace(".png", ".missing.png")
fig.savefig(png, bbox_inches="tight")
return
pubfile = utils.get_pubfile()
conn = utils.get_session(key_filename=pubfile)
if gmm: fname = "../outputs/figures_for_papers/{rad}.{a_name}.gmm.{dn}.csv"
else: fname = "../outputs/figures_for_papers/{rad}.{a_name}.{dn}.csv"
if tag: fname = fname.replace(".csv", ".missing.csv")
for rad, dn in zip(rads, dates):
ox = get_data_pkl(rad, dn, conn)
floc = fname.format(rad=rad, a_name=a_name, dn=dn.strftime("%Y%m%d"))
if not os.path.exists(floc): utils.fetch_file(conn, floc, LFS)
X = pd.read_csv(floc)
hdw = pydarn.read_hdw_file(rad)
egate = hdw.gates if not maxGate else maxGate
rfov = rad_fov.CalcFov(hdw=hdw, ngates=egate)
if "sza" not in X.columns:
X["sza"] = X.apply(lambda r: get_sza(r, rfov.latFull, rfov.lonFull), axis=1)
X.to_csv(floc)
X = utils._run_riberio_threshold_on_rad(X)
X["elv"] = ox.elevation
print(X.head())
conn.close()
if remove_file: os.system("rm -rf ../outputs/cluster_tags/*")
X.sza = (np.array(X.sza)/wid).astype(int)*wid
X = X[X.slist > gate]
X = X[["sza", "ribiero_gflg", "elv", "slist"]]
_is, _gs = X[X.ribiero_gflg==0], X[X.ribiero_gflg==1]
#Pr_ab = calculate_total_uncertainity(_is, _gs)
calculate_uq_elv(_is, _gs)
|
[
"numpy.sum",
"pandas.read_csv",
"utils.fetch_file",
"matplotlib.pyplot.figure",
"pickle.load",
"numpy.histogram",
"matplotlib.colors.LogNorm",
"numpy.round",
"utils._run_riberio_threshold_on_rad",
"utils.get_session",
"numpy.unique",
"sys.path.append",
"pandas.DataFrame",
"matplotlib.rcParams.update",
"matplotlib.dates.num2date",
"os.path.exists",
"pysolar.solar.get_altitude",
"rad_fov.CalcFov",
"pydarn.read_hdw_file",
"os.system",
"datetime.datetime",
"utils.get_pubfile",
"numpy.diff",
"numpy.array"
] |
[((21, 42), 'sys.path.append', 'sys.path.append', (['"""./"""'], {}), "('./')\n", (36, 42), False, 'import sys\n'), ((43, 65), 'sys.path.append', 'sys.path.append', (['"""../"""'], {}), "('../')\n", (58, 65), False, 'import sys\n'), ((66, 98), 'sys.path.append', 'sys.path.append', (['"""create_plots/"""'], {}), "('create_plots/')\n", (81, 98), False, 'import sys\n'), ((5954, 5973), 'utils.get_pubfile', 'utils.get_pubfile', ([], {}), '()\n', (5971, 5973), False, 'import utils\n'), ((5981, 6020), 'utils.get_session', 'utils.get_session', ([], {'key_filename': 'pubfile'}), '(key_filename=pubfile)\n', (5998, 6020), False, 'import utils\n'), ((525, 548), 'datetime.datetime', 'dt.datetime', (['(2012)', '(1)', '(2)'], {}), '(2012, 1, 2)\n', (536, 548), True, 'import datetime as dt\n'), ((1128, 1142), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (1140, 1142), True, 'import pandas as pd\n'), ((1407, 1428), 'matplotlib.dates.num2date', 'num2date', (["row['time']"], {}), "(row['time'])\n", (1415, 1428), False, 'from matplotlib.dates import num2date\n'), ((2429, 2453), 'numpy.round', 'np.round', (['(pr_a + pr_b)', '(3)'], {}), '(pr_a + pr_b, 3)\n', (2437, 2453), True, 'import numpy as np\n'), ((2499, 2534), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(4, 4)', 'dpi': '(100)'}), '(figsize=(4, 4), dpi=100)\n', (2509, 2534), True, 'import matplotlib.pyplot as plt\n'), ((2539, 2577), 'matplotlib.rcParams.update', 'mpl.rcParams.update', (["{'font.size': 10}"], {}), "({'font.size': 10})\n", (2558, 2577), True, 'import matplotlib as mpl\n'), ((4339, 4374), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(4, 7)', 'dpi': '(100)'}), '(figsize=(4, 7), dpi=100)\n', (4349, 4374), True, 'import matplotlib.pyplot as plt\n'), ((4379, 4417), 'matplotlib.rcParams.update', 'mpl.rcParams.update', (["{'font.size': 10}"], {}), "({'font.size': 10})\n", (4398, 4417), True, 'import matplotlib as mpl\n'), ((6456, 6473), 'pandas.read_csv', 'pd.read_csv', (['floc'], {}), '(floc)\n', (6467, 6473), True, 'import pandas as pd\n'), ((6484, 6509), 'pydarn.read_hdw_file', 'pydarn.read_hdw_file', (['rad'], {}), '(rad)\n', (6504, 6509), False, 'import pydarn\n'), ((6571, 6609), 'rad_fov.CalcFov', 'rad_fov.CalcFov', ([], {'hdw': 'hdw', 'ngates': 'egate'}), '(hdw=hdw, ngates=egate)\n', (6586, 6609), False, 'import rad_fov\n'), ((6758, 6796), 'utils._run_riberio_threshold_on_rad', 'utils._run_riberio_threshold_on_rad', (['X'], {}), '(X)\n', (6793, 6796), False, 'import utils\n'), ((6874, 6919), 'os.system', 'os.system', (['"""rm -rf ../outputs/cluster_tags/*"""'], {}), "('rm -rf ../outputs/cluster_tags/*')\n", (6883, 6919), False, 'import os\n'), ((976, 990), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (987, 990), False, 'import pickle\n'), ((1244, 1262), 'matplotlib.dates.num2date', 'num2date', (['row.time'], {}), '(row.time)\n', (1252, 1262), False, 'from matplotlib.dates import num2date\n'), ((1486, 1511), 'pysolar.solar.get_altitude', 'get_altitude', (['lat', 'lon', 'd'], {}), '(lat, lon, d)\n', (1498, 1511), False, 'from pysolar.solar import get_altitude\n'), ((1632, 1669), 'numpy.histogram', 'np.histogram', (['m'], {'bins': 'l', 'density': '(True)'}), '(m, bins=l, density=True)\n', (1644, 1669), True, 'import numpy as np\n'), ((1683, 1694), 'numpy.diff', 'np.diff', (['be'], {}), '(be)\n', (1690, 1694), True, 'import numpy as np\n'), ((1830, 1854), 'numpy.sum', 'np.sum', (['(h[idx] * bc[idx])'], {}), '(h[idx] * bc[idx])\n', (1836, 1854), True, 'import numpy as np\n'), ((6392, 6412), 'os.path.exists', 'os.path.exists', (['floc'], {}), '(floc)\n', (6406, 6412), False, 'import os\n'), ((6414, 6447), 'utils.fetch_file', 'utils.fetch_file', (['conn', 'floc', 'LFS'], {}), '(conn, floc, LFS)\n', (6430, 6447), False, 'import utils\n'), ((1083, 1094), 'matplotlib.dates.num2date', 'num2date', (['d'], {}), '(d)\n', (1091, 1094), False, 'from matplotlib.dates import num2date\n'), ((1965, 1983), 'numpy.unique', 'np.unique', (['_is.sza'], {}), '(_is.sza)\n', (1974, 1983), True, 'import numpy as np\n'), ((2047, 2065), 'numpy.unique', 'np.unique', (['_gs.sza'], {}), '(_gs.sza)\n', (2056, 2065), True, 'import numpy as np\n'), ((3805, 3823), 'numpy.unique', 'np.unique', (['_is.elv'], {}), '(_is.elv)\n', (3814, 3823), True, 'import numpy as np\n'), ((3887, 3905), 'numpy.unique', 'np.unique', (['_gs.elv'], {}), '(_gs.elv)\n', (3896, 3905), True, 'import numpy as np\n'), ((4621, 4641), 'matplotlib.colors.LogNorm', 'mpl.colors.LogNorm', ([], {}), '()\n', (4639, 4641), True, 'import matplotlib as mpl\n'), ((4915, 4935), 'matplotlib.colors.LogNorm', 'mpl.colors.LogNorm', ([], {}), '()\n', (4933, 4935), True, 'import matplotlib as mpl\n'), ((1992, 2010), 'numpy.unique', 'np.unique', (['_is.sza'], {}), '(_is.sza)\n', (2001, 2010), True, 'import numpy as np\n'), ((2018, 2036), 'numpy.unique', 'np.unique', (['_gs.sza'], {}), '(_gs.sza)\n', (2027, 2036), True, 'import numpy as np\n'), ((3832, 3850), 'numpy.unique', 'np.unique', (['_is.elv'], {}), '(_is.elv)\n', (3841, 3850), True, 'import numpy as np\n'), ((3858, 3876), 'numpy.unique', 'np.unique', (['_gs.elv'], {}), '(_gs.elv)\n', (3867, 3876), True, 'import numpy as np\n'), ((6930, 6945), 'numpy.array', 'np.array', (['X.sza'], {}), '(X.sza)\n', (6938, 6945), True, 'import numpy as np\n')]
|
"""Unit tests for code in shared.py.
Copyright by <NAME>
Released under the MIT license - see LICENSE file for details
"""
from unittest import TestCase
import numpy as np
import proset.shared as shared
from test.test_set_manager import REFERENCE, PROTOTYPES, FEATURE_WEIGHTS # pylint: disable=wrong-import-order
FEATURE_NAMES = ["feature_1", "feature_2"]
# pylint: disable=missing-function-docstring, protected-access, too-many-public-methods
class TestShared(TestCase):
"""Unit tests for functions in shared.py.
"""
def test_check_classifier_target_fail_1(self):
message = ""
try:
shared.check_classifier_target(np.array([[0, 1]]))
except ValueError as ex:
message = ex.args[0]
self.assertEqual(message, "Parameter target must be a 1D array.")
def test_check_classifier_target_fail_2(self):
message = ""
try:
shared.check_classifier_target(np.array([0.0, 1.0]))
except TypeError as ex:
message = ex.args[0]
self.assertEqual(message, "Parameter target must be an integer array.")
def test_check_classifier_target_fail_3(self):
message = ""
try:
shared.check_classifier_target(np.array([0, 2]))
except ValueError as ex:
message = ex.args[0]
self.assertEqual(
message, "Parameter target must encode classes as integers from 0 to K - 1 and every class must be present."
)
@staticmethod
def test_check_classifier_target_1():
result = shared.check_classifier_target(np.array([0, 1, 1, 0, 2]))
np.testing.assert_allclose(result, np.array([2, 2, 1]))
@staticmethod
def test_find_changes_1():
result = shared.find_changes(np.array([0, 0, 1, 1, 1, 2]))
np.testing.assert_allclose(result, np.array([0, 2, 5]))
@staticmethod
def test_quick_compute_similarity_1():
scaled_reference = REFERENCE * FEATURE_WEIGHTS
scaled_prototypes = PROTOTYPES * FEATURE_WEIGHTS
similarity = shared.quick_compute_similarity(
scaled_reference=scaled_reference,
scaled_prototypes=scaled_prototypes,
ssq_reference=np.sum(scaled_reference ** 2.0, axis=1),
ssq_prototypes=np.sum(scaled_prototypes ** 2.0, axis=1)
)
reference_similarity = np.zeros((REFERENCE.shape[0], PROTOTYPES.shape[0]), dtype=float)
for i in range(REFERENCE.shape[0]):
for j in range(PROTOTYPES.shape[0]):
reference_similarity[i, j] = np.exp(
-0.5 * np.sum(((REFERENCE[i] - PROTOTYPES[j]) * FEATURE_WEIGHTS) ** 2.0)
)
np.testing.assert_allclose(similarity, reference_similarity)
def test_check_feature_names_fail_1(self):
message = ""
try:
shared.check_feature_names(num_features=1.0, feature_names=None, active_features=None)
except TypeError as ex:
message = ex.args[0]
self.assertEqual(message, "Parameter num_features must be integer.")
def test_check_feature_names_fail_2(self):
message = ""
try:
shared.check_feature_names(num_features=0, feature_names=None, active_features=None)
except ValueError as ex:
message = ex.args[0]
self.assertEqual(message, "Parameter num_features must be positive.")
def test_check_feature_names_fail_3(self):
message = ""
try:
shared.check_feature_names(num_features=1, feature_names=FEATURE_NAMES, active_features=None)
except ValueError as ex:
message = ex.args[0]
self.assertEqual(message, "Parameter feature_names must have one element per feature if not None.")
def test_check_feature_names_fail_4(self):
message = ""
try:
shared.check_feature_names(num_features=2, feature_names=None, active_features=np.array([[0, 1]]))
except ValueError as ex:
message = ex.args[0]
self.assertEqual(message, "Parameter active_features must be a 1D array.")
def test_check_feature_names_fail_5(self):
message = ""
try:
shared.check_feature_names(num_features=2, feature_names=None, active_features=np.array([0.0, 1.0]))
except TypeError as ex:
message = ex.args[0]
self.assertEqual(message, "Parameter active_features must be an integer array.")
def test_check_feature_names_fail_6(self):
message = ""
try:
shared.check_feature_names(num_features=2, feature_names=None, active_features=np.array([-1, 0]))
except ValueError as ex:
message = ex.args[0]
self.assertEqual(
message,
"Parameter active_features must contain non-negative numbers less than the total number of features."
)
def test_check_feature_names_fail_7(self):
message = ""
try:
shared.check_feature_names(num_features=2, feature_names=None, active_features=np.array([0, 2]))
except ValueError as ex:
message = ex.args[0]
self.assertEqual(
message,
"Parameter active_features must contain non-negative numbers less than the total number of features."
)
def test_check_feature_names_1(self):
result = shared.check_feature_names(num_features=2, feature_names=FEATURE_NAMES, active_features=None)
self.assertEqual(result, FEATURE_NAMES)
self.assertFalse(result is FEATURE_NAMES) # ensure result is a copy and not a reference to the original input
def test_check_feature_names_2(self):
result = shared.check_feature_names(num_features=2, feature_names=None, active_features=None)
self.assertEqual(result, ["X0", "X1"])
def test_check_feature_names_3(self):
result = shared.check_feature_names(num_features=2, feature_names=FEATURE_NAMES, active_features=np.array([1]))
self.assertEqual(result, [FEATURE_NAMES[1]])
def test_check_feature_names_4(self):
result = shared.check_feature_names(num_features=2, feature_names=None, active_features=np.array([1]))
self.assertEqual(result, ["X1"])
def test_check_scale_offset_fail_1(self):
message = ""
try:
shared.check_scale_offset(num_features=2.0, scale=None, offset=None)
except TypeError as ex:
message = ex.args[0]
self.assertEqual(message, "Parameter num_features must be integer.")
def test_check_scale_offset_fail_2(self):
message = ""
try:
shared.check_scale_offset(num_features=0, scale=None, offset=None)
except ValueError as ex:
message = ex.args[0]
self.assertEqual(message, "Parameter num_features must be positive.")
def test_check_scale_offset_fail_3(self):
message = ""
try:
shared.check_scale_offset(num_features=2, scale=np.array([[0.5, 2.0]]), offset=None)
except ValueError as ex:
message = ex.args[0]
self.assertEqual(message, "Parameter scale must be a 1D array.")
def test_check_scale_offset_fail_4(self):
message = ""
try:
shared.check_scale_offset(num_features=3, scale=np.array([0.5, 2.0]), offset=None)
except ValueError as ex:
message = ex.args[0]
self.assertEqual(message, "Parameter scale must have one element per feature.")
def test_check_scale_offset_fail_5(self):
message = ""
try:
shared.check_scale_offset(num_features=2, scale=np.array([0.0, 2.0]), offset=None)
except ValueError as ex:
message = ex.args[0]
self.assertEqual(message, "Parameter scale must have strictly positive elements.")
def test_check_scale_offset_fail_6(self):
message = ""
try:
shared.check_scale_offset(num_features=2, scale=np.array([0.5, 2.0]), offset=np.array([[-1.0, 1.0]]))
except ValueError as ex:
message = ex.args[0]
self.assertEqual(message, "Parameter offset must be a 1D array.")
def test_check_scale_offset_fail_7(self):
message = ""
try:
shared.check_scale_offset(num_features=3, scale=np.array([0.5, 2.0, 1.0]), offset=np.array([-1.0, 1.0]))
except ValueError as ex:
message = ex.args[0]
self.assertEqual(message, "Parameter offset must have one element per feature.")
def test_check_scale_offset_1(self):
scale_in = np.array([0.5, 2.0])
offset_in = np.array([-1.0, 1.0])
scale_out, offset_out = shared.check_scale_offset(num_features=2, scale=scale_in, offset=offset_in)
np.testing.assert_array_equal(scale_out, scale_in)
np.testing.assert_array_equal(offset_out, offset_in)
self.assertFalse(scale_out is scale_in) # ensure result is a copy and not a reference to the original input
self.assertFalse(offset_out is offset_in)
@staticmethod
def test_check_scale_offset_2():
scale_out, offset_out = shared.check_scale_offset(num_features=2, scale=None, offset=None)
np.testing.assert_array_equal(scale_out, np.ones(2, dtype=float))
np.testing.assert_array_equal(offset_out, np.zeros(2, dtype=float))
|
[
"proset.shared.check_scale_offset",
"numpy.sum",
"numpy.testing.assert_array_equal",
"numpy.zeros",
"numpy.ones",
"numpy.array",
"numpy.testing.assert_allclose",
"proset.shared.check_feature_names"
] |
[((2439, 2503), 'numpy.zeros', 'np.zeros', (['(REFERENCE.shape[0], PROTOTYPES.shape[0])'], {'dtype': 'float'}), '((REFERENCE.shape[0], PROTOTYPES.shape[0]), dtype=float)\n', (2447, 2503), True, 'import numpy as np\n'), ((2775, 2835), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['similarity', 'reference_similarity'], {}), '(similarity, reference_similarity)\n', (2801, 2835), True, 'import numpy as np\n'), ((5517, 5614), 'proset.shared.check_feature_names', 'shared.check_feature_names', ([], {'num_features': '(2)', 'feature_names': 'FEATURE_NAMES', 'active_features': 'None'}), '(num_features=2, feature_names=FEATURE_NAMES,\n active_features=None)\n', (5543, 5614), True, 'import proset.shared as shared\n'), ((5843, 5931), 'proset.shared.check_feature_names', 'shared.check_feature_names', ([], {'num_features': '(2)', 'feature_names': 'None', 'active_features': 'None'}), '(num_features=2, feature_names=None,\n active_features=None)\n', (5869, 5931), True, 'import proset.shared as shared\n'), ((8791, 8811), 'numpy.array', 'np.array', (['[0.5, 2.0]'], {}), '([0.5, 2.0])\n', (8799, 8811), True, 'import numpy as np\n'), ((8833, 8854), 'numpy.array', 'np.array', (['[-1.0, 1.0]'], {}), '([-1.0, 1.0])\n', (8841, 8854), True, 'import numpy as np\n'), ((8888, 8963), 'proset.shared.check_scale_offset', 'shared.check_scale_offset', ([], {'num_features': '(2)', 'scale': 'scale_in', 'offset': 'offset_in'}), '(num_features=2, scale=scale_in, offset=offset_in)\n', (8913, 8963), True, 'import proset.shared as shared\n'), ((8973, 9023), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['scale_out', 'scale_in'], {}), '(scale_out, scale_in)\n', (9002, 9023), True, 'import numpy as np\n'), ((9033, 9085), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['offset_out', 'offset_in'], {}), '(offset_out, offset_in)\n', (9062, 9085), True, 'import numpy as np\n'), ((9347, 9413), 'proset.shared.check_scale_offset', 'shared.check_scale_offset', ([], {'num_features': '(2)', 'scale': 'None', 'offset': 'None'}), '(num_features=2, scale=None, offset=None)\n', (9372, 9413), True, 'import proset.shared as shared\n'), ((1649, 1674), 'numpy.array', 'np.array', (['[0, 1, 1, 0, 2]'], {}), '([0, 1, 1, 0, 2])\n', (1657, 1674), True, 'import numpy as np\n'), ((1720, 1739), 'numpy.array', 'np.array', (['[2, 2, 1]'], {}), '([2, 2, 1])\n', (1728, 1739), True, 'import numpy as np\n'), ((1832, 1860), 'numpy.array', 'np.array', (['[0, 0, 1, 1, 1, 2]'], {}), '([0, 0, 1, 1, 1, 2])\n', (1840, 1860), True, 'import numpy as np\n'), ((1906, 1925), 'numpy.array', 'np.array', (['[0, 2, 5]'], {}), '([0, 2, 5])\n', (1914, 1925), True, 'import numpy as np\n'), ((2935, 3025), 'proset.shared.check_feature_names', 'shared.check_feature_names', ([], {'num_features': '(1.0)', 'feature_names': 'None', 'active_features': 'None'}), '(num_features=1.0, feature_names=None,\n active_features=None)\n', (2961, 3025), True, 'import proset.shared as shared\n'), ((3266, 3354), 'proset.shared.check_feature_names', 'shared.check_feature_names', ([], {'num_features': '(0)', 'feature_names': 'None', 'active_features': 'None'}), '(num_features=0, feature_names=None,\n active_features=None)\n', (3292, 3354), True, 'import proset.shared as shared\n'), ((3597, 3694), 'proset.shared.check_feature_names', 'shared.check_feature_names', ([], {'num_features': '(1)', 'feature_names': 'FEATURE_NAMES', 'active_features': 'None'}), '(num_features=1, feature_names=FEATURE_NAMES,\n active_features=None)\n', (3623, 3694), True, 'import proset.shared as shared\n'), ((6493, 6561), 'proset.shared.check_scale_offset', 'shared.check_scale_offset', ([], {'num_features': '(2.0)', 'scale': 'None', 'offset': 'None'}), '(num_features=2.0, scale=None, offset=None)\n', (6518, 6561), True, 'import proset.shared as shared\n'), ((6805, 6871), 'proset.shared.check_scale_offset', 'shared.check_scale_offset', ([], {'num_features': '(0)', 'scale': 'None', 'offset': 'None'}), '(num_features=0, scale=None, offset=None)\n', (6830, 6871), True, 'import proset.shared as shared\n'), ((9464, 9487), 'numpy.ones', 'np.ones', (['(2)'], {'dtype': 'float'}), '(2, dtype=float)\n', (9471, 9487), True, 'import numpy as np\n'), ((9540, 9564), 'numpy.zeros', 'np.zeros', (['(2)'], {'dtype': 'float'}), '(2, dtype=float)\n', (9548, 9564), True, 'import numpy as np\n'), ((689, 707), 'numpy.array', 'np.array', (['[[0, 1]]'], {}), '([[0, 1]])\n', (697, 707), True, 'import numpy as np\n'), ((986, 1006), 'numpy.array', 'np.array', (['[0.0, 1.0]'], {}), '([0.0, 1.0])\n', (994, 1006), True, 'import numpy as np\n'), ((1290, 1306), 'numpy.array', 'np.array', (['[0, 2]'], {}), '([0, 2])\n', (1298, 1306), True, 'import numpy as np\n'), ((2286, 2325), 'numpy.sum', 'np.sum', (['(scaled_reference ** 2.0)'], {'axis': '(1)'}), '(scaled_reference ** 2.0, axis=1)\n', (2292, 2325), True, 'import numpy as np\n'), ((2355, 2395), 'numpy.sum', 'np.sum', (['(scaled_prototypes ** 2.0)'], {'axis': '(1)'}), '(scaled_prototypes ** 2.0, axis=1)\n', (2361, 2395), True, 'import numpy as np\n'), ((6127, 6140), 'numpy.array', 'np.array', (['[1]'], {}), '([1])\n', (6135, 6140), True, 'import numpy as np\n'), ((6338, 6351), 'numpy.array', 'np.array', (['[1]'], {}), '([1])\n', (6346, 6351), True, 'import numpy as np\n'), ((4046, 4064), 'numpy.array', 'np.array', (['[[0, 1]]'], {}), '([[0, 1]])\n', (4054, 4064), True, 'import numpy as np\n'), ((4396, 4416), 'numpy.array', 'np.array', (['[0.0, 1.0]'], {}), '([0.0, 1.0])\n', (4404, 4416), True, 'import numpy as np\n'), ((4753, 4770), 'numpy.array', 'np.array', (['[-1, 0]'], {}), '([-1, 0])\n', (4761, 4770), True, 'import numpy as np\n'), ((5193, 5209), 'numpy.array', 'np.array', (['[0, 2]'], {}), '([0, 2])\n', (5201, 5209), True, 'import numpy as np\n'), ((7165, 7187), 'numpy.array', 'np.array', (['[[0.5, 2.0]]'], {}), '([[0.5, 2.0]])\n', (7173, 7187), True, 'import numpy as np\n'), ((7490, 7510), 'numpy.array', 'np.array', (['[0.5, 2.0]'], {}), '([0.5, 2.0])\n', (7498, 7510), True, 'import numpy as np\n'), ((7828, 7848), 'numpy.array', 'np.array', (['[0.0, 2.0]'], {}), '([0.0, 2.0])\n', (7836, 7848), True, 'import numpy as np\n'), ((8169, 8189), 'numpy.array', 'np.array', (['[0.5, 2.0]'], {}), '([0.5, 2.0])\n', (8177, 8189), True, 'import numpy as np\n'), ((8198, 8221), 'numpy.array', 'np.array', (['[[-1.0, 1.0]]'], {}), '([[-1.0, 1.0]])\n', (8206, 8221), True, 'import numpy as np\n'), ((8512, 8537), 'numpy.array', 'np.array', (['[0.5, 2.0, 1.0]'], {}), '([0.5, 2.0, 1.0])\n', (8520, 8537), True, 'import numpy as np\n'), ((8546, 8567), 'numpy.array', 'np.array', (['[-1.0, 1.0]'], {}), '([-1.0, 1.0])\n', (8554, 8567), True, 'import numpy as np\n'), ((2681, 2746), 'numpy.sum', 'np.sum', (['(((REFERENCE[i] - PROTOTYPES[j]) * FEATURE_WEIGHTS) ** 2.0)'], {}), '(((REFERENCE[i] - PROTOTYPES[j]) * FEATURE_WEIGHTS) ** 2.0)\n', (2687, 2746), True, 'import numpy as np\n')]
|
import os
import time
import h5py
import numpy as np
from annotypes import Anno, add_call_types
from scanpointgenerator import Point
from malcolm.core import APartName, Part, PartRegistrar
from malcolm.modules import builtin, scanning
from ..util import interesting_pattern, make_gaussian_blob
with Anno("Width of detector image"):
AWidth = int
with Anno("Height of detector image"):
AHeight = int
# Datasets where we will write our data
DATA_PATH = "/entry/data"
SUM_PATH = "/entry/sum"
UID_PATH = "/entry/uid"
SET_PATH = "/entry/%s_set"
# How often we flush in seconds
FLUSH_PERIOD = 1
class FileWritePart(Part):
"""Minimal interface demonstrating a file writing detector part"""
def __init__(self, name: APartName, width: AWidth, height: AHeight) -> None:
super().__init__(name)
# Store input arguments
self._width = width
self._height = height
# The detector image we will modify for each image (0..255 range)
self._blob = make_gaussian_blob(width, height) * 255
# The hdf file we will write
self._hdf: h5py.File = None
# Configure args and progress info
self._exposure = 0.0
self._generator: scanning.hooks.AGenerator = None
self._completed_steps = 0
self._steps_to_do = 0
# How much to offset uid value from generator point
self._uid_offset = 0
def setup(self, registrar: PartRegistrar) -> None:
super().setup(registrar)
# Hooks
registrar.hook(scanning.hooks.ConfigureHook, self.on_configure)
registrar.hook(
(scanning.hooks.PostRunArmedHook, scanning.hooks.SeekHook), self.on_seek
)
registrar.hook(scanning.hooks.RunHook, self.on_run)
registrar.hook(
(scanning.hooks.AbortHook, builtin.hooks.ResetHook), self.on_reset
)
# Tell the controller to expose some extra configure parameters
registrar.report(scanning.hooks.ConfigureHook.create_info(self.on_configure))
# Allow CamelCase as these parameters will be serialized
# noinspection PyPep8Naming
@add_call_types
def on_configure(
self,
completed_steps: scanning.hooks.ACompletedSteps,
steps_to_do: scanning.hooks.AStepsToDo,
generator: scanning.hooks.AGenerator,
fileDir: scanning.hooks.AFileDir,
exposure: scanning.hooks.AExposure = 0.0,
formatName: scanning.hooks.AFormatName = "det",
fileTemplate: scanning.hooks.AFileTemplate = "%s.h5",
) -> scanning.hooks.UInfos:
"""On `ConfigureHook` create HDF file with datasets"""
# Store args
self._completed_steps = completed_steps
self._steps_to_do = steps_to_do
self._generator = generator
self._uid_offset = 0
self._exposure = exposure
# Work out where to write the file
filename = fileTemplate % formatName
filepath = os.path.join(fileDir, filename)
# Make the HDF file
self._hdf = self._create_hdf(filepath)
# Tell everyone what we're going to make
infos = list(self._create_infos(formatName, filename))
return infos
# For docs: Before run
@add_call_types
def on_run(self, context: scanning.hooks.AContext) -> None:
"""On `RunHook` record where to next take data"""
# Start time so everything is relative
end_of_exposure = time.time() + self._exposure
last_flush = end_of_exposure
assert self.registrar, "Part has no registrar"
for i in range(
self._completed_steps, self._completed_steps + self._steps_to_do
):
# Get the point we are meant to be scanning
point = self._generator.get_point(i)
# Simulate waiting for an exposure and writing the data
wait_time = end_of_exposure - time.time()
context.sleep(wait_time)
self.log.debug(f"Writing data for point {i}")
self._write_data(point, i)
# Flush the datasets if it is time to
if time.time() - last_flush > FLUSH_PERIOD:
last_flush = time.time()
self._flush_datasets()
# Schedule the end of the next exposure
end_of_exposure += point.duration
# Update the point as being complete
self.registrar.report(scanning.infos.RunProgressInfo(i + 1))
# Do one last flush and then we're done
self._flush_datasets()
@add_call_types
def on_seek(
self,
completed_steps: scanning.hooks.ACompletedSteps,
steps_to_do: scanning.hooks.AStepsToDo,
) -> None:
"""On `SeekHook`, `PostRunArmedHook` record where to next take data"""
# Skip the uid so it is guaranteed to be unique
self._uid_offset += self._completed_steps + self._steps_to_do - completed_steps
self._completed_steps = completed_steps
self._steps_to_do = steps_to_do
@add_call_types
def on_reset(self) -> None:
"""On `AbortHook`, `ResetHook` close HDF file if it exists"""
if self._hdf:
self._hdf.close()
self._hdf = None
def _create_infos(self, detector_name, filename):
# Main dataset
yield scanning.infos.DatasetProducedInfo(
name="%s.data" % detector_name,
filename=filename,
type=scanning.util.DatasetType.PRIMARY,
rank=len(self._generator.shape) + 2,
path=DATA_PATH,
uniqueid=UID_PATH,
)
# Sum
yield scanning.infos.DatasetProducedInfo(
name="%s.sum" % detector_name,
filename=filename,
type=scanning.util.DatasetType.SECONDARY,
rank=len(self._generator.shape) + 2,
path=SUM_PATH,
uniqueid=UID_PATH,
)
# Add an axis for each setpoint
for dim in self._generator.axes:
yield scanning.infos.DatasetProducedInfo(
name="%s.value_set" % dim,
filename=filename,
type=scanning.util.DatasetType.POSITION_SET,
rank=1,
path=SET_PATH % dim,
uniqueid="",
)
def _create_hdf(self, filepath: str) -> h5py.File:
# The generator tells us what dimensions our scan should be. The dataset
# will grow, so start off with the smallest we need
initial_shape = tuple(1 for _ in self._generator.shape)
# Open the file with the latest libver so SWMR works
hdf = h5py.File(filepath, "w", libver="latest")
# Write the datasets
# The detector dataset containing the simulated data
hdf.create_dataset(
DATA_PATH,
dtype=np.uint8,
shape=initial_shape + (self._height, self._width),
maxshape=self._generator.shape + (self._height, self._width),
)
# Make the scalar datasets
for path, dtype in {UID_PATH: np.int32, SUM_PATH: np.float64}.items():
hdf.create_dataset(
path,
dtype=dtype,
shape=initial_shape + (1, 1),
maxshape=self._generator.shape + (1, 1),
)
# Make the setpoint dataset
for d in self._generator.dimensions:
for axis in d.axes:
# Make a data set for the axes, holding an array holding
# floating point data, for each point specified in the generator
ds = hdf.create_dataset(SET_PATH % axis, data=d.get_positions(axis))
ds.attrs["units"] = self._generator.units[axis]
# Datasets made, we can switch to SWMR mode now
hdf.swmr_mode = True
return hdf
def _write_data(self, point: Point, step: int) -> None:
point_needs_shape = tuple(x + 1 for x in point.indexes) + (1, 1)
# Resize the datasets so they fit
for path in (DATA_PATH, SUM_PATH, UID_PATH):
ds = self._hdf[path]
expand_to = tuple(max(*z) for z in zip(point_needs_shape, ds.shape))
ds.resize(expand_to)
# Write the detector data, multiply by exposure / duration to allow us
# to make dimmer images by reducint exposure relative to other detectors
intensity = interesting_pattern(point) * self._exposure / point.duration
detector_data = (self._blob * intensity).astype(np.uint8)
index = tuple(point.indexes)
self._hdf[DATA_PATH][index] = detector_data
self._hdf[SUM_PATH][index] = np.sum(detector_data)
self._hdf[UID_PATH][index] = step + self._uid_offset + 1
def _flush_datasets(self):
# Note that UID comes last so anyone monitoring knows the data is there
for path in (DATA_PATH, SUM_PATH, UID_PATH):
self._hdf[path].flush()
|
[
"h5py.File",
"malcolm.modules.scanning.infos.RunProgressInfo",
"numpy.sum",
"annotypes.Anno",
"time.time",
"malcolm.modules.scanning.hooks.ConfigureHook.create_info",
"malcolm.modules.scanning.infos.DatasetProducedInfo",
"os.path.join"
] |
[((303, 334), 'annotypes.Anno', 'Anno', (['"""Width of detector image"""'], {}), "('Width of detector image')\n", (307, 334), False, 'from annotypes import Anno, add_call_types\n'), ((358, 390), 'annotypes.Anno', 'Anno', (['"""Height of detector image"""'], {}), "('Height of detector image')\n", (362, 390), False, 'from annotypes import Anno, add_call_types\n'), ((2945, 2976), 'os.path.join', 'os.path.join', (['fileDir', 'filename'], {}), '(fileDir, filename)\n', (2957, 2976), False, 'import os\n'), ((6590, 6631), 'h5py.File', 'h5py.File', (['filepath', '"""w"""'], {'libver': '"""latest"""'}), "(filepath, 'w', libver='latest')\n", (6599, 6631), False, 'import h5py\n'), ((8591, 8612), 'numpy.sum', 'np.sum', (['detector_data'], {}), '(detector_data)\n', (8597, 8612), True, 'import numpy as np\n'), ((1963, 2022), 'malcolm.modules.scanning.hooks.ConfigureHook.create_info', 'scanning.hooks.ConfigureHook.create_info', (['self.on_configure'], {}), '(self.on_configure)\n', (2003, 2022), False, 'from malcolm.modules import builtin, scanning\n'), ((3428, 3439), 'time.time', 'time.time', ([], {}), '()\n', (3437, 3439), False, 'import time\n'), ((3876, 3887), 'time.time', 'time.time', ([], {}), '()\n', (3885, 3887), False, 'import time\n'), ((4157, 4168), 'time.time', 'time.time', ([], {}), '()\n', (4166, 4168), False, 'import time\n'), ((4389, 4426), 'malcolm.modules.scanning.infos.RunProgressInfo', 'scanning.infos.RunProgressInfo', (['(i + 1)'], {}), '(i + 1)\n', (4419, 4426), False, 'from malcolm.modules import builtin, scanning\n'), ((5975, 6152), 'malcolm.modules.scanning.infos.DatasetProducedInfo', 'scanning.infos.DatasetProducedInfo', ([], {'name': "('%s.value_set' % dim)", 'filename': 'filename', 'type': 'scanning.util.DatasetType.POSITION_SET', 'rank': '(1)', 'path': '(SET_PATH % dim)', 'uniqueid': '""""""'}), "(name='%s.value_set' % dim, filename=\n filename, type=scanning.util.DatasetType.POSITION_SET, rank=1, path=\n SET_PATH % dim, uniqueid='')\n", (6009, 6152), False, 'from malcolm.modules import builtin, scanning\n'), ((4087, 4098), 'time.time', 'time.time', ([], {}), '()\n', (4096, 4098), False, 'import time\n')]
|
from skfuzzy import control as ctrl
import skfuzzy as fuzz
import numpy as np
from fuzzy_utils import create_universes_membership_functions
class VehicleRules:
def __init__(self, show_sim_result=None):
prox, over, spat = create_universes_membership_functions()
self.__show_sim_result = show_sim_result
self.__proximity = prox
self.__overlap = over
self.__spatial_relationships = spat
self.__create_universes_of_discourse()
self.__create_membership_functions()
self.__create_cycle_rules()
self.__create_passenger_rules()
self.__create_personal_rules()
def __create_universes_of_discourse(self):
self.__cycle_interaction = ctrl.Consequent(universe=np.arange(-0.1, 1.1, 0.1), label='cycle_interaction')
self.__passenger_interaction = ctrl.Consequent(universe=np.arange(-0.1, 1.1, 0.1),
label='passenger_interaction')
self.__personal_interaction = ctrl.Consequent(universe=np.arange(-0.1, 1.1, 0.1),
label='personal_interaction')
def __create_membership_functions(self):
self.__cycle_interaction['Riding'] = fuzz.trimf(self.__cycle_interaction.universe, [0.4, 0.7, 1.0])
self.__cycle_interaction['Not Riding'] = fuzz.trimf(self.__cycle_interaction.universe, [0.0, 0.3, 0.6])
self.__passenger_interaction['Riding'] = fuzz.trimf(self.__passenger_interaction.universe, [0.4, 0.7, 1.0])
self.__passenger_interaction['Not Riding'] = fuzz.trimf(self.__passenger_interaction.universe, [0.0, 0.3, 0.6])
self.__personal_interaction['Driving'] = fuzz.trimf(self.__personal_interaction.universe, [0.4, 0.7, 1.0])
self.__personal_interaction['Not Driving'] = fuzz.trimf(self.__personal_interaction.universe, [0.0, 0.3, 0.6])
def __create_cycle_rules(self):
# IF overlap AND very close AND above THEN riding
self.__riding_rule1 = ctrl.Rule(self.__overlap['Overlap'] & self.__proximity['Very Close'] &
(self.__spatial_relationships['Above Left'] |
self.__spatial_relationships['Above'] |
self.__spatial_relationships['Above Right'] |
self.__spatial_relationships['Left'] |
self.__spatial_relationships['Right1'] |
self.__spatial_relationships['Right2']),
self.__cycle_interaction['Riding'])
# IF overlap AND very close AND not above THEN not riding
self.__not_riding_rule1 = ctrl.Rule(self.__overlap['Overlap'] & self.__proximity['Very Close'] &
(self.__spatial_relationships['Below Right'] |
self.__spatial_relationships['Below'] |
self.__spatial_relationships['Below Left']),
self.__cycle_interaction['Not Riding'])
# IF overlap AND close OR medium OR far OR very far THEN not riding
self.__not_riding_rule2 = ctrl.Rule(self.__overlap['Overlap'] &
(self.__proximity['Close'] | self.__proximity['Medium'] |
self.__proximity['Far'] | self.__proximity['Very Far']),
self.__cycle_interaction['Not Riding'])
# IF no overlap THEN not riding
self.__not_riding_rule3 = ctrl.Rule(self.__overlap['No Overlap'], self.__cycle_interaction['Not Riding'])
self.__riding_ctrl = ctrl.ControlSystem([self.__riding_rule1, self.__not_riding_rule1,
self.__not_riding_rule2, self.__not_riding_rule3])
self.__riding_sim = ctrl.ControlSystemSimulation(self.__riding_ctrl, flush_after_run=100)
def __create_passenger_rules(self):
# IF overlap AND very close THEN riding
self.__riding_in_rule1 = ctrl.Rule(self.__overlap['Overlap'] & self.__proximity['Very Close'],
self.__passenger_interaction['Riding'])
# IF overlap AND close OR medium OR far OR very far THEN not riding
self.__not_riding_in_rule1 = ctrl.Rule(self.__overlap['Overlap'] &
(self.__proximity['Close'] | self.__proximity['Medium'] |
self.__proximity['Far'] | self.__proximity['Very Far']),
self.__passenger_interaction['Not Riding'])
# IF no overlap THEN not riding
self.__not_riding_in_rule2 = ctrl.Rule(self.__overlap['No Overlap'],
self.__passenger_interaction['Not Riding'])
self.__passenger_ctrl = ctrl.ControlSystem([self.__riding_in_rule1, self.__not_riding_in_rule1,
self.__not_riding_in_rule2])
self.__passenger_sim = ctrl.ControlSystemSimulation(self.__passenger_ctrl, flush_after_run=100)
def __create_personal_rules(self):
# IF overlap AND very close THEN driving
self.__driving_rule1 = ctrl.Rule(self.__overlap['Overlap'] & self.__proximity['Very Close'] &
(self.__spatial_relationships['Right1'] |
self.__spatial_relationships['Right2'] |
self.__spatial_relationships['Above Right'] |
self.__spatial_relationships['Above'] |
self.__spatial_relationships['Above Left'] |
self.__spatial_relationships['Left']),
self.__personal_interaction['Driving'])
# IF overlap AND close OR medium OR far OR very far THEN not driving
self.__not_driving_rule1 = ctrl.Rule(self.__overlap['Overlap'] &
(self.__proximity['Close'] | self.__proximity['Medium'] |
self.__proximity['Far'] | self.__proximity['Very Far']),
self.__personal_interaction['Not Driving'])
# IF no overlap THEN not driving
self.__not_driving_rule2 = ctrl.Rule(self.__overlap['No Overlap'], self.__personal_interaction['Not Driving'])
# IF overlap AND very close AND below(s) THEN not driving
self.__not_driving_rule3 = ctrl.Rule(self.__overlap['Overlap'] & self.__proximity['Very Close'] &
(self.__spatial_relationships['Below Left'] |
self.__spatial_relationships['Below'] |
self.__spatial_relationships['Below Right']),
self.__personal_interaction['Not Driving'])
self.__personal_ctrl = ctrl.ControlSystem([self.__driving_rule1, self.__not_driving_rule1,
self.__not_driving_rule2, self.__not_driving_rule3])
self.__personal_sim = ctrl.ControlSystemSimulation(self.__personal_ctrl, flush_after_run=100)
def compute_cycle_interaction(self, giou, iou, sr_angle):
self.__riding_sim.input['overlap'] = iou
self.__riding_sim.input['proximity'] = giou
self.__riding_sim.input['spatial_relationships'] = sr_angle
self.__riding_sim.compute()
if self.__show_sim_result:
self.__cycle_interaction.view(sim=self.__riding_sim)
riding_result = self.__riding_sim.output['cycle_interaction']
riding = fuzz.interp_membership(self.__cycle_interaction.universe, self.__cycle_interaction['Riding'].mf,
riding_result)
not_riding = fuzz.interp_membership(self.__cycle_interaction.universe,
self.__cycle_interaction['Not Riding'].mf, riding_result)
membership = {'Riding': riding, 'Not Riding': not_riding}
ret_label = max(membership, key=membership.get)
if ret_label == 'Not Riding':
return None
else:
return ret_label
def compute_passenger_interaction(self, giou, iou, sr_angle):
self.__passenger_sim.input['overlap'] = iou
self.__passenger_sim.input['proximity'] = giou
self.__passenger_sim.compute()
if self.__show_sim_result:
self.__passenger_interaction.view(sim=self.__passenger_sim)
riding_result = self.__passenger_sim.output['passenger_interaction']
riding = fuzz.interp_membership(self.__passenger_interaction.universe,
self.__passenger_interaction['Riding'].mf, riding_result)
not_riding = fuzz.interp_membership(self.__passenger_interaction.universe,
self.__passenger_interaction['Not Riding'].mf, riding_result)
membership = {'Riding': riding, 'Not Riding': not_riding}
ret_label = max(membership, key=membership.get)
if ret_label == 'Not Riding':
return None
else:
return ret_label
def compute_personal_interaction(self, giou, iou, sr_angle):
self.__personal_sim.input['overlap'] = iou
self.__personal_sim.input['proximity'] = giou
self.__personal_sim.input['spatial_relationships'] = sr_angle
self.__personal_sim.compute()
if self.__show_sim_result:
self.__personal_interaction.view(sim=self.__personal_sim)
driving_result = self.__personal_sim.output['personal_interaction']
driving = fuzz.interp_membership(self.__personal_interaction.universe,
self.__personal_interaction['Driving'].mf, driving_result)
not_driving = fuzz.interp_membership(self.__personal_interaction.universe,
self.__personal_interaction['Not Driving'].mf, driving_result)
membership = {'Driving': driving, 'Not Driving': not_driving}
ret_label = max(membership, key=membership.get)
if ret_label == 'Not Driving':
return None
else:
return ret_label
def compute_interaction(self, label, dom_cat, sub_cat, giou, iou, sr_angle):
if label == 'motorcycle' or label == 'bicycle' or label == 'motorbike':
res_label = self.compute_cycle_interaction(giou, iou, sr_angle)
return res_label
if dom_cat == 'passenger':
res_label = self.compute_passenger_interaction(giou, iou, sr_angle)
return res_label
if dom_cat == 'personal':
res_label = self.compute_personal_interaction(giou, iou, sr_angle)
return res_label
|
[
"skfuzzy.control.ControlSystemSimulation",
"skfuzzy.trimf",
"fuzzy_utils.create_universes_membership_functions",
"skfuzzy.control.Rule",
"numpy.arange",
"skfuzzy.control.ControlSystem",
"skfuzzy.interp_membership"
] |
[((235, 274), 'fuzzy_utils.create_universes_membership_functions', 'create_universes_membership_functions', ([], {}), '()\n', (272, 274), False, 'from fuzzy_utils import create_universes_membership_functions\n'), ((1241, 1303), 'skfuzzy.trimf', 'fuzz.trimf', (['self.__cycle_interaction.universe', '[0.4, 0.7, 1.0]'], {}), '(self.__cycle_interaction.universe, [0.4, 0.7, 1.0])\n', (1251, 1303), True, 'import skfuzzy as fuzz\n'), ((1353, 1415), 'skfuzzy.trimf', 'fuzz.trimf', (['self.__cycle_interaction.universe', '[0.0, 0.3, 0.6]'], {}), '(self.__cycle_interaction.universe, [0.0, 0.3, 0.6])\n', (1363, 1415), True, 'import skfuzzy as fuzz\n'), ((1465, 1531), 'skfuzzy.trimf', 'fuzz.trimf', (['self.__passenger_interaction.universe', '[0.4, 0.7, 1.0]'], {}), '(self.__passenger_interaction.universe, [0.4, 0.7, 1.0])\n', (1475, 1531), True, 'import skfuzzy as fuzz\n'), ((1585, 1651), 'skfuzzy.trimf', 'fuzz.trimf', (['self.__passenger_interaction.universe', '[0.0, 0.3, 0.6]'], {}), '(self.__passenger_interaction.universe, [0.0, 0.3, 0.6])\n', (1595, 1651), True, 'import skfuzzy as fuzz\n'), ((1701, 1766), 'skfuzzy.trimf', 'fuzz.trimf', (['self.__personal_interaction.universe', '[0.4, 0.7, 1.0]'], {}), '(self.__personal_interaction.universe, [0.4, 0.7, 1.0])\n', (1711, 1766), True, 'import skfuzzy as fuzz\n'), ((1820, 1885), 'skfuzzy.trimf', 'fuzz.trimf', (['self.__personal_interaction.universe', '[0.0, 0.3, 0.6]'], {}), '(self.__personal_interaction.universe, [0.0, 0.3, 0.6])\n', (1830, 1885), True, 'import skfuzzy as fuzz\n'), ((2011, 2395), 'skfuzzy.control.Rule', 'ctrl.Rule', (["(self.__overlap['Overlap'] & self.__proximity['Very Close'] & (self.\n __spatial_relationships['Above Left'] | self.__spatial_relationships[\n 'Above'] | self.__spatial_relationships['Above Right'] | self.\n __spatial_relationships['Left'] | self.__spatial_relationships['Right1'\n ] | self.__spatial_relationships['Right2']))", "self.__cycle_interaction['Riding']"], {}), "(self.__overlap['Overlap'] & self.__proximity['Very Close'] & (\n self.__spatial_relationships['Above Left'] | self.\n __spatial_relationships['Above'] | self.__spatial_relationships[\n 'Above Right'] | self.__spatial_relationships['Left'] | self.\n __spatial_relationships['Right1'] | self.__spatial_relationships[\n 'Right2']), self.__cycle_interaction['Riding'])\n", (2020, 2395), True, 'from skfuzzy import control as ctrl\n'), ((2757, 3014), 'skfuzzy.control.Rule', 'ctrl.Rule', (["(self.__overlap['Overlap'] & self.__proximity['Very Close'] & (self.\n __spatial_relationships['Below Right'] | self.__spatial_relationships[\n 'Below'] | self.__spatial_relationships['Below Left']))", "self.__cycle_interaction['Not Riding']"], {}), "(self.__overlap['Overlap'] & self.__proximity['Very Close'] & (\n self.__spatial_relationships['Below Right'] | self.\n __spatial_relationships['Below'] | self.__spatial_relationships[\n 'Below Left']), self.__cycle_interaction['Not Riding'])\n", (2766, 3014), True, 'from skfuzzy import control as ctrl\n'), ((3289, 3491), 'skfuzzy.control.Rule', 'ctrl.Rule', (["(self.__overlap['Overlap'] & (self.__proximity['Close'] | self.__proximity[\n 'Medium'] | self.__proximity['Far'] | self.__proximity['Very Far']))", "self.__cycle_interaction['Not Riding']"], {}), "(self.__overlap['Overlap'] & (self.__proximity['Close'] | self.\n __proximity['Medium'] | self.__proximity['Far'] | self.__proximity[\n 'Very Far']), self.__cycle_interaction['Not Riding'])\n", (3298, 3491), True, 'from skfuzzy import control as ctrl\n'), ((3690, 3769), 'skfuzzy.control.Rule', 'ctrl.Rule', (["self.__overlap['No Overlap']", "self.__cycle_interaction['Not Riding']"], {}), "(self.__overlap['No Overlap'], self.__cycle_interaction['Not Riding'])\n", (3699, 3769), True, 'from skfuzzy import control as ctrl\n'), ((3800, 3921), 'skfuzzy.control.ControlSystem', 'ctrl.ControlSystem', (['[self.__riding_rule1, self.__not_riding_rule1, self.__not_riding_rule2,\n self.__not_riding_rule3]'], {}), '([self.__riding_rule1, self.__not_riding_rule1, self.\n __not_riding_rule2, self.__not_riding_rule3])\n', (3818, 3921), True, 'from skfuzzy import control as ctrl\n'), ((3994, 4063), 'skfuzzy.control.ControlSystemSimulation', 'ctrl.ControlSystemSimulation', (['self.__riding_ctrl'], {'flush_after_run': '(100)'}), '(self.__riding_ctrl, flush_after_run=100)\n', (4022, 4063), True, 'from skfuzzy import control as ctrl\n'), ((4186, 4300), 'skfuzzy.control.Rule', 'ctrl.Rule', (["(self.__overlap['Overlap'] & self.__proximity['Very Close'])", "self.__passenger_interaction['Riding']"], {}), "(self.__overlap['Overlap'] & self.__proximity['Very Close'], self.\n __passenger_interaction['Riding'])\n", (4195, 4300), True, 'from skfuzzy import control as ctrl\n'), ((4452, 4658), 'skfuzzy.control.Rule', 'ctrl.Rule', (["(self.__overlap['Overlap'] & (self.__proximity['Close'] | self.__proximity[\n 'Medium'] | self.__proximity['Far'] | self.__proximity['Very Far']))", "self.__passenger_interaction['Not Riding']"], {}), "(self.__overlap['Overlap'] & (self.__proximity['Close'] | self.\n __proximity['Medium'] | self.__proximity['Far'] | self.__proximity[\n 'Very Far']), self.__passenger_interaction['Not Riding'])\n", (4461, 4658), True, 'from skfuzzy import control as ctrl\n'), ((4868, 4956), 'skfuzzy.control.Rule', 'ctrl.Rule', (["self.__overlap['No Overlap']", "self.__passenger_interaction['Not Riding']"], {}), "(self.__overlap['No Overlap'], self.__passenger_interaction[\n 'Not Riding'])\n", (4877, 4956), True, 'from skfuzzy import control as ctrl\n'), ((5032, 5136), 'skfuzzy.control.ControlSystem', 'ctrl.ControlSystem', (['[self.__riding_in_rule1, self.__not_riding_in_rule1, self.__not_riding_in_rule2\n ]'], {}), '([self.__riding_in_rule1, self.__not_riding_in_rule1,\n self.__not_riding_in_rule2])\n', (5050, 5136), True, 'from skfuzzy import control as ctrl\n'), ((5216, 5288), 'skfuzzy.control.ControlSystemSimulation', 'ctrl.ControlSystemSimulation', (['self.__passenger_ctrl'], {'flush_after_run': '(100)'}), '(self.__passenger_ctrl, flush_after_run=100)\n', (5244, 5288), True, 'from skfuzzy import control as ctrl\n'), ((5409, 5797), 'skfuzzy.control.Rule', 'ctrl.Rule', (["(self.__overlap['Overlap'] & self.__proximity['Very Close'] & (self.\n __spatial_relationships['Right1'] | self.__spatial_relationships[\n 'Right2'] | self.__spatial_relationships['Above Right'] | self.\n __spatial_relationships['Above'] | self.__spatial_relationships[\n 'Above Left'] | self.__spatial_relationships['Left']))", "self.__personal_interaction['Driving']"], {}), "(self.__overlap['Overlap'] & self.__proximity['Very Close'] & (\n self.__spatial_relationships['Right1'] | self.__spatial_relationships[\n 'Right2'] | self.__spatial_relationships['Above Right'] | self.\n __spatial_relationships['Above'] | self.__spatial_relationships[\n 'Above Left'] | self.__spatial_relationships['Left']), self.\n __personal_interaction['Driving'])\n", (5418, 5797), True, 'from skfuzzy import control as ctrl\n'), ((6177, 6383), 'skfuzzy.control.Rule', 'ctrl.Rule', (["(self.__overlap['Overlap'] & (self.__proximity['Close'] | self.__proximity[\n 'Medium'] | self.__proximity['Far'] | self.__proximity['Very Far']))", "self.__personal_interaction['Not Driving']"], {}), "(self.__overlap['Overlap'] & (self.__proximity['Close'] | self.\n __proximity['Medium'] | self.__proximity['Far'] | self.__proximity[\n 'Very Far']), self.__personal_interaction['Not Driving'])\n", (6186, 6383), True, 'from skfuzzy import control as ctrl\n'), ((6586, 6674), 'skfuzzy.control.Rule', 'ctrl.Rule', (["self.__overlap['No Overlap']", "self.__personal_interaction['Not Driving']"], {}), "(self.__overlap['No Overlap'], self.__personal_interaction[\n 'Not Driving'])\n", (6595, 6674), True, 'from skfuzzy import control as ctrl\n'), ((6772, 7033), 'skfuzzy.control.Rule', 'ctrl.Rule', (["(self.__overlap['Overlap'] & self.__proximity['Very Close'] & (self.\n __spatial_relationships['Below Left'] | self.__spatial_relationships[\n 'Below'] | self.__spatial_relationships['Below Right']))", "self.__personal_interaction['Not Driving']"], {}), "(self.__overlap['Overlap'] & self.__proximity['Very Close'] & (\n self.__spatial_relationships['Below Left'] | self.\n __spatial_relationships['Below'] | self.__spatial_relationships[\n 'Below Right']), self.__personal_interaction['Not Driving'])\n", (6781, 7033), True, 'from skfuzzy import control as ctrl\n'), ((7233, 7358), 'skfuzzy.control.ControlSystem', 'ctrl.ControlSystem', (['[self.__driving_rule1, self.__not_driving_rule1, self.__not_driving_rule2,\n self.__not_driving_rule3]'], {}), '([self.__driving_rule1, self.__not_driving_rule1, self.\n __not_driving_rule2, self.__not_driving_rule3])\n', (7251, 7358), True, 'from skfuzzy import control as ctrl\n'), ((7435, 7506), 'skfuzzy.control.ControlSystemSimulation', 'ctrl.ControlSystemSimulation', (['self.__personal_ctrl'], {'flush_after_run': '(100)'}), '(self.__personal_ctrl, flush_after_run=100)\n', (7463, 7506), True, 'from skfuzzy import control as ctrl\n'), ((7962, 8078), 'skfuzzy.interp_membership', 'fuzz.interp_membership', (['self.__cycle_interaction.universe', "self.__cycle_interaction['Riding'].mf", 'riding_result'], {}), "(self.__cycle_interaction.universe, self.\n __cycle_interaction['Riding'].mf, riding_result)\n", (7984, 8078), True, 'import skfuzzy as fuzz\n'), ((8135, 8255), 'skfuzzy.interp_membership', 'fuzz.interp_membership', (['self.__cycle_interaction.universe', "self.__cycle_interaction['Not Riding'].mf", 'riding_result'], {}), "(self.__cycle_interaction.universe, self.\n __cycle_interaction['Not Riding'].mf, riding_result)\n", (8157, 8255), True, 'import skfuzzy as fuzz\n'), ((8936, 9060), 'skfuzzy.interp_membership', 'fuzz.interp_membership', (['self.__passenger_interaction.universe', "self.__passenger_interaction['Riding'].mf", 'riding_result'], {}), "(self.__passenger_interaction.universe, self.\n __passenger_interaction['Riding'].mf, riding_result)\n", (8958, 9060), True, 'import skfuzzy as fuzz\n'), ((9117, 9245), 'skfuzzy.interp_membership', 'fuzz.interp_membership', (['self.__passenger_interaction.universe', "self.__passenger_interaction['Not Riding'].mf", 'riding_result'], {}), "(self.__passenger_interaction.universe, self.\n __passenger_interaction['Not Riding'].mf, riding_result)\n", (9139, 9245), True, 'import skfuzzy as fuzz\n'), ((9990, 10114), 'skfuzzy.interp_membership', 'fuzz.interp_membership', (['self.__personal_interaction.universe', "self.__personal_interaction['Driving'].mf", 'driving_result'], {}), "(self.__personal_interaction.universe, self.\n __personal_interaction['Driving'].mf, driving_result)\n", (10012, 10114), True, 'import skfuzzy as fuzz\n'), ((10173, 10301), 'skfuzzy.interp_membership', 'fuzz.interp_membership', (['self.__personal_interaction.universe', "self.__personal_interaction['Not Driving'].mf", 'driving_result'], {}), "(self.__personal_interaction.universe, self.\n __personal_interaction['Not Driving'].mf, driving_result)\n", (10195, 10301), True, 'import skfuzzy as fuzz\n'), ((745, 770), 'numpy.arange', 'np.arange', (['(-0.1)', '(1.1)', '(0.1)'], {}), '(-0.1, 1.1, 0.1)\n', (754, 770), True, 'import numpy as np\n'), ((863, 888), 'numpy.arange', 'np.arange', (['(-0.1)', '(1.1)', '(0.1)'], {}), '(-0.1, 1.1, 0.1)\n', (872, 888), True, 'import numpy as np\n'), ((1039, 1064), 'numpy.arange', 'np.arange', (['(-0.1)', '(1.1)', '(0.1)'], {}), '(-0.1, 1.1, 0.1)\n', (1048, 1064), True, 'import numpy as np\n')]
|
import pandas as pd
import numpy as np
import json
import subprocess
df = pd.read_csv('ingr.csv', encoding='latin-1')
df_new = df.groupby('recipe_id')['ingredients'].apply(list).reset_index(name='ingredients')
ingredients = df_new['ingredients'].to_numpy()
parsed_ingr = []
for ingr in ingredients:
with open('tmp/parser-input.txt', 'w') as f:
f.write('\n'.join(ingr))
with open('tmp/parser-output.txt', 'w') as f:
bash_cmd = "python bin/parse-ingredients.py tmp/parser-input.txt"
process = subprocess.check_call(bash_cmd.split(), stdout=f)
with open('tmp/parser-output.json', 'w') as f:
bash_cmd = "python bin/convert-to-json.py tmp/parser-output.txt"
process = subprocess.check_call(bash_cmd.split(), stdout=f)
with open('tmp/parser-output.json', 'r') as f:
pingr = json.load(f)
parsed_ingr.append(pingr)
np.savetxt('parsed_ingredients', parsed_ingr, delimiter=',')
|
[
"pandas.read_csv",
"numpy.savetxt",
"json.load"
] |
[((75, 118), 'pandas.read_csv', 'pd.read_csv', (['"""ingr.csv"""'], {'encoding': '"""latin-1"""'}), "('ingr.csv', encoding='latin-1')\n", (86, 118), True, 'import pandas as pd\n'), ((887, 947), 'numpy.savetxt', 'np.savetxt', (['"""parsed_ingredients"""', 'parsed_ingr'], {'delimiter': '""","""'}), "('parsed_ingredients', parsed_ingr, delimiter=',')\n", (897, 947), True, 'import numpy as np\n'), ((835, 847), 'json.load', 'json.load', (['f'], {}), '(f)\n', (844, 847), False, 'import json\n')]
|
""" Epsilon Greedy. """
from typing import Union, Dict, Iterator, NamedTuple
from numpy import random
from .deterministic import DeterministicPolicy
from .exploration_schedules import get_schedule as get_epsilon_schedule
class EpsilonGreedyOutput(NamedTuple):
""" The output of the epsilon greedy policy. """
action: int
q_value: float
full: object
class EpsilonGreedyPolicy(object):
""" Epsilon greedy policy.
Takes an estimator and an epsilon greedy schedule to imbue an epsilon
greedy policy.
"""
def __init__(self, estimator, epsilon: Union[Dict, Iterator]):
self.policy = DeterministicPolicy(estimator)
self.epsilon = epsilon
def get_action(self, state, action_space):
""" Selects an action based on an epsilon greedy strategy.
Returns the Q-value and the epsilon greedy action.
"""
pi = self.policy.get_action(state)
try:
epsilon = next(self.epsilon)
except TypeError:
self.epsilon = get_epsilon_schedule(**self.epsilon)
epsilon = next(self.epsilon)
if epsilon < random.uniform():
pi = EpsilonGreedyOutput(action=pi.action, q_value=pi.q_value,
full=pi.full)
return pi
pi = EpsilonGreedyOutput(action=action_space.sample(), q_value=0,
full={})
return pi
def get_estimator(self):
return self.policy.get_estimator()
def set_estimator(self, estimator):
self.policy.set_estimator(estimator)
def __call__(self, state, action_space):
return self.get_action(state, action_space)
def __str__(self):
return f'{self.__class__.__name__}(id={self.policy})'
def __repr__(self):
obj_id = hex(id(self))
name = self.__str__()
return f'{name} @ {obj_id}'
|
[
"numpy.random.uniform"
] |
[((1141, 1157), 'numpy.random.uniform', 'random.uniform', ([], {}), '()\n', (1155, 1157), False, 'from numpy import random\n')]
|
# coding: utf-8
# In[1]:
from pynq import Overlay, allocate
import numpy as np
# In[2]:
bitfile = "stream_axi_stream_fifo_ipxact.bit"
overlay = Overlay(bitfile)
overlay.ip_dict.keys()
# In[3]:
dma = overlay.axi_dma_0
blinkled = overlay.blinkled_0
# In[4]:
reduce_size = 8
read_size = 1024
write_size = read_size // reduce_size
src = allocate(shape=(read_size,), dtype=np.int32)
dst = allocate(shape=(write_size,), dtype=np.int32)
bias = allocate(shape=(write_size,), dtype=np.int32)
bias_addr = bias.physical_address
# In[5]:
src[:] = np.arange(read_size, dtype=np.int32)
dst[:] = np.zeros([write_size], dtype=np.int32)
bias[:] = np.ones([write_size], dtype=np.int32)
print(dst[-16:])
# In[6]:
dma.sendchannel.transfer(src)
dma.recvchannel.transfer(dst)
# read_size, write_size, reduce_size, offset
blinkled.write(2 * 4, read_size)
blinkled.write(3 * 4, write_size)
blinkled.write(4 * 4, reduce_size)
blinkled.write(5 * 4, bias_addr)
# start
blinkled.write(0 * 4, 1)
# busy wait
while True:
busy = blinkled.read(1 * 4)
if not busy:
break
# In[7]:
print(dst[-16:])
# In[8]:
expected = np.sum(np.multiply(src, src).reshape([-1, reduce_size]), axis=-1) + bias
print(expected[-16:])
# In[9]:
diff_sum = np.sum(expected - dst)
print(diff_sum)
|
[
"pynq.Overlay",
"numpy.sum",
"numpy.multiply",
"numpy.zeros",
"numpy.ones",
"numpy.arange",
"pynq.allocate"
] |
[((152, 168), 'pynq.Overlay', 'Overlay', (['bitfile'], {}), '(bitfile)\n', (159, 168), False, 'from pynq import Overlay, allocate\n'), ((350, 394), 'pynq.allocate', 'allocate', ([], {'shape': '(read_size,)', 'dtype': 'np.int32'}), '(shape=(read_size,), dtype=np.int32)\n', (358, 394), False, 'from pynq import Overlay, allocate\n'), ((401, 446), 'pynq.allocate', 'allocate', ([], {'shape': '(write_size,)', 'dtype': 'np.int32'}), '(shape=(write_size,), dtype=np.int32)\n', (409, 446), False, 'from pynq import Overlay, allocate\n'), ((454, 499), 'pynq.allocate', 'allocate', ([], {'shape': '(write_size,)', 'dtype': 'np.int32'}), '(shape=(write_size,), dtype=np.int32)\n', (462, 499), False, 'from pynq import Overlay, allocate\n'), ((557, 593), 'numpy.arange', 'np.arange', (['read_size'], {'dtype': 'np.int32'}), '(read_size, dtype=np.int32)\n', (566, 593), True, 'import numpy as np\n'), ((603, 641), 'numpy.zeros', 'np.zeros', (['[write_size]'], {'dtype': 'np.int32'}), '([write_size], dtype=np.int32)\n', (611, 641), True, 'import numpy as np\n'), ((652, 689), 'numpy.ones', 'np.ones', (['[write_size]'], {'dtype': 'np.int32'}), '([write_size], dtype=np.int32)\n', (659, 689), True, 'import numpy as np\n'), ((1256, 1278), 'numpy.sum', 'np.sum', (['(expected - dst)'], {}), '(expected - dst)\n', (1262, 1278), True, 'import numpy as np\n'), ((1144, 1165), 'numpy.multiply', 'np.multiply', (['src', 'src'], {}), '(src, src)\n', (1155, 1165), True, 'import numpy as np\n')]
|
import os
import cv2
import numpy as np
import matplotlib.pyplot as plt
from keras.utils.np_utils import to_categorical
from keras.layers import Conv2D, Dense, Flatten, MaxPooling2D, Dropout
from keras.models import Sequential
from tensorflow.python.keras.utils.vis_utils import plot_model
from sklearn.model_selection import train_test_split
def load_images(image_directory):
image_file_list = []
# 지정한 디렉토리내 파일 추출
image_file_name_list = os.listdir(image_directory)
print(f"대상 이미지 파일수:{len(image_file_name_list)}")
for image_file_name in image_file_name_list:
# 이미지 파일 경로
image_file_path = os.path.join(image_directory, image_file_name)
print(f"이미지 파일 경로:{image_file_path}")
# 이미지 읽기
image = cv2.imread(image_file_path)
if image is None:
print(f"이미지 파일[{image_file_name}]을 읽을 수 없습니다.")
continue
image_file_list.append((image_file_name, image))
print(f"읽은 이미지 수:{len(image_file_list)}")
return image_file_list
def labeling_images(image_file_list):
x_data = []
y_data = []
for idx, (file_name, image) in enumerate(image_file_list):
# 이미지를 BGR 형식에서 RGB 형식으로 변환
# image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# 이미지 배열(RGB 이미지)
x_data.append(image)
# 레이블 배열(파일명의 앞 2글자를 레이블로 이용)
label = int(file_name[0:2])
print(f"레이블:{label:02} 이미지 파일명:{file_name}")
if label != 0: # 00 : True
label = 1 # 99 : False
y_data = np.append(y_data, label).reshape(idx+1, 1)
x_data = np.array(x_data)
print(f"레이블링 이미지 수:{len(x_data)}")
return (x_data, y_data)
def delete_dir(dir_path, is_delete_top_dir=True):
for root, dirs, files in os.walk(dir_path, topdown=False):
for name in files:
os.remove(os.path.join(root, name))
for name in dirs:
os.rmdir(os.path.join(root, name))
if is_delete_top_dir:
os.rmdir(dir_path)
RETURN_SUCCESS = 0
RETURN_FAILURE = -1
# Outoput Model Only
OUTPUT_MODEL_ONLY = False
# Test Image Directory
# TEST_IMAGE_DIR = "./dataset/test"
# # Train Image Directory
# TRAIN_IMAGE_DIR = "./dataset/training"
# resize data 전체를 돌려봅시다!!
RESIZE_IMAGE_DIR = "./dataset/grass_output"
# Output Model Directory
OUTPUT_MODEL_DIR = "./dataset/model"
# Output Model File Name
OUTPUT_MODEL_FILE = "model_relu.h5"
# Output Plot File Name
OUTPUT_PLOT_FILE = "model_relu.png"
def main():
print("===================================================================")
print("Keras를 이용한 모델 학습 ")
print("지정한 이미지 파일을 학습하는 모델 생성")
print("===================================================================")
# 디렉토리 작성
if not os.path.isdir(OUTPUT_MODEL_DIR):
os.mkdir(OUTPUT_MODEL_DIR)
# 디렉토리 내 파일 삭제
delete_dir(OUTPUT_MODEL_DIR, False)
num_classes = 200*200 #카테고리 갯수
batch_size = 32
epochs = 10
# 학습용 이미지 파일 읽기
resize_file_list = load_images(RESIZE_IMAGE_DIR)
# 학습용 이미지 파일 레이블 처리
x, y = labeling_images(resize_file_list) #파일명- 시작하는 두 숫자가 레이블
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3, random_state=42)
# plt.imshow(x_train[0])
# plt.show()
# print(y_train[0])
# # 테스트용 이미지 파일 읽기
# test_file_list = load_images(TEST_IMAGE_DIR)
# # 테스트용 이미지 파일의 레이블 처리
# x_test, y_test = labeling_images(test_file_list)
# plt.imshow(x_test[0])
# plt.show()
# print(y_test[0])
# 이미지와 레이블의 배열 확인: 2차원 배열
print("x_train.shape:", x_train.shape)
print("y_train.shape:", y_train.shape)
print("x_test.shape:", x_test.shape)
print("y_test.shape:", y_test.shape)
# 분류 레이블의 1-hot encoding처리(선형 분류를 쉽게 하기 위해)
y_train = to_categorical(y_train, num_classes)
y_test = to_categorical(y_test, num_classes)
# 이미지와 레이블의 배열 차수 확인 -> 2차원
print("x_train.shape:", x_train.shape)
print("y_train.shape:", y_train.shape)
print("x_test.shape:", x_test.shape)
print("y_test.shape:", y_test.shape)
# 모델 정의
model = Sequential()
#CNN-1
model.add(Conv2D(
input_shape=(200,200,3),
filters=32,
kernel_size=(3,3),
strides=(1,1),
padding="same",
activation='relu',
))
model.add(MaxPooling2D(pool_size=(2, 2)))
#cnn-2
model.add(Conv2D(
filters=32,
kernel_size=(3,3),
strides=(1,1),
padding="same",
activation='relu',
))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.01))
#cnn-3
model.add(Conv2D(
filters=64,
kernel_size=(3,3),
strides=(1,1),
padding="same",
activation='relu',
))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.01))
# fully-connected
model.add(Flatten())
model.add(Dense(512, activation='relu'))
model.add(Dense(128, activation='relu'))
model.add(Dense(40000, activation='sigmoid'))
model.summary()
#compile
model.compile(optimizer='adam',
loss = 'categorical_crossentropy', #'categorical_crossentropy'
metrics= ['accuracy'],
)
plot_file_path = os.path.join(OUTPUT_MODEL_DIR, OUTPUT_PLOT_FILE)
plot_model(model, to_file=plot_file_path, show_shapes=True)
# 모델 시각화
if OUTPUT_MODEL_ONLY: #FALSE
#학습
model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs)
else:
#학습 + 그래프 (학습했던 결과 history에 보관했다가 나중에 그래프 그림)
history = model.fit(x_train, y_train,
batch_size=batch_size, epochs=epochs,
validation_data=(x_test, y_test),verbose=1)
test_loss, test_acc = model.evaluate(x_train, y_train,batch_size=batch_size,verbose=0)
print(f"validation loss:{test_loss}")
print(f"validation accuracy:{test_acc}")
#acc(정확도), loss(손실) 그래프
plt.plot(history.history['accuracy'], label = "accuracy", ls='-', marker="o")
plt.plot(history.history['val_accuracy'], label = "val_accuracy", ls='-', marker="x")
plt.title("model accuracy")
plt.xlabel("Epoch")
plt.ylabel("Accuracy")
plt.legend(loc="best")
plt.show()
#손실 그래프
plt.plot(history.history['loss'], label='loss', ls='-',marker="o")
plt.plot(history.history['val_loss'], label='val_loss', ls='-',marker="x")
plt.title("model loss")
plt.xlabel("Epoch")
plt.ylabel("Loss")
plt.legend(loc="best")
plt.show()
# 모델 저장
model_file_path = os.path.join(OUTPUT_MODEL_DIR, OUTPUT_MODEL_FILE)
model.save(model_file_path)
return RETURN_SUCCESS
if __name__ == "__main__":
main()
|
[
"matplotlib.pyplot.title",
"os.mkdir",
"sklearn.model_selection.train_test_split",
"os.walk",
"tensorflow.python.keras.utils.vis_utils.plot_model",
"os.path.join",
"keras.layers.Flatten",
"numpy.append",
"keras.utils.np_utils.to_categorical",
"keras.layers.MaxPooling2D",
"matplotlib.pyplot.show",
"keras.layers.Dropout",
"matplotlib.pyplot.legend",
"keras.layers.Conv2D",
"os.rmdir",
"matplotlib.pyplot.ylabel",
"os.listdir",
"matplotlib.pyplot.plot",
"os.path.isdir",
"cv2.imread",
"keras.layers.Dense",
"numpy.array",
"keras.models.Sequential",
"matplotlib.pyplot.xlabel"
] |
[((453, 480), 'os.listdir', 'os.listdir', (['image_directory'], {}), '(image_directory)\n', (463, 480), False, 'import os\n'), ((1572, 1588), 'numpy.array', 'np.array', (['x_data'], {}), '(x_data)\n', (1580, 1588), True, 'import numpy as np\n'), ((1736, 1768), 'os.walk', 'os.walk', (['dir_path'], {'topdown': '(False)'}), '(dir_path, topdown=False)\n', (1743, 1768), False, 'import os\n'), ((3110, 3164), 'sklearn.model_selection.train_test_split', 'train_test_split', (['x', 'y'], {'test_size': '(0.3)', 'random_state': '(42)'}), '(x, y, test_size=0.3, random_state=42)\n', (3126, 3164), False, 'from sklearn.model_selection import train_test_split\n'), ((3725, 3761), 'keras.utils.np_utils.to_categorical', 'to_categorical', (['y_train', 'num_classes'], {}), '(y_train, num_classes)\n', (3739, 3761), False, 'from keras.utils.np_utils import to_categorical\n'), ((3775, 3810), 'keras.utils.np_utils.to_categorical', 'to_categorical', (['y_test', 'num_classes'], {}), '(y_test, num_classes)\n', (3789, 3810), False, 'from keras.utils.np_utils import to_categorical\n'), ((4037, 4049), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (4047, 4049), False, 'from keras.models import Sequential\n'), ((5143, 5191), 'os.path.join', 'os.path.join', (['OUTPUT_MODEL_DIR', 'OUTPUT_PLOT_FILE'], {}), '(OUTPUT_MODEL_DIR, OUTPUT_PLOT_FILE)\n', (5155, 5191), False, 'import os\n'), ((5196, 5255), 'tensorflow.python.keras.utils.vis_utils.plot_model', 'plot_model', (['model'], {'to_file': 'plot_file_path', 'show_shapes': '(True)'}), '(model, to_file=plot_file_path, show_shapes=True)\n', (5206, 5255), False, 'from tensorflow.python.keras.utils.vis_utils import plot_model\n'), ((6518, 6567), 'os.path.join', 'os.path.join', (['OUTPUT_MODEL_DIR', 'OUTPUT_MODEL_FILE'], {}), '(OUTPUT_MODEL_DIR, OUTPUT_MODEL_FILE)\n', (6530, 6567), False, 'import os\n'), ((629, 675), 'os.path.join', 'os.path.join', (['image_directory', 'image_file_name'], {}), '(image_directory, image_file_name)\n', (641, 675), False, 'import os\n'), ((755, 782), 'cv2.imread', 'cv2.imread', (['image_file_path'], {}), '(image_file_path)\n', (765, 782), False, 'import cv2\n'), ((1952, 1970), 'os.rmdir', 'os.rmdir', (['dir_path'], {}), '(dir_path)\n', (1960, 1970), False, 'import os\n'), ((2705, 2736), 'os.path.isdir', 'os.path.isdir', (['OUTPUT_MODEL_DIR'], {}), '(OUTPUT_MODEL_DIR)\n', (2718, 2736), False, 'import os\n'), ((2746, 2772), 'os.mkdir', 'os.mkdir', (['OUTPUT_MODEL_DIR'], {}), '(OUTPUT_MODEL_DIR)\n', (2754, 2772), False, 'import os\n'), ((4075, 4196), 'keras.layers.Conv2D', 'Conv2D', ([], {'input_shape': '(200, 200, 3)', 'filters': '(32)', 'kernel_size': '(3, 3)', 'strides': '(1, 1)', 'padding': '"""same"""', 'activation': '"""relu"""'}), "(input_shape=(200, 200, 3), filters=32, kernel_size=(3, 3), strides=(\n 1, 1), padding='same', activation='relu')\n", (4081, 4196), False, 'from keras.layers import Conv2D, Dense, Flatten, MaxPooling2D, Dropout\n'), ((4258, 4288), 'keras.layers.MaxPooling2D', 'MaxPooling2D', ([], {'pool_size': '(2, 2)'}), '(pool_size=(2, 2))\n', (4270, 4288), False, 'from keras.layers import Conv2D, Dense, Flatten, MaxPooling2D, Dropout\n'), ((4315, 4408), 'keras.layers.Conv2D', 'Conv2D', ([], {'filters': '(32)', 'kernel_size': '(3, 3)', 'strides': '(1, 1)', 'padding': '"""same"""', 'activation': '"""relu"""'}), "(filters=32, kernel_size=(3, 3), strides=(1, 1), padding='same',\n activation='relu')\n", (4321, 4408), False, 'from keras.layers import Conv2D, Dense, Flatten, MaxPooling2D, Dropout\n'), ((4465, 4495), 'keras.layers.MaxPooling2D', 'MaxPooling2D', ([], {'pool_size': '(2, 2)'}), '(pool_size=(2, 2))\n', (4477, 4495), False, 'from keras.layers import Conv2D, Dense, Flatten, MaxPooling2D, Dropout\n'), ((4511, 4524), 'keras.layers.Dropout', 'Dropout', (['(0.01)'], {}), '(0.01)\n', (4518, 4524), False, 'from keras.layers import Conv2D, Dense, Flatten, MaxPooling2D, Dropout\n'), ((4551, 4644), 'keras.layers.Conv2D', 'Conv2D', ([], {'filters': '(64)', 'kernel_size': '(3, 3)', 'strides': '(1, 1)', 'padding': '"""same"""', 'activation': '"""relu"""'}), "(filters=64, kernel_size=(3, 3), strides=(1, 1), padding='same',\n activation='relu')\n", (4557, 4644), False, 'from keras.layers import Conv2D, Dense, Flatten, MaxPooling2D, Dropout\n'), ((4701, 4731), 'keras.layers.MaxPooling2D', 'MaxPooling2D', ([], {'pool_size': '(2, 2)'}), '(pool_size=(2, 2))\n', (4713, 4731), False, 'from keras.layers import Conv2D, Dense, Flatten, MaxPooling2D, Dropout\n'), ((4747, 4760), 'keras.layers.Dropout', 'Dropout', (['(0.01)'], {}), '(0.01)\n', (4754, 4760), False, 'from keras.layers import Conv2D, Dense, Flatten, MaxPooling2D, Dropout\n'), ((4798, 4807), 'keras.layers.Flatten', 'Flatten', ([], {}), '()\n', (4805, 4807), False, 'from keras.layers import Conv2D, Dense, Flatten, MaxPooling2D, Dropout\n'), ((4823, 4852), 'keras.layers.Dense', 'Dense', (['(512)'], {'activation': '"""relu"""'}), "(512, activation='relu')\n", (4828, 4852), False, 'from keras.layers import Conv2D, Dense, Flatten, MaxPooling2D, Dropout\n'), ((4868, 4897), 'keras.layers.Dense', 'Dense', (['(128)'], {'activation': '"""relu"""'}), "(128, activation='relu')\n", (4873, 4897), False, 'from keras.layers import Conv2D, Dense, Flatten, MaxPooling2D, Dropout\n'), ((4913, 4947), 'keras.layers.Dense', 'Dense', (['(40000)'], {'activation': '"""sigmoid"""'}), "(40000, activation='sigmoid')\n", (4918, 4947), False, 'from keras.layers import Conv2D, Dense, Flatten, MaxPooling2D, Dropout\n'), ((5855, 5930), 'matplotlib.pyplot.plot', 'plt.plot', (["history.history['accuracy']"], {'label': '"""accuracy"""', 'ls': '"""-"""', 'marker': '"""o"""'}), "(history.history['accuracy'], label='accuracy', ls='-', marker='o')\n", (5863, 5930), True, 'import matplotlib.pyplot as plt\n'), ((5941, 6028), 'matplotlib.pyplot.plot', 'plt.plot', (["history.history['val_accuracy']"], {'label': '"""val_accuracy"""', 'ls': '"""-"""', 'marker': '"""x"""'}), "(history.history['val_accuracy'], label='val_accuracy', ls='-',\n marker='x')\n", (5949, 6028), True, 'import matplotlib.pyplot as plt\n'), ((6035, 6062), 'matplotlib.pyplot.title', 'plt.title', (['"""model accuracy"""'], {}), "('model accuracy')\n", (6044, 6062), True, 'import matplotlib.pyplot as plt\n'), ((6071, 6090), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Epoch"""'], {}), "('Epoch')\n", (6081, 6090), True, 'import matplotlib.pyplot as plt\n'), ((6099, 6121), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Accuracy"""'], {}), "('Accuracy')\n", (6109, 6121), True, 'import matplotlib.pyplot as plt\n'), ((6130, 6152), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""best"""'}), "(loc='best')\n", (6140, 6152), True, 'import matplotlib.pyplot as plt\n'), ((6161, 6171), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6169, 6171), True, 'import matplotlib.pyplot as plt\n'), ((6197, 6264), 'matplotlib.pyplot.plot', 'plt.plot', (["history.history['loss']"], {'label': '"""loss"""', 'ls': '"""-"""', 'marker': '"""o"""'}), "(history.history['loss'], label='loss', ls='-', marker='o')\n", (6205, 6264), True, 'import matplotlib.pyplot as plt\n'), ((6272, 6347), 'matplotlib.pyplot.plot', 'plt.plot', (["history.history['val_loss']"], {'label': '"""val_loss"""', 'ls': '"""-"""', 'marker': '"""x"""'}), "(history.history['val_loss'], label='val_loss', ls='-', marker='x')\n", (6280, 6347), True, 'import matplotlib.pyplot as plt\n'), ((6355, 6378), 'matplotlib.pyplot.title', 'plt.title', (['"""model loss"""'], {}), "('model loss')\n", (6364, 6378), True, 'import matplotlib.pyplot as plt\n'), ((6387, 6406), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Epoch"""'], {}), "('Epoch')\n", (6397, 6406), True, 'import matplotlib.pyplot as plt\n'), ((6415, 6433), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Loss"""'], {}), "('Loss')\n", (6425, 6433), True, 'import matplotlib.pyplot as plt\n'), ((6442, 6464), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""best"""'}), "(loc='best')\n", (6452, 6464), True, 'import matplotlib.pyplot as plt\n'), ((6473, 6483), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6481, 6483), True, 'import matplotlib.pyplot as plt\n'), ((1516, 1540), 'numpy.append', 'np.append', (['y_data', 'label'], {}), '(y_data, label)\n', (1525, 1540), True, 'import numpy as np\n'), ((1819, 1843), 'os.path.join', 'os.path.join', (['root', 'name'], {}), '(root, name)\n', (1831, 1843), False, 'import os\n'), ((1892, 1916), 'os.path.join', 'os.path.join', (['root', 'name'], {}), '(root, name)\n', (1904, 1916), False, 'import os\n')]
|
"""
Convenience functions for the construction of spatial weights based on
contiguity and distance criteria.
"""
__author__ = "<NAME> <<EMAIL>> "
import pysal
from Contiguity import buildContiguity, Queen, Rook
from Distance import knnW, Kernel, DistanceBand
from util import get_ids, get_points_array_from_shapefile, min_threshold_distance
import numpy as np
__all__ = ['queen_from_shapefile', 'rook_from_shapefile', 'knnW_from_array',
'knnW_from_shapefile', 'threshold_binaryW_from_array',
'threshold_binaryW_from_shapefile', 'threshold_continuousW_from_array',
'threshold_continuousW_from_shapefile', 'kernelW', 'kernelW_from_shapefile',
'adaptive_kernelW', 'adaptive_kernelW_from_shapefile',
'min_threshold_dist_from_shapefile', 'build_lattice_shapefile']
def queen_from_shapefile(shapefile, idVariable=None, sparse=False):
"""
Queen contiguity weights from a polygon shapefile.
Parameters
----------
shapefile : string
name of polygon shapefile including suffix.
idVariable : string
name of a column in the shapefile's DBF to use for ids.
sparse : boolean
If True return WSP instance
If False return W instance
Returns
-------
w : W
instance of spatial weights
Examples
--------
>>> wq=queen_from_shapefile(pysal.examples.get_path("columbus.shp"))
>>> "%.3f"%wq.pct_nonzero
'9.829'
>>> wq=queen_from_shapefile(pysal.examples.get_path("columbus.shp"),"POLYID")
>>> "%.3f"%wq.pct_nonzero
'9.829'
>>> wq=queen_from_shapefile(pysal.examples.get_path("columbus.shp"), sparse=True)
>>> pct_sp = wq.sparse.nnz *1. / wq.n**2
>>> "%.3f"%pct_sp
'0.098'
Notes
-----
Queen contiguity defines as neighbors any pair of polygons that share at
least one vertex in their polygon definitions.
See Also
--------
:class:`pysal.weights.W`
"""
w = Queen.from_shapefile(shapefile, idVariable=idVariable)
if sparse:
w = pysal.weights.WSP(w.sparse, id_order=w.id_order)
return w
def rook_from_shapefile(shapefile, idVariable=None, sparse=False):
"""
Rook contiguity weights from a polygon shapefile.
Parameters
----------
shapefile : string
name of polygon shapefile including suffix.
idVariable: string
name of a column in the shapefile's DBF to use for ids
sparse : boolean
If True return WSP instance
If False return W instance
Returns
-------
w : W
instance of spatial weights
Examples
--------
>>> wr=rook_from_shapefile(pysal.examples.get_path("columbus.shp"), "POLYID")
>>> "%.3f"%wr.pct_nonzero
'8.330'
>>> wr=rook_from_shapefile(pysal.examples.get_path("columbus.shp"), sparse=True)
>>> pct_sp = wr.sparse.nnz *1. / wr.n**2
>>> "%.3f"%pct_sp
'0.083'
Notes
-----
Rook contiguity defines as neighbors any pair of polygons that share a
common edge in their polygon definitions.
See Also
--------
:class:`pysal.weights.W`
"""
w = Rook.from_shapefile(shapefile, idVariable=idVariable)
if sparse:
w = pysal.weights.WSP(w.sparse, id_order=w.id_order)
return w
def spw_from_gal(galfile):
"""
Sparse scipy matrix for w from a gal file.
Parameters
----------
galfile : string
name of gal file including suffix
Returns
-------
spw : sparse_matrix
scipy sparse matrix in CSR format
ids : array
identifiers for rows/cols of spw
Examples
--------
>>> spw = pysal.weights.user.spw_from_gal(pysal.examples.get_path("sids2.gal"))
>>> spw.sparse.nnz
462
"""
return pysal.open(galfile, 'r').read(sparse=True)
# Distance based weights
def knnW_from_array(array, k=2, p=2, ids=None, radius=None):
"""
Nearest neighbor weights from a numpy array.
Parameters
----------
data : array
(n,m)
attribute data, n observations on m attributes
k : int
number of nearest neighbors
p : float
Minkowski p-norm distance metric parameter:
1<=p<=infinity
2: Euclidean distance
1: Manhattan distance
ids : list
identifiers to attach to each observation
radius : float
If supplied arc_distances will be calculated
based on the given radius. p will be ignored.
Returns
-------
w : W
instance; Weights object with binary weights.
Examples
--------
>>> import numpy as np
>>> x,y=np.indices((5,5))
>>> x.shape=(25,1)
>>> y.shape=(25,1)
>>> data=np.hstack([x,y])
>>> wnn2=knnW_from_array(data,k=2)
>>> wnn4=knnW_from_array(data,k=4)
>>> set([1, 5, 6, 2]) == set(wnn4.neighbors[0])
True
>>> set([0, 1, 10, 6]) == set(wnn4.neighbors[5])
True
>>> set([1, 5]) == set(wnn2.neighbors[0])
True
>>> set([0,6]) == set(wnn2.neighbors[5])
True
>>> "%.2f"%wnn2.pct_nonzero
'8.00'
>>> wnn4.pct_nonzero
16.0
>>> wnn4=knnW_from_array(data,k=4)
>>> set([ 1,5,6,2]) == set(wnn4.neighbors[0])
True
Notes
-----
Ties between neighbors of equal distance are arbitrarily broken.
See Also
--------
:class:`pysal.weights.W`
"""
if radius is not None:
kdtree = pysal.cg.KDTree(array, distance_metric='Arc', radius=radius)
else:
kdtree = pysal.cg.KDTree(array)
return knnW(kdtree, k=k, p=p, ids=ids)
def knnW_from_shapefile(shapefile, k=2, p=2, idVariable=None, radius=None):
"""
Nearest neighbor weights from a shapefile.
Parameters
----------
shapefile : string
shapefile name with shp suffix
k : int
number of nearest neighbors
p : float
Minkowski p-norm distance metric parameter:
1<=p<=infinity
2: Euclidean distance
1: Manhattan distance
idVariable : string
name of a column in the shapefile's DBF to use for ids
radius : float
If supplied arc_distances will be calculated
based on the given radius. p will be ignored.
Returns
-------
w : W
instance; Weights object with binary weights
Examples
--------
Polygon shapefile
>>> wc=knnW_from_shapefile(pysal.examples.get_path("columbus.shp"))
>>> "%.4f"%wc.pct_nonzero
'4.0816'
>>> set([2,1]) == set(wc.neighbors[0])
True
>>> wc3=pysal.knnW_from_shapefile(pysal.examples.get_path("columbus.shp"),k=3)
>>> set(wc3.neighbors[0]) == set([2,1,3])
True
>>> set(wc3.neighbors[2]) == set([4,3,0])
True
1 offset rather than 0 offset
>>> wc3_1=knnW_from_shapefile(pysal.examples.get_path("columbus.shp"),k=3,idVariable="POLYID")
>>> set([4,3,2]) == set(wc3_1.neighbors[1])
True
>>> wc3_1.weights[2]
[1.0, 1.0, 1.0]
>>> set([4,1,8]) == set(wc3_1.neighbors[2])
True
Point shapefile
>>> w=knnW_from_shapefile(pysal.examples.get_path("juvenile.shp"))
>>> w.pct_nonzero
1.1904761904761905
>>> w1=knnW_from_shapefile(pysal.examples.get_path("juvenile.shp"),k=1)
>>> "%.3f"%w1.pct_nonzero
'0.595'
>>>
Notes
-----
Supports polygon or point shapefiles. For polygon shapefiles, distance is
based on polygon centroids. Distances are defined using coordinates in
shapefile which are assumed to be projected and not geographical
coordinates.
Ties between neighbors of equal distance are arbitrarily broken.
See Also
--------
:class:`pysal.weights.W`
"""
data = get_points_array_from_shapefile(shapefile)
if radius is not None:
kdtree = pysal.cg.KDTree(data, distance_metric='Arc', radius=radius)
else:
kdtree = pysal.cg.KDTree(data)
if idVariable:
ids = get_ids(shapefile, idVariable)
return knnW(kdtree, k=k, p=p, ids=ids)
return knnW(kdtree, k=k, p=p)
def threshold_binaryW_from_array(array, threshold, p=2, radius=None):
"""
Binary weights based on a distance threshold.
Parameters
----------
array : array
(n,m)
attribute data, n observations on m attributes
threshold : float
distance band
p : float
Minkowski p-norm distance metric parameter:
1<=p<=infinity
2: Euclidean distance
1: Manhattan distance
radius : float
If supplied arc_distances will be calculated
based on the given radius. p will be ignored.
Returns
-------
w : W
instance
Weights object with binary weights
Examples
--------
>>> points=[(10, 10), (20, 10), (40, 10), (15, 20), (30, 20), (30, 30)]
>>> wcheck = pysal.W({0: [1, 3], 1: [0, 3, ], 2: [], 3: [1, 0], 4: [5], 5: [4]})
WARNING: there is one disconnected observation (no neighbors)
Island id: [2]
>>> w=threshold_binaryW_from_array(points,threshold=11.2)
WARNING: there is one disconnected observation (no neighbors)
Island id: [2]
>>> pysal.weights.util.neighbor_equality(w, wcheck)
True
>>>
"""
if radius is not None:
array = pysal.cg.KDTree(array, distance_metric='Arc', radius=radius)
return DistanceBand(array, threshold=threshold, p=p)
def threshold_binaryW_from_shapefile(shapefile, threshold, p=2, idVariable=None, radius=None):
"""
Threshold distance based binary weights from a shapefile.
Parameters
----------
shapefile : string
shapefile name with shp suffix
threshold : float
distance band
p : float
Minkowski p-norm distance metric parameter:
1<=p<=infinity
2: Euclidean distance
1: Manhattan distance
idVariable : string
name of a column in the shapefile's DBF to use for ids
radius : float
If supplied arc_distances will be calculated
based on the given radius. p will be ignored.
Returns
-------
w : W
instance
Weights object with binary weights
Examples
--------
>>> w = threshold_binaryW_from_shapefile(pysal.examples.get_path("columbus.shp"),0.62,idVariable="POLYID")
>>> w.weights[1]
[1, 1]
Notes
-----
Supports polygon or point shapefiles. For polygon shapefiles, distance is
based on polygon centroids. Distances are defined using coordinates in
shapefile which are assumed to be projected and not geographical
coordinates.
"""
data = get_points_array_from_shapefile(shapefile)
if radius is not None:
data = pysal.cg.KDTree(data, distance_metric='Arc', radius=radius)
if idVariable:
ids = get_ids(shapefile, idVariable)
w = DistanceBand(data, threshold=threshold, p=p)
w.remap_ids(ids)
return w
return threshold_binaryW_from_array(data, threshold, p=p)
def threshold_continuousW_from_array(array, threshold, p=2,
alpha=-1, radius=None):
"""
Continuous weights based on a distance threshold.
Parameters
----------
array : array
(n,m)
attribute data, n observations on m attributes
threshold : float
distance band
p : float
Minkowski p-norm distance metric parameter:
1<=p<=infinity
2: Euclidean distance
1: Manhattan distance
alpha : float
distance decay parameter for weight (default -1.0)
if alpha is positive the weights will not decline with
distance.
radius : If supplied arc_distances will be calculated
based on the given radius. p will be ignored.
Returns
-------
w : W
instance; Weights object with continuous weights.
Examples
--------
inverse distance weights
>>> points=[(10, 10), (20, 10), (40, 10), (15, 20), (30, 20), (30, 30)]
>>> wid=threshold_continuousW_from_array(points,11.2)
WARNING: there is one disconnected observation (no neighbors)
Island id: [2]
>>> wid.weights[0]
[0.10000000000000001, 0.089442719099991588]
gravity weights
>>> wid2=threshold_continuousW_from_array(points,11.2,alpha=-2.0)
WARNING: there is one disconnected observation (no neighbors)
Island id: [2]
>>> wid2.weights[0]
[0.01, 0.0079999999999999984]
"""
if radius is not None:
array = pysal.cg.KDTree(array, distance_metric='Arc', radius=radius)
w = DistanceBand(
array, threshold=threshold, p=p, alpha=alpha, binary=False)
return w
def threshold_continuousW_from_shapefile(shapefile, threshold, p=2,
alpha=-1, idVariable=None, radius=None):
"""
Threshold distance based continuous weights from a shapefile.
Parameters
----------
shapefile : string
shapefile name with shp suffix
threshold : float
distance band
p : float
Minkowski p-norm distance metric parameter:
1<=p<=infinity
2: Euclidean distance
1: Manhattan distance
alpha : float
distance decay parameter for weight (default -1.0)
if alpha is positive the weights will not decline with
distance.
idVariable : string
name of a column in the shapefile's DBF to use for ids
radius : float
If supplied arc_distances will be calculated
based on the given radius. p will be ignored.
Returns
-------
w : W
instance; Weights object with continuous weights.
Examples
--------
>>> w = threshold_continuousW_from_shapefile(pysal.examples.get_path("columbus.shp"),0.62,idVariable="POLYID")
>>> w.weights[1]
[1.6702346893743334, 1.7250729841938093]
Notes
-----
Supports polygon or point shapefiles. For polygon shapefiles, distance is
based on polygon centroids. Distances are defined using coordinates in
shapefile which are assumed to be projected and not geographical
coordinates.
"""
data = get_points_array_from_shapefile(shapefile)
if radius is not None:
data = pysal.cg.KDTree(data, distance_metric='Arc', radius=radius)
if idVariable:
ids = get_ids(shapefile, idVariable)
w = DistanceBand(data, threshold=threshold, p=p, alpha=alpha, binary=False)
w.remap_ids(ids)
else:
w = threshold_continuousW_from_array(data, threshold, p=p, alpha=alpha)
w.set_shapefile(shapefile,idVariable)
return w
# Kernel Weights
def kernelW(points, k=2, function='triangular', fixed=True,
radius=None, diagonal=False):
"""
Kernel based weights.
Parameters
----------
points : array
(n,k)
n observations on k characteristics used to measure
distances between the n objects
k : int
the number of nearest neighbors to use for determining
bandwidth. Bandwidth taken as :math:`h_i=max(dknn) \\forall i`
where :math:`dknn` is a vector of k-nearest neighbor
distances (the distance to the kth nearest neighbor for each
observation).
function : {'triangular','uniform','quadratic','epanechnikov','quartic','bisquare','gaussian'}
.. math::
z_{i,j} = d_{i,j}/h_i
triangular
.. math::
K(z) = (1 - |z|) \ if |z| \le 1
uniform
.. math::
K(z) = |z| \ if |z| \le 1
quadratic
.. math::
K(z) = (3/4)(1-z^2) \ if |z| \le 1
epanechnikov
.. math::
K(z) = (1-z^2) \ if |z| \le 1
quartic
.. math::
K(z) = (15/16)(1-z^2)^2 \ if |z| \le 1
bisquare
.. math::
K(z) = (1-z^2)^2 \ if |z| \le 1
gaussian
.. math::
K(z) = (2\pi)^{(-1/2)} exp(-z^2 / 2)
fixed : boolean
If true then :math:`h_i=h \\forall i`. If false then
bandwidth is adaptive across observations.
radius : float
If supplied arc_distances will be calculated
based on the given radius. p will be ignored.
diagonal : boolean
If true, set diagonal weights = 1.0, if false (
default) diagonal weights are set to value
according to kernel function.
Returns
-------
w : W
instance of spatial weights
Examples
--------
>>> points=[(10, 10), (20, 10), (40, 10), (15, 20), (30, 20), (30, 30)]
>>> kw=kernelW(points)
>>> kw.weights[0]
[1.0, 0.500000049999995, 0.4409830615267465]
>>> kw.neighbors[0]
[0, 1, 3]
>>> kw.bandwidth
array([[ 20.000002],
[ 20.000002],
[ 20.000002],
[ 20.000002],
[ 20.000002],
[ 20.000002]])
use different k
>>> kw=kernelW(points,k=3)
>>> kw.neighbors[0]
[0, 1, 3, 4]
>>> kw.bandwidth
array([[ 22.36068201],
[ 22.36068201],
[ 22.36068201],
[ 22.36068201],
[ 22.36068201],
[ 22.36068201]])
Diagonals to 1.0
>>> kq = kernelW(points,function='gaussian')
>>> kq.weights
{0: [0.3989422804014327, 0.35206533556593145, 0.3412334260702758], 1: [0.35206533556593145, 0.3989422804014327, 0.2419707487162134, 0.3412334260702758, 0.31069657591175387], 2: [0.2419707487162134, 0.3989422804014327, 0.31069657591175387], 3: [0.3412334260702758, 0.3412334260702758, 0.3989422804014327, 0.3011374490937829, 0.26575287272131043], 4: [0.31069657591175387, 0.31069657591175387, 0.3011374490937829, 0.3989422804014327, 0.35206533556593145], 5: [0.26575287272131043, 0.35206533556593145, 0.3989422804014327]}
>>> kqd = kernelW(points, function='gaussian', diagonal=True)
>>> kqd.weights
{0: [1.0, 0.35206533556593145, 0.3412334260702758], 1: [0.35206533556593145, 1.0, 0.2419707487162134, 0.3412334260702758, 0.31069657591175387], 2: [0.2419707487162134, 1.0, 0.31069657591175387], 3: [0.3412334260702758, 0.3412334260702758, 1.0, 0.3011374490937829, 0.26575287272131043], 4: [0.31069657591175387, 0.31069657591175387, 0.3011374490937829, 1.0, 0.35206533556593145], 5: [0.26575287272131043, 0.35206533556593145, 1.0]}
"""
if radius is not None:
points = pysal.cg.KDTree(points, distance_metric='Arc', radius=radius)
return Kernel(points, function=function, k=k, fixed=fixed,
diagonal=diagonal)
def kernelW_from_shapefile(shapefile, k=2, function='triangular',
idVariable=None, fixed=True, radius=None, diagonal=False):
"""
Kernel based weights.
Parameters
----------
shapefile : string
shapefile name with shp suffix
k : int
the number of nearest neighbors to use for determining
bandwidth. Bandwidth taken as :math:`h_i=max(dknn) \\forall i`
where :math:`dknn` is a vector of k-nearest neighbor
distances (the distance to the kth nearest neighbor for each
observation).
function : {'triangular','uniform','quadratic','epanechnikov', 'quartic','bisquare','gaussian'}
.. math::
z_{i,j} = d_{i,j}/h_i
triangular
.. math::
K(z) = (1 - |z|) \ if |z| \le 1
uniform
.. math::
K(z) = |z| \ if |z| \le 1
quadratic
.. math::
K(z) = (3/4)(1-z^2) \ if |z| \le 1
epanechnikov
.. math::
K(z) = (1-z^2) \ if |z| \le 1
quartic
.. math::
K(z) = (15/16)(1-z^2)^2 \ if |z| \le 1
bisquare
.. math::
K(z) = (1-z^2)^2 \ if |z| \le 1
gaussian
.. math::
K(z) = (2\pi)^{(-1/2)} exp(-z^2 / 2)
idVariable : string
name of a column in the shapefile's DBF to use for ids
fixed : binary
If true then :math:`h_i=h \\forall i`. If false then
bandwidth is adaptive across observations.
radius : float
If supplied arc_distances will be calculated
based on the given radius. p will be ignored.
diagonal : boolean
If true, set diagonal weights = 1.0, if false (
default) diagonal weights are set to value
according to kernel function.
Returns
-------
w : W
instance of spatial weights
Examples
--------
>>> kw = pysal.kernelW_from_shapefile(pysal.examples.get_path("columbus.shp"),idVariable='POLYID', function = 'gaussian')
>>> kwd = pysal.kernelW_from_shapefile(pysal.examples.get_path("columbus.shp"),idVariable='POLYID', function = 'gaussian', diagonal = True)
>>> set(kw.neighbors[1]) == set([4, 2, 3, 1])
True
>>> set(kwd.neighbors[1]) == set([4, 2, 3, 1])
True
>>>
>>> set(kw.weights[1]) == set( [0.2436835517263174, 0.29090631630909874, 0.29671172124745776, 0.3989422804014327])
True
>>> set(kwd.weights[1]) == set( [0.2436835517263174, 0.29090631630909874, 0.29671172124745776, 1.0])
True
Notes
-----
Supports polygon or point shapefiles. For polygon shapefiles, distance is
based on polygon centroids. Distances are defined using coordinates in
shapefile which are assumed to be projected and not geographical
coordinates.
"""
points = get_points_array_from_shapefile(shapefile)
if radius is not None:
points = pysal.cg.KDTree(points, distance_metric='Arc', radius=radius)
if idVariable:
ids = get_ids(shapefile, idVariable)
return Kernel(points, function=function, k=k, ids=ids, fixed=fixed,
diagonal = diagonal)
return kernelW(points, k=k, function=function, fixed=fixed,
diagonal=diagonal)
def adaptive_kernelW(points, bandwidths=None, k=2, function='triangular',
radius=None, diagonal=False):
"""
Kernel weights with adaptive bandwidths.
Parameters
----------
points : array
(n,k)
n observations on k characteristics used to measure
distances between the n objects
bandwidths : float
or array-like (optional)
the bandwidth :math:`h_i` for the kernel.
if no bandwidth is specified k is used to determine the
adaptive bandwidth
k : int
the number of nearest neighbors to use for determining
bandwidth. For fixed bandwidth, :math:`h_i=max(dknn) \\forall i`
where :math:`dknn` is a vector of k-nearest neighbor
distances (the distance to the kth nearest neighbor for each
observation). For adaptive bandwidths, :math:`h_i=dknn_i`
function : {'triangular','uniform','quadratic','quartic','gaussian'}
kernel function defined as follows with
.. math::
z_{i,j} = d_{i,j}/h_i
triangular
.. math::
K(z) = (1 - |z|) \ if |z| \le 1
uniform
.. math::
K(z) = |z| \ if |z| \le 1
quadratic
.. math::
K(z) = (3/4)(1-z^2) \ if |z| \le 1
quartic
.. math::
K(z) = (15/16)(1-z^2)^2 \ if |z| \le 1
gaussian
.. math::
K(z) = (2\pi)^{(-1/2)} exp(-z^2 / 2)
radius : float
If supplied arc_distances will be calculated
based on the given radius. p will be ignored.
diagonal : boolean
If true, set diagonal weights = 1.0, if false (
default) diagonal weights are set to value
according to kernel function.
Returns
-------
w : W
instance of spatial weights
Examples
--------
User specified bandwidths
>>> points=[(10, 10), (20, 10), (40, 10), (15, 20), (30, 20), (30, 30)]
>>> bw=[25.0,15.0,25.0,16.0,14.5,25.0]
>>> kwa=adaptive_kernelW(points,bandwidths=bw)
>>> kwa.weights[0]
[1.0, 0.6, 0.552786404500042, 0.10557280900008403]
>>> kwa.neighbors[0]
[0, 1, 3, 4]
>>> kwa.bandwidth
array([[ 25. ],
[ 15. ],
[ 25. ],
[ 16. ],
[ 14.5],
[ 25. ]])
Endogenous adaptive bandwidths
>>> kwea=adaptive_kernelW(points)
>>> kwea.weights[0]
[1.0, 0.10557289844279438, 9.99999900663795e-08]
>>> kwea.neighbors[0]
[0, 1, 3]
>>> kwea.bandwidth
array([[ 11.18034101],
[ 11.18034101],
[ 20.000002 ],
[ 11.18034101],
[ 14.14213704],
[ 18.02775818]])
Endogenous adaptive bandwidths with Gaussian kernel
>>> kweag=adaptive_kernelW(points,function='gaussian')
>>> kweag.weights[0]
[0.3989422804014327, 0.2674190291577696, 0.2419707487162134]
>>> kweag.bandwidth
array([[ 11.18034101],
[ 11.18034101],
[ 20.000002 ],
[ 11.18034101],
[ 14.14213704],
[ 18.02775818]])
with diagonal
>>> kweag = pysal.adaptive_kernelW(points, function='gaussian')
>>> kweagd = pysal.adaptive_kernelW(points, function='gaussian', diagonal=True)
>>> kweag.neighbors[0]
[0, 1, 3]
>>> kweagd.neighbors[0]
[0, 1, 3]
>>> kweag.weights[0]
[0.3989422804014327, 0.2674190291577696, 0.2419707487162134]
>>> kweagd.weights[0]
[1.0, 0.2674190291577696, 0.2419707487162134]
"""
if radius is not None:
points = pysal.cg.KDTree(points, distance_metric='Arc', radius=radius)
return Kernel(points, bandwidth=bandwidths, fixed=False, k=k,
function=function, diagonal=diagonal)
def adaptive_kernelW_from_shapefile(shapefile, bandwidths=None, k=2, function='triangular',
idVariable=None, radius=None,
diagonal = False):
"""
Kernel weights with adaptive bandwidths.
Parameters
----------
shapefile : string
shapefile name with shp suffix
bandwidths : float
or array-like (optional)
the bandwidth :math:`h_i` for the kernel.
if no bandwidth is specified k is used to determine the
adaptive bandwidth
k : int
the number of nearest neighbors to use for determining
bandwidth. For fixed bandwidth, :math:`h_i=max(dknn) \\forall i`
where :math:`dknn` is a vector of k-nearest neighbor
distances (the distance to the kth nearest neighbor for each
observation). For adaptive bandwidths, :math:`h_i=dknn_i`
function : {'triangular','uniform','quadratic','quartic','gaussian'}
kernel function defined as follows with
.. math::
z_{i,j} = d_{i,j}/h_i
triangular
.. math::
K(z) = (1 - |z|) \ if |z| \le 1
uniform
.. math::
K(z) = |z| \ if |z| \le 1
quadratic
.. math::
K(z) = (3/4)(1-z^2) \ if |z| \le 1
quartic
.. math::
K(z) = (15/16)(1-z^2)^2 \ if |z| \le 1
gaussian
.. math::
K(z) = (2\pi)^{(-1/2)} exp(-z^2 / 2)
idVariable : string
name of a column in the shapefile's DBF to use for ids
radius : float
If supplied arc_distances will be calculated
based on the given radius. p will be ignored.
diagonal : boolean
If true, set diagonal weights = 1.0, if false (
default) diagonal weights are set to value
according to kernel function.
Returns
-------
w : W
instance of spatial weights
Examples
--------
>>> kwa = pysal.adaptive_kernelW_from_shapefile(pysal.examples.get_path("columbus.shp"), function='gaussian')
>>> kwad = pysal.adaptive_kernelW_from_shapefile(pysal.examples.get_path("columbus.shp"), function='gaussian', diagonal=True)
>>> kwa.neighbors[0]
[0, 2, 1]
>>> kwad.neighbors[0]
[0, 2, 1]
>>> kwa.weights[0]
[0.3989422804014327, 0.24966013701844503, 0.2419707487162134]
>>> kwad.weights[0]
[1.0, 0.24966013701844503, 0.2419707487162134]
Notes
-----
Supports polygon or point shapefiles. For polygon shapefiles, distance is
based on polygon centroids. Distances are defined using coordinates in
shapefile which are assumed to be projected and not geographical
coordinates.
"""
points = get_points_array_from_shapefile(shapefile)
if radius is not None:
points = pysal.cg.KDTree(points, distance_metric='Arc', radius=radius)
if idVariable:
ids = get_ids(shapefile, idVariable)
return Kernel(points, bandwidth=bandwidths, fixed=False, k=k,
function=function, ids=ids, diagonal=diagonal)
return adaptive_kernelW(points, bandwidths=bandwidths, k=k,
function=function, diagonal=diagonal)
def min_threshold_dist_from_shapefile(shapefile, radius=None, p=2):
"""
Kernel weights with adaptive bandwidths.
Parameters
----------
shapefile : string
shapefile name with shp suffix.
radius : float
If supplied arc_distances will be calculated
based on the given radius. p will be ignored.
p : float
Minkowski p-norm distance metric parameter:
1<=p<=infinity
2: Euclidean distance
1: Manhattan distance
Returns
-------
d : float
Maximum nearest neighbor distance between the n
observations.
Examples
--------
>>> md = min_threshold_dist_from_shapefile(pysal.examples.get_path("columbus.shp"))
>>> md
0.61886415807685413
>>> min_threshold_dist_from_shapefile(pysal.examples.get_path("stl_hom.shp"), pysal.cg.sphere.RADIUS_EARTH_MILES)
31.846942936393717
Notes
-----
Supports polygon or point shapefiles. For polygon shapefiles, distance is
based on polygon centroids. Distances are defined using coordinates in
shapefile which are assumed to be projected and not geographical
coordinates.
"""
points = get_points_array_from_shapefile(shapefile)
if radius is not None:
kdt = pysal.cg.kdtree.Arc_KDTree(points, radius=radius)
nn = kdt.query(kdt.data, k=2)
nnd = nn[0].max(axis=0)[1]
return nnd
return min_threshold_distance(points, p)
def build_lattice_shapefile(nrows, ncols, outFileName):
"""
Build a lattice shapefile with nrows rows and ncols cols.
Parameters
----------
nrows : int
Number of rows
ncols : int
Number of cols
outFileName : str
shapefile name with shp suffix
Returns
-------
None
"""
if not outFileName.endswith('.shp'):
raise ValueError("outFileName must end with .shp")
o = pysal.open(outFileName, 'w')
dbf_name = outFileName.split(".")[0] + ".dbf"
d = pysal.open(dbf_name, 'w')
d.header = [ 'ID' ]
d.field_spec = [ ('N', 8, 0) ]
c = 0
for i in xrange(nrows):
for j in xrange(ncols):
ll = i, j
ul = i, j + 1
ur = i + 1, j + 1
lr = i + 1, j
o.write(pysal.cg.Polygon([ll, ul, ur, lr, ll]))
d.write([c])
c += 1
d.close()
o.close()
def _test():
import doctest
# the following line could be used to define an alternative to the '<BLANKLINE>' flag
#doctest.BLANKLINE_MARKER = 'something better than <BLANKLINE>'
start_suppress = np.get_printoptions()['suppress']
np.set_printoptions(suppress=True)
doctest.testmod()
np.set_printoptions(suppress=start_suppress)
if __name__ == '__main__':
_test()
|
[
"numpy.set_printoptions",
"pysal.cg.kdtree.Arc_KDTree",
"Contiguity.Queen.from_shapefile",
"pysal.open",
"util.get_ids",
"Distance.knnW",
"Distance.Kernel",
"pysal.weights.WSP",
"pysal.cg.KDTree",
"Distance.DistanceBand",
"Contiguity.Rook.from_shapefile",
"util.min_threshold_distance",
"util.get_points_array_from_shapefile",
"pysal.cg.Polygon",
"doctest.testmod",
"numpy.get_printoptions"
] |
[((2032, 2086), 'Contiguity.Queen.from_shapefile', 'Queen.from_shapefile', (['shapefile'], {'idVariable': 'idVariable'}), '(shapefile, idVariable=idVariable)\n', (2052, 2086), False, 'from Contiguity import buildContiguity, Queen, Rook\n'), ((3247, 3300), 'Contiguity.Rook.from_shapefile', 'Rook.from_shapefile', (['shapefile'], {'idVariable': 'idVariable'}), '(shapefile, idVariable=idVariable)\n', (3266, 3300), False, 'from Contiguity import buildContiguity, Queen, Rook\n'), ((5809, 5840), 'Distance.knnW', 'knnW', (['kdtree'], {'k': 'k', 'p': 'p', 'ids': 'ids'}), '(kdtree, k=k, p=p, ids=ids)\n', (5813, 5840), False, 'from Distance import knnW, Kernel, DistanceBand\n'), ((8067, 8109), 'util.get_points_array_from_shapefile', 'get_points_array_from_shapefile', (['shapefile'], {}), '(shapefile)\n', (8098, 8109), False, 'from util import get_ids, get_points_array_from_shapefile, min_threshold_distance\n'), ((8386, 8408), 'Distance.knnW', 'knnW', (['kdtree'], {'k': 'k', 'p': 'p'}), '(kdtree, k=k, p=p)\n', (8390, 8408), False, 'from Distance import knnW, Kernel, DistanceBand\n'), ((9819, 9864), 'Distance.DistanceBand', 'DistanceBand', (['array'], {'threshold': 'threshold', 'p': 'p'}), '(array, threshold=threshold, p=p)\n', (9831, 9864), False, 'from Distance import knnW, Kernel, DistanceBand\n'), ((11199, 11241), 'util.get_points_array_from_shapefile', 'get_points_array_from_shapefile', (['shapefile'], {}), '(shapefile)\n', (11230, 11241), False, 'from util import get_ids, get_points_array_from_shapefile, min_threshold_distance\n'), ((13279, 13351), 'Distance.DistanceBand', 'DistanceBand', (['array'], {'threshold': 'threshold', 'p': 'p', 'alpha': 'alpha', 'binary': '(False)'}), '(array, threshold=threshold, p=p, alpha=alpha, binary=False)\n', (13291, 13351), False, 'from Distance import knnW, Kernel, DistanceBand\n'), ((14987, 15029), 'util.get_points_array_from_shapefile', 'get_points_array_from_shapefile', (['shapefile'], {}), '(shapefile)\n', (15018, 15029), False, 'from util import get_ids, get_points_array_from_shapefile, min_threshold_distance\n'), ((19689, 19759), 'Distance.Kernel', 'Kernel', (['points'], {'function': 'function', 'k': 'k', 'fixed': 'fixed', 'diagonal': 'diagonal'}), '(points, function=function, k=k, fixed=fixed, diagonal=diagonal)\n', (19695, 19759), False, 'from Distance import knnW, Kernel, DistanceBand\n'), ((23043, 23085), 'util.get_points_array_from_shapefile', 'get_points_array_from_shapefile', (['shapefile'], {}), '(shapefile)\n', (23074, 23085), False, 'from util import get_ids, get_points_array_from_shapefile, min_threshold_distance\n'), ((27507, 27603), 'Distance.Kernel', 'Kernel', (['points'], {'bandwidth': 'bandwidths', 'fixed': '(False)', 'k': 'k', 'function': 'function', 'diagonal': 'diagonal'}), '(points, bandwidth=bandwidths, fixed=False, k=k, function=function,\n diagonal=diagonal)\n', (27513, 27603), False, 'from Distance import knnW, Kernel, DistanceBand\n'), ((30745, 30787), 'util.get_points_array_from_shapefile', 'get_points_array_from_shapefile', (['shapefile'], {}), '(shapefile)\n', (30776, 30787), False, 'from util import get_ids, get_points_array_from_shapefile, min_threshold_distance\n'), ((32492, 32534), 'util.get_points_array_from_shapefile', 'get_points_array_from_shapefile', (['shapefile'], {}), '(shapefile)\n', (32523, 32534), False, 'from util import get_ids, get_points_array_from_shapefile, min_threshold_distance\n'), ((32729, 32762), 'util.min_threshold_distance', 'min_threshold_distance', (['points', 'p'], {}), '(points, p)\n', (32751, 32762), False, 'from util import get_ids, get_points_array_from_shapefile, min_threshold_distance\n'), ((33255, 33283), 'pysal.open', 'pysal.open', (['outFileName', '"""w"""'], {}), "(outFileName, 'w')\n", (33265, 33283), False, 'import pysal\n'), ((33342, 33367), 'pysal.open', 'pysal.open', (['dbf_name', '"""w"""'], {}), "(dbf_name, 'w')\n", (33352, 33367), False, 'import pysal\n'), ((33983, 34017), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'suppress': '(True)'}), '(suppress=True)\n', (34002, 34017), True, 'import numpy as np\n'), ((34022, 34039), 'doctest.testmod', 'doctest.testmod', ([], {}), '()\n', (34037, 34039), False, 'import doctest\n'), ((34044, 34088), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'suppress': 'start_suppress'}), '(suppress=start_suppress)\n', (34063, 34088), True, 'import numpy as np\n'), ((2114, 2162), 'pysal.weights.WSP', 'pysal.weights.WSP', (['w.sparse'], {'id_order': 'w.id_order'}), '(w.sparse, id_order=w.id_order)\n', (2131, 2162), False, 'import pysal\n'), ((3328, 3376), 'pysal.weights.WSP', 'pysal.weights.WSP', (['w.sparse'], {'id_order': 'w.id_order'}), '(w.sparse, id_order=w.id_order)\n', (3345, 3376), False, 'import pysal\n'), ((5687, 5747), 'pysal.cg.KDTree', 'pysal.cg.KDTree', (['array'], {'distance_metric': '"""Arc"""', 'radius': 'radius'}), "(array, distance_metric='Arc', radius=radius)\n", (5702, 5747), False, 'import pysal\n'), ((5775, 5797), 'pysal.cg.KDTree', 'pysal.cg.KDTree', (['array'], {}), '(array)\n', (5790, 5797), False, 'import pysal\n'), ((8155, 8214), 'pysal.cg.KDTree', 'pysal.cg.KDTree', (['data'], {'distance_metric': '"""Arc"""', 'radius': 'radius'}), "(data, distance_metric='Arc', radius=radius)\n", (8170, 8214), False, 'import pysal\n'), ((8242, 8263), 'pysal.cg.KDTree', 'pysal.cg.KDTree', (['data'], {}), '(data)\n', (8257, 8263), False, 'import pysal\n'), ((8297, 8327), 'util.get_ids', 'get_ids', (['shapefile', 'idVariable'], {}), '(shapefile, idVariable)\n', (8304, 8327), False, 'from util import get_ids, get_points_array_from_shapefile, min_threshold_distance\n'), ((8343, 8374), 'Distance.knnW', 'knnW', (['kdtree'], {'k': 'k', 'p': 'p', 'ids': 'ids'}), '(kdtree, k=k, p=p, ids=ids)\n', (8347, 8374), False, 'from Distance import knnW, Kernel, DistanceBand\n'), ((9747, 9807), 'pysal.cg.KDTree', 'pysal.cg.KDTree', (['array'], {'distance_metric': '"""Arc"""', 'radius': 'radius'}), "(array, distance_metric='Arc', radius=radius)\n", (9762, 9807), False, 'import pysal\n'), ((11284, 11343), 'pysal.cg.KDTree', 'pysal.cg.KDTree', (['data'], {'distance_metric': '"""Arc"""', 'radius': 'radius'}), "(data, distance_metric='Arc', radius=radius)\n", (11299, 11343), False, 'import pysal\n'), ((11377, 11407), 'util.get_ids', 'get_ids', (['shapefile', 'idVariable'], {}), '(shapefile, idVariable)\n', (11384, 11407), False, 'from util import get_ids, get_points_array_from_shapefile, min_threshold_distance\n'), ((11420, 11464), 'Distance.DistanceBand', 'DistanceBand', (['data'], {'threshold': 'threshold', 'p': 'p'}), '(data, threshold=threshold, p=p)\n', (11432, 11464), False, 'from Distance import knnW, Kernel, DistanceBand\n'), ((13210, 13270), 'pysal.cg.KDTree', 'pysal.cg.KDTree', (['array'], {'distance_metric': '"""Arc"""', 'radius': 'radius'}), "(array, distance_metric='Arc', radius=radius)\n", (13225, 13270), False, 'import pysal\n'), ((15072, 15131), 'pysal.cg.KDTree', 'pysal.cg.KDTree', (['data'], {'distance_metric': '"""Arc"""', 'radius': 'radius'}), "(data, distance_metric='Arc', radius=radius)\n", (15087, 15131), False, 'import pysal\n'), ((15165, 15195), 'util.get_ids', 'get_ids', (['shapefile', 'idVariable'], {}), '(shapefile, idVariable)\n', (15172, 15195), False, 'from util import get_ids, get_points_array_from_shapefile, min_threshold_distance\n'), ((15208, 15279), 'Distance.DistanceBand', 'DistanceBand', (['data'], {'threshold': 'threshold', 'p': 'p', 'alpha': 'alpha', 'binary': '(False)'}), '(data, threshold=threshold, p=p, alpha=alpha, binary=False)\n', (15220, 15279), False, 'from Distance import knnW, Kernel, DistanceBand\n'), ((19616, 19677), 'pysal.cg.KDTree', 'pysal.cg.KDTree', (['points'], {'distance_metric': '"""Arc"""', 'radius': 'radius'}), "(points, distance_metric='Arc', radius=radius)\n", (19631, 19677), False, 'import pysal\n'), ((23130, 23191), 'pysal.cg.KDTree', 'pysal.cg.KDTree', (['points'], {'distance_metric': '"""Arc"""', 'radius': 'radius'}), "(points, distance_metric='Arc', radius=radius)\n", (23145, 23191), False, 'import pysal\n'), ((23225, 23255), 'util.get_ids', 'get_ids', (['shapefile', 'idVariable'], {}), '(shapefile, idVariable)\n', (23232, 23255), False, 'from util import get_ids, get_points_array_from_shapefile, min_threshold_distance\n'), ((23271, 23350), 'Distance.Kernel', 'Kernel', (['points'], {'function': 'function', 'k': 'k', 'ids': 'ids', 'fixed': 'fixed', 'diagonal': 'diagonal'}), '(points, function=function, k=k, ids=ids, fixed=fixed, diagonal=diagonal)\n', (23277, 23350), False, 'from Distance import knnW, Kernel, DistanceBand\n'), ((27434, 27495), 'pysal.cg.KDTree', 'pysal.cg.KDTree', (['points'], {'distance_metric': '"""Arc"""', 'radius': 'radius'}), "(points, distance_metric='Arc', radius=radius)\n", (27449, 27495), False, 'import pysal\n'), ((30832, 30893), 'pysal.cg.KDTree', 'pysal.cg.KDTree', (['points'], {'distance_metric': '"""Arc"""', 'radius': 'radius'}), "(points, distance_metric='Arc', radius=radius)\n", (30847, 30893), False, 'import pysal\n'), ((30927, 30957), 'util.get_ids', 'get_ids', (['shapefile', 'idVariable'], {}), '(shapefile, idVariable)\n', (30934, 30957), False, 'from util import get_ids, get_points_array_from_shapefile, min_threshold_distance\n'), ((30973, 31078), 'Distance.Kernel', 'Kernel', (['points'], {'bandwidth': 'bandwidths', 'fixed': '(False)', 'k': 'k', 'function': 'function', 'ids': 'ids', 'diagonal': 'diagonal'}), '(points, bandwidth=bandwidths, fixed=False, k=k, function=function,\n ids=ids, diagonal=diagonal)\n', (30979, 31078), False, 'from Distance import knnW, Kernel, DistanceBand\n'), ((32576, 32625), 'pysal.cg.kdtree.Arc_KDTree', 'pysal.cg.kdtree.Arc_KDTree', (['points'], {'radius': 'radius'}), '(points, radius=radius)\n', (32602, 32625), False, 'import pysal\n'), ((33945, 33966), 'numpy.get_printoptions', 'np.get_printoptions', ([], {}), '()\n', (33964, 33966), True, 'import numpy as np\n'), ((3914, 3938), 'pysal.open', 'pysal.open', (['galfile', '"""r"""'], {}), "(galfile, 'r')\n", (3924, 3938), False, 'import pysal\n'), ((33621, 33659), 'pysal.cg.Polygon', 'pysal.cg.Polygon', (['[ll, ul, ur, lr, ll]'], {}), '([ll, ul, ur, lr, ll])\n', (33637, 33659), False, 'import pysal\n')]
|
#!/usr/bin/env python
# coding: utf-8
import argparse
import os
import random
import matplotlib.pyplot as plt
import numpy as np
import torch
import tqdm
from l5kit.configs import load_config_data
from l5kit.dataset import AgentDataset
from l5kit.geometry import transform_points
from l5kit.visualization import (
PREDICTED_POINTS_COLOR,
TARGET_POINTS_COLOR,
draw_trajectory,
)
from torch.utils.data import DataLoader
import lyft_loss
import lyft_utils
import run_lyft_mpred
CFG_PATH = "./agent_motion_config.yaml"
VIS_SELECTED_FRAMES = (99,)
def visualize_prediction(
model,
data_loader: DataLoader,
rasterizer: AgentDataset,
args: argparse.Namespace,
device,
save_name: str = "agent_train_feature",
) -> None:
model.eval()
model.to(device)
os.makedirs(args.output_dir, exist_ok=True)
with torch.no_grad():
dataiter = tqdm.tqdm(data_loader)
for i, data in enumerate(dataiter):
image = data["image"].to(device)
pred, confidences = model(image)
losses = lyft_loss.pytorch_neg_multi_log_likelihood_batch(
data["target_positions"].to(device),
pred,
confidences,
data["target_availabilities"].to(device),
is_reduce=False,
)
# model output
losses = losses.cpu().numpy().squeeze()
pred = pred.cpu().numpy()
confidences = confidences.cpu().numpy()
# meta data
images = image.cpu().numpy()
raster_from_agents = data["raster_from_agent"].numpy()
timestamps = data["timestamp"].numpy()
track_ids = data["track_id"].numpy()
# target data
target_availabilities = data["target_availabilities"].numpy()
target_positions = data["target_positions"].numpy()
# ploting
for ba_ind in range(len(pred)):
_, axarr = plt.subplots(1, 4, figsize=(5 * 4, 5))
# input image
im = images[ba_ind].transpose(1, 2, 0)
im = rasterizer.to_rgb(im)
# plotting ground truth
im_gt = im.copy()
target_positions_pixels = transform_points(
target_positions[ba_ind],
raster_from_agents[ba_ind],
)
draw_trajectory(im_gt, target_positions_pixels, TARGET_POINTS_COLOR)
axarr[0].imshow(im_gt[::-1])
axarr[0].set_title(
"ground truth/pink, loss:{:>3.1f}".format(losses[ba_ind])
)
# plotting prediction of each mode
mode_inds = np.argsort(confidences[ba_ind])[::-1]
for p in range(1, 4):
im_pred = im.copy()
mode_ind = mode_inds[p - 1]
pred_positions_pixels = transform_points(
pred[ba_ind][mode_ind],
raster_from_agents[ba_ind],
)
draw_trajectory(
im_pred,
pred_positions_pixels[target_availabilities[ba_ind] > 0],
PREDICTED_POINTS_COLOR,
)
axarr[p].imshow(im_pred[::-1])
axarr[p].set_title(
"mode:{}, confidence:{:>3.2f}/cyan".format(
p, confidences[ba_ind][mode_ind]
)
)
# save path
save_path = os.path.join(
args.output_dir,
f"{timestamps[ba_ind]}_{track_ids[ba_ind]}.png",
)
plt.savefig(save_path)
plt.show()
def main(cfg: dict, args: argparse.Namespace) -> None:
# set random seeds
SEED = 42
os.environ["PYTHONHASHSEED"] = str(SEED)
# set Python random seed
random.seed(SEED)
# set NumPy random seed
np.random.seed(SEED)
os.environ["CUDA_VISIBLE_DEVICES"] = args.visible_gpus
# ===== Configure LYFT dataset
# mypy error due to pl.DataModule.transfer_batch_to_device
mpred_dm = run_lyft_mpred.LyftMpredDatamodule( # type: ignore[abstract]
args.l5kit_data_folder,
cfg,
batch_size=args.batch_size,
num_workers=args.num_workers,
downsample_train=args.downsample_train,
is_test=False,
is_debug=args.is_debug,
)
mpred_dm.prepare_data()
mpred_dm.setup()
val_datalader = mpred_dm.val_dataloader()
rasterizer = mpred_dm.rasterizer
print("load from: ", args.ckpt_path)
model = run_lyft_mpred.LitModel.load_from_checkpoint(args.ckpt_path, cfg=cfg)
device = torch.device("cuda")
visualize_prediction(model, val_datalader, rasterizer, args, device)
if __name__ == "__main__":
cfg = load_config_data(CFG_PATH)
parser = argparse.ArgumentParser(
description="Visualize lyft motion prediction",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument(
"--l5kit_data_folder",
default="/your/dataset/path",
type=str,
help="root directory path for lyft motion prediction dataset",
)
parser.add_argument(
"--num_modes",
type=int,
default=3,
help="number of the modes on each prediction",
)
parser.add_argument("--batch_size", type=int, default=220, help="batch size")
parser.add_argument(
"--downsample_train",
action="store_true",
help="using only 4 frames from each scene, the loss converge is \
much faster than using all data, but it will get larger loss",
)
parser.add_argument(
"--ckpt_path",
type=str,
default="./model.pth",
help="path for model checkpoint at test mode",
)
parser.add_argument(
"--visible_gpus",
type=str,
default="0",
help="Select gpu ids with comma separated format",
)
parser.add_argument(
"--num_workers",
default="16",
type=int,
help="number of cpus for DataLoader",
)
parser.add_argument("--is_debug", action="store_true", help="debug mode")
parser.add_argument(
"--output_dir",
type=str,
default="./prediction_images",
help="directory for visualized images",
)
args = parser.parse_args()
if args.is_debug:
DEBUG = True
print("\t ---- DEBUG RUN ---- ")
cfg["train_data_loader"]["key"] = "scenes/sample.zarr"
cfg["val_data_loader"]["key"] = "scenes/sample.zarr"
args.batch_size = 16
else:
DEBUG = False
print("\t ---- NORMAL RUN ---- ")
lyft_utils.print_argparse_arguments(args)
main(cfg, args)
|
[
"l5kit.geometry.transform_points",
"l5kit.visualization.draw_trajectory",
"tqdm.tqdm",
"l5kit.configs.load_config_data",
"numpy.random.seed",
"os.makedirs",
"argparse.ArgumentParser",
"lyft_utils.print_argparse_arguments",
"os.path.join",
"matplotlib.pyplot.show",
"run_lyft_mpred.LitModel.load_from_checkpoint",
"numpy.argsort",
"random.seed",
"run_lyft_mpred.LyftMpredDatamodule",
"torch.device",
"torch.no_grad",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.savefig"
] |
[((796, 839), 'os.makedirs', 'os.makedirs', (['args.output_dir'], {'exist_ok': '(True)'}), '(args.output_dir, exist_ok=True)\n', (807, 839), False, 'import os\n'), ((4008, 4025), 'random.seed', 'random.seed', (['SEED'], {}), '(SEED)\n', (4019, 4025), False, 'import random\n'), ((4058, 4078), 'numpy.random.seed', 'np.random.seed', (['SEED'], {}), '(SEED)\n', (4072, 4078), True, 'import numpy as np\n'), ((4253, 4463), 'run_lyft_mpred.LyftMpredDatamodule', 'run_lyft_mpred.LyftMpredDatamodule', (['args.l5kit_data_folder', 'cfg'], {'batch_size': 'args.batch_size', 'num_workers': 'args.num_workers', 'downsample_train': 'args.downsample_train', 'is_test': '(False)', 'is_debug': 'args.is_debug'}), '(args.l5kit_data_folder, cfg, batch_size=\n args.batch_size, num_workers=args.num_workers, downsample_train=args.\n downsample_train, is_test=False, is_debug=args.is_debug)\n', (4287, 4463), False, 'import run_lyft_mpred\n'), ((4729, 4798), 'run_lyft_mpred.LitModel.load_from_checkpoint', 'run_lyft_mpred.LitModel.load_from_checkpoint', (['args.ckpt_path'], {'cfg': 'cfg'}), '(args.ckpt_path, cfg=cfg)\n', (4773, 4798), False, 'import run_lyft_mpred\n'), ((4812, 4832), 'torch.device', 'torch.device', (['"""cuda"""'], {}), "('cuda')\n", (4824, 4832), False, 'import torch\n'), ((4945, 4971), 'l5kit.configs.load_config_data', 'load_config_data', (['CFG_PATH'], {}), '(CFG_PATH)\n', (4961, 4971), False, 'from l5kit.configs import load_config_data\n'), ((4986, 5117), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Visualize lyft motion prediction"""', 'formatter_class': 'argparse.ArgumentDefaultsHelpFormatter'}), "(description='Visualize lyft motion prediction',\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n", (5009, 5117), False, 'import argparse\n'), ((6822, 6863), 'lyft_utils.print_argparse_arguments', 'lyft_utils.print_argparse_arguments', (['args'], {}), '(args)\n', (6857, 6863), False, 'import lyft_utils\n'), ((850, 865), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (863, 865), False, 'import torch\n'), ((886, 908), 'tqdm.tqdm', 'tqdm.tqdm', (['data_loader'], {}), '(data_loader)\n', (895, 908), False, 'import tqdm\n'), ((1984, 2022), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(4)'], {'figsize': '(5 * 4, 5)'}), '(1, 4, figsize=(5 * 4, 5))\n', (1996, 2022), True, 'import matplotlib.pyplot as plt\n'), ((2267, 2337), 'l5kit.geometry.transform_points', 'transform_points', (['target_positions[ba_ind]', 'raster_from_agents[ba_ind]'], {}), '(target_positions[ba_ind], raster_from_agents[ba_ind])\n', (2283, 2337), False, 'from l5kit.geometry import transform_points\n'), ((2413, 2481), 'l5kit.visualization.draw_trajectory', 'draw_trajectory', (['im_gt', 'target_positions_pixels', 'TARGET_POINTS_COLOR'], {}), '(im_gt, target_positions_pixels, TARGET_POINTS_COLOR)\n', (2428, 2481), False, 'from l5kit.visualization import PREDICTED_POINTS_COLOR, TARGET_POINTS_COLOR, draw_trajectory\n'), ((3632, 3710), 'os.path.join', 'os.path.join', (['args.output_dir', 'f"""{timestamps[ba_ind]}_{track_ids[ba_ind]}.png"""'], {}), "(args.output_dir, f'{timestamps[ba_ind]}_{track_ids[ba_ind]}.png')\n", (3644, 3710), False, 'import os\n'), ((3786, 3808), 'matplotlib.pyplot.savefig', 'plt.savefig', (['save_path'], {}), '(save_path)\n', (3797, 3808), True, 'import matplotlib.pyplot as plt\n'), ((3825, 3835), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3833, 3835), True, 'import matplotlib.pyplot as plt\n'), ((2738, 2769), 'numpy.argsort', 'np.argsort', (['confidences[ba_ind]'], {}), '(confidences[ba_ind])\n', (2748, 2769), True, 'import numpy as np\n'), ((2946, 3014), 'l5kit.geometry.transform_points', 'transform_points', (['pred[ba_ind][mode_ind]', 'raster_from_agents[ba_ind]'], {}), '(pred[ba_ind][mode_ind], raster_from_agents[ba_ind])\n', (2962, 3014), False, 'from l5kit.geometry import transform_points\n'), ((3106, 3217), 'l5kit.visualization.draw_trajectory', 'draw_trajectory', (['im_pred', 'pred_positions_pixels[target_availabilities[ba_ind] > 0]', 'PREDICTED_POINTS_COLOR'], {}), '(im_pred, pred_positions_pixels[target_availabilities[ba_ind\n ] > 0], PREDICTED_POINTS_COLOR)\n', (3121, 3217), False, 'from l5kit.visualization import PREDICTED_POINTS_COLOR, TARGET_POINTS_COLOR, draw_trajectory\n')]
|
import cv2 as cv
import numpy as np
# 分水岭算法
def watershed_image():
print(src.shape)
blurred = cv.pyrMeanShiftFiltering(src, 10, 100) # 利用边缘滤波,去除噪点
# gray\binary image 灰度二值图像
gray = cv.cvtColor(blurred, cv.COLOR_BGR2GRAY)
ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY | cv.THRESH_OTSU)
cv.imshow("binary_image", binary)
# morphology operation 形态学操作
kernel = cv.getStructuringElement(cv.MORPH_RECT, (3, 3)) #结构元素
mb = cv.morphologyEx(binary, cv.MORPH_OPEN, kernel, iterations=2) #连续两次开操作
sure_bg = cv.dilate(mb, kernel, iterations=3)
cv.imshow("mor_opt", sure_bg)
# distance transform 对上面的mb进行距离变换
dist = cv.distanceTransform(mb, cv.DIST_L2, 3)
dist_output = cv.normalize(dist, 0, 1.0, cv.NORM_MINMAX)
cv.imshow("distance", dist_output * 70)
ret, surface = cv.threshold(dist, dist.max() * 0.6, 255, cv.THRESH_BINARY)
cv.imshow("surface-bin", surface)
surface_fg = np.uint8(surface)
unknown = cv.subtract(sure_bg, surface_fg)
ret, markers = cv.connectedComponents(surface_fg)
print(ret)
# watershed transfrom 分水岭变换
markers += 1
markers[unknown == 255] = 0
markers = cv.watershed(src, markers=markers)
src[markers == -1] = [0, 0, 255]
cv.imshow("result", src)
src = cv.imread('F:00.jpg')
#cv.namedWindow('input_image', cv.WINDOW_AUTOSIZE)
cv.imshow("0", src)
watershed_image()
cv.waitKey(0)
cv.destroyAllWindows()
|
[
"numpy.uint8",
"cv2.subtract",
"cv2.dilate",
"cv2.waitKey",
"cv2.destroyAllWindows",
"cv2.cvtColor",
"cv2.threshold",
"cv2.getStructuringElement",
"cv2.morphologyEx",
"cv2.watershed",
"cv2.connectedComponents",
"cv2.imread",
"cv2.pyrMeanShiftFiltering",
"cv2.normalize",
"cv2.imshow",
"cv2.distanceTransform"
] |
[((1338, 1359), 'cv2.imread', 'cv.imread', (['"""F:00.jpg"""'], {}), "('F:00.jpg')\n", (1347, 1359), True, 'import cv2 as cv\n'), ((1413, 1432), 'cv2.imshow', 'cv.imshow', (['"""0"""', 'src'], {}), "('0', src)\n", (1422, 1432), True, 'import cv2 as cv\n'), ((1453, 1466), 'cv2.waitKey', 'cv.waitKey', (['(0)'], {}), '(0)\n', (1463, 1466), True, 'import cv2 as cv\n'), ((1468, 1490), 'cv2.destroyAllWindows', 'cv.destroyAllWindows', ([], {}), '()\n', (1488, 1490), True, 'import cv2 as cv\n'), ((111, 149), 'cv2.pyrMeanShiftFiltering', 'cv.pyrMeanShiftFiltering', (['src', '(10)', '(100)'], {}), '(src, 10, 100)\n', (135, 149), True, 'import cv2 as cv\n'), ((211, 250), 'cv2.cvtColor', 'cv.cvtColor', (['blurred', 'cv.COLOR_BGR2GRAY'], {}), '(blurred, cv.COLOR_BGR2GRAY)\n', (222, 250), True, 'import cv2 as cv\n'), ((270, 331), 'cv2.threshold', 'cv.threshold', (['gray', '(0)', '(255)', '(cv.THRESH_BINARY | cv.THRESH_OTSU)'], {}), '(gray, 0, 255, cv.THRESH_BINARY | cv.THRESH_OTSU)\n', (282, 331), True, 'import cv2 as cv\n'), ((337, 370), 'cv2.imshow', 'cv.imshow', (['"""binary_image"""', 'binary'], {}), "('binary_image', binary)\n", (346, 370), True, 'import cv2 as cv\n'), ((422, 469), 'cv2.getStructuringElement', 'cv.getStructuringElement', (['cv.MORPH_RECT', '(3, 3)'], {}), '(cv.MORPH_RECT, (3, 3))\n', (446, 469), True, 'import cv2 as cv\n'), ((488, 548), 'cv2.morphologyEx', 'cv.morphologyEx', (['binary', 'cv.MORPH_OPEN', 'kernel'], {'iterations': '(2)'}), '(binary, cv.MORPH_OPEN, kernel, iterations=2)\n', (503, 548), True, 'import cv2 as cv\n'), ((574, 609), 'cv2.dilate', 'cv.dilate', (['mb', 'kernel'], {'iterations': '(3)'}), '(mb, kernel, iterations=3)\n', (583, 609), True, 'import cv2 as cv\n'), ((615, 644), 'cv2.imshow', 'cv.imshow', (['"""mor_opt"""', 'sure_bg'], {}), "('mor_opt', sure_bg)\n", (624, 644), True, 'import cv2 as cv\n'), ((698, 737), 'cv2.distanceTransform', 'cv.distanceTransform', (['mb', 'cv.DIST_L2', '(3)'], {}), '(mb, cv.DIST_L2, 3)\n', (718, 737), True, 'import cv2 as cv\n'), ((757, 799), 'cv2.normalize', 'cv.normalize', (['dist', '(0)', '(1.0)', 'cv.NORM_MINMAX'], {}), '(dist, 0, 1.0, cv.NORM_MINMAX)\n', (769, 799), True, 'import cv2 as cv\n'), ((805, 844), 'cv2.imshow', 'cv.imshow', (['"""distance"""', '(dist_output * 70)'], {}), "('distance', dist_output * 70)\n", (814, 844), True, 'import cv2 as cv\n'), ((932, 965), 'cv2.imshow', 'cv.imshow', (['"""surface-bin"""', 'surface'], {}), "('surface-bin', surface)\n", (941, 965), True, 'import cv2 as cv\n'), ((986, 1003), 'numpy.uint8', 'np.uint8', (['surface'], {}), '(surface)\n', (994, 1003), True, 'import numpy as np\n'), ((1019, 1051), 'cv2.subtract', 'cv.subtract', (['sure_bg', 'surface_fg'], {}), '(sure_bg, surface_fg)\n', (1030, 1051), True, 'import cv2 as cv\n'), ((1072, 1106), 'cv2.connectedComponents', 'cv.connectedComponents', (['surface_fg'], {}), '(surface_fg)\n', (1094, 1106), True, 'import cv2 as cv\n'), ((1224, 1258), 'cv2.watershed', 'cv.watershed', (['src'], {'markers': 'markers'}), '(src, markers=markers)\n', (1236, 1258), True, 'import cv2 as cv\n'), ((1302, 1326), 'cv2.imshow', 'cv.imshow', (['"""result"""', 'src'], {}), "('result', src)\n", (1311, 1326), True, 'import cv2 as cv\n')]
|
####################################################################
# Copyright (c) 2019 <NAME> #
# #
# This source code is licensed under the MIT license found in the #
# LICENSE file in the root directory of this source tree. #
####################################################################
import PyDelFEM2 as dfm2
import PyDelFEM2.gl.glfw
import numpy, math
def height_map():
A0 = numpy.zeros((16,32))
for iy in range(A0.shape[0]):
for ix in range(A0.shape[1]):
A0[iy,ix] = 5*math.sin(ix*0.4)*math.cos(iy*0.6) + 5
msh = dfm2.Mesh()
msh.set_grid([A0.shape[1],A0.shape[0]])
msh.np_pos = numpy.hstack((msh.np_pos,A0.reshape((-1,1))))
axis = dfm2.gl.AxisXYZ(32)
print("hight_map")
dfm2.gl.glfw.winDraw3d([msh,axis],(400,400))
print("edge_quad_mesh")
msh_edge = msh.mesh_edge()
dfm2.gl.glfw.winDraw3d([msh_edge,axis])
def edge_tri():
msh = dfm2.Mesh()
msh.read("../test_inputs/bunny_2k.ply")
msh_edge = msh.mesh_edge()
dfm2.gl.glfw.winDraw3d([msh_edge,msh.aabb3()])
def edge_quad_hex():
grid = dfm2.VoxelGrid()
grid.add(0, 0, 0)
grid.add(1, 0, 0)
grid.add(1, 1, 0)
msh = grid.mesh_hex()
msh = msh.subdiv()
msh_edge = msh.mesh_edge()
dfm2.gl.glfw.winDraw3d([msh_edge])
msh = grid.mesh_quad()
msh = msh.subdiv()
msh_edge = msh.mesh_edge()
dfm2.gl.glfw.winDraw3d([msh_edge])
def primitive():
msh = dfm2.Mesh()
msh.set_cylinder(1.0,1.0, 16, 4)
dfm2.gl.glfw.winDraw3d([msh])
msh.set_sphere(1.0,16, 32)
dfm2.gl.glfw.winDraw3d([msh])
msh.set_icosahedron()
dfm2.gl.glfw.winDraw3d([msh])
msh.set_geopoly()
dfm2.gl.glfw.winDraw3d([msh])
msh.set_torus(2,1)
dfm2.gl.glfw.winDraw3d([msh])
def read_file():
msh = dfm2.Mesh()
msh.read("../test_inputs/A.obj")
dfm2.gl.glfw.winDraw3d([msh,msh.aabb3(),dfm2.gl.AxisXYZ()])
msh.rotate([3.1415*0.5, 0.0, 0.0])
dfm2.gl.glfw.winDraw3d([msh, msh.aabb3(), dfm2.gl.AxisXYZ()])
msh.translate([1, 1.0, 0.0], 1.0)
dfm2.gl.glfw.winDraw3d([msh, msh.aabb3(), dfm2.gl.AxisXYZ()])
msh.read("../test_inputs/bunny_2k.ply")
dfm2.gl.glfw.winDraw3d([msh,msh.aabb3()])
msh.read("../test_inputs/bunny_1k.obj")
dfm2.gl.glfw.winDraw3d([msh,msh.aabb3()])
if __name__ == "__main__":
read_file()
height_map()
edge_tri()
edge_quad_hex()
primitive()
|
[
"PyDelFEM2.Mesh",
"numpy.zeros",
"PyDelFEM2.VoxelGrid",
"math.sin",
"PyDelFEM2.gl.glfw.winDraw3d",
"math.cos",
"PyDelFEM2.gl.AxisXYZ"
] |
[((501, 522), 'numpy.zeros', 'numpy.zeros', (['(16, 32)'], {}), '((16, 32))\n', (512, 522), False, 'import numpy, math\n'), ((655, 666), 'PyDelFEM2.Mesh', 'dfm2.Mesh', ([], {}), '()\n', (664, 666), True, 'import PyDelFEM2 as dfm2\n'), ((779, 798), 'PyDelFEM2.gl.AxisXYZ', 'dfm2.gl.AxisXYZ', (['(32)'], {}), '(32)\n', (794, 798), True, 'import PyDelFEM2 as dfm2\n'), ((822, 869), 'PyDelFEM2.gl.glfw.winDraw3d', 'dfm2.gl.glfw.winDraw3d', (['[msh, axis]', '(400, 400)'], {}), '([msh, axis], (400, 400))\n', (844, 869), True, 'import PyDelFEM2 as dfm2\n'), ((925, 965), 'PyDelFEM2.gl.glfw.winDraw3d', 'dfm2.gl.glfw.winDraw3d', (['[msh_edge, axis]'], {}), '([msh_edge, axis])\n', (947, 965), True, 'import PyDelFEM2 as dfm2\n'), ((991, 1002), 'PyDelFEM2.Mesh', 'dfm2.Mesh', ([], {}), '()\n', (1000, 1002), True, 'import PyDelFEM2 as dfm2\n'), ((1155, 1171), 'PyDelFEM2.VoxelGrid', 'dfm2.VoxelGrid', ([], {}), '()\n', (1169, 1171), True, 'import PyDelFEM2 as dfm2\n'), ((1308, 1342), 'PyDelFEM2.gl.glfw.winDraw3d', 'dfm2.gl.glfw.winDraw3d', (['[msh_edge]'], {}), '([msh_edge])\n', (1330, 1342), True, 'import PyDelFEM2 as dfm2\n'), ((1421, 1455), 'PyDelFEM2.gl.glfw.winDraw3d', 'dfm2.gl.glfw.winDraw3d', (['[msh_edge]'], {}), '([msh_edge])\n', (1443, 1455), True, 'import PyDelFEM2 as dfm2\n'), ((1482, 1493), 'PyDelFEM2.Mesh', 'dfm2.Mesh', ([], {}), '()\n', (1491, 1493), True, 'import PyDelFEM2 as dfm2\n'), ((1531, 1560), 'PyDelFEM2.gl.glfw.winDraw3d', 'dfm2.gl.glfw.winDraw3d', (['[msh]'], {}), '([msh])\n', (1553, 1560), True, 'import PyDelFEM2 as dfm2\n'), ((1593, 1622), 'PyDelFEM2.gl.glfw.winDraw3d', 'dfm2.gl.glfw.winDraw3d', (['[msh]'], {}), '([msh])\n', (1615, 1622), True, 'import PyDelFEM2 as dfm2\n'), ((1650, 1679), 'PyDelFEM2.gl.glfw.winDraw3d', 'dfm2.gl.glfw.winDraw3d', (['[msh]'], {}), '([msh])\n', (1672, 1679), True, 'import PyDelFEM2 as dfm2\n'), ((1703, 1732), 'PyDelFEM2.gl.glfw.winDraw3d', 'dfm2.gl.glfw.winDraw3d', (['[msh]'], {}), '([msh])\n', (1725, 1732), True, 'import PyDelFEM2 as dfm2\n'), ((1757, 1786), 'PyDelFEM2.gl.glfw.winDraw3d', 'dfm2.gl.glfw.winDraw3d', (['[msh]'], {}), '([msh])\n', (1779, 1786), True, 'import PyDelFEM2 as dfm2\n'), ((1814, 1825), 'PyDelFEM2.Mesh', 'dfm2.Mesh', ([], {}), '()\n', (1823, 1825), True, 'import PyDelFEM2 as dfm2\n'), ((1904, 1921), 'PyDelFEM2.gl.AxisXYZ', 'dfm2.gl.AxisXYZ', ([], {}), '()\n', (1919, 1921), True, 'import PyDelFEM2 as dfm2\n'), ((2006, 2023), 'PyDelFEM2.gl.AxisXYZ', 'dfm2.gl.AxisXYZ', ([], {}), '()\n', (2021, 2023), True, 'import PyDelFEM2 as dfm2\n'), ((2107, 2124), 'PyDelFEM2.gl.AxisXYZ', 'dfm2.gl.AxisXYZ', ([], {}), '()\n', (2122, 2124), True, 'import PyDelFEM2 as dfm2\n'), ((625, 643), 'math.cos', 'math.cos', (['(iy * 0.6)'], {}), '(iy * 0.6)\n', (633, 643), False, 'import numpy, math\n'), ((608, 626), 'math.sin', 'math.sin', (['(ix * 0.4)'], {}), '(ix * 0.4)\n', (616, 626), False, 'import numpy, math\n')]
|
import os
import h5py
import numpy as np
def copy_file_struct(f, hmap, fo):
"""
Iteratively copy a HDF5 file structure to a new file
Arguments:
-f : File from which to copy [OPEN HDF5 file handle]
-hmap : Current file object of interest to copy from
-fo : File to copy structure to [OPEN HDF5 file handle]
"""
# First, see if object is a group
if type(hmap) == h5py._hl.group.Group:
name = hmap.name.encode("ascii")
# Copy attributes associated with group
atts = f[name].attrs.keys()
if len(atts) > 0:
group = fo.create_group(name)
for v in atts:
group.attrs[v] = f[name].attrs[v]
# Now deal with subgroups and datasets
for w in hmap:
if type(f[name][w]) == h5py._hl.group.Group:
atts = f[name][w].attrs.keys()
if len(atts) > 0:
group = fo.create_group("{0}/{1}".format(name, w))
for v in atts:
group.attrs[v] = f[name][w].attrs[v]
copy_file_struct(f, f[name][w], fo)
elif type(f[name][w]) == h5py._hl.dataset.Dataset:
tmp = np.zeros(f[name][w][:].shape, dtype=f[name][w][:].dtype)
tmp[:] = f[name][w][:]
dset = fo.create_dataset(
"{0}/{1}".format(name.decode("utf-8"), w),
data=tmp,
dtype=f[name][w][:].dtype,
)
del tmp
atts = f[name][w].attrs.keys()
if len(atts) > 0:
for v in atts:
dset.attrs[v] = f[name][w].attrs[v]
# Otherwise deal with the dataset
elif type(hmap) == h5py._hl.dataset.Dataset:
name = hmap.name.encode("ascii")
tmp = np.zeros(f[name][:].shape, dtype=f[name][:].dtype)
tmp[:] = f[name][:]
dset = fo.create_dataset(name.decode("utf-8"), data=tmp, dtype=f[name][:].dtype)
atts = f[name].attrs.keys()
if len(atts) > 0:
for v in atts:
dset.attrs[v] = f[name].attrs[v]
del tmp
return
def merge_outputs(outputs):
"""
Merge all outputs from different processors into one file
Arguments:
-outputs : Search term for output files of interest [STRING]
"""
print(" > Merging {0}*".format(outputs), flush=True)
# Find outputs of interest
files = []
for y in os.listdir("output/"):
if y.startswith(outputs):
files.append("output/{0}".format(y))
files.sort()
# Create output file
flib = "output/{0}.hdf5".format(outputs)
outf = h5py.File(flib, "w")
# Loop over files of interest, iteratively copying data to consolidated output file
for y in files:
if y == flib:
continue
print(" -{0}".format(y), flush=True)
f = h5py.File(y, "r")
fk = sorted(f.keys())
for z in fk:
print(" --> {0}".format(z), flush=True)
copy_file_struct(f, f[z], outf)
f.close()
os.remove(y)
outf.close()
del files, flib
return
|
[
"h5py.File",
"numpy.zeros",
"os.listdir",
"os.remove"
] |
[((2497, 2518), 'os.listdir', 'os.listdir', (['"""output/"""'], {}), "('output/')\n", (2507, 2518), False, 'import os\n'), ((2702, 2722), 'h5py.File', 'h5py.File', (['flib', '"""w"""'], {}), "(flib, 'w')\n", (2711, 2722), False, 'import h5py\n'), ((2933, 2950), 'h5py.File', 'h5py.File', (['y', '"""r"""'], {}), "(y, 'r')\n", (2942, 2950), False, 'import h5py\n'), ((3125, 3137), 'os.remove', 'os.remove', (['y'], {}), '(y)\n', (3134, 3137), False, 'import os\n'), ((1856, 1906), 'numpy.zeros', 'np.zeros', (['f[name][:].shape'], {'dtype': 'f[name][:].dtype'}), '(f[name][:].shape, dtype=f[name][:].dtype)\n', (1864, 1906), True, 'import numpy as np\n'), ((1218, 1274), 'numpy.zeros', 'np.zeros', (['f[name][w][:].shape'], {'dtype': 'f[name][w][:].dtype'}), '(f[name][w][:].shape, dtype=f[name][w][:].dtype)\n', (1226, 1274), True, 'import numpy as np\n')]
|
import numpy as np
from ..orbit import calcNhat
def test_calcNhat_normalized():
state_vectors = np.array([
[1.0, 0.0, 0.0, 0.0, 0.002, 0.000],
[1.0, 0.0, 1.0, 0.0, 0.002, 0.000],
[1.0, 0.0, 1.0, 0.0, 0.000, 0.002]
])
n_hat = calcNhat(state_vectors)
n_hat_norm = np.linalg.norm(n_hat, axis=1)
# Each vector should have magnitude of 1.0
np.testing.assert_equal(np.ones(len(n_hat)), n_hat_norm)
return
def test_calcNhat_orientation():
state_vectors = np.array([
[1.0, 0.0, 0.0, 0.0, 0.002, 0.000],
[1.0, 0.0, 1.0, 0.0, 0.002, 0.000],
[1.0, 0.0, 1.0, 0.0, 0.000, 0.002]
])
n_hat = calcNhat(state_vectors)
# First orbit lies in the x-y plane and so should have a unit
# vector normal equivalent to the z-axis
np.testing.assert_equal(np.array([0., 0., 1.0]), n_hat[0])
# Second orbit lies in a plane inclined 45 degrees from the x-y plane, intersecting
# the x-y plane along the y-axis.
np.testing.assert_equal(np.array([-np.sqrt(2)/2, 0.0, np.sqrt(2)/2]), n_hat[1])
# Third orbit lies in a plane inclined 90 degrees from the x-y plane, intersecting
# the x-y plane along the x-axis.
np.testing.assert_equal(np.array([0.0, -1.0, 0]), n_hat[2])
return
|
[
"numpy.linalg.norm",
"numpy.array",
"numpy.sqrt"
] |
[((102, 219), 'numpy.array', 'np.array', (['[[1.0, 0.0, 0.0, 0.0, 0.002, 0.0], [1.0, 0.0, 1.0, 0.0, 0.002, 0.0], [1.0, \n 0.0, 1.0, 0.0, 0.0, 0.002]]'], {}), '([[1.0, 0.0, 0.0, 0.0, 0.002, 0.0], [1.0, 0.0, 1.0, 0.0, 0.002, 0.0\n ], [1.0, 0.0, 1.0, 0.0, 0.0, 0.002]])\n', (110, 219), True, 'import numpy as np\n'), ((304, 333), 'numpy.linalg.norm', 'np.linalg.norm', (['n_hat'], {'axis': '(1)'}), '(n_hat, axis=1)\n', (318, 333), True, 'import numpy as np\n'), ((508, 625), 'numpy.array', 'np.array', (['[[1.0, 0.0, 0.0, 0.0, 0.002, 0.0], [1.0, 0.0, 1.0, 0.0, 0.002, 0.0], [1.0, \n 0.0, 1.0, 0.0, 0.0, 0.002]]'], {}), '([[1.0, 0.0, 0.0, 0.0, 0.002, 0.0], [1.0, 0.0, 1.0, 0.0, 0.002, 0.0\n ], [1.0, 0.0, 1.0, 0.0, 0.0, 0.002]])\n', (516, 625), True, 'import numpy as np\n'), ((833, 858), 'numpy.array', 'np.array', (['[0.0, 0.0, 1.0]'], {}), '([0.0, 0.0, 1.0])\n', (841, 858), True, 'import numpy as np\n'), ((1233, 1257), 'numpy.array', 'np.array', (['[0.0, -1.0, 0]'], {}), '([0.0, -1.0, 0])\n', (1241, 1257), True, 'import numpy as np\n'), ((1053, 1063), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (1060, 1063), True, 'import numpy as np\n'), ((1034, 1044), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (1041, 1044), True, 'import numpy as np\n')]
|
import numpy as np
import os
import copy
import torch
import random
import utils as du
from torch.utils.data import Dataset
class SliceDataset(Dataset):
def __init__(self, data_path, dataset='kits', task='tumor', series_index=None, train=True):
super(SliceDataset, self).__init__()
assert dataset in ['lits', 'kits']
assert task in ['organ', 'tumor']
self.load_path = data_path
self.series_index = series_index
self.task = task
self.train = train
self.dataset = dataset
self.tumor_slices = np.load(os.path.join(data_path, '%s_%s_slices.npy' % (dataset, task)))
def rotate(self, img, mask, k=None):
if k is None:
k = random.choice([0, 1, 2, 3])
img = np.rot90(img, k, (-2, -1))
mask = np.rot90(mask, k, (-2, -1))
return img, mask
def flip(self, img, mask, flip=None):
if flip is None:
a, b = random.choice([1, -1]), random.choice([1, -1])
else:
a, b = flip
if img.ndim == 2:
img = img[::a, ::b]
elif img.ndim == 3:
img = img[:, ::a, ::b]
mask = mask[::a, ::b]
return img, mask
def __len__(self):
return len(self.tumor_slices)
def __getitem__(self, item):
# Data loading
f_name = self.tumor_slices[item]
case = f_name.split('_')[0]
npz = np.load(os.path.join(self.load_path, f_name), allow_pickle=True)
ct = npz.get('ct')
mask = npz.get('mask')
# Preprocess
if self.task == 'organ':
mask[mask > 0] = 1
elif self.task == 'tumor':
mask = mask >> 1
mask[mask > 0] = 1
if self.dataset == 'lits':
ct = du.window_standardize(ct, -60, 140)
elif self.dataset == 'kits':
ct = du.window_standardize(ct, -200, 300)
if self.train:
ct, mask = self.flip(ct, mask)
ct, mask = self.rotate(ct, mask)
# one-hot
img0 = copy.deepcopy(mask)
img0 += 1
img0[img0 != 1] = 0
mask = np.stack((img0, mask), axis=0)
mask[mask > 0] = 1
# To tensor & cut to 384
ct = torch.from_numpy(du.cut_384(ct.copy())).unsqueeze(0).float()
mask = torch.from_numpy(du.cut_384(mask.copy())).float()
return ct, mask, case
|
[
"numpy.stack",
"copy.deepcopy",
"utils.window_standardize",
"random.choice",
"numpy.rot90",
"os.path.join"
] |
[((761, 787), 'numpy.rot90', 'np.rot90', (['img', 'k', '(-2, -1)'], {}), '(img, k, (-2, -1))\n', (769, 787), True, 'import numpy as np\n'), ((803, 830), 'numpy.rot90', 'np.rot90', (['mask', 'k', '(-2, -1)'], {}), '(mask, k, (-2, -1))\n', (811, 830), True, 'import numpy as np\n'), ((2046, 2065), 'copy.deepcopy', 'copy.deepcopy', (['mask'], {}), '(mask)\n', (2059, 2065), False, 'import copy\n'), ((2127, 2157), 'numpy.stack', 'np.stack', (['(img0, mask)'], {'axis': '(0)'}), '((img0, mask), axis=0)\n', (2135, 2157), True, 'import numpy as np\n'), ((576, 637), 'os.path.join', 'os.path.join', (['data_path', "('%s_%s_slices.npy' % (dataset, task))"], {}), "(data_path, '%s_%s_slices.npy' % (dataset, task))\n", (588, 637), False, 'import os\n'), ((719, 746), 'random.choice', 'random.choice', (['[0, 1, 2, 3]'], {}), '([0, 1, 2, 3])\n', (732, 746), False, 'import random\n'), ((1424, 1460), 'os.path.join', 'os.path.join', (['self.load_path', 'f_name'], {}), '(self.load_path, f_name)\n', (1436, 1460), False, 'import os\n'), ((1773, 1808), 'utils.window_standardize', 'du.window_standardize', (['ct', '(-60)', '(140)'], {}), '(ct, -60, 140)\n', (1794, 1808), True, 'import utils as du\n'), ((944, 966), 'random.choice', 'random.choice', (['[1, -1]'], {}), '([1, -1])\n', (957, 966), False, 'import random\n'), ((968, 990), 'random.choice', 'random.choice', (['[1, -1]'], {}), '([1, -1])\n', (981, 990), False, 'import random\n'), ((1863, 1899), 'utils.window_standardize', 'du.window_standardize', (['ct', '(-200)', '(300)'], {}), '(ct, -200, 300)\n', (1884, 1899), True, 'import utils as du\n')]
|
from PyAstronomy.pyaC import pyaErrors as PE
from PyAstronomy.pyaC import invertIndexSelection
import numpy as np
def intep(x, y, xinter, boundsError=True, fillValue=None):
"""
The INTEP interpolation algorithm
The INTEP interpolation algorithm is described
by Hill 1982, PDAO 16, 67 ("Intep - an Effective
Interpolation Subroutine"). The implementation
at hand is based on the FORTRAN code stated
therein.
The aim of the algorithm is to imitate the curve
"an experienced scientist" would draw through a
given set of points.
Parameters
----------
x : array
Independent values.
y : array
Dependent values.
xinter : array
Values at which to interpolate the tabulated
data given by `x` and `y`.
boundsError : boolean, optional
If True, an exception will be raised if values
need to be extrapolated beyond the limits of
the given tabulated data. Values beyond the
limits are simply replaced with the closest
valid value available, which might not be a
good approximation. Set this flag to False
suppress the exception.
fillValue : float, optional
If given (i.e., not None), this value will be
used to represent values outside of the given
bounds. Note that `boundsError` must be set
False for this to have an effect. For instance,
use np.NaN.
Returns
-------
Interpolated values : array
Interpolated values at the locations
specified by `xinter`.
"""
# Check whether x-array is sorted
if not np.all((x[1:] - x[0:-1]) > 0.0):
raise(PE.PyAValError("The array of independent values (`x`) is not sorted in (strictly) " + \
"ascending order, but it needs to be.", \
solution=["Sort the arrays `x` (and `y` accordingly), e.g., using numpy.argsort.", \
"Check whether there are duplicate values in `x`."]))
# Create result array
result = np.zeros(len(xinter))
# Treat extrapolation points
ilow = np.where(xinter < min(x))[0]
if fillValue is None:
# Use first point beyond limit
result[ilow] = y[0]
else:
result[ilow] = fillValue
iup = np.where(xinter > max(x))[0]
if fillValue is None:
# Use last point beyond limit
result[iup] = y[-1]
else:
result[iup] = fillValue
# No extrapolation (noepo)
noepo = invertIndexSelection(xinter, np.concatenate((ilow, iup)))
if (len(noepo) < len(xinter)) and boundsError:
raise(PE.PyAValError("There are " + str(len(xinter) - len(noepo)) + " points, which need to be extrapolated. " + \
"Attention: Extrapolation is simply done by using the closest valid value.", \
solution=["Use only interpolation points (`xinter`) within the valid range.",
"Set the `boundsError` flag to False (will suppress this exception)."]))
# Loop over all indices of xinter, which were
# not already subject to extrapolation.
for i in noepo:
xp = xinter[i]
# Index of the first entry in x larger (or equal) than
# `val`
infl = np.where(x >= xp)[0][0]
infl -= 1
lp1 = 1.0/(x[infl] - x[infl+1])
lp2 = -lp1
if infl <= 0:
# Special treatment for first point
fp1 = (y[1] -y[0]) / (x[1] - x[0])
else:
fp1 = (y[infl+1] - y[infl-1]) / (x[infl+1] - x[infl-1])
if infl >= (len(x) - 2):
# Special treatment for last points
fp2 = (y[-1] - y[-2]) / (x[-1] - x[-2])
else:
fp2 = (y[infl+2] - y[infl]) / (x[infl+2] - x[infl])
xpi1 = xp - x[infl+1]
xpi = xp - x[infl]
l1 = xpi1 * lp1
l2 = xpi * lp2
result[i] = y[infl]*(1. - 2.*lp1*xpi)*l1**2 + \
y[infl+1]*(1. - 2.*lp2*xpi1)*l2**2 + \
fp2*xpi1*l2**2 + fp1*xpi*l1**2
return result
|
[
"numpy.where",
"PyAstronomy.pyaC.pyaErrors.PyAValError",
"numpy.concatenate",
"numpy.all"
] |
[((1638, 1667), 'numpy.all', 'np.all', (['(x[1:] - x[0:-1] > 0.0)'], {}), '(x[1:] - x[0:-1] > 0.0)\n', (1644, 1667), True, 'import numpy as np\n'), ((1681, 1960), 'PyAstronomy.pyaC.pyaErrors.PyAValError', 'PE.PyAValError', (["('The array of independent values (`x`) is not sorted in (strictly) ' +\n 'ascending order, but it needs to be.')"], {'solution': "['Sort the arrays `x` (and `y` accordingly), e.g., using numpy.argsort.',\n 'Check whether there are duplicate values in `x`.']"}), "(\n 'The array of independent values (`x`) is not sorted in (strictly) ' +\n 'ascending order, but it needs to be.', solution=[\n 'Sort the arrays `x` (and `y` accordingly), e.g., using numpy.argsort.',\n 'Check whether there are duplicate values in `x`.'])\n", (1695, 1960), True, 'from PyAstronomy.pyaC import pyaErrors as PE\n'), ((2480, 2507), 'numpy.concatenate', 'np.concatenate', (['(ilow, iup)'], {}), '((ilow, iup))\n', (2494, 2507), True, 'import numpy as np\n'), ((3162, 3179), 'numpy.where', 'np.where', (['(x >= xp)'], {}), '(x >= xp)\n', (3170, 3179), True, 'import numpy as np\n')]
|
import numpy as np
import math
var = 2
n_eq = 3
n_un = 2
weights = np.array([[2, 3], [3, -5]])
outputs = np.array([4, 7])
def eqnfit(chromosome, weights, outputs):
'''
Equation 1:
'''
print(weights.shape)
print(outputs.shape)
output_model = np.dot(weights, np.array(chromosome))
print(output_model)
error = np.sum(np.power(output_model - outputs, 2))
if error == 0:
error = 1
return 1 / error
def value(chromosome, weights):
return np.dot(weights, np.array(chromosome))
|
[
"numpy.power",
"numpy.array"
] |
[((70, 97), 'numpy.array', 'np.array', (['[[2, 3], [3, -5]]'], {}), '([[2, 3], [3, -5]])\n', (78, 97), True, 'import numpy as np\n'), ((108, 124), 'numpy.array', 'np.array', (['[4, 7]'], {}), '([4, 7])\n', (116, 124), True, 'import numpy as np\n'), ((288, 308), 'numpy.array', 'np.array', (['chromosome'], {}), '(chromosome)\n', (296, 308), True, 'import numpy as np\n'), ((354, 389), 'numpy.power', 'np.power', (['(output_model - outputs)', '(2)'], {}), '(output_model - outputs, 2)\n', (362, 389), True, 'import numpy as np\n'), ((513, 533), 'numpy.array', 'np.array', (['chromosome'], {}), '(chromosome)\n', (521, 533), True, 'import numpy as np\n')]
|
# Copyright (c) 2021 Graphcore Ltd. All rights reserved.
import popart
import pytest
import numpy as np
# `import test_util` requires adding to sys.path
import sys
from pathlib import Path
sys.path.append(str(Path(__file__).resolve().parent.parent))
import test_util as tu
@tu.requires_ipu_model
def test_2_restores_for_1_stash():
"""
The model:
IPU0, PS0
w0 ---. IPU1, PS1 IPU0, PS2 IPU0, PS2
in0 --- Matmul --- x0 -- Sqrt --- x1 -- Add -- x2 -- IdLoss -- out
\ /
----------------------------------
\
Transpose (for MatmulGrad) -- ...
IPU0, PS4
Important feature: in0 is consumed by three ops on the same
VirtualGraph, but all on different PipelineStages. The pipeline
transform handles this by adding two Restore ops.
"""
np.random.seed(2)
bps = 5
dshape = [1, 4, 4]
in0_data = np.random.rand(bps, *dshape).astype(np.float32)
w0_data = np.random.rand(*dshape).astype(np.float32)
def runModel(pipeline, recompute):
builder = popart.Builder()
in0 = builder.addInputTensor("FLOAT", dshape)
w0 = builder.addInitializedInputTensor(w0_data)
with builder.virtualGraph(0), builder.pipelineStage(0):
x = builder.aiOnnx.matmul([in0, w0])
with builder.virtualGraph(1), builder.pipelineStage(1):
x = builder.aiOnnx.sqrt([x])
with builder.virtualGraph(0), builder.pipelineStage(2):
x = builder.aiOnnx.add([in0, x])
loss = builder.aiGraphcore.identityloss([x])
opts = popart.SessionOptions()
opts.virtualGraphMode = popart.VirtualGraphMode.Manual
opts.enablePipelining = pipeline
opts.enableGradientAccumulation = True
opts.accumulationFactor = bps
if recompute == True:
opts.autoRecomputation = popart.RecomputationType.Pipeline
session = popart.TrainingSession(
deviceInfo=tu.create_test_device(numIpus=2),
dataFlow=popart.DataFlow(1, [loss, w0],
popart.AnchorReturnType("Final")),
fnModel=builder.getModelProto(),
loss=loss,
optimizer=popart.ConstSGD(0.1),
userOptions=opts)
session.prepareDevice()
session.weightsFromHost()
anchors = session.initAnchorArrays()
stepio = popart.PyStepIO({in0: in0_data}, anchors)
session.run(stepio)
return anchors[w0]
ref_weights = runModel(pipeline=False, recompute=False)
pipelined_weights = runModel(pipeline=True, recompute=False)
pipelined_recomp_weights = runModel(pipeline=True, recompute=True)
print("Ref :", ref_weights)
print("Pipelined :", pipelined_weights)
print("Pipelined, recomp:", pipelined_recomp_weights)
# Verify that the final weights are the same for pipelined vs non-pipelined
assert np.allclose(ref_weights, pipelined_weights)
assert np.allclose(ref_weights, pipelined_recomp_weights)
@tu.requires_ipu_model
def test_2_restores_for_1_stash_not_supported_with_recomp():
"""
The model:
IPU0, PS0 IPU0, PS0
w0 ---. IPU1, PS1 IPU0, PS2 IPU0, PS2
in0 -- Nop - x0 - Matmul --- x0 -- Sqrt --- x1 -- Add -- x2 -- IdLoss -- out
\ /
---------------------------------
\
Transpose (for MatmulGrad) -- ...
IPU0, PS4
As in the above test except that there is now an Op (Nop) between in0
and x0 - the tensor that is by Ops on three different PipelineStages.
When in popart.RecomputationType.Pipeline mode, in0 is still the stashed
tensor. But in order to compute x0's consumers, we would require two
recompute fragments:
- Restore in0 in PS2, recompute x0 for Add's consumption
- Restore in0 in PS4, recompute x0 Transpose's consumption
Supporting recomputation of a tenosr in >1 fragment is to do in T30014.
For now we raise an exception
"""
bps = 5
dshape = [1, 4, 4]
w0_data = np.random.rand(*dshape).astype(np.float32)
builder = popart.Builder()
in0 = builder.addInputTensor("FLOAT", dshape)
w0 = builder.addInitializedInputTensor(w0_data)
with builder.virtualGraph(0), builder.pipelineStage(0):
in0 = builder.aiGraphcore.nop([in0])
x = builder.aiOnnx.matmul([in0, w0])
with builder.virtualGraph(1), builder.pipelineStage(1):
x = builder.aiOnnx.sqrt([x])
with builder.virtualGraph(0), builder.pipelineStage(2):
x = builder.aiOnnx.add([in0, x])
loss = builder.aiGraphcore.identityloss([x])
opts = popart.SessionOptions()
opts.virtualGraphMode = popart.VirtualGraphMode.Manual
opts.enablePipelining = True
opts.autoRecomputation = popart.RecomputationType.Pipeline
with pytest.raises(popart.popart_exception) as e_info:
session = popart.TrainingSession(
deviceInfo=tu.create_test_device(numIpus=2),
dataFlow=popart.DataFlow(bps, [loss, w0],
popart.AnchorReturnType("Final")),
fnModel=builder.getModelProto(),
loss=loss,
optimizer=popart.ConstSGD(0.1),
userOptions=opts)
assert e_info.value.args[0].find(
"To-stash Tensor '" + in0 +
"' must be restored for recomputation of a descendent that is not a direct consumer on more than 1 PipelineStage, but this is currently not supported"
)
|
[
"popart.ConstSGD",
"numpy.random.seed",
"numpy.allclose",
"popart.Builder",
"popart.AnchorReturnType",
"pytest.raises",
"test_util.create_test_device",
"pathlib.Path",
"popart.PyStepIO",
"numpy.random.rand",
"popart.SessionOptions"
] |
[((887, 904), 'numpy.random.seed', 'np.random.seed', (['(2)'], {}), '(2)\n', (901, 904), True, 'import numpy as np\n'), ((2993, 3036), 'numpy.allclose', 'np.allclose', (['ref_weights', 'pipelined_weights'], {}), '(ref_weights, pipelined_weights)\n', (3004, 3036), True, 'import numpy as np\n'), ((3048, 3098), 'numpy.allclose', 'np.allclose', (['ref_weights', 'pipelined_recomp_weights'], {}), '(ref_weights, pipelined_recomp_weights)\n', (3059, 3098), True, 'import numpy as np\n'), ((4303, 4319), 'popart.Builder', 'popart.Builder', ([], {}), '()\n', (4317, 4319), False, 'import popart\n'), ((4835, 4858), 'popart.SessionOptions', 'popart.SessionOptions', ([], {}), '()\n', (4856, 4858), False, 'import popart\n'), ((1118, 1134), 'popart.Builder', 'popart.Builder', ([], {}), '()\n', (1132, 1134), False, 'import popart\n'), ((1645, 1668), 'popart.SessionOptions', 'popart.SessionOptions', ([], {}), '()\n', (1666, 1668), False, 'import popart\n'), ((2454, 2495), 'popart.PyStepIO', 'popart.PyStepIO', (['{in0: in0_data}', 'anchors'], {}), '({in0: in0_data}, anchors)\n', (2469, 2495), False, 'import popart\n'), ((5024, 5062), 'pytest.raises', 'pytest.raises', (['popart.popart_exception'], {}), '(popart.popart_exception)\n', (5037, 5062), False, 'import pytest\n'), ((955, 983), 'numpy.random.rand', 'np.random.rand', (['bps', '*dshape'], {}), '(bps, *dshape)\n', (969, 983), True, 'import numpy as np\n'), ((1017, 1040), 'numpy.random.rand', 'np.random.rand', (['*dshape'], {}), '(*dshape)\n', (1031, 1040), True, 'import numpy as np\n'), ((4245, 4268), 'numpy.random.rand', 'np.random.rand', (['*dshape'], {}), '(*dshape)\n', (4259, 4268), True, 'import numpy as np\n'), ((2025, 2057), 'test_util.create_test_device', 'tu.create_test_device', ([], {'numIpus': '(2)'}), '(numIpus=2)\n', (2046, 2057), True, 'import test_util as tu\n'), ((2273, 2293), 'popart.ConstSGD', 'popart.ConstSGD', (['(0.1)'], {}), '(0.1)\n', (2288, 2293), False, 'import popart\n'), ((5139, 5171), 'test_util.create_test_device', 'tu.create_test_device', ([], {'numIpus': '(2)'}), '(numIpus=2)\n', (5160, 5171), True, 'import test_util as tu\n'), ((5389, 5409), 'popart.ConstSGD', 'popart.ConstSGD', (['(0.1)'], {}), '(0.1)\n', (5404, 5409), False, 'import popart\n'), ((2148, 2180), 'popart.AnchorReturnType', 'popart.AnchorReturnType', (['"""Final"""'], {}), "('Final')\n", (2171, 2180), False, 'import popart\n'), ((5264, 5296), 'popart.AnchorReturnType', 'popart.AnchorReturnType', (['"""Final"""'], {}), "('Final')\n", (5287, 5296), False, 'import popart\n'), ((210, 224), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (214, 224), False, 'from pathlib import Path\n')]
|
"""
Module for guiding Arc/Sky line tracing
.. _numpy.ndarray: https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.html
"""
import os
import copy
import inspect
import numpy as np
from astropy.io import fits
from pypeit import msgs
from pypeit import masterframe
from pypeit import ginga
from pypeit.core import arc
from pypeit.core import tracewave, pixels
from pypeit.par import pypeitpar
from pypeit.spectrographs.util import load_spectrograph
class WaveTilts(masterframe.MasterFrame):
"""
Class to guide slit/order tracing
Args:
msarc (ndarray): Arc image
tslits_dict (dict): dict from TraceSlits class (e.g. slitpix)
spectrograph (:obj:`pypeit.spectrographs.spectrograph.Spectrograph`):
Spectrograph object
par (:class:`pypeit.par.pypeitpar.WaveTiltsPar`):
The parameters used to fuss with the tilts
wavepar (:class:`pypeit.par.pypeitpar.WaveSolutionPar`):
The parameters used for the wavelength solution
det (int): Detector index
master_key (:obj:`str`, optional):
The string identifier for the instrument configuration. See
:class:`pypeit.masterframe.MasterFrame`.
master_dir (:obj:`str`, optional):
Path to master frames.
reuse_masters (:obj:`bool`, optional):
Load master files from disk, if possible.
qa_path (:obj:`str`, optional):
Directory for QA output.
msbpm (`numpy.ndarray`_, optional):
Bad pixel mask. If not provided, a dummy array with no
masking is generated.
Attributes:
frametype : str
Hard-coded to 'tilts'
steps : list
mask : ndarray, bool
True = Ignore this slit
all_trcdict : list of dict
All trace dict's
tilts : ndarray
Tilts for a single slit/order
all_ttilts : list of tuples
Tuple of tilts ndarray's
final_tilts : ndarray
Final tilts image
"""
# Frametype is a class attribute
master_type = 'Tilts'
def __init__(self, msarc, tslits_dict, spectrograph, par, wavepar, det=1, master_key=None,
master_dir=None, reuse_masters=False, qa_path=None, msbpm=None):
self.spectrograph = spectrograph
self.par = par
self.wavepar = wavepar
# MasterFrame
masterframe.MasterFrame.__init__(self, self.master_type, master_dir=master_dir,
master_key=master_key, reuse_masters=reuse_masters)
self.msarc = msarc
self.tslits_dict = tslits_dict
self.msbpm = msbpm
self.det = det
self.qa_path = qa_path
# --------------------------------------------------------------
# TODO: Build another base class that does these things for both
# WaveTilts and WaveCalib?
# Get the non-linear count level
self.nonlinear_counts = 1e10 if self.spectrograph is None \
else self.spectrograph.nonlinear_counts(det=self.det)
# Set the slitmask and slit boundary related attributes that the
# code needs for execution. This also deals with arcimages that
# have a different binning then the trace images used to defined
# the slits
if self.tslits_dict is not None and self.msarc is not None:
self.slitmask_science = pixels.tslits2mask(self.tslits_dict)
inmask = (self.msbpm == 0) if self.msbpm is not None \
else np.ones_like(self.slitmask_science, dtype=bool)
self.shape_science = self.slitmask_science.shape
self.shape_arc = self.msarc.shape
self.nslits = self.tslits_dict['slit_left'].shape[1]
self.slit_left = arc.resize_slits2arc(self.shape_arc, self.shape_science, self.tslits_dict['slit_left'])
self.slit_righ = arc.resize_slits2arc(self.shape_arc, self.shape_science, self.tslits_dict['slit_righ'])
self.slitcen = arc.resize_slits2arc(self.shape_arc, self.shape_science, self.tslits_dict['slitcen'])
self.slitmask = arc.resize_mask2arc(self.shape_arc, self.slitmask_science)
self.inmask = (arc.resize_mask2arc(self.shape_arc, inmask)) & (self.msarc < self.nonlinear_counts)
else:
self.slitmask_science = None
self.shape_science = None
self.shape_arc = None
self.nslits = 0
self.slit_left = None
self.slit_righ = None
self.slitcen = None
self.slitmask = None
self.inmask = None
# --------------------------------------------------------------
# Key Internals
self.mask = None
self.all_trace_dict = [None]*self.nslits
self.tilts = None
# 2D fits are stored as a dictionary rather than list because we will jsonify the dict
self.all_fit_dict = [None]*self.nslits
self.steps = []
# Main outputs
self.final_tilts = None
self.fit_dict = None
self.trace_dict = None
def extract_arcs(self, slitcen, slitmask, msarc, inmask):
"""
Extract the arcs down each slit/order
Wrapper to arc.get_censpec()
Args:
slitcen (ndarray): Image for tracing
slitmask (ndarray):
msarc (ndarray):
inmask (ndarray):
Returns:
ndarray, ndarray: Extracted arcs
"""
arccen, arc_maskslit = arc.get_censpec(slitcen, slitmask, msarc, inmask=inmask,
nonlinear_counts=self.nonlinear_counts)
# Step
self.steps.append(inspect.stack()[0][3])
return arccen, arc_maskslit
def find_lines(self, arcspec, slit_cen, slit, debug=False):
"""
Find the lines for tracing
Wrapper to tracewave.tilts_find_lines()
Args:
arcspec:
slit_cen:
slit (int):
debug:
Returns:
ndarray, ndarray: Spectral, spatial positions of lines to trace
"""
if self.par['idsonly'] is not None:
# Put in some hook here for getting the lines out of the
# wave calib for i.e. LRIS ghosts.
only_these_lines = None
pass
else:
only_these_lines = None
tracethresh = self._parse_param(self.par, 'tracethresh', slit)
lines_spec, lines_spat \
= tracewave.tilts_find_lines(arcspec, slit_cen, tracethresh=tracethresh,
sig_neigh=self.par['sig_neigh'],
nfwhm_neigh=self.par['nfwhm_neigh'],
only_these_lines=only_these_lines,
fwhm=self.wavepar['fwhm'],
nonlinear_counts=self.nonlinear_counts,
debug_peaks=False, debug_lines=debug)
self.steps.append(inspect.stack()[0][3])
return lines_spec, lines_spat
def fit_tilts(self, trc_tilt_dict, thismask, slit_cen, spat_order, spec_order, slit,
show_QA=False, doqa=True, debug=False):
"""
Fit the tilts
Args:
trc_tilt_dict (dict): Contains information from tilt tracing
slit_cen (ndarray): (nspec,) Central trace for this slit
spat_order (int): Order of the 2d polynomial fit for the spatial direction
spec_order (int): Order of the 2d polytnomial fit for the spectral direction
slit (int): integer index for the slit in question
Optional Args:
show_QA: bool, default = False
show the QA instead of writing it out to the outfile
doqa: bool, default = True
Construct the QA plot
debug: bool, default = False
Show additional plots useful for debugging.
Returns:
(tilts, coeffs)
tilts: ndarray (nspec, nspat)
tilts image
coeff: ndarray (spat_order + 1, spec_order+1)
Array containing the coefficients for the 2d legendre polynomial fit
"""
# Now perform a fit to the tilts
tilt_fit_dict, trc_tilt_dict_out \
= tracewave.fit_tilts(trc_tilt_dict, thismask, slit_cen, spat_order=spat_order,
spec_order=spec_order,maxdev=self.par['maxdev2d'],
sigrej=self.par['sigrej2d'], func2d=self.par['func2d'],
doqa=doqa, master_key=self.master_key, slit=slit,
show_QA=show_QA, out_dir=self.qa_path, debug=debug)
# Evaluate the fit
#tilts = tracewave.fit2tilts((tilt_fit_dict['nspec'], tilt_fit_dict['nspat']), slit_cen,
# tilt_fit_dict['coeff2'], tilt_fit_dict['func'])
# Populate the fit dict, and update the all_trace_dict
self.all_fit_dict[slit] = copy.deepcopy(tilt_fit_dict)
self.all_trace_dict[slit] = copy.deepcopy(trc_tilt_dict_out)
self.steps.append(inspect.stack()[0][3])
return tilt_fit_dict['coeff2']
def trace_tilts(self, arcimg, lines_spec, lines_spat, thismask, slit_cen):
"""
Trace the tilts
Args:
arcimg (`numpy.ndarray`_):
Arc image. Shape is (nspec, nspat).
lines_spec (`numpy.ndarray`_):
Array containing the spectral pixel location of each
line found for this slit. Shape is (nlines,).
lines_spat (`numpy.ndarray`_):
Array containing the spatial pixel location of each line,
which is the slitcen evaluate at the spectral position
position of the line stored in lines_spec. Shape is
(nlines,).
thismask (`numpy.ndarray`_):
Image indicating which pixels lie on the slit in
equation. True = on the slit. False = not on slit. Shape
is (nspec, nspat) with dtype=bool.
slit_cen (:obj:`int`):
Integer index indicating the slit in question.
Returns:
dict: Dictionary containing information on the traced tilts required to fit the filts.
"""
trace_dict = tracewave.trace_tilts(arcimg, lines_spec, lines_spat, thismask, slit_cen,
inmask=self.inmask, fwhm=self.wavepar['fwhm'],
spat_order=self.par['spat_order'],
maxdev_tracefit=self.par['maxdev_tracefit'],
sigrej_trace=self.par['sigrej_trace'])
# Return
self.steps.append(inspect.stack()[0][3])
return trace_dict
def run(self, maskslits=None, doqa=True, debug=False, show=False):
"""
Main driver for tracing arc lines
Code flow::
1. Extract an arc spectrum down the center of each slit/order
2. Loop on slits/orders
i. Trace and fit the arc lines (This is done twice, once
with trace_crude as the tracing crutch, then again
with a PCA model fit as the crutch).
ii. Repeat trace.
iii. 2D Fit to the offset from slitcen
iv. Save
Keyword Args:
maskslits (`numpy.ndarray`_, optional):
Boolean array to ignore slits.
doqa (bool):
debug (bool):
show (bool):
Returns:
dict, ndarray: Tilts dict and maskslits array
"""
if maskslits is None:
maskslits = np.zeros(self.nslits, dtype=bool)
# Extract the arc spectra for all slits
self.arccen, self.arc_maskslit = self.extract_arcs(self.slitcen, self.slitmask,
self.msarc, self.inmask)
# maskslit
self.mask = maskslits & (self.arc_maskslit==1)
gdslits = np.where(np.invert(self.mask))[0]
# Final tilts image
self.final_tilts = np.zeros(self.shape_science,dtype=float)
max_spat_dim = (np.asarray(self.par['spat_order']) + 1).max()
max_spec_dim = (np.asarray(self.par['spec_order']) + 1).max()
self.coeffs = np.zeros((max_spec_dim, max_spat_dim,self.nslits))
self.spat_order = np.zeros(self.nslits, dtype=int)
self.spec_order = np.zeros(self.nslits, dtype=int)
# TODO sort out show methods for debugging
#if show:
# viewer,ch = ginga.show_image(self.msarc*(self.slitmask > -1),chname='tilts')
# Loop on all slits
for slit in gdslits:
msgs.info('Computing tilts for slit {:d}/{:d}'.format(slit,self.nslits-1))
# Identify lines for tracing tilts
msgs.info('Finding lines for tilt analysis')
self.lines_spec, self.lines_spat = self.find_lines(self.arccen[:,slit], self.slitcen[:,slit], slit, debug=debug)
if self.lines_spec is None:
self.mask[slit] = True
maskslits[slit] = True
continue
thismask = self.slitmask == slit
# Trace
msgs.info('Trace the tilts')
self.trace_dict = self.trace_tilts(self.msarc, self.lines_spec, self.lines_spat,
thismask, self.slitcen[:,slit])
#if show:
# ginga.show_tilts(viewer, ch, self.trace_dict)
self.spat_order[slit] = self._parse_param(self.par, 'spat_order', slit)
self.spec_order[slit] = self._parse_param(self.par, 'spec_order', slit)
# 2D model of the tilts, includes construction of QA
coeff_out = self.fit_tilts(self.trace_dict, thismask, self.slitcen[:,slit],
self.spat_order[slit], self.spec_order[slit], slit,
doqa=doqa, show_QA=show, debug=show)
self.coeffs[0:self.spec_order[slit]+1, 0:self.spat_order[slit]+1 , slit] = coeff_out
# Tilts are created with the size of the original slitmask,
# which corresonds to the same binning as the science
# images, trace images, and pixelflats etc.
self.tilts = tracewave.fit2tilts(self.slitmask_science.shape, coeff_out,
self.par['func2d'])
# Save to final image
thismask_science = self.slitmask_science == slit
self.final_tilts[thismask_science] = self.tilts[thismask_science]
self.tilts_dict = {'tilts':self.final_tilts, 'coeffs':self.coeffs, 'slitcen':self.slitcen,
'func2d':self.par['func2d'], 'nslit':self.nslits,
'spat_order':self.spat_order, 'spec_order':self.spec_order}
return self.tilts_dict, maskslits
def save(self, outfile=None, overwrite=True):
"""
Save the wavelength tilts data to a master frame
Args:
outfile (:obj:`str`, optional):
Name for the output file. Defaults to
:attr:`file_path`.
overwrite (:obj:`bool`, optional):
Overwrite any existing file.
"""
_outfile = self.file_path if outfile is None else outfile
# Check if it exists
if os.path.exists(_outfile) and not overwrite:
msgs.warn('Master file exists: {0}'.format(_outfile) + msgs.newline()
+ 'Set overwrite=True to overwrite it.')
return
# Log
msgs.info('Saving master frame to {0}'.format(_outfile))
# Build the header
hdr = fits.Header()
# - Set the master frame type
hdr['FRAMETYP'] = (self.master_type, 'PypeIt: Master calibration frame type')
# - List the completed steps
hdr['STEPS'] = (','.join(self.steps), 'Completed reduction steps')
# - Tilts metadata
hdr['FUNC2D'] = self.tilts_dict['func2d']
hdr['NSLIT'] = self.tilts_dict['nslit']
# Write the fits file
fits.HDUList([fits.PrimaryHDU(header=hdr),
fits.ImageHDU(data=self.tilts_dict['tilts'], name='TILTS'),
fits.ImageHDU(data=self.tilts_dict['coeffs'], name='COEFFS'),
fits.ImageHDU(data=self.tilts_dict['slitcen'], name='SLITCEN'),
fits.ImageHDU(data=self.tilts_dict['spat_order'], name='SPAT_ORDER'),
fits.ImageHDU(data=self.tilts_dict['spec_order'], name='SPEC_ORDER')
]).writeto(_outfile, overwrite=True)
def load(self, ifile=None, return_header=False):
"""
Load the tilts data.
This is largely a wrapper for :func:`pypeit.wavetilts.WaveTilts.load_from_file`.
Args:
ifile (:obj:`str`, optional):
Name of the master frame file. Defaults to
:attr:`file_path`.
return_header (:obj:`bool`, optional):
Return the header.
Returns:
Returns the tilts dictionary. If return_header is
true, the primary header is also returned. If nothing is
loaded, either because :attr:`reuse_masters` is `False` or
the file does not exist, everything is returned as None (one
per expected return object).
"""
# Format the input and set the tuple for an empty return
_ifile = self.file_path if ifile is None else ifile
empty_return = (None, None) if return_header else None
if not self.reuse_masters:
# User does not want to load masters
msgs.warn('PypeIt will not reuse masters!')
return empty_return
if not os.path.isfile(_ifile):
# Master file doesn't exist
msgs.warn('No Master {0} frame found: {1}'.format(self.master_type, self.file_path))
return empty_return
# Read and return
msgs.info('Loading Master {0} frame: {1}'.format(self.master_type, _ifile))
return self.load_from_file(_ifile, return_header=return_header)
@staticmethod
def load_from_file(filename, return_header=False):
"""
Load the tilts data, without the benefit of the rest of the
class.
Args:
ifile (:obj:`str`, optional):
Name of the master frame file. Defaults to
:attr:`file_path`.
return_header (:obj:`bool`, optional):
Return the header, which will include the TraceImage
metadata if available.
Returns:
Returns the tilts dictionary. If return_header is
true, the primary header is also returned. If nothing is
loaded, either because :attr:`reuse_masters` is `False` or
the file does not exist, everything is returned as None (one
per expected return object).
"""
# Check it exists
if not os.path.isfile(filename):
msgs.error('File does not exist: {0}'.format(filename))
# Open the file
hdu = fits.open(filename)
# Metadata
tilts_dict = {}
keys = ['func2d', 'nslit']
for k in keys:
tilts_dict[k] = hdu[0].header[k.upper()]
# Data extensions
keys = ['tilts', 'coeffs', 'slitcen', 'spat_order', 'spec_order']
for k in keys:
tilts_dict[k] = hdu[k.upper()].data
return (tilts_dict, hdu[0].header) if return_header else tilts_dict
def _parse_param(self, par, key, slit):
"""
Grab a parameter for a given slit
Args:
par (ParSet):
key (str):
slit (int):
Returns:
object: Value of the parameter
"""
param_in = par[key]
if isinstance(param_in, (float, int)):
param = param_in
elif isinstance(param_in, (list, np.ndarray)):
param = param_in[slit]
else:
raise ValueError('Invalid input for parameter {:s}'.format(key))
return param
def show(self, attr, slit=None, display='ginga', cname=None):
"""
Display an image or spectrum in TraceSlits
Parameters
----------
attr : str
'fweight' -- Show the msarc image and the tilts traced by fweight
'model' -- Show the msarc image and the poylynomial model fits to the individual arc lines that
were traced by fweight.
'arcmodel -- This illustrates the global final 2-d model fit to the indivdiaul models of each traced fweight arc line
tilts evaluated at the location of the specific arclines that wered use for the fit.
'final_tilts' -- Show the final 2-d tilt model for all the slits that were fit.
slit : int, optional
-- The slit to plot. This needs to be an integer between 1 and nslit
display : str (optional)
'ginga' -- Display to an RC Ginga
"""
viewer, ch = ginga.show_image(self.arcimg*(self.slitmask == slit), chname='Tilts')
ginga.show_tilts(viewer, ch, self.trace_dict,
sedges=(self.tslits_dict['slit_left'][:,slit],
self.tslits_dict['slit_righ'][:,slit]), points=True, clear_canvas=True)
def __repr__(self):
# Generate sets string
txt = '<{:s}: '.format(self.__class__.__name__)
if len(self.steps) > 0:
txt+= ' steps: ['
for step in self.steps:
txt += '{:s}, '.format(step)
txt = txt[:-2]+']' # Trim the trailing comma
txt += '>'
return txt
|
[
"numpy.invert",
"astropy.io.fits.PrimaryHDU",
"pypeit.core.tracewave.fit2tilts",
"os.path.isfile",
"astropy.io.fits.Header",
"pypeit.msgs.warn",
"pypeit.core.pixels.tslits2mask",
"pypeit.core.arc.get_censpec",
"pypeit.msgs.info",
"astropy.io.fits.ImageHDU",
"pypeit.core.arc.resize_mask2arc",
"pypeit.core.tracewave.tilts_find_lines",
"pypeit.ginga.show_image",
"os.path.exists",
"pypeit.core.tracewave.trace_tilts",
"copy.deepcopy",
"numpy.ones_like",
"numpy.asarray",
"pypeit.core.tracewave.fit_tilts",
"astropy.io.fits.open",
"pypeit.ginga.show_tilts",
"pypeit.masterframe.MasterFrame.__init__",
"numpy.zeros",
"pypeit.msgs.newline",
"inspect.stack",
"pypeit.core.arc.resize_slits2arc"
] |
[((2420, 2556), 'pypeit.masterframe.MasterFrame.__init__', 'masterframe.MasterFrame.__init__', (['self', 'self.master_type'], {'master_dir': 'master_dir', 'master_key': 'master_key', 'reuse_masters': 'reuse_masters'}), '(self, self.master_type, master_dir=\n master_dir, master_key=master_key, reuse_masters=reuse_masters)\n', (2452, 2556), False, 'from pypeit import masterframe\n'), ((5603, 5704), 'pypeit.core.arc.get_censpec', 'arc.get_censpec', (['slitcen', 'slitmask', 'msarc'], {'inmask': 'inmask', 'nonlinear_counts': 'self.nonlinear_counts'}), '(slitcen, slitmask, msarc, inmask=inmask, nonlinear_counts=\n self.nonlinear_counts)\n', (5618, 5704), False, 'from pypeit.core import arc\n'), ((6603, 6900), 'pypeit.core.tracewave.tilts_find_lines', 'tracewave.tilts_find_lines', (['arcspec', 'slit_cen'], {'tracethresh': 'tracethresh', 'sig_neigh': "self.par['sig_neigh']", 'nfwhm_neigh': "self.par['nfwhm_neigh']", 'only_these_lines': 'only_these_lines', 'fwhm': "self.wavepar['fwhm']", 'nonlinear_counts': 'self.nonlinear_counts', 'debug_peaks': '(False)', 'debug_lines': 'debug'}), "(arcspec, slit_cen, tracethresh=tracethresh,\n sig_neigh=self.par['sig_neigh'], nfwhm_neigh=self.par['nfwhm_neigh'],\n only_these_lines=only_these_lines, fwhm=self.wavepar['fwhm'],\n nonlinear_counts=self.nonlinear_counts, debug_peaks=False, debug_lines=\n debug)\n", (6629, 6900), False, 'from pypeit.core import tracewave, pixels\n'), ((8506, 8812), 'pypeit.core.tracewave.fit_tilts', 'tracewave.fit_tilts', (['trc_tilt_dict', 'thismask', 'slit_cen'], {'spat_order': 'spat_order', 'spec_order': 'spec_order', 'maxdev': "self.par['maxdev2d']", 'sigrej': "self.par['sigrej2d']", 'func2d': "self.par['func2d']", 'doqa': 'doqa', 'master_key': 'self.master_key', 'slit': 'slit', 'show_QA': 'show_QA', 'out_dir': 'self.qa_path', 'debug': 'debug'}), "(trc_tilt_dict, thismask, slit_cen, spat_order=\n spat_order, spec_order=spec_order, maxdev=self.par['maxdev2d'], sigrej=\n self.par['sigrej2d'], func2d=self.par['func2d'], doqa=doqa, master_key=\n self.master_key, slit=slit, show_QA=show_QA, out_dir=self.qa_path,\n debug=debug)\n", (8525, 8812), False, 'from pypeit.core import tracewave, pixels\n'), ((9253, 9281), 'copy.deepcopy', 'copy.deepcopy', (['tilt_fit_dict'], {}), '(tilt_fit_dict)\n', (9266, 9281), False, 'import copy\n'), ((9318, 9350), 'copy.deepcopy', 'copy.deepcopy', (['trc_tilt_dict_out'], {}), '(trc_tilt_dict_out)\n', (9331, 9350), False, 'import copy\n'), ((10595, 10847), 'pypeit.core.tracewave.trace_tilts', 'tracewave.trace_tilts', (['arcimg', 'lines_spec', 'lines_spat', 'thismask', 'slit_cen'], {'inmask': 'self.inmask', 'fwhm': "self.wavepar['fwhm']", 'spat_order': "self.par['spat_order']", 'maxdev_tracefit': "self.par['maxdev_tracefit']", 'sigrej_trace': "self.par['sigrej_trace']"}), "(arcimg, lines_spec, lines_spat, thismask, slit_cen,\n inmask=self.inmask, fwhm=self.wavepar['fwhm'], spat_order=self.par[\n 'spat_order'], maxdev_tracefit=self.par['maxdev_tracefit'],\n sigrej_trace=self.par['sigrej_trace'])\n", (10616, 10847), False, 'from pypeit.core import tracewave, pixels\n'), ((12454, 12495), 'numpy.zeros', 'np.zeros', (['self.shape_science'], {'dtype': 'float'}), '(self.shape_science, dtype=float)\n', (12462, 12495), True, 'import numpy as np\n'), ((12657, 12708), 'numpy.zeros', 'np.zeros', (['(max_spec_dim, max_spat_dim, self.nslits)'], {}), '((max_spec_dim, max_spat_dim, self.nslits))\n', (12665, 12708), True, 'import numpy as np\n'), ((12734, 12766), 'numpy.zeros', 'np.zeros', (['self.nslits'], {'dtype': 'int'}), '(self.nslits, dtype=int)\n', (12742, 12766), True, 'import numpy as np\n'), ((12793, 12825), 'numpy.zeros', 'np.zeros', (['self.nslits'], {'dtype': 'int'}), '(self.nslits, dtype=int)\n', (12801, 12825), True, 'import numpy as np\n'), ((16086, 16099), 'astropy.io.fits.Header', 'fits.Header', ([], {}), '()\n', (16097, 16099), False, 'from astropy.io import fits\n'), ((19568, 19587), 'astropy.io.fits.open', 'fits.open', (['filename'], {}), '(filename)\n', (19577, 19587), False, 'from astropy.io import fits\n'), ((21534, 21605), 'pypeit.ginga.show_image', 'ginga.show_image', (['(self.arcimg * (self.slitmask == slit))'], {'chname': '"""Tilts"""'}), "(self.arcimg * (self.slitmask == slit), chname='Tilts')\n", (21550, 21605), False, 'from pypeit import ginga\n'), ((21612, 21788), 'pypeit.ginga.show_tilts', 'ginga.show_tilts', (['viewer', 'ch', 'self.trace_dict'], {'sedges': "(self.tslits_dict['slit_left'][:, slit], self.tslits_dict['slit_righ'][:, slit]\n )", 'points': '(True)', 'clear_canvas': '(True)'}), "(viewer, ch, self.trace_dict, sedges=(self.tslits_dict[\n 'slit_left'][:, slit], self.tslits_dict['slit_righ'][:, slit]), points=\n True, clear_canvas=True)\n", (21628, 21788), False, 'from pypeit import ginga\n'), ((3466, 3502), 'pypeit.core.pixels.tslits2mask', 'pixels.tslits2mask', (['self.tslits_dict'], {}), '(self.tslits_dict)\n', (3484, 3502), False, 'from pypeit.core import tracewave, pixels\n'), ((3864, 3956), 'pypeit.core.arc.resize_slits2arc', 'arc.resize_slits2arc', (['self.shape_arc', 'self.shape_science', "self.tslits_dict['slit_left']"], {}), "(self.shape_arc, self.shape_science, self.tslits_dict[\n 'slit_left'])\n", (3884, 3956), False, 'from pypeit.core import arc\n'), ((3981, 4073), 'pypeit.core.arc.resize_slits2arc', 'arc.resize_slits2arc', (['self.shape_arc', 'self.shape_science', "self.tslits_dict['slit_righ']"], {}), "(self.shape_arc, self.shape_science, self.tslits_dict[\n 'slit_righ'])\n", (4001, 4073), False, 'from pypeit.core import arc\n'), ((4098, 4188), 'pypeit.core.arc.resize_slits2arc', 'arc.resize_slits2arc', (['self.shape_arc', 'self.shape_science', "self.tslits_dict['slitcen']"], {}), "(self.shape_arc, self.shape_science, self.tslits_dict[\n 'slitcen'])\n", (4118, 4188), False, 'from pypeit.core import arc\n'), ((4213, 4271), 'pypeit.core.arc.resize_mask2arc', 'arc.resize_mask2arc', (['self.shape_arc', 'self.slitmask_science'], {}), '(self.shape_arc, self.slitmask_science)\n', (4232, 4271), False, 'from pypeit.core import arc\n'), ((12016, 12049), 'numpy.zeros', 'np.zeros', (['self.nslits'], {'dtype': 'bool'}), '(self.nslits, dtype=bool)\n', (12024, 12049), True, 'import numpy as np\n'), ((13190, 13234), 'pypeit.msgs.info', 'msgs.info', (['"""Finding lines for tilt analysis"""'], {}), "('Finding lines for tilt analysis')\n", (13199, 13234), False, 'from pypeit import msgs\n'), ((13581, 13609), 'pypeit.msgs.info', 'msgs.info', (['"""Trace the tilts"""'], {}), "('Trace the tilts')\n", (13590, 13609), False, 'from pypeit import msgs\n'), ((14673, 14752), 'pypeit.core.tracewave.fit2tilts', 'tracewave.fit2tilts', (['self.slitmask_science.shape', 'coeff_out', "self.par['func2d']"], {}), "(self.slitmask_science.shape, coeff_out, self.par['func2d'])\n", (14692, 14752), False, 'from pypeit.core import tracewave, pixels\n'), ((15756, 15780), 'os.path.exists', 'os.path.exists', (['_outfile'], {}), '(_outfile)\n', (15770, 15780), False, 'import os\n'), ((18099, 18142), 'pypeit.msgs.warn', 'msgs.warn', (['"""PypeIt will not reuse masters!"""'], {}), "('PypeIt will not reuse masters!')\n", (18108, 18142), False, 'from pypeit import msgs\n'), ((18191, 18213), 'os.path.isfile', 'os.path.isfile', (['_ifile'], {}), '(_ifile)\n', (18205, 18213), False, 'import os\n'), ((19436, 19460), 'os.path.isfile', 'os.path.isfile', (['filename'], {}), '(filename)\n', (19450, 19460), False, 'import os\n'), ((3615, 3662), 'numpy.ones_like', 'np.ones_like', (['self.slitmask_science'], {'dtype': 'bool'}), '(self.slitmask_science, dtype=bool)\n', (3627, 3662), True, 'import numpy as np\n'), ((4299, 4342), 'pypeit.core.arc.resize_mask2arc', 'arc.resize_mask2arc', (['self.shape_arc', 'inmask'], {}), '(self.shape_arc, inmask)\n', (4318, 4342), False, 'from pypeit.core import arc\n'), ((12373, 12393), 'numpy.invert', 'np.invert', (['self.mask'], {}), '(self.mask)\n', (12382, 12393), True, 'import numpy as np\n'), ((5788, 5803), 'inspect.stack', 'inspect.stack', ([], {}), '()\n', (5801, 5803), False, 'import inspect\n'), ((7181, 7196), 'inspect.stack', 'inspect.stack', ([], {}), '()\n', (7194, 7196), False, 'import inspect\n'), ((9378, 9393), 'inspect.stack', 'inspect.stack', ([], {}), '()\n', (9391, 9393), False, 'import inspect\n'), ((11051, 11066), 'inspect.stack', 'inspect.stack', ([], {}), '()\n', (11064, 11066), False, 'import inspect\n'), ((12519, 12553), 'numpy.asarray', 'np.asarray', (["self.par['spat_order']"], {}), "(self.par['spat_order'])\n", (12529, 12553), True, 'import numpy as np\n'), ((12589, 12623), 'numpy.asarray', 'np.asarray', (["self.par['spec_order']"], {}), "(self.par['spec_order'])\n", (12599, 12623), True, 'import numpy as np\n'), ((15867, 15881), 'pypeit.msgs.newline', 'msgs.newline', ([], {}), '()\n', (15879, 15881), False, 'from pypeit import msgs\n'), ((16521, 16548), 'astropy.io.fits.PrimaryHDU', 'fits.PrimaryHDU', ([], {'header': 'hdr'}), '(header=hdr)\n', (16536, 16548), False, 'from astropy.io import fits\n'), ((16572, 16630), 'astropy.io.fits.ImageHDU', 'fits.ImageHDU', ([], {'data': "self.tilts_dict['tilts']", 'name': '"""TILTS"""'}), "(data=self.tilts_dict['tilts'], name='TILTS')\n", (16585, 16630), False, 'from astropy.io import fits\n'), ((16654, 16714), 'astropy.io.fits.ImageHDU', 'fits.ImageHDU', ([], {'data': "self.tilts_dict['coeffs']", 'name': '"""COEFFS"""'}), "(data=self.tilts_dict['coeffs'], name='COEFFS')\n", (16667, 16714), False, 'from astropy.io import fits\n'), ((16738, 16800), 'astropy.io.fits.ImageHDU', 'fits.ImageHDU', ([], {'data': "self.tilts_dict['slitcen']", 'name': '"""SLITCEN"""'}), "(data=self.tilts_dict['slitcen'], name='SLITCEN')\n", (16751, 16800), False, 'from astropy.io import fits\n'), ((16824, 16892), 'astropy.io.fits.ImageHDU', 'fits.ImageHDU', ([], {'data': "self.tilts_dict['spat_order']", 'name': '"""SPAT_ORDER"""'}), "(data=self.tilts_dict['spat_order'], name='SPAT_ORDER')\n", (16837, 16892), False, 'from astropy.io import fits\n'), ((16916, 16984), 'astropy.io.fits.ImageHDU', 'fits.ImageHDU', ([], {'data': "self.tilts_dict['spec_order']", 'name': '"""SPEC_ORDER"""'}), "(data=self.tilts_dict['spec_order'], name='SPEC_ORDER')\n", (16929, 16984), False, 'from astropy.io import fits\n')]
|
## @package libgsidem2el 地理院標高タイルから標高値を取得するライブラリ
# @brief 地理院標高タイルから標高値を取得するライブラリ
# 地図の種類はDEM5A,DEM5B,DEM10B,DEMGMの4種類が選択可能 https://maps.gsi.go.jp/help/pdf/demapi.pdf参照
# zoom levelは,DEM5A,B:15, DEM10B:0-14, DEMGM:0-8
# getELメソッドで取得,DEM5AB,10Bは[m],DEMGMは[cm]の標高値を返す.
# それぞれの地図の対象範囲外は'outside'を返す
# 水面等により欠測の場合は,'e'を返す(地理院タイルの使用).
# 一度読み込んだタイルはクラスの変数demdfに保存.近接するデータの取得が高速化される反面,大領域を一度に処理する場合はメモリを消費する.
# @author computational-sediment-hyd https://github.com/computational-sediment-hyd
# @date 2018/12/19
# @version version 0.1.0
import numpy as np
import pandas as pd
import urllib.request
## 地理院標高タイルから標高値を取得するライブラリ
# @brief
class libgsidem2el:
def __init__(self, dem:'DEM5A, DEM5B, DEM10B, DEMGM' = 'DEM5A'):
self.demdf = {}
# https://maps.gsi.go.jp/development/ichiran.html#dem
kind = {'DEM5A':'dem5a', 'DEM5B':'dem5b', 'DEM10B':'dem', 'DEMGM':'demgm' }
self.url = "https://cyberjapandata.gsi.go.jp/xyz/" + kind[dem] + "/"
# get Elevation from tile layer
def getEL(self, lon, lat, zoom=15):
# change lon,lat to pixel coordinate
z = zoom
L = 85.05112878
x = 2**(z+7)*(lon/180.0+1.0)
y = 2**(z+7)/np.pi*(-np.arctanh(np.sin(np.pi/180.0*lat)) + np.arctanh(np.sin(np.pi/180.0*L)))
# set tile number
Xt, Yt = int(x//256), int(y//256)
# set pixle number per tile
Xp, Yp = int(x%256), int(y%256)
key = str(Xt) + '-' + str(Yt)
url = self.url + str(z) + "/" + str(Xt) + "/" + str(Yt) + ".txt"
if key in self.demdf:
df = self.demdf[key]
return df.iloc[Yp, Xp]
else:
# add url error works
req = urllib.request.Request(urllib)
try:
df = pd.read_csv(url, header=None)
self.demdf[key] = df
return df.iloc[Yp, Xp]
except urllib.error.HTTPError as error:
return 'outside'
except urllib.error.URLError as error:
return 'outside'
def __del__(self):
del self.demdf
|
[
"pandas.read_csv",
"numpy.sin"
] |
[((1769, 1798), 'pandas.read_csv', 'pd.read_csv', (['url'], {'header': 'None'}), '(url, header=None)\n', (1780, 1798), True, 'import pandas as pd\n'), ((1251, 1276), 'numpy.sin', 'np.sin', (['(np.pi / 180.0 * L)'], {}), '(np.pi / 180.0 * L)\n', (1257, 1276), True, 'import numpy as np\n'), ((1213, 1240), 'numpy.sin', 'np.sin', (['(np.pi / 180.0 * lat)'], {}), '(np.pi / 180.0 * lat)\n', (1219, 1240), True, 'import numpy as np\n')]
|
import pandas as pd
import numpy as np
import os
import keras
from sklearn.model_selection import train_test_split
from keras.models import load_model, Sequential
model = Sequential()
model_path = os.path.join(os.getcwd(),'convmodel.h5')
model = load_model(model_path)
test_data = pd.read_csv('test.csv').astype('float32')
test_data /= 255
test_data = test_data.as_matrix()
test_data = test_data.reshape(test_data.shape[0],28,28,1)
results = model.predict(test_data)
results = np.argmax(results,axis=1)
df = pd.DataFrame(results)
df.index+=1
df.columns=['Label']
df.to_csv('results.csv', header=True)
|
[
"keras.models.load_model",
"pandas.DataFrame",
"numpy.argmax",
"os.getcwd",
"pandas.read_csv",
"keras.models.Sequential"
] |
[((171, 183), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (181, 183), False, 'from keras.models import load_model, Sequential\n'), ((246, 268), 'keras.models.load_model', 'load_model', (['model_path'], {}), '(model_path)\n', (256, 268), False, 'from keras.models import load_model, Sequential\n'), ((477, 503), 'numpy.argmax', 'np.argmax', (['results'], {'axis': '(1)'}), '(results, axis=1)\n', (486, 503), True, 'import numpy as np\n'), ((508, 529), 'pandas.DataFrame', 'pd.DataFrame', (['results'], {}), '(results)\n', (520, 529), True, 'import pandas as pd\n'), ((210, 221), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (219, 221), False, 'import os\n'), ((281, 304), 'pandas.read_csv', 'pd.read_csv', (['"""test.csv"""'], {}), "('test.csv')\n", (292, 304), True, 'import pandas as pd\n')]
|
import sys
import cv2
import numpy as np
from .detect_reso_chart import detect_reso_chart
from .compute_mtf import compute_mtf
def reso_meas(images, verbose=False):
""" measure the resolution from multiple photos of resolution test chart
STEP1: Extract edge images from photos.
STEP2: Estimate MTF from edge images
STEP3: Merge the detected MTFs and return
Args:
images ([numpy.array]): Photo of resolution test chart
verbose (bool, optional): Defaults to False.
Return:
(touple): x and y coordinates of MTF curve
([numpy.array]): output images
"""
mtf_list = []
for img in images:
edge = detect_reso_chart(img, verbose)
mtf = compute_mtf(edge, verbose)
mtf_list.append(mtf)
"""
try:
edge = detect_reso_chart(img, verbose)
mtf = compute_mtf(edge, verbose=False)
print(f"mtf: {mtf}")
mtf_list.append(mtf)
except:
continue
"""
if len(mtf_list) == 0:
sys.exit("[ERROR]: no valid image for resolution measurement!")
mtf_x = mtf_list[0][0]
mtf_y = mtf_list[0][1] if len(
mtf_list) == 1 else np.mean([mtf[1] for mtf in mtf_list], axis=0)
return (mtf_x, mtf_y), []
if __name__ == "__main__":
mocked_urls = [
'test_chart/reso_test_chart.png'
]
mocked_imgs = []
for url in mocked_urls:
mocked_imgs.append(cv2.imread(url, 0))
mtf, output_imgs = reso_meas(mocked_imgs, verbose=True)
print(mtf)
|
[
"cv2.imread",
"numpy.mean",
"sys.exit"
] |
[((1063, 1126), 'sys.exit', 'sys.exit', (['"""[ERROR]: no valid image for resolution measurement!"""'], {}), "('[ERROR]: no valid image for resolution measurement!')\n", (1071, 1126), False, 'import sys\n'), ((1218, 1263), 'numpy.mean', 'np.mean', (['[mtf[1] for mtf in mtf_list]'], {'axis': '(0)'}), '([mtf[1] for mtf in mtf_list], axis=0)\n', (1225, 1263), True, 'import numpy as np\n'), ((1468, 1486), 'cv2.imread', 'cv2.imread', (['url', '(0)'], {}), '(url, 0)\n', (1478, 1486), False, 'import cv2\n')]
|
# test_model.py
import numpy as np
import cv2
import time
import os
from grabscreen import grab_screen
from directkeys import PressKey, ReleaseKey, DirectionKey as dk
from alexnet import alexnet
from getkeys import key_check
cwd = os.getcwd()
for file_name in os.listdir(cwd):
if file_name.startswith('Osori-SelfDrivingWithGTA5'):
MODEL_NAME = file_name.split('.model')[0] + '.model'
print('{} is selected'.format(MODEL_NAME))
break
t_time = 0.1
def straight():
PressKey(dk.W)
ReleaseKey(dk.A)
ReleaseKey(dk.D)
def left():
ReleaseKey(dk.D)
PressKey(dk.W)
PressKey(dk.A)
time.sleep(t_time)
ReleaseKey(dk.A)
def right():
ReleaseKey(dk.A)
PressKey(dk.W)
PressKey(dk.D)
time.sleep(t_time)
ReleaseKey(dk.D)
WIDTH = 160
HEIGHT = 120
LEARNING_RATE = 0.001
model = alexnet(WIDTH, HEIGHT, LEARNING_RATE)
model.load(MODEL_NAME)
def main():
last_time = time.time()
for i in list(range(4))[::-1]:
print(i + 1)
time.sleep(1)
paused = False
while True:
if not paused:
# 800x600 windowed mode
# screen = np.array(ImageGrab.grab(bbox=(0,40,800,640)))
screen = grab_screen(region=(0, 40, 800, 640))
print('loop took {} seconds'.format(time.time() - last_time))
last_time = time.time()
screen = cv2.cvtColor(screen, cv2.COLOR_BGR2GRAY)
input_screen = cv2.resize(screen, (160, 120))
cv2.imshow('screen', screen)
if cv2.waitKey(25) & 0xFF == ord('q'):
cv2.destroyAllWindows()
break
prediction = model.predict([input_screen.reshape(160, 120, 1)])[0]
print(prediction)
dir = np.argmax(prediction)
if prediction[1] > 0.2:
straight()
elif prediction[0] > prediction[2]:
left()
else:
right()
keys = key_check()
# p pauses game and can get annoying.
if 'T' in keys:
if paused:
paused = False
else:
paused = True
ReleaseKey(dk.A)
ReleaseKey(dk.W)
ReleaseKey(dk.D)
time.sleep(1)
main()
|
[
"alexnet.alexnet",
"numpy.argmax",
"os.getcwd",
"cv2.cvtColor",
"cv2.destroyAllWindows",
"cv2.waitKey",
"directkeys.ReleaseKey",
"time.sleep",
"directkeys.PressKey",
"time.time",
"grabscreen.grab_screen",
"getkeys.key_check",
"cv2.imshow",
"os.listdir",
"cv2.resize"
] |
[((234, 245), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (243, 245), False, 'import os\n'), ((263, 278), 'os.listdir', 'os.listdir', (['cwd'], {}), '(cwd)\n', (273, 278), False, 'import os\n'), ((849, 886), 'alexnet.alexnet', 'alexnet', (['WIDTH', 'HEIGHT', 'LEARNING_RATE'], {}), '(WIDTH, HEIGHT, LEARNING_RATE)\n', (856, 886), False, 'from alexnet import alexnet\n'), ((500, 514), 'directkeys.PressKey', 'PressKey', (['dk.W'], {}), '(dk.W)\n', (508, 514), False, 'from directkeys import PressKey, ReleaseKey, DirectionKey as dk\n'), ((519, 535), 'directkeys.ReleaseKey', 'ReleaseKey', (['dk.A'], {}), '(dk.A)\n', (529, 535), False, 'from directkeys import PressKey, ReleaseKey, DirectionKey as dk\n'), ((540, 556), 'directkeys.ReleaseKey', 'ReleaseKey', (['dk.D'], {}), '(dk.D)\n', (550, 556), False, 'from directkeys import PressKey, ReleaseKey, DirectionKey as dk\n'), ((575, 591), 'directkeys.ReleaseKey', 'ReleaseKey', (['dk.D'], {}), '(dk.D)\n', (585, 591), False, 'from directkeys import PressKey, ReleaseKey, DirectionKey as dk\n'), ((596, 610), 'directkeys.PressKey', 'PressKey', (['dk.W'], {}), '(dk.W)\n', (604, 610), False, 'from directkeys import PressKey, ReleaseKey, DirectionKey as dk\n'), ((615, 629), 'directkeys.PressKey', 'PressKey', (['dk.A'], {}), '(dk.A)\n', (623, 629), False, 'from directkeys import PressKey, ReleaseKey, DirectionKey as dk\n'), ((634, 652), 'time.sleep', 'time.sleep', (['t_time'], {}), '(t_time)\n', (644, 652), False, 'import time\n'), ((657, 673), 'directkeys.ReleaseKey', 'ReleaseKey', (['dk.A'], {}), '(dk.A)\n', (667, 673), False, 'from directkeys import PressKey, ReleaseKey, DirectionKey as dk\n'), ((693, 709), 'directkeys.ReleaseKey', 'ReleaseKey', (['dk.A'], {}), '(dk.A)\n', (703, 709), False, 'from directkeys import PressKey, ReleaseKey, DirectionKey as dk\n'), ((714, 728), 'directkeys.PressKey', 'PressKey', (['dk.W'], {}), '(dk.W)\n', (722, 728), False, 'from directkeys import PressKey, ReleaseKey, DirectionKey as dk\n'), ((733, 747), 'directkeys.PressKey', 'PressKey', (['dk.D'], {}), '(dk.D)\n', (741, 747), False, 'from directkeys import PressKey, ReleaseKey, DirectionKey as dk\n'), ((752, 770), 'time.sleep', 'time.sleep', (['t_time'], {}), '(t_time)\n', (762, 770), False, 'import time\n'), ((775, 791), 'directkeys.ReleaseKey', 'ReleaseKey', (['dk.D'], {}), '(dk.D)\n', (785, 791), False, 'from directkeys import PressKey, ReleaseKey, DirectionKey as dk\n'), ((940, 951), 'time.time', 'time.time', ([], {}), '()\n', (949, 951), False, 'import time\n'), ((1016, 1029), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (1026, 1029), False, 'import time\n'), ((1982, 1993), 'getkeys.key_check', 'key_check', ([], {}), '()\n', (1991, 1993), False, 'from getkeys import key_check\n'), ((1216, 1253), 'grabscreen.grab_screen', 'grab_screen', ([], {'region': '(0, 40, 800, 640)'}), '(region=(0, 40, 800, 640))\n', (1227, 1253), False, 'from grabscreen import grab_screen\n'), ((1352, 1363), 'time.time', 'time.time', ([], {}), '()\n', (1361, 1363), False, 'import time\n'), ((1385, 1425), 'cv2.cvtColor', 'cv2.cvtColor', (['screen', 'cv2.COLOR_BGR2GRAY'], {}), '(screen, cv2.COLOR_BGR2GRAY)\n', (1397, 1425), False, 'import cv2\n'), ((1453, 1483), 'cv2.resize', 'cv2.resize', (['screen', '(160, 120)'], {}), '(screen, (160, 120))\n', (1463, 1483), False, 'import cv2\n'), ((1497, 1525), 'cv2.imshow', 'cv2.imshow', (['"""screen"""', 'screen'], {}), "('screen', screen)\n", (1507, 1525), False, 'import cv2\n'), ((1768, 1789), 'numpy.argmax', 'np.argmax', (['prediction'], {}), '(prediction)\n', (1777, 1789), True, 'import numpy as np\n'), ((2278, 2291), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (2288, 2291), False, 'import time\n'), ((1593, 1616), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (1614, 1616), False, 'import cv2\n'), ((2182, 2198), 'directkeys.ReleaseKey', 'ReleaseKey', (['dk.A'], {}), '(dk.A)\n', (2192, 2198), False, 'from directkeys import PressKey, ReleaseKey, DirectionKey as dk\n'), ((2215, 2231), 'directkeys.ReleaseKey', 'ReleaseKey', (['dk.W'], {}), '(dk.W)\n', (2225, 2231), False, 'from directkeys import PressKey, ReleaseKey, DirectionKey as dk\n'), ((2248, 2264), 'directkeys.ReleaseKey', 'ReleaseKey', (['dk.D'], {}), '(dk.D)\n', (2258, 2264), False, 'from directkeys import PressKey, ReleaseKey, DirectionKey as dk\n'), ((1541, 1556), 'cv2.waitKey', 'cv2.waitKey', (['(25)'], {}), '(25)\n', (1552, 1556), False, 'import cv2\n'), ((1302, 1313), 'time.time', 'time.time', ([], {}), '()\n', (1311, 1313), False, 'import time\n')]
|
import cv2
import time
import imutils
import argparse
import numpy as np
import logging
from imutils.video import FPS
from imutils.video import VideoStream
logging.basicConfig(level=logging.INFO,
format='%(asctime)s :: %(levelname)s :: %(message)s')
#Constructing Argument Parse to input from Command Line
ap = argparse.ArgumentParser()
ap.add_argument("-p", "--prototxt", help = 'Path to prototxt', default = 'object/model/SSD_MobileNet_prototxt.txt')
ap.add_argument("-m", "--model", help = 'Path to model weights', default = 'object/model/SSD_MobileNet.caffemodel')
ap.add_argument("-c", "--confidence", type = float, default = 0.7)
args = vars(ap.parse_args())
#Initialize Objects and corresponding colors which the model can detect
labels = ["background", "aeroplane", "bicycle", "bird",
"boat","bottle", "bus", "car", "cat", "chair", "cow",
"diningtable","dog", "horse", "motorbike", "person", "pottedplant",
"sheep","sofa", "train", "tvmonitor"]
colors = np.random.uniform(0, 255, size=(len(labels), 3))
#Loading Caffe Model
print('[Status] Loading Model...')
nn = cv2.dnn.readNetFromCaffe(args['prototxt'], args['model'])
#Initialize Video Stream
print('[Status] Starting Video Stream...')
vs = VideoStream(src=0, framerate=120, resolution=(1280,720)).start()
time.sleep(2.0)
fps = FPS().start()
#Loop Video Stream
while True:
#Resize Frame to 400 pixels
frame = vs.read()
frame = imutils.resize(frame, width=1280)
(h, w) = frame.shape[:2]
#Converting Frame to Blob
blob = cv2.dnn.blobFromImage(cv2.resize(frame, (300, 300)),
0.007843, (300, 300), 127.5)
#Passing Blob through network to detect and predict
nn.setInput(blob)
detections = nn.forward()
#Loop over the detections
for i in np.arange(0, detections.shape[2]):
#Extracting the confidence of predictions
confidence = detections[0, 0, i, 2]
#Filtering out weak predictions
if confidence > args["confidence"]:
#Extracting the index of the labels from the detection
#Computing the (x,y) - coordinates of the bounding box
idx = int(detections[0, 0, i, 1])
#Extracting bounding box coordinates
box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
(startX, startY, endX, endY) = box.astype("int")
#Drawing the prediction and bounding box
label = "{}: {:.2f}%".format(labels[idx], confidence * 100)
cv2.rectangle(frame, (startX, startY), (endX, endY), colors[idx], 2)
y = startY - 15 if startY - 15 > 15 else startY + 15
cv2.putText(frame, label, (startX, y),cv2.FONT_HERSHEY_SIMPLEX, 0.5, colors[idx], 2)
cv2.imshow("Frame", frame)
key = cv2.waitKey(1) & 0xFF
if key == ord('q'):
break
fps.update()
fps.stop()
print("[Info] Elapsed time: {:.2f}".format(fps.elapsed()))
print("[Info] Approximate FPS: {:.2f}".format(fps.fps()))
cv2.destroyAllWindows()
vs.stop()
|
[
"imutils.video.VideoStream",
"imutils.video.FPS",
"cv2.putText",
"argparse.ArgumentParser",
"logging.basicConfig",
"cv2.waitKey",
"cv2.imshow",
"time.sleep",
"cv2.rectangle",
"numpy.arange",
"numpy.array",
"cv2.dnn.readNetFromCaffe",
"imutils.resize",
"cv2.destroyAllWindows",
"cv2.resize"
] |
[((166, 264), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO', 'format': '"""%(asctime)s :: %(levelname)s :: %(message)s"""'}), "(level=logging.INFO, format=\n '%(asctime)s :: %(levelname)s :: %(message)s')\n", (185, 264), False, 'import logging\n'), ((346, 371), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (369, 371), False, 'import argparse\n'), ((1127, 1184), 'cv2.dnn.readNetFromCaffe', 'cv2.dnn.readNetFromCaffe', (["args['prototxt']", "args['model']"], {}), "(args['prototxt'], args['model'])\n", (1151, 1184), False, 'import cv2\n'), ((1329, 1344), 'time.sleep', 'time.sleep', (['(2.0)'], {}), '(2.0)\n', (1339, 1344), False, 'import time\n'), ((3083, 3106), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (3104, 3106), False, 'import cv2\n'), ((1472, 1505), 'imutils.resize', 'imutils.resize', (['frame'], {'width': '(1280)'}), '(frame, width=1280)\n', (1486, 1505), False, 'import imutils\n'), ((1832, 1865), 'numpy.arange', 'np.arange', (['(0)', 'detections.shape[2]'], {}), '(0, detections.shape[2])\n', (1841, 1865), True, 'import numpy as np\n'), ((2818, 2844), 'cv2.imshow', 'cv2.imshow', (['"""Frame"""', 'frame'], {}), "('Frame', frame)\n", (2828, 2844), False, 'import cv2\n'), ((1263, 1320), 'imutils.video.VideoStream', 'VideoStream', ([], {'src': '(0)', 'framerate': '(120)', 'resolution': '(1280, 720)'}), '(src=0, framerate=120, resolution=(1280, 720))\n', (1274, 1320), False, 'from imutils.video import VideoStream\n'), ((1352, 1357), 'imutils.video.FPS', 'FPS', ([], {}), '()\n', (1355, 1357), False, 'from imutils.video import FPS\n'), ((1603, 1632), 'cv2.resize', 'cv2.resize', (['frame', '(300, 300)'], {}), '(frame, (300, 300))\n', (1613, 1632), False, 'import cv2\n'), ((2856, 2870), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (2867, 2870), False, 'import cv2\n'), ((2576, 2644), 'cv2.rectangle', 'cv2.rectangle', (['frame', '(startX, startY)', '(endX, endY)', 'colors[idx]', '(2)'], {}), '(frame, (startX, startY), (endX, endY), colors[idx], 2)\n', (2589, 2644), False, 'import cv2\n'), ((2726, 2815), 'cv2.putText', 'cv2.putText', (['frame', 'label', '(startX, y)', 'cv2.FONT_HERSHEY_SIMPLEX', '(0.5)', 'colors[idx]', '(2)'], {}), '(frame, label, (startX, y), cv2.FONT_HERSHEY_SIMPLEX, 0.5,\n colors[idx], 2)\n', (2737, 2815), False, 'import cv2\n'), ((2349, 2371), 'numpy.array', 'np.array', (['[w, h, w, h]'], {}), '([w, h, w, h])\n', (2357, 2371), True, 'import numpy as np\n')]
|
import cv2
import glob
import h5py
import imageio
import numpy as np
import os
import matplotlib.pylab as plt
from keras.datasets import mnist
from keras.preprocessing.image import ImageDataGenerator
from keras.utils import np_utils
def normalization(X):
return X / 127.5 - 1
def inverse_normalization(X):
return np.round((X + 1.) / 2. * 255.).astype('uint8')
def load_mnist(image_data_format):
(X_train, y_train), (X_test, y_test) = mnist.load_data()
if image_data_format == "channels_first":
X_train = X_train.reshape(X_train.shape[0], 1, 28, 28)
X_test = X_test.reshape(X_test.shape[0], 1, 28, 28)
else:
X_train = X_train.reshape(X_train.shape[0], 28, 28, 1)
X_test = X_test.reshape(X_test.shape[0], 28, 28, 1)
X_train = X_train.astype("float32")
X_test = X_test.astype("float32")
X_train = normalization(X_train)
X_test = normalization(X_test)
nb_classes = len(np.unique(np.hstack((y_train, y_test))))
Y_train = np_utils.to_categorical(y_train, nb_classes)
Y_test = np_utils.to_categorical(y_test, nb_classes)
print(X_train.shape, X_test.shape, Y_train.shape, Y_test.shape)
return X_train, Y_train, X_test, Y_test
def load_celebA(img_dim, image_data_format):
with h5py.File("../../data/processed/CelebA_%s_data.h5" % img_dim, "r") as hf:
X_real_train = hf["data"][:].astype(np.float32)
X_real_train = normalization(X_real_train)
if image_data_format == "channels_last":
X_real_train = X_real_train.transpose(0, 2, 3, 1)
return X_real_train
def gen_batch(X, batch_size):
while True:
idx = np.random.choice(X.shape[0], batch_size, replace=False)
yield X[idx]
def data_generator_from_dir(data_dir, target_size, batch_size):
# data_gen args
print("Loading data from", data_dir)
# Check if number of files in data_dir is a multiple of batch_size
number_of_images = sum([len(files) for r, d, files in os.walk(data_dir)])
if number_of_images % batch_size != 0:
raise ValueError("ERROR: # of images in " + str(data_dir) + " found by keras.ImageDataGenerator is not a multiple of the batch_size ( " + str(batch_size) + " )!\nFound " + str(number_of_images) + " images. Add " + str(batch_size - number_of_images % batch_size) + " more image(s), or delete " + str(number_of_images % batch_size) + " image(s).")
# datagens
data_generator_args = dict(preprocessing_function=normalization)
image_datagen = ImageDataGenerator(**data_generator_args)
# Image generators
image_data_generator = image_datagen.flow_from_directory(data_dir, target_size=target_size, batch_size=batch_size, class_mode=None, seed=29)
if len(image_data_generator) == 0:
raise ValueError("ERROR: # of images found by keras.ImageDataGenerator is 0!\nPlease save the images in the data_dir into at least one modre directory, preferably into classes. Given data_dir:", data_dir)
return image_data_generator
def sample_noise(noise_scale, batch_size, noise_dim):
return np.random.normal(scale=noise_scale, size=(batch_size, noise_dim[0]))
def sample_cat(batch_size, cat_dim):
y = np.zeros((batch_size, cat_dim[0]), dtype="float32")
random_y = np.random.randint(0, cat_dim[0], size=batch_size)
y[np.arange(batch_size), random_y] = 1
return y
def get_disc_batch(X_real_batch, generator_model, batch_counter, batch_size, cat_dim, cont_dim, noise_dim,
noise_scale=0.5, label_smoothing=False, label_flipping=0):
# Create X_disc: alternatively only generated or real images
if batch_counter % 2 == 0:
# Pass noise to the generator
y_cat = sample_cat(batch_size, cat_dim)
y_cont = sample_noise(noise_scale, batch_size, cont_dim)
noise_input = sample_noise(noise_scale, batch_size, noise_dim)
# Produce an output
X_disc = generator_model.predict([y_cat, y_cont, noise_input],batch_size=batch_size)
y_disc = np.zeros((X_disc.shape[0], 2), dtype=np.uint8)
y_disc[:, 0] = 1
if label_flipping > 0:
p = np.random.binomial(1, label_flipping)
if p > 0:
y_disc[:, [0, 1]] = y_disc[:, [1, 0]]
else:
X_disc = X_real_batch
y_cat = sample_cat(batch_size, cat_dim)
y_cont = sample_noise(noise_scale, batch_size, cont_dim)
y_disc = np.zeros((X_disc.shape[0], 2), dtype=np.uint8)
if label_smoothing:
y_disc[:, 1] = np.random.uniform(low=0.9, high=1, size=y_disc.shape[0])
else:
y_disc[:, 1] = 1
if label_flipping > 0:
p = np.random.binomial(1, label_flipping)
if p > 0:
y_disc[:, [0, 1]] = y_disc[:, [1, 0]]
# Repeat y_cont to accomodate for keras" loss function conventions
y_cont = np.expand_dims(y_cont, 1)
y_cont = np.repeat(y_cont, 2, axis=1)
return X_disc, y_disc, y_cat, y_cont
def get_gen_batch(batch_size, cat_dim, cont_dim, noise_dim, noise_scale=0.5):
X_gen = sample_noise(noise_scale, batch_size, noise_dim)
y_gen = np.zeros((X_gen.shape[0], 2), dtype=np.uint8)
y_gen[:, 1] = 1
y_cat = sample_cat(batch_size, cat_dim)
y_cont = sample_noise(noise_scale, batch_size, cont_dim)
# Repeat y_cont to accomodate for keras" loss function conventions
y_cont_target = np.expand_dims(y_cont, 1)
y_cont_target = np.repeat(y_cont_target, 2, axis=1)
return X_gen, y_gen, y_cat, y_cont, y_cont_target
def plot_losses(disc_total_losses, disc_log_losses, disc_cat_losses, disc_cont_losses,
gen_total_losses, gen_log_losses, gen_cat_losses, gen_cont_losses,
model_name, init_epoch=0):
epochs = np.arange(len(disc_total_losses)) + init_epoch
fig = plt.figure()
plt.plot(epochs, disc_total_losses, linewidth=2, label='disc_total_loss')
plt.plot(epochs, disc_log_losses, linewidth=1, label='disc_log_loss')
plt.plot(epochs, disc_cat_losses, linewidth=1, label='disc_cat_loss')
plt.plot(epochs, disc_cont_losses, linewidth=1, label='disc_cont_loss')
plt.plot(epochs, gen_total_losses, linewidth=2, label='gen_total_loss')
plt.plot(epochs, gen_log_losses, linewidth=1, label='gen_log_loss')
plt.plot(epochs, gen_cat_losses, linewidth=1, label='gen_cat_loss')
plt.plot(epochs, gen_cont_losses, linewidth=1, label='gen_cont_loss')
plt.legend()
plt.title("Losses")
plt.xlabel("Epochs")
plt.savefig(os.path.join("../../figures", model_name, model_name + "_losses.png"), bbox_inches='tight')
plt.clf()
plt.close()
def plot_generated_batch(X_real, generator_model, epoch_number,
batch_size, cat_dim, cont_dim, noise_dim,
image_data_format, model_name,
noise_scale=0.5, suffix='training', MAX_FRAMES_PER_GIF=100):
# Generate images
y_cat = sample_cat(batch_size, cat_dim)
y_cont = sample_noise(noise_scale, batch_size, cont_dim)
noise_input = sample_noise(noise_scale, batch_size, noise_dim)
# Produce an output
X_gen = generator_model.predict([y_cat, y_cont, noise_input],batch_size=batch_size)
X_real = inverse_normalization(X_real)
X_gen = inverse_normalization(X_gen)
Xg = X_gen[:8]
Xr = X_real[:8]
if image_data_format == "channels_last":
X = np.concatenate((Xg, Xr), axis=0)
list_rows = []
for i in range(int(X.shape[0] / 4)):
Xr = np.concatenate([X[k] for k in range(4 * i, 4 * (i + 1))], axis=1)
list_rows.append(Xr)
Xr = np.concatenate(list_rows, axis=0)
if image_data_format == "channels_first":
X = np.concatenate((Xg, Xr), axis=0)
list_rows = []
for i in range(int(X.shape[0] / 4)):
Xr = np.concatenate([X[k] for k in range(4 * i, 4 * (i + 1))], axis=2)
list_rows.append(Xr)
Xr = np.concatenate(list_rows, axis=1)
Xr = Xr.transpose(1,2,0)
# Make iter text
text_image = cv2.putText(np.zeros((32, Xr.shape[1], Xr.shape[2])),
'iter %s' % str(epoch_number), (10, 20), cv2.FONT_HERSHEY_SIMPLEX, .5, (255, 255, 255), 1, cv2.LINE_AA).astype('uint8')
image = np.vstack((text_image, Xr))
# if Xr.shape[-1] == 1:
# plt.imshow(Xr[:, :, 0], cmap="gray")
# else:
# plt.imshow(Xr)
# plt.axis('off')
# plt.savefig(os.path.join("../../figures", model_name, "current_batch.png"), bbox_inches='tight')
# plt.clf()
# plt.close()
imageio.imsave(os.path.join("../../figures", model_name, model_name + "_current_batch_%s.png" % suffix), image)
# Make gif
gif_frames = []
# Read old gif frames
try:
gif_frames_reader = imageio.get_reader(os.path.join("../../figures", model_name, model_name + "_%s.gif" % suffix))
for frame in gif_frames_reader:
gif_frames.append(frame[:, :, :3])
except:
pass
# Append new frame
im = cv2.putText(np.concatenate((np.zeros((32, Xg[0].shape[1], Xg[0].shape[2])), Xg[0]), axis=0),
'iter %s' % str(epoch_number), (10, 20), cv2.FONT_HERSHEY_SIMPLEX, .5, (255, 255, 255), 1, cv2.LINE_AA).astype('uint8')
gif_frames.append(im)
# If frames exceeds, save as different file
if len(gif_frames) > MAX_FRAMES_PER_GIF:
print("Splitting the GIF...")
gif_frames_00 = gif_frames[:MAX_FRAMES_PER_GIF]
num_of_gifs_already_saved = len(glob.glob(os.path.join("../../figures", model_name, model_name + "_%s_*.gif" % suffix)))
print("Saving", os.path.join("../../figures", model_name, model_name + "_%s_%03d.gif" % (suffix, num_of_gifs_already_saved)))
imageio.mimsave(os.path.join("../../figures", model_name, model_name + "_%s_%03d.gif" % (suffix, num_of_gifs_already_saved)), gif_frames_00)
gif_frames = gif_frames[MAX_FRAMES_PER_GIF:]
# Save gif
print("Saving", os.path.join("../../figures", model_name, model_name + "_%s.gif" % suffix))
imageio.mimsave(os.path.join("../../figures", model_name, model_name + "_%s.gif" % suffix), gif_frames)
|
[
"keras.preprocessing.image.ImageDataGenerator",
"os.walk",
"numpy.random.randint",
"numpy.arange",
"numpy.random.normal",
"matplotlib.pylab.close",
"matplotlib.pylab.title",
"os.path.join",
"numpy.round",
"matplotlib.pylab.figure",
"matplotlib.pylab.legend",
"keras.utils.np_utils.to_categorical",
"numpy.random.choice",
"numpy.repeat",
"h5py.File",
"numpy.random.binomial",
"matplotlib.pylab.clf",
"numpy.hstack",
"matplotlib.pylab.plot",
"matplotlib.pylab.xlabel",
"numpy.vstack",
"numpy.concatenate",
"numpy.random.uniform",
"keras.datasets.mnist.load_data",
"numpy.zeros",
"numpy.expand_dims"
] |
[((455, 472), 'keras.datasets.mnist.load_data', 'mnist.load_data', ([], {}), '()\n', (470, 472), False, 'from keras.datasets import mnist\n'), ((1006, 1050), 'keras.utils.np_utils.to_categorical', 'np_utils.to_categorical', (['y_train', 'nb_classes'], {}), '(y_train, nb_classes)\n', (1029, 1050), False, 'from keras.utils import np_utils\n'), ((1064, 1107), 'keras.utils.np_utils.to_categorical', 'np_utils.to_categorical', (['y_test', 'nb_classes'], {}), '(y_test, nb_classes)\n', (1087, 1107), False, 'from keras.utils import np_utils\n'), ((2522, 2563), 'keras.preprocessing.image.ImageDataGenerator', 'ImageDataGenerator', ([], {}), '(**data_generator_args)\n', (2540, 2563), False, 'from keras.preprocessing.image import ImageDataGenerator\n'), ((3087, 3155), 'numpy.random.normal', 'np.random.normal', ([], {'scale': 'noise_scale', 'size': '(batch_size, noise_dim[0])'}), '(scale=noise_scale, size=(batch_size, noise_dim[0]))\n', (3103, 3155), True, 'import numpy as np\n'), ((3204, 3255), 'numpy.zeros', 'np.zeros', (['(batch_size, cat_dim[0])'], {'dtype': '"""float32"""'}), "((batch_size, cat_dim[0]), dtype='float32')\n", (3212, 3255), True, 'import numpy as np\n'), ((3271, 3320), 'numpy.random.randint', 'np.random.randint', (['(0)', 'cat_dim[0]'], {'size': 'batch_size'}), '(0, cat_dim[0], size=batch_size)\n', (3288, 3320), True, 'import numpy as np\n'), ((4876, 4901), 'numpy.expand_dims', 'np.expand_dims', (['y_cont', '(1)'], {}), '(y_cont, 1)\n', (4890, 4901), True, 'import numpy as np\n'), ((4915, 4943), 'numpy.repeat', 'np.repeat', (['y_cont', '(2)'], {'axis': '(1)'}), '(y_cont, 2, axis=1)\n', (4924, 4943), True, 'import numpy as np\n'), ((5140, 5185), 'numpy.zeros', 'np.zeros', (['(X_gen.shape[0], 2)'], {'dtype': 'np.uint8'}), '((X_gen.shape[0], 2), dtype=np.uint8)\n', (5148, 5185), True, 'import numpy as np\n'), ((5404, 5429), 'numpy.expand_dims', 'np.expand_dims', (['y_cont', '(1)'], {}), '(y_cont, 1)\n', (5418, 5429), True, 'import numpy as np\n'), ((5450, 5485), 'numpy.repeat', 'np.repeat', (['y_cont_target', '(2)'], {'axis': '(1)'}), '(y_cont_target, 2, axis=1)\n', (5459, 5485), True, 'import numpy as np\n'), ((5826, 5838), 'matplotlib.pylab.figure', 'plt.figure', ([], {}), '()\n', (5836, 5838), True, 'import matplotlib.pylab as plt\n'), ((5843, 5916), 'matplotlib.pylab.plot', 'plt.plot', (['epochs', 'disc_total_losses'], {'linewidth': '(2)', 'label': '"""disc_total_loss"""'}), "(epochs, disc_total_losses, linewidth=2, label='disc_total_loss')\n", (5851, 5916), True, 'import matplotlib.pylab as plt\n'), ((5921, 5990), 'matplotlib.pylab.plot', 'plt.plot', (['epochs', 'disc_log_losses'], {'linewidth': '(1)', 'label': '"""disc_log_loss"""'}), "(epochs, disc_log_losses, linewidth=1, label='disc_log_loss')\n", (5929, 5990), True, 'import matplotlib.pylab as plt\n'), ((5995, 6064), 'matplotlib.pylab.plot', 'plt.plot', (['epochs', 'disc_cat_losses'], {'linewidth': '(1)', 'label': '"""disc_cat_loss"""'}), "(epochs, disc_cat_losses, linewidth=1, label='disc_cat_loss')\n", (6003, 6064), True, 'import matplotlib.pylab as plt\n'), ((6069, 6140), 'matplotlib.pylab.plot', 'plt.plot', (['epochs', 'disc_cont_losses'], {'linewidth': '(1)', 'label': '"""disc_cont_loss"""'}), "(epochs, disc_cont_losses, linewidth=1, label='disc_cont_loss')\n", (6077, 6140), True, 'import matplotlib.pylab as plt\n'), ((6145, 6216), 'matplotlib.pylab.plot', 'plt.plot', (['epochs', 'gen_total_losses'], {'linewidth': '(2)', 'label': '"""gen_total_loss"""'}), "(epochs, gen_total_losses, linewidth=2, label='gen_total_loss')\n", (6153, 6216), True, 'import matplotlib.pylab as plt\n'), ((6221, 6288), 'matplotlib.pylab.plot', 'plt.plot', (['epochs', 'gen_log_losses'], {'linewidth': '(1)', 'label': '"""gen_log_loss"""'}), "(epochs, gen_log_losses, linewidth=1, label='gen_log_loss')\n", (6229, 6288), True, 'import matplotlib.pylab as plt\n'), ((6293, 6360), 'matplotlib.pylab.plot', 'plt.plot', (['epochs', 'gen_cat_losses'], {'linewidth': '(1)', 'label': '"""gen_cat_loss"""'}), "(epochs, gen_cat_losses, linewidth=1, label='gen_cat_loss')\n", (6301, 6360), True, 'import matplotlib.pylab as plt\n'), ((6365, 6434), 'matplotlib.pylab.plot', 'plt.plot', (['epochs', 'gen_cont_losses'], {'linewidth': '(1)', 'label': '"""gen_cont_loss"""'}), "(epochs, gen_cont_losses, linewidth=1, label='gen_cont_loss')\n", (6373, 6434), True, 'import matplotlib.pylab as plt\n'), ((6439, 6451), 'matplotlib.pylab.legend', 'plt.legend', ([], {}), '()\n', (6449, 6451), True, 'import matplotlib.pylab as plt\n'), ((6456, 6475), 'matplotlib.pylab.title', 'plt.title', (['"""Losses"""'], {}), "('Losses')\n", (6465, 6475), True, 'import matplotlib.pylab as plt\n'), ((6480, 6500), 'matplotlib.pylab.xlabel', 'plt.xlabel', (['"""Epochs"""'], {}), "('Epochs')\n", (6490, 6500), True, 'import matplotlib.pylab as plt\n'), ((6613, 6622), 'matplotlib.pylab.clf', 'plt.clf', ([], {}), '()\n', (6620, 6622), True, 'import matplotlib.pylab as plt\n'), ((6627, 6638), 'matplotlib.pylab.close', 'plt.close', ([], {}), '()\n', (6636, 6638), True, 'import matplotlib.pylab as plt\n'), ((8281, 8308), 'numpy.vstack', 'np.vstack', (['(text_image, Xr)'], {}), '((text_image, Xr))\n', (8290, 8308), True, 'import numpy as np\n'), ((1279, 1345), 'h5py.File', 'h5py.File', (["('../../data/processed/CelebA_%s_data.h5' % img_dim)", '"""r"""'], {}), "('../../data/processed/CelebA_%s_data.h5' % img_dim, 'r')\n", (1288, 1345), False, 'import h5py\n'), ((1665, 1720), 'numpy.random.choice', 'np.random.choice', (['X.shape[0]', 'batch_size'], {'replace': '(False)'}), '(X.shape[0], batch_size, replace=False)\n', (1681, 1720), True, 'import numpy as np\n'), ((4022, 4068), 'numpy.zeros', 'np.zeros', (['(X_disc.shape[0], 2)'], {'dtype': 'np.uint8'}), '((X_disc.shape[0], 2), dtype=np.uint8)\n', (4030, 4068), True, 'import numpy as np\n'), ((4427, 4473), 'numpy.zeros', 'np.zeros', (['(X_disc.shape[0], 2)'], {'dtype': 'np.uint8'}), '((X_disc.shape[0], 2), dtype=np.uint8)\n', (4435, 4473), True, 'import numpy as np\n'), ((6517, 6586), 'os.path.join', 'os.path.join', (['"""../../figures"""', 'model_name', "(model_name + '_losses.png')"], {}), "('../../figures', model_name, model_name + '_losses.png')\n", (6529, 6586), False, 'import os\n'), ((7404, 7436), 'numpy.concatenate', 'np.concatenate', (['(Xg, Xr)'], {'axis': '(0)'}), '((Xg, Xr), axis=0)\n', (7418, 7436), True, 'import numpy as np\n'), ((7635, 7668), 'numpy.concatenate', 'np.concatenate', (['list_rows'], {'axis': '(0)'}), '(list_rows, axis=0)\n', (7649, 7668), True, 'import numpy as np\n'), ((7728, 7760), 'numpy.concatenate', 'np.concatenate', (['(Xg, Xr)'], {'axis': '(0)'}), '((Xg, Xr), axis=0)\n', (7742, 7760), True, 'import numpy as np\n'), ((7959, 7992), 'numpy.concatenate', 'np.concatenate', (['list_rows'], {'axis': '(1)'}), '(list_rows, axis=1)\n', (7973, 7992), True, 'import numpy as np\n'), ((8601, 8694), 'os.path.join', 'os.path.join', (['"""../../figures"""', 'model_name', "(model_name + '_current_batch_%s.png' % suffix)"], {}), "('../../figures', model_name, model_name + \n '_current_batch_%s.png' % suffix)\n", (8613, 8694), False, 'import os\n'), ((9987, 10061), 'os.path.join', 'os.path.join', (['"""../../figures"""', 'model_name', "(model_name + '_%s.gif' % suffix)"], {}), "('../../figures', model_name, model_name + '_%s.gif' % suffix)\n", (9999, 10061), False, 'import os\n'), ((10083, 10157), 'os.path.join', 'os.path.join', (['"""../../figures"""', 'model_name', "(model_name + '_%s.gif' % suffix)"], {}), "('../../figures', model_name, model_name + '_%s.gif' % suffix)\n", (10095, 10157), False, 'import os\n'), ((327, 360), 'numpy.round', 'np.round', (['((X + 1.0) / 2.0 * 255.0)'], {}), '((X + 1.0) / 2.0 * 255.0)\n', (335, 360), True, 'import numpy as np\n'), ((960, 988), 'numpy.hstack', 'np.hstack', (['(y_train, y_test)'], {}), '((y_train, y_test))\n', (969, 988), True, 'import numpy as np\n'), ((3327, 3348), 'numpy.arange', 'np.arange', (['batch_size'], {}), '(batch_size)\n', (3336, 3348), True, 'import numpy as np\n'), ((4142, 4179), 'numpy.random.binomial', 'np.random.binomial', (['(1)', 'label_flipping'], {}), '(1, label_flipping)\n', (4160, 4179), True, 'import numpy as np\n'), ((4529, 4585), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': '(0.9)', 'high': '(1)', 'size': 'y_disc.shape[0]'}), '(low=0.9, high=1, size=y_disc.shape[0])\n', (4546, 4585), True, 'import numpy as np\n'), ((4677, 4714), 'numpy.random.binomial', 'np.random.binomial', (['(1)', 'label_flipping'], {}), '(1, label_flipping)\n', (4695, 4714), True, 'import numpy as np\n'), ((8817, 8891), 'os.path.join', 'os.path.join', (['"""../../figures"""', 'model_name', "(model_name + '_%s.gif' % suffix)"], {}), "('../../figures', model_name, model_name + '_%s.gif' % suffix)\n", (8829, 8891), False, 'import os\n'), ((9639, 9752), 'os.path.join', 'os.path.join', (['"""../../figures"""', 'model_name', "(model_name + '_%s_%03d.gif' % (suffix, num_of_gifs_already_saved))"], {}), "('../../figures', model_name, model_name + '_%s_%03d.gif' % (\n suffix, num_of_gifs_already_saved))\n", (9651, 9752), False, 'import os\n'), ((9773, 9886), 'os.path.join', 'os.path.join', (['"""../../figures"""', 'model_name', "(model_name + '_%s_%03d.gif' % (suffix, num_of_gifs_already_saved))"], {}), "('../../figures', model_name, model_name + '_%s_%03d.gif' % (\n suffix, num_of_gifs_already_saved))\n", (9785, 9886), False, 'import os\n'), ((2000, 2017), 'os.walk', 'os.walk', (['data_dir'], {}), '(data_dir)\n', (2007, 2017), False, 'import os\n'), ((8077, 8117), 'numpy.zeros', 'np.zeros', (['(32, Xr.shape[1], Xr.shape[2])'], {}), '((32, Xr.shape[1], Xr.shape[2]))\n', (8085, 8117), True, 'import numpy as np\n'), ((9536, 9612), 'os.path.join', 'os.path.join', (['"""../../figures"""', 'model_name', "(model_name + '_%s_*.gif' % suffix)"], {}), "('../../figures', model_name, model_name + '_%s_*.gif' % suffix)\n", (9548, 9612), False, 'import os\n'), ((9066, 9112), 'numpy.zeros', 'np.zeros', (['(32, Xg[0].shape[1], Xg[0].shape[2])'], {}), '((32, Xg[0].shape[1], Xg[0].shape[2]))\n', (9074, 9112), True, 'import numpy as np\n')]
|
__author__ = '<NAME>'
import pymc
import numpy as np
from simtk.unit import kilojoules_per_mole
import torsionfit.database.qmdatabase as TorsionScan
import torsionfit.parameters as par
import warnings
from torsionfit.utils import logger
class TorsionFitModel(object):
"""pymc model
This model only allows a phase angle of 0 but allows force constants to flip signs. If the sign is negative, the
phase angle will be 180.
Attributes:
----------
pymc_parameters: dict() of pymc parameters
parameters_to_optimize: list of tuples (dihedrals to optimize)
fags: list of TorsionScanSet for fragments
platform: OpenMM platform to use for potential energy calculations
"""
def __init__(self, param, frags, stream=None, platform=None, param_to_opt=None, rj=False, sample_n5=False,
continuous_phase=False, sample_phase=False, init_random=True):
"""
Parameters
----------
param : Parmed CharmmParameterSet
frags : list of torsionfit.QMDataBase
stream : str
Path to CHARMM stream file. Default None.
platform : openmm.Platform
Default None.
param_to_opt : list of tuples of torsions.
Default None.
rj : bool
If True, will use reversible jump to sample Fourier terms. If False, will sample all Ks. Default False
sample_n5 : bool
If True, will also sample n=5. Default False
eliminate_phase : bool
If True, will not sample phase. Instead, Ks will be able to take on negative values. Default True. If True,
make sure continuous_phase is also False.
continuous_phase : bool
If True, will allow phases to take on any value between 0-180. If False, phase will be a discrete and only
sample 0 or 180
init_random: bool
Randomize starting condition. Default is True. If false, will resort to whatever value is in the parameter set.
tau: float
hyperparameter on Gaussian prior on K
Returns
-------
pymc model
"""
if type(frags) != list:
frags = [frags]
self.pymc_parameters = dict()
self.frags = frags
self.platform = platform
self.rj = rj
self.sample_n5 = sample_n5
self.continuous_phase = continuous_phase
self.sample_phase = sample_phase
if param_to_opt:
self.parameters_to_optimize = param_to_opt
else:
self.parameters_to_optimize = TorsionScan.to_optimize(param, stream)
# Check that options are reasonable
if not sample_phase and continuous_phase:
warnings.warn("You can't eliminate phase but have continuous phase. Changing continuous phase to False")
self.continuous_phase = False
# set all phases to 0 if eliminate phase is True
if not self.sample_phase:
par.set_phase_0(self.parameters_to_optimize, param)
multiplicities = [1, 2, 3, 4, 6]
if self.sample_n5:
multiplicities = [1, 2, 3, 4, 5, 6]
multiplicity_bitstrings = dict()
# offset
for frag in self.frags:
name = '%s_offset' % frag.topology._residues[0]
offset = pymc.Uniform(name, lower=-50, upper=50, value=0)
self.pymc_parameters[name] = offset
# self.pymc_parameters['log_sigma_k'] = pymc.Uniform('log_sigma_k', lower=-4.6052, upper=3.453, value=np.log(0.01))
# self.pymc_parameters['sigma_k'] = pymc.Lambda('sigma_k',
# lambda log_sigma_k=self.pymc_parameters['log_sigma_k']: np.exp(
# log_sigma_k))
# self.pymc_parameters['precision_k'] = pymc.Lambda('precision_k',
# lambda log_sigma_k=self.pymc_parameters['log_sigma_k']: np.exp(
# -2 * log_sigma_k))
for p in self.parameters_to_optimize:
torsion_name = p[0] + '_' + p[1] + '_' + p[2] + '_' + p[3]
self.pymc_parameters['log_sigma_k_{}'.format(torsion_name)] = pymc.Uniform('log_sigma_k_{}'.format(torsion_name), lower=-4.6052, upper=3.453, value=np.log(0.01))
self.pymc_parameters['sigma_k_{}'.format(torsion_name)] = pymc.Lambda('sigma_k_{}'.format(torsion_name),
lambda log_sigma_k=self.pymc_parameters['log_sigma_k_{}'.format(torsion_name)]: np.exp(
log_sigma_k))
self.pymc_parameters['precision_k_{}'.format(torsion_name)] = pymc.Lambda('precision_k_{}'.format(torsion_name),
lambda log_sigma_k=self.pymc_parameters['log_sigma_k_{}'.format(torsion_name)]: np.exp(
-2 * log_sigma_k))
if torsion_name not in multiplicity_bitstrings.keys():
multiplicity_bitstrings[torsion_name] = 0
for m in multiplicities:
name = p[0] + '_' + p[1] + '_' + p[2] + '_' + p[3] + '_' + str(m) + '_K'
if not self.sample_phase:
k = pymc.Normal(name, mu=0, tau=self.pymc_parameters['precision_k_{}'.format(torsion_name)], value=0)
else:
k = pymc.Uniform(name, lower=0, upper=20, value=0)
for i in range(len(param.dihedral_types[p])):
if param.dihedral_types[p][i].per == m:
multiplicity_bitstrings[torsion_name] += 2 ** (m - 1)
if not self.sample_phase:
k = pymc.Normal(name, mu=0, tau=self.pymc_parameters['precision_k_{}'.format(torsion_name)],
value=param.dihedral_types[p][i].phi_k)
else:
k = pymc.Uniform(name, lower=0, upper=20, value=param.dihedral_types[p][i].phi_k)
break
self.pymc_parameters[name] = k
if self.sample_phase:
name = p[0] + '_' + p[1] + '_' + p[2] + '_' + p[3] + '_' + str(m) + '_Phase'
for i in range(len(param.dihedral_types[p])):
if param.dihedral_types[p][i].per == m:
if self.continuous_phase:
phase = pymc.Uniform(name, lower=0, upper=180.0, value=param.dihedral_types[p][i].phase)
else:
if param.dihedral_types[p][i].phase == 0:
phase = pymc.DiscreteUniform(name, lower=0, upper=1, value=0)
break
if param.dihedral_types[p][i].phase == 180.0:
phase = pymc.DiscreteUniform(name, lower=0, upper=1, value=1)
break
else:
if self.continuous_phase:
phase = pymc.Uniform(name, lower=0, upper=180.0, value=0)
else:
phase = pymc.DiscreteUniform(name, lower=0, upper=1, value=0)
self.pymc_parameters[name] = phase
if self.rj:
for torsion_name in multiplicity_bitstrings.keys():
name = torsion_name + '_multiplicity_bitstring'
bitstring = pymc.DiscreteUniform(name, lower=0, upper=63, value=multiplicity_bitstrings[torsion_name])
self.pymc_parameters[name] = bitstring
if init_random:
# randomize initial value
for parameter in self.pymc_parameters:
if type(self.pymc_parameters[parameter]) != pymc.CommonDeterministics.Lambda: # and parameter[:11] != 'log_sigma_k':
self.pymc_parameters[parameter].random()
logger().info('initial value for {} is {}'.format(parameter, self.pymc_parameters[parameter].value))
self.pymc_parameters['log_sigma'] = pymc.Uniform('log_sigma', lower=-10, upper=3, value=np.log(0.01))
self.pymc_parameters['sigma'] = pymc.Lambda('sigma',
lambda log_sigma=self.pymc_parameters['log_sigma']: np.exp(
log_sigma))
self.pymc_parameters['precision'] = pymc.Lambda('precision',
lambda log_sigma=self.pymc_parameters['log_sigma']: np.exp(
-2 * log_sigma))
# add missing multiplicity terms to parameterSet so that the system has the same number of parameters
par.add_missing(self.parameters_to_optimize, param, sample_n5=self.sample_n5)
@pymc.deterministic
def mm_energy(pymc_parameters=self.pymc_parameters, param=param):
mm = np.ndarray(0)
par.update_param_from_sample(self.parameters_to_optimize, param, model=self, rj=self.rj,
phase=self.sample_phase, n_5=self.sample_n5, continuous=self.continuous_phase,
model_type='openmm')
for mol in self.frags:
mol.compute_energy(param, offset=self.pymc_parameters['%s_offset' % mol.topology._residues[0]],
platform=self.platform)
mm = np.append(mm, mol.mm_energy / kilojoules_per_mole)
return mm
size = sum([len(i.qm_energy) for i in self.frags])
qm_energy = np.ndarray(0)
for i in range(len(frags)):
qm_energy = np.append(qm_energy, frags[i].qm_energy)
#diff_energy = np.ndarray(0)
#for i in range(len(frags)):
# diff_energy = np.append(diff_energy, frags[i].delta_energy)
self.pymc_parameters['mm_energy'] = mm_energy
self.pymc_parameters['qm_fit'] = pymc.Normal('qm_fit', mu=self.pymc_parameters['mm_energy'],
tau=self.pymc_parameters['precision'], size=size, observed=True,
value=qm_energy)
|
[
"torsionfit.parameters.set_phase_0",
"numpy.log",
"pymc.Uniform",
"torsionfit.utils.logger",
"torsionfit.parameters.add_missing",
"torsionfit.parameters.update_param_from_sample",
"numpy.append",
"numpy.exp",
"pymc.Normal",
"warnings.warn",
"torsionfit.database.qmdatabase.to_optimize",
"pymc.DiscreteUniform",
"numpy.ndarray"
] |
[((8975, 9052), 'torsionfit.parameters.add_missing', 'par.add_missing', (['self.parameters_to_optimize', 'param'], {'sample_n5': 'self.sample_n5'}), '(self.parameters_to_optimize, param, sample_n5=self.sample_n5)\n', (8990, 9052), True, 'import torsionfit.parameters as par\n'), ((9850, 9863), 'numpy.ndarray', 'np.ndarray', (['(0)'], {}), '(0)\n', (9860, 9863), True, 'import numpy as np\n'), ((10208, 10354), 'pymc.Normal', 'pymc.Normal', (['"""qm_fit"""'], {'mu': "self.pymc_parameters['mm_energy']", 'tau': "self.pymc_parameters['precision']", 'size': 'size', 'observed': '(True)', 'value': 'qm_energy'}), "('qm_fit', mu=self.pymc_parameters['mm_energy'], tau=self.\n pymc_parameters['precision'], size=size, observed=True, value=qm_energy)\n", (10219, 10354), False, 'import pymc\n'), ((2579, 2617), 'torsionfit.database.qmdatabase.to_optimize', 'TorsionScan.to_optimize', (['param', 'stream'], {}), '(param, stream)\n', (2602, 2617), True, 'import torsionfit.database.qmdatabase as TorsionScan\n'), ((2725, 2839), 'warnings.warn', 'warnings.warn', (['"""You can\'t eliminate phase but have continuous phase. Changing continuous phase to False"""'], {}), '(\n "You can\'t eliminate phase but have continuous phase. Changing continuous phase to False"\n )\n', (2738, 2839), False, 'import warnings\n'), ((2976, 3027), 'torsionfit.parameters.set_phase_0', 'par.set_phase_0', (['self.parameters_to_optimize', 'param'], {}), '(self.parameters_to_optimize, param)\n', (2991, 3027), True, 'import torsionfit.parameters as par\n'), ((3317, 3365), 'pymc.Uniform', 'pymc.Uniform', (['name'], {'lower': '(-50)', 'upper': '(50)', 'value': '(0)'}), '(name, lower=-50, upper=50, value=0)\n', (3329, 3365), False, 'import pymc\n'), ((9173, 9186), 'numpy.ndarray', 'np.ndarray', (['(0)'], {}), '(0)\n', (9183, 9186), True, 'import numpy as np\n'), ((9199, 9396), 'torsionfit.parameters.update_param_from_sample', 'par.update_param_from_sample', (['self.parameters_to_optimize', 'param'], {'model': 'self', 'rj': 'self.rj', 'phase': 'self.sample_phase', 'n_5': 'self.sample_n5', 'continuous': 'self.continuous_phase', 'model_type': '"""openmm"""'}), "(self.parameters_to_optimize, param, model=self,\n rj=self.rj, phase=self.sample_phase, n_5=self.sample_n5, continuous=\n self.continuous_phase, model_type='openmm')\n", (9227, 9396), True, 'import torsionfit.parameters as par\n'), ((9925, 9965), 'numpy.append', 'np.append', (['qm_energy', 'frags[i].qm_energy'], {}), '(qm_energy, frags[i].qm_energy)\n', (9934, 9965), True, 'import numpy as np\n'), ((7666, 7761), 'pymc.DiscreteUniform', 'pymc.DiscreteUniform', (['name'], {'lower': '(0)', 'upper': '(63)', 'value': 'multiplicity_bitstrings[torsion_name]'}), '(name, lower=0, upper=63, value=multiplicity_bitstrings\n [torsion_name])\n', (7686, 7761), False, 'import pymc\n'), ((8339, 8351), 'numpy.log', 'np.log', (['(0.01)'], {}), '(0.01)\n', (8345, 8351), True, 'import numpy as np\n'), ((8518, 8535), 'numpy.exp', 'np.exp', (['log_sigma'], {}), '(log_sigma)\n', (8524, 8535), True, 'import numpy as np\n'), ((8771, 8793), 'numpy.exp', 'np.exp', (['(-2 * log_sigma)'], {}), '(-2 * log_sigma)\n', (8777, 8793), True, 'import numpy as np\n'), ((9697, 9747), 'numpy.append', 'np.append', (['mm', '(mol.mm_energy / kilojoules_per_mole)'], {}), '(mm, mol.mm_energy / kilojoules_per_mole)\n', (9706, 9747), True, 'import numpy as np\n'), ((4351, 4363), 'numpy.log', 'np.log', (['(0.01)'], {}), '(0.01)\n', (4357, 4363), True, 'import numpy as np\n'), ((4614, 4633), 'numpy.exp', 'np.exp', (['log_sigma_k'], {}), '(log_sigma_k)\n', (4620, 4633), True, 'import numpy as np\n'), ((4951, 4975), 'numpy.exp', 'np.exp', (['(-2 * log_sigma_k)'], {}), '(-2 * log_sigma_k)\n', (4957, 4975), True, 'import numpy as np\n'), ((5502, 5548), 'pymc.Uniform', 'pymc.Uniform', (['name'], {'lower': '(0)', 'upper': '(20)', 'value': '(0)'}), '(name, lower=0, upper=20, value=0)\n', (5514, 5548), False, 'import pymc\n'), ((6067, 6144), 'pymc.Uniform', 'pymc.Uniform', (['name'], {'lower': '(0)', 'upper': '(20)', 'value': 'param.dihedral_types[p][i].phi_k'}), '(name, lower=0, upper=20, value=param.dihedral_types[p][i].phi_k)\n', (6079, 6144), False, 'import pymc\n'), ((8140, 8148), 'torsionfit.utils.logger', 'logger', ([], {}), '()\n', (8146, 8148), False, 'from torsionfit.utils import logger\n'), ((6583, 6668), 'pymc.Uniform', 'pymc.Uniform', (['name'], {'lower': '(0)', 'upper': '(180.0)', 'value': 'param.dihedral_types[p][i].phase'}), '(name, lower=0, upper=180.0, value=param.dihedral_types[p][i].phase\n )\n', (6595, 6668), False, 'import pymc\n'), ((7255, 7304), 'pymc.Uniform', 'pymc.Uniform', (['name'], {'lower': '(0)', 'upper': '(180.0)', 'value': '(0)'}), '(name, lower=0, upper=180.0, value=0)\n', (7267, 7304), False, 'import pymc\n'), ((7379, 7432), 'pymc.DiscreteUniform', 'pymc.DiscreteUniform', (['name'], {'lower': '(0)', 'upper': '(1)', 'value': '(0)'}), '(name, lower=0, upper=1, value=0)\n', (7399, 7432), False, 'import pymc\n'), ((6816, 6869), 'pymc.DiscreteUniform', 'pymc.DiscreteUniform', (['name'], {'lower': '(0)', 'upper': '(1)', 'value': '(0)'}), '(name, lower=0, upper=1, value=0)\n', (6836, 6869), False, 'import pymc\n'), ((7035, 7088), 'pymc.DiscreteUniform', 'pymc.DiscreteUniform', (['name'], {'lower': '(0)', 'upper': '(1)', 'value': '(1)'}), '(name, lower=0, upper=1, value=1)\n', (7055, 7088), False, 'import pymc\n')]
|
from numpy import random
from RandomGenerator.randomDecimal import random_decimal
def random_decimal_seeded(start, end, seed):
state = random.get_state()
random.seed(seed)
try:
rand_decimal_seeded = random_decimal(start, end)
return rand_decimal_seeded
finally:
random.set_state(state)
|
[
"numpy.random.get_state",
"RandomGenerator.randomDecimal.random_decimal",
"numpy.random.seed",
"numpy.random.set_state"
] |
[((141, 159), 'numpy.random.get_state', 'random.get_state', ([], {}), '()\n', (157, 159), False, 'from numpy import random\n'), ((164, 181), 'numpy.random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (175, 181), False, 'from numpy import random\n'), ((221, 247), 'RandomGenerator.randomDecimal.random_decimal', 'random_decimal', (['start', 'end'], {}), '(start, end)\n', (235, 247), False, 'from RandomGenerator.randomDecimal import random_decimal\n'), ((304, 327), 'numpy.random.set_state', 'random.set_state', (['state'], {}), '(state)\n', (320, 327), False, 'from numpy import random\n')]
|
"""Copyright (c) Facebook, Inc. and its affiliates.
All rights reserved.
This source code is licensed under the license found in the
LICENSE file in the root directory of this source tree.
Portions of the source code are from the OLTR project which
notice below and in LICENSE in the root directory of
this source tree.
Copyright (c) 2019, <NAME>
All rights reserved.
"""
import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
class CrossEntropyLoss(nn.Module):
def __init__(self, cls_num_list=None, reweight_CE=False):
super().__init__()
if reweight_CE:
idx = 1 # condition could be put in order to set idx
betas = [0, 0.9999]
effective_num = 1.0 - np.power(betas[idx], cls_num_list)
per_cls_weights = (1.0 - betas[idx]) / np.array(effective_num)
per_cls_weights = per_cls_weights / np.sum(per_cls_weights) * len(cls_num_list)
self.per_cls_weights = torch.tensor(per_cls_weights, dtype=torch.float, requires_grad=False)
else:
self.per_cls_weights = None
def to(self, device):
super().to(device)
if self.per_cls_weights is not None:
self.per_cls_weights = self.per_cls_weights.to(device)
return self
def forward(self, output_logits, target): # output is logits
return F.cross_entropy(output_logits, target, weight=self.per_cls_weights)
def create_loss (cls_num_list=None, reweight_CE=False):
print('Loading Softmax Loss.')
return CrossEntropyLoss(cls_num_list, reweight_CE).cuda()
|
[
"numpy.sum",
"numpy.power",
"torch.nn.functional.cross_entropy",
"numpy.array",
"torch.tensor"
] |
[((1370, 1437), 'torch.nn.functional.cross_entropy', 'F.cross_entropy', (['output_logits', 'target'], {'weight': 'self.per_cls_weights'}), '(output_logits, target, weight=self.per_cls_weights)\n', (1385, 1437), True, 'import torch.nn.functional as F\n'), ((977, 1046), 'torch.tensor', 'torch.tensor', (['per_cls_weights'], {'dtype': 'torch.float', 'requires_grad': '(False)'}), '(per_cls_weights, dtype=torch.float, requires_grad=False)\n', (989, 1046), False, 'import torch\n'), ((740, 774), 'numpy.power', 'np.power', (['betas[idx]', 'cls_num_list'], {}), '(betas[idx], cls_num_list)\n', (748, 774), True, 'import numpy as np\n'), ((826, 849), 'numpy.array', 'np.array', (['effective_num'], {}), '(effective_num)\n', (834, 849), True, 'import numpy as np\n'), ((898, 921), 'numpy.sum', 'np.sum', (['per_cls_weights'], {}), '(per_cls_weights)\n', (904, 921), True, 'import numpy as np\n')]
|
# --------------
# Importing header files
import numpy as np
# Path of the file has been stored in variable called 'path'
data = np.genfromtxt(path, delimiter = ",", skip_header = 1)
#New record
new_record=[[50, 9, 4, 1, 0, 0, 40, 0]]
#Code starts here
census = np.concatenate((data, new_record))
print(census)
# --------------
#Code starts here
age = census[:,0]
print(age)
max_age = np.max(age)
print(max_age)
min_age = np.min(age)
print(min_age)
age_mean = np.mean(age)
print(age_mean)
age_std = np.std(age)
print(age_std)
# --------------
#Code starts here
race_0 = census[census[:,2] == 0]
race_1 = census[census[:,2] == 1]
race_2 = census[census[:,2] == 2]
race_3 = census[census[:,2] == 3]
race_4 = census[census[:,2] == 4]
len_0 = len(race_0)
len_1 = len(race_1)
len_2 = len(race_2)
len_3 = len(race_3)
len_4 = len(race_4)
minimum = min(len_0,len_1,len_2,len_3,len_4)
if len_0 == minimum:
minority_race = 0
elif len_1 == minimum:
minority_race = 1
elif len_2 == minimum:
minority_race = 2
elif len_3 == minimum:
minority_race = 3
else:
minority_race = 4
print(minority_race)
# --------------
#Code starts here
senior_citizens = census[census[:,0] > 60]
working_hours_sum = sum(senior_citizens[:,6])
senior_citizens_len = len(senior_citizens)
avg_working_hours = working_hours_sum / senior_citizens_len
print(avg_working_hours)
# --------------
#Code starts here
high = census[census[:,1] > 10]
low = census[census[:,1] <= 10]
avg_pay_high = np.mean(high[:,7])
avg_pay_low = np.mean(low[:,7])
print(avg_pay_high)
print(avg_pay_low)
|
[
"numpy.std",
"numpy.genfromtxt",
"numpy.max",
"numpy.mean",
"numpy.min",
"numpy.concatenate"
] |
[((134, 183), 'numpy.genfromtxt', 'np.genfromtxt', (['path'], {'delimiter': '""","""', 'skip_header': '(1)'}), "(path, delimiter=',', skip_header=1)\n", (147, 183), True, 'import numpy as np\n'), ((279, 313), 'numpy.concatenate', 'np.concatenate', (['(data, new_record)'], {}), '((data, new_record))\n', (293, 313), True, 'import numpy as np\n'), ((410, 421), 'numpy.max', 'np.max', (['age'], {}), '(age)\n', (416, 421), True, 'import numpy as np\n'), ((449, 460), 'numpy.min', 'np.min', (['age'], {}), '(age)\n', (455, 460), True, 'import numpy as np\n'), ((489, 501), 'numpy.mean', 'np.mean', (['age'], {}), '(age)\n', (496, 501), True, 'import numpy as np\n'), ((530, 541), 'numpy.std', 'np.std', (['age'], {}), '(age)\n', (536, 541), True, 'import numpy as np\n'), ((1573, 1592), 'numpy.mean', 'np.mean', (['high[:, 7]'], {}), '(high[:, 7])\n', (1580, 1592), True, 'import numpy as np\n'), ((1607, 1625), 'numpy.mean', 'np.mean', (['low[:, 7]'], {}), '(low[:, 7])\n', (1614, 1625), True, 'import numpy as np\n')]
|
import tensorflow as tf
import numpy as np
test_arr = [[np.zeros(shape=(2, 2), dtype="float32"), 0], [np.ones(shape=(2, 2), dtype="float32"), 1]]
def input_gen():
for i in range(len(test_arr)):
label = test_arr[i][1]
features = test_arr[i][0]
yield label, features
dataset = tf.data.Dataset.from_generator(input_gen, output_types=(tf.int64, tf.float32)).batch(1)
iterator = dataset.make_initializable_iterator()
x, y = iterator.get_next()
print(x, y)
|
[
"tensorflow.data.Dataset.from_generator",
"numpy.zeros",
"numpy.ones"
] |
[((57, 96), 'numpy.zeros', 'np.zeros', ([], {'shape': '(2, 2)', 'dtype': '"""float32"""'}), "(shape=(2, 2), dtype='float32')\n", (65, 96), True, 'import numpy as np\n'), ((103, 141), 'numpy.ones', 'np.ones', ([], {'shape': '(2, 2)', 'dtype': '"""float32"""'}), "(shape=(2, 2), dtype='float32')\n", (110, 141), True, 'import numpy as np\n'), ((308, 386), 'tensorflow.data.Dataset.from_generator', 'tf.data.Dataset.from_generator', (['input_gen'], {'output_types': '(tf.int64, tf.float32)'}), '(input_gen, output_types=(tf.int64, tf.float32))\n', (338, 386), True, 'import tensorflow as tf\n')]
|
"""
Tools for gapfilling missing data.
Gapfill functions that can be applied are called from the gapfunctions module.
"""
import pandas as pd
import numpy as np
from datetime import datetime
from sawyer import gapfunctions as gfuncs
import sawyer.plots as dpl
import sawyer.io as sio
import sawyer.dtools as tools
from IPython.core.debugger import set_trace
class GapfillSource:
"""
Class to make gapfilling data accessible
"""
def __init__(self, dlevel, gapconfs):
"""
Initialize GapfillSource object.
"""
# Get a list of all sources in the gapfill.yaml file (exclude items
# without external sources like interp and fillna)
sourcelist = [gapconfs[k]['sources'].keys() for k in gapconfs.keys()
if 'sources' in gapconfs[k]]
sourcelist = [item for sublist in sourcelist for item in sublist]
self.sourcelist = set(sourcelist)
for i in self.sourcelist:
files = sio.get_file_list(sio.get_datadir(i, datalevel=dlevel))
if len(files) < 1:
raise ValueError('Data from logger {0} and level {1} is not available to gapfill!'.format(i, dlevel))
if not self.sourcelist:
print('Gapfilling configuration contains no external sources...')
else:
# Load dataframes for all external sources into a dictionary
self.sources = {}
self.externalsource = True
for s in self.sourcelist:
if s in sio.sy.loggers: # Check if datalogger is in project
self.sources[s], _ = sio.get_latest_df(s, dlevel,
optmatch='masked')
else: # Eventually check for other sources...
raise ValueError('Source not configured for gapfilling!')
def get_source_list(self, colnum, gapconf, targetidx):
"""
Get data from requested source.
"""
sources = gapconf['sources']
source_list = []
source_df = pd.DataFrame(index=targetidx)
# Multi-source fills send a >1 list of dataframes to gffunc
if len(sources) > 1:
# For each source
for i, sname in enumerate(sources.keys()):
sourcecols = sources[sname]
filldf = self.sources[sname].loc[:,sourcecols[colnum]]
filldf.name = sname + '_' + filldf.name
source_list.append(source_df.join(filldf))
# Single source fills send a one dataframe list to gffunc
else:
sname = list(sources.keys())[0]
sourcecol = sources[sname][colnum]
filldf = self.sources[sname].loc[:,sourcecol]
source_list.append(source_df.join(filldf))
# The source data can be trimmed, which could be useful for linear
# fits.
if 'start_fit' in gapconf and 'end_fit' in gapconf:
stf = gapconf['start_fit']
if stf is None:
stf = source_df.index.min()
enf = gapconf['end_fit']
if enf is None:
enf = datetime.now()
# Get the index range to be trimmed
idxrange = np.logical_and(source_df.index >= stf,
source_df.index <= enf)
for i, f in enumerate(source_list):
source_list[i] = source_list[i].loc[idxrange,:]
return source_list
def get_gffunction(gapconf):
"""
Get the gapfilling function and arguments
"""
args = (); kwargs = {}
if 'gf_function' in gapconf:
outfunc = getattr(gfuncs, gapconf['gf_function'])
if 'gf_kwargs' in gapconf and gapconf['gf_kwargs'] is not None:
kwargs = gapconf['gf_kwargs']
else:
outfunc = getattr(gffunctions, 'substitution')
return [outfunc, kwargs]
def validate_gf_conf(gapconf, gapcolumns):
# Make a gapconf to validate
vgapconf = gapconf.copy()
for c, conf in vgapconf.items():
conf['filltype'] = 'self'
# Validate conf key (non-zero)
assert c not in (0, '0')
# Check for required keys
required_keys = ('gf_function', 'gap_cols', 'start_fill', 'end_fill')
assert all (k in conf for k in required_keys)
# First - copy gapfilling df column names into conf if requested
if conf['gap_cols']=='all':
conf['gap_cols'] = gapcolumns
# Check if gap_cols could be expanded
expand_gfcols = not all([c in gapcolumns for c in conf['gap_cols']])
# External source(s) required to gapfill?
# Are they present and same length?
if conf['gf_function'] in gfuncs.require_src:
assert ('sources' in conf.keys() and len(conf['sources']) > 0)
sources_columns = [conf['sources'][k]
for k in conf['sources'].keys()]
sourcelen = len(sources_columns[0])
assert all(len(l) == sourcelen for l in sources_columns)
# A bunch of stuff to expand or fill in columns for gapfilling
# For one source fills (same source/column fills all gap_cols)
if sourcelen==1 and len(conf['gap_cols'])==1 and not expand_gfcols:
conf['filltype'] = 'one2one'
elif sourcelen==1 and len(conf['gap_cols'])==1 and expand_gfcols:
conf['filltype'] = 'one2many'
test = [any(s in var for s in conf['gap_cols'])
for var in gapcolumns]
conf['gap_cols'] = gapcolumns[test]
elif sourcelen==1 and len(conf['gap_cols'])>1 and not expand_gfcols:
conf['filltype'] = 'one2many'
elif sourcelen==1 and len(conf['gap_cols'])>1 and expand_gfcols:
conf['filltype'] = 'one2many'
test = [any(s in var for s in conf['gap_cols'])
for var in gapcolumns]
conf['gap_cols'] = gapcolumns[test]
# For many-source fills, gap_cols must be same length
elif (sourcelen > 1 and sourcelen==len(conf['gap_cols']) and
not expand_gfcols):
conf['filltype'] = 'many2many'
elif (sourcelen > 1 and sourcelen!=len(conf['gap_cols']) and
not expand_gfcols):
raise ValueError('The number of source and gapfill columns in '
'the configuration file do not match')
elif (sourcelen > 1 and sourcelen==len(conf['gap_cols']) and
expand_gfcols):
raise ValueError('Some of the gapfill columns are incorrect in '
'the configuration file.')
else:
raise ValueError('Unspecified error')
# If no sources required, just expand gap_cols if needed
else:
# Or find dataframe columns matching those in qa_flags
conf['gap_cols'] = tools.regex_colnames(
gapcolumns, conf['gap_cols'])
# Copy modified configuration into vgaconf
vgapconf[c] = conf
return vgapconf
def apply_gapfilling(df_in, dlevel, gapconf, plot=False):
"""
Apply gapfilling to a dataframe. The incoming dataframe (df) is copied
and gaps are filled according to the function and parameters in gapconf.
These changes are recorded in the logical array (df_isfilled)
Args:
df : input dataframe (a qa_masked dataframe for a logger)
gapconf : dict from the logger's gapfill.yaml in sawyer_config
plot : if True, make diagnostic plots for gapfilled column in df
Returns:
Three pandas dataframes with identical dimensions to the input df
df_new : dataframe with any gaps filled using methods in gapconf
df_isfilled : logical dataframe indicating filling (True = filled)
"""
# Make a copy to be a gapfilled dataframe and a boolean array
df = df_in.copy()
df_isfilled = pd.DataFrame(False, index=df.index, columns=df.columns)
# Get gapfilling sources object
gfsource = GapfillSource(dlevel, gapconf)
# Loop through gapconf
for k, conf in gapconf.items():
# Get the start and end fill dates
st = conf['start_fill']
if st is None:
st = df.index.min()
en = conf['end_fill']
if en is None:
en = datetime.now()
# Get the index range to be filled
fillidx = np.logical_and(df.index >= st, df.index <= en)
# Get the gapfilling function and arguments
gffunc, gf_kwargs = get_gffunction(conf)
print('Fill gap {0}, using {1}.'.format(k, gffunc))
# Now loop through
for c, col in enumerate(conf['gap_cols']):
print('Fill column {0}'.format(col))
gf_sources = []
to_fill = df[col]
# Source data must be sent to gffunc, and it must be adjusted
# by methods in the gfsource depending on filltype
if conf['filltype'] == 'one2one' or conf['filltype'] == 'one2many':
gf_sources = gfsource.get_source_list(0, conf, to_fill.index)
elif conf['filltype'] == 'many2many':
gf_sources = gfsource.get_source_list(c, conf, to_fill.index)
# Run the gapfilling function
df[col], gf_bool = gffunc(to_fill, fillidx, *gf_sources,
**gf_kwargs)
df_isfilled[col] = np.logical_or(gf_bool, df_isfilled[col])
# Plot if requested
if plot:
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1,1)
dpl.gf_var_tsplot(ax, col, df_in, df)
plt.show()
# Rewrite df_flag column names
df_isfilled.columns = df_isfilled.columns + '_f'
return df, df_isfilled
def fill_logger(lname, dlevel, plot=False):
"""
Get a gapfilled dataframe for the given logger and a boolean dataframe
indicating what data is filled.
Args:
lname (string): datalogger name
dlevel (string): data level to gapfill
plot (bool): if set, make a plot of the gapfilling
Returns:
df_gf : gapfilled dataframe
df_isfilled : boolean dataframe indicating what values are filled
filedate : datetime object indicating last date of data collection
"""
# Get most recent qa masked data file for logger
df, filedate = sio.get_latest_df(lname, dlevel, optmatch='masked')
# Get gapfilling configuration
gapconf = sio.read_yaml_conf(lname, 'gapfill')
# Validate gapconf
gapconfv = validate_gf_conf(gapconf, df.columns)
# Fill gaps
df_gf, df_isfilled = apply_gapfilling(df, dlevel, gapconfv, plot=plot)
return df_gf, df_isfilled, filedate
|
[
"pandas.DataFrame",
"matplotlib.pyplot.show",
"numpy.logical_and",
"sawyer.dtools.regex_colnames",
"matplotlib.pyplot.subplots",
"sawyer.io.get_datadir",
"sawyer.io.read_yaml_conf",
"numpy.logical_or",
"sawyer.plots.gf_var_tsplot",
"sawyer.io.get_latest_df",
"datetime.datetime.now"
] |
[((7957, 8012), 'pandas.DataFrame', 'pd.DataFrame', (['(False)'], {'index': 'df.index', 'columns': 'df.columns'}), '(False, index=df.index, columns=df.columns)\n', (7969, 8012), True, 'import pandas as pd\n'), ((10443, 10494), 'sawyer.io.get_latest_df', 'sio.get_latest_df', (['lname', 'dlevel'], {'optmatch': '"""masked"""'}), "(lname, dlevel, optmatch='masked')\n", (10460, 10494), True, 'import sawyer.io as sio\n'), ((10544, 10580), 'sawyer.io.read_yaml_conf', 'sio.read_yaml_conf', (['lname', '"""gapfill"""'], {}), "(lname, 'gapfill')\n", (10562, 10580), True, 'import sawyer.io as sio\n'), ((2036, 2065), 'pandas.DataFrame', 'pd.DataFrame', ([], {'index': 'targetidx'}), '(index=targetidx)\n', (2048, 2065), True, 'import pandas as pd\n'), ((8442, 8488), 'numpy.logical_and', 'np.logical_and', (['(df.index >= st)', '(df.index <= en)'], {}), '(df.index >= st, df.index <= en)\n', (8456, 8488), True, 'import numpy as np\n'), ((3198, 3260), 'numpy.logical_and', 'np.logical_and', (['(source_df.index >= stf)', '(source_df.index <= enf)'], {}), '(source_df.index >= stf, source_df.index <= enf)\n', (3212, 3260), True, 'import numpy as np\n'), ((6917, 6967), 'sawyer.dtools.regex_colnames', 'tools.regex_colnames', (['gapcolumns', "conf['gap_cols']"], {}), "(gapcolumns, conf['gap_cols'])\n", (6937, 6967), True, 'import sawyer.dtools as tools\n'), ((8366, 8380), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (8378, 8380), False, 'from datetime import datetime\n'), ((9452, 9492), 'numpy.logical_or', 'np.logical_or', (['gf_bool', 'df_isfilled[col]'], {}), '(gf_bool, df_isfilled[col])\n', (9465, 9492), True, 'import numpy as np\n'), ((997, 1033), 'sawyer.io.get_datadir', 'sio.get_datadir', (['i'], {'datalevel': 'dlevel'}), '(i, datalevel=dlevel)\n', (1012, 1033), True, 'import sawyer.io as sio\n'), ((3112, 3126), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (3124, 3126), False, 'from datetime import datetime\n'), ((9617, 9635), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {}), '(1, 1)\n', (9629, 9635), True, 'import matplotlib.pyplot as plt\n'), ((9651, 9688), 'sawyer.plots.gf_var_tsplot', 'dpl.gf_var_tsplot', (['ax', 'col', 'df_in', 'df'], {}), '(ax, col, df_in, df)\n', (9668, 9688), True, 'import sawyer.plots as dpl\n'), ((9705, 9715), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (9713, 9715), True, 'import matplotlib.pyplot as plt\n'), ((1614, 1661), 'sawyer.io.get_latest_df', 'sio.get_latest_df', (['s', 'dlevel'], {'optmatch': '"""masked"""'}), "(s, dlevel, optmatch='masked')\n", (1631, 1661), True, 'import sawyer.io as sio\n')]
|
from car_utils import get_rotation, get_car_can_path, get_points_rotated
from street_view import ImageWgsHandler
import sys
import time
import threading
from argparse import ArgumentParser
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os
import cv2
from car_utils import OFFSET_STEERING, WHEEL_STEER_RATIO
loopBool = True
orientation, offset_x, offset_y = 0., 0., 0.
fig_gps, fig_path = None, None
ax_gps, ax_path = None, None
base_coord = None
gps_split = None
speed_split, steer_split = None, None
loaded = False
interval_idx = -1
steering_offset, steering_ratio = None, None
factor = 1.
def closeLooping():
global loopBool
loopBool = False
def looping():
global loopBool, loaded
global orientation, offset_x, offset_y
global fig_gps, fig_path
global ax_gps, ax_path
global base_coord
global gps_split
global speed_split, steer_split
global interval_idx
global steering_offset, steering_ratio
g_out_fld = export_info["g_out_fld"]
for idx, (tp_start, tp_end) in enumerate(cut_intervals):
if idx < start_idx:
continue
print(f"{idx} - {tp_start} : {tp_end}")
interval_idx = idx
tp_start += tp_reference
tp_end += tp_reference
rideID = export_info["rideIDs"][idx]
camera_base_path = os.path.join(g_out_fld, rideID[:16])
camera_path = f"{camera_base_path}-{0}.mov"
if os.path.isfile(camera_path):
vid = cv2.VideoCapture(camera_path)
no_frames = vid.get(cv2.CAP_PROP_FRAME_COUNT)
ret, frame = vid.read()
cv2.imshow("First frame", frame)
cv2.waitKey(1)
vid.set(cv2.CAP_PROP_POS_FRAMES, no_frames-2)
ret, frame = vid.read()
cv2.imshow("Last frame", frame)
cv2.waitKey(3)
vid.set(cv2.CAP_PROP_POS_FRAMES, int(no_frames/3))
ret, frame = vid.read()
cv2.imshow("Frame 1/3", frame)
cv2.waitKey(3)
vid.set(cv2.CAP_PROP_POS_FRAMES, int(no_frames/3*2))
ret, frame = vid.read()
cv2.imshow("Frame 2/3", frame)
cv2.waitKey(3)
phone_split = phone[(phone.tp >= tp_start) & (phone.tp < tp_end)]
steer_split = steer[(steer.tp >= tp_start) & (steer.tp < tp_end)]
speed_split = speed[(speed.tp >= tp_start) & (speed.tp < tp_end)]
gps_split = gps_unique[(gps_unique.tp >= tp_start) & (gps_unique.tp < tp_end)]
if prev_annotation is None or idx not in prev_annotation_idx:
steering_offset = OFFSET_STEERING
steering_ratio = WHEEL_STEER_RATIO
print(len(speed_split))
print(len(steer_split))
can_coord = get_car_can_path(speed_split.copy(), steer_split.copy())
guess_orientation = np.random.uniform(0, 360)
guess_offest_x = np.random.uniform(-4, 4)
guess_offest_y = np.random.uniform(-4, 4)
if len(gps_split) > 0:
new_points, new_gps_unique, result = get_rotation(can_coord.copy(), gps_split.copy(),
guess_orientation=guess_orientation,
guess_offest_x=guess_offest_x,
guess_offest_y=guess_offest_y,
simple=False)
orientation, offset_x, offset_y = result.x
offset_x += gps_split.iloc[0].easting
offset_y += gps_split.iloc[0].northing
else:
print("ERROR: No GPS Points (will random guess)")
orientation = guess_orientation
# offset_x, offset_y # Previous offset
closest_gps = gps_unique.iloc[(gps_unique.tp - tp_start).values.argmin()]
offset_x = closest_gps.easting
offset_y = closest_gps.northing
else:
prev = prev_annotation[prev_annotation.interval_idx == idx].iloc[0]
orientation = prev.orientation
steering_offset = prev.steering_offset
steering_ratio = prev.wheel_steer_ratio
if use_px_coord:
offset_px_row, offset_px_col = prev.offset_px_row, prev.offset_px_col
offset_x, offset_y = map_viewer.get_wgs_coord(offset_px_row, offset_px_col)
offset_x, offset_y = offset_x[0], offset_y[0]
else:
offset_x, offset_y = prev.offset_x, prev.offset_y
can_coord = get_car_can_path(speed_split.copy(), steer_split.copy(), steering_offset=steering_offset,
wheel_steer_ratio=steering_ratio)
base_coord = can_coord[["coord_x", "coord_y"]].values
loaded = True
print("Adjust ...")
while loopBool == True:
time.sleep(1)
print("Go to next map...")
loaded = False
loopBool = True
print("Stop!!")
def looping_pre(): # this is new
thread = threading.Thread(target=looping, args=())
# thread.daemon=True #might or might not be needed
thread.start()
if __name__ == "__main__":
arg_parser = ArgumentParser()
arg_parser = ArgumentParser(description='.')
arg_parser.add_argument('dataset', help='Path to dataset folder.')
arg_parser.add_argument('export_info', help='Path to export_info file.')
arg_parser.add_argument('--map', default="util_data/high_res_full_UPB_hybrid.jpg", help='Map.')
arg_parser.add_argument('--start-idx', default=0, type=int, help='interval start idx.')
arg_parser.add_argument('--prev-annotation', default=None, type=str, help='Previous annotation csv file.')
arg_parser.add_argument('--use-px-coord', default=False, type=bool, help='Use conversion from px to coord from '
'csv file.')
arg = arg_parser.parse_args()
start_idx = arg.start_idx
exp = arg.dataset
prev_annotation = arg.prev_annotation
use_px_coord = arg.use_px_coord
prev_annotation_idx = []
# Load data
export_info = np.load(arg.export_info).item()
phone = pd.read_pickle("{}/phone.log.pkl".format(exp))
steer = pd.read_csv("{}/steer.csv".format(exp))
speed = pd.read_csv("{}/speed.csv".format(exp))
map_viewer = ImageWgsHandler(arg.map)
if prev_annotation:
prev_annotation = pd.read_csv(prev_annotation)
prev_annotation_idx = prev_annotation.interval_idx.values
gps_unique = phone.groupby(['loc_tp']).head(1).copy()
fig, ax = map_viewer.plot_wgs_coord(gps_unique.easting.values, gps_unique.northing.values)
ax.set_title(f"{exp} full dataset")
cut_intervals = export_info["cut_intervals"]
tp_reference = export_info["tp_reference"]
fig_path, ax_path = plt.subplots()
fig_gps, ax_gps = plt.subplots()
looping_pre()
convert_method = 1
while not loaded:
time.sleep(0.1)
ax_gps.clear()
map_viewer.plot_wgs_coord(gps_split.easting.values, gps_split.northing.values,
ax=ax_gps)
fig_gps.canvas.draw()
plt.draw()
solver_path = f"{os.path.splitext(arg.export_info)[0]}_{int(time.time()%10000)}.csv"
print(f"Writing solutions to: {solver_path}")
solver = open(solver_path, "a")
solver.write(f"interval_idx,start,end,orientation,offset_x,offset_y,"
f"offset_px_row,offset_px_col,steering_offset,wheel_steer_ratio"
f"\n")
def press(event):
global orientation, offset_x, offset_y, fig_path, ax_path, base_coord, gps_split, loaded
global interval_idx
global convert_method
global steering_offset, steering_ratio
global speed_split, steer_split
global factor
load_next, save_conf = False, False
redo_can_path = False
sys.stdout.flush()
if event.key == 'up':
offset_y += 0.1 * factor
elif event.key == 'down':
offset_y -= 0.1 * factor
elif event.key == 'right':
offset_x += 0.1 * factor
elif event.key == 'left':
offset_x -= 0.1 * factor
elif event.key == ',':
orientation -= 0.30 * factor
elif event.key == '.':
orientation += 0.30 * factor
elif event.key == 'u':
redo_can_path = True
steering_offset += 0.10 * factor
elif event.key == 'i':
redo_can_path = True
steering_offset -= 0.10 * factor
elif event.key == 'o':
redo_can_path = True
steering_ratio += 0.05 * factor
elif event.key == 'p':
redo_can_path = True
steering_ratio -= 0.05 * factor
elif event.key == '-':
redo_can_path = True
factor *= 0.1
print(f"New factor: {factor}")
elif event.key == '+':
redo_can_path = True
factor *= 10.
print(f"New factor: {factor}")
elif event.key == 'c':
convert_method = int(not convert_method)
elif event.key == 'n':
load_next = True
save_conf = True
elif event.key == 'm':
print(f"This {interval_idx} - {orientation},{offset_x},{offset_y},{steering_offset},{steering_ratio}")
elif event.key == 'x':
print(f"skip interval: {interval_idx}")
save_conf = False
load_next = True
elif event.key == 'e':
plt.close("all")
cv2.destroyAllWindows()
exit(0)
if redo_can_path:
can_coord = get_car_can_path(speed_split.copy(), steer_split.copy(), steering_offset=steering_offset,
wheel_steer_ratio=steering_ratio)
base_coord = can_coord[["coord_x", "coord_y"]].values
if load_next:
loaded = False
if save_conf:
# Save final configuration
print(f"Done {interval_idx} - {orientation},{offset_x},{offset_y},{steering_offset},{steering_ratio}")
st, end = cut_intervals[interval_idx]
st += tp_reference
end += tp_reference
px_row, px_col = map_viewer.get_image_coord([offset_x], [offset_y])
solver.write(f"{interval_idx},{st},{end},{orientation},{offset_x},{offset_y},"
f"{px_row[0]},{px_col[0]},{steering_offset},{steering_ratio}\n")
solver.flush()
closeLooping()
while not loaded:
time.sleep(0.1)
print("Draw gps small")
ax_gps.clear()
map_viewer.plot_wgs_coord(gps_split.easting.values, gps_split.northing.values,
ax=ax_gps, convert_method=convert_method)
fig_gps.canvas.draw()
plt.draw()
steering_offset = OFFSET_STEERING
steering_ratio = WHEEL_STEER_RATIO
new_points = get_points_rotated(base_coord, orientation, offset_x, offset_y)
# if fig_path is not None:
ax_path.clear()
map_viewer.plot_wgs_coord(new_points[:, 0], new_points[:, 1], ax=ax_path, convert_method=convert_method)
map_viewer.plot_wgs_coord(gps_split.easting.values, gps_split.northing.values,
ax=ax_path, show_image=False, c="b", convert_method=convert_method)
plt.draw()
fig_path.canvas.mpl_connect('key_press_event', press)
plt.show()
plt.pause(0.0001)
|
[
"numpy.load",
"argparse.ArgumentParser",
"pandas.read_csv",
"car_utils.get_points_rotated",
"os.path.isfile",
"sys.stdout.flush",
"cv2.imshow",
"os.path.join",
"matplotlib.pyplot.close",
"matplotlib.pyplot.draw",
"cv2.destroyAllWindows",
"matplotlib.pyplot.pause",
"matplotlib.pyplot.subplots",
"threading.Thread",
"matplotlib.pyplot.show",
"cv2.waitKey",
"time.sleep",
"numpy.random.uniform",
"time.time",
"cv2.VideoCapture",
"street_view.ImageWgsHandler",
"os.path.splitext"
] |
[((5159, 5200), 'threading.Thread', 'threading.Thread', ([], {'target': 'looping', 'args': '()'}), '(target=looping, args=())\n', (5175, 5200), False, 'import threading\n'), ((5323, 5339), 'argparse.ArgumentParser', 'ArgumentParser', ([], {}), '()\n', (5337, 5339), False, 'from argparse import ArgumentParser\n'), ((5357, 5388), 'argparse.ArgumentParser', 'ArgumentParser', ([], {'description': '"""."""'}), "(description='.')\n", (5371, 5388), False, 'from argparse import ArgumentParser\n'), ((6487, 6511), 'street_view.ImageWgsHandler', 'ImageWgsHandler', (['arg.map'], {}), '(arg.map)\n', (6502, 6511), False, 'from street_view import ImageWgsHandler\n'), ((6975, 6989), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (6987, 6989), True, 'import matplotlib.pyplot as plt\n'), ((7012, 7026), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (7024, 7026), True, 'import matplotlib.pyplot as plt\n'), ((7289, 7299), 'matplotlib.pyplot.draw', 'plt.draw', ([], {}), '()\n', (7297, 7299), True, 'import matplotlib.pyplot as plt\n'), ((11712, 11722), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (11720, 11722), True, 'import matplotlib.pyplot as plt\n'), ((11727, 11744), 'matplotlib.pyplot.pause', 'plt.pause', (['(0.0001)'], {}), '(0.0001)\n', (11736, 11744), True, 'import matplotlib.pyplot as plt\n'), ((1344, 1380), 'os.path.join', 'os.path.join', (['g_out_fld', 'rideID[:16]'], {}), '(g_out_fld, rideID[:16])\n', (1356, 1380), False, 'import os\n'), ((1445, 1472), 'os.path.isfile', 'os.path.isfile', (['camera_path'], {}), '(camera_path)\n', (1459, 1472), False, 'import os\n'), ((6563, 6591), 'pandas.read_csv', 'pd.read_csv', (['prev_annotation'], {}), '(prev_annotation)\n', (6574, 6591), True, 'import pandas as pd\n'), ((7100, 7115), 'time.sleep', 'time.sleep', (['(0.1)'], {}), '(0.1)\n', (7110, 7115), False, 'import time\n'), ((8029, 8047), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (8045, 8047), False, 'import sys\n'), ((11201, 11264), 'car_utils.get_points_rotated', 'get_points_rotated', (['base_coord', 'orientation', 'offset_x', 'offset_y'], {}), '(base_coord, orientation, offset_x, offset_y)\n', (11219, 11264), False, 'from car_utils import get_rotation, get_car_can_path, get_points_rotated\n'), ((11637, 11647), 'matplotlib.pyplot.draw', 'plt.draw', ([], {}), '()\n', (11645, 11647), True, 'import matplotlib.pyplot as plt\n'), ((1492, 1521), 'cv2.VideoCapture', 'cv2.VideoCapture', (['camera_path'], {}), '(camera_path)\n', (1508, 1521), False, 'import cv2\n'), ((1629, 1661), 'cv2.imshow', 'cv2.imshow', (['"""First frame"""', 'frame'], {}), "('First frame', frame)\n", (1639, 1661), False, 'import cv2\n'), ((1674, 1688), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (1685, 1688), False, 'import cv2\n'), ((1796, 1827), 'cv2.imshow', 'cv2.imshow', (['"""Last frame"""', 'frame'], {}), "('Last frame', frame)\n", (1806, 1827), False, 'import cv2\n'), ((1840, 1854), 'cv2.waitKey', 'cv2.waitKey', (['(3)'], {}), '(3)\n', (1851, 1854), False, 'import cv2\n'), ((1967, 1997), 'cv2.imshow', 'cv2.imshow', (['"""Frame 1/3"""', 'frame'], {}), "('Frame 1/3', frame)\n", (1977, 1997), False, 'import cv2\n'), ((2010, 2024), 'cv2.waitKey', 'cv2.waitKey', (['(3)'], {}), '(3)\n', (2021, 2024), False, 'import cv2\n'), ((2139, 2169), 'cv2.imshow', 'cv2.imshow', (['"""Frame 2/3"""', 'frame'], {}), "('Frame 2/3', frame)\n", (2149, 2169), False, 'import cv2\n'), ((2182, 2196), 'cv2.waitKey', 'cv2.waitKey', (['(3)'], {}), '(3)\n', (2193, 2196), False, 'import cv2\n'), ((2858, 2883), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(360)'], {}), '(0, 360)\n', (2875, 2883), True, 'import numpy as np\n'), ((2913, 2937), 'numpy.random.uniform', 'np.random.uniform', (['(-4)', '(4)'], {}), '(-4, 4)\n', (2930, 2937), True, 'import numpy as np\n'), ((2967, 2991), 'numpy.random.uniform', 'np.random.uniform', (['(-4)', '(4)'], {}), '(-4, 4)\n', (2984, 2991), True, 'import numpy as np\n'), ((4992, 5005), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (5002, 5005), False, 'import time\n'), ((6275, 6299), 'numpy.load', 'np.load', (['arg.export_info'], {}), '(arg.export_info)\n', (6282, 6299), True, 'import numpy as np\n'), ((11074, 11084), 'matplotlib.pyplot.draw', 'plt.draw', ([], {}), '()\n', (11082, 11084), True, 'import matplotlib.pyplot as plt\n'), ((7322, 7355), 'os.path.splitext', 'os.path.splitext', (['arg.export_info'], {}), '(arg.export_info)\n', (7338, 7355), False, 'import os\n'), ((10777, 10792), 'time.sleep', 'time.sleep', (['(0.1)'], {}), '(0.1)\n', (10787, 10792), False, 'import time\n'), ((7365, 7376), 'time.time', 'time.time', ([], {}), '()\n', (7374, 7376), False, 'import time\n'), ((9677, 9693), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (9686, 9693), True, 'import matplotlib.pyplot as plt\n'), ((9706, 9729), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (9727, 9729), False, 'import cv2\n')]
|
#! /bin/env python
"""
Examples
--------
Create a grid of length 2 in the x direction, and 3 in the y direction.
>>> (x, y) = np.meshgrid ([1., 2., 4., 8.], [1., 2., 3.])
>>> g = Structured(y.flatten(), x.flatten(), [3, 4])
>>> g.get_point_count()
12
>>> g.get_cell_count()
6
>>> g.get_x()
array([ 1., 2., 4., 8., 1., 2., 4., 8., 1., 2., 4., 8.])
>>> g.get_y()
array([ 1., 1., 1., 1., 2., 2., 2., 2., 3., 3., 3., 3.])
>>> g.get_shape()
array([3, 4])
Create a grid of length 2 in the i direction, and 3 in the j direction.
>>> (x, y) = np.meshgrid ([1., 2., 4., 8.], [1., 2., 3.])
>>> g = Structured (y.flatten (), x.flatten (), (3, 4), indexing='ij')
>>> g.get_x()
array([ 1., 2., 4., 8., 1., 2., 4., 8., 1., 2., 4., 8.])
>>> g.get_y()
array([ 1., 1., 1., 1., 2., 2., 2., 2., 3., 3., 3., 3.])
>>> g.get_shape()
array([3, 4])
>>> g.get_offset()
array([ 4, 8, 12, 16, 20, 24])
>>> g.get_connectivity()
array([ 0, 1, 5, 4, 1, 2, 6, 5, 2, 3, 7, 6, 4, 5, 9, 8, 5,
6, 10, 9, 6, 7, 11, 10])
**Structured grid of points**
The same grid as the previous example but without any cells - just points.
>>> (x, y) = np.meshgrid ([1., 2., 4., 8.], [1., 2., 3.])
>>> g = StructuredPoints (y.flatten (), x.flatten (), (3, 4), indexing='ij', set_connectivity=True)
>>> g.get_x()
array([ 1., 2., 4., 8., 1., 2., 4., 8., 1., 2., 4., 8.])
>>> g.get_y()
array([ 1., 1., 1., 1., 2., 2., 2., 2., 3., 3., 3., 3.])
>>> g.get_shape()
array([3, 4])
The number of points are the same, but the number of cells is now 0.
>>> g.get_point_count()
12
>>> g.get_cell_count()
0
The offset runs from 1 up to (and including) the number of points.
>>> all (g.get_offset ()==np.arange (1, g.get_point_count ()+1))
True
The connectivity runs from 0 to one less than the number of points.
>>> all (g.get_connectivity ()==np.arange (g.get_point_count ()))
True
**1D Grid of line segments**
>>> g = Structured([-1, 2, 3, 6], (4, ))
>>> g.get_x()
array([-1., 2., 3., 6.])
>>> g.get_y()
Traceback (most recent call last):
...
IndexError: Dimension out of bounds
>>> g.get_shape()
array([4])
>>> g.get_offset()
array([2, 4, 6])
>>> g.get_connectivity()
array([0, 1, 1, 2, 2, 3])
**3D Grid of cubes**
>>> x = [0, 1, 0, 1, 0, 1, 0, 1]
>>> y = [0, 0, 1, 1, 0, 0, 1, 1]
>>> z = [0, 0, 0, 0, 1, 1, 1, 1]
>>> g = Structured(z, y, x, (2, 2, 2))
>>> g.get_x()
array([ 0., 1., 0., 1., 0., 1., 0., 1.])
>>> g.get_y()
array([ 0., 0., 1., 1., 0., 0., 1., 1.])
>>> g.get_z()
array([ 0., 0., 0., 0., 1., 1., 1., 1.])
>>> g.get_connectivity()
array([0, 1, 3, 2, 4, 5, 7, 6])
>>> g.get_offset()
array([8])
>>> g = Structured(x, y, z, (2, 2, 2), ordering='ccw')
>>> g.get_connectivity()
array([1, 0, 2, 3, 5, 4, 6, 7])
"""
import warnings
import numpy as np
from pymt.grids.connectivity import get_connectivity
from pymt.grids.utils import get_default_coordinate_names, get_default_coordinate_units
from .unstructured import Unstructured, UnstructuredPoints
class StructuredPoints(UnstructuredPoints):
def __init__(self, *args, **kwds):
"""StructuredPoints(x0 [, x1 [, x2]], shape)"""
(coordinates, shape) = (args[:-1], args[-1])
if len(coordinates) < 1 or len(coordinates) > 3:
raise ValueError("number of dimensions must be between 1 and 3")
kwds.setdefault("set_connectivity", True)
indexing = kwds.pop("indexing", "xy")
if indexing != "ij":
warnings.warn("only ij indexing is supported", RuntimeWarning)
indexing = "ij"
coordinate_names = kwds.pop(
"coordinate_names", get_default_coordinate_names(len(coordinates))
)
coordinate_units = kwds.pop(
"units", get_default_coordinate_units(len(coordinates))
)
self._shape = np.array(shape, dtype=int)
kwds["units"] = coordinate_units
kwds["coordinate_names"] = coordinate_names
super().__init__(*coordinates, **kwds)
def get_shape(self, remove_singleton=False):
"""The shape of the structured grid with the given indexing.
Use remove_singleton=False to include singleton dimensions.
"""
shape = self._shape.copy()
if remove_singleton:
shape = shape[shape > 1]
return shape
def get_coordinate_units(self, i):
return super().get_coordinate_units(i)
def get_coordinate_name(self, i):
return super().get_coordinate_name(i)
def get_coordinate(self, i):
return super().get_coordinate(i)
def get_point_coordinates(self, *args, **kwds):
return super().get_point_coordinates(*args, **kwds)
class Structured(StructuredPoints, Unstructured):
"""Create a structured rectilinear grid.
Parameters
----------
x: ndarray
1-D array of x-coordinates of nodes.
y: ndarray
1-D array of y-coordinates of nodes.
shape: tuple of int
Shape of the grid.
indexing: {'xy', 'ij'}, optional
Cartesian('xy', default) or matrix('ij') indexing of output.
Returns
-------
Structured
An instance of a Structured grid.
"""
def __init__(self, *args, **kwds):
kwds.setdefault("indexing", "xy")
kwds.setdefault("set_connectivity", True)
ordering = kwds.pop("ordering", "cw")
if ordering not in ["cw", "ccw"]:
raise TypeError("ordering not understood (valid choices are 'cw' or 'ccw')")
shape = args[-1]
if kwds["set_connectivity"]:
(c, o) = get_connectivity(shape, ordering=ordering, with_offsets=True)
self._set_connectivity(c, o)
kwds["set_connectivity"] = False
super().__init__(*args, **kwds)
if __name__ == "__main__":
import doctest
doctest.testmod(optionflags=doctest.NORMALIZE_WHITESPACE)
|
[
"warnings.warn",
"pymt.grids.connectivity.get_connectivity",
"numpy.array",
"doctest.testmod"
] |
[((5855, 5912), 'doctest.testmod', 'doctest.testmod', ([], {'optionflags': 'doctest.NORMALIZE_WHITESPACE'}), '(optionflags=doctest.NORMALIZE_WHITESPACE)\n', (5870, 5912), False, 'import doctest\n'), ((3872, 3898), 'numpy.array', 'np.array', (['shape'], {'dtype': 'int'}), '(shape, dtype=int)\n', (3880, 3898), True, 'import numpy as np\n'), ((3516, 3578), 'warnings.warn', 'warnings.warn', (['"""only ij indexing is supported"""', 'RuntimeWarning'], {}), "('only ij indexing is supported', RuntimeWarning)\n", (3529, 3578), False, 'import warnings\n'), ((5613, 5674), 'pymt.grids.connectivity.get_connectivity', 'get_connectivity', (['shape'], {'ordering': 'ordering', 'with_offsets': '(True)'}), '(shape, ordering=ordering, with_offsets=True)\n', (5629, 5674), False, 'from pymt.grids.connectivity import get_connectivity\n')]
|
# -*- coding: utf-8 -*-
""" Thresholds Functions
This file helps to calculate useful statistics to further choose thresholds
Created on Fri May 15 12:47:14 2020
Authors: <NAME> (<EMAIL>)
<NAME> (<EMAIL>)
"""
import numpy as np
import pandas as pd
from trackintel.geogr.distances import haversine_dist
# Local files
import help_functions as hlp
def stydiffstat(dataNameList, SELECT_RANGE, dateStart, dateEnd):
"""
Return the place name of input places
Parameters
----------
dataNameList : list - list of strings of all participant id with shared data
SELECT_RANGE: var - flag to define if select certain period
dateStart: str - the start date of the period if selecting certain period
dateEnd: str - the end date of the period if selecting certain period
Returns
-------
staythredstat: useful statistics to semi-automatically choose thresholds
"""
ddiff_max = []
ddiff_min = []
ddiff_mean = []
ddiff_median = []
ddiff_quar = []
tdiff_max = []
tdiff_min = []
tdiff_mean = []
tdiff_median = []
tdiff_quar = []
for dataName in dataNameList:
dataPathLocs,dataPathTrips = hlp.getDataPaths(dataName)
if SELECT_RANGE:
dataPathLocs,dataPathTrips = hlp.selectRange(dataPathLocs, dataPathTrips, dateStart, dateEnd)
locs, locsgdf = hlp.parseLocs(dataPathLocs)
locs['d_diff'] = np.append(haversine_dist(locs.longitudeE7[1:], locs.latitudeE7[1:], locs.longitudeE7[:-1], locs.latitudeE7[:-1]),0)
accuracy_threshold = np.quantile(locs['d_diff'], .95)
locs['t_diff'] = np.append((locs.index[1:]-locs.index[:-1]).total_seconds(),0)
maxi = max(locs['d_diff'])
ddiff_max.append(maxi)
mini = min(locs['d_diff'])
ddiff_min.append(mini)
meani = np.mean(locs['d_diff'])
ddiff_mean.append(meani)
mediani = np.median(locs['d_diff'])
ddiff_median.append(mediani)
quari = np.quantile(locs['d_diff'], .25)
ddiff_quar.append(quari)
maxi = max(locs['t_diff'])
tdiff_max.append(maxi)
mini = min(locs['t_diff'])
tdiff_min.append(mini)
meani = np.mean(locs['t_diff'])
tdiff_mean.append(meani)
mediani = np.median(locs['t_diff'])
tdiff_median.append(mediani)
quari = np.quantile(locs['t_diff'], .25)
tdiff_quar.append(quari)
ddiff_max = np.array(ddiff_max)
ddiff_max = np.transpose(ddiff_max)
ddiff_min = np.array(ddiff_min)
ddiff_min = np.transpose(ddiff_min)
ddiff_mean = np.array(ddiff_mean)
ddiff_mean = np.transpose(ddiff_mean)
ddiff_median = np.array(ddiff_median)
ddiff_median = np.transpose(ddiff_median)
ddiff_quar = np.array(ddiff_quar)
ddiff_quar = np.transpose(ddiff_quar)
tdiff_max = np.array(tdiff_max)
tdiff_max = np.transpose(tdiff_max)
tdiff_min = np.array(tdiff_min)
tdiff_min = np.transpose(tdiff_min)
tdiff_mean = np.array(tdiff_mean)
tdiff_mean = np.transpose(tdiff_mean)
tdiff_median = np.array(tdiff_median)
tdiff_median = np.transpose(tdiff_median)
tdiff_quar = np.array(tdiff_quar)
tdiff_quar = np.transpose(tdiff_quar)
thredstat = {'dataName': np.array(dataNameList),
'dist_max': ddiff_max,
'dist_min': ddiff_min,
'dist_range': ddiff_max-ddiff_min,
'dist_mean': ddiff_mean,
'dist_median': ddiff_median,
'dist_quarter': ddiff_quar,
'time_max': tdiff_max,
'time_min': tdiff_min,
'time_range': tdiff_max-tdiff_min,
'time_mean': tdiff_mean,
'time_median': tdiff_median,
'time_quarter': tdiff_quar}
staythredstat = pd.DataFrame(thredstat)
return staythredstat
|
[
"pandas.DataFrame",
"numpy.quantile",
"numpy.median",
"help_functions.getDataPaths",
"help_functions.selectRange",
"numpy.transpose",
"trackintel.geogr.distances.haversine_dist",
"numpy.mean",
"numpy.array",
"help_functions.parseLocs"
] |
[((2554, 2573), 'numpy.array', 'np.array', (['ddiff_max'], {}), '(ddiff_max)\n', (2562, 2573), True, 'import numpy as np\n'), ((2590, 2613), 'numpy.transpose', 'np.transpose', (['ddiff_max'], {}), '(ddiff_max)\n', (2602, 2613), True, 'import numpy as np\n'), ((2630, 2649), 'numpy.array', 'np.array', (['ddiff_min'], {}), '(ddiff_min)\n', (2638, 2649), True, 'import numpy as np\n'), ((2666, 2689), 'numpy.transpose', 'np.transpose', (['ddiff_min'], {}), '(ddiff_min)\n', (2678, 2689), True, 'import numpy as np\n'), ((2707, 2727), 'numpy.array', 'np.array', (['ddiff_mean'], {}), '(ddiff_mean)\n', (2715, 2727), True, 'import numpy as np\n'), ((2745, 2769), 'numpy.transpose', 'np.transpose', (['ddiff_mean'], {}), '(ddiff_mean)\n', (2757, 2769), True, 'import numpy as np\n'), ((2789, 2811), 'numpy.array', 'np.array', (['ddiff_median'], {}), '(ddiff_median)\n', (2797, 2811), True, 'import numpy as np\n'), ((2831, 2857), 'numpy.transpose', 'np.transpose', (['ddiff_median'], {}), '(ddiff_median)\n', (2843, 2857), True, 'import numpy as np\n'), ((2875, 2895), 'numpy.array', 'np.array', (['ddiff_quar'], {}), '(ddiff_quar)\n', (2883, 2895), True, 'import numpy as np\n'), ((2913, 2937), 'numpy.transpose', 'np.transpose', (['ddiff_quar'], {}), '(ddiff_quar)\n', (2925, 2937), True, 'import numpy as np\n'), ((2959, 2978), 'numpy.array', 'np.array', (['tdiff_max'], {}), '(tdiff_max)\n', (2967, 2978), True, 'import numpy as np\n'), ((2995, 3018), 'numpy.transpose', 'np.transpose', (['tdiff_max'], {}), '(tdiff_max)\n', (3007, 3018), True, 'import numpy as np\n'), ((3035, 3054), 'numpy.array', 'np.array', (['tdiff_min'], {}), '(tdiff_min)\n', (3043, 3054), True, 'import numpy as np\n'), ((3071, 3094), 'numpy.transpose', 'np.transpose', (['tdiff_min'], {}), '(tdiff_min)\n', (3083, 3094), True, 'import numpy as np\n'), ((3112, 3132), 'numpy.array', 'np.array', (['tdiff_mean'], {}), '(tdiff_mean)\n', (3120, 3132), True, 'import numpy as np\n'), ((3150, 3174), 'numpy.transpose', 'np.transpose', (['tdiff_mean'], {}), '(tdiff_mean)\n', (3162, 3174), True, 'import numpy as np\n'), ((3194, 3216), 'numpy.array', 'np.array', (['tdiff_median'], {}), '(tdiff_median)\n', (3202, 3216), True, 'import numpy as np\n'), ((3236, 3262), 'numpy.transpose', 'np.transpose', (['tdiff_median'], {}), '(tdiff_median)\n', (3248, 3262), True, 'import numpy as np\n'), ((3280, 3300), 'numpy.array', 'np.array', (['tdiff_quar'], {}), '(tdiff_quar)\n', (3288, 3300), True, 'import numpy as np\n'), ((3318, 3342), 'numpy.transpose', 'np.transpose', (['tdiff_quar'], {}), '(tdiff_quar)\n', (3330, 3342), True, 'import numpy as np\n'), ((3952, 3975), 'pandas.DataFrame', 'pd.DataFrame', (['thredstat'], {}), '(thredstat)\n', (3964, 3975), True, 'import pandas as pd\n'), ((1231, 1257), 'help_functions.getDataPaths', 'hlp.getDataPaths', (['dataName'], {}), '(dataName)\n', (1247, 1257), True, 'import help_functions as hlp\n'), ((1435, 1462), 'help_functions.parseLocs', 'hlp.parseLocs', (['dataPathLocs'], {}), '(dataPathLocs)\n', (1448, 1462), True, 'import help_functions as hlp\n'), ((1642, 1675), 'numpy.quantile', 'np.quantile', (["locs['d_diff']", '(0.95)'], {}), "(locs['d_diff'], 0.95)\n", (1653, 1675), True, 'import numpy as np\n'), ((1932, 1955), 'numpy.mean', 'np.mean', (["locs['d_diff']"], {}), "(locs['d_diff'])\n", (1939, 1955), True, 'import numpy as np\n'), ((2007, 2032), 'numpy.median', 'np.median', (["locs['d_diff']"], {}), "(locs['d_diff'])\n", (2016, 2032), True, 'import numpy as np\n'), ((2086, 2119), 'numpy.quantile', 'np.quantile', (["locs['d_diff']", '(0.25)'], {}), "(locs['d_diff'], 0.25)\n", (2097, 2119), True, 'import numpy as np\n'), ((2309, 2332), 'numpy.mean', 'np.mean', (["locs['t_diff']"], {}), "(locs['t_diff'])\n", (2316, 2332), True, 'import numpy as np\n'), ((2384, 2409), 'numpy.median', 'np.median', (["locs['t_diff']"], {}), "(locs['t_diff'])\n", (2393, 2409), True, 'import numpy as np\n'), ((2463, 2496), 'numpy.quantile', 'np.quantile', (["locs['t_diff']", '(0.25)'], {}), "(locs['t_diff'], 0.25)\n", (2474, 2496), True, 'import numpy as np\n'), ((3377, 3399), 'numpy.array', 'np.array', (['dataNameList'], {}), '(dataNameList)\n', (3385, 3399), True, 'import numpy as np\n'), ((1337, 1401), 'help_functions.selectRange', 'hlp.selectRange', (['dataPathLocs', 'dataPathTrips', 'dateStart', 'dateEnd'], {}), '(dataPathLocs, dataPathTrips, dateStart, dateEnd)\n', (1352, 1401), True, 'import help_functions as hlp\n'), ((1507, 1614), 'trackintel.geogr.distances.haversine_dist', 'haversine_dist', (['locs.longitudeE7[1:]', 'locs.latitudeE7[1:]', 'locs.longitudeE7[:-1]', 'locs.latitudeE7[:-1]'], {}), '(locs.longitudeE7[1:], locs.latitudeE7[1:], locs.longitudeE7[\n :-1], locs.latitudeE7[:-1])\n', (1521, 1614), False, 'from trackintel.geogr.distances import haversine_dist\n')]
|
# Copyright 2013 <NAME>
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from SimpleGP import GP
import numpy as np
class TestEval(object):
def __init__(self):
x = np.linspace(-10, 10, 100)
pol = np.array([0.2, -0.3, 0.2])
X = np.vstack((x**2, x, np.ones(x.shape[0])))
y = (X.T * pol).sum(axis=1)
x = x[:, np.newaxis]
self._gp = GP(fname_best=None).train(x, y)
self._gp.create_population()
self._cons = 1.2
self._gp._p_constants[0][0] = self._cons
self._nfunc = self._gp._nop.shape[0]
self._nvar = self._nfunc + self._gp._x.shape[1]
def test_sum(self):
self._gp._p[0] = np.array([0, self._nfunc, self._nvar], dtype=np.int)
y = self._gp._x.flatten() + self._cons
yh = self._gp.eval(0)
assert np.fabs(y - yh).sum() == 0
def test_subtract(self):
self._gp._p[0] = np.array([1, self._nfunc, self._nvar], dtype=np.int)
y = self._gp._x.flatten() - self._cons
yh = self._gp.eval(0)
assert np.fabs(y - yh).sum() == 0
def test_multiply(self):
self._gp._p[0] = np.array([2, self._nfunc, self._nvar], dtype=np.int)
y = self._gp._x.flatten() * self._cons
yh = self._gp.eval(0)
assert np.fabs(y - yh).sum() == 0
|
[
"SimpleGP.GP",
"numpy.ones",
"numpy.fabs",
"numpy.array",
"numpy.linspace"
] |
[((672, 697), 'numpy.linspace', 'np.linspace', (['(-10)', '(10)', '(100)'], {}), '(-10, 10, 100)\n', (683, 697), True, 'import numpy as np\n'), ((712, 738), 'numpy.array', 'np.array', (['[0.2, -0.3, 0.2]'], {}), '([0.2, -0.3, 0.2])\n', (720, 738), True, 'import numpy as np\n'), ((1171, 1223), 'numpy.array', 'np.array', (['[0, self._nfunc, self._nvar]'], {'dtype': 'np.int'}), '([0, self._nfunc, self._nvar], dtype=np.int)\n', (1179, 1223), True, 'import numpy as np\n'), ((1398, 1450), 'numpy.array', 'np.array', (['[1, self._nfunc, self._nvar]'], {'dtype': 'np.int'}), '([1, self._nfunc, self._nvar], dtype=np.int)\n', (1406, 1450), True, 'import numpy as np\n'), ((1625, 1677), 'numpy.array', 'np.array', (['[2, self._nfunc, self._nvar]'], {'dtype': 'np.int'}), '([2, self._nfunc, self._nvar], dtype=np.int)\n', (1633, 1677), True, 'import numpy as np\n'), ((771, 790), 'numpy.ones', 'np.ones', (['x.shape[0]'], {}), '(x.shape[0])\n', (778, 790), True, 'import numpy as np\n'), ((877, 896), 'SimpleGP.GP', 'GP', ([], {'fname_best': 'None'}), '(fname_best=None)\n', (879, 896), False, 'from SimpleGP import GP\n'), ((1316, 1331), 'numpy.fabs', 'np.fabs', (['(y - yh)'], {}), '(y - yh)\n', (1323, 1331), True, 'import numpy as np\n'), ((1543, 1558), 'numpy.fabs', 'np.fabs', (['(y - yh)'], {}), '(y - yh)\n', (1550, 1558), True, 'import numpy as np\n'), ((1770, 1785), 'numpy.fabs', 'np.fabs', (['(y - yh)'], {}), '(y - yh)\n', (1777, 1785), True, 'import numpy as np\n')]
|
import motionTools
import numpy as np
import os
print("Loading Simulator Motion Files")
simMotion_1 = np.genfromtxt("data/MotionCondition_1.csv", delimiter = ",", skip_header = 1)
simMotion_2 = np.genfromtxt("data/MotionCondition_2.csv", delimiter = ",", skip_header = 1)
# Changing time to seconds instead of DUECA time
simMotion_1[:,0] = (simMotion_1[:,0] - simMotion_1[0,0]) * 0.0001
simMotion_2[:,0] = (simMotion_2[:,0] - simMotion_2[0,0]) * 0.0001
print("Loading Head Motion Files")
headMotions_1 = []
headMotions_2 = []
for filename in os.listdir("filtered_data"):
#if "MC1" in filename:
#headMotions_1.append(np.genfromtxt("filtered_data/" + filename, delimiter = ","))
#print(filename)
if "MC1" in filename:
if "01" in filename:
headMotions_1.append(np.genfromtxt("filtered_data/" + filename, delimiter = ","))
print(filename)
headMotionSystems = []
print("Initializing all experiments")
max_rotation = 0
for i, headMotion in enumerate(headMotions_1):
headMotion[:,0] = (headMotion[:,0] - headMotion[0,0]) * 0.0001
# Synchronising
# It was found the subjects 3 to 10 had to be synchronized by changing the time by 0.02s
if (i >= 2 and i <= 9):
headMotion[:,0] += 0.02
# Initializes model
headMotionSystems.append(motionTools.headMotionSystem(simMotion_1, headMotion, (i + 1, 1), [[0.75,4.0,0.0]] * 6))
for i, headMotion in enumerate(headMotions_2):
headMotion[:,0] = (headMotion[:,0] - headMotion[0,0]) * 0.0001
# Synchronising
if ((i >= 1 and i <= 4) or i in [8, 10]):
headMotion[:,0] += 0.02
# Initializes model
headMotionSystems.append(motionTools.headMotionSystem(simMotion_2, headMotion, (i + 1, 2), [[1.0,3.0,-0.55]] * 6))
print("Solving all experiments")
for i, system in enumerate(headMotionSystems):
print("solving:", i)
system.solve()
|
[
"os.listdir",
"motionTools.headMotionSystem",
"numpy.genfromtxt"
] |
[((108, 181), 'numpy.genfromtxt', 'np.genfromtxt', (['"""data/MotionCondition_1.csv"""'], {'delimiter': '""","""', 'skip_header': '(1)'}), "('data/MotionCondition_1.csv', delimiter=',', skip_header=1)\n", (121, 181), True, 'import numpy as np\n'), ((201, 274), 'numpy.genfromtxt', 'np.genfromtxt', (['"""data/MotionCondition_2.csv"""'], {'delimiter': '""","""', 'skip_header': '(1)'}), "('data/MotionCondition_2.csv', delimiter=',', skip_header=1)\n", (214, 274), True, 'import numpy as np\n'), ((564, 591), 'os.listdir', 'os.listdir', (['"""filtered_data"""'], {}), "('filtered_data')\n", (574, 591), False, 'import os\n'), ((1359, 1453), 'motionTools.headMotionSystem', 'motionTools.headMotionSystem', (['simMotion_1', 'headMotion', '(i + 1, 1)', '([[0.75, 4.0, 0.0]] * 6)'], {}), '(simMotion_1, headMotion, (i + 1, 1), [[0.75, \n 4.0, 0.0]] * 6)\n', (1387, 1453), False, 'import motionTools\n'), ((1722, 1817), 'motionTools.headMotionSystem', 'motionTools.headMotionSystem', (['simMotion_2', 'headMotion', '(i + 1, 2)', '([[1.0, 3.0, -0.55]] * 6)'], {}), '(simMotion_2, headMotion, (i + 1, 2), [[1.0, \n 3.0, -0.55]] * 6)\n', (1750, 1817), False, 'import motionTools\n'), ((832, 889), 'numpy.genfromtxt', 'np.genfromtxt', (["('filtered_data/' + filename)"], {'delimiter': '""","""'}), "('filtered_data/' + filename, delimiter=',')\n", (845, 889), True, 'import numpy as np\n')]
|
try:
from plotting import hd_hist
except ImportError:
from utilities.plotting import hd_hist
from sklearn.externals import joblib
import numpy as np
etbins = np.linspace(20.0, 400.0, num=100)
etabins = np.linspace(-4.0, 4.0, num=100)
mbins = np.linspace(0.0, 200.0, num=100)
ktbins = np.linspace(0.0, 100000.0, num=100)
sig_data = joblib.load('../data/signal_data_gpd.p')
bkg_data = joblib.load('../data/background_data_gpd.p')
sig_data = sig_data[:2000]
bkg_data = bkg_data[:2000]
sig_eta = [e[0] for e in sig_data]
sig_et = [e[1] for e in sig_data]
sig_m = [e[2] for e in sig_data]
sig_kt = [e[3] for e in sig_data]
bkg_eta = [e[0] for e in bkg_data]
bkg_et = [e[1] for e in bkg_data]
bkg_m = [e[2] for e in bkg_data]
bkg_kt = [e[3] for e in bkg_data]
hd_hist([sig_et, bkg_et], 'plots_gpd/et_comp_gpd.pdf'
, [20.0, 400.0], [0.0, 600.0]
, "$E_{T}$ GeV", "Events", etbins
, ['signal', 'background'])
hd_hist([sig_eta, bkg_eta], 'plots_gpd/eta_comp_gpd.pdf'
, [-4.0, 4.0], [0.0, 100.0]
, "$\eta$", "Events", etabins
, ['signal', 'background'])
hd_hist([sig_m, bkg_m], 'plots_gpd/m_comp_gpd.pdf'
, [0.0, 100.0], [0.0, 600.0]
, "Mass [GeV]", "Events", mbins
, ['signal', 'background'])
hd_hist([sig_kt, bkg_kt], 'plots_gpd/kt_comp_gpd.pdf'
, [0.0, 100000.0], [0.0, 1000.0]
, "$K_{T}$", "Events", ktbins
, ['signal', 'background'])
|
[
"utilities.plotting.hd_hist",
"numpy.linspace",
"sklearn.externals.joblib.load"
] |
[((167, 200), 'numpy.linspace', 'np.linspace', (['(20.0)', '(400.0)'], {'num': '(100)'}), '(20.0, 400.0, num=100)\n', (178, 200), True, 'import numpy as np\n'), ((211, 242), 'numpy.linspace', 'np.linspace', (['(-4.0)', '(4.0)'], {'num': '(100)'}), '(-4.0, 4.0, num=100)\n', (222, 242), True, 'import numpy as np\n'), ((251, 283), 'numpy.linspace', 'np.linspace', (['(0.0)', '(200.0)'], {'num': '(100)'}), '(0.0, 200.0, num=100)\n', (262, 283), True, 'import numpy as np\n'), ((293, 328), 'numpy.linspace', 'np.linspace', (['(0.0)', '(100000.0)'], {'num': '(100)'}), '(0.0, 100000.0, num=100)\n', (304, 328), True, 'import numpy as np\n'), ((341, 381), 'sklearn.externals.joblib.load', 'joblib.load', (['"""../data/signal_data_gpd.p"""'], {}), "('../data/signal_data_gpd.p')\n", (352, 381), False, 'from sklearn.externals import joblib\n'), ((393, 437), 'sklearn.externals.joblib.load', 'joblib.load', (['"""../data/background_data_gpd.p"""'], {}), "('../data/background_data_gpd.p')\n", (404, 437), False, 'from sklearn.externals import joblib\n'), ((766, 912), 'utilities.plotting.hd_hist', 'hd_hist', (['[sig_et, bkg_et]', '"""plots_gpd/et_comp_gpd.pdf"""', '[20.0, 400.0]', '[0.0, 600.0]', '"""$E_{T}$ GeV"""', '"""Events"""', 'etbins', "['signal', 'background']"], {}), "([sig_et, bkg_et], 'plots_gpd/et_comp_gpd.pdf', [20.0, 400.0], [0.0,\n 600.0], '$E_{T}$ GeV', 'Events', etbins, ['signal', 'background'])\n", (773, 912), False, 'from utilities.plotting import hd_hist\n'), ((937, 1081), 'utilities.plotting.hd_hist', 'hd_hist', (['[sig_eta, bkg_eta]', '"""plots_gpd/eta_comp_gpd.pdf"""', '[-4.0, 4.0]', '[0.0, 100.0]', '"""$\\\\eta$"""', '"""Events"""', 'etabins', "['signal', 'background']"], {}), "([sig_eta, bkg_eta], 'plots_gpd/eta_comp_gpd.pdf', [-4.0, 4.0], [0.0,\n 100.0], '$\\\\eta$', 'Events', etabins, ['signal', 'background'])\n", (944, 1081), False, 'from utilities.plotting import hd_hist\n'), ((1105, 1246), 'utilities.plotting.hd_hist', 'hd_hist', (['[sig_m, bkg_m]', '"""plots_gpd/m_comp_gpd.pdf"""', '[0.0, 100.0]', '[0.0, 600.0]', '"""Mass [GeV]"""', '"""Events"""', 'mbins', "['signal', 'background']"], {}), "([sig_m, bkg_m], 'plots_gpd/m_comp_gpd.pdf', [0.0, 100.0], [0.0, \n 600.0], 'Mass [GeV]', 'Events', mbins, ['signal', 'background'])\n", (1112, 1246), False, 'from utilities.plotting import hd_hist\n'), ((1270, 1416), 'utilities.plotting.hd_hist', 'hd_hist', (['[sig_kt, bkg_kt]', '"""plots_gpd/kt_comp_gpd.pdf"""', '[0.0, 100000.0]', '[0.0, 1000.0]', '"""$K_{T}$"""', '"""Events"""', 'ktbins', "['signal', 'background']"], {}), "([sig_kt, bkg_kt], 'plots_gpd/kt_comp_gpd.pdf', [0.0, 100000.0], [\n 0.0, 1000.0], '$K_{T}$', 'Events', ktbins, ['signal', 'background'])\n", (1277, 1416), False, 'from utilities.plotting import hd_hist\n')]
|
from sklearn.model_selection import train_test_split
import numpy as np
import matplotlib.pyplot as plt
def sigmoid(x):
return 1.0/(1 + np.exp(-x))
def sigmoid_derivative(x):
return x * (1.0 - x)
class NeuralNetwork:
def __init__(self, x, y, epoch, typeofweightinitialise = "random"):
self.input = x
if(typeofweightinitialise=='random'):
self.weights1 = np.random.rand(self.input.shape[1], 4)
self.weights2 = np.random.rand(4, 1)
elif(typeofweightinitialise=='ones'):
self.weights1 = np.ones((trainsamples.shape[1], 4))
self.weights2 = np.ones((4, 1))
elif(typeofweightinitialise=='zeros'):
self.weights1 = np.zeros((trainsamples.shape[1], 4))
self.weights2 = np.zeros((4, 1))
self.typeofweightinitialise = typeofweightinitialise
self.y = y
self.output = np.zeros(self.y.shape)
self.epoch=epoch
self.losslist = []
def feedforward(self, inputvalue):
self.layer1 = sigmoid(np.dot(inputvalue, self.weights1))
self.output = sigmoid(np.dot(self.layer1, self.weights2))
def backprop(self):
# application of the chain rule to find derivative of the loss function with respect to weights2 and weights1
d_weights2 = np.dot(
self.layer1.T, (2*(self.y - self.output) * sigmoid_derivative(self.output)))
d_weights1 = np.dot(self.input.T, (np.dot(2*(self.y - self.output) * sigmoid_derivative(
self.output), self.weights2.T) * sigmoid_derivative(self.layer1)))
# update the weights with the derivative (slope) of the loss function
self.weights1 += d_weights1
self.weights2 += d_weights2
def train(self,showgraph=True):
for i in range(self.epoch):
nn.feedforward(self.input)
nn.backprop()
self.losslist.append(self.calculateLoss())
if(showgraph):
plt.plot(range(self.epoch), self.losslist , c="red", label="Loss")
plt.legend()
plt.title("Initialisation of weights is : {}".format(self.typeofweightinitialise))
plt.show()
def calculateLoss(self):
loss = 0
for i in range(len(self.input)):
nn.feedforward(self.input[i])
loss += (nn.output - self.y[i])**2
print('Loss is ', loss)
return loss
def accuracy(self, pred, true):
c = 0
for i in range(true.shape[0]):
if(pred[i] == true[i]):
c += 1
return c
def calculateAccuracy(self, predictedout, actualout):
acc = self.accuracy(np.round(predictedout), actualout)
acc = acc/actualout.shape[0]
return acc
def test(self, testx, testy):
self.feedforward(testx)
print(self.calculateAccuracy(self.output, testy))
if __name__ == "__main__":
def create_data(samplesize, mu1, cov1, mu2, cov2):
class_zeros = np.random.multivariate_normal(mu1, cov1, samplesize)
class_ones = np.random.multivariate_normal(mu2, cov2, samplesize)
return class_zeros, class_ones
# Creating Data...........................
samplesize = 50
mu1 = np.array([2, 3])
mu2 = np.array([0, 0])
cov1 = np.array([[10, 0.01], [0.01, 10]])
cov2 = np.array([[1, 0], [0, 3]])
class0y = np.zeros(samplesize)
class1y = np.ones(samplesize)
class_zeros, class_ones = create_data(samplesize, mu1, cov1, mu2, cov2)
plt.scatter(class_zeros.T[0], class_zeros.T[1], c="orange", label="Class0")
plt.scatter(class_ones.T[0], class_ones.T[1], c="blue", label="Class1")
plt.legend()
plt.show()
# Splitting data into train and test............................
# and randomizing
class0trainsample, class0testsample, class0ytrain, class0ytest = train_test_split(
class_zeros, class0y, test_size=0.2, random_state=0)
class1trainsample, class1testsample, class1ytrain, class1ytest, = train_test_split(
class_ones, class1y, test_size=0.2, random_state=0)
trainsamples = np.concatenate((class0trainsample, class1trainsample))
trainyclassification = np.concatenate((class0ytrain, class1ytrain))
testsamples = np.concatenate((class0testsample, class1testsample))
testyclassification = np.concatenate((class0ytest, class1ytest))
train_data = list(zip(trainsamples, trainyclassification))
np.random.shuffle(train_data)
trainsamples, trainyclassification = zip(*train_data)
test_data = list(zip(testsamples, testyclassification))
np.random.shuffle(test_data)
testsamples, testyclassification = zip(*test_data)
trainsamples = np.array(trainsamples)
trainyclassification = np.c_[trainyclassification].T
testsamples = np.array(testsamples)
testyclassification = np.c_[testyclassification].T
ones = np.ones((trainsamples.shape[0],trainsamples.shape[1]+1))
ones[:,:-1] = trainsamples
trainsamples = ones
ones = np.ones((testsamples.shape[0],testsamples.shape[1]+1))
ones[:,:-1] = testsamples
testsamples = ones
epoch = 500
### All weights are zero
nn = NeuralNetwork(trainsamples, trainyclassification, epoch,'zeros')
nn.train()
nn.test( testsamples, testyclassification)
nn.test( trainsamples,trainyclassification)
### All weights are ones
nn = NeuralNetwork(trainsamples, trainyclassification, epoch,'ones')
nn.train()
nn.test( testsamples, testyclassification)
nn.test( trainsamples,trainyclassification)
### Random Weights
nn = NeuralNetwork(trainsamples, trainyclassification, epoch)
nn.train()
nn.test( testsamples, testyclassification)
nn.test( trainsamples,trainyclassification)
|
[
"matplotlib.pyplot.show",
"numpy.random.shuffle",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.legend",
"sklearn.model_selection.train_test_split",
"numpy.zeros",
"numpy.ones",
"numpy.array",
"numpy.random.multivariate_normal",
"numpy.exp",
"numpy.random.rand",
"numpy.dot",
"numpy.round",
"numpy.concatenate"
] |
[((3232, 3248), 'numpy.array', 'np.array', (['[2, 3]'], {}), '([2, 3])\n', (3240, 3248), True, 'import numpy as np\n'), ((3259, 3275), 'numpy.array', 'np.array', (['[0, 0]'], {}), '([0, 0])\n', (3267, 3275), True, 'import numpy as np\n'), ((3287, 3321), 'numpy.array', 'np.array', (['[[10, 0.01], [0.01, 10]]'], {}), '([[10, 0.01], [0.01, 10]])\n', (3295, 3321), True, 'import numpy as np\n'), ((3333, 3359), 'numpy.array', 'np.array', (['[[1, 0], [0, 3]]'], {}), '([[1, 0], [0, 3]])\n', (3341, 3359), True, 'import numpy as np\n'), ((3379, 3399), 'numpy.zeros', 'np.zeros', (['samplesize'], {}), '(samplesize)\n', (3387, 3399), True, 'import numpy as np\n'), ((3414, 3433), 'numpy.ones', 'np.ones', (['samplesize'], {}), '(samplesize)\n', (3421, 3433), True, 'import numpy as np\n'), ((3514, 3589), 'matplotlib.pyplot.scatter', 'plt.scatter', (['class_zeros.T[0]', 'class_zeros.T[1]'], {'c': '"""orange"""', 'label': '"""Class0"""'}), "(class_zeros.T[0], class_zeros.T[1], c='orange', label='Class0')\n", (3525, 3589), True, 'import matplotlib.pyplot as plt\n'), ((3594, 3665), 'matplotlib.pyplot.scatter', 'plt.scatter', (['class_ones.T[0]', 'class_ones.T[1]'], {'c': '"""blue"""', 'label': '"""Class1"""'}), "(class_ones.T[0], class_ones.T[1], c='blue', label='Class1')\n", (3605, 3665), True, 'import matplotlib.pyplot as plt\n'), ((3670, 3682), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (3680, 3682), True, 'import matplotlib.pyplot as plt\n'), ((3687, 3697), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3695, 3697), True, 'import matplotlib.pyplot as plt\n'), ((3859, 3928), 'sklearn.model_selection.train_test_split', 'train_test_split', (['class_zeros', 'class0y'], {'test_size': '(0.2)', 'random_state': '(0)'}), '(class_zeros, class0y, test_size=0.2, random_state=0)\n', (3875, 3928), False, 'from sklearn.model_selection import train_test_split\n'), ((4008, 4076), 'sklearn.model_selection.train_test_split', 'train_test_split', (['class_ones', 'class1y'], {'test_size': '(0.2)', 'random_state': '(0)'}), '(class_ones, class1y, test_size=0.2, random_state=0)\n', (4024, 4076), False, 'from sklearn.model_selection import train_test_split\n'), ((4106, 4160), 'numpy.concatenate', 'np.concatenate', (['(class0trainsample, class1trainsample)'], {}), '((class0trainsample, class1trainsample))\n', (4120, 4160), True, 'import numpy as np\n'), ((4188, 4232), 'numpy.concatenate', 'np.concatenate', (['(class0ytrain, class1ytrain)'], {}), '((class0ytrain, class1ytrain))\n', (4202, 4232), True, 'import numpy as np\n'), ((4251, 4303), 'numpy.concatenate', 'np.concatenate', (['(class0testsample, class1testsample)'], {}), '((class0testsample, class1testsample))\n', (4265, 4303), True, 'import numpy as np\n'), ((4330, 4372), 'numpy.concatenate', 'np.concatenate', (['(class0ytest, class1ytest)'], {}), '((class0ytest, class1ytest))\n', (4344, 4372), True, 'import numpy as np\n'), ((4440, 4469), 'numpy.random.shuffle', 'np.random.shuffle', (['train_data'], {}), '(train_data)\n', (4457, 4469), True, 'import numpy as np\n'), ((4592, 4620), 'numpy.random.shuffle', 'np.random.shuffle', (['test_data'], {}), '(test_data)\n', (4609, 4620), True, 'import numpy as np\n'), ((4696, 4718), 'numpy.array', 'np.array', (['trainsamples'], {}), '(trainsamples)\n', (4704, 4718), True, 'import numpy as np\n'), ((4794, 4815), 'numpy.array', 'np.array', (['testsamples'], {}), '(testsamples)\n', (4802, 4815), True, 'import numpy as np\n'), ((4887, 4946), 'numpy.ones', 'np.ones', (['(trainsamples.shape[0], trainsamples.shape[1] + 1)'], {}), '((trainsamples.shape[0], trainsamples.shape[1] + 1))\n', (4894, 4946), True, 'import numpy as np\n'), ((5011, 5068), 'numpy.ones', 'np.ones', (['(testsamples.shape[0], testsamples.shape[1] + 1)'], {}), '((testsamples.shape[0], testsamples.shape[1] + 1))\n', (5018, 5068), True, 'import numpy as np\n'), ((901, 923), 'numpy.zeros', 'np.zeros', (['self.y.shape'], {}), '(self.y.shape)\n', (909, 923), True, 'import numpy as np\n'), ((2988, 3040), 'numpy.random.multivariate_normal', 'np.random.multivariate_normal', (['mu1', 'cov1', 'samplesize'], {}), '(mu1, cov1, samplesize)\n', (3017, 3040), True, 'import numpy as np\n'), ((3062, 3114), 'numpy.random.multivariate_normal', 'np.random.multivariate_normal', (['mu2', 'cov2', 'samplesize'], {}), '(mu2, cov2, samplesize)\n', (3091, 3114), True, 'import numpy as np\n'), ((142, 152), 'numpy.exp', 'np.exp', (['(-x)'], {}), '(-x)\n', (148, 152), True, 'import numpy as np\n'), ((400, 438), 'numpy.random.rand', 'np.random.rand', (['self.input.shape[1]', '(4)'], {}), '(self.input.shape[1], 4)\n', (414, 438), True, 'import numpy as np\n'), ((467, 487), 'numpy.random.rand', 'np.random.rand', (['(4)', '(1)'], {}), '(4, 1)\n', (481, 487), True, 'import numpy as np\n'), ((1045, 1078), 'numpy.dot', 'np.dot', (['inputvalue', 'self.weights1'], {}), '(inputvalue, self.weights1)\n', (1051, 1078), True, 'import numpy as np\n'), ((1110, 1144), 'numpy.dot', 'np.dot', (['self.layer1', 'self.weights2'], {}), '(self.layer1, self.weights2)\n', (1116, 1144), True, 'import numpy as np\n'), ((2052, 2064), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (2062, 2064), True, 'import matplotlib.pyplot as plt\n'), ((2172, 2182), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2180, 2182), True, 'import matplotlib.pyplot as plt\n'), ((2666, 2688), 'numpy.round', 'np.round', (['predictedout'], {}), '(predictedout)\n', (2674, 2688), True, 'import numpy as np\n'), ((562, 597), 'numpy.ones', 'np.ones', (['(trainsamples.shape[1], 4)'], {}), '((trainsamples.shape[1], 4))\n', (569, 597), True, 'import numpy as np\n'), ((626, 641), 'numpy.ones', 'np.ones', (['(4, 1)'], {}), '((4, 1))\n', (633, 641), True, 'import numpy as np\n'), ((717, 753), 'numpy.zeros', 'np.zeros', (['(trainsamples.shape[1], 4)'], {}), '((trainsamples.shape[1], 4))\n', (725, 753), True, 'import numpy as np\n'), ((782, 798), 'numpy.zeros', 'np.zeros', (['(4, 1)'], {}), '((4, 1))\n', (790, 798), True, 'import numpy as np\n')]
|
# -*- coding: utf-8 -*-
"""ahp.utils
This module contains the common functions and methods used by other modules in the class.
"""
import numpy as np
def normalize_priorities(criteria_pr, global_pr):
"""Normalize the priorities received from the lower layer.
This function performs a Global Prioritization at the current node.
Args:
criteria_pr (list(list(float))): The priorities of all the alternatives/sub-criteria.
global_pr (list(float)): The global priorities of all criteria.
Returns:
Normalized priorities
"""
return np.dot(global_pr, criteria_pr)
|
[
"numpy.dot"
] |
[((584, 614), 'numpy.dot', 'np.dot', (['global_pr', 'criteria_pr'], {}), '(global_pr, criteria_pr)\n', (590, 614), True, 'import numpy as np\n')]
|
"""
Custom preprocessing transformation functions for video/sequential frame
MRI data from the UK Biobank
"""
import numpy as np
from skimage.exposure import rescale_intensity
from torchvision.transforms import Lambda
class NullTransform(Lambda):
"""
Create a null transformation.
This is to be used when a given augmentation is not selected in the config
so that it simply returns the input.
"""
def __init__(self):
"""
Instantiate lambda x: x.
Params
------
None
"""
super(NullTransform, self).__init__(lambda x: x)
class FrameSelectionStd(object):
"""
Select subset of MRI frames based on pixel variance
Assumes NUM_FRAMES X WIDTH X HEIGHT tensors
TODO: Setup for 3 channel images
"""
def __init__(self, n_frames=15, channel=1, epsilon=0.05):
"""
:param n_frames:
:param channel:
:param epsilon:
"""
self.n_frames = n_frames
self.channel = channel
self.epsilon = epsilon
def std_by_frame(self, seq, normalize=True):
"""
Compute standard deviation by frame
:param seq:
:param normalize:
:return:
"""
# z-score transform frames
z = (seq - np.mean(seq)) / np.std(seq) if normalize else seq
# standard deviation per frame
std = [np.std(z[i]) for i in range(seq.shape[0])]
return [v - min(std) for v in std]
def select_frames(self, seq, epsilon=0.05):
"""
Select a contiguous subset of frames based on each frame's
overall pixel standard deviation. Determine cut points based
on the first set of inflection points.
P2
/\
/ \
__/ \__/\____
P1 P3
:param seq:
:param epsilon:
:return:
"""
std = self.std_by_frame(seq)
# threshold SD
std = [v if v > epsilon else 0 for v in std]
# find inflection points
signs = [np.sign(std[i + 1] - std[i]) for i in range(len(std) - 1)]
# skip if first point is no slope or negative
inf_pnts = [] if signs[0] <= 0 else [0]
for i in range(1, len(signs)):
if signs[i] != signs[i - 1]:
inf_pnts.append(i)
if len(inf_pnts) < 3:
raise ValueError("No inflection points found")
return (inf_pnts[0], inf_pnts[2])
def __call__(self, sample):
# x,y = sample
# i,j = self.select_frames(x, self.epsilon)
if (self.n_frames == 30):
return sample
i, j = self.select_frames(sample, self.epsilon)
j = i + self.n_frames
# return (x[i:j,...], y)
return sample[i:j,...]
class FrameSelectionVar():
"""
Frame selector class.
Select the N best frames from a series to use for classification.
In this case, the N best frames are the "brightest" sequential frames. The
frames with the most variance between dark and light pixels, centered
around the brightest frame (frame with most variance). Nowing how the
frames are structured (with a lot of noise), we konw that the best frames
are where the noise dies down and the consentration is on the aortic valve.
Therefore, with pixel intensities around the valve going up and intensities
away from the valve go down, we get our largest variance in pixels with
these frames.
"""
def __init__(self, n_frames=6):
"""
Class initialization function.
Params
------
None
"""
self.N = n_frames
def __call__(self, seq):
"""
Select the BEST frames from the given series.
Params
------
npy_series : np.array
- numpy array of the series of DICOM images.
Return
------
list
- list of the most best (sequential) frames
"""
if (self.N == seq.shape[0]):
return seq
# Otherwise find correct frames to output
var = [fr.var() for fr in seq]
varDict = dict((i, fr.var()) for i, fr in enumerate(seq))
frameIndx = [np.argmax(var)]
low_, high_ = frameIndx[-1]-1, frameIndx[-1]+1
if (self.N > 1):
for i in range(self.N-1):
if (low_ >= 0 and high_ <= len(seq)-1):
if (varDict[low_] > varDict[high_]):
frameIndx.append(low_)
low_ = sorted(frameIndx)[0] - 1
high_ = sorted(frameIndx)[-1] + 1
else:
frameIndx.append(high_)
low_ = sorted(frameIndx)[0] - 1
high_ = sorted(frameIndx)[-1] + 1
elif (low_ == -1):
frameIndx.append(high_)
low_ = sorted(frameIndx)[0] - 1
high_ = sorted(frameIndx)[-1] + 1
else:
frameIndx.append(low_)
low_ = sorted(frameIndx)[0] - 1
high_ = sorted(frameIndx)[-1] + 1
return seq[sorted(frameIndx)]
class RescaleIntensity():
"""Rescale pixel values of a DICOM Series so that they span low-high."""
def __init__(self, out_range=(0.0,255.0)):
"""
Class initialization function.
Params
------
None
"""
self.out_range = out_range
def __call__(self, series):
"""
Execute normalization for the given series.
Params
------
seris : np.array
- DICOM Series as an np.array
Return
------
np.array
- new normalized series
"""
return np.array(
[rescale_intensity(1.0*frame, out_range=self.out_range) for frame in series])
class GammaCorrection():
"""Enhance Gray Scale Levels of a DICOM Series frame."""
def __init__(self, gamma=2.0, intensity=255.0):
"""
Class initialization function.
Params
------
gamma : float
- gamma correction amount
"""
assert isinstance(gamma, (int, float))
self.gamma = gamma
self.intensity = intensity
def __call__(self, series):
"""
Execute gamma correction for the entire series.
Params
------
series : np.array
- DICOM Series of images as an np.array
Return
------
np.array
- new gamma corrected series
"""
return np.array([self.intensity*(1.0*frame/frame.max())**self.gamma for frame in series])
class StdNormalize(object):
"""Standard Deviation Normalization mu = 0, std = 1.0."""
def __call__(self, series):
"""
Execute std normalization for each individual image in the series.
Params
------
series : np.array
- series of images
Return
------
stdNorm series
- standard normalized series
"""
stdSeries = []
for img in series:
stdSeries.append((img - img.mean())/img.std())
return np.array(stdSeries)
|
[
"numpy.argmax",
"numpy.std",
"skimage.exposure.rescale_intensity",
"numpy.mean",
"numpy.array",
"numpy.sign"
] |
[((7264, 7283), 'numpy.array', 'np.array', (['stdSeries'], {}), '(stdSeries)\n', (7272, 7283), True, 'import numpy as np\n'), ((1393, 1405), 'numpy.std', 'np.std', (['z[i]'], {}), '(z[i])\n', (1399, 1405), True, 'import numpy as np\n'), ((2050, 2078), 'numpy.sign', 'np.sign', (['(std[i + 1] - std[i])'], {}), '(std[i + 1] - std[i])\n', (2057, 2078), True, 'import numpy as np\n'), ((4214, 4228), 'numpy.argmax', 'np.argmax', (['var'], {}), '(var)\n', (4223, 4228), True, 'import numpy as np\n'), ((1305, 1316), 'numpy.std', 'np.std', (['seq'], {}), '(seq)\n', (1311, 1316), True, 'import numpy as np\n'), ((5833, 5889), 'skimage.exposure.rescale_intensity', 'rescale_intensity', (['(1.0 * frame)'], {'out_range': 'self.out_range'}), '(1.0 * frame, out_range=self.out_range)\n', (5850, 5889), False, 'from skimage.exposure import rescale_intensity\n'), ((1289, 1301), 'numpy.mean', 'np.mean', (['seq'], {}), '(seq)\n', (1296, 1301), True, 'import numpy as np\n')]
|
# Copyright <NAME> S.A. 2019
import numpy as np
import cv2
from shapely.geometry import Point, Polygon
from shapely.ops import cascaded_union
from sklearn.cluster import KMeans, DBSCAN
from .Config import OCRConfig
from .utils import DebugUtils, sort_box
class TextBinarizer:
def __init__(self, config=None):
if config is None:
config = OCRConfig()
self.config = config
self.debugger = DebugUtils()
self.debugger.set_debug(self.config.debug)
self.do_visualisation = self.config.debug
if (256 % config.binarization_rgb_bin_size) != 0:
raise Exception("RGB bin size should divide 256 into an integer number of bins. Given: {}".
format(config.binarization_rgb_bin_size))
self.dbscan_eps = config.binarization_dbscan_eps
self.rgb_bin_size = config.binarization_rgb_bin_size
self.dbscan_min_sample_frac = config.binarization_dbscan_min_sample_frac
self.roi_x_padding = config.binarization_roi_x_padding
self.roi_y_padding = config.binarization_roi_y_padding
def binarize(self, image, detections):
self.debugger.log("binarize: ", len(detections))
h, w = image.shape[:2]
scale = np.sqrt(750*750/(h*w))
self.debugger.log("--> scale: ", w, h, scale)
if scale > 1:
scale = 1
else:
image = cv2.resize(image, None, fx=scale, fy=scale)
h, w = image.shape[:2]
binarized = np.ones((h, w), np.uint8) * 255
refined_text_boxes = []
self.do_visualisation = self.config.debug
for _, box, confidence in detections:
if scale < 1:
box = (box.astype("float") * scale).astype("int")
_x, _y, _w, _h = cv2.boundingRect(box)
_x -= int(_w*self.roi_x_padding)
_w = int(_w*(1 + 2*self.roi_x_padding))
_y -= int(_h*self.roi_y_padding)
_h = int(_h*(1 + 2*self.roi_y_padding))
if _x < 0:
_x = 0
if _x+_w > w:
_w = w - _x
if _y < 0:
_y = 0
if _y+_h > h:
_h = h - _y
if _w <= 0 or _h <= 0:
continue
roi = image[_y:_y+_h, _x:_x+_w]
binary_roi, text_box = self._binarize_roi(box.astype("int") - [_x, _y], roi)
if text_box is not None:
binarized[_y:_y+_h, _x:_x+_w] = np.bitwise_and(binarized[_y:_y+_h, _x:_x+_w], binary_roi)
refined_text_boxes += [text_box+(_x, _y)]
refined_text_boxes = self.refine_text_boxes(refined_text_boxes)
if scale < 1:
refined_text_boxes = (np.array(refined_text_boxes).astype("float") / scale).astype("int")
binarized = cv2.resize(binarized, None, fx=1./scale, fy=1./scale)
_, binarized = cv2.threshold(binarized, 127, 255, cv2.THRESH_BINARY)
return binarized, refined_text_boxes
def _binarize_roi(self, box, roi):
_h, _w = roi.shape[:2]
binarized_roi = np.ones((_h, _w), np.uint8)*255
binarized_layers = []
layer_components = []
# Preselection
for layer, cluster in self._get_affinity_layers(box, roi):
binarized_layer = np.zeros_like(binarized_roi)
labels, stats, centroids = self.get_connected_components(layer, cluster)
components = np.zeros((_h, _w, 3))
selected_labels = []
for label, stat in enumerate(stats):
left = stat[cv2.CC_STAT_LEFT]
top = stat[cv2.CC_STAT_TOP]
width = stat[cv2.CC_STAT_WIDTH]
height = stat[cv2.CC_STAT_HEIGHT]
right = left + width - 1
bottom = top + height - 1
is_good = self._select_good_char_box((_w, _h), (left, top, width, height),
(labels == label), debug_mode=self.config.debug)
if self.config.debug:
is_good, reason = is_good
cv2.rectangle(components, (left, top), (right, bottom), (0, 255, 255), 1, cv2.LINE_AA)
if reason == 1:
continue
cv2.rectangle(components, (left, top), (right, bottom), (0, 0, 255), 1, cv2.LINE_AA)
if reason == 2:
continue
cv2.rectangle(components, (left, top), (right, bottom), (0, 255, 0), 1, cv2.LINE_AA)
if reason == 3:
continue
cv2.rectangle(components, (left, top), (right, bottom), (0, 125, 255), 1, cv2.LINE_AA)
if reason == 4:
continue
cv2.rectangle(components, (left, top), (right, bottom), (0, 255, 125), 1, cv2.LINE_AA)
if reason == 5:
continue
cv2.rectangle(components, (left, top), (right, bottom), (255, 0, 0), 1, cv2.LINE_AA)
if not is_good:
continue
selected_labels += [label]
layer_box = np.array([(0, 0), (0, _h), (_w, _h), (_w, 0)])
stubs = []
isolated_points = []
stubs_image = np.zeros((_h, _w, 3), np.uint8)
words = []
words_image = np.zeros((_h, _w, 3), np.uint8)
layer_components += [[labels, stats, centroids, selected_labels,
binarized_layer, components, layer, cluster, layer_box,
stubs, isolated_points, stubs_image, words, words_image]]
# Reduce Noise
for component in layer_components:
self.reduce_noise(component)
if self.config.debug:
stats = component[1]
pre_selected_labels = component[3]
components = component[5]
for label in pre_selected_labels:
stat = stats[label]
left = stat[cv2.CC_STAT_LEFT]
top = stat[cv2.CC_STAT_TOP]
width = stat[cv2.CC_STAT_WIDTH]
height = stat[cv2.CC_STAT_HEIGHT]
right = left + width - 1
bottom = top + height - 1
cv2.rectangle(components, (left, top), (right, bottom), (255, 0, 255), 1, cv2.LINE_AA)
# Find Stubs
best_layer_index = None
best_layer_overlap = 0
best_layer_char_count = 999
for i_component, component in enumerate(layer_components):
self.find_stubs(component, _w, _h)
stubs = component[9]
best_stub_index, best_overlap = self.get_best_stub(component, box)
best_char_count = len(stubs[best_stub_index][2]) if best_stub_index >= 0 else 999
if best_overlap > 1.5 * best_layer_overlap:
is_better = True
elif best_overlap < best_layer_overlap / 1.5:
is_better = False
else:
if best_layer_char_count < best_char_count:
is_better = False
else:
is_better = True
if is_better:
best_layer_index = i_component
best_layer_overlap = best_overlap
best_layer_char_count = best_char_count
stats = component[1]
isolated_points = component[10]
stubs_canvas = component[11]
words = [stubs[best_stub_index]] if best_stub_index >= 0 else []
component[12] = words
words_canvas = component[13]
if self.config.debug:
colors = [
(0, 0, 255),
(0, 255, 0),
(255, 0, 0),
(255, 255, 0),
(255, 0, 255),
(0, 255, 255),
(0, 127, 255),
(0, 255, 127),
(127, 0, 255),
(255, 0, 127),
(127, 255, 0),
(255, 127, 0),
(0, 0, 125),
(0, 125, 0),
(125, 0, 0),
(255, 255, 255)
]
for label in isolated_points:
stat = stats[label]
left = stat[cv2.CC_STAT_LEFT]
top = stat[cv2.CC_STAT_TOP]
width = stat[cv2.CC_STAT_WIDTH]
height = stat[cv2.CC_STAT_HEIGHT]
right = left + width - 1
bottom = top + height - 1
center = (left + width/2, top + height/2)
cv2.circle(stubs_canvas, (int(center[0]), int(center[1])), 3, (127, 127, 127), -1)
cv2.rectangle(stubs_canvas, (left, top), (right, bottom), (127, 127, 127), 1)
cv2.circle(words_canvas, (int(center[0]), int(center[1])), 3, (127, 127, 127), -1)
cv2.rectangle(words_canvas, (left, top), (right, bottom), (127, 127, 127), 1)
for ic, line in enumerate(stubs):
a, b, stub = line
color = colors[ic % len(colors)]
for label in stub:
stat = stats[label]
left = stat[cv2.CC_STAT_LEFT]
top = stat[cv2.CC_STAT_TOP]
width = stat[cv2.CC_STAT_WIDTH]
height = stat[cv2.CC_STAT_HEIGHT]
right = left + width - 1
bottom = top + height - 1
center = (left + width/2, top + height/2)
cv2.circle(stubs_canvas, (int(center[0]), int(center[1])), 3, color, -1)
cv2.rectangle(stubs_canvas, (left, top), (right, bottom), color, 1)
x0 = int(stats[stub[0]][cv2.CC_STAT_LEFT])
x1 = int(stats[stub[-1]][cv2.CC_STAT_LEFT] + stats[stub[-1]][cv2.CC_STAT_WIDTH])
y0 = int(a*x0 + b)
y1 = int(a*x1 + b)
cv2.line(stubs_canvas, (x0, y0), (x1, y1), color, 1, cv2.LINE_AA)
for ic, line in enumerate(words):
a, b, stub = line
color = colors[ic % len(colors)]
for label in stub:
stat = stats[label]
left = stat[cv2.CC_STAT_LEFT]
top = stat[cv2.CC_STAT_TOP]
width = stat[cv2.CC_STAT_WIDTH]
height = stat[cv2.CC_STAT_HEIGHT]
right = left + width - 1
bottom = top + height - 1
center = (left + width/2, top + height/2)
cv2.circle(words_canvas, (int(center[0]), int(center[1])), 3, color, -1)
cv2.rectangle(words_canvas, (left, top), (right, bottom), color, 1)
x0 = int(stats[stub[0]][cv2.CC_STAT_LEFT])
x1 = int(stats[stub[-1]][cv2.CC_STAT_LEFT] + stats[stub[-1]][cv2.CC_STAT_WIDTH])
y0 = int(a*x0 + b)
y1 = int(a*x1 + b)
cv2.line(words_canvas, (x0, y0), (x1, y1), color, 1, cv2.LINE_AA)
if best_layer_index is not None:
best_layer_component = layer_components[best_layer_index]
best_layer_stats = best_layer_component[1]
for i_component, component in enumerate(layer_components):
selected_labels = []
for a, b, word in component[12]:
for label in word:
selected_labels += [label]
if i_component == best_layer_index:
component[3] = selected_labels
continue
stats = component[1]
good_labels = []
for label in selected_labels:
stat = stats[label]
left = stat[cv2.CC_STAT_LEFT]
top = stat[cv2.CC_STAT_TOP]
width = stat[cv2.CC_STAT_WIDTH]
height = stat[cv2.CC_STAT_HEIGHT]
right = left + width - 1
bottom = top + height - 1
area = width * height
should_break = False
for good_label in best_layer_component[3]:
good_stat = best_layer_stats[good_label]
good_left = good_stat[cv2.CC_STAT_LEFT]
good_top = good_stat[cv2.CC_STAT_TOP]
good_width = good_stat[cv2.CC_STAT_WIDTH]
good_height = good_stat[cv2.CC_STAT_HEIGHT]
good_right = good_left + good_width - 1
good_bottom = good_top + good_height - 1
good_area = good_width * good_height
overlap_area = ((min(right, good_right) - max(left, good_left)) *
(min(bottom, good_bottom) - max(top, good_top)))
overlap = overlap_area / (area + good_area - overlap_area)
if 0.5 < overlap < 1.5:
good_labels += selected_labels
should_break = True
break
if should_break:
break
component[3] = good_labels
text_box = []
for component in layer_components:
stats = component[1]
centroids = component[2]
good_labels = component[3]
for label in good_labels:
stat = stats[label]
centroid = centroids[label]
width = stat[cv2.CC_STAT_WIDTH]
height = stat[cv2.CC_STAT_HEIGHT]
l_box = [[centroid[0], centroid[1]+height/2],
[centroid[0], centroid[1]-height/2],
[centroid[0]+width/2, centroid[1]],
[centroid[0]-width/2, centroid[1]]]
text_box += l_box
if len(text_box) > 0:
text_box = cv2.boxPoints(cv2.minAreaRect(np.array(text_box).astype(np.int32)))
else:
text_box = box
# Restore punctuation
expanded_text_box = []
box_center = np.mean(text_box, axis=0)
for p in text_box:
cx = box_center[0]
cy = box_center[1]
px = 1.2 * (p[0] - cx) + cx
py = 1.2 * (p[1] - cy) + cy
expanded_text_box += [(px, py)]
expanded_text_box = np.array(expanded_text_box)
text_box = []
for component in layer_components:
stats = component[1]
centroids = component[2]
isolated_points = component[10]
selected_labels = component[3]
for label in isolated_points:
if Point(centroids[label]).within(Polygon(expanded_text_box)):
selected_labels += [label]
for label in selected_labels:
stat = stats[label]
centroid = centroids[label]
width = stat[cv2.CC_STAT_WIDTH]
height = stat[cv2.CC_STAT_HEIGHT]
l_box = [[centroid[0], centroid[1] + height / 2],
[centroid[0], centroid[1] - height / 2],
[centroid[0] + width / 2, centroid[1]],
[centroid[0] - width / 2, centroid[1]]]
text_box += l_box
component[3] = selected_labels
if len(text_box) > 0:
text_box = cv2.boxPoints(cv2.minAreaRect(np.array(text_box).astype(np.int32)))
else:
text_box = box
expanded_text_box = []
box_center = np.mean(text_box, axis=0)
for p in text_box:
cx = box_center[0]
cy = box_center[1]
px = 1.05 * (p[0] - cx) + cx
py = 1.05 * (p[1] - cy) + cy
expanded_text_box += [(px, py)]
text_box = np.array(expanded_text_box)
for component in layer_components:
labels = component[0]
good_labels = component[3]
binarized_layer = component[4]
components = component[5]
layer = component[6]
cluster = component[7]
stubs = component[11]
words = component[13]
for label in good_labels:
binarized_layer[labels == label] = 255
binarized_layers += [binarized_layer]
if self.do_visualisation:
cv2.imshow("roi", roi)
cv2.imshow("layer", layer)
cv2.imshow("cluster", cluster)
cv2.imshow("labels", cv2.applyColorMap((labels*255/labels.max()).astype(np.uint8), cv2.COLORMAP_JET))
cv2.imshow("components", components)
cv2.imshow("stubs", stubs)
cv2.imshow("words", words)
cv2.imshow("binarized_layer", binarized_layer)
cv2.imshow("binarized_roi", binarized_roi)
key = cv2.waitKey(0)
if key & 0xff == ord('q'):
break
if key & 0xff == ord('s'):
self.do_visualisation = False
break
cv2.destroyWindow("roi")
cv2.destroyWindow("layer")
cv2.destroyWindow("cluster")
cv2.destroyWindow("labels")
cv2.destroyWindow("components")
cv2.destroyWindow("stubs")
cv2.destroyWindow("words")
cv2.destroyWindow("binarized_layer")
cv2.destroyWindow("binarized_roi")
for binarized_layer in binarized_layers:
binarized_roi = np.bitwise_and(binarized_roi, np.bitwise_not(binarized_layer))
return binarized_roi, text_box
def _select_good_char_box(self, roi_size, box, bin_layer, debug_mode=False):
_w, _h = roi_size
left, top, width, height = box
min_size = 0.05 * (_h if _h < _w else _w)
if width < min_size and height < min_size:
return (False, 1) if debug_mode else False
if width > 0.5 * _w or (height > 0.9 * _h and width > 0.3 * _w):
return (False, 2) if debug_mode else False
aspect_ratio = width / height
if aspect_ratio < 1. / 15 or aspect_ratio > 15:
return (False, 3) if debug_mode else False
n_white = np.count_nonzero(bin_layer)
if n_white / (width*height) < 0.1:
return (False, 4) if debug_mode else False
if n_white / (width*height) > 0.95 and width > _h:
return (False, 5) if debug_mode else False
return (True, 0) if debug_mode else True
def _get_affinity_layers(self, box, roi):
_h, _w = roi.shape[:2]
box_mask = np.zeros((_h, _w, 3), np.uint8)
cv2.fillPoly(box_mask, [box], (255, 255, 255))
bins = int(256 / self.rgb_bin_size)
hist, _ = np.histogramdd(np.bitwise_and(box_mask, roi).reshape(-1, 3),
(bins, bins, bins), ((0, 256), (0, 256), (0, 256)))
X = []
weights = []
for i in range(bins):
for j in range(bins):
for k in range(bins):
if hist[i, j, k] != 0:
X += [(i, j, k)]
weights += [hist[i, j, k]]
X = np.array(X)
weights = np.array(weights)
Xw = X * np.hstack((weights.reshape(-1, 1),
weights.reshape(-1, 1),
weights.reshape(-1, 1)))
dbscan = DBSCAN(eps=self.dbscan_eps, min_samples=np.sum(weights) * self.dbscan_min_sample_frac)
dbscan.fit(X, sample_weight=weights)
clusters = []
for label in np.unique(dbscan.labels_):
cluster_indices = dbscan.labels_ == label
clusters += [np.sum(Xw[cluster_indices], axis=0) /
np.sum(weights[cluster_indices])]
clusters = np.array(clusters) * 256 / bins
kmeans = KMeans(n_clusters=len(clusters))
kmeans.cluster_centers_ = clusters
labels = kmeans.predict(roi.reshape(-1, 3)).reshape(_h, _w)
for label in np.unique(labels):
layer = np.zeros((_h, _w), np.uint8)
cluster = np.zeros_like(roi)
layer[labels == label] = 255
cluster[labels == label] = roi[labels == label]
n_white = cv2.countNonZero(np.bitwise_and(box_mask[:, :, 0], layer))
n_all = cv2.contourArea(box)
if n_white > n_all / 2:
layer = np.bitwise_not(layer)
yield layer, cluster
def get_connected_components(self, layer, cluster):
kernel = np.ones((3, 3), np.uint8)
opening = cv2.morphologyEx(layer, cv2.MORPH_OPEN, kernel, iterations=2)
sure_bg = cv2.dilate(opening, kernel, iterations=3)
dist_transform = cv2.distanceTransform(layer, cv2.DIST_L2, 5)
dist_transform = (dist_transform * 255 / dist_transform.max()).astype(np.uint8)
# _, sure_fg = cv2.threshold(dist_transform, 0.1 * dist_transform.max(), 255, 0)
_h, _w = layer.shape[:2]
ath_block_size = int(_h/8)*2+1
sure_fg = cv2.adaptiveThreshold(dist_transform, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY,
ath_block_size, 0)
sure_fg = np.uint8(sure_fg)
unknown = cv2.subtract(sure_bg, sure_fg)
_, markers = cv2.connectedComponents(sure_fg)
markers = markers + 1
markers[unknown == 255] = 0
labels = cv2.watershed(cluster, markers)
labels[labels == -1] = 0
labels[layer == 0] = 0
stats = []
centroids = []
for i_label, label in enumerate(np.sort(np.unique(labels))):
i, j = np.where(labels == label)
top, left, bottom, right = i.min(), j.min(), i.max(), j.max()
m = cv2.moments( (labels == label).astype(np.uint8))
x = int(m["m10"] / m["m00"])
y = int(m["m01"] / m["m00"])
stats += [{
cv2.CC_STAT_LEFT: left,
cv2.CC_STAT_TOP: top,
cv2.CC_STAT_WIDTH: right - left + 1,
cv2.CC_STAT_HEIGHT: bottom - top + 1,
}]
centroids += [[x, y]]
labels[labels == label] = i_label
if self.do_visualisation:
cv2.imshow("layer", layer)
cv2.imshow("cluster", cluster)
cv2.imshow("dist_transform", dist_transform)
cv2.imshow("sure_fg", sure_fg)
cv2.imshow("markers", cv2.applyColorMap((labels * 255 / labels.max()).astype(np.uint8), cv2.COLORMAP_JET))
key = cv2.waitKey(0)
if key & 0xff == ord('q'):
self.do_visualisation = False
cv2.destroyWindow("layer")
cv2.destroyWindow("cluster")
cv2.destroyWindow("dist_transform")
cv2.destroyWindow("sure_fg")
cv2.destroyWindow("markers")
return labels, stats, centroids
def reduce_noise(self, component):
stats = component[1]
preselected_labels = component[3]
selected_labels = []
for label in preselected_labels:
stat = stats[label]
left = stat[cv2.CC_STAT_LEFT]
top = stat[cv2.CC_STAT_TOP]
width = stat[cv2.CC_STAT_WIDTH]
height = stat[cv2.CC_STAT_HEIGHT]
right = left + width - 1
bottom = top + height - 1
n_overlaps = 0
is_contained = False
for j_label in preselected_labels:
if j_label == label:
continue
j_stat = stats[j_label]
j_left = j_stat[cv2.CC_STAT_LEFT]
j_top = j_stat[cv2.CC_STAT_TOP]
j_width = j_stat[cv2.CC_STAT_WIDTH]
j_height = j_stat[cv2.CC_STAT_HEIGHT]
j_right = j_left + j_width - 1
j_bottom = j_top + j_height - 1
if j_right < left or j_left > right or j_top > bottom or j_bottom < top:
continue
overlap = ((min(right, j_right) - max(left, j_left) + 1) *
(min(bottom, j_bottom) - max(top, j_top) + 1))
if overlap <= 0:
continue
max_overlap = min((width * height), (j_width * j_height))
if overlap / max_overlap > 0.25:
n_overlaps += 1
if overlap / max_overlap > 0.95 and (j_width * j_height) > (width * height):
is_contained = True
if n_overlaps > 4 or is_contained:
continue
selected_labels += [label]
component[3] = selected_labels
def find_stubs(self, component, _w, _h):
roi_center = np.array((_w / 2, _h / 2))
stats = component[1]
centers = [(stat[cv2.CC_STAT_LEFT] + stat[cv2.CC_STAT_WIDTH]/2,
stat[cv2.CC_STAT_TOP] + stat[cv2.CC_STAT_HEIGHT]/2)
for stat in stats]
pre_selected_labels = component[3]
distances = []
for label in pre_selected_labels:
center = centers[label]
distance = np.linalg.norm(center - roi_center)
distances += [distance]
sorted_labels = [pre_selected_labels[idx] for idx in np.argsort(np.array(distances))]
if 0 < len(sorted_labels) < 3:
stub = sorted_labels
points_to_fit = np.array([centers[label] for label in stub])
a, b = self.fit_line_to_points(points_to_fit)
component[9] = [(a, b, stub)]
component[10] = []
return
tolerance = _h / 5
stub_candidates = []
isolated_points = []
points = [label for label in sorted_labels]
rejected = []
while len(points) > 0:
seed = points.pop(0)
stub = [seed]
unused = []
while len(points) > 0:
point = points.pop(0)
if len(stub) < 2:
stub += [point]
else:
points_to_fit = np.array([centers[label] for label in stub])
line = np.polyfit(points_to_fit[:, 0], points_to_fit[:, 1], 1)
a, b = line[0], line[1]
residual = self.distance_to_line(centers[point], (a, b))
height = stats[point][cv2.CC_STAT_HEIGHT]
point_tolerance = max(tolerance, height / 2)
if residual < point_tolerance:
stub += [point]
points += rejected + unused
rejected = []
unused = []
else:
unused += [point]
if len(stub) == 2:
points = [seed] + unused
rejected += [stub.pop()]
elif len(stub) == 1:
isolated_points += [seed]
points = unused + rejected
rejected = []
else:
points_to_fit = np.array([centers[label] for label in stub])
line = np.polyfit(points_to_fit[:, 0], points_to_fit[:, 1], 1)
a, b = line[0], line[1]
stub_candidates += [(a, b, stub)]
points = rejected + unused
rejected = []
component[9] = [(a, b, [stub[idx] for idx in np.argsort([centers[point][0] for point in stub])])
for a, b, stub in stub_candidates]
component[10] = isolated_points
def get_best_stub(self, component, box):
stats = component[1]
stubs = component[9]
box_poly = Polygon(box)
best_stub_index = -1
best_overlap = 0
for index, (a, b, stub) in enumerate(stubs):
in_box_area = 0
for label in stub:
stat = stats[label]
top = stat[cv2.CC_STAT_TOP]
left = stat[cv2.CC_STAT_LEFT]
width = stat[cv2.CC_STAT_WIDTH]
height = stat[cv2.CC_STAT_HEIGHT]
bottom = top + height - 1
right = left + width - 1
label_poly = Polygon([[left, top],
[left, bottom],
[right, bottom],
[right, top]])
in_box_area += label_poly.intersection(box_poly).area
if in_box_area > best_overlap:
best_stub_index = index
best_overlap = in_box_area
return best_stub_index, best_overlap
def find_words(self, component):
stats = component[1]
stubs = component[9]
isolated_points = component[10]
centers = [(stat[cv2.CC_STAT_LEFT] + stat[cv2.CC_STAT_WIDTH]/2,
stat[cv2.CC_STAT_TOP] + stat[cv2.CC_STAT_HEIGHT]/2)
for stat in stats]
words = []
for a, b, stub in stubs:
heights = []
widths = []
gaps = []
for i, label in enumerate(stub):
stat = stats[label]
left = stat[cv2.CC_STAT_LEFT]
width = stat[cv2.CC_STAT_WIDTH]
height = stat[cv2.CC_STAT_HEIGHT]
i_next = i+1 if (i+1) < len(stub) else -1
widths += [width]
heights += [height]
if i_next >= 0:
next_left = stats[stub[i_next]][cv2.CC_STAT_LEFT]
gaps += [next_left - left - width]
median_width = np.median(widths)
median_gap = np.median(gaps)
if median_gap < 0:
isolated_points += stub
continue
if median_gap > median_width * 2:
isolated_points += stub
continue
max_gap = min(median_width, max(median_width/4, 2*median_gap))
large_gaps = np.where(gaps > max_gap)[0]
break_indices = [0] + [index+1 for index in large_gaps] + [len(stub)]
for start, end in zip(break_indices[:-1], break_indices[1:]):
word = stub[start:end]
word_points = np.array([centers[point] for point in word])
word_line = np.polyfit(word_points[:, 0], word_points[:, 1], 1)
word_a, word_b = word_line[0], word_line[1]
words += [(word_a, word_b, word)]
component[12] = words
def distance_to_line(self, P, line):
a, b = line
v = np.array([1, a])
v = v / np.linalg.norm(v)
beta = np.array([0, b])
H = np.dot(v, (P - beta)) * v + beta
residual = np.linalg.norm(P - H)
return residual
def get_stub_mean_residuals(self, a, b, points):
if len(points) <= 2:
return 0
residuals = np.array([self.distance_to_line(point, (a, b)) for point in points])
mean = np.mean(residuals)
return mean
def fit_line_to_points(self, points_to_fit):
if len(points_to_fit) == 0:
return 0, 0
if len(points_to_fit) == 1:
return 0, points_to_fit[0][1]
if len(points_to_fit) == 2:
x1, y1 = points_to_fit[0][0], points_to_fit[0][1]
x2, y2 = points_to_fit[1][0], points_to_fit[1][1]
if x1 == x2:
x1 = x2 - np.finfo(np.float32).eps
a = (y2 - y1) / (x2 - x1)
b = y1 - a * x1
return a, b
line = np.polyfit(points_to_fit[:, 0], points_to_fit[:, 1], 1)
a, b = line[0], line[1]
return a, b
def refine_text_boxes(self, text_boxes, overlap_threshold=0.1):
if len(text_boxes) == 0:
return []
attempt_merge = True
sel_boxes = [box for box in text_boxes]
while attempt_merge:
attempt_merge = False
boxes = np.array(sel_boxes)
if boxes.dtype.kind == "i":
boxes = boxes.astype("float")
p1 = boxes[:, 0]
p2 = boxes[:, 1]
p3 = boxes[:, 2]
p4 = boxes[:, 3]
polygons = [Polygon([ip1, ip2, ip3, ip4]) for ip1, ip2, ip3, ip4 in zip(p1, p2, p3, p4)]
areas = np.array([p.area for p in polygons])
indices = np.argsort(-areas)
pick = []
sel_boxes = []
while len(indices) > 0:
last = len(indices) - 1
i = indices[last]
pick.append(i)
polygon = polygons[i]
overlaps = np.array([polygon.intersection(polygons[other]).area for other in indices[:last]])
overlaps = overlaps / areas[indices[:last]]
group = np.concatenate(([last], np.where(overlaps > overlap_threshold)[0]))
group_box = cascaded_union([polygons[indices[ig]] for ig in group]).minimum_rotated_rectangle
sel_boxes += [sort_box(group_box.exterior.coords[:-1])]
indices = np.delete(indices, group)
if len(group) > 1:
attempt_merge = True
sel_boxes = np.array(sel_boxes).astype("int")
self.debugger.log("refined: ", np.array(text_boxes).shape, sel_boxes.shape)
return sel_boxes
|
[
"numpy.sum",
"numpy.polyfit",
"numpy.ones",
"cv2.adaptiveThreshold",
"cv2.fillPoly",
"numpy.argsort",
"numpy.mean",
"numpy.linalg.norm",
"cv2.rectangle",
"cv2.imshow",
"numpy.unique",
"cv2.line",
"cv2.contourArea",
"cv2.subtract",
"numpy.zeros_like",
"shapely.geometry.Point",
"shapely.geometry.Polygon",
"cv2.dilate",
"cv2.connectedComponents",
"numpy.finfo",
"cv2.boundingRect",
"cv2.resize",
"numpy.uint8",
"shapely.ops.cascaded_union",
"cv2.waitKey",
"cv2.morphologyEx",
"numpy.median",
"numpy.bitwise_not",
"numpy.dot",
"cv2.distanceTransform",
"numpy.delete",
"numpy.count_nonzero",
"cv2.threshold",
"numpy.zeros",
"cv2.watershed",
"numpy.where",
"numpy.array",
"numpy.bitwise_and",
"cv2.destroyWindow",
"numpy.sqrt"
] |
[((1257, 1285), 'numpy.sqrt', 'np.sqrt', (['(750 * 750 / (h * w))'], {}), '(750 * 750 / (h * w))\n', (1264, 1285), True, 'import numpy as np\n'), ((14615, 14640), 'numpy.mean', 'np.mean', (['text_box'], {'axis': '(0)'}), '(text_box, axis=0)\n', (14622, 14640), True, 'import numpy as np\n'), ((14882, 14909), 'numpy.array', 'np.array', (['expanded_text_box'], {}), '(expanded_text_box)\n', (14890, 14909), True, 'import numpy as np\n'), ((16078, 16103), 'numpy.mean', 'np.mean', (['text_box'], {'axis': '(0)'}), '(text_box, axis=0)\n', (16085, 16103), True, 'import numpy as np\n'), ((16338, 16365), 'numpy.array', 'np.array', (['expanded_text_box'], {}), '(expanded_text_box)\n', (16346, 16365), True, 'import numpy as np\n'), ((18811, 18838), 'numpy.count_nonzero', 'np.count_nonzero', (['bin_layer'], {}), '(bin_layer)\n', (18827, 18838), True, 'import numpy as np\n'), ((19198, 19229), 'numpy.zeros', 'np.zeros', (['(_h, _w, 3)', 'np.uint8'], {}), '((_h, _w, 3), np.uint8)\n', (19206, 19229), True, 'import numpy as np\n'), ((19238, 19284), 'cv2.fillPoly', 'cv2.fillPoly', (['box_mask', '[box]', '(255, 255, 255)'], {}), '(box_mask, [box], (255, 255, 255))\n', (19250, 19284), False, 'import cv2\n'), ((19779, 19790), 'numpy.array', 'np.array', (['X'], {}), '(X)\n', (19787, 19790), True, 'import numpy as np\n'), ((19809, 19826), 'numpy.array', 'np.array', (['weights'], {}), '(weights)\n', (19817, 19826), True, 'import numpy as np\n'), ((20176, 20201), 'numpy.unique', 'np.unique', (['dbscan.labels_'], {}), '(dbscan.labels_)\n', (20185, 20201), True, 'import numpy as np\n'), ((20612, 20629), 'numpy.unique', 'np.unique', (['labels'], {}), '(labels)\n', (20621, 20629), True, 'import numpy as np\n'), ((21135, 21160), 'numpy.ones', 'np.ones', (['(3, 3)', 'np.uint8'], {}), '((3, 3), np.uint8)\n', (21142, 21160), True, 'import numpy as np\n'), ((21179, 21240), 'cv2.morphologyEx', 'cv2.morphologyEx', (['layer', 'cv2.MORPH_OPEN', 'kernel'], {'iterations': '(2)'}), '(layer, cv2.MORPH_OPEN, kernel, iterations=2)\n', (21195, 21240), False, 'import cv2\n'), ((21259, 21300), 'cv2.dilate', 'cv2.dilate', (['opening', 'kernel'], {'iterations': '(3)'}), '(opening, kernel, iterations=3)\n', (21269, 21300), False, 'import cv2\n'), ((21326, 21370), 'cv2.distanceTransform', 'cv2.distanceTransform', (['layer', 'cv2.DIST_L2', '(5)'], {}), '(layer, cv2.DIST_L2, 5)\n', (21347, 21370), False, 'import cv2\n'), ((21638, 21751), 'cv2.adaptiveThreshold', 'cv2.adaptiveThreshold', (['dist_transform', '(255)', 'cv2.ADAPTIVE_THRESH_MEAN_C', 'cv2.THRESH_BINARY', 'ath_block_size', '(0)'], {}), '(dist_transform, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.\n THRESH_BINARY, ath_block_size, 0)\n', (21659, 21751), False, 'import cv2\n'), ((21805, 21822), 'numpy.uint8', 'np.uint8', (['sure_fg'], {}), '(sure_fg)\n', (21813, 21822), True, 'import numpy as np\n'), ((21841, 21871), 'cv2.subtract', 'cv2.subtract', (['sure_bg', 'sure_fg'], {}), '(sure_bg, sure_fg)\n', (21853, 21871), False, 'import cv2\n'), ((21893, 21925), 'cv2.connectedComponents', 'cv2.connectedComponents', (['sure_fg'], {}), '(sure_fg)\n', (21916, 21925), False, 'import cv2\n'), ((22009, 22040), 'cv2.watershed', 'cv2.watershed', (['cluster', 'markers'], {}), '(cluster, markers)\n', (22022, 22040), False, 'import cv2\n'), ((25311, 25337), 'numpy.array', 'np.array', (['(_w / 2, _h / 2)'], {}), '((_w / 2, _h / 2))\n', (25319, 25337), True, 'import numpy as np\n'), ((28247, 28259), 'shapely.geometry.Polygon', 'Polygon', (['box'], {}), '(box)\n', (28254, 28259), False, 'from shapely.geometry import Point, Polygon\n'), ((31140, 31156), 'numpy.array', 'np.array', (['[1, a]'], {}), '([1, a])\n', (31148, 31156), True, 'import numpy as np\n'), ((31206, 31222), 'numpy.array', 'np.array', (['[0, b]'], {}), '([0, b])\n', (31214, 31222), True, 'import numpy as np\n'), ((31287, 31308), 'numpy.linalg.norm', 'np.linalg.norm', (['(P - H)'], {}), '(P - H)\n', (31301, 31308), True, 'import numpy as np\n'), ((31544, 31562), 'numpy.mean', 'np.mean', (['residuals'], {}), '(residuals)\n', (31551, 31562), True, 'import numpy as np\n'), ((32113, 32168), 'numpy.polyfit', 'np.polyfit', (['points_to_fit[:, 0]', 'points_to_fit[:, 1]', '(1)'], {}), '(points_to_fit[:, 0], points_to_fit[:, 1], 1)\n', (32123, 32168), True, 'import numpy as np\n'), ((1412, 1455), 'cv2.resize', 'cv2.resize', (['image', 'None'], {'fx': 'scale', 'fy': 'scale'}), '(image, None, fx=scale, fy=scale)\n', (1422, 1455), False, 'import cv2\n'), ((1512, 1537), 'numpy.ones', 'np.ones', (['(h, w)', 'np.uint8'], {}), '((h, w), np.uint8)\n', (1519, 1537), True, 'import numpy as np\n'), ((1796, 1817), 'cv2.boundingRect', 'cv2.boundingRect', (['box'], {}), '(box)\n', (1812, 1817), False, 'import cv2\n'), ((2828, 2887), 'cv2.resize', 'cv2.resize', (['binarized', 'None'], {'fx': '(1.0 / scale)', 'fy': '(1.0 / scale)'}), '(binarized, None, fx=1.0 / scale, fy=1.0 / scale)\n', (2838, 2887), False, 'import cv2\n'), ((2909, 2962), 'cv2.threshold', 'cv2.threshold', (['binarized', '(127)', '(255)', 'cv2.THRESH_BINARY'], {}), '(binarized, 127, 255, cv2.THRESH_BINARY)\n', (2922, 2962), False, 'import cv2\n'), ((3106, 3133), 'numpy.ones', 'np.ones', (['(_h, _w)', 'np.uint8'], {}), '((_h, _w), np.uint8)\n', (3113, 3133), True, 'import numpy as np\n'), ((3321, 3349), 'numpy.zeros_like', 'np.zeros_like', (['binarized_roi'], {}), '(binarized_roi)\n', (3334, 3349), True, 'import numpy as np\n'), ((3460, 3481), 'numpy.zeros', 'np.zeros', (['(_h, _w, 3)'], {}), '((_h, _w, 3))\n', (3468, 3481), True, 'import numpy as np\n'), ((5228, 5274), 'numpy.array', 'np.array', (['[(0, 0), (0, _h), (_w, _h), (_w, 0)]'], {}), '([(0, 0), (0, _h), (_w, _h), (_w, 0)])\n', (5236, 5274), True, 'import numpy as np\n'), ((5357, 5388), 'numpy.zeros', 'np.zeros', (['(_h, _w, 3)', 'np.uint8'], {}), '((_h, _w, 3), np.uint8)\n', (5365, 5388), True, 'import numpy as np\n'), ((5438, 5469), 'numpy.zeros', 'np.zeros', (['(_h, _w, 3)', 'np.uint8'], {}), '((_h, _w, 3), np.uint8)\n', (5446, 5469), True, 'import numpy as np\n'), ((20651, 20679), 'numpy.zeros', 'np.zeros', (['(_h, _w)', 'np.uint8'], {}), '((_h, _w), np.uint8)\n', (20659, 20679), True, 'import numpy as np\n'), ((20702, 20720), 'numpy.zeros_like', 'np.zeros_like', (['roi'], {}), '(roi)\n', (20715, 20720), True, 'import numpy as np\n'), ((20923, 20943), 'cv2.contourArea', 'cv2.contourArea', (['box'], {}), '(box)\n', (20938, 20943), False, 'import cv2\n'), ((22236, 22261), 'numpy.where', 'np.where', (['(labels == label)'], {}), '(labels == label)\n', (22244, 22261), True, 'import numpy as np\n'), ((22835, 22861), 'cv2.imshow', 'cv2.imshow', (['"""layer"""', 'layer'], {}), "('layer', layer)\n", (22845, 22861), False, 'import cv2\n'), ((22874, 22904), 'cv2.imshow', 'cv2.imshow', (['"""cluster"""', 'cluster'], {}), "('cluster', cluster)\n", (22884, 22904), False, 'import cv2\n'), ((22917, 22961), 'cv2.imshow', 'cv2.imshow', (['"""dist_transform"""', 'dist_transform'], {}), "('dist_transform', dist_transform)\n", (22927, 22961), False, 'import cv2\n'), ((22974, 23004), 'cv2.imshow', 'cv2.imshow', (['"""sure_fg"""', 'sure_fg'], {}), "('sure_fg', sure_fg)\n", (22984, 23004), False, 'import cv2\n'), ((23143, 23157), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (23154, 23157), False, 'import cv2\n'), ((23256, 23282), 'cv2.destroyWindow', 'cv2.destroyWindow', (['"""layer"""'], {}), "('layer')\n", (23273, 23282), False, 'import cv2\n'), ((23295, 23323), 'cv2.destroyWindow', 'cv2.destroyWindow', (['"""cluster"""'], {}), "('cluster')\n", (23312, 23323), False, 'import cv2\n'), ((23336, 23371), 'cv2.destroyWindow', 'cv2.destroyWindow', (['"""dist_transform"""'], {}), "('dist_transform')\n", (23353, 23371), False, 'import cv2\n'), ((23384, 23412), 'cv2.destroyWindow', 'cv2.destroyWindow', (['"""sure_fg"""'], {}), "('sure_fg')\n", (23401, 23412), False, 'import cv2\n'), ((23425, 23453), 'cv2.destroyWindow', 'cv2.destroyWindow', (['"""markers"""'], {}), "('markers')\n", (23442, 23453), False, 'import cv2\n'), ((25719, 25754), 'numpy.linalg.norm', 'np.linalg.norm', (['(center - roi_center)'], {}), '(center - roi_center)\n', (25733, 25754), True, 'import numpy as np\n'), ((25987, 26031), 'numpy.array', 'np.array', (['[centers[label] for label in stub]'], {}), '([centers[label] for label in stub])\n', (25995, 26031), True, 'import numpy as np\n'), ((30176, 30193), 'numpy.median', 'np.median', (['widths'], {}), '(widths)\n', (30185, 30193), True, 'import numpy as np\n'), ((30219, 30234), 'numpy.median', 'np.median', (['gaps'], {}), '(gaps)\n', (30228, 30234), True, 'import numpy as np\n'), ((31173, 31190), 'numpy.linalg.norm', 'np.linalg.norm', (['v'], {}), '(v)\n', (31187, 31190), True, 'import numpy as np\n'), ((32510, 32529), 'numpy.array', 'np.array', (['sel_boxes'], {}), '(sel_boxes)\n', (32518, 32529), True, 'import numpy as np\n'), ((32855, 32891), 'numpy.array', 'np.array', (['[p.area for p in polygons]'], {}), '([p.area for p in polygons])\n', (32863, 32891), True, 'import numpy as np\n'), ((32914, 32932), 'numpy.argsort', 'np.argsort', (['(-areas)'], {}), '(-areas)\n', (32924, 32932), True, 'import numpy as np\n'), ((2490, 2551), 'numpy.bitwise_and', 'np.bitwise_and', (['binarized[_y:_y + _h, _x:_x + _w]', 'binary_roi'], {}), '(binarized[_y:_y + _h, _x:_x + _w], binary_roi)\n', (2504, 2551), True, 'import numpy as np\n'), ((16901, 16923), 'cv2.imshow', 'cv2.imshow', (['"""roi"""', 'roi'], {}), "('roi', roi)\n", (16911, 16923), False, 'import cv2\n'), ((16940, 16966), 'cv2.imshow', 'cv2.imshow', (['"""layer"""', 'layer'], {}), "('layer', layer)\n", (16950, 16966), False, 'import cv2\n'), ((16983, 17013), 'cv2.imshow', 'cv2.imshow', (['"""cluster"""', 'cluster'], {}), "('cluster', cluster)\n", (16993, 17013), False, 'import cv2\n'), ((17148, 17184), 'cv2.imshow', 'cv2.imshow', (['"""components"""', 'components'], {}), "('components', components)\n", (17158, 17184), False, 'import cv2\n'), ((17201, 17227), 'cv2.imshow', 'cv2.imshow', (['"""stubs"""', 'stubs'], {}), "('stubs', stubs)\n", (17211, 17227), False, 'import cv2\n'), ((17244, 17270), 'cv2.imshow', 'cv2.imshow', (['"""words"""', 'words'], {}), "('words', words)\n", (17254, 17270), False, 'import cv2\n'), ((17287, 17333), 'cv2.imshow', 'cv2.imshow', (['"""binarized_layer"""', 'binarized_layer'], {}), "('binarized_layer', binarized_layer)\n", (17297, 17333), False, 'import cv2\n'), ((17350, 17392), 'cv2.imshow', 'cv2.imshow', (['"""binarized_roi"""', 'binarized_roi'], {}), "('binarized_roi', binarized_roi)\n", (17360, 17392), False, 'import cv2\n'), ((17416, 17430), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (17427, 17430), False, 'import cv2\n'), ((17636, 17660), 'cv2.destroyWindow', 'cv2.destroyWindow', (['"""roi"""'], {}), "('roi')\n", (17653, 17660), False, 'import cv2\n'), ((17677, 17703), 'cv2.destroyWindow', 'cv2.destroyWindow', (['"""layer"""'], {}), "('layer')\n", (17694, 17703), False, 'import cv2\n'), ((17720, 17748), 'cv2.destroyWindow', 'cv2.destroyWindow', (['"""cluster"""'], {}), "('cluster')\n", (17737, 17748), False, 'import cv2\n'), ((17765, 17792), 'cv2.destroyWindow', 'cv2.destroyWindow', (['"""labels"""'], {}), "('labels')\n", (17782, 17792), False, 'import cv2\n'), ((17809, 17840), 'cv2.destroyWindow', 'cv2.destroyWindow', (['"""components"""'], {}), "('components')\n", (17826, 17840), False, 'import cv2\n'), ((17857, 17883), 'cv2.destroyWindow', 'cv2.destroyWindow', (['"""stubs"""'], {}), "('stubs')\n", (17874, 17883), False, 'import cv2\n'), ((17900, 17926), 'cv2.destroyWindow', 'cv2.destroyWindow', (['"""words"""'], {}), "('words')\n", (17917, 17926), False, 'import cv2\n'), ((17943, 17979), 'cv2.destroyWindow', 'cv2.destroyWindow', (['"""binarized_layer"""'], {}), "('binarized_layer')\n", (17960, 17979), False, 'import cv2\n'), ((17996, 18030), 'cv2.destroyWindow', 'cv2.destroyWindow', (['"""binarized_roi"""'], {}), "('binarized_roi')\n", (18013, 18030), False, 'import cv2\n'), ((18139, 18170), 'numpy.bitwise_not', 'np.bitwise_not', (['binarized_layer'], {}), '(binarized_layer)\n', (18153, 18170), True, 'import numpy as np\n'), ((20398, 20416), 'numpy.array', 'np.array', (['clusters'], {}), '(clusters)\n', (20406, 20416), True, 'import numpy as np\n'), ((20861, 20901), 'numpy.bitwise_and', 'np.bitwise_and', (['box_mask[:, :, 0]', 'layer'], {}), '(box_mask[:, :, 0], layer)\n', (20875, 20901), True, 'import numpy as np\n'), ((21004, 21025), 'numpy.bitwise_not', 'np.bitwise_not', (['layer'], {}), '(layer)\n', (21018, 21025), True, 'import numpy as np\n'), ((22196, 22213), 'numpy.unique', 'np.unique', (['labels'], {}), '(labels)\n', (22205, 22213), True, 'import numpy as np\n'), ((28763, 28832), 'shapely.geometry.Polygon', 'Polygon', (['[[left, top], [left, bottom], [right, bottom], [right, top]]'], {}), '([[left, top], [left, bottom], [right, bottom], [right, top]])\n', (28770, 28832), False, 'from shapely.geometry import Point, Polygon\n'), ((30545, 30569), 'numpy.where', 'np.where', (['(gaps > max_gap)'], {}), '(gaps > max_gap)\n', (30553, 30569), True, 'import numpy as np\n'), ((30798, 30842), 'numpy.array', 'np.array', (['[centers[point] for point in word]'], {}), '([centers[point] for point in word])\n', (30806, 30842), True, 'import numpy as np\n'), ((30871, 30922), 'numpy.polyfit', 'np.polyfit', (['word_points[:, 0]', 'word_points[:, 1]', '(1)'], {}), '(word_points[:, 0], word_points[:, 1], 1)\n', (30881, 30922), True, 'import numpy as np\n'), ((31235, 31254), 'numpy.dot', 'np.dot', (['v', '(P - beta)'], {}), '(v, P - beta)\n', (31241, 31254), True, 'import numpy as np\n'), ((32758, 32787), 'shapely.geometry.Polygon', 'Polygon', (['[ip1, ip2, ip3, ip4]'], {}), '([ip1, ip2, ip3, ip4])\n', (32765, 32787), False, 'from shapely.geometry import Point, Polygon\n'), ((33635, 33660), 'numpy.delete', 'np.delete', (['indices', 'group'], {}), '(indices, group)\n', (33644, 33660), True, 'import numpy as np\n'), ((33759, 33778), 'numpy.array', 'np.array', (['sel_boxes'], {}), '(sel_boxes)\n', (33767, 33778), True, 'import numpy as np\n'), ((33833, 33853), 'numpy.array', 'np.array', (['text_boxes'], {}), '(text_boxes)\n', (33841, 33853), True, 'import numpy as np\n'), ((4136, 4226), 'cv2.rectangle', 'cv2.rectangle', (['components', '(left, top)', '(right, bottom)', '(0, 255, 255)', '(1)', 'cv2.LINE_AA'], {}), '(components, (left, top), (right, bottom), (0, 255, 255), 1,\n cv2.LINE_AA)\n', (4149, 4226), False, 'import cv2\n'), ((4312, 4401), 'cv2.rectangle', 'cv2.rectangle', (['components', '(left, top)', '(right, bottom)', '(0, 0, 255)', '(1)', 'cv2.LINE_AA'], {}), '(components, (left, top), (right, bottom), (0, 0, 255), 1, cv2\n .LINE_AA)\n', (4325, 4401), False, 'import cv2\n'), ((4486, 4575), 'cv2.rectangle', 'cv2.rectangle', (['components', '(left, top)', '(right, bottom)', '(0, 255, 0)', '(1)', 'cv2.LINE_AA'], {}), '(components, (left, top), (right, bottom), (0, 255, 0), 1, cv2\n .LINE_AA)\n', (4499, 4575), False, 'import cv2\n'), ((4660, 4750), 'cv2.rectangle', 'cv2.rectangle', (['components', '(left, top)', '(right, bottom)', '(0, 125, 255)', '(1)', 'cv2.LINE_AA'], {}), '(components, (left, top), (right, bottom), (0, 125, 255), 1,\n cv2.LINE_AA)\n', (4673, 4750), False, 'import cv2\n'), ((4836, 4926), 'cv2.rectangle', 'cv2.rectangle', (['components', '(left, top)', '(right, bottom)', '(0, 255, 125)', '(1)', 'cv2.LINE_AA'], {}), '(components, (left, top), (right, bottom), (0, 255, 125), 1,\n cv2.LINE_AA)\n', (4849, 4926), False, 'import cv2\n'), ((5012, 5101), 'cv2.rectangle', 'cv2.rectangle', (['components', '(left, top)', '(right, bottom)', '(255, 0, 0)', '(1)', 'cv2.LINE_AA'], {}), '(components, (left, top), (right, bottom), (255, 0, 0), 1, cv2\n .LINE_AA)\n', (5025, 5101), False, 'import cv2\n'), ((6409, 6499), 'cv2.rectangle', 'cv2.rectangle', (['components', '(left, top)', '(right, bottom)', '(255, 0, 255)', '(1)', 'cv2.LINE_AA'], {}), '(components, (left, top), (right, bottom), (255, 0, 255), 1,\n cv2.LINE_AA)\n', (6422, 6499), False, 'import cv2\n'), ((8941, 9018), 'cv2.rectangle', 'cv2.rectangle', (['stubs_canvas', '(left, top)', '(right, bottom)', '(127, 127, 127)', '(1)'], {}), '(stubs_canvas, (left, top), (right, bottom), (127, 127, 127), 1)\n', (8954, 9018), False, 'import cv2\n'), ((9142, 9219), 'cv2.rectangle', 'cv2.rectangle', (['words_canvas', '(left, top)', '(right, bottom)', '(127, 127, 127)', '(1)'], {}), '(words_canvas, (left, top), (right, bottom), (127, 127, 127), 1)\n', (9155, 9219), False, 'import cv2\n'), ((10282, 10347), 'cv2.line', 'cv2.line', (['stubs_canvas', '(x0, y0)', '(x1, y1)', 'color', '(1)', 'cv2.LINE_AA'], {}), '(stubs_canvas, (x0, y0), (x1, y1), color, 1, cv2.LINE_AA)\n', (10290, 10347), False, 'import cv2\n'), ((11410, 11475), 'cv2.line', 'cv2.line', (['words_canvas', '(x0, y0)', '(x1, y1)', 'color', '(1)', 'cv2.LINE_AA'], {}), '(words_canvas, (x0, y0), (x1, y1), color, 1, cv2.LINE_AA)\n', (11418, 11475), False, 'import cv2\n'), ((15226, 15252), 'shapely.geometry.Polygon', 'Polygon', (['expanded_text_box'], {}), '(expanded_text_box)\n', (15233, 15252), False, 'from shapely.geometry import Point, Polygon\n'), ((19363, 19392), 'numpy.bitwise_and', 'np.bitwise_and', (['box_mask', 'roi'], {}), '(box_mask, roi)\n', (19377, 19392), True, 'import numpy as np\n'), ((20041, 20056), 'numpy.sum', 'np.sum', (['weights'], {}), '(weights)\n', (20047, 20056), True, 'import numpy as np\n'), ((20282, 20317), 'numpy.sum', 'np.sum', (['Xw[cluster_indices]'], {'axis': '(0)'}), '(Xw[cluster_indices], axis=0)\n', (20288, 20317), True, 'import numpy as np\n'), ((20345, 20377), 'numpy.sum', 'np.sum', (['weights[cluster_indices]'], {}), '(weights[cluster_indices])\n', (20351, 20377), True, 'import numpy as np\n'), ((25865, 25884), 'numpy.array', 'np.array', (['distances'], {}), '(distances)\n', (25873, 25884), True, 'import numpy as np\n'), ((26657, 26701), 'numpy.array', 'np.array', (['[centers[label] for label in stub]'], {}), '([centers[label] for label in stub])\n', (26665, 26701), True, 'import numpy as np\n'), ((26729, 26784), 'numpy.polyfit', 'np.polyfit', (['points_to_fit[:, 0]', 'points_to_fit[:, 1]', '(1)'], {}), '(points_to_fit[:, 0], points_to_fit[:, 1], 1)\n', (26739, 26784), True, 'import numpy as np\n'), ((27631, 27675), 'numpy.array', 'np.array', (['[centers[label] for label in stub]'], {}), '([centers[label] for label in stub])\n', (27639, 27675), True, 'import numpy as np\n'), ((27699, 27754), 'numpy.polyfit', 'np.polyfit', (['points_to_fit[:, 0]', 'points_to_fit[:, 1]', '(1)'], {}), '(points_to_fit[:, 0], points_to_fit[:, 1], 1)\n', (27709, 27754), True, 'import numpy as np\n'), ((33454, 33509), 'shapely.ops.cascaded_union', 'cascaded_union', (['[polygons[indices[ig]] for ig in group]'], {}), '([polygons[indices[ig]] for ig in group])\n', (33468, 33509), False, 'from shapely.ops import cascaded_union\n'), ((9952, 10019), 'cv2.rectangle', 'cv2.rectangle', (['stubs_canvas', '(left, top)', '(right, bottom)', 'color', '(1)'], {}), '(stubs_canvas, (left, top), (right, bottom), color, 1)\n', (9965, 10019), False, 'import cv2\n'), ((11080, 11147), 'cv2.rectangle', 'cv2.rectangle', (['words_canvas', '(left, top)', '(right, bottom)', 'color', '(1)'], {}), '(words_canvas, (left, top), (right, bottom), color, 1)\n', (11093, 11147), False, 'import cv2\n'), ((15195, 15218), 'shapely.geometry.Point', 'Point', (['centroids[label]'], {}), '(centroids[label])\n', (15200, 15218), False, 'from shapely.geometry import Point, Polygon\n'), ((27972, 28021), 'numpy.argsort', 'np.argsort', (['[centers[point][0] for point in stub]'], {}), '([centers[point][0] for point in stub])\n', (27982, 28021), True, 'import numpy as np\n'), ((31983, 32003), 'numpy.finfo', 'np.finfo', (['np.float32'], {}), '(np.float32)\n', (31991, 32003), True, 'import numpy as np\n'), ((14453, 14471), 'numpy.array', 'np.array', (['text_box'], {}), '(text_box)\n', (14461, 14471), True, 'import numpy as np\n'), ((15946, 15964), 'numpy.array', 'np.array', (['text_box'], {}), '(text_box)\n', (15954, 15964), True, 'import numpy as np\n'), ((33382, 33420), 'numpy.where', 'np.where', (['(overlaps > overlap_threshold)'], {}), '(overlaps > overlap_threshold)\n', (33390, 33420), True, 'import numpy as np\n'), ((2736, 2764), 'numpy.array', 'np.array', (['refined_text_boxes'], {}), '(refined_text_boxes)\n', (2744, 2764), True, 'import numpy as np\n')]
|
import os
from collections import defaultdict
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy import stats
DISTRIBUTIONS = {
'exp' : "Exponential",
'N': "Normal"
}
def plot_cdf(groupings, name):
conf = name.split('-')
reservoir_size = conf[0]
distribution = DISTRIBUTIONS[conf[1]]
parameters = conf[2:]
fig, ax = plt.subplots()
xmin = 1000000
xmax = -1
for grouping in groupings:
cdf = grouping['cdf']
x = cdf.lowerlimit + np.linspace(0, cdf.binsize * cdf.cumcount.size, cdf.cumcount.size)
xmin = min(x.min(), xmin)
xmax = max(x.max(), xmax)
ax.plot(x, np.divide(cdf.cumcount, grouping['bincount']), label="Algorithm %s" % grouping['sampler'])
ax.set(xlabel='x', ylabel='P(X ≤ x)', title=f'{distribution}({parameters}), Reservoir size = {reservoir_size}')
ax.set_ylim([0, 1.5])
ax.set_xlim([xmin, xmax])
ax.grid()
ax.legend()
fig.savefig(f'{name}.png')
cdfs = defaultdict(list)
for file in os.listdir('../gen'):
key = file[2:].strip('.csv')
conf = file.strip('.csv').split('-')
algorithm = conf[0]
reservoir_size = conf[1]
distribution = conf[2]
parameters = conf[3:]
absolute = os.path.abspath(f'../gen/{file}')
df = pd.read_csv(absolute)
samples = df.to_numpy()
cdf = stats.cumfreq(samples, numbins=df.size)
cdfs[key].append({
'cdf': cdf,
'dist': DISTRIBUTIONS[distribution],
'reservoir_size': reservoir_size,
'params': parameters,
'sampler': algorithm,
'bincount': df.size
})
for name in cdfs.keys():
plot_cdf(cdfs[name], name)
|
[
"scipy.stats.cumfreq",
"os.path.abspath",
"numpy.divide",
"pandas.read_csv",
"collections.defaultdict",
"numpy.linspace",
"matplotlib.pyplot.subplots",
"os.listdir"
] |
[((1004, 1021), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (1015, 1021), False, 'from collections import defaultdict\n'), ((1034, 1054), 'os.listdir', 'os.listdir', (['"""../gen"""'], {}), "('../gen')\n", (1044, 1054), False, 'import os\n'), ((379, 393), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (391, 393), True, 'import matplotlib.pyplot as plt\n'), ((1251, 1284), 'os.path.abspath', 'os.path.abspath', (['f"""../gen/{file}"""'], {}), "(f'../gen/{file}')\n", (1266, 1284), False, 'import os\n'), ((1294, 1315), 'pandas.read_csv', 'pd.read_csv', (['absolute'], {}), '(absolute)\n', (1305, 1315), True, 'import pandas as pd\n'), ((1354, 1393), 'scipy.stats.cumfreq', 'stats.cumfreq', (['samples'], {'numbins': 'df.size'}), '(samples, numbins=df.size)\n', (1367, 1393), False, 'from scipy import stats\n'), ((517, 583), 'numpy.linspace', 'np.linspace', (['(0)', '(cdf.binsize * cdf.cumcount.size)', 'cdf.cumcount.size'], {}), '(0, cdf.binsize * cdf.cumcount.size, cdf.cumcount.size)\n', (528, 583), True, 'import numpy as np\n'), ((671, 716), 'numpy.divide', 'np.divide', (['cdf.cumcount', "grouping['bincount']"], {}), "(cdf.cumcount, grouping['bincount'])\n", (680, 716), True, 'import numpy as np\n')]
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import copy
from functools import reduce
from hypothesis import assume, given, settings
import hypothesis.strategies as st
from functools import partial
import unittest
from caffe2.python import core, workspace, tt_core, dyndep
import caffe2.python.hypothesis_test_util as hu
from caffe2.proto.caffe2_pb2 import TensorProto
dyndep.InitOpsLibrary('@/caffe2/caffe2/fb/optimizers:sgd_simd_ops')
def sigmoid(x):
return 1.0 / (1.0 + np.exp(-x))
def tanh(x):
return 2.0 * sigmoid(2.0 * x) - 1
def lstm_unit(cell_t_m_1, gates, seq_lengths, timestep):
D = cell_t_m_1.shape[2]
G = gates.shape[2]
N = gates.shape[1]
t = (timestep[0].reshape(1, 1) * np.ones(shape=(N, D))).astype(np.int32)
assert t.shape == (N, D)
seq_lengths = (np.ones(shape=(N, D)) *
seq_lengths.reshape(N, 1)).astype(np.int32)
assert seq_lengths.shape == (N, D)
assert G == 4 * D
# Resize to avoid broadcasting inconsistencies with NumPy
gates = gates.reshape(N, 4, D)
cell_t_m_1 = cell_t_m_1.reshape(N, D)
i_t = gates[:, 0, :].reshape(N, D)
f_t = gates[:, 1, :].reshape(N, D)
o_t = gates[:, 2, :].reshape(N, D)
g_t = gates[:, 3, :].reshape(N, D)
i_t = sigmoid(i_t)
f_t = sigmoid(f_t)
o_t = sigmoid(o_t)
g_t = tanh(g_t)
valid = (seq_lengths < t).astype(np.int32)
assert valid.shape == (N, D)
cell_t = ((f_t * cell_t_m_1) + (i_t * g_t)) * (valid) + \
(1 - valid) * cell_t_m_1
assert cell_t.shape == (N, D)
hidden_t = (o_t * tanh(cell_t)) * valid
hidden_t = hidden_t.reshape(1, N, D)
cell_t = cell_t.reshape(1, N, D)
return hidden_t, cell_t
@st.composite
def _tensor_and_prefix(draw, dtype, elements, min_dim=1, max_dim=4, **kwargs):
dims_ = draw(
st.lists(hu.dims(**kwargs), min_size=min_dim, max_size=max_dim))
extra_ = draw(
st.lists(hu.dims(**kwargs), min_size=min_dim, max_size=max_dim))
return (draw(hu.arrays(dims_ + extra_, dtype, elements)),
draw(hu.arrays(extra_, dtype, elements)))
_NUMPY_TYPE_TO_ENUM = {
np.float32: core.DataType.FLOAT,
np.int32: core.DataType.INT32,
np.bool: core.DataType.BOOL,
np.uint8: core.DataType.UINT8,
np.int8: core.DataType.INT8,
np.uint16: core.DataType.UINT16,
np.int16: core.DataType.INT16,
np.int64: core.DataType.INT64,
np.float64: core.DataType.DOUBLE,
}
def _dtypes():
return st.sampled_from([np.int32, np.int64, np.float32, np.float64])
def _test_binary(name, ref, filter_=None, gcs=hu.gcs,
test_gradient=False, allow_inplace=False, dtypes=_dtypes):
@given(
inputs=dtypes().flatmap(
lambda dtype: hu.tensors(
n=2, dtype=dtype,
elements=hu.elements_of_type(dtype, filter_=filter_))),
out=st.sampled_from(('Y', 'X1', 'X2') if allow_inplace else ('Y',)),
**gcs)
@settings(max_examples=3, timeout=100)
def test_binary(self, inputs, out, gc, dc):
op = core.CreateOperator(name, ["X1", "X2"], [out])
X1, X2 = inputs
self.assertDeviceChecks(dc, op, [X1, X2], [0])
# We only do gradient check with float32 types.
if test_gradient and X1.dtype == np.float32:
self.assertGradientChecks(gc, op, [X1, X2], 0, [0])
self.assertReferenceChecks(gc, op, [X1, X2], ref)
return test_binary
def _test_binary_broadcast(name, ref, filter_=None,
gcs=hu.gcs, allow_inplace=False, dtypes=_dtypes):
@given(
inputs=dtypes().flatmap(lambda dtype: _tensor_and_prefix(
dtype=dtype,
elements=hu.elements_of_type(dtype, filter_=filter_))),
in_place=(st.booleans() if allow_inplace else st.just(False)),
**gcs)
@settings(max_examples=3, timeout=100)
def test_binary_broadcast(self, inputs, in_place, gc, dc):
op = core.CreateOperator(
name, ["X1", "X2"], ["X1" if in_place else "Y"], broadcast=1)
X1, X2 = inputs
self.assertDeviceChecks(dc, op, [X1, X2], [0])
def cast_ref(x, y):
return (np.array(ref(x, y)[0], dtype=x.dtype), )
# gradient not implemented yet
# self.assertGradientChecks(gc, op, [X1, X2], 0, [0])
self.assertReferenceChecks(gc, op, [X1, X2], cast_ref)
return test_binary_broadcast
class TestOperators(hu.HypothesisTestCase):
def test_comparison_ops(self):
ops = {"LT": lambda x1, x2: [x1 < x2],
"LE": lambda x1, x2: [x1 <= x2],
"GT": lambda x1, x2: [x1 > x2],
"GE": lambda x1, x2: [x1 >= x2]}
for name, ref in ops.items():
_test_binary(name, ref, gcs=hu.gcs_cpu_only)(self)
_test_binary_broadcast(name, ref, gcs=hu.gcs_cpu_only)(self)
@given(inputs=hu.tensors(n=2), in_place=st.booleans(), **hu.gcs)
def test_sum(self, inputs, in_place, gc, dc):
op = core.CreateOperator("Sum", ["X1", "X2"],
["Y" if not in_place else "X1"])
X1, X2 = inputs
self.assertDeviceChecks(dc, op, [X1, X2], [0])
self.assertGradientChecks(gc, op, [X1, X2], 0, [0])
def test_add(self):
def ref(x, y):
return (x + y, )
_test_binary("Add", ref, test_gradient=True)(self)
_test_binary_broadcast("Add", ref)(self)
def test_sub(self):
def ref(x, y):
return (x - y, )
# TODO(jiayq): enable gradient test when implemented.
_test_binary("Sub", ref, test_gradient=True)(self)
_test_binary_broadcast("Sub", ref)(self)
def test_mul(self):
def ref(x, y):
return (x * y, )
_test_binary("Mul", ref, test_gradient=True)(self)
_test_binary_broadcast("Mul", ref)(self)
def test_div(self):
def ref(x, y):
return (x / y, )
def non_zero(x):
return abs(x) > 10e-5
def div_dtypes():
return st.sampled_from([np.float32, np.float64])
_test_binary(
"Div", ref, filter_=non_zero, test_gradient=True,
dtypes=div_dtypes, gcs=hu.gcs_cpu_only
)(self)
_test_binary(
"Div", ref, filter_=non_zero, test_gradient=False,
dtypes=div_dtypes
)(self)
_test_binary_broadcast(
"Div", ref, filter_=non_zero, dtypes=div_dtypes)(self)
@given(X=hu.tensor(), in_place=st.booleans(), **hu.gcs)
def test_negative(self, X, in_place, gc, dc):
op = core.CreateOperator("Negative", ["X"],
["Y" if not in_place else "X"])
self.assertDeviceChecks(dc, op, [X], [0])
self.assertGradientChecks(gc, op, [X], 0, [0])
@given(X=hu.tensor(), **hu.gcs)
def test_relu(self, X, gc, dc):
op = core.CreateOperator("Relu", ["X"], ["Y"])
# go away from the origin point to avoid kink problems
X += 0.02 * np.sign(X)
X[X == 0.0] += 0.02
self.assertDeviceChecks(dc, op, [X], [0])
self.assertGradientChecks(gc, op, [X], 0, [0])
@given(X=hu.tensor(), **hu.gcs)
def test_averaged_loss(self, X, gc, dc):
op = core.CreateOperator("AveragedLoss", ["X"], ["loss"])
self.assertDeviceChecks(dc, op, [X], [0])
self.assertGradientChecks(gc, op, [X], 0, [0])
@given(
device_options=st.lists(
min_size=2,
max_size=4,
elements=st.sampled_from(hu.expanded_device_options)),
set_seed=st.booleans())
def test_random_seed_behaviour(self, device_options, set_seed):
# Assume we are always operating on CUDA or CPU, since RNG is
# inconsistent between CPU and GPU.
device_options = copy.deepcopy(device_options)
assume(len({do.device_type for do in device_options}) == 1)
if set_seed:
for do in device_options:
do.random_seed = 1000
def run(do):
op = core.CreateOperator(
"XavierFill", [], ["Y"],
device_option=do,
shape=[2])
workspace.RunOperatorOnce(op)
return workspace.FetchBlob("Y")
ys = [run(do) for do in device_options]
for y in ys[1:]:
if set_seed:
np.testing.assert_array_equal(ys[0], y)
else:
with self.assertRaises(AssertionError):
np.testing.assert_array_equal(ys[0], y)
@given(axis=st.integers(min_value=1, max_value=4),
num_output=st.integers(min_value=4, max_value=8),
**hu.gcs)
def test_fully_connected_axis(self, axis, num_output, gc, dc):
np.random.seed(1)
X = np.random.randn(1, 2, 3, 2, 1).astype(np.float32)
def prod(xs):
p = 1
for x in xs:
p *= x
return p
K = prod(list(X.shape)[axis:])
N = num_output
W = np.random.randn(N, K).astype(np.float32)
b = np.random.randn(N).astype(np.float32)
op = core.CreateOperator(
"FC",
["X", "W", "b"],
["Y"],
axis=axis)
for name, param in [("X", X), ("W", W), ("b", b)]:
workspace.FeedBlob(name, param)
workspace.RunOperatorOnce(op)
Y = workspace.FetchBlob("Y")
self.assertEqual(list(Y.shape), list(X.shape)[:axis] + [N])
inputs = [X, W, b]
self.assertDeviceChecks(dc, op, inputs, [0])
for param, _ in enumerate(inputs):
self.assertGradientChecks(gc, op, inputs, param, [0])
@unittest.skipIf(not workspace.has_gpu_support,
"Skipping test due to no gpu present.")
@given(hidden_size=st.integers(min_value=1, max_value=3),
num_layers=st.integers(min_value=1, max_value=3),
bidirectional=st.booleans(),
rnn_mode=st.sampled_from(["gru", "lstm"]),
input_mode=st.sampled_from(["linear"]),
dropout=st.floats(min_value=0.0, max_value=0.0),
T=st.integers(min_value=1, max_value=4),
N=st.integers(min_value=1, max_value=4),
D=st.integers(min_value=1, max_value=4))
def test_recurrent(self, hidden_size, num_layers, bidirectional, rnn_mode,
input_mode, dropout, T, N, D):
init_op = core.CreateOperator(
"RecurrentInit",
["INPUT"],
["WEIGHT", "DROPOUT_STATES"],
hidden_size=hidden_size,
bidirectional=bidirectional,
rnn_mode=rnn_mode,
dropout=dropout,
input_mode=input_mode,
num_layers=num_layers,
device_option=hu.gpu_do,
engine="CUDNN")
op = core.CreateOperator(
"Recurrent",
["INPUT", "HIDDEN_INPUT", "CELL_INPUT", "WEIGHT"],
["OUTPUT", "HIDDEN_OUTPUT", "CELL_OUTPUT",
"RNN_SCRATCH", "DROPOUT_STATES"],
hidden_size=hidden_size,
bidirectional=bidirectional,
rnn_mode=rnn_mode,
dropout=dropout,
input_mode=input_mode,
num_layers=num_layers,
engine="CUDNN")
num_directions = 2 if bidirectional else 1
X = np.random.randn(T, N, D).astype(np.float32)
workspace.FeedBlob("INPUT", X, device_option=hu.gpu_do)
workspace.RunOperatorOnce(init_op)
W = workspace.FetchBlob("WEIGHT")
H = np.random.randn(
hidden_size, N, num_layers * num_directions).astype(
np.float32)
C = np.random.randn(
hidden_size, N, num_layers * num_directions).astype(
np.float32) if rnn_mode == "lstm" else \
np.empty((1,)).astype(np.float32) # unused in GRU
inputs = [X, H, C, W]
input_idxs = [i for (i, _) in enumerate(inputs)] \
if rnn_mode == "lstm" else [0, 1, 3] # ignore C
for input_idx in input_idxs:
self.assertGradientChecks(
hu.gpu_do, op, inputs, input_idx, [0, 1, 2])
@given(ndim=st.integers(1, 4),
axis=st.integers(0, 3),
num_inputs=st.integers(2, 4), **hu.gcs)
def test_depth_concat(self, ndim, axis, num_inputs, gc, dc):
if (axis >= ndim):
return
input_names = ['X0', 'X1', 'X2', 'X3'][:num_inputs]
shape = [2, 3, 5, 7][:ndim]
individual_dims = [11, 13, 17, 19][:num_inputs]
inputs = []
for i in range(num_inputs):
# Sets a unique dim and create the input.
shape[axis] = individual_dims[i]
inputs.append(np.random.rand(*shape).astype(np.float32))
op = core.CreateOperator("Concat", input_names, ["Y", "Y_dims"],
axis=axis)
self.assertDeviceChecks(dc, op, inputs, [0])
for i in range(num_inputs):
self.assertGradientChecks(gc, op, inputs, i, [0])
@given(num_inputs=st.integers(2, 4),
order=st.sampled_from([("NCHW", 1), ("NHWC", 3)]),
**hu.gcs)
def test_depth_concat_with_order(self, num_inputs, order, gc, dc):
input_names = ['X0', 'X1', 'X2', 'X3'][:num_inputs]
shape = [2, 3, 5, 7]
individual_dims = [11, 13, 17, 19][:num_inputs]
inputs = []
for i in range(num_inputs):
# Sets a unique dim and create the input.
shape[order[1]] = individual_dims[i]
inputs.append(np.random.rand(*shape).astype(np.float32))
op = core.CreateOperator("Concat", input_names, ["Y", "Y_dims"],
order=order[0])
self.assertDeviceChecks(dc, op, inputs, [0])
for i in range(num_inputs):
self.assertGradientChecks(gc, op, inputs, i, [0])
# CUDNN does NOT support different padding values and we skip it
@given(stride_h=st.integers(1, 3),
stride_w=st.integers(1, 3),
pad_t=st.integers(0, 3),
pad_l=st.integers(0, 3),
pad_b=st.integers(0, 3),
pad_r=st.integers(0, 3),
kernel=st.integers(3, 5),
size=st.integers(8, 8),
input_channels=st.integers(1, 3),
output_channels=st.integers(1, 3),
batch_size=st.integers(1, 3),
order=st.sampled_from(["NCHW", "NHWC"]),
engine=st.sampled_from([""]),
**hu.gcs)
@settings(max_examples=2, timeout=100)
def test_convolution_separate_stride_pad_gradients(self, stride_h, stride_w,
pad_t, pad_l, pad_b,
pad_r, kernel, size,
input_channels,
output_channels,
batch_size, order,
engine, gc, dc):
assume(stride_h <= kernel)
assume(stride_w <= kernel)
op = core.CreateOperator(
"Conv",
["X", "w", "b"],
["Y"],
stride_h=stride_h,
stride_w=stride_w,
pad_t=pad_t,
pad_l=pad_l,
pad_b=pad_b,
pad_r=pad_r,
kernel=kernel,
order=order,
engine=engine,
)
X = np.random.rand(
batch_size, size, size, input_channels).astype(np.float32) - 0.5
w = np.random.rand(
output_channels, kernel, kernel, input_channels).astype(np.float32)\
- 0.5
b = np.random.rand(output_channels).astype(np.float32) - 0.5
if order == "NCHW":
X = X.transpose((0, 3, 1, 2))
w = w.transpose((0, 3, 1, 2))
self.assertDeviceChecks(dc, op, [X, w, b], [0])
for i in range(3):
self.assertGradientChecks(gc, op, [X, w, b], i, [0])
# CUDNN does NOT support different padding values and we skip it
@given(stride_h=st.integers(1, 3),
stride_w=st.integers(1, 3),
pad_t=st.integers(0, 3),
pad_l=st.integers(0, 3),
pad_b=st.integers(0, 3),
pad_r=st.integers(0, 3),
kernel=st.integers(1, 5),
size=st.integers(7, 10),
input_channels=st.integers(1, 8),
output_channels=st.integers(1, 8),
batch_size=st.integers(1, 3),
engine=st.sampled_from([""]), **hu.gcs)
def test_convolution_separate_stride_pad_layout(self, stride_h, stride_w,
pad_t, pad_l, pad_b, pad_r,
kernel, size,
input_channels,
output_channels, batch_size,
engine, gc, dc):
assume(stride_h <= kernel)
assume(stride_w <= kernel)
X = np.random.rand(
batch_size, size, size, input_channels).astype(np.float32) - 0.5
w = np.random.rand(
output_channels, kernel, kernel, input_channels).astype(np.float32)\
- 0.5
b = np.random.rand(output_channels).astype(np.float32) - 0.5
outputs = {}
for order in ["NCHW", "NHWC"]:
op = core.CreateOperator(
"Conv",
["X", "w", "b"],
["Y"],
stride_h=stride_h,
stride_w=stride_w,
kernel=kernel,
pad_t=pad_t,
pad_l=pad_l,
pad_b=pad_b,
pad_r=pad_r,
order=order,
engine=engine,
device_option=gc,
)
if order == "NCHW":
X_f = X.transpose((0, 3, 1, 2))
w_f = w.transpose((0, 3, 1, 2))
else:
X_f = X
w_f = w
workspace.FeedBlob("X", X_f, device_option=gc)
workspace.FeedBlob("w", w_f, device_option=gc)
workspace.FeedBlob("b", b, device_option=gc)
workspace.RunOperatorOnce(op)
outputs[order] = workspace.FetchBlob("Y")
np.testing.assert_allclose(
outputs["NCHW"],
outputs["NHWC"].transpose((0, 3, 1, 2)),
atol=1e-4,
rtol=1e-4)
@given(stride=st.integers(1, 3),
pad=st.integers(0, 3),
kernel=st.integers(1, 5),
size=st.integers(7, 10),
input_channels=st.integers(1, 8),
output_channels=st.integers(1, 8),
batch_size=st.integers(1, 3),
order=st.sampled_from(["NCHW", "NHWC"]),
engine=st.sampled_from(["", "CUDNN"]),
**hu.gcs)
@settings(max_examples=2, timeout=100)
def test_convolution_gradients(self, stride, pad, kernel, size,
input_channels, output_channels, batch_size,
order, engine, gc, dc):
assume(stride <= kernel)
op = core.CreateOperator(
"Conv",
["X", "w", "b"],
["Y"],
stride=stride,
kernel=kernel,
pad=pad,
order=order,
engine=engine,
)
X = np.random.rand(
batch_size, size, size, input_channels).astype(np.float32) - 0.5
w = np.random.rand(
output_channels, kernel, kernel, input_channels).astype(np.float32)\
- 0.5
b = np.random.rand(output_channels).astype(np.float32) - 0.5
if order == "NCHW":
X = X.transpose((0, 3, 1, 2))
w = w.transpose((0, 3, 1, 2))
self.assertDeviceChecks(dc, op, [X, w, b], [0])
for i in range(3):
self.assertGradientChecks(gc, op, [X, w, b], i, [0])
@given(stride=st.integers(1, 3),
pad=st.integers(0, 3),
kernel=st.integers(1, 5),
size=st.integers(7, 10),
input_channels=st.integers(1, 8),
output_channels=st.integers(1, 8),
batch_size=st.integers(1, 3),
engine=st.sampled_from(["", "CUDNN"]), **hu.gcs)
def test_convolution_layout(self, stride, pad, kernel, size,
input_channels, output_channels, batch_size,
engine, gc, dc):
assume(stride <= kernel)
X = np.random.rand(
batch_size, size, size, input_channels).astype(np.float32) - 0.5
w = np.random.rand(
output_channels, kernel, kernel, input_channels).astype(np.float32)\
- 0.5
b = np.random.rand(output_channels).astype(np.float32) - 0.5
outputs = {}
for order in ["NCHW", "NHWC"]:
op = core.CreateOperator(
"Conv",
["X", "w", "b"],
["Y"],
stride=stride,
kernel=kernel,
pad=pad,
order=order,
engine=engine,
device_option=gc,
)
if order == "NCHW":
X_f = X.transpose((0, 3, 1, 2))
w_f = w.transpose((0, 3, 1, 2))
else:
X_f = X
w_f = w
workspace.FeedBlob("X", X_f, device_option=gc)
workspace.FeedBlob("w", w_f, device_option=gc)
workspace.FeedBlob("b", b, device_option=gc)
workspace.RunOperatorOnce(op)
outputs[order] = workspace.FetchBlob("Y")
np.testing.assert_allclose(
outputs["NCHW"],
outputs["NHWC"].transpose((0, 3, 1, 2)),
atol=1e-4,
rtol=1e-4)
@given(num_workers=st.integers(1, 4),
net_type=st.sampled_from(
["simple", "dag"] +
(["async_dag"] if workspace.has_gpu_support else [])),
do=st.sampled_from(hu.device_options),
engine=st.sampled_from(["CUDNN", ""]))
def test_convolution_sync(self, net_type, num_workers, do, engine):
from caffe2.python.cnn import CNNModelHelper
m = CNNModelHelper()
n = 1
d = 2
depth = 3
iters = 5
h = 5
w = 5
workspace.ResetWorkspace()
np.random.seed(1701)
# Build a binary tree of conv layers, summing at each node.
for i in reversed(range(depth)):
for j in range(2 ** i):
bottom_1 = "{}_{}".format(i + 1, 2 * j)
bottom_2 = "{}_{}".format(i + 1, 2 * j + 1)
mid_1 = "{}_{}_m".format(i + 1, 2 * j)
mid_2 = "{}_{}_m".format(i + 1, 2 * j + 1)
top = "{}_{}".format(i, j)
w1, b1, w2, b2 = np.random.randn(4).tolist()
m.Conv(
bottom_1, mid_1,
dim_in=d, dim_out=d,
kernel=3,
weight_init=m.ConstantInit(w1),
bias_init=m.ConstantInit(b1),
cudnn_state=np.random.randint(0, 3),
stride=1,
pad=1,
deterministic=1,
engine=engine)
m.Conv(
bottom_2, mid_2,
dim_in=d, dim_out=d,
kernel=3,
stride=1,
pad=1,
weight_init=m.ConstantInit(w2),
bias_init=m.ConstantInit(b2),
deterministic=1,
cudnn_state=np.random.randint(0, 3),
engine=engine)
m.net.Sum([mid_1, mid_2], top)
m.net.Flatten(["0_0"], ["0_0_flat"])
m.net.SquaredL2Distance(["0_0_flat", "label"], "xent")
m.net.AveragedLoss("xent", "loss")
input_to_grad = m.AddGradientOperators(["loss"])
m.Proto().device_option.CopyFrom(do)
m.param_init_net.Proto().device_option.CopyFrom(do)
m.Proto().type = net_type
m.Proto().num_workers = num_workers
workspace.RunNetOnce(m.param_init_net)
def run():
import numpy as np
np.random.seed(1701)
input_blobs = ["{}_{}".format(depth, j) for j in range(2 ** depth)]
for input_blob in input_blobs:
workspace.FeedBlob(
input_blob,
np.random.randn(n, d, h, w).astype(np.float32),
device_option=do)
workspace.FeedBlob(
"label",
np.random.randn(n, d * h * w).astype(np.float32),
device_option=do)
workspace.RunNetOnce(m.net)
gradients = [
workspace.FetchBlob(str(input_to_grad[input_blob]))
for input_blob in input_blobs]
return gradients
outputs = [run() for _ in range(iters)]
for output in outputs[1:]:
np.testing.assert_array_equal(outputs[0], output)
np.testing.assert_allclose(
np.sum(np.square(output)),
1763719461732352.0,
rtol=1e-5)
@given(stride=st.integers(1, 3),
pad=st.integers(0, 3),
kernel=st.integers(1, 5),
adj=st.integers(0, 2),
size=st.integers(7, 10),
input_channels=st.integers(1, 8),
output_channels=st.integers(1, 8),
batch_size=st.integers(1, 3),
order=st.sampled_from(["NCHW", "NHWC"]),
engine=st.sampled_from(["", "CUDNN"]), **hu.gcs)
@settings(max_examples=2, timeout=100)
def test_convolution_transpose_gradients(self, stride, pad, kernel, adj,
size, input_channels,
output_channels, batch_size,
order, engine, gc, dc):
assume(stride <= kernel)
assume(adj < stride)
X = np.random.rand(
batch_size, size, size, input_channels).astype(np.float32) - 0.5
w = np.random.rand(
input_channels, kernel, kernel, output_channels)\
.astype(np.float32) - 0.5
b = np.random.rand(output_channels).astype(np.float32) - 0.5
op = core.CreateOperator(
"ConvTranspose",
["X", "w", "b"],
["Y"],
stride=stride,
kernel=kernel,
pad=pad,
adj=adj,
order=order,
engine=engine,
)
if order == "NCHW":
X = X.transpose((0, 3, 1, 2))
w = w.transpose((0, 3, 1, 2))
self.assertDeviceChecks(dc, op, [X, w, b], [0])
for i in range(3):
self.assertGradientChecks(gc, op, [X, w, b], i, [0])
@given(stride=st.integers(1, 3),
pad=st.integers(0, 3),
kernel=st.integers(1, 5),
adj=st.integers(0, 2),
size=st.integers(7, 10),
input_channels=st.integers(1, 8),
output_channels=st.integers(1, 8),
batch_size=st.integers(1, 3),
engine=st.sampled_from(["", "CUDNN"]), **hu.gcs)
def test_convolution_transpose_layout(self, stride, pad, kernel, adj,
size, input_channels,
output_channels, batch_size,
engine, gc, dc):
assume(stride <= kernel)
assume(adj < stride)
X = np.random.rand(
batch_size, size, size, input_channels).astype(np.float32) - 0.5
w = np.random.rand(
input_channels, kernel, kernel, output_channels)\
.astype(np.float32) - 0.5
b = np.random.rand(output_channels).astype(np.float32) - 0.5
outputs = {}
for order in ["NCHW", "NHWC"]:
op = core.CreateOperator(
"ConvTranspose",
["X", "w", "b"],
["Y"],
stride=stride,
kernel=kernel,
pad=pad,
adj=adj,
order=order,
engine=engine,
device_option=gc,
)
if order == "NCHW":
X_f = X.transpose((0, 3, 1, 2))
w_f = w.transpose((0, 3, 1, 2))
else:
X_f = X
w_f = w
workspace.FeedBlob("X", X_f, device_option=gc)
workspace.FeedBlob("w", w_f, device_option=gc)
workspace.FeedBlob("b", b, device_option=gc)
workspace.RunOperatorOnce(op)
outputs[order] = workspace.FetchBlob("Y")
output_size = (size - 1) * stride + kernel + adj - 2 * pad
self.assertEqual(
outputs["NCHW"].shape,
(batch_size, output_channels, output_size, output_size))
np.testing.assert_allclose(
outputs["NCHW"],
outputs["NHWC"].transpose((0, 3, 1, 2)),
atol=1e-4,
rtol=1e-4)
@given(dtype=st.sampled_from([np.float32, np.float64, np.int32, np.bool]))
def test_print(self, dtype):
data = np.random.permutation(6).astype(dtype)
workspace.FeedBlob("data", data)
op = core.CreateOperator("Print", "data", [])
self.assertTrue(workspace.RunOperatorOnce(op))
@given(inputs=hu.tensors(n=3),
in_place=st.booleans(),
beta1=st.floats(min_value=0.1, max_value=0.9),
beta2=st.floats(min_value=0.1, max_value=0.9),
lr=st.floats(min_value=0.1, max_value=0.9),
iters=st.integers(min_value=1, max_value=10000),
epsilon=st.floats(min_value=1e-5, max_value=1e-2),
**hu.gcs)
def test_adam_sgd(self, inputs, in_place, beta1, beta2, lr, iters, epsilon,
gc, dc):
grad, m1, m2 = inputs
m2 += np.abs(m2) + 0.01
lr = np.asarray([lr], dtype=np.float32)
iters = np.asarray([iters], dtype=np.int32)
op = core.CreateOperator(
"Adam",
["grad", "m1", "m2", "lr", "iters"],
["grad" if in_place else "grad_o",
"m1" if in_place else "m1_o",
"m2" if in_place else "m2_o"],
beta1=beta1, beta2=beta2, epsilon=epsilon,
device_option=gc)
input_device_options = {"iters": hu.cpu_do}
self.assertDeviceChecks(
dc, op, [grad, m1, m2, lr, iters], [0], input_device_options)
# Reference
def adam(grad, m1, m2, lr, iters):
lr = lr[0]
iters = iters[0]
t = iters + 1
corrected_local_rate = lr * np.sqrt(1. - np.power(beta2, t)) / \
(1. - np.power(beta1, t))
m1_o = (beta1 * m1) + (1. - beta1) * grad
m2_o = (beta2 * m2) + (1. - beta2) * np.square(grad)
grad_o = corrected_local_rate * m1_o / \
(np.sqrt(m2_o) + epsilon)
return (grad_o, m1_o, m2_o)
self.assertReferenceChecks(gc, op, [grad, m1, m2, lr, iters],
adam, input_device_options)
@given(inputs=hu.tensors(n=2),
in_place=st.booleans(),
momentum=st.floats(min_value=0.1, max_value=0.9),
nesterov=st.booleans(),
lr=st.floats(min_value=0.1, max_value=0.9),
**hu.gcs)
def test_momentum_sgd(
self, inputs, in_place, momentum, nesterov, lr, gc, dc):
grad, m = inputs
lr = np.asarray([lr], dtype=np.float32)
op = core.CreateOperator(
"MomentumSGD",
["grad", "m", "lr"],
["grad" if in_place else "grad_o",
"m" if in_place else "m_o"],
momentum=momentum,
nesterov=int(nesterov),
device_option=gc)
self.assertDeviceChecks(
dc, op, [grad, m, lr], [0])
# Reference
def momentum_sgd(grad, m, lr):
lr = lr[0]
if not nesterov:
adjusted_gradient = lr * grad + momentum * m
return (adjusted_gradient, adjusted_gradient)
else:
m_new = momentum * m + lr * grad
return ((1 + momentum) * m_new - momentum * m, m_new)
self.assertReferenceChecks(gc, op, [grad, m, lr], momentum_sgd)
@given(inputs=hu.tensors(n=3),
in_place=st.booleans(),
decay=st.floats(min_value=0.1, max_value=0.9),
momentum=st.floats(min_value=0.1, max_value=0.9),
lr=st.floats(min_value=0.1, max_value=0.9),
epsilon=st.floats(min_value=1e-5, max_value=1e-2),
**hu.gcs)
def test_rmsprop_sgd(self, inputs, in_place, decay, momentum, lr, epsilon,
gc, dc):
grad, ms, mom = inputs
ms = np.abs(ms) + 0.01
lr = np.asarray([lr], dtype=np.float32)
op = core.CreateOperator(
"RmsProp",
["grad", "ms", "mom", "lr"],
["grad" if in_place else "grad_o",
"ms" if in_place else "ms_o",
"mom" if in_place else "mom_o"],
momentum=momentum, decay=decay, epsilon=epsilon, device_option=gc)
self.assertDeviceChecks(dc, op, [grad, ms, mom, lr], [0])
def rmsprop(grad, ms, mom, lr):
lr = lr[0]
ms_o = ms + (1. - decay) * (np.square(grad) - ms)
mom_o = momentum * mom + lr * grad / np.sqrt(epsilon + ms_o)
grad_o = mom_o
return (grad_o, ms_o, mom_o)
self.assertReferenceChecks(gc, op, [grad, ms, mom, lr], rmsprop)
@staticmethod
def _dense_adagrad(epsilon, grad, h, lr):
lr = lr[0]
h_o = h + np.square(grad)
grad_o = lr * grad / (np.sqrt(h_o) + epsilon)
return (grad_o, h_o)
@given(inputs=hu.tensors(n=2),
in_place=st.booleans(),
lr=st.floats(min_value=0.1, max_value=0.9),
epsilon=st.floats(min_value=1e-5, max_value=1e-2),
**hu.gcs)
def test_adagrad_sgd(self, inputs, in_place, lr, epsilon,
gc, dc):
grad, h = inputs
h = np.abs(h) + 0.01
lr = np.asarray([lr], dtype=np.float32)
op = core.CreateOperator(
"Adagrad",
["grad", "h", "lr"],
["grad" if in_place else "grad_o",
"h" if in_place else "h_o"],
epsilon=epsilon, device_option=gc)
self.assertDeviceChecks(dc, op, [grad, h, lr], [0])
self.assertReferenceChecks(gc, op, [grad, h, lr],
partial(self._dense_adagrad, epsilon))
@given(inputs=hu.tensors(n=2),
lr=st.floats(min_value=0.1, max_value=0.9),
epsilon=st.floats(min_value=1e-5, max_value=1e-2),
**hu.gcs_cpu_only)
def test_sparse_adagrad_sgd(self, inputs, lr, epsilon,
gc, dc):
grad, h = inputs
indices = np.arange(h.shape[0])
indices = indices[indices % 2 == 0]
grad = grad[indices]
h = np.abs(h)
lr = np.asarray([lr], dtype=np.float32)
op = core.CreateOperator(
"SparseAdagrad",
["indices", "grad", "h", "lr"],
["grad", "h"],
epsilon=epsilon,
device_option=gc)
self.assertDeviceChecks(
dc, op, [indices, grad, h, lr], [0])
def adagrad(i, grad, h, lr):
sg, sh = self._dense_adagrad(epsilon, grad, h[i], lr)
h[i] = sh
return (sg, h)
self.assertReferenceChecks(gc, op, [indices, grad, h, lr], adagrad)
# Reference
@staticmethod
def _dense_ftrl(alpha, beta, lambda1, lambda2, w, nz, g):
n = np.take(nz, 0, axis=-1)
z = np.take(nz, 1, axis=-1)
# python port of Sigrid's implementation
g2 = g * g
sigma = (np.sqrt(n + g2) - np.sqrt(n)) / alpha
z += g - sigma * w
n += g2
w = (np.sign(z) * lambda1 - z) / (
(beta + np.sqrt(n)) / alpha + lambda2)
w[np.abs(z) <= lambda1] = 0
return (w, np.stack([n, z], axis=-1))
@given(inputs=hu.tensors(n=4),
in_place=st.booleans(),
alpha=st.floats(min_value=0.01, max_value=0.1),
beta=st.floats(min_value=0.1, max_value=0.9),
lambda1=st.floats(min_value=0.001, max_value=0.1),
lambda2=st.floats(min_value=0.001, max_value=0.1),
engine=st.sampled_from([None, "SIMD"]),
**hu.gcs_cpu_only)
def test_ftrl_sgd(self, inputs, in_place, alpha, beta, lambda1, lambda2,
engine, gc, dc):
var, n, z, grad = inputs
n = np.abs(n)
nz = np.stack([n, z], axis=-1)
op = core.CreateOperator(
"Ftrl",
["var", "nz", "grad"],
["var" if in_place else "var_o",
"nz" if in_place else "nz_o"],
alpha=alpha, beta=beta, lambda1=lambda1, lambda2=lambda2,
engine=engine,
device_option=gc)
self.assertDeviceChecks(
dc, op, [var, nz, grad], [0])
self.assertReferenceChecks(
gc, op, [var, nz, grad],
partial(self._dense_ftrl, alpha, beta, lambda1, lambda2))
@given(inputs=hu.tensors(n=4),
alpha=st.floats(min_value=0.01, max_value=0.1),
beta=st.floats(min_value=0.1, max_value=0.9),
lambda1=st.floats(min_value=0.001, max_value=0.1),
lambda2=st.floats(min_value=0.001, max_value=0.1),
engine=st.sampled_from([None, "SIMD"]),
**hu.gcs_cpu_only)
def test_sparse_ftrl_sgd(self, inputs, alpha, beta, lambda1, lambda2,
engine, gc, dc):
var, n, z, grad = inputs
# generate fake subset manually because hypothesis is too complicated :)
indices = np.arange(var.shape[0])
indices = indices[indices % 2 == 0]
grad = grad[indices]
n = np.abs(n)
nz = np.stack([n, z], axis=-1)
op = core.CreateOperator(
"SparseFtrl",
["var", "nz", "indices", "grad"],
["var", "nz"],
alpha=alpha, beta=beta, lambda1=lambda1, lambda2=lambda2,
engine=engine,
device_option=gc)
self.assertDeviceChecks(
dc, op, [var, nz, indices, grad], [0])
# Reference
def ftrl(w, nz, i, g):
sw, snz = self._dense_ftrl(alpha, beta, lambda1, lambda2,
w[i], nz[i], g)
w[i] = sw
nz[i] = snz
return (w, nz)
self.assertReferenceChecks(gc, op, [var, nz, indices, grad], ftrl)
@given(input=hu.tensor(max_value=20,
max_dim=1,
dtype=np.int32,
elements=st.integers(min_value=0, max_value=10)),
with_remapping=st.booleans(),
**hu.gcs_cpu_only)
def test_unique(self, input, with_remapping, gc, dc):
op = core.CreateOperator(
"Unique",
["input"],
["unique"] + (["remapping"] if with_remapping else []),
device_option=gc)
self.assertDeviceChecks(dc, op, [input], [0])
# Validator
def unique_valid(input, unique, remapping=None):
self.assertEqual(unique.size, len(set(input)))
self.assertEqual(sorted(unique), sorted(set(input)))
if with_remapping:
self.assertEqual(remapping.shape, input.shape)
remapped = [unique[remapping[i]] for i in range(len(input))]
np.testing.assert_array_equal(remapped, input)
self.assertValidationChecks(gc, op, [input], unique_valid)
@given(prediction=hu.arrays(dims=[10, 3],
elements=st.floats(allow_nan=False,
allow_infinity=False,
min_value=0,
max_value=1)),
labels=hu.arrays(dims=[10],
dtype=np.int32,
elements=st.integers(min_value=0,
max_value=3 - 1)),
**hu.gcs)
def test_accuracy(self, prediction, labels, gc, dc):
op = core.CreateOperator(
"Accuracy",
["prediction", "labels"],
["accuracy"]
)
def op_ref(prediction, labels):
N = prediction.shape[0]
correct = 0
max_ids = np.argmax(prediction, axis=1)
for i in range(0, N):
if max_ids[i] == labels[i]:
correct += 1
accuracy = correct / N
return (accuracy,)
self.assertReferenceChecks(
device_option=gc,
op=op,
inputs=[prediction, labels],
reference=op_ref)
@given(target_probabilities=hu.arrays(
dims=[10], elements=st.floats(allow_nan=False,
allow_infinity=False,
min_value=0.01,
max_value=1)),
**hu.gcs)
def test_perplexity(self, target_probabilities, gc, dc):
op = core.CreateOperator(
"Perplexity",
["target_probabilities"],
["perplexity"]
)
def op_ref(target_probabilities):
N = target_probabilities.shape[0]
perplexities = np.power(target_probabilities, -1.0 / N)
perplexity = reduce(lambda x, y: x * y, perplexities)
return (perplexity,)
self.assertReferenceChecks(
device_option=gc,
op=op,
inputs=[target_probabilities],
reference=op_ref)
@given(lengths=st.lists(st.integers(min_value=0, max_value=10),
min_size=0,
max_size=10),
**hu.gcs_cpu_only)
def test_lengths_to_segment_ids(self, lengths, gc, dc):
op = core.CreateOperator(
"LengthsToSegmentIds",
["lengths"],
["segment_ids"])
def op_ref(lengths):
sids = []
for i, l in enumerate(lengths):
sids.extend(l * [i])
return (np.array(sids, dtype=int), )
self.assertReferenceChecks(
device_option=gc,
op=op,
inputs=[np.array(lengths, dtype=int)],
reference=op_ref)
@given(prediction=hu.arrays(dims=[10, 3],
elements=st.floats(allow_nan=False,
allow_infinity=False,
min_value=0,
max_value=1)),
labels=hu.arrays(dims=[10],
dtype=np.int32,
elements=st.integers(min_value=0,
max_value=3 - 1)),
**hu.gcs)
def test_multi_class_accuracy(self, prediction, labels, gc, dc):
op = core.CreateOperator(
"MultiClassAccuracy",
["prediction", "labels"],
["accuracies", "amounts"]
)
def op_ref(prediction, labels):
N = prediction.shape[0]
D = prediction.shape[1]
accuracies = np.empty(D, dtype=float)
accuracies.fill(0)
amounts = np.empty(D, dtype=int)
amounts.fill(0)
max_ids = np.argmax(prediction, axis=1)
for i in range(0, N):
max_id = max_ids[i]
label_id = labels[i]
if max_id == label_id:
accuracies[label_id] += 1
amounts[label_id] += 1
for i in range(0, D):
amount = amounts[i]
if amount:
accuracies[i] /= amount
return (accuracies, amounts,)
self.assertReferenceChecks(
device_option=gc,
op=op,
inputs=[prediction, labels],
reference=op_ref)
@given(lengths=st.lists(st.integers(min_value=0, max_value=10),
min_size=0,
max_size=10),
**hu.gcs_cpu_only)
def test_segment_ids_to_lengths(self, lengths, gc, dc):
op = core.CreateOperator(
"SegmentIdsToLengths",
["segment_ids"],
["lengths"])
def lengths_to_ids(lengths):
sids = []
for i, l in enumerate(lengths):
sids.extend(l * [i])
return sids
segment_ids = lengths_to_ids(lengths)
def ids_to_lengths(ids):
ids_length = len(ids)
if ids_length == 0:
return (np.array([], dtype=int),)
lengths = []
# segment id starts with 0
prev_id = -1
tmp_length = 0
for idx in range(ids_length):
cur_id = ids[idx]
if cur_id != prev_id:
if idx != 0:
lengths.append(tmp_length)
while prev_id + 1 != cur_id:
lengths.append(0)
prev_id += 1
prev_id = cur_id
tmp_length = 0
tmp_length += 1
lengths.append(tmp_length)
return (np.array(lengths, dtype=int),)
self.assertReferenceChecks(
device_option=gc,
op=op,
inputs=[np.array(segment_ids, dtype=int)],
reference=ids_to_lengths)
@given(input_tensor=hu.arrays(
dims=[10], elements=st.floats(allow_nan=False,
allow_infinity=False)),
**hu.gcs)
def test_exp(self, input_tensor, gc, dc):
op = core.CreateOperator(
"Exp",
["input"],
["output"]
)
def exp_ref(input_tensor):
return (np.exp(input_tensor),)
self.assertReferenceChecks(
device_option=gc,
op=op,
inputs=[input_tensor],
reference=exp_ref)
@given(num_threads=st.integers(1, 10), # noqa
num_elements=st.integers(1, 100),
capacity=st.integers(1, 5),
num_blobs=st.integers(1, 3),
do=st.sampled_from(hu.device_options))
def test_blobs_queue_threading(self, num_threads, num_elements,
capacity, num_blobs, do):
"""
- Construct matrices of size N x D
- Start K threads
- Push all N rows into the queue of capacity C
- Pull all N rows out of the queue.
- Verify that the output matrices are permutation of the rows of the
original matrices.
"""
import threading
import Queue
op = core.CreateOperator(
"CreateBlobsQueue",
[],
["queue"],
capacity=capacity,
num_blobs=num_blobs,
device_option=do)
workspace.RunOperatorOnce(op)
xs = [np.random.randn(num_elements, 5).astype(np.float32)
for _ in range(num_blobs)]
q = Queue.Queue()
for i in range(num_elements):
q.put([x[i] for x in xs])
def enqueue(t):
while True:
feed_blobs = ["x_{}_{}".format(i, t) for i in range(num_blobs)]
op = core.CreateOperator(
"EnqueueBlobs",
["queue"] + feed_blobs,
feed_blobs,
device_option=do)
try:
elems = q.get_nowait()
for elem, feed_blob in zip(elems, feed_blobs):
workspace.FeedBlob(feed_blob, elem, device_option=do)
workspace.RunOperatorOnce(op)
except Queue.Empty:
return
# Create all blobs before racing on multiple threads
# (blob creation is not threadsafe)
for t in range(num_threads):
for i in range(num_blobs):
workspace.CreateBlob("x_{}_{}".format(i, t))
threads = [threading.Thread(target=enqueue, args=(t,))
for t in range(num_threads)]
for thread in threads:
thread.start()
for n in range(num_elements):
dequeue_blobs = ["y_{}_{}".format(i, n) for i in range(num_blobs)]
op = core.CreateOperator(
"DequeueBlobs",
["queue"],
dequeue_blobs,
device_option=do)
workspace.RunOperatorOnce(op)
for thread in threads:
thread.join()
op = core.CreateOperator("CloseBlobsQueue", ["queue"], [])
workspace.RunOperatorOnce(op)
ys = [np.vstack([workspace.FetchBlob("y_{}_{}".format(i, n))
for n in range(num_elements)])
for i in range(num_blobs)]
for i in range(num_blobs):
self.assertEqual(ys[i].shape, xs[i].shape)
for j in range(num_elements):
# Verify that the rows of the returned blob are a
# permutation. The order may be different due to
# different threads racing.
self.assertTrue(
any(np.array_equal(xs[i][j], ys[i][k])
for k in range(num_elements)))
@given(num_producers=st.integers(1, 10),
num_consumers=st.integers(1, 10),
capacity=st.integers(1, 5),
num_blobs=st.integers(1, 3),
do=st.sampled_from(hu.device_options))
def test_safe_blobs_queue(self, num_producers, num_consumers,
capacity, num_blobs, do):
init_net = core.Net('init_net')
queue = init_net.CreateBlobsQueue(
[], 1, capacity=capacity, num_blobs=num_blobs)
producer_steps = []
truth = 0
for i in range(num_producers):
name = 'producer_%d' % i
net = core.Net(name)
blobs = [net.ConstantFill([], 1, value=1.0, run_once=False)
for times in range(num_blobs)]
status = net.NextName()
net.SafeEnqueueBlobs([queue] + blobs, blobs + [status])
count = (i + 1) * 10
step = core.execution_step(name, net, num_iter=count)
truth += count
producer_steps.append(step)
producer_exit_net = core.Net('producer_exit_net')
producer_exit_net.CloseBlobsQueue([queue], 0)
producer_step = core.execution_step('producer', [
core.execution_step(
'producers', producer_steps, concurrent_substeps=True),
core.execution_step('producer_exit', producer_exit_net)]
)
consumer_steps = []
counters = []
const_1 = init_net.ConstantFill([], 1, value=1.0)
for i in range(num_consumers):
name = 'consumer_%d' % i
net1 = core.Net(name)
blobs = net1.SafeDequeueBlobs([queue], num_blobs + 1)
status = blobs[-1]
net2 = core.Net(name + '_counter')
counter = init_net.ConstantFill([], 1, value=0.0)
counters.append(counter)
net2.Add([counter, const_1], counter)
consumer_steps.append(core.execution_step(
name, [net1, net2], should_stop_blob=status))
consumer_step = core.execution_step(
'consumer', consumer_steps, concurrent_substeps=True)
init_step = core.execution_step('init', init_net)
worker_step = core.execution_step(
'worker', [consumer_step, producer_step], concurrent_substeps=True)
plan = core.Plan('test')
plan.AddStep(init_step)
plan.AddStep(worker_step)
core.workspace.RunPlan(plan)
v = 0
for counter in counters:
v += core.workspace.FetchBlob(str(counter)).tolist()
self.assertEqual(v, truth)
@given(
data=hu.tensor(),
**hu.gcs_cpu_only)
def test_squeeze_expand_dims(self, data, gc, dc):
dims = [0]
if len(data.shape) > 2:
dims.append(2)
op = core.CreateOperator(
"ExpandDims",
["data"],
["expanded"],
dims=dims)
def expand_dims_ref(data, *args, **kw):
inc_dims = list(set(dims))
inc_dims.sort()
r = data
for dim in inc_dims:
r = np.expand_dims(r, axis=dim)
return (r, )
def squeeze_ref(data, *args, **kw):
dec_dims = list(set(dims))
dec_dims.sort(reverse=True)
r = data
for dim in dec_dims:
r = np.squeeze(r, axis=dim)
return (r, )
self.assertReferenceChecks(
device_option=gc,
op=op,
inputs=[data],
reference=expand_dims_ref,
output_to_grad='expanded',
grad_reference=squeeze_ref)
@given(**hu.gcs_cpu_only)
def test_tt_layer(self, gc, dc):
seed = 1234
np.random.seed(seed)
inp_sizes = [2, 2, 2, 2]
out_sizes = [2, 2, 2, 2]
tt_ranks = [1, 3, 3, 3, 1]
op = core.CreateOperator(
"TT",
["X", "b", "cores"],
["Y"],
inp_sizes=inp_sizes,
out_sizes=out_sizes,
tt_ranks=tt_ranks,
)
X = np.expand_dims(
np.random.rand(16).astype(np.float32), axis=0)
b = np.array([0] * 16).astype(np.float32)
cores = tt_core.init_tt_cores(inp_sizes, out_sizes, tt_ranks)
workspace.FeedBlob("X", X)
workspace.FeedBlob("b", b)
workspace.FeedBlob("cores", cores)
workspace.RunOperatorOnce(op)
Y = workspace.FetchBlob("Y")
Y = Y.reshape([16])
golden = np.array([-9.51763490e-07, -1.28442286e-06,
-2.86281141e-07, 2.28865644e-07,
-1.96180017e-06, -1.78920531e-06,
9.31094666e-07, -2.04273989e-07,
1.70017107e-06, 1.64845711e-06,
-1.06099132e-06, -4.69111137e-07,
6.57552358e-08, -1.28942040e-08,
-2.29114004e-07, -1.04262714e-06])
# This golden array is dependent on the specified inp_sizes, out_sizes,
# tt_ranks, and seed. Changing these will cause the test to fail.
self.assertAlmostEqual(np.linalg.norm(golden - Y), 0, delta=1e-12)
@given(num_workers=st.integers(1, 10),
net_type=st.sampled_from(
["simple", "dag"] +
(["async_dag"] if workspace.has_gpu_support else [])),
do=st.sampled_from(hu.device_options))
def test_dag_net_forking(self, net_type, num_workers, do):
from caffe2.python.cnn import CNNModelHelper
m = CNNModelHelper()
n = 10
d = 2
depth = 2
iters = 5
np.random.seed(1701)
# Build a binary tree of FC layers, summing at each node.
for i in reversed(range(depth)):
for j in range(2 ** i):
bottom_1 = "{}_{}".format(i + 1, 2 * j)
bottom_2 = "{}_{}".format(i + 1, 2 * j + 1)
mid_1 = "{}_{}_m".format(i + 1, 2 * j)
mid_2 = "{}_{}_m".format(i + 1, 2 * j + 1)
top = "{}_{}".format(i, j)
m.FC(
bottom_1, mid_1,
dim_in=d, dim_out=d,
weight_init=m.ConstantInit(np.random.randn()),
bias_init=m.ConstantInit(np.random.randn()))
m.FC(
bottom_2, mid_2,
dim_in=d, dim_out=d,
weight_init=m.ConstantInit(np.random.randn()),
bias_init=m.ConstantInit(np.random.randn()))
m.net.Sum([mid_1, mid_2], top)
m.net.SquaredL2Distance(["0_0", "label"], "xent")
m.net.AveragedLoss("xent", "loss")
input_to_grad = m.AddGradientOperators(["loss"])
m.Proto().device_option.CopyFrom(do)
m.param_init_net.Proto().device_option.CopyFrom(do)
m.Proto().type = net_type
m.Proto().num_workers = num_workers
workspace.RunNetOnce(m.param_init_net)
print(str(m.Proto()))
def run():
import numpy as np
np.random.seed(1701)
input_blobs = ["{}_{}".format(depth, j) for j in range(2 ** depth)]
for input_blob in input_blobs:
workspace.FeedBlob(
input_blob,
np.random.randn(n, d).astype(np.float32),
device_option=do)
workspace.FeedBlob(
"label",
np.random.randn(n, d).astype(np.float32),
device_option=do)
workspace.RunNetOnce(m.net)
gradients = [
workspace.FetchBlob(str(input_to_grad[input_blob]))
for input_blob in input_blobs]
return gradients
outputs = [run() for _ in range(iters)]
for output in outputs[1:]:
np.testing.assert_array_equal(outputs[0], output)
self.assertAlmostEqual(np.sum(np.square(output)), 91.81752,
delta=1e-2)
@given(input=hu.tensor(min_dim=2, max_dim=6, dtype=np.int32,
elements=st.integers(min_value=0,
max_value=2**32 - 1)),
slice_dim=st.integers(),
a=st.integers(),
b=st.integers(),
**hu.gcs_cpu_only)
def test_slice(self, input, slice_dim, a, b, gc, dc):
slice_dim %= len(input.shape)
a %= input.shape[slice_dim]
b %= input.shape[slice_dim] + 1
start_vec = np.zeros(len(input.shape), dtype=np.int32)
end_vec = np.ones(len(input.shape), dtype=np.int32) * -1
start_vec[slice_dim] = min(a, b)
end_vec[slice_dim] = max(a, b)
op = core.CreateOperator(
"Slice",
["input", "start", "end"],
["output"])
def slice_ref(x, s, e):
if len(s.shape) == 0:
return x
slc = [slice(si, None if ei == -1 else ei) for si, ei in zip(s, e)]
return (x[slc], )
self.assertReferenceChecks(gc, op, [input, start_vec, end_vec],
slice_ref)
@given(data=hu.tensor(), **hu.gcs_cpu_only)
def test_shape(self, data, gc, dc):
op = core.CreateOperator("Shape", ["data"], ["shape"])
self.assertReferenceChecks(gc, op, [data], lambda x: (x.shape, ))
@given(data=hu.tensor(), **hu.gcs_cpu_only)
def test_has_elements(self, data, gc, dc):
op = core.CreateOperator("HasElements", ["data"], ["has_elements"])
self.assertReferenceChecks(gc, op, [data], lambda x: (len(x) > 0, ))
op = core.CreateOperator("IsEmpty", ["data"], ["is_empty"])
self.assertReferenceChecks(gc, op, [data], lambda x: (len(x) == 0, ))
@given(initial_iters=st.integers(0, 100),
max_iters=st.integers(0, 100))
def test_should_stop_as_criteria_net_execution_step(
self, initial_iters, max_iters):
net = core.Net("net")
net.Iter(["iter"], ["iter"])
workspace.FeedBlob(
"iter", np.asarray([initial_iters]).astype(np.int32))
workspace.FeedBlob(
"num_iters", np.asarray([max_iters]).astype(np.int32))
criteria_net = core.Net("criteria")
criteria_net.GE(["iter", "num_iters"], ["stop"])
criteria_net.Proto().external_output.extend(["stop"])
plan = core.Plan('plan')
plan.AddStep(core.execution_step(
'step', [criteria_net, net],
should_stop_blob=core.BlobReference("stop")))
workspace.RunPlan(plan)
iters = workspace.FetchBlob("iter")
self.assertEqual(iters.dtype, np.int32)
self.assertEqual(iters[0], max(initial_iters, max_iters))
def test_disabled_execution_step(self):
def createNets(i, disabled):
should_stop = 'should_stop_{}'.format(i)
output = 'output_{}'.format(i)
# init content and stop signal
init = core.Net("init_{}".format(i))
init.ConstantFill(
[],
[output],
shape=[1],
value=0.0
)
init.Cast([output], [should_stop], to='bool')
# decide if disabled or not
criterion = core.Net("criterion_{}".format(i))
tmp = criterion.ConstantFill(
[],
shape=[1],
value=1.0 if disabled else 0.0
)
criterion.Cast([tmp], [should_stop], to='bool')
criterion.Proto().external_output.extend([should_stop])
# the body net is just to turn a 0 blob to 1
net = core.Net("net_{}".format(i))
net.ConstantFill(
[],
[output],
shape=[1],
value=1.0
)
# always end the loop
ender = core.Net("ender_{}".format(i))
tmp = ender.ConstantFill(
[],
shape=[1],
value=1.0
)
ender.Cast([tmp], [should_stop], to='bool')
ender.Proto().external_output.extend([should_stop])
return [init, criterion, net, ender]
nets = [createNets(1, False),
createNets(2, True),
createNets(3, False)]
steps = [
core.execution_step(
'step_1', nets[0],
should_stop_blob=core.BlobReference('should_stop_1')),
core.execution_step(
'step_2', nets[1],
should_stop_blob=core.BlobReference('should_stop_2')),
core.execution_step('step_3', nets[2])
]
expected = [1.0, 0.0, 1.0]
plan = core.Plan('plan')
plan.AddStep(core.execution_step('all_steps', steps, num_iter=3))
workspace.RunPlan(plan)
for i, net in enumerate(nets):
self.assertEqual(
workspace.FetchBlob('output_{}'.format(i + 1))[0],
expected[i])
@given(initial_iters=st.integers(0, 100),
num_iters=st.integers(0, 100))
def test_iter_count_with_execution_step(self, initial_iters, num_iters):
net = core.Net("net")
net.Iter(["iter"], ["iter"])
workspace.FeedBlob(
"iter", np.asarray([initial_iters]).astype(np.int32))
step = core.ExecutionStep("step", [net])
step.SetIter(num_iters)
plan = core.Plan("plan")
plan.AddStep(step)
workspace.RunPlan(plan)
iters = workspace.FetchBlob("iter")
self.assertEqual(iters.dtype, np.int32)
self.assertEqual(iters[0], initial_iters + num_iters)
@given(a=hu.tensor(),
src=st.sampled_from(_NUMPY_TYPE_TO_ENUM.keys()),
dst=st.sampled_from(_NUMPY_TYPE_TO_ENUM.keys()),
use_name=st.booleans(),
**hu.gcs)
def test_cast(self, a, src, dst, use_name, gc, dc):
a = a.astype(src)
# Casting from a float type outside the range of the integral
# type is UB.
ftypes = [np.float32, np.float64]
if src in ftypes and dst not in ftypes and dst is not np.bool:
info = np.iinfo(dst)
a = np.clip(a, info.min, info.max)
def ref(data):
return [data.astype(dst)]
to = _NUMPY_TYPE_TO_ENUM[dst]
if use_name:
to = TensorProto.DataType.Name(to).lower()
op = core.CreateOperator('Cast', ["X"], ["Y"], to=to)
self.assertDeviceChecks(dc, op, [a], [0])
out, = self.assertReferenceChecks(gc, op, [a], ref)
self.assertEqual(dst, out.dtype)
@given(n=st.integers(1, 10),
d=st.integers(1, 10),
t=st.integers(1, 10),
**hu.gcs)
def test_lstm_unit_recurrent_network(self, n, d, t, dc, gc):
op = core.CreateOperator(
"LSTMUnit",
["cell_t-1", "gates_t", "seq_lengths", "timestep"],
["hidden_t", "cell_t"])
cell_t_m_1 = np.random.randn(1, n, d).astype(np.float32)
gates = np.random.randn(1, n, 4 * d).astype(np.float32)
seq_lengths = np.random.randint(0, t, size=(n,)).astype(np.int32)
timestep = np.random.randint(0, t, size=(1,)).astype(np.int32)
inputs = [cell_t_m_1, gates, seq_lengths, timestep]
input_device_options = {"timestep": hu.cpu_do}
self.assertDeviceChecks(
dc, op, inputs, [0],
input_device_options=input_device_options)
self.assertReferenceChecks(
gc, op, inputs, lstm_unit,
input_device_options=input_device_options)
for i in range(2):
self.assertGradientChecks(
gc, op, inputs, i, [0, 1],
input_device_options=input_device_options)
@given(n=st.integers(1, 5),
c=st.integers(1, 5),
h=st.integers(1, 5),
w=st.integers(1, 5),
pad=st.integers(0, 2),
block_size=st.integers(2, 3),
**hu.gcs)
def test_space_to_batch(self, n, c, h, w, pad, block_size, gc, dc):
assume((h + 2 * pad) % block_size == 0)
assume((w + 2 * pad) % block_size == 0)
X = np.random.randn(n, c, h, w).astype(np.float32)
op = core.CreateOperator("SpaceToBatch", ["X"], ["Y"],
pad=pad, block_size=block_size)
self.assertDeviceChecks(dc, op, [X], [0])
self.assertGradientChecks(gc, op, [X], 0, [0])
@given(n=st.integers(1, 5),
c=st.integers(1, 5),
h=st.integers(1, 5),
w=st.integers(1, 5),
pad=st.integers(0, 2),
block_size=st.integers(2, 3),
**hu.gcs)
def test_batch_to_space(self, n, c, h, w, pad, block_size, gc, dc):
assume((h + 2 * pad) % block_size == 0)
assume((w + 2 * pad) % block_size == 0)
X = np.random.randn(
n * block_size * block_size,
c,
(h + 2 * pad) / block_size,
(w + 2 * pad) / block_size).astype(np.float32)
op = core.CreateOperator("BatchToSpace", ["X"], ["Y"],
pad=pad, block_size=block_size)
self.assertDeviceChecks(dc, op, [X], [0])
self.assertGradientChecks(gc, op, [X], 0, [0])
@given(X=hu.tensor(),
in_place=st.booleans(),
scale=st.floats(min_value=-2.0, max_value=2.0),
**hu.gcs)
def test_scale(self, X, in_place, scale, gc, dc):
op = core.CreateOperator(
"Scale", ["X"], ["Y" if not in_place else "X"],
scale=scale)
self.assertDeviceChecks(dc, op, [X], [0])
self.assertGradientChecks(gc, op, [X], 0, [0])
@given(X=_dtypes().flatmap(lambda dtype: hu.tensor(dtype=dtype)),
seed=st.integers(min_value=0, max_value=65536),
null_axes=st.booleans(),
**hu.gcs)
def test_transpose(self, X, seed, null_axes, gc, dc):
if null_axes:
axes = None
op = core.CreateOperator("Transpose", "input", "output")
else:
np.random.seed(int(seed))
axes = [int(v) for v in list(np.random.permutation(X.ndim))]
op = core.CreateOperator(
"Transpose", "input", "output", axes=axes)
def transpose_ref(x, axes):
return (np.transpose(x, axes),)
self.assertReferenceChecks(gc, op, [X, axes],
transpose_ref)
if X.dtype != np.int32 and X.dtype != np.int64:
self.assertGradientChecks(gc, op, [X], 0, [0])
@given(s=st.text())
def test_string_serde(self, s):
s = s.encode('ascii', 'ignore')
workspace.FeedBlob("a", s)
serialized = workspace.SerializeBlob("a")
workspace.DeserializeBlob("b", serialized)
self.assertEqual(s, workspace.FetchBlob("a"))
self.assertEqual(s, workspace.FetchBlob("b"))
@given(n=st.integers(1, 3),
dim=st.integers(4, 16),
**hu.gcs_cpu_only)
def test_distances(self, n, dim, gc, dc):
X = np.random.uniform(-1, 1, (n, dim)).astype(np.float32)
Y = np.random.uniform(-1, 1, (n, dim)).astype(np.float32)
workspace.FeedBlob("X", X)
workspace.FeedBlob("Y", Y)
def check_grad(op):
self.assertGradientChecks(gc, op, [X, Y], 0, [0],
stepsize=1e-2, threshold=1e-2)
self.assertGradientChecks(gc, op, [X, Y], 1, [0],
stepsize=1e-2, threshold=1e-2)
l2_op = core.CreateOperator("SquaredL2Distance",
["X", "Y"], ["l2_dist"])
workspace.RunOperatorOnce(l2_op)
np.testing.assert_allclose(workspace.FetchBlob("l2_dist"),
np.square(X - Y).sum(axis=1) * 0.5,
rtol=1e-4, atol=1e-4)
check_grad(l2_op)
dot_op = core.CreateOperator("DotProduct", ["X", "Y"], ["dot"])
workspace.RunOperatorOnce(dot_op)
np.testing.assert_allclose(workspace.FetchBlob("dot"),
np.multiply(X, Y).sum(axis=1),
rtol=1e-4, atol=1e-4)
check_grad(dot_op)
kEps = 1e-12
cos_op = core.CreateOperator("CosineSimilarity", ["X", "Y"], ["cos"])
workspace.RunOperatorOnce(cos_op)
cos = np.divide(np.multiply(X, Y).sum(axis=1),
np.multiply(np.linalg.norm(X, axis=1) + kEps,
np.linalg.norm(Y, axis=1) + kEps))
np.testing.assert_allclose(workspace.FetchBlob("cos"), cos,
rtol=1e-4, atol=1e-4)
check_grad(cos_op)
|
[
"caffe2.python.core.Net",
"numpy.random.seed",
"numpy.abs",
"numpy.array_equal",
"numpy.argmax",
"numpy.empty",
"caffe2.python.core.BlobReference",
"numpy.iinfo",
"numpy.clip",
"numpy.ones",
"hypothesis.settings",
"numpy.random.randint",
"numpy.arange",
"hypothesis.given",
"numpy.exp",
"numpy.linalg.norm",
"caffe2.python.hypothesis_test_util.elements_of_type",
"caffe2.python.hypothesis_test_util.dims",
"unittest.skipIf",
"numpy.multiply",
"caffe2.python.core.workspace.RunPlan",
"caffe2.python.core.ExecutionStep",
"caffe2.python.core.Plan",
"numpy.random.randn",
"caffe2.python.workspace.FeedBlob",
"Queue.Queue",
"caffe2.python.workspace.RunNetOnce",
"caffe2.python.core.execution_step",
"hypothesis.strategies.sampled_from",
"caffe2.python.workspace.RunOperatorOnce",
"numpy.power",
"numpy.transpose",
"numpy.random.rand",
"hypothesis.strategies.booleans",
"hypothesis.strategies.text",
"hypothesis.strategies.integers",
"hypothesis.assume",
"numpy.stack",
"functools.partial",
"copy.deepcopy",
"caffe2.python.hypothesis_test_util.tensor",
"caffe2.python.tt_core.init_tt_cores",
"threading.Thread",
"caffe2.python.dyndep.InitOpsLibrary",
"caffe2.python.hypothesis_test_util.tensors",
"numpy.asarray",
"caffe2.python.workspace.SerializeBlob",
"numpy.testing.assert_array_equal",
"numpy.square",
"caffe2.python.workspace.ResetWorkspace",
"numpy.random.permutation",
"numpy.squeeze",
"hypothesis.strategies.floats",
"caffe2.python.workspace.FetchBlob",
"numpy.random.uniform",
"caffe2.python.workspace.RunPlan",
"caffe2.proto.caffe2_pb2.TensorProto.DataType.Name",
"caffe2.python.workspace.DeserializeBlob",
"numpy.expand_dims",
"numpy.sign",
"hypothesis.strategies.just",
"caffe2.python.cnn.CNNModelHelper",
"caffe2.python.core.CreateOperator",
"numpy.take",
"numpy.array",
"caffe2.python.hypothesis_test_util.arrays",
"functools.reduce",
"numpy.sqrt"
] |
[((456, 523), 'caffe2.python.dyndep.InitOpsLibrary', 'dyndep.InitOpsLibrary', (['"""@/caffe2/caffe2/fb/optimizers:sgd_simd_ops"""'], {}), "('@/caffe2/caffe2/fb/optimizers:sgd_simd_ops')\n", (477, 523), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((2548, 2609), 'hypothesis.strategies.sampled_from', 'st.sampled_from', (['[np.int32, np.int64, np.float32, np.float64]'], {}), '([np.int32, np.int64, np.float32, np.float64])\n', (2563, 2609), True, 'import hypothesis.strategies as st\n'), ((3028, 3065), 'hypothesis.settings', 'settings', ([], {'max_examples': '(3)', 'timeout': '(100)'}), '(max_examples=3, timeout=100)\n', (3036, 3065), False, 'from hypothesis import assume, given, settings\n'), ((3901, 3938), 'hypothesis.settings', 'settings', ([], {'max_examples': '(3)', 'timeout': '(100)'}), '(max_examples=3, timeout=100)\n', (3909, 3938), False, 'from hypothesis import assume, given, settings\n'), ((9740, 9830), 'unittest.skipIf', 'unittest.skipIf', (['(not workspace.has_gpu_support)', '"""Skipping test due to no gpu present."""'], {}), "(not workspace.has_gpu_support,\n 'Skipping test due to no gpu present.')\n", (9755, 9830), False, 'import unittest\n'), ((14545, 14582), 'hypothesis.settings', 'settings', ([], {'max_examples': '(2)', 'timeout': '(100)'}), '(max_examples=2, timeout=100)\n', (14553, 14582), False, 'from hypothesis import assume, given, settings\n'), ((18999, 19036), 'hypothesis.settings', 'settings', ([], {'max_examples': '(2)', 'timeout': '(100)'}), '(max_examples=2, timeout=100)\n', (19007, 19036), False, 'from hypothesis import assume, given, settings\n'), ((25827, 25864), 'hypothesis.settings', 'settings', ([], {'max_examples': '(2)', 'timeout': '(100)'}), '(max_examples=2, timeout=100)\n', (25835, 25864), False, 'from hypothesis import assume, given, settings\n'), ((53710, 53734), 'hypothesis.given', 'given', ([], {}), '(**hu.gcs_cpu_only)\n', (53715, 53734), False, 'from hypothesis import assume, given, settings\n'), ((3127, 3173), 'caffe2.python.core.CreateOperator', 'core.CreateOperator', (['name', "['X1', 'X2']", '[out]'], {}), "(name, ['X1', 'X2'], [out])\n", (3146, 3173), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((4015, 4100), 'caffe2.python.core.CreateOperator', 'core.CreateOperator', (['name', "['X1', 'X2']", "['X1' if in_place else 'Y']"], {'broadcast': '(1)'}), "(name, ['X1', 'X2'], ['X1' if in_place else 'Y'],\n broadcast=1)\n", (4034, 4100), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((5056, 5129), 'caffe2.python.core.CreateOperator', 'core.CreateOperator', (['"""Sum"""', "['X1', 'X2']", "['Y' if not in_place else 'X1']"], {}), "('Sum', ['X1', 'X2'], ['Y' if not in_place else 'X1'])\n", (5075, 5129), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((6657, 6727), 'caffe2.python.core.CreateOperator', 'core.CreateOperator', (['"""Negative"""', "['X']", "['Y' if not in_place else 'X']"], {}), "('Negative', ['X'], ['Y' if not in_place else 'X'])\n", (6676, 6727), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((6952, 6993), 'caffe2.python.core.CreateOperator', 'core.CreateOperator', (['"""Relu"""', "['X']", "['Y']"], {}), "('Relu', ['X'], ['Y'])\n", (6971, 6993), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((7316, 7368), 'caffe2.python.core.CreateOperator', 'core.CreateOperator', (['"""AveragedLoss"""', "['X']", "['loss']"], {}), "('AveragedLoss', ['X'], ['loss'])\n", (7335, 7368), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((7874, 7903), 'copy.deepcopy', 'copy.deepcopy', (['device_options'], {}), '(device_options)\n', (7887, 7903), False, 'import copy\n'), ((8818, 8835), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (8832, 8835), True, 'import numpy as np\n'), ((9188, 9248), 'caffe2.python.core.CreateOperator', 'core.CreateOperator', (['"""FC"""', "['X', 'W', 'b']", "['Y']"], {'axis': 'axis'}), "('FC', ['X', 'W', 'b'], ['Y'], axis=axis)\n", (9207, 9248), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((9409, 9438), 'caffe2.python.workspace.RunOperatorOnce', 'workspace.RunOperatorOnce', (['op'], {}), '(op)\n', (9434, 9438), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((9451, 9475), 'caffe2.python.workspace.FetchBlob', 'workspace.FetchBlob', (['"""Y"""'], {}), "('Y')\n", (9470, 9475), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((10483, 10751), 'caffe2.python.core.CreateOperator', 'core.CreateOperator', (['"""RecurrentInit"""', "['INPUT']", "['WEIGHT', 'DROPOUT_STATES']"], {'hidden_size': 'hidden_size', 'bidirectional': 'bidirectional', 'rnn_mode': 'rnn_mode', 'dropout': 'dropout', 'input_mode': 'input_mode', 'num_layers': 'num_layers', 'device_option': 'hu.gpu_do', 'engine': '"""CUDNN"""'}), "('RecurrentInit', ['INPUT'], ['WEIGHT', 'DROPOUT_STATES'\n ], hidden_size=hidden_size, bidirectional=bidirectional, rnn_mode=\n rnn_mode, dropout=dropout, input_mode=input_mode, num_layers=num_layers,\n device_option=hu.gpu_do, engine='CUDNN')\n", (10502, 10751), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((10885, 11214), 'caffe2.python.core.CreateOperator', 'core.CreateOperator', (['"""Recurrent"""', "['INPUT', 'HIDDEN_INPUT', 'CELL_INPUT', 'WEIGHT']", "['OUTPUT', 'HIDDEN_OUTPUT', 'CELL_OUTPUT', 'RNN_SCRATCH', 'DROPOUT_STATES']"], {'hidden_size': 'hidden_size', 'bidirectional': 'bidirectional', 'rnn_mode': 'rnn_mode', 'dropout': 'dropout', 'input_mode': 'input_mode', 'num_layers': 'num_layers', 'engine': '"""CUDNN"""'}), "('Recurrent', ['INPUT', 'HIDDEN_INPUT', 'CELL_INPUT',\n 'WEIGHT'], ['OUTPUT', 'HIDDEN_OUTPUT', 'CELL_OUTPUT', 'RNN_SCRATCH',\n 'DROPOUT_STATES'], hidden_size=hidden_size, bidirectional=bidirectional,\n rnn_mode=rnn_mode, dropout=dropout, input_mode=input_mode, num_layers=\n num_layers, engine='CUDNN')\n", (10904, 11214), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((11447, 11502), 'caffe2.python.workspace.FeedBlob', 'workspace.FeedBlob', (['"""INPUT"""', 'X'], {'device_option': 'hu.gpu_do'}), "('INPUT', X, device_option=hu.gpu_do)\n", (11465, 11502), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((11511, 11545), 'caffe2.python.workspace.RunOperatorOnce', 'workspace.RunOperatorOnce', (['init_op'], {}), '(init_op)\n', (11536, 11545), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((11558, 11587), 'caffe2.python.workspace.FetchBlob', 'workspace.FetchBlob', (['"""WEIGHT"""'], {}), "('WEIGHT')\n", (11577, 11587), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((12833, 12903), 'caffe2.python.core.CreateOperator', 'core.CreateOperator', (['"""Concat"""', 'input_names', "['Y', 'Y_dims']"], {'axis': 'axis'}), "('Concat', input_names, ['Y', 'Y_dims'], axis=axis)\n", (12852, 12903), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((13670, 13745), 'caffe2.python.core.CreateOperator', 'core.CreateOperator', (['"""Concat"""', 'input_names', "['Y', 'Y_dims']"], {'order': 'order[0]'}), "('Concat', input_names, ['Y', 'Y_dims'], order=order[0])\n", (13689, 13745), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((15113, 15139), 'hypothesis.assume', 'assume', (['(stride_h <= kernel)'], {}), '(stride_h <= kernel)\n', (15119, 15139), False, 'from hypothesis import assume, given, settings\n'), ((15148, 15174), 'hypothesis.assume', 'assume', (['(stride_w <= kernel)'], {}), '(stride_w <= kernel)\n', (15154, 15174), False, 'from hypothesis import assume, given, settings\n'), ((15188, 15380), 'caffe2.python.core.CreateOperator', 'core.CreateOperator', (['"""Conv"""', "['X', 'w', 'b']", "['Y']"], {'stride_h': 'stride_h', 'stride_w': 'stride_w', 'pad_t': 'pad_t', 'pad_l': 'pad_l', 'pad_b': 'pad_b', 'pad_r': 'pad_r', 'kernel': 'kernel', 'order': 'order', 'engine': 'engine'}), "('Conv', ['X', 'w', 'b'], ['Y'], stride_h=stride_h,\n stride_w=stride_w, pad_t=pad_t, pad_l=pad_l, pad_b=pad_b, pad_r=pad_r,\n kernel=kernel, order=order, engine=engine)\n", (15207, 15380), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((17099, 17125), 'hypothesis.assume', 'assume', (['(stride_h <= kernel)'], {}), '(stride_h <= kernel)\n', (17105, 17125), False, 'from hypothesis import assume, given, settings\n'), ((17134, 17160), 'hypothesis.assume', 'assume', (['(stride_w <= kernel)'], {}), '(stride_w <= kernel)\n', (17140, 17160), False, 'from hypothesis import assume, given, settings\n'), ((19252, 19276), 'hypothesis.assume', 'assume', (['(stride <= kernel)'], {}), '(stride <= kernel)\n', (19258, 19276), False, 'from hypothesis import assume, given, settings\n'), ((19290, 19413), 'caffe2.python.core.CreateOperator', 'core.CreateOperator', (['"""Conv"""', "['X', 'w', 'b']", "['Y']"], {'stride': 'stride', 'kernel': 'kernel', 'pad': 'pad', 'order': 'order', 'engine': 'engine'}), "('Conv', ['X', 'w', 'b'], ['Y'], stride=stride, kernel=\n kernel, pad=pad, order=order, engine=engine)\n", (19309, 19413), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((20614, 20638), 'hypothesis.assume', 'assume', (['(stride <= kernel)'], {}), '(stride <= kernel)\n', (20620, 20638), False, 'from hypothesis import assume, given, settings\n'), ((22364, 22380), 'caffe2.python.cnn.CNNModelHelper', 'CNNModelHelper', ([], {}), '()\n', (22378, 22380), False, 'from caffe2.python.cnn import CNNModelHelper\n'), ((22481, 22507), 'caffe2.python.workspace.ResetWorkspace', 'workspace.ResetWorkspace', ([], {}), '()\n', (22505, 22507), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((22517, 22537), 'numpy.random.seed', 'np.random.seed', (['(1701)'], {}), '(1701)\n', (22531, 22537), True, 'import numpy as np\n'), ((24304, 24342), 'caffe2.python.workspace.RunNetOnce', 'workspace.RunNetOnce', (['m.param_init_net'], {}), '(m.param_init_net)\n', (24324, 24342), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((26160, 26184), 'hypothesis.assume', 'assume', (['(stride <= kernel)'], {}), '(stride <= kernel)\n', (26166, 26184), False, 'from hypothesis import assume, given, settings\n'), ((26193, 26213), 'hypothesis.assume', 'assume', (['(adj < stride)'], {}), '(adj < stride)\n', (26199, 26213), False, 'from hypothesis import assume, given, settings\n'), ((26529, 26669), 'caffe2.python.core.CreateOperator', 'core.CreateOperator', (['"""ConvTranspose"""', "['X', 'w', 'b']", "['Y']"], {'stride': 'stride', 'kernel': 'kernel', 'pad': 'pad', 'adj': 'adj', 'order': 'order', 'engine': 'engine'}), "('ConvTranspose', ['X', 'w', 'b'], ['Y'], stride=stride,\n kernel=kernel, pad=pad, adj=adj, order=order, engine=engine)\n", (26548, 26669), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((27693, 27717), 'hypothesis.assume', 'assume', (['(stride <= kernel)'], {}), '(stride <= kernel)\n', (27699, 27717), False, 'from hypothesis import assume, given, settings\n'), ((27726, 27746), 'hypothesis.assume', 'assume', (['(adj < stride)'], {}), '(adj < stride)\n', (27732, 27746), False, 'from hypothesis import assume, given, settings\n'), ((29457, 29489), 'caffe2.python.workspace.FeedBlob', 'workspace.FeedBlob', (['"""data"""', 'data'], {}), "('data', data)\n", (29475, 29489), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((29503, 29543), 'caffe2.python.core.CreateOperator', 'core.CreateOperator', (['"""Print"""', '"""data"""', '[]'], {}), "('Print', 'data', [])\n", (29522, 29543), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((30170, 30204), 'numpy.asarray', 'np.asarray', (['[lr]'], {'dtype': 'np.float32'}), '([lr], dtype=np.float32)\n', (30180, 30204), True, 'import numpy as np\n'), ((30221, 30256), 'numpy.asarray', 'np.asarray', (['[iters]'], {'dtype': 'np.int32'}), '([iters], dtype=np.int32)\n', (30231, 30256), True, 'import numpy as np\n'), ((30270, 30499), 'caffe2.python.core.CreateOperator', 'core.CreateOperator', (['"""Adam"""', "['grad', 'm1', 'm2', 'lr', 'iters']", "['grad' if in_place else 'grad_o', 'm1' if in_place else 'm1_o', 'm2' if\n in_place else 'm2_o']"], {'beta1': 'beta1', 'beta2': 'beta2', 'epsilon': 'epsilon', 'device_option': 'gc'}), "('Adam', ['grad', 'm1', 'm2', 'lr', 'iters'], ['grad' if\n in_place else 'grad_o', 'm1' if in_place else 'm1_o', 'm2' if in_place else\n 'm2_o'], beta1=beta1, beta2=beta2, epsilon=epsilon, device_option=gc)\n", (30289, 30499), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((31766, 31800), 'numpy.asarray', 'np.asarray', (['[lr]'], {'dtype': 'np.float32'}), '([lr], dtype=np.float32)\n', (31776, 31800), True, 'import numpy as np\n'), ((33115, 33149), 'numpy.asarray', 'np.asarray', (['[lr]'], {'dtype': 'np.float32'}), '([lr], dtype=np.float32)\n', (33125, 33149), True, 'import numpy as np\n'), ((33163, 33400), 'caffe2.python.core.CreateOperator', 'core.CreateOperator', (['"""RmsProp"""', "['grad', 'ms', 'mom', 'lr']", "['grad' if in_place else 'grad_o', 'ms' if in_place else 'ms_o', 'mom' if\n in_place else 'mom_o']"], {'momentum': 'momentum', 'decay': 'decay', 'epsilon': 'epsilon', 'device_option': 'gc'}), "('RmsProp', ['grad', 'ms', 'mom', 'lr'], ['grad' if\n in_place else 'grad_o', 'ms' if in_place else 'ms_o', 'mom' if in_place\n else 'mom_o'], momentum=momentum, decay=decay, epsilon=epsilon,\n device_option=gc)\n", (33182, 33400), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((34442, 34476), 'numpy.asarray', 'np.asarray', (['[lr]'], {'dtype': 'np.float32'}), '([lr], dtype=np.float32)\n', (34452, 34476), True, 'import numpy as np\n'), ((34490, 34644), 'caffe2.python.core.CreateOperator', 'core.CreateOperator', (['"""Adagrad"""', "['grad', 'h', 'lr']", "['grad' if in_place else 'grad_o', 'h' if in_place else 'h_o']"], {'epsilon': 'epsilon', 'device_option': 'gc'}), "('Adagrad', ['grad', 'h', 'lr'], ['grad' if in_place else\n 'grad_o', 'h' if in_place else 'h_o'], epsilon=epsilon, device_option=gc)\n", (34509, 34644), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((35222, 35243), 'numpy.arange', 'np.arange', (['h.shape[0]'], {}), '(h.shape[0])\n', (35231, 35243), True, 'import numpy as np\n'), ((35329, 35338), 'numpy.abs', 'np.abs', (['h'], {}), '(h)\n', (35335, 35338), True, 'import numpy as np\n'), ((35352, 35386), 'numpy.asarray', 'np.asarray', (['[lr]'], {'dtype': 'np.float32'}), '([lr], dtype=np.float32)\n', (35362, 35386), True, 'import numpy as np\n'), ((35400, 35523), 'caffe2.python.core.CreateOperator', 'core.CreateOperator', (['"""SparseAdagrad"""', "['indices', 'grad', 'h', 'lr']", "['grad', 'h']"], {'epsilon': 'epsilon', 'device_option': 'gc'}), "('SparseAdagrad', ['indices', 'grad', 'h', 'lr'], [\n 'grad', 'h'], epsilon=epsilon, device_option=gc)\n", (35419, 35523), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((36001, 36024), 'numpy.take', 'np.take', (['nz', '(0)'], {'axis': '(-1)'}), '(nz, 0, axis=-1)\n', (36008, 36024), True, 'import numpy as np\n'), ((36037, 36060), 'numpy.take', 'np.take', (['nz', '(1)'], {'axis': '(-1)'}), '(nz, 1, axis=-1)\n', (36044, 36060), True, 'import numpy as np\n'), ((36956, 36965), 'numpy.abs', 'np.abs', (['n'], {}), '(n)\n', (36962, 36965), True, 'import numpy as np\n'), ((36979, 37004), 'numpy.stack', 'np.stack', (['[n, z]'], {'axis': '(-1)'}), '([n, z], axis=-1)\n', (36987, 37004), True, 'import numpy as np\n'), ((37018, 37232), 'caffe2.python.core.CreateOperator', 'core.CreateOperator', (['"""Ftrl"""', "['var', 'nz', 'grad']", "['var' if in_place else 'var_o', 'nz' if in_place else 'nz_o']"], {'alpha': 'alpha', 'beta': 'beta', 'lambda1': 'lambda1', 'lambda2': 'lambda2', 'engine': 'engine', 'device_option': 'gc'}), "('Ftrl', ['var', 'nz', 'grad'], ['var' if in_place else\n 'var_o', 'nz' if in_place else 'nz_o'], alpha=alpha, beta=beta, lambda1\n =lambda1, lambda2=lambda2, engine=engine, device_option=gc)\n", (37037, 37232), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((38138, 38161), 'numpy.arange', 'np.arange', (['var.shape[0]'], {}), '(var.shape[0])\n', (38147, 38161), True, 'import numpy as np\n'), ((38247, 38256), 'numpy.abs', 'np.abs', (['n'], {}), '(n)\n', (38253, 38256), True, 'import numpy as np\n'), ((38270, 38295), 'numpy.stack', 'np.stack', (['[n, z]'], {'axis': '(-1)'}), '([n, z], axis=-1)\n', (38278, 38295), True, 'import numpy as np\n'), ((38309, 38491), 'caffe2.python.core.CreateOperator', 'core.CreateOperator', (['"""SparseFtrl"""', "['var', 'nz', 'indices', 'grad']", "['var', 'nz']"], {'alpha': 'alpha', 'beta': 'beta', 'lambda1': 'lambda1', 'lambda2': 'lambda2', 'engine': 'engine', 'device_option': 'gc'}), "('SparseFtrl', ['var', 'nz', 'indices', 'grad'], ['var',\n 'nz'], alpha=alpha, beta=beta, lambda1=lambda1, lambda2=lambda2, engine\n =engine, device_option=gc)\n", (38328, 38491), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((39308, 39426), 'caffe2.python.core.CreateOperator', 'core.CreateOperator', (['"""Unique"""', "['input']", "(['unique'] + (['remapping'] if with_remapping else []))"], {'device_option': 'gc'}), "('Unique', ['input'], ['unique'] + (['remapping'] if\n with_remapping else []), device_option=gc)\n", (39327, 39426), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((40653, 40724), 'caffe2.python.core.CreateOperator', 'core.CreateOperator', (['"""Accuracy"""', "['prediction', 'labels']", "['accuracy']"], {}), "('Accuracy', ['prediction', 'labels'], ['accuracy'])\n", (40672, 40724), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((41619, 41694), 'caffe2.python.core.CreateOperator', 'core.CreateOperator', (['"""Perplexity"""', "['target_probabilities']", "['perplexity']"], {}), "('Perplexity', ['target_probabilities'], ['perplexity'])\n", (41638, 41694), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((42410, 42482), 'caffe2.python.core.CreateOperator', 'core.CreateOperator', (['"""LengthsToSegmentIds"""', "['lengths']", "['segment_ids']"], {}), "('LengthsToSegmentIds', ['lengths'], ['segment_ids'])\n", (42429, 42482), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((43504, 43603), 'caffe2.python.core.CreateOperator', 'core.CreateOperator', (['"""MultiClassAccuracy"""', "['prediction', 'labels']", "['accuracies', 'amounts']"], {}), "('MultiClassAccuracy', ['prediction', 'labels'], [\n 'accuracies', 'amounts'])\n", (43523, 43603), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((44789, 44861), 'caffe2.python.core.CreateOperator', 'core.CreateOperator', (['"""SegmentIdsToLengths"""', "['segment_ids']", "['lengths']"], {}), "('SegmentIdsToLengths', ['segment_ids'], ['lengths'])\n", (44808, 44861), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((46310, 46359), 'caffe2.python.core.CreateOperator', 'core.CreateOperator', (['"""Exp"""', "['input']", "['output']"], {}), "('Exp', ['input'], ['output'])\n", (46329, 46359), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((47349, 47465), 'caffe2.python.core.CreateOperator', 'core.CreateOperator', (['"""CreateBlobsQueue"""', '[]', "['queue']"], {'capacity': 'capacity', 'num_blobs': 'num_blobs', 'device_option': 'do'}), "('CreateBlobsQueue', [], ['queue'], capacity=capacity,\n num_blobs=num_blobs, device_option=do)\n", (47368, 47465), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((47543, 47572), 'caffe2.python.workspace.RunOperatorOnce', 'workspace.RunOperatorOnce', (['op'], {}), '(op)\n', (47568, 47572), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((47693, 47706), 'Queue.Queue', 'Queue.Queue', ([], {}), '()\n', (47704, 47706), False, 'import Queue\n'), ((49231, 49284), 'caffe2.python.core.CreateOperator', 'core.CreateOperator', (['"""CloseBlobsQueue"""', "['queue']", '[]'], {}), "('CloseBlobsQueue', ['queue'], [])\n", (49250, 49284), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((49293, 49322), 'caffe2.python.workspace.RunOperatorOnce', 'workspace.RunOperatorOnce', (['op'], {}), '(op)\n', (49318, 49322), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((50304, 50324), 'caffe2.python.core.Net', 'core.Net', (['"""init_net"""'], {}), "('init_net')\n", (50312, 50324), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((51004, 51033), 'caffe2.python.core.Net', 'core.Net', (['"""producer_exit_net"""'], {}), "('producer_exit_net')\n", (51012, 51033), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((51984, 52057), 'caffe2.python.core.execution_step', 'core.execution_step', (['"""consumer"""', 'consumer_steps'], {'concurrent_substeps': '(True)'}), "('consumer', consumer_steps, concurrent_substeps=True)\n", (52003, 52057), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((52092, 52129), 'caffe2.python.core.execution_step', 'core.execution_step', (['"""init"""', 'init_net'], {}), "('init', init_net)\n", (52111, 52129), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((52152, 52243), 'caffe2.python.core.execution_step', 'core.execution_step', (['"""worker"""', '[consumer_step, producer_step]'], {'concurrent_substeps': '(True)'}), "('worker', [consumer_step, producer_step],\n concurrent_substeps=True)\n", (52171, 52243), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((52269, 52286), 'caffe2.python.core.Plan', 'core.Plan', (['"""test"""'], {}), "('test')\n", (52278, 52286), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((52362, 52390), 'caffe2.python.core.workspace.RunPlan', 'core.workspace.RunPlan', (['plan'], {}), '(plan)\n', (52384, 52390), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((52765, 52833), 'caffe2.python.core.CreateOperator', 'core.CreateOperator', (['"""ExpandDims"""', "['data']", "['expanded']"], {'dims': 'dims'}), "('ExpandDims', ['data'], ['expanded'], dims=dims)\n", (52784, 52833), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((53800, 53820), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (53814, 53820), True, 'import numpy as np\n'), ((53937, 54055), 'caffe2.python.core.CreateOperator', 'core.CreateOperator', (['"""TT"""', "['X', 'b', 'cores']", "['Y']"], {'inp_sizes': 'inp_sizes', 'out_sizes': 'out_sizes', 'tt_ranks': 'tt_ranks'}), "('TT', ['X', 'b', 'cores'], ['Y'], inp_sizes=inp_sizes,\n out_sizes=out_sizes, tt_ranks=tt_ranks)\n", (53956, 54055), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((54289, 54342), 'caffe2.python.tt_core.init_tt_cores', 'tt_core.init_tt_cores', (['inp_sizes', 'out_sizes', 'tt_ranks'], {}), '(inp_sizes, out_sizes, tt_ranks)\n', (54310, 54342), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((54352, 54378), 'caffe2.python.workspace.FeedBlob', 'workspace.FeedBlob', (['"""X"""', 'X'], {}), "('X', X)\n", (54370, 54378), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((54387, 54413), 'caffe2.python.workspace.FeedBlob', 'workspace.FeedBlob', (['"""b"""', 'b'], {}), "('b', b)\n", (54405, 54413), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((54422, 54456), 'caffe2.python.workspace.FeedBlob', 'workspace.FeedBlob', (['"""cores"""', 'cores'], {}), "('cores', cores)\n", (54440, 54456), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((54465, 54494), 'caffe2.python.workspace.RunOperatorOnce', 'workspace.RunOperatorOnce', (['op'], {}), '(op)\n', (54490, 54494), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((54508, 54532), 'caffe2.python.workspace.FetchBlob', 'workspace.FetchBlob', (['"""Y"""'], {}), "('Y')\n", (54527, 54532), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((54579, 54868), 'numpy.array', 'np.array', (['[-9.5176349e-07, -1.28442286e-06, -2.86281141e-07, 2.28865644e-07, -\n 1.96180017e-06, -1.78920531e-06, 9.31094666e-07, -2.04273989e-07, \n 1.70017107e-06, 1.64845711e-06, -1.06099132e-06, -4.69111137e-07, \n 6.57552358e-08, -1.2894204e-08, -2.29114004e-07, -1.04262714e-06]'], {}), '([-9.5176349e-07, -1.28442286e-06, -2.86281141e-07, 2.28865644e-07,\n -1.96180017e-06, -1.78920531e-06, 9.31094666e-07, -2.04273989e-07, \n 1.70017107e-06, 1.64845711e-06, -1.06099132e-06, -4.69111137e-07, \n 6.57552358e-08, -1.2894204e-08, -2.29114004e-07, -1.04262714e-06])\n', (54587, 54868), True, 'import numpy as np\n'), ((55640, 55656), 'caffe2.python.cnn.CNNModelHelper', 'CNNModelHelper', ([], {}), '()\n', (55654, 55656), False, 'from caffe2.python.cnn import CNNModelHelper\n'), ((55730, 55750), 'numpy.random.seed', 'np.random.seed', (['(1701)'], {}), '(1701)\n', (55744, 55750), True, 'import numpy as np\n'), ((57029, 57067), 'caffe2.python.workspace.RunNetOnce', 'workspace.RunNetOnce', (['m.param_init_net'], {}), '(m.param_init_net)\n', (57049, 57067), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((58827, 58894), 'caffe2.python.core.CreateOperator', 'core.CreateOperator', (['"""Slice"""', "['input', 'start', 'end']", "['output']"], {}), "('Slice', ['input', 'start', 'end'], ['output'])\n", (58846, 58894), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((59355, 59404), 'caffe2.python.core.CreateOperator', 'core.CreateOperator', (['"""Shape"""', "['data']", "['shape']"], {}), "('Shape', ['data'], ['shape'])\n", (59374, 59404), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((59588, 59650), 'caffe2.python.core.CreateOperator', 'core.CreateOperator', (['"""HasElements"""', "['data']", "['has_elements']"], {}), "('HasElements', ['data'], ['has_elements'])\n", (59607, 59650), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((59742, 59796), 'caffe2.python.core.CreateOperator', 'core.CreateOperator', (['"""IsEmpty"""', "['data']", "['is_empty']"], {}), "('IsEmpty', ['data'], ['is_empty'])\n", (59761, 59796), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((60080, 60095), 'caffe2.python.core.Net', 'core.Net', (['"""net"""'], {}), "('net')\n", (60088, 60095), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((60345, 60365), 'caffe2.python.core.Net', 'core.Net', (['"""criteria"""'], {}), "('criteria')\n", (60353, 60365), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((60501, 60518), 'caffe2.python.core.Plan', 'core.Plan', (['"""plan"""'], {}), "('plan')\n", (60510, 60518), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((60668, 60691), 'caffe2.python.workspace.RunPlan', 'workspace.RunPlan', (['plan'], {}), '(plan)\n', (60685, 60691), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((60708, 60735), 'caffe2.python.workspace.FetchBlob', 'workspace.FetchBlob', (['"""iter"""'], {}), "('iter')\n", (60727, 60735), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((62852, 62869), 'caffe2.python.core.Plan', 'core.Plan', (['"""plan"""'], {}), "('plan')\n", (62861, 62869), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((62952, 62975), 'caffe2.python.workspace.RunPlan', 'workspace.RunPlan', (['plan'], {}), '(plan)\n', (62969, 62975), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((63322, 63337), 'caffe2.python.core.Net', 'core.Net', (['"""net"""'], {}), "('net')\n", (63330, 63337), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((63485, 63518), 'caffe2.python.core.ExecutionStep', 'core.ExecutionStep', (['"""step"""', '[net]'], {}), "('step', [net])\n", (63503, 63518), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((63567, 63584), 'caffe2.python.core.Plan', 'core.Plan', (['"""plan"""'], {}), "('plan')\n", (63576, 63584), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((63620, 63643), 'caffe2.python.workspace.RunPlan', 'workspace.RunPlan', (['plan'], {}), '(plan)\n', (63637, 63643), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((63660, 63687), 'caffe2.python.workspace.FetchBlob', 'workspace.FetchBlob', (['"""iter"""'], {}), "('iter')\n", (63679, 63687), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((64559, 64607), 'caffe2.python.core.CreateOperator', 'core.CreateOperator', (['"""Cast"""', "['X']", "['Y']"], {'to': 'to'}), "('Cast', ['X'], ['Y'], to=to)\n", (64578, 64607), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((64958, 65069), 'caffe2.python.core.CreateOperator', 'core.CreateOperator', (['"""LSTMUnit"""', "['cell_t-1', 'gates_t', 'seq_lengths', 'timestep']", "['hidden_t', 'cell_t']"], {}), "('LSTMUnit', ['cell_t-1', 'gates_t', 'seq_lengths',\n 'timestep'], ['hidden_t', 'cell_t'])\n", (64977, 65069), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((66216, 66255), 'hypothesis.assume', 'assume', (['((h + 2 * pad) % block_size == 0)'], {}), '((h + 2 * pad) % block_size == 0)\n', (66222, 66255), False, 'from hypothesis import assume, given, settings\n'), ((66264, 66303), 'hypothesis.assume', 'assume', (['((w + 2 * pad) % block_size == 0)'], {}), '((w + 2 * pad) % block_size == 0)\n', (66270, 66303), False, 'from hypothesis import assume, given, settings\n'), ((66376, 66462), 'caffe2.python.core.CreateOperator', 'core.CreateOperator', (['"""SpaceToBatch"""', "['X']", "['Y']"], {'pad': 'pad', 'block_size': 'block_size'}), "('SpaceToBatch', ['X'], ['Y'], pad=pad, block_size=\n block_size)\n", (66395, 66462), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((66901, 66940), 'hypothesis.assume', 'assume', (['((h + 2 * pad) % block_size == 0)'], {}), '((h + 2 * pad) % block_size == 0)\n', (66907, 66940), False, 'from hypothesis import assume, given, settings\n'), ((66949, 66988), 'hypothesis.assume', 'assume', (['((w + 2 * pad) % block_size == 0)'], {}), '((w + 2 * pad) % block_size == 0)\n', (66955, 66988), False, 'from hypothesis import assume, given, settings\n'), ((67186, 67272), 'caffe2.python.core.CreateOperator', 'core.CreateOperator', (['"""BatchToSpace"""', "['X']", "['Y']"], {'pad': 'pad', 'block_size': 'block_size'}), "('BatchToSpace', ['X'], ['Y'], pad=pad, block_size=\n block_size)\n", (67205, 67272), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((67616, 67701), 'caffe2.python.core.CreateOperator', 'core.CreateOperator', (['"""Scale"""', "['X']", "['Y' if not in_place else 'X']"], {'scale': 'scale'}), "('Scale', ['X'], ['Y' if not in_place else 'X'], scale=scale\n )\n", (67635, 67701), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((68819, 68845), 'caffe2.python.workspace.FeedBlob', 'workspace.FeedBlob', (['"""a"""', 's'], {}), "('a', s)\n", (68837, 68845), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((68867, 68895), 'caffe2.python.workspace.SerializeBlob', 'workspace.SerializeBlob', (['"""a"""'], {}), "('a')\n", (68890, 68895), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((68904, 68946), 'caffe2.python.workspace.DeserializeBlob', 'workspace.DeserializeBlob', (['"""b"""', 'serialized'], {}), "('b', serialized)\n", (68929, 68946), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((69339, 69365), 'caffe2.python.workspace.FeedBlob', 'workspace.FeedBlob', (['"""X"""', 'X'], {}), "('X', X)\n", (69357, 69365), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((69374, 69400), 'caffe2.python.workspace.FeedBlob', 'workspace.FeedBlob', (['"""Y"""', 'Y'], {}), "('Y', Y)\n", (69392, 69400), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((69709, 69774), 'caffe2.python.core.CreateOperator', 'core.CreateOperator', (['"""SquaredL2Distance"""', "['X', 'Y']", "['l2_dist']"], {}), "('SquaredL2Distance', ['X', 'Y'], ['l2_dist'])\n", (69728, 69774), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((69819, 69851), 'caffe2.python.workspace.RunOperatorOnce', 'workspace.RunOperatorOnce', (['l2_op'], {}), '(l2_op)\n', (69844, 69851), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((70091, 70145), 'caffe2.python.core.CreateOperator', 'core.CreateOperator', (['"""DotProduct"""', "['X', 'Y']", "['dot']"], {}), "('DotProduct', ['X', 'Y'], ['dot'])\n", (70110, 70145), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((70154, 70187), 'caffe2.python.workspace.RunOperatorOnce', 'workspace.RunOperatorOnce', (['dot_op'], {}), '(dot_op)\n', (70179, 70187), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((70440, 70500), 'caffe2.python.core.CreateOperator', 'core.CreateOperator', (['"""CosineSimilarity"""', "['X', 'Y']", "['cos']"], {}), "('CosineSimilarity', ['X', 'Y'], ['cos'])\n", (70459, 70500), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((70509, 70542), 'caffe2.python.workspace.RunOperatorOnce', 'workspace.RunOperatorOnce', (['cos_op'], {}), '(cos_op)\n', (70534, 70542), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((566, 576), 'numpy.exp', 'np.exp', (['(-x)'], {}), '(-x)\n', (572, 576), True, 'import numpy as np\n'), ((1910, 1927), 'caffe2.python.hypothesis_test_util.dims', 'hu.dims', ([], {}), '(**kwargs)\n', (1917, 1927), True, 'import caffe2.python.hypothesis_test_util as hu\n'), ((2002, 2019), 'caffe2.python.hypothesis_test_util.dims', 'hu.dims', ([], {}), '(**kwargs)\n', (2009, 2019), True, 'import caffe2.python.hypothesis_test_util as hu\n'), ((2075, 2117), 'caffe2.python.hypothesis_test_util.arrays', 'hu.arrays', (['(dims_ + extra_)', 'dtype', 'elements'], {}), '(dims_ + extra_, dtype, elements)\n', (2084, 2117), True, 'import caffe2.python.hypothesis_test_util as hu\n'), ((2137, 2171), 'caffe2.python.hypothesis_test_util.arrays', 'hu.arrays', (['extra_', 'dtype', 'elements'], {}), '(extra_, dtype, elements)\n', (2146, 2171), True, 'import caffe2.python.hypothesis_test_util as hu\n'), ((2943, 3006), 'hypothesis.strategies.sampled_from', 'st.sampled_from', (["(('Y', 'X1', 'X2') if allow_inplace else ('Y',))"], {}), "(('Y', 'X1', 'X2') if allow_inplace else ('Y',))\n", (2958, 3006), True, 'import hypothesis.strategies as st\n'), ((4942, 4957), 'caffe2.python.hypothesis_test_util.tensors', 'hu.tensors', ([], {'n': '(2)'}), '(n=2)\n', (4952, 4957), True, 'import caffe2.python.hypothesis_test_util as hu\n'), ((4968, 4981), 'hypothesis.strategies.booleans', 'st.booleans', ([], {}), '()\n', (4979, 4981), True, 'import hypothesis.strategies as st\n'), ((6109, 6150), 'hypothesis.strategies.sampled_from', 'st.sampled_from', (['[np.float32, np.float64]'], {}), '([np.float32, np.float64])\n', (6124, 6150), True, 'import hypothesis.strategies as st\n'), ((6547, 6558), 'caffe2.python.hypothesis_test_util.tensor', 'hu.tensor', ([], {}), '()\n', (6556, 6558), True, 'import caffe2.python.hypothesis_test_util as hu\n'), ((6569, 6582), 'hypothesis.strategies.booleans', 'st.booleans', ([], {}), '()\n', (6580, 6582), True, 'import hypothesis.strategies as st\n'), ((7077, 7087), 'numpy.sign', 'np.sign', (['X'], {}), '(X)\n', (7084, 7087), True, 'import numpy as np\n'), ((6880, 6891), 'caffe2.python.hypothesis_test_util.tensor', 'hu.tensor', ([], {}), '()\n', (6889, 6891), True, 'import caffe2.python.hypothesis_test_util as hu\n'), ((7235, 7246), 'caffe2.python.hypothesis_test_util.tensor', 'hu.tensor', ([], {}), '()\n', (7244, 7246), True, 'import caffe2.python.hypothesis_test_util as hu\n'), ((8108, 8181), 'caffe2.python.core.CreateOperator', 'core.CreateOperator', (['"""XavierFill"""', '[]', "['Y']"], {'device_option': 'do', 'shape': '[2]'}), "('XavierFill', [], ['Y'], device_option=do, shape=[2])\n", (8127, 8181), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((8243, 8272), 'caffe2.python.workspace.RunOperatorOnce', 'workspace.RunOperatorOnce', (['op'], {}), '(op)\n', (8268, 8272), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((8292, 8316), 'caffe2.python.workspace.FetchBlob', 'workspace.FetchBlob', (['"""Y"""'], {}), "('Y')\n", (8311, 8316), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((7652, 7665), 'hypothesis.strategies.booleans', 'st.booleans', ([], {}), '()\n', (7663, 7665), True, 'import hypothesis.strategies as st\n'), ((9369, 9400), 'caffe2.python.workspace.FeedBlob', 'workspace.FeedBlob', (['name', 'param'], {}), '(name, param)\n', (9387, 9400), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((8622, 8659), 'hypothesis.strategies.integers', 'st.integers', ([], {'min_value': '(1)', 'max_value': '(4)'}), '(min_value=1, max_value=4)\n', (8633, 8659), True, 'import hypothesis.strategies as st\n'), ((8683, 8720), 'hypothesis.strategies.integers', 'st.integers', ([], {'min_value': '(4)', 'max_value': '(8)'}), '(min_value=4, max_value=8)\n', (8694, 8720), True, 'import hypothesis.strategies as st\n'), ((9871, 9908), 'hypothesis.strategies.integers', 'st.integers', ([], {'min_value': '(1)', 'max_value': '(3)'}), '(min_value=1, max_value=3)\n', (9882, 9908), True, 'import hypothesis.strategies as st\n'), ((9932, 9969), 'hypothesis.strategies.integers', 'st.integers', ([], {'min_value': '(1)', 'max_value': '(3)'}), '(min_value=1, max_value=3)\n', (9943, 9969), True, 'import hypothesis.strategies as st\n'), ((9996, 10009), 'hypothesis.strategies.booleans', 'st.booleans', ([], {}), '()\n', (10007, 10009), True, 'import hypothesis.strategies as st\n'), ((10031, 10063), 'hypothesis.strategies.sampled_from', 'st.sampled_from', (["['gru', 'lstm']"], {}), "(['gru', 'lstm'])\n", (10046, 10063), True, 'import hypothesis.strategies as st\n'), ((10087, 10114), 'hypothesis.strategies.sampled_from', 'st.sampled_from', (["['linear']"], {}), "(['linear'])\n", (10102, 10114), True, 'import hypothesis.strategies as st\n'), ((10135, 10174), 'hypothesis.strategies.floats', 'st.floats', ([], {'min_value': '(0.0)', 'max_value': '(0.0)'}), '(min_value=0.0, max_value=0.0)\n', (10144, 10174), True, 'import hypothesis.strategies as st\n'), ((10189, 10226), 'hypothesis.strategies.integers', 'st.integers', ([], {'min_value': '(1)', 'max_value': '(4)'}), '(min_value=1, max_value=4)\n', (10200, 10226), True, 'import hypothesis.strategies as st\n'), ((10241, 10278), 'hypothesis.strategies.integers', 'st.integers', ([], {'min_value': '(1)', 'max_value': '(4)'}), '(min_value=1, max_value=4)\n', (10252, 10278), True, 'import hypothesis.strategies as st\n'), ((10293, 10330), 'hypothesis.strategies.integers', 'st.integers', ([], {'min_value': '(1)', 'max_value': '(4)'}), '(min_value=1, max_value=4)\n', (10304, 10330), True, 'import hypothesis.strategies as st\n'), ((12228, 12245), 'hypothesis.strategies.integers', 'st.integers', (['(1)', '(4)'], {}), '(1, 4)\n', (12239, 12245), True, 'import hypothesis.strategies as st\n'), ((12263, 12280), 'hypothesis.strategies.integers', 'st.integers', (['(0)', '(3)'], {}), '(0, 3)\n', (12274, 12280), True, 'import hypothesis.strategies as st\n'), ((12304, 12321), 'hypothesis.strategies.integers', 'st.integers', (['(2)', '(4)'], {}), '(2, 4)\n', (12315, 12321), True, 'import hypothesis.strategies as st\n'), ((13111, 13128), 'hypothesis.strategies.integers', 'st.integers', (['(2)', '(4)'], {}), '(2, 4)\n', (13122, 13128), True, 'import hypothesis.strategies as st\n'), ((13147, 13190), 'hypothesis.strategies.sampled_from', 'st.sampled_from', (["[('NCHW', 1), ('NHWC', 3)]"], {}), "([('NCHW', 1), ('NHWC', 3)])\n", (13162, 13190), True, 'import hypothesis.strategies as st\n'), ((14020, 14037), 'hypothesis.strategies.integers', 'st.integers', (['(1)', '(3)'], {}), '(1, 3)\n', (14031, 14037), True, 'import hypothesis.strategies as st\n'), ((14059, 14076), 'hypothesis.strategies.integers', 'st.integers', (['(1)', '(3)'], {}), '(1, 3)\n', (14070, 14076), True, 'import hypothesis.strategies as st\n'), ((14095, 14112), 'hypothesis.strategies.integers', 'st.integers', (['(0)', '(3)'], {}), '(0, 3)\n', (14106, 14112), True, 'import hypothesis.strategies as st\n'), ((14131, 14148), 'hypothesis.strategies.integers', 'st.integers', (['(0)', '(3)'], {}), '(0, 3)\n', (14142, 14148), True, 'import hypothesis.strategies as st\n'), ((14167, 14184), 'hypothesis.strategies.integers', 'st.integers', (['(0)', '(3)'], {}), '(0, 3)\n', (14178, 14184), True, 'import hypothesis.strategies as st\n'), ((14203, 14220), 'hypothesis.strategies.integers', 'st.integers', (['(0)', '(3)'], {}), '(0, 3)\n', (14214, 14220), True, 'import hypothesis.strategies as st\n'), ((14240, 14257), 'hypothesis.strategies.integers', 'st.integers', (['(3)', '(5)'], {}), '(3, 5)\n', (14251, 14257), True, 'import hypothesis.strategies as st\n'), ((14275, 14292), 'hypothesis.strategies.integers', 'st.integers', (['(8)', '(8)'], {}), '(8, 8)\n', (14286, 14292), True, 'import hypothesis.strategies as st\n'), ((14320, 14337), 'hypothesis.strategies.integers', 'st.integers', (['(1)', '(3)'], {}), '(1, 3)\n', (14331, 14337), True, 'import hypothesis.strategies as st\n'), ((14366, 14383), 'hypothesis.strategies.integers', 'st.integers', (['(1)', '(3)'], {}), '(1, 3)\n', (14377, 14383), True, 'import hypothesis.strategies as st\n'), ((14407, 14424), 'hypothesis.strategies.integers', 'st.integers', (['(1)', '(3)'], {}), '(1, 3)\n', (14418, 14424), True, 'import hypothesis.strategies as st\n'), ((14443, 14476), 'hypothesis.strategies.sampled_from', 'st.sampled_from', (["['NCHW', 'NHWC']"], {}), "(['NCHW', 'NHWC'])\n", (14458, 14476), True, 'import hypothesis.strategies as st\n'), ((14496, 14517), 'hypothesis.strategies.sampled_from', 'st.sampled_from', (["['']"], {}), "([''])\n", (14511, 14517), True, 'import hypothesis.strategies as st\n'), ((17539, 17749), 'caffe2.python.core.CreateOperator', 'core.CreateOperator', (['"""Conv"""', "['X', 'w', 'b']", "['Y']"], {'stride_h': 'stride_h', 'stride_w': 'stride_w', 'kernel': 'kernel', 'pad_t': 'pad_t', 'pad_l': 'pad_l', 'pad_b': 'pad_b', 'pad_r': 'pad_r', 'order': 'order', 'engine': 'engine', 'device_option': 'gc'}), "('Conv', ['X', 'w', 'b'], ['Y'], stride_h=stride_h,\n stride_w=stride_w, kernel=kernel, pad_t=pad_t, pad_l=pad_l, pad_b=pad_b,\n pad_r=pad_r, order=order, engine=engine, device_option=gc)\n", (17558, 17749), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((18171, 18217), 'caffe2.python.workspace.FeedBlob', 'workspace.FeedBlob', (['"""X"""', 'X_f'], {'device_option': 'gc'}), "('X', X_f, device_option=gc)\n", (18189, 18217), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((18230, 18276), 'caffe2.python.workspace.FeedBlob', 'workspace.FeedBlob', (['"""w"""', 'w_f'], {'device_option': 'gc'}), "('w', w_f, device_option=gc)\n", (18248, 18276), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((18289, 18333), 'caffe2.python.workspace.FeedBlob', 'workspace.FeedBlob', (['"""b"""', 'b'], {'device_option': 'gc'}), "('b', b, device_option=gc)\n", (18307, 18333), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((18346, 18375), 'caffe2.python.workspace.RunOperatorOnce', 'workspace.RunOperatorOnce', (['op'], {}), '(op)\n', (18371, 18375), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((18405, 18429), 'caffe2.python.workspace.FetchBlob', 'workspace.FetchBlob', (['"""Y"""'], {}), "('Y')\n", (18424, 18429), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((16180, 16197), 'hypothesis.strategies.integers', 'st.integers', (['(1)', '(3)'], {}), '(1, 3)\n', (16191, 16197), True, 'import hypothesis.strategies as st\n'), ((16220, 16237), 'hypothesis.strategies.integers', 'st.integers', (['(1)', '(3)'], {}), '(1, 3)\n', (16231, 16237), True, 'import hypothesis.strategies as st\n'), ((16257, 16274), 'hypothesis.strategies.integers', 'st.integers', (['(0)', '(3)'], {}), '(0, 3)\n', (16268, 16274), True, 'import hypothesis.strategies as st\n'), ((16294, 16311), 'hypothesis.strategies.integers', 'st.integers', (['(0)', '(3)'], {}), '(0, 3)\n', (16305, 16311), True, 'import hypothesis.strategies as st\n'), ((16331, 16348), 'hypothesis.strategies.integers', 'st.integers', (['(0)', '(3)'], {}), '(0, 3)\n', (16342, 16348), True, 'import hypothesis.strategies as st\n'), ((16368, 16385), 'hypothesis.strategies.integers', 'st.integers', (['(0)', '(3)'], {}), '(0, 3)\n', (16379, 16385), True, 'import hypothesis.strategies as st\n'), ((16406, 16423), 'hypothesis.strategies.integers', 'st.integers', (['(1)', '(5)'], {}), '(1, 5)\n', (16417, 16423), True, 'import hypothesis.strategies as st\n'), ((16442, 16460), 'hypothesis.strategies.integers', 'st.integers', (['(7)', '(10)'], {}), '(7, 10)\n', (16453, 16460), True, 'import hypothesis.strategies as st\n'), ((16489, 16506), 'hypothesis.strategies.integers', 'st.integers', (['(1)', '(8)'], {}), '(1, 8)\n', (16500, 16506), True, 'import hypothesis.strategies as st\n'), ((16536, 16553), 'hypothesis.strategies.integers', 'st.integers', (['(1)', '(8)'], {}), '(1, 8)\n', (16547, 16553), True, 'import hypothesis.strategies as st\n'), ((16578, 16595), 'hypothesis.strategies.integers', 'st.integers', (['(1)', '(3)'], {}), '(1, 3)\n', (16589, 16595), True, 'import hypothesis.strategies as st\n'), ((16616, 16637), 'hypothesis.strategies.sampled_from', 'st.sampled_from', (["['']"], {}), "([''])\n", (16631, 16637), True, 'import hypothesis.strategies as st\n'), ((18613, 18630), 'hypothesis.strategies.integers', 'st.integers', (['(1)', '(3)'], {}), '(1, 3)\n', (18624, 18630), True, 'import hypothesis.strategies as st\n'), ((18647, 18664), 'hypothesis.strategies.integers', 'st.integers', (['(0)', '(3)'], {}), '(0, 3)\n', (18658, 18664), True, 'import hypothesis.strategies as st\n'), ((18684, 18701), 'hypothesis.strategies.integers', 'st.integers', (['(1)', '(5)'], {}), '(1, 5)\n', (18695, 18701), True, 'import hypothesis.strategies as st\n'), ((18719, 18737), 'hypothesis.strategies.integers', 'st.integers', (['(7)', '(10)'], {}), '(7, 10)\n', (18730, 18737), True, 'import hypothesis.strategies as st\n'), ((18765, 18782), 'hypothesis.strategies.integers', 'st.integers', (['(1)', '(8)'], {}), '(1, 8)\n', (18776, 18782), True, 'import hypothesis.strategies as st\n'), ((18811, 18828), 'hypothesis.strategies.integers', 'st.integers', (['(1)', '(8)'], {}), '(1, 8)\n', (18822, 18828), True, 'import hypothesis.strategies as st\n'), ((18852, 18869), 'hypothesis.strategies.integers', 'st.integers', (['(1)', '(3)'], {}), '(1, 3)\n', (18863, 18869), True, 'import hypothesis.strategies as st\n'), ((18888, 18921), 'hypothesis.strategies.sampled_from', 'st.sampled_from', (["['NCHW', 'NHWC']"], {}), "(['NCHW', 'NHWC'])\n", (18903, 18921), True, 'import hypothesis.strategies as st\n'), ((18941, 18971), 'hypothesis.strategies.sampled_from', 'st.sampled_from', (["['', 'CUDNN']"], {}), "(['', 'CUDNN'])\n", (18956, 18971), True, 'import hypothesis.strategies as st\n'), ((21017, 21158), 'caffe2.python.core.CreateOperator', 'core.CreateOperator', (['"""Conv"""', "['X', 'w', 'b']", "['Y']"], {'stride': 'stride', 'kernel': 'kernel', 'pad': 'pad', 'order': 'order', 'engine': 'engine', 'device_option': 'gc'}), "('Conv', ['X', 'w', 'b'], ['Y'], stride=stride, kernel=\n kernel, pad=pad, order=order, engine=engine, device_option=gc)\n", (21036, 21158), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((21519, 21565), 'caffe2.python.workspace.FeedBlob', 'workspace.FeedBlob', (['"""X"""', 'X_f'], {'device_option': 'gc'}), "('X', X_f, device_option=gc)\n", (21537, 21565), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((21578, 21624), 'caffe2.python.workspace.FeedBlob', 'workspace.FeedBlob', (['"""w"""', 'w_f'], {'device_option': 'gc'}), "('w', w_f, device_option=gc)\n", (21596, 21624), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((21637, 21681), 'caffe2.python.workspace.FeedBlob', 'workspace.FeedBlob', (['"""b"""', 'b'], {'device_option': 'gc'}), "('b', b, device_option=gc)\n", (21655, 21681), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((21694, 21723), 'caffe2.python.workspace.RunOperatorOnce', 'workspace.RunOperatorOnce', (['op'], {}), '(op)\n', (21719, 21723), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((21753, 21777), 'caffe2.python.workspace.FetchBlob', 'workspace.FetchBlob', (['"""Y"""'], {}), "('Y')\n", (21772, 21777), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((20097, 20114), 'hypothesis.strategies.integers', 'st.integers', (['(1)', '(3)'], {}), '(1, 3)\n', (20108, 20114), True, 'import hypothesis.strategies as st\n'), ((20131, 20148), 'hypothesis.strategies.integers', 'st.integers', (['(0)', '(3)'], {}), '(0, 3)\n', (20142, 20148), True, 'import hypothesis.strategies as st\n'), ((20168, 20185), 'hypothesis.strategies.integers', 'st.integers', (['(1)', '(5)'], {}), '(1, 5)\n', (20179, 20185), True, 'import hypothesis.strategies as st\n'), ((20203, 20221), 'hypothesis.strategies.integers', 'st.integers', (['(7)', '(10)'], {}), '(7, 10)\n', (20214, 20221), True, 'import hypothesis.strategies as st\n'), ((20249, 20266), 'hypothesis.strategies.integers', 'st.integers', (['(1)', '(8)'], {}), '(1, 8)\n', (20260, 20266), True, 'import hypothesis.strategies as st\n'), ((20295, 20312), 'hypothesis.strategies.integers', 'st.integers', (['(1)', '(8)'], {}), '(1, 8)\n', (20306, 20312), True, 'import hypothesis.strategies as st\n'), ((20336, 20353), 'hypothesis.strategies.integers', 'st.integers', (['(1)', '(3)'], {}), '(1, 3)\n', (20347, 20353), True, 'import hypothesis.strategies as st\n'), ((20373, 20403), 'hypothesis.strategies.sampled_from', 'st.sampled_from', (["['', 'CUDNN']"], {}), "(['', 'CUDNN'])\n", (20388, 20403), True, 'import hypothesis.strategies as st\n'), ((24406, 24426), 'numpy.random.seed', 'np.random.seed', (['(1701)'], {}), '(1701)\n', (24420, 24426), True, 'import numpy as np\n'), ((24909, 24936), 'caffe2.python.workspace.RunNetOnce', 'workspace.RunNetOnce', (['m.net'], {}), '(m.net)\n', (24929, 24936), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((25203, 25252), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['outputs[0]', 'output'], {}), '(outputs[0], output)\n', (25232, 25252), True, 'import numpy as np\n'), ((21966, 21983), 'hypothesis.strategies.integers', 'st.integers', (['(1)', '(4)'], {}), '(1, 4)\n', (21977, 21983), True, 'import hypothesis.strategies as st\n'), ((22005, 22099), 'hypothesis.strategies.sampled_from', 'st.sampled_from', (["(['simple', 'dag'] + (['async_dag'] if workspace.has_gpu_support else []))"], {}), "(['simple', 'dag'] + (['async_dag'] if workspace.\n has_gpu_support else []))\n", (22020, 22099), True, 'import hypothesis.strategies as st\n'), ((22141, 22175), 'hypothesis.strategies.sampled_from', 'st.sampled_from', (['hu.device_options'], {}), '(hu.device_options)\n', (22156, 22175), True, 'import hypothesis.strategies as st\n'), ((22195, 22225), 'hypothesis.strategies.sampled_from', 'st.sampled_from', (["['CUDNN', '']"], {}), "(['CUDNN', ''])\n", (22210, 22225), True, 'import hypothesis.strategies as st\n'), ((25418, 25435), 'hypothesis.strategies.integers', 'st.integers', (['(1)', '(3)'], {}), '(1, 3)\n', (25429, 25435), True, 'import hypothesis.strategies as st\n'), ((25452, 25469), 'hypothesis.strategies.integers', 'st.integers', (['(0)', '(3)'], {}), '(0, 3)\n', (25463, 25469), True, 'import hypothesis.strategies as st\n'), ((25489, 25506), 'hypothesis.strategies.integers', 'st.integers', (['(1)', '(5)'], {}), '(1, 5)\n', (25500, 25506), True, 'import hypothesis.strategies as st\n'), ((25523, 25540), 'hypothesis.strategies.integers', 'st.integers', (['(0)', '(2)'], {}), '(0, 2)\n', (25534, 25540), True, 'import hypothesis.strategies as st\n'), ((25558, 25576), 'hypothesis.strategies.integers', 'st.integers', (['(7)', '(10)'], {}), '(7, 10)\n', (25569, 25576), True, 'import hypothesis.strategies as st\n'), ((25604, 25621), 'hypothesis.strategies.integers', 'st.integers', (['(1)', '(8)'], {}), '(1, 8)\n', (25615, 25621), True, 'import hypothesis.strategies as st\n'), ((25650, 25667), 'hypothesis.strategies.integers', 'st.integers', (['(1)', '(8)'], {}), '(1, 8)\n', (25661, 25667), True, 'import hypothesis.strategies as st\n'), ((25691, 25708), 'hypothesis.strategies.integers', 'st.integers', (['(1)', '(3)'], {}), '(1, 3)\n', (25702, 25708), True, 'import hypothesis.strategies as st\n'), ((25727, 25760), 'hypothesis.strategies.sampled_from', 'st.sampled_from', (["['NCHW', 'NHWC']"], {}), "(['NCHW', 'NHWC'])\n", (25742, 25760), True, 'import hypothesis.strategies as st\n'), ((25780, 25810), 'hypothesis.strategies.sampled_from', 'st.sampled_from', (["['', 'CUDNN']"], {}), "(['', 'CUDNN'])\n", (25795, 25810), True, 'import hypothesis.strategies as st\n'), ((28126, 28288), 'caffe2.python.core.CreateOperator', 'core.CreateOperator', (['"""ConvTranspose"""', "['X', 'w', 'b']", "['Y']"], {'stride': 'stride', 'kernel': 'kernel', 'pad': 'pad', 'adj': 'adj', 'order': 'order', 'engine': 'engine', 'device_option': 'gc'}), "('ConvTranspose', ['X', 'w', 'b'], ['Y'], stride=stride,\n kernel=kernel, pad=pad, adj=adj, order=order, engine=engine,\n device_option=gc)\n", (28145, 28288), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((28662, 28708), 'caffe2.python.workspace.FeedBlob', 'workspace.FeedBlob', (['"""X"""', 'X_f'], {'device_option': 'gc'}), "('X', X_f, device_option=gc)\n", (28680, 28708), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((28721, 28767), 'caffe2.python.workspace.FeedBlob', 'workspace.FeedBlob', (['"""w"""', 'w_f'], {'device_option': 'gc'}), "('w', w_f, device_option=gc)\n", (28739, 28767), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((28780, 28824), 'caffe2.python.workspace.FeedBlob', 'workspace.FeedBlob', (['"""b"""', 'b'], {'device_option': 'gc'}), "('b', b, device_option=gc)\n", (28798, 28824), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((28837, 28866), 'caffe2.python.workspace.RunOperatorOnce', 'workspace.RunOperatorOnce', (['op'], {}), '(op)\n', (28862, 28866), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((28896, 28920), 'caffe2.python.workspace.FetchBlob', 'workspace.FetchBlob', (['"""Y"""'], {}), "('Y')\n", (28915, 28920), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((27065, 27082), 'hypothesis.strategies.integers', 'st.integers', (['(1)', '(3)'], {}), '(1, 3)\n', (27076, 27082), True, 'import hypothesis.strategies as st\n'), ((27099, 27116), 'hypothesis.strategies.integers', 'st.integers', (['(0)', '(3)'], {}), '(0, 3)\n', (27110, 27116), True, 'import hypothesis.strategies as st\n'), ((27136, 27153), 'hypothesis.strategies.integers', 'st.integers', (['(1)', '(5)'], {}), '(1, 5)\n', (27147, 27153), True, 'import hypothesis.strategies as st\n'), ((27170, 27187), 'hypothesis.strategies.integers', 'st.integers', (['(0)', '(2)'], {}), '(0, 2)\n', (27181, 27187), True, 'import hypothesis.strategies as st\n'), ((27205, 27223), 'hypothesis.strategies.integers', 'st.integers', (['(7)', '(10)'], {}), '(7, 10)\n', (27216, 27223), True, 'import hypothesis.strategies as st\n'), ((27251, 27268), 'hypothesis.strategies.integers', 'st.integers', (['(1)', '(8)'], {}), '(1, 8)\n', (27262, 27268), True, 'import hypothesis.strategies as st\n'), ((27297, 27314), 'hypothesis.strategies.integers', 'st.integers', (['(1)', '(8)'], {}), '(1, 8)\n', (27308, 27314), True, 'import hypothesis.strategies as st\n'), ((27338, 27355), 'hypothesis.strategies.integers', 'st.integers', (['(1)', '(3)'], {}), '(1, 3)\n', (27349, 27355), True, 'import hypothesis.strategies as st\n'), ((27375, 27405), 'hypothesis.strategies.sampled_from', 'st.sampled_from', (["['', 'CUDNN']"], {}), "(['', 'CUDNN'])\n", (27390, 27405), True, 'import hypothesis.strategies as st\n'), ((29568, 29597), 'caffe2.python.workspace.RunOperatorOnce', 'workspace.RunOperatorOnce', (['op'], {}), '(op)\n', (29593, 29597), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((29300, 29360), 'hypothesis.strategies.sampled_from', 'st.sampled_from', (['[np.float32, np.float64, np.int32, np.bool]'], {}), '([np.float32, np.float64, np.int32, np.bool])\n', (29315, 29360), True, 'import hypothesis.strategies as st\n'), ((30139, 30149), 'numpy.abs', 'np.abs', (['m2'], {}), '(m2)\n', (30145, 30149), True, 'import numpy as np\n'), ((29618, 29633), 'caffe2.python.hypothesis_test_util.tensors', 'hu.tensors', ([], {'n': '(3)'}), '(n=3)\n', (29628, 29633), True, 'import caffe2.python.hypothesis_test_util as hu\n'), ((29655, 29668), 'hypothesis.strategies.booleans', 'st.booleans', ([], {}), '()\n', (29666, 29668), True, 'import hypothesis.strategies as st\n'), ((29687, 29726), 'hypothesis.strategies.floats', 'st.floats', ([], {'min_value': '(0.1)', 'max_value': '(0.9)'}), '(min_value=0.1, max_value=0.9)\n', (29696, 29726), True, 'import hypothesis.strategies as st\n'), ((29745, 29784), 'hypothesis.strategies.floats', 'st.floats', ([], {'min_value': '(0.1)', 'max_value': '(0.9)'}), '(min_value=0.1, max_value=0.9)\n', (29754, 29784), True, 'import hypothesis.strategies as st\n'), ((29800, 29839), 'hypothesis.strategies.floats', 'st.floats', ([], {'min_value': '(0.1)', 'max_value': '(0.9)'}), '(min_value=0.1, max_value=0.9)\n', (29809, 29839), True, 'import hypothesis.strategies as st\n'), ((29858, 29899), 'hypothesis.strategies.integers', 'st.integers', ([], {'min_value': '(1)', 'max_value': '(10000)'}), '(min_value=1, max_value=10000)\n', (29869, 29899), True, 'import hypothesis.strategies as st\n'), ((29920, 29962), 'hypothesis.strategies.floats', 'st.floats', ([], {'min_value': '(1e-05)', 'max_value': '(0.01)'}), '(min_value=1e-05, max_value=0.01)\n', (29929, 29962), True, 'import hypothesis.strategies as st\n'), ((31408, 31423), 'caffe2.python.hypothesis_test_util.tensors', 'hu.tensors', ([], {'n': '(2)'}), '(n=2)\n', (31418, 31423), True, 'import caffe2.python.hypothesis_test_util as hu\n'), ((31445, 31458), 'hypothesis.strategies.booleans', 'st.booleans', ([], {}), '()\n', (31456, 31458), True, 'import hypothesis.strategies as st\n'), ((31480, 31519), 'hypothesis.strategies.floats', 'st.floats', ([], {'min_value': '(0.1)', 'max_value': '(0.9)'}), '(min_value=0.1, max_value=0.9)\n', (31489, 31519), True, 'import hypothesis.strategies as st\n'), ((31541, 31554), 'hypothesis.strategies.booleans', 'st.booleans', ([], {}), '()\n', (31552, 31554), True, 'import hypothesis.strategies as st\n'), ((31570, 31609), 'hypothesis.strategies.floats', 'st.floats', ([], {'min_value': '(0.1)', 'max_value': '(0.9)'}), '(min_value=0.1, max_value=0.9)\n', (31579, 31609), True, 'import hypothesis.strategies as st\n'), ((33084, 33094), 'numpy.abs', 'np.abs', (['ms'], {}), '(ms)\n', (33090, 33094), True, 'import numpy as np\n'), ((32618, 32633), 'caffe2.python.hypothesis_test_util.tensors', 'hu.tensors', ([], {'n': '(3)'}), '(n=3)\n', (32628, 32633), True, 'import caffe2.python.hypothesis_test_util as hu\n'), ((32655, 32668), 'hypothesis.strategies.booleans', 'st.booleans', ([], {}), '()\n', (32666, 32668), True, 'import hypothesis.strategies as st\n'), ((32687, 32726), 'hypothesis.strategies.floats', 'st.floats', ([], {'min_value': '(0.1)', 'max_value': '(0.9)'}), '(min_value=0.1, max_value=0.9)\n', (32696, 32726), True, 'import hypothesis.strategies as st\n'), ((32748, 32787), 'hypothesis.strategies.floats', 'st.floats', ([], {'min_value': '(0.1)', 'max_value': '(0.9)'}), '(min_value=0.1, max_value=0.9)\n', (32757, 32787), True, 'import hypothesis.strategies as st\n'), ((32803, 32842), 'hypothesis.strategies.floats', 'st.floats', ([], {'min_value': '(0.1)', 'max_value': '(0.9)'}), '(min_value=0.1, max_value=0.9)\n', (32812, 32842), True, 'import hypothesis.strategies as st\n'), ((32863, 32905), 'hypothesis.strategies.floats', 'st.floats', ([], {'min_value': '(1e-05)', 'max_value': '(0.01)'}), '(min_value=1e-05, max_value=0.01)\n', (32872, 32905), True, 'import hypothesis.strategies as st\n'), ((33971, 33986), 'numpy.square', 'np.square', (['grad'], {}), '(grad)\n', (33980, 33986), True, 'import numpy as np\n'), ((34412, 34421), 'numpy.abs', 'np.abs', (['h'], {}), '(h)\n', (34418, 34421), True, 'import numpy as np\n'), ((34857, 34894), 'functools.partial', 'partial', (['self._dense_adagrad', 'epsilon'], {}), '(self._dense_adagrad, epsilon)\n', (34864, 34894), False, 'from functools import partial\n'), ((34089, 34104), 'caffe2.python.hypothesis_test_util.tensors', 'hu.tensors', ([], {'n': '(2)'}), '(n=2)\n', (34099, 34104), True, 'import caffe2.python.hypothesis_test_util as hu\n'), ((34126, 34139), 'hypothesis.strategies.booleans', 'st.booleans', ([], {}), '()\n', (34137, 34139), True, 'import hypothesis.strategies as st\n'), ((34155, 34194), 'hypothesis.strategies.floats', 'st.floats', ([], {'min_value': '(0.1)', 'max_value': '(0.9)'}), '(min_value=0.1, max_value=0.9)\n', (34164, 34194), True, 'import hypothesis.strategies as st\n'), ((34215, 34257), 'hypothesis.strategies.floats', 'st.floats', ([], {'min_value': '(1e-05)', 'max_value': '(0.01)'}), '(min_value=1e-05, max_value=0.01)\n', (34224, 34257), True, 'import hypothesis.strategies as st\n'), ((34915, 34930), 'caffe2.python.hypothesis_test_util.tensors', 'hu.tensors', ([], {'n': '(2)'}), '(n=2)\n', (34925, 34930), True, 'import caffe2.python.hypothesis_test_util as hu\n'), ((34946, 34985), 'hypothesis.strategies.floats', 'st.floats', ([], {'min_value': '(0.1)', 'max_value': '(0.9)'}), '(min_value=0.1, max_value=0.9)\n', (34955, 34985), True, 'import hypothesis.strategies as st\n'), ((35006, 35048), 'hypothesis.strategies.floats', 'st.floats', ([], {'min_value': '(1e-05)', 'max_value': '(0.01)'}), '(min_value=1e-05, max_value=0.01)\n', (35015, 35048), True, 'import hypothesis.strategies as st\n'), ((36376, 36401), 'numpy.stack', 'np.stack', (['[n, z]'], {'axis': '(-1)'}), '([n, z], axis=-1)\n', (36384, 36401), True, 'import numpy as np\n'), ((37471, 37527), 'functools.partial', 'partial', (['self._dense_ftrl', 'alpha', 'beta', 'lambda1', 'lambda2'], {}), '(self._dense_ftrl, alpha, beta, lambda1, lambda2)\n', (37478, 37527), False, 'from functools import partial\n'), ((36422, 36437), 'caffe2.python.hypothesis_test_util.tensors', 'hu.tensors', ([], {'n': '(4)'}), '(n=4)\n', (36432, 36437), True, 'import caffe2.python.hypothesis_test_util as hu\n'), ((36459, 36472), 'hypothesis.strategies.booleans', 'st.booleans', ([], {}), '()\n', (36470, 36472), True, 'import hypothesis.strategies as st\n'), ((36491, 36531), 'hypothesis.strategies.floats', 'st.floats', ([], {'min_value': '(0.01)', 'max_value': '(0.1)'}), '(min_value=0.01, max_value=0.1)\n', (36500, 36531), True, 'import hypothesis.strategies as st\n'), ((36549, 36588), 'hypothesis.strategies.floats', 'st.floats', ([], {'min_value': '(0.1)', 'max_value': '(0.9)'}), '(min_value=0.1, max_value=0.9)\n', (36558, 36588), True, 'import hypothesis.strategies as st\n'), ((36609, 36650), 'hypothesis.strategies.floats', 'st.floats', ([], {'min_value': '(0.001)', 'max_value': '(0.1)'}), '(min_value=0.001, max_value=0.1)\n', (36618, 36650), True, 'import hypothesis.strategies as st\n'), ((36671, 36712), 'hypothesis.strategies.floats', 'st.floats', ([], {'min_value': '(0.001)', 'max_value': '(0.1)'}), '(min_value=0.001, max_value=0.1)\n', (36680, 36712), True, 'import hypothesis.strategies as st\n'), ((36732, 36763), 'hypothesis.strategies.sampled_from', 'st.sampled_from', (["[None, 'SIMD']"], {}), "([None, 'SIMD'])\n", (36747, 36763), True, 'import hypothesis.strategies as st\n'), ((37548, 37563), 'caffe2.python.hypothesis_test_util.tensors', 'hu.tensors', ([], {'n': '(4)'}), '(n=4)\n', (37558, 37563), True, 'import caffe2.python.hypothesis_test_util as hu\n'), ((37582, 37622), 'hypothesis.strategies.floats', 'st.floats', ([], {'min_value': '(0.01)', 'max_value': '(0.1)'}), '(min_value=0.01, max_value=0.1)\n', (37591, 37622), True, 'import hypothesis.strategies as st\n'), ((37640, 37679), 'hypothesis.strategies.floats', 'st.floats', ([], {'min_value': '(0.1)', 'max_value': '(0.9)'}), '(min_value=0.1, max_value=0.9)\n', (37649, 37679), True, 'import hypothesis.strategies as st\n'), ((37700, 37741), 'hypothesis.strategies.floats', 'st.floats', ([], {'min_value': '(0.001)', 'max_value': '(0.1)'}), '(min_value=0.001, max_value=0.1)\n', (37709, 37741), True, 'import hypothesis.strategies as st\n'), ((37762, 37803), 'hypothesis.strategies.floats', 'st.floats', ([], {'min_value': '(0.001)', 'max_value': '(0.1)'}), '(min_value=0.001, max_value=0.1)\n', (37771, 37803), True, 'import hypothesis.strategies as st\n'), ((37823, 37854), 'hypothesis.strategies.sampled_from', 'st.sampled_from', (["[None, 'SIMD']"], {}), "([None, 'SIMD'])\n", (37838, 37854), True, 'import hypothesis.strategies as st\n'), ((39192, 39205), 'hypothesis.strategies.booleans', 'st.booleans', ([], {}), '()\n', (39203, 39205), True, 'import hypothesis.strategies as st\n'), ((40894, 40923), 'numpy.argmax', 'np.argmax', (['prediction'], {'axis': '(1)'}), '(prediction, axis=1)\n', (40903, 40923), True, 'import numpy as np\n'), ((41857, 41897), 'numpy.power', 'np.power', (['target_probabilities', '(-1.0 / N)'], {}), '(target_probabilities, -1.0 / N)\n', (41865, 41897), True, 'import numpy as np\n'), ((41923, 41963), 'functools.reduce', 'reduce', (['(lambda x, y: x * y)', 'perplexities'], {}), '(lambda x, y: x * y, perplexities)\n', (41929, 41963), False, 'from functools import reduce\n'), ((43783, 43807), 'numpy.empty', 'np.empty', (['D'], {'dtype': 'float'}), '(D, dtype=float)\n', (43791, 43807), True, 'import numpy as np\n'), ((43861, 43883), 'numpy.empty', 'np.empty', (['D'], {'dtype': 'int'}), '(D, dtype=int)\n', (43869, 43883), True, 'import numpy as np\n'), ((43934, 43963), 'numpy.argmax', 'np.argmax', (['prediction'], {'axis': '(1)'}), '(prediction, axis=1)\n', (43943, 43963), True, 'import numpy as np\n'), ((48689, 48732), 'threading.Thread', 'threading.Thread', ([], {'target': 'enqueue', 'args': '(t,)'}), '(target=enqueue, args=(t,))\n', (48705, 48732), False, 'import threading\n'), ((48974, 49053), 'caffe2.python.core.CreateOperator', 'core.CreateOperator', (['"""DequeueBlobs"""', "['queue']", 'dequeue_blobs'], {'device_option': 'do'}), "('DequeueBlobs', ['queue'], dequeue_blobs, device_option=do)\n", (48993, 49053), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((49131, 49160), 'caffe2.python.workspace.RunOperatorOnce', 'workspace.RunOperatorOnce', (['op'], {}), '(op)\n', (49156, 49160), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((46661, 46679), 'hypothesis.strategies.integers', 'st.integers', (['(1)', '(10)'], {}), '(1, 10)\n', (46672, 46679), True, 'import hypothesis.strategies as st\n'), ((46713, 46732), 'hypothesis.strategies.integers', 'st.integers', (['(1)', '(100)'], {}), '(1, 100)\n', (46724, 46732), True, 'import hypothesis.strategies as st\n'), ((46754, 46771), 'hypothesis.strategies.integers', 'st.integers', (['(1)', '(5)'], {}), '(1, 5)\n', (46765, 46771), True, 'import hypothesis.strategies as st\n'), ((46794, 46811), 'hypothesis.strategies.integers', 'st.integers', (['(1)', '(3)'], {}), '(1, 3)\n', (46805, 46811), True, 'import hypothesis.strategies as st\n'), ((46827, 46861), 'hypothesis.strategies.sampled_from', 'st.sampled_from', (['hu.device_options'], {}), '(hu.device_options)\n', (46842, 46861), True, 'import hypothesis.strategies as st\n'), ((50567, 50581), 'caffe2.python.core.Net', 'core.Net', (['name'], {}), '(name)\n', (50575, 50581), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((50862, 50908), 'caffe2.python.core.execution_step', 'core.execution_step', (['name', 'net'], {'num_iter': 'count'}), '(name, net, num_iter=count)\n', (50881, 50908), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((51534, 51548), 'caffe2.python.core.Net', 'core.Net', (['name'], {}), '(name)\n', (51542, 51548), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((51666, 51693), 'caffe2.python.core.Net', 'core.Net', (["(name + '_counter')"], {}), "(name + '_counter')\n", (51674, 51693), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((49969, 49987), 'hypothesis.strategies.integers', 'st.integers', (['(1)', '(10)'], {}), '(1, 10)\n', (49980, 49987), True, 'import hypothesis.strategies as st\n'), ((50014, 50032), 'hypothesis.strategies.integers', 'st.integers', (['(1)', '(10)'], {}), '(1, 10)\n', (50025, 50032), True, 'import hypothesis.strategies as st\n'), ((50054, 50071), 'hypothesis.strategies.integers', 'st.integers', (['(1)', '(5)'], {}), '(1, 5)\n', (50065, 50071), True, 'import hypothesis.strategies as st\n'), ((50094, 50111), 'hypothesis.strategies.integers', 'st.integers', (['(1)', '(3)'], {}), '(1, 3)\n', (50105, 50111), True, 'import hypothesis.strategies as st\n'), ((50127, 50161), 'hypothesis.strategies.sampled_from', 'st.sampled_from', (['hu.device_options'], {}), '(hu.device_options)\n', (50142, 50161), True, 'import hypothesis.strategies as st\n'), ((52564, 52575), 'caffe2.python.hypothesis_test_util.tensor', 'hu.tensor', ([], {}), '()\n', (52573, 52575), True, 'import caffe2.python.hypothesis_test_util as hu\n'), ((55232, 55258), 'numpy.linalg.norm', 'np.linalg.norm', (['(golden - Y)'], {}), '(golden - Y)\n', (55246, 55258), True, 'import numpy as np\n'), ((57162, 57182), 'numpy.random.seed', 'np.random.seed', (['(1701)'], {}), '(1701)\n', (57176, 57182), True, 'import numpy as np\n'), ((57651, 57678), 'caffe2.python.workspace.RunNetOnce', 'workspace.RunNetOnce', (['m.net'], {}), '(m.net)\n', (57671, 57678), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((57945, 57994), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['outputs[0]', 'output'], {}), '(outputs[0], output)\n', (57974, 57994), True, 'import numpy as np\n'), ((55300, 55318), 'hypothesis.strategies.integers', 'st.integers', (['(1)', '(10)'], {}), '(1, 10)\n', (55311, 55318), True, 'import hypothesis.strategies as st\n'), ((55340, 55434), 'hypothesis.strategies.sampled_from', 'st.sampled_from', (["(['simple', 'dag'] + (['async_dag'] if workspace.has_gpu_support else []))"], {}), "(['simple', 'dag'] + (['async_dag'] if workspace.\n has_gpu_support else []))\n", (55355, 55434), True, 'import hypothesis.strategies as st\n'), ((55476, 55510), 'hypothesis.strategies.sampled_from', 'st.sampled_from', (['hu.device_options'], {}), '(hu.device_options)\n', (55491, 55510), True, 'import hypothesis.strategies as st\n'), ((58333, 58346), 'hypothesis.strategies.integers', 'st.integers', ([], {}), '()\n', (58344, 58346), True, 'import hypothesis.strategies as st\n'), ((58361, 58374), 'hypothesis.strategies.integers', 'st.integers', ([], {}), '()\n', (58372, 58374), True, 'import hypothesis.strategies as st\n'), ((58389, 58402), 'hypothesis.strategies.integers', 'st.integers', ([], {}), '()\n', (58400, 58402), True, 'import hypothesis.strategies as st\n'), ((59270, 59281), 'caffe2.python.hypothesis_test_util.tensor', 'hu.tensor', ([], {}), '()\n', (59279, 59281), True, 'import caffe2.python.hypothesis_test_util as hu\n'), ((59496, 59507), 'caffe2.python.hypothesis_test_util.tensor', 'hu.tensor', ([], {}), '()\n', (59505, 59507), True, 'import caffe2.python.hypothesis_test_util as hu\n'), ((59901, 59920), 'hypothesis.strategies.integers', 'st.integers', (['(0)', '(100)'], {}), '(0, 100)\n', (59912, 59920), True, 'import hypothesis.strategies as st\n'), ((59943, 59962), 'hypothesis.strategies.integers', 'st.integers', (['(0)', '(100)'], {}), '(0, 100)\n', (59954, 59962), True, 'import hypothesis.strategies as st\n'), ((62752, 62790), 'caffe2.python.core.execution_step', 'core.execution_step', (['"""step_3"""', 'nets[2]'], {}), "('step_3', nets[2])\n", (62771, 62790), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((62891, 62942), 'caffe2.python.core.execution_step', 'core.execution_step', (['"""all_steps"""', 'steps'], {'num_iter': '(3)'}), "('all_steps', steps, num_iter=3)\n", (62910, 62942), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((63168, 63187), 'hypothesis.strategies.integers', 'st.integers', (['(0)', '(100)'], {}), '(0, 100)\n', (63179, 63187), True, 'import hypothesis.strategies as st\n'), ((63210, 63229), 'hypothesis.strategies.integers', 'st.integers', (['(0)', '(100)'], {}), '(0, 100)\n', (63221, 63229), True, 'import hypothesis.strategies as st\n'), ((64308, 64321), 'numpy.iinfo', 'np.iinfo', (['dst'], {}), '(dst)\n', (64316, 64321), True, 'import numpy as np\n'), ((64338, 64368), 'numpy.clip', 'np.clip', (['a', 'info.min', 'info.max'], {}), '(a, info.min, info.max)\n', (64345, 64368), True, 'import numpy as np\n'), ((63812, 63823), 'caffe2.python.hypothesis_test_util.tensor', 'hu.tensor', ([], {}), '()\n', (63821, 63823), True, 'import caffe2.python.hypothesis_test_util as hu\n'), ((63965, 63978), 'hypothesis.strategies.booleans', 'st.booleans', ([], {}), '()\n', (63976, 63978), True, 'import hypothesis.strategies as st\n'), ((64773, 64791), 'hypothesis.strategies.integers', 'st.integers', (['(1)', '(10)'], {}), '(1, 10)\n', (64784, 64791), True, 'import hypothesis.strategies as st\n'), ((64806, 64824), 'hypothesis.strategies.integers', 'st.integers', (['(1)', '(10)'], {}), '(1, 10)\n', (64817, 64824), True, 'import hypothesis.strategies as st\n'), ((64839, 64857), 'hypothesis.strategies.integers', 'st.integers', (['(1)', '(10)'], {}), '(1, 10)\n', (64850, 64857), True, 'import hypothesis.strategies as st\n'), ((65925, 65942), 'hypothesis.strategies.integers', 'st.integers', (['(1)', '(5)'], {}), '(1, 5)\n', (65936, 65942), True, 'import hypothesis.strategies as st\n'), ((65957, 65974), 'hypothesis.strategies.integers', 'st.integers', (['(1)', '(5)'], {}), '(1, 5)\n', (65968, 65974), True, 'import hypothesis.strategies as st\n'), ((65989, 66006), 'hypothesis.strategies.integers', 'st.integers', (['(1)', '(5)'], {}), '(1, 5)\n', (66000, 66006), True, 'import hypothesis.strategies as st\n'), ((66021, 66038), 'hypothesis.strategies.integers', 'st.integers', (['(1)', '(5)'], {}), '(1, 5)\n', (66032, 66038), True, 'import hypothesis.strategies as st\n'), ((66055, 66072), 'hypothesis.strategies.integers', 'st.integers', (['(0)', '(2)'], {}), '(0, 2)\n', (66066, 66072), True, 'import hypothesis.strategies as st\n'), ((66096, 66113), 'hypothesis.strategies.integers', 'st.integers', (['(2)', '(3)'], {}), '(2, 3)\n', (66107, 66113), True, 'import hypothesis.strategies as st\n'), ((66610, 66627), 'hypothesis.strategies.integers', 'st.integers', (['(1)', '(5)'], {}), '(1, 5)\n', (66621, 66627), True, 'import hypothesis.strategies as st\n'), ((66642, 66659), 'hypothesis.strategies.integers', 'st.integers', (['(1)', '(5)'], {}), '(1, 5)\n', (66653, 66659), True, 'import hypothesis.strategies as st\n'), ((66674, 66691), 'hypothesis.strategies.integers', 'st.integers', (['(1)', '(5)'], {}), '(1, 5)\n', (66685, 66691), True, 'import hypothesis.strategies as st\n'), ((66706, 66723), 'hypothesis.strategies.integers', 'st.integers', (['(1)', '(5)'], {}), '(1, 5)\n', (66717, 66723), True, 'import hypothesis.strategies as st\n'), ((66740, 66757), 'hypothesis.strategies.integers', 'st.integers', (['(0)', '(2)'], {}), '(0, 2)\n', (66751, 66757), True, 'import hypothesis.strategies as st\n'), ((66781, 66798), 'hypothesis.strategies.integers', 'st.integers', (['(2)', '(3)'], {}), '(2, 3)\n', (66792, 66798), True, 'import hypothesis.strategies as st\n'), ((67421, 67432), 'caffe2.python.hypothesis_test_util.tensor', 'hu.tensor', ([], {}), '()\n', (67430, 67432), True, 'import caffe2.python.hypothesis_test_util as hu\n'), ((67454, 67467), 'hypothesis.strategies.booleans', 'st.booleans', ([], {}), '()\n', (67465, 67467), True, 'import hypothesis.strategies as st\n'), ((67486, 67526), 'hypothesis.strategies.floats', 'st.floats', ([], {'min_value': '(-2.0)', 'max_value': '(2.0)'}), '(min_value=-2.0, max_value=2.0)\n', (67495, 67526), True, 'import hypothesis.strategies as st\n'), ((68135, 68186), 'caffe2.python.core.CreateOperator', 'core.CreateOperator', (['"""Transpose"""', '"""input"""', '"""output"""'], {}), "('Transpose', 'input', 'output')\n", (68154, 68186), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((68329, 68391), 'caffe2.python.core.CreateOperator', 'core.CreateOperator', (['"""Transpose"""', '"""input"""', '"""output"""'], {'axes': 'axes'}), "('Transpose', 'input', 'output', axes=axes)\n", (68348, 68391), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((67914, 67955), 'hypothesis.strategies.integers', 'st.integers', ([], {'min_value': '(0)', 'max_value': '(65536)'}), '(min_value=0, max_value=65536)\n', (67925, 67955), True, 'import hypothesis.strategies as st\n'), ((67978, 67991), 'hypothesis.strategies.booleans', 'st.booleans', ([], {}), '()\n', (67989, 67991), True, 'import hypothesis.strategies as st\n'), ((68975, 68999), 'caffe2.python.workspace.FetchBlob', 'workspace.FetchBlob', (['"""a"""'], {}), "('a')\n", (68994, 68999), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((69029, 69053), 'caffe2.python.workspace.FetchBlob', 'workspace.FetchBlob', (['"""b"""'], {}), "('b')\n", (69048, 69053), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((68724, 68733), 'hypothesis.strategies.text', 'st.text', ([], {}), '()\n', (68731, 68733), True, 'import hypothesis.strategies as st\n'), ((69887, 69917), 'caffe2.python.workspace.FetchBlob', 'workspace.FetchBlob', (['"""l2_dist"""'], {}), "('l2_dist')\n", (69906, 69917), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((70223, 70249), 'caffe2.python.workspace.FetchBlob', 'workspace.FetchBlob', (['"""dot"""'], {}), "('dot')\n", (70242, 70249), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((70774, 70800), 'caffe2.python.workspace.FetchBlob', 'workspace.FetchBlob', (['"""cos"""'], {}), "('cos')\n", (70793, 70800), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((69069, 69086), 'hypothesis.strategies.integers', 'st.integers', (['(1)', '(3)'], {}), '(1, 3)\n', (69080, 69086), True, 'import hypothesis.strategies as st\n'), ((69103, 69121), 'hypothesis.strategies.integers', 'st.integers', (['(4)', '(16)'], {}), '(4, 16)\n', (69114, 69121), True, 'import hypothesis.strategies as st\n'), ((801, 822), 'numpy.ones', 'np.ones', ([], {'shape': '(N, D)'}), '(shape=(N, D))\n', (808, 822), True, 'import numpy as np\n'), ((889, 910), 'numpy.ones', 'np.ones', ([], {'shape': '(N, D)'}), '(shape=(N, D))\n', (896, 910), True, 'import numpy as np\n'), ((3828, 3841), 'hypothesis.strategies.booleans', 'st.booleans', ([], {}), '()\n', (3839, 3841), True, 'import hypothesis.strategies as st\n'), ((3864, 3878), 'hypothesis.strategies.just', 'st.just', (['(False)'], {}), '(False)\n', (3871, 3878), True, 'import hypothesis.strategies as st\n'), ((8431, 8470), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['ys[0]', 'y'], {}), '(ys[0], y)\n', (8460, 8470), True, 'import numpy as np\n'), ((8848, 8878), 'numpy.random.randn', 'np.random.randn', (['(1)', '(2)', '(3)', '(2)', '(1)'], {}), '(1, 2, 3, 2, 1)\n', (8863, 8878), True, 'import numpy as np\n'), ((9083, 9104), 'numpy.random.randn', 'np.random.randn', (['N', 'K'], {}), '(N, K)\n', (9098, 9104), True, 'import numpy as np\n'), ((9136, 9154), 'numpy.random.randn', 'np.random.randn', (['N'], {}), '(N)\n', (9151, 9154), True, 'import numpy as np\n'), ((11395, 11419), 'numpy.random.randn', 'np.random.randn', (['T', 'N', 'D'], {}), '(T, N, D)\n', (11410, 11419), True, 'import numpy as np\n'), ((11600, 11660), 'numpy.random.randn', 'np.random.randn', (['hidden_size', 'N', '(num_layers * num_directions)'], {}), '(hidden_size, N, num_layers * num_directions)\n', (11615, 11660), True, 'import numpy as np\n'), ((29410, 29434), 'numpy.random.permutation', 'np.random.permutation', (['(6)'], {}), '(6)\n', (29431, 29434), True, 'import numpy as np\n'), ((34017, 34029), 'numpy.sqrt', 'np.sqrt', (['h_o'], {}), '(h_o)\n', (34024, 34029), True, 'import numpy as np\n'), ((36146, 36161), 'numpy.sqrt', 'np.sqrt', (['(n + g2)'], {}), '(n + g2)\n', (36153, 36161), True, 'import numpy as np\n'), ((36164, 36174), 'numpy.sqrt', 'np.sqrt', (['n'], {}), '(n)\n', (36171, 36174), True, 'import numpy as np\n'), ((36331, 36340), 'numpy.abs', 'np.abs', (['z'], {}), '(z)\n', (36337, 36340), True, 'import numpy as np\n'), ((39915, 39961), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['remapped', 'input'], {}), '(remapped, input)\n', (39944, 39961), True, 'import numpy as np\n'), ((42673, 42698), 'numpy.array', 'np.array', (['sids'], {'dtype': 'int'}), '(sids, dtype=int)\n', (42681, 42698), True, 'import numpy as np\n'), ((42185, 42223), 'hypothesis.strategies.integers', 'st.integers', ([], {'min_value': '(0)', 'max_value': '(10)'}), '(min_value=0, max_value=10)\n', (42196, 42223), True, 'import hypothesis.strategies as st\n'), ((45867, 45895), 'numpy.array', 'np.array', (['lengths'], {'dtype': 'int'}), '(lengths, dtype=int)\n', (45875, 45895), True, 'import numpy as np\n'), ((44564, 44602), 'hypothesis.strategies.integers', 'st.integers', ([], {'min_value': '(0)', 'max_value': '(10)'}), '(min_value=0, max_value=10)\n', (44575, 44602), True, 'import hypothesis.strategies as st\n'), ((46462, 46482), 'numpy.exp', 'np.exp', (['input_tensor'], {}), '(input_tensor)\n', (46468, 46482), True, 'import numpy as np\n'), ((47933, 48026), 'caffe2.python.core.CreateOperator', 'core.CreateOperator', (['"""EnqueueBlobs"""', "(['queue'] + feed_blobs)", 'feed_blobs'], {'device_option': 'do'}), "('EnqueueBlobs', ['queue'] + feed_blobs, feed_blobs,\n device_option=do)\n", (47952, 48026), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((51158, 51232), 'caffe2.python.core.execution_step', 'core.execution_step', (['"""producers"""', 'producer_steps'], {'concurrent_substeps': '(True)'}), "('producers', producer_steps, concurrent_substeps=True)\n", (51177, 51232), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((51263, 51318), 'caffe2.python.core.execution_step', 'core.execution_step', (['"""producer_exit"""', 'producer_exit_net'], {}), "('producer_exit', producer_exit_net)\n", (51282, 51318), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((51877, 51941), 'caffe2.python.core.execution_step', 'core.execution_step', (['name', '[net1, net2]'], {'should_stop_blob': 'status'}), '(name, [net1, net2], should_stop_blob=status)\n', (51896, 51941), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((53113, 53140), 'numpy.expand_dims', 'np.expand_dims', (['r'], {'axis': 'dim'}), '(r, axis=dim)\n', (53127, 53140), True, 'import numpy as np\n'), ((53392, 53415), 'numpy.squeeze', 'np.squeeze', (['r'], {'axis': 'dim'}), '(r, axis=dim)\n', (53402, 53415), True, 'import numpy as np\n'), ((54235, 54253), 'numpy.array', 'np.array', (['([0] * 16)'], {}), '([0] * 16)\n', (54243, 54253), True, 'import numpy as np\n'), ((65124, 65148), 'numpy.random.randn', 'np.random.randn', (['(1)', 'n', 'd'], {}), '(1, n, d)\n', (65139, 65148), True, 'import numpy as np\n'), ((65184, 65212), 'numpy.random.randn', 'np.random.randn', (['(1)', 'n', '(4 * d)'], {}), '(1, n, 4 * d)\n', (65199, 65212), True, 'import numpy as np\n'), ((65254, 65288), 'numpy.random.randint', 'np.random.randint', (['(0)', 't'], {'size': '(n,)'}), '(0, t, size=(n,))\n', (65271, 65288), True, 'import numpy as np\n'), ((65325, 65359), 'numpy.random.randint', 'np.random.randint', (['(0)', 't'], {'size': '(1,)'}), '(0, t, size=(1,))\n', (65342, 65359), True, 'import numpy as np\n'), ((66316, 66343), 'numpy.random.randn', 'np.random.randn', (['n', 'c', 'h', 'w'], {}), '(n, c, h, w)\n', (66331, 66343), True, 'import numpy as np\n'), ((67001, 67108), 'numpy.random.randn', 'np.random.randn', (['(n * block_size * block_size)', 'c', '((h + 2 * pad) / block_size)', '((w + 2 * pad) / block_size)'], {}), '(n * block_size * block_size, c, (h + 2 * pad) / block_size,\n (w + 2 * pad) / block_size)\n', (67016, 67108), True, 'import numpy as np\n'), ((68466, 68487), 'numpy.transpose', 'np.transpose', (['x', 'axes'], {}), '(x, axes)\n', (68478, 68487), True, 'import numpy as np\n'), ((69211, 69245), 'numpy.random.uniform', 'np.random.uniform', (['(-1)', '(1)', '(n, dim)'], {}), '(-1, 1, (n, dim))\n', (69228, 69245), True, 'import numpy as np\n'), ((69277, 69311), 'numpy.random.uniform', 'np.random.uniform', (['(-1)', '(1)', '(n, dim)'], {}), '(-1, 1, (n, dim))\n', (69294, 69311), True, 'import numpy as np\n'), ((8565, 8604), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['ys[0]', 'y'], {}), '(ys[0], y)\n', (8594, 8604), True, 'import numpy as np\n'), ((7589, 7632), 'hypothesis.strategies.sampled_from', 'st.sampled_from', (['hu.expanded_device_options'], {}), '(hu.expanded_device_options)\n', (7604, 7632), True, 'import hypothesis.strategies as st\n'), ((11722, 11782), 'numpy.random.randn', 'np.random.randn', (['hidden_size', 'N', '(num_layers * num_directions)'], {}), '(hidden_size, N, num_layers * num_directions)\n', (11737, 11782), True, 'import numpy as np\n'), ((11873, 11887), 'numpy.empty', 'np.empty', (['(1,)'], {}), '((1,))\n', (11881, 11887), True, 'import numpy as np\n'), ((15540, 15594), 'numpy.random.rand', 'np.random.rand', (['batch_size', 'size', 'size', 'input_channels'], {}), '(batch_size, size, size, input_channels)\n', (15554, 15594), True, 'import numpy as np\n'), ((15645, 15708), 'numpy.random.rand', 'np.random.rand', (['output_channels', 'kernel', 'kernel', 'input_channels'], {}), '(output_channels, kernel, kernel, input_channels)\n', (15659, 15708), True, 'import numpy as np\n'), ((15772, 15803), 'numpy.random.rand', 'np.random.rand', (['output_channels'], {}), '(output_channels)\n', (15786, 15803), True, 'import numpy as np\n'), ((17173, 17227), 'numpy.random.rand', 'np.random.rand', (['batch_size', 'size', 'size', 'input_channels'], {}), '(batch_size, size, size, input_channels)\n', (17187, 17227), True, 'import numpy as np\n'), ((17278, 17341), 'numpy.random.rand', 'np.random.rand', (['output_channels', 'kernel', 'kernel', 'input_channels'], {}), '(output_channels, kernel, kernel, input_channels)\n', (17292, 17341), True, 'import numpy as np\n'), ((17405, 17436), 'numpy.random.rand', 'np.random.rand', (['output_channels'], {}), '(output_channels)\n', (17419, 17436), True, 'import numpy as np\n'), ((19528, 19582), 'numpy.random.rand', 'np.random.rand', (['batch_size', 'size', 'size', 'input_channels'], {}), '(batch_size, size, size, input_channels)\n', (19542, 19582), True, 'import numpy as np\n'), ((19633, 19696), 'numpy.random.rand', 'np.random.rand', (['output_channels', 'kernel', 'kernel', 'input_channels'], {}), '(output_channels, kernel, kernel, input_channels)\n', (19647, 19696), True, 'import numpy as np\n'), ((19760, 19791), 'numpy.random.rand', 'np.random.rand', (['output_channels'], {}), '(output_channels)\n', (19774, 19791), True, 'import numpy as np\n'), ((20651, 20705), 'numpy.random.rand', 'np.random.rand', (['batch_size', 'size', 'size', 'input_channels'], {}), '(batch_size, size, size, input_channels)\n', (20665, 20705), True, 'import numpy as np\n'), ((20756, 20819), 'numpy.random.rand', 'np.random.rand', (['output_channels', 'kernel', 'kernel', 'input_channels'], {}), '(output_channels, kernel, kernel, input_channels)\n', (20770, 20819), True, 'import numpy as np\n'), ((20883, 20914), 'numpy.random.rand', 'np.random.rand', (['output_channels'], {}), '(output_channels)\n', (20897, 20914), True, 'import numpy as np\n'), ((25316, 25333), 'numpy.square', 'np.square', (['output'], {}), '(output)\n', (25325, 25333), True, 'import numpy as np\n'), ((26226, 26280), 'numpy.random.rand', 'np.random.rand', (['batch_size', 'size', 'size', 'input_channels'], {}), '(batch_size, size, size, input_channels)\n', (26240, 26280), True, 'import numpy as np\n'), ((26331, 26394), 'numpy.random.rand', 'np.random.rand', (['input_channels', 'kernel', 'kernel', 'output_channels'], {}), '(input_channels, kernel, kernel, output_channels)\n', (26345, 26394), True, 'import numpy as np\n'), ((26459, 26490), 'numpy.random.rand', 'np.random.rand', (['output_channels'], {}), '(output_channels)\n', (26473, 26490), True, 'import numpy as np\n'), ((27759, 27813), 'numpy.random.rand', 'np.random.rand', (['batch_size', 'size', 'size', 'input_channels'], {}), '(batch_size, size, size, input_channels)\n', (27773, 27813), True, 'import numpy as np\n'), ((27864, 27927), 'numpy.random.rand', 'np.random.rand', (['input_channels', 'kernel', 'kernel', 'output_channels'], {}), '(input_channels, kernel, kernel, output_channels)\n', (27878, 27927), True, 'import numpy as np\n'), ((27992, 28023), 'numpy.random.rand', 'np.random.rand', (['output_channels'], {}), '(output_channels)\n', (28006, 28023), True, 'import numpy as np\n'), ((30979, 30997), 'numpy.power', 'np.power', (['beta1', 't'], {}), '(beta1, t)\n', (30987, 30997), True, 'import numpy as np\n'), ((31103, 31118), 'numpy.square', 'np.square', (['grad'], {}), '(grad)\n', (31112, 31118), True, 'import numpy as np\n'), ((31189, 31202), 'numpy.sqrt', 'np.sqrt', (['m2_o'], {}), '(m2_o)\n', (31196, 31202), True, 'import numpy as np\n'), ((33704, 33727), 'numpy.sqrt', 'np.sqrt', (['(epsilon + ms_o)'], {}), '(epsilon + ms_o)\n', (33711, 33727), True, 'import numpy as np\n'), ((36240, 36250), 'numpy.sign', 'np.sign', (['z'], {}), '(z)\n', (36247, 36250), True, 'import numpy as np\n'), ((39125, 39163), 'hypothesis.strategies.integers', 'st.integers', ([], {'min_value': '(0)', 'max_value': '(10)'}), '(min_value=0, max_value=10)\n', (39136, 39163), True, 'import hypothesis.strategies as st\n'), ((40118, 40192), 'hypothesis.strategies.floats', 'st.floats', ([], {'allow_nan': '(False)', 'allow_infinity': '(False)', 'min_value': '(0)', 'max_value': '(1)'}), '(allow_nan=False, allow_infinity=False, min_value=0, max_value=1)\n', (40127, 40192), True, 'import hypothesis.strategies as st\n'), ((40468, 40509), 'hypothesis.strategies.integers', 'st.integers', ([], {'min_value': '(0)', 'max_value': '(3 - 1)'}), '(min_value=0, max_value=3 - 1)\n', (40479, 40509), True, 'import hypothesis.strategies as st\n'), ((41330, 41407), 'hypothesis.strategies.floats', 'st.floats', ([], {'allow_nan': '(False)', 'allow_infinity': '(False)', 'min_value': '(0.01)', 'max_value': '(1)'}), '(allow_nan=False, allow_infinity=False, min_value=0.01, max_value=1)\n', (41339, 41407), True, 'import hypothesis.strategies as st\n'), ((42808, 42836), 'numpy.array', 'np.array', (['lengths'], {'dtype': 'int'}), '(lengths, dtype=int)\n', (42816, 42836), True, 'import numpy as np\n'), ((42957, 43031), 'hypothesis.strategies.floats', 'st.floats', ([], {'allow_nan': '(False)', 'allow_infinity': '(False)', 'min_value': '(0)', 'max_value': '(1)'}), '(allow_nan=False, allow_infinity=False, min_value=0, max_value=1)\n', (42966, 43031), True, 'import hypothesis.strategies as st\n'), ((43307, 43348), 'hypothesis.strategies.integers', 'st.integers', ([], {'min_value': '(0)', 'max_value': '(3 - 1)'}), '(min_value=0, max_value=3 - 1)\n', (43318, 43348), True, 'import hypothesis.strategies as st\n'), ((45235, 45258), 'numpy.array', 'np.array', (['[]'], {'dtype': 'int'}), '([], dtype=int)\n', (45243, 45258), True, 'import numpy as np\n'), ((46004, 46036), 'numpy.array', 'np.array', (['segment_ids'], {'dtype': 'int'}), '(segment_ids, dtype=int)\n', (46012, 46036), True, 'import numpy as np\n'), ((46141, 46189), 'hypothesis.strategies.floats', 'st.floats', ([], {'allow_nan': '(False)', 'allow_infinity': '(False)'}), '(allow_nan=False, allow_infinity=False)\n', (46150, 46189), True, 'import hypothesis.strategies as st\n'), ((47588, 47620), 'numpy.random.randn', 'np.random.randn', (['num_elements', '(5)'], {}), '(num_elements, 5)\n', (47603, 47620), True, 'import numpy as np\n'), ((48333, 48362), 'caffe2.python.workspace.RunOperatorOnce', 'workspace.RunOperatorOnce', (['op'], {}), '(op)\n', (48358, 48362), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((54176, 54194), 'numpy.random.rand', 'np.random.rand', (['(16)'], {}), '(16)\n', (54190, 54194), True, 'import numpy as np\n'), ((58037, 58054), 'numpy.square', 'np.square', (['output'], {}), '(output)\n', (58046, 58054), True, 'import numpy as np\n'), ((58216, 58263), 'hypothesis.strategies.integers', 'st.integers', ([], {'min_value': '(0)', 'max_value': '(2 ** 32 - 1)'}), '(min_value=0, max_value=2 ** 32 - 1)\n', (58227, 58263), True, 'import hypothesis.strategies as st\n'), ((60181, 60208), 'numpy.asarray', 'np.asarray', (['[initial_iters]'], {}), '([initial_iters])\n', (60191, 60208), True, 'import numpy as np\n'), ((60280, 60303), 'numpy.asarray', 'np.asarray', (['[max_iters]'], {}), '([max_iters])\n', (60290, 60303), True, 'import numpy as np\n'), ((60631, 60657), 'caffe2.python.core.BlobReference', 'core.BlobReference', (['"""stop"""'], {}), "('stop')\n", (60649, 60657), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((62563, 62598), 'caffe2.python.core.BlobReference', 'core.BlobReference', (['"""should_stop_1"""'], {}), "('should_stop_1')\n", (62581, 62598), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((62702, 62737), 'caffe2.python.core.BlobReference', 'core.BlobReference', (['"""should_stop_2"""'], {}), "('should_stop_2')\n", (62720, 62737), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((63423, 63450), 'numpy.asarray', 'np.asarray', (['[initial_iters]'], {}), '([initial_iters])\n', (63433, 63450), True, 'import numpy as np\n'), ((64508, 64537), 'caffe2.proto.caffe2_pb2.TensorProto.DataType.Name', 'TensorProto.DataType.Name', (['to'], {}), '(to)\n', (64533, 64537), False, 'from caffe2.proto.caffe2_pb2 import TensorProto\n'), ((67873, 67895), 'caffe2.python.hypothesis_test_util.tensor', 'hu.tensor', ([], {'dtype': 'dtype'}), '(dtype=dtype)\n', (67882, 67895), True, 'import caffe2.python.hypothesis_test_util as hu\n'), ((70286, 70303), 'numpy.multiply', 'np.multiply', (['X', 'Y'], {}), '(X, Y)\n', (70297, 70303), True, 'import numpy as np\n'), ((70567, 70584), 'numpy.multiply', 'np.multiply', (['X', 'Y'], {}), '(X, Y)\n', (70578, 70584), True, 'import numpy as np\n'), ((70634, 70659), 'numpy.linalg.norm', 'np.linalg.norm', (['X'], {'axis': '(1)'}), '(X, axis=1)\n', (70648, 70659), True, 'import numpy as np\n'), ((70704, 70729), 'numpy.linalg.norm', 'np.linalg.norm', (['Y'], {'axis': '(1)'}), '(Y, axis=1)\n', (70718, 70729), True, 'import numpy as np\n'), ((12777, 12799), 'numpy.random.rand', 'np.random.rand', (['*shape'], {}), '(*shape)\n', (12791, 12799), True, 'import numpy as np\n'), ((13614, 13636), 'numpy.random.rand', 'np.random.rand', (['*shape'], {}), '(*shape)\n', (13628, 13636), True, 'import numpy as np\n'), ((22989, 23007), 'numpy.random.randn', 'np.random.randn', (['(4)'], {}), '(4)\n', (23004, 23007), True, 'import numpy as np\n'), ((23283, 23306), 'numpy.random.randint', 'np.random.randint', (['(0)', '(3)'], {}), '(0, 3)\n', (23300, 23306), True, 'import numpy as np\n'), ((23797, 23820), 'numpy.random.randint', 'np.random.randint', (['(0)', '(3)'], {}), '(0, 3)\n', (23814, 23820), True, 'import numpy as np\n'), ((33633, 33648), 'numpy.square', 'np.square', (['grad'], {}), '(grad)\n', (33642, 33648), True, 'import numpy as np\n'), ((36290, 36300), 'numpy.sqrt', 'np.sqrt', (['n'], {}), '(n)\n', (36297, 36300), True, 'import numpy as np\n'), ((48259, 48312), 'caffe2.python.workspace.FeedBlob', 'workspace.FeedBlob', (['feed_blob', 'elem'], {'device_option': 'do'}), '(feed_blob, elem, device_option=do)\n', (48277, 48312), False, 'from caffe2.python import core, workspace, tt_core, dyndep\n'), ((68280, 68309), 'numpy.random.permutation', 'np.random.permutation', (['X.ndim'], {}), '(X.ndim)\n', (68301, 68309), True, 'import numpy as np\n'), ((69954, 69970), 'numpy.square', 'np.square', (['(X - Y)'], {}), '(X - Y)\n', (69963, 69970), True, 'import numpy as np\n'), ((2884, 2927), 'caffe2.python.hypothesis_test_util.elements_of_type', 'hu.elements_of_type', (['dtype'], {'filter_': 'filter_'}), '(dtype, filter_=filter_)\n', (2903, 2927), True, 'import caffe2.python.hypothesis_test_util as hu\n'), ((3763, 3806), 'caffe2.python.hypothesis_test_util.elements_of_type', 'hu.elements_of_type', (['dtype'], {'filter_': 'filter_'}), '(dtype, filter_=filter_)\n', (3782, 3806), True, 'import caffe2.python.hypothesis_test_util as hu\n'), ((24638, 24665), 'numpy.random.randn', 'np.random.randn', (['n', 'd', 'h', 'w'], {}), '(n, d, h, w)\n', (24653, 24665), True, 'import numpy as np\n'), ((24809, 24838), 'numpy.random.randn', 'np.random.randn', (['n', '(d * h * w)'], {}), '(n, d * h * w)\n', (24824, 24838), True, 'import numpy as np\n'), ((30933, 30951), 'numpy.power', 'np.power', (['beta2', 't'], {}), '(beta2, t)\n', (30941, 30951), True, 'import numpy as np\n'), ((49853, 49887), 'numpy.array_equal', 'np.array_equal', (['xs[i][j]', 'ys[i][k]'], {}), '(xs[i][j], ys[i][k])\n', (49867, 49887), True, 'import numpy as np\n'), ((56314, 56331), 'numpy.random.randn', 'np.random.randn', ([], {}), '()\n', (56329, 56331), True, 'import numpy as np\n'), ((56379, 56396), 'numpy.random.randn', 'np.random.randn', ([], {}), '()\n', (56394, 56396), True, 'import numpy as np\n'), ((56546, 56563), 'numpy.random.randn', 'np.random.randn', ([], {}), '()\n', (56561, 56563), True, 'import numpy as np\n'), ((56611, 56628), 'numpy.random.randn', 'np.random.randn', ([], {}), '()\n', (56626, 56628), True, 'import numpy as np\n'), ((57394, 57415), 'numpy.random.randn', 'np.random.randn', (['n', 'd'], {}), '(n, d)\n', (57409, 57415), True, 'import numpy as np\n'), ((57559, 57580), 'numpy.random.randn', 'np.random.randn', (['n', 'd'], {}), '(n, d)\n', (57574, 57580), True, 'import numpy as np\n')]
|
from typing import Optional
import numpy as np
from sklearn.decomposition import KernelPCA, PCA
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import MinMaxScaler, OneHotEncoder, PolynomialFeatures, StandardScaler
from fedot.core.operations.evaluation.operation_implementations. \
implementation_interfaces import DataOperationImplementation, EncodedInvariantImplementation
class ComponentAnalysisImplementation(DataOperationImplementation):
""" Class for applying PCA and kernel PCA models form sklearn
:param params: optional, dictionary with the arguments
"""
def __init__(self, **params: Optional[dict]):
super().__init__()
self.pca = None
self.params = None
self.amount_of_features = None
def fit(self, input_data):
"""
The method trains the PCA model
:param input_data: data with features, target and ids for PCA training
:return pca: trained PCA model (optional output)
"""
self.amount_of_features = np.array(input_data.features).shape[1]
if self.amount_of_features > 1:
self.check_and_correct_params()
self.pca.fit(input_data.features)
return self.pca
def transform(self, input_data, is_fit_chain_stage: Optional[bool]):
"""
Method for transformation tabular data using PCA
:param input_data: data with features, target and ids for PCA applying
:param is_fit_chain_stage: is this fit or predict stage for chain
:return input_data: data with transformed features attribute
"""
if self.amount_of_features > 1:
transformed_features = self.pca.transform(input_data.features)
else:
transformed_features = input_data.features
# Update features
output_data = self._convert_to_output(input_data,
transformed_features)
return output_data
def check_and_correct_params(self) -> None:
""" Method check if amount of features in data enough for n_components
parameter in PCA or not. And if not enough - fixes it
"""
current_parameters = self.pca.get_params()
if type(current_parameters['n_components']) == int:
if current_parameters['n_components'] > self.amount_of_features:
current_parameters['n_components'] = self.amount_of_features
self.pca.set_params(**current_parameters)
self.params = current_parameters
def get_params(self):
return self.pca.get_params()
class PCAImplementation(ComponentAnalysisImplementation):
""" Class for applying PCA from sklearn
:param params: optional, dictionary with the hyperparameters
"""
def __init__(self, **params: Optional[dict]):
super().__init__()
if not params:
# Default parameters
self.pca = PCA(svd_solver='full', n_components='mle')
else:
self.pca = PCA(**params)
self.params = params
self.amount_of_features = None
class KernelPCAImplementation(ComponentAnalysisImplementation):
""" Class for applying kernel PCA from sklearn
:param params: optional, dictionary with the hyperparameters
"""
def __init__(self, **params: Optional[dict]):
super().__init__()
if not params:
# Default parameters
self.pca = KernelPCA()
else:
self.pca = KernelPCA(**params)
self.params = params
class OneHotEncodingImplementation(DataOperationImplementation):
""" Class for automatic categorical data detection and one hot encoding """
def __init__(self, **params: Optional[dict]):
super().__init__()
if not params:
# Default parameters
self.encoder = OneHotEncoder()
else:
self.encoder = OneHotEncoder(**params)
self.categorical_ids = None
self.non_categorical_ids = None
def fit(self, input_data):
""" Method for fit encoder with automatic determination of categorical
features
:param input_data: data with features, target and ids for encoder training
:return encoder: trained encoder (optional output)
"""
features = input_data.features
categorical_ids, non_categorical_ids = self.str_columns_check(features)
# Indices of columns with categorical and non-categorical features
self.categorical_ids = categorical_ids
self.non_categorical_ids = non_categorical_ids
if len(categorical_ids) == 0:
pass
else:
categorical_features = np.array(features[:, categorical_ids])
self.encoder.fit(categorical_features)
return self.encoder
def transform(self, input_data, is_fit_chain_stage: Optional[bool]):
"""
The method that transforms the categorical features in the original
dataset, but does not affect the rest features
:param input_data: data with features, target and ids for transformation
:param is_fit_chain_stage: is this fit or predict stage for chain
:return output_data: output data with transformed features table
"""
features = input_data.features
if len(self.categorical_ids) == 0:
# If there are no categorical features in the table
transformed_features = features
else:
# If categorical features are exists
transformed_features = self._make_new_table(features)
# Update features
output_data = self._convert_to_output(input_data,
transformed_features)
return output_data
def _make_new_table(self, features):
"""
The method creates a table based on categorical and real features
:param features: tabular data for processing
:return transformed_features: transformed features table
"""
categorical_features = np.array(features[:, self.categorical_ids])
transformed_categorical = self.encoder.transform(categorical_features).toarray()
# If there are non-categorical features in the data
if len(self.non_categorical_ids) == 0:
transformed_features = transformed_categorical
else:
# Stack transformed categorical and non-categorical data
non_categorical_features = np.array(features[:, self.non_categorical_ids])
frames = (non_categorical_features, transformed_categorical)
transformed_features = np.hstack(frames)
return transformed_features
def get_params(self):
return self.encoder.get_params()
@staticmethod
def str_columns_check(features):
"""
Method for checking which columns contain categorical (text) data
:param features: tabular data for check
:return categorical_ids: indices of categorical columns in table
:return non_categorical_ids: indices of non categorical columns in table
"""
source_shape = features.shape
columns_amount = source_shape[1] if len(source_shape) > 1 else 1
categorical_ids = []
non_categorical_ids = []
# For every column in table make check for first element
for column_id in range(0, columns_amount):
column = features[:, column_id] if columns_amount > 1 else features
if type(column[0]) == str:
categorical_ids.append(column_id)
else:
non_categorical_ids.append(column_id)
return categorical_ids, non_categorical_ids
class PolyFeaturesImplementation(EncodedInvariantImplementation):
""" Class for application of PolynomialFeatures operation on data,
where only not encoded features (were not converted from categorical using
OneHot encoding) are used
:param params: optional, dictionary with the arguments
"""
def __init__(self, **params: Optional[dict]):
super().__init__()
if not params:
# Default parameters
self.operation = PolynomialFeatures(include_bias=False)
else:
# Checking the appropriate params are using or not
poly_params = {k: params[k] for k in
['degree', 'interaction_only']}
self.operation = PolynomialFeatures(include_bias=False,
**poly_params)
self.params = params
def get_params(self):
return self.operation.get_params()
class ScalingImplementation(EncodedInvariantImplementation):
""" Class for application of Scaling operation on data,
where only not encoded features (were not converted from categorical using
OneHot encoding) are used
:param params: optional, dictionary with the arguments
"""
def __init__(self, **params: Optional[dict]):
super().__init__()
if not params:
# Default parameters
self.operation = StandardScaler()
else:
self.operation = StandardScaler(**params)
self.params = params
def get_params(self):
return self.operation.get_params()
class NormalizationImplementation(EncodedInvariantImplementation):
""" Class for application of MinMax normalization operation on data,
where only not encoded features (were not converted from categorical using
OneHot encoding) are used
:param params: optional, dictionary with the arguments
"""
def __init__(self, **params: Optional[dict]):
super().__init__()
if not params:
# Default parameters
self.operation = MinMaxScaler()
else:
self.operation = MinMaxScaler(**params)
self.params = params
def get_params(self):
return self.operation.get_params()
class ImputationImplementation(DataOperationImplementation):
""" Class for applying imputation on tabular data
:param params: optional, dictionary with the arguments
"""
def __init__(self, **params: Optional[dict]):
super().__init__()
if not params:
# Default parameters
self.imputer = SimpleImputer()
else:
self.imputer = SimpleImputer(**params)
self.params = params
def fit(self, input_data):
"""
The method trains SimpleImputer
:param input_data: data with features
:return imputer: trained SimpleImputer model
"""
self.imputer.fit(input_data.features)
return self.imputer
def transform(self, input_data, is_fit_chain_stage: Optional[bool] = None):
"""
Method for transformation tabular data using SimpleImputer
:param input_data: data with features
:param is_fit_chain_stage: is this fit or predict stage for chain
:return input_data: data with transformed features attribute
"""
transformed_features = self.imputer.transform(input_data.features)
# Update features
output_data = self._convert_to_output(input_data,
transformed_features)
return output_data
def get_params(self):
return self.imputer.get_params()
|
[
"sklearn.impute.SimpleImputer",
"sklearn.preprocessing.StandardScaler",
"sklearn.preprocessing.MinMaxScaler",
"sklearn.preprocessing.OneHotEncoder",
"numpy.hstack",
"sklearn.preprocessing.PolynomialFeatures",
"numpy.array",
"sklearn.decomposition.PCA",
"sklearn.decomposition.KernelPCA"
] |
[((6063, 6106), 'numpy.array', 'np.array', (['features[:, self.categorical_ids]'], {}), '(features[:, self.categorical_ids])\n', (6071, 6106), True, 'import numpy as np\n'), ((2937, 2979), 'sklearn.decomposition.PCA', 'PCA', ([], {'svd_solver': '"""full"""', 'n_components': '"""mle"""'}), "(svd_solver='full', n_components='mle')\n", (2940, 2979), False, 'from sklearn.decomposition import KernelPCA, PCA\n'), ((3017, 3030), 'sklearn.decomposition.PCA', 'PCA', ([], {}), '(**params)\n', (3020, 3030), False, 'from sklearn.decomposition import KernelPCA, PCA\n'), ((3447, 3458), 'sklearn.decomposition.KernelPCA', 'KernelPCA', ([], {}), '()\n', (3456, 3458), False, 'from sklearn.decomposition import KernelPCA, PCA\n'), ((3496, 3515), 'sklearn.decomposition.KernelPCA', 'KernelPCA', ([], {}), '(**params)\n', (3505, 3515), False, 'from sklearn.decomposition import KernelPCA, PCA\n'), ((3853, 3868), 'sklearn.preprocessing.OneHotEncoder', 'OneHotEncoder', ([], {}), '()\n', (3866, 3868), False, 'from sklearn.preprocessing import MinMaxScaler, OneHotEncoder, PolynomialFeatures, StandardScaler\n'), ((3910, 3933), 'sklearn.preprocessing.OneHotEncoder', 'OneHotEncoder', ([], {}), '(**params)\n', (3923, 3933), False, 'from sklearn.preprocessing import MinMaxScaler, OneHotEncoder, PolynomialFeatures, StandardScaler\n'), ((4695, 4733), 'numpy.array', 'np.array', (['features[:, categorical_ids]'], {}), '(features[:, categorical_ids])\n', (4703, 4733), True, 'import numpy as np\n'), ((6485, 6532), 'numpy.array', 'np.array', (['features[:, self.non_categorical_ids]'], {}), '(features[:, self.non_categorical_ids])\n', (6493, 6532), True, 'import numpy as np\n'), ((6641, 6658), 'numpy.hstack', 'np.hstack', (['frames'], {}), '(frames)\n', (6650, 6658), True, 'import numpy as np\n'), ((8184, 8222), 'sklearn.preprocessing.PolynomialFeatures', 'PolynomialFeatures', ([], {'include_bias': '(False)'}), '(include_bias=False)\n', (8202, 8222), False, 'from sklearn.preprocessing import MinMaxScaler, OneHotEncoder, PolynomialFeatures, StandardScaler\n'), ((8437, 8490), 'sklearn.preprocessing.PolynomialFeatures', 'PolynomialFeatures', ([], {'include_bias': '(False)'}), '(include_bias=False, **poly_params)\n', (8455, 8490), False, 'from sklearn.preprocessing import MinMaxScaler, OneHotEncoder, PolynomialFeatures, StandardScaler\n'), ((9101, 9117), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (9115, 9117), False, 'from sklearn.preprocessing import MinMaxScaler, OneHotEncoder, PolynomialFeatures, StandardScaler\n'), ((9161, 9185), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '(**params)\n', (9175, 9185), False, 'from sklearn.preprocessing import MinMaxScaler, OneHotEncoder, PolynomialFeatures, StandardScaler\n'), ((9767, 9781), 'sklearn.preprocessing.MinMaxScaler', 'MinMaxScaler', ([], {}), '()\n', (9779, 9781), False, 'from sklearn.preprocessing import MinMaxScaler, OneHotEncoder, PolynomialFeatures, StandardScaler\n'), ((9825, 9847), 'sklearn.preprocessing.MinMaxScaler', 'MinMaxScaler', ([], {}), '(**params)\n', (9837, 9847), False, 'from sklearn.preprocessing import MinMaxScaler, OneHotEncoder, PolynomialFeatures, StandardScaler\n'), ((10293, 10308), 'sklearn.impute.SimpleImputer', 'SimpleImputer', ([], {}), '()\n', (10306, 10308), False, 'from sklearn.impute import SimpleImputer\n'), ((10350, 10373), 'sklearn.impute.SimpleImputer', 'SimpleImputer', ([], {}), '(**params)\n', (10363, 10373), False, 'from sklearn.impute import SimpleImputer\n'), ((1040, 1069), 'numpy.array', 'np.array', (['input_data.features'], {}), '(input_data.features)\n', (1048, 1069), True, 'import numpy as np\n')]
|
from astropy.io import fits
import pandas as pd
import numpy as np
import glob
import os
class ExternalFile:
""" Read in external files and turn them into numpy arrays to work with pyRT_DISORT functions"""
def __init__(self, file_path, header_lines=0, text1d=True):
"""
Parameters
----------
file_path: str
The absolute path to the file
header_lines: int, optional
The number of header lines to skip. Only used for plain text input
text1d: bool, optional
Denote if the data are 1D or 2D. Only used for plain text input
"""
self.file_path = file_path
self.header_lines = header_lines
self.text1d = text1d
self.__check_inputs()
self.__trim_file_path()
self.filename = self.__get_filename()
self.extension = self.__get_extension()
self.array = self.__read_in_file()
def __check_inputs(self):
assert isinstance(self.file_path, str), 'file_path must be a string'
assert isinstance(self.header_lines, int), 'header_lines must be an int'
assert isinstance(self.text1d, bool), 'text1d needs to be a boolean'
def __trim_file_path(self):
self.file_path = self.file_path.strip()
def __get_filename(self):
return self.file_path.split('.')[0]
def __get_extension(self):
return self.file_path.split('.')[-1]
def __read_in_file(self):
if self.extension == 'npy':
return self.__read_npy_file()
elif self.extension == 'csv':
return self.__csv_to_npy()
elif self.extension == 'fits':
return self.__read_fits_file()
elif self.extension in ['txt', 'dat', 'coef', 'phsfn']:
if self.text1d:
return self.__1dtext_to_npy()
else:
return self.__2dtext_to_npy()
else:
print('Unsure how to handle that extension... please use .npy, .csv, .fits, .txt, .dat, .coef, .phsfn')
return None
def __read_npy_file(self):
return np.load(self.file_path)
def __csv_to_npy(self):
return pd.read_csv(self.file_path).to_numpy()
def __read_fits_file(self):
return fits.open(self.file_path)
def __get_absolute_path(self, new_filename):
if new_filename.strip()[-1] == '/':
raise SystemExit('You provided a path but not a filename...')
# assume it's a relative path
if '/' not in new_filename:
stripped_filename = self.__strip_extensions(new_filename)
split_paths = self.file_path.split('/')
split_paths[-1] = stripped_filename
return '/'.join(split_paths)
# assume it's an absolute path
else:
return new_filename
@staticmethod
def __strip_extensions(filename):
return filename.split('.')[0]
def __1dtext_to_npy(self):
coeff = []
f = open(self.file_path)
lines = f.readlines()[self.header_lines:]
for line in lines:
a = np.fromstring(line.strip(), sep=' ')
coeff.append(a)
# This unravels a list and stores it as an array
return np.array([co for all_coeff in coeff for co in all_coeff])
def __2dtext_to_npy(self):
return np.genfromtxt(self.file_path, skip_header=self.header_lines, filling_values=np.nan)
def save_as_npy(self, new_filename=''):
""" Save the input file as a numpy array
Parameters
----------
new_filename: str
The filename for the newly created file. Can be an absolute path; otherwise makes a file in the same
location as the data file.
Returns
-------
None
Examples
--------
>>> folder = '/path/to/my/data/'
>>> file = 'folder' + 'myDataFile.csv'
>>> f = ExternalFiles(file)
>>> f.save_as_npy(new_filename='myBetterNamedDataFile')
>>> folder = '/path/to/my/data/'
>>> file = 'folder' + 'myDataFile.txt'
>>> f = ExternalFiles(file)
>>> f.save_as_npy(new_filename='/absolute/path/to/my/new/file/fileName')
"""
assert isinstance(new_filename, str), 'new_filename must be a string'
absolute_path = self.__get_absolute_path(new_filename)
np.save(absolute_path, self.array)
def save_as_csv(self, new_filename, headers):
""" Save the input file in .csv format
Parameters
----------
new_filename: str
The filename for the newly created file. Can be an absolute path; otherwise makes a file in the same
location as the data file.
headers: list
A list of strings of each of the column names
Returns
-------
None
"""
if (dims := np.ndim(self.array)) > 2:
print('You\'re trying to save a {}D array in 2D format... consult a string theorist.'.format(dims))
return
absolute_path = self.__get_absolute_path(new_filename)
pd.DataFrame(self.array).to_csv('{}.csv'.format(absolute_path), header=headers, index=False)
class MultipleExternalFiles:
""" Get the absolute paths of files matching a given pattern"""
def __init__(self, pattern, path):
"""
Parameters
----------
pattern: str
A regex pattern to match
path: str
The location of files to match the pattern to
"""
self.pattern = pattern
self.path = path
self.files = self.__get_files()
def __check_inputs(self):
assert isinstance(self.pattern, str), 'pattern must a string'
assert isinstance(self.path, str), 'path must be a string'
def __get_files(self):
absolute_path = os.path.join(self.path, self.pattern)
return sorted(glob.glob(absolute_path))
|
[
"pandas.DataFrame",
"numpy.load",
"numpy.save",
"pandas.read_csv",
"numpy.ndim",
"numpy.genfromtxt",
"numpy.array",
"astropy.io.fits.open",
"glob.glob",
"os.path.join"
] |
[((2099, 2122), 'numpy.load', 'np.load', (['self.file_path'], {}), '(self.file_path)\n', (2106, 2122), True, 'import numpy as np\n'), ((2254, 2279), 'astropy.io.fits.open', 'fits.open', (['self.file_path'], {}), '(self.file_path)\n', (2263, 2279), False, 'from astropy.io import fits\n'), ((3229, 3286), 'numpy.array', 'np.array', (['[co for all_coeff in coeff for co in all_coeff]'], {}), '([co for all_coeff in coeff for co in all_coeff])\n', (3237, 3286), True, 'import numpy as np\n'), ((3334, 3422), 'numpy.genfromtxt', 'np.genfromtxt', (['self.file_path'], {'skip_header': 'self.header_lines', 'filling_values': 'np.nan'}), '(self.file_path, skip_header=self.header_lines, filling_values\n =np.nan)\n', (3347, 3422), True, 'import numpy as np\n'), ((4366, 4400), 'numpy.save', 'np.save', (['absolute_path', 'self.array'], {}), '(absolute_path, self.array)\n', (4373, 4400), True, 'import numpy as np\n'), ((5845, 5882), 'os.path.join', 'os.path.join', (['self.path', 'self.pattern'], {}), '(self.path, self.pattern)\n', (5857, 5882), False, 'import os\n'), ((5905, 5929), 'glob.glob', 'glob.glob', (['absolute_path'], {}), '(absolute_path)\n', (5914, 5929), False, 'import glob\n'), ((2167, 2194), 'pandas.read_csv', 'pd.read_csv', (['self.file_path'], {}), '(self.file_path)\n', (2178, 2194), True, 'import pandas as pd\n'), ((4874, 4893), 'numpy.ndim', 'np.ndim', (['self.array'], {}), '(self.array)\n', (4881, 4893), True, 'import numpy as np\n'), ((5102, 5126), 'pandas.DataFrame', 'pd.DataFrame', (['self.array'], {}), '(self.array)\n', (5114, 5126), True, 'import pandas as pd\n')]
|
#!/usr/bin/env python
import os
from argparse import ArgumentParser
from os import listdir
from time import time
import h5py
import numpy as np
import tensorflow as tf
import tensorflow.contrib.slim.python.slim.nets.vgg as vgg
from PIL import Image, ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
from tqdm import tqdm
parser = ArgumentParser()
parser.add_argument("-image_dir", help="Path to the directory containing the images")
parser.add_argument("-output_dir", help="ResNet features output directory where the features metadata will be stored")
parser.add_argument("-model_ckpt", default="data/vgg.ckpt", help="Path to the VGG-16 Net model checkpoint")
def get_splits(image_dir):
dirs = [name for name in os.listdir(image_dir) if os.path.isdir(os.path.join(image_dir, name))]
if not dirs:
return ['train', 'val', 'test']
return dirs
def extract_features(
images_placeholder,
image_dir,
split,
ft_output,
network_ckpt,
out_dir):
with tf.Session(config=tf.ConfigProto(allow_soft_placement=True)) as sess:
saver = tf.train.Saver()
saver.restore(sess, network_ckpt)
img_list = listdir(image_dir)
print("Load dataset -> set: {}".format(split))
no_images = len(img_list)
############################
# CREATE FEATURES
############################
print("Start computing image features...")
filepath = os.path.join(out_dir, "{}_features.h5".format(split))
with h5py.File(filepath, 'w') as f:
ft_shape = [int(dim) for dim in ft_output.get_shape()[1:]]
ft_dataset = f.create_dataset('features', shape=[no_images] + ft_shape, dtype=np.float32)
idx2img = f.create_dataset('idx2img', shape=[no_images], dtype=h5py.special_dtype(vlen=str))
for i in tqdm(range(len(img_list))):
image_filepath = os.path.join(image_dir, img_list[i])
image_tensor = Image.open(image_filepath).convert('RGB')
feat = sess.run(ft_output, feed_dict={images_placeholder: np.expand_dims(image_tensor, 0)})
# Store dataset
ft_dataset[i] = feat
image_id = img_list[i][:img_list[i].index(".")]
idx2img[i] = image_id
print("Finished dumping file: {}".format(filepath))
print("Done!")
def main(args):
start = time()
print('Start')
splits = get_splits(args.image_dir)
img_size = 224
# TF graph creation
images_placeholder = tf.placeholder(tf.float32, [None, None, None, 3], name='image')
proc_image_op = tf.image.resize_image_with_crop_or_pad(
images_placeholder,
target_height=224,
target_width=224
)
_, end_points = vgg.vgg_16(proc_image_op, is_training=False, dropout_keep_prob=1.0)
ft_name = os.path.join("vgg_16", "fc8")
ft_output = end_points[ft_name]
####
for split in splits:
extract_features(
images_placeholder=images_placeholder,
image_dir=os.path.join(args.image_dir, split),
ft_output=ft_output,
out_dir=args.output_dir,
split=split,
network_ckpt=args.model_ckpt)
print('Image Features extracted.')
print('Time taken: ', time() - start)
if __name__ == '__main__':
args = parser.parse_args()
main(args)
|
[
"h5py.File",
"argparse.ArgumentParser",
"tensorflow.train.Saver",
"h5py.special_dtype",
"tensorflow.contrib.slim.python.slim.nets.vgg.vgg_16",
"numpy.expand_dims",
"time.time",
"PIL.Image.open",
"tensorflow.placeholder",
"tensorflow.ConfigProto",
"tensorflow.image.resize_image_with_crop_or_pad",
"os.path.join",
"os.listdir"
] |
[((332, 348), 'argparse.ArgumentParser', 'ArgumentParser', ([], {}), '()\n', (346, 348), False, 'from argparse import ArgumentParser\n'), ((2429, 2435), 'time.time', 'time', ([], {}), '()\n', (2433, 2435), False, 'from time import time\n'), ((2564, 2627), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, None, None, 3]'], {'name': '"""image"""'}), "(tf.float32, [None, None, None, 3], name='image')\n", (2578, 2627), True, 'import tensorflow as tf\n'), ((2648, 2748), 'tensorflow.image.resize_image_with_crop_or_pad', 'tf.image.resize_image_with_crop_or_pad', (['images_placeholder'], {'target_height': '(224)', 'target_width': '(224)'}), '(images_placeholder, target_height=\n 224, target_width=224)\n', (2686, 2748), True, 'import tensorflow as tf\n'), ((2794, 2861), 'tensorflow.contrib.slim.python.slim.nets.vgg.vgg_16', 'vgg.vgg_16', (['proc_image_op'], {'is_training': '(False)', 'dropout_keep_prob': '(1.0)'}), '(proc_image_op, is_training=False, dropout_keep_prob=1.0)\n', (2804, 2861), True, 'import tensorflow.contrib.slim.python.slim.nets.vgg as vgg\n'), ((2876, 2905), 'os.path.join', 'os.path.join', (['"""vgg_16"""', '"""fc8"""'], {}), "('vgg_16', 'fc8')\n", (2888, 2905), False, 'import os\n'), ((1108, 1124), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), '()\n', (1122, 1124), True, 'import tensorflow as tf\n'), ((1186, 1204), 'os.listdir', 'listdir', (['image_dir'], {}), '(image_dir)\n', (1193, 1204), False, 'from os import listdir\n'), ((721, 742), 'os.listdir', 'os.listdir', (['image_dir'], {}), '(image_dir)\n', (731, 742), False, 'import os\n'), ((1535, 1559), 'h5py.File', 'h5py.File', (['filepath', '"""w"""'], {}), "(filepath, 'w')\n", (1544, 1559), False, 'import h5py\n'), ((3316, 3322), 'time.time', 'time', ([], {}), '()\n', (3320, 3322), False, 'from time import time\n'), ((760, 789), 'os.path.join', 'os.path.join', (['image_dir', 'name'], {}), '(image_dir, name)\n', (772, 789), False, 'import os\n'), ((1040, 1081), 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {'allow_soft_placement': '(True)'}), '(allow_soft_placement=True)\n', (1054, 1081), True, 'import tensorflow as tf\n'), ((1927, 1963), 'os.path.join', 'os.path.join', (['image_dir', 'img_list[i]'], {}), '(image_dir, img_list[i])\n', (1939, 1963), False, 'import os\n'), ((3076, 3111), 'os.path.join', 'os.path.join', (['args.image_dir', 'split'], {}), '(args.image_dir, split)\n', (3088, 3111), False, 'import os\n'), ((1814, 1842), 'h5py.special_dtype', 'h5py.special_dtype', ([], {'vlen': 'str'}), '(vlen=str)\n', (1832, 1842), False, 'import h5py\n'), ((1995, 2021), 'PIL.Image.open', 'Image.open', (['image_filepath'], {}), '(image_filepath)\n', (2005, 2021), False, 'from PIL import Image, ImageFile\n'), ((2111, 2142), 'numpy.expand_dims', 'np.expand_dims', (['image_tensor', '(0)'], {}), '(image_tensor, 0)\n', (2125, 2142), True, 'import numpy as np\n')]
|
import networkx as nx
import numpy as np
from scipy.linalg import fractional_matrix_power, inv
import tensorlayerx as tlx
from sklearn.preprocessing import MinMaxScaler
import scipy.sparse as sp
def preprocess_features(features):
"""Row-normalize feature matrix and convert to tuple representation"""
rowsum = np.array(features.sum(1))
r_inv = np.power(rowsum, -1).flatten()
r_inv[np.isinf(r_inv)] = 0.
r_mat_inv = sp.diags(r_inv)
features = r_mat_inv.dot(features)
return tlx.convert_to_tensor(features)
def compute_ppr(graph: nx.Graph, alpha=0.2, self_loop=True):
a = nx.convert_matrix.to_numpy_array(graph, dtype=np.float32)
if self_loop:
a = a + np.eye(a.shape[0], dtype=np.float32) # A^ = A + I_n
d = np.diag(np.sum(a, 1)) # D^ = Sigma A^_ii
dinv = fractional_matrix_power(d, -0.5) # D^(-1/2)
at = np.matmul(np.matmul(dinv, a), dinv) # A~ = D^(-1/2) x A^ x D^(-1/2)
return alpha * inv((np.eye(a.shape[0], dtype=np.float32) - (1 - alpha) * at)) # a(I_n-(1-a)A~)^-1
def process_dataset(name, graph, epsilon):
feat = graph.x
label = graph.y
train_mask = graph.train_mask
val_mask = graph.val_mask
test_mask = graph.test_mask
train_idx = np.nonzero(train_mask)[0]
val_idx = np.nonzero(val_mask)[0]
test_idx = np.nonzero(test_mask)[0]
src, dst = graph.edge_index.numpy()
nx_g = nx.DiGraph()
nx_g.add_nodes_from(range(graph.num_nodes))
for e, (u, v) in enumerate(zip(src, dst)):
nx_g.add_edge(u, v, id=e)
print('computing ppr')
diff_adj = compute_ppr(nx_g, 0.2)
print('computing end')
if name == 'citeseer':
print('additional processing')
feat = preprocess_features(tlx.convert_to_numpy(feat))
diff_adj[diff_adj < epsilon] = 0
scaler = MinMaxScaler()
scaler.fit(diff_adj)
diff_adj = scaler.transform(diff_adj)
diff_edges = np.nonzero(diff_adj)
diff_weight = diff_adj[diff_edges]
coo = sp.coo_matrix((diff_weight, np.array([diff_edges[0], diff_edges[1]])), shape=(feat.shape[0], feat.shape[0]))
return np.array(coo.todense()), feat, label, train_idx, val_idx, test_idx
|
[
"scipy.sparse.diags",
"numpy.sum",
"numpy.power",
"tensorlayerx.convert_to_numpy",
"scipy.linalg.fractional_matrix_power",
"sklearn.preprocessing.MinMaxScaler",
"numpy.isinf",
"tensorlayerx.convert_to_tensor",
"numpy.nonzero",
"networkx.convert_matrix.to_numpy_array",
"numpy.array",
"numpy.matmul",
"numpy.eye",
"networkx.DiGraph"
] |
[((436, 451), 'scipy.sparse.diags', 'sp.diags', (['r_inv'], {}), '(r_inv)\n', (444, 451), True, 'import scipy.sparse as sp\n'), ((502, 533), 'tensorlayerx.convert_to_tensor', 'tlx.convert_to_tensor', (['features'], {}), '(features)\n', (523, 533), True, 'import tensorlayerx as tlx\n'), ((605, 662), 'networkx.convert_matrix.to_numpy_array', 'nx.convert_matrix.to_numpy_array', (['graph'], {'dtype': 'np.float32'}), '(graph, dtype=np.float32)\n', (637, 662), True, 'import networkx as nx\n'), ((811, 843), 'scipy.linalg.fractional_matrix_power', 'fractional_matrix_power', (['d', '(-0.5)'], {}), '(d, -0.5)\n', (834, 843), False, 'from scipy.linalg import fractional_matrix_power, inv\n'), ((1392, 1404), 'networkx.DiGraph', 'nx.DiGraph', ([], {}), '()\n', (1402, 1404), True, 'import networkx as nx\n'), ((1921, 1941), 'numpy.nonzero', 'np.nonzero', (['diff_adj'], {}), '(diff_adj)\n', (1931, 1941), True, 'import numpy as np\n'), ((398, 413), 'numpy.isinf', 'np.isinf', (['r_inv'], {}), '(r_inv)\n', (406, 413), True, 'import numpy as np\n'), ((766, 778), 'numpy.sum', 'np.sum', (['a', '(1)'], {}), '(a, 1)\n', (772, 778), True, 'import numpy as np\n'), ((875, 893), 'numpy.matmul', 'np.matmul', (['dinv', 'a'], {}), '(dinv, a)\n', (884, 893), True, 'import numpy as np\n'), ((1236, 1258), 'numpy.nonzero', 'np.nonzero', (['train_mask'], {}), '(train_mask)\n', (1246, 1258), True, 'import numpy as np\n'), ((1276, 1296), 'numpy.nonzero', 'np.nonzero', (['val_mask'], {}), '(val_mask)\n', (1286, 1296), True, 'import numpy as np\n'), ((1315, 1336), 'numpy.nonzero', 'np.nonzero', (['test_mask'], {}), '(test_mask)\n', (1325, 1336), True, 'import numpy as np\n'), ((1813, 1827), 'sklearn.preprocessing.MinMaxScaler', 'MinMaxScaler', ([], {}), '()\n', (1825, 1827), False, 'from sklearn.preprocessing import MinMaxScaler\n'), ((357, 377), 'numpy.power', 'np.power', (['rowsum', '(-1)'], {}), '(rowsum, -1)\n', (365, 377), True, 'import numpy as np\n'), ((697, 733), 'numpy.eye', 'np.eye', (['a.shape[0]'], {'dtype': 'np.float32'}), '(a.shape[0], dtype=np.float32)\n', (703, 733), True, 'import numpy as np\n'), ((1727, 1753), 'tensorlayerx.convert_to_numpy', 'tlx.convert_to_numpy', (['feat'], {}), '(feat)\n', (1747, 1753), True, 'import tensorlayerx as tlx\n'), ((2019, 2059), 'numpy.array', 'np.array', (['[diff_edges[0], diff_edges[1]]'], {}), '([diff_edges[0], diff_edges[1]])\n', (2027, 2059), True, 'import numpy as np\n'), ((958, 994), 'numpy.eye', 'np.eye', (['a.shape[0]'], {'dtype': 'np.float32'}), '(a.shape[0], dtype=np.float32)\n', (964, 994), True, 'import numpy as np\n')]
|
from typing import List, Optional
import os
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as mpc
import matplotlib.cm as cm
from matplotlib import rc
from matplotlib import colors
from matplotlib.ticker import MaxNLocator
from matplotlib.colors import BoundaryNorm
import numpy as np
import pandas as pd
from mpl_toolkits.axes_grid1 import make_axes_locatable
from string import ascii_lowercase
from math import floor
from helper_funcs import convert2rgb, get_tab_colors
import data_tools as dt
def plot_metric(data_paths:List[str], metric:str,
lower_bound:Optional[str] = None, upper_bound:Optional[str] = None,
normalize:bool = False, labels:Optional[List[str]] = None):
"""Plots a metric evolution from the given data_paths.
Since metrics require an evaluation of the forward model,
the last iteration must be discarded (only parameters available).
Args:
- data_paths: List of diagnostic data paths from which to draw
the metrics.
- metric: Name of the metric to be plotted.
- lower_bound: If given, shades the area between the metric
and this lower bound metric from the same dataset.
- upper_bound: If given, shades the area between the metric
and this upper bound metric from the same dataset.
- normalize: If True, normalizes the metric with respect to
the metric at t=0.
"""
tab_colors = get_tab_colors()
fig = plt.figure(metric)
max_t = 0
for (i, data_path) in enumerate(data_paths):
shading = convert2rgb(tab_colors[i], 0.4)
var = dt.ncFetch(data_path, 'metrics', metric)[:-1]
if normalize:
den = var[0]
var = var/den
else:
den = 1.
if labels is not None:
label = labels[i]
else:
label = (data_path).split('_')[-1]
t = dt.ncFetch(data_path, 'metrics', 'iteration')[:-1]
max_t = max(max_t, t[-1])
plt.plot(t, var, color=tab_colors[i], label = label)
if lower_bound is not None:
low = dt.ncFetch(data_path, 'metrics', lower_bound)[:-1]/den
plt.fill_between(t, var, low, color=shading)
if upper_bound is not None:
upp = dt.ncFetch(data_path, 'metrics', upper_bound)[:-1]/den
plt.fill_between(t, var, upp, color=shading)
plt.ylabel(metric)
plt.xlabel('Iteration')
plt.xlim(0, max_t)
ax = fig.gca()
ax.xaxis.set_major_locator(MaxNLocator(integer=True))
plt.legend(frameon=False)
plt.tight_layout()
plt.savefig(metric+'.pdf', format='pdf')
return
def plot_epoch_avg_metric(data_paths:List[str], metric:str,
lower_bound:Optional[str] = None, upper_bound:Optional[str] = None,
normalize:bool = False, labels:Optional[List[str]] = None):
"""Plots an epoch-averaged metric evolution from the given data_paths.
Since metrics require an evaluation of the forward model,
the last iteration must be discarded (only parameters available).
Args:
- data_paths: List of diagnostic data paths from which to draw
the metrics.
- metric: Name of the metric to be plotted.
- lower_bound: If given, shades the area between the metric
and this lower bound metric from the same dataset.
- upper_bound: If given, shades the area between the metric
and this upper bound metric from the same dataset.
- normalize: If True, normalizes the metric with respect to
the metric at t=0.
"""
tab_colors = get_tab_colors()
fig = plt.figure(metric+' per epoch')
for (i, data_path) in enumerate(data_paths):
shading = convert2rgb(tab_colors[i], 0.4)
batch_size = dt.ncFetchDim(data_path, 'reference', 'batch_size')
config_num = dt.ncFetchDim(data_path, 'reference', 'config')
iter_per_epoch = int(config_num/batch_size) # Should be read from file
var = dt.ncFetch(data_path, 'metrics', metric)[:-1]
var = iter_to_epochs(var, iter_per_epoch)
epoch = np.arange(len(var))
if normalize:
den = var[0]
var = var/den
else:
den = 1.
if labels is not None:
label = labels[i]
else:
label = (data_path).split('_')[-1]
plt.plot(epoch, var, color=tab_colors[i], label = label)
if lower_bound is not None:
low = dt.ncFetch(data_path, 'metrics', lower_bound)[:-1]
low = iter_to_epochs(low, iter_per_epoch)/den
plt.fill_between(epoch, var, low, color=shading)
if upper_bound is not None:
upp = dt.ncFetch(data_path, 'metrics', upper_bound)[:-1]
upp = iter_to_epochs(upp, iter_per_epoch)/den
plt.fill_between(epoch, var, upp, color=shading)
plt.ylabel(metric)
plt.xlabel('Epoch')
ax = fig.gca()
ax.xaxis.set_major_locator(MaxNLocator(integer=True))
plt.legend(frameon=False)
plt.savefig(metric+'_per_epoch.pdf', format='pdf')
return
def iter_to_epochs(var:np.ndarray, iter_per_epoch:int) -> np.ndarray:
"""Converts an iteration-dependent array to an epoch-dependent array through averaging.
The operation ignores any remainder iterations of unfinished training epochs.
Args:
- var: Array with iterations as a dimension.
- iter_per_epoch: Number of iterations per epoch.
"""
# Set epochs as rows
var = np.reshape(
var[:len(var) - len(var)%iter_per_epoch], (-1, iter_per_epoch))
# Average metric per epoch
var = np.mean(var, axis=1)
return var
def plot_y_full(data_path:str, var_names:Optional[List[str]] = None):
"""Plots vertical profiles from `y_full` for each variable and
configuration.
Args:
- data_path: Diagnostic data path from which to draw
the metrics.
- var_names: List of variable names for each configuration,
assuming they are constant across configurations.
"""
config_names = dt.ncFetch(data_path, 'reference', 'config_name')
config_dz = dt.ncFetch(data_path, 'reference', 'config_dz')
y_full = dt.ncFetch(data_path, 'reference', 'y_full')
var_dof = dt.ncFetch(data_path, 'reference', 'var_dof')
num_vars = dt.ncFetch(data_path, 'reference', 'num_vars')
tab_colors = get_tab_colors()
# Loop over configs
idx_y_full = 0
for (c, (num_var, dof, config_name, dz)) in enumerate(
zip(num_vars, var_dof, config_names, config_dz)):
for v in range(int(num_var)):
if var_names is not None:
var_name = var_names[v]
else:
var_name = str(v)
title = 'y_full_'+config_name+'_var_'+var_name
plt.figure(title)
profile = y_full[idx_y_full:idx_y_full+int(dof)]
z = dz*range(int(dof))
plt.plot(profile, z, color=tab_colors[c])
# Decorate plot
plt.ylabel(r'$z$ (m)')
plt.xlabel(var_name)
delta_profile = max(profile) - min(profile)
plt.xlim(min(profile) - 0.1*delta_profile,
max(profile) + 0.1*delta_profile)
plt.ylim(0, 3000)
plt.tight_layout()
# Save plot and update index
plt.savefig(title+'.pdf', format='pdf')
idx_y_full += int(dof)
return
def plot_prior_post_ref(data_path:str, var_names:Optional[List[str]] = None, validation:bool =True):
"""Plots vertical profiles of the reference/truth, best initial particle and
best final particle for each variable and configuration.
Args:
- data_path: Diagnostic data path from which to draw
the metrics.
- var_names: List of variable names for each configuration,
assuming they are constant across configurations.
"""
if validation:
num_vars = dt.ncFetch(data_path, 'reference', 'num_vars_val')
var_dof = dt.ncFetch(data_path, 'reference', 'var_dof_val')
y_full = dt.ncFetch(data_path, 'reference', 'y_full_val')
config_dz = dt.ncFetch(data_path, 'reference', 'config_dz_val')
config_names = dt.ncFetch(data_path, 'reference', 'config_name_val')
norm_factor = dt.ncFetch(data_path, 'reference', 'norm_factor_val')
# Last forward model evals are empty
g_full = dt.ncFetch(data_path, 'particle_diags', 'val_g_full')[:-1, :, :]
mse_full = dt.ncFetch(data_path, 'particle_diags', 'val_mse_full')[:-1, :]
else:
num_vars = dt.ncFetch(data_path, 'reference', 'num_vars')
var_dof = dt.ncFetch(data_path, 'reference', 'var_dof')
y_full = dt.ncFetch(data_path, 'reference', 'y_full')
config_dz = dt.ncFetch(data_path, 'reference', 'config_dz')
config_names = dt.ncFetch(data_path, 'reference', 'config_name')
norm_factor = dt.ncFetch(data_path, 'reference', 'norm_factor')
# Last forward model evals are empty
g_full = dt.ncFetch(data_path, 'particle_diags', 'g_full')[:-1, :, :]
mse_full = dt.ncFetch(data_path, 'particle_diags', 'mse_full')[:-1, :]
print("Shape of mse_full is", np.shape(mse_full))
print("Shape of g_full is", np.shape(g_full))
best_particle = np.argmin(mse_full, axis = 1)
print("Shape of best_particle is", np.shape(best_particle))
tab_colors = get_tab_colors()
# Loop over configs
idx_y_full = 0
for (c, (num_var, dof, config_name, dz)) in enumerate(
zip(num_vars, var_dof, config_names, config_dz)):
for v in range(int(num_var)):
if var_names is not None:
var_name = var_names[v]
else:
var_name = str(v)
title = 'y_full_'+config_name+'_var_'+var_name
plt.figure(title)
ref_profile = y_full[idx_y_full:idx_y_full+int(dof)]*np.sqrt(norm_factor[v, c])
prior_profile = g_full[0, idx_y_full:idx_y_full+int(dof), best_particle[0]]*np.sqrt(norm_factor[v, c])
post_profile = g_full[-1, idx_y_full:idx_y_full+int(dof), best_particle[-1]]*np.sqrt(norm_factor[v, c])
z = dz*range(int(dof))
plt.plot(ref_profile, z, color='0.2', label='LES')
plt.plot(prior_profile, z, color='tab:orange', label='Prior')
plt.plot(post_profile, z, color='tab:green', label='Posterior')
# Decorate plot
plt.ylabel(r'$z$ (m)')
plt.xlabel(var_name)
delta_profile = max(ref_profile) - min(ref_profile)
plt.xlim(min(ref_profile) - 0.1*delta_profile,
max(ref_profile) + 0.1*delta_profile)
plt.ylim(0, 3000)
plt.legend(frameon=False)
plt.ticklabel_format(axis="x", style="sci", scilimits=(-2, 4))
plt.tight_layout()
# Save plot and update index
plt.savefig(title+'.pdf', format='pdf')
idx_y_full += int(dof)
return
def plot_cov_spectrum(data_paths:List[str]):
"""Plots vertical profiles from `y_full` for each variable and
configuration.
Args:
- data_path: Diagnostic data path from which to draw
the metrics.
- var_names: List of variable names for each configuration,
assuming they are constant across configurations.
"""
tab_colors = get_tab_colors()
for data_path in data_paths:
gamma_full = dt.ncFetch(data_path, 'reference', 'Gamma_full')
gamma = dt.ncFetch(data_path, 'reference', 'Gamma')
eig_full, _ = np.linalg.eig(gamma_full)
eig_full = sorted(eig_full, reverse=True)
eig = sorted(np.diagonal(gamma), reverse=True)
title = 'spectrum_'+os.path.basename(data_path)
plt.figure(title)
plt.plot(range(len(eig_full)), eig_full, color='tab:orange')
plt.plot(range(len(eig)), eig, color='tab:green')
plt.yscale('log')
# Decorate plot
plt.ylabel(r'Eigenvalue')
plt.xlabel(r'Mode')
plt.ylim(min(eig_full), 1.05*max(eig))
plt.xlim(0, len(eig_full))
plt.tight_layout()
# Save plot and update index
plt.savefig(title+'.pdf', format='pdf')
return
def plot_modes(data_path:str, num_modes:int = 5, same_plot:bool = False):
"""Plots leading `num_modes` of each ReferenceModel in the data_path
diagnostics.
Args:
- data_path: Diagnostic data path from which to draw the modes.
- num_modes: Modes to plot from each ReferenceModel.
- same_plot: Whether to plot modes in the same figure or different ones.
"""
config_names = dt.ncFetch(data_path, 'reference', 'config_name')
d_csum = np.cumsum(dt.ncFetch(data_path, 'reference', 'config_pca_dim'))
d_csum = np.insert(d_csum, 0, 0)
var_dof = dt.ncFetch(data_path, 'reference', 'var_dof')
num_vars = dt.ncFetch(data_path, 'reference', 'num_vars')
config_dofsum = np.cumsum(np.multiply(num_vars, var_dof))
config_dofsum = np.insert(config_dofsum, 0, 0)
P_pca = dt.ncFetch(data_path, 'reference', 'P_pca')
tab_colors = get_tab_colors()
# Loop over configs
for (c, (config_dofs, d_cs, config_name)) in enumerate(
zip(config_dofsum, d_csum, config_names)):
# PCA matrix for this configuration
modes = P_pca[d_cs:d_csum[c+1], config_dofs:config_dofsum[c+1]]
# Number of principal modes
max_modes = d_csum[c+1] - d_cs
if same_plot:
title = 'modes_'+config_name
plt.figure(title)
for m in range(min(num_modes, max_modes)):
if not same_plot:
title = 'mode_'+str(m)+'_'+config_name
plt.figure(title)
# Leading eigenvectors are last in julia eig(), so reverse order
mode = modes[max_modes - 1 - m, :]
plt.plot(range(len(mode)), mode, color=tab_colors[m], label='Mode'+str(m))
# Decorate plot
plt.ylabel(r'Magnitude')
plt.xlabel(r'Degree of Freedom')
plt.legend(frameon=False)
plt.tight_layout()
# Save plot and update index
if not same_plot:
plt.savefig(title+'.pdf', format='pdf')
if same_plot:
plt.savefig(title+'.pdf', format='pdf')
return
def plot_eigval_zero_crossings(data_path:str, normalize:bool = False):
"""Plots scatterplot of eigenvalue magnitude with the number of
zero-crossings of the corresponding eigenmode, for each ReferenceModel.
Args:
- data_path: Diagnostic data path from which to draw
the metrics.
- normalize: Whether to normalize eigenvalues by the maximum
eigenvalue in the ReferenceModel.
"""
config_names = dt.ncFetch(data_path, 'reference', 'config_name')
d_csum = np.cumsum(dt.ncFetch(data_path, 'reference', 'config_pca_dim'))
d_csum = np.insert(d_csum, 0, 0)
gamma = dt.ncFetch(data_path, 'reference', 'Gamma')
var_dof = dt.ncFetch(data_path, 'reference', 'var_dof')
num_vars = dt.ncFetch(data_path, 'reference', 'num_vars')
config_dofsum = np.cumsum(np.multiply(num_vars, var_dof))
config_dofsum = np.insert(config_dofsum, 0, 0)
P_pca = dt.ncFetch(data_path, 'reference', 'P_pca')
tab_colors = get_tab_colors()
title = 'zero_crossings'
if normalize:
title = title+'_normalized'
plt.figure(title)
# Loop over configs
for (c, (config_dofs, d_cs, config_name)) in enumerate(
zip(config_dofsum, d_csum, config_names)):
# PCA matrix for this configuration
modes = P_pca[d_cs:d_csum[c+1], config_dofs:config_dofsum[c+1]]
# Number of principal modes
max_modes = d_csum[c+1] - d_cs
zero_crossing_num = np.zeros(max_modes)
for m in range(max_modes):
# Leading eigenvectors are last in julia eig(), so reverse order
mode = modes[max_modes - 1 - m, :]
zero_crossings = np.where(np.diff(np.sign(mode)))[0]
zero_crossing_num[m] = len(zero_crossings)
# Get eigenvalues and order them
eigvals_ = np.array(sorted(np.diagonal(gamma[d_cs:d_csum[c+1], d_cs:d_csum[c+1]]),
reverse=True))
if normalize:
den = eigvals_[0]
else:
den = 1.0
plt.plot(zero_crossing_num, eigvals_/den, color=tab_colors[c], label=config_name)
plt.yscale('log')
# Decorate plot
plt.xlabel(r'Zero crossings')
plt.ylabel(r'Eigenvalue')
plt.legend(frameon=False)
plt.tight_layout()
# Save plot and update index
plt.savefig(title+'.pdf', format='pdf')
return
def plot_parameter_evol(data_paths:List[str]):
"""Plots the parameter evolution from the given data_paths.
The plotted results are the parameter means in physical (constrained) space,
with shading bounds defined by the marginal standard deviation of each
parameter.
The extreme values of the bounds are the transformed parameter values
1 standard deviation from the mean in unconstrained space. These bounds
are not representative of parameter uncertainty when using the Ensemble
Kalman Inversion, but they are representative of the parameter sensitivities
in the case of Unscented Kalman Inversion.
Args:
- data_paths: List of diagnostic data paths from which to draw
the parameter evolutions.
"""
tab_colors = get_tab_colors()
# Fetch parameter and covariance evolutions
param_evolutions = []
param_low_evolutions = []
param_upp_evolutions = []
for data_path in data_paths:
phi_mean = dt.ncFetch(data_path, 'ensemble_diags', 'phi_mean')
phi_low = dt.ncFetch(data_path, 'ensemble_diags', 'phi_low_unc')
phi_upp = dt.ncFetch(data_path, 'ensemble_diags', 'phi_upp_unc')
param_evolutions.append(phi_mean)
param_low_evolutions.append(phi_low)
param_upp_evolutions.append(phi_upp)
params = dt.ncFetch(data_path, 'particle_diags', 'param')
for (i, param) in enumerate(params):
title = "Parameter "+str(param)
fig = plt.figure(title)
max_t = 0
for c, (param_evol, low_evol, upp_evol, data_path) in enumerate(zip(param_evolutions,
param_low_evolutions, param_upp_evolutions, data_paths)):
shading = convert2rgb(tab_colors[c], 0.4)
t = dt.ncFetch(data_path, 'ensemble_diags', 'iteration')
max_t = max(t[-1], max_t)
mean_val = param_evol[:, i]
lower_bound = low_evol[:, i]
upper_bound = upp_evol[:, i]
plt.plot(t, mean_val, color=tab_colors[c])
plt.fill_between(t, mean_val, lower_bound, color=shading)
plt.fill_between(t, mean_val, upper_bound, color=shading)
label = (data_path).split('_')[-1]
plt.xlabel(r'Iteration')
plt.ylabel(param)
plt.xlim(0, max_t)
ax = fig.gca()
ax.xaxis.set_major_locator(MaxNLocator(integer=True))
plt.legend(frameon=False)
plt.savefig(title+'.pdf', format='pdf')
return
|
[
"matplotlib.pyplot.yscale",
"numpy.argmin",
"numpy.shape",
"matplotlib.pyplot.figure",
"numpy.mean",
"matplotlib.pyplot.fill_between",
"matplotlib.pyplot.tight_layout",
"numpy.multiply",
"matplotlib.ticker.MaxNLocator",
"helper_funcs.get_tab_colors",
"numpy.insert",
"numpy.linalg.eig",
"numpy.diagonal",
"matplotlib.pyplot.ylim",
"os.path.basename",
"matplotlib.pyplot.legend",
"data_tools.ncFetchDim",
"matplotlib.pyplot.ticklabel_format",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.plot",
"helper_funcs.convert2rgb",
"numpy.zeros",
"data_tools.ncFetch",
"numpy.sign",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.savefig",
"numpy.sqrt"
] |
[((1411, 1427), 'helper_funcs.get_tab_colors', 'get_tab_colors', ([], {}), '()\n', (1425, 1427), False, 'from helper_funcs import convert2rgb, get_tab_colors\n'), ((1438, 1456), 'matplotlib.pyplot.figure', 'plt.figure', (['metric'], {}), '(metric)\n', (1448, 1456), True, 'import matplotlib.pyplot as plt\n'), ((2354, 2372), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['metric'], {}), '(metric)\n', (2364, 2372), True, 'import matplotlib.pyplot as plt\n'), ((2377, 2400), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Iteration"""'], {}), "('Iteration')\n", (2387, 2400), True, 'import matplotlib.pyplot as plt\n'), ((2405, 2423), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(0)', 'max_t'], {}), '(0, max_t)\n', (2413, 2423), True, 'import matplotlib.pyplot as plt\n'), ((2505, 2530), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'frameon': '(False)'}), '(frameon=False)\n', (2515, 2530), True, 'import matplotlib.pyplot as plt\n'), ((2535, 2553), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (2551, 2553), True, 'import matplotlib.pyplot as plt\n'), ((2558, 2600), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(metric + '.pdf')"], {'format': '"""pdf"""'}), "(metric + '.pdf', format='pdf')\n", (2569, 2600), True, 'import matplotlib.pyplot as plt\n'), ((3521, 3537), 'helper_funcs.get_tab_colors', 'get_tab_colors', ([], {}), '()\n', (3535, 3537), False, 'from helper_funcs import convert2rgb, get_tab_colors\n'), ((3548, 3581), 'matplotlib.pyplot.figure', 'plt.figure', (["(metric + ' per epoch')"], {}), "(metric + ' per epoch')\n", (3558, 3581), True, 'import matplotlib.pyplot as plt\n'), ((5563, 5583), 'numpy.mean', 'np.mean', (['var'], {'axis': '(1)'}), '(var, axis=1)\n', (5570, 5583), True, 'import numpy as np\n'), ((5992, 6041), 'data_tools.ncFetch', 'dt.ncFetch', (['data_path', '"""reference"""', '"""config_name"""'], {}), "(data_path, 'reference', 'config_name')\n", (6002, 6041), True, 'import data_tools as dt\n'), ((6058, 6105), 'data_tools.ncFetch', 'dt.ncFetch', (['data_path', '"""reference"""', '"""config_dz"""'], {}), "(data_path, 'reference', 'config_dz')\n", (6068, 6105), True, 'import data_tools as dt\n'), ((6119, 6163), 'data_tools.ncFetch', 'dt.ncFetch', (['data_path', '"""reference"""', '"""y_full"""'], {}), "(data_path, 'reference', 'y_full')\n", (6129, 6163), True, 'import data_tools as dt\n'), ((6178, 6223), 'data_tools.ncFetch', 'dt.ncFetch', (['data_path', '"""reference"""', '"""var_dof"""'], {}), "(data_path, 'reference', 'var_dof')\n", (6188, 6223), True, 'import data_tools as dt\n'), ((6239, 6285), 'data_tools.ncFetch', 'dt.ncFetch', (['data_path', '"""reference"""', '"""num_vars"""'], {}), "(data_path, 'reference', 'num_vars')\n", (6249, 6285), True, 'import data_tools as dt\n'), ((6303, 6319), 'helper_funcs.get_tab_colors', 'get_tab_colors', ([], {}), '()\n', (6317, 6319), False, 'from helper_funcs import convert2rgb, get_tab_colors\n'), ((9209, 9236), 'numpy.argmin', 'np.argmin', (['mse_full'], {'axis': '(1)'}), '(mse_full, axis=1)\n', (9218, 9236), True, 'import numpy as np\n'), ((9320, 9336), 'helper_funcs.get_tab_colors', 'get_tab_colors', ([], {}), '()\n', (9334, 9336), False, 'from helper_funcs import convert2rgb, get_tab_colors\n'), ((11281, 11297), 'helper_funcs.get_tab_colors', 'get_tab_colors', ([], {}), '()\n', (11295, 11297), False, 'from helper_funcs import convert2rgb, get_tab_colors\n'), ((12548, 12597), 'data_tools.ncFetch', 'dt.ncFetch', (['data_path', '"""reference"""', '"""config_name"""'], {}), "(data_path, 'reference', 'config_name')\n", (12558, 12597), True, 'import data_tools as dt\n'), ((12688, 12711), 'numpy.insert', 'np.insert', (['d_csum', '(0)', '(0)'], {}), '(d_csum, 0, 0)\n', (12697, 12711), True, 'import numpy as np\n'), ((12726, 12771), 'data_tools.ncFetch', 'dt.ncFetch', (['data_path', '"""reference"""', '"""var_dof"""'], {}), "(data_path, 'reference', 'var_dof')\n", (12736, 12771), True, 'import data_tools as dt\n'), ((12787, 12833), 'data_tools.ncFetch', 'dt.ncFetch', (['data_path', '"""reference"""', '"""num_vars"""'], {}), "(data_path, 'reference', 'num_vars')\n", (12797, 12833), True, 'import data_tools as dt\n'), ((12916, 12946), 'numpy.insert', 'np.insert', (['config_dofsum', '(0)', '(0)'], {}), '(config_dofsum, 0, 0)\n', (12925, 12946), True, 'import numpy as np\n'), ((12959, 13002), 'data_tools.ncFetch', 'dt.ncFetch', (['data_path', '"""reference"""', '"""P_pca"""'], {}), "(data_path, 'reference', 'P_pca')\n", (12969, 13002), True, 'import data_tools as dt\n'), ((13020, 13036), 'helper_funcs.get_tab_colors', 'get_tab_colors', ([], {}), '()\n', (13034, 13036), False, 'from helper_funcs import convert2rgb, get_tab_colors\n'), ((14671, 14720), 'data_tools.ncFetch', 'dt.ncFetch', (['data_path', '"""reference"""', '"""config_name"""'], {}), "(data_path, 'reference', 'config_name')\n", (14681, 14720), True, 'import data_tools as dt\n'), ((14811, 14834), 'numpy.insert', 'np.insert', (['d_csum', '(0)', '(0)'], {}), '(d_csum, 0, 0)\n', (14820, 14834), True, 'import numpy as np\n'), ((14847, 14890), 'data_tools.ncFetch', 'dt.ncFetch', (['data_path', '"""reference"""', '"""Gamma"""'], {}), "(data_path, 'reference', 'Gamma')\n", (14857, 14890), True, 'import data_tools as dt\n'), ((14905, 14950), 'data_tools.ncFetch', 'dt.ncFetch', (['data_path', '"""reference"""', '"""var_dof"""'], {}), "(data_path, 'reference', 'var_dof')\n", (14915, 14950), True, 'import data_tools as dt\n'), ((14966, 15012), 'data_tools.ncFetch', 'dt.ncFetch', (['data_path', '"""reference"""', '"""num_vars"""'], {}), "(data_path, 'reference', 'num_vars')\n", (14976, 15012), True, 'import data_tools as dt\n'), ((15095, 15125), 'numpy.insert', 'np.insert', (['config_dofsum', '(0)', '(0)'], {}), '(config_dofsum, 0, 0)\n', (15104, 15125), True, 'import numpy as np\n'), ((15138, 15181), 'data_tools.ncFetch', 'dt.ncFetch', (['data_path', '"""reference"""', '"""P_pca"""'], {}), "(data_path, 'reference', 'P_pca')\n", (15148, 15181), True, 'import data_tools as dt\n'), ((15199, 15215), 'helper_funcs.get_tab_colors', 'get_tab_colors', ([], {}), '()\n', (15213, 15215), False, 'from helper_funcs import convert2rgb, get_tab_colors\n'), ((15303, 15320), 'matplotlib.pyplot.figure', 'plt.figure', (['title'], {}), '(title)\n', (15313, 15320), True, 'import matplotlib.pyplot as plt\n'), ((17370, 17386), 'helper_funcs.get_tab_colors', 'get_tab_colors', ([], {}), '()\n', (17384, 17386), False, 'from helper_funcs import convert2rgb, get_tab_colors\n'), ((17917, 17965), 'data_tools.ncFetch', 'dt.ncFetch', (['data_path', '"""particle_diags"""', '"""param"""'], {}), "(data_path, 'particle_diags', 'param')\n", (17927, 17965), True, 'import data_tools as dt\n'), ((1538, 1569), 'helper_funcs.convert2rgb', 'convert2rgb', (['tab_colors[i]', '(0.4)'], {}), '(tab_colors[i], 0.4)\n', (1549, 1569), False, 'from helper_funcs import convert2rgb, get_tab_colors\n'), ((1965, 2015), 'matplotlib.pyplot.plot', 'plt.plot', (['t', 'var'], {'color': 'tab_colors[i]', 'label': 'label'}), '(t, var, color=tab_colors[i], label=label)\n', (1973, 2015), True, 'import matplotlib.pyplot as plt\n'), ((2474, 2499), 'matplotlib.ticker.MaxNLocator', 'MaxNLocator', ([], {'integer': '(True)'}), '(integer=True)\n', (2485, 2499), False, 'from matplotlib.ticker import MaxNLocator\n'), ((3647, 3678), 'helper_funcs.convert2rgb', 'convert2rgb', (['tab_colors[i]', '(0.4)'], {}), '(tab_colors[i], 0.4)\n', (3658, 3678), False, 'from helper_funcs import convert2rgb, get_tab_colors\n'), ((3700, 3751), 'data_tools.ncFetchDim', 'dt.ncFetchDim', (['data_path', '"""reference"""', '"""batch_size"""'], {}), "(data_path, 'reference', 'batch_size')\n", (3713, 3751), True, 'import data_tools as dt\n'), ((3773, 3820), 'data_tools.ncFetchDim', 'dt.ncFetchDim', (['data_path', '"""reference"""', '"""config"""'], {}), "(data_path, 'reference', 'config')\n", (3786, 3820), True, 'import data_tools as dt\n'), ((4284, 4338), 'matplotlib.pyplot.plot', 'plt.plot', (['epoch', 'var'], {'color': 'tab_colors[i]', 'label': 'label'}), '(epoch, var, color=tab_colors[i], label=label)\n', (4292, 4338), True, 'import matplotlib.pyplot as plt\n'), ((4797, 4815), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['metric'], {}), '(metric)\n', (4807, 4815), True, 'import matplotlib.pyplot as plt\n'), ((4824, 4843), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Epoch"""'], {}), "('Epoch')\n", (4834, 4843), True, 'import matplotlib.pyplot as plt\n'), ((4937, 4962), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'frameon': '(False)'}), '(frameon=False)\n', (4947, 4962), True, 'import matplotlib.pyplot as plt\n'), ((4971, 5023), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(metric + '_per_epoch.pdf')"], {'format': '"""pdf"""'}), "(metric + '_per_epoch.pdf', format='pdf')\n", (4982, 5023), True, 'import matplotlib.pyplot as plt\n'), ((7847, 7897), 'data_tools.ncFetch', 'dt.ncFetch', (['data_path', '"""reference"""', '"""num_vars_val"""'], {}), "(data_path, 'reference', 'num_vars_val')\n", (7857, 7897), True, 'import data_tools as dt\n'), ((7916, 7965), 'data_tools.ncFetch', 'dt.ncFetch', (['data_path', '"""reference"""', '"""var_dof_val"""'], {}), "(data_path, 'reference', 'var_dof_val')\n", (7926, 7965), True, 'import data_tools as dt\n'), ((7983, 8031), 'data_tools.ncFetch', 'dt.ncFetch', (['data_path', '"""reference"""', '"""y_full_val"""'], {}), "(data_path, 'reference', 'y_full_val')\n", (7993, 8031), True, 'import data_tools as dt\n'), ((8052, 8103), 'data_tools.ncFetch', 'dt.ncFetch', (['data_path', '"""reference"""', '"""config_dz_val"""'], {}), "(data_path, 'reference', 'config_dz_val')\n", (8062, 8103), True, 'import data_tools as dt\n'), ((8127, 8180), 'data_tools.ncFetch', 'dt.ncFetch', (['data_path', '"""reference"""', '"""config_name_val"""'], {}), "(data_path, 'reference', 'config_name_val')\n", (8137, 8180), True, 'import data_tools as dt\n'), ((8203, 8256), 'data_tools.ncFetch', 'dt.ncFetch', (['data_path', '"""reference"""', '"""norm_factor_val"""'], {}), "(data_path, 'reference', 'norm_factor_val')\n", (8213, 8256), True, 'import data_tools as dt\n'), ((8496, 8542), 'data_tools.ncFetch', 'dt.ncFetch', (['data_path', '"""reference"""', '"""num_vars"""'], {}), "(data_path, 'reference', 'num_vars')\n", (8506, 8542), True, 'import data_tools as dt\n'), ((8561, 8606), 'data_tools.ncFetch', 'dt.ncFetch', (['data_path', '"""reference"""', '"""var_dof"""'], {}), "(data_path, 'reference', 'var_dof')\n", (8571, 8606), True, 'import data_tools as dt\n'), ((8624, 8668), 'data_tools.ncFetch', 'dt.ncFetch', (['data_path', '"""reference"""', '"""y_full"""'], {}), "(data_path, 'reference', 'y_full')\n", (8634, 8668), True, 'import data_tools as dt\n'), ((8689, 8736), 'data_tools.ncFetch', 'dt.ncFetch', (['data_path', '"""reference"""', '"""config_dz"""'], {}), "(data_path, 'reference', 'config_dz')\n", (8699, 8736), True, 'import data_tools as dt\n'), ((8760, 8809), 'data_tools.ncFetch', 'dt.ncFetch', (['data_path', '"""reference"""', '"""config_name"""'], {}), "(data_path, 'reference', 'config_name')\n", (8770, 8809), True, 'import data_tools as dt\n'), ((8832, 8881), 'data_tools.ncFetch', 'dt.ncFetch', (['data_path', '"""reference"""', '"""norm_factor"""'], {}), "(data_path, 'reference', 'norm_factor')\n", (8842, 8881), True, 'import data_tools as dt\n'), ((9119, 9137), 'numpy.shape', 'np.shape', (['mse_full'], {}), '(mse_full)\n', (9127, 9137), True, 'import numpy as np\n'), ((9171, 9187), 'numpy.shape', 'np.shape', (['g_full'], {}), '(g_full)\n', (9179, 9187), True, 'import numpy as np\n'), ((9278, 9301), 'numpy.shape', 'np.shape', (['best_particle'], {}), '(best_particle)\n', (9286, 9301), True, 'import numpy as np\n'), ((11352, 11400), 'data_tools.ncFetch', 'dt.ncFetch', (['data_path', '"""reference"""', '"""Gamma_full"""'], {}), "(data_path, 'reference', 'Gamma_full')\n", (11362, 11400), True, 'import data_tools as dt\n'), ((11417, 11460), 'data_tools.ncFetch', 'dt.ncFetch', (['data_path', '"""reference"""', '"""Gamma"""'], {}), "(data_path, 'reference', 'Gamma')\n", (11427, 11460), True, 'import data_tools as dt\n'), ((11483, 11508), 'numpy.linalg.eig', 'np.linalg.eig', (['gamma_full'], {}), '(gamma_full)\n', (11496, 11508), True, 'import numpy as np\n'), ((11678, 11695), 'matplotlib.pyplot.figure', 'plt.figure', (['title'], {}), '(title)\n', (11688, 11695), True, 'import matplotlib.pyplot as plt\n'), ((11831, 11848), 'matplotlib.pyplot.yscale', 'plt.yscale', (['"""log"""'], {}), "('log')\n", (11841, 11848), True, 'import matplotlib.pyplot as plt\n'), ((11881, 11905), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Eigenvalue"""'], {}), "('Eigenvalue')\n", (11891, 11905), True, 'import matplotlib.pyplot as plt\n'), ((11915, 11933), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Mode"""'], {}), "('Mode')\n", (11925, 11933), True, 'import matplotlib.pyplot as plt\n'), ((12025, 12043), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (12041, 12043), True, 'import matplotlib.pyplot as plt\n'), ((12089, 12130), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(title + '.pdf')"], {'format': '"""pdf"""'}), "(title + '.pdf', format='pdf')\n", (12100, 12130), True, 'import matplotlib.pyplot as plt\n'), ((12621, 12673), 'data_tools.ncFetch', 'dt.ncFetch', (['data_path', '"""reference"""', '"""config_pca_dim"""'], {}), "(data_path, 'reference', 'config_pca_dim')\n", (12631, 12673), True, 'import data_tools as dt\n'), ((12864, 12894), 'numpy.multiply', 'np.multiply', (['num_vars', 'var_dof'], {}), '(num_vars, var_dof)\n', (12875, 12894), True, 'import numpy as np\n'), ((14744, 14796), 'data_tools.ncFetch', 'dt.ncFetch', (['data_path', '"""reference"""', '"""config_pca_dim"""'], {}), "(data_path, 'reference', 'config_pca_dim')\n", (14754, 14796), True, 'import data_tools as dt\n'), ((15043, 15073), 'numpy.multiply', 'np.multiply', (['num_vars', 'var_dof'], {}), '(num_vars, var_dof)\n', (15054, 15073), True, 'import numpy as np\n'), ((15679, 15698), 'numpy.zeros', 'np.zeros', (['max_modes'], {}), '(max_modes)\n', (15687, 15698), True, 'import numpy as np\n'), ((16233, 16321), 'matplotlib.pyplot.plot', 'plt.plot', (['zero_crossing_num', '(eigvals_ / den)'], {'color': 'tab_colors[c]', 'label': 'config_name'}), '(zero_crossing_num, eigvals_ / den, color=tab_colors[c], label=\n config_name)\n', (16241, 16321), True, 'import matplotlib.pyplot as plt\n'), ((16323, 16340), 'matplotlib.pyplot.yscale', 'plt.yscale', (['"""log"""'], {}), "('log')\n", (16333, 16340), True, 'import matplotlib.pyplot as plt\n'), ((16373, 16401), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Zero crossings"""'], {}), "('Zero crossings')\n", (16383, 16401), True, 'import matplotlib.pyplot as plt\n'), ((16411, 16435), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Eigenvalue"""'], {}), "('Eigenvalue')\n", (16421, 16435), True, 'import matplotlib.pyplot as plt\n'), ((16445, 16470), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'frameon': '(False)'}), '(frameon=False)\n', (16455, 16470), True, 'import matplotlib.pyplot as plt\n'), ((16479, 16497), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (16495, 16497), True, 'import matplotlib.pyplot as plt\n'), ((16543, 16584), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(title + '.pdf')"], {'format': '"""pdf"""'}), "(title + '.pdf', format='pdf')\n", (16554, 16584), True, 'import matplotlib.pyplot as plt\n'), ((17574, 17625), 'data_tools.ncFetch', 'dt.ncFetch', (['data_path', '"""ensemble_diags"""', '"""phi_mean"""'], {}), "(data_path, 'ensemble_diags', 'phi_mean')\n", (17584, 17625), True, 'import data_tools as dt\n'), ((17644, 17698), 'data_tools.ncFetch', 'dt.ncFetch', (['data_path', '"""ensemble_diags"""', '"""phi_low_unc"""'], {}), "(data_path, 'ensemble_diags', 'phi_low_unc')\n", (17654, 17698), True, 'import data_tools as dt\n'), ((17717, 17771), 'data_tools.ncFetch', 'dt.ncFetch', (['data_path', '"""ensemble_diags"""', '"""phi_upp_unc"""'], {}), "(data_path, 'ensemble_diags', 'phi_upp_unc')\n", (17727, 17771), True, 'import data_tools as dt\n'), ((18061, 18078), 'matplotlib.pyplot.figure', 'plt.figure', (['title'], {}), '(title)\n', (18071, 18078), True, 'import matplotlib.pyplot as plt\n'), ((18798, 18821), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Iteration"""'], {}), "('Iteration')\n", (18808, 18821), True, 'import matplotlib.pyplot as plt\n'), ((18831, 18848), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['param'], {}), '(param)\n', (18841, 18848), True, 'import matplotlib.pyplot as plt\n'), ((18857, 18875), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(0)', 'max_t'], {}), '(0, max_t)\n', (18865, 18875), True, 'import matplotlib.pyplot as plt\n'), ((18969, 18994), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'frameon': '(False)'}), '(frameon=False)\n', (18979, 18994), True, 'import matplotlib.pyplot as plt\n'), ((19003, 19044), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(title + '.pdf')"], {'format': '"""pdf"""'}), "(title + '.pdf', format='pdf')\n", (19014, 19044), True, 'import matplotlib.pyplot as plt\n'), ((1584, 1624), 'data_tools.ncFetch', 'dt.ncFetch', (['data_path', '"""metrics"""', 'metric'], {}), "(data_path, 'metrics', metric)\n", (1594, 1624), True, 'import data_tools as dt\n'), ((1872, 1917), 'data_tools.ncFetch', 'dt.ncFetch', (['data_path', '"""metrics"""', '"""iteration"""'], {}), "(data_path, 'metrics', 'iteration')\n", (1882, 1917), True, 'import data_tools as dt\n'), ((2139, 2183), 'matplotlib.pyplot.fill_between', 'plt.fill_between', (['t', 'var', 'low'], {'color': 'shading'}), '(t, var, low, color=shading)\n', (2155, 2183), True, 'import matplotlib.pyplot as plt\n'), ((2305, 2349), 'matplotlib.pyplot.fill_between', 'plt.fill_between', (['t', 'var', 'upp'], {'color': 'shading'}), '(t, var, upp, color=shading)\n', (2321, 2349), True, 'import matplotlib.pyplot as plt\n'), ((3914, 3954), 'data_tools.ncFetch', 'dt.ncFetch', (['data_path', '"""metrics"""', 'metric'], {}), "(data_path, 'metrics', metric)\n", (3924, 3954), True, 'import data_tools as dt\n'), ((4516, 4564), 'matplotlib.pyplot.fill_between', 'plt.fill_between', (['epoch', 'var', 'low'], {'color': 'shading'}), '(epoch, var, low, color=shading)\n', (4532, 4564), True, 'import matplotlib.pyplot as plt\n'), ((4740, 4788), 'matplotlib.pyplot.fill_between', 'plt.fill_between', (['epoch', 'var', 'upp'], {'color': 'shading'}), '(epoch, var, upp, color=shading)\n', (4756, 4788), True, 'import matplotlib.pyplot as plt\n'), ((4902, 4927), 'matplotlib.ticker.MaxNLocator', 'MaxNLocator', ([], {'integer': '(True)'}), '(integer=True)\n', (4913, 4927), False, 'from matplotlib.ticker import MaxNLocator\n'), ((6723, 6740), 'matplotlib.pyplot.figure', 'plt.figure', (['title'], {}), '(title)\n', (6733, 6740), True, 'import matplotlib.pyplot as plt\n'), ((6849, 6890), 'matplotlib.pyplot.plot', 'plt.plot', (['profile', 'z'], {'color': 'tab_colors[c]'}), '(profile, z, color=tab_colors[c])\n', (6857, 6890), True, 'import matplotlib.pyplot as plt\n'), ((6931, 6952), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""$z$ (m)"""'], {}), "('$z$ (m)')\n", (6941, 6952), True, 'import matplotlib.pyplot as plt\n'), ((6966, 6986), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['var_name'], {}), '(var_name)\n', (6976, 6986), True, 'import matplotlib.pyplot as plt\n'), ((7160, 7177), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(0)', '(3000)'], {}), '(0, 3000)\n', (7168, 7177), True, 'import matplotlib.pyplot as plt\n'), ((7190, 7208), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (7206, 7208), True, 'import matplotlib.pyplot as plt\n'), ((7262, 7303), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(title + '.pdf')"], {'format': '"""pdf"""'}), "(title + '.pdf', format='pdf')\n", (7273, 7303), True, 'import matplotlib.pyplot as plt\n'), ((8319, 8372), 'data_tools.ncFetch', 'dt.ncFetch', (['data_path', '"""particle_diags"""', '"""val_g_full"""'], {}), "(data_path, 'particle_diags', 'val_g_full')\n", (8329, 8372), True, 'import data_tools as dt\n'), ((8403, 8458), 'data_tools.ncFetch', 'dt.ncFetch', (['data_path', '"""particle_diags"""', '"""val_mse_full"""'], {}), "(data_path, 'particle_diags', 'val_mse_full')\n", (8413, 8458), True, 'import data_tools as dt\n'), ((8944, 8993), 'data_tools.ncFetch', 'dt.ncFetch', (['data_path', '"""particle_diags"""', '"""g_full"""'], {}), "(data_path, 'particle_diags', 'g_full')\n", (8954, 8993), True, 'import data_tools as dt\n'), ((9024, 9075), 'data_tools.ncFetch', 'dt.ncFetch', (['data_path', '"""particle_diags"""', '"""mse_full"""'], {}), "(data_path, 'particle_diags', 'mse_full')\n", (9034, 9075), True, 'import data_tools as dt\n'), ((9740, 9757), 'matplotlib.pyplot.figure', 'plt.figure', (['title'], {}), '(title)\n', (9750, 9757), True, 'import matplotlib.pyplot as plt\n'), ((10128, 10178), 'matplotlib.pyplot.plot', 'plt.plot', (['ref_profile', 'z'], {'color': '"""0.2"""', 'label': '"""LES"""'}), "(ref_profile, z, color='0.2', label='LES')\n", (10136, 10178), True, 'import matplotlib.pyplot as plt\n'), ((10191, 10252), 'matplotlib.pyplot.plot', 'plt.plot', (['prior_profile', 'z'], {'color': '"""tab:orange"""', 'label': '"""Prior"""'}), "(prior_profile, z, color='tab:orange', label='Prior')\n", (10199, 10252), True, 'import matplotlib.pyplot as plt\n'), ((10265, 10328), 'matplotlib.pyplot.plot', 'plt.plot', (['post_profile', 'z'], {'color': '"""tab:green"""', 'label': '"""Posterior"""'}), "(post_profile, z, color='tab:green', label='Posterior')\n", (10273, 10328), True, 'import matplotlib.pyplot as plt\n'), ((10369, 10390), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""$z$ (m)"""'], {}), "('$z$ (m)')\n", (10379, 10390), True, 'import matplotlib.pyplot as plt\n'), ((10404, 10424), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['var_name'], {}), '(var_name)\n', (10414, 10424), True, 'import matplotlib.pyplot as plt\n'), ((10614, 10631), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(0)', '(3000)'], {}), '(0, 3000)\n', (10622, 10631), True, 'import matplotlib.pyplot as plt\n'), ((10644, 10669), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'frameon': '(False)'}), '(frameon=False)\n', (10654, 10669), True, 'import matplotlib.pyplot as plt\n'), ((10682, 10744), 'matplotlib.pyplot.ticklabel_format', 'plt.ticklabel_format', ([], {'axis': '"""x"""', 'style': '"""sci"""', 'scilimits': '(-2, 4)'}), "(axis='x', style='sci', scilimits=(-2, 4))\n", (10702, 10744), True, 'import matplotlib.pyplot as plt\n'), ((10757, 10775), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (10773, 10775), True, 'import matplotlib.pyplot as plt\n'), ((10829, 10870), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(title + '.pdf')"], {'format': '"""pdf"""'}), "(title + '.pdf', format='pdf')\n", (10840, 10870), True, 'import matplotlib.pyplot as plt\n'), ((11580, 11598), 'numpy.diagonal', 'np.diagonal', (['gamma'], {}), '(gamma)\n', (11591, 11598), True, 'import numpy as np\n'), ((11642, 11669), 'os.path.basename', 'os.path.basename', (['data_path'], {}), '(data_path)\n', (11658, 11669), False, 'import os\n'), ((13442, 13459), 'matplotlib.pyplot.figure', 'plt.figure', (['title'], {}), '(title)\n', (13452, 13459), True, 'import matplotlib.pyplot as plt\n'), ((13881, 13904), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Magnitude"""'], {}), "('Magnitude')\n", (13891, 13904), True, 'import matplotlib.pyplot as plt\n'), ((13918, 13949), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Degree of Freedom"""'], {}), "('Degree of Freedom')\n", (13928, 13949), True, 'import matplotlib.pyplot as plt\n'), ((13963, 13988), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'frameon': '(False)'}), '(frameon=False)\n', (13973, 13988), True, 'import matplotlib.pyplot as plt\n'), ((14001, 14019), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (14017, 14019), True, 'import matplotlib.pyplot as plt\n'), ((14181, 14222), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(title + '.pdf')"], {'format': '"""pdf"""'}), "(title + '.pdf', format='pdf')\n", (14192, 14222), True, 'import matplotlib.pyplot as plt\n'), ((18287, 18318), 'helper_funcs.convert2rgb', 'convert2rgb', (['tab_colors[c]', '(0.4)'], {}), '(tab_colors[c], 0.4)\n', (18298, 18318), False, 'from helper_funcs import convert2rgb, get_tab_colors\n'), ((18335, 18387), 'data_tools.ncFetch', 'dt.ncFetch', (['data_path', '"""ensemble_diags"""', '"""iteration"""'], {}), "(data_path, 'ensemble_diags', 'iteration')\n", (18345, 18387), True, 'import data_tools as dt\n'), ((18560, 18602), 'matplotlib.pyplot.plot', 'plt.plot', (['t', 'mean_val'], {'color': 'tab_colors[c]'}), '(t, mean_val, color=tab_colors[c])\n', (18568, 18602), True, 'import matplotlib.pyplot as plt\n'), ((18615, 18672), 'matplotlib.pyplot.fill_between', 'plt.fill_between', (['t', 'mean_val', 'lower_bound'], {'color': 'shading'}), '(t, mean_val, lower_bound, color=shading)\n', (18631, 18672), True, 'import matplotlib.pyplot as plt\n'), ((18685, 18742), 'matplotlib.pyplot.fill_between', 'plt.fill_between', (['t', 'mean_val', 'upper_bound'], {'color': 'shading'}), '(t, mean_val, upper_bound, color=shading)\n', (18701, 18742), True, 'import matplotlib.pyplot as plt\n'), ((18934, 18959), 'matplotlib.ticker.MaxNLocator', 'MaxNLocator', ([], {'integer': '(True)'}), '(integer=True)\n', (18945, 18959), False, 'from matplotlib.ticker import MaxNLocator\n'), ((4395, 4440), 'data_tools.ncFetch', 'dt.ncFetch', (['data_path', '"""metrics"""', 'lower_bound'], {}), "(data_path, 'metrics', lower_bound)\n", (4405, 4440), True, 'import data_tools as dt\n'), ((4619, 4664), 'data_tools.ncFetch', 'dt.ncFetch', (['data_path', '"""metrics"""', 'upper_bound'], {}), "(data_path, 'metrics', upper_bound)\n", (4629, 4664), True, 'import data_tools as dt\n'), ((9823, 9849), 'numpy.sqrt', 'np.sqrt', (['norm_factor[v, c]'], {}), '(norm_factor[v, c])\n', (9830, 9849), True, 'import numpy as np\n'), ((9938, 9964), 'numpy.sqrt', 'np.sqrt', (['norm_factor[v, c]'], {}), '(norm_factor[v, c])\n', (9945, 9964), True, 'import numpy as np\n'), ((10054, 10080), 'numpy.sqrt', 'np.sqrt', (['norm_factor[v, c]'], {}), '(norm_factor[v, c])\n', (10061, 10080), True, 'import numpy as np\n'), ((13612, 13629), 'matplotlib.pyplot.figure', 'plt.figure', (['title'], {}), '(title)\n', (13622, 13629), True, 'import matplotlib.pyplot as plt\n'), ((14107, 14148), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(title + '.pdf')"], {'format': '"""pdf"""'}), "(title + '.pdf', format='pdf')\n", (14118, 14148), True, 'import matplotlib.pyplot as plt\n'), ((16054, 16112), 'numpy.diagonal', 'np.diagonal', (['gamma[d_cs:d_csum[c + 1], d_cs:d_csum[c + 1]]'], {}), '(gamma[d_cs:d_csum[c + 1], d_cs:d_csum[c + 1]])\n', (16065, 16112), True, 'import numpy as np\n'), ((2072, 2117), 'data_tools.ncFetch', 'dt.ncFetch', (['data_path', '"""metrics"""', 'lower_bound'], {}), "(data_path, 'metrics', lower_bound)\n", (2082, 2117), True, 'import data_tools as dt\n'), ((2238, 2283), 'data_tools.ncFetch', 'dt.ncFetch', (['data_path', '"""metrics"""', 'upper_bound'], {}), "(data_path, 'metrics', upper_bound)\n", (2248, 2283), True, 'import data_tools as dt\n'), ((15904, 15917), 'numpy.sign', 'np.sign', (['mode'], {}), '(mode)\n', (15911, 15917), True, 'import numpy as np\n')]
|
import numpy as np
import pandas as pd
import biclust_comp.analysis.accuracy as acc
import biclust_comp.analysis.accuracy_utils as acc_utils
import biclust_comp.analysis.enrichment as enrich
def get_results_with_num_unique(error_df_file):
error_df = pd.read_csv(error_df_file)
unique_factors_df = get_unique_factors_df(error_df)
unique_pathways_df = enrich.get_number_unique_pathways(error_df_file)
results_with_fac = error_df.merge(unique_factors_df, how='left', on='method_dataset_run_id')
results_with_fac_path = results_with_fac.merge(unique_pathways_df, on='method_dataset_run_id', how='left')
return results_with_fac_path
def get_unique_factors_df(error_df):
unique_factors_dicts = []
thresholds = np.arange(0.2*100, 1.05*100, 0.05*100) / 100
for mdr in error_df[error_df['run_complete']]['method_dataset_run_id'].unique():
unique_factors, jaccard = get_unique_biclusters_thresholds(mdr, thresholds)
unique_factors_dicts.append(unique_factors)
unique_factors_df = pd.DataFrame(unique_factors_dicts)
return unique_factors_df
def get_unique_biclusters_thresholds(method_dataset_run_id, sim_thresholds):
K, X, B = acc_utils.read_result_binary_best_threshold(f"results/{method_dataset_run_id}")
intersect, union = acc.calc_overlaps(X, B, X, B)
jaccard = intersect/union
similarity_matrix = jaccard.copy()
similarity_matrix_reduced = similarity_matrix
np.fill_diagonal(similarity_matrix, 0)
indices = np.array(range(K))
unique_factors = {"method_dataset_run_id": method_dataset_run_id}
for sim_threshold in sorted(list(sim_thresholds), reverse=True):
indices = reduce_to_sim_threshold(similarity_matrix, indices, sim_threshold)
unique_factors[f"unique_factors_{sim_threshold}"] = len(indices)
return unique_factors, jaccard
def reduce_to_sim_threshold(similarity_matrix, current_indices, sim_threshold):
indices = current_indices.copy()
similarity_matrix_reduced = similarity_matrix[np.ix_(indices, indices)]
while similarity_matrix_reduced.max() > sim_threshold:
max_similarities = similarity_matrix_reduced.max(axis=1)
is_max = np.where(max_similarities == similarity_matrix_reduced.max())[0]
print("Maximum", is_max)
keep = is_max[0]
discard = is_max[1:]
print(discard)
indices = np.delete(indices, discard)
similarity_matrix_reduced = similarity_matrix[np.ix_(indices, indices)]
print(indices)
return indices
|
[
"pandas.DataFrame",
"numpy.fill_diagonal",
"pandas.read_csv",
"numpy.ix_",
"biclust_comp.analysis.enrichment.get_number_unique_pathways",
"biclust_comp.analysis.accuracy.calc_overlaps",
"biclust_comp.analysis.accuracy_utils.read_result_binary_best_threshold",
"numpy.arange",
"numpy.delete"
] |
[((256, 282), 'pandas.read_csv', 'pd.read_csv', (['error_df_file'], {}), '(error_df_file)\n', (267, 282), True, 'import pandas as pd\n'), ((364, 412), 'biclust_comp.analysis.enrichment.get_number_unique_pathways', 'enrich.get_number_unique_pathways', (['error_df_file'], {}), '(error_df_file)\n', (397, 412), True, 'import biclust_comp.analysis.enrichment as enrich\n'), ((1030, 1064), 'pandas.DataFrame', 'pd.DataFrame', (['unique_factors_dicts'], {}), '(unique_factors_dicts)\n', (1042, 1064), True, 'import pandas as pd\n'), ((1186, 1265), 'biclust_comp.analysis.accuracy_utils.read_result_binary_best_threshold', 'acc_utils.read_result_binary_best_threshold', (['f"""results/{method_dataset_run_id}"""'], {}), "(f'results/{method_dataset_run_id}')\n", (1229, 1265), True, 'import biclust_comp.analysis.accuracy_utils as acc_utils\n'), ((1289, 1318), 'biclust_comp.analysis.accuracy.calc_overlaps', 'acc.calc_overlaps', (['X', 'B', 'X', 'B'], {}), '(X, B, X, B)\n', (1306, 1318), True, 'import biclust_comp.analysis.accuracy as acc\n'), ((1443, 1481), 'numpy.fill_diagonal', 'np.fill_diagonal', (['similarity_matrix', '(0)'], {}), '(similarity_matrix, 0)\n', (1459, 1481), True, 'import numpy as np\n'), ((740, 784), 'numpy.arange', 'np.arange', (['(0.2 * 100)', '(1.05 * 100)', '(0.05 * 100)'], {}), '(0.2 * 100, 1.05 * 100, 0.05 * 100)\n', (749, 784), True, 'import numpy as np\n'), ((2018, 2042), 'numpy.ix_', 'np.ix_', (['indices', 'indices'], {}), '(indices, indices)\n', (2024, 2042), True, 'import numpy as np\n'), ((2379, 2406), 'numpy.delete', 'np.delete', (['indices', 'discard'], {}), '(indices, discard)\n', (2388, 2406), True, 'import numpy as np\n'), ((2461, 2485), 'numpy.ix_', 'np.ix_', (['indices', 'indices'], {}), '(indices, indices)\n', (2467, 2485), True, 'import numpy as np\n')]
|
import prata
import time
import timeit
import numpy as np
import sys
import random
import string
B = 1
KB = 1000
MB = 1000000
END = []
def getString(s):
#''.join(random.choice(string.ascii_letters) for x in range(int(real)))
real = 1 if (s-49) < 1 else s-49
return "1"*real
TIMES = 5
SLEEP = 2
NUMBER = 1
def printStats(stats, title, size, u = True):
f = open("pythonThrouput.txt","a")
stats = [round((x)/NUMBER,5) for x in stats]
kilo = size#/1000
bytes = "B"
if u:
if kilo > 1000:
kilo /= 1000
bytes = "KB"
if kilo > 1000:
kilo /= 1000
bytes = "MB"
mbs = [round(kilo/(i),5) for i in stats]
f.write(title + '\n')
f.write("###################\n")
f.write("Min: {}s\n".format(stats[0]))
f.write("Min {}/s: {}\n".format(bytes,mbs[0]))
f.write("Median: {}s\n".format(stats[1]))
f.write("Median {}/s: {}\n".format(bytes,mbs[1]))
f.write("Max: {}s\n".format(stats[2]))
f.write("Max {}/s: {}\n".format(bytes,mbs[2]))
f.write("Average: {}s\n".format(stats[3]))
f.write("Average {}/s: {}\n".format(bytes,mbs[3]))
f.write("###################\n\n")
else:
END.append([kilo,stats[3]])
f.close()
def getStats(times):
return [np.min(times), np.median(times), np.max(times), np.average(times)]
f = open("pythonThrouput.txt","w")
f.close()
m = prata.connect("127.0.0.1",25565)
m.host()
m.createChannel(25566, "test", "FIFO", 500)
SIZE = (1*B)
testListen='''
p.publish("test",STRING)
t = s.listen("test")
'''
obj = getString(SIZE)
setupTestListen = """
STRING = \""""+obj+"""\"
import prata
m = prata.connect(\"127.0.0.1\",25565)
s = m.subscriber()
p = m.publisher()
s.connect(\"test\")
p.connect(\"test\")
"""
printStats(getStats(timeit.Timer(stmt=testListen,setup=setupTestListen).repeat(number=NUMBER,repeat=TIMES)),"Round Trip 50 bytes", sys.getsizeof(obj))
SIZE = (1*KB)
testListen='''
p.publish("test",STRING)
t = s.listen("test")
'''
obj = getString(SIZE)
setupTestListen = """
STRING = \""""+obj+"""\"
import prata
m = prata.connect(\"127.0.0.1\",25565)
s = m.subscriber()
p = m.publisher()
s.connect(\"test\")
p.connect(\"test\")
"""
printStats(getStats(timeit.Timer(stmt=testListen,setup=setupTestListen).repeat(number=NUMBER,repeat=TIMES)),"Round Trip 1 KiloByte", sys.getsizeof(obj))
SIZE = (1*MB)
testListen='''
p.publish("test",STRING)
t = s.listen("test")
'''
obj = getString(SIZE)
setupTestListen = """
STRING = \""""+obj+"""\"
import prata
m = prata.connect(\"127.0.0.1\",25565)
s = m.subscriber()
p = m.publisher()
s.connect(\"test\")
p.connect(\"test\")
"""
printStats(getStats(timeit.Timer(stmt=testListen,setup=setupTestListen).repeat(number=NUMBER,repeat=TIMES)),"Round Trip 1 MegaByte", sys.getsizeof(obj))
SIZE = (35*MB)
testListen='''
p.publish("test",STRING)
t = s.listen("test")
'''
obj = getString(SIZE)
setupTestListen = """
STRING = \""""+obj+"""\"
import prata
m = prata.connect(\"127.0.0.1\",25565)
s = m.subscriber()
p = m.publisher()
s.connect(\"test\")
p.connect(\"test\")
"""
printStats(getStats(timeit.Timer(stmt=testListen,setup=setupTestListen).repeat(number=NUMBER,repeat=TIMES)),"Round Trip 35 MegaBytes", sys.getsizeof(obj))
def largegroup():
for i in range(1,10001):
SIZE = i*100
testListen='''
p.publish("test",STRING)
t = s.listen("test")
'''
obj = getString(SIZE)
setupTestListen = """
STRING = \""""+obj+"""\"
import prata
m = prata.connect(\"127.0.0.1\",25565)
s = m.subscriber()
p = m.publisher()
s.connect(\"test\")
p.connect(\"test\")
"""
printStats(getStats(timeit.Timer(stmt=testListen,setup=setupTestListen).repeat(number=1,repeat=2)),"Round Trip {} Bytes".format(SIZE), sys.getsizeof(obj),False)
time.sleep(.1)
def manyGroup():
for i in range(1,1001):
R = random.randint(1,10)
SIZE = i*100
testListen='''
for i in range('''+str(R)+'''):
p.publish("test",STRING)
for i in range('''+str(R)+'''):
t = s.listen("test")
'''
obj = getString(SIZE)
setupTestListen = """
STRING = \""""+obj+"""\"
import prata
m = prata.connect(\"127.0.0.1\",25565)
s = m.subscriber()
p = m.publisher()
s.connect(\"test\")
p.connect(\"test\")
"""
printStats(getStats(timeit.Timer(stmt=testListen,setup=setupTestListen).repeat(number=1,repeat=2)),"".format(SIZE), sys.getsizeof(obj),False)
END[-1].append(R)
time.sleep(.1)
manyGroup()
f = open("many.csv","w")
f.write("Bytes,Time(s),Iterations,Total Throughput, Singular Throughput\n")
for e in END:
f.write(str(e[0]))
f.write(", ")
f.write(str(e[1]))
f.write(", ")
f.write(str(e[2]))
f.write(", ")
f.write(str(e[0]/e[1]))
f.write(", ")
f.write(str((e[0]/e[1])*e[2]))
f.write("\n")
f.close()
m.terminate()
|
[
"numpy.average",
"random.randint",
"numpy.median",
"timeit.Timer",
"time.sleep",
"numpy.max",
"numpy.min",
"sys.getsizeof",
"prata.connect"
] |
[((1454, 1487), 'prata.connect', 'prata.connect', (['"""127.0.0.1"""', '(25565)'], {}), "('127.0.0.1', 25565)\n", (1467, 1487), False, 'import prata\n'), ((1955, 1973), 'sys.getsizeof', 'sys.getsizeof', (['obj'], {}), '(obj)\n', (1968, 1973), False, 'import sys\n'), ((2396, 2414), 'sys.getsizeof', 'sys.getsizeof', (['obj'], {}), '(obj)\n', (2409, 2414), False, 'import sys\n'), ((2837, 2855), 'sys.getsizeof', 'sys.getsizeof', (['obj'], {}), '(obj)\n', (2850, 2855), False, 'import sys\n'), ((3281, 3299), 'sys.getsizeof', 'sys.getsizeof', (['obj'], {}), '(obj)\n', (3294, 3299), False, 'import sys\n'), ((1336, 1349), 'numpy.min', 'np.min', (['times'], {}), '(times)\n', (1342, 1349), True, 'import numpy as np\n'), ((1351, 1367), 'numpy.median', 'np.median', (['times'], {}), '(times)\n', (1360, 1367), True, 'import numpy as np\n'), ((1369, 1382), 'numpy.max', 'np.max', (['times'], {}), '(times)\n', (1375, 1382), True, 'import numpy as np\n'), ((1384, 1401), 'numpy.average', 'np.average', (['times'], {}), '(times)\n', (1394, 1401), True, 'import numpy as np\n'), ((3865, 3880), 'time.sleep', 'time.sleep', (['(0.1)'], {}), '(0.1)\n', (3875, 3880), False, 'import time\n'), ((3948, 3969), 'random.randint', 'random.randint', (['(1)', '(10)'], {}), '(1, 10)\n', (3962, 3969), False, 'import random\n'), ((4593, 4608), 'time.sleep', 'time.sleep', (['(0.1)'], {}), '(0.1)\n', (4603, 4608), False, 'import time\n'), ((3831, 3849), 'sys.getsizeof', 'sys.getsizeof', (['obj'], {}), '(obj)\n', (3844, 3849), False, 'import sys\n'), ((4525, 4543), 'sys.getsizeof', 'sys.getsizeof', (['obj'], {}), '(obj)\n', (4538, 4543), False, 'import sys\n'), ((1843, 1895), 'timeit.Timer', 'timeit.Timer', ([], {'stmt': 'testListen', 'setup': 'setupTestListen'}), '(stmt=testListen, setup=setupTestListen)\n', (1855, 1895), False, 'import timeit\n'), ((2283, 2335), 'timeit.Timer', 'timeit.Timer', ([], {'stmt': 'testListen', 'setup': 'setupTestListen'}), '(stmt=testListen, setup=setupTestListen)\n', (2295, 2335), False, 'import timeit\n'), ((2724, 2776), 'timeit.Timer', 'timeit.Timer', ([], {'stmt': 'testListen', 'setup': 'setupTestListen'}), '(stmt=testListen, setup=setupTestListen)\n', (2736, 2776), False, 'import timeit\n'), ((3166, 3218), 'timeit.Timer', 'timeit.Timer', ([], {'stmt': 'testListen', 'setup': 'setupTestListen'}), '(stmt=testListen, setup=setupTestListen)\n', (3178, 3218), False, 'import timeit\n'), ((3716, 3768), 'timeit.Timer', 'timeit.Timer', ([], {'stmt': 'testListen', 'setup': 'setupTestListen'}), '(stmt=testListen, setup=setupTestListen)\n', (3728, 3768), False, 'import timeit\n'), ((4429, 4481), 'timeit.Timer', 'timeit.Timer', ([], {'stmt': 'testListen', 'setup': 'setupTestListen'}), '(stmt=testListen, setup=setupTestListen)\n', (4441, 4481), False, 'import timeit\n')]
|
import numpy as np
"""
these are altitudes hard-coded into the old version of NCAR GLOW.
"""
def glowalt() -> np.ndarray:
# z = range(80,110+1,1)
z = np.arange(30.0, 110 + 1.0, 1.0)
z = np.append(z, [111.5, 113.0, 114.5, 116.0])
z = np.append(z, np.arange(118, 150 + 2, 2.0))
z = np.append(z, np.arange(153, 168 + 3, 3.0))
z = np.append(z, np.arange(172, 180 + 4, 4.0))
z = np.append(z, np.arange(185, 205 + 5, 5))
z = np.append(z, np.arange(211, 223 + 6, 6))
z = np.append(z, np.arange(230, 244 + 7, 7))
z = np.append(z, np.arange(252, 300 + 8, 8))
z = np.append(z, np.arange(309, 345 + 9, 9))
z = np.append(z, np.arange(355, 395 + 10, 10))
z = np.append(z, np.arange(406, 428 + 11, 11))
z = np.append(z, [440.0, 453, 467, 482, 498, 515, 533, 551])
z = np.append(z, np.arange(570, 950 + 20, 20))
return z
|
[
"numpy.append",
"numpy.arange"
] |
[((161, 192), 'numpy.arange', 'np.arange', (['(30.0)', '(110 + 1.0)', '(1.0)'], {}), '(30.0, 110 + 1.0, 1.0)\n', (170, 192), True, 'import numpy as np\n'), ((201, 243), 'numpy.append', 'np.append', (['z', '[111.5, 113.0, 114.5, 116.0]'], {}), '(z, [111.5, 113.0, 114.5, 116.0])\n', (210, 243), True, 'import numpy as np\n'), ((752, 808), 'numpy.append', 'np.append', (['z', '[440.0, 453, 467, 482, 498, 515, 533, 551]'], {}), '(z, [440.0, 453, 467, 482, 498, 515, 533, 551])\n', (761, 808), True, 'import numpy as np\n'), ((265, 293), 'numpy.arange', 'np.arange', (['(118)', '(150 + 2)', '(2.0)'], {}), '(118, 150 + 2, 2.0)\n', (274, 293), True, 'import numpy as np\n'), ((316, 344), 'numpy.arange', 'np.arange', (['(153)', '(168 + 3)', '(3.0)'], {}), '(153, 168 + 3, 3.0)\n', (325, 344), True, 'import numpy as np\n'), ((367, 395), 'numpy.arange', 'np.arange', (['(172)', '(180 + 4)', '(4.0)'], {}), '(172, 180 + 4, 4.0)\n', (376, 395), True, 'import numpy as np\n'), ((418, 444), 'numpy.arange', 'np.arange', (['(185)', '(205 + 5)', '(5)'], {}), '(185, 205 + 5, 5)\n', (427, 444), True, 'import numpy as np\n'), ((467, 493), 'numpy.arange', 'np.arange', (['(211)', '(223 + 6)', '(6)'], {}), '(211, 223 + 6, 6)\n', (476, 493), True, 'import numpy as np\n'), ((516, 542), 'numpy.arange', 'np.arange', (['(230)', '(244 + 7)', '(7)'], {}), '(230, 244 + 7, 7)\n', (525, 542), True, 'import numpy as np\n'), ((565, 591), 'numpy.arange', 'np.arange', (['(252)', '(300 + 8)', '(8)'], {}), '(252, 300 + 8, 8)\n', (574, 591), True, 'import numpy as np\n'), ((614, 640), 'numpy.arange', 'np.arange', (['(309)', '(345 + 9)', '(9)'], {}), '(309, 345 + 9, 9)\n', (623, 640), True, 'import numpy as np\n'), ((663, 691), 'numpy.arange', 'np.arange', (['(355)', '(395 + 10)', '(10)'], {}), '(355, 395 + 10, 10)\n', (672, 691), True, 'import numpy as np\n'), ((714, 742), 'numpy.arange', 'np.arange', (['(406)', '(428 + 11)', '(11)'], {}), '(406, 428 + 11, 11)\n', (723, 742), True, 'import numpy as np\n'), ((830, 858), 'numpy.arange', 'np.arange', (['(570)', '(950 + 20)', '(20)'], {}), '(570, 950 + 20, 20)\n', (839, 858), True, 'import numpy as np\n')]
|
from typing import Union, Tuple
import multiaug
import numpy as np
import scipy.ndimage
from multiaug.augmenters import meta
def _generate_bool_sequence(num: int, random_state: int) -> list:
return [random_state.choice([True, False], 1)[0] for _ in range(num)]
def _merge_bool_sequences(proposed: list, mask: list) -> list:
return [x and y for x, y in zip(proposed, mask)]
def _validate_angle(angle: Union[int, float]):
assert (angle >= 0 and angle <= 360), "Angle not within valid range [0, 360], received {}".format(angle)
class Rotate3d(meta.Augmenter):
'''
Apply random rotation to 3D images.
Parameters
----------
angle : int or float or list
The maximum angle by which to rotate the image.
* If 'int' or 'float' then use the angle specified for all axes.
* If 'list' then must be of format [angle_x, angle_y, angle_z].
axes : list
Flags for the x, y, z axes that determine which axes the image can be rotated about.
* If 'True' then axis can be rotated about
* If 'False' then axis cannot be rotated about
interpolation : str
Interpolation method to use.
* If 'nearest' then use nearest interpolation.
'''
def __init__(self, angle: Union[int, float, list], axes: Tuple[bool, bool, bool] = [True, True, True], interpolation: str = 'nearest'):
super(Rotate3d, self).__init__()
if isinstance(angle, list):
assert len(angle) == 3, "Please specify rotation angle for x, y and z dimensions, only {} angles provided".format(len(angle))
self.x_max, self.y_max, self.z_max = angle
elif isinstance(angle, float) or isinstance(angle, int):
self.x_max = self.y_max = self.z_max = angle
else:
raise NotImplementedError("Angle must either be a list of length 3 or a single number, not {}".format(angle))
_validate_angle(self.x_max)
_validate_angle(self.y_max)
_validate_angle(self.z_max)
self.interpolation = interpolation
self.active_axes = axes
if sum(self.active_axes) == 0:
raise RuntimeError("All axes have been deactivated, please activate atleast one axes for augmentation to take place")
def apply(self, images: np.ndarray, row_ids: list) -> np.ndarray:
'''
Apply transformations to an entire batch.
Parameters
----------
images : np.ndarray
Image batch of shape N x H x W x D.
row_ids : list
Indices of rows to rotate.
Returns
-------
np.ndarray
Batch of rotated images.
'''
rotated_images = []
for image in images[row_ids]:
rotated_images.append(self.apply_to_sample(image))
return np.array(rotated_images)
def apply_to_sample(self, image: np.ndarray) -> np.ndarray:
'''
Apply transformation to a single image. Randomly samples one or more active axes and applies
a random rotation about that axes.
Parameters
----------
image : np.ndarray
Image to transform.
Returns
-------
np.ndarray
Rotated image.
'''
which_axes = _generate_bool_sequence(3, self.random_state)
which_axes = _merge_bool_sequences(which_axes, self.active_axes)
while sum(which_axes) == 0: # at least rotate around one axes
which_axes = _generate_bool_sequence(3, self.random_state)
which_axes = _merge_bool_sequences(which_axes, self.active_axes)
img = image.copy()
# z-axis
if which_axes[2]:
angle = self.random_state.uniform(-self.z_max, self.z_max)
img = scipy.ndimage.interpolation.rotate(img, angle, mode=self.interpolation, axes=(0, 1), reshape=False)
# y-axis
if which_axes[1]:
angle = self.random_state.uniform(-self.y_max, self.y_max)
img = scipy.ndimage.interpolation.rotate(img, angle, mode=self.interpolation, axes=(0, 2), reshape=False)
# x-axis
if which_axes[0]:
angle = self.random_state.uniform(-self.x_max, self.x_max)
img = scipy.ndimage.interpolation.rotate(img, angle, mode=self.interpolation, axes=(1, 2), reshape=False)
return img
|
[
"numpy.array"
] |
[((2833, 2857), 'numpy.array', 'np.array', (['rotated_images'], {}), '(rotated_images)\n', (2841, 2857), True, 'import numpy as np\n')]
|
"""Took all this from https://github.com/MadryLab/implementation-matters"""
import gym
import numpy as np
class RunningStat:
def __init__(self):
self.n = 0
self.m = 0
self.s = 0
def add(self, v):
self.n += 1
if self.n == 1:
self.m = v
else:
old_m = self.m
self.m = self.m + (v - self.m) / self.n
self.s = self.s + (v - old_m) * (v - self.m)
@property
def mean(self):
return self.m
@property
def var(self):
return self.s / (self.n - 1) if self.n > 1 else self.m**2
@property
def std(self):
return np.sqrt(self.var)
def __repr__(self):
return f"Running stat with count: {self.n}, mean: {self.mean:.4f}, variance: {self.var:.4f}"
class DiscountedReturnStdEstimator:
def __init__(self, discount):
self.discount = discount
self.reset()
def __call__(self, x):
self.ret = self.ret * self.discount + x
self.rs.add(self.ret)
return self.rs.std
def reset(self):
self.rs = RunningStat()
self.ret = 0
class RewardNormalizationWrapper(gym.Wrapper):
def __init__(self, env, discount):
super().__init__(env)
self.estimator = DiscountedReturnStdEstimator(discount)
def step(self, action):
obs, rew, done, info = self.env.step(action)
info["rew_norm_g"] = self.estimator(rew)
return obs, rew, done, info
def reset(self):
self.estimator.reset()
return self.env.reset()
|
[
"numpy.sqrt"
] |
[((655, 672), 'numpy.sqrt', 'np.sqrt', (['self.var'], {}), '(self.var)\n', (662, 672), True, 'import numpy as np\n')]
|
import os
import random
import numpy as np
import torch
from torch import nn
import torch.nn.functional as F
import torchvision.transforms as T
import torchvision
from torchvision import datasets, transforms
# from stylegan_model import Generator, Encoder
# from view_generator import VGGLoss
from functools import partial
import matplotlib.pyplot as plt
from pathlib import Path
import argparse
import pickle
from utils import toggle_grad, image2tensor, tensor2image, imshow, imsave, Config, fix_seed
from einops import rearrange
import pdb
st = pdb.set_trace
class ResNetWrapper(nn.Module):
def __init__(
self,
model,
):
super().__init__()
self.model = model
def forward(self, x):
x = self.model.conv1(x)
x = self.model.bn1(x)
x = self.model.relu(x)
x = self.model.maxpool(x)
x = self.model.layer1(x)
x = self.model.layer2(x)
x = self.model.layer3(x)
x = self.model.layer4(x)
x = self.model.avgpool(x)
return x
class SimCLRWrapper(nn.Module):
def __init__(
self,
model,
):
super().__init__()
self.model = model
def forward(self, x):
r = self.model.backbone(x)
z = self.model.projector(r)
return z
def encode(vqgan, x):
h = vqgan.encoder(x)
z = vqgan.quant_conv(h)
z_q, _, [_, _, indices] = vqgan.quantize(z)
return z_q, z, indices
def decode(vqgan, z_q):
quant = vqgan.post_quant_conv(z_q)
x = vqgan.decoder(quant)
return x
def decode_z(vqgan, z):
z_q, _, info = vqgan.quantize(z)
quant = vqgan.post_quant_conv(z_q)
x = vqgan.decoder(quant)
return x
def decode_fn(vqgan, z, indices=None):
z_q, loss, [_, _, inds] = vqgan.quantize(z)
zq = vqgan.quantize.embedding(inds)
zq = rearrange(zq, '(b h w) c -> b c h w', b = z_q.shape[0], h=z_q.shape[2], w=z_q.shape[3])
quant = vqgan.post_quant_conv(zq)
x = vqgan.decoder(quant)
return x
# def decode_fn(vqgan, z_q, indices=None):
# quant = vqgan.post_quant_conv(z_q)
# x = vqgan.decoder(quant)
# return x
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--seed', type=int, default=0)
parser.add_argument('--batch_size', type=int, default=4)
parser.add_argument('--image_size', type=int, default=256)
parser.add_argument('--iters', type=int, default=4000)
parser.add_argument('--lr', type=float, default=0.01)
parser.add_argument('--optimizer', type=str, default='adam', choices=['adam', 'sgd', 'lbfgs'])
parser.add_argument('--beta1', type=float, default=0.5)
parser.add_argument('--beta2', type=float, default=0.999)
parser.add_argument('--log_root', type=str, default='logs_gen')
parser.add_argument('--name', type=str, default='test')
parser.add_argument('--data_root', type=str, default='../data')
parser.add_argument('--load_model', type=str, default='simclr')
parser.add_argument('--eps1', type=float, default=0.5)
parser.add_argument('--eps2', type=float, default=1)
parser.add_argument('--init_noise_scale', type=float, default=0.001)
parser.add_argument('--p', type=int, default=2)
parser.add_argument('--n', type=int, default=1)
parser.add_argument('--save_every', type=int, default=100)
parser.add_argument('--lam2', type=float, default=0, help='weight of distance regularization')
parser.add_argument('--no_proj', action='store_true')
parser.add_argument('--objective', type=str, default='norm', choices=['norm', 'cosine'])
parser.add_argument('--loss_type', type=str, default='l2', choices=['l2', 'l1', 'hinge'])
parser.add_argument('--method', type=str, default='gd', choices=['gd', 'fgsm', 'vat'])
parser.add_argument('--eval', action='store_true')
parser.add_argument('--clamp', action='store_true')
parser.add_argument('--which_decode', type=str, default='from_z', choices=['from_z', 'from_zq'])
parser.add_argument('--optimize_dict', action='store_true')
args = parser.parse_args()
fix_seed(args.seed)
name = args.name
log_root = Path(args.log_root)
log_dir = log_root / name
os.makedirs(log_dir, exist_ok=True)
USE_HTML = True
log_web_dir = log_dir / 'web'
webpage = None
if USE_HTML:
import utils_html
webpage = utils_html.initialize_webpage(log_web_dir, 'ViewMaker: ' + args.name + f'{args.which_decode}', resume=False)
device = 'cuda'
image_size = args.image_size
tol = 1e-5
image_size = 256
args.clamp = True
vqgan_config_path = '/research/cbim/medical/lh599/code/DALLE/pretrained/vqgan.1024.config.yml'
vqgan_model_path = '/research/cbim/medical/lh599/code/DALLE/pretrained/vqgan.1024.model.ckpt'
from taming.models.vqgan import VQModel
from omegaconf import OmegaConf
config = OmegaConf.load(vqgan_config_path)
config.model.params['ddconfig']['resolution'] = image_size
vqgan = VQModel(**config.model.params)
state = torch.load(vqgan_model_path, map_location='cpu')['state_dict']
vqgan.load_state_dict(state, strict=True) # NOTE: set False if resoluton is changed
# Define SimCLR encoder
if args.no_proj:
exit(0)
if args.objective == 'norm':
normalize = lambda x: x
elif args.objective == 'cosine':
normalize = partial(F.normalize, dim=1)
prefix = 'noproj'
from resnet import resnet18
model = resnet18(pretrained=False, num_classes=10)
checkpoint = torch.load('../pretrained/simclr-cifar10-resnet18-800ep-1.pth')
state_dict = checkpoint['state_dict']
for k in list(state_dict.keys()):
if k.startswith('encoder.'):
if k.startswith('encoder') and not k.startswith('encoder.fc'):
# remove prefix
state_dict[k[len("encoder."):]] = state_dict[k]
del state_dict[k]
log = model.load_state_dict(state_dict, strict=True)
# assert log.missing_keys == ['fc.weight', 'fc.bias']
# model = ResNetWrapper(model).to(device)
model.to(device)
else:
# from simclr.main import SimCLR
from models import SimCLR
normalize = partial(F.normalize, dim=1)
prefix = 'proj'
args_simclr = Config(rotation=0)
model = SimCLR(args_simclr).to(device)
saved_dict = torch.load('../pretrained/simclr-imagenet-resnet50-300ep.pth')
model.backbone.load_state_dict(saved_dict['backbone'])
model.projector.load_state_dict(saved_dict['projector'])
# model.load_state_dict(saved_dict['model'], strict=True)
model = SimCLRWrapper(model)
model.eval()
batch_size = args.batch_size
transform = transforms.Compose([
transforms.CenterCrop(image_size),
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
])
image_cache = 'I256_256.pkl'
if not os.path.exists(image_cache):
# dataset = torchvision.datasets.ImageFolder(root='/research/cbim/medical/lh599/data/ILSVRC2012/train', transform=transform)
dataset = torchvision.datasets.ImageFolder(root='/research/cbim/medical/lh599/data/ImageNet100/train', transform=transform)
loader = iter(torch.utils.data.DataLoader(dataset=dataset, batch_size=256, shuffle=True))
imgs, _ = next(loader)
with open(image_cache, 'wb') as f:
pickle.dump(imgs, f)
else:
with open(image_cache, 'rb') as f:
imgs = pickle.load(f)
imgs = imgs[:batch_size].to(device)
vqgan = vqgan.to(device)
with torch.no_grad():
z0_q, z0, ind0 = encode(vqgan, imgs)
imgs_gen = decode(vqgan, z0_q)
# NOTE: z and z_q are of shape [b, 256, 16, 16]
imgs_real = torch.cat([img for img in imgs], dim=1)
imgs_fakes = torch.cat([img_gen for img_gen in imgs_gen], dim=1)
imsave(log_dir / f'rec.png', tensor2image(torch.cat([imgs_real, imgs_fakes], dim=2)))
# input transform
encoder_input_transform = T.Compose(
[
T.Resize(224), # TODO: is this backpropable? -> yes
T.Normalize([-1, -1, -1], [2, 2, 2]), # to [0, 1]
T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
]
)
eps1 = args.eps1
eps2 = args.eps2
p = args.p
n = args.n
# z = z0_q.detach().clone()
z = z0_q
z = z.repeat_interleave(n, dim=0)
z_noise = args.init_noise_scale * torch.randn_like(z) # [b*n, L, D]
z_noise[::n, ...] = 0 # make sure the first one is accurate
z = z + z_noise
imgs_rep = imgs.repeat_interleave(n, dim=0)
# decode_fn = decode_z # TODO: test out different decode
# if args.which_decode == 'from_z':
# decode_fn = decode_z
# elif args.which_decode == 'from_zq':
# decode_fn = decode
imgs_rec = imgs_gen.detach()
if args.clamp:
imgs_rec = torch.clamp(imgs_rec, -1, 1)
imgs_recon = imgs_fakes
imgs_blank = torch.ones_like(imgs_recon)[:,:,:8]
# z.requires_grad = True
if args.optimizer == 'adam':
optimizer = torch.optim.Adam(vqgan.quantize.embedding.parameters(), lr=args.lr)
elif args.optimizer == 'sgd':
optimizer = torch.optim.SGD([z], lr=args.lr)
elif args.optimizer == 'lbfgs':
optimizer = torch.optim.LBFGS([z], max_iter=500) # TODO: max_iter
toggle_grad(model, False)
# toggle_grad(vqgan, False)
h_img = model(encoder_input_transform(imgs_rec).repeat_interleave(n, dim=0)) # start from the reconstructed images
h_img = normalize(h_img.squeeze()).detach()
losses = []
print('generating views...')
done = False
for step in range(args.iters):
imgs_gen = decode_fn(vqgan, z, ind0)
if args.clamp:
imgs_gen = torch.clamp(imgs_gen, -1, 1)
h_gen = model(encoder_input_transform(imgs_gen))
h_gen = normalize(h_gen.squeeze())
pdist = torch.cdist(h_gen.view(batch_size, n, -1), h_gen.view(batch_size, n, -1), p=p)
pdist = pdist * n / (n-1)
loss_reg = torch.mean(F.relu(eps2 - torch.mean(pdist.view(batch_size*n, n), dim=1)))
if args.loss_type == 'l2':
if args.objective == 'norm':
diff = torch.norm(h_gen - h_img, dim=1, p=p) - eps1
elif args.objective == 'cosine':
diff = torch.sum(h_gen * h_img, dim=1) - eps1
loss = torch.mean(diff ** 2) + args.lam2 * loss_reg
elif args.loss_type == 'hinge':
if args.objective == 'norm':
diff = F.relu(eps1 - torch.norm(h_gen - h_img, dim=1, p=p))
elif args.objective == 'cosine':
diff = F.relu(torch.sum(h_gen * h_img, dim=1) - eps1)
loss = torch.mean(diff) + args.lam2 * loss_reg
if args.method == 'gd':
if loss.item() > tol:
optimizer.zero_grad()
loss.backward()
optimizer.step()
else:
done = True
elif args.method == 'fgsm':
optimizer.zero_grad()
loss.backward()
z_delta = z.grad.data.sign()
z = z - args.lr * z_delta
done = True
if args.objective == 'norm':
losses.append(torch.norm(h_gen - h_img, dim=1, p=p).mean().item())
elif args.objective == 'cosine':
losses.append(torch.sum(h_gen * h_img, dim=1).mean().item())
if done or step == 0 or step == args.iters - 1 or (step + 1) % args.save_every == 0:
imgs_gen = decode_fn(vqgan, z)
if args.clamp:
imgs_gen = torch.clamp(imgs_gen, -1, 1)
h_gen = model(encoder_input_transform(imgs_gen))
h_gen = normalize(h_gen.squeeze())
if args.objective == 'norm':
print(f'step: {step+1}, loss: {loss.item()}, norm: {torch.norm(h_gen - h_img, dim=1, p=p).mean().item()}, pdist: {pdist.mean().item()}')
elif args.objective == 'cosine':
print(f'step: {step+1}, loss: {loss.item()}, cos: {torch.sum(h_gen * h_img, dim=1).mean().item()}, pdist: {pdist.mean().item()}')
# st()
# imsave(log_dir / 'debug_clamp.png', tensor2image(torch.cat([xx for xx in torch.clamp(imgs_gen[32:40,...], -1, 1)], dim=2)))
imgs_gen = imgs_gen.view(batch_size, n, 3, image_size, image_size)
imgs_fakes = []
imgs_diffs = []
for j in range(n):
imgs_fakes.append(torch.cat([img_gen for img_gen in imgs_gen[:,j,...]], dim=1))
img_diff = torch.cat([img_gen for img_gen in imgs_gen[:,j,...] - imgs_rec], dim=1)
imgs_diffs.append((img_diff - img_diff.min()) / (img_diff.max() - img_diff.min()) * 2 - 1)
imsave(log_dir / f'view_{step+1:04d}.png', tensor2image(torch.cat([imgs_real, imgs_recon, imgs_blank] + imgs_fakes, dim=2)))
imsave(log_dir / f'diff_{step+1:04d}.png', tensor2image(torch.cat([imgs_real, imgs_recon, imgs_blank] + imgs_diffs, dim=2)))
image_tensor = torch.cat([imgs_real, imgs_recon, imgs_blank] + imgs_fakes, dim=2)
if USE_HTML:
if args.objective == 'norm':
header = f'step: {step+1}, loss: {loss.item()}, norm: {torch.norm(h_gen - h_img, dim=1, p=p).mean().item()}, pdist: {pdist.mean().item()}'
elif args.objective == 'cosine':
header = f'step: {step+1}, loss: {loss.item()}, cos: {torch.sum(h_gen * h_img, dim=1).mean().item()}, pdist: {pdist.mean().item()}'
webpage.add_header(header)
utils_html.save_grid(
webpage=webpage,
tensor=[(image_tensor + 1) / 2],
caption=[f'real recon | views x {n}'],
name=f'{step+1:04d}',
nrow=[1],
width=768,
)
if done:
print(f"loss is {loss.item()}!")
if args.objective == 'norm':
print(torch.norm(h_gen - h_img, dim=1, p=p).mean().item(), pdist.mean().item())
elif args.objective == 'cosine':
print(torch.sum(h_gen * h_img, dim=1).mean().item(), pdist.mean().item())
break
losses = np.array(losses)
plt.plot(losses)
plt.xlabel('steps')
if args.objective == 'norm':
plt.ylabel(f'L{p}')
elif args.objective == 'cosine':
plt.ylabel(f'cos')
plt.savefig(log_dir / f'loss_plot.png')
|
[
"pickle.dump",
"argparse.ArgumentParser",
"torch.cat",
"pathlib.Path",
"pickle.load",
"torchvision.transforms.Normalize",
"torch.no_grad",
"torch.utils.data.DataLoader",
"utils_html.save_grid",
"torch.load",
"os.path.exists",
"resnet.resnet18",
"torchvision.transforms.CenterCrop",
"utils.fix_seed",
"torch.mean",
"functools.partial",
"utils.Config",
"torch.randn_like",
"torch.optim.SGD",
"torch.norm",
"torchvision.datasets.ImageFolder",
"torch.clamp",
"einops.rearrange",
"matplotlib.pyplot.ylabel",
"torch.sum",
"utils_html.initialize_webpage",
"taming.models.vqgan.VQModel",
"torchvision.transforms.Resize",
"torch.ones_like",
"models.SimCLR",
"os.makedirs",
"matplotlib.pyplot.plot",
"omegaconf.OmegaConf.load",
"numpy.array",
"utils.toggle_grad",
"matplotlib.pyplot.xlabel",
"torch.optim.LBFGS",
"matplotlib.pyplot.savefig",
"torchvision.transforms.ToTensor"
] |
[((1837, 1927), 'einops.rearrange', 'rearrange', (['zq', '"""(b h w) c -> b c h w"""'], {'b': 'z_q.shape[0]', 'h': 'z_q.shape[2]', 'w': 'z_q.shape[3]'}), "(zq, '(b h w) c -> b c h w', b=z_q.shape[0], h=z_q.shape[2], w=z_q\n .shape[3])\n", (1846, 1927), False, 'from einops import rearrange\n'), ((2176, 2201), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (2199, 2201), False, 'import argparse\n'), ((4087, 4106), 'utils.fix_seed', 'fix_seed', (['args.seed'], {}), '(args.seed)\n', (4095, 4106), False, 'from utils import toggle_grad, image2tensor, tensor2image, imshow, imsave, Config, fix_seed\n'), ((4144, 4163), 'pathlib.Path', 'Path', (['args.log_root'], {}), '(args.log_root)\n', (4148, 4163), False, 'from pathlib import Path\n'), ((4198, 4233), 'os.makedirs', 'os.makedirs', (['log_dir'], {'exist_ok': '(True)'}), '(log_dir, exist_ok=True)\n', (4209, 4233), False, 'import os\n'), ((4886, 4919), 'omegaconf.OmegaConf.load', 'OmegaConf.load', (['vqgan_config_path'], {}), '(vqgan_config_path)\n', (4900, 4919), False, 'from omegaconf import OmegaConf\n'), ((4995, 5025), 'taming.models.vqgan.VQModel', 'VQModel', ([], {}), '(**config.model.params)\n', (5002, 5025), False, 'from taming.models.vqgan import VQModel\n'), ((7848, 7887), 'torch.cat', 'torch.cat', (['[img for img in imgs]'], {'dim': '(1)'}), '([img for img in imgs], dim=1)\n', (7857, 7887), False, 'import torch\n'), ((7905, 7956), 'torch.cat', 'torch.cat', (['[img_gen for img_gen in imgs_gen]'], {'dim': '(1)'}), '([img_gen for img_gen in imgs_gen], dim=1)\n', (7914, 7956), False, 'import torch\n'), ((9452, 9477), 'utils.toggle_grad', 'toggle_grad', (['model', '(False)'], {}), '(model, False)\n', (9463, 9477), False, 'from utils import toggle_grad, image2tensor, tensor2image, imshow, imsave, Config, fix_seed\n'), ((14391, 14407), 'numpy.array', 'np.array', (['losses'], {}), '(losses)\n', (14399, 14407), True, 'import numpy as np\n'), ((14413, 14429), 'matplotlib.pyplot.plot', 'plt.plot', (['losses'], {}), '(losses)\n', (14421, 14429), True, 'import matplotlib.pyplot as plt\n'), ((14434, 14453), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""steps"""'], {}), "('steps')\n", (14444, 14453), True, 'import matplotlib.pyplot as plt\n'), ((14583, 14622), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(log_dir / f'loss_plot.png')"], {}), "(log_dir / f'loss_plot.png')\n", (14594, 14622), True, 'import matplotlib.pyplot as plt\n'), ((4369, 4481), 'utils_html.initialize_webpage', 'utils_html.initialize_webpage', (['log_web_dir', "('ViewMaker: ' + args.name + f'{args.which_decode}')"], {'resume': '(False)'}), "(log_web_dir, 'ViewMaker: ' + args.name +\n f'{args.which_decode}', resume=False)\n", (4398, 4481), False, 'import utils_html\n'), ((5038, 5086), 'torch.load', 'torch.load', (['vqgan_model_path'], {'map_location': '"""cpu"""'}), "(vqgan_model_path, map_location='cpu')\n", (5048, 5086), False, 'import torch\n'), ((5500, 5542), 'resnet.resnet18', 'resnet18', ([], {'pretrained': '(False)', 'num_classes': '(10)'}), '(pretrained=False, num_classes=10)\n', (5508, 5542), False, 'from resnet import resnet18\n'), ((5564, 5627), 'torch.load', 'torch.load', (['"""../pretrained/simclr-cifar10-resnet18-800ep-1.pth"""'], {}), "('../pretrained/simclr-cifar10-resnet18-800ep-1.pth')\n", (5574, 5627), False, 'import torch\n'), ((6273, 6300), 'functools.partial', 'partial', (['F.normalize'], {'dim': '(1)'}), '(F.normalize, dim=1)\n', (6280, 6300), False, 'from functools import partial\n'), ((6347, 6365), 'utils.Config', 'Config', ([], {'rotation': '(0)'}), '(rotation=0)\n', (6353, 6365), False, 'from utils import toggle_grad, image2tensor, tensor2image, imshow, imsave, Config, fix_seed\n'), ((6434, 6496), 'torch.load', 'torch.load', (['"""../pretrained/simclr-imagenet-resnet50-300ep.pth"""'], {}), "('../pretrained/simclr-imagenet-resnet50-300ep.pth')\n", (6444, 6496), False, 'import torch\n'), ((7013, 7040), 'os.path.exists', 'os.path.exists', (['image_cache'], {}), '(image_cache)\n', (7027, 7040), False, 'import os\n'), ((7193, 7311), 'torchvision.datasets.ImageFolder', 'torchvision.datasets.ImageFolder', ([], {'root': '"""/research/cbim/medical/lh599/data/ImageNet100/train"""', 'transform': 'transform'}), "(root=\n '/research/cbim/medical/lh599/data/ImageNet100/train', transform=transform)\n", (7225, 7311), False, 'import torchvision\n'), ((7678, 7693), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (7691, 7693), False, 'import torch\n'), ((8541, 8560), 'torch.randn_like', 'torch.randn_like', (['z'], {}), '(z)\n', (8557, 8560), False, 'import torch\n'), ((8988, 9016), 'torch.clamp', 'torch.clamp', (['imgs_rec', '(-1)', '(1)'], {}), '(imgs_rec, -1, 1)\n', (8999, 9016), False, 'import torch\n'), ((9062, 9089), 'torch.ones_like', 'torch.ones_like', (['imgs_recon'], {}), '(imgs_recon)\n', (9077, 9089), False, 'import torch\n'), ((14495, 14514), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['f"""L{p}"""'], {}), "(f'L{p}')\n", (14505, 14514), True, 'import matplotlib.pyplot as plt\n'), ((6831, 6864), 'torchvision.transforms.CenterCrop', 'transforms.CenterCrop', (['image_size'], {}), '(image_size)\n', (6852, 6864), False, 'from torchvision import datasets, transforms\n'), ((6874, 6895), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (6893, 6895), False, 'from torchvision import datasets, transforms\n'), ((6905, 6959), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['(0.5, 0.5, 0.5)', '(0.5, 0.5, 0.5)'], {}), '((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))\n', (6925, 6959), False, 'from torchvision import datasets, transforms\n'), ((7329, 7403), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', ([], {'dataset': 'dataset', 'batch_size': '(256)', 'shuffle': '(True)'}), '(dataset=dataset, batch_size=256, shuffle=True)\n', (7356, 7403), False, 'import torch\n'), ((7491, 7511), 'pickle.dump', 'pickle.dump', (['imgs', 'f'], {}), '(imgs, f)\n', (7502, 7511), False, 'import pickle\n'), ((7584, 7598), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (7595, 7598), False, 'import pickle\n'), ((8003, 8044), 'torch.cat', 'torch.cat', (['[imgs_real, imgs_fakes]'], {'dim': '(2)'}), '([imgs_real, imgs_fakes], dim=2)\n', (8012, 8044), False, 'import torch\n'), ((8133, 8146), 'torchvision.transforms.Resize', 'T.Resize', (['(224)'], {}), '(224)\n', (8141, 8146), True, 'import torchvision.transforms as T\n'), ((8198, 8234), 'torchvision.transforms.Normalize', 'T.Normalize', (['[-1, -1, -1]', '[2, 2, 2]'], {}), '([-1, -1, -1], [2, 2, 2])\n', (8209, 8234), True, 'import torchvision.transforms as T\n'), ((8261, 8327), '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', (8272, 8327), True, 'import torchvision.transforms as T\n'), ((9303, 9335), 'torch.optim.SGD', 'torch.optim.SGD', (['[z]'], {'lr': 'args.lr'}), '([z], lr=args.lr)\n', (9318, 9335), False, 'import torch\n'), ((9872, 9900), 'torch.clamp', 'torch.clamp', (['imgs_gen', '(-1)', '(1)'], {}), '(imgs_gen, -1, 1)\n', (9883, 9900), False, 'import torch\n'), ((13168, 13234), 'torch.cat', 'torch.cat', (['([imgs_real, imgs_recon, imgs_blank] + imgs_fakes)'], {'dim': '(2)'}), '([imgs_real, imgs_recon, imgs_blank] + imgs_fakes, dim=2)\n', (13177, 13234), False, 'import torch\n'), ((14560, 14578), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['f"""cos"""'], {}), "(f'cos')\n", (14570, 14578), True, 'import matplotlib.pyplot as plt\n'), ((5394, 5421), 'functools.partial', 'partial', (['F.normalize'], {'dim': '(1)'}), '(F.normalize, dim=1)\n', (5401, 5421), False, 'from functools import partial\n'), ((6382, 6401), 'models.SimCLR', 'SimCLR', (['args_simclr'], {}), '(args_simclr)\n', (6388, 6401), False, 'from models import SimCLR\n'), ((9392, 9428), 'torch.optim.LBFGS', 'torch.optim.LBFGS', (['[z]'], {'max_iter': '(500)'}), '([z], max_iter=500)\n', (9409, 9428), False, 'import torch\n'), ((10495, 10516), 'torch.mean', 'torch.mean', (['(diff ** 2)'], {}), '(diff ** 2)\n', (10505, 10516), False, 'import torch\n'), ((11718, 11746), 'torch.clamp', 'torch.clamp', (['imgs_gen', '(-1)', '(1)'], {}), '(imgs_gen, -1, 1)\n', (11729, 11746), False, 'import torch\n'), ((12688, 12761), 'torch.cat', 'torch.cat', (['[img_gen for img_gen in imgs_gen[:, j, ...] - imgs_rec]'], {'dim': '(1)'}), '([img_gen for img_gen in imgs_gen[:, j, ...] - imgs_rec], dim=1)\n', (12697, 12761), False, 'import torch\n'), ((13724, 13886), 'utils_html.save_grid', 'utils_html.save_grid', ([], {'webpage': 'webpage', 'tensor': '[(image_tensor + 1) / 2]', 'caption': "[f'real recon | views x {n}']", 'name': 'f"""{step + 1:04d}"""', 'nrow': '[1]', 'width': '(768)'}), "(webpage=webpage, tensor=[(image_tensor + 1) / 2],\n caption=[f'real recon | views x {n}'], name=f'{step + 1:04d}', nrow=[1],\n width=768)\n", (13744, 13886), False, 'import utils_html\n'), ((10324, 10361), 'torch.norm', 'torch.norm', (['(h_gen - h_img)'], {'dim': '(1)', 'p': 'p'}), '(h_gen - h_img, dim=1, p=p)\n', (10334, 10361), False, 'import torch\n'), ((10831, 10847), 'torch.mean', 'torch.mean', (['diff'], {}), '(diff)\n', (10841, 10847), False, 'import torch\n'), ((12599, 12661), 'torch.cat', 'torch.cat', (['[img_gen for img_gen in imgs_gen[:, j, ...]]'], {'dim': '(1)'}), '([img_gen for img_gen in imgs_gen[:, j, ...]], dim=1)\n', (12608, 12661), False, 'import torch\n'), ((12935, 13001), 'torch.cat', 'torch.cat', (['([imgs_real, imgs_recon, imgs_blank] + imgs_fakes)'], {'dim': '(2)'}), '([imgs_real, imgs_recon, imgs_blank] + imgs_fakes, dim=2)\n', (12944, 13001), False, 'import torch\n'), ((13072, 13138), 'torch.cat', 'torch.cat', (['([imgs_real, imgs_recon, imgs_blank] + imgs_diffs)'], {'dim': '(2)'}), '([imgs_real, imgs_recon, imgs_blank] + imgs_diffs, dim=2)\n', (13081, 13138), False, 'import torch\n'), ((10437, 10468), 'torch.sum', 'torch.sum', (['(h_gen * h_img)'], {'dim': '(1)'}), '(h_gen * h_img, dim=1)\n', (10446, 10468), False, 'import torch\n'), ((10658, 10695), 'torch.norm', 'torch.norm', (['(h_gen - h_img)'], {'dim': '(1)', 'p': 'p'}), '(h_gen - h_img, dim=1, p=p)\n', (10668, 10695), False, 'import torch\n'), ((10772, 10803), 'torch.sum', 'torch.sum', (['(h_gen * h_img)'], {'dim': '(1)'}), '(h_gen * h_img, dim=1)\n', (10781, 10803), False, 'import torch\n'), ((11360, 11397), 'torch.norm', 'torch.norm', (['(h_gen - h_img)'], {'dim': '(1)', 'p': 'p'}), '(h_gen - h_img, dim=1, p=p)\n', (11370, 11397), False, 'import torch\n'), ((11480, 11511), 'torch.sum', 'torch.sum', (['(h_gen * h_img)'], {'dim': '(1)'}), '(h_gen * h_img, dim=1)\n', (11489, 11511), False, 'import torch\n'), ((14150, 14187), 'torch.norm', 'torch.norm', (['(h_gen - h_img)'], {'dim': '(1)', 'p': 'p'}), '(h_gen - h_img, dim=1, p=p)\n', (14160, 14187), False, 'import torch\n'), ((14291, 14322), 'torch.sum', 'torch.sum', (['(h_gen * h_img)'], {'dim': '(1)'}), '(h_gen * h_img, dim=1)\n', (14300, 14322), False, 'import torch\n'), ((11965, 12002), 'torch.norm', 'torch.norm', (['(h_gen - h_img)'], {'dim': '(1)', 'p': 'p'}), '(h_gen - h_img, dim=1, p=p)\n', (11975, 12002), False, 'import torch\n'), ((13380, 13417), 'torch.norm', 'torch.norm', (['(h_gen - h_img)'], {'dim': '(1)', 'p': 'p'}), '(h_gen - h_img, dim=1, p=p)\n', (13390, 13417), False, 'import torch\n'), ((12162, 12193), 'torch.sum', 'torch.sum', (['(h_gen * h_img)'], {'dim': '(1)'}), '(h_gen * h_img, dim=1)\n', (12171, 12193), False, 'import torch\n'), ((13587, 13618), 'torch.sum', 'torch.sum', (['(h_gen * h_img)'], {'dim': '(1)'}), '(h_gen * h_img, dim=1)\n', (13596, 13618), False, 'import torch\n')]
|
import os.path as osp
import logging
import time
import argparse
from collections import OrderedDict
import torch
import numpy as np
import options.options as option
import utils.util as util
from data.util import bgr2ycbcr
from data import create_dataset, create_dataloader
from models import create_model
import matplotlib.pyplot as plot
from torchvision import utils as utils
import cv2
import os
def rgb2gray(rgb):
return np.dot(rgb[..., :3], [0.299, 0.587, 0.114]) # 分别对应通道 R G B
def displayFeature(feature, savepath, image, image_name):
# plot.axis('off')
feat_permute = feature.permute(1, 0, 2, 3).cpu()
if not os.path.exists(savepath+'/'+str(image_name)):
os.mkdir(savepath+'/'+str(image_name))
for i in range(64):
# grid = utils.make_grid(feat_permute.cpu(), nrow=16, normalize=True, padding=10)
grid = feat_permute[i, :, :, :]
grid = grid.numpy().transpose((1, 2, 0))[:, :, 0]
# display_grid = np.zeros(grid.shape)
display_grid = (grid - np.min(grid)) / (np.max(grid) - np.min(grid))*255
display_grid = display_grid.astype(np.uint8)
# cv2.normalize(grid, display_grid, 0, 255, cv2.NORM_MINMAX)
# display_grid = ((grid[:, :, 0] + 1)/2)*255
heatmap = cv2.applyColorMap(display_grid, cv2.COLORMAP_JET)
# heatmap = cv2.applyColorMap(display_grid, 2)
cv2.imwrite(savepath+'/'+str(image_name)+'/feature'+str(i)+'.png', heatmap)
# util.save_img(heatmap, savepath+'/'+str(image_name)+'/feature'+str(i)+'.png')
# print(savepath+'/'+str(image_name)+'/feature'+str(i)+'.png')
# fig = plot.gcf()
# # 去除图像周围的白边
# height, width = display_grid.shape
# # 如果dpi=300,那么图像大小=height*width
# fig.set_size_inches(width / 100.0 / 3.0, height / 100.0 / 3.0)
# plot.gca().xaxis.set_major_locator(plot.NullLocator())
# plot.gca().yaxis.set_major_locator(plot.NullLocator())
# plot.subplots_adjust(top=1, bottom=0, left=0, right=1, hspace=0, wspace=0)
# plot.margins(0, 0)
#
# plot.imshow(display_grid, cmap='jet')
# # plot.colorbar()
#
# plot.savefig(savepath+'/'+str(image_name)+'/'+'feature'+str(i)+'.png', dpi=300)
# util.save_img(display_grid, savepath+'feature'+str(i)+'.png')
# merge_image = heatmap_overlay(image, display_grid)
# plot.imshow(merge_image, cmap='jet')
# plot.savefig(savepath+'/'+str(image_name)+'/'+'merger'+str(i)+'.png', dpi=300)
def heatmap_overlay(image,heatmap):
# 灰度化heatmap
heatmap = heatmap.astype(np.uint8)
# 热力图伪彩色
# heatmap_color = cv2.applyColorMap(heatmap_g, cv2.COLORMAP_JET)
# overlay热力图
merge_img = image.copy()
# heatmap_img = heatmap_color.copy()
overlay = image.copy()
alpha = 0.3 # 设置覆盖图片的透明度
# cv2.rectangle(overlay, (0, 0), (merge_img.shape[1], merge_img.shape[0]), (0, 0, 0), -1) # 设置蓝色为热度图基本色
# cv2.addWeighted(overlay, alpha, merge_img, 1-alpha, 0) # 将背景热度图覆盖到原图
cv2.addWeighted(merge_img, alpha, heatmap, 1-alpha, 0) # 将热度图覆盖到原图
return merge_img
#### options
parser = argparse.ArgumentParser()
parser.add_argument('-opt', type=str, required=True, help='Path to options YMAL file.')
opt = option.parse(parser.parse_args().opt, is_train=False)
opt = option.dict_to_nonedict(opt)
util.mkdirs(
(path for key, path in opt['path'].items()
if not key == 'experiments_root' and 'pretrain_model' not in key and 'resume' not in key))
util.setup_logger('base', opt['path']['log'], 'test_' + opt['name'], level=logging.INFO,
screen=True, tofile=True)
logger = logging.getLogger('base')
logger.info(option.dict2str(opt))
#### Create test dataset and dataloader
test_loaders = []
for phase, dataset_opt in sorted(opt['datasets'].items()):
test_set = create_dataset(dataset_opt)
test_loader = create_dataloader(test_set, dataset_opt)
logger.info('Number of test images in [{:s}]: {:d}'.format(dataset_opt['name'], len(test_set)))
test_loaders.append(test_loader)
model = create_model(opt)
for test_loader in test_loaders:
if opt['model'] == 'srgan' or opt['model'] =='sr':
test_set_name = test_loader.dataset.opt['name']
logger.info('\nTesting [{:s}]...'.format(test_set_name))
test_start_time = time.time()
dataset_dir = osp.join(opt['path']['results_root'], test_set_name)
util.mkdir(dataset_dir)
test_results = OrderedDict()
test_results['psnr'] = []
test_results['ssim'] = []
test_results['psnr_y'] = []
test_results['ssim_y'] = []
for data in test_loader:
need_GT = False if test_loader.dataset.opt['dataroot_GT'] is None else True
model.feed_data(data, need_GT=need_GT)
img_path = data['GT_path'][0] if need_GT else data['LQ_path'][0]
img_name = osp.splitext(osp.basename(img_path))[0]
model.test()
visuals = model.get_current_visuals(need_GT=need_GT)
# sr_img = util.tensor2img(visuals['rlt']) # uint8
# LQ_img = util.tensor2img(visuals['LQ'])
sr_img = util.tensor2img(torch.div(torch.add(visuals['rlt'], 1), 2))
LQ_img = util.tensor2img(torch.div(torch.add(visuals['LQ'], 1), 2))
# sr_img = cv2.resize(sr_img, (136, 96), interpolation=cv2.INTER_CUBIC)
# save images
suffix = opt['suffix']
if suffix:
save_img_path = osp.join(dataset_dir, img_name + suffix + '.png')
else:
save_img_path = osp.join(dataset_dir, img_name + '.png')
# LQ_path = osp.join(dataset_dir, img_name +'_LQ'+ '.png')
# print(LQ_path)
# util.save_img(LQ_img, LQ_path)
# calculate PSNR and SSIM
if need_GT:
# gt_img = util.tensor2img(visuals['GT'])
gt_img = util.tensor2img(torch.div(torch.add(visuals['GT'], 1), 2)) # uint8
sr_img, gt_img = util.crop_border([sr_img[:, :], gt_img[:, :]], 0)
#GC
# sr_img, gt_img = util.crop_border([sr_img[:, :], gt_img[:, 4:132]], 0)
#EC
# sr_img, gt_img = util.crop_border([sr_img[:, :], gt_img[:, 10:138]], 0)
util.save_img(sr_img, save_img_path)
psnr = util.calculate_psnr(sr_img, gt_img)
ssim = util.calculate_ssim(sr_img, gt_img)
test_results['psnr'].append(psnr)
test_results['ssim'].append(ssim)
# if gt_img.shape[2] == 3: # RGB image
if gt_img.ndim == 3: # RGB image
sr_img_y = bgr2ycbcr(sr_img / 255., only_y=True)
gt_img_y = bgr2ycbcr(gt_img / 255., only_y=True)
psnr_y = util.calculate_psnr(sr_img_y * 255, gt_img_y * 255)
ssim_y = util.calculate_ssim(sr_img_y * 255, gt_img_y * 255)
test_results['psnr_y'].append(psnr_y)
test_results['ssim_y'].append(ssim_y)
logger.info(
'{:20s} - PSNR: {:.6f} dB; SSIM: {:.6f}; PSNR_Y: {:.6f} dB; SSIM_Y: {:.6f}.'.
format(img_name, psnr, ssim, psnr_y, ssim_y))
else:
logger.info('{:20s} - PSNR: {:.6f} dB; SSIM: {:.6f}.'.format(img_name, psnr, ssim))
else:
logger.info(img_name)
if need_GT: # metrics
# Average PSNR/SSIM results
ave_psnr = sum(test_results['psnr']) / len(test_results['psnr'])
ave_ssim = sum(test_results['ssim']) / len(test_results['ssim'])
# 计算方差
std_psnr = np.std(test_results['psnr'])
std_ssim = np.std(test_results['ssim'])
logger.info(
'----Average PSNR/SSIM results for {}----\n\tPSNR: {:.6f} dB; SSIM: {:.6f}\n'.format(
test_set_name, ave_psnr, ave_ssim))
logger.info(
'----Std PSNR/SSIM results for {}----\n\tPSNR: {:.6f} dB; SSIM: {:.6f}\n'.format(
test_set_name, std_psnr, std_ssim))
if test_results['psnr_y'] and test_results['ssim_y']:
ave_psnr_y = sum(test_results['psnr_y']) / len(test_results['psnr_y'])
ave_ssim_y = sum(test_results['ssim_y']) / len(test_results['ssim_y'])
logger.info(
'----Y channel, average PSNR/SSIM----\n\tPSNR_Y: {:.6f} dB; SSIM_Y: {:.6f}\n'.
format(ave_psnr_y, ave_ssim_y))
elif opt['model'] == 'srgan_joint':
test_set_name = test_loader.dataset.opt['name']
logger.info('\nTesting [{:s}]...'.format(test_set_name))
test_start_time = time.time()
G1_dataset_dir = osp.join(opt['path']['results_root'], test_set_name, 'G1')
G2_dataset_dir = osp.join(opt['path']['results_root'], test_set_name, 'G2')
util.mkdir(G1_dataset_dir)
util.mkdir(G2_dataset_dir)
g1_test_results = OrderedDict()
g2_test_results = OrderedDict()
g1_test_results['psnr'] = []
g1_test_results['ssim'] = []
g1_test_results['psnr_y'] = []
g1_test_results['ssim_y'] = []
g2_test_results['psnr'] = []
g2_test_results['ssim'] = []
g2_test_results['psnr_y'] = []
g2_test_results['ssim_y'] = []
for data in test_loader:
need_GT = False if test_loader.dataset.opt['dataroot_GT'] is None else True
model.feed_data(data, need_GT=need_GT)
img_path = data['GT_path'][0] if need_GT else data['LQ_path'][0]
img_name = osp.splitext(osp.basename(img_path))[0]
model.test()
visuals = model.get_current_visuals(need_GT=need_GT)
# sr_img = util.tensor2img(visuals['rlt']) # uint8
G1_img = util.tensor2img(torch.div(torch.add(visuals['rlt'], 1), 2))
G2_img = util.tensor2img(torch.div(torch.add(visuals['rlt_2'], 1), 2)) # uint8
# G2_img = cv2.imread('/media/omnisky/ubuntu/zxz/model/mmsr/val/20191206/val_set14/G2/' + img_name+'.png')
# G2_img = G2_img[:, :, 0]
#特征可视化
# displayFeature(visuals['GAB_inpaint'].view(1, 64, 48, 69),
# savepath='/media/omnisky/7D37935326D33C41/zxz/model/mmsr/val/feature/inpaint',
# image_name=img_name,
# image=G1_img)
# displayFeature(visuals['GAB_sr'].view(1, 64, 48, 69),
# savepath='/media/omnisky/7D37935326D33C41/zxz/model/mmsr/val/feature/sr',
# image_name=img_name,
# image=G1_img)
# displayFeature(visuals['fea3'].view(1, 64, 48, 69),
# savepath='/media/omnisky/7D37935326D33C41/zxz/model/mmsr/val/feature/fea3',
# image_name=img_name,
# image=G1_img)
# displayFeature(visuals['fea5'].view(1, 64, 48, 69),
# savepath='/media/omnisky/7D37935326D33C41/zxz/model/mmsr/val/feature/fea5',
# image_name=img_name,
# image=G1_img)
# displayFeature(visuals['fea7'].view(1, 64, 48, 69),
# savepath='/media/omnisky/7D37935326D33C41/zxz/model/mmsr/val/feature/fea7',
# image_name=img_name,
# image=G1_img)
# save images
suffix = opt['suffix']
if suffix:
G1_save_img_path = osp.join(G1_dataset_dir, img_name + suffix + '.png')
G2_save_img_path = osp.join(G2_dataset_dir, img_name + suffix + '.png')
else:
G1_save_img_path = osp.join(G1_dataset_dir, img_name + '.png')
G2_save_img_path = osp.join(G2_dataset_dir, img_name + '.png')
util.save_img(G1_img, G1_save_img_path)
util.save_img(G2_img, G2_save_img_path)
# calculate PSNR and SSIM
# if need_GT:
# # gt_img = util.tensor2img(visuals['GT'])
# LRgt_img = util.tensor2img(torch.div(torch.add(visuals['LR'], 1), 2)) # uint8
# HRgt_img = util.tensor2img(torch.div(torch.add(visuals['GT'], 1), 2)) # uint8
#
# G1_img, LRgt_img = util.crop_border([G1_img, LRgt_img], 0)
# G2_img, HRgt_img = util.crop_border([G2_img[:, :], HRgt_img[:, :]], 0)
# util.save_img(G1_img, G1_save_img_path)
# util.save_img(G2_img, G2_save_img_path)
# g1_psnr = util.calculate_psnr(G1_img, LRgt_img)
# g1_ssim = util.calculate_ssim(G1_img, LRgt_img)
# g2_psnr = util.calculate_psnr(G2_img, HRgt_img)
# g2_ssim = util.calculate_ssim(G2_img, HRgt_img)
# g1_test_results['psnr'].append(g1_psnr)
# g1_test_results['ssim'].append(g1_ssim)
# g2_test_results['psnr'].append(g2_psnr)
# g2_test_results['ssim'].append(g2_ssim)
# # if gt_img.shape[2] == 3: # RGB image
# if LRgt_img.ndim == 3: # RGB image
# sr_img_y = bgr2ycbcr(sr_img / 255., only_y=True)
# gt_img_y = bgr2ycbcr(gt_img / 255., only_y=True)
#
# psnr_y = util.calculate_psnr(sr_img_y * 255, gt_img_y * 255)
# ssim_y = util.calculate_ssim(sr_img_y * 255, gt_img_y * 255)
# test_results['psnr_y'].append(psnr_y)
# test_results['ssim_y'].append(ssim_y)
# logger.info(
# 'RGB:{:20s} - PSNR: {:.6f} dB; SSIM: {:.6f}; PSNR_Y: {:.6f} dB; SSIM_Y: {:.6f}.'.
# format(img_name, psnr, ssim, psnr_y, ssim_y))
# else:
# logger.info('{:20s} - G1 - PSNR: {:.6f} dB; SSIM: {:.6f}.'.format(img_name, g1_psnr, g1_ssim))
# logger.info('{:20s} - G2 - PSNR: {:.6f} dB; SSIM: {:.6f}.'.format(img_name, g2_psnr, g2_ssim))
# else:
# logger.info(img_name)
#
# if need_GT: # metrics
# # Average PSNR/SSIM results
# g1_ave_psnr = sum(g1_test_results['psnr']) / len(g1_test_results['psnr'])
# g1_ave_ssim = sum(g1_test_results['ssim']) / len(g1_test_results['ssim'])
# g2_ave_psnr = sum(g2_test_results['psnr']) / len(g2_test_results['psnr'])
# g2_ave_ssim = sum(g2_test_results['ssim']) / len(g2_test_results['ssim'])
# # 计算方差
# g1_std_psnr = np.std(g1_test_results['psnr'])
# g1_std_ssim = np.std(g1_test_results['ssim'])
# g2_std_psnr = np.std(g2_test_results['psnr'])
# g2_std_ssim = np.std(g2_test_results['ssim'])
# logger.info('------------------G1-----------------')
# logger.info(
# '----Average PSNR/SSIM results for {}----\n\tPSNR: {:.6f} dB; SSIM: {:.6f}\n'.format(
# test_set_name, g1_ave_psnr, g1_ave_ssim))
# logger.info(
# '----Std PSNR/SSIM results for {}----\n\tPSNR: {:.6f} dB; SSIM: {:.6f}\n'.format(
# test_set_name, g1_std_psnr, g1_std_ssim))
# logger.info('------------------G2-----------------')
# logger.info(
# '----Average PSNR/SSIM results for {}----\n\tPSNR: {:.6f} dB; SSIM: {:.6f}\n'.format(
# test_set_name, g2_ave_psnr, g2_ave_ssim))
# logger.info(
# '----Std PSNR/SSIM results for {}----\n\tPSNR: {:.6f} dB; SSIM: {:.6f}\n'.format(
# test_set_name, g2_std_psnr, g2_std_ssim))
# # if test_results['psnr_y'] and test_results['ssim_y']:
# # ave_psnr_y = sum(test_results['psnr_y']) / len(test_results['psnr_y'])
# # ave_ssim_y = sum(test_results['ssim_y']) / len(test_results['ssim_y'])
# # logger.info(
# # '----Y channel, average PSNR/SSIM----\n\tPSNR_Y: {:.6f} dB; SSIM_Y: {:.6f}\n'.
# # format(ave_psnr_y, ave_ssim_y))
|
[
"utils.util.crop_border",
"argparse.ArgumentParser",
"models.create_model",
"utils.util.mkdir",
"os.path.join",
"utils.util.calculate_psnr",
"numpy.std",
"utils.util.save_img",
"numpy.max",
"utils.util.setup_logger",
"data.create_dataloader",
"os.path.basename",
"cv2.addWeighted",
"numpy.min",
"cv2.applyColorMap",
"numpy.dot",
"options.options.dict_to_nonedict",
"data.util.bgr2ycbcr",
"data.create_dataset",
"torch.add",
"time.time",
"collections.OrderedDict",
"options.options.dict2str",
"utils.util.calculate_ssim",
"logging.getLogger"
] |
[((3130, 3155), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (3153, 3155), False, 'import argparse\n'), ((3310, 3338), 'options.options.dict_to_nonedict', 'option.dict_to_nonedict', (['opt'], {}), '(opt)\n', (3333, 3338), True, 'import options.options as option\n'), ((3496, 3615), 'utils.util.setup_logger', 'util.setup_logger', (['"""base"""', "opt['path']['log']", "('test_' + opt['name'])"], {'level': 'logging.INFO', 'screen': '(True)', 'tofile': '(True)'}), "('base', opt['path']['log'], 'test_' + opt['name'], level=\n logging.INFO, screen=True, tofile=True)\n", (3513, 3615), True, 'import utils.util as util\n'), ((3638, 3663), 'logging.getLogger', 'logging.getLogger', (['"""base"""'], {}), "('base')\n", (3655, 3663), False, 'import logging\n'), ((4064, 4081), 'models.create_model', 'create_model', (['opt'], {}), '(opt)\n', (4076, 4081), False, 'from models import create_model\n'), ((430, 473), 'numpy.dot', 'np.dot', (['rgb[..., :3]', '[0.299, 0.587, 0.114]'], {}), '(rgb[..., :3], [0.299, 0.587, 0.114])\n', (436, 473), True, 'import numpy as np\n'), ((3020, 3076), 'cv2.addWeighted', 'cv2.addWeighted', (['merge_img', 'alpha', 'heatmap', '(1 - alpha)', '(0)'], {}), '(merge_img, alpha, heatmap, 1 - alpha, 0)\n', (3035, 3076), False, 'import cv2\n'), ((3676, 3696), 'options.options.dict2str', 'option.dict2str', (['opt'], {}), '(opt)\n', (3691, 3696), True, 'import options.options as option\n'), ((3831, 3858), 'data.create_dataset', 'create_dataset', (['dataset_opt'], {}), '(dataset_opt)\n', (3845, 3858), False, 'from data import create_dataset, create_dataloader\n'), ((3877, 3917), 'data.create_dataloader', 'create_dataloader', (['test_set', 'dataset_opt'], {}), '(test_set, dataset_opt)\n', (3894, 3917), False, 'from data import create_dataset, create_dataloader\n'), ((1260, 1309), 'cv2.applyColorMap', 'cv2.applyColorMap', (['display_grid', 'cv2.COLORMAP_JET'], {}), '(display_grid, cv2.COLORMAP_JET)\n', (1277, 1309), False, 'import cv2\n'), ((4317, 4328), 'time.time', 'time.time', ([], {}), '()\n', (4326, 4328), False, 'import time\n'), ((4351, 4403), 'os.path.join', 'osp.join', (["opt['path']['results_root']", 'test_set_name'], {}), "(opt['path']['results_root'], test_set_name)\n", (4359, 4403), True, 'import os.path as osp\n'), ((4412, 4435), 'utils.util.mkdir', 'util.mkdir', (['dataset_dir'], {}), '(dataset_dir)\n', (4422, 4435), True, 'import utils.util as util\n'), ((4460, 4473), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (4471, 4473), False, 'from collections import OrderedDict\n'), ((7752, 7780), 'numpy.std', 'np.std', (["test_results['psnr']"], {}), "(test_results['psnr'])\n", (7758, 7780), True, 'import numpy as np\n'), ((7804, 7832), 'numpy.std', 'np.std', (["test_results['ssim']"], {}), "(test_results['ssim'])\n", (7810, 7832), True, 'import numpy as np\n'), ((8803, 8814), 'time.time', 'time.time', ([], {}), '()\n', (8812, 8814), False, 'import time\n'), ((8840, 8898), 'os.path.join', 'osp.join', (["opt['path']['results_root']", 'test_set_name', '"""G1"""'], {}), "(opt['path']['results_root'], test_set_name, 'G1')\n", (8848, 8898), True, 'import os.path as osp\n'), ((8924, 8982), 'os.path.join', 'osp.join', (["opt['path']['results_root']", 'test_set_name', '"""G2"""'], {}), "(opt['path']['results_root'], test_set_name, 'G2')\n", (8932, 8982), True, 'import os.path as osp\n'), ((8991, 9017), 'utils.util.mkdir', 'util.mkdir', (['G1_dataset_dir'], {}), '(G1_dataset_dir)\n', (9001, 9017), True, 'import utils.util as util\n'), ((9026, 9052), 'utils.util.mkdir', 'util.mkdir', (['G2_dataset_dir'], {}), '(G2_dataset_dir)\n', (9036, 9052), True, 'import utils.util as util\n'), ((9080, 9093), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (9091, 9093), False, 'from collections import OrderedDict\n'), ((9120, 9133), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (9131, 9133), False, 'from collections import OrderedDict\n'), ((5498, 5547), 'os.path.join', 'osp.join', (['dataset_dir', "(img_name + suffix + '.png')"], {}), "(dataset_dir, img_name + suffix + '.png')\n", (5506, 5547), True, 'import os.path as osp\n'), ((5598, 5638), 'os.path.join', 'osp.join', (['dataset_dir', "(img_name + '.png')"], {}), "(dataset_dir, img_name + '.png')\n", (5606, 5638), True, 'import os.path as osp\n'), ((6032, 6081), 'utils.util.crop_border', 'util.crop_border', (['[sr_img[:, :], gt_img[:, :]]', '(0)'], {}), '([sr_img[:, :], gt_img[:, :]], 0)\n', (6048, 6081), True, 'import utils.util as util\n'), ((6317, 6353), 'utils.util.save_img', 'util.save_img', (['sr_img', 'save_img_path'], {}), '(sr_img, save_img_path)\n', (6330, 6353), True, 'import utils.util as util\n'), ((6378, 6413), 'utils.util.calculate_psnr', 'util.calculate_psnr', (['sr_img', 'gt_img'], {}), '(sr_img, gt_img)\n', (6397, 6413), True, 'import utils.util as util\n'), ((6437, 6472), 'utils.util.calculate_ssim', 'util.calculate_ssim', (['sr_img', 'gt_img'], {}), '(sr_img, gt_img)\n', (6456, 6472), True, 'import utils.util as util\n'), ((12040, 12079), 'utils.util.save_img', 'util.save_img', (['G1_img', 'G1_save_img_path'], {}), '(G1_img, G1_save_img_path)\n', (12053, 12079), True, 'import utils.util as util\n'), ((12092, 12131), 'utils.util.save_img', 'util.save_img', (['G2_img', 'G2_save_img_path'], {}), '(G2_img, G2_save_img_path)\n', (12105, 12131), True, 'import utils.util as util\n'), ((1017, 1029), 'numpy.min', 'np.min', (['grid'], {}), '(grid)\n', (1023, 1029), True, 'import numpy as np\n'), ((1034, 1046), 'numpy.max', 'np.max', (['grid'], {}), '(grid)\n', (1040, 1046), True, 'import numpy as np\n'), ((1049, 1061), 'numpy.min', 'np.min', (['grid'], {}), '(grid)\n', (1055, 1061), True, 'import numpy as np\n'), ((4900, 4922), 'os.path.basename', 'osp.basename', (['img_path'], {}), '(img_path)\n', (4912, 4922), True, 'import os.path as osp\n'), ((5184, 5212), 'torch.add', 'torch.add', (["visuals['rlt']", '(1)'], {}), "(visuals['rlt'], 1)\n", (5193, 5212), False, 'import torch\n'), ((5265, 5292), 'torch.add', 'torch.add', (["visuals['LQ']", '(1)'], {}), "(visuals['LQ'], 1)\n", (5274, 5292), False, 'import torch\n'), ((6711, 6749), 'data.util.bgr2ycbcr', 'bgr2ycbcr', (['(sr_img / 255.0)'], {'only_y': '(True)'}), '(sr_img / 255.0, only_y=True)\n', (6720, 6749), False, 'from data.util import bgr2ycbcr\n'), ((6780, 6818), 'data.util.bgr2ycbcr', 'bgr2ycbcr', (['(gt_img / 255.0)'], {'only_y': '(True)'}), '(gt_img / 255.0, only_y=True)\n', (6789, 6818), False, 'from data.util import bgr2ycbcr\n'), ((6848, 6899), 'utils.util.calculate_psnr', 'util.calculate_psnr', (['(sr_img_y * 255)', '(gt_img_y * 255)'], {}), '(sr_img_y * 255, gt_img_y * 255)\n', (6867, 6899), True, 'import utils.util as util\n'), ((6929, 6980), 'utils.util.calculate_ssim', 'util.calculate_ssim', (['(sr_img_y * 255)', '(gt_img_y * 255)'], {}), '(sr_img_y * 255, gt_img_y * 255)\n', (6948, 6980), True, 'import utils.util as util\n'), ((11710, 11762), 'os.path.join', 'osp.join', (['G1_dataset_dir', "(img_name + suffix + '.png')"], {}), "(G1_dataset_dir, img_name + suffix + '.png')\n", (11718, 11762), True, 'import os.path as osp\n'), ((11798, 11850), 'os.path.join', 'osp.join', (['G2_dataset_dir', "(img_name + suffix + '.png')"], {}), "(G2_dataset_dir, img_name + suffix + '.png')\n", (11806, 11850), True, 'import os.path as osp\n'), ((11904, 11947), 'os.path.join', 'osp.join', (['G1_dataset_dir', "(img_name + '.png')"], {}), "(G1_dataset_dir, img_name + '.png')\n", (11912, 11947), True, 'import os.path as osp\n'), ((11983, 12026), 'os.path.join', 'osp.join', (['G2_dataset_dir', "(img_name + '.png')"], {}), "(G2_dataset_dir, img_name + '.png')\n", (11991, 12026), True, 'import os.path as osp\n'), ((5956, 5983), 'torch.add', 'torch.add', (["visuals['GT']", '(1)'], {}), "(visuals['GT'], 1)\n", (5965, 5983), False, 'import torch\n'), ((9725, 9747), 'os.path.basename', 'osp.basename', (['img_path'], {}), '(img_path)\n', (9737, 9747), True, 'import os.path as osp\n'), ((9955, 9983), 'torch.add', 'torch.add', (["visuals['rlt']", '(1)'], {}), "(visuals['rlt'], 1)\n", (9964, 9983), False, 'import torch\n'), ((10036, 10066), 'torch.add', 'torch.add', (["visuals['rlt_2']", '(1)'], {}), "(visuals['rlt_2'], 1)\n", (10045, 10066), False, 'import torch\n')]
|
"""
Copyright (c) 2018 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import numpy as np
def space_to_batch_infer(node):
"""
https://www.tensorflow.org/api_docs/cc/class/tensorflow/ops/space-to-batch
"""
input_shape = node.in_node(0).shape
if input_shape is None:
return
if len(node.in_nodes()) != 3:
return
if node.in_node(1).value is None or node.in_node(2).value is None:
return
block_size = node.in_node(1).value
pad = node.in_node(2).value
if np.any(np.array(block_size.shape) != 2) or np.any(np.array(pad.shape) != 2): # TODO REWRITE!!!
return
height_pad = pad[0][0] + input_shape[1] + pad[0][1]
width_pad = pad[1][0] + input_shape[2] + pad[1][1]
output_shape = [input_shape[0] * block_size[0] * block_size[1], int(height_pad / block_size[0]),
int(width_pad / block_size[1]), input_shape[3]]
node.out_node().shape = np.array(output_shape)
def batch_to_space_infer(node):
"""
https://www.tensorflow.org/api_docs/cc/class/tensorflow/ops/space-to-batch
"""
input_shape = node.in_node(0).shape
if input_shape is None:
return
if len(node.in_nodes()) != 3:
return
if node.in_node(1).value is None or node.in_node(2).value is None:
return
block_size = node.in_node(1).value
crop = node.in_node(2).value
if np.any(np.array(block_size.shape) != 2) or np.any(np.array(crop.shape) != 2): # TODO REWRITE!!!
return
hp = block_size[0] * input_shape[1]
wp = block_size[1] * input_shape[2]
height = hp - crop[0][0] - crop[0][1]
width = wp - crop[1][0] - crop[1][1]
batch = int(input_shape[0] / (block_size[0] * block_size[1]))
output_shape = [batch, height, width, input_shape[3]]
node.out_node().shape = np.array(output_shape)
|
[
"numpy.array"
] |
[((1451, 1473), 'numpy.array', 'np.array', (['output_shape'], {}), '(output_shape)\n', (1459, 1473), True, 'import numpy as np\n'), ((2334, 2356), 'numpy.array', 'np.array', (['output_shape'], {}), '(output_shape)\n', (2342, 2356), True, 'import numpy as np\n'), ((1037, 1063), 'numpy.array', 'np.array', (['block_size.shape'], {}), '(block_size.shape)\n', (1045, 1063), True, 'import numpy as np\n'), ((1080, 1099), 'numpy.array', 'np.array', (['pad.shape'], {}), '(pad.shape)\n', (1088, 1099), True, 'import numpy as np\n'), ((1911, 1937), 'numpy.array', 'np.array', (['block_size.shape'], {}), '(block_size.shape)\n', (1919, 1937), True, 'import numpy as np\n'), ((1954, 1974), 'numpy.array', 'np.array', (['crop.shape'], {}), '(crop.shape)\n', (1962, 1974), True, 'import numpy as np\n')]
|
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from wordcloud import WordCloud, STOPWORDS
# Lists, dicts, and sorting
l = [3, 5, 6, 1, -6]
d = {'a': 9, 'b': 2, 'c': 5, 'd': 3}
sl = sorted(l)
sorted(d)
sorted(d.values())
sorted(d.items())
print(l[:2])
# Capturing standard output
# Call this program in cmd/terminal and do: python program_name.py > captured_std_output.txt
print("Here's some text.")
# Enumerate()
for i, x in enumerate([1, 2, 3, 4, 5]):
print("The index of {} is {}".format(x, i))
# # Inelegant, don't do:
# i = 0
# for x in [1,2,3,4,5]:
# print("The index of {} is {}".format(x, i))
# i += 1
# Plots
X = range(-5, 6) # this actually ranges from -5 to 4
Y = [pow(x, 2) for x in X]
# Label the axes:
plt.xlabel('Integers')
plt.ylabel('f(x)')
# Control the scale of the Y-axis
plt.ylim([0, 30])
plt.plot(X, Y, label="X-squared")
plt.show()
plt.savefig('figures/parabola1.png')
# Add a second plot
Y2 = [pow(x, 3) for x in X]
plt.plot(X, Y2, 'o-', color='fuchsia', label="X-cubed") # 'o-', '--'
plt.legend()
plt.savefig('figures/cube.png')
# Activity: Plot 4 different polynomial functions!
# https://github.com/olzama/Ling471/blob/gh-pages/assignments/activity_plots.py
# Bars
numbers = np.random.rand(10, 4)
# print(numbers)
# Let's use pandas visualization tools:
df = pd.DataFrame(numbers, columns=['a', 'b', 'c', 'd'])
print(df)
df.plot.bar().get_figure().savefig('figures/bars.png')
df.plot.barh().get_figure().savefig('figures/hbars.png')
df.plot.bar(stacked=True).get_figure().savefig('figures/stacked-bars.png')
# Pie chart
df = pd.DataFrame({'mass': [0.330, 4.87, 5.97],
'radius': [2439.7, 6051.8, 6378.1]},
index=['Mercury', 'Venus', 'Earth'])
df.plot.pie(y='mass').get_figure().savefig('figures/pie.png')
fig = plt.figure()
subplots = df.plot.pie(subplots=True, figsize=(11, 6))
# Subplots will contain an object that has a savefig() function at index [0]:
subplots[0].get_figure().savefig('figures/pie1.png')
# Text
# Back to matplotlib:
plt.cla() # Clear plot
plt.clf()
imdb = pd.read_csv('../datasets/my_imdb.csv')
text = imdb['review'][0]
print(text)
wordcloud = WordCloud(width=3000, height=2000, random_state=1, background_color='blue',
collocations=False, stopwords=STOPWORDS).generate(text)
plt.imshow(wordcloud)
plt.axis("off")
plt.savefig('figures/wordcloud.png')
|
[
"pandas.DataFrame",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.clf",
"pandas.read_csv",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.imshow",
"wordcloud.WordCloud",
"matplotlib.pyplot.axis",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.cla",
"numpy.random.rand",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.savefig"
] |
[((760, 782), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Integers"""'], {}), "('Integers')\n", (770, 782), True, 'import matplotlib.pyplot as plt\n'), ((783, 801), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""f(x)"""'], {}), "('f(x)')\n", (793, 801), True, 'import matplotlib.pyplot as plt\n'), ((836, 853), 'matplotlib.pyplot.ylim', 'plt.ylim', (['[0, 30]'], {}), '([0, 30])\n', (844, 853), True, 'import matplotlib.pyplot as plt\n'), ((854, 887), 'matplotlib.pyplot.plot', 'plt.plot', (['X', 'Y'], {'label': '"""X-squared"""'}), "(X, Y, label='X-squared')\n", (862, 887), True, 'import matplotlib.pyplot as plt\n'), ((888, 898), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (896, 898), True, 'import matplotlib.pyplot as plt\n'), ((899, 935), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""figures/parabola1.png"""'], {}), "('figures/parabola1.png')\n", (910, 935), True, 'import matplotlib.pyplot as plt\n'), ((985, 1040), 'matplotlib.pyplot.plot', 'plt.plot', (['X', 'Y2', '"""o-"""'], {'color': '"""fuchsia"""', 'label': '"""X-cubed"""'}), "(X, Y2, 'o-', color='fuchsia', label='X-cubed')\n", (993, 1040), True, 'import matplotlib.pyplot as plt\n'), ((1055, 1067), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (1065, 1067), True, 'import matplotlib.pyplot as plt\n'), ((1068, 1099), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""figures/cube.png"""'], {}), "('figures/cube.png')\n", (1079, 1099), True, 'import matplotlib.pyplot as plt\n'), ((1252, 1273), 'numpy.random.rand', 'np.random.rand', (['(10)', '(4)'], {}), '(10, 4)\n', (1266, 1273), True, 'import numpy as np\n'), ((1336, 1387), 'pandas.DataFrame', 'pd.DataFrame', (['numbers'], {'columns': "['a', 'b', 'c', 'd']"}), "(numbers, columns=['a', 'b', 'c', 'd'])\n", (1348, 1387), True, 'import pandas as pd\n'), ((1603, 1723), 'pandas.DataFrame', 'pd.DataFrame', (["{'mass': [0.33, 4.87, 5.97], 'radius': [2439.7, 6051.8, 6378.1]}"], {'index': "['Mercury', 'Venus', 'Earth']"}), "({'mass': [0.33, 4.87, 5.97], 'radius': [2439.7, 6051.8, 6378.1\n ]}, index=['Mercury', 'Venus', 'Earth'])\n", (1615, 1723), True, 'import pandas as pd\n'), ((1825, 1837), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1835, 1837), True, 'import matplotlib.pyplot as plt\n'), ((2054, 2063), 'matplotlib.pyplot.cla', 'plt.cla', ([], {}), '()\n', (2061, 2063), True, 'import matplotlib.pyplot as plt\n'), ((2078, 2087), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (2085, 2087), True, 'import matplotlib.pyplot as plt\n'), ((2095, 2133), 'pandas.read_csv', 'pd.read_csv', (['"""../datasets/my_imdb.csv"""'], {}), "('../datasets/my_imdb.csv')\n", (2106, 2133), True, 'import pandas as pd\n'), ((2337, 2358), 'matplotlib.pyplot.imshow', 'plt.imshow', (['wordcloud'], {}), '(wordcloud)\n', (2347, 2358), True, 'import matplotlib.pyplot as plt\n'), ((2359, 2374), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (2367, 2374), True, 'import matplotlib.pyplot as plt\n'), ((2375, 2411), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""figures/wordcloud.png"""'], {}), "('figures/wordcloud.png')\n", (2386, 2411), True, 'import matplotlib.pyplot as plt\n'), ((2183, 2303), 'wordcloud.WordCloud', 'WordCloud', ([], {'width': '(3000)', 'height': '(2000)', 'random_state': '(1)', 'background_color': '"""blue"""', 'collocations': '(False)', 'stopwords': 'STOPWORDS'}), "(width=3000, height=2000, random_state=1, background_color='blue',\n collocations=False, stopwords=STOPWORDS)\n", (2192, 2303), False, 'from wordcloud import WordCloud, STOPWORDS\n')]
|
# Copyright 2021 Adobe
# All Rights Reserved.
# NOTICE: Adobe permits you to use, modify, and distribute this file in
# accordance with the terms of the Adobe license agreement accompanying
# it.
'''
>> python -m unittest unit_test.TestSingle_operator
'''
from skimage import io
import time
import beacon_aug as BA
# from beacon_aug.generator.operator_generator import DEFAULT_LIBRARIES
import numpy as np
import unittest
from datetime import timedelta
from hypothesis import given, settings, strategies as st
from hypothesis.extra.numpy import arrays
class TestSingle_operator(unittest.TestCase):
# @given(image=arrays(np.float32, st.tuples(*[st.integers(1, 500), st.integers(1, 500), st.just(3)])),
# limit=st.tuples(*[st.integers(-128, 0), st.integers(1, 128)]))
def testSingle_operator(self):
image = io.imread("../data/example.png")
limit = (-128, 128)
print("\n" + "="*5 + " Unit test 1: Single augmentation operator " + "="*5 + "\n")
for library in BA.Rotate().avail_libraries:
aug_pipeline = BA.Rotate(p=1, limit=limit, library=library)
augmented_image1 = aug_pipeline(image=image)['image'].copy()
augmented_image2 = aug_pipeline(image=image)['image'].copy()
# self.assertNotEqual(image, augmented_image1)
assert not np.array_equal(
image, augmented_image1), "Failed to generate augmentation different to input"
# self.assertNotEqual(augmented_image1, augmented_image2)
assert not np.array_equal(
augmented_image1, augmented_image2), "Failed to generate different augmentation results when calling "
if __name__ == "__main__":
unittest.main()
|
[
"unittest.main",
"beacon_aug.Rotate",
"numpy.array_equal",
"skimage.io.imread"
] |
[((1719, 1734), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1732, 1734), False, 'import unittest\n'), ((838, 870), 'skimage.io.imread', 'io.imread', (['"""../data/example.png"""'], {}), "('../data/example.png')\n", (847, 870), False, 'from skimage import io\n'), ((1014, 1025), 'beacon_aug.Rotate', 'BA.Rotate', ([], {}), '()\n', (1023, 1025), True, 'import beacon_aug as BA\n'), ((1070, 1114), 'beacon_aug.Rotate', 'BA.Rotate', ([], {'p': '(1)', 'limit': 'limit', 'library': 'library'}), '(p=1, limit=limit, library=library)\n', (1079, 1114), True, 'import beacon_aug as BA\n'), ((1345, 1384), 'numpy.array_equal', 'np.array_equal', (['image', 'augmented_image1'], {}), '(image, augmented_image1)\n', (1359, 1384), True, 'import numpy as np\n'), ((1551, 1601), 'numpy.array_equal', 'np.array_equal', (['augmented_image1', 'augmented_image2'], {}), '(augmented_image1, augmented_image2)\n', (1565, 1601), True, 'import numpy as np\n')]
|
"""
Copyright 2017 Neural Networks and Deep Learning lab, MIPT
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from deeppavlov.core.models.component import Component
from deeppavlov.core.common.registry import register
import numpy as np
@register('mask')
class Mask(Component):
def __init__(self, *args, **kwargs):
pass
@staticmethod
def __call__(tokens_batch, **kwargs):
"""Takes batch of tokens and returns the masks of corresponding length"""
batch_size = len(tokens_batch)
max_len = max(len(utt) for utt in tokens_batch)
mask = np.zeros([batch_size, max_len], dtype=np.float32)
for n, utterance in enumerate(tokens_batch):
mask[n, :len(utterance)] = 1
return mask
|
[
"numpy.zeros",
"deeppavlov.core.common.registry.register"
] |
[((723, 739), 'deeppavlov.core.common.registry.register', 'register', (['"""mask"""'], {}), "('mask')\n", (731, 739), False, 'from deeppavlov.core.common.registry import register\n'), ((1070, 1119), 'numpy.zeros', 'np.zeros', (['[batch_size, max_len]'], {'dtype': 'np.float32'}), '([batch_size, max_len], dtype=np.float32)\n', (1078, 1119), True, 'import numpy as np\n')]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.