code
stringlengths
31
1.05M
apis
list
extract_api
stringlengths
97
1.91M
import tensorflow as tf from scipy.stats import rankdata import numpy as np import os import time import datetime from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter from builddata_softplus import * from capsuleNet import CapsE # Parameters # ================================================== parser = ArgumentParser("CapsE", formatter_class=ArgumentDefaultsHelpFormatter, conflict_handler='resolve') parser.add_argument("--data", default="./data/", help="Data sources.") parser.add_argument("--run_folder", default="./", help="Data sources.") parser.add_argument("--name", default="WN18RR", help="Name of the dataset.") parser.add_argument("--embedding_dim", default=100, type=int, help="Dimensionality of character embedding (default: 128)") parser.add_argument("--filter_size", default=1, type=int, help="Comma-separated filter sizes (default: '3,4,5')") parser.add_argument("--num_filters", default=400, type=int, help="Number of filters per filter size (default: 128)") parser.add_argument("--learning_rate", default=0.00001, type=float, help="Learning rate") parser.add_argument("--batch_size", default=128, type=int, help="Batch Size") parser.add_argument("--neg_ratio", default=1.0, help="Number of negative triples generated by positive (default: 1.0)") parser.add_argument("--useInitialization", default=True, type=bool, help="Using the pretrained embeddings") parser.add_argument("--num_epochs", default=51, type=int, help="Number of training epochs") parser.add_argument("--savedEpochs", default=10, type=int, help="") parser.add_argument("--allow_soft_placement", default=True, type=bool, help="Allow device soft device placement") parser.add_argument("--log_device_placement", default=False, type=bool, help="Log placement of ops on devices") parser.add_argument("--model_name", default='wn18rr_400_4', help="") parser.add_argument("--useConstantInit", action='store_true') parser.add_argument('--iter_routing', default=1, type=int, help='number of iterations in routing algorithm') parser.add_argument('--num_outputs_secondCaps', default=1, type=int, help='') parser.add_argument('--vec_len_secondCaps', default=10, type=int, help='') parser.add_argument("--model_index", default='30') parser.add_argument("--num_splits", default=8, type=int) parser.add_argument("--testIdx", default=1, type=int, help="From 0 to 7") parser.add_argument("--decode", action='store_false') args = parser.parse_args() print(args) # Load data print("Loading data...") train, valid, test, words_indexes, indexes_words, \ headTailSelector, entity2id, id2entity, relation2id, id2relation = build_data(path=args.data, name=args.name) data_size = len(train) train_batch = Batch_Loader(train, words_indexes, indexes_words, headTailSelector, \ entity2id, id2entity, relation2id, id2relation, batch_size=args.batch_size, neg_ratio=args.neg_ratio) entity_array = np.array(list(train_batch.indexes_ents.keys())) initialization = [] if args.useInitialization == True: print("Using pre-trained initialization.") initialization = np.empty([len(words_indexes), args.embedding_dim]).astype(np.float32) initEnt, initRel = init_norm_Vector(args.data + args.name + '/relation2vec' + str(args.embedding_dim) + '.init', args.data + args.name + '/entity2vec' + str(args.embedding_dim) + '.init', args.embedding_dim) for _word in words_indexes: if _word in relation2id: index = relation2id[_word] _ind = words_indexes[_word] initialization[_ind] = initRel[index] elif _word in entity2id: index = entity2id[_word] _ind = words_indexes[_word] initialization[_ind] = initEnt[index] else: print('*****************Error********************!') break initialization = np.array(initialization, dtype=np.float32) assert len(words_indexes) % (len(entity2id) + len(relation2id)) == 0 print("Loading data... finished!") x_valid = np.array(list(valid.keys())).astype(np.int32) y_valid = np.array(list(valid.values())).astype(np.float32) len_valid = len(x_valid) batch_valid = int(len_valid / (args.num_splits - 1)) x_test = np.array(list(test.keys())).astype(np.int32) y_test = np.array(list(test.values())).astype(np.float32) len_test = len(x_test) batch_test = int(len_test / (args.num_splits - 1)) # uncomment when tuning hyper-parameters on the validation set # x_test = x_valid # y_test = y_valid # len_test = len_valid # batch_test = batch_valid ########################################## if args.decode == False: lstModelNames = list(args.model_name.split(",")) for _model_name in lstModelNames: out_dir = os.path.abspath(os.path.join(args.run_folder, "runs_CapsE", _model_name)) print("Evaluating {}\n".format(out_dir)) checkpoint_dir = os.path.abspath(os.path.join(out_dir, "checkpoints")) checkpoint_prefix = os.path.join(checkpoint_dir, "model") lstModelIndexes = list(args.model_index.split(",")) for _model_index in lstModelIndexes: _file = checkpoint_prefix + "-" + _model_index lstHT = [] for _index in range(args.num_splits): with open(_file + '.eval.' + str(_index) + '.txt') as f: for _line in f: if _line.strip() != '': lstHT.append(list(map(float, _line.strip().split()))) lstHT = np.array(lstHT) print(_file, 'mr, mrr, hits@1, hits@10 --> ', np.sum(lstHT, axis=0) / (2 * len_test)) print('------------------------------------') else: with tf.Graph().as_default(): tf.set_random_seed(1234) session_conf = tf.ConfigProto(allow_soft_placement=args.allow_soft_placement, log_device_placement=args.log_device_placement) session_conf.gpu_options.allow_growth = True sess = tf.Session(config=session_conf) with sess.as_default(): global_step = tf.Variable(0, name="global_step", trainable=False) capse = CapsE(sequence_length=x_valid.shape[1], initialization=initialization, embedding_size=args.embedding_dim, filter_size=args.filter_size, num_filters=args.num_filters, vocab_size=len(words_indexes), iter_routing=args.iter_routing, batch_size=2 * args.batch_size, num_outputs_secondCaps=args.num_outputs_secondCaps, vec_len_secondCaps=args.vec_len_secondCaps, useConstantInit=args.useConstantInit ) # Output directory for models and summaries lstModelNames = list(args.model_name.split(",")) for _model_name in lstModelNames: out_dir = os.path.abspath(os.path.join(args.run_folder, "runs_CapsE", _model_name)) print("Evaluating {}\n".format(out_dir)) # Checkpoint directory. Tensorflow assumes this directory already exists so we need to create it checkpoint_dir = os.path.abspath(os.path.join(out_dir, "checkpoints")) checkpoint_prefix = os.path.join(checkpoint_dir, "model") lstModelIndexes = list(args.model_index.split(",")) for _model_index in lstModelIndexes: _file = checkpoint_prefix + "-" + _model_index capse.saver.restore(sess, _file) print("Loaded model", _file) # Predict function to predict scores for test data def predict(x_batch, y_batch, writer=None): feed_dict = { capse.input_x: x_batch, capse.input_y: y_batch } scores = sess.run([capse.predictions], feed_dict) return scores def test_prediction(x_batch, y_batch, head_or_tail='head'): hits10 = 0.0 mrr = 0.0 mr = 0.0 hits1 = 0.0 for i in range(len(x_batch)): new_x_batch = np.tile(x_batch[i], (len(entity2id), 1)) new_y_batch = np.tile(y_batch[i], (len(entity2id), 1)) if head_or_tail == 'head': new_x_batch[:, 0] = entity_array else: # 'tail' new_x_batch[:, 2] = entity_array lstIdx = [] for tmpIdxTriple in range(len(new_x_batch)): tmpTriple = (new_x_batch[tmpIdxTriple][0], new_x_batch[tmpIdxTriple][1], new_x_batch[tmpIdxTriple][2]) if (tmpTriple in train) or (tmpTriple in valid) or ( tmpTriple in test): # also remove the valid test triple lstIdx.append(tmpIdxTriple) new_x_batch = np.delete(new_x_batch, lstIdx, axis=0) new_y_batch = np.delete(new_y_batch, lstIdx, axis=0) # thus, insert the valid test triple again, to the beginning of the array new_x_batch = np.insert(new_x_batch, 0, x_batch[i], axis=0) # thus, the index of the valid test triple is equal to 0 new_y_batch = np.insert(new_y_batch, 0, y_batch[i], axis=0) # for running with a batch size while len(new_x_batch) % ((int(args.neg_ratio) + 1) * args.batch_size) != 0: new_x_batch = np.append(new_x_batch, [x_batch[i]], axis=0) new_y_batch = np.append(new_y_batch, [y_batch[i]], axis=0) results = [] listIndexes = range(0, len(new_x_batch), (int(args.neg_ratio) + 1) * args.batch_size) for tmpIndex in range(len(listIndexes) - 1): results = np.append(results, predict( new_x_batch[listIndexes[tmpIndex]:listIndexes[tmpIndex + 1]], new_y_batch[listIndexes[tmpIndex]:listIndexes[tmpIndex + 1]])) results = np.append(results, predict(new_x_batch[listIndexes[-1]:], new_y_batch[listIndexes[-1]:])) results = np.reshape(results, -1) results_with_id = rankdata(results, method='ordinal') _filter = results_with_id[0] mr += _filter mrr += 1.0 / _filter if _filter <= 10: hits10 += 1 if _filter == 1: hits1 += 1 return np.array([mr, mrr, hits1, hits10]) if args.testIdx < (args.num_splits - 1): head_results = test_prediction( x_test[batch_test * args.testIdx: batch_test * (args.testIdx + 1)], y_test[batch_test * args.testIdx: batch_test * (args.testIdx + 1)], head_or_tail='head') tail_results = test_prediction( x_test[batch_test * args.testIdx: batch_test * (args.testIdx + 1)], y_test[batch_test * args.testIdx: batch_test * (args.testIdx + 1)], head_or_tail='tail') else: head_results = test_prediction(x_test[batch_test * args.testIdx: len_test], y_test[batch_test * args.testIdx: len_test], head_or_tail='head') tail_results = test_prediction(x_test[batch_test * args.testIdx: len_test], y_test[batch_test * args.testIdx: len_test], head_or_tail='tail') wri = open(_file + '.eval.' + str(args.testIdx) + '.txt', 'w') for _val in head_results: wri.write(str(_val) + ' ') wri.write('\n') for _val in tail_results: wri.write(str(_val) + ' ') wri.write('\n') wri.close()
[ "numpy.sum", "argparse.ArgumentParser", "tensorflow.Session", "scipy.stats.rankdata", "tensorflow.set_random_seed", "numpy.insert", "tensorflow.ConfigProto", "numpy.append", "tensorflow.Variable", "numpy.array", "numpy.reshape", "tensorflow.Graph", "os.path.join", "numpy.delete" ]
[((319, 421), 'argparse.ArgumentParser', 'ArgumentParser', (['"""CapsE"""'], {'formatter_class': 'ArgumentDefaultsHelpFormatter', 'conflict_handler': '"""resolve"""'}), "('CapsE', formatter_class=ArgumentDefaultsHelpFormatter,\n conflict_handler='resolve')\n", (333, 421), False, 'from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter\n'), ((3735, 3777), 'numpy.array', 'np.array', (['initialization'], {'dtype': 'np.float32'}), '(initialization, dtype=np.float32)\n', (3743, 3777), True, 'import numpy as np\n'), ((4797, 4834), 'os.path.join', 'os.path.join', (['checkpoint_dir', '"""model"""'], {}), "(checkpoint_dir, 'model')\n", (4809, 4834), False, 'import os\n'), ((5412, 5436), 'tensorflow.set_random_seed', 'tf.set_random_seed', (['(1234)'], {}), '(1234)\n', (5430, 5436), True, 'import tensorflow as tf\n'), ((5454, 5568), 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {'allow_soft_placement': 'args.allow_soft_placement', 'log_device_placement': 'args.log_device_placement'}), '(allow_soft_placement=args.allow_soft_placement,\n log_device_placement=args.log_device_placement)\n', (5468, 5568), True, 'import tensorflow as tf\n'), ((5632, 5663), 'tensorflow.Session', 'tf.Session', ([], {'config': 'session_conf'}), '(config=session_conf)\n', (5642, 5663), True, 'import tensorflow as tf\n'), ((4601, 4657), 'os.path.join', 'os.path.join', (['args.run_folder', '"""runs_CapsE"""', '_model_name'], {}), "(args.run_folder, 'runs_CapsE', _model_name)\n", (4613, 4657), False, 'import os\n'), ((4737, 4773), 'os.path.join', 'os.path.join', (['out_dir', '"""checkpoints"""'], {}), "(out_dir, 'checkpoints')\n", (4749, 4773), False, 'import os\n'), ((5218, 5233), 'numpy.array', 'np.array', (['lstHT'], {}), '(lstHT)\n', (5226, 5233), True, 'import numpy as np\n'), ((5707, 5758), 'tensorflow.Variable', 'tf.Variable', (['(0)'], {'name': '"""global_step"""', 'trainable': '(False)'}), "(0, name='global_step', trainable=False)\n", (5718, 5758), True, 'import tensorflow as tf\n'), ((5385, 5395), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (5393, 5395), True, 'import tensorflow as tf\n'), ((6728, 6765), 'os.path.join', 'os.path.join', (['checkpoint_dir', '"""model"""'], {}), "(checkpoint_dir, 'model')\n", (6740, 6765), False, 'import os\n'), ((5283, 5304), 'numpy.sum', 'np.sum', (['lstHT'], {'axis': '(0)'}), '(lstHT, axis=0)\n', (5289, 5304), True, 'import numpy as np\n'), ((6424, 6480), 'os.path.join', 'os.path.join', (['args.run_folder', '"""runs_CapsE"""', '_model_name'], {}), "(args.run_folder, 'runs_CapsE', _model_name)\n", (6436, 6480), False, 'import os\n'), ((6666, 6702), 'os.path.join', 'os.path.join', (['out_dir', '"""checkpoints"""'], {}), "(out_dir, 'checkpoints')\n", (6678, 6702), False, 'import os\n'), ((9464, 9498), 'numpy.array', 'np.array', (['[mr, mrr, hits1, hits10]'], {}), '([mr, mrr, hits1, hits10])\n', (9472, 9498), True, 'import numpy as np\n'), ((8079, 8117), 'numpy.delete', 'np.delete', (['new_x_batch', 'lstIdx'], {'axis': '(0)'}), '(new_x_batch, lstIdx, axis=0)\n', (8088, 8117), True, 'import numpy as np\n'), ((8139, 8177), 'numpy.delete', 'np.delete', (['new_y_batch', 'lstIdx'], {'axis': '(0)'}), '(new_y_batch, lstIdx, axis=0)\n', (8148, 8177), True, 'import numpy as np\n'), ((8281, 8326), 'numpy.insert', 'np.insert', (['new_x_batch', '(0)', 'x_batch[i]'], {'axis': '(0)'}), '(new_x_batch, 0, x_batch[i], axis=0)\n', (8290, 8326), True, 'import numpy as np\n'), ((8406, 8451), 'numpy.insert', 'np.insert', (['new_y_batch', '(0)', 'y_batch[i]'], {'axis': '(0)'}), '(new_y_batch, 0, y_batch[i], axis=0)\n', (8415, 8451), True, 'import numpy as np\n'), ((9190, 9213), 'numpy.reshape', 'np.reshape', (['results', '(-1)'], {}), '(results, -1)\n', (9200, 9213), True, 'import numpy as np\n'), ((9239, 9274), 'scipy.stats.rankdata', 'rankdata', (['results'], {'method': '"""ordinal"""'}), "(results, method='ordinal')\n", (9247, 9274), False, 'from scipy.stats import rankdata\n'), ((8598, 8642), 'numpy.append', 'np.append', (['new_x_batch', '[x_batch[i]]'], {'axis': '(0)'}), '(new_x_batch, [x_batch[i]], axis=0)\n', (8607, 8642), True, 'import numpy as np\n'), ((8665, 8709), 'numpy.append', 'np.append', (['new_y_batch', '[y_batch[i]]'], {'axis': '(0)'}), '(new_y_batch, [y_batch[i]], axis=0)\n', (8674, 8709), True, 'import numpy as np\n')]
#%% import matplotlib.pyplot as plt from numpy import sin, pi from cmath import phase import os def stringToComplex(s): s = s.replace('\n', '') s = s.replace('j', '') s = s.replace(' ', '') real, imag = tuple( s.split('+') ) real, imag = float(real), float(imag) return complex(real, imag) def f(x): y = [(1/n) * sin(2*pi*100*n*x) for n in range(1, 10, 2)] return sum(y) #%% n = 2**12 data = [ f(t/n) for t in range(n) ] plt.figure(figsize = (12, 5)) plt.plot(data) plt.grid() plt.savefig('images/input.png', dpi=300) plt.show() python_dir = os.path.dirname(__file__) input_path = os.path.join(python_dir, "data/input.txt") output_path = os.path.join(python_dir, "data/output.txt") buildandrun_path = os.path.join(python_dir, "BuildAndRun.bat") with open(input_path, "w+") as file: file.write(str(n) + '\n') for x in data: file.write(str(x) + '\n') #%% os.system(buildandrun_path) #%% with open(output_path, "r") as file: data.clear() for x in file.readlines(): data.append( stringToComplex(x) ) fig, (ax1, ax2) = plt.subplots(2, 1, figsize = (12, 8)) ax1.plot([abs(x) for x in data]) ax1.set_title('Valor absoluto') ax1.grid() ax2.plot([phase(x) for x in data]) ax2.set_title('Fase') ax2.grid() plt.tight_layout() plt.savefig('images/output.png', dpi=300) plt.show() # %%
[ "matplotlib.pyplot.tight_layout", "matplotlib.pyplot.show", "os.path.join", "matplotlib.pyplot.plot", "cmath.phase", "os.path.dirname", "os.system", "matplotlib.pyplot.subplots", "matplotlib.pyplot.figure", "numpy.sin", "matplotlib.pyplot.grid", "matplotlib.pyplot.savefig" ]
[((457, 484), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(12, 5)'}), '(figsize=(12, 5))\n', (467, 484), True, 'import matplotlib.pyplot as plt\n'), ((487, 501), 'matplotlib.pyplot.plot', 'plt.plot', (['data'], {}), '(data)\n', (495, 501), True, 'import matplotlib.pyplot as plt\n'), ((502, 512), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (510, 512), True, 'import matplotlib.pyplot as plt\n'), ((513, 553), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""images/input.png"""'], {'dpi': '(300)'}), "('images/input.png', dpi=300)\n", (524, 553), True, 'import matplotlib.pyplot as plt\n'), ((554, 564), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (562, 564), True, 'import matplotlib.pyplot as plt\n'), ((579, 604), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (594, 604), False, 'import os\n'), ((618, 660), 'os.path.join', 'os.path.join', (['python_dir', '"""data/input.txt"""'], {}), "(python_dir, 'data/input.txt')\n", (630, 660), False, 'import os\n'), ((675, 718), 'os.path.join', 'os.path.join', (['python_dir', '"""data/output.txt"""'], {}), "(python_dir, 'data/output.txt')\n", (687, 718), False, 'import os\n'), ((738, 781), 'os.path.join', 'os.path.join', (['python_dir', '"""BuildAndRun.bat"""'], {}), "(python_dir, 'BuildAndRun.bat')\n", (750, 781), False, 'import os\n'), ((908, 935), 'os.system', 'os.system', (['buildandrun_path'], {}), '(buildandrun_path)\n', (917, 935), False, 'import os\n'), ((1099, 1134), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)', '(1)'], {'figsize': '(12, 8)'}), '(2, 1, figsize=(12, 8))\n', (1111, 1134), True, 'import matplotlib.pyplot as plt\n'), ((1310, 1328), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (1326, 1328), True, 'import matplotlib.pyplot as plt\n'), ((1333, 1374), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""images/output.png"""'], {'dpi': '(300)'}), "('images/output.png', dpi=300)\n", (1344, 1374), True, 'import matplotlib.pyplot as plt\n'), ((1379, 1389), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1387, 1389), True, 'import matplotlib.pyplot as plt\n'), ((343, 368), 'numpy.sin', 'sin', (['(2 * pi * 100 * n * x)'], {}), '(2 * pi * 100 * n * x)\n', (346, 368), False, 'from numpy import sin, pi\n'), ((1239, 1247), 'cmath.phase', 'phase', (['x'], {}), '(x)\n', (1244, 1247), False, 'from cmath import phase\n')]
import numpy from matchms import Spectrum from matplotlib import pyplot as plt def test_spectrum_plot_with_histogram_unspecified(): mz = numpy.array([10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110], dtype="float") intensities = numpy.array([1, 1, 5, 5, 5, 5, 7, 7, 7, 9, 9], dtype="float") spectrum = Spectrum(mz=mz, intensities=intensities) fig = spectrum.plot() assert fig is not None assert hasattr(fig, "axes") assert isinstance(fig.axes, list) assert len(fig.axes) == 1 assert isinstance(fig.axes[0], plt.Axes) assert hasattr(fig.axes[0], "lines") assert isinstance(fig.axes[0].lines, list) assert len(fig.axes[0].lines) == 11 assert isinstance(fig.axes[0].lines[0], plt.Line2D) assert hasattr(fig.axes[0].lines[0], "_x") def test_spectrum_plot_with_histogram_false(): mz = numpy.array([10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110], dtype="float") intensities = numpy.array([1, 1, 5, 5, 5, 5, 7, 7, 7, 9, 9], dtype="float") spectrum = Spectrum(mz=mz, intensities=intensities) fig = spectrum.plot(with_histogram=False) assert fig is not None assert hasattr(fig, "axes") assert isinstance(fig.axes, list) assert len(fig.axes) == 1 assert isinstance(fig.axes[0], plt.Axes) assert hasattr(fig.axes[0], "lines") assert isinstance(fig.axes[0].lines, list) assert len(fig.axes[0].lines) == 11 assert isinstance(fig.axes[0].lines[0], plt.Line2D) assert hasattr(fig.axes[0].lines[0], "_x") def test_spectrum_plot_with_histogram_true(): mz = numpy.array([10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110], dtype="float") intensities = numpy.array([1, 1, 5, 5, 5, 5, 7, 7, 7, 9, 9], dtype="float") spectrum = Spectrum(mz=mz, intensities=intensities) fig = spectrum.plot(with_histogram=True) assert fig is not None assert hasattr(fig, "axes") assert isinstance(fig.axes, list) assert len(fig.axes) == 2 assert isinstance(fig.axes[0], plt.Axes) assert hasattr(fig.axes[0], "lines") assert isinstance(fig.axes[0].lines, list) assert len(fig.axes[0].lines) == 11 assert isinstance(fig.axes[0].lines[0], plt.Line2D) assert hasattr(fig.axes[0].lines[0], "_x") def test_spectrum_plot_with_histogram_true_and_intensity_limit(): mz = numpy.array([10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110], dtype="float") intensities = numpy.array([1, 1, 5, 5, 5, 5, 7, 7, 7, 9, 9], dtype="float") spectrum = Spectrum(mz=mz, intensities=intensities) fig = spectrum.plot(with_histogram=True, intensity_to=10.0) assert fig is not None assert hasattr(fig, "axes") assert isinstance(fig.axes, list) assert len(fig.axes) == 2 assert isinstance(fig.axes[0], plt.Axes) assert hasattr(fig.axes[0], "lines") assert isinstance(fig.axes[0].lines, list) assert len(fig.axes[0].lines) == 11 assert isinstance(fig.axes[0].lines[0], plt.Line2D) assert hasattr(fig.axes[0].lines[0], "_x") def test_spectrum_plot_with_histogram_true_and_expfit_true_and_intensity_limit(): mz = numpy.array([10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110], dtype="float") intensities = numpy.array([1, 1, 5, 5, 5, 5, 7, 7, 7, 9, 9], dtype="float") spectrum = Spectrum(mz=mz, intensities=intensities) fig = spectrum.plot(with_histogram=True, with_expfit=True, intensity_to=10.0) assert fig is not None assert hasattr(fig, "axes") assert isinstance(fig.axes, list) assert len(fig.axes) == 2 assert isinstance(fig.axes[0], plt.Axes) assert hasattr(fig.axes[0], "lines") assert isinstance(fig.axes[0].lines, list) assert len(fig.axes[0].lines) == 11 assert isinstance(fig.axes[0].lines[0], plt.Line2D) assert hasattr(fig.axes[0].lines[0], "_x")
[ "matchms.Spectrum", "numpy.array" ]
[((144, 218), 'numpy.array', 'numpy.array', (['[10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110]'], {'dtype': '"""float"""'}), "([10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110], dtype='float')\n", (155, 218), False, 'import numpy\n'), ((237, 298), 'numpy.array', 'numpy.array', (['[1, 1, 5, 5, 5, 5, 7, 7, 7, 9, 9]'], {'dtype': '"""float"""'}), "([1, 1, 5, 5, 5, 5, 7, 7, 7, 9, 9], dtype='float')\n", (248, 298), False, 'import numpy\n'), ((314, 354), 'matchms.Spectrum', 'Spectrum', ([], {'mz': 'mz', 'intensities': 'intensities'}), '(mz=mz, intensities=intensities)\n', (322, 354), False, 'from matchms import Spectrum\n'), ((845, 919), 'numpy.array', 'numpy.array', (['[10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110]'], {'dtype': '"""float"""'}), "([10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110], dtype='float')\n", (856, 919), False, 'import numpy\n'), ((938, 999), 'numpy.array', 'numpy.array', (['[1, 1, 5, 5, 5, 5, 7, 7, 7, 9, 9]'], {'dtype': '"""float"""'}), "([1, 1, 5, 5, 5, 5, 7, 7, 7, 9, 9], dtype='float')\n", (949, 999), False, 'import numpy\n'), ((1015, 1055), 'matchms.Spectrum', 'Spectrum', ([], {'mz': 'mz', 'intensities': 'intensities'}), '(mz=mz, intensities=intensities)\n', (1023, 1055), False, 'from matchms import Spectrum\n'), ((1565, 1639), 'numpy.array', 'numpy.array', (['[10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110]'], {'dtype': '"""float"""'}), "([10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110], dtype='float')\n", (1576, 1639), False, 'import numpy\n'), ((1658, 1719), 'numpy.array', 'numpy.array', (['[1, 1, 5, 5, 5, 5, 7, 7, 7, 9, 9]'], {'dtype': '"""float"""'}), "([1, 1, 5, 5, 5, 5, 7, 7, 7, 9, 9], dtype='float')\n", (1669, 1719), False, 'import numpy\n'), ((1735, 1775), 'matchms.Spectrum', 'Spectrum', ([], {'mz': 'mz', 'intensities': 'intensities'}), '(mz=mz, intensities=intensities)\n', (1743, 1775), False, 'from matchms import Spectrum\n'), ((2304, 2378), 'numpy.array', 'numpy.array', (['[10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110]'], {'dtype': '"""float"""'}), "([10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110], dtype='float')\n", (2315, 2378), False, 'import numpy\n'), ((2397, 2458), 'numpy.array', 'numpy.array', (['[1, 1, 5, 5, 5, 5, 7, 7, 7, 9, 9]'], {'dtype': '"""float"""'}), "([1, 1, 5, 5, 5, 5, 7, 7, 7, 9, 9], dtype='float')\n", (2408, 2458), False, 'import numpy\n'), ((2474, 2514), 'matchms.Spectrum', 'Spectrum', ([], {'mz': 'mz', 'intensities': 'intensities'}), '(mz=mz, intensities=intensities)\n', (2482, 2514), False, 'from matchms import Spectrum\n'), ((3078, 3152), 'numpy.array', 'numpy.array', (['[10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110]'], {'dtype': '"""float"""'}), "([10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110], dtype='float')\n", (3089, 3152), False, 'import numpy\n'), ((3171, 3232), 'numpy.array', 'numpy.array', (['[1, 1, 5, 5, 5, 5, 7, 7, 7, 9, 9]'], {'dtype': '"""float"""'}), "([1, 1, 5, 5, 5, 5, 7, 7, 7, 9, 9], dtype='float')\n", (3182, 3232), False, 'import numpy\n'), ((3248, 3288), 'matchms.Spectrum', 'Spectrum', ([], {'mz': 'mz', 'intensities': 'intensities'}), '(mz=mz, intensities=intensities)\n', (3256, 3288), False, 'from matchms import Spectrum\n')]
# third party import numpy as np import pytest # syft absolute from syft import deserialize from syft import serialize from syft.core.adp.entity import Entity from syft.core.tensor.tensor import Tensor gonzalo = Entity(name="Gonzalo") @pytest.fixture(scope="function") def x() -> Tensor: x = Tensor(np.array([[1, 2, 3], [4, 5, 6]])) x = x.private(min_val=-1, max_val=7, entity=gonzalo) return x @pytest.fixture(scope="function") def y() -> Tensor: y = Tensor(np.array([[-1, -2, -3], [-4, -5, -6]])) y = y.private(min_val=-7, max_val=1, entity=gonzalo) return y # # ######################### ADD ############################ # # MADHAVA: this needs fixing @pytest.mark.xfail def test_add(x: Tensor) -> None: z = x + x assert isinstance(z, Tensor), "Add: Result is not a Tensor" assert ( z.child.min_vals == 2 * x.child.min_vals ).all(), "(Add, Minval) Result is not correct" assert ( z.child.max_vals == 2 * x.child.max_vals ).all(), "(Add, Maxval) Result is not correct" # MADHAVA: this needs fixing @pytest.mark.xfail def test_single_entity_phi_tensor_serde(x: Tensor) -> None: blob = serialize(x.child) x2 = deserialize(blob) assert (x.child.min_vals == x2.min_vals).all() assert (x.child.max_vals == x2.max_vals).all() # def test_add(x,y): # z = x+y # assert isinstance(z, Tensor), "Add: Result is not a Tensor" # assert z.child.min_vals == x.child.min_vals + y.child.min_vals, "(Add, Minval) Result is not correct" # assert z.child.max_vals == x.child.max_vals + y.child.max_vals, "(Add, Maxval) Result is not correct" # # ######################### SUB ############################ # # def test_sub(x): # z=x-x # assert isinstance(z, Tensor), "Sub: Result is not a Tensor" # assert z.child.min_vals == 0 * x.child.min_vals, "(Sub, Minval) Result is not correct" # assert z.child.max_vals == 0 * x.child.max_vals, "(Sub, Maxval) Result is not correct" # # def test_sub(x,y): # z=x-y # assert isinstance(z, Tensor), "Sub: Result is not a Tensor" # assert z.child.min_vals == x.child.min_vals - y.child.min_vals, "(Sub, Minval) Result is not correct" # assert z.child.max_vals == x.child.max_vals - y.child.max_vals, "(Sub, Maxval) Result is not correct" # # ######################### MUL ############################ # # def test_mul(x): # z = x*x # assert isinstance(z, Tensor), "Mul: Result is not a Tensor" # assert z.child.min_vals == x.child.min_vals ** 2, "(Mul, Minval) Result is not correct" # assert z.child.max_vals == x.child.max_vals ** 2, "(Mul, Maxval) Result is not correct" # # def test_mul(x,y): # z = x*y # assert isinstance(z, Tensor), "Mul: Result is not a Tensor" # assert z.child.min_vals == x.child.min_vals ** 2, "(Mul, Minval) Result is not correct" # assert z.child.max_vals == x.child.max_vals ** 2, "(Mul, Maxval) Result is not correct"
[ "syft.deserialize", "syft.serialize", "pytest.fixture", "syft.core.adp.entity.Entity", "numpy.array" ]
[((214, 236), 'syft.core.adp.entity.Entity', 'Entity', ([], {'name': '"""Gonzalo"""'}), "(name='Gonzalo')\n", (220, 236), False, 'from syft.core.adp.entity import Entity\n'), ((240, 272), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""function"""'}), "(scope='function')\n", (254, 272), False, 'import pytest\n'), ((414, 446), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""function"""'}), "(scope='function')\n", (428, 446), False, 'import pytest\n'), ((1165, 1183), 'syft.serialize', 'serialize', (['x.child'], {}), '(x.child)\n', (1174, 1183), False, 'from syft import serialize\n'), ((1193, 1210), 'syft.deserialize', 'deserialize', (['blob'], {}), '(blob)\n', (1204, 1210), False, 'from syft import deserialize\n'), ((307, 339), 'numpy.array', 'np.array', (['[[1, 2, 3], [4, 5, 6]]'], {}), '([[1, 2, 3], [4, 5, 6]])\n', (315, 339), True, 'import numpy as np\n'), ((481, 519), 'numpy.array', 'np.array', (['[[-1, -2, -3], [-4, -5, -6]]'], {}), '([[-1, -2, -3], [-4, -5, -6]])\n', (489, 519), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- ''' Multiclass Budget Support Vector Machine under POM6 ''' __author__ = "<NAME>" __date__ = "Apr. 2021" import numpy as np from MMLL.models.Common_to_all_POMs import Common_to_all_POMs from transitions import State from transitions.extensions import GraphMachine from sklearn.metrics import roc_curve, auc from pympler import asizeof #asizeof.asizeof(my_object) import pickle import dill import time class Model(): """ Multiclass Budget Support Vector Machine. """ def __init__(self): self.C = None self.w_dict = {} self.sigma = None self.Csvm = None self.classes = None self.is_trained = False self.supported_formats = ['pkl'] t = time.time() seed = int((t - int(t)) * 10000) np.random.seed(seed=seed) def predict(self, X): """ Predicts outputs given the inputs Parameters ---------- X: ndarray Matrix with the input values Returns ------- prediction_values: ndarray """ NP = X.shape[0] NC = self.C.shape[0] XC2 = -2 * np.dot(X, self.C.T) XC2 += np.sum(np.multiply(X, X), axis=1).reshape((NP, 1)) XC2 += np.sum(np.multiply(self.C, self.C), axis=1).reshape((1, NC)) # Gauss KXC = np.exp(-XC2 / 2.0 / (self.sigma ** 2)) #1 ./ ( 1 + ((x).^2 / (2 * sigma ^2 ))); #KXC = 1 / (1 + (XC2 / 2.0 / (self.sigma ** 2) ) ) # bias KXC = np.hstack( (np.ones((NP, 1)), KXC)) preds_dict = {} NCLA = len(self.classes) O = [] for cla in self.classes: o = np.dot(KXC, self.w_dict[cla]).ravel() preds_dict.update({cla: o}) O.append(o) O = np.array(O) winners = list(np.argmax(O, axis=0)) o = np.array([self.classes[pos] for pos in winners]).ravel() return o def predict_soft(self, X): """ Predicts outputs given the inputs Parameters ---------- X: ndarray Matrix with the input values Returns ------- prediction_values: ndarray """ NP = X.shape[0] NC = self.C.shape[0] XC2 = -2 * np.dot(X, self.C.T) XC2 += np.sum(np.multiply(X, X), axis=1).reshape((NP, 1)) XC2 += np.sum(np.multiply(self.C, self.C), axis=1).reshape((1, NC)) # Gauss KXC = np.exp(-XC2 / 2.0 / (self.sigma ** 2)) #1 ./ ( 1 + ((x).^2 / (2 * sigma ^2 ))); #KXC = 1 / (1 + (XC2 / 2.0 / (self.sigma ** 2) ) ) # bias KXC = np.hstack( (np.ones((NP, 1)), KXC)) preds_dict = {} NCLA = len(self.classes) O = [] for cla in self.classes: o = np.dot(KXC, self.w_dict[cla]).ravel() preds_dict.update({cla: o}) O.append(o) O = np.array(O) winners = list(np.argmax(O, axis=0)) o = np.array([self.classes[pos] for pos in winners]).ravel() return preds_dict def save(self, filename=None): """ Saves the trained model to file. The valid file extensions are: - "pkl": saves the model as a Python3 pickle file Parameters ---------- filename: string path+filename """ if filename is None: print('=' * 80) print('Model Save Error: A valid filename must be provided, otherwise nothing is saved. The valid file extensions are:') print('\t - "pkl": saves the model as a Python3 pickle file') print('\t - "onnx": saves the model using Open Neural Network Exchange format (ONNX)') print('\t - "pmml": saves the model using Predictive Model Markup Language (PMML)') print('=' * 80) else: # Checking filename extension extension = filename.split('.')[-1] if extension not in self.supported_formats: print('=' * 80) print('Model Save Error: Unsupported format. The valid file extensions are:') print('\t - "pkl": saves the model as a Python3 pickle file') print('=' * 80) else: if not self.is_trained: print('=' * 80) print('Model Save Error: model not trained yet, nothing to save.') print('=' * 80) else: try: if extension == 'pkl': with open(filename, 'wb') as f: pickle.dump(self, f) print('=' * 80) print('Model saved at %s in pickle format.' %filename) print('=' * 80) except: print('=' * 80) print('Model Save Error: model cannot be saved at %s, please check the provided path/filename.' %filename) print('=' * 80) raise class MBSVM_Master(Common_to_all_POMs): """ This class implements the Multiclass Budget Support Vector Machine, run at Master node. It inherits from Common_to_all_POMs. """ def __init__(self, master_address, workers_addresses, model_type, comms, logger, verbose=True, **kwargs): """ Create a :class:`BSVM_Master` instance. Parameters ---------- master_address: string address of the master node workers_addresses: list of strings list of the addresses of the workers comms: comms object instance object providing communications logger: class:`logging.Logger` logging object instance verbose: boolean indicates if messages are print or not on screen kwargs: Keyword arguments. """ super().__init__() self.pom = 6 self.model_type = model_type self.name = self.model_type + '_Master' # Name self.master_address = master_address self.workers_addresses = workers_addresses self.epsilon = 0.00000001 # to avoid log(0) self.landa = 0.5 try: kwargs.update(kwargs['model_parameters']) del kwargs['model_parameters'] except Exception as err: pass self.process_kwargs(kwargs) # Convert workers_addresses -> '0', '1', + send_to dict self.broadcast_addresses = workers_addresses self.Nworkers = len(workers_addresses) # Nworkers self.workers_addresses = list(range(self.Nworkers)) self.workers_addresses = [str(x) for x in self.workers_addresses] self.send_to = {} self.receive_from = {} for k in range(self.Nworkers): self.send_to.update({str(k): workers_addresses[k]}) self.receive_from.update({workers_addresses[k]: str(k)}) self.logger = logger # logger self.comms = comms # comms lib self.verbose = verbose # print on screen when true self.NI = None self.state_dict = {} # dictionary storing the execution state for k in range(0, self.Nworkers): self.state_dict.update({self.workers_addresses[k]: ''}) # we extract the model_parameters as extra kwargs, to be all jointly processed try: kwargs.update(kwargs['model_parameters']) del kwargs['model_parameters'] except Exception as err: pass self.process_kwargs(kwargs) self.create_FSM_master() self.FSMmaster.master_address = master_address self.message_counter = 100 # used to number the messages self.cryptonode_address = None self.KTK_dict = {} self.KTy_dict = {} #self.NC = self.C.shape[0] self.NI = self.C.shape[1] self.newNI_dict = {} self.model = Model() self.model.C = self.C self.model.sigma = np.sqrt(self.NI) * self.fsigma self.model.Csvm = self.Csvm self.Kacum_dict = {} self.grady_dict = {} self.s0_dict = {} self.s1_dict = {} self.grads_dict = {} self.Ztr_dict = {} self.NPtr_dict = {} self.eps = 0.0000001 try: if self.target_data_description['NT'] == 1: if self.target_data_description['output_type'][0]['type'] == 'cat': self.classes = self.target_data_description['output_type'][0]['values'] else: self.display('Target values must be categorical (string)') sys.exit() else: self.display('The case with more than one target is not covered yet.') sys.exit() except Exception as err: self.display('The target_data_description is not well defined, please check.', str(err)) raise t = time.time() seed = int((t - int(t)) * 10000) np.random.seed(seed=seed) def create_FSM_master(self): """ Creates a Finite State Machine to be run at the Master Node Parameters ---------- None """ self.display(self.name + ': creating FSM') states_master = [ State(name='waiting_order', on_enter=['while_waiting_order']), State(name='update_tr_data', on_enter=['while_update_tr_data']), State(name='getting_KTK', on_enter=['while_getting_KTK']), State(name='selecting_C', on_enter=['while_selecting_C']), State(name='sending_C', on_enter=['while_sending_C']), State(name='computing_XTw', on_enter=['while_computing_XTw']), State(name='computing_oi', on_enter=['while_computing_oi']), State(name='updating_w', on_enter=['while_updating_w']) ] transitions_master = [ ['go_update_tr_data', 'waiting_order', 'update_tr_data'], ['go_waiting_order', 'update_tr_data', 'waiting_order'], ['go_selecting_C', 'waiting_order', 'selecting_C'], ['go_waiting_order', 'selecting_C', 'waiting_order'], ['go_sending_C', 'waiting_order', 'sending_C'], ['go_waiting_order', 'sending_C', 'waiting_order'], ['go_computing_oi', 'waiting_order', 'computing_oi'], ['go_waiting_order', 'computing_oi', 'waiting_order'], ['go_getting_KTK', 'waiting_order', 'getting_KTK'], ['go_waiting_order', 'getting_KTK', 'waiting_order'], ['go_computing_XTw', 'waiting_order', 'computing_XTw'], ['go_waiting_order', 'computing_XTw', 'waiting_order'], ['go_updating_w', 'waiting_order', 'updating_w'], ['go_waiting_order', 'updating_w', 'waiting_order'] ] class FSM_master(object): self.name = 'FSM_master' def while_waiting_order(self, MLmodel): MLmodel.display(MLmodel.name + ': WAITING for instructions...') return def while_update_tr_data(self, MLmodel): try: action = 'update_tr_data' data = {} packet = {'action': action, 'to': 'MLmodel', 'data': data, 'sender': MLmodel.master_address} message_id = MLmodel.master_address+'_'+str(MLmodel.message_counter) packet.update({'message_id': message_id}) MLmodel.message_counter += 1 size_bytes = asizeof.asizeof(dill.dumps(packet)) MLmodel.display('COMMS_MASTER_BROADCAST %s, id = %s, bytes=%s' % (action, message_id, str(size_bytes)), verbose=False) MLmodel.comms.broadcast(packet) MLmodel.display(MLmodel.name + ': broadcasted update_tr_data to all Workers') except Exception as err: raise ''' message = "ERROR: %s %s" % (str(err), str(type(err))) MLmodel.display('\n ' + '='*50 + '\n' + message + '\n ' + '='*50 + '\n' ) MLmodel.display('ERROR AT while_update_tr_data') import code code.interact(local=locals()) ''' return def while_selecting_C(self, MLmodel): try: action = 'selecting_C' data = {'C': MLmodel.model.C, 'sigma': MLmodel.model.sigma} packet = {'action': action, 'to': 'MLmodel', 'data': data, 'sender': MLmodel.master_address} message_id = MLmodel.master_address+'_'+str(MLmodel.message_counter) packet.update({'message_id': message_id}) MLmodel.message_counter += 1 size_bytes = asizeof.asizeof(dill.dumps(packet)) MLmodel.display('COMMS_MASTER_BROADCAST %s, id = %s, bytes=%s' % (action, message_id, str(size_bytes)), verbose=False) if MLmodel.selected_workers is None: MLmodel.comms.broadcast(packet) MLmodel.display(MLmodel.name + ': broadcasted C to all Workers') else: recipients = [MLmodel.send_to[w] for w in MLmodel.selected_workers] MLmodel.comms.broadcast(packet, recipients) MLmodel.display(MLmodel.name + ': broadcasted C to Workers: %s' % str([MLmodel.receive_from[w] for w in MLmodel.selected_workers])) except Exception as err: raise ''' print('ERROR AT while_selecting_C') import code code.interact(local=locals()) ''' return def while_sending_C(self, MLmodel): try: action = 'sending_C' data = {'C': MLmodel.model.C, 'sigma': MLmodel.model.sigma, 'Csvm': MLmodel.model.Csvm, 'classes': MLmodel.classes} packet = {'action': action, 'to': 'MLmodel', 'data': data, 'sender': MLmodel.master_address} message_id = MLmodel.master_address+'_'+str(MLmodel.message_counter) packet.update({'message_id': message_id}) MLmodel.message_counter += 1 size_bytes = asizeof.asizeof(dill.dumps(packet)) MLmodel.display('COMMS_MASTER_BROADCAST %s, id = %s, bytes=%s' % (action, message_id, str(size_bytes)), verbose=False) if MLmodel.selected_workers is None: MLmodel.comms.broadcast(packet) MLmodel.display(MLmodel.name + ': broadcasted C to all Workers') else: recipients = [MLmodel.send_to[w] for w in MLmodel.selected_workers] MLmodel.comms.broadcast(packet, recipients) MLmodel.display(MLmodel.name + ': broadcasted C to Workers: %s' % str([MLmodel.receive_from[w] for w in MLmodel.selected_workers])) except Exception as err: raise ''' print('ERROR AT while_sending_C') import code code.interact(local=locals()) ''' return def while_computing_XTw(self, MLmodel): try: #action = 'computing_XTw' MLmodel.ACxaxb_dict = {} xaxbP_dict = {} for cla in MLmodel.classes: MLmodel.display('PROC_MASTER_START', verbose=False) MLmodel.x = MLmodel.model.w_dict[cla].T NItrain = MLmodel.x.shape[1] K = int(NItrain / 2) # Guardar tmp_dict = {} tmp_dict.update({'A': np.random.uniform(-10, 10, K).reshape((1, K))}) tmp_dict.update({'C': np.random.uniform(-10, 10, K).reshape((1, K))}) tmp_dict.update({'xa': MLmodel.x[:, 0:K]}) tmp_dict.update({'xb': MLmodel.x[:, K:]}) MLmodel.ACxaxb_dict.update({cla: tmp_dict}) # Enviar #xa_ = MLmodel.xa + MLmodel.A #xb_ = MLmodel.xb + MLmodel.C #P = MLmodel.A + MLmodel.C # warning, check the sum is nonzero (low prob...) tmp_dict = {} tmp_dict.update({'xa_': MLmodel.ACxaxb_dict[cla]['xa'] + MLmodel.ACxaxb_dict[cla]['A']}) tmp_dict.update({'xb_': MLmodel.ACxaxb_dict[cla]['xb'] + MLmodel.ACxaxb_dict[cla]['C']}) tmp_dict.update({'P': MLmodel.ACxaxb_dict[cla]['A'] + MLmodel.ACxaxb_dict[cla]['C']}) xaxbP_dict.update({cla: tmp_dict}) MLmodel.display('PROC_MASTER_END', verbose=False) # broadcasts xaxbP_dict action = 'sending_xaxbP' data = {'xaxbP_dict': xaxbP_dict, 'classes': MLmodel.classes} del xaxbP_dict packet = {'action': action, 'to': 'MLmodel', 'data': data, 'sender': MLmodel.master_address} del data message_id = MLmodel.master_address+'_'+str(MLmodel.message_counter) packet.update({'message_id': message_id}) MLmodel.message_counter += 1 size_bytes = asizeof.asizeof(dill.dumps(packet)) MLmodel.display('COMMS_MASTER_BROADCAST %s, id = %s, bytes=%s' % (action, message_id, str(size_bytes)), verbose=False) if MLmodel.selected_workers is None: MLmodel.comms.broadcast(packet) MLmodel.display(MLmodel.name + ': computing_XTw with all Workers') else: recipients = [MLmodel.send_to[w] for w in MLmodel.selected_workers] MLmodel.comms.broadcast(packet, recipients) MLmodel.display(MLmodel.name + ': computing_XTw with Workers: %s' % str(MLmodel.selected_workers)) except Exception as err: raise ''' message = "ERROR: %s %s" % (str(err), str(type(err))) MLmodel.display('\n ' + '='*50 + '\n' + message + '\n ' + '='*50 + '\n' ) MLmodel.display('ERROR AT while_computing_XTw') import code code.interact(local=locals()) ''' return def while_computing_oi(self, MLmodel): # MLmodel.s0_dict, MLmodel.s1_dict try: MLmodel.o_dict = {} for addr in MLmodel.workers_addresses: MLmodel.display('PROC_MASTER_START', verbose=False) # We need to compute these and send them to every worker: Rzz_dict = {} rzt_dict = {} for cla in MLmodel.classes: #MLmodel.display('PROC_MASTER_START', verbose=False) U0 = MLmodel.s0_dict[addr]['ya_0_dict'][cla] * (MLmodel.ACxaxb_dict[cla]['xa'] + 2 * MLmodel.ACxaxb_dict[cla]['A']) + MLmodel.s0_dict[addr]['yb_0_dict'][cla] * (MLmodel.ACxaxb_dict[cla]['xb'] + 2 * MLmodel.ACxaxb_dict[cla]['C']) + MLmodel.s0_dict[addr]['Q0_dict'][cla] * (MLmodel.ACxaxb_dict[cla]['A'] + 2 * MLmodel.ACxaxb_dict[cla]['C']) u0 = np.sum(U0, axis=1) del U0 s0 = u0 + MLmodel.s0_dict[addr]['v0_dict'][cla] del u0 NPtr0 = s0.shape[0] y0 = -np.ones(NPtr0) e0 = y0 - s0 del s0 # Weighting values a a0 = np.ones(NPtr0) ey0 = e0 * y0 which0 = ey0 >= MLmodel.eps a0[which0] = 2 * MLmodel.Csvm / ey0[which0] which0 = ey0 < MLmodel.eps a0[which0] = 2 * MLmodel.Csvm / MLmodel.eps which0 = ey0 < 0 a0[which0] = 0 a0 = a0.reshape((-1, 1)) del ey0, e0, which0 Rzz0 = MLmodel.Ztr_dict[addr]['Ztr0_dict'][cla] * a0 rzt0 = np.dot(Rzz0.T, y0) Rzz0 = np.dot(Rzz0.T, MLmodel.Ztr_dict[addr]['Ztr0_dict'][cla]) del a0, y0 #U1 = MLmodel.s1_dict[addr]['ya_1'] * (MLmodel.xa + 2 * MLmodel.A) + MLmodel.s1_dict[addr]['yb_1'] * (MLmodel.xb + 2 * MLmodel.C) + MLmodel.s1_dict[addr]['Q1'] * (MLmodel.A + 2 * MLmodel.C) U1 = MLmodel.s1_dict[addr]['ya_1_dict'][cla] * (MLmodel.ACxaxb_dict[cla]['xa'] + 2 * MLmodel.ACxaxb_dict[cla]['A']) + MLmodel.s1_dict[addr]['yb_1_dict'][cla] * (MLmodel.ACxaxb_dict[cla]['xb'] + 2 * MLmodel.ACxaxb_dict[cla]['C']) + MLmodel.s1_dict[addr]['Q1_dict'][cla] * (MLmodel.ACxaxb_dict[cla]['A'] + 2 * MLmodel.ACxaxb_dict[cla]['C']) u1 = np.sum(U1, axis=1) del U1 s1 = u1 + MLmodel.s1_dict[addr]['v1_dict'][cla] del u1 NPtr1 = s1.shape[0] y1 = np.ones(NPtr1) e1 = y1 - s1 del s1 # Weighting values a a1 = np.ones(NPtr1) ey1 = e1 * y1 which1 = ey1 >= MLmodel.eps a1[which1] = 2 * MLmodel.Csvm / ey1[which1] which1 = ey1 < MLmodel.eps a1[which1] = 2 * MLmodel.Csvm / MLmodel.eps which1 = ey1 < 0 a1[which1] = 0 a1 = a1.reshape((-1, 1)) del ey1, e1, which1 Rzz1 = MLmodel.Ztr_dict[addr]['Ztr1_dict'][cla] * a1 rzt1 = np.dot(Rzz1.T, y1) Rzz1 = np.dot(Rzz1.T, MLmodel.Ztr_dict[addr]['Ztr1_dict'][cla]) del a1, y1 Rzz_dict.update({cla: Rzz0 + Rzz1}) rzt_dict.update({cla: rzt0 + rzt1}) # Needed ? #MLmodel.NPtr_dict.update({addr: NPtr0 + NPtr1}) MLmodel.display('PROC_MASTER_END', verbose=False) action = 'sending_Rzz_rzt' data = {'Rzz_dict': Rzz_dict, 'rzt_dict': rzt_dict} #del Rzz0, Rzz1, rzt0, rzt1 packet = {'action': action, 'to': 'MLmodel', 'data': data, 'sender': MLmodel.master_address} del data message_id = MLmodel.master_address+'_'+str(MLmodel.message_counter) packet.update({'message_id': message_id}) MLmodel.message_counter += 1 size_bytes = asizeof.asizeof(dill.dumps(packet)) MLmodel.display('COMMS_MASTER_SEND %s to %s, id = %s, bytes=%s' % (action, addr, message_id, str(size_bytes)), verbose=False) MLmodel.comms.send(packet, MLmodel.send_to[addr]) #del packet, size_bytes, message_id del packet MLmodel.display(MLmodel.name + ' %s: sent sending_Rzz to %s' % (str(MLmodel.master_address), str(addr))) #del MLmodel.xa, MLmodel.xb, MLmodel.A, MLmodel.C except: raise ''' print('ERROR AT while_computing_oi') import code code.interact(local=locals()) ''' return def while_getting_KTK(self, MLmodel): try: action = 'compute_KTK' data = {'w': MLmodel.model.w} packet = {'action': action, 'to': 'MLmodel', 'data': data, 'sender': MLmodel.master_address} message_id = MLmodel.master_address+'_'+str(MLmodel.message_counter) packet.update({'message_id': message_id}) MLmodel.message_counter += 1 size_bytes = asizeof.asizeof(dill.dumps(packet)) MLmodel.display('COMMS_MASTER_BROADCAST %s, id = %s, bytes=%s' % (action, message_id, str(size_bytes)), verbose=False) if MLmodel.selected_workers is None: MLmodel.comms.broadcast(packet) MLmodel.display(MLmodel.name + ': broadcasted compute_KTK to all workers') else: recipients = [MLmodel.send_to[w] for w in MLmodel.selected_workers] MLmodel.comms.broadcast(packet, recipients) MLmodel.display(MLmodel.name + ': broadcasted compute_KTK to Workers: %s' % str([MLmodel.receive_from[w] for w in MLmodel.selected_workers])) except Exception as err: raise ''' print('ERROR AT while_getting_KTK') import code code.interact(local=locals()) ''' return def while_updating_w(self, MLmodel): MLmodel.display('PROC_MASTER_START', verbose=False) MLmodel.w_old_dict = dict(MLmodel.model.w_dict) try: MLmodel.w_new_dict = {} for cla in MLmodel.classes: MLmodel.KTK_accum = np.zeros((MLmodel.NItrain, MLmodel.NItrain)) MLmodel.KTy_accum = np.zeros((MLmodel.NItrain, 1)) for waddr in MLmodel.workers_addresses: MLmodel.KTK_accum += MLmodel.KTK_dict[waddr][cla] MLmodel.KTy_accum += MLmodel.KTy_dict[waddr][cla].reshape((-1, 1)) #MLmodel.model.w_dict[cla] = np.dot(np.linalg.inv(MLmodel.KTK_accum + MLmodel.Kcc), MLmodel.KTy_accum) MLmodel.w_new_dict[cla] = np.dot(np.linalg.inv(MLmodel.KTK_accum + MLmodel.Kcc), MLmodel.KTy_accum) MLmodel.display('PROC_MASTER_END', verbose=False) except Exception as err: raise ''' print('ERROR AT while_updating_w') import code code.interact(local=locals()) ''' return def while_Exit(self, MLmodel): #print('while_Exit') return self.FSMmaster = FSM_master() self.grafmachine_master = GraphMachine(model=self.FSMmaster, states=states_master, transitions=transitions_master, initial='waiting_order', show_auto_transitions=False, # default value is False title="Finite State Machine modelling the behaviour of the master", show_conditions=False) return def reset(self, NI): """ Create some empty variables needed by the Master Node Parameters ---------- NI: integer Number of input features """ self.NI = NI self.model.w = np.random.normal(0, 0.001, (self.NI + 1, 1)) # weights in plaintext, first value is bias self.w_old = np.random.normal(0, 1.0, (self.NI + 1, 1)) self.XTDaX_accum = np.zeros((self.NI + 1, self.NI + 1)) # Cov. matrix in plaintext self.XTDast_accum = np.zeros((self.NI + 1, 1)) # Cov. matrix in plaintext self.preds_dict = {} # dictionary storing the prediction errors self.XTX_dict = {} self.XTy_dict = {} self.display(self.name + ': Resetting local data') def train_Master(self): """ This is the main training loop, it runs the following actions until the stop condition is met: - Update the execution state - Process the received packets - Perform actions according to the state Parameters ---------- None """ self.display(self.name + ': Starting training') self.display('MASTER_INIT', verbose=False) self.FSMmaster.go_update_tr_data(self) self.run_Master() self.display('PROC_MASTER_START', verbose=False) # Checking the new NI values newNIs = list(set(list(self.newNI_dict.values()))) if len(newNIs) > 1: message = 'ERROR: the training data has different number of features...' self.display(message) self.display(list(self.newNI_dict.values())) raise Exception(message) else: self.reset(newNIs[0]) ## Adding bias to validation data, if any #if self.Xval_b is not None: # self.Xval_b = self.add_bias(self.Xval_b).astype(float) # self.yval = self.yval.astype(float) ''' self.FSMmaster.go_selecting_C(self) self.run_Master() # Selecting centroids with largest projection Ncandidates = self.C.shape[0] Kacum_total = np.zeros(Ncandidates) for addr in self.workers_addresses: Kacum_total += self.Kacum_dict[addr].ravel() index = np.argsort(-Kacum_total) self.C = self.C[index[0: self.NC], :] ''' self.model.C = self.C self.NC = self.C.shape[0] # computing Kcc, only once X = self.model.C XC2 = -2 * np.dot(X, self.model.C.T) XC2 += np.sum(np.multiply(X, X), axis=1).reshape((self.NC, 1)) XC2 += np.sum(np.multiply(self.model.C, self.model.C), axis=1).reshape((1, self.NC)) KCC = np.exp(-XC2 / 2.0 / (self.model.sigma ** 2)) self.Kcc = np.zeros((self.NC + 1, self.NC + 1)) self.Kcc[1:, 1:] = KCC self.Kcc[0, 0] = 0.00001 self.Bob_data_s = False self.Bob_data_grad = False self.NI = self.NC + 1 # Checking dimensions if int(self.NI / 2) != self.NI / 2: # add one value self.w_orig_size = self.NI self.NItrain = self.NI + 1 # Adding row and column to Kcc self.Kcc = np.hstack((self.Kcc, np.zeros((self.NI, 1)))) self.Kcc = np.vstack((self.Kcc, np.zeros((1, self.NI + 1)))) self.Kcc[self.NI, self.NI] = 1.0 else: self.w_orig_size = self.NI self.NItrain = self.NI # Computing and storing KXC_val if self.Xval is not None: XC2 = -2 * np.dot(self.Xval, self.C.T) XC2 += np.sum(np.multiply(self.Xval, self.Xval), axis=1).reshape((-1, 1)) XC2 += np.sum(np.multiply(self.C, self.C), axis=1).reshape((1, self.NC)) # Gauss KXC_val = np.exp(-XC2 / 2.0 / (self.model.sigma ** 2)) self.KXC_val = np.hstack( (np.ones((self.Xval.shape[0], 1)), KXC_val)) # NP_val x NC + 1 #self.yval.astype(float).reshape((-1, 1)) self.stop_training = False self.kiter = 0 self.display('PROC_MASTER_END', verbose=False) self.FSMmaster.go_sending_C(self) self.run_Master() self.ceval_acum = 100 # Checking dimensions if int(self.NI / 2) != self.NI / 2: # add one value self.w_orig_size = self.NI self.NItrain = self.NI + 1 else: self.w_orig_size = self.NI self.NItrain = self.NI self.model.w_dict = {} self.w_old_dict = {} self.model.classes = self.classes for cla in self.classes: self.model.w_dict.update({cla: np.random.normal(0, 0.001, (self.NItrain, 1))}) self.w_old_dict.update({cla: np.random.normal(0, 0.001, (self.NItrain, 1))}) self.ACC_val = 0 self.ACC_val_old = 0 while not self.stop_training: self.display('MASTER_ITER_START', verbose=False) self.FSMmaster.go_computing_XTw(self) self.run_Master() # We receive self.s_dict, self.Ztr_dict (once) self.FSMmaster.go_computing_oi(self) self.run_Master() # Updating w self.FSMmaster.go_updating_w(self) self.FSMmaster.go_waiting_order(self) self.display('PROC_MASTER_START', verbose=False) self.kiter += 1 # Stop if Maxiter is reached if self.kiter == self.Nmaxiter: self.stop_training = True if self.Xval is None: # A validation set is not provided for cla in self.classes: self.model.w_dict[cla] = (1 - self.landa) * self.w_old_dict[cla] + self.landa * self.w_new_dict[cla] inc_w = 0 for cla in self.classes: inc_w += np.linalg.norm(self.model.w_dict[cla] - self.w_old_dict[cla]) / np.linalg.norm(self.w_old_dict[cla]) message = 'Maxiter = %d, iter = %d, inc_w = %f' % (self.Nmaxiter, self.kiter, inc_w) #self.display(message) print(message) if inc_w <= self.conv_stop: self.stop_training = True else: self.ceval_acum_old = self.ceval_acum NIval = self.KXC_val.shape[1] O = [] for cla in self.classes: #w_ = self.model.w_dict[cla][0: NIval] w_ = ((1 - self.landa) * self.w_old_dict[cla] + self.landa * self.w_new_dict[cla])[0: NIval] o_val = np.dot(self.KXC_val, w_).ravel() O.append(o_val) O = np.array(O) winners = list(np.argmax(O, axis=0)) preds_val = np.array([self.classes[pos] for pos in winners]).ravel() ACC_val = np.mean(preds_val.ravel() == self.yval) if ACC_val > self.ACC_val_old: # retain the new for cla in self.classes: self.model.w_dict[cla] = (1 - self.landa) * self.w_old_dict[cla] + self.landa * self.w_new_dict[cla] self.ACC_val_old = ACC_val message = 'Maxiter = %d, iter = %d, ACC val = %f' % (self.Nmaxiter, self.kiter, ACC_val) print(message) else: # restore the previous one and stop self.model.w_dict = dict(self.w_old_dict) self.stop_training = True ''' self.ceval_acum = 0 for cla in self.classes: yval = np.array(self.yval == cla).astype(float).reshape((-1, 1)) w_ = self.model.w_dict[cla][0: NIval] w_old_ = self.w_old_dict[cla][0: NIval] CE_val = [] landas = np.arange(0, 1.0, 0.001) Xw = np.dot(self.KXC_val, w_) Xw_old = np.dot(self.KXC_val, w_old_) for landa in landas: w_tmp = landa * w_ + (1 - landa) * w_old_ o_tmp = landa * Xw + (1 - landa) * Xw_old ce_val = np.mean(self.cross_entropy(self.sigm(o_tmp), yval, self.epsilon)) CE_val.append(ce_val) min_pos = np.argmin(CE_val) CEval_opt = CE_val[min_pos] indices = np.array(range(len(landas)))[CE_val == CEval_opt] min_pos = indices[0] # first landa_opt = landas[min_pos] self.ceval_acum += CEval_opt self.model.w_dict[cla] = (1.0 - landa_opt) * self.w_old_dict[cla] + landa_opt * self.model.w_dict[cla] message = 'Class = %s, landa_opt = %f' % (cla, landa_opt) self.display(message) self.ceval_acum = self.ceval_acum / len(self.classes) if self.ceval_acum < self.ceval_acum_old: message = 'Maxiter = %d, iter = %d, CE val = %f' % (self.Nmaxiter, self.kiter, self.ceval_acum) print(message) self.w_old_dict = dict(self.model.w_dict) else: self.stop_training = True # We retain the last weight values self.model.w_dict = dict(self.w_old_dict) ''' self.display('PROC_MASTER_END', verbose=False) self.display('MASTER_ITER_END', verbose=False) self.display(self.name + ': Training is done') self.model.niter = self.kiter self.model.is_trained = True # reduciendo a dimensiรณn original for cla in self.classes: self.model.w_dict[cla] = self.model.w_dict[cla][0:self.w_orig_size, :] self.display('MASTER_FINISH', verbose=False) def Update_State_Master(self): """ We update control the flow given some conditions and parameters Parameters ---------- None """ if self.chekAllStates('ACK_update_tr_data'): self.FSMmaster.go_waiting_order(self) if self.chekAllStates('ACK_projecting_C'): self.FSMmaster.go_waiting_order(self) if self.chekAllStates('ACK_storing_C'): self.FSMmaster.go_waiting_order(self) if self.chekAllStates('ACK_sending_s'): if not self.Bob_data_s: self.Bob_data_s = True self.FSMmaster.go_waiting_order(self) if self.chekAllStates('ACK_sending_KTK'): self.FSMmaster.go_waiting_order(self) def ProcessReceivedPacket_Master(self, packet, sender): """ Process the received packet at Master and take some actions, possibly changing the state Parameters ---------- packet: packet object packet received (usually a dict with various content) sender: string id of the sender """ if packet is not None: try: #sender = packet['sender'] sender = self.receive_from[packet['sender']] if packet['action'][0:3] == 'ACK': self.display(self.name + ': received ACK from %s: %s' % (str(sender), packet['action'])) self.state_dict[sender] = packet['action'] try: self.display('COMMS_MASTER_RECEIVED %s from %s, id=%s' % (packet['action'], sender, str(packet['message_id'])), verbose=False) except: self.display('MASTER MISSING message_id in %s from %s' % (packet['action'], sender), verbose=False) pass if packet['action'] == 'ACK_update_tr_data': self.newNI_dict.update({sender: packet['data']['newNI']}) if packet['action'] == 'ACK_projecting_C': self.Kacum_dict.update({sender: packet['data']['Kacum']}) if packet['action'] == 'ACK_sending_s': if not self.Bob_data_s: self.s0_dict.update({sender: {'ya_0_dict': packet['data']['ya_0_dict'], 'yb_0_dict': packet['data']['yb_0_dict'], 'Q0_dict': packet['data']['Q0_dict'], 'v0_dict': packet['data']['v0_dict']}}) self.s1_dict.update({sender: {'ya_1_dict': packet['data']['ya_1_dict'], 'yb_1_dict': packet['data']['yb_1_dict'], 'Q1_dict': packet['data']['Q1_dict'], 'v1_dict': packet['data']['v1_dict']}}) self.Ztr_dict.update({sender: {'Ztr0_dict': packet['data']['Ztr0_dict'], 'Ztr1_dict': packet['data']['Ztr1_dict']}}) else: self.s0_dict[sender]['v0_dict'] = packet['data']['v0_dict'] self.s1_dict[sender]['v1_dict'] = packet['data']['v1_dict'] if packet['action'] == 'ACK_sending_KTK': self.KTK_dict.update({sender: packet['data']['KTK_dict']}) self.KTy_dict.update({sender: packet['data']['KTy_dict']}) except Exception as err: raise ''' print('ERROR AT ProcessReceivedPacket_Master') import code code.interact(local=locals()) ''' return #=============================================================== # Worker #=============================================================== class MBSVM_Worker(Common_to_all_POMs): ''' Class implementing Multiclass Budget Support Vector Machine, run at Worker ''' def __init__(self, master_address, worker_address, model_type, comms, logger, verbose=True, Xtr_b=None, ytr=None): """ Create a :class:`BSVM_Worker` instance. Parameters ---------- master_address: string address of the master node worker_address: string id of this worker model_type: string type of ML model comms: comms object instance object providing communications logger: class:`logging.Logger` logging object instance verbose: boolean indicates if messages are print or not on screen Xtr_b: ndarray 2-D numpy array containing the input training patterns ytr: ndarray 1-D numpy array containing the target training values """ self.pom = 6 self.master_address = master_address self.worker_address = worker_address # The id of this Worker #self.workers_addresses = workers_addresses # The id of this Worker self.model_type = model_type self.comms = comms # The comms library self.logger = logger # logger self.name = model_type + '_Worker' # Name self.verbose = verbose # print on screen when true self.Xtr_b = Xtr_b self.ytr = ytr self.NPtr = len(ytr) self.w = None self.create_FSM_worker() self.message_id = 0 # used to number the messages self.eps = 0.0000001 self.Bob_data_s = False self.Bob_data_grad = False self.message_counter = 100 t = time.time() seed = int((t - int(t)) * 10000) np.random.seed(seed=seed) def create_FSM_worker(self): """ Creates a Finite State Machine to be run at the Worker Node Parameters ---------- None """ self.name = 'FSM_worker' self.display(self.name + ' %s: creating FSM' % (str(self.worker_address))) class FSM_worker(object): name = 'FSM_worker' def while_waiting_order(self, MLmodel): MLmodel.display(MLmodel.name + ' %s: WAITING for instructions...' % (str(MLmodel.worker_address))) return def while_setting_tr_data(self, MLmodel, packet): try: NPtr, newNI = MLmodel.Xtr_b.shape #MLmodel.Xtr_b = MLmodel.add_bias(MLmodel.Xtr_b).astype(float) #MLmodel.ytr = MLmodel.ytr.astype(float) action = 'ACK_update_tr_data' data = {'newNI': newNI} packet = {'action': action, 'data': data, 'sender': MLmodel.worker_address} message_id = 'worker_' + MLmodel.worker_address + '_' + str(MLmodel.message_counter) packet.update({'message_id': message_id}) MLmodel.message_counter += 1 size_bytes = asizeof.asizeof(dill.dumps(packet)) MLmodel.display('COMMS_WORKER_SEND %s to %s, id = %s, bytes=%s' % (action, MLmodel.master_address, message_id, str(size_bytes)), verbose=False) MLmodel.comms.send(packet, MLmodel.master_address) MLmodel.display(MLmodel.name + ' %s: sent ACK_update_tr_data' % (str(MLmodel.worker_address))) except Exception as err: raise ''' message = "ERROR: %s %s" % (str(err), str(type(err))) MLmodel.display('\n ' + '='*50 + '\n' + message + '\n ' + '='*50 + '\n' ) import code code.interact(local=locals()) #MLmodel.display('ERROR AT while_computing_XTDaX') ''' def while_projecting_C(self, MLmodel, packet): # We project X over C and return accumulated try: MLmodel.display('PROC_WORKER_START', verbose=False) MLmodel.C = packet['data']['C'] NC = MLmodel.C.shape[0] MLmodel.sigma = packet['data']['sigma'] NI = MLmodel.Xtr_b.shape[1] NP = MLmodel.Xtr_b.shape[0] #MLmodel.sigma = np.sqrt(NI) * MLmodel.fsigma X = MLmodel.Xtr_b XC2 = -2 * np.dot(X, MLmodel.C.T) XC2 += np.sum(np.multiply(X, X), axis=1).reshape((NP, 1)) XC2 += np.sum(np.multiply(MLmodel.C, MLmodel.C), axis=1).reshape((1, NC)) # Gauss KXC = np.exp(-XC2 / 2.0 / (MLmodel.sigma ** 2)) #Kacum contains the number of closest patterns winners = list(np.argmax(KXC, axis=1)) Kacum = np.zeros((NC, 1)) for kc in range(NC): Kacum[kc] = winners.count(kc) #Kacum = np.sum(KXC, axis = 0) MLmodel.display('PROC_WORKER_END', verbose=False) action = 'ACK_projecting_C' data = {'Kacum': Kacum} packet = {'action': action, 'data': data, 'sender': MLmodel.worker_address} message_id = 'worker_' + MLmodel.worker_address + '_' + str(MLmodel.message_counter) packet.update({'message_id': message_id}) MLmodel.message_counter += 1 size_bytes = asizeof.asizeof(dill.dumps(packet)) MLmodel.display('COMMS_WORKER_SEND %s to %s, id = %s, bytes=%s' % (action, MLmodel.master_address, message_id, str(size_bytes)), verbose=False) MLmodel.comms.send(packet, MLmodel.master_address) MLmodel.display(MLmodel.name + ' %s: sent ACK_projecting_C' % (str(MLmodel.worker_address))) except Exception as err: raise ''' print('ERROR AT while_projecting_C') import code code.interact(local=locals()) ''' return def while_storing_C(self, MLmodel, packet): # We store C and compute KXC try: MLmodel.display('PROC_WORKER_START', verbose=False) MLmodel.C = packet['data']['C'] MLmodel.Csvm = packet['data']['Csvm'] MLmodel.classes = packet['data']['classes'] NC = MLmodel.C.shape[0] MLmodel.sigma = packet['data']['sigma'] NI = MLmodel.Xtr_b.shape[1] NP = MLmodel.Xtr_b.shape[0] #MLmodel.sigma = np.sqrt(NI) * MLmodel.fsigma X = MLmodel.Xtr_b XC2 = -2 * np.dot(X, MLmodel.C.T) XC2 += np.sum(np.multiply(X, X), axis=1).reshape((NP, 1)) XC2 += np.sum(np.multiply(MLmodel.C, MLmodel.C), axis=1).reshape((1, NC)) # Gauss KXC = np.exp(-XC2 / 2.0 / (MLmodel.sigma ** 2)) # Poly #KXC = 1 / (1 + (XC2 / 2.0 / (MLmodel.sigma ** 2) ) ) MLmodel.KXC = np.hstack( (np.ones((NP, 1)), KXC)) # NP x NC + 1 print('KXC min max', np.min(MLmodel.KXC), np.max(MLmodel.KXC)) # Checking NI NI = MLmodel.KXC.shape[1] NPtr = MLmodel.KXC.shape[0] if NI/2 != int(NI/2): MLmodel.KXC = np.hstack((MLmodel.KXC, np.random.normal(0, 0.01, (MLmodel.NPtr, 1)))) MLmodel.NPtr_train = MLmodel.KXC.shape[0] MLmodel.NI_train = MLmodel.KXC.shape[1] # RMD MLmodel.Cmat_dict = {} MLmodel.Dmat_dict = {} MLmodel.Ztr0_dict = {} MLmodel.Ztr1_dict = {} for cla in MLmodel.classes: MLmodel.Cmat_dict.update({cla: np.random.normal(0, 1, (MLmodel.NI_train, MLmodel.NI_train))}) MLmodel.Dmat_dict.update({cla: np.linalg.inv(MLmodel.Cmat_dict[cla])}) ytr = np.array(MLmodel.ytr == cla).astype(float).reshape((-1, 1)) which0 = (ytr == 0).ravel() MLmodel.Ztr0_dict.update({cla: np.dot(MLmodel.KXC[which0, :], MLmodel.Cmat_dict[cla])}) which1 = (ytr == 1).ravel() MLmodel.Ztr1_dict.update({cla: np.dot(MLmodel.KXC[which1, :], MLmodel.Cmat_dict[cla])}) MLmodel.display('PROC_WORKER_END', verbose=False) action = 'ACK_storing_C' data = {} packet = {'action': action, 'data': data, 'sender': MLmodel.worker_address} message_id = 'worker_' + MLmodel.worker_address + '_' + str(MLmodel.message_counter) packet.update({'message_id': message_id}) MLmodel.message_counter += 1 size_bytes = asizeof.asizeof(dill.dumps(packet)) MLmodel.display('COMMS_WORKER_SEND %s to %s, id = %s, bytes=%s' % (action, MLmodel.master_address, message_id, str(size_bytes)), verbose=False) MLmodel.comms.send(packet, MLmodel.master_address) MLmodel.display(MLmodel.name + ' %s: sent ACK_storing_C' % (str(MLmodel.worker_address))) except Exception as err: raise ''' print('ERROR AT while_storing_C') import code code.interact(local=locals()) ''' def while_computing_s(self, MLmodel, packet): try: MLmodel.display('PROC_WORKER_START', verbose=False) MLmodel.classes = packet['data']['classes'] if not MLmodel.Bob_data_s: NI_train = MLmodel.KXC.shape[1] NPtr_train = MLmodel.Xtr_b.shape[0] # MLmodel.Cmat_dict # MLmodel.Dmat_dict # MLmodel.Ztr0_dict # MLmodel.Ztr1_dict K = int(NI_train / 2) MLmodel.yas0_dict = {} MLmodel.yas1_dict = {} MLmodel.ybs0_dict = {} MLmodel.ybs1_dict = {} MLmodel.Bs0_dict = {} MLmodel.Ds0_dict = {} MLmodel.Bs1_dict = {} MLmodel.Ds1_dict = {} # Send once MLmodel.Qs0_dict = {} MLmodel.Qs1_dict = {} MLmodel.ya_s0_dict = {} MLmodel.yb_s0_dict = {} MLmodel.ya_s1_dict = {} MLmodel.yb_s1_dict = {} for cla in MLmodel.classes: ytr = np.array(MLmodel.ytr == cla).astype(float).reshape((-1, 1)) which0 = (ytr == 0).ravel() NPtr0 = np.sum(which0) which1 = (ytr == 1).ravel() NPtr1 = np.sum(which1) aux = MLmodel.KXC[:, 0:K] MLmodel.yas0_dict.update({cla: aux[which0, :]}) MLmodel.yas1_dict.update({cla: aux[which1, :]}) aux = MLmodel.KXC[:, K:] MLmodel.ybs0_dict.update({cla: aux[which0, :]}) MLmodel.ybs1_dict.update({cla: aux[which1, :]}) MLmodel.Bs0_dict.update({cla: np.random.uniform(-10, 10, (NPtr0, K))}) MLmodel.Ds0_dict.update({cla: np.random.uniform(-10, 10, (NPtr0, K))}) MLmodel.Bs1_dict.update({cla: np.random.uniform(-10, 10, (NPtr1, K))}) MLmodel.Ds1_dict.update({cla: np.random.uniform(-10, 10, (NPtr1, K))}) # Send once #MLmodel.Qs = MLmodel.Bs - MLmodel.Ds # warning, check the sum is nonzero (low prob...) MLmodel.Qs0_dict.update({cla: MLmodel.Bs0_dict[cla] - MLmodel.Ds0_dict[cla]}) MLmodel.Qs1_dict.update({cla: MLmodel.Bs1_dict[cla] - MLmodel.Ds1_dict[cla]}) #MLmodel.ya_s = MLmodel.Bs - MLmodel.yas MLmodel.ya_s0_dict.update({cla: MLmodel.Bs0_dict[cla] - MLmodel.yas0_dict[cla]}) MLmodel.ya_s1_dict.update({cla: MLmodel.Bs1_dict[cla] - MLmodel.yas1_dict[cla]}) #MLmodel.yb_s = MLmodel.Ds - MLmodel.ybs MLmodel.yb_s0_dict.update({cla: MLmodel.Ds0_dict[cla] - MLmodel.ybs0_dict[cla]}) MLmodel.yb_s1_dict.update({cla: MLmodel.Ds1_dict[cla] - MLmodel.ybs1_dict[cla]}) v0_dict = {} v1_dict = {} for cla in MLmodel.classes: xa_ = packet['data']['xaxbP_dict'][cla]['xa_'] xb_ = packet['data']['xaxbP_dict'][cla]['xb_'] P = packet['data']['xaxbP_dict'][cla]['P'] V0 = xa_ * (2 * MLmodel.yas0_dict[cla] - MLmodel.Bs0_dict[cla]) + xb_ * (2 * MLmodel.ybs0_dict[cla] - MLmodel.Ds0_dict[cla]) + P * (MLmodel.Ds0_dict[cla] - 2 * MLmodel.Bs0_dict[cla]) v0 = np.sum(V0, axis=1) v0_dict.update({cla: v0}) V1 = xa_ * (2 * MLmodel.yas1_dict[cla] - MLmodel.Bs1_dict[cla]) + xb_ * (2 * MLmodel.ybs1_dict[cla] - MLmodel.Ds1_dict[cla]) + P * (MLmodel.Ds1_dict[cla] - 2 * MLmodel.Bs1_dict[cla]) v1 = np.sum(V1, axis=1) v1_dict.update({cla: v1}) MLmodel.display('PROC_WORKER_END', verbose=False) # send to Master ya_, yb_, Q, v action = 'ACK_sending_s' #message_id = 'worker_' + MLmodel.worker_address + '_' + str(MLmodel.message_counter) if not MLmodel.Bob_data_s: data = {'ya_0_dict': MLmodel.ya_s0_dict, 'yb_0_dict': MLmodel.yb_s0_dict, 'Q0_dict': MLmodel.Qs0_dict, 'v0_dict': v0_dict, 'Ztr0_dict': MLmodel.Ztr0_dict, 'Ztr1_dict': MLmodel.Ztr1_dict} data.update({'ya_1_dict': MLmodel.ya_s1_dict, 'yb_1_dict': MLmodel.yb_s1_dict, 'Q1_dict': MLmodel.Qs1_dict, 'v1_dict': v1_dict}) MLmodel.Bob_data_s = True else: data = {'v0_dict': v0_dict, 'v1_dict': v1_dict} #del v0, v1 packet = {'action': action, 'data': data, 'sender': MLmodel.worker_address} del data message_id = 'worker_' + MLmodel.worker_address + '_' + str(MLmodel.message_counter) packet.update({'message_id': message_id}) MLmodel.message_counter += 1 size_bytes = asizeof.asizeof(dill.dumps(packet)) MLmodel.display('COMMS_WORKER_SEND %s to %s, id = %s, bytes=%s' % (action, MLmodel.master_address, message_id, str(size_bytes)), verbose=False) MLmodel.comms.send(packet, MLmodel.master_address) del packet#, size_bytes MLmodel.display(MLmodel.name + ' %s: sent ACK_sending_s' % (str(MLmodel.worker_address))) except: raise ''' print('ERROR AT while_computing_s') import code code.interact(local=locals()) ''' return def while_computing_KTK(self, MLmodel, packet): try: MLmodel.display('PROC_WORKER_START', verbose=False) KTK_dict = {} KTy_dict = {} for cla in MLmodel.classes: KTK = np.dot(MLmodel.Dmat_dict[cla].T, packet['data']['Rzz_dict'][cla]) KTK = np.dot(KTK, MLmodel.Dmat_dict[cla]) KTK_dict.update({cla: KTK}) KTy = np.dot(MLmodel.Dmat_dict[cla].T, packet['data']['rzt_dict'][cla]) KTy_dict.update({cla: KTy}) MLmodel.display('PROC_WORKER_END', verbose=False) action = 'ACK_sending_KTK' data = {'KTK_dict': KTK_dict, 'KTy_dict': KTy_dict} #del KTK, KTy packet = {'action': action, 'data': data, 'sender': MLmodel.worker_address} message_id = 'worker_' + MLmodel.worker_address + '_' + str(MLmodel.message_counter) packet.update({'message_id': message_id}) MLmodel.message_counter += 1 size_bytes = asizeof.asizeof(dill.dumps(packet)) MLmodel.display('COMMS_WORKER_SEND %s to %s, id = %s, bytes=%s' % (action, MLmodel.master_address, message_id, str(size_bytes)), verbose=False) #MLmodel.comms.send(MLmodel.master_address, packet) MLmodel.comms.send(packet, MLmodel.master_address) MLmodel.display(MLmodel.name + ' %s: sent ACK_sending_KTK' % (str(MLmodel.worker_address))) except Exception as err: raise ''' print('ERROR AT while_computing_KTK') import code code.interact(local=locals()) pass ''' return states_worker = [ State(name='waiting_order', on_enter=['while_waiting_order']), State(name='setting_tr_data', on_enter=['while_setting_tr_data']), State(name='projecting_C', on_enter=['while_projecting_C']), State(name='storing_C', on_enter=['while_storing_C']), State(name='computing_s', on_enter=['while_computing_s']), State(name='computing_KTK', on_enter=['while_computing_KTK']), State(name='computing_KXC', on_enter=['while_computing_KXC']), State(name='Exit', on_enter=['while_Exit']) ] transitions_worker = [ ['go_setting_tr_data', 'waiting_order', 'setting_tr_data'], ['done_setting_tr_data', 'setting_tr_data', 'waiting_order'], ['go_projecting_C', 'waiting_order', 'projecting_C'], ['done_projecting_C', 'projecting_C', 'waiting_order'], ['go_storing_C', 'waiting_order', 'storing_C'], ['done_storing_C', 'storing_C', 'waiting_order'], ['go_computing_s', 'waiting_order', 'computing_s'], ['done_computing_s', 'computing_s', 'waiting_order'], ['go_computing_KXC', 'waiting_order', 'computing_KXC'], ['done_computing_KXC', 'computing_KXC', 'waiting_order'], ['go_computing_KTK', 'waiting_order', 'computing_KTK'], ['done_computing_KTK', 'computing_KTK', 'waiting_order'], ['go_exit', 'waiting_order', 'Exit'] ] self.FSMworker = FSM_worker() self.grafmachine_worker = GraphMachine(model=self.FSMworker, states=states_worker, transitions=transitions_worker, initial='waiting_order', show_auto_transitions=False, # default value is False title="Finite State Machine modelling the behaviour of worker No. %s" % str(self.worker_address), show_conditions=False) return def ProcessReceivedPacket_Worker(self, packet, sender): """ Take an action after receiving a packet Parameters ---------- packet: packet object packet received (usually a dict with various content) sender: string id of the sender """ self.terminate = False try: self.display('COMMS_WORKER_RECEIVED %s from %s, id=%s' % (packet['action'], sender, str(packet['message_id'])), verbose=False) except: self.display('WORKER MISSING message_id in %s from %s' % (packet['action'], sender), verbose=False) pass if packet is not None: try: # Exit the process if packet['action'] == 'STOP': self.display(self.name + ' %s: terminated by Master' % (str(self.worker_address))) self.display('EXIT_WORKER') self.terminate = True if packet['action'] == 'update_tr_data': # We update the training data self.FSMworker.go_setting_tr_data(self, packet) self.FSMworker.done_setting_tr_data(self) if packet['action'] == 'compute_KTK': self.FSMworker.go_computing_KTK(self, packet) self.FSMworker.done_computing_KTK(self) if packet['action'] == 'selecting_C': #self.C = packet['data']['C'] self.FSMworker.go_projecting_C(self, packet) self.FSMworker.done_projecting_C(self) if packet['action'] == 'sending_C': #self.C = packet['data']['C'] self.FSMworker.go_storing_C(self, packet) self.FSMworker.done_storing_C(self) if packet['action'] == 'sending_xaxbP': self.FSMworker.go_computing_s(self, packet) self.FSMworker.done_computing_s(self) if packet['action'] == 'sending_Rzz_rzt': self.FSMworker.go_computing_KTK(self, packet) self.FSMworker.done_computing_KTK(self) except Exception as err: raise ''' print('ERROR AT CheckNewPacket_worker') import code code.interact(local=locals()) ''' return self.terminate
[ "pickle.dump", "numpy.random.seed", "numpy.sum", "numpy.argmax", "numpy.ones", "numpy.linalg.norm", "numpy.exp", "numpy.random.normal", "transitions.extensions.GraphMachine", "numpy.multiply", "numpy.max", "transitions.State", "dill.dumps", "numpy.min", "numpy.linalg.inv", "numpy.dot",...
[((770, 781), 'time.time', 'time.time', ([], {}), '()\n', (779, 781), False, 'import time\n'), ((833, 858), 'numpy.random.seed', 'np.random.seed', ([], {'seed': 'seed'}), '(seed=seed)\n', (847, 858), True, 'import numpy as np\n'), ((1410, 1446), 'numpy.exp', 'np.exp', (['(-XC2 / 2.0 / self.sigma ** 2)'], {}), '(-XC2 / 2.0 / self.sigma ** 2)\n', (1416, 1446), True, 'import numpy as np\n'), ((1876, 1887), 'numpy.array', 'np.array', (['O'], {}), '(O)\n', (1884, 1887), True, 'import numpy as np\n'), ((2579, 2615), 'numpy.exp', 'np.exp', (['(-XC2 / 2.0 / self.sigma ** 2)'], {}), '(-XC2 / 2.0 / self.sigma ** 2)\n', (2585, 2615), True, 'import numpy as np\n'), ((3045, 3056), 'numpy.array', 'np.array', (['O'], {}), '(O)\n', (3053, 3056), True, 'import numpy as np\n'), ((9574, 9585), 'time.time', 'time.time', ([], {}), '()\n', (9583, 9585), False, 'import time\n'), ((9637, 9662), 'numpy.random.seed', 'np.random.seed', ([], {'seed': 'seed'}), '(seed=seed)\n', (9651, 9662), True, 'import numpy as np\n'), ((28916, 29168), 'transitions.extensions.GraphMachine', 'GraphMachine', ([], {'model': 'self.FSMmaster', 'states': 'states_master', 'transitions': 'transitions_master', 'initial': '"""waiting_order"""', 'show_auto_transitions': '(False)', 'title': '"""Finite State Machine modelling the behaviour of the master"""', 'show_conditions': '(False)'}), "(model=self.FSMmaster, states=states_master, transitions=\n transitions_master, initial='waiting_order', show_auto_transitions=\n False, title=\n 'Finite State Machine modelling the behaviour of the master',\n show_conditions=False)\n", (28928, 29168), False, 'from transitions.extensions import GraphMachine\n'), ((29534, 29578), 'numpy.random.normal', 'np.random.normal', (['(0)', '(0.001)', '(self.NI + 1, 1)'], {}), '(0, 0.001, (self.NI + 1, 1))\n', (29550, 29578), True, 'import numpy as np\n'), ((29650, 29692), 'numpy.random.normal', 'np.random.normal', (['(0)', '(1.0)', '(self.NI + 1, 1)'], {}), '(0, 1.0, (self.NI + 1, 1))\n', (29666, 29692), True, 'import numpy as np\n'), ((29721, 29757), 'numpy.zeros', 'np.zeros', (['(self.NI + 1, self.NI + 1)'], {}), '((self.NI + 1, self.NI + 1))\n', (29729, 29757), True, 'import numpy as np\n'), ((29817, 29843), 'numpy.zeros', 'np.zeros', (['(self.NI + 1, 1)'], {}), '((self.NI + 1, 1))\n', (29825, 29843), True, 'import numpy as np\n'), ((32150, 32192), 'numpy.exp', 'np.exp', (['(-XC2 / 2.0 / self.model.sigma ** 2)'], {}), '(-XC2 / 2.0 / self.model.sigma ** 2)\n', (32156, 32192), True, 'import numpy as np\n'), ((32216, 32252), 'numpy.zeros', 'np.zeros', (['(self.NC + 1, self.NC + 1)'], {}), '((self.NC + 1, self.NC + 1))\n', (32224, 32252), True, 'import numpy as np\n'), ((45284, 45295), 'time.time', 'time.time', ([], {}), '()\n', (45293, 45295), False, 'import time\n'), ((45347, 45372), 'numpy.random.seed', 'np.random.seed', ([], {'seed': 'seed'}), '(seed=seed)\n', (45361, 45372), True, 'import numpy as np\n'), ((1210, 1229), 'numpy.dot', 'np.dot', (['X', 'self.C.T'], {}), '(X, self.C.T)\n', (1216, 1229), True, 'import numpy as np\n'), ((1912, 1932), 'numpy.argmax', 'np.argmax', (['O'], {'axis': '(0)'}), '(O, axis=0)\n', (1921, 1932), True, 'import numpy as np\n'), ((2379, 2398), 'numpy.dot', 'np.dot', (['X', 'self.C.T'], {}), '(X, self.C.T)\n', (2385, 2398), True, 'import numpy as np\n'), ((3081, 3101), 'numpy.argmax', 'np.argmax', (['O'], {'axis': '(0)'}), '(O, axis=0)\n', (3090, 3101), True, 'import numpy as np\n'), ((8585, 8601), 'numpy.sqrt', 'np.sqrt', (['self.NI'], {}), '(self.NI)\n', (8592, 8601), True, 'import numpy as np\n'), ((9946, 10007), 'transitions.State', 'State', ([], {'name': '"""waiting_order"""', 'on_enter': "['while_waiting_order']"}), "(name='waiting_order', on_enter=['while_waiting_order'])\n", (9951, 10007), False, 'from transitions import State\n'), ((10022, 10085), 'transitions.State', 'State', ([], {'name': '"""update_tr_data"""', 'on_enter': "['while_update_tr_data']"}), "(name='update_tr_data', on_enter=['while_update_tr_data'])\n", (10027, 10085), False, 'from transitions import State\n'), ((10100, 10157), 'transitions.State', 'State', ([], {'name': '"""getting_KTK"""', 'on_enter': "['while_getting_KTK']"}), "(name='getting_KTK', on_enter=['while_getting_KTK'])\n", (10105, 10157), False, 'from transitions import State\n'), ((10172, 10229), 'transitions.State', 'State', ([], {'name': '"""selecting_C"""', 'on_enter': "['while_selecting_C']"}), "(name='selecting_C', on_enter=['while_selecting_C'])\n", (10177, 10229), False, 'from transitions import State\n'), ((10244, 10297), 'transitions.State', 'State', ([], {'name': '"""sending_C"""', 'on_enter': "['while_sending_C']"}), "(name='sending_C', on_enter=['while_sending_C'])\n", (10249, 10297), False, 'from transitions import State\n'), ((10314, 10375), 'transitions.State', 'State', ([], {'name': '"""computing_XTw"""', 'on_enter': "['while_computing_XTw']"}), "(name='computing_XTw', on_enter=['while_computing_XTw'])\n", (10319, 10375), False, 'from transitions import State\n'), ((10390, 10449), 'transitions.State', 'State', ([], {'name': '"""computing_oi"""', 'on_enter': "['while_computing_oi']"}), "(name='computing_oi', on_enter=['while_computing_oi'])\n", (10395, 10449), False, 'from transitions import State\n'), ((10466, 10521), 'transitions.State', 'State', ([], {'name': '"""updating_w"""', 'on_enter': "['while_updating_w']"}), "(name='updating_w', on_enter=['while_updating_w'])\n", (10471, 10521), False, 'from transitions import State\n'), ((31943, 31968), 'numpy.dot', 'np.dot', (['X', 'self.model.C.T'], {}), '(X, self.model.C.T)\n', (31949, 31968), True, 'import numpy as np\n'), ((33270, 33312), 'numpy.exp', 'np.exp', (['(-XC2 / 2.0 / self.model.sigma ** 2)'], {}), '(-XC2 / 2.0 / self.model.sigma ** 2)\n', (33276, 33312), True, 'import numpy as np\n'), ((62395, 62456), 'transitions.State', 'State', ([], {'name': '"""waiting_order"""', 'on_enter': "['while_waiting_order']"}), "(name='waiting_order', on_enter=['while_waiting_order'])\n", (62400, 62456), False, 'from transitions import State\n'), ((62471, 62536), 'transitions.State', 'State', ([], {'name': '"""setting_tr_data"""', 'on_enter': "['while_setting_tr_data']"}), "(name='setting_tr_data', on_enter=['while_setting_tr_data'])\n", (62476, 62536), False, 'from transitions import State\n'), ((62551, 62610), 'transitions.State', 'State', ([], {'name': '"""projecting_C"""', 'on_enter': "['while_projecting_C']"}), "(name='projecting_C', on_enter=['while_projecting_C'])\n", (62556, 62610), False, 'from transitions import State\n'), ((62625, 62678), 'transitions.State', 'State', ([], {'name': '"""storing_C"""', 'on_enter': "['while_storing_C']"}), "(name='storing_C', on_enter=['while_storing_C'])\n", (62630, 62678), False, 'from transitions import State\n'), ((62695, 62752), 'transitions.State', 'State', ([], {'name': '"""computing_s"""', 'on_enter': "['while_computing_s']"}), "(name='computing_s', on_enter=['while_computing_s'])\n", (62700, 62752), False, 'from transitions import State\n'), ((62769, 62830), 'transitions.State', 'State', ([], {'name': '"""computing_KTK"""', 'on_enter': "['while_computing_KTK']"}), "(name='computing_KTK', on_enter=['while_computing_KTK'])\n", (62774, 62830), False, 'from transitions import State\n'), ((62845, 62906), 'transitions.State', 'State', ([], {'name': '"""computing_KXC"""', 'on_enter': "['while_computing_KXC']"}), "(name='computing_KXC', on_enter=['while_computing_KXC'])\n", (62850, 62906), False, 'from transitions import State\n'), ((62921, 62964), 'transitions.State', 'State', ([], {'name': '"""Exit"""', 'on_enter': "['while_Exit']"}), "(name='Exit', on_enter=['while_Exit'])\n", (62926, 62964), False, 'from transitions import State\n'), ((1605, 1621), 'numpy.ones', 'np.ones', (['(NP, 1)'], {}), '((NP, 1))\n', (1612, 1621), True, 'import numpy as np\n'), ((1947, 1995), 'numpy.array', 'np.array', (['[self.classes[pos] for pos in winners]'], {}), '([self.classes[pos] for pos in winners])\n', (1955, 1995), True, 'import numpy as np\n'), ((2774, 2790), 'numpy.ones', 'np.ones', (['(NP, 1)'], {}), '((NP, 1))\n', (2781, 2790), True, 'import numpy as np\n'), ((3116, 3164), 'numpy.array', 'np.array', (['[self.classes[pos] for pos in winners]'], {}), '([self.classes[pos] for pos in winners])\n', (3124, 3164), True, 'import numpy as np\n'), ((33025, 33052), 'numpy.dot', 'np.dot', (['self.Xval', 'self.C.T'], {}), '(self.Xval, self.C.T)\n', (33031, 33052), True, 'import numpy as np\n'), ((36259, 36270), 'numpy.array', 'np.array', (['O'], {}), '(O)\n', (36267, 36270), True, 'import numpy as np\n'), ((1253, 1270), 'numpy.multiply', 'np.multiply', (['X', 'X'], {}), '(X, X)\n', (1264, 1270), True, 'import numpy as np\n'), ((1320, 1347), 'numpy.multiply', 'np.multiply', (['self.C', 'self.C'], {}), '(self.C, self.C)\n', (1331, 1347), True, 'import numpy as np\n'), ((1757, 1786), 'numpy.dot', 'np.dot', (['KXC', 'self.w_dict[cla]'], {}), '(KXC, self.w_dict[cla])\n', (1763, 1786), True, 'import numpy as np\n'), ((2422, 2439), 'numpy.multiply', 'np.multiply', (['X', 'X'], {}), '(X, X)\n', (2433, 2439), True, 'import numpy as np\n'), ((2489, 2516), 'numpy.multiply', 'np.multiply', (['self.C', 'self.C'], {}), '(self.C, self.C)\n', (2500, 2516), True, 'import numpy as np\n'), ((2926, 2955), 'numpy.dot', 'np.dot', (['KXC', 'self.w_dict[cla]'], {}), '(KXC, self.w_dict[cla])\n', (2932, 2955), True, 'import numpy as np\n'), ((31992, 32009), 'numpy.multiply', 'np.multiply', (['X', 'X'], {}), '(X, X)\n', (32003, 32009), True, 'import numpy as np\n'), ((32064, 32103), 'numpy.multiply', 'np.multiply', (['self.model.C', 'self.model.C'], {}), '(self.model.C, self.model.C)\n', (32075, 32103), True, 'import numpy as np\n'), ((32685, 32707), 'numpy.zeros', 'np.zeros', (['(self.NI, 1)'], {}), '((self.NI, 1))\n', (32693, 32707), True, 'import numpy as np\n'), ((32755, 32781), 'numpy.zeros', 'np.zeros', (['(1, self.NI + 1)'], {}), '((1, self.NI + 1))\n', (32763, 32781), True, 'import numpy as np\n'), ((33356, 33388), 'numpy.ones', 'np.ones', (['(self.Xval.shape[0], 1)'], {}), '((self.Xval.shape[0], 1))\n', (33363, 33388), True, 'import numpy as np\n'), ((34152, 34197), 'numpy.random.normal', 'np.random.normal', (['(0)', '(0.001)', '(self.NItrain, 1)'], {}), '(0, 0.001, (self.NItrain, 1))\n', (34168, 34197), True, 'import numpy as np\n'), ((34242, 34287), 'numpy.random.normal', 'np.random.normal', (['(0)', '(0.001)', '(self.NItrain, 1)'], {}), '(0, 0.001, (self.NItrain, 1))\n', (34258, 34287), True, 'import numpy as np\n'), ((36303, 36323), 'numpy.argmax', 'np.argmax', (['O'], {'axis': '(0)'}), '(O, axis=0)\n', (36312, 36323), True, 'import numpy as np\n'), ((48412, 48451), 'numpy.exp', 'np.exp', (['(-XC2 / 2.0 / MLmodel.sigma ** 2)'], {}), '(-XC2 / 2.0 / MLmodel.sigma ** 2)\n', (48418, 48451), True, 'import numpy as np\n'), ((48635, 48652), 'numpy.zeros', 'np.zeros', (['(NC, 1)'], {}), '((NC, 1))\n', (48643, 48652), True, 'import numpy as np\n'), ((51024, 51063), 'numpy.exp', 'np.exp', (['(-XC2 / 2.0 / MLmodel.sigma ** 2)'], {}), '(-XC2 / 2.0 / MLmodel.sigma ** 2)\n', (51030, 51063), True, 'import numpy as np\n'), ((12290, 12308), 'dill.dumps', 'dill.dumps', (['packet'], {}), '(packet)\n', (12300, 12308), False, 'import dill\n'), ((13660, 13678), 'dill.dumps', 'dill.dumps', (['packet'], {}), '(packet)\n', (13670, 13678), False, 'import dill\n'), ((15310, 15328), 'dill.dumps', 'dill.dumps', (['packet'], {}), '(packet)\n', (15320, 15328), False, 'import dill\n'), ((18683, 18701), 'dill.dumps', 'dill.dumps', (['packet'], {}), '(packet)\n', (18693, 18701), False, 'import dill\n'), ((26299, 26317), 'dill.dumps', 'dill.dumps', (['packet'], {}), '(packet)\n', (26309, 26317), False, 'import dill\n'), ((27720, 27764), 'numpy.zeros', 'np.zeros', (['(MLmodel.NItrain, MLmodel.NItrain)'], {}), '((MLmodel.NItrain, MLmodel.NItrain))\n', (27728, 27764), True, 'import numpy as np\n'), ((27810, 27840), 'numpy.zeros', 'np.zeros', (['(MLmodel.NItrain, 1)'], {}), '((MLmodel.NItrain, 1))\n', (27818, 27840), True, 'import numpy as np\n'), ((33080, 33113), 'numpy.multiply', 'np.multiply', (['self.Xval', 'self.Xval'], {}), '(self.Xval, self.Xval)\n', (33091, 33113), True, 'import numpy as np\n'), ((33167, 33194), 'numpy.multiply', 'np.multiply', (['self.C', 'self.C'], {}), '(self.C, self.C)\n', (33178, 33194), True, 'import numpy as np\n'), ((35370, 35431), 'numpy.linalg.norm', 'np.linalg.norm', (['(self.model.w_dict[cla] - self.w_old_dict[cla])'], {}), '(self.model.w_dict[cla] - self.w_old_dict[cla])\n', (35384, 35431), True, 'import numpy as np\n'), ((35434, 35470), 'numpy.linalg.norm', 'np.linalg.norm', (['self.w_old_dict[cla]'], {}), '(self.w_old_dict[cla])\n', (35448, 35470), True, 'import numpy as np\n'), ((36354, 36402), 'numpy.array', 'np.array', (['[self.classes[pos] for pos in winners]'], {}), '([self.classes[pos] for pos in winners])\n', (36362, 36402), True, 'import numpy as np\n'), ((46721, 46739), 'dill.dumps', 'dill.dumps', (['packet'], {}), '(packet)\n', (46731, 46739), False, 'import dill\n'), ((48159, 48181), 'numpy.dot', 'np.dot', (['X', 'MLmodel.C.T'], {}), '(X, MLmodel.C.T)\n', (48165, 48181), True, 'import numpy as np\n'), ((48582, 48604), 'numpy.argmax', 'np.argmax', (['KXC'], {'axis': '(1)'}), '(KXC, axis=1)\n', (48591, 48604), True, 'import numpy as np\n'), ((49359, 49377), 'dill.dumps', 'dill.dumps', (['packet'], {}), '(packet)\n', (49369, 49377), False, 'import dill\n'), ((50771, 50793), 'numpy.dot', 'np.dot', (['X', 'MLmodel.C.T'], {}), '(X, MLmodel.C.T)\n', (50777, 50793), True, 'import numpy as np\n'), ((51300, 51319), 'numpy.min', 'np.min', (['MLmodel.KXC'], {}), '(MLmodel.KXC)\n', (51306, 51319), True, 'import numpy as np\n'), ((51321, 51340), 'numpy.max', 'np.max', (['MLmodel.KXC'], {}), '(MLmodel.KXC)\n', (51327, 51340), True, 'import numpy as np\n'), ((53190, 53208), 'dill.dumps', 'dill.dumps', (['packet'], {}), '(packet)\n', (53200, 53208), False, 'import dill\n'), ((57952, 57970), 'numpy.sum', 'np.sum', (['V0'], {'axis': '(1)'}), '(V0, axis=1)\n', (57958, 57970), True, 'import numpy as np\n'), ((58260, 58278), 'numpy.sum', 'np.sum', (['V1'], {'axis': '(1)'}), '(V1, axis=1)\n', (58266, 58278), True, 'import numpy as np\n'), ((59611, 59629), 'dill.dumps', 'dill.dumps', (['packet'], {}), '(packet)\n', (59621, 59629), False, 'import dill\n'), ((60608, 60673), 'numpy.dot', 'np.dot', (['MLmodel.Dmat_dict[cla].T', "packet['data']['Rzz_dict'][cla]"], {}), "(MLmodel.Dmat_dict[cla].T, packet['data']['Rzz_dict'][cla])\n", (60614, 60673), True, 'import numpy as np\n'), ((60707, 60742), 'numpy.dot', 'np.dot', (['KTK', 'MLmodel.Dmat_dict[cla]'], {}), '(KTK, MLmodel.Dmat_dict[cla])\n', (60713, 60742), True, 'import numpy as np\n'), ((60828, 60893), 'numpy.dot', 'np.dot', (['MLmodel.Dmat_dict[cla].T', "packet['data']['rzt_dict'][cla]"], {}), "(MLmodel.Dmat_dict[cla].T, packet['data']['rzt_dict'][cla])\n", (60834, 60893), True, 'import numpy as np\n'), ((61585, 61603), 'dill.dumps', 'dill.dumps', (['packet'], {}), '(packet)\n', (61595, 61603), False, 'import dill\n'), ((20901, 20919), 'numpy.sum', 'np.sum', (['U0'], {'axis': '(1)'}), '(U0, axis=1)\n', (20907, 20919), True, 'import numpy as np\n'), ((21336, 21350), 'numpy.ones', 'np.ones', (['NPtr0'], {}), '(NPtr0)\n', (21343, 21350), True, 'import numpy as np\n'), ((21966, 21984), 'numpy.dot', 'np.dot', (['Rzz0.T', 'y0'], {}), '(Rzz0.T, y0)\n', (21972, 21984), True, 'import numpy as np\n'), ((22021, 22077), 'numpy.dot', 'np.dot', (['Rzz0.T', "MLmodel.Ztr_dict[addr]['Ztr0_dict'][cla]"], {}), "(Rzz0.T, MLmodel.Ztr_dict[addr]['Ztr0_dict'][cla])\n", (22027, 22077), True, 'import numpy as np\n'), ((22743, 22761), 'numpy.sum', 'np.sum', (['U1'], {'axis': '(1)'}), '(U1, axis=1)\n', (22749, 22761), True, 'import numpy as np\n'), ((22998, 23012), 'numpy.ones', 'np.ones', (['NPtr1'], {}), '(NPtr1)\n', (23005, 23012), True, 'import numpy as np\n'), ((23177, 23191), 'numpy.ones', 'np.ones', (['NPtr1'], {}), '(NPtr1)\n', (23184, 23191), True, 'import numpy as np\n'), ((23807, 23825), 'numpy.dot', 'np.dot', (['Rzz1.T', 'y1'], {}), '(Rzz1.T, y1)\n', (23813, 23825), True, 'import numpy as np\n'), ((23862, 23918), 'numpy.dot', 'np.dot', (['Rzz1.T', "MLmodel.Ztr_dict[addr]['Ztr1_dict'][cla]"], {}), "(Rzz1.T, MLmodel.Ztr_dict[addr]['Ztr1_dict'][cla])\n", (23868, 23918), True, 'import numpy as np\n'), ((24920, 24938), 'dill.dumps', 'dill.dumps', (['packet'], {}), '(packet)\n', (24930, 24938), False, 'import dill\n'), ((28277, 28323), 'numpy.linalg.inv', 'np.linalg.inv', (['(MLmodel.KTK_accum + MLmodel.Kcc)'], {}), '(MLmodel.KTK_accum + MLmodel.Kcc)\n', (28290, 28323), True, 'import numpy as np\n'), ((36166, 36190), 'numpy.dot', 'np.dot', (['self.KXC_val', 'w_'], {}), '(self.KXC_val, w_)\n', (36172, 36190), True, 'import numpy as np\n'), ((51220, 51236), 'numpy.ones', 'np.ones', (['(NP, 1)'], {}), '((NP, 1))\n', (51227, 51236), True, 'import numpy as np\n'), ((55417, 55431), 'numpy.sum', 'np.sum', (['which0'], {}), '(which0)\n', (55423, 55431), True, 'import numpy as np\n'), ((55526, 55540), 'numpy.sum', 'np.sum', (['which1'], {}), '(which1)\n', (55532, 55540), True, 'import numpy as np\n'), ((4908, 4928), 'pickle.dump', 'pickle.dump', (['self', 'f'], {}), '(self, f)\n', (4919, 4928), False, 'import pickle\n'), ((21157, 21171), 'numpy.ones', 'np.ones', (['NPtr0'], {}), '(NPtr0)\n', (21164, 21171), True, 'import numpy as np\n'), ((48217, 48234), 'numpy.multiply', 'np.multiply', (['X', 'X'], {}), '(X, X)\n', (48228, 48234), True, 'import numpy as np\n'), ((48296, 48329), 'numpy.multiply', 'np.multiply', (['MLmodel.C', 'MLmodel.C'], {}), '(MLmodel.C, MLmodel.C)\n', (48307, 48329), True, 'import numpy as np\n'), ((50829, 50846), 'numpy.multiply', 'np.multiply', (['X', 'X'], {}), '(X, X)\n', (50840, 50846), True, 'import numpy as np\n'), ((50908, 50941), 'numpy.multiply', 'np.multiply', (['MLmodel.C', 'MLmodel.C'], {}), '(MLmodel.C, MLmodel.C)\n', (50919, 50941), True, 'import numpy as np\n'), ((51583, 51627), 'numpy.random.normal', 'np.random.normal', (['(0)', '(0.01)', '(MLmodel.NPtr, 1)'], {}), '(0, 0.01, (MLmodel.NPtr, 1))\n', (51599, 51627), True, 'import numpy as np\n'), ((52068, 52128), 'numpy.random.normal', 'np.random.normal', (['(0)', '(1)', '(MLmodel.NI_train, MLmodel.NI_train)'], {}), '(0, 1, (MLmodel.NI_train, MLmodel.NI_train))\n', (52084, 52128), True, 'import numpy as np\n'), ((52187, 52224), 'numpy.linalg.inv', 'np.linalg.inv', (['MLmodel.Cmat_dict[cla]'], {}), '(MLmodel.Cmat_dict[cla])\n', (52200, 52224), True, 'import numpy as np\n'), ((52427, 52481), 'numpy.dot', 'np.dot', (['MLmodel.KXC[which0, :]', 'MLmodel.Cmat_dict[cla]'], {}), '(MLmodel.KXC[which0, :], MLmodel.Cmat_dict[cla])\n', (52433, 52481), True, 'import numpy as np\n'), ((52593, 52647), 'numpy.dot', 'np.dot', (['MLmodel.KXC[which1, :]', 'MLmodel.Cmat_dict[cla]'], {}), '(MLmodel.KXC[which1, :], MLmodel.Cmat_dict[cla])\n', (52599, 52647), True, 'import numpy as np\n'), ((56019, 56057), 'numpy.random.uniform', 'np.random.uniform', (['(-10)', '(10)', '(NPtr0, K)'], {}), '(-10, 10, (NPtr0, K))\n', (56036, 56057), True, 'import numpy as np\n'), ((56120, 56158), 'numpy.random.uniform', 'np.random.uniform', (['(-10)', '(10)', '(NPtr0, K)'], {}), '(-10, 10, (NPtr0, K))\n', (56137, 56158), True, 'import numpy as np\n'), ((56221, 56259), 'numpy.random.uniform', 'np.random.uniform', (['(-10)', '(10)', '(NPtr1, K)'], {}), '(-10, 10, (NPtr1, K))\n', (56238, 56259), True, 'import numpy as np\n'), ((56322, 56360), 'numpy.random.uniform', 'np.random.uniform', (['(-10)', '(10)', '(NPtr1, K)'], {}), '(-10, 10, (NPtr1, K))\n', (56339, 56360), True, 'import numpy as np\n'), ((16938, 16967), 'numpy.random.uniform', 'np.random.uniform', (['(-10)', '(10)', 'K'], {}), '(-10, 10, K)\n', (16955, 16967), True, 'import numpy as np\n'), ((17033, 17062), 'numpy.random.uniform', 'np.random.uniform', (['(-10)', '(10)', 'K'], {}), '(-10, 10, K)\n', (17050, 17062), True, 'import numpy as np\n'), ((52258, 52286), 'numpy.array', 'np.array', (['(MLmodel.ytr == cla)'], {}), '(MLmodel.ytr == cla)\n', (52266, 52286), True, 'import numpy as np\n'), ((55263, 55291), 'numpy.array', 'np.array', (['(MLmodel.ytr == cla)'], {}), '(MLmodel.ytr == cla)\n', (55271, 55291), True, 'import numpy as np\n')]
import pytest import os import pandas as pd import riptable as rt from enum import IntEnum from numpy.testing import assert_array_equal from riptable import * from riptable import save_sds, load_sds from riptable import FastArray, Categorical, CatZero from riptable.rt_categorical import Categories from riptable.rt_enum import ( INVALID_DICT, ) from riptable.rt_enum import ( DisplayLength, DisplayJustification, DisplayColumnColors, ) from riptable.rt_enum import CategoryMode, TypeRegister from riptable.rt_numpy import isnan, isnotnan, arange, ones from riptable.tests.test_utils import ( get_categorical_data_factory_method, get_all_categorical_data, ) from riptable.rt_sds import SDSMakeDirsOn from riptable.tests.utils import LikertDecision # change to true since we write into /tests directory SDSMakeDirsOn() three_unicode = np.array(["AAPL\u2080", "AMZN\u2082", "IBM\u2081"]) three_bytes = FastArray([b'a', b'b', b'c']) three_ints = FastArray([1, 2, 3]) compare_func_names = ['__ne__', '__eq__', '__ge__', '__gt__', '__le__', '__lt__'] int_success = [ np.array([True, False, True]), # ne np.array([False, True, False]), # eq np.array([False, True, True]), # ge np.array([False, False, True]), # gt np.array([True, True, False]), # le np.array([True, False, False]), # lt ] same_success = [ np.array([False, False, False]), # ne np.array([True, True, True]), # eq np.array([True, True, True]), # ge np.array([False, False, False]), # gt np.array([True, True, True]), # le np.array([False, False, False]), # lt ] diff_success = [ np.array([True, False, True]), # ne np.array([False, True, False]), # eq np.array([False, True, False]), # ge np.array([False, False, False]), # gt np.array([True, True, True]), # le np.array([True, False, True]), # lt ] ShowCompareInfo = False list_bytes = [b'b', b'b', b'a', b'd', b'c'] list_unicode = ['b', 'b', 'a', 'd', 'c'] list_true_unicode = [u'b\u2082', u'b\u2082', u'a\u2082', u'd\u2082', u'c\u2082'] decision_dict = dict(zip(LikertDecision.__members__.keys(), [int(v) for v in LikertDecision.__members__.values()],)) def array_equal(arr1, arr2): subr = arr1 - arr2 sumr = sum(subr == 0) result = sumr == len(arr1) if not result: print("array comparison failed", arr1, arr2) return result class TestCategorical: def _notimpl(self): pytest.skip("This test needs to be implemented.") def test_constructor(self): # from pandas categorical # from single parameter # from two parameters # ndarray # python list self._notimpl() def test_ctor_list(self): c_bytes = Categorical(list_bytes) assert c_bytes.dtype == np.int8, f"Dtype {c_bytes.dtype} was not correct for construction from small list." assert len(c_bytes) == 5, f"Length of underlying index array was incorrect for construction from bytes." unique_bytes = np.unique(list_bytes) assert np.all( c_bytes._categories_wrap._list == unique_bytes ), f"Categories did not generate a unique list of categories from input bytes list." c_unicode = Categorical(list_unicode) assert c_unicode.dtype == np.int8, f"Dtype {c_unicode.dtype} was not correct for construction from small list." assert len(c_unicode) == 5, f"Length of underlying index array was incorrect for construction from unicode." assert ( len(c_unicode._categories_wrap) == 4 ), f"Length of unique categories was incorrect for construction from unicode." assert ( c_unicode._categories_wrap._list[0] == b'a' ), f"Unique categories were not sorted for construction from unicode." assert c_unicode._categories_wrap._list.dtype.char == 'S', f"Unicode strings were not flipped to byte strings." c_true_unicode = Categorical(list_true_unicode) assert ( c_true_unicode.dtype == np.int8 ), f"Dtype {c_true_unicode.dtype} was not correct for construction from small list." assert ( len(c_true_unicode) == 5 ), f"Length of underlying index array was incorrect for construction from true unicode." assert ( len(c_true_unicode._categories_wrap) == 4 ), f"Length of unique categories was incorrect for construction from true unicode." assert ( c_true_unicode._categories_wrap._list[0] == u'a\u2082' ), f"Unique categories were not sorted for construction from true unicode." assert ( c_true_unicode._categories_wrap._list.dtype.char == 'U' ), f"Unicode strings were not flipped to byte strings." def test_ctor_nparray(self): c_bytes = Categorical(np.array(list_bytes)) assert c_bytes.dtype == np.int8, f"Dtype {c_bytes.dtype} was not correct for construction from small list." assert len(c_bytes) == 5, f"Length of underlying index array was incorrect for construction from bytes." unique_bytes = np.unique(list_bytes) assert np.all( c_bytes._categories_wrap._list == unique_bytes ), f"Categories did not generate a unique list of categories from input bytes list." c_unicode = Categorical(np.array(list_unicode)) assert c_unicode.dtype == np.int8, f"Dtype {c_unicode.dtype} was not correct for construction from small list." assert len(c_unicode) == 5, f"Length of underlying index array was incorrect for construction from unicode." assert ( len(c_unicode._categories_wrap._list) == 4 ), f"Length of unique categories was incorrect for construction from unicode." assert ( c_unicode._categories_wrap._list[0] == b'a' ), f"Unique categories were not sorted for construction from unicode." assert c_unicode._categories_wrap._list.dtype.char == 'S', f"Unicode strings were not flipped to byte strings." c_true_unicode = Categorical(np.array(list_true_unicode)) assert ( c_true_unicode.dtype == np.int8 ), f"Dtype {c_true_unicode.dtype} was not correct for construction from small list." assert ( len(c_true_unicode) == 5 ), f"Length of underlying index array was incorrect for construction from true unicode." assert ( len(c_true_unicode._categories_wrap._list) == 4 ), f"Length of unique categories was incorrect for construction from true unicode." assert ( c_true_unicode._categories_wrap._list[0] == u'a\u2082' ), f"Unique categories were not sorted for construction from true unicode." assert ( c_true_unicode._categories_wrap._list.dtype.char == 'U' ), f"Unicode strings were not flipped to byte strings." def test_ctor_values_and_cats(self): v_bytes = [b'IBM', b'AAPL', b'AMZN', b'IBM', b'hello'] v_str = ['IBM', 'AAPL', 'AMZN', 'IBM', 'hello'] v_true = [ u'IBM\u2082', u'AAPL\u2082', u'AMZN\u2082', u'IBM\u2082', u'hello\u2082', ] c_bytes = [b'AAPL', b'AMZN', b'IBM'] c_str = ['AAPL', 'AMZN', 'IBM'] c_true = [u'AAPL\u2082', u'AMZN\u2082', u'IBM\u2082'] v_correct = [2, 0, 1, 2, 3] c_correct = [b'AAPL', b'AMZN', b'IBM', b'inv'] valid_v = [ v_bytes, v_str, np.array(v_bytes), np.array(v_str), FastArray(v_bytes), FastArray(v_str), ] valid_c = [ c_bytes, c_str, np.array(c_bytes), np.array(c_str), FastArray(c_bytes), FastArray(c_str), ] for v in valid_v: vdt = None if hasattr(v, 'dtype'): vdt = v.dtype else: vdt = type(v) for c in valid_c: cdt = None if hasattr(c, 'dtype'): cdt = c.dtype else: cdt = type(c) # error if no invalid provided with pytest.raises(ValueError): cat = Categorical(v, c) # accept invalid and correctly assign # cat = Categorical(v, c, invalid_category=b'inv') # self.assertEqual(cat._categories.dtype.char, 'S', msg=f"Categorical from v: {vdt} and c: {cdt} did not flip categories to bytestring") # v_is_correct = bool(np.all(v_correct == cat.view(FastArray))) # self.assertTrue(v_is_correct, msg=f"Did not create the correct underlying index array from v: {vdt} and c: {cdt}") # c_is_correct = bool(np.all(c_correct == cat._categories)) # self.assertTrue(c_is_correct, msg=f"Did not create the correct categories from v: {vdt} and c: {cdt}") # v = v_true # vdt = "TRUE unicode" # for c in valid_c: # if hasattr(c,'dtype'): # cdt = c.dtype # else: # cdt = type(c) # cat = Categorical(v,c) # --------------------------------------------------------------------------- def test_ctor_bad_index(self): idx_list = [1, 2, 3, 4, 5] str_list = ['a', 'b'] with pytest.raises(ValueError): c = Categorical(idx_list, str_list) # --------------------------------------------------------------------------- def test_ctor_non_unique(self): ''' riptable categoricals, like pandas categoricals, do not allow a non-unique list of categories when an index array is provided. ''' idx_list = [0, 1] str_list = ['b', 'b', 'a'] c = Categorical(idx_list, str_list) # --------------------------------------------------------------------------- def test_ctor_enum(self): codes = [1, 44, 44, 133, 75] c = Categorical(codes, LikertDecision) # --------------------------------------------------------------------------- def test_compare_enum_int(self): compare_func_names = [ '__ne__', '__eq__', '__ge__', '__gt__', '__le__', '__lt__', ] codes = [1, 44, 44, 133, 75] valid_idx = 44 bad_idx = 43 valid_idx_correct = [ FastArray([True, False, False, True, True]), FastArray([False, True, True, False, False]), FastArray([False, True, True, True, True]), FastArray([False, False, False, True, True]), FastArray([True, True, True, False, False]), FastArray([True, False, False, False, False]), ] bad_idx_correct = [ FastArray([True, True, True, True, True]), FastArray([False, False, False, False, False]), FastArray([False, True, True, True, True]), FastArray([False, True, True, True, True]), FastArray([True, False, False, False, False]), FastArray([True, False, False, False, False]), ] for d in (LikertDecision, decision_dict): c = Categorical(codes, d) # test valid integer code for name, correct in zip(compare_func_names, valid_idx_correct): func = c.__getattribute__(name) result = func(valid_idx) was_correct = bool(np.all(correct == result)) assert ( was_correct ), f"Categorical enum comparison failed with good integer index on {name} operation. {c.view(FastArray)} code: {valid_idx}" # test invalid integer code for name, correct in zip(compare_func_names, bad_idx_correct): func = c.__getattribute__(name) result = func(bad_idx) was_correct = bool(np.all(correct == result)) assert was_correct, f"Categorical enum comparison failed with good integer index on {name} operation" # --------------------------------------------------------------------------- def test_compare_enum_str(self): compare_func_names = [ '__ne__', '__eq__', '__ge__', '__gt__', '__le__', '__lt__', ] codes = [1, 44, 44, 133, 75] valid_idx = 'StronglyAgree' bad_idx = 'x' valid_idx_correct = [ FastArray([True, False, False, True, True]), FastArray([False, True, True, False, False]), FastArray([False, True, True, True, True]), FastArray([False, False, False, True, True]), FastArray([True, True, True, False, False]), FastArray([True, False, False, False, False]), ] for d in (LikertDecision, decision_dict): c = Categorical(codes, d) # test valid category string for name, correct in zip(compare_func_names, valid_idx_correct): func = c.__getattribute__(name) result = func(valid_idx) was_correct = bool(np.all(correct == result)) assert was_correct, f"Categorical enum comparison failed with good category string on {name} operation" # test invalid category string for name in compare_func_names: func = c.__getattribute__(name) with pytest.raises(ValueError): result = func(bad_idx) def test_map(self): c = Categorical(['b', 'b', 'c', 'a', 'd'], ordered=False) mapping = {'a': 'AA', 'b': 'BB', 'c': 'CC', 'd': 'DD'} result = c.map(mapping) correct = FastArray([b'BB', b'BB', b'CC', b'AA', b'DD']) assert bool(np.all(result == correct)) c = Categorical(['b', 'b', 'c', 'a', 'd'], ordered=False, base_index=0) result = c.map(mapping) assert bool(np.all(result == correct)) c = Categorical(['b', 'b', 'c', 'a', 'd'], ordered=False) mapping = {'a': 'AA', 'b': 'BB', 'c': 'CC'} result = c.map(mapping, invalid='INVALID') correct = FastArray([b'BB', b'BB', b'CC', b'AA', b'INVALID']) assert bool(np.all(result == correct)) c = Categorical(['b', 'b', 'c', 'a', 'd'], ordered=False, base_index=0) result = c.map(mapping, invalid='INVALID') assert bool(np.all(result == correct)) c = Categorical(['b', 'b', 'c', 'a', 'd'], ordered=False) mapping = {'a': 1.0, 'b': 2.0, 'c': 3.0} result = c.map(mapping, invalid=666) correct = FastArray([2.0, 2.0, 3.0, 1.0, 666.0]) assert bool(np.all(result == correct)) c = Categorical(['b', 'b', 'c', 'a', 'd'], ordered=False, base_index=0) result = c.map(mapping, invalid=666) assert bool(np.all(result == correct)) c = Categorical(['b', 'b', 'c', 'a', 'd'], ordered=False) result = c.map(mapping) assert np.isnan(result[4]) c = Categorical(['b', 'b', 'c', 'a', 'd'], ordered=False, base_index=0) result = c.map(mapping) assert np.isnan(result[4]) c = Categorical(['b', 'b', 'c', 'a', 'd'], ordered=False) mapping = FastArray(['w', 'x', 'y', 'z']) result = c.map(mapping) correct = FastArray([b'w', b'w', b'x', b'y', b'z']) assert bool(np.all(result == correct)) c = Categorical(['b', 'b', 'c', 'a', 'd'], ordered=False, base_index=0) result = c.map(mapping) assert bool(np.all(result == correct)) c = Categorical([2, 2, 3, 1, 4, 0], ['a', 'b', 'c', 'd']) mapping = {'a': 1.0, 'b': 2.0, 'c': 3.0} result = c.map(mapping, invalid=666) correct = FastArray([2.0, 2.0, 3.0, 1.0, 666.0, 666.0]) assert bool(np.all(result == correct)) # --------------------------------------------------------------------------- def test_from_category(self): c = Categorical(['a', 'a', 'b', 'c', 'a']) bin = c.from_category('a') assert bin == 1 c = Categorical(['a', 'a', 'b', 'c', 'a'], base_index=0) bin = c.from_category(b'a') assert bin == 0 with pytest.raises(ValueError): bin = c.from_category('z') c = Categorical(np.arange(5, 10)) bin = c.from_category(5) assert bin == 1 with pytest.raises(ValueError): bin = c.from_category(100) c = Categorical([FastArray(['a', 'b', 'c']), np.arange(3)]) bin = c.from_category(('c', 2)) assert bin == 3 # --------------------------------------------------------------------------- def test_getitem_enum_int(self): codes = [1, 44, 44, 133, 75] correct_strings = [ 'StronglyDisagree', 'StronglyAgree', 'StronglyAgree', 'Agree', 'Disagree', ] c = Categorical(codes, LikertDecision) # getitem good init for idx in range(5): assert correct_strings[idx] == c[idx], f"Failed to return correct string for valid index in categorical." # getitem bad init with pytest.raises(IndexError): result = c[5] # --------------------------------------------------------------------------- def test_getitem_enum_int_list(self): codes = [1, 44, 44, 133, 75] correct_strings = [ 'StronglyDisagree', 'StronglyAgree', 'StronglyAgree', 'Agree', 'Disagree', ] c = Categorical(codes, LikertDecision) result = c[[1, 4]] assert isinstance( result, Categorical ), f"Failed to return Categorical when indexing by integer list. Returned {type(result)} instead." assert result[0] == 'StronglyAgree' assert result[1] == 'Disagree' result = c[np.array([1, 4])] assert isinstance( result, Categorical ), f"Failed to return Categorical when indexing by integer list. Returned {type(result)} instead." assert result[0] == 'StronglyAgree' assert result[1] == 'Disagree' result = c[FastArray([1, 4])] assert isinstance( result, Categorical ), f"Failed to return Categorical when indexing by integer list. Returned {type(result)} instead." assert result[0] == 'StronglyAgree' assert result[1] == 'Disagree' def test_getitem_enum(self): self._notimpl() def test_setitem_enum(self): self._notimpl() # -------------------------------------------- MATLAB ---------------------------------- def test_ctor_matlab(self): idx_list = [1.0, 2.0, 3.0, 4.0, 5.0] str_list = ['a', 'b', 'c', 'd', 'e'] with pytest.raises(TypeError): c = Categorical(idx_list, str_list) c = Categorical(idx_list, str_list, from_matlab=True) assert c[0] == 'a' assert c.dtype == np.dtype(np.int8) # def test_ctor_matlab_non_unique(self): # idx_list = [1.0, 2.0, 3.0, 4.0, 5.0] # str_list = ['a','b','c','d','d'] # with self.assertRaises(ValueError, msg=f"Failed to raise error when MATLab categories were not unique."): # c = Categorical(idx_list, str_list, from_matlab=True) # ------------------------------- PANDAS CATEGORICAL ---------------------------------- def test_ctor_pandas_cat(self): idx_list = [0, 1, 2, 3, 4] str_list = ['a', 'b', 'c', 'd', 'e'] pd_c = pd.Categorical.from_codes(idx_list, str_list) pd_c = Categorical(pd_c) rt_c = Categorical(idx_list, str_list) cats_match = bool(np.all(pd_c.category_array == rt_c.category_array)) assert cats_match, f"Failed to create matching categories from pandas categorical" # idx_match = bool(np.all(pd_c.view(np.ndarray)+1 == rt_c.view(np.ndarray))) # self.assertTrue(idx_match, msg=f"Failed to create matching unerlying array from pandas categorical") # convert pandas invalid bytes pd_c = pd.Categorical.from_codes([-1, 0, 1, 2], ['a', 'b', 'c']) pd_c = Categorical(pd_c) cat_list = pd_c.category_array assert len(cat_list) == 3 no_negative = bool(np.all(pd_c.view(FastArray) >= 0)) assert no_negative # convert pandas invalid unicode pd_c = pd.Categorical.from_codes([-1, 0, 1, 2], [u'\u2082', u'\u2083', u'\u2084']) pd_c = Categorical(pd_c) cat_list = pd_c.category_array assert len(cat_list) == 3 no_negative = bool(np.all(pd_c.view(FastArray) >= 0)) assert no_negative # --------------------------------RIPTABLE CATEGORICAL ---------------------------------------- # def test_ctor_rt_cat(self): # c_unicode = Categorical(list_unicode) # c = c_unicode.copy(forceunicode=True) # self.assertEqual(c._categories_wrap._list.dtype.char, 'U', msg=f"Failed to force unicode on categorical copy.") # ------------------------------------CUSTOM CATEGORIES ---------------------------------- def test_ctor_list_unique(self): unique_str = ['a', 'b', 'c', 'd', 'e', 'f'] str_list = ['a', 'b', 'c', 'd', 'e'] c = Categorical(str_list, unique_str) cats_match = bool(np.all(c._categories_wrap._list == unique_str)) assert cats_match, f"Failed to create matching categories from unique category input." # ------------------------------------INTEGER ARRAY ---------------------------------- def test_ctor_integer_array(self): lis = [1, 4, 9, 16, 25] c = Categorical(lis) for v1, v2 in zip(c, lis): assert v1 == v2 # ------------------------------------GARBAGE ---------------------------------- def test_ctor_garbage(self): with pytest.raises(TypeError): c = Categorical(1, 2) # ------------------------------------TEST FORCE DTYPE ---------------------------------- def test_init_with_dtype(self): int_types = [np.int8, np.int16, np.int32, np.int64] float_types = [np.float32, np.float64] uint_types = [np.uint8, np.uint16, np.uint32, np.uint64] arr = ['a', 'b', 'c', 'd', 'e'] for dt in int_types: c = Categorical(arr, dtype=dt) assert c.dtype == dt, f"Failed to force the correct dtype {dt} for categorical." for dt in float_types + uint_types: with pytest.raises(TypeError): c = Categorical(arr, dtype=dt) # ------------------------------------TEST CONVERT VALUE------------------------------------- def test_possibly_convert_value(self): ''' TODO: fix for new Categories class ''' self._notimpl() def test_categories_bad_init(self): tup = ('a', 'b', 'c') with pytest.raises(TypeError): cat = Categories(tup) def test_categories_len(self): cats_from_list = Categorical(['a', 'b', 'c'], ordered=True, base_index=1, filter=None)._categories_wrap assert len(cats_from_list) == 3 cats_from_enum = Categorical(FastArray([144]), LikertDecision)._categories_wrap assert len(cats_from_enum) == 144 def test_get_categories(self): c_list = [ 'StronglyAgree', 'Agree', 'Disagree', 'StronglyDisagree', 'NeitherAgreeNorDisagree', ] cats_from_list = Categories(c_list, unicode=True) cats_from_enum = Categories(LikertDecision) get_cats_match = bool(np.all(cats_from_list.get_categories() == cats_from_enum.get_categories())) assert get_cats_match def test_possibly_add_categories(self): self._notimpl() # uniquify and sort # raise exception for adding cats to intenum, etc. def test_categories_preserves_subtype(self): # Test the Categorical.categories() method preserves the array type for the category data. # This is important because we want the array(s) returned by this method to have the same type # as the internal data (i.e. what's returned by Categorical.category_array or Categorical.category_dict). # Single-key Categorical dates = rt.Date( [ '2019-03-15', '2019-04-18', '2019-05-17', '2019-06-21', '2019-07-19', '2019-08-16', '2019-09-20', '2019-10-18', '2019-11-15', '2019-12-20', ] ) dates.name = 'dates' dates_cat = rt.Cat(dates) cats = dates_cat.categories() assert type(dates) == type(cats) # Multi-key Categorical datestrs = rt.FA( [ '2019-03-15', '2019-04-18', '2019-05-17', '2019-06-21', '2019-07-19', '2019-08-16', '2019-09-20', '2019-10-18', '2019-11-15', '2019-12-20', ] ) datestrs.name = 'datestrs' mcat = rt.Cat([dates, datestrs]) mcats = mcat.categories() assert type(mcats['key_0']) == type(dates) assert type(mcats['key_1']) == type(datestrs) # Empty single-key Categorical dates = rt.Date([]) dates_cat = rt.Cat(dates) cats = dates_cat.categories() assert type(dates) == type(cats) def test_make_unique(self): # SJK: changed this test on 8/21/2018 - count now comes from the grouping object, not Categories.make unique values = FastArray(['a', 'b', 'c', 'c', 'd', 'a', 'b']) # c = Categories([],base_index=1) # index, cat_len, filter = c.make_unique(values) cat = Categorical(values, ordered=True, base_index=1, filter=None) index = cat._fa c = cat._categories_wrap assert len(index) == 7 assert max(index) == 4 assert c._mode == CategoryMode.StringArray assert c._list.dtype.char == 'S' assert c.isbytes univals = values.astype('U') cat = Categorical(univals, ordered=True, base_index=1, filter=None, unicode=True) index = cat._fa c = cat._categories_wrap assert len(index) == 7 assert max(index) == 4 assert c._mode == CategoryMode.StringArray assert c._list.dtype.char == 'U' assert c.isunicode @pytest.mark.xfail( reason='20200416 This test was previously overridden by a later test in the file with the same name. Need to revisit and get back in a working state.' ) def test_force_base_index(self): filter = FastArray([True, True, False, False, True]) c = Categorical(['a', 'a', 'b', 'c', 'a']) assert c.base_index == 1, 'Did not default base index to 1' assert c._fa[0] == 1, 'Did not default base index to 1' c = Categorical(['a', 'a', 'b', 'c', 'a'], base_index=0) assert c.base_index == 0, 'Did not force base index to 0' assert c._fa[0] == 0, 'Did not force base index to 0' c = Categorical(['a', 'a', 'b', 'c', 'a'], filter=filter) assert len(c.category_array) == 1 assert c._fa[2] == 0, 'Did not default base index to 1' c = Categorical(['a', 'a', 'b', 'c', 'a'], base_index=0, filter=filter) assert len(c.category_array) == 1 assert c._fa[2] == INVALID_DICT[c.dtype.num], 'Did not force base index to 0' with pytest.raises(ValueError): c = Categorical(['a', 'a', 'b', 'c', 'a'], base_index=99, filter=filter) c = Categorical(['a', 'a', 'b', 'c', 'a'], ['a', 'b', 'c']) assert c.base_index == 1, 'Did not default base index to 1' assert c._fa[0] == 1, 'Did not default base index to 1' c = Categorical(['a', 'a', 'b', 'c', 'a'], ['a', 'b', 'c'], base_index=0) assert c.base_index == 0, 'Did not force base index to 0' assert c._fa[0] == 0, 'Did not force base index to 0' with pytest.raises(NotImplementedError): c = Categorical(['a', 'a', 'b', 'c', 'a'], ['a', 'b', 'c'], base_index=0, filter=filter) with pytest.raises(ValueError): c = Categorical([1.0, 2.0, 3.0], ['a', 'b', 'c'], from_matlab=True, base_index=0) pdc = pd.Categorical(['a', 'a', 'b', 'c', 'a']) with pytest.raises(ValueError): c = Categorical(pdc, base_index=0) def test_is_in_unique_strings(self): values = ['a', 'b', 'c', 'c', 'd', 'a', 'b'] good_cats = ['a', 'b', 'c', 'd'] incomplete_cats = ['a', 'b', 'c'] bad_cats = ['a', 'a', 'b'] invalid = 'invalid' ###--------REMOVED from_provided_categories, rewrite these tests to go through main constructor # valid bytes c = Categorical(values, good_cats, ordered=True, base_index=1, unicode=False, filter=None) cats = c._categories_wrap assert len(c) == 7 assert max(c._fa) == 4 assert cats._mode == CategoryMode.StringArray assert cats._list.dtype.char == 'S' assert cats.isbytes # valid unicode c = Categorical(values, good_cats, ordered=True, base_index=1, unicode=True, filter=None) cats = c._categories_wrap assert len(c) == 7 assert max(c._fa) == 4 assert cats._mode == CategoryMode.StringArray assert cats._list.dtype.char == 'U' assert cats.isunicode # non-unique categories # 4/12/2019 - no longer checks for uniqueness # with self.assertRaises(ValueError): # c = Categories.from_provided_categories(values, bad_cats, ordered=True, base_index=1, unicode=False, filter=None) # not all values found in categories with pytest.raises(ValueError): c = Categorical(values, incomplete_cats, ordered=True, base_index=1, unicode=False, filter=None,) # insert invalid True # 5/16/2019 invalid must appear in provided uniques with pytest.raises(ValueError): c = Categorical( values, incomplete_cats, ordered=True, base_index=1, unicode=True, filter=None, invalid=invalid, ) cats = c._categories_wrap assert len(c) == 7 assert max(c._fa) == 3 assert cats._mode == CategoryMode.StringArray assert cats._list.dtype.char == 'U' assert cats.isunicode def test_getitem_enum_str(self): codes = [1, 44, 44, 133, 75] correct = [True, False, False, False, False] valid_str = 'StronglyDisagree' invalid_str = 'q' c = Categorical(codes, LikertDecision) # with self.assertRaises(IndexError): mask = c[valid_str] is_correct = bool(np.all(mask == correct)) assert is_correct with pytest.raises(ValueError): mask = c[invalid_str] assert sum(mask) == 0 def test_match_str_to_category(self): single_byte = b'a' single_unicode = 'a' single_true_unicode = u'\u2082' byte_values = [b'a', b'b', b'c', b'c', b'd', b'a', b'b'] values = FastArray(['a', 'b', 'c', 'c', 'd', 'a', 'b']) true_unicode = [u'\u2082', u'\u2083', u'\u2082'] # 4/25/2019 - changed these tests to construct a Categorical, rather than # a Categories object directly. Categorical will always make a Categories object. # (held in _categories_wrap) c = Categorical(values, ordered=True, base_index=1, filter=None) matching_char = c._categories_wrap.match_str_to_category(single_unicode) assert isinstance(matching_char, bytes) with pytest.raises(TypeError): matching = c._categories_wrap.match_str_to_category(single_true_unicode) univals = np.array(['a', 'b', 'c', 'c', 'd', 'a', 'b']) c = Categorical(univals, ordered=True, base_index=1, filter=None, unicode=True) matching_char = c._categories_wrap.match_str_to_category(single_byte) assert isinstance(matching_char, str) c = Categorical(values, ordered=True, base_index=1, filter=None) matching = c._categories_wrap.match_str_to_category(values) assert matching.dtype.char == 'S' with pytest.raises(TypeError): matching = c._categories_wrap.match_str_to_category(true_unicode) c = Categorical(univals, ordered=True, base_index=1, filter=None, unicode=True) matching = c._categories_wrap.match_str_to_category(values) assert matching.dtype.char == 'U' # Categories object being removed # Disabling these tests - methods will move into Categorical # 4/24/2019 # def test_get_category_index(self): # values = FastArray(['a', 'b', 'c', 'c', 'd', 'a', 'b', 'g']) # _, c, _, _ = Categories.from_array(values, ordered=True, base_index=1, filter=None) # # when found, will return exact index # str_idx = c.get_category_index('b') # self.assertEqual(str_idx, 2) # # when ordered, will return floating point for LTE GTE # str_idx = c.get_category_index('e') # self.assertEqual(str_idx, 4.5) # # when unordered, will return invalid index (length of string array) # c._sorted = False # str_idx = c.get_category_index('e') # self.assertEqual(str_idx, 6) # def test_get_category_match_index(self): # values = FastArray(['a', 'b', 'c', 'c', 'd', 'a', 'b', 'g']) # _, c, _, _ = Categories.from_array(values, ordered=False, base_index=1, filter=None) # string_matches = c.get_category_match_index(['a','b']) # self.assertEqual(string_matches, [1,2]) # c._mode = CategoryMode.IntEnum # with self.assertRaises(NotImplementedError): # string_matches = c.get_category_match_index(['a','b']) def test_possibly_invalid(self): values = ['a', 'b', 'c', 'c', 'd', 'a', 'b', 'g'] c = Categorical(values, base_index=1) out_of_range = -50 sentinel = INVALID_DICT[c.dtype.num] c.view(FastArray)[0] = out_of_range # c.view(FastArray)[1] = sentinel # **changed invalid, all will display as bad code if changed underneath and not in range assert c[0] == "!<-50>" # self.assertEqual(c[1], "!<inv>") def test_categories_getitem_str_list(self): codes = [1, 44, 44, 133, 75] correct = FastArray([False, True, True, False, True]) c = Categorical(codes, LikertDecision) mask = c[['StronglyAgree', 'Disagree']] is_correct = bool(np.all(mask == correct)) assert is_correct mask = c[[b'StronglyAgree', b'Disagree']] is_correct = bool(np.all(mask == correct)) assert is_correct def test_categories_print_repr(self): self._notimpl() def test_enum_dict_warning(self): class DupeEnum(IntEnum): code_a = 1 code_b = 1 code_c = 1 code_d = 2 with pytest.warns(UserWarning): c = Categorical([1, 2], DupeEnum) # ------------------------- TEST MERGE ------------------------------------------- # def test_merge(self): # from riptable.rt_categorical import categorical_merge # c_bytes = Categorical(['b','b','b','a','b','b'], ['a','b']) # c_unicode = Categorical(["AAPL\u2080","AMZN\u2082"]) # result = categorical_merge([c_bytes, c_unicode]) # # self.assertTrue(result[0]._categories_wrap._list is result[1]._categories_wrap._list, msg=f"Categorical merge did not assign the same dictionary to both arrays.") # self.assertEqual(result[0]._categories_wrap._list.dtype.char, 'U', msg=f"{result[0]._categories_wrap._list.dtype.char} was not 'U'. dictionary was not flipped to unicode.") # for item in c_bytes._categories_wrap._list: # self.assertTrue(item.decode() in result[0]._categories_wrap._list, msg=f"{item} did not appear in final categories") # for item in c_unicode._categories_wrap._list: # self.assertTrue(item in result[0]._categories_wrap._list, msg=f"{item} did not appear in final categories") # c1 = Categorical([1, 1, 3, 2, 2], [1, 2, 3, 4, 5], from_matlab=True) # c2 = Categorical([2, 2, 4, 4, 3], [1, 2, 3, 4, 5], from_matlab=True) # [cm1, cm2] = categorical_merge([c1, c2]) # self.assertTrue((cm1 == [1, 1, 3, 2, 2]).all()) # self.assertTrue((cm2 == [2, 2, 4, 4, 3]).all()) # ------------------------- TEST HSTACK ------------------------------------------- def test_hstack(self): c1 = Categorical(['a', 'a', 'c', 'b', 'b']) c2 = Categorical(['b', 'b', 'd', 'd', 'c']) cm = Categorical.hstack([c1, c2]) assert (cm.as_string_array == ['a', 'a', 'c', 'b', 'b', 'b', 'b', 'd', 'd', 'c']).all() c1 = Categorical([1, 1, 3, 2, 2], [1, 2, 3, 4, 5], from_matlab=True) c2 = Categorical([2, 2, 4, 4, 3], [1, 2, 3, 4, 5], from_matlab=True) cm = Categorical.hstack([c1, c2]) assert (cm == [1, 1, 3, 2, 2, 2, 2, 4, 4, 3]).all() def test_hstack_fails_for_different_mode_cats(self): # Create a dictionary-mode Categorical (from ISO3166 data). # The dictionary is created manually below instead of using e.g. # {k: int(v) for (k, v) in ISOCountryCode.__members__.items()} # so the dictionary we give to Categorical does not have the insert ordering # imply an ordering of the keys/values. country_code_dict = { 'IRL': 372, 'USA': 840, 'AUS': 36, 'HKG': 344, 'JPN': 392, 'MEX': 484, 'KHM': 116, 'THA': 764, 'JAM': 388, 'ARM': 51 } # The values for the Categorical's backing array. # This includes some value(s) not in the dictionary and not all values in the dictionary are used here. country_num_codes = [36, 36, 344, 840, 840, 372, 840, 372, 840, 124, 840, 124, 36, 484] cat1 = rt.Categorical(country_num_codes, country_code_dict) assert cat1.category_mode == CategoryMode.Dictionary # Create a single-key, string-mode Categorical. cat2 = rt.Categorical(['AUS', 'AUS', 'HKG', 'USA', 'USA', 'IRL', 'USA', 'IRL', 'USA', 'KHM', 'IRL', 'AUS', 'MEX']) assert cat2.category_mode != CategoryMode.Dictionary # Try to hstack the two Categoricals. This should fail due to the CategoryMode values being different. with pytest.raises((ValueError, TypeError)): rt.hstack([cat1, cat2]) def test_align(self): c1 = Categorical(['a', 'b', 'c']) c2 = Categorical(['d', 'e', 'f']) c3 = Categorical(['c', 'f', 'z']) cm = Categorical.align([c1, c2, c3]) assert (cm[0].as_string_array == ['a', 'b', 'c']).all() assert (cm[1].as_string_array == ['d', 'e', 'f']).all() assert (cm[2].as_string_array == ['c', 'f', 'z']).all() assert (cm[0].categories() == FastArray([b'Filtered', b'a', b'b', b'c', b'd', b'e', b'f', b'z'])).all() assert (cm[0].categories() == cm[1].categories()).all() assert (cm[0].categories() == cm[2].categories()).all() c1 = Categorical([1, 1, 3, 2, 2], [1, 2, 3, 4, 5], from_matlab=True) c2 = Categorical([2, 2, 4, 4, 3], [1, 2, 3, 4, 5], from_matlab=True) cm = Categorical.align([c1, c2]) assert (cm[0] == [1, 1, 3, 2, 2]).all() assert (cm[1] == [2, 2, 4, 4, 3]).all() # Multikey with nested Categorical c1 = Categorical([Categorical(['a']), FastArray([1])]) c2 = Categorical([Categorical(['b']), FastArray([2])]) cm = Categorical.align([c1, c2]) assert cm[0][0] == ('a', 1) assert cm[1][0] == ('b', 2) assert cm[0].category_dict == cm[1].category_dict def test_categorical_merge_dict(self): from riptable.rt_categorical import categorical_merge_dict d1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5} d2 = {'a': 1, 'e': 5, 'b': 2, 'f': 6} c1 = Categorical([3, 3, 4, 3, 1, 2, 5], d1) c2 = Categorical([1, 1, 5, 2, 2, 1, 5], d2) combined = categorical_merge_dict([c1, c2], return_type=dict) for i in range(1, 6): assert i in combined.values() def test_getitem_empty(self): c = Categorical([0, 1, 2], ['a', 'b', 'c']) empty_list = c[[]] assert isinstance(empty_list, Categorical) dict_matches = bool(np.all(empty_list.categories() == c.categories())) assert dict_matches with pytest.raises(IndexError): empty_np = c[np.array([])] assert isinstance(empty_np, Categorical) dict_matches = bool(np.all(empty_np.categories() == c.categories())) assert dict_matches def test_iter_groups(self): correct_keys = FastArray(['a', 'b', 'c', 'd', 'e']) correct_idx = [[8], [3], [5, 6], [2, 9], [0, 1, 4, 7]] str_arr = FastArray(['e', 'e', 'd', 'b', 'e', 'c', 'c', 'e', 'a', 'd']) c = Categorical(str_arr) for i, tup in enumerate(c.iter_groups()): assert tup[0] == correct_keys[i] assert bool(np.all(tup[1] == correct_idx[i])) def test_enum_dict_multi(self): self._notimpl() # not implemented def test_enum_init_errors(self): with pytest.raises(TypeError): c = Categorical(['a', 'b', 'c'], LikertDecision) def test_custom_invalid_category(self): # 5/16/2019 invalid must appear in provided uniques c = Categorical( ['a', 'b', 'c', 'my_invalid'], ['a', 'b', 'c', 'my_invalid'], invalid='my_invalid', base_index=1, ) assert c[3] == 'my_invalid' assert c.isnan()[3] assert len(c.category_array) == 4 @pytest.mark.xfail(reason="After invalid_set, the custom invalid value is not displayed.") def test_invalid_set(self): c = Categorical( ['a', 'b', 'c', 'my_invalid'], ['a', 'b', 'c', 'my_invalid'], invalid='my_invalid', base_index=1, ) # set a new string to be displayed for invalid items and validate custom_invalid = "custom_invalid" c.invalid_set(custom_invalid) assert c[3] == custom_invalid assert c.isnan()[3] assert len(c.category_array) == 4 def test_lock_unlock(self): self._notimpl() # halfway implemented def test_set_item(self): self._notimpl() # when index needs to be fixed after categories are added # setitem with integer / invalid integer # setitem with string / invalid category def test_return_empty_cat(self): self._notimpl() # this code still needs to get written def test_getitem_np_str(self): c = Categorical(['a', 'a', 'b', 'a', 'c', 'c', 'b']) correct = FastArray([True, True, True, True, False, False, True]) with pytest.raises(IndexError): result = c[np.array(['a', 'b'])] # self.assertTrue(array_equal(result, correct), msg=f"incorrect getitem result when indexing by numpy array of strings") with pytest.raises(IndexError): result = c[np.array(['a', 'b']).astype('S')] # self.assertTrue(array_equal(result, correct), msg=f"incorrect getitem result when indexing by numpy array of strings") def test_getitem_slice(self): c = Categorical(['a', 'a', 'b', 'a', 'c', 'c', 'b']) result = c[:3] assert isinstance(result, Categorical) match_fa = bool(np.all(result.view(FastArray) == [1, 1, 2])) assert match_fa assert len(result) == 3 assert len(result._categories_wrap) == 3 def test_categorical_compare_check(self): self._notimpl() # Categories have different modes # categories are both enum # compare cat to empty list # non-categorical input # convert all to unicode if one is unicode # this keyword wasn't used anywhere, removed from copy() # def test_copy_invalid(self): # c = Categorical(['a','a','b','a','c','c','b']) # invalid_copy = c.copy(fill_invalid=True) # all_invalid = bool(np.all(invalid_copy.view(FastArray)==-128)) # self.assertTrue(all_invalid) # for idx, item in enumerate(c.categories()): # self.assertEqual(item, invalid_copy.categories()[idx]) # self.assertFalse(c.categories() is invalid_copy.categories()) def test_fill_invalid(self): values = list('aabaccb') c = Categorical(values, base_index=1) c.fill_invalid(inplace=True) assert_array_equal(FastArray([c.filtered_name] * len(values)), c.expand_array) assert_array_equal(FastArray([0] * len(values)), c._fa) expected = FastArray(sorted(set(values))).astype('|S1') assert_array_equal(expected, c.category_array) assert_array_equal(expected, c.category_dict[next(iter(c.category_dict))]) # values of first key def test_force_unicode(self): c = Categorical(['a', 'a', 'b', 'a', 'c', 'c', 'b'], unicode=True) result_dtype = c.categories().dtype.char assert result_dtype == 'U', f"Failed to force unicode when constructing categorical from list of string values" def test_categories_shallow_copy(self): codes = [10, 10, 20, 10, 30, 20, 10] d = {10: 'a', 20: 'b', 30: 'c'} c = Categorical(codes, d) original_cats = c._categories_wrap new_cats = original_cats.copy(deep=False) assert ( original_cats._str_to_int_dict is new_cats._str_to_int_dict ), f"Categories did not use same str_to_int dictionary after shallow copy." assert ( original_cats._int_to_str_dict is new_cats._int_to_str_dict ), f"Categories did not use same int_to_str dictionary after shallow copy." # 5/16/2019 invalid category must be in user provided # def test_two_lists_invalid(self): # c = Categorical(['a','a','b','a','c','c','b'],np.array(['a','b']), invalid='inv', base_index=1) # self.assertEqual(c[4],FILTERED_LONG_NAME) @pytest.mark.xfail( reason='20200416 This test was previously overridden by a later test in the file with the same name. Need to revisit and get back in a working state.' ) def test_getitem_enum_list(self): c = Categorical([44, 133, 133, 75, 144, 1], LikertDecision) with pytest.raises(IndexError): result = c[[b'NeitherAgreeNorDisagree']] correct = FastArray([False, False, False, False, True, False]) # self.assertTrue(array_equal(result, correct)) result = c[[4]] assert result[0] == 'NeitherAgreeNorDisagree' def test_non_unique(self): with pytest.raises(ValueError): c = Categorical(['a', 'a', 'b', 'a', 'c', 'c', 'b'], ['a', 'a', 'b']) def test_match_to_category(self): c = Categorical(['a', 'a', 'b', 'a', 'c', 'c', 'b']) result = c._categories_wrap.match_str_to_category('a') assert b'a' == result with pytest.raises(TypeError): result = c._categories_wrap.match_str_to_category([1, 2, 3]) with pytest.raises(TypeError): result = c._categories_wrap.match_str_to_category({1, 2, 3}) c1 = Categorical(['abc', 'def', 'abc', 'abc'], np.array(['abc', 'def']), unicode=True) result = c1._categories_wrap.match_str_to_category([b'a']) assert result.dtype.char == 'U' # ------------------------------------TEST SET ITEM------------------------------------------ def test_set_item_str_index(self): c = Categorical(['b', 'b', 'b', 'a', 'b', 'b'], ['a', 'b']) correct = [2, 2, 2, 2, 2, 2] c['a'] = 'b' is_correct = bool(np.all(c.view(FastArray) == correct)) assert is_correct, f"Category was not correctly changed with set item on a string." with pytest.raises(ValueError): c['b'] = 'c' def test_set_item_int_index(self): c = Categorical(['b', 'b', 'b', 'a', 'b', 'b'], ['a', 'b']) correct = [1, 2, 2, 1, 2, 2] c[0] = 'a' is_correct = bool(np.all(c.view(FastArray) == correct)) assert is_correct, f"Category was not correctly changed with set item on an int." with pytest.raises(ValueError): c[0] = 'c' # ------------------------------------TEST CALCULATE DTYPE ---------------------------------- def test_get_dtype_from_len(self): ''' Categorical will select different types ''' dtype_sizes = { np.int8: 1, np.int16: 101, np.int32: 50001, } # , np.int64:2000000001 } for dt, sz in dtype_sizes.items(): LENGTH = 6 NO_CODES = sz alphabet = list('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789') np_alphabet = np.array(alphabet, dtype="|U1") np_codes = np.random.choice(np_alphabet, [NO_CODES, LENGTH]) codes = ["".join(np_codes[i]) for i in range(len(np_codes))] c = Categorical(["".join(np_codes[i]) for i in range(len(np_codes))]) # only perform the test if there are enough uniques if len(c._categories_wrap._list) >= sz: assert c.dtype == dt, f"Categorical did not set dtype to {dt} for array of size {sz}." # -------SINGLE INTEGER def test_getitem_int(self): ''' Single integer index should return the corresponding category in unicode format. ''' c = Categorical(['b', 'b', 'b', 'a', 'b', 'b'], ['a', 'b']) assert c[0] == 'b', f"Get item with integer did not return the correct category." assert isinstance(c[0], str), f"Get item with integer did not return as unicode." assert c[3] == 'a', f"Get item with integer did not return the correct category." assert isinstance(c[3], str), f"Get item with integer did not return as unicode." with pytest.raises(IndexError): d = c[10] # --------INTEGER MASK def test_getitem_int_mask(self): py_mask = [0, 3] c = Categorical(['b', 'b', 'b', 'a', 'b', 'b'], ['a', 'b']) for mask in [py_mask, np.array(py_mask)]: d = c[mask] assert isinstance( d, Categorical ), f"Get item with integer mask did not return a categorical. Returned {type(d).__name__} instead." assert len(d) == len( mask ), f"Get item with integer mask did not return categorical of {len(mask)}. returned {len(d)} instead." has_same_cats = bool(np.all(d._categories_wrap._list == c._categories_wrap._list)) assert ( has_same_cats ), f"Failed to copy the same categories to new categorical after getitem with integer mask." d = c[[0, 10]] assert d._fa[1] == 0, f"Failed to put invalid for out of range index." # -------BOOLEAN MASK def test_getitem_bool_mask(self): py_mask = [True, True, True, False, True, True] c = Categorical(['b', 'b', 'b', 'a', 'b', 'b'], ['a', 'b']) for mask in [py_mask, np.array(py_mask)]: d = c[mask] assert not ( b'a' in d.as_string_array ), f"b'a' does not get trimmed out of categorical with getitem from boolean array." assert 5 == len( d ), f"Length {len(d)} did not match 5 in categorical getitem with a boolean array of the same size." has_same_cats = bool(np.all(d._categories_wrap._list == c._categories_wrap._list)) assert ( has_same_cats ), f"Failed to copy the same categories to new categorical after getitem with integer mask." # -------SINGLE STRING def test_getitem_single_string(self): b_result = [True, True, True, False, True, True] c = Categorical(['b', 'b', 'b', 'a', 'b', 'b'], ['a', 'b']) idx = b'c' # with self.assertRaises(IndexError): d = c[idx] has_true = bool(np.any(d)) assert not has_true, f"Failed to return an array of all false for getitem with {idx}" assert isinstance(d, FastArray), f"Get item input {idx} did not return FastArray" assert d.dtype.char == '?', f"Get item input {idx} did not return FastArray" idx = idx.decode() # with self.assertRaises(IndexError): d = c[idx] has_true = bool(np.any(d)) assert not has_true, f"Failed to return an array of all false for getitem with {idx}" assert isinstance(d, FastArray), f"Get item input {idx} did not return FastArray" assert d.dtype.char == '?', f"Get item input {idx} did not return FastArray" idx = b'b' # with self.assertRaises(IndexError): d = c[idx] is_correct = bool(np.all(d == b_result)) assert is_correct, f"Did not return the correct array for getitem with {idx}" assert isinstance(d, FastArray), f"Get item input {idx} did not return FastArray" assert d.dtype.char == '?', f"Get item input {idx} did not return FastArray" idx = idx.decode() # with self.assertRaises(IndexError): d = c[idx] is_correct = bool(np.all(d == b_result)) assert is_correct, f"Did not return the correct array for getitem with {idx}" assert isinstance(d, FastArray), f"Get item input {idx} did not return FastArray" assert d.dtype.char == '?', f"Get item input {idx} did not return FastArray" # ------MULTIPLE STRINGS def test_getitem_multiple_strings(self): c = Categorical(['b', 'b', 'b', 'a', 'b', 'b']) inputs = { (b'b',): [True, True, True, False, True, True], # single in (list) (b'c',): [False, False, False, False, False, False], # single not in (list) (b'a', b'b'): [True, True, True, True, True, True], # both in (list) (b'c', b'd'): [False, False, False, False, False, False,], # both not in (list) (b'b', b'c'): [True, True, True, False, True, True], # mixed (list) } for idx, correct in inputs.items(): idx = list(idx) d = c[idx] is_correct = bool(np.all(d == correct)) assert is_correct, f"Indexing categorical {c} by {idx} did not return the correct result." assert d.dtype.char == '?', f"Get item input {idx} did not return FastArray" idx = [b.decode() for b in idx] d = c[idx] is_correct = bool(np.all(d == correct)) assert is_correct, f"Indexing categorical {c} by {idx} did not return the correct result." assert d.dtype.char == '?', f"Get item input {idx} did not return FastArray" # ------NUMERIC GETITEM def test_getitem_numeric_categories(self): # before it was fixed, a bug was returning a string of the numeric category nums = np.array([1, 1, 2, 3, 4, 5, 1, 1, 1]) c = Categorical(nums) assert c[0] == 1 assert isinstance(c[0], (int, np.integer)) nums = nums.astype(np.float32) c = Categorical(nums) assert c[0] == 1.0 assert isinstance(c[0], (float, np.floating)), f"Expected float, got {type(c[0])}" # ------------------------- TEST COMPARE CHECK ------------------------------------------- def test_compare_check(self): ''' Test comparison between two 'equal' categoricals with different underlying arrays. ''' compare_ops = { '__ne__': [False, False, False, False, False, False], '__eq__': [True, True, True, True, True, True], '__ge__': [True, True, True, True, True, True], '__gt__': [False, False, False, False, False, False], '__le__': [True, True, True, True, True, True], '__lt__': [False, False, False, False, False, False], } c = Categorical(['b', 'b', 'b', 'a', 'b', 'b'], ['a', 'b', 'c']) d = Categorical(['b', 'b', 'b', 'a', 'b', 'b'], ['a', 'b']) for name, correct in compare_ops.items(): func = c.__getattribute__(name) result = func(d) is_correct = bool(np.all(result == correct)) assert is_correct, f"Compare operation betweeen two equal categoricals did not return the correct result." def test_compare_return_type(self): ''' Test comparison operations with single strings to make sure FastArray of boolean is returned. ''' c = Categorical(['b', 'b', 'b', 'a', 'b', 'b'], ['a', 'b']) scalars = ['a', 'c'] compare_ops = ['__ne__', '__eq__', '__ge__', '__gt__', '__le__', '__lt__'] for s in scalars: for op in compare_ops: func = c.__getattribute__(op) result = func(s) assert isinstance(result, FastArray), f"comparison {op} with input {s} did not return FastArray" assert result.dtype.char == '?', f"comparison {op} with input {s} did not return boolean" def test_compare_different_modes(self): c1 = Categorical(['b', 'b', 'b', 'a', 'b', 'b'], ['a', 'b']) c2 = Categorical([0, 1], {0: 'a', 1: 'b'}) with pytest.raises(TypeError): c1 == c2 def test_compare_conflicting_dicts(self): c1 = Categorical([0, 1], {0: 'a', 1: 'b'}) c2 = Categorical([0, 1], {1: 'a', 0: 'b'}) with pytest.raises(ValueError): c1 == c2 def test_compare_safe_dicts(self): c1 = Categorical([0, 1], {0: 'a', 1: 'b'}) c2 = Categorical([2, 1], {2: 'c', 1: 'b'}) correct = FastArray([False, True]) result = c1 == c2 match = bool(np.all(correct == result)) assert match def test_isnan(self): c = Categorical([1, 1, 3, 2, 2], ['a', 'b', 'c'], base_index=1, invalid='a') is_correct = [True, True, False, False, False] is_not_correct = [False, False, True, True, True] assert bool(np.all(is_correct == isnan(c))) assert bool(np.all(is_correct == c.isnan())) assert bool(np.all(is_not_correct == isnotnan(c))) assert bool(np.all(is_not_correct == c.isnotnan())) # ------------------------------------------------------ def test_get_categories(self): # string list c = Categorical(['a', 'b', 'c', 'd', 'e']) catsarray = c.category_array assert isinstance(catsarray, np.ndarray) catsdict = c.category_dict assert isinstance(catsdict, dict) assert len(catsdict) == 1 with pytest.raises(TypeError): catscodes = c.category_codes with pytest.raises(TypeError): catsmapping = c.category_mapping # numeric list c = Categorical(np.array([1, 2, 3, 4, 5])) catsarray = c.category_array assert isinstance(catsarray, np.ndarray) catsdict = c.category_dict assert isinstance(catsdict, dict) assert len(catsdict) == 1 with pytest.raises(TypeError): catscodes = c.category_codes with pytest.raises(TypeError): catsmapping = c.category_mapping # dict/enum c = Categorical([1, 2, 3, 4], {1: 'a', 2: 'b', 3: 'c', 4: 'd'}) catsarray = c.category_array assert isinstance(catsarray, np.ndarray) catsdict = c.category_dict assert isinstance(catsdict, dict) assert len(catsdict) == 1 catscodes = c.category_codes assert isinstance(catscodes, np.ndarray) catsmapping = c.category_mapping assert isinstance(catsmapping, dict) # multikey c = Categorical([np.arange(5), np.random.rand(5)]) with pytest.raises(TypeError): catsarray = c.category_array catsdict = c.category_dict assert isinstance(catsdict, dict) assert len(catsdict), 2 with pytest.raises(TypeError): catscodes = c.category_codes with pytest.raises(TypeError): catsmapping = c.category_mapping # ------------------------------------------------------ def test_force_base_index2(self): c = Categorical(['a', 'a', 'b', 'c', 'a']) assert c.base_index == 1 assert c._fa[0] == 1 c = Categorical(['a', 'a', 'b', 'c', 'a'], base_index=0) assert c.base_index == 0 assert c._fa[0] == 0 codes = np.array([0, 0, 1, 2, 0]) cats = np.array(['a', 'b', 'c']) # c = Categorical(codes, cats) # self.assertEqual(c.base_index, 0) # self.assertEqual(c._fa[0], 0) codes += 1 c = Categorical(codes, cats, base_index=1) assert c.base_index == 1 assert c._fa[0] == 1 codes = codes.astype(np.float32) c = Categorical(codes, cats, from_matlab=True) assert c.base_index == 1 assert c._fa[0] == 1 with pytest.raises(ValueError): c = Categorical(codes, cats, from_matlab=True, base_index=0) c = Categorical(np.array(['a', 'a', 'b', 'c', 'a']), np.array(['a', 'b', 'c'])) assert c.base_index == 1 assert c._fa[0] == 1 c = Categorical(np.array(['a', 'a', 'b', 'c', 'a']), np.array(['a', 'b', 'c']), base_index=0) assert c.base_index == 0 assert c._fa[0] == 0 # ------------------------------------------------------ def test_ordered(self): c = Categorical(['c', 'c', 'a', 'b', 'c']) cats = c.category_array assert cats[0] == b'a' c = Categorical(['c', 'c', 'a', 'b', 'c'], ordered=False) cats = c.category_array assert cats[0] == b'c' c = Categorical(['c', 'c', 'a', 'b', 'c'], ['c', 'a', 'b']) cats = c.category_array assert cats[0] == b'c' assert not c.ordered c = Categorical(['c', 'c', 'a', 'b', 'c'], ['a', 'b', 'c']) assert c.ordered ## removed this test - side-effect of search sorted with unsorted array (not categorical related) ## false claim that categories are ordered in keyword # c = Categorical(['c','c','a','c','c'], ['c','a','b'], ordered=True) # self.assertTrue(bool(np.all(c!='c'))) # self.assertTrue(bool(np.all(c!=b'c'))) c = Categorical(['c', 'c', 'a', 'b', 'c'], ['c', 'a', 'b'], ordered=False) cats = c.category_array assert cats[0] == b'c' assert not c.ordered codes = FastArray([0, 0, 1, 2, 0]) cats = FastArray(['c', 'b', 'a'], unicode=True) c = Categorical(codes, cats) assert c.category_array[0] == 'c' assert not c.ordered # with self.assertWarns(UserWarning): # c = Categorical(codes, cats, ordered=True) # self.assertEqual(c.category_array[0], b'c') # self.assertFalse(c.ordered) # ------------------------------------------------------ def test_keywords_not_allowed(self): # filter + base index 0 f = np.array([True, False, True]) with pytest.raises(ValueError): c = Categorical(['a', 'b', 'c'], filter=f, base_index=0) # ------------------------------------------------------ def test_display_properties(self): ''' Categoricals take over their display properties to appear like strings (not the underlying integer array) (see Utils.rt_display_properties) ''' c = Categorical(['b', 'b', 'b', 'a', 'b', 'b'], ['a', 'b']) item_format, convert_func = c.display_query_properties() assert item_format.length == DisplayLength.Long, f"Incorrect length for item format." assert item_format.justification == DisplayJustification.Left assert item_format.invalid == None assert item_format.can_have_spaces == True assert item_format.decoration == None assert item_format.color == DisplayColumnColors.Default assert convert_func.__name__ == 'display_convert_func' # this could change, right now the convert function just does a str over the item assert convert_func(1, item_format) == '1', f"Incorrect convert function was returned." # ------------------------------------------------------ # -----MISC. COVER TESTS-------------------------------- def test_non_array_dict_categories_ctor(self): with pytest.raises(TypeError): c = Categories(['garbage', 'list']) def test_too_many_args_categories_ctor(self): with pytest.raises(ValueError): c = Categories(FastArray([1]), FastArray([2]), FastArray([3])) def test_filter_and_invalid(self): c = Categorical( ['a', 'a', 'b', 'c', 'c'], ['c'], invalid='a', filter=FastArray([True, True, False, True, True]), ) c.filtered_set_name('a') assert bool(np.all(c._fa == [0, 0, 0, 1, 1])) for i in range(3): assert c[i] == 'a' for i in range(3, 5): assert c[i] == 'c' def test_zero_base_with_invalid(self): with pytest.raises(ValueError): c = Categorical(['a', 'b', 'c'], ['b', 'c'], base_index=0) # removed this property from Categories 04/24/2019 # def test_multikey_labels(self): # c = Categorical([FastArray(['a','b','c']), FastArray([1,2,3])]) # labels = c._categories_wrap.multikey_labels # self.assertTrue(isinstance(labels[0], tuple)) # self.assertEqual(labels[0][0],'a') def test_ncols_non_multikey(self): c = Categorical(['a', 'b', 'c']) assert c._categories_wrap.ncols == 1 # now checks for single / multikey / enum, not CategoryMode # def test_len_undefined_mode(self): # c = Categorical(['a','b','c']) # c._categories_wrap._mode = CategoryMode.Default # self.assertEqual(len(c._categories_wrap),0) def test_categories_copy_shallow(self): c = Categorical(['a', 'b', 'c']) copycat = c._categories_wrap.copy(deep=False) assert isinstance(copycat, Categories) def test_categories_copy_deep(self): c = Categorical([1, 2, 3], {1: 'a', 2: 'b', 3: 'c'}) copycat = c._categories_wrap.copy(deep=False) assert isinstance(copycat, Categories) # impossible path, unless mode is forced like below. disabling 4/24/2019 # c._categories_wrap._mode = CategoryMode.Default # with self.assertRaises(NotImplementedError): # c = c._categories_wrap.copy() def test_wrap_get_categories(self): c = Categorical(['a', 'b', 'c']) arr = c._categories_wrap.get_categories() assert isinstance(arr, FastArray) c = Categorical([FastArray(['a', 'b', 'c']), FastArray([1, 2, 3])]) d = c._categories_wrap.get_categories() assert isinstance(d, dict) def test_get_string_mode_nums(self): c = Categorical(np.arange(5)) assert not c._categories_wrap.isbytes assert not c._categories_wrap.isunicode def test_pop_single_arr(self): c = Categorical([np.array(['a', 'b', 'c'])]) d = Categorical(np.array(['a', 'b', 'c'])) assert bool(np.all(c == d)) c = Categorical({'test': np.array(['a', 'b', 'c'])}) d = Categorical(np.array(['a', 'b', 'c'])) assert bool(np.all(c == d)) def test_from_cat_as_array(self): c = Categorical(FastArray([1, 2, 3]), _from_categorical=np.array(['a', 'b', 'c'])) assert isinstance(c.category_array, FastArray) assert c.base_index == 1 def test_from_pandas_object(self): pdc = pd.Categorical(['a', 'b', 'c']) c = Categorical(pdc, unicode=True) assert c.category_array.dtype.char == 'U' c = Categorical(pdc, unicode=False) assert c.category_array.dtype.char == 'S' pdc = pd.Categorical(three_unicode) c = Categorical(pdc) assert c.category_array.dtype.char == 'U' def test_empty_init(self): with pytest.raises(ValueError): c = Categorical({}) with pytest.raises(ValueError): c = Categorical([]) def test_multi_with_cats(self): with pytest.raises(NotImplementedError): c = Categorical( [FastArray(['a', 'b', 'c', 'a']), FastArray([1, 2, 3, 1])], [FastArray(['a', 'b', 'c']), FastArray([1, 2, 3])], ) # 5/9/2019 removed this warning to reduce constructor paths # def test_unicode_warn(self): # with self.assertWarns(UserWarning): # c = Categorical([1,2,3],{1:'a',2:'b',3:'c'}, unicode=False) def test_map_non_integer(self): with pytest.raises(TypeError): c = Categorical([1.0, 2.0, 3.0], {1: 'a', 2: 'b', 3: 'c'}) def test_category_multi_arrays(self): with pytest.raises(TypeError): c = Categorical([1, 2, 3], [np.arange(5), np.arange(5)]) def test_getitem_enum_list2(self): c = Categorical([1, 1, 2, 3, 1], {'a': 1, 'b': 2, 'c': 3}) d = c[[1, 2, 3]] assert d[0] == 'a' def test_tuple_compare_error(self): c = Categorical([FastArray(['a', 'b', 'c', 'a']), FastArray([1, 2, 3, 1])]) with pytest.raises(ValueError): _ = c == ('a', 'b', 'c') def test_filter_out_bytes_from_unicode(self): c = Categorical(['a', 'a', 'b', 'c', 'a'], unicode=True, invalid=b'a') assert bool(np.all(c._fa == [1, 1, 2, 3, 1])) assert c.category_array.dtype.char == 'U' assert 'a' in c.category_array def test_bytes_compare_multikey(self): c = Categorical([np.array(['a', 'b', 'c', 'a']), FastArray([1, 2, 3, 1])], unicode=True) cols = c.category_dict bytescol = list(cols.values())[0] assert bytescol.dtype.char == 'U' result = c == (b'a', 1) assert bool(np.all(FastArray([True, False, False, True]) == result)) def test_cat_zero_wronge_base(self): with pytest.raises(ValueError): c = CatZero(['a', 'a', 'b', 'c', 'a'], base_index=1) def test_preserve_name(self): ds = TypeRegister.Dataset({'strcol': np.random.choice(['a', 'b', 'c'], 10), 'numcol': arange(10)}) c = Categorical(ds.strcol) assert c.get_name() == 'strcol' c = Categorical([ds.strcol, ds.numcol]) ds2 = c.sum(arange(10)) labels = ds2.label_get_names() assert labels[0] == 'strcol' assert labels[1] == 'numcol' ds = TypeRegister.Dataset({'mycodes': np.random.randint(1, 4, 10)}) c = Categorical(ds.mycodes, {'a': 1, 'b': 2, 'c': 3}) assert c.get_name() == 'mycodes' codes = np.random.randint(1, 4, 10) cats = FastArray(['a', 'b', 'c']) cats.set_name('test') c = Categorical(codes, cats) assert c.get_name(), 'test' def test_subarray_name(self): c = Categorical(['a', 'b']) c1 = c[[0]] assert c1.get_name() == c.get_name() # Make sure there is no "quantum effect" that printing the array changes it's name. _ = str(c1) assert c1.get_name() == c.get_name() def test_construct_from_categorical(self): c = Categorical(['a', 'a', 'b', 'c', 'a']) d = Categorical(c) assert isinstance(d.category_array, np.ndarray) assert isinstance(d.expand_array, np.ndarray) d2 = Categorical([c]) assert isinstance(d2.category_array, np.ndarray) assert isinstance(d2.expand_array, np.ndarray) def test_total_size(self): c = Categorical(['a', 'a', 'b', 'c', 'a']) assert c._total_size == 8 c = Categorical([arange(5, dtype=np.int32), arange(5, dtype=np.int32)]) assert c._total_size == 45 c = Categorical([arange(5, dtype=np.int64), arange(5, dtype=np.int64)]) assert c._total_size == 85 # removed while modifying groupby calculation behavior # def test_hold_dataset(self): # ds = TypeRegister.Dataset({'strcol':np.random.choice(['a','b','c'],30), 'numcol':arange(30)}) # c = ds.cat('strcol') # self.assertTrue(isinstance(c._dataset, TypeRegister.Dataset)) # result = c.sum() # self.assertTrue(isinstance(result, TypeRegister.Dataset)) # self.assertEqual(result._nrows, 3) def test_expand_dict(self): og_strings = FastArray(['a', 'a', 'b', 'c', 'a']) og_nums = arange(5) c = Categorical([og_strings, og_nums]) d = c.expand_dict assert isinstance(d, dict) assert len(d) == 2 dictlist = list(d.values()) assert bool(np.all(dictlist[0] == og_strings)) assert bool(np.all(dictlist[1] == og_nums)) c = Categorical([1, 2, 3], {'a': 1, 'b': 2, 'c': 3}) d = c.expand_dict assert isinstance(d, dict) assert len(d) == 1 dictlist = list(d.values()) assert bool(np.all(dictlist[0] == arange(1, 4))) c = Categorical(np.random.randint(0, 10, 100_100)) with pytest.warns(UserWarning): d = c.expand_dict def test_expand_array(self): c = Categorical([1, 2, 3], {'a': 1, 'b': 2, 'c': 3}) arr = c.expand_array assert bool(np.all(arr == arange(1, 4))) c = Categorical([FastArray(['a', 'b', 'c', 'a']), FastArray([1, 2, 3, 1])]) # expand array now works on multikey categoricals, returns a tuple of expanded arrays SJK: 4/29/2019 multi_expand = c.expand_array assert isinstance(multi_expand, tuple) assert len(multi_expand) == 2 assert bool(np.all(FastArray(['a', 'b', 'c', 'a']) == multi_expand[0])) assert bool(np.all(FastArray([1, 2, 3, 1]) == multi_expand[1])) c._fa[:] = 0 multi_expand = c.expand_array assert bool(np.all(isnan(multi_expand[1]))) assert bool(np.all(multi_expand[0] == b'Filtered')) def test_true_false_spacer(self): c = Categorical(['a', 'b', 'c']) t_true = c._tf_spacer(['test', True]) assert t_true == 'testTrue ' t_false = c._tf_spacer(['test', False]) assert t_false == 'testFalse' def test_mapping_hstack(self): c1 = Categorical([1, 1, 1, 1, 2, 3], {'a': 1, 'b': 2, 'c': 3}) c2 = Categorical([1, 1, 1, 1, 3, 4], {'a': 1, 'c': 3, 'd': 4}) stacked = Categorical.hstack([c1, c2]) assert stacked.unique_count == 4 assert stacked.from_category('b') == 2 assert stacked.from_category('d') == 4 assert len(stacked) == 12 c1 = Categorical([1, 1, 1, 1, 2, 3], {'a': 1, 'b': 2, 'd': 3}) c2 = Categorical([1, 1, 1, 1, 3, 4], {'a': 1, 'c': 3, 'd': 4}) # removed, hstack now relies on unique codes only SJK: 3/5/2019 # with self.assertRaises(TypeError): # c3 = Categorical.hstack([c1, c2]) def test_matlab_nan(self): dts = [np.int8, np.int16, np.int32, np.int64] matlab_float_idx = FastArray([1.0, 0.0, np.nan]) matlab_cats = ['a', 'b'] for dt in dts: c = Categorical(matlab_float_idx, matlab_cats, dtype=dt, from_matlab=True) assert bool(np.all(c._fa == [1, 0, 0])), f'failed to flip nan to zero for dtype {dt}' assert np.dtype(dt) == c.dtype def test_from_provided_with_filter(self): # not found and filter c = Categorical( ['a', 'a', 'b', 'c', 'd'], ['a', 'b', 'c'], filter=FastArray([False, False, True, True, False]), invalid='INVALID', ) c.filtered_set_name('INVALID') correct = FastArray([b'INVALID', b'INVALID', b'b', b'c', b'INVALID']) assert bool(np.all(c.expand_array == correct)) # filter only (uses default invalid) c = Categorical(['a', 'a', 'b', 'c'], ['a', 'b', 'c'], filter=FastArray([False, False, True, True]),) f = c.filtered_name correct = FastArray([f, f, b'b', b'c']) assert bool(np.all(c.expand_array == correct)) # even though filtered out, categories still untouched correct = FastArray([b'a', b'b', b'c']) assert bool(np.all(c.category_array == correct)) # filtering not allowed for base index 0 with pytest.raises(ValueError): c = Categorical( ['a', 'a', 'b', 'c'], ['a', 'b', 'c'], filter=FastArray([False, False, True, True]), base_index=0, ) def test_numeric_invalid(self): # 5/16/2019 invalid category must be in provided uniques c = Categorical([1.0, 1.0, 2.0], [1.0, 2.0], invalid=2.0) assert c._fa[2] == 2 num = c.sum(arange(1, 4)).col_0[0] assert num == 3 def test_get_groupings(self): g, f, n = ( FastArray([2, 3, 0, 4, 1]), FastArray([0, 0, 2, 4]), FastArray([0, 2, 2, 1]), ) c = Categorical(['b', 'c', 'a', 'a', 'b'], base_index=0) gg = c.get_groupings() group = gg['iGroup'] first = gg['iFirstGroup'] ncount = gg['nCountGroup'] assert bool(np.all(g == group)) assert bool(np.all(f == first)) assert bool(np.all(n == ncount)) c = Categorical(['b', 'c', 'a', 'a', 'b'], base_index=1) gg = c.get_groupings() group = gg['iGroup'] first = gg['iFirstGroup'] ncount = gg['nCountGroup'] assert bool(np.all(g == group)) assert bool(np.all(f == first)) assert bool(np.all(n == ncount)) def test_repr(self): # just make sure no error for coverage c = Categorical(['a', 'b', 'c']) r = c.__repr__() assert r, f"Representation should not be empty for Categorical '{c}'." assert isinstance(r, str) def test_copy_deep(self): c = Categorical(['a', 'b', 'c']) d = c.copy(deep=True) d[0] = 'b' assert c[0] == 'a' assert c._fa[0] == 1 assert d[0] == 'b' assert d._fa[0] == 2 def test_copy_new_filter(self): a = Categorical('A B A B A B'.split()) b = Categorical('B A B A B A'.split()) c = a.copy() f = c == 'A' c[f] = b[f] assert c[0] == 'B' assert c[1] == 'B' assert a[0] == 'A' assert a[1] == 'B' assert b[0] == 'B' assert b[1] == 'A' def test_setitem_tuple(self): c = Categorical([arange(5), arange(5)]) c[0] = (1, 1) assert c._fa[0] == 2 def test_nunique(self): codes = np.random.randint(0, 3, 1000) d = {0: 'All', 1: 'ManualAndQuasi', 2: 'Manual'} c = Categorical(codes, d) n = c.nunique() assert n == 3 assert len(c.unique()) == 3 codes = np.ones(1000, dtype=np.int32) c = Categorical(codes, d) n = c.nunique() assert n == 1 assert len(c.unique()) == 1 codes = arange(5) c = Categorical(codes, d) n = c.nunique() assert n == 5 assert len(c.unique()) == 5 c = Categorical(['a', 'a', 'b', 'c', 'd'], ['a', 'b', 'c', 'd']) n = c.nunique() assert n == 4 assert len(c.unique()) == 4 c = Categorical(['a', 'a', 'b', 'c', 'd'], ['a', 'b', 'c', 'd'], base_index=0) n = c.nunique() assert n == 4 assert len(c.unique()) == 4 c = Categorical(['a', 'a', 'b', 'c', 'd']) c[2] = 0 n = c.nunique() assert n == 3 assert len(c.unique()) == 3 assert c.unique_count == 4 c = Categorical([arange(3), np.array(['a', 'b', 'c'])]) c[0] = 0 n = c.nunique() assert n == 2 assert c.unique_count == 3 # The following assertion is moved to it's own unit pytest along with an xfail. # found below and named test_multikey_categorical_unique. # assert len(c.unique()) == 2 def test_unique(self): l = list('xyyz') c, c_sub = rt.Cat(l), rt.Cat(l[:3]) assert_array_equal(c.unique(), c.category_array, 'mismatch between unique categories and category array') assert_array_equal(c.unique(), c.category_array.unique(), 'mismatch between unique categories and expanded category array') assert c.nunique() == 3, 'mismatch in number of unique categories' assert_array_equal(c[:3].unique(), c_sub.category_array, 'mismatch between unique categories and category array with sliced categorical') assert_array_equal(c[:3].unique(), c_sub.category_array.unique(), 'mismatch between unique categories and expanded category array with sliced categorical') assert c[:3].nunique() == 2, 'mismatch in number of unique categories with sliced categorical' def test_scalar_unique(self): idx = ones(100) cats = 700_000.0 c = Categorical(idx, cats, from_matlab=True) assert isinstance(c, Categorical) assert c.unique_count == 1 def test_stack_multikey(self): # TODO pytest parameterize the strings strs = FA(np.random.choice(['aaaaa', 'b', 'ccc'], 23)) flts = np.random.choice([7.14, 6.66, 5.03], 23) c1 = Categorical([strs, flts]) c1_str = Categorical(strs) c1_flt = Categorical(flts) strs2 = FA(np.random.choice(['b', 'aaaaa'], 17)) flts2 = np.random.choice([5.03, 7.14], 17) c2 = Categorical([strs2, flts2]) c2_str = Categorical(strs2) c2_flt = Categorical(flts2) fa_str = hstack([strs, strs2]) fa_flt = hstack([flts, flts2]) # TODO add assertions for multikey Categoricals c_str = Categorical(fa_str) c_flt = Categorical(fa_flt) # TODO move these into SDS save / load tests paths = [r'riptable/tests/temp/ds1.sds', r'riptable/tests/temp/ds2.sds'] ds1 = Dataset( { 'mkcat': c1, 'strcat': c1_str, 'fltcat': c1_flt, 'strfa': strs, 'fltfa': flts, } ) ds2 = Dataset( { 'mkcat': c2, 'strcat': c2_str, 'fltcat': c2_flt, 'strfa': strs2, 'fltfa': flts2, } ) ds1.save(paths[0]) ds2.save(paths[1]) # normal dataset hstack hstack_ds = hstack([ds1, ds2]) assert isinstance(hstack_ds, Dataset) # dataset hstack from load stack_load_ds = load_sds(paths, stack=True) assert isinstance(stack_load_ds, PDataset) # multikey cat hstack hstack_mkcats = hstack([c1, c2]) assert isinstance(hstack_mkcats, Categorical) # normal array hstack hstack_strs = hstack([strs, strs2]) hstack_flts = hstack([flts, flts2]) # single cat hstack hstack_cstrs = hstack([c1_str, c2_str]) assert isinstance(hstack_cstrs, Categorical) hstack_cflts = hstack([c1_flt, c2_flt]) assert isinstance(hstack_cflts, Categorical) assert bool(np.all(hstack_strs == hstack_cstrs.expand_array)) assert bool(np.all(hstack_flts == hstack_cflts.expand_array)) mktup = [*hstack_mkcats.category_dict.values()] assert bool(np.all(hstack_mkcats._expand_array(mktup[0]) == fa_str)) assert bool(np.all(hstack_mkcats._expand_array(mktup[1]) == fa_flt)) mktup2 = [*stack_load_ds.mkcat.category_dict.values()] assert bool(np.all(stack_load_ds.mkcat._expand_array(mktup2[0]) == fa_str)) assert bool(np.all(stack_load_ds.mkcat._expand_array(mktup2[1]) == fa_flt)) mktup3 = [*hstack_ds.mkcat.category_dict.values()] assert bool(np.all(hstack_ds.mkcat._expand_array(mktup3[0]) == fa_str)) assert bool(np.all(hstack_ds.mkcat._expand_array(mktup3[1]) == fa_flt)) for p in paths: os.remove(p) # TO TEST: # regular python Enum # apply / apply_dataset, etc. # def test_sort_copy(self): # c = Categorical(np.random.choice(['a','b','c'], 15)) # d = c.sort_copy() # c = Categorical([np.random.choice(['a','b','c'], 15), np.random.randint(0,3,15)]) # d = c.sort_copy() # ---------------------------------------------------------- # def test_str_repr(self): # ''' # SJK: We're still in the early stages of deciding how to print out or summarize a categorical in the workspace. # Comment it out if repr or str changes, and I will fix up. # ''' # # no break # input = ['b', 'b', 'b', 'a', 'b', 'b'] # str_string = ', '.join(input) # repr_string = "Categorical(["+str_string+"])" # c = Categorical(input) # self.assertEqual(str(c),str_string, msg=f"__str__ did not produce the correct string {str_string} for categorical. got {str_string} instead") # self.assertEqual(c.__repr__(),repr_string, msg=f"__repr__ did not produce the correct string {str_string} for categorical. got {str_string} instead") # # add break # slice_size = 5 # input = ['b', 'b', 'b', 'a', 'b', 'b', 'b', 'b', 'b', 'a', 'b', 'b', 'c', 'c'] # str_string = ', '.join(input[:slice_size]+['...']+input[-slice_size:]) # repr_string = "Categorical(["+str_string+"])" # c = Categorical(input) # self.assertEqual(str(c),str_string, msg=f"__str__ did not produce the correct string {str_string} for categorical. got {str_string} instead") # self.assertEqual(c.__repr__(),repr_string, msg=f"__repr__ did not produce the correct string {str_string} for categorical. got {str_string} instead") def test_as_string_array(self): # SJK 10/4/2018 - as string array now returns bytes OR unicode (whatever type the string based categorical is holding) f = np.array([b'b', b'b', b'b', b'a', b'b', b'b']) c = Categorical(f) is_equal = bool(np.all(c.as_string_array == f)) assert isinstance(c.as_string_array, FastArray), f"Categorical did not return a fastarray in as_string_array" assert ( is_equal ), f"Categorical returned an incorrect string array {c.as_string_array} view of itself. Expected {f}" def test_indexing_numeric(self): c = Cat([1.1, 2.2, 3.3]) result = c['2.2'] assert np.all(result == [False, True, False]) def test_fill_forward(self): fa = FA([1., np.nan, 1.]) c = Cat([1,1,1]) c.fill_forward(fa, inplace=True) assert np.all(fa == [1., 1., 1.]) # TODO pytest parameterize `compare_func_names` def test_all_compare_tests(self): # with scalar # cat(unicode) i = 2 c1 = Categorical(three_ints) if ShowCompareInfo: print("Categorical:", c1) if ShowCompareInfo: print("Compare unicode to int scalar: 2") self.compare_cat_test(c1, compare_func_names, int_success, i) # cat(unicode) / unicode, unicode list i = "AMZN\u2082" c3 = Categorical(three_unicode) if ShowCompareInfo: print("Categorical:", c3) if ShowCompareInfo: print("Compare unicode cat to unicode string") self.compare_cat_test(c3, compare_func_names, int_success, i) if ShowCompareInfo: print("Compare to list of unicode string") self.compare_cat_test(c3, compare_func_names, int_success, [i]) if ShowCompareInfo: print("Compare to a numpy array of unicode string") self.compare_cat_test(c3, compare_func_names, int_success, np.array([i])) # cat(bytes) / bytes, bytes list i = b'b' c4 = Categorical(three_bytes) if ShowCompareInfo: print("Categorical:", c4) if ShowCompareInfo: print("Compare bytes cat to bytestring") self.compare_cat_test(c4, compare_func_names, int_success, i) if ShowCompareInfo: print("Compare to bytestring in list") self.compare_cat_test(c4, compare_func_names, int_success, [i]) if ShowCompareInfo: print("Compare to bytestring in numpy array") self.compare_cat_test(c4, compare_func_names, int_success, np.array([i])) # cat(bytes) / unicode, unicode list i = "b" c5 = Categorical(three_bytes) if ShowCompareInfo: print("Categorical:", c5) if ShowCompareInfo: print("Compare bytes cat to unicode string") self.compare_cat_test(c5, compare_func_names, int_success, i) if ShowCompareInfo: print("Compare to unicode string in list") self.compare_cat_test(c5, compare_func_names, int_success, [i]) if ShowCompareInfo: print("Compare to unicode string in numpy array") self.compare_cat_test(c5, compare_func_names, int_success, np.array([i])) # equal categoricals (same dictionary) # cat(bytes) / cat(bytes) if ShowCompareInfo: print("Compare two equal categoricals:") if ShowCompareInfo: print("Both from byte lists:") c1 = Categorical(three_bytes) c2 = Categorical(three_bytes) if ShowCompareInfo: print("cat1:", c1) if ShowCompareInfo: print("cat2:", c2) self.compare_cat_test(c1, compare_func_names, same_success, c2) # cat(unicode) / cat(unicode) if ShowCompareInfo: print("Both from unicode lists:") c1 = Categorical(three_unicode) c2 = Categorical(three_unicode) if ShowCompareInfo: print("cat1:", c1) if ShowCompareInfo: print("cat2:", c2) self.compare_cat_test(c1, compare_func_names, same_success, c2) # cat(unicode) / cat(bytes) if ShowCompareInfo: print("unicode/bytes list") c1 = Categorical(["a", "b", "c"]) c2 = Categorical(three_bytes) if ShowCompareInfo: print("cat1:", c1) if ShowCompareInfo: print("cat2:", c2) self.compare_cat_test(c1, compare_func_names, same_success, c2) # unequal categoricals (same dictionary) # cat(bytes) / cat(bytes) if ShowCompareInfo: print("Compare two unequal categoricals (same dict):") if ShowCompareInfo: print("both bytes") c1 = Categorical([0, 1, 0], three_bytes) c2 = Categorical([2, 1, 2], three_bytes) if ShowCompareInfo: print("cat1:", c1) if ShowCompareInfo: print("cat2:", c2) self.compare_cat_test(c1, compare_func_names, diff_success, c2) # cat(unicode) / cat(unicode) if ShowCompareInfo: print("both unicode") c1 = Categorical([0, 1, 0], three_unicode) c2 = Categorical([2, 1, 2], three_unicode) if ShowCompareInfo: print("cat1:", c1) if ShowCompareInfo: print("cat2:", c2) self.compare_cat_test(c1, compare_func_names, diff_success, c2) ## cat(bytes) / int list (matching) # if ShowCompareInfo: print("Compare categorical to matching int list") # if ShowCompareInfo: print("bytes") # i = [1,2,3] # c1 = Categorical(three_bytes) # self.compare_cat_test(c1,compare_func_names,same_success,i) ## cat(unicode) / int list (matching) # if ShowCompareInfo: print("unicode") # c1 = Categorical(three_unicode) # self.compare_cat_test(c1,compare_func_names,same_success,i) ## cat(bytes) / int list (non-matching) # if ShowCompareInfo: print("Compare categorical to non-matching int list") # if ShowCompareInfo: print("bytes") # i = [3,2,1] # c1 = Categorical(three_bytes) # self.compare_cat_test(c1,compare_func_names,int_success,i) ## cat(unicode) / int list(non-matching) # if ShowCompareInfo: print("unicode") # c1 = Categorical(three_unicode) # self.compare_cat_test(c1,compare_func_names,int_success,i) # def cat_slicing(self): # three_unicode =FA(["AAPL\u2080","AMZN\u2082","IBM\u2081"]) # three_bytes = FA([b'a',b'b',b'c']) # num_rows=8 # idx_size=15 # get_item_dicts = { # "single_slices" : { # ":2" : slice(None,2,None), # "-2:": slice(-2,None,None), # "2:5": slice(2,5,None), # "5:" : slice(5,None,None), # ":" : slice(None,None,None) # }, # "bool_arrays" : { # "python_bool" : [True, False, True, False, False, True, True, True, False, True, False, False, True, False, True], # "numpy_bool" : np.array([True, False, True, False, False, True, True, True, False, True, False, False, True, False, True]) # }, # "int_indices" : { "int_idx_size"+str(idx_size) : np.random.randint(low=0,high=num_rows,size=idx_size) for idx_size in range(1,num_rows) } # } # failures = 0 # idx_list = np.random.randint(low=0,high=8,size=15) # s_list = np.array([b'adam',b'bob',b'charlie',b'david',b'edward',b'frank',b'greg',b'harold']) # c = Categorical(idx_list, s_list) # for key, test_dict in get_item_dicts.items(): # print("\n\n"+key) # for call_str, val in test_dict.items(): # success = s_list[idx_list[val]] # if np.all(c[val].as_string_array == success): # message = "success" # else: # message = "failure" # failures += 1 # print(call_str, message) # print("Tests complete with",failures,"errors") # return c @pytest.mark.xfail( reason="RIP-215 - lead to inconsistent Categorical state; please add hypothesis tests when resolved." ) def test_category_add(self): cat = Categorical(list("bbcdebc")) e = "a" cat.category_add(e) assert e in cat, "expect the added category to be added to the Categorical" assert e in cat._categories, "expect the added category to be added to the Categorical._categories" assert e in cat.category_array, "expect the added category to be added to the Categorical.category_array" assert e in cat.category_dict, "expect the added category to be added to the Categorical.category_dict" @pytest.mark.xfail( reason="RIP-215 - lead to inconsistent Categorical state; please add hypothesis tests when resolved." ) def test_category_remove(self): cat = Categorical(list("bbcdebc")) e = cat[0] cat.category_remove(e) assert e not in cat, "expect the removed category to be removed from the Categorical" assert e not in cat._categories, "expect the removed category to be removed from the Categorical._categories" assert ( e not in cat.category_array ), "expect the removed category to be removed from the Categorical.category_array" assert ( e not in cat.category_dict ), "expect the removed category to be removed from the Categorical.category_dict" # TODO move this to testing utils def compare_cat_test(self, cat, compare_func_names, success_bools, i): for fname, success in zip(compare_func_names, success_bools): func = getattr(cat, fname) result = func(i) assert np.all(result == success), f'fail on {fname} {cat} {i}' if ShowCompareInfo: if np.all(result == success): message = "succeeded" else: message = "failed" print(fname, message) def test_duplicated(self): result = Cat([2, 3, 2], list('qwery')).duplicated() assert np.all(result == FA([False, False, True])) def test_cat_copy(self): # add deep copy for enum, single, multi x = arange(6, dtype=uint16) // 2 c = Cat(x, {0: 'Run', 1: 'Stop', 2: 'Start'}, dtype=uint16) c[1] = 'Start' a = c.copy() d = a[:5] a[1] = 'Run' b = a[:5] assert a._fa[1] == 0 assert b._fa[1] == 0 assert c._fa[1] == 2 assert d._fa[1] == 0 def test_assinglekey(self): c = Cat([1, 2, 1, 2, 1, 2], {'Sunny': 1, 'Thunderstorms': 2}) # insert bad value c._fa[3] = 17 c1 = c.as_singlekey(ordered=False) c2 = c.as_singlekey(ordered=True) assert np.all(c1.expand_array == c2.expand_array) c = Cat([-1, -2, -1, -2, -1, -2], {'Sunny': -1, 'Thunderstorms': -2}) c._fa[3] = 17 c3 = c.as_singlekey(ordered=False) c2 = c.as_singlekey(ordered=True) assert np.all(c1.expand_array == c2.expand_array) assert np.all(c3.expand_array == c2.expand_array) # Cannot use the pytest.mark.parameterize decorator within classes that inherit from unittest.TestCase. # Will need to migrate for unittest to pytest and fold the following categorical tests into Categorical_Test. @pytest.mark.parametrize( "categoricals", [ # Categorical constructed from python list data pytest.param( [ Categorical(data) for data in get_categorical_data_factory_method([CategoryMode.StringArray, CategoryMode.NumericArray]) ], id="cat_with_list_values", ), # Categorical constructed from numpy array pytest.param( [ Categorical(np.array(data)) for data in get_categorical_data_factory_method([CategoryMode.StringArray, CategoryMode.NumericArray]) ], id="cat_with_np_array_values", ), # Categorical constructred from riptable fast array pytest.param( [ Categorical(rt.FastArray(data)) for data in get_categorical_data_factory_method([CategoryMode.StringArray, CategoryMode.NumericArray]) ], id="cat_with_rt_fastarray_values", ), # failed test cases pytest.param( [Categorical(data) for data in get_categorical_data_factory_method(CategoryMode.MultiKey)], marks=[ pytest.mark.xfail( reason="RIP-410 - Bug for MultiKey Categoricals: AttributeError: 'Categorical' object has no attribute 'ismultikey_labels'" ) ], id="cat_with_tuple_values", ), ], ) def test_one_hot_encode(categoricals): for categorical in categoricals: col_names, encoded_arrays = categorical.one_hot_encode() category_array = categorical.category_array.astype('U') # Test 1.1 The col_names are the same as the category array. assert not set(category_array).symmetric_difference(set(col_names)), ( f"The column names should be the same as the names in the category array", f"category array {category_array}\ncolumn names {col_names}", ) # Test 1.2 The encoded_arrays dtypes are consistent with one another. encoded_arrays_dtypes = set([fa.dtype for fa in encoded_arrays]) assert ( len(encoded_arrays_dtypes) == 1 ), f"Encoded array dtypes should be consistent, got {encoded_arrays_dtypes}" # todo for each category, assert the mask of the categorical is in the encoded_arrays @pytest.mark.parametrize( "categoricals", [ # Categorical constructed from python list data pytest.param( [Categorical(data) for data in get_categorical_data_factory_method([CategoryMode.StringArray])], id="cat_with_list_values", ), # Categorical constructed from numpy array pytest.param( [Categorical(np.array(data)) for data in get_categorical_data_factory_method([CategoryMode.StringArray])], id="cat_with_np_array_values", ), # Categorical constructred from riptable fast array pytest.param( [ Categorical(rt.FastArray(data)) for data in get_categorical_data_factory_method([CategoryMode.StringArray]) ], id="cat_with_rt_fastarray_values", ), ], ) def test_shift_cat(categoricals): # todo Handle numeric invalid types for categoricals with values other than strings. filtered_name = rt.rt_enum.FILTERED_LONG_NAME.encode("utf-8") for categorical in categoricals: cat_len = len(categorical) for i in range(-cat_len + 1, cat_len): # exhaustive shift of all Categorical values. # shift the categorical i-places shift_cat = categorical.shift_cat(i) # The category array should remain unchanged. assert_array_equal(shift_cat.category_array, categorical.category_array) # The underlying FastArray should have the items shifted to the i-th position. if i > 0: # shift forwards case assert_array_equal( shift_cat._fa[i:], categorical._fa[:-i], f"FastArray items should be shifted by {i} postions.", ) # The Categorical should have the values shifted to the i-th position. cat_values, shift_cat_values = ( categorical.expand_array, shift_cat.expand_array, ) assert_array_equal( shift_cat_values[i:], cat_values[:-i], f"Categorical values should be shifted by {i} positions.", ) # The underlying FastArray should have the first i-items to be the invalid value. # The Categorical values should have the first i-items be the filtered or invalid name. # Need to handle other invalid values and other Categorical base indexing. assert_array_equal( shift_cat_values[:i], np.full(i, filtered_name), f"Shifted Categorical values up to {i}-th position should be '{filtered_name}'.", ) assert_array_equal( shift_cat._fa[:i], np.zeros(i), f"Shifted Categorical underlying FastArray items up to {i}-th position should be the invalid value 0.", ) elif i < 0: # shifted backwards case i = abs(i) # slicing arithmetic based on positional value of i assert_array_equal( shift_cat._fa[: cat_len - i], categorical._fa[i:], f"FastArray items should be shifted by -{i} postions.", ) cat_values, shift_cat_values = ( categorical.expand_array, shift_cat.expand_array, ) assert_array_equal( shift_cat_values[: cat_len - i], cat_values[i:], f"Categorical values should be shifted by -{i} positions.", ) assert_array_equal( shift_cat_values[-i:], np.full(i, filtered_name), f"Shifted Categorical values up to -{i}-th position should be '{filtered_name}'.", ) assert_array_equal( shift_cat._fa[-i:], np.zeros(i), f"Shifted Categorical underlying FastArray items up to -{i}-th position should be the invalid value 0.", ) elif i == 0: # zero-th shift case # test for equality assert_array_equal(shift_cat.category_array, categorical.category_array) assert_array_equal(shift_cat._fa, categorical._fa) cat_values, shift_cat_values = ( categorical.expand_array, shift_cat.expand_array, ) assert_array_equal(shift_cat_values, cat_values) # shift overflow for backward and forward case up to two values for i in list(range(-cat_len - 2, -cat_len)) + list(range(cat_len, cat_len + 2)): shift_cat = categorical.shift_cat(i) assert_array_equal(shift_cat.category_array, categorical.category_array) # Investigate possible bug with expanding Categorical values. E.g.: # given: # Categorical([a, a, a, a, a, a, a, a, a, a]) Length: 10 # FastArray([1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=int8) Base Index: 1 # FastArray([b'a'], dtype='|S1') Unique count: 1 # shifted categorical # Categorical([Filtered, Filtered, Filtered, Filtered, Filtered, Filtered, Filtered, Filtered, Filtered, Filtered]) Length: 10 # FastArray([0, 0, 0, 0, 0, 0, 0, 0, 0, 0], dtype=int8) Base Index: 1 # FastArray([b'a'], dtype='|S1') Unique count: 1 # got # E x: FastArray([b'Filtered', b'Filtered', b'Filtered', b'Filtered', # E b'Filtered', b'Filtered', b'Filtered', b'Filtered', # E b'Filtered', b'a'], dtype='|S8') # E y: array([b'Filtered', b'Filtered', b'Filtered', b'Filtered', b'Filtered', # E b'Filtered', b'Filtered', b'Filtered', b'Filtered', b'Filtered'], # E dtype='|S8') # Expected all values to be b'Filtered', but saw b'a'. # todo assert_array_equal(shift_cat_values, np.full(cat_len, filtered_name), f"Overflow shifted Categorical values. All values are expected to be invalid '{filtered_name}'.") assert_array_equal( shift_cat._fa, np.zeros(cat_len), f"Overflow shifted Categorical underlying FastArray items. All values are expected to be invalid value 0.", ) @pytest.mark.parametrize( # TODO - add base 0 and base 1 indexing w/ expectations "categoricals", [ # Categorical constructed from python list data pytest.param( [Categorical(data) for data in get_categorical_data_factory_method([CategoryMode.StringArray])], id="cat_with_list_values", ), # Categorical constructed from numpy array pytest.param( [Categorical(np.array(data)) for data in get_categorical_data_factory_method([CategoryMode.StringArray])], id="cat_with_np_array_values", ), # Categorical constructred from riptable fast array pytest.param( [ Categorical(rt.FastArray(data)) for data in get_categorical_data_factory_method([CategoryMode.StringArray]) ], id="cat_with_rt_fastarray_values", ), ], ) @pytest.mark.parametrize("misc", [None, "INVALID"]) # TODO - add numeric values @pytest.mark.parametrize("inplace", [False, True]) def test_shrink(categoricals, misc, inplace): for categorical in categoricals: cat = categorical.copy(deep=True) # deep copy so test data remains unchanged with inplace shrinks # Test 1 Shrink with empty values. # Shrink to empty categories. shrink_cat = cat.shrink([], misc=misc, inplace=inplace) # Type is preserved after shrinking. assert isinstance(shrink_cat, Categorical), "shrink_cat should be a Categorical." if misc is None: # For base index 1 Categorical, the underlying FastArray should be all zeros. assert_array_equal(shrink_cat._fa, np.zeros(len(cat))) # The Categorical categories should be empty. expected_category_array = np.empty(0) assert_array_equal( shrink_cat.category_array, expected_category_array, f"Category dictionary values should be empty.", ) for arr in shrink_cat.category_dict.values(): assert_array_equal( arr, expected_category_array, f"Category dictionary values should be empty.", ) # TODO expanding shrink categorical does not return original types invalid value; instead it returns nans # N.B, when shrinking, the category array type changes to float64 # E x: FastArray([nan]) # E y: array([b'Filtered'], dtype='|S8') # assert_array_equal(shrink_cat.expand_array, np.full(len(cat), filtered_name), f"Given empty values, shrink categorical values should all be invalid '{filtered_name}'.") else: # single categories being the specified misc # TODO - consider any constraints to assert on for the dtype? # The invalid value based on the dtype: e.g., for U32 its -2147483646 # assert_array_equal(shrink_cat._fa, InvalidValuesForDtype) # assert_array_equal(shrink_cat.expand_array, InvalidValuesForDtypeExpanded) # The categories should only contain the misc value. expected_category_array = np.array(misc) assert_array_equal( shrink_cat.category_array, expected_category_array, f"Category array should only contain the '{misc}' category.", ) for arr in shrink_cat.category_dict.values(): assert_array_equal( arr, expected_category_array, f"Category dictionary values should only contain the '{misc}' category.", ) # Test 2 Shrink with same categories cat = categorical.copy(deep=True) # Shrink to all the same categories. shrink_cat = cat.shrink(cat.category_array, misc=misc, inplace=inplace) # Type is preserved after shrinking. assert isinstance(shrink_cat, Categorical), "shrink_cat should be a Categorical." if misc is None: # TODO handle the misc not None case shrink_cat_values, cat_values = shrink_cat.expand_array, cat.expand_array assert_array_equal(shrink_cat_values, cat_values) assert_array_equal(shrink_cat._fa, cat._fa) assert_array_equal(shrink_cat.category_array, cat.category_array) for arr, expected_arr in zip(shrink_cat.category_dict.values(), cat.category_dict.values()): assert_array_equal(arr, expected_arr) # TODO Test 3 Shrink with subset of categories cat = categorical.copy(deep=True) # Shrink to all the same categories. n = int(len(cat) / 2) shrink_cat = cat.shrink(cat.category_array[:n], misc=misc, inplace=inplace) # Type is preserved after shrinking. assert isinstance(shrink_cat, Categorical), "shrink_cat should be a Categorical." @pytest.mark.parametrize( "categoricals", [ # TODO - test categorical construction using numpy and riptable arrays as a separate test # Categorical constructed from python list data pytest.param([Categorical(data) for data in get_categorical_data_factory_method()], id="cat_with_list_values",), # Categorical constructed from numpy array pytest.param( [ Categorical(np.array(data)) for data in get_categorical_data_factory_method([CategoryMode.StringArray, CategoryMode.NumericArray]) ], id="cat_with_np_array_values", ), # Categorical constructred from riptable fast array pytest.param( [ Categorical(rt.FastArray(data)) for data in get_categorical_data_factory_method([CategoryMode.StringArray, CategoryMode.NumericArray]) ], id="cat_with_rt_fastarray_values", ), ], ) def test_sds(categoricals, tmpdir): dir = tmpdir.mkdir("test_categorical_sds") for i, cat in enumerate(categoricals): name = "categorical_" + str(i) p = str(dir.join(name)) save_sds(p, cat) cat2 = load_sds(p) # Test 1 Saved and loaded categoricals should be the same. # TODO vary the meta version optional parameter when calling Categorical._load_from_sds_meta_data assert isinstance(cat2, Categorical) assert_array_equal(cat2._fa, cat._fa) if not cat.ismultikey: # MultiKey Categorical's do not support category_array operation assert_array_equal(cat2.category_array, cat.category_array) for actual, expected in zip(cat2.category_dict.values(), cat.category_dict.values()): assert_array_equal(actual, expected) cat2_values, cat_values = cat2.expand_array, cat.expand_array assert_array_equal(cat2_values, cat_values) # Test 2 As and from meta data Categoricals should be the same. cat3 = Categorical._from_meta_data(*cat._as_meta_data(name=name)) # Saved and loaded categoricals should be the same. assert isinstance(cat3, Categorical) assert_array_equal(cat3._fa, cat._fa) if not cat.ismultikey: # MultiKey Categorical's do not support category_array operation assert_array_equal(cat3.category_array, cat.category_array) for actual, expected in zip(cat3.category_dict.values(), cat.category_dict.values()): assert_array_equal(actual, expected) cat3_values, cat_values = cat3.expand_array, cat.expand_array assert_array_equal(cat3_values, cat_values) @pytest.mark.parametrize( "categoricals", [ # TODO handle CategoryMode IntEnum and Default [ Categorical(data) for data in get_categorical_data_factory_method([CategoryMode.StringArray, CategoryMode.NumericArray]) ] + [ Categorical(data, base_index=0) for data in get_categorical_data_factory_method([CategoryMode.StringArray, CategoryMode.NumericArray]) ] ], ) def test_from_bin(categoricals): for cat in categoricals: cat_arr_len = len(cat.category_array) # Test 1 All bin values are in the category array. if cat.base_index == 0: for i in range(cat_arr_len): assert cat.from_bin(i) in cat.category_array elif cat.base_index == 1: for i in range(1, cat_arr_len + 1): assert cat.from_bin(i) in cat.category_array else: raise ValueError(f"Unhandled Categorical base index {cat.base_index}") # Test 2 Handling of invalid input types: base_index and bin. # The bin is not an integer. with pytest.raises(TypeError): cat.from_bin(str(i)) cat.from_bin(float(i)) # Bin value out of range. with pytest.raises(ValueError): cat.from_bin(-1) if cat.base_index == 0: cat.from_bin(cat_arr_len) elif cat.base_index == 1: cat.from_bin(0) cat.from_bin(cat_arr_len + 1) else: raise ValueError(f"Unhandled Categorical base index {cat.base_index}") # The base index is None. cat.grouping._base_index = None with pytest.raises(TypeError): cat.from_bin(1) @pytest.mark.parametrize("cat", get_all_categorical_data()) def test_argsort(cat): assert_array_equal( cat.argsort(), np.argsort(cat._fa), "Categorical argsort should be equivalent to the argsort of the underlying FastArray", ) @pytest.mark.parametrize( "cats", [ pytest.param( [ Categorical(data) for data in get_categorical_data_factory_method([CategoryMode.StringArray, CategoryMode.NumericArray]) ] ), pytest.param( [Categorical(data) for data in get_categorical_data_factory_method(CategoryMode.MultiKey)], marks=[ pytest.mark.xfail(reason="NotImplementedError: Add categories not supported for MultiKey Categoricals") ], ), ], ) # TODO parameterize across base index 0 and 1 def test_auto_add(cats): for cat in cats: alpha, beta = "alpha", "beta" first_index, last_index = 0, len(cat) - 1 # Test 1 auto_add_on will allow addition of a category if the Categorical is unlocked, # otherwise an error is raised. cat.auto_add_on() cat.unlock() # Categorical is unlocked # Test 1.1 When unlocked and attempting to add a category, the categories should be added. # set the first and last categories cat[first_index] = cat[last_index] = alpha # auto_add_on and unlock should not allow setting beyond the first and last index of categories with pytest.raises(IndexError): # index out of bounds cat[first_index - 1] = alpha cat[last_index + 1] = alpha # category is added at specified index first_category = cat.category_array[cat._fa[first_index] - 1] # TODO normalize the category_array value, which is sometimes a numpy str_ or bytes_ to an ascii and compare # assert cat.category_array[cat._fa[first_index]-1] == alpha # assert at.category_array[cat._fa[last_index]-1] == alpha # added category is in category array and dictionary assert alpha in cat.category_array for categories in cat.category_dict.values(): assert alpha in categories # Test 1.2 When locked and attempting to add a category, an error is raised and the categories should not be added. cat.lock() # Categorical is locked with pytest.raises(IndexError): # cannot add a category since index is locked cat[first_index] = beta assert beta not in cat.category_array for categories in cat.category_dict.values(): assert beta not in categories # Test 2 auto_add_off will prevent category assignment of non-existing categories and raise an error cat.auto_add_off() # Test 2.1 Unlocked case cat.unlock() # Categorical is unlocked with pytest.raises(ValueError): # cannot automatically add categories while auto_add_categories is False cat[first_index] = beta # Test 2.2 Locked case cat.lock() with pytest.raises(IndexError): # cannot add a category since index is locked cat[first_index] = beta @pytest.mark.xfail(reason="rt_numpy.unique() needs to handles multikey categoricals") def test_multikey_categorical_unique(): c = Categorical([arange(3), FA(list('abc'))]) assert len(c.unique()) == c.nunique() @pytest.mark.parametrize("values", [list_bytes, list_unicode, list_true_unicode]) def test_categorical_convert(values): categories = list(set(values)) # pd_c is a pandas Categorical with a missing category. # pandas Categorical will designate the values with a missing category by -1. pd_c = pd.Categorical(values, categories=categories[:-1]) # The output of categorical_convert, when applied to a pandas Categorical, can be used to # construct a riptable Categorical. We test that this handles missing categories correctly. rt_values, rt_categories = rt.categorical_convert(pd_c) cat = rt.Categorical(rt_values, categories=rt_categories) # The invalid category should not be in the Categorical. missing_category = categories[-1] assert missing_category not in cat assert missing_category not in cat._categories assert missing_category not in cat.category_array assert missing_category not in cat.category_dict[next(iter(cat.category_dict))] # values of first key # All other category values should be in the Categorical. for e in categories[:-1]: # assert e in cat # uncomment when test_categorical_convert_xfail is fixed assert e in cat._categories assert e in cat.category_array assert e in cat.category_dict[next(iter(cat.category_dict))] # values of first key @pytest.mark.xfail(reason="RIP-396 - category not in Categorical, but is in Categorical.category_array") @pytest.mark.parametrize("values", [list_bytes,]) def test_categorical_convert_xfail(values): categories = list(set(values)) # pd_c is a pandas Categorical with a missing category. # pandas Categorical will designate the values with a missing category by -1. pd_c = pd.Categorical(values, categories=categories[:-1]) rt_values, rt_categories = rt.categorical_convert(pd_c) cat = rt.Categorical(rt_values, categories=rt_categories) # All other category values should be in the Categorical. for e in categories[:-1]: assert e in cat def test_build_dicts_enum(): str_to_int, int_to_str = Categories.build_dicts_enum(LikertDecision) codes = list(str_to_int.values()) * 2 c = Categorical(codes, categories=LikertDecision) c2 = Categorical(codes, categories=str_to_int) c3 = Categorical(codes, categories=int_to_str) # c is the our oracle Categorical. # Categoricals constructed from any of the dictionaries built by build_dicts_enum # should construct the same Categorical as c. assert_array_equal(c, c2) assert_array_equal(c, c3) @pytest.mark.parametrize("values", [list("abcdef"), [b"a", b"b", b"c", b"d", b"e", b"f"]]) def test_build_dicts_python(values): # int d = {k: v for k, v in enumerate(values)} str_to_int, int_to_str = Categories.build_dicts_python(d) codes = list(d.keys()) * 2 c = Categorical(codes, categories=d) c2 = Categorical(codes, categories=str_to_int) c3 = Categorical(codes, categories=int_to_str) # c is the our oracle Categorical. # Categoricals constructed from any of the dictionaries built by build_dicts_python # should construct the same Categorical as c. assert_array_equal(c, c2) assert_array_equal(c, c3) @pytest.mark.parametrize( "a,b,a_in_b,b_in_a", [ pytest.param(Cat(list('abc')), Cat(list('a')), FA([True, False, False]), FA([True]), id='single_key_overlap'), pytest.param( Cat([FA(list('abc')), FA([1,2,3])]), Cat([FA(list('a')), FA([1])]), FA([True, False, False]), FA([True]), id='single_multikey_overlap' ), pytest.param( Cat([FA(list('abc')), FA([1,2,3])]), Cat([FA(list('ab')), FA([1,2])]), FA([True, True, False]), FA([True, True]), id='two_multikey_overlap' ), pytest.param( Cat([FA(list('abcde')), FA([1,2,3,4,5])]), Cat([FA(list('dc')), FA([4,5])]), FA([False, False, False, True, False]), FA([True, False]), id='single_multikey_overlap2' ), pytest.param( Cat([FA(list('abcde')), FA([1,2,3,4,5])]), Cat([FA(list('aba')), FA([1,2,1])]), FA([True, True, False, False, False]), FA([True, True, True]), id='repeated_key_multikey_overlap' ), pytest.param( Cat([FA(list('abcdeab')), FA([1,2,3,4,5,1,6])]), Cat([FA(list('aba')), FA([1, 2, 1])]), FA([True, True, False, False, False, True, False]), FA([True, True, True]), id='repeated_key_multikey_overlap2' ), ] ) def test_multikey_categorical_isin(a, b, a_in_b, b_in_a): assert_array_equal(a_in_b, a.isin(b)) assert_array_equal(b_in_a, b.isin(a)) # TODO this is a good candidate for a hypothesis test once the CategoricalStrategy is able to generate MultiKey Categoricals f_msg = 'expected to be consistent with cat1.as_singlekey().isin(cat2.as_singlekey()) operation.' assert_array_equal(a.as_singlekey().isin(b.as_singlekey()), a.isin(b), f_msg) assert_array_equal(b.as_singlekey().isin(a.as_singlekey()), b.isin(a), f_msg) _make_unique_test_cases = pytest.mark.parametrize('cat, expected', [ (rt.Cat([1, 1, 2, 2], ['a', 'a']), rt.Cat([1, 1, 1, 1], ['a'])), (rt.Cat([2, 2, 2, 2], ['a', 'a']), rt.Cat([1, 1, 1, 1], ['a'])), (rt.Cat([1, 2, 3, 3], ['a', 'a', 'b']), rt.Cat([1, 1, 2, 2], ['a', 'b'])), (rt.Cat([0, 0, 1, 1], ['a', 'a'], base_index=0), rt.Cat([0, 0, 0, 0], ['a'], base_index=0)), (rt.Cat([1, 1, 1, 1], ['a', 'a'], base_index=0), rt.Cat([0, 0, 0, 0], ['a'], base_index=0)), (rt.Cat([0, 0, 1, 1], ['a', 'b'], base_index=0), rt.Cat([0, 0, 1, 1], ['a', 'b'], base_index=0)), (rt.Cat([1, 1, 2, 2, 3], [99, 99, 101], ), rt.Cat([1, 1, 1, 1, 2], [99, 101])), (rt.Cat([0, 0, 1, 1], [99, 99], base_index=0), rt.Cat([0, 0, 0, 0], [99], base_index=0)), (rt.Cat([0, 0, 1, 1], [99, 101], base_index=0), rt.Cat([0, 0, 1, 1], [99, 101], base_index=0)), (rt.Cat([0, 0, 1, 1, 2, 2], ['a', 'a'], ), rt.Cat([0, 0, 1, 1, 1, 1], ['a'], )), (rt.Cat([0, 0, 1, 1, 2, 2, 3, 3], ['a', 'a', 'b'], ), rt.Cat([0, 0, 1, 1, 1, 1, 2, 2], ['a', 'b'], )), ]) @_make_unique_test_cases def test_category_make_unique_not_inplace(cat, expected): res = cat.category_make_unique() assert (res == expected).all() @pytest.mark.parametrize('base_index', [0, 1]) def test_category_make_unique_multikey(base_index): c1 = Categorical(np.arange(10) % 2, ['a', 'a'], base_index=base_index) c2 = Categorical(np.arange(10) % 3, ['a', 'b', 'c'], base_index=base_index) cat = Categorical([c1, c2], base_index=base_index) res = cat.category_make_unique() assert list(cat) == list(res)
[ "riptable.rt_enum.FILTERED_LONG_NAME.encode", "os.remove", "riptable.tests.utils.LikertDecision.__members__.values", "riptable.FastArray", "riptable.hstack", "riptable.rt_categorical.Categories", "pytest.mark.parametrize", "riptable.tests.test_utils.get_all_categorical_data", "riptable.rt_numpy.isno...
[((861, 876), 'riptable.rt_sds.SDSMakeDirsOn', 'SDSMakeDirsOn', ([], {}), '()\n', (874, 876), False, 'from riptable.rt_sds import SDSMakeDirsOn\n'), ((963, 992), 'riptable.FastArray', 'FastArray', (["[b'a', b'b', b'c']"], {}), "([b'a', b'b', b'c'])\n", (972, 992), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((1007, 1027), 'riptable.FastArray', 'FastArray', (['[1, 2, 3]'], {}), '([1, 2, 3])\n', (1016, 1027), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((110068, 110118), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""misc"""', "[None, 'INVALID']"], {}), "('misc', [None, 'INVALID'])\n", (110091, 110118), False, 'import pytest\n'), ((110150, 110199), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""inplace"""', '[False, True]'], {}), "('inplace', [False, True])\n", (110173, 110199), False, 'import pytest\n'), ((121970, 122059), 'pytest.mark.xfail', 'pytest.mark.xfail', ([], {'reason': '"""rt_numpy.unique() needs to handles multikey categoricals"""'}), "(reason=\n 'rt_numpy.unique() needs to handles multikey categoricals')\n", (121987, 122059), False, 'import pytest\n'), ((122196, 122281), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""values"""', '[list_bytes, list_unicode, list_true_unicode]'], {}), "('values', [list_bytes, list_unicode, list_true_unicode]\n )\n", (122219, 122281), False, 'import pytest\n'), ((123592, 123705), 'pytest.mark.xfail', 'pytest.mark.xfail', ([], {'reason': '"""RIP-396 - category not in Categorical, but is in Categorical.category_array"""'}), "(reason=\n 'RIP-396 - category not in Categorical, but is in Categorical.category_array'\n )\n", (123609, 123705), False, 'import pytest\n'), ((123698, 123745), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""values"""', '[list_bytes]'], {}), "('values', [list_bytes])\n", (123721, 123745), False, 'import pytest\n'), ((128816, 128861), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""base_index"""', '[0, 1]'], {}), "('base_index', [0, 1])\n", (128839, 128861), False, 'import pytest\n'), ((27402, 27581), 'pytest.mark.xfail', 'pytest.mark.xfail', ([], {'reason': '"""20200416 This test was previously overridden by a later test in the file with the same name. Need to revisit and get back in a working state."""'}), "(reason=\n '20200416 This test was previously overridden by a later test in the file with the same name. Need to revisit and get back in a working state.'\n )\n", (27419, 27581), False, 'import pytest\n'), ((43126, 43220), 'pytest.mark.xfail', 'pytest.mark.xfail', ([], {'reason': '"""After invalid_set, the custom invalid value is not displayed."""'}), "(reason=\n 'After invalid_set, the custom invalid value is not displayed.')\n", (43143, 43220), False, 'import pytest\n'), ((47569, 47748), 'pytest.mark.xfail', 'pytest.mark.xfail', ([], {'reason': '"""20200416 This test was previously overridden by a later test in the file with the same name. Need to revisit and get back in a working state."""'}), "(reason=\n '20200416 This test was previously overridden by a later test in the file with the same name. Need to revisit and get back in a working state.'\n )\n", (47586, 47748), False, 'import pytest\n'), ((96527, 96657), 'pytest.mark.xfail', 'pytest.mark.xfail', ([], {'reason': '"""RIP-215 - lead to inconsistent Categorical state; please add hypothesis tests when resolved."""'}), "(reason=\n 'RIP-215 - lead to inconsistent Categorical state; please add hypothesis tests when resolved.'\n )\n", (96544, 96657), False, 'import pytest\n'), ((97218, 97348), 'pytest.mark.xfail', 'pytest.mark.xfail', ([], {'reason': '"""RIP-215 - lead to inconsistent Categorical state; please add hypothesis tests when resolved."""'}), "(reason=\n 'RIP-215 - lead to inconsistent Categorical state; please add hypothesis tests when resolved.'\n )\n", (97235, 97348), False, 'import pytest\n'), ((103431, 103476), 'riptable.rt_enum.FILTERED_LONG_NAME.encode', 'rt.rt_enum.FILTERED_LONG_NAME.encode', (['"""utf-8"""'], {}), "('utf-8')\n", (103467, 103476), True, 'import riptable as rt\n'), ((118721, 118747), 'riptable.tests.test_utils.get_all_categorical_data', 'get_all_categorical_data', ([], {}), '()\n', (118745, 118747), False, 'from riptable.tests.test_utils import get_categorical_data_factory_method, get_all_categorical_data\n'), ((122508, 122558), 'pandas.Categorical', 'pd.Categorical', (['values'], {'categories': 'categories[:-1]'}), '(values, categories=categories[:-1])\n', (122522, 122558), True, 'import pandas as pd\n'), ((122785, 122813), 'riptable.categorical_convert', 'rt.categorical_convert', (['pd_c'], {}), '(pd_c)\n', (122807, 122813), True, 'import riptable as rt\n'), ((122825, 122876), 'riptable.Categorical', 'rt.Categorical', (['rt_values'], {'categories': 'rt_categories'}), '(rt_values, categories=rt_categories)\n', (122839, 122876), True, 'import riptable as rt\n'), ((123984, 124034), 'pandas.Categorical', 'pd.Categorical', (['values'], {'categories': 'categories[:-1]'}), '(values, categories=categories[:-1])\n', (123998, 124034), True, 'import pandas as pd\n'), ((124069, 124097), 'riptable.categorical_convert', 'rt.categorical_convert', (['pd_c'], {}), '(pd_c)\n', (124091, 124097), True, 'import riptable as rt\n'), ((124109, 124160), 'riptable.Categorical', 'rt.Categorical', (['rt_values'], {'categories': 'rt_categories'}), '(rt_values, categories=rt_categories)\n', (124123, 124160), True, 'import riptable as rt\n'), ((124346, 124389), 'riptable.rt_categorical.Categories.build_dicts_enum', 'Categories.build_dicts_enum', (['LikertDecision'], {}), '(LikertDecision)\n', (124373, 124389), False, 'from riptable.rt_categorical import Categories\n'), ((124444, 124489), 'riptable.Categorical', 'Categorical', (['codes'], {'categories': 'LikertDecision'}), '(codes, categories=LikertDecision)\n', (124455, 124489), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((124500, 124541), 'riptable.Categorical', 'Categorical', (['codes'], {'categories': 'str_to_int'}), '(codes, categories=str_to_int)\n', (124511, 124541), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((124552, 124593), 'riptable.Categorical', 'Categorical', (['codes'], {'categories': 'int_to_str'}), '(codes, categories=int_to_str)\n', (124563, 124593), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((124779, 124804), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['c', 'c2'], {}), '(c, c2)\n', (124797, 124804), False, 'from numpy.testing import assert_array_equal\n'), ((124810, 124835), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['c', 'c3'], {}), '(c, c3)\n', (124828, 124835), False, 'from numpy.testing import assert_array_equal\n'), ((125057, 125089), 'riptable.rt_categorical.Categories.build_dicts_python', 'Categories.build_dicts_python', (['d'], {}), '(d)\n', (125086, 125089), False, 'from riptable.rt_categorical import Categories\n'), ((125131, 125163), 'riptable.Categorical', 'Categorical', (['codes'], {'categories': 'd'}), '(codes, categories=d)\n', (125142, 125163), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((125174, 125215), 'riptable.Categorical', 'Categorical', (['codes'], {'categories': 'str_to_int'}), '(codes, categories=str_to_int)\n', (125185, 125215), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((125226, 125267), 'riptable.Categorical', 'Categorical', (['codes'], {'categories': 'int_to_str'}), '(codes, categories=int_to_str)\n', (125237, 125267), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((125455, 125480), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['c', 'c2'], {}), '(c, c2)\n', (125473, 125480), False, 'from numpy.testing import assert_array_equal\n'), ((125486, 125511), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['c', 'c3'], {}), '(c, c3)\n', (125504, 125511), False, 'from numpy.testing import assert_array_equal\n'), ((129083, 129127), 'riptable.Categorical', 'Categorical', (['[c1, c2]'], {'base_index': 'base_index'}), '([c1, c2], base_index=base_index)\n', (129094, 129127), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((2166, 2199), 'riptable.tests.utils.LikertDecision.__members__.keys', 'LikertDecision.__members__.keys', ([], {}), '()\n', (2197, 2199), False, 'from riptable.tests.utils import LikertDecision\n'), ((2530, 2579), 'pytest.skip', 'pytest.skip', (['"""This test needs to be implemented."""'], {}), "('This test needs to be implemented.')\n", (2541, 2579), False, 'import pytest\n'), ((2839, 2862), 'riptable.Categorical', 'Categorical', (['list_bytes'], {}), '(list_bytes)\n', (2850, 2862), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((3341, 3366), 'riptable.Categorical', 'Categorical', (['list_unicode'], {}), '(list_unicode)\n', (3352, 3366), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((4066, 4096), 'riptable.Categorical', 'Categorical', (['list_true_unicode'], {}), '(list_true_unicode)\n', (4077, 4096), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((10120, 10151), 'riptable.Categorical', 'Categorical', (['idx_list', 'str_list'], {}), '(idx_list, str_list)\n', (10131, 10151), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((10319, 10353), 'riptable.Categorical', 'Categorical', (['codes', 'LikertDecision'], {}), '(codes, LikertDecision)\n', (10330, 10353), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((14036, 14089), 'riptable.Categorical', 'Categorical', (["['b', 'b', 'c', 'a', 'd']"], {'ordered': '(False)'}), "(['b', 'b', 'c', 'a', 'd'], ordered=False)\n", (14047, 14089), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((14206, 14252), 'riptable.FastArray', 'FastArray', (["[b'BB', b'BB', b'CC', b'AA', b'DD']"], {}), "([b'BB', b'BB', b'CC', b'AA', b'DD'])\n", (14215, 14252), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((14314, 14381), 'riptable.Categorical', 'Categorical', (["['b', 'b', 'c', 'a', 'd']"], {'ordered': '(False)', 'base_index': '(0)'}), "(['b', 'b', 'c', 'a', 'd'], ordered=False, base_index=0)\n", (14325, 14381), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((14478, 14531), 'riptable.Categorical', 'Categorical', (["['b', 'b', 'c', 'a', 'd']"], {'ordered': '(False)'}), "(['b', 'b', 'c', 'a', 'd'], ordered=False)\n", (14489, 14531), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((14656, 14707), 'riptable.FastArray', 'FastArray', (["[b'BB', b'BB', b'CC', b'AA', b'INVALID']"], {}), "([b'BB', b'BB', b'CC', b'AA', b'INVALID'])\n", (14665, 14707), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((14769, 14836), 'riptable.Categorical', 'Categorical', (["['b', 'b', 'c', 'a', 'd']"], {'ordered': '(False)', 'base_index': '(0)'}), "(['b', 'b', 'c', 'a', 'd'], ordered=False, base_index=0)\n", (14780, 14836), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((14952, 15005), 'riptable.Categorical', 'Categorical', (["['b', 'b', 'c', 'a', 'd']"], {'ordered': '(False)'}), "(['b', 'b', 'c', 'a', 'd'], ordered=False)\n", (14963, 15005), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((15121, 15159), 'riptable.FastArray', 'FastArray', (['[2.0, 2.0, 3.0, 1.0, 666.0]'], {}), '([2.0, 2.0, 3.0, 1.0, 666.0])\n', (15130, 15159), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((15221, 15288), 'riptable.Categorical', 'Categorical', (["['b', 'b', 'c', 'a', 'd']"], {'ordered': '(False)', 'base_index': '(0)'}), "(['b', 'b', 'c', 'a', 'd'], ordered=False, base_index=0)\n", (15232, 15288), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((15398, 15451), 'riptable.Categorical', 'Categorical', (["['b', 'b', 'c', 'a', 'd']"], {'ordered': '(False)'}), "(['b', 'b', 'c', 'a', 'd'], ordered=False)\n", (15409, 15451), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((15534, 15601), 'riptable.Categorical', 'Categorical', (["['b', 'b', 'c', 'a', 'd']"], {'ordered': '(False)', 'base_index': '(0)'}), "(['b', 'b', 'c', 'a', 'd'], ordered=False, base_index=0)\n", (15545, 15601), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((15686, 15739), 'riptable.Categorical', 'Categorical', (["['b', 'b', 'c', 'a', 'd']"], {'ordered': '(False)'}), "(['b', 'b', 'c', 'a', 'd'], ordered=False)\n", (15697, 15739), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((15759, 15790), 'riptable.FastArray', 'FastArray', (["['w', 'x', 'y', 'z']"], {}), "(['w', 'x', 'y', 'z'])\n", (15768, 15790), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((15843, 15884), 'riptable.FastArray', 'FastArray', (["[b'w', b'w', b'x', b'y', b'z']"], {}), "([b'w', b'w', b'x', b'y', b'z'])\n", (15852, 15884), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((15946, 16013), 'riptable.Categorical', 'Categorical', (["['b', 'b', 'c', 'a', 'd']"], {'ordered': '(False)', 'base_index': '(0)'}), "(['b', 'b', 'c', 'a', 'd'], ordered=False, base_index=0)\n", (15957, 16013), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((16110, 16163), 'riptable.Categorical', 'Categorical', (['[2, 2, 3, 1, 4, 0]', "['a', 'b', 'c', 'd']"], {}), "([2, 2, 3, 1, 4, 0], ['a', 'b', 'c', 'd'])\n", (16121, 16163), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((16279, 16324), 'riptable.FastArray', 'FastArray', (['[2.0, 2.0, 3.0, 1.0, 666.0, 666.0]'], {}), '([2.0, 2.0, 3.0, 1.0, 666.0, 666.0])\n', (16288, 16324), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((16506, 16544), 'riptable.Categorical', 'Categorical', (["['a', 'a', 'b', 'c', 'a']"], {}), "(['a', 'a', 'b', 'c', 'a'])\n", (16517, 16544), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((16621, 16673), 'riptable.Categorical', 'Categorical', (["['a', 'a', 'b', 'c', 'a']"], {'base_index': '(0)'}), "(['a', 'a', 'b', 'c', 'a'], base_index=0)\n", (16632, 16673), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((17497, 17531), 'riptable.Categorical', 'Categorical', (['codes', 'LikertDecision'], {}), '(codes, LikertDecision)\n', (17508, 17531), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((18169, 18203), 'riptable.Categorical', 'Categorical', (['codes', 'LikertDecision'], {}), '(codes, LikertDecision)\n', (18180, 18203), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((19524, 19573), 'riptable.Categorical', 'Categorical', (['idx_list', 'str_list'], {'from_matlab': '(True)'}), '(idx_list, str_list, from_matlab=True)\n', (19535, 19573), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((20199, 20244), 'pandas.Categorical.from_codes', 'pd.Categorical.from_codes', (['idx_list', 'str_list'], {}), '(idx_list, str_list)\n', (20224, 20244), True, 'import pandas as pd\n'), ((20261, 20278), 'riptable.Categorical', 'Categorical', (['pd_c'], {}), '(pd_c)\n', (20272, 20278), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((20295, 20326), 'riptable.Categorical', 'Categorical', (['idx_list', 'str_list'], {}), '(idx_list, str_list)\n', (20306, 20326), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((20758, 20815), 'pandas.Categorical.from_codes', 'pd.Categorical.from_codes', (['[-1, 0, 1, 2]', "['a', 'b', 'c']"], {}), "([-1, 0, 1, 2], ['a', 'b', 'c'])\n", (20783, 20815), True, 'import pandas as pd\n'), ((20832, 20849), 'riptable.Categorical', 'Categorical', (['pd_c'], {}), '(pd_c)\n', (20843, 20849), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((21076, 21136), 'pandas.Categorical.from_codes', 'pd.Categorical.from_codes', (['[-1, 0, 1, 2]', "[u'โ‚‚', u'โ‚ƒ', u'โ‚„']"], {}), "([-1, 0, 1, 2], [u'โ‚‚', u'โ‚ƒ', u'โ‚„'])\n", (21101, 21136), True, 'import pandas as pd\n'), ((21168, 21185), 'riptable.Categorical', 'Categorical', (['pd_c'], {}), '(pd_c)\n', (21179, 21185), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((21956, 21989), 'riptable.Categorical', 'Categorical', (['str_list', 'unique_str'], {}), '(str_list, unique_str)\n', (21967, 21989), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((22341, 22357), 'riptable.Categorical', 'Categorical', (['lis'], {}), '(lis)\n', (22352, 22357), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((24237, 24269), 'riptable.rt_categorical.Categories', 'Categories', (['c_list'], {'unicode': '(True)'}), '(c_list, unicode=True)\n', (24247, 24269), False, 'from riptable.rt_categorical import Categories\n'), ((24296, 24322), 'riptable.rt_categorical.Categories', 'Categories', (['LikertDecision'], {}), '(LikertDecision)\n', (24306, 24322), False, 'from riptable.rt_categorical import Categories\n'), ((25048, 25205), 'riptable.Date', 'rt.Date', (["['2019-03-15', '2019-04-18', '2019-05-17', '2019-06-21', '2019-07-19',\n '2019-08-16', '2019-09-20', '2019-10-18', '2019-11-15', '2019-12-20']"], {}), "(['2019-03-15', '2019-04-18', '2019-05-17', '2019-06-21',\n '2019-07-19', '2019-08-16', '2019-09-20', '2019-10-18', '2019-11-15',\n '2019-12-20'])\n", (25055, 25205), True, 'import riptable as rt\n'), ((25459, 25472), 'riptable.Cat', 'rt.Cat', (['dates'], {}), '(dates)\n', (25465, 25472), True, 'import riptable as rt\n'), ((25609, 25760), 'riptable.FA', 'rt.FA', (["['2019-03-15', '2019-04-18', '2019-05-17', '2019-06-21', '2019-07-19',\n '2019-08-16', '2019-09-20', '2019-10-18', '2019-11-15', '2019-12-20']"], {}), "(['2019-03-15', '2019-04-18', '2019-05-17', '2019-06-21', '2019-07-19',\n '2019-08-16', '2019-09-20', '2019-10-18', '2019-11-15', '2019-12-20'])\n", (25614, 25760), True, 'import riptable as rt\n'), ((26019, 26044), 'riptable.Cat', 'rt.Cat', (['[dates, datestrs]'], {}), '([dates, datestrs])\n', (26025, 26044), True, 'import riptable as rt\n'), ((26246, 26257), 'riptable.Date', 'rt.Date', (['[]'], {}), '([])\n', (26253, 26257), True, 'import riptable as rt\n'), ((26279, 26292), 'riptable.Cat', 'rt.Cat', (['dates'], {}), '(dates)\n', (26285, 26292), True, 'import riptable as rt\n'), ((26545, 26591), 'riptable.FastArray', 'FastArray', (["['a', 'b', 'c', 'c', 'd', 'a', 'b']"], {}), "(['a', 'b', 'c', 'c', 'd', 'a', 'b'])\n", (26554, 26591), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((26710, 26770), 'riptable.Categorical', 'Categorical', (['values'], {'ordered': '(True)', 'base_index': '(1)', 'filter': 'None'}), '(values, ordered=True, base_index=1, filter=None)\n', (26721, 26770), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((27071, 27146), 'riptable.Categorical', 'Categorical', (['univals'], {'ordered': '(True)', 'base_index': '(1)', 'filter': 'None', 'unicode': '(True)'}), '(univals, ordered=True, base_index=1, filter=None, unicode=True)\n', (27082, 27146), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((27644, 27687), 'riptable.FastArray', 'FastArray', (['[True, True, False, False, True]'], {}), '([True, True, False, False, True])\n', (27653, 27687), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((27703, 27741), 'riptable.Categorical', 'Categorical', (["['a', 'a', 'b', 'c', 'a']"], {}), "(['a', 'a', 'b', 'c', 'a'])\n", (27714, 27741), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((27891, 27943), 'riptable.Categorical', 'Categorical', (["['a', 'a', 'b', 'c', 'a']"], {'base_index': '(0)'}), "(['a', 'a', 'b', 'c', 'a'], base_index=0)\n", (27902, 27943), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((28089, 28142), 'riptable.Categorical', 'Categorical', (["['a', 'a', 'b', 'c', 'a']"], {'filter': 'filter'}), "(['a', 'a', 'b', 'c', 'a'], filter=filter)\n", (28100, 28142), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((28266, 28333), 'riptable.Categorical', 'Categorical', (["['a', 'a', 'b', 'c', 'a']"], {'base_index': '(0)', 'filter': 'filter'}), "(['a', 'a', 'b', 'c', 'a'], base_index=0, filter=filter)\n", (28277, 28333), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((28608, 28663), 'riptable.Categorical', 'Categorical', (["['a', 'a', 'b', 'c', 'a']", "['a', 'b', 'c']"], {}), "(['a', 'a', 'b', 'c', 'a'], ['a', 'b', 'c'])\n", (28619, 28663), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((28813, 28882), 'riptable.Categorical', 'Categorical', (["['a', 'a', 'b', 'c', 'a']", "['a', 'b', 'c']"], {'base_index': '(0)'}), "(['a', 'a', 'b', 'c', 'a'], ['a', 'b', 'c'], base_index=0)\n", (28824, 28882), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((29322, 29363), 'pandas.Categorical', 'pd.Categorical', (["['a', 'a', 'b', 'c', 'a']"], {}), "(['a', 'a', 'b', 'c', 'a'])\n", (29336, 29363), True, 'import pandas as pd\n'), ((29846, 29936), 'riptable.Categorical', 'Categorical', (['values', 'good_cats'], {'ordered': '(True)', 'base_index': '(1)', 'unicode': '(False)', 'filter': 'None'}), '(values, good_cats, ordered=True, base_index=1, unicode=False,\n filter=None)\n', (29857, 29936), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((30197, 30286), 'riptable.Categorical', 'Categorical', (['values', 'good_cats'], {'ordered': '(True)', 'base_index': '(1)', 'unicode': '(True)', 'filter': 'None'}), '(values, good_cats, ordered=True, base_index=1, unicode=True,\n filter=None)\n', (30208, 30286), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((31730, 31764), 'riptable.Categorical', 'Categorical', (['codes', 'LikertDecision'], {}), '(codes, LikertDecision)\n', (31741, 31764), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((32265, 32311), 'riptable.FastArray', 'FastArray', (["['a', 'b', 'c', 'c', 'd', 'a', 'b']"], {}), "(['a', 'b', 'c', 'c', 'd', 'a', 'b'])\n", (32274, 32311), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((32597, 32657), 'riptable.Categorical', 'Categorical', (['values'], {'ordered': '(True)', 'base_index': '(1)', 'filter': 'None'}), '(values, ordered=True, base_index=1, filter=None)\n', (32608, 32657), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((32995, 33070), 'riptable.Categorical', 'Categorical', (['univals'], {'ordered': '(True)', 'base_index': '(1)', 'filter': 'None', 'unicode': '(True)'}), '(univals, ordered=True, base_index=1, filter=None, unicode=True)\n', (33006, 33070), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((33212, 33272), 'riptable.Categorical', 'Categorical', (['values'], {'ordered': '(True)', 'base_index': '(1)', 'filter': 'None'}), '(values, ordered=True, base_index=1, filter=None)\n', (33223, 33272), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((33519, 33594), 'riptable.Categorical', 'Categorical', (['univals'], {'ordered': '(True)', 'base_index': '(1)', 'filter': 'None', 'unicode': '(True)'}), '(univals, ordered=True, base_index=1, filter=None, unicode=True)\n', (33530, 33594), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((35133, 35166), 'riptable.Categorical', 'Categorical', (['values'], {'base_index': '(1)'}), '(values, base_index=1)\n', (35144, 35166), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((35614, 35657), 'riptable.FastArray', 'FastArray', (['[False, True, True, False, True]'], {}), '([False, True, True, False, True])\n', (35623, 35657), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((35671, 35705), 'riptable.Categorical', 'Categorical', (['codes', 'LikertDecision'], {}), '(codes, LikertDecision)\n', (35682, 35705), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((37853, 37891), 'riptable.Categorical', 'Categorical', (["['a', 'a', 'c', 'b', 'b']"], {}), "(['a', 'a', 'c', 'b', 'b'])\n", (37864, 37891), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((37906, 37944), 'riptable.Categorical', 'Categorical', (["['b', 'b', 'd', 'd', 'c']"], {}), "(['b', 'b', 'd', 'd', 'c'])\n", (37917, 37944), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((37959, 37987), 'riptable.Categorical.hstack', 'Categorical.hstack', (['[c1, c2]'], {}), '([c1, c2])\n', (37977, 37987), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((38099, 38162), 'riptable.Categorical', 'Categorical', (['[1, 1, 3, 2, 2]', '[1, 2, 3, 4, 5]'], {'from_matlab': '(True)'}), '([1, 1, 3, 2, 2], [1, 2, 3, 4, 5], from_matlab=True)\n', (38110, 38162), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((38177, 38240), 'riptable.Categorical', 'Categorical', (['[2, 2, 4, 4, 3]', '[1, 2, 3, 4, 5]'], {'from_matlab': '(True)'}), '([2, 2, 4, 4, 3], [1, 2, 3, 4, 5], from_matlab=True)\n', (38188, 38240), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((38255, 38283), 'riptable.Categorical.hstack', 'Categorical.hstack', (['[c1, c2]'], {}), '([c1, c2])\n', (38273, 38283), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((39231, 39283), 'riptable.Categorical', 'rt.Categorical', (['country_num_codes', 'country_code_dict'], {}), '(country_num_codes, country_code_dict)\n', (39245, 39283), True, 'import riptable as rt\n'), ((39421, 39532), 'riptable.Categorical', 'rt.Categorical', (["['AUS', 'AUS', 'HKG', 'USA', 'USA', 'IRL', 'USA', 'IRL', 'USA', 'KHM',\n 'IRL', 'AUS', 'MEX']"], {}), "(['AUS', 'AUS', 'HKG', 'USA', 'USA', 'IRL', 'USA', 'IRL',\n 'USA', 'KHM', 'IRL', 'AUS', 'MEX'])\n", (39435, 39532), True, 'import riptable as rt\n'), ((39839, 39867), 'riptable.Categorical', 'Categorical', (["['a', 'b', 'c']"], {}), "(['a', 'b', 'c'])\n", (39850, 39867), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((39882, 39910), 'riptable.Categorical', 'Categorical', (["['d', 'e', 'f']"], {}), "(['d', 'e', 'f'])\n", (39893, 39910), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((39925, 39953), 'riptable.Categorical', 'Categorical', (["['c', 'f', 'z']"], {}), "(['c', 'f', 'z'])\n", (39936, 39953), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((39968, 39999), 'riptable.Categorical.align', 'Categorical.align', (['[c1, c2, c3]'], {}), '([c1, c2, c3])\n', (39985, 39999), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((40452, 40515), 'riptable.Categorical', 'Categorical', (['[1, 1, 3, 2, 2]', '[1, 2, 3, 4, 5]'], {'from_matlab': '(True)'}), '([1, 1, 3, 2, 2], [1, 2, 3, 4, 5], from_matlab=True)\n', (40463, 40515), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((40530, 40593), 'riptable.Categorical', 'Categorical', (['[2, 2, 4, 4, 3]', '[1, 2, 3, 4, 5]'], {'from_matlab': '(True)'}), '([2, 2, 4, 4, 3], [1, 2, 3, 4, 5], from_matlab=True)\n', (40541, 40593), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((40608, 40635), 'riptable.Categorical.align', 'Categorical.align', (['[c1, c2]'], {}), '([c1, c2])\n', (40625, 40635), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((40922, 40949), 'riptable.Categorical.align', 'Categorical.align', (['[c1, c2]'], {}), '([c1, c2])\n', (40939, 40949), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((41317, 41355), 'riptable.Categorical', 'Categorical', (['[3, 3, 4, 3, 1, 2, 5]', 'd1'], {}), '([3, 3, 4, 3, 1, 2, 5], d1)\n', (41328, 41355), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((41370, 41408), 'riptable.Categorical', 'Categorical', (['[1, 1, 5, 2, 2, 1, 5]', 'd2'], {}), '([1, 1, 5, 2, 2, 1, 5], d2)\n', (41381, 41408), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((41431, 41481), 'riptable.rt_categorical.categorical_merge_dict', 'categorical_merge_dict', (['[c1, c2]'], {'return_type': 'dict'}), '([c1, c2], return_type=dict)\n', (41453, 41481), False, 'from riptable.rt_categorical import categorical_merge_dict\n'), ((41606, 41645), 'riptable.Categorical', 'Categorical', (['[0, 1, 2]', "['a', 'b', 'c']"], {}), "([0, 1, 2], ['a', 'b', 'c'])\n", (41617, 41645), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((42148, 42184), 'riptable.FastArray', 'FastArray', (["['a', 'b', 'c', 'd', 'e']"], {}), "(['a', 'b', 'c', 'd', 'e'])\n", (42157, 42184), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((42268, 42329), 'riptable.FastArray', 'FastArray', (["['e', 'e', 'd', 'b', 'e', 'c', 'c', 'e', 'a', 'd']"], {}), "(['e', 'e', 'd', 'b', 'e', 'c', 'c', 'e', 'a', 'd'])\n", (42277, 42329), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((42343, 42363), 'riptable.Categorical', 'Categorical', (['str_arr'], {}), '(str_arr)\n', (42354, 42363), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((42874, 42987), 'riptable.Categorical', 'Categorical', (["['a', 'b', 'c', 'my_invalid']", "['a', 'b', 'c', 'my_invalid']"], {'invalid': '"""my_invalid"""', 'base_index': '(1)'}), "(['a', 'b', 'c', 'my_invalid'], ['a', 'b', 'c', 'my_invalid'],\n invalid='my_invalid', base_index=1)\n", (42885, 42987), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((43262, 43375), 'riptable.Categorical', 'Categorical', (["['a', 'b', 'c', 'my_invalid']", "['a', 'b', 'c', 'my_invalid']"], {'invalid': '"""my_invalid"""', 'base_index': '(1)'}), "(['a', 'b', 'c', 'my_invalid'], ['a', 'b', 'c', 'my_invalid'],\n invalid='my_invalid', base_index=1)\n", (43273, 43375), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((44146, 44194), 'riptable.Categorical', 'Categorical', (["['a', 'a', 'b', 'a', 'c', 'c', 'b']"], {}), "(['a', 'a', 'b', 'a', 'c', 'c', 'b'])\n", (44157, 44194), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((44214, 44269), 'riptable.FastArray', 'FastArray', (['[True, True, True, True, False, False, True]'], {}), '([True, True, True, True, False, False, True])\n', (44223, 44269), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((44766, 44814), 'riptable.Categorical', 'Categorical', (["['a', 'a', 'b', 'a', 'c', 'c', 'b']"], {}), "(['a', 'a', 'b', 'a', 'c', 'c', 'b'])\n", (44777, 44814), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((45944, 45977), 'riptable.Categorical', 'Categorical', (['values'], {'base_index': '(1)'}), '(values, base_index=1)\n', (45955, 45977), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((46247, 46293), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['expected', 'c.category_array'], {}), '(expected, c.category_array)\n', (46265, 46293), False, 'from numpy.testing import assert_array_equal\n'), ((46451, 46513), 'riptable.Categorical', 'Categorical', (["['a', 'a', 'b', 'a', 'c', 'c', 'b']"], {'unicode': '(True)'}), "(['a', 'a', 'b', 'a', 'c', 'c', 'b'], unicode=True)\n", (46462, 46513), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((46832, 46853), 'riptable.Categorical', 'Categorical', (['codes', 'd'], {}), '(codes, d)\n', (46843, 46853), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((47807, 47862), 'riptable.Categorical', 'Categorical', (['[44, 133, 133, 75, 144, 1]', 'LikertDecision'], {}), '([44, 133, 133, 75, 144, 1], LikertDecision)\n', (47818, 47862), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((47977, 48029), 'riptable.FastArray', 'FastArray', (['[False, False, False, False, True, False]'], {}), '([False, False, False, False, True, False])\n', (47986, 48029), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((48381, 48429), 'riptable.Categorical', 'Categorical', (["['a', 'a', 'b', 'a', 'c', 'c', 'b']"], {}), "(['a', 'a', 'b', 'a', 'c', 'c', 'b'])\n", (48392, 48429), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((49118, 49173), 'riptable.Categorical', 'Categorical', (["['b', 'b', 'b', 'a', 'b', 'b']", "['a', 'b']"], {}), "(['b', 'b', 'b', 'a', 'b', 'b'], ['a', 'b'])\n", (49129, 49173), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((49514, 49569), 'riptable.Categorical', 'Categorical', (["['b', 'b', 'b', 'a', 'b', 'b']", "['a', 'b']"], {}), "(['b', 'b', 'b', 'a', 'b', 'b'], ['a', 'b'])\n", (49525, 49569), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((51108, 51163), 'riptable.Categorical', 'Categorical', (["['b', 'b', 'b', 'a', 'b', 'b']", "['a', 'b']"], {}), "(['b', 'b', 'b', 'a', 'b', 'b'], ['a', 'b'])\n", (51119, 51163), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((51699, 51754), 'riptable.Categorical', 'Categorical', (["['b', 'b', 'b', 'a', 'b', 'b']", "['a', 'b']"], {}), "(['b', 'b', 'b', 'a', 'b', 'b'], ['a', 'b'])\n", (51710, 51754), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((52688, 52743), 'riptable.Categorical', 'Categorical', (["['b', 'b', 'b', 'a', 'b', 'b']", "['a', 'b']"], {}), "(['b', 'b', 'b', 'a', 'b', 'b'], ['a', 'b'])\n", (52699, 52743), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((53549, 53604), 'riptable.Categorical', 'Categorical', (["['b', 'b', 'b', 'a', 'b', 'b']", "['a', 'b']"], {}), "(['b', 'b', 'b', 'a', 'b', 'b'], ['a', 'b'])\n", (53560, 53604), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((55306, 55349), 'riptable.Categorical', 'Categorical', (["['b', 'b', 'b', 'a', 'b', 'b']"], {}), "(['b', 'b', 'b', 'a', 'b', 'b'])\n", (55317, 55349), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((56707, 56724), 'riptable.Categorical', 'Categorical', (['nums'], {}), '(nums)\n', (56718, 56724), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((56856, 56873), 'riptable.Categorical', 'Categorical', (['nums'], {}), '(nums)\n', (56867, 56873), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((57678, 57738), 'riptable.Categorical', 'Categorical', (["['b', 'b', 'b', 'a', 'b', 'b']", "['a', 'b', 'c']"], {}), "(['b', 'b', 'b', 'a', 'b', 'b'], ['a', 'b', 'c'])\n", (57689, 57738), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((57752, 57807), 'riptable.Categorical', 'Categorical', (["['b', 'b', 'b', 'a', 'b', 'b']", "['a', 'b']"], {}), "(['b', 'b', 'b', 'a', 'b', 'b'], ['a', 'b'])\n", (57763, 57807), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((58297, 58352), 'riptable.Categorical', 'Categorical', (["['b', 'b', 'b', 'a', 'b', 'b']", "['a', 'b']"], {}), "(['b', 'b', 'b', 'a', 'b', 'b'], ['a', 'b'])\n", (58308, 58352), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((58893, 58948), 'riptable.Categorical', 'Categorical', (["['b', 'b', 'b', 'a', 'b', 'b']", "['a', 'b']"], {}), "(['b', 'b', 'b', 'a', 'b', 'b'], ['a', 'b'])\n", (58904, 58948), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((58963, 59004), 'riptable.Categorical', 'Categorical', (['[0, 1]', "{(0): 'a', (1): 'b'}"], {}), "([0, 1], {(0): 'a', (1): 'b'})\n", (58974, 59004), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((59126, 59167), 'riptable.Categorical', 'Categorical', (['[0, 1]', "{(0): 'a', (1): 'b'}"], {}), "([0, 1], {(0): 'a', (1): 'b'})\n", (59137, 59167), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((59178, 59219), 'riptable.Categorical', 'Categorical', (['[0, 1]', "{(1): 'a', (0): 'b'}"], {}), "([0, 1], {(1): 'a', (0): 'b'})\n", (59189, 59219), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((59335, 59376), 'riptable.Categorical', 'Categorical', (['[0, 1]', "{(0): 'a', (1): 'b'}"], {}), "([0, 1], {(0): 'a', (1): 'b'})\n", (59346, 59376), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((59387, 59428), 'riptable.Categorical', 'Categorical', (['[2, 1]', "{(2): 'c', (1): 'b'}"], {}), "([2, 1], {(2): 'c', (1): 'b'})\n", (59398, 59428), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((59444, 59468), 'riptable.FastArray', 'FastArray', (['[False, True]'], {}), '([False, True])\n', (59453, 59468), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((59609, 59681), 'riptable.Categorical', 'Categorical', (['[1, 1, 3, 2, 2]', "['a', 'b', 'c']"], {'base_index': '(1)', 'invalid': '"""a"""'}), "([1, 1, 3, 2, 2], ['a', 'b', 'c'], base_index=1, invalid='a')\n", (59620, 59681), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((60161, 60199), 'riptable.Categorical', 'Categorical', (["['a', 'b', 'c', 'd', 'e']"], {}), "(['a', 'b', 'c', 'd', 'e'])\n", (60172, 60199), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((61054, 61121), 'riptable.Categorical', 'Categorical', (['[1, 2, 3, 4]', "{(1): 'a', (2): 'b', (3): 'c', (4): 'd'}"], {}), "([1, 2, 3, 4], {(1): 'a', (2): 'b', (3): 'c', (4): 'd'})\n", (61065, 61121), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((62052, 62090), 'riptable.Categorical', 'Categorical', (["['a', 'a', 'b', 'c', 'a']"], {}), "(['a', 'a', 'b', 'c', 'a'])\n", (62063, 62090), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((62170, 62222), 'riptable.Categorical', 'Categorical', (["['a', 'a', 'b', 'c', 'a']"], {'base_index': '(0)'}), "(['a', 'a', 'b', 'c', 'a'], base_index=0)\n", (62181, 62222), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((62535, 62573), 'riptable.Categorical', 'Categorical', (['codes', 'cats'], {'base_index': '(1)'}), '(codes, cats, base_index=1)\n', (62546, 62573), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((62695, 62737), 'riptable.Categorical', 'Categorical', (['codes', 'cats'], {'from_matlab': '(True)'}), '(codes, cats, from_matlab=True)\n', (62706, 62737), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((63349, 63387), 'riptable.Categorical', 'Categorical', (["['c', 'c', 'a', 'b', 'c']"], {}), "(['c', 'c', 'a', 'b', 'c'])\n", (63360, 63387), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((63468, 63521), 'riptable.Categorical', 'Categorical', (["['c', 'c', 'a', 'b', 'c']"], {'ordered': '(False)'}), "(['c', 'c', 'a', 'b', 'c'], ordered=False)\n", (63479, 63521), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((63602, 63657), 'riptable.Categorical', 'Categorical', (["['c', 'c', 'a', 'b', 'c']", "['c', 'a', 'b']"], {}), "(['c', 'c', 'a', 'b', 'c'], ['c', 'a', 'b'])\n", (63613, 63657), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((63768, 63823), 'riptable.Categorical', 'Categorical', (["['c', 'c', 'a', 'b', 'c']", "['a', 'b', 'c']"], {}), "(['c', 'c', 'a', 'b', 'c'], ['a', 'b', 'c'])\n", (63779, 63823), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((64215, 64285), 'riptable.Categorical', 'Categorical', (["['c', 'c', 'a', 'b', 'c']", "['c', 'a', 'b']"], {'ordered': '(False)'}), "(['c', 'c', 'a', 'b', 'c'], ['c', 'a', 'b'], ordered=False)\n", (64226, 64285), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((64400, 64426), 'riptable.FastArray', 'FastArray', (['[0, 0, 1, 2, 0]'], {}), '([0, 0, 1, 2, 0])\n', (64409, 64426), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((64443, 64483), 'riptable.FastArray', 'FastArray', (["['c', 'b', 'a']"], {'unicode': '(True)'}), "(['c', 'b', 'a'], unicode=True)\n", (64452, 64483), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((64497, 64521), 'riptable.Categorical', 'Categorical', (['codes', 'cats'], {}), '(codes, cats)\n', (64508, 64521), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((65397, 65452), 'riptable.Categorical', 'Categorical', (["['b', 'b', 'b', 'a', 'b', 'b']", "['a', 'b']"], {}), "(['b', 'b', 'b', 'a', 'b', 'b'], ['a', 'b'])\n", (65408, 65452), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((67528, 67556), 'riptable.Categorical', 'Categorical', (["['a', 'b', 'c']"], {}), "(['a', 'b', 'c'])\n", (67539, 67556), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((67925, 67953), 'riptable.Categorical', 'Categorical', (["['a', 'b', 'c']"], {}), "(['a', 'b', 'c'])\n", (67936, 67953), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((68114, 68168), 'riptable.Categorical', 'Categorical', (['[1, 2, 3]', "{(1): 'a', (2): 'b', (3): 'c'}"], {}), "([1, 2, 3], {(1): 'a', (2): 'b', (3): 'c'})\n", (68125, 68168), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((68565, 68593), 'riptable.Categorical', 'Categorical', (["['a', 'b', 'c']"], {}), "(['a', 'b', 'c'])\n", (68576, 68593), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((69645, 69676), 'pandas.Categorical', 'pd.Categorical', (["['a', 'b', 'c']"], {}), "(['a', 'b', 'c'])\n", (69659, 69676), True, 'import pandas as pd\n'), ((69690, 69720), 'riptable.Categorical', 'Categorical', (['pdc'], {'unicode': '(True)'}), '(pdc, unicode=True)\n', (69701, 69720), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((69787, 69818), 'riptable.Categorical', 'Categorical', (['pdc'], {'unicode': '(False)'}), '(pdc, unicode=False)\n', (69798, 69818), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((69887, 69916), 'pandas.Categorical', 'pd.Categorical', (['three_unicode'], {}), '(three_unicode)\n', (69901, 69916), True, 'import pandas as pd\n'), ((69930, 69946), 'riptable.Categorical', 'Categorical', (['pdc'], {}), '(pdc)\n', (69941, 69946), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((71046, 71100), 'riptable.Categorical', 'Categorical', (['[1, 1, 2, 3, 1]', "{'a': 1, 'b': 2, 'c': 3}"], {}), "([1, 1, 2, 3, 1], {'a': 1, 'b': 2, 'c': 3})\n", (71057, 71100), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((71428, 71494), 'riptable.Categorical', 'Categorical', (["['a', 'a', 'b', 'c', 'a']"], {'unicode': '(True)', 'invalid': "b'a'"}), "(['a', 'a', 'b', 'c', 'a'], unicode=True, invalid=b'a')\n", (71439, 71494), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((72323, 72345), 'riptable.Categorical', 'Categorical', (['ds.strcol'], {}), '(ds.strcol)\n', (72334, 72345), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((72402, 72437), 'riptable.Categorical', 'Categorical', (['[ds.strcol, ds.numcol]'], {}), '([ds.strcol, ds.numcol])\n', (72413, 72437), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((72679, 72728), 'riptable.Categorical', 'Categorical', (['ds.mycodes', "{'a': 1, 'b': 2, 'c': 3}"], {}), "(ds.mycodes, {'a': 1, 'b': 2, 'c': 3})\n", (72690, 72728), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((72834, 72860), 'riptable.FastArray', 'FastArray', (["['a', 'b', 'c']"], {}), "(['a', 'b', 'c'])\n", (72843, 72860), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((72905, 72929), 'riptable.Categorical', 'Categorical', (['codes', 'cats'], {}), '(codes, cats)\n', (72916, 72929), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((73017, 73040), 'riptable.Categorical', 'Categorical', (["['a', 'b']"], {}), "(['a', 'b'])\n", (73028, 73040), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((73331, 73369), 'riptable.Categorical', 'Categorical', (["['a', 'a', 'b', 'c', 'a']"], {}), "(['a', 'a', 'b', 'c', 'a'])\n", (73342, 73369), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((73383, 73397), 'riptable.Categorical', 'Categorical', (['c'], {}), '(c)\n', (73394, 73397), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((73526, 73542), 'riptable.Categorical', 'Categorical', (['[c]'], {}), '([c])\n', (73537, 73542), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((73704, 73742), 'riptable.Categorical', 'Categorical', (["['a', 'a', 'b', 'c', 'a']"], {}), "(['a', 'a', 'b', 'c', 'a'])\n", (73715, 73742), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((74518, 74554), 'riptable.FastArray', 'FastArray', (["['a', 'a', 'b', 'c', 'a']"], {}), "(['a', 'a', 'b', 'c', 'a'])\n", (74527, 74554), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((74574, 74583), 'riptable.rt_numpy.arange', 'arange', (['(5)'], {}), '(5)\n', (74580, 74583), False, 'from riptable.rt_numpy import isnan, isnotnan, arange, ones\n'), ((74599, 74633), 'riptable.Categorical', 'Categorical', (['[og_strings, og_nums]'], {}), '([og_strings, og_nums])\n', (74610, 74633), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((74886, 74934), 'riptable.Categorical', 'Categorical', (['[1, 2, 3]', "{'a': 1, 'b': 2, 'c': 3}"], {}), "([1, 2, 3], {'a': 1, 'b': 2, 'c': 3})\n", (74897, 74934), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((75304, 75352), 'riptable.Categorical', 'Categorical', (['[1, 2, 3]', "{'a': 1, 'b': 2, 'c': 3}"], {}), "([1, 2, 3], {'a': 1, 'b': 2, 'c': 3})\n", (75315, 75352), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((76143, 76171), 'riptable.Categorical', 'Categorical', (["['a', 'b', 'c']"], {}), "(['a', 'b', 'c'])\n", (76154, 76171), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((76399, 76456), 'riptable.Categorical', 'Categorical', (['[1, 1, 1, 1, 2, 3]', "{'a': 1, 'b': 2, 'c': 3}"], {}), "([1, 1, 1, 1, 2, 3], {'a': 1, 'b': 2, 'c': 3})\n", (76410, 76456), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((76471, 76528), 'riptable.Categorical', 'Categorical', (['[1, 1, 1, 1, 3, 4]', "{'a': 1, 'c': 3, 'd': 4}"], {}), "([1, 1, 1, 1, 3, 4], {'a': 1, 'c': 3, 'd': 4})\n", (76482, 76528), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((76548, 76576), 'riptable.Categorical.hstack', 'Categorical.hstack', (['[c1, c2]'], {}), '([c1, c2])\n', (76566, 76576), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((76766, 76823), 'riptable.Categorical', 'Categorical', (['[1, 1, 1, 1, 2, 3]', "{'a': 1, 'b': 2, 'd': 3}"], {}), "([1, 1, 1, 1, 2, 3], {'a': 1, 'b': 2, 'd': 3})\n", (76777, 76823), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((76838, 76895), 'riptable.Categorical', 'Categorical', (['[1, 1, 1, 1, 3, 4]', "{'a': 1, 'c': 3, 'd': 4}"], {}), "([1, 1, 1, 1, 3, 4], {'a': 1, 'c': 3, 'd': 4})\n", (76849, 76895), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((77182, 77211), 'riptable.FastArray', 'FastArray', (['[1.0, 0.0, np.nan]'], {}), '([1.0, 0.0, np.nan])\n', (77191, 77211), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((77848, 77907), 'riptable.FastArray', 'FastArray', (["[b'INVALID', b'INVALID', b'b', b'c', b'INVALID']"], {}), "([b'INVALID', b'INVALID', b'b', b'c', b'INVALID'])\n", (77857, 77907), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((78171, 78200), 'riptable.FastArray', 'FastArray', (["[f, f, b'b', b'c']"], {}), "([f, f, b'b', b'c'])\n", (78180, 78200), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((78340, 78369), 'riptable.FastArray', 'FastArray', (["[b'a', b'b', b'c']"], {}), "([b'a', b'b', b'c'])\n", (78349, 78369), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((78800, 78853), 'riptable.Categorical', 'Categorical', (['[1.0, 1.0, 2.0]', '[1.0, 2.0]'], {'invalid': '(2.0)'}), '([1.0, 1.0, 2.0], [1.0, 2.0], invalid=2.0)\n', (78811, 78853), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((79154, 79206), 'riptable.Categorical', 'Categorical', (["['b', 'c', 'a', 'a', 'b']"], {'base_index': '(0)'}), "(['b', 'c', 'a', 'a', 'b'], base_index=0)\n", (79165, 79206), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((79481, 79533), 'riptable.Categorical', 'Categorical', (["['b', 'c', 'a', 'a', 'b']"], {'base_index': '(1)'}), "(['b', 'c', 'a', 'a', 'b'], base_index=1)\n", (79492, 79533), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((79880, 79908), 'riptable.Categorical', 'Categorical', (["['a', 'b', 'c']"], {}), "(['a', 'b', 'c'])\n", (79891, 79908), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((80096, 80124), 'riptable.Categorical', 'Categorical', (["['a', 'b', 'c']"], {}), "(['a', 'b', 'c'])\n", (80107, 80124), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((80950, 80971), 'riptable.Categorical', 'Categorical', (['codes', 'd'], {}), '(codes, d)\n', (80961, 80971), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((81119, 81140), 'riptable.Categorical', 'Categorical', (['codes', 'd'], {}), '(codes, d)\n', (81130, 81140), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((81245, 81254), 'riptable.rt_numpy.arange', 'arange', (['(5)'], {}), '(5)\n', (81251, 81254), False, 'from riptable.rt_numpy import isnan, isnotnan, arange, ones\n'), ((81268, 81289), 'riptable.Categorical', 'Categorical', (['codes', 'd'], {}), '(codes, d)\n', (81279, 81289), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((81390, 81450), 'riptable.Categorical', 'Categorical', (["['a', 'a', 'b', 'c', 'd']", "['a', 'b', 'c', 'd']"], {}), "(['a', 'a', 'b', 'c', 'd'], ['a', 'b', 'c', 'd'])\n", (81401, 81450), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((81551, 81625), 'riptable.Categorical', 'Categorical', (["['a', 'a', 'b', 'c', 'd']", "['a', 'b', 'c', 'd']"], {'base_index': '(0)'}), "(['a', 'a', 'b', 'c', 'd'], ['a', 'b', 'c', 'd'], base_index=0)\n", (81562, 81625), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((81726, 81764), 'riptable.Categorical', 'Categorical', (["['a', 'a', 'b', 'c', 'd']"], {}), "(['a', 'a', 'b', 'c', 'd'])\n", (81737, 81764), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((83169, 83178), 'riptable.rt_numpy.ones', 'ones', (['(100)'], {}), '(100)\n', (83173, 83178), False, 'from riptable.rt_numpy import isnan, isnotnan, arange, ones\n'), ((83218, 83258), 'riptable.Categorical', 'Categorical', (['idx', 'cats'], {'from_matlab': '(True)'}), '(idx, cats, from_matlab=True)\n', (83229, 83258), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((83559, 83584), 'riptable.Categorical', 'Categorical', (['[strs, flts]'], {}), '([strs, flts])\n', (83570, 83584), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((83603, 83620), 'riptable.Categorical', 'Categorical', (['strs'], {}), '(strs)\n', (83614, 83620), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((83639, 83656), 'riptable.Categorical', 'Categorical', (['flts'], {}), '(flts)\n', (83650, 83656), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((83783, 83810), 'riptable.Categorical', 'Categorical', (['[strs2, flts2]'], {}), '([strs2, flts2])\n', (83794, 83810), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((83829, 83847), 'riptable.Categorical', 'Categorical', (['strs2'], {}), '(strs2)\n', (83840, 83847), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((83866, 83884), 'riptable.Categorical', 'Categorical', (['flts2'], {}), '(flts2)\n', (83877, 83884), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((84043, 84062), 'riptable.Categorical', 'Categorical', (['fa_str'], {}), '(fa_str)\n', (84054, 84062), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((84080, 84099), 'riptable.Categorical', 'Categorical', (['fa_flt'], {}), '(fa_flt)\n', (84091, 84099), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((84939, 84966), 'riptable.load_sds', 'load_sds', (['paths'], {'stack': '(True)'}), '(paths, stack=True)\n', (84947, 84966), False, 'from riptable import save_sds, load_sds\n'), ((88397, 88411), 'riptable.Categorical', 'Categorical', (['f'], {}), '(f)\n', (88408, 88411), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((89247, 89270), 'riptable.Categorical', 'Categorical', (['three_ints'], {}), '(three_ints)\n', (89258, 89270), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((89584, 89610), 'riptable.Categorical', 'Categorical', (['three_unicode'], {}), '(three_unicode)\n', (89595, 89610), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((90250, 90274), 'riptable.Categorical', 'Categorical', (['three_bytes'], {}), '(three_bytes)\n', (90261, 90274), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((90901, 90925), 'riptable.Categorical', 'Categorical', (['three_bytes'], {}), '(three_bytes)\n', (90912, 90925), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((91740, 91764), 'riptable.Categorical', 'Categorical', (['three_bytes'], {}), '(three_bytes)\n', (91751, 91764), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((91779, 91803), 'riptable.Categorical', 'Categorical', (['three_bytes'], {}), '(three_bytes)\n', (91790, 91803), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((92130, 92156), 'riptable.Categorical', 'Categorical', (['three_unicode'], {}), '(three_unicode)\n', (92141, 92156), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((92171, 92197), 'riptable.Categorical', 'Categorical', (['three_unicode'], {}), '(three_unicode)\n', (92182, 92197), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((92516, 92544), 'riptable.Categorical', 'Categorical', (["['a', 'b', 'c']"], {}), "(['a', 'b', 'c'])\n", (92527, 92544), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((92559, 92583), 'riptable.Categorical', 'Categorical', (['three_bytes'], {}), '(three_bytes)\n', (92570, 92583), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((93039, 93074), 'riptable.Categorical', 'Categorical', (['[0, 1, 0]', 'three_bytes'], {}), '([0, 1, 0], three_bytes)\n', (93050, 93074), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((93089, 93124), 'riptable.Categorical', 'Categorical', (['[2, 1, 2]', 'three_bytes'], {}), '([2, 1, 2], three_bytes)\n', (93100, 93124), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((93439, 93476), 'riptable.Categorical', 'Categorical', (['[0, 1, 0]', 'three_unicode'], {}), '([0, 1, 0], three_unicode)\n', (93450, 93476), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((93491, 93528), 'riptable.Categorical', 'Categorical', (['[2, 1, 2]', 'three_unicode'], {}), '([2, 1, 2], three_unicode)\n', (93502, 93528), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((115370, 115386), 'riptable.save_sds', 'save_sds', (['p', 'cat'], {}), '(p, cat)\n', (115378, 115386), False, 'from riptable import save_sds, load_sds\n'), ((115403, 115414), 'riptable.load_sds', 'load_sds', (['p'], {}), '(p)\n', (115411, 115414), False, 'from riptable import save_sds, load_sds\n'), ((115647, 115684), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['cat2._fa', 'cat._fa'], {}), '(cat2._fa, cat._fa)\n', (115665, 115684), False, 'from numpy.testing import assert_array_equal\n'), ((116081, 116124), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['cat2_values', 'cat_values'], {}), '(cat2_values, cat_values)\n', (116099, 116124), False, 'from numpy.testing import assert_array_equal\n'), ((116391, 116428), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['cat3._fa', 'cat._fa'], {}), '(cat3._fa, cat._fa)\n', (116409, 116428), False, 'from numpy.testing import assert_array_equal\n'), ((116825, 116868), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['cat3_values', 'cat_values'], {}), '(cat3_values, cat_values)\n', (116843, 116868), False, 'from numpy.testing import assert_array_equal\n'), ((7774, 7792), 'riptable.FastArray', 'FastArray', (['v_bytes'], {}), '(v_bytes)\n', (7783, 7792), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((7807, 7823), 'riptable.FastArray', 'FastArray', (['v_str'], {}), '(v_str)\n', (7816, 7823), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((7974, 7992), 'riptable.FastArray', 'FastArray', (['c_bytes'], {}), '(c_bytes)\n', (7983, 7992), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((8007, 8023), 'riptable.FastArray', 'FastArray', (['c_str'], {}), '(c_str)\n', (8016, 8023), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((9684, 9709), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (9697, 9709), False, 'import pytest\n'), ((9728, 9759), 'riptable.Categorical', 'Categorical', (['idx_list', 'str_list'], {}), '(idx_list, str_list)\n', (9739, 9759), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((10786, 10829), 'riptable.FastArray', 'FastArray', (['[True, False, False, True, True]'], {}), '([True, False, False, True, True])\n', (10795, 10829), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((10844, 10888), 'riptable.FastArray', 'FastArray', (['[False, True, True, False, False]'], {}), '([False, True, True, False, False])\n', (10853, 10888), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((10903, 10945), 'riptable.FastArray', 'FastArray', (['[False, True, True, True, True]'], {}), '([False, True, True, True, True])\n', (10912, 10945), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((10960, 11004), 'riptable.FastArray', 'FastArray', (['[False, False, False, True, True]'], {}), '([False, False, False, True, True])\n', (10969, 11004), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((11019, 11062), 'riptable.FastArray', 'FastArray', (['[True, True, True, False, False]'], {}), '([True, True, True, False, False])\n', (11028, 11062), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((11077, 11122), 'riptable.FastArray', 'FastArray', (['[True, False, False, False, False]'], {}), '([True, False, False, False, False])\n', (11086, 11122), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((11177, 11218), 'riptable.FastArray', 'FastArray', (['[True, True, True, True, True]'], {}), '([True, True, True, True, True])\n', (11186, 11218), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((11233, 11279), 'riptable.FastArray', 'FastArray', (['[False, False, False, False, False]'], {}), '([False, False, False, False, False])\n', (11242, 11279), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((11294, 11336), 'riptable.FastArray', 'FastArray', (['[False, True, True, True, True]'], {}), '([False, True, True, True, True])\n', (11303, 11336), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((11351, 11393), 'riptable.FastArray', 'FastArray', (['[False, True, True, True, True]'], {}), '([False, True, True, True, True])\n', (11360, 11393), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((11408, 11453), 'riptable.FastArray', 'FastArray', (['[True, False, False, False, False]'], {}), '([True, False, False, False, False])\n', (11417, 11453), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((11468, 11513), 'riptable.FastArray', 'FastArray', (['[True, False, False, False, False]'], {}), '([True, False, False, False, False])\n', (11477, 11513), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((11594, 11615), 'riptable.Categorical', 'Categorical', (['codes', 'd'], {}), '(codes, d)\n', (11605, 11615), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((12925, 12968), 'riptable.FastArray', 'FastArray', (['[True, False, False, True, True]'], {}), '([True, False, False, True, True])\n', (12934, 12968), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((12983, 13027), 'riptable.FastArray', 'FastArray', (['[False, True, True, False, False]'], {}), '([False, True, True, False, False])\n', (12992, 13027), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((13042, 13084), 'riptable.FastArray', 'FastArray', (['[False, True, True, True, True]'], {}), '([False, True, True, True, True])\n', (13051, 13084), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((13099, 13143), 'riptable.FastArray', 'FastArray', (['[False, False, False, True, True]'], {}), '([False, False, False, True, True])\n', (13108, 13143), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((13158, 13201), 'riptable.FastArray', 'FastArray', (['[True, True, True, False, False]'], {}), '([True, True, True, False, False])\n', (13167, 13201), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((13216, 13261), 'riptable.FastArray', 'FastArray', (['[True, False, False, False, False]'], {}), '([True, False, False, False, False])\n', (13225, 13261), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((13342, 13363), 'riptable.Categorical', 'Categorical', (['codes', 'd'], {}), '(codes, d)\n', (13353, 13363), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((16752, 16777), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (16765, 16777), False, 'import pytest\n'), ((16939, 16964), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (16952, 16964), False, 'import pytest\n'), ((17756, 17781), 'pytest.raises', 'pytest.raises', (['IndexError'], {}), '(IndexError)\n', (17769, 17781), False, 'import pytest\n'), ((18804, 18821), 'riptable.FastArray', 'FastArray', (['[1, 4]'], {}), '([1, 4])\n', (18813, 18821), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((19434, 19458), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (19447, 19458), False, 'import pytest\n'), ((19477, 19508), 'riptable.Categorical', 'Categorical', (['idx_list', 'str_list'], {}), '(idx_list, str_list)\n', (19488, 19508), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((22559, 22583), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (22572, 22583), False, 'import pytest\n'), ((22602, 22619), 'riptable.Categorical', 'Categorical', (['(1)', '(2)'], {}), '(1, 2)\n', (22613, 22619), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((23017, 23043), 'riptable.Categorical', 'Categorical', (['arr'], {'dtype': 'dt'}), '(arr, dtype=dt)\n', (23028, 23043), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((23605, 23629), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (23618, 23629), False, 'import pytest\n'), ((23650, 23665), 'riptable.rt_categorical.Categories', 'Categories', (['tup'], {}), '(tup)\n', (23660, 23665), False, 'from riptable.rt_categorical import Categories\n'), ((23730, 23799), 'riptable.Categorical', 'Categorical', (["['a', 'b', 'c']"], {'ordered': '(True)', 'base_index': '(1)', 'filter': 'None'}), "(['a', 'b', 'c'], ordered=True, base_index=1, filter=None)\n", (23741, 23799), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((28480, 28505), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (28493, 28505), False, 'import pytest\n'), ((28524, 28592), 'riptable.Categorical', 'Categorical', (["['a', 'a', 'b', 'c', 'a']"], {'base_index': '(99)', 'filter': 'filter'}), "(['a', 'a', 'b', 'c', 'a'], base_index=99, filter=filter)\n", (28535, 28592), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((29029, 29063), 'pytest.raises', 'pytest.raises', (['NotImplementedError'], {}), '(NotImplementedError)\n', (29042, 29063), False, 'import pytest\n'), ((29082, 29170), 'riptable.Categorical', 'Categorical', (["['a', 'a', 'b', 'c', 'a']", "['a', 'b', 'c']"], {'base_index': '(0)', 'filter': 'filter'}), "(['a', 'a', 'b', 'c', 'a'], ['a', 'b', 'c'], base_index=0,\n filter=filter)\n", (29093, 29170), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((29183, 29208), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (29196, 29208), False, 'import pytest\n'), ((29227, 29304), 'riptable.Categorical', 'Categorical', (['[1.0, 2.0, 3.0]', "['a', 'b', 'c']"], {'from_matlab': '(True)', 'base_index': '(0)'}), "([1.0, 2.0, 3.0], ['a', 'b', 'c'], from_matlab=True, base_index=0)\n", (29238, 29304), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((29378, 29403), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (29391, 29403), False, 'import pytest\n'), ((29422, 29452), 'riptable.Categorical', 'Categorical', (['pdc'], {'base_index': '(0)'}), '(pdc, base_index=0)\n', (29433, 29452), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((30836, 30861), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (30849, 30861), False, 'import pytest\n'), ((30880, 30977), 'riptable.Categorical', 'Categorical', (['values', 'incomplete_cats'], {'ordered': '(True)', 'base_index': '(1)', 'unicode': '(False)', 'filter': 'None'}), '(values, incomplete_cats, ordered=True, base_index=1, unicode=\n False, filter=None)\n', (30891, 30977), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((31082, 31107), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (31095, 31107), False, 'import pytest\n'), ((31126, 31239), 'riptable.Categorical', 'Categorical', (['values', 'incomplete_cats'], {'ordered': '(True)', 'base_index': '(1)', 'unicode': '(True)', 'filter': 'None', 'invalid': 'invalid'}), '(values, incomplete_cats, ordered=True, base_index=1, unicode=\n True, filter=None, invalid=invalid)\n', (31137, 31239), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((31938, 31963), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (31951, 31963), False, 'import pytest\n'), ((32803, 32827), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (32816, 32827), False, 'import pytest\n'), ((33399, 33423), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (33412, 33423), False, 'import pytest\n'), ((36225, 36250), 'pytest.warns', 'pytest.warns', (['UserWarning'], {}), '(UserWarning)\n', (36237, 36250), False, 'import pytest\n'), ((36269, 36298), 'riptable.Categorical', 'Categorical', (['[1, 2]', 'DupeEnum'], {}), '([1, 2], DupeEnum)\n', (36280, 36298), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((39719, 39757), 'pytest.raises', 'pytest.raises', (['(ValueError, TypeError)'], {}), '((ValueError, TypeError))\n', (39732, 39757), False, 'import pytest\n'), ((39772, 39795), 'riptable.hstack', 'rt.hstack', (['[cat1, cat2]'], {}), '([cat1, cat2])\n', (39781, 39795), True, 'import riptable as rt\n'), ((41853, 41878), 'pytest.raises', 'pytest.raises', (['IndexError'], {}), '(IndexError)\n', (41866, 41878), False, 'import pytest\n'), ((42665, 42689), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (42678, 42689), False, 'import pytest\n'), ((42708, 42752), 'riptable.Categorical', 'Categorical', (["['a', 'b', 'c']", 'LikertDecision'], {}), "(['a', 'b', 'c'], LikertDecision)\n", (42719, 42752), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((44284, 44309), 'pytest.raises', 'pytest.raises', (['IndexError'], {}), '(IndexError)\n', (44297, 44309), False, 'import pytest\n'), ((44501, 44526), 'pytest.raises', 'pytest.raises', (['IndexError'], {}), '(IndexError)\n', (44514, 44526), False, 'import pytest\n'), ((47877, 47902), 'pytest.raises', 'pytest.raises', (['IndexError'], {}), '(IndexError)\n', (47890, 47902), False, 'import pytest\n'), ((48217, 48242), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (48230, 48242), False, 'import pytest\n'), ((48261, 48326), 'riptable.Categorical', 'Categorical', (["['a', 'a', 'b', 'a', 'c', 'c', 'b']", "['a', 'a', 'b']"], {}), "(['a', 'a', 'b', 'a', 'c', 'c', 'b'], ['a', 'a', 'b'])\n", (48272, 48326), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((48541, 48565), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (48554, 48565), False, 'import pytest\n'), ((48657, 48681), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (48670, 48681), False, 'import pytest\n'), ((49406, 49431), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (49419, 49431), False, 'import pytest\n'), ((49798, 49823), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (49811, 49823), False, 'import pytest\n'), ((51542, 51567), 'pytest.raises', 'pytest.raises', (['IndexError'], {}), '(IndexError)\n', (51555, 51567), False, 'import pytest\n'), ((59015, 59039), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (59028, 59039), False, 'import pytest\n'), ((59230, 59255), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (59243, 59255), False, 'import pytest\n'), ((60416, 60440), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (60429, 60440), False, 'import pytest\n'), ((60498, 60522), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (60511, 60522), False, 'import pytest\n'), ((60864, 60888), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (60877, 60888), False, 'import pytest\n'), ((60946, 60970), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (60959, 60970), False, 'import pytest\n'), ((61588, 61612), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (61601, 61612), False, 'import pytest\n'), ((61782, 61806), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (61795, 61806), False, 'import pytest\n'), ((61864, 61888), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (61877, 61888), False, 'import pytest\n'), ((62818, 62843), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (62831, 62843), False, 'import pytest\n'), ((62862, 62918), 'riptable.Categorical', 'Categorical', (['codes', 'cats'], {'from_matlab': '(True)', 'base_index': '(0)'}), '(codes, cats, from_matlab=True, base_index=0)\n', (62873, 62918), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((64999, 65024), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (65012, 65024), False, 'import pytest\n'), ((65043, 65095), 'riptable.Categorical', 'Categorical', (["['a', 'b', 'c']"], {'filter': 'f', 'base_index': '(0)'}), "(['a', 'b', 'c'], filter=f, base_index=0)\n", (65054, 65095), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((66341, 66365), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (66354, 66365), False, 'import pytest\n'), ((66384, 66415), 'riptable.rt_categorical.Categories', 'Categories', (["['garbage', 'list']"], {}), "(['garbage', 'list'])\n", (66394, 66415), False, 'from riptable.rt_categorical import Categories\n'), ((66483, 66508), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (66496, 66508), False, 'import pytest\n'), ((67048, 67073), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (67061, 67073), False, 'import pytest\n'), ((67092, 67146), 'riptable.Categorical', 'Categorical', (["['a', 'b', 'c']", "['b', 'c']"], {'base_index': '(0)'}), "(['a', 'b', 'c'], ['b', 'c'], base_index=0)\n", (67103, 67146), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((69431, 69451), 'riptable.FastArray', 'FastArray', (['[1, 2, 3]'], {}), '([1, 2, 3])\n', (69440, 69451), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((70046, 70071), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (70059, 70071), False, 'import pytest\n'), ((70090, 70105), 'riptable.Categorical', 'Categorical', (['{}'], {}), '({})\n', (70101, 70105), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((70122, 70147), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (70135, 70147), False, 'import pytest\n'), ((70166, 70181), 'riptable.Categorical', 'Categorical', (['[]'], {}), '([])\n', (70177, 70181), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((70235, 70269), 'pytest.raises', 'pytest.raises', (['NotImplementedError'], {}), '(NotImplementedError)\n', (70248, 70269), False, 'import pytest\n'), ((70738, 70762), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (70751, 70762), False, 'import pytest\n'), ((70781, 70841), 'riptable.Categorical', 'Categorical', (['[1.0, 2.0, 3.0]', "{(1): 'a', (2): 'b', (3): 'c'}"], {}), "([1.0, 2.0, 3.0], {(1): 'a', (2): 'b', (3): 'c'})\n", (70792, 70841), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((70895, 70919), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (70908, 70919), False, 'import pytest\n'), ((71297, 71322), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (71310, 71322), False, 'import pytest\n'), ((72072, 72097), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (72085, 72097), False, 'import pytest\n'), ((72116, 72164), 'riptable.CatZero', 'CatZero', (["['a', 'a', 'b', 'c', 'a']"], {'base_index': '(1)'}), "(['a', 'a', 'b', 'c', 'a'], base_index=1)\n", (72123, 72164), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((72459, 72469), 'riptable.rt_numpy.arange', 'arange', (['(10)'], {}), '(10)\n', (72465, 72469), False, 'from riptable.rt_numpy import isnan, isnotnan, arange, ones\n'), ((75197, 75222), 'pytest.warns', 'pytest.warns', (['UserWarning'], {}), '(UserWarning)\n', (75209, 75222), False, 'import pytest\n'), ((77289, 77359), 'riptable.Categorical', 'Categorical', (['matlab_float_idx', 'matlab_cats'], {'dtype': 'dt', 'from_matlab': '(True)'}), '(matlab_float_idx, matlab_cats, dtype=dt, from_matlab=True)\n', (77300, 77359), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((78494, 78519), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (78507, 78519), False, 'import pytest\n'), ((79024, 79050), 'riptable.FastArray', 'FastArray', (['[2, 3, 0, 4, 1]'], {}), '([2, 3, 0, 4, 1])\n', (79033, 79050), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((79065, 79088), 'riptable.FastArray', 'FastArray', (['[0, 0, 2, 4]'], {}), '([0, 0, 2, 4])\n', (79074, 79088), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((79103, 79126), 'riptable.FastArray', 'FastArray', (['[0, 2, 2, 1]'], {}), '([0, 2, 2, 1])\n', (79112, 79126), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((82348, 82357), 'riptable.Cat', 'rt.Cat', (['l'], {}), '(l)\n', (82354, 82357), True, 'import riptable as rt\n'), ((82359, 82372), 'riptable.Cat', 'rt.Cat', (['l[:3]'], {}), '(l[:3])\n', (82365, 82372), True, 'import riptable as rt\n'), ((86368, 86380), 'os.remove', 'os.remove', (['p'], {}), '(p)\n', (86377, 86380), False, 'import os\n'), ((98809, 98832), 'riptable.rt_numpy.arange', 'arange', (['(6)'], {'dtype': 'uint16'}), '(6, dtype=uint16)\n', (98815, 98832), False, 'from riptable.rt_numpy import isnan, isnotnan, arange, ones\n'), ((103816, 103888), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['shift_cat.category_array', 'categorical.category_array'], {}), '(shift_cat.category_array, categorical.category_array)\n', (103834, 103888), False, 'from numpy.testing import assert_array_equal\n'), ((107386, 107458), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['shift_cat.category_array', 'categorical.category_array'], {}), '(shift_cat.category_array, categorical.category_array)\n', (107404, 107458), False, 'from numpy.testing import assert_array_equal\n'), ((110994, 111116), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['shrink_cat.category_array', 'expected_category_array', 'f"""Category dictionary values should be empty."""'], {}), "(shrink_cat.category_array, expected_category_array,\n f'Category dictionary values should be empty.')\n", (111012, 111116), False, 'from numpy.testing import assert_array_equal\n'), ((112382, 112518), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['shrink_cat.category_array', 'expected_category_array', 'f"""Category array should only contain the \'{misc}\' category."""'], {}), '(shrink_cat.category_array, expected_category_array,\n f"Category array should only contain the \'{misc}\' category.")\n', (112400, 112518), False, 'from numpy.testing import assert_array_equal\n'), ((113389, 113438), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['shrink_cat_values', 'cat_values'], {}), '(shrink_cat_values, cat_values)\n', (113407, 113438), False, 'from numpy.testing import assert_array_equal\n'), ((113452, 113495), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['shrink_cat._fa', 'cat._fa'], {}), '(shrink_cat._fa, cat._fa)\n', (113470, 113495), False, 'from numpy.testing import assert_array_equal\n'), ((113509, 113574), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['shrink_cat.category_array', 'cat.category_array'], {}), '(shrink_cat.category_array, cat.category_array)\n', (113527, 113574), False, 'from numpy.testing import assert_array_equal\n'), ((115796, 115855), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['cat2.category_array', 'cat.category_array'], {}), '(cat2.category_array, cat.category_array)\n', (115814, 115855), False, 'from numpy.testing import assert_array_equal\n'), ((115964, 116000), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['actual', 'expected'], {}), '(actual, expected)\n', (115982, 116000), False, 'from numpy.testing import assert_array_equal\n'), ((116540, 116599), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['cat3.category_array', 'cat.category_array'], {}), '(cat3.category_array, cat.category_array)\n', (116558, 116599), False, 'from numpy.testing import assert_array_equal\n'), ((116708, 116744), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['actual', 'expected'], {}), '(actual, expected)\n', (116726, 116744), False, 'from numpy.testing import assert_array_equal\n'), ((118027, 118051), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (118040, 118051), False, 'import pytest\n'), ((118174, 118199), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (118187, 118199), False, 'import pytest\n'), ((118629, 118653), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (118642, 118653), False, 'import pytest\n'), ((120253, 120278), 'pytest.raises', 'pytest.raises', (['IndexError'], {}), '(IndexError)\n', (120266, 120278), False, 'import pytest\n'), ((121152, 121177), 'pytest.raises', 'pytest.raises', (['IndexError'], {}), '(IndexError)\n', (121165, 121177), False, 'import pytest\n'), ((121647, 121672), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (121660, 121672), False, 'import pytest\n'), ((121853, 121878), 'pytest.raises', 'pytest.raises', (['IndexError'], {}), '(IndexError)\n', (121866, 121878), False, 'import pytest\n'), ((122118, 122127), 'riptable.rt_numpy.arange', 'arange', (['(3)'], {}), '(3)\n', (122124, 122127), False, 'from riptable.rt_numpy import isnan, isnotnan, arange, ones\n'), ((127651, 127683), 'riptable.Cat', 'rt.Cat', (['[1, 1, 2, 2]', "['a', 'a']"], {}), "([1, 1, 2, 2], ['a', 'a'])\n", (127657, 127683), True, 'import riptable as rt\n'), ((127685, 127712), 'riptable.Cat', 'rt.Cat', (['[1, 1, 1, 1]', "['a']"], {}), "([1, 1, 1, 1], ['a'])\n", (127691, 127712), True, 'import riptable as rt\n'), ((127721, 127753), 'riptable.Cat', 'rt.Cat', (['[2, 2, 2, 2]', "['a', 'a']"], {}), "([2, 2, 2, 2], ['a', 'a'])\n", (127727, 127753), True, 'import riptable as rt\n'), ((127755, 127782), 'riptable.Cat', 'rt.Cat', (['[1, 1, 1, 1]', "['a']"], {}), "([1, 1, 1, 1], ['a'])\n", (127761, 127782), True, 'import riptable as rt\n'), ((127791, 127828), 'riptable.Cat', 'rt.Cat', (['[1, 2, 3, 3]', "['a', 'a', 'b']"], {}), "([1, 2, 3, 3], ['a', 'a', 'b'])\n", (127797, 127828), True, 'import riptable as rt\n'), ((127830, 127862), 'riptable.Cat', 'rt.Cat', (['[1, 1, 2, 2]', "['a', 'b']"], {}), "([1, 1, 2, 2], ['a', 'b'])\n", (127836, 127862), True, 'import riptable as rt\n'), ((127871, 127917), 'riptable.Cat', 'rt.Cat', (['[0, 0, 1, 1]', "['a', 'a']"], {'base_index': '(0)'}), "([0, 0, 1, 1], ['a', 'a'], base_index=0)\n", (127877, 127917), True, 'import riptable as rt\n'), ((127919, 127960), 'riptable.Cat', 'rt.Cat', (['[0, 0, 0, 0]', "['a']"], {'base_index': '(0)'}), "([0, 0, 0, 0], ['a'], base_index=0)\n", (127925, 127960), True, 'import riptable as rt\n'), ((127969, 128015), 'riptable.Cat', 'rt.Cat', (['[1, 1, 1, 1]', "['a', 'a']"], {'base_index': '(0)'}), "([1, 1, 1, 1], ['a', 'a'], base_index=0)\n", (127975, 128015), True, 'import riptable as rt\n'), ((128017, 128058), 'riptable.Cat', 'rt.Cat', (['[0, 0, 0, 0]', "['a']"], {'base_index': '(0)'}), "([0, 0, 0, 0], ['a'], base_index=0)\n", (128023, 128058), True, 'import riptable as rt\n'), ((128067, 128113), 'riptable.Cat', 'rt.Cat', (['[0, 0, 1, 1]', "['a', 'b']"], {'base_index': '(0)'}), "([0, 0, 1, 1], ['a', 'b'], base_index=0)\n", (128073, 128113), True, 'import riptable as rt\n'), ((128115, 128161), 'riptable.Cat', 'rt.Cat', (['[0, 0, 1, 1]', "['a', 'b']"], {'base_index': '(0)'}), "([0, 0, 1, 1], ['a', 'b'], base_index=0)\n", (128121, 128161), True, 'import riptable as rt\n'), ((128172, 128210), 'riptable.Cat', 'rt.Cat', (['[1, 1, 2, 2, 3]', '[99, 99, 101]'], {}), '([1, 1, 2, 2, 3], [99, 99, 101])\n', (128178, 128210), True, 'import riptable as rt\n'), ((128214, 128248), 'riptable.Cat', 'rt.Cat', (['[1, 1, 1, 1, 2]', '[99, 101]'], {}), '([1, 1, 1, 1, 2], [99, 101])\n', (128220, 128248), True, 'import riptable as rt\n'), ((128257, 128301), 'riptable.Cat', 'rt.Cat', (['[0, 0, 1, 1]', '[99, 99]'], {'base_index': '(0)'}), '([0, 0, 1, 1], [99, 99], base_index=0)\n', (128263, 128301), True, 'import riptable as rt\n'), ((128303, 128343), 'riptable.Cat', 'rt.Cat', (['[0, 0, 0, 0]', '[99]'], {'base_index': '(0)'}), '([0, 0, 0, 0], [99], base_index=0)\n', (128309, 128343), True, 'import riptable as rt\n'), ((128352, 128397), 'riptable.Cat', 'rt.Cat', (['[0, 0, 1, 1]', '[99, 101]'], {'base_index': '(0)'}), '([0, 0, 1, 1], [99, 101], base_index=0)\n', (128358, 128397), True, 'import riptable as rt\n'), ((128399, 128444), 'riptable.Cat', 'rt.Cat', (['[0, 0, 1, 1]', '[99, 101]'], {'base_index': '(0)'}), '([0, 0, 1, 1], [99, 101], base_index=0)\n', (128405, 128444), True, 'import riptable as rt\n'), ((128455, 128493), 'riptable.Cat', 'rt.Cat', (['[0, 0, 1, 1, 2, 2]', "['a', 'a']"], {}), "([0, 0, 1, 1, 2, 2], ['a', 'a'])\n", (128461, 128493), True, 'import riptable as rt\n'), ((128497, 128530), 'riptable.Cat', 'rt.Cat', (['[0, 0, 1, 1, 1, 1]', "['a']"], {}), "([0, 0, 1, 1, 1, 1], ['a'])\n", (128503, 128530), True, 'import riptable as rt\n'), ((128541, 128590), 'riptable.Cat', 'rt.Cat', (['[0, 0, 1, 1, 2, 2, 3, 3]', "['a', 'a', 'b']"], {}), "([0, 0, 1, 1, 2, 2, 3, 3], ['a', 'a', 'b'])\n", (128547, 128590), True, 'import riptable as rt\n'), ((128594, 128638), 'riptable.Cat', 'rt.Cat', (['[0, 0, 1, 1, 1, 1, 2, 2]', "['a', 'b']"], {}), "([0, 0, 1, 1, 1, 1, 2, 2], ['a', 'b'])\n", (128600, 128638), True, 'import riptable as rt\n'), ((2218, 2253), 'riptable.tests.utils.LikertDecision.__members__.values', 'LikertDecision.__members__.values', ([], {}), '()\n', (2251, 2253), False, 'from riptable.tests.utils import LikertDecision\n'), ((17034, 17060), 'riptable.FastArray', 'FastArray', (["['a', 'b', 'c']"], {}), "(['a', 'b', 'c'])\n", (17043, 17060), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((23203, 23227), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (23216, 23227), False, 'import pytest\n'), ((23250, 23276), 'riptable.Categorical', 'Categorical', (['arr'], {'dtype': 'dt'}), '(arr, dtype=dt)\n', (23261, 23276), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((23898, 23914), 'riptable.FastArray', 'FastArray', (['[144]'], {}), '([144])\n', (23907, 23914), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((40807, 40825), 'riptable.Categorical', 'Categorical', (["['a']"], {}), "(['a'])\n", (40818, 40825), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((40827, 40841), 'riptable.FastArray', 'FastArray', (['[1]'], {}), '([1])\n', (40836, 40841), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((40871, 40889), 'riptable.Categorical', 'Categorical', (["['b']"], {}), "(['b'])\n", (40882, 40889), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((40891, 40905), 'riptable.FastArray', 'FastArray', (['[2]'], {}), '([2])\n', (40900, 40905), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((66538, 66552), 'riptable.FastArray', 'FastArray', (['[1]'], {}), '([1])\n', (66547, 66552), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((66554, 66568), 'riptable.FastArray', 'FastArray', (['[2]'], {}), '([2])\n', (66563, 66568), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((66570, 66584), 'riptable.FastArray', 'FastArray', (['[3]'], {}), '([3])\n', (66579, 66584), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((66721, 66763), 'riptable.FastArray', 'FastArray', (['[True, True, False, True, True]'], {}), '([True, True, False, True, True])\n', (66730, 66763), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((68716, 68742), 'riptable.FastArray', 'FastArray', (["['a', 'b', 'c']"], {}), "(['a', 'b', 'c'])\n", (68725, 68742), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((68744, 68764), 'riptable.FastArray', 'FastArray', (['[1, 2, 3]'], {}), '([1, 2, 3])\n', (68753, 68764), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((71224, 71255), 'riptable.FastArray', 'FastArray', (["['a', 'b', 'c', 'a']"], {}), "(['a', 'b', 'c', 'a'])\n", (71233, 71255), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((71257, 71280), 'riptable.FastArray', 'FastArray', (['[1, 2, 3, 1]'], {}), '([1, 2, 3, 1])\n', (71266, 71280), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((71745, 71768), 'riptable.FastArray', 'FastArray', (['[1, 2, 3, 1]'], {}), '([1, 2, 3, 1])\n', (71754, 71768), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((72297, 72307), 'riptable.rt_numpy.arange', 'arange', (['(10)'], {}), '(10)\n', (72303, 72307), False, 'from riptable.rt_numpy import isnan, isnotnan, arange, ones\n'), ((73806, 73831), 'riptable.rt_numpy.arange', 'arange', (['(5)'], {'dtype': 'np.int32'}), '(5, dtype=np.int32)\n', (73812, 73831), False, 'from riptable.rt_numpy import isnan, isnotnan, arange, ones\n'), ((73833, 73858), 'riptable.rt_numpy.arange', 'arange', (['(5)'], {'dtype': 'np.int32'}), '(5, dtype=np.int32)\n', (73839, 73858), False, 'from riptable.rt_numpy import isnan, isnotnan, arange, ones\n'), ((73925, 73950), 'riptable.rt_numpy.arange', 'arange', (['(5)'], {'dtype': 'np.int64'}), '(5, dtype=np.int64)\n', (73931, 73950), False, 'from riptable.rt_numpy import isnan, isnotnan, arange, ones\n'), ((73952, 73977), 'riptable.rt_numpy.arange', 'arange', (['(5)'], {'dtype': 'np.int64'}), '(5, dtype=np.int64)\n', (73958, 73977), False, 'from riptable.rt_numpy import isnan, isnotnan, arange, ones\n'), ((75461, 75492), 'riptable.FastArray', 'FastArray', (["['a', 'b', 'c', 'a']"], {}), "(['a', 'b', 'c', 'a'])\n", (75470, 75492), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((75494, 75517), 'riptable.FastArray', 'FastArray', (['[1, 2, 3, 1]'], {}), '([1, 2, 3, 1])\n', (75503, 75517), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((76003, 76025), 'riptable.rt_numpy.isnan', 'isnan', (['multi_expand[1]'], {}), '(multi_expand[1])\n', (76008, 76025), False, 'from riptable.rt_numpy import isnan, isnotnan, arange, ones\n'), ((77700, 77744), 'riptable.FastArray', 'FastArray', (['[False, False, True, True, False]'], {}), '([False, False, True, True, False])\n', (77709, 77744), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((78083, 78120), 'riptable.FastArray', 'FastArray', (['[False, False, True, True]'], {}), '([False, False, True, True])\n', (78092, 78120), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((80725, 80734), 'riptable.rt_numpy.arange', 'arange', (['(5)'], {}), '(5)\n', (80731, 80734), False, 'from riptable.rt_numpy import isnan, isnotnan, arange, ones\n'), ((80736, 80745), 'riptable.rt_numpy.arange', 'arange', (['(5)'], {}), '(5)\n', (80742, 80745), False, 'from riptable.rt_numpy import isnan, isnotnan, arange, ones\n'), ((81932, 81941), 'riptable.rt_numpy.arange', 'arange', (['(3)'], {}), '(3)\n', (81938, 81941), False, 'from riptable.rt_numpy import isnan, isnotnan, arange, ones\n'), ((100134, 100151), 'riptable.Categorical', 'Categorical', (['data'], {}), '(data)\n', (100145, 100151), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((101077, 101094), 'riptable.Categorical', 'Categorical', (['data'], {}), '(data)\n', (101088, 101094), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((104046, 104164), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['shift_cat._fa[i:]', 'categorical._fa[:-i]', 'f"""FastArray items should be shifted by {i} postions."""'], {}), "(shift_cat._fa[i:], categorical._fa[:-i],\n f'FastArray items should be shifted by {i} postions.')\n", (104064, 104164), False, 'from numpy.testing import assert_array_equal\n'), ((104470, 104590), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['shift_cat_values[i:]', 'cat_values[:-i]', 'f"""Categorical values should be shifted by {i} positions."""'], {}), "(shift_cat_values[i:], cat_values[:-i],\n f'Categorical values should be shifted by {i} positions.')\n", (104488, 104590), False, 'from numpy.testing import assert_array_equal\n'), ((102558, 102575), 'riptable.Categorical', 'Categorical', (['data'], {}), '(data)\n', (102569, 102575), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((111222, 111322), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['arr', 'expected_category_array', 'f"""Category dictionary values should be empty."""'], {}), "(arr, expected_category_array,\n f'Category dictionary values should be empty.')\n", (111240, 111322), False, 'from numpy.testing import assert_array_equal\n'), ((112658, 112784), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['arr', 'expected_category_array', 'f"""Category dictionary values should only contain the \'{misc}\' category."""'], {}), '(arr, expected_category_array,\n f"Category dictionary values should only contain the \'{misc}\' category.")\n', (112676, 112784), False, 'from numpy.testing import assert_array_equal\n'), ((113698, 113735), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['arr', 'expected_arr'], {}), '(arr, expected_arr)\n', (113716, 113735), False, 'from numpy.testing import assert_array_equal\n'), ((109339, 109356), 'riptable.Categorical', 'Categorical', (['data'], {}), '(data)\n', (109350, 109356), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((114378, 114395), 'riptable.Categorical', 'Categorical', (['data'], {}), '(data)\n', (114389, 114395), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((117008, 117025), 'riptable.Categorical', 'Categorical', (['data'], {}), '(data)\n', (117019, 117025), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((117179, 117210), 'riptable.Categorical', 'Categorical', (['data'], {'base_index': '(0)'}), '(data, base_index=0)\n', (117190, 117210), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((119061, 119078), 'riptable.Categorical', 'Categorical', (['data'], {}), '(data)\n', (119072, 119078), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((119263, 119280), 'riptable.Categorical', 'Categorical', (['data'], {}), '(data)\n', (119274, 119280), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((8470, 8495), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (8483, 8495), False, 'import pytest\n'), ((8524, 8541), 'riptable.Categorical', 'Categorical', (['v', 'c'], {}), '(v, c)\n', (8535, 8541), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((13923, 13948), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (13936, 13948), False, 'import pytest\n'), ((40234, 40300), 'riptable.FastArray', 'FastArray', (["[b'Filtered', b'a', b'b', b'c', b'd', b'e', b'f', b'z']"], {}), "([b'Filtered', b'a', b'b', b'c', b'd', b'e', b'f', b'z'])\n", (40243, 40300), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((59839, 59847), 'riptable.rt_numpy.isnan', 'isnan', (['c'], {}), '(c)\n', (59844, 59847), False, 'from riptable.rt_numpy import isnan, isnotnan, arange, ones\n'), ((59950, 59961), 'riptable.rt_numpy.isnotnan', 'isnotnan', (['c'], {}), '(c)\n', (59958, 59961), False, 'from riptable.rt_numpy import isnan, isnotnan, arange, ones\n'), ((70319, 70350), 'riptable.FastArray', 'FastArray', (["['a', 'b', 'c', 'a']"], {}), "(['a', 'b', 'c', 'a'])\n", (70328, 70350), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((70352, 70375), 'riptable.FastArray', 'FastArray', (['[1, 2, 3, 1]'], {}), '([1, 2, 3, 1])\n', (70361, 70375), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((70396, 70422), 'riptable.FastArray', 'FastArray', (["['a', 'b', 'c']"], {}), "(['a', 'b', 'c'])\n", (70405, 70422), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((70424, 70444), 'riptable.FastArray', 'FastArray', (['[1, 2, 3]'], {}), '([1, 2, 3])\n', (70433, 70444), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((71964, 72001), 'riptable.FastArray', 'FastArray', (['[True, False, False, True]'], {}), '([True, False, False, True])\n', (71973, 72001), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((75106, 75118), 'riptable.rt_numpy.arange', 'arange', (['(1)', '(4)'], {}), '(1, 4)\n', (75112, 75118), False, 'from riptable.rt_numpy import isnan, isnotnan, arange, ones\n'), ((75418, 75430), 'riptable.rt_numpy.arange', 'arange', (['(1)', '(4)'], {}), '(1, 4)\n', (75424, 75430), False, 'from riptable.rt_numpy import isnan, isnotnan, arange, ones\n'), ((75786, 75817), 'riptable.FastArray', 'FastArray', (["['a', 'b', 'c', 'a']"], {}), "(['a', 'b', 'c', 'a'])\n", (75795, 75817), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((75867, 75890), 'riptable.FastArray', 'FastArray', (['[1, 2, 3, 1]'], {}), '([1, 2, 3, 1])\n', (75876, 75890), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((78614, 78651), 'riptable.FastArray', 'FastArray', (['[False, False, True, True]'], {}), '([False, False, True, True])\n', (78623, 78651), False, 'from riptable import FastArray, Categorical, CatZero\n'), ((78905, 78917), 'riptable.rt_numpy.arange', 'arange', (['(1)', '(4)'], {}), '(1, 4)\n', (78911, 78917), False, 'from riptable.rt_numpy import isnan, isnotnan, arange, ones\n'), ((100181, 100276), 'riptable.tests.test_utils.get_categorical_data_factory_method', 'get_categorical_data_factory_method', (['[CategoryMode.StringArray, CategoryMode.NumericArray]'], {}), '([CategoryMode.StringArray, CategoryMode\n .NumericArray])\n', (100216, 100276), False, 'from riptable.tests.test_utils import get_categorical_data_factory_method, get_all_categorical_data\n'), ((100504, 100599), 'riptable.tests.test_utils.get_categorical_data_factory_method', 'get_categorical_data_factory_method', (['[CategoryMode.StringArray, CategoryMode.NumericArray]'], {}), '([CategoryMode.StringArray, CategoryMode\n .NumericArray])\n', (100539, 100599), False, 'from riptable.tests.test_utils import get_categorical_data_factory_method, get_all_categorical_data\n'), ((100795, 100813), 'riptable.FastArray', 'rt.FastArray', (['data'], {}), '(data)\n', (100807, 100813), True, 'import riptable as rt\n'), ((100844, 100939), 'riptable.tests.test_utils.get_categorical_data_factory_method', 'get_categorical_data_factory_method', (['[CategoryMode.StringArray, CategoryMode.NumericArray]'], {}), '([CategoryMode.StringArray, CategoryMode\n .NumericArray])\n', (100879, 100939), False, 'from riptable.tests.test_utils import get_categorical_data_factory_method, get_all_categorical_data\n'), ((101107, 101165), 'riptable.tests.test_utils.get_categorical_data_factory_method', 'get_categorical_data_factory_method', (['CategoryMode.MultiKey'], {}), '(CategoryMode.MultiKey)\n', (101142, 101165), False, 'from riptable.tests.test_utils import get_categorical_data_factory_method, get_all_categorical_data\n'), ((101206, 101358), 'pytest.mark.xfail', 'pytest.mark.xfail', ([], {'reason': '"""RIP-410 - Bug for MultiKey Categoricals: AttributeError: \'Categorical\' object has no attribute \'ismultikey_labels\'"""'}), '(reason=\n "RIP-410 - Bug for MultiKey Categoricals: AttributeError: \'Categorical\' object has no attribute \'ismultikey_labels\'"\n )\n', (101223, 101358), False, 'import pytest\n'), ((105580, 105708), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['shift_cat._fa[:cat_len - i]', 'categorical._fa[i:]', 'f"""FastArray items should be shifted by -{i} postions."""'], {}), "(shift_cat._fa[:cat_len - i], categorical._fa[i:],\n f'FastArray items should be shifted by -{i} postions.')\n", (105598, 105708), False, 'from numpy.testing import assert_array_equal\n'), ((105967, 106097), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['shift_cat_values[:cat_len - i]', 'cat_values[i:]', 'f"""Categorical values should be shifted by -{i} positions."""'], {}), "(shift_cat_values[:cat_len - i], cat_values[i:],\n f'Categorical values should be shifted by -{i} positions.')\n", (105985, 106097), False, 'from numpy.testing import assert_array_equal\n'), ((102588, 102651), 'riptable.tests.test_utils.get_categorical_data_factory_method', 'get_categorical_data_factory_method', (['[CategoryMode.StringArray]'], {}), '([CategoryMode.StringArray])\n', (102623, 102651), False, 'from riptable.tests.test_utils import get_categorical_data_factory_method, get_all_categorical_data\n'), ((102835, 102898), 'riptable.tests.test_utils.get_categorical_data_factory_method', 'get_categorical_data_factory_method', (['[CategoryMode.StringArray]'], {}), '([CategoryMode.StringArray])\n', (102870, 102898), False, 'from riptable.tests.test_utils import get_categorical_data_factory_method, get_all_categorical_data\n'), ((103085, 103103), 'riptable.FastArray', 'rt.FastArray', (['data'], {}), '(data)\n', (103097, 103103), True, 'import riptable as rt\n'), ((103134, 103197), 'riptable.tests.test_utils.get_categorical_data_factory_method', 'get_categorical_data_factory_method', (['[CategoryMode.StringArray]'], {}), '([CategoryMode.StringArray])\n', (103169, 103197), False, 'from riptable.tests.test_utils import get_categorical_data_factory_method, get_all_categorical_data\n'), ((109369, 109432), 'riptable.tests.test_utils.get_categorical_data_factory_method', 'get_categorical_data_factory_method', (['[CategoryMode.StringArray]'], {}), '([CategoryMode.StringArray])\n', (109404, 109432), False, 'from riptable.tests.test_utils import get_categorical_data_factory_method, get_all_categorical_data\n'), ((109616, 109679), 'riptable.tests.test_utils.get_categorical_data_factory_method', 'get_categorical_data_factory_method', (['[CategoryMode.StringArray]'], {}), '([CategoryMode.StringArray])\n', (109651, 109679), False, 'from riptable.tests.test_utils import get_categorical_data_factory_method, get_all_categorical_data\n'), ((109866, 109884), 'riptable.FastArray', 'rt.FastArray', (['data'], {}), '(data)\n', (109878, 109884), True, 'import riptable as rt\n'), ((109915, 109978), 'riptable.tests.test_utils.get_categorical_data_factory_method', 'get_categorical_data_factory_method', (['[CategoryMode.StringArray]'], {}), '([CategoryMode.StringArray])\n', (109950, 109978), False, 'from riptable.tests.test_utils import get_categorical_data_factory_method, get_all_categorical_data\n'), ((114408, 114445), 'riptable.tests.test_utils.get_categorical_data_factory_method', 'get_categorical_data_factory_method', ([], {}), '()\n', (114443, 114445), False, 'from riptable.tests.test_utils import get_categorical_data_factory_method, get_all_categorical_data\n'), ((114641, 114736), 'riptable.tests.test_utils.get_categorical_data_factory_method', 'get_categorical_data_factory_method', (['[CategoryMode.StringArray, CategoryMode.NumericArray]'], {}), '([CategoryMode.StringArray, CategoryMode\n .NumericArray])\n', (114676, 114736), False, 'from riptable.tests.test_utils import get_categorical_data_factory_method, get_all_categorical_data\n'), ((114932, 114950), 'riptable.FastArray', 'rt.FastArray', (['data'], {}), '(data)\n', (114944, 114950), True, 'import riptable as rt\n'), ((114981, 115076), 'riptable.tests.test_utils.get_categorical_data_factory_method', 'get_categorical_data_factory_method', (['[CategoryMode.StringArray, CategoryMode.NumericArray]'], {}), '([CategoryMode.StringArray, CategoryMode\n .NumericArray])\n', (115016, 115076), False, 'from riptable.tests.test_utils import get_categorical_data_factory_method, get_all_categorical_data\n'), ((117051, 117146), 'riptable.tests.test_utils.get_categorical_data_factory_method', 'get_categorical_data_factory_method', (['[CategoryMode.StringArray, CategoryMode.NumericArray]'], {}), '([CategoryMode.StringArray, CategoryMode\n .NumericArray])\n', (117086, 117146), False, 'from riptable.tests.test_utils import get_categorical_data_factory_method, get_all_categorical_data\n'), ((117236, 117331), 'riptable.tests.test_utils.get_categorical_data_factory_method', 'get_categorical_data_factory_method', (['[CategoryMode.StringArray, CategoryMode.NumericArray]'], {}), '([CategoryMode.StringArray, CategoryMode\n .NumericArray])\n', (117271, 117331), False, 'from riptable.tests.test_utils import get_categorical_data_factory_method, get_all_categorical_data\n'), ((119108, 119203), 'riptable.tests.test_utils.get_categorical_data_factory_method', 'get_categorical_data_factory_method', (['[CategoryMode.StringArray, CategoryMode.NumericArray]'], {}), '([CategoryMode.StringArray, CategoryMode\n .NumericArray])\n', (119143, 119203), False, 'from riptable.tests.test_utils import get_categorical_data_factory_method, get_all_categorical_data\n'), ((119293, 119351), 'riptable.tests.test_utils.get_categorical_data_factory_method', 'get_categorical_data_factory_method', (['CategoryMode.MultiKey'], {}), '(CategoryMode.MultiKey)\n', (119328, 119351), False, 'from riptable.tests.test_utils import get_categorical_data_factory_method, get_all_categorical_data\n'), ((119392, 119505), 'pytest.mark.xfail', 'pytest.mark.xfail', ([], {'reason': '"""NotImplementedError: Add categories not supported for MultiKey Categoricals"""'}), "(reason=\n 'NotImplementedError: Add categories not supported for MultiKey Categoricals'\n )\n", (119409, 119505), False, 'import pytest\n'), ((106789, 106861), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['shift_cat.category_array', 'categorical.category_array'], {}), '(shift_cat.category_array, categorical.category_array)\n', (106807, 106861), False, 'from numpy.testing import assert_array_equal\n'), ((106879, 106929), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['shift_cat._fa', 'categorical._fa'], {}), '(shift_cat._fa, categorical._fa)\n', (106897, 106929), False, 'from numpy.testing import assert_array_equal\n'), ((107108, 107156), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['shift_cat_values', 'cat_values'], {}), '(shift_cat_values, cat_values)\n', (107126, 107156), False, 'from numpy.testing import assert_array_equal\n')]
import numpy as np from scipy import io, sparse, linalg # run this from elegant scipy chapter chem = np.load('chem-network.npy') gap = np.load('gap-network.npy') neuron_types = np.load('neuron-types.npy') neuron_ids = np.load('neurons.npy') A = chem + gap n = A.shape[0] c = (A + A.T) / 2 d = sparse.diags([np.sum(c, axis=0)], [0]) d = d.toarray() L = np.array(d - c) b = np.sum(c * np.sign(A - A.T), axis=1) z = np.linalg.pinv(L) @ b # IPython log file dinv2 = np.copy(d) diag = (np.arange(n), np.arange(n)) dinv2[diag] = dinv[diag] ** (-.5) q = dinv2 @ L @ dinv2 eigvals, vec = linalg.eig(q) x = dinv2 @ vec[:, 1] x.shape from matplotlib import pyplot as plt from matplotlib import colors ii, jj = np.nonzero(c) plt.scatter(x, z, c=neuron_types, cmap=colors.ListedColormap(((1, 0, 0), (0, 1, 0), (0, 0, 1))), zorder=1) for src, dst in zip(ii, jj): plt.plot(x[[src, dst]], z[[src, dst]], c=(0.85, 0.85, 0.85), lw=0.2, alpha=0.5, zorder=0) for x0, z0, neuron_id in zip(x, z, neuron_ids): plt.text(x0, z0, ' ' + neuron_id, horizontalalignment='left', verticalalignment='center', fontsize=4, zorder=2)
[ "numpy.load", "numpy.sum", "numpy.copy", "matplotlib.pyplot.plot", "scipy.linalg.eig", "numpy.nonzero", "matplotlib.pyplot.text", "numpy.array", "numpy.arange", "numpy.sign", "numpy.linalg.pinv", "matplotlib.colors.ListedColormap" ]
[((102, 129), 'numpy.load', 'np.load', (['"""chem-network.npy"""'], {}), "('chem-network.npy')\n", (109, 129), True, 'import numpy as np\n'), ((136, 162), 'numpy.load', 'np.load', (['"""gap-network.npy"""'], {}), "('gap-network.npy')\n", (143, 162), True, 'import numpy as np\n'), ((178, 205), 'numpy.load', 'np.load', (['"""neuron-types.npy"""'], {}), "('neuron-types.npy')\n", (185, 205), True, 'import numpy as np\n'), ((219, 241), 'numpy.load', 'np.load', (['"""neurons.npy"""'], {}), "('neurons.npy')\n", (226, 241), True, 'import numpy as np\n'), ((353, 368), 'numpy.array', 'np.array', (['(d - c)'], {}), '(d - c)\n', (361, 368), True, 'import numpy as np\n'), ((463, 473), 'numpy.copy', 'np.copy', (['d'], {}), '(d)\n', (470, 473), True, 'import numpy as np\n'), ((581, 594), 'scipy.linalg.eig', 'linalg.eig', (['q'], {}), '(q)\n', (591, 594), False, 'from scipy import io, sparse, linalg\n'), ((701, 714), 'numpy.nonzero', 'np.nonzero', (['c'], {}), '(c)\n', (711, 714), True, 'import numpy as np\n'), ((414, 431), 'numpy.linalg.pinv', 'np.linalg.pinv', (['L'], {}), '(L)\n', (428, 431), True, 'import numpy as np\n'), ((482, 494), 'numpy.arange', 'np.arange', (['n'], {}), '(n)\n', (491, 494), True, 'import numpy as np\n'), ((496, 508), 'numpy.arange', 'np.arange', (['n'], {}), '(n)\n', (505, 508), True, 'import numpy as np\n'), ((855, 949), 'matplotlib.pyplot.plot', 'plt.plot', (['x[[src, dst]]', 'z[[src, dst]]'], {'c': '(0.85, 0.85, 0.85)', 'lw': '(0.2)', 'alpha': '(0.5)', 'zorder': '(0)'}), '(x[[src, dst]], z[[src, dst]], c=(0.85, 0.85, 0.85), lw=0.2, alpha=\n 0.5, zorder=0)\n', (863, 949), True, 'from matplotlib import pyplot as plt\n'), ((997, 1113), 'matplotlib.pyplot.text', 'plt.text', (['x0', 'z0', "(' ' + neuron_id)"], {'horizontalalignment': '"""left"""', 'verticalalignment': '"""center"""', 'fontsize': '(4)', 'zorder': '(2)'}), "(x0, z0, ' ' + neuron_id, horizontalalignment='left',\n verticalalignment='center', fontsize=4, zorder=2)\n", (1005, 1113), True, 'from matplotlib import pyplot as plt\n'), ((308, 325), 'numpy.sum', 'np.sum', (['c'], {'axis': '(0)'}), '(c, axis=0)\n', (314, 325), True, 'import numpy as np\n'), ((384, 400), 'numpy.sign', 'np.sign', (['(A - A.T)'], {}), '(A - A.T)\n', (391, 400), True, 'import numpy as np\n'), ((754, 810), 'matplotlib.colors.ListedColormap', 'colors.ListedColormap', (['((1, 0, 0), (0, 1, 0), (0, 0, 1))'], {}), '(((1, 0, 0), (0, 1, 0), (0, 0, 1)))\n', (775, 810), False, 'from matplotlib import colors\n')]
''' Define the operations used to denoise the image. ''' import cv2 import numpy as np def denoise(frame, useMorphOps = True, useGaussianBlur = True): if useMorphOps: kernel = np.ones((5,5),np.uint8) frame = cv2.morphologyEx(frame, cv2.MORPH_OPEN, kernel) frame = cv2.morphologyEx(frame, cv2.MORPH_CLOSE, kernel) if useGaussianBlur: frame = cv2.GaussianBlur(frame, (5, 5), 0) return frame
[ "cv2.morphologyEx", "numpy.ones", "cv2.GaussianBlur" ]
[((189, 214), 'numpy.ones', 'np.ones', (['(5, 5)', 'np.uint8'], {}), '((5, 5), np.uint8)\n', (196, 214), True, 'import numpy as np\n'), ((229, 276), 'cv2.morphologyEx', 'cv2.morphologyEx', (['frame', 'cv2.MORPH_OPEN', 'kernel'], {}), '(frame, cv2.MORPH_OPEN, kernel)\n', (245, 276), False, 'import cv2\n'), ((293, 341), 'cv2.morphologyEx', 'cv2.morphologyEx', (['frame', 'cv2.MORPH_CLOSE', 'kernel'], {}), '(frame, cv2.MORPH_CLOSE, kernel)\n', (309, 341), False, 'import cv2\n'), ((382, 416), 'cv2.GaussianBlur', 'cv2.GaussianBlur', (['frame', '(5, 5)', '(0)'], {}), '(frame, (5, 5), 0)\n', (398, 416), False, 'import cv2\n')]
""" ###################### EDGE ####################""" import numpy as np from collections import defaultdict class vertex: def __init__(self, type, node, id): """ :param node: """ self.id = id self.Type = type self.Cells = node self.Trains = [] self.TrainsDir = [] # 0 = A->B, 1 = B->A self.Links = [] self.TrainsTraversal = defaultdict(list) self.is_signal_on = False self.is_starting_edge = False self.is_safe = True self.occupancy = 0 self.extended_capacity = len(node) self.capacity = len(node) def __str__(self): """ :return: """ return 'Type : ' + str(self.Type) \ + '; Trains: ' + str(self.Trains) \ + '; Safety Status: ' + str(self.is_safe) def other_end(self, first): return self.Cells[0] if self.Cells[-1] == first else self.Cells[-1] def setCosts(self): """ :return: """ #self.setCollision() #self.CostCollisionLockTotal = 0 #self.CostTransitionTimeTotal = 0 #self.CostDeadLockTotal = 0 #self.CostTotal = 0 #self.CostPerTrain = [] #self.DeadlockCostPerTrain = [] #if self.signal_time > 1: # self.signal_time -= 1 #elif self.signal_time == 1: # self.signal_time -= 1 # self.signal_deadlocks = [] #start_times = [item[0] for item in self.TrainsTime] agent_dirs = np.unique(self.TrainsDir) if self.is_starting_edge: self.is_safe = True else: self.is_safe = True if len(agent_dirs) <= 1 else False #self.is_safe = True if len(np.unique(self.TrainsDir)) <= 1 else False def setExtendedCapacity(self): """ :return: """ if self.is_safe: pending_to_explore = [] explored = [] explored.append(self.id) for vertex in self.Links: if vertex[1].is_safe: pending_to_explore.append(vertex[1]) capacity = 0 while len(pending_to_explore): vertex = pending_to_explore.pop() explored.append(vertex.id) capacity += len(vertex.Cells) for next_vertex in vertex.Links: if next_vertex[1].is_safe and next_vertex[1].id not in explored: pending_to_explore.append(next_vertex[1]) self.extended_capacity = capacity if self.extended_capacity > 2*self.capacity: self.extended_capacity = 2*self.capacity class Global_Graph: def __init__(self): """ """ self.vertices = {} self.num_vertices = 0 #self.Deadlocks = [] #self.LastUpdated = 0 #self.CostTotalEnv = 0 def __str__(self): """ :return: """ return 'Cost: ' + str(self.CostTotalEnv) + ' Deadlocks: ' + str(self.Deadlocks) def setCosts(self): """ :return: """ #cost = 0 for vertex in self.vertices: if len(self.vertices[vertex].Trains): self.vertices[vertex].setCosts() #cost += self.vertices[vertex].CostTotal #for vertex in self.vertices: # if len(self.vertices[vertex].Trains): # self.vertices[vertex].setExtendedCapacity() #self.CostTotalEnv = cost def add_edge_vertex(self, type, cells): """ :param node: :return: """ if str(cells[0])[1:-1]+","+str(cells[-1])[1:-1] not in self.vertices\ and str(cells[-1])[1:-1]+","+str(cells[0])[1:-1] not in self.vertices: new_edge_vertex = vertex(type, cells, str(cells[0])[1:-1]+","+str(cells[-1])[1:-1]) self.vertices[str(cells[0])[1:-1]+","+str(cells[-1])[1:-1]] = new_edge_vertex self.num_vertices += 1 return new_edge_vertex elif str(cells[0])[1:-1]+","+str(cells[-1])[1:-1] in self.vertices: return self.vertices[str(cells[0])[1:-1]+","+str(cells[-1])[1:-1]] elif str(cells[-1])[1:-1]+","+str(cells[0])[1:-1] in self.vertices: return self.vertices[str(cells[-1])[1:-1]+","+str(cells[0])[1:-1]] def add_signal_vertex(self, type, node): """ :param node: :return: """ if str(node)[1:-1] not in self.vertices: new_vertex = vertex(type, [node], str(node)[1:-1]) self.vertices[str(node)[1:-1]] = new_vertex self.num_vertices = self.num_vertices + 1 return new_vertex return self.vertices[str(node)[1:-1]] if __name__ == "__main__": # create a graph of 4 nodes # # if a node is added - only node list is updated # call graph insert method # if an edge is added - possibly two nodes will be added g = Global_Graph() g.add_vertex('a') g.add_edge('a','b') g.add_edge('a','c') g.add_edge('b','c') g.add_edge('b','d') g.add_edge('c','d') source_vert = g.vert_dict['a'] for edge in g.vert_dict['a'].edges: if edge.end == 'c': edge.cost_triples.append([1,2,3]) #print("found") #edge_temp = g.edge_dict['ab'] #edge_temp.cost_triples.append([1,2,3]) #g.add_vertex('b') #g.add_vertex('c') #g.add_vertex('d') #g.add_vertex('e') #print("done")
[ "collections.defaultdict", "numpy.unique" ]
[((417, 434), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (428, 434), False, 'from collections import defaultdict\n'), ((1552, 1577), 'numpy.unique', 'np.unique', (['self.TrainsDir'], {}), '(self.TrainsDir)\n', (1561, 1577), True, 'import numpy as np\n')]
import numpy as np from matplotlib import pyplot as plt, gridspec as gridspec import seaborn as sns import matplotlib as mpl import matplotlib.cm as cm from rl_agents.utils import remap, constrain class DQNGraphics(object): """ Graphical visualization of the DQNAgent state-action values. """ RED = (255, 0, 0) BLACK = (0, 0, 0) MIN_ATTENTION = 0.01 @classmethod def display(cls, agent, surface, sim_surface=None, display_text=True): """ Display the action-values for the current state :param agent: the DQNAgent to be displayed :param surface: the pygame surface on which the agent is displayed :param sim_surface: the pygame surface on which the env is rendered :param display_text: whether to display the action values as text """ import pygame action_values = agent.get_state_action_values(agent.previous_state) action_distribution = agent.action_distribution(agent.previous_state) cell_size = (surface.get_width() // len(action_values), surface.get_height()) pygame.draw.rect(surface, cls.BLACK, (0, 0, surface.get_width(), surface.get_height()), 0) # Display node value for action, value in enumerate(action_values): cmap = cm.jet_r norm = mpl.colors.Normalize(vmin=0, vmax=1/(1-agent.config["gamma"])) color = cmap(norm(value), bytes=True) pygame.draw.rect(surface, color, (cell_size[0]*action, 0, cell_size[0], cell_size[1]), 0) if display_text: font = pygame.font.Font(None, 15) text = "v={:.2f} / p={:.2f}".format(value, action_distribution[action]) text = font.render(text, 1, (10, 10, 10), (255, 255, 255)) surface.blit(text, (cell_size[0]*action, 0)) if sim_surface and hasattr(agent.value_net, "get_attention_matrix"): cls.display_vehicles_attention(agent, sim_surface) @classmethod def display_vehicles_attention(cls, agent, sim_surface): import pygame try: state = agent.previous_state if (not hasattr(cls, "state")) or (cls.state != state).any(): cls.v_attention = cls.compute_vehicles_attention(agent, state) cls.state = state for head in range(list(cls.v_attention.values())[0].shape[0]): attention_surface = pygame.Surface(sim_surface.get_size(), pygame.SRCALPHA) for vehicle, attention in cls.v_attention.items(): if attention[head] < cls.MIN_ATTENTION: continue width = attention[head] * 5 desat = remap(attention[head], (0, 0.5), (0.7, 1), clip=True) colors = sns.color_palette("dark", desat=desat) color = np.array(colors[(2*head) % (len(colors) - 1)]) * 255 color = (*color, remap(attention[head], (0, 0.5), (100, 200), clip=True)) if vehicle is agent.env.vehicle: pygame.draw.circle(attention_surface, color, sim_surface.vec2pix(agent.env.vehicle.position), max(sim_surface.pix(width / 2), 1)) else: pygame.draw.line(attention_surface, color, sim_surface.vec2pix(agent.env.vehicle.position), sim_surface.vec2pix(vehicle.position), max(sim_surface.pix(width), 1)) sim_surface.blit(attention_surface, (0, 0)) except ValueError as e: print("Unable to display vehicles attention", e) @classmethod def compute_vehicles_attention(cls, agent, state): import torch state_t = torch.tensor([state], dtype=torch.float).to(agent.device) attention = agent.value_net.get_attention_matrix(state_t).squeeze(0).squeeze(1).detach().cpu().numpy() ego, others, mask = agent.value_net.split_input(state_t) mask = mask.squeeze() v_attention = {} for v_index in range(state.shape[0]): if mask[v_index]: continue v_position = {} for feature in ["x", "y"]: v_feature = state[v_index, agent.env.observation_type.features.index(feature)] v_feature = remap(v_feature, [-1, 1], agent.env.observation_type.features_range[feature]) v_position[feature] = v_feature v_position = np.array([v_position["x"], v_position["y"]]) if not agent.env.observation_type.absolute and v_index > 0: v_position += agent.env.unwrapped.vehicle.position vehicle = min(agent.env.road.vehicles, key=lambda v: np.linalg.norm(v.position - v_position)) v_attention[vehicle] = attention[:, v_index] return v_attention class ValueFunctionViewer(object): def __init__(self, agent, state_sampler): self.agent = agent self.state_sampler = state_sampler self.values_history = np.array([]) self.figure = None self.axes = [] def display(self): if not self.state_sampler: return if not self.figure: plt.ion() self.figure = plt.figure('Value function') gs = gridspec.GridSpec(2, 2) self.axes.append(plt.subplot(gs[0, :])) self.axes.append(plt.subplot(gs[1, 0])) self.axes.append(plt.subplot(gs[1, 1])) xx, _, _ = self.state_sampler.states_mesh() cax1 = self.axes[1].imshow(xx) cax2 = self.axes[2].imshow(xx) self.figure.colorbar(cax1, ax=self.axes[1]) self.figure.colorbar(cax2, ax=self.axes[2]) self.plot_values() self.plot_value_map() def plot_value_map(self): xx, yy, states = self.state_sampler.states_mesh() values, actions = self.agent.get_batch_state_values(states) values, actions = np.reshape(values, np.shape(xx)), np.reshape(actions, np.shape(xx)) self.axes[1].clear() self.axes[2].clear() self.axes[1].imshow(values) self.axes[2].imshow(actions) plt.pause(0.001) plt.draw() def plot_values(self): states = self.state_sampler.states_list() values, _ = self.agent.get_batch_state_values(states) self.values_history = np.vstack((self.values_history, values)) if self.values_history.size else values self.axes[0].clear() self.axes[0].set_xlabel('Episode') self.axes[0].set_ylabel('Value') self.axes[0].plot(self.values_history) plt.pause(0.001) plt.draw()
[ "matplotlib.pyplot.subplot", "torch.tensor", "matplotlib.colors.Normalize", "pygame.draw.rect", "matplotlib.pyplot.draw", "matplotlib.pyplot.ion", "matplotlib.pyplot.figure", "rl_agents.utils.remap", "numpy.array", "numpy.shape", "seaborn.color_palette", "pygame.font.Font", "numpy.linalg.nor...
[((5249, 5261), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (5257, 5261), True, 'import numpy as np\n'), ((6396, 6412), 'matplotlib.pyplot.pause', 'plt.pause', (['(0.001)'], {}), '(0.001)\n', (6405, 6412), True, 'from matplotlib import pyplot as plt, gridspec as gridspec\n'), ((6421, 6431), 'matplotlib.pyplot.draw', 'plt.draw', ([], {}), '()\n', (6429, 6431), True, 'from matplotlib import pyplot as plt, gridspec as gridspec\n'), ((6852, 6868), 'matplotlib.pyplot.pause', 'plt.pause', (['(0.001)'], {}), '(0.001)\n', (6861, 6868), True, 'from matplotlib import pyplot as plt, gridspec as gridspec\n'), ((6877, 6887), 'matplotlib.pyplot.draw', 'plt.draw', ([], {}), '()\n', (6885, 6887), True, 'from matplotlib import pyplot as plt, gridspec as gridspec\n'), ((1329, 1395), 'matplotlib.colors.Normalize', 'mpl.colors.Normalize', ([], {'vmin': '(0)', 'vmax': "(1 / (1 - agent.config['gamma']))"}), "(vmin=0, vmax=1 / (1 - agent.config['gamma']))\n", (1349, 1395), True, 'import matplotlib as mpl\n'), ((1454, 1549), 'pygame.draw.rect', 'pygame.draw.rect', (['surface', 'color', '(cell_size[0] * action, 0, cell_size[0], cell_size[1])', '(0)'], {}), '(surface, color, (cell_size[0] * action, 0, cell_size[0],\n cell_size[1]), 0)\n', (1470, 1549), False, 'import pygame\n'), ((4692, 4736), 'numpy.array', 'np.array', (["[v_position['x'], v_position['y']]"], {}), "([v_position['x'], v_position['y']])\n", (4700, 4736), True, 'import numpy as np\n'), ((5430, 5439), 'matplotlib.pyplot.ion', 'plt.ion', ([], {}), '()\n', (5437, 5439), True, 'from matplotlib import pyplot as plt, gridspec as gridspec\n'), ((5466, 5494), 'matplotlib.pyplot.figure', 'plt.figure', (['"""Value function"""'], {}), "('Value function')\n", (5476, 5494), True, 'from matplotlib import pyplot as plt, gridspec as gridspec\n'), ((5512, 5535), 'matplotlib.gridspec.GridSpec', 'gridspec.GridSpec', (['(2)', '(2)'], {}), '(2, 2)\n', (5529, 5535), True, 'from matplotlib import pyplot as plt, gridspec as gridspec\n'), ((6602, 6642), 'numpy.vstack', 'np.vstack', (['(self.values_history, values)'], {}), '((self.values_history, values))\n', (6611, 6642), True, 'import numpy as np\n'), ((1597, 1623), 'pygame.font.Font', 'pygame.font.Font', (['None', '(15)'], {}), '(None, 15)\n', (1613, 1623), False, 'import pygame\n'), ((3961, 4001), 'torch.tensor', 'torch.tensor', (['[state]'], {'dtype': 'torch.float'}), '([state], dtype=torch.float)\n', (3973, 4001), False, 'import torch\n'), ((4541, 4618), 'rl_agents.utils.remap', 'remap', (['v_feature', '[-1, 1]', 'agent.env.observation_type.features_range[feature]'], {}), '(v_feature, [-1, 1], agent.env.observation_type.features_range[feature])\n', (4546, 4618), False, 'from rl_agents.utils import remap, constrain\n'), ((5565, 5586), 'matplotlib.pyplot.subplot', 'plt.subplot', (['gs[0, :]'], {}), '(gs[0, :])\n', (5576, 5586), True, 'from matplotlib import pyplot as plt, gridspec as gridspec\n'), ((5617, 5638), 'matplotlib.pyplot.subplot', 'plt.subplot', (['gs[1, 0]'], {}), '(gs[1, 0])\n', (5628, 5638), True, 'from matplotlib import pyplot as plt, gridspec as gridspec\n'), ((5669, 5690), 'matplotlib.pyplot.subplot', 'plt.subplot', (['gs[1, 1]'], {}), '(gs[1, 1])\n', (5680, 5690), True, 'from matplotlib import pyplot as plt, gridspec as gridspec\n'), ((6207, 6219), 'numpy.shape', 'np.shape', (['xx'], {}), '(xx)\n', (6215, 6219), True, 'import numpy as np\n'), ((6242, 6254), 'numpy.shape', 'np.shape', (['xx'], {}), '(xx)\n', (6250, 6254), True, 'import numpy as np\n'), ((2770, 2823), 'rl_agents.utils.remap', 'remap', (['attention[head]', '(0, 0.5)', '(0.7, 1)'], {'clip': '(True)'}), '(attention[head], (0, 0.5), (0.7, 1), clip=True)\n', (2775, 2823), False, 'from rl_agents.utils import remap, constrain\n'), ((2853, 2891), 'seaborn.color_palette', 'sns.color_palette', (['"""dark"""'], {'desat': 'desat'}), "('dark', desat=desat)\n", (2870, 2891), True, 'import seaborn as sns\n'), ((3010, 3065), 'rl_agents.utils.remap', 'remap', (['attention[head]', '(0, 0.5)', '(100, 200)'], {'clip': '(True)'}), '(attention[head], (0, 0.5), (100, 200), clip=True)\n', (3015, 3065), False, 'from rl_agents.utils import remap, constrain\n'), ((4941, 4980), 'numpy.linalg.norm', 'np.linalg.norm', (['(v.position - v_position)'], {}), '(v.position - v_position)\n', (4955, 4980), True, 'import numpy as np\n')]
import datetime as DT import numpy as NP import matplotlib.pyplot as PLT import matplotlib.colors as PLTC import scipy.constants as FCNST from astropy.io import fits from astropy.io import ascii from astropy.table import Table import progressbar as PGB import antenna_array as AA import geometry as GEOM import my_DSP_modules as DSP import sim_observe as SIM import ipdb as PDB itr = 4 # Antenna initialization lat = -26.701 # Latitude of MWA in degrees f0 = 150e6 # Center frequency antenna_file = '/data3/t_nithyanandan/project_MWA/MWA_128T_antenna_locations_MNRAS_2012_Beardsley_et_al.txt' ant_info = NP.loadtxt(antenna_file, skiprows=6, comments='#', usecols=(0,1,2,3)) ant_info[:,1] -= NP.mean(ant_info[:,1]) ant_info[:,2] -= NP.mean(ant_info[:,2]) ant_info[:,3] -= NP.mean(ant_info[:,3]) max_antenna_radius = 75.0 # in meters # max_antenna_radius = 75.0 # in meters # core_ind = NP.logical_and((NP.abs(ant_info[:,1]) < max_antenna_radius), (NP.abs(ant_info[:,2]) < max_antenna_radius)) core_ind = NP.logical_and((NP.abs(ant_info[:,1]) < max_antenna_radius), (NP.abs(ant_info[:,2]) < max_antenna_radius)) ant_info = ant_info[core_ind,:] # ant_info = ant_info[:30,:] n_antennas = ant_info.shape[0] nx = 4 # dipoles along x ny = 4 # dipoles along y dx = 1.1 # dipole spacing along x dy = 1.1 # dipole spacing along y nchan = 16 f_center = f0 channel_width = 40e3 bandwidth = nchan * channel_width dt = 1/bandwidth # ant_locs = NP.asarray([[0.0, 0.0, 0.0],[100.0, 0.0, 0.0],[50.0, 400.0, 0.0]]) # src_flux = [1.0] # skypos = NP.asarray([0.0, 0.0]).reshape(-1,2) # src_flux = [1.0, 1.0] # skypos = NP.asarray([[0.0, 0.0], [0.1, 0.0]]) src_seed = 50 NP.random.seed(src_seed) # n_src = NP.random.poisson(lam=5) n_src = 10 lmrad = NP.random.uniform(low=0.0, high=0.5, size=n_src).reshape(-1,1) lmang = NP.random.uniform(low=0.0, high=2*NP.pi, size=n_src).reshape(-1,1) skypos = NP.hstack((lmrad * NP.cos(lmang), lmrad * NP.sin(lmang))) src_flux = NP.ones(n_src) # n_src = 4 # src_flux = NP.ones(n_src) # skypos = 0.25*NP.hstack((NP.cos(2.0*NP.pi*NP.arange(n_src).reshape(-1,1)/n_src), # NP.sin(2.0*NP.pi*NP.arange(n_src).reshape(-1,1)/n_src))) # src_flux = [1.0, 1.0, 1.0, 1.0] # skypos = NP.asarray([[0.25, 0.0], [0.0, -0.25], [-0.25, 0.0], [0.0, 0.25]]) # skypos = NP.asarray([[0.0, 0.0], [0.2, 0.0], [0.0, 0.4], [0.0, -0.5]]) nvect = NP.sqrt(1.0-NP.sum(skypos**2, axis=1)).reshape(-1,1) skypos = NP.hstack((skypos,nvect)) ants = [] aar = AA.AntennaArray() for i in xrange(n_antennas): ant = AA.Antenna('{0:0d}'.format(int(ant_info[i,0])), lat, ant_info[i,1:], f0, nsamples=nchan/2) ant.f = ant.f0 + DSP.spectax(nchan, dt, shift=True) ants += [ant] aar = aar + ant iar = AA.InterferometerArray(antenna_array=aar) iar.grid() antpos_info = aar.antenna_positions(sort=True) Ef_runs = None count = 0 for i in xrange(itr): E_timeseries_dict = SIM.stochastic_E_timeseries(f_center, nchan/2, 2*channel_width, flux_ref=src_flux, skypos=skypos, antpos=antpos_info['positions'], tshift=False) timestamp = str(DT.datetime.now()) antenna_level_update_info = {} antenna_level_update_info['antenna_array'] = {} antenna_level_update_info['antenna_array']['timestamp'] = timestamp antenna_level_update_info['antennas'] = [] for label in iar.antenna_array.antennas: adict = {} adict['label'] = label adict['action'] = 'modify' adict['timestamp'] = timestamp ind = antpos_info['labels'].index(label) adict['t'] = E_timeseries_dict['t'] adict['Et'] = {} adict['flags'] = {} for pol in ['P1', 'P2']: adict['flags'][pol] = False adict['Et'][pol] = E_timeseries_dict['Et'][:,ind] # adict['Et_P1'] = E_timeseries_dict['Et'][:,ind] # adict['Et_P2'] = E_timeseries_dict['Et'][:,ind] # adict['flag_P1'] = False # adict['flag_P2'] = False antenna_level_update_info['antennas'] += [adict] interferometer_level_update_info = {} interferometer_level_update_info['interferometers'] = [] for label in iar.interferometers: idict = {} idict['label'] = label idict['action'] = 'modify' idict['gridfunc_freq'] = 'scale' idict['gridmethod'] = 'NN' idict['distNN'] = 0.5 * FCNST.c / f0 idict['tol'] = 1.0e-6 idict['maxmatch'] = 1 idict['wtsinfo'] = {} for pol in ['P11', 'P12', 'P21', 'P22']: # idict['wtsinfo'][pol] = [{'orientation':0.0, 'lookup':'/data3/t_nithyanandan/project_MOFF/simulated/MWA/data/lookup/V_illumination_lookup_zenith.txt'}] idict['wtsinfo'][pol] = [{'orientation':0.0, 'lookup':'/data3/t_nithyanandan/project_MOFF/simulated/LWA/data/lookup/E_illumination_isotropic_radiators_lookup_zenith.txt'}] interferometer_level_update_info['interferometers'] += [idict] iar.update(antenna_level_updates=antenna_level_update_info, interferometer_level_updates=interferometer_level_update_info, do_correlate='FX', parallel=True, verbose=True) iar.grid_convolve(pol='P11', method='NN', distNN=0.5*FCNST.c/f0, tol=1.0e-6, maxmatch=1, identical_interferometers=True, gridfunc_freq='scale', mapping='weighted', wts_change=False, parallel=True, pp_method='queue') imgobj = AA.NewImage(interferometer_array=iar, pol='P11') imgobj.imagr(weighting='natural', pol='P11') if i == 0: avg_img = imgobj.img['P11'] else: avg_img += imgobj.img['P11'] avg_img /= itr fig = PLT.figure() ax = fig.add_subplot(111) imgplot = ax.imshow(NP.mean(avg_img, axis=2), aspect='equal', origin='lower', extent=(imgobj.gridl.min(), imgobj.gridl.max(), imgobj.gridm.min(), imgobj.gridm.max())) posplot, = ax.plot(skypos[:,0], skypos[:,1], 'o', mfc='none', mec='black', mew=1, ms=8) ax.set_xlim(imgobj.gridl.min(), imgobj.gridl.max()) ax.set_ylim(imgobj.gridm.min(), imgobj.gridm.max()) PLT.savefig('/data3/t_nithyanandan/project_MOFF/simulated/MWA/figures/FX_image_random_source_positions_{0:0d}_iterations.png'.format(itr), bbox_inches=0) fig = PLT.figure() ax = fig.add_subplot(111) imgplot = ax.imshow(NP.mean(imgobj.beam['P11'], axis=2), aspect='equal', origin='lower', extent=(imgobj.gridl.min(), imgobj.gridl.max(), imgobj.gridm.min(), imgobj.gridm.max())) ax.set_xlim(imgobj.gridl.min(), imgobj.gridl.max()) ax.set_ylim(imgobj.gridm.min(), imgobj.gridm.max()) PLT.savefig('/data3/t_nithyanandan/project_MOFF/simulated/MWA/figures/FX_psf_square_illumination.png'.format(itr), bbox_inches=0)
[ "antenna_array.InterferometerArray", "numpy.random.uniform", "numpy.random.seed", "numpy.abs", "numpy.sum", "sim_observe.stochastic_E_timeseries", "numpy.ones", "datetime.datetime.now", "numpy.hstack", "matplotlib.pyplot.figure", "numpy.mean", "antenna_array.NewImage", "numpy.loadtxt", "nu...
[((608, 680), 'numpy.loadtxt', 'NP.loadtxt', (['antenna_file'], {'skiprows': '(6)', 'comments': '"""#"""', 'usecols': '(0, 1, 2, 3)'}), "(antenna_file, skiprows=6, comments='#', usecols=(0, 1, 2, 3))\n", (618, 680), True, 'import numpy as NP\n'), ((696, 719), 'numpy.mean', 'NP.mean', (['ant_info[:, 1]'], {}), '(ant_info[:, 1])\n', (703, 719), True, 'import numpy as NP\n'), ((736, 759), 'numpy.mean', 'NP.mean', (['ant_info[:, 2]'], {}), '(ant_info[:, 2])\n', (743, 759), True, 'import numpy as NP\n'), ((776, 799), 'numpy.mean', 'NP.mean', (['ant_info[:, 3]'], {}), '(ant_info[:, 3])\n', (783, 799), True, 'import numpy as NP\n'), ((1664, 1688), 'numpy.random.seed', 'NP.random.seed', (['src_seed'], {}), '(src_seed)\n', (1678, 1688), True, 'import numpy as NP\n'), ((1959, 1973), 'numpy.ones', 'NP.ones', (['n_src'], {}), '(n_src)\n', (1966, 1973), True, 'import numpy as NP\n'), ((2439, 2465), 'numpy.hstack', 'NP.hstack', (['(skypos, nvect)'], {}), '((skypos, nvect))\n', (2448, 2465), True, 'import numpy as NP\n'), ((2482, 2499), 'antenna_array.AntennaArray', 'AA.AntennaArray', ([], {}), '()\n', (2497, 2499), True, 'import antenna_array as AA\n'), ((2731, 2772), 'antenna_array.InterferometerArray', 'AA.InterferometerArray', ([], {'antenna_array': 'aar'}), '(antenna_array=aar)\n', (2753, 2772), True, 'import antenna_array as AA\n'), ((5702, 5714), 'matplotlib.pyplot.figure', 'PLT.figure', ([], {}), '()\n', (5712, 5714), True, 'import matplotlib.pyplot as PLT\n'), ((6261, 6273), 'matplotlib.pyplot.figure', 'PLT.figure', ([], {}), '()\n', (6271, 6273), True, 'import matplotlib.pyplot as PLT\n'), ((2905, 3061), 'sim_observe.stochastic_E_timeseries', 'SIM.stochastic_E_timeseries', (['f_center', '(nchan / 2)', '(2 * channel_width)'], {'flux_ref': 'src_flux', 'skypos': 'skypos', 'antpos': "antpos_info['positions']", 'tshift': '(False)'}), "(f_center, nchan / 2, 2 * channel_width,\n flux_ref=src_flux, skypos=skypos, antpos=antpos_info['positions'],\n tshift=False)\n", (2932, 3061), True, 'import sim_observe as SIM\n'), ((5482, 5530), 'antenna_array.NewImage', 'AA.NewImage', ([], {'interferometer_array': 'iar', 'pol': '"""P11"""'}), "(interferometer_array=iar, pol='P11')\n", (5493, 5530), True, 'import antenna_array as AA\n'), ((5761, 5785), 'numpy.mean', 'NP.mean', (['avg_img'], {'axis': '(2)'}), '(avg_img, axis=2)\n', (5768, 5785), True, 'import numpy as NP\n'), ((6320, 6355), 'numpy.mean', 'NP.mean', (["imgobj.beam['P11']"], {'axis': '(2)'}), "(imgobj.beam['P11'], axis=2)\n", (6327, 6355), True, 'import numpy as NP\n'), ((1026, 1048), 'numpy.abs', 'NP.abs', (['ant_info[:, 1]'], {}), '(ant_info[:, 1])\n', (1032, 1048), True, 'import numpy as NP\n'), ((1072, 1094), 'numpy.abs', 'NP.abs', (['ant_info[:, 2]'], {}), '(ant_info[:, 2])\n', (1078, 1094), True, 'import numpy as NP\n'), ((1743, 1791), 'numpy.random.uniform', 'NP.random.uniform', ([], {'low': '(0.0)', 'high': '(0.5)', 'size': 'n_src'}), '(low=0.0, high=0.5, size=n_src)\n', (1760, 1791), True, 'import numpy as NP\n'), ((1814, 1868), 'numpy.random.uniform', 'NP.random.uniform', ([], {'low': '(0.0)', 'high': '(2 * NP.pi)', 'size': 'n_src'}), '(low=0.0, high=2 * NP.pi, size=n_src)\n', (1831, 1868), True, 'import numpy as NP\n'), ((2651, 2685), 'my_DSP_modules.spectax', 'DSP.spectax', (['nchan', 'dt'], {'shift': '(True)'}), '(nchan, dt, shift=True)\n', (2662, 2685), True, 'import my_DSP_modules as DSP\n'), ((3227, 3244), 'datetime.datetime.now', 'DT.datetime.now', ([], {}), '()\n', (3242, 3244), True, 'import datetime as DT\n'), ((1909, 1922), 'numpy.cos', 'NP.cos', (['lmang'], {}), '(lmang)\n', (1915, 1922), True, 'import numpy as NP\n'), ((1932, 1945), 'numpy.sin', 'NP.sin', (['lmang'], {}), '(lmang)\n', (1938, 1945), True, 'import numpy as NP\n'), ((2389, 2416), 'numpy.sum', 'NP.sum', (['(skypos ** 2)'], {'axis': '(1)'}), '(skypos ** 2, axis=1)\n', (2395, 2416), True, 'import numpy as NP\n')]
from torch.autograd import Variable from net_gan_mnist import * import torch import torch.nn as nn import numpy as np from init import * class MNISTGanTrainer(object): def __init__(self, batch_size=64, latent_dims=100): super(MNISTGanTrainer, self).__init__() self.dis = Dis28x28() self.gen = Gen28x28(latent_dims) self.dis_opt = torch.optim.Adam(self.dis.parameters(), lr=0.0002, betas=(0.5, 0.999), weight_decay=0.0005) self.gen_opt = torch.optim.Adam(self.gen.parameters(), lr=0.0002, betas=(0.5, 0.999), weight_decay=0.0005) self.true_labels = Variable(torch.LongTensor(np.ones(batch_size, dtype=np.int))) self.fake_labels = Variable(torch.LongTensor(np.zeros(batch_size, dtype=np.int))) self.dis.apply(xavier_weights_init) self.gen.apply(xavier_weights_init) def cuda(self): self.dis.cuda() self.gen.cuda() self.true_labels = self.true_labels.cuda() self.fake_labels = self.fake_labels.cuda() def dis_update(self, images, noise): self.dis.zero_grad() true_outputs = self.dis(images) true_loss = nn.functional.cross_entropy(true_outputs, self.true_labels) _, true_predicts = torch.max(true_outputs.data, 1) true_acc = (true_predicts == 1).sum()/(1.0*true_predicts.size(0)) fake_images = self.gen(noise) fake_outputs = self.dis(fake_images) fake_loss = nn.functional.cross_entropy(fake_outputs, self.fake_labels) _, fake_predicts = torch.max(fake_outputs.data, 1) fake_acc = (fake_predicts == 0).sum() / (1.0 * fake_predicts.size(0)) d_loss = true_loss + fake_loss d_loss.backward() self.dis_opt.step() return 0.5 * (true_acc + fake_acc) def gen_update(self, noise): self.gen.zero_grad() fake_images = self.gen(noise) fake_outputs = self.dis(fake_images) fake_loss = nn.functional.cross_entropy(fake_outputs, self.true_labels) fake_loss.backward() self.gen_opt.step() return fake_images
[ "numpy.zeros", "numpy.ones", "torch.max", "torch.nn.functional.cross_entropy" ]
[((1144, 1203), 'torch.nn.functional.cross_entropy', 'nn.functional.cross_entropy', (['true_outputs', 'self.true_labels'], {}), '(true_outputs, self.true_labels)\n', (1171, 1203), True, 'import torch.nn as nn\n'), ((1231, 1262), 'torch.max', 'torch.max', (['true_outputs.data', '(1)'], {}), '(true_outputs.data, 1)\n', (1240, 1262), False, 'import torch\n'), ((1440, 1499), 'torch.nn.functional.cross_entropy', 'nn.functional.cross_entropy', (['fake_outputs', 'self.fake_labels'], {}), '(fake_outputs, self.fake_labels)\n', (1467, 1499), True, 'import torch.nn as nn\n'), ((1527, 1558), 'torch.max', 'torch.max', (['fake_outputs.data', '(1)'], {}), '(fake_outputs.data, 1)\n', (1536, 1558), False, 'import torch\n'), ((1939, 1998), 'torch.nn.functional.cross_entropy', 'nn.functional.cross_entropy', (['fake_outputs', 'self.true_labels'], {}), '(fake_outputs, self.true_labels)\n', (1966, 1998), True, 'import torch.nn as nn\n'), ((628, 661), 'numpy.ones', 'np.ones', (['batch_size'], {'dtype': 'np.int'}), '(batch_size, dtype=np.int)\n', (635, 661), True, 'import numpy as np\n'), ((717, 751), 'numpy.zeros', 'np.zeros', (['batch_size'], {'dtype': 'np.int'}), '(batch_size, dtype=np.int)\n', (725, 751), True, 'import numpy as np\n')]
from controller import * import random from keras.optimizers import Adam from keras.models import Sequential from keras.layers.core import Dense, Dropout from keras.utils.np_utils import to_categorical import numpy as np class CellItemType(enum.Enum): WALL = -1 EMPTY = 0 BODY = 1 HEAD = 2 FRUIT = 4 def __int__(self): return self.value class AIController(Controller): player = None game = None neural_network = None learning_rate = 0.0005 first_layer = 150 second_layer = 150 third_layer = 150 train_flag = True def init(self, player, game): self.player = player self.game = game self.reward = 0 self.score = 0 self.last_state = self.get_snake_vision() self.last_decision = None if not self.neural_network: self.create_network() def get_input_size(self): return len(self.last_state) def scan(self, board, start_pos, itemType, direction): i = 1 while True: x = start_pos.x + i * self.player.step * direction[0] y = start_pos.y + i * self.player.step * direction[1] if x < self.get_min_x() or x >= self.get_max_x() or y < self.get_min_y() or y >= self.get_max_y(): if itemType == CellItemType.WALL: return 1 / start_pos.distance(Position(x, y)) break curr_idx = self.coordinates_to_board_index(x, y) if board[curr_idx] == int(itemType): return 1 / start_pos.distance(Position(x, y)) i += 1 #print(" i = ", i) return 1 def get_snake_vision(self): board = self.board_state_to_list() directions = [(0, -1), (1, -1), (1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0), (-1, -1)] # up, up-right, right... directions_for_move = None if self.player.last_move == Move.UP: directions_for_move = directions[-3:] + directions[:4] elif self.player.last_move == Move.RIGHT: directions_for_move = directions[-1:] + directions[:6] elif self.player.last_move == Move.DOWN: directions_for_move = directions[1:] elif self.player.last_move == Move.LEFT: directions_for_move = directions[3:] + directions[:2] vision = [] for cell in (CellItemType.WALL, CellItemType.FRUIT, CellItemType.BODY): for direction in directions_for_move: vision.append(self.scan(board, self.player.positions[0], cell, direction)) return np.asarray(vision) def make_move(self): self.reward -= 0 self.last_state = self.get_snake_vision() prediction = self.neural_network.predict(self.last_state.reshape((1, self.get_input_size()))) #print(" ---------------------------------------- ") #print("Snake vision = ", self.last_state) #print("Prediction = ", prediction) #print("------------------------------------------\n\n") # Predictions will be a [[0.3333328 0.3332601 0.33340713]] type np array self.last_decision = to_categorical(np.argmax(prediction[0]), num_classes=3) print("Current Reward = ", self.reward) if self.last_decision[0]: # left self.player.turn_left() elif self.last_decision[1]: # forward pass elif self.last_decision[2]: # right self.player.turn_right() def set_reward(self): #self.reward = 0 if self.player.get_score() > self.score: self.score = self.player.get_score() self.reward += 500 elif self.game.is_end(): self.reward += -500 # else: # self.reward = - self.player.positions[0].distance(self.game.fruit.position) / self.player.step def update_state(self): if self.train_flag: self.set_reward() #print(self.reward) target_f = self.neural_network.predict(self.last_state.reshape((1, self.get_input_size()))) target_f[0][np.argmax(self.last_decision)] = self.reward self.neural_network.fit(self.last_state.reshape((1, self.get_input_size())), target_f, epochs=1, verbose=0) def get_board_width(self): return (self.game.board_rect.right - self.game.board_rect.left) / self.player.step def get_board_height(self): return (self.game.board_rect.bottom - self.game.board_rect.top) / self.player.step def get_min_x(self): return self.game.board_rect.left def get_min_y(self): return self.game.board_rect.top def get_max_x(self): return self.game.board_rect.right def get_max_y(self): return self.game.board_rect.bottom def coordinates_to_board_index(self, x, y): tmp_x = (x - self.get_min_x()) / self.player.step tmp_y = (y - self.get_min_y()) / self.player.step width = self.get_board_width() return int(tmp_y * width + tmp_x) def board_state_to_list(self): board = [] for row in range(self.game.board_rect.top, self.game.board_rect.bottom, self.player.step): for col in range(self.game.board_rect.left, self.game.board_rect.right, self.player.step): board.append(CellItemType.EMPTY.value) board[self.coordinates_to_board_index(self.game.fruit.position.x, self.game.fruit.position.y)] = CellItemType.FRUIT.value for pos in self.player.positions: board[self.coordinates_to_board_index(pos.x, pos.y)] = CellItemType.BODY.value snake_head = self.player.positions[0] board[self.coordinates_to_board_index(snake_head.x, snake_head.y)] = CellItemType.HEAD.value return np.asarray(board) def create_network(self): self.neural_network = Sequential() self.neural_network.add(Dense(self.first_layer, activation='relu', input_dim=self.get_input_size())) self.neural_network.add(Dense(self.second_layer, activation='relu')) self.neural_network.add(Dense(self.third_layer, activation='relu')) self.neural_network.add(Dense(3, activation='softmax')) opt = Adam(self.learning_rate) self.neural_network.compile(loss='mse', optimizer=opt)
[ "keras.layers.core.Dense", "numpy.argmax", "numpy.asarray", "keras.optimizers.Adam", "keras.models.Sequential" ]
[((2644, 2662), 'numpy.asarray', 'np.asarray', (['vision'], {}), '(vision)\n', (2654, 2662), True, 'import numpy as np\n'), ((5964, 5981), 'numpy.asarray', 'np.asarray', (['board'], {}), '(board)\n', (5974, 5981), True, 'import numpy as np\n'), ((6052, 6064), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (6062, 6064), False, 'from keras.models import Sequential\n'), ((6414, 6438), 'keras.optimizers.Adam', 'Adam', (['self.learning_rate'], {}), '(self.learning_rate)\n', (6418, 6438), False, 'from keras.optimizers import Adam\n'), ((3228, 3252), 'numpy.argmax', 'np.argmax', (['prediction[0]'], {}), '(prediction[0])\n', (3237, 3252), True, 'import numpy as np\n'), ((6206, 6249), 'keras.layers.core.Dense', 'Dense', (['self.second_layer'], {'activation': '"""relu"""'}), "(self.second_layer, activation='relu')\n", (6211, 6249), False, 'from keras.layers.core import Dense, Dropout\n'), ((6283, 6325), 'keras.layers.core.Dense', 'Dense', (['self.third_layer'], {'activation': '"""relu"""'}), "(self.third_layer, activation='relu')\n", (6288, 6325), False, 'from keras.layers.core import Dense, Dropout\n'), ((6359, 6389), 'keras.layers.core.Dense', 'Dense', (['(3)'], {'activation': '"""softmax"""'}), "(3, activation='softmax')\n", (6364, 6389), False, 'from keras.layers.core import Dense, Dropout\n'), ((4224, 4253), 'numpy.argmax', 'np.argmax', (['self.last_decision'], {}), '(self.last_decision)\n', (4233, 4253), True, 'import numpy as np\n')]
#!/usr/bin/env python # -*- coding: utf-8 -*- #%% from numpy import * import numpy as np import torch import aTEAM.nn.functional as aF #%% a = np.arange(10) a = a[:,None]+a[None,:] b = torch.from_numpy(a) print(np.roll(a, shift=[0,1],axis=[1,0])-aF.roll(b, shift=[0,1],axis=[1,0]).data.numpy()) print(np.roll(a, shift=[2,1])-aF.roll(b, shift=[2,1]).data.numpy()) print(np.roll(a, shift=[2,-1], axis=[0,1])-aF.roll(b, shift=[2,-1], axis=[0,1]).data.numpy()) #%%
[ "aTEAM.nn.functional.roll", "numpy.roll", "numpy.arange", "torch.from_numpy" ]
[((143, 156), 'numpy.arange', 'np.arange', (['(10)'], {}), '(10)\n', (152, 156), True, 'import numpy as np\n'), ((185, 204), 'torch.from_numpy', 'torch.from_numpy', (['a'], {}), '(a)\n', (201, 204), False, 'import torch\n'), ((212, 249), 'numpy.roll', 'np.roll', (['a'], {'shift': '[0, 1]', 'axis': '[1, 0]'}), '(a, shift=[0, 1], axis=[1, 0])\n', (219, 249), True, 'import numpy as np\n'), ((302, 326), 'numpy.roll', 'np.roll', (['a'], {'shift': '[2, 1]'}), '(a, shift=[2, 1])\n', (309, 326), True, 'import numpy as np\n'), ((370, 408), 'numpy.roll', 'np.roll', (['a'], {'shift': '[2, -1]', 'axis': '[0, 1]'}), '(a, shift=[2, -1], axis=[0, 1])\n', (377, 408), True, 'import numpy as np\n'), ((247, 284), 'aTEAM.nn.functional.roll', 'aF.roll', (['b'], {'shift': '[0, 1]', 'axis': '[1, 0]'}), '(b, shift=[0, 1], axis=[1, 0])\n', (254, 284), True, 'import aTEAM.nn.functional as aF\n'), ((326, 350), 'aTEAM.nn.functional.roll', 'aF.roll', (['b'], {'shift': '[2, 1]'}), '(b, shift=[2, 1])\n', (333, 350), True, 'import aTEAM.nn.functional as aF\n'), ((407, 445), 'aTEAM.nn.functional.roll', 'aF.roll', (['b'], {'shift': '[2, -1]', 'axis': '[0, 1]'}), '(b, shift=[2, -1], axis=[0, 1])\n', (414, 445), True, 'import aTEAM.nn.functional as aF\n')]
"""Most test exploit the special case where simulate_moments just returns parameters.""" import itertools import warnings import numpy as np import pandas as pd import pytest from estimagic.estimation.estimate_msm import estimate_msm from estimagic.shared.check_option_dicts import check_numdiff_options from estimagic.shared.check_option_dicts import check_optimization_options from numpy.testing import assert_array_almost_equal as aaae def _sim_pd(params): return params["value"] def _sim_np(params): return params["value"].to_numpy() def _sim_dict_pd(params): return {"simulated_moments": params["value"], "other": "bla"} def _sim_dict_np(params): return {"simulated_moments": params["value"].to_numpy(), "other": "bla"} cov_np = np.diag([1, 2, 3.0]) cov_pd = pd.DataFrame(cov_np) funcs = [_sim_pd, _sim_np, _sim_dict_pd, _sim_dict_np] covs = [cov_np, cov_pd] test_cases = list(itertools.product(funcs, covs)) @pytest.mark.parametrize("simulate_moments, moments_cov", test_cases) def test_estimate_msm(simulate_moments, moments_cov): start_params = pd.DataFrame() start_params["value"] = [3, 2, 1] expected_params = pd.DataFrame() expected_params["value"] = np.zeros(3) # abuse simulate_moments to get empirical moments in correct format empirical_moments = simulate_moments(expected_params) if isinstance(empirical_moments, dict): empirical_moments = empirical_moments["simulated_moments"] optimize_options = {"algorithm": "scipy_lbfgsb"} # catching warnings is necessary because the very special case with diagonal # weighting and diagonal jacobian leads to singular matrices while calculating # sensitivity to removal of moments. with warnings.catch_warnings(): warnings.filterwarnings("ignore", message="Standard matrix inversion failed") calculated = estimate_msm( simulate_moments=simulate_moments, empirical_moments=empirical_moments, moments_cov=moments_cov, params=start_params, optimize_options=optimize_options, ) calculated_params = calculated["optimize_res"]["solution_params"][["value"]] # check that minimization works aaae(calculated_params["value"].to_numpy(), expected_params["value"].to_numpy()) # check that cov works calculated_cov = calculated["cov"] if isinstance(calculated_cov, pd.DataFrame): calculated_cov = calculated_cov.to_numpy() # this works only in the very special case with diagonal moments cov and # jac = identity matrix expected_cov = np.diag([1, 2, 3]) aaae(calculated_cov, expected_cov) def test_check_and_process_numdiff_options_with_invalid_entries(): with pytest.raises(ValueError): check_numdiff_options({"func": lambda x: x}, "estimate_msm") def test_check_and_process_optimize_options_with_invalid_entries(): with pytest.raises(ValueError): check_optimization_options({"criterion": lambda x: x}, "estimate_msm")
[ "pandas.DataFrame", "estimagic.shared.check_option_dicts.check_numdiff_options", "warnings.filterwarnings", "estimagic.estimation.estimate_msm.estimate_msm", "numpy.zeros", "pytest.raises", "estimagic.shared.check_option_dicts.check_optimization_options", "warnings.catch_warnings", "pytest.mark.para...
[((761, 781), 'numpy.diag', 'np.diag', (['[1, 2, 3.0]'], {}), '([1, 2, 3.0])\n', (768, 781), True, 'import numpy as np\n'), ((791, 811), 'pandas.DataFrame', 'pd.DataFrame', (['cov_np'], {}), '(cov_np)\n', (803, 811), True, 'import pandas as pd\n'), ((947, 1015), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""simulate_moments, moments_cov"""', 'test_cases'], {}), "('simulate_moments, moments_cov', test_cases)\n", (970, 1015), False, 'import pytest\n'), ((912, 942), 'itertools.product', 'itertools.product', (['funcs', 'covs'], {}), '(funcs, covs)\n', (929, 942), False, 'import itertools\n'), ((1089, 1103), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (1101, 1103), True, 'import pandas as pd\n'), ((1165, 1179), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (1177, 1179), True, 'import pandas as pd\n'), ((1211, 1222), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (1219, 1222), True, 'import numpy as np\n'), ((2600, 2618), 'numpy.diag', 'np.diag', (['[1, 2, 3]'], {}), '([1, 2, 3])\n', (2607, 2618), True, 'import numpy as np\n'), ((2623, 2657), 'numpy.testing.assert_array_almost_equal', 'aaae', (['calculated_cov', 'expected_cov'], {}), '(calculated_cov, expected_cov)\n', (2627, 2657), True, 'from numpy.testing import assert_array_almost_equal as aaae\n'), ((1734, 1759), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {}), '()\n', (1757, 1759), False, 'import warnings\n'), ((1769, 1846), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {'message': '"""Standard matrix inversion failed"""'}), "('ignore', message='Standard matrix inversion failed')\n", (1792, 1846), False, 'import warnings\n'), ((1868, 2042), 'estimagic.estimation.estimate_msm.estimate_msm', 'estimate_msm', ([], {'simulate_moments': 'simulate_moments', 'empirical_moments': 'empirical_moments', 'moments_cov': 'moments_cov', 'params': 'start_params', 'optimize_options': 'optimize_options'}), '(simulate_moments=simulate_moments, empirical_moments=\n empirical_moments, moments_cov=moments_cov, params=start_params,\n optimize_options=optimize_options)\n', (1880, 2042), False, 'from estimagic.estimation.estimate_msm import estimate_msm\n'), ((2736, 2761), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (2749, 2761), False, 'import pytest\n'), ((2771, 2831), 'estimagic.shared.check_option_dicts.check_numdiff_options', 'check_numdiff_options', (["{'func': lambda x: x}", '"""estimate_msm"""'], {}), "({'func': lambda x: x}, 'estimate_msm')\n", (2792, 2831), False, 'from estimagic.shared.check_option_dicts import check_numdiff_options\n'), ((2911, 2936), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (2924, 2936), False, 'import pytest\n'), ((2946, 3016), 'estimagic.shared.check_option_dicts.check_optimization_options', 'check_optimization_options', (["{'criterion': lambda x: x}", '"""estimate_msm"""'], {}), "({'criterion': lambda x: x}, 'estimate_msm')\n", (2972, 3016), False, 'from estimagic.shared.check_option_dicts import check_optimization_options\n')]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun May 9 11:59:51 2021 @author: Daniel """ import numpy as np from get_sudoku import get_sudoku_ from copy import deepcopy def look_row(row): #creates local set for current square local_set_row = {i for i in range(1,10)} #iterates through elements of row of current square for element in row: #eleminates number from local set if present in row #this will reduce the possibilities of numbers to be put on current square if element in local_set_row: local_set_row.remove(element) return local_set_row def look_column(column): #creates local set for current square local_set_column = {i for i in range(1,10)} #iterates through elements of column of current square for element in column: #eliminates number from local set if present in row #this will reduce the possibilities of numbers to be put on current square if element in local_set_column: local_set_column.remove(element) return local_set_column def get_square(sudoku, row, column): #finds square where current cell is located if row in range(0,3): if column in range(0,3): search_square = sudoku[0:3,0:3] if column in range(3,6): search_square = sudoku[0:3,3:6] if column in range(6,9): search_square = sudoku[0:3,6:9] if row in range(3,6): if column in range(0,3): search_square = sudoku[3:6,0:3] if column in range(3,6): search_square = sudoku[3:6,3:6] if column in range(6,9): search_square = sudoku[3:6,6:9] if row in range(6,9): if column in range(0,3): search_square = sudoku[6:9,0:3] if column in range(3,6): search_square = sudoku[6:9,3:6] if column in range(6,9): search_square = sudoku[6:9,6:9] return search_square def look_square(sudoku, row, column): #creates local set for current square local_set_square = {i for i in range(1,10)} #finds square where current cell is located search_square = get_square(sudoku, row, column) #iterates through elements of column of current square for row in search_square: for column in row: #eleminates number from local set if present in row #this will reduce the possibilities of numbers to be put on current square if column in local_set_square: local_set_square.remove(column) return local_set_square def intercept_locals(local_set_row, local_set_column, local_set_square): #intercepts sets of possible numbers to put on current square according to #evaluation of row, column and big square local_set = local_set_row.intersection(local_set_column) local_set = local_set.intersection(local_set_square) return local_set def get_candidates(sudoku): candidates = sudoku.tolist() #starts searching by row for i in range(0,9): #iterates through column of said row for j in range(0,9): #only interested in squares that don't already have a number assigned if sudoku[i,j] == 0: #look row set_row = look_row(sudoku[i]) #look column set_column = look_column(sudoku[:,j]) #look big square set_square = look_square(sudoku, i, j) #intercept all local_set = intercept_locals(set_row, set_column, set_square) # candidates[i][j] = list(local_set) else: candidates[i][j] = [sudoku[i,j]] return candidates def filter_candidates(sudoku): test_sudoku = sudoku.copy() candidates = get_candidates(sudoku) filtered_candidates = deepcopy(candidates) for i in range(9): for j in range(9): # Check for empty cells if sudoku[i][j] == 0: for candidate in candidates[i][j]: # Use test candidate test_sudoku[i][j] = candidate # Remove candidate if it produces an invalid grid if not check_solution(fill_singles(test_sudoku)): filtered_candidates[i][j].remove(candidate) # Revert changes test_sudoku[i][j] = 0 return filtered_candidates def fill_singles(sudoku, candidates=None): sudoku = sudoku.copy() if not candidates: candidates = get_candidates(sudoku) singles = True while singles: singles = False for i in range(0,9): for j in range(0,9): if type(candidates[i][j]) == list: if len(candidates[i][j]) == 1 and sudoku[i, j] == 0: sudoku[i, j] = candidates[i][j][0] candidates = merge(get_candidates(sudoku), candidates) singles = True return sudoku def merge(candidates_1, candidates_2): candidates_min = [] for i in range(9): row = [] for j in range(9): if len(candidates_1[i][j]) < len(candidates_2[i][j]): row.append(candidates_1[i][j][:]) else: row.append(candidates_2[i][j][:]) candidates_min.append(row) return candidates_min def make_guess(sudoku, candidates=None): print("Making guesses, still on it :(") min_len = 9 sudoku = sudoku.copy() if not candidates: candidates = get_candidates(sudoku) for i in range(9): for j in range(9): #checks if current cell in memory is set to unique value or is still undecided if type(candidates[i][j]) == list: #finds list with lowest lentgh to maximize hypothesis of getting substitution right if len(candidates[i][j]) < min_len: min_len = len(candidates[i][j]) for i in range(9): for j in range(9): if type(candidates[i][j]) == list: if len(candidates[i][j]) == min_len: for guess in candidates[i][j]: sudoku[i][j] = guess solution = filtered_solve(sudoku) if solution is not None: return solution # Discarding incorrect guess sudoku[i][j] = 0 def check_solution(sudoku): '''checks whether solution is valid (particularly useful after making guess)''' candidates = get_candidates(sudoku) for i in range(0, 9): for j in range(0, 9): #checks if in candidates list there are lists with no values (=cells with no candidates) if type(candidates[i][j]) == list: if len(candidates[i][j]) == 0: return False return True def is_solution(sudoku): if np.all(np.sum(sudoku, axis=1) == 45) and \ np.all(np.sum(sudoku, axis=0) == 45): if sum(map(sum, sudoku[0:3, 0:3])) == 45 and sum(map(sum, sudoku[0:3, 3:6])) == 45 and sum(map(sum, sudoku[0:3, 6:9])) == 45 and \ sum(map(sum, sudoku[3:6, 0:3])) == 45 and sum(map(sum, sudoku[3:6, 3:6])) == 45 and sum(map(sum, sudoku[3:6, 6:9])) == 45 and \ sum(map(sum, sudoku[6:9, 0:3])) == 45 and sum(map(sum, sudoku[6:9, 3:6])) == 45 and sum(map(sum, sudoku[6:9, 6:9])) == 45: return True return False def filtered_solve(sudoku): candidates = filter_candidates(sudoku) sudoku = fill_singles(sudoku, candidates) if is_solution(sudoku): return sudoku if not check_solution(sudoku): return None return make_guess(sudoku, candidates) def solve(sudoku): sudoku = fill_singles(sudoku) if is_solution(sudoku): print(sudoku) return sudoku if not check_solution(sudoku): return None return make_guess(sudoku) solve(get_sudoku_())
[ "copy.deepcopy", "numpy.sum", "get_sudoku.get_sudoku_" ]
[((4135, 4155), 'copy.deepcopy', 'deepcopy', (['candidates'], {}), '(candidates)\n', (4143, 4155), False, 'from copy import deepcopy\n'), ((8732, 8745), 'get_sudoku.get_sudoku_', 'get_sudoku_', ([], {}), '()\n', (8743, 8745), False, 'from get_sudoku import get_sudoku_\n'), ((7630, 7652), 'numpy.sum', 'np.sum', (['sudoku'], {'axis': '(1)'}), '(sudoku, axis=1)\n', (7636, 7652), True, 'import numpy as np\n'), ((7680, 7702), 'numpy.sum', 'np.sum', (['sudoku'], {'axis': '(0)'}), '(sudoku, axis=0)\n', (7686, 7702), True, 'import numpy as np\n')]
import math import numpy as np import torch from sklearn.metrics import average_precision_score, roc_auc_score def choose_target(model,memory_s, memory_g, src_mem): u = model.memory_merge(memory_s[1], memory_g[1]) #[num_nodes,mem_d] u_norm = torch.norm(u, dim=1) #[num_nodes, 1] u_normalized = u/u_norm.view(-1, 1) #[num_nodes,mem_d] src_mem_norm = torch.norm(src_mem, dim=1) #[batch_size, 1] src_mem_normalized = src_mem / src_mem_norm.view(-1, 1) #[batch_size, mem_d] cos_similarity = torch.matmul(src_mem_normalized, u_normalized.t()) #[batch_size, num_nodes] cos_similarity, idx = torch.sort(cos_similarity, descending=True) return cos_similarity, idx def recall(des_node, idx, top_k): bs = idx.shape[0] idx = idx[:, :top_k] #[bs,top_k] recall = np.array([a in idx[i] for i, a in enumerate(des_node)])#[bs,1] recall = recall.sum() / recall.size return recall def MRR(des_node, idx): bs = idx.shape[0] mrr = np.array([float(np.where(idx[i].cpu() == a)[0] + 1) for i, a in enumerate(des_node)])#[bs,1] mrr = (1 / mrr).mean() return mrr def eval_edge_prediction(model, negative_edge_sampler, data, n_neighbors, batch_size=200): # Ensures the random sampler uses a seed for evaluation (i.e. we sample always the same # negatives for validation / test set) assert negative_edge_sampler.seed is not None negative_edge_sampler.reset_random_state() val_mrr, val_recall_20, val_recall_50 = [], [], [] with torch.no_grad(): model = model.eval() # While usually the test batch size is as big as it fits in memory, here we keep it the same # size as the training batch size, since it allows the memory to be updated more frequently, # and later test batches to access information from interactions in previous test batches # through the memory TEST_BATCH_SIZE = batch_size num_test_instance = len(data.sources) num_test_batch = math.ceil(num_test_instance / TEST_BATCH_SIZE) for k in range(num_test_batch): s_idx = k * TEST_BATCH_SIZE e_idx = min(num_test_instance, s_idx + TEST_BATCH_SIZE) sources_batch = data.sources[s_idx:e_idx] destinations_batch = data.destinations[s_idx:e_idx] timestamps_batch = data.timestamps[s_idx:e_idx] edge_idxs_batch = data.edge_idxs[s_idx: e_idx] size = len(sources_batch) _, negative_samples = negative_edge_sampler.sample(size) src_mem, des_mem = model(sources_batch, destinations_batch, negative_samples, timestamps_batch, edge_idxs_batch, test=True) src_cos_sim, src_idx = choose_target(model, model.memory_s.memory, model.memory_g.memory, src_mem) des_cos_sim, des_idx = choose_target(model, model.memory_s.memory, model.memory_g.memory, des_mem) recall_20 = (recall(destinations_batch, src_idx, 20) + recall(sources_batch, des_idx, 20)) / 2 recall_50 = (recall(destinations_batch, src_idx, 50) + recall(sources_batch, des_idx, 50)) / 2 mrr = (MRR(destinations_batch, src_idx) + MRR(sources_batch, des_idx)) / 2 true_label = np.concatenate([np.ones(size), np.zeros(size)]) val_mrr.append(mrr) val_recall_20.append(recall_20) val_recall_50.append(recall_50) return np.mean(val_mrr), np.mean(val_recall_20), np.mean(val_recall_50)
[ "math.ceil", "torch.norm", "numpy.zeros", "numpy.ones", "numpy.mean", "torch.no_grad", "torch.sort" ]
[((248, 268), 'torch.norm', 'torch.norm', (['u'], {'dim': '(1)'}), '(u, dim=1)\n', (258, 268), False, 'import torch\n'), ((361, 387), 'torch.norm', 'torch.norm', (['src_mem'], {'dim': '(1)'}), '(src_mem, dim=1)\n', (371, 387), False, 'import torch\n'), ((605, 648), 'torch.sort', 'torch.sort', (['cos_similarity'], {'descending': '(True)'}), '(cos_similarity, descending=True)\n', (615, 648), False, 'import torch\n'), ((1458, 1473), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (1471, 1473), False, 'import torch\n'), ((1909, 1955), 'math.ceil', 'math.ceil', (['(num_test_instance / TEST_BATCH_SIZE)'], {}), '(num_test_instance / TEST_BATCH_SIZE)\n', (1918, 1955), False, 'import math\n'), ((3323, 3339), 'numpy.mean', 'np.mean', (['val_mrr'], {}), '(val_mrr)\n', (3330, 3339), True, 'import numpy as np\n'), ((3341, 3363), 'numpy.mean', 'np.mean', (['val_recall_20'], {}), '(val_recall_20)\n', (3348, 3363), True, 'import numpy as np\n'), ((3365, 3387), 'numpy.mean', 'np.mean', (['val_recall_50'], {}), '(val_recall_50)\n', (3372, 3387), True, 'import numpy as np\n'), ((3178, 3191), 'numpy.ones', 'np.ones', (['size'], {}), '(size)\n', (3185, 3191), True, 'import numpy as np\n'), ((3193, 3207), 'numpy.zeros', 'np.zeros', (['size'], {}), '(size)\n', (3201, 3207), True, 'import numpy as np\n')]
__author__ = 'Zander' from pygame import gfxdraw from Vector2 import Vector2 from Vector4 import Vector4 from Vector3 import Vector3 from Matrix4 import Matrix4 import math, pygame import numpy as np class Renderer: def __init__(self, screen, width, height, scale=1): self.width = width self.height = height self.screen = screen self.matrix = Matrix4() self.scale = scale self.wireframe = False self.pixels = [] def clear(self): self.screen.fill((0,0,0)) self.pixels = [] def drawScreen(self): self.pixels = sorted(self.pixels, key=lambda x: x[3]) for p in self.pixels: gfxdraw.pixel(self.screen, p[0], p[1], p[2]) def putPixel(self, vector, color): if not vector.x < 0 and not vector.x > self.width: if not vector.y < 0 and not vector.y > self.height: self.pixels += [[int(vector.x), int(vector.y), color, vector.z]] def drawLine(self, point0, point1, color): dist = (point0 - point1).length if dist < 2: return middlePoint = point0 + (point1 - point0)/Vector2(2, 2) self.putPixel(middlePoint, color) self.drawLine(point0, middlePoint, color) self.drawLine(middlePoint, point1, color) def drawScanLine(self, pointA, pointB, y, sz, ez, sShade, eShade, color): if pointA > pointB: temp = pointA pointA = pointB pointB = temp z_slope = (ez - sz)/(pointB - pointA) shadingGradient = (eShade - sShade)/(pointB - pointA) for x in range(int(pointA), int(pointB)): if x > self.width: return if y > self.height: return color *= sShade color = self.clamp(color, 0, 255) self.putPixel(Vector3(x, y, sz), (color, color, color)) sz += z_slope sShade += shadingGradient def clamp (self, value, min, max): if value < min: return min elif value > max: return max else: return value """a.y <= b.y <= c.y""" def drawTriangle(self, pointA, pointB, pointC, shades, color): #Uses rasterization to draw triangle #slopes dx/dy drawUpper = True #handles weird exceptions if int(pointA.y - pointC.y) != 0: slopeAC = (pointA.x - pointC.x)/(pointA.y - pointC.y) slopeACZ = (pointA.z - pointC.z)/(pointA.y - pointC.y) #new beta test shadingGradientAC = (shades[0] - shades[2])/(pointA.y - pointC.y) else: return if int(pointA.y - pointB.y) != 0: slopeAB = (pointA.x - pointB.x)/(pointA.y - pointB.y) slopeABZ = (pointA.z - pointB.z)/(pointA.y - pointB.y) #new beta code shadingGradientAB = (shades[0] - shades[1])/(pointA.y - pointB.y) else: drawUpper = False self.drawScanLine(pointA.x, pointB.x, pointA.y, pointA.z, pointB.z, shades[0], shades[0], color) slopeBC = (pointB.x - pointC.x)/(pointB.y - pointC.y) slopeBCZ = (pointB.z - pointC.z)/(pointB.y - pointC.y) #new beta shadingGradientBC = (shades[1] - shades[2])/(pointB.y - pointC.y) sx, ex = pointA.x, pointA.x sz, ez = pointA.z, pointA.z #new beta test sShade, eShade = shades[0], shades[0] if drawUpper: for y in range(int(pointA.y), int(pointB.y)): self.drawScanLine(sx, ex, y, sz, ez, sShade, eShade, color) sx += slopeAC ex += slopeAB sz += slopeACZ ez += slopeABZ sShade += shadingGradientAC eShade += shadingGradientAB else: ex = pointB.x ez = pointB.z eShade = shades[1] for y in range(int(pointB.y), int(pointC.y)): self.drawScanLine(sx, ex, y, sz, ez, sShade, eShade, color) sx += slopeAC ex += slopeBC sz += slopeACZ ez += slopeBCZ sShade += shadingGradientAC eShade += shadingGradientBC def drawBline(self, point0, point1, color): x0 = int(point0.x) y0 = int(point0.y) x1 = int(point1.x) y1 = int(point1.y) dx = abs(x1 - x0) dy = abs(y1 - y0) if (x0 < x1): sx = 1 else: sx = -1 if y0 < y1: sy = 1 else: sy = -1 err = dx - dy while x0 != x1 or y0 != y1: self.putPixel(Vector3(x0, y0, 0), color) e2 = 2 * err if e2 > -dy: err -= dy x0 += sx elif e2 < dx: err += dx y0 += sy def project(self, vector, aspectRatio, zNear, zFar, fov_degree): if (aspectRatio > 1): sX = 1/aspectRatio else: sX = 1 if (aspectRatio > 1): sY = 1 else: sY = aspectRatio fov = 1/math.tan(math.radians(fov_degree/2)) scaleX = fov * sX scaleY = fov * sY projectionMatrix = self.matrix.get_projection_matrix(zNear, zFar, scaleX, scaleY) projectedVector = Vector4(vector.x, vector.y, vector.z, 1).dot_product_with_matrix(projectionMatrix) return Vector3(projectedVector[0] + self.width/2, projectedVector[1]+ self.height/2, projectedVector[2]) def render(self, camera, lights, meshes): polygons=[] for mesh in meshes: rotationMatrix = self.matrix.get_rotation_matrix(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z) translationMatrix = self.matrix.get_translation_matrix(mesh.position - camera.position) worldMatrix = np.dot(self.matrix.get_scaling_matrix(Vector3(self.scale,self.scale,self.scale)), np.dot(rotationMatrix, translationMatrix)) for face in mesh.faces: # print face[0], face[1], face[2] vertexA = mesh.vertices[face[0][0]] vertexB = mesh.vertices[face[0][1]] vertexC = mesh.vertices[face[0][2]] vertexA = vertexA.dot_product_with_matrix(worldMatrix) vertexB = vertexB.dot_product_with_matrix(worldMatrix) vertexC = vertexC.dot_product_with_matrix(worldMatrix) pixelA = self.project(vertexA, 800/600, 1, 1000, 70) pixelB = self.project(vertexB, 800/600, 1, 1000, 70) pixelC = self.project(vertexC, 800/600, 1, 1000, 70) if not self.wireframe: #still in devoplment.... BETA!!!! norm1 = mesh.normals[face[1][0]] norm2 = mesh.normals[face[1][1]] norm3 = mesh.normals[face[1][2]] norm1 = norm1.dot_product_with_matrix(worldMatrix) norm2 = norm2.dot_product_with_matrix(worldMatrix) norm3 = norm3.dot_product_with_matrix(worldMatrix) #sorts pixels pixels = [pixelA, pixelB, pixelC] pixels = sorted(pixels, key=lambda x: x.y) color = 255 #gouraud shading # vertices = [[vertexA, pixelA.y], [vertexB, pixelB.y], [vertexC, pixelC.y]] # vertices = sorted(vertices, key=lambda x: x[1]) # # diffuseIntensities = [] # for light in lights: # lightingDistanceA = light.position - vertices[0][0] # lightingDistanceB = light.position - vertices[1][0] # lightingDistanceC = light.position - vertices[2][0] # # diffuseIntensities += [light.getIntensity(vertices[0][0]) * norm1.normalize().dot_product(lightingDistanceA.normalize())] # diffuseIntensities += [light.getIntensity(vertices[1][0]) * norm1.normalize().dot_product(lightingDistanceB.normalize())] # diffuseIntensities += [light.getIntensity(vertices[2][0]) * norm1.normalize().dot_product(lightingDistanceC.normalize())] # # self.drawTriangle(pixels[0], pixels[1], pixels[2], diffuseIntensities, color) #flat shading nFace = (norm1 + norm2 + norm3)/Vector3(3,3,3) center = (vertexA + vertexB + vertexC)/Vector3(3,3,3) diffuseIntensity = 0 for light in lights: lightingDistance = light.position - center diffuseIntensity += light.getIntensity(center) * \ nFace.normalize().dot_product(lightingDistance.normalize()) color *= diffuseIntensity color += 50 color = self.clamp(color, 0, 255) polygons += [(self.screen, (int(color), int(color), int(color)), [[pixelA.x, pixelA.y], [pixelB.x, pixelB.y], [pixelC.x, pixelC.y]], vertexA.z)] else: self.drawBline(pixelA, pixelB, (255,255,255)) self.drawBline(pixelB, pixelC, (255,255,255)) self.drawBline(pixelC, pixelA, (255,255,255)) if not self.wireframe: polygons = sorted(polygons, key=lambda x: x[3]) for polygon in polygons: pygame.draw.polygon(polygon[0], polygon[1], polygon[2]) self.drawScreen()
[ "Vector2.Vector2", "pygame.gfxdraw.pixel", "math.radians", "Vector3.Vector3", "Matrix4.Matrix4", "numpy.dot", "pygame.draw.polygon", "Vector4.Vector4" ]
[((383, 392), 'Matrix4.Matrix4', 'Matrix4', ([], {}), '()\n', (390, 392), False, 'from Matrix4 import Matrix4\n'), ((5489, 5596), 'Vector3.Vector3', 'Vector3', (['(projectedVector[0] + self.width / 2)', '(projectedVector[1] + self.height / 2)', 'projectedVector[2]'], {}), '(projectedVector[0] + self.width / 2, projectedVector[1] + self.\n height / 2, projectedVector[2])\n', (5496, 5596), False, 'from Vector3 import Vector3\n'), ((688, 732), 'pygame.gfxdraw.pixel', 'gfxdraw.pixel', (['self.screen', 'p[0]', 'p[1]', 'p[2]'], {}), '(self.screen, p[0], p[1], p[2])\n', (701, 732), False, 'from pygame import gfxdraw\n'), ((1154, 1167), 'Vector2.Vector2', 'Vector2', (['(2)', '(2)'], {}), '(2, 2)\n', (1161, 1167), False, 'from Vector2 import Vector2\n'), ((1871, 1888), 'Vector3.Vector3', 'Vector3', (['x', 'y', 'sz'], {}), '(x, y, sz)\n', (1878, 1888), False, 'from Vector3 import Vector3\n'), ((4705, 4723), 'Vector3.Vector3', 'Vector3', (['x0', 'y0', '(0)'], {}), '(x0, y0, 0)\n', (4712, 4723), False, 'from Vector3 import Vector3\n'), ((5193, 5221), 'math.radians', 'math.radians', (['(fov_degree / 2)'], {}), '(fov_degree / 2)\n', (5205, 5221), False, 'import math, pygame\n'), ((5390, 5430), 'Vector4.Vector4', 'Vector4', (['vector.x', 'vector.y', 'vector.z', '(1)'], {}), '(vector.x, vector.y, vector.z, 1)\n', (5397, 5430), False, 'from Vector4 import Vector4\n'), ((6002, 6043), 'numpy.dot', 'np.dot', (['rotationMatrix', 'translationMatrix'], {}), '(rotationMatrix, translationMatrix)\n', (6008, 6043), True, 'import numpy as np\n'), ((9708, 9763), 'pygame.draw.polygon', 'pygame.draw.polygon', (['polygon[0]', 'polygon[1]', 'polygon[2]'], {}), '(polygon[0], polygon[1], polygon[2])\n', (9727, 9763), False, 'import math, pygame\n'), ((5958, 6001), 'Vector3.Vector3', 'Vector3', (['self.scale', 'self.scale', 'self.scale'], {}), '(self.scale, self.scale, self.scale)\n', (5965, 6001), False, 'from Vector3 import Vector3\n'), ((8586, 8602), 'Vector3.Vector3', 'Vector3', (['(3)', '(3)', '(3)'], {}), '(3, 3, 3)\n', (8593, 8602), False, 'from Vector3 import Vector3\n'), ((8660, 8676), 'Vector3.Vector3', 'Vector3', (['(3)', '(3)', '(3)'], {}), '(3, 3, 3)\n', (8667, 8676), False, 'from Vector3 import Vector3\n')]
import astropy.units as u from numpy.linalg import norm from .izzo import lambert as lambert_izzo class Maneuver: r"""Class to represent a Maneuver. Each ``Maneuver`` consists on a list of impulses :math:`\Delta v_i` (changes in velocity) each one applied at a certain instant :math:`t_i`. You can access them directly indexing the ``Maneuver`` object itself. >>> man = Maneuver((0 * u.s, [1, 0, 0] * u.km / u.s), ... (10 * u.s, [1, 0, 0] * u.km / u.s)) >>> man[0] (<Quantity 0. s>, <Quantity [1., 0., 0.] km / s>) >>> man.impulses[1] (<Quantity 10. s>, <Quantity [1., 0., 0.] km / s>) """ def __init__(self, *args): r"""Constructor. Parameters ---------- impulses : list List of pairs (delta_time, delta_velocity) """ self.impulses = args # HACK: Change API or validation code _dts, _dvs = zip(*args) self._dts, self._dvs = self._initialize( [(_dt * u.one).value for _dt in _dts] * (_dts[0] * u.one).unit, [(_dv * u.one).value for _dv in _dvs] * (_dvs[0] * u.one).unit, ) try: if not all(len(dv) == 3 for dv in self._dvs): raise TypeError except TypeError: raise ValueError("Delta-V must be three dimensions vectors") def __repr__(self): return f"Number of impulses: {len(self.impulses)}, Total cost: {self.get_total_cost():.6f}" @u.quantity_input(dts=u.s, dvs=u.m / u.s) def _initialize(self, dts, dvs): return dts, dvs # def __getitem__(self, key): # return self.impulses[key] @classmethod def lambert(cls, orbit_i, orbit_f, method=lambert_izzo, short=True, **kwargs): """Computes Lambert maneuver between two different points. Parameters ---------- orbit_i: ~poliastro.twobody.Orbit Initial orbit orbit_f: ~poliastro.twobody.Orbit Final orbit method: function Method for solving Lambert's problem short: keyword, boolean Selects between short and long solution """ # Get initial algorithm conditions k = orbit_i.attractor.k r_i = orbit_i.r r_f = orbit_f.r # Time of flight is solved by subtracting both orbit epochs tof = orbit_f.epoch - orbit_i.epoch # Compute all possible solutions to the Lambert transfer sols = list(method(k, r_i, r_f, tof, **kwargs)) # Return short or long solution if short: dv_a, dv_b = sols[0] else: dv_a, dv_b = sols[-1] return cls( (0 * u.s, (dv_a - orbit_i.v).decompose()), (tof.to(u.s), (orbit_f.v - dv_b).decompose()), ) def get_total_time(self): """Returns total time of the maneuver. """ total_time = sum(self._dts, 0 * u.s) return total_time def get_total_cost(self): """Returns total cost of the maneuver. """ dvs = [norm(dv) for dv in self._dvs] return sum(dvs, 0 * u.km / u.s)
[ "numpy.linalg.norm", "astropy.units.quantity_input" ]
[((1476, 1516), 'astropy.units.quantity_input', 'u.quantity_input', ([], {'dts': 'u.s', 'dvs': '(u.m / u.s)'}), '(dts=u.s, dvs=u.m / u.s)\n', (1492, 1516), True, 'import astropy.units as u\n'), ((3069, 3077), 'numpy.linalg.norm', 'norm', (['dv'], {}), '(dv)\n', (3073, 3077), False, 'from numpy.linalg import norm\n')]
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np import importlib from cosyai.dataset.base import _BaseDataset from cosyai.util import check_config_none class RandSet(_BaseDataset): def __init__(self, conf): super().__init__(conf) check_config_none(conf, ["input_dim", "output_dim", "dataset_size"]) self._create(conf.task, conf.input_dim, conf.output_dim, conf.dataset_size, conf.split_weight) self._transform(conf.backend) def _create(self, task, input_dim, output_dim, num, split_weight,): split_weight = split_weight or [7, 1, 2] x = np.random.rand(num, 1, input_dim,) if task == "classification": y = np.random.randint(0, 2, (num, output_dim)) elif task == "regression": y = np.random.rand(num, output_dim) else: raise NotImplementedError() indices = np.cumsum( np.asarray(split_weight) * num / np.sum(split_weight), dtype=int) self.train_set = x[:indices[0]], y[:indices[0]] self.eval_set = x[indices[0]:indices[1]], y[indices[0]:indices[1]] self.test_set = x[indices[1]:], y[indices[1]:] def _transform(self, backend): module = importlib.import_module('cosyai.backend.' + backend + '.util') self.train_set = module.data_transformer(*self.train_set) self.eval_set = module.data_transformer(*self.eval_set) self.test_set = module.data_transformer(*self.test_set)
[ "numpy.sum", "importlib.import_module", "numpy.asarray", "cosyai.util.check_config_none", "numpy.random.randint", "numpy.random.rand" ]
[((270, 338), 'cosyai.util.check_config_none', 'check_config_none', (['conf', "['input_dim', 'output_dim', 'dataset_size']"], {}), "(conf, ['input_dim', 'output_dim', 'dataset_size'])\n", (287, 338), False, 'from cosyai.util import check_config_none\n'), ((717, 750), 'numpy.random.rand', 'np.random.rand', (['num', '(1)', 'input_dim'], {}), '(num, 1, input_dim)\n', (731, 750), True, 'import numpy as np\n'), ((1334, 1396), 'importlib.import_module', 'importlib.import_module', (["('cosyai.backend.' + backend + '.util')"], {}), "('cosyai.backend.' + backend + '.util')\n", (1357, 1396), False, 'import importlib\n'), ((806, 848), 'numpy.random.randint', 'np.random.randint', (['(0)', '(2)', '(num, output_dim)'], {}), '(0, 2, (num, output_dim))\n', (823, 848), True, 'import numpy as np\n'), ((900, 931), 'numpy.random.rand', 'np.random.rand', (['num', 'output_dim'], {}), '(num, output_dim)\n', (914, 931), True, 'import numpy as np\n'), ((1061, 1081), 'numpy.sum', 'np.sum', (['split_weight'], {}), '(split_weight)\n', (1067, 1081), True, 'import numpy as np\n'), ((1028, 1052), 'numpy.asarray', 'np.asarray', (['split_weight'], {}), '(split_weight)\n', (1038, 1052), True, 'import numpy as np\n')]
''' Code from https://github.com/matheusgadelha/MRTNet/blob/master/models/AutoEncoder.py https://github.com/matheusgadelha/MRTNet/blob/master/models/MRTDecoder.py revised by <NAME> ''' import torch import torch.nn as nn import numpy as np import math from torch.nn import Sequential, Linear, ModuleList tree_arch = {} tree_arch[4] = [4, 8, 8, 8] tree_arch[6] = [2, 4, 4, 4, 4, 4] tree_arch[8] = [2, 2, 2, 2, 2, 4, 4, 4] tree_arch[11] = [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2] class SRTDecoder(nn.Module): def __init__(self, z_dim, nlevels, feat_dims, num_output_points): super(SRTDecoder, self).__init__() self.z_dim = z_dim self.nlevels = nlevels self.feat_dims = feat_dims self.num_output_points = num_output_points self.tarch, self.num_nodes = self.get_arch() self.base_size = int(self.tarch[0]) self.fc1 = Linear(self.z_dim, self.base_size * self.feat_dims[0]) upconv_list = [] for level in range(1, self.nlevels): upconv_list.append(self.upconv(level)) self.upconv_list = ModuleList(upconv_list) self.final_conv = nn.Sequential() self.final_conv.add_module('final_conv1', nn.ConvTranspose1d(self.feat_dims[-1], 32, kernel_size=1, stride=1, padding=0)) self.final_conv.add_module('relu_final', nn.ReLU(inplace=True)) self.final_conv.add_module('final_conv2', nn.ConvTranspose1d(32, 3, kernel_size=1, stride=1, padding=0)) self.final_conv.add_module('tanh_final', nn.Tanh()) def get_arch(self): logmult = int(math.log2(self.num_output_points / 2048)) tarch = tree_arch[self.nlevels] if self.num_output_points == 16384: while logmult > 0: last_min_pos = np.where(tarch == np.min(tarch))[0][-1] tarch[last_min_pos] *= 2 logmult -= 1 # number of node for each level num_nodes = [] for i, up_ratio in enumerate(tarch): if i == 0: num_nodes.append(up_ratio) else: last_num_node = num_nodes[-1] num_nodes.append(up_ratio * last_num_node) return tarch, num_nodes def upconv(self, level): in_channels = self.feat_dims[level-1] out_channels = self.feat_dims[level] up_ratio = self.tarch[level] return Sequential( nn.ConvTranspose1d(in_channels, out_channels, kernel_size=up_ratio, stride=up_ratio, padding=0), nn.LeakyReLU(0.2, inplace=True) ) def forward(self, z): batch_size = z.shape[0] node = self.fc1(z).view(batch_size, -1, self.base_size) for upconv in self.upconv_list: node = upconv(node) out = self.final_conv(node) out = torch.transpose(out, 1, 2).contiguous() return out
[ "torch.nn.ReLU", "torch.nn.Sequential", "torch.nn.ModuleList", "torch.nn.Tanh", "torch.nn.ConvTranspose1d", "numpy.min", "torch.nn.Linear", "torch.nn.LeakyReLU", "math.log2", "torch.transpose" ]
[((876, 930), 'torch.nn.Linear', 'Linear', (['self.z_dim', '(self.base_size * self.feat_dims[0])'], {}), '(self.z_dim, self.base_size * self.feat_dims[0])\n', (882, 930), False, 'from torch.nn import Sequential, Linear, ModuleList\n'), ((1088, 1111), 'torch.nn.ModuleList', 'ModuleList', (['upconv_list'], {}), '(upconv_list)\n', (1098, 1111), False, 'from torch.nn import Sequential, Linear, ModuleList\n'), ((1139, 1154), 'torch.nn.Sequential', 'nn.Sequential', ([], {}), '()\n', (1152, 1154), True, 'import torch.nn as nn\n'), ((1221, 1299), 'torch.nn.ConvTranspose1d', 'nn.ConvTranspose1d', (['self.feat_dims[-1]', '(32)'], {'kernel_size': '(1)', 'stride': '(1)', 'padding': '(0)'}), '(self.feat_dims[-1], 32, kernel_size=1, stride=1, padding=0)\n', (1239, 1299), True, 'import torch.nn as nn\n'), ((1366, 1387), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (1373, 1387), True, 'import torch.nn as nn\n'), ((1455, 1516), 'torch.nn.ConvTranspose1d', 'nn.ConvTranspose1d', (['(32)', '(3)'], {'kernel_size': '(1)', 'stride': '(1)', 'padding': '(0)'}), '(32, 3, kernel_size=1, stride=1, padding=0)\n', (1473, 1516), True, 'import torch.nn as nn\n'), ((1583, 1592), 'torch.nn.Tanh', 'nn.Tanh', ([], {}), '()\n', (1590, 1592), True, 'import torch.nn as nn\n'), ((1645, 1685), 'math.log2', 'math.log2', (['(self.num_output_points / 2048)'], {}), '(self.num_output_points / 2048)\n', (1654, 1685), False, 'import math\n'), ((2485, 2585), 'torch.nn.ConvTranspose1d', 'nn.ConvTranspose1d', (['in_channels', 'out_channels'], {'kernel_size': 'up_ratio', 'stride': 'up_ratio', 'padding': '(0)'}), '(in_channels, out_channels, kernel_size=up_ratio, stride=\n up_ratio, padding=0)\n', (2503, 2585), True, 'import torch.nn as nn\n'), ((2609, 2640), 'torch.nn.LeakyReLU', 'nn.LeakyReLU', (['(0.2)'], {'inplace': '(True)'}), '(0.2, inplace=True)\n', (2621, 2640), True, 'import torch.nn as nn\n'), ((2915, 2941), 'torch.transpose', 'torch.transpose', (['out', '(1)', '(2)'], {}), '(out, 1, 2)\n', (2930, 2941), False, 'import torch\n'), ((1851, 1864), 'numpy.min', 'np.min', (['tarch'], {}), '(tarch)\n', (1857, 1864), True, 'import numpy as np\n')]
# Copyright 2020 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. """ A few routines to generate random data """ from typing import Optional, Tuple import numpy as np from scipy.stats import cauchy, expon, gamma from .utils import iscomplex, tensor_H def crandn(*shape, dtype=np.complex128): """ wrapper for numpy.random.randn that can produce complex numbers """ out = np.zeros(shape, dtype=dtype) if iscomplex(out): out = np.random.randn(*shape) + 1j * np.random.randn(*shape) return out.astype(dtype) else: out = np.random.randn(*shape) return out.astype(dtype) def rand_psd(*shape, inner=None, dtype=np.complex): """ Random PSD matrices """ if inner is None: shape = shape + (shape[-1],) else: shape = shape + (inner,) X = crandn(*shape, dtype=dtype) V = X @ tensor_H(X) / shape[-1] return 0.5 * (V + tensor_H(V)) def circular_symmetric( loc=0, scale=1.0, dim=1, size=None, distrib="laplace", dtype=np.complex128 ): if size is None: size = [1] elif not isinstance(size, tuple): size = (size,) # generate first normal vectors out = crandn(*((dim,) + size), dtype=dtype) out /= np.linalg.norm(out, axis=0) # generate the norms according to exponential distribution if distrib == "laplace": # the marginal of the norm of symmetric circularl Laplace distributed # vectors is a gamma random variable with shape=dim and scale=1 if dtype in [np.complex128, np.complex64]: a = 2 * dim else: a = dim norms = gamma.rvs(a, size=size) elif distrib == "gauss": raise NotImplementedError norms = cauchy.rvs(loc=loc, scale=scale, size=size) else: raise NotImplementedError() out *= norms[None, ...] return out def rand_mixture( n_freq: int, n_sources: int, n_frames: int, distrib: Optional[str] = "laplace", scale: Optional[float] = 1.0, dtype: Optional[np.dtype] = np.complex128, ) -> Tuple[np.array, np.array, np.array]: A = crandn(n_freq, n_sources, n_sources, dtype=dtype) groundtruths = circular_symmetric( dim=n_freq, size=(n_sources, n_frames), distrib=distrib, scale=scale, dtype=dtype, ) mixtures = A @ groundtruths return mixtures, groundtruths, A
[ "scipy.stats.gamma.rvs", "numpy.random.randn", "numpy.zeros", "scipy.stats.cauchy.rvs", "numpy.linalg.norm" ]
[((1397, 1425), 'numpy.zeros', 'np.zeros', (['shape'], {'dtype': 'dtype'}), '(shape, dtype=dtype)\n', (1405, 1425), True, 'import numpy as np\n'), ((2233, 2260), 'numpy.linalg.norm', 'np.linalg.norm', (['out'], {'axis': '(0)'}), '(out, axis=0)\n', (2247, 2260), True, 'import numpy as np\n'), ((1575, 1598), 'numpy.random.randn', 'np.random.randn', (['*shape'], {}), '(*shape)\n', (1590, 1598), True, 'import numpy as np\n'), ((2629, 2652), 'scipy.stats.gamma.rvs', 'gamma.rvs', (['a'], {'size': 'size'}), '(a, size=size)\n', (2638, 2652), False, 'from scipy.stats import cauchy, expon, gamma\n'), ((1463, 1486), 'numpy.random.randn', 'np.random.randn', (['*shape'], {}), '(*shape)\n', (1478, 1486), True, 'import numpy as np\n'), ((2732, 2775), 'scipy.stats.cauchy.rvs', 'cauchy.rvs', ([], {'loc': 'loc', 'scale': 'scale', 'size': 'size'}), '(loc=loc, scale=scale, size=size)\n', (2742, 2775), False, 'from scipy.stats import cauchy, expon, gamma\n'), ((1494, 1517), 'numpy.random.randn', 'np.random.randn', (['*shape'], {}), '(*shape)\n', (1509, 1517), True, 'import numpy as np\n')]
""" Build JobStats (returned to the client after job completion) - based mostly on the DataFrame of collected metrics from the invoker and all workers. """ # Copyright 2021 The Funnel Rocket Maintainers # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import sys from typing import Optional, Union, List, Dict import pandas import numpy as np from pandas import DataFrame from frocket.common.config import config from frocket.common.dataset import DatasetPartsInfo, PartNamingMethod from frocket.common.tasks.base import JobStats, JobDatasetStats, JobInvokerStats, TimingStats, JobWorkerStats from frocket.invoker.metrics_frame import MetricsFrame, METRIC_NAME_COLUMN, METRIC_VALUE_COLUMN, METRIC_SOURCE_COLUMN from frocket.common.metrics import MetricName, ComponentLabel, SUCCESS_LABEL, MetricLabelEnum, \ WorkerStartupLabel, LoadFromLabel logger = logging.getLogger(__name__) TASK_COMPLETION_GRANULARITY_SECONDS = 0.25 # Data series of task success over time is measured in this resolution TIMING_PERCENTILES = [float(pct) for pct in config.get('stats.timing.percentiles').split(',')] MIN_METRICS_FOR_PERCENTILES = 20 # Below this sample count, don't return percentiles MIN_METRICS_FOR_99_PERCENTILE = 100 # Below this count, don't return 99th percentile # List of keys to pull from Pandas' describe() TIMING_DESCRIBE_KEYS = ['min', 'mean', 'max'] + [f"{int(pct*100)}%" for pct in TIMING_PERCENTILES] def build_stats(frame: MetricsFrame, parts_info: DatasetPartsInfo = None) -> JobStats: df = frame.dataframe if df is None: # In job failure cases return JobStats() if parts_info: ds_stats = JobDatasetStats(total_size=parts_info.total_size, parts=parts_info.total_parts) else: ds_stats = None # Invoker stats all_task_rows_df = _filter_by_label(df, ComponentLabel.WORKER) successful_task_rows_df = _filter_by_success(all_task_rows_df) total_tasks = _count_tasks(all_task_rows_df) failed_tasks = total_tasks - _count_tasks(successful_task_rows_df) invoker_stats = JobInvokerStats( enqueue_time=_sum_value(df, MetricName.ASYNC_ENQUEUE_SECONDS, single_value=True), poll_time=_sum_value(df, MetricName.ASYNC_POLL_SECONDS, single_value=True), total_tasks=total_tasks, failed_tasks=failed_tasks, task_success_over_time=_task_success_over_time(successful_task_rows_df) # TODO backlog add: lost_task_retries as counted by the invoker; support sync. invokers? ) # Worker stats worker_stats = JobWorkerStats( cold_tasks=_count_tasks(_filter_by_label(successful_task_rows_df, WorkerStartupLabel.COLD)), warm_tasks=_count_tasks(_filter_by_label(successful_task_rows_df, WorkerStartupLabel.WARM)), scanned_rows=_sum_value(successful_task_rows_df, MetricName.SCANNED_ROWS, as_int=True), scanned_groups=_sum_value(successful_task_rows_df, MetricName.SCANNED_GROUPS, as_int=True), cache=_cache_performance(successful_task_rows_df), invoke_latency=_timing_stats(successful_task_rows_df, MetricName.INVOKE_TO_RUN_SECONDS), load_time=_timing_stats(successful_task_rows_df, MetricName.TASK_TOTAL_LOAD_SECONDS), total_time=_timing_stats(successful_task_rows_df, MetricName.TASK_TOTAL_RUN_SECONDS) # TODO backlog add: loaded_column_types - mapping of column type to count, which affects load time ) job_stats = JobStats( total_time=_sum_value(df, MetricName.INVOKER_TOTAL_SECONDS, single_value=True), cost=_total_cost(df), dataset=ds_stats, invoker=invoker_stats, worker=worker_stats) return job_stats def _task_success_over_time(task_rows_df: DataFrame) -> Dict[float, int]: """Return a sparse series of data points - for each time slot (e.g. 0.25 secs) since the job started, return how many tasks completed successfully in that slot. Non-cumulative, does not include zeros.""" task_duration_rows = _filter_by_metrics( task_rows_df, metrics=[MetricName.INVOKE_TO_RUN_SECONDS, MetricName.TASK_TOTAL_RUN_SECONDS]) task_durations = task_duration_rows.groupby(METRIC_SOURCE_COLUMN)[METRIC_VALUE_COLUMN].sum() quantized_task_durations = \ np.ceil(task_durations / TASK_COMPLETION_GRANULARITY_SECONDS) * TASK_COMPLETION_GRANULARITY_SECONDS return quantized_task_durations.value_counts().sort_index().to_dict() def _cache_performance(task_rows_df: DataFrame) -> Dict[str, int]: return { # Note the 'source' is always the case for locally-loaded files, in which case caching is N/A. 'source': _count_tasks(_filter_by_label(task_rows_df, LoadFromLabel.SOURCE)), 'diskCache': _count_tasks(_filter_by_label(task_rows_df, LoadFromLabel.DISK_CACHE)) } def _sum_value(df: DataFrame, metric: MetricName, single_value: bool = False, as_int: bool = False) -> Union[float, int, None]: df = _filter_by_metrics(df, metric) if single_value: assert len(df) <= 1 if df.empty: return None else: values_sum = df[METRIC_VALUE_COLUMN].sum() return int(values_sum) if as_int else float(values_sum) def _count(df: DataFrame, metric: MetricName) -> int: return _filter_by_metrics(df, metric)[METRIC_VALUE_COLUMN].count() def _timing_stats(task_rows_df: DataFrame, metric: MetricName) -> TimingStats: values_df = _filter_by_metrics(task_rows_df, metric)[METRIC_VALUE_COLUMN] if len(values_df) < MIN_METRICS_FOR_PERCENTILES: percentiles = [0.5] else: percentiles = TIMING_PERCENTILES if len(values_df) < MIN_METRICS_FOR_99_PERCENTILE: percentiles = [pct for pct in percentiles if pct < 0.99] raw_stats = values_df.describe(percentiles=percentiles).to_dict() return {k: v for k, v in raw_stats.items() if k in TIMING_DESCRIBE_KEYS and not np.isnan(v)} def _filter_by_metrics(df: DataFrame, metrics: Union[MetricName, List[MetricName]]) -> DataFrame: if type(metrics) is MetricName: return df[df[METRIC_NAME_COLUMN] == metrics.name] else: return df[df[METRIC_NAME_COLUMN].isin([m.name for m in metrics])] def _filter_by_label(df: DataFrame, label: MetricLabelEnum) -> DataFrame: return df[df[label.label_name] == label.label_value.lower()] def _filter_by_success(df: DataFrame, value: bool = True) -> DataFrame: return df[df[SUCCESS_LABEL] == str(value)] def _count_tasks(task_rows_df: DataFrame) -> int: """Each task attempt (e.g. task index 117, attempt 2) has a unique name in the source column, which ofc appears in multiple rows. This count the unique count of task attempt IDs in the given DF.""" return task_rows_df[METRIC_SOURCE_COLUMN].nunique() def _total_cost(df: DataFrame) -> Optional[float]: cost_reports_df = _filter_by_metrics(df, MetricName.COST_DOLLARS) num_reports = len(cost_reports_df) if num_reports == 0: logger.debug(f"Total cost: no metrics found") return None else: total_cost = float(cost_reports_df[METRIC_VALUE_COLUMN].sum()) logger.debug(f"Total cost: ${total_cost:.6f} (sum of {num_reports} metric reports)") return total_cost # Stand-alone testing if __name__ == "__main__": config.init_logging(force_level=logging.DEBUG, force_console_output=True) filename = config.get('metrics.export.lastrun', None) if not filename: sys.exit('No lastrun file defined') df = pandas.read_parquet(filename) dummy_frame = MetricsFrame([]) dummy_frame._df = df dummy_parts_info = DatasetPartsInfo(naming_method=PartNamingMethod.LIST, total_parts=4, total_size=1024) build_stats(dummy_frame, dummy_parts_info)
[ "frocket.invoker.metrics_frame.MetricsFrame", "frocket.common.config.config.init_logging", "numpy.ceil", "frocket.common.config.config.get", "frocket.common.tasks.base.JobDatasetStats", "sys.exit", "numpy.isnan", "pandas.read_parquet", "frocket.common.tasks.base.JobStats", "frocket.common.dataset....
[((1379, 1406), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1396, 1406), False, 'import logging\n'), ((7793, 7866), 'frocket.common.config.config.init_logging', 'config.init_logging', ([], {'force_level': 'logging.DEBUG', 'force_console_output': '(True)'}), '(force_level=logging.DEBUG, force_console_output=True)\n', (7812, 7866), False, 'from frocket.common.config import config\n'), ((7882, 7924), 'frocket.common.config.config.get', 'config.get', (['"""metrics.export.lastrun"""', 'None'], {}), "('metrics.export.lastrun', None)\n", (7892, 7924), False, 'from frocket.common.config import config\n'), ((8000, 8029), 'pandas.read_parquet', 'pandas.read_parquet', (['filename'], {}), '(filename)\n', (8019, 8029), False, 'import pandas\n'), ((8048, 8064), 'frocket.invoker.metrics_frame.MetricsFrame', 'MetricsFrame', (['[]'], {}), '([])\n', (8060, 8064), False, 'from frocket.invoker.metrics_frame import MetricsFrame, METRIC_NAME_COLUMN, METRIC_VALUE_COLUMN, METRIC_SOURCE_COLUMN\n'), ((8113, 8202), 'frocket.common.dataset.DatasetPartsInfo', 'DatasetPartsInfo', ([], {'naming_method': 'PartNamingMethod.LIST', 'total_parts': '(4)', 'total_size': '(1024)'}), '(naming_method=PartNamingMethod.LIST, total_parts=4,\n total_size=1024)\n', (8129, 8202), False, 'from frocket.common.dataset import DatasetPartsInfo, PartNamingMethod\n'), ((2108, 2118), 'frocket.common.tasks.base.JobStats', 'JobStats', ([], {}), '()\n', (2116, 2118), False, 'from frocket.common.tasks.base import JobStats, JobDatasetStats, JobInvokerStats, TimingStats, JobWorkerStats\n'), ((2158, 2237), 'frocket.common.tasks.base.JobDatasetStats', 'JobDatasetStats', ([], {'total_size': 'parts_info.total_size', 'parts': 'parts_info.total_parts'}), '(total_size=parts_info.total_size, parts=parts_info.total_parts)\n', (2173, 2237), False, 'from frocket.common.tasks.base import JobStats, JobDatasetStats, JobInvokerStats, TimingStats, JobWorkerStats\n'), ((4743, 4804), 'numpy.ceil', 'np.ceil', (['(task_durations / TASK_COMPLETION_GRANULARITY_SECONDS)'], {}), '(task_durations / TASK_COMPLETION_GRANULARITY_SECONDS)\n', (4750, 4804), True, 'import numpy as np\n'), ((7954, 7989), 'sys.exit', 'sys.exit', (['"""No lastrun file defined"""'], {}), "('No lastrun file defined')\n", (7962, 7989), False, 'import sys\n'), ((1567, 1605), 'frocket.common.config.config.get', 'config.get', (['"""stats.timing.percentiles"""'], {}), "('stats.timing.percentiles')\n", (1577, 1605), False, 'from frocket.common.config import config\n'), ((6410, 6421), 'numpy.isnan', 'np.isnan', (['v'], {}), '(v)\n', (6418, 6421), True, 'import numpy as np\n')]
import warnings from io import BytesIO from tempfile import NamedTemporaryFile import onnx import torch.nn from torch.nn import Module import torch.nn.functional as F from torchvision import models from numpy.testing import assert_almost_equal import numpy as np import tensorflow as tf from onnx2keras import onnx2keras, compatible_data_format, OnnxConstant, OnnxTensor, InterleavedImageBatch, \ ensure_data_format, OptimizationMissingWarning def make_onnx_model(net, indata, opset_version=None): fd = BytesIO() torch.onnx.export(net, indata, fd, opset_version=opset_version) # with open("/tmp/t.onnx", "wb") as debug: torch.onnx.export(net, indata, debug, opset_version=opset_version) fd.seek(0) return onnx.load(fd) def convert_and_compare_output(net, indata, precition=5, image_out=True, savable=True, missing_optimizations=False, opset_version=None): try: return _convert_and_compare_output(net, indata, precition, image_out, savable, missing_optimizations, opset_version) except AssertionError: return _convert_and_compare_output(net, indata, precition, image_out, savable, missing_optimizations, opset_version) def _convert_and_compare_output(net, indata, precition=5, image_out=True, savable=True, missing_optimizations=False, opset_version=None): torch_indata = torch.tensor(indata) y1 = net(torch_indata).detach().numpy() onnx_model = make_onnx_model(net, torch.zeros_like(torch_indata), opset_version) with warnings.catch_warnings(record=True) as warns: warnings.simplefilter("always") kernas_net = onnx2keras(onnx_model) warns = [w for w in warns if w.category is OptimizationMissingWarning] if not missing_optimizations: assert len(warns) == 0 if savable: with NamedTemporaryFile() as f: f.close() kernas_net.save(f.name) y2 = kernas_net.predict(indata.transpose(0, 2, 3, 1)) if image_out: y2 = y2.transpose(0, 3, 1, 2) assert_almost_equal(y1, y2, precition) return kernas_net class GlobalAvgPool(Module): def forward(self, x): return x.mean([2, 3]) class TestUtils: def test_compatible_data_format(self): assert compatible_data_format(OnnxConstant, OnnxConstant) assert compatible_data_format(OnnxTensor, OnnxTensor) assert compatible_data_format(OnnxConstant, OnnxTensor) assert compatible_data_format(OnnxTensor, OnnxConstant) assert compatible_data_format(InterleavedImageBatch, InterleavedImageBatch) assert not compatible_data_format(OnnxTensor, InterleavedImageBatch) assert not compatible_data_format(OnnxConstant, InterleavedImageBatch) assert not compatible_data_format(InterleavedImageBatch, OnnxTensor) assert not compatible_data_format(InterleavedImageBatch, OnnxConstant) class TestOnnx: def test_conv(self): net = torch.nn.Sequential(torch.nn.Conv2d(3, 16, 7), torch.nn.ReLU()) x = np.random.rand(1, 3, 224, 224).astype(np.float32) convert_and_compare_output(net, x) def test_conv_no_bias(self): net = torch.nn.Sequential(torch.nn.Conv2d(3, 16, 7, bias=False), torch.nn.ReLU()) x = np.random.rand(1, 3, 224, 224).astype(np.float32) convert_and_compare_output(net, x) def test_conv_padding(self): net = torch.nn.Sequential(torch.nn.Conv2d(1, 16, 3, padding=1), torch.nn.ReLU()) x = np.random.rand(1, 1, 224, 224).astype(np.float32) convert_and_compare_output(net, x) def test_prelu(self): net = torch.nn.Sequential(torch.nn.Conv2d(3, 16, 7), torch.nn.PReLU()) x = np.random.rand(1, 3, 224, 224).astype(np.float32) convert_and_compare_output(net, x) def test_prelu_per_channel(self): act = torch.nn.PReLU(num_parameters=16) with torch.no_grad(): act.weight[:] = torch.tensor(range(16)) net = torch.nn.Sequential(torch.nn.Conv2d(3, 16, 7), act) x = np.random.rand(1, 3, 224, 224).astype(np.float32) convert_and_compare_output(net, x, 5) def test_maxpool(self): net = torch.nn.Sequential(torch.nn.MaxPool2d(2)) x = np.random.rand(1, 3, 224, 224).astype(np.float32) convert_and_compare_output(net, x) def test_maxpool_resnet(self): net = torch.nn.MaxPool2d(kernel_size=3, stride=2, padding=1) x = np.random.rand(1, 192, 272, 64).astype(np.float32) convert_and_compare_output(net, x) def test_concat(self): for axis in range(1,4): class Dbl(torch.nn.Module): def forward(self, x): return torch.cat((x, x), axis) x = np.random.rand(1, 3, 224, 224).astype(np.float32) convert_and_compare_output(Dbl(), x) def test_conv_transpose(self): net = torch.nn.Sequential(torch.nn.ConvTranspose2d(3, 16, 5, 2), torch.nn.ReLU()) x = np.random.rand(1, 3, 112, 112).astype(np.float32) convert_and_compare_output(net, x) def test_conv_transpose_padding(self): net = torch.nn.Sequential(torch.nn.ConvTranspose2d(3, 16, 4, 2, padding=1), torch.nn.ReLU()) x = np.random.rand(1, 3, 112, 112).astype(np.float32) convert_and_compare_output(net, x) def test_conv_different_padding(self): net = torch.nn.Sequential(torch.nn.Conv2d(3, 64, kernel_size=7, stride=1, padding=(3, 4))) x = np.random.rand(1, 3, 384, 544).astype(np.float32) convert_and_compare_output(net, x) def test_conv_transpose_no_bias(self): net = torch.nn.Sequential(torch.nn.ConvTranspose2d(3, 16, 5, 2, bias=False), torch.nn.ReLU()) x = np.random.rand(1, 3, 112, 112).astype(np.float32) convert_and_compare_output(net, x) def test_conv_transpose_grouped_no_bias(self): net = torch.nn.Sequential(torch.nn.ConvTranspose2d(16, 16, 5, 2, groups=2, bias=False), torch.nn.ReLU()) x = np.random.rand(1, 16, 112, 112).astype(np.float32) convert_and_compare_output(net, x) def test_conv_transpose_grouped_bias(self): net = torch.nn.Sequential(torch.nn.ConvTranspose2d(16, 16, 5, 2, groups=2), torch.nn.ReLU()) x = np.random.rand(1, 16, 112, 112).astype(np.float32) convert_and_compare_output(net, x) def test_conv_transpose_grouped_fully(self): net = torch.nn.Sequential(torch.nn.ConvTranspose2d(16, 16, 5, 2, groups=16), torch.nn.ReLU()) x = np.random.rand(1, 16, 112, 112).astype(np.float32) convert_and_compare_output(net, x) def test_conv_transpose_output_padding(self): net = torch.nn.Sequential(torch.nn.ConvTranspose2d(16, 16, 3, 2, output_padding=1), torch.nn.ReLU()) x = np.random.rand(1, 16, 112, 112).astype(np.float32) convert_and_compare_output(net, x) def test_conv_stride2_padding_strange(self): net = torch.nn.Sequential(torch.nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3)) x = np.random.rand(1, 3, 384, 544).astype(np.float32) convert_and_compare_output(net, x) def test_conv_stride2_padding_simple_odd(self): net = torch.nn.Sequential(torch.nn.Conv2d(3, 64, kernel_size=3, stride=2, padding=1)) x = np.random.rand(1, 3, 223, 223).astype(np.float32) kernas_net = convert_and_compare_output(net, x) assert [l.__class__.__name__ for l in kernas_net.layers] == ['InputLayer', 'Conv2D'] def test_conv_stride2_padding_simple_even(self): net = torch.nn.Sequential(torch.nn.Conv2d(3, 64, kernel_size=3, stride=2, padding=1)) x = np.random.rand(1, 3, 224, 224).astype(np.float32) kernas_net = convert_and_compare_output(net, x) # assert [l.__class__.__name__ for l in kernas_net.layers] == ['InputLayer', 'Conv2D'] def test_batchnorm(self): bn = torch.nn.BatchNorm2d(3) bn.running_mean.uniform_() bn.running_var.uniform_() net = torch.nn.Sequential(bn, torch.nn.ReLU()) net.eval() x = np.random.rand(1, 3, 224, 224).astype(np.float32) convert_and_compare_output(net, x) def test_batchnorm1d(self): bn = torch.nn.BatchNorm1d(3) bn.running_mean.uniform_() bn.running_var.uniform_() net = torch.nn.Sequential(GlobalAvgPool(), bn, torch.nn.ReLU()) net.eval() x = np.random.rand(1, 3, 224, 224).astype(np.float32) convert_and_compare_output(net, x, image_out=False) def test_clamp(self): class Clamp(Module): def forward(self, x): return torch.clamp(x, 0.3, 0.7) net = torch.nn.Sequential(torch.nn.ReLU(), Clamp(), torch.nn.ReLU()) x = np.random.rand(1, 3, 224, 224).astype(np.float32) convert_and_compare_output(net, x, savable=False) def test_relu6(self): class Clamp(Module): def forward(self, x): return torch.clamp(x, 0, 6) net = torch.nn.Sequential(torch.nn.ReLU(), Clamp(), torch.nn.ReLU()) x = np.random.rand(1, 3, 224, 224).astype(np.float32) convert_and_compare_output(net, x) def test_leaky_relu(self): net = torch.nn.Sequential(torch.nn.Conv2d(3, 3, 3), torch.nn.LeakyReLU(), torch.nn.Conv2d(3, 3, 3)) x = np.random.rand(1, 3, 224, 224).astype(np.float32) convert_and_compare_output(net, x) def test_depthwise(self): net = torch.nn.Sequential(torch.nn.Conv2d(3, 3, 7, groups=3), torch.nn.ReLU()) x = np.random.rand(1, 3, 224, 224).astype(np.float32) convert_and_compare_output(net, x) def test_groupwise(self): net = torch.nn.Conv2d(8, 8, 7, groups=4) x = np.random.rand(1, 8, 224, 224).astype(np.float32) convert_and_compare_output(net, x) def test_depthwise_no_bias(self): net = torch.nn.Sequential(torch.nn.Conv2d(3, 3, 7, groups=3, bias=False), torch.nn.ReLU()) x = np.random.rand(1, 3, 224, 224).astype(np.float32) convert_and_compare_output(net, x) def test_add(self): class AddTst(Module): def __init__(self): Module.__init__(self) self.conv1 = torch.nn.Conv2d(3, 3, 7) self.conv2 = torch.nn.Conv2d(3, 3, 7) def forward(self, x): return self.conv1(x).relu_() + self.conv2(x).relu_() net = torch.nn.Sequential(AddTst(), torch.nn.ReLU()) x = np.random.rand(1, 3, 224, 224).astype(np.float32) convert_and_compare_output(net, x) def test_global_avrage_pooling(self): net = torch.nn.Sequential(GlobalAvgPool(), torch.nn.ReLU()) x = np.random.rand(1, 3, 16, 16).astype(np.float32) convert_and_compare_output(net, x, image_out=False) def test_dropout(self): net = torch.nn.Sequential(GlobalAvgPool(), torch.nn.Dropout(), torch.nn.ReLU()) net.eval() x = np.random.rand(1, 3, 16, 16).astype(np.float32) convert_and_compare_output(net, x, image_out=False) def test_linear(self): net = torch.nn.Sequential(GlobalAvgPool(), torch.nn.Linear(3, 8), torch.nn.ReLU()) net.eval() x = np.random.rand(5, 3, 16, 16).astype(np.float32) convert_and_compare_output(net, x, image_out=False) def test_linear_no_bias(self): net = torch.nn.Sequential(GlobalAvgPool(), torch.nn.Linear(3, 8, bias=False), torch.nn.ReLU()) net.eval() x = np.random.rand(5, 3, 16, 16).astype(np.float32) convert_and_compare_output(net, x, image_out=False) def test_mobilenet_v2(self): net = models.mobilenet_v2() net.eval() x = np.random.rand(1, 3, 224, 224).astype(np.float32) convert_and_compare_output(net, x, image_out=False) def test_avg_pool_pad(self): class PadTst(Module): def forward(self, x): return F.avg_pool2d(x, kernel_size=3, stride=1, padding=1) net = torch.nn.Sequential(PadTst(), torch.nn.ReLU()) x = np.random.rand(1, 3, 224, 224).astype(np.float32) convert_and_compare_output(net, x) def test_avg_pool_pad_asym(self): class PadTst(Module): def forward(self, x): return F.avg_pool2d(x, kernel_size=(3, 6), stride=(1, 2), padding=(1, 2)) net = torch.nn.Sequential(PadTst(), torch.nn.ReLU()) x = np.random.rand(1, 3, 224, 224).astype(np.float32) convert_and_compare_output(net, x) def test_gloabl_avg_pool(self): class AvgTst(Module): def forward(self, x): return F.adaptive_avg_pool2d(x, (1, 1)) net = torch.nn.Sequential(AvgTst(), torch.nn.ReLU()) x = np.random.rand(1, 3, 224, 224).astype(np.float32) convert_and_compare_output(net, x) def test_flatten(self): class Tst(Module): def forward(self, x): return torch.flatten(x, 1) net = torch.nn.Sequential(Tst(), torch.nn.ReLU()) x = np.random.rand(1, 3, 1, 1).astype(np.float32) convert_and_compare_output(net, x, image_out=False) def test_vector_pad(self): class VectorPad2D(Module): def forward(self, x): tt = [torch.nn.functional.pad(x[:, i:i + 1], [1,1,1,1], 'constant', [1,2,3][i]) for i in range(x.shape[1])] return torch.cat(tt, 1) net = torch.nn.Sequential(VectorPad2D(), torch.nn.ReLU()) x = np.random.rand(2, 3, 5, 5).astype(np.float32) convert_and_compare_output(net, x) def test_vector_pad_addhack(self): class VectorPad2D(Module): def forward(self, x): c = torch.tensor([1,2,3]).reshape(1, 3, 1, 1) return torch.nn.functional.pad(x - c, [1,1,1,1]) + c net = torch.nn.Sequential(VectorPad2D(), torch.nn.ReLU()) x = np.random.rand(1, 3, 5, 5).astype(np.float32) convert_and_compare_output(net, x) def test_vector_pad_addhack_asym(self): class VectorPad2D(Module): def forward(self, x): c = torch.tensor([1,2,3]).reshape(1, 3, 1, 1) return torch.nn.functional.pad(x - c, [1,0,1,0]) + c net = torch.nn.Sequential(VectorPad2D(), torch.nn.ReLU()) x = np.random.rand(1, 3, 5, 5).astype(np.float32) convert_and_compare_output(net, x) def test_sigmoid(self): net = torch.nn.Sequential(torch.nn.Conv2d(3, 16, 7), torch.nn.Sigmoid()) x = np.random.rand(1, 3, 224, 224).astype(np.float32) convert_and_compare_output(net, x) def test_upsample_nearest(self): net = torch.nn.Sequential(torch.nn.UpsamplingNearest2d(scale_factor=2), torch.nn.ReLU()) x = np.random.rand(1, 3, 32, 32).astype(np.float32) convert_and_compare_output(net, x) def test_upsample_nearest_v11(self): net = torch.nn.Sequential(torch.nn.UpsamplingNearest2d(scale_factor=2), torch.nn.ReLU()) x = np.random.rand(1, 3, 32, 32).astype(np.float32) convert_and_compare_output(net, x, opset_version=11) def test_upsample_bilinear(self): net = torch.nn.Sequential(torch.nn.UpsamplingBilinear2d(scale_factor=2), torch.nn.ReLU()) x = np.random.rand(1, 3, 32, 32).astype(np.float32) convert_and_compare_output(net, x, opset_version=11) def test_interpolate_nearest(self): class Net(Module): def forward(self, x): return F.interpolate(x, scale_factor=2, mode="nearest") net = torch.nn.Sequential(Net(), torch.nn.ReLU()) x = np.random.rand(1, 3, 32, 32).astype(np.float32) convert_and_compare_output(net, x) def test_interpolate_bilinear(self): class Net(Module): def forward(self, x): return F.interpolate(x, scale_factor=2, mode="bilinear", align_corners=True) net = torch.nn.Sequential(Net(), torch.nn.ReLU()) x = np.random.rand(1, 3, 32, 32).astype(np.float32) convert_and_compare_output(net, x, opset_version=11) def test_eq_mul(self): class EqProd(Module): def forward(self, x): maxmap = F.max_pool2d(x, 3, 1, 1, 1, False, False) return x * (maxmap == x) net = torch.nn.Sequential(EqProd(), torch.nn.ReLU()) x = np.random.rand(1, 3, 5, 5).astype(np.float32) convert_and_compare_output(net, x) def test_adaptive_avgpool_reshape(self): class Net(Module): def forward(self, x): return F.adaptive_avg_pool2d(x, 1).reshape(x.shape[0], -1) net = torch.nn.Sequential(Net(), torch.nn.ReLU()) x = np.random.rand(1, 3, 16, 16).astype(np.float32) convert_and_compare_output(net, x, image_out=False) x = np.random.rand(4, 3, 16, 16).astype(np.float32) convert_and_compare_output(net, x, image_out=False) def test_bmm(self): class Net(Module): def forward(self, x): x = x.reshape(1, 16, 16) return torch.bmm(x, x) net = torch.nn.Sequential(Net(), torch.nn.ReLU()) x = np.random.rand(1, 1, 16, 16).astype(np.float32) convert_and_compare_output(net, x, image_out=False) def test_matmul(self): class Net(Module): def forward(self, x): x = x.reshape(1, 1, 16, 16) return torch.matmul(x, x) net = torch.nn.Sequential(Net(), torch.nn.ReLU()) x = np.random.rand(1, 1, 16, 16).astype(np.float32) convert_and_compare_output(net, x, image_out=False) def test_unsupported_optimasation(self): class Reshape(Module): def forward(self, x): return x.reshape(4, 4, 16, 16) net = torch.nn.Sequential(GlobalAvgPool(), torch.nn.Linear(3, 4 * 16 * 16), Reshape(), torch.nn.Conv2d(4, 3, 3), torch.nn.ReLU()) net.eval() x = np.random.rand(4, 3, 16, 16).astype(np.float32) convert_and_compare_output(net, x, missing_optimizations=True) def test_sqrt(self): class Sq(Module): def forward(self, x): return torch.sqrt(x) net = torch.nn.Sequential(Sq(), torch.nn.ReLU()) x = np.random.rand(4, 3, 16, 16).astype(np.float32) is_tf1 = tuple(map(int, tf.__version__.split('.'))) < (2, 0, 0) convert_and_compare_output(net, x, savable=(not is_tf1)) def test_abs(self): class Abs(Module): def forward(self, x): return torch.abs(x) net = torch.nn.Sequential(Abs(), torch.nn.ReLU()) x = np.random.rand(4, 3, 16, 16).astype(np.float32) convert_and_compare_output(net, x) def test_neg(self): class Neg(Module): def forward(self, x): return -x net = torch.nn.Sequential(Neg(), torch.nn.ReLU()) x = np.random.rand(4, 3, 16, 16).astype(np.float32) convert_and_compare_output(net, x) def test_center_crop(self): class CenterCrop8x8(Module): def forward(self, x): n, c, h, w = x.shape dx = (w - 8) // 2 dy = (h - 8) // 2 crop = x[:, :, dy:dy+8, dx:dx+8] return crop net = torch.nn.Sequential(CenterCrop8x8(), torch.nn.ReLU()) x = np.random.rand(4, 3, 16, 32).astype(np.float32) convert_and_compare_output(net, x, opset_version=11) def test_mul(self): class Mul(Module): def forward(self, x): return x * x net = torch.nn.Sequential(Mul(), torch.nn.ReLU()) x = np.random.rand(4, 3, 16, 32).astype(np.float32) convert_and_compare_output(net, x, opset_version=11) def test_mul_const(self): class Mul(Module): def forward(self, x): return (2 * x) * (x * 2) net = torch.nn.Sequential(Mul(), torch.nn.ReLU()) x = np.random.rand(4, 3, 16, 32).astype(np.float32) convert_and_compare_output(net, x, opset_version=11) def test_concat_for_OnnxTensor(self): batch = 4 class Net(Module): def __init__(self): super().__init__() self.conv1 = torch.nn.Conv2d(3, 4, 5) self.conv2 = torch.nn.Conv2d(3, 4, 5) self.ClassHead = torch.nn.ModuleList([torch.nn.Conv2d(4, 16, 3), torch.nn.Conv2d(4, 16, 3)]) def forward(self, x): features = [self.conv1(x), self.conv2(x)] classifications = torch.cat([self.ClassHead[i](feature).reshape(batch, -1, 2) for i, feature in enumerate(features)], dim=1) return classifications x = np.random.rand(batch, 3, 16, 32).astype(np.float32) convert_and_compare_output(Net(), x, missing_optimizations=True, image_out=False) def test_transpose_to_onnx_testor(self): class Net(Module): def forward(self, x): return x.permute(0,2,3,1) x = np.random.rand(2, 3, 16, 32).astype(np.float32) convert_and_compare_output(Net(), x, image_out=False) def test_concat_for_OnnxTensor_optimized(self): batch = 4 class Net(Module): def __init__(self): super().__init__() self.conv1 = torch.nn.Conv2d(3, 4, 5) self.conv2 = torch.nn.Conv2d(3, 4, 5) self.ClassHead = torch.nn.ModuleList([torch.nn.Conv2d(4, 16, 3), torch.nn.Conv2d(4, 16, 3)]) def forward(self, x): features = [self.conv1(x), self.conv2(x)] classifications = torch.cat([self.ClassHead[i](feature).permute(0,2,3,1).reshape(batch, -1, 2) for i, feature in enumerate(features)], dim=1) return classifications x = np.random.rand(batch, 3, 16, 32).astype(np.float32) convert_and_compare_output(Net(), x, image_out=False) def test_gather(self): class Net(Module): def forward(self, x): return x.permute(0,2,3,1).select(2,1) net = torch.nn.Sequential(Net(), torch.nn.ReLU()) x = np.random.rand(2, 3, 16, 32).astype(np.float32) convert_and_compare_output(net, x, image_out=False) # def test_inception_v3(self): # net = models.Inception3(aux_logits=False) # net.eval() # x = np.random.rand(1, 3, 299, 299).astype(np.float32) # convert_and_compare_output(net, x, image_out=False)
[ "tempfile.NamedTemporaryFile", "io.BytesIO", "warnings.simplefilter", "numpy.testing.assert_almost_equal", "onnx2keras.onnx2keras", "torch.nn.functional.avg_pool2d", "tensorflow.__version__.split", "torch.nn.functional.adaptive_avg_pool2d", "warnings.catch_warnings", "torch.nn.Module.__init__", ...
[((515, 524), 'io.BytesIO', 'BytesIO', ([], {}), '()\n', (522, 524), False, 'from io import BytesIO\n'), ((733, 746), 'onnx.load', 'onnx.load', (['fd'], {}), '(fd)\n', (742, 746), False, 'import onnx\n'), ((2004, 2042), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['y1', 'y2', 'precition'], {}), '(y1, y2, precition)\n', (2023, 2042), False, 'from numpy.testing import assert_almost_equal\n'), ((1489, 1525), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {'record': '(True)'}), '(record=True)\n', (1512, 1525), False, 'import warnings\n'), ((1544, 1575), 'warnings.simplefilter', 'warnings.simplefilter', (['"""always"""'], {}), "('always')\n", (1565, 1575), False, 'import warnings\n'), ((1597, 1619), 'onnx2keras.onnx2keras', 'onnx2keras', (['onnx_model'], {}), '(onnx_model)\n', (1607, 1619), False, 'from onnx2keras import onnx2keras, compatible_data_format, OnnxConstant, OnnxTensor, InterleavedImageBatch, ensure_data_format, OptimizationMissingWarning\n'), ((2228, 2278), 'onnx2keras.compatible_data_format', 'compatible_data_format', (['OnnxConstant', 'OnnxConstant'], {}), '(OnnxConstant, OnnxConstant)\n', (2250, 2278), False, 'from onnx2keras import onnx2keras, compatible_data_format, OnnxConstant, OnnxTensor, InterleavedImageBatch, ensure_data_format, OptimizationMissingWarning\n'), ((2294, 2340), 'onnx2keras.compatible_data_format', 'compatible_data_format', (['OnnxTensor', 'OnnxTensor'], {}), '(OnnxTensor, OnnxTensor)\n', (2316, 2340), False, 'from onnx2keras import onnx2keras, compatible_data_format, OnnxConstant, OnnxTensor, InterleavedImageBatch, ensure_data_format, OptimizationMissingWarning\n'), ((2356, 2404), 'onnx2keras.compatible_data_format', 'compatible_data_format', (['OnnxConstant', 'OnnxTensor'], {}), '(OnnxConstant, OnnxTensor)\n', (2378, 2404), False, 'from onnx2keras import onnx2keras, compatible_data_format, OnnxConstant, OnnxTensor, InterleavedImageBatch, ensure_data_format, OptimizationMissingWarning\n'), ((2420, 2468), 'onnx2keras.compatible_data_format', 'compatible_data_format', (['OnnxTensor', 'OnnxConstant'], {}), '(OnnxTensor, OnnxConstant)\n', (2442, 2468), False, 'from onnx2keras import onnx2keras, compatible_data_format, OnnxConstant, OnnxTensor, InterleavedImageBatch, ensure_data_format, OptimizationMissingWarning\n'), ((2484, 2552), 'onnx2keras.compatible_data_format', 'compatible_data_format', (['InterleavedImageBatch', 'InterleavedImageBatch'], {}), '(InterleavedImageBatch, InterleavedImageBatch)\n', (2506, 2552), False, 'from onnx2keras import onnx2keras, compatible_data_format, OnnxConstant, OnnxTensor, InterleavedImageBatch, ensure_data_format, OptimizationMissingWarning\n'), ((11595, 11616), 'torchvision.models.mobilenet_v2', 'models.mobilenet_v2', ([], {}), '()\n', (11614, 11616), False, 'from torchvision import models\n'), ((1801, 1821), 'tempfile.NamedTemporaryFile', 'NamedTemporaryFile', ([], {}), '()\n', (1819, 1821), False, 'from tempfile import NamedTemporaryFile\n'), ((2572, 2629), 'onnx2keras.compatible_data_format', 'compatible_data_format', (['OnnxTensor', 'InterleavedImageBatch'], {}), '(OnnxTensor, InterleavedImageBatch)\n', (2594, 2629), False, 'from onnx2keras import onnx2keras, compatible_data_format, OnnxConstant, OnnxTensor, InterleavedImageBatch, ensure_data_format, OptimizationMissingWarning\n'), ((2649, 2708), 'onnx2keras.compatible_data_format', 'compatible_data_format', (['OnnxConstant', 'InterleavedImageBatch'], {}), '(OnnxConstant, InterleavedImageBatch)\n', (2671, 2708), False, 'from onnx2keras import onnx2keras, compatible_data_format, OnnxConstant, OnnxTensor, InterleavedImageBatch, ensure_data_format, OptimizationMissingWarning\n'), ((2728, 2785), 'onnx2keras.compatible_data_format', 'compatible_data_format', (['InterleavedImageBatch', 'OnnxTensor'], {}), '(InterleavedImageBatch, OnnxTensor)\n', (2750, 2785), False, 'from onnx2keras import onnx2keras, compatible_data_format, OnnxConstant, OnnxTensor, InterleavedImageBatch, ensure_data_format, OptimizationMissingWarning\n'), ((2805, 2864), 'onnx2keras.compatible_data_format', 'compatible_data_format', (['InterleavedImageBatch', 'OnnxConstant'], {}), '(InterleavedImageBatch, OnnxConstant)\n', (2827, 2864), False, 'from onnx2keras import onnx2keras, compatible_data_format, OnnxConstant, OnnxTensor, InterleavedImageBatch, ensure_data_format, OptimizationMissingWarning\n'), ((2998, 3028), 'numpy.random.rand', 'np.random.rand', (['(1)', '(3)', '(224)', '(224)'], {}), '(1, 3, 224, 224)\n', (3012, 3028), True, 'import numpy as np\n'), ((3227, 3257), 'numpy.random.rand', 'np.random.rand', (['(1)', '(3)', '(224)', '(224)'], {}), '(1, 3, 224, 224)\n', (3241, 3257), True, 'import numpy as np\n'), ((3455, 3485), 'numpy.random.rand', 'np.random.rand', (['(1)', '(1)', '(224)', '(224)'], {}), '(1, 1, 224, 224)\n', (3469, 3485), True, 'import numpy as np\n'), ((3666, 3696), 'numpy.random.rand', 'np.random.rand', (['(1)', '(3)', '(224)', '(224)'], {}), '(1, 3, 224, 224)\n', (3680, 3696), True, 'import numpy as np\n'), ((4006, 4036), 'numpy.random.rand', 'np.random.rand', (['(1)', '(3)', '(224)', '(224)'], {}), '(1, 3, 224, 224)\n', (4020, 4036), True, 'import numpy as np\n'), ((4200, 4230), 'numpy.random.rand', 'np.random.rand', (['(1)', '(3)', '(224)', '(224)'], {}), '(1, 3, 224, 224)\n', (4214, 4230), True, 'import numpy as np\n'), ((4410, 4441), 'numpy.random.rand', 'np.random.rand', (['(1)', '(192)', '(272)', '(64)'], {}), '(1, 192, 272, 64)\n', (4424, 4441), True, 'import numpy as np\n'), ((4946, 4976), 'numpy.random.rand', 'np.random.rand', (['(1)', '(3)', '(112)', '(112)'], {}), '(1, 3, 112, 112)\n', (4960, 4976), True, 'import numpy as np\n'), ((5196, 5226), 'numpy.random.rand', 'np.random.rand', (['(1)', '(3)', '(112)', '(112)'], {}), '(1, 3, 112, 112)\n', (5210, 5226), True, 'import numpy as np\n'), ((5444, 5474), 'numpy.random.rand', 'np.random.rand', (['(1)', '(3)', '(384)', '(544)'], {}), '(1, 3, 384, 544)\n', (5458, 5474), True, 'import numpy as np\n'), ((5695, 5725), 'numpy.random.rand', 'np.random.rand', (['(1)', '(3)', '(112)', '(112)'], {}), '(1, 3, 112, 112)\n', (5709, 5725), True, 'import numpy as np\n'), ((5965, 5996), 'numpy.random.rand', 'np.random.rand', (['(1)', '(16)', '(112)', '(112)'], {}), '(1, 16, 112, 112)\n', (5979, 5996), True, 'import numpy as np\n'), ((6221, 6252), 'numpy.random.rand', 'np.random.rand', (['(1)', '(16)', '(112)', '(112)'], {}), '(1, 16, 112, 112)\n', (6235, 6252), True, 'import numpy as np\n'), ((6479, 6510), 'numpy.random.rand', 'np.random.rand', (['(1)', '(16)', '(112)', '(112)'], {}), '(1, 16, 112, 112)\n', (6493, 6510), True, 'import numpy as np\n'), ((6745, 6776), 'numpy.random.rand', 'np.random.rand', (['(1)', '(16)', '(112)', '(112)'], {}), '(1, 16, 112, 112)\n', (6759, 6776), True, 'import numpy as np\n'), ((6995, 7025), 'numpy.random.rand', 'np.random.rand', (['(1)', '(3)', '(384)', '(544)'], {}), '(1, 3, 384, 544)\n', (7009, 7025), True, 'import numpy as np\n'), ((7247, 7277), 'numpy.random.rand', 'np.random.rand', (['(1)', '(3)', '(223)', '(223)'], {}), '(1, 3, 223, 223)\n', (7261, 7277), True, 'import numpy as np\n'), ((7606, 7636), 'numpy.random.rand', 'np.random.rand', (['(1)', '(3)', '(224)', '(224)'], {}), '(1, 3, 224, 224)\n', (7620, 7636), True, 'import numpy as np\n'), ((8030, 8060), 'numpy.random.rand', 'np.random.rand', (['(1)', '(3)', '(224)', '(224)'], {}), '(1, 3, 224, 224)\n', (8044, 8060), True, 'import numpy as np\n'), ((8365, 8395), 'numpy.random.rand', 'np.random.rand', (['(1)', '(3)', '(224)', '(224)'], {}), '(1, 3, 224, 224)\n', (8379, 8395), True, 'import numpy as np\n'), ((8702, 8732), 'numpy.random.rand', 'np.random.rand', (['(1)', '(3)', '(224)', '(224)'], {}), '(1, 3, 224, 224)\n', (8716, 8732), True, 'import numpy as np\n'), ((9033, 9063), 'numpy.random.rand', 'np.random.rand', (['(1)', '(3)', '(224)', '(224)'], {}), '(1, 3, 224, 224)\n', (9047, 9063), True, 'import numpy as np\n'), ((9278, 9308), 'numpy.random.rand', 'np.random.rand', (['(1)', '(3)', '(224)', '(224)'], {}), '(1, 3, 224, 224)\n', (9292, 9308), True, 'import numpy as np\n'), ((9501, 9531), 'numpy.random.rand', 'np.random.rand', (['(1)', '(3)', '(224)', '(224)'], {}), '(1, 3, 224, 224)\n', (9515, 9531), True, 'import numpy as np\n'), ((9686, 9716), 'numpy.random.rand', 'np.random.rand', (['(1)', '(8)', '(224)', '(224)'], {}), '(1, 8, 224, 224)\n', (9700, 9716), True, 'import numpy as np\n'), ((9929, 9959), 'numpy.random.rand', 'np.random.rand', (['(1)', '(3)', '(224)', '(224)'], {}), '(1, 3, 224, 224)\n', (9943, 9959), True, 'import numpy as np\n'), ((10125, 10146), 'torch.nn.Module.__init__', 'Module.__init__', (['self'], {}), '(self)\n', (10140, 10146), False, 'from torch.nn import Module\n'), ((10431, 10461), 'numpy.random.rand', 'np.random.rand', (['(1)', '(3)', '(224)', '(224)'], {}), '(1, 3, 224, 224)\n', (10445, 10461), True, 'import numpy as np\n'), ((10647, 10675), 'numpy.random.rand', 'np.random.rand', (['(1)', '(3)', '(16)', '(16)'], {}), '(1, 3, 16, 16)\n', (10661, 10675), True, 'import numpy as np\n'), ((10903, 10931), 'numpy.random.rand', 'np.random.rand', (['(1)', '(3)', '(16)', '(16)'], {}), '(1, 3, 16, 16)\n', (10917, 10931), True, 'import numpy as np\n'), ((11161, 11189), 'numpy.random.rand', 'np.random.rand', (['(5)', '(3)', '(16)', '(16)'], {}), '(5, 3, 16, 16)\n', (11175, 11189), True, 'import numpy as np\n'), ((11439, 11467), 'numpy.random.rand', 'np.random.rand', (['(5)', '(3)', '(16)', '(16)'], {}), '(5, 3, 16, 16)\n', (11453, 11467), True, 'import numpy as np\n'), ((11648, 11678), 'numpy.random.rand', 'np.random.rand', (['(1)', '(3)', '(224)', '(224)'], {}), '(1, 3, 224, 224)\n', (11662, 11678), True, 'import numpy as np\n'), ((11879, 11930), 'torch.nn.functional.avg_pool2d', 'F.avg_pool2d', (['x'], {'kernel_size': '(3)', 'stride': '(1)', 'padding': '(1)'}), '(x, kernel_size=3, stride=1, padding=1)\n', (11891, 11930), True, 'import torch.nn.functional as F\n'), ((12004, 12034), 'numpy.random.rand', 'np.random.rand', (['(1)', '(3)', '(224)', '(224)'], {}), '(1, 3, 224, 224)\n', (12018, 12034), True, 'import numpy as np\n'), ((12223, 12289), 'torch.nn.functional.avg_pool2d', 'F.avg_pool2d', (['x'], {'kernel_size': '(3, 6)', 'stride': '(1, 2)', 'padding': '(1, 2)'}), '(x, kernel_size=(3, 6), stride=(1, 2), padding=(1, 2))\n', (12235, 12289), True, 'import torch.nn.functional as F\n'), ((12363, 12393), 'numpy.random.rand', 'np.random.rand', (['(1)', '(3)', '(224)', '(224)'], {}), '(1, 3, 224, 224)\n', (12377, 12393), True, 'import numpy as np\n'), ((12580, 12612), 'torch.nn.functional.adaptive_avg_pool2d', 'F.adaptive_avg_pool2d', (['x', '(1, 1)'], {}), '(x, (1, 1))\n', (12601, 12612), True, 'import torch.nn.functional as F\n'), ((12686, 12716), 'numpy.random.rand', 'np.random.rand', (['(1)', '(3)', '(224)', '(224)'], {}), '(1, 3, 224, 224)\n', (12700, 12716), True, 'import numpy as np\n'), ((12982, 13008), 'numpy.random.rand', 'np.random.rand', (['(1)', '(3)', '(1)', '(1)'], {}), '(1, 3, 1, 1)\n', (12996, 13008), True, 'import numpy as np\n'), ((13453, 13479), 'numpy.random.rand', 'np.random.rand', (['(2)', '(3)', '(5)', '(5)'], {}), '(2, 3, 5, 5)\n', (13467, 13479), True, 'import numpy as np\n'), ((13860, 13886), 'numpy.random.rand', 'np.random.rand', (['(1)', '(3)', '(5)', '(5)'], {}), '(1, 3, 5, 5)\n', (13874, 13886), True, 'import numpy as np\n'), ((14272, 14298), 'numpy.random.rand', 'np.random.rand', (['(1)', '(3)', '(5)', '(5)'], {}), '(1, 3, 5, 5)\n', (14286, 14298), True, 'import numpy as np\n'), ((14483, 14513), 'numpy.random.rand', 'np.random.rand', (['(1)', '(3)', '(224)', '(224)'], {}), '(1, 3, 224, 224)\n', (14497, 14513), True, 'import numpy as np\n'), ((14723, 14751), 'numpy.random.rand', 'np.random.rand', (['(1)', '(3)', '(32)', '(32)'], {}), '(1, 3, 32, 32)\n', (14737, 14751), True, 'import numpy as np\n'), ((14965, 14993), 'numpy.random.rand', 'np.random.rand', (['(1)', '(3)', '(32)', '(32)'], {}), '(1, 3, 32, 32)\n', (14979, 14993), True, 'import numpy as np\n'), ((15223, 15251), 'numpy.random.rand', 'np.random.rand', (['(1)', '(3)', '(32)', '(32)'], {}), '(1, 3, 32, 32)\n', (15237, 15251), True, 'import numpy as np\n'), ((15457, 15505), 'torch.nn.functional.interpolate', 'F.interpolate', (['x'], {'scale_factor': '(2)', 'mode': '"""nearest"""'}), "(x, scale_factor=2, mode='nearest')\n", (15470, 15505), True, 'import torch.nn.functional as F\n'), ((15576, 15604), 'numpy.random.rand', 'np.random.rand', (['(1)', '(3)', '(32)', '(32)'], {}), '(1, 3, 32, 32)\n', (15590, 15604), True, 'import numpy as np\n'), ((15793, 15862), 'torch.nn.functional.interpolate', 'F.interpolate', (['x'], {'scale_factor': '(2)', 'mode': '"""bilinear"""', 'align_corners': '(True)'}), "(x, scale_factor=2, mode='bilinear', align_corners=True)\n", (15806, 15862), True, 'import torch.nn.functional as F\n'), ((15933, 15961), 'numpy.random.rand', 'np.random.rand', (['(1)', '(3)', '(32)', '(32)'], {}), '(1, 3, 32, 32)\n', (15947, 15961), True, 'import numpy as np\n'), ((16159, 16200), 'torch.nn.functional.max_pool2d', 'F.max_pool2d', (['x', '(3)', '(1)', '(1)', '(1)', '(False)', '(False)'], {}), '(x, 3, 1, 1, 1, False, False)\n', (16171, 16200), True, 'import torch.nn.functional as F\n'), ((16315, 16341), 'numpy.random.rand', 'np.random.rand', (['(1)', '(3)', '(5)', '(5)'], {}), '(1, 3, 5, 5)\n', (16329, 16341), True, 'import numpy as np\n'), ((16656, 16684), 'numpy.random.rand', 'np.random.rand', (['(1)', '(3)', '(16)', '(16)'], {}), '(1, 3, 16, 16)\n', (16670, 16684), True, 'import numpy as np\n'), ((16776, 16804), 'numpy.random.rand', 'np.random.rand', (['(4)', '(3)', '(16)', '(16)'], {}), '(4, 3, 16, 16)\n', (16790, 16804), True, 'import numpy as np\n'), ((17120, 17148), 'numpy.random.rand', 'np.random.rand', (['(1)', '(1)', '(16)', '(16)'], {}), '(1, 1, 16, 16)\n', (17134, 17148), True, 'import numpy as np\n'), ((17473, 17501), 'numpy.random.rand', 'np.random.rand', (['(1)', '(1)', '(16)', '(16)'], {}), '(1, 1, 16, 16)\n', (17487, 17501), True, 'import numpy as np\n'), ((17942, 17970), 'numpy.random.rand', 'np.random.rand', (['(4)', '(3)', '(16)', '(16)'], {}), '(4, 3, 16, 16)\n', (17956, 17970), True, 'import numpy as np\n'), ((18253, 18281), 'numpy.random.rand', 'np.random.rand', (['(4)', '(3)', '(16)', '(16)'], {}), '(4, 3, 16, 16)\n', (18267, 18281), True, 'import numpy as np\n'), ((18630, 18658), 'numpy.random.rand', 'np.random.rand', (['(4)', '(3)', '(16)', '(16)'], {}), '(4, 3, 16, 16)\n', (18644, 18658), True, 'import numpy as np\n'), ((18903, 18931), 'numpy.random.rand', 'np.random.rand', (['(4)', '(3)', '(16)', '(16)'], {}), '(4, 3, 16, 16)\n', (18917, 18931), True, 'import numpy as np\n'), ((19360, 19388), 'numpy.random.rand', 'np.random.rand', (['(4)', '(3)', '(16)', '(32)'], {}), '(4, 3, 16, 32)\n', (19374, 19388), True, 'import numpy as np\n'), ((19654, 19682), 'numpy.random.rand', 'np.random.rand', (['(4)', '(3)', '(16)', '(32)'], {}), '(4, 3, 16, 32)\n', (19668, 19682), True, 'import numpy as np\n'), ((19966, 19994), 'numpy.random.rand', 'np.random.rand', (['(4)', '(3)', '(16)', '(32)'], {}), '(4, 3, 16, 32)\n', (19980, 19994), True, 'import numpy as np\n'), ((20731, 20763), 'numpy.random.rand', 'np.random.rand', (['batch', '(3)', '(16)', '(32)'], {}), '(batch, 3, 16, 32)\n', (20745, 20763), True, 'import numpy as np\n'), ((21034, 21062), 'numpy.random.rand', 'np.random.rand', (['(2)', '(3)', '(16)', '(32)'], {}), '(2, 3, 16, 32)\n', (21048, 21062), True, 'import numpy as np\n'), ((21827, 21859), 'numpy.random.rand', 'np.random.rand', (['batch', '(3)', '(16)', '(32)'], {}), '(batch, 3, 16, 32)\n', (21841, 21859), True, 'import numpy as np\n'), ((22154, 22182), 'numpy.random.rand', 'np.random.rand', (['(2)', '(3)', '(16)', '(32)'], {}), '(2, 3, 16, 32)\n', (22168, 22182), True, 'import numpy as np\n'), ((4709, 4739), 'numpy.random.rand', 'np.random.rand', (['(1)', '(3)', '(224)', '(224)'], {}), '(1, 3, 224, 224)\n', (4723, 4739), True, 'import numpy as np\n'), ((18333, 18358), 'tensorflow.__version__.split', 'tf.__version__.split', (['"""."""'], {}), "('.')\n", (18353, 18358), True, 'import tensorflow as tf\n'), ((16534, 16561), 'torch.nn.functional.adaptive_avg_pool2d', 'F.adaptive_avg_pool2d', (['x', '(1)'], {}), '(x, 1)\n', (16555, 16561), True, 'import torch.nn.functional as F\n')]
#!/usr/bin/env python # -*- coding: utf-8 -*- # # nnutil2 - Tensorflow utilities for training neural networks # Copyright (c) 2019, <NAME> <<EMAIL>> # # This file is part of 'nnutil2'. # # This file may be modified and distributed under the terms of the 3-clause BSD # license. See the LICENSE file for details. import tensorflow as tf import numpy as np def is_tensor(x): return isinstance(x, (tf.Tensor, tf.SparseTensor, tf.RaggedTensor)) def as_tensor(structure): if tf.nest.is_nested(structure): return tf.nest.map_structure(as_tensor, structure) elif isinstance(structure, tf.Tensor): return structure elif isinstance(structure, tf.SparseTensor): return tf.sparse.to_dense(structure) elif isinstance(structure, tf.RaggedTensor): return tf.sparse.to_dense(structure) elif isinstance(structure, np.ndarray): return tf.constant(structure, shape=structure.shape, dtype=tf.dtype.as_dtype(structure.dtype)) elif isinstance(structure, (int, np.integer, np.signedinteger, float, np.floating, str, bytes)): return tf.constant(structure, shape=(), dtype=tf.dtype.as_dtype(type(structure))) else: raise Exception("Cannot handle nested structure of type: {}".format(type(structure))) def as_numpy(structure): if tf.nest.is_nested(structure): return tf.nest.map_structure(as_numpy, structure) elif is_tensor(structure): return structure.numpy() elif isinstance(structure, np.ndarray): return structure elif isinstance(structure, (int, np.integer, np.signedinteger, float, np.floating, str, bytes)): dtype = tf.dtype.as_dtype(type(structure)).as_numpy_dtype() return np.array(structure, shape=(), dtype=dtype) else: raise Exception("Cannot handle nested structure of type: {}".format(type(structure)))
[ "tensorflow.dtype.as_dtype", "tensorflow.sparse.to_dense", "tensorflow.nest.is_nested", "tensorflow.nest.map_structure", "numpy.array" ]
[((483, 511), 'tensorflow.nest.is_nested', 'tf.nest.is_nested', (['structure'], {}), '(structure)\n', (500, 511), True, 'import tensorflow as tf\n'), ((1310, 1338), 'tensorflow.nest.is_nested', 'tf.nest.is_nested', (['structure'], {}), '(structure)\n', (1327, 1338), True, 'import tensorflow as tf\n'), ((528, 571), 'tensorflow.nest.map_structure', 'tf.nest.map_structure', (['as_tensor', 'structure'], {}), '(as_tensor, structure)\n', (549, 571), True, 'import tensorflow as tf\n'), ((1355, 1397), 'tensorflow.nest.map_structure', 'tf.nest.map_structure', (['as_numpy', 'structure'], {}), '(as_numpy, structure)\n', (1376, 1397), True, 'import tensorflow as tf\n'), ((706, 735), 'tensorflow.sparse.to_dense', 'tf.sparse.to_dense', (['structure'], {}), '(structure)\n', (724, 735), True, 'import tensorflow as tf\n'), ((801, 830), 'tensorflow.sparse.to_dense', 'tf.sparse.to_dense', (['structure'], {}), '(structure)\n', (819, 830), True, 'import tensorflow as tf\n'), ((1718, 1760), 'numpy.array', 'np.array', (['structure'], {'shape': '()', 'dtype': 'dtype'}), '(structure, shape=(), dtype=dtype)\n', (1726, 1760), True, 'import numpy as np\n'), ((943, 977), 'tensorflow.dtype.as_dtype', 'tf.dtype.as_dtype', (['structure.dtype'], {}), '(structure.dtype)\n', (960, 977), True, 'import tensorflow as tf\n')]
#!/usr/bin/env python3.7 # # Copyright (c) University of Luxembourg 2021. # Created by <NAME>, <EMAIL>, SnT, 2021. # import argparse import numpy from utilities import print_new_test, is_int, cosine, euclidean, searchStringInFile parser = argparse.ArgumentParser() parser.add_argument('--name', type=str) parser.add_argument('--cov_a', type=str) parser.add_argument('--cov_b', type=str) parser.add_argument('--result', type=str) parser.add_argument('--line', type=int) parser.add_argument('--operator', type=str) args = parser.parse_args() cov_a = args.cov_a cov_b = args.cov_b name = args.name result = args.result lineNumber = int(args.line) - 1 operator = args.operator def getCoverageAsList(test): global name coverage_line_splitted = searchStringInFile(test, name).split(':') if len(coverage_line_splitted) == 1: raise ValueError("coverage not found") coverage = coverage_line_splitted[1] coverage_frequencies = coverage.split(',') return coverage_frequencies def get_distance(testA, testB): try: coverageA_frequencies = getCoverageAsList(testA) coverageB_frequencies = getCoverageAsList(testB) except ValueError as err: print(err.args) return -1 covAList = [] for i in coverageA_frequencies: if is_int(i): covAList.append(int(i)) else: covAList.append(int(0)) covBList = [] for i in coverageB_frequencies: if is_int(i): covBList.append(int(i)) else: covBList.append(int(0)) # SDL, LOD corrections global lineNumber if operator == "SDL": if len(covAList) == len(covBList): del covAList[lineNumber] del covBList[lineNumber] else: while len(covAList) != len(covBList): if len(covAList) > len(covBList): del covAList[lineNumber] else: covAList.insert(len(covAList), int(0)) del covAList[lineNumber] del covBList[lineNumber] elif operator == 'LOD': while len(covAList) != len(covBList): if len(covAList) > len(covBList): del covAList[lineNumber] else: covAList.insert(len(covAList), int(0)) print(covAList) print(covBList) A = numpy.array(covAList) B = numpy.array(covBList) distance = cosine(A, B) print(distance) return distance distance = get_distance(cov_a, cov_b) print_new_test(result, distance)
[ "utilities.searchStringInFile", "argparse.ArgumentParser", "utilities.cosine", "utilities.print_new_test", "numpy.array", "utilities.is_int" ]
[((243, 268), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (266, 268), False, 'import argparse\n'), ((2739, 2771), 'utilities.print_new_test', 'print_new_test', (['result', 'distance'], {}), '(result, distance)\n', (2753, 2771), False, 'from utilities import print_new_test, is_int, cosine, euclidean, searchStringInFile\n'), ((2578, 2599), 'numpy.array', 'numpy.array', (['covAList'], {}), '(covAList)\n', (2589, 2599), False, 'import numpy\n'), ((2608, 2629), 'numpy.array', 'numpy.array', (['covBList'], {}), '(covBList)\n', (2619, 2629), False, 'import numpy\n'), ((2646, 2658), 'utilities.cosine', 'cosine', (['A', 'B'], {}), '(A, B)\n', (2652, 2658), False, 'from utilities import print_new_test, is_int, cosine, euclidean, searchStringInFile\n'), ((1514, 1523), 'utilities.is_int', 'is_int', (['i'], {}), '(i)\n', (1520, 1523), False, 'from utilities import print_new_test, is_int, cosine, euclidean, searchStringInFile\n'), ((1677, 1686), 'utilities.is_int', 'is_int', (['i'], {}), '(i)\n', (1683, 1686), False, 'from utilities import print_new_test, is_int, cosine, euclidean, searchStringInFile\n'), ((860, 890), 'utilities.searchStringInFile', 'searchStringInFile', (['test', 'name'], {}), '(test, name)\n', (878, 890), False, 'from utilities import print_new_test, is_int, cosine, euclidean, searchStringInFile\n')]
import numpy def permute_node(node, permutation_index, axis=-1): """Permute index of `node` array Args: node (numpy.ndarray): the array whose `axis` to be permuted. permutation_index (numpy.ndarray): 1d numpy array whose size should be same as permutation axis of `node`. axis (int): permutation axis. Returns (numpy.ndarray): permutated `node` array. """ if node.shape[axis] != len(permutation_index): raise ValueError( 'node.shape[{}] = {} and len(permutation_index) = {} do not match!' .format(axis, node.shape[axis], len(permutation_index))) out_node = numpy.take(node, permutation_index, axis=axis).copy() return out_node def permute_adj(adj, permutation_index, axis=None): """Permute index of adjacency matrix array Args: adj (numpy.ndarray): the array whose `axis` to be permuted. It is considered as adjacency matrix. permutation_index (numpy.ndarray): 1d numpy array whose size should be same as permutation axis of `node`. axis (list or tuple or None): list of 2d int, indicates the permutation axis. When None is passed (default), it uses -1 and -2 as `axis`, it means that last 2 axis are considered to be permuted. Returns (numpy.ndarray): permutated `adj` array. """ if axis is not None: if not isinstance(axis, (list, tuple)): raise TypeError('axis must be list or tuple, got {}' .format(type(axis))) if len(axis) != 2: raise ValueError('axis length must 2, got {}'.format(len(axis))) else: axis = [-1, -2] # default value is to use last 2 axis num_node = len(permutation_index) for ax in axis: if adj.shape[ax] != len(permutation_index): raise ValueError( 'adj.shape[{}] = {} and len(permutation_index) = {} do not ' 'match!'.format(axis, adj.shape[axis], len(permutation_index))) out_adj = numpy.zeros_like(adj) ndim = adj.ndim for i in range(num_node): for j in range(num_node): in_indices = [slice(None)] * ndim out_indices = [slice(None)] * ndim in_indices[axis[0]] = i in_indices[axis[1]] = j out_indices[axis[0]] = permutation_index[i] out_indices[axis[1]] = permutation_index[j] out_adj[tuple(in_indices)] = adj[tuple(out_indices)] return out_adj
[ "numpy.zeros_like", "numpy.take" ]
[((2052, 2073), 'numpy.zeros_like', 'numpy.zeros_like', (['adj'], {}), '(adj)\n', (2068, 2073), False, 'import numpy\n'), ((654, 700), 'numpy.take', 'numpy.take', (['node', 'permutation_index'], {'axis': 'axis'}), '(node, permutation_index, axis=axis)\n', (664, 700), False, 'import numpy\n')]
import cv2 import numpy as np from random import randint from scipy.optimize import least_squares from math import sqrt, atan2 def get_8_points(len_features): """ Function to get 8 indices of random points Implements the 8-point algorithm :param len_features: total no. of features retrieved from feature extractor :return: a list containing indices of 8 random feature points """ eight_points = [] # Iterate until 8 points are not stored in the list while len(eight_points) != 8: # Get a index of a random point index = randint(0, len_features - 1) # Add only distinct points to the list if index not in eight_points: eight_points.append(index) return eight_points class MotionEstimator: """ A class to estimate 3D motion of a camera """ def __init__(self, focal_lengths, principal_pts): # Define K-matrix using camera parameters self.k_mat = np.array([[focal_lengths[0], 0, principal_pts[0]], [0, focal_lengths[1], principal_pts[1]], [0, 0, 1]]) # Define no. of iterations for RANSAC self.iterations = 60 # Define threshold for outlier rejection in RANSAC self.epsilon = 0.01 # Create SIFT detector object self.sift = cv2.xfeatures2d.SIFT_create() # Define parameters for Flann-based matcher index_params = dict(algorithm=0, trees=5) search_params = dict(checks=50) # Create object of Flann-based matcher self.matcher = cv2.FlannBasedMatcher(index_params, search_params) # Define original homogeneous matrix for the camera pose # Camera is considered to be at origin self.original_h = np.identity(4) self.h_mat_last_row = np.array([0, 0, 0, 1]) self.u = np.zeros((3, 1)) self.v = np.identity(3) def extract_features(self, curr_img, next_img): """ Method to extract matching key features from 2 images :param curr_img: current image frame from the dataset :param next_img: next image frame from the dataset :return: a tuple of lists containing matching key features from both images """ # Get key-points and descriptors for both frames key_points_curr, descriptor_curr = self.sift.detectAndCompute(curr_img, None) key_points_next, descriptor_next = self.sift.detectAndCompute(next_img, None) # Get matches between the current and next frame matches = self.matcher.knnMatch(descriptor_curr, descriptor_next, k=2) # Define empty list to store features of current and next frame features_curr, features_next = [], [] # Employ ratio test for _, (m, n) in enumerate(matches): if m.distance < 0.5 * n.distance: features_curr.append(key_points_curr[m.queryIdx].pt) features_next.append(key_points_next[m.trainIdx].pt) return features_curr, features_next def ransac_with_8_point(self, features_curr, features_next): """ Method to ransac on features of current and next image frame using 8-point algorithm :param features_curr: a list of feature points in the current image frame :param features_next: a list of feature points in the next image frame :return: a tuple containing the 3x3 fundamental matrix, inliers in the current and next image frame """ count_inliers = 0 final_fundamental_mat = np.zeros((3, 3)) # Define list to store inliers from current and next image frame inliers_curr, inliers_next = [], [] for _ in range(self.iterations): count = 0 good_features_curr, good_features_next = [], [] temp_features_curr, temp_features_next = [], [] # Get 8 random points and extract features at those points for pt in get_8_points(len(features_curr)): good_features_curr.append([features_curr[pt][0], features_curr[pt][1]]) good_features_next.append([features_next[pt][0], features_next[pt][1]]) # Calculate fundamental matrix using these 8 features fundamental_mat = self.calc_fundamental_matrix(good_features_curr, good_features_next) # Employ outlier rejection for i in range(len(features_curr)): if self.check_fundamental_matrix(features_curr[i], features_next[i], fundamental_mat): count += 1 temp_features_curr.append(features_curr[i]) temp_features_next.append(features_next[i]) if count > count_inliers: count_inliers = count final_fundamental_mat = fundamental_mat inliers_curr, inliers_next = temp_features_curr, temp_features_next return final_fundamental_mat, inliers_curr, inliers_next @staticmethod def calc_fundamental_matrix(features_curr, features_next): """ Method to estimate the fundamental matrix using 8 points :param features_curr: a list of 8 feature points in the current image frame :param features_next: a list of 8 feature points in the next image frame :return: a 3x3 fundamental matrix """ a_mat = np.empty((8, 9)) # Iterate over all features for i in range(len(features_curr)): # Get positions of features in current and next frame x_curr, y_curr = features_curr[i][0], features_curr[i][1] x_next, y_next = features_next[i][0], features_next[i][1] # Fill ith column of A matrix a_mat[i] = np.array([x_next * x_curr, x_next * y_curr, x_next, y_next * x_curr, y_next * y_curr, y_next, x_curr, y_curr, 1]) # Get SVD of A matrix _, _, v = np.linalg.svd(a_mat, full_matrices=True) # Get SVD of last column of V matrix u, s, v_new = np.linalg.svd(v[-1].reshape(3, 3)) # Restrain fundamental matrix to a rank of 2 s_new = np.array([[s[0], 0, 0], [0, s[1], 0], [0, 0, 0]]) f_mat = u @ s_new @ v_new return f_mat def check_fundamental_matrix(self, feature_curr, feature_next, fundamental_mat): """ Method to calculate transpose(x2).F.x1 and check if it satisfies the desired threshold :param feature_curr: a tuple of feature in current image frame :param feature_next: a tuple of corresponding feature in next image frame :param fundamental_mat: a 3x3 array of fundamental matrix :return: true if estimate is less than threshold """ # Get transpose of current features fc_new = np.array([feature_curr[0], feature_curr[1], 1]).T fn_new = np.array([feature_next[0], feature_next[1], 1]) # Estimate transpose(x2).F.x1 est = abs(np.squeeze(np.matmul(np.matmul(fn_new, fundamental_mat), fc_new))) return est < self.epsilon def calc_essential_matrix(self, fundamental_mat): """ Method to calculate the essential matrix :param fundamental_mat: a numpy 3x3 array of fundamental matrix :return: a numpy 3x3 array of essential matrix """ temp = np.matmul(np.matmul(self.k_mat.T, fundamental_mat), self.k_mat) u, _, v = np.linalg.svd(temp, full_matrices=True) sigma = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 0]]) essential_mat = np.matmul(np.matmul(u, sigma), v) return essential_mat @staticmethod def estimate_camera_pose(essential_mat): """ Estimate the various possible poses of the camera :param essential_mat: a numpy 3x3 array of essential matrix :return: a tuple containing 4 camera centers and 4 rotation matrices """ # Define empty lists to store camera poses camera_centers, rotation_matrices = [], [] u, _, v = np.linalg.svd(essential_mat) w_mat = np.array([[0, -1, 0], [1, 0, 0], [0, 0, 1]]) # Get the 4 pose configurations of the camera for i in range(4): # Evaluate center of camera for camera pose cam_center = u[:, 2] # Check if additive inverse needs to be taken if i % 2 == 1: cam_center = -cam_center # Evaluate rotation matrix for camera pose # Check whether transpose of W matrix needs to be taken if i < 2: rotation_mat = u @ w_mat @ v else: rotation_mat = u @ w_mat.T @ v # Check for negative determinant condition if np.linalg.det(rotation_mat) < 0: cam_center, rotation_mat = -cam_center, -rotation_mat camera_centers.append(cam_center.reshape((3, 1))) rotation_matrices.append(rotation_mat) return camera_centers, rotation_matrices def disambiguate_camera_pose(self, camera_centers, rotation_matrices, inliers_curr, inliers_next): """ Method to find the unique camera pose using the 4 possible poses :param camera_centers: a list of camera centers :param rotation_matrices: a list of rotation matrices :param inliers_curr: a list of inliers in the current image frame :param inliers_next: a list of inliers in the next image frame :return: a tuple containing the pose of the camera """ check = 0 rotation_final, cam_center_final, x_final = None, None, None # Iterate over all the rotation matrices for i in range(len(rotation_matrices)): euler_angles = self.get_euler_angles(rotation_matrices[i]) if -50 < euler_angles[0] < 50 and -50 < euler_angles[2] < 50: count = 0 x_inlier = None cam_pose_new = np.hstack((rotation_matrices[i], camera_centers[i])) for j in range(len(inliers_curr)): temp_x = self.get_triangulation_point(cam_pose_new, inliers_curr[j], inliers_next[j]) r_mat_row = rotation_matrices[i][2, :].reshape((1, 3)) if np.squeeze(r_mat_row @ (temp_x - camera_centers[i])): count += 1 x_inlier = temp_x if check < count: check = count rotation_final = rotation_matrices[i] cam_center_final = camera_centers[i] x_final = x_inlier if cam_center_final[2] > 0: cam_center_final = -cam_center_final return cam_center_final, rotation_final, x_final @ staticmethod def get_euler_angles(rotation_mat): """ Method to get Euler angles using a 3x3 rotation matrix :param rotation_mat: a 3x3 numpy array of rotation matrix :return: a tuple of Euler angles in x,y, and z directions respectively """ psi = sqrt((rotation_mat[0][0] ** 2) + (rotation_mat[1][0] ** 2)) if not psi < 1e-6: x = atan2(rotation_mat[2][1], rotation_mat[2][2]) y = atan2(-rotation_mat[2][1], psi) z = atan2(rotation_mat[1][0], rotation_mat[0][0]) else: x = atan2(-rotation_mat[1][2], rotation_mat[1][1]) y = atan2(-rotation_mat[2][0], psi) z = 0 return (x * 180 / np.pi), (y * 180 / np.pi), (z * 180 / np.pi) def get_triangulation_point(self, camera_pose, inlier_curr, inlier_next): """ Method to employ triangular check for cheirality condition Method to triangulate inliers :param camera_pose: new camera pose :param inlier_curr: an inlier in the current image frame :param inlier_next: an inlier in the next image frame :return: """ x_old = np.array([[0, -1, inlier_curr[1]], [1, 0, -inlier_curr[0]], [inlier_curr[1], inlier_curr[0], 0]]) x_new = np.array([[0, -1, inlier_next[1]], [1, 0, -inlier_next[0]], [inlier_next[1], inlier_next[0], 0]]) a_old = x_old @ self.original_h[0:3, :] a_new = x_new @ camera_pose a_mat = np.vstack((a_old, a_new)) _, _, v = np.linalg.svd(a_mat) x_final = (v[-1] / v[-1][3]).reshape((4, 1)) return x_final[0:3].reshape((3, 1)) def get_homogeneous_matrix(self, rotation_mat, translation_mat): """ Method to get the homogeneous matrix :param rotation_mat: a 3x3 numpy array of rotation matrix :param translation_mat: a 3x1 translation matrix :return: a 4x4 numpy array """ # Homogenoeous matrix is of the form: H = [r t # 0 1] # where r is a 3x3 rotational matrix and t is a 3x1 translation matrix # Generate a 3x4 matrix of the form [r t] z = np.column_stack((rotation_mat, translation_mat)) # Append the constant last row in the 3x4 matrix and return it return np.vstack((z, self.h_mat_last_row)) @staticmethod def get_drift(drift, custom_pose, opencv_pose): """ Evalute drift between 2 trajectories :param drift: drift from the previous frame :param custom_pose: pose of the camera using our pipeline :param opencv_pose: pose of the camera using opencv's in-built functions :return: drift of the current frame """ drift += sqrt(((custom_pose[0] - opencv_pose[1]) ** 2) + ((custom_pose[0] - opencv_pose[1]) ** 2)) return drift def get_triangulation_error(self, x_linear, camera_pose): """ Get the error in linear triangulation :param x_linear: X returned from linear triangulation :param camera_pose: a tuple containing rotation and translation matrices :return: error between the current and next frame """ p_old = np.matmul(self.k_mat, self.original_h[0:3, :]) p_new = np.matmul(self.k_mat, camera_pose) x_linear = np.reshape(x_linear, (np.shape(x_linear)[0], 1)) x_0 = np.insert(x_linear, 3, 1) x_pt = np.reshape(x_0, (4, 1)) error_1 = (self.u[0] - (np.dot(p_old[0], x_pt) / np.dot(p_old[2], x_pt))) ** 2 + ( self.u[1] - (np.dot(p_old[1], x_pt) / np.dot(p_new[2], x_pt))) ** 2 error_2 = (self.v[0] - (np.dot(p_new[0], x_pt) / np.dot(p_new[2], x_pt))) ** 2 + ( self.v[1] - (np.dot(p_new[1], x_pt) / np.dot(p_old[2], x_pt))) ** 2 error_total = error_1 + error_2 return error_total def nonlinear_triangulation(self, x_linear, camera_pose, inlier_curr, inlier_next): """ Method to employ non-linear triangulation :param x_linear: X returned from linear triangulation :param camera_pose: a tuple containing rotation and translation matrices :param inlier_curr: inliers from the current image frame :param inlier_next: inliers from the next image frame :return: """ x_init = np.reshape(x_linear, (np.shape(x_linear)[0])) error = self.get_triangulation_error(x_linear, camera_pose) refined_pts = least_squares(error, x_init, args=(self, x_linear, camera_pose, inlier_curr, inlier_next)) return refined_pts
[ "math.atan2", "numpy.empty", "numpy.shape", "numpy.linalg.svd", "random.randint", "numpy.identity", "numpy.insert", "scipy.optimize.least_squares", "numpy.reshape", "numpy.linalg.det", "math.sqrt", "cv2.FlannBasedMatcher", "numpy.hstack", "numpy.squeeze", "numpy.dot", "numpy.vstack", ...
[((575, 603), 'random.randint', 'randint', (['(0)', '(len_features - 1)'], {}), '(0, len_features - 1)\n', (582, 603), False, 'from random import randint\n'), ((964, 1071), 'numpy.array', 'np.array', (['[[focal_lengths[0], 0, principal_pts[0]], [0, focal_lengths[1],\n principal_pts[1]], [0, 0, 1]]'], {}), '([[focal_lengths[0], 0, principal_pts[0]], [0, focal_lengths[1],\n principal_pts[1]], [0, 0, 1]])\n', (972, 1071), True, 'import numpy as np\n'), ((1350, 1379), 'cv2.xfeatures2d.SIFT_create', 'cv2.xfeatures2d.SIFT_create', ([], {}), '()\n', (1377, 1379), False, 'import cv2\n'), ((1592, 1642), 'cv2.FlannBasedMatcher', 'cv2.FlannBasedMatcher', (['index_params', 'search_params'], {}), '(index_params, search_params)\n', (1613, 1642), False, 'import cv2\n'), ((1781, 1795), 'numpy.identity', 'np.identity', (['(4)'], {}), '(4)\n', (1792, 1795), True, 'import numpy as np\n'), ((1826, 1848), 'numpy.array', 'np.array', (['[0, 0, 0, 1]'], {}), '([0, 0, 0, 1])\n', (1834, 1848), True, 'import numpy as np\n'), ((1866, 1882), 'numpy.zeros', 'np.zeros', (['(3, 1)'], {}), '((3, 1))\n', (1874, 1882), True, 'import numpy as np\n'), ((1900, 1914), 'numpy.identity', 'np.identity', (['(3)'], {}), '(3)\n', (1911, 1914), True, 'import numpy as np\n'), ((3553, 3569), 'numpy.zeros', 'np.zeros', (['(3, 3)'], {}), '((3, 3))\n', (3561, 3569), True, 'import numpy as np\n'), ((5362, 5378), 'numpy.empty', 'np.empty', (['(8, 9)'], {}), '((8, 9))\n', (5370, 5378), True, 'import numpy as np\n'), ((5958, 5998), 'numpy.linalg.svd', 'np.linalg.svd', (['a_mat'], {'full_matrices': '(True)'}), '(a_mat, full_matrices=True)\n', (5971, 5998), True, 'import numpy as np\n'), ((6170, 6219), 'numpy.array', 'np.array', (['[[s[0], 0, 0], [0, s[1], 0], [0, 0, 0]]'], {}), '([[s[0], 0, 0], [0, s[1], 0], [0, 0, 0]])\n', (6178, 6219), True, 'import numpy as np\n'), ((6936, 6983), 'numpy.array', 'np.array', (['[feature_next[0], feature_next[1], 1]'], {}), '([feature_next[0], feature_next[1], 1])\n', (6944, 6983), True, 'import numpy as np\n'), ((7493, 7532), 'numpy.linalg.svd', 'np.linalg.svd', (['temp'], {'full_matrices': '(True)'}), '(temp, full_matrices=True)\n', (7506, 7532), True, 'import numpy as np\n'), ((7549, 7592), 'numpy.array', 'np.array', (['[[1, 0, 0], [0, 1, 0], [0, 0, 0]]'], {}), '([[1, 0, 0], [0, 1, 0], [0, 0, 0]])\n', (7557, 7592), True, 'import numpy as np\n'), ((8091, 8119), 'numpy.linalg.svd', 'np.linalg.svd', (['essential_mat'], {}), '(essential_mat)\n', (8104, 8119), True, 'import numpy as np\n'), ((8136, 8180), 'numpy.array', 'np.array', (['[[0, -1, 0], [1, 0, 0], [0, 0, 1]]'], {}), '([[0, -1, 0], [1, 0, 0], [0, 0, 1]])\n', (8144, 8180), True, 'import numpy as np\n'), ((11117, 11172), 'math.sqrt', 'sqrt', (['(rotation_mat[0][0] ** 2 + rotation_mat[1][0] ** 2)'], {}), '(rotation_mat[0][0] ** 2 + rotation_mat[1][0] ** 2)\n', (11121, 11172), False, 'from math import sqrt, atan2\n'), ((12002, 12103), 'numpy.array', 'np.array', (['[[0, -1, inlier_curr[1]], [1, 0, -inlier_curr[0]], [inlier_curr[1],\n inlier_curr[0], 0]]'], {}), '([[0, -1, inlier_curr[1]], [1, 0, -inlier_curr[0]], [inlier_curr[1],\n inlier_curr[0], 0]])\n', (12010, 12103), True, 'import numpy as np\n'), ((12168, 12269), 'numpy.array', 'np.array', (['[[0, -1, inlier_next[1]], [1, 0, -inlier_next[0]], [inlier_next[1],\n inlier_next[0], 0]]'], {}), '([[0, -1, inlier_next[1]], [1, 0, -inlier_next[0]], [inlier_next[1],\n inlier_next[0], 0]])\n', (12176, 12269), True, 'import numpy as np\n'), ((12418, 12443), 'numpy.vstack', 'np.vstack', (['(a_old, a_new)'], {}), '((a_old, a_new))\n', (12427, 12443), True, 'import numpy as np\n'), ((12462, 12482), 'numpy.linalg.svd', 'np.linalg.svd', (['a_mat'], {}), '(a_mat)\n', (12475, 12482), True, 'import numpy as np\n'), ((13129, 13177), 'numpy.column_stack', 'np.column_stack', (['(rotation_mat, translation_mat)'], {}), '((rotation_mat, translation_mat))\n', (13144, 13177), True, 'import numpy as np\n'), ((13264, 13299), 'numpy.vstack', 'np.vstack', (['(z, self.h_mat_last_row)'], {}), '((z, self.h_mat_last_row))\n', (13273, 13299), True, 'import numpy as np\n'), ((13700, 13790), 'math.sqrt', 'sqrt', (['((custom_pose[0] - opencv_pose[1]) ** 2 + (custom_pose[0] - opencv_pose[1]) **\n 2)'], {}), '((custom_pose[0] - opencv_pose[1]) ** 2 + (custom_pose[0] - opencv_pose\n [1]) ** 2)\n', (13704, 13790), False, 'from math import sqrt, atan2\n'), ((14161, 14207), 'numpy.matmul', 'np.matmul', (['self.k_mat', 'self.original_h[0:3, :]'], {}), '(self.k_mat, self.original_h[0:3, :])\n', (14170, 14207), True, 'import numpy as np\n'), ((14224, 14258), 'numpy.matmul', 'np.matmul', (['self.k_mat', 'camera_pose'], {}), '(self.k_mat, camera_pose)\n', (14233, 14258), True, 'import numpy as np\n'), ((14341, 14366), 'numpy.insert', 'np.insert', (['x_linear', '(3)', '(1)'], {}), '(x_linear, 3, 1)\n', (14350, 14366), True, 'import numpy as np\n'), ((14382, 14405), 'numpy.reshape', 'np.reshape', (['x_0', '(4, 1)'], {}), '(x_0, (4, 1))\n', (14392, 14405), True, 'import numpy as np\n'), ((15434, 15528), 'scipy.optimize.least_squares', 'least_squares', (['error', 'x_init'], {'args': '(self, x_linear, camera_pose, inlier_curr, inlier_next)'}), '(error, x_init, args=(self, x_linear, camera_pose, inlier_curr,\n inlier_next))\n', (15447, 15528), False, 'from scipy.optimize import least_squares\n'), ((5730, 5847), 'numpy.array', 'np.array', (['[x_next * x_curr, x_next * y_curr, x_next, y_next * x_curr, y_next * y_curr,\n y_next, x_curr, y_curr, 1]'], {}), '([x_next * x_curr, x_next * y_curr, x_next, y_next * x_curr, y_next *\n y_curr, y_next, x_curr, y_curr, 1])\n', (5738, 5847), True, 'import numpy as np\n'), ((6869, 6916), 'numpy.array', 'np.array', (['[feature_curr[0], feature_curr[1], 1]'], {}), '([feature_curr[0], feature_curr[1], 1])\n', (6877, 6916), True, 'import numpy as np\n'), ((7421, 7461), 'numpy.matmul', 'np.matmul', (['self.k_mat.T', 'fundamental_mat'], {}), '(self.k_mat.T, fundamental_mat)\n', (7430, 7461), True, 'import numpy as np\n'), ((7627, 7646), 'numpy.matmul', 'np.matmul', (['u', 'sigma'], {}), '(u, sigma)\n', (7636, 7646), True, 'import numpy as np\n'), ((11220, 11265), 'math.atan2', 'atan2', (['rotation_mat[2][1]', 'rotation_mat[2][2]'], {}), '(rotation_mat[2][1], rotation_mat[2][2])\n', (11225, 11265), False, 'from math import sqrt, atan2\n'), ((11282, 11313), 'math.atan2', 'atan2', (['(-rotation_mat[2][1])', 'psi'], {}), '(-rotation_mat[2][1], psi)\n', (11287, 11313), False, 'from math import sqrt, atan2\n'), ((11330, 11375), 'math.atan2', 'atan2', (['rotation_mat[1][0]', 'rotation_mat[0][0]'], {}), '(rotation_mat[1][0], rotation_mat[0][0])\n', (11335, 11375), False, 'from math import sqrt, atan2\n'), ((11406, 11452), 'math.atan2', 'atan2', (['(-rotation_mat[1][2])', 'rotation_mat[1][1]'], {}), '(-rotation_mat[1][2], rotation_mat[1][1])\n', (11411, 11452), False, 'from math import sqrt, atan2\n'), ((11469, 11500), 'math.atan2', 'atan2', (['(-rotation_mat[2][0])', 'psi'], {}), '(-rotation_mat[2][0], psi)\n', (11474, 11500), False, 'from math import sqrt, atan2\n'), ((8802, 8829), 'numpy.linalg.det', 'np.linalg.det', (['rotation_mat'], {}), '(rotation_mat)\n', (8815, 8829), True, 'import numpy as np\n'), ((10008, 10060), 'numpy.hstack', 'np.hstack', (['(rotation_matrices[i], camera_centers[i])'], {}), '((rotation_matrices[i], camera_centers[i]))\n', (10017, 10060), True, 'import numpy as np\n'), ((15320, 15338), 'numpy.shape', 'np.shape', (['x_linear'], {}), '(x_linear)\n', (15328, 15338), True, 'import numpy as np\n'), ((7061, 7095), 'numpy.matmul', 'np.matmul', (['fn_new', 'fundamental_mat'], {}), '(fn_new, fundamental_mat)\n', (7070, 7095), True, 'import numpy as np\n'), ((10316, 10368), 'numpy.squeeze', 'np.squeeze', (['(r_mat_row @ (temp_x - camera_centers[i]))'], {}), '(r_mat_row @ (temp_x - camera_centers[i]))\n', (10326, 10368), True, 'import numpy as np\n'), ((14300, 14318), 'numpy.shape', 'np.shape', (['x_linear'], {}), '(x_linear)\n', (14308, 14318), True, 'import numpy as np\n'), ((14438, 14460), 'numpy.dot', 'np.dot', (['p_old[0]', 'x_pt'], {}), '(p_old[0], x_pt)\n', (14444, 14460), True, 'import numpy as np\n'), ((14463, 14485), 'numpy.dot', 'np.dot', (['p_old[2]', 'x_pt'], {}), '(p_old[2], x_pt)\n', (14469, 14485), True, 'import numpy as np\n'), ((14530, 14552), 'numpy.dot', 'np.dot', (['p_old[1]', 'x_pt'], {}), '(p_old[1], x_pt)\n', (14536, 14552), True, 'import numpy as np\n'), ((14555, 14577), 'numpy.dot', 'np.dot', (['p_new[2]', 'x_pt'], {}), '(p_new[2], x_pt)\n', (14561, 14577), True, 'import numpy as np\n'), ((14617, 14639), 'numpy.dot', 'np.dot', (['p_new[0]', 'x_pt'], {}), '(p_new[0], x_pt)\n', (14623, 14639), True, 'import numpy as np\n'), ((14642, 14664), 'numpy.dot', 'np.dot', (['p_new[2]', 'x_pt'], {}), '(p_new[2], x_pt)\n', (14648, 14664), True, 'import numpy as np\n'), ((14709, 14731), 'numpy.dot', 'np.dot', (['p_new[1]', 'x_pt'], {}), '(p_new[1], x_pt)\n', (14715, 14731), True, 'import numpy as np\n'), ((14734, 14756), 'numpy.dot', 'np.dot', (['p_old[2]', 'x_pt'], {}), '(p_old[2], x_pt)\n', (14740, 14756), True, 'import numpy as np\n')]
import time import configparser import numpy as np import re class PowerSupplyCalib(object): def __init__(self, ps, vstart, vend, vstep, scan_speed=1.5): self.vstart = vstart self.vend = vend self.vstep = vstep self.scan_vals = np.arange(self.vstart, self.vend+(0.5*self.vstep), self.vstep) self.ps = ps self.scan_speed = scan_speed self._scans = {} self._volt_key = 'VoltCalib' self._curr_key = 'CurrCalib' self._key_regex = re.compile('address\.([0-9]{3})') self._min_volt_addr = 59 self._max_volt_addr = 84 self._start_volt_val = 8 self._volt_per_addr = 8 self._min_curr_addr = 110 self._max_curr_addr = 142 self._start_curr_val = 0 self._curr_per_addr = 32 self._calib_types = { self._volt_key: range(self._min_volt_addr, self._max_volt_addr, 1), self._curr_key: range(self._min_curr_addr, self._max_curr_addr, 1), } self.prntstr = '{0:.1f}: {1:.2f}' def scan(self, name=None, residual=False): scan_result = [] if self.ps.voltage() < 0.01: self.ps.on() for val in self.scan_vals: self.ps.voltage(val) time.sleep(self.scan_speed) if residual: setp, _ = self.ps.setpoint() result = self.ps.voltage() - setp else: result = self.ps.voltage() scan_result.append(result) if name is None: return scan_result else: self._scans[name] = scan_result def dump(self, filename): config = configparser.ConfigParser() for k, v in self._calib_types.items(): config.add_section(k) for addr in v: config[k]['address.{:0>3d}'.format(addr)] = self.address(addr) with open(filename, 'w') as configfile: config.write(configfile) def load(self, filename): config = configparser.ConfigParser() config.read(filename) for calib_type in self._calib_types.keys(): for addr_key, value in config[calib_type].items(): match = self._key_regex.match(addr_key) if match: self.address(int(match.group(1)), value) @property def volt_addr(self): return self._calib_types[self._volt_key] @property def curr_addr(self): return self._calib_types[self._curr_key] def set_scan(self, vstart, vend, vstep, scan_speed=None): self._scans = {} self.vstart = vstart self.vend = vend self.vstep = vstep self.scan_vals = np.arange(self.vstart, self.vend+(0.5*self.vstep), self.vstep) if scan_speed is not None: self.scan_speed = scan_speed def set_scan_address(self, address): voltages = self.get_voltages(address) self.set_scan(voltages[0], voltages[-1], 0.1) def get_scan(self, name, show=False): if show and name in self._scans: print('\n'.join(self.prntstr.format(setp, res) for setp, res in zip(self.scan_vals, self._scans[name]))) else: return self._scans.get(name) def residual(self, name1, name2, show=False): avals = self.get_scan(name1) bvals = self.get_scan(name2) residuals = [a-b for a, b in zip(avals, bvals)] if show: print('\n'.join(self.prntstr.format(setp, res) for setp, res in zip(self.scan_vals, residuals))) else: return residuals def address(self, addr, val=None): if val is None: return self.ps.cmd('GEEP', '{:0>3d}'.format(addr)) else: self.ps.cmd('SEEP', '{addr:0>3d}{val}'.format(addr=addr, val=val)) def get_volt_address(self, voltage): return (int(voltage*10) - self._start_volt_val) // self._volt_per_addr + self._min_volt_addr def get_curr_address(self, current): return (int(current*100) - self._start_curr_val) // self._curr_per_addr + self._min_curr_addr def get_voltages(self, address): voltint = self._volt_per_addr * (address - self._min_volt_addr) + self._start_volt_val return [volt/10.0 for volt in range(voltint, voltint+self._volt_per_addr, 1)] def get_currents(self, address): currint = self._curr_per_addr * (address - self._min_curr_addr) + self._start_curr_val return [curr/100.0 for curr in range(currint, currint+self._curr_per_addr, 1)]
[ "time.sleep", "configparser.ConfigParser", "numpy.arange", "re.compile" ]
[((268, 332), 'numpy.arange', 'np.arange', (['self.vstart', '(self.vend + 0.5 * self.vstep)', 'self.vstep'], {}), '(self.vstart, self.vend + 0.5 * self.vstep, self.vstep)\n', (277, 332), True, 'import numpy as np\n'), ((514, 548), 're.compile', 're.compile', (['"""address\\\\.([0-9]{3})"""'], {}), "('address\\\\.([0-9]{3})')\n", (524, 548), False, 'import re\n'), ((1680, 1707), 'configparser.ConfigParser', 'configparser.ConfigParser', ([], {}), '()\n', (1705, 1707), False, 'import configparser\n'), ((2028, 2055), 'configparser.ConfigParser', 'configparser.ConfigParser', ([], {}), '()\n', (2053, 2055), False, 'import configparser\n'), ((2716, 2780), 'numpy.arange', 'np.arange', (['self.vstart', '(self.vend + 0.5 * self.vstep)', 'self.vstep'], {}), '(self.vstart, self.vend + 0.5 * self.vstep, self.vstep)\n', (2725, 2780), True, 'import numpy as np\n'), ((1270, 1297), 'time.sleep', 'time.sleep', (['self.scan_speed'], {}), '(self.scan_speed)\n', (1280, 1297), False, 'import time\n')]
import numpy as np import pickle import contrib_to_behavior import matplotlib import matplotlib.pyplot as plt import matplotlib.patches as mpatches from sklearn import svm matplotlib.rcParams['pdf.fonttype'] = 42 matplotlib.rcParams['ps.fonttype'] = 42 plt.rcParams["font.family"] = "arial" class neural_analysis: def __init__(self, model_filename, ABBA=False, old_format = False): x = pickle.load(open(model_filename, 'rb')) self.ABBA = ABBA # reshape STP depression self.syn_x = np.stack(x['syn_x'],axis=2) self.syn_x = np.stack(self.syn_x,axis=1) if self.syn_x.shape[0] == 0: self.syn_x = None else: num_neurons, trial_length, num_blocks, trials_per_block = self.syn_x.shape self.syn_x = np.reshape(self.syn_x,(num_neurons,trial_length,num_blocks*trials_per_block)) # reshape STP facilitation self.syn_u = np.stack(x['syn_u'],axis=2) self.syn_u = np.stack(self.syn_u,axis=1) if self.syn_u.shape[0] == 0: self.syn_u = None else: num_neurons, trial_length, num_blocks, trials_per_block = self.syn_u.shape self.syn_u = np.reshape(self.syn_u,(num_neurons,trial_length,num_blocks*trials_per_block)) # reshape RNN outputs self.rnn_outputs = np.stack(x['hidden_state'],axis=2) self.rnn_outputs = np.stack(self.rnn_outputs,axis=1) num_neurons, trial_length, num_blocks, trials_per_block = self.rnn_outputs.shape self.rnn_outputs = np.reshape(self.rnn_outputs,(num_neurons,trial_length,num_blocks*trials_per_block)) # reshape desired outputs self.desired_outputs = x['desired_output'] if old_format: self.desired_outputs = np.transpose(self.desired_outputs,(2,0,1)) # reshape train_mask self.train_mask = x['train_mask'] self.train_mask = np.transpose(self.train_mask,(0,1)) # reshape RNN inputs self.rnn_inputs = x['rnn_input'] self.rnn_inputs = np.transpose(self.rnn_inputs,(2,0,1)) # reshape model outputs self.model_outputs = np.stack(x['model_outputs'],axis=2) self.model_outputs = np.stack(self.model_outputs,axis=1) num_classes = self.model_outputs.shape[0] self.model_outputs = np.reshape(self.model_outputs,(num_classes,trial_length,num_blocks*trials_per_block)) """ rnn_inputs, desired_outputs, rnn_outputs, model_outputs should be of shape neurons X time X trials print(self.rnn_inputs.shape, self.desired_outputs.shape,self.rnn_outputs.shape,self.model_outputs.shape, self.train_mask.shape) """ # reshape trial_conds self.sample_dir = x['sample_dir'] self.test_dir = x['test_dir'] self.match = x['match'] self.rule = x['rule'] self.catch = x['catch'] self.probe = x['probe'] # for the ABBA trials if self.ABBA: self.num_test_stim = x['num_test_stim'] self.repeat_test_stim = x['repeat_test_stim'] self.ABBA_delay = x['params']['ABBA_delay'] # other info #self.EI_list = x['params']['EI_list'] self.num_rules = len(x['params']['possible_rules']) self.possible_rules = x['params']['possible_rules'] self.num_motion_dirs = x['params']['num_motion_dirs'] self.U = x['U'] self.W_rnn = x['w_rnn'] self.b_rnn = x['b_rnn'] self.W_in = x['w_in'] self.EI_list = x['params']['EI_list'] self.dead_time = x['params']['dead_time'] self.fix_time = x['params']['fix_time'] self.delta_t = x['params']['dt'] if self.ABBA: self.max_num_tests = x['params']['max_num_tests'] self.ABBA_accuracy_match, self.ABBA_accuracy_non_match = self.performance_ABBA() else: pass #accuracy = self.performance() #print(accuracy) def calc_native_tuning(self): rule = 0 sample_rng = range(8+20,8+20+20) #sample_rng = range(88,108) num_dirs = self.num_motion_dirs num_input_neurons, trial_length, num_trials = self.rnn_inputs.shape mean_input_resp = np.zeros((num_input_neurons, num_dirs)) num_rnn_neurons = self.rnn_outputs.shape[0] native_tuning = np.zeros((num_rnn_neurons, num_dirs)) for d in range(num_dirs): ind = np.where((self.rule == self.possible_rules[rule])*(self.sample_dir==d)) #ind = np.where((self.rule == self.possible_rules[rule])*(self.test_dir==d)) s = np.mean(self.rnn_inputs[:,:,ind[0]],axis=2) mean_input_resp[:,d] = np.mean(s[:,sample_rng],axis=1) native_tuning = np.dot(self.W_in, mean_input_resp) return native_tuning def motion_tuning(self): num_neurons, trial_length, num_trials = self.rnn_outputs.shape sample_pd = np.zeros((num_neurons, trial_length)) sample_pev = np.zeros((num_neurons, trial_length)) sample_amp = np.zeros((num_neurons, trial_length)) test_pd = np.zeros((num_neurons, 2, trial_length)) test_pev = np.zeros((num_neurons, 2, trial_length)) test_amp = np.zeros((num_neurons, 2, trial_length)) sample_dir = np.ones((num_trials, 3)) sample_dir[:,1] = np.cos(2*np.pi*self.sample_dir/self.num_motion_dirs) sample_dir[:,2] = np.sin(2*np.pi*self.sample_dir/self.num_motion_dirs) test_dir = np.ones((num_trials, 3)) test_dir[:,1] = np.cos(2*np.pi*self.test_dir/self.num_motion_dirs) test_dir[:,2] = np.sin(2*np.pi*self.test_dir/self.num_motion_dirs) for n in range(num_neurons): for t in range(trial_length): h = np.linalg.lstsq(sample_dir, self.rnn_outputs[n,t,:]) pred_err = self.rnn_outputs[n,t,:] - np.dot(h[0], sample_dir.T) mse = np.mean(pred_err**2) response_var = np.var(self.rnn_outputs[n,t,:]) sample_pev[n,t] = 1 - (mse)/(response_var+1e-9) sample_pd[n,t] = np.arctan2(h[0][2],h[0][1]) sample_amp[n,t] = np.sqrt(h[0][0]**2+h[0][1]**2) for m in range(2): ind = np.where(self.match==m)[0] h = np.linalg.lstsq(test_dir[ind], self.rnn_outputs[n,t,ind]) pred_err = self.rnn_outputs[n,t,ind] - np.dot(h[0], test_dir[ind].T) mse = np.mean(pred_err**2) response_var = np.var(self.rnn_outputs[n,t,ind]) test_pev[n,m,t] = 1 - (mse)/(response_var+1e-9) test_pd[n,m,t] = np.arctan2(h[0][2],h[0][1]) test_amp[n,m,t] = np.sqrt(h[0][0]**2+h[0][1]**2) return sample_pd, sample_pev, sample_amp, test_pd, test_pev, test_amp def recreate_effective_weight_matrix(self, EI = False): rule = 0 num_neurons, trial_length, num_trials = self.syn_u.shape W = np.zeros((num_neurons,num_neurons,self.num_motion_dirs, trial_length)) mean_efficacy = np.zeros((num_neurons,self.num_motion_dirs, trial_length)) for d in range(self.num_motion_dirs): ind = np.where((self.rule == self.possible_rules[rule])*(self.sample_dir==d)*(self.match==1))[0] mean_efficacy[:,d,:] = np.mean(self.syn_u[:,:,ind]*self.syn_x[:,:,ind],axis=2) if EI: ei_diag = np.diag(self.EI_list) W_rnn = np.dot(np.maximum(0,self.W_rnn), ei_diag) else: W_rnn = self.W_rnn for n1 in range(num_neurons): for n2 in range(num_neurons): for d in range(self.num_motion_dirs): W[n1,n2,d,:] = mean_efficacy[n2,d,:]*W_rnn[n1,n2] return W def recreate_output_current(self, EI = False): rule = 0 num_neurons, trial_length, num_trials = self.syn_u.shape out_current = np.zeros((num_neurons,self.num_motion_dirs, self.num_motion_dirs, trial_length)) out_current = np.zeros((num_neurons,self.num_motion_dirs, self.num_motion_dirs, trial_length)) for s in range(self.num_motion_dirs): for t in range(self.num_motion_dirs): ind = np.where((self.rule == self.possible_rules[rule])*(self.sample_dir==s)*(self.test_dir==t))[0] out_current[:,s,t,:] = np.mean(self.syn_u[:,:,ind]*self.syn_x[:,:,ind]*self.rnn_outputs[:,:,ind],axis=2) """ if EI: ei_diag = np.diag(self.EI_list) W_rnn = np.dot(np.maximum(0,self.W_rnn), ei_diag) else: W_rnn = self.W_rnn for n1 in range(num_neurons): for n2 in range(num_neurons): for s in range(self.num_motion_dirs): for t in range(self.num_motion_dirs): out_current[n1,n2,s,t,:] = post_syn[n2,s,t,:]*W_rnn[n1,n2] """ return out_current def performance(self): n = 18 # number of time steps to measure during test, this will be the basis of performance time_correct = np.zeros((self.num_rules, self.num_motion_dirs, 2)) count = np.zeros((self.num_rules, self.num_motion_dirs, 2)) for i in range(len(self.sample_dir)): if self.catch[i]==0: s = np.int_(self.sample_dir[i]) m = np.int_(self.match[i]) r = np.int_(np.where(self.rule[i]==self.possible_rules)[0]) count[r,s,m] +=1 if m==1: score=np.mean((self.model_outputs[2,-n:,i]>self.model_outputs[1,-n:,i])*(self.model_outputs[2,-n:,i]>self.model_outputs[0,-n:,i])) else: score=np.mean((self.model_outputs[1,-n:,i]>self.model_outputs[2,-n:,i])*(self.model_outputs[1,-n:,i]>self.model_outputs[0,-n:,i])) time_correct[r,s,m] += score return time_correct/count def performance_ABBA(self): ABBA_delay = self.ABBA_delay//self.delta_t eof = (self.dead_time+self.fix_time)//self.delta_t eos = eof + ABBA_delay # performance is measured with and without a repeated distractor time_correct_match = np.zeros((self.max_num_tests)) time_correct_non_match = np.zeros((self.max_num_tests)) time_match = np.zeros((self.max_num_tests)) time_non_match = np.zeros((self.max_num_tests)) for i in range(len(self.sample_dir)): for j in range(self.num_test_stim[i]): # will discard the first time point of each test stim test_rng = range(1+eos+(2*j+1)*ABBA_delay, eos+(2*j+2)*ABBA_delay) matching_stim = self.match[i]==1 and j==self.num_test_stim[i]-1 if matching_stim: time_match[j] += ABBA_delay-1 # -1 because we're discarding the first time point of each test stim time_correct_match[j] += np.sum((self.model_outputs[2,test_rng,i]>self.model_outputs[1,test_rng,i])*(self.model_outputs[2,test_rng,i]>self.model_outputs[0,test_rng,i])) else: time_non_match[j] += ABBA_delay-1 time_correct_non_match[j] += np.sum((self.model_outputs[1,test_rng,i]>self.model_outputs[2,test_rng,i])*(self.model_outputs[1,test_rng,i]>self.model_outputs[0,test_rng,i])) auccracy_match = time_correct_match/time_match auccracy_non_match = time_correct_non_match/time_non_match print('Accuracy') print(time_correct_non_match, time_non_match) print(time_correct_match, time_match) return auccracy_match, auccracy_non_match def show_results(self): print(self.results) def plot_example_neurons(self, example_numbers): mean_resp = calc_mean_responses(self) 1/0 f = plt.figure(figsize=(12,8)) ax = f.add_subplot(1, 3, 1) ax.imshow(trial_info['sample_direction'],interpolation='none',aspect='auto') ax = f.add_subplot(1, 3, 2) ax.imshow(trial_info['test_direction'],interpolation='none',aspect='auto') ax = f.add_subplot(1, 3, 3) ax.imshow(trial_info['match'],interpolation='none',aspect='auto') plt.show() 1/0 def calculate_svms(self, num_reps = 3, DMC = [False], decode_test = False): lin_clf = svm.SVC(C=1,kernel='linear',decision_function_shape='ovr', shrinking=False, tol=1e-4) num_neurons, trial_length, num_trials = self.rnn_outputs.shape spike_decoding = np.zeros((trial_length,self.num_rules,num_reps)) synapse_decoding = np.zeros((trial_length,self.num_rules,num_reps)) spike_decoding_test = np.zeros((trial_length,self.num_rules,num_reps)) synapse_decoding_test = np.zeros((trial_length,self.num_rules,num_reps)) N = self.num_motion_dirs sample_cat = np.floor(self.sample_dir/(self.num_motion_dirs/2)*np.ones_like(self.sample_dir)) if self.ABBA: test_dir = self.test_dir[:,0] else: test_dir = self.test_dir test_cat = np.floor(test_dir/(self.num_motion_dirs/2)*np.ones_like(test_dir)) for r in range(self.num_rules): if self.ABBA: ind = np.where((self.num_test_stim>=4))[0] else: ind = np.where((self.rule==self.possible_rules[r]))[0] for t in range(trial_length): if DMC[r]: spike_decoding[t,r,:] = self.calc_svm_equal_trials(lin_clf,self.rnn_outputs[:,t,ind].T, sample_cat[ind],num_reps,2) if decode_test: spike_decoding_test[t,r,:] = self.calc_svm_equal_trials(lin_clf,self.rnn_outputs[:,t,ind].T, test_cat[ind],num_reps,2) else: spike_decoding[t,r,:] = self.calc_svm_equal_trials(lin_clf,self.rnn_outputs[:,t,ind].T, self.sample_dir[ind],num_reps,N) if decode_test: spike_decoding_test[t,r,:] = self.calc_svm_equal_trials(lin_clf,self.rnn_outputs[:,t,ind].T, test_dir[ind],num_reps,N) if self.syn_x is not None: effective_current = self.syn_x[:,t,ind].T*self.syn_u[:,t,ind].T if DMC[r]: synapse_decoding[t,r,:] = self.calc_svm_equal_trials(lin_clf,effective_current, sample_cat[ind],num_reps,2) if decode_test: synapse_decoding_test[t,r,:] = self.calc_svm_equal_trials(lin_clf,effective_current, test_cat[ind],num_reps,2) else: synapse_decoding[t,r,:] = self.calc_svm_equal_trials(lin_clf,effective_current, self.sample_dir[ind],num_reps,N) if decode_test: synapse_decoding_test[t,r,:] = self.calc_svm_equal_trials(lin_clf,effective_current, test_dir[ind],num_reps,N) return spike_decoding, synapse_decoding, spike_decoding_test, synapse_decoding_test def calculate_autocorr(self, time_start, time_end): num_neurons, trial_length, num_trials = self.rnn_outputs.shape num_lags = time_end-time_start spike_autocorr = np.zeros((num_neurons, num_lags)) syn_x_autocorr = np.zeros((num_neurons, num_lags)) syn_adapt_autocorr = np.zeros((num_neurons, num_lags)) for n in range(num_neurons): count = np.zeros((num_lags)) for i in range(time_start, time_end): for j in range(time_start, time_end): lag = np.abs(i-j) for s in range(4): ind = np.where(self.sample_dir==s) ind = np.where(self.match==1) ind = ind[0] count[lag] += 1 r1 = np.corrcoef(self.rnn_outputs[n,i,ind], self.rnn_outputs[n,j,ind]) spike_autocorr[n, lag] += r1[0,1] if self.syn_x is not None: r1 = np.corrcoef(self.syn_x[n,i,ind], self.syn_x[n,j,ind]) syn_x_autocorr[n, lag] += r1[0,1] if self.sa is not None: r1 = np.corrcoef(self.sa[n,i,ind], self.sa[n,j,ind]) syn_adapt_autocorr[n, lag] += r1[0,1] spike_autocorr[n,:] /= count syn_x_autocorr[n,:] /= count syn_adapt_autocorr[n,:] /= count return spike_autocorr,syn_x_autocorr,syn_adapt_autocorr def calc_mean_responses(self): num_rules = self.num_rules num_dirs = self.num_motion_dirs num_neurons, trial_length, num_trials = self.rnn_outputs.shape num_classes = self.model_outputs.shape[0] mean_resp = np.zeros((num_neurons, num_rules, num_dirs, trial_length)) mean_out_match = np.zeros((num_classes, num_rules, trial_length)) mean_out_non_match = np.zeros((num_classes, num_rules, trial_length)) for n in range(num_neurons): for r in range(num_rules): for d in range(num_dirs): if self.ABBA: ind = np.where((self.num_test_stim>=4)*(self.sample_dir==d))[0] else: ind = np.where((self.rule == self.possible_rules[r])*(self.sample_dir==d))[0] mean_resp[n,r,d,:] = np.mean(self.rnn_outputs[n,:,ind],axis=0) for n in range(num_classes): for r in range(num_rules): ind_match = np.where((self.rule == self.possible_rules[r])*(self.match==1)*(self.catch==0)) ind_non_match = np.where((self.rule == self.possible_rules[r])*(self.match==0)*(self.catch==0)) mean_out_match[n,r,:] = np.mean(self.model_outputs[n,:,ind_match[0]],axis=0) mean_out_non_match[n,r,:] = np.mean(self.model_outputs[n,:,ind_non_match[0]],axis=0) return mean_resp, mean_out_match, mean_out_non_match def decoding_accuracy_postle(self, num_reps = 10): lin_clf = svm.SVC(C=1,kernel='linear',decision_function_shape='ovr', shrinking=False, tol=1e-5) num_neurons, trial_length, num_trials = self.rnn_outputs.shape sample_pev = np.zeros((num_neurons, 2,2,2,2,trial_length)) sample_stp_pev = np.zeros((num_neurons, 2,2,2,2,trial_length)) sample_decoding = np.zeros((2,2,2,2,trial_length,num_reps)) sample_stp_decoding = np.zeros((2,2,2,2,trial_length,num_reps)) model_output = np.zeros((2,2,3,trial_length)) # r1 and r2 refer to the first and second rule (attention) cue # m refers to the modality # p refers to the presence or absence of a probe for m1 in range(2): for m2 in range(2): ind = np.where((self.match[:,0] == m1)*(self.match[:,1] == m2)*(self.probe[:,1]==0))[0] model_output[m1,m2,:,:] = np.mean(self.model_outputs[:,:,ind],axis=2) for r1 in range(2): for r2 in range(2): for p in range(2): ind = np.where((self.rule[:,0] == r1)*(self.rule[:,1] == r2)*(self.probe[:,1]==p))[0] #ind = np.where((self.rule[:,0] == r1)*(self.rule[:,1] == r2)*(self.probe[:,1]>=0))[0] for m in range(2): for t in range(trial_length): for n in range(num_neurons): sample_pev[n,r1,r2,p,m,t] = self.calc_pev(self.rnn_outputs[n,t,ind], self.sample_dir[ind,m]) sample_decoding[r1,r2,p,m,t,:] = self.calc_svm_equal_trials(lin_clf,self.rnn_outputs[:,t,ind].T, self.sample_dir[ind,m],num_reps, self.num_motion_dirs) if self.syn_x is not None: for n in range(num_neurons): effective_current = self.syn_x[n,t,ind]*self.syn_u[n,t,ind] sample_stp_pev[n,r1,r2,p,m,t] = self.calc_pev(effective_current, self.sample_dir[ind,m]) effective_current = self.syn_x[:,t,ind]*self.syn_u[:,t,ind] sample_stp_decoding[r1,r2,p,m,t,:] = self.calc_svm_equal_trials(lin_clf,effective_current.T, self.sample_dir[ind,m],num_reps, self.num_motion_dirs) return sample_pev, sample_stp_pev, sample_decoding, sample_stp_decoding, model_output @staticmethod def calc_svm_equal_trials(lin_clf, y, conds, num_reps, num_conds): # normalize values between 0 and 1 for i in range(y.shape[1]): m1 = y[:,i].min() m2 = y[:,i].max() y[:,i] -= m1 if m2>m1: y[:,i] /=(m2-m1) """ Want to ensure that all conditions have the same number of trials Will find the min number of trials per conditions, and remove trials above the min number """ num_trials = np.zeros((num_conds)) for i in range(num_conds): num_trials[i] = np.sum(conds==i) min_num_trials = int(np.min(num_trials)) conds_equal = np.zeros((min_num_trials*num_conds)) y_equal = np.zeros((min_num_trials*num_conds, y.shape[1])) for i in range(num_conds): ind = np.where(conds==i)[0] ind = ind[:min_num_trials] conds_equal[i*min_num_trials:(i+1)*min_num_trials] = i y_equal[i*min_num_trials:(i+1)*min_num_trials, :] = y[ind,:] train_pct = 0.75 score = np.zeros((num_reps)) for r in range(num_reps): q = np.random.permutation(len(conds_equal)) i = np.int_(np.round(len(conds_equal)*train_pct)) train_ind = q[:i] test_ind = q[i:] lin_clf.fit(y_equal[train_ind,:], conds_equal[train_ind]) #dec = lin_clf.decision_function(y[test_ind,:]) dec = lin_clf.predict(y_equal[test_ind,:]) for i in range(len(test_ind)): if conds_equal[test_ind[i]]==dec[i]: score[r] += 1/len(test_ind) return score @staticmethod def calc_svm(lin_clf, y, conds, num_reps): num_conds = len(np.unique(conds)) y = np.squeeze(y).T # normalize values between 0 and 1 for i in range(y.shape[1]): m1 = y[:,i].min() m2 = y[:,i].max() y[:,i] -= m1 if m2>m1: y[:,i] /=(m2-m1) train_pct = 0.75 score = np.zeros((num_reps)) for r in range(num_reps): q = np.random.permutation(len(conds)) i = np.int_(np.round(len(conds)*train_pct)) train_ind = q[:i] test_ind = q[i:] lin_clf.fit(y[train_ind,:], conds[train_ind]) dec = lin_clf.decision_function(y[test_ind,:]) if num_conds>2: dec = np.argmax(dec, 1) else: dec = np.int_(np.sign(dec)*0.5+0.5) for i in range(len(test_ind)): if conds[test_ind[i]]==dec[i]: score[r] += 1/len(test_ind) return score def calculate_pevs(self): num_neurons, trial_length, num_trials = self.rnn_outputs.shape sample_pev = np.zeros((num_neurons, self.num_rules,trial_length)) test_pev = np.zeros((num_neurons, self.num_rules,trial_length)) rule_pev = np.zeros((num_neurons,trial_length)) match_pev = np.zeros((num_neurons, self.num_rules,trial_length)) sample_stp_pev = np.zeros((num_neurons, self.num_rules,trial_length)) sample_cat_pev = np.zeros((num_neurons, self.num_rules,trial_length)) sample_cat_stp_pev = np.zeros((num_neurons, self.num_rules,trial_length)) test_stp_pev = np.zeros((num_neurons, self.num_rules,trial_length)) for r in range(self.num_rules): if self.ABBA: ind = np.where((self.num_test_stim>=4))[0] else: ind = np.where((self.rule == self.possible_rules[r]))[0] ind_test = np.where((self.rule == self.possible_rules[r])*(self.match == 0))[0] for n in range(num_neurons): for t in range(trial_length): sample_pev[n,r,t] = self.calc_pev(self.rnn_outputs[n,t,ind], self.sample_dir[ind]) sample_cat_pev[n,r,t] = self.calc_pev(self.rnn_outputs[n,t,ind], np.floor(self.sample_dir[ind]/(self.num_motion_dirs/2))) if not self.ABBA: test_pev[n,r,t] = self.calc_pev(self.rnn_outputs[n,t,ind_test], self.test_dir[ind_test]) rule_pev[n,t] = self.calc_pev(self.rnn_outputs[n,t,:], self.rule) match_pev[n,r,t] = self.calc_pev(self.rnn_outputs[n,t,ind], self.match[ind]) if self.syn_x is not None: effective_current = self.syn_x[n,t,ind]*self.syn_u[n,t,ind] sample_stp_pev[n,r,t] = self.calc_pev(effective_current, self.sample_dir[ind]) if not self.ABBA: test_stp_pev[n,r,t] = self.calc_pev(effective_current, self.test_dir[ind_test]) sample_cat_stp_pev[n,r,t] = self.calc_pev(effective_current, np.floor(self.sample_dir[ind]/(self.num_motion_dirs/2))) return sample_pev, test_pev, rule_pev, match_pev, sample_stp_pev, sample_cat_pev, sample_cat_stp_pev, test_stp_pev @staticmethod def calc_pev(x, conds): unique_conds = np.unique(conds) m = len(unique_conds) lx = len(x) xr = x - np.mean(x) xm = np.zeros((1,m)) countx = np.zeros((1,m)) for (j,i) in enumerate(unique_conds): ind = np.where(conds==i) countx[0,j] = len(ind[0]) xm[0,j] = np.mean(xr[ind[0]]) gm = np.mean(xr) df1 = np.sum(countx>0)-1 df2 = lx - df1 - 1 xc = xm - gm ix = np.where(countx==0) xc[ix] = 0 RSS = np.dot(countx, np.transpose(xc**2)) #TSS = (xr - gm)**2 TSS = np.dot(np.transpose(xr - gm),xr - gm) #print(TSS.shape) SSE = TSS - RSS if df2 > 0: mse = SSE/df2 else: mse = np.NaN F = (RSS/df1)/mse """ Table = np.zeros((3,5)) Table[:,0] = [RSS,SSE,TSS] Table[:,1] = [df1,df2,df1+df2] Table[:,2] = [RSS/df1,mse,999]; Table[:,3] = [F,999,999] """ SS_groups = RSS; SS_total = TSS; df_groups = df1; MS_error = mse; pev = (SS_groups-df_groups*MS_error)/(SS_total+MS_error) if np.isnan(pev): pev = 0 return pev def plot_all_figures(self, rule,dt=25, STP=False, DMC = [False], f=None, start_sp=0, num_rows=3, tight=False, two_rules = False, decode_test = False): font = {'family' : 'normal', 'weight' : 'bold', 'size' : 12} mean_resp, mean_out_match, mean_out_non_match = self.calc_mean_responses() spike_decode, synapse_decode, spike_decode_test, synapse_decode_test = self.calculate_svms(DMC=DMC,decode_test=decode_test) sample_pev, test_pev, rule_pev, _, sample_stp_pev, sample_cat_pev, sample_cat_stp_pev, test_stp_pev = self.calculate_pevs() if DMC[0]: sample_pev = sample_cat_pev sample_stp_pev = sample_cat_stp_pev chance_level = 1/2 else: chance_level = 1/8 if two_rules: num_cols = 4 else: num_cols = 3 # find good example neuron mean_pev = np.mean(sample_pev[:, rule, 30:],axis=1) ind = np.argsort(mean_pev) example_neuron = ind[-1] trial_length_steps = sample_pev.shape[2] trial_length = np.int_(trial_length_steps*dt) t = np.arange(0,trial_length,dt) t -= 900 # assuming 400 ms dead time, 500 ms fixation if self.ABBA: t0,t1,t2,t3 = np.where(t==-500), np.where(t==0),np.where(t==500),np.where(t==1500) else: t0,t1,t2,t3 = np.where(t==-500), np.where(t==0),np.where(t==500),np.where(t==1500) if f is None: f = plt.figure(figsize=(8,2*num_rows)) ax = f.add_subplot(num_rows, num_cols, start_sp+1) if self.ABBA: # plot accuracy bar plot instead x=np.array([0,1,2,3]) ax.bar(x+0.1, self.ABBA_accuracy_match,width=0.2,color='r',align='center') ax.bar(x-0.1, self.ABBA_accuracy_non_match,width=0.2,color='b',align='center') ax.set_title('Accuracy') ax.set_ylabel('Fraction correct') ax.set_xlabel('Num. of distractors') else: ax.hold(True) if two_rules: ax.plot(t, mean_out_match[0,0,:] ,'k',linewidth=2,label='Fixation') ax.plot(t, mean_out_match[1,0,:] ,'m',linewidth=2,label='Non-match') ax.plot(t, mean_out_match[2,0,:] ,'g',linewidth=2,label='Match') ax.plot(t, mean_out_match[0,1,:] ,'k--',linewidth=2,label='Fixation') ax.plot(t, mean_out_match[1,1,:] ,'m--',linewidth=2,label='Non-match') ax.plot(t, mean_out_match[2,1,:] ,'g--',linewidth=2,label='Match') else: ax.plot(t, mean_out_match[0,rule,:] ,'k',linewidth=2,label='Fixation') ax.plot(t, mean_out_match[1,rule,:] ,'m',linewidth=2,label='Non-match') ax.plot(t, mean_out_match[2,rule,:] ,'g',linewidth=2,label='Match') #plt.legend(loc=3) self.add_subplot_fixings(ax) ax.set_title('Network output - match trials') if self.ABBA: pass else: ax = f.add_subplot(num_rows, num_cols, start_sp+2) ax.hold(True) if two_rules: ax.plot(t, mean_out_non_match[0,0,:] ,'k',linewidth=2,label='Fixation') ax.plot(t, mean_out_non_match[1,0,:] ,'m',linewidth=2,label='Non-match') ax.plot(t, mean_out_non_match[2,0,:] ,'g',linewidth=2,label='Match') ax.plot(t, mean_out_non_match[0,1,:] ,'k--',linewidth=2,label='Fixation') ax.plot(t, mean_out_non_match[1,1,:] ,'m--',linewidth=2,label='Non-match') ax.plot(t, mean_out_non_match[2,1,:] ,'g--',linewidth=2,label='Match') else: ax.plot(t, mean_out_non_match[0,rule,:] ,'k',linewidth=2) ax.plot(t, mean_out_non_match[1,rule,:] ,'m',linewidth=2) ax.plot(t, mean_out_non_match[2,rule,:] ,'g',linewidth=2) self.add_subplot_fixings(ax) ax.set_title('Network output - non-match trials') ax = f.add_subplot(num_rows, num_cols, start_sp+3) ax.hold(True) # if plotting the result of the delayed rule task, show rule PEV instead of example neuron if two_rules: max_val = np.max(rule_pev) ax.plot(t,np.mean(rule_pev, axis=0), linewidth=2) self.add_subplot_fixings(ax,chance_level=0,ylim=0.2) ax.set_title('Rule selectivity') ax.set_ylabel('Normalized PEV') else: """ max_val = np.max(mean_resp[example_neuron,rule,:,:]) print(max_val) for i in range(8): ax.plot(t,mean_resp[example_neuron,rule,i,:],color=[1-i/7,0,i/7], linewidth=1) self.add_subplot_fixings(ax,chance_level=0,ylim=max_val*1.05) ax.set_title('Example neuron') ax.set_ylabel('Activity (a.u.)') # plot the mean population response from those neurons whose synapses are informative of sample """ #syn_pev = np.mean(sample_stp_pev[:,0,t2[0]:t3[0]], axis=1) #ind_syn = np.where(syn_pev > 0.1)[0] #print('Informative synapses ', ind_syn) s = np.mean(mean_resp[:,rule,:,:],axis=0) max_val = np.max(s) for i in range(8): ax.plot(t,s[i,:],color=[1-i/7,0,i/7], linewidth=1) self.add_subplot_fixings(ax,chance_level=0,ylim=0.5) ax.set_title('Mean response from synpases informative neurons') ax.set_ylabel('Activity (a.u.)') ax.set_ylim([0, 0.5]) if two_rules: ax = f.add_subplot(num_rows, num_cols, start_sp+5) im = ax.imshow(sample_pev[:,0,:],aspect='auto',interpolation=None) f.colorbar(im,orientation='vertical') ax.spines['right'].set_visible(False) ax.set_ylabel('Neuron number') ax.set_xlabel('Time relative to sample onset (ms)') ax.spines['top'].set_visible(False) ax.set_xticks([t0[0], t1[0], t2[0], t3[0]]) ax.set_xticklabels([-500,0,500,1500]) ax.set_title('Neuronal sample \nselectvity - DMS task') ax = f.add_subplot(num_rows, num_cols, start_sp+6) im = ax.imshow(sample_pev[:,1,:],aspect='auto',interpolation=None) f.colorbar(im,orientation='vertical') ax.spines['right'].set_visible(False) ax.set_ylabel('Neuron number') ax.set_xlabel('Time relative to sample onset (ms)') ax.spines['top'].set_visible(False) ax.set_xticks([t0[0], t1[0], t2[0], t3[0]]) ax.set_xticklabels([-500,0,500,1500]) ax.set_title('Neuronal sample \nselectvity - DMrS task') else: ax = f.add_subplot(num_rows, 3, start_sp+4) im = ax.imshow(sample_pev[:,rule,:],aspect='auto',interpolation=None) f.colorbar(im,orientation='vertical') ax.spines['right'].set_visible(False) ax.set_ylabel('Neuron number') ax.set_xlabel('Time relative to sample onset (ms)') ax.spines['top'].set_visible(False) if DMC: ax.set_title('Neuronal sample \ncategory selectvity') else: ax.set_title('Neuronal sample selectvity') if self.ABBA: ax.set_xticks([t0[0], t1[0], t2[0], t3[0]]) ax.set_xticklabels([-500,0,500,1500]) else: ax.set_xticks([t0[0], t1[0], t2[0], t3[0]]) ax.set_xticklabels([-500,0,500,1500]) if two_rules: ax = f.add_subplot(num_rows, num_cols, start_sp+7) plt.hold(True) u = np.mean(sample_pev[:,0,:],axis=0) se = np.std(sample_pev[:,0,:],axis=0)/np.sqrt(sample_pev.shape[0]) ax.plot(t,u,'g') sample_max1 = np.max(u) ax.fill_between(t,u-se,u+se,facecolor=(0,1,0,0.5)) u = np.mean(sample_pev[:,1,:],axis=0) se = np.std(sample_pev[:,1,:],axis=0)/np.sqrt(sample_pev.shape[0]) ax.plot(t,u,'m') sample_max = np.max(u) sample_max = np.max([sample_max, sample_max1]) ax.fill_between(t,u-se,u+se,facecolor=(1,0,1,0.5)) else: ax = f.add_subplot(num_rows, num_cols, start_sp+5) u = np.mean(sample_pev[:,rule,:],axis=0) se = np.std(sample_pev[:,rule,:],axis=0)/np.sqrt(sample_pev.shape[0]) ax.plot(t,u,'k') sample_max = np.max(u) ax.fill_between(t,u-se,u+se,facecolor=(0,0,0,0.5)) self.add_subplot_fixings(ax,chance_level=0,ylim=sample_max*2) if DMC: ax.set_title('Neuronal sample \ncategory selectivity') else: ax.set_title('Neuronal sample selectivity') ax.set_ylabel('Normalized PEV') if two_rules: ax = f.add_subplot(num_rows, num_cols, start_sp+8) u = np.mean(spike_decode[:,0,:],axis=1) se = np.std(spike_decode[:,0,:],axis=1) ax.plot(t,u,'g') ax.fill_between(t,u-se,u+se,facecolor=(0,1,0,0.5)) u = np.mean(spike_decode[:,1,:],axis=1) se = np.std(spike_decode[:,1,:],axis=1) ax.plot(t,u,'m') ax.fill_between(t,u-se,u+se,facecolor=(1,0,1,0.5)) self.add_subplot_fixings(ax, chance_level=chance_level) else: ax = f.add_subplot(num_rows, num_cols, start_sp+6) u = np.mean(spike_decode[:,rule,:],axis=1) se = np.std(spike_decode[:,rule,:],axis=1) ax.plot(t,u,'k') ax.fill_between(t,u-se,u+se,facecolor=(0,0,0,0.5)) u = np.mean(spike_decode_test[:,rule,:],axis=1) se = np.std(spike_decode_test[:,rule,:],axis=1) ax.plot(t,u,'c') ax.fill_between(t,u-se,u+se,facecolor=(0,1,1,0.5)) self.add_subplot_fixings(ax, chance_level=chance_level) if DMC: ax.set_title('Neuronal sample \ncategory decoding') else: ax.set_title('Neuronal sample decoding') ax.set_ylabel('Decoding accuracy') # add short term plasticity plots if STP: if two_rules: ax = f.add_subplot(num_rows, num_cols, start_sp+9) im = ax.imshow(sample_stp_pev[:,0,:],aspect='auto',interpolation=None) f.colorbar(im,orientation='vertical') ax.spines['right'].set_visible(False) ax.set_ylabel('Neuron number') ax.set_xlabel('Time relative to sample onset (ms)') ax.spines['top'].set_visible(False) ax.set_xticks([t0[0], t1[0], t2[0], t3[0]]) ax.set_xticklabels([-500,0,500,1500]) ax.set_title('Synaptic sample \nselectvity - DMS task') ax = f.add_subplot(num_rows, num_cols, start_sp+10) im = ax.imshow(sample_stp_pev[:,1,:],aspect='auto',interpolation=None) f.colorbar(im,orientation='vertical') ax.spines['right'].set_visible(False) ax.set_ylabel('Neuron number') ax.set_xlabel('Time relative to sample onset (ms)') ax.spines['top'].set_visible(False) ax.set_xticks([t0[0], t1[0], t2[0], t3[0]]) ax.set_xticklabels([-500,0,500,1500]) ax.set_title('Synaptic sample \nselectvity - DMrS task') else: ax = f.add_subplot(num_rows, 3, start_sp+7) im = ax.imshow(sample_stp_pev[:,rule,:],aspect='auto',interpolation=None) f.colorbar(im,orientation='vertical') ax.spines['right'].set_visible(False) ax.set_ylabel('Neuron number') ax.set_xlabel('Time relative to sample onset (ms)') ax.spines['top'].set_visible(False) if DMC: ax.set_title('Synaptic sample \ncategory selectvity') else: ax.set_title('Synaptic sample selectvity') if self.ABBA: ax.set_xticks([t0[0], t1[0], t2[0], t3[0]]) ax.set_xticklabels([-500,0,500,1500]) else: ax.set_xticks([t0[0], t1[0], t2[0], t3[0]]) ax.set_xticklabels([-500,0,500,1500]) if two_rules: ax = f.add_subplot(num_rows, num_cols, start_sp+11) plt.hold(True) u = np.mean(sample_stp_pev[:,0,:],axis=0) se = np.std(sample_stp_pev[:,0,:],axis=0)/np.sqrt(sample_pev.shape[0]) ax.plot(t,u,'g') ax.fill_between(t,u-se,u+se,facecolor=(0,1,0,0.5)) u = np.mean(sample_stp_pev[:,1,:],axis=0) se = np.std(sample_stp_pev[:,1,:],axis=0)/np.sqrt(sample_pev.shape[0]) ax.plot(t,u,'m') ax.fill_between(t,u-se,u+se,facecolor=(1,0,1,0.5)) ax.set_title('Synaptic sample selectivity') else: ax = f.add_subplot(num_rows, num_cols, start_sp+8) u = np.mean(sample_stp_pev[:,rule,:],axis=0) se = np.std(sample_stp_pev[:,rule,:],axis=0)/np.sqrt(sample_pev.shape[0]) ax.plot(t,u,'k') ax.fill_between(t,u-se,u+se,facecolor=(0,0,0,0.5)) if DMC: ax.set_title('Synaptic sample \ncategory selectivity') else: ax.set_title('Synaptic sample selectivity') self.add_subplot_fixings(ax,chance_level=0,ylim=sample_max*2) ax.set_ylabel('Normalized PEV') if two_rules: ax = f.add_subplot(num_rows, num_cols, start_sp+12) u = np.mean(synapse_decode[:,0,:],axis=1) se = np.std(synapse_decode[:,0,:],axis=1) ax.plot(t,u,'g') ax.fill_between(t,u-se,u+se,facecolor=(0,1,0,0.5)) u = np.mean(synapse_decode[:,1,:],axis=1) se = np.std(synapse_decode[:,1,:],axis=1) ax.plot(t,u,'m') ax.fill_between(t,u-se,u+se,facecolor=(0.5,0,0.5)) ax.set_title('Synaptic sample decoding') else: ax = f.add_subplot(num_rows, num_cols, start_sp+9) u = np.mean(synapse_decode[:,rule,:],axis=1) se = np.std(synapse_decode[:,rule,:],axis=1) ax.plot(t,u,'k') ax.fill_between(t,u-se,u+se,facecolor=(0,0,0,0.5)) u = np.mean(synapse_decode_test[:,rule,:],axis=1) se = np.std(synapse_decode_test[:,rule,:],axis=1) ax.plot(t,u,'c') ax.fill_between(t,u-se,u+se,facecolor=(0,1,1,0.5)) if DMC: ax.set_title('Synaptic sample \ncategory decoding') else: ax.set_title('Synaptic sample decoding') self.add_subplot_fixings(ax, chance_level=chance_level) ax.set_ylabel('Decoding accuracy') if tight: plt.tight_layout() plt.savefig('DMS summary.pdf', format='pdf') plt.show() def plot_postle_figure(self,dt=20, STP=False, tight=False): # declare that we're analyzing a postle task self.postle = True sample_pev, sample_stp_pev, sample_decoding, sample_stp_decoding, model_output = self.decoding_accuracy_postle(num_reps=10) t = np.arange(0,220*dt,dt) t -= 900 # assuming 400 ms dead time, 500 ms fixation t0,t1,t2,t3,t4,t5,t6 = np.where(t==-500), np.where(t==0), np.where(t==500), np.where(t==1000), np.where(t==1500), np.where(t==2000), np.where(t==2500) f = plt.figure(figsize=(6,6)) for i in range(2): for j in range(2): ax = f.add_subplot(3, 2, 2*i+j+1) u = np.mean(sample_decoding[i,j,0,0,:,:],axis=1) se = np.std(sample_decoding[i,j,0,0,:,:],axis=1) ax.fill_between(t,u-se,u+se,facecolor=(0,1,0,0.5)) ax.plot(t,u,'g') u = np.mean(sample_decoding[i,j,0,1,:,:],axis=1) se = np.std(sample_decoding[i,j,0,1,:,:],axis=1) ax.fill_between(t,u-se,u+se,facecolor=(1,0.6,0,0.5)) ax.plot(t,u,color=[1,0.6,0]) if STP: u = np.mean(sample_stp_decoding[i,j,0,0,:,:],axis=1) se = np.std(sample_stp_decoding[i,j,0,0,:,:],axis=1) ax.fill_between(t,u-se,u+se,facecolor=(1,0,1,0.5)) ax.plot(t,u,'m') u = np.mean(sample_stp_decoding[i,j,0,1,:,:],axis=1) se = np.std(sample_stp_decoding[i,j,0,1,:,:],axis=1) ax.fill_between(t,u-se,u+se,facecolor=(0,1,1,0.5)) ax.plot(t,u,'c') self.add_subplot_fixings(ax, chance_level=1/8, ylim=1.1) ax.set_ylabel('Decoding accuracy') ax = f.add_subplot(3, 2, 5) u = np.mean(sample_decoding[0,0,1,1,:,:],axis=1) se = np.std(sample_decoding[0,0,1,1,:,:],axis=1) #u = np.mean(np.mean(sample_decoding[0,:,1,1,:,:],axis=0),axis=1) #se = np.std(np.mean(sample_decoding[0,:,1,1,:,:],axis=0),axis=1) ax.fill_between(t,u-se,u+se,facecolor=(0,0,0,0.5)) ax.plot(t,u,'k') u = np.mean(sample_decoding[0,0,0,1,:,:],axis=1) se = np.std(sample_decoding[0,0,0,1,:,:],axis=1) #u = np.mean(np.mean(sample_decoding[0,:,0,1,:,:],axis=0),axis=1) #se = np.std(np.mean(sample_decoding[0,:,0,1,:,:],axis=0),axis=1) ax.fill_between(t,u-se,u+se,facecolor=(1,0.6,0,0.5)) ax.plot(t,u,color=[1,0.6,0]) self.add_subplot_fixings(ax, chance_level=1/8, ylim=1.1) ax.plot([2400,2400],[-2, 99],'y--') ax.set_ylabel('Decoding accuracy') ax = f.add_subplot(3, 2, 6) u = np.mean(sample_decoding[1,1,1,0,:,:],axis=1) se = np.std(sample_decoding[1,1,1,0,:,:],axis=1) #u = np.mean(np.mean(sample_decoding[1,:,1,0,:,:],axis=0),axis=1) #se = np.std(np.mean(sample_decoding[1,:,1,0,:,:],axis=0),axis=1) ax.fill_between(t,u-se,u+se,facecolor=(0,0,0,0.5)) ax.plot(t,u,'k') u = np.mean(sample_decoding[1,1,0,0,:,:],axis=1) se = np.std(sample_decoding[1,1,0,0,:,:],axis=1) #u = np.mean(np.mean(sample_decoding[1,:,0,0,:,:],axis=0),axis=1) #se = np.std(np.mean(sample_decoding[1,:,0,0,:,:],axis=0),axis=1) ax.fill_between(t,u-se,u+se,facecolor=(0,1,0,0.5)) ax.plot(t,u,'g') self.add_subplot_fixings(ax, chance_level=1/8, ylim=1.1) ax.plot([2400,2400],[-2, 99],'y--') ax.set_ylabel('Decoding accuracy') plt.tight_layout() plt.savefig('postle summary.pdf', format='pdf') plt.show() return sample_decoding, sample_stp_decoding def plot_ABBA_figures(self,dt=25, STP=False, tight=False): mean_resp, mean_out_match, mean_out_non_match = self.calc_mean_responses() spike_decode, synapse_decode, spike_decode_test, synapse_decode_test = self.calculate_svms(DMC=[False],decode_test=True) #sample_pev, test_pev, rule_pev, _, sample_stp_pev, sample_cat_pev, sample_cat_stp_pev, test_stp_pev = self.calculate_pevs() chance_level = 1/2 trial_length_steps = self.rnn_outputs.shape[1] trial_length = np.int_(trial_length_steps*dt) t = np.arange(0,trial_length,dt) t -= 900 # assuming 400 ms dead time, 500 ms fixation t0,t1,t2,t3 = np.where(t==-500), np.where(t==0),np.where(t==500),np.where(t==1500) f = plt.figure(figsize=(6,4)) ax = f.add_subplot(2, 2, 1) # plot accuracy bars x=np.array([0,1,2,3]) ax.bar(x+0.1, self.ABBA_accuracy_match,width=0.2,color='r',align='center') ax.bar(x-0.1, self.ABBA_accuracy_non_match,width=0.2,color='b',align='center') ax.set_title('Accuracy') ax.set_ylabel('Fraction correct') ax.set_xlabel('Num. of distractors') ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) ax = f.add_subplot(2, 2, 2) ax.hold(True) s = np.mean(mean_resp[:,0,:,:],axis=0) max_val = np.max(s) for i in range(8): ax.plot(t,s[i,:],color=[1-i/7,0,i/7], linewidth=1) self.add_subplot_fixings(ax,chance_level=0,ylim=0.5) ax.set_title('Mean response from synpases informative neurons') ax.set_ylabel('Activity (a.u.)') ax.set_ylim([0, 0.5]) ax = f.add_subplot(2, 2, 3) u = np.mean(spike_decode[:,0,:],axis=1) se = np.std(spike_decode[:,0,:],axis=1) ax.plot(t,u,'b') ax.fill_between(t,u-se,u+se,facecolor=(0,0,1,0.5)) u = np.mean(spike_decode_test[:,0,:],axis=1) se = np.std(spike_decode_test[:,0,:],axis=1) ax.plot(t,u,'r') ax.fill_between(t,u-se,u+se,facecolor=(1,0,0,0.5)) self.add_subplot_fixings(ax, chance_level=1/8, ylim=1.1) ax.set_ylabel('Decoding accuracy') ax = f.add_subplot(2, 2, 4) u = np.mean(spike_decode[:,0,:],axis=1) se = np.std(spike_decode[:,0,:],axis=1) ax.plot(t,u,'b') ax.fill_between(t,u-se,u+se,facecolor=(0,0,1,0.5)) u = np.mean(synapse_decode_test[:,0,:],axis=1) se = np.std(synapse_decode_test[:,0,:],axis=1) ax.plot(t,u,'r') ax.fill_between(t,u-se,u+se,facecolor=(1,0,0,0.5)) self.add_subplot_fixings(ax, chance_level=1/8, ylim=1.1) ax.set_ylabel('Decoding accuracy') if tight: plt.tight_layout() plt.savefig('ABBA summary.pdf', format='pdf') plt.show() def add_subplot_fixings(self, ax, chance_level = 0, ylim = 1.1, delayed_rule=False): ax.plot([0,0],[-2, 99],'k--') if self.ABBA: ax.plot([500,500],[-2, 99],'k--') ax.plot([1000,1000],[-2, 99],'k--') ax.plot([1500,1500],[-2, 99],'k--') ax.plot([2000,2000],[-2, 99],'k--') ax.set_xlim([-500,2500]) ax.set_xticks([-500,0,500,1000,1500,2000,2500]) elif self.postle: ax.plot([500,500],[-2, 99],'k--') ax.plot([1000,1000],[-2, 99],'k--') ax.plot([1500,1500],[-2, 99],'k--') ax.plot([2000,2000],[-2, 99],'k--') ax.plot([2500,2500],[-2, 99],'k--') ax.plot([3000,3000],[-2, 99],'k--') ax.set_xlim([-500,3500]) ax.set_xticks([-500,0,500,1000,1500,2000,2500,3000]) else: ax.plot([500,500],[-2, 99],'k--') ax.plot([1500,1500],[-2, 99],'k--') ax.set_xlim([-500,2000]) ax.set_xticks([-500,0,500,1500]) if delayed_rule: ax.set_xticks([-500,0,500,1000,1500]) ax.plot([1000,1000],[-2, 99],'k--') ax.plot([-700,3600],[chance_level, chance_level],'k--') ax.set_ylim([-0.1, ylim]) ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') #ax.set_title('Tuning similarity between proximal and distal neurons') ax.set_ylabel('Response') ax.set_xlabel('Time relative to sample onset (ms)') def compare_two_tasks(fn1, fn2, DMC=False, ABBA_flag=False,rule = 0, dt=25): # enter the two filenames, fn1 and fn2 font = {'family' : 'normal', 'weight' : 'bold', 'size' : 12} na1 = neural_analysis(fn1, ABBA = ABBA_flag) na2 = neural_analysis(fn2, ABBA = ABBA_flag) mean_resp1, _, _ = na1.calc_mean_responses() svm_results1 = na1.calculate_svms(ABBA = ABBA_flag) sample_pev1, _, rule_pev1, _, sample_stp_pev1, _ , sample_cat_pev1, sample_cat_stp_pev1 = na1.calculate_pevs(ABBA = ABBA_flag) mean_resp2, _, _ = na2.calc_mean_responses() svm_results2 = na2.calculate_svms() sample_pev2, _, rule_pev2, _, sample_stp_pev2, _ ,sample_cat_pev2, sample_cat_stp_pev2 = na2.calculate_pevs() if DMC: sample_pev1 = sample_cat_pev1 sample_pev2 = sample_cat_pev2 sample_stp_pev1 = sample_cat_stp_pev1 sample_stp_pev2 = sample_cat_stp_pev2 svm_results1['sample_full'] = svm_results1['sample_full_cat'] svm_results2['sample_full'] = svm_results2['sample_full_cat'] svm_results1['sample_full_stp'] = svm_results1['sample_full_cat_stp'] svm_results2['sample_full_stp'] = svm_results2['sample_full_cat_stp'] if na1.num_rules>1 and False: # not sure if I want this. If there are more than one task rules, this part will average # across all rules sample_pev1[:,0,:] = np.mean(sample_cat_pev1,axis=1) sample_pev2[:,0,:] = np.mean(sample_cat_pev2,axis=1) sample_stp_pev1[:,0,:] = np.mean(sample_cat_stp_pev1,axis=1) sample_stp_pev2[:,0,:] = np.mean(sample_cat_stp_pev2,axis=1) svm_results1['sample_full'][:,0,:] = np.mean(svm_results1['sample_full'],axis=1) svm_results2['sample_full'][:,0,:] = np.mean(svm_results2['sample_full'],axis=1) svm_results1['sample_full_stp'][:,0,:] = np.mean(svm_results1['sample_full_stp'],axis=1) svm_results2['sample_full_stp'][:,0,:] = np.mean(svm_results2['sample_full_stp'],axis=1) rule = 0 f = plt.figure(figsize=(8,4)) t = np.arange(0,2700,dt) t -= 900 t0,t1,t2,t3 = np.where(t==-500), np.where(t==0),np.where(t==500),np.where(t==1500) if ABBA_flag: t = np.arange(0,200+500+1500+300+300,dt) t = np.arange(0,200+500+250+2000,dt) t -= 700 t0,t1,t2,t3,t4,t5,t6 = np.where(t==-500), np.where(t==0),np.where(t==500),np.where(t==1000),np.where(t==1500),np.where(t==2000), np.where(t==2500) ax = f.add_subplot(2, 3, 1) ax.hold(True) u1 = np.mean(np.mean(mean_resp1[:,rule,:,:],axis=1),axis=0) u2 = np.mean(np.mean(mean_resp2[:,rule,:,:],axis=1),axis=0) se1 = np.std(np.mean(mean_resp1[:,rule,:,:],axis=1),axis=0)/np.sqrt(mean_resp1.shape[0]) se2 = np.std(np.mean(mean_resp2[:,rule,:,:],axis=1),axis=0)/np.sqrt(mean_resp1.shape[0]) ax.fill_between(t,u1-se1,u1+se1,facecolor=(0,1,0)) ax.fill_between(t,u2-se2,u2+se2,facecolor=(1,0,1)) ax.plot(t,u1,'g',label='without STP',color=(0,0.5,0),linewidth=2) ax.plot(t,u2,'m',label='with STP',color=(0.5,0,0.5),linewidth=2) na1.add_subplot_fixings(ax, chance_level=0, ylim=6, ABBA_task=ABBA_flag) green_patch = mpatches.Patch(color='green', label='without STP') magenta_patch = mpatches.Patch(color='magenta', label='with STP') plt.legend(loc=0, handles=[green_patch,magenta_patch],prop={'size':6}) ax.set_title('Mean population response') ax.set_ylabel('Mean response') ax = f.add_subplot(2, 3, 2) ax.hold(True) u1 = np.mean(sample_pev1[:,rule,:],axis=0) u2 = np.mean(sample_pev2[:,rule,:],axis=0) u3 = np.mean(rule_pev2,axis=0) se1 = np.std(sample_pev1[:,rule,:],axis=0)/np.sqrt(sample_pev1.shape[0]) se2 = np.std(sample_pev2[:,rule,:],axis=0)/np.sqrt(sample_pev1.shape[0]) ax.fill_between(t,u1-se1,u1+se1,facecolor=(0,1,0)) ax.fill_between(t,u2-se2,u2+se2,facecolor=(1,0,1)) ax.plot(t,u1,'g',label='without STP',color=(0,0.5,0),linewidth=2) ax.plot(t,u2,'m',label='with STP',color=(0.5,0,0.5),linewidth=2) ax.plot(t,u3,label='rule with STP',color=(0,0,0),linewidth=2) na1.add_subplot_fixings(ax, chance_level=0, ylim=0.35,ABBA_task=ABBA_flag) #green_patch = mpatches.Patch(color='green', label='without STP') #magenta_patch = mpatches.Patch(color='magenta', label='with STP') #plt.legend(loc=0, handles=[green_patch,magenta_patch]) ax.set_title('Neuron sample selectivity') ax.set_ylabel('Normalized PEV') ax = f.add_subplot(2, 3, 3) ax.hold(True) u1 = np.mean(svm_results1['sample_full'][:,rule,:],axis=1) u2 = np.mean(svm_results2['sample_full'][:,rule,:],axis=1) se1 = np.std(svm_results1['sample_full'][:,rule,:],axis=1) se2 = np.std(svm_results2['sample_full'][:,rule,:],axis=1) se1[np.isnan(se1)] = 0 se2[np.isnan(se2)] = 0 ax.fill_between(t,u1-se1,u1+se1,facecolor=(0,1,0)) ax.fill_between(t,u2-se2,u2+se2,facecolor=(1,0,1)) ax.plot(t,u1,'g',label='without STP',color=(0,0.5,0),linewidth=2) ax.plot(t,u2,'m',label='with STP',color=(0.5,0,0.5),linewidth=2) na1.add_subplot_fixings(ax, chance_level=1/8, ylim=1.1,ABBA_task=ABBA_flag) #green_patch = mpatches.Patch(color='green', label='without STP') #magenta_patch = mpatches.Patch(color='magenta', label='with STP') #plt.legend(loc=0, handles=[green_patch,magenta_patch]) ax.set_title('Neuron sample decoding accuracy') ax.set_ylabel('Decoding accuracy') ax = f.add_subplot(2, 3, 4) im = ax.imshow(sample_stp_pev2[:,rule,:],aspect='auto',interpolation=None) if not ABBA_flag: ax.set_xticks([t0[0], t1[0], t2[0], t3[0]]) ax.set_xticklabels([-500,0,500,1500]) else: ax.set_xticks([t0[0], t1[0], t2[0], t3[0], t4[0], t5[0], t6[0]]) ax.set_xticklabels([-500,0,500,1000,1500,2000,2000,2500]) f.colorbar(im,orientation='vertical') ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) ax.set_ylabel('Neuron number') ax.set_xlabel('Time relative to sample onset (ms)') ax.set_title('Synaptic sample selectivity') ax = f.add_subplot(2, 3, 5) ax.hold(True) u2 = np.mean(sample_stp_pev2[:,rule,:],axis=0) se2 = np.std(sample_stp_pev2[:,rule,:],axis=0)/np.sqrt(sample_pev1.shape[0]) ax.fill_between(t,u2-se2,u2+se2,facecolor=(1,0,1)) ax.plot(t,u2,'m',label='with STP',color=(0.5,0,0.5),linewidth=2) na1.add_subplot_fixings(ax, chance_level=0, ylim=0.3,ABBA_task=ABBA_flag) #green_patch = mpatches.Patch(color='green', label='without STP') #magenta_patch = mpatches.Patch(color='magenta', label='with STP') #plt.legend(loc=0, handles=[green_patch,magenta_patch]) ax.set_title('Synaptic sample selectivity') ax.set_ylabel('Normalized PEV') ax = f.add_subplot(2, 3, 6) ax.hold(True) u2 = np.mean(svm_results2['sample_full_stp'][:,rule,:],axis=1) se2 = np.std(svm_results2['sample_full_stp'][:,rule,:],axis=1) se2[np.isnan(se2)] = 0 ax.fill_between(t,u2-se2,u2+se2,facecolor=(1,0,1)) ax.plot(t,u2,'m',label='with STP',color=(0.5,0,0.5),linewidth=2) na1.add_subplot_fixings(ax, chance_level=1/8, ylim=1.1,ABBA_task=ABBA_flag) #green_patch = mpatches.Patch(color='green', label='without STP') #magenta_patch = mpatches.Patch(color='magenta', label='with STP') #plt.legend(loc=0, handles=[green_patch,magenta_patch]) ax.set_title('Synaptic sample decoding accuray') ax.set_ylabel('Decoding accuracy') plt.tight_layout() plt.savefig('DMS comparison.pdf', format='pdf') plt.show() def compare_two_tasks_two_rules(fn1, fn2, DMC=False, ABBA=False, dt=25): # enter the two filenames, fn1 and fn2 font = {'family' : 'normal', 'weight' : 'bold', 'size' : 12} na1 = neural_analysis(fn1) na2 = neural_analysis(fn2) mean_resp1, _, _ = na1.calc_mean_responses() svm_results1 = na1.calculate_svms() sample_pev1, _, rule_pev1, _, sample_stp_pev1, _ , sample_cat_pev1, sample_cat_stp_pev1 = na1.calculate_pevs() mean_resp2, _, _ = na2.calc_mean_responses() svm_results2 = na2.calculate_svms() sample_pev2, _, rule_pev2, _, sample_stp_pev2, _ ,sample_cat_pev2, sample_cat_stp_pev2 = na2.calculate_pevs() if DMC: sample_pev1 = sample_cat_pev1 sample_pev2 = sample_cat_pev2 sample_stp_pev1 = sample_cat_stp_pev1 sample_stp_pev2 = sample_cat_stp_pev2 svm_results1['sample_full'] = svm_results1['sample_full_cat'] svm_results2['sample_full'] = svm_results2['sample_full_cat'] svm_results1['sample_full_stp'] = svm_results1['sample_full_cat_stp'] svm_results2['sample_full_stp'] = svm_results2['sample_full_cat_stp'] f = plt.figure(figsize=(8,9)) t = np.arange(0,2700,dt) t -= 900 t0,t1,t2,t3 = np.where(t==-500), np.where(t==0),np.where(t==500),np.where(t==1500) if ABBA: t = np.arange(0,200+500+1500+300+300,dt) t -= 700 t0,t1,t2,t3,t4,t5,t6,t7 = np.where(t==-500), np.where(t==0),np.where(t==300),np.where(t==600),np.where(t==900),np.where(t==1200), np.where(t==1500), np.where(t==1800) ax = f.add_subplot(5, 2, 1) ax.hold(True) u1 = np.mean(np.mean(np.mean(mean_resp1[:,:,:,:],axis=1),axis=1),axis=0) u2 = np.mean(np.mean(np.mean(mean_resp2[:,:,:,:],axis=1),axis=1),axis=0) se1 = np.std(np.mean(np.mean(mean_resp1[:,:,:,:],axis=1),axis=1),axis=0)/np.sqrt(mean_resp1.shape[0]) se2 = np.std(np.mean(np.mean(mean_resp2[:,:,:,:],axis=1),axis=1),axis=0)/np.sqrt(mean_resp1.shape[0]) ax.fill_between(t,u1-se1,u1+se1,facecolor=(0,1,0)) ax.fill_between(t,u2-se2,u2+se2,facecolor=(1,0,1)) ax.plot(t,u1,'g',label='without STP',color=(0,0.5,0),linewidth=2) ax.plot(t,u2,'m',label='with STP',color=(0.5,0,0.5),linewidth=2) na1.add_subplot_fixings(ax, chance_level=0, ylim=4, ABBA_task=ABBA,delayed_rule=True) green_patch = mpatches.Patch(color='green', label='without STP') magenta_patch = mpatches.Patch(color='magenta', label='with STP') plt.legend(loc=0, handles=[green_patch,magenta_patch],prop={'size':6}) ax.set_title('Mean population response') ax.set_ylabel('Mean response') ax = f.add_subplot(5, 2, 2) ax.hold(True) u1 = np.mean(rule_pev1,axis=0) u2 = np.mean(rule_pev2,axis=0) se1 = np.std(rule_pev1,axis=0)/np.sqrt(sample_pev1.shape[0]) se2 = np.std(rule_pev2,axis=0)/np.sqrt(sample_pev1.shape[0]) ax.fill_between(t,u1-se1,u1+se1,facecolor=(0,1,0)) ax.fill_between(t,u2-se2,u2+se2,facecolor=(1,0,1)) ax.plot(t,u1,'g',label='without STP',color=(0,0.5,0),linewidth=2) ax.plot(t,u2,'m',label='with STP',color=(0.5,0,0.5),linewidth=2) na1.add_subplot_fixings(ax, chance_level=0, ylim=0.3,ABBA_task=ABBA,delayed_rule=True) ax.set_title('Neuron rule selectivity') ax.set_ylabel('Normalized PEV') for rule in range(2): ax = f.add_subplot(5, 2, 3+2*rule) ax.hold(True) u1 = np.mean(sample_pev1[:,rule,:],axis=0) u2 = np.mean(sample_pev2[:,rule,:],axis=0) se1 = np.std(sample_pev1[:,rule,:],axis=0)/np.sqrt(sample_pev1.shape[0]) se2 = np.std(sample_pev2[:,rule,:],axis=0)/np.sqrt(sample_pev1.shape[0]) ax.fill_between(t,u1-se1,u1+se1,facecolor=(0,1,0)) ax.fill_between(t,u2-se2,u2+se2,facecolor=(1,0,1)) ax.plot(t,u1,'g',label='without STP',color=(0,0.5,0),linewidth=2) ax.plot(t,u2,'m',label='with STP',color=(0.5,0,0.5),linewidth=2) na1.add_subplot_fixings(ax, chance_level=0, ylim=0.7,ABBA_task=ABBA,delayed_rule=True) ax.set_title('Neuron sample selectivity') ax.set_ylabel('Normalized PEV') ax = f.add_subplot(5, 2, 4+2*rule) ax.hold(True) u1 = np.mean(svm_results1['sample_full'][:,rule,:],axis=1) u2 = np.mean(svm_results2['sample_full'][:,rule,:],axis=1) se1 = np.std(svm_results1['sample_full'][:,rule,:],axis=1) se2 = np.std(svm_results2['sample_full'][:,rule,:],axis=1) se1[np.isnan(se1)] = 0 se2[np.isnan(se2)] = 0 ax.fill_between(t,u1-se1,u1+se1,facecolor=(0,1,0)) ax.fill_between(t,u2-se2,u2+se2,facecolor=(1,0,1)) ax.plot(t,u1,'g',label='without STP',color=(0,0.5,0),linewidth=2) ax.plot(t,u2,'m',label='with STP',color=(0.5,0,0.5),linewidth=2) na1.add_subplot_fixings(ax, chance_level=1/8, ylim=1.1,ABBA_task=ABBA,delayed_rule=True) ax.set_title('Neuron sample decoding accuracy') ax.set_ylabel('Decoding accuracy') ax = f.add_subplot(5, 2, 7+2*rule) ax.hold(True) u1 = np.mean(sample_stp_pev1[:,rule,:],axis=0) u2 = np.mean(sample_stp_pev2[:,rule,:],axis=0) se1 = np.std(sample_stp_pev1[:,rule,:],axis=0)/np.sqrt(sample_pev1.shape[0]) se2 = np.std(sample_stp_pev2[:,rule,:],axis=0)/np.sqrt(sample_pev1.shape[0]) ax.fill_between(t,u1-se1,u1+se1,facecolor=(0,1,0)) ax.fill_between(t,u2-se2,u2+se2,facecolor=(1,0,1)) ax.plot(t,u1,'g',label='without STP',color=(0,0.5,0),linewidth=2) ax.plot(t,u2,'m',label='with STP',color=(0.5,0,0.5),linewidth=2) na1.add_subplot_fixings(ax, chance_level=0, ylim=0.7,ABBA_task=ABBA,delayed_rule=True) ax.set_title('Synaptic sample selectivity') ax.set_ylabel('Normalized PEV') ax = f.add_subplot(5, 2, 8+2*rule) ax.hold(True) u1 = np.mean(svm_results1['sample_full_stp'][:,rule,:],axis=1) u2 = np.mean(svm_results2['sample_full_stp'][:,rule,:],axis=1) se1 = np.std(svm_results1['sample_full_stp'][:,rule,:],axis=1) se2 = np.std(svm_results2['sample_full_stp'][:,rule,:],axis=1) se1[np.isnan(se1)] = 0 se2[np.isnan(se2)] = 0 ax.fill_between(t,u1-se1,u1+se1,facecolor=(0,1,0)) ax.fill_between(t,u2-se2,u2+se2,facecolor=(1,0,1)) ax.plot(t,u1,'g',label='without STP',color=(0,0.5,0),linewidth=2) ax.plot(t,u2,'m',label='with STP',color=(0.5,0,0.5),linewidth=2) na1.add_subplot_fixings(ax, chance_level=1/8, ylim=1.1,ABBA_task=ABBA,delayed_rule=True) ax.set_title('Synaptic sample decoding accuracy') ax.set_ylabel('Decoding accuracy') plt.tight_layout() plt.savefig('Two rules comparison.pdf', format='pdf') plt.show() def plt_dual_figures(fn1, fn2, ABBA=False, DMC=False, two_rules=False): # assume fn1 has no STP, and fn2 does if two_rules: fig_handle = plt.figure(figsize=(10,10)) sp = 8 else: fig_handle = plt.figure(figsize=(8,10)) sp = 6 na = neural_analysis(fn1, ABBA=ABBA) na.plot_all_figures(rule=0, STP=False, ABBA=ABBA, DMC=DMC, two_rules=two_rules,f=fig_handle, start_sp=0, num_rows=5, tight=False) na = neural_analysis(fn2, ABBA=ABBA) na.plot_all_figures(rule=0, STP=True, ABBA=ABBA, DMC=DMC, two_rules=two_rules,f=fig_handle, start_sp=sp, num_rows=5, tight=True) def plot_summary_decoding_figure(): fn1 = 'C:/Users/nicol_000/Projects/RNN STP Model/saved_model_files/DMS.pkl' fn2 = 'C:/Users/nicol_000/Projects/RNN STP Model/saved_model_files/DMS_std_stf.pkl' fn3 = 'C:/Users/nicol_000/Projects/RNN STP Model/saved_model_files/DMC.pkl' fn4 = 'C:/Users/nicol_000/Projects/RNN STP Model/saved_model_files/DMC_std_stf.pkl' fn5 = 'C:/Users/nicol_000/Projects/RNN STP Model/saved_model_files/DMS_rotation.pkl' fn6 = 'C:/Users/nicol_000/Projects/RNN STP Model/saved_model_files/DMS_rotate_std_stf_v3.pkl' fn7 = 'C:/Users/nicol_000/Projects/RNN STP Model/saved_model_files/DMS_and_rotate_v3.pkl' fn8 = 'C:/Users/nicol_000/Projects/RNN STP Model/saved_model_files/DMS_and_rotate_std_stf_v3.pkl' fn9 = 'C:/Users/nicol_000/Projects/RNN STP Model/saved_model_files/ABBA.pkl' fn10 = 'C:/Users/nicol_000/Projects/RNN STP Model/saved_model_files/ABBA_std_stf_v2.pkl' fig_handle = plt.figure(figsize=(6,10)) num_rows = 5 plot_decoding_pairs(fn1, fn2, fig_handle, num_rows=num_rows, start_sp=0, DMC=False, ABBA=False, two_rules=False) plot_decoding_pairs(fn3, fn4, fig_handle, num_rows=num_rows, start_sp=2, DMC=True, ABBA=False, two_rules=False) plot_decoding_pairs(fn5, fn6, fig_handle, num_rows=num_rows, start_sp=4, DMC=False, ABBA=False, two_rules=False) plot_decoding_pairs(fn7, fn8, fig_handle, num_rows=num_rows, start_sp=6, DMC=False, ABBA=False, two_rules=True) plot_decoding_pairs(fn9, fn10, fig_handle, num_rows=num_rows, start_sp=8, DMC=False, ABBA=True, two_rules=False) plt.tight_layout() plt.savefig('Summary.pdf', format='pdf') plt.show() def plot_decoding_pairs(fn1, fn2, f, num_rows, start_sp, DMC=False, ABBA=False, two_rules=False): dt = 25 na = neural_analysis(fn1, ABBA=False) svm_results1 = na.calculate_svms() na = neural_analysis(fn2, ABBA=False) svm_results2 = na.calculate_svms() trial_length_steps = svm_results1['sample_full'].shape[0] trial_length = np.int_(trial_length_steps*dt) t = np.arange(0,trial_length,dt) t -= 900 # assuming 400 ms dead time, 500 ms fixation if DMC: svm_results1['sample_full'] = svm_results1['sample_full_cat'] svm_results2['sample_full'] = svm_results2['sample_full_cat'] svm_results1['sample_full_stp'] = svm_results1['sample_full_cat_stp'] svm_results2['sample_full_stp'] = svm_results2['sample_full_cat_stp'] if two_rules: svm_results1['sample_full'] = np.mean(svm_results1['sample_full'],axis=1) svm_results2['sample_full'] = np.mean(svm_results2['sample_full'],axis=1) svm_results1['sample_full_stp'] = np.mean(svm_results1['sample_full_stp'],axis=1) svm_results2['sample_full_stp'] = np.mean(svm_results2['sample_full_stp'],axis=1) else: svm_results1['sample_full'] = np.squeeze(svm_results1['sample_full'][:,0,:]) svm_results2['sample_full'] = np.squeeze(svm_results2['sample_full'][:,0,:]) svm_results1['sample_full_stp'] = np.squeeze(svm_results1['sample_full_stp'][:,0,:]) svm_results2['sample_full_stp'] = np.squeeze(svm_results2['sample_full_stp'][:,0,:]) print(svm_results1['sample_full'].shape) ax = f.add_subplot(num_rows, 2, start_sp+1) u = np.mean(svm_results1['sample_full'],axis=1) se = np.std(svm_results1['sample_full'],axis=1) print(u.shape, se.shape, t.shape) ax.plot(t,u,'g') ax.fill_between(t,u-se,u+se,facecolor=(0,0.5,0)) u = np.mean(svm_results2['sample_full'],axis=1) se = np.std(svm_results2['sample_full'],axis=1) ax.plot(t,u,'m') ax.fill_between(t,u-se,u+se,facecolor=(0.5,0,0.5)) if DMC: ax.set_title('Neuronal sample \category decoding') cl = 1/2 else: ax.set_title('Neuronal sample decoding') cl = 1/8 na.add_subplot_fixings(ax, chance_level=cl) ax.set_ylabel('Decoding accuracy') ax = f.add_subplot(num_rows, 2, start_sp+2) u = np.mean(svm_results2['sample_full_stp'],axis=1) se = np.std(svm_results2['sample_full_stp'],axis=1) ax.plot(t,u,'m') ax.fill_between(t,u-se,u+se,facecolor=(0.5,0,0.5)) if DMC: ax.set_title('Synaptic sample \category decoding') cl = 1/2 else: ax.set_title('Synaptic sample decoding') cl = 1/8 na.add_subplot_fixings(ax, chance_level=cl) def plot_summary_results(old_format = False): dt = 20 t = np.arange(0,2900,dt) t -= 900 t0,t1,t2,t3 = np.where(t==-500), np.where(t==0),np.where(t==500),np.where(t==1500) num_svm_reps = 2 trial_length = (400+500+500+1000+500)//dt N = 11 data_dir = 'D:/Masse/RNN STP/saved_models/' fn = ['DMS_', 'DMS_stp_', 'DMC_stp_', 'DMrS_stp_'] titles = ['DMS no STP', 'DMS', 'DMC', 'DMrS'] spike_decoding = np.zeros((4, N, trial_length, num_svm_reps)) synapse_decoding = np.zeros((4, N, trial_length, num_svm_reps)) spike_decoding_test = np.zeros((4, N, trial_length, num_svm_reps)) synapse_decoding_test = np.zeros((4, N, trial_length, num_svm_reps)) perf = np.zeros((4, N)) perf_shuffled_hidden = np.zeros((4, N)) perf_shuffled_stp = np.zeros((4, N)) """ Calculate the spiking and synaptic sample decoding accuracy across all networks Calculate the behavioral performance """ for i in range(N): print('Group ', i) for j in range(1,4): if j == 2: DMC = [True] else: DMC = [False] f = data_dir + fn[j] + str(i) + '.pkl' na = neural_analysis(f, ABBA=False, old_format = old_format) perf[j,i] = get_perf(na.desired_outputs, na.model_outputs, na.train_mask, na.rule) spike_decode, synapse_decode, spike_decode_test, synapse_decode_test = na.calculate_svms(num_reps = num_svm_reps, DMC = DMC) spike_decoding[j,i,:,:] = spike_decode[:,0,:] synapse_decoding[j,i,:,:] = synapse_decode[:,0,:] spike_decoding_test[j,i,:,:] = spike_decode_test[:,0,:] synapse_decoding_test[j,i,:,:] = synapse_decode_test[:,0,:] a = contrib_to_behavior.Analysis(f,old_format = old_format) perf[j,i], perf_shuffled_hidden[j,i], perf_shuffled_stp[j,i] = a.simulate_network() """ Calculate the mean decoding accuracy for the last 500 ms of the delay """ d = range(1900//dt,2400//dt) delay_accuracy = np.mean(np.mean(spike_decoding[:,:,d,:],axis=3),axis=2) ind_example = [0] for j in range(1,4): ind_good_perf = np.where(perf[j,:] > 0.9)[0] ind_sort = np.argsort(delay_accuracy[j,ind_good_perf])[0] ind_example.append(ind_good_perf[ind_sort]) """ Plot decoding accuracy from example models Only consider models with performance accuracy above 99.0% Will use the model with the lowest spike decoding value during the last 500 ms of the delay """ print(ind_example) f = plt.figure(figsize=(6,4)) for j in range(1,4): if j == 2: chance_level = 1/2 else: chance_level = 1/8 ax = f.add_subplot(2, 2, j+1) u = np.mean(spike_decoding[j,ind_example[j],:,:],axis=1) se = np.std(spike_decoding[j,ind_example[j],:,:],axis=1) ax.plot(t,u,'g') ax.fill_between(t,u-se,u+se,facecolor=(0,1,0,0.5)) u = np.mean(synapse_decoding[j,ind_example[j],:,:],axis=1) se = np.std(synapse_decoding[j,ind_example[j],:,:],axis=1) ax.plot(t,u,'m') ax.fill_between(t,u-se,u+se,facecolor=(1,0,1,0.5)) na.add_subplot_fixings(ax, chance_level=chance_level) ax.set_title(titles[j]) ax.set_ylabel('Decoding accuracy') ax.set_ylim([0, 1]) plt.tight_layout() plt.savefig('Example models.pdf', format='pdf') plt.show() """ Plot mean decoding accuracy across all models Only use models with performance accuracy above 85% """ print(ind_example) f = plt.figure(figsize=(6,4)) for j in range(1,4): if j == 2: chance_level = 1/2 else: chance_level = 1/8 ind_good_models = np.where(perf[j,:] > 0.85)[0] ax = f.add_subplot(2, 2, j+1) u = np.mean(np.mean(spike_decoding[j,ind_good_models,:,:],axis=2),axis=0) se = np.std(np.mean(spike_decoding[j,ind_good_models,:,:],axis=2),axis=0)/np.sqrt(len(ind_good_models)) ax.plot(t,u,'g') ax.fill_between(t,u-se,u+se,facecolor=(0,1,0,0.5)) u = np.mean(np.mean(synapse_decoding[j,ind_good_models,:,:],axis=2),axis=0) se = np.std(np.mean(synapse_decoding[j,ind_good_models,:,:],axis=2),axis=0)/np.sqrt(len(ind_good_models)) ax.plot(t,u,'m') ax.fill_between(t,u-se,u+se,facecolor=(1,0,1,0.5)) na.add_subplot_fixings(ax, chance_level=chance_level) ax.set_title(titles[j]) ax.set_ylabel('Decoding accuracy') ax.set_ylim([0, 1]) plt.tight_layout() plt.savefig('Average models.pdf', format='pdf') plt.show() """ Plot decoding accuracy across all models using heatmaps Only use models with performance accuracy above 97.5% """ print(ind_example) f = plt.figure(figsize=(6,4)) for j in range(1,4): if j == 2: chance_level = 1/2 else: chance_level = 1/8 ind_good_models = np.where(perf[j,:] > 0.975)[0] ax = f.add_subplot(2, 2, j+1) u = np.mean(synapse_decoding[j,ind_good_models,:,:],axis=2) im = ax.imshow(u,aspect='auto',interpolation=None) f.colorbar(im,orientation='vertical') ax.spines['right'].set_visible(False) ax.set_ylabel('Model number') ax.set_xlabel('Time relative to sample onset (ms)') ax.spines['top'].set_visible(False) ax.set_title(titles[j]) ax.set_xticks([t0[0], t1[0], t2[0], t3[0]]) ax.set_xticklabels([-500,0,500,1500]) plt.tight_layout() plt.savefig('All models.pdf', format='pdf') plt.show() print(ind_example) return spike_decoding, synapse_decoding, spike_decoding_test, synapse_decoding_test, perf, perf_shuffled_hidden, perf_shuffled_stp def plot_variable_delay_results(): """ Plot a model that was trained on a variable delay """ data_dir = 'C:/Users/Freedmanlab/Documents/Masse/STP/saved_models/' dt = 25 num_svm_reps = 5 t = np.arange(0,2900,dt) t -= 900 fn = 'DMS_EI_std_stf_var_delay_1_iter1000.pkl' f = data_dir + fn na = neural_analysis(f, ABBA=False) perf = get_perf(na.desired_outputs, na.model_outputs, na.train_mask) print('Model accuracy = ', perf) spike_decode, synapse_decode = na.calculate_svms(num_reps = num_svm_reps, DMC = False) f = plt.figure(figsize=(3,2)) chance_level = 1/8 ax = f.add_subplot(1, 1, 1) u = np.mean(spike_decode[:,0,:],axis=1) se = np.std(spike_decode[:,0,:],axis=1) ax.plot(t,u,'g') ax.fill_between(t,u-se,u+se,facecolor=(0,1,0,0.5)) u = np.mean(synapse_decode[:,0,:],axis=1) se = np.std(synapse_decode[:,0,:],axis=1) ax.plot(t,u,'m') ax.fill_between(t,u-se,u+se,facecolor=(1,0,1,0.5)) na.add_subplot_fixings(ax, chance_level=chance_level) ax.set_ylabel('Decoding accuracy') ax.set_ylim([0, 1]) plt.tight_layout() plt.savefig('Var delay model.pdf', format='pdf') plt.show() def plot_multiple_delay_results(): dt = 20 num_svm_reps = 5 N = 8 data_dir = 'D:/Masse/RNN STP/saved_models/' delay = [1000,1500,2000] num_delays = len(delay) mean_decoding = np.zeros((num_delays, N)) std_decoding = np.zeros((num_delays, N)) perf = np.zeros((num_delays, N)) for i in range(N): print('Group ', i) for j in range(num_delays): if j==0: f = data_dir + 'DMS_stp_' + str(i) + '.pkl' else: f = data_dir + 'DMS_stp_delay_' + str(delay[j]) + '_' + str(i) + '.pkl' try: na = neural_analysis(f, ABBA=False, old_format = False) spike_decode, synapse_decode,_,_ = na.calculate_svms(num_reps = num_svm_reps, DMC = [False]) perf[j,i] = get_perf(na.desired_outputs, na.model_outputs, na.train_mask, na.rule) except: na = neural_analysis(f, ABBA=False, old_format = True) spike_decode, synapse_decode,_,_ = na.calculate_svms(num_reps = num_svm_reps, DMC = [False]) perf[j,i] = get_perf(na.desired_outputs, na.model_outputs, na.train_mask, na.rule) # look at last 100 ms of delay epoch # variable delay delay_end = (400+500+500+delay[j])//dt delay_start = (400+500+500+delay[j]-100)//dt # variable tau #delay_end = (400+500+500+1000)//dt #delay_start = (400+500+500+900)//dt mean_decoding[j,i] = np.mean(spike_decode[delay_start:delay_end,0,:]) std_decoding[j,i] = np.std(np.mean(spike_decode[delay_start:delay_end,0,:],axis=0)) print(i,j,perf[j,i],mean_decoding[j,i],std_decoding[j,i]) f = plt.figure(figsize=(3,2)) chance_level = 1/8 ax = f.add_subplot(1, 1, 1) for i, d in enumerate(delay): # only use models with over 90% accuracy ind_good_model = np.where(perf[i,:]>0.90)[0] ax.plot([d]*len(ind_good_model),mean_decoding[i,ind_good_model],'k.') ax.plot([0,3000],[chance_level,chance_level],'k--') ax.set_ylim([0, 1]) ax.set_xlim([400, 2100]) ax.set_xticks(delay) ax.set_xticklabels(delay) return mean_decoding, std_decoding, perf def plot_summary_results_v2(old_format = False): dt = 20 t = np.arange(0,2900,dt) t -= 900 t0,t1,t2,t3 = np.where(t==-500), np.where(t==0),np.where(t==500),np.where(t==1500) num_svm_reps = 2 trial_length = (400+500+500+1000+500)//dt N = 20 data_dir = 'D:/Masse/RNN STP/saved_models/' fn = ['DMS_stp_', 'DMC_stp_', 'DMrS_stp_', 'DMS_DMrS_stp_'] titles = ['DMS', 'DMC', 'DMrS', 'DMS_DMrS'] num_tasks = len(fn) """ the DMS_DMrS will produce two decoding/accuracy scores, one for each task thus, will show num_tasks+1 set of values """ spike_decoding = np.zeros((num_tasks+1, N, trial_length, num_svm_reps)) synapse_decoding = np.zeros((num_tasks+1, N, trial_length, num_svm_reps)) spike_decoding_test = np.zeros((num_tasks+1, N, trial_length, num_svm_reps)) synapse_decoding_test = np.zeros((num_tasks+1, N, trial_length, num_svm_reps)) perf = np.zeros((num_tasks+1, N)) perf_shuffled_hidden = np.zeros((num_tasks+1, N)) perf_shuffled_stp = np.zeros((num_tasks+1, N)) """ Calculate the spiking and synaptic sample decoding accuracy across all networks Calculate the behavioral performance """ for i in range(N): print('Group ', i) for j in range(num_tasks): if fn[j] == 'DMC_stp_': DMC = [True] elif fn[j] == 'DMS_DMrS_stp_': DMC = [False, False] else: DMC = [False] f = data_dir + fn[j] + str(i) + '.pkl' try: na = neural_analysis(f, ABBA=False, old_format = old_format) except: na = neural_analysis(f, ABBA=False, old_format = not old_format) #perf_temp = get_perf(na.desired_outputs, na.model_outputs, na.train_mask, na.rule) spike_decode, synapse_decode, spike_decode_test, synapse_decode_test = na.calculate_svms(num_reps = num_svm_reps, DMC = DMC) try: a = contrib_to_behavior.Analysis(f,old_format = old_format) perf_temp, perf_shuffled_hidden_temp, perf_shuffled_stp_temp = a.simulate_network() except: a = contrib_to_behavior.Analysis(f,old_format = not old_format) perf_temp, perf_shuffled_hidden_temp, perf_shuffled_stp_temp = a.simulate_network() if j<3: print(perf_temp) perf[j,i] = perf_temp perf_shuffled_hidden[j,i] = perf_shuffled_hidden_temp perf_shuffled_stp[j,i] = perf_shuffled_stp_temp spike_decoding[j,i,:,:] = spike_decode[:,0,:] synapse_decoding[j,i,:,:] = synapse_decode[:,0,:] spike_decoding_test[j,i,:,:] = spike_decode_test[:,0,:] synapse_decoding_test[j,i,:,:] = synapse_decode_test[:,0,:] else: perf[j:,i] = perf_temp perf_shuffled_hidden[j:,i] = perf_shuffled_hidden_temp perf_shuffled_stp[j:,i] = perf_shuffled_stp_temp spike_decoding[j:,i,:,:] = np.transpose(spike_decode[:,:,:],(1,0,2)) synapse_decoding[j:,i,:,:] = np.transpose(synapse_decode[:,:,:],(1,0,2)) spike_decoding_test[j:,i,:,:] = np.transpose(spike_decode_test[:,:,:],(1,0,2)) synapse_decoding_test[j:,i,:,:] = np.transpose(synapse_decode_test[:,:,:],(1,0,2)) print(spike_decoding.shape) """ Calculate the mean decoding accuracy for the last 500 ms of the delay """ dt=20 d = range(1900//dt,2400//dt) delay_accuracy = np.mean(np.mean(spike_decoding[:,:,d,:],axis=3),axis=2) fn = ['DMS_stp_', 'DMC_stp_', 'DMrS_stp_', 'DMS_DMrS_stp_'] titles = ['DMS', 'DMC', 'DMrS', 'DMS + DMrS'] # combine the DMS and DMrS trials for the DMS_DMrS task delay_accuracy[3,:] = np.mean(delay_accuracy[3:,:],axis=0) perf_combined = perf[:num_tasks,:] perf_combined[num_tasks-1,:] = np.mean(perf[num_tasks:,:],axis=0) # will find 2 examples for each task ind_example = np.zeros((num_tasks, 3),dtype=np.int8) for j in range(num_tasks): ind_good_perf = np.where(perf_combined[j,:] > 0.9)[0] ind_sort = np.argsort(delay_accuracy[j,ind_good_perf]) #ind_example[j,0] = ind_good_perf[ind_sort][-1] ind_example[j,0]= ind_good_perf[ind_sort][len(ind_sort)//2] ind_example[j,1]= ind_good_perf[ind_sort][0] f = plt.figure(figsize=(6,8.5)) for j in range(num_tasks): if fn[j] == 'DMC_stp_': chance_level = 1/2 else: chance_level = 1/8 for i in range(2): ax = f.add_subplot(num_tasks+1, 2, j*2+i+1) u = np.mean(spike_decoding[j,ind_example[j,i],:,:],axis=1) se = np.std(spike_decoding[j,ind_example[j,i],:,:],axis=1) ax.plot(t,u,'g') ax.fill_between(t,u-se,u+se,facecolor=(0,1,0,0.5)) u = np.mean(synapse_decoding[j,ind_example[j,i],:,:],axis=1) se = np.std(synapse_decoding[j,ind_example[j,i],:,:],axis=1) ax.plot(t,u,'m') ax.fill_between(t,u-se,u+se,facecolor=(1,0,1,0.5)) na.add_subplot_fixings(ax, chance_level=chance_level) if j == 3: # DMS_DMrS task u = np.mean(spike_decoding[j+1,ind_example[j,i],:,:],axis=1) se = np.std(spike_decoding[j+1,ind_example[j,i],:,:],axis=1) ax.plot(t,u,'b') ax.fill_between(t,u-se,u+se,facecolor=(0,0,1,0.5)) u = np.mean(synapse_decoding[j+1,ind_example[j,i],:,:],axis=1) se = np.std(synapse_decoding[j+1,ind_example[j,i],:,:],axis=1) ax.plot(t,u,'r') ax.fill_between(t,u-se,u+se,facecolor=(1,0,0,0.5)) ax.set_xticks([-500,0,500,1000,1500]) ax.plot([1000,1000],[-2, 99],'k--') ax.set_yticks([0,0.5,1]) ax.set_title(titles[j]) ax.set_ylabel('Decoding accuracy') ax.set_ylim([0, 1]) plt.tight_layout() plt.savefig('Summary1.pdf', format='pdf') plt.show() col=['b','r','g','c','k'] marker = ['o','v','^','s','D'] """ Normalize delay decoding """ for j in range(num_tasks+1): if j == 1: delay_accuracy[j,:] = (delay_accuracy[j,:]-0.5)*2 else: delay_accuracy[j,:] = (delay_accuracy[j,:]-1/8)*8/7 f = plt.figure(figsize=(6.5,3)) ax = f.add_subplot(1, 3, 1) for j in range(num_tasks+1): ind_good_models = np.where(perf[j,:] > 0.9)[0] #ax.plot(delay_accuracy[j,ind_good_models], perf_shuffled_hidden[j,ind_good_models] # -perf[j,ind_good_models],marker[j], color=col[j], markersize=3) ax.plot(delay_accuracy[j,ind_good_models], perf_shuffled_hidden[j,ind_good_models] -perf[j,ind_good_models],marker[j], color=col[j], markersize=3) ax.set_xlim(-0.1,1.02) ax.set_aspect(1.12/0.5) ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') ax.set_yticks([-0.5,-0.25,0]) ax.set_xticks([0,0.5,1]) ax.set_ylabel('Delta acc. shuffled spike rate') ax.set_xlabel('Normalized delay decoding acc.') ax = f.add_subplot(1, 3, 2) for j in range(num_tasks+1): ind_good_models = np.where(perf[j,:] > 0.9)[0] #ax.plot(delay_accuracy[j,ind_good_models], perf_shuffled_hidden[j,ind_good_models] # -perf[j,ind_good_models],marker[j], color=col[j], markersize=3) ax.plot(delay_accuracy[j,ind_good_models], perf_shuffled_stp[j,ind_good_models] -perf[j,ind_good_models],marker[j], color=col[j], markersize=3) ax.set_xlim(-0.1,1.02) ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') ax.set_yticks([-0.5,-0.25,0]) ax.set_xticks([0,0.5,1]) ax.set_aspect(1.12/0.5) ax.set_ylabel('Delta acc. shuffled STP') ax.set_xlabel('Normalized delay decoding acc.') ax = f.add_subplot(1, 3, 3) for j in range(num_tasks+1): ind_good_models = np.where(perf[j,:] > 0.9)[0] ax.plot(perf_shuffled_stp[j,ind_good_models]-perf[j,ind_good_models], perf_shuffled_hidden[j,ind_good_models] -perf[j,ind_good_models],marker[j], color=col[j], markersize=3) ax.set_aspect(1) ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') ax.set_yticks([-0.5,-0.25,0]) ax.set_xticks([-0.5,-0.25,0]) ax.set_ylabel('Delta acc. shuffled spike rate') ax.set_xlabel('Delta acc. shuffled STP') plt.tight_layout() plt.savefig('Summary2.pdf', format='pdf') plt.show() return spike_decoding, synapse_decoding, spike_decoding_test, synapse_decoding_test, perf, perf_shuffled_hidden, perf_shuffled_stp, ind_example def get_perf(y, y_hat, mask, rule): """ only examine time points when test stimulus is on in another words, when y[0,:,:] is not 0 """ print('Neural analysis: get_perf') print(y.shape, y_hat.shape, mask.shape) mask *= np.logical_or(y[1,:,:]>0,y[2,:,:]>0) #mask *= y[0,:,:]==0 y = np.argmax(y, axis = 0) y_hat = np.argmax(y_hat, axis = 0) return np.sum(np.float32(y == y_hat)*np.squeeze(mask))/np.sum(mask)
[ "numpy.sum", "numpy.arctan2", "numpy.maximum", "numpy.argmax", "numpy.abs", "numpy.floor", "numpy.ones", "numpy.isnan", "numpy.argsort", "matplotlib.pyplot.figure", "numpy.mean", "numpy.arange", "numpy.sin", "sklearn.svm.SVC", "matplotlib.patches.Patch", "numpy.diag", "matplotlib.pyp...
[((54515, 54541), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(8, 4)'}), '(figsize=(8, 4))\n', (54525, 54541), True, 'import matplotlib.pyplot as plt\n'), ((54549, 54571), 'numpy.arange', 'np.arange', (['(0)', '(2700)', 'dt'], {}), '(0, 2700, dt)\n', (54558, 54571), True, 'import numpy as np\n'), ((55684, 55734), 'matplotlib.patches.Patch', 'mpatches.Patch', ([], {'color': '"""green"""', 'label': '"""without STP"""'}), "(color='green', label='without STP')\n", (55698, 55734), True, 'import matplotlib.patches as mpatches\n'), ((55755, 55804), 'matplotlib.patches.Patch', 'mpatches.Patch', ([], {'color': '"""magenta"""', 'label': '"""with STP"""'}), "(color='magenta', label='with STP')\n", (55769, 55804), True, 'import matplotlib.patches as mpatches\n'), ((55809, 55882), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '(0)', 'handles': '[green_patch, magenta_patch]', 'prop': "{'size': 6}"}), "(loc=0, handles=[green_patch, magenta_patch], prop={'size': 6})\n", (55819, 55882), True, 'import matplotlib.pyplot as plt\n'), ((56024, 56064), 'numpy.mean', 'np.mean', (['sample_pev1[:, rule, :]'], {'axis': '(0)'}), '(sample_pev1[:, rule, :], axis=0)\n', (56031, 56064), True, 'import numpy as np\n'), ((56071, 56111), 'numpy.mean', 'np.mean', (['sample_pev2[:, rule, :]'], {'axis': '(0)'}), '(sample_pev2[:, rule, :], axis=0)\n', (56078, 56111), True, 'import numpy as np\n'), ((56118, 56144), 'numpy.mean', 'np.mean', (['rule_pev2'], {'axis': '(0)'}), '(rule_pev2, axis=0)\n', (56125, 56144), True, 'import numpy as np\n'), ((57039, 57095), 'numpy.mean', 'np.mean', (["svm_results1['sample_full'][:, rule, :]"], {'axis': '(1)'}), "(svm_results1['sample_full'][:, rule, :], axis=1)\n", (57046, 57095), True, 'import numpy as np\n'), ((57102, 57158), 'numpy.mean', 'np.mean', (["svm_results2['sample_full'][:, rule, :]"], {'axis': '(1)'}), "(svm_results2['sample_full'][:, rule, :], axis=1)\n", (57109, 57158), True, 'import numpy as np\n'), ((57166, 57221), 'numpy.std', 'np.std', (["svm_results1['sample_full'][:, rule, :]"], {'axis': '(1)'}), "(svm_results1['sample_full'][:, rule, :], axis=1)\n", (57172, 57221), True, 'import numpy as np\n'), ((57229, 57284), 'numpy.std', 'np.std', (["svm_results2['sample_full'][:, rule, :]"], {'axis': '(1)'}), "(svm_results2['sample_full'][:, rule, :], axis=1)\n", (57235, 57284), True, 'import numpy as np\n'), ((58674, 58718), 'numpy.mean', 'np.mean', (['sample_stp_pev2[:, rule, :]'], {'axis': '(0)'}), '(sample_stp_pev2[:, rule, :], axis=0)\n', (58681, 58718), True, 'import numpy as np\n'), ((59348, 59408), 'numpy.mean', 'np.mean', (["svm_results2['sample_full_stp'][:, rule, :]"], {'axis': '(1)'}), "(svm_results2['sample_full_stp'][:, rule, :], axis=1)\n", (59355, 59408), True, 'import numpy as np\n'), ((59416, 59475), 'numpy.std', 'np.std', (["svm_results2['sample_full_stp'][:, rule, :]"], {'axis': '(1)'}), "(svm_results2['sample_full_stp'][:, rule, :], axis=1)\n", (59422, 59475), True, 'import numpy as np\n'), ((60006, 60024), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (60022, 60024), True, 'import matplotlib.pyplot as plt\n'), ((60029, 60076), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""DMS comparison.pdf"""'], {'format': '"""pdf"""'}), "('DMS comparison.pdf', format='pdf')\n", (60040, 60076), True, 'import matplotlib.pyplot as plt\n'), ((60081, 60091), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (60089, 60091), True, 'import matplotlib.pyplot as plt\n'), ((61305, 61331), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(8, 9)'}), '(figsize=(8, 9))\n', (61315, 61331), True, 'import matplotlib.pyplot as plt\n'), ((61339, 61361), 'numpy.arange', 'np.arange', (['(0)', '(2700)', 'dt'], {}), '(0, 2700, dt)\n', (61348, 61361), True, 'import numpy as np\n'), ((62504, 62554), 'matplotlib.patches.Patch', 'mpatches.Patch', ([], {'color': '"""green"""', 'label': '"""without STP"""'}), "(color='green', label='without STP')\n", (62518, 62554), True, 'import matplotlib.patches as mpatches\n'), ((62575, 62624), 'matplotlib.patches.Patch', 'mpatches.Patch', ([], {'color': '"""magenta"""', 'label': '"""with STP"""'}), "(color='magenta', label='with STP')\n", (62589, 62624), True, 'import matplotlib.patches as mpatches\n'), ((62629, 62702), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '(0)', 'handles': '[green_patch, magenta_patch]', 'prop': "{'size': 6}"}), "(loc=0, handles=[green_patch, magenta_patch], prop={'size': 6})\n", (62639, 62702), True, 'import matplotlib.pyplot as plt\n'), ((62845, 62871), 'numpy.mean', 'np.mean', (['rule_pev1'], {'axis': '(0)'}), '(rule_pev1, axis=0)\n', (62852, 62871), True, 'import numpy as np\n'), ((62880, 62906), 'numpy.mean', 'np.mean', (['rule_pev2'], {'axis': '(0)'}), '(rule_pev2, axis=0)\n', (62887, 62906), True, 'import numpy as np\n'), ((66833, 66851), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (66849, 66851), True, 'import matplotlib.pyplot as plt\n'), ((66856, 66909), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""Two rules comparison.pdf"""'], {'format': '"""pdf"""'}), "('Two rules comparison.pdf', format='pdf')\n", (66867, 66909), True, 'import matplotlib.pyplot as plt\n'), ((66914, 66924), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (66922, 66924), True, 'import matplotlib.pyplot as plt\n'), ((68516, 68543), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(6, 10)'}), '(figsize=(6, 10))\n', (68526, 68543), True, 'import matplotlib.pyplot as plt\n'), ((69150, 69168), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (69166, 69168), True, 'import matplotlib.pyplot as plt\n'), ((69173, 69213), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""Summary.pdf"""'], {'format': '"""pdf"""'}), "('Summary.pdf', format='pdf')\n", (69184, 69213), True, 'import matplotlib.pyplot as plt\n'), ((69218, 69228), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (69226, 69228), True, 'import matplotlib.pyplot as plt\n'), ((69592, 69624), 'numpy.int_', 'np.int_', (['(trial_length_steps * dt)'], {}), '(trial_length_steps * dt)\n', (69599, 69624), True, 'import numpy as np\n'), ((69640, 69670), 'numpy.arange', 'np.arange', (['(0)', 'trial_length', 'dt'], {}), '(0, trial_length, dt)\n', (69649, 69670), True, 'import numpy as np\n'), ((70883, 70927), 'numpy.mean', 'np.mean', (["svm_results1['sample_full']"], {'axis': '(1)'}), "(svm_results1['sample_full'], axis=1)\n", (70890, 70927), True, 'import numpy as np\n'), ((70936, 70979), 'numpy.std', 'np.std', (["svm_results1['sample_full']"], {'axis': '(1)'}), "(svm_results1['sample_full'], axis=1)\n", (70942, 70979), True, 'import numpy as np\n'), ((71099, 71143), 'numpy.mean', 'np.mean', (["svm_results2['sample_full']"], {'axis': '(1)'}), "(svm_results2['sample_full'], axis=1)\n", (71106, 71143), True, 'import numpy as np\n'), ((71152, 71195), 'numpy.std', 'np.std', (["svm_results2['sample_full']"], {'axis': '(1)'}), "(svm_results2['sample_full'], axis=1)\n", (71158, 71195), True, 'import numpy as np\n'), ((71583, 71631), 'numpy.mean', 'np.mean', (["svm_results2['sample_full_stp']"], {'axis': '(1)'}), "(svm_results2['sample_full_stp'], axis=1)\n", (71590, 71631), True, 'import numpy as np\n'), ((71640, 71687), 'numpy.std', 'np.std', (["svm_results2['sample_full_stp']"], {'axis': '(1)'}), "(svm_results2['sample_full_stp'], axis=1)\n", (71646, 71687), True, 'import numpy as np\n'), ((72056, 72078), 'numpy.arange', 'np.arange', (['(0)', '(2900)', 'dt'], {}), '(0, 2900, dt)\n', (72065, 72078), True, 'import numpy as np\n'), ((72434, 72478), 'numpy.zeros', 'np.zeros', (['(4, N, trial_length, num_svm_reps)'], {}), '((4, N, trial_length, num_svm_reps))\n', (72442, 72478), True, 'import numpy as np\n'), ((72502, 72546), 'numpy.zeros', 'np.zeros', (['(4, N, trial_length, num_svm_reps)'], {}), '((4, N, trial_length, num_svm_reps))\n', (72510, 72546), True, 'import numpy as np\n'), ((72573, 72617), 'numpy.zeros', 'np.zeros', (['(4, N, trial_length, num_svm_reps)'], {}), '((4, N, trial_length, num_svm_reps))\n', (72581, 72617), True, 'import numpy as np\n'), ((72646, 72690), 'numpy.zeros', 'np.zeros', (['(4, N, trial_length, num_svm_reps)'], {}), '((4, N, trial_length, num_svm_reps))\n', (72654, 72690), True, 'import numpy as np\n'), ((72702, 72718), 'numpy.zeros', 'np.zeros', (['(4, N)'], {}), '((4, N))\n', (72710, 72718), True, 'import numpy as np\n'), ((72746, 72762), 'numpy.zeros', 'np.zeros', (['(4, N)'], {}), '((4, N))\n', (72754, 72762), True, 'import numpy as np\n'), ((72787, 72803), 'numpy.zeros', 'np.zeros', (['(4, N)'], {}), '((4, N))\n', (72795, 72803), True, 'import numpy as np\n'), ((74620, 74646), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(6, 4)'}), '(figsize=(6, 4))\n', (74630, 74646), True, 'import matplotlib.pyplot as plt\n'), ((75405, 75423), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (75421, 75423), True, 'import matplotlib.pyplot as plt\n'), ((75428, 75475), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""Example models.pdf"""'], {'format': '"""pdf"""'}), "('Example models.pdf', format='pdf')\n", (75439, 75475), True, 'import matplotlib.pyplot as plt\n'), ((75484, 75494), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (75492, 75494), True, 'import matplotlib.pyplot as plt\n'), ((75664, 75690), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(6, 4)'}), '(figsize=(6, 4))\n', (75674, 75690), True, 'import matplotlib.pyplot as plt\n'), ((76633, 76651), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (76649, 76651), True, 'import matplotlib.pyplot as plt\n'), ((76656, 76703), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""Average models.pdf"""'], {'format': '"""pdf"""'}), "('Average models.pdf', format='pdf')\n", (76667, 76703), True, 'import matplotlib.pyplot as plt\n'), ((76709, 76719), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (76717, 76719), True, 'import matplotlib.pyplot as plt\n'), ((76899, 76925), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(6, 4)'}), '(figsize=(6, 4))\n', (76909, 76925), True, 'import matplotlib.pyplot as plt\n'), ((77645, 77663), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (77661, 77663), True, 'import matplotlib.pyplot as plt\n'), ((77668, 77711), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""All models.pdf"""'], {'format': '"""pdf"""'}), "('All models.pdf', format='pdf')\n", (77679, 77711), True, 'import matplotlib.pyplot as plt\n'), ((77717, 77727), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (77725, 77727), True, 'import matplotlib.pyplot as plt\n'), ((78125, 78147), 'numpy.arange', 'np.arange', (['(0)', '(2900)', 'dt'], {}), '(0, 2900, dt)\n', (78134, 78147), True, 'import numpy as np\n'), ((78487, 78513), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(3, 2)'}), '(figsize=(3, 2))\n', (78497, 78513), True, 'import matplotlib.pyplot as plt\n'), ((78576, 78614), 'numpy.mean', 'np.mean', (['spike_decode[:, 0, :]'], {'axis': '(1)'}), '(spike_decode[:, 0, :], axis=1)\n', (78583, 78614), True, 'import numpy as np\n'), ((78621, 78658), 'numpy.std', 'np.std', (['spike_decode[:, 0, :]'], {'axis': '(1)'}), '(spike_decode[:, 0, :], axis=1)\n', (78627, 78658), True, 'import numpy as np\n'), ((78740, 78780), 'numpy.mean', 'np.mean', (['synapse_decode[:, 0, :]'], {'axis': '(1)'}), '(synapse_decode[:, 0, :], axis=1)\n', (78747, 78780), True, 'import numpy as np\n'), ((78787, 78826), 'numpy.std', 'np.std', (['synapse_decode[:, 0, :]'], {'axis': '(1)'}), '(synapse_decode[:, 0, :], axis=1)\n', (78793, 78826), True, 'import numpy as np\n'), ((79025, 79043), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (79041, 79043), True, 'import matplotlib.pyplot as plt\n'), ((79048, 79096), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""Var delay model.pdf"""'], {'format': '"""pdf"""'}), "('Var delay model.pdf', format='pdf')\n", (79059, 79096), True, 'import matplotlib.pyplot as plt\n'), ((79102, 79112), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (79110, 79112), True, 'import matplotlib.pyplot as plt\n'), ((79319, 79344), 'numpy.zeros', 'np.zeros', (['(num_delays, N)'], {}), '((num_delays, N))\n', (79327, 79344), True, 'import numpy as np\n'), ((79364, 79389), 'numpy.zeros', 'np.zeros', (['(num_delays, N)'], {}), '((num_delays, N))\n', (79372, 79389), True, 'import numpy as np\n'), ((79401, 79426), 'numpy.zeros', 'np.zeros', (['(num_delays, N)'], {}), '((num_delays, N))\n', (79409, 79426), True, 'import numpy as np\n'), ((80988, 81014), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(3, 2)'}), '(figsize=(3, 2))\n', (80998, 81014), True, 'import matplotlib.pyplot as plt\n'), ((81593, 81615), 'numpy.arange', 'np.arange', (['(0)', '(2900)', 'dt'], {}), '(0, 2900, dt)\n', (81602, 81615), True, 'import numpy as np\n'), ((82142, 82198), 'numpy.zeros', 'np.zeros', (['(num_tasks + 1, N, trial_length, num_svm_reps)'], {}), '((num_tasks + 1, N, trial_length, num_svm_reps))\n', (82150, 82198), True, 'import numpy as np\n'), ((82220, 82276), 'numpy.zeros', 'np.zeros', (['(num_tasks + 1, N, trial_length, num_svm_reps)'], {}), '((num_tasks + 1, N, trial_length, num_svm_reps))\n', (82228, 82276), True, 'import numpy as np\n'), ((82301, 82357), 'numpy.zeros', 'np.zeros', (['(num_tasks + 1, N, trial_length, num_svm_reps)'], {}), '((num_tasks + 1, N, trial_length, num_svm_reps))\n', (82309, 82357), True, 'import numpy as np\n'), ((82384, 82440), 'numpy.zeros', 'np.zeros', (['(num_tasks + 1, N, trial_length, num_svm_reps)'], {}), '((num_tasks + 1, N, trial_length, num_svm_reps))\n', (82392, 82440), True, 'import numpy as np\n'), ((82450, 82478), 'numpy.zeros', 'np.zeros', (['(num_tasks + 1, N)'], {}), '((num_tasks + 1, N))\n', (82458, 82478), True, 'import numpy as np\n'), ((82504, 82532), 'numpy.zeros', 'np.zeros', (['(num_tasks + 1, N)'], {}), '((num_tasks + 1, N))\n', (82512, 82532), True, 'import numpy as np\n'), ((82555, 82583), 'numpy.zeros', 'np.zeros', (['(num_tasks + 1, N)'], {}), '((num_tasks + 1, N))\n', (82563, 82583), True, 'import numpy as np\n'), ((85424, 85462), 'numpy.mean', 'np.mean', (['delay_accuracy[3:, :]'], {'axis': '(0)'}), '(delay_accuracy[3:, :], axis=0)\n', (85431, 85462), True, 'import numpy as np\n'), ((85535, 85571), 'numpy.mean', 'np.mean', (['perf[num_tasks:, :]'], {'axis': '(0)'}), '(perf[num_tasks:, :], axis=0)\n', (85542, 85571), True, 'import numpy as np\n'), ((85634, 85673), 'numpy.zeros', 'np.zeros', (['(num_tasks, 3)'], {'dtype': 'np.int8'}), '((num_tasks, 3), dtype=np.int8)\n', (85642, 85673), True, 'import numpy as np\n'), ((86023, 86051), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(6, 8.5)'}), '(figsize=(6, 8.5))\n', (86033, 86051), True, 'import matplotlib.pyplot as plt\n'), ((87607, 87625), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (87623, 87625), True, 'import matplotlib.pyplot as plt\n'), ((87630, 87671), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""Summary1.pdf"""'], {'format': '"""pdf"""'}), "('Summary1.pdf', format='pdf')\n", (87641, 87671), True, 'import matplotlib.pyplot as plt\n'), ((87680, 87690), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (87688, 87690), True, 'import matplotlib.pyplot as plt\n'), ((88012, 88040), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(6.5, 3)'}), '(figsize=(6.5, 3))\n', (88022, 88040), True, 'import matplotlib.pyplot as plt\n'), ((90430, 90448), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (90446, 90448), True, 'import matplotlib.pyplot as plt\n'), ((90453, 90494), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""Summary2.pdf"""'], {'format': '"""pdf"""'}), "('Summary2.pdf', format='pdf')\n", (90464, 90494), True, 'import matplotlib.pyplot as plt\n'), ((90503, 90513), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (90511, 90513), True, 'import matplotlib.pyplot as plt\n'), ((90916, 90961), 'numpy.logical_or', 'np.logical_or', (['(y[1, :, :] > 0)', '(y[2, :, :] > 0)'], {}), '(y[1, :, :] > 0, y[2, :, :] > 0)\n', (90929, 90961), True, 'import numpy as np\n'), ((90987, 91007), 'numpy.argmax', 'np.argmax', (['y'], {'axis': '(0)'}), '(y, axis=0)\n', (90996, 91007), True, 'import numpy as np\n'), ((91022, 91046), 'numpy.argmax', 'np.argmax', (['y_hat'], {'axis': '(0)'}), '(y_hat, axis=0)\n', (91031, 91046), True, 'import numpy as np\n'), ((542, 570), 'numpy.stack', 'np.stack', (["x['syn_x']"], {'axis': '(2)'}), "(x['syn_x'], axis=2)\n", (550, 570), True, 'import numpy as np\n'), ((591, 619), 'numpy.stack', 'np.stack', (['self.syn_x'], {'axis': '(1)'}), '(self.syn_x, axis=1)\n', (599, 619), True, 'import numpy as np\n'), ((955, 983), 'numpy.stack', 'np.stack', (["x['syn_u']"], {'axis': '(2)'}), "(x['syn_u'], axis=2)\n", (963, 983), True, 'import numpy as np\n'), ((1004, 1032), 'numpy.stack', 'np.stack', (['self.syn_u'], {'axis': '(1)'}), '(self.syn_u, axis=1)\n', (1012, 1032), True, 'import numpy as np\n'), ((1378, 1413), 'numpy.stack', 'np.stack', (["x['hidden_state']"], {'axis': '(2)'}), "(x['hidden_state'], axis=2)\n", (1386, 1413), True, 'import numpy as np\n'), ((1440, 1474), 'numpy.stack', 'np.stack', (['self.rnn_outputs'], {'axis': '(1)'}), '(self.rnn_outputs, axis=1)\n', (1448, 1474), True, 'import numpy as np\n'), ((1590, 1682), 'numpy.reshape', 'np.reshape', (['self.rnn_outputs', '(num_neurons, trial_length, num_blocks * trials_per_block)'], {}), '(self.rnn_outputs, (num_neurons, trial_length, num_blocks *\n trials_per_block))\n', (1600, 1682), True, 'import numpy as np\n'), ((1975, 2012), 'numpy.transpose', 'np.transpose', (['self.train_mask', '(0, 1)'], {}), '(self.train_mask, (0, 1))\n', (1987, 2012), True, 'import numpy as np\n'), ((2117, 2157), 'numpy.transpose', 'np.transpose', (['self.rnn_inputs', '(2, 0, 1)'], {}), '(self.rnn_inputs, (2, 0, 1))\n', (2129, 2157), True, 'import numpy as np\n'), ((2226, 2262), 'numpy.stack', 'np.stack', (["x['model_outputs']"], {'axis': '(2)'}), "(x['model_outputs'], axis=2)\n", (2234, 2262), True, 'import numpy as np\n'), ((2291, 2327), 'numpy.stack', 'np.stack', (['self.model_outputs'], {'axis': '(1)'}), '(self.model_outputs, axis=1)\n', (2299, 2327), True, 'import numpy as np\n'), ((2406, 2500), 'numpy.reshape', 'np.reshape', (['self.model_outputs', '(num_classes, trial_length, num_blocks * trials_per_block)'], {}), '(self.model_outputs, (num_classes, trial_length, num_blocks *\n trials_per_block))\n', (2416, 2500), True, 'import numpy as np\n'), ((4386, 4425), 'numpy.zeros', 'np.zeros', (['(num_input_neurons, num_dirs)'], {}), '((num_input_neurons, num_dirs))\n', (4394, 4425), True, 'import numpy as np\n'), ((4502, 4539), 'numpy.zeros', 'np.zeros', (['(num_rnn_neurons, num_dirs)'], {}), '((num_rnn_neurons, num_dirs))\n', (4510, 4539), True, 'import numpy as np\n'), ((4906, 4940), 'numpy.dot', 'np.dot', (['self.W_in', 'mean_input_resp'], {}), '(self.W_in, mean_input_resp)\n', (4912, 4940), True, 'import numpy as np\n'), ((5117, 5154), 'numpy.zeros', 'np.zeros', (['(num_neurons, trial_length)'], {}), '((num_neurons, trial_length))\n', (5125, 5154), True, 'import numpy as np\n'), ((5176, 5213), 'numpy.zeros', 'np.zeros', (['(num_neurons, trial_length)'], {}), '((num_neurons, trial_length))\n', (5184, 5213), True, 'import numpy as np\n'), ((5235, 5272), 'numpy.zeros', 'np.zeros', (['(num_neurons, trial_length)'], {}), '((num_neurons, trial_length))\n', (5243, 5272), True, 'import numpy as np\n'), ((5291, 5331), 'numpy.zeros', 'np.zeros', (['(num_neurons, 2, trial_length)'], {}), '((num_neurons, 2, trial_length))\n', (5299, 5331), True, 'import numpy as np\n'), ((5351, 5391), 'numpy.zeros', 'np.zeros', (['(num_neurons, 2, trial_length)'], {}), '((num_neurons, 2, trial_length))\n', (5359, 5391), True, 'import numpy as np\n'), ((5411, 5451), 'numpy.zeros', 'np.zeros', (['(num_neurons, 2, trial_length)'], {}), '((num_neurons, 2, trial_length))\n', (5419, 5451), True, 'import numpy as np\n'), ((5482, 5506), 'numpy.ones', 'np.ones', (['(num_trials, 3)'], {}), '((num_trials, 3))\n', (5489, 5506), True, 'import numpy as np\n'), ((5533, 5591), 'numpy.cos', 'np.cos', (['(2 * np.pi * self.sample_dir / self.num_motion_dirs)'], {}), '(2 * np.pi * self.sample_dir / self.num_motion_dirs)\n', (5539, 5591), True, 'import numpy as np\n'), ((5614, 5672), 'numpy.sin', 'np.sin', (['(2 * np.pi * self.sample_dir / self.num_motion_dirs)'], {}), '(2 * np.pi * self.sample_dir / self.num_motion_dirs)\n', (5620, 5672), True, 'import numpy as np\n'), ((5696, 5720), 'numpy.ones', 'np.ones', (['(num_trials, 3)'], {}), '((num_trials, 3))\n', (5703, 5720), True, 'import numpy as np\n'), ((5745, 5801), 'numpy.cos', 'np.cos', (['(2 * np.pi * self.test_dir / self.num_motion_dirs)'], {}), '(2 * np.pi * self.test_dir / self.num_motion_dirs)\n', (5751, 5801), True, 'import numpy as np\n'), ((5822, 5878), 'numpy.sin', 'np.sin', (['(2 * np.pi * self.test_dir / self.num_motion_dirs)'], {}), '(2 * np.pi * self.test_dir / self.num_motion_dirs)\n', (5828, 5878), True, 'import numpy as np\n'), ((7277, 7349), 'numpy.zeros', 'np.zeros', (['(num_neurons, num_neurons, self.num_motion_dirs, trial_length)'], {}), '((num_neurons, num_neurons, self.num_motion_dirs, trial_length))\n', (7285, 7349), True, 'import numpy as np\n'), ((7381, 7440), 'numpy.zeros', 'np.zeros', (['(num_neurons, self.num_motion_dirs, trial_length)'], {}), '((num_neurons, self.num_motion_dirs, trial_length))\n', (7389, 7440), True, 'import numpy as np\n'), ((8311, 8396), 'numpy.zeros', 'np.zeros', (['(num_neurons, self.num_motion_dirs, self.num_motion_dirs, trial_length)'], {}), '((num_neurons, self.num_motion_dirs, self.num_motion_dirs,\n trial_length))\n', (8319, 8396), True, 'import numpy as np\n'), ((8423, 8508), 'numpy.zeros', 'np.zeros', (['(num_neurons, self.num_motion_dirs, self.num_motion_dirs, trial_length)'], {}), '((num_neurons, self.num_motion_dirs, self.num_motion_dirs,\n trial_length))\n', (8431, 8508), True, 'import numpy as np\n'), ((9609, 9660), 'numpy.zeros', 'np.zeros', (['(self.num_rules, self.num_motion_dirs, 2)'], {}), '((self.num_rules, self.num_motion_dirs, 2))\n', (9617, 9660), True, 'import numpy as np\n'), ((9677, 9728), 'numpy.zeros', 'np.zeros', (['(self.num_rules, self.num_motion_dirs, 2)'], {}), '((self.num_rules, self.num_motion_dirs, 2))\n', (9685, 9728), True, 'import numpy as np\n'), ((10758, 10786), 'numpy.zeros', 'np.zeros', (['self.max_num_tests'], {}), '(self.max_num_tests)\n', (10766, 10786), True, 'import numpy as np\n'), ((10824, 10852), 'numpy.zeros', 'np.zeros', (['self.max_num_tests'], {}), '(self.max_num_tests)\n', (10832, 10852), True, 'import numpy as np\n'), ((10876, 10904), 'numpy.zeros', 'np.zeros', (['self.max_num_tests'], {}), '(self.max_num_tests)\n', (10884, 10904), True, 'import numpy as np\n'), ((10934, 10962), 'numpy.zeros', 'np.zeros', (['self.max_num_tests'], {}), '(self.max_num_tests)\n', (10942, 10962), True, 'import numpy as np\n'), ((12520, 12547), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(12, 8)'}), '(figsize=(12, 8))\n', (12530, 12547), True, 'import matplotlib.pyplot as plt\n'), ((12905, 12915), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (12913, 12915), True, 'import matplotlib.pyplot as plt\n'), ((13046, 13140), 'sklearn.svm.SVC', 'svm.SVC', ([], {'C': '(1)', 'kernel': '"""linear"""', 'decision_function_shape': '"""ovr"""', 'shrinking': '(False)', 'tol': '(0.0001)'}), "(C=1, kernel='linear', decision_function_shape='ovr', shrinking=\n False, tol=0.0001)\n", (13053, 13140), False, 'from sklearn import svm\n'), ((13228, 13278), 'numpy.zeros', 'np.zeros', (['(trial_length, self.num_rules, num_reps)'], {}), '((trial_length, self.num_rules, num_reps))\n', (13236, 13278), True, 'import numpy as np\n'), ((13304, 13354), 'numpy.zeros', 'np.zeros', (['(trial_length, self.num_rules, num_reps)'], {}), '((trial_length, self.num_rules, num_reps))\n', (13312, 13354), True, 'import numpy as np\n'), ((13383, 13433), 'numpy.zeros', 'np.zeros', (['(trial_length, self.num_rules, num_reps)'], {}), '((trial_length, self.num_rules, num_reps))\n', (13391, 13433), True, 'import numpy as np\n'), ((13464, 13514), 'numpy.zeros', 'np.zeros', (['(trial_length, self.num_rules, num_reps)'], {}), '((trial_length, self.num_rules, num_reps))\n', (13472, 13514), True, 'import numpy as np\n'), ((15946, 15979), 'numpy.zeros', 'np.zeros', (['(num_neurons, num_lags)'], {}), '((num_neurons, num_lags))\n', (15954, 15979), True, 'import numpy as np\n'), ((16005, 16038), 'numpy.zeros', 'np.zeros', (['(num_neurons, num_lags)'], {}), '((num_neurons, num_lags))\n', (16013, 16038), True, 'import numpy as np\n'), ((16068, 16101), 'numpy.zeros', 'np.zeros', (['(num_neurons, num_lags)'], {}), '((num_neurons, num_lags))\n', (16076, 16101), True, 'import numpy as np\n'), ((17711, 17769), 'numpy.zeros', 'np.zeros', (['(num_neurons, num_rules, num_dirs, trial_length)'], {}), '((num_neurons, num_rules, num_dirs, trial_length))\n', (17719, 17769), True, 'import numpy as np\n'), ((17795, 17843), 'numpy.zeros', 'np.zeros', (['(num_classes, num_rules, trial_length)'], {}), '((num_classes, num_rules, trial_length))\n', (17803, 17843), True, 'import numpy as np\n'), ((17873, 17921), 'numpy.zeros', 'np.zeros', (['(num_classes, num_rules, trial_length)'], {}), '((num_classes, num_rules, trial_length))\n', (17881, 17921), True, 'import numpy as np\n'), ((19073, 19166), 'sklearn.svm.SVC', 'svm.SVC', ([], {'C': '(1)', 'kernel': '"""linear"""', 'decision_function_shape': '"""ovr"""', 'shrinking': '(False)', 'tol': '(1e-05)'}), "(C=1, kernel='linear', decision_function_shape='ovr', shrinking=\n False, tol=1e-05)\n", (19080, 19166), False, 'from sklearn import svm\n'), ((19260, 19309), 'numpy.zeros', 'np.zeros', (['(num_neurons, 2, 2, 2, 2, trial_length)'], {}), '((num_neurons, 2, 2, 2, 2, trial_length))\n', (19268, 19309), True, 'import numpy as np\n'), ((19331, 19380), 'numpy.zeros', 'np.zeros', (['(num_neurons, 2, 2, 2, 2, trial_length)'], {}), '((num_neurons, 2, 2, 2, 2, trial_length))\n', (19339, 19380), True, 'import numpy as np\n'), ((19412, 19458), 'numpy.zeros', 'np.zeros', (['(2, 2, 2, 2, trial_length, num_reps)'], {}), '((2, 2, 2, 2, trial_length, num_reps))\n', (19420, 19458), True, 'import numpy as np\n'), ((19484, 19530), 'numpy.zeros', 'np.zeros', (['(2, 2, 2, 2, trial_length, num_reps)'], {}), '((2, 2, 2, 2, trial_length, num_reps))\n', (19492, 19530), True, 'import numpy as np\n'), ((19558, 19591), 'numpy.zeros', 'np.zeros', (['(2, 2, 3, trial_length)'], {}), '((2, 2, 3, trial_length))\n', (19566, 19591), True, 'import numpy as np\n'), ((22082, 22101), 'numpy.zeros', 'np.zeros', (['num_conds'], {}), '(num_conds)\n', (22090, 22101), True, 'import numpy as np\n'), ((22255, 22291), 'numpy.zeros', 'np.zeros', (['(min_num_trials * num_conds)'], {}), '(min_num_trials * num_conds)\n', (22263, 22291), True, 'import numpy as np\n'), ((22310, 22360), 'numpy.zeros', 'np.zeros', (['(min_num_trials * num_conds, y.shape[1])'], {}), '((min_num_trials * num_conds, y.shape[1]))\n', (22318, 22360), True, 'import numpy as np\n'), ((22655, 22673), 'numpy.zeros', 'np.zeros', (['num_reps'], {}), '(num_reps)\n', (22663, 22673), True, 'import numpy as np\n'), ((23691, 23709), 'numpy.zeros', 'np.zeros', (['num_reps'], {}), '(num_reps)\n', (23699, 23709), True, 'import numpy as np\n'), ((24526, 24579), 'numpy.zeros', 'np.zeros', (['(num_neurons, self.num_rules, trial_length)'], {}), '((num_neurons, self.num_rules, trial_length))\n', (24534, 24579), True, 'import numpy as np\n'), ((24598, 24651), 'numpy.zeros', 'np.zeros', (['(num_neurons, self.num_rules, trial_length)'], {}), '((num_neurons, self.num_rules, trial_length))\n', (24606, 24651), True, 'import numpy as np\n'), ((24670, 24707), 'numpy.zeros', 'np.zeros', (['(num_neurons, trial_length)'], {}), '((num_neurons, trial_length))\n', (24678, 24707), True, 'import numpy as np\n'), ((24727, 24780), 'numpy.zeros', 'np.zeros', (['(num_neurons, self.num_rules, trial_length)'], {}), '((num_neurons, self.num_rules, trial_length))\n', (24735, 24780), True, 'import numpy as np\n'), ((24805, 24858), 'numpy.zeros', 'np.zeros', (['(num_neurons, self.num_rules, trial_length)'], {}), '((num_neurons, self.num_rules, trial_length))\n', (24813, 24858), True, 'import numpy as np\n'), ((24883, 24936), 'numpy.zeros', 'np.zeros', (['(num_neurons, self.num_rules, trial_length)'], {}), '((num_neurons, self.num_rules, trial_length))\n', (24891, 24936), True, 'import numpy as np\n'), ((24965, 25018), 'numpy.zeros', 'np.zeros', (['(num_neurons, self.num_rules, trial_length)'], {}), '((num_neurons, self.num_rules, trial_length))\n', (24973, 25018), True, 'import numpy as np\n'), ((25041, 25094), 'numpy.zeros', 'np.zeros', (['(num_neurons, self.num_rules, trial_length)'], {}), '((num_neurons, self.num_rules, trial_length))\n', (25049, 25094), True, 'import numpy as np\n'), ((26889, 26905), 'numpy.unique', 'np.unique', (['conds'], {}), '(conds)\n', (26898, 26905), True, 'import numpy as np\n'), ((26997, 27013), 'numpy.zeros', 'np.zeros', (['(1, m)'], {}), '((1, m))\n', (27005, 27013), True, 'import numpy as np\n'), ((27030, 27046), 'numpy.zeros', 'np.zeros', (['(1, m)'], {}), '((1, m))\n', (27038, 27046), True, 'import numpy as np\n'), ((27231, 27242), 'numpy.mean', 'np.mean', (['xr'], {}), '(xr)\n', (27238, 27242), True, 'import numpy as np\n'), ((27337, 27358), 'numpy.where', 'np.where', (['(countx == 0)'], {}), '(countx == 0)\n', (27345, 27358), True, 'import numpy as np\n'), ((28058, 28071), 'numpy.isnan', 'np.isnan', (['pev'], {}), '(pev)\n', (28066, 28071), True, 'import numpy as np\n'), ((29117, 29158), 'numpy.mean', 'np.mean', (['sample_pev[:, rule, 30:]'], {'axis': '(1)'}), '(sample_pev[:, rule, 30:], axis=1)\n', (29124, 29158), True, 'import numpy as np\n'), ((29172, 29192), 'numpy.argsort', 'np.argsort', (['mean_pev'], {}), '(mean_pev)\n', (29182, 29192), True, 'import numpy as np\n'), ((29307, 29339), 'numpy.int_', 'np.int_', (['(trial_length_steps * dt)'], {}), '(trial_length_steps * dt)\n', (29314, 29339), True, 'import numpy as np\n'), ((29359, 29389), 'numpy.arange', 'np.arange', (['(0)', 'trial_length', 'dt'], {}), '(0, trial_length, dt)\n', (29368, 29389), True, 'import numpy as np\n'), ((44196, 44222), 'numpy.arange', 'np.arange', (['(0)', '(220 * dt)', 'dt'], {}), '(0, 220 * dt, dt)\n', (44205, 44222), True, 'import numpy as np\n'), ((44453, 44479), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(6, 6)'}), '(figsize=(6, 6))\n', (44463, 44479), True, 'import matplotlib.pyplot as plt\n'), ((45855, 45905), 'numpy.mean', 'np.mean', (['sample_decoding[0, 0, 1, 1, :, :]'], {'axis': '(1)'}), '(sample_decoding[0, 0, 1, 1, :, :], axis=1)\n', (45862, 45905), True, 'import numpy as np\n'), ((45913, 45962), 'numpy.std', 'np.std', (['sample_decoding[0, 0, 1, 1, :, :]'], {'axis': '(1)'}), '(sample_decoding[0, 0, 1, 1, :, :], axis=1)\n', (45919, 45962), True, 'import numpy as np\n'), ((46210, 46260), 'numpy.mean', 'np.mean', (['sample_decoding[0, 0, 0, 1, :, :]'], {'axis': '(1)'}), '(sample_decoding[0, 0, 0, 1, :, :], axis=1)\n', (46217, 46260), True, 'import numpy as np\n'), ((46268, 46317), 'numpy.std', 'np.std', (['sample_decoding[0, 0, 0, 1, :, :]'], {'axis': '(1)'}), '(sample_decoding[0, 0, 0, 1, :, :], axis=1)\n', (46274, 46317), True, 'import numpy as np\n'), ((46768, 46818), 'numpy.mean', 'np.mean', (['sample_decoding[1, 1, 1, 0, :, :]'], {'axis': '(1)'}), '(sample_decoding[1, 1, 1, 0, :, :], axis=1)\n', (46775, 46818), True, 'import numpy as np\n'), ((46826, 46875), 'numpy.std', 'np.std', (['sample_decoding[1, 1, 1, 0, :, :]'], {'axis': '(1)'}), '(sample_decoding[1, 1, 1, 0, :, :], axis=1)\n', (46832, 46875), True, 'import numpy as np\n'), ((47123, 47173), 'numpy.mean', 'np.mean', (['sample_decoding[1, 1, 0, 0, :, :]'], {'axis': '(1)'}), '(sample_decoding[1, 1, 0, 0, :, :], axis=1)\n', (47130, 47173), True, 'import numpy as np\n'), ((47181, 47230), 'numpy.std', 'np.std', (['sample_decoding[1, 1, 0, 0, :, :]'], {'axis': '(1)'}), '(sample_decoding[1, 1, 0, 0, :, :], axis=1)\n', (47187, 47230), True, 'import numpy as np\n'), ((47630, 47648), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (47646, 47648), True, 'import matplotlib.pyplot as plt\n'), ((47657, 47704), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""postle summary.pdf"""'], {'format': '"""pdf"""'}), "('postle summary.pdf', format='pdf')\n", (47668, 47704), True, 'import matplotlib.pyplot as plt\n'), ((47717, 47727), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (47725, 47727), True, 'import matplotlib.pyplot as plt\n'), ((48365, 48397), 'numpy.int_', 'np.int_', (['(trial_length_steps * dt)'], {}), '(trial_length_steps * dt)\n', (48372, 48397), True, 'import numpy as np\n'), ((48417, 48447), 'numpy.arange', 'np.arange', (['(0)', 'trial_length', 'dt'], {}), '(0, trial_length, dt)\n', (48426, 48447), True, 'import numpy as np\n'), ((48613, 48639), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(6, 4)'}), '(figsize=(6, 4))\n', (48623, 48639), True, 'import matplotlib.pyplot as plt\n'), ((48723, 48745), 'numpy.array', 'np.array', (['[0, 1, 2, 3]'], {}), '([0, 1, 2, 3])\n', (48731, 48745), True, 'import numpy as np\n'), ((49205, 49243), 'numpy.mean', 'np.mean', (['mean_resp[:, 0, :, :]'], {'axis': '(0)'}), '(mean_resp[:, 0, :, :], axis=0)\n', (49212, 49243), True, 'import numpy as np\n'), ((49258, 49267), 'numpy.max', 'np.max', (['s'], {}), '(s)\n', (49264, 49267), True, 'import numpy as np\n'), ((49619, 49657), 'numpy.mean', 'np.mean', (['spike_decode[:, 0, :]'], {'axis': '(1)'}), '(spike_decode[:, 0, :], axis=1)\n', (49626, 49657), True, 'import numpy as np\n'), ((49668, 49705), 'numpy.std', 'np.std', (['spike_decode[:, 0, :]'], {'axis': '(1)'}), '(spike_decode[:, 0, :], axis=1)\n', (49674, 49705), True, 'import numpy as np\n'), ((49799, 49842), 'numpy.mean', 'np.mean', (['spike_decode_test[:, 0, :]'], {'axis': '(1)'}), '(spike_decode_test[:, 0, :], axis=1)\n', (49806, 49842), True, 'import numpy as np\n'), ((49853, 49895), 'numpy.std', 'np.std', (['spike_decode_test[:, 0, :]'], {'axis': '(1)'}), '(spike_decode_test[:, 0, :], axis=1)\n', (49859, 49895), True, 'import numpy as np\n'), ((50142, 50180), 'numpy.mean', 'np.mean', (['spike_decode[:, 0, :]'], {'axis': '(1)'}), '(spike_decode[:, 0, :], axis=1)\n', (50149, 50180), True, 'import numpy as np\n'), ((50191, 50228), 'numpy.std', 'np.std', (['spike_decode[:, 0, :]'], {'axis': '(1)'}), '(spike_decode[:, 0, :], axis=1)\n', (50197, 50228), True, 'import numpy as np\n'), ((50322, 50367), 'numpy.mean', 'np.mean', (['synapse_decode_test[:, 0, :]'], {'axis': '(1)'}), '(synapse_decode_test[:, 0, :], axis=1)\n', (50329, 50367), True, 'import numpy as np\n'), ((50378, 50422), 'numpy.std', 'np.std', (['synapse_decode_test[:, 0, :]'], {'axis': '(1)'}), '(synapse_decode_test[:, 0, :], axis=1)\n', (50384, 50422), True, 'import numpy as np\n'), ((50738, 50748), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (50746, 50748), True, 'import matplotlib.pyplot as plt\n'), ((53873, 53905), 'numpy.mean', 'np.mean', (['sample_cat_pev1'], {'axis': '(1)'}), '(sample_cat_pev1, axis=1)\n', (53880, 53905), True, 'import numpy as np\n'), ((53934, 53966), 'numpy.mean', 'np.mean', (['sample_cat_pev2'], {'axis': '(1)'}), '(sample_cat_pev2, axis=1)\n', (53941, 53966), True, 'import numpy as np\n'), ((53999, 54035), 'numpy.mean', 'np.mean', (['sample_cat_stp_pev1'], {'axis': '(1)'}), '(sample_cat_stp_pev1, axis=1)\n', (54006, 54035), True, 'import numpy as np\n'), ((54068, 54104), 'numpy.mean', 'np.mean', (['sample_cat_stp_pev2'], {'axis': '(1)'}), '(sample_cat_stp_pev2, axis=1)\n', (54075, 54104), True, 'import numpy as np\n'), ((54149, 54193), 'numpy.mean', 'np.mean', (["svm_results1['sample_full']"], {'axis': '(1)'}), "(svm_results1['sample_full'], axis=1)\n", (54156, 54193), True, 'import numpy as np\n'), ((54238, 54282), 'numpy.mean', 'np.mean', (["svm_results2['sample_full']"], {'axis': '(1)'}), "(svm_results2['sample_full'], axis=1)\n", (54245, 54282), True, 'import numpy as np\n'), ((54331, 54379), 'numpy.mean', 'np.mean', (["svm_results1['sample_full_stp']"], {'axis': '(1)'}), "(svm_results1['sample_full_stp'], axis=1)\n", (54338, 54379), True, 'import numpy as np\n'), ((54428, 54476), 'numpy.mean', 'np.mean', (["svm_results2['sample_full_stp']"], {'axis': '(1)'}), "(svm_results2['sample_full_stp'], axis=1)\n", (54435, 54476), True, 'import numpy as np\n'), ((54606, 54625), 'numpy.where', 'np.where', (['(t == -500)'], {}), '(t == -500)\n', (54614, 54625), True, 'import numpy as np\n'), ((54625, 54641), 'numpy.where', 'np.where', (['(t == 0)'], {}), '(t == 0)\n', (54633, 54641), True, 'import numpy as np\n'), ((54640, 54658), 'numpy.where', 'np.where', (['(t == 500)'], {}), '(t == 500)\n', (54648, 54658), True, 'import numpy as np\n'), ((54657, 54676), 'numpy.where', 'np.where', (['(t == 1500)'], {}), '(t == 1500)\n', (54665, 54676), True, 'import numpy as np\n'), ((54705, 54751), 'numpy.arange', 'np.arange', (['(0)', '(200 + 500 + 1500 + 300 + 300)', 'dt'], {}), '(0, 200 + 500 + 1500 + 300 + 300, dt)\n', (54714, 54751), True, 'import numpy as np\n'), ((54754, 54794), 'numpy.arange', 'np.arange', (['(0)', '(200 + 500 + 250 + 2000)', 'dt'], {}), '(0, 200 + 500 + 250 + 2000, dt)\n', (54763, 54794), True, 'import numpy as np\n'), ((55043, 55085), 'numpy.mean', 'np.mean', (['mean_resp1[:, rule, :, :]'], {'axis': '(1)'}), '(mean_resp1[:, rule, :, :], axis=1)\n', (55050, 55085), True, 'import numpy as np\n'), ((55107, 55149), 'numpy.mean', 'np.mean', (['mean_resp2[:, rule, :, :]'], {'axis': '(1)'}), '(mean_resp2[:, rule, :, :], axis=1)\n', (55114, 55149), True, 'import numpy as np\n'), ((55218, 55246), 'numpy.sqrt', 'np.sqrt', (['mean_resp1.shape[0]'], {}), '(mean_resp1.shape[0])\n', (55225, 55246), True, 'import numpy as np\n'), ((55311, 55339), 'numpy.sqrt', 'np.sqrt', (['mean_resp1.shape[0]'], {}), '(mean_resp1.shape[0])\n', (55318, 55339), True, 'import numpy as np\n'), ((56154, 56193), 'numpy.std', 'np.std', (['sample_pev1[:, rule, :]'], {'axis': '(0)'}), '(sample_pev1[:, rule, :], axis=0)\n', (56160, 56193), True, 'import numpy as np\n'), ((56191, 56220), 'numpy.sqrt', 'np.sqrt', (['sample_pev1.shape[0]'], {}), '(sample_pev1.shape[0])\n', (56198, 56220), True, 'import numpy as np\n'), ((56231, 56270), 'numpy.std', 'np.std', (['sample_pev2[:, rule, :]'], {'axis': '(0)'}), '(sample_pev2[:, rule, :], axis=0)\n', (56237, 56270), True, 'import numpy as np\n'), ((56268, 56297), 'numpy.sqrt', 'np.sqrt', (['sample_pev1.shape[0]'], {}), '(sample_pev1.shape[0])\n', (56275, 56297), True, 'import numpy as np\n'), ((57290, 57303), 'numpy.isnan', 'np.isnan', (['se1'], {}), '(se1)\n', (57298, 57303), True, 'import numpy as np\n'), ((57317, 57330), 'numpy.isnan', 'np.isnan', (['se2'], {}), '(se2)\n', (57325, 57330), True, 'import numpy as np\n'), ((58726, 58769), 'numpy.std', 'np.std', (['sample_stp_pev2[:, rule, :]'], {'axis': '(0)'}), '(sample_stp_pev2[:, rule, :], axis=0)\n', (58732, 58769), True, 'import numpy as np\n'), ((58767, 58796), 'numpy.sqrt', 'np.sqrt', (['sample_pev1.shape[0]'], {}), '(sample_pev1.shape[0])\n', (58774, 58796), True, 'import numpy as np\n'), ((59481, 59494), 'numpy.isnan', 'np.isnan', (['se2'], {}), '(se2)\n', (59489, 59494), True, 'import numpy as np\n'), ((61391, 61410), 'numpy.where', 'np.where', (['(t == -500)'], {}), '(t == -500)\n', (61399, 61410), True, 'import numpy as np\n'), ((61410, 61426), 'numpy.where', 'np.where', (['(t == 0)'], {}), '(t == 0)\n', (61418, 61426), True, 'import numpy as np\n'), ((61425, 61443), 'numpy.where', 'np.where', (['(t == 500)'], {}), '(t == 500)\n', (61433, 61443), True, 'import numpy as np\n'), ((61442, 61461), 'numpy.where', 'np.where', (['(t == 1500)'], {}), '(t == 1500)\n', (61450, 61461), True, 'import numpy as np\n'), ((61485, 61531), 'numpy.arange', 'np.arange', (['(0)', '(200 + 500 + 1500 + 300 + 300)', 'dt'], {}), '(0, 200 + 500 + 1500 + 300 + 300, dt)\n', (61494, 61531), True, 'import numpy as np\n'), ((62012, 62040), 'numpy.sqrt', 'np.sqrt', (['mean_resp1.shape[0]'], {}), '(mean_resp1.shape[0])\n', (62019, 62040), True, 'import numpy as np\n'), ((62118, 62146), 'numpy.sqrt', 'np.sqrt', (['mean_resp1.shape[0]'], {}), '(mean_resp1.shape[0])\n', (62125, 62146), True, 'import numpy as np\n'), ((62916, 62941), 'numpy.std', 'np.std', (['rule_pev1'], {'axis': '(0)'}), '(rule_pev1, axis=0)\n', (62922, 62941), True, 'import numpy as np\n'), ((62941, 62970), 'numpy.sqrt', 'np.sqrt', (['sample_pev1.shape[0]'], {}), '(sample_pev1.shape[0])\n', (62948, 62970), True, 'import numpy as np\n'), ((62981, 63006), 'numpy.std', 'np.std', (['rule_pev2'], {'axis': '(0)'}), '(rule_pev2, axis=0)\n', (62987, 63006), True, 'import numpy as np\n'), ((63006, 63035), 'numpy.sqrt', 'np.sqrt', (['sample_pev1.shape[0]'], {}), '(sample_pev1.shape[0])\n', (63013, 63035), True, 'import numpy as np\n'), ((63565, 63605), 'numpy.mean', 'np.mean', (['sample_pev1[:, rule, :]'], {'axis': '(0)'}), '(sample_pev1[:, rule, :], axis=0)\n', (63572, 63605), True, 'import numpy as np\n'), ((63616, 63656), 'numpy.mean', 'np.mean', (['sample_pev2[:, rule, :]'], {'axis': '(0)'}), '(sample_pev2[:, rule, :], axis=0)\n', (63623, 63656), True, 'import numpy as np\n'), ((64353, 64409), 'numpy.mean', 'np.mean', (["svm_results1['sample_full'][:, rule, :]"], {'axis': '(1)'}), "(svm_results1['sample_full'][:, rule, :], axis=1)\n", (64360, 64409), True, 'import numpy as np\n'), ((64420, 64476), 'numpy.mean', 'np.mean', (["svm_results2['sample_full'][:, rule, :]"], {'axis': '(1)'}), "(svm_results2['sample_full'][:, rule, :], axis=1)\n", (64427, 64476), True, 'import numpy as np\n'), ((64488, 64543), 'numpy.std', 'np.std', (["svm_results1['sample_full'][:, rule, :]"], {'axis': '(1)'}), "(svm_results1['sample_full'][:, rule, :], axis=1)\n", (64494, 64543), True, 'import numpy as np\n'), ((64555, 64610), 'numpy.std', 'np.std', (["svm_results2['sample_full'][:, rule, :]"], {'axis': '(1)'}), "(svm_results2['sample_full'][:, rule, :], axis=1)\n", (64561, 64610), True, 'import numpy as np\n'), ((65218, 65262), 'numpy.mean', 'np.mean', (['sample_stp_pev1[:, rule, :]'], {'axis': '(0)'}), '(sample_stp_pev1[:, rule, :], axis=0)\n', (65225, 65262), True, 'import numpy as np\n'), ((65273, 65317), 'numpy.mean', 'np.mean', (['sample_stp_pev2[:, rule, :]'], {'axis': '(0)'}), '(sample_stp_pev2[:, rule, :], axis=0)\n', (65280, 65317), True, 'import numpy as np\n'), ((66024, 66084), 'numpy.mean', 'np.mean', (["svm_results1['sample_full_stp'][:, rule, :]"], {'axis': '(1)'}), "(svm_results1['sample_full_stp'][:, rule, :], axis=1)\n", (66031, 66084), True, 'import numpy as np\n'), ((66095, 66155), 'numpy.mean', 'np.mean', (["svm_results2['sample_full_stp'][:, rule, :]"], {'axis': '(1)'}), "(svm_results2['sample_full_stp'][:, rule, :], axis=1)\n", (66102, 66155), True, 'import numpy as np\n'), ((66167, 66226), 'numpy.std', 'np.std', (["svm_results1['sample_full_stp'][:, rule, :]"], {'axis': '(1)'}), "(svm_results1['sample_full_stp'][:, rule, :], axis=1)\n", (66173, 66226), True, 'import numpy as np\n'), ((66238, 66297), 'numpy.std', 'np.std', (["svm_results2['sample_full_stp'][:, rule, :]"], {'axis': '(1)'}), "(svm_results2['sample_full_stp'][:, rule, :], axis=1)\n", (66244, 66297), True, 'import numpy as np\n'), ((67093, 67121), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 10)'}), '(figsize=(10, 10))\n', (67103, 67121), True, 'import matplotlib.pyplot as plt\n'), ((67167, 67194), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(8, 10)'}), '(figsize=(8, 10))\n', (67177, 67194), True, 'import matplotlib.pyplot as plt\n'), ((70096, 70140), 'numpy.mean', 'np.mean', (["svm_results1['sample_full']"], {'axis': '(1)'}), "(svm_results1['sample_full'], axis=1)\n", (70103, 70140), True, 'import numpy as np\n'), ((70178, 70222), 'numpy.mean', 'np.mean', (["svm_results2['sample_full']"], {'axis': '(1)'}), "(svm_results2['sample_full'], axis=1)\n", (70185, 70222), True, 'import numpy as np\n'), ((70264, 70312), 'numpy.mean', 'np.mean', (["svm_results1['sample_full_stp']"], {'axis': '(1)'}), "(svm_results1['sample_full_stp'], axis=1)\n", (70271, 70312), True, 'import numpy as np\n'), ((70354, 70402), 'numpy.mean', 'np.mean', (["svm_results2['sample_full_stp']"], {'axis': '(1)'}), "(svm_results2['sample_full_stp'], axis=1)\n", (70361, 70402), True, 'import numpy as np\n'), ((70450, 70498), 'numpy.squeeze', 'np.squeeze', (["svm_results1['sample_full'][:, 0, :]"], {}), "(svm_results1['sample_full'][:, 0, :])\n", (70460, 70498), True, 'import numpy as np\n'), ((70535, 70583), 'numpy.squeeze', 'np.squeeze', (["svm_results2['sample_full'][:, 0, :]"], {}), "(svm_results2['sample_full'][:, 0, :])\n", (70545, 70583), True, 'import numpy as np\n'), ((70624, 70676), 'numpy.squeeze', 'np.squeeze', (["svm_results1['sample_full_stp'][:, 0, :]"], {}), "(svm_results1['sample_full_stp'][:, 0, :])\n", (70634, 70676), True, 'import numpy as np\n'), ((70717, 70769), 'numpy.squeeze', 'np.squeeze', (["svm_results2['sample_full_stp'][:, 0, :]"], {}), "(svm_results2['sample_full_stp'][:, 0, :])\n", (70727, 70769), True, 'import numpy as np\n'), ((72108, 72127), 'numpy.where', 'np.where', (['(t == -500)'], {}), '(t == -500)\n', (72116, 72127), True, 'import numpy as np\n'), ((72127, 72143), 'numpy.where', 'np.where', (['(t == 0)'], {}), '(t == 0)\n', (72135, 72143), True, 'import numpy as np\n'), ((72142, 72160), 'numpy.where', 'np.where', (['(t == 500)'], {}), '(t == 500)\n', (72150, 72160), True, 'import numpy as np\n'), ((72159, 72178), 'numpy.where', 'np.where', (['(t == 1500)'], {}), '(t == 1500)\n', (72167, 72178), True, 'import numpy as np\n'), ((74085, 74128), 'numpy.mean', 'np.mean', (['spike_decoding[:, :, d, :]'], {'axis': '(3)'}), '(spike_decoding[:, :, d, :], axis=3)\n', (74092, 74128), True, 'import numpy as np\n'), ((74816, 74872), 'numpy.mean', 'np.mean', (['spike_decoding[j, ind_example[j], :, :]'], {'axis': '(1)'}), '(spike_decoding[j, ind_example[j], :, :], axis=1)\n', (74823, 74872), True, 'import numpy as np\n'), ((74882, 74937), 'numpy.std', 'np.std', (['spike_decoding[j, ind_example[j], :, :]'], {'axis': '(1)'}), '(spike_decoding[j, ind_example[j], :, :], axis=1)\n', (74888, 74937), True, 'import numpy as np\n'), ((75030, 75088), 'numpy.mean', 'np.mean', (['synapse_decoding[j, ind_example[j], :, :]'], {'axis': '(1)'}), '(synapse_decoding[j, ind_example[j], :, :], axis=1)\n', (75037, 75088), True, 'import numpy as np\n'), ((75098, 75155), 'numpy.std', 'np.std', (['synapse_decoding[j, ind_example[j], :, :]'], {'axis': '(1)'}), '(synapse_decoding[j, ind_example[j], :, :], axis=1)\n', (75104, 75155), True, 'import numpy as np\n'), ((77152, 77211), 'numpy.mean', 'np.mean', (['synapse_decoding[j, ind_good_models, :, :]'], {'axis': '(2)'}), '(synapse_decoding[j, ind_good_models, :, :], axis=2)\n', (77159, 77211), True, 'import numpy as np\n'), ((81645, 81664), 'numpy.where', 'np.where', (['(t == -500)'], {}), '(t == -500)\n', (81653, 81664), True, 'import numpy as np\n'), ((81664, 81680), 'numpy.where', 'np.where', (['(t == 0)'], {}), '(t == 0)\n', (81672, 81680), True, 'import numpy as np\n'), ((81679, 81697), 'numpy.where', 'np.where', (['(t == 500)'], {}), '(t == 500)\n', (81687, 81697), True, 'import numpy as np\n'), ((81696, 81715), 'numpy.where', 'np.where', (['(t == 1500)'], {}), '(t == 1500)\n', (81704, 81715), True, 'import numpy as np\n'), ((85174, 85217), 'numpy.mean', 'np.mean', (['spike_decoding[:, :, d, :]'], {'axis': '(3)'}), '(spike_decoding[:, :, d, :], axis=3)\n', (85181, 85217), True, 'import numpy as np\n'), ((85785, 85829), 'numpy.argsort', 'np.argsort', (['delay_accuracy[j, ind_good_perf]'], {}), '(delay_accuracy[j, ind_good_perf])\n', (85795, 85829), True, 'import numpy as np\n'), ((91109, 91121), 'numpy.sum', 'np.sum', (['mask'], {}), '(mask)\n', (91115, 91121), True, 'import numpy as np\n'), ((812, 898), 'numpy.reshape', 'np.reshape', (['self.syn_x', '(num_neurons, trial_length, num_blocks * trials_per_block)'], {}), '(self.syn_x, (num_neurons, trial_length, num_blocks *\n trials_per_block))\n', (822, 898), True, 'import numpy as np\n'), ((1225, 1311), 'numpy.reshape', 'np.reshape', (['self.syn_u', '(num_neurons, trial_length, num_blocks * trials_per_block)'], {}), '(self.syn_u, (num_neurons, trial_length, num_blocks *\n trials_per_block))\n', (1235, 1311), True, 'import numpy as np\n'), ((1826, 1871), 'numpy.transpose', 'np.transpose', (['self.desired_outputs', '(2, 0, 1)'], {}), '(self.desired_outputs, (2, 0, 1))\n', (1838, 1871), True, 'import numpy as np\n'), ((4593, 4668), 'numpy.where', 'np.where', (['((self.rule == self.possible_rules[rule]) * (self.sample_dir == d))'], {}), '((self.rule == self.possible_rules[rule]) * (self.sample_dir == d))\n', (4601, 4668), True, 'import numpy as np\n'), ((4770, 4816), 'numpy.mean', 'np.mean', (['self.rnn_inputs[:, :, ind[0]]'], {'axis': '(2)'}), '(self.rnn_inputs[:, :, ind[0]], axis=2)\n', (4777, 4816), True, 'import numpy as np\n'), ((4849, 4882), 'numpy.mean', 'np.mean', (['s[:, sample_rng]'], {'axis': '(1)'}), '(s[:, sample_rng], axis=1)\n', (4856, 4882), True, 'import numpy as np\n'), ((7639, 7701), 'numpy.mean', 'np.mean', (['(self.syn_u[:, :, ind] * self.syn_x[:, :, ind])'], {'axis': '(2)'}), '(self.syn_u[:, :, ind] * self.syn_x[:, :, ind], axis=2)\n', (7646, 7701), True, 'import numpy as np\n'), ((7745, 7766), 'numpy.diag', 'np.diag', (['self.EI_list'], {}), '(self.EI_list)\n', (7752, 7766), True, 'import numpy as np\n'), ((16160, 16178), 'numpy.zeros', 'np.zeros', (['num_lags'], {}), '(num_lags)\n', (16168, 16178), True, 'import numpy as np\n'), ((22167, 22185), 'numpy.sum', 'np.sum', (['(conds == i)'], {}), '(conds == i)\n', (22173, 22185), True, 'import numpy as np\n'), ((22213, 22231), 'numpy.min', 'np.min', (['num_trials'], {}), '(num_trials)\n', (22219, 22231), True, 'import numpy as np\n'), ((23385, 23401), 'numpy.unique', 'np.unique', (['conds'], {}), '(conds)\n', (23394, 23401), True, 'import numpy as np\n'), ((23415, 23428), 'numpy.squeeze', 'np.squeeze', (['y'], {}), '(y)\n', (23425, 23428), True, 'import numpy as np\n'), ((26973, 26983), 'numpy.mean', 'np.mean', (['x'], {}), '(x)\n', (26980, 26983), True, 'import numpy as np\n'), ((27119, 27139), 'numpy.where', 'np.where', (['(conds == i)'], {}), '(conds == i)\n', (27127, 27139), True, 'import numpy as np\n'), ((27198, 27217), 'numpy.mean', 'np.mean', (['xr[ind[0]]'], {}), '(xr[ind[0]])\n', (27205, 27217), True, 'import numpy as np\n'), ((27257, 27275), 'numpy.sum', 'np.sum', (['(countx > 0)'], {}), '(countx > 0)\n', (27263, 27275), True, 'import numpy as np\n'), ((27405, 27426), 'numpy.transpose', 'np.transpose', (['(xc ** 2)'], {}), '(xc ** 2)\n', (27417, 27426), True, 'import numpy as np\n'), ((27475, 27496), 'numpy.transpose', 'np.transpose', (['(xr - gm)'], {}), '(xr - gm)\n', (27487, 27496), True, 'import numpy as np\n'), ((29727, 29764), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(8, 2 * num_rows)'}), '(figsize=(8, 2 * num_rows))\n', (29737, 29764), True, 'import matplotlib.pyplot as plt\n'), ((29924, 29946), 'numpy.array', 'np.array', (['[0, 1, 2, 3]'], {}), '([0, 1, 2, 3])\n', (29932, 29946), True, 'import numpy as np\n'), ((32550, 32566), 'numpy.max', 'np.max', (['rule_pev'], {}), '(rule_pev)\n', (32556, 32566), True, 'import numpy as np\n'), ((33534, 33575), 'numpy.mean', 'np.mean', (['mean_resp[:, rule, :, :]'], {'axis': '(0)'}), '(mean_resp[:, rule, :, :], axis=0)\n', (33541, 33575), True, 'import numpy as np\n'), ((33594, 33603), 'numpy.max', 'np.max', (['s'], {}), '(s)\n', (33600, 33603), True, 'import numpy as np\n'), ((36069, 36083), 'matplotlib.pyplot.hold', 'plt.hold', (['(True)'], {}), '(True)\n', (36077, 36083), True, 'import matplotlib.pyplot as plt\n'), ((36100, 36136), 'numpy.mean', 'np.mean', (['sample_pev[:, 0, :]'], {'axis': '(0)'}), '(sample_pev[:, 0, :], axis=0)\n', (36107, 36136), True, 'import numpy as np\n'), ((36268, 36277), 'numpy.max', 'np.max', (['u'], {}), '(u)\n', (36274, 36277), True, 'import numpy as np\n'), ((36357, 36393), 'numpy.mean', 'np.mean', (['sample_pev[:, 1, :]'], {'axis': '(0)'}), '(sample_pev[:, 1, :], axis=0)\n', (36364, 36393), True, 'import numpy as np\n'), ((36524, 36533), 'numpy.max', 'np.max', (['u'], {}), '(u)\n', (36530, 36533), True, 'import numpy as np\n'), ((36559, 36592), 'numpy.max', 'np.max', (['[sample_max, sample_max1]'], {}), '([sample_max, sample_max1])\n', (36565, 36592), True, 'import numpy as np\n'), ((36749, 36788), 'numpy.mean', 'np.mean', (['sample_pev[:, rule, :]'], {'axis': '(0)'}), '(sample_pev[:, rule, :], axis=0)\n', (36756, 36788), True, 'import numpy as np\n'), ((36922, 36931), 'numpy.max', 'np.max', (['u'], {}), '(u)\n', (36928, 36931), True, 'import numpy as np\n'), ((37360, 37398), 'numpy.mean', 'np.mean', (['spike_decode[:, 0, :]'], {'axis': '(1)'}), '(spike_decode[:, 0, :], axis=1)\n', (37367, 37398), True, 'import numpy as np\n'), ((37413, 37450), 'numpy.std', 'np.std', (['spike_decode[:, 0, :]'], {'axis': '(1)'}), '(spike_decode[:, 0, :], axis=1)\n', (37419, 37450), True, 'import numpy as np\n'), ((37556, 37594), 'numpy.mean', 'np.mean', (['spike_decode[:, 1, :]'], {'axis': '(1)'}), '(spike_decode[:, 1, :], axis=1)\n', (37563, 37594), True, 'import numpy as np\n'), ((37609, 37646), 'numpy.std', 'np.std', (['spike_decode[:, 1, :]'], {'axis': '(1)'}), '(spike_decode[:, 1, :], axis=1)\n', (37615, 37646), True, 'import numpy as np\n'), ((37910, 37951), 'numpy.mean', 'np.mean', (['spike_decode[:, rule, :]'], {'axis': '(1)'}), '(spike_decode[:, rule, :], axis=1)\n', (37917, 37951), True, 'import numpy as np\n'), ((37966, 38006), 'numpy.std', 'np.std', (['spike_decode[:, rule, :]'], {'axis': '(1)'}), '(spike_decode[:, rule, :], axis=1)\n', (37972, 38006), True, 'import numpy as np\n'), ((38112, 38158), 'numpy.mean', 'np.mean', (['spike_decode_test[:, rule, :]'], {'axis': '(1)'}), '(spike_decode_test[:, rule, :], axis=1)\n', (38119, 38158), True, 'import numpy as np\n'), ((38173, 38218), 'numpy.std', 'np.std', (['spike_decode_test[:, rule, :]'], {'axis': '(1)'}), '(spike_decode_test[:, rule, :], axis=1)\n', (38179, 38218), True, 'import numpy as np\n'), ((43851, 43861), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (43859, 43861), True, 'import matplotlib.pyplot as plt\n'), ((44312, 44331), 'numpy.where', 'np.where', (['(t == -500)'], {}), '(t == -500)\n', (44320, 44331), True, 'import numpy as np\n'), ((44331, 44347), 'numpy.where', 'np.where', (['(t == 0)'], {}), '(t == 0)\n', (44339, 44347), True, 'import numpy as np\n'), ((44347, 44365), 'numpy.where', 'np.where', (['(t == 500)'], {}), '(t == 500)\n', (44355, 44365), True, 'import numpy as np\n'), ((44365, 44384), 'numpy.where', 'np.where', (['(t == 1000)'], {}), '(t == 1000)\n', (44373, 44384), True, 'import numpy as np\n'), ((44384, 44403), 'numpy.where', 'np.where', (['(t == 1500)'], {}), '(t == 1500)\n', (44392, 44403), True, 'import numpy as np\n'), ((44403, 44422), 'numpy.where', 'np.where', (['(t == 2000)'], {}), '(t == 2000)\n', (44411, 44422), True, 'import numpy as np\n'), ((44422, 44441), 'numpy.where', 'np.where', (['(t == 2500)'], {}), '(t == 2500)\n', (44430, 44441), True, 'import numpy as np\n'), ((48531, 48550), 'numpy.where', 'np.where', (['(t == -500)'], {}), '(t == -500)\n', (48539, 48550), True, 'import numpy as np\n'), ((48550, 48566), 'numpy.where', 'np.where', (['(t == 0)'], {}), '(t == 0)\n', (48558, 48566), True, 'import numpy as np\n'), ((48565, 48583), 'numpy.where', 'np.where', (['(t == 500)'], {}), '(t == 500)\n', (48573, 48583), True, 'import numpy as np\n'), ((48582, 48601), 'numpy.where', 'np.where', (['(t == 1500)'], {}), '(t == 1500)\n', (48590, 48601), True, 'import numpy as np\n'), ((50653, 50671), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (50669, 50671), True, 'import matplotlib.pyplot as plt\n'), ((50684, 50729), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""ABBA summary.pdf"""'], {'format': '"""pdf"""'}), "('ABBA summary.pdf', format='pdf')\n", (50695, 50729), True, 'import matplotlib.pyplot as plt\n'), ((54835, 54854), 'numpy.where', 'np.where', (['(t == -500)'], {}), '(t == -500)\n', (54843, 54854), True, 'import numpy as np\n'), ((54854, 54870), 'numpy.where', 'np.where', (['(t == 0)'], {}), '(t == 0)\n', (54862, 54870), True, 'import numpy as np\n'), ((54869, 54887), 'numpy.where', 'np.where', (['(t == 500)'], {}), '(t == 500)\n', (54877, 54887), True, 'import numpy as np\n'), ((54886, 54905), 'numpy.where', 'np.where', (['(t == 1000)'], {}), '(t == 1000)\n', (54894, 54905), True, 'import numpy as np\n'), ((54904, 54923), 'numpy.where', 'np.where', (['(t == 1500)'], {}), '(t == 1500)\n', (54912, 54923), True, 'import numpy as np\n'), ((54922, 54941), 'numpy.where', 'np.where', (['(t == 2000)'], {}), '(t == 2000)\n', (54930, 54941), True, 'import numpy as np\n'), ((54941, 54960), 'numpy.where', 'np.where', (['(t == 2500)'], {}), '(t == 2500)\n', (54949, 54960), True, 'import numpy as np\n'), ((55171, 55213), 'numpy.mean', 'np.mean', (['mean_resp1[:, rule, :, :]'], {'axis': '(1)'}), '(mean_resp1[:, rule, :, :], axis=1)\n', (55178, 55213), True, 'import numpy as np\n'), ((55264, 55306), 'numpy.mean', 'np.mean', (['mean_resp2[:, rule, :, :]'], {'axis': '(1)'}), '(mean_resp2[:, rule, :, :], axis=1)\n', (55271, 55306), True, 'import numpy as np\n'), ((61573, 61592), 'numpy.where', 'np.where', (['(t == -500)'], {}), '(t == -500)\n', (61581, 61592), True, 'import numpy as np\n'), ((61592, 61608), 'numpy.where', 'np.where', (['(t == 0)'], {}), '(t == 0)\n', (61600, 61608), True, 'import numpy as np\n'), ((61607, 61625), 'numpy.where', 'np.where', (['(t == 300)'], {}), '(t == 300)\n', (61615, 61625), True, 'import numpy as np\n'), ((61624, 61642), 'numpy.where', 'np.where', (['(t == 600)'], {}), '(t == 600)\n', (61632, 61642), True, 'import numpy as np\n'), ((61641, 61659), 'numpy.where', 'np.where', (['(t == 900)'], {}), '(t == 900)\n', (61649, 61659), True, 'import numpy as np\n'), ((61658, 61677), 'numpy.where', 'np.where', (['(t == 1200)'], {}), '(t == 1200)\n', (61666, 61677), True, 'import numpy as np\n'), ((61677, 61696), 'numpy.where', 'np.where', (['(t == 1500)'], {}), '(t == 1500)\n', (61685, 61696), True, 'import numpy as np\n'), ((61696, 61715), 'numpy.where', 'np.where', (['(t == 1800)'], {}), '(t == 1800)\n', (61704, 61715), True, 'import numpy as np\n'), ((61806, 61845), 'numpy.mean', 'np.mean', (['mean_resp1[:, :, :, :]'], {'axis': '(1)'}), '(mean_resp1[:, :, :, :], axis=1)\n', (61813, 61845), True, 'import numpy as np\n'), ((61883, 61922), 'numpy.mean', 'np.mean', (['mean_resp2[:, :, :, :]'], {'axis': '(1)'}), '(mean_resp2[:, :, :, :], axis=1)\n', (61890, 61922), True, 'import numpy as np\n'), ((63668, 63707), 'numpy.std', 'np.std', (['sample_pev1[:, rule, :]'], {'axis': '(0)'}), '(sample_pev1[:, rule, :], axis=0)\n', (63674, 63707), True, 'import numpy as np\n'), ((63705, 63734), 'numpy.sqrt', 'np.sqrt', (['sample_pev1.shape[0]'], {}), '(sample_pev1.shape[0])\n', (63712, 63734), True, 'import numpy as np\n'), ((63749, 63788), 'numpy.std', 'np.std', (['sample_pev2[:, rule, :]'], {'axis': '(0)'}), '(sample_pev2[:, rule, :], axis=0)\n', (63755, 63788), True, 'import numpy as np\n'), ((63786, 63815), 'numpy.sqrt', 'np.sqrt', (['sample_pev1.shape[0]'], {}), '(sample_pev1.shape[0])\n', (63793, 63815), True, 'import numpy as np\n'), ((64620, 64633), 'numpy.isnan', 'np.isnan', (['se1'], {}), '(se1)\n', (64628, 64633), True, 'import numpy as np\n'), ((64651, 64664), 'numpy.isnan', 'np.isnan', (['se2'], {}), '(se2)\n', (64659, 64664), True, 'import numpy as np\n'), ((65329, 65372), 'numpy.std', 'np.std', (['sample_stp_pev1[:, rule, :]'], {'axis': '(0)'}), '(sample_stp_pev1[:, rule, :], axis=0)\n', (65335, 65372), True, 'import numpy as np\n'), ((65370, 65399), 'numpy.sqrt', 'np.sqrt', (['sample_pev1.shape[0]'], {}), '(sample_pev1.shape[0])\n', (65377, 65399), True, 'import numpy as np\n'), ((65414, 65457), 'numpy.std', 'np.std', (['sample_stp_pev2[:, rule, :]'], {'axis': '(0)'}), '(sample_stp_pev2[:, rule, :], axis=0)\n', (65420, 65457), True, 'import numpy as np\n'), ((65455, 65484), 'numpy.sqrt', 'np.sqrt', (['sample_pev1.shape[0]'], {}), '(sample_pev1.shape[0])\n', (65462, 65484), True, 'import numpy as np\n'), ((66307, 66320), 'numpy.isnan', 'np.isnan', (['se1'], {}), '(se1)\n', (66315, 66320), True, 'import numpy as np\n'), ((66338, 66351), 'numpy.isnan', 'np.isnan', (['se2'], {}), '(se2)\n', (66346, 66351), True, 'import numpy as np\n'), ((73761, 73815), 'contrib_to_behavior.Analysis', 'contrib_to_behavior.Analysis', (['f'], {'old_format': 'old_format'}), '(f, old_format=old_format)\n', (73789, 73815), False, 'import contrib_to_behavior\n'), ((74204, 74230), 'numpy.where', 'np.where', (['(perf[j, :] > 0.9)'], {}), '(perf[j, :] > 0.9)\n', (74212, 74230), True, 'import numpy as np\n'), ((74252, 74296), 'numpy.argsort', 'np.argsort', (['delay_accuracy[j, ind_good_perf]'], {}), '(delay_accuracy[j, ind_good_perf])\n', (74262, 74296), True, 'import numpy as np\n'), ((75836, 75863), 'numpy.where', 'np.where', (['(perf[j, :] > 0.85)'], {}), '(perf[j, :] > 0.85)\n', (75844, 75863), True, 'import numpy as np\n'), ((75924, 75981), 'numpy.mean', 'np.mean', (['spike_decoding[j, ind_good_models, :, :]'], {'axis': '(2)'}), '(spike_decoding[j, ind_good_models, :, :], axis=2)\n', (75931, 75981), True, 'import numpy as np\n'), ((76202, 76261), 'numpy.mean', 'np.mean', (['synapse_decoding[j, ind_good_models, :, :]'], {'axis': '(2)'}), '(synapse_decoding[j, ind_good_models, :, :], axis=2)\n', (76209, 76261), True, 'import numpy as np\n'), ((77071, 77099), 'numpy.where', 'np.where', (['(perf[j, :] > 0.975)'], {}), '(perf[j, :] > 0.975)\n', (77079, 77099), True, 'import numpy as np\n'), ((80739, 80789), 'numpy.mean', 'np.mean', (['spike_decode[delay_start:delay_end, 0, :]'], {}), '(spike_decode[delay_start:delay_end, 0, :])\n', (80746, 80789), True, 'import numpy as np\n'), ((81182, 81208), 'numpy.where', 'np.where', (['(perf[i, :] > 0.9)'], {}), '(perf[i, :] > 0.9)\n', (81190, 81208), True, 'import numpy as np\n'), ((85728, 85763), 'numpy.where', 'np.where', (['(perf_combined[j, :] > 0.9)'], {}), '(perf_combined[j, :] > 0.9)\n', (85736, 85763), True, 'import numpy as np\n'), ((86289, 86348), 'numpy.mean', 'np.mean', (['spike_decoding[j, ind_example[j, i], :, :]'], {'axis': '(1)'}), '(spike_decoding[j, ind_example[j, i], :, :], axis=1)\n', (86296, 86348), True, 'import numpy as np\n'), ((86361, 86419), 'numpy.std', 'np.std', (['spike_decoding[j, ind_example[j, i], :, :]'], {'axis': '(1)'}), '(spike_decoding[j, ind_example[j, i], :, :], axis=1)\n', (86367, 86419), True, 'import numpy as np\n'), ((86523, 86584), 'numpy.mean', 'np.mean', (['synapse_decoding[j, ind_example[j, i], :, :]'], {'axis': '(1)'}), '(synapse_decoding[j, ind_example[j, i], :, :], axis=1)\n', (86530, 86584), True, 'import numpy as np\n'), ((86597, 86657), 'numpy.std', 'np.std', (['synapse_decoding[j, ind_example[j, i], :, :]'], {'axis': '(1)'}), '(synapse_decoding[j, ind_example[j, i], :, :], axis=1)\n', (86603, 86657), True, 'import numpy as np\n'), ((86883, 86946), 'numpy.mean', 'np.mean', (['spike_decoding[j + 1, ind_example[j, i], :, :]'], {'axis': '(1)'}), '(spike_decoding[j + 1, ind_example[j, i], :, :], axis=1)\n', (86890, 86946), True, 'import numpy as np\n'), ((86957, 87019), 'numpy.std', 'np.std', (['spike_decoding[j + 1, ind_example[j, i], :, :]'], {'axis': '(1)'}), '(spike_decoding[j + 1, ind_example[j, i], :, :], axis=1)\n', (86963, 87019), True, 'import numpy as np\n'), ((87121, 87186), 'numpy.mean', 'np.mean', (['synapse_decoding[j + 1, ind_example[j, i], :, :]'], {'axis': '(1)'}), '(synapse_decoding[j + 1, ind_example[j, i], :, :], axis=1)\n', (87128, 87186), True, 'import numpy as np\n'), ((87197, 87261), 'numpy.std', 'np.std', (['synapse_decoding[j + 1, ind_example[j, i], :, :]'], {'axis': '(1)'}), '(synapse_decoding[j + 1, ind_example[j, i], :, :], axis=1)\n', (87203, 87261), True, 'import numpy as np\n'), ((88131, 88157), 'numpy.where', 'np.where', (['(perf[j, :] > 0.9)'], {}), '(perf[j, :] > 0.9)\n', (88139, 88157), True, 'import numpy as np\n'), ((88993, 89019), 'numpy.where', 'np.where', (['(perf[j, :] > 0.9)'], {}), '(perf[j, :] > 0.9)\n', (89001, 89019), True, 'import numpy as np\n'), ((89846, 89872), 'numpy.where', 'np.where', (['(perf[j, :] > 0.9)'], {}), '(perf[j, :] > 0.9)\n', (89854, 89872), True, 'import numpy as np\n'), ((5974, 6028), 'numpy.linalg.lstsq', 'np.linalg.lstsq', (['sample_dir', 'self.rnn_outputs[n, t, :]'], {}), '(sample_dir, self.rnn_outputs[n, t, :])\n', (5989, 6028), True, 'import numpy as np\n'), ((6129, 6151), 'numpy.mean', 'np.mean', (['(pred_err ** 2)'], {}), '(pred_err ** 2)\n', (6136, 6151), True, 'import numpy as np\n'), ((6181, 6214), 'numpy.var', 'np.var', (['self.rnn_outputs[n, t, :]'], {}), '(self.rnn_outputs[n, t, :])\n', (6187, 6214), True, 'import numpy as np\n'), ((6310, 6338), 'numpy.arctan2', 'np.arctan2', (['h[0][2]', 'h[0][1]'], {}), '(h[0][2], h[0][1])\n', (6320, 6338), True, 'import numpy as np\n'), ((6372, 6408), 'numpy.sqrt', 'np.sqrt', (['(h[0][0] ** 2 + h[0][1] ** 2)'], {}), '(h[0][0] ** 2 + h[0][1] ** 2)\n', (6379, 6408), True, 'import numpy as np\n'), ((7513, 7612), 'numpy.where', 'np.where', (['((self.rule == self.possible_rules[rule]) * (self.sample_dir == d) * (self.\n match == 1))'], {}), '((self.rule == self.possible_rules[rule]) * (self.sample_dir == d) *\n (self.match == 1))\n', (7521, 7612), True, 'import numpy as np\n'), ((7794, 7819), 'numpy.maximum', 'np.maximum', (['(0)', 'self.W_rnn'], {}), '(0, self.W_rnn)\n', (7804, 7819), True, 'import numpy as np\n'), ((8764, 8860), 'numpy.mean', 'np.mean', (['(self.syn_u[:, :, ind] * self.syn_x[:, :, ind] * self.rnn_outputs[:, :, ind])'], {'axis': '(2)'}), '(self.syn_u[:, :, ind] * self.syn_x[:, :, ind] * self.rnn_outputs[:,\n :, ind], axis=2)\n', (8771, 8860), True, 'import numpy as np\n'), ((9828, 9855), 'numpy.int_', 'np.int_', (['self.sample_dir[i]'], {}), '(self.sample_dir[i])\n', (9835, 9855), True, 'import numpy as np\n'), ((9876, 9898), 'numpy.int_', 'np.int_', (['self.match[i]'], {}), '(self.match[i])\n', (9883, 9898), True, 'import numpy as np\n'), ((13626, 13655), 'numpy.ones_like', 'np.ones_like', (['self.sample_dir'], {}), '(self.sample_dir)\n', (13638, 13655), True, 'import numpy as np\n'), ((13834, 13856), 'numpy.ones_like', 'np.ones_like', (['test_dir'], {}), '(test_dir)\n', (13846, 13856), True, 'import numpy as np\n'), ((18517, 18609), 'numpy.where', 'np.where', (['((self.rule == self.possible_rules[r]) * (self.match == 1) * (self.catch == 0))'], {}), '((self.rule == self.possible_rules[r]) * (self.match == 1) * (self.\n catch == 0))\n', (18525, 18609), True, 'import numpy as np\n'), ((18629, 18721), 'numpy.where', 'np.where', (['((self.rule == self.possible_rules[r]) * (self.match == 0) * (self.catch == 0))'], {}), '((self.rule == self.possible_rules[r]) * (self.match == 0) * (self.\n catch == 0))\n', (18637, 18721), True, 'import numpy as np\n'), ((18749, 18804), 'numpy.mean', 'np.mean', (['self.model_outputs[n, :, ind_match[0]]'], {'axis': '(0)'}), '(self.model_outputs[n, :, ind_match[0]], axis=0)\n', (18756, 18804), True, 'import numpy as np\n'), ((18846, 18905), 'numpy.mean', 'np.mean', (['self.model_outputs[n, :, ind_non_match[0]]'], {'axis': '(0)'}), '(self.model_outputs[n, :, ind_non_match[0]], axis=0)\n', (18853, 18905), True, 'import numpy as np\n'), ((19985, 20031), 'numpy.mean', 'np.mean', (['self.model_outputs[:, :, ind]'], {'axis': '(2)'}), '(self.model_outputs[:, :, ind], axis=2)\n', (19992, 20031), True, 'import numpy as np\n'), ((22412, 22432), 'numpy.where', 'np.where', (['(conds == i)'], {}), '(conds == i)\n', (22420, 22432), True, 'import numpy as np\n'), ((24092, 24109), 'numpy.argmax', 'np.argmax', (['dec', '(1)'], {}), '(dec, 1)\n', (24101, 24109), True, 'import numpy as np\n'), ((29507, 29526), 'numpy.where', 'np.where', (['(t == -500)'], {}), '(t == -500)\n', (29515, 29526), True, 'import numpy as np\n'), ((29526, 29542), 'numpy.where', 'np.where', (['(t == 0)'], {}), '(t == 0)\n', (29534, 29542), True, 'import numpy as np\n'), ((29541, 29559), 'numpy.where', 'np.where', (['(t == 500)'], {}), '(t == 500)\n', (29549, 29559), True, 'import numpy as np\n'), ((29558, 29577), 'numpy.where', 'np.where', (['(t == 1500)'], {}), '(t == 1500)\n', (29566, 29577), True, 'import numpy as np\n'), ((29616, 29635), 'numpy.where', 'np.where', (['(t == -500)'], {}), '(t == -500)\n', (29624, 29635), True, 'import numpy as np\n'), ((29635, 29651), 'numpy.where', 'np.where', (['(t == 0)'], {}), '(t == 0)\n', (29643, 29651), True, 'import numpy as np\n'), ((29650, 29668), 'numpy.where', 'np.where', (['(t == 500)'], {}), '(t == 500)\n', (29658, 29668), True, 'import numpy as np\n'), ((29667, 29686), 'numpy.where', 'np.where', (['(t == 1500)'], {}), '(t == 1500)\n', (29675, 29686), True, 'import numpy as np\n'), ((32589, 32614), 'numpy.mean', 'np.mean', (['rule_pev'], {'axis': '(0)'}), '(rule_pev, axis=0)\n', (32596, 32614), True, 'import numpy as np\n'), ((36151, 36186), 'numpy.std', 'np.std', (['sample_pev[:, 0, :]'], {'axis': '(0)'}), '(sample_pev[:, 0, :], axis=0)\n', (36157, 36186), True, 'import numpy as np\n'), ((36184, 36212), 'numpy.sqrt', 'np.sqrt', (['sample_pev.shape[0]'], {}), '(sample_pev.shape[0])\n', (36191, 36212), True, 'import numpy as np\n'), ((36408, 36443), 'numpy.std', 'np.std', (['sample_pev[:, 1, :]'], {'axis': '(0)'}), '(sample_pev[:, 1, :], axis=0)\n', (36414, 36443), True, 'import numpy as np\n'), ((36441, 36469), 'numpy.sqrt', 'np.sqrt', (['sample_pev.shape[0]'], {}), '(sample_pev.shape[0])\n', (36448, 36469), True, 'import numpy as np\n'), ((36803, 36841), 'numpy.std', 'np.std', (['sample_pev[:, rule, :]'], {'axis': '(0)'}), '(sample_pev[:, rule, :], axis=0)\n', (36809, 36841), True, 'import numpy as np\n'), ((36839, 36867), 'numpy.sqrt', 'np.sqrt', (['sample_pev.shape[0]'], {}), '(sample_pev.shape[0])\n', (36846, 36867), True, 'import numpy as np\n'), ((41002, 41016), 'matplotlib.pyplot.hold', 'plt.hold', (['(True)'], {}), '(True)\n', (41010, 41016), True, 'import matplotlib.pyplot as plt\n'), ((41037, 41077), 'numpy.mean', 'np.mean', (['sample_stp_pev[:, 0, :]'], {'axis': '(0)'}), '(sample_stp_pev[:, 0, :], axis=0)\n', (41044, 41077), True, 'import numpy as np\n'), ((41282, 41322), 'numpy.mean', 'np.mean', (['sample_stp_pev[:, 1, :]'], {'axis': '(0)'}), '(sample_stp_pev[:, 1, :], axis=0)\n', (41289, 41322), True, 'import numpy as np\n'), ((41698, 41741), 'numpy.mean', 'np.mean', (['sample_stp_pev[:, rule, :]'], {'axis': '(0)'}), '(sample_stp_pev[:, rule, :], axis=0)\n', (41705, 41741), True, 'import numpy as np\n'), ((42372, 42412), 'numpy.mean', 'np.mean', (['synapse_decode[:, 0, :]'], {'axis': '(1)'}), '(synapse_decode[:, 0, :], axis=1)\n', (42379, 42412), True, 'import numpy as np\n'), ((42431, 42470), 'numpy.std', 'np.std', (['synapse_decode[:, 0, :]'], {'axis': '(1)'}), '(synapse_decode[:, 0, :], axis=1)\n', (42437, 42470), True, 'import numpy as np\n'), ((42588, 42628), 'numpy.mean', 'np.mean', (['synapse_decode[:, 1, :]'], {'axis': '(1)'}), '(synapse_decode[:, 1, :], axis=1)\n', (42595, 42628), True, 'import numpy as np\n'), ((42647, 42686), 'numpy.std', 'np.std', (['synapse_decode[:, 1, :]'], {'axis': '(1)'}), '(synapse_decode[:, 1, :], axis=1)\n', (42653, 42686), True, 'import numpy as np\n'), ((42963, 43006), 'numpy.mean', 'np.mean', (['synapse_decode[:, rule, :]'], {'axis': '(1)'}), '(synapse_decode[:, rule, :], axis=1)\n', (42970, 43006), True, 'import numpy as np\n'), ((43025, 43067), 'numpy.std', 'np.std', (['synapse_decode[:, rule, :]'], {'axis': '(1)'}), '(synapse_decode[:, rule, :], axis=1)\n', (43031, 43067), True, 'import numpy as np\n'), ((43185, 43233), 'numpy.mean', 'np.mean', (['synapse_decode_test[:, rule, :]'], {'axis': '(1)'}), '(synapse_decode_test[:, rule, :], axis=1)\n', (43192, 43233), True, 'import numpy as np\n'), ((43252, 43299), 'numpy.std', 'np.std', (['synapse_decode_test[:, rule, :]'], {'axis': '(1)'}), '(synapse_decode_test[:, rule, :], axis=1)\n', (43258, 43299), True, 'import numpy as np\n'), ((43759, 43777), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (43775, 43777), True, 'import matplotlib.pyplot as plt\n'), ((43794, 43838), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""DMS summary.pdf"""'], {'format': '"""pdf"""'}), "('DMS summary.pdf', format='pdf')\n", (43805, 43838), True, 'import matplotlib.pyplot as plt\n'), ((44616, 44666), 'numpy.mean', 'np.mean', (['sample_decoding[i, j, 0, 0, :, :]'], {'axis': '(1)'}), '(sample_decoding[i, j, 0, 0, :, :], axis=1)\n', (44623, 44666), True, 'import numpy as np\n'), ((44682, 44731), 'numpy.std', 'np.std', (['sample_decoding[i, j, 0, 0, :, :]'], {'axis': '(1)'}), '(sample_decoding[i, j, 0, 0, :, :], axis=1)\n', (44688, 44731), True, 'import numpy as np\n'), ((44846, 44896), 'numpy.mean', 'np.mean', (['sample_decoding[i, j, 0, 1, :, :]'], {'axis': '(1)'}), '(sample_decoding[i, j, 0, 1, :, :], axis=1)\n', (44853, 44896), True, 'import numpy as np\n'), ((44912, 44961), 'numpy.std', 'np.std', (['sample_decoding[i, j, 0, 1, :, :]'], {'axis': '(1)'}), '(sample_decoding[i, j, 0, 1, :, :], axis=1)\n', (44918, 44961), True, 'import numpy as np\n'), ((61960, 61999), 'numpy.mean', 'np.mean', (['mean_resp1[:, :, :, :]'], {'axis': '(1)'}), '(mean_resp1[:, :, :, :], axis=1)\n', (61967, 61999), True, 'import numpy as np\n'), ((62066, 62105), 'numpy.mean', 'np.mean', (['mean_resp2[:, :, :, :]'], {'axis': '(1)'}), '(mean_resp2[:, :, :, :], axis=1)\n', (62073, 62105), True, 'import numpy as np\n'), ((76006, 76063), 'numpy.mean', 'np.mean', (['spike_decoding[j, ind_good_models, :, :]'], {'axis': '(2)'}), '(spike_decoding[j, ind_good_models, :, :], axis=2)\n', (76013, 76063), True, 'import numpy as np\n'), ((76286, 76345), 'numpy.mean', 'np.mean', (['synapse_decoding[j, ind_good_models, :, :]'], {'axis': '(2)'}), '(synapse_decoding[j, ind_good_models, :, :], axis=2)\n', (76293, 76345), True, 'import numpy as np\n'), ((80827, 80885), 'numpy.mean', 'np.mean', (['spike_decode[delay_start:delay_end, 0, :]'], {'axis': '(0)'}), '(spike_decode[delay_start:delay_end, 0, :], axis=0)\n', (80834, 80885), True, 'import numpy as np\n'), ((83535, 83589), 'contrib_to_behavior.Analysis', 'contrib_to_behavior.Analysis', (['f'], {'old_format': 'old_format'}), '(f, old_format=old_format)\n', (83563, 83589), False, 'import contrib_to_behavior\n'), ((84628, 84674), 'numpy.transpose', 'np.transpose', (['spike_decode[:, :, :]', '(1, 0, 2)'], {}), '(spike_decode[:, :, :], (1, 0, 2))\n', (84640, 84674), True, 'import numpy as np\n'), ((84715, 84763), 'numpy.transpose', 'np.transpose', (['synapse_decode[:, :, :]', '(1, 0, 2)'], {}), '(synapse_decode[:, :, :], (1, 0, 2))\n', (84727, 84763), True, 'import numpy as np\n'), ((84807, 84858), 'numpy.transpose', 'np.transpose', (['spike_decode_test[:, :, :]', '(1, 0, 2)'], {}), '(spike_decode_test[:, :, :], (1, 0, 2))\n', (84819, 84858), True, 'import numpy as np\n'), ((84904, 84957), 'numpy.transpose', 'np.transpose', (['synapse_decode_test[:, :, :]', '(1, 0, 2)'], {}), '(synapse_decode_test[:, :, :], (1, 0, 2))\n', (84916, 84957), True, 'import numpy as np\n'), ((91068, 91090), 'numpy.float32', 'np.float32', (['(y == y_hat)'], {}), '(y == y_hat)\n', (91078, 91090), True, 'import numpy as np\n'), ((91091, 91107), 'numpy.squeeze', 'np.squeeze', (['mask'], {}), '(mask)\n', (91101, 91107), True, 'import numpy as np\n'), ((6080, 6106), 'numpy.dot', 'np.dot', (['h[0]', 'sample_dir.T'], {}), '(h[0], sample_dir.T)\n', (6086, 6106), True, 'import numpy as np\n'), ((6549, 6608), 'numpy.linalg.lstsq', 'np.linalg.lstsq', (['test_dir[ind]', 'self.rnn_outputs[n, t, ind]'], {}), '(test_dir[ind], self.rnn_outputs[n, t, ind])\n', (6564, 6608), True, 'import numpy as np\n'), ((6722, 6744), 'numpy.mean', 'np.mean', (['(pred_err ** 2)'], {}), '(pred_err ** 2)\n', (6729, 6744), True, 'import numpy as np\n'), ((6778, 6813), 'numpy.var', 'np.var', (['self.rnn_outputs[n, t, ind]'], {}), '(self.rnn_outputs[n, t, ind])\n', (6784, 6813), True, 'import numpy as np\n'), ((6917, 6945), 'numpy.arctan2', 'np.arctan2', (['h[0][2]', 'h[0][1]'], {}), '(h[0][2], h[0][1])\n', (6927, 6945), True, 'import numpy as np\n'), ((6983, 7019), 'numpy.sqrt', 'np.sqrt', (['(h[0][0] ** 2 + h[0][1] ** 2)'], {}), '(h[0][0] ** 2 + h[0][1] ** 2)\n', (6990, 7019), True, 'import numpy as np\n'), ((8631, 8733), 'numpy.where', 'np.where', (['((self.rule == self.possible_rules[rule]) * (self.sample_dir == s) * (self.\n test_dir == t))'], {}), '((self.rule == self.possible_rules[rule]) * (self.sample_dir == s) *\n (self.test_dir == t))\n', (8639, 8733), True, 'import numpy as np\n'), ((10059, 10202), 'numpy.mean', 'np.mean', (['((self.model_outputs[2, -n:, i] > self.model_outputs[1, -n:, i]) * (self.\n model_outputs[2, -n:, i] > self.model_outputs[0, -n:, i]))'], {}), '((self.model_outputs[2, -n:, i] > self.model_outputs[1, -n:, i]) * (\n self.model_outputs[2, -n:, i] > self.model_outputs[0, -n:, i]))\n', (10066, 10202), True, 'import numpy as np\n'), ((10232, 10375), 'numpy.mean', 'np.mean', (['((self.model_outputs[1, -n:, i] > self.model_outputs[2, -n:, i]) * (self.\n model_outputs[1, -n:, i] > self.model_outputs[0, -n:, i]))'], {}), '((self.model_outputs[1, -n:, i] > self.model_outputs[2, -n:, i]) * (\n self.model_outputs[1, -n:, i] > self.model_outputs[0, -n:, i]))\n', (10239, 10375), True, 'import numpy as np\n'), ((11522, 11687), 'numpy.sum', 'np.sum', (['((self.model_outputs[2, test_rng, i] > self.model_outputs[1, test_rng, i]) *\n (self.model_outputs[2, test_rng, i] > self.model_outputs[0, test_rng, i]))'], {}), '((self.model_outputs[2, test_rng, i] > self.model_outputs[1, test_rng,\n i]) * (self.model_outputs[2, test_rng, i] > self.model_outputs[0,\n test_rng, i]))\n', (11528, 11687), True, 'import numpy as np\n'), ((11793, 11958), 'numpy.sum', 'np.sum', (['((self.model_outputs[1, test_rng, i] > self.model_outputs[2, test_rng, i]) *\n (self.model_outputs[1, test_rng, i] > self.model_outputs[0, test_rng, i]))'], {}), '((self.model_outputs[1, test_rng, i] > self.model_outputs[2, test_rng,\n i]) * (self.model_outputs[1, test_rng, i] > self.model_outputs[0,\n test_rng, i]))\n', (11799, 11958), True, 'import numpy as np\n'), ((13955, 13988), 'numpy.where', 'np.where', (['(self.num_test_stim >= 4)'], {}), '(self.num_test_stim >= 4)\n', (13963, 13988), True, 'import numpy as np\n'), ((14032, 14077), 'numpy.where', 'np.where', (['(self.rule == self.possible_rules[r])'], {}), '(self.rule == self.possible_rules[r])\n', (14040, 14077), True, 'import numpy as np\n'), ((16311, 16324), 'numpy.abs', 'np.abs', (['(i - j)'], {}), '(i - j)\n', (16317, 16324), True, 'import numpy as np\n'), ((18340, 18384), 'numpy.mean', 'np.mean', (['self.rnn_outputs[n, :, ind]'], {'axis': '(0)'}), '(self.rnn_outputs[n, :, ind], axis=0)\n', (18347, 18384), True, 'import numpy as np\n'), ((19861, 19953), 'numpy.where', 'np.where', (['((self.match[:, 0] == m1) * (self.match[:, 1] == m2) * (self.probe[:, 1] == 0))'], {}), '((self.match[:, 0] == m1) * (self.match[:, 1] == m2) * (self.probe[\n :, 1] == 0))\n', (19869, 19953), True, 'import numpy as np\n'), ((25191, 25224), 'numpy.where', 'np.where', (['(self.num_test_stim >= 4)'], {}), '(self.num_test_stim >= 4)\n', (25199, 25224), True, 'import numpy as np\n'), ((25268, 25313), 'numpy.where', 'np.where', (['(self.rule == self.possible_rules[r])'], {}), '(self.rule == self.possible_rules[r])\n', (25276, 25313), True, 'import numpy as np\n'), ((25346, 25413), 'numpy.where', 'np.where', (['((self.rule == self.possible_rules[r]) * (self.match == 0))'], {}), '((self.rule == self.possible_rules[r]) * (self.match == 0))\n', (25354, 25413), True, 'import numpy as np\n'), ((41096, 41135), 'numpy.std', 'np.std', (['sample_stp_pev[:, 0, :]'], {'axis': '(0)'}), '(sample_stp_pev[:, 0, :], axis=0)\n', (41102, 41135), True, 'import numpy as np\n'), ((41133, 41161), 'numpy.sqrt', 'np.sqrt', (['sample_pev.shape[0]'], {}), '(sample_pev.shape[0])\n', (41140, 41161), True, 'import numpy as np\n'), ((41341, 41380), 'numpy.std', 'np.std', (['sample_stp_pev[:, 1, :]'], {'axis': '(0)'}), '(sample_stp_pev[:, 1, :], axis=0)\n', (41347, 41380), True, 'import numpy as np\n'), ((41378, 41406), 'numpy.sqrt', 'np.sqrt', (['sample_pev.shape[0]'], {}), '(sample_pev.shape[0])\n', (41385, 41406), True, 'import numpy as np\n'), ((41760, 41802), 'numpy.std', 'np.std', (['sample_stp_pev[:, rule, :]'], {'axis': '(0)'}), '(sample_stp_pev[:, rule, :], axis=0)\n', (41766, 41802), True, 'import numpy as np\n'), ((41800, 41828), 'numpy.sqrt', 'np.sqrt', (['sample_pev.shape[0]'], {}), '(sample_pev.shape[0])\n', (41807, 41828), True, 'import numpy as np\n'), ((45135, 45189), 'numpy.mean', 'np.mean', (['sample_stp_decoding[i, j, 0, 0, :, :]'], {'axis': '(1)'}), '(sample_stp_decoding[i, j, 0, 0, :, :], axis=1)\n', (45142, 45189), True, 'import numpy as np\n'), ((45209, 45262), 'numpy.std', 'np.std', (['sample_stp_decoding[i, j, 0, 0, :, :]'], {'axis': '(1)'}), '(sample_stp_decoding[i, j, 0, 0, :, :], axis=1)\n', (45215, 45262), True, 'import numpy as np\n'), ((45410, 45464), 'numpy.mean', 'np.mean', (['sample_stp_decoding[i, j, 0, 1, :, :]'], {'axis': '(1)'}), '(sample_stp_decoding[i, j, 0, 1, :, :], axis=1)\n', (45417, 45464), True, 'import numpy as np\n'), ((45484, 45537), 'numpy.std', 'np.std', (['sample_stp_decoding[i, j, 0, 1, :, :]'], {'axis': '(1)'}), '(sample_stp_decoding[i, j, 0, 1, :, :], axis=1)\n', (45490, 45537), True, 'import numpy as np\n'), ((83731, 83789), 'contrib_to_behavior.Analysis', 'contrib_to_behavior.Analysis', (['f'], {'old_format': '(not old_format)'}), '(f, old_format=not old_format)\n', (83759, 83789), False, 'import contrib_to_behavior\n'), ((6481, 6506), 'numpy.where', 'np.where', (['(self.match == m)'], {}), '(self.match == m)\n', (6489, 6506), True, 'import numpy as np\n'), ((6666, 6695), 'numpy.dot', 'np.dot', (['h[0]', 'test_dir[ind].T'], {}), '(h[0], test_dir[ind].T)\n', (6672, 6695), True, 'import numpy as np\n'), ((9927, 9972), 'numpy.where', 'np.where', (['(self.rule[i] == self.possible_rules)'], {}), '(self.rule[i] == self.possible_rules)\n', (9935, 9972), True, 'import numpy as np\n'), ((16413, 16443), 'numpy.where', 'np.where', (['(self.sample_dir == s)'], {}), '(self.sample_dir == s)\n', (16421, 16443), True, 'import numpy as np\n'), ((16472, 16497), 'numpy.where', 'np.where', (['(self.match == 1)'], {}), '(self.match == 1)\n', (16480, 16497), True, 'import numpy as np\n'), ((16627, 16696), 'numpy.corrcoef', 'np.corrcoef', (['self.rnn_outputs[n, i, ind]', 'self.rnn_outputs[n, j, ind]'], {}), '(self.rnn_outputs[n, i, ind], self.rnn_outputs[n, j, ind])\n', (16638, 16696), True, 'import numpy as np\n'), ((20159, 20248), 'numpy.where', 'np.where', (['((self.rule[:, 0] == r1) * (self.rule[:, 1] == r2) * (self.probe[:, 1] == p))'], {}), '((self.rule[:, 0] == r1) * (self.rule[:, 1] == r2) * (self.probe[:,\n 1] == p))\n', (20167, 20248), True, 'import numpy as np\n'), ((25707, 25766), 'numpy.floor', 'np.floor', (['(self.sample_dir[ind] / (self.num_motion_dirs / 2))'], {}), '(self.sample_dir[ind] / (self.num_motion_dirs / 2))\n', (25715, 25766), True, 'import numpy as np\n'), ((16864, 16921), 'numpy.corrcoef', 'np.corrcoef', (['self.syn_x[n, i, ind]', 'self.syn_x[n, j, ind]'], {}), '(self.syn_x[n, i, ind], self.syn_x[n, j, ind])\n', (16875, 16921), True, 'import numpy as np\n'), ((17094, 17145), 'numpy.corrcoef', 'np.corrcoef', (['self.sa[n, i, ind]', 'self.sa[n, j, ind]'], {}), '(self.sa[n, i, ind], self.sa[n, j, ind])\n', (17105, 17145), True, 'import numpy as np\n'), ((18113, 18173), 'numpy.where', 'np.where', (['((self.num_test_stim >= 4) * (self.sample_dir == d))'], {}), '((self.num_test_stim >= 4) * (self.sample_dir == d))\n', (18121, 18173), True, 'import numpy as np\n'), ((18227, 18299), 'numpy.where', 'np.where', (['((self.rule == self.possible_rules[r]) * (self.sample_dir == d))'], {}), '((self.rule == self.possible_rules[r]) * (self.sample_dir == d))\n', (18235, 18299), True, 'import numpy as np\n'), ((24158, 24170), 'numpy.sign', 'np.sign', (['dec'], {}), '(dec)\n', (24165, 24170), True, 'import numpy as np\n'), ((26613, 26672), 'numpy.floor', 'np.floor', (['(self.sample_dir[ind] / (self.num_motion_dirs / 2))'], {}), '(self.sample_dir[ind] / (self.num_motion_dirs / 2))\n', (26621, 26672), True, 'import numpy as np\n')]
import unittest import numpy as np from trip_kinematics.Utility import Rotation as R class TestStates(unittest.TestCase): """Correct results were generated using scipy.spatial.transform.Rotation. """ def test_from_euler_to_quat(self): from_euler_cases = [ ([1, 2, 3], [0.4359528440735657, -0.7182870182434115, 0.3106224510657039, 0.44443511344300074]), ([1, 0, 0], [0.8775825618903728, 0.479425538604203, 0.0, 0.0]), ([0, 1, 0], [0.8775825618903728, 0.0, 0.479425538604203, 0.0]), ([0, 0, 1], [0.8775825618903728, 0.0, 0.0, 0.479425538604203]), ([1.9259795237086745, -1.3166224746837234, -1.6487569080546618], [0.6754185988029391, 0.1844402562591348, -0.7139352011035228, 0.00938279741930681]), ([1.7518638481261277, -1.4762648402511551, 2.783050177056892], [-0.4241491835815902, 0.5252649613496548, 0.482281714511987, 0.5582101201991901]), ([-1.5637740430088356, 0.9967772877753394, -1.281072618629502], [0.7010098084209453, -0.2935149227036473, 0.6418274036266723, -0.1024295982699634]), ([-2.018987322821037, -2.477643741973166, -1.7329756283622468], [-0.4975785988500945, -0.562138163026927, -0.1155880687282515, -0.6504272611159234]), ([-1.547364165870453, 3.1155873968096914, 2.5081666410682404], [-0.6610669854921286, -0.6825367059399726, 0.2141370877143812, 0.22644953831298628]), ([0.9232800471655072, 2.9636239629991614, 1.3121379453450235], [0.3336790888032567, -0.5126269396587794, 0.7307896657891122, -0.3030154299822701]), ([-3.0969110304794603, 1.6540648344396605, -1.1444726410810802], [0.4111294068459875, -0.5601567984771901, 0.38036785991321215, 0.6103419230982696]), ] for euler_angles, quat in from_euler_cases: assert np.allclose(R.from_euler('xyz', euler_angles, degrees=False).as_quat(), quat) euler_angles_deg = np.array(euler_angles) * (180 / np.pi) assert np.allclose(R.from_euler('xyz', euler_angles_deg, degrees=True).as_quat(), quat) def test_from_matrix_to_quat(self): test_cases = [ (np.array([[0.41198224566568303, -0.8337376517741568, -0.3676304629248995], [-0.058726644927620864, -0.4269176212762076, 0.902381585483331], [-0.9092974268256819, -0.35017548837401474, -0.2248450953661529]]), [-0.43595284407356566, 0.7182870182434113, -0.31062245106570385, -0.4444351134430007]), (np.array([[1., 0., 0.], [0., 0.54030231, -0.84147098], [0., 0.84147098, 0.54030231]]), [0.8775825618903726, 0.47942553860420295, 0.0, 0.0]), (np.array([[0.54030231, 0., 0.84147098], [0., 1., 0.], [-0.84147098, 0., 0.54030231]]), [0.8775825618903726, 0.0, 0.47942553860420295, 0.0]), (np.array([[0.54030231, -0.84147098, 0.], [0.84147098, 0.54030231, 0.], [0., 0., 1.]]), [0.8775825618903726, 0.0, 0.0, 0.47942553860420295]), (np.array([[-0.01958302, -0.27603141, -0.9609491], [-0.25068215, 0.93178751, -0.26254618], [0.96787136, 0.23575134, -0.08744336]]), [-0.6754185988029392, -0.18444025625913482, 0.7139352011035228, -0.00938279741930680]), (np.array([[-0.08838838, 0.98018011, 0.17729764], [0.03312264, -0.17500364, 0.98401048], [0.99553523, 0.09284766, -0.01699786]]), [-0.4241491835815902, 0.5252649613496548, 0.4822817145119869, 0.5582101201991901]), (np.array([[0.15513152, -0.23316354, 0.95998384], [-0.52038015, 0.80671434, 0.28002943], [-0.83972538, -0.54299793, 0.00381315]]), [0.7010098084209453, -0.2935149227036473, 0.6418274036266723, -0.10242959826996342]), (np.array([[0.12716755, -0.51732444, 0.84628827], [0.7772303, -0.47810987, -0.40905258], [0.61623167, 0.7097791, 0.34128017]]), [0.49757859885009453, 0.5621381630269271, 0.11558806872825153, 0.6504272611159234]), (np.array([[0.80573183, 0.00708378, -0.59223816], [-0.59170947, -0.0342715, -0.80542248], [-0.02600233, 0.99938745, -0.02342209]]), [0.6610669854921286, 0.6825367059399726, -0.2141370877143812, -0.22644953831298634]), (np.array([[-0.25174377, -0.54702511, 0.7983662], [-0.95146476, 0.29079054, -0.10077531], [-0.17703071, -0.78498687, -0.59367983]]), [0.3336790888032567, -0.5126269396587794, 0.7307896657891123, -0.30301542998227005]), (np.array([[-0.03439394, -0.92799031, -0.37101353], [0.07572774, -0.3725858, 0.92490277], [-0.99653518, 0.00371504, 0.0830893]]), [0.4111294068459875, -0.5601567984771901, 0.38036785991321215, 0.6103419230982696]) ] for matrix, quat in test_cases: assert np.allclose(R.from_matrix(matrix).as_quat(), quat) def main(): test_cases = [ (np.array([[0.41198224566568303, -0.8337376517741568, -0.3676304629248995], [-0.058726644927620864, -0.4269176212762076, 0.902381585483331], [-0.9092974268256819, -0.35017548837401474, -0.2248450953661529]]), [-0.43595284407356566, 0.7182870182434113, -0.31062245106570385, -0.4444351134430007]), (np.array([[1., 0., 0.], [0., 0.54030231, -0.84147098], [0., 0.84147098, 0.54030231]]), [0.8775825618903726, 0.47942553860420295, 0.0, 0.0]), (np.array([[0.54030231, 0., 0.84147098], [0., 1., 0.], [-0.84147098, 0., 0.54030231]]), [0.8775825618903726, 0.0, 0.47942553860420295, 0.0]), (np.array([[0.54030231, -0.84147098, 0.], [0.84147098, 0.54030231, 0.], [0., 0., 1.]]), [0.8775825618903726, 0.0, 0.0, 0.47942553860420295]), (np.array([[-0.01958302, -0.27603141, -0.9609491], [-0.25068215, 0.93178751, -0.26254618], [0.96787136, 0.23575134, -0.08744336]]), [-0.6754185988029392, -0.18444025625913482, 0.7139352011035228, -0.009382797419306801]), (np.array([[-0.08838838, 0.98018011, 0.17729764], [0.03312264, -0.17500364, 0.98401048], [0.99553523, 0.09284766, -0.01699786]]), [-0.4241491835815902, 0.5252649613496548, 0.4822817145119869, 0.5582101201991901]), (np.array([[0.15513152, -0.23316354, 0.95998384], [-0.52038015, 0.80671434, 0.28002943], [-0.83972538, -0.54299793, 0.00381315]]), [0.7010098084209453, -0.2935149227036473, 0.6418274036266723, -0.10242959826996342]), (np.array([[0.12716755, -0.51732444, 0.84628827], [0.7772303, -0.47810987, -0.40905258], [0.61623167, 0.7097791, 0.34128017]]), [0.49757859885009453, 0.5621381630269271, 0.11558806872825153, 0.6504272611159234]), (np.array([[0.80573183, 0.00708378, -0.59223816], [-0.59170947, -0.0342715, -0.80542248], [-0.02600233, 0.99938745, -0.02342209]]), [0.6610669854921286, 0.6825367059399726, -0.2141370877143812, -0.22644953831298634]), (np.array([[-0.25174377, -0.54702511, 0.7983662], [-0.95146476, 0.29079054, -0.10077531], [-0.17703071, -0.78498687, -0.59367983]]), [0.3336790888032567, -0.5126269396587794, 0.7307896657891123, -0.30301542998227005]), (np.array([[-0.03439394, -0.92799031, -0.37101353], [0.07572774, -0.3725858, 0.92490277], [-0.99653518, 0.00371504, 0.0830893]]), [0.4111294068459875, -0.5601567984771901, 0.38036785991321215, 0.6103419230982696]) ] for matrix, quat in test_cases: assert np.allclose(R.from_matrix(matrix).as_quat(), quat) if __name__ == '__main__': main()
[ "trip_kinematics.Utility.Rotation.from_matrix", "numpy.array", "trip_kinematics.Utility.Rotation.from_euler" ]
[((5515, 5730), 'numpy.array', 'np.array', (['[[0.41198224566568303, -0.8337376517741568, -0.3676304629248995], [-\n 0.058726644927620864, -0.4269176212762076, 0.902381585483331], [-\n 0.9092974268256819, -0.35017548837401474, -0.2248450953661529]]'], {}), '([[0.41198224566568303, -0.8337376517741568, -0.3676304629248995],\n [-0.058726644927620864, -0.4269176212762076, 0.902381585483331], [-\n 0.9092974268256819, -0.35017548837401474, -0.2248450953661529]])\n', (5523, 5730), True, 'import numpy as np\n'), ((5871, 5965), 'numpy.array', 'np.array', (['[[1.0, 0.0, 0.0], [0.0, 0.54030231, -0.84147098], [0.0, 0.84147098, 0.54030231]\n ]'], {}), '([[1.0, 0.0, 0.0], [0.0, 0.54030231, -0.84147098], [0.0, 0.84147098,\n 0.54030231]])\n', (5879, 5965), True, 'import numpy as np\n'), ((6072, 6166), 'numpy.array', 'np.array', (['[[0.54030231, 0.0, 0.84147098], [0.0, 1.0, 0.0], [-0.84147098, 0.0, 0.54030231]\n ]'], {}), '([[0.54030231, 0.0, 0.84147098], [0.0, 1.0, 0.0], [-0.84147098, 0.0,\n 0.54030231]])\n', (6080, 6166), True, 'import numpy as np\n'), ((6273, 6368), 'numpy.array', 'np.array', (['[[0.54030231, -0.84147098, 0.0], [0.84147098, 0.54030231, 0.0], [0.0, 0.0, 1.0]\n ]'], {}), '([[0.54030231, -0.84147098, 0.0], [0.84147098, 0.54030231, 0.0], [\n 0.0, 0.0, 1.0]])\n', (6281, 6368), True, 'import numpy as np\n'), ((6474, 6607), 'numpy.array', 'np.array', (['[[-0.01958302, -0.27603141, -0.9609491], [-0.25068215, 0.93178751, -\n 0.26254618], [0.96787136, 0.23575134, -0.08744336]]'], {}), '([[-0.01958302, -0.27603141, -0.9609491], [-0.25068215, 0.93178751,\n -0.26254618], [0.96787136, 0.23575134, -0.08744336]])\n', (6482, 6607), True, 'import numpy as np\n'), ((6754, 6886), 'numpy.array', 'np.array', (['[[-0.08838838, 0.98018011, 0.17729764], [0.03312264, -0.17500364, \n 0.98401048], [0.99553523, 0.09284766, -0.01699786]]'], {}), '([[-0.08838838, 0.98018011, 0.17729764], [0.03312264, -0.17500364, \n 0.98401048], [0.99553523, 0.09284766, -0.01699786]])\n', (6762, 6886), True, 'import numpy as np\n'), ((7027, 7160), 'numpy.array', 'np.array', (['[[0.15513152, -0.23316354, 0.95998384], [-0.52038015, 0.80671434, \n 0.28002943], [-0.83972538, -0.54299793, 0.00381315]]'], {}), '([[0.15513152, -0.23316354, 0.95998384], [-0.52038015, 0.80671434, \n 0.28002943], [-0.83972538, -0.54299793, 0.00381315]])\n', (7035, 7160), True, 'import numpy as np\n'), ((7303, 7433), 'numpy.array', 'np.array', (['[[0.12716755, -0.51732444, 0.84628827], [0.7772303, -0.47810987, -\n 0.40905258], [0.61623167, 0.7097791, 0.34128017]]'], {}), '([[0.12716755, -0.51732444, 0.84628827], [0.7772303, -0.47810987, -\n 0.40905258], [0.61623167, 0.7097791, 0.34128017]])\n', (7311, 7433), True, 'import numpy as np\n'), ((7575, 7709), 'numpy.array', 'np.array', (['[[0.80573183, 0.00708378, -0.59223816], [-0.59170947, -0.0342715, -\n 0.80542248], [-0.02600233, 0.99938745, -0.02342209]]'], {}), '([[0.80573183, 0.00708378, -0.59223816], [-0.59170947, -0.0342715, \n -0.80542248], [-0.02600233, 0.99938745, -0.02342209]])\n', (7583, 7709), True, 'import numpy as np\n'), ((7852, 7987), 'numpy.array', 'np.array', (['[[-0.25174377, -0.54702511, 0.7983662], [-0.95146476, 0.29079054, -\n 0.10077531], [-0.17703071, -0.78498687, -0.59367983]]'], {}), '([[-0.25174377, -0.54702511, 0.7983662], [-0.95146476, 0.29079054, \n -0.10077531], [-0.17703071, -0.78498687, -0.59367983]])\n', (7860, 7987), True, 'import numpy as np\n'), ((8130, 8261), 'numpy.array', 'np.array', (['[[-0.03439394, -0.92799031, -0.37101353], [0.07572774, -0.3725858, \n 0.92490277], [-0.99653518, 0.00371504, 0.0830893]]'], {}), '([[-0.03439394, -0.92799031, -0.37101353], [0.07572774, -0.3725858,\n 0.92490277], [-0.99653518, 0.00371504, 0.0830893]])\n', (8138, 8261), True, 'import numpy as np\n'), ((2073, 2095), 'numpy.array', 'np.array', (['euler_angles'], {}), '(euler_angles)\n', (2081, 2095), True, 'import numpy as np\n'), ((2294, 2509), 'numpy.array', 'np.array', (['[[0.41198224566568303, -0.8337376517741568, -0.3676304629248995], [-\n 0.058726644927620864, -0.4269176212762076, 0.902381585483331], [-\n 0.9092974268256819, -0.35017548837401474, -0.2248450953661529]]'], {}), '([[0.41198224566568303, -0.8337376517741568, -0.3676304629248995],\n [-0.058726644927620864, -0.4269176212762076, 0.902381585483331], [-\n 0.9092974268256819, -0.35017548837401474, -0.2248450953661529]])\n', (2302, 2509), True, 'import numpy as np\n'), ((2666, 2760), 'numpy.array', 'np.array', (['[[1.0, 0.0, 0.0], [0.0, 0.54030231, -0.84147098], [0.0, 0.84147098, 0.54030231]\n ]'], {}), '([[1.0, 0.0, 0.0], [0.0, 0.54030231, -0.84147098], [0.0, 0.84147098,\n 0.54030231]])\n', (2674, 2760), True, 'import numpy as np\n'), ((2883, 2977), 'numpy.array', 'np.array', (['[[0.54030231, 0.0, 0.84147098], [0.0, 1.0, 0.0], [-0.84147098, 0.0, 0.54030231]\n ]'], {}), '([[0.54030231, 0.0, 0.84147098], [0.0, 1.0, 0.0], [-0.84147098, 0.0,\n 0.54030231]])\n', (2891, 2977), True, 'import numpy as np\n'), ((3100, 3195), 'numpy.array', 'np.array', (['[[0.54030231, -0.84147098, 0.0], [0.84147098, 0.54030231, 0.0], [0.0, 0.0, 1.0]\n ]'], {}), '([[0.54030231, -0.84147098, 0.0], [0.84147098, 0.54030231, 0.0], [\n 0.0, 0.0, 1.0]])\n', (3108, 3195), True, 'import numpy as np\n'), ((3317, 3450), 'numpy.array', 'np.array', (['[[-0.01958302, -0.27603141, -0.9609491], [-0.25068215, 0.93178751, -\n 0.26254618], [0.96787136, 0.23575134, -0.08744336]]'], {}), '([[-0.01958302, -0.27603141, -0.9609491], [-0.25068215, 0.93178751,\n -0.26254618], [0.96787136, 0.23575134, -0.08744336]])\n', (3325, 3450), True, 'import numpy as np\n'), ((3612, 3744), 'numpy.array', 'np.array', (['[[-0.08838838, 0.98018011, 0.17729764], [0.03312264, -0.17500364, \n 0.98401048], [0.99553523, 0.09284766, -0.01699786]]'], {}), '([[-0.08838838, 0.98018011, 0.17729764], [0.03312264, -0.17500364, \n 0.98401048], [0.99553523, 0.09284766, -0.01699786]])\n', (3620, 3744), True, 'import numpy as np\n'), ((3901, 4034), 'numpy.array', 'np.array', (['[[0.15513152, -0.23316354, 0.95998384], [-0.52038015, 0.80671434, \n 0.28002943], [-0.83972538, -0.54299793, 0.00381315]]'], {}), '([[0.15513152, -0.23316354, 0.95998384], [-0.52038015, 0.80671434, \n 0.28002943], [-0.83972538, -0.54299793, 0.00381315]])\n', (3909, 4034), True, 'import numpy as np\n'), ((4193, 4323), 'numpy.array', 'np.array', (['[[0.12716755, -0.51732444, 0.84628827], [0.7772303, -0.47810987, -\n 0.40905258], [0.61623167, 0.7097791, 0.34128017]]'], {}), '([[0.12716755, -0.51732444, 0.84628827], [0.7772303, -0.47810987, -\n 0.40905258], [0.61623167, 0.7097791, 0.34128017]])\n', (4201, 4323), True, 'import numpy as np\n'), ((4481, 4615), 'numpy.array', 'np.array', (['[[0.80573183, 0.00708378, -0.59223816], [-0.59170947, -0.0342715, -\n 0.80542248], [-0.02600233, 0.99938745, -0.02342209]]'], {}), '([[0.80573183, 0.00708378, -0.59223816], [-0.59170947, -0.0342715, \n -0.80542248], [-0.02600233, 0.99938745, -0.02342209]])\n', (4489, 4615), True, 'import numpy as np\n'), ((4774, 4909), 'numpy.array', 'np.array', (['[[-0.25174377, -0.54702511, 0.7983662], [-0.95146476, 0.29079054, -\n 0.10077531], [-0.17703071, -0.78498687, -0.59367983]]'], {}), '([[-0.25174377, -0.54702511, 0.7983662], [-0.95146476, 0.29079054, \n -0.10077531], [-0.17703071, -0.78498687, -0.59367983]])\n', (4782, 4909), True, 'import numpy as np\n'), ((5068, 5199), 'numpy.array', 'np.array', (['[[-0.03439394, -0.92799031, -0.37101353], [0.07572774, -0.3725858, \n 0.92490277], [-0.99653518, 0.00371504, 0.0830893]]'], {}), '([[-0.03439394, -0.92799031, -0.37101353], [0.07572774, -0.3725858,\n 0.92490277], [-0.99653518, 0.00371504, 0.0830893]])\n', (5076, 5199), True, 'import numpy as np\n'), ((8467, 8488), 'trip_kinematics.Utility.Rotation.from_matrix', 'R.from_matrix', (['matrix'], {}), '(matrix)\n', (8480, 8488), True, 'from trip_kinematics.Utility import Rotation as R\n'), ((1975, 2023), 'trip_kinematics.Utility.Rotation.from_euler', 'R.from_euler', (['"""xyz"""', 'euler_angles'], {'degrees': '(False)'}), "('xyz', euler_angles, degrees=False)\n", (1987, 2023), True, 'from trip_kinematics.Utility import Rotation as R\n'), ((2144, 2195), 'trip_kinematics.Utility.Rotation.from_euler', 'R.from_euler', (['"""xyz"""', 'euler_angles_deg'], {'degrees': '(True)'}), "('xyz', euler_angles_deg, degrees=True)\n", (2156, 2195), True, 'from trip_kinematics.Utility import Rotation as R\n'), ((5429, 5450), 'trip_kinematics.Utility.Rotation.from_matrix', 'R.from_matrix', (['matrix'], {}), '(matrix)\n', (5442, 5450), True, 'from trip_kinematics.Utility import Rotation as R\n')]
import os os.environ['CUDA_VISIBLE_DEVICES'] = '1' import cv2 import glob import numpy as np from PIL import Image from core.utils import load_image, deprocess_image, preprocess_image from core.networks import unet_spp_large_swish_generator_model from core.dcp import estimate_transmission img_size = 512 def preprocess_image(cv_img): cv_img = cv2.resize(cv_img, (img_size,img_size)) img = np.array(cv_img) img = (img - 127.5) / 127.5 return img def load_image(path): img = Image.open(path) return img def deprocess_image(img): img = img * 127.5 + 127.5 return img.astype('uint8') def get_file_name(path): basename = os.path.basename(path) onlyname = os.path.splitext(basename)[0] return onlyname def preprocess_cv2_image(cv_img): cv_img = cv2.cvtColor(cv_img, cv2.COLOR_BGR2RGB) cv_img = cv2.resize(cv_img, (img_size, img_size)) img = np.array(cv_img) img = (img - 127.5) / 127.5 return img def preprocess_depth_img(cv_img): cv_img = cv2.resize(cv_img, (img_size, img_size)) img = np.array(cv_img) img = np.reshape(img, (img_size, img_size, 1)) img = 2*(img - 0.5) return img g = unet_spp_large_swish_generator_model() weight_path = "./weights/generator_185_26.h5" g.load_weights(weight_path) g.summary() output_dir = "outputs/generator_185_26" if not os.path.exists(output_dir): os.makedirs(output_dir) if __name__ == "__main__": img_src = glob.glob("path/to/test/image/folder/*.jpg") cnt=0 for img_path in img_src: img_name = get_file_name(img_path) ori_image = cv2.imread(img_path) h, w, _ = ori_image.shape # ori_image_resized = cv2.resize(ori_image, (img_size,img_size)) # cv2.imwrite(f"{img_name}_resized.jpg", ori_image_resized) t = estimate_transmission(ori_image) t = preprocess_depth_img(t) ori_image = preprocess_cv2_image(ori_image) x_test = np.concatenate((ori_image, t), axis=2) x_test = np.reshape(x_test, (1,img_size,img_size,4)) generated_images = g.predict(x=x_test) de_test = deprocess_image(generated_images) de_test = np.reshape(de_test, (img_size,img_size,3)) # pred_image_resized = cv2.cvtColor(de_test, cv2.COLOR_BGR2RGB) # cv2.imwrite(f"{img_name}_resized_pred.jpg", pred_image_resized) de_test = cv2.resize(de_test, (w, h)) rgb_de_test = cv2.cvtColor(de_test, cv2.COLOR_BGR2RGB) cv2.imwrite(f"{output_dir}/{img_name}.jpg", rgb_de_test) cnt+=1 print(cnt, len(img_src)) # if cnt==10: break print("Done!")
[ "core.utils.deprocess_image", "os.makedirs", "core.dcp.estimate_transmission", "os.path.basename", "cv2.cvtColor", "numpy.concatenate", "cv2.imwrite", "os.path.exists", "PIL.Image.open", "cv2.imread", "numpy.array", "numpy.reshape", "os.path.splitext", "core.networks.unet_spp_large_swish_g...
[((1240, 1278), 'core.networks.unet_spp_large_swish_generator_model', 'unet_spp_large_swish_generator_model', ([], {}), '()\n', (1276, 1278), False, 'from core.networks import unet_spp_large_swish_generator_model\n'), ((371, 411), 'cv2.resize', 'cv2.resize', (['cv_img', '(img_size, img_size)'], {}), '(cv_img, (img_size, img_size))\n', (381, 411), False, 'import cv2\n'), ((422, 438), 'numpy.array', 'np.array', (['cv_img'], {}), '(cv_img)\n', (430, 438), True, 'import numpy as np\n'), ((526, 542), 'PIL.Image.open', 'Image.open', (['path'], {}), '(path)\n', (536, 542), False, 'from PIL import Image\n'), ((699, 721), 'os.path.basename', 'os.path.basename', (['path'], {}), '(path)\n', (715, 721), False, 'import os\n'), ((842, 881), 'cv2.cvtColor', 'cv2.cvtColor', (['cv_img', 'cv2.COLOR_BGR2RGB'], {}), '(cv_img, cv2.COLOR_BGR2RGB)\n', (854, 881), False, 'import cv2\n'), ((896, 936), 'cv2.resize', 'cv2.resize', (['cv_img', '(img_size, img_size)'], {}), '(cv_img, (img_size, img_size))\n', (906, 936), False, 'import cv2\n'), ((948, 964), 'numpy.array', 'np.array', (['cv_img'], {}), '(cv_img)\n', (956, 964), True, 'import numpy as np\n'), ((1067, 1107), 'cv2.resize', 'cv2.resize', (['cv_img', '(img_size, img_size)'], {}), '(cv_img, (img_size, img_size))\n', (1077, 1107), False, 'import cv2\n'), ((1119, 1135), 'numpy.array', 'np.array', (['cv_img'], {}), '(cv_img)\n', (1127, 1135), True, 'import numpy as np\n'), ((1147, 1187), 'numpy.reshape', 'np.reshape', (['img', '(img_size, img_size, 1)'], {}), '(img, (img_size, img_size, 1))\n', (1157, 1187), True, 'import numpy as np\n'), ((1421, 1447), 'os.path.exists', 'os.path.exists', (['output_dir'], {}), '(output_dir)\n', (1435, 1447), False, 'import os\n'), ((1454, 1477), 'os.makedirs', 'os.makedirs', (['output_dir'], {}), '(output_dir)\n', (1465, 1477), False, 'import os\n'), ((1525, 1569), 'glob.glob', 'glob.glob', (['"""path/to/test/image/folder/*.jpg"""'], {}), "('path/to/test/image/folder/*.jpg')\n", (1534, 1569), False, 'import glob\n'), ((738, 764), 'os.path.splitext', 'os.path.splitext', (['basename'], {}), '(basename)\n', (754, 764), False, 'import os\n'), ((1680, 1700), 'cv2.imread', 'cv2.imread', (['img_path'], {}), '(img_path)\n', (1690, 1700), False, 'import cv2\n'), ((1896, 1928), 'core.dcp.estimate_transmission', 'estimate_transmission', (['ori_image'], {}), '(ori_image)\n', (1917, 1928), False, 'from core.dcp import estimate_transmission\n'), ((2041, 2079), 'numpy.concatenate', 'np.concatenate', (['(ori_image, t)'], {'axis': '(2)'}), '((ori_image, t), axis=2)\n', (2055, 2079), True, 'import numpy as np\n'), ((2100, 2146), 'numpy.reshape', 'np.reshape', (['x_test', '(1, img_size, img_size, 4)'], {}), '(x_test, (1, img_size, img_size, 4))\n', (2110, 2146), True, 'import numpy as np\n'), ((2213, 2246), 'core.utils.deprocess_image', 'deprocess_image', (['generated_images'], {}), '(generated_images)\n', (2228, 2246), False, 'from core.utils import load_image, deprocess_image, preprocess_image\n'), ((2266, 2310), 'numpy.reshape', 'np.reshape', (['de_test', '(img_size, img_size, 3)'], {}), '(de_test, (img_size, img_size, 3))\n', (2276, 2310), True, 'import numpy as np\n'), ((2480, 2507), 'cv2.resize', 'cv2.resize', (['de_test', '(w, h)'], {}), '(de_test, (w, h))\n', (2490, 2507), False, 'import cv2\n'), ((2533, 2573), 'cv2.cvtColor', 'cv2.cvtColor', (['de_test', 'cv2.COLOR_BGR2RGB'], {}), '(de_test, cv2.COLOR_BGR2RGB)\n', (2545, 2573), False, 'import cv2\n'), ((2583, 2639), 'cv2.imwrite', 'cv2.imwrite', (['f"""{output_dir}/{img_name}.jpg"""', 'rgb_de_test'], {}), "(f'{output_dir}/{img_name}.jpg', rgb_de_test)\n", (2594, 2639), False, 'import cv2\n')]
from OT.PSD import OT_PSD from basic.select import select_file from basic.filter import MA from matplotlib import rcParams rcParams["font.family"] = "sans-serif" rcParams["font.sans-serif"] = ["Arial"] rcParams.update({'font.size': 18}) import pandas as pd import numpy as np import random import math import matplotlib.pyplot as plt # plt.rc('text', usetex=True) # plt.rc('font', **{'family' : 'sans-serif'}) # plt.rc('font', **{'sans-serif' : 'Arial'}) # plt.rc('legend', fontsize=18) ## generate #n uniform RV range from 0 to max def get_uRV(max, n): RVs = np.array([int(math.floor(random.uniform(0, max))) for i in range(n)]) return RVs def get_boot_select(signals): n = len(signals) signals_boot = [] index = get_uRV(n, n) for i in index: signals_boot += [list(signals)[i]] return signals_boot def get_excel_data(data): n_traces = int(data.shape[1] / 4) signals = [] dt = [] t_end = [] # ending time Fs = [] for i in range(n_traces): ## select and remove nan data signal = data[:, 1 + 4 * i] signals += [signal[~np.isnan(signal)]] dt += [data[1, 0 + 4 * i] - data[0, 0 + 4 * i]] t_end += [dt[-1] * len(signals[-1])] Fs += [1 / dt[-1]] return signals, Fs def connect_traces(signals): signal_connect = [] L_cum = 0 ## for connecting all traces for fs,signal in zip(Fs,signals): signal_connect = np.append(signal_connect, signal+L_cum) L_cum += np.mean(signal[-20:]) return signal_connect ### import data # path = select_file() path = r'C:\Users\pine\Desktop\Data\time trace\m51 all traces\m51_2.0uM_All.xlsx' ## x:1.8, df = pd.read_excel(path) data = np.array(df.dropna(axis='columns', how='all')) signals, Fs = get_excel_data(data) freq_all_c = [] psd_all_c = [] t_AFC_all = [] AFC_all = [] n_boot = 2 for i in range(n_boot): Fs_spatial = 5 F_resolution = 0.002 signals_boot = get_boot_select(signals) signal_connect = connect_traces(signals_boot) PSD_connect = OT_PSD(signal_connect, fs=np.mean(Fs), Fs_spatial=Fs_spatial, F_resolution=F_resolution, bintype='set_width') t_AFC_conn, AFC_conn = PSD_connect.t_ACF, PSD_connect.ACF freq_conn, psd_conn = PSD_connect.get_PSD() freq_all_c = np.append(freq_all_c, freq_conn) psd_all_c = np.append(psd_all_c, psd_conn) t_AFC_all += [t_AFC_conn[:200]] AFC_all += [AFC_conn[:200]] t_AFC = np.mean(np.array(t_AFC_all), axis=0) AFC = np.mean(np.array(AFC_all), axis=0) # fig, ax = plt.subplots(figsize=(10,8)) # ax.plot(freq_conn, psd_conn, '.') # ax.set_xlim(0, Fs_spatial/2) # ax.set_ylim(0, psd[np.argsort(psd)[-2]]*2) # ax.set_xlabel('spatial frequency (1/count)') # ax.set_ylabel('PSD') fig, ax = plt.subplots(figsize=(10,8)) ax.plot(t_AFC, AFC, '-.') ax.set_xlim(0, 40) # ax.set_xlim(0, 100) # ax.set_ylim(0.000, 0.1) ax.set_xlabel('Distance (count)') ax.set_ylabel('Autocorrelation') fig, ax = plt.subplots(figsize=(10,8)) f = np.sort(freq_all_c) p = psd_all_c[np.argsort(freq_all_c)] ax.plot(MA(f,15,mode='silding'), MA(p,15,mode='silding'), '-') # ax.plot(f, p, '-') ax.set_xlim(0, 0.5) # ax.set_xlim(0, 100) ax.set_ylim(0.000, 5e7) ax.set_xlabel('Spatial frequency (1/count)') ax.set_ylabel('Power spectral density(a.u.)') ax.annotate(r'$\frac{1}{7.5}$', xy=(1/7.5, 3e7), xytext=(1/7.5, 5e7), arrowprops=dict(facecolor='black', shrink=0.05) ) plt.figure() plt.plot(signal_connect)
[ "matplotlib.pyplot.plot", "random.uniform", "matplotlib.rcParams.update", "numpy.isnan", "pandas.read_excel", "numpy.sort", "matplotlib.pyplot.figure", "numpy.append", "numpy.array", "numpy.argsort", "basic.filter.MA", "numpy.mean", "matplotlib.pyplot.subplots" ]
[((202, 236), 'matplotlib.rcParams.update', 'rcParams.update', (["{'font.size': 18}"], {}), "({'font.size': 18})\n", (217, 236), False, 'from matplotlib import rcParams\n'), ((1686, 1705), 'pandas.read_excel', 'pd.read_excel', (['path'], {}), '(path)\n', (1699, 1705), True, 'import pandas as pd\n'), ((2757, 2786), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(10, 8)'}), '(figsize=(10, 8))\n', (2769, 2786), True, 'import matplotlib.pyplot as plt\n'), ((2957, 2986), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(10, 8)'}), '(figsize=(10, 8))\n', (2969, 2986), True, 'import matplotlib.pyplot as plt\n'), ((2990, 3009), 'numpy.sort', 'np.sort', (['freq_all_c'], {}), '(freq_all_c)\n', (2997, 3009), True, 'import numpy as np\n'), ((3436, 3448), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (3446, 3448), True, 'import matplotlib.pyplot as plt\n'), ((3449, 3473), 'matplotlib.pyplot.plot', 'plt.plot', (['signal_connect'], {}), '(signal_connect)\n', (3457, 3473), True, 'import matplotlib.pyplot as plt\n'), ((2287, 2319), 'numpy.append', 'np.append', (['freq_all_c', 'freq_conn'], {}), '(freq_all_c, freq_conn)\n', (2296, 2319), True, 'import numpy as np\n'), ((2336, 2366), 'numpy.append', 'np.append', (['psd_all_c', 'psd_conn'], {}), '(psd_all_c, psd_conn)\n', (2345, 2366), True, 'import numpy as np\n'), ((2452, 2471), 'numpy.array', 'np.array', (['t_AFC_all'], {}), '(t_AFC_all)\n', (2460, 2471), True, 'import numpy as np\n'), ((2495, 2512), 'numpy.array', 'np.array', (['AFC_all'], {}), '(AFC_all)\n', (2503, 2512), True, 'import numpy as np\n'), ((3024, 3046), 'numpy.argsort', 'np.argsort', (['freq_all_c'], {}), '(freq_all_c)\n', (3034, 3046), True, 'import numpy as np\n'), ((3056, 3081), 'basic.filter.MA', 'MA', (['f', '(15)'], {'mode': '"""silding"""'}), "(f, 15, mode='silding')\n", (3058, 3081), False, 'from basic.filter import MA\n'), ((3081, 3106), 'basic.filter.MA', 'MA', (['p', '(15)'], {'mode': '"""silding"""'}), "(p, 15, mode='silding')\n", (3083, 3106), False, 'from basic.filter import MA\n'), ((1443, 1484), 'numpy.append', 'np.append', (['signal_connect', '(signal + L_cum)'], {}), '(signal_connect, signal + L_cum)\n', (1452, 1484), True, 'import numpy as np\n'), ((1500, 1521), 'numpy.mean', 'np.mean', (['signal[-20:]'], {}), '(signal[-20:])\n', (1507, 1521), True, 'import numpy as np\n'), ((2075, 2086), 'numpy.mean', 'np.mean', (['Fs'], {}), '(Fs)\n', (2082, 2086), True, 'import numpy as np\n'), ((592, 614), 'random.uniform', 'random.uniform', (['(0)', 'max'], {}), '(0, max)\n', (606, 614), False, 'import random\n'), ((1108, 1124), 'numpy.isnan', 'np.isnan', (['signal'], {}), '(signal)\n', (1116, 1124), True, 'import numpy as np\n')]
import copy import h5py import math import numpy as np import os import torch from torch.utils.data import Dataset import sys BASE_DIR = os.path.dirname(os.path.abspath(__file__)) ROOR_DIR = os.path.dirname(BASE_DIR) sys.path.append(ROOR_DIR) from utils import random_select_points, shift_point_cloud, jitter_point_cloud, \ generate_random_rotation_matrix, generate_random_tranlation_vector, \ transform, random_crop, shuffle_pc, random_scale_point_cloud, flip_pc half1 = ['airplane', 'bathtub', 'bed', 'bench', 'bookshelf', 'bottle', 'bowl', 'car', 'chair', 'cone', 'cup', 'curtain', 'desk', 'door', 'dresser', 'flower_pot', 'glass_box', 'guitar', 'keyboard', 'lamp'] half1_symmetric = ['bottle', 'bowl', 'cone', 'cup', 'flower_pot', 'lamp'] half2 = ['laptop', 'mantel', 'monitor', 'night_stand', 'person', 'piano', 'plant', 'radio', 'range_hood', 'sink', 'sofa', 'stairs', 'stool', 'table', 'tent', 'toilet', 'tv_stand', 'vase', 'wardrobe', 'xbox'] half2_symmetric = ['tent', 'vase'] class ModelNet40(Dataset): def __init__(self, root, split, npts, p_keep, noise, unseen, ao=False, normal=False): super(ModelNet40, self).__init__() self.single = False # for specific-class visualization assert split in ['train', 'val', 'test'] self.split = split self.npts = npts self.p_keep = p_keep self.noise = noise self.unseen = unseen self.ao = ao # Asymmetric Objects self.normal = normal self.half = half1 if split in 'train' else half2 self.symmetric = half1_symmetric + half2_symmetric self.label2cat, self.cat2label = self.label2category( os.path.join(root, 'shape_names.txt')) self.half_labels = [self.cat2label[cat] for cat in self.half] self.symmetric_labels = [self.cat2label[cat] for cat in self.symmetric] files = [os.path.join(root, 'ply_data_train{}.h5'.format(i)) for i in range(5)] if split == 'test': files = [os.path.join(root, 'ply_data_test{}.h5'.format(i)) for i in range(2)] self.data, self.labels = self.decode_h5(files) print(f'split: {self.split}, unique_ids: {len(np.unique(self.labels))}') if self.split == 'train': self.Rs = [generate_random_rotation_matrix() for _ in range(len(self.data))] self.ts = [generate_random_tranlation_vector() for _ in range(len(self.data))] def label2category(self, file): with open(file, 'r') as f: label2cat = [category.strip() for category in f.readlines()] cat2label = {label2cat[i]: i for i in range(len(label2cat))} return label2cat, cat2label def decode_h5(self, files): points, normal, label = [], [], [] for file in files: f = h5py.File(file, 'r') cur_points = f['data'][:].astype(np.float32) cur_normal = f['normal'][:].astype(np.float32) cur_label = f['label'][:].flatten().astype(np.int32) if self.unseen: idx = np.isin(cur_label, self.half_labels) cur_points = cur_points[idx] cur_normal = cur_normal[idx] cur_label = cur_label[idx] if self.ao and self.split in ['val', 'test']: idx = ~np.isin(cur_label, self.symmetric_labels) cur_points = cur_points[idx] cur_normal = cur_normal[idx] cur_label = cur_label[idx] if self.single: idx = np.isin(cur_label, [8]) cur_points = cur_points[idx] cur_normal = cur_normal[idx] cur_label = cur_label[idx] points.append(cur_points) normal.append(cur_normal) label.append(cur_label) points = np.concatenate(points, axis=0) normal = np.concatenate(normal, axis=0) data = np.concatenate([points, normal], axis=-1).astype(np.float32) label = np.concatenate(label, axis=0) return data, label def compose(self, item, p_keep): tgt_cloud = self.data[item, ...] if self.split != 'train': np.random.seed(item) R, t = generate_random_rotation_matrix(), generate_random_tranlation_vector() else: tgt_cloud = flip_pc(tgt_cloud) R, t = generate_random_rotation_matrix(), generate_random_tranlation_vector() src_cloud = random_crop(copy.deepcopy(tgt_cloud), p_keep=p_keep[0]) src_size = math.ceil(self.npts * p_keep[0]) tgt_size = self.npts if len(p_keep) > 1: tgt_cloud = random_crop(copy.deepcopy(tgt_cloud), p_keep=p_keep[1]) tgt_size = math.ceil(self.npts * p_keep[1]) src_cloud_points = transform(src_cloud[:, :3], R, t) src_cloud_normal = transform(src_cloud[:, 3:], R) src_cloud = np.concatenate([src_cloud_points, src_cloud_normal], axis=-1) src_cloud = random_select_points(src_cloud, m=src_size) tgt_cloud = random_select_points(tgt_cloud, m=tgt_size) if self.split == 'train' or self.noise: src_cloud[:, :3] = jitter_point_cloud(src_cloud[:, :3]) tgt_cloud[:, :3] = jitter_point_cloud(tgt_cloud[:, :3]) tgt_cloud, src_cloud = shuffle_pc(tgt_cloud), shuffle_pc( src_cloud) return src_cloud, tgt_cloud, R, t def __getitem__(self, item): src_cloud, tgt_cloud, R, t = self.compose(item=item, p_keep=self.p_keep) if not self.normal: tgt_cloud, src_cloud = tgt_cloud[:, :3], src_cloud[:, :3] return tgt_cloud, src_cloud, R, t def __len__(self): return len(self.data)
[ "sys.path.append", "numpy.isin", "os.path.abspath", "h5py.File", "numpy.random.seed", "copy.deepcopy", "math.ceil", "os.path.dirname", "utils.generate_random_rotation_matrix", "utils.generate_random_tranlation_vector", "numpy.unique", "utils.jitter_point_cloud", "utils.shuffle_pc", "utils....
[((193, 218), 'os.path.dirname', 'os.path.dirname', (['BASE_DIR'], {}), '(BASE_DIR)\n', (208, 218), False, 'import os\n'), ((219, 244), 'sys.path.append', 'sys.path.append', (['ROOR_DIR'], {}), '(ROOR_DIR)\n', (234, 244), False, 'import sys\n'), ((155, 180), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (170, 180), False, 'import os\n'), ((3897, 3927), 'numpy.concatenate', 'np.concatenate', (['points'], {'axis': '(0)'}), '(points, axis=0)\n', (3911, 3927), True, 'import numpy as np\n'), ((3945, 3975), 'numpy.concatenate', 'np.concatenate', (['normal'], {'axis': '(0)'}), '(normal, axis=0)\n', (3959, 3975), True, 'import numpy as np\n'), ((4068, 4097), 'numpy.concatenate', 'np.concatenate', (['label'], {'axis': '(0)'}), '(label, axis=0)\n', (4082, 4097), True, 'import numpy as np\n'), ((4604, 4636), 'math.ceil', 'math.ceil', (['(self.npts * p_keep[0])'], {}), '(self.npts * p_keep[0])\n', (4613, 4636), False, 'import math\n'), ((4894, 4927), 'utils.transform', 'transform', (['src_cloud[:, :3]', 'R', 't'], {}), '(src_cloud[:, :3], R, t)\n', (4903, 4927), False, 'from utils import random_select_points, shift_point_cloud, jitter_point_cloud, generate_random_rotation_matrix, generate_random_tranlation_vector, transform, random_crop, shuffle_pc, random_scale_point_cloud, flip_pc\n'), ((4955, 4985), 'utils.transform', 'transform', (['src_cloud[:, 3:]', 'R'], {}), '(src_cloud[:, 3:], R)\n', (4964, 4985), False, 'from utils import random_select_points, shift_point_cloud, jitter_point_cloud, generate_random_rotation_matrix, generate_random_tranlation_vector, transform, random_crop, shuffle_pc, random_scale_point_cloud, flip_pc\n'), ((5006, 5067), 'numpy.concatenate', 'np.concatenate', (['[src_cloud_points, src_cloud_normal]'], {'axis': '(-1)'}), '([src_cloud_points, src_cloud_normal], axis=-1)\n', (5020, 5067), True, 'import numpy as np\n'), ((5123, 5166), 'utils.random_select_points', 'random_select_points', (['src_cloud'], {'m': 'src_size'}), '(src_cloud, m=src_size)\n', (5143, 5166), False, 'from utils import random_select_points, shift_point_cloud, jitter_point_cloud, generate_random_rotation_matrix, generate_random_tranlation_vector, transform, random_crop, shuffle_pc, random_scale_point_cloud, flip_pc\n'), ((5187, 5230), 'utils.random_select_points', 'random_select_points', (['tgt_cloud'], {'m': 'tgt_size'}), '(tgt_cloud, m=tgt_size)\n', (5207, 5230), False, 'from utils import random_select_points, shift_point_cloud, jitter_point_cloud, generate_random_rotation_matrix, generate_random_tranlation_vector, transform, random_crop, shuffle_pc, random_scale_point_cloud, flip_pc\n'), ((1725, 1762), 'os.path.join', 'os.path.join', (['root', '"""shape_names.txt"""'], {}), "(root, 'shape_names.txt')\n", (1737, 1762), False, 'import os\n'), ((2883, 2903), 'h5py.File', 'h5py.File', (['file', '"""r"""'], {}), "(file, 'r')\n", (2892, 2903), False, 'import h5py\n'), ((4250, 4270), 'numpy.random.seed', 'np.random.seed', (['item'], {}), '(item)\n', (4264, 4270), True, 'import numpy as np\n'), ((4399, 4417), 'utils.flip_pc', 'flip_pc', (['tgt_cloud'], {}), '(tgt_cloud)\n', (4406, 4417), False, 'from utils import random_select_points, shift_point_cloud, jitter_point_cloud, generate_random_rotation_matrix, generate_random_tranlation_vector, transform, random_crop, shuffle_pc, random_scale_point_cloud, flip_pc\n'), ((4541, 4565), 'copy.deepcopy', 'copy.deepcopy', (['tgt_cloud'], {}), '(tgt_cloud)\n', (4554, 4565), False, 'import copy\n'), ((4833, 4865), 'math.ceil', 'math.ceil', (['(self.npts * p_keep[1])'], {}), '(self.npts * p_keep[1])\n', (4842, 4865), False, 'import math\n'), ((5311, 5347), 'utils.jitter_point_cloud', 'jitter_point_cloud', (['src_cloud[:, :3]'], {}), '(src_cloud[:, :3])\n', (5329, 5347), False, 'from utils import random_select_points, shift_point_cloud, jitter_point_cloud, generate_random_rotation_matrix, generate_random_tranlation_vector, transform, random_crop, shuffle_pc, random_scale_point_cloud, flip_pc\n'), ((5379, 5415), 'utils.jitter_point_cloud', 'jitter_point_cloud', (['tgt_cloud[:, :3]'], {}), '(tgt_cloud[:, :3])\n', (5397, 5415), False, 'from utils import random_select_points, shift_point_cloud, jitter_point_cloud, generate_random_rotation_matrix, generate_random_tranlation_vector, transform, random_crop, shuffle_pc, random_scale_point_cloud, flip_pc\n'), ((5447, 5468), 'utils.shuffle_pc', 'shuffle_pc', (['tgt_cloud'], {}), '(tgt_cloud)\n', (5457, 5468), False, 'from utils import random_select_points, shift_point_cloud, jitter_point_cloud, generate_random_rotation_matrix, generate_random_tranlation_vector, transform, random_crop, shuffle_pc, random_scale_point_cloud, flip_pc\n'), ((5470, 5491), 'utils.shuffle_pc', 'shuffle_pc', (['src_cloud'], {}), '(src_cloud)\n', (5480, 5491), False, 'from utils import random_select_points, shift_point_cloud, jitter_point_cloud, generate_random_rotation_matrix, generate_random_tranlation_vector, transform, random_crop, shuffle_pc, random_scale_point_cloud, flip_pc\n'), ((2353, 2386), 'utils.generate_random_rotation_matrix', 'generate_random_rotation_matrix', ([], {}), '()\n', (2384, 2386), False, 'from utils import random_select_points, shift_point_cloud, jitter_point_cloud, generate_random_rotation_matrix, generate_random_tranlation_vector, transform, random_crop, shuffle_pc, random_scale_point_cloud, flip_pc\n'), ((2442, 2477), 'utils.generate_random_tranlation_vector', 'generate_random_tranlation_vector', ([], {}), '()\n', (2475, 2477), False, 'from utils import random_select_points, shift_point_cloud, jitter_point_cloud, generate_random_rotation_matrix, generate_random_tranlation_vector, transform, random_crop, shuffle_pc, random_scale_point_cloud, flip_pc\n'), ((3135, 3171), 'numpy.isin', 'np.isin', (['cur_label', 'self.half_labels'], {}), '(cur_label, self.half_labels)\n', (3142, 3171), True, 'import numpy as np\n'), ((3611, 3634), 'numpy.isin', 'np.isin', (['cur_label', '[8]'], {}), '(cur_label, [8])\n', (3618, 3634), True, 'import numpy as np\n'), ((3991, 4032), 'numpy.concatenate', 'np.concatenate', (['[points, normal]'], {'axis': '(-1)'}), '([points, normal], axis=-1)\n', (4005, 4032), True, 'import numpy as np\n'), ((4290, 4323), 'utils.generate_random_rotation_matrix', 'generate_random_rotation_matrix', ([], {}), '()\n', (4321, 4323), False, 'from utils import random_select_points, shift_point_cloud, jitter_point_cloud, generate_random_rotation_matrix, generate_random_tranlation_vector, transform, random_crop, shuffle_pc, random_scale_point_cloud, flip_pc\n'), ((4325, 4360), 'utils.generate_random_tranlation_vector', 'generate_random_tranlation_vector', ([], {}), '()\n', (4358, 4360), False, 'from utils import random_select_points, shift_point_cloud, jitter_point_cloud, generate_random_rotation_matrix, generate_random_tranlation_vector, transform, random_crop, shuffle_pc, random_scale_point_cloud, flip_pc\n'), ((4437, 4470), 'utils.generate_random_rotation_matrix', 'generate_random_rotation_matrix', ([], {}), '()\n', (4468, 4470), False, 'from utils import random_select_points, shift_point_cloud, jitter_point_cloud, generate_random_rotation_matrix, generate_random_tranlation_vector, transform, random_crop, shuffle_pc, random_scale_point_cloud, flip_pc\n'), ((4472, 4507), 'utils.generate_random_tranlation_vector', 'generate_random_tranlation_vector', ([], {}), '()\n', (4505, 4507), False, 'from utils import random_select_points, shift_point_cloud, jitter_point_cloud, generate_random_rotation_matrix, generate_random_tranlation_vector, transform, random_crop, shuffle_pc, random_scale_point_cloud, flip_pc\n'), ((4730, 4754), 'copy.deepcopy', 'copy.deepcopy', (['tgt_cloud'], {}), '(tgt_cloud)\n', (4743, 4754), False, 'import copy\n'), ((3386, 3427), 'numpy.isin', 'np.isin', (['cur_label', 'self.symmetric_labels'], {}), '(cur_label, self.symmetric_labels)\n', (3393, 3427), True, 'import numpy as np\n'), ((2268, 2290), 'numpy.unique', 'np.unique', (['self.labels'], {}), '(self.labels)\n', (2277, 2290), True, 'import numpy as np\n')]
from astropy.table import Table from astropy.io import fits from GPSTiming.interpolation import interpolate_boardtimes from numpy import diff def test_time_differences_greater_zero(path: str): fits_file = fits.open(path) table = Table(fits_file[1].data) fits_file.close() table = interpolate_boardtimes(table) assert diff(table["InterpolatedUnixTime"]).all() > 0 def main(): path = '/net/big-tank/POOL/projects/fact/gps_timestamp_data/2014/01/01/20140101_073_v1.1.1_gps_timestamp_data_timestamps.fits' test_time_differences_greater_zero(path) if __name__ == "__main__": main()
[ "numpy.diff", "astropy.table.Table", "astropy.io.fits.open", "GPSTiming.interpolation.interpolate_boardtimes" ]
[((211, 226), 'astropy.io.fits.open', 'fits.open', (['path'], {}), '(path)\n', (220, 226), False, 'from astropy.io import fits\n'), ((239, 263), 'astropy.table.Table', 'Table', (['fits_file[1].data'], {}), '(fits_file[1].data)\n', (244, 263), False, 'from astropy.table import Table\n'), ((298, 327), 'GPSTiming.interpolation.interpolate_boardtimes', 'interpolate_boardtimes', (['table'], {}), '(table)\n', (320, 327), False, 'from GPSTiming.interpolation import interpolate_boardtimes\n'), ((339, 374), 'numpy.diff', 'diff', (["table['InterpolatedUnixTime']"], {}), "(table['InterpolatedUnixTime'])\n", (343, 374), False, 'from numpy import diff\n')]
import matplotlib.pyplot as plt import matplotlib.cm as cm import numpy as np class TransitionPlot: N_COL = 8 OBJ_NAMES = ['BG', 'SQ', 'SC', 'BQ', 'BC', 'P1', 'P2', 'P3', 'P4'] def __init__(self, num_obj_slots): assert num_obj_slots in (4,8,9) self.COLORS = [cm.rainbow(x) for x in np.linspace(0, 1, num_obj_slots)] self.OBJ_ROW = np.ceil(num_obj_slots / 4).astype(np.int32) self.N_ROW = 4 + self.OBJ_ROW + 8 self.FIGURE_SIZE = (self.N_COL*2, self.N_ROW*2) print(num_obj_slots) plt.subplots(figsize=self.FIGURE_SIZE) self.obs_axs = [] self.act_axs = [] self.latent_axs = [] self.obj_axs = [] self.next_obj_axs = [] for i in [0, 3]: self.obs_axs.append( plt.subplot2grid( shape=(self.N_ROW, self.N_COL), loc=(0, i*2), colspan=2, rowspan=2 ) ) for i in [1, 2]: self.act_axs.append( plt.subplot2grid( shape=(self.N_ROW, self.N_COL), loc=(0, i*2), colspan=2, rowspan=2 ) ) for i in range(self.OBJ_ROW): for j in range(4): self.obj_axs.append( plt.subplot2grid(shape=(self.N_ROW, self.N_COL), loc=(2 + i, 0 + j), colspan=1, rowspan=1) ) self.next_obj_axs.append( plt.subplot2grid(shape=(self.N_ROW, self.N_COL), loc=(2 + i, 4 + j), colspan=1, rowspan=1) ) self.latent_axs.append( plt.subplot2grid( shape=(self.N_ROW, self.N_COL), loc=(2 + self.OBJ_ROW, 0), colspan=4, rowspan=4 ) ) self.latent_axs.append( plt.subplot2grid( shape=(self.N_ROW, self.N_COL), loc=(2 + self.OBJ_ROW, 4), colspan=4, rowspan=4 ) ) self.latent_axs.append( plt.subplot2grid( shape=(self.N_ROW, self.N_COL), loc=(2 + self.OBJ_ROW + 4, 4), colspan=4, rowspan=4 ) ) plt.tight_layout() def reset(self): for ax in self.obs_axs + self.act_axs + self.latent_axs + self.obj_axs + self.next_obj_axs: ax.cla() for ax in self.obj_axs + self.next_obj_axs + self.act_axs + self.obs_axs: ax.axis('off') for i in range(3): self.latent_axs[i].set_xlim(-5, 5) self.latent_axs[i].set_ylim(-5, 5) self.latent_axs[0].set_title("Pre State Latent", fontsize=6) self.latent_axs[1].set_title("Next State Latent", fontsize=6) self.latent_axs[2].set_title("Pre State Latent +\n Transition", fontsize=6) self.obs_axs[0].set_title("Pre State Latent", fontsize=6) self.obs_axs[1].set_title("Next State Latent", fontsize=6) self.act_axs[0].set_title("Action Moving Object", fontsize=6) self.act_axs[1].set_title("Action Target Object", fontsize=6) def plt_observations(self, obs, next_obs): np_obs = np.transpose(obs[0].cpu().numpy(), (1,2,0)) np_next_obs = np.transpose(next_obs[0].cpu().numpy(), (1,2,0)) # print(np_obs.shape, np_next_obs.shape) self.obs_axs[0].imshow(np_obs) self.obs_axs[1].imshow(np_next_obs) def plt_action(self, action): np_mov_obj = np.transpose(action[0][0].cpu().numpy(), (1,2,0)) np_tar_obj = np.transpose(action[0][1].cpu().numpy(), (1,2,0)) # print(np_obs.shape, np_next_obs.shape) self.act_axs[0].imshow(np_mov_obj) self.act_axs[1].imshow(np_tar_obj) def plt_objects(self, objs, next_objs): for i in range(objs.size()[1]): np_obj = np.transpose(objs[0][i].cpu().numpy(), (1,2,0)) np_next_obj = np.transpose(next_objs[0][i].cpu().numpy(), (1,2,0)) self.obj_axs[i].imshow(np_obj) self.next_obj_axs[i].imshow(np_next_obj) def plt_latent(self, state, next_state, pred_state): legend = [[], [], []] for i in range(state.size()[1]): np_state = state[0][i].cpu().numpy() np_next_state = next_state[0][i].cpu().numpy() np_pred_state = pred_state[0][i].cpu().numpy() # if i == 0: # print(np_state, np_next_state, np_pred_state) # print("-*40") self.latent_axs[0].scatter(np_state[0], np_state[1], color=self.COLORS[i], marker='x', s=10) self.latent_axs[1].scatter(np_next_state[0], np_next_state[1], color=self.COLORS[i], marker='x', s=10) self.latent_axs[2].scatter(np_pred_state[0], np_pred_state[1], color=self.COLORS[i], marker='x', s=10) # for j, st in enumerate([np_state, np_next_state, np_pred_state]): legend[j].append("{}-({:.2f},{:.2f})".format(self.OBJ_NAMES[i], st[0], st[1])) for ax, lgd in zip(self.latent_axs, legend): ax.legend(lgd, prop={'size': 6}, loc=2, ncol=2) def show(self, interval=0.5): plt.pause(interval) def close(self): plt.close()
[ "numpy.ceil", "matplotlib.pyplot.close", "matplotlib.pyplot.subplot2grid", "matplotlib.pyplot.subplots", "matplotlib.cm.rainbow", "matplotlib.pyplot.pause", "numpy.linspace", "matplotlib.pyplot.tight_layout" ]
[((549, 587), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': 'self.FIGURE_SIZE'}), '(figsize=self.FIGURE_SIZE)\n', (561, 587), True, 'import matplotlib.pyplot as plt\n'), ((2120, 2138), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (2136, 2138), True, 'import matplotlib.pyplot as plt\n'), ((5057, 5076), 'matplotlib.pyplot.pause', 'plt.pause', (['interval'], {}), '(interval)\n', (5066, 5076), True, 'import matplotlib.pyplot as plt\n'), ((5107, 5118), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (5116, 5118), True, 'import matplotlib.pyplot as plt\n'), ((290, 303), 'matplotlib.cm.rainbow', 'cm.rainbow', (['x'], {}), '(x)\n', (300, 303), True, 'import matplotlib.cm as cm\n'), ((1603, 1704), 'matplotlib.pyplot.subplot2grid', 'plt.subplot2grid', ([], {'shape': '(self.N_ROW, self.N_COL)', 'loc': '(2 + self.OBJ_ROW, 0)', 'colspan': '(4)', 'rowspan': '(4)'}), '(shape=(self.N_ROW, self.N_COL), loc=(2 + self.OBJ_ROW, 0),\n colspan=4, rowspan=4)\n', (1619, 1704), True, 'import matplotlib.pyplot as plt\n'), ((1786, 1887), 'matplotlib.pyplot.subplot2grid', 'plt.subplot2grid', ([], {'shape': '(self.N_ROW, self.N_COL)', 'loc': '(2 + self.OBJ_ROW, 4)', 'colspan': '(4)', 'rowspan': '(4)'}), '(shape=(self.N_ROW, self.N_COL), loc=(2 + self.OBJ_ROW, 4),\n colspan=4, rowspan=4)\n', (1802, 1887), True, 'import matplotlib.pyplot as plt\n'), ((1969, 2074), 'matplotlib.pyplot.subplot2grid', 'plt.subplot2grid', ([], {'shape': '(self.N_ROW, self.N_COL)', 'loc': '(2 + self.OBJ_ROW + 4, 4)', 'colspan': '(4)', 'rowspan': '(4)'}), '(shape=(self.N_ROW, self.N_COL), loc=(2 + self.OBJ_ROW + 4,\n 4), colspan=4, rowspan=4)\n', (1985, 2074), True, 'import matplotlib.pyplot as plt\n'), ((313, 345), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', 'num_obj_slots'], {}), '(0, 1, num_obj_slots)\n', (324, 345), True, 'import numpy as np\n'), ((370, 396), 'numpy.ceil', 'np.ceil', (['(num_obj_slots / 4)'], {}), '(num_obj_slots / 4)\n', (377, 396), True, 'import numpy as np\n'), ((801, 891), 'matplotlib.pyplot.subplot2grid', 'plt.subplot2grid', ([], {'shape': '(self.N_ROW, self.N_COL)', 'loc': '(0, i * 2)', 'colspan': '(2)', 'rowspan': '(2)'}), '(shape=(self.N_ROW, self.N_COL), loc=(0, i * 2), colspan=2,\n rowspan=2)\n', (817, 891), True, 'import matplotlib.pyplot as plt\n'), ((1013, 1103), 'matplotlib.pyplot.subplot2grid', 'plt.subplot2grid', ([], {'shape': '(self.N_ROW, self.N_COL)', 'loc': '(0, i * 2)', 'colspan': '(2)', 'rowspan': '(2)'}), '(shape=(self.N_ROW, self.N_COL), loc=(0, i * 2), colspan=2,\n rowspan=2)\n', (1029, 1103), True, 'import matplotlib.pyplot as plt\n'), ((1277, 1371), 'matplotlib.pyplot.subplot2grid', 'plt.subplot2grid', ([], {'shape': '(self.N_ROW, self.N_COL)', 'loc': '(2 + i, 0 + j)', 'colspan': '(1)', 'rowspan': '(1)'}), '(shape=(self.N_ROW, self.N_COL), loc=(2 + i, 0 + j),\n colspan=1, rowspan=1)\n', (1293, 1371), True, 'import matplotlib.pyplot as plt\n'), ((1448, 1542), 'matplotlib.pyplot.subplot2grid', 'plt.subplot2grid', ([], {'shape': '(self.N_ROW, self.N_COL)', 'loc': '(2 + i, 4 + j)', 'colspan': '(1)', 'rowspan': '(1)'}), '(shape=(self.N_ROW, self.N_COL), loc=(2 + i, 4 + j),\n colspan=1, rowspan=1)\n', (1464, 1542), True, 'import matplotlib.pyplot as plt\n')]
import time import numpy as np import mxnet as mx import matplotlib.pyplot as plt from mxnet import nd from mxnet import autograd from mxnet import gluon from mxnet.gluon import nn def gpu_exists(): try: mx.nd.zeros((1, ), ctx=mx.gpu(0)) except: return False return True data_ctx = mx.cpu() if gpu_exists(): print("Using GPU for model context.") model_ctx = mx.gpu(0) else: print("Using CPU for model context.") model_ctx = mx.cpu(0) mx.random.seed(1) # %% # Load MNIST mnist_data = mx.test_utils.get_mnist() n_samples = 10 def show_samples(n_samples, mnist_data): idx_list = np.random.choice(len(mnist_data["train_data"]), n_samples) fig, axs = plt.subplots(1, n_samples) for i, j in enumerate(idx_list): axs[i].imshow(mnist_data["train_data"][j][0], cmap="Greys") axs[i].get_xaxis().set_ticks([]) axs[i].get_yaxis().set_ticks([]) plt.show() train_data = np.reshape(mnist_data["train_data"], (-1, 28*28)) test_data = np.reshape(mnist_data["test_data"], (-1, 28*28)) class VAE(gluon.HybridBlock): def __init__(self, n_hidden=400, n_latent=2, n_layers=1, n_output=768, batch_size=100): # TODO Continue implementation pass
[ "matplotlib.pyplot.show", "mxnet.random.seed", "mxnet.test_utils.get_mnist", "numpy.reshape", "mxnet.cpu", "mxnet.gpu", "matplotlib.pyplot.subplots" ]
[((314, 322), 'mxnet.cpu', 'mx.cpu', ([], {}), '()\n', (320, 322), True, 'import mxnet as mx\n'), ((484, 501), 'mxnet.random.seed', 'mx.random.seed', (['(1)'], {}), '(1)\n', (498, 501), True, 'import mxnet as mx\n'), ((535, 560), 'mxnet.test_utils.get_mnist', 'mx.test_utils.get_mnist', ([], {}), '()\n', (558, 560), True, 'import mxnet as mx\n'), ((953, 1004), 'numpy.reshape', 'np.reshape', (["mnist_data['train_data']", '(-1, 28 * 28)'], {}), "(mnist_data['train_data'], (-1, 28 * 28))\n", (963, 1004), True, 'import numpy as np\n'), ((1015, 1065), 'numpy.reshape', 'np.reshape', (["mnist_data['test_data']", '(-1, 28 * 28)'], {}), "(mnist_data['test_data'], (-1, 28 * 28))\n", (1025, 1065), True, 'import numpy as np\n'), ((399, 408), 'mxnet.gpu', 'mx.gpu', (['(0)'], {}), '(0)\n', (405, 408), True, 'import mxnet as mx\n'), ((473, 482), 'mxnet.cpu', 'mx.cpu', (['(0)'], {}), '(0)\n', (479, 482), True, 'import mxnet as mx\n'), ((709, 735), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', 'n_samples'], {}), '(1, n_samples)\n', (721, 735), True, 'import matplotlib.pyplot as plt\n'), ((927, 937), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (935, 937), True, 'import matplotlib.pyplot as plt\n'), ((241, 250), 'mxnet.gpu', 'mx.gpu', (['(0)'], {}), '(0)\n', (247, 250), True, 'import mxnet as mx\n')]
#!/usr/bin/env python3 import os import sys import importlib import h5py import random import numpy as np from argparse import ArgumentParser def main(): args = parse_args() if not importlib.util.find_spec('chimeranet'): print('ChimeraNet is not installed, import from source.') sys.path.append(os.path.join(os.path.split(__file__)[0], '..')) from keras.callbacks import Callback, CSVLogger from chimeranet.models import probe_model_shape, load_model, ChimeraPPModel class NameDataset(Callback): def __init__(self, name, val_name=None): self.name = name self.val_name = val_name def on_epoch_end(self, epoch, logs): logs['dataset'] = self.name logs['val_dataset'] = self.val_name with h5py.File(args.train_data, 'r') as f: _, T, F, C = f['y/embedding'].shape # build/load model if args.input_model is not None: T_, F_, C_, D_ = probe_model_shape(args.input_model) assert T == T_ and F == F_ and C == C_,\ 'Incompatible dataset with the model' model = load_model(args.input_model) else: cm = ChimeraPPModel(T, F, C, args.embedding_dims) model = cm.build_model() model.compile( 'rmsprop', loss={ 'embedding': cm.loss_deepclustering(), 'mask': cm.loss_mask() }, loss_weights={ 'embedding': 0.9, 'mask': 0.1 } ) # train train_generator = generate_data( args.train_data, args.batch_size, shuffle=True) train_steps = get_dataset_size( args.train_data) // args.batch_size if args.validation_data: validation_generator = generate_data( args.validation_data, args.batch_size) validation_steps = get_dataset_size( args.validation_data) // args.batch_size else: validation_generator = None validation_steps = None model.fit_generator( train_generator, steps_per_epoch=train_steps, validation_data=validation_generator, validation_steps=validation_steps, initial_epoch=args.initial_epoch, epochs=args.stop_epoch, callbacks=[ NameDataset(args.train_data, args.validation_data), CSVLogger(args.log, append=args.initial_epoch > 0), ], ) model.save(args.output_model) def get_dataset_size(filename): with h5py.File(filename, 'r') as f: sample_size = f['x'].shape[0] return sample_size def generate_data(filename, batch_size, shuffle=False): while True: for x, y in generate_data_one(filename, batch_size, shuffle): yield x, y def generate_data_one(filename, batch_size, shuffle=False): with h5py.File(filename, 'r') as f: sample_size = get_dataset_size(filename) sample_idx = list(range(sample_size)) if shuffle: random.shuffle(sample_idx) sample_idxs = [ sorted(sample_idx[batch_i*batch_size:(batch_i+1)*batch_size]) for batch_i in range(sample_size // batch_size) ] for sample_idx in sample_idxs: x = f['x'][sample_idx] y = dict( (k, f['y/{}'.format(k)][sample_idx]) for k in ('mask', 'embedding') ) if shuffle: idx = np.arange(batch_size) np.random.shuffle(idx) x = x[idx] y = dict((k, v[idx]) for k, v in y.items()) yield x, y def parse_args(): parser = ArgumentParser() parser.add_argument( '-i', '--train-data', type=str, required=True, metavar='PATH', help='Train dataset path' ) parser.add_argument( '-o', '--output-model', type=str, required=True, metavar='PATH', help='Output model path' ) parser.add_argument( '-m', '--input-model', type=str, metavar='PATH', help='Input model path (train from this model)' ) parser.add_argument( '-d', '--embedding-dims', type=int, default=20, metavar='D', help='Dimension of embedding, ignored -m is given (default=20)' ) parser.add_argument( '-b', '--batch-size', type=int, default=32, metavar='B', help='Batch size of train/validation' ) parser.add_argument( '--validation-data', type=str, metavar='PATH', help='Validation dtaset path' ) parser.add_argument( '--log', type=str, metavar='PATH', help='Log path' ) parser.add_argument( '--stop-epoch', type=int, default=None, metavar='N', help='Train stops on this epoch (default=initial_epoch+1)' ) parser.add_argument( '--initial-epoch', type=int, default=0, metavar='N', help='Train starts on this epoch (default=0)' ) args = parser.parse_args() if args.stop_epoch is None: args.stop_epoch = args.initial_epoch + 1 return args if __name__ == '__main__': main()
[ "chimeranet.models.ChimeraPPModel", "chimeranet.models.probe_model_shape", "h5py.File", "chimeranet.models.load_model", "argparse.ArgumentParser", "importlib.util.find_spec", "random.shuffle", "numpy.arange", "keras.callbacks.CSVLogger", "os.path.split", "numpy.random.shuffle" ]
[((3651, 3667), 'argparse.ArgumentParser', 'ArgumentParser', ([], {}), '()\n', (3665, 3667), False, 'from argparse import ArgumentParser\n'), ((192, 230), 'importlib.util.find_spec', 'importlib.util.find_spec', (['"""chimeranet"""'], {}), "('chimeranet')\n", (216, 230), False, 'import importlib\n'), ((794, 825), 'h5py.File', 'h5py.File', (['args.train_data', '"""r"""'], {}), "(args.train_data, 'r')\n", (803, 825), False, 'import h5py\n'), ((962, 997), 'chimeranet.models.probe_model_shape', 'probe_model_shape', (['args.input_model'], {}), '(args.input_model)\n', (979, 997), False, 'from chimeranet.models import probe_model_shape, load_model, ChimeraPPModel\n'), ((1113, 1141), 'chimeranet.models.load_model', 'load_model', (['args.input_model'], {}), '(args.input_model)\n', (1123, 1141), False, 'from chimeranet.models import probe_model_shape, load_model, ChimeraPPModel\n'), ((1165, 1209), 'chimeranet.models.ChimeraPPModel', 'ChimeraPPModel', (['T', 'F', 'C', 'args.embedding_dims'], {}), '(T, F, C, args.embedding_dims)\n', (1179, 1209), False, 'from chimeranet.models import probe_model_shape, load_model, ChimeraPPModel\n'), ((2511, 2535), 'h5py.File', 'h5py.File', (['filename', '"""r"""'], {}), "(filename, 'r')\n", (2520, 2535), False, 'import h5py\n'), ((2839, 2863), 'h5py.File', 'h5py.File', (['filename', '"""r"""'], {}), "(filename, 'r')\n", (2848, 2863), False, 'import h5py\n'), ((2997, 3023), 'random.shuffle', 'random.shuffle', (['sample_idx'], {}), '(sample_idx)\n', (3011, 3023), False, 'import random\n'), ((2366, 2416), 'keras.callbacks.CSVLogger', 'CSVLogger', (['args.log'], {'append': '(args.initial_epoch > 0)'}), '(args.log, append=args.initial_epoch > 0)\n', (2375, 2416), False, 'from keras.callbacks import Callback, CSVLogger\n'), ((3448, 3469), 'numpy.arange', 'np.arange', (['batch_size'], {}), '(batch_size)\n', (3457, 3469), True, 'import numpy as np\n'), ((3486, 3508), 'numpy.random.shuffle', 'np.random.shuffle', (['idx'], {}), '(idx)\n', (3503, 3508), True, 'import numpy as np\n'), ((335, 358), 'os.path.split', 'os.path.split', (['__file__'], {}), '(__file__)\n', (348, 358), False, 'import os\n')]
import numpy as np import time from tscc.optimization.optimizescale import optimizescale # add constraints according to the a,b,c coefficients of quadratic function def computescale(a, b, c, iters, stateRobo, limitsRobo, weightSlack, guessScale, deltaT): nObst = len(a) for i in range(iters): listLeft = [] listRight = [] for j in range(nObst): # concave case that leads to linearization if (a[j] <= 0 and c[j] <= 0 and b[j] >= 0): tempLeft = (a[j] + b[j]/(2*guessScale)) tempRight = - (c[j] + (b[j]/2.0)*guessScale) listLeft.append(tempLeft) listRight.append(tempRight) # convex case with a as coefficient of s^2 elif (a[j] >= 0): root1 = (-b[j] + np.sqrt(b[j]**2 - 4*a[j]*c[j]))/(2*a[j]) root2 = (-b[j] - np.sqrt(b[j]**2 - 4*a[j]*c[j]))/(2*a[j]) scaleMax = max(root1, root2) scaleMin = min(root1, root2) if (scaleMin >= 0): listLeft.append(-1.0) listRight.append(-1*scaleMin**2) listLeft.append(1.0) listRight.append(scaleMax**2) else: if (scaleMax < 0): raise ValueError('Invalid constraint') else: listLeft.append(1.0) listRight.append(scaleMax**2) # convex case with c as coefficient of (1/s)^2 elif (a[j] <= 0 and c[j] >= 0): root1 = (-b[j] + np.sqrt(b[j]**2 - 4*a[j]*c[j]))/(2*a[j]) root2 = (-b[j] - np.sqrt(b[j]**2 - 4*a[j]*c[j]))/(2*a[j]) scaleMax = max(root1, root2) scaleMin = min(root1, root2) if(scaleMin > 0): listLeft.append(-1.0) listRight.append(-1.0/scaleMin**2) listLeft.append(1.0) listRight.append(1.0/scaleMax**2) else: if (scaleMax <= 0): raise ValueError('Invalid constraint') else: listLeft.append(1.0) listRight.append(1/scaleMax**2) # satisfied for any scale greater than zero, so no constriants else: pass guessScale = optimizescale(listLeft, listRight, stateRobo, limitsRobo, weightSlack, deltaT) return guessScale
[ "tscc.optimization.optimizescale.optimizescale", "numpy.sqrt" ]
[((2468, 2546), 'tscc.optimization.optimizescale.optimizescale', 'optimizescale', (['listLeft', 'listRight', 'stateRobo', 'limitsRobo', 'weightSlack', 'deltaT'], {}), '(listLeft, listRight, stateRobo, limitsRobo, weightSlack, deltaT)\n', (2481, 2546), False, 'from tscc.optimization.optimizescale import optimizescale\n'), ((833, 869), 'numpy.sqrt', 'np.sqrt', (['(b[j] ** 2 - 4 * a[j] * c[j])'], {}), '(b[j] ** 2 - 4 * a[j] * c[j])\n', (840, 869), True, 'import numpy as np\n'), ((907, 943), 'numpy.sqrt', 'np.sqrt', (['(b[j] ** 2 - 4 * a[j] * c[j])'], {}), '(b[j] ** 2 - 4 * a[j] * c[j])\n', (914, 943), True, 'import numpy as np\n'), ((1647, 1683), 'numpy.sqrt', 'np.sqrt', (['(b[j] ** 2 - 4 * a[j] * c[j])'], {}), '(b[j] ** 2 - 4 * a[j] * c[j])\n', (1654, 1683), True, 'import numpy as np\n'), ((1721, 1757), 'numpy.sqrt', 'np.sqrt', (['(b[j] ** 2 - 4 * a[j] * c[j])'], {}), '(b[j] ** 2 - 4 * a[j] * c[j])\n', (1728, 1757), True, 'import numpy as np\n')]
#!/usr/bin/env python """plots.py: plots utility functions.""" __author__ = "<NAME>." __copyright__ = "Copyright 2020, SuperDARN@VT" __credits__ = [] __license__ = "MIT" __version__ = "1.0" __maintainer__ = "<NAME>." __email__ = "<EMAIL>" __status__ = "Research" import os import sys sys.path.extend(["code/", "code/rt/", "code/sd/"]) import matplotlib as mpl import matplotlib.pyplot as plt from matplotlib.collections import LineCollection import matplotlib.dates as mdates import plot_utils from matplotlib.colors import LogNorm import numpy import pydarn import datetime as dt import pickle import numpy as np class TracePlots(object): """ Plot ray-traced using .pickle files stored under data/{date}/{rad}/ folder """ def __init__(self, ev, rad, bm, f, dstart, dend): self.ev = ev self.rad = rad self.freq = f self.bm = bm self.folder = "data/{dn}/{rad}/".format(dn=ev.strftime("%Y-%m-%d"), rad=rad) file = self.folder + "%s_%s_%d.pickle"%(dstart.strftime("%H%M"), dend.strftime("%H%M"), f) with open(file, "rb") as f: self.rdict = pickle.load(f) self.dstart, self.dend = dstart, dend return def plot(self, ix_date, jx_azimuth, fname): rdict = self.rdict fname = self.folder + fname fig = plt.figure(figsize=(14, 8)) ax, aax = plot_utils.curved_earth_axes() elevbeg = list(rdict[ix_date][jx_azimuth].keys())[0] edenstht = rdict[ix_date][jx_azimuth][elevbeg]["edensTHT"] edensArr = rdict[ix_date][jx_azimuth][elevbeg]["edensARR"] rays = rdict[ix_date][jx_azimuth][elevbeg]["ray_parameters"] ionos = rdict[ix_date][jx_azimuth][elevbeg]["ionospheric_scatter"] X, Y = numpy.meshgrid(edenstht, ax.Re + numpy.linspace(60,560,500)) im = aax.pcolormesh(X, Y, edensArr, cmap="cividis", norm=mpl.colors.LogNorm(vmax=1e12, vmin=1e8)) cbax = plot_utils.add_cbar(im, ax) _ = cbax.set_ylabel(r"N$_{el}$ [$m^{-3}$]", fontsize=14) ax.set_title(ix_date.strftime("%Y-%m-%d %H:%M") + " (%s, Beam-%d, %d MHz)"%(self.rad.upper(), self.bm, self.freq), fontsize=14) ax.set_ylabel(r"Alt. [km]", size=16) ax.set_xlabel(r"Ground range [km]", size=16) for _el in rdict[ix_date][jx_azimuth].keys(): rays = rdict[ix_date][jx_azimuth][_el]["ray_parameters"] aax.plot(rays["th"], numpy.array(rays["r"])*1e-3, c="#9658B1", zorder=8, linewidth=1.) range_markers = [0] + list(numpy.arange(180, 5000, 225)) x, y = [], [] for _el in rdict[ix_date][jx_azimuth].keys(): rays = rdict[ix_date][jx_azimuth][_el]["ray_parameters"] grans = numpy.array(rays["gran"])*1e-3 th = numpy.array(rays["th"]) r = numpy.array(rays["r"]) for rm in range_markers: inds = (grans >= rm) if inds.any(): x.append( th[inds][0] ) y.append( r[inds][0]*1e-3 ) aax.scatter(x, y, color="w",s=1) scatter_color = "k" for _el in rdict[ix_date][jx_azimuth].keys(): ionos = rdict[ix_date][jx_azimuth][_el]["ionospheric_scatter"] if ionos["nstep"] <= 0: continue t = ionos["theta"] r = ionos["altitude"]*1e-3 spts = numpy.array([t, r]).T.reshape(-1, 1, 2) h = ionos["h"]*1e-3 rel = numpy.radians( ionos["ranelev"] ) r = numpy.sqrt( r**2 + h**2 + 2*r*h*numpy.sin( rel ) ) t = t + numpy.arcsin( h/r * numpy.cos( rel ) ) epts = numpy.array([t, r]).T.reshape(-1, 1, 2) segments = numpy.concatenate([spts, epts], axis=1) lcol = LineCollection( segments, zorder=10,linewidths=5. ) _ = lcol.set_color(scatter_color) aax.add_collection( lcol ) for _el in rdict[ix_date][jx_azimuth].keys(): gscat = rdict[ix_date][jx_azimuth][_el]["ground_scatter"] if gscat is not None: aax.scatter(gscat["theta"], ax.Re*numpy.ones(gscat["theta"].shape), color=scatter_color, zorder=20) ax.grid() fig.savefig(fname) img = plt.imread(fname) img = img[220:620, 120:1380, :] fig = plt.figure(figsize=(8, 3), dpi=180) ax = fig.add_subplot(111) ax.imshow(img) ax.set_xticks([]) ax.set_yticks([]) fig.patch.set_visible(False) ax.axis("off") fig.savefig(fname, bbox_inches="tight") plt.close() return def plot_rays(rad, ev, fs, dstart, dend, ix_date=5): hdw = pydarn.read_hdw_file(rad) for f in fs: u = dstart while u < dend: fold = "data/{dn}/{rad}/".format(dn=ev.strftime("%Y-%m-%d"), rad=rad) + "traces_%02d/"%(f) if not os.path.exists(fold): os.system("mkdir " + fold) for bm in range(1): fname = "traces_%02d/%s_%d_%d.png"%(f, u.strftime("%H%M"), bm, f) boresite = hdw.boresight offset = hdw.beams/2. - 0.5 beam_azim = round(boresite + (bm - offset)*hdw.beam_separation,2) tp = TracePlots(ev, rad, bm, f, u, u) tp.plot(u, beam_azim, fname) u = u + dt.timedelta(minutes=ix_date) return def plot_2D_electron_density(H, T, edens, f0, lat, lon, p_time, fname, location): p_time = p_time.replace(minute=int(p_time.minute/5)*5) if numpy.mod(p_time.minute, 5) != 0 else p_time fig = plt.figure(figsize=(5, 3), dpi=180) ax = fig.add_subplot(111) ax.xaxis.set_major_formatter(mdates.DateFormatter(r"$%H^{%M}$")) im = ax.contourf(T, H, edens.T/1e12, cmap="plasma", vmin=0, vmax=0.5) pos = ax.get_position() cpos = [pos.x1 + 0.025, pos.y0 + 0.0125, 0.015, pos.height * 0.8] # this list defines (left, bottom, width, height cax = fig.add_axes(cpos) boundaries = np.linspace(0, 0.5, 5) cb2 = mpl.colorbar.ColorbarBase(cax, cmap=plt.cm.plasma, boundaries=boundaries, spacing="proportional", orientation="vertical") cb2.set_label(r"$N_e, \times 10^{12}m^{-3}$") maxx = numpy.argmax(edens, axis=1) h = [H[i] for i in maxx] ax.set_ylim(60, 460) ax.set_ylabel("Height, km") ax.set_xlim(T[0], T[-1]) ax.set_xlabel("Time, UT") t_prior = p_time - dt.timedelta(minutes=30) ax.axvline(t_prior, color="b", lw=0.8, ls="--") t_post = p_time + dt.timedelta(minutes=30) ax.axvline(t_post, color="r", lw=0.8, ls="--") ax.axvline(p_time, color="k", lw=0.8, ls="--") ax.text(0.01, 1.05, "Date: "+T[0].strftime("%Y-%m-%d"), va="center", ha="left", transform=ax.transAxes) ax.text(0.99, 1.05, r"$T^{O_{max}}$: "+p_time.strftime("%H:%M UT"), va="center", ha="right", transform=ax.transAxes) ax.text(1.02, 0.99, r"Location: %s"%(location), va="top", ha="center", rotation=90, transform=ax.transAxes, fontdict={"size":6}) #fig.savefig(fname.format(d=2), bbox_inches="tight") t_id = T.index(p_time) tpri_id = T.index(t_prior) tpos_id = T.index(t_post) fig, axes = plt.subplots(figsize=(3, 3), dpi=150) ax = axes ax.set_ylabel("Height, km") ax.set_xlabel(r"$N_e$, $m^{-3}$") ax.semilogx(edens[t_id, :], H, color="k", lw=1., ls="-", label=r"$N_e[T^{O_{max}}]$") ax.semilogx(edens[tpri_id, :], H, color="b", lw=1., ls="-", label=r"$N_e[T^{O_{max}}-30min]$") ax.semilogx(edens[tpos_id, :], H, color="r", lw=1., ls="-", label=r"$N_e[T^{O_{max}}+30min]$") ax.axhline(H[np.argmax(edens[t_id, :])], color="k", lw=0.6, ls="--") ax.axhline(H[np.argmax(edens[tpri_id, :])], color="b", lw=0.6, ls="--") ax.axhline(H[np.argmax(edens[tpos_id, :])], color="r", lw=0.6, ls="--") ax.legend(loc=2) ax.set_ylim(50,400) ax.set_xlim(1e8,1e12) ax.text(0.01, 1.05, "Date: "+T[0].strftime("%Y-%m-%d"), va="center", ha="left", transform=ax.transAxes) ax.text(0.99, 1.05, r"$T^{O_{max}}$: "+p_time.strftime("%H:%M UT"), va="center", ha="right", transform=ax.transAxes) ax.text(1.05, 0.99, "Location: "+location, va="top", ha="right", rotation=90, transform=ax.transAxes) #fig.savefig(fname.format(d=1), bbox_inches="tight") fig = plt.figure(figsize=(5, 3), dpi=180) ax = fig.add_subplot(111) ax.xaxis.set_major_formatter(mdates.DateFormatter(r"$%H^{%M}$")) hF1, hF2 = H.tolist().index(150), H.tolist().index(240) ax.semilogy(T, edens[:, hF1], "bo", ms=.8, ls="None", alpha=0.5, label=r"$N_e(hF_1=150km)$") ax.semilogy(T, edens[:, hF2], "ro", ms=.8, ls="None", alpha=0.5, label=r"$N_e(hF_2=240km)$") ax.axvline(T[np.argmin(edens[:, hF1])], ls="--", lw=0.8, color="b") ax.axvline(T[np.argmin(edens[:, hF2])], ls="--", lw=0.8, color="r") ax.legend(loc=4) ax.set_xlim(T[0], T[-1]) ax.set_xlabel("Time, UT") ax.set_ylabel(r"$N_e$, $m^{-3}$") #fig.savefig(fname.format(d=0), bbox_inches="tight") return def plot_params(H, T, params, p_time, fname, location, pname, vlim, dlim): keys = {"opdt":[r"$\frac{dO^+}{dt}, s^{-1}$", r"\frac{dO^+}{dt}"], "dfield":[r"$D_{\vec{E}\times\vec{B}}, s^{-1}$", r"D_{\vec{E}\times\vec{B}}"], "amb_diff":[r"$D_{\alpha}, s^{-1}$", r"D_{\alpha}"], "dwind":[r"$D_{\vec{w}}, s^{-1}$", r"D_{\vec{w}}"], "WI":[r"$W_I, ms^{-1}$", r"W_I"], "U":[r"$U, ms^{-1}$", r"U"], "V":[r"$V, ms^{-1}$", r"V"], } p_time = p_time.replace(minute=int(p_time.minute/5)*5) if numpy.mod(p_time.minute, 5) != 0 else p_time fig = plt.figure(figsize=(5, 3), dpi=180) ax = fig.add_subplot(111) ax.xaxis.set_major_formatter(mdates.DateFormatter(r"$%H^{%M}$")) im = ax.contourf(T, H, params.T, cmap="plasma", vmax=vlim[1], vmin=vlim[0]) pos = ax.get_position() cpos = [pos.x1 + 0.025, pos.y0 + 0.0125, 0.015, pos.height * 0.8] # this list defines (left, bottom, width, height cax = fig.add_axes(cpos) boundaries = np.linspace(vlim[0], vlim[1], int((vlim[1]-vlim[0])/dlim)) cb2 = mpl.colorbar.ColorbarBase(cax, cmap=plt.cm.plasma, boundaries=boundaries, spacing="proportional", orientation="vertical") cb2.set_label(keys[pname][0]) ax.set_ylim(60, 460) ax.set_ylabel("Height, km") ax.set_xlim(T[0], T[-1]) ax.set_xlabel("Time, UT") t_prior = p_time - dt.timedelta(minutes=30) ax.axvline(t_prior, color="b", lw=0.8, ls="--") t_post = p_time + dt.timedelta(minutes=30) ax.axvline(t_post, color="r", lw=0.8, ls="--") ax.axvline(p_time, color="k", lw=0.8, ls="--") ax.text(0.01, 1.05, "Date: "+T[0].strftime("%Y-%m-%d"), va="center", ha="left", transform=ax.transAxes) ax.text(0.99, 1.05, r"$T^{O_{max}}$: "+p_time.strftime("%H:%M UT"), va="center", ha="right", transform=ax.transAxes) ax.text(1.02, 0.99, r"Location: %s"%(location), va="top", ha="center", rotation=90, transform=ax.transAxes, fontdict={"size":6}) #fig.savefig(fname.format(d=2), bbox_inches="tight") t_id = T.index(p_time) tpri_id = T.index(t_prior) tpos_id = T.index(t_post) fig, axes = plt.subplots(figsize=(3, 3), dpi=150) ax = axes ax.set_ylabel("Height, km") ax.set_xlabel(keys[pname][0]) ax.plot(params[t_id, :], H, color="k", lw=1., ls="-", label=r"$%s[T^{O_{max}}]$"%keys[pname][1]) ax.plot(params[tpri_id, :], H, color="b", lw=1., ls="-", label=r"$%s[T^{O_{max}}-30min]$"%keys[pname][1]) ax.plot(params[tpos_id, :], H, color="r", lw=1., ls="-", label=r"$%s[T^{O_{max}}+30min]$"%keys[pname][1]) ax.axhline(H[np.argmax(params[t_id, :])], color="k", lw=0.6, ls="--") ax.axhline(H[np.argmax(params[tpri_id, :])], color="b", lw=0.6, ls="--") ax.axhline(H[np.argmax(params[tpos_id, :])], color="r", lw=0.6, ls="--") ax.legend(loc=0) ax.set_ylim(50,400) ax.set_xlim(vlim) ax.text(0.01, 1.05, "Date: "+T[0].strftime("%Y-%m-%d"), va="center", ha="left", transform=ax.transAxes) ax.text(0.99, 1.05, r"$T^{O_{max}}$: "+p_time.strftime("%H:%M UT"), va="center", ha="right", transform=ax.transAxes) ax.text(1.05, 0.99, "Location: "+location, va="top", ha="right", rotation=90, transform=ax.transAxes) #fig.savefig(fname.format(d=1), bbox_inches="tight") fig = plt.figure(figsize=(5, 3), dpi=180) ax = fig.add_subplot(111) ax.xaxis.set_major_formatter(mdates.DateFormatter(r"$%H^{%M}$")) hF1, hF2 = H.tolist().index(150), H.tolist().index(240) ax.plot(T, params[:, hF1], "bo", ms=.8, ls="None", alpha=0.5, label=r"$%s(hF_1=150km)$"%keys[pname][1]) ax.plot(T, params[:, hF2], "ro", ms=.8, ls="None", alpha=0.5, label=r"$%s(hF_2=240km)$"%keys[pname][1]) ax.axvline(T[np.argmin(params[:, hF1])], ls="--", lw=0.8, color="b") ax.axvline(T[np.argmin(params[:, hF2])], ls="--", lw=0.8, color="r") ax.legend(loc=0) ax.set_xlim(T[0], T[-1]) ax.set_ylim(vlim) ax.set_xlabel("Time, UT") ax.set_ylabel(keys[pname][0]) #fig.savefig(fname.format(d=0), bbox_inches="tight") return def create_ts_label_plots(T, params, H, ylabel, yscale=None, ylim=None, xlabel=r"Time ($\tau$), UT"): fig = plt.figure(figsize=(5, 3), dpi=180) ax = fig.add_subplot(111) ax.xaxis.set_major_formatter(mdates.DateFormatter(r"$%H^{%M}$")) hF1, hF2 = H.tolist().index(150), H.tolist().index(240) for lab, shape, param in zip([r"$\mathcal{E}$", r"$\mathcal{D}$"], ["o", "D"], params): ax.plot(T, param[:,hF1], "r"+shape, ms=.8, ls="None", alpha=0.5, label=r"$hF_1=150km$ [%s]"%lab) ax.plot(T, param[:,hF2], "b"+shape, ms=.8, ls="None", alpha=0.5, label=r"$hF_2=240km$ [%s]"%lab) ax.legend(loc=4) ax.set_xlabel(xlabel) ax.set_ylabel(ylabel) if yscale: ax.set_yscale(yscale) if ylim: ax.set_ylim(ylim) ax.set_xlim(T[0], T[-1]) return fig, ax def normalize_data(data): return (data - np.min(data)) / (np.max(data) - np.min(data)) def create_ts_plot(H, T, params, label, vlim=[0,1], xlim=[dt.datetime(2017,8,21,16), dt.datetime(2017,8,21,19,30)], h1=150, h2=220, mult=None, units=r"m^{-3}s^{-%d}"): fig = plt.figure(figsize=(5, 6), dpi=180) ax = fig.add_subplot(211) ax.xaxis.set_major_formatter(mdates.DateFormatter(r"$%H^{%M}$")) hF1, hF2 = H.tolist().index(h1), H.tolist().index(h2) u = params[:, hF1] if mult==1. else params[:, hF1] * mult[:, hF1] ax.plot(T, u, "bo", ms=.8, ls="None", alpha=0.5, label=r"$%s(hF_1=%d km)$"%(label, h1)) ax.axvline(T[np.argmin(u)], ls="--", lw=0.8, color="b") u = params[:, hF2] if mult==1. else params[:, hF2] * mult[:, hF2] ax.plot(T, u, "ro", ms=.8, ls="None", alpha=0.5, label=r"$%s(hF_2=%d km)$"%(label, h2)) ax.axvline(T[np.argmin(params[:, hF2])], ls="--", lw=0.8, color="r") ax.legend(loc=2) ax.set_xlim(xlim) #ax.set_ylim(vlim) ax.set_ylabel(r"$%s$, $%s$"%(label, units%1)) ax = fig.add_subplot(212) ax.xaxis.set_major_formatter(mdates.DateFormatter(r"$%H^{%M}$")) hF1, hF2 = H.tolist().index(h1), H.tolist().index(h2) u = params[:, hF1] if mult==1. else params[:, hF1] * mult[:, hF1] u = np.diff(u, prepend=u[0]) ax.plot(T, u, "bo", ms=.8, ls="None", alpha=0.5, label=r"$%s(hF_1=%d km)$"%(label, h1)) #ax.axvline(T[np.argmin(u)], ls="--", lw=0.8, color="b") u = params[:, hF2] if mult==1. else params[:, hF2] * mult[:, hF2] u = np.diff(u, prepend=u[0]) ax.plot(T, u, "ro", ms=.8, ls="None", alpha=0.5, label=r"$%s(hF_2=%d km)$"%(label, h2)) ax.axhline(0, color="k", ls="--", lw=0.8) #ax.axvline(T[np.argmin(u)], ls="--", lw=0.8, color="r") ax.legend(loc=2) ax.set_xlim(xlim) ax.set_xlabel("Time, UT") ax.set_ylabel(r"$\frac{\partial}{\partial t}$ $%s$, $%s$"%(label, units%2)) return def create_rate_ts_plot(H, T, params, label, vlim=[0,1], xlim=[dt.datetime(2017,8,21,16), dt.datetime(2017,8,21,19,30)], h1=150, h2=220, mult=None, units=r"s^{-2}"): fig = plt.figure(figsize=(5, 3), dpi=180) ax = fig.add_subplot(111) ax.xaxis.set_major_formatter(mdates.DateFormatter(r"$%H^{%M}$")) hF1, hF2 = H.tolist().index(h1), H.tolist().index(h2) #params = normalize_data(params) #params *= mult u = params[:, hF1] if mult==1. else params[:, hF1] * mult[:, hF1] u = np.diff(u, prepend=u[0]) ax.plot(T, u, "bo", ms=.8, ls="None", alpha=0.5, label=r"$%s(hF_1=%d km)$"%(label, h1)) ax.axvline(T[np.argmin(u)], ls="--", lw=0.8, color="b") u = params[:, hF2] if mult==1. else params[:, hF2] * mult[:, hF2] u = np.diff(u, prepend=u[0]) ax.plot(T, u, "ro", ms=.8, ls="None", alpha=0.5, label=r"$%s(hF_2=%d km)$"%(label, h2)) ax.axvline(T[np.argmin(u)], ls="--", lw=0.8, color="r") ax.legend(loc=0) ax.set_xlim(xlim) #ax.set_ylim(vlim) ax.set_xlabel("Time, UT") ax.set_ylabel(r"$%s$, $%s$"%(label, units)) return if __name__ == "__main__": plot_rays("cvw", ev=dt.datetime(2017,8,21), fs=[12, 14, 16, 18], dstart=dt.datetime(2017,8,21,14,10), dend=dt.datetime(2017,8,21,20,10), ix_date=5)
[ "numpy.argmax", "numpy.ones", "numpy.argmin", "matplotlib.pyplot.figure", "pickle.load", "matplotlib.colors.LogNorm", "numpy.arange", "numpy.sin", "matplotlib.pyplot.imread", "matplotlib.pyplot.close", "sys.path.extend", "os.path.exists", "matplotlib.dates.DateFormatter", "numpy.max", "d...
[((287, 337), 'sys.path.extend', 'sys.path.extend', (["['code/', 'code/rt/', 'code/sd/']"], {}), "(['code/', 'code/rt/', 'code/sd/'])\n", (302, 337), False, 'import sys\n'), ((4759, 4784), 'pydarn.read_hdw_file', 'pydarn.read_hdw_file', (['rad'], {}), '(rad)\n', (4779, 4784), False, 'import pydarn\n'), ((5661, 5696), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(5, 3)', 'dpi': '(180)'}), '(figsize=(5, 3), dpi=180)\n', (5671, 5696), True, 'import matplotlib.pyplot as plt\n'), ((6090, 6112), 'numpy.linspace', 'np.linspace', (['(0)', '(0.5)', '(5)'], {}), '(0, 0.5, 5)\n', (6101, 6112), True, 'import numpy as np\n'), ((6123, 6248), 'matplotlib.colorbar.ColorbarBase', 'mpl.colorbar.ColorbarBase', (['cax'], {'cmap': 'plt.cm.plasma', 'boundaries': 'boundaries', 'spacing': '"""proportional"""', 'orientation': '"""vertical"""'}), "(cax, cmap=plt.cm.plasma, boundaries=boundaries,\n spacing='proportional', orientation='vertical')\n", (6148, 6248), True, 'import matplotlib as mpl\n'), ((6306, 6333), 'numpy.argmax', 'numpy.argmax', (['edens'], {'axis': '(1)'}), '(edens, axis=1)\n', (6318, 6333), False, 'import numpy\n'), ((7269, 7306), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(3, 3)', 'dpi': '(150)'}), '(figsize=(3, 3), dpi=150)\n', (7281, 7306), True, 'import matplotlib.pyplot as plt\n'), ((8382, 8417), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(5, 3)', 'dpi': '(180)'}), '(figsize=(5, 3), dpi=180)\n', (8392, 8417), True, 'import matplotlib.pyplot as plt\n'), ((9728, 9763), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(5, 3)', 'dpi': '(180)'}), '(figsize=(5, 3), dpi=180)\n', (9738, 9763), True, 'import matplotlib.pyplot as plt\n'), ((10232, 10357), 'matplotlib.colorbar.ColorbarBase', 'mpl.colorbar.ColorbarBase', (['cax'], {'cmap': 'plt.cm.plasma', 'boundaries': 'boundaries', 'spacing': '"""proportional"""', 'orientation': '"""vertical"""'}), "(cax, cmap=plt.cm.plasma, boundaries=boundaries,\n spacing='proportional', orientation='vertical')\n", (10257, 10357), True, 'import matplotlib as mpl\n'), ((11294, 11331), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(3, 3)', 'dpi': '(150)'}), '(figsize=(3, 3), dpi=150)\n', (11306, 11331), True, 'import matplotlib.pyplot as plt\n'), ((12435, 12470), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(5, 3)', 'dpi': '(180)'}), '(figsize=(5, 3), dpi=180)\n', (12445, 12470), True, 'import matplotlib.pyplot as plt\n'), ((13309, 13344), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(5, 3)', 'dpi': '(180)'}), '(figsize=(5, 3), dpi=180)\n', (13319, 13344), True, 'import matplotlib.pyplot as plt\n'), ((14289, 14324), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(5, 6)', 'dpi': '(180)'}), '(figsize=(5, 6), dpi=180)\n', (14299, 14324), True, 'import matplotlib.pyplot as plt\n'), ((15298, 15322), 'numpy.diff', 'np.diff', (['u'], {'prepend': 'u[0]'}), '(u, prepend=u[0])\n', (15305, 15322), True, 'import numpy as np\n'), ((15555, 15579), 'numpy.diff', 'np.diff', (['u'], {'prepend': 'u[0]'}), '(u, prepend=u[0])\n', (15562, 15579), True, 'import numpy as np\n'), ((16144, 16179), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(5, 3)', 'dpi': '(180)'}), '(figsize=(5, 3), dpi=180)\n', (16154, 16179), True, 'import matplotlib.pyplot as plt\n'), ((16473, 16497), 'numpy.diff', 'np.diff', (['u'], {'prepend': 'u[0]'}), '(u, prepend=u[0])\n', (16480, 16497), True, 'import numpy as np\n'), ((16729, 16753), 'numpy.diff', 'np.diff', (['u'], {'prepend': 'u[0]'}), '(u, prepend=u[0])\n', (16736, 16753), True, 'import numpy as np\n'), ((1325, 1352), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(14, 8)'}), '(figsize=(14, 8))\n', (1335, 1352), True, 'import matplotlib.pyplot as plt\n'), ((1371, 1401), 'plot_utils.curved_earth_axes', 'plot_utils.curved_earth_axes', ([], {}), '()\n', (1399, 1401), False, 'import plot_utils\n'), ((1957, 1984), 'plot_utils.add_cbar', 'plot_utils.add_cbar', (['im', 'ax'], {}), '(im, ax)\n', (1976, 1984), False, 'import plot_utils\n'), ((4331, 4348), 'matplotlib.pyplot.imread', 'plt.imread', (['fname'], {}), '(fname)\n', (4341, 4348), True, 'import matplotlib.pyplot as plt\n'), ((4403, 4438), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(8, 3)', 'dpi': '(180)'}), '(figsize=(8, 3), dpi=180)\n', (4413, 4438), True, 'import matplotlib.pyplot as plt\n'), ((4664, 4675), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (4673, 4675), True, 'import matplotlib.pyplot as plt\n'), ((5760, 5793), 'matplotlib.dates.DateFormatter', 'mdates.DateFormatter', (['"""$%H^{%M}$"""'], {}), "('$%H^{%M}$')\n", (5780, 5793), True, 'import matplotlib.dates as mdates\n'), ((6502, 6526), 'datetime.timedelta', 'dt.timedelta', ([], {'minutes': '(30)'}), '(minutes=30)\n', (6514, 6526), True, 'import datetime as dt\n'), ((6601, 6625), 'datetime.timedelta', 'dt.timedelta', ([], {'minutes': '(30)'}), '(minutes=30)\n', (6613, 6625), True, 'import datetime as dt\n'), ((8481, 8514), 'matplotlib.dates.DateFormatter', 'mdates.DateFormatter', (['"""$%H^{%M}$"""'], {}), "('$%H^{%M}$')\n", (8501, 8514), True, 'import matplotlib.dates as mdates\n'), ((9827, 9860), 'matplotlib.dates.DateFormatter', 'mdates.DateFormatter', (['"""$%H^{%M}$"""'], {}), "('$%H^{%M}$')\n", (9847, 9860), True, 'import matplotlib.dates as mdates\n'), ((10527, 10551), 'datetime.timedelta', 'dt.timedelta', ([], {'minutes': '(30)'}), '(minutes=30)\n', (10539, 10551), True, 'import datetime as dt\n'), ((10626, 10650), 'datetime.timedelta', 'dt.timedelta', ([], {'minutes': '(30)'}), '(minutes=30)\n', (10638, 10650), True, 'import datetime as dt\n'), ((12534, 12567), 'matplotlib.dates.DateFormatter', 'mdates.DateFormatter', (['"""$%H^{%M}$"""'], {}), "('$%H^{%M}$')\n", (12554, 12567), True, 'import matplotlib.dates as mdates\n'), ((13408, 13441), 'matplotlib.dates.DateFormatter', 'mdates.DateFormatter', (['"""$%H^{%M}$"""'], {}), "('$%H^{%M}$')\n", (13428, 13441), True, 'import matplotlib.dates as mdates\n'), ((14150, 14178), 'datetime.datetime', 'dt.datetime', (['(2017)', '(8)', '(21)', '(16)'], {}), '(2017, 8, 21, 16)\n', (14161, 14178), True, 'import datetime as dt\n'), ((14177, 14209), 'datetime.datetime', 'dt.datetime', (['(2017)', '(8)', '(21)', '(19)', '(30)'], {}), '(2017, 8, 21, 19, 30)\n', (14188, 14209), True, 'import datetime as dt\n'), ((14388, 14421), 'matplotlib.dates.DateFormatter', 'mdates.DateFormatter', (['"""$%H^{%M}$"""'], {}), "('$%H^{%M}$')\n", (14408, 14421), True, 'import matplotlib.dates as mdates\n'), ((15125, 15158), 'matplotlib.dates.DateFormatter', 'mdates.DateFormatter', (['"""$%H^{%M}$"""'], {}), "('$%H^{%M}$')\n", (15145, 15158), True, 'import matplotlib.dates as mdates\n'), ((16007, 16035), 'datetime.datetime', 'dt.datetime', (['(2017)', '(8)', '(21)', '(16)'], {}), '(2017, 8, 21, 16)\n', (16018, 16035), True, 'import datetime as dt\n'), ((16034, 16066), 'datetime.datetime', 'dt.datetime', (['(2017)', '(8)', '(21)', '(19)', '(30)'], {}), '(2017, 8, 21, 19, 30)\n', (16045, 16066), True, 'import datetime as dt\n'), ((16243, 16276), 'matplotlib.dates.DateFormatter', 'mdates.DateFormatter', (['"""$%H^{%M}$"""'], {}), "('$%H^{%M}$')\n", (16263, 16276), True, 'import matplotlib.dates as mdates\n'), ((1119, 1133), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (1130, 1133), False, 'import pickle\n'), ((2843, 2866), 'numpy.array', 'numpy.array', (["rays['th']"], {}), "(rays['th'])\n", (2854, 2866), False, 'import numpy\n'), ((2883, 2905), 'numpy.array', 'numpy.array', (["rays['r']"], {}), "(rays['r'])\n", (2894, 2905), False, 'import numpy\n'), ((3529, 3560), 'numpy.radians', 'numpy.radians', (["ionos['ranelev']"], {}), "(ionos['ranelev'])\n", (3542, 3560), False, 'import numpy\n'), ((3771, 3810), 'numpy.concatenate', 'numpy.concatenate', (['[spts, epts]'], {'axis': '(1)'}), '([spts, epts], axis=1)\n', (3788, 3810), False, 'import numpy\n'), ((3830, 3881), 'matplotlib.collections.LineCollection', 'LineCollection', (['segments'], {'zorder': '(10)', 'linewidths': '(5.0)'}), '(segments, zorder=10, linewidths=5.0)\n', (3844, 3881), False, 'from matplotlib.collections import LineCollection\n'), ((5606, 5633), 'numpy.mod', 'numpy.mod', (['p_time.minute', '(5)'], {}), '(p_time.minute, 5)\n', (5615, 5633), False, 'import numpy\n'), ((7696, 7721), 'numpy.argmax', 'np.argmax', (['edens[t_id, :]'], {}), '(edens[t_id, :])\n', (7705, 7721), True, 'import numpy as np\n'), ((7769, 7797), 'numpy.argmax', 'np.argmax', (['edens[tpri_id, :]'], {}), '(edens[tpri_id, :])\n', (7778, 7797), True, 'import numpy as np\n'), ((7845, 7873), 'numpy.argmax', 'np.argmax', (['edens[tpos_id, :]'], {}), '(edens[tpos_id, :])\n', (7854, 7873), True, 'import numpy as np\n'), ((8788, 8812), 'numpy.argmin', 'np.argmin', (['edens[:, hF1]'], {}), '(edens[:, hF1])\n', (8797, 8812), True, 'import numpy as np\n'), ((8860, 8884), 'numpy.argmin', 'np.argmin', (['edens[:, hF2]'], {}), '(edens[:, hF2])\n', (8869, 8884), True, 'import numpy as np\n'), ((9673, 9700), 'numpy.mod', 'numpy.mod', (['p_time.minute', '(5)'], {}), '(p_time.minute, 5)\n', (9682, 9700), False, 'import numpy\n'), ((11750, 11776), 'numpy.argmax', 'np.argmax', (['params[t_id, :]'], {}), '(params[t_id, :])\n', (11759, 11776), True, 'import numpy as np\n'), ((11824, 11853), 'numpy.argmax', 'np.argmax', (['params[tpri_id, :]'], {}), '(params[tpri_id, :])\n', (11833, 11853), True, 'import numpy as np\n'), ((11901, 11930), 'numpy.argmax', 'np.argmax', (['params[tpos_id, :]'], {}), '(params[tpos_id, :])\n', (11910, 11930), True, 'import numpy as np\n'), ((12863, 12888), 'numpy.argmin', 'np.argmin', (['params[:, hF1]'], {}), '(params[:, hF1])\n', (12872, 12888), True, 'import numpy as np\n'), ((12936, 12961), 'numpy.argmin', 'np.argmin', (['params[:, hF2]'], {}), '(params[:, hF2])\n', (12945, 12961), True, 'import numpy as np\n'), ((14045, 14057), 'numpy.min', 'np.min', (['data'], {}), '(data)\n', (14051, 14057), True, 'import numpy as np\n'), ((14062, 14074), 'numpy.max', 'np.max', (['data'], {}), '(data)\n', (14068, 14074), True, 'import numpy as np\n'), ((14077, 14089), 'numpy.min', 'np.min', (['data'], {}), '(data)\n', (14083, 14089), True, 'import numpy as np\n'), ((14662, 14674), 'numpy.argmin', 'np.argmin', (['u'], {}), '(u)\n', (14671, 14674), True, 'import numpy as np\n'), ((14885, 14910), 'numpy.argmin', 'np.argmin', (['params[:, hF2]'], {}), '(params[:, hF2])\n', (14894, 14910), True, 'import numpy as np\n'), ((16607, 16619), 'numpy.argmin', 'np.argmin', (['u'], {}), '(u)\n', (16616, 16619), True, 'import numpy as np\n'), ((16863, 16875), 'numpy.argmin', 'np.argmin', (['u'], {}), '(u)\n', (16872, 16875), True, 'import numpy as np\n'), ((17113, 17137), 'datetime.datetime', 'dt.datetime', (['(2017)', '(8)', '(21)'], {}), '(2017, 8, 21)\n', (17124, 17137), True, 'import datetime as dt\n'), ((17165, 17197), 'datetime.datetime', 'dt.datetime', (['(2017)', '(8)', '(21)', '(14)', '(10)'], {}), '(2017, 8, 21, 14, 10)\n', (17176, 17197), True, 'import datetime as dt\n'), ((17214, 17246), 'datetime.datetime', 'dt.datetime', (['(2017)', '(8)', '(21)', '(20)', '(10)'], {}), '(2017, 8, 21, 20, 10)\n', (17225, 17246), True, 'import datetime as dt\n'), ((1807, 1835), 'numpy.linspace', 'numpy.linspace', (['(60)', '(560)', '(500)'], {}), '(60, 560, 500)\n', (1821, 1835), False, 'import numpy\n'), ((1901, 1959), 'matplotlib.colors.LogNorm', 'mpl.colors.LogNorm', ([], {'vmax': '(1000000000000.0)', 'vmin': '(100000000.0)'}), '(vmax=1000000000000.0, vmin=100000000.0)\n', (1919, 1959), True, 'import matplotlib as mpl\n'), ((2600, 2628), 'numpy.arange', 'numpy.arange', (['(180)', '(5000)', '(225)'], {}), '(180, 5000, 225)\n', (2612, 2628), False, 'import numpy\n'), ((2795, 2820), 'numpy.array', 'numpy.array', (["rays['gran']"], {}), "(rays['gran'])\n", (2806, 2820), False, 'import numpy\n'), ((4967, 4987), 'os.path.exists', 'os.path.exists', (['fold'], {}), '(fold)\n', (4981, 4987), False, 'import os\n'), ((4989, 5015), 'os.system', 'os.system', (["('mkdir ' + fold)"], {}), "('mkdir ' + fold)\n", (4998, 5015), False, 'import os\n'), ((2449, 2471), 'numpy.array', 'numpy.array', (["rays['r']"], {}), "(rays['r'])\n", (2460, 2471), False, 'import numpy\n'), ((5420, 5449), 'datetime.timedelta', 'dt.timedelta', ([], {'minutes': 'ix_date'}), '(minutes=ix_date)\n', (5432, 5449), True, 'import datetime as dt\n'), ((3439, 3458), 'numpy.array', 'numpy.array', (['[t, r]'], {}), '([t, r])\n', (3450, 3458), False, 'import numpy\n'), ((3611, 3625), 'numpy.sin', 'numpy.sin', (['rel'], {}), '(rel)\n', (3620, 3625), False, 'import numpy\n'), ((3670, 3684), 'numpy.cos', 'numpy.cos', (['rel'], {}), '(rel)\n', (3679, 3684), False, 'import numpy\n'), ((3708, 3727), 'numpy.array', 'numpy.array', (['[t, r]'], {}), '([t, r])\n', (3719, 3727), False, 'import numpy\n'), ((4159, 4191), 'numpy.ones', 'numpy.ones', (["gscat['theta'].shape"], {}), "(gscat['theta'].shape)\n", (4169, 4191), False, 'import numpy\n')]
#!/usr/bin/python3 # Tested with Python 3.8.6 #------------------------------------------------------------------------------ # runEmceeAfterglow.py #------------------------------------------------------------------------------ # Authors: <NAME>, <NAME> # Oregon State University #------------------------------------------------------------------------------ """ Use emcee module to generate parameter fits based on DL afterglow code. Imported files -------------- init_params.py plots.py multibandDataMooley.py exceptionHandler.py <afterglowModel.py> Functions -------------- cleanTempFolder(None) Remove files from /temp folder. Used by: main() createParamFiles(*args) Store emcee parameter values in .dat file. Used by: main() runAfterglow(*args) Call afterglow script to calculate lightcurves. Used by: logLikelihood() logPrior(*agrs) Create parameter lables using math text. Used by: logProbability() logLikelihood(*args) Used by: logProbability() logProbability(*args) Used by: main() main(None) Run emcee package, save and plot results. """ # Standard Python library imports import numpy as np from math import log10 import time import shutil # for cleaning temp folder import os os.environ["OMP_NUM_THREADS"] = "1" import sys print("Python version {}".format(sys.version)) import multiprocessing from multiprocessing import Pool # Emcee imports import emcee print("emcee version", emcee.__version__) import tqdm # for progress bar # Companion scripts from cleanDataGW170817 import time_obs, flux_obs, flux_uncert from init_params import params_list # import <yourAfterglowModel> as run_ag from exceptionHandler import exception_handler def cleanTempFolder(): """Remove files from temp folder.""" folder = "./temp/" for filename in os.listdir(folder): file_path = folder + filename if os.path.isfile(file_path) or os.path.islink(file_path): os.unlink(file_path) elif os.path.isdir(file_path): shutil.rmtree(file_path) def createParamFiles(params_list): """ Determine whether a duplicate file exists using pid and timestamp as identifiers. If file exists, create a new one with a different timestamp. If not, create a temp file containing emcee parameter samples. Parameters ---------- params_list: list List of emcee parameter values. Returns ---------- params_datafile: .dat file Contains emcee parameter values for use by runAfterglow. """ folder = "./temp/" filename = "params-pid-{}-time-{}.dat".format( str(os.getpid()), str(time.time())) # Ensure filenames are unique if os.path.isfile(folder + filename): new_filename = 'params-pid-{}-time-{}.dat'.format( str(os.getpid()), str(time.time())) params_datafile = folder + new_filename else: params_datafile = folder + filename dataout = [] for i, item in enumerate(params_list): dataout.append(item[0]) np.savetxt(params_datafile, dataout, fmt='%s') return params_datafile def runAfterglow(eps_E, eps_B, p_e, n_ISM, E_j, E_c, theta_j, theta_c, theta_obs, Gamma_0): """ Convert emcee parameter values from log space to linear space. Call afterglow script runAfterglowDL.py to calculate lightcurves. Parameters ---------- theta = {eps_E,...,Gamma_0} Returns ---------- lightcurve: float """ params = zip((eps_E, eps_B, p_e, n_ISM, E_j, E_c, theta_j, theta_c, theta_obs, Gamma_0)) params_list = (list(params)) params_datafile = createParamFiles(params_list) lightcurve = run_ag.main(params_datafile=params_datafile) return lightcurve def logPrior(theta): """ Define flat ("uninformative") prior distributions for a set of parameters. Parameters ---------- theta: set of parameters Returns ---------- 0.0 if sample drawn within the bounds, -infinity otherwise. """ eps_E, eps_B, p_e, \ n_ISM, E_j, E_c, theta_j, \ theta_c, theta_obs, Gamma_0 = theta # NOTE: eps_E, eps_B, n_ISM, E_j, E_c, and Gamma_0 are flat priors # in log space if (-4 < eps_E < -0.3 and -4 < eps_B < -0.3 and 2 < p_e < 2.5 and -4 < n_ISM < -0.3 and -4 < E_j < 50 and -4 < E_c < 49 and 0 < theta_j < 10 and theta_j + 0.6 < theta_c < 20 and 0 < theta_obs < 90 and -4 < Gamma_0 < 2.7): return 0.0 return -np.inf def logLikelihood(theta, x, y, yerr): """ Define log-likelihood function assuming a Gaussian distribution. Parameters ---------- theta: set of parameters y: array, float Observed flux yerr: array, float Observed flux uncertainty Returns ---------- -0.5 * np.sum(((y-model)/yerr)**2): float Likelihood function """ eps_E, eps_B, p_e, \ n_ISM, E_j, E_c, theta_j, \ theta_c, theta_obs, Gamma_0 = theta lightcurve = runAfterglow(eps_E, eps_B, p_e, n_ISM, E_j, E_c, theta_j, theta_c, theta_obs, Gamma_0) model = lightcurve return -0.5 * np.sum(((y-model)/yerr)**2) def logProbability(theta, x, y, yerr): """Define full log-probabilty function.""" if not np.isfinite(logPrior(theta)): return -np.inf return logPrior(theta) + logLikelihood(theta, x, y, yerr) def emceeSampler(params_list): """" Run emcee sampler and check for convergence every n steps. Parameters ---------- params_list: list, float NOTE: This is a global variable, imported from init_params.py (see imports list, line 63). Returns ---------- None """ def _prepEmcee(params_list, Gaussian_ball=False): """ Iniitalize walkers around initial guess. If 'Gaussian_ball' is set to True, initialize walkers in a small Gaussian ball around the inital guess. """ num_params = len(params_list) print("# of parameters emcee is fitting: {}".format(num_params)) print("Initial parameter guesses:{}".format(params_list)) params_list = np.reshape(params_list, (1, num_params)) if Gaussian_ball == True: pos = params_list + 1e-4 * np.random.randn(n_walkers, num_params) else: pos = params_list * np.random.randn(n_walkers, num_params) print(pos) print("Initial walkers set.") nwalkers, ndim = pos.shape return nwalkers, ndim, pos def _createBackendFile(): """Generate a .h5 backend file to save and monitor progress.""" print(os.getcwd()) folder = "./backend" datestamp = time.strftime("%Y%m%d-%H%M") filename = "backend-file-{}.h5".format(datestamp) backend = emcee.backends.HDFBackend(folder+filename) return backend def _saveResults(backend, samples): """Rename backend file to match when the emcee run completed.""" datestamp = time.strftime("%Y%m%d-%H%M") backend_folder = './backend/' filename = "backend-file-{}.h5".format(datestamp) os.rename(backend.filename, backend_folder + filename) def _runEmcee(backend, nwalkers, ndim, pos): """ Set up a pool process to run emcee in parallel. Run emcee sampler and check for convergence very n steps, where n is user-defined. """ backend.reset(nwalkers, ndim) index = 0 autocorr = np.empty(max_iter) old_tau = np.inf # Set up parallel processing with Pool(processes = n_processes) as pool: sampler = emcee.EnsembleSampler(nwalkers, ndim, logProbability, args = (x,y,yerr), backend=backend, pool=pool) # Run emcee for sample in sampler.sample( pos, iterations=max_iter, progress=True): #print("log_prob = {} ".format(sampler.get_log_prob())) #print("tau = {}".format(sampler.get_autocorr_time())) #print("acceptance fraction = {} ".format(sampler.acceptance_fraction)) # Check for convergence very "check_iter" steps if sampler.iteration % check_iter: continue tau = sampler.get_autocorr_time(tol=0) autocorr[index] = np.mean(tau) index += 1 converged = np.all(tau * 100 < sampler.iteration) converged &= np.all(np.abs(old_tau - tau) / tau < 0.01) if converged: break old_tau = tau # Get samples samples = sampler.chain[:, :, :].reshape((-1,ndim)) print(samples.shape, samples) return samples backend = _createBackendFile() nwalkers, ndim, pos = _prepEmcee(params_list) samples = _runEmcee(backend, nwalkers, ndim, pos) _saveResults(backend, samples) print("Emcee run complete. Access backend file to plot.") @exception_handler def main(): """Clean temp folder and run emcee sampler.""" cleanTempFolder() emceeSampler(params_list) if __name__ == "__main__": # Global variables from imports x = time_obs y = flux_obs yerr = flux_uncert num_params = len(params_list) params = np.reshape(params_list, (1, num_params)) # User-defined global variables n_walkers = 20 n_processes = 1 max_iter = 1 # Check for convergence every n iterations # NOTE: max_iter must be divisible by n check_iter = 1 # Run script main()
[ "numpy.sum", "os.unlink", "numpy.abs", "numpy.empty", "time.strftime", "os.path.isfile", "os.path.islink", "numpy.mean", "shutil.rmtree", "numpy.random.randn", "emcee.backends.HDFBackend", "numpy.savetxt", "numpy.reshape", "os.rename", "multiprocessing.Pool", "os.listdir", "numpy.all...
[((1831, 1849), 'os.listdir', 'os.listdir', (['folder'], {}), '(folder)\n', (1841, 1849), False, 'import os\n'), ((2724, 2757), 'os.path.isfile', 'os.path.isfile', (['(folder + filename)'], {}), '(folder + filename)\n', (2738, 2757), False, 'import os\n'), ((3065, 3111), 'numpy.savetxt', 'np.savetxt', (['params_datafile', 'dataout'], {'fmt': '"""%s"""'}), "(params_datafile, dataout, fmt='%s')\n", (3075, 3111), True, 'import numpy as np\n'), ((9819, 9859), 'numpy.reshape', 'np.reshape', (['params_list', '(1, num_params)'], {}), '(params_list, (1, num_params))\n', (9829, 9859), True, 'import numpy as np\n'), ((5353, 5386), 'numpy.sum', 'np.sum', (['(((y - model) / yerr) ** 2)'], {}), '(((y - model) / yerr) ** 2)\n', (5359, 5386), True, 'import numpy as np\n'), ((6375, 6415), 'numpy.reshape', 'np.reshape', (['params_list', '(1, num_params)'], {}), '(params_list, (1, num_params))\n', (6385, 6415), True, 'import numpy as np\n'), ((6924, 6952), 'time.strftime', 'time.strftime', (['"""%Y%m%d-%H%M"""'], {}), "('%Y%m%d-%H%M')\n", (6937, 6952), False, 'import time\n'), ((7029, 7073), 'emcee.backends.HDFBackend', 'emcee.backends.HDFBackend', (['(folder + filename)'], {}), '(folder + filename)\n', (7054, 7073), False, 'import emcee\n'), ((7230, 7258), 'time.strftime', 'time.strftime', (['"""%Y%m%d-%H%M"""'], {}), "('%Y%m%d-%H%M')\n", (7243, 7258), False, 'import time\n'), ((7363, 7417), 'os.rename', 'os.rename', (['backend.filename', '(backend_folder + filename)'], {}), '(backend.filename, backend_folder + filename)\n', (7372, 7417), False, 'import os\n'), ((7755, 7773), 'numpy.empty', 'np.empty', (['max_iter'], {}), '(max_iter)\n', (7763, 7773), True, 'import numpy as np\n'), ((1900, 1925), 'os.path.isfile', 'os.path.isfile', (['file_path'], {}), '(file_path)\n', (1914, 1925), False, 'import os\n'), ((1929, 1954), 'os.path.islink', 'os.path.islink', (['file_path'], {}), '(file_path)\n', (1943, 1954), False, 'import os\n'), ((1968, 1988), 'os.unlink', 'os.unlink', (['file_path'], {}), '(file_path)\n', (1977, 1988), False, 'import os\n'), ((2002, 2026), 'os.path.isdir', 'os.path.isdir', (['file_path'], {}), '(file_path)\n', (2015, 2026), False, 'import os\n'), ((2650, 2661), 'os.getpid', 'os.getpid', ([], {}), '()\n', (2659, 2661), False, 'import os\n'), ((2668, 2679), 'time.time', 'time.time', ([], {}), '()\n', (2677, 2679), False, 'import time\n'), ((6862, 6873), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (6871, 6873), False, 'import os\n'), ((7860, 7887), 'multiprocessing.Pool', 'Pool', ([], {'processes': 'n_processes'}), '(processes=n_processes)\n', (7864, 7887), False, 'from multiprocessing import Pool\n'), ((7921, 8025), 'emcee.EnsembleSampler', 'emcee.EnsembleSampler', (['nwalkers', 'ndim', 'logProbability'], {'args': '(x, y, yerr)', 'backend': 'backend', 'pool': 'pool'}), '(nwalkers, ndim, logProbability, args=(x, y, yerr),\n backend=backend, pool=pool)\n', (7942, 8025), False, 'import emcee\n'), ((2040, 2064), 'shutil.rmtree', 'shutil.rmtree', (['file_path'], {}), '(file_path)\n', (2053, 2064), False, 'import shutil\n'), ((2834, 2845), 'os.getpid', 'os.getpid', ([], {}), '()\n', (2843, 2845), False, 'import os\n'), ((2852, 2863), 'time.time', 'time.time', ([], {}), '()\n', (2861, 2863), False, 'import time\n'), ((6574, 6612), 'numpy.random.randn', 'np.random.randn', (['n_walkers', 'num_params'], {}), '(n_walkers, num_params)\n', (6589, 6612), True, 'import numpy as np\n'), ((8841, 8853), 'numpy.mean', 'np.mean', (['tau'], {}), '(tau)\n', (8848, 8853), True, 'import numpy as np\n'), ((8909, 8946), 'numpy.all', 'np.all', (['(tau * 100 < sampler.iteration)'], {}), '(tau * 100 < sampler.iteration)\n', (8915, 8946), True, 'import numpy as np\n'), ((6489, 6527), 'numpy.random.randn', 'np.random.randn', (['n_walkers', 'num_params'], {}), '(n_walkers, num_params)\n', (6504, 6527), True, 'import numpy as np\n'), ((8983, 9004), 'numpy.abs', 'np.abs', (['(old_tau - tau)'], {}), '(old_tau - tau)\n', (8989, 9004), True, 'import numpy as np\n')]
#!/usr/bin/python """ """ # ---- import json import tempfile import itertools import subprocess import matplotlib.pyplot as plt import scipy.stats as stats from matplotlib.font_manager import FontProperties # ---- import numpy as np import pandas as pd import statsmodels.api as sm ## ---------------------------------------------------------------- ## Commit time related plots ## ---------------------------------------------------------------- class CommitData(object): "Prepare commit data into ready to plot form" def __init__(self, logs): # Clean data dfs = {k : d.commit for k,d in logs.items() if not d.commit.empty} # Get summary stats pts = pd.concat([d[['H','at']] for _,d in dfs.items()]) t0 = np.min(pts['at']).tz_localize(None) ts = (pts['at'].dt.tz_localize(None) - t0).astype('timedelta64') / 1e9 hs = pts['H'] # Calculate relative time for k, df in dfs.items() : df['dt'] = (df['at'].dt.tz_localize(None) - t0).astype('timedelta64') / 1e9 self.fit = logs.fitTvsH self.TPS = logs.TPS # Store precalculated data self.tMin = np.min(ts) self.tMax = np.max(ts) self.hMin = np.min(hs) self.hMax = np.max(hs) self.dfs = dfs def plot_points(self, ax, reltime=False): "Simply plot points" for k,df in self.dfs.items() : xs = df['dt' if reltime else 'at'] ys = df['H'] ax.plot(xs, ys, '+', label=k) self.add_title_h("Height vs time") p = self.fit.params hs = np.asarray([ np.min(df['H']), np.max(df['H'])]) ax.plot( hs * p[1] + p[0], hs, '-', color='gray', lw=0.5) plt.xlabel("time") plt.ylabel("H") def plot_residuals_HvsT(self, ax): for k,df in self.dfs.items() : p = self.fit.params xs = df['dt'] ys = df['H'] - (xs / p[1] - p[0]/p[1]) ax.plot(xs, ys, '+', label=k) self.add_title_h("Height residuals") plt.xlabel("time") plt.ylabel("ฮ”H") def plot_residuals_TvsH(self, ax): for k,df in self.dfs.items() : p = self.fit.params xs = df['H'] ys = df['dt'] - (xs * p[1] + p[0]) ax.plot(xs, ys, '+', label=k) self.add_title_h("Time residuals") plt.xlabel("H") plt.ylabel("ฮ”t") def plot_ntx(self,ax): for k in self.dfs: df = self.dfs[k] break tot = np.sum(df['Ntx']) avg = np.average(df['Ntx']) plt.title("Block size (ฮผ=%.2f, tot=%i)" % (avg,tot)) plt.xlabel("Height") plt.ylabel("N of transactions") plt.axhline(y=0, color='k') plt.axhline(y=avg, color='k') plt.plot(df['H'], df['Ntx'],'+') def plot_ntx_distr(self,ax): for k in self.dfs: df = self.dfs[k] break ntx = df['Ntx'] mu = np.average(ntx) sig = np.std(ntx) n1 = np.min(ntx) n2 = np.max(ntx) # plt.title("Block size (ฮผ=%.2f)" % (mu)) plt.xlabel("N of transactions") plt.ylabel("prob. density") # plt.hist(ntx, n2-n1+1, density=True) x = np.linspace(n1, n2, 200) plt.plot(x, stats.norm.pdf(x, mu, sig), color='r') plt.axvline(mu, color='r') def plot_n_signatures(self,ax): for k in self.dfs: df = self.dfs[k] break df = df[df['H']>1] avg = np.average(df['nsign']) plt.title("N signatures for block (avg = %.2f)" % avg) plt.plot(df['H'] - 1, df['nsign'],'+') def add_title_h(self,s ): plt.title("%s (%.03f s/block, %.f tps)" % (s, float(self.fit.params[1]), self.TPS )) # ---------------------------------------------------------------- # Plotting routines # ---------------------------------------------------------------- class SimplePlot(object): "Simple plotter" def __init__(self): self.fig = plt.figure() self.ax = plt.subplot(111) plt.grid() def __enter__(self): return self.ax def __exit__(self, type, value, trace): pass class LegendPlot(object): "Plotter with legend" def __init__(self): fig,ax = figure_with_legend() self.fig = fig self.ax = ax plt.grid() def __enter__(self): return self.ax def __exit__(self, type, value, trace): add_legend(self.ax) def figure_with_legend(): fig = plt.figure(figsize=[9, 4.8]) ax = plt.subplot(111) box = ax.get_position() ax.set_position([box.x0, box.y0, box.width * 0.8, box.height]) return fig,ax def add_legend(ax) : fontP = FontProperties() fontP.set_size('small') ax.legend(loc='center left', bbox_to_anchor=(1, 0.5), prop=fontP) # ---------------------------------------------------------------- # Plotting routines # ---------------------------------------------------------------- def plot_round(logs): """ Plot round growth """ dfs = {k : v.round for k,v in logs.items() if not v.round.empty} # fig,ax = figure_with_legend() plt.title("Round vs T") plt.grid() plt.xlabel("Time") plt.ylabel("Round") for k,v in dfs.items(): plt.plot(v['at'], v['R'], lw=0.5, marker='x', markersize=2, label=k) add_legend(ax) return fig def plot_round_distr(logs): "Plot distribution of round numbers per figure" dfs = {k : v.roundDistr for k,v in logs.items() if not v.round.empty} n = len(dfs) fig,ax = figure_with_legend() for i,(nm,rs) in enumerate(dfs.items()): xs = np.asarray(range(len(rs))) plt.bar(xs + i / n, rs, width=1/n, align='edge', label=nm) print("%12s: <R> = %.2f" % (nm, np.average(xs, weights=rs))) add_legend(ax) return fig def plot_mempool_size(dfs): "Plot mempool size over time" fig,ax = figure_with_legend() plt.grid() plt.title("Mempool size") colors = plt.rcParams['axes.prop_cycle'].by_key()['color'] def pickColor(i): return colors[i % len(colors)] for i,k in enumerate(dfs) : df = dfs[k].mempool dB = df[df['msg'] == "Mempool before filtering"] dA = df[df['msg'] == "Mempool after filtering"] plt.plot(dB['at'], dB['size'], '+', color=pickColor(i), ms=3, label=k+' before') plt.plot(dA['at'], dA['size'], 'x', color=pickColor(i), ms=3, label=k+' after') add_legend(ax) return fig def plot_mempool_added(dfs): "Plot N of tx added to mempool over time" fig = plt.figure() plt.grid() plt.title("Number of transaction added to mempool") colors = plt.rcParams['axes.prop_cycle'].by_key()['color'] for i,df in enumerate(dfs) : df = dfs[df].mempool d = df[df['msg'] == "Mempool after filtering"] plt.plot(d['at'], d['added'], '+', color=colors[i], ms=3) plt.plot(d['at'], d['discarded'], 'v', color=colors[i], ms=3) plt.plot(d['at'], d['filtered'], 'x', color=colors[i], ms=3) return fig def plot_gossip(logs, key): """ Plot statistics about gossip" """ fig,ax = figure_with_legend() plt.grid() plt.title("Gossip statistics for: "+key) for i,(k,d) in enumerate(logs.items()): tx = d[key] tx = tx - tx.values[0] ax.plot(d['at'], tx, '+', label=k, markersize=1.5) add_legend(ax) return fig def plot_gossip_rxtx_ratio(dfs, key): "Plot statistics about gossip" dfs = [d.gossip() for d in dfs] fig = plt.figure() plt.grid() plt.title("Rx/Tx ratio for: "+key) for d in dfs: plt.plot(d['at'], d['Rx' + key]/d['Tx'+key], '+') return fig
[ "matplotlib.pyplot.title", "numpy.sum", "matplotlib.pyplot.bar", "matplotlib.pyplot.figure", "matplotlib.pyplot.axvline", "matplotlib.font_manager.FontProperties", "numpy.std", "numpy.max", "numpy.linspace", "matplotlib.pyplot.axhline", "numpy.average", "numpy.min", "matplotlib.pyplot.ylabel...
[((4652, 4680), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '[9, 4.8]'}), '(figsize=[9, 4.8])\n', (4662, 4680), True, 'import matplotlib.pyplot as plt\n'), ((4691, 4707), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(111)'], {}), '(111)\n', (4702, 4707), True, 'import matplotlib.pyplot as plt\n'), ((4855, 4871), 'matplotlib.font_manager.FontProperties', 'FontProperties', ([], {}), '()\n', (4869, 4871), False, 'from matplotlib.font_manager import FontProperties\n'), ((5300, 5323), 'matplotlib.pyplot.title', 'plt.title', (['"""Round vs T"""'], {}), "('Round vs T')\n", (5309, 5323), True, 'import matplotlib.pyplot as plt\n'), ((5328, 5338), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (5336, 5338), True, 'import matplotlib.pyplot as plt\n'), ((5343, 5361), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Time"""'], {}), "('Time')\n", (5353, 5361), True, 'import matplotlib.pyplot as plt\n'), ((5366, 5385), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Round"""'], {}), "('Round')\n", (5376, 5385), True, 'import matplotlib.pyplot as plt\n'), ((6089, 6099), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (6097, 6099), True, 'import matplotlib.pyplot as plt\n'), ((6104, 6129), 'matplotlib.pyplot.title', 'plt.title', (['"""Mempool size"""'], {}), "('Mempool size')\n", (6113, 6129), True, 'import matplotlib.pyplot as plt\n'), ((6725, 6737), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (6735, 6737), True, 'import matplotlib.pyplot as plt\n'), ((6742, 6752), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (6750, 6752), True, 'import matplotlib.pyplot as plt\n'), ((6757, 6808), 'matplotlib.pyplot.title', 'plt.title', (['"""Number of transaction added to mempool"""'], {}), "('Number of transaction added to mempool')\n", (6766, 6808), True, 'import matplotlib.pyplot as plt\n'), ((7327, 7337), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (7335, 7337), True, 'import matplotlib.pyplot as plt\n'), ((7342, 7384), 'matplotlib.pyplot.title', 'plt.title', (["('Gossip statistics for: ' + key)"], {}), "('Gossip statistics for: ' + key)\n", (7351, 7384), True, 'import matplotlib.pyplot as plt\n'), ((7697, 7709), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (7707, 7709), True, 'import matplotlib.pyplot as plt\n'), ((7714, 7724), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (7722, 7724), True, 'import matplotlib.pyplot as plt\n'), ((7729, 7765), 'matplotlib.pyplot.title', 'plt.title', (["('Rx/Tx ratio for: ' + key)"], {}), "('Rx/Tx ratio for: ' + key)\n", (7738, 7765), True, 'import matplotlib.pyplot as plt\n'), ((1178, 1188), 'numpy.min', 'np.min', (['ts'], {}), '(ts)\n', (1184, 1188), True, 'import numpy as np\n'), ((1209, 1219), 'numpy.max', 'np.max', (['ts'], {}), '(ts)\n', (1215, 1219), True, 'import numpy as np\n'), ((1240, 1250), 'numpy.min', 'np.min', (['hs'], {}), '(hs)\n', (1246, 1250), True, 'import numpy as np\n'), ((1271, 1281), 'numpy.max', 'np.max', (['hs'], {}), '(hs)\n', (1277, 1281), True, 'import numpy as np\n'), ((1742, 1760), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""time"""'], {}), "('time')\n", (1752, 1760), True, 'import matplotlib.pyplot as plt\n'), ((1769, 1784), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""H"""'], {}), "('H')\n", (1779, 1784), True, 'import matplotlib.pyplot as plt\n'), ((2069, 2087), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""time"""'], {}), "('time')\n", (2079, 2087), True, 'import matplotlib.pyplot as plt\n'), ((2096, 2112), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""ฮ”H"""'], {}), "('ฮ”H')\n", (2106, 2112), True, 'import matplotlib.pyplot as plt\n'), ((2390, 2405), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""H"""'], {}), "('H')\n", (2400, 2405), True, 'import matplotlib.pyplot as plt\n'), ((2414, 2430), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""ฮ”t"""'], {}), "('ฮ”t')\n", (2424, 2430), True, 'import matplotlib.pyplot as plt\n'), ((2547, 2564), 'numpy.sum', 'np.sum', (["df['Ntx']"], {}), "(df['Ntx'])\n", (2553, 2564), True, 'import numpy as np\n'), ((2579, 2600), 'numpy.average', 'np.average', (["df['Ntx']"], {}), "(df['Ntx'])\n", (2589, 2600), True, 'import numpy as np\n'), ((2609, 2662), 'matplotlib.pyplot.title', 'plt.title', (["('Block size (ฮผ=%.2f, tot=%i)' % (avg, tot))"], {}), "('Block size (ฮผ=%.2f, tot=%i)' % (avg, tot))\n", (2618, 2662), True, 'import matplotlib.pyplot as plt\n'), ((2670, 2690), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Height"""'], {}), "('Height')\n", (2680, 2690), True, 'import matplotlib.pyplot as plt\n'), ((2699, 2730), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""N of transactions"""'], {}), "('N of transactions')\n", (2709, 2730), True, 'import matplotlib.pyplot as plt\n'), ((2739, 2766), 'matplotlib.pyplot.axhline', 'plt.axhline', ([], {'y': '(0)', 'color': '"""k"""'}), "(y=0, color='k')\n", (2750, 2766), True, 'import matplotlib.pyplot as plt\n'), ((2777, 2806), 'matplotlib.pyplot.axhline', 'plt.axhline', ([], {'y': 'avg', 'color': '"""k"""'}), "(y=avg, color='k')\n", (2788, 2806), True, 'import matplotlib.pyplot as plt\n'), ((2815, 2848), 'matplotlib.pyplot.plot', 'plt.plot', (["df['H']", "df['Ntx']", '"""+"""'], {}), "(df['H'], df['Ntx'], '+')\n", (2823, 2848), True, 'import matplotlib.pyplot as plt\n'), ((2994, 3009), 'numpy.average', 'np.average', (['ntx'], {}), '(ntx)\n', (3004, 3009), True, 'import numpy as np\n'), ((3024, 3035), 'numpy.std', 'np.std', (['ntx'], {}), '(ntx)\n', (3030, 3035), True, 'import numpy as np\n'), ((3050, 3061), 'numpy.min', 'np.min', (['ntx'], {}), '(ntx)\n', (3056, 3061), True, 'import numpy as np\n'), ((3076, 3087), 'numpy.max', 'np.max', (['ntx'], {}), '(ntx)\n', (3082, 3087), True, 'import numpy as np\n'), ((3106, 3143), 'matplotlib.pyplot.title', 'plt.title', (["('Block size (ฮผ=%.2f)' % mu)"], {}), "('Block size (ฮผ=%.2f)' % mu)\n", (3115, 3143), True, 'import matplotlib.pyplot as plt\n'), ((3154, 3185), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""N of transactions"""'], {}), "('N of transactions')\n", (3164, 3185), True, 'import matplotlib.pyplot as plt\n'), ((3194, 3221), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""prob. density"""'], {}), "('prob. density')\n", (3204, 3221), True, 'import matplotlib.pyplot as plt\n'), ((3240, 3280), 'matplotlib.pyplot.hist', 'plt.hist', (['ntx', '(n2 - n1 + 1)'], {'density': '(True)'}), '(ntx, n2 - n1 + 1, density=True)\n', (3248, 3280), True, 'import matplotlib.pyplot as plt\n'), ((3291, 3315), 'numpy.linspace', 'np.linspace', (['n1', 'n2', '(200)'], {}), '(n1, n2, 200)\n', (3302, 3315), True, 'import numpy as np\n'), ((3383, 3409), 'matplotlib.pyplot.axvline', 'plt.axvline', (['mu'], {'color': '"""r"""'}), "(mu, color='r')\n", (3394, 3409), True, 'import matplotlib.pyplot as plt\n'), ((3562, 3585), 'numpy.average', 'np.average', (["df['nsign']"], {}), "(df['nsign'])\n", (3572, 3585), True, 'import numpy as np\n'), ((3594, 3648), 'matplotlib.pyplot.title', 'plt.title', (["('N signatures for block (avg = %.2f)' % avg)"], {}), "('N signatures for block (avg = %.2f)' % avg)\n", (3603, 3648), True, 'import matplotlib.pyplot as plt\n'), ((3657, 3696), 'matplotlib.pyplot.plot', 'plt.plot', (["(df['H'] - 1)", "df['nsign']", '"""+"""'], {}), "(df['H'] - 1, df['nsign'], '+')\n", (3665, 3696), True, 'import matplotlib.pyplot as plt\n'), ((4140, 4152), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (4150, 4152), True, 'import matplotlib.pyplot as plt\n'), ((4172, 4188), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(111)'], {}), '(111)\n', (4183, 4188), True, 'import matplotlib.pyplot as plt\n'), ((4197, 4207), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (4205, 4207), True, 'import matplotlib.pyplot as plt\n'), ((4482, 4492), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (4490, 4492), True, 'import matplotlib.pyplot as plt\n'), ((5422, 5490), 'matplotlib.pyplot.plot', 'plt.plot', (["v['at']", "v['R']"], {'lw': '(0.5)', 'marker': '"""x"""', 'markersize': '(2)', 'label': 'k'}), "(v['at'], v['R'], lw=0.5, marker='x', markersize=2, label=k)\n", (5430, 5490), True, 'import matplotlib.pyplot as plt\n'), ((5826, 5886), 'matplotlib.pyplot.bar', 'plt.bar', (['(xs + i / n)', 'rs'], {'width': '(1 / n)', 'align': '"""edge"""', 'label': 'nm'}), "(xs + i / n, rs, width=1 / n, align='edge', label=nm)\n", (5833, 5886), True, 'import matplotlib.pyplot as plt\n'), ((6998, 7055), 'matplotlib.pyplot.plot', 'plt.plot', (["d['at']", "d['added']", '"""+"""'], {'color': 'colors[i]', 'ms': '(3)'}), "(d['at'], d['added'], '+', color=colors[i], ms=3)\n", (7006, 7055), True, 'import matplotlib.pyplot as plt\n'), ((7064, 7125), 'matplotlib.pyplot.plot', 'plt.plot', (["d['at']", "d['discarded']", '"""v"""'], {'color': 'colors[i]', 'ms': '(3)'}), "(d['at'], d['discarded'], 'v', color=colors[i], ms=3)\n", (7072, 7125), True, 'import matplotlib.pyplot as plt\n'), ((7134, 7194), 'matplotlib.pyplot.plot', 'plt.plot', (["d['at']", "d['filtered']", '"""x"""'], {'color': 'colors[i]', 'ms': '(3)'}), "(d['at'], d['filtered'], 'x', color=colors[i], ms=3)\n", (7142, 7194), True, 'import matplotlib.pyplot as plt\n'), ((7790, 7843), 'matplotlib.pyplot.plot', 'plt.plot', (["d['at']", "(d['Rx' + key] / d['Tx' + key])", '"""+"""'], {}), "(d['at'], d['Rx' + key] / d['Tx' + key], '+')\n", (7798, 7843), True, 'import matplotlib.pyplot as plt\n'), ((3336, 3362), 'scipy.stats.norm.pdf', 'stats.norm.pdf', (['x', 'mu', 'sig'], {}), '(x, mu, sig)\n', (3350, 3362), True, 'import scipy.stats as stats\n'), ((767, 784), 'numpy.min', 'np.min', (["pts['at']"], {}), "(pts['at'])\n", (773, 784), True, 'import numpy as np\n'), ((1633, 1648), 'numpy.min', 'np.min', (["df['H']"], {}), "(df['H'])\n", (1639, 1648), True, 'import numpy as np\n'), ((1650, 1665), 'numpy.max', 'np.max', (["df['H']"], {}), "(df['H'])\n", (1656, 1665), True, 'import numpy as np\n'), ((5925, 5951), 'numpy.average', 'np.average', (['xs'], {'weights': 'rs'}), '(xs, weights=rs)\n', (5935, 5951), True, 'import numpy as np\n')]
""" Regression Using Decision Tree, Random Tree, Bootstrap Aggregating, and Boosting. Copyright (c) 2020 <NAME> """ import numpy as np class RTLearner: def __init__(self, leaf=1, tol=1.0e-6): """ leaf Lowest number of leaves tol Tolerance to group close-valued leaves """ self.leaf = leaf self.tol = tol def buildTree(self, X, Y): """ Builds the decision-tree table. column 0 = feature used for the split (-1 indicates a leaf) column 1 = split value column 2 = relative position left branch (0 indicates no left branch) column 3 = relative position right branch (0 indicates no right branch) """ # Return the mean if equal or less than the lowest number of leaves if (X.shape[0] <= self.leaf): return np.array([-1, Y.mean(), 0, 0]) # Return the mean if all remaining leaves have close values Ym = Y.mean() deltaY = np.absolute(Y-Ym) if (all(deltaY <= self.tol)): return np.array([-1, Ym, 0, 0]) # Keep splitting else: # Randomly pick a feature and split idx = np.random.randint(0, X.shape[1]) i = np.random.randint(0, X.shape[0], size=2) split_value = (X[i[0], idx] + X[i[1], idx]) / 2.0 # Build the left branch dataset X_left = X[X[:, idx] <= split_value] Y_left = Y[X[:, idx] <= split_value] # Return the mean if there is no split (because all data end up in # the left branch). if (X_left.shape[0] == X.shape[0]): return np.array([-1, Y_left.mean(), 0, 0]) # Keep splitting else: # Build the right branch dataset X_right = X[X[:, idx] > split_value] Y_right = Y[X[:, idx] > split_value] # Search the two new branches left_branch = self.buildTree(X_left, Y_left) right_branch = self.buildTree(X_right, Y_right) # Return the sub-tree table k = divmod(len(left_branch), 4)[0] root = np.array([idx, split_value, 1, k+1]) return np.concatenate((root, left_branch, right_branch)) def createModel(self, X, Y): """ Wrapper for building the decision-tree table. """ # Build the tree-table as 1-dim array a = self.buildTree(X, Y) # Reshape it as an (n_row, 4) matrix n_row = divmod(len(a), 4)[0] self.treeTable = a.reshape(n_row, 4) def evalData(self, X): """ Evaluates a dataset of features with the created decision-tree table. column 0 = feature used for the split (-1 indicates a leaf) column 1 = split value column 2 = relative position left branch (0 indicates no left branch) column 3 = relative position right branch (0 indicates no right branch) """ n = X.shape[0] # Number of data to evaluate pred_Y = np.empty(n) # Allocate prediction array # Loop over the dataset for i in range(n): # Start from the root node of the decision-tree table row = 0 feature = int(round(self.treeTable[0, 0])) # Move along the decision-tree table until a leaf is found while (feature != -1): # Next node is on the left branch if (X[i, feature] <= self.treeTable[row, 1]): delta = int(round(self.treeTable[row, 2])) # Next node is on the right branch else: delta = int(round(self.treeTable[row, 3])) # Get the feature of the next node row += delta feature = int(round(self.treeTable[row, 0])) # Set the leaf value as predicted value pred_Y[i] = self.treeTable[row, 1] return pred_Y
[ "numpy.absolute", "numpy.empty", "numpy.random.randint", "numpy.array", "numpy.concatenate" ]
[((1001, 1020), 'numpy.absolute', 'np.absolute', (['(Y - Ym)'], {}), '(Y - Ym)\n', (1012, 1020), True, 'import numpy as np\n'), ((3122, 3133), 'numpy.empty', 'np.empty', (['n'], {}), '(n)\n', (3130, 3133), True, 'import numpy as np\n'), ((1076, 1100), 'numpy.array', 'np.array', (['[-1, Ym, 0, 0]'], {}), '([-1, Ym, 0, 0])\n', (1084, 1100), True, 'import numpy as np\n'), ((1207, 1239), 'numpy.random.randint', 'np.random.randint', (['(0)', 'X.shape[1]'], {}), '(0, X.shape[1])\n', (1224, 1239), True, 'import numpy as np\n'), ((1256, 1296), 'numpy.random.randint', 'np.random.randint', (['(0)', 'X.shape[0]'], {'size': '(2)'}), '(0, X.shape[0], size=2)\n', (1273, 1296), True, 'import numpy as np\n'), ((2215, 2253), 'numpy.array', 'np.array', (['[idx, split_value, 1, k + 1]'], {}), '([idx, split_value, 1, k + 1])\n', (2223, 2253), True, 'import numpy as np\n'), ((2275, 2324), 'numpy.concatenate', 'np.concatenate', (['(root, left_branch, right_branch)'], {}), '((root, left_branch, right_branch))\n', (2289, 2324), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- """ Module summary description. More detailed description. """ import numpy as np import networkx as nx from math import sqrt as msqrt from numba import njit from shapely.errors import TopologicalError from shapely.geometry import MultiPolygon, GeometryCollection, Polygon, box, LineString, \ Point, MultiLineString, JOIN_STYLE from shapely.ops import cascaded_union, linemerge, unary_union, transform from gistools.coordinates import r_tree_idx from gistools.graph import part_graph from gistools.utils.check.type import is_iterable, type_assert def add_points_to_line(line, threshold): """ Add point coordinates to line geometry :param line: :param threshold: :return: """ return linemerge(cut_(line, threshold)) def aggregate_partitions(polygons, weights, nparts, division, weight_attr, split, recursive, **metis_options): """ Aggregate polygons into partitions :param polygons: polygons to aggregate :param weights: polygons' corresponding weight :param nparts: number of partitions :param division: list of final relative weights of each partition :param weight_attr: :param split: :param recursive: :param metis_options: :return: """ if "contig" not in metis_options.keys(): metis_options["contig"] = False graph = polygon_collection_to_graph(polygons, weights, split, metis_options["contig"], weight_attr) tpweights = [(d,) for d in division] partition = part_graph(graph, nparts, weight_attr, tpweights, recursive, **metis_options) # Return unions of polygons belonging to each part (no multi-polygons) return explode([no_artifact_unary_union([polygons[n] for n in part]) for part in partition]) def area_partition_polygon(polygon, unit_area, disaggregation_factor, precision, recursive, split, **metis_options): """ Partition polygon into a subset of polygons of equal area :param polygon: polygon intended to be partitioned :param unit_area: area of a sub-polygon :param disaggregation_factor: factor use to discretize polygons before aggregation :param recursive: k-way or recursive method for partitioning :param precision: metric precision for sub-polygon area :param split: function used to split polygon into smaller unit blocks :param metis_options: specific METIS options (see METIS manual) :return: """ nparts = int(polygon.area/unit_area) if nparts <= 1 and (polygon.area - unit_area) < unit_area/disaggregation_factor: return [polygon] # Split polygon into sub-elements split_poly = split_polygon(polygon, split, unit_area/disaggregation_factor, get_explode=True) division = [unit_area/polygon.area] * nparts if polygon.area % unit_area != 0: # and (polygon.area - nparts * unit_area) >= unit_area/disaggregation_factor: division += [(polygon.area - nparts * unit_area)/polygon.area] nparts += 1 area = [int(poly.area / precision) for poly in split_poly] return aggregate_partitions(split_poly, area, nparts, division, "area", split, recursive, **metis_options) def centroid(point_collection): """ Retrieve centroid of multiple points :param point_collection: :return: """ x_centroid = np.mean([pt.x for pt in point_collection]) y_centroid = np.mean([pt.y for pt in point_collection]) return Point([x_centroid, y_centroid]) def connect_lines_to_point(line_collection, point): """ Connect a set of lines to some point :param line_collection: :param point: :return: """ new_line_collection = [] for line in line_collection: if Point(line.coords[0]).distance(point) < Point(line.coords[-1]).distance(point): new_line_collection.append(LineString(point.coords[:] + line.coords[:])) else: new_line_collection.append(LineString(line.coords[:] + point.coords[:])) return new_line_collection def cut(line, threshold, count=0): """ Cut a line in segments Cut a line in segments whose length is below a threshold value. This method is more randomless regarding the final size of the line segments. See 'cut_' function for more accuracy :param line: :param threshold: :param count: :return: """ result = [] if threshold < 0 or threshold >= line.length or count == 250: return [line] # Recursively cut line in 2 at midpoint p = line.interpolate(0.5, normalized=True) split_line = cut_at_point(line, p) for sub_line in split_line: result.extend(cut(sub_line, threshold, count + 1)) return result def cut_(line, threshold): """ Cut a line in segments (method 2) This method cuts a line in as many segments as necessary, depending on the given threshold. For instance, a line of 105m will be cut into 10 pieces of 10m + 1 piece of 5m if threshold=10 :param line: LineString :param threshold: minimum sub line piece size :return: """ if threshold < 0 or threshold >= line.length: return [line] result = [] while "It remains line to cut": split_line = cut_at_distance(line, threshold/line.length, normalized=True) result.append(split_line[0]) if split_line[1].length > threshold: line = split_line[1] else: result.append(split_line[1]) break return result def cut_at_distance(line, distance, normalized=False): """ Cut line at given distance from starting point :param line: :param distance: :param normalized: :return: """ if normalized: length = 1 else: length = line.length if distance <= 0.0 or distance >= length: return [line] coords = list(line.coords) for i, p in enumerate(coords): pd = line.project(Point(p), normalized=normalized) if pd == distance: return [LineString(coords[:i+1]), LineString(coords[i:])] elif pd > distance: cp = line.interpolate(distance, normalized=normalized) try: return [LineString(coords[:i] + [(cp.x, cp.y)]), LineString([(cp.x, cp.y)] + coords[i:])] except ValueError: return [LineString(coords[:i] + [(cp.x, cp.y, cp.z)]), LineString([(cp.x, cp.y, cp.z)] + coords[i:])] def cut_at_point(line, point): """ Cut line at point Cut line at point, which can be within or without the geometry :param line: :param point: :return: """ d = line.project(point) return cut_at_distance(line, d) def cut_at_points(line, points): """ Cut line at multiple points :param line: :param points: :return: """ cut_line = [] distance = [line.project(point) for point in points] sorted_points = [point for _, point in sorted(zip(distance, points))] for idx, point in enumerate(sorted_points): cut_line.extend(cut_at_point(line, point)) if idx < len(sorted_points) - 1: line = cut_line.pop() return cut_line def dissolve(geometry_collection): """ Recursively join contiguous geometries in collection :param geometry_collection: :return: """ if not is_iterable(geometry_collection): raise TypeError("Input must be a collection but is '{}'".format(type(geometry_collection))) while "There is still geometries to aggregate": joint = [] idx = r_tree_idx(geometry_collection) geom_idx = [] increment = 0 while len(geom_idx) < len(geometry_collection): if increment not in geom_idx: geom = geometry_collection[increment] union_idx, union = intersecting_features(geom, geometry_collection, idx) if len(union) > 0: joint.append(cascaded_union(union)) for ix in union_idx: idx.delete(ix, geometry_collection[ix].bounds) geom_idx.extend(union_idx) increment += 1 if len(joint) < len(geometry_collection): geometry_collection = joint else: break return joint def explode(geometry_collection): """ Convert multi-part geometry collection into single-part :param geometry_collection: valid geometry collection :return: """ single = [] if not is_iterable(geometry_collection): geometry_collection = [geometry_collection] for geom in geometry_collection: try: single.extend(geom) except TypeError: single.append(geom) return single def fishnet(polygon, threshold): """ Intersect polygon with a regular grid or "fishnet" :param polygon: :param threshold: :return: """ return polygon_to_mesh(polygon, threshold, mesh) def hexana(polygon, threshold): """ Split a polygon using a honeycomb grid :param polygon: original polygon to split :param threshold: unit hexagon surface :return: list of polygons """ return polygon_to_mesh(polygon, threshold, honeycomb) # Thanks to https://gist.github.com/urschrei/17cf0be92ca90a244a91 @njit() def honeycomb_nb(startx, starty, endx, endy, radius): """ Calculate a grid of hexagon coordinates of the given radius given lower-left and upper-right coordinates Returns a list of lists containing 6 tuples of x, y point coordinates These can be used to construct valid regular hexagonal polygons - update 04/23/2019: * can give either radius or area of unit hexagon * return a list of shapely Polygon You will probably want to use projected coordinates for this """ # calculate side length given radius sl = (2 * radius) * np.tan(np.pi / 6) # calculate radius for a given side-length # (a * (math.cos(math.pi / 6) / math.sin(math.pi / 6)) / 2) # see http://www.calculatorsoup.com/calculators/geometry-plane/polygon.php # calculate coordinates of the hexagon points # sin(30) p = sl * 0.5 b = sl * np.cos(np.radians(30)) w = b * 2 h = 2 * sl # offset start and end coordinates by hex widths and heights to guarantee coverage startx = startx - w starty = starty - h endx = endx + w endy = endy + h origx = startx # offsets for moving along and up rows xoffset = b yoffset = 3 * p row = 1 while starty < endy: if row % 2 == 0: startx = origx + xoffset else: startx = origx while startx < endx: p1x = startx p1y = starty + p p2x = startx p2y = starty + (3 * p) p3x = startx + b p3y = starty + h p4x = startx + w p4y = starty + (3 * p) p5x = startx + w p5y = starty + p p6x = startx + b p6y = starty poly = [ (p1x, p1y), (p2x, p2y), (p3x, p3y), (p4x, p4y), (p5x, p5y), (p6x, p6y), (p1x, p1y)] yield poly startx += w starty += yoffset row += 1 def honeycomb(startx, starty, endx, endy, radius=None, area=None): """ Parameters ---------- startx starty endx endy radius area Returns ------- """ if not radius: radius = msqrt(area / (2*msqrt(3))) return (Polygon(poly) for poly in honeycomb_nb(startx, starty, endx, endy, radius)) def intersecting_features(geometry, geometry_collection, r_tree=None): """ Return list of geometries intersecting with given geometry :param geometry: :param geometry_collection: :param r_tree: rtree index corresponding to geometry collection :return: """ is_intersecting = intersects(geometry, geometry_collection, r_tree) return [i for i in range(len(geometry_collection)) if is_intersecting[i]], \ [geom for i, geom in enumerate(geometry_collection) if is_intersecting[i]] def intersects(geometry, geometry_collection, r_tree=None): """ Return if geometry intersects with geometries of collection Use this function with large geometry collections :param geometry: :param geometry_collection: :param r_tree: :return: list of boolean of length = length(geometry_collection) """ # Use Rtree to speed up ! if r_tree is None: r_tree = r_tree_idx(geometry_collection) list_of_intersecting_features = list(r_tree.intersection(geometry.bounds)) return [False if f not in list_of_intersecting_features else geometry.intersects(geometry_collection[f]) for f in range(len(geometry_collection))] def is_in_collection(geometry, geometry_collection, r_tree): """ Test if geometry is present in collection (using shapely 'equals' method) :param geometry: :param geometry_collection: :param r_tree: :return: """ _, list_of_intersecting_features = intersecting_features(geometry, geometry_collection, r_tree) for geom in list_of_intersecting_features: if geometry.equals(geom): return True return False def is_line_connected_to(line, geometry_collection): """ Is line connected to one of the geometries in collection ? :param line: :param geometry_collection: :return: """ return [other.intersects(Point(line.coords[0])) for other in geometry_collection], [other.intersects(Point( line.coords[-1])) for other in geometry_collection] def katana(polygon, threshold, count=0): """ Split a polygon See https://snorfalorpagus.net/blog/2016/03/13/splitting-large-polygons-for-faster-intersections/ Copyright (c) 2016, <NAME> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. :param polygon: Shapely polygon :param threshold: :param count: :return: """ if count == 0: if not polygon.is_valid: polygon = polygon.buffer(0, 0) result = [] width = polygon.bounds[2] - polygon.bounds[0] height = polygon.bounds[3] - polygon.bounds[1] if width * height <= threshold or count == 250: return [polygon] if height >= width: a = box(polygon.bounds[0], polygon.bounds[1], polygon.bounds[2], polygon.bounds[1] + height/2) b = box(polygon.bounds[0], polygon.bounds[1] + height/2, polygon.bounds[2], polygon.bounds[3]) else: a = box(polygon.bounds[0], polygon.bounds[1], polygon.bounds[0] + width/2, polygon.bounds[3]) b = box(polygon.bounds[0] + width/2, polygon.bounds[1], polygon.bounds[2], polygon.bounds[3]) for sword in (a, b,): split_poly = polygon.intersection(sword) if not isinstance(split_poly, GeometryCollection): split_poly = [split_poly] for sub_poly in split_poly: if isinstance(sub_poly, (Polygon, MultiPolygon)): result.extend(katana(sub_poly, threshold, count+1)) return result def katana_centroid(polygon, threshold, count=0): """ Split a polygon in equal areas Thanks to https://snorfalorpagus.net/blog/2016/03/13/splitting-large-polygons-for-faster-intersections/ and <NAME> in http://community-gispython-org-community-projects.955323.n3.nabble.com/Community-Spliting-a -polygon- into-two-polygons-with-the-same-area-td4024026.html#a4024033, we merge here both approaches to split a polygon into a number of sub-polygons of almost equal areas. :param polygon: Shapely polygon :param threshold: :param count: :return: """ if count == 0: if not polygon.is_valid: polygon = polygon.buffer(0, 0) result = [] width = polygon.bounds[2] - polygon.bounds[0] height = polygon.bounds[3] - polygon.bounds[1] if width * height <= threshold or count == 250: return [polygon] if height >= width: a = box(polygon.bounds[0], polygon.bounds[1], polygon.bounds[2], polygon.centroid.y) b = box(polygon.bounds[0], polygon.centroid.y, polygon.bounds[2], polygon.bounds[3]) else: a = box(polygon.bounds[0], polygon.bounds[1], polygon.centroid.x, polygon.bounds[3]) b = box(polygon.centroid.x, polygon.bounds[1], polygon.bounds[2], polygon.bounds[3]) for sword in (a, b,): split_poly = polygon.intersection(sword) if not isinstance(split_poly, GeometryCollection): split_poly = [split_poly] for sub_poly in split_poly: if isinstance(sub_poly, (Polygon, MultiPolygon)): result.extend(katana_centroid(sub_poly, threshold, count+1)) return result def length_of_segments(line): """ Retrieve segment length in line :param line: :return: """ return np.diff([line.project(Point(p)) for p in line.coords]) def mask(polygon_collection, mask_collection, fast_intersection_surface): """ Geometry mask :param polygon_collection: :param mask_collection: :param fast_intersection_surface: :return: """ # Retrieve base layer and mask geometry, split it for faster intersection # and explode it (to be sure there is no multi-parts) geometry = split_polygon_collection(polygon_collection, fast_intersection_surface, get_explode=True) mask_geometry = split_polygon_collection(mask_collection, fast_intersection_surface, get_explode=True) # Use Rtree to speed up ! idx = r_tree_idx(mask_geometry) # 0. Initialization result = [] for geom in geometry: list_of_intersecting_mask = list(idx.intersection(geom.bounds)) within = [geom.within(mask_geometry[n]) for n in list_of_intersecting_mask] if not any(within): is_intersecting = [geom.intersects(mask_geometry[n]) for n in list_of_intersecting_mask] if any(is_intersecting): difference = geom.difference(cascaded_union([mask_geometry[n] for n in list_of_intersecting_mask])) if not difference.is_empty: result.append(difference) else: result.append(geom) # Multi to single + dissolve coincident polygons result = explode(result) result = [no_artifact_unary_union(poly) for poly in dissolve(result)] return result def merge(line_collection): """ Merge connected lines :param line_collection: :return: """ # Merge MultiLinestring objects returned by the "join" function merged_line = [linemerge(line) if isinstance(line, MultiLineString) else line for line in dissolve(line_collection)] # Keep only single parts return explode(merged_line) def mesh(startx, starty, endx, endy, side=None, area=None): """ Compute a mesh grid :param startx: :param starty: :param endx: :param endy: :param side: :param area: :return: """ if not side: side = msqrt(area) startx = startx - side/2 starty = starty - side/2 endx = endx + side/2 endy = endy + side/2 origx = startx polygons = [] while starty < endy: startx = origx while startx < endx: poly = [ (startx, starty), (startx, starty + side), (startx + side, starty + side), (startx + side, starty)] polygons.append(Polygon(poly)) startx += side starty += side return polygons def nearest_feature(geometry, geometry_collection, r_tree=None): """ Return nearest feature from geometry collection to given geometry If some of the geometries intersect, the nearest feature is the one whose centroid is the closest to the centroid of the given geometry (but distance remains 0) :param geometry: :param geometry_collection: :param r_tree: rtree index corresponding to geometry collection :return: nearest feature index and corresponding distance """ # Use Rtree to speed up ! if r_tree is None: r_tree = r_tree_idx(geometry_collection) # Look if some geometries intersect list_of_intersecting_features, _ = intersecting_features(geometry, geometry_collection, r_tree) if list_of_intersecting_features: distance = [geometry.centroid.distance(geometry_collection[n].centroid) for n in list_of_intersecting_features] return list_of_intersecting_features[np.argmin(distance)], 0 else: list_of_nearest_features = list(r_tree.nearest(geometry.bounds, 1)) distance = [geometry.distance(geometry_collection[n]) for n in list_of_nearest_features] return list_of_nearest_features[np.argmin(distance)], np.min(distance) def no_artifact_unary_union(geoms, eps=0.00001): """ Make unary union that does not return artifacts Thanks to https://gis.stackexchange.com/questions/277334/shapely-polygon-union-results-in-strange-artifacts-of -tiny-non-overlapping-area :param geoms: list of geoms to aggregate :param eps: buffering precision :return: """ return unary_union(geoms).buffer(eps, 1, join_style=JOIN_STYLE.mitre).buffer(-eps, 1, join_style=JOIN_STYLE.mitre) def overlapping_features(geometry, geometry_collection, r_tree=None): """ Return list of geometries overlapping with given geometry Overlapping geometry is either overlapping in the shapely way, or within or containing the other geometry :param geometry: :param geometry_collection: :param r_tree: :return: """ idx, list_of_intersecting_features = intersecting_features(geometry, geometry_collection, r_tree) _overlaps = [[i, geom] for i, geom in zip(idx, list_of_intersecting_features) if geom.overlaps(geometry) or geom.within(geometry) or geom.contains(geometry)] return [overlap[0] for overlap in _overlaps], [overlap[1] for overlap in _overlaps] def overlaps(geometry, geometry_collection, r_tree=None): """ Return if geometry overlaps with geometries of collection Overlapping is regarded as any area shared by two geometries :param geometry: :param geometry_collection: :param r_tree: :return: """ is_intersecting = intersects(geometry, geometry_collection, r_tree) return [False if not is_intersecting[i] else geom.overlaps(geometry) or geom.within(geometry) or geom.contains( geometry) for i, geom in enumerate(geometry_collection)] def polygon_to_mesh(polygon, threshold, method): """ :param polygon: :param threshold: :param method: {'hexana', 'fishnet'} :return: """ grid = method(*polygon.bounds, area=threshold) split = [] for unit in grid: if unit.within(polygon): split.append(unit) elif unit.overlaps(polygon): split.append(unit.intersection(polygon)) return explode(split) def polygon_collection_to_graph(polygon_collection, weights, split, is_contiguous, weight_attr="weight"): """ Convert collection of polygons to networkx graph Conversion of a polygon collection into a graph allows later graph partitioning :param polygon_collection: :param weights: weight of each polygon in collection :param split: split function :param is_contiguous: True or False (metis options) :param weight_attr: name of weight attribute :return: """ if not is_iterable(polygon_collection): raise TypeError("Input must be a collection but is '{}'".format(type(polygon_collection))) if 'katana' in split.__name__: is_katana = True else: is_katana = False r_tree = r_tree_idx(polygon_collection) graph = nx.Graph() for n, polygon in enumerate(polygon_collection): list_of_intersecting_features, _ = intersecting_features(polygon, polygon_collection, r_tree) list_of_intersecting_features.remove(n) if list_of_intersecting_features or not is_contiguous: if is_katana: graph.add_edges_from([(n, feature) for feature in list_of_intersecting_features if not isinstance(polygon.intersection(polygon_collection[feature]), Point)]) else: graph.add_edges_from([(n, feature) for feature in list_of_intersecting_features]) graph.add_node(n, **{weight_attr: weights[n]}) return graph def radius_of_curvature(line, method="osculating"): """ Compute curvature radius of LineString :param line: :param method: method for computing radius of curvature {'circumscribe', 'osculating'} :return: """ def norm(xx, yy): return np.sqrt(xx ** 2 + yy ** 2) def tangent_vector(xi, yi): return (xi[2::] - xi[:-2]) / norm(xi[2::] - xi[:-2], yi[2::] - yi[:-2]), \ (yi[2::] - yi[:-2]) / norm(xi[2::] - xi[:-2], yi[2::] - yi[:-2]) if method == "osculating": if len(line.coords) >= 3: x = np.array(line.coords.xy[0]) y = np.array(line.coords.xy[1]) xi1 = np.concatenate((x[1::], [x[-1]])) yi1 = np.concatenate((y[1::], [y[-1]])) xi_1 = np.concatenate(([x[0]], x[:-1])) yi_1 = np.concatenate(([y[0]], y[:-1])) tangent_vector_xi1, tangent_vector_yi1 = tangent_vector(xi1, yi1) tangent_vector_xi_1, tangent_vector_yi_1 = tangent_vector(xi_1, yi_1) coefficient_of_curvature = \ norm(tangent_vector_xi1 - tangent_vector_xi_1, tangent_vector_yi1 - tangent_vector_yi_1) /\ norm(x[2::] - x[:-2], y[2::] - y[:-2]) coefficient_of_curvature[coefficient_of_curvature == 0] = 1e-6 rad_of_curvature = 1 / coefficient_of_curvature else: return np.array([10000]) elif method == "circumscribe": segment_length = length_of_segments(line) a, b = segment_length[:-1:], segment_length[1::] c = [] if len(line.coords) > 3: length_2_by_2_start = length_of_segments(LineString(line.coords[::2])) length_2_by_2_end = length_of_segments(LineString(line.coords[1::2])) for n in range(len(length_2_by_2_end)): c.extend([length_2_by_2_start[n], length_2_by_2_end[n]]) if len(length_2_by_2_start) > len(length_2_by_2_end): c.append(length_2_by_2_start[-1]) elif len(line.coords) == 3: c = LineString(line.coords[::2]).length elif len(line.coords) < 3: return np.array([10000]) heron = (a + b + c) * (b + c - a) * (c + a - b) * (a + b - c) heron[heron < 0] = 0 divider = np.sqrt(heron) divider[divider == 0] = 0.1 rad_of_curvature = a * b * c / divider else: rad_of_curvature = [] # Return values and add replicate to beginning of array (as result of curvature computation returns an array with # length = length(line.coords) - 2): return array with length = length(line.coords) - 1 return np.concatenate(([rad_of_curvature[0]], rad_of_curvature)) def shape_factor(polygon, convex_hull): """ Compute shape factor of given polygon Compute shape factor (here, circularity) of a given polygon using either convex hull or not :param polygon: :param convex_hull: should convex hull be used for computing shape ? (bool) :return: """ if convex_hull: return 4 * np.pi * polygon.convex_hull.area / (polygon.convex_hull.length ** 2) else: return 4 * np.pi * polygon.area / (polygon.length ** 2) @type_assert(polygon1=(Polygon, MultiPolygon), polygon2=(Polygon, MultiPolygon), normalized=bool) def shared_area(polygon1, polygon2, normalized=False): """ Get area shared by 2 polygons :param polygon1: :param polygon2: :param normalized: :return: """ if not polygon1.intersects(polygon2): return 0 else: new_poly = polygon1.intersection(polygon2) if normalized: return new_poly.area / polygon1.area else: return new_poly.area @type_assert(polygon=(Polygon, MultiPolygon), normalized=bool) def shared_area_among_collection(polygon: Polygon, polygon_collection, normalized: bool = False, r_tree=None): """ Get area shared by a polygon with polygons from a collection :param polygon: :param polygon_collection: :param normalized: :param r_tree: :return: """ if not is_iterable(polygon_collection): raise TypeError("Input 2 must be a collection but is '{}'".format(type(polygon_collection))) poly_intersects = intersects(polygon, polygon_collection, r_tree) return [shared_area(polygon, poly, normalized) if poly_intersects[n] else 0 for n, poly in enumerate( polygon_collection)] def split_collection(geometry_collection, threshold, method, get_explode): """ Split geometry collection :param geometry_collection: :param threshold: :param method: :param get_explode: :return: """ if not is_iterable(geometry_collection): raise TypeError("Geometry must be a collection") new_collection = [] for geom in geometry_collection: try: new_collection.extend(method(geom, threshold)) except TopologicalError: new_collection.append(geom) if get_explode: new_collection = explode(new_collection) # Return new collection return new_collection def split_line_collection(line_collection, threshold, method="cut", get_explode=False): """ :param line_collection: :param threshold: :param method: :param get_explode: :return: """ split_method = {'cut': cut} return split_collection(line_collection, threshold, split_method[method], get_explode) def split_polygon(polygon, method, threshold, get_explode): """ Split polygon with respect to method Split polygon and return exploded (no multi part) if necessary :param polygon: :param method: :param threshold: :param get_explode: (boolean) return exploded collection :return: """ sp_poly = method(polygon, threshold) if get_explode: return explode(sp_poly) else: return sp_poly def split_polygon_collection(polygon_collection, threshold, method="katana", get_explode=False): """ Split a collection of polygons :param polygon_collection: collection of shapely polygons :param threshold: threshold surface under which no more splitting must be achieved :param method: method used for splitting :param get_explode: :return: new polygon collection with only Polygon geometries (no MultiPolygon geometries) """ split_method = {'katana': katana, 'katana_centroid': katana_centroid} return split_collection(polygon_collection, threshold, split_method[method], get_explode) def to_2d(geometry): """ Convert 3D geometry to 2D Credit to @feenster and @hunt3ri from https://github.com/hotosm/tasking-manager/blob/master/server/services/grid/grid_service.py :param geometry: :return: """ def _to_2d(x, y, z): return tuple(filter(None, [x, y])) return transform(_to_2d, geometry)
[ "shapely.ops.unary_union", "numba.njit", "shapely.ops.transform", "numpy.argmin", "gistools.coordinates.r_tree_idx", "numpy.mean", "shapely.geometry.box", "shapely.geometry.Point", "shapely.geometry.Polygon", "shapely.geometry.LineString", "numpy.tan", "numpy.radians", "shapely.ops.cascaded_...
[((9332, 9338), 'numba.njit', 'njit', ([], {}), '()\n', (9336, 9338), False, 'from numba import njit\n'), ((29009, 29109), 'gistools.utils.check.type.type_assert', 'type_assert', ([], {'polygon1': '(Polygon, MultiPolygon)', 'polygon2': '(Polygon, MultiPolygon)', 'normalized': 'bool'}), '(polygon1=(Polygon, MultiPolygon), polygon2=(Polygon,\n MultiPolygon), normalized=bool)\n', (29020, 29109), False, 'from gistools.utils.check.type import is_iterable, type_assert\n'), ((29528, 29589), 'gistools.utils.check.type.type_assert', 'type_assert', ([], {'polygon': '(Polygon, MultiPolygon)', 'normalized': 'bool'}), '(polygon=(Polygon, MultiPolygon), normalized=bool)\n', (29539, 29589), False, 'from gistools.utils.check.type import is_iterable, type_assert\n'), ((1559, 1636), 'gistools.graph.part_graph', 'part_graph', (['graph', 'nparts', 'weight_attr', 'tpweights', 'recursive'], {}), '(graph, nparts, weight_attr, tpweights, recursive, **metis_options)\n', (1569, 1636), False, 'from gistools.graph import part_graph\n'), ((3399, 3441), 'numpy.mean', 'np.mean', (['[pt.x for pt in point_collection]'], {}), '([pt.x for pt in point_collection])\n', (3406, 3441), True, 'import numpy as np\n'), ((3459, 3501), 'numpy.mean', 'np.mean', (['[pt.y for pt in point_collection]'], {}), '([pt.y for pt in point_collection])\n', (3466, 3501), True, 'import numpy as np\n'), ((3514, 3545), 'shapely.geometry.Point', 'Point', (['[x_centroid, y_centroid]'], {}), '([x_centroid, y_centroid])\n', (3519, 3545), False, 'from shapely.geometry import MultiPolygon, GeometryCollection, Polygon, box, LineString, Point, MultiLineString, JOIN_STYLE\n'), ((18905, 18930), 'gistools.coordinates.r_tree_idx', 'r_tree_idx', (['mask_geometry'], {}), '(mask_geometry)\n', (18915, 18930), False, 'from gistools.coordinates import r_tree_idx\n'), ((25055, 25085), 'gistools.coordinates.r_tree_idx', 'r_tree_idx', (['polygon_collection'], {}), '(polygon_collection)\n', (25065, 25085), False, 'from gistools.coordinates import r_tree_idx\n'), ((25098, 25108), 'networkx.Graph', 'nx.Graph', ([], {}), '()\n', (25106, 25108), True, 'import networkx as nx\n'), ((28455, 28512), 'numpy.concatenate', 'np.concatenate', (['([rad_of_curvature[0]], rad_of_curvature)'], {}), '(([rad_of_curvature[0]], rad_of_curvature))\n', (28469, 28512), True, 'import numpy as np\n'), ((32632, 32659), 'shapely.ops.transform', 'transform', (['_to_2d', 'geometry'], {}), '(_to_2d, geometry)\n', (32641, 32659), False, 'from shapely.ops import cascaded_union, linemerge, unary_union, transform\n'), ((7382, 7414), 'gistools.utils.check.type.is_iterable', 'is_iterable', (['geometry_collection'], {}), '(geometry_collection)\n', (7393, 7414), False, 'from gistools.utils.check.type import is_iterable, type_assert\n'), ((7603, 7634), 'gistools.coordinates.r_tree_idx', 'r_tree_idx', (['geometry_collection'], {}), '(geometry_collection)\n', (7613, 7634), False, 'from gistools.coordinates import r_tree_idx\n'), ((8539, 8571), 'gistools.utils.check.type.is_iterable', 'is_iterable', (['geometry_collection'], {}), '(geometry_collection)\n', (8550, 8571), False, 'from gistools.utils.check.type import is_iterable, type_assert\n'), ((9922, 9939), 'numpy.tan', 'np.tan', (['(np.pi / 6)'], {}), '(np.pi / 6)\n', (9928, 9939), True, 'import numpy as np\n'), ((11657, 11670), 'shapely.geometry.Polygon', 'Polygon', (['poly'], {}), '(poly)\n', (11664, 11670), False, 'from shapely.geometry import MultiPolygon, GeometryCollection, Polygon, box, LineString, Point, MultiLineString, JOIN_STYLE\n'), ((12659, 12690), 'gistools.coordinates.r_tree_idx', 'r_tree_idx', (['geometry_collection'], {}), '(geometry_collection)\n', (12669, 12690), False, 'from gistools.coordinates import r_tree_idx\n'), ((15703, 15800), 'shapely.geometry.box', 'box', (['polygon.bounds[0]', 'polygon.bounds[1]', 'polygon.bounds[2]', '(polygon.bounds[1] + height / 2)'], {}), '(polygon.bounds[0], polygon.bounds[1], polygon.bounds[2], polygon.bounds\n [1] + height / 2)\n', (15706, 15800), False, 'from shapely.geometry import MultiPolygon, GeometryCollection, Polygon, box, LineString, Point, MultiLineString, JOIN_STYLE\n'), ((15806, 15902), 'shapely.geometry.box', 'box', (['polygon.bounds[0]', '(polygon.bounds[1] + height / 2)', 'polygon.bounds[2]', 'polygon.bounds[3]'], {}), '(polygon.bounds[0], polygon.bounds[1] + height / 2, polygon.bounds[2],\n polygon.bounds[3])\n', (15809, 15902), False, 'from shapely.geometry import MultiPolygon, GeometryCollection, Polygon, box, LineString, Point, MultiLineString, JOIN_STYLE\n'), ((15919, 16014), 'shapely.geometry.box', 'box', (['polygon.bounds[0]', 'polygon.bounds[1]', '(polygon.bounds[0] + width / 2)', 'polygon.bounds[3]'], {}), '(polygon.bounds[0], polygon.bounds[1], polygon.bounds[0] + width / 2,\n polygon.bounds[3])\n', (15922, 16014), False, 'from shapely.geometry import MultiPolygon, GeometryCollection, Polygon, box, LineString, Point, MultiLineString, JOIN_STYLE\n'), ((16021, 16116), 'shapely.geometry.box', 'box', (['(polygon.bounds[0] + width / 2)', 'polygon.bounds[1]', 'polygon.bounds[2]', 'polygon.bounds[3]'], {}), '(polygon.bounds[0] + width / 2, polygon.bounds[1], polygon.bounds[2],\n polygon.bounds[3])\n', (16024, 16116), False, 'from shapely.geometry import MultiPolygon, GeometryCollection, Polygon, box, LineString, Point, MultiLineString, JOIN_STYLE\n'), ((17384, 17469), 'shapely.geometry.box', 'box', (['polygon.bounds[0]', 'polygon.bounds[1]', 'polygon.bounds[2]', 'polygon.centroid.y'], {}), '(polygon.bounds[0], polygon.bounds[1], polygon.bounds[2], polygon.centroid.y\n )\n', (17387, 17469), False, 'from shapely.geometry import MultiPolygon, GeometryCollection, Polygon, box, LineString, Point, MultiLineString, JOIN_STYLE\n'), ((17477, 17562), 'shapely.geometry.box', 'box', (['polygon.bounds[0]', 'polygon.centroid.y', 'polygon.bounds[2]', 'polygon.bounds[3]'], {}), '(polygon.bounds[0], polygon.centroid.y, polygon.bounds[2], polygon.bounds[3]\n )\n', (17480, 17562), False, 'from shapely.geometry import MultiPolygon, GeometryCollection, Polygon, box, LineString, Point, MultiLineString, JOIN_STYLE\n'), ((17580, 17665), 'shapely.geometry.box', 'box', (['polygon.bounds[0]', 'polygon.bounds[1]', 'polygon.centroid.x', 'polygon.bounds[3]'], {}), '(polygon.bounds[0], polygon.bounds[1], polygon.centroid.x, polygon.bounds[3]\n )\n', (17583, 17665), False, 'from shapely.geometry import MultiPolygon, GeometryCollection, Polygon, box, LineString, Point, MultiLineString, JOIN_STYLE\n'), ((17673, 17758), 'shapely.geometry.box', 'box', (['polygon.centroid.x', 'polygon.bounds[1]', 'polygon.bounds[2]', 'polygon.bounds[3]'], {}), '(polygon.centroid.x, polygon.bounds[1], polygon.bounds[2], polygon.bounds[3]\n )\n', (17676, 17758), False, 'from shapely.geometry import MultiPolygon, GeometryCollection, Polygon, box, LineString, Point, MultiLineString, JOIN_STYLE\n'), ((20368, 20379), 'math.sqrt', 'msqrt', (['area'], {}), '(area)\n', (20373, 20379), True, 'from math import sqrt as msqrt\n'), ((21475, 21506), 'gistools.coordinates.r_tree_idx', 'r_tree_idx', (['geometry_collection'], {}), '(geometry_collection)\n', (21485, 21506), False, 'from gistools.coordinates import r_tree_idx\n'), ((24812, 24843), 'gistools.utils.check.type.is_iterable', 'is_iterable', (['polygon_collection'], {}), '(polygon_collection)\n', (24823, 24843), False, 'from gistools.utils.check.type import is_iterable, type_assert\n'), ((26075, 26101), 'numpy.sqrt', 'np.sqrt', (['(xx ** 2 + yy ** 2)'], {}), '(xx ** 2 + yy ** 2)\n', (26082, 26101), True, 'import numpy as np\n'), ((29896, 29927), 'gistools.utils.check.type.is_iterable', 'is_iterable', (['polygon_collection'], {}), '(polygon_collection)\n', (29907, 29927), False, 'from gistools.utils.check.type import is_iterable, type_assert\n'), ((30482, 30514), 'gistools.utils.check.type.is_iterable', 'is_iterable', (['geometry_collection'], {}), '(geometry_collection)\n', (30493, 30514), False, 'from gistools.utils.check.type import is_iterable, type_assert\n'), ((5997, 6005), 'shapely.geometry.Point', 'Point', (['p'], {}), '(p)\n', (6002, 6005), False, 'from shapely.geometry import MultiPolygon, GeometryCollection, Polygon, box, LineString, Point, MultiLineString, JOIN_STYLE\n'), ((10232, 10246), 'numpy.radians', 'np.radians', (['(30)'], {}), '(30)\n', (10242, 10246), True, 'import numpy as np\n'), ((19954, 19969), 'shapely.ops.linemerge', 'linemerge', (['line'], {}), '(line)\n', (19963, 19969), False, 'from shapely.ops import cascaded_union, linemerge, unary_union, transform\n'), ((22121, 22137), 'numpy.min', 'np.min', (['distance'], {}), '(distance)\n', (22127, 22137), True, 'import numpy as np\n'), ((26381, 26408), 'numpy.array', 'np.array', (['line.coords.xy[0]'], {}), '(line.coords.xy[0])\n', (26389, 26408), True, 'import numpy as np\n'), ((26425, 26452), 'numpy.array', 'np.array', (['line.coords.xy[1]'], {}), '(line.coords.xy[1])\n', (26433, 26452), True, 'import numpy as np\n'), ((26471, 26503), 'numpy.concatenate', 'np.concatenate', (['(x[1:], [x[-1]])'], {}), '((x[1:], [x[-1]]))\n', (26485, 26503), True, 'import numpy as np\n'), ((26523, 26555), 'numpy.concatenate', 'np.concatenate', (['(y[1:], [y[-1]])'], {}), '((y[1:], [y[-1]]))\n', (26537, 26555), True, 'import numpy as np\n'), ((26576, 26608), 'numpy.concatenate', 'np.concatenate', (['([x[0]], x[:-1])'], {}), '(([x[0]], x[:-1]))\n', (26590, 26608), True, 'import numpy as np\n'), ((26628, 26660), 'numpy.concatenate', 'np.concatenate', (['([y[0]], y[:-1])'], {}), '(([y[0]], y[:-1]))\n', (26642, 26660), True, 'import numpy as np\n'), ((27195, 27212), 'numpy.array', 'np.array', (['[10000]'], {}), '([10000])\n', (27203, 27212), True, 'import numpy as np\n'), ((28093, 28107), 'numpy.sqrt', 'np.sqrt', (['heron'], {}), '(heron)\n', (28100, 28107), True, 'import numpy as np\n'), ((3905, 3949), 'shapely.geometry.LineString', 'LineString', (['(point.coords[:] + line.coords[:])'], {}), '(point.coords[:] + line.coords[:])\n', (3915, 3949), False, 'from shapely.geometry import MultiPolygon, GeometryCollection, Polygon, box, LineString, Point, MultiLineString, JOIN_STYLE\n'), ((4004, 4048), 'shapely.geometry.LineString', 'LineString', (['(line.coords[:] + point.coords[:])'], {}), '(line.coords[:] + point.coords[:])\n', (4014, 4048), False, 'from shapely.geometry import MultiPolygon, GeometryCollection, Polygon, box, LineString, Point, MultiLineString, JOIN_STYLE\n'), ((6077, 6103), 'shapely.geometry.LineString', 'LineString', (['coords[:i + 1]'], {}), '(coords[:i + 1])\n', (6087, 6103), False, 'from shapely.geometry import MultiPolygon, GeometryCollection, Polygon, box, LineString, Point, MultiLineString, JOIN_STYLE\n'), ((6103, 6125), 'shapely.geometry.LineString', 'LineString', (['coords[i:]'], {}), '(coords[i:])\n', (6113, 6125), False, 'from shapely.geometry import MultiPolygon, GeometryCollection, Polygon, box, LineString, Point, MultiLineString, JOIN_STYLE\n'), ((13620, 13641), 'shapely.geometry.Point', 'Point', (['line.coords[0]'], {}), '(line.coords[0])\n', (13625, 13641), False, 'from shapely.geometry import MultiPolygon, GeometryCollection, Polygon, box, LineString, Point, MultiLineString, JOIN_STYLE\n'), ((13696, 13718), 'shapely.geometry.Point', 'Point', (['line.coords[-1]'], {}), '(line.coords[-1])\n', (13701, 13718), False, 'from shapely.geometry import MultiPolygon, GeometryCollection, Polygon, box, LineString, Point, MultiLineString, JOIN_STYLE\n'), ((18265, 18273), 'shapely.geometry.Point', 'Point', (['p'], {}), '(p)\n', (18270, 18273), False, 'from shapely.geometry import MultiPolygon, GeometryCollection, Polygon, box, LineString, Point, MultiLineString, JOIN_STYLE\n'), ((20817, 20830), 'shapely.geometry.Polygon', 'Polygon', (['poly'], {}), '(poly)\n', (20824, 20830), False, 'from shapely.geometry import MultiPolygon, GeometryCollection, Polygon, box, LineString, Point, MultiLineString, JOIN_STYLE\n'), ((21852, 21871), 'numpy.argmin', 'np.argmin', (['distance'], {}), '(distance)\n', (21861, 21871), True, 'import numpy as np\n'), ((22099, 22118), 'numpy.argmin', 'np.argmin', (['distance'], {}), '(distance)\n', (22108, 22118), True, 'import numpy as np\n'), ((3786, 3807), 'shapely.geometry.Point', 'Point', (['line.coords[0]'], {}), '(line.coords[0])\n', (3791, 3807), False, 'from shapely.geometry import MultiPolygon, GeometryCollection, Polygon, box, LineString, Point, MultiLineString, JOIN_STYLE\n'), ((3826, 3848), 'shapely.geometry.Point', 'Point', (['line.coords[-1]'], {}), '(line.coords[-1])\n', (3831, 3848), False, 'from shapely.geometry import MultiPolygon, GeometryCollection, Polygon, box, LineString, Point, MultiLineString, JOIN_STYLE\n'), ((11633, 11641), 'math.sqrt', 'msqrt', (['(3)'], {}), '(3)\n', (11638, 11641), True, 'from math import sqrt as msqrt\n'), ((19366, 19435), 'shapely.ops.cascaded_union', 'cascaded_union', (['[mask_geometry[n] for n in list_of_intersecting_mask]'], {}), '([mask_geometry[n] for n in list_of_intersecting_mask])\n', (19380, 19435), False, 'from shapely.ops import cascaded_union, linemerge, unary_union, transform\n'), ((22505, 22523), 'shapely.ops.unary_union', 'unary_union', (['geoms'], {}), '(geoms)\n', (22516, 22523), False, 'from shapely.ops import cascaded_union, linemerge, unary_union, transform\n'), ((27458, 27486), 'shapely.geometry.LineString', 'LineString', (['line.coords[::2]'], {}), '(line.coords[::2])\n', (27468, 27486), False, 'from shapely.geometry import MultiPolygon, GeometryCollection, Polygon, box, LineString, Point, MultiLineString, JOIN_STYLE\n'), ((27539, 27568), 'shapely.geometry.LineString', 'LineString', (['line.coords[1::2]'], {}), '(line.coords[1::2])\n', (27549, 27568), False, 'from shapely.geometry import MultiPolygon, GeometryCollection, Polygon, box, LineString, Point, MultiLineString, JOIN_STYLE\n'), ((6263, 6302), 'shapely.geometry.LineString', 'LineString', (['(coords[:i] + [(cp.x, cp.y)])'], {}), '(coords[:i] + [(cp.x, cp.y)])\n', (6273, 6302), False, 'from shapely.geometry import MultiPolygon, GeometryCollection, Polygon, box, LineString, Point, MultiLineString, JOIN_STYLE\n'), ((6304, 6343), 'shapely.geometry.LineString', 'LineString', (['([(cp.x, cp.y)] + coords[i:])'], {}), '([(cp.x, cp.y)] + coords[i:])\n', (6314, 6343), False, 'from shapely.geometry import MultiPolygon, GeometryCollection, Polygon, box, LineString, Point, MultiLineString, JOIN_STYLE\n'), ((7991, 8012), 'shapely.ops.cascaded_union', 'cascaded_union', (['union'], {}), '(union)\n', (8005, 8012), False, 'from shapely.ops import cascaded_union, linemerge, unary_union, transform\n'), ((27866, 27894), 'shapely.geometry.LineString', 'LineString', (['line.coords[::2]'], {}), '(line.coords[::2])\n', (27876, 27894), False, 'from shapely.geometry import MultiPolygon, GeometryCollection, Polygon, box, LineString, Point, MultiLineString, JOIN_STYLE\n'), ((27957, 27974), 'numpy.array', 'np.array', (['[10000]'], {}), '([10000])\n', (27965, 27974), True, 'import numpy as np\n'), ((6400, 6445), 'shapely.geometry.LineString', 'LineString', (['(coords[:i] + [(cp.x, cp.y, cp.z)])'], {}), '(coords[:i] + [(cp.x, cp.y, cp.z)])\n', (6410, 6445), False, 'from shapely.geometry import MultiPolygon, GeometryCollection, Polygon, box, LineString, Point, MultiLineString, JOIN_STYLE\n'), ((6447, 6492), 'shapely.geometry.LineString', 'LineString', (['([(cp.x, cp.y, cp.z)] + coords[i:])'], {}), '([(cp.x, cp.y, cp.z)] + coords[i:])\n', (6457, 6492), False, 'from shapely.geometry import MultiPolygon, GeometryCollection, Polygon, box, LineString, Point, MultiLineString, JOIN_STYLE\n')]
#! /usr/bin/env python # -*- coding: utf-8 -*- import os import random import logging import datetime import numpy as np # padle import paddle logger = logging.getLogger(__name__) def get_logger(log_file=None):# {{{ """Set logger and return it. If the log_file is not None, log will be written into log_file. Else, log will be shown in the screen. Args: log_file (str): If log_file is not None, log will be written into the log_file. Return: ~Logger * **logger**: An Logger object with customed config. """ # Basic config logging.basicConfig( format='%(asctime)s - %(levelname)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO, ) logger = logging.getLogger(__name__) # Add filehandler if log_file is not None: file_handler = logging.FileHandler(log_file, mode='w') file_handler.setLevel(logging.INFO) file_handler.setFormatter( logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') ) logger.addHandler(file_handler) return logger# }}} def set_seed_logger(args, cfg):# {{{ """Experiments preparation, e.g., fix random seed, prepare checkpoint dir and set logger. Args: args (parser.Argument): An parser.Argument object. cfg (yacs.config): An yacs.config.CfgNode object. Return: ~(Logger, str): * **logger**: An Logger object with customed config. * **save_dir**: Checkpoint dir to save models. """ seed = cfg['MISC']['SEED'] # Set random seed paddle.seed(seed) random.seed(seed) np.random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) # Prepare save dir if cfg['OUTPUT']['SAVE_NAME']: prefix = cfg['OUTPUT']['SAVE_NAME'] + '_' else: prefix = '' exp_name = prefix + datetime.datetime.now().strftime('%yY_%mM_%dD_%HH') save_dir = os.path.join(cfg['OUTPUT']['CHECKPOINT_DIR'], exp_name) if not os.path.exists(save_dir): os.makedirs(save_dir, exist_ok=True) # Build logger log_file = os.path.join(save_dir, 'log.txt') logger = get_logger(log_file) return logger, save_dir# }}} def dump_cfg(cfg, cfg_file):# {{{ """Dump config of each experiment into file for backup. Args: cfg (yacs.config): An yacs.config.CfgNode object. cfg_file (str): Dump config to this file. """ logger.info('Dump configs into {}'.format(cfg_file)) logger.info('Using configs: ') logger.info(cfg) with open(cfg_file, 'w') as f: f.write(cfg.dump())# }}} def compute_ranks(dataset, results):# {{{ sims = np.array([results[i] for i in range(len(dataset))]) labels = np.array([dataset.get_label(i) for i in range(len(dataset))]) if dataset.has_caption_indices: num_captions_per_image = dataset.num_captions_per_image else: num_captions_per_image = len(dataset.image_keys) * dataset.num_captions_per_image sims = sims.reshape([-1, num_captions_per_image]) labels = labels.reshape([-1, num_captions_per_image]) # Compute i2t ranks i2t_ranks = [] for sim, label in zip(sims, labels): inds = np.argsort(sim)[::-1] rank = num_captions_per_image for r, ind in enumerate(inds): if label[ind] == 1: rank = r break i2t_ranks.append(rank) # Compute t2i ranks t2i_ranks = [] if not dataset.has_caption_indices: sims = np.swapaxes(sims, 0, 1) labels = np.swapaxes(labels, 0, 1) for sim, label in zip(sims, labels): inds = np.argsort(sim)[::-1] rank = num_captions_per_image for r, ind in enumerate(inds): if label[ind] == 1: rank = r break t2i_ranks.append(rank) return i2t_ranks, t2i_ranks# }}} def get_retrieval_results(dataset, results): sims = np.array([results[i] for i in range(len(dataset))]) images = np.array([dataset.get_result(i)[0] for i in range(len(dataset))]) captions = np.array([dataset.get_result(i)[1] for i in range(len(dataset))]) if dataset.has_caption_indices: num_captions_per_image = dataset.num_captions_per_image else: num_captions_per_image = len(dataset.image_keys) * dataset.num_captions_per_image sims = sims.reshape([-1, num_captions_per_image]) # num_image x num_captions images = images.reshape([-1, num_captions_per_image]) # num_images x num_captions captions = captions.reshape([-1, num_captions_per_image]) # num_images x num_captions # Get i2t results i2t_results = {} for i, (sim, cap) in enumerate(zip(sims, captions)): inds = np.argsort(sim)[::-1] tmp_results = [] for ind in inds: tmp_results.append(cap[ind]) i2t_results[images[i][0]] = tmp_results[:10] # Get t2i results t2i_results = {} if not dataset.has_caption_indices: sims = np.swapaxes(sims, 0, 1) # num_captions x num_images images = np.swapaxes(images, 0, 1) # num_captions x num_images for t, (sim, image) in enumerate(zip(sims, images)): inds = np.argsort(sim)[::-1] tmp_results = [] for ind in inds: tmp_results.append(image[ind]) t2i_results[captions[0][t]] = tmp_results return i2t_results, t2i_results
[ "numpy.random.seed", "logging.FileHandler", "logging.basicConfig", "os.makedirs", "os.path.exists", "datetime.datetime.now", "logging.Formatter", "numpy.argsort", "paddle.seed", "random.seed", "numpy.swapaxes", "os.path.join", "logging.getLogger" ]
[((155, 182), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (172, 182), False, 'import logging\n'), ((600, 724), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""%(asctime)s - %(levelname)s - %(message)s"""', 'datefmt': '"""%m/%d/%Y %H:%M:%S"""', 'level': 'logging.INFO'}), "(format='%(asctime)s - %(levelname)s - %(message)s',\n datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO)\n", (619, 724), False, 'import logging\n'), ((765, 792), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (782, 792), False, 'import logging\n'), ((1620, 1637), 'paddle.seed', 'paddle.seed', (['seed'], {}), '(seed)\n', (1631, 1637), False, 'import paddle\n'), ((1642, 1659), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (1653, 1659), False, 'import random\n'), ((1664, 1684), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (1678, 1684), True, 'import numpy as np\n'), ((1960, 2015), 'os.path.join', 'os.path.join', (["cfg['OUTPUT']['CHECKPOINT_DIR']", 'exp_name'], {}), "(cfg['OUTPUT']['CHECKPOINT_DIR'], exp_name)\n", (1972, 2015), False, 'import os\n'), ((2133, 2166), 'os.path.join', 'os.path.join', (['save_dir', '"""log.txt"""'], {}), "(save_dir, 'log.txt')\n", (2145, 2166), False, 'import os\n'), ((868, 907), 'logging.FileHandler', 'logging.FileHandler', (['log_file'], {'mode': '"""w"""'}), "(log_file, mode='w')\n", (887, 907), False, 'import logging\n'), ((2027, 2051), 'os.path.exists', 'os.path.exists', (['save_dir'], {}), '(save_dir)\n', (2041, 2051), False, 'import os\n'), ((2061, 2097), 'os.makedirs', 'os.makedirs', (['save_dir'], {'exist_ok': '(True)'}), '(save_dir, exist_ok=True)\n', (2072, 2097), False, 'import os\n'), ((3541, 3564), 'numpy.swapaxes', 'np.swapaxes', (['sims', '(0)', '(1)'], {}), '(sims, 0, 1)\n', (3552, 3564), True, 'import numpy as np\n'), ((3582, 3607), 'numpy.swapaxes', 'np.swapaxes', (['labels', '(0)', '(1)'], {}), '(labels, 0, 1)\n', (3593, 3607), True, 'import numpy as np\n'), ((5053, 5076), 'numpy.swapaxes', 'np.swapaxes', (['sims', '(0)', '(1)'], {}), '(sims, 0, 1)\n', (5064, 5076), True, 'import numpy as np\n'), ((5123, 5148), 'numpy.swapaxes', 'np.swapaxes', (['images', '(0)', '(1)'], {}), '(images, 0, 1)\n', (5134, 5148), True, 'import numpy as np\n'), ((999, 1061), 'logging.Formatter', 'logging.Formatter', (['"""%(asctime)s - %(levelname)s - %(message)s"""'], {}), "('%(asctime)s - %(levelname)s - %(message)s')\n", (1016, 1061), False, 'import logging\n'), ((3233, 3248), 'numpy.argsort', 'np.argsort', (['sim'], {}), '(sim)\n', (3243, 3248), True, 'import numpy as np\n'), ((4788, 4803), 'numpy.argsort', 'np.argsort', (['sim'], {}), '(sim)\n', (4798, 4803), True, 'import numpy as np\n'), ((1893, 1916), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (1914, 1916), False, 'import datetime\n'), ((3672, 3687), 'numpy.argsort', 'np.argsort', (['sim'], {}), '(sim)\n', (3682, 3687), True, 'import numpy as np\n'), ((5258, 5273), 'numpy.argsort', 'np.argsort', (['sim'], {}), '(sim)\n', (5268, 5273), True, 'import numpy as np\n')]
import numpy as np from cloudvolume import CloudVolume from cloudvolume.lib import Bbox from cloudvolume.storage import Storage from chunkflow.chunk.validate import validate_by_template_matching from tinybrain import downsample_with_averaging from chunkflow.chunk import Chunk from .base import OperatorBase class CutoutOperator(OperatorBase): def __init__(self, volume_path: str, mip: int = 0, expand_margin_size=(0, 0, 0), fill_missing: bool = False, validate_mip: int = None, blackout_sections: bool = None, dry_run: bool = False, name: str = 'cutout', verbose: bool = True, use_https: bool = True): super().__init__(name=name, verbose=verbose) self.volume_path = volume_path self.mip = mip self.expand_margin_size = expand_margin_size self.fill_missing = fill_missing self.validate_mip = validate_mip self.blackout_sections = blackout_sections self.dry_run = dry_run self.use_https = use_https if blackout_sections: with Storage(volume_path) as stor: self.blackout_section_ids = stor.get_json( 'blackout_section_ids.json')['section_ids'] def __call__(self, output_bbox): #gevent.monkey.patch_all(thread=False) vol = CloudVolume(self.volume_path, bounded=False, fill_missing=self.fill_missing, progress=self.verbose, mip=self.mip, cache=False, use_https=self.use_https, green_threads=True) chunk_slices = tuple( slice(s.start - m, s.stop + m) for s, m in zip(output_bbox.to_slices(), self.expand_margin_size)) if self.dry_run: input_bbox = Bbox.from_slices(chunk_slices) return Chunk.from_bbox(input_bbox) if self.verbose: print('cutout {} from {}'.format(chunk_slices[::-1], self.volume_path)) # always reverse the indexes since cloudvolume use x,y,z indexing chunk = vol[chunk_slices[::-1]] # the cutout is fortran ordered, so need to transpose and make it C order chunk = chunk.transpose() # we can delay this transpose later # actually we do not need to make it contiguous # chunk = np.ascontiguousarray(chunk) # if the channel number is 1, squeeze it as 3d array # this should not be neccessary # TODO: remove this step and use 4D array all over this package. # always use 4D array will simplify some operations global_offset = tuple(s.start for s in chunk_slices) if chunk.shape[0] == 1: chunk = np.squeeze(chunk, axis=0) else: global_offset = (chunk.shape[0], ) + global_offset chunk = Chunk(chunk, global_offset=global_offset) if self.blackout_sections: chunk = self._blackout_sections(chunk) if self.validate_mip: self._validate_chunk(chunk, vol) return chunk def _blackout_sections(self, chunk): """ make some sections black. this was normally used for the section with bad alignment. The ConvNet was supposed to handle them better with black image. TODO: make this function as a separate operator """ # current code only works with 3d image assert chunk.ndim == 3, "current code assumes that the chunk is 3D image." for z in self.blackout_section_ids: z0 = z - chunk.global_offset[0] if z0 >= 0 and z0 < chunk.shape[0]: chunk[z0, :, :] = 0 return chunk def _validate_chunk(self, chunk, vol): """ check that all the input voxels was downloaded without black region We have found some black regions in previous inference run, so hopefully this will solve the problem. """ if chunk.ndim == 4 and chunk.shape[0] > 1: chunk = chunk[0, :, :, :] validate_vol = CloudVolume(self.volume_path, bounded=False, fill_missing=self.fill_missing, progress=self.verbose, mip=self.validate_mip, cache=False, green_threads=True) chunk_mip = self.mip if self.verbose: print('validate chunk in mip {}'.format(self.validate_mip)) assert self.validate_mip >= chunk_mip # only use the region corresponds to higher mip level # clamp the surrounding regions in XY plane # this assumes that the input dataset was downsampled starting from the # beginning offset in the info file global_offset = chunk.global_offset # factor3 follows xyz order in CloudVolume factor3 = np.array([ 2**(self.validate_mip - chunk_mip), 2 **(self.validate_mip - chunk_mip), 1 ], dtype=np.int32) clamped_offset = tuple(go + f - (go - vo) % f for go, vo, f in zip( global_offset[::-1], vol.voxel_offset, factor3)) clamped_stop = tuple( go + s - (go + s - vo) % f for go, s, vo, f in zip(global_offset[::-1], chunk.shape[::-1], vol.voxel_offset, factor3)) clamped_slices = tuple( slice(o, s) for o, s in zip(clamped_offset, clamped_stop)) clamped_bbox = Bbox.from_slices(clamped_slices) clamped_input = chunk.cutout(clamped_slices[::-1]) # transform to xyz order clamped_input = np.transpose(clamped_input) # get the corresponding bounding box for validation validate_bbox = vol.bbox_to_mip(clamped_bbox, mip=chunk_mip, to_mip=self.validate_mip) #validate_bbox = clamped_bbox // factor3 # downsample the input using avaraging # keep the z as it is since the mip only applies to xy plane # recursivly downsample the input # if we do it directly, the downsampled input will not be the same with the recursive one # because of the rounding error of integer division for _ in range(self.validate_mip - chunk_mip): clamped_input = downsample_with_averaging(clamped_input, (2, 2, 1)) # validation by template matching assert validate_by_template_matching(clamped_input) validate_input = validate_vol[validate_bbox.to_slices()] if validate_input.shape[3] == 1: validate_input = np.squeeze(validate_input, axis=3) # use the validate input to check the downloaded input assert np.alltrue(validate_input == clamped_input)
[ "chunkflow.chunk.validate.validate_by_template_matching", "numpy.transpose", "cloudvolume.lib.Bbox.from_slices", "cloudvolume.CloudVolume", "numpy.array", "numpy.alltrue", "numpy.squeeze", "cloudvolume.storage.Storage", "tinybrain.downsample_with_averaging", "chunkflow.chunk.Chunk", "chunkflow.c...
[((1446, 1627), 'cloudvolume.CloudVolume', 'CloudVolume', (['self.volume_path'], {'bounded': '(False)', 'fill_missing': 'self.fill_missing', 'progress': 'self.verbose', 'mip': 'self.mip', 'cache': '(False)', 'use_https': 'self.use_https', 'green_threads': '(True)'}), '(self.volume_path, bounded=False, fill_missing=self.fill_missing,\n progress=self.verbose, mip=self.mip, cache=False, use_https=self.\n use_https, green_threads=True)\n', (1457, 1627), False, 'from cloudvolume import CloudVolume\n'), ((3106, 3147), 'chunkflow.chunk.Chunk', 'Chunk', (['chunk'], {'global_offset': 'global_offset'}), '(chunk, global_offset=global_offset)\n', (3111, 3147), False, 'from chunkflow.chunk import Chunk\n'), ((4348, 4511), 'cloudvolume.CloudVolume', 'CloudVolume', (['self.volume_path'], {'bounded': '(False)', 'fill_missing': 'self.fill_missing', 'progress': 'self.verbose', 'mip': 'self.validate_mip', 'cache': '(False)', 'green_threads': '(True)'}), '(self.volume_path, bounded=False, fill_missing=self.fill_missing,\n progress=self.verbose, mip=self.validate_mip, cache=False,\n green_threads=True)\n', (4359, 4511), False, 'from cloudvolume import CloudVolume\n'), ((5240, 5349), 'numpy.array', 'np.array', (['[2 ** (self.validate_mip - chunk_mip), 2 ** (self.validate_mip - chunk_mip), 1]'], {'dtype': 'np.int32'}), '([2 ** (self.validate_mip - chunk_mip), 2 ** (self.validate_mip -\n chunk_mip), 1], dtype=np.int32)\n', (5248, 5349), True, 'import numpy as np\n'), ((5876, 5908), 'cloudvolume.lib.Bbox.from_slices', 'Bbox.from_slices', (['clamped_slices'], {}), '(clamped_slices)\n', (5892, 5908), False, 'from cloudvolume.lib import Bbox\n'), ((6025, 6052), 'numpy.transpose', 'np.transpose', (['clamped_input'], {}), '(clamped_input)\n', (6037, 6052), True, 'import numpy as np\n'), ((6857, 6901), 'chunkflow.chunk.validate.validate_by_template_matching', 'validate_by_template_matching', (['clamped_input'], {}), '(clamped_input)\n', (6886, 6901), False, 'from chunkflow.chunk.validate import validate_by_template_matching\n'), ((7152, 7195), 'numpy.alltrue', 'np.alltrue', (['(validate_input == clamped_input)'], {}), '(validate_input == clamped_input)\n', (7162, 7195), True, 'import numpy as np\n'), ((2020, 2050), 'cloudvolume.lib.Bbox.from_slices', 'Bbox.from_slices', (['chunk_slices'], {}), '(chunk_slices)\n', (2036, 2050), False, 'from cloudvolume.lib import Bbox\n'), ((2070, 2097), 'chunkflow.chunk.Chunk.from_bbox', 'Chunk.from_bbox', (['input_bbox'], {}), '(input_bbox)\n', (2085, 2097), False, 'from chunkflow.chunk import Chunk\n'), ((2978, 3003), 'numpy.squeeze', 'np.squeeze', (['chunk'], {'axis': '(0)'}), '(chunk, axis=0)\n', (2988, 3003), True, 'import numpy as np\n'), ((6747, 6798), 'tinybrain.downsample_with_averaging', 'downsample_with_averaging', (['clamped_input', '(2, 2, 1)'], {}), '(clamped_input, (2, 2, 1))\n', (6772, 6798), False, 'from tinybrain import downsample_with_averaging\n'), ((7038, 7072), 'numpy.squeeze', 'np.squeeze', (['validate_input'], {'axis': '(3)'}), '(validate_input, axis=3)\n', (7048, 7072), True, 'import numpy as np\n'), ((1194, 1214), 'cloudvolume.storage.Storage', 'Storage', (['volume_path'], {}), '(volume_path)\n', (1201, 1214), False, 'from cloudvolume.storage import Storage\n')]
#!/usr/bin/python3 # -*- coding: utf-8 -*- import logging import matplotlib import multiprocessing as mp import numpy as np import os import sys # Fix problem: no $DISPLAY environment variable matplotlib.use('Agg') from argparse import ArgumentParser from datetime import datetime as dt from pprint import pprint from config import cfg from core.train import train_net from core.test import test_net def get_args_from_command_line(): parser = ArgumentParser(description='Parser of Runner of Pix2Vox') parser.add_argument('--gpu', dest='gpu_id', help='GPU device id to use [cuda0]', default=cfg.CONST.DEVICE, type=str) parser.add_argument('--rand', dest='randomize', help='Randomize (do not use a fixed seed)', action='store_true') parser.add_argument('--test', dest='test', help='Test neural networks', action='store_true') parser.add_argument('--batch-size', dest='batch_size', help='name of the net', default=cfg.CONST.BATCH_SIZE, type=int) parser.add_argument('--epoch', dest='epoch', help='number of epoches', default=cfg.TRAIN.NUM_EPOCHES, type=int) parser.add_argument('--weights', dest='weights', help='Initialize network from the weights file', default=None) parser.add_argument('--out', dest='out_path', help='Set output path', default=cfg.DIR.OUT_PATH) args = parser.parse_args() return args def main(): # Get args from command line args = get_args_from_command_line() if args.gpu_id is not None: cfg.CONST.DEVICE = args.gpu_id if not args.randomize: np.random.seed(cfg.CONST.RNG_SEED) if args.batch_size is not None: cfg.CONST.BATCH_SIZE = args.batch_size if args.epoch is not None: cfg.TRAIN.NUM_EPOCHES = args.epoch if args.out_path is not None: cfg.DIR.OUT_PATH = args.out_path if args.weights is not None: cfg.CONST.WEIGHTS = args.weights if not args.test: cfg.TRAIN.RESUME_TRAIN = True # Print config print('Use config:') pprint(cfg) # Set GPU to use if type(cfg.CONST.DEVICE) == str: os.environ["CUDA_VISIBLE_DEVICES"] = cfg.CONST.DEVICE # Start train/test process if not args.test: train_net(cfg) else: # print('WEIGHTS' in cfg.CONST) # print(os.path.exists(cfg.CONST.WEIGHTS)) if 'WEIGHTS' in cfg.CONST and os.path.exists(cfg.CONST.WEIGHTS): test_net(cfg) else: print('[FATAL] %s Please specify the file path of checkpoint.' % (dt.now())) sys.exit(2) if __name__ == '__main__': # Check python version if sys.version_info < (3, 0): raise Exception("Please Check python version") # Setup logger mp.log_to_stderr() logger = mp.get_logger() logger.setLevel(logging.INFO) main()
[ "numpy.random.seed", "argparse.ArgumentParser", "os.path.exists", "core.test.test_net", "multiprocessing.log_to_stderr", "matplotlib.use", "pprint.pprint", "core.train.train_net", "datetime.datetime.now", "sys.exit", "multiprocessing.get_logger" ]
[((194, 215), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (208, 215), False, 'import matplotlib\n'), ((452, 509), 'argparse.ArgumentParser', 'ArgumentParser', ([], {'description': '"""Parser of Runner of Pix2Vox"""'}), "(description='Parser of Runner of Pix2Vox')\n", (466, 509), False, 'from argparse import ArgumentParser\n'), ((2191, 2202), 'pprint.pprint', 'pprint', (['cfg'], {}), '(cfg)\n', (2197, 2202), False, 'from pprint import pprint\n'), ((2898, 2916), 'multiprocessing.log_to_stderr', 'mp.log_to_stderr', ([], {}), '()\n', (2914, 2916), True, 'import multiprocessing as mp\n'), ((2930, 2945), 'multiprocessing.get_logger', 'mp.get_logger', ([], {}), '()\n', (2943, 2945), True, 'import multiprocessing as mp\n'), ((1733, 1767), 'numpy.random.seed', 'np.random.seed', (['cfg.CONST.RNG_SEED'], {}), '(cfg.CONST.RNG_SEED)\n', (1747, 1767), True, 'import numpy as np\n'), ((2387, 2401), 'core.train.train_net', 'train_net', (['cfg'], {}), '(cfg)\n', (2396, 2401), False, 'from core.train import train_net\n'), ((2541, 2574), 'os.path.exists', 'os.path.exists', (['cfg.CONST.WEIGHTS'], {}), '(cfg.CONST.WEIGHTS)\n', (2555, 2574), False, 'import os\n'), ((2588, 2601), 'core.test.test_net', 'test_net', (['cfg'], {}), '(cfg)\n', (2596, 2601), False, 'from core.test import test_net\n'), ((2717, 2728), 'sys.exit', 'sys.exit', (['(2)'], {}), '(2)\n', (2725, 2728), False, 'import sys\n'), ((2694, 2702), 'datetime.datetime.now', 'dt.now', ([], {}), '()\n', (2700, 2702), True, 'from datetime import datetime as dt\n')]
# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. # # 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 os import os.path as osp import time import cv2 import numpy as np import yaml from six import text_type as _text_type from paddlelite.lite import * class Predictor: def __init__(self, model_nb, model_yaml, thread_num, shape): if not osp.exists(model_nb): print("model nb file is not exists in {}".format(model_xml)) self.model_nb = model_nb self.shape = shape config = MobileConfig() config.set_model_from_file(model_nb) config.set_threads(thread_num) if not osp.exists(model_yaml): print("model yaml file is not exists in {}".format(model_yaml)) with open(model_yaml) as f: self.info = yaml.load(f.read(), Loader=yaml.Loader) self.model_type = self.info['_Attributes']['model_type'] self.model_name = self.info['Model'] self.num_classes = self.info['_Attributes']['num_classes'] self.labels = self.info['_Attributes']['labels'] if self.info['Model'] == 'MaskRCNN': if self.info['_init_params']['with_fpn']: self.mask_head_resolution = 28 else: self.mask_head_resolution = 14 transforms_mode = self.info.get('TransformsMode', 'RGB') if transforms_mode == 'RGB': to_rgb = True else: to_rgb = False self.transforms = self.build_transforms(self.info['Transforms'], to_rgb) self.predictor = create_paddle_predictor(config) self.total_time = 0 self.count_num = 0 def build_transforms(self, transforms_info, to_rgb=True): if self.model_type == "classifier": import transforms.cls_transforms as transforms elif self.model_type == "detector": import transforms.det_transforms as transforms elif self.model_type == "segmenter": import transforms.seg_transforms as transforms op_list = list() for op_info in transforms_info: op_name = list(op_info.keys())[0] op_attr = op_info[op_name] if not hasattr(transforms, op_name): raise Exception( "There's no operator named '{}' in transforms of {}". format(op_name, self.model_type)) op_list.append(getattr(transforms, op_name)(**op_attr)) eval_transforms = transforms.Compose(op_list) if hasattr(eval_transforms, 'to_rgb'): eval_transforms.to_rgb = to_rgb self.arrange_transforms(eval_transforms) return eval_transforms def arrange_transforms(self, eval_transforms): if self.model_type == 'classifier': import transforms.cls_transforms as transforms arrange_transform = transforms.ArrangeClassifier elif self.model_type == 'segmenter': import transforms.seg_transforms as transforms arrange_transform = transforms.ArrangeSegmenter elif self.model_type == 'detector': import transforms.det_transforms as transforms arrange_name = 'Arrange{}'.format(self.model_name) arrange_transform = getattr(transforms, arrange_name) else: raise Exception("Unrecognized model type: {}".format( self.model_type)) if type(eval_transforms.transforms[-1]).__name__.startswith('Arrange'): eval_transforms.transforms[-1] = arrange_transform(mode='test') else: eval_transforms.transforms.append(arrange_transform(mode='test')) def raw_predict(self, preprocessed_input): self.count_num += 1 input_tensor = self.predictor.get_input(0) input_tensor.resize(self.shape) input_tensor.set_float_data(preprocessed_input['image']) if self.model_name == "YOLOv3": input_size_tensor = self.predictor.get_input(1) input_size_tensor.resize([1, 2]) input_size_tensor.set_float_data(preprocessed_input['im_size']) #Start inference start_time = time.time() self.predictor.run() time_use = time.time() - start_time if (self.count_num >= 20): self.total_time += time_use if (self.count_num >= 120): print("avgtime:", self.total_time * 10) #Processing output blob print("Processing output blob") return def preprocess(self, image): res = dict() if self.model_type == "classifier": im, = self.transforms(image) im = np.expand_dims(im, axis=0).copy() im = im.flatten() res['image'] = im elif self.model_type == "detector": if self.model_name == "YOLOv3": im, im_shape = self.transforms(image) im = np.expand_dims(im, axis=0).copy() im_shape = np.expand_dims(im_shape, axis=0).copy() res['image'] = im res['im_size'] = im_shape if self.model_name.count('RCNN') > 0: im, im_resize_info, im_shape = self.transforms(image) im = np.expand_dims(im, axis=0).copy() im_resize_info = np.expand_dims(im_resize_info, axis=0).copy() im_shape = np.expand_dims(im_shape, axis=0).copy() res['image'] = im res['im_info'] = im_resize_info res['im_shape'] = im_shape elif self.model_type == "segmenter": im, im_info = self.transforms(image) im = np.expand_dims(im, axis=0).copy() #np.savetxt('./input_data.txt',im.flatten()) res['image'] = im res['im_info'] = im_info return res def classifier_postprocess(self, topk=1): output_tensor = self.predictor.get_output(0) output_data = output_tensor.float_data() true_topk = min(self.num_classes, topk) pred_label = np.argsort(-np.array(output_data))[:true_topk] result = [{ 'category_id': l, 'category': self.labels[l], 'score': output_data[l], } for l in pred_label] print(result) return result def segmenter_postprocess(self, preprocessed_inputs): out_label_tensor = self.predictor.get_output(0) out_label = out_label_tensor.float_data() label_shape = tuple(out_label_tensor.shape()) label_map = np.array(out_label).astype('uint8') label_map = label_map.reshap(label_shape) label_map = np.squeeze(label_map) out_score_tensor = self.predictor.get_output(1) out_score = out_score_tensor.float_data() score_shape = tuple(out_score_tensor.shape()) score_map = np.array(out_score) score_map = score_map.reshap(score_shape) score_map = np.transpose(score_map, (1, 2, 0)) im_info = preprocessed_inputs['im_info'] for info in im_info[::-1]: if info[0] == 'resize': w, h = info[1][1], info[1][0] label_map = cv2.resize(label_map, (w, h), cv2.INTER_NEAREST) score_map = cv2.resize(score_map, (w, h), cv2.INTER_LINEAR) elif info[0] == 'padding': w, h = info[1][1], info[1][0] label_map = label_map[0:h, 0:w] score_map = score_map[0:h, 0:w, :] else: raise Exception("Unexpected info '{}' in im_info".format(info[ 0])) return {'label_map': label_map, 'score_map': score_map} def detector_postprocess(self, preprocessed_inputs): out_tensor = self.predictor.get_output(0) out_data = out_tensor.float_data() out_shape = tuple(out_tensor.shape()) out_data = np.array(out_data) outputs = label_data.reshap(out_shape) result = [] for out in outputs: result.append(out.tolist()) return result def predict(self, image, topk=1, threshold=0.5): preprocessed_input = self.preprocess(image) self.raw_predict(preprocessed_input) if self.model_type == "classifier": results = self.classifier_postprocess(topk) elif self.model_type == "detector": results = self.detector_postprocess(preprocessed_input) elif self.model_type == "segmenter": pass results = self.segmenter_postprocess(preprocessed_input)
[ "numpy.transpose", "os.path.exists", "numpy.expand_dims", "time.time", "numpy.array", "transforms.det_transforms.Compose", "numpy.squeeze", "cv2.resize" ]
[((3044, 3071), 'transforms.det_transforms.Compose', 'transforms.Compose', (['op_list'], {}), '(op_list)\n', (3062, 3071), True, 'import transforms.det_transforms as transforms\n'), ((4717, 4728), 'time.time', 'time.time', ([], {}), '()\n', (4726, 4728), False, 'import time\n'), ((7190, 7211), 'numpy.squeeze', 'np.squeeze', (['label_map'], {}), '(label_map)\n', (7200, 7211), True, 'import numpy as np\n'), ((7393, 7412), 'numpy.array', 'np.array', (['out_score'], {}), '(out_score)\n', (7401, 7412), True, 'import numpy as np\n'), ((7483, 7517), 'numpy.transpose', 'np.transpose', (['score_map', '(1, 2, 0)'], {}), '(score_map, (1, 2, 0))\n', (7495, 7517), True, 'import numpy as np\n'), ((8424, 8442), 'numpy.array', 'np.array', (['out_data'], {}), '(out_data)\n', (8432, 8442), True, 'import numpy as np\n'), ((876, 896), 'os.path.exists', 'osp.exists', (['model_nb'], {}), '(model_nb)\n', (886, 896), True, 'import os.path as osp\n'), ((1162, 1184), 'os.path.exists', 'osp.exists', (['model_yaml'], {}), '(model_yaml)\n', (1172, 1184), True, 'import os.path as osp\n'), ((4777, 4788), 'time.time', 'time.time', ([], {}), '()\n', (4786, 4788), False, 'import time\n'), ((7084, 7103), 'numpy.array', 'np.array', (['out_label'], {}), '(out_label)\n', (7092, 7103), True, 'import numpy as np\n'), ((7713, 7761), 'cv2.resize', 'cv2.resize', (['label_map', '(w, h)', 'cv2.INTER_NEAREST'], {}), '(label_map, (w, h), cv2.INTER_NEAREST)\n', (7723, 7761), False, 'import cv2\n'), ((7790, 7837), 'cv2.resize', 'cv2.resize', (['score_map', '(w, h)', 'cv2.INTER_LINEAR'], {}), '(score_map, (w, h), cv2.INTER_LINEAR)\n', (7800, 7837), False, 'import cv2\n'), ((5210, 5236), 'numpy.expand_dims', 'np.expand_dims', (['im'], {'axis': '(0)'}), '(im, axis=0)\n', (5224, 5236), True, 'import numpy as np\n'), ((6608, 6629), 'numpy.array', 'np.array', (['output_data'], {}), '(output_data)\n', (6616, 6629), True, 'import numpy as np\n'), ((5467, 5493), 'numpy.expand_dims', 'np.expand_dims', (['im'], {'axis': '(0)'}), '(im, axis=0)\n', (5481, 5493), True, 'import numpy as np\n'), ((5528, 5560), 'numpy.expand_dims', 'np.expand_dims', (['im_shape'], {'axis': '(0)'}), '(im_shape, axis=0)\n', (5542, 5560), True, 'import numpy as np\n'), ((5785, 5811), 'numpy.expand_dims', 'np.expand_dims', (['im'], {'axis': '(0)'}), '(im, axis=0)\n', (5799, 5811), True, 'import numpy as np\n'), ((5852, 5890), 'numpy.expand_dims', 'np.expand_dims', (['im_resize_info'], {'axis': '(0)'}), '(im_resize_info, axis=0)\n', (5866, 5890), True, 'import numpy as np\n'), ((5925, 5957), 'numpy.expand_dims', 'np.expand_dims', (['im_shape'], {'axis': '(0)'}), '(im_shape, axis=0)\n', (5939, 5957), True, 'import numpy as np\n'), ((6201, 6227), 'numpy.expand_dims', 'np.expand_dims', (['im'], {'axis': '(0)'}), '(im, axis=0)\n', (6215, 6227), True, 'import numpy as np\n')]
"""FFX.py v1.3 (Sept 16, 2011) This module implements the Fast Function Extraction (FFX) algorithm. Reference: <NAME>, FFX: Fast, Scalable, Deterministic Symbolic Regression Technology, Genetic Programming Theory and Practice IX, Edited by R. Riolo, <NAME>, and <NAME>, Springer, 2011. http://www.trent.st/ffx HOW TO USE THIS MODULE: Easiest to use by calling runffx.py. Its code has example usage patterns. The main routines are: models = MultiFFXModelFactory().build(train_X, train_y, test_X, test_y, varnames) yhat = model.simulate(X) print model Can expand / restrict the set of functions via the user-changeable constants (right below licence). FFX Software Licence Agreement (like BSD, but adapted for non-commercial gain only) Copyright (c) 2011, Solido Design Automation Inc. Authored by <NAME>. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Usage does not involve commercial gain. * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the associated institutions nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. For permissions beyond the scope of this license, please contact <NAME> (<EMAIL>). THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE DEVELOPERS OR THEIR INSTITUTIONS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Patent pending. """ from __future__ import print_function import itertools import math import signal import time import sys from functools import wraps # 3rd party dependencies import numpy import scipy from sklearn.linear_model import ElasticNet # user-changeable constants CONSIDER_INTER = True # consider interactions? CONSIDER_DENOM = True # consider denominator? CONSIDER_EXPON = True # consider exponents? CONSIDER_NONLIN = True # consider abs() and log()? CONSIDER_THRESH = True # consider hinge functions? if sys.version_info >= (3, 0): # hacky python3 compatibility # so as not to rely on six xrange = range itertools.izip = zip # Make dependency on pandas optional. try: import pandas except ImportError: pandas = None INF = float('Inf') # maximum time (s) for regularization update during pathwise learn. MAX_TIME_REGULARIZE_UPDATE = 5 # GTH = Greater-Than Hinge function, LTH = Less-Than Hinge function OP_ABS, OP_MAX0, OP_MIN0, OP_LOG10, OP_GTH, OP_LTH = 1, 2, 3, 4, 5, 6 def _approachStr(approach): assert len(approach) == 5 assert set(approach).issubset([0, 1]) return 'inter%d denom%d expon%d nonlin%d thresh%d' % \ (approach[0], approach[1], approach[2], approach[3], approach[4]) #========================================================================= # strategy class FFXBuildStrategy(object): """All parameter settings. Put magic numbers here.""" def __init__(self, approach): """ @arguments approach -- 5-d list of [use_inter, use_denom, use_expon, use_nonlin, use_thresh] """ assert len(approach) == 5 assert set(approach).issubset([0, 1]) self.approach = approach self.num_alphas = 1000 # final round will stop if either of these is hit self.final_target_train_nmse = 0.01 # 0.01 = 1% self.final_max_num_bases = 250 # aggressive pruning (note: lasso has l1_ratio=1.0, ridge regression # has l1_ratio=0.0) self._l1_ratio = 0.95 # eps -- Length of the path. eps=1e-3 means that alpha_min / alpha_max # = 1e-3. self._eps = 1e-70 # will use all if 'nonlin1', else [] self.all_nonlin_ops = [OP_ABS, OP_LOG10] # will use all if 'thresh1', else [] self.all_threshold_ops = [OP_GTH, OP_LTH] self.num_thrs_per_var = 5 # will use all if 'expon1', else [1.0] self.all_expr_exponents = [-1.0, -0.5, +0.5, +1.0] def includeInteractions(self): return bool(self.approach[0]) def includeDenominator(self): return bool(self.approach[1]) def exprExponents(self): if self.approach[2]: return self.all_expr_exponents else: return [1.0] def nonlinOps(self): if self.approach[3]: return self.all_nonlin_ops else: return [] def thresholdOps(self): if self.approach[4]: return self.all_threshold_ops else: return [] def eps(self): return self._eps def l1_ratio(self): return self._l1_ratio def numAlphas(self): return self.num_alphas #========================================================================= #models / bases class FFXModel: def __init__(self, coefs_n, bases_n, coefs_d, bases_d, varnames=None): """ @arguments coefs_n -- 1d array of float -- coefficients for numerator. bases_n -- list of *Base -- bases for numerator coefs_d -- 1d array of float -- coefficients for denominator bases_d -- list of *Base -- bases for denominator varnames -- list of string """ # preconditions # offset + numer_bases == numer_coefs assert 1 + len(bases_n) == len(coefs_n) assert len(bases_d) == len(coefs_d) # denom_bases == denom_coefs # make sure that the coefs line up with their 'pretty' versions coefs_n = numpy.array([float(coefStr(coef)) for coef in coefs_n]) coefs_d = numpy.array([float(coefStr(coef)) for coef in coefs_d]) # reorder numerator bases from highest-to-lowest influence # -but keep offset 0th of course offset = coefs_n[0] coefs_n2 = coefs_n[1:] I = numpy.argsort(numpy.abs(coefs_n2))[::-1] coefs_n = [offset] + [coefs_n2[i] for i in I] bases_n = [bases_n[i] for i in I] # reorder denominator bases from highest-to-lowest influence I = numpy.argsort(numpy.abs(coefs_d))[::-1] coefs_d = [coefs_d[i] for i in I] bases_d = [bases_d[i] for i in I] # store values self.varnames = varnames self.coefs_n = coefs_n self.bases_n = bases_n self.coefs_d = coefs_d self.bases_d = bases_d def numBases(self): """Return total number of bases""" return len(self.bases_n) + len(self.bases_d) def simulate(self, X): """ @arguments X -- 2d array of [sample_i][var_i] : float @return y -- 1d array of [sample_i] : float """ N = X.shape[0] # numerator y = numpy.zeros(N, dtype=float) y += self.coefs_n[0] for (coef, base) in itertools.izip(self.coefs_n[1:], self.bases_n): y += coef * base.simulate(X) # denominator if self.bases_d: denom_y = numpy.zeros(N, dtype=float) denom_y += 1.0 for (coef, base) in itertools.izip(self.coefs_d, self.bases_d): denom_y += coef * base.simulate(X) y /= denom_y return y def __str__(self): return self.str2() def str2(self, maxlen=100000): include_denom = bool(self.bases_d) s = '' # numerator if include_denom and len(self.coefs_n) > 1: s += '(' numer_s = ['%s' % coefStr(self.coefs_n[0])] for (coef, base) in itertools.izip(self.coefs_n[1:], self.bases_n): numer_s += ['%s*%s' % (coefStr(coef), base)] s += ' + '.join(numer_s) if include_denom and len(self.coefs_n) > 1: s += ')' # denominator if self.bases_d: s += ' / (' denom_s = ['1.0'] for (coef, base) in itertools.izip(self.coefs_d, self.bases_d): denom_s += ['%s*%s' % (coefStr(coef), base)] s += ' + '.join(denom_s) s += ')' # change xi to actual variable names for var_i in xrange(len(self.varnames) - 1, -1, -1): s = s.replace('x%d' % var_i, self.varnames[var_i]) s = s.replace('+ -', '- ') # truncate long strings if len(s) > maxlen: s = s[:maxlen] + '...' return s def complexity(self): # Define complexity as the number of nodes needed in the # corresponding GP tree. # We have a leading constant, then for each base we have a # coefficient, a multiply, and a plus, plus the complexity of # the base itself. num_complexity = 1 + sum(3 + b.complexity() for b in self.bases_n) if self.bases_d: denom_complexity = 1 + sum(3 + b.complexity() for b in self.bases_d) # add 1 for the division return num_complexity + 1 + denom_complexity else: return num_complexity class SimpleBase: """e.g. x4^2""" def __init__(self, var, exponent): self.var = var self.exponent = exponent def simulate(self, X): """ @arguments X -- 2d array of [sample_i][var_i] : float @return y -- 1d array of [sample_i] : float """ return X[:, self.var] ** self.exponent def __str__(self): if self.exponent == 1: return 'x%d' % self.var else: return 'x%d^%g' % (self.var, self.exponent) def complexity(self): if self.exponent == 1: return 1 else: return 3 class OperatorBase: """e.g. log(x4^2)""" def __init__(self, simple_base, nonlin_op, thr=INF): """ @arguments simple_base -- SimpleBase nonlin_op -- one of OPS thr -- None or float -- depends on nonlin_op """ self.simple_base = simple_base self.nonlin_op = nonlin_op self.thr = thr def simulate(self, X): """ @arguments X -- 2d array of [sample_i][var_i] : float @return y -- 1d array of [sample_i] : float """ op = self.nonlin_op ok = True y_lin = self.simple_base.simulate(X) if op == OP_ABS: ya = numpy.abs(y_lin) elif op == OP_MAX0: ya = numpy.clip(y_lin, 0.0, INF) elif op == OP_MIN0: ya = numpy.clip(y_lin, -INF, 0.0) elif op == OP_LOG10: # safeguard against: log() on values <= 0.0 mn, mx = min(y_lin), max(y_lin) if mn <= 0.0 or scipy.isnan(mn) or mx == INF or scipy.isnan(mx): ok = False else: ya = numpy.log10(y_lin) elif op == OP_GTH: ya = numpy.clip(self.thr - y_lin, 0.0, INF) elif op == OP_LTH: ya = numpy.clip(y_lin - self.thr, 0.0, INF) else: raise 'Unknown op %d' % op if ok: # could always do ** exp, but faster ways if exp is 0,1 y = ya else: y = INF * numpy.ones(X.shape[0], dtype=float) return y def __str__(self): op = self.nonlin_op simple_s = str(self.simple_base) if op == OP_ABS: return 'abs(%s)' % simple_s elif op == OP_MAX0: return 'max(0, %s)' % simple_s elif op == OP_MIN0: return 'min(0, %s)' % simple_s elif op == OP_LOG10: return 'log10(%s)' % simple_s elif op == OP_GTH: return 'max(0,%s-%s)' % (coefStr(self.thr), simple_s) elif op == OP_LTH: return ('max(0,%s-%s)' % (simple_s, coefStr(self.thr))).replace('--', '+') else: raise 'Unknown op %d' % op def complexity(self): """Return an integer measure of model complexity. It's intended to measure the number of nodes in the GP tree corresponding to the model. We assume the GP language includes: +, -, *, /, MAX0, MIN0, LOG10 but not GTH, LTH. Thus, MAX0(x) returns the value max(0, x) but contributes only 1 + complexity(x) to the complexity count. GTH(thr, x) returns the value max(0, thr-x) but because it would be implemented in GP as MAX0(thr-x) it contributes 3 + complexity(x) to the count.""" op = self.nonlin_op if op == OP_ABS: return 1 + self.simple_base.complexity() elif op == OP_MAX0: return 1 + self.simple_base.complexity() elif op == OP_MIN0: return 1 + self.simple_base.complexity() elif op == OP_LOG10: return 1 + self.simple_base.complexity() elif op == OP_GTH: return 3 + self.simple_base.complexity() elif op == OP_LTH: return 3 + self.simple_base.complexity() else: raise 'Unknown op %d' % op class ProductBase: """e.g. x2^2 * log(x1^3)""" def __init__(self, base1, base2): self.base1 = base1 self.base2 = base2 def simulate(self, X): """ @arguments X -- 2d array of [sample_i][var_i] : float @return y -- 1d array of [sample_i] : float """ yhat1 = self.base1.simulate(X) yhat2 = self.base2.simulate(X) return yhat1 * yhat2 def __str__(self): return '%s * %s' % (self.base1, self.base2) def complexity(self): return 1 + self.base1.complexity() + self.base2.complexity() class ConstantModel: """e.g. 3.2""" def __init__(self, constant, numvars): """ @description Constructor. @arguments constant -- float -- constant value returned by this model numvars -- int -- number of input variables to this model """ self.constant = float(constant) self.numvars = numvars def numBases(self): """Return total number of bases""" return 0 def simulate(self, X): """ @arguments X -- 2d array of [sample_i][var_i] : float @return y -- 1d array of [sample_i] : float """ N = X.shape[0] if scipy.isnan(self.constant): # corner case yhat = numpy.array([INF] * N) else: # typical case yhat = numpy.ones(N, dtype=float) * self.constant return yhat def __str__(self): return self.str2() def str2(self, dummy_arg=None): return coefStr(self.constant) def complexity(self): return 1 #============================================================================== # Model factories class MultiFFXModelFactory: def build(self, train_X, train_y, test_X, test_y, varnames=None, verbose=False): """ @description Builds FFX models at many different settings, then merges the results into a single Pareto Optimal Set. @argument train_X -- 2d array of [sample_i][var_i] : float -- training inputs train_y -- 1d array of [sample_i] : float -- training outputs test_X -- 2d array -- testing inputs test_y -- 1d array -- testing outputs varnames -- list of string -- variable names @return models -- list of FFXModel -- Pareto-optimal set of models """ if pandas is not None and isinstance(train_X, pandas.DataFrame): varnames = train_X.columns train_X = train_X.as_matrix() test_X = test_X.as_matrix() if isinstance(train_X, numpy.ndarray) and varnames is None: raise Exception('varnames required for numpy.ndarray') if verbose: print('Build(): begin. {2} variables, {1} training samples, {0} test samples'.format( test_X.shape[0], *train_X.shape)) models = [] min_y = min(min(train_y), min(test_y)) max_y = max(max(train_y), max(test_y)) # build all combinations of approaches, except for (a) features we don't consider # and (b) too many features at once approaches = [] if verbose: print("Learning Approaches Considered:") print("=========================================") print("Inter Denom Expon Nonlin Threshold") print("=========================================") if CONSIDER_INTER: inters = [1] # inter=0 is a subset of inter=1 else: inters = [0] for inter in inters: for denom in [0, 1]: if denom == 1 and not CONSIDER_DENOM: continue for expon in [0, 1]: if expon == 1 and not CONSIDER_EXPON: continue if expon == 1 and inter == 1: continue # never need both exponent and inter for nonlin in [0, 1]: if nonlin == 1 and not CONSIDER_NONLIN: continue for thresh in [0, 1]: if thresh == 1 and not CONSIDER_THRESH: continue approach = [inter, denom, expon, nonlin, thresh] if sum(approach) >= 4: continue # not too many features at once approaches.append(approach) if verbose: # " ", _approachStr(approach) print( '\t'.join(['Yes' if a else 'No' for a in approach])) for (i, approach) in enumerate(approaches): if verbose: print('-' * 200) print('Build with approach %d/%d (%s): begin' % (i + 1, len(approaches), _approachStr(approach))) ss = FFXBuildStrategy(approach) next_models = FFXModelFactory().build(train_X, train_y, ss, varnames, verbose) # set test_nmse on each model for model in next_models: test_yhat = model.simulate(test_X) model.test_nmse = nmse(test_yhat, test_y, min_y, max_y) # pareto filter if verbose: print(' STEP 3: Nondominated filter') next_models = self._nondominatedModels(next_models) models += next_models if verbose: print('Build with approach %d/%d (%s): done. %d model(s).' % (i + 1, len(approaches), _approachStr(approach), len(next_models))) print('Models:') for model in next_models: print("num_bases=%d, test_nmse=%.6f, model=%s" % (model.numBases(), model.test_nmse, model.str2(500))) # final pareto filter models = self._nondominatedModels(models) # log nondominated models if verbose: print('=' * 200) print('%d nondominated models (wrt test error & num. bases):' % len(models)) for (i, model) in enumerate(models): print("Nondom model %d/%d: num_bases=%d, test_nmse=%.6f, model=%s" % (i + 1, len(models), model.numBases(), model.test_nmse, model.str2(500))) return models def _FFXapproach(self, inter, denom, expon, nonlin, thresh): return 'FFX inter%d denom%d expon%d nonlin%d thresh%d' % \ (inter, denom, expon, nonlin, thresh) def _nondominatedModels(self, models): test_nmses = [model.test_nmse for model in models] num_bases = [model.numBases() for model in models] I = nondominatedIndices2d(test_nmses, num_bases) models = [models[i] for i in I] I = numpy.argsort([model.numBases() for model in models]) models = [models[i] for i in I] return models class FFXModelFactory: def build(self, X, y, ss, varnames=None, verbose=False): """ @description Build FFX models at the settings of input solution strategy 'ss'. @argument X -- 2d array of [var_i][sample_i] : float -- training inputs y -- 1d array of [sample_i] : float -- training outputs varnames -- list of string -- variable names ss -- FFXSolutionStrategy @return models -- list of FFXModel -- Pareto-optimal set of models """ if pandas is not None and isinstance(X, pandas.DataFrame): varnames = X.columns X = X.as_matrix() if isinstance(X, numpy.ndarray) and varnames is None: raise Exception('varnames required for numpy.ndarray') if X.ndim == 1: self.nrow, self.ncol = len(X), 1 elif X.ndim == 2: self.nrow, self.ncol = X.shape else: raise Exception('X is wrong dimensionality.') y = numpy.asarray(y) if self.nrow != len(y): raise Exception('X sample count and y sample count do not match') # if y has shape (N, 1) then we reshape to just (N,) if len(y.shape) > 1: assert y.shape[1] == 1 y = numpy.reshape(y, (y.shape[0],)) if self.ncol == 0: print(' Corner case: no input vars, so return a ConstantModel') return [ConstantModel(y.mean(), 0)] # Main work... # build up each combination of all {var_i} x {op_j}, except for # when a combination is unsuccessful if verbose: print(' STEP 1A: Build order-1 bases: begin') order1_bases = [] for var_i in range(self.ncol): for exponent in ss.exprExponents(): if exponent == 0.0: continue #'lin' version of base simple_base = SimpleBase(var_i, exponent) lin_yhat = simple_base.simulate(X) # checking exponent is a speedup if exponent in [1.0, 2.0] or not yIsPoor(lin_yhat): order1_bases.append(simple_base) # add e.g. OP_ABS, OP_MAX0, OP_MIN0, OP_LOG10 for nonlin_op in ss.nonlinOps(): # ignore cases where op has no effect if nonlin_op == OP_ABS and exponent in [-2, +2]: continue if nonlin_op == OP_MAX0 and min(lin_yhat) >= 0: continue if nonlin_op == OP_MIN0 and max(lin_yhat) <= 0: continue nonsimple_base = OperatorBase( simple_base, nonlin_op, None) nonsimple_base.var = var_i # easy access when considering interactions nonlin_yhat = nonsimple_base.simulate(X) if numpy.all(nonlin_yhat == lin_yhat): continue # op has no effect if not yIsPoor(nonlin_yhat): order1_bases.append(nonsimple_base) # add e.g. OP_GTH, OP_LTH if exponent == 1.0 and ss.thresholdOps(): minx, maxx = min(X[:, var_i]), max(X[:, var_i]) rangex = maxx - minx stepx = 0.8 * rangex / float(ss.num_thrs_per_var + 1) thrs = numpy.arange( minx + 0.2 * rangex, maxx - 0.2 * rangex + 0.1 * rangex, stepx) for threshold_op in ss.thresholdOps(): for thr in thrs: nonsimple_base = OperatorBase( simple_base, threshold_op, thr) # easy access when considering interactions nonsimple_base.var = var_i order1_bases.append(nonsimple_base) if verbose: print(' STEP 1A: Build order-1 bases: done. Have %d order-1 bases.' % len(order1_bases)) var1_models = None if ss.includeInteractions(): # find base-1 influences if verbose: print(' STEP 1B: Find order-1 base infls: begin') max_num_bases = len(order1_bases) # no limit target_train_nmse = 0.01 models = self._basesToModels( ss, varnames, order1_bases, X, y, max_num_bases, target_train_nmse, verbose) if models is None: # fit failed. model = ConstantModel(y[0], 0) return [model] var1_models = models # use most-explaining model (which also has the max num bases) model = models[-1] order1_bases = model.bases_n + model.bases_d if len(order1_bases) == 0: # the most-explaining model is a constant model model = ConstantModel(y[0], 0) return [model] # order bases by influence order1_infls = numpy.abs( list(model.coefs_n[1:]) + list(model.coefs_d)) # influences I = numpy.argsort(-1 * order1_infls) order1_bases = [order1_bases[i] for i in I] if verbose: print(' STEP 1B: Find order-1 base infls: done') # don't let inter coeffs swamp linear ones; but handle more when n # small n_order1_bases = len(order1_bases) max_n_order2_bases = 3 * math.sqrt(n_order1_bases) # default max_n_order2_bases = max(max_n_order2_bases, 10) # lower limit max_n_order2_bases = max( max_n_order2_bases, 2 * n_order1_bases) # "" if ss.includeDenominator(): max_n_order2_bases = min( max_n_order2_bases, 4000) # upper limit else: max_n_order2_bases = min(max_n_order2_bases, 8000) # "" # build up order2 bases if verbose: print(' STEP 1C: Build order-2 bases: begin') # -always have all xi*xi terms order2_bases = [] order2_basetups = set() # set of (basei_id, basej_id) tuples for i, basei in enumerate(order1_bases): if basei.__class__ != SimpleBase: continue # just xi if basei.exponent != 1.0: continue # just exponent==1 combined_base = SimpleBase(basei.var, 2) order2_bases.append(combined_base) tup = (id(basei), id(basei)) order2_basetups.add(tup) # -then add other terms for max_base_i in xrange(len(order1_bases)): for i in xrange(max_base_i): basei = order1_bases[i] for j in xrange(max_base_i): if j >= i: continue # disallow mirror image basej = order1_bases[j] tup = (id(basei), id(basej)) if tup in order2_basetups: continue # no duplicate pairs combined_base = ProductBase(basei, basej) order2_bases.append(combined_base) order2_basetups.add(tup) if len(order2_bases) >= max_n_order2_bases: break # for j if len(order2_bases) >= max_n_order2_bases: break # for i if len(order2_bases) >= max_n_order2_bases: break # for max_base_i if verbose: print(' STEP 1C: Build order-2 bases: done. Have %d order-2' ' bases.' % len(order2_bases)) bases = order1_bases + order2_bases else: bases = order1_bases # all bases. Stop based on target nmse, not number of bases if verbose: print(' STEP 2: Regress on all %d bases: begin.' % len(bases)) var2_models = self._basesToModels( ss, varnames, bases, X, y, ss.final_max_num_bases, ss.final_target_train_nmse, verbose) if verbose: print(' STEP 2: Regress on all %d bases: done.' % len(bases)) # combine models having 1-var with models having 2-vars if var1_models is None and var2_models is None: models = [] elif var1_models is None and var2_models is not None: models = var2_models elif var1_models is not None and var2_models is None: models = var1_models else: # var1_models is not None and var2_models is not None models = var1_models + var2_models # add constant; done models = [ConstantModel(numpy.mean(y), X.shape[0])] + models return models def _basesToModels(self, ss, varnames, bases, X, y, max_num_bases, target_train_nmse, verbose): # compute regress_X if ss.includeDenominator(): regress_X = numpy.zeros((self.nrow, len(bases) * 2), dtype=float) else: regress_X = numpy.zeros((self.nrow, len(bases)), dtype=float) for i, base in enumerate(bases): base_y = base.simulate(X) regress_X[:, i] = base_y # numerators if ss.includeDenominator(): regress_X[:, len(bases) + i] = -1.0 * \ base_y * y # denominators # compute models. models = self._pathwiseLearn(ss, varnames, bases, X, regress_X, y, max_num_bases, target_train_nmse, verbose) return models def _pathwiseLearn(self, ss, varnames, bases, X_orig, X_orig_regress, y_orig, max_num_bases, target_nmse, verbose=False, **fit_params): """Adapted from enet_path() in sklearn.linear_model. http://scikit-learn.sourceforge.net/modules/linear_model.html Compute Elastic-Net path with coordinate descent. Returns list of model (or None if failure).""" if verbose: print(' Pathwise learn: begin. max_num_bases=%d' % max_num_bases) max_iter = 1000 # default 1000. magic number. # Condition X and y: # -"unbias" = rescale so that (mean=0, stddev=1) -- subtract each row's # mean, then divide by stddev # -X transposed # -X as fortran array (X_unbiased, y_unbiased, X_avgs, X_stds, y_avg, y_std) = self._unbiasedXy(X_orig_regress, y_orig) # make data contiguous in memory X_unbiased = numpy.asfortranarray(X_unbiased) n_samples = X_unbiased.shape[0] vals = numpy.dot(X_unbiased.T, y_unbiased) vals = [val for val in vals if not scipy.isnan(val)] if vals: alpha_max = numpy.abs(max(vals) / (n_samples * ss.l1_ratio())) else: alpha_max = 1.0 # backup: pick a value from the air # alphas = lotsa alphas at beginning, and usual rate for rest st, fin = numpy.log10(alpha_max * ss.eps()), numpy.log10(alpha_max) alphas1 = numpy.logspace( st, fin, num=ss.numAlphas() * 10)[::-1][:ss.numAlphas() // 4] alphas2 = numpy.logspace(st, fin, num=ss.numAlphas()) alphas = sorted(set(alphas1).union(alphas2), reverse=True) if 'precompute' not in fit_params or fit_params['precompute'] is True: fit_params['precompute'] = numpy.dot(X_unbiased.T, X_unbiased) # if not 'Xy' in fit_params or fit_params['Xy'] is None: # fit_params['Xy'] = numpy.dot(X_unbiased.T, y_unbiased) models = [] # build this up nmses = [] # for detecting stagnation cur_unbiased_coefs = None # init values for coefs start_time = time.time() for (alpha_i, alpha) in enumerate(alphas): # compute (unbiased) coefficients. Recall that mean=0 so no # intercept needed clf = ElasticNetWithTimeout(alpha=alpha, l1_ratio=ss.l1_ratio(), fit_intercept=False, max_iter=max_iter, **fit_params) try: clf.fit(X_unbiased, y_unbiased) except TimeoutError: print(' Regularized update failed. Returning None') return None # failure except ValueError: print(' Regularized update failed with ValueError.') print(' X_unbiased:') print(X_unbiased) print(' y_unbiased:') print(y_unbiased) sys.exit(1) cur_unbiased_coefs = clf.coef_.copy() if cur_unbiased_coefs.shape == tuple(): # This happens when we have only one variable because # ElasticNet calls numpy.squeeze(), which reduces a # single element array to a 0-d array. That would # crash us below in list(cur_unbiased_coefs). We just # undo the squeeze. cur_unbiased_coefs = cur_unbiased_coefs.reshape((1,)) # compute model; update models # -"rebias" means convert from (mean=0, stddev=1) to original (mean, stddev) coefs = self._rebiasCoefs( [0.0] + list(cur_unbiased_coefs), X_stds, X_avgs, y_std, y_avg) (coefs_n, bases_n, coefs_d, bases_d) = self._allocateToNumerDenom( ss, bases, coefs) model = FFXModel(coefs_n, bases_n, coefs_d, bases_d, varnames) models.append(model) # update nmses nmse_unbiased = nmse(numpy.dot(cur_unbiased_coefs, X_unbiased.T), y_unbiased, min(y_unbiased), max(y_unbiased)) nmses.append(nmse_unbiased) # log num_bases = len(numpy.nonzero(cur_unbiased_coefs)[0]) if verbose and ((alpha_i == 0) or (alpha_i + 1) % 50 == 0): print(' alpha %d/%d (%3e): num_bases=%d, nmse=%.6f, time %.2f s' % (alpha_i + 1, len(alphas), alpha, num_bases, nmse_unbiased, time.time() - start_time)) # maybe stop if scipy.isinf(nmses[-1]): if verbose: print(' Pathwise learn: Early stop because nmse is inf') return None if nmse_unbiased < target_nmse: if verbose: print(' Pathwise learn: Early stop because nmse < target') return models if num_bases > max_num_bases: if verbose: print(' Pathwise learn: Early stop because num bases > %d' % max_num_bases) return models if len(nmses) > 15 and round(nmses[-1], 4) == round(nmses[-15], 4): if verbose: print(' Pathwise learn: Early stop because nmses stagnated') return models if verbose: print(' Pathwise learn: done') return models def _allocateToNumerDenom(self, ss, bases, coefs): """Prune out nonzero coefficients/bases. Allocate to numerator vs. denominator.""" if ss.includeDenominator(): # offset + numer_bases + denom_bases assert 1 + len(bases) + len(bases) == len(coefs) n_bases = len(bases) coefs_n = [coefs[0]] + \ [coef for coef in coefs[1:n_bases + 1] if coef != 0] bases_n = [base for (base, coef) in itertools.izip( bases, coefs[1:n_bases + 1]) if coef != 0] coefs_d = [coef for coef in coefs[n_bases + 1:] if coef != 0] bases_d = [base for (base, coef) in itertools.izip( bases, coefs[n_bases + 1:]) if coef != 0] else: # offset + numer_bases + denom_bases assert 1 + len(bases) == len(coefs) coefs_n = [coefs[0]] + [coef for coef in coefs[1:] if coef != 0] bases_n = [base for (base, coef) in itertools.izip( bases, coefs[1:]) if coef != 0] coefs_d = [] bases_d = [] return (coefs_n, bases_n, coefs_d, bases_d) def _unbiasedXy(self, Xin, yin): """Make all input rows of X, and y, to have mean=0 stddev=1 """ # unbiased X X_avgs, X_stds = Xin.mean(0), Xin.std(0) # if any stddev was 0, overwrite with 1 to prevent divide by # zero. Because we then return the overwritten value, #_rebiasCoefs will end up with the right rebiased values. Same # for y below. numpy.copyto(X_stds, 1.0, where=~(X_stds > 0.0)) X_unbiased = (Xin - X_avgs) / X_stds # unbiased y y_avg, y_std = yin.mean(0), yin.std(0) # if stddev was 0, overwrite with 1 if not y_std > 0.0: y_std = 1.0 y_unbiased = (yin - y_avg) / y_std assert numpy.all(numpy.isfinite(X_unbiased)) assert numpy.all(numpy.isfinite(y_unbiased)) return (X_unbiased, y_unbiased, X_avgs, X_stds, y_avg, y_std) def _rebiasCoefs(self, unbiased_coefs, X_stds, X_avgs, y_std, y_avg): """Given the coefficients that were learned using unbiased training data, rebias the coefficients so that they are at the scale of the real training X and y.""" # preconditions assert unbiased_coefs is not None assert len(unbiased_coefs) == (len(X_stds) + 1) == (len(X_avgs) + 1), \ (len(unbiased_coefs), (len(X_stds) + 1), (len(X_avgs) + 1)) # main work n = len(X_stds) coefs = numpy.zeros(n + 1, dtype=float) coefs[0] = unbiased_coefs[0] * y_std + y_avg for j in range(1, n + 1): coefs[j] = unbiased_coefs[j] * y_std / X_stds[j - 1] coefs[0] -= coefs[j] * X_avgs[j - 1] return coefs #========================================================================= # Revise linear_model.coordinate_descent.ElasticNet.fit() to handle when it hangs # http://www.saltycrane.com/blog/2010/04/using-python-timeout-decorator-uploading-s3/ class TimeoutError(Exception): def __init__(self, value="Timed Out"): self.value = value def __str__(self): return repr(self.value) def timeout(seconds_before_timeout): def decorate(f): # Just do without the timeout on Windows: see # https://github.com/natekupp/ffx/issues/17 if not hasattr(signal, "SIGALRM"): return f def handler(signum, frame): raise TimeoutError() @wraps(f) def new_f(*args, **kwargs): old = signal.signal(signal.SIGALRM, handler) signal.alarm(seconds_before_timeout) try: result = f(*args, **kwargs) finally: signal.signal(signal.SIGALRM, old) signal.alarm(0) return result return new_f return decorate class ElasticNetWithTimeout(ElasticNet): # if this freezes, then exit with a TimeoutError @timeout(MAX_TIME_REGULARIZE_UPDATE) def fit(self, *args, **kwargs): return ElasticNet.fit(self, *args, **kwargs) #========================================================================= # utility classes / functions def nondominatedIndices2d(cost0s, cost1s): """ @description Find indices of individuals that are on the nondominated 2-d tradeoff. @arguments cost0s -- 1d array of float [model_i] -- want to minimize this. E.g. complexity. cost1s -- 1d array of float [model_i] -- want to minimize this too. E.g. nmse. @return nondomI -- list of int -- nondominated indices; each is in range [0, #inds - 1] ALWAYS returns at least one entry if there is valid data """ cost0s, cost1s = numpy.asarray(cost0s), numpy.asarray(cost1s) n_points = len(cost0s) assert n_points == len(cost1s) if n_points == 0: # corner case return [] # indices of cost0s sorted for ascending order I = numpy.argsort(cost0s) #'cur' == best at this cost0s best_cost = [cost0s[I[0]], cost1s[I[0]]] best_cost_index = I[0] nondom_locs = [] for i in xrange(n_points): loc = I[i] # traverse cost0s in ascending order if cost0s[loc] == best_cost[0]: if cost1s[loc] < best_cost[1]: best_cost_index = loc best_cost = [cost0s[loc], cost1s[loc]] else: # cost0s[loc] > best_cost[0] because # loc indexes cost0s in ascending order if not nondom_locs: # initial value nondom_locs = [best_cost_index] elif best_cost[1] < cost1s[nondom_locs[-1]]: # if the current cost is lower than the last item # on the non-dominated list, add it's index to # the non-dominated list nondom_locs.append(best_cost_index) # set up "last tested value" best_cost_index = loc best_cost = [cost0s[loc], cost1s[loc]] if not nondom_locs: # if none are non-dominated, return the last one nondom_locs = [loc] elif best_cost[1] < cost1s[nondom_locs[-1]]: # if the current cost is lower than the last item # on the non-dominated list, add it's index to # the non-dominated list nondom_locs.append(best_cost_index) # return the non-dominated in sorted order nondomI = sorted(nondom_locs) return nondomI def nmse(yhat, y, min_y, max_y): """ @description Calculates the normalized mean-squared error. @arguments yhat -- 1d array or list of floats -- estimated values of y y -- 1d array or list of floats -- true values min_y, max_y -- float, float -- roughly the min and max; they do not have to be the perfect values of min and max, because they're just here to scale the output into a roughly [0,1] range @return nmse -- float -- normalized mean-squared error """ # base case: no entries if len(yhat) == 0: return 0.0 # base case: both yhat and y are constant, and same values if (max_y == min_y) and (max(yhat) == min(yhat) == max(y) == min(y)): return 0.0 # main case assert max_y > min_y, 'max_y=%g was not > min_y=%g' % (max_y, min_y) yhat_a, y_a = numpy.asarray(yhat), numpy.asarray(y) y_range = float(max_y - min_y) try: result = math.sqrt(numpy.mean(((yhat_a - y_a) / y_range) ** 2)) if scipy.isnan(result): return INF return result except: return INF def yIsPoor(y): """Returns True if y is not usable""" return max(scipy.isinf(y)) or max(scipy.isnan(y)) def coefStr(x): """Gracefully print a number to 3 significant digits. See _testCoefStr in unit tests""" if x == 0.0: s = '0' elif numpy.abs(x) < 1e-4: s = ('%.2e' % x).replace('e-0', 'e-') elif numpy.abs(x) < 1e-3: s = '%.6f' % x elif numpy.abs(x) < 1e-2: s = '%.5f' % x elif numpy.abs(x) < 1e-1: s = '%.4f' % x elif numpy.abs(x) < 1e0: s = '%.3f' % x elif numpy.abs(x) < 1e1: s = '%.2f' % x elif numpy.abs(x) < 1e2: s = '%.1f' % x elif numpy.abs(x) < 1e4: s = '%.0f' % x else: s = ('%.2e' % x).replace('e+0', 'e') return s def basesStr(bases): """Pretty print list of bases""" return ', '.join([str(base) for base in bases]) def rail(x, minx, maxx): return max(minx, max(maxx, x))
[ "numpy.abs", "numpy.ones", "numpy.clip", "numpy.argsort", "numpy.mean", "numpy.arange", "numpy.isfinite", "numpy.reshape", "signal.alarm", "numpy.log10", "scipy.isinf", "math.sqrt", "numpy.asarray", "numpy.asfortranarray", "scipy.isnan", "functools.wraps", "numpy.dot", "signal.sign...
[((41297, 41318), 'numpy.argsort', 'numpy.argsort', (['cost0s'], {}), '(cost0s)\n', (41310, 41318), False, 'import numpy\n'), ((7638, 7665), 'numpy.zeros', 'numpy.zeros', (['N'], {'dtype': 'float'}), '(N, dtype=float)\n', (7649, 7665), False, 'import numpy\n'), ((7723, 7769), 'itertools.izip', 'itertools.izip', (['self.coefs_n[1:]', 'self.bases_n'], {}), '(self.coefs_n[1:], self.bases_n)\n', (7737, 7769), False, 'import itertools\n'), ((8426, 8472), 'itertools.izip', 'itertools.izip', (['self.coefs_n[1:]', 'self.bases_n'], {}), '(self.coefs_n[1:], self.bases_n)\n', (8440, 8472), False, 'import itertools\n'), ((15129, 15155), 'scipy.isnan', 'scipy.isnan', (['self.constant'], {}), '(self.constant)\n', (15140, 15155), False, 'import scipy\n'), ((21956, 21972), 'numpy.asarray', 'numpy.asarray', (['y'], {}), '(y)\n', (21969, 21972), False, 'import numpy\n'), ((31793, 31825), 'numpy.asfortranarray', 'numpy.asfortranarray', (['X_unbiased'], {}), '(X_unbiased)\n', (31813, 31825), False, 'import numpy\n'), ((31882, 31917), 'numpy.dot', 'numpy.dot', (['X_unbiased.T', 'y_unbiased'], {}), '(X_unbiased.T, y_unbiased)\n', (31891, 31917), False, 'import numpy\n'), ((32995, 33006), 'time.time', 'time.time', ([], {}), '()\n', (33004, 33006), False, 'import time\n'), ((37843, 37891), 'numpy.copyto', 'numpy.copyto', (['X_stds', '(1.0)'], {'where': '(~(X_stds > 0.0))'}), '(X_stds, 1.0, where=~(X_stds > 0.0))\n', (37855, 37891), False, 'import numpy\n'), ((38854, 38885), 'numpy.zeros', 'numpy.zeros', (['(n + 1)'], {'dtype': 'float'}), '(n + 1, dtype=float)\n', (38865, 38885), False, 'import numpy\n'), ((39822, 39830), 'functools.wraps', 'wraps', (['f'], {}), '(f)\n', (39827, 39830), False, 'from functools import wraps\n'), ((40390, 40427), 'sklearn.linear_model.ElasticNet.fit', 'ElasticNet.fit', (['self', '*args'], {}), '(self, *args, **kwargs)\n', (40404, 40427), False, 'from sklearn.linear_model import ElasticNet\n'), ((41074, 41095), 'numpy.asarray', 'numpy.asarray', (['cost0s'], {}), '(cost0s)\n', (41087, 41095), False, 'import numpy\n'), ((41097, 41118), 'numpy.asarray', 'numpy.asarray', (['cost1s'], {}), '(cost1s)\n', (41110, 41118), False, 'import numpy\n'), ((43668, 43687), 'numpy.asarray', 'numpy.asarray', (['yhat'], {}), '(yhat)\n', (43681, 43687), False, 'import numpy\n'), ((43689, 43705), 'numpy.asarray', 'numpy.asarray', (['y'], {}), '(y)\n', (43702, 43705), False, 'import numpy\n'), ((43833, 43852), 'scipy.isnan', 'scipy.isnan', (['result'], {}), '(result)\n', (43844, 43852), False, 'import scipy\n'), ((7882, 7909), 'numpy.zeros', 'numpy.zeros', (['N'], {'dtype': 'float'}), '(N, dtype=float)\n', (7893, 7909), False, 'import numpy\n'), ((7969, 8011), 'itertools.izip', 'itertools.izip', (['self.coefs_d', 'self.bases_d'], {}), '(self.coefs_d, self.bases_d)\n', (7983, 8011), False, 'import itertools\n'), ((8771, 8813), 'itertools.izip', 'itertools.izip', (['self.coefs_d', 'self.bases_d'], {}), '(self.coefs_d, self.bases_d)\n', (8785, 8813), False, 'import itertools\n'), ((11239, 11255), 'numpy.abs', 'numpy.abs', (['y_lin'], {}), '(y_lin)\n', (11248, 11255), False, 'import numpy\n'), ((15191, 15213), 'numpy.array', 'numpy.array', (['([INF] * N)'], {}), '([INF] * N)\n', (15202, 15213), False, 'import numpy\n'), ((22225, 22256), 'numpy.reshape', 'numpy.reshape', (['y', '(y.shape[0],)'], {}), '(y, (y.shape[0],))\n', (22238, 22256), False, 'import numpy\n'), ((26257, 26289), 'numpy.argsort', 'numpy.argsort', (['(-1 * order1_infls)'], {}), '(-1 * order1_infls)\n', (26270, 26289), False, 'import numpy\n'), ((32274, 32296), 'numpy.log10', 'numpy.log10', (['alpha_max'], {}), '(alpha_max)\n', (32285, 32296), False, 'import numpy\n'), ((32653, 32688), 'numpy.dot', 'numpy.dot', (['X_unbiased.T', 'X_unbiased'], {}), '(X_unbiased.T, X_unbiased)\n', (32662, 32688), False, 'import numpy\n'), ((35421, 35443), 'scipy.isinf', 'scipy.isinf', (['nmses[-1]'], {}), '(nmses[-1])\n', (35432, 35443), False, 'import scipy\n'), ((38171, 38197), 'numpy.isfinite', 'numpy.isfinite', (['X_unbiased'], {}), '(X_unbiased)\n', (38185, 38197), False, 'import numpy\n'), ((38224, 38250), 'numpy.isfinite', 'numpy.isfinite', (['y_unbiased'], {}), '(y_unbiased)\n', (38238, 38250), False, 'import numpy\n'), ((39885, 39923), 'signal.signal', 'signal.signal', (['signal.SIGALRM', 'handler'], {}), '(signal.SIGALRM, handler)\n', (39898, 39923), False, 'import signal\n'), ((39936, 39972), 'signal.alarm', 'signal.alarm', (['seconds_before_timeout'], {}), '(seconds_before_timeout)\n', (39948, 39972), False, 'import signal\n'), ((40118, 40133), 'signal.alarm', 'signal.alarm', (['(0)'], {}), '(0)\n', (40130, 40133), False, 'import signal\n'), ((43777, 43820), 'numpy.mean', 'numpy.mean', (['(((yhat_a - y_a) / y_range) ** 2)'], {}), '(((yhat_a - y_a) / y_range) ** 2)\n', (43787, 43820), False, 'import numpy\n'), ((44005, 44019), 'scipy.isinf', 'scipy.isinf', (['y'], {}), '(y)\n', (44016, 44019), False, 'import scipy\n'), ((44028, 44042), 'scipy.isnan', 'scipy.isnan', (['y'], {}), '(y)\n', (44039, 44042), False, 'import scipy\n'), ((44201, 44213), 'numpy.abs', 'numpy.abs', (['x'], {}), '(x)\n', (44210, 44213), False, 'import numpy\n'), ((6765, 6784), 'numpy.abs', 'numpy.abs', (['coefs_n2'], {}), '(coefs_n2)\n', (6774, 6784), False, 'import numpy\n'), ((6984, 7002), 'numpy.abs', 'numpy.abs', (['coefs_d'], {}), '(coefs_d)\n', (6993, 7002), False, 'import numpy\n'), ((11301, 11328), 'numpy.clip', 'numpy.clip', (['y_lin', '(0.0)', 'INF'], {}), '(y_lin, 0.0, INF)\n', (11311, 11328), False, 'import numpy\n'), ((12041, 12076), 'numpy.ones', 'numpy.ones', (['X.shape[0]'], {'dtype': 'float'}), '(X.shape[0], dtype=float)\n', (12051, 12076), False, 'import numpy\n'), ((15263, 15289), 'numpy.ones', 'numpy.ones', (['N'], {'dtype': 'float'}), '(N, dtype=float)\n', (15273, 15289), False, 'import numpy\n'), ((26620, 26645), 'math.sqrt', 'math.sqrt', (['n_order1_bases'], {}), '(n_order1_bases)\n', (26629, 26645), False, 'import math\n'), ((34839, 34882), 'numpy.dot', 'numpy.dot', (['cur_unbiased_coefs', 'X_unbiased.T'], {}), '(cur_unbiased_coefs, X_unbiased.T)\n', (34848, 34882), False, 'import numpy\n'), ((40071, 40105), 'signal.signal', 'signal.signal', (['signal.SIGALRM', 'old'], {}), '(signal.SIGALRM, old)\n', (40084, 40105), False, 'import signal\n'), ((44269, 44281), 'numpy.abs', 'numpy.abs', (['x'], {}), '(x)\n', (44278, 44281), False, 'import numpy\n'), ((11374, 11402), 'numpy.clip', 'numpy.clip', (['y_lin', '(-INF)', '(0.0)'], {}), '(y_lin, -INF, 0.0)\n', (11384, 11402), False, 'import numpy\n'), ((29971, 29984), 'numpy.mean', 'numpy.mean', (['y'], {}), '(y)\n', (29981, 29984), False, 'import numpy\n'), ((31961, 31977), 'scipy.isnan', 'scipy.isnan', (['val'], {}), '(val)\n', (31972, 31977), False, 'import scipy\n'), ((33809, 33820), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (33817, 33820), False, 'import sys\n'), ((35050, 35083), 'numpy.nonzero', 'numpy.nonzero', (['cur_unbiased_coefs'], {}), '(cur_unbiased_coefs)\n', (35063, 35083), False, 'import numpy\n'), ((36755, 36798), 'itertools.izip', 'itertools.izip', (['bases', 'coefs[1:n_bases + 1]'], {}), '(bases, coefs[1:n_bases + 1])\n', (36769, 36798), False, 'import itertools\n'), ((36952, 36994), 'itertools.izip', 'itertools.izip', (['bases', 'coefs[n_bases + 1:]'], {}), '(bases, coefs[n_bases + 1:])\n', (36966, 36994), False, 'import itertools\n'), ((37263, 37295), 'itertools.izip', 'itertools.izip', (['bases', 'coefs[1:]'], {}), '(bases, coefs[1:])\n', (37277, 37295), False, 'import itertools\n'), ((44314, 44326), 'numpy.abs', 'numpy.abs', (['x'], {}), '(x)\n', (44323, 44326), False, 'import numpy\n'), ((23941, 23975), 'numpy.all', 'numpy.all', (['(nonlin_yhat == lin_yhat)'], {}), '(nonlin_yhat == lin_yhat)\n', (23950, 23975), False, 'import numpy\n'), ((24486, 24562), 'numpy.arange', 'numpy.arange', (['(minx + 0.2 * rangex)', '(maxx - 0.2 * rangex + 0.1 * rangex)', 'stepx'], {}), '(minx + 0.2 * rangex, maxx - 0.2 * rangex + 0.1 * rangex, stepx)\n', (24498, 24562), False, 'import numpy\n'), ((44359, 44371), 'numpy.abs', 'numpy.abs', (['x'], {}), '(x)\n', (44368, 44371), False, 'import numpy\n'), ((11560, 11575), 'scipy.isnan', 'scipy.isnan', (['mn'], {}), '(mn)\n', (11571, 11575), False, 'import scipy\n'), ((11592, 11607), 'scipy.isnan', 'scipy.isnan', (['mx'], {}), '(mx)\n', (11603, 11607), False, 'import scipy\n'), ((11675, 11693), 'numpy.log10', 'numpy.log10', (['y_lin'], {}), '(y_lin)\n', (11686, 11693), False, 'import numpy\n'), ((11738, 11776), 'numpy.clip', 'numpy.clip', (['(self.thr - y_lin)', '(0.0)', 'INF'], {}), '(self.thr - y_lin, 0.0, INF)\n', (11748, 11776), False, 'import numpy\n'), ((44404, 44416), 'numpy.abs', 'numpy.abs', (['x'], {}), '(x)\n', (44413, 44416), False, 'import numpy\n'), ((11821, 11859), 'numpy.clip', 'numpy.clip', (['(y_lin - self.thr)', '(0.0)', 'INF'], {}), '(y_lin - self.thr, 0.0, INF)\n', (11831, 11859), False, 'import numpy\n'), ((35353, 35364), 'time.time', 'time.time', ([], {}), '()\n', (35362, 35364), False, 'import time\n'), ((44449, 44461), 'numpy.abs', 'numpy.abs', (['x'], {}), '(x)\n', (44458, 44461), False, 'import numpy\n'), ((44494, 44506), 'numpy.abs', 'numpy.abs', (['x'], {}), '(x)\n', (44503, 44506), False, 'import numpy\n'), ((44539, 44551), 'numpy.abs', 'numpy.abs', (['x'], {}), '(x)\n', (44548, 44551), False, 'import numpy\n')]
""" DataContainer class for linking directories containing different sorts of data. This is meant to make plotting and analysis easier. TO DO ----- - request random subsets. - make sure input directories are iterable - add features to existing files. """ __date__ = "July-November 2019" import h5py try: from numba.errors import NumbaPerformanceWarning except NameError: pass import numpy as np import os from scipy.io import wavfile from sklearn.decomposition import PCA from time import strptime, mktime import torch import umap import warnings from ava.models.vae import VAE from ava.models.vae_dataset import get_syllable_partition, \ get_syllable_data_loaders, get_hdf5s_from_dir AUDIO_FIELDS = ['audio'] FILENAME_FIELDS = ['sap_time'] SEGMENT_FIELDS = ['segments', 'segment_audio'] PROJECTION_FIELDS = ['latent_means', 'latent_mean_pca', 'latent_mean_umap'] SPEC_FIELDS = ['specs', 'onsets', 'offsets', 'audio_filenames'] MUPET_FIELDS = ['syllable_number', 'syllable_start_time', 'syllable_end_time', 'inter-syllable_interval', 'syllable_duration', 'starting_frequency', 'final_frequency', 'minimum_frequency', 'maximum_frequency', 'mean_frequency', 'frequency_bandwidth', 'total_syllable_energy', 'peak_syllable_amplitude', 'cluster'] DEEPSQUEAK_FIELDS = ['id', 'label', 'accepted', 'score', 'begin_time', 'end_time', 'call_length', 'principal_frequency', 'low_freq', 'high_freq', 'delta_freq', 'frequency_standard_deviation', 'slope', 'sinuosity', 'mean_power', 'tonality'] SAP_FIELDS = ['syllable_duration_sap', 'syllable_start', 'mean_amplitude', 'mean_pitch', 'mean_FM', 'mean_AM2', 'mean_entropy', 'mean_pitch_goodness', 'mean_mean_freq', 'pitch_variance', 'FM_variance', 'entropy_variance', 'pitch_goodness_variance', 'mean_freq_variance', 'AM_variance'] ALL_FIELDS = AUDIO_FIELDS + FILENAME_FIELDS + SEGMENT_FIELDS + \ PROJECTION_FIELDS + SPEC_FIELDS + MUPET_FIELDS + DEEPSQUEAK_FIELDS + \ SAP_FIELDS """All fields that can be requested by a DataContainer object.""" MUPET_ONSET_COL = MUPET_FIELDS.index('syllable_start_time') DEEPSQUEAK_ONSET_COL = DEEPSQUEAK_FIELDS.index('begin_time') SAP_ONSET_COL = SAP_FIELDS.index('syllable_start') PRETTY_NAMES = { 'audio': 'Audio', 'segments': 'Segments', 'segment_audio': 'Segment Audio', 'latent_means': 'Latent Means', 'latent_mean_pca': 'Latent Mean PCA Projection', 'latent_mean_umap': 'Latent Mean UMAP Projection', 'specs': 'Spectrograms', 'onsets': 'Onsets (s)', 'offsets': 'Offsets (s)', 'aduio_filenames': 'Filenames', 'syllable_number': 'Syllable Number', 'syllable_start_time': 'Onsets (s)', 'syllable_duration': 'Duration (ms)', 'starting_frequency': 'Starting Freq. (kHz)', 'final_frequency': 'Final Freq. (kHz)', 'minimum_frequency': 'Min Freq. (kHz)', 'maximum_frequency': 'Max Freq. (kHz)', 'mean_frequency': 'Mean Freq. (kHz)', 'frequency_bandwidth': 'Freq. Bandwidth (kHz)', 'total_syllable_energy': 'Total Energy (dB)', 'peak_syllable_amplitude': 'Peak Amplitude (dB)', 'cluster': 'Cluster', 'id': 'Syllabler Number', 'label': 'Label', 'accepted': 'Accepted', 'score': 'DeepSqueak Detection Score', 'begin_time': 'Onsets (s)', 'end_time': 'Offsets (s)', 'call_length': 'Duration (ms)', 'principal_frequency': 'Principal Freq. (kHz)', 'low_freq': 'Minimum Freq. (kHz)', 'high_freq': 'Max Freq. (kHz)', 'delta_freq': 'Freq. Bandwidth (kHz)', 'frequency_standard_deviation': 'Freq Std. Dev. (kHz)', 'slope': 'Freq. Mod. (kHz/s)', 'sinuosity': 'Sinuosity', 'mean_power': 'Power (dB/Hz)', 'tonality': 'Tonality', 'syllable_duration_sap': 'Duration (s)', 'syllable_start': 'Onset (s)', 'mean_amplitude': 'Amplitude', 'mean_pitch': 'Pitch', 'mean_FM': 'Freq. Mod.', 'mean_AM2': 'Amp. Mod.', 'mean_entropy': 'Entropy', 'mean_pitch_goodness': 'Goodness of Pitch', 'mean_mean_freq': 'Mean Frequency', 'pitch_variance': 'Pitch Variance', 'FM_variance': 'Freq. Mod. Var.', 'entropy_variance': 'Entropy Var.', 'pitch_goodness_variance': 'Goodness of Pitch Var.', 'mean_freq_variance': 'Freq. Var.', 'AM_variance': 'Amp. Mod. Var.', } PRETTY_NAMES_NO_UNITS = {} for k in PRETTY_NAMES: PRETTY_NAMES_NO_UNITS[k] = ' '.join(PRETTY_NAMES[k].split('(')[0].split(' ')) class DataContainer(): """ Link directories containing different data sources for easy plotting. The idea here is for plotting and analysis tools to accept a DataContainer, from which they can request different types of data. Those requests can then be handled here in a central location, which can cut down on redundant code and processing steps. Attributes ---------- audio_dirs : {list of str, None}, optional Directories containing audio. Defaults to None. segment_dirs : {list of str, None}, optional Directories containing segmenting decisions. spec_dirs : list of {str, None}, optional Directories containing hdf5 files of spectrograms. These should be files output by ava.preprocessing.preprocessing. Defaults to None. model_filename : {str, None}, optional The VAE checkpoint to load. Written by models.vae.save_state. Defaults to None. projection_dirs : list of {str, None}, optional Directory containing different projections. This is where things like latent means, their projections, and handcrafted features found in feature_dirs are saved. Defaults to None. plots_dir : str, optional Directory to save plots. Defaults to '' (current working directory). feature_dirs : list of {str, None}, optional Directory containing text files with different syllable features. For exmaple, this could contain exported MUPET, DeepSqueak or SAP syllable tables. Defaults to None. template_dir : {str, None}, optional Directory continaing audio files of song templates. Defaults to None. Methods ------- request(field) Request some type of data. Notes ----- Supported directory structure: :: โ”œโ”€โ”€ animal_1 โ”‚ โ”œโ”€โ”€ audio (raw audio) โ”‚ โ”‚ โ”œโ”€โ”€ foo.wav โ”‚ โ”‚ โ”œโ”€โ”€ bar.wav โ”‚ โ”‚ โ””โ”€โ”€ baz.wav โ”‚ โ”œโ”€โ”€ features (output of MUPET, DeepSqueak, SAP, ...) โ”‚ โ”‚ โ”œโ”€โ”€ foo.csv โ”‚ โ”‚ โ”œโ”€โ”€ bar.csv โ”‚ โ”‚ โ””โ”€โ”€ baz.csv โ”‚ โ”œโ”€โ”€ spectrograms (used to train models, written by โ”‚ โ”‚ โ”œโ”€โ”€ syllables_000.hdf5 preprocessing.preprocess.process_sylls) โ”‚ โ”‚ โ””โ”€โ”€ syllables_001.hdf5 โ”‚ โ””โ”€โ”€ projections (latent means, UMAP, PCA, tSNE โ”‚ โ”œโ”€โ”€ syllables_000.hdf5 projections, copies of features in โ”‚ โ””โ”€โ”€ syllables_001.hdf5 experiment_1/features. These are โ”‚ written by a DataContainer object.) โ”œโ”€โ”€ animal_2 โ”‚ โ”œโ”€โ”€ audio โ”‚ โ”‚ โ”œโ”€โ”€ 1.wav โ”‚ โ”‚ โ””โ”€โ”€ 2.wav โ”‚ โ”œโ”€โ”€ features โ”‚ โ”‚ โ”œโ”€โ”€ 1.csv โ”‚ โ”‚ โ””โ”€โ”€ 2.csv โ”‚ โ”œโ”€โ”€ spectrograms โ”‚ โ”‚ โ”œโ”€โ”€ syllables_000.hdf5 โ”‚ โ”‚ โ””โ”€โ”€ syllables_001.hdf5 โ”‚ โ””โ”€โ”€ projections โ”‚ โ”œโ”€โ”€ syllables_000.hdf5 โ”‚ โ””โ”€โ”€ syllables_001.hdf5 . . . There should be a 1-to-1 correspondence between, for example, the syllables in `animal_1/audio/baz.wav` and the features described in `animal_1/features/baz.csv`. Analogously, the fifth entry in `animal_2/spectrograms/syllables_000.hdf5` should describe the same syllable as the fifth entry in `animal_2/projections/syllables_000.hdf5`. There is no strict relationship, however, between individual files in `animal_1/audio` and `animal_1/spectrograms`. The hdf5 files in the spectrograms and projections directories should contain a subset of the syllables in the audio and features directories. Then a DataContainer object can be initialized as: >>> from ava.data.data_container import DataContainer >>> audio_dirs = ['animal_1/audio', 'animal_2/audio'] >>> spec_dirs = ['animal_1/spectrograms', 'animal_2/spectrograms'] >>> model_filename = 'checkpoint.tar' >>> dc = DataContainer(audio_dirs=audio_dirs, spec_dirs=spec_dirs, \ model_filename=model_filename) >>> latent_means = dc.request('latent_means') It's fine to leave some of the initialization parameters unspecified. If the DataContainer object is asked to do something it can't, it will hopefully complain politely. Or at least informatively. """ def __init__(self, audio_dirs=None, segment_dirs=None, spec_dirs=None, \ feature_dirs=None, projection_dirs=None, plots_dir='', \ model_filename=None, template_dir=None, verbose=True): self.audio_dirs = audio_dirs self.segment_dirs = segment_dirs self.spec_dirs = spec_dirs self.feature_dirs = feature_dirs self.projection_dirs = projection_dirs self.plots_dir = plots_dir self.model_filename = model_filename self.template_dir = template_dir self.verbose = verbose self.sylls_per_file = None # syllables in each hdf5 file in spec_dirs self.fields = self._check_for_fields() if self.plots_dir not in [None, ''] and not os.path.exists(self.plots_dir): os.makedirs(self.plots_dir) def request(self, field): """ Request some type of data. Parameters ---------- field : str The type of data being requested. Should come from ... Raises ------ `NotImplementedError` when `field` is not recognized. Note ---- Besides `__init__` and `clear_projections`, this should be the only external-facing method. """ if field not in ALL_FIELDS: print(str(field) + " is not a valid field!") raise NotImplementedError # If it's not here, make it and return it. if field not in self.fields: if self.verbose: print("Making field:", field) data = self._make_field(field) # Otherwise, read it and return it. else: if self.verbose: print("Reading field:", field) data = self._read_field(field) if self.verbose: print("\tDone with:", field) return data def clear_projections(self): """Remove all projections.""" for proj_dir in self.projection_dirs: if not os.path.exists(proj_dir): continue fns = [os.path.join(proj_dir, i) for i in os.listdir(proj_dir)] fns = [i for i in fns if len(i) > 5 and i[-5:] == '.hdf5'] for fn in fns: os.remove(fn) self.fields = self._check_for_fields() def clean_projections(self): """ Remove all projections. Note ---- * This will be deprecated in 0.3.0. Use ``clear_projections`` instead. """ warnings.warn( "clean_projections will be deprecated in v0.3.0. " + \ "Use clear_projections instead.", UserWarning ) self.clear_projections() def _make_field(self, field): """Make a field.""" if field == 'latent_means': data = self._make_latent_means() elif field == 'latent_mean_pca': data = self._make_latent_mean_pca_projection() elif field == 'latent_mean_umap': data = self._make_latent_mean_umap_projection() elif field in MUPET_FIELDS: data = self._make_feature_field(field, kind='mupet') elif field in DEEPSQUEAK_FIELDS: data = self._make_feature_field(field, kind='deepsqueak') elif field in SAP_FIELDS: data = self._make_feature_field(field, kind='sap') elif field in FILENAME_FIELDS: data = self._read_filename_field(field) elif field == 'specs': raise NotImplementedError else: raise NotImplementedError # Add this field to the collection of fields that have been computed. self.fields[field] = 1 if self.verbose: print("Making field:", field) return data def _read_field(self, field): """ Read a field from memory. Parameters ---------- field : str Field name to read from file. See ``ALL_FIELDS`` for possible fields. """ if field in AUDIO_FIELDS: raise NotImplementedError elif field == 'segments': return self._read_segments() elif field == 'segment_audio': return self._read_segment_audio() elif field in PROJECTION_FIELDS: load_dirs = self.projection_dirs elif field in SPEC_FIELDS: load_dirs = self.spec_dirs elif field in MUPET_FIELDS: load_dirs = self.projection_dirs elif field in DEEPSQUEAK_FIELDS: load_dirs = self.projection_dirs elif field in SAP_FIELDS: load_dirs = self.projection_dirs else: raise Exception("Can\'t read field: "+field+"\n This should have \ been caught in self.request!") to_return = [] for i in range(len(self.spec_dirs)): spec_dir, load_dir = self.spec_dirs[i], load_dirs[i] hdf5s = get_hdf5s_from_dir(spec_dir) for j, hdf5 in enumerate(hdf5s): filename = os.path.join(load_dir, os.path.split(hdf5)[-1]) with h5py.File(filename, 'r') as f: assert field in f, "Can\'t find field \'"+field+"\' in"+ \ " file \'"+filename+"\'!" if field == 'audio_filenames': data = np.array([k.decode('UTF-8') for k in f[field]]) to_return.append(data) else: to_return.append(np.array(f[field])) return np.concatenate(to_return) def _read_segment_audio(self): """ Read all the segmented audio and return it. result[audio_dir][audio_filename] = [audio_1, audio_2, ..., audio_n] """ self._check_for_dirs(['audio_dirs'], 'audio') segments = self.request('segments') result = {} for audio_dir in self.audio_dirs: dir_result = {} audio_fns = [i for i in os.listdir(audio_dir) if _is_wav_file(i) \ and i in segments[audio_dir]] for audio_fn in audio_fns: fs, audio = wavfile.read(os.path.join(audio_dir, audio_fn)) fn_result = [] for seg in segments[audio_dir][audio_fn]: i1 = int(round(seg[0]*fs)) i2 = int(round(seg[1]*fs)) fn_result.append(audio[i1:i2]) dir_result[audio_fn] = fn_result result[audio_dir] = dir_result return result def _read_segments(self): """ Return all the segmenting decisions. Return a dictionary mapping audio directories to audio filenames to numpy arrays of shape [num_segments,2] containing onset and offset times. TO DO: add support for other delimiters, file extstensions, etc. Returns ------- segments : dict Maps audio directories to audio filenames to numpy arrays. """ self._check_for_dirs(['audio_dirs', 'segment_dirs'], 'segments') result = {} for audio_dir, seg_dir in zip(self.audio_dirs, self.segment_dirs): dir_result = {} seg_fns = [os.path.join(seg_dir, i) for i in os.listdir(seg_dir) \ if _is_seg_file(i)] audio_fns = [os.path.split(i)[1][:-4]+'.wav' for i in seg_fns] for audio_fn, seg_fn in zip(audio_fns, seg_fns): segs = _read_columns(seg_fn, delimiter='\t', unpack=False, \ skiprows=0) if len(segs) > 0: dir_result[audio_fn] = segs result[audio_dir] = dir_result return result def _make_latent_means(self): """ Write latent means for the syllables in self.spec_dirs. Returns ------- latent_means : numpy.ndarray Latent means of shape (max_num_syllables, z_dim) Note ---- * Duplicated code with ``_write_projection``? """ self._check_for_dirs(['projection_dirs', 'spec_dirs', 'model_filename'],\ 'latent_means') # First, see how many syllables are in each file. temp = get_hdf5s_from_dir(self.spec_dirs[0]) assert len(temp) > 0, "Found no specs in" + self.spec_dirs[0] hdf5_file = temp[0] with h5py.File(hdf5_file, 'r') as f: self.sylls_per_file = len(f['specs']) spf = self.sylls_per_file # Load the model, making sure to get z_dim correct. map_loc = 'cuda' if torch.cuda.is_available() else 'cpu' z_dim = torch.load(self.model_filename, map_location=map_loc)['z_dim'] model = VAE(z_dim=z_dim) model.load_state(self.model_filename) # For each directory... all_latent = [] for i in range(len(self.spec_dirs)): spec_dir, proj_dir = self.spec_dirs[i], self.projection_dirs[i] # Make the projection directory if it doesn't exist. if proj_dir != '' and not os.path.exists(proj_dir): os.makedirs(proj_dir) # Make a DataLoader for the syllables. partition = get_syllable_partition([spec_dir], 1, shuffle=False) try: loader = get_syllable_data_loaders(partition, \ shuffle=(False,False))['train'] # Get the latent means from the model. latent_means = model.get_latent(loader) all_latent.append(latent_means) # Write them to the corresponding projection directory. hdf5s = get_hdf5s_from_dir(spec_dir) assert len(latent_means) // len(hdf5s) == spf for j in range(len(hdf5s)): filename = os.path.join(proj_dir, os.path.split(hdf5s[j])[-1]) data = latent_means[j*spf:(j+1)*spf] with h5py.File(filename, 'a') as f: f.create_dataset('latent_means', data=data) except AssertionError: # No specs in this directory pass return np.concatenate(all_latent) def _read_filename_field(self, field): if field == 'sap_time': data = self._make_sap_time() else: raise NotImplementedError return data def _make_sap_time(self): """Return time in seconds, following SAP conventions.""" onsets = self.request('syllable_start') fns = self.request('audio_filenames') result = np.zeros(lemn(onsets)) for i, onset, fn in zip(range(len(onsets)), onsets, fns): # December 29, 1899, 7pm is the SAP anchor time. anchor = mktime(strptime("1899 12 29 19", "%Y %m %d %H")) temp = os.path.split(fn)[-1].split('_')[1].split('.') day = float(temp[0]) millisecond = float(temp[1]) time = anchor + 24*60*60*day + 1e-3*millisecond result[i] = time + onset return result def _make_latent_mean_umap_projection(self): """Project latent means to two dimensions with UMAP.""" # Get latent means. latent_means = self.request('latent_means') # UMAP them. transform = umap.UMAP(n_components=2, n_neighbors=20, min_dist=0.1, \ metric='euclidean', random_state=42) if self.verbose: print("Running UMAP... (n="+str(len(latent_means))+")") # https://github.com/lmcinnes/umap/issues/252 with warnings.catch_warnings(): try: warnings.filterwarnings("ignore", \ category=NumbaPerformanceWarning) except NameError: pass embedding = transform.fit_transform(latent_means) if self.verbose: print("Done.") # Write to files. self._write_projection("latent_mean_umap", embedding) return embedding def _make_latent_mean_pca_projection(self): """Project latent means to two dimensions with PCA.""" # Get latent means. latent_means = self.request('latent_means') # UMAP them. transform = PCA(n_components=2, copy=False, random_state=42) if self.verbose: print("Running PCA...") embedding = transform.fit_transform(latent_means) if self.verbose: print("Done.") # Write to files. self._write_projection("latent_mean_pca", embedding) return embedding def _make_feature_field(self, field, kind): """ Read a feature from a text file and put it in an hdf5 file. Read from self.feature_dirs and write to self.projection_dirs. This could be a bit tricky because we need to match up the syllables in the text file with the ones in the hdf5 file. Parameters ---------- field : str Name of data being requested. See ``ALL_FIELDS`` for a complete list. kind : str, 'mupet' or 'deepsqueak' Is this a MUPET or a DeepSqueak field? Returns ------- data : numpy.ndarray Requested data. """ self._check_for_dirs( \ ['spec_dirs', 'feature_dirs', 'projection_dirs'], field) # FInd which column the field is stored in. if kind == 'mupet': file_fields = MUPET_FIELDS onset_col = MUPET_ONSET_COL elif kind == 'deepsqueak': file_fields = DEEPSQUEAK_FIELDS onset_col = DEEPSQUEAK_ONSET_COL elif kind == 'sap': file_fields = SAP_FIELDS onset_col = SAP_ONSET_COL else: assert NotImplementedError field_col = file_fields.index(field) to_return = [] # Run through each directory. for i in range(len(self.spec_dirs)): spec_dir = self.spec_dirs[i] feature_dir = self.feature_dirs[i] proj_dir = self.projection_dirs[i] hdf5s = get_hdf5s_from_dir(spec_dir) current_fn, k = None, None for hdf5 in hdf5s: # Get the filenames and onsets from self.spec_dirs. with h5py.File(hdf5, 'r') as f: audio_filenames = np.array(f['audio_filenames']) spec_onsets = np.array(f['onsets']) # if kind == 'sap': # SAP writes onsets in milliseconds. # spec_onsets /= 1e3 feature_arr = np.zeros(len(spec_onsets)) # Loop through each syllable. for j in range(len(spec_onsets)): audio_fn, spec_onset = audio_filenames[j], spec_onsets[j] audio_fn = audio_fn.decode('UTF-8') # Update the feature file, if needed. if audio_fn != current_fn: current_fn = audio_fn feature_fn = os.path.split(audio_fn)[-1][:-4] if kind == 'deepsqueak': # DeepSqueak appends '_Stats' feature_fn += '_Stats' # when exporting features. feature_fn += '.csv' feature_fn = os.path.join(feature_dir, feature_fn) # Read the onsets and features. feature_onsets, features = \ _read_columns(feature_fn, [onset_col, field_col]) if kind == 'sap': # SAP writes onsets in milliseconds. feature_onsets /= 1e3 k = 0 # Look for the corresponding onset in the feature file. while spec_onset > feature_onsets[k] + 0.01: k += 1 assert k < len(feature_onsets) if abs(spec_onset - feature_onsets[k]) > 0.01: print("Mismatch between spec_dirs and feature_dirs!") print("hdf5 file:", hdf5) print("\tindex:", j) print("audio filename:", audio_fn) print("feature filename:", feature_fn) print("Didn't find spec_onset", spec_onset) print("in feature onsets of min:", \ np.min(feature_onsets), "max:", \ np.max(feature_onsets)) print("field:", field) print("kind:", kind) quit() # And add it to the feature array. feature_arr[j] = features[k] # Write the fields to self.projection_dirs. write_fn = os.path.join(proj_dir, os.path.split(hdf5)[-1]) with h5py.File(write_fn, 'a') as f: f.create_dataset(field, data=feature_arr) to_return.append(feature_arr) self.fields[field] = 1 return np.concatenate(to_return) def _write_projection(self, key, data): """Write the given projection to self.projection_dirs.""" sylls_per_file = self.sylls_per_file # For each directory... k = 0 for i in range(len(self.projection_dirs)): spec_dir, proj_dir = self.spec_dirs[i], self.projection_dirs[i] hdf5s = get_hdf5s_from_dir(spec_dir) for j in range(len(hdf5s)): filename = os.path.join(proj_dir, os.path.split(hdf5s[j])[-1]) to_write = data[k:k+sylls_per_file] with h5py.File(filename, 'a') as f: f.create_dataset(key, data=to_write) k += sylls_per_file def _check_for_fields(self): """Check to see which fields are saved.""" fields = {} # If self.spec_dirs is registered, assume everything is there. if self.spec_dirs is not None: for field in SPEC_FIELDS: fields[field] = 1 # Same for self.audio_dirs. if self.audio_dirs is not None: fields['audio'] = 1 # Same for self.segment_dirs. if self.segment_dirs is not None: fields['segments'] = 1 fields['segment_audio'] = 1 # If self.projection_dirs is registered, see what we have. # If it's in one file, assume it's in all of them. if self.projection_dirs is not None: if os.path.exists(self.projection_dirs[0]): hdf5s = get_hdf5s_from_dir(self.projection_dirs[0]) if len(hdf5s) > 0: hdf5 = hdf5s[0] if os.path.exists(hdf5): with h5py.File(hdf5, 'r') as f: for key in f.keys(): if key in ALL_FIELDS: fields[key] = 1 self.sylls_per_file = len(f[key]) return fields def _check_for_dirs(self, dir_names, field): """Check that the given directories exist.""" for dir_name in dir_names: if dir_name == 'audio_dirs': temp = self.audio_dirs elif dir_name == 'segment_dirs': temp = self.segment_dirs elif dir_name == 'spec_dirs': temp = self.spec_dirs elif dir_name == 'feature_dirs': temp = self.feature_dirs elif dir_name == 'projection_dirs': temp = self.projection_dirs elif dir_name == 'model_filename': temp = self.model_filename else: raise NotImplementedError assert temp is not None, dir_name + " must be specified before " + \ field + " is made!" def _read_columns(filename, columns=(0,1), delimiter=',', skiprows=1, \ unpack=True): """ A wrapper around numpy.loadtxt to handle empty files. TO DO: Add categorical variables. """ data = np.loadtxt(filename, delimiter=delimiter, usecols=columns, \ skiprows=skiprows).reshape(-1,len(columns)) if unpack: return tuple(data[:,i] for i in range(data.shape[1])) return data def _is_seg_file(filename): """Is this a segmenting file?""" return len(filename) > 4 and filename[-4:] == '.txt' def _is_wav_file(filename): """Is this a wav file?""" return len(filename) > 4 and filename[-4:] == '.wav' if __name__ == '__main__': pass ###
[ "os.remove", "ava.models.vae.VAE", "os.path.join", "ava.models.vae_dataset.get_syllable_partition", "torch.load", "os.path.exists", "numpy.max", "warnings.catch_warnings", "numpy.loadtxt", "h5py.File", "ava.models.vae_dataset.get_hdf5s_from_dir", "umap.UMAP", "numpy.min", "torch.cuda.is_av...
[((10192, 10309), 'warnings.warn', 'warnings.warn', (["('clean_projections will be deprecated in v0.3.0. ' +\n 'Use clear_projections instead.')", 'UserWarning'], {}), "('clean_projections will be deprecated in v0.3.0. ' +\n 'Use clear_projections instead.', UserWarning)\n", (10205, 10309), False, 'import warnings\n'), ((12632, 12657), 'numpy.concatenate', 'np.concatenate', (['to_return'], {}), '(to_return)\n', (12646, 12657), True, 'import numpy as np\n'), ((14819, 14856), 'ava.models.vae_dataset.get_hdf5s_from_dir', 'get_hdf5s_from_dir', (['self.spec_dirs[0]'], {}), '(self.spec_dirs[0])\n', (14837, 14856), False, 'from ava.models.vae_dataset import get_syllable_partition, get_syllable_data_loaders, get_hdf5s_from_dir\n'), ((15247, 15263), 'ava.models.vae.VAE', 'VAE', ([], {'z_dim': 'z_dim'}), '(z_dim=z_dim)\n', (15250, 15263), False, 'from ava.models.vae import VAE\n'), ((16378, 16404), 'numpy.concatenate', 'np.concatenate', (['all_latent'], {}), '(all_latent)\n', (16392, 16404), True, 'import numpy as np\n'), ((17344, 17440), 'umap.UMAP', 'umap.UMAP', ([], {'n_components': '(2)', 'n_neighbors': '(20)', 'min_dist': '(0.1)', 'metric': '"""euclidean"""', 'random_state': '(42)'}), "(n_components=2, n_neighbors=20, min_dist=0.1, metric='euclidean',\n random_state=42)\n", (17353, 17440), False, 'import umap\n'), ((18106, 18154), 'sklearn.decomposition.PCA', 'PCA', ([], {'n_components': '(2)', 'copy': '(False)', 'random_state': '(42)'}), '(n_components=2, copy=False, random_state=42)\n', (18109, 18154), False, 'from sklearn.decomposition import PCA\n'), ((21794, 21819), 'numpy.concatenate', 'np.concatenate', (['to_return'], {}), '(to_return)\n', (21808, 21819), True, 'import numpy as np\n'), ((8816, 8843), 'os.makedirs', 'os.makedirs', (['self.plots_dir'], {}), '(self.plots_dir)\n', (8827, 8843), False, 'import os\n'), ((12179, 12207), 'ava.models.vae_dataset.get_hdf5s_from_dir', 'get_hdf5s_from_dir', (['spec_dir'], {}), '(spec_dir)\n', (12197, 12207), False, 'from ava.models.vae_dataset import get_syllable_partition, get_syllable_data_loaders, get_hdf5s_from_dir\n'), ((14950, 14975), 'h5py.File', 'h5py.File', (['hdf5_file', '"""r"""'], {}), "(hdf5_file, 'r')\n", (14959, 14975), False, 'import h5py\n'), ((15127, 15152), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (15150, 15152), False, 'import torch\n'), ((15174, 15227), 'torch.load', 'torch.load', (['self.model_filename'], {'map_location': 'map_loc'}), '(self.model_filename, map_location=map_loc)\n', (15184, 15227), False, 'import torch\n'), ((15648, 15700), 'ava.models.vae_dataset.get_syllable_partition', 'get_syllable_partition', (['[spec_dir]', '(1)'], {'shuffle': '(False)'}), '([spec_dir], 1, shuffle=False)\n', (15670, 15700), False, 'from ava.models.vae_dataset import get_syllable_partition, get_syllable_data_loaders, get_hdf5s_from_dir\n'), ((17575, 17600), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {}), '()\n', (17598, 17600), False, 'import warnings\n'), ((19631, 19659), 'ava.models.vae_dataset.get_hdf5s_from_dir', 'get_hdf5s_from_dir', (['spec_dir'], {}), '(spec_dir)\n', (19649, 19659), False, 'from ava.models.vae_dataset import get_syllable_partition, get_syllable_data_loaders, get_hdf5s_from_dir\n'), ((22119, 22147), 'ava.models.vae_dataset.get_hdf5s_from_dir', 'get_hdf5s_from_dir', (['spec_dir'], {}), '(spec_dir)\n', (22137, 22147), False, 'from ava.models.vae_dataset import get_syllable_partition, get_syllable_data_loaders, get_hdf5s_from_dir\n'), ((23003, 23042), 'os.path.exists', 'os.path.exists', (['self.projection_dirs[0]'], {}), '(self.projection_dirs[0])\n', (23017, 23042), False, 'import os\n'), ((24201, 24278), 'numpy.loadtxt', 'np.loadtxt', (['filename'], {'delimiter': 'delimiter', 'usecols': 'columns', 'skiprows': 'skiprows'}), '(filename, delimiter=delimiter, usecols=columns, skiprows=skiprows)\n', (24211, 24278), True, 'import numpy as np\n'), ((8781, 8811), 'os.path.exists', 'os.path.exists', (['self.plots_dir'], {}), '(self.plots_dir)\n', (8795, 8811), False, 'import os\n'), ((9787, 9811), 'os.path.exists', 'os.path.exists', (['proj_dir'], {}), '(proj_dir)\n', (9801, 9811), False, 'import os\n'), ((9836, 9861), 'os.path.join', 'os.path.join', (['proj_dir', 'i'], {}), '(proj_dir, i)\n', (9848, 9861), False, 'import os\n'), ((9977, 9990), 'os.remove', 'os.remove', (['fn'], {}), '(fn)\n', (9986, 9990), False, 'import os\n'), ((14008, 14032), 'os.path.join', 'os.path.join', (['seg_dir', 'i'], {}), '(seg_dir, i)\n', (14020, 14032), False, 'import os\n'), ((15569, 15590), 'os.makedirs', 'os.makedirs', (['proj_dir'], {}), '(proj_dir)\n', (15580, 15590), False, 'import os\n'), ((15993, 16021), 'ava.models.vae_dataset.get_hdf5s_from_dir', 'get_hdf5s_from_dir', (['spec_dir'], {}), '(spec_dir)\n', (16011, 16021), False, 'from ava.models.vae_dataset import get_syllable_partition, get_syllable_data_loaders, get_hdf5s_from_dir\n'), ((16891, 16931), 'time.strptime', 'strptime', (['"""1899 12 29 19"""', '"""%Y %m %d %H"""'], {}), "('1899 12 29 19', '%Y %m %d %H')\n", (16899, 16931), False, 'from time import strptime, mktime\n'), ((17614, 17681), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {'category': 'NumbaPerformanceWarning'}), "('ignore', category=NumbaPerformanceWarning)\n", (17637, 17681), False, 'import warnings\n'), ((23056, 23099), 'ava.models.vae_dataset.get_hdf5s_from_dir', 'get_hdf5s_from_dir', (['self.projection_dirs[0]'], {}), '(self.projection_dirs[0])\n', (23074, 23099), False, 'from ava.models.vae_dataset import get_syllable_partition, get_syllable_data_loaders, get_hdf5s_from_dir\n'), ((9871, 9891), 'os.listdir', 'os.listdir', (['proj_dir'], {}), '(proj_dir)\n', (9881, 9891), False, 'import os\n'), ((12316, 12340), 'h5py.File', 'h5py.File', (['filename', '"""r"""'], {}), "(filename, 'r')\n", (12325, 12340), False, 'import h5py\n'), ((13004, 13025), 'os.listdir', 'os.listdir', (['audio_dir'], {}), '(audio_dir)\n', (13014, 13025), False, 'import os\n'), ((13140, 13173), 'os.path.join', 'os.path.join', (['audio_dir', 'audio_fn'], {}), '(audio_dir, audio_fn)\n', (13152, 13173), False, 'import os\n'), ((14042, 14061), 'os.listdir', 'os.listdir', (['seg_dir'], {}), '(seg_dir)\n', (14052, 14061), False, 'import os\n'), ((15539, 15563), 'os.path.exists', 'os.path.exists', (['proj_dir'], {}), '(proj_dir)\n', (15553, 15563), False, 'import os\n'), ((15722, 15782), 'ava.models.vae_dataset.get_syllable_data_loaders', 'get_syllable_data_loaders', (['partition'], {'shuffle': '(False, False)'}), '(partition, shuffle=(False, False))\n', (15747, 15782), False, 'from ava.models.vae_dataset import get_syllable_partition, get_syllable_data_loaders, get_hdf5s_from_dir\n'), ((19777, 19797), 'h5py.File', 'h5py.File', (['hdf5', '"""r"""'], {}), "(hdf5, 'r')\n", (19786, 19797), False, 'import h5py\n'), ((19827, 19857), 'numpy.array', 'np.array', (["f['audio_filenames']"], {}), "(f['audio_filenames'])\n", (19835, 19857), True, 'import numpy as np\n'), ((19877, 19898), 'numpy.array', 'np.array', (["f['onsets']"], {}), "(f['onsets'])\n", (19885, 19898), True, 'import numpy as np\n'), ((21648, 21672), 'h5py.File', 'h5py.File', (['write_fn', '"""a"""'], {}), "(write_fn, 'a')\n", (21657, 21672), False, 'import h5py\n'), ((22295, 22319), 'h5py.File', 'h5py.File', (['filename', '"""a"""'], {}), "(filename, 'a')\n", (22304, 22319), False, 'import h5py\n'), ((23152, 23172), 'os.path.exists', 'os.path.exists', (['hdf5'], {}), '(hdf5)\n', (23166, 23172), False, 'import os\n'), ((12282, 12301), 'os.path.split', 'os.path.split', (['hdf5'], {}), '(hdf5)\n', (12295, 12301), False, 'import os\n'), ((16224, 16248), 'h5py.File', 'h5py.File', (['filename', '"""a"""'], {}), "(filename, 'a')\n", (16233, 16248), False, 'import h5py\n'), ((20530, 20567), 'os.path.join', 'os.path.join', (['feature_dir', 'feature_fn'], {}), '(feature_dir, feature_fn)\n', (20542, 20567), False, 'import os\n'), ((21614, 21633), 'os.path.split', 'os.path.split', (['hdf5'], {}), '(hdf5)\n', (21627, 21633), False, 'import os\n'), ((22217, 22240), 'os.path.split', 'os.path.split', (['hdf5s[j]'], {}), '(hdf5s[j])\n', (22230, 22240), False, 'import os\n'), ((12603, 12621), 'numpy.array', 'np.array', (['f[field]'], {}), '(f[field])\n', (12611, 12621), True, 'import numpy as np\n'), ((14104, 14120), 'os.path.split', 'os.path.split', (['i'], {}), '(i)\n', (14117, 14120), False, 'import os\n'), ((16143, 16166), 'os.path.split', 'os.path.split', (['hdf5s[j]'], {}), '(hdf5s[j])\n', (16156, 16166), False, 'import os\n'), ((21319, 21341), 'numpy.min', 'np.min', (['feature_onsets'], {}), '(feature_onsets)\n', (21325, 21341), True, 'import numpy as np\n'), ((21361, 21383), 'numpy.max', 'np.max', (['feature_onsets'], {}), '(feature_onsets)\n', (21367, 21383), True, 'import numpy as np\n'), ((23185, 23205), 'h5py.File', 'h5py.File', (['hdf5', '"""r"""'], {}), "(hdf5, 'r')\n", (23194, 23205), False, 'import h5py\n'), ((20331, 20354), 'os.path.split', 'os.path.split', (['audio_fn'], {}), '(audio_fn)\n', (20344, 20354), False, 'import os\n'), ((16943, 16960), 'os.path.split', 'os.path.split', (['fn'], {}), '(fn)\n', (16956, 16960), False, 'import os\n')]
import os import sys import logging as log import numpy as np import cv2 from openvino.inference_engine import IENetwork, IECore class ModelDetection: ''' Class for the Face Detection Model. ''' def __init__(self, model_name, device='CPU', extensions=None, threshold=0.5): self.threshold = threshold self.model_name = model_name self.device = device self.extensions = extensions def load_model(self): ## Get model_bin and model_xml model_bin = self.model_name + ".bin" model_xml = self.model_name + ".xml" plugin = IECore() network = IENetwork(model=model_xml, weights=model_bin) ## Add extension if any if self.extensions and "CPU" in self.device: # Add a CPU extension, if applicable plugin.add_extension(self.extensions, self.device) ## (Additional) Check unsupported layer supported_layers = plugin.query_network(network=network, device_name=self.device) unsupported_layers = [l for l in network.layers.keys() if l not in supported_layers] if len(unsupported_layers) > 2: print("Unsupported layers found: {}".format(unsupported_layers)) print("Check whether extensions are available to add to IECore.") exit(1) ## Load network self.exec_network = plugin.load_network(network, self.device) self.input_blob = next(iter(network.inputs)) self.output_blob = next(iter(network.outputs)) self.n, self.c, self.h, self.w = network.inputs[self.input_blob].shape self.plugin = plugin self.network = network def predict(self, image): frame_shape = image.shape image = self.preprocess_input(image) self.exec_network.requests[0].infer({self.input_blob: image}) outputs = self.exec_network.requests[0].outputs[self.output_blob] self.outputs = outputs boxes, scores = self.preprocess_output(outputs, frame_shape) return boxes, scores def check_model(self): raise NotImplementedError def preprocess_input(self, image): img = cv2.dnn.blobFromImage(image, size=(self.w, self.h)) return img def preprocess_output(self, outputs, frame_shape): img_h, img_w, _ = frame_shape boxes = [] scores = [] res = outputs people = res[0][:, np.where((res[0][0][:, 2] > self.threshold))] for person in people[0][0]: box = person[3:7] * np.array([img_w, img_h, img_w, img_h]) box = int(box[0]), int(box[1]), int(box[2]), int(box[3]) boxes.append(box) scores.append(person[2]) return boxes, scores
[ "openvino.inference_engine.IENetwork", "openvino.inference_engine.IECore", "cv2.dnn.blobFromImage", "numpy.where", "numpy.array" ]
[((601, 609), 'openvino.inference_engine.IECore', 'IECore', ([], {}), '()\n', (607, 609), False, 'from openvino.inference_engine import IENetwork, IECore\n'), ((628, 673), 'openvino.inference_engine.IENetwork', 'IENetwork', ([], {'model': 'model_xml', 'weights': 'model_bin'}), '(model=model_xml, weights=model_bin)\n', (637, 673), False, 'from openvino.inference_engine import IENetwork, IECore\n'), ((2218, 2269), 'cv2.dnn.blobFromImage', 'cv2.dnn.blobFromImage', (['image'], {'size': '(self.w, self.h)'}), '(image, size=(self.w, self.h))\n', (2239, 2269), False, 'import cv2\n'), ((2471, 2513), 'numpy.where', 'np.where', (['(res[0][0][:, 2] > self.threshold)'], {}), '(res[0][0][:, 2] > self.threshold)\n', (2479, 2513), True, 'import numpy as np\n'), ((2585, 2623), 'numpy.array', 'np.array', (['[img_w, img_h, img_w, img_h]'], {}), '([img_w, img_h, img_w, img_h])\n', (2593, 2623), True, 'import numpy as np\n')]
# Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utilities for running predictions. Includes (from the Cloud ML SDK): - _predict_lib Important changes: - Remove interfaces for TensorFlowModel (they don't change behavior). - Set from_client(skip_preprocessing=True) and remove the pre-processing code. """ import __builtin__ import base64 import collections from contextlib import contextmanager import importlib import inspect import json import logging import os import pickle import pydoc # used for importing python classes from their FQN import StringIO import timeit from _interfaces import Model from _interfaces import PredictionClient from enum import Enum import numpy as np from tensorflow.python.client import session as tf_session from tensorflow.python.framework import dtypes from tensorflow.python.saved_model import loader from tensorflow.python.saved_model import signature_constants from tensorflow.python.saved_model import tag_constants # -------------------------- # prediction.prediction_lib # -------------------------- class UserClassType(Enum): model_class = "model_class" processor_class = "processor_class" ENGINE = "Prediction-Engine" ENGINE_RUN_TIME = "Prediction-Engine-Run-Time" FRAMEWORK = "Framework" SCIKIT_LEARN_FRAMEWORK_NAME = "scikit_learn" XGBOOST_FRAMEWORK_NAME = "xgboost" TENSORFLOW_FRAMEWORK_NAME = "tensorflow" PREPROCESS_TIME = "Prediction-Preprocess-Time" POSTPROCESS_TIME = "Prediction-Postprocess-Time" # Keys for the name of the methods that the user provided `Processor` # class should implement. PREPROCESS_KEY = "preprocess" POSTPROCESS_KEY = "postprocess" FROM_MODEL_KEY = "from_model_path" # Additional TF keyword arguments INPUTS_KEY = "inputs" OUTPUTS_KEY = "outputs" SIGNATURE_KEY = "signature_name" # Stats COLUMNARIZE_TIME = "Prediction-Columnarize-Time" UNALIAS_TIME = "Prediction-Unalias-Time" ENCODE_TIME = "Prediction-Encode-Time" SESSION_RUN_TIME = "Prediction-Session-Run-Time" ALIAS_TIME = "Prediction-Alias-Time" ROWIFY_TIME = "Prediction-Rowify-Time" # TODO(b/67586901): Consider removing INPUT_PROCESSING_TIME during cleanup. SESSION_RUN_ENGINE_NAME = "TF_SESSION_RUN" # Scikit-learn and XGBoost related constants MODEL_FILE_NAME_JOBLIB = "model.joblib" MODEL_FILE_NAME_PICKLE = "model.pkl" MODEL_FILE_NAME_BST = "model.bst" PredictionErrorType = collections.namedtuple( "PredictionErrorType", ("message", "code")) class PredictionError(Exception): """Customer exception for known prediction exception.""" # The error code for prediction. FAILED_TO_LOAD_MODEL = PredictionErrorType( message="Failed to load model", code=0) INVALID_INPUTS = PredictionErrorType("Invalid inputs", code=1) FAILED_TO_RUN_MODEL = PredictionErrorType( message="Failed to run the provided model", code=2) INVALID_OUTPUTS = PredictionErrorType( message="There was a problem processing the outputs", code=3) INVALID_USER_CODE = PredictionErrorType( message="There was a problem processing the user code", code=4) # When adding new exception, please update the ERROR_MESSAGE_ list as well as # unittest. def __init__(self, error_code, error_detail, *args): super(PredictionError, self).__init__(error_code, error_detail, *args) @property def error_code(self): return self.args[0].code @property def error_message(self): return self.args[0].message @property def error_detail(self): return self.args[1] def __str__(self): return ("%s: %s (Error code: %d)" % (self.error_message, self.error_detail, self.error_code)) MICRO = 1000000 MILLI = 1000 class Timer(object): """Context manager for timing code blocks. The object is intended to be used solely as a context manager and not as a general purpose object. The timer starts when __enter__ is invoked on the context manager and stopped when __exit__ is invoked. After __exit__ is called, the duration properties report the amount of time between __enter__ and __exit__ and thus do not change. However, if any of the duration properties are called between the call to __enter__ and __exit__, then they will return the "live" value of the timer. If the same Timer object is re-used in multiple with statements, the values reported will reflect the latest call. Do not use the same Timer object in nested with blocks with the same Timer context manager. Example usage: with Timer() as timer: foo() print(timer.duration_secs) """ def __init__(self, timer_fn=None): self.start = None self.end = None self._get_time = timer_fn or timeit.default_timer def __enter__(self): self.end = None self.start = self._get_time() return self def __exit__(self, exc_type, value, traceback): self.end = self._get_time() return False @property def seconds(self): now = self._get_time() return (self.end or now) - (self.start or now) @property def microseconds(self): return int(MICRO * self.seconds) @property def milliseconds(self): return int(MILLI * self.seconds) class Stats(dict): """An object for tracking stats. This class is dict-like, so stats are accessed/stored like so: stats = Stats() stats["count"] = 1 stats["foo"] = "bar" This class also facilitates collecting timing information via the context manager obtained using the "time" method. Reported timings are in microseconds. Example usage: with stats.time("foo_time"): foo() print(stats["foo_time"]) """ @contextmanager def time(self, name, timer_fn=None): with Timer(timer_fn) as timer: yield timer self[name] = timer.microseconds def columnarize(instances): """Columnarize inputs. Each line in the input is a dictionary of input names to the value for that input (a single instance). For each input "column", this method appends each of the input values to a list. The result is a dict mapping input names to a batch of input data. This can be directly used as the feed dict during prediction. For example, instances = [{"a": [1.0, 2.0], "b": "a"}, {"a": [3.0, 4.0], "b": "c"}, {"a": [5.0, 6.0], "b": "e"},] batch = prediction_server_lib.columnarize(instances) assert batch == {"a": [[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]], "b": ["a", "c", "e"]} Arguments: instances: (list of dict) where the dictionaries map input names to the values for those inputs. Returns: A dictionary mapping input names to values, as described above. """ columns = collections.defaultdict(list) for instance in instances: for k, v in instance.iteritems(): columns[k].append(v) return columns def rowify(columns): """Converts columnar input to row data. Consider the following code: columns = {"prediction": np.array([1, # 1st instance 0, # 2nd 1]), # 3rd "scores": np.array([[0.1, 0.9], # 1st instance [0.7, 0.3], # 2nd [0.4, 0.6]])} # 3rd Then rowify will return the equivalent of: [{"prediction": 1, "scores": [0.1, 0.9]}, {"prediction": 0, "scores": [0.7, 0.3]}, {"prediction": 1, "scores": [0.4, 0.6]}] (each row is yielded; no list is actually created). Arguments: columns: (dict) mapping names to numpy arrays, where the arrays contain a batch of data. Raises: PredictionError: if the outer dimension of each input isn't identical for each of element. Yields: A map with a single instance, as described above. Note: instances is not a numpy array. """ sizes_set = {e.shape[0] for e in columns.itervalues()} # All the elements in the length array should be identical. Otherwise, # raise an exception. if len(sizes_set) != 1: sizes_dict = {name: e.shape[0] for name, e in columns.iteritems()} raise PredictionError( PredictionError.INVALID_OUTPUTS, "Bad output from running tensorflow session: outputs had differing " "sizes in the batch (outer) dimension. See the outputs and their " "size: %s. Check your model for bugs that effect the size of the " "outputs." % sizes_dict) # Pick an arbitrary value in the map to get it's size. num_instances = len(next(columns.itervalues())) for row in xrange(num_instances): yield {name: output[row, ...].tolist() for name, output in columns.iteritems()} def canonicalize_single_tensor_input(instances, tensor_name): """Canonicalize single input tensor instances into list of dicts. Instances that are single input tensors may or may not be provided with their tensor name. The following are both valid instances: 1) instances = [{"x": "a"}, {"x": "b"}, {"x": "c"}] 2) instances = ["a", "b", "c"] This function canonicalizes the input instances to be of type 1). Arguments: instances: single input tensor instances as supplied by the user to the predict method. tensor_name: the expected name of the single input tensor. Raises: PredictionError: if the wrong tensor name is supplied to instances. Returns: A list of dicts. Where each dict is a single instance, mapping the tensor_name to the value (as supplied by the original instances). """ # Input is a single string tensor, the tensor name might or might not # be given. # There are 3 cases (assuming the tensor name is "t", tensor = "abc"): # 1) {"t": "abc"} # 2) "abc" # 3) {"y": ...} --> wrong tensor name is given. def parse_single_tensor(x, tensor_name): if not isinstance(x, dict): # case (2) return {tensor_name: x} elif len(x) == 1 and tensor_name == x.keys()[0]: # case (1) return x else: raise PredictionError(PredictionError.INVALID_INPUTS, "Expected tensor name: %s, got tensor name: %s." % (tensor_name, x.keys())) if not isinstance(instances, list): instances = [instances] instances = [parse_single_tensor(x, tensor_name) for x in instances] return instances class BaseModel(Model): """The base definition of an internal Model interface. """ def __init__(self, client): """Constructs a BaseModel. Args: client: An instance of PredictionClient for performing prediction. """ self._client = client self._user_processor = None def preprocess(self, instances, stats=None, **kwargs): """Runs the preprocessing function on the instances. Args: instances: list of instances as provided to the predict() method. stats: Stats object for recording timing information. **kwargs: Additional keyword arguments for preprocessing. Returns: A new list of preprocessed instances. Each instance is as described in the predict() method. """ pass def postprocess(self, predicted_output, original_input=None, stats=None, **kwargs): """Runs the postprocessing function on the instances. Args: predicted_output: list of instances returned by the predict() method on preprocessed instances. original_input: List of instances, before any pre-processing was applied. stats: Stats object for recording timing information. **kwargs: Additional keyword arguments for postprocessing. Returns: A new list of postprocessed instances. """ pass def predict(self, instances, stats=None, **kwargs): """Runs preprocessing, predict, and postprocessing on the input.""" stats = stats or Stats() self._validate_kwargs(kwargs) with stats.time(PREPROCESS_TIME): preprocessed = self.preprocess(instances, stats=stats, **kwargs) with stats.time(ENGINE_RUN_TIME): predicted_outputs = self._client.predict( preprocessed, stats=stats, **kwargs) with stats.time(POSTPROCESS_TIME): postprocessed = self.postprocess( predicted_outputs, original_input=instances, stats=stats, **kwargs) return instances, postprocessed def _validate_kwargs(self, kwargs): """Validates and sets defaults for extra predict keyword arguments. Modifies the keyword args dictionary in-place. Keyword args will be included into pre/post-processing and the client predict method. Can raise Exception to error out of request on bad keyword args. If no additional args are required, pass. Args: kwargs: Dictionary (str->str) of keyword arguments to check. """ pass # TODO(b/34686738): when we no longer load the model to get the signature # consider making this a named constructor on SessionClient. def load_model( model_path, tags=(tag_constants.SERVING,), config=None): """Loads the model at the specified path. Args: model_path: the path to either session_bundle or SavedModel tags: the tags that determines the model to load. config: tf.ConfigProto containing session configuration options. Returns: A pair of (Session, map<string, SignatureDef>) objects. Raises: PredictionError: if the model could not be loaded. """ if loader.maybe_saved_model_directory(model_path): try: logging.info("Importing tensorflow.contrib in load_model") import tensorflow.contrib # pylint: disable=redefined-outer-name, unused-variable, g-import-not-at-top session = tf_session.Session(target="", graph=None, config=config) meta_graph = loader.load(session, tags=list(tags), export_dir=model_path) except Exception as e: # pylint: disable=broad-except raise PredictionError(PredictionError.FAILED_TO_LOAD_MODEL, "Failed to load the model due to bad model data." " tags: %s\n%s" % (list(tags), str(e))) else: raise PredictionError(PredictionError.FAILED_TO_LOAD_MODEL, "Cloud ML only supports TF 1.0 or above and models " "saved in SavedModel format.") if session is None: raise PredictionError(PredictionError.FAILED_TO_LOAD_MODEL, "Failed to create session when loading the model") if not meta_graph.signature_def: raise PredictionError(PredictionError.FAILED_TO_LOAD_MODEL, "MetaGraph must have at least one signature_def.") # Remove invalid signatures from the signature map. invalid_signatures = [] for signature_name in meta_graph.signature_def: try: signature = meta_graph.signature_def[signature_name] _update_dtypes(session.graph, signature.inputs) _update_dtypes(session.graph, signature.outputs) except ValueError as e: logging.warn("Error updating signature %s: %s", signature_name, str(e)) invalid_signatures.append(signature_name) for signature_name in invalid_signatures: del meta_graph.signature_def[signature_name] return session, meta_graph.signature_def def _update_dtypes(graph, interface): """Adds dtype to TensorInfos in interface if necessary. If already present, validates TensorInfo matches values in the graph. TensorInfo is updated in place. Args: graph: the TensorFlow graph; used to lookup datatypes of tensors. interface: map from alias to TensorInfo object. Raises: ValueError: if the data type in the TensorInfo does not match the type found in graph. """ for alias, info in interface.iteritems(): # Postpone conversion to enum for better error messages. dtype = graph.get_tensor_by_name(info.name).dtype if not info.dtype: info.dtype = dtype.as_datatype_enum elif info.dtype != dtype.as_datatype_enum: raise ValueError("Specified data types do not match for alias %s. " "Graph has %d while TensorInfo reports %d." % (alias, dtype, info.dtype)) # (TODO:b/68775232): Move this to a Tensorflow specific library. class TensorFlowClient(PredictionClient): """A client for Prediction that uses Session.run.""" def __init__(self, signature_map, *args, **kwargs): self._signature_map = signature_map super(TensorFlowClient, self).__init__(*args, **kwargs) @property def signature_map(self): return self._signature_map def get_signature(self, signature_name=None): """Gets tensorflow signature for the given signature_name. Args: signature_name: string The signature name to use to choose the signature from the signature map. Returns: a pair of signature_name and signature. The first element is the signature name in string that is actually used. The second one is the signature. Raises: PredictionError: when the signature is not found with the given signature name or when there are more than one signatures in the signature map. """ # The way to find signature is: # 1) if signature_name is specified, try to find it in the signature_map. If # not found, raise an exception. # 2) if signature_name is not specified, check if signature_map only # contains one entry. If so, return the only signature. # 3) Otherwise, use the default signature_name and do 1). if not signature_name and len(self.signature_map) == 1: return self.signature_map.keys()[0], self.signature_map.values()[0] key = (signature_name or signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY) if key in self.signature_map: return key, self.signature_map[key] else: raise PredictionError( PredictionError.INVALID_INPUTS, "No signature found for signature key %s." % signature_name) # (TODO:b/68775232): Move this to a Tensorflow specific library. class SessionClient(TensorFlowClient): """A client for Prediction that uses Session.run.""" def __init__(self, session, signature_map): self._session = session super(SessionClient, self).__init__(signature_map) def predict(self, inputs, stats=None, signature_name=None, **unused_kwargs): """Produces predictions for the given inputs. Args: inputs: a dict mapping input names to values stats: Stats object for recording timing information. signature_name: name of SignatureDef to use in this prediction **unused_kwargs: placeholder, pre/postprocess may have additional args Returns: A dict mapping output names to output values, similar to the input dict. """ stats = stats or Stats() stats[ENGINE] = "SessionRun" stats[FRAMEWORK] = TENSORFLOW_FRAMEWORK_NAME with stats.time(UNALIAS_TIME): _, signature = self.get_signature(signature_name) fetches = [output.name for output in signature.outputs.values()] try: unaliased = {signature.inputs[key].name: val for key, val in inputs.iteritems()} except Exception as e: raise PredictionError(PredictionError.INVALID_INPUTS, "Input mismatch: " + str(e)) with stats.time(SESSION_RUN_TIME): try: # TODO(b/33849399): measure the actual session.run() time, even in the # case of ModelServer. outputs = self._session.run(fetches=fetches, feed_dict=unaliased) except Exception as e: logging.error("Exception during running the graph: " + str(e)) raise PredictionError(PredictionError.FAILED_TO_RUN_MODEL, "Exception during running the graph: " + str(e)) with stats.time(ALIAS_TIME): return dict(zip(signature.outputs.iterkeys(), outputs)) def load_model_class(client, model_path): """Loads in the user specified custom Model class. Args: client: An instance of ModelServerClient for performing prediction. model_path: the path to either session_bundle or SavedModel Returns: An instance of a Model. Returns None if the user didn't specify the name of the custom python class to load in the create_version_request. Raises: PredictionError: for any of the following: (1) the user provided python model class cannot be found (2) if the loaded class does not implement the Model interface. """ model_class = load_custom_class(UserClassType.model_class) if not model_class: return None model_instance = model_class.from_client(client, model_path) _validate_model_class(model_instance) return model_instance def load_custom_class(class_type): """Loads in the user specified custom class. Args: class_type: An instance of UserClassType specifying what type of class to load. Returns: An instance of a class specified by the user in the `create_version_request` or None if no such class was specified. Raises: PredictionError: if the user provided python class cannot be found. """ create_version_json = os.environ.get("create_version_request") if not create_version_json: return None create_version_request = json.loads(create_version_json) if not create_version_request: return None version = create_version_request.get("version") if not version: return None class_name = version.get(class_type.name) if not class_name: return None custom_class = pydoc.locate(class_name) # TODO(b/37749453): right place to generate errors? if not custom_class: package_uris = [str(s) for s in version.get("package_uris")] raise PredictionError(PredictionError.INVALID_USER_CODE, "%s cannot be found. Please make sure " "(1) %s is the fully qualified function " "name, and (2) %s uses the correct package " "name as provided by the package_uris: %s" % (class_name, class_type.name, class_type.name, package_uris)) return custom_class def _validate_model_class(user_class): """Validates a user provided instance of a Model implementation. Args: user_class: An instance of a Model implementation. Raises: PredictionError: for any of the following: (1) the user model class does not have the correct method signatures for the predict method """ user_class_name = type(user_class).__name__ # Can't use isinstance() because the user doesn't have access to our Model # class. We can only inspect the user_class to check if it conforms to the # Model interface. if not hasattr(user_class, "predict"): raise PredictionError(PredictionError.INVALID_USER_CODE, "The provided model class, %s, is missing the " "required predict method." % user_class_name) # Check the predict method has the correct number of arguments user_signature = inspect.getargspec(user_class.predict)[0] model_signature = inspect.getargspec(Model.predict)[0] user_predict_num_args = len(user_signature) predict_num_args = len(model_signature) if predict_num_args is not user_predict_num_args: raise PredictionError(PredictionError.INVALID_USER_CODE, "The provided model class, %s, has a predict method " "with an invalid signature. Expected signature: %s " "User signature: %s" % (user_class_name, model_signature, user_signature)) # TODO(user): Make this generic so it can load any Processor class, not just # from the create_version_request. def _new_processor_class(model_path=None): user_processor_cls = load_custom_class(UserClassType.processor_class) if user_processor_cls: user_preprocess_fn = getattr(user_processor_cls, PREPROCESS_KEY, None) user_postprocess_fn = getattr(user_processor_cls, POSTPROCESS_KEY, None) user_from_model_path_fn = getattr(user_processor_cls, FROM_MODEL_KEY, None) _validate_fn_signature(user_preprocess_fn, ["self", "instances"], PREPROCESS_KEY, user_processor_cls.__name__) _validate_fn_signature(user_postprocess_fn, ["self", "instances"], POSTPROCESS_KEY, user_processor_cls.__name__) _validate_fn_signature(user_from_model_path_fn, ["cls", "model_path"], FROM_MODEL_KEY, user_processor_cls.__name__) if user_from_model_path_fn: return user_from_model_path_fn(model_path) # pylint: disable=not-callable # Call the constructor if no `from_model_path` method provided. return user_processor_cls() def _validate_fn_signature(fn, required_arg_names, expected_fn_name, cls_name): if not fn: return if not callable(fn): raise PredictionError( PredictionError.INVALID_USER_CODE, "The provided %s function in the Processor class " "%s is not callable." % (expected_fn_name, cls_name)) for arg in required_arg_names: if arg not in inspect.getargspec(fn).args: raise PredictionError( PredictionError.INVALID_USER_CODE, "The provided %s function in the Processor class " "has an invalid signature. It should take %s as arguments but " "takes %s" % (fn.__name__, required_arg_names, inspect.getargspec(fn).args)) # (TODO:b/68775232): Move this to a Tensorflow specific library. class TensorFlowModel(BaseModel): """The default implementation of the Model interface that uses TensorFlow. This implementation optionally performs preprocessing and postprocessing using the provided functions. These functions accept a single instance as input and produce a corresponding output to send to the prediction client. """ def __init__(self, client): """Constructs a TensorFlowModel. Args: client: An instance of ModelServerClient or SessionClient. """ super(TensorFlowModel, self).__init__(client) self._preprocess_fn = None self._postprocess_fn = None processor_cls = _new_processor_class() if processor_cls: self._preprocess_fn = getattr(processor_cls, PREPROCESS_KEY, None) self._postprocess_fn = getattr(processor_cls, POSTPROCESS_KEY, None) def _get_columns(self, instances, stats, signature): """Columnarize the instances, appending input_name, if necessary. Instances are the same instances passed to the predict() method. Since models with a single input can accept the raw input without the name, we create a dict here with that name. This list of instances is then converted into a column-oriented format: The result is a dictionary mapping input name to a list of values for just that input (one entry per row in the original instances list). Args: instances: the list of instances as provided to the predict() method. stats: Stats object for recording timing information. signature: SignatureDef for the current request. Returns: A dictionary mapping input names to their values. Raises: PredictionError: if an error occurs during prediction. """ with stats.time(COLUMNARIZE_TIME): columns = columnarize(instances) for k, v in columns.iteritems(): if k not in signature.inputs.keys(): raise PredictionError( PredictionError.INVALID_INPUTS, "Unexpected tensor name: %s" % k) # Detect whether or not the user omits an input in one or more inputs. # TODO(b/34686738): perform this check in columnarize? if isinstance(v, list) and len(v) != len(instances): raise PredictionError( PredictionError.INVALID_INPUTS, "Input %s was missing in at least one input instance." % k) return columns # TODO(b/34686738): can this be removed? def is_single_input(self, signature): """Returns True if the graph only has one input tensor.""" return len(signature.inputs) == 1 # TODO(b/34686738): can this be removed? def is_single_string_input(self, signature): """Returns True if the graph only has one string input tensor.""" if self.is_single_input(signature): dtype = signature.inputs.values()[0].dtype return dtype == dtypes.string.as_datatype_enum return False def get_signature(self, signature_name=None): return self._client.get_signature(signature_name) def preprocess(self, instances, stats=None, signature_name=None, **kwargs): _, signature = self.get_signature(signature_name) preprocessed = self._canonicalize_input(instances, signature) if self._preprocess_fn: try: preprocessed = self._preprocess_fn(preprocessed, **kwargs) except Exception as e: logging.error("Exception during preprocessing: " + str(e)) raise PredictionError(PredictionError.INVALID_INPUTS, "Exception during preprocessing: " + str(e)) return self._get_columns(preprocessed, stats, signature) def _canonicalize_input(self, instances, signature): """Preprocess single-input instances to be dicts if they aren't already.""" # The instances should be already (b64-) decoded here. if not self.is_single_input(signature): return instances tensor_name = signature.inputs.keys()[0] return canonicalize_single_tensor_input(instances, tensor_name) def postprocess(self, predicted_output, original_input=None, stats=None, signature_name=None, **kwargs): """Performs the necessary transformations on the prediction results. The transformations include rowifying the predicted results, and also making sure that each input/output is a dict mapping input/output alias to the value for that input/output. Args: predicted_output: list of instances returned by the predict() method on preprocessed instances. original_input: List of instances, before any pre-processing was applied. stats: Stats object for recording timing information. signature_name: the signature name to find out the signature. **kwargs: Additional keyword arguments for postprocessing Returns: A list which is a dict mapping output alias to the output. """ _, signature = self.get_signature(signature_name) with stats.time(ROWIFY_TIME): # When returned element only contains one result (batch size == 1), # tensorflow's session.run() will return a scalar directly instead of a # a list. So we need to listify that scalar. # TODO(b/34686738): verify this behavior is correct. def listify(value): if not hasattr(value, "shape"): return np.asarray([value], dtype=np.object) elif not value.shape: # TODO(b/34686738): pretty sure this is a bug that only exists because # samples like iris have a bug where they use tf.squeeze which removes # the batch dimension. The samples should be fixed. return np.expand_dims(value, axis=0) else: return value postprocessed_outputs = { alias: listify(val) for alias, val in predicted_output.iteritems() } postprocessed_outputs = rowify(postprocessed_outputs) postprocessed_outputs = list(postprocessed_outputs) if self._postprocess_fn: try: postprocessed_outputs = self._postprocess_fn(postprocessed_outputs, **kwargs) except Exception as e: logging.error("Exception during postprocessing: %s", e) raise PredictionError(PredictionError.INVALID_INPUTS, "Exception during postprocessing: " + str(e)) with stats.time(ENCODE_TIME): try: postprocessed_outputs = encode_base64( postprocessed_outputs, signature.outputs) except PredictionError as e: logging.error("Encode base64 failed: %s", e) raise PredictionError(PredictionError.INVALID_OUTPUTS, "Prediction failed during encoding instances: {0}" .format(e.error_detail)) except ValueError as e: logging.error("Encode base64 failed: %s", e) raise PredictionError(PredictionError.INVALID_OUTPUTS, "Prediction failed during encoding instances: {0}" .format(e)) except Exception as e: # pylint: disable=broad-except logging.error("Encode base64 failed: %s", e) raise PredictionError(PredictionError.INVALID_OUTPUTS, "Prediction failed during encoding instances") return postprocessed_outputs @classmethod def from_client(cls, client, unused_model_path, **unused_kwargs): """Creates a TensorFlowModel from a SessionClient and model data files.""" return cls(client) @property def signature_map(self): return self._client.signature_map # This class is specific to Scikit-learn, and should be moved to a separate # module. However due to gcloud's complicated copying mechanism we need to keep # things in one file for now. class SklearnClient(PredictionClient): """A loaded scikit-learn model to be used for prediction.""" def __init__(self, predictor): self._predictor = predictor def predict(self, inputs, stats=None, **kwargs): stats = stats or Stats() stats[FRAMEWORK] = SCIKIT_LEARN_FRAMEWORK_NAME stats[ENGINE] = SCIKIT_LEARN_FRAMEWORK_NAME try: return self._predictor.predict(inputs, **kwargs) except Exception as e: logging.exception("Exception while predicting with sklearn model.") raise PredictionError(PredictionError.FAILED_TO_RUN_MODEL, "Exception during sklearn prediction: " + str(e)) # (TODO:b/68775232) This class is specific to Xgboost, and should be moved to a # separate module. However due to gcloud's complicated copying mechanism we need # to keep things in one file for now. class XgboostClient(PredictionClient): """A loaded xgboost model to be used for prediction.""" def __init__(self, booster): self._booster = booster def predict(self, inputs, stats=None, **kwargs): stats = stats or Stats() stats[FRAMEWORK] = XGBOOST_FRAMEWORK_NAME stats[ENGINE] = XGBOOST_FRAMEWORK_NAME # TODO(b/64574886): Move this to the top once b/64574886 is resolved. # Before then, it would work in production since we install xgboost in # the Dockerfile, but the problem is the unit test that will fail to build # and run since xgboost can not be added as a dependency to this target. import xgboost as xgb # pylint: disable=g-import-not-at-top try: inputs_dmatrix = xgb.DMatrix(inputs) except Exception as e: logging.exception("Could not initialize DMatrix from inputs: ") raise PredictionError( PredictionError.FAILED_TO_RUN_MODEL, "Could not initialize DMatrix from inputs: " + str(e)) try: return self._booster.predict(inputs_dmatrix, **kwargs) except Exception as e: logging.exception("Exception during predicting with xgboost model: ") raise PredictionError(PredictionError.FAILED_TO_RUN_MODEL, "Exception during xgboost prediction: " + str(e)) # (TODO:b/68775232) Move this to a separate Scikit-learn specific library. class SklearnModel(BaseModel): """The implementation of Scikit-learn Model. """ def __init__(self, client): super(SklearnModel, self).__init__(client) self._user_processor = _new_processor_class() if self._user_processor and hasattr(self._user_processor, PREPROCESS_KEY): self._preprocess = self._user_processor.preprocess else: self._preprocess = self._null_processor if self._user_processor and hasattr(self._user_processor, POSTPROCESS_KEY): self._postprocess = self._user_processor.postprocess else: self._postprocess = self._null_processor def predict(self, instances, stats=None, **kwargs): """Override the predict method to remove TF-specific args from kwargs.""" kwargs.pop(SIGNATURE_KEY, None) return super(SklearnModel, self).predict(instances, stats, **kwargs) def preprocess(self, instances, stats=None, **kwargs): # TODO(b/67383676) Consider changing this to a more generic type. return self._preprocess(np.array(instances), **kwargs) def postprocess(self, predicted_outputs, original_input=None, stats=None, **kwargs): # TODO(b/67383676) Consider changing this to a more generic type. post_processed = self._postprocess(predicted_outputs, **kwargs) if isinstance(post_processed, np.ndarray): return post_processed.tolist() if isinstance(post_processed, list): return post_processed raise PredictionError( PredictionError.INVALID_OUTPUTS, "Bad output type returned after running %s" "The post-processing function should return either " "a numpy ndarray or a list." % self._postprocess.__name__) def _null_processor(self, instances, **unused_kwargs): return instances # (TODO:b/68775232): Move this to a XGboost specific library. class XGBoostModel(SklearnModel): """The implementation of XGboost Model. """ def __init__(self, client): super(XGBoostModel, self).__init__(client) def create_sklearn_client(model_path, unused_tags): """Returns a prediction client for the corresponding sklearn model.""" logging.info("Loading the scikit-learn model file from %s", model_path) sklearn_predictor = _load_joblib_or_pickle_model(model_path) if not sklearn_predictor: error_msg = "Could not find either {} or {} in {}".format( MODEL_FILE_NAME_JOBLIB, MODEL_FILE_NAME_PICKLE, model_path) logging.critical(error_msg) raise PredictionError(PredictionError.FAILED_TO_LOAD_MODEL, error_msg) return SklearnClient(sklearn_predictor) def create_sklearn_model(model_path, unused_flags): """Returns a sklearn model from the given model_path.""" return SklearnModel(create_sklearn_client(model_path, None)) def create_xgboost_client(model_path, unused_tags): """Returns a prediction client for the corresponding xgboost model.""" logging.info("Loading the xgboost model from %s", model_path) # TODO(b/64574886): Move this to the top once b/64574886 is resolved. Before # then, it would work in production since we install xgboost in the # Dockerfile, but the problem is the unit test that will fail to build and run # since xgboost can not be added as a dependency to this target. import xgboost as xgb # pylint: disable=g-import-not-at-top try: booster = _load_joblib_or_pickle_model(model_path) or xgb.Booster( model_file=os.path.join(model_path, MODEL_FILE_NAME_BST)) except xgb.core.XGBoostError as e: error_msg = "Could not load the model: {}. {}.".format( os.path.join(model_path, MODEL_FILE_NAME_BST), str(e)) logging.critical(error_msg) raise PredictionError(PredictionError.FAILED_TO_LOAD_MODEL, error_msg) return XgboostClient(booster) def create_xgboost_model(model_path, unused_flags): """Returns a xgboost model from the given model_path.""" return XGBoostModel(create_xgboost_client(model_path, None)) # (TODO:b/68775232): Move this to a Tensorflow specific library. def create_tf_session_client(model_dir, tags): return SessionClient(*load_model(model_dir, tags)) # (TODO:b/68775232): Move this to a separate utils library. _PICKLE_MODULE_WHITELIST = [ "sklearn", "copy_reg", "xgboost", "numpy", "scipy", "pandas" ] _PICKLE_CLASS_WHITELIST = { "__builtin__": (__builtin__, [ "basestring", "bool", "buffer", "bytearray", "bytes", "complex", "dict", "enumerate", "float", "frozenset", "int", "list", "long", "reversed", "set", "slice", "str", "tuple", "unicode", "xrange", "object", ],), } class _RestrictedUnpickler(pickle.Unpickler): """Restricted Unpickler implementation. Prevents execution of code from pickled data by allowing only importing whitelisted modules. """ def find_class(self, module_name, name): if module_name.split(".")[0] in _PICKLE_MODULE_WHITELIST: module = importlib.import_module(module_name) return getattr(module, name) (module, safe_names) = _PICKLE_CLASS_WHITELIST.get(module_name, (None, [])) if name in safe_names: return getattr(module, name) # Forbid everything else. raise pickle.UnpicklingError("Importing global module: %s.%s is forbidden" % (module_name, name)) @classmethod def load_string(class_, pickle_string): return class_(StringIO.StringIO(pickle_string)).load() def _load_joblib_or_pickle_model(model_path): """Loads either a .joblib or .pkl file. Loads one of MODEL_FILE_NAME_JOBLIB or MODEL_FILE_NAME_PICKLE files if they exist. Arguments: model_path: The path to the directory that contains the model file. Raises: PredictionError: If there is a problem while loading the file. Returns: A loaded scikit-learn predictor object or None if neither MODEL_FILE_NAME_JOBLIB nor MODEL_FILE_NAME_PICKLE files are found. """ try: # If we put this at the top, we need to add a dependency to sklearn # anywhere that prediction_lib is called. from sklearn.externals import joblib # pylint: disable=g-import-not-at-top except Exception as e: error_msg = "Could not import sklearn module." logging.critical(error_msg) raise PredictionError(PredictionError.FAILED_TO_LOAD_MODEL, error_msg) try: if os.path.exists(os.path.join(model_path, MODEL_FILE_NAME_JOBLIB)): model_file_name = os.path.join(model_path, MODEL_FILE_NAME_JOBLIB) logging.info("Loading model %s using joblib.", model_file_name) return joblib.load(os.path.join(model_path, MODEL_FILE_NAME_JOBLIB)) elif os.path.exists(os.path.join(model_path, MODEL_FILE_NAME_PICKLE)): model_file_name = os.path.join(model_path, MODEL_FILE_NAME_PICKLE) logging.info("Loading model %s using pickle.", model_file_name) with open(os.path.join(model_path, MODEL_FILE_NAME_PICKLE), "rb") as f: return _RestrictedUnpickler.load_string(f.read()) except Exception as e: error_msg = "Could not load the model: {}. {}.".format( model_file_name, str(e)) logging.critical(error_msg) raise PredictionError(PredictionError.FAILED_TO_LOAD_MODEL, error_msg) return None _FRAMEWORK_TO_MODEL_MAP = { TENSORFLOW_FRAMEWORK_NAME: (TensorFlowModel, create_tf_session_client), SCIKIT_LEARN_FRAMEWORK_NAME: (SklearnModel, create_sklearn_client), XGBOOST_FRAMEWORK_NAME: (XGBoostModel, create_xgboost_client) } def create_model(client, model_path, framework=TENSORFLOW_FRAMEWORK_NAME, **unused_kwargs): """Creates and returns the appropriate model. Creates and returns a Model if no user specified model is provided. Otherwise, the user specified model is imported, created, and returned. Args: client: An instance of PredictionClient for performing prediction. model_path: The path to the exported model (e.g. session_bundle or SavedModel) framework: The framework used to train the model. Returns: An instance of the appropriate model class. """ if framework is TENSORFLOW_FRAMEWORK_NAME: logging.info("Importing tensorflow.contrib in create_model") import tensorflow.contrib # pylint: disable=redefined-outer-name, unused-variable, g-import-not-at-top model_cls = _FRAMEWORK_TO_MODEL_MAP[framework][0] return (load_model_class(client, model_path) or model_cls(client)) def create_client(framework, model_path, tags): framework = framework or TENSORFLOW_FRAMEWORK_NAME create_client_fn = _FRAMEWORK_TO_MODEL_MAP[framework][1] return create_client_fn(model_path, tags) def decode_base64(data): if isinstance(data, list): return [decode_base64(val) for val in data] elif isinstance(data, dict): if data.viewkeys() == {"b64"}: return base64.b64decode(data["b64"]) else: return {k: decode_base64(v) for k, v in data.iteritems()} else: return data def encode_base64(instances, outputs_map): """Encodes binary data in a JSON-friendly way.""" if not isinstance(instances, list): raise ValueError("only lists allowed in output; got %s" % (type(instances),)) if not instances: return instances first_value = instances[0] if not isinstance(first_value, dict): if len(outputs_map) != 1: return ValueError("The first instance was a string, but there are " "more than one output tensor, so dict expected.") # Only string tensors whose name ends in _bytes needs encoding. tensor_name, tensor_info = outputs_map.items()[0] tensor_type = tensor_info.dtype if tensor_type == dtypes.string and tensor_name.endswith("_bytes"): instances = _encode_str_tensor(instances) return instances encoded_data = [] for instance in instances: encoded_instance = {} for tensor_name, tensor_info in outputs_map.iteritems(): tensor_type = tensor_info.dtype tensor_data = instance[tensor_name] if tensor_type == dtypes.string and tensor_name.endswith("_bytes"): tensor_data = _encode_str_tensor(tensor_data) encoded_instance[tensor_name] = tensor_data encoded_data.append(encoded_instance) return encoded_data def _encode_str_tensor(data): if isinstance(data, list): return [_encode_str_tensor(val) for val in data] return {"b64": base64.b64encode(data)} def local_predict( model_dir=None, tags=(tag_constants.SERVING,), signature_name=None, instances=None, framework=TENSORFLOW_FRAMEWORK_NAME): """Run a prediction locally.""" instances = decode_base64(instances) client = create_client(framework, model_dir, tags) model = create_model(client, model_dir, framework) _, predictions = model.predict(instances, signature_name=signature_name) return {"predictions": list(predictions)}
[ "tensorflow.python.saved_model.loader.maybe_saved_model_directory", "base64.b64decode", "collections.defaultdict", "logging.critical", "os.path.join", "StringIO.StringIO", "logging.error", "json.loads", "tensorflow.python.client.session.Session", "importlib.import_module", "pydoc.locate", "num...
[((2882, 2948), 'collections.namedtuple', 'collections.namedtuple', (['"""PredictionErrorType"""', "('message', 'code')"], {}), "('PredictionErrorType', ('message', 'code'))\n", (2904, 2948), False, 'import collections\n'), ((7173, 7202), 'collections.defaultdict', 'collections.defaultdict', (['list'], {}), '(list)\n', (7196, 7202), False, 'import collections\n'), ((13862, 13908), 'tensorflow.python.saved_model.loader.maybe_saved_model_directory', 'loader.maybe_saved_model_directory', (['model_path'], {}), '(model_path)\n', (13896, 13908), False, 'from tensorflow.python.saved_model import loader\n'), ((21572, 21612), 'os.environ.get', 'os.environ.get', (['"""create_version_request"""'], {}), "('create_version_request')\n", (21586, 21612), False, 'import os\n'), ((21686, 21717), 'json.loads', 'json.loads', (['create_version_json'], {}), '(create_version_json)\n', (21696, 21717), False, 'import json\n'), ((21949, 21973), 'pydoc.locate', 'pydoc.locate', (['class_name'], {}), '(class_name)\n', (21961, 21973), False, 'import pydoc\n'), ((38126, 38197), 'logging.info', 'logging.info', (['"""Loading the scikit-learn model file from %s"""', 'model_path'], {}), "('Loading the scikit-learn model file from %s', model_path)\n", (38138, 38197), False, 'import logging\n'), ((38875, 38936), 'logging.info', 'logging.info', (['"""Loading the xgboost model from %s"""', 'model_path'], {}), "('Loading the xgboost model from %s', model_path)\n", (38887, 38936), False, 'import logging\n'), ((23483, 23521), 'inspect.getargspec', 'inspect.getargspec', (['user_class.predict'], {}), '(user_class.predict)\n', (23501, 23521), False, 'import inspect\n'), ((23545, 23578), 'inspect.getargspec', 'inspect.getargspec', (['Model.predict'], {}), '(Model.predict)\n', (23563, 23578), False, 'import inspect\n'), ((38424, 38451), 'logging.critical', 'logging.critical', (['error_msg'], {}), '(error_msg)\n', (38440, 38451), False, 'import logging\n'), ((41258, 41354), 'pickle.UnpicklingError', 'pickle.UnpicklingError', (["('Importing global module: %s.%s is forbidden' % (module_name, name))"], {}), "('Importing global module: %s.%s is forbidden' % (\n module_name, name))\n", (41280, 41354), False, 'import pickle\n'), ((44197, 44257), 'logging.info', 'logging.info', (['"""Importing tensorflow.contrib in create_model"""'], {}), "('Importing tensorflow.contrib in create_model')\n", (44209, 44257), False, 'import logging\n'), ((46430, 46452), 'base64.b64encode', 'base64.b64encode', (['data'], {}), '(data)\n', (46446, 46452), False, 'import base64\n'), ((13925, 13983), 'logging.info', 'logging.info', (['"""Importing tensorflow.contrib in load_model"""'], {}), "('Importing tensorflow.contrib in load_model')\n", (13937, 13983), False, 'import logging\n'), ((14110, 14166), 'tensorflow.python.client.session.Session', 'tf_session.Session', ([], {'target': '""""""', 'graph': 'None', 'config': 'config'}), "(target='', graph=None, config=config)\n", (14128, 14166), True, 'from tensorflow.python.client import session as tf_session\n'), ((35361, 35380), 'xgboost.DMatrix', 'xgb.DMatrix', (['inputs'], {}), '(inputs)\n', (35372, 35380), True, 'import xgboost as xgb\n'), ((37010, 37029), 'numpy.array', 'np.array', (['instances'], {}), '(instances)\n', (37018, 37029), True, 'import numpy as np\n'), ((39605, 39632), 'logging.critical', 'logging.critical', (['error_msg'], {}), '(error_msg)\n', (39621, 39632), False, 'import logging\n'), ((41003, 41039), 'importlib.import_module', 'importlib.import_module', (['module_name'], {}), '(module_name)\n', (41026, 41039), False, 'import importlib\n'), ((42278, 42305), 'logging.critical', 'logging.critical', (['error_msg'], {}), '(error_msg)\n', (42294, 42305), False, 'import logging\n'), ((42410, 42458), 'os.path.join', 'os.path.join', (['model_path', 'MODEL_FILE_NAME_JOBLIB'], {}), '(model_path, MODEL_FILE_NAME_JOBLIB)\n', (42422, 42458), False, 'import os\n'), ((42485, 42533), 'os.path.join', 'os.path.join', (['model_path', 'MODEL_FILE_NAME_JOBLIB'], {}), '(model_path, MODEL_FILE_NAME_JOBLIB)\n', (42497, 42533), False, 'import os\n'), ((42540, 42603), 'logging.info', 'logging.info', (['"""Loading model %s using joblib."""', 'model_file_name'], {}), "('Loading model %s using joblib.', model_file_name)\n", (42552, 42603), False, 'import logging\n'), ((43156, 43183), 'logging.critical', 'logging.critical', (['error_msg'], {}), '(error_msg)\n', (43172, 43183), False, 'import logging\n'), ((25627, 25649), 'inspect.getargspec', 'inspect.getargspec', (['fn'], {}), '(fn)\n', (25645, 25649), False, 'import inspect\n'), ((34220, 34287), 'logging.exception', 'logging.exception', (['"""Exception while predicting with sklearn model."""'], {}), "('Exception while predicting with sklearn model.')\n", (34237, 34287), False, 'import logging\n'), ((35414, 35477), 'logging.exception', 'logging.exception', (['"""Could not initialize DMatrix from inputs: """'], {}), "('Could not initialize DMatrix from inputs: ')\n", (35431, 35477), False, 'import logging\n'), ((35722, 35791), 'logging.exception', 'logging.exception', (['"""Exception during predicting with xgboost model: """'], {}), "('Exception during predicting with xgboost model: ')\n", (35739, 35791), False, 'import logging\n'), ((39546, 39591), 'os.path.join', 'os.path.join', (['model_path', 'MODEL_FILE_NAME_BST'], {}), '(model_path, MODEL_FILE_NAME_BST)\n', (39558, 39591), False, 'import os\n'), ((42629, 42677), 'os.path.join', 'os.path.join', (['model_path', 'MODEL_FILE_NAME_JOBLIB'], {}), '(model_path, MODEL_FILE_NAME_JOBLIB)\n', (42641, 42677), False, 'import os\n'), ((42704, 42752), 'os.path.join', 'os.path.join', (['model_path', 'MODEL_FILE_NAME_PICKLE'], {}), '(model_path, MODEL_FILE_NAME_PICKLE)\n', (42716, 42752), False, 'import os\n'), ((42779, 42827), 'os.path.join', 'os.path.join', (['model_path', 'MODEL_FILE_NAME_PICKLE'], {}), '(model_path, MODEL_FILE_NAME_PICKLE)\n', (42791, 42827), False, 'import os\n'), ((42834, 42897), 'logging.info', 'logging.info', (['"""Loading model %s using pickle."""', 'model_file_name'], {}), "('Loading model %s using pickle.', model_file_name)\n", (42846, 42897), False, 'import logging\n'), ((44886, 44915), 'base64.b64decode', 'base64.b64decode', (["data['b64']"], {}), "(data['b64'])\n", (44902, 44915), False, 'import base64\n'), ((31300, 31336), 'numpy.asarray', 'np.asarray', (['[value]'], {'dtype': 'np.object'}), '([value], dtype=np.object)\n', (31310, 31336), True, 'import numpy as np\n'), ((32136, 32191), 'logging.error', 'logging.error', (['"""Exception during postprocessing: %s"""', 'e'], {}), "('Exception during postprocessing: %s', e)\n", (32149, 32191), False, 'import logging\n'), ((32520, 32564), 'logging.error', 'logging.error', (['"""Encode base64 failed: %s"""', 'e'], {}), "('Encode base64 failed: %s', e)\n", (32533, 32564), False, 'import logging\n'), ((32802, 32846), 'logging.error', 'logging.error', (['"""Encode base64 failed: %s"""', 'e'], {}), "('Encode base64 failed: %s', e)\n", (32815, 32846), False, 'import logging\n'), ((33102, 33146), 'logging.error', 'logging.error', (['"""Encode base64 failed: %s"""', 'e'], {}), "('Encode base64 failed: %s', e)\n", (33115, 33146), False, 'import logging\n'), ((39394, 39439), 'os.path.join', 'os.path.join', (['model_path', 'MODEL_FILE_NAME_BST'], {}), '(model_path, MODEL_FILE_NAME_BST)\n', (39406, 39439), False, 'import os\n'), ((41459, 41491), 'StringIO.StringIO', 'StringIO.StringIO', (['pickle_string'], {}), '(pickle_string)\n', (41476, 41491), False, 'import StringIO\n'), ((31608, 31637), 'numpy.expand_dims', 'np.expand_dims', (['value'], {'axis': '(0)'}), '(value, axis=0)\n', (31622, 31637), True, 'import numpy as np\n'), ((42914, 42962), 'os.path.join', 'os.path.join', (['model_path', 'MODEL_FILE_NAME_PICKLE'], {}), '(model_path, MODEL_FILE_NAME_PICKLE)\n', (42926, 42962), False, 'import os\n'), ((25932, 25954), 'inspect.getargspec', 'inspect.getargspec', (['fn'], {}), '(fn)\n', (25950, 25954), False, 'import inspect\n')]
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Project: Fast Azimuthal integration # https://github.com/silx-kit/pyFAI # # Copyright (C) 2017-2020 European Synchrotron Radiation Facility, Grenoble, France # # Principal author: <NAME> (<EMAIL>) # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # . # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # . # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. """ Description of detectors which are not flat. Mainly cylindrical curved imaging-plates for now. """ __author__ = "<NAME>" __contact__ = "<EMAIL>" __license__ = "MIT" __copyright__ = "European Synchrotron Radiation Facility, Grenoble, France" __date__ = "25/06/2020" __status__ = "production" import numpy import logging logger = logging.getLogger(__name__) import json from collections import OrderedDict from ._common import Detector from pyFAI.utils import mathutil try: from ..ext import bilinear except ImportError: logger.debug("Backtrace", exc_info=True) bilinear = None class CylindricalDetector(Detector): "Abstract base class for all cylindrical detecors" MANUFACTURER = None IS_FLAT = False force_pixel = True def __init__(self, pixel1=24.893e-6, pixel2=24.893e-6, radius=0.29989): Detector.__init__(self, pixel1, pixel2) self.radius = radius self._pixel_corners = None def get_config(self): """Return the configuration with arguments to the constructor :return: dict with param for serialization """ return OrderedDict((("pixel1", self._pixel1), ("pixel2", self._pixel2), ("radius", self.radius))) def set_config(self, config): """Sets the configuration of the detector. The configuration is either a python dictionary or a JSON string or a file containing this JSON configuration keys in that dictionary are: pixel1, pixel2, radius :param config: string or JSON-serialized dict :return: self """ if not isinstance(config, dict): try: config = json.loads(config) except Exception as err: # IGNORE:W0703: logger.error("Unable to parse config %s with JSON: %s, %s", config, err) raise err pixel1 = config.get("pixel1") if pixel1: self.set_pixel1(pixel1) pixel2 = config.get("pixel2") if pixel2: self.set_pixel1(pixel2) radius = config.get("radius") if radius: self.radius = radius self._pixel_corners = None return self def _get_compact_pixel_corners(self): "The core function which calculates the pixel corner coordinates" raise NotImplementedError("This is an abtract class") def get_pixel_corners(self, correct_binning=False, use_cython=True): """ Calculate the position of the corner of the pixels This should be overwritten by class representing non-contiguous detector (Xpad, ...) :param correct_binning: If True, check that the produced array have the right shape regarding binning :param use_cython: set to False for testing :return: 4D array containing: pixel index (slow dimension) pixel index (fast dimension) corner index (A, B, C or D), triangles or hexagons can be handled the same way vertex position (z,y,x) """ if self._pixel_corners is None: with self._sem: if self._pixel_corners is None: p1, p2, p3 = self._get_compact_pixel_corners() if bilinear and use_cython: d1 = mathutil.expand2d(p1, self.shape[1] + 1, False) d2 = mathutil.expand2d(p2, self.shape[0] + 1, True) d3 = mathutil.expand2d(p3, self.shape[0] + 1, True) corners = bilinear.convert_corner_2D_to_4D(3, d1, d2, d3) else: p1.shape = -1, 1 p1.strides = p1.strides[0], 0 p2.shape = 1, -1 p2.strides = 0, p2.strides[1] p3.shape = 1, -1 p3.strides = 0, p3.strides[1] corners = numpy.zeros((self.shape[0], self.shape[1], 4, 3), dtype=numpy.float32) corners[:, :, 0, 0] = p3[:, :-1] corners[:, :, 0, 1] = p1[:-1, :] corners[:, :, 0, 2] = p2[:, :-1] corners[:, :, 1, 0] = p3[:, :-1] corners[:, :, 1, 1] = p1[1:, :] corners[:, :, 1, 2] = p2[:, :-1] corners[:, :, 2, 1] = p1[1:, :] corners[:, :, 2, 2] = p2[:, 1:] corners[:, :, 2, 0] = p3[:, 1:] corners[:, :, 3, 0] = p3[:, 1:] corners[:, :, 3, 1] = p1[:-1, :] corners[:, :, 3, 2] = p2[:, 1:] self._pixel_corners = corners if correct_binning and self._pixel_corners.shape[:2] != self.shape: return self._rebin_pixel_corners() else: return self._pixel_corners def calc_cartesian_positions(self, d1=None, d2=None, center=True, use_cython=True): """ Calculate the position of each pixel center in cartesian coordinate and in meter of a couple of coordinates. The half pixel offset is taken into account here !!! Adapted to Nexus detector definition :param d1: the Y pixel positions (slow dimension) :type d1: ndarray (1D or 2D) :param d2: the X pixel positions (fast dimension) :type d2: ndarray (1D or 2D) :param center: retrieve the coordinate of the center of the pixel :param use_cython: set to False to test Python implementeation :return: position in meter of the center of each pixels. :rtype: ndarray d1 and d2 must have the same shape, returned array will have the same shape. """ if (d1 is None) or d2 is None: d1 = mathutil.expand2d(numpy.arange(self.shape[0]).astype(numpy.float32), self.shape[1], False) d2 = mathutil.expand2d(numpy.arange(self.shape[1]).astype(numpy.float32), self.shape[0], True) corners = self.get_pixel_corners() if center: # avoid += It modifies in place and segfaults d1 = d1 + 0.5 d2 = d2 + 0.5 if bilinear and use_cython: p1, p2, p3 = bilinear.calc_cartesian_positions(d1.ravel(), d2.ravel(), corners, is_flat=False) p1.shape = d1.shape p2.shape = d2.shape p3.shape = d2.shape else: i1 = d1.astype(int).clip(0, corners.shape[0] - 1) i2 = d2.astype(int).clip(0, corners.shape[1] - 1) delta1 = d1 - i1 delta2 = d2 - i2 pixels = corners[i1, i2] if pixels.ndim == 3: A0 = pixels[:, 0, 0] A1 = pixels[:, 0, 1] A2 = pixels[:, 0, 2] B0 = pixels[:, 1, 0] B1 = pixels[:, 1, 1] B2 = pixels[:, 1, 2] C0 = pixels[:, 2, 0] C1 = pixels[:, 2, 1] C2 = pixels[:, 2, 2] D0 = pixels[:, 3, 0] D1 = pixels[:, 3, 1] D2 = pixels[:, 3, 2] else: A0 = pixels[:, :, 0, 0] A1 = pixels[:, :, 0, 1] A2 = pixels[:, :, 0, 2] B0 = pixels[:, :, 1, 0] B1 = pixels[:, :, 1, 1] B2 = pixels[:, :, 1, 2] C0 = pixels[:, :, 2, 0] C1 = pixels[:, :, 2, 1] C2 = pixels[:, :, 2, 2] D0 = pixels[:, :, 3, 0] D1 = pixels[:, :, 3, 1] D2 = pixels[:, :, 3, 2] # points A and D are on the same dim1 (Y), they differ in dim2 (X) # points B and C are on the same dim1 (Y), they differ in dim2 (X) # points A and B are on the same dim2 (X), they differ in dim1 (Y) # points C and D are on the same dim2 (X), they differ in dim1 ( p1 = A1 * (1.0 - delta1) * (1.0 - delta2) \ + B1 * delta1 * (1.0 - delta2) \ + C1 * delta1 * delta2 \ + D1 * (1.0 - delta1) * delta2 p2 = A2 * (1.0 - delta1) * (1.0 - delta2) \ + B2 * delta1 * (1.0 - delta2) \ + C2 * delta1 * delta2 \ + D2 * (1.0 - delta1) * delta2 p3 = A0 * (1.0 - delta1) * (1.0 - delta2) \ + B0 * delta1 * (1.0 - delta2) \ + C0 * delta1 * delta2 \ + D0 * (1.0 - delta1) * delta2 # To ensure numerical consitency with cython procedure. p1 = p1.astype(numpy.float32) p2 = p2.astype(numpy.float32) p3 = p3.astype(numpy.float32) return p1, p2, p3 class Aarhus(CylindricalDetector): """ Cylindrical detector made of a bent imaging-plate. Developped at the Danish university of Aarhus r = 1.2m or 0.3m Credits: Private communication; <NAME>, Center for Materials Crystallography & Dept. of Chemistry and iNANO, Aarhus University The image has to be laid-out horizontally Nota: the detector is bend towards the sample, hence reducing the sample-detector distance. This is why z<0 (or p3<0) """ MANUFACTURER = "Aarhus University" MAX_SHAPE = (1000, 16000) def __init__(self, pixel1=24.893e-6, pixel2=24.893e-6, radius=0.29989): CylindricalDetector.__init__(self, pixel1, pixel2, radius) def _get_compact_pixel_corners(self): "The core function which calculates the pixel corner coordinates" p1 = (numpy.arange(self.shape[0] + 1.0) * self._pixel1).astype(numpy.float32) t2 = numpy.arange(self.shape[1] + 1.0) * (self._pixel2 / self.radius) p2 = (self.radius * numpy.sin(t2)).astype(numpy.float32) p3 = (self.radius * (numpy.cos(t2) - 1.0)).astype(numpy.float32) return p1, p2, p3 class Rapid(CylindricalDetector): """ Cylindrical detector: Rigaku R-axis RAPID II Unlike the Aarhus detector, the detectors is bent the other direction. It covers 210ยฐ r = 127.26mm pixel size 100ยตm but can be binned 2x2 Credits: Private communication; Dr. <NAME> Department of Condensed Matter Physics Institute of Physics P.J. ล afรกrik University, Koลกice, Slovakia The image has to be laid-out horizontally Nota: the detector is bend towards the sample, hence reducing the sample-detector distance. This is why z<0 (or p3<0) """ MANUFACTURER = "Rigaku" aliases = ["RapidII"] MAX_SHAPE = (2560, 4700) def __init__(self, pixel1=0.1e-3, pixel2=0.1e-3, radius=0.12726): CylindricalDetector.__init__(self, pixel1, pixel2, radius) def _get_compact_pixel_corners(self): "The core function which calculates the pixel corner coordinates" p1 = (numpy.arange(self.shape[0] + 1.0) * self._pixel1).astype(numpy.float32) t2 = numpy.arange(self.shape[1] + 1.0) * (self._pixel2 / self.radius) p2 = (self.radius * numpy.sin(t2)).astype(numpy.float32) p3 = (self.radius * (numpy.cos(t2) - 1.0)).astype(numpy.float32) return p1, p2, p3
[ "json.loads", "pyFAI.utils.mathutil.expand2d", "numpy.zeros", "numpy.sin", "numpy.arange", "numpy.cos", "collections.OrderedDict", "logging.getLogger" ]
[((1690, 1717), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1707, 1717), False, 'import logging\n'), ((2486, 2580), 'collections.OrderedDict', 'OrderedDict', (["(('pixel1', self._pixel1), ('pixel2', self._pixel2), ('radius', self.radius))"], {}), "((('pixel1', self._pixel1), ('pixel2', self._pixel2), ('radius',\n self.radius)))\n", (2497, 2580), False, 'from collections import OrderedDict\n'), ((11170, 11203), 'numpy.arange', 'numpy.arange', (['(self.shape[1] + 1.0)'], {}), '(self.shape[1] + 1.0)\n', (11182, 11203), False, 'import numpy\n'), ((12436, 12469), 'numpy.arange', 'numpy.arange', (['(self.shape[1] + 1.0)'], {}), '(self.shape[1] + 1.0)\n', (12448, 12469), False, 'import numpy\n'), ((3080, 3098), 'json.loads', 'json.loads', (['config'], {}), '(config)\n', (3090, 3098), False, 'import json\n'), ((11085, 11118), 'numpy.arange', 'numpy.arange', (['(self.shape[0] + 1.0)'], {}), '(self.shape[0] + 1.0)\n', (11097, 11118), False, 'import numpy\n'), ((11263, 11276), 'numpy.sin', 'numpy.sin', (['t2'], {}), '(t2)\n', (11272, 11276), False, 'import numpy\n'), ((12351, 12384), 'numpy.arange', 'numpy.arange', (['(self.shape[0] + 1.0)'], {}), '(self.shape[0] + 1.0)\n', (12363, 12384), False, 'import numpy\n'), ((12529, 12542), 'numpy.sin', 'numpy.sin', (['t2'], {}), '(t2)\n', (12538, 12542), False, 'import numpy\n'), ((4768, 4815), 'pyFAI.utils.mathutil.expand2d', 'mathutil.expand2d', (['p1', '(self.shape[1] + 1)', '(False)'], {}), '(p1, self.shape[1] + 1, False)\n', (4785, 4815), False, 'from pyFAI.utils import mathutil\n'), ((4845, 4891), 'pyFAI.utils.mathutil.expand2d', 'mathutil.expand2d', (['p2', '(self.shape[0] + 1)', '(True)'], {}), '(p2, self.shape[0] + 1, True)\n', (4862, 4891), False, 'from pyFAI.utils import mathutil\n'), ((4921, 4967), 'pyFAI.utils.mathutil.expand2d', 'mathutil.expand2d', (['p3', '(self.shape[0] + 1)', '(True)'], {}), '(p3, self.shape[0] + 1, True)\n', (4938, 4967), False, 'from pyFAI.utils import mathutil\n'), ((5395, 5465), 'numpy.zeros', 'numpy.zeros', (['(self.shape[0], self.shape[1], 4, 3)'], {'dtype': 'numpy.float32'}), '((self.shape[0], self.shape[1], 4, 3), dtype=numpy.float32)\n', (5406, 5465), False, 'import numpy\n'), ((7309, 7336), 'numpy.arange', 'numpy.arange', (['self.shape[0]'], {}), '(self.shape[0])\n', (7321, 7336), False, 'import numpy\n'), ((7417, 7444), 'numpy.arange', 'numpy.arange', (['self.shape[1]'], {}), '(self.shape[1])\n', (7429, 7444), False, 'import numpy\n'), ((11329, 11342), 'numpy.cos', 'numpy.cos', (['t2'], {}), '(t2)\n', (11338, 11342), False, 'import numpy\n'), ((12595, 12608), 'numpy.cos', 'numpy.cos', (['t2'], {}), '(t2)\n', (12604, 12608), False, 'import numpy\n')]
import h5py import math import os import numpy as np import torch import torch.optim as optim import torch.nn as nn from net import classifier from torchlight import torchlight def weights_init(m): classname = m.__class__.__name__ if classname.find('Conv1d') != -1: m.weight.data.normal_(0.0, 0.02) if m.bias is not None: m.bias.data.fill_(0) elif classname.find('Conv2d') != -1: m.weight.data.normal_(0.0, 0.02) if m.bias is not None: m.bias.data.fill_(0) elif classname.find('BatchNorm') != -1: m.weight.data.normal_(1.0, 0.02) m.bias.data.fill_(0) def find_all_substr(a_str, sub): start = 0 while True: start = a_str.find(sub, start) if start == -1: return yield start start += len(sub) # use start += 1 to find overlapping matches def get_best_epoch_and_accuracy(path_to_model_files): all_models = os.listdir(path_to_model_files) acc_list = np.zeros(len(all_models)) for i, model in enumerate(all_models): acc = str.split(model, '_') if len(acc) > 1: acc_list[i] = float(acc[1][3:]) best_model = all_models[np.argmax(acc_list)] all_us = list(find_all_substr(best_model, '_')) return int(best_model[5:all_us[0]]), float(best_model[all_us[0]+4:all_us[1]]) class Processor(object): """ Processor for gait generation """ def __init__(self, args, data_loader, C, num_classes, graph_dict, device='cuda:0'): self.args = args self.data_loader = data_loader self.num_classes = num_classes self.result = dict() self.iter_info = dict() self.epoch_info = dict() self.meta_info = dict(epoch=0, iter=0) self.device = device self.io = torchlight.IO( self.args.work_dir, save_log=self.args.save_log, print_log=self.args.print_log) # model if not os.path.isdir(self.args.work_dir): os.mkdir(self.args.work_dir) self.model = classifier.Classifier(C, num_classes, graph_dict) self.model.cuda('cuda:0') self.model.apply(weights_init) self.loss = nn.CrossEntropyLoss() self.best_loss = math.inf self.step_epochs = [math.ceil(float(self.args.num_epoch * x)) for x in self.args.step] self.best_epoch = None self.best_accuracy = np.zeros((1, np.max(self.args.topk))) self.accuracy_updated = False # optimizer if self.args.optimizer == 'SGD': self.optimizer = optim.SGD( self.model.parameters(), lr=self.args.base_lr, momentum=0.9, nesterov=self.args.nesterov, weight_decay=self.args.weight_decay) elif self.args.optimizer == 'Adam': self.optimizer = optim.Adam( self.model.parameters(), lr=self.args.base_lr, weight_decay=self.args.weight_decay) else: raise ValueError() self.lr = self.args.base_lr def adjust_lr(self): # if self.args.optimizer == 'SGD' and\ if self.meta_info['epoch'] in self.step_epochs: lr = self.args.base_lr * ( 0.1 ** np.sum(self.meta_info['epoch'] >= np.array(self.step_epochs))) for param_group in self.optimizer.param_groups: param_group['lr'] = lr self.lr = lr def show_epoch_info(self): for k, v in self.epoch_info.items(): self.io.print_log('\t{}: {}'.format(k, v)) if self.args.pavi_log: self.io.log('train', self.meta_info['iter'], self.epoch_info) def show_iter_info(self): if self.meta_info['iter'] % self.args.log_interval == 0: info = '\tIter {} Done.'.format(self.meta_info['iter']) for k, v in self.iter_info.items(): if isinstance(v, float): info = info + ' | {}: {:.4f}'.format(k, v) else: info = info + ' | {}: {}'.format(k, v) self.io.print_log(info) if self.args.pavi_log: self.io.log('train', self.meta_info['iter'], self.iter_info) def show_topk(self, k): rank = self.result.argsort() hit_top_k = [l in rank[i, -k:] for i, l in enumerate(self.label)] accuracy = 100. * sum(hit_top_k) * 1.0 / len(hit_top_k) if accuracy > self.best_accuracy[0, k-1]: self.best_accuracy[0, k-1] = accuracy self.accuracy_updated = True else: self.accuracy_updated = False print_epoch = self.best_epoch if self.best_epoch is not None else 0 self.io.print_log('\tTop{}: {:.2f}%. Best so far: {:.2f}% (epoch: {:d}).'. format(k, accuracy, self.best_accuracy[0, k-1], print_epoch)) def per_train(self): self.model.train() self.adjust_lr() loader = self.data_loader['train'] loss_value = [] for data, label in loader: # get data data = data.float().to(self.device) label = label.long().to(self.device) # forward output, _ = self.model(data) loss = self.loss(output, label) # backward self.optimizer.zero_grad() loss.backward() self.optimizer.step() # statistics self.iter_info['loss'] = loss.data.item() self.iter_info['lr'] = '{:.6f}'.format(self.lr) loss_value.append(self.iter_info['loss']) self.show_iter_info() self.meta_info['iter'] += 1 self.epoch_info['mean_loss'] = np.mean(loss_value) self.show_epoch_info() self.io.print_timer() # for k in self.args.topk: # self.calculate_topk(k, show=False) # if self.accuracy_updated: # self.model.extract_feature() def per_test(self, evaluation=True): self.model.eval() loader = self.data_loader['test'] loss_value = [] result_frag = [] label_frag = [] for data, label in loader: # get data data = data.float().to(self.device) label = label.long().to(self.device) # inference with torch.no_grad(): output, _ = self.model(data) result_frag.append(output.data.cpu().numpy()) # get loss if evaluation: loss = self.loss(output, label) loss_value.append(loss.item()) label_frag.append(label.data.cpu().numpy()) self.result = np.concatenate(result_frag) if evaluation: self.label = np.concatenate(label_frag) self.epoch_info['mean_loss'] = np.mean(loss_value) self.show_epoch_info() # show top-k accuracy for k in self.args.topk: self.show_topk(k) def train(self): for epoch in range(self.args.start_epoch, self.args.num_epoch): self.meta_info['epoch'] = epoch # training self.io.print_log('Training epoch: {}'.format(epoch)) self.per_train() self.io.print_log('Done.') # evaluation if (epoch % self.args.eval_interval == 0) or ( epoch + 1 == self.args.num_epoch): self.io.print_log('Eval epoch: {}'.format(epoch)) self.per_test() self.io.print_log('Done.') # save model and weights if self.accuracy_updated: torch.save(self.model.state_dict(), os.path.join(self.args.work_dir, 'epoch{}_acc{:.2f}_model.pth.tar'.format(epoch, self.best_accuracy.item()))) if self.epoch_info['mean_loss'] < self.best_loss: self.best_loss = self.epoch_info['mean_loss'] self.best_epoch = epoch def test(self): # the path of weights must be appointed if self.args.weights is None: raise ValueError('Please appoint --weights.') self.io.print_log('Model: {}.'.format(self.args.model)) self.io.print_log('Weights: {}.'.format(self.args.weights)) # evaluation self.io.print_log('Evaluation Start:') self.per_test() self.io.print_log('Done.\n') # save the output of model if self.args.save_result: result_dict = dict( zip(self.data_loader['test'].dataset.sample_name, self.result)) self.io.save_pkl(result_dict, 'test_result.pkl') def save_best_feature(self, ftype_real, ftype_synth, data, joints, coords): if self.best_epoch is None: self.best_epoch, best_accuracy = get_best_epoch_and_accuracy(self.args.work_dir) else: best_accuracy = self.best_accuracy.item() filename = os.path.join(self.args.work_dir, 'epoch{}_acc{:.2f}_model.pth.tar'.format(self.best_epoch, best_accuracy)) self.model.load_state_dict(torch.load(filename)) features = np.empty((0, 64)) fr = h5py.File('../data/features'+ftype_real+'.h5', 'r') fl = h5py.File('../data/features'+ftype_synth+'.h5', 'r') frkeys = fr.keys() flkeys = fl.keys() df_save = h5py.File('../data/deepFeatures'+ftype_real+'+'+ftype_synth+'.h5', 'w') for i, (each_data, each_key) in enumerate(zip(data[:len(frkeys)], frkeys)): # get data each_data = np.reshape(each_data, (1, each_data.shape[0], joints, coords, 1)) each_data = np.moveaxis(each_data, [1, 2, 3], [2, 3, 1]) each_data = torch.from_numpy(each_data).float().to(self.device) # get feature with torch.no_grad(): _, feature = self.model(each_data) fname = [each_key][0]+'_real' df_save.create_dataset(fname, data=feature) features = np.append(features, np.array(feature).reshape((1, feature.shape[0])), axis=0) for i, (each_data, each_key) in enumerate(zip(data[len(frkeys):], flkeys)): # get data each_data = np.reshape(each_data, (1, each_data.shape[0], joints, coords, 1)) each_data = np.moveaxis(each_data, [1, 2, 3], [2, 3, 1]) each_data = torch.from_numpy(each_data).float().to(self.device) # get feature with torch.no_grad(): _, feature = self.model(each_data) fname = [each_key][0]+'_synth' df_save.create_dataset(fname, data=feature) features = np.append(features, np.array(feature).reshape((1, feature.shape[0])), axis=0) df_save.close() return features
[ "os.mkdir", "h5py.File", "numpy.moveaxis", "numpy.argmax", "os.path.isdir", "numpy.empty", "torch.load", "torch.nn.CrossEntropyLoss", "net.classifier.Classifier", "numpy.max", "numpy.mean", "numpy.array", "numpy.reshape", "torchlight.torchlight.IO", "torch.no_grad", "os.listdir", "nu...
[((953, 984), 'os.listdir', 'os.listdir', (['path_to_model_files'], {}), '(path_to_model_files)\n', (963, 984), False, 'import os\n'), ((1202, 1221), 'numpy.argmax', 'np.argmax', (['acc_list'], {}), '(acc_list)\n', (1211, 1221), True, 'import numpy as np\n'), ((1819, 1917), 'torchlight.torchlight.IO', 'torchlight.IO', (['self.args.work_dir'], {'save_log': 'self.args.save_log', 'print_log': 'self.args.print_log'}), '(self.args.work_dir, save_log=self.args.save_log, print_log=\n self.args.print_log)\n', (1832, 1917), False, 'from torchlight import torchlight\n'), ((2079, 2128), 'net.classifier.Classifier', 'classifier.Classifier', (['C', 'num_classes', 'graph_dict'], {}), '(C, num_classes, graph_dict)\n', (2100, 2128), False, 'from net import classifier\n'), ((2222, 2243), 'torch.nn.CrossEntropyLoss', 'nn.CrossEntropyLoss', ([], {}), '()\n', (2241, 2243), True, 'import torch.nn as nn\n'), ((5777, 5796), 'numpy.mean', 'np.mean', (['loss_value'], {}), '(loss_value)\n', (5784, 5796), True, 'import numpy as np\n'), ((6753, 6780), 'numpy.concatenate', 'np.concatenate', (['result_frag'], {}), '(result_frag)\n', (6767, 6780), True, 'import numpy as np\n'), ((9324, 9341), 'numpy.empty', 'np.empty', (['(0, 64)'], {}), '((0, 64))\n', (9332, 9341), True, 'import numpy as np\n'), ((9355, 9410), 'h5py.File', 'h5py.File', (["('../data/features' + ftype_real + '.h5')", '"""r"""'], {}), "('../data/features' + ftype_real + '.h5', 'r')\n", (9364, 9410), False, 'import h5py\n'), ((9420, 9476), 'h5py.File', 'h5py.File', (["('../data/features' + ftype_synth + '.h5')", '"""r"""'], {}), "('../data/features' + ftype_synth + '.h5', 'r')\n", (9429, 9476), False, 'import h5py\n'), ((9545, 9624), 'h5py.File', 'h5py.File', (["('../data/deepFeatures' + ftype_real + '+' + ftype_synth + '.h5')", '"""w"""'], {}), "('../data/deepFeatures' + ftype_real + '+' + ftype_synth + '.h5', 'w')\n", (9554, 9624), False, 'import h5py\n'), ((1982, 2015), 'os.path.isdir', 'os.path.isdir', (['self.args.work_dir'], {}), '(self.args.work_dir)\n', (1995, 2015), False, 'import os\n'), ((2029, 2057), 'os.mkdir', 'os.mkdir', (['self.args.work_dir'], {}), '(self.args.work_dir)\n', (2037, 2057), False, 'import os\n'), ((6829, 6855), 'numpy.concatenate', 'np.concatenate', (['label_frag'], {}), '(label_frag)\n', (6843, 6855), True, 'import numpy as np\n'), ((6899, 6918), 'numpy.mean', 'np.mean', (['loss_value'], {}), '(loss_value)\n', (6906, 6918), True, 'import numpy as np\n'), ((9283, 9303), 'torch.load', 'torch.load', (['filename'], {}), '(filename)\n', (9293, 9303), False, 'import torch\n'), ((9749, 9814), 'numpy.reshape', 'np.reshape', (['each_data', '(1, each_data.shape[0], joints, coords, 1)'], {}), '(each_data, (1, each_data.shape[0], joints, coords, 1))\n', (9759, 9814), True, 'import numpy as np\n'), ((9839, 9883), 'numpy.moveaxis', 'np.moveaxis', (['each_data', '[1, 2, 3]', '[2, 3, 1]'], {}), '(each_data, [1, 2, 3], [2, 3, 1])\n', (9850, 9883), True, 'import numpy as np\n'), ((10415, 10480), 'numpy.reshape', 'np.reshape', (['each_data', '(1, each_data.shape[0], joints, coords, 1)'], {}), '(each_data, (1, each_data.shape[0], joints, coords, 1))\n', (10425, 10480), True, 'import numpy as np\n'), ((10505, 10549), 'numpy.moveaxis', 'np.moveaxis', (['each_data', '[1, 2, 3]', '[2, 3, 1]'], {}), '(each_data, [1, 2, 3], [2, 3, 1])\n', (10516, 10549), True, 'import numpy as np\n'), ((2446, 2468), 'numpy.max', 'np.max', (['self.args.topk'], {}), '(self.args.topk)\n', (2452, 2468), True, 'import numpy as np\n'), ((6404, 6419), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (6417, 6419), False, 'import torch\n'), ((10004, 10019), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (10017, 10019), False, 'import torch\n'), ((10670, 10685), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (10683, 10685), False, 'import torch\n'), ((3346, 3372), 'numpy.array', 'np.array', (['self.step_epochs'], {}), '(self.step_epochs)\n', (3354, 3372), True, 'import numpy as np\n'), ((9908, 9935), 'torch.from_numpy', 'torch.from_numpy', (['each_data'], {}), '(each_data)\n', (9924, 9935), False, 'import torch\n'), ((10225, 10242), 'numpy.array', 'np.array', (['feature'], {}), '(feature)\n', (10233, 10242), True, 'import numpy as np\n'), ((10574, 10601), 'torch.from_numpy', 'torch.from_numpy', (['each_data'], {}), '(each_data)\n', (10590, 10601), False, 'import torch\n'), ((10892, 10909), 'numpy.array', 'np.array', (['feature'], {}), '(feature)\n', (10900, 10909), True, 'import numpy as np\n')]
# Built in python libs from typing import List, Tuple, Any # Additional libs import numpy as np import cv2 from numba import jit, njit, prange # Custom imports # performs the ratio test on a set of matched keypoints # the ratio test filters matched keypoints out if they are greater than the minimum seperation between matched # by a set amount. The usual value is 3. Thus, if the distance between two matched features is 3 times larger than the # minimum pixel distance between 2 matched features, than we can say it is invalid and in outlier. # This is because the typical image to image comparision will have a small change between frames # takes a list of keypoints, a minimum distance, and a given ratio # kpMatches must be SORTED for optimization purposes @jit(forceobj=True) def ratioTest(kpMatches: np.ndarray, ratio: float) -> List: if len(kpMatches) > 0: minDist = kpMatches[0].distance else: minDist = 0.0 goodDistanceDiffs = [] for m in kpMatches: if m.distance < ratio * minDist: goodDistanceDiffs.append(m) else: break return goodDistanceDiffs @jit(forceobj=True) def adaptiveRatioTest(kpMatches: np.ndarray, startingRatio: float, targetFeatureRatio: float, stepSize: float, timeout=1000) -> List: ratioPoints: List = list() currentFeatureRatio = 0.0 counter = 0 while currentFeatureRatio < targetFeatureRatio: ratioPoints = ratioTest(kpMatches, startingRatio + stepSize * counter) currentFeatureRatio = len(ratioPoints) / len(kpMatches) counter += 1 if counter > timeout: break # print(f"CurrentFeatureRatio: {currentFeatureRatio} with ratio: {startingRatio + (counter - 1) * stepSize}") return ratioPoints @jit(forceobj=True) def getSrcDstPointsFromMatches(matchedKp, prevKp, currKp): # (x, y) coordinates from the first image. prevPts = np.float32([prevKp[m.trainIdx].pt for m in matchedKp]).reshape(-1, 1, 2) # (x, y) coordinates from the second image. currPts = np.float32([currKp[m.trainIdx].pt for m in matchedKp]).reshape(-1, 1, 2) # converts to np.arrays return np.array(prevPts), np.array(currPts) # actually gets average X @jit(nopython=True) def getAvgCoordinate(array): x_val_sum = 0 for element in array: x_val_sum += element return x_val_sum / len(array) @jit(forceobj=True) def getCoordinateAverage(array): # Grabs only the first column (x values) avgX = getAvgCoordinate(array[:, 0][:, 0]) # Grabs only the second column (y values) avgY = getAvgCoordinate(array[0, :][0, :]) return avgX, avgY @jit(forceobj=True) def getTranslationXY(matchedKp: np.ndarray, prevKp: np.ndarray, currKp: np.ndarray) -> Tuple[float, float]: prevPts, currPts = getSrcDstPointsFromMatches(matchedKp, prevKp, currKp) prevAvgX, prevAvgY = getCoordinateAverage(prevPts) currAvgX, currAvgY = getCoordinateAverage(currPts) transX = currAvgX - prevAvgX transY = currAvgY - prevAvgY return transX, transY def getAvgTranslationXY(leftMatches: np.ndarray, prevLeftKp: np.ndarray, leftKp: np.ndarray, rightMatches: np.ndarray, prevRightKp: np.ndarray, rightKp: np.ndarray) -> Tuple[float, float]: leftX, leftY = 0.0, 0.0 rightX, rightY = 0.0, 0.0 numErrors = 0 try: leftX, leftY = getTranslationXY(leftMatches, prevLeftKp, leftKp) except IndexError: numErrors += 1 except ZeroDivisionError: numErrors += 1 try: rightX, rightY = getTranslationXY(rightMatches, prevRightKp, rightKp) except IndexError: numErrors += 1 except ZeroDivisionError: numErrors += 1 if numErrors >= 2: return 0.0, 0.0 return (leftX + rightX) / (2 - numErrors), (leftY + rightY) / (2 - numErrors)
[ "numpy.array", "numpy.float32", "numba.jit" ]
[((768, 786), 'numba.jit', 'jit', ([], {'forceobj': '(True)'}), '(forceobj=True)\n', (771, 786), False, 'from numba import jit, njit, prange\n'), ((1142, 1160), 'numba.jit', 'jit', ([], {'forceobj': '(True)'}), '(forceobj=True)\n', (1145, 1160), False, 'from numba import jit, njit, prange\n'), ((1798, 1816), 'numba.jit', 'jit', ([], {'forceobj': '(True)'}), '(forceobj=True)\n', (1801, 1816), False, 'from numba import jit, njit, prange\n'), ((2250, 2268), 'numba.jit', 'jit', ([], {'nopython': '(True)'}), '(nopython=True)\n', (2253, 2268), False, 'from numba import jit, njit, prange\n'), ((2408, 2426), 'numba.jit', 'jit', ([], {'forceobj': '(True)'}), '(forceobj=True)\n', (2411, 2426), False, 'from numba import jit, njit, prange\n'), ((2670, 2688), 'numba.jit', 'jit', ([], {'forceobj': '(True)'}), '(forceobj=True)\n', (2673, 2688), False, 'from numba import jit, njit, prange\n'), ((2184, 2201), 'numpy.array', 'np.array', (['prevPts'], {}), '(prevPts)\n', (2192, 2201), True, 'import numpy as np\n'), ((2203, 2220), 'numpy.array', 'np.array', (['currPts'], {}), '(currPts)\n', (2211, 2220), True, 'import numpy as np\n'), ((1937, 1991), 'numpy.float32', 'np.float32', (['[prevKp[m.trainIdx].pt for m in matchedKp]'], {}), '([prevKp[m.trainIdx].pt for m in matchedKp])\n', (1947, 1991), True, 'import numpy as np\n'), ((2072, 2126), 'numpy.float32', 'np.float32', (['[currKp[m.trainIdx].pt for m in matchedKp]'], {}), '([currKp[m.trainIdx].pt for m in matchedKp])\n', (2082, 2126), True, 'import numpy as np\n')]
import numpy from distutils.core import setup from Cython.Build import cythonize setup( name='features_labels', ext_modules=cythonize('features_labels.pyx', include_dirs=[numpy.get_include()]) )
[ "numpy.get_include" ]
[((180, 199), 'numpy.get_include', 'numpy.get_include', ([], {}), '()\n', (197, 199), False, 'import numpy\n')]
""" Script for extracting particles from membranes by looking for low pass filtering + non-maximum suppression Input: - Directory with the _imod.csv files with reference picked particles for each microsome - Directory with offsets for each microsome in a tomogram - Directory with the density maps Output: - A STAR file and a list with the coordinates pickled per microsome - Additional files for visualization """ __author__ = '<NAME>' import pyseg as ps import scipy as sp ######################################################################################## # GLOBAL VARIABLES ######################################################################################## MB_LBL = 1 ######################################################################################## # PARAMETERS ######################################################################################## ROOT_PATH = '/fs/pool/pool-lucic2' # Input STAR files in_dir = ROOT_PATH + '/antonio/pick_test/cont/160614' # '/johannes/tomograms/stefan/090614/reconstruct/coords' in_dir_seg = ROOT_PATH + '/johannes/tomograms/stefan/160614/graph_ribo' in_dir_den = ROOT_PATH + '/antonio/pick_test/tm/cc/tomos_nobeads/160614' in_ctf = ROOT_PATH + '/antonio/pick_test/recontruct/ctf/CTF_model_160.mrc' ####### Output data out_dir = ROOT_PATH + '/antonio/pick_test/pick/den/160614' out_dir_parts = ROOT_PATH + '/antonio/pick_test/recontruct/den/160614/protein_160' ###### Low pass filter settings lp_res = 1.048 # nm lp_sg = 0.8 # Gaussian: min_feat=(1/fc), fc=Fs/(2*pi*sg), Fs=1/vx_size ###### Peaks configuration peak_side = 2 # 3 peak_dst_rg = (0, 20) # vx # None ###### Advanced peaks configuration peak_prop_pt = 'pt_normal' peak_prop_norm = 'smb_normal' peak_prop_rot = 'norm_rot' ######################################################################################## # MAIN ROUTINE ######################################################################################## ################# Package import import os import gc import csv import time import math import numpy as np from pyseg.sub import TomoPeaks from skimage.feature import peak_local_max from pyorg.surf import points_to_poly ########## Global variables ########## Print initial message print('Extracting particles randomly within segmented membranes.') print('\tAuthor: ' + __author__) print('\tDate: ' + time.strftime("%c") + '\n') print('Options:') print('\tDirectory for reference picked particles: ' + str(in_dir)) print('\tDirectory for microsomes offset per tomogram: ' + str(in_dir_seg)) print('\tDirectory for density maps: ' + str(in_dir_den)) print('\tOutput directory: ' + str(out_dir)) print('\tLow pass filter settings (Gaussian):') print('\t\t-Voxel size (nm/vx): ' + str(lp_res)) print('\t\t-Gaussian sigma (nm): ' + str(lp_sg)) sampling_rate = 1. / lp_res print('\t\t-Sampling rate (1/nm): ' + str(sampling_rate)) freq_cutoff = sampling_rate / (2.*np.pi*lp_sg) print('\t\t-Cut-off frequency at level 0.5 (1/nm): ' + str(freq_cutoff)) min_feature = 1. / freq_cutoff print('\t\t-Min. feature size (nm): ' + str(min_feature)) print('\tPeaks configuration:') print('\t\t-Peak side: ' + str(peak_side)) if peak_dst_rg is None: print('\t\t-Distances range: [0, 0]') else: print('\t\t-Distances range: (' + str(peak_dst_rg[0]) + ', ' + str(peak_dst_rg[1]) + ')') print('') ######### Process print('\tSearching for *_imod.csv files in input folder...') ref_files = list() for fname in os.listdir(in_dir): if fname.endswith('_imod.csv'): ref_files.append(os.path.split(fname)[1]) print('\t\t-File found: ' + ref_files[-1]) print('\tPairing files found with their segmentation offset...') mic_dic = dict() for fname in ref_files: names = fname.split('_') fname_off = in_dir_seg + '/' + names[0] + '_' + names[1] + '_mb_graph.star' ves_id = names[3] print('\t\t-Tomogram offset found: ' + fname_off) star = ps.sub.Star() star.load(fname_off) for row in range(star.get_nrows()): path_seg = star.get_element('_psSegImage', row) path_ref = star.get_element('_rlnMicrographName', row) fname_seg = os.path.split(path_seg)[1] names_seg = fname_seg.split('_') if ves_id == names_seg[3]: offx = star.get_element('_psSegOffX', row) offy = star.get_element('_psSegOffY', row) offz = star.get_element('_psSegOffZ', row) n_parts = sum(1 for line in open(in_dir + '/' + fname)) mic_dic[fname] = (path_ref, path_seg, offx, offy, offz, n_parts) print('\t\t\t-Offset found for microsome ' + fname + ' with ' + str(n_parts) + ' particles.') print('\tPreparing output particles STAR file...') star_parts = ps.sub.Star() star_parts.add_column('_rlnMicrographName') star_parts.add_column('_rlnImageName') star_parts.add_column('_rlnCtfImage') star_parts.add_column('_rlnCoordinateX') star_parts.add_column('_rlnCoordinateY') star_parts.add_column('_rlnCoordinateZ') star_parts.add_column('_rlnAngleRot') star_parts.add_column('_rlnAngleTilt') star_parts.add_column('_rlnAnglePsi') part_row = 0 print('\tPICKING LOOP:') for in_mic in mic_dic.keys(): path_seg, path_ref = mic_dic[in_mic][1], mic_dic[in_mic][0] names = (os.path.splitext(os.path.split(path_seg)[1])[0]).split('_') stem_mic = names[0] + '_' + names[1] + '_' + names[2] + '_' + names[3] print('\t-Processing stem: ' + stem_mic) path_cc = in_dir_den + '/' + stem_mic + '.mrc' print('\t\t-Loading corresponding density map: ' + path_cc) try: tomo_cc = ps.disperse_io.load_tomo(path_cc, mmap=True) except IOError: print('\t\t\t-WARNING: the corresponding CC map cannot be loaded, continuing...') gc.collect() continue print('\t\t-Low pass filtering...') tomo_cc = sp.ndimage.filters.gaussian_filter(ps.globals.lin_map(tomo_cc, lb=1, ub=0), lp_sg) print('\t\t-Loading microsome segmentation file: ' + path_seg) seg = ps.disperse_io.load_tomo(path_seg, mmap=True) mb_mask, seg_mask = seg == MB_LBL, seg == peak_side del seg n_samp = mic_dic[in_mic][5] if peak_dst_rg is not None: mb_dsts = sp.ndimage.morphology.distance_transform_edt(~mb_mask) mb_mask = (mb_dsts > peak_dst_rg[0]) & (mb_dsts < peak_dst_rg[1]) del mb_dsts mb_mask *= seg_mask seg_mask[mb_mask] = False # ps.disperse_io.save_numpy(mb_mask, out_dir + '/hold1.mrc') # ps.disperse_io.save_numpy(seg_mask, out_dir + '/hold2.mrc') print('\t\t-Finding peaks (local maxima) in the cross-correlation map: ') tomo_peaks = peak_local_max(tomo_cc, min_distance=int(math.ceil(min_feature)), indices=False) # tomo_peaks = ski.morphology.local_maxima(tomo_cc, indices=False) peaks = np.where(tomo_peaks * mb_mask) n_peaks = len(peaks[0]) hold_peaks = n_samp if n_peaks < hold_peaks: hold_peaks = n_peaks print('\t\t\t-Number of peaks found ' + str(n_peaks) + ', ' + str(hold_peaks) + ' are going to be picked.') peaks_cc = np.zeros(shape=n_peaks, dtype=np.float) for i in range(n_peaks): peaks_cc[i] = tomo_cc[peaks[0][i], peaks[1][i], peaks[2][i]] peaks_sorted = np.argsort(peaks_cc)[::-1] coords = list() for id in peaks_sorted[:hold_peaks]: coords.append((peaks[0][id], peaks[1][id], peaks[2][id])) print('\t\t-Creating the peaks container...') out_seg = out_dir + '/' + stem_mic + '_mb.mrc' tomo_peaks = TomoPeaks(shape=mb_mask.shape, name=out_seg, mask=mb_mask) tomo_peaks.add_peaks(coords) tomo_peaks.seg_shortest_pt(seg_mask, peak_prop_pt) print('\t\t\t-Number of peaks found: ' + str(tomo_peaks.get_num_peaks())) out_imod_csv = out_dir + '/' + stem_mic + '_den_imod.csv' if not os.path.exists(out_imod_csv): print('\t\t-Creating output IMOD CSV file: ' + out_imod_csv) with open(out_imod_csv, 'w') as imod_csv_file: writer = csv.DictWriter(imod_csv_file, dialect=csv.excel_tab, fieldnames=('X', 'Y', 'Z')) out_rln_coords = out_dir + '/' + stem_mic + '_den_rln.coords' if not os.path.exists(out_rln_coords): print('\t\t-Creating output RELION COORDS file: ' + out_rln_coords) with open(out_rln_coords, 'w') as rln_coords_file: writer = csv.DictWriter(rln_coords_file, dialect=csv.excel_tab, fieldnames=('X', 'Y', 'Z', 'Rho', 'Tilt', 'Psi')) print('\t\tParticles loop..') part_seg_row = 1 coords_noff, normals_imod = list(), list() gcrop_off = mic_dic[in_mic][2], mic_dic[in_mic][3], mic_dic[in_mic][4] gcrop_off_rln = np.asarray((gcrop_off[1], gcrop_off[0], gcrop_off[2]), dtype=np.float32) coords, coords_pt = tomo_peaks.get_prop_vals(ps.sub.PK_COORDS), tomo_peaks.get_prop_vals(peak_prop_pt) for coord, pt_coord in zip(coords, coords_pt): # Coordinate transformation for IMOD coords_noff.append(coord) coord_imod, pt_coord_imod = coord + gcrop_off, pt_coord + gcrop_off vec_imod = pt_coord_imod - coord_imod hold_norm = math.sqrt((vec_imod * vec_imod).sum()) if hold_norm <= 0: vec_imod = np.asarray((0., 0., 0.)) else: vec_imod /= hold_norm normals_imod.append(vec_imod) out_imod_csv = out_dir + '/' + stem_mic + '_den_imod.csv' with open(out_imod_csv, 'a') as imod_csv_file: writer = csv.DictWriter(imod_csv_file, dialect=csv.excel_tab, fieldnames=('X', 'Y', 'Z')) writer.writerow({'X':coord_imod[0], 'Y':coord_imod[1], 'Z':coord_imod[2]}) # Coordinate transformation for RELION coord_rln = np.asarray((coord[1], coord[0], coord[2]), dtype=np.float32) pt_coord_rln = np.asarray((pt_coord[1], pt_coord[0], pt_coord[2]), dtype=np.float32) coord_rln, pt_coord_rln = coord_rln + gcrop_off_rln, pt_coord_rln + gcrop_off_rln vec_rln = pt_coord_rln - coord_rln # hold_norm = math.sqrt((vec_rln * vec_rln).sum()) # if hold_norm <= 0: # vec_rln = np.asarray((0., 0., 0.)) # else: # vec_rln /= hold_norm rho, tilt, psi = ps.globals.vect_to_zrelion(vec_rln) out_rln_coords = out_dir + '/' + stem_mic + '_den_rln.coords' with open(out_rln_coords, 'a') as rln_coords_file: writer = csv.DictWriter(rln_coords_file, dialect=csv.excel_tab, fieldnames=('X', 'Y', 'Z', 'Rho', 'Tilt', 'Psi')) writer.writerow({'X':coord_rln[0], 'Y':coord_rln[1], 'Z':coord_rln[2], 'Rho':rho, 'Tilt':tilt, 'Psi':psi}) part_path = out_dir_parts + '/' + stem_mic + '_' + str(part_seg_row) + '.mrc' star_row = {'_rlnMicrographName':path_seg, '_rlnImageName':part_path, '_rlnCtfImage':in_ctf, '_rlnCoordinateX':coord_rln[0], '_rlnCoordinateY':coord_rln[1], '_rlnCoordinateZ':coord_rln[2], '_rlnAngleRot':rho, '_rlnAngleTilt':tilt, '_rlnAnglePsi':psi} star_parts.add_row(**star_row) part_row += 1 part_seg_row += 1 out_vtp = out_dir + '/' + stem_mic + '.vtp' print('\t\t-Storing the vtp file: ' + out_vtp) coords_vtp = points_to_poly(coords_noff, normals=normals_imod, n_name='n_normal') ps.disperse_io.save_vtp(coords_vtp, out_vtp) gc.collect() print('\tNumber of particles found: ' + str(part_row)) out_star = out_dir + '/particles_160614_den.star' print('\tStoring particles STAR file in: ' + out_star) star_parts.store(out_star) print('Terminated. (' + time.strftime("%c") + ')')
[ "pyseg.globals.lin_map", "time.strftime", "numpy.argsort", "gc.collect", "pyseg.globals.vect_to_zrelion", "pyseg.sub.Star", "csv.DictWriter", "pyseg.sub.TomoPeaks", "os.path.exists", "pyseg.disperse_io.load_tomo", "pyorg.surf.points_to_poly", "math.ceil", "numpy.asarray", "scipy.ndimage.mo...
[((3509, 3527), 'os.listdir', 'os.listdir', (['in_dir'], {}), '(in_dir)\n', (3519, 3527), False, 'import os\n'), ((4771, 4784), 'pyseg.sub.Star', 'ps.sub.Star', ([], {}), '()\n', (4782, 4784), True, 'import pyseg as ps\n'), ((3969, 3982), 'pyseg.sub.Star', 'ps.sub.Star', ([], {}), '()\n', (3980, 3982), True, 'import pyseg as ps\n'), ((6023, 6068), 'pyseg.disperse_io.load_tomo', 'ps.disperse_io.load_tomo', (['path_seg'], {'mmap': '(True)'}), '(path_seg, mmap=True)\n', (6047, 6068), True, 'import pyseg as ps\n'), ((6830, 6860), 'numpy.where', 'np.where', (['(tomo_peaks * mb_mask)'], {}), '(tomo_peaks * mb_mask)\n', (6838, 6860), True, 'import numpy as np\n'), ((7098, 7137), 'numpy.zeros', 'np.zeros', ([], {'shape': 'n_peaks', 'dtype': 'np.float'}), '(shape=n_peaks, dtype=np.float)\n', (7106, 7137), True, 'import numpy as np\n'), ((7528, 7586), 'pyseg.sub.TomoPeaks', 'TomoPeaks', ([], {'shape': 'mb_mask.shape', 'name': 'out_seg', 'mask': 'mb_mask'}), '(shape=mb_mask.shape, name=out_seg, mask=mb_mask)\n', (7537, 7586), False, 'from pyseg.sub import TomoPeaks\n'), ((8651, 8723), 'numpy.asarray', 'np.asarray', (['(gcrop_off[1], gcrop_off[0], gcrop_off[2])'], {'dtype': 'np.float32'}), '((gcrop_off[1], gcrop_off[0], gcrop_off[2]), dtype=np.float32)\n', (8661, 8723), True, 'import numpy as np\n'), ((11181, 11249), 'pyorg.surf.points_to_poly', 'points_to_poly', (['coords_noff'], {'normals': 'normals_imod', 'n_name': '"""n_normal"""'}), "(coords_noff, normals=normals_imod, n_name='n_normal')\n", (11195, 11249), False, 'from pyorg.surf import points_to_poly\n'), ((11254, 11298), 'pyseg.disperse_io.save_vtp', 'ps.disperse_io.save_vtp', (['coords_vtp', 'out_vtp'], {}), '(coords_vtp, out_vtp)\n', (11277, 11298), True, 'import pyseg as ps\n'), ((11304, 11316), 'gc.collect', 'gc.collect', ([], {}), '()\n', (11314, 11316), False, 'import gc\n'), ((5614, 5658), 'pyseg.disperse_io.load_tomo', 'ps.disperse_io.load_tomo', (['path_cc'], {'mmap': '(True)'}), '(path_cc, mmap=True)\n', (5638, 5658), True, 'import pyseg as ps\n'), ((5897, 5936), 'pyseg.globals.lin_map', 'ps.globals.lin_map', (['tomo_cc'], {'lb': '(1)', 'ub': '(0)'}), '(tomo_cc, lb=1, ub=0)\n', (5915, 5936), True, 'import pyseg as ps\n'), ((6220, 6274), 'scipy.ndimage.morphology.distance_transform_edt', 'sp.ndimage.morphology.distance_transform_edt', (['(~mb_mask)'], {}), '(~mb_mask)\n', (6264, 6274), True, 'import scipy as sp\n'), ((7255, 7275), 'numpy.argsort', 'np.argsort', (['peaks_cc'], {}), '(peaks_cc)\n', (7265, 7275), True, 'import numpy as np\n'), ((7827, 7855), 'os.path.exists', 'os.path.exists', (['out_imod_csv'], {}), '(out_imod_csv)\n', (7841, 7855), False, 'import os\n'), ((8160, 8190), 'os.path.exists', 'os.path.exists', (['out_rln_coords'], {}), '(out_rln_coords)\n', (8174, 8190), False, 'import os\n'), ((9682, 9742), 'numpy.asarray', 'np.asarray', (['(coord[1], coord[0], coord[2])'], {'dtype': 'np.float32'}), '((coord[1], coord[0], coord[2]), dtype=np.float32)\n', (9692, 9742), True, 'import numpy as np\n'), ((9766, 9835), 'numpy.asarray', 'np.asarray', (['(pt_coord[1], pt_coord[0], pt_coord[2])'], {'dtype': 'np.float32'}), '((pt_coord[1], pt_coord[0], pt_coord[2]), dtype=np.float32)\n', (9776, 9835), True, 'import numpy as np\n'), ((10182, 10217), 'pyseg.globals.vect_to_zrelion', 'ps.globals.vect_to_zrelion', (['vec_rln'], {}), '(vec_rln)\n', (10208, 10217), True, 'import pyseg as ps\n'), ((2411, 2430), 'time.strftime', 'time.strftime', (['"""%c"""'], {}), "('%c')\n", (2424, 2430), False, 'import time\n'), ((4187, 4210), 'os.path.split', 'os.path.split', (['path_seg'], {}), '(path_seg)\n', (4200, 4210), False, 'import os\n'), ((5777, 5789), 'gc.collect', 'gc.collect', ([], {}), '()\n', (5787, 5789), False, 'import gc\n'), ((8002, 8087), 'csv.DictWriter', 'csv.DictWriter', (['imod_csv_file'], {'dialect': 'csv.excel_tab', 'fieldnames': "('X', 'Y', 'Z')"}), "(imod_csv_file, dialect=csv.excel_tab, fieldnames=('X', 'Y', 'Z')\n )\n", (8016, 8087), False, 'import csv\n'), ((8348, 8456), 'csv.DictWriter', 'csv.DictWriter', (['rln_coords_file'], {'dialect': 'csv.excel_tab', 'fieldnames': "('X', 'Y', 'Z', 'Rho', 'Tilt', 'Psi')"}), "(rln_coords_file, dialect=csv.excel_tab, fieldnames=('X', 'Y',\n 'Z', 'Rho', 'Tilt', 'Psi'))\n", (8362, 8456), False, 'import csv\n'), ((9193, 9220), 'numpy.asarray', 'np.asarray', (['(0.0, 0.0, 0.0)'], {}), '((0.0, 0.0, 0.0))\n', (9203, 9220), True, 'import numpy as np\n'), ((9446, 9531), 'csv.DictWriter', 'csv.DictWriter', (['imod_csv_file'], {'dialect': 'csv.excel_tab', 'fieldnames': "('X', 'Y', 'Z')"}), "(imod_csv_file, dialect=csv.excel_tab, fieldnames=('X', 'Y', 'Z')\n )\n", (9460, 9531), False, 'import csv\n'), ((10368, 10476), 'csv.DictWriter', 'csv.DictWriter', (['rln_coords_file'], {'dialect': 'csv.excel_tab', 'fieldnames': "('X', 'Y', 'Z', 'Rho', 'Tilt', 'Psi')"}), "(rln_coords_file, dialect=csv.excel_tab, fieldnames=('X', 'Y',\n 'Z', 'Rho', 'Tilt', 'Psi'))\n", (10382, 10476), False, 'import csv\n'), ((11530, 11549), 'time.strftime', 'time.strftime', (['"""%c"""'], {}), "('%c')\n", (11543, 11549), False, 'import time\n'), ((3590, 3610), 'os.path.split', 'os.path.split', (['fname'], {}), '(fname)\n', (3603, 3610), False, 'import os\n'), ((6707, 6729), 'math.ceil', 'math.ceil', (['min_feature'], {}), '(min_feature)\n', (6716, 6729), False, 'import math\n'), ((5308, 5331), 'os.path.split', 'os.path.split', (['path_seg'], {}), '(path_seg)\n', (5321, 5331), False, 'import os\n')]
import napari import os import shutil import squidpy as sq from ngff_tables_prototype.writer import write_spatial_anndata from ngff_tables_prototype.reader import load_to_napari_viewer import numpy as np output_fpath = "test_segment.zarr" def write_segmentation_adata() -> None: adata = sq.datasets.mibitof() lib_id = "point8" spatial_key = "spatial" adata = adata[adata.obs.library_id == lib_id].copy() image = adata.uns[spatial_key][lib_id]["images"]["hires"] segment = adata.uns[spatial_key][lib_id]["images"]["segmentation"] adata.X = adata.X.A.copy() tables_adata = adata.copy() if True: if os.path.isdir(output_fpath): shutil.rmtree(output_fpath) if not os.path.isdir(output_fpath): write_spatial_anndata( file_path=output_fpath, image_axes=["c", "y", "x"], image=np.swapaxes(image, 2, 0), label_image=segment, tables_adata=tables_adata, tables_region="labels/label_image", tables_instance_key="cell_id", ) return if __name__ == "__main__": write_segmentation_adata() viewer = load_to_napari_viewer( file_path=output_fpath, groups=["labels/label_image", "tables/regions_table"], ) napari.run()
[ "os.path.isdir", "squidpy.datasets.mibitof", "numpy.swapaxes", "ngff_tables_prototype.reader.load_to_napari_viewer", "shutil.rmtree", "napari.run" ]
[((294, 315), 'squidpy.datasets.mibitof', 'sq.datasets.mibitof', ([], {}), '()\n', (313, 315), True, 'import squidpy as sq\n'), ((1163, 1267), 'ngff_tables_prototype.reader.load_to_napari_viewer', 'load_to_napari_viewer', ([], {'file_path': 'output_fpath', 'groups': "['labels/label_image', 'tables/regions_table']"}), "(file_path=output_fpath, groups=['labels/label_image',\n 'tables/regions_table'])\n", (1184, 1267), False, 'from ngff_tables_prototype.reader import load_to_napari_viewer\n'), ((1291, 1303), 'napari.run', 'napari.run', ([], {}), '()\n', (1301, 1303), False, 'import napari\n'), ((644, 671), 'os.path.isdir', 'os.path.isdir', (['output_fpath'], {}), '(output_fpath)\n', (657, 671), False, 'import os\n'), ((725, 752), 'os.path.isdir', 'os.path.isdir', (['output_fpath'], {}), '(output_fpath)\n', (738, 752), False, 'import os\n'), ((685, 712), 'shutil.rmtree', 'shutil.rmtree', (['output_fpath'], {}), '(output_fpath)\n', (698, 712), False, 'import shutil\n'), ((879, 903), 'numpy.swapaxes', 'np.swapaxes', (['image', '(2)', '(0)'], {}), '(image, 2, 0)\n', (890, 903), True, 'import numpy as np\n')]
from __future__ import division import numpy as np #----------------------------- COSMOS galaxy bias (arXiv:1205.1064) ---------------------------------------- def bias_Amara(z, bias_type, zcutoff): y = z/(1+z) ycutoff = zcutoff/(1+zcutoff) #bias_type --> nn:fifth nearest neighbor or gs: gaussian smoothing if(bias_type=='nn'): b0=1.25; f=-1.4 if(bias_type=='gs'): b0=0.7 ; f=-1.615 bmax = b0/(1 + (f*ycutoff) ) if(z<=zcutoff): return b0/(1+ (f*y)) if(z>zcutoff): return bmax #----------------- Galaxy bias (1.> arXiv:1101.2453 (pg. 4), 2.> arXiv:0810.0003 (pg. 7, Table 3)) --------- def bias_Porto(z): return np.sqrt(1+z)
[ "numpy.sqrt" ]
[((629, 643), 'numpy.sqrt', 'np.sqrt', (['(1 + z)'], {}), '(1 + z)\n', (636, 643), True, 'import numpy as np\n')]
import os import json from collections import OrderedDict import numpy as np import tensorflow as tf cur_path = os.path.realpath(__file__) ROOT_PATH = os.path.dirname(cur_path) # add any new ops under the following pose_to_heatmap_fn = tf.load_op_library( os.path.join(ROOT_PATH, 'pose_to_heatmap.so')).pose_to_heatmap zero_out_channels_fn = tf.load_op_library( os.path.join(ROOT_PATH, 'zero_out_channels.so')).zero_out_channels render_pose_fn = tf.load_op_library( os.path.join(ROOT_PATH, 'render_pose.so')).render_pose render_objects_fn = tf.load_op_library( os.path.join(ROOT_PATH, 'render_objects.so')).render_objects def pose_to_heatmap(*args, **kwargs): with tf.variable_scope('pose_to_heatmap_pyWrapper'): pose_img, pose_valid = pose_to_heatmap_fn(*args, **kwargs) out_channels = kwargs['out_channels'] pose_img.set_shape((None, None, out_channels)) pose_valid.set_shape((out_channels,)) pose_img *= 255.0 pose_img = tf.cast(pose_img, tf.uint8) return pose_img, pose_valid def zero_out_channels(*args, **kwargs): with tf.variable_scope('zero_out_channels_pyWrapper'): return zero_out_channels_fn(*args, **kwargs) def render_pose(*args, **kwargs): with tf.variable_scope('render_pose_pyWrapper'): out_channels = 3 if kwargs['out_type'] == 'rgb': kwargs['out_type'] = 1 out_channels = 3 elif kwargs['out_type'] == 'split-channel': kwargs['out_type'] = 2 out_channels = 18 # number of limbs img = render_pose_fn(*args, **kwargs) img *= 255.0 img = tf.cast(img, tf.uint8) img.set_shape((None, None, out_channels)) return img # from render_pose.cc mpii_to_coco = OrderedDict([ (9, 0), (8, 1), (12, 2), (11, 3), (10, 4), (13, 5), (14, 6), (15, 7), (2, 8), (1, 9), (0, 10), (3, 11), (4, 12), (5, 13), ]) def read_json_pose_fn(fpath): try: with open(fpath, 'r') as fin: data = json.load(fin) except: print('Unable to open file {}'.format(fpath)) return -np.ones((16*3,)).astype('int64') res = [] for body in data['bodies']: mpii_joints = -np.ones((16, 3)) joints = np.array(body['joints']) joints = np.reshape(joints, (-1, 3)) joints[joints[..., :] <= 0] = -1 mpii_joints[np.array(mpii_to_coco.keys()), :] = \ joints[np.array(mpii_to_coco.values()), :] res += mpii_joints.reshape((-1,)).tolist() res = np.array(res).astype('int64') return res def read_json_pose(*args): return tf.py_func(read_json_pose_fn, args, tf.int64) def render_objects(*args, **kwargs): with tf.variable_scope('render_objects_pyWrapper'): img = render_objects_fn(*args, **kwargs) img *= 255.0 img = tf.cast(img, tf.uint8) img.set_shape((None, None, kwargs['out_channels'])) return img def extract_glimpse(image, pose_label, orig_im_ht, orig_im_wd, out_side, pad_ratio, parts_keep): # pose label is a [3x16xn,] vector # for now just take the first pose and crop out the human with tf.name_scope('ExtractGlimpse'): pose_label = pose_label[:16*3] pose_label = tf.reshape(pose_label, [16, 3]) if len(parts_keep) > 0: pose_label = tf.gather(pose_label, parts_keep) if len(parts_keep) == 1: # now only one point, but need at least two to make a crop region delta = tf.to_int64( [tf.to_float(tf.shape(image)[-2]) * 0.1, tf.to_float(tf.shape(image)[-3]) * 0.1, 0]) pose_label = tf.stack([ pose_label[0] - delta, pose_label[0] + delta]) pose_label_x = tf.to_float(pose_label[:, 0]) * \ tf.to_float(tf.shape(image)[-2]) / tf.to_float(orig_im_wd) pose_label_y = tf.to_float(pose_label[:, 1]) * \ tf.to_float(tf.shape(image)[-3]) / tf.to_float(orig_im_ht) pose_label = tf.stack([pose_label_y, pose_label_x]) mx_pts = tf.to_int32(tf.reduce_max(pose_label, axis=1)) mn_pts = tf.to_int32(tf.reduce_min( tf.where(tf.greater_equal(pose_label, 0), pose_label, tf.ones(pose_label.get_shape()) * 999999), axis=1)) delta_0 = tf.to_int32(tf.to_float((mx_pts[0] - mn_pts[0])) * pad_ratio) delta_1 = tf.to_int32(tf.to_float((mx_pts[1] - mn_pts[1])) * pad_ratio) mx_pts = mx_pts + [delta_0, delta_1] mn_pts = mn_pts - [delta_0, delta_1] offset_ht = tf.maximum(mn_pts[0], 0) offset_wd = tf.maximum(mn_pts[1], 0) target_ht = tf.minimum(mx_pts[0]-offset_ht, tf.shape(image)[-3]-offset_ht-1) target_wd = tf.minimum(mx_pts[1]-offset_wd, tf.shape(image)[-2]-offset_wd-1) # image = tf.Print(image, [offset_ht, offset_wd, target_ht, target_wd, # tf.shape(image)], "stuff:") image = tf.cond(tf.logical_and( tf.greater(mx_pts[1], mn_pts[1]), tf.greater(mx_pts[0], mn_pts[0])), lambda: tf.image.crop_to_bounding_box( image, offset_ht, offset_wd, target_ht, target_wd), lambda: image) if out_side > 0: image = tf.image.resize_images( image, [out_side, out_side]) return image def read_sparse_label_fn(sparse_label, nclasses): """sparse_label is a string and return a 1D vector with the dense label """ res = np.zeros((nclasses,), dtype='int32') res[np.array([int(el.split(':')[0]) for el in sparse_label.split(',')])] = \ np.array([int(el.split(':')[1]) for el in sparse_label.split(',')]) res[res < 0] = 0 # get rid of -1 label for now return res def read_sparse_label(*args): return tf.py_func(read_sparse_label_fn, args, tf.int32)
[ "tensorflow.maximum", "tensorflow.reshape", "numpy.ones", "tensorflow.greater_equal", "tensorflow.reduce_max", "tensorflow.greater", "os.path.join", "tensorflow.image.crop_to_bounding_box", "tensorflow.gather", "os.path.dirname", "tensorflow.variable_scope", "tensorflow.stack", "tensorflow.c...
[((113, 139), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (129, 139), False, 'import os\n'), ((152, 177), 'os.path.dirname', 'os.path.dirname', (['cur_path'], {}), '(cur_path)\n', (167, 177), False, 'import os\n'), ((1670, 1810), 'collections.OrderedDict', 'OrderedDict', (['[(9, 0), (8, 1), (12, 2), (11, 3), (10, 4), (13, 5), (14, 6), (15, 7), (2, \n 8), (1, 9), (0, 10), (3, 11), (4, 12), (5, 13)]'], {}), '([(9, 0), (8, 1), (12, 2), (11, 3), (10, 4), (13, 5), (14, 6), (\n 15, 7), (2, 8), (1, 9), (0, 10), (3, 11), (4, 12), (5, 13)])\n', (1681, 1810), False, 'from collections import OrderedDict\n'), ((2472, 2517), 'tensorflow.py_func', 'tf.py_func', (['read_json_pose_fn', 'args', 'tf.int64'], {}), '(read_json_pose_fn, args, tf.int64)\n', (2482, 2517), True, 'import tensorflow as tf\n'), ((5140, 5176), 'numpy.zeros', 'np.zeros', (['(nclasses,)'], {'dtype': '"""int32"""'}), "((nclasses,), dtype='int32')\n", (5148, 5176), True, 'import numpy as np\n'), ((5433, 5481), 'tensorflow.py_func', 'tf.py_func', (['read_sparse_label_fn', 'args', 'tf.int32'], {}), '(read_sparse_label_fn, args, tf.int32)\n', (5443, 5481), True, 'import tensorflow as tf\n'), ((260, 305), 'os.path.join', 'os.path.join', (['ROOT_PATH', '"""pose_to_heatmap.so"""'], {}), "(ROOT_PATH, 'pose_to_heatmap.so')\n", (272, 305), False, 'import os\n'), ((368, 415), 'os.path.join', 'os.path.join', (['ROOT_PATH', '"""zero_out_channels.so"""'], {}), "(ROOT_PATH, 'zero_out_channels.so')\n", (380, 415), False, 'import os\n'), ((474, 515), 'os.path.join', 'os.path.join', (['ROOT_PATH', '"""render_pose.so"""'], {}), "(ROOT_PATH, 'render_pose.so')\n", (486, 515), False, 'import os\n'), ((571, 615), 'os.path.join', 'os.path.join', (['ROOT_PATH', '"""render_objects.so"""'], {}), "(ROOT_PATH, 'render_objects.so')\n", (583, 615), False, 'import os\n'), ((678, 724), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""pose_to_heatmap_pyWrapper"""'], {}), "('pose_to_heatmap_pyWrapper')\n", (695, 724), True, 'import tensorflow as tf\n'), ((961, 988), 'tensorflow.cast', 'tf.cast', (['pose_img', 'tf.uint8'], {}), '(pose_img, tf.uint8)\n', (968, 988), True, 'import tensorflow as tf\n'), ((1067, 1115), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""zero_out_channels_pyWrapper"""'], {}), "('zero_out_channels_pyWrapper')\n", (1084, 1115), True, 'import tensorflow as tf\n'), ((1208, 1250), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""render_pose_pyWrapper"""'], {}), "('render_pose_pyWrapper')\n", (1225, 1250), True, 'import tensorflow as tf\n'), ((1550, 1572), 'tensorflow.cast', 'tf.cast', (['img', 'tf.uint8'], {}), '(img, tf.uint8)\n', (1557, 1572), True, 'import tensorflow as tf\n'), ((2131, 2155), 'numpy.array', 'np.array', (["body['joints']"], {}), "(body['joints'])\n", (2139, 2155), True, 'import numpy as np\n'), ((2169, 2196), 'numpy.reshape', 'np.reshape', (['joints', '(-1, 3)'], {}), '(joints, (-1, 3))\n', (2179, 2196), True, 'import numpy as np\n'), ((2563, 2608), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""render_objects_pyWrapper"""'], {}), "('render_objects_pyWrapper')\n", (2580, 2608), True, 'import tensorflow as tf\n'), ((2682, 2704), 'tensorflow.cast', 'tf.cast', (['img', 'tf.uint8'], {}), '(img, tf.uint8)\n', (2689, 2704), True, 'import tensorflow as tf\n'), ((2996, 3027), 'tensorflow.name_scope', 'tf.name_scope', (['"""ExtractGlimpse"""'], {}), "('ExtractGlimpse')\n", (3009, 3027), True, 'import tensorflow as tf\n'), ((3081, 3112), 'tensorflow.reshape', 'tf.reshape', (['pose_label', '[16, 3]'], {}), '(pose_label, [16, 3])\n', (3091, 3112), True, 'import tensorflow as tf\n'), ((3766, 3804), 'tensorflow.stack', 'tf.stack', (['[pose_label_y, pose_label_x]'], {}), '([pose_label_y, pose_label_x])\n', (3774, 3804), True, 'import tensorflow as tf\n'), ((4283, 4307), 'tensorflow.maximum', 'tf.maximum', (['mn_pts[0]', '(0)'], {}), '(mn_pts[0], 0)\n', (4293, 4307), True, 'import tensorflow as tf\n'), ((4324, 4348), 'tensorflow.maximum', 'tf.maximum', (['mn_pts[1]', '(0)'], {}), '(mn_pts[1], 0)\n', (4334, 4348), True, 'import tensorflow as tf\n'), ((1921, 1935), 'json.load', 'json.load', (['fin'], {}), '(fin)\n', (1930, 1935), False, 'import json\n'), ((2101, 2117), 'numpy.ones', 'np.ones', (['(16, 3)'], {}), '((16, 3))\n', (2108, 2117), True, 'import numpy as np\n'), ((2392, 2405), 'numpy.array', 'np.array', (['res'], {}), '(res)\n', (2400, 2405), True, 'import numpy as np\n'), ((3160, 3193), 'tensorflow.gather', 'tf.gather', (['pose_label', 'parts_keep'], {}), '(pose_label, parts_keep)\n', (3169, 3193), True, 'import tensorflow as tf\n'), ((3443, 3499), 'tensorflow.stack', 'tf.stack', (['[pose_label[0] - delta, pose_label[0] + delta]'], {}), '([pose_label[0] - delta, pose_label[0] + delta])\n', (3451, 3499), True, 'import tensorflow as tf\n'), ((3605, 3628), 'tensorflow.to_float', 'tf.to_float', (['orig_im_wd'], {}), '(orig_im_wd)\n', (3616, 3628), True, 'import tensorflow as tf\n'), ((3725, 3748), 'tensorflow.to_float', 'tf.to_float', (['orig_im_ht'], {}), '(orig_im_ht)\n', (3736, 3748), True, 'import tensorflow as tf\n'), ((3830, 3863), 'tensorflow.reduce_max', 'tf.reduce_max', (['pose_label'], {'axis': '(1)'}), '(pose_label, axis=1)\n', (3843, 3863), True, 'import tensorflow as tf\n'), ((4923, 4974), 'tensorflow.image.resize_images', 'tf.image.resize_images', (['image', '[out_side, out_side]'], {}), '(image, [out_side, out_side])\n', (4945, 4974), True, 'import tensorflow as tf\n'), ((3528, 3557), 'tensorflow.to_float', 'tf.to_float', (['pose_label[:, 0]'], {}), '(pose_label[:, 0])\n', (3539, 3557), True, 'import tensorflow as tf\n'), ((3648, 3677), 'tensorflow.to_float', 'tf.to_float', (['pose_label[:, 1]'], {}), '(pose_label[:, 1])\n', (3659, 3677), True, 'import tensorflow as tf\n'), ((4058, 4092), 'tensorflow.to_float', 'tf.to_float', (['(mx_pts[0] - mn_pts[0])'], {}), '(mx_pts[0] - mn_pts[0])\n', (4069, 4092), True, 'import tensorflow as tf\n'), ((4134, 4168), 'tensorflow.to_float', 'tf.to_float', (['(mx_pts[1] - mn_pts[1])'], {}), '(mx_pts[1] - mn_pts[1])\n', (4145, 4168), True, 'import tensorflow as tf\n'), ((4687, 4719), 'tensorflow.greater', 'tf.greater', (['mx_pts[1]', 'mn_pts[1]'], {}), '(mx_pts[1], mn_pts[1])\n', (4697, 4719), True, 'import tensorflow as tf\n'), ((4727, 4759), 'tensorflow.greater', 'tf.greater', (['mx_pts[0]', 'mn_pts[0]'], {}), '(mx_pts[0], mn_pts[0])\n', (4737, 4759), True, 'import tensorflow as tf\n'), ((4776, 4861), 'tensorflow.image.crop_to_bounding_box', 'tf.image.crop_to_bounding_box', (['image', 'offset_ht', 'offset_wd', 'target_ht', 'target_wd'], {}), '(image, offset_ht, offset_wd, target_ht, target_wd\n )\n', (4805, 4861), True, 'import tensorflow as tf\n'), ((3920, 3951), 'tensorflow.greater_equal', 'tf.greater_equal', (['pose_label', '(0)'], {}), '(pose_label, 0)\n', (3936, 3951), True, 'import tensorflow as tf\n'), ((2008, 2026), 'numpy.ones', 'np.ones', (['(16 * 3,)'], {}), '((16 * 3,))\n', (2015, 2026), True, 'import numpy as np\n'), ((3582, 3597), 'tensorflow.shape', 'tf.shape', (['image'], {}), '(image)\n', (3590, 3597), True, 'import tensorflow as tf\n'), ((3702, 3717), 'tensorflow.shape', 'tf.shape', (['image'], {}), '(image)\n', (3710, 3717), True, 'import tensorflow as tf\n'), ((4397, 4412), 'tensorflow.shape', 'tf.shape', (['image'], {}), '(image)\n', (4405, 4412), True, 'import tensorflow as tf\n'), ((4478, 4493), 'tensorflow.shape', 'tf.shape', (['image'], {}), '(image)\n', (4486, 4493), True, 'import tensorflow as tf\n'), ((3343, 3358), 'tensorflow.shape', 'tf.shape', (['image'], {}), '(image)\n', (3351, 3358), True, 'import tensorflow as tf\n'), ((3392, 3407), 'tensorflow.shape', 'tf.shape', (['image'], {}), '(image)\n', (3400, 3407), True, 'import tensorflow as tf\n')]
""" Authors: <NAME> Contact : https://adityajain.me """ import numpy as np class KNeighborsClassifier(): """ K Nearest Neighbors Classifier which classifies sample point based on majority of k nearby sample classes Parameters ---------- n_neighbors : integer (Default 5), number of neighbors to consider metric : str ( 'minkowski', 'euclidean', 'manhatten' ) (Default : 'minkowski') p : integer (Default 2), metric used in minkowski distance normalize : boolean, normalize data before calculating distance """ def __init__(self, n_neighbors=5, metric='minkowski', p=2, normalize=False): self.__n_neighbors = n_neighbors self.__X = None self.__y = None self.__normalize = normalize self.__metric = { 'minkowski': self.__minkowski, 'euclidean':self.__euclidean, 'manhatten':self.__manhatten }[metric] self.__p = p self.__n_classes = None self.__means = None self.__std = None def __euclidean(self,X1,X2): return np.sqrt(np.sum(np.square(X1-X2),axis=1)) def __manhatten(self,X1,X2): return np.sum(np.abs(X1-X2),axis=1) def __minkowski(self,X1,X2): return np.power(np.sum(np.power(np.abs(X1-X2),self.__p),axis=1),1/self.__p) def __normalizeX(self,X): return (X-self.__means)/self.__std def fit(self,X,y): """ Fit X using y Parameters ---------- X : 2D numpy array, independent variables y : 1D numpy array, dependent variable """ self.__y, self.__n_classes = y, len(np.unique(y)) if self.__normalize: self.__means, self.__std = X.mean(axis=0), X.std(axis=0) self.__X = self.__normalizeX(X) else: self.__X = X def predict_proba(self,X): """ Predict probability of all classes Parameters ---------- X : numpy array, independent variables Returns ------- predicted probabilities """ if self.__normalize: X = self.__normalizeX(X) probs = [] for sample in X: x = np.expand_dims(sample,axis=0) distances = self.__metric(self.__X, x) top_k_index = distances.argsort()[:self.__n_neighbors] prob = np.zeros(self.__n_classes) cls,cnts = np.unique(self.__y[top_k_index], return_counts=True) for cl,cn in zip(cls,cnts): prob[cl] = cn/sum(cnts) probs.append(prob) return np.array(probs) def predict(self,X): """ Predict dependent variable Parameters --------- X : numpy array, independent variables Returns ------- Predicted classes """ return np.argmax( self.predict_proba(X), axis=1 ) def score(self,X,y): """ Calculate accuracy from independent variables Parameters ---------- X : numpy array, independent variables y : numpy array, dependent variable Returns ------- accuracy score """ return (y==self.predict(X)).sum()/len(y)
[ "numpy.abs", "numpy.square", "numpy.zeros", "numpy.expand_dims", "numpy.array", "numpy.unique" ]
[((2204, 2219), 'numpy.array', 'np.array', (['probs'], {}), '(probs)\n', (2212, 2219), True, 'import numpy as np\n'), ((1039, 1054), 'numpy.abs', 'np.abs', (['(X1 - X2)'], {}), '(X1 - X2)\n', (1045, 1054), True, 'import numpy as np\n'), ((1883, 1913), 'numpy.expand_dims', 'np.expand_dims', (['sample'], {'axis': '(0)'}), '(sample, axis=0)\n', (1897, 1913), True, 'import numpy as np\n'), ((2024, 2050), 'numpy.zeros', 'np.zeros', (['self.__n_classes'], {}), '(self.__n_classes)\n', (2032, 2050), True, 'import numpy as np\n'), ((2065, 2117), 'numpy.unique', 'np.unique', (['self.__y[top_k_index]'], {'return_counts': '(True)'}), '(self.__y[top_k_index], return_counts=True)\n', (2074, 2117), True, 'import numpy as np\n'), ((966, 984), 'numpy.square', 'np.square', (['(X1 - X2)'], {}), '(X1 - X2)\n', (975, 984), True, 'import numpy as np\n'), ((1442, 1454), 'numpy.unique', 'np.unique', (['y'], {}), '(y)\n', (1451, 1454), True, 'import numpy as np\n'), ((1126, 1141), 'numpy.abs', 'np.abs', (['(X1 - X2)'], {}), '(X1 - X2)\n', (1132, 1141), True, 'import numpy as np\n')]
"""TFRecords data-loader for audiovisual datasets.""" import functools from typing import Dict, Iterator, List, Optional, Text, Tuple, Union from absl import logging from dmvr import modalities as load_modalities from flax import jax_utils import jax import jax.numpy as jnp import ml_collections import numpy as np from scenic.dataset_lib import dataset_utils from scenic.dataset_lib import datasets from scenic.dataset_lib import video_ops from scenic.projects.mbt.datasets.dataset_utils import add_spectrogram from scenic.projects.vivit.data import video_tfrecord_dataset import tensorflow as tf # Aliases for custom types: Batch = Dict[str, jnp.ndarray] def maybe_pad_batch(batch, train, batch_size, return_as_dict): """Zero pad the batch on the right to the batch_size.""" if not return_as_dict: return dataset_utils.maybe_pad_batch(batch, train, batch_size) assert 'batch_mask' not in batch if 'rgb' in batch['inputs']: unpadded_mask_shape = batch['inputs']['rgb'].shape[0] batch_pad = batch_size - unpadded_mask_shape elif 'spectrogram' in batch['inputs']: unpadded_mask_shape = batch['inputs']['spectrogram'].shape[0] batch_pad = batch_size - unpadded_mask_shape else: raise ValueError('invalid input batch') if train and batch_pad != 0: raise ValueError('In this codebase, we assumed that we always drop the ' 'last partial batch of the train set. Please use ' '` drop_remainder=True` for the training set.') # Most batches will not need padding so we quickly return to avoid slowdown. if train or batch_pad == 0: if 'batch_mask' not in batch: batch['batch_mask'] = np.ones(unpadded_mask_shape, dtype=np.float32) return batch def zero_pad(array): pad_with = [(0, batch_pad)] + [(0, 0)] * (array.ndim - 1) return np.pad(array, pad_with, mode='constant') padded_batch = jax.tree_map(zero_pad, batch) padded_batch_mask = zero_pad(np.ones(unpadded_mask_shape, dtype=np.float32)) padded_batch['batch_mask'] = padded_batch_mask return padded_batch class AVTFRecordDatasetFactory(video_tfrecord_dataset.TFRecordDatasetFactory): """Reader for TFRecords using the MediaSequence format. The TFrecords already contain images and spectrograms. Spectrograms are extracted per second and stored with size 128x100 for each second of audio. """ _MODALITIES = ('rgb', 'spectrogram') def __init__(self, base_dir: str, tables: Dict[str, Union[str, List[str]]], num_classes: int, examples_per_subset: Dict[str, int], subset: str = 'train', modalities: Tuple[str] = ('rgb',), prop_data: float = 1.0, num_groups: Optional[int] = None, group_index: Optional[int] = None): """Initializes the instance of TFRecordDatasetFactory. Initializes a data-loader using DeepMind Video Reader (DMVR) pre-processing (https://github.com/deepmind/dmvr). TFRecords are assumed to consist of tf.SequenceExample protocol buffers in the MediaSequence (https://github.com/google/mediapipe/tree/master/mediapipe/util/sequence) format. Args: base_dir: The base directory of the TFRecords. tables: A dictionary mapping the subset name (train, val or test) to the relative path of the SSTable containing them. Follows DMVR convention. The values of the dictionary can either be a string or a list. If it is a string, it specifies all the shards in the SSTable. Example - "/path/to/sstable@10". If passing a list, each entry is a shard of the SSTable. Example - "[/path/to/sstable_shard_1_of_10, ..., /path/to/sstabble_shard_10_of_10]." The latter scenario is useful for debugging. num_classes: The number of classes in the dataset. examples_per_subset: A dictionary mapping the subset name (train, val or test) to the number of examples in the dataset for that subset. subset: The subset of the dataset to load. Must be a key of "tables" modalities: Which modality to load. Currently supports 'rgb' and 'spectrogram' prop_data: The proportion of the data to load. If less than 1.0, this proportion of the total TFRecord shards are read. num_groups: If specified will reshard the data according to `num_groups`. A `group_index` should be specified if using `num_groups`. group_index: Index of the shard to return after resharding. `num_groups` should be specified if using `group_index`. This is useful in distributed setting where one wants to ensure that different data is read by different workers. """ for modality in modalities: if modality not in AVTFRecordDatasetFactory._MODALITIES: raise ValueError('Invalid modality %s.' % modality) self._modalities = modalities super().__init__( base_dir=base_dir, tables=tables, examples_per_subset=examples_per_subset, subset=subset, num_classes=num_classes, fraction_data=prop_data, num_groups=num_groups, group_index=group_index) def _build( self, is_training: bool = True, # Video related parameters. num_frames: int = 32, stride: int = 1, num_spec_frames: int = 5, spec_stride: int = 1, dataset_spec_mean: float = 0., dataset_spec_stddev: float = 1., num_test_clips: int = 1, min_resize: int = 256, crop_size: int = 224, # Audio related parameters. spec_shape: Tuple[int, int] = (100, 128), spec_augment: bool = False, spec_augment_params=None, zero_centering_image: bool = False, # Label related parameters. one_hot_label: bool = True, get_label_str: bool = False): """Adds DMVR pre-processors to the dataset. Args: is_training: whether or not in training mode. num_frames: number of frames per subclip. stride: temporal stride to sample frames. num_spec_frames: number of spectrogram frames. spec_stride: stride to sample spectrogram. dataset_spec_mean: Mean of spectrograms in the dataset. dataset_spec_stddev: Std dev of spectrograms in the dataset. num_test_clips: number of test clip (1 by default). If more than one, this will sample multiple linearly spaced clips within each video at test time. If 1, then a single clip in the middle of the video is sampled. min_resize: frames are resized so that min width/height is min_resize. crop_size: final size of the frame after cropping the resized frames. spec_shape: input size of spectrogram per frame. spec_augment: whether to apply augmentation using SpecAugment. spec_augment_params: parameters for SpecAugment. zero_centering_image: whether to have images between [-1, 1] or [0, 1]. one_hot_label: whether or not to return one hot version of labels. get_label_str: whether or not to return label as text. """ # We set sync_random_state to True so that sample_offset_proportion is # the same for all modalities. if 'rgb' in self._modalities: load_modalities.add_image( parser_builder=self.parser_builder, sampler_builder=self.sampler_builder, decoder_builder=self.decoder_builder, preprocessor_builder=self.preprocessor_builder, postprocessor_builder=self.postprocessor_builder, is_training=is_training, num_frames=num_frames, stride=stride, num_test_clips=num_test_clips, min_resize=min_resize, crop_size=crop_size, zero_centering_image=zero_centering_image, sync_random_state=True) if 'spectrogram' in self._modalities: add_spectrogram( parser_builder=self.parser_builder, sampler_builder=self.sampler_builder, decoder_builder=self.decoder_builder, preprocessor_builder=self.preprocessor_builder, postprocessor_builder=self.postprocessor_builder, input_shape=spec_shape, is_training=is_training, num_frames=num_spec_frames, stride=spec_stride, num_test_clips=num_test_clips, spec_augment=spec_augment, spec_augment_params=spec_augment_params, zero_centering_image=zero_centering_image, dataset_mean=dataset_spec_mean, dataset_stddev=dataset_spec_stddev, sync_random_state=True) load_modalities.add_label( parser_builder=self.parser_builder, decoder_builder=self.decoder_builder, preprocessor_builder=self.preprocessor_builder, is_multi_label=False, one_hot_label=True, num_classes=self.num_classes, add_label_name=False) def load_split_from_dmvr(ds_factory, batch_size, subset='train', modalities=('rgb'), num_frames=32, stride=2, num_spec_frames=5, spec_stride=1, num_test_clips=1, min_resize=256, crop_size=224, spec_shape=(100, 128), dataset_spec_mean=0., dataset_spec_stddev=1., spec_augment=False, spec_augment_params=None, one_hot_label=True, zero_centering=True, get_label_str=False, augmentation_params=None, keep_key=False): """Loads dataset using DMVR for pre-processing. DMVR dataset loader already does basic augmentation (random crop and flip in train mode. It also already shuffles and batches the data. Args: ds_factory: A DMVR factory to instantiate with the subset. batch_size: The batch_size to use. subset: train, validation or test. modalities: list of input modalities. num_frames: Number of RGB frames per subclip. stride: Temporal stride to sample RGB frames. num_spec_frames: Number of spectrogram frames per subclip. spec_stride: Temporal stride to sample spectrogram. num_test_clips: Number of test clips (1 by default). If more than 1, this will sample multiple linearly spaced clips within each video at test time. If 1, then a single clip in the middle of the video is sampled. The clips are aggreagated in the batch dimension. min_resize: Frames are resized so that min(height, width) is min_resize. crop_size: Final size of the frame after cropping the resized frames. Both height and width are the same. spec_shape: Input size of spectrogram per frame. dataset_spec_mean: Mean of spectrograms in the dataset. dataset_spec_stddev: Std dev of spectrograms in the dataset. spec_augment: whether to apply augmentation using SpecAugment. spec_augment_params: dict; augmentation configurations for SpecAugment one_hot_label: If True, return one-hot version of the labels (ie [N, C]) array. Otherwise, return [N]-dimensional array of labels. zero_centering: If True, frames are normalized to values in [-1, 1]. If False, values in [0, 1]. get_label_str: whether or not to return label as text. This does not work on TPU!. augmentation_params: dict; augmentation configurations in train mode. keep_key: bool; If true, also return the key for each example. Returns: A pair `(ds, num_examples)` with ds: A `tf.data.Dataset` object num_examples: Number of examples in the dataset. """ is_training = (subset == 'train') ds_factory = ds_factory( subset=subset, modalities=modalities).configure( is_training=is_training, num_frames=num_frames, stride=stride, num_spec_frames=num_spec_frames, spec_stride=spec_stride, num_test_clips=num_test_clips, min_resize=min_resize, crop_size=crop_size, spec_shape=spec_shape, dataset_spec_mean=dataset_spec_mean, dataset_spec_stddev=dataset_spec_stddev, spec_augment=spec_augment, spec_augment_params=spec_augment_params, zero_centering_image=zero_centering, one_hot_label=one_hot_label, get_label_str=get_label_str) if 'rgb' in modalities and is_training and augmentation_params: # additional augmentation for the RGB features. ds_factory = video_ops.additional_augmentations(ds_factory, augmentation_params, crop_size, num_frames, zero_centering) logging.info('Preprocessing graph: %s', ds_factory.preprocessor_builder.get_summary()) logging.info('Postprocessing graph: %s', ds_factory.postprocessor_builder.get_summary()) num_examples = ds_factory.num_examples ds = ds_factory.make_dataset( batch_size=batch_size, shuffle=is_training, num_epochs=None if is_training else 1, drop_remainder=is_training, keep_key=(not is_training and keep_key)) if not is_training: ds = ds.repeat(None) options = tf.data.Options() options.experimental_threading.private_threadpool_size = 48 ds = ds.with_options(options) return ds, num_examples def map_keys(batch, modalities=('rgb'), return_as_dict=False): """DMVR dataset returns 'image' and 'label'. We want 'inputs' and 'label'.""" if not return_as_dict: if len(modalities) == 1 and modalities[0] == 'rgb': batch['inputs'] = batch['image'] elif len(modalities) == 1 and modalities[0] == 'spectrogram': batch['inputs'] = batch['spectrogram'] else: raise NotImplementedError('modality not supported by map_keys.') else: batch['inputs'] = {} if 'rgb' in modalities: batch['inputs']['rgb'] = batch['image'] if 'spectrogram' in modalities: batch['inputs']['spectrogram'] = batch['spectrogram'] return batch def tile_label_key(batch, return_as_dict=False): """Tile labels and keys to match input videos when num_test_clips > 1. When multiple test crops are used (ie num_test_clips > 1), the batch dimension of batch['inputs'] = test_batch_size * num_test_clips. However, labels and keys remain of size [test_batch_size]. This function repeats label and key to match the inputs. Args: batch: Batch from iterator return_as_dict: Whether to return multimodal inputs as a dictionary. Returns: batch: Batch with 'label' and 'key' tiled to match 'inputs'. """ if not return_as_dict: n_repeats = batch['inputs'].shape[0] // batch['label'].shape[0] elif 'rgb' in batch['inputs']: n_repeats = batch['inputs']['rgb'].shape[0] // batch['label'].shape[0] elif 'spectrogram' in batch['inputs']: n_repeats = ( batch['inputs']['spectrogram'].shape[0] // batch['label'].shape[0]) batch['label'] = np.repeat(batch['label'], n_repeats, axis=0) if 'key' in batch: batch['key'] = np.repeat(batch['key'], n_repeats, axis=0) return batch @datasets.add_dataset('audiovisual_tfrecord_dataset') def get_dataset( *, batch_size, eval_batch_size, num_shards, dtype_str='float32', shuffle_seed=0, # pylint:disable=unused-argument rng=None, dataset_configs: ml_collections.ConfigDict, dataset_service_address: Optional[str] = None): """Returns a generator for the audiovisual dataset.""" del rng modalities = dataset_configs.get('modalities', ['rgb']) return_as_dict = dataset_configs.get('return_as_dict', False) # RGB related configs. num_frames = dataset_configs.get('num_frames', 32) stride = dataset_configs.get('stride', 2) min_resize = dataset_configs.get('min_resize', 256) crop_size = dataset_configs.get('crop_size', 224) # Spectrogram related configs. num_spec_frames = dataset_configs.get('num_spec_frames', 5) spec_stride = dataset_configs.get('spec_stride', 1) spec_shape = dataset_configs.get('spec_shape', (100, 128)) spec_augment = dataset_configs.get('spec_augment', False) spec_augment_params = dataset_configs.get('spec_augment_params', None) dataset_spec_mean = dataset_configs.get('spec_mean', 0.) dataset_spec_stddev = dataset_configs.get('spec_stddev', 1.) # General configs. num_test_clips = dataset_configs.get('num_test_clips', 1) one_hot_label = dataset_configs.get('one_hot_label', True) zero_centre_data = dataset_configs.get('zero_centering', True) augmentation_params = dataset_configs.get('augmentation_params', None) num_train_val_clips = dataset_configs.get('num_train_val_clips', 1) do_three_spatial_crops = dataset_configs.get('do_three_spatial_crops', False) num_spatial_crops = 3 if do_three_spatial_crops else 1 keep_test_key = dataset_configs.get('keep_test_key', False) test_split = dataset_configs.get('test_split', 'test') # For the test set, the actual batch size is # test_batch_size * num_test_clips test_batch_size = dataset_configs.get('test_batch_size', eval_batch_size) def validate_config(field): if dataset_configs.get(field) is None: raise ValueError(f'{field} must be specified for TFRecord dataset.') validate_config('base_dir') validate_config('tables') validate_config('examples_per_subset') validate_config('num_classes') ds_factory = functools.partial( AVTFRecordDatasetFactory, base_dir=dataset_configs.base_dir, tables=dataset_configs.tables, examples_per_subset=dataset_configs.examples_per_subset, num_classes=dataset_configs.num_classes, num_groups=jax.process_count(), group_index=jax.process_index()) def create_dataset_iterator( subset: Text, batch_size_local: int, num_clips: int, keep_key_local: bool = False) -> Tuple[Iterator[Batch], int]: is_training = subset == 'train' is_test = subset == 'test' logging.info('Loading split %s', subset) dataset, num_examples = load_split_from_dmvr( ds_factory, batch_size=batch_size_local, subset=subset, modalities=modalities, num_frames=num_frames, stride=stride, num_spec_frames=num_spec_frames, spec_stride=spec_stride, num_test_clips=num_clips, min_resize=min_resize, crop_size=crop_size, spec_shape=spec_shape, dataset_spec_mean=dataset_spec_mean, dataset_spec_stddev=dataset_spec_stddev, spec_augment=spec_augment, spec_augment_params=spec_augment_params, one_hot_label=one_hot_label, zero_centering=zero_centre_data, augmentation_params=augmentation_params, keep_key=keep_key_local) if dataset_service_address and is_training: if shuffle_seed is not None: raise ValueError('Using dataset service with a random seed causes each ' 'worker to produce exactly the same data. Add ' 'config.shuffle_seed = None to your config if you ' 'want to run with dataset service.') logging.info('Using the tf.data service at %s', dataset_service_address) dataset = dataset_utils.distribute(dataset, dataset_service_address) pad_batch_size = batch_size_local if is_test: pad_batch_size = batch_size_local * num_clips * num_spatial_crops maybe_pad_batches = functools.partial( maybe_pad_batch, train=is_training, batch_size=pad_batch_size, return_as_dict=return_as_dict) shard_batches = functools.partial(dataset_utils.shard, n_devices=num_shards) current_iter = iter(dataset) current_iter = map(dataset_utils.tf_to_numpy, current_iter) current_iter = map( functools.partial( map_keys, modalities=modalities, return_as_dict=return_as_dict), current_iter) current_iter = map( functools.partial( tile_label_key, return_as_dict=return_as_dict), current_iter) current_iter = map(maybe_pad_batches, current_iter) if augmentation_params and augmentation_params.get('do_mixup', False): raise ValueError('mixup should be done in the trainer.') current_iter = map(shard_batches, current_iter) if is_training and dataset_configs.get('prefetch_to_device'): # Async bind batch to device which speeds up training. current_iter = jax_utils.prefetch_to_device( current_iter, dataset_configs.get('prefetch_to_device')) return current_iter, num_examples train_iter, n_train_examples = create_dataset_iterator( 'train', batch_size, num_train_val_clips) eval_iter, n_eval_examples = create_dataset_iterator('validation', eval_batch_size, num_train_val_clips) test_iter, n_test_examples = create_dataset_iterator(test_split, test_batch_size, num_test_clips, keep_test_key) meta_data = { 'num_classes': dataset_configs.num_classes, # pylint:disable=protected-access 'num_train_examples': (n_train_examples * num_train_val_clips), 'num_eval_examples': (n_eval_examples * num_train_val_clips), 'num_test_examples': (n_test_examples * num_test_clips * num_spatial_crops), 'input_dtype': getattr(jnp, dtype_str), 'target_is_onehot': True, } if return_as_dict: meta_data['input_shape'] = { 'rgb': (-1, num_frames, crop_size, crop_size, 3), 'spectrogram': (-1, num_spec_frames * spec_shape[0], spec_shape[1], 3) } elif len(modalities) == 1 and modalities[0] == 'rgb': meta_data['input_shape'] = (-1, num_frames, crop_size, crop_size, 3) elif len(modalities) == 1 and modalities[0] == 'spectrogram': meta_data['input_shape'] = (-1, num_spec_frames * spec_shape[0], spec_shape[1], 3) else: raise NotImplementedError('modality not supported') logging.info('Dataset metadata:\n%s', meta_data) return dataset_utils.Dataset(train_iter, eval_iter, test_iter, meta_data)
[ "numpy.pad", "functools.partial", "scenic.projects.mbt.datasets.dataset_utils.add_spectrogram", "scenic.dataset_lib.datasets.add_dataset", "dmvr.modalities.add_label", "numpy.ones", "scenic.dataset_lib.dataset_utils.distribute", "absl.logging.info", "jax.process_count", "tensorflow.data.Options", ...
[((15405, 15457), 'scenic.dataset_lib.datasets.add_dataset', 'datasets.add_dataset', (['"""audiovisual_tfrecord_dataset"""'], {}), "('audiovisual_tfrecord_dataset')\n", (15425, 15457), False, 'from scenic.dataset_lib import datasets\n'), ((1900, 1929), 'jax.tree_map', 'jax.tree_map', (['zero_pad', 'batch'], {}), '(zero_pad, batch)\n', (1912, 1929), False, 'import jax\n'), ((13511, 13528), 'tensorflow.data.Options', 'tf.data.Options', ([], {}), '()\n', (13526, 13528), True, 'import tensorflow as tf\n'), ((15259, 15303), 'numpy.repeat', 'np.repeat', (["batch['label']", 'n_repeats'], {'axis': '(0)'}), "(batch['label'], n_repeats, axis=0)\n", (15268, 15303), True, 'import numpy as np\n'), ((22441, 22492), 'absl.logging.info', 'logging.info', (['"""Dataset metadata:\n%s"""', 'meta_data'], {}), '("""Dataset metadata:\n%s""", meta_data)\n', (22453, 22492), False, 'from absl import logging\n'), ((22500, 22566), 'scenic.dataset_lib.dataset_utils.Dataset', 'dataset_utils.Dataset', (['train_iter', 'eval_iter', 'test_iter', 'meta_data'], {}), '(train_iter, eval_iter, test_iter, meta_data)\n', (22521, 22566), False, 'from scenic.dataset_lib import dataset_utils\n'), ((820, 875), 'scenic.dataset_lib.dataset_utils.maybe_pad_batch', 'dataset_utils.maybe_pad_batch', (['batch', 'train', 'batch_size'], {}), '(batch, train, batch_size)\n', (849, 875), False, 'from scenic.dataset_lib import dataset_utils\n'), ((1841, 1881), 'numpy.pad', 'np.pad', (['array', 'pad_with'], {'mode': '"""constant"""'}), "(array, pad_with, mode='constant')\n", (1847, 1881), True, 'import numpy as np\n'), ((1961, 2007), 'numpy.ones', 'np.ones', (['unpadded_mask_shape'], {'dtype': 'np.float32'}), '(unpadded_mask_shape, dtype=np.float32)\n', (1968, 2007), True, 'import numpy as np\n'), ((8599, 8853), 'dmvr.modalities.add_label', 'load_modalities.add_label', ([], {'parser_builder': 'self.parser_builder', 'decoder_builder': 'self.decoder_builder', 'preprocessor_builder': 'self.preprocessor_builder', 'is_multi_label': '(False)', 'one_hot_label': '(True)', 'num_classes': 'self.num_classes', 'add_label_name': '(False)'}), '(parser_builder=self.parser_builder,\n decoder_builder=self.decoder_builder, preprocessor_builder=self.\n preprocessor_builder, is_multi_label=False, one_hot_label=True,\n num_classes=self.num_classes, add_label_name=False)\n', (8624, 8853), True, 'from dmvr import modalities as load_modalities\n'), ((12719, 12829), 'scenic.dataset_lib.video_ops.additional_augmentations', 'video_ops.additional_augmentations', (['ds_factory', 'augmentation_params', 'crop_size', 'num_frames', 'zero_centering'], {}), '(ds_factory, augmentation_params,\n crop_size, num_frames, zero_centering)\n', (12753, 12829), False, 'from scenic.dataset_lib import video_ops\n'), ((15344, 15386), 'numpy.repeat', 'np.repeat', (["batch['key']", 'n_repeats'], {'axis': '(0)'}), "(batch['key'], n_repeats, axis=0)\n", (15353, 15386), True, 'import numpy as np\n'), ((18232, 18272), 'absl.logging.info', 'logging.info', (['"""Loading split %s"""', 'subset'], {}), "('Loading split %s', subset)\n", (18244, 18272), False, 'from absl import logging\n'), ((19707, 19823), 'functools.partial', 'functools.partial', (['maybe_pad_batch'], {'train': 'is_training', 'batch_size': 'pad_batch_size', 'return_as_dict': 'return_as_dict'}), '(maybe_pad_batch, train=is_training, batch_size=\n pad_batch_size, return_as_dict=return_as_dict)\n', (19724, 19823), False, 'import functools\n'), ((19873, 19933), 'functools.partial', 'functools.partial', (['dataset_utils.shard'], {'n_devices': 'num_shards'}), '(dataset_utils.shard, n_devices=num_shards)\n', (19890, 19933), False, 'import functools\n'), ((1680, 1726), 'numpy.ones', 'np.ones', (['unpadded_mask_shape'], {'dtype': 'np.float32'}), '(unpadded_mask_shape, dtype=np.float32)\n', (1687, 1726), True, 'import numpy as np\n'), ((7256, 7723), 'dmvr.modalities.add_image', 'load_modalities.add_image', ([], {'parser_builder': 'self.parser_builder', 'sampler_builder': 'self.sampler_builder', 'decoder_builder': 'self.decoder_builder', 'preprocessor_builder': 'self.preprocessor_builder', 'postprocessor_builder': 'self.postprocessor_builder', 'is_training': 'is_training', 'num_frames': 'num_frames', 'stride': 'stride', 'num_test_clips': 'num_test_clips', 'min_resize': 'min_resize', 'crop_size': 'crop_size', 'zero_centering_image': 'zero_centering_image', 'sync_random_state': '(True)'}), '(parser_builder=self.parser_builder,\n sampler_builder=self.sampler_builder, decoder_builder=self.\n decoder_builder, preprocessor_builder=self.preprocessor_builder,\n postprocessor_builder=self.postprocessor_builder, is_training=\n is_training, num_frames=num_frames, stride=stride, num_test_clips=\n num_test_clips, min_resize=min_resize, crop_size=crop_size,\n zero_centering_image=zero_centering_image, sync_random_state=True)\n', (7281, 7723), True, 'from dmvr import modalities as load_modalities\n'), ((7876, 8469), 'scenic.projects.mbt.datasets.dataset_utils.add_spectrogram', 'add_spectrogram', ([], {'parser_builder': 'self.parser_builder', 'sampler_builder': 'self.sampler_builder', 'decoder_builder': 'self.decoder_builder', 'preprocessor_builder': 'self.preprocessor_builder', 'postprocessor_builder': 'self.postprocessor_builder', 'input_shape': 'spec_shape', 'is_training': 'is_training', 'num_frames': 'num_spec_frames', 'stride': 'spec_stride', 'num_test_clips': 'num_test_clips', 'spec_augment': 'spec_augment', 'spec_augment_params': 'spec_augment_params', 'zero_centering_image': 'zero_centering_image', 'dataset_mean': 'dataset_spec_mean', 'dataset_stddev': 'dataset_spec_stddev', 'sync_random_state': '(True)'}), '(parser_builder=self.parser_builder, sampler_builder=self.\n sampler_builder, decoder_builder=self.decoder_builder,\n preprocessor_builder=self.preprocessor_builder, postprocessor_builder=\n self.postprocessor_builder, input_shape=spec_shape, is_training=\n is_training, num_frames=num_spec_frames, stride=spec_stride,\n num_test_clips=num_test_clips, spec_augment=spec_augment,\n spec_augment_params=spec_augment_params, zero_centering_image=\n zero_centering_image, dataset_mean=dataset_spec_mean, dataset_stddev=\n dataset_spec_stddev, sync_random_state=True)\n', (7891, 8469), False, 'from scenic.projects.mbt.datasets.dataset_utils import add_spectrogram\n'), ((17929, 17948), 'jax.process_count', 'jax.process_count', ([], {}), '()\n', (17946, 17948), False, 'import jax\n'), ((17968, 17987), 'jax.process_index', 'jax.process_index', ([], {}), '()\n', (17985, 17987), False, 'import jax\n'), ((19408, 19480), 'absl.logging.info', 'logging.info', (['"""Using the tf.data service at %s"""', 'dataset_service_address'], {}), "('Using the tf.data service at %s', dataset_service_address)\n", (19420, 19480), False, 'from absl import logging\n'), ((19497, 19555), 'scenic.dataset_lib.dataset_utils.distribute', 'dataset_utils.distribute', (['dataset', 'dataset_service_address'], {}), '(dataset, dataset_service_address)\n', (19521, 19555), False, 'from scenic.dataset_lib import dataset_utils\n'), ((20063, 20149), 'functools.partial', 'functools.partial', (['map_keys'], {'modalities': 'modalities', 'return_as_dict': 'return_as_dict'}), '(map_keys, modalities=modalities, return_as_dict=\n return_as_dict)\n', (20080, 20149), False, 'import functools\n'), ((20213, 20277), 'functools.partial', 'functools.partial', (['tile_label_key'], {'return_as_dict': 'return_as_dict'}), '(tile_label_key, return_as_dict=return_as_dict)\n', (20230, 20277), False, 'import functools\n')]
# -*- coding: utf-8 -*- # File generated according to Generator/ClassesRef/Simulation/InputFlux.csv # WARNING! All changes made in this file will be lost! """Method code available at https://github.com/Eomys/pyleecan/tree/master/pyleecan/Methods/Simulation/InputFlux """ from os import linesep from sys import getsizeof from logging import getLogger from ._check import set_array, check_var, raise_ from ..Functions.get_logger import get_logger from ..Functions.save import save from ..Functions.copy import copy from ..Functions.load import load_init_dict from ..Functions.Load.import_class import import_class from .InputCurrent import InputCurrent # Import all class method # Try/catch to remove unnecessary dependencies in unused method try: from ..Methods.Simulation.InputFlux.gen_input import gen_input except ImportError as error: gen_input = error from ..Classes.ImportMatrixVal import ImportMatrixVal from numpy import ndarray from numpy import array, array_equal from ._check import InitUnKnowClassError from .ImportMatrix import ImportMatrix from .ImportData import ImportData from .ImportGenPWM import ImportGenPWM from .OP import OP class InputFlux(InputCurrent): """Input to skip the magnetic module and start with the structural one""" VERSION = 1 # cf Methods.Simulation.InputFlux.gen_input if isinstance(gen_input, ImportError): gen_input = property( fget=lambda x: raise_( ImportError("Can't use InputFlux method gen_input: " + str(gen_input)) ) ) else: gen_input = gen_input # save and copy methods are available in all object save = save copy = copy # get_logger method is available in all object get_logger = get_logger def __init__( self, per_a=1, per_t=1, is_antiper_a=False, is_antiper_t=False, B_dict=None, unit=None, slice=None, B_enforced=None, Is=None, Ir=None, Is_harm=None, rot_dir=None, angle_rotor_initial=0, PWM=None, phase_dir=None, current_dir=None, is_periodicity_t=False, is_periodicity_a=False, time=None, angle=None, Nt_tot=2048, Nrev=None, Na_tot=2048, OP=None, t_final=None, init_dict=None, init_str=None, ): """Constructor of the class. Can be use in three ways : - __init__ (arg1 = 1, arg3 = 5) every parameters have name and default values for pyleecan type, -1 will call the default constructor - __init__ (init_dict = d) d must be a dictionary with property names as keys - __init__ (init_str = s) s must be a string s is the file path to load ndarray or list can be given for Vector and Matrix object or dict can be given for pyleecan Object""" if init_str is not None: # Load from a file init_dict = load_init_dict(init_str)[1] if init_dict is not None: # Initialisation by dict assert type(init_dict) is dict # Overwrite default value with init_dict content if "per_a" in list(init_dict.keys()): per_a = init_dict["per_a"] if "per_t" in list(init_dict.keys()): per_t = init_dict["per_t"] if "is_antiper_a" in list(init_dict.keys()): is_antiper_a = init_dict["is_antiper_a"] if "is_antiper_t" in list(init_dict.keys()): is_antiper_t = init_dict["is_antiper_t"] if "B_dict" in list(init_dict.keys()): B_dict = init_dict["B_dict"] if "unit" in list(init_dict.keys()): unit = init_dict["unit"] if "slice" in list(init_dict.keys()): slice = init_dict["slice"] if "B_enforced" in list(init_dict.keys()): B_enforced = init_dict["B_enforced"] if "Is" in list(init_dict.keys()): Is = init_dict["Is"] if "Ir" in list(init_dict.keys()): Ir = init_dict["Ir"] if "Is_harm" in list(init_dict.keys()): Is_harm = init_dict["Is_harm"] if "rot_dir" in list(init_dict.keys()): rot_dir = init_dict["rot_dir"] if "angle_rotor_initial" in list(init_dict.keys()): angle_rotor_initial = init_dict["angle_rotor_initial"] if "PWM" in list(init_dict.keys()): PWM = init_dict["PWM"] if "phase_dir" in list(init_dict.keys()): phase_dir = init_dict["phase_dir"] if "current_dir" in list(init_dict.keys()): current_dir = init_dict["current_dir"] if "is_periodicity_t" in list(init_dict.keys()): is_periodicity_t = init_dict["is_periodicity_t"] if "is_periodicity_a" in list(init_dict.keys()): is_periodicity_a = init_dict["is_periodicity_a"] if "time" in list(init_dict.keys()): time = init_dict["time"] if "angle" in list(init_dict.keys()): angle = init_dict["angle"] if "Nt_tot" in list(init_dict.keys()): Nt_tot = init_dict["Nt_tot"] if "Nrev" in list(init_dict.keys()): Nrev = init_dict["Nrev"] if "Na_tot" in list(init_dict.keys()): Na_tot = init_dict["Na_tot"] if "OP" in list(init_dict.keys()): OP = init_dict["OP"] if "t_final" in list(init_dict.keys()): t_final = init_dict["t_final"] # Set the properties (value check and convertion are done in setter) self.per_a = per_a self.per_t = per_t self.is_antiper_a = is_antiper_a self.is_antiper_t = is_antiper_t self.B_dict = B_dict self.unit = unit self.slice = slice self.B_enforced = B_enforced # Call InputCurrent init super(InputFlux, self).__init__( Is=Is, Ir=Ir, Is_harm=Is_harm, rot_dir=rot_dir, angle_rotor_initial=angle_rotor_initial, PWM=PWM, phase_dir=phase_dir, current_dir=current_dir, is_periodicity_t=is_periodicity_t, is_periodicity_a=is_periodicity_a, time=time, angle=angle, Nt_tot=Nt_tot, Nrev=Nrev, Na_tot=Na_tot, OP=OP, t_final=t_final, ) # The class is frozen (in InputCurrent init), for now it's impossible to # add new properties def __str__(self): """Convert this object in a readeable string (for print)""" InputFlux_str = "" # Get the properties inherited from InputCurrent InputFlux_str += super(InputFlux, self).__str__() InputFlux_str += "per_a = " + str(self.per_a) + linesep InputFlux_str += "per_t = " + str(self.per_t) + linesep InputFlux_str += "is_antiper_a = " + str(self.is_antiper_a) + linesep InputFlux_str += "is_antiper_t = " + str(self.is_antiper_t) + linesep InputFlux_str += "B_dict = " + str(self.B_dict) + linesep InputFlux_str += 'unit = "' + str(self.unit) + '"' + linesep InputFlux_str += ( "slice = " + linesep + str(self.slice).replace(linesep, linesep + "\t") + linesep + linesep ) InputFlux_str += "B_enforced = " + str(self.B_enforced) + linesep + linesep return InputFlux_str def __eq__(self, other): """Compare two objects (skip parent)""" if type(other) != type(self): return False # Check the properties inherited from InputCurrent if not super(InputFlux, self).__eq__(other): return False if other.per_a != self.per_a: return False if other.per_t != self.per_t: return False if other.is_antiper_a != self.is_antiper_a: return False if other.is_antiper_t != self.is_antiper_t: return False if other.B_dict != self.B_dict: return False if other.unit != self.unit: return False if not array_equal(other.slice, self.slice): return False if other.B_enforced != self.B_enforced: return False return True def compare(self, other, name="self", ignore_list=None): """Compare two objects and return list of differences""" if ignore_list is None: ignore_list = list() if type(other) != type(self): return ["type(" + name + ")"] diff_list = list() # Check the properties inherited from InputCurrent diff_list.extend(super(InputFlux, self).compare(other, name=name)) if other._per_a != self._per_a: diff_list.append(name + ".per_a") if other._per_t != self._per_t: diff_list.append(name + ".per_t") if other._is_antiper_a != self._is_antiper_a: diff_list.append(name + ".is_antiper_a") if other._is_antiper_t != self._is_antiper_t: diff_list.append(name + ".is_antiper_t") if other._B_dict != self._B_dict: diff_list.append(name + ".B_dict") if other._unit != self._unit: diff_list.append(name + ".unit") if not array_equal(other.slice, self.slice): diff_list.append(name + ".slice") if (other.B_enforced is None and self.B_enforced is not None) or ( other.B_enforced is not None and self.B_enforced is None ): diff_list.append(name + ".B_enforced None mismatch") elif self.B_enforced is not None: diff_list.extend( self.B_enforced.compare(other.B_enforced, name=name + ".B_enforced") ) # Filter ignore differences diff_list = list(filter(lambda x: x not in ignore_list, diff_list)) return diff_list def __sizeof__(self): """Return the size in memory of the object (including all subobject)""" S = 0 # Full size of the object # Get size of the properties inherited from InputCurrent S += super(InputFlux, self).__sizeof__() S += getsizeof(self.per_a) S += getsizeof(self.per_t) S += getsizeof(self.is_antiper_a) S += getsizeof(self.is_antiper_t) if self.B_dict is not None: for key, value in self.B_dict.items(): S += getsizeof(value) + getsizeof(key) S += getsizeof(self.unit) S += getsizeof(self.slice) S += getsizeof(self.B_enforced) return S def as_dict(self, type_handle_ndarray=0, keep_function=False, **kwargs): """ Convert this object in a json serializable dict (can be use in __init__). type_handle_ndarray: int How to handle ndarray (0: tolist, 1: copy, 2: nothing) keep_function : bool True to keep the function object, else return str Optional keyword input parameter is for internal use only and may prevent json serializability. """ # Get the properties inherited from InputCurrent InputFlux_dict = super(InputFlux, self).as_dict( type_handle_ndarray=type_handle_ndarray, keep_function=keep_function, **kwargs ) InputFlux_dict["per_a"] = self.per_a InputFlux_dict["per_t"] = self.per_t InputFlux_dict["is_antiper_a"] = self.is_antiper_a InputFlux_dict["is_antiper_t"] = self.is_antiper_t InputFlux_dict["B_dict"] = ( self.B_dict.copy() if self.B_dict is not None else None ) InputFlux_dict["unit"] = self.unit if self.slice is None: InputFlux_dict["slice"] = None else: if type_handle_ndarray == 0: InputFlux_dict["slice"] = self.slice.tolist() elif type_handle_ndarray == 1: InputFlux_dict["slice"] = self.slice.copy() elif type_handle_ndarray == 2: InputFlux_dict["slice"] = self.slice else: raise Exception( "Unknown type_handle_ndarray: " + str(type_handle_ndarray) ) if self.B_enforced is None: InputFlux_dict["B_enforced"] = None else: InputFlux_dict["B_enforced"] = self.B_enforced.as_dict( type_handle_ndarray=type_handle_ndarray, keep_function=keep_function, **kwargs ) # The class name is added to the dict for deserialisation purpose # Overwrite the mother class name InputFlux_dict["__class__"] = "InputFlux" return InputFlux_dict def _set_None(self): """Set all the properties to None (except pyleecan object)""" self.per_a = None self.per_t = None self.is_antiper_a = None self.is_antiper_t = None self.B_dict = None self.unit = None self.slice = None self.B_enforced = None # Set to None the properties inherited from InputCurrent super(InputFlux, self)._set_None() def _get_per_a(self): """getter of per_a""" return self._per_a def _set_per_a(self, value): """setter of per_a""" check_var("per_a", value, "int") self._per_a = value per_a = property( fget=_get_per_a, fset=_set_per_a, doc=u"""Angle periodicity :Type: int """, ) def _get_per_t(self): """getter of per_t""" return self._per_t def _set_per_t(self, value): """setter of per_t""" check_var("per_t", value, "int") self._per_t = value per_t = property( fget=_get_per_t, fset=_set_per_t, doc=u"""Time periodicity :Type: int """, ) def _get_is_antiper_a(self): """getter of is_antiper_a""" return self._is_antiper_a def _set_is_antiper_a(self, value): """setter of is_antiper_a""" check_var("is_antiper_a", value, "bool") self._is_antiper_a = value is_antiper_a = property( fget=_get_is_antiper_a, fset=_set_is_antiper_a, doc=u"""If angle is antiperiodic :Type: bool """, ) def _get_is_antiper_t(self): """getter of is_antiper_t""" return self._is_antiper_t def _set_is_antiper_t(self, value): """setter of is_antiper_t""" check_var("is_antiper_t", value, "bool") self._is_antiper_t = value is_antiper_t = property( fget=_get_is_antiper_t, fset=_set_is_antiper_t, doc=u"""If time is antiperiodic :Type: bool """, ) def _get_B_dict(self): """getter of B_dict""" return self._B_dict def _set_B_dict(self, value): """setter of B_dict""" if type(value) is int and value == -1: value = dict() check_var("B_dict", value, "dict") self._B_dict = value B_dict = property( fget=_get_B_dict, fset=_set_B_dict, doc=u"""Dict of Import objects or lists for each component of the flux :Type: dict """, ) def _get_unit(self): """getter of unit""" return self._unit def _set_unit(self, value): """setter of unit""" check_var("unit", value, "str") self._unit = value unit = property( fget=_get_unit, fset=_set_unit, doc=u"""Unit of the flux if not T :Type: str """, ) def _get_slice(self): """getter of slice""" return self._slice def _set_slice(self, value): """setter of slice""" if type(value) is int and value == -1: value = array([]) elif type(value) is list: try: value = array(value) except: pass check_var("slice", value, "ndarray") self._slice = value slice = property( fget=_get_slice, fset=_set_slice, doc=u"""Slice axis values :Type: ndarray """, ) def _get_B_enforced(self): """getter of B_enforced""" return self._B_enforced def _set_B_enforced(self, value): """setter of B_enforced""" if isinstance(value, str): # Load from file value = load_init_dict(value)[1] if isinstance(value, dict) and "__class__" in value: class_obj = import_class( "SciDataTool.Classes", value.get("__class__"), "B_enforced" ) value = class_obj(init_dict=value) elif type(value) is int and value == -1: # Default constructor value = VectorField() check_var("B_enforced", value, "VectorField") self._B_enforced = value B_enforced = property( fget=_get_B_enforced, fset=_set_B_enforced, doc=u"""Airgap flux density as VectorField object :Type: SciDataTool.Classes.VectorField.VectorField """, )
[ "numpy.array_equal", "numpy.array", "sys.getsizeof" ]
[((10431, 10452), 'sys.getsizeof', 'getsizeof', (['self.per_a'], {}), '(self.per_a)\n', (10440, 10452), False, 'from sys import getsizeof\n'), ((10466, 10487), 'sys.getsizeof', 'getsizeof', (['self.per_t'], {}), '(self.per_t)\n', (10475, 10487), False, 'from sys import getsizeof\n'), ((10501, 10529), 'sys.getsizeof', 'getsizeof', (['self.is_antiper_a'], {}), '(self.is_antiper_a)\n', (10510, 10529), False, 'from sys import getsizeof\n'), ((10543, 10571), 'sys.getsizeof', 'getsizeof', (['self.is_antiper_t'], {}), '(self.is_antiper_t)\n', (10552, 10571), False, 'from sys import getsizeof\n'), ((10727, 10747), 'sys.getsizeof', 'getsizeof', (['self.unit'], {}), '(self.unit)\n', (10736, 10747), False, 'from sys import getsizeof\n'), ((10761, 10782), 'sys.getsizeof', 'getsizeof', (['self.slice'], {}), '(self.slice)\n', (10770, 10782), False, 'from sys import getsizeof\n'), ((10796, 10822), 'sys.getsizeof', 'getsizeof', (['self.B_enforced'], {}), '(self.B_enforced)\n', (10805, 10822), False, 'from sys import getsizeof\n'), ((8378, 8414), 'numpy.array_equal', 'array_equal', (['other.slice', 'self.slice'], {}), '(other.slice, self.slice)\n', (8389, 8414), False, 'from numpy import array, array_equal\n'), ((9542, 9578), 'numpy.array_equal', 'array_equal', (['other.slice', 'self.slice'], {}), '(other.slice, self.slice)\n', (9553, 9578), False, 'from numpy import array, array_equal\n'), ((16084, 16093), 'numpy.array', 'array', (['[]'], {}), '([])\n', (16089, 16093), False, 'from numpy import array, array_equal\n'), ((10680, 10696), 'sys.getsizeof', 'getsizeof', (['value'], {}), '(value)\n', (10689, 10696), False, 'from sys import getsizeof\n'), ((10699, 10713), 'sys.getsizeof', 'getsizeof', (['key'], {}), '(key)\n', (10708, 10713), False, 'from sys import getsizeof\n'), ((16169, 16181), 'numpy.array', 'array', (['value'], {}), '(value)\n', (16174, 16181), False, 'from numpy import array, array_equal\n')]
from __future__ import print_function, absolute_import import stimela import stimela.dismissable as sdm from pyrap.tables import table as tbl import os import sys import argparse import numpy as np from collections import OrderedDict import shutil import vermeerkat parser = argparse.ArgumentParser("MeerKAT BasicApplyTransfer (BAT) pipeline") parser.add_argument('--input_dir', dest='input_directory', metavar='<input directory>', action='store', default='input', help='directory to read input data with e.g. antenna table and beam files') parser.add_argument('--output_dir', dest='output_directory', metavar='<output directory>', action='store', default='output', help='directory to write output data') parser.add_argument('--msdir_dir', dest='msdir_directory', metavar='<msdir directory>', action='store', default='msdir', help='directory to store measurement sets') parser.add_argument('--bp', dest='bandpass_field', metavar='<bandpass field>', help='Bandpass fields') parser.add_argument('--gc', dest='gain_field', metavar='<gain calibrator fields>', default=[], action="append", nargs="+", help='Gain fields. This switch can be used multiple times for more than 1 field') parser.add_argument('--altcal', dest='alt_cal_field', metavar='<alternative calibrator fields>', default=[], action="append", nargs="+", help='Alternative calibrator. Phase corrections will be applied to this field for further ' 'diagnostic or calibration procedures. This switch can be used multiple times for ' 'more than 1 field. This field has no impact on target field calibration.') parser.add_argument('--tar', dest='target_field', metavar='<target fields>', type=str, default=[], action="append", nargs="+", help='Target fields. This switch can be used multiple times for more than 1 field') parser.add_argument('--no_delay_with_gcal', dest='delay_with_gcal', action='store_false', default=True, help='DON''t use gain calibrators for delay calibration') parser.add_argument('--flag_antenna', dest='flag_antenna', action='append', default=[], help="Flag antenna. Can be specified more than once to flag more than one antenna.") parser.add_argument('--skip_prepdata', dest='skip_prepdata', action='store_true', help="Skip prepdata") parser.add_argument('--skip_prelim_flagging', dest='skip_prelim_flagging', action='store_true', help="Skip preliminary flagging") parser.add_argument('--skip_prelim_1GC', dest='skip_prelim_1GC', action='store_true', help="Skip preliminary 1GC") parser.add_argument('--skip_final_flagging', dest='skip_final_flagging', action='store_true', help="Skip final flagging") parser.add_argument('--skip_final_1GC', dest='skip_final_1GC', action='store_true', help="Skip final 1GC") parser.add_argument('--skip_flag_targets', dest='skip_flag_targets', action='store_true', help="Skip flag targets") parser.add_argument('--skip_transfer_to_targets', dest='skip_transfer_to_targets', action='store_true', help="Skip transfer of solutions to target") parser.add_argument('--skip_final_split', dest='skip_final_split', action='store_true', help="Skip final split") parser.add_argument('msprefix', metavar='<measurement set name prefix>', help='Prefix of measurement set name as it appears relative to msdir. This must NOT be a ' 'path prefix') parser.add_argument('--time_sol_interval', dest='time_sol_interval', default="inf", help="Time (gain) solutions interval (default one per scan)") parser.add_argument('--freq_sol_interval', dest='freq_sol_interval', default="inf", help="Frequency time-invariant solutions interval (default one per observation)") parser.add_argument('--clip_delays', dest='clip_delays', default=1, type=float, help="Clip delays above this absolute in nanoseconds") parser.add_argument('--cal_model', dest='cal_model', default='pks1934-638.lsm', help="Calibrator apparent sky model (tigger lsm format)") parser.add_argument('--ref_ant', dest='ref_ant', default='m037', help="Reference antenna to use throughout") parser.add_argument("--containerization", dest="containerization", default="docker", help="Containerization technology to use. See your stimela installation for options") parser.add_argument("--image_gaincalibrators", dest="image_gaincalibrators", action="store_true", help="Image gain calibrators") parser.add_argument("--dont_prompt", dest="dont_prompt", action="store_true", help="Don't prompt the user for confirmation of parameters") args = parser.parse_args(sys.argv[2:]) INPUT = args.input_directory MSDIR = args.msdir_directory OUTPUT = args.output_directory vermeerkat.log.info("Directory '{0:s}' is used as input directory".format(INPUT)) vermeerkat.log.info("Directory '{0:s}' is used as output directory".format(OUTPUT)) vermeerkat.log.info("Directory '{0:s}' is used as msdir directory".format(MSDIR)) PREFIX = args.msprefix ZEROGEN_DATA = PREFIX + ".ms" vermeerkat.log.info("Dataset '{0:s}' to be used throughout".format(ZEROGEN_DATA)) with tbl(os.path.join(MSDIR, ZEROGEN_DATA)+"::FIELD", ack=False) as t: field_names = t.getcol("NAME") FDB = {fn: str(fni) for fni, fn in enumerate(field_names)} def flistr(): vermeerkat.log.info("The following fields are available:") for f in FDB: vermeerkat.log.info("\t '{0:s}' index {1:s}".format(f, FDB[f])) sys.exit(0) def __merge_input(): mod_path = os.path.dirname(vermeerkat.__file__) data_dir = os.path.join(mod_path, "data", "input") shutil.copytree(data_dir, INPUT) if not os.path.exists(INPUT): __merge_input() elif os.path.isdir(INPUT): shutil.rmtree(INPUT) __merge_input() else: raise RuntimeError("A file called {} already exists, but is not a input directory".format(INPUT)) vermeerkat.log.info("Time invariant solution time interval: {0:s}".format(args.time_sol_interval)) vermeerkat.log.info("Frequency invariant solution frequency interval: {0:s}".format(args.freq_sol_interval)) vermeerkat.log.info("Will clip absolute delays over {0:.2f}ns".format(args.clip_delays)) vermeerkat.log.info("Will use '{}' as flux calibrator full sky model".format(args.cal_model)) FLAGANT = [f[0] if isinstance(f, list) else f for f in args.flag_antenna] if len(FLAGANT) != 0: vermeerkat.log.info("Will flag antenna {}".format(", ".join(["'{}'".format(a) for a in FLAGANT]))) BPCALIBRATOR = args.bandpass_field if BPCALIBRATOR is None: raise ValueError("No bandpass calibrator specified") GCALIBRATOR = [f[0] if isinstance(f, list) else f for f in args.gain_field] ALTCAL = [f[0] if isinstance(f, list) else f for f in args.alt_cal_field] TARGET = [f[0] if isinstance(f, list) else f for f in args.target_field] if len(TARGET) < 1: raise ValueError("No target specified") DO_USE_GAINCALIBRATOR = len(GCALIBRATOR) > 0 if not DO_USE_GAINCALIBRATOR: vermeerkat.log.info("*NO* gain calibrator specified") DO_USE_GAINCALIBRATOR_DELAY = args.delay_with_gcal and DO_USE_GAINCALIBRATOR if DO_USE_GAINCALIBRATOR_DELAY: vermeerkat.log.info("Will transfer rate calibraton using gain calibrator") else: vermeerkat.log.info("Will *NOT* transfer rate calibraton from gain calibrator") REFANT = args.ref_ant vermeerkat.log.info("Reference antenna {0:s} to be used throughout".format(REFANT)) ## DO NOT EDIT ANY OF THESE PREDEFINED WORKERS UNLESS YOU KNOW WHAT YOU'RE DOING K0 = PREFIX + ".K0" B0 = PREFIX + ".B0" G0 = PREFIX + ".G0" GA = PREFIX + ".GAlt" G1 = PREFIX + ".G1" F0 = PREFIX + ".F0" B1 = PREFIX + ".B1" MANUAL_FLAG_LIST = [] FIRSTGEN_DATA = ["{}.{}.1gc.ms".format(t, PREFIX) for t in TARGET] vermeerkat.log.info("The following fields are available:") for f in FDB: vermeerkat.log.info("\t '{0:s}' index {1:s}{2:s}".format( f, FDB[f], " selected as 'BP'" if f == BPCALIBRATOR else " selected as 'GC'" if f in GCALIBRATOR else " selected as 'ALTCAL'" if f in ALTCAL else " selected as 'TARGET'" if f in TARGET else " not selected")) try: input = raw_input except NameError: pass while not args.dont_prompt: r = input("Is this configuration correct? (Y/N) >> ").lower() if r == "y": break elif r == "n": sys.exit(0) else: continue stimela.register_globals() recipe = stimela.Recipe('MEERKAT: basic transfer calibration', ms_dir=MSDIR, singularity_image_dir=os.environ.get("SINGULARITY_PULLFOLDER", ""), JOB_TYPE=args.containerization) def addmanualflags(recipe, reason, antenna="", spw="", scan="", uvrange="", field=""): """ Read CASA flagdata docs before using """ recipe.add("cab/casa_flagdata", "handflags", { "vis": ZEROGEN_DATA, "mode": "manual", "antenna": antenna, "spw": spw, "scan": scan, "uvrange": uvrange, "field": field }, input=INPUT, output=OUTPUT, label=reason) MANUAL_FLAG_LIST.append(reason) return [reason] def prepare_data(): recipe.add("cab/casa_flagmanager", "backup_CAM_SP_flags", { "vis": ZEROGEN_DATA, "mode": "save", "versionname": "SP_ORIGINAL", }, input=INPUT, output=OUTPUT, label="backup_CAM_SP_flags") recipe.add("cab/casa_listobs", "listobs", { "vis": ZEROGEN_DATA, }, input=INPUT, output=OUTPUT, label="listobs") recipe.add("cab/casa_flagdata", "flag_reset", { "vis": ZEROGEN_DATA, "mode": "unflag", }, input=INPUT, output=OUTPUT, label="reset_flags") recipe.add("cab/politsiyakat_autocorr_amp", "flag_autopower", { "msname": ZEROGEN_DATA, "field": ",".join(str(FDB[f]) for f in FDB), "cal_field": ",".join([FDB[BPCALIBRATOR]] + [FDB[f] for f in GCALIBRATOR + ALTCAL]), "nrows_chunk": 15000, "scan_to_scan_threshold": 1.5, "antenna_to_group_threshold": 4, "output_dir": "./:output", "nio_threads": 1, "nproc_threads": 32, "dpi": 80, },input=INPUT, output=OUTPUT, label="flag_autopower") recipe.add("cab/casa_flagdata", "flag_autocorrelations", { "vis": ZEROGEN_DATA, "mode": "manual", "autocorr": True, }, input=INPUT, output=OUTPUT, label="flagging_auto_correlations") recipe.add("cab/casa_flagdata", "flag_rolloff", { "vis": ZEROGEN_DATA, "mode": "manual", "spw": "*:850~980MHz,*:1658~1800MHz,*:1419.8~1421.3MHz", #band-rolloffs and Milkyway HI line }, input=INPUT, output=OUTPUT, label="flagging_rolloff") recipe.add("cab/casa_clearcal", "clear_calibration", { "vis": ZEROGEN_DATA, "addmodel": True, }, input=INPUT, output=OUTPUT, label="clear_calibration") return [ "backup_CAM_SP_flags", "listobs", ####"reset_flags", "flag_autopower", "flagging_auto_correlations", "flagging_rolloff", "clear_calibration", ] def rfiflag_data(do_flag_targets=False, steplabel="flagpass1", exec_strategy="mk_rfi_flagging_calibrator_fields_firstpass.yaml", on_corr_residuals=False, dc="DATA"): recipe.add('cab/tricolour', steplabel, { "ms" : ZEROGEN_DATA, "data-column" : dc, "window-backend" : 'numpy', "field-names" : [FDB[BPCALIBRATOR]], "flagging-strategy" : "total_power" if not do_flag_targets else "polarisation", "config" : exec_strategy, "subtract-model-column": sdm.dismissable("MODEL_DATA" if on_corr_residuals else None), "dilate-masks": sdm.dismissable(None), "ignore-flags": sdm.dismissable(None), "scan-numbers": sdm.dismissable(None), }, input=INPUT, output=OUTPUT, label=steplabel) recipe.add('cab/tricolour', steplabel + "_gc", { "ms" : ZEROGEN_DATA, "data-column" : dc, "window-backend" : 'numpy', "field-names" : [FDB[t] for t in TARGET] if do_flag_targets else [FDB[t] for t in GCALIBRATOR + ALTCAL], "flagging-strategy" : "total_power" if not do_flag_targets else "polarisation", "subtract-model-column": sdm.dismissable("MODEL_DATA" if on_corr_residuals else None), "config" : exec_strategy, "dilate-masks": sdm.dismissable(None), "ignore-flags": sdm.dismissable(None), "scan-numbers": sdm.dismissable(None), }, input=INPUT, output=OUTPUT, label=steplabel + ".gc" if not do_flag_targets else steplabel + ".targets") recipe.add("cab/casa_flagdata", "flag_summary_{}".format(steplabel), { "vis": ZEROGEN_DATA, "mode": "summary" }, input=INPUT, output=OUTPUT, label="flagging_summary_{}".format(steplabel)) return (([steplabel, steplabel + ".gc"] if len(ALTCAL) > 0 or DO_USE_GAINCALIBRATOR else [steplabel]) if not do_flag_targets else [steplabel + ".targets"]) + \ [ "flagging_summary_{}".format(steplabel) ] def image_calibrator(recipe, label="prelim"): imfields = [FDB[a] for a in ALTCAL] + \ ([FDB[t] for t in GCALIBRATOR] if (DO_USE_GAINCALIBRATOR and DO_USE_GAINCALIBRATOR_DELAY) else []) steps = [] for f in imfields: imopts={ "msname": ZEROGEN_DATA, "join-channels": True, "channels-out": 9, "size": 4096, "scale": "1.6asec", "mgain": 0.8, "gain": 0.1, "niter": 3000, "name": "calfield-{}-{}".format(f, label), "field": f, "fits-mask": sdm.dismissable(None), ###"save-source-list": True, "fit-spectral-pol": 3, } maskname = "MASK-{}-{}.fits".format(f, label) recipe.add("cab/wsclean", "image_{}_field{}".format(label, f), imopts, input=INPUT, output=OUTPUT, label="image_calfield_{}_{}".format(f, label)) recipe.add("cab/cleanmask", "mask_{}_{}".format(label, f), { 'image': "calfield-{}-{}-MFS-image.fits:output".format(f, label), 'output': maskname, 'sigma': 35, 'boxes': 9, 'iters': 20, 'overlap': 0.3, 'no-negative': True, 'tolerance': 0.75, }, input=INPUT, output=OUTPUT, label='mask_{}_{}'.format(label, f)) imopts2 = {k: v for k, v in list(imopts.items())} imopts2["fits-mask"] = maskname + ":output" imopts2["local-rms"] = True imopts2["auto-threshold"] = 5 recipe.add("cab/wsclean", "image_{}_field{}_rnd2".format(label, f), imopts2, input=INPUT, output=OUTPUT, label="image_calfield_{}_{}_rnd2".format(f, label)) steps += ["image_calfield_{}_{}".format(f, label), 'mask_{}_{}'.format(label, f), "image_calfield_{}_{}_rnd2".format(f, label)] return steps def do_1GC(recipe, label="prelim", do_apply_target=False, do_predict=True, applyonly=False): recipe.add("cab/casa_flagmanager", "backup_flags_prior_1gc_%s" % label, { "vis": ZEROGEN_DATA, "mode": "save", "versionname": "prior_%s_1GC" % label, }, input=INPUT, output=OUTPUT, label="backup_flags_prior_1gc_%s" % label) recipe.add("cab/simulator", "predict_fluxcalibrator_%s" % label, { "skymodel": args.cal_model, # we are using 1934-638 as flux scale reference "msname": ZEROGEN_DATA, "threads": 24, "mode": "simulate", "column": "MODEL_DATA", "Ejones": False, # first bandpass calibration is normal calibration then we absorb coefficients into another table "beam-files-pattern": "meerkat_pb_jones_cube_95channels_$(xy)_$(reim).fits", "beam-l-axis": "X", "beam-m-axis": "-Y", #[OMS] flipped in code: southern hemisphere "parallactic-angle-rotation": True, "field-id": int(FDB[BPCALIBRATOR]), }, input=INPUT, output=OUTPUT, label="set_flux_reference_%s" % label) recipe.add("cab/casa47_gaincal", "delaycal_%s" % label, { "vis": ZEROGEN_DATA, "caltable": K0, "field": ",".join([FDB[BPCALIBRATOR]]), "refant": REFANT, "solint": args.time_sol_interval, "combine": "", "minsnr": 3, "minblperant": 4, "gaintype": "K", }, input=INPUT, output=OUTPUT, label="delay_calibration_bp_%s" % label) def clip_delays(vis, clipminmax): with tbl(os.path.join(OUTPUT, vis), readonly=False) as t: fl = t.getcol("FLAG") d = t.getcol("FPARAM") prevflagged = np.sum(fl) * 100.0 / fl.size fl = np.logical_or(fl, np.logical_or(d.real > np.max(clipminmax), d.real < np.min(clipminmax))) t.putcol("FLAG", fl) currentflagged = np.sum(fl) * 100.0 / fl.size vermeerkat.log.info("Flagged {0:.2f}%, up from previous {1:.2f}%".format(currentflagged, prevflagged)) recipe.add(clip_delays, "clipdel_%s" % label, { "vis": K0, "clipminmax": [-args.clip_delays, +args.clip_delays], }, input=INPUT, output=OUTPUT, label="clip_delay_%s" % label) ##capture time drift of bandpass recipe.add("cab/casa47_gaincal", "bandpassgain_%s" % label, { "vis": ZEROGEN_DATA, "caltable": G0, "field": ",".join([FDB[BPCALIBRATOR]]), "solint": args.time_sol_interval, "combine": "", "gaintype": "G", "uvrange": "150~10000m", # EXCLUDE RFI INFESTATION! ##"spw": "0:1.3~1.5GHz", "gaintable": ["%s:output" % ct for ct in [K0]], "gainfield": [FDB[BPCALIBRATOR]], "interp":["nearest"], "refant": REFANT, }, input=INPUT, output=OUTPUT, label="remove_bp_average_%s" % label) # average as much as possible to get as good SNR on bandpass as possible recipe.add("cab/casa47_bandpass", "bandpasscal_%s" % label, { "vis": ZEROGEN_DATA, "caltable": "%s:output" % B0, "field": ",".join([FDB[BPCALIBRATOR]]), "solint": args.freq_sol_interval, "combine": "scan", "minsnr": 3.0, "uvrange": "150~10000m", # EXCLUDE RFI INFESTATION! #"fillgaps": 100000000, # LERP! "gaintable": ["%s:output" % ct for ct in [K0, G0]], "gainfield": [FDB[BPCALIBRATOR], FDB[BPCALIBRATOR]], "interp": ["nearest", "nearest"], "refant": REFANT, }, input=INPUT, output=OUTPUT, label="bp_freq_calibration_%s" % label) recipe.add("cab/casa47_applycal", "apply_sols_bp_%s" % label, { "vis": ZEROGEN_DATA, "field": ",".join([FDB[BPCALIBRATOR]] + [FDB[a] for a in ALTCAL] + ([FDB[t] for t in GCALIBRATOR] if (DO_USE_GAINCALIBRATOR and DO_USE_GAINCALIBRATOR_DELAY) else [])), "gaintable": ["%s:output" % ct for ct in [K0,G0,B0]], "gainfield": [",".join([FDB[BPCALIBRATOR]]), ",".join([FDB[BPCALIBRATOR]]), ",".join([FDB[BPCALIBRATOR]])], "interp": ["nearest","nearest","linear,linear"] }, input=INPUT, output=OUTPUT, label="apply_sols_bp_%s" % label) #create basic model for secondaries cal_im_steps = image_calibrator(recipe=recipe, label=label) if args.image_gaincalibrators else [] ##capture time drift of gain and alternative calibrators recipe.add("cab/casa47_gaincal", "delaycal_gc_%s" % label, { "vis": ZEROGEN_DATA, "caltable": K0, "field": ",".join([FDB[a] for a in ALTCAL] + [FDB[t] for t in GCALIBRATOR]) if (DO_USE_GAINCALIBRATOR and DO_USE_GAINCALIBRATOR_DELAY) else ",".join([FDB[a] for a in ALTCAL]), "refant": REFANT, "solint": args.time_sol_interval, "combine": "", "minsnr": 3, "minblperant": 4, "gaintype": "K", "gaintable": ["%s:output" % ct for ct in [B0]], "gainfield": [",".join([FDB[BPCALIBRATOR]])], "interp": ["linear,linear"], ##"spw": "0:1.3~1.5GHz", "uvrange": "150~10000m", # EXCLUDE RFI INFESTATION! "append": True, "refant": REFANT, }, input=INPUT, output=OUTPUT, label="delay_calibration_gc_%s" % label) recipe.add(clip_delays, "clipdel_%s" % label, { "vis": K0, "clipminmax": [-args.clip_delays, +args.clip_delays], }, input=INPUT, output=OUTPUT, label="clip_delay_gc_%s" % label) recipe.add("cab/msutils", "delaycal_plot_%s" % label, { "command": "plot_gains", "ctable": "%s:output" % K0, "tabtype": "delay", "plot_file": "{0:s}.{1:s}.K0.png".format(PREFIX, label), "subplot_scale": 4, "plot_dpi": 180 }, input=INPUT, output=OUTPUT, label="plot_delays_%s" % label) if DO_USE_GAINCALIBRATOR: recipe.add("cab/casa47_gaincal", "apgain_%s" % label, { "vis": ZEROGEN_DATA, "caltable": G0, "field": ",".join([FDB[t] for t in GCALIBRATOR]), "solint": args.time_sol_interval, "combine": "", "gaintype": "G", "uvrange": "150~10000m", # EXCLUDE RFI INFESTATION! ##"spw": "0:1.3~1.5GHz", "gaintable": ["%s:output" % ct for ct in [B0, K0]], "gainfield": [FDB[BPCALIBRATOR], ",".join([FDB[a] for a in ALTCAL] + [FDB[t] for t in GCALIBRATOR]) if (DO_USE_GAINCALIBRATOR and DO_USE_GAINCALIBRATOR_DELAY) else ",".join([FDB[a] for a in ALTCAL]), ], "interp":["linear,linear", "nearest"], "append": True, "refant": REFANT, }, input=INPUT, output=OUTPUT, label="apgain_%s" % label) recipe.add("cab/casa_fluxscale", "fluxscale_%s" % label, { "vis": ZEROGEN_DATA, "caltable": "%s:output" % G0, "fluxtable": "%s:output" % F0, "reference": ",".join([FDB[BPCALIBRATOR]]), "transfer": ",".join([FDB[t] for t in GCALIBRATOR]), }, input=INPUT, output=OUTPUT, label="fluxscale_%s" % label) recipe.add("cab/msutils", "gain_plot_%s" % label, { "command": "plot_gains", "ctable": "%s:output" % (F0 if DO_USE_GAINCALIBRATOR else G0), "tabtype": "gain", "plot_file": "{0:s}.{1:s}.F0.png".format(PREFIX, label), "subplot_scale": 4, "plot_dpi": 180 }, input=INPUT, output=OUTPUT, label="plot_gain_%s" % label) recipe.add("cab/msutils", "bpgain_plot_%s" % label, { "command": "plot_gains", "ctable": "%s:output" % B0, "tabtype": "bandpass", "plot_file": "{0:s}.{1:s}.B0.png".format(PREFIX, label), "subplot_scale": 4, "plot_dpi": 180 }, input=INPUT, output=OUTPUT, label="plot_bpgain_%s" % label) if len(ALTCAL) > 0: # no model of alternatives, don't adjust amp recipe.add("cab/casa47_gaincal", "altcalgain_%s" % label, { "vis": ZEROGEN_DATA, "caltable": GA, "field": ",".join([FDB[a] for a in ALTCAL]), "solint": args.time_sol_interval, "combine": "", "gaintype": "G", "calmode": "p", "uvrange": "150~10000m", # EXCLUDE RFI INFESTATION! ##"spw": "0:1.3~1.5GHz", "gaintable": ["%s:output" % ct for ct in [K0, G0, B0]], "gainfield": [ ",".join([FDB[a] for a in ALTCAL]), FDB[BPCALIBRATOR], FDB[BPCALIBRATOR]], "interp":["linear,linear","nearest"], "refant": REFANT, }, input=INPUT, output=OUTPUT, label="remove_altcal_average_%s" % label) recipe.add("cab/msutils", "altgain_plot_%s" % label, { "command": "plot_gains", "ctable": "%s:output" % GA, "tabtype": "gain", "plot_file": "{0:s}.{1:s}.GA.png".format(PREFIX, label), "subplot_scale": 4, "plot_dpi": 180 }, input=INPUT, output=OUTPUT, label="plot_altgains_%s" % label) for a in ALTCAL: recipe.add("cab/casa47_applycal", "apply_sols_ac_%s_%s" % (FDB[a], label), { "vis": ZEROGEN_DATA, "field": FDB[a], "gaintable": ["%s:output" % ct for ct in [K0,G0,B0,GA]], "gainfield": [ ",".join([FDB[a]]), ",".join([FDB[BPCALIBRATOR]]), ",".join([FDB[BPCALIBRATOR]]), ",".join([FDB[a]]), ], "interp": ["linear,linear","nearest","nearest"] }, input=INPUT, output=OUTPUT, label="apply_sols_ac_%s_%s" % (FDB[a], label)) if do_apply_target or DO_USE_GAINCALIBRATOR: recipe.add("cab/casa47_applycal", "apply_sols_%s" % label, { "vis": ZEROGEN_DATA, "field": ",".join([FDB[t] for t in GCALIBRATOR] + ([FDB[t] for t in TARGET] if do_apply_target else [])), "gaintable": ["%s:output" % ct for ct in [B0,K0,F0]] if DO_USE_GAINCALIBRATOR else ["%s:output" % ct for ct in [B0,K0,G0]], "gainfield": [FDB[BPCALIBRATOR], ",".join([FDB[t] for t in GCALIBRATOR]) if (DO_USE_GAINCALIBRATOR and DO_USE_GAINCALIBRATOR_DELAY) else FDB[BPCALIBRATOR], ",".join([FDB[t] for t in GCALIBRATOR]) if DO_USE_GAINCALIBRATOR else FDB[BPCALIBRATOR], ], "interp": ["linear,linear","nearest","nearest"] }, input=INPUT, output=OUTPUT, label="apply_1GC_solutions_%s" % label) recipe.add("cab/casa_plotms", "plot_pa_bp_%s" % label, { "vis": ZEROGEN_DATA, "field": ",".join([FDB[BPCALIBRATOR]]), "correlation": "XX,YY", "xaxis": "amp", "xdatacolumn": "corrected/model_vector", "yaxis": "phase", "ydatacolumn": "corrected/model_vector", "coloraxis": "baseline", "expformat": "png", "exprange": "all", "overwrite": True, "showgui": False, "avgtime": "32", "avgchannel": "32", "plotfile": "{}.{}.bp.ampphase.png".format(PREFIX, label) }, input=INPUT, output=OUTPUT, label="phaseamp_plot_for_bandpass_%s" % label) recipe.add("cab/casa_plotms", "plot_pa_gcal_%s" % label, { "vis": ZEROGEN_DATA, "field": ",".join([FDB[t] for t in GCALIBRATOR]), "correlation": "XX,YY", "xaxis": "amp", "xdatacolumn": "corrected/model_vector", "yaxis": "phase", "ydatacolumn": "corrected/model_vector", "coloraxis": "baseline", "expformat": "png", "exprange": "all", "iteraxis": "field", "overwrite": True, "showgui": False, "avgtime": "32", "avgchannel": "32", "plotfile": "{}.{}.gc.ampphase.png".format(PREFIX, label) }, input=INPUT, output=OUTPUT, label="phaseamp_plot_for_gain_%s" % label) recipe.add("cab/casa_plotms", "plot_ri_gcal_%s" % label, { "vis": ZEROGEN_DATA, "field": ",".join([FDB[t] for t in GCALIBRATOR + ALTCAL]), "correlation": "XX,YY", "xaxis": "real", "xdatacolumn": "corrected/model_vector", "yaxis": "imag", "ydatacolumn": "corrected/model_vector", "coloraxis": "baseline", "expformat": "png", "exprange": "all", "iteraxis": "field", "overwrite": True, "showgui": False, "avgtime": "32", "avgchannel": "32", "plotfile": "{}.{}.gc.realimag.png".format(PREFIX, label) }, input=INPUT, output=OUTPUT, label="reim_plot_for_gain_%s" % label) recipe.add("cab/casa_plotms", "plot_ri_bpcal_%s" % label, { "vis": ZEROGEN_DATA, "field": FDB[BPCALIBRATOR], "correlation": "XX,YY", "xaxis": "real", "xdatacolumn": "corrected/model_vector", "yaxis": "imag", "ydatacolumn": "corrected/model_vector", "coloraxis": "baseline", "expformat": "png", "exprange": "all", "iteraxis": "field", "overwrite": True, "showgui": False, "avgtime": "32", "avgchannel": "32", "plotfile": "{}.{}.bp.realimag.png".format(PREFIX, label) }, input=INPUT, output=OUTPUT, label="reim_plot_for_bp_%s" % label) recipe.add("cab/casa_plotms", "plot_afreq_gcal_%s" % label, { "vis": ZEROGEN_DATA, "field": ",".join([FDB[t] for t in GCALIBRATOR + ALTCAL]), "correlation": "XX,YY", "xaxis": "freq", "yaxis": "amp", "xdatacolumn": "corrected/model_vector", "ydatacolumn": "corrected/model_vector", "coloraxis": "baseline", "expformat": "png", "exprange": "all", "iteraxis": "field", "overwrite": True, "showgui": False, "avgtime": "64", "plotfile": "{}.{}.gc.ampfreq.png".format(PREFIX, label) }, input=INPUT, output=OUTPUT, label="afreq_for_gain_%s" % label) recipe.add("cab/casa_plotms", "plot_pfreq_gcal_%s" % label, { "vis": ZEROGEN_DATA, "field": ",".join([FDB[t] for t in GCALIBRATOR + ALTCAL]), "correlation": "XX,YY", "xaxis": "freq", "yaxis": "phase", "xdatacolumn": "corrected/model_vector", "ydatacolumn": "corrected/model_vector", "coloraxis": "baseline", "expformat": "png", "exprange": "all", "iteraxis": "field", "overwrite": True, "showgui": False, "avgtime": "64", "plotfile": "{}.{}.gc.phasefreq.png".format(PREFIX, label) }, input=INPUT, output=OUTPUT, label="pfreq_for_gain_%s" % label) recipe.add("cab/casa_plotms", "plot_ascan_gcal_%s" % label, { "vis": ZEROGEN_DATA, "field": ",".join([FDB[t] for t in GCALIBRATOR + ALTCAL]), "correlation": "XX,YY", "xaxis": "scan", "yaxis": "amp", "xdatacolumn": "corrected/model_vector", "ydatacolumn": "corrected/model_vector", "coloraxis": "baseline", "expformat": "png", "exprange": "all", "iteraxis": "field", "overwrite": True, "showgui": False, "avgtime": "64", "avgchannel": "32", "plotfile": "{}.{}.gc.ampscan.png".format(PREFIX, label) }, input=INPUT, output=OUTPUT, label="ascan_for_gain_%s" % label) recipe.add("cab/casa_plotms", "plot_pscan_gcal_%s" % label, { "vis": ZEROGEN_DATA, "field": ",".join([FDB[t] for t in GCALIBRATOR + ALTCAL]), "correlation": "XX,YY", "xaxis": "scan", "yaxis": "phase", "xdatacolumn": "corrected/model_vector", "ydatacolumn": "corrected/model_vector", "coloraxis": "baseline", "expformat": "png", "exprange": "all", "iteraxis": "field", "overwrite": True, "showgui": False, "avgtime": "64", "avgchannel": "32", "plotfile": "{}.{}.gc.phasescan.png".format(PREFIX, label) }, input=INPUT, output=OUTPUT, label="pscan_for_gain_%s" % label) recipe.add("cab/casa_plotms", "plot_afreq_bpcal_%s" % label, { "vis": ZEROGEN_DATA, "field": ",".join([FDB[BPCALIBRATOR]]), "correlation": "XX,YY", "xaxis": "freq", "yaxis": "amp", "xdatacolumn": "corrected/model_vector", "ydatacolumn": "corrected/model_vector", "coloraxis": "baseline", "expformat": "png", "exprange": "all", "overwrite": True, "showgui": False, "avgtime": "64", "plotfile": "{}.{}.bp.ampfreq.png".format(PREFIX, label) }, input=INPUT, output=OUTPUT, label="afreq_for_bp_%s" % label) recipe.add("cab/casa_plotms", "plot_pfreq_bpcal_%s" % label, { "vis": ZEROGEN_DATA, "field": ",".join([FDB[BPCALIBRATOR]]), "correlation": "XX,YY", "xaxis": "freq", "yaxis": "phase", "xdatacolumn": "corrected/model_vector", "ydatacolumn": "corrected/model_vector", "coloraxis": "baseline", "expformat": "png", "exprange": "all", "overwrite": True, "showgui": False, "avgtime": "64", "plotfile": "{}.{}.bp.phasefreq.png".format(PREFIX, label) }, input=INPUT, output=OUTPUT, label="pfreq_for_bp_%s" % label) recipe.add("cab/casa_plotms", "plot_ascan_bpcal_%s" % label, { "vis": ZEROGEN_DATA, "field": ",".join([FDB[BPCALIBRATOR]]), "correlation": "XX,YY", "xaxis": "scan", "yaxis": "amp", "xdatacolumn": "corrected/model_vector", "ydatacolumn": "corrected/model_vector", "coloraxis": "baseline", "expformat": "png", "exprange": "all", "overwrite": True, "showgui": False, "avgtime": "64", "avgchannel": "32", "plotfile": "{}.{}.bp.ampscan.png".format(PREFIX, label) }, input=INPUT, output=OUTPUT, label="ascan_for_bp_%s" % label) recipe.add("cab/casa_plotms", "plot_pscan_bpcal_%s" % label, { "vis": ZEROGEN_DATA, "field": ",".join([FDB[BPCALIBRATOR]]), "correlation": "XX,YY", "xaxis": "scan", "yaxis": "phase", "xdatacolumn": "corrected/model_vector", "ydatacolumn": "corrected/model_vector", "coloraxis": "baseline", "expformat": "png", "exprange": "all", "overwrite": True, "showgui": False, "avgtime": "64", "avgchannel": "32", "plotfile": "{}.{}.bp.phasescan.png".format(PREFIX, label) }, input=INPUT, output=OUTPUT, label="pscan_for_bp_%s" % label) return ([ "backup_flags_prior_1gc_{}".format(label) ] + [ "set_flux_reference_{}".format(label) ] if do_predict else []) + ([ "delay_calibration_bp_{}".format(label), "clip_delay_{}".format(label), "remove_bp_average_{}".format(label), "bp_freq_calibration_{}".format(label), "apply_sols_bp_{}".format(label), ] + cal_im_steps + ([ "delay_calibration_gc_{}".format(label), "clip_delay_gc_{}".format(label), ] if len(ALTCAL) > 0 or DO_USE_GAINCALIBRATOR_DELAY else []) + ([ "apgain_{}".format(label), "fluxscale_{}".format(label), ] if DO_USE_GAINCALIBRATOR else []) + ([ "remove_altcal_average_{}".format(label), "plot_altgains_{}".format(label), ] if len(ALTCAL) > 0 else []) if not applyonly else [ "apply_sols_bp_{}".format(label) ]) +\ [ "plot_delays_{}".format(label), "plot_gain_{}".format(label), "plot_bpgain_{}".format(label), "apply_sols_bp_{}".format(label), ] + ([ "apply_1GC_solutions_{}".format(label) ] if do_apply_target or DO_USE_GAINCALIBRATOR else []) +\ [ "apply_sols_ac_{0:s}_{1:s}".format(FDB[a], label) for a in ALTCAL ] +\ [ "phaseamp_plot_for_bandpass_{}".format(label), "reim_plot_for_bp_{}".format(label), "afreq_for_bp_{}".format(label), "pfreq_for_bp_{}".format(label), "ascan_for_bp_{}".format(label), "pscan_for_bp_{}".format(label) ] + ([ "afreq_for_gain_{}".format(label), "pfreq_for_gain_{}".format(label), "ascan_for_gain_{}".format(label), "pscan_for_gain_{}".format(label), "phaseamp_plot_for_gain_{}".format(label), "reim_plot_for_gain_{}".format(label), ] if len(ALTCAL) > 0 or DO_USE_GAINCALIBRATOR else []) def finalize_and_split(): for ti, t in enumerate(TARGET): recipe.add("cab/casa_split", "split_%d" % ti, { "vis": ZEROGEN_DATA, "field": ",".join([FDB[t]]), "outputvis": FIRSTGEN_DATA[ti] }, input=INPUT, output=OUTPUT, label="split_%d" % ti) recipe.add("cab/casa_flagmanager", "backup_1GC_flags_%d" % ti, { "vis": FIRSTGEN_DATA[ti], "mode": "save", "versionname": "1GC_LEGACY", }, input=INPUT, output=OUTPUT, label="backup_1GC_flags_%d" % ti) return ["split_%d" % ti for ti, t in enumerate(TARGET)] + \ ["backup_1GC_flags_%d" % ti for ti, t in enumerate(TARGET)] def define_steps(): STEPS = [] if not args.skip_prepdata: STEPS += prepare_data() for a in FLAGANT: STEPS += addmanualflags(recipe, "Pointing issue {}".format(a), antenna=a, spw="", scan="", uvrange="", field="") if not args.skip_prelim_flagging: STEPS += rfiflag_data(do_flag_targets=False, steplabel="flagpass1", exec_strategy="mk_rfi_flagging_calibrator_fields_firstpass.yaml", on_corr_residuals=False, dc="DATA") if not args.skip_prelim_1GC: STEPS += do_1GC(recipe, label="prelim", do_predict=True) if not args.skip_final_flagging: STEPS += rfiflag_data(do_flag_targets=False, steplabel="flagpass2", exec_strategy="mk_rfi_flagging_calibrator_fields_secondpass.yaml", on_corr_residuals=True, dc="CORRECTED_DATA") if not args.skip_final_1GC: STEPS += do_1GC(recipe, label="second_round", do_predict=False, do_apply_target=False) if not args.skip_transfer_to_targets: STEPS += do_1GC(recipe, label="apply_only", do_predict=False, do_apply_target=True, applyonly=True) if not args.skip_flag_targets: STEPS += rfiflag_data(do_flag_targets=True, steplabel="flagfinal", exec_strategy="mk_rfi_flagging_target_fields_firstpass.yaml", on_corr_residuals=False, dc="CORRECTED_DATA") if not args.skip_final_split: STEPS += finalize_and_split() checked_opts = OrderedDict() for o in STEPS: checked_opts[o] = True return checked_opts def compile_and_run(STEPS): if len(STEPS) != 0: recipe.run(STEPS) def main(): steps = define_steps() compile_and_run(list(steps.keys())) if __name__ == "__main__": main()
[ "stimela.dismissable.dismissable", "numpy.sum", "argparse.ArgumentParser", "shutil.rmtree", "vermeerkat.log.info", "os.path.isdir", "os.path.dirname", "os.path.exists", "stimela.register_globals", "os.environ.get", "numpy.max", "numpy.min", "collections.OrderedDict", "shutil.copytree", "...
[((277, 345), 'argparse.ArgumentParser', 'argparse.ArgumentParser', (['"""MeerKAT BasicApplyTransfer (BAT) pipeline"""'], {}), "('MeerKAT BasicApplyTransfer (BAT) pipeline')\n", (300, 345), False, 'import argparse\n'), ((8170, 8228), 'vermeerkat.log.info', 'vermeerkat.log.info', (['"""The following fields are available:"""'], {}), "('The following fields are available:')\n", (8189, 8228), False, 'import vermeerkat\n'), ((8809, 8835), 'stimela.register_globals', 'stimela.register_globals', ([], {}), '()\n', (8833, 8835), False, 'import stimela\n'), ((5782, 5840), 'vermeerkat.log.info', 'vermeerkat.log.info', (['"""The following fields are available:"""'], {}), "('The following fields are available:')\n", (5801, 5840), False, 'import vermeerkat\n'), ((5935, 5946), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (5943, 5946), False, 'import sys\n'), ((5984, 6020), 'os.path.dirname', 'os.path.dirname', (['vermeerkat.__file__'], {}), '(vermeerkat.__file__)\n', (5999, 6020), False, 'import os\n'), ((6036, 6075), 'os.path.join', 'os.path.join', (['mod_path', '"""data"""', '"""input"""'], {}), "(mod_path, 'data', 'input')\n", (6048, 6075), False, 'import os\n'), ((6080, 6112), 'shutil.copytree', 'shutil.copytree', (['data_dir', 'INPUT'], {}), '(data_dir, INPUT)\n', (6095, 6112), False, 'import shutil\n'), ((6121, 6142), 'os.path.exists', 'os.path.exists', (['INPUT'], {}), '(INPUT)\n', (6135, 6142), False, 'import os\n'), ((6169, 6189), 'os.path.isdir', 'os.path.isdir', (['INPUT'], {}), '(INPUT)\n', (6182, 6189), False, 'import os\n'), ((7413, 7466), 'vermeerkat.log.info', 'vermeerkat.log.info', (['"""*NO* gain calibrator specified"""'], {}), "('*NO* gain calibrator specified')\n", (7432, 7466), False, 'import vermeerkat\n'), ((7581, 7655), 'vermeerkat.log.info', 'vermeerkat.log.info', (['"""Will transfer rate calibraton using gain calibrator"""'], {}), "('Will transfer rate calibraton using gain calibrator')\n", (7600, 7655), False, 'import vermeerkat\n'), ((7666, 7745), 'vermeerkat.log.info', 'vermeerkat.log.info', (['"""Will *NOT* transfer rate calibraton from gain calibrator"""'], {}), "('Will *NOT* transfer rate calibraton from gain calibrator')\n", (7685, 7745), False, 'import vermeerkat\n'), ((41749, 41762), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (41760, 41762), False, 'from collections import OrderedDict\n'), ((6195, 6215), 'shutil.rmtree', 'shutil.rmtree', (['INPUT'], {}), '(INPUT)\n', (6208, 6215), False, 'import shutil\n'), ((8983, 9027), 'os.environ.get', 'os.environ.get', (['"""SINGULARITY_PULLFOLDER"""', '""""""'], {}), "('SINGULARITY_PULLFOLDER', '')\n", (8997, 9027), False, 'import os\n'), ((5603, 5636), 'os.path.join', 'os.path.join', (['MSDIR', 'ZEROGEN_DATA'], {}), '(MSDIR, ZEROGEN_DATA)\n', (5615, 5636), False, 'import os\n'), ((8769, 8780), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (8777, 8780), False, 'import sys\n'), ((12594, 12654), 'stimela.dismissable.dismissable', 'sdm.dismissable', (["('MODEL_DATA' if on_corr_residuals else None)"], {}), "('MODEL_DATA' if on_corr_residuals else None)\n", (12609, 12654), True, 'import stimela.dismissable as sdm\n'), ((12690, 12711), 'stimela.dismissable.dismissable', 'sdm.dismissable', (['None'], {}), '(None)\n', (12705, 12711), True, 'import stimela.dismissable as sdm\n'), ((12747, 12768), 'stimela.dismissable.dismissable', 'sdm.dismissable', (['None'], {}), '(None)\n', (12762, 12768), True, 'import stimela.dismissable as sdm\n'), ((12804, 12825), 'stimela.dismissable.dismissable', 'sdm.dismissable', (['None'], {}), '(None)\n', (12819, 12825), True, 'import stimela.dismissable as sdm\n'), ((13383, 13443), 'stimela.dismissable.dismissable', 'sdm.dismissable', (["('MODEL_DATA' if on_corr_residuals else None)"], {}), "('MODEL_DATA' if on_corr_residuals else None)\n", (13398, 13443), True, 'import stimela.dismissable as sdm\n'), ((13536, 13557), 'stimela.dismissable.dismissable', 'sdm.dismissable', (['None'], {}), '(None)\n', (13551, 13557), True, 'import stimela.dismissable as sdm\n'), ((13593, 13614), 'stimela.dismissable.dismissable', 'sdm.dismissable', (['None'], {}), '(None)\n', (13608, 13614), True, 'import stimela.dismissable as sdm\n'), ((13650, 13671), 'stimela.dismissable.dismissable', 'sdm.dismissable', (['None'], {}), '(None)\n', (13665, 13671), True, 'import stimela.dismissable as sdm\n'), ((14963, 14984), 'stimela.dismissable.dismissable', 'sdm.dismissable', (['None'], {}), '(None)\n', (14978, 14984), True, 'import stimela.dismissable as sdm\n'), ((18001, 18026), 'os.path.join', 'os.path.join', (['OUTPUT', 'vis'], {}), '(OUTPUT, vis)\n', (18013, 18026), False, 'import os\n'), ((18145, 18155), 'numpy.sum', 'np.sum', (['fl'], {}), '(fl)\n', (18151, 18155), True, 'import numpy as np\n'), ((18420, 18430), 'numpy.sum', 'np.sum', (['fl'], {}), '(fl)\n', (18426, 18430), True, 'import numpy as np\n'), ((18263, 18281), 'numpy.max', 'np.max', (['clipminmax'], {}), '(clipminmax)\n', (18269, 18281), True, 'import numpy as np\n'), ((18337, 18355), 'numpy.min', 'np.min', (['clipminmax'], {}), '(clipminmax)\n', (18343, 18355), True, 'import numpy as np\n')]
#! /usr/bin/python # -*- coding: utf-8 -*- """NAO tasks.""" import itertools import os import numpy as np import torch import torch.nn.functional as F from fairseq import utils from fairseq.data import ConcatDataset, NaoLanguagePairDataset from fairseq.data.nao_dataset import SingleTensorDataset from . import register_task from .translation import TranslationTask # TODO: Move it to molecule related folder. DEFAULT_BOUNDS = { '01': (0.0, 1.0), 'default': (0.0, 1.0), 'drd2-m1': (0.0, 0.05), 'qed-m1': (0.7, 0.8), 'logp04-m1': (-10.0, 2.0), 'logp06-m1': (-10.0, 4.0), 'drd2-default': (0.0, 1.0), 'qed-default': (0.0, 1.0), 'logp-default': (-10.0, 5.0), } def _get_bound(bound_str: str): if bound_str is None: return None if ',' in bound_str: low, high = bound_str.split(',') return float(low), float(high) bound = DEFAULT_BOUNDS.get(bound_str, None) if bound is None: print('| WARNING: default bound name {!r} not found, fall back to [0, 1].'.format(bound_str)) bound = (0.0, 1.0) return bound def load_score( data_path, split, src, props, bounds, combine, upsample_primary, ): if len(props) > 1: raise NotImplementedError('multiple property scores not supported now') if len(props) != len(bounds): raise RuntimeError('property and bound length mismatch') prop = props[0] bound = _get_bound(bounds[0]) prop_name = '' if prop is None else '-{}'.format(prop) score_datasets = [] for k in itertools.count(): split_k = split + (str(k) if k > 0 else '') filename = os.path.join(data_path, '{}.score{}.{}.npz'.format(split_k, prop_name, src)) if not os.path.exists(filename): if k > 0: break else: raise FileNotFoundError('Score dataset not found: {}, {} ({})'.format(split, prop, data_path)) data = np.load(filename)['arr_0'] if bound is None: if np.any(data > 1.0) and np.any(data < 0.0): raise RuntimeError('scores must be scaled to [0, 1]') else: assert bound[0] < bound[1] data = np.maximum(data, bound[0]) data = np.minimum(data, bound[1]) data = (data - bound[0]) / (bound[1] - bound[0]) dataset = SingleTensorDataset(torch.from_numpy(data).to(dtype=torch.float32)) score_datasets.append(dataset) print('| {} {} {}-score{} {} examples'.format(data_path, split_k, src, prop_name, len(score_datasets[-1]))) if not combine: break if len(score_datasets) == 1: score_dataset = score_datasets[0] else: sample_ratios = [1] * len(score_datasets) sample_ratios[0] = upsample_primary score_dataset = ConcatDataset(score_datasets, sample_ratios) return score_dataset @register_task('nao_translation') class NaoTranslationTask(TranslationTask): """Translation task with NAO prediction. Include sources, targets and scores. """ def __init__(self, args, src_dict, tgt_dict): super().__init__(args, src_dict, tgt_dict) @staticmethod def add_args(parser): TranslationTask.add_args(parser) parser.add_argument('--disable-score', action='store_true', default=False, help='disable score dataset, train as common translation tasks') parser.add_argument('--score-prop', default=None, help='colon separated score property list, will use "score" name by default') parser.add_argument('--score-bound', default=None, help='colon separated score bound list in format "<LOW>,<HIGH>" or string name, ' 'default is no scaling') # Evaluation arguments. parser.add_argument('--eval-score-only', action='store_true', help='Only evaluate predicted scores for NAO tasks') parser.add_argument('--nao-gen-step', action='store_true', help='Generate new target sequences for NAO tasks') parser.add_argument('--nao-lambda-max', type=float, default=1000.0, help='Max value of NAO predict lambda, default is %(default)r') @classmethod def setup_task(cls, args, **kwargs): instance = super().setup_task(args, **kwargs) if instance.args.eval_score_only: print('| NAO evaluate score only') if instance.args.nao_gen_step: print('| NAO generate | max-lambda {:6.1f}'.format(instance.args.nao_lambda_max)) return instance def load_dataset(self, split, epoch=0, combine=False, **kwargs): super().load_dataset(split, epoch=epoch, combine=combine, **kwargs) if self.args.disable_score: score = None else: paths = self.args.data.split(':') assert len(paths) > 0 data_path = paths[epoch % len(paths)] # infer langcode src, tgt = self.args.source_lang, self.args.target_lang if self.args.score_prop is None: props = [None] else: props = self.args.score_prop.split(':') if self.args.score_bound is None: bounds = [None] else: bounds = self.args.score_bound.split(':') score = load_score( data_path, split, src, props, bounds, combine=combine, upsample_primary=self.args.upsample_primary, ) self.datasets[split] = NaoLanguagePairDataset.from_base_dataset(self.datasets[split], score) def build_dataset_for_inference(self, src_tokens, src_lengths): return NaoLanguagePairDataset(src_tokens, src_lengths, self.source_dictionary) def valid_step(self, sample, model, criterion): if self.args.eval_score_only: assert hasattr(criterion, 'eval_score_only'), 'the criterion does not support --eval-score-only mode' old_flag = criterion.eval_score_only criterion.eval_score_only = True loss, sample_size, logging_output = super().valid_step(sample, model, criterion) criterion.eval_score_only = old_flag return loss, sample_size, logging_output else: return super().valid_step(sample, model, criterion) def predict_step(self, sample, model): model.eval() with torch.no_grad(): predict_value = model.encode_and_predict(**sample['net_input']) return predict_value def inference_step(self, generator, models, sample, prefix_tokens=None): if self.args.nao_gen_step: # TODO pass else: return super().inference_step(generator, models, sample, prefix_tokens=prefix_tokens) def generate_new_seq_step(self): # TODO: Add new sequence generation step of NAO tasks. pass
[ "numpy.load", "numpy.minimum", "numpy.maximum", "fairseq.data.ConcatDataset", "os.path.exists", "itertools.count", "numpy.any", "fairseq.data.NaoLanguagePairDataset.from_base_dataset", "torch.no_grad", "fairseq.data.NaoLanguagePairDataset", "torch.from_numpy" ]
[((1550, 1567), 'itertools.count', 'itertools.count', ([], {}), '()\n', (1565, 1567), False, 'import itertools\n'), ((2826, 2870), 'fairseq.data.ConcatDataset', 'ConcatDataset', (['score_datasets', 'sample_ratios'], {}), '(score_datasets, sample_ratios)\n', (2839, 2870), False, 'from fairseq.data import ConcatDataset, NaoLanguagePairDataset\n'), ((5653, 5722), 'fairseq.data.NaoLanguagePairDataset.from_base_dataset', 'NaoLanguagePairDataset.from_base_dataset', (['self.datasets[split]', 'score'], {}), '(self.datasets[split], score)\n', (5693, 5722), False, 'from fairseq.data import ConcatDataset, NaoLanguagePairDataset\n'), ((5807, 5878), 'fairseq.data.NaoLanguagePairDataset', 'NaoLanguagePairDataset', (['src_tokens', 'src_lengths', 'self.source_dictionary'], {}), '(src_tokens, src_lengths, self.source_dictionary)\n', (5829, 5878), False, 'from fairseq.data import ConcatDataset, NaoLanguagePairDataset\n'), ((1734, 1758), 'os.path.exists', 'os.path.exists', (['filename'], {}), '(filename)\n', (1748, 1758), False, 'import os\n'), ((1949, 1966), 'numpy.load', 'np.load', (['filename'], {}), '(filename)\n', (1956, 1966), True, 'import numpy as np\n'), ((2202, 2228), 'numpy.maximum', 'np.maximum', (['data', 'bound[0]'], {}), '(data, bound[0])\n', (2212, 2228), True, 'import numpy as np\n'), ((2248, 2274), 'numpy.minimum', 'np.minimum', (['data', 'bound[1]'], {}), '(data, bound[1])\n', (2258, 2274), True, 'import numpy as np\n'), ((6532, 6547), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (6545, 6547), False, 'import torch\n'), ((2017, 2035), 'numpy.any', 'np.any', (['(data > 1.0)'], {}), '(data > 1.0)\n', (2023, 2035), True, 'import numpy as np\n'), ((2040, 2058), 'numpy.any', 'np.any', (['(data < 0.0)'], {}), '(data < 0.0)\n', (2046, 2058), True, 'import numpy as np\n'), ((2375, 2397), 'torch.from_numpy', 'torch.from_numpy', (['data'], {}), '(data)\n', (2391, 2397), False, 'import torch\n')]
#! -*- coding: utf-8 -*- # ็”จGlobalPointerๅšไธญๆ–‡ๅ‘ฝๅๅฎžไฝ“่ฏ†ๅˆซ # ๆ•ฐๆฎ้›† https://github.com/CLUEbenchmark/CLUENER2020 import json import numpy as np from snippets import * from bert4keras.backend import keras from bert4keras.backend import multilabel_categorical_crossentropy from bert4keras.layers import EfficientGlobalPointer as GlobalPointer from bert4keras.snippets import sequence_padding, DataGenerator from bert4keras.snippets import open from tqdm import tqdm maxlen = 256 epochs = 10 batch_size = 32 categories = set() def load_data(filename): """ๅŠ ่ฝฝๆ•ฐๆฎ ๅ•ๆกๆ ผๅผ๏ผš[text, (start, end, label), (start, end, label), ...]๏ผŒ ๆ„ๅ‘ณ็€text[start:end + 1]ๆ˜ฏ็ฑปๅž‹ไธบlabel็š„ๅฎžไฝ“ใ€‚ """ D = [] with open(filename, encoding='utf-8') as f: for l in f: l = json.loads(l) d = [l['text']] for k, v in l.get('label', {}).items(): categories.add(k) for spans in v.values(): for start, end in spans: d.append((start, end, k)) D.append(d) return D # ๆ ‡ๆณจๆ•ฐๆฎ train_data = load_data(data_path + 'cluener/train.json') valid_data = load_data(data_path + 'cluener/dev.json') categories = list(sorted(categories)) num_classes = len(categories) class data_generator(DataGenerator): """ๆ•ฐๆฎ็”Ÿๆˆๅ™จ """ def __iter__(self, random=False): batch_token_ids, batch_segment_ids, batch_labels = [], [], [] for is_end, d in self.sample(random): tokens = tokenizer.tokenize(d[0], maxlen=maxlen) mapping = tokenizer.rematch(d[0], tokens) start_mapping = {j[0]: i for i, j in enumerate(mapping) if j} end_mapping = {j[-1]: i for i, j in enumerate(mapping) if j} token_ids = tokenizer.tokens_to_ids(tokens) segment_ids = [0] * len(token_ids) labels = np.zeros((len(categories), maxlen, maxlen)) for start, end, label in d[1:]: if start in start_mapping and end in end_mapping: start = start_mapping[start] end = end_mapping[end] label = categories.index(label) labels[label, start, end] = 1 batch_token_ids.append(token_ids) batch_segment_ids.append(segment_ids) batch_labels.append(labels[:, :len(token_ids), :len(token_ids)]) if len(batch_token_ids) == self.batch_size or is_end: batch_token_ids = sequence_padding(batch_token_ids) batch_segment_ids = sequence_padding(batch_segment_ids) batch_labels = sequence_padding(batch_labels, seq_dims=3) yield [batch_token_ids, batch_segment_ids], batch_labels batch_token_ids, batch_segment_ids, batch_labels = [], [], [] # ่ฝฌๆขๆ•ฐๆฎ้›† train_generator = data_generator(train_data, batch_size) valid_generator = data_generator(valid_data, batch_size) def globalpointer_crossentropy(y_true, y_pred): """็ป™GlobalPointer่ฎพ่ฎก็š„ไบคๅ‰็†ต """ bh = K.prod(K.shape(y_pred)[:2]) y_true = K.reshape(y_true, (bh, -1)) y_pred = K.reshape(y_pred, (bh, -1)) return K.mean(multilabel_categorical_crossentropy(y_true, y_pred)) def globalpointer_f1score(y_true, y_pred): """็ป™GlobalPointer่ฎพ่ฎก็š„F1 """ y_pred = K.cast(K.greater(y_pred, 0), K.floatx()) return 2 * K.sum(y_true * y_pred) / K.sum(y_true + y_pred) # ๆž„ๅปบๆจกๅž‹ output = base.model.output output = GlobalPointer( heads=num_classes, head_size=base.attention_head_size, use_bias=False, kernel_initializer=base.initializer )(output) model = keras.models.Model(base.model.input, output) model.summary() model.compile( loss=globalpointer_crossentropy, optimizer=optimizer, metrics=[globalpointer_f1score] ) class Evaluator(keras.callbacks.Callback): """ไฟๅญ˜้ชŒ่ฏ้›†f1ๆœ€ๅฅฝ็š„ๆจกๅž‹ """ def __init__(self): self.best_val_f1 = 0 def on_epoch_end(self, epoch, logs=None): f1, precision, recall = self.evaluate(valid_generator) # ไฟๅญ˜ๆœ€ไผ˜ if f1 >= self.best_val_f1: self.best_val_f1 = f1 model.save_weights('weights/cluener.weights') print( 'valid: f1: %.5f, precision: %.5f, recall: %.5f, best f1: %.5f\n' % (f1, precision, recall, self.best_val_f1) ) def evaluate(self, data): X, Y, Z = 1e-10, 1e-10, 1e-10 for x_true, y_true in data: y_pred = (model.predict(x_true) > 0).astype(int) X += (y_pred * y_true).sum() Y += y_pred.sum() Z += y_true.sum() f1, precision, recall = 2 * X / (Y + Z), X / Y, X / Z return f1, precision, recall def test_predict(in_file, out_file): """่พ“ๅ‡บๆต‹่ฏ•็ป“ๆžœๅˆฐๆ–‡ไปถ ็ป“ๆžœๆ–‡ไปถๅฏไปฅๆไบคๅˆฐ https://www.cluebenchmarks.com ่ฏ„ๆต‹ใ€‚ """ test_data = load_data(in_file) test_generator = data_generator(test_data, batch_size) results = [] for x_true, _ in tqdm(test_generator, ncols=0): y_pred = model.predict(x_true) for y in y_pred: results.append(np.where(y > 0)) fw = open(out_file, 'w', encoding='utf-8') with open(in_file) as fr: for l, r in zip(fr, results): l = json.loads(l) l['label'] = {} tokens = tokenizer.tokenize(l['text'], maxlen=maxlen) mapping = tokenizer.rematch(l['text'], tokens) for label, start, end in zip(*r): label = categories[label] start, end = mapping[start][0], mapping[end][-1] if label not in l['label']: l['label'][label] = {} entity = l['text'][start:end + 1] if entity not in l['label'][label]: l['label'][label][entity] = [] l['label'][label][entity].append([start, end]) l = json.dumps(l, ensure_ascii=False) fw.write(l + '\n') fw.close() if __name__ == '__main__': evaluator = Evaluator() model.fit_generator( train_generator.forfit(), steps_per_epoch=len(train_generator), epochs=epochs, callbacks=[evaluator] ) model.load_weights('weights/cluener.weights') test_predict( in_file=data_path + 'cluener/test.json', out_file='results/cluener_predict.json' ) else: model.load_weights('weights/cluener.weights')
[ "tqdm.tqdm", "json.loads", "bert4keras.backend.multilabel_categorical_crossentropy", "bert4keras.backend.keras.models.Model", "json.dumps", "bert4keras.snippets.open", "numpy.where", "bert4keras.layers.EfficientGlobalPointer", "bert4keras.snippets.sequence_padding" ]
[((3612, 3656), 'bert4keras.backend.keras.models.Model', 'keras.models.Model', (['base.model.input', 'output'], {}), '(base.model.input, output)\n', (3630, 3656), False, 'from bert4keras.backend import keras\n'), ((3455, 3580), 'bert4keras.layers.EfficientGlobalPointer', 'GlobalPointer', ([], {'heads': 'num_classes', 'head_size': 'base.attention_head_size', 'use_bias': '(False)', 'kernel_initializer': 'base.initializer'}), '(heads=num_classes, head_size=base.attention_head_size,\n use_bias=False, kernel_initializer=base.initializer)\n', (3468, 3580), True, 'from bert4keras.layers import EfficientGlobalPointer as GlobalPointer\n'), ((4939, 4968), 'tqdm.tqdm', 'tqdm', (['test_generator'], {'ncols': '(0)'}), '(test_generator, ncols=0)\n', (4943, 4968), False, 'from tqdm import tqdm\n'), ((5088, 5125), 'bert4keras.snippets.open', 'open', (['out_file', '"""w"""'], {'encoding': '"""utf-8"""'}), "(out_file, 'w', encoding='utf-8')\n", (5092, 5125), False, 'from bert4keras.snippets import open\n'), ((696, 728), 'bert4keras.snippets.open', 'open', (['filename'], {'encoding': '"""utf-8"""'}), "(filename, encoding='utf-8')\n", (700, 728), False, 'from bert4keras.snippets import open\n'), ((3160, 3211), 'bert4keras.backend.multilabel_categorical_crossentropy', 'multilabel_categorical_crossentropy', (['y_true', 'y_pred'], {}), '(y_true, y_pred)\n', (3195, 3211), False, 'from bert4keras.backend import multilabel_categorical_crossentropy\n'), ((5135, 5148), 'bert4keras.snippets.open', 'open', (['in_file'], {}), '(in_file)\n', (5139, 5148), False, 'from bert4keras.snippets import open\n'), ((771, 784), 'json.loads', 'json.loads', (['l'], {}), '(l)\n', (781, 784), False, 'import json\n'), ((5210, 5223), 'json.loads', 'json.loads', (['l'], {}), '(l)\n', (5220, 5223), False, 'import json\n'), ((5849, 5882), 'json.dumps', 'json.dumps', (['l'], {'ensure_ascii': '(False)'}), '(l, ensure_ascii=False)\n', (5859, 5882), False, 'import json\n'), ((2482, 2515), 'bert4keras.snippets.sequence_padding', 'sequence_padding', (['batch_token_ids'], {}), '(batch_token_ids)\n', (2498, 2515), False, 'from bert4keras.snippets import sequence_padding, DataGenerator\n'), ((2552, 2587), 'bert4keras.snippets.sequence_padding', 'sequence_padding', (['batch_segment_ids'], {}), '(batch_segment_ids)\n', (2568, 2587), False, 'from bert4keras.snippets import sequence_padding, DataGenerator\n'), ((2619, 2661), 'bert4keras.snippets.sequence_padding', 'sequence_padding', (['batch_labels'], {'seq_dims': '(3)'}), '(batch_labels, seq_dims=3)\n', (2635, 2661), False, 'from bert4keras.snippets import sequence_padding, DataGenerator\n'), ((5061, 5076), 'numpy.where', 'np.where', (['(y > 0)'], {}), '(y > 0)\n', (5069, 5076), True, 'import numpy as np\n')]
import pandas as pd import numpy as np import matplotlib.pyplot as plt import csv array=[['wrong_covid_normal','wrong_covid_pneu','correct_covid'], ['wrong_pneu_normal','correct_pneu','wrong_pneu_covid'], ['correct_normal','wrong_normal_pneu','wrong_normal_covid']] results={1:{},2:{},3:{},4:{},5:{}} for fo in range(1,6): report=pd.read_excel('results/selected_fold{}.xlsx'.format(fo)) data={} for index,item in report.iterrows(): images_num=item['tp']+item['fp'] data[item['name']]=[[],[],[]] acc=item['tp']/(item['tp']+item['fp']) covid_recall=item['correct_covid']/item['covid_num'] covid_Specificity=(images_num-item['covid_num']-item['wrong_covid'])/(images_num-item['covid_num']-item['wrong_covid']+item['wrong_covid']) covid_accuracy=(images_num-item['covid_num']-item['wrong_covid']+item['correct_covid'])/(images_num-item['covid_num']-item['wrong_covid']+item['correct_covid']+item['wrong_covid']+item['not_detected_covid']) pneu_recall=item['correct_pneu']/item['pneu_num'] pneu_Specificity=(images_num-item['pneu_num']-item['wrong_pneu'])/(images_num-item['pneu_num']-item['wrong_pneu']+item['wrong_pneu']) pneu_accuracy=(images_num-item['pneu_num']-item['wrong_pneu']+item['correct_pneu'])/(images_num-item['pneu_num']-item['wrong_pneu']+item['correct_pneu']+item['wrong_pneu']+item['not_detected_pneu']) normal_recall=item['correct_normal']/item['normal_num'] normal_Specificity=(images_num-item['normal_num']-item['wrong_normal'])/(images_num-item['normal_num']-item['wrong_normal']+item['wrong_normal']) normal_accuracy=(images_num-item['normal_num']-item['wrong_normal']+item['correct_normal'])/(images_num-item['normal_num']-item['wrong_normal']+item['correct_normal']+item['wrong_normal']+item['not_detected_normal']) results[fo][item['name']]={'acc':acc,'covid_recall':covid_recall,'covid_Specificity':covid_Specificity, 'covid_accuracy':covid_accuracy,'pneu_recall':pneu_recall,'pneu_Specificity':pneu_Specificity, 'pneu_accuracy':pneu_accuracy, 'normal_recall':normal_recall,'normal_Specificity':normal_Specificity, 'normal_accuracy':normal_accuracy} for nn,aa in enumerate(array): for a in aa: data[item['name']][nn].append(item[a]) for key in data: gt = ['NORMAL','PNEUMONIA','COVID-19'] preds = ["COVID-19", "PNEUMONIA", "NORMAL",] fig, ax = plt.subplots() im = ax.imshow(np.array(data[key]), interpolation='nearest', cmap=plt.cm.Blues) index=key.find('-') if 'concatenat' in key: ax.set(xticks=np.arange(np.array(data[key]).shape[1]), yticks=np.arange(np.array(data[key]).shape[0]), # ... and label them with the respective list entries xticklabels=gt, yticklabels=preds, title='Confusion Matrix for the concatenated network-fold{}'.format(fo), ylabel='Ground Truth Label', xlabel='Predicted Label') else: ax.set(xticks=np.arange(np.array(data[key]).shape[1]), yticks=np.arange(np.array(data[key]).shape[0]), # ... and label them with the respective list entries xticklabels=gt, yticklabels=preds, title='Confusion Matrix for {}-fold{}'.format(key[:index],fo), ylabel='Ground Truth Label', xlabel='Predicted Label') # Rotate the tick labels and set their alignment. plt.setp(ax.get_xticklabels(), rotation=45, ha="right", rotation_mode="anchor") fmt = '.2f' thresh = 1000000. # Loop over data dimensions and create text annotations. for i in range(len(gt)): for j in range(len(preds)): ax.text(j, i, format(np.array(data[key])[i, j]), ha="center", va="center", color="white" if np.array(data[key])[i, j] > thresh else "black") fig.tight_layout() #plt.show() dash=key.find('-') plt.savefig('{}-fold{}-confusion_matrix.pdf'.format(key[:dash],fo)) results['Full']={'Xception':{}, 'concatenate':{},'ResNet50V2':{}} results['average']={'Xception':{}, 'concatenate':{},'ResNet50V2':{}} nets=['Xception','ResNet50V2','concatenate'] for net in nets: for fokey in results: for netkey in results[fokey]: if net in netkey: for param in results[fokey][netkey]: if param not in results['Full'][net]: results['Full'][net][param]=[] results['Full'][net][param].append(results[fokey][netkey][param]) for net in results['Full']: for param in results['Full'][net]: results['average'][net][param]=np.average(results['Full'][net][param][:-1]) temp_data=[] for fo in [1,2,3,4,5,'average']: for net in results[fo]: if 'Xception' in net: temp_data.append([results[fo][net]['covid_Specificity'], results[fo][net]['pneu_Specificity'], results[fo][net]['normal_Specificity'], results[fo][net]['covid_accuracy'], results[fo][net]['pneu_accuracy'], results[fo][net]['normal_accuracy']]) for net in results[fo]: if 'ResNet' in net: temp_data.append([results[fo][net]['covid_Specificity'], results[fo][net]['pneu_Specificity'], results[fo][net]['normal_Specificity'], results[fo][net]['covid_accuracy'], results[fo][net]['pneu_accuracy'], results[fo][net]['normal_accuracy']]) for net in results[fo]: if 'oncatenat' in net: temp_data.append([results[fo][net]['covid_Specificity'], results[fo][net]['pneu_Specificity'], results[fo][net]['normal_Specificity'], results[fo][net]['covid_accuracy'], results[fo][net]['pneu_accuracy'], results[fo][net]['normal_accuracy']])
[ "numpy.array", "numpy.average", "matplotlib.pyplot.subplots" ]
[((2672, 2686), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (2684, 2686), True, 'import matplotlib.pyplot as plt\n'), ((5142, 5186), 'numpy.average', 'np.average', (["results['Full'][net][param][:-1]"], {}), "(results['Full'][net][param][:-1])\n", (5152, 5186), True, 'import numpy as np\n'), ((2711, 2730), 'numpy.array', 'np.array', (['data[key]'], {}), '(data[key])\n', (2719, 2730), True, 'import numpy as np\n'), ((4123, 4142), 'numpy.array', 'np.array', (['data[key]'], {}), '(data[key])\n', (4131, 4142), True, 'import numpy as np\n'), ((2875, 2894), 'numpy.array', 'np.array', (['data[key]'], {}), '(data[key])\n', (2883, 2894), True, 'import numpy as np\n'), ((2939, 2958), 'numpy.array', 'np.array', (['data[key]'], {}), '(data[key])\n', (2947, 2958), True, 'import numpy as np\n'), ((3320, 3339), 'numpy.array', 'np.array', (['data[key]'], {}), '(data[key])\n', (3328, 3339), True, 'import numpy as np\n'), ((3384, 3403), 'numpy.array', 'np.array', (['data[key]'], {}), '(data[key])\n', (3392, 3403), True, 'import numpy as np\n'), ((4252, 4271), 'numpy.array', 'np.array', (['data[key]'], {}), '(data[key])\n', (4260, 4271), True, 'import numpy as np\n')]
# Python 3.7.6 # -*- coding: utf-8 -*- # Author: <NAME> import os import numpy as np import torch from torch.nn.utils.rnn import pad_sequence char_list = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' len_char_list = len(char_list) def pad_labels(): path = os.getcwd() labels = [] max_text_length = 0 np_data = np.load(path+'/val/val_labels.npy', allow_pickle=True) np_data1 = np.load(path+'/test/test_labels.npy', allow_pickle=True) np_data2 = np.load(path+'/train/train_labels.npy', allow_pickle=True) datasets = ['train', 'val', 'test'] sizes = [160000, 20000, 20000] for dataset in datasets: dset = np.load(path+'/'+dataset+'/'+dataset+'_labels.npy', allow_pickle=True).tolist() new_dset = [] for arr in dset: #new_arr = arr.tolist() new_arr = torch.from_numpy(arr).long().cuda() if len(new_arr) > max_text_length: max_text_length = len(new_arr) new_dset.append(new_arr) labels.extend(new_dset) new_labels = pad_sequence(labels, padding_value=len_char_list).transpose(0,1).tolist() tmp = 0 for dataset, size in zip(datasets, sizes): new_dataset = new_labels[tmp:tmp+size] res = torch.stack([torch.LongTensor(x) for x in new_dataset]) torch.save(res, path+'/'+dataset+'/'+dataset+'_labels.pt') tmp += size if __name__ == '__main__': pad_labels()
[ "numpy.load", "torch.LongTensor", "os.getcwd", "torch.save", "torch.nn.utils.rnn.pad_sequence", "torch.from_numpy" ]
[((301, 312), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (310, 312), False, 'import os\n'), ((388, 444), 'numpy.load', 'np.load', (["(path + '/val/val_labels.npy')"], {'allow_pickle': '(True)'}), "(path + '/val/val_labels.npy', allow_pickle=True)\n", (395, 444), True, 'import numpy as np\n'), ((459, 517), 'numpy.load', 'np.load', (["(path + '/test/test_labels.npy')"], {'allow_pickle': '(True)'}), "(path + '/test/test_labels.npy', allow_pickle=True)\n", (466, 517), True, 'import numpy as np\n'), ((532, 592), 'numpy.load', 'np.load', (["(path + '/train/train_labels.npy')"], {'allow_pickle': '(True)'}), "(path + '/train/train_labels.npy', allow_pickle=True)\n", (539, 592), True, 'import numpy as np\n'), ((1421, 1489), 'torch.save', 'torch.save', (['res', "(path + '/' + dataset + '/' + dataset + '_labels.pt')"], {}), "(res, path + '/' + dataset + '/' + dataset + '_labels.pt')\n", (1431, 1489), False, 'import torch\n'), ((736, 821), 'numpy.load', 'np.load', (["(path + '/' + dataset + '/' + dataset + '_labels.npy')"], {'allow_pickle': '(True)'}), "(path + '/' + dataset + '/' + dataset + '_labels.npy', allow_pickle=True\n )\n", (743, 821), True, 'import numpy as np\n'), ((1369, 1388), 'torch.LongTensor', 'torch.LongTensor', (['x'], {}), '(x)\n', (1385, 1388), False, 'import torch\n'), ((1152, 1201), 'torch.nn.utils.rnn.pad_sequence', 'pad_sequence', (['labels'], {'padding_value': 'len_char_list'}), '(labels, padding_value=len_char_list)\n', (1164, 1201), False, 'from torch.nn.utils.rnn import pad_sequence\n'), ((925, 946), 'torch.from_numpy', 'torch.from_numpy', (['arr'], {}), '(arr)\n', (941, 946), False, 'import torch\n')]
from copy import deepcopy import numpy as np import pickle as pkl import random from joblib import Parallel, delayed from tqdm.notebook import tqdm import colorednoise as cn import mne from time import time from . import util DEFAULT_SETTINGS = { 'number_of_sources': (1, 20), 'extents': (1, 50), 'amplitudes': (1, 10), 'shapes': 'both', 'duration_of_trial': 0, 'sample_frequency': 100, 'target_snr': 4, 'beta': (0, 3), } class Simulation: ''' Simulate and hold source and M/EEG data. Attributes ---------- settings : dict The Settings for the simulation. Keys: number_of_sources : int/tuple/list number of sources. Can be a single number or a list of two numbers specifying a range. extents : int/float/tuple/list size of sources in mm. Can be a single number or a list of two numbers specifying a range. amplitudes : int/float/tuple/list the current of the source in nAm shapes : str How the amplitudes evolve over space. Can be 'gaussian' or 'flat' (i.e. uniform) or 'both'. duration_of_trial : int/float specifies the duration of a trial. sample_frequency : int specifies the sample frequency of the data. target_snr : float/tuple/list The desired average SNR of the simulation(s) beta : float/tuple/list The desired frequency spectrum slope (1/f**beta) of the noise. fwd : mne.Forward The mne-python Forward object that contains the forward model source_data : mne.sourceEstimate A source estimate object from mne-python which contains the source data. eeg_data : mne.Epochs A mne.Epochs object which contains the EEG data. n_jobs : int The number of jobs/cores to utilize. Methods ------- simulate : Simulate source and EEG data plot : plot a random sample source and EEG ''' def __init__(self, fwd, info, settings=DEFAULT_SETTINGS, n_jobs=-1, parallel=False, verbose=False): settings['sample_frequency'] = info['sfreq'] self.settings = settings self.check_settings() self.source_data = None self.eeg_data = None self.fwd = deepcopy(fwd) self.fwd.pick_channels(info['ch_names']) self.check_info(deepcopy(info)) self.info['sfreq'] = self.settings['sample_frequency'] self.subject = self.fwd['src'][0]['subject_his_id'] self.n_jobs = n_jobs self.parallel = parallel self.verbose = verbose _, _, self.pos, _ = util.unpack_fwd(self.fwd) def check_info(self, info): self.info = info.pick_channels(self.fwd.ch_names, ordered=True) def simulate(self, n_samples=10000): ''' Simulate sources and EEG data''' self.source_data = self.simulate_sources(n_samples) self.eeg_data = self.simulate_eeg() return self def plot(self): pass def simulate_sources(self, n_samples): if self.verbose: print(f'Simulate Source') if self.parallel: source_data = np.stack(Parallel(n_jobs=self.n_jobs, backend='loky') (delayed(self.simulate_source)() for _ in range(n_samples))) else: source_data = np.stack([self.simulate_source() for _ in tqdm(range(n_samples))], axis=0) # Convert to mne.SourceEstimate if self.verbose: print(f'Converting Source Data to mne.SourceEstimate object') if self.settings['duration_of_trial'] == 0: sources = util.source_to_sourceEstimate(source_data, self.fwd, sfreq=self.settings['sample_frequency'], subject=self.subject) else: sources = self.sources_to_sourceEstimates(source_data) return sources def sources_to_sourceEstimates(self, source_data): template = util.source_to_sourceEstimate(source_data[0], self.fwd, sfreq=self.settings['sample_frequency'], subject=self.subject) sources = [] for source in tqdm(source_data): tmp = deepcopy(template) tmp.data = source sources.append(tmp) return sources def simulate_source(self): ''' Returns a vector containing the dipole currents. Requires only a dipole position list and the simulation settings. Parameters ---------- pos : numpy.ndarray (n_dipoles x 3), list of dipole positions. number_of_sources : int/tuple/list number of sources. Can be a single number or a list of two numbers specifying a range. extents : int/float/tuple/list diameter of sources (in mm). Can be a single number or a list of two numbers specifying a range. amplitudes : int/float/tuple/list the current of the source in nAm shapes : str How the amplitudes evolve over space. Can be 'gaussian' or 'flat' (i.e. uniform) or 'both'. duration_of_trial : int/float specifies the duration of a trial. sample_frequency : int specifies the sample frequency of the data. Return ------ source : numpy.ndarray, (n_dipoles x n_timepoints), the simulated source signal simSettings : dict, specifications about the source. <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., & <NAME>. (2006). Evaluation of EEG localization methods using realistic simulations of interictal spikes. Neuroimage, 29(3), 734-753. ''' ########################################### # Select ranges and prepare some variables # Get number of sources is a range: number_of_sources = self.get_from_range( self.settings['number_of_sources'], dtype=int) # Get amplitudes for each source extents = [self.get_from_range(self.settings['extents'], dtype=float) for _ in range(number_of_sources)] # Decide shape of sources if self.settings['shapes'] == 'both': shapes = ['gaussian', 'flat']*number_of_sources np.random.shuffle(shapes) shapes = shapes[:number_of_sources] if type(shapes) == str: shapes = [shapes] elif self.settings['shapes'] == 'gaussian' or self.settings['shapes'] == 'flat': shapes = [self.settings['shapes']] * number_of_sources # Get amplitude gain for each source (amplitudes come in nAm) amplitudes = [self.get_from_range(self.settings['amplitudes'], dtype=float) * 1e-9 for _ in range(number_of_sources)] src_centers = np.random.choice(np.arange(self.pos.shape[0]), \ number_of_sources, replace=False) if self.settings['duration_of_trial'] > 0: signal_length = int(self.settings['sample_frequency']*self.settings['duration_of_trial']) pulselen = self.settings['sample_frequency']/10 # pulse = self.get_pulse(pulselen) signals = [] for _ in range(number_of_sources): signal = cn.powerlaw_psd_gaussian(self.get_from_range(self.settings['beta'], dtype=float), signal_length) # Old: have positive source values # signal += np.abs(np.min(signal)) # signal /= np.max(signal) # New: signal /= np.max(np.abs(signal)) signals.append(signal) sample_frequency = self.settings['sample_frequency'] else: # else its a single instance sample_frequency = 0 signal_length = 1 signals = [np.array([1])]*number_of_sources # sourceMask = np.zeros((self.pos.shape[0])) source = np.zeros((self.pos.shape[0], signal_length)) ############################################## # Loop through source centers (i.e. seeds of source positions) for i, (src_center, shape, amplitude, signal) in enumerate(zip(src_centers, shapes, amplitudes, signals)): dists = np.sqrt(np.sum((self.pos - self.pos[src_center, :])**2, axis=1)) d = np.where(dists<extents[i]/2)[0] if shape == 'gaussian': sd = np.clip(np.max(dists[d]) / 2, a_min=0.1, a_max=np.inf) # <- works better activity = np.expand_dims(util.gaussian(dists, 0, sd) * amplitude, axis=1) * signal source += activity elif shape == 'flat': activity = util.repeat_newcol(amplitude * signal, len(d)).T if len(activity.shape) == 1: if len(d) == 1: activity = np.expand_dims(activity, axis=0) else: activity = np.expand_dims(activity, axis=1) source[d, :] += activity else: msg = BaseException("shape must be of type >string< and be either >gaussian< or >flat<.") raise(msg) # sourceMask[d] = 1 # if durOfTrial > 0: # n = np.clip(int(sample_frequency * self.settings['duration_of_trial']), a_min=1, a_max=None) # sourceOverTime = util.repeat_newcol(source, n) # source = np.squeeze(sourceOverTime * signal) # if len(source.shape) == 1: # source = np.expand_dims(source, axis=1) return source def simulate_eeg(self): ''' Create EEG of specified number of trials based on sources and some SNR. Parameters ----------- sourceEstimates : list list containing mne.SourceEstimate objects fwd : mne.Forward the mne.Forward object target_snr : tuple/list/float, desired signal to noise ratio. Can be a list or tuple of two floats specifying a range. beta : float determines the frequency spectrum of the noise added to the signal: power = 1/f^beta. 0 will yield white noise, 1 will yield pink noise (1/f spectrum) n_jobs : int Number of jobs to run in parallel. -1 will utilize all cores. return_raw_data : bool if True the function returns a list of mne.SourceEstimate objects, otherwise it returns raw data Return ------- epochs : list list of either mne.Epochs objects or list of raw EEG data (see argument <return_raw_data> to change output) ''' n_simulation_trials = 20 # Desired Dim of sources: (samples x dipoles x time points) # unpack numpy array of source data if isinstance(self.source_data, (list, tuple)): sources = np.stack([source.data for source in self.source_data], axis=0) else: sources = self.source_data.data.T # if there is no temporal dimension... if len(sources.shape) < 3: # ...add empty temporal dimension sources = np.expand_dims(sources, axis=2) # Load some forward model objects fwd_fixed, leadfield = util.unpack_fwd(self.fwd)[:2] n_samples, _, _ = sources.shape n_elec = leadfield.shape[0] # Desired Dim for eeg_clean: (samples, electrodes, time points) if self.verbose: print(f'\nProject sources to EEG...') eeg_clean = self.project_sources(sources) if self.verbose: print(f'\nCreate EEG trials with noise...') if self.parallel: eeg_trials_noisy = np.stack(Parallel(n_jobs=self.n_jobs, backend='loky') (delayed(self.create_eeg_helper)(eeg_clean[sample], n_simulation_trials, self.settings['target_snr'], self.settings['beta']) for sample in tqdm(range(n_samples))), axis=0) else: eeg_trials_noisy = np.stack( [self.create_eeg_helper(eeg_clean[sample], n_simulation_trials, self.settings['target_snr'], self.settings['beta']) for sample in tqdm(range(n_samples))], axis=0) if n_simulation_trials == 1 and len(eeg_trials_noisy.shape) == 2: # Add empty dimension to contain the single trial eeg_trials_noisy = np.expand_dims(eeg_trials_noisy, axis=1) if len(eeg_trials_noisy.shape) == 3: eeg_trials_noisy = np.expand_dims(eeg_trials_noisy, axis=-1) if eeg_trials_noisy.shape[2] != n_elec: eeg_trials_noisy = np.swapaxes(eeg_trials_noisy, 1, 2) if self.verbose: print(f'\nConvert EEG matrices to a single instance of mne.Epochs...') ERP_samples_noisy = np.mean(eeg_trials_noisy, axis=1) epochs = util.eeg_to_Epochs(ERP_samples_noisy, fwd_fixed, info=self.info) return epochs def create_eeg_helper(self, eeg_sample, n_simulation_trials, target_snr, beta): ''' Helper function for EEG simulation that transforms a clean M/EEG signal to a bunch of noisy trials. Parameters ---------- eeg_sample : numpy.ndarray data sample with dimension (time_points, electrodes) n_simulation_trials : int The number of trials desired target_snr : float/list/tuple The target signal-to-noise ratio, is converted to single-trial SNR based on number of trials beta : float/list/tuple The beta exponent of the 1/f**beta noise ''' target_snr = self.get_from_range(target_snr, dtype=float) beta = self.get_from_range(beta, dtype=float) assert len(eeg_sample.shape) == 2, 'Length of eeg_sample must be 2 (time_points, electrodes)' eeg_sample = np.repeat(np.expand_dims(eeg_sample, 0), n_simulation_trials, axis=0) snr = target_snr / np.sqrt(n_simulation_trials) # Before: Add noise based on the GFP of all channels # noise_trial = self.add_noise(eeg_sample, snr, beta=beta) # NEW: ADD noise for different types of channels, separately # since they can have entirely different scales. coil_types = [ch['coil_type'] for ch in self.info['chs']] coil_types_set = list(set(coil_types)) if len(coil_types_set)>1: msg = f'Simulations attempted with more than one channel type \ ({coil_types_set}) may result in unexpected behavior. Please \ select one channel type in your data only' raise ValueError(msg) coil_types_set = np.array([int(i) for i in coil_types_set]) coil_type_assignments = np.array( [np.where(coil_types_set==coil_type)[0][0] for coil_type in coil_types] ) noise_trial = np.zeros( (eeg_sample.shape[0], eeg_sample.shape[1], eeg_sample.shape[2]) ) for i, coil_type in enumerate(coil_types_set): channel_indices = np.where(coil_type_assignments==i)[0] eeg_sample_temp = eeg_sample[:, channel_indices, :] noise_trial_subtype = self.add_noise(eeg_sample_temp, snr, beta=beta) noise_trial[:, channel_indices, :] = noise_trial_subtype return noise_trial def project_sources(self, sources): ''' Project sources through the leadfield to obtain the EEG data. Parameters ---------- sources : numpy.ndarray 3D array of shape (samples, dipoles, time points) Return ------ ''' fwd_fixed, leadfield = util.unpack_fwd(self.fwd)[:2] n_samples, n_dipoles, n_timepoints = sources.shape n_elec = leadfield.shape[0] eeg = np.zeros((n_samples, n_elec, n_timepoints)) # Swap axes to dipoles, samples, time_points sources_tmp = np.swapaxes(sources, 0,1) # Collapse last two dims into one short_shape = (sources_tmp.shape[0], sources_tmp.shape[1]*sources_tmp.shape[2]) sources_tmp = sources_tmp.reshape(short_shape) # Scale to allow for lower precision scaler = 1/sources_tmp.max() sources_tmp *= scaler # Perform Matmul result = np.matmul( leadfield.astype(np.float32), sources_tmp.astype(np.float32)) # Reshape result result = result.reshape(result.shape[0], n_samples, n_timepoints) # swap axes to correct order result = np.swapaxes(result,0,1) # Rescale result /= scaler return result def add_noise(self, x, snr, beta=0): """ Add noise of given SNR to signal x. Parameters: ----------- x : numpy.ndarray, 3-dimensional numpy array of dims (trials, channels, timepoints) Return: ------- """ # This looks inconvenient but we need to make sure that there is no empty dimension for the powerlaw noise function. x_shape = (x.shape[0], x.shape[1], np.clip(x.shape[2], a_min=2, a_max=np.inf).astype(int)) noise = cn.powerlaw_psd_gaussian(beta, x_shape) # In case we added another entry in the 2nd dimension we have to remove it here again. if x_shape[2] != x.shape[2]: noise=noise[:, :, :1] noise_gfp = np.std(noise, axis=1) rms_noise = np.mean(noise_gfp) # rms(noise) x_gfp = np.std(x, axis=1) rms_x = np.mean(np.max(np.abs(x_gfp), axis=1)) # x.max() # rms_noise = rms(noise-np.mean(noise)) noise_scaler = rms_x / (rms_noise*snr) out = x + noise*noise_scaler return out def check_settings(self): ''' Check if settings are complete and insert missing entries if there are any. ''' # Check for wrong keys: for key in self.settings.keys(): if not key in DEFAULT_SETTINGS.keys(): msg = f'key {key} is not part of allowed settings. See DEFAULT_SETTINGS for reference: {DEFAULT_SETTINGS}' raise AttributeError(msg) # Check for missing keys and replace them from the DEFAULT_SETTINGS for key in DEFAULT_SETTINGS.keys(): # Check if setting exists and is not None if not (key in self.settings.keys() and self.settings[key] is not None): self.settings[key] = DEFAULT_SETTINGS[key] if self.settings['duration_of_trial'] == 0: self.temporal = False else: self.temporal = True @staticmethod def get_pulse(pulse_len): ''' Returns a pulse of given length. A pulse is defined as half a revolution of a sine. Parameters ---------- x : int the number of data points ''' pulse_len = int(pulse_len) freq = (1/pulse_len) / 2 time = np.arange(pulse_len) signal = np.sin(2*np.pi*freq*time) return signal @staticmethod def get_from_range(val, dtype=int): ''' If list of two integers/floats is given this method outputs a value in between the two values. Otherwise, it returns the value. Parameters ---------- val : list/tuple/int/float Return ------ out : int/float ''' if dtype==int: rng = random.randrange elif dtype==float: rng = random.uniform else: msg = f'dtype must be int or float, got {type(dtype)} instead' raise AttributeError(msg) if isinstance(val, (list, tuple, np.ndarray)): out = rng(*val) elif isinstance(val, (int, float)): out = val return out def save(self, file_name): ''' Store the simulation object. Parameters ---------- file_name : str Filename or full path to store the object to. Example ------- sim = Simulation().simulate() sim.save('C/Users/User/Desktop/simulation.pkl') ''' with open(file_name, 'wb') as f: pkl.dump(self, f) def to_nontemporal(self): ''' Converts the internal data representation from temporal to non-temporal. Specifically, this changes the shape of sources from a list of mne.sourceEstimate to a single mne.sourceEstimate in which the time dimension holds a concatenation of timepoints and samples. The eeg data is reshaped from (samples, channels, time points) to (samples*time points, channels, 1). Parameters ---------- Return ------ self : esinet.Simulation Method returns itself for convenience ''' if not self.temporal: print('This Simulation() instance is already non-temporal') return self self.temporal = False self.settings['duration_of_trial'] = 0 eeg_data_lstm = self.eeg_data.get_data() # Reshape EEG data eeg_data_single = np.expand_dims(np.vstack(np.swapaxes(eeg_data_lstm, 1,2)), axis=-1) # Pack into mne.EpochsArray object epochs_single = mne.EpochsArray(eeg_data_single, self.eeg_data.info, tmin=self.eeg_data.tmin, verbose=0) # Store the newly shaped data self.eeg_data = epochs_single # Reshape Source data source_data = np.vstack(np.swapaxes(np.stack( [source.data for source in self.source_data], axis=0), 1,2)).T # Pack into mne.SourceEstimate object source_single = deepcopy(self.source_data[0]) source_single.data = source_data self.source_data = source_single return self
[ "pickle.dump", "numpy.sum", "numpy.abs", "tqdm.notebook.tqdm", "numpy.clip", "numpy.mean", "numpy.arange", "numpy.sin", "numpy.std", "numpy.max", "numpy.swapaxes", "numpy.random.shuffle", "numpy.stack", "copy.deepcopy", "colorednoise.powerlaw_psd_gaussian", "numpy.zeros", "numpy.expa...
[((2411, 2424), 'copy.deepcopy', 'deepcopy', (['fwd'], {}), '(fwd)\n', (2419, 2424), False, 'from copy import deepcopy\n'), ((4332, 4349), 'tqdm.notebook.tqdm', 'tqdm', (['source_data'], {}), '(source_data)\n', (4336, 4349), False, 'from tqdm.notebook import tqdm\n'), ((8199, 8243), 'numpy.zeros', 'np.zeros', (['(self.pos.shape[0], signal_length)'], {}), '((self.pos.shape[0], signal_length))\n', (8207, 8243), True, 'import numpy as np\n'), ((13256, 13289), 'numpy.mean', 'np.mean', (['eeg_trials_noisy'], {'axis': '(1)'}), '(eeg_trials_noisy, axis=1)\n', (13263, 13289), True, 'import numpy as np\n'), ((15396, 15469), 'numpy.zeros', 'np.zeros', (['(eeg_sample.shape[0], eeg_sample.shape[1], eeg_sample.shape[2])'], {}), '((eeg_sample.shape[0], eeg_sample.shape[1], eeg_sample.shape[2]))\n', (15404, 15469), True, 'import numpy as np\n'), ((16343, 16386), 'numpy.zeros', 'np.zeros', (['(n_samples, n_elec, n_timepoints)'], {}), '((n_samples, n_elec, n_timepoints))\n', (16351, 16386), True, 'import numpy as np\n'), ((16463, 16489), 'numpy.swapaxes', 'np.swapaxes', (['sources', '(0)', '(1)'], {}), '(sources, 0, 1)\n', (16474, 16489), True, 'import numpy as np\n'), ((17079, 17104), 'numpy.swapaxes', 'np.swapaxes', (['result', '(0)', '(1)'], {}), '(result, 0, 1)\n', (17090, 17104), True, 'import numpy as np\n'), ((17685, 17724), 'colorednoise.powerlaw_psd_gaussian', 'cn.powerlaw_psd_gaussian', (['beta', 'x_shape'], {}), '(beta, x_shape)\n', (17709, 17724), True, 'import colorednoise as cn\n'), ((17925, 17946), 'numpy.std', 'np.std', (['noise'], {'axis': '(1)'}), '(noise, axis=1)\n', (17931, 17946), True, 'import numpy as np\n'), ((17967, 17985), 'numpy.mean', 'np.mean', (['noise_gfp'], {}), '(noise_gfp)\n', (17974, 17985), True, 'import numpy as np\n'), ((18025, 18042), 'numpy.std', 'np.std', (['x'], {'axis': '(1)'}), '(x, axis=1)\n', (18031, 18042), True, 'import numpy as np\n'), ((19540, 19560), 'numpy.arange', 'np.arange', (['pulse_len'], {}), '(pulse_len)\n', (19549, 19560), True, 'import numpy as np\n'), ((19579, 19610), 'numpy.sin', 'np.sin', (['(2 * np.pi * freq * time)'], {}), '(2 * np.pi * freq * time)\n', (19585, 19610), True, 'import numpy as np\n'), ((21897, 21990), 'mne.EpochsArray', 'mne.EpochsArray', (['eeg_data_single', 'self.eeg_data.info'], {'tmin': 'self.eeg_data.tmin', 'verbose': '(0)'}), '(eeg_data_single, self.eeg_data.info, tmin=self.eeg_data.\n tmin, verbose=0)\n', (21912, 21990), False, 'import mne\n'), ((22313, 22342), 'copy.deepcopy', 'deepcopy', (['self.source_data[0]'], {}), '(self.source_data[0])\n', (22321, 22342), False, 'from copy import deepcopy\n'), ((2498, 2512), 'copy.deepcopy', 'deepcopy', (['info'], {}), '(info)\n', (2506, 2512), False, 'from copy import deepcopy\n'), ((4369, 4387), 'copy.deepcopy', 'deepcopy', (['template'], {}), '(template)\n', (4377, 4387), False, 'from copy import deepcopy\n'), ((6512, 6537), 'numpy.random.shuffle', 'np.random.shuffle', (['shapes'], {}), '(shapes)\n', (6529, 6537), True, 'import numpy as np\n'), ((7066, 7094), 'numpy.arange', 'np.arange', (['self.pos.shape[0]'], {}), '(self.pos.shape[0])\n', (7075, 7094), True, 'import numpy as np\n'), ((11242, 11304), 'numpy.stack', 'np.stack', (['[source.data for source in self.source_data]'], {'axis': '(0)'}), '([source.data for source in self.source_data], axis=0)\n', (11250, 11304), True, 'import numpy as np\n'), ((11516, 11547), 'numpy.expand_dims', 'np.expand_dims', (['sources'], {'axis': '(2)'}), '(sources, axis=2)\n', (11530, 11547), True, 'import numpy as np\n'), ((12814, 12854), 'numpy.expand_dims', 'np.expand_dims', (['eeg_trials_noisy'], {'axis': '(1)'}), '(eeg_trials_noisy, axis=1)\n', (12828, 12854), True, 'import numpy as np\n'), ((12941, 12982), 'numpy.expand_dims', 'np.expand_dims', (['eeg_trials_noisy'], {'axis': '(-1)'}), '(eeg_trials_noisy, axis=-1)\n', (12955, 12982), True, 'import numpy as np\n'), ((13075, 13110), 'numpy.swapaxes', 'np.swapaxes', (['eeg_trials_noisy', '(1)', '(2)'], {}), '(eeg_trials_noisy, 1, 2)\n', (13086, 13110), True, 'import numpy as np\n'), ((14348, 14377), 'numpy.expand_dims', 'np.expand_dims', (['eeg_sample', '(0)'], {}), '(eeg_sample, 0)\n', (14362, 14377), True, 'import numpy as np\n'), ((14435, 14463), 'numpy.sqrt', 'np.sqrt', (['n_simulation_trials'], {}), '(n_simulation_trials)\n', (14442, 14463), True, 'import numpy as np\n'), ((20792, 20809), 'pickle.dump', 'pkl.dump', (['self', 'f'], {}), '(self, f)\n', (20800, 20809), True, 'import pickle as pkl\n'), ((8522, 8579), 'numpy.sum', 'np.sum', (['((self.pos - self.pos[src_center, :]) ** 2)'], {'axis': '(1)'}), '((self.pos - self.pos[src_center, :]) ** 2, axis=1)\n', (8528, 8579), True, 'import numpy as np\n'), ((8595, 8627), 'numpy.where', 'np.where', (['(dists < extents[i] / 2)'], {}), '(dists < extents[i] / 2)\n', (8603, 8627), True, 'import numpy as np\n'), ((15578, 15614), 'numpy.where', 'np.where', (['(coil_type_assignments == i)'], {}), '(coil_type_assignments == i)\n', (15586, 15614), True, 'import numpy as np\n'), ((18074, 18087), 'numpy.abs', 'np.abs', (['x_gfp'], {}), '(x_gfp)\n', (18080, 18087), True, 'import numpy as np\n'), ((21787, 21819), 'numpy.swapaxes', 'np.swapaxes', (['eeg_data_lstm', '(1)', '(2)'], {}), '(eeg_data_lstm, 1, 2)\n', (21798, 21819), True, 'import numpy as np\n'), ((3321, 3365), 'joblib.Parallel', 'Parallel', ([], {'n_jobs': 'self.n_jobs', 'backend': '"""loky"""'}), "(n_jobs=self.n_jobs, backend='loky')\n", (3329, 3365), False, 'from joblib import Parallel, delayed\n'), ((7814, 7828), 'numpy.abs', 'np.abs', (['signal'], {}), '(signal)\n', (7820, 7828), True, 'import numpy as np\n'), ((8078, 8091), 'numpy.array', 'np.array', (['[1]'], {}), '([1])\n', (8086, 8091), True, 'import numpy as np\n'), ((12083, 12127), 'joblib.Parallel', 'Parallel', ([], {'n_jobs': 'self.n_jobs', 'backend': '"""loky"""'}), "(n_jobs=self.n_jobs, backend='loky')\n", (12091, 12127), False, 'from joblib import Parallel, delayed\n'), ((17613, 17655), 'numpy.clip', 'np.clip', (['x.shape[2]'], {'a_min': '(2)', 'a_max': 'np.inf'}), '(x.shape[2], a_min=2, a_max=np.inf)\n', (17620, 17655), True, 'import numpy as np\n'), ((22158, 22220), 'numpy.stack', 'np.stack', (['[source.data for source in self.source_data]'], {'axis': '(0)'}), '([source.data for source in self.source_data], axis=0)\n', (22166, 22220), True, 'import numpy as np\n'), ((8693, 8709), 'numpy.max', 'np.max', (['dists[d]'], {}), '(dists[d])\n', (8699, 8709), True, 'import numpy as np\n'), ((15276, 15313), 'numpy.where', 'np.where', (['(coil_types_set == coil_type)'], {}), '(coil_types_set == coil_type)\n', (15284, 15313), True, 'import numpy as np\n'), ((3383, 3412), 'joblib.delayed', 'delayed', (['self.simulate_source'], {}), '(self.simulate_source)\n', (3390, 3412), False, 'from joblib import Parallel, delayed\n'), ((9120, 9152), 'numpy.expand_dims', 'np.expand_dims', (['activity'], {'axis': '(0)'}), '(activity, axis=0)\n', (9134, 9152), True, 'import numpy as np\n'), ((9218, 9250), 'numpy.expand_dims', 'np.expand_dims', (['activity'], {'axis': '(1)'}), '(activity, axis=1)\n', (9232, 9250), True, 'import numpy as np\n'), ((12145, 12176), 'joblib.delayed', 'delayed', (['self.create_eeg_helper'], {}), '(self.create_eeg_helper)\n', (12152, 12176), False, 'from joblib import Parallel, delayed\n')]
# -*- coding: utf-8 -*- import numpy as np NUMPY_COMPLEX128_MAX = np.finfo(np.complex128).max NUMPY_LOG_COMPLEX128_MAX = np.log(NUMPY_COMPLEX128_MAX) class HestonModel: def __init__(self, forward, vol, kappa, theta, sigma, rho, rate): self.forward = forward self.vol = vol self.kappa = kappa self.theta = theta self.sigma = sigma self.rho = rho self.rate = rate def __str__(self): out_str = f"forward: {self.forward}\n\r" +\ f"vol: {self.vol}\n\r" +\ f"kappa: {self.kappa}\n\r" +\ f"theta: {self.theta}\n\r" +\ f"sigma: {self.sigma}\n\r" +\ f"rho: {self.rho}\n\r" + \ f"rate: {self.rate}\n\r" return out_str def cf(self, z, tau) -> complex: beta = self.kappa - 1j * self.sigma * self.rho * z sigma_sq = self.sigma * self.sigma D = np.sqrt(beta * beta + sigma_sq * z * (z + 1j)) if beta.real * D.real + beta.imag * D.imag > 0: r = - sigma_sq * z * (z + 1j) / (beta + D) else: r = beta - D if D != 0: y = np.expm1(-D * tau) / (2 * D) else: y = -tau / 2 A = self.kappa * self.theta / sigma_sq * \ (r * tau - 2 * np.log1p(- r * y)) B = z * (z + 1j) * y / (1 - r * y) exponent = A + B * self.vol if exponent > NUMPY_LOG_COMPLEX128_MAX: raise OverflowError("too large exponent in characteristic function") return np.exp(exponent) def log_cf_real(self, alpha, tau) -> float: # Evaluation of ln HestomModel.cf(-1j * (1 + alpha)) beta = self.kappa - self.rho * self.sigma * (1 + alpha) Dsq = beta**2 - self.sigma**2 * (1 + alpha) * alpha if Dsq > 0: D = np.sqrt(Dsq) coshdt = np.cosh(D * tau / 2) sinhdt = np.sinh(D * tau / 2) / D nume = coshdt + beta * sinhdt else: # D = 1j * x x = np.sqrt(-Dsq) coshdt = np.cos(x * tau / 2) sinhdt = np.sin(x * tau / 2) / x nume = coshdt + beta * sinhdt A = self.kappa * self.theta / self.sigma**2 *\ (beta * tau - np.log(nume**2)) B = alpha * (1 + alpha) * sinhdt / nume return A + B * self.vol class BlackScholesModel(): def __init__(self, forward, vol, rate): self.forward = forward self.vol = vol self.rate = rate def cf(self, z, tau): return np.exp(-0.5 * self.vol * tau * z * (z + 1j))
[ "numpy.log", "numpy.finfo", "numpy.expm1", "numpy.sin", "numpy.exp", "numpy.cos", "numpy.cosh", "numpy.sinh", "numpy.log1p", "numpy.sqrt" ]
[((122, 150), 'numpy.log', 'np.log', (['NUMPY_COMPLEX128_MAX'], {}), '(NUMPY_COMPLEX128_MAX)\n', (128, 150), True, 'import numpy as np\n'), ((67, 90), 'numpy.finfo', 'np.finfo', (['np.complex128'], {}), '(np.complex128)\n', (75, 90), True, 'import numpy as np\n'), ((952, 1000), 'numpy.sqrt', 'np.sqrt', (['(beta * beta + sigma_sq * z * (z + 1.0j))'], {}), '(beta * beta + sigma_sq * z * (z + 1.0j))\n', (959, 1000), True, 'import numpy as np\n'), ((1579, 1595), 'numpy.exp', 'np.exp', (['exponent'], {}), '(exponent)\n', (1585, 1595), True, 'import numpy as np\n'), ((2601, 2647), 'numpy.exp', 'np.exp', (['(-0.5 * self.vol * tau * z * (z + 1.0j))'], {}), '(-0.5 * self.vol * tau * z * (z + 1.0j))\n', (2607, 2647), True, 'import numpy as np\n'), ((1875, 1887), 'numpy.sqrt', 'np.sqrt', (['Dsq'], {}), '(Dsq)\n', (1882, 1887), True, 'import numpy as np\n'), ((1909, 1929), 'numpy.cosh', 'np.cosh', (['(D * tau / 2)'], {}), '(D * tau / 2)\n', (1916, 1929), True, 'import numpy as np\n'), ((2086, 2099), 'numpy.sqrt', 'np.sqrt', (['(-Dsq)'], {}), '(-Dsq)\n', (2093, 2099), True, 'import numpy as np\n'), ((2121, 2140), 'numpy.cos', 'np.cos', (['(x * tau / 2)'], {}), '(x * tau / 2)\n', (2127, 2140), True, 'import numpy as np\n'), ((1186, 1204), 'numpy.expm1', 'np.expm1', (['(-D * tau)'], {}), '(-D * tau)\n', (1194, 1204), True, 'import numpy as np\n'), ((1951, 1971), 'numpy.sinh', 'np.sinh', (['(D * tau / 2)'], {}), '(D * tau / 2)\n', (1958, 1971), True, 'import numpy as np\n'), ((2162, 2181), 'numpy.sin', 'np.sin', (['(x * tau / 2)'], {}), '(x * tau / 2)\n', (2168, 2181), True, 'import numpy as np\n'), ((2310, 2327), 'numpy.log', 'np.log', (['(nume ** 2)'], {}), '(nume ** 2)\n', (2316, 2327), True, 'import numpy as np\n'), ((1333, 1349), 'numpy.log1p', 'np.log1p', (['(-r * y)'], {}), '(-r * y)\n', (1341, 1349), True, 'import numpy as np\n')]
import numpy as np import unittest from laika.gps_time import GPSTime from laika import AstroDog gps_times_list = [[1950, 415621.0], [1895, 455457.0], [1885, 443787.0]] svIds = ['G01', 'G31', 'R08'] gps_times = [GPSTime(*gps_time_list) for gps_time_list in gps_times_list] class TestAstroDog(unittest.TestCase): ''' def test_nav_vs_orbit_now(self): dog_orbit = AstroDog(pull_orbit=True) dog_nav = AstroDog(pull_orbit=False) gps_time = GPSTime.from_datetime(datetime.utcnow()) - SECS_IN_DAY*2 for svId in svIds: sat_info_nav = dog_nav.get_sat_info(svId, gps_time) sat_info_orbit = dog_orbit.get_sat_info(svId, gps_time) np.testing.assert_allclose(sat_info_nav[0], sat_info_orbit[0], rtol=0, atol=5) np.testing.assert_allclose(sat_info_nav[1], sat_info_orbit[1], rtol=0, atol=.1) np.testing.assert_allclose(sat_info_nav[2], sat_info_orbit[2], rtol=0, atol=1e-7) np.testing.assert_allclose(sat_info_nav[3], sat_info_orbit[3], rtol=0, atol=1e-11) ''' def test_nav_vs_orbit__old(self): dog_orbit = AstroDog(pull_orbit=True) dog_nav = AstroDog(pull_orbit=False) for gps_time in gps_times: for svId in svIds: sat_info_nav = dog_nav.get_sat_info(svId, gps_time) sat_info_orbit = dog_orbit.get_sat_info(svId, gps_time) np.testing.assert_allclose(sat_info_nav[0], sat_info_orbit[0], rtol=0, atol=5) np.testing.assert_allclose(sat_info_nav[1], sat_info_orbit[1], rtol=0, atol=.1) np.testing.assert_allclose(sat_info_nav[2], sat_info_orbit[2], rtol=0, atol=1e-7) np.testing.assert_allclose(sat_info_nav[3], sat_info_orbit[3], rtol=0, atol=1e-11) if __name__ == "__main__": unittest.main()
[ "unittest.main", "numpy.testing.assert_allclose", "laika.AstroDog", "laika.gps_time.GPSTime" ]
[((223, 246), 'laika.gps_time.GPSTime', 'GPSTime', (['*gps_time_list'], {}), '(*gps_time_list)\n', (230, 246), False, 'from laika.gps_time import GPSTime\n'), ((1704, 1719), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1717, 1719), False, 'import unittest\n'), ((1070, 1095), 'laika.AstroDog', 'AstroDog', ([], {'pull_orbit': '(True)'}), '(pull_orbit=True)\n', (1078, 1095), False, 'from laika import AstroDog\n'), ((1110, 1136), 'laika.AstroDog', 'AstroDog', ([], {'pull_orbit': '(False)'}), '(pull_orbit=False)\n', (1118, 1136), False, 'from laika import AstroDog\n'), ((1325, 1403), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['sat_info_nav[0]', 'sat_info_orbit[0]'], {'rtol': '(0)', 'atol': '(5)'}), '(sat_info_nav[0], sat_info_orbit[0], rtol=0, atol=5)\n', (1351, 1403), True, 'import numpy as np\n'), ((1412, 1497), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['sat_info_nav[1]', 'sat_info_orbit[1]'], {'rtol': '(0)', 'atol': '(0.1)'}), '(sat_info_nav[1], sat_info_orbit[1], rtol=0, atol=0.1\n )\n', (1438, 1497), True, 'import numpy as np\n'), ((1500, 1587), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['sat_info_nav[2]', 'sat_info_orbit[2]'], {'rtol': '(0)', 'atol': '(1e-07)'}), '(sat_info_nav[2], sat_info_orbit[2], rtol=0, atol\n =1e-07)\n', (1526, 1587), True, 'import numpy as np\n'), ((1590, 1677), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['sat_info_nav[3]', 'sat_info_orbit[3]'], {'rtol': '(0)', 'atol': '(1e-11)'}), '(sat_info_nav[3], sat_info_orbit[3], rtol=0, atol\n =1e-11)\n', (1616, 1677), True, 'import numpy as np\n')]
import numpy as np a = np.array([1, 2, 3, 4, 5]) np.sum(a ** 2)
[ "numpy.array", "numpy.sum" ]
[((23, 48), 'numpy.array', 'np.array', (['[1, 2, 3, 4, 5]'], {}), '([1, 2, 3, 4, 5])\n', (31, 48), True, 'import numpy as np\n'), ((49, 63), 'numpy.sum', 'np.sum', (['(a ** 2)'], {}), '(a ** 2)\n', (55, 63), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- """ Created on Thu Dec 5 12:43:51 2019 @author: Blackr """ """Cyclic Voltammetry (CV) technique class. The CV technique returns data on fields (in order): * time (float) * Ec (float) * I (float) * Ewe (float) * cycle (int) """ ''' E_we ^ | E_1 | /\ | / \ | / \ E_f | E_i/ \ / | \ / | \/ | E_2 +----------------------> t Args: vs_initial (list): List (or tuple) of 5 booleans indicating whether the current step is vs. the initial one voltage_step (list): List (or tuple) of 5 floats (Ei, E1, E2, Ei, Ef) indicating the voltage steps (V) scan_rate (list): List (or tuple) of 5 floats indicating the scan rates (mV/s) record_every_dE (float): Record every dE (V) average_over_dE (bool): Whether averaging should be performed over dE N_cycles (int): The number of cycles begin_measuring_I (float): Begin step accumulation, 1 is 100% end_measuring_I (float): Begin step accumulation, 1 is 100% I_Range (str): A string describing the I range, see the :data:`I_RANGES` module variable for possible values E_range (str): A string describing the E range to use, see the :data:`E_RANGES` module variable for possible values Bandwidth (str): A string describing the bandwidth setting, see the :data:`BANDWIDTHS` module variable for possible values''' """CV example""" '''A program to run a typical CV experiment and export the data to a .csv file''' '''Currently have 32-bit vs. 64-bit interpreter problems with pandas library, so dump to .csv and use other to put into pandas database''' import time import numpy from bio_logic import SP150, CV def run_cv(): """Test the CV technique""" ip_address = 'USB0' # REPLACE THIS WITH A VALID IP # Instantiate the instrument and connect to it sp150 = SP150(ip_address, 'C:\\EC-Lab Development Package\\EC-Lab Development Package\\EClib.dll') sp150.connect() sp150.load_firmware([1]) # Instantiate the technique. Make sure to give values for all the # arguments where the default values does not fit your purpose. The # default values can be viewed in the API documentation for the # technique. cv = CV(vs_initial=(False,) * 5, voltage_step=(2, 0.5, -0.7, 0.0, 0.0), scan_rate=(10.0,) * 5, record_every_dE=0.01, N_cycles=3) # Load the technique onto channel 0 of the potentiostat and start it sp150.load_technique(0, cv) sp150.start_channel(0) Time = numpy.array([]) Ewe = numpy.array([]) Ec = numpy.array([]) I = numpy.array([]) cycle = numpy.array([]) while True: # Get the currently available data on channel 0 (only what has # been gathered since last get_data) data_out = sp150.get_data(0) # If there is none, assume the technique has finished if data_out is None: break # The data is available in lists as attributes on the data # object. The available data fields are listed in the API # documentation for the technique. # print("Time:", data_out.time) # print("Ewe:", data_out.Ewe) # If numpy is installed, the data can also be retrieved as # numpy arrays # printing the values to follow for testing print('Time:', data_out.time_numpy) print('Ewe:', data_out.Ewe_numpy) print('Ec', data_out.Ec_numpy) print('I', data_out.I_numpy) print('cycle', data_out.cycle_numpy) # Updating the variables with the appended data per data call Ewe = numpy.append(Ewe, data_out.Ewe_numpy_numpy) Time = numpy.append(Time, data_out.time_numpy) Ec = numpy.append(Ec, data_out.Ec_numpy) I = numpy.append(I, data_out.I_numpy) cycle = numpy.append(cycle, data_out.cycle_numpy) # Sleep # dataframe of each variable df = (Time, Ewe, Ec, I, cycle) #Due to compatibility issues (in my head, this can be fixed), writing data to a .csv for importing into pandas # Note the order of header and the df as indicated numpy.savetxt("testCV.csv", numpy.transpose(df), delimiter=",", header = 'Time,Ewe,Ec,I,cycle', comments = '') sp150.stop_channel(0) sp150.disconnect() if __name__ == '__main__': run_cv()
[ "bio_logic.CV", "numpy.transpose", "numpy.append", "numpy.array", "bio_logic.SP150" ]
[((2207, 2301), 'bio_logic.SP150', 'SP150', (['ip_address', '"""C:\\\\EC-Lab Development Package\\\\EC-Lab Development Package\\\\EClib.dll"""'], {}), "(ip_address,\n 'C:\\\\EC-Lab Development Package\\\\EC-Lab Development Package\\\\EClib.dll')\n", (2212, 2301), False, 'from bio_logic import SP150, CV\n'), ((2590, 2717), 'bio_logic.CV', 'CV', ([], {'vs_initial': '((False,) * 5)', 'voltage_step': '(2, 0.5, -0.7, 0.0, 0.0)', 'scan_rate': '((10.0,) * 5)', 'record_every_dE': '(0.01)', 'N_cycles': '(3)'}), '(vs_initial=(False,) * 5, voltage_step=(2, 0.5, -0.7, 0.0, 0.0),\n scan_rate=(10.0,) * 5, record_every_dE=0.01, N_cycles=3)\n', (2592, 2717), False, 'from bio_logic import SP150, CV\n'), ((2921, 2936), 'numpy.array', 'numpy.array', (['[]'], {}), '([])\n', (2932, 2936), False, 'import numpy\n'), ((2948, 2963), 'numpy.array', 'numpy.array', (['[]'], {}), '([])\n', (2959, 2963), False, 'import numpy\n'), ((2974, 2989), 'numpy.array', 'numpy.array', (['[]'], {}), '([])\n', (2985, 2989), False, 'import numpy\n'), ((2999, 3014), 'numpy.array', 'numpy.array', (['[]'], {}), '([])\n', (3010, 3014), False, 'import numpy\n'), ((3028, 3043), 'numpy.array', 'numpy.array', (['[]'], {}), '([])\n', (3039, 3043), False, 'import numpy\n'), ((4037, 4080), 'numpy.append', 'numpy.append', (['Ewe', 'data_out.Ewe_numpy_numpy'], {}), '(Ewe, data_out.Ewe_numpy_numpy)\n', (4049, 4080), False, 'import numpy\n'), ((4097, 4136), 'numpy.append', 'numpy.append', (['Time', 'data_out.time_numpy'], {}), '(Time, data_out.time_numpy)\n', (4109, 4136), False, 'import numpy\n'), ((4151, 4186), 'numpy.append', 'numpy.append', (['Ec', 'data_out.Ec_numpy'], {}), '(Ec, data_out.Ec_numpy)\n', (4163, 4186), False, 'import numpy\n'), ((4200, 4233), 'numpy.append', 'numpy.append', (['I', 'data_out.I_numpy'], {}), '(I, data_out.I_numpy)\n', (4212, 4233), False, 'import numpy\n'), ((4251, 4292), 'numpy.append', 'numpy.append', (['cycle', 'data_out.cycle_numpy'], {}), '(cycle, data_out.cycle_numpy)\n', (4263, 4292), False, 'import numpy\n'), ((4587, 4606), 'numpy.transpose', 'numpy.transpose', (['df'], {}), '(df)\n', (4602, 4606), False, 'import numpy\n')]
""" Matplotlib volumetric benchmarking plotting routines. """ #*************************************************************************************************** # Copyright 2015, 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS). # Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government retains certain rights # in this software. # 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 or in the LICENSE file in the root pyGSTi directory. #*************************************************************************************************** import numpy as _np try: import matplotlib.pyplot as _plt from matplotlib.colors import ListedColormap as _ListedColormap from matplotlib import cm as _cm import seaborn as _sns _sns.set_style('white') _sns.set_style('ticks') # Utility color maps. blues = _sns.color_palette(_sns.color_palette("Blues", 200)).as_hex() blues[0] = '#ffffff' blues = _ListedColormap(blues) reds = _sns.color_palette(_sns.color_palette("Reds", 200)).as_hex() reds[0] = '#ffffff' reds = _ListedColormap(reds) greens = _sns.color_palette(_sns.color_palette("Greens", 200)).as_hex() greens[0] = '#ffffff' greens = _ListedColormap(greens) binary_blue = _sns.color_palette(_sns.color_palette("Blues", 200)).as_hex() binary_blue[0] = '#ffffff' binary_blue = _ListedColormap([binary_blue[0], binary_blue[50]]) spectral = _cm.get_cmap('Spectral') # The default color map. my_cmap = blues except ImportError: _plt = None _sns = None my_cmap = None def empty_volumetric_plot(figsize=None, y_values=None, x_values=None, title=None, xlabel='Depth', ylabel='Width'): """ Creates an empty volumetric plot with just the axes set. Parameters ---------- figsize : tuple or None, optional The figure size. y_values : list or None, optional The y-axis values, typically corresponding to circuit widths. x_values : list or None, optional The x-axis values, typically corresponding to circuit depths. title : string or None, optional Plot title xlabel : string, optional x-axis label ylabel : string, optional y-axis label. Return ------ fig, ax : matplolib fig and ax. """ if _plt is None or _sns is None: raise ValueError(("While not a core requirement of pyGSTi, Matplotlib and Seaborn are " "required to generate VB plots. It looks like you " "don't have them installed on your system (it failed to import).")) fig, ax = _plt.subplots(figsize=figsize) ax.set_aspect('equal') _plt.xlabel(xlabel, fontsize=20) _plt.ylabel(ylabel, fontsize=20) _plt.title(title, fontsize=24, y=1.02) _plt.xlim(-1, len(x_values)) _plt.ylim(-1, len(y_values)) depth_labels = [str(d)[0:len(str(d)) - ((len(str(d)) - 1) // 3) * 3] + ['', 'k', 'M', 'G'][(len(str(d)) - 1) // 3] for d in x_values] _plt.xticks(range(len(x_values)), depth_labels, rotation=-60, fontsize=14) _plt.yticks(range(len(y_values)), y_values, fontsize=14) _sns.despine() return fig, ax def _get_xy(data, y_values=None, x_values=None): # Helper function for setting the x and y axes of VB plots. if x_values is None: x_values = list(set([shape[0] for shape in data.keys()])) x_values.sort() if y_values is None: y_values = list(set([shape[1] for shape in data.keys()])) y_values.sort() return y_values, x_values def volumetric_plot(data, y_values=None, x_values=None, title=None, fig=None, ax=None, cmap=my_cmap, color=None, flagQV=False, qv_threshold=None, figsize=(10, 10), scale=1., centerscale=1., linescale=1., pass_threshold=0, show_threshold=0): """ Creates a volumetric benchmarking plot. """ y_values, x_values = _get_xy(data, y_values, x_values) if fig is None: fig, ax = empty_volumetric_plot(figsize=figsize, y_values=y_values, x_values=x_values, title=title) if qv_threshold is None: qv_threshold = pass_threshold if color is not None: cmap = None point_color = color for indw, w in enumerate(y_values): for indd, d in enumerate(x_values): edgecolor = 'k' linewidth = 1 * linescale datapoint = data.get((d, w), None) if (datapoint is not None) and (not _np.isnan(datapoint)): if w == d and flagQV: if datapoint > qv_threshold: edgecolor = 'r' linewidth = 5 * scale * linescale if datapoint >= show_threshold: if datapoint < pass_threshold: datapoint = 0 if color is None: point_color = [datapoint] ax.scatter([indd], [indw], marker="s", s=280 * scale - 30 * linewidth, c=point_color, cmap=cmap, vmin=0, vmax=1, edgecolor=edgecolor, linewidth=linewidth) return fig, ax def volumetric_boundary_plot(data, y_values=None, x_values=None, boundary=None, threshold=.5, missing_data_action='continue', monotonic=True, color='k', linewidth=4, linestyle='-', dashing=None, fig=None, ax=None, figsize=None, title=None, label=None): """ Creates a volumetric benchmarking boundary plot, that displays boundary at which the given data drops below the specified threshold """ y_values, x_values = _get_xy(data, y_values, x_values) if fig is None: fig, ax = empty_volumetric_plot(figsize=figsize, y_values=y_values, x_values=x_values, title=title) if boundary is not None: boundaries = _np.array([-1 if boundary[d] == 0 else y_values.index(boundary[d]) for d in x_values]) # x-values for a jagged line that outlines the boxes (one pair for each box) xvals = [y for x in range(len(x_values)) for y in [x - .5, x + .5]] # y-values for a jagged line that outlines the boxes (one pair for each box) yvals = [y + .5 for boundary in boundaries for y in [boundary, boundary]] else: # For each depth, find the widest circuit that achieves the threshold performance (return -1 if none) if missing_data_action == 'none': boundaries = _np.array([_np.max([-1] + [y_values.index(w) for w in y_values if (d, w) in data.keys() and data[d, w] >= threshold]) for d in x_values]) # x-values for a jagged line that outlines the boxes (one pair for each box) xvals = [y for x in range(len(x_values)) for y in [x - .5, x + .5]] # y-values for a jagged line that outlines the boxes (one pair for each box) yvals = [y + .5 for boundary in boundaries for y in [boundary, boundary]] elif missing_data_action == 'continue' or missing_data_action == 'hedge': boundaries = [] d = x_values[0] boundary_at_d = _np.max([-1] + [y_values.index(w) for w in y_values if (d, w) in data.keys() and data[d, w] >= threshold]) boundaries.append(boundary_at_d) previous_boundary = boundary_at_d hedged_x_values = [] for i, d in enumerate(x_values[1:]): max_width_at_depth = _np.max([-1] + [w for w in y_values if (d, w) in data.keys()]) if max_width_at_depth < previous_boundary: boundary_at_d = previous_boundary hedged_x_values.append(d) else: boundary_at_d = _np.max([-1] + [y_values.index(w) for w in y_values if (d, w) in data.keys() and data[d, w] >= threshold]) boundaries.append(boundary_at_d) previous_boundary = boundary_at_d if missing_data_action == 'continue': # x-values for a jagged line that outlines the boxes (one pair for each box) xvals = [y for x in range(len(x_values)) for y in [x - .5, x + .5]] # y-values for a jagged line that outlines the boxes (one pair for each box) yvals = [y + .5 for boundary in boundaries for y in [boundary, boundary]] elif missing_data_action == 'hedge': # x-values for a jagged line that outlines the boxes (one pair for each box) xvals = [] yvals = [] last_xval = -0.5 for x, boundary in zip(range(len(x_values)), boundaries): d = x_values[x] if d in hedged_x_values: # Only hedge when there's actually some data at larger x_values. if not all([d in hedged_x_values for d in x_values[x:]]): xvals += [last_xval, x] yvals += [boundary + .5, boundary + .5] else: xvals += [last_xval, x + .5] yvals += [boundary + .5, boundary + .5] last_xval = xvals[-1] if monotonic: monotonic_yvals = [yvals[0]] for y in yvals[1:]: if y > monotonic_yvals[-1]: monotonic_yvals.append(monotonic_yvals[-1]) else: monotonic_yvals.append(y) yvals = monotonic_yvals line, = ax.plot(xvals, yvals, color, linewidth=linewidth, label=label, linestyle=linestyle) if dashing is not None: line.set_dashes(dashing) return fig, ax def capability_region_plot(vbdataframe, metric='polarization', threshold=1 / _np.e, significance=0.05, figsize=(10, 10), scale=1., title=None, colors=None): """ Creates a capability regions plot from a VBDataFrame. Default options creates plots like those shown in Fig. 3 of "Measuring the Capabilities of Quantum Computers" arXiv:2008.11294. """ x_values = vbdataframe.x_values y_values = vbdataframe.y_values fig, ax = empty_volumetric_plot(figsize=figsize, y_values=y_values, x_values=x_values, title=title) creg = vbdataframe.capability_regions(metric=metric, threshold=threshold, significance=significance, monotonic=True) # Split the data up into dicts for the three different regions: 'success', 'indeterminate' and 'fail'. creg_split = {} creg_split['success'] = {(w, d): 1 for (w, d), val in creg.items() if val == 2} creg_split['indeterminate'] = {(w, d): 1 for (w, d), val in creg.items() if val == 1} creg_split['fail'] = {(w, d): 1 for (w, d), val in creg.items() if val == 0} if colors is None: colors = {'success': [(0.2, 0.6274509803921569, 0.17254901960784313)], 'indeterminate': [(0.9921568627450981, 0.7490196078431373, 0.43529411764705883)], 'fail': 'w'} for region in ('success', 'indeterminate', 'fail'): fig, ax = volumetric_plot(creg_split[region], y_values=y_values, x_values=x_values, scale=scale, fig=fig, ax=ax, color=colors[region]) return fig, ax def volumetric_distribution_plot(vbdataframe, metric='polarization', threshold=1 / _np.e, hypothesis_test='standard', significance=0.05, figsize=(10, 10), scale={'min': 1.95, 'mean': 1, 'max': 0.13}, title=None, cmap=my_cmap): """ Creates volumetric benchmarking plots that display the maximum, mean and minimum of a given figure-of-merit (by default, circuit polarization) as a function of circuit shape. This function can be used to create figures like those shown in Fig. 1 of "Measuring the Capabilities of Quantum Computers" arXiv:2008.11294. Parameters ---------- vbdataframe : VBDataFrame A VBDataFrame object containing the data to be plotted in a VB plot. metric : string, optional The quantity to plot. Default is 'polarization' as used and defined in arXiv:2008.11294. The plot will show the maximum, mean, and minimum of this metric at each circuit shape. threshold : float, optional The threshold for "success" for the figure-of-merit defined by `metric`. This threshold is used to compute the three "success" boundaries that are shown in the plot. hypothesis_test : string, optional The type of statistical significance adjustment to apply to the boundaries. The options are - 'standard': this reproduces the method used and described in arXiv:2008.11294 (see the appendices for details). With this option, there will be a difference between the boundary for the minimum and maximum polarization only if there is statistically significant evidence in the data for this. - 'none': no statistical significance adjustment: all three boundaries show the point at which relevant statistic (maximum, mean, minimum) drops below the threshold. significance : float, optional The statistical significance in the hypothesis tests. Only used in `hypothesis_test` is not 'none'. figsize : tuple, optional The figure size scale : dict, optional The scale for the three concentric squares, showing the maximum, mean and minimum. title : sting, optional The figure title. cmap : ColorMap, optional A matplotlib colormap. Return ------ fig, ax : matplolib fig and ax. """ linescale = {'min': 1, 'mean': 0, 'max': 0} boundary_color = {'min': '#ff0000', 'mean': '#000000', 'max': '#2ecc71'} boundary_dashing = {'min': [1, 1], 'mean': None, 'max': [0.5, 0.5]} boundary_linewidth = {'min': 3, 'mean': 6, 'max': 5} x_values = vbdataframe.x_values y_values = vbdataframe.y_values fig, ax = empty_volumetric_plot(figsize=figsize, y_values=y_values, x_values=x_values, title=title) # Dictionary containing the three types of VB data that are used in this plot. vb_data = {stat: vbdataframe.vb_data(metric=metric, statistic=stat, no_data_action='discard') for stat in ('min', 'mean', 'max')} # Used to find the min and max boundaries if they are adjusted for statistical significance. capability_regions = vbdataframe.capability_regions(metric=metric, threshold=threshold, significance=significance, monotonic=True) if hypothesis_test == 'standard': adjusted_boundaries = ('max', 'min') unadjusted_boundaries = ('mean',) elif hypothesis_test == 'none': adjusted_boundaries = () unadjusted_boundaries = ('max', 'mean', 'min',) else: raise ValueError("`hypothesis_test` must be 'standard' or 'none'!") # Plots the data. for statistic in ('min', 'mean', 'max'): fig, ax = volumetric_plot(vb_data[statistic], y_values=y_values, x_values=x_values, fig=fig, ax=ax, scale=scale[statistic], linescale=linescale[statistic], cmap=cmap) # Plots the boundaries that have been adjusted for statistical significance. for statistic in adjusted_boundaries: if statistic == 'max': effective_threshold = 0.99 elif statistic == 'min': effective_threshold = 1.99 volumetric_boundary_plot(capability_regions, y_values=y_values, x_values=x_values, threshold=effective_threshold, missing_data_action='hedge', fig=fig, ax=ax, linestyle='-', color=boundary_color[statistic], linewidth=boundary_linewidth[statistic], dashing=boundary_dashing[statistic]) # Plots the boundaries that are not adjusted for statistical significance. for statistic in unadjusted_boundaries: volumetric_boundary_plot(vb_data[statistic], y_values=y_values, x_values=x_values, threshold=threshold, monotonic=False, missing_data_action='hedge', fig=fig, ax=ax, linestyle='-', color=boundary_color[statistic], linewidth=boundary_linewidth[statistic], dashing=boundary_dashing[statistic]) return fig, ax
[ "matplotlib.pyplot.title", "seaborn.set_style", "matplotlib.cm.get_cmap", "seaborn.despine", "numpy.isnan", "seaborn.color_palette", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.subplots", "matplotlib.colors.ListedColormap" ]
[((946, 969), 'seaborn.set_style', '_sns.set_style', (['"""white"""'], {}), "('white')\n", (960, 969), True, 'import seaborn as _sns\n'), ((974, 997), 'seaborn.set_style', '_sns.set_style', (['"""ticks"""'], {}), "('ticks')\n", (988, 997), True, 'import seaborn as _sns\n'), ((1136, 1158), 'matplotlib.colors.ListedColormap', '_ListedColormap', (['blues'], {}), '(blues)\n', (1151, 1158), True, 'from matplotlib.colors import ListedColormap as _ListedColormap\n'), ((1267, 1288), 'matplotlib.colors.ListedColormap', '_ListedColormap', (['reds'], {}), '(reds)\n', (1282, 1288), True, 'from matplotlib.colors import ListedColormap as _ListedColormap\n'), ((1405, 1428), 'matplotlib.colors.ListedColormap', '_ListedColormap', (['greens'], {}), '(greens)\n', (1420, 1428), True, 'from matplotlib.colors import ListedColormap as _ListedColormap\n'), ((1559, 1609), 'matplotlib.colors.ListedColormap', '_ListedColormap', (['[binary_blue[0], binary_blue[50]]'], {}), '([binary_blue[0], binary_blue[50]])\n', (1574, 1609), True, 'from matplotlib.colors import ListedColormap as _ListedColormap\n'), ((1626, 1650), 'matplotlib.cm.get_cmap', '_cm.get_cmap', (['"""Spectral"""'], {}), "('Spectral')\n", (1638, 1650), True, 'from matplotlib import cm as _cm\n'), ((2821, 2851), 'matplotlib.pyplot.subplots', '_plt.subplots', ([], {'figsize': 'figsize'}), '(figsize=figsize)\n', (2834, 2851), True, 'import matplotlib.pyplot as _plt\n'), ((2883, 2915), 'matplotlib.pyplot.xlabel', '_plt.xlabel', (['xlabel'], {'fontsize': '(20)'}), '(xlabel, fontsize=20)\n', (2894, 2915), True, 'import matplotlib.pyplot as _plt\n'), ((2920, 2952), 'matplotlib.pyplot.ylabel', '_plt.ylabel', (['ylabel'], {'fontsize': '(20)'}), '(ylabel, fontsize=20)\n', (2931, 2952), True, 'import matplotlib.pyplot as _plt\n'), ((2957, 2995), 'matplotlib.pyplot.title', '_plt.title', (['title'], {'fontsize': '(24)', 'y': '(1.02)'}), '(title, fontsize=24, y=1.02)\n', (2967, 2995), True, 'import matplotlib.pyplot as _plt\n'), ((3365, 3379), 'seaborn.despine', '_sns.despine', ([], {}), '()\n', (3377, 3379), True, 'import seaborn as _sns\n'), ((1056, 1088), 'seaborn.color_palette', '_sns.color_palette', (['"""Blues"""', '(200)'], {}), "('Blues', 200)\n", (1074, 1088), True, 'import seaborn as _sns\n'), ((1190, 1221), 'seaborn.color_palette', '_sns.color_palette', (['"""Reds"""', '(200)'], {}), "('Reds', 200)\n", (1208, 1221), True, 'import seaborn as _sns\n'), ((1322, 1355), 'seaborn.color_palette', '_sns.color_palette', (['"""Greens"""', '(200)'], {}), "('Greens', 200)\n", (1340, 1355), True, 'import seaborn as _sns\n'), ((1467, 1499), 'seaborn.color_palette', '_sns.color_palette', (['"""Blues"""', '(200)'], {}), "('Blues', 200)\n", (1485, 1499), True, 'import seaborn as _sns\n'), ((4750, 4770), 'numpy.isnan', '_np.isnan', (['datapoint'], {}), '(datapoint)\n', (4759, 4770), True, 'import numpy as _np\n')]
import os import numpy as np opj = os.path.join from astropy.io import fits data_path = '../../data/cosmology' def downsample(parameter_file, root_dir, resize=64, nsamples=30000, ncosmo=10): ''' downsample cosmolgy image ''' print('preprocessing...') img_size = 256 params_ = np.loadtxt(parameter_file)[:ncosmo] image = [] params = [] for idx in range(nsamples): img_name = opj(root_dir, 'model%03d/WLconv_z1.00_%04dr.fits' % (idx % len(params_), idx // len(params_))) start1 = np.random.randint(0, img_size - resize - 1, 1)[0] start2 = np.random.randint(0, img_size - resize - 1, 1)[0] end1 = start1 + resize end2 = start2 + resize hdu_list = fits.open(img_name, memmap=False) img_data = hdu_list[0].data image.append(img_data[start1:end1, start2:end2]) hdu_list.close() params.append(params_[idx % len(params_), 1:-1]) print('\r idx: {}/{}'.format(idx, nsamples), end='') image = np.stack(image, axis=0) params = np.stack(params, axis=0) # save np.savez(opj(data_path, 'cosmo_resize_{}.npz'.format(resize)), imgs=image, params=params) if __name__ == '__main__': parameter_file = opj(data_path, 'cosmological_parameters.txt') root_dir = opj(data_path, 'z1_256') resize = 64 # save downsample(parameter_file, root_dir, resize) # load dataset_zip = np.load(opj(data_path, 'cosmo_resize_{}.npz'.format(resize))) imgs = dataset_zip['imgs'] params = dataset_zip['params'] print(imgs.shape, params.shape)
[ "numpy.stack", "numpy.random.randint", "astropy.io.fits.open", "numpy.loadtxt" ]
[((1017, 1040), 'numpy.stack', 'np.stack', (['image'], {'axis': '(0)'}), '(image, axis=0)\n', (1025, 1040), True, 'import numpy as np\n'), ((1054, 1078), 'numpy.stack', 'np.stack', (['params'], {'axis': '(0)'}), '(params, axis=0)\n', (1062, 1078), True, 'import numpy as np\n'), ((305, 331), 'numpy.loadtxt', 'np.loadtxt', (['parameter_file'], {}), '(parameter_file)\n', (315, 331), True, 'import numpy as np\n'), ((734, 767), 'astropy.io.fits.open', 'fits.open', (['img_name'], {'memmap': '(False)'}), '(img_name, memmap=False)\n', (743, 767), False, 'from astropy.io import fits\n'), ((536, 582), 'numpy.random.randint', 'np.random.randint', (['(0)', '(img_size - resize - 1)', '(1)'], {}), '(0, img_size - resize - 1, 1)\n', (553, 582), True, 'import numpy as np\n'), ((603, 649), 'numpy.random.randint', 'np.random.randint', (['(0)', '(img_size - resize - 1)', '(1)'], {}), '(0, img_size - resize - 1, 1)\n', (620, 649), True, 'import numpy as np\n')]
#!/usr/bin/env python # -*- coding: utf-8 -*- """Core IO, DSP and utility functions.""" import os import six import audioread import numpy as np import scipy.signal import scipy.fftpack as fft import resampy from .time_frequency import frames_to_samples, time_to_samples from .. import cache from .. import util from ..util.exceptions import ParameterError __all__ = ['load', 'to_mono', 'resample', 'get_duration', 'autocorrelate', 'zero_crossings', 'clicks', 'tone', 'chirp'] # Resampling bandwidths as percentage of Nyquist BW_BEST = resampy.filters.get_filter('kaiser_best')[2] BW_FASTEST = resampy.filters.get_filter('kaiser_fast')[2] # -- CORE ROUTINES --# # Load should never be cached, since we cannot verify that the contents of # 'path' are unchanged across calls. def load(path, sr=22050, mono=True, offset=0.0, duration=None, dtype=np.float32, res_type='kaiser_best'): """Load an audio file as a floating point time series. Audio will be automatically resampled to the given rate (default `sr=22050`). To preserve the native sampling rate of the file, use `sr=None`. Parameters ---------- path : string path to the input file. Any format supported by `audioread` will work. sr : number > 0 [scalar] target sampling rate 'None' uses the native sampling rate mono : bool convert signal to mono offset : float start reading after this time (in seconds) duration : float only load up to this much audio (in seconds) dtype : numeric type data type of `y` res_type : str resample type (see note) .. note:: By default, this uses `resampy`'s high-quality mode ('kaiser_best'). To use a faster method, set `res_type='kaiser_fast'`. To use `scipy.signal.resample`, set `res_type='scipy'`. Returns ------- y : np.ndarray [shape=(n,) or (2, n)] audio time series sr : number > 0 [scalar] sampling rate of `y` Examples -------- >>> # Load a wav file >>> filename = librosa.util.example_audio_file() >>> y, sr = librosa.load(filename) >>> y array([ -4.756e-06, -6.020e-06, ..., -1.040e-06, 0.000e+00], dtype=float32) >>> sr 22050 >>> # Load a wav file and resample to 11 KHz >>> filename = librosa.util.example_audio_file() >>> y, sr = librosa.load(filename, sr=11025) >>> y array([ -2.077e-06, -2.928e-06, ..., -4.395e-06, 0.000e+00], dtype=float32) >>> sr 11025 >>> # Load 5 seconds of a wav file, starting 15 seconds in >>> filename = librosa.util.example_audio_file() >>> y, sr = librosa.load(filename, offset=15.0, duration=5.0) >>> y array([ 0.069, 0.1 , ..., -0.101, 0. ], dtype=float32) >>> sr 22050 """ y = [] with audioread.audio_open(os.path.realpath(path)) as input_file: sr_native = input_file.samplerate n_channels = input_file.channels s_start = int(np.round(sr_native * offset)) * n_channels if duration is None: s_end = np.inf else: s_end = s_start + (int(np.round(sr_native * duration)) * n_channels) n = 0 for frame in input_file: frame = util.buf_to_float(frame, dtype=dtype) n_prev = n n = n + len(frame) if n < s_start: # offset is after the current frame # keep reading continue if s_end < n_prev: # we're off the end. stop reading break if s_end < n: # the end is in this frame. crop. frame = frame[:s_end - n_prev] if n_prev <= s_start <= n: # beginning is in this frame frame = frame[(s_start - n_prev):] # tack on the current frame y.append(frame) if y: y = np.concatenate(y) if n_channels > 1: y = y.reshape((-1, n_channels)).T if mono: y = to_mono(y) if sr is not None: y = resample(y, sr_native, sr, res_type=res_type) else: sr = sr_native # Final cleanup for dtype and contiguity y = np.ascontiguousarray(y, dtype=dtype) return (y, sr) @cache(level=20) def to_mono(y): '''Force an audio signal down to mono. Parameters ---------- y : np.ndarray [shape=(2,n) or shape=(n,)] audio time series, either stereo or mono Returns ------- y_mono : np.ndarray [shape=(n,)] `y` as a monophonic time-series Notes ----- This function caches at level 20. Examples -------- >>> y, sr = librosa.load(librosa.util.example_audio_file(), mono=False) >>> y.shape (2, 1355168) >>> y_mono = librosa.to_mono(y) >>> y_mono.shape (1355168,) ''' # Validate the buffer. Stereo is ok here. util.valid_audio(y, mono=False) if y.ndim > 1: y = np.mean(y, axis=0) return y @cache(level=20) def resample(y, orig_sr, target_sr, res_type='kaiser_best', fix=True, scale=False, **kwargs): """Resample a time series from orig_sr to target_sr Parameters ---------- y : np.ndarray [shape=(n,) or shape=(2, n)] audio time series. Can be mono or stereo. orig_sr : number > 0 [scalar] original sampling rate of `y` target_sr : number > 0 [scalar] target sampling rate res_type : str resample type (see note) .. note:: By default, this uses `resampy`'s high-quality mode ('kaiser_best'). To use a faster method, set `res_type='kaiser_fast'`. To use `scipy.signal.resample`, set `res_type='scipy'`. fix : bool adjust the length of the resampled signal to be of size exactly `ceil(target_sr * len(y) / orig_sr)` scale : bool Scale the resampled signal so that `y` and `y_hat` have approximately equal total energy. kwargs : additional keyword arguments If `fix==True`, additional keyword arguments to pass to `librosa.util.fix_length`. Returns ------- y_hat : np.ndarray [shape=(n * target_sr / orig_sr,)] `y` resampled from `orig_sr` to `target_sr` See Also -------- librosa.util.fix_length scipy.signal.resample resampy.resample Notes ----- This function caches at level 20. Examples -------- Downsample from 22 KHz to 8 KHz >>> y, sr = librosa.load(librosa.util.example_audio_file(), sr=22050) >>> y_8k = librosa.resample(y, sr, 8000) >>> y.shape, y_8k.shape ((1355168,), (491671,)) """ # First, validate the audio buffer util.valid_audio(y, mono=False) if orig_sr == target_sr: return y ratio = float(target_sr) / orig_sr n_samples = int(np.ceil(y.shape[-1] * ratio)) if res_type == 'scipy': y_hat = scipy.signal.resample(y, n_samples, axis=-1) else: y_hat = resampy.resample(y, orig_sr, target_sr, filter=res_type, axis=-1) if fix: y_hat = util.fix_length(y_hat, n_samples, **kwargs) if scale: y_hat /= np.sqrt(ratio) return np.ascontiguousarray(y_hat, dtype=y.dtype) def get_duration(y=None, sr=22050, S=None, n_fft=2048, hop_length=512, center=True, filename=None): """Compute the duration (in seconds) of an audio time series, feature matrix, or filename. Examples -------- >>> # Load the example audio file >>> y, sr = librosa.load(librosa.util.example_audio_file()) >>> librosa.get_duration(y=y, sr=sr) 61.45886621315193 >>> # Or directly from an audio file >>> librosa.get_duration(filename=librosa.util.example_audio_file()) 61.4 >>> # Or compute duration from an STFT matrix >>> y, sr = librosa.load(librosa.util.example_audio_file()) >>> S = librosa.stft(y) >>> librosa.get_duration(S=S, sr=sr) 61.44 >>> # Or a non-centered STFT matrix >>> S_left = librosa.stft(y, center=False) >>> librosa.get_duration(S=S_left, sr=sr) 61.3471201814059 Parameters ---------- y : np.ndarray [shape=(n,), (2, n)] or None audio time series sr : number > 0 [scalar] audio sampling rate of `y` S : np.ndarray [shape=(d, t)] or None STFT matrix, or any STFT-derived matrix (e.g., chromagram or mel spectrogram). Durations calculated from spectrogram inputs are only accurate up to the frame resolution. If high precision is required, it is better to use the audio time series directly. n_fft : int > 0 [scalar] FFT window size for `S` hop_length : int > 0 [ scalar] number of audio samples between columns of `S` center : boolean - If `True`, `S[:, t]` is centered at `y[t * hop_length]` - If `False`, then `S[:, t]` begins at `y[t * hop_length]` filename : str If provided, all other parameters are ignored, and the duration is calculated directly from the audio file. Note that this avoids loading the contents into memory, and is therefore useful for querying the duration of long files. Returns ------- d : float >= 0 Duration (in seconds) of the input time series or spectrogram. Raises ------ ParameterError if none of `y`, `S`, or `filename` are provided. Notes ----- `get_duration` can be applied to a file (`filename`), a spectrogram (`S`), or audio buffer (`y, sr`). Only one of these three options should be provided. If you do provide multiple options (e.g., `filename` and `S`), then `filename` takes precedence over `S`, and `S` takes precedence over `(y, sr)`. """ if filename is not None: with audioread.audio_open(filename) as fdesc: return fdesc.duration if y is None: if S is None: raise ParameterError('At least one of (y, sr), S, or filename must be provided') n_frames = S.shape[1] n_samples = n_fft + hop_length * (n_frames - 1) # If centered, we lose half a window from each end of S if center: n_samples = n_samples - 2 * int(n_fft / 2) else: # Validate the audio buffer. Stereo is okay here. util.valid_audio(y, mono=False) if y.ndim == 1: n_samples = len(y) else: n_samples = y.shape[-1] return float(n_samples) / sr @cache(level=20) def autocorrelate(y, max_size=None, axis=-1): """Bounded auto-correlation Parameters ---------- y : np.ndarray array to autocorrelate max_size : int > 0 or None maximum correlation lag. If unspecified, defaults to `y.shape[axis]` (unbounded) axis : int The axis along which to autocorrelate. By default, the last axis (-1) is taken. Returns ------- z : np.ndarray truncated autocorrelation `y*y` along the specified axis. If `max_size` is specified, then `z.shape[axis]` is bounded to `max_size`. Notes ----- This function caches at level 20. Examples -------- Compute full autocorrelation of y >>> y, sr = librosa.load(librosa.util.example_audio_file(), offset=20, duration=10) >>> librosa.autocorrelate(y) array([ 3.226e+03, 3.217e+03, ..., 8.277e-04, 3.575e-04], dtype=float32) Compute onset strength auto-correlation up to 4 seconds >>> import matplotlib.pyplot as plt >>> odf = librosa.onset.onset_strength(y=y, sr=sr, hop_length=512) >>> ac = librosa.autocorrelate(odf, max_size=4* sr / 512) >>> plt.plot(ac) >>> plt.title('Auto-correlation') >>> plt.xlabel('Lag (frames)') """ if max_size is None: max_size = y.shape[axis] max_size = int(min(max_size, y.shape[axis])) # Compute the power spectrum along the chosen axis # Pad out the signal to support full-length auto-correlation. powspec = np.abs(fft.fft(y, n=2 * y.shape[axis] + 1, axis=axis))**2 # Convert back to time domain autocorr = fft.ifft(powspec, axis=axis, overwrite_x=True) # Slice down to max_size subslice = [slice(None)] * autocorr.ndim subslice[axis] = slice(max_size) autocorr = autocorr[tuple(subslice)] if not np.iscomplexobj(y): autocorr = autocorr.real return autocorr @cache(level=20) def zero_crossings(y, threshold=1e-10, ref_magnitude=None, pad=True, zero_pos=True, axis=-1): '''Find the zero-crossings of a signal `y`: indices `i` such that `sign(y[i]) != sign(y[j])`. If `y` is multi-dimensional, then zero-crossings are computed along the specified `axis`. Parameters ---------- y : np.ndarray The input array threshold : float > 0 or None If specified, values where `-threshold <= y <= threshold` are clipped to 0. ref_magnitude : float > 0 or callable If numeric, the threshold is scaled relative to `ref_magnitude`. If callable, the threshold is scaled relative to `ref_magnitude(np.abs(y))`. pad : boolean If `True`, then `y[0]` is considered a valid zero-crossing. zero_pos : boolean If `True` then the value 0 is interpreted as having positive sign. If `False`, then 0, -1, and +1 all have distinct signs. axis : int Axis along which to compute zero-crossings. Returns ------- zero_crossings : np.ndarray [shape=y.shape, dtype=boolean] Indicator array of zero-crossings in `y` along the selected axis. Notes ----- This function caches at level 20. Examples -------- >>> # Generate a time-series >>> y = np.sin(np.linspace(0, 4 * 2 * np.pi, 20)) >>> y array([ 0.000e+00, 9.694e-01, 4.759e-01, -7.357e-01, -8.372e-01, 3.247e-01, 9.966e-01, 1.646e-01, -9.158e-01, -6.142e-01, 6.142e-01, 9.158e-01, -1.646e-01, -9.966e-01, -3.247e-01, 8.372e-01, 7.357e-01, -4.759e-01, -9.694e-01, -9.797e-16]) >>> # Compute zero-crossings >>> z = librosa.zero_crossings(y) >>> z array([ True, False, False, True, False, True, False, False, True, False, True, False, True, False, False, True, False, True, False, True], dtype=bool) >>> # Stack y against the zero-crossing indicator >>> np.vstack([y, z]).T array([[ 0.000e+00, 1.000e+00], [ 9.694e-01, 0.000e+00], [ 4.759e-01, 0.000e+00], [ -7.357e-01, 1.000e+00], [ -8.372e-01, 0.000e+00], [ 3.247e-01, 1.000e+00], [ 9.966e-01, 0.000e+00], [ 1.646e-01, 0.000e+00], [ -9.158e-01, 1.000e+00], [ -6.142e-01, 0.000e+00], [ 6.142e-01, 1.000e+00], [ 9.158e-01, 0.000e+00], [ -1.646e-01, 1.000e+00], [ -9.966e-01, 0.000e+00], [ -3.247e-01, 0.000e+00], [ 8.372e-01, 1.000e+00], [ 7.357e-01, 0.000e+00], [ -4.759e-01, 1.000e+00], [ -9.694e-01, 0.000e+00], [ -9.797e-16, 1.000e+00]]) >>> # Find the indices of zero-crossings >>> np.nonzero(z) (array([ 0, 3, 5, 8, 10, 12, 15, 17, 19]),) ''' # Clip within the threshold if threshold is None: threshold = 0.0 if six.callable(ref_magnitude): threshold = threshold * ref_magnitude(np.abs(y)) elif ref_magnitude is not None: threshold = threshold * ref_magnitude if threshold > 0: y = y.copy() y[np.abs(y) <= threshold] = 0 # Extract the sign bit if zero_pos: y_sign = np.signbit(y) else: y_sign = np.sign(y) # Find the change-points by slicing slice_pre = [slice(None)] * y.ndim slice_pre[axis] = slice(1, None) slice_post = [slice(None)] * y.ndim slice_post[axis] = slice(-1) # Since we've offset the input by one, pad back onto the front padding = [(0, 0)] * y.ndim padding[axis] = (1, 0) return np.pad((y_sign[tuple(slice_post)] != y_sign[tuple(slice_pre)]), padding, mode='constant', constant_values=pad) def clicks(times=None, frames=None, sr=22050, hop_length=512, click_freq=1000.0, click_duration=0.1, click=None, length=None): """Returns a signal with the signal `click` placed at each specified time Parameters ---------- times : np.ndarray or None times to place clicks, in seconds frames : np.ndarray or None frame indices to place clicks sr : number > 0 desired sampling rate of the output signal hop_length : int > 0 if positions are specified by `frames`, the number of samples between frames. click_freq : float > 0 frequency (in Hz) of the default click signal. Default is 1KHz. click_duration : float > 0 duration (in seconds) of the default click signal. Default is 100ms. click : np.ndarray or None optional click signal sample to use instead of the default blip. length : int > 0 desired number of samples in the output signal Returns ------- click_signal : np.ndarray Synthesized click signal Raises ------ ParameterError - If neither `times` nor `frames` are provided. - If any of `click_freq`, `click_duration`, or `length` are out of range. Examples -------- >>> # Sonify detected beat events >>> y, sr = librosa.load(librosa.util.example_audio_file()) >>> tempo, beats = librosa.beat.beat_track(y=y, sr=sr) >>> y_beats = librosa.clicks(frames=beats, sr=sr) >>> # Or generate a signal of the same length as y >>> y_beats = librosa.clicks(frames=beats, sr=sr, length=len(y)) >>> # Or use timing instead of frame indices >>> times = librosa.frames_to_time(beats, sr=sr) >>> y_beat_times = librosa.clicks(times=times, sr=sr) >>> # Or with a click frequency of 880Hz and a 500ms sample >>> y_beat_times880 = librosa.clicks(times=times, sr=sr, ... click_freq=880, click_duration=0.5) Display click waveform next to the spectrogram >>> import matplotlib.pyplot as plt >>> plt.figure() >>> S = librosa.feature.melspectrogram(y=y, sr=sr) >>> ax = plt.subplot(2,1,2) >>> librosa.display.specshow(librosa.power_to_db(S, ref=np.max), ... x_axis='time', y_axis='mel') >>> plt.subplot(2,1,1, sharex=ax) >>> librosa.display.waveplot(y_beat_times, sr=sr, label='Beat clicks') >>> plt.legend() >>> plt.xlim(15, 30) >>> plt.tight_layout() """ # Compute sample positions from time or frames if times is None: if frames is None: raise ParameterError('either "times" or "frames" must be provided') positions = frames_to_samples(frames, hop_length=hop_length) else: # Convert times to positions positions = time_to_samples(times, sr=sr) if click is not None: # Check that we have a well-formed audio buffer util.valid_audio(click, mono=True) else: # Create default click signal if click_duration <= 0: raise ParameterError('click_duration must be strictly positive') if click_freq <= 0: raise ParameterError('click_freq must be strictly positive') angular_freq = 2 * np.pi * click_freq / float(sr) click = np.logspace(0, -10, num=int(np.round(sr * click_duration)), base=2.0) click *= np.sin(angular_freq * np.arange(len(click))) # Set default length if length is None: length = positions.max() + click.shape[0] else: if length < 1: raise ParameterError('length must be a positive integer') # Filter out any positions past the length boundary positions = positions[positions < length] # Pre-allocate click signal click_signal = np.zeros(length, dtype=np.float32) # Place clicks for start in positions: # Compute the end-point of this click end = start + click.shape[0] if end >= length: click_signal[start:] += click[:length - start] else: # Normally, just add a click here click_signal[start:end] += click return click_signal def tone(frequency, sr=22050, length=None, duration=None, phi=None): """Returns a pure tone signal. The signal generated is a cosine wave. Parameters ---------- frequency : float > 0 frequency sr : number > 0 desired sampling rate of the output signal length : int > 0 desired number of samples in the output signal. When both `duration` and `length` are defined, `length` would take priority. duration : float > 0 desired duration in seconds. When both `duration` and `length` are defined, `length` would take priority. phi : float or None phase offset, in radians. If unspecified, defaults to `-np.pi * 0.5`. Returns ------- tone_signal : np.ndarray [shape=(length,), dtype=float64] Synthesized pure sine tone signal Raises ------ ParameterError - If `frequency` is not provided. - If neither `length` nor `duration` are provided. Examples -------- >>> # Generate a pure sine tone A4 >>> tone = librosa.tone(440, duration=1) >>> # Or generate the same signal using `length` >>> tone = librosa.tone(440, sr=22050, length=22050) Display spectrogram >>> import matplotlib.pyplot as plt >>> plt.figure() >>> S = librosa.feature.melspectrogram(y=tone) >>> librosa.display.specshow(librosa.power_to_db(S, ref=np.max), ... x_axis='time', y_axis='mel') """ if frequency is None: raise ParameterError('"frequency" must be provided') # Compute signal length if length is None: if duration is None: raise ParameterError('either "length" or "duration" must be provided') length = duration * sr if phi is None: phi = -np.pi * 0.5 step = 1.0 / sr return np.cos(2 * np.pi * frequency * (np.arange(step * length, step=step)) + phi) def chirp(fmin, fmax, sr=22050, length=None, duration=None, linear=False, phi=None): """Returns a chirp signal that goes from frequency `fmin` to frequency `fmax` Parameters ---------- fmin : float > 0 initial frequency fmax : float > 0 final frequency sr : number > 0 desired sampling rate of the output signal length : int > 0 desired number of samples in the output signal. When both `duration` and `length` are defined, `length` would take priority. duration : float > 0 desired duration in seconds. When both `duration` and `length` are defined, `length` would take priority. linear : boolean - If `True`, use a linear sweep, i.e., frequency changes linearly with time - If `False`, use a exponential sweep. Default is `False`. phi : float or None phase offset, in radians. If unspecified, defaults to `-np.pi * 0.5`. Returns ------- chirp_signal : np.ndarray [shape=(length,), dtype=float64] Synthesized chirp signal Raises ------ ParameterError - If either `fmin` or `fmax` are not provided. - If neither `length` nor `duration` are provided. See Also -------- scipy.signal.chirp Examples -------- >>> # Generate a exponential chirp from A4 to A5 >>> exponential_chirp = librosa.chirp(440, 880, duration=1) >>> # Or generate the same signal using `length` >>> exponential_chirp = librosa.chirp(440, 880, sr=22050, length=22050) >>> # Or generate a linear chirp instead >>> linear_chirp = librosa.chirp(440, 880, duration=1, linear=True) Display spectrogram for both exponential and linear chirps >>> import matplotlib.pyplot as plt >>> plt.figure() >>> S_exponential = librosa.feature.melspectrogram(y=exponential_chirp) >>> ax = plt.subplot(2,1,1) >>> librosa.display.specshow(librosa.power_to_db(S_exponential, ref=np.max), ... x_axis='time', y_axis='mel') >>> plt.subplot(2,1,2, sharex=ax) >>> S_linear = librosa.feature.melspectrogram(y=linear_chirp) >>> librosa.display.specshow(librosa.power_to_db(S_linear, ref=np.max), ... x_axis='time', y_axis='mel') >>> plt.tight_layout() """ if fmin is None or fmax is None: raise ParameterError('both "fmin" and "fmax" must be provided') # Compute signal duration period = 1.0 / sr if length is None: if duration is None: raise ParameterError('either "length" or "duration" must be provided') else: duration = period * length if phi is None: phi = -np.pi * 0.5 method = 'linear' if linear else 'logarithmic' return scipy.signal.chirp( np.arange(duration, step=period), fmin, duration, fmax, method=method, phi=phi / np.pi * 180, # scipy.signal.chirp uses degrees for phase offset )
[ "numpy.abs", "resampy.filters.get_filter", "numpy.mean", "numpy.arange", "numpy.sqrt", "numpy.round", "resampy.resample", "six.callable", "numpy.ceil", "os.path.realpath", "audioread.audio_open", "scipy.fftpack.ifft", "scipy.fftpack.fft", "numpy.concatenate", "numpy.iscomplexobj", "num...
[((552, 593), 'resampy.filters.get_filter', 'resampy.filters.get_filter', (['"""kaiser_best"""'], {}), "('kaiser_best')\n", (578, 593), False, 'import resampy\n'), ((610, 651), 'resampy.filters.get_filter', 'resampy.filters.get_filter', (['"""kaiser_fast"""'], {}), "('kaiser_fast')\n", (636, 651), False, 'import resampy\n'), ((4373, 4409), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['y'], {'dtype': 'dtype'}), '(y, dtype=dtype)\n', (4393, 4409), True, 'import numpy as np\n'), ((7361, 7403), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['y_hat'], {'dtype': 'y.dtype'}), '(y_hat, dtype=y.dtype)\n', (7381, 7403), True, 'import numpy as np\n'), ((12333, 12379), 'scipy.fftpack.ifft', 'fft.ifft', (['powspec'], {'axis': 'axis', 'overwrite_x': '(True)'}), '(powspec, axis=axis, overwrite_x=True)\n', (12341, 12379), True, 'import scipy.fftpack as fft\n'), ((15692, 15719), 'six.callable', 'six.callable', (['ref_magnitude'], {}), '(ref_magnitude)\n', (15704, 15719), False, 'import six\n'), ((20414, 20448), 'numpy.zeros', 'np.zeros', (['length'], {'dtype': 'np.float32'}), '(length, dtype=np.float32)\n', (20422, 20448), True, 'import numpy as np\n'), ((4043, 4060), 'numpy.concatenate', 'np.concatenate', (['y'], {}), '(y)\n', (4057, 4060), True, 'import numpy as np\n'), ((5129, 5147), 'numpy.mean', 'np.mean', (['y'], {'axis': '(0)'}), '(y, axis=0)\n', (5136, 5147), True, 'import numpy as np\n'), ((7017, 7045), 'numpy.ceil', 'np.ceil', (['(y.shape[-1] * ratio)'], {}), '(y.shape[-1] * ratio)\n', (7024, 7045), True, 'import numpy as np\n'), ((7163, 7228), 'resampy.resample', 'resampy.resample', (['y', 'orig_sr', 'target_sr'], {'filter': 'res_type', 'axis': '(-1)'}), '(y, orig_sr, target_sr, filter=res_type, axis=-1)\n', (7179, 7228), False, 'import resampy\n'), ((7334, 7348), 'numpy.sqrt', 'np.sqrt', (['ratio'], {}), '(ratio)\n', (7341, 7348), True, 'import numpy as np\n'), ((12546, 12564), 'numpy.iscomplexobj', 'np.iscomplexobj', (['y'], {}), '(y)\n', (12561, 12564), True, 'import numpy as np\n'), ((16005, 16018), 'numpy.signbit', 'np.signbit', (['y'], {}), '(y)\n', (16015, 16018), True, 'import numpy as np\n'), ((16046, 16056), 'numpy.sign', 'np.sign', (['y'], {}), '(y)\n', (16053, 16056), True, 'import numpy as np\n'), ((25526, 25558), 'numpy.arange', 'np.arange', (['duration'], {'step': 'period'}), '(duration, step=period)\n', (25535, 25558), True, 'import numpy as np\n'), ((2916, 2938), 'os.path.realpath', 'os.path.realpath', (['path'], {}), '(path)\n', (2932, 2938), False, 'import os\n'), ((10007, 10037), 'audioread.audio_open', 'audioread.audio_open', (['filename'], {}), '(filename)\n', (10027, 10037), False, 'import audioread\n'), ((12232, 12278), 'scipy.fftpack.fft', 'fft.fft', (['y'], {'n': '(2 * y.shape[axis] + 1)', 'axis': 'axis'}), '(y, n=2 * y.shape[axis] + 1, axis=axis)\n', (12239, 12278), True, 'import scipy.fftpack as fft\n'), ((3061, 3089), 'numpy.round', 'np.round', (['(sr_native * offset)'], {}), '(sr_native * offset)\n', (3069, 3089), True, 'import numpy as np\n'), ((15767, 15776), 'numpy.abs', 'np.abs', (['y'], {}), '(y)\n', (15773, 15776), True, 'import numpy as np\n'), ((15915, 15924), 'numpy.abs', 'np.abs', (['y'], {}), '(y)\n', (15921, 15924), True, 'import numpy as np\n'), ((22655, 22690), 'numpy.arange', 'np.arange', (['(step * length)'], {'step': 'step'}), '(step * length, step=step)\n', (22664, 22690), True, 'import numpy as np\n'), ((19916, 19945), 'numpy.round', 'np.round', (['(sr * click_duration)'], {}), '(sr * click_duration)\n', (19924, 19945), True, 'import numpy as np\n'), ((3210, 3240), 'numpy.round', 'np.round', (['(sr_native * duration)'], {}), '(sr_native * duration)\n', (3218, 3240), True, 'import numpy as np\n')]
import tkinter as tk from collections import deque from tkinter.constants import BUTT, END, GROOVE, NW, RAISED, RIDGE, S, SUNKEN import numpy as np import cv2 from PIL import Image,ImageTk import os import face_recognition import time window =tk.Tk() window.option_add("*Font","Helvetica 14") window.geometry("300x350+100+20") window.title("Face Recognition System") window.resizable(False, False) window.configure(bg="#7FACD6") facerecog_Mainbutton= ImageTk.PhotoImage((Image.open('./Asset/savemain.png')).resize((250,100), Image.ANTIALIAS)) facerecog_Mainbutton_change= ImageTk.PhotoImage((Image.open('./Asset/savemain_change.png')).resize((250,100), Image.ANTIALIAS)) facedetect_Mainbutton= ImageTk.PhotoImage((Image.open('./Asset/facerecognitionmain.png')).resize((250,100), Image.ANTIALIAS)) facedetect_Mainbutton_change=ImageTk.PhotoImage((Image.open('./Asset/facerecognitionmain_change.png')).resize((250,100), Image.ANTIALIAS)) video_capture=cv2.VideoCapture(0+cv2.CAP_DSHOW) def recog_enter(a): facerecog.configure(image=facerecog_Mainbutton_change) def recog_leave(a): facerecog.configure(image=facerecog_Mainbutton) def detect_enter(a): facedetect.configure(image=facedetect_Mainbutton_change) def detect_leave(a): facedetect.configure(image=facedetect_Mainbutton) def save_file(): Name=str(save_Entry.get()) print("Your name is "+Name) newpath = f'./Known/{Name}' ret,capture=video_capture.read() if not os.path.exists(newpath): os.makedirs(newpath) print("make new floder") time.sleep(1) print("processing.......") time.sleep(2) filename=Name+"1.jpg" cv2.imwrite(f'./Known/{Name}/{filename}',capture) Path, dirs, files_now = next(os.walk("./Known/{}".format(Name))) file_count_now = len(files_now) print("now you have {} picture in floder".format(file_count_now)) print(os.listdir(f'./Known/{Name}')) else : Path, dirs, files = next(os.walk("./Known/{}".format(Name))) file_count_beta = len(files) print("Before : you have {} picture in floder ".format(file_count_beta)) print(os.listdir(f'./Known/{Name}')) time.sleep(1) print("processing.......") time.sleep(2) filename=Name+str(file_count_beta+1)+".jpg" cv2.imwrite('./Known/{}/{}'.format(Name,filename),capture) Path, dirs, files_now = next(os.walk("./Known/{}".format(Name))) file_count_now = len(files_now) print("After : you have {} picture in floder".format(file_count_now)) print(os.listdir(f'./Known/{Name}')) def facerecognition(): def reset(): fps_label.pack_forget() image_label.place_forget() def Entry_Callback(event): save_Entry.selection_range(0, END) reset() new_tab.title("เธˆเธ”เธˆเธณเนƒเธšเธซเธ™เน‰เธฒ") window.geometry("300x490+100+20") image_label.place(x = 0, y = 0) save_Label.configure(text='เธฅเธ‡เธŠเธทเนˆเธญเธœเธนเน‰เนƒเธŠเน‰เธฃเธฐเธšเธš') save_Label.pack(pady=20) save_Entry.pack() save_Entry.bind("<FocusIn>",Entry_Callback) save_Button.pack(pady=10) fps_label._frame_times = deque([0]*5) fps_label.pack() cascPathface = os.path.dirname(cv2.__file__) + "/data/haarcascade_frontalface_alt2.xml" faceCascade = cv2.CascadeClassifier(cascPathface) video_capture= cv2.VideoCapture(0+cv2.CAP_DSHOW) video_capture.set(3, 640) video_capture.set(4, 480) def all_update(new_tab, image_label, video_capture,fps_label): show_frames(image_label, video_capture) update_fps(fps_label) new_tab.after(0, func=lambda: all_update(new_tab, image_label, video_capture,fps_label)) def update_fps(fps_label): frame_times = fps_label._frame_times frame_times.rotate() frame_times[0] = time.time() sum_of_deltas = frame_times[0] - frame_times[-1] count_of_deltas = len(frame_times) - 1 try: fps = int(float(count_of_deltas) / sum_of_deltas) except ZeroDivisionError: fps = 0 fps_label.configure(text=("FPS: {}".format(fps))) def show_frames(image_label, video_capture): ret,frame = video_capture.read(0) gray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY) Face = faceCascade.detectMultiScale(gray,scaleFactor=1.1,minNeighbors=5,minSize=(60, 60),flags=cv2.CASCADE_SCALE_IMAGE) for (x, y, w, h) in Face: cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2) cv2.waitKey(0) img = ImageTk.PhotoImage(Image.fromarray(cv2.cvtColor(cv2.resize(frame,(0,0),fx=1.35,fy=1.35), cv2.COLOR_BGR2RGB))) image_label.configure(image=img) image_label._image_cache = img (new_tab).update() new_tab.after(0,func=lambda:all_update(new_tab, image_label, video_capture,fps_label)) new_tab.mainloop() def facedetect(): def reset(): fps_label.pack_forget() image_label.place_forget() save_Label.pack_forget() save_Entry.pack_forget() save_Button.pack_forget() reset() new_tab.title("เธ•เธฃเธงเธˆเธชเธญเธšเนƒเธšเธซเธ™เน‰เธฒ") window.geometry("300x370+100+20") image_label.place(x = 0, y = 0) fps_label._frame_times = deque([0]*5) fps_label.pack() video_capture = cv2.VideoCapture(0+cv2.CAP_DSHOW) video_capture.set(3, 640) video_capture.set(4, 480) known_faces = [] known_names = [] try: for name in os.listdir('Known'): for filename in os.listdir(f'Known/{name}'): image = face_recognition.load_image_file(f'Known/{name}/{filename}') test_encoding = face_recognition.face_encodings(image) if len(test_encoding) > 0 : encoding = test_encoding[0] else: continue known_faces.append(encoding) known_names.append(name) except: known_faces.append(None) known_names.append("Unknown") def all_update(new_tab, image_label, video_capture,fps_label): show_frames(image_label, video_capture) update_fps(fps_label) new_tab.after(0, func=lambda: all_update(new_tab, image_label, video_capture,fps_label)) def update_fps(fps_label): frame_times = fps_label._frame_times frame_times.rotate() frame_times[0] = time.time() sum_of_deltas = frame_times[0] - frame_times[-1] count_of_deltas = len(frame_times) - 1 try: fps = int(float(count_of_deltas) / sum_of_deltas) except ZeroDivisionError: fps = 0 fps_label.configure(text=("FPS: {}".format(fps))) def show_frames(image_label, video_capture): face_locations = [] face_encodings = [] face_name = [] face_percent=[] ret,frame = video_capture.read(0) if not ret: new_tab.destroy() rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) small_frame = cv2.resize(rgb, (0, 0), fx=1/4, fy=1/4) try: face_locations = face_recognition.face_locations(small_frame) face_encodings = face_recognition.face_encodings(small_frame,face_locations) for encoding in face_encodings: face_distance=face_recognition.face_distance(known_faces,encoding) best_match = np.argmin(face_distance) value_percent = 1-face_distance[best_match] if value_percent >=0.5: name=known_names[best_match] percent=round(value_percent*100,0) face_percent.append(int(percent)) else: name='Unknown' face_percent.append(0) face_name.append(name) for ( (TOP,RIGHT,BOTTOM,LEFT), name,percent) in zip( face_locations, face_name,face_percent): if name == 'Unknown': color_rectangle= [46,2,209] color_Match=[0, 0, 255] else: color_rectangle=[255,102,51] color_Match=[0,255,0] cv2.rectangle(frame, (LEFT*4, TOP*4), (RIGHT*4,BOTTOM*4), color_rectangle, 2) cv2.putText(frame, name, (LEFT*4, TOP*4), cv2.FONT_HERSHEY_COMPLEX,1, (255, 255, 255), 2) cv2.putText(frame,'Matches '+str(percent)+' %',(LEFT*4,(BOTTOM*4)+16),cv2.FONT_HERSHEY_COMPLEX,0.5, color_Match, 1) except: face_locations = face_recognition.face_locations(small_frame) for (TOP,RIGHT,BOTTOM,LEFT) in face_locations: name = 'Unknown' color_rectangle= [46,2,209] color_Match=[0, 0, 255] cv2.rectangle(frame, (LEFT*4, TOP*4), (RIGHT*4,BOTTOM*4), color_rectangle, 2) cv2.putText(frame, name, (LEFT*4, TOP*4), cv2.FONT_HERSHEY_COMPLEX,1, (255, 255, 255), 2) cv2.putText(frame,'Matches '+'0'+' %',(LEFT*4,(BOTTOM*4)+16),cv2.FONT_HERSHEY_COMPLEX,0.5, color_Match, 1) cv2.waitKey(0) img = ImageTk.PhotoImage(Image.fromarray(cv2.cvtColor(cv2.resize(frame,(0,0),fx=1.35,fy=1.35), cv2.COLOR_BGR2RGB))) image_label.configure(image=img) image_label._image_cache = img (new_tab).update() new_tab.after(0,func=lambda:all_update(new_tab, image_label, video_capture,fps_label)) new_tab.mainloop() label_main = (tk.Label(master=window,text="Face Recognition System",bg="#7FACD6")).pack(pady=30) facerecog=tk.Button(master=window,image=facerecog_Mainbutton,command=facerecognition,background="#7FACD6",activebackground="#7FACD6",borderwidth=0) facerecog.pack() facerecog.bind("<Enter>", recog_enter) facerecog.bind("<Leave>", recog_leave) facedetect=tk.Button(master=window,image=facedetect_Mainbutton,command=facedetect,background="#7FACD6",activebackground="#7FACD6",borderwidth=0) facedetect.pack(pady=10) facedetect.bind("<Enter>", detect_enter) facedetect.bind("<Leave>", detect_leave) new_tab=tk.Toplevel() new_tab.option_add("*Font","Helvetica 14") new_tab.configure(bg='black') new_tab.title("เธชเธงเธฑเธชเธ”เธตเธ„เธฃเธฑเธš") new_tab.geometry("%dx%d+%d+%d" % (864,648, 300+100, 20)) new_tab.resizable(False, False) image_label=tk.Label(master=new_tab,borderwidth=0) save_Label =tk.Label(master=window,bg="#7FACD6",borderwidth=0) save_Entry=tk.Entry(master=window,borderwidth=1,width=16,relief=SUNKEN,fg="#6E3CBC") save_Button=tk.Button(master=window,command=save_file,bg="#B8E4F0",activebackground="#B8E4F0",text='เธšเธฑเธ™เธ—เธถเธเธฃเธนเธ›เธ เธฒเธž',relief=RAISED,borderwidth=1) fps_label = tk.Label(master=window,background="#7FACD6",foreground="#225140",borderwidth=0) new_tab.mainloop() window.mainloop()
[ "numpy.argmin", "cv2.rectangle", "tkinter.Label", "collections.deque", "tkinter.Button", "cv2.imwrite", "os.path.dirname", "tkinter.Entry", "os.path.exists", "cv2.cvtColor", "face_recognition.face_encodings", "tkinter.Toplevel", "tkinter.Tk", "cv2.resize", "face_recognition.face_distance...
[((254, 261), 'tkinter.Tk', 'tk.Tk', ([], {}), '()\n', (259, 261), True, 'import tkinter as tk\n'), ((971, 1006), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0 + cv2.CAP_DSHOW)'], {}), '(0 + cv2.CAP_DSHOW)\n', (987, 1006), False, 'import cv2\n'), ((9862, 10013), 'tkinter.Button', 'tk.Button', ([], {'master': 'window', 'image': 'facerecog_Mainbutton', 'command': 'facerecognition', 'background': '"""#7FACD6"""', 'activebackground': '"""#7FACD6"""', 'borderwidth': '(0)'}), "(master=window, image=facerecog_Mainbutton, command=\n facerecognition, background='#7FACD6', activebackground='#7FACD6',\n borderwidth=0)\n", (9871, 10013), True, 'import tkinter as tk\n'), ((10110, 10252), 'tkinter.Button', 'tk.Button', ([], {'master': 'window', 'image': 'facedetect_Mainbutton', 'command': 'facedetect', 'background': '"""#7FACD6"""', 'activebackground': '"""#7FACD6"""', 'borderwidth': '(0)'}), "(master=window, image=facedetect_Mainbutton, command=facedetect,\n background='#7FACD6', activebackground='#7FACD6', borderwidth=0)\n", (10119, 10252), True, 'import tkinter as tk\n'), ((10363, 10376), 'tkinter.Toplevel', 'tk.Toplevel', ([], {}), '()\n', (10374, 10376), True, 'import tkinter as tk\n'), ((10586, 10625), 'tkinter.Label', 'tk.Label', ([], {'master': 'new_tab', 'borderwidth': '(0)'}), '(master=new_tab, borderwidth=0)\n', (10594, 10625), True, 'import tkinter as tk\n'), ((10638, 10690), 'tkinter.Label', 'tk.Label', ([], {'master': 'window', 'bg': '"""#7FACD6"""', 'borderwidth': '(0)'}), "(master=window, bg='#7FACD6', borderwidth=0)\n", (10646, 10690), True, 'import tkinter as tk\n'), ((10701, 10778), 'tkinter.Entry', 'tk.Entry', ([], {'master': 'window', 'borderwidth': '(1)', 'width': '(16)', 'relief': 'SUNKEN', 'fg': '"""#6E3CBC"""'}), "(master=window, borderwidth=1, width=16, relief=SUNKEN, fg='#6E3CBC')\n", (10709, 10778), True, 'import tkinter as tk\n'), ((10788, 10929), 'tkinter.Button', 'tk.Button', ([], {'master': 'window', 'command': 'save_file', 'bg': '"""#B8E4F0"""', 'activebackground': '"""#B8E4F0"""', 'text': '"""เธšเธฑเธ™เธ—เธถเธเธฃเธนเธ›เธ เธฒเธž"""', 'relief': 'RAISED', 'borderwidth': '(1)'}), "(master=window, command=save_file, bg='#B8E4F0', activebackground=\n '#B8E4F0', text='เธšเธฑเธ™เธ—เธถเธเธฃเธนเธ›เธ เธฒเธž', relief=RAISED, borderwidth=1)\n", (10797, 10929), True, 'import tkinter as tk\n'), ((10932, 11018), 'tkinter.Label', 'tk.Label', ([], {'master': 'window', 'background': '"""#7FACD6"""', 'foreground': '"""#225140"""', 'borderwidth': '(0)'}), "(master=window, background='#7FACD6', foreground='#225140',\n borderwidth=0)\n", (10940, 11018), True, 'import tkinter as tk\n'), ((3323, 3337), 'collections.deque', 'deque', (['([0] * 5)'], {}), '([0] * 5)\n', (3328, 3337), False, 'from collections import deque\n'), ((3472, 3507), 'cv2.CascadeClassifier', 'cv2.CascadeClassifier', (['cascPathface'], {}), '(cascPathface)\n', (3493, 3507), False, 'import cv2\n'), ((3528, 3563), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0 + cv2.CAP_DSHOW)'], {}), '(0 + cv2.CAP_DSHOW)\n', (3544, 3563), False, 'import cv2\n'), ((5445, 5459), 'collections.deque', 'deque', (['([0] * 5)'], {}), '([0] * 5)\n', (5450, 5459), False, 'from collections import deque\n'), ((5503, 5538), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0 + cv2.CAP_DSHOW)'], {}), '(0 + cv2.CAP_DSHOW)\n', (5519, 5538), False, 'import cv2\n'), ((1512, 1535), 'os.path.exists', 'os.path.exists', (['newpath'], {}), '(newpath)\n', (1526, 1535), False, 'import os\n'), ((1550, 1570), 'os.makedirs', 'os.makedirs', (['newpath'], {}), '(newpath)\n', (1561, 1570), False, 'import os\n'), ((1622, 1635), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (1632, 1635), False, 'import time\n'), ((1689, 1702), 'time.sleep', 'time.sleep', (['(2)'], {}), '(2)\n', (1699, 1702), False, 'import time\n'), ((1751, 1801), 'cv2.imwrite', 'cv2.imwrite', (['f"""./Known/{Name}/{filename}"""', 'capture'], {}), "(f'./Known/{Name}/{filename}', capture)\n", (1762, 1801), False, 'import cv2\n'), ((2334, 2347), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (2344, 2347), False, 'import time\n'), ((2401, 2414), 'time.sleep', 'time.sleep', (['(2)'], {}), '(2)\n', (2411, 2414), False, 'import time\n'), ((3380, 3409), 'os.path.dirname', 'os.path.dirname', (['cv2.__file__'], {}), '(cv2.__file__)\n', (3395, 3409), False, 'import os\n'), ((4009, 4020), 'time.time', 'time.time', ([], {}), '()\n', (4018, 4020), False, 'import time\n'), ((4426, 4465), 'cv2.cvtColor', 'cv2.cvtColor', (['frame', 'cv2.COLOR_BGR2GRAY'], {}), '(frame, cv2.COLOR_BGR2GRAY)\n', (4438, 4465), False, 'import cv2\n'), ((4712, 4726), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (4723, 4726), False, 'import cv2\n'), ((5674, 5693), 'os.listdir', 'os.listdir', (['"""Known"""'], {}), "('Known')\n", (5684, 5693), False, 'import os\n'), ((6638, 6649), 'time.time', 'time.time', ([], {}), '()\n', (6647, 6649), False, 'import time\n'), ((7215, 7253), 'cv2.cvtColor', 'cv2.cvtColor', (['frame', 'cv2.COLOR_BGR2RGB'], {}), '(frame, cv2.COLOR_BGR2RGB)\n', (7227, 7253), False, 'import cv2\n'), ((7277, 7320), 'cv2.resize', 'cv2.resize', (['rgb', '(0, 0)'], {'fx': '(1 / 4)', 'fy': '(1 / 4)'}), '(rgb, (0, 0), fx=1 / 4, fy=1 / 4)\n', (7287, 7320), False, 'import cv2\n'), ((9386, 9400), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (9397, 9400), False, 'import cv2\n'), ((9768, 9837), 'tkinter.Label', 'tk.Label', ([], {'master': 'window', 'text': '"""Face Recognition System"""', 'bg': '"""#7FACD6"""'}), "(master=window, text='Face Recognition System', bg='#7FACD6')\n", (9776, 9837), True, 'import tkinter as tk\n'), ((488, 522), 'PIL.Image.open', 'Image.open', (['"""./Asset/savemain.png"""'], {}), "('./Asset/savemain.png')\n", (498, 522), False, 'from PIL import Image, ImageTk\n'), ((610, 651), 'PIL.Image.open', 'Image.open', (['"""./Asset/savemain_change.png"""'], {}), "('./Asset/savemain_change.png')\n", (620, 651), False, 'from PIL import Image, ImageTk\n'), ((733, 778), 'PIL.Image.open', 'Image.open', (['"""./Asset/facerecognitionmain.png"""'], {}), "('./Asset/facerecognitionmain.png')\n", (743, 778), False, 'from PIL import Image, ImageTk\n'), ((866, 918), 'PIL.Image.open', 'Image.open', (['"""./Asset/facerecognitionmain_change.png"""'], {}), "('./Asset/facerecognitionmain_change.png')\n", (876, 918), False, 'from PIL import Image, ImageTk\n'), ((2022, 2051), 'os.listdir', 'os.listdir', (['f"""./Known/{Name}"""'], {}), "(f'./Known/{Name}')\n", (2032, 2051), False, 'import os\n'), ((2290, 2319), 'os.listdir', 'os.listdir', (['f"""./Known/{Name}"""'], {}), "(f'./Known/{Name}')\n", (2300, 2319), False, 'import os\n'), ((2769, 2798), 'os.listdir', 'os.listdir', (['f"""./Known/{Name}"""'], {}), "(f'./Known/{Name}')\n", (2779, 2798), False, 'import os\n'), ((4642, 4702), 'cv2.rectangle', 'cv2.rectangle', (['frame', '(x, y)', '(x + w, y + h)', '(0, 255, 0)', '(2)'], {}), '(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)\n', (4655, 4702), False, 'import cv2\n'), ((5724, 5751), 'os.listdir', 'os.listdir', (['f"""Known/{name}"""'], {}), "(f'Known/{name}')\n", (5734, 5751), False, 'import os\n'), ((7361, 7405), 'face_recognition.face_locations', 'face_recognition.face_locations', (['small_frame'], {}), '(small_frame)\n', (7392, 7405), False, 'import face_recognition\n'), ((7436, 7496), 'face_recognition.face_encodings', 'face_recognition.face_encodings', (['small_frame', 'face_locations'], {}), '(small_frame, face_locations)\n', (7467, 7496), False, 'import face_recognition\n'), ((5778, 5838), 'face_recognition.load_image_file', 'face_recognition.load_image_file', (['f"""Known/{name}/{filename}"""'], {}), "(f'Known/{name}/{filename}')\n", (5810, 5838), False, 'import face_recognition\n'), ((5872, 5910), 'face_recognition.face_encodings', 'face_recognition.face_encodings', (['image'], {}), '(image)\n', (5903, 5910), False, 'import face_recognition\n'), ((7572, 7625), 'face_recognition.face_distance', 'face_recognition.face_distance', (['known_faces', 'encoding'], {}), '(known_faces, encoding)\n', (7602, 7625), False, 'import face_recognition\n'), ((7655, 7679), 'numpy.argmin', 'np.argmin', (['face_distance'], {}), '(face_distance)\n', (7664, 7679), True, 'import numpy as np\n'), ((8459, 8549), 'cv2.rectangle', 'cv2.rectangle', (['frame', '(LEFT * 4, TOP * 4)', '(RIGHT * 4, BOTTOM * 4)', 'color_rectangle', '(2)'], {}), '(frame, (LEFT * 4, TOP * 4), (RIGHT * 4, BOTTOM * 4),\n color_rectangle, 2)\n', (8472, 8549), False, 'import cv2\n'), ((8554, 8652), 'cv2.putText', 'cv2.putText', (['frame', 'name', '(LEFT * 4, TOP * 4)', 'cv2.FONT_HERSHEY_COMPLEX', '(1)', '(255, 255, 255)', '(2)'], {}), '(frame, name, (LEFT * 4, TOP * 4), cv2.FONT_HERSHEY_COMPLEX, 1,\n (255, 255, 255), 2)\n', (8565, 8652), False, 'import cv2\n'), ((8824, 8868), 'face_recognition.face_locations', 'face_recognition.face_locations', (['small_frame'], {}), '(small_frame)\n', (8855, 8868), False, 'import face_recognition\n'), ((4790, 4833), 'cv2.resize', 'cv2.resize', (['frame', '(0, 0)'], {'fx': '(1.35)', 'fy': '(1.35)'}), '(frame, (0, 0), fx=1.35, fy=1.35)\n', (4800, 4833), False, 'import cv2\n'), ((9068, 9158), 'cv2.rectangle', 'cv2.rectangle', (['frame', '(LEFT * 4, TOP * 4)', '(RIGHT * 4, BOTTOM * 4)', 'color_rectangle', '(2)'], {}), '(frame, (LEFT * 4, TOP * 4), (RIGHT * 4, BOTTOM * 4),\n color_rectangle, 2)\n', (9081, 9158), False, 'import cv2\n'), ((9163, 9261), 'cv2.putText', 'cv2.putText', (['frame', 'name', '(LEFT * 4, TOP * 4)', 'cv2.FONT_HERSHEY_COMPLEX', '(1)', '(255, 255, 255)', '(2)'], {}), '(frame, name, (LEFT * 4, TOP * 4), cv2.FONT_HERSHEY_COMPLEX, 1,\n (255, 255, 255), 2)\n', (9174, 9261), False, 'import cv2\n'), ((9270, 9393), 'cv2.putText', 'cv2.putText', (['frame', "('Matches ' + '0' + ' %')", '(LEFT * 4, BOTTOM * 4 + 16)', 'cv2.FONT_HERSHEY_COMPLEX', '(0.5)', 'color_Match', '(1)'], {}), "(frame, 'Matches ' + '0' + ' %', (LEFT * 4, BOTTOM * 4 + 16),\n cv2.FONT_HERSHEY_COMPLEX, 0.5, color_Match, 1)\n", (9281, 9393), False, 'import cv2\n'), ((9464, 9507), 'cv2.resize', 'cv2.resize', (['frame', '(0, 0)'], {'fx': '(1.35)', 'fy': '(1.35)'}), '(frame, (0, 0), fx=1.35, fy=1.35)\n', (9474, 9507), False, 'import cv2\n')]
import numpy as np import cv2 as cv import cmath #cap = cv.VideoCapture(0) cap = cv.VideoCapture('udpsrc port=5004 ! application/x-rtp,encoding-name=H264,payload=96 ! rtph264depay ! avdec_h264 ! videoconvert ! appsink', cv.CAP_GSTREAMER) PI = 3.14159 while(1): # read the video capture frame _, frame = cap.read() #cv.imshow('frame',frame) #break # blur for better edge finding blur = cv.GaussianBlur(frame,(5,5),0) frameGray = cv.cvtColor(blur, cv.COLOR_BGR2GRAY) # create threshold for edge finding ret, thresh = cv.threshold(frameGray, 120, 255, cv.THRESH_BINARY) contours, _ = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_NONE) count = 0 tri = 0 sqr = 0 rect = 0 circ = 0 for contour in contours: area = cv.contourArea(contour) if area > 1000 and area < 30000: M = cv.moments(contour) cX = int(M["m10"]/M["m00"]) cY = int(M["m01"]/M["m00"]) if(frame[cY,cX][0] < 50 and frame[cY,cX][1] < 50 and frame[cY,cX][2] < 50): cv.circle(frame, (cX,cY), 7, (255,255,0), -1) #cv.drawContours(frame, contour, -1, (0,255,0), 3) count += 1 (x,y), (MA, ma), angle = cv.fitEllipse(contour) areaEllipse = PI/4 * MA * ma if(abs(areaEllipse - area) < 100): #is circle circ += 1 cv.drawContours(frame, contour, -1, (0,255,255), 3) else: ((x,y), (w,h), rot) = cv.minAreaRect(contour) if(float(w) > 0.0 and float(h) > 0.0): ratio = w / float(h) #font = cv.FONT_HERSHEY_COMPLEX_SMALL #cv.putText(frame, str(ratio), (cX, cY - 40), font, 2, (0, 0, 255), 2, cv.LINE_AA) if ratio <= 0.6 or ratio >= 2.8: #is rect cv.drawContours(frame, contour, -1, (0,255,0), 3) rect += 1 else: #peri = cv.arcLength(contour, True) #approx = cv.approxPolyDP(contour, 0.04 * peri, True) #if len(approx) == 3: areaAdj = 1400 #font = cv.FONT_HERSHEY_COMPLEX_SMALL #cv.putText(frame, str(int(area)), (cX, cY - 40), font, 2, (0, 0, 255), 2, cv.LINE_AA) #cv.putText(frame, str(int(w*h/2)), (cX, cY - 60), font, 2, (0, 0, 255), 2, cv.LINE_AA) if(w*h/2 > area - areaAdj and w*h/2 < area + areaAdj): #is triangle cv.drawContours(frame, contour, -1, (255,0,0), 3) tri += 1 else: #is square sqr += 1 cv.drawContours(frame, contour, -1, (0,0,255), 3) cv.circle(frame, (70, 300), 20, (0,0,255), -1) pts = np.array([[70, 330], [50, 360], [90, 360]], np.int32) pts = pts.reshape((-1,1,2)) cv.fillPoly(frame, [pts], (0, 0, 255)) cv.rectangle(frame, (50, 381), (90, 389), (0,0,255), -1) cv.rectangle(frame, (50, 410), (90, 450), (0,0,255), -1) font = cv.FONT_HERSHEY_COMPLEX_SMALL cv.putText(frame, str(circ), (10, 310), font, 2, (0, 0, 255), 2, cv.LINE_AA) cv.putText(frame, str(tri), (10, 355), font, 2, (0, 0, 255), 2, cv.LINE_AA) cv.putText(frame, str(rect), (10, 400), font, 2, (0, 0, 255), 2, cv.LINE_AA) cv.putText(frame, str(sqr), (10, 445), font, 2, (0, 0, 255), 2, cv.LINE_AA) cv.imshow('frame',frame) #cv.imshow('thresh', thresh) k = cv.waitKey(5) & 0xFF if k == 27: break cv.destroyAllWindows() cap.release()
[ "cv2.minAreaRect", "cv2.GaussianBlur", "cv2.contourArea", "cv2.circle", "cv2.cvtColor", "cv2.waitKey", "cv2.threshold", "cv2.moments", "cv2.imshow", "cv2.fillPoly", "cv2.VideoCapture", "cv2.fitEllipse", "numpy.array", "cv2.rectangle", "cv2.drawContours", "cv2.destroyAllWindows", "cv2...
[((82, 248), 'cv2.VideoCapture', 'cv.VideoCapture', (['"""udpsrc port=5004 ! application/x-rtp,encoding-name=H264,payload=96 ! rtph264depay ! avdec_h264 ! videoconvert ! appsink"""', 'cv.CAP_GSTREAMER'], {}), "(\n 'udpsrc port=5004 ! application/x-rtp,encoding-name=H264,payload=96 ! rtph264depay ! avdec_h264 ! videoconvert ! appsink'\n , cv.CAP_GSTREAMER)\n", (97, 248), True, 'import cv2 as cv\n'), ((4034, 4056), 'cv2.destroyAllWindows', 'cv.destroyAllWindows', ([], {}), '()\n', (4054, 4056), True, 'import cv2 as cv\n'), ((421, 454), 'cv2.GaussianBlur', 'cv.GaussianBlur', (['frame', '(5, 5)', '(0)'], {}), '(frame, (5, 5), 0)\n', (436, 454), True, 'import cv2 as cv\n'), ((468, 504), 'cv2.cvtColor', 'cv.cvtColor', (['blur', 'cv.COLOR_BGR2GRAY'], {}), '(blur, cv.COLOR_BGR2GRAY)\n', (479, 504), True, 'import cv2 as cv\n'), ((563, 614), 'cv2.threshold', 'cv.threshold', (['frameGray', '(120)', '(255)', 'cv.THRESH_BINARY'], {}), '(frameGray, 120, 255, cv.THRESH_BINARY)\n', (575, 614), True, 'import cv2 as cv\n'), ((633, 692), 'cv2.findContours', 'cv.findContours', (['thresh', 'cv.RETR_TREE', 'cv.CHAIN_APPROX_NONE'], {}), '(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_NONE)\n', (648, 692), True, 'import cv2 as cv\n'), ((3239, 3287), 'cv2.circle', 'cv.circle', (['frame', '(70, 300)', '(20)', '(0, 0, 255)', '(-1)'], {}), '(frame, (70, 300), 20, (0, 0, 255), -1)\n', (3248, 3287), True, 'import cv2 as cv\n'), ((3296, 3349), 'numpy.array', 'np.array', (['[[70, 330], [50, 360], [90, 360]]', 'np.int32'], {}), '([[70, 330], [50, 360], [90, 360]], np.int32)\n', (3304, 3349), True, 'import numpy as np\n'), ((3386, 3424), 'cv2.fillPoly', 'cv.fillPoly', (['frame', '[pts]', '(0, 0, 255)'], {}), '(frame, [pts], (0, 0, 255))\n', (3397, 3424), True, 'import cv2 as cv\n'), ((3429, 3487), 'cv2.rectangle', 'cv.rectangle', (['frame', '(50, 381)', '(90, 389)', '(0, 0, 255)', '(-1)'], {}), '(frame, (50, 381), (90, 389), (0, 0, 255), -1)\n', (3441, 3487), True, 'import cv2 as cv\n'), ((3490, 3548), 'cv2.rectangle', 'cv.rectangle', (['frame', '(50, 410)', '(90, 450)', '(0, 0, 255)', '(-1)'], {}), '(frame, (50, 410), (90, 450), (0, 0, 255), -1)\n', (3502, 3548), True, 'import cv2 as cv\n'), ((3915, 3940), 'cv2.imshow', 'cv.imshow', (['"""frame"""', 'frame'], {}), "('frame', frame)\n", (3924, 3940), True, 'import cv2 as cv\n'), ((802, 825), 'cv2.contourArea', 'cv.contourArea', (['contour'], {}), '(contour)\n', (816, 825), True, 'import cv2 as cv\n'), ((3982, 3995), 'cv2.waitKey', 'cv.waitKey', (['(5)'], {}), '(5)\n', (3992, 3995), True, 'import cv2 as cv\n'), ((883, 902), 'cv2.moments', 'cv.moments', (['contour'], {}), '(contour)\n', (893, 902), True, 'import cv2 as cv\n'), ((1087, 1135), 'cv2.circle', 'cv.circle', (['frame', '(cX, cY)', '(7)', '(255, 255, 0)', '(-1)'], {}), '(frame, (cX, cY), 7, (255, 255, 0), -1)\n', (1096, 1135), True, 'import cv2 as cv\n'), ((1285, 1307), 'cv2.fitEllipse', 'cv.fitEllipse', (['contour'], {}), '(contour)\n', (1298, 1307), True, 'import cv2 as cv\n'), ((1485, 1538), 'cv2.drawContours', 'cv.drawContours', (['frame', 'contour', '(-1)', '(0, 255, 255)', '(3)'], {}), '(frame, contour, -1, (0, 255, 255), 3)\n', (1500, 1538), True, 'import cv2 as cv\n'), ((1601, 1624), 'cv2.minAreaRect', 'cv.minAreaRect', (['contour'], {}), '(contour)\n', (1615, 1624), True, 'import cv2 as cv\n'), ((2046, 2097), 'cv2.drawContours', 'cv.drawContours', (['frame', 'contour', '(-1)', '(0, 255, 0)', '(3)'], {}), '(frame, contour, -1, (0, 255, 0), 3)\n', (2061, 2097), True, 'import cv2 as cv\n'), ((2943, 2994), 'cv2.drawContours', 'cv.drawContours', (['frame', 'contour', '(-1)', '(255, 0, 0)', '(3)'], {}), '(frame, contour, -1, (255, 0, 0), 3)\n', (2958, 2994), True, 'import cv2 as cv\n'), ((3184, 3235), 'cv2.drawContours', 'cv.drawContours', (['frame', 'contour', '(-1)', '(0, 0, 255)', '(3)'], {}), '(frame, contour, -1, (0, 0, 255), 3)\n', (3199, 3235), True, 'import cv2 as cv\n')]
import sys import sysconfig import warnings import numpy as nu import ctypes import ctypes.util from numpy.ctypeslib import ndpointer import os from galpy import potential from galpy.util import galpyWarning from galpy.orbit_src.integratePlanarOrbit import _parse_integrator, _parse_tol #Find and load the library _lib= None outerr= None PY3= sys.version > '3' if PY3: #pragma: no cover _ext_suffix= sysconfig.get_config_var('EXT_SUFFIX') else: _ext_suffix= '.so' for path in sys.path: try: _lib = ctypes.CDLL(os.path.join(path,'galpy_integrate_c%s' % _ext_suffix)) except OSError as e: if os.path.exists(os.path.join(path,'galpy_integrate_c%s' % _ext_suffix)): #pragma: no cover outerr= e _lib = None else: break if _lib is None: #pragma: no cover if not outerr is None: warnings.warn("integrateFullOrbit_c extension module not loaded, because of error '%s' " % outerr, galpyWarning) else: warnings.warn("integrateFullOrbit_c extension module not loaded, because galpy_integrate_c%s image was not found" % _ext_suffix, galpyWarning) _ext_loaded= False else: _ext_loaded= True def _parse_pot(pot,potforactions=False): """Parse the potential so it can be fed to C""" #Figure out what's in pot if not isinstance(pot,list): pot= [pot] #Initialize everything pot_type= [] pot_args= [] npot= len(pot) for p in pot: if isinstance(p,potential.LogarithmicHaloPotential): pot_type.append(0) pot_args.extend([p._amp,p._q,p._core2]) elif isinstance(p,potential.MiyamotoNagaiPotential): pot_type.append(5) pot_args.extend([p._amp,p._a,p._b]) elif isinstance(p,potential.PowerSphericalPotential): pot_type.append(7) pot_args.extend([p._amp,p.alpha]) elif isinstance(p,potential.HernquistPotential): pot_type.append(8) pot_args.extend([p._amp,p.a]) elif isinstance(p,potential.FlattenedNFWPotential): pot_type.append(91) pot_args.extend([p._amp,p.a,p.q]) elif isinstance(p,potential.NFWPotential): pot_type.append(9) pot_args.extend([p._amp,p.a]) elif isinstance(p,potential.JaffePotential): pot_type.append(10) pot_args.extend([p._amp,p.a]) elif isinstance(p,potential.DoubleExponentialDiskPotential): pot_type.append(11) pot_args.extend([p._amp,p._alpha,p._beta,p._kmaxFac, p._nzeros,p._glorder]) pot_args.extend([p._glx[ii] for ii in range(p._glorder)]) pot_args.extend([p._glw[ii] for ii in range(p._glorder)]) pot_args.extend([p._j0zeros[ii] for ii in range(p._nzeros+1)]) pot_args.extend([p._dj0zeros[ii] for ii in range(p._nzeros+1)]) pot_args.extend([p._j1zeros[ii] for ii in range(p._nzeros+1)]) pot_args.extend([p._dj1zeros[ii] for ii in range(p._nzeros+1)]) pot_args.extend([p._kp._amp,p._kp.alpha]) elif isinstance(p,potential.FlattenedPowerPotential): pot_type.append(12) pot_args.extend([p._amp,p.alpha,p.q2,p.core2]) elif isinstance(p,potential.interpRZPotential): pot_type.append(13) pot_args.extend([len(p._rgrid),len(p._zgrid)]) if p._logR: pot_args.extend([p._logrgrid[ii] for ii in range(len(p._rgrid))]) else: pot_args.extend([p._rgrid[ii] for ii in range(len(p._rgrid))]) pot_args.extend([p._zgrid[ii] for ii in range(len(p._zgrid))]) if potforactions: pot_args.extend([x for x in p._potGrid_splinecoeffs.flatten(order='C')]) else: pot_args.extend([x for x in p._rforceGrid_splinecoeffs.flatten(order='C')]) pot_args.extend([x for x in p._zforceGrid_splinecoeffs.flatten(order='C')]) pot_args.extend([p._amp,int(p._logR)]) elif isinstance(p,potential.IsochronePotential): pot_type.append(14) pot_args.extend([p._amp,p.b]) elif isinstance(p,potential.PowerSphericalPotentialwCutoff): pot_type.append(15) pot_args.extend([p._amp,p.alpha,p.rc]) elif isinstance(p,potential.MN3ExponentialDiskPotential): # Three Miyamoto-Nagai disks npot+= 2 pot_type.extend([5,5,5]) pot_args.extend([p._amp*p._mn3[0]._amp, p._mn3[0]._a,p._mn3[0]._b, p._amp*p._mn3[1]._amp, p._mn3[1]._a,p._mn3[1]._b, p._amp*p._mn3[2]._amp, p._mn3[2]._a,p._mn3[2]._b]) elif isinstance(p,potential.KuzminKutuzovStaeckelPotential): pot_type.append(16) pot_args.extend([p._amp,p._ac,p._Delta]) elif isinstance(p,potential.PlummerPotential): pot_type.append(17) pot_args.extend([p._amp,p._b]) elif isinstance(p,potential.PseudoIsothermalPotential): pot_type.append(18) pot_args.extend([p._amp,p._a]) pot_type= nu.array(pot_type,dtype=nu.int32,order='C') pot_args= nu.array(pot_args,dtype=nu.float64,order='C') return (npot,pot_type,pot_args) def integrateFullOrbit_c(pot,yo,t,int_method,rtol=None,atol=None,dt=None): """ NAME: integrateFullOrbit_c PURPOSE: C integrate an ode for a FullOrbit INPUT: pot - Potential or list of such instances yo - initial condition [q,p] t - set of times at which one wants the result int_method= 'leapfrog_c', 'rk4_c', 'rk6_c', 'symplec4_c' rtol, atol dt= (None) force integrator to use this stepsize (default is to automatically determine one)) OUTPUT: (y,err) y : array, shape (len(y0), len(t)) Array containing the value of y for each desired time in t, \ with the initial value y0 in the first row. err: error message, if not zero: 1 means maximum step reduction happened for adaptive integrators HISTORY: 2011-11-13 - Written - Bovy (IAS) """ rtol, atol= _parse_tol(rtol,atol) npot, pot_type, pot_args= _parse_pot(pot) int_method_c= _parse_integrator(int_method) if dt is None: dt= -9999.99 #Set up result array result= nu.empty((len(t),6)) err= ctypes.c_int(0) #Set up the C code ndarrayFlags= ('C_CONTIGUOUS','WRITEABLE') integrationFunc= _lib.integrateFullOrbit integrationFunc.argtypes= [ndpointer(dtype=nu.float64,flags=ndarrayFlags), ctypes.c_int, ndpointer(dtype=nu.float64,flags=ndarrayFlags), ctypes.c_int, ndpointer(dtype=nu.int32,flags=ndarrayFlags), ndpointer(dtype=nu.float64,flags=ndarrayFlags), ctypes.c_double, ctypes.c_double, ctypes.c_double, ndpointer(dtype=nu.float64,flags=ndarrayFlags), ctypes.POINTER(ctypes.c_int), ctypes.c_int] #Array requirements, first store old order f_cont= [yo.flags['F_CONTIGUOUS'], t.flags['F_CONTIGUOUS']] yo= nu.require(yo,dtype=nu.float64,requirements=['C','W']) t= nu.require(t,dtype=nu.float64,requirements=['C','W']) result= nu.require(result,dtype=nu.float64,requirements=['C','W']) #Run the C code integrationFunc(yo, ctypes.c_int(len(t)), t, ctypes.c_int(npot), pot_type, pot_args, ctypes.c_double(dt), ctypes.c_double(rtol),ctypes.c_double(atol), result, ctypes.byref(err), ctypes.c_int(int_method_c)) #Reset input arrays if f_cont[0]: yo= nu.asfortranarray(yo) if f_cont[1]: t= nu.asfortranarray(t) return (result,err.value) def integrateFullOrbit_dxdv_c(pot,yo,dyo,t,int_method,rtol=None,atol=None): #pragma: no cover because not included in v1, uncover when included """ NAME: integrateFullOrbit_dxdv_c PURPOSE: C integrate an ode for a planarOrbit+phase space volume dxdv INPUT: pot - Potential or list of such instances yo - initial condition [q,p] dyo - initial condition [dq,dp] t - set of times at which one wants the result int_method= 'leapfrog_c', 'rk4_c', 'rk6_c', 'symplec4_c' rtol, atol OUTPUT: (y,err) y : array, shape (len(y0), len(t)) Array containing the value of y for each desired time in t, \ with the initial value y0 in the first row. err: error message if not zero, 1: maximum step reduction happened for adaptive integrators HISTORY: 2011-11-13 - Written - Bovy (IAS) """ rtol, atol= _parse_tol(rtol,atol) npot, pot_type, pot_args= _parse_pot(pot) int_method_c= _parse_integrator(int_method) yo= nu.concatenate((yo,dyo)) #Set up result array result= nu.empty((len(t),12)) err= ctypes.c_int(0) #Set up the C code ndarrayFlags= ('C_CONTIGUOUS','WRITEABLE') integrationFunc= _lib.integrateFullOrbit_dxdv integrationFunc.argtypes= [ndpointer(dtype=nu.float64,flags=ndarrayFlags), ctypes.c_int, ndpointer(dtype=nu.float64,flags=ndarrayFlags), ctypes.c_int, ndpointer(dtype=nu.int32,flags=ndarrayFlags), ndpointer(dtype=nu.float64,flags=ndarrayFlags), ctypes.c_double, ctypes.c_double, ndpointer(dtype=nu.float64,flags=ndarrayFlags), ctypes.POINTER(ctypes.c_int), ctypes.c_int] #Array requirements, first store old order f_cont= [yo.flags['F_CONTIGUOUS'], t.flags['F_CONTIGUOUS']] yo= nu.require(yo,dtype=nu.float64,requirements=['C','W']) t= nu.require(t,dtype=nu.float64,requirements=['C','W']) result= nu.require(result,dtype=nu.float64,requirements=['C','W']) #Run the C code integrationFunc(yo, ctypes.c_int(len(t)), t, ctypes.c_int(npot), pot_type, pot_args, ctypes.c_double(rtol),ctypes.c_double(atol), result, ctypes.byref(err), ctypes.c_int(int_method_c)) #Reset input arrays if f_cont[0]: yo= nu.asfortranarray(yo) if f_cont[1]: t= nu.asfortranarray(t) return (result,err.value)
[ "numpy.ctypeslib.ndpointer", "ctypes.c_int", "ctypes.c_double", "galpy.orbit_src.integratePlanarOrbit._parse_tol", "ctypes.byref", "sysconfig.get_config_var", "numpy.asfortranarray", "numpy.require", "numpy.array", "warnings.warn", "galpy.orbit_src.integratePlanarOrbit._parse_integrator", "os....
[((404, 442), 'sysconfig.get_config_var', 'sysconfig.get_config_var', (['"""EXT_SUFFIX"""'], {}), "('EXT_SUFFIX')\n", (428, 442), False, 'import sysconfig\n'), ((5307, 5352), 'numpy.array', 'nu.array', (['pot_type'], {'dtype': 'nu.int32', 'order': '"""C"""'}), "(pot_type, dtype=nu.int32, order='C')\n", (5315, 5352), True, 'import numpy as nu\n'), ((5365, 5412), 'numpy.array', 'nu.array', (['pot_args'], {'dtype': 'nu.float64', 'order': '"""C"""'}), "(pot_args, dtype=nu.float64, order='C')\n", (5373, 5412), True, 'import numpy as nu\n'), ((6329, 6351), 'galpy.orbit_src.integratePlanarOrbit._parse_tol', '_parse_tol', (['rtol', 'atol'], {}), '(rtol, atol)\n', (6339, 6351), False, 'from galpy.orbit_src.integratePlanarOrbit import _parse_integrator, _parse_tol\n'), ((6415, 6444), 'galpy.orbit_src.integratePlanarOrbit._parse_integrator', '_parse_integrator', (['int_method'], {}), '(int_method)\n', (6432, 6444), False, 'from galpy.orbit_src.integratePlanarOrbit import _parse_integrator, _parse_tol\n'), ((6554, 6569), 'ctypes.c_int', 'ctypes.c_int', (['(0)'], {}), '(0)\n', (6566, 6569), False, 'import ctypes\n'), ((7581, 7638), 'numpy.require', 'nu.require', (['yo'], {'dtype': 'nu.float64', 'requirements': "['C', 'W']"}), "(yo, dtype=nu.float64, requirements=['C', 'W'])\n", (7591, 7638), True, 'import numpy as nu\n'), ((7643, 7699), 'numpy.require', 'nu.require', (['t'], {'dtype': 'nu.float64', 'requirements': "['C', 'W']"}), "(t, dtype=nu.float64, requirements=['C', 'W'])\n", (7653, 7699), True, 'import numpy as nu\n'), ((7709, 7770), 'numpy.require', 'nu.require', (['result'], {'dtype': 'nu.float64', 'requirements': "['C', 'W']"}), "(result, dtype=nu.float64, requirements=['C', 'W'])\n", (7719, 7770), True, 'import numpy as nu\n'), ((9255, 9277), 'galpy.orbit_src.integratePlanarOrbit._parse_tol', '_parse_tol', (['rtol', 'atol'], {}), '(rtol, atol)\n', (9265, 9277), False, 'from galpy.orbit_src.integratePlanarOrbit import _parse_integrator, _parse_tol\n'), ((9341, 9370), 'galpy.orbit_src.integratePlanarOrbit._parse_integrator', '_parse_integrator', (['int_method'], {}), '(int_method)\n', (9358, 9370), False, 'from galpy.orbit_src.integratePlanarOrbit import _parse_integrator, _parse_tol\n'), ((9379, 9404), 'numpy.concatenate', 'nu.concatenate', (['(yo, dyo)'], {}), '((yo, dyo))\n', (9393, 9404), True, 'import numpy as nu\n'), ((9473, 9488), 'ctypes.c_int', 'ctypes.c_int', (['(0)'], {}), '(0)\n', (9485, 9488), False, 'import ctypes\n'), ((10457, 10514), 'numpy.require', 'nu.require', (['yo'], {'dtype': 'nu.float64', 'requirements': "['C', 'W']"}), "(yo, dtype=nu.float64, requirements=['C', 'W'])\n", (10467, 10514), True, 'import numpy as nu\n'), ((10519, 10575), 'numpy.require', 'nu.require', (['t'], {'dtype': 'nu.float64', 'requirements': "['C', 'W']"}), "(t, dtype=nu.float64, requirements=['C', 'W'])\n", (10529, 10575), True, 'import numpy as nu\n'), ((10585, 10646), 'numpy.require', 'nu.require', (['result'], {'dtype': 'nu.float64', 'requirements': "['C', 'W']"}), "(result, dtype=nu.float64, requirements=['C', 'W'])\n", (10595, 10646), True, 'import numpy as nu\n'), ((848, 970), 'warnings.warn', 'warnings.warn', (['("integrateFullOrbit_c extension module not loaded, because of error \'%s\' " %\n outerr)', 'galpyWarning'], {}), '(\n "integrateFullOrbit_c extension module not loaded, because of error \'%s\' "\n % outerr, galpyWarning)\n', (861, 970), False, 'import warnings\n'), ((1001, 1153), 'warnings.warn', 'warnings.warn', (["('integrateFullOrbit_c extension module not loaded, because galpy_integrate_c%s image was not found'\n % _ext_suffix)", 'galpyWarning'], {}), "(\n 'integrateFullOrbit_c extension module not loaded, because galpy_integrate_c%s image was not found'\n % _ext_suffix, galpyWarning)\n", (1014, 1153), False, 'import warnings\n'), ((6717, 6764), 'numpy.ctypeslib.ndpointer', 'ndpointer', ([], {'dtype': 'nu.float64', 'flags': 'ndarrayFlags'}), '(dtype=nu.float64, flags=ndarrayFlags)\n', (6726, 6764), False, 'from numpy.ctypeslib import ndpointer\n'), ((6870, 6917), 'numpy.ctypeslib.ndpointer', 'ndpointer', ([], {'dtype': 'nu.float64', 'flags': 'ndarrayFlags'}), '(dtype=nu.float64, flags=ndarrayFlags)\n', (6879, 6917), False, 'from numpy.ctypeslib import ndpointer\n'), ((6994, 7039), 'numpy.ctypeslib.ndpointer', 'ndpointer', ([], {'dtype': 'nu.int32', 'flags': 'ndarrayFlags'}), '(dtype=nu.int32, flags=ndarrayFlags)\n', (7003, 7039), False, 'from numpy.ctypeslib import ndpointer\n'), ((7071, 7118), 'numpy.ctypeslib.ndpointer', 'ndpointer', ([], {'dtype': 'nu.float64', 'flags': 'ndarrayFlags'}), '(dtype=nu.float64, flags=ndarrayFlags)\n', (7080, 7118), False, 'from numpy.ctypeslib import ndpointer\n'), ((7294, 7341), 'numpy.ctypeslib.ndpointer', 'ndpointer', ([], {'dtype': 'nu.float64', 'flags': 'ndarrayFlags'}), '(dtype=nu.float64, flags=ndarrayFlags)\n', (7303, 7341), False, 'from numpy.ctypeslib import ndpointer\n'), ((7373, 7401), 'ctypes.POINTER', 'ctypes.POINTER', (['ctypes.c_int'], {}), '(ctypes.c_int)\n', (7387, 7401), False, 'import ctypes\n'), ((7898, 7916), 'ctypes.c_int', 'ctypes.c_int', (['npot'], {}), '(npot)\n', (7910, 7916), False, 'import ctypes\n'), ((7998, 8017), 'ctypes.c_double', 'ctypes.c_double', (['dt'], {}), '(dt)\n', (8013, 8017), False, 'import ctypes\n'), ((8039, 8060), 'ctypes.c_double', 'ctypes.c_double', (['rtol'], {}), '(rtol)\n', (8054, 8060), False, 'import ctypes\n'), ((8061, 8082), 'ctypes.c_double', 'ctypes.c_double', (['atol'], {}), '(atol)\n', (8076, 8082), False, 'import ctypes\n'), ((8132, 8149), 'ctypes.byref', 'ctypes.byref', (['err'], {}), '(err)\n', (8144, 8149), False, 'import ctypes\n'), ((8171, 8197), 'ctypes.c_int', 'ctypes.c_int', (['int_method_c'], {}), '(int_method_c)\n', (8183, 8197), False, 'import ctypes\n'), ((8246, 8267), 'numpy.asfortranarray', 'nu.asfortranarray', (['yo'], {}), '(yo)\n', (8263, 8267), True, 'import numpy as nu\n'), ((8289, 8309), 'numpy.asfortranarray', 'nu.asfortranarray', (['t'], {}), '(t)\n', (8306, 8309), True, 'import numpy as nu\n'), ((9641, 9688), 'numpy.ctypeslib.ndpointer', 'ndpointer', ([], {'dtype': 'nu.float64', 'flags': 'ndarrayFlags'}), '(dtype=nu.float64, flags=ndarrayFlags)\n', (9650, 9688), False, 'from numpy.ctypeslib import ndpointer\n'), ((9794, 9841), 'numpy.ctypeslib.ndpointer', 'ndpointer', ([], {'dtype': 'nu.float64', 'flags': 'ndarrayFlags'}), '(dtype=nu.float64, flags=ndarrayFlags)\n', (9803, 9841), False, 'from numpy.ctypeslib import ndpointer\n'), ((9918, 9963), 'numpy.ctypeslib.ndpointer', 'ndpointer', ([], {'dtype': 'nu.int32', 'flags': 'ndarrayFlags'}), '(dtype=nu.int32, flags=ndarrayFlags)\n', (9927, 9963), False, 'from numpy.ctypeslib import ndpointer\n'), ((9995, 10042), 'numpy.ctypeslib.ndpointer', 'ndpointer', ([], {'dtype': 'nu.float64', 'flags': 'ndarrayFlags'}), '(dtype=nu.float64, flags=ndarrayFlags)\n', (10004, 10042), False, 'from numpy.ctypeslib import ndpointer\n'), ((10170, 10217), 'numpy.ctypeslib.ndpointer', 'ndpointer', ([], {'dtype': 'nu.float64', 'flags': 'ndarrayFlags'}), '(dtype=nu.float64, flags=ndarrayFlags)\n', (10179, 10217), False, 'from numpy.ctypeslib import ndpointer\n'), ((10249, 10277), 'ctypes.POINTER', 'ctypes.POINTER', (['ctypes.c_int'], {}), '(ctypes.c_int)\n', (10263, 10277), False, 'import ctypes\n'), ((10774, 10792), 'ctypes.c_int', 'ctypes.c_int', (['npot'], {}), '(npot)\n', (10786, 10792), False, 'import ctypes\n'), ((10874, 10895), 'ctypes.c_double', 'ctypes.c_double', (['rtol'], {}), '(rtol)\n', (10889, 10895), False, 'import ctypes\n'), ((10896, 10917), 'ctypes.c_double', 'ctypes.c_double', (['atol'], {}), '(atol)\n', (10911, 10917), False, 'import ctypes\n'), ((10967, 10984), 'ctypes.byref', 'ctypes.byref', (['err'], {}), '(err)\n', (10979, 10984), False, 'import ctypes\n'), ((11006, 11032), 'ctypes.c_int', 'ctypes.c_int', (['int_method_c'], {}), '(int_method_c)\n', (11018, 11032), False, 'import ctypes\n'), ((11081, 11102), 'numpy.asfortranarray', 'nu.asfortranarray', (['yo'], {}), '(yo)\n', (11098, 11102), True, 'import numpy as nu\n'), ((11124, 11144), 'numpy.asfortranarray', 'nu.asfortranarray', (['t'], {}), '(t)\n', (11141, 11144), True, 'import numpy as nu\n'), ((530, 585), 'os.path.join', 'os.path.join', (['path', "('galpy_integrate_c%s' % _ext_suffix)"], {}), "(path, 'galpy_integrate_c%s' % _ext_suffix)\n", (542, 585), False, 'import os\n'), ((637, 692), 'os.path.join', 'os.path.join', (['path', "('galpy_integrate_c%s' % _ext_suffix)"], {}), "(path, 'galpy_integrate_c%s' % _ext_suffix)\n", (649, 692), False, 'import os\n')]
import numpy as np import pandas as pd from sklearn.preprocessing import LabelBinarizer from sklearn.model_selection import StratifiedKFold from sklearn.preprocessing import StandardScaler from joblib import parallel_backend from multiprocessing import cpu_count import os, gc, joblib from tqdm import tqdm from collections import defaultdict import torch import warnings warnings.filterwarnings('ignore') pd.set_option("display.max_colwidth", 100) pd.set_option("display.max_rows", 20) osj = os.path.join; osl = os.listdir n_cpus = cpu_count() class ViralDataset(torch.utils.data.Dataset): def __init__(self, df: pd.DataFrame, feat_cols: list, mode: str): self.X = df[feat_cols].values # [:,np.newaxis,:] self.mode = mode if mode != 'test': self.targets = df['virality'].values # [:,np.newaxis] # - 1 # assert np.sum(~df['virality'].isin(list(range(5))))==0 def __len__(self): return len(self.X) def __getitem__(self, idx): if self.mode=='test': return torch.tensor(self.X[idx], dtype=torch.float32) else: return (torch.tensor(self.X[idx], dtype=torch.float32), torch.tensor(self.targets[idx], dtype=torch.long)) # long)) class ExtractFeatsDataset(torch.utils.data.Dataset): def __init__(self, df: pd.DataFrame, feat_cols: list, target_cols: list, mode: str): self.X = df[feat_cols].values # [:,np.newaxis,:] # self.target_cols = target_cols self.mode = mode if mode != 'test': if len(target_cols)==1: self.targets = df[target_cols[0]].values # [:,np.newaxis] # - 1 self.target_dtype = torch.long else: self.targets = df[target_cols].values # [:,np.newaxis] # - 1 self.target_dtype = torch.float32 # assert np.sum(~df['virality'].isin(list(range(5))))==0 def __len__(self): return len(self.X) def __getitem__(self, idx): if self.mode=='test': return torch.tensor(self.X[idx], dtype=torch.float32) else: return (torch.tensor(self.X[idx], dtype=torch.float32), torch.tensor(self.targets[idx], dtype=self.target_dtype)) # long)) def to_binary_categories(df, cat_col='tweet_language_id'): df.loc[:, cat_col] = (df[cat_col]!=0).astype(np.int8) return df def freq_encoding(df, freq_cols: list, main_col='tweet_id'): for c in freq_cols: count_df = df.groupby([c])[main_col].count().reset_index() count_df.columns = [c, '{}_freq'.format(c)] df = df.merge(count_df, how='left', on=c) return df def bin_feats(df, feats=[], n_bins_default=20): bin_counts = defaultdict(lambda: n_bins_default) bin_counts['user_tweet_count'] = 20 for feature in feats: if '_binned' in feature: continue n_bins = bin_counts[feature] if n_bins: bins = np.unique(df[feature].quantile(np.linspace(0, 1, n_bins)).values) df[feature + '_binned'] = pd.cut( df[feature], bins=bins, duplicates='drop' ).cat.codes return df def to_categorical(df): cat_cols = ['tweet_has_attachment', 'user_has_location', 'user_has_url', 'user_verified', ] df[cat_cols] = df[cat_cols].astype('category') return df def change2float32(df): float_cols = df.select_dtypes('float64').columns df[float_cols] = df[float_cols].astype(np.float32) return df def merge_df2media(df, df_media): num_media = (df_media.groupby('tweet_id')['media_id'] .nunique() .reset_index()) df_media.drop('media_id', axis=1, inplace=True) num_media.columns = ['tweet_id', 'num_media'] df_media = df_media.merge(num_media, how='left', on='tweet_id') media_cols = [col for col in df_media if col not in ['tweet_id','media_id']] df_media = df_media.groupby('tweet_id')[media_cols].mean().reset_index() # df_media = mean_feats.merge(df_media[['tweet_id']], how='left', on='tweet_id') # del mean_feats; _ = gc.collect() df_media['tweet_has_media'] = True df = df.merge(df_media, how='left', on='tweet_id') # fillna False if tweet has no media df['tweet_has_media'] = df['tweet_has_media'].fillna(False) # the same for the count of number of media per tweet df['num_media'] = df['num_media'].fillna(0).astype(np.int8) return df # def add_num_media_user(df): # # todo when not debug: df['num_media'].equals(df['num_media_user']) # num_media_user = df.groupby('tweet_id')['num_media'].sum().reset_index() # num_media_user.columns = ['tweet_id','num_media_user'] # df = df.merge(num_media_user, how='left', on='tweet_id') # df['num_media_user'] = df['num_media_user'].astype(np.int8) # return df def tweets_user_created_date(df): for feat_ in ['tweet_created_at_year', 'tweet_created_at_month', 'tweet_created_at_day', 'tweet_created_at_hour']: # counts_df_cols = ['tweet_user_id']+[f"tweets_in_{feat_.split('_')[-1]}_{time_}" for time_ in np.sort(df[feat_].unique())] # tweet_user_ids = np.sort(df['tweet_user_id'].unique()) # counts_df = pd.DataFrame(index=range(tweet_user_ids), columns=counts_df_cols) # counts_df['tweet_user_id'] = tweet_user_ids counts_map = df.groupby('tweet_user_id')[feat_].apply(lambda x: x.value_counts()) counts_map = counts_map.unstack(level=1) counts_map.columns = [f"tweets_in_{feat_.split('_')[-1]}_"+str(col) for col in counts_map.columns] counts_map = counts_map.fillna(0).reset_index() df = df.merge(counts_map, how='left', on='tweet_user_id') return df # n_tweets_time_user = df.groupby('tweet_user_id')[feat_].count().reset_index() # n_tweets_time_user.columns = ['tweet_user_id', f"n_tweets_{feat_.split('_')[-1]}_user_count"] # df = df.merge(n_tweets_time_user, how='left', on='tweet_user_id') def create_date_col(df): tweet_date_cols = ['tweet_created_at_year', 'tweet_created_at_month', 'tweet_created_at_day'] df['date'] = df[tweet_date_cols].apply(lambda x: str(x['tweet_created_at_month']).strip() + '/' + str(x['tweet_created_at_day']).strip() + '/' + str(x['tweet_created_at_year']).strip(), axis=1) df['date'] = pd.to_datetime(df['date']) return df def add_sincos(df): hour_sine = np.sin(2 * np.pi * df['tweet_created_at_hour'] / 24.0) hour_sine.name = 'sin_hour' hour_cosine = np.cos(2 * np.pi * df['tweet_created_at_hour'] / 24.0) hour_cosine.name = 'cos_hour' df = df.join([hour_sine, hour_cosine]) return df def add_dummy_dates(df): year = pd.get_dummies(df.tweet_created_at_year, prefix='ohe_year') month = pd.get_dummies(df.tweet_created_at_month, prefix='ohe_month') day = pd.get_dummies(df.tweet_created_at_day, prefix='ohe_day') user_year = pd.get_dummies(df.user_created_at_year, prefix='ohe_user_year') user_month = pd.get_dummies(df.user_created_at_month, prefix='ohe_user_month') df = df.join([year, month, day, user_year, user_month]) return df def add_date_feats(df): # todo OHE date # todo to sin, cos(date) #df_old_index = df.index df = create_date_col(df) df = add_sincos(df) df = add_dummy_dates(df) cols_resample = ['tweet_hashtag_count', 'tweet_url_count', 'tweet_mention_count', ] date_freqs = ['1Q'] # ,'1M'] # todo DON't use _func_min if does not affect CV (low feat importance) stats = ['sum','mean','std','max'] # ['mean', 'max', 'min', 'median', 'std'] for freq_ in date_freqs: for stat_ in stats: df.set_index('date', inplace=True) g = (df.groupby('tweet_user_id').resample(freq_, closed='left') [cols_resample].agg(stat_) .astype(np.float32) ) # .set_index('date')) g = g.unstack('date').fillna(0) g.columns = [col1 + f'_func_{stat_}_' + col2.strftime('%Y-%m-%d') for (col1, col2) in g.columns] g.reset_index(inplace=True) # g = g.rename(columns ={col: f"{col}_rsmpl_{freq_}_func_{stat_}" # for col in g.columns if col not in ['tweet_user_id','date']}) #df = df.reset_index().merge(g, how='left', on='tweet_user_id') df = df.reset_index().merge(g, how='left', on='tweet_user_id') # df.reset_index(drop=False, inplace=True) # todo count 'tweet_id' for each period for user today = pd.to_datetime('7/1/2021') df['days_since_tweet'] = (today - df['date']).dt.days # .astype(int) df['user_followers_count_2days'] = df['user_followers_count'] / df['days_since_tweet'] df['user_following_count_2days'] = df['user_following_count'] / df['days_since_tweet'] df['user_listed_on_count_2days'] = df['user_listed_on_count'] / df['days_since_tweet'] df['user_tweet_count_2days'] = df['user_tweet_count'] / df['days_since_tweet'] df['tweet_hashtag_count_2days'] = df['tweet_hashtag_count'] / df['days_since_tweet'] df['tweet_mention_count_2days'] = df['tweet_mention_count'] / df['days_since_tweet'] df['tweet_url_count_2days'] = df['tweet_url_count'] / df['days_since_tweet'] # todo not a date related functions: df['tweet_mention_count_div_followers'] = df['tweet_mention_count'].divide(df['user_followers_count']+1) df['tweet_url_count_div_followers'] = df['tweet_url_count'].divide(df['user_followers_count']+1) df['tweet_hashtag_count_div_followers'] = df['tweet_hashtag_count'].divide(df['user_followers_count']+1) df['tweet_mention_count_div_followers'] = df['tweet_mention_count'].divide(df['user_followers_count']+1) df['tweet_mention_count_div_n_tweets'] = df['tweet_mention_count'].divide(df['user_tweet_count']+1) df['tweet_url_count_div_n_tweets'] = df['tweet_url_count'].divide(df['user_tweet_count']+1) df['tweet_hashtag_count_div_n_tweets'] = df['tweet_hashtag_count'].divide(df['user_tweet_count']+1) df['tweet_mention_count_div_n_tweets'] = df['tweet_mention_count'].divide(df['user_tweet_count']+1) df['tweet_mention_count_div_likes'] = df['tweet_mention_count'].divide(df['user_like_count']+1) df['tweet_url_count_div_likes'] = df['tweet_url_count'].divide(df['user_like_count']+1) df['tweet_hashtag_count_div_likes'] = df['tweet_hashtag_count'].divide(df['user_like_count']+1) df['tweet_mention_count_div_likes'] = df['tweet_mention_count'].divide(df['user_like_count']+1) cols_drop = ['date', 'tweet_created_at_year', 'tweet_created_at_month', 'tweet_created_at_day', 'user_created_at_year', 'user_created_at_month'] df.drop(cols_drop, axis=1, inplace=True) return df def ohe_func(df, cat_col, ohe_tfm=LabelBinarizer(), prefix=None): """ OHE one categorical column of df, and return df with columns 'label_{range(1,x}' added """ # ohe.iloc[:, df['tweet_language_id'].tolist()] ohe_tfm.fit(df[cat_col]) ohe_transformed = ohe_tfm.transform(df[cat_col]) if prefix: cat_cols = [f'{prefix}_{cat_col}_{i}' for i in range(ohe_transformed.shape[1])] else: cat_cols = [f'{cat_col}_{i}' for i in range(ohe_transformed.shape[1])] ohe_df = pd.DataFrame(ohe_transformed, index=df.index, columns=cat_cols) df = pd.concat([df, ohe_df], axis=1) df.drop(cat_col, axis=1, inplace=True) return df def drop_unnecessary_cols(cfg, df): cols_drop = [] # 'tweet_created_at_year', 'tweet_created_at_month', # 'tweet_created_at_day'] # 'days_since_user', 'user_created_at_year', 'user_created_at_month', # 'user_verified', 'user_has_url'] if cfg.drop_rare_ohe_language_ids and cfg.one_hot_encode: lang_leave_ids = [0, 1, 3] cols_drop += [f'tweet_language_id_{i}' for i in range(31) if i not in lang_leave_ids ] for col in cols_drop: if col in df.columns: df.drop(col, axis=1, inplace=True) # print(f"Dropped col: {col}") return df class Features(): def __init__(self,): self.transformers = {} self.impute_img_feature_nulls = -1 self.media_img_feat_cols = [] self.text_feat_cols = [] self.user_des_feat_cols = [] self.user_img_feat_cols = [] # union of topic ids in train and test , 0 - nan value, min=36, max=172 # xor train, test = [ 38, 117, 123, 165] # in test but not in train = [ 38, 117, 123] self.unique_topic_ids = [ 0, 36, 37, 38, 39, 43, 44, 45, 52, 58, 59, 60, 61, 63, 68, 71, 72, 73, 78, 79, 80, 81, 82, 87, 88, 89, 91, 93, 98, 99, 100, 101, 104, 111, 112, 117, 118, 119, 120, 121, 122, 123, 125, 126, 127, 147, 148, 149, 150, 151, 152, 153, 155, 156, 163, 165, 169, 170, 171, 172] self.cols2int8 = ['fold', 'user_created_at_month', 'tweet_created_at_day', 'tweet_created_at_hour', 'tweet_hashtag_count', 'tweet_url_count', 'tweet_mention_count', 'tweet_has_attachment', 'virality', 'tweet_has_media', 'user_has_url', 'user_verified', 'num_media', 'user_id', 'tweet_user_id'] # 'tweet_created_at_year', 'user_created_at_year', self.cols2int8 += [f'tweet_language_id_{i}' for i in range(30)] def get_data_stage1(self, cfg, base_dir, n_samples=int(1e10)): df = pd.read_csv(osj(base_dir, 'Tweets',f'train_tweets.csv'), nrows=n_samples) test = pd.read_csv(osj(base_dir, 'Tweets',f'test_tweets.csv'), nrows=n_samples) # test_tweet_ids = test['tweet_id'].to_list() # self.tabular_feats.append() df = pd.concat([df, test]) del test; _ = gc.collect() df = change2float32(df) df = self.optimize_ints(df) #df.drop('tweet_attachment_class', axis=1, inplace=True) # try using 'media_id' columns df_media = pd.read_csv(osj(base_dir, 'Tweets',f'train_tweets_vectorized_media.csv')) df_media_test = pd.read_csv(osj(base_dir, 'Tweets',f'test_tweets_vectorized_media.csv')) df_media = pd.concat([df_media, df_media_test]) df_media = change2float32(df_media) df = merge_df2media(df, df_media) del df_media, df_media_test; _ = gc.collect() df_text = pd.read_csv(osj(base_dir, 'Tweets',f'train_tweets_vectorized_text.csv')) df_text_test = pd.read_csv(osj(base_dir, 'Tweets',f'test_tweets_vectorized_text.csv')) df_text = pd.concat([df_text, df_text_test]) text_feat_cols = ['text_'+ col for col in df_text.columns if col.startswith('feature_')] df_text.columns = ['tweet_id'] + text_feat_cols df_text.loc[:, text_feat_cols] = np.log(df_text[text_feat_cols] + 13) df_text = change2float32(df_text) df = df.merge(df_text, how='left', on='tweet_id') del df_text, df_text_test; _ = gc.collect() users = pd.read_csv(osj(base_dir, 'Users','users.csv')) # log of _count feats users_des = pd.read_csv(osj(base_dir, 'Users','user_vectorized_descriptions.csv')) # for col in ['tweet_hashtag_count','tweet_url_count','tweet_mention_count']: # users[col] = users[col].astype(int) users_img = pd.read_csv(osj(base_dir, 'Users','user_vectorized_profile_images.csv')) user_des_feat_cols = ['user_des_'+col for col in users_des.columns if col.startswith('feature')] users_des.columns = ['user_id'] + user_des_feat_cols user_img_feat_cols = ['user_img_'+col for col in users_img.columns if col.startswith('feature')] users_img.columns = ['user_id'] + user_img_feat_cols # user_data = users # .merge(users, how='left', on='user_id') user_data = users.merge(users_des, how='left', on='user_id') user_data = user_data.merge(users_img, how='left', on='user_id') user_data = change2float32(user_data) user_data = self.optimize_ints(user_data) # # no nulls in user_data 25-may df = df.merge(user_data, how='left', left_on='tweet_user_id', right_on='user_id') df.drop('user_id', axis=1, inplace=True) df = cond_drop_imgtext(cfg, df) # df = add_num_media_user(df) del users_des, users_img, user_data; _ = gc.collect() return df # , test_tweet_ids def get_data_stage2(self, cfg, df): df = tweets_user_created_date(df) # add feats: number of user tweets in time period (year, month, day, hour) df = add_date_feats(df) df = bin_feats(df, feats=['tweet_mention_count','user_tweet_count', 'user_followers_count','user_following_count', 'user_listed_on_count']) df = add_topic_count(df) df = add_topic_ids(df) bool_cols = df.select_dtypes(include='bool').columns df[bool_cols] = df[bool_cols].astype(np.int8) if cfg.one_hot_encode: df = ohe_func(df, cat_col='tweet_language_id', ohe_tfm=LabelBinarizer()) df = ohe_func(df, cat_col='tweet_attachment_class', ohe_tfm=LabelBinarizer()) else: df['tweet_attachment_class'] = df['tweet_attachment_class'].astype('category').cat.codes # df = to_binary_categories(df, cat_col='tweet_language_id') media_img_feat_cols = [col for col in df.columns if col.startswith('img_feature_')] if cfg.impute_nulls: df.loc[:,media_img_feat_cols] = df[media_img_feat_cols].fillna(self.impute_img_feature_nulls) if cfg.add_user_virality: df = self.add_virality_feature(df) df = freq_encoding(df, freq_cols=['tweet_user_id'], main_col='tweet_id') df = drop_unnecessary_cols(cfg, df) # log (feats) : cols2log = ['user_like_count','user_followers_count', 'user_following_count', 'user_listed_on_count', 'user_tweet_count'] # 'tweet_hashtag_count' , 'tweet_url_count', 'tweet_mention_count' cols2log = [col for col in df.columns if col in cols2log] df = logtransform(df, cols2log) # print("df.shape after merging all csv files:", df.shape) # print("df.dtypes.value_counts():\n", df.dtypes.value_counts()) # train = df[~df['tweet_id'].isin(test_tweet_ids)] # test = df[df['tweet_id'].isin(test_tweet_ids)] train = df[~df['virality'].isnull()] test = df[df['virality'].isnull()] del test['virality']; _ = gc.collect() print(f"train.shape = {train.shape}, test.shape = {test.shape}") return train, test # end of def get_data def add_virality_feature(self, df): df_train = df[~df['virality'].isnull()] viral_user = df_train.groupby('tweet_user_id')['virality'].mean().reset_index() viral_user.columns = ['tweet_user_id', 'user_virality'] df = df.merge(viral_user, how='left', on='tweet_user_id') return df def optimize_ints(self, df): int8_candidates = self.cols2int8 # for col in ['tweet_created_at_year', 'user_created_at_year']: # if col in df.columns: # df.loc[:, col] = df.loc[:, col] - 2000 # df.loc[:, col] = df.loc[:, col].astype(np.int8) for col in int8_candidates: if (col in df.columns) and (df[col].isnull().sum()==0): df.loc[:, col] = df.loc[:, col].astype(np.int8) return df # end of class Features def logtransform(df, cols2log): df.loc[:, cols2log] = np.log(df[cols2log] + 2) return df class NormalizeFeats_Parallel(): """ https://scikit-learn.org/stable/computing/parallelism.html from joblib import parallel_backend with parallel_backend('threading', n_jobs=2): # Your scikit-learn code here """ def __init__(self, feat_cols: list): self.feat_cols = feat_cols self.scalers_dict = {} def normalize_data(self, df, mode='train', scaler=StandardScaler()): if mode =='train': for col in self.feat_cols: with parallel_backend('threading', n_jobs=n_cpus): scaler.fit(df[col].values.reshape(-1,1)) self.scalers_dict[col] = scaler # scaler.fit(df[feat_cols].values) df.loc[:,col] = self.scalers_dict[col].transform(df[col].values.reshape(-1,1)) else: for col in self.feat_cols: with parallel_backend('threading', n_jobs=n_cpus): df.loc[:,col] = self.scalers_dict[col].transform(df[col].values.reshape(-1,1)) return df # end of NormalizeFeats class class NormalizeFeats(): def __init__(self, feat_cols: list): self.feat_cols = feat_cols self.scalers_dict = {} def normalize_data(self, df, mode='train', scaler=StandardScaler()): if mode =='train': for col in self.feat_cols: scaler.fit(df[col].values.reshape(-1,1)) self.scalers_dict[col] = scaler # scaler.fit(df[feat_cols].values) df.loc[:,col] = self.scalers_dict[col].transform(df[col].values.reshape(-1,1)) else: for col in self.feat_cols: df.loc[:,col] = self.scalers_dict[col].transform(df[col].values.reshape(-1,1)) return df # end of NormalizeFeats class def transform_joint(train, test=None, norm_cols=None, tfm = StandardScaler()): # normalize joint train test data in chunks by columns l_train = len(train) if len(norm_cols) < 1000: if isinstance(test, pd.DataFrame): assert train[norm_cols].columns.equals(test[norm_cols].columns) data = pd.concat([train[norm_cols], test[norm_cols]]).values else: data = train[norm_cols].values with parallel_backend('threading', n_jobs=n_cpus): tfm.fit(data) data = tfm.transform(data) train.loc[:, norm_cols] = data[:l_train] if isinstance(test, pd.DataFrame): test.loc[:, norm_cols] = data[l_train:] else: # len(norm_cols) >= 1000 all_col_chunks = [norm_cols[i:i+1000] for i in range(0, len(norm_cols), 1000)] for cols_chunk in all_col_chunks: if isinstance(test, pd.DataFrame): assert train[norm_cols].columns.equals(test[norm_cols].columns) data_chunk = pd.concat([train[cols_chunk], test[cols_chunk]]).values else: data_chunk = train[cols_chunk] scaler = StandardScaler() with parallel_backend('threading', n_jobs=n_cpus): tfm.fit(data_chunk) data_chunk = tfm.transform(data_chunk) train.loc[:, cols_chunk] = data_chunk[:l_train] # todo LONGEST RUNTIME and memory if isinstance(test, pd.DataFrame): test.loc[:, cols_chunk] = data_chunk[l_train:] # todo LONGEST RUNTIME and memory return train, test # test cab be None def normalize_npnan(train, test=None, norm_cols=[]): if len(norm_cols)==0: raise NotImplementedError l_train = len(train) if len(norm_cols) < 1000: if isinstance(test, pd.DataFrame): # assert train[norm_cols].columns.equals(test[norm_cols].columns) data = pd.concat([train[norm_cols], test[norm_cols]]).values else: data = train[norm_cols].values data = (data - np.nanmean(data, axis=0))/np.nanstd(data, axis=0) train.loc[:, norm_cols] = data[:l_train] if isinstance(test, pd.DataFrame): test.loc[:, norm_cols] = data[l_train:] else: # len(norm_cols) >= 1000 all_col_chunks = [norm_cols[i:i + 1000] for i in range(0, len(norm_cols), 1000)] for cols_chunk in all_col_chunks: if isinstance(test, pd.DataFrame): # assert train[norm_cols].columns.equals(test[norm_cols].columns) data_chunk = pd.concat([train[cols_chunk], test[cols_chunk]]).values else: data_chunk = train[cols_chunk] data_chunk = (data_chunk - np.nanmean(data_chunk, axis=0))/np.nanstd(data_chunk, axis=0) train.loc[:, cols_chunk] = data_chunk[:l_train] # todo LONGEST RUNTIME and memory if isinstance(test, pd.DataFrame): test.loc[:, cols_chunk] = data_chunk[l_train:] # todo LONGEST RUNTIME and memory return train, test # test cab be None def normalize_joint(train, test=None, norm_cols=None): # normalize joint train test data in chunks by columns l_train = len(train) if len(norm_cols) < 1000: if isinstance(test, pd.DataFrame): assert train[norm_cols].columns.equals(test[norm_cols].columns) data = pd.concat([train[norm_cols], test[norm_cols]]).values else: data = train[norm_cols].values scaler = StandardScaler() with parallel_backend('threading', n_jobs=n_cpus): scaler.fit(data) data = scaler.transform(data) train.loc[:, norm_cols] = data[:l_train] if isinstance(test, pd.DataFrame): test.loc[:, norm_cols] = data[l_train:] else: # len(norm_cols) >= 1000 all_col_chunks = [norm_cols[i:i+1000] for i in range(0, len(norm_cols), 1000)] for cols_chunk in all_col_chunks: if isinstance(test, pd.DataFrame): assert train[norm_cols].columns.equals(test[norm_cols].columns) data_chunk = pd.concat([train[cols_chunk], test[cols_chunk]]).values else: data_chunk = train[cols_chunk] scaler = StandardScaler() with parallel_backend('threading', n_jobs=n_cpus): scaler.fit(data_chunk) data_chunk = scaler.transform(data_chunk) train.loc[:, cols_chunk] = data_chunk[:l_train] # todo LONGEST RUNTIME and memory if isinstance(test, pd.DataFrame): test.loc[:, cols_chunk] = data_chunk[l_train:] # todo LONGEST RUNTIME and memory return train, test # test cab be None def normalize_joint_parallel(train, test, norm_cols, num_workers=6): # normalize joint train test data in chunks by columns from joblib import Parallel, delayed l_train = len(train) assert train[norm_cols].columns.equals(test[norm_cols].columns) if len(norm_cols) < 1000: data = pd.concat([train[norm_cols], test[norm_cols]]).values scaler = StandardScaler() with parallel_backend('threading', n_jobs=n_cpus): scaler.fit(data) data = scaler.transform(data) train.loc[:, norm_cols] = data[:l_train] test.loc[:, norm_cols] = data[l_train:] else: # len(norm_cols) >= 1000 all_col_chunks = [norm_cols[i:i+1000] for i in range(0, len(norm_cols), 1000)] for cols_chunk in all_col_chunks: data_chunk = pd.concat([train[cols_chunk], test[cols_chunk]]).values scaler = StandardScaler() with parallel_backend('threading', n_jobs=n_cpus): scaler.fit(data_chunk) data_chunk = scaler.transform(data_chunk) train.loc[:, cols_chunk] = data_chunk[:l_train] # todo LONGEST RUNTIME and memory test.loc[:, cols_chunk] = data_chunk[l_train:] # todo LONGEST RUNTIME and memory return train, test def split2folds_user_viral(df, n_folds, seed_folds, label_cols=None, foldnum_col='fold'): # df is added foldnum_col='fold' column based on KFoldMethod = StratifiedKFold class # applied to label_col='label' column temp_col = label_cols[0] + "_" + label_cols[1] df[temp_col] = df[label_cols[0]].astype(str) + "_" + df[label_cols[1]].astype(str) df[temp_col] =df[temp_col].astype('category') skf = StratifiedKFold(n_splits=n_folds, shuffle=True, random_state=seed_folds) df[foldnum_col] = np.nan for fold, (train_idx, val_idx) in enumerate(skf.split(np.zeros(df.shape[0]), df[temp_col])): df.iloc[val_idx, df.columns.get_loc(foldnum_col)] = fold df[foldnum_col] = df[foldnum_col].astype(int) # assert df.isnull().sum().sum() == 0, "Error: null values in df" del df[temp_col] return df def split2folds_viral_only(df, n_folds, seed_folds, label_col='label', foldnum_col='fold'): # df is added foldnum_col='fold' column based on KFoldMethod = StratifiedKFold class # applied to label_col='label' column skf = StratifiedKFold(n_splits=n_folds, shuffle=True, random_state=seed_folds) df[foldnum_col] = np.nan for fold, (train_idx, val_idx) in enumerate(skf.split(df.values[:,:1], df[label_col])): df.iloc[val_idx, df.columns.get_loc(foldnum_col)] = fold df[foldnum_col] = df[foldnum_col].astype(int) # assert df.isnull().sum().sum() == 0, "Error: null values in df" return df def split2folds_simple(df, n_folds, seed_folds, foldnum_col='fold'): # df is added foldnum_col='fold' column based on KFoldMethod = StratifiedKFold class # applied to label_col='label' column skf = KFold(n_splits=n_folds, shuffle=True, random_state=seed_folds) df[foldnum_col] = np.nan for fold, (train_idx, val_idx) in enumerate(skf.split(df.values[:,:1])): df.iloc[val_idx, df.columns.get_loc(foldnum_col)] = fold df[foldnum_col] = df[foldnum_col].astype(int) # assert df.isnull().sum().sum() == 0, "Error: null values in df" return df def get_folds(cfg, train, default_seed_folds=24): # if cfg.seed_folds == default_seed_folds: # folds = pd.read_csv(cfg.folds_split_path) # if 'fold' in train.columns: # del train['fold'] # train = train.merge(folds, how='left', on='tweet_id') # train.dropna(0, subset=['fold'], inplace=True) # else: if cfg.folds_split_method == 'user_viral': train = split2folds_user_viral(train, cfg.n_folds, cfg.seed_folds, label_cols=['tweet_user_id', 'virality'], foldnum_col='fold') return train def get_feat_cols(train): feat_cols = [col for col in train.columns if (col not in ['virality', 'tweet_id', 'fold','is_test']) and not col.startswith('target_')] media_img_feat_cols = [col for col in train.columns if col.startswith('img_feature')] text_feat_cols = [col for col in train.columns if col.startswith('text_feature')] user_des_feat_cols = [col for col in train.columns if col.startswith('user_des_feature')] user_img_feat_cols = [col for col in train.columns if col.startswith('user_img_feature')] feats_some = [col for col in feat_cols if not col in media_img_feat_cols + text_feat_cols + user_img_feat_cols + user_des_feat_cols] # print(f"Null values:\n{train[feat_cols].isnull().sum().sort_values(ascending=False).head(2)}") return (feat_cols, media_img_feat_cols, text_feat_cols, user_des_feat_cols, user_img_feat_cols, feats_some) def cond_drop_imgtext(cfg, df): (feat_cols, media_img_feat_cols, text_feat_cols, user_des_feat_cols, user_img_feat_cols, feats_some) = get_feat_cols(df) if cfg.drop_media_img_feats: df.drop(media_img_feat_cols, axis=1, inplace=True) if cfg.drop_text_feats: df.drop(text_feat_cols, axis=1, inplace=True) if cfg.drop_user_des_feats: df.drop(user_des_feat_cols, axis=1, inplace=True) if cfg.drop_user_img_feats: df.drop(user_img_feat_cols, axis=1, inplace=True) return df def add_topic_count(df): # and drop the column nan_replace = '0' topics = df['tweet_topic_ids'].fillna(f'[{nan_replace}]') # topics_xnan = train['tweet_topic_ids'].dropna() # fill_value = topicsx_xnan.apply(lambda x: len(eval(x))).mean() # fill_value = topicx_xnan.apply(lambda x: len(eval(x))).median() n_topics = topics.apply(lambda x: len(eval(x))) n_topics_mean = n_topics.mean() n_topics = np.where(topics == nan_replace, n_topics_mean, n_topics) df['n_topics'] = n_topics.astype(int) return df def add_topic_ids(df): df.fillna({'tweet_topic_ids': "['0']"}, inplace=True) topic_ids = ( df['tweet_topic_ids'].str.strip('[]').str.split('\s*,\s*').explode() .str.get_dummies().sum(level=0).add_prefix('topic_id_') ) topic_ids.rename(columns=lambda x: x.replace("'", ""), inplace=True) if 'tweet_topic_ids' in df.columns: df.drop('tweet_topic_ids', 1) df = df.join(topic_ids) # , how='left', on='tweet_id') for col_ in topic_ids.columns: if df[col_].max() > 1: df[f"{col_}_hthan1_binary"] = (df[col_] > 0).astype(np.int8) df.drop('tweet_topic_ids',1, inplace=True) return df # # def replace_add_new_topic_ids(train, test): # # add topic_id cols (57) with number of times the topic is in the sample # # add _binary cols (45) where =1 if topic_id is more than once # old_topic_id_cols = [col for col in train.columns if 'topic_id' in col] # print(f"old_topic_id_cols: {old_topic_id_cols}") # len_train = train.shape[0] # train = pd.concat([train, test]).reset_index(drop=True) # del test; # _ = gc.collect() # train.drop(old_topic_id_cols, axis=1, inplace=True) # train, new_topic_id_cols = add_new_topic_ids(base_dir, train, df_name='train_test') # # todo cols ['topic_id_117' 'topic_id_123' 'topic_id_38'] are not in new_topic_id_cols # # done: only one sample==1 for each topic_id_117 topic_id_123 topic_id_38 [0 42274 42274 42274] [1 1 1 1] # for col_ in new_topic_id_cols: # if train[col_].max() > 1: # train[f"{col_}_hthan1_binary"] = (train[col_] > 0).astype(np.int8) # # train.drop(col_, axis=1, inplace=True) # test = train.iloc[len_train:, :].reset_index(drop=True) # train = train.iloc[:len_train, :] # return train, test def extract_feats_media_text(df): # todo extact_feats_media_text # Set the target as well as dependent variables from image data. y = vectorized_media_df['virality'] x = vectorized_media_df.loc[:, vectorized_media_df.columns.str.contains("img_")] # Run Lasso regression for feature selection. sel_model = SelectFromModel(LogisticRegression(C=1, penalty='l1', solver='liblinear')) # time the model fitting start = timeit.default_timer() # Fit the trained model on our data sel_model.fit(x, y) stop = timeit.default_timer() print('Time: ', stop - start) # get index of good features sel_index = sel_model.get_support() # count the no of columns selected counter = collections.Counter(sel_model.get_support()) print(counter) def save_preprocessed(cfg, train, test, path_train, path_test): # p_train = cfg.train_preprocessed_path # p_test = cfg.test_preprocessed_path # if cfg.debug: # path_train = osj(os.path.dirname(p_train), 'debug_' + os.path.basename(path_train)) # path_test = osj(os.path.dirname(p_test), 'debug_' + os.path.basename(path_test)) assert not os.path.isfile(path_train), f"WON'T OVERWRITE/SAVE: file exists {os.path.basename(path_train)}" assert not os.path.isfile(path_test), f"WON'T OVERWRITE/SAVE: file exists {os.path.basename(path_test)}" train.to_csv(path_train, index=False) test.to_csv(path_test, index=False) def get_raw_train_tweet_cols(df): # get cols from train_tweets.csv and users.csv init_tweets_cols = ['tweet_id', 'tweet_user_id', 'tweet_created_at_year', 'tweet_created_at_month', 'tweet_created_at_day', 'tweet_created_at_hour', 'tweet_hashtag_count', 'tweet_url_count', 'tweet_mention_count', 'tweet_has_attachment', 'tweet_attachment_class', 'tweet_language_id', 'tweet_topic_ids', 'virality'] init_users_cols = ['user_id', 'user_like_count', 'user_followers_count', 'user_following_count', 'user_listed_on_count', 'user_has_location', 'user_tweet_count', 'user_has_url', 'user_verified', 'user_created_at_year', 'user_created_at_month'] def add_new_topic_ids(base_dir, df, df_name='train'): if df_name=='train_test': df_tweets = pd.read_csv(osj(base_dir, 'Tweets', f'train_tweets.csv'), usecols=['tweet_id', 'tweet_topic_ids'] ) df_tweets_test = pd.read_csv(osj(base_dir, 'Tweets', f'test_tweets.csv'), usecols=['tweet_id', 'tweet_topic_ids'] ) df_tweets = pd.concat([df_tweets, df_tweets_test]).reset_index(drop=True) # df_tweets = df.reindex(df.index) else: df_tweets = pd.read_csv(osj(base_dir, 'Tweets', f'{df_name}_tweets.csv'), usecols=['tweet_id', 'tweet_topic_ids'] ) df_tweets.fillna({'tweet_topic_ids': "['0']"}, inplace=True) topic_ids = ( df_tweets['tweet_topic_ids'].str.strip('[]').str.split('\s*,\s*').explode() .str.get_dummies().sum(level=0).add_prefix('topic_id_') ) topic_ids.rename(columns=lambda x: x.replace("'", ""), inplace=True) topic_ids['tweet_id'] = df_tweets['tweet_id'] if 'tweet_topic_ids' in df.columns: df.drop('tweet_topic_ids') df = df.merge(topic_ids, how='left', on='tweet_id') return df, list(topic_ids.columns)
[ "sklearn.preprocessing.LabelBinarizer", "sklearn.preprocessing.StandardScaler", "collections.defaultdict", "gc.collect", "os.path.isfile", "numpy.sin", "joblib.parallel_backend", "pandas.set_option", "multiprocessing.cpu_count", "pandas.DataFrame", "numpy.nanmean", "numpy.linspace", "pandas....
[((375, 408), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (398, 408), False, 'import warnings\n'), ((409, 451), 'pandas.set_option', 'pd.set_option', (['"""display.max_colwidth"""', '(100)'], {}), "('display.max_colwidth', 100)\n", (422, 451), True, 'import pandas as pd\n'), ((452, 489), 'pandas.set_option', 'pd.set_option', (['"""display.max_rows"""', '(20)'], {}), "('display.max_rows', 20)\n", (465, 489), True, 'import pandas as pd\n'), ((537, 548), 'multiprocessing.cpu_count', 'cpu_count', ([], {}), '()\n', (546, 548), False, 'from multiprocessing import cpu_count\n'), ((2758, 2794), 'collections.defaultdict', 'defaultdict', (['(lambda : n_bins_default)'], {}), '(lambda : n_bins_default)\n', (2769, 2794), False, 'from collections import defaultdict\n'), ((6491, 6517), 'pandas.to_datetime', 'pd.to_datetime', (["df['date']"], {}), "(df['date'])\n", (6505, 6517), True, 'import pandas as pd\n'), ((6570, 6624), 'numpy.sin', 'np.sin', (["(2 * np.pi * df['tweet_created_at_hour'] / 24.0)"], {}), "(2 * np.pi * df['tweet_created_at_hour'] / 24.0)\n", (6576, 6624), True, 'import numpy as np\n'), ((6675, 6729), 'numpy.cos', 'np.cos', (["(2 * np.pi * df['tweet_created_at_hour'] / 24.0)"], {}), "(2 * np.pi * df['tweet_created_at_hour'] / 24.0)\n", (6681, 6729), True, 'import numpy as np\n'), ((6858, 6917), 'pandas.get_dummies', 'pd.get_dummies', (['df.tweet_created_at_year'], {'prefix': '"""ohe_year"""'}), "(df.tweet_created_at_year, prefix='ohe_year')\n", (6872, 6917), True, 'import pandas as pd\n'), ((6930, 6991), 'pandas.get_dummies', 'pd.get_dummies', (['df.tweet_created_at_month'], {'prefix': '"""ohe_month"""'}), "(df.tweet_created_at_month, prefix='ohe_month')\n", (6944, 6991), True, 'import pandas as pd\n'), ((7002, 7059), 'pandas.get_dummies', 'pd.get_dummies', (['df.tweet_created_at_day'], {'prefix': '"""ohe_day"""'}), "(df.tweet_created_at_day, prefix='ohe_day')\n", (7016, 7059), True, 'import pandas as pd\n'), ((7076, 7139), 'pandas.get_dummies', 'pd.get_dummies', (['df.user_created_at_year'], {'prefix': '"""ohe_user_year"""'}), "(df.user_created_at_year, prefix='ohe_user_year')\n", (7090, 7139), True, 'import pandas as pd\n'), ((7157, 7222), 'pandas.get_dummies', 'pd.get_dummies', (['df.user_created_at_month'], {'prefix': '"""ohe_user_month"""'}), "(df.user_created_at_month, prefix='ohe_user_month')\n", (7171, 7222), True, 'import pandas as pd\n'), ((8761, 8787), 'pandas.to_datetime', 'pd.to_datetime', (['"""7/1/2021"""'], {}), "('7/1/2021')\n", (8775, 8787), True, 'import pandas as pd\n'), ((11030, 11046), 'sklearn.preprocessing.LabelBinarizer', 'LabelBinarizer', ([], {}), '()\n', (11044, 11046), False, 'from sklearn.preprocessing import LabelBinarizer\n'), ((11505, 11568), 'pandas.DataFrame', 'pd.DataFrame', (['ohe_transformed'], {'index': 'df.index', 'columns': 'cat_cols'}), '(ohe_transformed, index=df.index, columns=cat_cols)\n', (11517, 11568), True, 'import pandas as pd\n'), ((11578, 11609), 'pandas.concat', 'pd.concat', (['[df, ohe_df]'], {'axis': '(1)'}), '([df, ohe_df], axis=1)\n', (11587, 11609), True, 'import pandas as pd\n'), ((19868, 19892), 'numpy.log', 'np.log', (['(df[cols2log] + 2)'], {}), '(df[cols2log] + 2)\n', (19874, 19892), True, 'import numpy as np\n'), ((21780, 21796), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (21794, 21796), False, 'from sklearn.preprocessing import StandardScaler\n'), ((28169, 28241), 'sklearn.model_selection.StratifiedKFold', 'StratifiedKFold', ([], {'n_splits': 'n_folds', 'shuffle': '(True)', 'random_state': 'seed_folds'}), '(n_splits=n_folds, shuffle=True, random_state=seed_folds)\n', (28184, 28241), False, 'from sklearn.model_selection import StratifiedKFold\n'), ((28828, 28900), 'sklearn.model_selection.StratifiedKFold', 'StratifiedKFold', ([], {'n_splits': 'n_folds', 'shuffle': '(True)', 'random_state': 'seed_folds'}), '(n_splits=n_folds, shuffle=True, random_state=seed_folds)\n', (28843, 28900), False, 'from sklearn.model_selection import StratifiedKFold\n'), ((32400, 32456), 'numpy.where', 'np.where', (['(topics == nan_replace)', 'n_topics_mean', 'n_topics'], {}), '(topics == nan_replace, n_topics_mean, n_topics)\n', (32408, 32456), True, 'import numpy as np\n'), ((13985, 14006), 'pandas.concat', 'pd.concat', (['[df, test]'], {}), '([df, test])\n', (13994, 14006), True, 'import pandas as pd\n'), ((14029, 14041), 'gc.collect', 'gc.collect', ([], {}), '()\n', (14039, 14041), False, 'import os, gc, joblib\n'), ((14424, 14460), 'pandas.concat', 'pd.concat', (['[df_media, df_media_test]'], {}), '([df_media, df_media_test])\n', (14433, 14460), True, 'import pandas as pd\n'), ((14588, 14600), 'gc.collect', 'gc.collect', ([], {}), '()\n', (14598, 14600), False, 'import os, gc, joblib\n'), ((14806, 14840), 'pandas.concat', 'pd.concat', (['[df_text, df_text_test]'], {}), '([df_text, df_text_test])\n', (14815, 14840), True, 'import pandas as pd\n'), ((15035, 15071), 'numpy.log', 'np.log', (['(df_text[text_feat_cols] + 13)'], {}), '(df_text[text_feat_cols] + 13)\n', (15041, 15071), True, 'import numpy as np\n'), ((15211, 15223), 'gc.collect', 'gc.collect', ([], {}), '()\n', (15221, 15223), False, 'import os, gc, joblib\n'), ((16597, 16609), 'gc.collect', 'gc.collect', ([], {}), '()\n', (16607, 16609), False, 'import os, gc, joblib\n'), ((18821, 18833), 'gc.collect', 'gc.collect', ([], {}), '()\n', (18831, 18833), False, 'import os, gc, joblib\n'), ((20305, 20321), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (20319, 20321), False, 'from sklearn.preprocessing import StandardScaler\n'), ((21182, 21198), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (21196, 21198), False, 'from sklearn.preprocessing import StandardScaler\n'), ((25252, 25268), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (25266, 25268), False, 'from sklearn.preprocessing import StandardScaler\n'), ((26843, 26859), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (26857, 26859), False, 'from sklearn.preprocessing import StandardScaler\n'), ((35557, 35583), 'os.path.isfile', 'os.path.isfile', (['path_train'], {}), '(path_train)\n', (35571, 35583), False, 'import os, gc, joblib\n'), ((35668, 35693), 'os.path.isfile', 'os.path.isfile', (['path_test'], {}), '(path_test)\n', (35682, 35693), False, 'import os, gc, joblib\n'), ((1053, 1099), 'torch.tensor', 'torch.tensor', (['self.X[idx]'], {'dtype': 'torch.float32'}), '(self.X[idx], dtype=torch.float32)\n', (1065, 1099), False, 'import torch\n'), ((2072, 2118), 'torch.tensor', 'torch.tensor', (['self.X[idx]'], {'dtype': 'torch.float32'}), '(self.X[idx], dtype=torch.float32)\n', (2084, 2118), False, 'import torch\n'), ((22176, 22220), 'joblib.parallel_backend', 'parallel_backend', (['"""threading"""'], {'n_jobs': 'n_cpus'}), "('threading', n_jobs=n_cpus)\n", (22192, 22220), False, 'from joblib import parallel_backend\n'), ((22893, 22909), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (22907, 22909), False, 'from sklearn.preprocessing import StandardScaler\n'), ((23815, 23838), 'numpy.nanstd', 'np.nanstd', (['data'], {'axis': '(0)'}), '(data, axis=0)\n', (23824, 23838), True, 'import numpy as np\n'), ((25282, 25326), 'joblib.parallel_backend', 'parallel_backend', (['"""threading"""'], {'n_jobs': 'n_cpus'}), "('threading', n_jobs=n_cpus)\n", (25298, 25326), False, 'from joblib import parallel_backend\n'), ((26005, 26021), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (26019, 26021), False, 'from sklearn.preprocessing import StandardScaler\n'), ((26772, 26818), 'pandas.concat', 'pd.concat', (['[train[norm_cols], test[norm_cols]]'], {}), '([train[norm_cols], test[norm_cols]])\n', (26781, 26818), True, 'import pandas as pd\n'), ((26873, 26917), 'joblib.parallel_backend', 'parallel_backend', (['"""threading"""'], {'n_jobs': 'n_cpus'}), "('threading', n_jobs=n_cpus)\n", (26889, 26917), False, 'from joblib import parallel_backend\n'), ((27354, 27370), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (27368, 27370), False, 'from sklearn.preprocessing import StandardScaler\n'), ((28330, 28351), 'numpy.zeros', 'np.zeros', (['df.shape[0]'], {}), '(df.shape[0])\n', (28338, 28351), True, 'import numpy as np\n'), ((35622, 35650), 'os.path.basename', 'os.path.basename', (['path_train'], {}), '(path_train)\n', (35638, 35650), False, 'import os, gc, joblib\n'), ((35732, 35759), 'os.path.basename', 'os.path.basename', (['path_test'], {}), '(path_test)\n', (35748, 35759), False, 'import os, gc, joblib\n'), ((1134, 1180), 'torch.tensor', 'torch.tensor', (['self.X[idx]'], {'dtype': 'torch.float32'}), '(self.X[idx], dtype=torch.float32)\n', (1146, 1180), False, 'import torch\n'), ((1202, 1251), 'torch.tensor', 'torch.tensor', (['self.targets[idx]'], {'dtype': 'torch.long'}), '(self.targets[idx], dtype=torch.long)\n', (1214, 1251), False, 'import torch\n'), ((2153, 2199), 'torch.tensor', 'torch.tensor', (['self.X[idx]'], {'dtype': 'torch.float32'}), '(self.X[idx], dtype=torch.float32)\n', (2165, 2199), False, 'import torch\n'), ((2221, 2277), 'torch.tensor', 'torch.tensor', (['self.targets[idx]'], {'dtype': 'self.target_dtype'}), '(self.targets[idx], dtype=self.target_dtype)\n', (2233, 2277), False, 'import torch\n'), ((22052, 22098), 'pandas.concat', 'pd.concat', (['[train[norm_cols], test[norm_cols]]'], {}), '([train[norm_cols], test[norm_cols]])\n', (22061, 22098), True, 'import pandas as pd\n'), ((22927, 22971), 'joblib.parallel_backend', 'parallel_backend', (['"""threading"""'], {'n_jobs': 'n_cpus'}), "('threading', n_jobs=n_cpus)\n", (22943, 22971), False, 'from joblib import parallel_backend\n'), ((23655, 23701), 'pandas.concat', 'pd.concat', (['[train[norm_cols], test[norm_cols]]'], {}), '([train[norm_cols], test[norm_cols]])\n', (23664, 23701), True, 'import pandas as pd\n'), ((23789, 23813), 'numpy.nanmean', 'np.nanmean', (['data'], {'axis': '(0)'}), '(data, axis=0)\n', (23799, 23813), True, 'import numpy as np\n'), ((24501, 24530), 'numpy.nanstd', 'np.nanstd', (['data_chunk'], {'axis': '(0)'}), '(data_chunk, axis=0)\n', (24510, 24530), True, 'import numpy as np\n'), ((25124, 25170), 'pandas.concat', 'pd.concat', (['[train[norm_cols], test[norm_cols]]'], {}), '([train[norm_cols], test[norm_cols]])\n', (25133, 25170), True, 'import pandas as pd\n'), ((26039, 26083), 'joblib.parallel_backend', 'parallel_backend', (['"""threading"""'], {'n_jobs': 'n_cpus'}), "('threading', n_jobs=n_cpus)\n", (26055, 26083), False, 'from joblib import parallel_backend\n'), ((27277, 27325), 'pandas.concat', 'pd.concat', (['[train[cols_chunk], test[cols_chunk]]'], {}), '([train[cols_chunk], test[cols_chunk]])\n', (27286, 27325), True, 'import pandas as pd\n'), ((27388, 27432), 'joblib.parallel_backend', 'parallel_backend', (['"""threading"""'], {'n_jobs': 'n_cpus'}), "('threading', n_jobs=n_cpus)\n", (27404, 27432), False, 'from joblib import parallel_backend\n'), ((37026, 37064), 'pandas.concat', 'pd.concat', (['[df_tweets, df_tweets_test]'], {}), '([df_tweets, df_tweets_test])\n', (37035, 37064), True, 'import pandas as pd\n'), ((3093, 3142), 'pandas.cut', 'pd.cut', (['df[feature]'], {'bins': 'bins', 'duplicates': '"""drop"""'}), "(df[feature], bins=bins, duplicates='drop')\n", (3099, 3142), True, 'import pandas as pd\n'), ((17336, 17352), 'sklearn.preprocessing.LabelBinarizer', 'LabelBinarizer', ([], {}), '()\n', (17350, 17352), False, 'from sklearn.preprocessing import LabelBinarizer\n'), ((17426, 17442), 'sklearn.preprocessing.LabelBinarizer', 'LabelBinarizer', ([], {}), '()\n', (17440, 17442), False, 'from sklearn.preprocessing import LabelBinarizer\n'), ((20411, 20455), 'joblib.parallel_backend', 'parallel_backend', (['"""threading"""'], {'n_jobs': 'n_cpus'}), "('threading', n_jobs=n_cpus)\n", (20427, 20455), False, 'from joblib import parallel_backend\n'), ((20798, 20842), 'joblib.parallel_backend', 'parallel_backend', (['"""threading"""'], {'n_jobs': 'n_cpus'}), "('threading', n_jobs=n_cpus)\n", (20814, 20842), False, 'from joblib import parallel_backend\n'), ((22751, 22799), 'pandas.concat', 'pd.concat', (['[train[cols_chunk], test[cols_chunk]]'], {}), '([train[cols_chunk], test[cols_chunk]])\n', (22760, 22799), True, 'import pandas as pd\n'), ((24308, 24356), 'pandas.concat', 'pd.concat', (['[train[cols_chunk], test[cols_chunk]]'], {}), '([train[cols_chunk], test[cols_chunk]])\n', (24317, 24356), True, 'import pandas as pd\n'), ((24469, 24499), 'numpy.nanmean', 'np.nanmean', (['data_chunk'], {'axis': '(0)'}), '(data_chunk, axis=0)\n', (24479, 24499), True, 'import numpy as np\n'), ((25863, 25911), 'pandas.concat', 'pd.concat', (['[train[cols_chunk], test[cols_chunk]]'], {}), '([train[cols_chunk], test[cols_chunk]])\n', (25872, 25911), True, 'import pandas as pd\n'), ((3020, 3045), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', 'n_bins'], {}), '(0, 1, n_bins)\n', (3031, 3045), True, 'import numpy as np\n')]
import tensorflow as tf import numpy as np def _tf_fspecial_gauss(size, sigma, ch=1): """Function to mimic the 'fspecial' gaussian MATLAB function """ x_data, y_data = np.mgrid[-size//2 + 1:size//2 + 1, -size//2 + 1:size//2 + 1] x_data = np.expand_dims(x_data, axis=-1) x_data = np.expand_dims(x_data, axis=-1) y_data = np.expand_dims(y_data, axis=-1) y_data = np.expand_dims(y_data, axis=-1) x = tf.constant(x_data, dtype=tf.float32) y = tf.constant(y_data, dtype=tf.float32) g = tf.exp(-((x**2 + y**2)/(2.0*sigma**2))) g = tf.tile(g, [1, 1, ch, 1]) return g / tf.reduce_sum(g) def tf_ssim(img1, img2, cs_map=False, mean_metric=True, size=11, sigma=0.5): img1 = tf.image.rgb_to_grayscale(img1) img2 = tf.image.rgb_to_grayscale(img2) window = _tf_fspecial_gauss(size, sigma, ch=img1.get_shape().as_list()[-1]) # window shape [size, size] K1 = 0.01 K2 = 0.03 L = 1 # depth of image (255 in case the image has a differnt scale) C1 = (K1*L)**2 C2 = (K2*L)**2 mu1 = tf.nn.conv2d(img1, window, strides=[1, 1, 1, 1], padding='VALID') mu2 = tf.nn.conv2d(img2, window, strides=[1, 1, 1, 1], padding='VALID') mu1_sq = mu1*mu1 mu2_sq = mu2*mu2 mu1_mu2 = mu1*mu2 sigma1_sq = tf.nn.conv2d(img1*img1, window, strides=[1, 1, 1, 1], padding='VALID') - mu1_sq sigma2_sq = tf.nn.conv2d(img2*img2, window, strides=[1, 1, 1, 1], padding='VALID') - mu2_sq sigma12 = tf.nn.conv2d(img1*img2, window, strides=[1, 1, 1, 1], padding='VALID') - mu1_mu2 if cs_map: value = ( ((2*mu1_mu2 + C1) * (2*sigma12 + C2)) / ( (mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2) ), (2.0*sigma12 + C2)/(sigma1_sq + sigma2_sq + C2) ) else: value = ((2*mu1_mu2 + C1)*(2*sigma12 + C2)) / ( (mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2)) if mean_metric: value = tf.reduce_mean(value) return value def tf_ms_ssim(img1, img2, mean_metric=True, level=5): weight = tf.constant([0.0448, 0.2856, 0.3001, 0.2363, 0.1333], dtype=tf.float32) mssim = [] mcs = [] for l in range(level): ssim_map, cs_map = tf_ssim(img1, img2, cs_map=True, mean_metric=False) mssim.append(tf.reduce_mean(ssim_map)) mcs.append(tf.reduce_mean(cs_map)) filtered_im1 = tf.nn.avg_pool(img1, [1, 2, 2, 1], [1, 2, 2, 1], padding='SAME') filtered_im2 = tf.nn.avg_pool(img2, [1, 2, 2, 1], [1, 2, 2, 1], padding='SAME') img1 = filtered_im1 img2 = filtered_im2 # list to tensor of dim D+1 mssim = tf.pack(mssim, axis=0) mcs = tf.pack(mcs, axis=0) value = (tf.reduce_prod( mcs[0:level-1]**weight[0:level-1]) * (mssim[level-1]**weight[level-1])) if mean_metric: value = tf.reduce_mean(value) return value
[ "tensorflow.image.rgb_to_grayscale", "tensorflow.reduce_sum", "tensorflow.reduce_mean", "numpy.expand_dims", "tensorflow.constant", "tensorflow.tile", "tensorflow.nn.avg_pool", "tensorflow.exp", "tensorflow.nn.conv2d", "tensorflow.reduce_prod", "tensorflow.pack" ]
[((257, 288), 'numpy.expand_dims', 'np.expand_dims', (['x_data'], {'axis': '(-1)'}), '(x_data, axis=-1)\n', (271, 288), True, 'import numpy as np\n'), ((302, 333), 'numpy.expand_dims', 'np.expand_dims', (['x_data'], {'axis': '(-1)'}), '(x_data, axis=-1)\n', (316, 333), True, 'import numpy as np\n'), ((348, 379), 'numpy.expand_dims', 'np.expand_dims', (['y_data'], {'axis': '(-1)'}), '(y_data, axis=-1)\n', (362, 379), True, 'import numpy as np\n'), ((393, 424), 'numpy.expand_dims', 'np.expand_dims', (['y_data'], {'axis': '(-1)'}), '(y_data, axis=-1)\n', (407, 424), True, 'import numpy as np\n'), ((434, 471), 'tensorflow.constant', 'tf.constant', (['x_data'], {'dtype': 'tf.float32'}), '(x_data, dtype=tf.float32)\n', (445, 471), True, 'import tensorflow as tf\n'), ((480, 517), 'tensorflow.constant', 'tf.constant', (['y_data'], {'dtype': 'tf.float32'}), '(y_data, dtype=tf.float32)\n', (491, 517), True, 'import tensorflow as tf\n'), ((527, 576), 'tensorflow.exp', 'tf.exp', (['(-((x ** 2 + y ** 2) / (2.0 * sigma ** 2)))'], {}), '(-((x ** 2 + y ** 2) / (2.0 * sigma ** 2)))\n', (533, 576), True, 'import tensorflow as tf\n'), ((575, 600), 'tensorflow.tile', 'tf.tile', (['g', '[1, 1, ch, 1]'], {}), '(g, [1, 1, ch, 1])\n', (582, 600), True, 'import tensorflow as tf\n'), ((724, 755), 'tensorflow.image.rgb_to_grayscale', 'tf.image.rgb_to_grayscale', (['img1'], {}), '(img1)\n', (749, 755), True, 'import tensorflow as tf\n'), ((767, 798), 'tensorflow.image.rgb_to_grayscale', 'tf.image.rgb_to_grayscale', (['img2'], {}), '(img2)\n', (792, 798), True, 'import tensorflow as tf\n'), ((1089, 1154), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (['img1', 'window'], {'strides': '[1, 1, 1, 1]', 'padding': '"""VALID"""'}), "(img1, window, strides=[1, 1, 1, 1], padding='VALID')\n", (1101, 1154), True, 'import tensorflow as tf\n'), ((1165, 1230), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (['img2', 'window'], {'strides': '[1, 1, 1, 1]', 'padding': '"""VALID"""'}), "(img2, window, strides=[1, 1, 1, 1], padding='VALID')\n", (1177, 1230), True, 'import tensorflow as tf\n'), ((2176, 2247), 'tensorflow.constant', 'tf.constant', (['[0.0448, 0.2856, 0.3001, 0.2363, 0.1333]'], {'dtype': 'tf.float32'}), '([0.0448, 0.2856, 0.3001, 0.2363, 0.1333], dtype=tf.float32)\n', (2187, 2247), True, 'import tensorflow as tf\n'), ((2749, 2771), 'tensorflow.pack', 'tf.pack', (['mssim'], {'axis': '(0)'}), '(mssim, axis=0)\n', (2756, 2771), True, 'import tensorflow as tf\n'), ((2782, 2802), 'tensorflow.pack', 'tf.pack', (['mcs'], {'axis': '(0)'}), '(mcs, axis=0)\n', (2789, 2802), True, 'import tensorflow as tf\n'), ((617, 633), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['g'], {}), '(g)\n', (630, 633), True, 'import tensorflow as tf\n'), ((1311, 1383), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (['(img1 * img1)', 'window'], {'strides': '[1, 1, 1, 1]', 'padding': '"""VALID"""'}), "(img1 * img1, window, strides=[1, 1, 1, 1], padding='VALID')\n", (1323, 1383), True, 'import tensorflow as tf\n'), ((1436, 1508), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (['(img2 * img2)', 'window'], {'strides': '[1, 1, 1, 1]', 'padding': '"""VALID"""'}), "(img2 * img2, window, strides=[1, 1, 1, 1], padding='VALID')\n", (1448, 1508), True, 'import tensorflow as tf\n'), ((1559, 1631), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (['(img1 * img2)', 'window'], {'strides': '[1, 1, 1, 1]', 'padding': '"""VALID"""'}), "(img1 * img2, window, strides=[1, 1, 1, 1], padding='VALID')\n", (1571, 1631), True, 'import tensorflow as tf\n'), ((2067, 2088), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['value'], {}), '(value)\n', (2081, 2088), True, 'import tensorflow as tf\n'), ((2495, 2559), 'tensorflow.nn.avg_pool', 'tf.nn.avg_pool', (['img1', '[1, 2, 2, 1]', '[1, 2, 2, 1]'], {'padding': '"""SAME"""'}), "(img1, [1, 2, 2, 1], [1, 2, 2, 1], padding='SAME')\n", (2509, 2559), True, 'import tensorflow as tf\n'), ((2583, 2647), 'tensorflow.nn.avg_pool', 'tf.nn.avg_pool', (['img2', '[1, 2, 2, 1]', '[1, 2, 2, 1]'], {'padding': '"""SAME"""'}), "(img2, [1, 2, 2, 1], [1, 2, 2, 1], padding='SAME')\n", (2597, 2647), True, 'import tensorflow as tf\n'), ((2817, 2872), 'tensorflow.reduce_prod', 'tf.reduce_prod', (['(mcs[0:level - 1] ** weight[0:level - 1])'], {}), '(mcs[0:level - 1] ** weight[0:level - 1])\n', (2831, 2872), True, 'import tensorflow as tf\n'), ((2950, 2971), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['value'], {}), '(value)\n', (2964, 2971), True, 'import tensorflow as tf\n'), ((2403, 2427), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['ssim_map'], {}), '(ssim_map)\n', (2417, 2427), True, 'import tensorflow as tf\n'), ((2448, 2470), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['cs_map'], {}), '(cs_map)\n', (2462, 2470), True, 'import tensorflow as tf\n')]
import train_keras from keras.models import load_model import os import numpy as np import pandas as pd from tqdm import tqdm from keras.callbacks import ModelCheckpoint import sys TF_CPP_MIN_LOG_LEVEL=2 TEST_BATCH = 128 def load_params(): X_test = os.listdir('./test-jpg') X_test = [fn.replace('.jpg', '') for fn in X_test] model = load_model('model_amazon6.h5', custom_objects={'fbeta': train_keras.fbeta}) with open('tag_columns.txt', 'r') as f: tag_columns = f.read().split('\n') return X_test, model, tag_columns def prediction(X_test, model, tag_columns, test_folder): result = [] for i in tqdm(range(0, len(X_test), TEST_BATCH)): X_batch = X_test[i:i+TEST_BATCH] X_batch = np.array([train_keras.preprocess(train_keras.load_image(fn, folder=test_folder)) for fn in X_batch]) p = model.predict(X_batch) result.append(p) r = np.concatenate(result) r = r > 0.5 table = [] for row in r: t = [] for b, v in zip(row, tag_columns): if b: t.append(v.replace('tag_', '')) table.append(' '.join(t)) print('Prediction done !') return table def launch(test_folder): X_test, model, tag_columns = load_params() table = prediction(X_test, model, tag_columns, test_folder) try: df_pred = pd.DataFrame.from_dict({'image_name': X_test, 'tags': table}) df_pred.to_csv('submission9.csv', index=False) except: np.save('image_name', X_test) np.save('table', table) if __name__ == '__main__': if len(sys.argv) > 1: test_folder = sys.argv[1] else: test_folder='test-jpg' launch(test_folder)
[ "keras.models.load_model", "numpy.save", "train_keras.load_image", "pandas.DataFrame.from_dict", "os.listdir", "numpy.concatenate" ]
[((255, 279), 'os.listdir', 'os.listdir', (['"""./test-jpg"""'], {}), "('./test-jpg')\n", (265, 279), False, 'import os\n'), ((347, 422), 'keras.models.load_model', 'load_model', (['"""model_amazon6.h5"""'], {'custom_objects': "{'fbeta': train_keras.fbeta}"}), "('model_amazon6.h5', custom_objects={'fbeta': train_keras.fbeta})\n", (357, 422), False, 'from keras.models import load_model\n'), ((905, 927), 'numpy.concatenate', 'np.concatenate', (['result'], {}), '(result)\n', (919, 927), True, 'import numpy as np\n'), ((1347, 1408), 'pandas.DataFrame.from_dict', 'pd.DataFrame.from_dict', (["{'image_name': X_test, 'tags': table}"], {}), "({'image_name': X_test, 'tags': table})\n", (1369, 1408), True, 'import pandas as pd\n'), ((1484, 1513), 'numpy.save', 'np.save', (['"""image_name"""', 'X_test'], {}), "('image_name', X_test)\n", (1491, 1513), True, 'import numpy as np\n'), ((1522, 1545), 'numpy.save', 'np.save', (['"""table"""', 'table'], {}), "('table', table)\n", (1529, 1545), True, 'import numpy as np\n'), ((768, 814), 'train_keras.load_image', 'train_keras.load_image', (['fn'], {'folder': 'test_folder'}), '(fn, folder=test_folder)\n', (790, 814), False, 'import train_keras\n')]
# -*- coding: utf-8 -*- # # BRAINS # (B)LR (R)everberation-mapping (A)nalysis (I)n AGNs with (N)ested (S)ampling # <NAME>, <EMAIL> # Thu, Aug 4, 2016 # import os import sys import corner import numpy as np import configparser as cp import matplotlib.pyplot as plt __all__ = ['plotbackend'] class plotbackend: """ plot backend for BRAINS """ def __init__(self, fname="../src/param", fopt=""): # setup param self.param_file = fname self._param_parser(self.param_file) self.file_dir = self.param['filedir']+"/" # setup options if fopt == "": if self.param['flagdim'] == '-2': self.option_file = "" elif self.param['flagdim'] == '-1': self.option_file = self.file_dir + "/src/OPTIONSCON" elif self.param['flagdim'] == '0': self.option_file = self.file_dir + "/src/OPTIONSCON" elif self.param['flagdim'] == '1': self.option_file = self.file_dir + "/src/OPTIONS1D" elif self.param['flagdim'] == '2': self.option_file = self.file_dir + "/src/OPTIONS2D" elif self.param['flagdim'] == '3': self.option_file = self.file_dir + "/src/OPTIONSSA" elif self.param['flagdim'] == '4': self.option_file = self.file_dir + "/src/OPTIONSSA1D" elif self.param['flagdim'] == '5': self.option_file = self.file_dir + "/src/OPTIONSSA2D" if self.option_file != "": self._option_load(self.option_file) self._get_sample_size() else: self.sample_size = 0 else: self.set_option_file(fopt) def _option_load(self, fname): """ load option file """ with open(fname, "r") as f: lines = f.readlines() # negect comments i=0 for line in lines: if line[0] == '#' or len(line.strip()) == 0: i+=1 option={} option['num_particles'] = int(lines[i].split()[0]) i+=1 option['new_level_interval'] = int(lines[i].split()[0]) i+=1 option['save_interval'] = int(lines[i].split()[0]) i+=1 option['thread_step'] = int(lines[i].split()[0]) i+=1 option['num_levels'] = int(lines[i].split()[0]) i+=1 option['lambda'] = int(lines[i].split()[0]) i+=1 option['beta'] = int(lines[i].split()[0]) i+=1 option['num_saves'] = int(lines[i].split()[0]) i+=1 option['file_sample'] = lines[i].split()[0] i+=1 option['file_sample_info'] = lines[i].split()[0] i+=1 option['file_levels'] = lines[i].split()[0] i+=1 option['file_sampler_state'] = lines[i].split()[0] i+=1 option['file_post_sample'] = lines[i].split()[0] i+=1 option['file_post_sample_info'] = lines[i].split()[0] i+=1 option['file_limits'] = lines[i].split()[0] self.option = option def _param_parser(self, fname): """ parse parameter file """ config = cp.RawConfigParser(delimiters=' ', comment_prefixes='%', inline_comment_prefixes='%', default_section=cp.DEFAULTSECT, empty_lines_in_values=False) with open(fname) as f: file_content = '[dump]\n' + f.read() config.read_string(file_content) # check the absolute path if os.path.isabs(config['dump']['filedir']) == False: raise Exception("FileDir in %s is not an absoulte path.\n"%self.param_file) self.param = config['dump'] def _get_sample_size(self): """ load results """ with open(self.file_dir+self.option['file_post_sample']) as f: self.sample_size = int(f.readline().split()[1]) def set_param_file(self, fname): """ set parameter file """ self.param_file = fname self._param_parser(fname) self.file_dir = self.param['filedir']+"/" return def set_option_file(self, fname): """ set option file """ self.option_file = fname self._option_load(fname) self._get_sample_size() return def load_results(self): """ load results """ self.results={} if self.param['flagdim'] == '-2': self.results['con_sim'] = np.loadtxt(self.file_dir+"data/sim_con.txt") self.results['line_sim'] = np.loadtxt(self.file_dir+"data/sim_hb.txt") self.results['line2d_sim'] = np.loadtxt(self.file_dir+"data/sim_hb2d.txt") elif self.param['flagdim'] == '-1': self.results['con_data'] = np.loadtxt(self.file_dir+self.param['continuumfile']) self.results['con_sim'] = np.loadtxt(self.file_dir+"data/sim_con.txt") self.results['line_sim'] = np.loadtxt(self.file_dir+"data/sim_hb.txt") self.results['line2d_sim'] = np.loadtxt(self.file_dir+"data/sim_hb2d.txt") elif self.param['flagdim'] == '0': self.results['sample'] = np.loadtxt(self.file_dir + self.option['file_post_sample']) self.results['con_data'] = np.loadtxt(self.file_dir+self.param['continuumfile']) self.results['con_rec'] = np.loadtxt(self.file_dir+"data/con_rec.txt") return def plot_drw_parameters(self): if self.param['flagdim'] == '3' or self.param['flagdim'] == '-2': raise Exception("FlagDim=%d, no DRW parameters.\n"%self.param['flagdim']) sample = self.results['sample'] fig = corner.corner(sample[:, 1:3], smooth=True, smooth1d=True, labels=[r"$\ln(\hat\sigma)$", r"$\ln(\tau)$"]) return fig def plot_con_rec(self): if self.param['flagdim'] == '3' or self.param['flagdim'] == '-2': raise Exception("FlagDim=%d, no continuum reconstruction.\n"%self.param['flagdim']) con_data = self.results['con_data'] con = self.results['con_rec'] offset = int(con.shape[0]/self.sample_size) fig, ax = plt.subplots(1,1) ax.errorbar(con_data[:, 0], con_data[:, 1], yerr = con_data[:, 2], ls='none', marker='o', label='Data') for i in np.random.randint(self.sample_size, size=np.min((100, self.sample_size))): plt.plot(con[i*offset:(i+1)*offset, 0], con[i*offset:(i+1)*offset, 1], lw=0.2) ax.set_xlabel('Time') ax.set_ylabel('Flux') ax.legend() return fig
[ "os.path.isabs", "corner.corner", "matplotlib.pyplot.plot", "configparser.RawConfigParser", "numpy.min", "numpy.loadtxt", "matplotlib.pyplot.subplots" ]
[((2873, 3027), 'configparser.RawConfigParser', 'cp.RawConfigParser', ([], {'delimiters': '""" """', 'comment_prefixes': '"""%"""', 'inline_comment_prefixes': '"""%"""', 'default_section': 'cp.DEFAULTSECT', 'empty_lines_in_values': '(False)'}), "(delimiters=' ', comment_prefixes='%',\n inline_comment_prefixes='%', default_section=cp.DEFAULTSECT,\n empty_lines_in_values=False)\n", (2891, 3027), True, 'import configparser as cp\n'), ((5179, 5291), 'corner.corner', 'corner.corner', (['sample[:, 1:3]'], {'smooth': '(True)', 'smooth1d': '(True)', 'labels': "['$\\\\ln(\\\\hat\\\\sigma)$', '$\\\\ln(\\\\tau)$']"}), "(sample[:, 1:3], smooth=True, smooth1d=True, labels=[\n '$\\\\ln(\\\\hat\\\\sigma)$', '$\\\\ln(\\\\tau)$'])\n", (5192, 5291), False, 'import corner\n'), ((5631, 5649), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {}), '(1, 1)\n', (5643, 5649), True, 'import matplotlib.pyplot as plt\n'), ((3178, 3218), 'os.path.isabs', 'os.path.isabs', (["config['dump']['filedir']"], {}), "(config['dump']['filedir'])\n", (3191, 3218), False, 'import os\n'), ((4059, 4105), 'numpy.loadtxt', 'np.loadtxt', (["(self.file_dir + 'data/sim_con.txt')"], {}), "(self.file_dir + 'data/sim_con.txt')\n", (4069, 4105), True, 'import numpy as np\n'), ((4137, 4182), 'numpy.loadtxt', 'np.loadtxt', (["(self.file_dir + 'data/sim_hb.txt')"], {}), "(self.file_dir + 'data/sim_hb.txt')\n", (4147, 4182), True, 'import numpy as np\n'), ((4216, 4263), 'numpy.loadtxt', 'np.loadtxt', (["(self.file_dir + 'data/sim_hb2d.txt')"], {}), "(self.file_dir + 'data/sim_hb2d.txt')\n", (4226, 4263), True, 'import numpy as np\n'), ((5851, 5945), 'matplotlib.pyplot.plot', 'plt.plot', (['con[i * offset:(i + 1) * offset, 0]', 'con[i * offset:(i + 1) * offset, 1]'], {'lw': '(0.2)'}), '(con[i * offset:(i + 1) * offset, 0], con[i * offset:(i + 1) *\n offset, 1], lw=0.2)\n', (5859, 5945), True, 'import matplotlib.pyplot as plt\n'), ((4336, 4391), 'numpy.loadtxt', 'np.loadtxt', (["(self.file_dir + self.param['continuumfile'])"], {}), "(self.file_dir + self.param['continuumfile'])\n", (4346, 4391), True, 'import numpy as np\n'), ((4422, 4468), 'numpy.loadtxt', 'np.loadtxt', (["(self.file_dir + 'data/sim_con.txt')"], {}), "(self.file_dir + 'data/sim_con.txt')\n", (4432, 4468), True, 'import numpy as np\n'), ((4500, 4545), 'numpy.loadtxt', 'np.loadtxt', (["(self.file_dir + 'data/sim_hb.txt')"], {}), "(self.file_dir + 'data/sim_hb.txt')\n", (4510, 4545), True, 'import numpy as np\n'), ((4579, 4626), 'numpy.loadtxt', 'np.loadtxt', (["(self.file_dir + 'data/sim_hb2d.txt')"], {}), "(self.file_dir + 'data/sim_hb2d.txt')\n", (4589, 4626), True, 'import numpy as np\n'), ((5811, 5842), 'numpy.min', 'np.min', (['(100, self.sample_size)'], {}), '((100, self.sample_size))\n', (5817, 5842), True, 'import numpy as np\n'), ((4700, 4759), 'numpy.loadtxt', 'np.loadtxt', (["(self.file_dir + self.option['file_post_sample'])"], {}), "(self.file_dir + self.option['file_post_sample'])\n", (4710, 4759), True, 'import numpy as np\n'), ((4793, 4848), 'numpy.loadtxt', 'np.loadtxt', (["(self.file_dir + self.param['continuumfile'])"], {}), "(self.file_dir + self.param['continuumfile'])\n", (4803, 4848), True, 'import numpy as np\n'), ((4879, 4925), 'numpy.loadtxt', 'np.loadtxt', (["(self.file_dir + 'data/con_rec.txt')"], {}), "(self.file_dir + 'data/con_rec.txt')\n", (4889, 4925), True, 'import numpy as np\n')]
import sys import os import numpy as np import random from collections import OrderedDict import pickle import datetime from tqdm import tqdm from recordclass import recordclass import math import torch import torch.autograd as autograd import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import json # Helper funcs def custom_print(*msg): for i in range(0, len(msg)): if i == len(msg) - 1: print(msg[i]) logger.write(str(msg[i]) + '\n') else: print(msg[i], ' ', end='') logger.write(str(msg[i])) def load_word_embedding(embed_file, vocab): custom_print('vocab length:', len(vocab)) embed_vocab = OrderedDict() rev_embed_vocab = OrderedDict() embed_matrix = list() embed_vocab['<PAD>'] = 0 rev_embed_vocab[0] = '<PAD>' embed_matrix.append(np.zeros(word_embed_dim, dtype=np.float32)) embed_vocab['<UNK>'] = 1 rev_embed_vocab[1] = '<UNK>' embed_matrix.append(np.random.uniform(-0.25, 0.25, word_embed_dim)) embed_vocab['<SOS>'] = 2 rev_embed_vocab[2] = '<SOS>' embed_matrix.append(np.random.uniform(-0.25, 0.25, word_embed_dim)) embed_vocab['<EOS>'] = 3 rev_embed_vocab[3] = '<EOS>' embed_matrix.append(np.random.uniform(-0.25, 0.25, word_embed_dim)) word_idx = 4 with open(embed_file, "r") as f: for line in f: parts = line.split() if len(parts) < word_embed_dim + 1: continue word = parts[0] if word in vocab and vocab[word] >= word_min_freq: vec = [np.float32(val) for val in parts[1:]] embed_matrix.append(vec) embed_vocab[word] = word_idx rev_embed_vocab[word_idx] = word word_idx += 1 for word in vocab: if word not in embed_vocab and vocab[word] >= word_min_freq: embed_matrix.append(np.random.uniform(-0.25, 0.25, word_embed_dim)) embed_vocab[word] = word_idx rev_embed_vocab[word_idx] = word word_idx += 1 custom_print('embed dictionary length:', len(embed_vocab)) return embed_vocab, rev_embed_vocab, np.array(embed_matrix, dtype=np.float32) def build_vocab(data, events, arguments, roles, vocab_file, embed_file): vocab = OrderedDict() char_v = OrderedDict() char_v['<PAD>'] = 0 char_v['<UNK>'] = 1 char_v[';'] = 2 char_v['|'] = 3 char_idx = 4 for d in data: for word in d.SrcWords: if word not in vocab: vocab[word] = 1 else: vocab[word] += 1 for c in word: if c not in char_v: char_v[c] = char_idx char_idx += 1 for event in events: vocab[event] = word_min_freq for argument in arguments: vocab[argument] = word_min_freq for role in roles: vocab[role] = word_min_freq vocab[';'] = word_min_freq vocab['|'] = word_min_freq word_v, rev_word_v, embed_matrix = load_word_embedding(embed_file, vocab) output = open(vocab_file, 'wb') pickle.dump([word_v, char_v], output) output.close() return word_v, rev_word_v, char_v, embed_matrix def load_vocab(vocab_file): with open(vocab_file, 'rb') as f: word_v, char_v = pickle.load(f) return word_v, char_v def get_adj_mat(amat): K = 5 adj_mat = np.zeros((len(amat), len(amat)), np.float32) for i in range(len(amat)): for j in range(len(amat)): if 0 <= amat[i][j] <= K: adj_mat[i][j] = 1.0 / math.pow(2, amat[i][j]) else: adj_mat[i][j] = 0 return adj_mat def get_data(src_lines, trg_lines, datatype): samples = [] uid = 1 src_len = -1 trg_len = -1 for i in range(0, len(src_lines)): src_line = src_lines[i].strip() trg_line = trg_lines[i].strip() src_words = src_line.split() if datatype == 1: tuples = trg_line.strip().split('|') random.shuffle(tuples) new_trg_line = ' | '.join(tuples) assert len(trg_line.split()) == len(new_trg_line.split()) trg_line = new_trg_line trg_words = list() trg_words.append('<SOS>') trg_words += trg_line.split() trg_words.append('<EOS>') if datatype == 1 and (len(src_words) > max_src_len or len(trg_words) > max_trg_len + 1): continue if len(src_words) > src_len: src_len = len(src_words) if len(trg_words) > trg_len: trg_len = len(trg_words) sample = Sample(Id=uid, SrcLen=len(src_words), SrcWords=src_words, TrgLen=len(trg_words), TrgWords=trg_words) #c samples.append(sample) uid += 1 print(src_len) print(trg_len) return samples def read_data(src_file, trg_file, datatype): reader = open(src_file) src_lines = reader.readlines() reader.close() reader = open(trg_file) trg_lines = reader.readlines() reader.close() # tot_len = 100 # src_lines = src_lines[0:min(tot_len, len(src_lines))] # trg_lines = trg_lines[0:min(tot_len, len(trg_lines))] # adj_lines = adj_lines[0:min(tot_len, len(adj_lines))] data = get_data(src_lines, trg_lines, datatype) return data #event_lines, argument_lines, roles_lines # to add option for less detailed checks def check_event_trigger(ref_string, pred_string): return (ref_string == pred_string) pass def check_event_type(ref_string, pred_string, event_lines): if granular_mode == 0: if pred_string in event_lines: return (ref_string == pred_string) else: # print("invalid prediction") return False pass if granular_mode == 1: pred_token = pred_string.split(":")[0] ref_token = ref_string.split(":")[0] return (pred_token == ref_token) pass def check_event_argument(ref_string, pred_string): return (ref_string == pred_string) pass def check_argument_type(ref_string, pred_string, argument_lines): if granular_mode == 0: if pred_string in argument_lines: return (ref_string == pred_string) else: # print("invalid prediction") return False pass if granular_mode == 1: pred_token = pred_string.split(":")[0] ref_token = ref_string.split(":")[0] return (pred_token == ref_token) pass def check_argument_role(ref_string, pred_string, roles_lines): if pred_string in roles_lines: return (ref_string == pred_string) else: # print("invalid prediction") return False pass def calculate_f1(ref_lines, pred_lines, event_lines, argument_lines, roles_lines): list_of_tracking_metrics = ['predicted_tuples', 'ground_truth_tuples', 'correct_predictions', 'events_count', 'correct_events', 'correct_event_type', 'correct_arguments', 'correct_argment_types', 'correct_argument_roles' ] metric_counts = dict.fromkeys(list_of_tracking_metrics, 0) for i in range(0, min(len(ref_lines), len(pred_lines))): ref_line = ref_lines[i].strip() pred_line = pred_lines[i].strip() ref_tuples = ref_line.split('|') pred_tuples = pred_line.split('|') # find a way to compare multiple tuples # correct - t1 | t2 | t3 # pred - p1 | p2 # postives = 3 [number of ground truths minus nones] # predicted_pos = 2 [number of preds minus nones] # TP = correct preds # TP + FP = predicted # TP + FN = positives # Precision = correct / predicted_pos # Recall = correct / positives # f = pr/p+r # handling repeated predictions # set_of_preds = set() # for pred_tuple in pred_tuples: # set_of_preds.add(pred_tuple.strip()) # pred_tuples = list(set_of_preds) for pred_tuple in pred_tuples: pred_strings = pred_tuple.split(';') if(len(pred_strings) < 3): continue # in the case of no argument detection, we only calculate the event trigger scores if(pred_strings[2].strip().lower()) == 'none': max_matches = 0 part_matches = [] for ref_tuple in ref_tuples: # ssss ev1, ev2 = cal_f1_for_pair(ref_tuple, pred_tuple, event_lines) pair_score = ev1+ev2 if pair_score > max_matches: max_matches = pair_score part_matches = (ev1, ev2) pass pass metric_counts['events_count'] += 1 if ev1 == 1: metric_counts['correct_events'] += 1 if ev2 == 1: metric_counts['correct_event_type'] += 1 continue max_matches = 0 part_matches = cal_f1_for_tuple(ref_tuples[0], pred_tuple, event_lines, argument_lines, roles_lines) for ref_tuple in ref_tuples: res = cal_f1_for_tuple(ref_tuple, pred_tuple, event_lines, argument_lines, roles_lines) tuple_score = sum(res) if tuple_score >= max_matches: max_matches = tuple_score part_matches = res pass pass metric_counts['predicted_tuples'] += 1 metric_counts['events_count'] += 1 if max_matches >= 4: metric_counts['correct_predictions'] += 1 if part_matches[0] == 1: metric_counts['correct_events'] += 1 if part_matches[1] == 1: metric_counts['correct_event_type'] += 1 if part_matches[2] == 1: metric_counts['correct_arguments'] += 1 if part_matches[3] == 1: metric_counts['correct_argment_types'] += 1 if part_matches[4] == 1: metric_counts['correct_argument_roles'] += 1 pass for ref_tuple in ref_tuples: if(ref_tuple.split(';')[2].strip().lower()) != 'none': metric_counts['ground_truth_tuples'] += 1 pass print(metric_counts) precision = float(metric_counts['correct_predictions'] / (metric_counts['predicted_tuples'] + 1e-08)) recall = float(metric_counts['correct_predictions'] / (metric_counts['ground_truth_tuples'] + 1e-08)) f1 = 2 * precision * recall / (precision + recall + 1e-08) precision = round(precision, 3) recall = round(recall, 3) f1 = round(f1, 3) print("Partwise Results") event_acc = metric_counts['correct_events']/ (metric_counts['events_count'] + 1e-08) evtype_acc = metric_counts['correct_event_type']/ (metric_counts['events_count'] + 1e-08) argument_acc = metric_counts['correct_arguments']/ (metric_counts['predicted_tuples'] + 1e-08) argtype_acc = metric_counts['correct_argment_types']/ (metric_counts['predicted_tuples'] + 1e-08) role_acc = metric_counts['correct_argument_roles']/ (metric_counts['predicted_tuples'] + 1e-08) print(f'Event Trigger Word Accuracy: {event_acc}') print(f'Event Type Accuracy: {evtype_acc}') print(f'Argument Identification Accuracy: {argument_acc}') print(f'Argument Type Accuracy: {argtype_acc}') print(f'Argument Role Accuracy: {role_acc}') print(f'Macro f-score: {f1}') targ_file = os.path.join(trg_data_folder, 'Results_logger.txt') f = open(targ_file, "a") f.write(f'Event Trigger Word Accuracy: {event_acc}') f.write("\n") f.write(f'Event Type Accuracy: {evtype_acc}') f.write("\n") f.write(f'Argument Identification Accuracy: {argument_acc}') f.write("\n") f.write(f'Argument Type Accuracy: {argtype_acc}') f.write("\n") f.write(f'Argument Role Accuracy: {role_acc}') f.write("\n") f.write(f'Macro f-score: {f1}') f.write("\n") f.close() return f1 def cal_f1_for_pair(ref_tuple: str , pred_tuple: str, event_lines: list ) -> list: ref_strings = ref_tuple.split(';') pred_strings = pred_tuple.split(';') ev1 = int( check_event_trigger(ref_strings[0].strip(), pred_strings[0].strip()) ) ev2 = int( check_event_type(ref_strings[1].strip(), pred_strings[1].strip(), event_lines) ) return ev1, ev2 def cal_f1_for_tuple(ref_tuple: str , pred_tuple: str, event_lines: list, argument_lines: list, roles_lines: list ) -> list: ref_strings = ref_tuple.split(';') pred_strings = pred_tuple.split(';') if (len (pred_strings) != 5 ): if (len (pred_strings) >= 2 ): ev1 = int( check_event_trigger(ref_strings[0].strip(), pred_strings[0].strip()) ) ev2 = int( check_event_type(ref_strings[1].strip(), pred_strings[1].strip(), event_lines) ) return [ev1, ev2, 0, 0, 0] return list([0,0,0,0,0]) ev1 = int( check_event_trigger(ref_strings[0].strip(), pred_strings[0].strip()) ) ev2 = int( check_event_type(ref_strings[1].strip(), pred_strings[1].strip(), event_lines) ) ev3 = int( check_event_argument(ref_strings[2].strip(), pred_strings[2].strip()) ) ev4 = int( check_argument_type(ref_strings[3].strip(), pred_strings[3].strip(), argument_lines) ) ev5 = int( check_argument_role(ref_strings[4].strip(), pred_strings[4].strip(), roles_lines) ) ret = [ev1, ev2, ev3, ev4, ev5] return ret def get_model(model_id): if model_id == 1: return SeqToSeqModel() def write_test_res(data, preds, attns, outfile): writer = open(outfile, 'w') for i in range(0, len(data)): pred_words = get_pred_words(preds[i], attns[i], data[i].SrcWords)[:-1] writer.write(' '.join(pred_words) + '\n') writer.close() def set_random_seeds(seed): random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) if n_gpu > 1: torch.cuda.manual_seed_all(seed) def get_max_len(sample_batch): src_max_len = len(sample_batch[0].SrcWords) for idx in range(1, len(sample_batch)): if len(sample_batch[idx].SrcWords) > src_max_len: src_max_len = len(sample_batch[idx].SrcWords) trg_max_len = len(sample_batch[0].TrgWords) for idx in range(1, len(sample_batch)): if len(sample_batch[idx].TrgWords) > trg_max_len: trg_max_len = len(sample_batch[idx].TrgWords) return src_max_len, trg_max_len def get_words_index_seq(words, max_len): seq = list() for word in words: if word in word_vocab: seq.append(word_vocab[word]) else: seq.append(word_vocab['<UNK>']) pad_len = max_len - len(words) for i in range(0, pad_len): seq.append(word_vocab['<PAD>']) return seq def get_target_words_index_seq(words, max_len): seq = list() for word in words: if word in word_vocab: seq.append(word_vocab[word]) else: seq.append(word_vocab['<UNK>']) pad_len = max_len - len(words) for i in range(0, pad_len): seq.append(word_vocab['<EOS>']) return seq def get_padded_mask(cur_len, max_len): mask_seq = list() for i in range(0, cur_len): mask_seq.append(0) pad_len = max_len - cur_len for i in range(0, pad_len): mask_seq.append(1) return mask_seq def get_target_vocab_mask(src_words): mask = [] for i in range(0, len(word_vocab)): mask.append(1) for word in src_words: if word in word_vocab: mask[word_vocab[word]] = 0 # events, arguments, roles for event in events: mask[word_vocab[event]] = 0 for argument in arguments: mask[word_vocab[argument]] = 0 for role in roles: mask[word_vocab[role]] = 0 mask[word_vocab['<UNK>']] = 0 mask[word_vocab['<EOS>']] = 0 mask[word_vocab[';']] = 0 mask[word_vocab['|']] = 0 return mask def get_rel_mask(trg_words, max_len): mask_seq = list() for word in trg_words: mask_seq.append(0) # if word in relations: # mask_seq.append(0) # else: # mask_seq.append(1) pad_len = max_len - len(trg_words) for i in range(0, pad_len): mask_seq.append(1) return mask_seq def get_char_seq(words, max_len): char_seq = list() for i in range(0, conv_filter_size - 1): char_seq.append(char_vocab['<PAD>']) for word in words: for c in word[0:min(len(word), max_word_len)]: if c in char_vocab: char_seq.append(char_vocab[c]) else: char_seq.append(char_vocab['<UNK>']) pad_len = max_word_len - len(word) for i in range(0, pad_len): char_seq.append(char_vocab['<PAD>']) for i in range(0, conv_filter_size - 1): char_seq.append(char_vocab['<PAD>']) pad_len = max_len - len(words) for i in range(0, pad_len): for i in range(0, max_word_len + conv_filter_size - 1): char_seq.append(char_vocab['<PAD>']) return char_seq def get_relations(file_name): rels = [] reader = open(file_name) lines = reader.readlines() reader.close() for line in lines: rels.append(line.strip()) return rels def get_batch_data(cur_samples, is_training=False): """ Returns the training samples and labels as numpy array """ batch_src_max_len, batch_trg_max_len = get_max_len(cur_samples) src_words_list = list() src_words_mask_list = list() src_char_seq = list() trg_words_list = list() trg_vocab_mask = list() adj_lst = [] target = list() cnt = 0 for sample in cur_samples: src_words_list.append(get_words_index_seq(sample.SrcWords, batch_src_max_len)) src_words_mask_list.append(get_padded_mask(sample.SrcLen, batch_src_max_len)) src_char_seq.append(get_char_seq(sample.SrcWords, batch_src_max_len)) trg_vocab_mask.append(get_target_vocab_mask(sample.SrcWords)) # cur_masked_adj = np.zeros((batch_src_max_len, batch_src_max_len), dtype=np.float32) # cur_masked_adj[:len(sample.SrcWords), :len(sample.SrcWords)] = sample.AdjMat # adj_lst.append(cur_masked_adj) if is_training: padded_trg_words = get_words_index_seq(sample.TrgWords, batch_trg_max_len) trg_words_list.append(padded_trg_words) target.append(padded_trg_words[1:]) else: trg_words_list.append(get_words_index_seq(['<SOS>'], 1)) cnt += 1 return {'src_words': np.array(src_words_list, dtype=np.float32), 'src_chars': np.array(src_char_seq), 'src_words_mask': np.array(src_words_mask_list), 'adj': np.array(adj_lst), 'trg_vocab_mask': np.array(trg_vocab_mask), 'trg_words': np.array(trg_words_list, dtype=np.int32), 'target': np.array(target)} def shuffle_data(data): custom_print(len(data)) data.sort(key=lambda x: x.SrcLen) num_batch = int(len(data) / batch_size) rand_idx = random.sample(range(num_batch), num_batch) new_data = [] for idx in rand_idx: new_data += data[batch_size * idx: batch_size * (idx + 1)] if len(new_data) < len(data): new_data += data[num_batch * batch_size:] return new_data def get_pred_words(preds, attns, src_words): pred_words = [] for i in range(0, max_trg_len): word_idx = preds[i] if word_vocab['<EOS>'] == word_idx: pred_words.append('<EOS>') break elif att_type != 'None' and copy_on and word_vocab['<UNK>'] == word_idx: word_idx = attns[i] pred_words.append(src_words[word_idx]) else: pred_words.append(rev_word_vocab[word_idx]) return pred_words class WordEmbeddings(nn.Module): def __init__(self, vocab_size, embed_dim, pre_trained_embed_matrix, drop_out_rate): super(WordEmbeddings, self).__init__() self.embeddings = nn.Embedding(vocab_size, embed_dim, padding_idx=0) self.embeddings.weight.data.copy_(torch.from_numpy(pre_trained_embed_matrix)) self.dropout = nn.Dropout(drop_out_rate) def forward(self, words_seq): word_embeds = self.embeddings(words_seq) word_embeds = self.dropout(word_embeds) return word_embeds def weight(self): return self.embeddings.weight # Potentially use a pretrained BERT - 509 class CharEmbeddings(nn.Module): def __init__(self, vocab_size, embed_dim, drop_out_rate): super(CharEmbeddings, self).__init__() # Layers self.embeddings = nn.Embedding(vocab_size, embed_dim, padding_idx=0) self.dropout = nn.Dropout(drop_out_rate) def forward(self, words_seq): char_embeds = self.embeddings(words_seq) char_embeds = self.dropout(char_embeds) return char_embeds # DONT CHANGE CLASSES # 543 class Encoder(nn.Module): def __init__(self, input_dim, hidden_dim, layers, is_bidirectional, drop_out_rate): super(Encoder, self).__init__() self.input_dim = input_dim self.hidden_dim = hidden_dim self.layers = layers self.is_bidirectional = is_bidirectional self.drop_rate = drop_out_rate self.char_embeddings = CharEmbeddings(len(char_vocab), char_embed_dim, drop_rate) # Remove In case we want to BERT self.lstm = nn.LSTM(self.input_dim, self.hidden_dim, self.layers, batch_first=True, bidirectional=self.is_bidirectional) self.dropout = nn.Dropout(self.drop_rate) self.conv1d = nn.Conv1d(char_embed_dim, char_feature_size, conv_filter_size) self.max_pool = nn.MaxPool1d(max_word_len + conv_filter_size - 1, max_word_len + conv_filter_size - 1) def forward(self, words_input, char_seq, adj, is_training=False): char_embeds = self.char_embeddings(char_seq) char_embeds = char_embeds.permute(0, 2, 1) char_feature = torch.tanh(self.max_pool(self.conv1d(char_embeds))) char_feature = char_feature.permute(0, 2, 1) words_input = torch.cat((words_input, char_feature), -1) outputs, hc = self.lstm(words_input) outputs = self.dropout(outputs) return outputs # 597 class Attention(nn.Module): def __init__(self, input_dim): super(Attention, self).__init__() self.input_dim = input_dim self.linear_ctx = nn.Linear(self.input_dim, self.input_dim, bias=False) self.linear_query = nn.Linear(self.input_dim, self.input_dim, bias=True) self.v = nn.Linear(self.input_dim, 1) def forward(self, s_prev, enc_hs, src_mask): uh = self.linear_ctx(enc_hs) wq = self.linear_query(s_prev) wquh = torch.tanh(wq + uh) attn_weights = self.v(wquh).squeeze() attn_weights.data.masked_fill_(src_mask.data, -float('inf')) attn_weights = F.softmax(attn_weights, dim=-1) ctx = torch.bmm(attn_weights.unsqueeze(1), enc_hs).squeeze() return ctx, attn_weights # 617 class NGram_Attention(nn.Module): def __init__(self, input_dim, N): super(NGram_Attention, self).__init__() self.input_dim = input_dim self.layers = N self.V_layers = nn.ModuleList() self.W_layers = nn.ModuleList() for i in range(N): self.V_layers.append(nn.Linear(input_dim, input_dim)) self.W_layers.append(nn.Linear(input_dim, input_dim)) def forward(self, s_prev, enc_hs, src_mask): att = torch.bmm(s_prev.unsqueeze(1), self.V_layers[0](enc_hs).transpose(1, 2)).squeeze() att.data.masked_fill_(src_mask.data, -float('inf')) att = F.softmax(att, dim=-1) ctx = self.W_layers[0](torch.bmm(att.unsqueeze(1), enc_hs).squeeze()) for i in range(1, self.layers): enc_hs_ngram = torch.nn.AvgPool1d(i+1, 1)(enc_hs.transpose(1, 2)).transpose(1, 2) n_mask = src_mask.unsqueeze(1).float() n_mask = torch.nn.AvgPool1d(i+1, 1)(n_mask).squeeze() n_mask[n_mask > 0] = 1 n_mask = n_mask.byte() n_att = torch.bmm(s_prev.unsqueeze(1), self.V_layers[i](enc_hs_ngram).transpose(1, 2)).squeeze() n_att.data.masked_fill_(n_mask.data, -float('inf')) n_att = F.softmax(n_att, dim=-1) ctx += self.W_layers[i](torch.bmm(n_att.unsqueeze(1), enc_hs_ngram).squeeze()) return ctx, att # 588 def mean_over_time(x, mask): x.data.masked_fill_(mask.unsqueeze(2).data, 0) x = torch.sum(x, dim=1) time_steps = torch.sum(mask.eq(0), dim=1, keepdim=True).float() x /= time_steps return x # 645 class Decoder(nn.Module): def __init__(self, input_dim, hidden_dim, layers, drop_out_rate, max_length): super(Decoder, self).__init__() self.input_dim = input_dim self.hidden_dim = hidden_dim self.layers = layers self.drop_rate = drop_out_rate self.max_length = max_length if att_type == 'None': self.lstm = nn.LSTMCell(2 * self.input_dim, self.hidden_dim, self.layers) elif att_type == 'Unigram': self.attention = Attention(input_dim) self.lstm = nn.LSTMCell(2 * self.input_dim, self.hidden_dim, self.layers) else: self.attention = NGram_Attention(input_dim, 3) self.lstm = nn.LSTMCell(3 * self.input_dim, self.hidden_dim, self.layers) self.dropout = nn.Dropout(self.drop_rate) self.ent_out = nn.Linear(self.input_dim, len(word_vocab)) def forward(self, y_prev, h_prev, enc_hs, src_word_embeds, src_mask, is_training=False): src_time_steps = enc_hs.size()[1] if att_type == 'None': ctx = mean_over_time(enc_hs, src_mask) attn_weights = torch.zeros(src_mask.size()).cuda() elif att_type == 'Unigram': s_prev = h_prev[0] s_prev = s_prev.unsqueeze(1) s_prev = s_prev.repeat(1, src_time_steps, 1) ctx, attn_weights = self.attention(s_prev, enc_hs, src_mask) else: last_index = src_mask.size()[1] - torch.sum(src_mask, dim=-1).long() - 1 last_index = last_index.unsqueeze(1).unsqueeze(1).repeat(1, 1, enc_hs.size()[-1]) enc_last = torch.gather(enc_hs, 1, last_index).squeeze() ctx, attn_weights = self.attention(enc_last, src_word_embeds, src_mask) ctx = torch.cat((enc_last, ctx), -1) y_prev = y_prev.squeeze() s_cur = torch.cat((y_prev, ctx), 1) hidden, cell_state = self.lstm(s_cur, h_prev) hidden = self.dropout(hidden) output = self.ent_out(hidden) return output, (hidden, cell_state), attn_weights # 690 class SeqToSeqModel(nn.Module): def __init__(self): super(SeqToSeqModel, self).__init__() self.word_embeddings = WordEmbeddings(len(word_vocab), word_embed_dim, word_embed_matrix, drop_rate) self.encoder = Encoder(enc_inp_size, int(enc_hidden_size/2), layers, True, drop_rate) self.decoder = Decoder(dec_inp_size, dec_hidden_size, layers, drop_rate, max_trg_len) def forward(self, src_words_seq, src_chars_seq, src_mask, trg_words_seq, trg_vocab_mask, adj, is_training=False): src_word_embeds = self.word_embeddings(src_words_seq) trg_word_embeds = self.word_embeddings(trg_words_seq) batch_len = src_word_embeds.size()[0] if is_training: time_steps = trg_word_embeds.size()[1] - 1 else: time_steps = max_trg_len encoder_output = self.encoder(src_word_embeds, src_chars_seq, adj, is_training) h0 = autograd.Variable(torch.FloatTensor(torch.zeros(batch_len, word_embed_dim))) h0 = h0.cuda() c0 = autograd.Variable(torch.FloatTensor(torch.zeros(batch_len, word_embed_dim))) c0 = c0.cuda() dec_hid = (h0, c0) if is_training: dec_inp = trg_word_embeds[:, 0, :] dec_out, dec_hid, dec_attn = self.decoder(dec_inp, dec_hid, encoder_output, src_word_embeds, src_mask, is_training) dec_out = dec_out.view(-1, len(word_vocab)) dec_out = F.log_softmax(dec_out, dim=-1) dec_out = dec_out.unsqueeze(1) for t in range(1, time_steps): dec_inp = trg_word_embeds[:, t, :] cur_dec_out, dec_hid, dec_attn = self.decoder(dec_inp, dec_hid, encoder_output, src_word_embeds, src_mask, is_training) cur_dec_out = cur_dec_out.view(-1, len(word_vocab)) dec_out = torch.cat((dec_out, F.log_softmax(cur_dec_out, dim=-1).unsqueeze(1)), 1) else: dec_inp = trg_word_embeds[:, 0, :] dec_out, dec_hid, dec_attn = self.decoder(dec_inp, dec_hid, encoder_output, src_word_embeds, src_mask, is_training) dec_out = dec_out.view(-1, len(word_vocab)) if copy_on: dec_out.data.masked_fill_(trg_vocab_mask.data, -float('inf')) dec_out = F.log_softmax(dec_out, dim=-1) topv, topi = dec_out.topk(1) dec_out_v, dec_out_i = dec_out.topk(1) dec_attn_v, dec_attn_i = dec_attn.topk(1) for t in range(1, time_steps): dec_inp = self.word_embeddings(topi.squeeze().detach()) cur_dec_out, dec_hid, cur_dec_attn = self.decoder(dec_inp, dec_hid, encoder_output, src_word_embeds, src_mask, is_training) cur_dec_out = cur_dec_out.view(-1, len(word_vocab)) if copy_on: cur_dec_out.data.masked_fill_(trg_vocab_mask.data, -float('inf')) cur_dec_out = F.log_softmax(cur_dec_out, dim=-1) topv, topi = cur_dec_out.topk(1) cur_dec_out_v, cur_dec_out_i = cur_dec_out.topk(1) dec_out_i = torch.cat((dec_out_i, cur_dec_out_i), 1) cur_dec_attn_v, cur_dec_attn_i = cur_dec_attn.topk(1) dec_attn_i = torch.cat((dec_attn_i, cur_dec_attn_i), 1) if is_training: dec_out = dec_out.view(-1, len(word_vocab)) return dec_out else: return dec_out_i, dec_attn_i def predict(samples, model, model_id): pred_batch_size = batch_size batch_count = math.ceil(len(samples) / pred_batch_size) move_last_batch = False if len(samples) - batch_size * (batch_count - 1) == 1: move_last_batch = True batch_count -= 1 preds = list() attns = list() model.eval() set_random_seeds(random_seed) start_time = datetime.datetime.now() for batch_idx in tqdm(range(0, batch_count)): batch_start = batch_idx * pred_batch_size batch_end = min(len(samples), batch_start + pred_batch_size) if batch_idx == batch_count - 1 and move_last_batch: batch_end = len(samples) cur_batch = samples[batch_start:batch_end] cur_samples_input = get_batch_data(cur_batch, False) src_words_seq = torch.from_numpy(cur_samples_input['src_words'].astype('long')) src_words_mask = torch.from_numpy(cur_samples_input['src_words_mask'].astype('uint8')) trg_vocab_mask = torch.from_numpy(cur_samples_input['trg_vocab_mask'].astype('uint8')) trg_words_seq = torch.from_numpy(cur_samples_input['trg_words'].astype('long')) adj = torch.from_numpy(cur_samples_input['adj'].astype('float32')) src_chars_seq = torch.from_numpy(cur_samples_input['src_chars'].astype('long')) if torch.cuda.is_available(): src_words_seq = src_words_seq.cuda() src_words_mask = src_words_mask.cuda() trg_vocab_mask = trg_vocab_mask.cuda() trg_words_seq = trg_words_seq.cuda() adj = adj.cuda() src_chars_seq = src_chars_seq.cuda() src_words_seq = autograd.Variable(src_words_seq) src_words_mask = autograd.Variable(src_words_mask) trg_vocab_mask = autograd.Variable(trg_vocab_mask) adj = autograd.Variable(adj) src_chars_seq = autograd.Variable(src_chars_seq) trg_words_seq = autograd.Variable(trg_words_seq) with torch.no_grad(): outputs = model(src_words_seq, src_chars_seq, src_words_mask, trg_words_seq, trg_vocab_mask, adj,False) preds += list(outputs[0].data.cpu().numpy()) attns += list(outputs[1].data.cpu().numpy()) model.zero_grad() end_time = datetime.datetime.now() custom_print('Prediction time:', end_time - start_time) return preds, attns def train_model(model_id, train_samples, dev_samples, best_model_file): train_size = len(train_samples) batch_count = int(math.ceil(train_size/batch_size)) move_last_batch = False if len(train_samples) - batch_size * (batch_count - 1) == 1: move_last_batch = True batch_count -= 1 custom_print(batch_count) # model = get_model(model_id) model = SeqToSeqModel() pytorch_total_params = sum(p.numel() for p in model.parameters() if p.requires_grad) custom_print('Parameters size:', pytorch_total_params) custom_print(model) if torch.cuda.is_available(): model.cuda() if n_gpu > 1: model = torch.nn.DataParallel(model) criterion = nn.NLLLoss(ignore_index=0) optimizer = optim.Adam(model.parameters()) custom_print(optimizer) best_dev_acc = -1.0 best_epoch_idx = -1 best_epoch_seed = -1 for epoch_idx in range(0, num_epoch): model.train() model.zero_grad() custom_print('Epoch:', epoch_idx + 1) cur_seed = random_seed + epoch_idx + 1 set_random_seeds(cur_seed) cur_shuffled_train_data = shuffle_data(train_samples) start_time = datetime.datetime.now() train_loss_val = 0.0 for batch_idx in tqdm(range(0, batch_count)): batch_start = batch_idx * batch_size batch_end = min(len(cur_shuffled_train_data), batch_start + batch_size) if batch_idx == batch_count - 1 and move_last_batch: batch_end = len(cur_shuffled_train_data) cur_batch = cur_shuffled_train_data[batch_start:batch_end] cur_samples_input = get_batch_data(cur_batch, True) # np arrays to tensors src_words_seq = torch.from_numpy(cur_samples_input['src_words'].astype('long')) src_words_mask = torch.from_numpy(cur_samples_input['src_words_mask'].astype('uint8')) trg_vocab_mask = torch.from_numpy(cur_samples_input['trg_vocab_mask'].astype('uint8')) trg_words_seq = torch.from_numpy(cur_samples_input['trg_words'].astype('long')) adj = torch.from_numpy(cur_samples_input['adj'].astype('float32')) src_chars_seq = torch.from_numpy(cur_samples_input['src_chars'].astype('long')) target = torch.from_numpy(cur_samples_input['target'].astype('long')) if torch.cuda.is_available(): src_words_seq = src_words_seq.cuda() src_words_mask = src_words_mask.cuda() trg_vocab_mask = trg_vocab_mask.cuda() trg_words_seq = trg_words_seq.cuda() adj = adj.cuda() src_chars_seq = src_chars_seq.cuda() target = target.cuda() src_words_seq = autograd.Variable(src_words_seq) src_words_mask = autograd.Variable(src_words_mask) trg_vocab_mask = autograd.Variable(trg_vocab_mask) trg_words_seq = autograd.Variable(trg_words_seq) adj = autograd.Variable(adj) src_chars_seq = autograd.Variable(src_chars_seq) target = autograd.Variable(target) outputs = model(src_words_seq, src_chars_seq, src_words_mask, trg_words_seq, trg_vocab_mask, adj, True) target = target.view(-1, 1).squeeze() loss = criterion(outputs, target) loss.backward() torch.nn.utils.clip_grad_norm_(model.parameters(), 10.0) if (batch_idx + 1) % update_freq == 0: optimizer.step() model.zero_grad() train_loss_val += loss.item() train_loss_val /= batch_count end_time = datetime.datetime.now() custom_print('Training loss:', train_loss_val) custom_print('Training time:', end_time - start_time) custom_print('\nDev Results\n') set_random_seeds(random_seed) dev_preds, dev_attns = predict(dev_samples, model, model_id) write_test_res(dev_samples, dev_preds, dev_attns, os.path.join(trg_data_folder, 'dev.out')) ref_lines = open(trg_dev_file).read().splitlines() pred_lines = open(os.path.join(trg_data_folder, 'dev.out')).read().splitlines() event_lines = open(events_file).read().splitlines() argument_lines = open(arguments_file).read().splitlines() roles_lines = open(roles_file).read().splitlines() dev_acc = calculate_f1(ref_lines, pred_lines, event_lines, argument_lines, roles_lines) # pred_pos, gt_pos, correct_pos = get_F1(dev_samples, dev_preds, dev_attns) # custom_print(pred_pos, '\t', gt_pos, '\t', correct_pos) # p = float(correct_pos) / (pred_pos + 1e-8) # r = float(correct_pos) / (gt_pos + 1e-8) # dev_acc = (2 * p * r) / (p + r + 1e-8) # custom_print('F1:', dev_acc) if dev_acc >= best_dev_acc: best_epoch_idx = epoch_idx + 1 best_epoch_seed = cur_seed custom_print('model saved......') best_dev_acc = dev_acc torch.save(model.state_dict(), best_model_file) custom_print('\n\n') if epoch_idx + 1 - best_epoch_idx >= early_stop_cnt: break custom_print('*******') custom_print('Best Epoch:', best_epoch_idx) custom_print('Best Epoch Seed:', best_epoch_seed) if __name__ == "__main__": os.environ['CUDA_VISIBLE_DEVICES'] = sys.argv[1] random_seed = int(sys.argv[2]) src_data_folder = sys.argv[3] trg_data_folder = sys.argv[4] job_mode = sys.argv[5] embedding_type = sys.argv[6] granular_mode = 1 n_gpu = torch.cuda.device_count() set_random_seeds(random_seed) if not os.path.exists(trg_data_folder): os.mkdir(trg_data_folder) model_name = 1 #Tunable Hyperparameters batch_size = 32 num_epoch = 30 max_src_len = 100 max_trg_len = 50 if embedding_type == 'w2v': embedding_file = os.path.join(src_data_folder, 'w2v.txt') else: embedding_file = os.path.join(src_data_folder, 'Bert_embeddings.txt') update_freq = 1 enc_type = ['LSTM', 'GCN', 'LSTM-GCN'][0] att_type = ['None', 'Unigram', 'N-Gram-Enc'][1] copy_on = True gcn_num_layers = 3 if embedding_type == 'w2v': word_embed_dim = 300 else: word_embed_dim = 768 word_min_freq = 2 char_embed_dim = 50 char_feature_size = 50 conv_filter_size = 3 max_word_len = 10 enc_inp_size = word_embed_dim + char_feature_size enc_hidden_size = word_embed_dim dec_inp_size = enc_hidden_size dec_hidden_size = dec_inp_size drop_rate = 0.3 layers = 1 early_stop_cnt = 20 sample_cnt = 0 Sample = recordclass("Sample", "Id SrcLen SrcWords TrgLen TrgWords") events_file = os.path.join(src_data_folder, 'event_types.txt') arguments_file = os.path.join(src_data_folder, 'arguments.txt') roles_file = os.path.join(src_data_folder, 'roles.txt') events = get_relations(events_file) arguments = get_relations(arguments_file) roles = get_relations(roles_file) # train a model if job_mode == 'train': logger = open(os.path.join(trg_data_folder, 'training.log'), 'w') custom_print(sys.argv) custom_print(max_src_len, max_trg_len, drop_rate, layers) custom_print('loading data......') model_file_name = os.path.join(trg_data_folder, 'model.h5py') src_train_file = os.path.join(src_data_folder, 'train.sent') trg_train_file = os.path.join(src_data_folder, 'train.tup') train_data = read_data(src_train_file, trg_train_file, 1) src_dev_file = os.path.join(src_data_folder, 'dev.sent') trg_dev_file = os.path.join(src_data_folder, 'dev.tup') dev_data = read_data(src_dev_file, trg_dev_file, 2) custom_print('Training data size:', len(train_data)) custom_print('Development data size:', len(dev_data)) custom_print("preparing vocabulary......") save_vocab = os.path.join(trg_data_folder, 'vocab.pkl') word_vocab, rev_word_vocab, char_vocab, word_embed_matrix = build_vocab(train_data, events, arguments, roles, save_vocab, embedding_file) custom_print("Training started......") train_model(model_name, train_data, dev_data, model_file_name) logger.close() if job_mode == 'test': logger = open(os.path.join(trg_data_folder, 'test.log'), 'w') custom_print(sys.argv) custom_print("loading word vectors......") vocab_file_name = os.path.join(trg_data_folder, 'vocab.pkl') word_vocab, char_vocab = load_vocab(vocab_file_name) rev_word_vocab = OrderedDict() for word in word_vocab: idx = word_vocab[word] rev_word_vocab[idx] = word word_embed_matrix = np.zeros((len(word_vocab), word_embed_dim), dtype=np.float32) custom_print('vocab size:', len(word_vocab)) src_test_file = os.path.join(src_data_folder, 'test.sent') trg_test_file = os.path.join(src_data_folder, 'test.tup') test_data = read_data(src_test_file, trg_test_file, 3) custom_print('Test data size:', len(test_data)) custom_print('seed:', random_seed) model_file = os.path.join(trg_data_folder, 'model.h5py') best_model = get_model(model_name) custom_print(best_model) if torch.cuda.is_available(): best_model.cuda() if n_gpu > 1: best_model = torch.nn.DataParallel(best_model) best_model.load_state_dict(torch.load(model_file)) custom_print('\nTest Results\n') set_random_seeds(random_seed) test_preds, test_attns = predict(test_data, best_model, model_name) custom_print('Copy On') write_test_res(test_data, test_preds, test_attns, os.path.join(trg_data_folder, 'test.out')) # ref_lines = open(trg_test_file).readlines() # pred_lines = open(os.path.join(trg_data_folder, 'test.out')).readlines() # event_lines = open(events_file).readlines() # argument_lines = open(arguments_file).readlines() # roles_lines = open(roles_file).readlines() ref_lines = open(trg_test_file).read().splitlines() pred_lines = open(os.path.join(trg_data_folder, 'test.out')).read().splitlines() event_lines = open(events_file).read().splitlines() argument_lines = open(arguments_file).read().splitlines() roles_lines = open(roles_file).read().splitlines() mode = 1 custom_print('Overall F1') # custom_print(cal_f1(ref_lines, pred_lines, event_lines, argument_lines, roles_lines, mode)) calculate_f1(ref_lines, pred_lines, event_lines, argument_lines, roles_lines) copy_on = False custom_print('Copy Off') set_random_seeds(random_seed) test_preds, test_attns = predict(test_data, best_model, model_name) write_test_res(test_data, test_preds, test_attns, os.path.join(trg_data_folder, 'test_without_copy.out')) # ref_lines = open(trg_test_file).readlines() # pred_lines = open(os.path.join(trg_data_folder, 'test_without_copy.out')).readlines() # event_lines = open(events_file).readlines() # argument_lines = open(arguments_file).readlines() # roles_lines = open(roles_file).readlines() ref_lines = open(trg_test_file).read().splitlines() pred_lines = open(os.path.join(trg_data_folder, 'test_without_copy.out')).read().splitlines() event_lines = open(events_file).read().splitlines() argument_lines = open(arguments_file).read().splitlines() roles_lines = open(roles_file).read().splitlines() mode = 1 custom_print('Overall F1') # custom_print(cal_f1(ref_lines, pred_lines, event_lines, argument_lines, roles_lines, mode)) calculate_f1(ref_lines, pred_lines, event_lines, argument_lines, roles_lines) logger.close()
[ "torch.nn.Dropout", "recordclass.recordclass", "pickle.dump", "os.mkdir", "numpy.random.seed", "random.shuffle", "torch.nn.Embedding", "torch.nn.MaxPool1d", "torch.nn.LSTMCell", "torch.cat", "torch.cuda.device_count", "torch.nn.NLLLoss", "pickle.load", "torch.no_grad", "os.path.join", ...
[((707, 720), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (718, 720), False, 'from collections import OrderedDict\n'), ((743, 756), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (754, 756), False, 'from collections import OrderedDict\n'), ((2338, 2351), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (2349, 2351), False, 'from collections import OrderedDict\n'), ((2365, 2378), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (2376, 2378), False, 'from collections import OrderedDict\n'), ((3166, 3203), 'pickle.dump', 'pickle.dump', (['[word_v, char_v]', 'output'], {}), '([word_v, char_v], output)\n', (3177, 3203), False, 'import pickle\n'), ((11979, 12030), 'os.path.join', 'os.path.join', (['trg_data_folder', '"""Results_logger.txt"""'], {}), "(trg_data_folder, 'Results_logger.txt')\n", (11991, 12030), False, 'import os\n'), ((14512, 14529), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (14523, 14529), False, 'import random\n'), ((14534, 14554), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (14548, 14554), True, 'import numpy as np\n'), ((14559, 14582), 'torch.manual_seed', 'torch.manual_seed', (['seed'], {}), '(seed)\n', (14576, 14582), False, 'import torch\n'), ((25290, 25309), 'torch.sum', 'torch.sum', (['x'], {'dim': '(1)'}), '(x, dim=1)\n', (25299, 25309), False, 'import torch\n'), ((31644, 31667), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (31665, 31667), False, 'import datetime\n'), ((33522, 33545), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (33543, 33545), False, 'import datetime\n'), ((34229, 34254), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (34252, 34254), False, 'import torch\n'), ((34357, 34383), 'torch.nn.NLLLoss', 'nn.NLLLoss', ([], {'ignore_index': '(0)'}), '(ignore_index=0)\n', (34367, 34383), True, 'import torch.nn as nn\n'), ((39283, 39308), 'torch.cuda.device_count', 'torch.cuda.device_count', ([], {}), '()\n', (39306, 39308), False, 'import torch\n'), ((40385, 40444), 'recordclass.recordclass', 'recordclass', (['"""Sample"""', '"""Id SrcLen SrcWords TrgLen TrgWords"""'], {}), "('Sample', 'Id SrcLen SrcWords TrgLen TrgWords')\n", (40396, 40444), False, 'from recordclass import recordclass\n'), ((40464, 40512), 'os.path.join', 'os.path.join', (['src_data_folder', '"""event_types.txt"""'], {}), "(src_data_folder, 'event_types.txt')\n", (40476, 40512), False, 'import os\n'), ((40534, 40580), 'os.path.join', 'os.path.join', (['src_data_folder', '"""arguments.txt"""'], {}), "(src_data_folder, 'arguments.txt')\n", (40546, 40580), False, 'import os\n'), ((40598, 40640), 'os.path.join', 'os.path.join', (['src_data_folder', '"""roles.txt"""'], {}), "(src_data_folder, 'roles.txt')\n", (40610, 40640), False, 'import os\n'), ((870, 912), 'numpy.zeros', 'np.zeros', (['word_embed_dim'], {'dtype': 'np.float32'}), '(word_embed_dim, dtype=np.float32)\n', (878, 912), True, 'import numpy as np\n'), ((1001, 1047), 'numpy.random.uniform', 'np.random.uniform', (['(-0.25)', '(0.25)', 'word_embed_dim'], {}), '(-0.25, 0.25, word_embed_dim)\n', (1018, 1047), True, 'import numpy as np\n'), ((1136, 1182), 'numpy.random.uniform', 'np.random.uniform', (['(-0.25)', '(0.25)', 'word_embed_dim'], {}), '(-0.25, 0.25, word_embed_dim)\n', (1153, 1182), True, 'import numpy as np\n'), ((1271, 1317), 'numpy.random.uniform', 'np.random.uniform', (['(-0.25)', '(0.25)', 'word_embed_dim'], {}), '(-0.25, 0.25, word_embed_dim)\n', (1288, 1317), True, 'import numpy as np\n'), ((2210, 2250), 'numpy.array', 'np.array', (['embed_matrix'], {'dtype': 'np.float32'}), '(embed_matrix, dtype=np.float32)\n', (2218, 2250), True, 'import numpy as np\n'), ((3368, 3382), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (3379, 3382), False, 'import pickle\n'), ((14609, 14641), 'torch.cuda.manual_seed_all', 'torch.cuda.manual_seed_all', (['seed'], {}), '(seed)\n', (14635, 14641), False, 'import torch\n'), ((19269, 19311), 'numpy.array', 'np.array', (['src_words_list'], {'dtype': 'np.float32'}), '(src_words_list, dtype=np.float32)\n', (19277, 19311), True, 'import numpy as np\n'), ((19338, 19360), 'numpy.array', 'np.array', (['src_char_seq'], {}), '(src_char_seq)\n', (19346, 19360), True, 'import numpy as np\n'), ((19392, 19421), 'numpy.array', 'np.array', (['src_words_mask_list'], {}), '(src_words_mask_list)\n', (19400, 19421), True, 'import numpy as np\n'), ((19442, 19459), 'numpy.array', 'np.array', (['adj_lst'], {}), '(adj_lst)\n', (19450, 19459), True, 'import numpy as np\n'), ((19491, 19515), 'numpy.array', 'np.array', (['trg_vocab_mask'], {}), '(trg_vocab_mask)\n', (19499, 19515), True, 'import numpy as np\n'), ((19542, 19582), 'numpy.array', 'np.array', (['trg_words_list'], {'dtype': 'np.int32'}), '(trg_words_list, dtype=np.int32)\n', (19550, 19582), True, 'import numpy as np\n'), ((19606, 19622), 'numpy.array', 'np.array', (['target'], {}), '(target)\n', (19614, 19622), True, 'import numpy as np\n'), ((20715, 20765), 'torch.nn.Embedding', 'nn.Embedding', (['vocab_size', 'embed_dim'], {'padding_idx': '(0)'}), '(vocab_size, embed_dim, padding_idx=0)\n', (20727, 20765), True, 'import torch.nn as nn\n'), ((20875, 20900), 'torch.nn.Dropout', 'nn.Dropout', (['drop_out_rate'], {}), '(drop_out_rate)\n', (20885, 20900), True, 'import torch.nn as nn\n'), ((21350, 21400), 'torch.nn.Embedding', 'nn.Embedding', (['vocab_size', 'embed_dim'], {'padding_idx': '(0)'}), '(vocab_size, embed_dim, padding_idx=0)\n', (21362, 21400), True, 'import torch.nn as nn\n'), ((21424, 21449), 'torch.nn.Dropout', 'nn.Dropout', (['drop_out_rate'], {}), '(drop_out_rate)\n', (21434, 21449), True, 'import torch.nn as nn\n'), ((22135, 22247), 'torch.nn.LSTM', 'nn.LSTM', (['self.input_dim', 'self.hidden_dim', 'self.layers'], {'batch_first': '(True)', 'bidirectional': 'self.is_bidirectional'}), '(self.input_dim, self.hidden_dim, self.layers, batch_first=True,\n bidirectional=self.is_bidirectional)\n', (22142, 22247), True, 'import torch.nn as nn\n'), ((22295, 22321), 'torch.nn.Dropout', 'nn.Dropout', (['self.drop_rate'], {}), '(self.drop_rate)\n', (22305, 22321), True, 'import torch.nn as nn\n'), ((22344, 22406), 'torch.nn.Conv1d', 'nn.Conv1d', (['char_embed_dim', 'char_feature_size', 'conv_filter_size'], {}), '(char_embed_dim, char_feature_size, conv_filter_size)\n', (22353, 22406), True, 'import torch.nn as nn\n'), ((22431, 22521), 'torch.nn.MaxPool1d', 'nn.MaxPool1d', (['(max_word_len + conv_filter_size - 1)', '(max_word_len + conv_filter_size - 1)'], {}), '(max_word_len + conv_filter_size - 1, max_word_len +\n conv_filter_size - 1)\n', (22443, 22521), True, 'import torch.nn as nn\n'), ((22845, 22887), 'torch.cat', 'torch.cat', (['(words_input, char_feature)', '(-1)'], {}), '((words_input, char_feature), -1)\n', (22854, 22887), False, 'import torch\n'), ((23180, 23233), 'torch.nn.Linear', 'nn.Linear', (['self.input_dim', 'self.input_dim'], {'bias': '(False)'}), '(self.input_dim, self.input_dim, bias=False)\n', (23189, 23233), True, 'import torch.nn as nn\n'), ((23262, 23314), 'torch.nn.Linear', 'nn.Linear', (['self.input_dim', 'self.input_dim'], {'bias': '(True)'}), '(self.input_dim, self.input_dim, bias=True)\n', (23271, 23314), True, 'import torch.nn as nn\n'), ((23332, 23360), 'torch.nn.Linear', 'nn.Linear', (['self.input_dim', '(1)'], {}), '(self.input_dim, 1)\n', (23341, 23360), True, 'import torch.nn as nn\n'), ((23502, 23521), 'torch.tanh', 'torch.tanh', (['(wq + uh)'], {}), '(wq + uh)\n', (23512, 23521), False, 'import torch\n'), ((23660, 23691), 'torch.nn.functional.softmax', 'F.softmax', (['attn_weights'], {'dim': '(-1)'}), '(attn_weights, dim=-1)\n', (23669, 23691), True, 'import torch.nn.functional as F\n'), ((24004, 24019), 'torch.nn.ModuleList', 'nn.ModuleList', ([], {}), '()\n', (24017, 24019), True, 'import torch.nn as nn\n'), ((24044, 24059), 'torch.nn.ModuleList', 'nn.ModuleList', ([], {}), '()\n', (24057, 24059), True, 'import torch.nn as nn\n'), ((24440, 24462), 'torch.nn.functional.softmax', 'F.softmax', (['att'], {'dim': '(-1)'}), '(att, dim=-1)\n', (24449, 24462), True, 'import torch.nn.functional as F\n'), ((26225, 26251), 'torch.nn.Dropout', 'nn.Dropout', (['self.drop_rate'], {}), '(self.drop_rate)\n', (26235, 26251), True, 'import torch.nn as nn\n'), ((27283, 27310), 'torch.cat', 'torch.cat', (['(y_prev, ctx)', '(1)'], {}), '((y_prev, ctx), 1)\n', (27292, 27310), False, 'import torch\n'), ((32595, 32620), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (32618, 32620), False, 'import torch\n'), ((32925, 32957), 'torch.autograd.Variable', 'autograd.Variable', (['src_words_seq'], {}), '(src_words_seq)\n', (32942, 32957), True, 'import torch.autograd as autograd\n'), ((32983, 33016), 'torch.autograd.Variable', 'autograd.Variable', (['src_words_mask'], {}), '(src_words_mask)\n', (33000, 33016), True, 'import torch.autograd as autograd\n'), ((33042, 33075), 'torch.autograd.Variable', 'autograd.Variable', (['trg_vocab_mask'], {}), '(trg_vocab_mask)\n', (33059, 33075), True, 'import torch.autograd as autograd\n'), ((33090, 33112), 'torch.autograd.Variable', 'autograd.Variable', (['adj'], {}), '(adj)\n', (33107, 33112), True, 'import torch.autograd as autograd\n'), ((33137, 33169), 'torch.autograd.Variable', 'autograd.Variable', (['src_chars_seq'], {}), '(src_chars_seq)\n', (33154, 33169), True, 'import torch.autograd as autograd\n'), ((33195, 33227), 'torch.autograd.Variable', 'autograd.Variable', (['trg_words_seq'], {}), '(trg_words_seq)\n', (33212, 33227), True, 'import torch.autograd as autograd\n'), ((33761, 33795), 'math.ceil', 'math.ceil', (['(train_size / batch_size)'], {}), '(train_size / batch_size)\n', (33770, 33795), False, 'import math\n'), ((34311, 34339), 'torch.nn.DataParallel', 'torch.nn.DataParallel', (['model'], {}), '(model)\n', (34332, 34339), False, 'import torch\n'), ((34839, 34862), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (34860, 34862), False, 'import datetime\n'), ((37326, 37349), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (37347, 37349), False, 'import datetime\n'), ((39356, 39387), 'os.path.exists', 'os.path.exists', (['trg_data_folder'], {}), '(trg_data_folder)\n', (39370, 39387), False, 'import os\n'), ((39397, 39422), 'os.mkdir', 'os.mkdir', (['trg_data_folder'], {}), '(trg_data_folder)\n', (39405, 39422), False, 'import os\n'), ((39613, 39653), 'os.path.join', 'os.path.join', (['src_data_folder', '"""w2v.txt"""'], {}), "(src_data_folder, 'w2v.txt')\n", (39625, 39653), False, 'import os\n'), ((39689, 39741), 'os.path.join', 'os.path.join', (['src_data_folder', '"""Bert_embeddings.txt"""'], {}), "(src_data_folder, 'Bert_embeddings.txt')\n", (39701, 39741), False, 'import os\n'), ((41056, 41099), 'os.path.join', 'os.path.join', (['trg_data_folder', '"""model.h5py"""'], {}), "(trg_data_folder, 'model.h5py')\n", (41068, 41099), False, 'import os\n'), ((41125, 41168), 'os.path.join', 'os.path.join', (['src_data_folder', '"""train.sent"""'], {}), "(src_data_folder, 'train.sent')\n", (41137, 41168), False, 'import os\n'), ((41194, 41236), 'os.path.join', 'os.path.join', (['src_data_folder', '"""train.tup"""'], {}), "(src_data_folder, 'train.tup')\n", (41206, 41236), False, 'import os\n'), ((41327, 41368), 'os.path.join', 'os.path.join', (['src_data_folder', '"""dev.sent"""'], {}), "(src_data_folder, 'dev.sent')\n", (41339, 41368), False, 'import os\n'), ((41392, 41432), 'os.path.join', 'os.path.join', (['src_data_folder', '"""dev.tup"""'], {}), "(src_data_folder, 'dev.tup')\n", (41404, 41432), False, 'import os\n'), ((41690, 41732), 'os.path.join', 'os.path.join', (['trg_data_folder', '"""vocab.pkl"""'], {}), "(trg_data_folder, 'vocab.pkl')\n", (41702, 41732), False, 'import os\n'), ((42307, 42349), 'os.path.join', 'os.path.join', (['trg_data_folder', '"""vocab.pkl"""'], {}), "(trg_data_folder, 'vocab.pkl')\n", (42319, 42349), False, 'import os\n'), ((42437, 42450), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (42448, 42450), False, 'from collections import OrderedDict\n'), ((42726, 42768), 'os.path.join', 'os.path.join', (['src_data_folder', '"""test.sent"""'], {}), "(src_data_folder, 'test.sent')\n", (42738, 42768), False, 'import os\n'), ((42793, 42834), 'os.path.join', 'os.path.join', (['src_data_folder', '"""test.tup"""'], {}), "(src_data_folder, 'test.tup')\n", (42805, 42834), False, 'import os\n'), ((43020, 43063), 'os.path.join', 'os.path.join', (['trg_data_folder', '"""model.h5py"""'], {}), "(trg_data_folder, 'model.h5py')\n", (43032, 43063), False, 'import os\n'), ((43152, 43177), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (43175, 43177), False, 'import torch\n'), ((4094, 4116), 'random.shuffle', 'random.shuffle', (['tuples'], {}), '(tuples)\n', (4108, 4116), False, 'import random\n'), ((20808, 20850), 'torch.from_numpy', 'torch.from_numpy', (['pre_trained_embed_matrix'], {}), '(pre_trained_embed_matrix)\n', (20824, 20850), False, 'import torch\n'), ((25055, 25079), 'torch.nn.functional.softmax', 'F.softmax', (['n_att'], {'dim': '(-1)'}), '(n_att, dim=-1)\n', (25064, 25079), True, 'import torch.nn.functional as F\n'), ((25808, 25869), 'torch.nn.LSTMCell', 'nn.LSTMCell', (['(2 * self.input_dim)', 'self.hidden_dim', 'self.layers'], {}), '(2 * self.input_dim, self.hidden_dim, self.layers)\n', (25819, 25869), True, 'import torch.nn as nn\n'), ((29049, 29079), 'torch.nn.functional.log_softmax', 'F.log_softmax', (['dec_out'], {'dim': '(-1)'}), '(dec_out, dim=-1)\n', (29062, 29079), True, 'import torch.nn.functional as F\n'), ((30006, 30036), 'torch.nn.functional.log_softmax', 'F.log_softmax', (['dec_out'], {'dim': '(-1)'}), '(dec_out, dim=-1)\n', (30019, 30036), True, 'import torch.nn.functional as F\n'), ((33241, 33256), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (33254, 33256), False, 'import torch\n'), ((36027, 36052), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (36050, 36052), False, 'import torch\n'), ((36425, 36457), 'torch.autograd.Variable', 'autograd.Variable', (['src_words_seq'], {}), '(src_words_seq)\n', (36442, 36457), True, 'import torch.autograd as autograd\n'), ((36487, 36520), 'torch.autograd.Variable', 'autograd.Variable', (['src_words_mask'], {}), '(src_words_mask)\n', (36504, 36520), True, 'import torch.autograd as autograd\n'), ((36550, 36583), 'torch.autograd.Variable', 'autograd.Variable', (['trg_vocab_mask'], {}), '(trg_vocab_mask)\n', (36567, 36583), True, 'import torch.autograd as autograd\n'), ((36612, 36644), 'torch.autograd.Variable', 'autograd.Variable', (['trg_words_seq'], {}), '(trg_words_seq)\n', (36629, 36644), True, 'import torch.autograd as autograd\n'), ((36663, 36685), 'torch.autograd.Variable', 'autograd.Variable', (['adj'], {}), '(adj)\n', (36680, 36685), True, 'import torch.autograd as autograd\n'), ((36714, 36746), 'torch.autograd.Variable', 'autograd.Variable', (['src_chars_seq'], {}), '(src_chars_seq)\n', (36731, 36746), True, 'import torch.autograd as autograd\n'), ((36769, 36794), 'torch.autograd.Variable', 'autograd.Variable', (['target'], {}), '(target)\n', (36786, 36794), True, 'import torch.autograd as autograd\n'), ((37682, 37722), 'os.path.join', 'os.path.join', (['trg_data_folder', '"""dev.out"""'], {}), "(trg_data_folder, 'dev.out')\n", (37694, 37722), False, 'import os\n'), ((40838, 40883), 'os.path.join', 'os.path.join', (['trg_data_folder', '"""training.log"""'], {}), "(trg_data_folder, 'training.log')\n", (40850, 40883), False, 'import os\n'), ((42151, 42192), 'os.path.join', 'os.path.join', (['trg_data_folder', '"""test.log"""'], {}), "(trg_data_folder, 'test.log')\n", (42163, 42192), False, 'import os\n'), ((43256, 43289), 'torch.nn.DataParallel', 'torch.nn.DataParallel', (['best_model'], {}), '(best_model)\n', (43277, 43289), False, 'import torch\n'), ((43325, 43347), 'torch.load', 'torch.load', (['model_file'], {}), '(model_file)\n', (43335, 43347), False, 'import torch\n'), ((43596, 43637), 'os.path.join', 'os.path.join', (['trg_data_folder', '"""test.out"""'], {}), "(trg_data_folder, 'test.out')\n", (43608, 43637), False, 'import os\n'), ((44750, 44804), 'os.path.join', 'os.path.join', (['trg_data_folder', '"""test_without_copy.out"""'], {}), "(trg_data_folder, 'test_without_copy.out')\n", (44762, 44804), False, 'import os\n'), ((1945, 1991), 'numpy.random.uniform', 'np.random.uniform', (['(-0.25)', '(0.25)', 'word_embed_dim'], {}), '(-0.25, 0.25, word_embed_dim)\n', (1962, 1991), True, 'import numpy as np\n'), ((24120, 24151), 'torch.nn.Linear', 'nn.Linear', (['input_dim', 'input_dim'], {}), '(input_dim, input_dim)\n', (24129, 24151), True, 'import torch.nn as nn\n'), ((24186, 24217), 'torch.nn.Linear', 'nn.Linear', (['input_dim', 'input_dim'], {}), '(input_dim, input_dim)\n', (24195, 24217), True, 'import torch.nn as nn\n'), ((25980, 26041), 'torch.nn.LSTMCell', 'nn.LSTMCell', (['(2 * self.input_dim)', 'self.hidden_dim', 'self.layers'], {}), '(2 * self.input_dim, self.hidden_dim, self.layers)\n', (25991, 26041), True, 'import torch.nn as nn\n'), ((26139, 26200), 'torch.nn.LSTMCell', 'nn.LSTMCell', (['(3 * self.input_dim)', 'self.hidden_dim', 'self.layers'], {}), '(3 * self.input_dim, self.hidden_dim, self.layers)\n', (26150, 26200), True, 'import torch.nn as nn\n'), ((27201, 27231), 'torch.cat', 'torch.cat', (['(enc_last, ctx)', '(-1)'], {}), '((enc_last, ctx), -1)\n', (27210, 27231), False, 'import torch\n'), ((28474, 28512), 'torch.zeros', 'torch.zeros', (['batch_len', 'word_embed_dim'], {}), '(batch_len, word_embed_dim)\n', (28485, 28512), False, 'import torch\n'), ((28587, 28625), 'torch.zeros', 'torch.zeros', (['batch_len', 'word_embed_dim'], {}), '(batch_len, word_embed_dim)\n', (28598, 28625), False, 'import torch\n'), ((30717, 30751), 'torch.nn.functional.log_softmax', 'F.log_softmax', (['cur_dec_out'], {'dim': '(-1)'}), '(cur_dec_out, dim=-1)\n', (30730, 30751), True, 'import torch.nn.functional as F\n'), ((30896, 30936), 'torch.cat', 'torch.cat', (['(dec_out_i, cur_dec_out_i)', '(1)'], {}), '((dec_out_i, cur_dec_out_i), 1)\n', (30905, 30936), False, 'import torch\n'), ((31036, 31078), 'torch.cat', 'torch.cat', (['(dec_attn_i, cur_dec_attn_i)', '(1)'], {}), '((dec_attn_i, cur_dec_attn_i), 1)\n', (31045, 31078), False, 'import torch\n'), ((1617, 1632), 'numpy.float32', 'np.float32', (['val'], {}), '(val)\n', (1627, 1632), True, 'import numpy as np\n'), ((3643, 3666), 'math.pow', 'math.pow', (['(2)', 'amat[i][j]'], {}), '(2, amat[i][j])\n', (3651, 3666), False, 'import math\n'), ((24608, 24636), 'torch.nn.AvgPool1d', 'torch.nn.AvgPool1d', (['(i + 1)', '(1)'], {}), '(i + 1, 1)\n', (24626, 24636), False, 'import torch\n'), ((24747, 24775), 'torch.nn.AvgPool1d', 'torch.nn.AvgPool1d', (['(i + 1)', '(1)'], {}), '(i + 1, 1)\n', (24765, 24775), False, 'import torch\n'), ((27053, 27088), 'torch.gather', 'torch.gather', (['enc_hs', '(1)', 'last_index'], {}), '(enc_hs, 1, last_index)\n', (27065, 27088), False, 'import torch\n'), ((37810, 37850), 'os.path.join', 'os.path.join', (['trg_data_folder', '"""dev.out"""'], {}), "(trg_data_folder, 'dev.out')\n", (37822, 37850), False, 'import os\n'), ((44031, 44072), 'os.path.join', 'os.path.join', (['trg_data_folder', '"""test.out"""'], {}), "(trg_data_folder, 'test.out')\n", (44043, 44072), False, 'import os\n'), ((45211, 45265), 'os.path.join', 'os.path.join', (['trg_data_folder', '"""test_without_copy.out"""'], {}), "(trg_data_folder, 'test_without_copy.out')\n", (45223, 45265), False, 'import os\n'), ((26897, 26924), 'torch.sum', 'torch.sum', (['src_mask'], {'dim': '(-1)'}), '(src_mask, dim=-1)\n', (26906, 26924), False, 'import torch\n'), ((29530, 29564), 'torch.nn.functional.log_softmax', 'F.log_softmax', (['cur_dec_out'], {'dim': '(-1)'}), '(cur_dec_out, dim=-1)\n', (29543, 29564), True, 'import torch.nn.functional as F\n')]
import numpy as np import cv2 import matplotlib.pyplot as plt import matplotlib.image as mpimg import pickle class Line(): def __init__(self,n): self.n=n self.detected =False #Polynomial coefficients of the lines self.A=[] self.B=[] self.C=[] #Running average of coefficients self.A_avg=0. self.B_avg=0. self.C_avg=0. def obtain_fit(self): return (self.A_avg,self.B_avg,self.C_avg) def update_fit(self,fit_coeffs): """Obtain the fit coefficients from the latest frame and apply over each of 2nd polynomial coefficients for the purpose of smoothing """ full_Q= len(self.A) >= self.n #Append line fit coefficients self.A.append(fit_coeffs[0]) self.B.append(fit_coeffs[1]) self.C.append(fit_coeffs[2]) if full_Q: _=self.A.pop(0) _=self.B.pop(0) _=self.C.pop(0) # Compute the average of the polynomial coefficients self.A_avg = np.mean(self.A) self.B_avg = np.mean(self.B) self.C_avg = np.mean(self.C) return (self.A_avg,self.B_avg,self.C_avg)
[ "numpy.mean" ]
[((950, 965), 'numpy.mean', 'np.mean', (['self.A'], {}), '(self.A)\n', (957, 965), True, 'import numpy as np\n'), ((982, 997), 'numpy.mean', 'np.mean', (['self.B'], {}), '(self.B)\n', (989, 997), True, 'import numpy as np\n'), ((1014, 1029), 'numpy.mean', 'np.mean', (['self.C'], {}), '(self.C)\n', (1021, 1029), True, 'import numpy as np\n')]
# Copyright 2016 <NAME>, alexggmatthews # # 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. # ------------------------------------------ # Modification notice: # This file was modified by <NAME> # ------------------------------------------ import tensorflow as tf from settings import float_type from quadrature import hermgauss import numpy as np def eye(N): """ An identitiy matrix """ return tf.diag(tf.ones(tf.stack([N, ]), dtype=float_type)) def variational_expectations( Fmu, Fvar, phi, num_gauss_hermite_points=20): """ Compute the expected value of a function phi, given a Gaussian distribution for the input values. if q(f) = N(Fmu, Fvar) then this method computes \int phi(f) q(f) df. Here, we implement a default Gauss-Hermite quadrature routine """ gh_x, gh_w = hermgauss(num_gauss_hermite_points) gh_x = gh_x.reshape(1, -1) gh_w = gh_w.reshape(-1, 1) / np.sqrt(np.pi) shape = tf.shape(Fmu) Fmu, Fvar = [tf.reshape(e, (-1, 1)) for e in (Fmu, Fvar)] X = gh_x * tf.sqrt(2.0 * Fvar) + Fmu logp = phi(X) return tf.reshape(tf.matmul(logp, gh_w), shape) import tensorflow as tf def block_diagonal(matrices, dtype=tf.float32): """Constructs block-diagonal matrices from a list of batched 2D tensors. Args: matrices: A list of Tensors with shape [..., N_i, M_i] (i.e. a list of matrices with the same batch dimension). dtype: Data type to use. The Tensors in `matrices` must match this dtype. Returns: A matrix with the input matrices stacked along its main diagonal, having shape [..., \sum_i N_i, \sum_i M_i]. """ matrices = [tf.convert_to_tensor(matrix, dtype=dtype) for matrix in matrices] blocked_rows = tf.Dimension(0) blocked_cols = tf.Dimension(0) batch_shape = tf.TensorShape(None) for matrix in matrices: full_matrix_shape = matrix.get_shape().with_rank_at_least(2) batch_shape = batch_shape.merge_with(full_matrix_shape[:-2]) blocked_rows += full_matrix_shape[-2] blocked_cols += full_matrix_shape[-1] ret_columns_list = [] for matrix in matrices: matrix_shape = tf.shape(matrix) ret_columns_list.append(matrix_shape[-1]) ret_columns = tf.add_n(ret_columns_list) row_blocks = [] current_column = 0 for matrix in matrices: matrix_shape = tf.shape(matrix) row_before_length = current_column current_column += matrix_shape[-1] row_after_length = ret_columns - current_column row_blocks.append(tf.pad( tensor=matrix, paddings=tf.concat( [tf.zeros([tf.rank(matrix) - 1, 2], dtype=tf.int32), [(row_before_length, row_after_length)]], axis=0))) blocked = tf.concat(row_blocks, -2) blocked.set_shape(batch_shape.concatenate((blocked_rows, blocked_cols))) return blocked
[ "tensorflow.Dimension", "tensorflow.add_n", "quadrature.hermgauss", "tensorflow.convert_to_tensor", "tensorflow.reshape", "tensorflow.TensorShape", "tensorflow.concat", "tensorflow.stack", "tensorflow.matmul", "tensorflow.shape", "tensorflow.sqrt", "tensorflow.rank", "numpy.sqrt" ]
[((1333, 1368), 'quadrature.hermgauss', 'hermgauss', (['num_gauss_hermite_points'], {}), '(num_gauss_hermite_points)\n', (1342, 1368), False, 'from quadrature import hermgauss\n'), ((1460, 1473), 'tensorflow.shape', 'tf.shape', (['Fmu'], {}), '(Fmu)\n', (1468, 1473), True, 'import tensorflow as tf\n'), ((2263, 2278), 'tensorflow.Dimension', 'tf.Dimension', (['(0)'], {}), '(0)\n', (2275, 2278), True, 'import tensorflow as tf\n'), ((2298, 2313), 'tensorflow.Dimension', 'tf.Dimension', (['(0)'], {}), '(0)\n', (2310, 2313), True, 'import tensorflow as tf\n'), ((2332, 2352), 'tensorflow.TensorShape', 'tf.TensorShape', (['None'], {}), '(None)\n', (2346, 2352), True, 'import tensorflow as tf\n'), ((2773, 2799), 'tensorflow.add_n', 'tf.add_n', (['ret_columns_list'], {}), '(ret_columns_list)\n', (2781, 2799), True, 'import tensorflow as tf\n'), ((3314, 3339), 'tensorflow.concat', 'tf.concat', (['row_blocks', '(-2)'], {}), '(row_blocks, -2)\n', (3323, 3339), True, 'import tensorflow as tf\n'), ((1433, 1447), 'numpy.sqrt', 'np.sqrt', (['np.pi'], {}), '(np.pi)\n', (1440, 1447), True, 'import numpy as np\n'), ((1491, 1513), 'tensorflow.reshape', 'tf.reshape', (['e', '(-1, 1)'], {}), '(e, (-1, 1))\n', (1501, 1513), True, 'import tensorflow as tf\n'), ((1617, 1638), 'tensorflow.matmul', 'tf.matmul', (['logp', 'gh_w'], {}), '(logp, gh_w)\n', (1626, 1638), True, 'import tensorflow as tf\n'), ((2178, 2219), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['matrix'], {'dtype': 'dtype'}), '(matrix, dtype=dtype)\n', (2198, 2219), True, 'import tensorflow as tf\n'), ((2688, 2704), 'tensorflow.shape', 'tf.shape', (['matrix'], {}), '(matrix)\n', (2696, 2704), True, 'import tensorflow as tf\n'), ((2894, 2910), 'tensorflow.shape', 'tf.shape', (['matrix'], {}), '(matrix)\n', (2902, 2910), True, 'import tensorflow as tf\n'), ((921, 934), 'tensorflow.stack', 'tf.stack', (['[N]'], {}), '([N])\n', (929, 934), True, 'import tensorflow as tf\n'), ((1551, 1570), 'tensorflow.sqrt', 'tf.sqrt', (['(2.0 * Fvar)'], {}), '(2.0 * Fvar)\n', (1558, 1570), True, 'import tensorflow as tf\n'), ((3173, 3188), 'tensorflow.rank', 'tf.rank', (['matrix'], {}), '(matrix)\n', (3180, 3188), True, 'import tensorflow as tf\n')]
# Copyright 2019 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for open_spiel.python.algorithms.double_oracle.""" from absl.testing import absltest import numpy as np from open_spiel.python.algorithms import double_oracle import pyspiel class DoubleOracleTest(absltest.TestCase): def test_rock_paper_scissors(self): game = pyspiel.load_matrix_game("matrix_rps") solver = double_oracle.DoubleOracleSolver(game) solution, iteration, value = solver.solve(initial_strategies=[[0], [0]]) np.testing.assert_allclose(solution[0], np.ones(3)/3.) np.testing.assert_allclose(solution[1], np.ones(3)/3.) self.assertEqual(iteration, 3) self.assertAlmostEqual(value, 0.0) def test_single_step(self): game = pyspiel.load_matrix_game("matrix_rps") solver = double_oracle.DoubleOracleSolver(game) solver.subgame_strategies = [[0], [0]] best_response, best_response_utility = solver.step() self.assertListEqual(best_response, [1, 1]) self.assertListEqual(best_response_utility, [1.0, 1.0]) def test_kuhn_poker(self): game = pyspiel.extensive_to_matrix_game(pyspiel.load_game("kuhn_poker")) solver = double_oracle.DoubleOracleSolver(game) solution, iteration, value = solver.solve(initial_strategies=[[0], [0]]) # check if solution is Nash exp_utilty = solution[0] @ solver.payoffs @ solution[1] self.assertAlmostEqual(max(solver.payoffs[0] @ solution[1]), exp_utilty[0]) self.assertAlmostEqual(max(solution[0] @ solver.payoffs[1]), exp_utilty[1]) self.assertEqual(iteration, 8) self.assertAlmostEqual(value, 0.0) if __name__ == "__main__": absltest.main()
[ "pyspiel.load_game", "absl.testing.absltest.main", "numpy.ones", "pyspiel.load_matrix_game", "open_spiel.python.algorithms.double_oracle.DoubleOracleSolver" ]
[((2171, 2186), 'absl.testing.absltest.main', 'absltest.main', ([], {}), '()\n', (2184, 2186), False, 'from absl.testing import absltest\n'), ((875, 913), 'pyspiel.load_matrix_game', 'pyspiel.load_matrix_game', (['"""matrix_rps"""'], {}), "('matrix_rps')\n", (899, 913), False, 'import pyspiel\n'), ((927, 965), 'open_spiel.python.algorithms.double_oracle.DoubleOracleSolver', 'double_oracle.DoubleOracleSolver', (['game'], {}), '(game)\n', (959, 965), False, 'from open_spiel.python.algorithms import double_oracle\n'), ((1277, 1315), 'pyspiel.load_matrix_game', 'pyspiel.load_matrix_game', (['"""matrix_rps"""'], {}), "('matrix_rps')\n", (1301, 1315), False, 'import pyspiel\n'), ((1329, 1367), 'open_spiel.python.algorithms.double_oracle.DoubleOracleSolver', 'double_oracle.DoubleOracleSolver', (['game'], {}), '(game)\n', (1361, 1367), False, 'from open_spiel.python.algorithms import double_oracle\n'), ((1696, 1734), 'open_spiel.python.algorithms.double_oracle.DoubleOracleSolver', 'double_oracle.DoubleOracleSolver', (['game'], {}), '(game)\n', (1728, 1734), False, 'from open_spiel.python.algorithms import double_oracle\n'), ((1650, 1681), 'pyspiel.load_game', 'pyspiel.load_game', (['"""kuhn_poker"""'], {}), "('kuhn_poker')\n", (1667, 1681), False, 'import pyspiel\n'), ((1087, 1097), 'numpy.ones', 'np.ones', (['(3)'], {}), '(3)\n', (1094, 1097), True, 'import numpy as np\n'), ((1146, 1156), 'numpy.ones', 'np.ones', (['(3)'], {}), '(3)\n', (1153, 1156), True, 'import numpy as np\n')]
import numpy as np import torch from torch import nn import torch.nn.functional as F # open text file and read in data as `text` with open('data/anna.txt', 'r') as f: text = f.read() # print(text[:100]) # encode the text and map each character to an integer and vice versa # we create two dictionaries: # 1. int2char, which maps integers to characters # 2. char2int, which maps characters to unique integers # text = text[:100] chars = tuple(set(text)) #(1', 'v', 'H', '.', 'i', 'E', 'a', 'r', 'C', 'p',...) int2char = dict(enumerate(chars)) char2int = {ch: ii for ii, ch in int2char.items()} # encode the text encoded = np.array([char2int[ch] for ch in text]) print(encoded[:100]) def one_hot_encode(arr, n_labels): # Initialize the the encoded array # arr is a multi-dim array one_hot = np.zeros((np.multiply(*arr.shape), n_labels), dtype=np.float32) # Fill the appropriate elements with ones one_hot[np.arange(one_hot.shape[0]), arr.flatten()] = 1. # Finally reshape it to get back to the original array one_hot = one_hot.reshape((*arr.shape, n_labels)) return one_hot # check that the function works as expected test_seq = np.array([[3, 5, 1]]) one_hot = np.zeros((np.multiply(*test_seq.shape), 8), dtype=np.float32) # one_hot = one_hot_encode(test_seq, 8) print(one_hot) def get_batches(arr, batch_size, seq_length): '''Create a generator that returns batches of size batch_size x seq_length from arr. Arguments --------- arr: Array you want to make batches from batch_size: Batch size, the number of sequences per batch seq_length: Number of encoded chars in a sequence ''' total = batch_size * seq_length n_batches = len(arr) // total arr = arr[:n_batches * total] arr = arr.reshape(batch_size, -1) for n in range(0, arr.shape[1], seq_length): # The features x = arr[:,n:n+seq_length] # The targets, shifted by one y = np.zeros_like(x) try: y[:, :-1], y[:, -1] = x[:, 1:], arr[:, n+seq_length] except IndexError: y[:, :-1], y[:, -1] = x[:, 1:], arr[:, 0] yield x, y batches = get_batches(encoded, 8, 50) x, y = next(batches) # printing out the first 10 items in a sequence print('x\n', x[:10, :10]) print('\ny\n', y[:10, :10]) # check if GPU is available train_on_gpu = torch.cuda.is_available() if(train_on_gpu): print('Training on GPU!') else: print('No GPU available, training on CPU; consider making n_epochs very small.') class CharRNN(nn.Module): def __init__(self, tokens, n_hidden=256, n_layers=2, drop_prob=0.5, lr=0.001): super().__init__() self.drop_prob = drop_prob self.n_layers = n_layers self.n_hidden = n_hidden self.lr = lr # creating character dictionaries self.chars = tokens self.int2char = dict(enumerate(self.chars)) self.char2int = {ch: ii for ii, ch in self.int2char.items()} ## TODO: define the layers of the model self.lstm = nn.LSTM(len(tokens), n_hidden, n_layers, dropout=drop_prob, batch_first=True) self.dropout = nn.Dropout(drop_prob) self.fc = nn.Linear (n_hidden, len(tokens)) def forward(self, x, hidden): ''' Forward pass through the network. These inputs are x, and the hidden/cell state `hidden`. ''' ## TODO: Get the outputs and the new hidden state from the lstm x, hidden = self.lstm(x,hidden) x = self.dropout(x) x = x.contiguous().view(-1, n_hidden) x = self.fc(x) # return the final output and the hidden state return x, hidden def init_hidden(self, batch_size): ''' Initializes hidden state ''' # Create two new tensors with sizes n_layers x batch_size x n_hidden, # initialized to zero, for hidden state and cell state of LSTM weight = next(self.parameters()).data if (train_on_gpu): hidden = (weight.new(self.n_layers, batch_size, self.n_hidden).zero_().cuda(), weight.new(self.n_layers, batch_size, self.n_hidden).zero_().cuda()) else: hidden = (weight.new(self.n_layers, batch_size, self.n_hidden).zero_(), weight.new(self.n_layers, batch_size, self.n_hidden).zero_()) return hidden def train(net, data, epochs=10, batch_size=10, seq_length=50, lr=0.001, clip=5, val_frac=0.1, print_every=10): ''' Training a network Arguments --------- net: CharRNN network data: text data to train the network epochs: Number of epochs to train batch_size: Number of mini-sequences per mini-batch, aka batch size seq_length: Number of character steps per mini-batch lr: learning rate clip: gradient clipping val_frac: Fraction of data to hold out for validation print_every: Number of steps for printing training and validation loss ''' net.train() opt = torch.optim.Adam(net.parameters(), lr=lr) criterion = nn.CrossEntropyLoss() # create training and validation data val_idx = int(len(data)*(1-val_frac)) data, val_data = data[:val_idx], data[val_idx:] if(train_on_gpu): net.cuda() counter = 0 n_chars = len(net.chars) for e in range(epochs): # initialize hidden state h = net.init_hidden(batch_size) for x, y in get_batches(data, batch_size, seq_length): counter += 1 # One-hot encode our data and make them Torch tensors x = one_hot_encode(x, n_chars) inputs, targets = torch.from_numpy(x), torch.from_numpy(y) if(train_on_gpu): inputs, targets = inputs.cuda(), targets.cuda() # Creating new variables for the hidden state, otherwise # we'd backprop through the entire training history h = tuple([each.data for each in h]) # zero accumulated gradients net.zero_grad() # get the output from the model output, h = net(inputs, h) # calculate the loss and perform backprop loss = criterion(output, targets.view(batch_size*seq_length)) loss.backward() # `clip_grad_norm` helps prevent the exploding gradient problem in RNNs / LSTMs. nn.utils.clip_grad_norm_(net.parameters(), clip) opt.step() # loss stats if counter % print_every == 0: # Get validation loss val_h = net.init_hidden(batch_size) val_losses = [] net.eval() for x, y in get_batches(val_data, batch_size, seq_length): # One-hot encode our data and make them Torch tensors x = one_hot_encode(x, n_chars) x, y = torch.from_numpy(x), torch.from_numpy(y) # Creating new variables for the hidden state, otherwise # we'd backprop through the entire training history val_h = tuple([each.data for each in val_h]) inputs, targets = x, y if(train_on_gpu): inputs, targets = inputs.cuda(), targets.cuda() output, val_h = net(inputs, val_h) val_loss = criterion(output, targets.view(batch_size*seq_length)) val_losses.append(val_loss.item()) net.train() # reset to train mode after iterationg through validation data print("Epoch: {}/{}...".format(e+1, epochs), "Step: {}...".format(counter), "Loss: {:.4f}...".format(loss.item()), "Val Loss: {:.4f}".format(np.mean(val_losses))) n_hidden=512 n_layers=2 net = CharRNN(chars, n_hidden, n_layers) print(net) batch_size = 128 seq_length = 100 n_epochs = 20 # start smaller if you are just testing initial behavior # train the model train(net, encoded, epochs=n_epochs, batch_size=batch_size, seq_length=seq_length, lr=0.001, print_every=10) # change the name, for saving multiple files model_name = 'rnn_20_epoch.net' checkpoint = {'n_hidden': net.n_hidden, 'n_layers': net.n_layers, 'state_dict': net.state_dict(), 'tokens': net.chars} with open(model_name, 'wb') as f: torch.save(checkpoint, f) ## Making Predictions def predict(net, char, h=None, top_k=None): ''' Given a character, predict the next character. Returns the predicted character and the hidden state. ''' # tensor inputs x = np.array([[net.char2int[char]]]) x = one_hot_encode(x, len(net.chars)) inputs = torch.from_numpy(x) if(train_on_gpu): inputs = inputs.cuda() # detach hidden state from history h = tuple([each.data for each in h]) # get the output of the model out, h = net(inputs, h) # get the character probabilities p = F.softmax(out, dim=1).data if(train_on_gpu): p = p.cpu() # move to cpu # get top characters if top_k is None: top_ch = np.arange(len(net.chars)) else: p, top_ch = p.topk(top_k) top_ch = top_ch.numpy().squeeze() # select the likely next character with some element of randomness p = p.numpy().squeeze() char = np.random.choice(top_ch, p=p/p.sum()) # return the encoded value of the predicted char and the hidden state return net.int2char[char], h def sample(net, size, prime='The', top_k=None): #prime is the arg that we want to start our model with if(train_on_gpu): net.cuda() else: net.cpu() net.eval() # eval mode # First off, run through the prime characters chars = [ch for ch in prime] h = net.init_hidden(1) for ch in prime: char, h = predict(net, ch, h, top_k=top_k) chars.append(char) # Now pass in the previous character and get a new one for ii in range(size): char, h = predict(net, chars[-1], h, top_k=top_k) chars.append(char) return ''.join(chars) print(sample(net, 1000, prime='Anna', top_k=5)) ## Loading a checkpoint with open('rnn_20_epoch.net', 'rb') as f: checkpoint = torch.load(f) loaded = CharRNN(checkpoint['tokens'], n_hidden=checkpoint['n_hidden'], n_layers=checkpoint['n_layers']) loaded.load_state_dict(checkpoint['state_dict']) # Sample using a loaded model print(sample(loaded, 2000, top_k=5, prime="And Levin said"))
[ "torch.nn.Dropout", "numpy.zeros_like", "numpy.multiply", "torch.load", "torch.nn.CrossEntropyLoss", "torch.nn.functional.softmax", "torch.save", "numpy.mean", "torch.cuda.is_available", "numpy.array", "numpy.arange", "torch.from_numpy" ]
[((630, 669), 'numpy.array', 'np.array', (['[char2int[ch] for ch in text]'], {}), '([char2int[ch] for ch in text])\n', (638, 669), True, 'import numpy as np\n'), ((1170, 1191), 'numpy.array', 'np.array', (['[[3, 5, 1]]'], {}), '([[3, 5, 1]])\n', (1178, 1191), True, 'import numpy as np\n'), ((2383, 2408), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (2406, 2408), False, 'import torch\n'), ((5229, 5250), 'torch.nn.CrossEntropyLoss', 'nn.CrossEntropyLoss', ([], {}), '()\n', (5248, 5250), False, 'from torch import nn\n'), ((8780, 8805), 'torch.save', 'torch.save', (['checkpoint', 'f'], {}), '(checkpoint, f)\n', (8790, 8805), False, 'import torch\n'), ((9060, 9092), 'numpy.array', 'np.array', (['[[net.char2int[char]]]'], {}), '([[net.char2int[char]]])\n', (9068, 9092), True, 'import numpy as np\n'), ((9156, 9175), 'torch.from_numpy', 'torch.from_numpy', (['x'], {}), '(x)\n', (9172, 9175), False, 'import torch\n'), ((10830, 10843), 'torch.load', 'torch.load', (['f'], {}), '(f)\n', (10840, 10843), False, 'import torch\n'), ((1212, 1240), 'numpy.multiply', 'np.multiply', (['*test_seq.shape'], {}), '(*test_seq.shape)\n', (1223, 1240), True, 'import numpy as np\n'), ((1982, 1998), 'numpy.zeros_like', 'np.zeros_like', (['x'], {}), '(x)\n', (1995, 1998), True, 'import numpy as np\n'), ((3226, 3247), 'torch.nn.Dropout', 'nn.Dropout', (['drop_prob'], {}), '(drop_prob)\n', (3236, 3247), False, 'from torch import nn\n'), ((9468, 9489), 'torch.nn.functional.softmax', 'F.softmax', (['out'], {'dim': '(1)'}), '(out, dim=1)\n', (9477, 9489), True, 'import torch.nn.functional as F\n'), ((821, 844), 'numpy.multiply', 'np.multiply', (['*arr.shape'], {}), '(*arr.shape)\n', (832, 844), True, 'import numpy as np\n'), ((933, 960), 'numpy.arange', 'np.arange', (['one_hot.shape[0]'], {}), '(one_hot.shape[0])\n', (942, 960), True, 'import numpy as np\n'), ((5839, 5858), 'torch.from_numpy', 'torch.from_numpy', (['x'], {}), '(x)\n', (5855, 5858), False, 'import torch\n'), ((5860, 5879), 'torch.from_numpy', 'torch.from_numpy', (['y'], {}), '(y)\n', (5876, 5879), False, 'import torch\n'), ((7139, 7158), 'torch.from_numpy', 'torch.from_numpy', (['x'], {}), '(x)\n', (7155, 7158), False, 'import torch\n'), ((7160, 7179), 'torch.from_numpy', 'torch.from_numpy', (['y'], {}), '(y)\n', (7176, 7179), False, 'import torch\n'), ((8151, 8170), 'numpy.mean', 'np.mean', (['val_losses'], {}), '(val_losses)\n', (8158, 8170), True, 'import numpy as np\n')]
""" Dataset classes for variable number of speakers Author: <NAME> """ import numpy as np import torch import torch.utils.data as data from librosa import load from time import time import glob import os import random import json from tqdm import tqdm def load_json(filename): with open(filename) as f: data = json.load(f) return data def pad_audio(audio, len_samples=4*8000): if len(audio) < len_samples: audio = np.concatenate([audio, np.zeros(len_samples - len(audio))]) return audio class MixtureDataset(data.Dataset): def __init__(self, root, json_folders, sr=8000, seglen=4.0, minlen=2.0, debug=False): # segment and cv_maxlen not implemented """ each line of textfile comes in the form of: filename1, dB1, filename2, dB2, ... args: root: folder where dataset/ is located json_folders: folders containing json files, **/dataset/#speakers/wav8k/min/tr/** sr: sample rate seglen: length of each segment in seconds minlen: minimum segment length """ str_tmp = '_debug' if debug else '' seglen = int(seglen * sr) minlen = int(minlen * sr) self.sr = sr self.mixes = [] for json_folder in json_folders: mixfiles, wavlens = list(zip(*load_json(os.path.join(root + str_tmp, json_folder, 'mix.json')))) # list of 20000 filenames, and 20000 lengths mixfiles = [os.path.join(root, mixfile.split('dataset/')[1]) for mixfile in mixfiles] sig_json = [load_json(file) for file in sorted(glob.glob(os.path.join(root + str_tmp, json_folder, 's*.json')))] # list C, each have 20000 filenames for i, spkr_json in enumerate(sig_json): sig_json[i] = [os.path.join(root, line[0].split('dataset/')[1]) for line in spkr_json] # list C, each have 20000 filenames siglists = list(zip(*sig_json)) # list of 20000, each have C filenames self.mixes += list(zip(mixfiles, siglists, wavlens)) self.examples = [] for i, mix in enumerate(self.mixes): if mix[2] < minlen: continue start = 0 while start + minlen <= mix[2]: end = min(start + seglen, mix[2]) self.examples.append({'mixfile': mix[0], 'sourcefiles': mix[1], 'start': start, 'end':end}) start += minlen random.seed(0) self.examples = random.sample(self.examples, len(self.examples)) # Count. example_source_files_len = [len(tmp['sourcefiles'] )for tmp in self.examples] unique, counts = np.unique(np.array(example_source_files_len), return_counts=True) self.example_weights =[] for tmp in example_source_files_len: self.example_weights.append(1./counts[tmp-2]) self.example_weights = torch.Tensor(self.example_weights) def __len__(self): return len(self.examples) def __getitem__(self, idx): """ Returns: mixture: [T] sources: list of C, each [T] """ example = self.examples[idx] mixfile, sourcefiles, start, end = example['mixfile'], example['sourcefiles'], example['start'], example['end'] mixture, sr = load(mixfile, sr=self.sr) assert sr == self.sr, 'need to resample' mixture = mixture[start:end] sources = [load(sourcefile, sr=sr)[0][start:end] for sourcefile in sourcefiles] return mixture, sources def _collate_fn(batch): """ Args: batch: list, len(batch) = batch_size, each entry is a tuple of (mixture, sources) Returns: mixtures_list: B x T, torch.Tensor, padded mixtures ilens : B, torch.Tensor, length of each mixture before padding sources_list: list of B Tensors, each C x T, where C is (variable) number of source audios """ ilens = [] # shape of mixtures mixtures = [] # mixtures, same length as longest source in whole batch sources_list = [] # padded sources, same length as mixtures for mixture, sources in batch: # compute length to pad to assert len(mixture) == len(sources[0]) assert len(mixture) <= 32000 ilens.append(len(mixture)) mixtures.append(pad_audio(mixture)) sources = torch.Tensor(np.stack([pad_audio(source) for source in sources], axis=0)).float() sources_list.append(sources) mixtures = torch.Tensor(np.stack(mixtures, axis=0)).float() ilens = torch.Tensor(np.stack(ilens)).int() return mixtures, ilens, sources_list class TestDataset(data.Dataset): def __init__(self, root, json_folders, sr=8000): # segment and cv_maxlen not implemented """ each line of textfile comes in the form of: filename1, dB1, filename2, dB2, ... args: root: folder where dataset/ is located json_folders: folders containing json files, **/dataset/#speakers/wav8k/min/tr/** sr: sample rate seglen: length of each segment in seconds minlen: minimum segment length """ self.sr = sr self.mixes = [] for json_folder in json_folders: mixfiles, wavlens = list(zip(*load_json(os.path.join(root, json_folder, 'mix.json')))) # list of 20000 filenames, and 20000 lengths mixfiles = [os.path.join(root, mixfile.split('dataset/')[1]) for mixfile in mixfiles] sig_json = [load_json(file) for file in sorted(glob.glob(os.path.join(root, json_folder, 's*.json')))] # list C, each have 20000 filenames for i, spkr_json in enumerate(sig_json): sig_json[i] = [os.path.join(root, line[0].split('dataset/')[1]) for line in spkr_json] # list C, each have 20000 filenames siglists = list(zip(*sig_json)) # list of 20000, each have C filenames self.mixes += list(zip(mixfiles, siglists, wavlens)) #printlist(self.mixes) self.examples = [] for i, mix in enumerate(self.mixes): self.examples.append({'mixfile': mix[0], 'sourcefiles': mix[1], 'start': 0, 'end': mix[2]}) random.seed(0) self.examples = random.sample(self.examples, len(self.examples)) def __len__(self): return len(self.examples) def __getitem__(self, idx): """ Returns: mixture: [T] sources: list of C, each [T] """ example = self.examples[idx] mixfile, sourcefiles, start, end = example['mixfile'], example['sourcefiles'], example['start'], example['end'] mixture, sr = load(mixfile, sr=self.sr) assert sr == self.sr, 'need to resample' mixture = mixture[start:end] sources = [load(sourcefile, sr=sr)[0][start:end] for sourcefile in sourcefiles] return mixture, sources if __name__ == "__main__": root = "/ws/ifp-10_3/hasegawa/junzhez2/Baseline_Model/dataset" tr_json = ["2spkr_json/tr/", "3spkr_json/tr/", "4spkr_json/tr/", "5spkr_json/tr/"] val_json = ["2spkr_json/cv/", "3spkr_json/cv/", "4spkr_json/cv/", "5spkr_json/cv/"] test_json = ["2spkr_json/tt", "3spkr_json/tt", "4spkr_json/tt", "5spkr_json/tt"] dataset = MixtureDataset(root, tr_json) dataloader = torch.utils.data.DataLoader(dataset, batch_size=3, collate_fn=_collate_fn) print(len(dataset)) for mixtures, ilens, sources_list in tqdm(dataloader): start = time() print(mixtures.shape, ilens.shape, [len(sources) for sources in sources_list]) print(time() - start)
[ "numpy.stack", "tqdm.tqdm", "json.load", "torch.utils.data.DataLoader", "time.time", "torch.Tensor", "random.seed", "librosa.load", "numpy.array", "os.path.join" ]
[((7485, 7559), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['dataset'], {'batch_size': '(3)', 'collate_fn': '_collate_fn'}), '(dataset, batch_size=3, collate_fn=_collate_fn)\n', (7512, 7559), False, 'import torch\n'), ((7625, 7641), 'tqdm.tqdm', 'tqdm', (['dataloader'], {}), '(dataloader)\n', (7629, 7641), False, 'from tqdm import tqdm\n'), ((322, 334), 'json.load', 'json.load', (['f'], {}), '(f)\n', (331, 334), False, 'import json\n'), ((2464, 2478), 'random.seed', 'random.seed', (['(0)'], {}), '(0)\n', (2475, 2478), False, 'import random\n'), ((2914, 2948), 'torch.Tensor', 'torch.Tensor', (['self.example_weights'], {}), '(self.example_weights)\n', (2926, 2948), False, 'import torch\n'), ((3324, 3349), 'librosa.load', 'load', (['mixfile'], {'sr': 'self.sr'}), '(mixfile, sr=self.sr)\n', (3328, 3349), False, 'from librosa import load\n'), ((6222, 6236), 'random.seed', 'random.seed', (['(0)'], {}), '(0)\n', (6233, 6236), False, 'import random\n'), ((6685, 6710), 'librosa.load', 'load', (['mixfile'], {'sr': 'self.sr'}), '(mixfile, sr=self.sr)\n', (6689, 6710), False, 'from librosa import load\n'), ((7659, 7665), 'time.time', 'time', ([], {}), '()\n', (7663, 7665), False, 'from time import time\n'), ((2691, 2725), 'numpy.array', 'np.array', (['example_source_files_len'], {}), '(example_source_files_len)\n', (2699, 2725), True, 'import numpy as np\n'), ((4504, 4530), 'numpy.stack', 'np.stack', (['mixtures'], {'axis': '(0)'}), '(mixtures, axis=0)\n', (4512, 4530), True, 'import numpy as np\n'), ((4565, 4580), 'numpy.stack', 'np.stack', (['ilens'], {}), '(ilens)\n', (4573, 4580), True, 'import numpy as np\n'), ((7767, 7773), 'time.time', 'time', ([], {}), '()\n', (7771, 7773), False, 'from time import time\n'), ((3455, 3478), 'librosa.load', 'load', (['sourcefile'], {'sr': 'sr'}), '(sourcefile, sr=sr)\n', (3459, 3478), False, 'from librosa import load\n'), ((6816, 6839), 'librosa.load', 'load', (['sourcefile'], {'sr': 'sr'}), '(sourcefile, sr=sr)\n', (6820, 6839), False, 'from librosa import load\n'), ((1369, 1422), 'os.path.join', 'os.path.join', (['(root + str_tmp)', 'json_folder', '"""mix.json"""'], {}), "(root + str_tmp, json_folder, 'mix.json')\n", (1381, 1422), False, 'import os\n'), ((1638, 1690), 'os.path.join', 'os.path.join', (['(root + str_tmp)', 'json_folder', '"""s*.json"""'], {}), "(root + str_tmp, json_folder, 's*.json')\n", (1650, 1690), False, 'import os\n'), ((5326, 5369), 'os.path.join', 'os.path.join', (['root', 'json_folder', '"""mix.json"""'], {}), "(root, json_folder, 'mix.json')\n", (5338, 5369), False, 'import os\n'), ((5585, 5627), 'os.path.join', 'os.path.join', (['root', 'json_folder', '"""s*.json"""'], {}), "(root, json_folder, 's*.json')\n", (5597, 5627), False, 'import os\n')]
import os from pathlib import Path import pytest from flopy.utils import binaryfile as bf import numpy as np import fiona import rasterio from shapely.geometry import box import pytest from ..grid import load_modelgrid from ..results import export_cell_budget, export_heads, export_drawdown, export_sfr_results @pytest.fixture(scope='module') def lpr_output_path(test_output_folder): return os.path.join(test_output_folder, 'lpr') def check_files(outfiles, variables, kstpkper=None, layers=None): replace = [('model_top', 'top')] variables = set(variables) if kstpkper is not None and np.isscalar(kstpkper[0]): kstpkper = [kstpkper] written = set() for f in outfiles: assert os.path.getsize(f) > 0 fname = os.path.split(f)[1] for pair in replace: fname = fname.replace(*pair) props = parse_fname(fname) assert props['var'] in variables written.add(props['var']) if kstpkper is not None: assert (props['stp'], props['per']) in kstpkper if props['lay'] is not None: assert props['lay'] in layers # verify that all variables were exported assert len(written.difference(variables)) == 0 def parse_fname(fname): props = {'var': None, 'lay': None, 'per': None, 'stp': None, 'suffix': None} if 'stress_period_data' in fname: props['var'] = os.path.splitext(fname)[0] return props info = os.path.splitext(fname)[0].split('_') props['var'] = info.pop(0) for i in range(len(info)): item = info.pop(0) if 'ctr' in item: continue for p in ['lay', 'per', 'stp']: if p in item: props[p] = int(item.strip(p)) return props def compare_polygons(p1, p2, **kwargs): """Check that two polygons have the same extent""" assert np.allclose(p1.area, p2.area, **kwargs) assert np.allclose(p1.intersection(p2).area, p1.area, **kwargs) def test_cell_budget_export(model): m, grid, output_path = model precision = 'single' binary_grid_file = None skip = [] if m.version == 'mf6': precision = 'double' binary_grid_file = os.path.join(m.model_ws, '{}.dis.grb'.format(m.name)) skip = ['WEL'] file = os.path.join(m.model_ws, '{}.cbc'.format(m.name)) #file = 'Examples/data/lpr/lpr_inset.cbc' assert os.path.exists(file) cbobj = bf.CellBudgetFile(file, precision=precision) layers = list(range(cbobj.nlay)) kstpkper = cbobj.get_kstpkper()[0] variables = [bs.decode().strip() for bs in cbobj.textlist if bs.decode().strip() not in skip] nrow, ncol = cbobj.nrow, cbobj.ncol cbobj.close() outfiles = export_cell_budget(file, grid, binary_grid_file=binary_grid_file, kstpkper=kstpkper, precision=precision, output_path=output_path) check_files(outfiles, variables, kstpkper) tifs = [f for f in outfiles if f.endswith('.tif')] for f in tifs: with rasterio.open(f) as src: assert src.width == ncol assert src.height == nrow compare_polygons(grid.bbox, box(*src.bounds)) @pytest.mark.parametrize(('export_depth_to_water,export_layers,' 'export_water_table'), ((True, False, True), (False, True, False) )) def test_heads_export(model, export_depth_to_water, export_layers, export_water_table): m, grid, output_path = model file = os.path.join(m.model_ws, '{}.hds'.format(m.name)) #file = 'Examples/data/lpr/lpr_inset.hds' variables = ['hds'] if export_depth_to_water: variables += ['wt', 'dtw', 'op'] if export_water_table and 'wt' not in variables: variables.append('wt') hdsobj = bf.HeadFile(file) kstpkper = hdsobj.get_kstpkper()[-1:] layers = list(range(hdsobj.nlay)) nrow, ncol = hdsobj.nrow, hdsobj.ncol hdsobj.close() outfiles = export_heads(file, grid, -1e4, -9999, kstpkper=kstpkper, export_depth_to_water=export_depth_to_water, export_water_table=export_water_table, export_layers=export_layers, land_surface_elevations=m.dis.top.array, output_path=output_path) check_files(outfiles, variables, kstpkper, layers) tifs = [f for f in outfiles if f.endswith('.tif')] for f in tifs: with rasterio.open(f) as src: assert src.width == ncol assert src.height == nrow compare_polygons(grid.bbox, box(*src.bounds)) shps = [f for f in outfiles if f.endswith('.shp')] for f in shps: with fiona.open(f) as src: assert box(*src.bounds).within(grid.bbox) #compare_polygons(grid.bbox, box(*src.bounds), rtol=0.1) def test_drawdown_export(model): m, grid, output_path = model file = os.path.join(m.model_ws, '{}.hds'.format(m.name)) #file = 'Examples/data/lpr/lpr_inset.hds' variables = ['ddn', 'wt-ddn'] hdsobj = bf.HeadFile(file) kstpkper0 = hdsobj.get_kstpkper()[1] kstpkper1 = hdsobj.get_kstpkper()[-1] layers = list(range(hdsobj.nlay)) nrow, ncol = hdsobj.nrow, hdsobj.ncol hdsobj.close() outfiles = export_drawdown(file, grid, -1e4, -9999, kstpkper0=kstpkper0, kstpkper1=kstpkper1, output_path=output_path) check_files(outfiles, variables, [kstpkper1], layers) tifs = [f for f in outfiles if f.endswith('.tif')] for f in tifs: with rasterio.open(f) as src: assert src.width == ncol assert src.height == nrow compare_polygons(grid.bbox, box(*src.bounds)) shps = [f for f in outfiles if f.endswith('.shp')] for f in shps: with fiona.open(f) as src: assert box(*src.bounds).within(grid.bbox) def test_sfr_results_export(lpr_model, lpr_modelgrid, lpr_output_path): mf2005_sfr_outputfile = 'Examples/data/lpr/lpr_inset.sfr.out' kstpkper = [(4, 0)] variables = ['sfrout', 'baseflow', 'qaquifer'] outfiles = export_sfr_results(mf2005_sfr_outputfile=mf2005_sfr_outputfile, model=lpr_model, grid=lpr_modelgrid, kstpkper=kstpkper, output_length_units='feet', output_time_units='seconds', output_path=lpr_output_path ) check_files(outfiles, variables, kstpkper) @pytest.mark.parametrize('use_flopy', (False, True)) def test_mf6sfr_results_export(shellmound_model, shellmound_modelgrid, shellmound_output_path, use_flopy): mf6_sfr_stage_file = os.path.join(shellmound_model.model_ws, '{}.sfr.stage.bin' .format(shellmound_model.name)) mf6_sfr_budget_file = os.path.join(shellmound_model.model_ws, '{}.sfr.out.bin' .format(shellmound_model.name)) model_ws = Path(shellmound_model.model_ws) if use_flopy: model = shellmound_model package_data_file=None else: package_data_file = model_ws / f'external/{shellmound_model.name}_packagedata.dat' model = None hdsobj = bf.HeadFile(mf6_sfr_stage_file, text='stage') kstpkper = hdsobj.get_kstpkper()[:1] + hdsobj.get_kstpkper()[-1:] variables = ['sfrout', 'baseflow', 'qaquifer'] outfiles = export_sfr_results(mf6_sfr_stage_file=mf6_sfr_stage_file, mf6_sfr_budget_file=mf6_sfr_budget_file, model=model, mf6_package_data=package_data_file, grid=shellmound_modelgrid, kstpkper=kstpkper, output_length_units='feet', output_time_units='seconds', output_path=shellmound_output_path ) check_files(outfiles, variables, kstpkper) def test_parse_fname(): fname = 'wel0_stress_period_data.shp' result = parse_fname(fname) assert result['var'] == os.path.splitext(fname)[0]
[ "rasterio.open", "fiona.open", "numpy.isscalar", "os.path.getsize", "numpy.allclose", "pytest.fixture", "os.path.exists", "flopy.utils.binaryfile.HeadFile", "pathlib.Path", "os.path.splitext", "flopy.utils.binaryfile.CellBudgetFile", "pytest.mark.parametrize", "os.path.split", "os.path.joi...
[((314, 344), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (328, 344), False, 'import pytest\n'), ((3345, 3480), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""export_depth_to_water,export_layers,export_water_table"""', '((True, False, True), (False, True, False))'], {}), "(\n 'export_depth_to_water,export_layers,export_water_table', ((True, False,\n True), (False, True, False)))\n", (3368, 3480), False, 'import pytest\n'), ((6899, 6950), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""use_flopy"""', '(False, True)'], {}), "('use_flopy', (False, True))\n", (6922, 6950), False, 'import pytest\n'), ((397, 436), 'os.path.join', 'os.path.join', (['test_output_folder', '"""lpr"""'], {}), "(test_output_folder, 'lpr')\n", (409, 436), False, 'import os\n'), ((1917, 1956), 'numpy.allclose', 'np.allclose', (['p1.area', 'p2.area'], {}), '(p1.area, p2.area, **kwargs)\n', (1928, 1956), True, 'import numpy as np\n'), ((2441, 2461), 'os.path.exists', 'os.path.exists', (['file'], {}), '(file)\n', (2455, 2461), False, 'import os\n'), ((2474, 2518), 'flopy.utils.binaryfile.CellBudgetFile', 'bf.CellBudgetFile', (['file'], {'precision': 'precision'}), '(file, precision=precision)\n', (2491, 2518), True, 'from flopy.utils import binaryfile as bf\n'), ((4024, 4041), 'flopy.utils.binaryfile.HeadFile', 'bf.HeadFile', (['file'], {}), '(file)\n', (4035, 4041), True, 'from flopy.utils import binaryfile as bf\n'), ((5292, 5309), 'flopy.utils.binaryfile.HeadFile', 'bf.HeadFile', (['file'], {}), '(file)\n', (5303, 5309), True, 'from flopy.utils import binaryfile as bf\n'), ((7413, 7444), 'pathlib.Path', 'Path', (['shellmound_model.model_ws'], {}), '(shellmound_model.model_ws)\n', (7417, 7444), False, 'from pathlib import Path\n'), ((7662, 7707), 'flopy.utils.binaryfile.HeadFile', 'bf.HeadFile', (['mf6_sfr_stage_file'], {'text': '"""stage"""'}), "(mf6_sfr_stage_file, text='stage')\n", (7673, 7707), True, 'from flopy.utils import binaryfile as bf\n'), ((605, 629), 'numpy.isscalar', 'np.isscalar', (['kstpkper[0]'], {}), '(kstpkper[0])\n', (616, 629), True, 'import numpy as np\n'), ((719, 737), 'os.path.getsize', 'os.path.getsize', (['f'], {}), '(f)\n', (734, 737), False, 'import os\n'), ((758, 774), 'os.path.split', 'os.path.split', (['f'], {}), '(f)\n', (771, 774), False, 'import os\n'), ((1447, 1470), 'os.path.splitext', 'os.path.splitext', (['fname'], {}), '(fname)\n', (1463, 1470), False, 'import os\n'), ((3184, 3200), 'rasterio.open', 'rasterio.open', (['f'], {}), '(f)\n', (3197, 3200), False, 'import rasterio\n'), ((4680, 4696), 'rasterio.open', 'rasterio.open', (['f'], {}), '(f)\n', (4693, 4696), False, 'import rasterio\n'), ((4925, 4938), 'fiona.open', 'fiona.open', (['f'], {}), '(f)\n', (4935, 4938), False, 'import fiona\n'), ((5853, 5869), 'rasterio.open', 'rasterio.open', (['f'], {}), '(f)\n', (5866, 5869), False, 'import rasterio\n'), ((6098, 6111), 'fiona.open', 'fiona.open', (['f'], {}), '(f)\n', (6108, 6111), False, 'import fiona\n'), ((8613, 8636), 'os.path.splitext', 'os.path.splitext', (['fname'], {}), '(fname)\n', (8629, 8636), False, 'import os\n'), ((1506, 1529), 'os.path.splitext', 'os.path.splitext', (['fname'], {}), '(fname)\n', (1522, 1529), False, 'import os\n'), ((3324, 3340), 'shapely.geometry.box', 'box', (['*src.bounds'], {}), '(*src.bounds)\n', (3327, 3340), False, 'from shapely.geometry import box\n'), ((4820, 4836), 'shapely.geometry.box', 'box', (['*src.bounds'], {}), '(*src.bounds)\n', (4823, 4836), False, 'from shapely.geometry import box\n'), ((5993, 6009), 'shapely.geometry.box', 'box', (['*src.bounds'], {}), '(*src.bounds)\n', (5996, 6009), False, 'from shapely.geometry import box\n'), ((4966, 4982), 'shapely.geometry.box', 'box', (['*src.bounds'], {}), '(*src.bounds)\n', (4969, 4982), False, 'from shapely.geometry import box\n'), ((6139, 6155), 'shapely.geometry.box', 'box', (['*src.bounds'], {}), '(*src.bounds)\n', (6142, 6155), False, 'from shapely.geometry import box\n')]
## Compiled from NodeLoads.ipynb on Sun Dec 10 12:51:11 2017 ## DO NOT EDIT THIS FILE. YOUR CHANGES WILL BE LOST!! ## In [1]: import numpy as np from salib import extend ## In [9]: class NodeLoad(object): def __init__(self,fx=0.,fy=0.,mz=0.): if np.isscalar(fx): self.forces = np.matrix([fx,fy,mz],dtype=np.float64).T else: self.forces= fx.copy() def __mul__(self,scale): if scale == 1.0: return self return self.__class__(self.forces*scale) __rmul__ = __mul__ def __repr__(self): return "{}({},{},{})".format(self.__class__.__name__,*list(np.array(self.forces.T)[0])) def __getitem__(self,ix): return self.forces[ix,0] ## In [11]: def makeNodeLoad(data): G = data.get return NodeLoad(G('FX',0),G('FY',0),G('MZ',0)) ## In [13]: id(NodeLoad) ## In [17]: @extend class NodeLoad: @property def fx(self): return self.forces[0,0] @fx.setter def fx(self,v): self.forces[0,0] = v @property def fy(self): return self.forces[1,0] @fy.setter def fy(self,v): self.forces[1,0] = v @property def mz(self): return self.forces[2,0] @mz.setter def mz(self,v): self.forces[2,0] = v ## In [ ]:
[ "numpy.isscalar", "numpy.matrix", "numpy.array" ]
[((265, 280), 'numpy.isscalar', 'np.isscalar', (['fx'], {}), '(fx)\n', (276, 280), True, 'import numpy as np\n'), ((308, 349), 'numpy.matrix', 'np.matrix', (['[fx, fy, mz]'], {'dtype': 'np.float64'}), '([fx, fy, mz], dtype=np.float64)\n', (317, 349), True, 'import numpy as np\n'), ((662, 685), 'numpy.array', 'np.array', (['self.forces.T'], {}), '(self.forces.T)\n', (670, 685), True, 'import numpy as np\n')]
import os filename = 'seg-0_0_0.npz' outputdir = os.getcwd() + os.sep + 'inferred_segmentation' inputdir = os.getcwd() import numpy as np import h5py import PIL import PIL.Image import cv2 import png def save_tif8(id_data, filename): cv2.imwrite(filename, id_data.astype('uint8')) def save_tifc(id_data, filename, colordata): pilOUT = gen_col_pil(id_data, colordata) pilOUT.save(filename) def save_png16(id_data, filename): # Use pypng to write zgray as a grayscale PNG. with open(filename, 'wb') as f: writer = png.Writer(width=id_data.shape[1], height=id_data.shape[0], bitdepth=16, greyscale=True) id_data_list = id_data.astype('uint16').tolist() writer.write(f, id_data_list) def save_png8(id_data, filename): # Use pypng to write zgray as a grayscale PNG. with open(filename, 'wb') as f: writer = png.Writer(width=id_data.shape[1], height=id_data.shape[0], bitdepth=8, greyscale=True) id_data_list = id_data.astype('uint8').tolist() writer.write(f, id_data_list) def save_pngc(id_data, filename, colordata): pilOUT = gen_col_pil(id_data, colordata) pilOUT.save(filename) def save_npy(id_data, filename): np.save(filename, id_data) inputdir = os.getcwd() data = np.load(inputdir+ os.sep+filename) # print data.files # print data['segmentation'].shape num_z = data['segmentation'].shape[0] num_y = data['segmentation'].shape[1] num_x = data['segmentation'].shape[2] for idz in range(num_z): tmp = outputdir + os.sep + 'z' + '%04d' % (idz) + '.png' save_png8(data['segmentation'][idz,:,:].transpose(), tmp)
[ "os.getcwd", "numpy.load", "numpy.save", "png.Writer" ]
[((110, 121), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (119, 121), False, 'import os\n'), ((1251, 1262), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (1260, 1262), False, 'import os\n'), ((1272, 1309), 'numpy.load', 'np.load', (['(inputdir + os.sep + filename)'], {}), '(inputdir + os.sep + filename)\n', (1279, 1309), True, 'import numpy as np\n'), ((1210, 1236), 'numpy.save', 'np.save', (['filename', 'id_data'], {}), '(filename, id_data)\n', (1217, 1236), True, 'import numpy as np\n'), ((50, 61), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (59, 61), False, 'import os\n'), ((550, 642), 'png.Writer', 'png.Writer', ([], {'width': 'id_data.shape[1]', 'height': 'id_data.shape[0]', 'bitdepth': '(16)', 'greyscale': '(True)'}), '(width=id_data.shape[1], height=id_data.shape[0], bitdepth=16,\n greyscale=True)\n', (560, 642), False, 'import png\n'), ((873, 964), 'png.Writer', 'png.Writer', ([], {'width': 'id_data.shape[1]', 'height': 'id_data.shape[0]', 'bitdepth': '(8)', 'greyscale': '(True)'}), '(width=id_data.shape[1], height=id_data.shape[0], bitdepth=8,\n greyscale=True)\n', (883, 964), False, 'import png\n')]
""" A. Long-term future prediction (model rollout) 1. encoder-decoder (0, 1 -> 8192-dim latent -> 2', 3'): - feed (2', 3') images as input to predict (4', 5') images ... 2. encoder-decoder-64 (0, 1 -> 64-dim latent -> 2', 3'): - feed (2', 3') images as input to predict (4', 5') images ... 3. encoder-decoder-64 & refine-64 ๏ผˆ0, 1 -> id-dim latent -> 2', 3') - feed (2', 3') images as input to predict (4', 5') images ... 4. encoder-decoder-64 & refine-64 hybrid: - use refine-64 model at certain prediction steps B. Long-term future prediction with perturbation (model rollout) """ import os import sys import glob import yaml import json import torch import pprint import shutil import numpy as np from PIL import Image from tqdm import tqdm from munch import munchify from torchvision import transforms from collections import OrderedDict from models import VisDynamicsModel from models_latentpred import VisLatentDynamicsModel from dataset import NeuralPhysDataset from pytorch_lightning import Trainer, seed_everything from pytorch_lightning.loggers import TensorBoardLogger def mkdir(folder): if os.path.exists(folder): shutil.rmtree(folder) os.makedirs(folder) def load_config(filepath): with open(filepath, 'r') as stream: try: trainer_params = yaml.safe_load(stream) return trainer_params except yaml.YAMLError as exc: print(exc) def seed(cfg): torch.manual_seed(cfg.seed) if cfg.if_cuda: torch.cuda.manual_seed(cfg.seed) # uncomment for strict reproducibility # torch.set_deterministic(True) def model_rollout(): config_filepath = str(sys.argv[2]) cfg = load_config(filepath=config_filepath) pprint.pprint(cfg) cfg = munchify(cfg) seed(cfg) seed_everything(cfg.seed) log_dir = '_'.join([cfg.log_dir, cfg.dataset, cfg.model_name, str(cfg.seed)]) model = VisDynamicsModel(lr=cfg.lr, seed=cfg.seed, if_cuda=cfg.if_cuda, if_test=True, gamma=cfg.gamma, log_dir=log_dir, train_batch=cfg.train_batch, val_batch=cfg.val_batch, test_batch=cfg.test_batch, num_workers=cfg.num_workers, model_name=cfg.model_name, data_filepath=cfg.data_filepath, dataset=cfg.dataset, lr_schedule=cfg.lr_schedule) # load model if cfg.model_name == 'encoder-decoder' or cfg.model_name == 'encoder-decoder-64': checkpoint_filepath = str(sys.argv[3]) checkpoint_filepath = glob.glob(os.path.join(checkpoint_filepath, '*.ckpt'))[0] ckpt = torch.load(checkpoint_filepath) model.load_state_dict(ckpt['state_dict']) if 'refine' in cfg.model_name: checkpoint_filepath = str(sys.argv[4]) checkpoint_filepath = glob.glob(os.path.join(checkpoint_filepath, '*.ckpt'))[0] ckpt = torch.load(checkpoint_filepath) ckpt = rename_ckpt_for_multi_models(ckpt) model.model.load_state_dict(ckpt) high_dim_checkpoint_filepath = str(sys.argv[3]) high_dim_checkpoint_filepath = glob.glob(os.path.join(high_dim_checkpoint_filepath, '*.ckpt'))[0] ckpt = torch.load(high_dim_checkpoint_filepath) ckpt = rename_ckpt_for_multi_models(ckpt) model.high_dim_model.load_state_dict(ckpt) model = model.to('cuda') model.eval() model.freeze() # get all the test video ids data_filepath_base = os.path.join(cfg.data_filepath, cfg.dataset) with open(os.path.join('../datainfo', cfg.dataset, f'data_split_dict_{cfg.seed}.json'), 'r') as file: seq_dict = json.load(file) test_vid_ids = seq_dict['test'] pred_len = int(sys.argv[6]) long_term_folder = os.path.join(log_dir, 'prediction_long_term', 'model_rollout') loss_dict = {} if cfg.model_name == 'encoder-decoder' or cfg.model_name == 'encoder-decoder-64': for p_vid_idx in tqdm(test_vid_ids): vid_filepath = os.path.join(data_filepath_base, str(p_vid_idx)) total_num_frames = len(os.listdir(vid_filepath)) suf = os.listdir(vid_filepath)[0].split('.')[-1] data = None saved_folder = os.path.join(long_term_folder, str(p_vid_idx)) mkdir(saved_folder) loss_lst = [] for start_frame_idx in range(total_num_frames - 3): if start_frame_idx % 2 != 0: continue # take the initial input from ground truth data if start_frame_idx % pred_len == 0: data = [get_data(os.path.join(vid_filepath, f'{start_frame_idx}.{suf}')), get_data(os.path.join(vid_filepath, f'{start_frame_idx+1}.{suf}'))] data = (torch.cat(data, 2)).unsqueeze(0) # get the target target = [get_data(os.path.join(vid_filepath, f'{start_frame_idx+2}.{suf}')), get_data(os.path.join(vid_filepath, f'{start_frame_idx+3}.{suf}'))] target = (torch.cat(target, 2)).unsqueeze(0) # feed into the model if cfg.model_name == 'encoder-decoder': output, latent = model.model(data.cuda()) if cfg.model_name == 'encoder-decoder-64': output, latent = model.model(data.cuda(), data.cuda(), False) # compute loss loss_lst.append(float(model.loss_func(output, target.cuda()).cpu().detach().numpy())) # save (2', 3'), (4', 5'), ... img = tensor_to_img(output[0, :, :, :128]) img.save(os.path.join(saved_folder, f'{start_frame_idx+2}.{suf}')) img = tensor_to_img(output[0, :, :, 128:]) img.save(os.path.join(saved_folder, f'{start_frame_idx+3}.{suf}')) # the output becomes the input data in the next iteration data = torch.tensor(output.cpu().detach().numpy()).float() loss_dict[p_vid_idx] = loss_lst # save the test loss for all the testing videos with open(os.path.join(long_term_folder, 'test_loss.json'), 'w') as file: json.dump(loss_dict, file, indent=4) if 'refine' in cfg.model_name: for p_vid_idx in tqdm(test_vid_ids): vid_filepath = os.path.join(data_filepath_base, str(p_vid_idx)) total_num_frames = len(os.listdir(vid_filepath)) suf = os.listdir(vid_filepath)[0].split('.')[-1] data = None saved_folder = os.path.join(long_term_folder, str(p_vid_idx)) mkdir(saved_folder) loss_lst = [] for start_frame_idx in range(total_num_frames - 3): if start_frame_idx % 2 != 0: continue # take the initial input from ground truth data if start_frame_idx % pred_len == 0: data = [get_data(os.path.join(vid_filepath, f'{start_frame_idx}.{suf}')), get_data(os.path.join(vid_filepath, f'{start_frame_idx+1}.{suf}'))] data = (torch.cat(data, 2)).unsqueeze(0) # get the target target = [get_data(os.path.join(vid_filepath, f'{start_frame_idx+2}.{suf}')), get_data(os.path.join(vid_filepath, f'{start_frame_idx+3}.{suf}'))] target = (torch.cat(target, 2)).unsqueeze(0) # feed into the model _, latent = model.high_dim_model(data.cuda(), data.cuda(), False) latent = latent.squeeze(-1).squeeze(-1) latent_reconstructed, latent_latent = model.model(latent) output, _ = model.high_dim_model(data.cuda(), latent_reconstructed.unsqueeze(2).unsqueeze(3), True) # compute loss loss_lst.append(float(model.loss_func(output, target.cuda()).cpu().detach().numpy())) # save (2', 3'), (4', 5'), ... img = tensor_to_img(output[0, :, :, :128]) img.save(os.path.join(saved_folder, f'{start_frame_idx+2}.{suf}')) img = tensor_to_img(output[0, :, :, 128:]) img.save(os.path.join(saved_folder, f'{start_frame_idx+3}.{suf}')) # the output becomes the input data in the next iteration data = torch.tensor(output.cpu().detach().numpy()).float() loss_dict[p_vid_idx] = loss_lst # save the test loss for all the testing videos with open(os.path.join(long_term_folder, 'test_loss.json'), 'w') as file: json.dump(loss_dict, file, indent=4) def model_rollout_hybrid(step): config_filepath = str(sys.argv[2]) cfg = load_config(filepath=config_filepath) pprint.pprint(cfg) cfg = munchify(cfg) seed(cfg) seed_everything(cfg.seed) if 'refine' not in cfg.model_name: assert False, "the hybrid scheme is only supported with refine model..." log_dir = '_'.join([cfg.log_dir, cfg.dataset, cfg.model_name, str(cfg.seed)]) model = VisDynamicsModel(lr=cfg.lr, seed=cfg.seed, if_cuda=cfg.if_cuda, if_test=True, gamma=cfg.gamma, log_dir=log_dir, train_batch=cfg.train_batch, val_batch=cfg.val_batch, test_batch=cfg.test_batch, num_workers=cfg.num_workers, model_name=cfg.model_name, data_filepath=cfg.data_filepath, dataset=cfg.dataset, lr_schedule=cfg.lr_schedule) # load model checkpoint_filepath = str(sys.argv[4]) checkpoint_filepath = glob.glob(os.path.join(checkpoint_filepath, '*.ckpt'))[0] ckpt = torch.load(checkpoint_filepath) ckpt = rename_ckpt_for_multi_models(ckpt) model.model.load_state_dict(ckpt) high_dim_checkpoint_filepath = str(sys.argv[3]) high_dim_checkpoint_filepath = glob.glob(os.path.join(high_dim_checkpoint_filepath, '*.ckpt'))[0] ckpt = torch.load(high_dim_checkpoint_filepath) ckpt = rename_ckpt_for_multi_models(ckpt) model.high_dim_model.load_state_dict(ckpt) model = model.to('cuda') model.eval() model.freeze() # get all the test video ids data_filepath_base = os.path.join(cfg.data_filepath, cfg.dataset) with open(os.path.join('../datainfo', cfg.dataset, f'data_split_dict_{cfg.seed}.json'), 'r') as file: seq_dict = json.load(file) test_vid_ids = seq_dict['test'] pred_len = int(sys.argv[6]) long_term_folder = os.path.join(log_dir, 'prediction_long_term', f'hybrid_rollout_{step}') loss_dict = {} for p_vid_idx in tqdm(test_vid_ids): vid_filepath = os.path.join(data_filepath_base, str(p_vid_idx)) total_num_frames = len(os.listdir(vid_filepath)) suf = os.listdir(vid_filepath)[0].split('.')[-1] data = None saved_folder = os.path.join(long_term_folder, str(p_vid_idx)) mkdir(saved_folder) loss_lst = [] for start_frame_idx in range(total_num_frames - 3): if start_frame_idx % 2 != 0: continue # take the initial input from ground truth data if start_frame_idx % pred_len == 0: data = [get_data(os.path.join(vid_filepath, f'{start_frame_idx}.{suf}')), get_data(os.path.join(vid_filepath, f'{start_frame_idx+1}.{suf}'))] data = (torch.cat(data, 2)).unsqueeze(0) # get the target target = [get_data(os.path.join(vid_filepath, f'{start_frame_idx+2}.{suf}')), get_data(os.path.join(vid_filepath, f'{start_frame_idx+3}.{suf}'))] target = (torch.cat(target, 2)).unsqueeze(0) # feed into the model if (start_frame_idx + 2) % (2 * step + 2) == 0: _, latent = model.high_dim_model(data.cuda(), data.cuda(), False) latent = latent.squeeze(-1).squeeze(-1) latent_reconstructed, latent_latent = model.model(latent) output, _ = model.high_dim_model(data.cuda(), latent_reconstructed.unsqueeze(2).unsqueeze(3), True) else: output, _ = model.high_dim_model(data.cuda(), data.cuda(), False) # compute loss loss_lst.append(float(model.loss_func(output, target.cuda()).cpu().detach().numpy())) # save (2', 3'), (4', 5'), ... img = tensor_to_img(output[0, :, :, :128]) img.save(os.path.join(saved_folder, f'{start_frame_idx+2}.{suf}')) img = tensor_to_img(output[0, :, :, 128:]) img.save(os.path.join(saved_folder, f'{start_frame_idx+3}.{suf}')) # the output becomes the input data in the next iteration data = torch.tensor(output.cpu().detach().numpy()).float() loss_dict[p_vid_idx] = loss_lst # save the test loss for all the testing videos with open(os.path.join(long_term_folder, 'test_loss.json'), 'w') as file: json.dump(loss_dict, file, indent=4) def model_rollout_perturb(perturb_type, perturb_level): config_filepath = str(sys.argv[2]) cfg = load_config(filepath=config_filepath) pprint.pprint(cfg) cfg = munchify(cfg) seed(cfg) seed_everything(cfg.seed) log_dir = '_'.join([cfg.log_dir, cfg.dataset, cfg.model_name, str(cfg.seed)]) model = VisDynamicsModel(lr=cfg.lr, seed=cfg.seed, if_cuda=cfg.if_cuda, if_test=True, gamma=cfg.gamma, log_dir=log_dir, train_batch=cfg.train_batch, val_batch=cfg.val_batch, test_batch=cfg.test_batch, num_workers=cfg.num_workers, model_name=cfg.model_name, data_filepath=cfg.data_filepath, dataset=cfg.dataset, lr_schedule=cfg.lr_schedule) # load model if cfg.model_name == 'encoder-decoder' or cfg.model_name == 'encoder-decoder-64': checkpoint_filepath = str(sys.argv[3]) checkpoint_filepath = glob.glob(os.path.join(checkpoint_filepath, '*.ckpt'))[0] ckpt = torch.load(checkpoint_filepath) model.load_state_dict(ckpt['state_dict']) if 'refine' in cfg.model_name: checkpoint_filepath = str(sys.argv[4]) checkpoint_filepath = glob.glob(os.path.join(checkpoint_filepath, '*.ckpt'))[0] ckpt = torch.load(checkpoint_filepath) ckpt = rename_ckpt_for_multi_models(ckpt) model.model.load_state_dict(ckpt) high_dim_checkpoint_filepath = str(sys.argv[3]) high_dim_checkpoint_filepath = glob.glob(os.path.join(high_dim_checkpoint_filepath, '*.ckpt'))[0] ckpt = torch.load(high_dim_checkpoint_filepath) ckpt = rename_ckpt_for_multi_models(ckpt) model.high_dim_model.load_state_dict(ckpt) model = model.to('cuda') model.eval() model.freeze() # get all the test video ids data_filepath_base = os.path.join(cfg.data_filepath, cfg.dataset) with open(os.path.join('../datainfo', cfg.dataset, f'data_split_dict_{cfg.seed}.json'), 'r') as file: seq_dict = json.load(file) test_vid_ids = seq_dict['test'] pred_len = int(sys.argv[6]) long_term_folder = os.path.join(log_dir, 'prediction_long_term', f'model_rollout_perturb_{perturb_type}_{perturb_level}') loss_dict = {} if cfg.model_name == 'encoder-decoder' or cfg.model_name == 'encoder-decoder-64': for p_vid_idx in tqdm(test_vid_ids): vid_filepath = os.path.join(data_filepath_base, str(p_vid_idx)) total_num_frames = len(os.listdir(vid_filepath)) suf = os.listdir(vid_filepath)[0].split('.')[-1] data = None saved_folder = os.path.join(long_term_folder, str(p_vid_idx)) mkdir(saved_folder) loss_lst = [] for start_frame_idx in range(total_num_frames - 3): if start_frame_idx % 2 != 0: continue # take the initial input from ground truth data if start_frame_idx % pred_len == 0: data = [get_data_perturb(os.path.join(vid_filepath, f'{start_frame_idx}.{suf}'), perturb_type, perturb_level), get_data_perturb(os.path.join(vid_filepath, f'{start_frame_idx+1}.{suf}'), perturb_type, perturb_level)] data = (torch.cat(data, 2)).unsqueeze(0) img = tensor_to_img(data[0, :, :, :128]) img.save(os.path.join(saved_folder, f'{start_frame_idx}.{suf}')) img = tensor_to_img(data[0, :, :, 128:]) img.save(os.path.join(saved_folder, f'{start_frame_idx+1}.{suf}')) # get the target target = [get_data(os.path.join(vid_filepath, f'{start_frame_idx+2}.{suf}')), get_data(os.path.join(vid_filepath, f'{start_frame_idx+3}.{suf}'))] target = (torch.cat(target, 2)).unsqueeze(0) # feed into the model if cfg.model_name == 'encoder-decoder': output, latent = model.model(data.cuda()) if cfg.model_name == 'encoder-decoder-64': output, latent = model.model(data.cuda(), data.cuda(), False) # compute loss loss_lst.append(float(model.loss_func(output, target.cuda()).cpu().detach().numpy())) # save (2', 3'), (4', 5'), ... img = tensor_to_img(output[0, :, :, :128]) img.save(os.path.join(saved_folder, f'{start_frame_idx+2}.{suf}')) img = tensor_to_img(output[0, :, :, 128:]) img.save(os.path.join(saved_folder, f'{start_frame_idx+3}.{suf}')) # the output becomes the input data in the next iteration data = torch.tensor(output.cpu().detach().numpy()).float() loss_dict[p_vid_idx] = loss_lst # save the test loss for all the testing videos with open(os.path.join(long_term_folder, 'test_loss.json'), 'w') as file: json.dump(loss_dict, file, indent=4) if 'refine' in cfg.model_name: for p_vid_idx in tqdm(test_vid_ids): vid_filepath = os.path.join(data_filepath_base, str(p_vid_idx)) total_num_frames = len(os.listdir(vid_filepath)) suf = os.listdir(vid_filepath)[0].split('.')[-1] data = None saved_folder = os.path.join(long_term_folder, str(p_vid_idx)) mkdir(saved_folder) loss_lst = [] for start_frame_idx in range(total_num_frames - 3): if start_frame_idx % 2 != 0: continue # take the initial input from ground truth data if start_frame_idx % pred_len == 0: data = [get_data_perturb(os.path.join(vid_filepath, f'{start_frame_idx}.{suf}'), perturb_type, perturb_level), get_data_perturb(os.path.join(vid_filepath, f'{start_frame_idx+1}.{suf}'), perturb_type, perturb_level)] data = (torch.cat(data, 2)).unsqueeze(0) img = tensor_to_img(data[0, :, :, :128]) img.save(os.path.join(saved_folder, f'{start_frame_idx}.{suf}')) img = tensor_to_img(data[0, :, :, 128:]) img.save(os.path.join(saved_folder, f'{start_frame_idx+1}.{suf}')) # get the target target = [get_data(os.path.join(vid_filepath, f'{start_frame_idx+2}.{suf}')), get_data(os.path.join(vid_filepath, f'{start_frame_idx+3}.{suf}'))] target = (torch.cat(target, 2)).unsqueeze(0) # feed into the model _, latent = model.high_dim_model(data.cuda(), data.cuda(), False) latent = latent.squeeze(-1).squeeze(-1) latent_reconstructed, latent_latent = model.model(latent) output, _ = model.high_dim_model(data.cuda(), latent_reconstructed.unsqueeze(2).unsqueeze(3), True) # compute loss loss_lst.append(float(model.loss_func(output, target.cuda()).cpu().detach().numpy())) # save (2', 3'), (4', 5'), ... img = tensor_to_img(output[0, :, :, :128]) img.save(os.path.join(saved_folder, f'{start_frame_idx+2}.{suf}')) img = tensor_to_img(output[0, :, :, 128:]) img.save(os.path.join(saved_folder, f'{start_frame_idx+3}.{suf}')) # the output becomes the input data in the next iteration data = torch.tensor(output.cpu().detach().numpy()).float() loss_dict[p_vid_idx] = loss_lst # save the test loss for all the testing videos with open(os.path.join(long_term_folder, 'test_loss.json'), 'w') as file: json.dump(loss_dict, file, indent=4) def rename_ckpt_for_multi_models(ckpt): renamed_state_dict = OrderedDict() for k, v in ckpt['state_dict'].items(): if 'high_dim_model' in k: name = k.replace('high_dim_model.', '') else: name = k.replace('model.', '') renamed_state_dict[name] = v return renamed_state_dict def get_data(filepath): data = Image.open(filepath) data = data.resize((128, 128)) data = np.array(data) data = torch.tensor(data / 255.0) data = data.permute(2, 0, 1).float() return data def get_data_perturb(filepath, perturb_type, perturb_level): data = Image.open(filepath) data = data.resize((128, 128)) data = np.array(data) bg_color = np.array([215, 205, 192]) rng = np.random.RandomState(int(filepath.split('/')[-2])) new_bg_color = rng.randint(256, size=3) if perturb_type == 'background_replace': for i in range(2**(perturb_level-1)): for j in range(2**(perturb_level-1)): if np.array_equal(data[i, j], bg_color): data[i, j] = new_bg_color elif perturb_type == 'background_cover': for i in range(2**(perturb_level-1)): for j in range(2**(perturb_level-1)): data[i, j] = new_bg_color elif perturb_type == 'white_noise': sigma = 255.0 * (2**(perturb_level-1) / 128) ** 2 data = data + rng.normal(0, sigma, data.shape) else: pass data = torch.tensor(data / 255.0) data = data.permute(2, 0, 1).float() return data # out_tensor: 3 x 128 x 128 -> 128 x 128 x 3 def tensor_to_img(out_tensor): return transforms.ToPILImage()(out_tensor).convert("RGB") if __name__ == '__main__': if str(sys.argv[1]) == 'model-rollout': model_rollout() elif 'hybrid' in str(sys.argv[1]): step = int(sys.argv[1].split('-')[-1]) model_rollout_hybrid(step) elif str(sys.argv[1]) == 'latent-prediction': latent_prediction() elif 'perturb' in str(sys.argv[1]): perturb_type = str(sys.argv[1].split('-')[-2]) perturb_level = int(sys.argv[1].split('-')[-1]) model_rollout_perturb(perturb_type, perturb_level) else: assert False, "prediction scheme is not supported..."
[ "pytorch_lightning.seed_everything", "numpy.array_equal", "torch.cat", "yaml.safe_load", "pprint.pprint", "shutil.rmtree", "os.path.join", "models.VisDynamicsModel", "torch.load", "os.path.exists", "torchvision.transforms.ToPILImage", "json.dump", "tqdm.tqdm", "munch.munchify", "torch.ma...
[((1128, 1150), 'os.path.exists', 'os.path.exists', (['folder'], {}), '(folder)\n', (1142, 1150), False, 'import os\n'), ((1186, 1205), 'os.makedirs', 'os.makedirs', (['folder'], {}), '(folder)\n', (1197, 1205), False, 'import os\n'), ((1454, 1481), 'torch.manual_seed', 'torch.manual_seed', (['cfg.seed'], {}), '(cfg.seed)\n', (1471, 1481), False, 'import torch\n'), ((1736, 1754), 'pprint.pprint', 'pprint.pprint', (['cfg'], {}), '(cfg)\n', (1749, 1754), False, 'import pprint\n'), ((1765, 1778), 'munch.munchify', 'munchify', (['cfg'], {}), '(cfg)\n', (1773, 1778), False, 'from munch import munchify\n'), ((1797, 1822), 'pytorch_lightning.seed_everything', 'seed_everything', (['cfg.seed'], {}), '(cfg.seed)\n', (1812, 1822), False, 'from pytorch_lightning import Trainer, seed_everything\n'), ((1991, 2340), 'models.VisDynamicsModel', 'VisDynamicsModel', ([], {'lr': 'cfg.lr', 'seed': 'cfg.seed', 'if_cuda': 'cfg.if_cuda', 'if_test': '(True)', 'gamma': 'cfg.gamma', 'log_dir': 'log_dir', 'train_batch': 'cfg.train_batch', 'val_batch': 'cfg.val_batch', 'test_batch': 'cfg.test_batch', 'num_workers': 'cfg.num_workers', 'model_name': 'cfg.model_name', 'data_filepath': 'cfg.data_filepath', 'dataset': 'cfg.dataset', 'lr_schedule': 'cfg.lr_schedule'}), '(lr=cfg.lr, seed=cfg.seed, if_cuda=cfg.if_cuda, if_test=\n True, gamma=cfg.gamma, log_dir=log_dir, train_batch=cfg.train_batch,\n val_batch=cfg.val_batch, test_batch=cfg.test_batch, num_workers=cfg.\n num_workers, model_name=cfg.model_name, data_filepath=cfg.data_filepath,\n dataset=cfg.dataset, lr_schedule=cfg.lr_schedule)\n', (2007, 2340), False, 'from models import VisDynamicsModel\n'), ((3799, 3843), 'os.path.join', 'os.path.join', (['cfg.data_filepath', 'cfg.dataset'], {}), '(cfg.data_filepath, cfg.dataset)\n', (3811, 3843), False, 'import os\n'), ((4077, 4139), 'os.path.join', 'os.path.join', (['log_dir', '"""prediction_long_term"""', '"""model_rollout"""'], {}), "(log_dir, 'prediction_long_term', 'model_rollout')\n", (4089, 4139), False, 'import os\n'), ((9160, 9178), 'pprint.pprint', 'pprint.pprint', (['cfg'], {}), '(cfg)\n', (9173, 9178), False, 'import pprint\n'), ((9189, 9202), 'munch.munchify', 'munchify', (['cfg'], {}), '(cfg)\n', (9197, 9202), False, 'from munch import munchify\n'), ((9221, 9246), 'pytorch_lightning.seed_everything', 'seed_everything', (['cfg.seed'], {}), '(cfg.seed)\n', (9236, 9246), False, 'from pytorch_lightning import Trainer, seed_everything\n'), ((9536, 9885), 'models.VisDynamicsModel', 'VisDynamicsModel', ([], {'lr': 'cfg.lr', 'seed': 'cfg.seed', 'if_cuda': 'cfg.if_cuda', 'if_test': '(True)', 'gamma': 'cfg.gamma', 'log_dir': 'log_dir', 'train_batch': 'cfg.train_batch', 'val_batch': 'cfg.val_batch', 'test_batch': 'cfg.test_batch', 'num_workers': 'cfg.num_workers', 'model_name': 'cfg.model_name', 'data_filepath': 'cfg.data_filepath', 'dataset': 'cfg.dataset', 'lr_schedule': 'cfg.lr_schedule'}), '(lr=cfg.lr, seed=cfg.seed, if_cuda=cfg.if_cuda, if_test=\n True, gamma=cfg.gamma, log_dir=log_dir, train_batch=cfg.train_batch,\n val_batch=cfg.val_batch, test_batch=cfg.test_batch, num_workers=cfg.\n num_workers, model_name=cfg.model_name, data_filepath=cfg.data_filepath,\n dataset=cfg.dataset, lr_schedule=cfg.lr_schedule)\n', (9552, 9885), False, 'from models import VisDynamicsModel\n'), ((10401, 10432), 'torch.load', 'torch.load', (['checkpoint_filepath'], {}), '(checkpoint_filepath)\n', (10411, 10432), False, 'import torch\n'), ((10683, 10723), 'torch.load', 'torch.load', (['high_dim_checkpoint_filepath'], {}), '(high_dim_checkpoint_filepath)\n', (10693, 10723), False, 'import torch\n'), ((10942, 10986), 'os.path.join', 'os.path.join', (['cfg.data_filepath', 'cfg.dataset'], {}), '(cfg.data_filepath, cfg.dataset)\n', (10954, 10986), False, 'import os\n'), ((11220, 11291), 'os.path.join', 'os.path.join', (['log_dir', '"""prediction_long_term"""', 'f"""hybrid_rollout_{step}"""'], {}), "(log_dir, 'prediction_long_term', f'hybrid_rollout_{step}')\n", (11232, 11291), False, 'import os\n'), ((11333, 11351), 'tqdm.tqdm', 'tqdm', (['test_vid_ids'], {}), '(test_vid_ids)\n', (11337, 11351), False, 'from tqdm import tqdm\n'), ((13886, 13904), 'pprint.pprint', 'pprint.pprint', (['cfg'], {}), '(cfg)\n', (13899, 13904), False, 'import pprint\n'), ((13915, 13928), 'munch.munchify', 'munchify', (['cfg'], {}), '(cfg)\n', (13923, 13928), False, 'from munch import munchify\n'), ((13947, 13972), 'pytorch_lightning.seed_everything', 'seed_everything', (['cfg.seed'], {}), '(cfg.seed)\n', (13962, 13972), False, 'from pytorch_lightning import Trainer, seed_everything\n'), ((14141, 14490), 'models.VisDynamicsModel', 'VisDynamicsModel', ([], {'lr': 'cfg.lr', 'seed': 'cfg.seed', 'if_cuda': 'cfg.if_cuda', 'if_test': '(True)', 'gamma': 'cfg.gamma', 'log_dir': 'log_dir', 'train_batch': 'cfg.train_batch', 'val_batch': 'cfg.val_batch', 'test_batch': 'cfg.test_batch', 'num_workers': 'cfg.num_workers', 'model_name': 'cfg.model_name', 'data_filepath': 'cfg.data_filepath', 'dataset': 'cfg.dataset', 'lr_schedule': 'cfg.lr_schedule'}), '(lr=cfg.lr, seed=cfg.seed, if_cuda=cfg.if_cuda, if_test=\n True, gamma=cfg.gamma, log_dir=log_dir, train_batch=cfg.train_batch,\n val_batch=cfg.val_batch, test_batch=cfg.test_batch, num_workers=cfg.\n num_workers, model_name=cfg.model_name, data_filepath=cfg.data_filepath,\n dataset=cfg.dataset, lr_schedule=cfg.lr_schedule)\n', (14157, 14490), False, 'from models import VisDynamicsModel\n'), ((15949, 15993), 'os.path.join', 'os.path.join', (['cfg.data_filepath', 'cfg.dataset'], {}), '(cfg.data_filepath, cfg.dataset)\n', (15961, 15993), False, 'import os\n'), ((16227, 16333), 'os.path.join', 'os.path.join', (['log_dir', '"""prediction_long_term"""', 'f"""model_rollout_perturb_{perturb_type}_{perturb_level}"""'], {}), "(log_dir, 'prediction_long_term',\n f'model_rollout_perturb_{perturb_type}_{perturb_level}')\n", (16239, 16333), False, 'import os\n'), ((22024, 22037), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (22035, 22037), False, 'from collections import OrderedDict\n'), ((22328, 22348), 'PIL.Image.open', 'Image.open', (['filepath'], {}), '(filepath)\n', (22338, 22348), False, 'from PIL import Image\n'), ((22395, 22409), 'numpy.array', 'np.array', (['data'], {}), '(data)\n', (22403, 22409), True, 'import numpy as np\n'), ((22421, 22447), 'torch.tensor', 'torch.tensor', (['(data / 255.0)'], {}), '(data / 255.0)\n', (22433, 22447), False, 'import torch\n'), ((22578, 22598), 'PIL.Image.open', 'Image.open', (['filepath'], {}), '(filepath)\n', (22588, 22598), False, 'from PIL import Image\n'), ((22645, 22659), 'numpy.array', 'np.array', (['data'], {}), '(data)\n', (22653, 22659), True, 'import numpy as np\n'), ((22680, 22705), 'numpy.array', 'np.array', (['[215, 205, 192]'], {}), '([215, 205, 192])\n', (22688, 22705), True, 'import numpy as np\n'), ((23429, 23455), 'torch.tensor', 'torch.tensor', (['(data / 255.0)'], {}), '(data / 255.0)\n', (23441, 23455), False, 'import torch\n'), ((1160, 1181), 'shutil.rmtree', 'shutil.rmtree', (['folder'], {}), '(folder)\n', (1173, 1181), False, 'import shutil\n'), ((1510, 1542), 'torch.cuda.manual_seed', 'torch.cuda.manual_seed', (['cfg.seed'], {}), '(cfg.seed)\n', (1532, 1542), False, 'import torch\n'), ((2958, 2989), 'torch.load', 'torch.load', (['checkpoint_filepath'], {}), '(checkpoint_filepath)\n', (2968, 2989), False, 'import torch\n'), ((3230, 3261), 'torch.load', 'torch.load', (['checkpoint_filepath'], {}), '(checkpoint_filepath)\n', (3240, 3261), False, 'import torch\n'), ((3532, 3572), 'torch.load', 'torch.load', (['high_dim_checkpoint_filepath'], {}), '(high_dim_checkpoint_filepath)\n', (3542, 3572), False, 'import torch\n'), ((3969, 3984), 'json.load', 'json.load', (['file'], {}), '(file)\n', (3978, 3984), False, 'import json\n'), ((4271, 4289), 'tqdm.tqdm', 'tqdm', (['test_vid_ids'], {}), '(test_vid_ids)\n', (4275, 4289), False, 'from tqdm import tqdm\n'), ((6659, 6677), 'tqdm.tqdm', 'tqdm', (['test_vid_ids'], {}), '(test_vid_ids)\n', (6663, 6677), False, 'from tqdm import tqdm\n'), ((11112, 11127), 'json.load', 'json.load', (['file'], {}), '(file)\n', (11121, 11127), False, 'import json\n'), ((13700, 13736), 'json.dump', 'json.dump', (['loss_dict', 'file'], {'indent': '(4)'}), '(loss_dict, file, indent=4)\n', (13709, 13736), False, 'import json\n'), ((15108, 15139), 'torch.load', 'torch.load', (['checkpoint_filepath'], {}), '(checkpoint_filepath)\n', (15118, 15139), False, 'import torch\n'), ((15380, 15411), 'torch.load', 'torch.load', (['checkpoint_filepath'], {}), '(checkpoint_filepath)\n', (15390, 15411), False, 'import torch\n'), ((15682, 15722), 'torch.load', 'torch.load', (['high_dim_checkpoint_filepath'], {}), '(high_dim_checkpoint_filepath)\n', (15692, 15722), False, 'import torch\n'), ((16119, 16134), 'json.load', 'json.load', (['file'], {}), '(file)\n', (16128, 16134), False, 'import json\n'), ((16461, 16479), 'tqdm.tqdm', 'tqdm', (['test_vid_ids'], {}), '(test_vid_ids)\n', (16465, 16479), False, 'from tqdm import tqdm\n'), ((19213, 19231), 'tqdm.tqdm', 'tqdm', (['test_vid_ids'], {}), '(test_vid_ids)\n', (19217, 19231), False, 'from tqdm import tqdm\n'), ((1316, 1338), 'yaml.safe_load', 'yaml.safe_load', (['stream'], {}), '(stream)\n', (1330, 1338), False, 'import yaml\n'), ((3858, 3934), 'os.path.join', 'os.path.join', (['"""../datainfo"""', 'cfg.dataset', 'f"""data_split_dict_{cfg.seed}.json"""'], {}), "('../datainfo', cfg.dataset, f'data_split_dict_{cfg.seed}.json')\n", (3870, 3934), False, 'import os\n'), ((6557, 6593), 'json.dump', 'json.dump', (['loss_dict', 'file'], {'indent': '(4)'}), '(loss_dict, file, indent=4)\n', (6566, 6593), False, 'import json\n'), ((8998, 9034), 'json.dump', 'json.dump', (['loss_dict', 'file'], {'indent': '(4)'}), '(loss_dict, file, indent=4)\n', (9007, 9034), False, 'import json\n'), ((10342, 10385), 'os.path.join', 'os.path.join', (['checkpoint_filepath', '"""*.ckpt"""'], {}), "(checkpoint_filepath, '*.ckpt')\n", (10354, 10385), False, 'import os\n'), ((10615, 10667), 'os.path.join', 'os.path.join', (['high_dim_checkpoint_filepath', '"""*.ckpt"""'], {}), "(high_dim_checkpoint_filepath, '*.ckpt')\n", (10627, 10667), False, 'import os\n'), ((11001, 11077), 'os.path.join', 'os.path.join', (['"""../datainfo"""', 'cfg.dataset', 'f"""data_split_dict_{cfg.seed}.json"""'], {}), "('../datainfo', cfg.dataset, f'data_split_dict_{cfg.seed}.json')\n", (11013, 11077), False, 'import os\n'), ((11456, 11480), 'os.listdir', 'os.listdir', (['vid_filepath'], {}), '(vid_filepath)\n', (11466, 11480), False, 'import os\n'), ((13628, 13676), 'os.path.join', 'os.path.join', (['long_term_folder', '"""test_loss.json"""'], {}), "(long_term_folder, 'test_loss.json')\n", (13640, 13676), False, 'import os\n'), ((16008, 16084), 'os.path.join', 'os.path.join', (['"""../datainfo"""', 'cfg.dataset', 'f"""data_split_dict_{cfg.seed}.json"""'], {}), "('../datainfo', cfg.dataset, f'data_split_dict_{cfg.seed}.json')\n", (16020, 16084), False, 'import os\n'), ((19115, 19151), 'json.dump', 'json.dump', (['loss_dict', 'file'], {'indent': '(4)'}), '(loss_dict, file, indent=4)\n', (19124, 19151), False, 'import json\n'), ((21920, 21956), 'json.dump', 'json.dump', (['loss_dict', 'file'], {'indent': '(4)'}), '(loss_dict, file, indent=4)\n', (21929, 21956), False, 'import json\n'), ((2895, 2938), 'os.path.join', 'os.path.join', (['checkpoint_filepath', '"""*.ckpt"""'], {}), "(checkpoint_filepath, '*.ckpt')\n", (2907, 2938), False, 'import os\n'), ((3167, 3210), 'os.path.join', 'os.path.join', (['checkpoint_filepath', '"""*.ckpt"""'], {}), "(checkpoint_filepath, '*.ckpt')\n", (3179, 3210), False, 'import os\n'), ((3460, 3512), 'os.path.join', 'os.path.join', (['high_dim_checkpoint_filepath', '"""*.ckpt"""'], {}), "(high_dim_checkpoint_filepath, '*.ckpt')\n", (3472, 3512), False, 'import os\n'), ((4402, 4426), 'os.listdir', 'os.listdir', (['vid_filepath'], {}), '(vid_filepath)\n', (4412, 4426), False, 'import os\n'), ((6481, 6529), 'os.path.join', 'os.path.join', (['long_term_folder', '"""test_loss.json"""'], {}), "(long_term_folder, 'test_loss.json')\n", (6493, 6529), False, 'import os\n'), ((6790, 6814), 'os.listdir', 'os.listdir', (['vid_filepath'], {}), '(vid_filepath)\n', (6800, 6814), False, 'import os\n'), ((8922, 8970), 'os.path.join', 'os.path.join', (['long_term_folder', '"""test_loss.json"""'], {}), "(long_term_folder, 'test_loss.json')\n", (8934, 8970), False, 'import os\n'), ((13186, 13244), 'os.path.join', 'os.path.join', (['saved_folder', 'f"""{start_frame_idx + 2}.{suf}"""'], {}), "(saved_folder, f'{start_frame_idx + 2}.{suf}')\n", (13198, 13244), False, 'import os\n'), ((13320, 13378), 'os.path.join', 'os.path.join', (['saved_folder', 'f"""{start_frame_idx + 3}.{suf}"""'], {}), "(saved_folder, f'{start_frame_idx + 3}.{suf}')\n", (13332, 13378), False, 'import os\n'), ((15045, 15088), 'os.path.join', 'os.path.join', (['checkpoint_filepath', '"""*.ckpt"""'], {}), "(checkpoint_filepath, '*.ckpt')\n", (15057, 15088), False, 'import os\n'), ((15317, 15360), 'os.path.join', 'os.path.join', (['checkpoint_filepath', '"""*.ckpt"""'], {}), "(checkpoint_filepath, '*.ckpt')\n", (15329, 15360), False, 'import os\n'), ((15610, 15662), 'os.path.join', 'os.path.join', (['high_dim_checkpoint_filepath', '"""*.ckpt"""'], {}), "(high_dim_checkpoint_filepath, '*.ckpt')\n", (15622, 15662), False, 'import os\n'), ((16592, 16616), 'os.listdir', 'os.listdir', (['vid_filepath'], {}), '(vid_filepath)\n', (16602, 16616), False, 'import os\n'), ((19039, 19087), 'os.path.join', 'os.path.join', (['long_term_folder', '"""test_loss.json"""'], {}), "(long_term_folder, 'test_loss.json')\n", (19051, 19087), False, 'import os\n'), ((19344, 19368), 'os.listdir', 'os.listdir', (['vid_filepath'], {}), '(vid_filepath)\n', (19354, 19368), False, 'import os\n'), ((21844, 21892), 'os.path.join', 'os.path.join', (['long_term_folder', '"""test_loss.json"""'], {}), "(long_term_folder, 'test_loss.json')\n", (21856, 21892), False, 'import os\n'), ((22973, 23009), 'numpy.array_equal', 'np.array_equal', (['data[i, j]', 'bg_color'], {}), '(data[i, j], bg_color)\n', (22987, 23009), True, 'import numpy as np\n'), ((23601, 23624), 'torchvision.transforms.ToPILImage', 'transforms.ToPILImage', ([], {}), '()\n', (23622, 23624), False, 'from torchvision import transforms\n'), ((6011, 6069), 'os.path.join', 'os.path.join', (['saved_folder', 'f"""{start_frame_idx + 2}.{suf}"""'], {}), "(saved_folder, f'{start_frame_idx + 2}.{suf}')\n", (6023, 6069), False, 'import os\n'), ((6153, 6211), 'os.path.join', 'os.path.join', (['saved_folder', 'f"""{start_frame_idx + 3}.{suf}"""'], {}), "(saved_folder, f'{start_frame_idx + 3}.{suf}')\n", (6165, 6211), False, 'import os\n'), ((8452, 8510), 'os.path.join', 'os.path.join', (['saved_folder', 'f"""{start_frame_idx + 2}.{suf}"""'], {}), "(saved_folder, f'{start_frame_idx + 2}.{suf}')\n", (8464, 8510), False, 'import os\n'), ((8594, 8652), 'os.path.join', 'os.path.join', (['saved_folder', 'f"""{start_frame_idx + 3}.{suf}"""'], {}), "(saved_folder, f'{start_frame_idx + 3}.{suf}')\n", (8606, 8652), False, 'import os\n'), ((12212, 12270), 'os.path.join', 'os.path.join', (['vid_filepath', 'f"""{start_frame_idx + 2}.{suf}"""'], {}), "(vid_filepath, f'{start_frame_idx + 2}.{suf}')\n", (12224, 12270), False, 'import os\n'), ((12302, 12360), 'os.path.join', 'os.path.join', (['vid_filepath', 'f"""{start_frame_idx + 3}.{suf}"""'], {}), "(vid_filepath, f'{start_frame_idx + 3}.{suf}')\n", (12314, 12360), False, 'import os\n'), ((12383, 12403), 'torch.cat', 'torch.cat', (['target', '(2)'], {}), '(target, 2)\n', (12392, 12403), False, 'import torch\n'), ((18569, 18627), 'os.path.join', 'os.path.join', (['saved_folder', 'f"""{start_frame_idx + 2}.{suf}"""'], {}), "(saved_folder, f'{start_frame_idx + 2}.{suf}')\n", (18581, 18627), False, 'import os\n'), ((18711, 18769), 'os.path.join', 'os.path.join', (['saved_folder', 'f"""{start_frame_idx + 3}.{suf}"""'], {}), "(saved_folder, f'{start_frame_idx + 3}.{suf}')\n", (18723, 18769), False, 'import os\n'), ((21374, 21432), 'os.path.join', 'os.path.join', (['saved_folder', 'f"""{start_frame_idx + 2}.{suf}"""'], {}), "(saved_folder, f'{start_frame_idx + 2}.{suf}')\n", (21386, 21432), False, 'import os\n'), ((21516, 21574), 'os.path.join', 'os.path.join', (['saved_folder', 'f"""{start_frame_idx + 3}.{suf}"""'], {}), "(saved_folder, f'{start_frame_idx + 3}.{suf}')\n", (21528, 21574), False, 'import os\n'), ((5218, 5276), 'os.path.join', 'os.path.join', (['vid_filepath', 'f"""{start_frame_idx + 2}.{suf}"""'], {}), "(vid_filepath, f'{start_frame_idx + 2}.{suf}')\n", (5230, 5276), False, 'import os\n'), ((5312, 5370), 'os.path.join', 'os.path.join', (['vid_filepath', 'f"""{start_frame_idx + 3}.{suf}"""'], {}), "(vid_filepath, f'{start_frame_idx + 3}.{suf}')\n", (5324, 5370), False, 'import os\n'), ((5397, 5417), 'torch.cat', 'torch.cat', (['target', '(2)'], {}), '(target, 2)\n', (5406, 5417), False, 'import torch\n'), ((7606, 7664), 'os.path.join', 'os.path.join', (['vid_filepath', 'f"""{start_frame_idx + 2}.{suf}"""'], {}), "(vid_filepath, f'{start_frame_idx + 2}.{suf}')\n", (7618, 7664), False, 'import os\n'), ((7700, 7758), 'os.path.join', 'os.path.join', (['vid_filepath', 'f"""{start_frame_idx + 3}.{suf}"""'], {}), "(vid_filepath, f'{start_frame_idx + 3}.{suf}')\n", (7712, 7758), False, 'import os\n'), ((7785, 7805), 'torch.cat', 'torch.cat', (['target', '(2)'], {}), '(target, 2)\n', (7794, 7805), False, 'import torch\n'), ((11496, 11520), 'os.listdir', 'os.listdir', (['vid_filepath'], {}), '(vid_filepath)\n', (11506, 11520), False, 'import os\n'), ((11946, 12000), 'os.path.join', 'os.path.join', (['vid_filepath', 'f"""{start_frame_idx}.{suf}"""'], {}), "(vid_filepath, f'{start_frame_idx}.{suf}')\n", (11958, 12000), False, 'import os\n'), ((12036, 12094), 'os.path.join', 'os.path.join', (['vid_filepath', 'f"""{start_frame_idx + 1}.{suf}"""'], {}), "(vid_filepath, f'{start_frame_idx + 1}.{suf}')\n", (12048, 12094), False, 'import os\n'), ((12119, 12137), 'torch.cat', 'torch.cat', (['data', '(2)'], {}), '(data, 2)\n', (12128, 12137), False, 'import torch\n'), ((17504, 17558), 'os.path.join', 'os.path.join', (['saved_folder', 'f"""{start_frame_idx}.{suf}"""'], {}), "(saved_folder, f'{start_frame_idx}.{suf}')\n", (17516, 17558), False, 'import os\n'), ((17650, 17708), 'os.path.join', 'os.path.join', (['saved_folder', 'f"""{start_frame_idx + 1}.{suf}"""'], {}), "(saved_folder, f'{start_frame_idx + 1}.{suf}')\n", (17662, 17708), False, 'import os\n'), ((17776, 17834), 'os.path.join', 'os.path.join', (['vid_filepath', 'f"""{start_frame_idx + 2}.{suf}"""'], {}), "(vid_filepath, f'{start_frame_idx + 2}.{suf}')\n", (17788, 17834), False, 'import os\n'), ((17870, 17928), 'os.path.join', 'os.path.join', (['vid_filepath', 'f"""{start_frame_idx + 3}.{suf}"""'], {}), "(vid_filepath, f'{start_frame_idx + 3}.{suf}')\n", (17882, 17928), False, 'import os\n'), ((17955, 17975), 'torch.cat', 'torch.cat', (['target', '(2)'], {}), '(target, 2)\n', (17964, 17975), False, 'import torch\n'), ((20256, 20310), 'os.path.join', 'os.path.join', (['saved_folder', 'f"""{start_frame_idx}.{suf}"""'], {}), "(saved_folder, f'{start_frame_idx}.{suf}')\n", (20268, 20310), False, 'import os\n'), ((20402, 20460), 'os.path.join', 'os.path.join', (['saved_folder', 'f"""{start_frame_idx + 1}.{suf}"""'], {}), "(saved_folder, f'{start_frame_idx + 1}.{suf}')\n", (20414, 20460), False, 'import os\n'), ((20528, 20586), 'os.path.join', 'os.path.join', (['vid_filepath', 'f"""{start_frame_idx + 2}.{suf}"""'], {}), "(vid_filepath, f'{start_frame_idx + 2}.{suf}')\n", (20540, 20586), False, 'import os\n'), ((20622, 20680), 'os.path.join', 'os.path.join', (['vid_filepath', 'f"""{start_frame_idx + 3}.{suf}"""'], {}), "(vid_filepath, f'{start_frame_idx + 3}.{suf}')\n", (20634, 20680), False, 'import os\n'), ((20707, 20727), 'torch.cat', 'torch.cat', (['target', '(2)'], {}), '(target, 2)\n', (20716, 20727), False, 'import torch\n'), ((4446, 4470), 'os.listdir', 'os.listdir', (['vid_filepath'], {}), '(vid_filepath)\n', (4456, 4470), False, 'import os\n'), ((4936, 4990), 'os.path.join', 'os.path.join', (['vid_filepath', 'f"""{start_frame_idx}.{suf}"""'], {}), "(vid_filepath, f'{start_frame_idx}.{suf}')\n", (4948, 4990), False, 'import os\n'), ((5030, 5088), 'os.path.join', 'os.path.join', (['vid_filepath', 'f"""{start_frame_idx + 1}.{suf}"""'], {}), "(vid_filepath, f'{start_frame_idx + 1}.{suf}')\n", (5042, 5088), False, 'import os\n'), ((5117, 5135), 'torch.cat', 'torch.cat', (['data', '(2)'], {}), '(data, 2)\n', (5126, 5135), False, 'import torch\n'), ((6834, 6858), 'os.listdir', 'os.listdir', (['vid_filepath'], {}), '(vid_filepath)\n', (6844, 6858), False, 'import os\n'), ((7324, 7378), 'os.path.join', 'os.path.join', (['vid_filepath', 'f"""{start_frame_idx}.{suf}"""'], {}), "(vid_filepath, f'{start_frame_idx}.{suf}')\n", (7336, 7378), False, 'import os\n'), ((7418, 7476), 'os.path.join', 'os.path.join', (['vid_filepath', 'f"""{start_frame_idx + 1}.{suf}"""'], {}), "(vid_filepath, f'{start_frame_idx + 1}.{suf}')\n", (7430, 7476), False, 'import os\n'), ((7505, 7523), 'torch.cat', 'torch.cat', (['data', '(2)'], {}), '(data, 2)\n', (7514, 7523), False, 'import torch\n'), ((16636, 16660), 'os.listdir', 'os.listdir', (['vid_filepath'], {}), '(vid_filepath)\n', (16646, 16660), False, 'import os\n'), ((17134, 17188), 'os.path.join', 'os.path.join', (['vid_filepath', 'f"""{start_frame_idx}.{suf}"""'], {}), "(vid_filepath, f'{start_frame_idx}.{suf}')\n", (17146, 17188), False, 'import os\n'), ((17265, 17323), 'os.path.join', 'os.path.join', (['vid_filepath', 'f"""{start_frame_idx + 1}.{suf}"""'], {}), "(vid_filepath, f'{start_frame_idx + 1}.{suf}')\n", (17277, 17323), False, 'import os\n'), ((17381, 17399), 'torch.cat', 'torch.cat', (['data', '(2)'], {}), '(data, 2)\n', (17390, 17399), False, 'import torch\n'), ((19388, 19412), 'os.listdir', 'os.listdir', (['vid_filepath'], {}), '(vid_filepath)\n', (19398, 19412), False, 'import os\n'), ((19886, 19940), 'os.path.join', 'os.path.join', (['vid_filepath', 'f"""{start_frame_idx}.{suf}"""'], {}), "(vid_filepath, f'{start_frame_idx}.{suf}')\n", (19898, 19940), False, 'import os\n'), ((20017, 20075), 'os.path.join', 'os.path.join', (['vid_filepath', 'f"""{start_frame_idx + 1}.{suf}"""'], {}), "(vid_filepath, f'{start_frame_idx + 1}.{suf}')\n", (20029, 20075), False, 'import os\n'), ((20133, 20151), 'torch.cat', 'torch.cat', (['data', '(2)'], {}), '(data, 2)\n', (20142, 20151), False, 'import torch\n')]
from keras.utils import Sequence import os import signal import psutil import gc import pandas as pd import numpy as np import random import math import pysam from ..util import * import threading import pickle import pdb def kill_child_processes(parent_pid, sig=signal.SIGTERM): try: parent = psutil.Process(parent_pid) except psutil.NoSuchProcess: return children = parent.children(recursive=True) for process in children: process.send_signal(sig) def get_weights(data): w1=[float(data.shape[0])/sum(data.iloc[:,i]==1) for i in range(data.shape[1])] w0=[float(data.shape[0])/sum(data.iloc[:,i]==0) for i in range(data.shape[1])] return w1,w0 def open_data_file(data_path=None,tasks=None,chroms_to_use=None): print("running open_data_file with tasks:"+str(tasks)) if data_path.endswith('.hdf5'): if tasks==None: data=pd.read_hdf(data_path) else: data=pd.read_hdf(data_path,columns=['CHR','START','END']+tasks) else: #treat as bed file if tasks==None: data=pd.read_csv(data_path,header=0,sep='\t') else: data=pd.read_csv(data_path,header=0,sep='\t',nrows=1) chrom_col=data.columns[0] start_col=data.columns[1] end_col=data.columns[2] data=pd.read_csv(data_path,header=0,sep='\t',usecols=[chrom_col,start_col,end_col]+tasks) print("loaded labels") print("chroms_to_use:"+str(chroms_to_use)) print(data.head()) try: data=data.set_index(['CHR','START','END']) print('set index to CHR, START, END') except: pass if chroms_to_use!=None: data=data[np.in1d(data.index.get_level_values(0), chroms_to_use)] print("filtered on chroms_to_use") print("data.shape:"+str(data.shape), data.columns) return data #use wrappers for keras Sequence generator class to allow batch shuffling upon epoch end class DataGenerator(Sequence): def __init__(self, index_path, input_path, output_path, num_inputs, num_outputs, ref_fasta=None, batch_size=128, add_revcomp=False, index_tasks=None, tasks=None, shuffled_ref_negatives=False, chroms_to_use=None, get_w1_w0=False, expand_dims=True, upsample_thresh_list=None, upsample_ratio_list=None, shuffle=True, return_coords=False): self.return_coords=return_coords self.expand_dims=expand_dims self.shuffle=shuffle self.batch_size=batch_size self.ref_fasta=ref_fasta self.chroms_to_use=chroms_to_use #decide if reverse complement should be used self.add_revcomp=add_revcomp if add_revcomp==True: self.batch_size=int(batch_size/2) #determine whether negative set should consist of the shuffled refs. # If so, split batch size in 2, as each batch will be augmented with shuffled ref negatives # in ratio equal to positives self.shuffled_ref_negatives=shuffled_ref_negatives if self.shuffled_ref_negatives==True: self.batch_size=int(self.batch_size/2) #get the index, input, and output files self.index_tasks=index_tasks if tasks is None: tasks=[None]*num_inputs else: tasks=[i.split(',') for i in tasks] + [None]*(num_inputs-1) self.tasks=tasks print("TASKS:"+str(self.tasks)) self.index_path=index_path self.input_path=input_path self.output_path=output_path self.num_inputs=num_inputs self.num_outputs=num_outputs self.file_to_pd=self.get_file_to_pd() self.indices=self.file_to_pd[self.index_path] self.num_indices=self.indices.shape[0] print("indices:"+str(self.indices.head())) print("num_indices:"+str(self.num_indices)) #handle task-specific weights -- this is a bit outdated and may be removed in the future. if get_w1_w0==True: assert self.data is not None w1,w0=get_weights(self.data) self.w1=w1 self.w0=w0 #set variables needed for upsampling the positives self.upsample_thresh_list=upsample_thresh_list self.upsample_ratio_list=upsample_ratio_list #generate the upsampled threshold index subgroups print("creating upsampling logic for generator") print("self.upsample_thresh_list:"+str(self.upsample_thresh_list)) if self.upsample_thresh_list is not None: self.get_upsampled_indices() else: self.indices=self.indices.index.tolist() if self.shuffle == True: np.random.shuffle(self.indices) self.lock=threading.Lock() print("generator initialized") def get_file_to_pd(self): ''' make sure all input/output/index files are loaded only once in case there's overlap generate a dictionary of file name to pandas data frame of file contents ''' file_to_df={} print(self.index_path) print(self.tasks) if self.tasks[0] is not None: file_to_df[self.index_path]=open_data_file(data_path=self.index_path,tasks=[ti[0] for ti in self.tasks if ti is not None],chroms_to_use=self.chroms_to_use) else: file_to_df[self.index_path]=open_data_file(data_path=self.index_path,tasks=self.index_tasks,chroms_to_use=self.chroms_to_use) print("got index_path df") for i in range(self.num_inputs): cur_input=self.input_path[i] print(cur_input) if cur_input=="seq": continue if cur_input in file_to_df: continue file_to_df[self.input_path[i]]=open_data_file(data_path=cur_input,tasks=self.tasks[i],chroms_to_use=self.chroms_to_use) print('got input') for i in range(self.num_outputs): cur_output=self.output_path[i] print(cur_output) if cur_output in file_to_df: print('skipped output reading') continue file_to_df[cur_output]=open_data_file(data_path=cur_output,tasks=self.tasks[i],chroms_to_use=self.chroms_to_use) return file_to_df def get_upsampled_indices(self): ''' several levels of upsampling are handled self.upsample_thresh_list -- list of thresholds for upsampling the dataset self.upsample_ratio_list -- fraction of batch to be generated at each threshold, length of this list = len(self.upsample_thresh_list)-1 i.e. upsample_thresh_list=[0,0.01,1], upsample_ratio_list=[0.7,0.2] means 70% of samples should be in the range [0,0.1), 20% of samples should be in the range [0.1,1), and remaining 10% of samples are in the range [1,inf) ''' self.upsampled_coord_indices = {} self.upsampled_numerical_indices = {} self.batch_sizes = [] print("upsample thresh list:"+str(self.upsample_thresh_list)) if self.upsample_ratio_list is None: #all thresholds represented equally in the batch self.upsample_ratio = 1 / (len(self.upsample_thresh_list) - 1) self.upsample_ratio_list = [self.upsample_ratio for i in range(len(self.upsample_thresh_list) - 1)] print("upsample ratio list: " + str(self.upsample_ratio_list)) for ind in range(len(self.upsample_thresh_list)-1): lower_thresh_bound=self.upsample_thresh_list[ind] upper_thresh_bound=self.upsample_thresh_list[ind+1] #get the sub-batch that contains values within this value threshold sub_batch_size=int(self.batch_size*self.upsample_ratio_list[ind]) self.batch_sizes.append(sub_batch_size) #get the coordinates where all values fall in the range [lower_thresh_bound, upper_thresh_bound) sub_batch_coords=self.indices.loc[(self.indices>=lower_thresh_bound).any(axis=1) & (self.indices < upper_thresh_bound).all(axis=1)].index len_sub_batch_coords=len(sub_batch_coords) self.upsampled_coord_indices[ind]=sub_batch_coords self.upsampled_numerical_indices[ind] = np.arange(len_sub_batch_coords) #number of times the current sub-set of upsampled indices should be wrapped to get to num_indices values num_wraps=math.ceil(self.num_indices/len_sub_batch_coords) self.upsampled_numerical_indices[ind] = np.tile(self.upsampled_numerical_indices[ind], num_wraps)[0:self.num_indices] #shuffle the sub-set of indices, if specified if self.shuffle == True: np.random.shuffle(self.upsampled_numerical_indices[ind]) #handle the final index (i.e. unspecified upper bound) ind=len(self.upsample_thresh_list)-1 lower_thresh_bound=self.upsample_thresh_list[ind] sub_batch_size=int(self.batch_size-sum(self.batch_sizes)) self.batch_sizes.append(sub_batch_size) sub_batch_coords=self.indices.loc[(self.indices>=lower_thresh_bound).any(axis=1)].index len_sub_batch_coords=len(sub_batch_coords) self.upsampled_coord_indices[ind]=sub_batch_coords self.upsampled_numerical_indices[ind] = np.arange(len_sub_batch_coords) #number of times the current sub-set of upsampled indices should be wrapped to get to num_indices values num_wraps=math.ceil(self.num_indices/len_sub_batch_coords) self.upsampled_numerical_indices[ind] = np.tile(self.upsampled_numerical_indices[ind], num_wraps)[0:self.num_indices] #shuffle the sub-set of indices, if specified if self.shuffle == True: np.random.shuffle(self.upsampled_numerical_indices[ind]) del self.indices return def __len__(self): return math.ceil(self.num_indices/self.batch_size) def get_coords(self,idx): if self.upsample_thresh_list is not None: all_bed_entries=[] for ind,val in enumerate(self.batch_sizes): batch_indices = self.upsampled_numerical_indices[ind][idx*val:(idx+1)*val] bed_entries = self.upsampled_coord_indices[ind][batch_indices].tolist() all_bed_entries+=bed_entries else: all_bed_entries=self.indices[idx*self.batch_size:(idx+1)*self.batch_size] return all_bed_entries def get_seq(self,coords): seqs=[self.ref.fetch(i[0],i[1],i[2]) for i in coords] return seqs def get_pd_vals(self,coords,io_index): try: return self.file_to_pd[io_index].loc[coords].values except: raise Exception("could not fetch coords:"+str(coords)) def transform_seq(self,seqs): if self.add_revcomp==True: #add in the reverse-complemented sequences for training. seqs_rc=[revcomp(s) for s in seqs] seqs=seqs+seqs_rc if self.shuffled_ref_negatives is True: #generate the corresponding negative set by dinucleotide-shuffling the sequences seqs_shuffled=[dinuc_shuffle(s) for s in seqs] seqs=seqs+seqs_shuffled return seqs def transform_vals(self,vals): if self.add_revcomp==True: vals=np.concatenate((vals,vals),axis=0) if self.shuffled_ref_negatives is True: val_shape=vals.shape vals=np.concatenate((vals,np.zeros(vals_shape))) return vals def __getitem__(self,idx): try: gc.unfreeze() self.lock.acquire() #print("STARTING") self.ref=pysam.FastaFile(self.ref_fasta) #get the coordinates for the current batch coords=self.get_coords(idx) #print("GOT COORDS") #get the inputs X=[] for cur_input_index in range(self.num_inputs): cur_input=self.input_path[cur_input_index] if cur_input=="seq": cur_x=one_hot_encode(self.transform_seq(self.get_seq(coords))) if self.expand_dims==True: cur_x=np.expand_dims(cur_x,axis=1) else: #extract values from pandas df cur_x=self.transform_vals(self.get_pd_vals(coords,cur_input)) X.append(cur_x) #get the outputs y=[] for cur_output_index in range(self.num_outputs): cur_output=self.output_path[cur_output_index] if cur_output=="seq": cur_y=one_hot_encode(self.transform_seq(self.get_seq(coords))) if self.expand_dims==True: cur_y=np.expand_dims(cur_y,axis=1) else: cur_y=self.transform_vals(self.get_pd_vals(coords,cur_output)) y.append(cur_y) self.lock.release() #return the batch as an X,y tuple #print("SUCCESS") if self.return_coords is False: return (X,y) else: return (X,y,coords) except Exception as e: print(str(e)+" from id:"+str(idx)) kill_child_processes(os.getpid()) raise def on_epoch_end(self): #if upsampling is being used, shuffle the positive and negative indices if self.shuffle==True: if self.upsample_thresh_list is not None: for ind,val in enumerate(self.batch_sizes): np.random.shuffle(self.upsampled_numerical_indices[ind]) else: np.random.shuffle(self.indices)
[ "psutil.Process", "os.getpid", "pandas.read_hdf", "numpy.concatenate", "math.ceil", "pandas.read_csv", "pysam.FastaFile", "numpy.zeros", "numpy.expand_dims", "threading.Lock", "numpy.arange", "numpy.tile", "numpy.random.shuffle", "gc.unfreeze" ]
[((308, 334), 'psutil.Process', 'psutil.Process', (['parent_pid'], {}), '(parent_pid)\n', (322, 334), False, 'import psutil\n'), ((5035, 5051), 'threading.Lock', 'threading.Lock', ([], {}), '()\n', (5049, 5051), False, 'import threading\n'), ((9662, 9693), 'numpy.arange', 'np.arange', (['len_sub_batch_coords'], {}), '(len_sub_batch_coords)\n', (9671, 9693), True, 'import numpy as np\n'), ((9834, 9884), 'math.ceil', 'math.ceil', (['(self.num_indices / len_sub_batch_coords)'], {}), '(self.num_indices / len_sub_batch_coords)\n', (9843, 9884), False, 'import math\n'), ((10267, 10312), 'math.ceil', 'math.ceil', (['(self.num_indices / self.batch_size)'], {}), '(self.num_indices / self.batch_size)\n', (10276, 10312), False, 'import math\n'), ((903, 925), 'pandas.read_hdf', 'pd.read_hdf', (['data_path'], {}), '(data_path)\n', (914, 925), True, 'import pandas as pd\n'), ((957, 1020), 'pandas.read_hdf', 'pd.read_hdf', (['data_path'], {'columns': "(['CHR', 'START', 'END'] + tasks)"}), "(data_path, columns=['CHR', 'START', 'END'] + tasks)\n", (968, 1020), True, 'import pandas as pd\n'), ((1094, 1136), 'pandas.read_csv', 'pd.read_csv', (['data_path'], {'header': '(0)', 'sep': '"""\t"""'}), "(data_path, header=0, sep='\\t')\n", (1105, 1136), True, 'import pandas as pd\n'), ((1166, 1217), 'pandas.read_csv', 'pd.read_csv', (['data_path'], {'header': '(0)', 'sep': '"""\t"""', 'nrows': '(1)'}), "(data_path, header=0, sep='\\t', nrows=1)\n", (1177, 1217), True, 'import pandas as pd\n'), ((1344, 1439), 'pandas.read_csv', 'pd.read_csv', (['data_path'], {'header': '(0)', 'sep': '"""\t"""', 'usecols': '([chrom_col, start_col, end_col] + tasks)'}), "(data_path, header=0, sep='\\t', usecols=[chrom_col, start_col,\n end_col] + tasks)\n", (1355, 1439), True, 'import pandas as pd\n'), ((8578, 8609), 'numpy.arange', 'np.arange', (['len_sub_batch_coords'], {}), '(len_sub_batch_coords)\n', (8587, 8609), True, 'import numpy as np\n'), ((8763, 8813), 'math.ceil', 'math.ceil', (['(self.num_indices / len_sub_batch_coords)'], {}), '(self.num_indices / len_sub_batch_coords)\n', (8772, 8813), False, 'import math\n'), ((9931, 9988), 'numpy.tile', 'np.tile', (['self.upsampled_numerical_indices[ind]', 'num_wraps'], {}), '(self.upsampled_numerical_indices[ind], num_wraps)\n', (9938, 9988), True, 'import numpy as np\n'), ((10109, 10165), 'numpy.random.shuffle', 'np.random.shuffle', (['self.upsampled_numerical_indices[ind]'], {}), '(self.upsampled_numerical_indices[ind])\n', (10126, 10165), True, 'import numpy as np\n'), ((11740, 11776), 'numpy.concatenate', 'np.concatenate', (['(vals, vals)'], {'axis': '(0)'}), '((vals, vals), axis=0)\n', (11754, 11776), True, 'import numpy as np\n'), ((12012, 12025), 'gc.unfreeze', 'gc.unfreeze', ([], {}), '()\n', (12023, 12025), False, 'import gc\n'), ((12111, 12142), 'pysam.FastaFile', 'pysam.FastaFile', (['self.ref_fasta'], {}), '(self.ref_fasta)\n', (12126, 12142), False, 'import pysam\n'), ((4985, 5016), 'numpy.random.shuffle', 'np.random.shuffle', (['self.indices'], {}), '(self.indices)\n', (5002, 5016), True, 'import numpy as np\n'), ((8864, 8921), 'numpy.tile', 'np.tile', (['self.upsampled_numerical_indices[ind]', 'num_wraps'], {}), '(self.upsampled_numerical_indices[ind], num_wraps)\n', (8871, 8921), True, 'import numpy as np\n'), ((9054, 9110), 'numpy.random.shuffle', 'np.random.shuffle', (['self.upsampled_numerical_indices[ind]'], {}), '(self.upsampled_numerical_indices[ind])\n', (9071, 9110), True, 'import numpy as np\n'), ((14132, 14163), 'numpy.random.shuffle', 'np.random.shuffle', (['self.indices'], {}), '(self.indices)\n', (14149, 14163), True, 'import numpy as np\n'), ((11895, 11915), 'numpy.zeros', 'np.zeros', (['vals_shape'], {}), '(vals_shape)\n', (11903, 11915), True, 'import numpy as np\n'), ((13732, 13743), 'os.getpid', 'os.getpid', ([], {}), '()\n', (13741, 13743), False, 'import os\n'), ((14041, 14097), 'numpy.random.shuffle', 'np.random.shuffle', (['self.upsampled_numerical_indices[ind]'], {}), '(self.upsampled_numerical_indices[ind])\n', (14058, 14097), True, 'import numpy as np\n'), ((12632, 12661), 'numpy.expand_dims', 'np.expand_dims', (['cur_x'], {'axis': '(1)'}), '(cur_x, axis=1)\n', (12646, 12661), True, 'import numpy as np\n'), ((13217, 13246), 'numpy.expand_dims', 'np.expand_dims', (['cur_y'], {'axis': '(1)'}), '(cur_y, axis=1)\n', (13231, 13246), True, 'import numpy as np\n')]
''' This script executes 2D FFT convolution on images in grayscale. Usage: Run without argument will use builtin Lena image: python fftconvolve.py Or, specify an image to use python fftconvolve.py myimage.jpg python fftconvolve.py myimage.png = Getting The Requirements = For Conda user, run the following to ensure the dependencies are fulfilled: conda install scipy matplotlib You may need to install PIL from pip. conda install pip pip install PIL DvG Note: conda install -c numba pyculib (deprecated though) ''' from __future__ import print_function import sys from timeit import default_timer as timer import numpy as np from scipy.signal import fftconvolve from scipy import misc, ndimage from matplotlib import pyplot as plt from accelerate.cuda.fft import FFTPlan from numba import cuda @cuda.jit('void(complex64[:,:], complex64[:,:])') def mult_inplace(img, resp): i, j = cuda.grid(2) if j < img.shape[0] and i < img.shape[1]: img[j, i] *= resp[j, i] def best_grid_size(size, tpb): bpg = np.ceil(np.array(size, dtype=np.float) / tpb).astype(np.int).tolist() return tuple(bpg) def main(): # Build Filter laplacian_pts = ''' -4 -1 0 -1 -4 -1 2 3 2 -1 0 3 4 3 0 -1 2 3 2 -1 -4 -1 0 -1 -4 '''.split() laplacian = np.array(laplacian_pts, dtype=np.float32).reshape(5, 5) # Build Image try: filename = sys.argv[1] image = ndimage.imread(filename, flatten=True).astype(np.float32) except IndexError: image = misc.face(gray=True).astype(np.float32) print("Image size: %s" % (image.shape,)) response = np.zeros_like(image) response[:5, :5] = laplacian # CPU ts = timer() cvimage_cpu = fftconvolve(image, laplacian, mode='same') te = timer() print('CPU: %.2fs' % (te - ts)) # GPU threadperblock = 32, 8 blockpergrid = best_grid_size(tuple(reversed(image.shape)), threadperblock) print('kernel config: %s x %s' % (blockpergrid, threadperblock)) # Trigger initialization the cuFFT system. # This takes significant time for small dataset. # We should not be including the time wasted here FFTPlan(shape=image.shape, itype=np.complex64, otype=np.complex64) # Start GPU timer ts = timer() image_complex = image.astype(np.complex64) response_complex = response.astype(np.complex64) stream1 = cuda.stream() stream2 = cuda.stream() fftplan1 = FFTPlan(shape=image.shape, itype=np.complex64, otype=np.complex64, stream=stream1) fftplan2 = FFTPlan(shape=image.shape, itype=np.complex64, otype=np.complex64, stream=stream2) # pagelock memory with cuda.pinned(image_complex, response_complex): # We can overlap the transfer of response_complex with the forward FFT # on image_complex. d_image_complex = cuda.to_device(image_complex, stream=stream1) d_response_complex = cuda.to_device(response_complex, stream=stream2) fftplan1.forward(d_image_complex, out=d_image_complex) fftplan2.forward(d_response_complex, out=d_response_complex) stream2.synchronize() mult_inplace[blockpergrid, threadperblock, stream1](d_image_complex, d_response_complex) fftplan1.inverse(d_image_complex, out=d_image_complex) # implicitly synchronizes the streams cvimage_gpu = d_image_complex.copy_to_host().real / np.prod(image.shape) te = timer() print('GPU: %.2fs' % (te - ts)) # Plot the results plt.subplot(1, 2, 1) plt.title('CPU') plt.imshow(cvimage_cpu, cmap=plt.cm.gray) plt.axis('off') plt.subplot(1, 2, 2) plt.title('GPU') plt.imshow(cvimage_gpu, cmap=plt.cm.gray) plt.axis('off') plt.show() if __name__ == '__main__': main()
[ "matplotlib.pyplot.title", "matplotlib.pyplot.subplot", "numpy.zeros_like", "numba.cuda.stream", "matplotlib.pyplot.show", "timeit.default_timer", "accelerate.cuda.fft.FFTPlan", "matplotlib.pyplot.imshow", "scipy.misc.face", "matplotlib.pyplot.axis", "numba.cuda.to_device", "numba.cuda.pinned"...
[((837, 885), 'numba.cuda.jit', 'cuda.jit', (['"""void(complex64[:,:], complex64[:,:])"""'], {}), "('void(complex64[:,:], complex64[:,:])')\n", (845, 885), False, 'from numba import cuda\n'), ((926, 938), 'numba.cuda.grid', 'cuda.grid', (['(2)'], {}), '(2)\n', (935, 938), False, 'from numba import cuda\n'), ((1654, 1674), 'numpy.zeros_like', 'np.zeros_like', (['image'], {}), '(image)\n', (1667, 1674), True, 'import numpy as np\n'), ((1728, 1735), 'timeit.default_timer', 'timer', ([], {}), '()\n', (1733, 1735), True, 'from timeit import default_timer as timer\n'), ((1754, 1796), 'scipy.signal.fftconvolve', 'fftconvolve', (['image', 'laplacian'], {'mode': '"""same"""'}), "(image, laplacian, mode='same')\n", (1765, 1796), False, 'from scipy.signal import fftconvolve\n'), ((1806, 1813), 'timeit.default_timer', 'timer', ([], {}), '()\n', (1811, 1813), True, 'from timeit import default_timer as timer\n'), ((2196, 2262), 'accelerate.cuda.fft.FFTPlan', 'FFTPlan', ([], {'shape': 'image.shape', 'itype': 'np.complex64', 'otype': 'np.complex64'}), '(shape=image.shape, itype=np.complex64, otype=np.complex64)\n', (2203, 2262), False, 'from accelerate.cuda.fft import FFTPlan\n'), ((2295, 2302), 'timeit.default_timer', 'timer', ([], {}), '()\n', (2300, 2302), True, 'from timeit import default_timer as timer\n'), ((2418, 2431), 'numba.cuda.stream', 'cuda.stream', ([], {}), '()\n', (2429, 2431), False, 'from numba import cuda\n'), ((2446, 2459), 'numba.cuda.stream', 'cuda.stream', ([], {}), '()\n', (2457, 2459), False, 'from numba import cuda\n'), ((2476, 2563), 'accelerate.cuda.fft.FFTPlan', 'FFTPlan', ([], {'shape': 'image.shape', 'itype': 'np.complex64', 'otype': 'np.complex64', 'stream': 'stream1'}), '(shape=image.shape, itype=np.complex64, otype=np.complex64, stream=\n stream1)\n', (2483, 2563), False, 'from accelerate.cuda.fft import FFTPlan\n'), ((2597, 2684), 'accelerate.cuda.fft.FFTPlan', 'FFTPlan', ([], {'shape': 'image.shape', 'itype': 'np.complex64', 'otype': 'np.complex64', 'stream': 'stream2'}), '(shape=image.shape, itype=np.complex64, otype=np.complex64, stream=\n stream2)\n', (2604, 2684), False, 'from accelerate.cuda.fft import FFTPlan\n'), ((3562, 3569), 'timeit.default_timer', 'timer', ([], {}), '()\n', (3567, 3569), True, 'from timeit import default_timer as timer\n'), ((3634, 3654), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(2)', '(1)'], {}), '(1, 2, 1)\n', (3645, 3654), True, 'from matplotlib import pyplot as plt\n'), ((3659, 3675), 'matplotlib.pyplot.title', 'plt.title', (['"""CPU"""'], {}), "('CPU')\n", (3668, 3675), True, 'from matplotlib import pyplot as plt\n'), ((3680, 3721), 'matplotlib.pyplot.imshow', 'plt.imshow', (['cvimage_cpu'], {'cmap': 'plt.cm.gray'}), '(cvimage_cpu, cmap=plt.cm.gray)\n', (3690, 3721), True, 'from matplotlib import pyplot as plt\n'), ((3726, 3741), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (3734, 3741), True, 'from matplotlib import pyplot as plt\n'), ((3747, 3767), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(2)', '(2)'], {}), '(1, 2, 2)\n', (3758, 3767), True, 'from matplotlib import pyplot as plt\n'), ((3772, 3788), 'matplotlib.pyplot.title', 'plt.title', (['"""GPU"""'], {}), "('GPU')\n", (3781, 3788), True, 'from matplotlib import pyplot as plt\n'), ((3793, 3834), 'matplotlib.pyplot.imshow', 'plt.imshow', (['cvimage_gpu'], {'cmap': 'plt.cm.gray'}), '(cvimage_gpu, cmap=plt.cm.gray)\n', (3803, 3834), True, 'from matplotlib import pyplot as plt\n'), ((3839, 3854), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (3847, 3854), True, 'from matplotlib import pyplot as plt\n'), ((3860, 3870), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3868, 3870), True, 'from matplotlib import pyplot as plt\n'), ((2735, 2779), 'numba.cuda.pinned', 'cuda.pinned', (['image_complex', 'response_complex'], {}), '(image_complex, response_complex)\n', (2746, 2779), False, 'from numba import cuda\n'), ((2915, 2960), 'numba.cuda.to_device', 'cuda.to_device', (['image_complex'], {'stream': 'stream1'}), '(image_complex, stream=stream1)\n', (2929, 2960), False, 'from numba import cuda\n'), ((2990, 3038), 'numba.cuda.to_device', 'cuda.to_device', (['response_complex'], {'stream': 'stream2'}), '(response_complex, stream=stream2)\n', (3004, 3038), False, 'from numba import cuda\n'), ((1324, 1365), 'numpy.array', 'np.array', (['laplacian_pts'], {'dtype': 'np.float32'}), '(laplacian_pts, dtype=np.float32)\n', (1332, 1365), True, 'import numpy as np\n'), ((3531, 3551), 'numpy.prod', 'np.prod', (['image.shape'], {}), '(image.shape)\n', (3538, 3551), True, 'import numpy as np\n'), ((1455, 1493), 'scipy.ndimage.imread', 'ndimage.imread', (['filename'], {'flatten': '(True)'}), '(filename, flatten=True)\n', (1469, 1493), False, 'from scipy import misc, ndimage\n'), ((1552, 1572), 'scipy.misc.face', 'misc.face', ([], {'gray': '(True)'}), '(gray=True)\n', (1561, 1572), False, 'from scipy import misc, ndimage\n'), ((1068, 1098), 'numpy.array', 'np.array', (['size'], {'dtype': 'np.float'}), '(size, dtype=np.float)\n', (1076, 1098), True, 'import numpy as np\n')]
""" Contains class that runs inferencing """ import torch import numpy as np from networks.RecursiveUNet import UNet from utils.utils import med_reshape import torch.nn.functional as F class UNetInferenceAgent: """ Stores model and parameters and some methods to handle inferencing """ def __init__(self, parameter_file_path='', model=None, device="cpu", patch_size=64): self.model = model self.patch_size = patch_size self.device = device if model is None: self.model = UNet(num_classes=3) if parameter_file_path: self.model.load_state_dict(torch.load(parameter_file_path, map_location=self.device)) self.model.to(device) def single_volume_inference_unpadded(self, volume): """ Runs inference on a single volume of arbitrary patch size, padding it to the conformant size first Arguments: volume {Numpy array} -- 3D array representing the volume Returns: 3D NumPy array with prediction mask """ volume =(volume.astype(float))/np.max(volume) reshaped_image = med_reshape(volume, new_shape=(volume.shape[0], self.patch_size, self.patch_size)).astype(np.single) return reshaped_image #raise NotImplementedError def single_volume_inference(self, volume): """ Runs inference on a single volume of conformant patch size Arguments: volume {Numpy array} -- 3D array representing the volume Returns: 3D NumPy array with prediction mask """ # Assuming volume is a numpy array of shape [X,Y,Z] and we need to slice X axis # TASK: Write code that will create mask for each slice across the X (0th) dimension. After # that, put all slices into a 3D Numpy array. You can verify if your method is # correct by running it on one of the volumes in your training set and comparing # with the label in 3D Slicer. volume=self.single_volume_inference_unpadded(volume) volume=volume.reshape([volume.shape[0],1,volume.shape[1],volume.shape[2]]) #slices = [] self.model.eval() with torch.no_grad(): #for batch_ind in range() data = torch.from_numpy(volume).to(self.device) print(data.shape) prediction = self.model(data) prediction_softmax = F.softmax(prediction, dim=1) res=(prediction_softmax).squeeze(0).cpu().detach().numpy() slices=res return slices
[ "utils.utils.med_reshape", "torch.load", "torch.nn.functional.softmax", "numpy.max", "networks.RecursiveUNet.UNet", "torch.no_grad", "torch.from_numpy" ]
[((535, 554), 'networks.RecursiveUNet.UNet', 'UNet', ([], {'num_classes': '(3)'}), '(num_classes=3)\n', (539, 554), False, 'from networks.RecursiveUNet import UNet\n'), ((1107, 1121), 'numpy.max', 'np.max', (['volume'], {}), '(volume)\n', (1113, 1121), True, 'import numpy as np\n'), ((2217, 2232), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (2230, 2232), False, 'import torch\n'), ((2437, 2465), 'torch.nn.functional.softmax', 'F.softmax', (['prediction'], {'dim': '(1)'}), '(prediction, dim=1)\n', (2446, 2465), True, 'import torch.nn.functional as F\n'), ((627, 684), 'torch.load', 'torch.load', (['parameter_file_path'], {'map_location': 'self.device'}), '(parameter_file_path, map_location=self.device)\n', (637, 684), False, 'import torch\n'), ((1147, 1234), 'utils.utils.med_reshape', 'med_reshape', (['volume'], {'new_shape': '(volume.shape[0], self.patch_size, self.patch_size)'}), '(volume, new_shape=(volume.shape[0], self.patch_size, self.\n patch_size))\n', (1158, 1234), False, 'from utils.utils import med_reshape\n'), ((2291, 2315), 'torch.from_numpy', 'torch.from_numpy', (['volume'], {}), '(volume)\n', (2307, 2315), False, 'import torch\n')]
# Copyright 2020 The Magenta Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utilities for fine alignment. CQT calculations and NoteSequence manipulations are done in Python. For speed, DTW calculations are done in C++ by calling the 'align' program, which is specifically intended to be used with this library. Communication between Python and C++ is done with a protobuf. """ import os import subprocess import tempfile from absl import logging import alignment_pb2 import librosa from magenta.music import midi_synth from magenta.music import sequences_lib import numpy as np # Constants based on craffel's example alignment script: # https://github.com/craffel/pretty-midi/blob/master/examples/align_midi.py SAMPLE_RATE = 22050 CQT_HOP_LENGTH_FINE = 64 # ~3ms CQT_N_BINS = 48 CQT_BINS_PER_OCTAVE = 12 CQT_FMIN = librosa.midi_to_hz(36) ALIGN_BINARY = './align' def extract_cqt(samples, sample_rate, cqt_hop_length): """Transforms the contents of a wav/mp3 file into a series of CQT frames.""" cqt = np.abs(librosa.core.cqt( samples, sample_rate, hop_length=cqt_hop_length, fmin=CQT_FMIN, n_bins=CQT_N_BINS, bins_per_octave=CQT_BINS_PER_OCTAVE), dtype=np.float32) # Compute log-amplitude cqt = librosa.power_to_db(cqt) return cqt def align_cpp(samples, sample_rate, ns, cqt_hop_length, sf2_path, penalty_mul=1.0, band_radius_seconds=.5): """Aligns the notesequence to the wav file using C++ DTW. Args: samples: Samples to align. sample_rate: Sample rate for samples. ns: The source notesequence to align. cqt_hop_length: Hop length to use for CQT calculations. sf2_path: Path to SF2 file for synthesis. penalty_mul: Penalty multiplier to use for non-diagonal moves. band_radius_seconds: What size of band radius to use for restricting DTW. Raises: RuntimeError: If notes are skipped during alignment. Returns: samples: The samples used from the wav file. aligned_ns: The aligned version of the notesequence. remaining_ns: Any remaining notesequence that extended beyond the length of the wav file. """ logging.info('Synthesizing') ns_samples = midi_synth.fluidsynth( ns, sf2_path=sf2_path, sample_rate=sample_rate).astype(np.float32) # It is critical that ns_samples and samples are the same length because the # alignment code does not do subsequence alignment. ns_samples = np.pad(ns_samples, (0, max(0, samples.shape[0] - ns_samples.shape[0])), 'constant') # Pad samples too, if needed, because there are some cases where the # synthesized NoteSequence is actually longer. samples = np.pad(samples, (0, max(0, ns_samples.shape[0] - samples.shape[0])), 'constant') # Note that we skip normalization here becasue it happens in C++. logging.info('source_cqt') source_cqt = extract_cqt(ns_samples, sample_rate, cqt_hop_length) logging.info('dest_cqt') dest_cqt = extract_cqt(samples, sample_rate, cqt_hop_length) alignment_task = alignment_pb2.AlignmentTask() alignment_task.sequence_1.x = source_cqt.shape[0] alignment_task.sequence_1.y = source_cqt.shape[1] for c in source_cqt.reshape([-1]): alignment_task.sequence_1.content.append(c) alignment_task.sequence_2.x = dest_cqt.shape[0] alignment_task.sequence_2.y = dest_cqt.shape[1] for c in dest_cqt.reshape([-1]): alignment_task.sequence_2.content.append(c) seconds_per_frame = cqt_hop_length / sample_rate alignment_task.band_radius = int(band_radius_seconds / seconds_per_frame) alignment_task.penalty = 0 alignment_task.penalty_mul = penalty_mul # Write to file. fh, temp_path = tempfile.mkstemp(suffix='.proto') os.close(fh) with open(temp_path, 'w') as f: f.write(alignment_task.SerializeToString()) # Align with C++ program. subprocess.check_call([ALIGN_BINARY, temp_path]) # Read file. with open(temp_path + '.result') as f: result = alignment_pb2.AlignmentResult.FromString(f.read()) # Clean up. os.remove(temp_path) os.remove(temp_path + '.result') logging.info('Aligning NoteSequence with warp path.') warp_seconds_i = np.array([i * seconds_per_frame for i in result.i]) warp_seconds_j = np.array([j * seconds_per_frame for j in result.j]) time_diffs = np.abs(warp_seconds_i - warp_seconds_j) warps = np.abs(time_diffs[1:] - time_diffs[:-1]) stats = { 'alignment_score': result.score, 'warp_mean_s': np.mean(warps), 'warp_median_s': np.median(warps), 'warp_max_s': np.max(warps), 'warp_min_s': np.min(warps), 'time_diff_mean_s': np.mean(time_diffs), 'time_diff_median_s': np.median(time_diffs), 'time_diff_max_s': np.max(time_diffs), 'time_diff_min_s': np.min(time_diffs), } for name, value in sorted(stats.iteritems()): logging.info('%s: %f', name, value) aligned_ns, skipped_notes = sequences_lib.adjust_notesequence_times( ns, lambda t: np.interp(t, warp_seconds_i, warp_seconds_j), minimum_duration=seconds_per_frame) if skipped_notes > 0: raise RuntimeError('Skipped {} notes'.format(skipped_notes)) logging.debug('done') return aligned_ns, stats
[ "os.remove", "numpy.abs", "tempfile.mkstemp", "alignment_pb2.AlignmentTask", "librosa.core.cqt", "absl.logging.debug", "numpy.median", "numpy.interp", "absl.logging.info", "numpy.max", "librosa.power_to_db", "os.close", "numpy.array", "numpy.mean", "numpy.min", "librosa.midi_to_hz", ...
[((1334, 1356), 'librosa.midi_to_hz', 'librosa.midi_to_hz', (['(36)'], {}), '(36)\n', (1352, 1356), False, 'import librosa\n'), ((1762, 1786), 'librosa.power_to_db', 'librosa.power_to_db', (['cqt'], {}), '(cqt)\n', (1781, 1786), False, 'import librosa\n'), ((2725, 2753), 'absl.logging.info', 'logging.info', (['"""Synthesizing"""'], {}), "('Synthesizing')\n", (2737, 2753), False, 'from absl import logging\n'), ((3465, 3491), 'absl.logging.info', 'logging.info', (['"""source_cqt"""'], {}), "('source_cqt')\n", (3477, 3491), False, 'from absl import logging\n'), ((3563, 3587), 'absl.logging.info', 'logging.info', (['"""dest_cqt"""'], {}), "('dest_cqt')\n", (3575, 3587), False, 'from absl import logging\n'), ((3671, 3700), 'alignment_pb2.AlignmentTask', 'alignment_pb2.AlignmentTask', ([], {}), '()\n', (3698, 3700), False, 'import alignment_pb2\n'), ((4313, 4346), 'tempfile.mkstemp', 'tempfile.mkstemp', ([], {'suffix': '""".proto"""'}), "(suffix='.proto')\n", (4329, 4346), False, 'import tempfile\n'), ((4349, 4361), 'os.close', 'os.close', (['fh'], {}), '(fh)\n', (4357, 4361), False, 'import os\n'), ((4475, 4523), 'subprocess.check_call', 'subprocess.check_call', (['[ALIGN_BINARY, temp_path]'], {}), '([ALIGN_BINARY, temp_path])\n', (4496, 4523), False, 'import subprocess\n'), ((4662, 4682), 'os.remove', 'os.remove', (['temp_path'], {}), '(temp_path)\n', (4671, 4682), False, 'import os\n'), ((4685, 4717), 'os.remove', 'os.remove', (["(temp_path + '.result')"], {}), "(temp_path + '.result')\n", (4694, 4717), False, 'import os\n'), ((4721, 4774), 'absl.logging.info', 'logging.info', (['"""Aligning NoteSequence with warp path."""'], {}), "('Aligning NoteSequence with warp path.')\n", (4733, 4774), False, 'from absl import logging\n'), ((4795, 4848), 'numpy.array', 'np.array', (['[(i * seconds_per_frame) for i in result.i]'], {}), '([(i * seconds_per_frame) for i in result.i])\n', (4803, 4848), True, 'import numpy as np\n'), ((4866, 4919), 'numpy.array', 'np.array', (['[(j * seconds_per_frame) for j in result.j]'], {}), '([(j * seconds_per_frame) for j in result.j])\n', (4874, 4919), True, 'import numpy as np\n'), ((4934, 4973), 'numpy.abs', 'np.abs', (['(warp_seconds_i - warp_seconds_j)'], {}), '(warp_seconds_i - warp_seconds_j)\n', (4940, 4973), True, 'import numpy as np\n'), ((4984, 5024), 'numpy.abs', 'np.abs', (['(time_diffs[1:] - time_diffs[:-1])'], {}), '(time_diffs[1:] - time_diffs[:-1])\n', (4990, 5024), True, 'import numpy as np\n'), ((5784, 5805), 'absl.logging.debug', 'logging.debug', (['"""done"""'], {}), "('done')\n", (5797, 5805), False, 'from absl import logging\n'), ((1534, 1675), 'librosa.core.cqt', 'librosa.core.cqt', (['samples', 'sample_rate'], {'hop_length': 'cqt_hop_length', 'fmin': 'CQT_FMIN', 'n_bins': 'CQT_N_BINS', 'bins_per_octave': 'CQT_BINS_PER_OCTAVE'}), '(samples, sample_rate, hop_length=cqt_hop_length, fmin=\n CQT_FMIN, n_bins=CQT_N_BINS, bins_per_octave=CQT_BINS_PER_OCTAVE)\n', (1550, 1675), False, 'import librosa\n'), ((5098, 5112), 'numpy.mean', 'np.mean', (['warps'], {}), '(warps)\n', (5105, 5112), True, 'import numpy as np\n'), ((5137, 5153), 'numpy.median', 'np.median', (['warps'], {}), '(warps)\n', (5146, 5153), True, 'import numpy as np\n'), ((5175, 5188), 'numpy.max', 'np.max', (['warps'], {}), '(warps)\n', (5181, 5188), True, 'import numpy as np\n'), ((5210, 5223), 'numpy.min', 'np.min', (['warps'], {}), '(warps)\n', (5216, 5223), True, 'import numpy as np\n'), ((5251, 5270), 'numpy.mean', 'np.mean', (['time_diffs'], {}), '(time_diffs)\n', (5258, 5270), True, 'import numpy as np\n'), ((5300, 5321), 'numpy.median', 'np.median', (['time_diffs'], {}), '(time_diffs)\n', (5309, 5321), True, 'import numpy as np\n'), ((5348, 5366), 'numpy.max', 'np.max', (['time_diffs'], {}), '(time_diffs)\n', (5354, 5366), True, 'import numpy as np\n'), ((5393, 5411), 'numpy.min', 'np.min', (['time_diffs'], {}), '(time_diffs)\n', (5399, 5411), True, 'import numpy as np\n'), ((5470, 5505), 'absl.logging.info', 'logging.info', (['"""%s: %f"""', 'name', 'value'], {}), "('%s: %f', name, value)\n", (5482, 5505), False, 'from absl import logging\n'), ((2769, 2838), 'magenta.music.midi_synth.fluidsynth', 'midi_synth.fluidsynth', (['ns'], {'sf2_path': 'sf2_path', 'sample_rate': 'sample_rate'}), '(ns, sf2_path=sf2_path, sample_rate=sample_rate)\n', (2790, 2838), False, 'from magenta.music import midi_synth\n'), ((5604, 5648), 'numpy.interp', 'np.interp', (['t', 'warp_seconds_i', 'warp_seconds_j'], {}), '(t, warp_seconds_i, warp_seconds_j)\n', (5613, 5648), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- """ Created on Sun Dec 8 22:37:00 2019 @author: for_y """ import numpy as np from AnnoDomini.hamilton_mc import HMC, describe import sys import os sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) def test_hmc(): def norm_function(x): var = 1 denom = (2*np.pi*var)**.5 num = np.exp(-x**2/2) return num/denom start_point = 0 chain,accepts_ratio = HMC(target_pdf = norm_function, burn_in=0, thinning=1,chain_len=100, q_init=[start_point],epsilon = 0.05) assert len(chain) == 100 q = chain[:,0] assert max(q) < 10 assert np.isnan(q).sum() == 0 def neg_log_weibull(lam = 1, k = 0.5): def w(x): if x > 0: return -(np.log(k / lam) + (k-1) * np.log(x/lam) - (x/lam) ** k) else: return float('inf') return w start_point = 3 func = neg_log_weibull(k = 1.5) chain,accepts_ratio = HMC(U = func, burn_in=0, thinning=1,chain_len=100, q_init=[start_point],epsilon = 0.02) assert len(chain) == 100 q = chain[:,0] assert max(q) < 10 assert min(q) > 0 assert np.isnan(q).sum() == 0
[ "AnnoDomini.hamilton_mc.HMC", "numpy.log", "os.path.dirname", "numpy.isnan", "numpy.exp" ]
[((457, 565), 'AnnoDomini.hamilton_mc.HMC', 'HMC', ([], {'target_pdf': 'norm_function', 'burn_in': '(0)', 'thinning': '(1)', 'chain_len': '(100)', 'q_init': '[start_point]', 'epsilon': '(0.05)'}), '(target_pdf=norm_function, burn_in=0, thinning=1, chain_len=100, q_init=\n [start_point], epsilon=0.05)\n', (460, 565), False, 'from AnnoDomini.hamilton_mc import HMC, describe\n'), ((1000, 1089), 'AnnoDomini.hamilton_mc.HMC', 'HMC', ([], {'U': 'func', 'burn_in': '(0)', 'thinning': '(1)', 'chain_len': '(100)', 'q_init': '[start_point]', 'epsilon': '(0.02)'}), '(U=func, burn_in=0, thinning=1, chain_len=100, q_init=[start_point],\n epsilon=0.02)\n', (1003, 1089), False, 'from AnnoDomini.hamilton_mc import HMC, describe\n'), ((365, 384), 'numpy.exp', 'np.exp', (['(-x ** 2 / 2)'], {}), '(-x ** 2 / 2)\n', (371, 384), True, 'import numpy as np\n'), ((223, 248), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (238, 248), False, 'import os\n'), ((645, 656), 'numpy.isnan', 'np.isnan', (['q'], {}), '(q)\n', (653, 656), True, 'import numpy as np\n'), ((1192, 1203), 'numpy.isnan', 'np.isnan', (['q'], {}), '(q)\n', (1200, 1203), True, 'import numpy as np\n'), ((786, 801), 'numpy.log', 'np.log', (['(k / lam)'], {}), '(k / lam)\n', (792, 801), True, 'import numpy as np\n'), ((812, 827), 'numpy.log', 'np.log', (['(x / lam)'], {}), '(x / lam)\n', (818, 827), True, 'import numpy as np\n')]
import librosa from utils.hparams import Hparams from jamo import hangul_to_jamo from tqdm import tqdm import numpy as np import os, glob, json, shutil, torch, torchaudio hparams = Hparams() class KSSDatasetPath(): def __init__(self, Hparams): self.Hparams = Hparams # Original data self.text_paths = glob.glob(os.path.join(self.Hparams.out_texts_dir, '*.pt')) self.mel_paths = glob.glob(os.path.join(self.Hparams.out_mels_dir, '*.pt')) self.original_len = len(self.text_paths) # Splited Data Length self.val_len = int(self.original_len * self.Hparams.split_ratio) if self.val_len % self.Hparams.batch_size != 0: extra_num = self.Hparams.batch_size - self.val_len % self.Hparams.batch_size self.val_len = self.val_len + extra_num self.trn_len = self.original_len - self.val_len # Train data, Validation data self.trn_text_paths, self.val_text_paths = (self.text_paths[:self.trn_len], self.text_paths[self.trn_len:]) self.trn_mel_paths, self.val_mel_paths = (self.mel_paths[:self.trn_len], self.mel_paths[self.trn_len:]) class KSSTrainDataset(torch.utils.data.Dataset, KSSDatasetPath): def __init__(self): KSSDatasetPath.__init__(self, hparams) def __len__(self): return self.trn_len def __getitem__(self, idx): # Train data self.trn_texts = torch.LongTensor(torch.load(self.trn_text_paths[idx])) self.trn_mels = torch.FloatTensor(torch.load(self.trn_mel_paths[idx])) return (self.trn_texts, self.trn_mels) class KSSValidateDataset(torch.utils.data.Dataset, KSSDatasetPath): def __init__(self): KSSDatasetPath.__init__(self, hparams) def __len__(self): return self.val_len def __getitem__(self, idx): # Validate data self.val_texts = torch.LongTensor(torch.load(self.val_text_paths[idx])) self.val_mels = torch.FloatTensor(torch.load(self.val_mel_paths[idx])) return (self.val_texts, self.val_mels) def collate_fn(batch): texts, mels = zip(*batch) text_pads = torch.nn.utils.rnn.pad_sequence(texts, batch_first=True) mel_pads = torch.nn.utils.rnn.pad_sequence(mels, batch_first=True) text_lengths = torch.LongTensor([text.size(0) for text in texts]) mel_lengths = torch.LongTensor([mel.size(0) for mel in mels]) return (text_pads.contiguous(), mel_pads.contiguous(), text_lengths.contiguous(), mel_lengths.contiguous()) def _normalize(S, hparams): return hparams.max_abs_value * ((S - hparams.min_level_db) / (-hparams.min_level_db)) def _denormalize(D, hparams): return ((D * -hparams.min_level_db / hparams.max_abs_value) + hparams.min_level_db) def preprocessing(hparams, ap, tp, data_length=None): print("Pre-processing Audio and Text data from Alignments") alignments_path = os.path.join(hparams.nas_path, 'kss', 'alignments.json') with open(alignments_path, 'r', encoding='utf-8') as f: alignments = json.loads(f.read()) # ๋””๋ ‰ํ† ๋ฆฌ ์ƒ์„ฑ data_dirs = [hparams.out_texts_dir, hparams.out_specs_dir, hparams.out_mels_dir] for data_dir in data_dirs: if os.path.isdir(data_dir): # ์ด๋ฏธ ์žˆ์œผ๋ฉด ๊ฐ•์ œ ์‚ญ์ œ shutil.rmtree(data_dir) os.makedirs(data_dir, exist_ok=True) # ๋””๋ ‰ํ† ๋ฆฌ ์ƒ์„ฑ # pre-processing for idx, (audio_path, text) in tqdm(enumerate(alignments.items())): # text pre-processing seq = tp.text_to_sequence(text) # audio load audio, _ = librosa.load(audio_path, hparams.sample_rate) audio, _ = librosa.effects.trim(audio, top_db=hparams.trim_top_db) # normalizing audio = ap._normalizing(audio) # audio pre-processing mel = _normalize(ap.melspectrogram(audio), hparams) # padded mel = ap.pre_padding(mel) # text save torch.save(seq, os.path.join(hparams.out_texts_dir, 'kss-text-%05d.pt' % idx)) torch.save(mel, os.path.join(hparams.out_mels_dir, 'kss-mel-%05d.pt' % idx)) if data_length is not None and idx+1 == data_length: break def get_pairs_from_source(hparams, save=True): print("Getting pairs from metadata") source_dir = os.path.join(hparams.nas_path, 'kss') if not os.path.isdir(source_dir): print("There are not exist data directories. Please check directory which is %s" % source_dir) source_file = glob.glob(os.path.join(source_dir, '*.txt'))[0] # path|text|text|text|digit|text pairs = {} with open(source_file, 'r', encoding='utf-8') as f: lines = f.readlines() # ์ฝ์–ด์˜ค๊ธฐ metadata = [line.strip('\n') for line in lines] # ๊ฐœํ–‰๋ฌธ์ž ์ œ๊ฑฐ for line in metadata: audio_path = line.split('|')[0] # audio path if '/' in audio_path: audio_path = audio_path.split('/') audio_path = os.path.join(audio_path[0], audio_path[1]) text = line.split('|')[1] # text pairs[os.path.join(source_dir, audio_path)] = text # save as dictionary if save==True: with open(os.path.join(source_dir, 'alignments.json'), 'w', encoding='UTF-8') as json_file: json.dump(pairs, json_file, ensure_ascii=False, indent=4, sort_keys=False) return pairs class AudioPreprocessing(): def __init__(self, Hparams): self.Hparams = Hparams def spectrogram(self, audio): D = self._stft(audio) M = np.abs(D) S = self._amp_to_db(M) - self.Hparams.ref_level_db return torch.Tensor(S.T) def melspectrogram(self, audio): D = self._stft(audio) M = np.abs(D) S = self._amp_to_db(self._linear_to_mel(M)) - self.Hparams.ref_level_db return torch.Tensor(S.T) def _stft(self, audio): return librosa.stft(audio, n_fft=self.Hparams.n_fft, hop_length=self.Hparams.hop_length, win_length=self.Hparams.win_length, pad_mode='constant') def _istft(self, spec): return librosa.istft(spec, hop_length=self.Hparams.hop_length, win_length=self.Hparams.win_length) def _linear_to_mel(self, spec): _mel_basis = self._build_mel_basis() return np.dot(_mel_basis, spec) def _build_mel_basis(self): if self.Hparams.fmax != self.Hparams.sample_rate // 2: self.Hparams.fmax = self.Hparams.sample_rate // 2 return librosa.filters.mel(sr=self.Hparams.sample_rate, n_fft=self.Hparams.n_fft, n_mels=self.Hparams.n_mels, fmin=self.Hparams.fmin, fmax=self.Hparams.fmax) def _amp_to_db(self, x): min_level = np.exp(self.Hparams.min_level_db / 20 * np.log(10)) return 20 * np.log10(np.maximum(min_level, x)) def _db_to_amp(self, x): return np.power(10.0, (x) * 0.05) def _resample(self, x): return librosa.resample(x, orig_sr=self.Hparams.origin_sample_rate, target_sr=self.Hparams.sample_rate) def _normalizing(self, x): return x / np.abs(x).max() def pre_padding(self, spec): # pre-padding from reduction factor(teacher forcing) to feed decoder input in training # matching r-times if type(spec) != torch.Tensor: spec = torch.Tensor(spec) t = spec.size(0) n_pads = self.Hparams.reduction - (t % self.Hparams.reduction)\ if t % self.Hparams.reduction != 0 else 0 pad = (0, 0, 0, n_pads) padded_spec = torch.nn.functional.pad(spec, pad, mode='constant', value=0) return padded_spec def spec_to_audio(self, spec): side_pad = np.zeros(int(0.15*self.Hparams.sample_rate)) audio = self._griffin_lim(spec, self.Hparams) audio = np.concatenate([side_pad, audio, side_pad]) return audio def _griffin_lim(self, spec, hparams): spec = self._db_to_amp(spec + self.Hparams.ref_level_db) if (spec.shape[0] == ((hparams.sample_rate//20)//2)+1): spec = spec else: inv_mel_filter = np.linalg.pinv(self._build_mel_basis()) if (inv_mel_filter.shape[-1] == spec.shape[-1]): spec = spec.T spec = np.maximum(1e-10, np.dot(inv_mel_filter, spec)) return librosa.core.griffinlim(spec, hop_length=hparams.sample_rate//80, win_length=hparams.sample_rate//20) class TextPreprocessing(): def __init__(self, Hparams): self.Hparams = Hparams # text -> sequence def text_to_sequence(self, text): sequence = [] if not 0x1100 <= ord(text[0]) <= 0x1113: text = ''.join(list(hangul_to_jamo(text))) for t in text: if t in self.Hparams._symbol_to_id: # ์ง€์ •ํ•˜์ง€ ์•Š์€ ์ด์™ธ์˜ ๋ฌธ์ž๋Š” ์‹œํ€€์Šค์— ํฌํ•จํ•˜์ง€ ์•Š์Œ sequence.append(self.Hparams._symbol_to_id[t]) sequence.append(self.Hparams._symbol_to_id['~']) return sequence # sequence -> text without PAD, EOS tokens def sequence_to_text(self, sequence): tokens = [self.Hparams._symbol_to_id[self.Hparams.PAD], self.Hparams._symbol_to_id[self.Hparams.EOS]] sequence = [s for s in sequence if s not in tokens] text = '' for symbol_id in sequence: if symbol_id in self.Hparams._id_to_symbol: t = self.Hparams._id_to_symbol[symbol_id] text += t return text
[ "numpy.abs", "numpy.maximum", "librosa.filters.mel", "librosa.istft", "librosa.resample", "shutil.rmtree", "os.path.join", "torch.nn.functional.pad", "utils.hparams.Hparams", "numpy.power", "librosa.core.griffinlim", "torch.load", "torch.Tensor", "librosa.effects.trim", "librosa.stft", ...
[((189, 198), 'utils.hparams.Hparams', 'Hparams', ([], {}), '()\n', (196, 198), False, 'from utils.hparams import Hparams\n'), ((2348, 2404), 'torch.nn.utils.rnn.pad_sequence', 'torch.nn.utils.rnn.pad_sequence', (['texts'], {'batch_first': '(True)'}), '(texts, batch_first=True)\n', (2379, 2404), False, 'import os, glob, json, shutil, torch, torchaudio\n'), ((2421, 2476), 'torch.nn.utils.rnn.pad_sequence', 'torch.nn.utils.rnn.pad_sequence', (['mels'], {'batch_first': '(True)'}), '(mels, batch_first=True)\n', (2452, 2476), False, 'import os, glob, json, shutil, torch, torchaudio\n'), ((3162, 3218), 'os.path.join', 'os.path.join', (['hparams.nas_path', '"""kss"""', '"""alignments.json"""'], {}), "(hparams.nas_path, 'kss', 'alignments.json')\n", (3174, 3218), False, 'import os, glob, json, shutil, torch, torchaudio\n'), ((4768, 4805), 'os.path.join', 'os.path.join', (['hparams.nas_path', '"""kss"""'], {}), "(hparams.nas_path, 'kss')\n", (4780, 4805), False, 'import os, glob, json, shutil, torch, torchaudio\n'), ((4818, 4843), 'os.path.isdir', 'os.path.isdir', (['source_dir'], {}), '(source_dir)\n', (4831, 4843), False, 'import os, glob, json, shutil, torch, torchaudio\n'), ((6043, 6052), 'numpy.abs', 'np.abs', (['D'], {}), '(D)\n', (6049, 6052), True, 'import numpy as np\n'), ((6129, 6146), 'torch.Tensor', 'torch.Tensor', (['S.T'], {}), '(S.T)\n', (6141, 6146), False, 'import os, glob, json, shutil, torch, torchaudio\n'), ((6231, 6240), 'numpy.abs', 'np.abs', (['D'], {}), '(D)\n', (6237, 6240), True, 'import numpy as np\n'), ((6338, 6355), 'torch.Tensor', 'torch.Tensor', (['S.T'], {}), '(S.T)\n', (6350, 6355), False, 'import os, glob, json, shutil, torch, torchaudio\n'), ((6403, 6546), 'librosa.stft', 'librosa.stft', (['audio'], {'n_fft': 'self.Hparams.n_fft', 'hop_length': 'self.Hparams.hop_length', 'win_length': 'self.Hparams.win_length', 'pad_mode': '"""constant"""'}), "(audio, n_fft=self.Hparams.n_fft, hop_length=self.Hparams.\n hop_length, win_length=self.Hparams.win_length, pad_mode='constant')\n", (6415, 6546), False, 'import librosa\n'), ((6713, 6809), 'librosa.istft', 'librosa.istft', (['spec'], {'hop_length': 'self.Hparams.hop_length', 'win_length': 'self.Hparams.win_length'}), '(spec, hop_length=self.Hparams.hop_length, win_length=self.\n Hparams.win_length)\n', (6726, 6809), False, 'import librosa\n'), ((6968, 6992), 'numpy.dot', 'np.dot', (['_mel_basis', 'spec'], {}), '(_mel_basis, spec)\n', (6974, 6992), True, 'import numpy as np\n'), ((7171, 7325), 'librosa.filters.mel', 'librosa.filters.mel', ([], {'sr': 'self.Hparams.sample_rate', 'n_fft': 'self.Hparams.n_fft', 'n_mels': 'self.Hparams.n_mels', 'fmin': 'self.Hparams.fmin', 'fmax': 'self.Hparams.fmax'}), '(sr=self.Hparams.sample_rate, n_fft=self.Hparams.n_fft,\n n_mels=self.Hparams.n_mels, fmin=self.Hparams.fmin, fmax=self.Hparams.fmax)\n', (7190, 7325), False, 'import librosa\n'), ((7682, 7706), 'numpy.power', 'np.power', (['(10.0)', '(x * 0.05)'], {}), '(10.0, x * 0.05)\n', (7690, 7706), True, 'import numpy as np\n'), ((7760, 7861), 'librosa.resample', 'librosa.resample', (['x'], {'orig_sr': 'self.Hparams.origin_sample_rate', 'target_sr': 'self.Hparams.sample_rate'}), '(x, orig_sr=self.Hparams.origin_sample_rate, target_sr=self\n .Hparams.sample_rate)\n', (7776, 7861), False, 'import librosa\n'), ((8448, 8508), 'torch.nn.functional.pad', 'torch.nn.functional.pad', (['spec', 'pad'], {'mode': '"""constant"""', 'value': '(0)'}), "(spec, pad, mode='constant', value=0)\n", (8471, 8508), False, 'import os, glob, json, shutil, torch, torchaudio\n'), ((8712, 8755), 'numpy.concatenate', 'np.concatenate', (['[side_pad, audio, side_pad]'], {}), '([side_pad, audio, side_pad])\n', (8726, 8755), True, 'import numpy as np\n'), ((9256, 9365), 'librosa.core.griffinlim', 'librosa.core.griffinlim', (['spec'], {'hop_length': '(hparams.sample_rate // 80)', 'win_length': '(hparams.sample_rate // 20)'}), '(spec, hop_length=hparams.sample_rate // 80,\n win_length=hparams.sample_rate // 20)\n', (9279, 9365), False, 'import librosa\n'), ((364, 412), 'os.path.join', 'os.path.join', (['self.Hparams.out_texts_dir', '"""*.pt"""'], {}), "(self.Hparams.out_texts_dir, '*.pt')\n", (376, 412), False, 'import os, glob, json, shutil, torch, torchaudio\n'), ((450, 497), 'os.path.join', 'os.path.join', (['self.Hparams.out_mels_dir', '"""*.pt"""'], {}), "(self.Hparams.out_mels_dir, '*.pt')\n", (462, 497), False, 'import os, glob, json, shutil, torch, torchaudio\n'), ((1614, 1650), 'torch.load', 'torch.load', (['self.trn_text_paths[idx]'], {}), '(self.trn_text_paths[idx])\n', (1624, 1650), False, 'import os, glob, json, shutil, torch, torchaudio\n'), ((1695, 1730), 'torch.load', 'torch.load', (['self.trn_mel_paths[idx]'], {}), '(self.trn_mel_paths[idx])\n', (1705, 1730), False, 'import os, glob, json, shutil, torch, torchaudio\n'), ((2096, 2132), 'torch.load', 'torch.load', (['self.val_text_paths[idx]'], {}), '(self.val_text_paths[idx])\n', (2106, 2132), False, 'import os, glob, json, shutil, torch, torchaudio\n'), ((2177, 2212), 'torch.load', 'torch.load', (['self.val_mel_paths[idx]'], {}), '(self.val_mel_paths[idx])\n', (2187, 2212), False, 'import os, glob, json, shutil, torch, torchaudio\n'), ((3545, 3568), 'os.path.isdir', 'os.path.isdir', (['data_dir'], {}), '(data_dir)\n', (3558, 3568), False, 'import os, glob, json, shutil, torch, torchaudio\n'), ((3639, 3675), 'os.makedirs', 'os.makedirs', (['data_dir'], {'exist_ok': '(True)'}), '(data_dir, exist_ok=True)\n', (3650, 3675), False, 'import os, glob, json, shutil, torch, torchaudio\n'), ((3943, 3988), 'librosa.load', 'librosa.load', (['audio_path', 'hparams.sample_rate'], {}), '(audio_path, hparams.sample_rate)\n', (3955, 3988), False, 'import librosa\n'), ((4013, 4068), 'librosa.effects.trim', 'librosa.effects.trim', (['audio'], {'top_db': 'hparams.trim_top_db'}), '(audio, top_db=hparams.trim_top_db)\n', (4033, 4068), False, 'import librosa\n'), ((4980, 5013), 'os.path.join', 'os.path.join', (['source_dir', '"""*.txt"""'], {}), "(source_dir, '*.txt')\n", (4992, 5013), False, 'import os, glob, json, shutil, torch, torchaudio\n'), ((8219, 8237), 'torch.Tensor', 'torch.Tensor', (['spec'], {}), '(spec)\n', (8231, 8237), False, 'import os, glob, json, shutil, torch, torchaudio\n'), ((3602, 3625), 'shutil.rmtree', 'shutil.rmtree', (['data_dir'], {}), '(data_dir)\n', (3615, 3625), False, 'import os, glob, json, shutil, torch, torchaudio\n'), ((4400, 4461), 'os.path.join', 'os.path.join', (['hparams.out_texts_dir', "('kss-text-%05d.pt' % idx)"], {}), "(hparams.out_texts_dir, 'kss-text-%05d.pt' % idx)\n", (4412, 4461), False, 'import os, glob, json, shutil, torch, torchaudio\n'), ((4492, 4551), 'os.path.join', 'os.path.join', (['hparams.out_mels_dir', "('kss-mel-%05d.pt' % idx)"], {}), "(hparams.out_mels_dir, 'kss-mel-%05d.pt' % idx)\n", (4504, 4551), False, 'import os, glob, json, shutil, torch, torchaudio\n'), ((5435, 5477), 'os.path.join', 'os.path.join', (['audio_path[0]', 'audio_path[1]'], {}), '(audio_path[0], audio_path[1])\n', (5447, 5477), False, 'import os, glob, json, shutil, torch, torchaudio\n'), ((5543, 5579), 'os.path.join', 'os.path.join', (['source_dir', 'audio_path'], {}), '(source_dir, audio_path)\n', (5555, 5579), False, 'import os, glob, json, shutil, torch, torchaudio\n'), ((5770, 5844), 'json.dump', 'json.dump', (['pairs', 'json_file'], {'ensure_ascii': '(False)', 'indent': '(4)', 'sort_keys': '(False)'}), '(pairs, json_file, ensure_ascii=False, indent=4, sort_keys=False)\n', (5779, 5844), False, 'import os, glob, json, shutil, torch, torchaudio\n'), ((7566, 7576), 'numpy.log', 'np.log', (['(10)'], {}), '(10)\n', (7572, 7576), True, 'import numpy as np\n'), ((7608, 7632), 'numpy.maximum', 'np.maximum', (['min_level', 'x'], {}), '(min_level, x)\n', (7618, 7632), True, 'import numpy as np\n'), ((9196, 9224), 'numpy.dot', 'np.dot', (['inv_mel_filter', 'spec'], {}), '(inv_mel_filter, spec)\n', (9202, 9224), True, 'import numpy as np\n'), ((5671, 5714), 'os.path.join', 'os.path.join', (['source_dir', '"""alignments.json"""'], {}), "(source_dir, 'alignments.json')\n", (5683, 5714), False, 'import os, glob, json, shutil, torch, torchaudio\n'), ((7979, 7988), 'numpy.abs', 'np.abs', (['x'], {}), '(x)\n', (7985, 7988), True, 'import numpy as np\n'), ((9705, 9725), 'jamo.hangul_to_jamo', 'hangul_to_jamo', (['text'], {}), '(text)\n', (9719, 9725), False, 'from jamo import hangul_to_jamo\n')]
#!/usr/bin/env python # -*- coding: utf-8 -*- # pylint: disable=wrong-import-position """ Generate a json file summarizing a CLSim table """ from __future__ import absolute_import, division, print_function __all__ = [ 'summarize_clsim_table', 'parse_args', 'main' ] __author__ = '<NAME>' __license__ = '''Copyright 2017 <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 argparse import ArgumentParser from collections import OrderedDict from glob import glob from itertools import product from os.path import abspath, basename, dirname, isfile, join, splitext import sys from time import time import numpy as np if __name__ == '__main__' and __package__ is None: RETRO_DIR = dirname(dirname(dirname(abspath(__file__)))) if RETRO_DIR not in sys.path: sys.path.append(RETRO_DIR) from retro.const import SPEED_OF_LIGHT_M_PER_NS from retro.utils.misc import expand, mkdir, wstderr from retro.tables.clsim_tables import ( CLSIM_TABLE_METANAME_PROTO, interpret_clsim_table_fname, load_clsim_table ) def summarize_clsim_table(table_fpath, table=None, save_summary=True, outdir=None): """ Parameters ---------- table_fpath : string Path to table (or just the table's filename if `outdir` is specified) table : mapping, optional If the table has already been loaded, it can be passed here to avoid re-loading the table. save_summary : bool Whether to save the table summary to disk. outdir : string, optional If `save_summary` is True, write the summary to this directory. If `outdir` is not specified and `save_summary` is True, the summary will be written to the same directory that contains `table_fpath`. Returns ------- table See `load_clsim_table` for details of the data structure summary : OrderedDict """ t_start = time() if save_summary: from pisa.utils.jsons import from_json, to_json table_fpath = expand(table_fpath) srcdir, clsim_fname = dirname(table_fpath), basename(table_fpath) invalid_fname = False try: fname_info = interpret_clsim_table_fname(clsim_fname) except ValueError: invalid_fname = True fname_info = {} if outdir is None: outdir = srcdir outdir = expand(outdir) mkdir(outdir) if invalid_fname: metapath = None else: metaname = (CLSIM_TABLE_METANAME_PROTO[-1] .format(hash_val=fname_info['hash_val'])) metapath = join(outdir, metaname) if metapath and isfile(metapath): meta = from_json(metapath) else: meta = dict() if table is None: table = load_clsim_table(table_fpath) summary = OrderedDict() for key in table.keys(): if key == 'table': continue summary[key] = table[key] if fname_info: for key in ('hash_val', 'string', 'depth_idx', 'seed'): summary[key] = fname_info[key] # TODO: Add hole ice info when added to tray_kw_to_hash if meta: summary['n_events'] = meta['tray_kw_to_hash']['NEvents'] summary['ice_model'] = meta['tray_kw_to_hash']['IceModel'] summary['tilt'] = not meta['tray_kw_to_hash']['DisableTilt'] for key, val in meta.items(): if key.endswith('_binning_kw'): summary[key] = val elif 'fname_version' in fname_info and fname_info['fname_version'] == 1: summary['n_events'] = fname_info['n_events'] summary['ice_model'] = 'spice_mie' summary['tilt'] = False summary['r_binning_kw'] = dict(min=0.0, max=400.0, n_bins=200, power=2) summary['costheta_binning_kw'] = dict(min=-1, max=1, n_bins=40) summary['t_binning_kw'] = dict(min=0.0, max=3000.0, n_bins=300) summary['costhetadir_binning_kw'] = dict(min=-1, max=1, n_bins=20) summary['deltaphidir_binning_kw'] = dict(min=0.0, max=np.pi, n_bins=20) # Save marginal distributions and info to file norm = ( 1 / table['n_photons'] / (SPEED_OF_LIGHT_M_PER_NS / table['phase_refractive_index'] * np.mean(np.diff(table['t_bin_edges']))) #* table['angular_acceptance_fract'] * (len(table['costheta_bin_edges']) - 1) ) summary['norm'] = norm dim_names = ('r', 'costheta', 't', 'costhetadir', 'deltaphidir') n_dims = len(table['table_shape']) assert n_dims == len(dim_names) # Apply norm to underflow and overflow so magnitudes can be compared # relative to plotted marginal distributions for flow, idx in product(('underflow', 'overflow'), iter(range(n_dims))): summary[flow][idx] = summary[flow][idx] * norm wstderr('Finding marginal distributions...\n') wstderr(' masking off zeros in table...') t0 = time() nonzero_table = np.ma.masked_equal(table['table'], 0) wstderr(' ({} ms)\n'.format(np.round((time() - t0)*1e3, 3))) t0_marg = time() summary['dimensions'] = OrderedDict() for keep_axis, ax_name in zip(tuple(range(n_dims)), dim_names): remove_axes = list(range(n_dims)) remove_axes.pop(keep_axis) remove_axes = tuple(remove_axes) axis = OrderedDict() wstderr(' mean across non-{} axes...'.format(ax_name)) t0 = time() axis['mean'] = norm * np.asarray( np.mean(table['table'], axis=remove_axes) ) wstderr(' ({} s)\n'.format(np.round(time() - t0, 3))) wstderr(' median across non-{} axes...'.format(ax_name)) t0 = time() axis['median'] = norm * np.asarray( np.ma.median(nonzero_table, axis=remove_axes) ) wstderr(' ({} s)\n'.format(np.round(time() - t0, 3))) wstderr(' max across non-{} axes...'.format(ax_name)) t0 = time() axis['max'] = norm * np.asarray( np.max(table['table'], axis=remove_axes) ) wstderr(' ({} s)\n'.format(np.round(time() - t0, 3))) summary['dimensions'][ax_name] = axis wstderr( ' Total time to find marginal distributions: {} s\n' .format(np.round(time() - t0_marg, 3)) ) if save_summary: ext = None base_fname = clsim_fname while ext not in ('', '.fits'): base_fname, ext = splitext(base_fname) ext = ext.lower() outfpath = join(outdir, base_fname + '_summary.json.bz2') to_json(summary, outfpath) print('saved summary to "{}"'.format(outfpath)) wstderr('Time to summarize table: {} s\n' .format(np.round(time() - t_start, 3))) return table, summary def parse_args(description=__doc__): """Parse command line args. Returns ------- args : Namespace """ parser = ArgumentParser(description=description) parser.add_argument( '--outdir', default=None, help='''Directory in which to save summary (if not specified, summary is saved to same directory as the table)''' ) parser.add_argument( 'table-fpaths', nargs='+', help='''Path(s) to CLSim table(s). Note that literal strings are glob-expanded.''' ) return parser.parse_args() def main(): """Main function for calling summarize_clsim_table as a script""" t0 = time() args = parse_args() kwargs = vars(args) table_fpaths = [] for fpath in kwargs.pop('table-fpaths'): table_fpaths.extend(glob(expand(fpath))) for fpath in table_fpaths: kwargs['table_fpath'] = fpath summarize_clsim_table(**kwargs) total_time = time() - t0 if len(table_fpaths) > 1: avg = np.round(total_time / len(table_fpaths), 3) wstderr('Average time to summarize tables: {} s/table\n'.format(avg)) if __name__ == '__main__': main()
[ "argparse.ArgumentParser", "os.path.isfile", "numpy.mean", "os.path.join", "retro.utils.misc.mkdir", "sys.path.append", "os.path.abspath", "pisa.utils.jsons.from_json", "os.path.dirname", "numpy.max", "numpy.ma.median", "retro.utils.misc.wstderr", "os.path.basename", "pisa.utils.jsons.to_j...
[((2394, 2400), 'time.time', 'time', ([], {}), '()\n', (2398, 2400), False, 'from time import time\n'), ((2497, 2516), 'retro.utils.misc.expand', 'expand', (['table_fpath'], {}), '(table_fpath)\n', (2503, 2516), False, 'from retro.utils.misc import expand, mkdir, wstderr\n'), ((2821, 2835), 'retro.utils.misc.expand', 'expand', (['outdir'], {}), '(outdir)\n', (2827, 2835), False, 'from retro.utils.misc import expand, mkdir, wstderr\n'), ((2840, 2853), 'retro.utils.misc.mkdir', 'mkdir', (['outdir'], {}), '(outdir)\n', (2845, 2853), False, 'from retro.utils.misc import expand, mkdir, wstderr\n'), ((3255, 3268), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (3266, 3268), False, 'from collections import OrderedDict\n'), ((5240, 5286), 'retro.utils.misc.wstderr', 'wstderr', (['"""Finding marginal distributions...\n"""'], {}), "('Finding marginal distributions...\\n')\n", (5247, 5286), False, 'from retro.utils.misc import expand, mkdir, wstderr\n'), ((5291, 5335), 'retro.utils.misc.wstderr', 'wstderr', (['""" masking off zeros in table..."""'], {}), "(' masking off zeros in table...')\n", (5298, 5335), False, 'from retro.utils.misc import expand, mkdir, wstderr\n'), ((5345, 5351), 'time.time', 'time', ([], {}), '()\n', (5349, 5351), False, 'from time import time\n'), ((5372, 5409), 'numpy.ma.masked_equal', 'np.ma.masked_equal', (["table['table']", '(0)'], {}), "(table['table'], 0)\n", (5390, 5409), True, 'import numpy as np\n'), ((5490, 5496), 'time.time', 'time', ([], {}), '()\n', (5494, 5496), False, 'from time import time\n'), ((5525, 5538), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (5536, 5538), False, 'from collections import OrderedDict\n'), ((7315, 7354), 'argparse.ArgumentParser', 'ArgumentParser', ([], {'description': 'description'}), '(description=description)\n', (7329, 7354), False, 'from argparse import ArgumentParser\n'), ((7839, 7845), 'time.time', 'time', ([], {}), '()\n', (7843, 7845), False, 'from time import time\n'), ((1275, 1301), 'sys.path.append', 'sys.path.append', (['RETRO_DIR'], {}), '(RETRO_DIR)\n', (1290, 1301), False, 'import sys\n'), ((2543, 2563), 'os.path.dirname', 'dirname', (['table_fpath'], {}), '(table_fpath)\n', (2550, 2563), False, 'from os.path import abspath, basename, dirname, isfile, join, splitext\n'), ((2565, 2586), 'os.path.basename', 'basename', (['table_fpath'], {}), '(table_fpath)\n', (2573, 2586), False, 'from os.path import abspath, basename, dirname, isfile, join, splitext\n'), ((2643, 2683), 'retro.tables.clsim_tables.interpret_clsim_table_fname', 'interpret_clsim_table_fname', (['clsim_fname'], {}), '(clsim_fname)\n', (2670, 2683), False, 'from retro.tables.clsim_tables import CLSIM_TABLE_METANAME_PROTO, interpret_clsim_table_fname, load_clsim_table\n'), ((3043, 3065), 'os.path.join', 'join', (['outdir', 'metaname'], {}), '(outdir, metaname)\n', (3047, 3065), False, 'from os.path import abspath, basename, dirname, isfile, join, splitext\n'), ((3086, 3102), 'os.path.isfile', 'isfile', (['metapath'], {}), '(metapath)\n', (3092, 3102), False, 'from os.path import abspath, basename, dirname, isfile, join, splitext\n'), ((3119, 3138), 'pisa.utils.jsons.from_json', 'from_json', (['metapath'], {}), '(metapath)\n', (3128, 3138), False, 'from pisa.utils.jsons import from_json, to_json\n'), ((3210, 3239), 'retro.tables.clsim_tables.load_clsim_table', 'load_clsim_table', (['table_fpath'], {}), '(table_fpath)\n', (3226, 3239), False, 'from retro.tables.clsim_tables import CLSIM_TABLE_METANAME_PROTO, interpret_clsim_table_fname, load_clsim_table\n'), ((5740, 5753), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (5751, 5753), False, 'from collections import OrderedDict\n'), ((5834, 5840), 'time.time', 'time', ([], {}), '()\n', (5838, 5840), False, 'from time import time\n'), ((6091, 6097), 'time.time', 'time', ([], {}), '()\n', (6095, 6097), False, 'from time import time\n'), ((6351, 6357), 'time.time', 'time', ([], {}), '()\n', (6355, 6357), False, 'from time import time\n'), ((6912, 6958), 'os.path.join', 'join', (['outdir', "(base_fname + '_summary.json.bz2')"], {}), "(outdir, base_fname + '_summary.json.bz2')\n", (6916, 6958), False, 'from os.path import abspath, basename, dirname, isfile, join, splitext\n'), ((6967, 6993), 'pisa.utils.jsons.to_json', 'to_json', (['summary', 'outfpath'], {}), '(summary, outfpath)\n', (6974, 6993), False, 'from pisa.utils.jsons import from_json, to_json\n'), ((8136, 8142), 'time.time', 'time', ([], {}), '()\n', (8140, 8142), False, 'from time import time\n'), ((6842, 6862), 'os.path.splitext', 'splitext', (['base_fname'], {}), '(base_fname)\n', (6850, 6862), False, 'from os.path import abspath, basename, dirname, isfile, join, splitext\n'), ((1212, 1229), 'os.path.abspath', 'abspath', (['__file__'], {}), '(__file__)\n', (1219, 1229), False, 'from os.path import abspath, basename, dirname, isfile, join, splitext\n'), ((5895, 5936), 'numpy.mean', 'np.mean', (["table['table']"], {'axis': 'remove_axes'}), "(table['table'], axis=remove_axes)\n", (5902, 5936), True, 'import numpy as np\n'), ((6154, 6199), 'numpy.ma.median', 'np.ma.median', (['nonzero_table'], {'axis': 'remove_axes'}), '(nonzero_table, axis=remove_axes)\n', (6166, 6199), True, 'import numpy as np\n'), ((6411, 6451), 'numpy.max', 'np.max', (["table['table']"], {'axis': 'remove_axes'}), "(table['table'], axis=remove_axes)\n", (6417, 6451), True, 'import numpy as np\n'), ((7994, 8007), 'retro.utils.misc.expand', 'expand', (['fpath'], {}), '(fpath)\n', (8000, 8007), False, 'from retro.utils.misc import expand, mkdir, wstderr\n'), ((4675, 4704), 'numpy.diff', 'np.diff', (["table['t_bin_edges']"], {}), "(table['t_bin_edges'])\n", (4682, 4704), True, 'import numpy as np\n'), ((6670, 6676), 'time.time', 'time', ([], {}), '()\n', (6674, 6676), False, 'from time import time\n'), ((7126, 7132), 'time.time', 'time', ([], {}), '()\n', (7130, 7132), False, 'from time import time\n'), ((5452, 5458), 'time.time', 'time', ([], {}), '()\n', (5456, 5458), False, 'from time import time\n'), ((5991, 5997), 'time.time', 'time', ([], {}), '()\n', (5995, 5997), False, 'from time import time\n'), ((6254, 6260), 'time.time', 'time', ([], {}), '()\n', (6258, 6260), False, 'from time import time\n'), ((6506, 6512), 'time.time', 'time', ([], {}), '()\n', (6510, 6512), False, 'from time import time\n')]