code
stringlengths
31
1.05M
apis
list
extract_api
stringlengths
97
1.91M
"""Exercise 1 Usage: $ CUDA_VISIBLE_DEVICES=2 python practico_1_train_petfinder.py --dataset_dir ../ --epochs 30 --dropout 0.1 0.1 --hidden_layer_sizes 200 100 To know which GPU to use, you can check it with the command $ nvidia-smi """ import argparse import os import mlflow import pickle import numpy as np import pandas as pd import tensorflow as tf from sklearn.model_selection import train_test_split from tensorflow.keras import layers, models import warnings warnings.filterwarnings("ignore") from auxiliary import process_features, load_dataset, build_columns, log_dir_name TARGET_COL = 'AdoptionSpeed' def read_args(): parser = argparse.ArgumentParser( description='Training a MLP on the petfinder dataset') # Here you have some examples of classifier parameters. You can add # more arguments or change these if you need to. parser.add_argument('--experiment_name', type=str, default='Base model', help='Name of the experiment, used in mlflow.') parser.add_argument('--dataset_dir', default='../petfinder_dataset', type=str, help='Directory with the training and test files.') parser.add_argument('--hidden_layer_sizes', nargs='+', default=[100], type=int, help='Number of hidden units of each hidden layer.') parser.add_argument('--epochs', default=50, type=int, help='Number of epochs to train.') parser.add_argument('--dropout', nargs='+', default=[0.5], type=float, help='Dropout ratio for every layer.') parser.add_argument('--batch_size', type=int, default=32, help='Number of instances in each batch.') parser.add_argument('--learning_rate', default=1e-3, type=float, help='Learning rate.') args = parser.parse_args() assert len(args.hidden_layer_sizes) == len(args.dropout) return args def print_args(args): print('-------------------------------------------') print('PARAMS ------------------------------------') print('-------------------------------------------') print('--experiment_name ', args.experiment_name) print('--dataset_dir ', args.dataset_dir) print('--epochs ', args.epochs) print('--hidden_layer_sizes', args.hidden_layer_sizes) print('--dropout ', args.dropout) print('--batch_size ', args.batch_size) print('--learning_rate ', args.learning_rate) print('-------------------------------------------') def main(): args = read_args() print_args(args) experiment_name = args.experiment_name batch_size = args.batch_size learning_rate = args.learning_rate hidden_layer_sizes = args.hidden_layer_sizes dropout = args.dropout epochs = args.epochs ### Output directory dir_name = log_dir_name(args) print() print(dir_name) print() output_dir = os.path.join('experiments', experiment_name, dir_name) if not os.path.exists(output_dir): os.makedirs(output_dir) dataset, dev_dataset, test_dataset = load_dataset(args.dataset_dir) nlabels = dataset[TARGET_COL].unique().shape[0] columns = [ 'Gender', 'Color1', 'Vaccinated', 'Dewormed', 'Breed1', 'Age', 'Fee', 'Quantity'] one_hot_columns, embedded_columns, numeric_columns = build_columns(dataset, columns) # TODO (optional) put these three types of columns in the same dictionary with "column types" X_train, y_train = process_features(dataset, one_hot_columns, numeric_columns, embedded_columns) direct_features_input_shape = (X_train['direct_features'].shape[1],) X_dev, y_dev = process_features(dev_dataset, one_hot_columns, numeric_columns, embedded_columns) ########################################################################################################### ### TODO: Shuffle train dataset - Done ########################################################################################################### shuffle_len = X_train['direct_features'].shape[0] train_ds = tf.data.Dataset.from_tensor_slices((X_train, y_train)).shuffle(shuffle_len).batch(batch_size) ########################################################################################################### dev_ds = tf.data.Dataset.from_tensor_slices((X_dev, y_dev)).batch(batch_size) test_ds = tf.data.Dataset.from_tensor_slices(process_features( test_dataset, one_hot_columns, numeric_columns, embedded_columns, test=True)[0]).batch(batch_size) ########################################################################################################### ### TODO: Build the Keras model - Done ########################################################################################################### tf.keras.backend.clear_session() # Add one input and one embedding for each embedded column embedding_layers = [] inputs = [] for embedded_col, max_value in embedded_columns.items(): input_layer = layers.Input(shape=(1,), name=embedded_col) inputs.append(input_layer) # Define the embedding layer embedding_size = int(max_value / 4) embedding_layers.append( tf.squeeze(layers.Embedding(input_dim=max_value, output_dim=embedding_size)(input_layer), axis=-2)) print('Adding embedding of size {} for layer {}'.format(embedding_size, embedded_col)) # Add the direct features already calculated direct_features_input = layers.Input(shape=direct_features_input_shape, name='direct_features') inputs.append(direct_features_input) # Concatenate everything together features = layers.concatenate(embedding_layers + [direct_features_input]) denses = [] dense1 = layers.Dense(hidden_layer_sizes[0], activation='relu')(features) denses.append(dense1) if len(hidden_layer_sizes) > 1: for hidden_layer_size in hidden_layer_sizes[1:]: dense = layers.Dense(hidden_layer_size, activation='relu')(denses[-1]) denses.append(dense) output_layer = layers.Dense(nlabels, activation='softmax')(dense1) model = models.Model(inputs=inputs, outputs=output_layer) ########################################################################################################### ########################################################################################################### ### TODO: Fit the model - Done ########################################################################################################### mlflow.set_experiment(experiment_name) optimizer = tf.keras.optimizers.Adam(learning_rate=learning_rate) model.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['accuracy']) logdir = "logs/scalars/" + dir_name tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=logdir) with mlflow.start_run(nested=True): # Log model hiperparameters first mlflow.log_param('hidden_layer_size', hidden_layer_sizes) mlflow.log_param('dropout', dropout) mlflow.log_param('embedded_columns', embedded_columns) mlflow.log_param('one_hot_columns', one_hot_columns) mlflow.log_param('numeric_columns', numeric_columns) # Not using these yet mlflow.log_param('epochs', epochs) mlflow.log_param('batch_size', batch_size) mlflow.log_param('learning_rate', learning_rate) # Train history = model.fit(train_ds, epochs=epochs, validation_data=dev_ds, callbacks=[tensorboard_callback]) ####################################################################################################### ### TODO: analyze history to see if model converges/overfits ####################################################################################################### output_csv = os.path.join(output_dir, 'history.pickle') with open(output_csv, 'bw') as f: pickle.dump(history.history, f) ####################################################################################################### ####################################################################################################### ### TODO: Evaluate the model, calculating the metrics. - Done ####################################################################################################### loss, accuracy = model.evaluate(dev_ds) print("*** Dev loss: {} - accuracy: {}".format(loss, accuracy)) mlflow.log_metric('loss', loss) mlflow.log_metric('accuracy', accuracy) predictions = model.predict(test_ds) ####################################################################################################### ####################################################################################################### ### TODO: Convert predictions to classes - Done ####################################################################################################### prediction_classes = np.argmax(predictions, axis=1) ####################################################################################################### ####################################################################################################### ### TODO: Save the results for submission - Done ####################################################################################################### output_csv = os.path.join(output_dir, 'submit.csv') submissions = pd.DataFrame(prediction_classes, columns=[TARGET_COL], index=test_dataset.PID) submissions.to_csv(output_csv) ####################################################################################################### ########################################################################################################### print('All operations completed') if __name__ == '__main__': main()
[ "mlflow.set_experiment", "mlflow.log_param", "tensorflow.keras.layers.Dense", "tensorflow.keras.layers.Input", "os.path.exists", "argparse.ArgumentParser", "tensorflow.data.Dataset.from_tensor_slices", "mlflow.log_metric", "auxiliary.log_dir_name", "auxiliary.load_dataset", "tensorflow.keras.models.Model", "mlflow.start_run", "pandas.DataFrame", "tensorflow.keras.callbacks.TensorBoard", "numpy.argmax", "tensorflow.keras.layers.Embedding", "warnings.filterwarnings", "pickle.dump", "os.makedirs", "auxiliary.build_columns", "os.path.join", "tensorflow.keras.layers.concatenate", "tensorflow.keras.optimizers.Adam", "tensorflow.keras.backend.clear_session", "auxiliary.process_features" ]
[((475, 508), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (498, 508), False, 'import warnings\n'), ((654, 732), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Training a MLP on the petfinder dataset"""'}), "(description='Training a MLP on the petfinder dataset')\n", (677, 732), False, 'import argparse\n'), ((2879, 2897), 'auxiliary.log_dir_name', 'log_dir_name', (['args'], {}), '(args)\n', (2891, 2897), False, 'from auxiliary import process_features, load_dataset, build_columns, log_dir_name\n'), ((2959, 3013), 'os.path.join', 'os.path.join', (['"""experiments"""', 'experiment_name', 'dir_name'], {}), "('experiments', experiment_name, dir_name)\n", (2971, 3013), False, 'import os\n'), ((3131, 3161), 'auxiliary.load_dataset', 'load_dataset', (['args.dataset_dir'], {}), '(args.dataset_dir)\n', (3143, 3161), False, 'from auxiliary import process_features, load_dataset, build_columns, log_dir_name\n'), ((3395, 3426), 'auxiliary.build_columns', 'build_columns', (['dataset', 'columns'], {}), '(dataset, columns)\n', (3408, 3426), False, 'from auxiliary import process_features, load_dataset, build_columns, log_dir_name\n'), ((3549, 3626), 'auxiliary.process_features', 'process_features', (['dataset', 'one_hot_columns', 'numeric_columns', 'embedded_columns'], {}), '(dataset, one_hot_columns, numeric_columns, embedded_columns)\n', (3565, 3626), False, 'from auxiliary import process_features, load_dataset, build_columns, log_dir_name\n'), ((3719, 3804), 'auxiliary.process_features', 'process_features', (['dev_dataset', 'one_hot_columns', 'numeric_columns', 'embedded_columns'], {}), '(dev_dataset, one_hot_columns, numeric_columns,\n embedded_columns)\n', (3735, 3804), False, 'from auxiliary import process_features, load_dataset, build_columns, log_dir_name\n'), ((4881, 4913), 'tensorflow.keras.backend.clear_session', 'tf.keras.backend.clear_session', ([], {}), '()\n', (4911, 4913), True, 'import tensorflow as tf\n'), ((5581, 5652), 'tensorflow.keras.layers.Input', 'layers.Input', ([], {'shape': 'direct_features_input_shape', 'name': '"""direct_features"""'}), "(shape=direct_features_input_shape, name='direct_features')\n", (5593, 5652), False, 'from tensorflow.keras import layers, models\n'), ((5756, 5818), 'tensorflow.keras.layers.concatenate', 'layers.concatenate', (['(embedding_layers + [direct_features_input])'], {}), '(embedding_layers + [direct_features_input])\n', (5774, 5818), False, 'from tensorflow.keras import layers, models\n'), ((6233, 6282), 'tensorflow.keras.models.Model', 'models.Model', ([], {'inputs': 'inputs', 'outputs': 'output_layer'}), '(inputs=inputs, outputs=output_layer)\n', (6245, 6282), False, 'from tensorflow.keras import layers, models\n'), ((6664, 6702), 'mlflow.set_experiment', 'mlflow.set_experiment', (['experiment_name'], {}), '(experiment_name)\n', (6685, 6702), False, 'import mlflow\n'), ((6720, 6773), 'tensorflow.keras.optimizers.Adam', 'tf.keras.optimizers.Adam', ([], {'learning_rate': 'learning_rate'}), '(learning_rate=learning_rate)\n', (6744, 6773), True, 'import tensorflow as tf\n'), ((6950, 6996), 'tensorflow.keras.callbacks.TensorBoard', 'tf.keras.callbacks.TensorBoard', ([], {'log_dir': 'logdir'}), '(log_dir=logdir)\n', (6980, 6996), True, 'import tensorflow as tf\n'), ((3025, 3051), 'os.path.exists', 'os.path.exists', (['output_dir'], {}), '(output_dir)\n', (3039, 3051), False, 'import os\n'), ((3061, 3084), 'os.makedirs', 'os.makedirs', (['output_dir'], {}), '(output_dir)\n', (3072, 3084), False, 'import os\n'), ((5103, 5146), 'tensorflow.keras.layers.Input', 'layers.Input', ([], {'shape': '(1,)', 'name': 'embedded_col'}), '(shape=(1,), name=embedded_col)\n', (5115, 5146), False, 'from tensorflow.keras import layers, models\n'), ((5849, 5903), 'tensorflow.keras.layers.Dense', 'layers.Dense', (['hidden_layer_sizes[0]'], {'activation': '"""relu"""'}), "(hidden_layer_sizes[0], activation='relu')\n", (5861, 5903), False, 'from tensorflow.keras import layers, models\n'), ((6168, 6211), 'tensorflow.keras.layers.Dense', 'layers.Dense', (['nlabels'], {'activation': '"""softmax"""'}), "(nlabels, activation='softmax')\n", (6180, 6211), False, 'from tensorflow.keras import layers, models\n'), ((7007, 7036), 'mlflow.start_run', 'mlflow.start_run', ([], {'nested': '(True)'}), '(nested=True)\n', (7023, 7036), False, 'import mlflow\n'), ((7088, 7145), 'mlflow.log_param', 'mlflow.log_param', (['"""hidden_layer_size"""', 'hidden_layer_sizes'], {}), "('hidden_layer_size', hidden_layer_sizes)\n", (7104, 7145), False, 'import mlflow\n'), ((7154, 7190), 'mlflow.log_param', 'mlflow.log_param', (['"""dropout"""', 'dropout'], {}), "('dropout', dropout)\n", (7170, 7190), False, 'import mlflow\n'), ((7199, 7253), 'mlflow.log_param', 'mlflow.log_param', (['"""embedded_columns"""', 'embedded_columns'], {}), "('embedded_columns', embedded_columns)\n", (7215, 7253), False, 'import mlflow\n'), ((7262, 7314), 'mlflow.log_param', 'mlflow.log_param', (['"""one_hot_columns"""', 'one_hot_columns'], {}), "('one_hot_columns', one_hot_columns)\n", (7278, 7314), False, 'import mlflow\n'), ((7323, 7375), 'mlflow.log_param', 'mlflow.log_param', (['"""numeric_columns"""', 'numeric_columns'], {}), "('numeric_columns', numeric_columns)\n", (7339, 7375), False, 'import mlflow\n'), ((7407, 7441), 'mlflow.log_param', 'mlflow.log_param', (['"""epochs"""', 'epochs'], {}), "('epochs', epochs)\n", (7423, 7441), False, 'import mlflow\n'), ((7450, 7492), 'mlflow.log_param', 'mlflow.log_param', (['"""batch_size"""', 'batch_size'], {}), "('batch_size', batch_size)\n", (7466, 7492), False, 'import mlflow\n'), ((7501, 7549), 'mlflow.log_param', 'mlflow.log_param', (['"""learning_rate"""', 'learning_rate'], {}), "('learning_rate', learning_rate)\n", (7517, 7549), False, 'import mlflow\n'), ((8058, 8100), 'os.path.join', 'os.path.join', (['output_dir', '"""history.pickle"""'], {}), "(output_dir, 'history.pickle')\n", (8070, 8100), False, 'import os\n'), ((8723, 8754), 'mlflow.log_metric', 'mlflow.log_metric', (['"""loss"""', 'loss'], {}), "('loss', loss)\n", (8740, 8754), False, 'import mlflow\n'), ((8763, 8802), 'mlflow.log_metric', 'mlflow.log_metric', (['"""accuracy"""', 'accuracy'], {}), "('accuracy', accuracy)\n", (8780, 8802), False, 'import mlflow\n'), ((9278, 9308), 'numpy.argmax', 'np.argmax', (['predictions'], {'axis': '(1)'}), '(predictions, axis=1)\n', (9287, 9308), True, 'import numpy as np\n'), ((9725, 9763), 'os.path.join', 'os.path.join', (['output_dir', '"""submit.csv"""'], {}), "(output_dir, 'submit.csv')\n", (9737, 9763), False, 'import os\n'), ((9786, 9864), 'pandas.DataFrame', 'pd.DataFrame', (['prediction_classes'], {'columns': '[TARGET_COL]', 'index': 'test_dataset.PID'}), '(prediction_classes, columns=[TARGET_COL], index=test_dataset.PID)\n', (9798, 9864), True, 'import pandas as pd\n'), ((4365, 4415), 'tensorflow.data.Dataset.from_tensor_slices', 'tf.data.Dataset.from_tensor_slices', (['(X_dev, y_dev)'], {}), '((X_dev, y_dev))\n', (4399, 4415), True, 'import tensorflow as tf\n'), ((8155, 8186), 'pickle.dump', 'pickle.dump', (['history.history', 'f'], {}), '(history.history, f)\n', (8166, 8186), False, 'import pickle\n'), ((6053, 6103), 'tensorflow.keras.layers.Dense', 'layers.Dense', (['hidden_layer_size'], {'activation': '"""relu"""'}), "(hidden_layer_size, activation='relu')\n", (6065, 6103), False, 'from tensorflow.keras import layers, models\n'), ((4145, 4199), 'tensorflow.data.Dataset.from_tensor_slices', 'tf.data.Dataset.from_tensor_slices', (['(X_train, y_train)'], {}), '((X_train, y_train))\n', (4179, 4199), True, 'import tensorflow as tf\n'), ((4483, 4580), 'auxiliary.process_features', 'process_features', (['test_dataset', 'one_hot_columns', 'numeric_columns', 'embedded_columns'], {'test': '(True)'}), '(test_dataset, one_hot_columns, numeric_columns,\n embedded_columns, test=True)\n', (4499, 4580), False, 'from auxiliary import process_features, load_dataset, build_columns, log_dir_name\n'), ((5319, 5383), 'tensorflow.keras.layers.Embedding', 'layers.Embedding', ([], {'input_dim': 'max_value', 'output_dim': 'embedding_size'}), '(input_dim=max_value, output_dim=embedding_size)\n', (5335, 5383), False, 'from tensorflow.keras import layers, models\n')]
import numpy as np import tensorflow as tf from tensorflow import keras import matplotlib.pyplot as plt from os import listdir from tensorflow.keras.callbacks import ModelCheckpoint dataDir = "./data/trainSmallFA/" files = listdir(dataDir) files.sort() totalLength = len(files) inputs = np.empty((len(files), 3, 64, 64)) targets = np.empty((len(files), 3, 64, 64)) for i, file in enumerate(files): npfile = np.load(dataDir + file) d = npfile['a'] inputs[i] = d[0:3] # inx, iny, mask targets[i] = d[3:6] # p, velx, vely # print("inputs shape = ", inputs.shape) print(np.shape(targets[:, 1, :, :].flatten())) maxvel = np.amax(np.sqrt(targets[:, 1, :, :]* targets[:, 1, :, :] + targets[:, 2, :, :]* targets[:, 2, :, :])) print(maxvel) targets[:, 1:3, :, :] /= maxvel targets[:, 0, :, :] /= np.amax(targets[:, 0, :, :]) for input in inputs: plt.figure(num=None, figsize=(20, 10), dpi=80, facecolor='w', edgecolor='k') # predicted data plt.subplot(331) plt.title('x vel') plt.imshow(input[0, :, :], cmap='jet') # vmin=-100,vmax=100, cmap='jet') plt.colorbar() plt.subplot(332) plt.title('y vel') plt.imshow(input[1, :, :], cmap='jet') plt.colorbar() plt.show()
[ "matplotlib.pyplot.imshow", "os.listdir", "numpy.sqrt", "matplotlib.pyplot.colorbar", "matplotlib.pyplot.subplot", "matplotlib.pyplot.figure", "matplotlib.pyplot.title", "numpy.load", "numpy.amax", "matplotlib.pyplot.show" ]
[((224, 240), 'os.listdir', 'listdir', (['dataDir'], {}), '(dataDir)\n', (231, 240), False, 'from os import listdir\n'), ((833, 861), 'numpy.amax', 'np.amax', (['targets[:, 0, :, :]'], {}), '(targets[:, 0, :, :])\n', (840, 861), True, 'import numpy as np\n'), ((413, 436), 'numpy.load', 'np.load', (['(dataDir + file)'], {}), '(dataDir + file)\n', (420, 436), True, 'import numpy as np\n'), ((645, 743), 'numpy.sqrt', 'np.sqrt', (['(targets[:, 1, :, :] * targets[:, 1, :, :] + targets[:, 2, :, :] * targets[\n :, 2, :, :])'], {}), '(targets[:, 1, :, :] * targets[:, 1, :, :] + targets[:, 2, :, :] *\n targets[:, 2, :, :])\n', (652, 743), True, 'import numpy as np\n'), ((887, 963), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'num': 'None', 'figsize': '(20, 10)', 'dpi': '(80)', 'facecolor': '"""w"""', 'edgecolor': '"""k"""'}), "(num=None, figsize=(20, 10), dpi=80, facecolor='w', edgecolor='k')\n", (897, 963), True, 'import matplotlib.pyplot as plt\n'), ((990, 1006), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(331)'], {}), '(331)\n', (1001, 1006), True, 'import matplotlib.pyplot as plt\n'), ((1011, 1029), 'matplotlib.pyplot.title', 'plt.title', (['"""x vel"""'], {}), "('x vel')\n", (1020, 1029), True, 'import matplotlib.pyplot as plt\n'), ((1034, 1072), 'matplotlib.pyplot.imshow', 'plt.imshow', (['input[0, :, :]'], {'cmap': '"""jet"""'}), "(input[0, :, :], cmap='jet')\n", (1044, 1072), True, 'import matplotlib.pyplot as plt\n'), ((1112, 1126), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (1124, 1126), True, 'import matplotlib.pyplot as plt\n'), ((1131, 1147), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(332)'], {}), '(332)\n', (1142, 1147), True, 'import matplotlib.pyplot as plt\n'), ((1152, 1170), 'matplotlib.pyplot.title', 'plt.title', (['"""y vel"""'], {}), "('y vel')\n", (1161, 1170), True, 'import matplotlib.pyplot as plt\n'), ((1175, 1213), 'matplotlib.pyplot.imshow', 'plt.imshow', (['input[1, :, :]'], {'cmap': '"""jet"""'}), "(input[1, :, :], cmap='jet')\n", (1185, 1213), True, 'import matplotlib.pyplot as plt\n'), ((1218, 1232), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (1230, 1232), True, 'import matplotlib.pyplot as plt\n'), ((1238, 1248), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1246, 1248), True, 'import matplotlib.pyplot as plt\n')]
import os import shutil import numpy as np import pandas as pd import seaborn as sns import cosmicfish as cf import matplotlib.pyplot as plt import dill # Instruct pyplot to use seaborn sns.set() # Set project, data, CLASS directories projectdir = os.environ['STORAGE_DIR'] datastore = os.environ['DATASTORE_DIR'] classpath = os.environ['CLASS_DIR'] fidx = int(os.environ['FORECAST_INDEX']) # Generate output paths fp_resultsdir = projectdir cf.makedirectory(fp_resultsdir) # Specify resolution of numerical integrals derivative_step = 0.008 # How much to vary parameter to calculate numerical derivative g_derivative_step = 0.1 mu_integral_step = 0.05 # For calculating numerical integral wrt mu between -1 and 1 # Linda Fiducial Cosmology fp_fid = { "A_s" : 2.2321e-9, "n_s" : 0.967, "omega_b" : 0.02226, "omega_cdm" : 0.1127, "tau_reio" : 0.0598, "h" : 0.701, "T_cmb" : 2.726, # Units [K] "N_ncdm" : 4., "deg_ncdm" : 1.0, "T_ncdm" : (0.79/2.726), # Units [T_cmb]. "m_ncdm" : 0.01, # Units [eV] "b0" : 1.0, "beta0" : 1.7, "beta1" : 1.0, "alphak2" : 1.0, "sigma_fog_0" : 250000, #Units [m s^-2] "N_eff" : 0.0064, #We allow relativistic neutrinos in addition to our DM relic "relic_vary" : "N_ncdm", # Fix T_ncdm or m_ncdm "m_nu" : 0.02 } # EUCLID values z_table = np.array([0.65, 0.75, 0.85, 0.95, 1.05, 1.15, 1.25, 1.35, 1.45, 1.55, 1.65, 1.75, 1.85, 1.95]) dNdz = np.array([2434.280, 4364.812, 4728.559, 4825.798, 4728.797, 4507.625, 4269.851, 3720.657, 3104.309, 2308.975, 1514.831, 1474.707, 893.716, 497.613]) skycover = 0.3636 # Run Fisher Forecast full_masses = np.geomspace(0.01, 10., 21) full_temps = np.array([0.79, 0.91, 0.94, 1.08]) mass_index=(fidx % 21) temp_index=(fidx // 21) masses = np.array([full_masses[mass_index]]) temps = np.array([full_temps[temp_index]]) omegacdm_set = np.array([ fp_fid['omega_cdm'] - ((masses/cf.NEUTRINO_SCALE_FACTOR)* np.power(tval / 1.95, 3.)) for tidx, tval in enumerate(temps)]) fp_fiducialset = [[ dict(fp_fid, **{ 'm_ncdm' : masses[midx], 'omega_cdm' : omegacdm_set[tidx, midx], 'T_ncdm' : temps[tidx]/2.726}) for midx, mval in enumerate(masses)] for tidx, tval in enumerate(temps)] fp_forecastset = [[cf.forecast( classpath, datastore, '2relic', fidval, z_table, "EUCLID", dNdz, fsky=skycover, dstep=derivative_step, gstep=g_derivative_step, RSD=True, FOG=True, AP=True, COV=True) for fididx, fidval in enumerate(fidrowvals)] for fidrowidx, fidrowvals in enumerate(fp_fiducialset)] #dill.load_session('') for frowidx, frowval in enumerate(fp_forecastset): for fidx, fcst in enumerate(frowval): if type(fcst.fisher)==type(None): fcst.gen_pm() fcst.gen_fisher( fisher_order=[ 'omega_b', 'omega_cdm', 'n_s', 'A_s', 'tau_reio', 'h', 'N_ncdm', 'M_ncdm', 'sigma_fog', 'beta0', 'beta1', 'alpha_k2'], mu_step=mu_integral_step, skipgen=False) print("Relic Forecast ", fidx, " complete...") dill.dump_session(os.path.join(fp_resultsdir, 'fp_'+str(temp_index)+'_'+str(mass_index)+'.db')) else: print('Fisher matrix already generated!')
[ "seaborn.set", "numpy.power", "numpy.geomspace", "numpy.array", "cosmicfish.makedirectory", "cosmicfish.forecast" ]
[((665, 674), 'seaborn.set', 'sns.set', ([], {}), '()\n', (672, 674), True, 'import seaborn as sns\n'), ((1328, 1359), 'cosmicfish.makedirectory', 'cf.makedirectory', (['fp_resultsdir'], {}), '(fp_resultsdir)\n', (1344, 1359), True, 'import cosmicfish as cf\n'), ((3270, 3368), 'numpy.array', 'np.array', (['[0.65, 0.75, 0.85, 0.95, 1.05, 1.15, 1.25, 1.35, 1.45, 1.55, 1.65, 1.75, \n 1.85, 1.95]'], {}), '([0.65, 0.75, 0.85, 0.95, 1.05, 1.15, 1.25, 1.35, 1.45, 1.55, 1.65,\n 1.75, 1.85, 1.95])\n', (3278, 3368), True, 'import numpy as np\n'), ((3372, 3529), 'numpy.array', 'np.array', (['[2434.28, 4364.812, 4728.559, 4825.798, 4728.797, 4507.625, 4269.851, \n 3720.657, 3104.309, 2308.975, 1514.831, 1474.707, 893.716, 497.613]'], {}), '([2434.28, 4364.812, 4728.559, 4825.798, 4728.797, 4507.625, \n 4269.851, 3720.657, 3104.309, 2308.975, 1514.831, 1474.707, 893.716, \n 497.613])\n', (3380, 3529), True, 'import numpy as np\n'), ((3675, 3703), 'numpy.geomspace', 'np.geomspace', (['(0.01)', '(10.0)', '(21)'], {}), '(0.01, 10.0, 21)\n', (3687, 3703), True, 'import numpy as np\n'), ((3768, 3802), 'numpy.array', 'np.array', (['[0.79, 0.91, 0.94, 1.08]'], {}), '([0.79, 0.91, 0.94, 1.08])\n', (3776, 3802), True, 'import numpy as np\n'), ((3865, 3900), 'numpy.array', 'np.array', (['[full_masses[mass_index]]'], {}), '([full_masses[mass_index]])\n', (3873, 3900), True, 'import numpy as np\n'), ((3909, 3943), 'numpy.array', 'np.array', (['[full_temps[temp_index]]'], {}), '([full_temps[temp_index]])\n', (3917, 3943), True, 'import numpy as np\n'), ((4805, 4991), 'cosmicfish.forecast', 'cf.forecast', (['classpath', 'datastore', '"""2relic"""', 'fidval', 'z_table', '"""EUCLID"""', 'dNdz'], {'fsky': 'skycover', 'dstep': 'derivative_step', 'gstep': 'g_derivative_step', 'RSD': '(True)', 'FOG': '(True)', 'AP': '(True)', 'COV': '(True)'}), "(classpath, datastore, '2relic', fidval, z_table, 'EUCLID', dNdz,\n fsky=skycover, dstep=derivative_step, gstep=g_derivative_step, RSD=True,\n FOG=True, AP=True, COV=True)\n", (4816, 4991), True, 'import cosmicfish as cf\n'), ((4147, 4173), 'numpy.power', 'np.power', (['(tval / 1.95)', '(3.0)'], {}), '(tval / 1.95, 3.0)\n', (4155, 4173), True, 'import numpy as np\n')]
import argparse import warnings warnings.simplefilter("ignore", UserWarning) import files from tensorboardX import SummaryWriter import os import numpy as np import time import torch import torch.optim import torch.nn as nn import torch.utils.data import torchvision import torchvision.transforms as tfs from data import DataSet,return_model_loader from util import weight_init, write_conv, setup_runtime, AverageMeter, MovingAverage def RotationDataLoader(image_dir, is_validation=False, batch_size=256, crop_size=224, num_workers=4,shuffle=True): normalize = tfs.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) transforms = tfs.Compose([ tfs.RandomResizedCrop(crop_size), tfs.RandomGrayscale(p=0.2), tfs.ColorJitter(0.4, 0.4, 0.4, 0.4), tfs.RandomHorizontalFlip(), tfs.Lambda(lambda img: torch.stack([normalize(tfs.ToTensor()( tfs.functional.rotate(img, angle))) for angle in [0, 90, 180, 270]] )) ]) if is_validation: dataset = DataSet(torchvision.datasets.ImageFolder(image_dir + '/val', transforms)) else: dataset = DataSet(torchvision.datasets.ImageFolder(image_dir + '/train', transforms)) loader = torch.utils.data.DataLoader( dataset, batch_size=batch_size, shuffle=shuffle, num_workers=num_workers, pin_memory=True, drop_last=False ) return loader class Optimizer: def __init__(self): self.num_epochs = 30 self.lr = 0.05 self.lr_schedule = lambda epoch: (self.lr * (0.1 ** (epoch//args.lrdrop)))*(epoch<80) + (epoch>=80)*self.lr*(0.1**3) self.momentum = 0.9 self.weight_decay = 10**(-5) self.resume = True self.checkpoint_dir = None self.writer = None self.K = args.ncl self.dev = torch.device("cuda" if torch.cuda.is_available() else "cpu") self.val_loader = RotationDataLoader(args.imagenet_path, is_validation=True, batch_size=args.batch_size, num_workers=args.workers,shuffle=True) def optimize_epoch(self, model, optimizer, loader, epoch, validation=False): print(f"Starting epoch {epoch}, validation: {validation} " + "="*30) loss_value = AverageMeter() rotacc_value = AverageMeter() # house keeping if not validation: model.train() lr = self.lr_schedule(epoch) for pg in optimizer.param_groups: pg['lr'] = lr else: model.eval() XE = torch.nn.CrossEntropyLoss().to(self.dev) l_dl = 0 # len(loader) now = time.time() batch_time = MovingAverage(intertia=0.9) for iter, (data, label, selected) in enumerate(loader): now = time.time() if not validation: niter = epoch * len(loader.dataset) + iter*args.batch_size data = data.to(self.dev) mass = data.size(0) where = np.arange(mass,dtype=int) * 4 data = data.view(mass * 4, 3, data.size(3), data.size(4)) rotlabel = torch.tensor(range(4)).view(-1, 1).repeat(mass, 1).view(-1).to(self.dev) #################### train CNN ########################################### if not validation: final = model(data) if args.onlyrot: loss = torch.Tensor([0]).to(self.dev) else: if args.hc == 1: loss = XE(final[0][where], self.L[selected]) else: loss = torch.mean(torch.stack([XE(final[k][where], self.L[k, selected]) for k in range(args.hc)])) rotloss = XE(final[-1], rotlabel) pred = torch.argmax(final[-1], 1) total_loss = loss + rotloss optimizer.zero_grad() total_loss.backward() optimizer.step() correct = (pred == rotlabel).to(torch.float) rotacc = correct.sum() / float(mass) else: final = model(data) pred = torch.argmax(final[-1], 1) correct = (pred == rotlabel.cuda()).to(torch.float) rotacc = correct.sum() / float(mass) total_loss = torch.Tensor([0]) loss = torch.Tensor([0]) rotloss = torch.Tensor([0]) rotacc_value.update(rotacc.item(), mass) loss_value.update(total_loss.item(), mass) batch_time.update(time.time() - now) now = time.time() print( f"Loss: {loss_value.avg:03.3f}, RotAcc: {rotacc_value.avg:03.3f} | {epoch: 3}/{iter:05}/{l_dl:05} Freq: {mass / batch_time.avg:04.1f}Hz:", end='\r', flush=True) # every few iter logging if (iter % args.logiter == 0): if not validation: print(niter, " Loss: {0:.3f}".format(loss.item()), flush=True) with torch.no_grad(): if not args.onlyrot: pred = torch.argmax(final[0][where], dim=1) pseudoloss = XE(final[0][where], pred) if not args.onlyrot: self.writer.add_scalar('Pseudoloss', pseudoloss.item(), niter) self.writer.add_scalar('lr', self.lr_schedule(epoch), niter) self.writer.add_scalar('Loss', loss.item(), niter) self.writer.add_scalar('RotLoss', rotloss.item(), niter) self.writer.add_scalar('RotAcc', rotacc.item(), niter) if iter > 0: self.writer.add_scalar('Freq(Hz)', mass/(time.time() - now), niter) # end of epoch logging if self.writer and (epoch % self.log_interval == 0): write_conv(self.writer, model, epoch) if validation: print('val Rot-Acc: ', rotacc_value.avg) self.writer.add_scalar('val Rot-Acc', rotacc_value.avg, epoch) files.save_checkpoint_all(self.checkpoint_dir, model, args.arch, optimizer, self.L, epoch,lowest=False) return {'loss': loss_value.avg} def optimize(self, model, train_loader): """Perform full optimization.""" first_epoch = 0 model = model.to(self.dev) self.optimize_times = [0] optimizer = torch.optim.SGD(filter(lambda p: p.requires_grad, model.parameters()), weight_decay=self.weight_decay, momentum=self.momentum, lr=self.lr) if self.checkpoint_dir is not None and self.resume: self.L, first_epoch = files.load_checkpoint_all(self.checkpoint_dir, model=None, opt=None) print('loaded from: ', self.checkpoint_dir,flush=True) print('first five entries of L: ', self.L[:5], flush=True) print('found first epoch to be', first_epoch, flush=True) first_epoch = 0 self.optimize_times = [0] self.L = self.L.cuda() print("model.headcount ", model.headcount, flush=True) ##################################################################################### # Perform optmization ############################################################### lowest_loss = 1e9 epoch = first_epoch while epoch < (self.num_epochs+1): if not args.val_only: m = self.optimize_epoch(model, optimizer, train_loader, epoch, validation=False) if m['loss'] < lowest_loss: lowest_loss = m['loss'] files.save_checkpoint_all(self.checkpoint_dir, model, args.arch, optimizer, self.L, epoch, lowest=True) else: print('='*30 +' doing only validation ' + "="*30) epoch = self.num_epochs m = self.optimize_epoch(model, optimizer, self.val_loader, epoch, validation=True) epoch += 1 print(f"Model optimization completed. Saving final model to {os.path.join(self.checkpoint_dir, 'model_final.pth.tar')}") torch.save(model, os.path.join(self.checkpoint_dir, 'model_final.pth.tar')) return model def get_parser(): parser = argparse.ArgumentParser(description='Retrain with given labels combined with RotNet loss') # optimizer parser.add_argument('--epochs', default=90, type=int, metavar='N', help='number of epochs') parser.add_argument('--batch-size', default=64, type=int, metavar='BS', help='batch size') parser.add_argument('--lr', default=0.05, type=float, metavar='FLOAT', help='initial learning rate') parser.add_argument('--lrdrop', default=30, type=int, metavar='INT', help='multiply LR by 0.1 every') # architecture parser.add_argument('--arch', default='alexnet', type=str, help='alexnet or resnet') parser.add_argument('--archspec', default='big', type=str, help='big or small for alexnet ') parser.add_argument('--ncl', default=1000, type=int, metavar='INT', help='number of clusters') parser.add_argument('--hc', default=1, type=int, metavar='INT', help='number of heads') parser.add_argument('--init', default=False, action='store_true', help='initialization of network to PyTorch 0.4') # what we do in this code parser.add_argument('--val-only', default=False, action='store_true', help='if we run only validation set') parser.add_argument('--onlyrot', default=False, action='store_true', help='if train only RotNet') # housekeeping parser.add_argument('--data', default="Imagenet", type=str) parser.add_argument('--device', default="0", type=str, metavar='N', help='GPU device') parser.add_argument('--exp', default='./rot-retrain', metavar='DIR', help='path to result dirs') parser.add_argument('--workers', default=6, type=int, metavar='N', help='number workers (default: 6)') parser.add_argument('--imagenet-path', default='/home/ubuntu/data/imagenet', type=str, help='') parser.add_argument('--comment', default='rot-retrain', type=str, help='comment for tensorboardX') parser.add_argument('--log-interval', default=1, type=int, metavar='INT', help='save stuff every x epochs') parser.add_argument('--logiter', default=200, type=int, metavar='INT', help='log every x-th batch') return parser if __name__ == "__main__": args = get_parser().parse_args() name = "%s" % args.comment.replace('/', '_') try: args.device = [int(item) for item in args.device.split(',')] except AttributeError: args.device = [int(args.device)] setup_runtime(seed=42, cuda_dev_id=args.device) print(args, flush=True) print() print(name,flush=True) writer = SummaryWriter('./runs/%s/%s'%(args.data,name)) writer.add_text('args', " \n".join(['%s %s' % (arg, getattr(args, arg)) for arg in vars(args)])) # Setup model and train_loader print('Commencing!', flush=True) model, train_loader = return_model_loader(args) train_loader = RotationDataLoader(args.imagenet_path, is_validation=False, crop_size=224, batch_size=args.batch_size, num_workers=args.workers, shuffle=True) # add additional head to the network for RotNet loss. if args.arch == 'alexnet': if args.hc == 1: model.__setattr__("top_layer0", nn.Linear(4096, args.ncl)) model.top_layer = None model.headcount = args.hc+1 model.__setattr__("top_layer%s" % args.hc, nn.Linear(4096, 4)) else: if args.hc == 1: model.__setattr__("top_layer0", nn.Linear(2048*int(args.archspec), args.ncl)) model.top_layer = None model.headcount = args.hc+1 model.__setattr__("top_layer%s" % args.hc, nn.Linear(2048*int(args.archspec), 4)) if args.init: for mod in model.modules(): mod.apply(weight_init) # Setup optimizer o = Optimizer() o.writer = writer o.lr = args.lr o.num_epochs = args.epochs o.resume = True o.log_interval = args.log_interval o.checkpoint_dir = os.path.join(args.exp, 'checkpoints') # Optimize o.optimize(model, train_loader)
[ "torch.nn.CrossEntropyLoss", "torchvision.transforms.ColorJitter", "torchvision.transforms.functional.rotate", "torch.cuda.is_available", "files.save_checkpoint_all", "numpy.arange", "util.setup_runtime", "tensorboardX.SummaryWriter", "argparse.ArgumentParser", "util.write_conv", "torchvision.datasets.ImageFolder", "util.MovingAverage", "files.load_checkpoint_all", "warnings.simplefilter", "torchvision.transforms.ToTensor", "torchvision.transforms.RandomResizedCrop", "torch.argmax", "torchvision.transforms.RandomHorizontalFlip", "torch.Tensor", "torchvision.transforms.Normalize", "data.return_model_loader", "util.AverageMeter", "time.time", "torchvision.transforms.RandomGrayscale", "os.path.join", "torch.nn.Linear", "torch.utils.data.DataLoader", "torch.no_grad" ]
[((32, 76), 'warnings.simplefilter', 'warnings.simplefilter', (['"""ignore"""', 'UserWarning'], {}), "('ignore', UserWarning)\n", (53, 76), False, 'import warnings\n'), ((594, 662), 'torchvision.transforms.Normalize', 'tfs.Normalize', ([], {'mean': '[0.485, 0.456, 0.406]', 'std': '[0.229, 0.224, 0.225]'}), '(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n', (607, 662), True, 'import torchvision.transforms as tfs\n'), ((1444, 1583), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['dataset'], {'batch_size': 'batch_size', 'shuffle': 'shuffle', 'num_workers': 'num_workers', 'pin_memory': '(True)', 'drop_last': '(False)'}), '(dataset, batch_size=batch_size, shuffle=shuffle,\n num_workers=num_workers, pin_memory=True, drop_last=False)\n', (1471, 1583), False, 'import torch\n'), ((8746, 8841), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Retrain with given labels combined with RotNet loss"""'}), "(description=\n 'Retrain with given labels combined with RotNet loss')\n", (8769, 8841), False, 'import argparse\n'), ((11101, 11148), 'util.setup_runtime', 'setup_runtime', ([], {'seed': '(42)', 'cuda_dev_id': 'args.device'}), '(seed=42, cuda_dev_id=args.device)\n', (11114, 11148), False, 'from util import weight_init, write_conv, setup_runtime, AverageMeter, MovingAverage\n'), ((11230, 11279), 'tensorboardX.SummaryWriter', 'SummaryWriter', (["('./runs/%s/%s' % (args.data, name))"], {}), "('./runs/%s/%s' % (args.data, name))\n", (11243, 11279), False, 'from tensorboardX import SummaryWriter\n'), ((11478, 11503), 'data.return_model_loader', 'return_model_loader', (['args'], {}), '(args)\n', (11497, 11503), False, 'from data import DataSet, return_model_loader\n'), ((12643, 12680), 'os.path.join', 'os.path.join', (['args.exp', '"""checkpoints"""'], {}), "(args.exp, 'checkpoints')\n", (12655, 12680), False, 'import os\n'), ((2512, 2526), 'util.AverageMeter', 'AverageMeter', ([], {}), '()\n', (2524, 2526), False, 'from util import weight_init, write_conv, setup_runtime, AverageMeter, MovingAverage\n'), ((2550, 2564), 'util.AverageMeter', 'AverageMeter', ([], {}), '()\n', (2562, 2564), False, 'from util import weight_init, write_conv, setup_runtime, AverageMeter, MovingAverage\n'), ((2900, 2911), 'time.time', 'time.time', ([], {}), '()\n', (2909, 2911), False, 'import time\n'), ((2933, 2960), 'util.MovingAverage', 'MovingAverage', ([], {'intertia': '(0.9)'}), '(intertia=0.9)\n', (2946, 2960), False, 'from util import weight_init, write_conv, setup_runtime, AverageMeter, MovingAverage\n'), ((6392, 6500), 'files.save_checkpoint_all', 'files.save_checkpoint_all', (['self.checkpoint_dir', 'model', 'args.arch', 'optimizer', 'self.L', 'epoch'], {'lowest': '(False)'}), '(self.checkpoint_dir, model, args.arch, optimizer,\n self.L, epoch, lowest=False)\n', (6417, 6500), False, 'import files\n'), ((726, 758), 'torchvision.transforms.RandomResizedCrop', 'tfs.RandomResizedCrop', (['crop_size'], {}), '(crop_size)\n', (747, 758), True, 'import torchvision.transforms as tfs\n'), ((792, 818), 'torchvision.transforms.RandomGrayscale', 'tfs.RandomGrayscale', ([], {'p': '(0.2)'}), '(p=0.2)\n', (811, 818), True, 'import torchvision.transforms as tfs\n'), ((852, 887), 'torchvision.transforms.ColorJitter', 'tfs.ColorJitter', (['(0.4)', '(0.4)', '(0.4)', '(0.4)'], {}), '(0.4, 0.4, 0.4, 0.4)\n', (867, 887), True, 'import torchvision.transforms as tfs\n'), ((921, 947), 'torchvision.transforms.RandomHorizontalFlip', 'tfs.RandomHorizontalFlip', ([], {}), '()\n', (945, 947), True, 'import torchvision.transforms as tfs\n'), ((1261, 1325), 'torchvision.datasets.ImageFolder', 'torchvision.datasets.ImageFolder', (["(image_dir + '/val')", 'transforms'], {}), "(image_dir + '/val', transforms)\n", (1293, 1325), False, 'import torchvision\n'), ((1363, 1429), 'torchvision.datasets.ImageFolder', 'torchvision.datasets.ImageFolder', (["(image_dir + '/train')", 'transforms'], {}), "(image_dir + '/train', transforms)\n", (1395, 1429), False, 'import torchvision\n'), ((3043, 3054), 'time.time', 'time.time', ([], {}), '()\n', (3052, 3054), False, 'import time\n'), ((4870, 4881), 'time.time', 'time.time', ([], {}), '()\n', (4879, 4881), False, 'import time\n'), ((6182, 6219), 'util.write_conv', 'write_conv', (['self.writer', 'model', 'epoch'], {}), '(self.writer, model, epoch)\n', (6192, 6219), False, 'from util import weight_init, write_conv, setup_runtime, AverageMeter, MovingAverage\n'), ((7114, 7182), 'files.load_checkpoint_all', 'files.load_checkpoint_all', (['self.checkpoint_dir'], {'model': 'None', 'opt': 'None'}), '(self.checkpoint_dir, model=None, opt=None)\n', (7139, 7182), False, 'import files\n'), ((8632, 8688), 'os.path.join', 'os.path.join', (['self.checkpoint_dir', '"""model_final.pth.tar"""'], {}), "(self.checkpoint_dir, 'model_final.pth.tar')\n", (8644, 8688), False, 'import os\n'), ((12051, 12069), 'torch.nn.Linear', 'nn.Linear', (['(4096)', '(4)'], {}), '(4096, 4)\n', (12060, 12069), True, 'import torch.nn as nn\n'), ((2095, 2120), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (2118, 2120), False, 'import torch\n'), ((2813, 2840), 'torch.nn.CrossEntropyLoss', 'torch.nn.CrossEntropyLoss', ([], {}), '()\n', (2838, 2840), False, 'import torch\n'), ((3251, 3277), 'numpy.arange', 'np.arange', (['mass'], {'dtype': 'int'}), '(mass, dtype=int)\n', (3260, 3277), True, 'import numpy as np\n'), ((4042, 4068), 'torch.argmax', 'torch.argmax', (['final[-1]', '(1)'], {}), '(final[-1], 1)\n', (4054, 4068), False, 'import torch\n'), ((4414, 4440), 'torch.argmax', 'torch.argmax', (['final[-1]', '(1)'], {}), '(final[-1], 1)\n', (4426, 4440), False, 'import torch\n'), ((4591, 4608), 'torch.Tensor', 'torch.Tensor', (['[0]'], {}), '([0])\n', (4603, 4608), False, 'import torch\n'), ((4632, 4649), 'torch.Tensor', 'torch.Tensor', (['[0]'], {}), '([0])\n', (4644, 4649), False, 'import torch\n'), ((4676, 4693), 'torch.Tensor', 'torch.Tensor', (['[0]'], {}), '([0])\n', (4688, 4693), False, 'import torch\n'), ((11902, 11927), 'torch.nn.Linear', 'nn.Linear', (['(4096)', 'args.ncl'], {}), '(4096, args.ncl)\n', (11911, 11927), True, 'import torch.nn as nn\n'), ((4833, 4844), 'time.time', 'time.time', ([], {}), '()\n', (4842, 4844), False, 'import time\n'), ((8085, 8192), 'files.save_checkpoint_all', 'files.save_checkpoint_all', (['self.checkpoint_dir', 'model', 'args.arch', 'optimizer', 'self.L', 'epoch'], {'lowest': '(True)'}), '(self.checkpoint_dir, model, args.arch, optimizer,\n self.L, epoch, lowest=True)\n', (8110, 8192), False, 'import files\n'), ((8546, 8602), 'os.path.join', 'os.path.join', (['self.checkpoint_dir', '"""model_final.pth.tar"""'], {}), "(self.checkpoint_dir, 'model_final.pth.tar')\n", (8558, 8602), False, 'import os\n'), ((5318, 5333), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (5331, 5333), False, 'import torch\n'), ((3661, 3678), 'torch.Tensor', 'torch.Tensor', (['[0]'], {}), '([0])\n', (3673, 3678), False, 'import torch\n'), ((5415, 5451), 'torch.argmax', 'torch.argmax', (['final[0][where]'], {'dim': '(1)'}), '(final[0][where], dim=1)\n', (5427, 5451), False, 'import torch\n'), ((1027, 1041), 'torchvision.transforms.ToTensor', 'tfs.ToTensor', ([], {}), '()\n', (1039, 1041), True, 'import torchvision.transforms as tfs\n'), ((1079, 1112), 'torchvision.transforms.functional.rotate', 'tfs.functional.rotate', (['img', 'angle'], {}), '(img, angle)\n', (1100, 1112), True, 'import torchvision.transforms as tfs\n'), ((6050, 6061), 'time.time', 'time.time', ([], {}), '()\n', (6059, 6061), False, 'import time\n')]
import numpy as np from something import Top i = 0 while i < 10: a = np.ndarray((10,4)) b = np.ones((10, Top)) i += 1 del Top # show_store()
[ "numpy.ndarray", "numpy.ones" ]
[((74, 93), 'numpy.ndarray', 'np.ndarray', (['(10, 4)'], {}), '((10, 4))\n', (84, 93), True, 'import numpy as np\n'), ((101, 119), 'numpy.ones', 'np.ones', (['(10, Top)'], {}), '((10, Top))\n', (108, 119), True, 'import numpy as np\n')]
import torch import numpy as np import hashlib from torch.autograd import Variable import os def deterministic_random(min_value, max_value, data): digest = hashlib.sha256(data.encode()).digest() raw_value = int.from_bytes(digest[:4], byteorder='little', signed=False) return int(raw_value / (2 ** 32 - 1) * (max_value - min_value)) + min_value def mpjpe_cal(predicted, target): assert predicted.shape == target.shape return torch.mean(torch.norm(predicted - target, dim=len(target.shape) - 1)) def test_calculation(predicted, target, action, error_sum, data_type, subject, MAE=False): error_sum = mpjpe_by_action_p1(predicted, target, action, error_sum) if not MAE: error_sum = mpjpe_by_action_p2(predicted, target, action, error_sum) return error_sum def mpjpe_by_action_p1(predicted, target, action, action_error_sum): assert predicted.shape == target.shape batch_num = predicted.size(0) frame_num = predicted.size(1) dist = torch.mean(torch.norm(predicted - target, dim=len(target.shape) - 1), dim=len(target.shape) - 2) if len(set(list(action))) == 1: end_index = action[0].find(' ') if end_index != -1: action_name = action[0][:end_index] else: action_name = action[0] action_error_sum[action_name]['p1'].update(torch.mean(dist).item()*batch_num*frame_num, batch_num*frame_num) else: for i in range(batch_num): end_index = action[i].find(' ') if end_index != -1: action_name = action[i][:end_index] else: action_name = action[i] action_error_sum[action_name]['p1'].update(torch.mean(dist[i]).item()*frame_num, frame_num) return action_error_sum def mpjpe_by_action_p2(predicted, target, action, action_error_sum): assert predicted.shape == target.shape num = predicted.size(0) pred = predicted.detach().cpu().numpy().reshape(-1, predicted.shape[-2], predicted.shape[-1]) gt = target.detach().cpu().numpy().reshape(-1, target.shape[-2], target.shape[-1]) dist = p_mpjpe(pred, gt) if len(set(list(action))) == 1: end_index = action[0].find(' ') if end_index != -1: action_name = action[0][:end_index] else: action_name = action[0] action_error_sum[action_name]['p2'].update(np.mean(dist) * num, num) else: for i in range(num): end_index = action[i].find(' ') if end_index != -1: action_name = action[i][:end_index] else: action_name = action[i] action_error_sum[action_name]['p2'].update(np.mean(dist), 1) return action_error_sum def p_mpjpe(predicted, target): assert predicted.shape == target.shape muX = np.mean(target, axis=1, keepdims=True) muY = np.mean(predicted, axis=1, keepdims=True) X0 = target - muX Y0 = predicted - muY normX = np.sqrt(np.sum(X0 ** 2, axis=(1, 2), keepdims=True)) normY = np.sqrt(np.sum(Y0 ** 2, axis=(1, 2), keepdims=True)) X0 /= normX Y0 /= normY H = np.matmul(X0.transpose(0, 2, 1), Y0) U, s, Vt = np.linalg.svd(H) V = Vt.transpose(0, 2, 1) R = np.matmul(V, U.transpose(0, 2, 1)) sign_detR = np.sign(np.expand_dims(np.linalg.det(R), axis=1)) V[:, :, -1] *= sign_detR s[:, -1] *= sign_detR.flatten() R = np.matmul(V, U.transpose(0, 2, 1)) tr = np.expand_dims(np.sum(s, axis=1, keepdims=True), axis=2) a = tr * normX / normY t = muX - a * np.matmul(muY, R) predicted_aligned = a * np.matmul(predicted, R) + t return np.mean(np.linalg.norm(predicted_aligned - target, axis=len(target.shape) - 1), axis=len(target.shape) - 2) def define_actions( action ): actions = ["Directions","Discussion","Eating","Greeting", "Phoning","Photo","Posing","Purchases", "Sitting","SittingDown","Smoking","Waiting", "WalkDog","Walking","WalkTogether"] if action == "All" or action == "all" or action == '*': return actions if not action in actions: raise( ValueError, "Unrecognized action: %s" % action ) return [action] def define_error_list(actions): error_sum = {} error_sum.update({actions[i]: {'p1':AccumLoss(), 'p2':AccumLoss()} for i in range(len(actions))}) return error_sum class AccumLoss(object): def __init__(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += val self.count += n self.avg = self.sum / self.count def get_varialbe(split, target): num = len(target) var = [] if split == 'train': for i in range(num): temp = Variable(target[i], requires_grad=False).contiguous().type(torch.cuda.FloatTensor) var.append(temp) else: for i in range(num): temp = Variable(target[i]).contiguous().cuda().type(torch.cuda.FloatTensor) var.append(temp) return var def print_error(data_type, action_error_sum, is_train): mean_error_p1, mean_error_p2 = print_error_action(action_error_sum, is_train) return mean_error_p1, mean_error_p2 def print_error_action(action_error_sum, is_train): mean_error_each = {'p1': 0.0, 'p2': 0.0} mean_error_all = {'p1': AccumLoss(), 'p2': AccumLoss()} if is_train == 0: print("{0:=^12} {1:=^10} {2:=^8}".format("Action", "p#1 mm", "p#2 mm")) for action, value in action_error_sum.items(): if is_train == 0: print("{0:<12} ".format(action), end="") mean_error_each['p1'] = action_error_sum[action]['p1'].avg * 1000.0 mean_error_all['p1'].update(mean_error_each['p1'], 1) mean_error_each['p2'] = action_error_sum[action]['p2'].avg * 1000.0 mean_error_all['p2'].update(mean_error_each['p2'], 1) if is_train == 0: print("{0:>6.2f} {1:>10.2f}".format(mean_error_each['p1'], mean_error_each['p2'])) if is_train == 0: print("{0:<12} {1:>6.2f} {2:>10.2f}".format("Average", mean_error_all['p1'].avg, \ mean_error_all['p2'].avg)) return mean_error_all['p1'].avg, mean_error_all['p2'].avg def save_model(previous_name, save_dir,epoch, data_threshold, model, model_name): # if os.path.exists(previous_name): # os.remove(previous_name) torch.save(model.state_dict(), '%s/%s_%d_%d.pth' % (save_dir, model_name, epoch, data_threshold * 100)) previous_name = '%s/%s_%d_%d.pth' % (save_dir, model_name, epoch, data_threshold * 100) return previous_name def save_model_new(save_dir,epoch, data_threshold, lr, optimizer, model, model_name): # if os.path.exists(previous_name): # os.remove(previous_name) # torch.save(model.state_dict(), # '%s/%s_%d_%d.pth' % (save_dir, model_name, epoch, data_threshold * 100)) torch.save({ 'epoch': epoch, 'lr': lr, 'optimizer': optimizer.state_dict(), 'model_pos': model.state_dict(), }, '%s/%s_%d_%d.pth' % (save_dir, model_name, epoch, data_threshold * 100))
[ "numpy.mean", "torch.mean", "numpy.linalg.det", "numpy.sum", "numpy.matmul", "numpy.linalg.svd", "torch.autograd.Variable" ]
[((2852, 2890), 'numpy.mean', 'np.mean', (['target'], {'axis': '(1)', 'keepdims': '(True)'}), '(target, axis=1, keepdims=True)\n', (2859, 2890), True, 'import numpy as np\n'), ((2901, 2942), 'numpy.mean', 'np.mean', (['predicted'], {'axis': '(1)', 'keepdims': '(True)'}), '(predicted, axis=1, keepdims=True)\n', (2908, 2942), True, 'import numpy as np\n'), ((3216, 3232), 'numpy.linalg.svd', 'np.linalg.svd', (['H'], {}), '(H)\n', (3229, 3232), True, 'import numpy as np\n'), ((3012, 3055), 'numpy.sum', 'np.sum', (['(X0 ** 2)'], {'axis': '(1, 2)', 'keepdims': '(True)'}), '(X0 ** 2, axis=(1, 2), keepdims=True)\n', (3018, 3055), True, 'import numpy as np\n'), ((3077, 3120), 'numpy.sum', 'np.sum', (['(Y0 ** 2)'], {'axis': '(1, 2)', 'keepdims': '(True)'}), '(Y0 ** 2, axis=(1, 2), keepdims=True)\n', (3083, 3120), True, 'import numpy as np\n'), ((3506, 3538), 'numpy.sum', 'np.sum', (['s'], {'axis': '(1)', 'keepdims': '(True)'}), '(s, axis=1, keepdims=True)\n', (3512, 3538), True, 'import numpy as np\n'), ((3346, 3362), 'numpy.linalg.det', 'np.linalg.det', (['R'], {}), '(R)\n', (3359, 3362), True, 'import numpy as np\n'), ((3594, 3611), 'numpy.matmul', 'np.matmul', (['muY', 'R'], {}), '(muY, R)\n', (3603, 3611), True, 'import numpy as np\n'), ((3641, 3664), 'numpy.matmul', 'np.matmul', (['predicted', 'R'], {}), '(predicted, R)\n', (3650, 3664), True, 'import numpy as np\n'), ((2399, 2412), 'numpy.mean', 'np.mean', (['dist'], {}), '(dist)\n', (2406, 2412), True, 'import numpy as np\n'), ((2705, 2718), 'numpy.mean', 'np.mean', (['dist'], {}), '(dist)\n', (2712, 2718), True, 'import numpy as np\n'), ((1347, 1363), 'torch.mean', 'torch.mean', (['dist'], {}), '(dist)\n', (1357, 1363), False, 'import torch\n'), ((1700, 1719), 'torch.mean', 'torch.mean', (['dist[i]'], {}), '(dist[i])\n', (1710, 1719), False, 'import torch\n'), ((4831, 4871), 'torch.autograd.Variable', 'Variable', (['target[i]'], {'requires_grad': '(False)'}), '(target[i], requires_grad=False)\n', (4839, 4871), False, 'from torch.autograd import Variable\n'), ((5001, 5020), 'torch.autograd.Variable', 'Variable', (['target[i]'], {}), '(target[i])\n', (5009, 5020), False, 'from torch.autograd import Variable\n')]
# should re-write compiled functions to take a local and global dict # as input. from __future__ import absolute_import, print_function import sys import os from . import ext_tools from . import catalog from . import common_info from numpy.core.multiarray import _get_ndarray_c_version ndarray_api_version = '/* NDARRAY API VERSION %x */' % (_get_ndarray_c_version(),) # not an easy way for the user_path_list to come in here. # the PYTHONCOMPILED environment variable offers the most hope. function_catalog = catalog.catalog() class inline_ext_function(ext_tools.ext_function): # Some specialization is needed for inline extension functions def function_declaration_code(self): code = 'static PyObject* %s(PyObject*self, PyObject* args)\n{\n' return code % self.name def template_declaration_code(self): code = 'template<class T>\n' \ 'static PyObject* %s(PyObject*self, PyObject* args)\n{\n' return code % self.name def parse_tuple_code(self): """ Create code block for PyArg_ParseTuple. Variable declarations for all PyObjects are done also. This code got a lot uglier when I added local_dict... """ declare_return = 'py::object return_val;\n' \ 'int exception_occurred = 0;\n' \ 'PyObject *py__locals = NULL;\n' \ 'PyObject *py__globals = NULL;\n' py_objects = ', '.join(self.arg_specs.py_pointers()) if py_objects: declare_py_objects = 'PyObject ' + py_objects + ';\n' else: declare_py_objects = '' py_vars = ' = '.join(self.arg_specs.py_variables()) if py_vars: init_values = py_vars + ' = NULL;\n\n' else: init_values = '' parse_tuple = 'if(!PyArg_ParseTuple(args,"OO:compiled_func",'\ '&py__locals,'\ '&py__globals))\n'\ ' return NULL;\n' return declare_return + declare_py_objects + \ init_values + parse_tuple def arg_declaration_code(self): """Return the declaration code as a string.""" arg_strings = [arg.declaration_code(inline=1) for arg in self.arg_specs] return "".join(arg_strings) def arg_cleanup_code(self): """Return the cleanup code as a string.""" arg_strings = [arg.cleanup_code() for arg in self.arg_specs] return "".join(arg_strings) def arg_local_dict_code(self): """Return the code to create the local dict as a string.""" arg_strings = [arg.local_dict_code() for arg in self.arg_specs] return "".join(arg_strings) def function_code(self): from .ext_tools import indent decl_code = indent(self.arg_declaration_code(),4) cleanup_code = indent(self.arg_cleanup_code(),4) function_code = indent(self.code_block,4) # local_dict_code = indent(self.arg_local_dict_code(),4) try_code = \ ' try \n' \ ' { \n' \ '#if defined(__GNUC__) || defined(__ICC)\n' \ ' PyObject* raw_locals __attribute__ ((unused));\n' \ ' PyObject* raw_globals __attribute__ ((unused));\n' \ '#else\n' \ ' PyObject* raw_locals;\n' \ ' PyObject* raw_globals;\n' \ '#endif\n' \ ' raw_locals = py_to_raw_dict(py__locals,"_locals");\n' \ ' raw_globals = py_to_raw_dict(py__globals,"_globals");\n' \ ' /* argument conversion code */ \n' \ + decl_code + \ ' /* inline code */ \n' \ + function_code + \ ' /*I would like to fill in changed locals and globals here...*/ \n' \ ' }\n' catch_code = "catch(...) \n" \ "{ \n" + \ " return_val = py::object(); \n" \ " exception_occurred = 1; \n" \ "} \n" return_code = " /* cleanup code */ \n" + \ cleanup_code + \ " if(!(PyObject*)return_val && !exception_occurred)\n" \ " {\n \n" \ " return_val = Py_None; \n" \ " }\n \n" \ " return return_val.disown(); \n" \ "} \n" all_code = self.function_declaration_code() + \ indent(self.parse_tuple_code(),4) + \ try_code + \ indent(catch_code,4) + \ return_code return all_code def python_function_definition_code(self): args = (self.name, self.name) function_decls = '{"%s",(PyCFunction)%s , METH_VARARGS},\n' % args return function_decls class inline_ext_module(ext_tools.ext_module): def __init__(self,name,compiler=''): ext_tools.ext_module.__init__(self,name,compiler) self._build_information.append(common_info.inline_info()) function_cache = {} def inline(code,arg_names=[],local_dict=None, global_dict=None, force=0, compiler='', verbose=0, support_code=None, headers=[], customize=None, type_converters=None, auto_downcast=1, newarr_converter=0, **kw): """ Inline C/C++ code within Python scripts. ``inline()`` compiles and executes C/C++ code on the fly. Variables in the local and global Python scope are also available in the C/C++ code. Values are passed to the C/C++ code by assignment much like variables passed are passed into a standard Python function. Values are returned from the C/C++ code through a special argument called return_val. Also, the contents of mutable objects can be changed within the C/C++ code and the changes remain after the C code exits and returns to Python. inline has quite a few options as listed below. Also, the keyword arguments for distutils extension modules are accepted to specify extra information needed for compiling. Parameters ---------- code : string A string of valid C++ code. It should not specify a return statement. Instead it should assign results that need to be returned to Python in the `return_val`. arg_names : [str], optional A list of Python variable names that should be transferred from Python into the C/C++ code. It defaults to an empty string. local_dict : dict, optional If specified, it is a dictionary of values that should be used as the local scope for the C/C++ code. If local_dict is not specified the local dictionary of the calling function is used. global_dict : dict, optional If specified, it is a dictionary of values that should be used as the global scope for the C/C++ code. If `global_dict` is not specified, the global dictionary of the calling function is used. force : {0, 1}, optional If 1, the C++ code is compiled every time inline is called. This is really only useful for debugging, and probably only useful if your editing `support_code` a lot. compiler : str, optional The name of compiler to use when compiling. On windows, it understands 'msvc' and 'gcc' as well as all the compiler names understood by distutils. On Unix, it'll only understand the values understood by distutils. (I should add 'gcc' though to this). On windows, the compiler defaults to the Microsoft C++ compiler. If this isn't available, it looks for mingw32 (the gcc compiler). On Unix, it'll probably use the same compiler that was used when compiling Python. Cygwin's behavior should be similar. verbose : {0,1,2}, optional Specifies how much information is printed during the compile phase of inlining code. 0 is silent (except on windows with msvc where it still prints some garbage). 1 informs you when compiling starts, finishes, and how long it took. 2 prints out the command lines for the compilation process and can be useful if your having problems getting code to work. Its handy for finding the name of the .cpp file if you need to examine it. verbose has no effect if the compilation isn't necessary. support_code : str, optional A string of valid C++ code declaring extra code that might be needed by your compiled function. This could be declarations of functions, classes, or structures. headers : [str], optional A list of strings specifying header files to use when compiling the code. The list might look like ``["<vector>","'my_header'"]``. Note that the header strings need to be in a form than can be pasted at the end of a ``#include`` statement in the C++ code. customize : base_info.custom_info, optional An alternative way to specify `support_code`, `headers`, etc. needed by the function. See :mod:`scipy.weave.base_info` for more details. (not sure this'll be used much). type_converters : [type converters], optional These guys are what convert Python data types to C/C++ data types. If you'd like to use a different set of type conversions than the default, specify them here. Look in the type conversions section of the main documentation for examples. auto_downcast : {1,0}, optional This only affects functions that have numpy arrays as input variables. Setting this to 1 will cause all floating point values to be cast as float instead of double if all the Numeric arrays are of type float. If even one of the arrays has type double or double complex, all variables maintain their standard types. newarr_converter : int, optional Unused. Other Parameters ---------------- Relevant :mod:`distutils` keywords. These are duplicated from <NAME>'s :class:`distutils.extension.Extension` class for convenience: sources : [string] List of source filenames, relative to the distribution root (where the setup script lives), in Unix form (slash-separated) for portability. Source files may be C, C++, SWIG (.i), platform-specific resource files, or whatever else is recognized by the "build_ext" command as source for a Python extension. .. note:: The `module_path` file is always appended to the front of this list include_dirs : [string] List of directories to search for C/C++ header files (in Unix form for portability). define_macros : [(name : string, value : string|None)] List of macros to define; each macro is defined using a 2-tuple, where 'value' is either the string to define it to or None to define it without a particular value (equivalent of "#define FOO" in source or -DFOO on Unix C compiler command line). undef_macros : [string] List of macros to undefine explicitly. library_dirs : [string] List of directories to search for C/C++ libraries at link time. libraries : [string] List of library names (not filenames or paths) to link against. runtime_library_dirs : [string] List of directories to search for C/C++ libraries at run time (for shared extensions, this is when the extension is loaded). extra_objects : [string] List of extra files to link with (e.g. object files not implied by 'sources', static libraries that must be explicitly specified, binary resource files, etc.) extra_compile_args : [string] Any extra platform- and compiler-specific information to use when compiling the source files in 'sources'. For platforms and compilers where "command line" makes sense, this is typically a list of command-line arguments, but for other platforms it could be anything. extra_link_args : [string] Any extra platform- and compiler-specific information to use when linking object files together to create the extension (or to create a new static Python interpreter). Similar interpretation as for 'extra_compile_args'. export_symbols : [string] List of symbols to be exported from a shared extension. Not used on all platforms, and not generally necessary for Python extensions, which typically export exactly one symbol: "init" + extension_name. swig_opts : [string] Any extra options to pass to SWIG if a source file has the .i extension. depends : [string] List of files that the extension depends on. language : string Extension language (i.e. "c", "c++", "objc"). Will be detected from the source extensions if not provided. See Also -------- distutils.extension.Extension : Describes additional parameters. """ # this grabs the local variables from the *previous* call # frame -- that is the locals from the function that called # inline. global function_catalog call_frame = sys._getframe().f_back if local_dict is None: local_dict = call_frame.f_locals if global_dict is None: global_dict = call_frame.f_globals if force: module_dir = global_dict.get('__file__',None) func = compile_function(code,arg_names,local_dict, global_dict,module_dir, compiler=compiler, verbose=verbose, support_code=support_code, headers=headers, customize=customize, type_converters=type_converters, auto_downcast=auto_downcast, **kw) function_catalog.add_function(code,func,module_dir) results = attempt_function_call(code,local_dict,global_dict) else: # 1. try local cache try: results = apply(function_cache[code],(local_dict,global_dict)) return results except TypeError as msg: msg = str(msg).strip() if msg[:16] == "Conversion Error": pass else: raise TypeError(msg) except NameError as msg: msg = str(msg).strip() if msg[:16] == "Conversion Error": pass else: raise NameError(msg) except KeyError: pass # 2. try function catalog try: results = attempt_function_call(code,local_dict,global_dict) # 3. build the function except ValueError: # compile the library module_dir = global_dict.get('__file__',None) func = compile_function(code,arg_names,local_dict, global_dict,module_dir, compiler=compiler, verbose=verbose, support_code=support_code, headers=headers, customize=customize, type_converters=type_converters, auto_downcast=auto_downcast, **kw) function_catalog.add_function(code,func,module_dir) results = attempt_function_call(code,local_dict,global_dict) return results def attempt_function_call(code,local_dict,global_dict): # we try 3 levels here -- a local cache first, then the # catalog cache, and then persistent catalog. # global function_catalog # 1. try local cache try: results = apply(function_cache[code],(local_dict,global_dict)) return results except TypeError as msg: msg = str(msg).strip() if msg[:16] == "Conversion Error": pass else: raise TypeError(msg) except NameError as msg: msg = str(msg).strip() if msg[:16] == "Conversion Error": pass else: raise NameError(msg) except KeyError: pass # 2. try catalog cache. function_list = function_catalog.get_functions_fast(code) for func in function_list: try: results = apply(func,(local_dict,global_dict)) function_catalog.fast_cache(code,func) function_cache[code] = func return results except TypeError as msg: # should specify argument types here. # This should really have its own error type, instead of # checking the beginning of the message, but I don't know # how to define that yet. msg = str(msg) if msg[:16] == "Conversion Error": pass else: raise TypeError(msg) except NameError as msg: msg = str(msg).strip() if msg[:16] == "Conversion Error": pass else: raise NameError(msg) # 3. try persistent catalog module_dir = global_dict.get('__file__',None) function_list = function_catalog.get_functions(code,module_dir) for func in function_list: try: results = apply(func,(local_dict,global_dict)) function_catalog.fast_cache(code,func) function_cache[code] = func return results except: # should specify argument types here. pass # if we get here, the function wasn't found raise ValueError('function with correct signature not found') def inline_function_code(code,arg_names,local_dict=None, global_dict=None,auto_downcast=1, type_converters=None,compiler=''): call_frame = sys._getframe().f_back if local_dict is None: local_dict = call_frame.f_locals if global_dict is None: global_dict = call_frame.f_globals ext_func = inline_ext_function('compiled_func',code,arg_names, local_dict,global_dict,auto_downcast, type_converters=type_converters) from . import build_tools compiler = build_tools.choose_compiler(compiler) ext_func.set_compiler(compiler) return ext_func.function_code() def compile_function(code,arg_names,local_dict,global_dict, module_dir, compiler='', verbose=1, support_code=None, headers=[], customize=None, type_converters=None, auto_downcast=1, **kw): # figure out where to store and what to name the extension module # that will contain the function. # storage_dir = catalog.intermediate_dir() code = ndarray_api_version + '\n' + code module_path = function_catalog.unique_module_name(code, module_dir) storage_dir, module_name = os.path.split(module_path) mod = inline_ext_module(module_name,compiler) # create the function. This relies on the auto_downcast and # type factories setting ext_func = inline_ext_function('compiled_func',code,arg_names, local_dict,global_dict,auto_downcast, type_converters=type_converters) mod.add_function(ext_func) # if customize (a custom_info object), then set the module customization. if customize: mod.customize = customize # add the extra "support code" needed by the function to the module. if support_code: mod.customize.add_support_code(support_code) # add the extra headers needed by the function to the module. for header in headers: mod.customize.add_header(header) # it's nice to let the users know when anything gets compiled, as the # slowdown is very noticeable. if verbose > 0: print('<weave: compiling>') # compile code in correct location, with the given compiler and verbosity # setting. All input keywords are passed through to distutils mod.compile(location=storage_dir,compiler=compiler, verbose=verbose, **kw) # import the module and return the function. Make sure # the directory where it lives is in the python path. try: sys.path.insert(0,storage_dir) exec('import ' + module_name) func = eval(module_name+'.compiled_func') finally: del sys.path[0] return func
[ "numpy.core.multiarray._get_ndarray_c_version", "sys.path.insert", "sys._getframe", "os.path.split" ]
[((19930, 19956), 'os.path.split', 'os.path.split', (['module_path'], {}), '(module_path)\n', (19943, 19956), False, 'import os\n'), ((344, 368), 'numpy.core.multiarray._get_ndarray_c_version', '_get_ndarray_c_version', ([], {}), '()\n', (366, 368), False, 'from numpy.core.multiarray import _get_ndarray_c_version\n'), ((13885, 13900), 'sys._getframe', 'sys._getframe', ([], {}), '()\n', (13898, 13900), False, 'import sys\n'), ((18722, 18737), 'sys._getframe', 'sys._getframe', ([], {}), '()\n', (18735, 18737), False, 'import sys\n'), ((21298, 21329), 'sys.path.insert', 'sys.path.insert', (['(0)', 'storage_dir'], {}), '(0, storage_dir)\n', (21313, 21329), False, 'import sys\n')]
#!/usr/bin/env python # -*- coding: utf-8 -*- """A module containing an algorithm for hand gesture recognition""" import numpy as np import cv2 from typing import Tuple __author__ = "<NAME>" __license__ = "GNU GPL 3.0 or later" def recognize(img_gray): """Recognizes hand gesture in a single-channel depth image This method estimates the number of extended fingers based on a single-channel depth image showing a hand and arm region. :param img_gray: single-channel depth image :returns: (num_fingers, img_draw) The estimated number of extended fingers and an annotated RGB image """ # segment arm region segment = segment_arm(img_gray) # find the hull of the segmented area, and based on that find the # convexity defects (contour, defects) = find_hull_defects(segment) # detect the number of fingers depending on the contours and convexity # defects, then draw defects that belong to fingers green, others red img_draw = cv2.cvtColor(segment, cv2.COLOR_GRAY2RGB) (num_fingers, img_draw) = detect_num_fingers(contour, defects, img_draw) return (num_fingers, img_draw) def segment_arm(frame: np.ndarray, abs_depth_dev: int = 14) -> np.ndarray: """Segments arm region This method accepts a single-channel depth image of an arm and hand region and extracts the segmented arm region. It is assumed that the hand is placed in the center of the image. :param frame: single-channel depth image :returns: binary image (mask) of segmented arm region, where arm=255, else=0 """ height, width = frame.shape # find center (21x21 pixel) region of imageheight frame center_half = 10 # half-width of 21 is 21/2-1 center = frame[height // 2 - center_half:height // 2 + center_half, width // 2 - center_half:width // 2 + center_half] # find median depth value of center region med_val = np.median(center) # try this instead: frame = np.where(abs(frame - med_val) <= abs_depth_dev, 128, 0).astype(np.uint8) # morphological kernel = np.ones((3, 3), np.uint8) frame = cv2.morphologyEx(frame, cv2.MORPH_CLOSE, kernel) # connected component small_kernel = 3 frame[height // 2 - small_kernel:height // 2 + small_kernel, width // 2 - small_kernel:width // 2 + small_kernel] = 128 mask = np.zeros((height + 2, width + 2), np.uint8) flood = frame.copy() cv2.floodFill(flood, mask, (width // 2, height // 2), 255, flags=4 | (255 << 8)) ret, flooded = cv2.threshold(flood, 129, 255, cv2.THRESH_BINARY) return flooded def find_hull_defects(segment: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: """Find hull defects This method finds all defects in the hull of a segmented arm region. :param segment: a binary image (mask) of a segmented arm region, where arm=255, else=0 :returns: (max_contour, defects) the largest contour in the image and all corresponding defects """ contours, hierarchy = cv2.findContours(segment, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # find largest area contour max_contour = max(contours, key=cv2.contourArea) epsilon = 0.01 * cv2.arcLength(max_contour, True) max_contour = cv2.approxPolyDP(max_contour, epsilon, True) # find convexity hull and defects hull = cv2.convexHull(max_contour, returnPoints=False) defects = cv2.convexityDefects(max_contour, hull) return max_contour, defects def detect_num_fingers(contour: np.ndarray, defects: np.ndarray, img_draw: np.ndarray, thresh_deg: float = 80.0) -> Tuple[int, np.ndarray]: """Detects the number of extended fingers This method determines the number of extended fingers based on a contour and convexity defects. It will annotate an RGB color image of the segmented arm region with all relevant defect points and the hull. :param contours: a list of contours :param defects: a list of convexity defects :param img_draw: an RGB color image to be annotated :returns: (num_fingers, img_draw) the estimated number of extended fingers and an annotated RGB color image """ # if there are no convexity defects, possibly no hull found or no # fingers extended if defects is None: return [0, img_draw] # we assume the wrist will generate two convexity defects (one on each # side), so if there are no additional defect points, there are no # fingers extended if len(defects) <= 2: return [0, img_draw] # if there is a sufficient amount of convexity defects, we will find a # defect point between two fingers so to get the number of fingers, # start counting at 1 num_fingers = 1 # Defects are of shape (num_defects,1,4) for defect in defects[:, 0, :]: # Each defect is an array of four integers. # First three indexes of start, end and the furthest # points respectively # contour is of shape (num_points,1,2) - 2 for point coordinates start, end, far = [contour[i][0] for i in defect[:3]] # draw the hull cv2.line(img_draw, tuple(start), tuple(end), (0, 255, 0), 2) # if angle is below a threshold, defect point belongs to two # extended fingers if angle_rad(start - far, end - far) < deg2rad(thresh_deg): # increment number of fingers num_fingers += 1 # draw point as green cv2.circle(img_draw, tuple(far), 5, (0, 255, 0), -1) else: # draw point as red cv2.circle(img_draw, tuple(far), 5, (0, 0, 255), -1) # make sure we cap the number of fingers return min(5, num_fingers), img_draw def angle_rad(v1, v2): """Angle in radians between two vectors This method returns the angle (in radians) between two array-like vectors using the cross-product method, which is more accurate for small angles than the dot-product-acos method. """ return np.arctan2(np.linalg.norm(np.cross(v1, v2)), np.dot(v1, v2)) def deg2rad(angle_deg): """Convert degrees to radians This method converts an angle in radians e[0,2*np.pi) into degrees e[0,360) """ return angle_deg / 180.0 * np.pi
[ "cv2.convexHull", "numpy.median", "numpy.ones", "numpy.cross", "cv2.threshold", "cv2.arcLength", "cv2.floodFill", "cv2.convexityDefects", "cv2.morphologyEx", "numpy.zeros", "numpy.dot", "cv2.approxPolyDP", "cv2.cvtColor", "cv2.findContours" ]
[((1022, 1063), 'cv2.cvtColor', 'cv2.cvtColor', (['segment', 'cv2.COLOR_GRAY2RGB'], {}), '(segment, cv2.COLOR_GRAY2RGB)\n', (1034, 1063), False, 'import cv2\n'), ((2042, 2059), 'numpy.median', 'np.median', (['center'], {}), '(center)\n', (2051, 2059), True, 'import numpy as np\n'), ((2225, 2250), 'numpy.ones', 'np.ones', (['(3, 3)', 'np.uint8'], {}), '((3, 3), np.uint8)\n', (2232, 2250), True, 'import numpy as np\n'), ((2263, 2311), 'cv2.morphologyEx', 'cv2.morphologyEx', (['frame', 'cv2.MORPH_CLOSE', 'kernel'], {}), '(frame, cv2.MORPH_CLOSE, kernel)\n', (2279, 2311), False, 'import cv2\n'), ((2506, 2549), 'numpy.zeros', 'np.zeros', (['(height + 2, width + 2)', 'np.uint8'], {}), '((height + 2, width + 2), np.uint8)\n', (2514, 2549), True, 'import numpy as np\n'), ((2579, 2657), 'cv2.floodFill', 'cv2.floodFill', (['flood', 'mask', '(width // 2, height // 2)', '(255)'], {'flags': '(4 | 255 << 8)'}), '(flood, mask, (width // 2, height // 2), 255, flags=4 | 255 << 8)\n', (2592, 2657), False, 'import cv2\n'), ((2698, 2747), 'cv2.threshold', 'cv2.threshold', (['flood', '(129)', '(255)', 'cv2.THRESH_BINARY'], {}), '(flood, 129, 255, cv2.THRESH_BINARY)\n', (2711, 2747), False, 'import cv2\n'), ((3232, 3297), 'cv2.findContours', 'cv2.findContours', (['segment', 'cv2.RETR_TREE', 'cv2.CHAIN_APPROX_SIMPLE'], {}), '(segment, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n', (3248, 3297), False, 'import cv2\n'), ((3499, 3543), 'cv2.approxPolyDP', 'cv2.approxPolyDP', (['max_contour', 'epsilon', '(True)'], {}), '(max_contour, epsilon, True)\n', (3515, 3543), False, 'import cv2\n'), ((3594, 3641), 'cv2.convexHull', 'cv2.convexHull', (['max_contour'], {'returnPoints': '(False)'}), '(max_contour, returnPoints=False)\n', (3608, 3641), False, 'import cv2\n'), ((3656, 3695), 'cv2.convexityDefects', 'cv2.convexityDefects', (['max_contour', 'hull'], {}), '(max_contour, hull)\n', (3676, 3695), False, 'import cv2\n'), ((3448, 3480), 'cv2.arcLength', 'cv2.arcLength', (['max_contour', '(True)'], {}), '(max_contour, True)\n', (3461, 3480), False, 'import cv2\n'), ((6368, 6382), 'numpy.dot', 'np.dot', (['v1', 'v2'], {}), '(v1, v2)\n', (6374, 6382), True, 'import numpy as np\n'), ((6349, 6365), 'numpy.cross', 'np.cross', (['v1', 'v2'], {}), '(v1, v2)\n', (6357, 6365), True, 'import numpy as np\n')]
from typing import Callable import numpy as np from hmc.integrators.states.leapfrog_state import LeapfrogState from hmc.integrators.fields import riemannian from hmc.linalg import solve_psd class RiemannianLeapfrogState(LeapfrogState): """The Riemannian leapfrog state uses the Fisher information matrix to provide a position-dependent Riemannian metric. As such, computing the gradients of the Hamiltonian requires higher derivatives of the metric, which vanish in the Euclidean case. """ def __init__(self, position: np.ndarray, momentum: np.ndarray): super().__init__(position, momentum) self._jac_metric: np.ndarray self._grad_logdet_metric: np.ndarray @property def requires_update(self) -> bool: o = self.log_posterior is None or \ self.grad_log_posterior is None or \ self.metric is None or \ self.inv_metric is None or \ self.jac_metric is None or \ self.grad_logdet_metric is None return o @property def jac_metric(self): return self._jac_metric @jac_metric.setter def jac_metric(self, value): self._jac_metric = value @jac_metric.deleter def jac_metric(self): del self._jac_metric @property def grad_logdet_metric(self): return self._grad_logdet_metric @grad_logdet_metric.setter def grad_logdet_metric(self, value): self._grad_logdet_metric = value @grad_logdet_metric.deleter def grad_logdet_metric(self): del self._grad_logdet_metric def update(self, auxiliaries: Callable): num_dims = len(self.position) log_posterior, grad_log_posterior, metric, jac_metric = auxiliaries(self.position) jac_metric = np.swapaxes(jac_metric, 0, -1) inv_metric, sqrtm_metric = solve_psd(metric, return_chol=True) grad_logdet_metric = riemannian.grad_logdet(inv_metric, jac_metric, num_dims) self.log_posterior = log_posterior self.grad_log_posterior = grad_log_posterior self.metric = metric self.sqrtm_metric = sqrtm_metric self.inv_metric = inv_metric self.jac_metric = jac_metric self.grad_logdet_metric = grad_logdet_metric self.velocity = riemannian.velocity(inv_metric, self.momentum) self.force = riemannian.force(self.velocity, grad_log_posterior, jac_metric, grad_logdet_metric) def clear(self): super().clear() del self.jac_metric del self.grad_logdet_metric del self.metric del self.inv_metric del self.logdet_metric del self.sqrtm_metric
[ "hmc.integrators.fields.riemannian.velocity", "hmc.integrators.fields.riemannian.grad_logdet", "hmc.integrators.fields.riemannian.force", "numpy.swapaxes", "hmc.linalg.solve_psd" ]
[((1817, 1847), 'numpy.swapaxes', 'np.swapaxes', (['jac_metric', '(0)', '(-1)'], {}), '(jac_metric, 0, -1)\n', (1828, 1847), True, 'import numpy as np\n'), ((1883, 1918), 'hmc.linalg.solve_psd', 'solve_psd', (['metric'], {'return_chol': '(True)'}), '(metric, return_chol=True)\n', (1892, 1918), False, 'from hmc.linalg import solve_psd\n'), ((1948, 2004), 'hmc.integrators.fields.riemannian.grad_logdet', 'riemannian.grad_logdet', (['inv_metric', 'jac_metric', 'num_dims'], {}), '(inv_metric, jac_metric, num_dims)\n', (1970, 2004), False, 'from hmc.integrators.fields import riemannian\n'), ((2322, 2368), 'hmc.integrators.fields.riemannian.velocity', 'riemannian.velocity', (['inv_metric', 'self.momentum'], {}), '(inv_metric, self.momentum)\n', (2341, 2368), False, 'from hmc.integrators.fields import riemannian\n'), ((2390, 2477), 'hmc.integrators.fields.riemannian.force', 'riemannian.force', (['self.velocity', 'grad_log_posterior', 'jac_metric', 'grad_logdet_metric'], {}), '(self.velocity, grad_log_posterior, jac_metric,\n grad_logdet_metric)\n', (2406, 2477), False, 'from hmc.integrators.fields import riemannian\n')]
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Affine Scalar Tests.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.contrib.distributions.python.ops.bijectors.affine_scalar import AffineScalar from tensorflow.python.framework import dtypes from tensorflow.python.ops import array_ops from tensorflow.python.ops.distributions.bijector_test_util import assert_scalar_congruency from tensorflow.python.platform import test class AffineScalarBijectorTest(test.TestCase): """Tests correctness of the Y = scale @ x + shift transformation.""" def testProperties(self): with self.test_session(): mu = -1. # scale corresponds to 1. bijector = AffineScalar(shift=mu) self.assertEqual("affine_scalar", bijector.name) def testNoBatchScalar(self): with self.test_session() as sess: def static_run(fun, x): return fun(x).eval() def dynamic_run(fun, x_value): x_value = np.array(x_value) x = array_ops.placeholder(dtypes.float32, name="x") return sess.run(fun(x), feed_dict={x: x_value}) for run in (static_run, dynamic_run): mu = -1. # Corresponds to scale = 2 bijector = AffineScalar(shift=mu, scale=2.) x = [1., 2, 3] # Three scalar samples (no batches). self.assertAllClose([1., 3, 5], run(bijector.forward, x)) self.assertAllClose([1., 1.5, 2.], run(bijector.inverse, x)) self.assertAllClose([-np.log(2.)] * 3, run(bijector.inverse_log_det_jacobian, x)) def testOneBatchScalarViaIdentityIn64BitUserProvidesShiftOnly(self): with self.test_session() as sess: def static_run(fun, x): return fun(x).eval() def dynamic_run(fun, x_value): x_value = np.array(x_value).astype(np.float64) x = array_ops.placeholder(dtypes.float64, name="x") return sess.run(fun(x), feed_dict={x: x_value}) for run in (static_run, dynamic_run): mu = np.float64([1.]) # One batch, scalar. # Corresponds to scale = 1. bijector = AffineScalar(shift=mu) x = np.float64([1.]) # One sample from one batches. self.assertAllClose([2.], run(bijector.forward, x)) self.assertAllClose([0.], run(bijector.inverse, x)) self.assertAllClose([0.], run(bijector.inverse_log_det_jacobian, x)) def testOneBatchScalarViaIdentityIn64BitUserProvidesScaleOnly(self): with self.test_session() as sess: def static_run(fun, x): return fun(x).eval() def dynamic_run(fun, x_value): x_value = np.array(x_value).astype(np.float64) x = array_ops.placeholder(dtypes.float64, name="x") return sess.run(fun(x), feed_dict={x: x_value}) for run in (static_run, dynamic_run): multiplier = np.float64([2.]) # One batch, scalar. # Corresponds to scale = 2, shift = 0. bijector = AffineScalar(scale=multiplier) x = np.float64([1.]) # One sample from one batches. self.assertAllClose([2.], run(bijector.forward, x)) self.assertAllClose([0.5], run(bijector.inverse, x)) self.assertAllClose([np.log(0.5)], run(bijector.inverse_log_det_jacobian, x)) def testTwoBatchScalarIdentityViaIdentity(self): with self.test_session() as sess: def static_run(fun, x): return fun(x).eval() def dynamic_run(fun, x_value): x_value = np.array(x_value) x = array_ops.placeholder(dtypes.float32, name="x") return sess.run(fun(x), feed_dict={x: x_value}) for run in (static_run, dynamic_run): mu = [1., -1] # Univariate, two batches. # Corresponds to scale = 1. bijector = AffineScalar(shift=mu) x = [1., 1] # One sample from each of two batches. self.assertAllClose([2., 0], run(bijector.forward, x)) self.assertAllClose([0., 2], run(bijector.inverse, x)) self.assertAllClose([0., 0.], run(bijector.inverse_log_det_jacobian, x)) def testTwoBatchScalarIdentityViaScale(self): with self.test_session() as sess: def static_run(fun, x): return fun(x).eval() def dynamic_run(fun, x_value): x_value = np.array(x_value) x = array_ops.placeholder(dtypes.float32, name="x") return sess.run(fun(x), feed_dict={x: x_value}) for run in (static_run, dynamic_run): mu = [1., -1] # Univariate, two batches. # Corresponds to scale = 1. bijector = AffineScalar(shift=mu, scale=[2., 1]) x = [1., 1] # One sample from each of two batches. self.assertAllClose([3., 0], run(bijector.forward, x)) self.assertAllClose([0., 2], run(bijector.inverse, x)) self.assertAllClose( [-np.log(2), 0.], run(bijector.inverse_log_det_jacobian, x)) def testScalarCongruency(self): with self.test_session(): bijector = AffineScalar(shift=3.6, scale=0.42) assert_scalar_congruency(bijector, lower_x=-2., upper_x=2.) if __name__ == "__main__": test.main()
[ "tensorflow.python.ops.array_ops.placeholder", "tensorflow.python.ops.distributions.bijector_test_util.assert_scalar_congruency", "numpy.float64", "tensorflow.contrib.distributions.python.ops.bijectors.affine_scalar.AffineScalar", "numpy.log", "numpy.array", "tensorflow.python.platform.test.main" ]
[((5795, 5806), 'tensorflow.python.platform.test.main', 'test.main', ([], {}), '()\n', (5804, 5806), False, 'from tensorflow.python.platform import test\n'), ((1410, 1432), 'tensorflow.contrib.distributions.python.ops.bijectors.affine_scalar.AffineScalar', 'AffineScalar', ([], {'shift': 'mu'}), '(shift=mu)\n', (1422, 1432), False, 'from tensorflow.contrib.distributions.python.ops.bijectors.affine_scalar import AffineScalar\n'), ((5663, 5698), 'tensorflow.contrib.distributions.python.ops.bijectors.affine_scalar.AffineScalar', 'AffineScalar', ([], {'shift': '(3.6)', 'scale': '(0.42)'}), '(shift=3.6, scale=0.42)\n', (5675, 5698), False, 'from tensorflow.contrib.distributions.python.ops.bijectors.affine_scalar import AffineScalar\n'), ((5705, 5766), 'tensorflow.python.ops.distributions.bijector_test_util.assert_scalar_congruency', 'assert_scalar_congruency', (['bijector'], {'lower_x': '(-2.0)', 'upper_x': '(2.0)'}), '(bijector, lower_x=-2.0, upper_x=2.0)\n', (5729, 5766), False, 'from tensorflow.python.ops.distributions.bijector_test_util import assert_scalar_congruency\n'), ((1674, 1691), 'numpy.array', 'np.array', (['x_value'], {}), '(x_value)\n', (1682, 1691), True, 'import numpy as np\n'), ((1704, 1751), 'tensorflow.python.ops.array_ops.placeholder', 'array_ops.placeholder', (['dtypes.float32'], {'name': '"""x"""'}), "(dtypes.float32, name='x')\n", (1725, 1751), False, 'from tensorflow.python.ops import array_ops\n'), ((1924, 1957), 'tensorflow.contrib.distributions.python.ops.bijectors.affine_scalar.AffineScalar', 'AffineScalar', ([], {'shift': 'mu', 'scale': '(2.0)'}), '(shift=mu, scale=2.0)\n', (1936, 1957), False, 'from tensorflow.contrib.distributions.python.ops.bijectors.affine_scalar import AffineScalar\n'), ((2546, 2593), 'tensorflow.python.ops.array_ops.placeholder', 'array_ops.placeholder', (['dtypes.float64'], {'name': '"""x"""'}), "(dtypes.float64, name='x')\n", (2567, 2593), False, 'from tensorflow.python.ops import array_ops\n'), ((2708, 2725), 'numpy.float64', 'np.float64', (['[1.0]'], {}), '([1.0])\n', (2718, 2725), True, 'import numpy as np\n'), ((2809, 2831), 'tensorflow.contrib.distributions.python.ops.bijectors.affine_scalar.AffineScalar', 'AffineScalar', ([], {'shift': 'mu'}), '(shift=mu)\n', (2821, 2831), False, 'from tensorflow.contrib.distributions.python.ops.bijectors.affine_scalar import AffineScalar\n'), ((2844, 2861), 'numpy.float64', 'np.float64', (['[1.0]'], {}), '([1.0])\n', (2854, 2861), True, 'import numpy as np\n'), ((3365, 3412), 'tensorflow.python.ops.array_ops.placeholder', 'array_ops.placeholder', (['dtypes.float64'], {'name': '"""x"""'}), "(dtypes.float64, name='x')\n", (3386, 3412), False, 'from tensorflow.python.ops import array_ops\n'), ((3535, 3552), 'numpy.float64', 'np.float64', (['[2.0]'], {}), '([2.0])\n', (3545, 3552), True, 'import numpy as np\n'), ((3647, 3677), 'tensorflow.contrib.distributions.python.ops.bijectors.affine_scalar.AffineScalar', 'AffineScalar', ([], {'scale': 'multiplier'}), '(scale=multiplier)\n', (3659, 3677), False, 'from tensorflow.contrib.distributions.python.ops.bijectors.affine_scalar import AffineScalar\n'), ((3690, 3707), 'numpy.float64', 'np.float64', (['[1.0]'], {}), '([1.0])\n', (3700, 3707), True, 'import numpy as np\n'), ((4180, 4197), 'numpy.array', 'np.array', (['x_value'], {}), '(x_value)\n', (4188, 4197), True, 'import numpy as np\n'), ((4210, 4257), 'tensorflow.python.ops.array_ops.placeholder', 'array_ops.placeholder', (['dtypes.float32'], {'name': '"""x"""'}), "(dtypes.float32, name='x')\n", (4231, 4257), False, 'from tensorflow.python.ops import array_ops\n'), ((4471, 4493), 'tensorflow.contrib.distributions.python.ops.bijectors.affine_scalar.AffineScalar', 'AffineScalar', ([], {'shift': 'mu'}), '(shift=mu)\n', (4483, 4493), False, 'from tensorflow.contrib.distributions.python.ops.bijectors.affine_scalar import AffineScalar\n'), ((4964, 4981), 'numpy.array', 'np.array', (['x_value'], {}), '(x_value)\n', (4972, 4981), True, 'import numpy as np\n'), ((4994, 5041), 'tensorflow.python.ops.array_ops.placeholder', 'array_ops.placeholder', (['dtypes.float32'], {'name': '"""x"""'}), "(dtypes.float32, name='x')\n", (5015, 5041), False, 'from tensorflow.python.ops import array_ops\n'), ((5255, 5293), 'tensorflow.contrib.distributions.python.ops.bijectors.affine_scalar.AffineScalar', 'AffineScalar', ([], {'shift': 'mu', 'scale': '[2.0, 1]'}), '(shift=mu, scale=[2.0, 1])\n', (5267, 5293), False, 'from tensorflow.contrib.distributions.python.ops.bijectors.affine_scalar import AffineScalar\n'), ((2497, 2514), 'numpy.array', 'np.array', (['x_value'], {}), '(x_value)\n', (2505, 2514), True, 'import numpy as np\n'), ((3316, 3333), 'numpy.array', 'np.array', (['x_value'], {}), '(x_value)\n', (3324, 3333), True, 'import numpy as np\n'), ((3889, 3900), 'numpy.log', 'np.log', (['(0.5)'], {}), '(0.5)\n', (3895, 3900), True, 'import numpy as np\n'), ((5522, 5531), 'numpy.log', 'np.log', (['(2)'], {}), '(2)\n', (5528, 5531), True, 'import numpy as np\n'), ((2183, 2194), 'numpy.log', 'np.log', (['(2.0)'], {}), '(2.0)\n', (2189, 2194), True, 'import numpy as np\n')]
from __future__ import annotations import numpy as np import pandas as pd from sklearn import datasets from IMLearn.metrics import mean_square_error from IMLearn.utils import split_train_test from IMLearn.model_selection import cross_validate from IMLearn.learners.regressors import PolynomialFitting, LinearRegression, RidgeRegression from sklearn.linear_model import Lasso from utils import * import plotnine as gg def select_polynomial_degree(n_samples: int = 100, noise: float = 5): """ Simulate data from a polynomial model and use cross-validation to select the best fitting degree Parameters ---------- n_samples: int, default=100 Number of samples to generate noise: float, default = 5 Noise level to simulate in responses """ # Question 1 - Generate dataset for model f(x)=(x+3)(x+2)(x+1)(x-1)(x-2) + eps for eps Gaussian noise # and split into training- and testing portions def f(x): return (x + 3) * (x + 2) * (x + 1) * (x - 1) * (x - 2) X = np.linspace(-1.2, 2, n_samples) y = f(X) + np.random.normal(0, noise, n_samples) train_X, train_y, test_X, test_y = split_train_test(pd.DataFrame(X), pd.Series(y), train_proportion=(2 / 3)) df_train = pd.DataFrame({"x": train_X.squeeze(), "y": train_y, "type": "Train"}) df_test = pd.DataFrame({"x": test_X.squeeze(), "y": test_y, "type": "test"}) x_stat = np.linspace(-1.4, 2, 100) df_stat = pd.DataFrame({"x": x_stat, "y": f(x_stat), "type": "Model"}) df = pd.concat([df_test, df_train]) title = f"f(x) = (x+3)(x+2)(x+1)(x-1)(x-2) + Gaussian noise ~ N(0,{noise})" p = gg.ggplot() + \ gg.geom_point(df, gg.aes("x", "y", color="type")) + \ gg.geom_line(df_stat, gg.aes("x", "y")) + \ gg.theme_bw() + \ gg.ggtitle(title) # print(p) gg.ggsave(filename=f'../../IML/ex5/plots/{title}.png', plot=p, verbose=False) # Question 2 - Perform CV for polynomial fitting with degrees 0,1,...,10 train_err = [] validation_err = [] for k in range(11): pf = PolynomialFitting(k) train_score, validation_score = cross_validate(pf, train_X.to_numpy(), train_y.to_numpy(), mean_square_error) train_err.append(train_score) validation_err.append(validation_score) df1 = pd.DataFrame({"k": range(11), "avg error": train_err, "type": "train error"}) df2 = pd.DataFrame({"k": range(11), "avg error": validation_err, "type": "validation error"}) df = pd.concat([df1, df2]) title = f" Cross Validation for Polynomial Fitting Over Different Degrees k" p = gg.ggplot(df, gg.aes("k", "avg error", color="type")) + \ gg.geom_point() + \ gg.theme_bw() + gg.scale_x_continuous(breaks=range(11)) + \ gg.labs(y="Average training and validation errors", title=f"{title} \nWith Noise: {noise}, Num of samples: {n_samples}") gg.ggsave(filename=f'../../IML/ex5/plots/{title} {noise} {n_samples}.png', plot=p, verbose=False) # Question 3 - Using best value of k, fit a k-degree polynomial model and report test error best_k = np.argmin(np.array(validation_err)) pf = PolynomialFitting(int(best_k)) pf.fit(train_X.to_numpy(), train_y.to_numpy()) y_pred = pf.predict(test_X.to_numpy()) print("best k =", best_k) print("Test = ", round(mean_square_error(test_y.to_numpy(), y_pred), 2)) print("Validation = ", round(validation_err[best_k], 2)) def select_regularization_parameter(n_samples: int = 50, n_evaluations: int = 500): """ Using sklearn's diabetes dataset use cross-validation to select the best fitting regularization parameter values for Ridge and Lasso regressions Parameters ---------- n_samples: int, default=50 Number of samples to generate n_evaluations: int, default = 500 Number of regularization parameter values to evaluate for each of the algorithms """ # Question 6 - Load diabetes dataset and split into training and testing portions X, y = datasets.load_diabetes(return_X_y=True, as_frame=True) train_X, train_y, test_X, test_y = X.iloc[:50, :], y[:50], X.iloc[50:, ], y[50:] # Question 7 - Perform CV for different values of the regularization parameter for Ridge and Lasso regressions for name, learner, ran in [("Ridge", RidgeRegression, np.linspace(0.001, 0.05, 500)), ("Lasso", Lasso, np.linspace(0.001, 0.5, 500))]: train_err = [] validation_err = [] for lam in ran: rg = learner(lam) train_score, validation_score = cross_validate(rg, train_X.to_numpy(), train_y.to_numpy(), mean_square_error) train_err.append(train_score) validation_err.append(validation_score) df1 = pd.DataFrame({"lambda": ran, "avg error": train_err, "type": "train error"}) df2 = pd.DataFrame({"lambda": ran, "avg error": validation_err, "type": "validation error"}) df = pd.concat([df1, df2]) title = f"{name} Regularization Cross Validate Over Different Lambda" p = gg.ggplot(df, gg.aes("lambda", "avg error", color="type")) + \ gg.geom_line() + \ gg.theme_bw() + gg.labs(y="Average training and validation errors", title=title) gg.ggsave(filename=f'../../IML/ex5/plots/{title}.png', plot=p, verbose=False) # Question 8 - Compare best Ridge model, best Lasso model and Least Squares model best_lam = np.argmin(np.array(validation_err)) rg = learner(ran[best_lam]) rg.fit(train_X.to_numpy(), train_y.to_numpy()) y_pred = rg.predict(test_X.to_numpy()) print(f"best lambda {name} = {round(ran[best_lam], 3)}") print(f"Test MSE {name} = {round(mean_square_error(test_y.to_numpy(), y_pred), 2)}") lr = LinearRegression() lr.fit(train_X.to_numpy(), train_y.to_numpy()) print("Linear Regression Loss = ", lr.loss(test_X.to_numpy(), test_y.to_numpy())) if __name__ == '__main__': np.random.seed(0) select_polynomial_degree() select_polynomial_degree(noise=0) select_polynomial_degree(n_samples=1500, noise=10) select_regularization_parameter()
[ "numpy.random.normal", "pandas.Series", "plotnine.ggtitle", "plotnine.ggsave", "plotnine.ggplot", "plotnine.theme_bw", "plotnine.geom_line", "plotnine.aes", "IMLearn.learners.regressors.LinearRegression", "numpy.array", "numpy.linspace", "sklearn.datasets.load_diabetes", "numpy.random.seed", "plotnine.geom_point", "pandas.DataFrame", "plotnine.labs", "pandas.concat", "IMLearn.learners.regressors.PolynomialFitting" ]
[((1030, 1061), 'numpy.linspace', 'np.linspace', (['(-1.2)', '(2)', 'n_samples'], {}), '(-1.2, 2, n_samples)\n', (1041, 1061), True, 'import numpy as np\n'), ((1408, 1433), 'numpy.linspace', 'np.linspace', (['(-1.4)', '(2)', '(100)'], {}), '(-1.4, 2, 100)\n', (1419, 1433), True, 'import numpy as np\n'), ((1518, 1548), 'pandas.concat', 'pd.concat', (['[df_test, df_train]'], {}), '([df_test, df_train])\n', (1527, 1548), True, 'import pandas as pd\n'), ((1839, 1916), 'plotnine.ggsave', 'gg.ggsave', ([], {'filename': 'f"""../../IML/ex5/plots/{title}.png"""', 'plot': 'p', 'verbose': '(False)'}), "(filename=f'../../IML/ex5/plots/{title}.png', plot=p, verbose=False)\n", (1848, 1916), True, 'import plotnine as gg\n'), ((2496, 2517), 'pandas.concat', 'pd.concat', (['[df1, df2]'], {}), '([df1, df2])\n', (2505, 2517), True, 'import pandas as pd\n'), ((2910, 3011), 'plotnine.ggsave', 'gg.ggsave', ([], {'filename': 'f"""../../IML/ex5/plots/{title} {noise} {n_samples}.png"""', 'plot': 'p', 'verbose': '(False)'}), "(filename=f'../../IML/ex5/plots/{title} {noise} {n_samples}.png',\n plot=p, verbose=False)\n", (2919, 3011), True, 'import plotnine as gg\n'), ((4036, 4090), 'sklearn.datasets.load_diabetes', 'datasets.load_diabetes', ([], {'return_X_y': '(True)', 'as_frame': '(True)'}), '(return_X_y=True, as_frame=True)\n', (4058, 4090), False, 'from sklearn import datasets\n'), ((5883, 5901), 'IMLearn.learners.regressors.LinearRegression', 'LinearRegression', ([], {}), '()\n', (5899, 5901), False, 'from IMLearn.learners.regressors import PolynomialFitting, LinearRegression, RidgeRegression\n'), ((6072, 6089), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (6086, 6089), True, 'import numpy as np\n'), ((1077, 1114), 'numpy.random.normal', 'np.random.normal', (['(0)', 'noise', 'n_samples'], {}), '(0, noise, n_samples)\n', (1093, 1114), True, 'import numpy as np\n'), ((1171, 1186), 'pandas.DataFrame', 'pd.DataFrame', (['X'], {}), '(X)\n', (1183, 1186), True, 'import pandas as pd\n'), ((1188, 1200), 'pandas.Series', 'pd.Series', (['y'], {}), '(y)\n', (1197, 1200), True, 'import pandas as pd\n'), ((1802, 1819), 'plotnine.ggtitle', 'gg.ggtitle', (['title'], {}), '(title)\n', (1812, 1819), True, 'import plotnine as gg\n'), ((2075, 2095), 'IMLearn.learners.regressors.PolynomialFitting', 'PolynomialFitting', (['k'], {}), '(k)\n', (2092, 2095), False, 'from IMLearn.learners.regressors import PolynomialFitting, LinearRegression, RidgeRegression\n'), ((2769, 2897), 'plotnine.labs', 'gg.labs', ([], {'y': '"""Average training and validation errors"""', 'title': 'f"""{title} \nWith Noise: {noise}, Num of samples: {n_samples}"""'}), '(y=\'Average training and validation errors\', title=\n f"""{title} \nWith Noise: {noise}, Num of samples: {n_samples}""")\n', (2776, 2897), True, 'import plotnine as gg\n'), ((3128, 3152), 'numpy.array', 'np.array', (['validation_err'], {}), '(validation_err)\n', (3136, 3152), True, 'import numpy as np\n'), ((4856, 4932), 'pandas.DataFrame', 'pd.DataFrame', (["{'lambda': ran, 'avg error': train_err, 'type': 'train error'}"], {}), "({'lambda': ran, 'avg error': train_err, 'type': 'train error'})\n", (4868, 4932), True, 'import pandas as pd\n'), ((4947, 5037), 'pandas.DataFrame', 'pd.DataFrame', (["{'lambda': ran, 'avg error': validation_err, 'type': 'validation error'}"], {}), "({'lambda': ran, 'avg error': validation_err, 'type':\n 'validation error'})\n", (4959, 5037), True, 'import pandas as pd\n'), ((5047, 5068), 'pandas.concat', 'pd.concat', (['[df1, df2]'], {}), '([df1, df2])\n', (5056, 5068), True, 'import pandas as pd\n'), ((5354, 5431), 'plotnine.ggsave', 'gg.ggsave', ([], {'filename': 'f"""../../IML/ex5/plots/{title}.png"""', 'plot': 'p', 'verbose': '(False)'}), "(filename=f'../../IML/ex5/plots/{title}.png', plot=p, verbose=False)\n", (5363, 5431), True, 'import plotnine as gg\n'), ((1776, 1789), 'plotnine.theme_bw', 'gg.theme_bw', ([], {}), '()\n', (1787, 1789), True, 'import plotnine as gg\n'), ((4350, 4379), 'numpy.linspace', 'np.linspace', (['(0.001)', '(0.05)', '(500)'], {}), '(0.001, 0.05, 500)\n', (4361, 4379), True, 'import numpy as np\n'), ((4430, 4458), 'numpy.linspace', 'np.linspace', (['(0.001)', '(0.5)', '(500)'], {}), '(0.001, 0.5, 500)\n', (4441, 4458), True, 'import numpy as np\n'), ((5281, 5345), 'plotnine.labs', 'gg.labs', ([], {'y': '"""Average training and validation errors"""', 'title': 'title'}), "(y='Average training and validation errors', title=title)\n", (5288, 5345), True, 'import plotnine as gg\n'), ((5552, 5576), 'numpy.array', 'np.array', (['validation_err'], {}), '(validation_err)\n', (5560, 5576), True, 'import numpy as np\n'), ((2701, 2714), 'plotnine.theme_bw', 'gg.theme_bw', ([], {}), '()\n', (2712, 2714), True, 'import plotnine as gg\n'), ((5265, 5278), 'plotnine.theme_bw', 'gg.theme_bw', ([], {}), '()\n', (5276, 5278), True, 'import plotnine as gg\n'), ((1638, 1649), 'plotnine.ggplot', 'gg.ggplot', ([], {}), '()\n', (1647, 1649), True, 'import plotnine as gg\n'), ((1746, 1762), 'plotnine.aes', 'gg.aes', (['"""x"""', '"""y"""'], {}), "('x', 'y')\n", (1752, 1762), True, 'import plotnine as gg\n'), ((2673, 2688), 'plotnine.geom_point', 'gg.geom_point', ([], {}), '()\n', (2686, 2688), True, 'import plotnine as gg\n'), ((5234, 5248), 'plotnine.geom_line', 'gg.geom_line', ([], {}), '()\n', (5246, 5248), True, 'import plotnine as gg\n'), ((1680, 1710), 'plotnine.aes', 'gg.aes', (['"""x"""', '"""y"""'], {'color': '"""type"""'}), "('x', 'y', color='type')\n", (1686, 1710), True, 'import plotnine as gg\n'), ((2621, 2659), 'plotnine.aes', 'gg.aes', (['"""k"""', '"""avg error"""'], {'color': '"""type"""'}), "('k', 'avg error', color='type')\n", (2627, 2659), True, 'import plotnine as gg\n'), ((5173, 5216), 'plotnine.aes', 'gg.aes', (['"""lambda"""', '"""avg error"""'], {'color': '"""type"""'}), "('lambda', 'avg error', color='type')\n", (5179, 5216), True, 'import plotnine as gg\n')]
__author__ = "<NAME>" __copyright__ = "Copyright 2017, Stanford University" __license__ = "MIT" import sys from deepchem.models import KerasModel from deepchem.models.layers import AtomicConvolution from deepchem.models.losses import L2Loss from tensorflow.keras.layers import Input, Layer import numpy as np import tensorflow as tf import itertools def initializeWeightsBiases(prev_layer_size, size, weights=None, biases=None, name=None): """Initializes weights and biases to be used in a fully-connected layer. Parameters ---------- prev_layer_size: int Number of features in previous layer. size: int Number of nodes in this layer. weights: tf.Tensor, optional (Default None) Weight tensor. biases: tf.Tensor, optional (Default None) Bias tensor. name: str Name for this op, optional (Defaults to 'fully_connected' if None) Returns ------- weights: tf.Variable Initialized weights. biases: tf.Variable Initialized biases. """ if weights is None: weights = tf.random.truncated_normal([prev_layer_size, size], stddev=0.01) if biases is None: biases = tf.zeros([size]) w = tf.Variable(weights, name='w') b = tf.Variable(biases, name='b') return w, b class AtomicConvScore(Layer): """The scoring function used by the atomic convolution models.""" def __init__(self, atom_types, layer_sizes, **kwargs): super(AtomicConvScore, self).__init__(**kwargs) self.atom_types = atom_types self.layer_sizes = layer_sizes def build(self, input_shape): self.type_weights = [] self.type_biases = [] self.output_weights = [] self.output_biases = [] n_features = int(input_shape[0][-1]) layer_sizes = self.layer_sizes num_layers = len(layer_sizes) weight_init_stddevs = [1 / np.sqrt(x) for x in layer_sizes] bias_init_consts = [0.0] * num_layers for ind, atomtype in enumerate(self.atom_types): prev_layer_size = n_features self.type_weights.append([]) self.type_biases.append([]) self.output_weights.append([]) self.output_biases.append([]) for i in range(num_layers): weight, bias = initializeWeightsBiases( prev_layer_size=prev_layer_size, size=layer_sizes[i], weights=tf.random.truncated_normal( shape=[prev_layer_size, layer_sizes[i]], stddev=weight_init_stddevs[i]), biases=tf.constant( value=bias_init_consts[i], shape=[layer_sizes[i]])) self.type_weights[ind].append(weight) self.type_biases[ind].append(bias) prev_layer_size = layer_sizes[i] weight, bias = initializeWeightsBiases(prev_layer_size, 1) self.output_weights[ind].append(weight) self.output_biases[ind].append(bias) def call(self, inputs): frag1_layer, frag2_layer, complex_layer, frag1_z, frag2_z, complex_z = inputs atom_types = self.atom_types num_layers = len(self.layer_sizes) def atomnet(current_input, atomtype): prev_layer = current_input for i in range(num_layers): layer = tf.nn.bias_add( tf.matmul(prev_layer, self.type_weights[atomtype][i]), self.type_biases[atomtype][i]) layer = tf.nn.relu(layer) prev_layer = layer output_layer = tf.squeeze( tf.nn.bias_add( tf.matmul(prev_layer, self.output_weights[atomtype][0]), self.output_biases[atomtype][0])) return output_layer frag1_zeros = tf.zeros_like(frag1_z, dtype=tf.float32) frag2_zeros = tf.zeros_like(frag2_z, dtype=tf.float32) complex_zeros = tf.zeros_like(complex_z, dtype=tf.float32) frag1_atomtype_energy = [] frag2_atomtype_energy = [] complex_atomtype_energy = [] for ind, atomtype in enumerate(atom_types): frag1_outputs = tf.map_fn(lambda x: atomnet(x, ind), frag1_layer) frag2_outputs = tf.map_fn(lambda x: atomnet(x, ind), frag2_layer) complex_outputs = tf.map_fn(lambda x: atomnet(x, ind), complex_layer) cond = tf.equal(frag1_z, atomtype) frag1_atomtype_energy.append(tf.where(cond, frag1_outputs, frag1_zeros)) cond = tf.equal(frag2_z, atomtype) frag2_atomtype_energy.append(tf.where(cond, frag2_outputs, frag2_zeros)) cond = tf.equal(complex_z, atomtype) complex_atomtype_energy.append( tf.where(cond, complex_outputs, complex_zeros)) frag1_outputs = tf.add_n(frag1_atomtype_energy) frag2_outputs = tf.add_n(frag2_atomtype_energy) complex_outputs = tf.add_n(complex_atomtype_energy) frag1_energy = tf.reduce_sum(frag1_outputs, 1) frag2_energy = tf.reduce_sum(frag2_outputs, 1) complex_energy = tf.reduce_sum(complex_outputs, 1) binding_energy = complex_energy - (frag1_energy + frag2_energy) return tf.expand_dims(binding_energy, axis=1) class AtomicConvModel(KerasModel): """Implements an Atomic Convolution Model. Implements the atomic convolutional networks as introduced in <NAME> al. "Atomic convolutional networks for predicting protein-ligand binding affinity." arXiv preprint arXiv:1703.10603 (2017). The atomic convolutional networks function as a variant of graph convolutions. The difference is that the "graph" here is the nearest neighbors graph in 3D space. The AtomicConvModel leverages these connections in 3D space to train models that learn to predict energetic state starting from the spatial geometry of the model. """ def __init__(self, frag1_num_atoms=70, frag2_num_atoms=634, complex_num_atoms=701, max_num_neighbors=12, batch_size=24, atom_types=[ 6, 7., 8., 9., 11., 12., 15., 16., 17., 20., 25., 30., 35., 53., -1. ], radial=[[ 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0, 7.5, 8.0, 8.5, 9.0, 9.5, 10.0, 10.5, 11.0, 11.5, 12.0 ], [0.0, 4.0, 8.0], [0.4]], layer_sizes=[32, 32, 16], learning_rate=0.001, **kwargs): """ Parameters ---------- frag1_num_atoms: int Number of atoms in first fragment frag2_num_atoms: int Number of atoms in sec max_num_neighbors: int Maximum number of neighbors possible for an atom. Recall neighbors are spatial neighbors. atom_types: list List of atoms recognized by model. Atoms are indicated by their nuclear numbers. radial: list TODO: add description layer_sizes: list TODO: add description learning_rate: float Learning rate for the model. """ # TODO: Turning off queue for now. Safe to re-activate? self.complex_num_atoms = complex_num_atoms self.frag1_num_atoms = frag1_num_atoms self.frag2_num_atoms = frag2_num_atoms self.max_num_neighbors = max_num_neighbors self.batch_size = batch_size self.atom_types = atom_types rp = [x for x in itertools.product(*radial)] frag1_X = Input(shape=(frag1_num_atoms, 3)) frag1_nbrs = Input(shape=(frag1_num_atoms, max_num_neighbors)) frag1_nbrs_z = Input(shape=(frag1_num_atoms, max_num_neighbors)) frag1_z = Input(shape=(frag1_num_atoms,)) frag2_X = Input(shape=(frag2_num_atoms, 3)) frag2_nbrs = Input(shape=(frag2_num_atoms, max_num_neighbors)) frag2_nbrs_z = Input(shape=(frag2_num_atoms, max_num_neighbors)) frag2_z = Input(shape=(frag2_num_atoms,)) complex_X = Input(shape=(complex_num_atoms, 3)) complex_nbrs = Input(shape=(complex_num_atoms, max_num_neighbors)) complex_nbrs_z = Input(shape=(complex_num_atoms, max_num_neighbors)) complex_z = Input(shape=(complex_num_atoms,)) self._frag1_conv = AtomicConvolution( atom_types=self.atom_types, radial_params=rp, boxsize=None)([frag1_X, frag1_nbrs, frag1_nbrs_z]) self._frag2_conv = AtomicConvolution( atom_types=self.atom_types, radial_params=rp, boxsize=None)([frag2_X, frag2_nbrs, frag2_nbrs_z]) self._complex_conv = AtomicConvolution( atom_types=self.atom_types, radial_params=rp, boxsize=None)([complex_X, complex_nbrs, complex_nbrs_z]) score = AtomicConvScore(self.atom_types, layer_sizes)([ self._frag1_conv, self._frag2_conv, self._complex_conv, frag1_z, frag2_z, complex_z ]) model = tf.keras.Model( inputs=[ frag1_X, frag1_nbrs, frag1_nbrs_z, frag1_z, frag2_X, frag2_nbrs, frag2_nbrs_z, frag2_z, complex_X, complex_nbrs, complex_nbrs_z, complex_z ], outputs=score) super(AtomicConvModel, self).__init__( model, L2Loss(), batch_size=batch_size, **kwargs) def default_generator(self, dataset, epochs=1, mode='fit', deterministic=True, pad_batches=True): batch_size = self.batch_size def replace_atom_types(z): def place_holder(i): if i in self.atom_types: return i return -1 return np.array([place_holder(x) for x in z]) for epoch in range(epochs): for ind, (F_b, y_b, w_b, ids_b) in enumerate( dataset.iterbatches( batch_size, deterministic=True, pad_batches=pad_batches)): N = self.complex_num_atoms N_1 = self.frag1_num_atoms N_2 = self.frag2_num_atoms M = self.max_num_neighbors batch_size = F_b.shape[0] num_features = F_b[0][0].shape[1] frag1_X_b = np.zeros((batch_size, N_1, num_features)) for i in range(batch_size): frag1_X_b[i] = F_b[i][0] frag2_X_b = np.zeros((batch_size, N_2, num_features)) for i in range(batch_size): frag2_X_b[i] = F_b[i][3] complex_X_b = np.zeros((batch_size, N, num_features)) for i in range(batch_size): complex_X_b[i] = F_b[i][6] frag1_Nbrs = np.zeros((batch_size, N_1, M)) frag1_Z_b = np.zeros((batch_size, N_1)) for i in range(batch_size): z = replace_atom_types(F_b[i][2]) frag1_Z_b[i] = z frag1_Nbrs_Z = np.zeros((batch_size, N_1, M)) for atom in range(N_1): for i in range(batch_size): atom_nbrs = F_b[i][1].get(atom, "") frag1_Nbrs[i, atom, :len(atom_nbrs)] = np.array(atom_nbrs) for j, atom_j in enumerate(atom_nbrs): frag1_Nbrs_Z[i, atom, j] = frag1_Z_b[i, atom_j] frag2_Nbrs = np.zeros((batch_size, N_2, M)) frag2_Z_b = np.zeros((batch_size, N_2)) for i in range(batch_size): z = replace_atom_types(F_b[i][5]) frag2_Z_b[i] = z frag2_Nbrs_Z = np.zeros((batch_size, N_2, M)) for atom in range(N_2): for i in range(batch_size): atom_nbrs = F_b[i][4].get(atom, "") frag2_Nbrs[i, atom, :len(atom_nbrs)] = np.array(atom_nbrs) for j, atom_j in enumerate(atom_nbrs): frag2_Nbrs_Z[i, atom, j] = frag2_Z_b[i, atom_j] complex_Nbrs = np.zeros((batch_size, N, M)) complex_Z_b = np.zeros((batch_size, N)) for i in range(batch_size): z = replace_atom_types(F_b[i][8]) complex_Z_b[i] = z complex_Nbrs_Z = np.zeros((batch_size, N, M)) for atom in range(N): for i in range(batch_size): atom_nbrs = F_b[i][7].get(atom, "") complex_Nbrs[i, atom, :len(atom_nbrs)] = np.array(atom_nbrs) for j, atom_j in enumerate(atom_nbrs): complex_Nbrs_Z[i, atom, j] = complex_Z_b[i, atom_j] inputs = [ frag1_X_b, frag1_Nbrs, frag1_Nbrs_Z, frag1_Z_b, frag2_X_b, frag2_Nbrs, frag2_Nbrs_Z, frag2_Z_b, complex_X_b, complex_Nbrs, complex_Nbrs_Z, complex_Z_b ] y_b = np.reshape(y_b, newshape=(batch_size, 1)) yield (inputs, [y_b], [w_b])
[ "tensorflow.equal", "numpy.sqrt", "tensorflow.reduce_sum", "numpy.array", "tensorflow.random.truncated_normal", "tensorflow.keras.layers.Input", "numpy.reshape", "deepchem.models.losses.L2Loss", "itertools.product", "tensorflow.matmul", "tensorflow.zeros_like", "tensorflow.zeros", "tensorflow.Variable", "tensorflow.where", "tensorflow.expand_dims", "deepchem.models.layers.AtomicConvolution", "tensorflow.nn.relu", "numpy.zeros", "tensorflow.add_n", "tensorflow.constant", "tensorflow.keras.Model" ]
[((1263, 1293), 'tensorflow.Variable', 'tf.Variable', (['weights'], {'name': '"""w"""'}), "(weights, name='w')\n", (1274, 1293), True, 'import tensorflow as tf\n'), ((1300, 1329), 'tensorflow.Variable', 'tf.Variable', (['biases'], {'name': '"""b"""'}), "(biases, name='b')\n", (1311, 1329), True, 'import tensorflow as tf\n'), ((1140, 1204), 'tensorflow.random.truncated_normal', 'tf.random.truncated_normal', (['[prev_layer_size, size]'], {'stddev': '(0.01)'}), '([prev_layer_size, size], stddev=0.01)\n', (1166, 1204), True, 'import tensorflow as tf\n'), ((1239, 1255), 'tensorflow.zeros', 'tf.zeros', (['[size]'], {}), '([size])\n', (1247, 1255), True, 'import tensorflow as tf\n'), ((3626, 3666), 'tensorflow.zeros_like', 'tf.zeros_like', (['frag1_z'], {'dtype': 'tf.float32'}), '(frag1_z, dtype=tf.float32)\n', (3639, 3666), True, 'import tensorflow as tf\n'), ((3685, 3725), 'tensorflow.zeros_like', 'tf.zeros_like', (['frag2_z'], {'dtype': 'tf.float32'}), '(frag2_z, dtype=tf.float32)\n', (3698, 3725), True, 'import tensorflow as tf\n'), ((3746, 3788), 'tensorflow.zeros_like', 'tf.zeros_like', (['complex_z'], {'dtype': 'tf.float32'}), '(complex_z, dtype=tf.float32)\n', (3759, 3788), True, 'import tensorflow as tf\n'), ((4555, 4586), 'tensorflow.add_n', 'tf.add_n', (['frag1_atomtype_energy'], {}), '(frag1_atomtype_energy)\n', (4563, 4586), True, 'import tensorflow as tf\n'), ((4607, 4638), 'tensorflow.add_n', 'tf.add_n', (['frag2_atomtype_energy'], {}), '(frag2_atomtype_energy)\n', (4615, 4638), True, 'import tensorflow as tf\n'), ((4661, 4694), 'tensorflow.add_n', 'tf.add_n', (['complex_atomtype_energy'], {}), '(complex_atomtype_energy)\n', (4669, 4694), True, 'import tensorflow as tf\n'), ((4715, 4746), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['frag1_outputs', '(1)'], {}), '(frag1_outputs, 1)\n', (4728, 4746), True, 'import tensorflow as tf\n'), ((4766, 4797), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['frag2_outputs', '(1)'], {}), '(frag2_outputs, 1)\n', (4779, 4797), True, 'import tensorflow as tf\n'), ((4819, 4852), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['complex_outputs', '(1)'], {}), '(complex_outputs, 1)\n', (4832, 4852), True, 'import tensorflow as tf\n'), ((4932, 4970), 'tensorflow.expand_dims', 'tf.expand_dims', (['binding_energy'], {'axis': '(1)'}), '(binding_energy, axis=1)\n', (4946, 4970), True, 'import tensorflow as tf\n'), ((7204, 7237), 'tensorflow.keras.layers.Input', 'Input', ([], {'shape': '(frag1_num_atoms, 3)'}), '(shape=(frag1_num_atoms, 3))\n', (7209, 7237), False, 'from tensorflow.keras.layers import Input, Layer\n'), ((7255, 7304), 'tensorflow.keras.layers.Input', 'Input', ([], {'shape': '(frag1_num_atoms, max_num_neighbors)'}), '(shape=(frag1_num_atoms, max_num_neighbors))\n', (7260, 7304), False, 'from tensorflow.keras.layers import Input, Layer\n'), ((7324, 7373), 'tensorflow.keras.layers.Input', 'Input', ([], {'shape': '(frag1_num_atoms, max_num_neighbors)'}), '(shape=(frag1_num_atoms, max_num_neighbors))\n', (7329, 7373), False, 'from tensorflow.keras.layers import Input, Layer\n'), ((7388, 7419), 'tensorflow.keras.layers.Input', 'Input', ([], {'shape': '(frag1_num_atoms,)'}), '(shape=(frag1_num_atoms,))\n', (7393, 7419), False, 'from tensorflow.keras.layers import Input, Layer\n'), ((7435, 7468), 'tensorflow.keras.layers.Input', 'Input', ([], {'shape': '(frag2_num_atoms, 3)'}), '(shape=(frag2_num_atoms, 3))\n', (7440, 7468), False, 'from tensorflow.keras.layers import Input, Layer\n'), ((7486, 7535), 'tensorflow.keras.layers.Input', 'Input', ([], {'shape': '(frag2_num_atoms, max_num_neighbors)'}), '(shape=(frag2_num_atoms, max_num_neighbors))\n', (7491, 7535), False, 'from tensorflow.keras.layers import Input, Layer\n'), ((7555, 7604), 'tensorflow.keras.layers.Input', 'Input', ([], {'shape': '(frag2_num_atoms, max_num_neighbors)'}), '(shape=(frag2_num_atoms, max_num_neighbors))\n', (7560, 7604), False, 'from tensorflow.keras.layers import Input, Layer\n'), ((7619, 7650), 'tensorflow.keras.layers.Input', 'Input', ([], {'shape': '(frag2_num_atoms,)'}), '(shape=(frag2_num_atoms,))\n', (7624, 7650), False, 'from tensorflow.keras.layers import Input, Layer\n'), ((7668, 7703), 'tensorflow.keras.layers.Input', 'Input', ([], {'shape': '(complex_num_atoms, 3)'}), '(shape=(complex_num_atoms, 3))\n', (7673, 7703), False, 'from tensorflow.keras.layers import Input, Layer\n'), ((7723, 7774), 'tensorflow.keras.layers.Input', 'Input', ([], {'shape': '(complex_num_atoms, max_num_neighbors)'}), '(shape=(complex_num_atoms, max_num_neighbors))\n', (7728, 7774), False, 'from tensorflow.keras.layers import Input, Layer\n'), ((7796, 7847), 'tensorflow.keras.layers.Input', 'Input', ([], {'shape': '(complex_num_atoms, max_num_neighbors)'}), '(shape=(complex_num_atoms, max_num_neighbors))\n', (7801, 7847), False, 'from tensorflow.keras.layers import Input, Layer\n'), ((7864, 7897), 'tensorflow.keras.layers.Input', 'Input', ([], {'shape': '(complex_num_atoms,)'}), '(shape=(complex_num_atoms,))\n', (7869, 7897), False, 'from tensorflow.keras.layers import Input, Layer\n'), ((8555, 8741), 'tensorflow.keras.Model', 'tf.keras.Model', ([], {'inputs': '[frag1_X, frag1_nbrs, frag1_nbrs_z, frag1_z, frag2_X, frag2_nbrs,\n frag2_nbrs_z, frag2_z, complex_X, complex_nbrs, complex_nbrs_z, complex_z]', 'outputs': 'score'}), '(inputs=[frag1_X, frag1_nbrs, frag1_nbrs_z, frag1_z, frag2_X,\n frag2_nbrs, frag2_nbrs_z, frag2_z, complex_X, complex_nbrs,\n complex_nbrs_z, complex_z], outputs=score)\n', (8569, 8741), True, 'import tensorflow as tf\n'), ((4168, 4195), 'tensorflow.equal', 'tf.equal', (['frag1_z', 'atomtype'], {}), '(frag1_z, atomtype)\n', (4176, 4195), True, 'import tensorflow as tf\n'), ((4288, 4315), 'tensorflow.equal', 'tf.equal', (['frag2_z', 'atomtype'], {}), '(frag2_z, atomtype)\n', (4296, 4315), True, 'import tensorflow as tf\n'), ((4408, 4437), 'tensorflow.equal', 'tf.equal', (['complex_z', 'atomtype'], {}), '(complex_z, atomtype)\n', (4416, 4437), True, 'import tensorflow as tf\n'), ((7922, 7999), 'deepchem.models.layers.AtomicConvolution', 'AtomicConvolution', ([], {'atom_types': 'self.atom_types', 'radial_params': 'rp', 'boxsize': 'None'}), '(atom_types=self.atom_types, radial_params=rp, boxsize=None)\n', (7939, 7999), False, 'from deepchem.models.layers import AtomicConvolution\n'), ((8078, 8155), 'deepchem.models.layers.AtomicConvolution', 'AtomicConvolution', ([], {'atom_types': 'self.atom_types', 'radial_params': 'rp', 'boxsize': 'None'}), '(atom_types=self.atom_types, radial_params=rp, boxsize=None)\n', (8095, 8155), False, 'from deepchem.models.layers import AtomicConvolution\n'), ((8236, 8313), 'deepchem.models.layers.AtomicConvolution', 'AtomicConvolution', ([], {'atom_types': 'self.atom_types', 'radial_params': 'rp', 'boxsize': 'None'}), '(atom_types=self.atom_types, radial_params=rp, boxsize=None)\n', (8253, 8313), False, 'from deepchem.models.layers import AtomicConvolution\n'), ((8855, 8863), 'deepchem.models.losses.L2Loss', 'L2Loss', ([], {}), '()\n', (8861, 8863), False, 'from deepchem.models.losses import L2Loss\n'), ((1906, 1916), 'numpy.sqrt', 'np.sqrt', (['x'], {}), '(x)\n', (1913, 1916), True, 'import numpy as np\n'), ((3357, 3374), 'tensorflow.nn.relu', 'tf.nn.relu', (['layer'], {}), '(layer)\n', (3367, 3374), True, 'import tensorflow as tf\n'), ((4231, 4273), 'tensorflow.where', 'tf.where', (['cond', 'frag1_outputs', 'frag1_zeros'], {}), '(cond, frag1_outputs, frag1_zeros)\n', (4239, 4273), True, 'import tensorflow as tf\n'), ((4351, 4393), 'tensorflow.where', 'tf.where', (['cond', 'frag2_outputs', 'frag2_zeros'], {}), '(cond, frag2_outputs, frag2_zeros)\n', (4359, 4393), True, 'import tensorflow as tf\n'), ((4486, 4532), 'tensorflow.where', 'tf.where', (['cond', 'complex_outputs', 'complex_zeros'], {}), '(cond, complex_outputs, complex_zeros)\n', (4494, 4532), True, 'import tensorflow as tf\n'), ((7162, 7188), 'itertools.product', 'itertools.product', (['*radial'], {}), '(*radial)\n', (7179, 7188), False, 'import itertools\n'), ((9761, 9802), 'numpy.zeros', 'np.zeros', (['(batch_size, N_1, num_features)'], {}), '((batch_size, N_1, num_features))\n', (9769, 9802), True, 'import numpy as np\n'), ((9895, 9936), 'numpy.zeros', 'np.zeros', (['(batch_size, N_2, num_features)'], {}), '((batch_size, N_2, num_features))\n', (9903, 9936), True, 'import numpy as np\n'), ((10031, 10070), 'numpy.zeros', 'np.zeros', (['(batch_size, N, num_features)'], {}), '((batch_size, N, num_features))\n', (10039, 10070), True, 'import numpy as np\n'), ((10166, 10196), 'numpy.zeros', 'np.zeros', (['(batch_size, N_1, M)'], {}), '((batch_size, N_1, M))\n', (10174, 10196), True, 'import numpy as np\n'), ((10217, 10244), 'numpy.zeros', 'np.zeros', (['(batch_size, N_1)'], {}), '((batch_size, N_1))\n', (10225, 10244), True, 'import numpy as np\n'), ((10375, 10405), 'numpy.zeros', 'np.zeros', (['(batch_size, N_1, M)'], {}), '((batch_size, N_1, M))\n', (10383, 10405), True, 'import numpy as np\n'), ((10730, 10760), 'numpy.zeros', 'np.zeros', (['(batch_size, N_2, M)'], {}), '((batch_size, N_2, M))\n', (10738, 10760), True, 'import numpy as np\n'), ((10781, 10808), 'numpy.zeros', 'np.zeros', (['(batch_size, N_2)'], {}), '((batch_size, N_2))\n', (10789, 10808), True, 'import numpy as np\n'), ((10939, 10969), 'numpy.zeros', 'np.zeros', (['(batch_size, N_2, M)'], {}), '((batch_size, N_2, M))\n', (10947, 10969), True, 'import numpy as np\n'), ((11296, 11324), 'numpy.zeros', 'np.zeros', (['(batch_size, N, M)'], {}), '((batch_size, N, M))\n', (11304, 11324), True, 'import numpy as np\n'), ((11347, 11372), 'numpy.zeros', 'np.zeros', (['(batch_size, N)'], {}), '((batch_size, N))\n', (11355, 11372), True, 'import numpy as np\n'), ((11507, 11535), 'numpy.zeros', 'np.zeros', (['(batch_size, N, M)'], {}), '((batch_size, N, M))\n', (11515, 11535), True, 'import numpy as np\n'), ((12073, 12114), 'numpy.reshape', 'np.reshape', (['y_b'], {'newshape': '(batch_size, 1)'}), '(y_b, newshape=(batch_size, 1))\n', (12083, 12114), True, 'import numpy as np\n'), ((3243, 3296), 'tensorflow.matmul', 'tf.matmul', (['prev_layer', 'self.type_weights[atomtype][i]'], {}), '(prev_layer, self.type_weights[atomtype][i])\n', (3252, 3296), True, 'import tensorflow as tf\n'), ((3476, 3531), 'tensorflow.matmul', 'tf.matmul', (['prev_layer', 'self.output_weights[atomtype][0]'], {}), '(prev_layer, self.output_weights[atomtype][0])\n', (3485, 3531), True, 'import tensorflow as tf\n'), ((2391, 2494), 'tensorflow.random.truncated_normal', 'tf.random.truncated_normal', ([], {'shape': '[prev_layer_size, layer_sizes[i]]', 'stddev': 'weight_init_stddevs[i]'}), '(shape=[prev_layer_size, layer_sizes[i]], stddev=\n weight_init_stddevs[i])\n', (2417, 2494), True, 'import tensorflow as tf\n'), ((2543, 2605), 'tensorflow.constant', 'tf.constant', ([], {'value': 'bias_init_consts[i]', 'shape': '[layer_sizes[i]]'}), '(value=bias_init_consts[i], shape=[layer_sizes[i]])\n', (2554, 2605), True, 'import tensorflow as tf\n'), ((10575, 10594), 'numpy.array', 'np.array', (['atom_nbrs'], {}), '(atom_nbrs)\n', (10583, 10594), True, 'import numpy as np\n'), ((11139, 11158), 'numpy.array', 'np.array', (['atom_nbrs'], {}), '(atom_nbrs)\n', (11147, 11158), True, 'import numpy as np\n'), ((11705, 11724), 'numpy.array', 'np.array', (['atom_nbrs'], {}), '(atom_nbrs)\n', (11713, 11724), True, 'import numpy as np\n')]
import math import os from copy import deepcopy from ast import literal_eval import pandas as pd from math import factorial import random from collections import Counter, defaultdict import sys from nltk import word_tokenize from tqdm import tqdm, trange import argparse import numpy as np import re import csv from sklearn.model_selection import train_test_split from swda.swda import CorpusReader, Transcript, Utterance act2word = {1:"inform",2:"question", 3:"directive", 4:"commissive"} def permute(sents, sent_DAs, amount): """ return a list of different! permuted sentences and their respective dialog acts """ """ if amount is greater than the possible amount of permutations, only the uniquely possible ones are returned """ assert len(sents) == len(sent_DAs), "length of permuted sentences and list of DAs must be equal" if amount == 0: return [] permutations = [list(range(len(sents)))] amount = min(amount, factorial(len(sents))-1) for i in range(amount): permutation = np.random.permutation(len(sents)) while permutation.tolist() in permutations: permutation = np.random.permutation(len(sents)) permutations.append(permutation.tolist()) return permutations[1:] #the first one is the original, which was included s.t. won't be generated def draw_rand_sent(act_utt_df, sent_len, amount): """ df is supposed to be a pandas dataframe with colums 'act' and 'utt' (utterance), with act being a number from 1 to 4 and utt being a sentence """ permutations = [] for _ in range(amount): (utt, da, name, ix) = draw_rand_sent_from_df(act_utt_df) sent_insert_ix = random.randint(0, sent_len-1) permutations.append((utt, da, name, ix, sent_insert_ix)) return permutations def draw_rand_sent_from_df(df): ix = random.randint(0, len(df['utt'])-1) return literal_eval(df['utt'][ix]), df['act'][ix], df['dialogue'][ix], df['ix'][ix] def half_perturb(sents, sent_DAs, amount): assert len(sents) == len(sent_DAs), "length of permuted sentences and list of DAs must be equal" permutations = [list(range(len(sents)))] for _ in range(amount): while True: speaker = random.randint(0,1) # choose one of the speakers speaker_ix = list(filter(lambda x: (x-speaker) % 2 == 0, range(len(sents)))) permuted_speaker_ix = np.random.permutation(speaker_ix) new_sents = list(range(len(sents))) for (i_to, i_from) in zip(speaker_ix, permuted_speaker_ix): new_sents[i_to] = i_from if (not new_sents == permutations[0]) and ( not new_sents in permutations or len(permutations) > math.factorial(len(speaker_ix))): permutations.append(new_sents) break return permutations[1:] def utterance_insertions(length, amount): possible_permutations = [] original = list(range(length)) for ix in original: for y in range(length): if ix == y: continue ix_removed = original[0:ix] + ([] if ix == length-1 else original[ix+1:]) ix_removed.insert(y, ix) possible_permutations.append(deepcopy(ix_removed)) permutations = [] for _ in range(amount): i = random.randint(0, len(possible_permutations)-1) permutations.append(possible_permutations[i]) return permutations class DailyDialogConverter: def __init__(self, data_dir, tokenizer, word2id, task='', ranking_dataset = True): self.data_dir = data_dir self.act_utt_file = os.path.join(data_dir, 'act_utt_name.txt') self.tokenizer = tokenizer self.word2id = word2id self.output_file = None self.task = task self.ranking_dataset = ranking_dataset self.perturbation_statistics = 0 self.setname = os.path.split(data_dir)[1] assert self.setname == 'train' or self.setname == 'validation' or self.setname == 'test', "wrong data dir name" def create_act_utt(self): dial_file = os.path.join(self.data_dir, "dialogues_{}.txt".format(self.setname)) act_file = os.path.join(self.data_dir, "dialogues_act_{}.txt".format(self.setname)) output_file = os.path.join(self.data_dir, 'act_utt_name.txt'.format(self.task)) df = open(dial_file, 'r') af = open(act_file, 'r') of = open(output_file, 'w') csv_writer = csv.writer(of, delimiter='|') for line_count, (dial, act) in tqdm(enumerate(zip(df, af)), total=11118): seqs = dial.split('__eou__') seqs = seqs[:-1] if len(seqs) < 5: continue tok_seqs = [self.tokenizer(seq) for seq in seqs] tok_seqs = [[w.lower() for w in utt] for utt in tok_seqs] tok_seqs = [self.word2id(seq) for seq in tok_seqs] acts = act.split(' ') acts = acts[:-1] acts = [int(act) for act in acts] for utt_i, (act, utt) in enumerate(zip(acts, tok_seqs)): dialog_name = "{}_{}".format(self.setname, line_count) row = (act, utt, dialog_name,utt_i) csv_writer.writerow(row) def convert_dset(self, amounts): # data_dir is supposed to be the dir with the respective train/test/val-dataset files print("Creating {} perturbations for task {}".format(amounts, self.task)) dial_file = os.path.join(self.data_dir, "dialogues_{}.txt".format(self.setname)) act_file = os.path.join(self.data_dir, "dialogues_act_{}.txt".format(self.setname)) self.output_file = os.path.join(self.data_dir, 'coherency_dset_{}.txt'.format(self.task)) root_data_dir = os.path.split(self.data_dir)[0] shuffled_path = os.path.join(root_data_dir, "shuffled_{}".format(self.task)) if not os.path.isdir(shuffled_path): os.mkdir(shuffled_path) assert os.path.isfile(dial_file) and os.path.isfile(act_file), "could not find input files" assert os.path.isfile(self.act_utt_file), "missing act_utt.txt in data_dir" with open(self.act_utt_file, 'r') as f: act_utt_df = pd.read_csv(f, sep='|', names=['act','utt','dialogue','ix']) rand_generator = lambda: draw_rand_sent_from_df(act_utt_df) df = open(dial_file, 'r') af = open(act_file, 'r') of = open(self.output_file, 'w') discarded = 0 for line_count, (dial, act) in tqdm(enumerate(zip(df, af)), total=11118): seqs = dial.split('__eou__') seqs = seqs[:-1] if len(seqs) < 5: discarded += 1 continue tok_seqs = [self.tokenizer(seq) for seq in seqs] tok_seqs = [[w.lower() for w in utt] for utt in tok_seqs] tok_seqs = [self.word2id(seq) for seq in tok_seqs] acts = act.split(' ') acts = acts[:-1] acts = [int(act) for act in acts] if self.task == 'up': permuted_ixs = permute(tok_seqs, acts, amounts) elif self.task == 'us': permuted_ixs = draw_rand_sent(act_utt_df, len(tok_seqs), amounts) elif self.task == 'hup': permuted_ixs = half_perturb(tok_seqs, acts, amounts) elif self.task == 'ui': permuted_ixs = utterance_insertions(len(tok_seqs), amounts) shuffle_file = os.path.join(shuffled_path, "{}_{}.csv".format(self.setname, line_count)) with open(shuffle_file, "w") as f: csv_writer = csv.writer(f) for perm in permuted_ixs: if self.task == 'us': (utt, da, name, ix, insert_ix) = perm row = [name, ix,insert_ix] csv_writer.writerow(row) else: csv_writer.writerow(perm) self.perturbation_statistics += len(permuted_ixs) if self.task == 'us': for p in permuted_ixs: (insert_sent, insert_da, name, ix, insert_ix) = p a = " ".join([str(a) for a in acts]) u = str(tok_seqs) p_a = deepcopy(acts) p_a[insert_ix] = insert_da pa = " ".join([str(a) for a in p_a]) p_u = deepcopy(tok_seqs) p_u[insert_ix] = self.word2id(insert_sent) of.write("{}|{}|{}|{}|{}\n".format("0",a,u,pa,p_u)) of.write("{}|{}|{}|{}|{}\n".format("1",pa,p_u,a,u)) else: for p in permuted_ixs: a = " ".join([str(a) for a in acts]) u = str(tok_seqs) pa = [acts[i] for i in p] p_a = " ".join([str(a) for a in pa]) pu = [tok_seqs[i] for i in p] p_u = str(pu) of.write("{}|{}|{}|{}|{}\n".format("0",a,u,p_a,p_u)) of.write("{}|{}|{}|{}|{}\n".format("1",p_a,p_u,a,u)) print(discarded) class SwitchboardConverter: def __init__(self, data_dir, tokenizer, word2id, task='', seed=42): self.corpus = CorpusReader(data_dir) self.data_dir = data_dir self.tokenizer = tokenizer self.word2id = word2id self.task = task self.utt_num = 0 for utt in self.corpus.iter_utterances(): self.utt_num += 1 self.trans_num = 0 for trans in self.corpus.iter_transcripts(): self.trans_num += 1 self.da2num = switchboard_da_mapping() # CAUTION: make sure that for each task the seed is the same s.t. the splits will be the same! train_ixs, val_ixs = train_test_split(range(self.trans_num), shuffle=True, train_size=0.8, random_state=seed) val_ixs, test_ixs = train_test_split(val_ixs, shuffle=True, train_size=0.5, random_state=seed) self.train_ixs, self.val_ixs, self.test_ixs = train_ixs, val_ixs, test_ixs self.utt_da_pairs = [] prev_da = "%" for i, utt in enumerate(self.corpus.iter_utterances()): sentence = re.sub(r"([+/\}\[\]]|\{\w)", "", utt.text) sentence = self.word2id(self.tokenizer(sentence)) act = utt.damsl_act_tag() if act == None: act = "%" if act == "+": act = prev_da _, swda_name = os.path.split(utt.swda_filename) swda_name = swda_name[:-4] if swda_name.endswith('.csv') else swda_name ix = utt.utterance_index self.utt_da_pairs.append((sentence, act, swda_name, ix)) def draw_rand_sent(self): r = random.randint(0, len(self.utt_da_pairs)-1) return self.utt_da_pairs[r] def create_vocab(self): print("Creating Vocab file for Switchboard") cnt = Counter() for utt in self.corpus.iter_utterances(): sentence = re.sub(r"([+/\}\[\]]|\{\w)", "", utt.text) sentence = self.tokenizer(sentence) for w in sentence: cnt[w] += 1 itos_file = os.path.join(self.data_dir, "itos.txt") itosf = open(itos_file, "w") for (word, _) in cnt.most_common(25000): itosf.write("{}\n".format(word)) #getKeysByValue def swda_permute(self, sents, amount, speaker_ixs): if amount == 0: return [] permutations = [list(range(len(sents)))] segment_permutations = [] amount = min(amount, factorial(len(sents))-1) segm_ixs = self.speaker_segment_ixs(speaker_ixs) segments = list(set(segm_ixs.values())) for i in range(amount): while True: permutation = [] segm_perm = np.random.permutation(len(segments)) segment_permutations.append(segm_perm) for segm_ix in segm_perm: utt_ixs = sorted(getKeysByValue(segm_ixs, segm_ix)) permutation = permutation + utt_ixs if permutation not in permutations: break permutations.append(permutation) return permutations[1:] , segment_permutations #the first one is the original, which was included s.t. won't be generated def speaker_segment_ixs(self, speaker_ixs): i = 0 segment_indices = dict() prev_speaker = speaker_ixs[0] for j,speaker in enumerate(speaker_ixs): if speaker != prev_speaker: prev_speaker = speaker i += 1 segment_indices[j] = i return segment_indices def swda_half_perturb(self, amount, speaker_ixs): segm_ixs = self.speaker_segment_ixs(speaker_ixs) segments = list(set(segm_ixs.values())) segment_permutations = [] permutations = [list(segm_ixs.keys())] for _ in range(amount): speaker = random.randint(0,1) # choose one of the speakers speaker_to_perm = list(filter(lambda x: (x-speaker) % 2 == 0, segments)) speaker_orig = list(filter(lambda x: (x-speaker) % 2 != 0, segments)) #TODO: rename either speaker_ix or speaker_ixs, they are something different, but the names are too close if len(speaker_to_perm) < 2: return [] while True: permuted_speaker_ix = np.random.permutation(speaker_to_perm).tolist() new_segments = [None]*(len(speaker_orig)+len(permuted_speaker_ix)) if speaker == 0 : new_segments[::2] = permuted_speaker_ix new_segments[1::2] = speaker_orig else: new_segments[1::2] = permuted_speaker_ix new_segments[::2] = speaker_orig segment_permutations.append(new_segments) permutation = [] for segm_ix in new_segments: utt_ixs = sorted(getKeysByValue(segm_ixs, segm_ix)) permutation = permutation + utt_ixs if not permutation in permutations: permutations.append(permutation) break return permutations[1:], segment_permutations def swda_utterance_insertion(self, speaker_ixs, amounts): segment_ixs = self.speaker_segment_ixs(speaker_ixs) segments = list(set(segment_ixs.values())) segment_permutations = [] permutations = [] i = 0 for _ in range(amounts): while True: # actually: do ... while permutation not in permutations i_from = random.randint(0, len(segments)-1) i_to = random.randint(0, len(segments)-2) segm_perm = deepcopy(segments) rem_elem = segments[i_from] segm_perm = segm_perm[0:i_from] + segm_perm[i_from+1:] segm_perm = segm_perm[0:i_to] + [rem_elem] + segm_perm[i_to:] permutation = [] for segm_ix in segm_perm: utt_ixs = sorted(getKeysByValue(segment_ixs, segm_ix)) permutation = permutation + utt_ixs if permutation not in permutations: permutations.append(permutation) segment_permutations.append(segm_perm) break return permutations, segment_permutations def swda_utterance_sampling(self, speaker_ixs, amount): segm_ixs = self.speaker_segment_ixs(speaker_ixs) segments = list(set(segm_ixs.values())) permutations = [] for i in range(amount): (sentence, act, swda_name, ix) = self.draw_rand_sent() insert_ix = random.choice(segments) permutations.append((sentence, act, swda_name, ix, insert_ix)) return permutations def convert_dset(self, amounts): # create distinct train/validation/test files. they'll correspond to the created # splits from the constructor train_output_file = os.path.join(self.data_dir, 'train', 'coherency_dset_{}.txt'.format(self.task)) val_output_file = os.path.join(self.data_dir, 'validation', 'coherency_dset_{}.txt'.format(self.task)) test_output_file = os.path.join(self.data_dir, 'test', 'coherency_dset_{}.txt'.format(self.task)) if not os.path.exists(os.path.join(self.data_dir, 'train')): os.makedirs(os.path.join(self.data_dir, 'train')) if not os.path.exists(os.path.join(self.data_dir, 'validation')): os.makedirs(os.path.join(self.data_dir, 'validation')) if not os.path.exists(os.path.join(self.data_dir, 'test')): os.makedirs(os.path.join(self.data_dir, 'test')) trainfile = open(train_output_file, 'w') valfile = open(val_output_file, 'w') testfile = open(test_output_file, 'w') shuffled_path = os.path.join(self.data_dir, "shuffled_{}".format(self.task)) if not os.path.isdir(shuffled_path): os.mkdir(shuffled_path) for i,trans in enumerate(tqdm(self.corpus.iter_transcripts(display_progress=False), total=1155)): utterances = [] acts = [] speaker_ixs = [] prev_act = "%" for utt in trans.utterances: sentence = re.sub(r"([+/\}\[\]]|\{\w)", "", utt.text) sentence = self.word2id(self.tokenizer(sentence)) utterances.append(sentence) act = utt.damsl_act_tag() if act == None: act = "%" if act == "+": act = prev_act acts.append(self.da2num[act]) prev_act = act if "A" in utt.caller: speaker_ixs.append(0) else: speaker_ixs.append(1) if self.task == 'up': permuted_ixs , segment_perms = self.swda_permute(utterances, amounts, speaker_ixs) elif self.task == 'us': permuted_ixs = self.swda_utterance_sampling(speaker_ixs, amounts) elif self.task == 'hup': permuted_ixs , segment_perms = self.swda_half_perturb(amounts, speaker_ixs) elif self.task == 'ui': permuted_ixs, segment_perms = self.swda_utterance_insertion(speaker_ixs, amounts) swda_fname = os.path.split(trans.swda_filename)[1] shuffle_file = os.path.join(shuffled_path, swda_fname) # [:-4] with open(shuffle_file, "w") as f: csv_writer = csv.writer(f) if self.task == 'us': for perm in permuted_ixs: (utt, da, name, ix, insert_ix) = perm row = [name, ix,insert_ix] csv_writer.writerow(row) else: for perm in segment_perms: csv_writer.writerow(perm) if self.task == 'us': for p in permuted_ixs: a = " ".join([str(x) for x in acts]) u = str(utterances) insert_sent, insert_da, name, ix, insert_ix = p insert_da = self.da2num[insert_da] p_a = deepcopy(acts) p_a[insert_ix] = insert_da pa = " ".join([str(x) for x in p_a]) p_u = deepcopy(utterances) p_u[insert_ix] = insert_sent if i in self.train_ixs: trainfile.write("{}|{}|{}|{}|{}\n".format("0",a,u,pa,p_u)) trainfile.write("{}|{}|{}|{}|{}\n".format("1",pa,p_u,a,u)) if i in self.val_ixs: valfile.write("{}|{}|{}|{}|{}\n".format("0",a,u,pa,p_u)) valfile.write("{}|{}|{}|{}|{}\n".format("1",pa,p_u,a,u)) if i in self.test_ixs: testfile.write("{}|{}|{}|{}|{}\n".format("0",a,u,pa,p_u)) testfile.write("{}|{}|{}|{}|{}\n".format("1",pa,p_u,a,u)) else: for p in permuted_ixs: a = " ".join([str(x) for x in acts]) u = str(utterances) pa = [acts[i] for i in p] p_a = " ".join([str(x) for x in pa]) pu = [utterances[i] for i in p] p_u = str(pu) if i in self.train_ixs: trainfile.write("{}|{}|{}|{}|{}\n".format("0",a,u,p_a,p_u)) trainfile.write("{}|{}|{}|{}|{}\n".format("1",p_a,p_u,a,u)) if i in self.val_ixs: valfile.write("{}|{}|{}|{}|{}\n".format("0",a,u,p_a,p_u)) valfile.write("{}|{}|{}|{}|{}\n".format("1",p_a,p_u,a,u)) if i in self.test_ixs: testfile.write("{}|{}|{}|{}|{}\n".format("0",a,u,p_a,p_u)) testfile.write("{}|{}|{}|{}|{}\n".format("1",p_a,p_u,a,u)) def main(): parser = argparse.ArgumentParser() parser.add_argument("--datadir", required=True, type=str, help="""The input directory where the files of the corpus are located. """) parser.add_argument("--corpus", required=True, type=str, help="""the name of the corpus to use, currently either 'DailyDialog' or 'Switchboard' """) parser.add_argument('--seed', type=int, default=42, help="random seed for initialization") parser.add_argument('--amount', type=int, default=20, help="random seed for initialization") parser.add_argument('--word2id', action='store_true', help= "convert the words to ids") parser.add_argument('--task', required=True, type=str, default="up", help="""for which task the dataset should be created. alternatives: up (utterance permutation) us (utterance sampling) hup (half utterance petrurbation) ui (utterance insertion, nothing directly added!)""") args = parser.parse_args() random.seed(args.seed) np.random.seed(args.seed) if args.word2id: f = open(os.path.join(args.datadir, "itos.txt"), "r") word2id_dict = dict() for i, word in enumerate(f): word2id_dict[word[:-1].lower()] = i word2id = lambda x: [word2id_dict[y] for y in x] # don't convert words to ids (yet). It gets done in the glove wrapper of mtl_coherence.py else: word2id = lambda x: x tokenizer = word_tokenize if args.corpus == 'DailyDialog': converter = DailyDialogConverter(args.datadir, tokenizer, word2id, task=args.task) converter.create_act_utt() elif args.corpus == 'Switchboard': converter = SwitchboardConverter(args.datadir, tokenizer, word2id, args.task, args.seed) converter.create_vocab() converter.convert_dset(amounts=args.amount) def getKeysByValue(dictOfElements, valueToFind): listOfKeys = list() for item in dictOfElements.items(): if item[1] == valueToFind: listOfKeys.append(item[0]) return listOfKeys def switchboard_da_mapping(): mapping_dict = dict({ "sd": 1, "b": 2, "sv": 3, "aa": 4, "%-": 5, "ba": 6, "qy": 7, "x": 8, "ny": 9, "fc": 10, "%": 11, "qw": 12, "nn": 13, "bk": 14, "h": 15, "qy^d": 16, "o": 17, "bh": 18, "^q": 19, "bf": 20, "na": 21, "ny^e": 22, "ad": 23, "^2": 24, "b^m": 25, "qo": 26, "qh": 27, "^h": 28, "ar": 29, "ng": 30, "nn^e": 31, "br": 32, "no": 33, "fp": 34, "qrr": 35, "arp": 36, "nd": 37, "t3": 38, "oo": 39, "co": 40, "cc": 41, "t1": 42, "bd": 43, "aap": 44, "am": 45, "^g": 46, "qw^d": 47, "fa": 48, "ft":49 }) d = defaultdict(lambda: 11) for (k, v) in mapping_dict.items(): d[k] = v return d if __name__ == "__main__": main()
[ "pandas.read_csv", "copy.deepcopy", "argparse.ArgumentParser", "os.path.split", "os.path.isdir", "numpy.random.seed", "os.mkdir", "random.randint", "numpy.random.permutation", "random.choice", "sklearn.model_selection.train_test_split", "csv.writer", "ast.literal_eval", "os.path.isfile", "re.sub", "os.path.join", "random.seed", "collections.Counter", "collections.defaultdict", "swda.swda.CorpusReader" ]
[((21335, 21360), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (21358, 21360), False, 'import argparse\n'), ((22879, 22901), 'random.seed', 'random.seed', (['args.seed'], {}), '(args.seed)\n', (22890, 22901), False, 'import random\n'), ((22906, 22931), 'numpy.random.seed', 'np.random.seed', (['args.seed'], {}), '(args.seed)\n', (22920, 22931), True, 'import numpy as np\n'), ((25293, 25317), 'collections.defaultdict', 'defaultdict', (['(lambda : 11)'], {}), '(lambda : 11)\n', (25304, 25317), False, 'from collections import Counter, defaultdict\n'), ((1684, 1715), 'random.randint', 'random.randint', (['(0)', '(sent_len - 1)'], {}), '(0, sent_len - 1)\n', (1698, 1715), False, 'import random\n'), ((1892, 1919), 'ast.literal_eval', 'literal_eval', (["df['utt'][ix]"], {}), "(df['utt'][ix])\n", (1904, 1919), False, 'from ast import literal_eval\n'), ((3613, 3655), 'os.path.join', 'os.path.join', (['data_dir', '"""act_utt_name.txt"""'], {}), "(data_dir, 'act_utt_name.txt')\n", (3625, 3655), False, 'import os\n'), ((4464, 4493), 'csv.writer', 'csv.writer', (['of'], {'delimiter': '"""|"""'}), "(of, delimiter='|')\n", (4474, 4493), False, 'import csv\n'), ((6075, 6108), 'os.path.isfile', 'os.path.isfile', (['self.act_utt_file'], {}), '(self.act_utt_file)\n', (6089, 6108), False, 'import os\n'), ((9308, 9330), 'swda.swda.CorpusReader', 'CorpusReader', (['data_dir'], {}), '(data_dir)\n', (9320, 9330), False, 'from swda.swda import CorpusReader, Transcript, Utterance\n'), ((9980, 10054), 'sklearn.model_selection.train_test_split', 'train_test_split', (['val_ixs'], {'shuffle': '(True)', 'train_size': '(0.5)', 'random_state': 'seed'}), '(val_ixs, shuffle=True, train_size=0.5, random_state=seed)\n', (9996, 10054), False, 'from sklearn.model_selection import train_test_split\n'), ((11003, 11012), 'collections.Counter', 'Counter', ([], {}), '()\n', (11010, 11012), False, 'from collections import Counter, defaultdict\n'), ((11285, 11324), 'os.path.join', 'os.path.join', (['self.data_dir', '"""itos.txt"""'], {}), "(self.data_dir, 'itos.txt')\n", (11297, 11324), False, 'import os\n'), ((2231, 2251), 'random.randint', 'random.randint', (['(0)', '(1)'], {}), '(0, 1)\n', (2245, 2251), False, 'import random\n'), ((2404, 2437), 'numpy.random.permutation', 'np.random.permutation', (['speaker_ix'], {}), '(speaker_ix)\n', (2425, 2437), True, 'import numpy as np\n'), ((3892, 3915), 'os.path.split', 'os.path.split', (['data_dir'], {}), '(data_dir)\n', (3905, 3915), False, 'import os\n'), ((5761, 5789), 'os.path.split', 'os.path.split', (['self.data_dir'], {}), '(self.data_dir)\n', (5774, 5789), False, 'import os\n'), ((5893, 5921), 'os.path.isdir', 'os.path.isdir', (['shuffled_path'], {}), '(shuffled_path)\n', (5906, 5921), False, 'import os\n'), ((5935, 5958), 'os.mkdir', 'os.mkdir', (['shuffled_path'], {}), '(shuffled_path)\n', (5943, 5958), False, 'import os\n'), ((5975, 6000), 'os.path.isfile', 'os.path.isfile', (['dial_file'], {}), '(dial_file)\n', (5989, 6000), False, 'import os\n'), ((6005, 6029), 'os.path.isfile', 'os.path.isfile', (['act_file'], {}), '(act_file)\n', (6019, 6029), False, 'import os\n'), ((6218, 6281), 'pandas.read_csv', 'pd.read_csv', (['f'], {'sep': '"""|"""', 'names': "['act', 'utt', 'dialogue', 'ix']"}), "(f, sep='|', names=['act', 'utt', 'dialogue', 'ix'])\n", (6229, 6281), True, 'import pandas as pd\n'), ((10279, 10325), 're.sub', 're.sub', (['"""([+/\\\\}\\\\[\\\\]]|\\\\{\\\\w)"""', '""""""', 'utt.text'], {}), "('([+/\\\\}\\\\[\\\\]]|\\\\{\\\\w)', '', utt.text)\n", (10285, 10325), False, 'import re\n'), ((10558, 10590), 'os.path.split', 'os.path.split', (['utt.swda_filename'], {}), '(utt.swda_filename)\n', (10571, 10590), False, 'import os\n'), ((11086, 11132), 're.sub', 're.sub', (['"""([+/\\\\}\\\\[\\\\]]|\\\\{\\\\w)"""', '""""""', 'utt.text'], {}), "('([+/\\\\}\\\\[\\\\]]|\\\\{\\\\w)', '', utt.text)\n", (11092, 11132), False, 'import re\n'), ((13105, 13125), 'random.randint', 'random.randint', (['(0)', '(1)'], {}), '(0, 1)\n', (13119, 13125), False, 'import random\n'), ((15925, 15948), 'random.choice', 'random.choice', (['segments'], {}), '(segments)\n', (15938, 15948), False, 'import random\n'), ((17187, 17215), 'os.path.isdir', 'os.path.isdir', (['shuffled_path'], {}), '(shuffled_path)\n', (17200, 17215), False, 'import os\n'), ((17229, 17252), 'os.mkdir', 'os.mkdir', (['shuffled_path'], {}), '(shuffled_path)\n', (17237, 17252), False, 'import os\n'), ((18676, 18715), 'os.path.join', 'os.path.join', (['shuffled_path', 'swda_fname'], {}), '(shuffled_path, swda_fname)\n', (18688, 18715), False, 'import os\n'), ((22971, 23009), 'os.path.join', 'os.path.join', (['args.datadir', '"""itos.txt"""'], {}), "(args.datadir, 'itos.txt')\n", (22983, 23009), False, 'import os\n'), ((3224, 3244), 'copy.deepcopy', 'deepcopy', (['ix_removed'], {}), '(ix_removed)\n', (3232, 3244), False, 'from copy import deepcopy\n'), ((7638, 7651), 'csv.writer', 'csv.writer', (['f'], {}), '(f)\n', (7648, 7651), False, 'import csv\n'), ((14947, 14965), 'copy.deepcopy', 'deepcopy', (['segments'], {}), '(segments)\n', (14955, 14965), False, 'from copy import deepcopy\n'), ((16573, 16609), 'os.path.join', 'os.path.join', (['self.data_dir', '"""train"""'], {}), "(self.data_dir, 'train')\n", (16585, 16609), False, 'import os\n'), ((16636, 16672), 'os.path.join', 'os.path.join', (['self.data_dir', '"""train"""'], {}), "(self.data_dir, 'train')\n", (16648, 16672), False, 'import os\n'), ((16704, 16745), 'os.path.join', 'os.path.join', (['self.data_dir', '"""validation"""'], {}), "(self.data_dir, 'validation')\n", (16716, 16745), False, 'import os\n'), ((16772, 16813), 'os.path.join', 'os.path.join', (['self.data_dir', '"""validation"""'], {}), "(self.data_dir, 'validation')\n", (16784, 16813), False, 'import os\n'), ((16845, 16880), 'os.path.join', 'os.path.join', (['self.data_dir', '"""test"""'], {}), "(self.data_dir, 'test')\n", (16857, 16880), False, 'import os\n'), ((16907, 16942), 'os.path.join', 'os.path.join', (['self.data_dir', '"""test"""'], {}), "(self.data_dir, 'test')\n", (16919, 16942), False, 'import os\n'), ((17534, 17580), 're.sub', 're.sub', (['"""([+/\\\\}\\\\[\\\\]]|\\\\{\\\\w)"""', '""""""', 'utt.text'], {}), "('([+/\\\\}\\\\[\\\\]]|\\\\{\\\\w)', '', utt.text)\n", (17540, 17580), False, 'import re\n'), ((18611, 18645), 'os.path.split', 'os.path.split', (['trans.swda_filename'], {}), '(trans.swda_filename)\n', (18624, 18645), False, 'import os\n'), ((18800, 18813), 'csv.writer', 'csv.writer', (['f'], {}), '(f)\n', (18810, 18813), False, 'import csv\n'), ((8302, 8316), 'copy.deepcopy', 'deepcopy', (['acts'], {}), '(acts)\n', (8310, 8316), False, 'from copy import deepcopy\n'), ((8447, 8465), 'copy.deepcopy', 'deepcopy', (['tok_seqs'], {}), '(tok_seqs)\n', (8455, 8465), False, 'from copy import deepcopy\n'), ((19499, 19513), 'copy.deepcopy', 'deepcopy', (['acts'], {}), '(acts)\n', (19507, 19513), False, 'from copy import deepcopy\n'), ((19644, 19664), 'copy.deepcopy', 'deepcopy', (['utterances'], {}), '(utterances)\n', (19652, 19664), False, 'from copy import deepcopy\n'), ((13569, 13607), 'numpy.random.permutation', 'np.random.permutation', (['speaker_to_perm'], {}), '(speaker_to_perm)\n', (13590, 13607), True, 'import numpy as np\n')]
from typing import Optional, Tuple, Union import numpy as np import pandas as pd import pyvista as pv from pyvista import DataSet, MultiBlock, PolyData, UnstructuredGrid try: from typing import Literal except ImportError: from typing_extensions import Literal from .ddrtree import DDRTree, cal_ncenter from .slice import euclidean_distance, three_d_slice #################################### # Changes along a vector direction # #################################### def changes_along_line( model: Union[PolyData, UnstructuredGrid], key: Union[str, list] = None, n_points: int = 100, vec: Union[tuple, list] = (1, 0, 0), center: Union[tuple, list] = None, ) -> Tuple[np.ndarray, np.ndarray, MultiBlock, MultiBlock]: slices, line_points, line = three_d_slice( model=model, method="line", n_slices=n_points, vec=vec, center=center ) x, y = [], [] x_length = 0 for slice, (point_i, point) in zip(slices, enumerate(line_points)): change_value = np.asarray(slice[key]).sum() y.append(change_value) if point_i == 0: x.append(0) else: point1 = line_points[point_i - 1].points.flatten() point2 = line_points[point_i].points.flatten() ed = euclidean_distance(instance1=point1, instance2=point2, dimension=3) x_length += ed x.append(x_length) return np.asarray(x), np.asarray(y), slices, line ################################# # Changes along the model shape # ################################# def changes_along_shape( model: Union[PolyData, UnstructuredGrid], spatial_key: Optional[str] = None, key_added: Optional[str] = "rd_spatial", dim: int = 2, inplace: bool = False, **kwargs, ): model = model.copy() if not inplace else model X = model.points if spatial_key is None else model[spatial_key] DDRTree_kwargs = { "maxIter": 10, "sigma": 0.001, "gamma": 10, "eps": 0, "dim": dim, "Lambda": 5 * X.shape[1], "ncenter": cal_ncenter(X.shape[1]), } DDRTree_kwargs.update(kwargs) Z, Y, stree, R, W, Q, C, objs = DDRTree(X, **DDRTree_kwargs) # Obtain the real part of the complex argument model[key_added] = np.real(W).astype(np.float64) return model if not inplace else None ############################## # Changes along the branches # ############################## def ElPiGraph_tree( X: np.ndarray, NumNodes: int = 50, **kwargs, ) -> Tuple[np.ndarray, np.ndarray]: """ Generate a principal elastic tree. Reference: Albergante et al. (2020), Robust and Scalable Learning of Complex Intrinsic Dataset Geometry via ElPiGraph. Args: X: DxN, data matrix list. NumNodes: The number of nodes of the principal graph. Use a range of 10 to 100 for ElPiGraph approach. **kwargs: Other parameters used in elpigraph.computeElasticPrincipalTree. For details, please see: https://github.com/j-bac/elpigraph-python/blob/master/elpigraph/_topologies.py Returns: nodes: The nodes in the principal tree. edges: The edges between nodes in the principal tree. """ try: import elpigraph except ImportError: raise ImportError( "You need to install the package `elpigraph-python`." "\nInstall elpigraph-python via `pip install git+https://github.com/j-bac/elpigraph-python.git`." ) ElPiGraph_kwargs = { "alpha": 0.01, "FinalEnergy": "Penalized", "StoreGraphEvolution": True, "GPU": False, } ElPiGraph_kwargs.update(kwargs) if ElPiGraph_kwargs["GPU"] is True: try: import cupy except ImportError: raise ImportError( "You need to install the package `cupy`." "\nInstall cupy via `pip install cupy-cuda113`." ) elpi_tree = elpigraph.computeElasticPrincipalTree( X=np.asarray(X), NumNodes=NumNodes, **ElPiGraph_kwargs ) nodes = elpi_tree[0]["NodePositions"] # ['AllNodePositions'][k] matrix_edges_weights = elpi_tree[0]["ElasticMatrix"] # ['AllElasticMatrices'][k] matrix_edges_weights = np.triu(matrix_edges_weights, 1) edges = np.array(np.nonzero(matrix_edges_weights), dtype=int).transpose() return nodes, edges def SimplePPT_tree( X: np.ndarray, NumNodes: int = 50, **kwargs, ) -> Tuple[np.ndarray, np.ndarray]: """ Generate a simple principal tree. Reference: Mao et al. (2015), SimplePPT: A simple principal tree algorithm, SIAM International Conference on Data Mining. Args: X: DxN, data matrix list. NumNodes: The number of nodes of the principal graph. Use a range of 100 to 2000 for PPT approach. **kwargs: Other parameters used in simpleppt.ppt. For details, please see: https://github.com/LouisFaure/simpleppt/blob/main/simpleppt/ppt.py Returns: nodes: The nodes in the principal tree. edges: The edges between nodes in the principal tree. """ try: import igraph import simpleppt except ImportError: raise ImportError( "You need to install the package `simpleppt` and `igraph`." "\nInstall simpleppt via `pip install -U simpleppt`." "\nInstall igraph via `pip install -U igraph`" ) SimplePPT_kwargs = { "seed": 1, "lam": 10, } SimplePPT_kwargs.update(kwargs) X = np.asarray(X) ppt_tree = simpleppt.ppt(X=X, Nodes=NumNodes, **SimplePPT_kwargs) R = ppt_tree.R nodes = (np.dot(X.T, R) / R.sum(axis=0)).T B = ppt_tree.B edges = np.array( igraph.Graph.Adjacency((B > 0).tolist(), mode="undirected").get_edgelist() ) return nodes, edges def map_points_to_branch( model: Union[PolyData, UnstructuredGrid], nodes: np.ndarray, spatial_key: Optional[str] = None, key_added: Optional[str] = "nodes", inplace: bool = False, **kwargs, ): """ Find the closest principal tree node to any point in the model through KDTree. Args: model: A reconstruct model. nodes: The nodes in the principal tree. spatial_key: The key that corresponds to the coordinates of the point in the model. If spatial_key is None, the coordinates are model.points. key_added: The key under which to add the nodes labels. inplace: Updates model in-place. kwargs: Other parameters used in scipy.spatial.KDTree. Returns: A model, which contains the following properties: `model.point_data[key_added]`, the nodes labels array. """ from scipy.spatial import KDTree model = model.copy() if not inplace else model X = model.points if spatial_key is None else model[spatial_key] nodes_kdtree = KDTree(np.asarray(nodes), **kwargs) _, ii = nodes_kdtree.query(np.asarray(X), k=1) model.point_data[key_added] = ii return model if not inplace else None def map_gene_to_branch( model: Union[PolyData, UnstructuredGrid], tree: PolyData, key: Union[str, list], nodes_key: Optional[str] = "nodes", inplace: bool = False, ): """ Find the closest principal tree node to any point in the model through KDTree. Args: model: A reconstruct model contains the gene expression label. tree: A three-dims principal tree model contains the nodes label. key: The key that corresponds to the gene expression. nodes_key: The key that corresponds to the coordinates of the nodes in the tree. inplace: Updates tree model in-place. Returns: A tree, which contains the following properties: `tree.point_data[key]`, the gene expression array. """ model = model.copy() model_data = pd.DataFrame(model[nodes_key], columns=["nodes_id"]) key = [key] if isinstance(key, str) else key for sub_key in key: model_data[sub_key] = np.asarray(model[sub_key]) model_data = model_data.groupby(by="nodes_id").sum() model_data["nodes_id"] = model_data.index model_data.index = range(len(model_data.index)) tree = tree.copy() if not inplace else tree tree_data = pd.DataFrame(tree[nodes_key], columns=["nodes_id"]) tree_data = pd.merge(tree_data, model_data, how="outer", on="nodes_id") tree_data.fillna(value=0, inplace=True) for sub_key in key: tree.point_data[sub_key] = tree_data[sub_key].values return tree if not inplace else None def construct_tree_model( nodes: np.ndarray, edges: np.ndarray, key_added: Optional[str] = "nodes", ) -> PolyData: """ Construct a principal tree model. Args: nodes: The nodes in the principal tree. edges: The edges between nodes in the principal tree. key_added: The key under which to add the nodes labels. Returns: A three-dims principal tree model, which contains the following properties: `tree_model.point_data[key_added]`, the nodes labels array. """ padding = np.empty(edges.shape[0], int) * 2 padding[:] = 2 edges_w_padding = np.vstack((padding, edges.T)).T tree_model = pv.PolyData(nodes, edges_w_padding) tree_model.point_data[key_added] = np.arange(0, len(nodes), 1) return tree_model def changes_along_branch( model: Union[PolyData, UnstructuredGrid], spatial_key: Optional[str] = None, map_key: Union[str, list] = None, key_added: Optional[str] = "nodes", rd_method: Literal["ElPiGraph", "SimplePPT"] = "ElPiGraph", NumNodes: int = 50, inplace: bool = False, **kwargs, ) -> Tuple[Union[DataSet, PolyData, UnstructuredGrid], PolyData]: model = model.copy() if not inplace else model X = model.points if spatial_key is None else model[spatial_key] if rd_method == "ElPiGraph": nodes, edges = ElPiGraph_tree(X=X, NumNodes=NumNodes, **kwargs) elif rd_method == "SimplePPT": nodes, edges = SimplePPT_tree(X=X, NumNodes=NumNodes, **kwargs) else: raise ValueError( "`rd_method` value is wrong." "\nAvailable `rd_method` are: `'ElPiGraph'`, `'SimplePPT'`." ) map_points_to_branch( model=model, nodes=nodes, spatial_key=spatial_key, key_added=key_added, inplace=True, ) tree_model = construct_tree_model(nodes=nodes, edges=edges) if not (map_key is None): map_gene_to_branch( model=model, tree=tree_model, key=map_key, nodes_key=key_added, inplace=True ) return model if not inplace else None, tree_model
[ "simpleppt.ppt", "pyvista.PolyData", "pandas.merge", "numpy.asarray", "numpy.real", "numpy.dot", "numpy.empty", "numpy.vstack", "numpy.nonzero", "pandas.DataFrame", "numpy.triu" ]
[((4270, 4302), 'numpy.triu', 'np.triu', (['matrix_edges_weights', '(1)'], {}), '(matrix_edges_weights, 1)\n', (4277, 4302), True, 'import numpy as np\n'), ((5574, 5587), 'numpy.asarray', 'np.asarray', (['X'], {}), '(X)\n', (5584, 5587), True, 'import numpy as np\n'), ((5603, 5657), 'simpleppt.ppt', 'simpleppt.ppt', ([], {'X': 'X', 'Nodes': 'NumNodes'}), '(X=X, Nodes=NumNodes, **SimplePPT_kwargs)\n', (5616, 5657), False, 'import simpleppt\n'), ((7935, 7987), 'pandas.DataFrame', 'pd.DataFrame', (['model[nodes_key]'], {'columns': "['nodes_id']"}), "(model[nodes_key], columns=['nodes_id'])\n", (7947, 7987), True, 'import pandas as pd\n'), ((8339, 8390), 'pandas.DataFrame', 'pd.DataFrame', (['tree[nodes_key]'], {'columns': "['nodes_id']"}), "(tree[nodes_key], columns=['nodes_id'])\n", (8351, 8390), True, 'import pandas as pd\n'), ((8407, 8466), 'pandas.merge', 'pd.merge', (['tree_data', 'model_data'], {'how': '"""outer"""', 'on': '"""nodes_id"""'}), "(tree_data, model_data, how='outer', on='nodes_id')\n", (8415, 8466), True, 'import pandas as pd\n'), ((9316, 9351), 'pyvista.PolyData', 'pv.PolyData', (['nodes', 'edges_w_padding'], {}), '(nodes, edges_w_padding)\n', (9327, 9351), True, 'import pyvista as pv\n'), ((1414, 1427), 'numpy.asarray', 'np.asarray', (['x'], {}), '(x)\n', (1424, 1427), True, 'import numpy as np\n'), ((1429, 1442), 'numpy.asarray', 'np.asarray', (['y'], {}), '(y)\n', (1439, 1442), True, 'import numpy as np\n'), ((6957, 6974), 'numpy.asarray', 'np.asarray', (['nodes'], {}), '(nodes)\n', (6967, 6974), True, 'import numpy as np\n'), ((7017, 7030), 'numpy.asarray', 'np.asarray', (['X'], {}), '(X)\n', (7027, 7030), True, 'import numpy as np\n'), ((8091, 8117), 'numpy.asarray', 'np.asarray', (['model[sub_key]'], {}), '(model[sub_key])\n', (8101, 8117), True, 'import numpy as np\n'), ((9192, 9221), 'numpy.empty', 'np.empty', (['edges.shape[0]', 'int'], {}), '(edges.shape[0], int)\n', (9200, 9221), True, 'import numpy as np\n'), ((9267, 9296), 'numpy.vstack', 'np.vstack', (['(padding, edges.T)'], {}), '((padding, edges.T))\n', (9276, 9296), True, 'import numpy as np\n'), ((2287, 2297), 'numpy.real', 'np.real', (['W'], {}), '(W)\n', (2294, 2297), True, 'import numpy as np\n'), ((4028, 4041), 'numpy.asarray', 'np.asarray', (['X'], {}), '(X)\n', (4038, 4041), True, 'import numpy as np\n'), ((5691, 5705), 'numpy.dot', 'np.dot', (['X.T', 'R'], {}), '(X.T, R)\n', (5697, 5705), True, 'import numpy as np\n'), ((1011, 1033), 'numpy.asarray', 'np.asarray', (['slice[key]'], {}), '(slice[key])\n', (1021, 1033), True, 'import numpy as np\n'), ((4324, 4356), 'numpy.nonzero', 'np.nonzero', (['matrix_edges_weights'], {}), '(matrix_edges_weights)\n', (4334, 4356), True, 'import numpy as np\n')]
# sacher_epos.py, python wrapper for sacher epos motor # <NAME> <<EMAIL>>, August 2014 # """ Possbily Maxon EPOS now """ """ This is the actual version that works But only in the lab32 virtual environment """ # from instrument import Instrument # import qt import ctypes import ctypes.wintypes import logging import time # from instrument import Instrument from ctypes.wintypes import DWORD, WORD import numpy as np """ okay so we import a bunch of random stuff I always forget what ctypes is for but I'll worry about it later """ # from subprocess import Popen, PIPE # from multiprocessing.managers import BaseManager # import atexit # import os # python32_dir = "C:\\Users\\Alex\\Miniconda3\\envs\\lab32" # assert os.path.isdir(python32_dir) # os.chdir(python32_dir) # derp = "C:\\Users\\Alex\\Documents\\wow_such_code" # assert os.path.isdir(derp) # os.chdir(derp) # p = Popen([python32_dir + "\\python.exe", derp + "\\delegate.py"], stdout=PIPE, cwd=derp) # atexit.register(p.terminate) # port = int(p.stdout.readline()) # authkey = p.stdout.read() # print(port, authkey) # m = BaseManager(address=("localhost", port), authkey=authkey) # m.connect() # tell manager to expect an attribute called LibC # m.register("SacherLasaTeknique") # access and use libc # libc = m.SacherLasaTeknique() # print(libc.vcs()) # eposlib = ctypes.windll.eposcmd eposlib = ctypes.windll.LoadLibrary('C:\\Users\\Carbro\\Desktop\\Charmander\\EposCmd.dll') DeviceName = b'EPOS' ProtocolStackName = b'MAXON_RS232' InterfaceName = b'RS232' """ Max on Max off but anyway it looks like ctypes is the thing that's talking to the epos dll """ HISTCHAN = 65536 TTREADMAX = 131072 RANGES = 8 MODE_HIST = 0 MODE_T2 = 2 MODE_T3 = 3 FLAG_OVERFLOW = 0x0040 FLAG_FIFOFULL = 0x0003 # in mV ZCMIN = 0 ZCMAX = 20 DISCRMIN = 0 DISCRMAX = 800 # in ps OFFSETMIN = 0 OFFSETMAX = 1000000000 # in ms ACQTMIN = 1 ACQTMAX = 10 * 60 * 60 * 1000 # in mV PHR800LVMIN = -1600 PHR800LVMAX = 2400 """ wooooooo a bunch a variables and none of them are explained way to go dc you da real champ """ class Sacher_EPOS(): """ ok before I dive into this giant Sacher class thing let me just list here all the functions that are being defined in this class: check(self) before wreck(self) ok but actually: __init__(self, name, address, reset=False) __del__(self) get_bit(self, byteval,idx) _u32todouble(self, uinput) open(self) close(self) get_offset(self) fine_tuning_steps(self, steps) set_new_offset(self, new_offset) get_motor_position(self) set_target_position(self, target, absolute, immediately) do_get_wavelength(self) do_set_wavelength(self, wavelength) is_open(self) clear_fault(self) initialize(self) The last one is really long And also damn there are 16 of them I'll comment about them as I go through them """ def __init__(self, name, address, reset=False): # Instrument.__init__(self, name, tags=['physical']) # self._port_name = str(address) self._port_name = address self._is_open = False self._HPM = True # self.add_parameter('wavelength', # flags = Instrument.FLAG_GETSET, # type = types.FloatType, # units = 'nm', # minval=1070.0,maxval=1180.0) # self.add_function('open') # self.add_function('close') # self.add_function('fine_tuning_steps') # self.add_function('get_motor_position') # self.add_function('set_target_position') # try: self.open() self.initialize() # except: # logging.error('Error loading Sacher EPOS motor. In use?') """ I mean to me this really seems like the initialize function so I wonder what initialize(self) is doing At any rate there doesn't seem to be a lot going on here """ def __del__(self): # execute disconnect self.close() return """ this might be the only self explanatory one it disconnects """ @staticmethod def get_bit(byteval, idx): # def get_bit(self, byteval,idx): return ((byteval & (1 << idx)) != 0) """ you get the bits, and then you use them but honestly I don't really get what this is doing sudo git a_clue """ @staticmethod def _u32todouble(uinput): # def _u32todouble(self, uinput): # this function implements the really weird/non-standard U32 to # floating point conversion in the sacher VIs # get sign of number sign = Sacher_EPOS.get_bit(uinput, 31) if sign == False: mantissa_sign = 1 elif sign == True: mantissa_sign = -1 exp_mask = 0b111111 # print 'uin u is %d' % uinput # print 'type uin %s' % type(uinput) # print 'binary input is %s' % bin(long(uinput)) # get sign of exponent if Sacher_EPOS.get_bit(uinput, 7) == False: exp_sign = 1 elif Sacher_EPOS.get_bit(uinput, 7) == True: exp_sign = -1 # print 'exp extract %s' % bin(int(uinput & exp_mask)) # print 'exp conv %s' % (exp_sign*int(uinput & exp_mask)) # print 'sign of exponent %s' % self.get_bit(uinput,7) # print 'binary constant is %s' % bin(int(0b10000000000000000000000000000000)) mantissa_mask = 0b01111111111111111111111100000000 # mantissa_mask = 0b0111111111111111111111110000000 # print 'mantissa extract is %s' % bin((uinput & mantissa_mask) >> 8) mantissa = 1.0 / 1000000.0 * float(mantissa_sign) * float((uinput & mantissa_mask) >> 8) # print 'mantissa is %.12f' % mantissa # print(1 if Sacher_EPOS.get_bit(uinput,31) else 0, mantissa, 1 if Sacher_EPOS.get_bit(uinput,7) else 0, uinput & exp_mask) output = mantissa * 2.0 ** (float(exp_sign) * float(int(uinput & exp_mask))) # print 'output is %s' % output return output """ ok dc gave some slight explanations here Apparently there's a "really weird/non-standard U32 to floating point conversion in the sacher VIs" It'd be gr8 if I knew what U32's were unsigned 32 bit something something? ah whatever I'll have to worry about this later """ @staticmethod def _doubletou32(dinput): mantissa_bit = 0 if int(dinput / abs(dinput)) > 0 else 1 exp_bit = 1 if -1 < dinput < 1 else 0 b = np.ceil(np.log10(abs(dinput))) a = dinput / 10 ** b if dinput < 0: a = -a # print('a:\t{}\tb:\t{}'.format(a, b)) d = np.log2(10) * b d_ = np.ceil(d) c = a * 2 ** (d - d_) # print('c:\t{}\td_:{}\toriginal:\t{}'.format(c, d_, c * 2 ** d_)) return (int(mantissa_bit) << 31) + (int(c * 1e6) << 8) + (int(exp_bit) << 7) + int(abs(d_)) def open(self): eposlib.VCS_OpenDevice.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p, ctypes.POINTER(DWORD)] eposlib.VCS_OpenDevice.restype = ctypes.wintypes.HANDLE buf = ctypes.pointer(DWORD(0)) ret = ctypes.wintypes.HANDLE() # print 'types are all %s %s %s %s %s' % (type(DeviceName), type(ProtocolStackName), type(InterfaceName), type(self._port_name), type(buf)) ret = eposlib.VCS_OpenDevice(DeviceName, ProtocolStackName, InterfaceName, self._port_name, buf) self._keyhandle = ret # print 'keyhandle is %s' % self._keyhandle # print 'open device ret %s' % buf # print 'printing' # print buf.contents.value # print 'done printer' if int(buf.contents.value) >= 0: self._is_open = True self._keyhandle = ret return """ I have absolutely no idea what the hell this is doing Considering that close(self) is apparently closing the EPOS motor, maybe this is opening it """ def close(self): print('closing EPOS motor.') eposlib.VCS_CloseDevice.argtypes = [ctypes.wintypes.HANDLE, ctypes.POINTER(DWORD)] eposlib.VCS_CloseDevice.restype = ctypes.wintypes.BOOL buf = ctypes.pointer(DWORD(0)) ret = ctypes.wintypes.BOOL() ret = eposlib.VCS_CloseDevice(self._keyhandle, buf) # print 'close device returned %s' % buf if int(buf.contents.value) >= 0: self._is_open = False else: logging.error(__name__ + ' did not close Sacher EPOS motor correctly.') return """ Apparently this closes the EPOS motor I don't know what "opening" and "closing" the motor means though and yeah also these random variables don't make any sense to me """ def get_motor_current(self): nodeID = ctypes.wintypes.WORD(0) eposlib.VCS_GetCurrentIs.argtypes = [ctypes.wintypes.HANDLE, ctypes.wintypes.WORD, ctypes.POINTER(ctypes.c_uint8), ctypes.POINTER(ctypes.wintypes.DWORD)] eposlib.VCS_GetCurrentIs.restype = ctypes.wintypes.BOOL motorCurrent = ctypes.c_uint8(0) buf = ctypes.wintypes.DWORD(0) ret = eposlib.VCS_GetCurrentIs(self._keyhandle, nodeID, ctypes.byref(motorCurrent), ctypes.byref(buf)) return motorCurrent.value """ Not sure what this is doing yet """ def find_home(self): nodeID = ctypes.wintypes.WORD(0) eposlib.VCS_FindHome.argtypes = [ctypes.wintypes.HANDLE, ctypes.wintypes.WORD, ctypes.c_uint8, ctypes.POINTER(ctypes.wintypes.DWORD)] eposlib.VCS_FindHome.restype = ctypes.wintypes.BOOL buf = ctypes.wintypes.DWORD(0) ret = eposlib.VCS_FindHome(self._keyhandle, nodeID, ctypes.c_uint8(35), ctypes.byref(buf)) print('Homing: {}'.format(ret)) return ret """ Not sure what this is doing yet """ def restore(self): nodeID = ctypes.wintypes.WORD(0) eposlib.VCS_FindHome.argtypes = [ctypes.wintypes.HANDLE, ctypes.wintypes.WORD, ctypes.POINTER(ctypes.wintypes.DWORD)] eposlib.VCS_FindHome.restype = ctypes.wintypes.BOOL buf = ctypes.wintypes.DWORD(0) ret = eposlib.VCS_Restore(self._keyhandle, nodeID, ctypes.byref(buf)) print('Restore: {}'.format(ret)) return ret """ Not sure what this is doing yet """ def get_offset(self): nodeID = ctypes.wintypes.WORD(0) buf = ctypes.wintypes.DWORD(0) eposlib.VCS_GetObject.argtypes = [ctypes.wintypes.HANDLE, ctypes.wintypes.WORD, ctypes.wintypes.WORD, ctypes.c_uint8, ctypes.c_void_p, ctypes.wintypes.DWORD, ctypes.POINTER(ctypes.wintypes.DWORD), ctypes.POINTER(ctypes.wintypes.DWORD)] eposlib.VCS_GetObject.restype = ctypes.wintypes.BOOL # These are hardcoded values I got from the LabVIEW program -- I don't think # any documentation exists on particular object indices StoredPositionObject = ctypes.wintypes.WORD(8321) StoredPositionObjectSubindex = ctypes.c_uint8(0) StoredPositionNbBytesToRead = ctypes.wintypes.DWORD(4) ObjectData = ctypes.c_void_p() ObjectDataArray = (ctypes.c_uint32 * 1)() ObjectData = ctypes.cast(ObjectDataArray, ctypes.POINTER(ctypes.c_int32)) StoredPositionNbBytesRead = ctypes.pointer(ctypes.wintypes.DWORD(0)) ret = eposlib.VCS_GetObject(self._keyhandle, nodeID, StoredPositionObject, StoredPositionObjectSubindex, ObjectData, StoredPositionNbBytesToRead, StoredPositionNbBytesRead, ctypes.byref(buf)) # Cast the object data to uint32 CastedObjectData = ctypes.cast(ObjectData, ctypes.POINTER(ctypes.c_int32)) if ret == 0: logging.error(__name__ + ' Could not read stored position from Sacher EPOS motor') return CastedObjectData[0] """ Not sure what this is doing yet """ def fine_tuning_steps(self, steps): current_motor_pos = self.get_motor_position() self._offset = self.get_offset() self.set_target_position(steps, False, True) new_motor_pos = self.get_motor_position() # print('New motor position is %s' % new_motor_pos) # print 'new offset is %s' % (new_motor_pos-current_motor_pos+self._offset) self.set_new_offset(new_motor_pos - current_motor_pos + self._offset) """ Not sure what this is doing yet """ def set_new_offset(self, new_offset): nodeID = ctypes.wintypes.WORD(0) buf = ctypes.wintypes.DWORD(0) eposlib.VCS_SetObject.argtypes = [ctypes.wintypes.HANDLE, ctypes.wintypes.WORD, ctypes.wintypes.WORD, ctypes.c_uint8, ctypes.POINTER(ctypes.wintypes.DWORD), ctypes.wintypes.DWORD, ctypes.POINTER(ctypes.wintypes.DWORD), ctypes.POINTER(ctypes.wintypes.DWORD)] eposlib.VCS_SetObject.restype = ctypes.wintypes.BOOL # print 'setting new offset' StoredPositionObject = ctypes.wintypes.WORD(8321) StoredPositionObjectSubindex = ctypes.c_uint8(0) StoredPositionNbBytesToWrite = ctypes.wintypes.DWORD(4) ObjectDataArray = (ctypes.c_uint32 * 1)(new_offset) ObjectData = ctypes.cast(ObjectDataArray, ctypes.POINTER(ctypes.c_uint32)) StoredPositionNbBytesWritten = ctypes.pointer(ctypes.wintypes.DWORD(0)) ret = eposlib.VCS_SetObject(self._keyhandle, nodeID, StoredPositionObject, StoredPositionObjectSubindex, ObjectData, StoredPositionNbBytesToWrite, StoredPositionNbBytesWritten, ctypes.byref(buf)) if ret == 0: logging.error(__name__ + ' Could not write stored position from Sacher EPOS motor') return """ Not sure what this is doing yet """ def set_coeffs(self, a, b, c, min_wl, max_wl): print('') print("setting coefficients...") nodeID = ctypes.wintypes.WORD(0) buf = ctypes.wintypes.DWORD(0) eposlib.VCS_SetObject.argtypes = [ctypes.wintypes.HANDLE, ctypes.wintypes.WORD, ctypes.wintypes.WORD, ctypes.c_uint8, ctypes.POINTER(ctypes.wintypes.DWORD), ctypes.wintypes.DWORD, ctypes.POINTER(ctypes.wintypes.DWORD), ctypes.POINTER(ctypes.wintypes.DWORD)] eposlib.VCS_SetObject.restype = ctypes.wintypes.BOOL # print 'setting new offset' d = (min_wl << 16) + max_wl StoredPositionObject = ctypes.wintypes.WORD(8204) for subidx, coeff in enumerate([a, b, c]): print(subidx, coeff) StoredPositionObjectSubindex = ctypes.c_uint8(subidx + 1) StoredPositionNbBytesToWrite = ctypes.wintypes.DWORD(4) ObjectDataArray = (ctypes.c_uint32 * 1)(self._doubletou32(coeff)) ObjectData = ctypes.cast(ObjectDataArray, ctypes.POINTER(ctypes.c_uint32)) StoredPositionNbBytesWritten = ctypes.pointer(ctypes.wintypes.DWORD(0)) ret = eposlib.VCS_SetObject(self._keyhandle, nodeID, StoredPositionObject, StoredPositionObjectSubindex, ObjectData, StoredPositionNbBytesToWrite, StoredPositionNbBytesWritten, ctypes.byref(buf)) StoredPositionObjectSubindex = ctypes.c_uint8(4) StoredPositionNbBytesToWrite = ctypes.wintypes.DWORD(4) ObjectDataArray = (ctypes.c_uint32 * 1)(d) ObjectData = ctypes.cast(ObjectDataArray, ctypes.POINTER(ctypes.c_uint32)) StoredPositionNbBytesWritten = ctypes.pointer(ctypes.wintypes.DWORD(0)) ret = eposlib.VCS_SetObject(self._keyhandle, nodeID, StoredPositionObject, StoredPositionObjectSubindex, ObjectData, StoredPositionNbBytesToWrite, StoredPositionNbBytesWritten, ctypes.byref(buf)) print('Coefficients are %s %s %s' % (self._doubleA, self._doubleB, self._doubleC)) if ret == 0: logging.error(__name__ + ' Could not write stored position from Sacher EPOS motor') return """ Not sure what this is doing yet """ def get_motor_position(self): nodeID = ctypes.wintypes.WORD(0) buf = ctypes.wintypes.DWORD(0) pPosition = ctypes.pointer(ctypes.c_long()) eposlib.VCS_GetPositionIs.argtypes = [ctypes.wintypes.HANDLE, ctypes.wintypes.WORD, ctypes.POINTER(ctypes.c_long), ctypes.POINTER(ctypes.wintypes.DWORD)] eposlib.VCS_GetPositionIs.restype = ctypes.wintypes.BOOL ret = eposlib.VCS_GetPositionIs(self._keyhandle, nodeID, pPosition, ctypes.byref(buf)) # print 'get motor position ret %s' % ret # print 'get motor position buf %s' % buf.value # print 'get motor position value %s' % pPosition.contents.value return pPosition.contents.value # print('getting motor position...') # print(ret) # return print(pPosition.contents.value) """ Not sure what this is doing yet """ def set_target_position(self, target, absolute, immediately): # print('check #1') nodeID = ctypes.wintypes.WORD(0) buf = ctypes.wintypes.DWORD(0) # First, set enabled state # print('#5 Motor current: {}'.format(self.get_motor_current())) # print('#5 Motor current: {}'.format(self.get_motor_current())) # print('#5 Motor current: {}'.format(self.get_motor_current())) # print('#5 Motor current: {}'.format(self.get_motor_current())) # print('#5 Motor current: {}'.format(self.get_motor_current())) ret = eposlib.VCS_SetEnableState(self._keyhandle, nodeID, ctypes.byref(buf)) # print('Enable state ret %s buf %s' % (ret, buf.value)) # print('#6 Motor current: {}'.format(self.get_motor_current())) # print('#6 Motor current: {}'.format(self.get_motor_current())) # print('#6 Motor current: {}'.format(self.get_motor_current())) # print('#6 Motor current: {}'.format(self.get_motor_current())) # print('#6 Motor current: {}'.format(self.get_motor_current())) pTarget = ctypes.c_long(target) pAbsolute = ctypes.wintypes.BOOL(absolute) pImmediately = ctypes.wintypes.BOOL(immediately) eposlib.VCS_MoveToPosition.argtypes = [ctypes.wintypes.HANDLE, ctypes.wintypes.WORD, ctypes.c_long, ctypes.wintypes.BOOL, ctypes.wintypes.BOOL, ctypes.POINTER(ctypes.wintypes.DWORD)] eposlib.VCS_MoveToPosition.restype = ctypes.wintypes.BOOL # print('check #2') # print('About to set motor position') # print('Current motor position is %d' % (self.get_motor_position())) ret = eposlib.VCS_MoveToPosition(self._keyhandle, nodeID, pTarget, pAbsolute, pImmediately, ctypes.byref(buf)) # print('#7 Motor current: {}'.format(self.get_motor_current())) # print('#7 Motor current: {}'.format(self.get_motor_current())) # print('#7 Motor current: {}'.format(self.get_motor_current())) # print('#7 Motor current: {}'.format(self.get_motor_current())) # print('#7 Motor current: {}'.format(self.get_motor_current())) # print('set motor position ret %s' % ret) # print('set motor position buf %s' % buf.value) steps_per_second = 14494.0 # hardcoded, estimated roughly, unused now nchecks = 0 # print('check #3') while nchecks < 1000: # get the movement state. a movement state of 1 indicates the motor # is done moving # print('') # print('check #4') # print('Motor current: {}'.format(self.get_motor_current())) print('Motor position: {}'.format(self.get_motor_position())) # print('Motor offset: {}'.format(self.get_offset())) self._offset = self.get_offset() # print('Motor offset is %s' % self._offset) pMovementState = ctypes.pointer(ctypes.wintypes.BOOL()) # print(pMovementState.contents.value) eposlib.VCS_GetMovementState.argtypes = [ctypes.wintypes.HANDLE, ctypes.wintypes.WORD, ctypes.POINTER(ctypes.wintypes.BOOL), ctypes.POINTER(ctypes.wintypes.DWORD)] eposlib.VCS_GetMovementState.restype = ctypes.wintypes.BOOL # print('Getting movement state') ret = eposlib.VCS_GetMovementState(self._keyhandle, nodeID, pMovementState, ctypes.byref(buf)) # print('set motor position ret %s' % ret) # print('set motor position buf %s' % buf.value) # print('Movement state is %s' % pMovementState.contents.value) if pMovementState.contents.value == 1: break nchecks = nchecks + 1 # print('Current motor position is %d' % self.get_motor_position()) # print('check #5') # print(nchecks) # print('') time.sleep(0.01) # Now set disabled state ret = eposlib.VCS_SetDisableState(self._keyhandle, nodeID, ctypes.byref(buf)) # print('check #6') # print('Disable state ret %s buf %s' % (ret, buf.value)) # print('Final motor position is %d' % (self.get_motor_position())) # print('check #7') return ret """ Not sure what this is doing yet """ def fuck_my_life(self, wavelength): print('goddamn this piece of shit') print('') print('Coefficients are %s %s %s' % (self._doubleA, self._doubleB, self._doubleC)) # print('#3 Motor current: {}'.format(self.get_motor_current())) nodeID = ctypes.wintypes.WORD(0) buf = ctypes.wintypes.DWORD(0) # Step 1: Get the actual motor position # print('Getting motor position') current_motor_pos = self.get_motor_position() # Step 2: Get the motor offset self._offset = self.get_offset() # print('Motor offset is %s' % self._offset) # Step 3: Convert the desired wavelength into a position # Check sign of position-to-wavelength pos0 = self._doubleA * (0.0) ** 2.0 + self._doubleB * 0.0 + self._doubleC pos5000 = self._doubleA * (5000.0) ** 2.0 + self._doubleB * 5000.0 + self._doubleC # logging.error(__name__ + ' Sacher wavelength calibration polynomials indicated a wrong wavelength direction') # If that's OK, use the quadratic formula to calculate the roots b2a = -1.0 * self._doubleB / (2.0 * self._doubleA) sqrtarg = self._doubleB ** 2.0 / (4.0 * self._doubleA ** 2.0) - (self._doubleC - wavelength) / self._doubleA # print('wut da fuuuu') # print(b2a) # print(sqrtarg) # print(pos0) # print(pos5000) if sqrtarg < 0.0: logging.error(__name__ + ' Negative value under square root sign -- something is wrong') if pos0 > pos5000: # Take the + square root solution x = b2a - np.sqrt(sqrtarg) elif pos0 < pos5000: x = b2a + np.sqrt(sqrtarg) print(b2a) print(np.sqrt(sqrtarg)) # print('Position is %s' % x) wavelength_to_pos = int(round(x)) # Step 4: Calculate difference between the output position and the stored offset # print('Step 4...') diff_wavelength_offset = wavelength_to_pos - int(self._offset) print('wavelength_to_pos: {}'.format(wavelength_to_pos)) print('diff_wavelength_offset: {}'.format(diff_wavelength_offset)) print('self._offset: {}'.format(int(self._offset))) """ Not sure what this is doing yet """ def do_get_wavelength(self): self._offset = self.get_offset() # self._currentwl = self._doubleA*(self._offset)**2.0 + self._doubleB*self._offset + self._doubleC self._currentwl = self._doubleA * ( self.get_motor_position()) ** 2.0 + self._doubleB * self.get_motor_position() + self._doubleC print('Current wavelength: %.3f nm' % self._currentwl) return self._currentwl """ Not sure what this is doing yet """ def do_set_wavelength(self, wavelength): print('setting wavelength...') print('') # print('Coefficients are %s %s %s' % (self._doubleA, self._doubleB, self._doubleC)) # print('#3 Motor current: {}'.format(self.get_motor_current())) nodeID = ctypes.wintypes.WORD(0) buf = ctypes.wintypes.DWORD(0) # Step 1: Get the actual motor position # print('Getting motor position') current_motor_pos = self.get_motor_position() # Step 2: Get the motor offset self._offset = self.get_offset() # print('Motor offset is %s' % self._offset) # Step 3: Convert the desired wavelength into a position # Check sign of position-to-wavelength pos0 = self._doubleA * (0.0) ** 2.0 + self._doubleB * 0.0 + self._doubleC pos5000 = self._doubleA * (5000.0) ** 2.0 + self._doubleB * 5000.0 + self._doubleC # logging.error(__name__ + ' Sacher wavelength calibration polynomials indicated a wrong wavelength direction') # If that's OK, use the quadratic formula to calculate the roots b2a = -1.0 * self._doubleB / (2.0 * self._doubleA) sqrtarg = self._doubleB ** 2.0 / (4.0 * self._doubleA ** 2.0) - (self._doubleC - wavelength) / self._doubleA # print('wut da fuuuu') # print(b2a) # print(sqrtarg) # print(pos0) # print(pos5000) if sqrtarg < 0.0: logging.error(__name__ + ' Negative value under square root sign -- something is wrong') if pos0 > pos5000: # Take the + square root solution x = b2a - np.sqrt(sqrtarg) elif pos0 < pos5000: x = b2a + np.sqrt(sqrtarg) # x is what the motor position should be # print('Position is %s' % x) wavelength_to_pos = int(round(x)) # Step 4: Calculate difference between the output position and the stored offset # print('Step 4...') diff_wavelength_offset = wavelength_to_pos - int(self._offset) # print('Diff wavelength offset %s' % diff_wavelength_offset) # Step 5: If HPM is activated and the wavelength position is lower, overshoot # the movement by 10,000 steps # print('Step 5...') # print('#4 Motor current: {}'.format(self.get_motor_current())) if 1 == 2: print('uh-oh') # if self._HPM and diff_wavelength_offset < 0: # # print('Overshooting by 10000') # # self.set_target_position(diff_wavelength_offset - 10000, False, True) # # Step 6: Set the real target position # # """ # HEY LOOK EVERYONE RIGHT ABOVE HERE THIS IS THE STUPID THING THAT'S NOT WORKING! # """ # # #print('Step 6a... diff wavelength') # # self.set_target_position(10000, False, True) else: # print('Step 6b... diff wavelength') # self.set_target_position(diff_wavelength_offset, False, True) """WRONG""" self.set_target_position(wavelength_to_pos, True, True) """this is the real shit right here I need to set the absolute position to true """ # self.set_target_position(10000, False, True) # Step 7: Get the actual motor position new_motor_pos = self.get_motor_position() # print('New motor position is %s' % new_motor_pos) # print('new offset is %s' % (new_motor_pos-current_motor_pos+self._offset)) self.set_new_offset(new_motor_pos - current_motor_pos + self._offset) # Step 8, get and print current wavelength # print('Current wavelength is %.3f' % self.do_get_wavelength()) # print('setting wavelength done') return """ Not sure what this is doing yet """ def is_open(self): return self._is_open """ Not sure what this is doing yet """ def clear_fault(self): nodeID = ctypes.wintypes.WORD(0) buf = ctypes.wintypes.DWORD(0) ret = eposlib.VCS_ClearFault(self._keyhandle, nodeID, ctypes.byref(buf)) print('clear fault buf %s, ret %s' % (buf, ret)) if ret == 0: errbuf = ctypes.create_string_buffer(64) eposlib.VCS_GetErrorInfo(buf, errbuf, WORD(64)) raise ValueError(errbuf.value) """ Not sure what this is doing yet """ def initialize(self): nodeID = ctypes.wintypes.WORD(0) buf = ctypes.wintypes.DWORD(0) BaudRate = DWORD(38400) Timeout = DWORD(100) ret = eposlib.VCS_SetProtocolStackSettings(self._keyhandle, BaudRate, Timeout, ctypes.byref(buf)) # print 'set protocol buf %s ret %s' % (buf, ret) if ret == 0: errbuf = ctypes.create_string_buffer(64) # eposlib.VCS_GetErrorInfo(buf, errbuf, WORD(64)) raise ValueError(errbuf.value) buf = ctypes.wintypes.DWORD(0) ret = eposlib.VCS_ClearFault(self._keyhandle, nodeID, ctypes.byref(buf)) # print 'clear fault buf %s, ret %s' % (buf, ret) if ret == 0: errbuf = ctypes.create_string_buffer(64) eposlib.VCS_GetErrorInfo(buf, errbuf, WORD(64)) raise ValueError(errbuf.value) buf = ctypes.wintypes.DWORD(0) plsenabled = ctypes.wintypes.DWORD(0) ret = eposlib.VCS_GetEnableState(self._keyhandle, nodeID, ctypes.byref(plsenabled), ctypes.byref(buf)) # print 'get enable state buf %s ret %s and en %s' % (buf, ret, plsenabled) if ret == 0: errbuf = ctypes.create_string_buffer(64) eposlib.VCS_GetErrorInfo(buf, errbuf, WORD(64)) raise ValueError(errbuf.value) if int(plsenabled.value) != 0: logging.warning(__name__ + ' EPOS motor enabled, disabling before proceeding.') ret = eposlib.VCS_SetDisableState(self._keyhandle, nodeID, ctypes.byref(buf)) if int(ret) != 0: logging.warning(__name__ + ' EPOS motor successfully disabled, proceeding') else: logging.error(__name__ + ' EPOS motor was not successfully disabled!') buf = ctypes.wintypes.DWORD(0) Counts = WORD(512) # incremental encoder counts in pulses per turn PositionSensorType = WORD(4) ret = eposlib.VCS_SetEncoderParameter(self._keyhandle, nodeID, Counts, PositionSensorType, ctypes.byref(buf)) ## if ret == int(0): ## print 'errr' ## errbuf = ctypes.create_string_buffer(64) ## print 'sending' ## eposlib.VCS_GetErrorInfo.restype = ctypes.wintypes.BOOL ## print 'boolerrorinfo' ## eposlib.VCS_GetErrorInfo.argtypes = [ctypes.wintypes.DWORD, ctypes.c_char_p, ctypes.wintypes.WORD] ## print 'arg' ## ## ret = eposlib.VCS_GetErrorInfo(buf, ctypes.byref(errbuf), WORD(64)) ## print 'err' ## raise ValueError(errbuf.value) # For some reason, it appears normal in the LabVIEW code that this # function actually returns an error, i.e. the return value is zero # and the buffer has a non-zero error code in it; the LabVIEW code # doesn't check it. # Also, it appears that in the 2005 version of this DLL, the function # VCS_GetErrorInfo doesn't exist! # Get operation mode, check if it's 1 -- this is "profile position mode" buf = ctypes.wintypes.DWORD(0) pMode = ctypes.pointer(ctypes.c_int8()) eposlib.VCS_GetOperationMode.argtypes = [ctypes.wintypes.HANDLE, ctypes.wintypes.WORD, ctypes.POINTER(ctypes.c_int8), ctypes.POINTER(ctypes.wintypes.DWORD)] eposlib.VCS_GetOperationMode.restype = ctypes.wintypes.BOOL ret = eposlib.VCS_GetOperationMode(self._keyhandle, nodeID, pMode, ctypes.byref(buf)) # if mode is not 1, make it 1 if pMode.contents.value != 1: eposlib.VCS_SetOperationMode.argtypes = [ctypes.wintypes.HANDLE, ctypes.wintypes.WORD, ctypes.c_int8, ctypes.POINTER(ctypes.wintypes.DWORD)] eposlib.VCS_SetOperationMode.restype = ctypes.wintypes.BOOL pMode_setting = ctypes.c_int8(1) ret = eposlib.VCS_SetOperationMode(self._keyhandle, nodeID, pMode_setting, ctypes.byref(buf)) eposlib.VCS_GetPositionProfile.argtypes = [ctypes.wintypes.HANDLE, ctypes.wintypes.WORD, ctypes.POINTER(ctypes.wintypes.DWORD), ctypes.POINTER(ctypes.wintypes.DWORD), ctypes.POINTER(ctypes.wintypes.DWORD), ctypes.POINTER(ctypes.wintypes.DWORD)] eposlib.VCS_GetPositionProfile.restype = ctypes.wintypes.BOOL pProfileVelocity = ctypes.pointer(ctypes.wintypes.DWORD()) pProfileAcceleration = ctypes.pointer(ctypes.wintypes.DWORD()) pProfileDeceleration = ctypes.pointer(ctypes.wintypes.DWORD()) ret = eposlib.VCS_GetPositionProfile(self._keyhandle, nodeID, pProfileVelocity, pProfileAcceleration, pProfileDeceleration, ctypes.byref(buf)) print(pProfileVelocity.contents.value, pProfileAcceleration.contents.value, pProfileDeceleration.contents.value) if (int(pProfileVelocity.contents.value) > int(11400) or int(pProfileAcceleration.contents.value) > int( 60000) or int(pProfileDeceleration.contents.value) > int(60000)): eposlib.VCS_GetPositionProfile.argtypes = [ctypes.wintypes.HANDLE, ctypes.wintypes.WORD, ctypes.wintypes.DWORD, ctypes.wintypes.DWORD, ctypes.wintypes.DWORD, ctypes.POINTER(ctypes.wintypes.DWORD)] eposlib.VCS_GetPositionProfile.restype = ctypes.wintypes.BOOL pProfileVelocity = ctypes.wintypes.DWORD(429) pProfileAcceleration = ctypes.wintypes.DWORD(429) pProfileDeceleration = ctypes.wintypes.DWORD(429) logging.warning(__name__ + ' GetPositionProfile out of bounds, resetting...') ret = eposlib.VCS_SetPositionProfile(self._keyhandle, nodeID, pProfileVelocity, pProfileAcceleration, pProfileDeceleration, ctypes.byref(buf)) # Now get the motor position (stored position offset) # from the device's "homposition" object self._offset = self.get_offset() # Now read the stored 'calculation parameters' eposlib.VCS_GetObject.argtypes = [ctypes.wintypes.HANDLE, ctypes.wintypes.WORD, ctypes.wintypes.WORD, ctypes.c_uint8, ctypes.c_void_p, ctypes.wintypes.DWORD, ctypes.POINTER(ctypes.wintypes.DWORD), ctypes.POINTER(ctypes.wintypes.DWORD)] eposlib.VCS_GetObject.restype = ctypes.wintypes.BOOL # More hardcoded values StoredPositionObject = ctypes.wintypes.WORD(8204) StoredPositionObjectSubindex = ctypes.c_uint8(1) StoredPositionNbBytesToRead = ctypes.wintypes.DWORD(4) ObjectData = ctypes.c_void_p() ObjectDataArray = (ctypes.c_uint32 * 1)() ObjectData = ctypes.cast(ObjectDataArray, ctypes.POINTER(ctypes.c_uint32)) StoredPositionNbBytesRead = ctypes.pointer(ctypes.wintypes.DWORD(0)) ret = eposlib.VCS_GetObject(self._keyhandle, nodeID, StoredPositionObject, StoredPositionObjectSubindex, ObjectData, StoredPositionNbBytesToRead, StoredPositionNbBytesRead, ctypes.byref(buf)) # Cast the object data to uint32 CastedObjectData = ctypes.cast(ObjectData, ctypes.POINTER(ctypes.c_uint32)) self._coefA = CastedObjectData[0] eposlib.VCS_GetObject.argtypes = [ctypes.wintypes.HANDLE, ctypes.wintypes.WORD, ctypes.wintypes.WORD, ctypes.c_uint8, ctypes.c_void_p, ctypes.wintypes.DWORD, ctypes.POINTER(ctypes.wintypes.DWORD), ctypes.POINTER(ctypes.wintypes.DWORD)] eposlib.VCS_GetObject.restype = ctypes.wintypes.BOOL # Get coefficient B StoredPositionObject = ctypes.wintypes.WORD(8204) StoredPositionObjectSubindex = ctypes.c_uint8(2) StoredPositionNbBytesToRead = ctypes.wintypes.DWORD(4) ObjectData = ctypes.c_void_p() ObjectDataArray = (ctypes.c_uint32 * 1)() ObjectData = ctypes.cast(ObjectDataArray, ctypes.POINTER(ctypes.c_uint32)) StoredPositionNbBytesRead = ctypes.pointer(ctypes.wintypes.DWORD(0)) ret = eposlib.VCS_GetObject(self._keyhandle, nodeID, StoredPositionObject, StoredPositionObjectSubindex, ObjectData, StoredPositionNbBytesToRead, StoredPositionNbBytesRead, ctypes.byref(buf)) # Cast the object data to uint32 CastedObjectData = ctypes.cast(ObjectData, ctypes.POINTER(ctypes.c_uint32)) self._coefB = CastedObjectData[0] eposlib.VCS_GetObject.argtypes = [ctypes.wintypes.HANDLE, ctypes.wintypes.WORD, ctypes.wintypes.WORD, ctypes.c_uint8, ctypes.c_void_p, ctypes.wintypes.DWORD, ctypes.POINTER(ctypes.wintypes.DWORD), ctypes.POINTER(ctypes.wintypes.DWORD)] eposlib.VCS_GetObject.restype = ctypes.wintypes.BOOL # These are hardcoded values I got from the LabVIEW program -- I don't think # any documentation exists on particular object indices StoredPositionObject = ctypes.wintypes.WORD(8204) StoredPositionObjectSubindex = ctypes.c_uint8(3) StoredPositionNbBytesToRead = ctypes.wintypes.DWORD(4) ObjectData = ctypes.c_void_p() ObjectDataArray = (ctypes.c_uint32 * 1)() ObjectData = ctypes.cast(ObjectDataArray, ctypes.POINTER(ctypes.c_uint32)) StoredPositionNbBytesRead = ctypes.pointer(ctypes.wintypes.DWORD(0)) ret = eposlib.VCS_GetObject(self._keyhandle, nodeID, StoredPositionObject, StoredPositionObjectSubindex, ObjectData, StoredPositionNbBytesToRead, StoredPositionNbBytesRead, ctypes.byref(buf)) # Cast the object data to uint32 CastedObjectData = ctypes.cast(ObjectData, ctypes.POINTER(ctypes.c_uint32)) self._coefC = CastedObjectData[0] # Get coefficient D eposlib.VCS_GetObject.argtypes = [ctypes.wintypes.HANDLE, ctypes.wintypes.WORD, ctypes.wintypes.WORD, ctypes.c_uint8, ctypes.c_void_p, ctypes.wintypes.DWORD, ctypes.POINTER(ctypes.wintypes.DWORD), ctypes.POINTER(ctypes.wintypes.DWORD)] eposlib.VCS_GetObject.restype = ctypes.wintypes.BOOL # These are hardcoded values I got from the LabVIEW program -- I don't think # any documentation exists on particular object indices StoredPositionObject = ctypes.wintypes.WORD(8204) StoredPositionObjectSubindex = ctypes.c_uint8(4) StoredPositionNbBytesToRead = ctypes.wintypes.DWORD(4) ObjectData = ctypes.c_void_p() ObjectDataArray = (ctypes.c_uint32 * 1)() ObjectData = ctypes.cast(ObjectDataArray, ctypes.POINTER(ctypes.c_uint32)) StoredPositionNbBytesRead = ctypes.pointer(ctypes.wintypes.DWORD(0)) ret = eposlib.VCS_GetObject(self._keyhandle, nodeID, StoredPositionObject, StoredPositionObjectSubindex, ObjectData, StoredPositionNbBytesToRead, StoredPositionNbBytesRead, ctypes.byref(buf)) # Cast the object data to uint32 CastedObjectData = ctypes.cast(ObjectData, ctypes.POINTER(ctypes.c_uint32)) self._coefD = CastedObjectData[0] # print 'coefficients are %s %s %s %s' % (self._coefA, self._coefB, self._coefC, self._coefD) self._doubleA = self._u32todouble(self._coefA) self._doubleB = self._u32todouble(self._coefB) self._doubleC = self._u32todouble(self._coefC) firstHalf = np.int16(self._coefD >> 16) secondHalf = np.int16(self._coefD & 0xffff) # Set the minimum and maximum wavelengths for the motor self._minwl = float(firstHalf) / 10.0 self._maxwl = float(secondHalf) / 10.0 # print 'first %s second %s' % (firstHalf, secondHalf) # This returns '10871' and '11859' for the Sacher, which are the correct # wavelength ranges in Angstroms # print 'Now calculate the current wavelength position:' self._currentwl = self._doubleA * (self._offset) ** 2.0 + self._doubleB * self._offset + self._doubleC print('Current wavelength: %.3f nm' % self._currentwl) print('initializing done') return True """ Not sure what this is doing yet """ """ Also we're done with the Sacher_EPOS() class at this point """ if __name__ == '__main__': epos = Sacher_EPOS(None, b'COM3') # epos.set_coeffs(8.34529e-12,8.49218e-5,1081.92,10840,11860) # epos.do_get_wavelength() # print('#1 Motor current: {}'.format(epos.get_motor_current())) # epos.do_get_wavelength() # print('motor position is...') # current_pos = epos.get_motor_position() # print('current position is {}'.format(current_pos)) # new_pos = current_pos + 10000 # epos.set_target_position(new_pos, True, True) # print(epos.get_motor_position()) # print('#2 Motor current: {}'.format(epos.get_motor_current())) # epos.find_home() # epos.restore() # time.sleep(7) epos.do_set_wavelength(1151.5) # epos.do_get_wavelength() print('Motor current: {}'.format(epos.get_motor_current())) print('Motor position: {}'.format(epos.get_motor_position())) """ OTHER MISC. NOTES: increasing wavelength: causes the square to rotate left causes base to move to the left when square is stuck in causes screw to loosen causes large gold base to tighten decreasing wavelength: there's an overshoot when lowering wavelength causes the square to rotate right causes base to move to the right when square is stuck in causes screw to tighten causes large gold base to loosen, and also unplug the motor Also you don't need to explicitly run epos.initialize() because there's an __init__ function which contains epos.initialize() """ # womp the end
[ "numpy.sqrt", "time.sleep", "ctypes.create_string_buffer", "ctypes.c_void_p", "logging.error", "ctypes.c_int8", "ctypes.wintypes.DWORD", "ctypes.windll.LoadLibrary", "numpy.ceil", "numpy.int16", "logging.warning", "ctypes.wintypes.WORD", "ctypes.wintypes.BOOL", "ctypes.wintypes.HANDLE", "numpy.log2", "ctypes.c_long", "ctypes.byref", "ctypes.POINTER", "ctypes.c_uint8" ]
[((1377, 1462), 'ctypes.windll.LoadLibrary', 'ctypes.windll.LoadLibrary', (['"""C:\\\\Users\\\\Carbro\\\\Desktop\\\\Charmander\\\\EposCmd.dll"""'], {}), "('C:\\\\Users\\\\Carbro\\\\Desktop\\\\Charmander\\\\EposCmd.dll'\n )\n", (1402, 1462), False, 'import ctypes\n'), ((6700, 6710), 'numpy.ceil', 'np.ceil', (['d'], {}), '(d)\n', (6707, 6710), True, 'import numpy as np\n'), ((7232, 7256), 'ctypes.wintypes.HANDLE', 'ctypes.wintypes.HANDLE', ([], {}), '()\n', (7254, 7256), False, 'import ctypes\n'), ((8290, 8312), 'ctypes.wintypes.BOOL', 'ctypes.wintypes.BOOL', ([], {}), '()\n', (8310, 8312), False, 'import ctypes\n'), ((8860, 8883), 'ctypes.wintypes.WORD', 'ctypes.wintypes.WORD', (['(0)'], {}), '(0)\n', (8880, 8883), False, 'import ctypes\n'), ((9179, 9196), 'ctypes.c_uint8', 'ctypes.c_uint8', (['(0)'], {}), '(0)\n', (9193, 9196), False, 'import ctypes\n'), ((9211, 9235), 'ctypes.wintypes.DWORD', 'ctypes.wintypes.DWORD', (['(0)'], {}), '(0)\n', (9232, 9235), False, 'import ctypes\n'), ((9477, 9500), 'ctypes.wintypes.WORD', 'ctypes.wintypes.WORD', (['(0)'], {}), '(0)\n', (9497, 9500), False, 'import ctypes\n'), ((9759, 9783), 'ctypes.wintypes.DWORD', 'ctypes.wintypes.DWORD', (['(0)'], {}), '(0)\n', (9780, 9783), False, 'import ctypes\n'), ((10036, 10059), 'ctypes.wintypes.WORD', 'ctypes.wintypes.WORD', (['(0)'], {}), '(0)\n', (10056, 10059), False, 'import ctypes\n'), ((10302, 10326), 'ctypes.wintypes.DWORD', 'ctypes.wintypes.DWORD', (['(0)'], {}), '(0)\n', (10323, 10326), False, 'import ctypes\n'), ((10562, 10585), 'ctypes.wintypes.WORD', 'ctypes.wintypes.WORD', (['(0)'], {}), '(0)\n', (10582, 10585), False, 'import ctypes\n'), ((10600, 10624), 'ctypes.wintypes.DWORD', 'ctypes.wintypes.DWORD', (['(0)'], {}), '(0)\n', (10621, 10624), False, 'import ctypes\n'), ((11194, 11220), 'ctypes.wintypes.WORD', 'ctypes.wintypes.WORD', (['(8321)'], {}), '(8321)\n', (11214, 11220), False, 'import ctypes\n'), ((11260, 11277), 'ctypes.c_uint8', 'ctypes.c_uint8', (['(0)'], {}), '(0)\n', (11274, 11277), False, 'import ctypes\n'), ((11316, 11340), 'ctypes.wintypes.DWORD', 'ctypes.wintypes.DWORD', (['(4)'], {}), '(4)\n', (11337, 11340), False, 'import ctypes\n'), ((11362, 11379), 'ctypes.c_void_p', 'ctypes.c_void_p', ([], {}), '()\n', (11377, 11379), False, 'import ctypes\n'), ((12764, 12787), 'ctypes.wintypes.WORD', 'ctypes.wintypes.WORD', (['(0)'], {}), '(0)\n', (12784, 12787), False, 'import ctypes\n'), ((12802, 12826), 'ctypes.wintypes.DWORD', 'ctypes.wintypes.DWORD', (['(0)'], {}), '(0)\n', (12823, 12826), False, 'import ctypes\n'), ((13307, 13333), 'ctypes.wintypes.WORD', 'ctypes.wintypes.WORD', (['(8321)'], {}), '(8321)\n', (13327, 13333), False, 'import ctypes\n'), ((13373, 13390), 'ctypes.c_uint8', 'ctypes.c_uint8', (['(0)'], {}), '(0)\n', (13387, 13390), False, 'import ctypes\n'), ((13430, 13454), 'ctypes.wintypes.DWORD', 'ctypes.wintypes.DWORD', (['(4)'], {}), '(4)\n', (13451, 13454), False, 'import ctypes\n'), ((14269, 14292), 'ctypes.wintypes.WORD', 'ctypes.wintypes.WORD', (['(0)'], {}), '(0)\n', (14289, 14292), False, 'import ctypes\n'), ((14307, 14331), 'ctypes.wintypes.DWORD', 'ctypes.wintypes.DWORD', (['(0)'], {}), '(0)\n', (14328, 14331), False, 'import ctypes\n'), ((14848, 14874), 'ctypes.wintypes.WORD', 'ctypes.wintypes.WORD', (['(8204)'], {}), '(8204)\n', (14868, 14874), False, 'import ctypes\n'), ((15675, 15692), 'ctypes.c_uint8', 'ctypes.c_uint8', (['(4)'], {}), '(4)\n', (15689, 15692), False, 'import ctypes\n'), ((15732, 15756), 'ctypes.wintypes.DWORD', 'ctypes.wintypes.DWORD', (['(4)'], {}), '(4)\n', (15753, 15756), False, 'import ctypes\n'), ((16577, 16600), 'ctypes.wintypes.WORD', 'ctypes.wintypes.WORD', (['(0)'], {}), '(0)\n', (16597, 16600), False, 'import ctypes\n'), ((16615, 16639), 'ctypes.wintypes.DWORD', 'ctypes.wintypes.DWORD', (['(0)'], {}), '(0)\n', (16636, 16639), False, 'import ctypes\n'), ((17562, 17585), 'ctypes.wintypes.WORD', 'ctypes.wintypes.WORD', (['(0)'], {}), '(0)\n', (17582, 17585), False, 'import ctypes\n'), ((17600, 17624), 'ctypes.wintypes.DWORD', 'ctypes.wintypes.DWORD', (['(0)'], {}), '(0)\n', (17621, 17624), False, 'import ctypes\n'), ((18562, 18583), 'ctypes.c_long', 'ctypes.c_long', (['target'], {}), '(target)\n', (18575, 18583), False, 'import ctypes\n'), ((18604, 18634), 'ctypes.wintypes.BOOL', 'ctypes.wintypes.BOOL', (['absolute'], {}), '(absolute)\n', (18624, 18634), False, 'import ctypes\n'), ((18658, 18691), 'ctypes.wintypes.BOOL', 'ctypes.wintypes.BOOL', (['immediately'], {}), '(immediately)\n', (18678, 18691), False, 'import ctypes\n'), ((22231, 22254), 'ctypes.wintypes.WORD', 'ctypes.wintypes.WORD', (['(0)'], {}), '(0)\n', (22251, 22254), False, 'import ctypes\n'), ((22269, 22293), 'ctypes.wintypes.DWORD', 'ctypes.wintypes.DWORD', (['(0)'], {}), '(0)\n', (22290, 22293), False, 'import ctypes\n'), ((25009, 25032), 'ctypes.wintypes.WORD', 'ctypes.wintypes.WORD', (['(0)'], {}), '(0)\n', (25029, 25032), False, 'import ctypes\n'), ((25047, 25071), 'ctypes.wintypes.DWORD', 'ctypes.wintypes.DWORD', (['(0)'], {}), '(0)\n', (25068, 25071), False, 'import ctypes\n'), ((28773, 28796), 'ctypes.wintypes.WORD', 'ctypes.wintypes.WORD', (['(0)'], {}), '(0)\n', (28793, 28796), False, 'import ctypes\n'), ((28811, 28835), 'ctypes.wintypes.DWORD', 'ctypes.wintypes.DWORD', (['(0)'], {}), '(0)\n', (28832, 28835), False, 'import ctypes\n'), ((29248, 29271), 'ctypes.wintypes.WORD', 'ctypes.wintypes.WORD', (['(0)'], {}), '(0)\n', (29268, 29271), False, 'import ctypes\n'), ((29286, 29310), 'ctypes.wintypes.DWORD', 'ctypes.wintypes.DWORD', (['(0)'], {}), '(0)\n', (29307, 29310), False, 'import ctypes\n'), ((29330, 29342), 'ctypes.wintypes.DWORD', 'DWORD', (['(38400)'], {}), '(38400)\n', (29335, 29342), False, 'from ctypes.wintypes import DWORD, WORD\n'), ((29361, 29371), 'ctypes.wintypes.DWORD', 'DWORD', (['(100)'], {}), '(100)\n', (29366, 29371), False, 'from ctypes.wintypes import DWORD, WORD\n'), ((29730, 29754), 'ctypes.wintypes.DWORD', 'ctypes.wintypes.DWORD', (['(0)'], {}), '(0)\n', (29751, 29754), False, 'import ctypes\n'), ((30085, 30109), 'ctypes.wintypes.DWORD', 'ctypes.wintypes.DWORD', (['(0)'], {}), '(0)\n', (30106, 30109), False, 'import ctypes\n'), ((30131, 30155), 'ctypes.wintypes.DWORD', 'ctypes.wintypes.DWORD', (['(0)'], {}), '(0)\n', (30152, 30155), False, 'import ctypes\n'), ((30991, 31015), 'ctypes.wintypes.DWORD', 'ctypes.wintypes.DWORD', (['(0)'], {}), '(0)\n', (31012, 31015), False, 'import ctypes\n'), ((31033, 31042), 'ctypes.wintypes.WORD', 'WORD', (['(512)'], {}), '(512)\n', (31037, 31042), False, 'from ctypes.wintypes import DWORD, WORD\n'), ((31121, 31128), 'ctypes.wintypes.WORD', 'WORD', (['(4)'], {}), '(4)\n', (31125, 31128), False, 'from ctypes.wintypes import DWORD, WORD\n'), ((32355, 32379), 'ctypes.wintypes.DWORD', 'ctypes.wintypes.DWORD', (['(0)'], {}), '(0)\n', (32376, 32379), False, 'import ctypes\n'), ((36092, 36118), 'ctypes.wintypes.WORD', 'ctypes.wintypes.WORD', (['(8204)'], {}), '(8204)\n', (36112, 36118), False, 'import ctypes\n'), ((36158, 36175), 'ctypes.c_uint8', 'ctypes.c_uint8', (['(1)'], {}), '(1)\n', (36172, 36175), False, 'import ctypes\n'), ((36214, 36238), 'ctypes.wintypes.DWORD', 'ctypes.wintypes.DWORD', (['(4)'], {}), '(4)\n', (36235, 36238), False, 'import ctypes\n'), ((36260, 36277), 'ctypes.c_void_p', 'ctypes.c_void_p', ([], {}), '()\n', (36275, 36277), False, 'import ctypes\n'), ((37377, 37403), 'ctypes.wintypes.WORD', 'ctypes.wintypes.WORD', (['(8204)'], {}), '(8204)\n', (37397, 37403), False, 'import ctypes\n'), ((37443, 37460), 'ctypes.c_uint8', 'ctypes.c_uint8', (['(2)'], {}), '(2)\n', (37457, 37460), False, 'import ctypes\n'), ((37499, 37523), 'ctypes.wintypes.DWORD', 'ctypes.wintypes.DWORD', (['(4)'], {}), '(4)\n', (37520, 37523), False, 'import ctypes\n'), ((37545, 37562), 'ctypes.c_void_p', 'ctypes.c_void_p', ([], {}), '()\n', (37560, 37562), False, 'import ctypes\n'), ((38783, 38809), 'ctypes.wintypes.WORD', 'ctypes.wintypes.WORD', (['(8204)'], {}), '(8204)\n', (38803, 38809), False, 'import ctypes\n'), ((38849, 38866), 'ctypes.c_uint8', 'ctypes.c_uint8', (['(3)'], {}), '(3)\n', (38863, 38866), False, 'import ctypes\n'), ((38905, 38929), 'ctypes.wintypes.DWORD', 'ctypes.wintypes.DWORD', (['(4)'], {}), '(4)\n', (38926, 38929), False, 'import ctypes\n'), ((38951, 38968), 'ctypes.c_void_p', 'ctypes.c_void_p', ([], {}), '()\n', (38966, 38968), False, 'import ctypes\n'), ((40218, 40244), 'ctypes.wintypes.WORD', 'ctypes.wintypes.WORD', (['(8204)'], {}), '(8204)\n', (40238, 40244), False, 'import ctypes\n'), ((40284, 40301), 'ctypes.c_uint8', 'ctypes.c_uint8', (['(4)'], {}), '(4)\n', (40298, 40301), False, 'import ctypes\n'), ((40340, 40364), 'ctypes.wintypes.DWORD', 'ctypes.wintypes.DWORD', (['(4)'], {}), '(4)\n', (40361, 40364), False, 'import ctypes\n'), ((40386, 40403), 'ctypes.c_void_p', 'ctypes.c_void_p', ([], {}), '()\n', (40401, 40403), False, 'import ctypes\n'), ((41341, 41368), 'numpy.int16', 'np.int16', (['(self._coefD >> 16)'], {}), '(self._coefD >> 16)\n', (41349, 41368), True, 'import numpy as np\n'), ((41390, 41419), 'numpy.int16', 'np.int16', (['(self._coefD & 65535)'], {}), '(self._coefD & 65535)\n', (41398, 41419), True, 'import numpy as np\n'), ((6671, 6682), 'numpy.log2', 'np.log2', (['(10)'], {}), '(10)\n', (6678, 6682), True, 'import numpy as np\n'), ((7092, 7113), 'ctypes.POINTER', 'ctypes.POINTER', (['DWORD'], {}), '(DWORD)\n', (7106, 7113), False, 'import ctypes\n'), ((7208, 7216), 'ctypes.wintypes.DWORD', 'DWORD', (['(0)'], {}), '(0)\n', (7213, 7216), False, 'from ctypes.wintypes import DWORD, WORD\n'), ((8151, 8172), 'ctypes.POINTER', 'ctypes.POINTER', (['DWORD'], {}), '(DWORD)\n', (8165, 8172), False, 'import ctypes\n'), ((8266, 8274), 'ctypes.wintypes.DWORD', 'DWORD', (['(0)'], {}), '(0)\n', (8271, 8274), False, 'from ctypes.wintypes import DWORD, WORD\n'), ((8526, 8597), 'logging.error', 'logging.error', (["(__name__ + ' did not close Sacher EPOS motor correctly.')"], {}), "(__name__ + ' did not close Sacher EPOS motor correctly.')\n", (8539, 8597), False, 'import logging\n'), ((9020, 9050), 'ctypes.POINTER', 'ctypes.POINTER', (['ctypes.c_uint8'], {}), '(ctypes.c_uint8)\n', (9034, 9050), False, 'import ctypes\n'), ((9052, 9089), 'ctypes.POINTER', 'ctypes.POINTER', (['ctypes.wintypes.DWORD'], {}), '(ctypes.wintypes.DWORD)\n', (9066, 9089), False, 'import ctypes\n'), ((9300, 9326), 'ctypes.byref', 'ctypes.byref', (['motorCurrent'], {}), '(motorCurrent)\n', (9312, 9326), False, 'import ctypes\n'), ((9328, 9345), 'ctypes.byref', 'ctypes.byref', (['buf'], {}), '(buf)\n', (9340, 9345), False, 'import ctypes\n'), ((9645, 9682), 'ctypes.POINTER', 'ctypes.POINTER', (['ctypes.wintypes.DWORD'], {}), '(ctypes.wintypes.DWORD)\n', (9659, 9682), False, 'import ctypes\n'), ((9844, 9862), 'ctypes.c_uint8', 'ctypes.c_uint8', (['(35)'], {}), '(35)\n', (9858, 9862), False, 'import ctypes\n'), ((9864, 9881), 'ctypes.byref', 'ctypes.byref', (['buf'], {}), '(buf)\n', (9876, 9881), False, 'import ctypes\n'), ((10188, 10225), 'ctypes.POINTER', 'ctypes.POINTER', (['ctypes.wintypes.DWORD'], {}), '(ctypes.wintypes.DWORD)\n', (10202, 10225), False, 'import ctypes\n'), ((10386, 10403), 'ctypes.byref', 'ctypes.byref', (['buf'], {}), '(buf)\n', (10398, 10403), False, 'import ctypes\n'), ((10875, 10912), 'ctypes.POINTER', 'ctypes.POINTER', (['ctypes.wintypes.DWORD'], {}), '(ctypes.wintypes.DWORD)\n', (10889, 10912), False, 'import ctypes\n'), ((10914, 10951), 'ctypes.POINTER', 'ctypes.POINTER', (['ctypes.wintypes.DWORD'], {}), '(ctypes.wintypes.DWORD)\n', (10928, 10951), False, 'import ctypes\n'), ((11480, 11510), 'ctypes.POINTER', 'ctypes.POINTER', (['ctypes.c_int32'], {}), '(ctypes.c_int32)\n', (11494, 11510), False, 'import ctypes\n'), ((11563, 11587), 'ctypes.wintypes.DWORD', 'ctypes.wintypes.DWORD', (['(0)'], {}), '(0)\n', (11584, 11587), False, 'import ctypes\n'), ((11842, 11859), 'ctypes.byref', 'ctypes.byref', (['buf'], {}), '(buf)\n', (11854, 11859), False, 'import ctypes\n'), ((11954, 11984), 'ctypes.POINTER', 'ctypes.POINTER', (['ctypes.c_int32'], {}), '(ctypes.c_int32)\n', (11968, 11984), False, 'import ctypes\n'), ((12019, 12105), 'logging.error', 'logging.error', (["(__name__ + ' Could not read stored position from Sacher EPOS motor')"], {}), "(__name__ +\n ' Could not read stored position from Sacher EPOS motor')\n", (12032, 12105), False, 'import logging\n'), ((12995, 13032), 'ctypes.POINTER', 'ctypes.POINTER', (['ctypes.wintypes.DWORD'], {}), '(ctypes.wintypes.DWORD)\n', (13009, 13032), False, 'import ctypes\n'), ((13099, 13136), 'ctypes.POINTER', 'ctypes.POINTER', (['ctypes.wintypes.DWORD'], {}), '(ctypes.wintypes.DWORD)\n', (13113, 13136), False, 'import ctypes\n'), ((13138, 13175), 'ctypes.POINTER', 'ctypes.POINTER', (['ctypes.wintypes.DWORD'], {}), '(ctypes.wintypes.DWORD)\n', (13152, 13175), False, 'import ctypes\n'), ((13566, 13597), 'ctypes.POINTER', 'ctypes.POINTER', (['ctypes.c_uint32'], {}), '(ctypes.c_uint32)\n', (13580, 13597), False, 'import ctypes\n'), ((13653, 13677), 'ctypes.wintypes.DWORD', 'ctypes.wintypes.DWORD', (['(0)'], {}), '(0)\n', (13674, 13677), False, 'import ctypes\n'), ((13936, 13953), 'ctypes.byref', 'ctypes.byref', (['buf'], {}), '(buf)\n', (13948, 13953), False, 'import ctypes\n'), ((13989, 14076), 'logging.error', 'logging.error', (["(__name__ + ' Could not write stored position from Sacher EPOS motor')"], {}), "(__name__ +\n ' Could not write stored position from Sacher EPOS motor')\n", (14002, 14076), False, 'import logging\n'), ((14500, 14537), 'ctypes.POINTER', 'ctypes.POINTER', (['ctypes.wintypes.DWORD'], {}), '(ctypes.wintypes.DWORD)\n', (14514, 14537), False, 'import ctypes\n'), ((14604, 14641), 'ctypes.POINTER', 'ctypes.POINTER', (['ctypes.wintypes.DWORD'], {}), '(ctypes.wintypes.DWORD)\n', (14618, 14641), False, 'import ctypes\n'), ((14643, 14680), 'ctypes.POINTER', 'ctypes.POINTER', (['ctypes.wintypes.DWORD'], {}), '(ctypes.wintypes.DWORD)\n', (14657, 14680), False, 'import ctypes\n'), ((15002, 15028), 'ctypes.c_uint8', 'ctypes.c_uint8', (['(subidx + 1)'], {}), '(subidx + 1)\n', (15016, 15028), False, 'import ctypes\n'), ((15072, 15096), 'ctypes.wintypes.DWORD', 'ctypes.wintypes.DWORD', (['(4)'], {}), '(4)\n', (15093, 15096), False, 'import ctypes\n'), ((15858, 15889), 'ctypes.POINTER', 'ctypes.POINTER', (['ctypes.c_uint32'], {}), '(ctypes.c_uint32)\n', (15872, 15889), False, 'import ctypes\n'), ((15945, 15969), 'ctypes.wintypes.DWORD', 'ctypes.wintypes.DWORD', (['(0)'], {}), '(0)\n', (15966, 15969), False, 'import ctypes\n'), ((16228, 16245), 'ctypes.byref', 'ctypes.byref', (['buf'], {}), '(buf)\n', (16240, 16245), False, 'import ctypes\n'), ((16373, 16460), 'logging.error', 'logging.error', (["(__name__ + ' Could not write stored position from Sacher EPOS motor')"], {}), "(__name__ +\n ' Could not write stored position from Sacher EPOS motor')\n", (16386, 16460), False, 'import logging\n'), ((16675, 16690), 'ctypes.c_long', 'ctypes.c_long', ([], {}), '()\n', (16688, 16690), False, 'import ctypes\n'), ((16830, 16859), 'ctypes.POINTER', 'ctypes.POINTER', (['ctypes.c_long'], {}), '(ctypes.c_long)\n', (16844, 16859), False, 'import ctypes\n'), ((16861, 16898), 'ctypes.POINTER', 'ctypes.POINTER', (['ctypes.wintypes.DWORD'], {}), '(ctypes.wintypes.DWORD)\n', (16875, 16898), False, 'import ctypes\n'), ((17041, 17058), 'ctypes.byref', 'ctypes.byref', (['buf'], {}), '(buf)\n', (17053, 17058), False, 'import ctypes\n'), ((18093, 18110), 'ctypes.byref', 'ctypes.byref', (['buf'], {}), '(buf)\n', (18105, 18110), False, 'import ctypes\n'), ((18939, 18976), 'ctypes.POINTER', 'ctypes.POINTER', (['ctypes.wintypes.DWORD'], {}), '(ctypes.wintypes.DWORD)\n', (18953, 18976), False, 'import ctypes\n'), ((19300, 19317), 'ctypes.byref', 'ctypes.byref', (['buf'], {}), '(buf)\n', (19312, 19317), False, 'import ctypes\n'), ((21540, 21556), 'time.sleep', 'time.sleep', (['(0.01)'], {}), '(0.01)\n', (21550, 21556), False, 'import time\n'), ((21657, 21674), 'ctypes.byref', 'ctypes.byref', (['buf'], {}), '(buf)\n', (21669, 21674), False, 'import ctypes\n'), ((23397, 23489), 'logging.error', 'logging.error', (["(__name__ + ' Negative value under square root sign -- something is wrong')"], {}), "(__name__ +\n ' Negative value under square root sign -- something is wrong')\n", (23410, 23489), False, 'import logging\n'), ((23700, 23716), 'numpy.sqrt', 'np.sqrt', (['sqrtarg'], {}), '(sqrtarg)\n', (23707, 23716), True, 'import numpy as np\n'), ((26175, 26267), 'logging.error', 'logging.error', (["(__name__ + ' Negative value under square root sign -- something is wrong')"], {}), "(__name__ +\n ' Negative value under square root sign -- something is wrong')\n", (26188, 26267), False, 'import logging\n'), ((28898, 28915), 'ctypes.byref', 'ctypes.byref', (['buf'], {}), '(buf)\n', (28910, 28915), False, 'import ctypes\n'), ((29016, 29047), 'ctypes.create_string_buffer', 'ctypes.create_string_buffer', (['(64)'], {}), '(64)\n', (29043, 29047), False, 'import ctypes\n'), ((29459, 29476), 'ctypes.byref', 'ctypes.byref', (['buf'], {}), '(buf)\n', (29471, 29476), False, 'import ctypes\n'), ((29578, 29609), 'ctypes.create_string_buffer', 'ctypes.create_string_buffer', (['(64)'], {}), '(64)\n', (29605, 29609), False, 'import ctypes\n'), ((29817, 29834), 'ctypes.byref', 'ctypes.byref', (['buf'], {}), '(buf)\n', (29829, 29834), False, 'import ctypes\n'), ((29936, 29967), 'ctypes.create_string_buffer', 'ctypes.create_string_buffer', (['(64)'], {}), '(64)\n', (29963, 29967), False, 'import ctypes\n'), ((30222, 30246), 'ctypes.byref', 'ctypes.byref', (['plsenabled'], {}), '(plsenabled)\n', (30234, 30246), False, 'import ctypes\n'), ((30248, 30265), 'ctypes.byref', 'ctypes.byref', (['buf'], {}), '(buf)\n', (30260, 30265), False, 'import ctypes\n'), ((30393, 30424), 'ctypes.create_string_buffer', 'ctypes.create_string_buffer', (['(64)'], {}), '(64)\n', (30420, 30424), False, 'import ctypes\n'), ((30580, 30659), 'logging.warning', 'logging.warning', (["(__name__ + ' EPOS motor enabled, disabling before proceeding.')"], {}), "(__name__ + ' EPOS motor enabled, disabling before proceeding.')\n", (30595, 30659), False, 'import logging\n'), ((31228, 31245), 'ctypes.byref', 'ctypes.byref', (['buf'], {}), '(buf)\n', (31240, 31245), False, 'import ctypes\n'), ((32411, 32426), 'ctypes.c_int8', 'ctypes.c_int8', ([], {}), '()\n', (32424, 32426), False, 'import ctypes\n'), ((32572, 32601), 'ctypes.POINTER', 'ctypes.POINTER', (['ctypes.c_int8'], {}), '(ctypes.c_int8)\n', (32586, 32601), False, 'import ctypes\n'), ((32603, 32640), 'ctypes.POINTER', 'ctypes.POINTER', (['ctypes.wintypes.DWORD'], {}), '(ctypes.wintypes.DWORD)\n', (32617, 32640), False, 'import ctypes\n'), ((32785, 32802), 'ctypes.byref', 'ctypes.byref', (['buf'], {}), '(buf)\n', (32797, 32802), False, 'import ctypes\n'), ((33186, 33202), 'ctypes.c_int8', 'ctypes.c_int8', (['(1)'], {}), '(1)\n', (33199, 33202), False, 'import ctypes\n'), ((33457, 33494), 'ctypes.POINTER', 'ctypes.POINTER', (['ctypes.wintypes.DWORD'], {}), '(ctypes.wintypes.DWORD)\n', (33471, 33494), False, 'import ctypes\n'), ((33547, 33584), 'ctypes.POINTER', 'ctypes.POINTER', (['ctypes.wintypes.DWORD'], {}), '(ctypes.wintypes.DWORD)\n', (33561, 33584), False, 'import ctypes\n'), ((33637, 33674), 'ctypes.POINTER', 'ctypes.POINTER', (['ctypes.wintypes.DWORD'], {}), '(ctypes.wintypes.DWORD)\n', (33651, 33674), False, 'import ctypes\n'), ((33727, 33764), 'ctypes.POINTER', 'ctypes.POINTER', (['ctypes.wintypes.DWORD'], {}), '(ctypes.wintypes.DWORD)\n', (33741, 33764), False, 'import ctypes\n'), ((33878, 33901), 'ctypes.wintypes.DWORD', 'ctypes.wintypes.DWORD', ([], {}), '()\n', (33899, 33901), False, 'import ctypes\n'), ((33949, 33972), 'ctypes.wintypes.DWORD', 'ctypes.wintypes.DWORD', ([], {}), '()\n', (33970, 33972), False, 'import ctypes\n'), ((34020, 34043), 'ctypes.wintypes.DWORD', 'ctypes.wintypes.DWORD', ([], {}), '()\n', (34041, 34043), False, 'import ctypes\n'), ((34223, 34240), 'ctypes.byref', 'ctypes.byref', (['buf'], {}), '(buf)\n', (34235, 34240), False, 'import ctypes\n'), ((34984, 35010), 'ctypes.wintypes.DWORD', 'ctypes.wintypes.DWORD', (['(429)'], {}), '(429)\n', (35005, 35010), False, 'import ctypes\n'), ((35046, 35072), 'ctypes.wintypes.DWORD', 'ctypes.wintypes.DWORD', (['(429)'], {}), '(429)\n', (35067, 35072), False, 'import ctypes\n'), ((35108, 35134), 'ctypes.wintypes.DWORD', 'ctypes.wintypes.DWORD', (['(429)'], {}), '(429)\n', (35129, 35134), False, 'import ctypes\n'), ((35147, 35224), 'logging.warning', 'logging.warning', (["(__name__ + ' GetPositionProfile out of bounds, resetting...')"], {}), "(__name__ + ' GetPositionProfile out of bounds, resetting...')\n", (35162, 35224), False, 'import logging\n'), ((35889, 35926), 'ctypes.POINTER', 'ctypes.POINTER', (['ctypes.wintypes.DWORD'], {}), '(ctypes.wintypes.DWORD)\n', (35903, 35926), False, 'import ctypes\n'), ((35928, 35965), 'ctypes.POINTER', 'ctypes.POINTER', (['ctypes.wintypes.DWORD'], {}), '(ctypes.wintypes.DWORD)\n', (35942, 35965), False, 'import ctypes\n'), ((36378, 36409), 'ctypes.POINTER', 'ctypes.POINTER', (['ctypes.c_uint32'], {}), '(ctypes.c_uint32)\n', (36392, 36409), False, 'import ctypes\n'), ((36462, 36486), 'ctypes.wintypes.DWORD', 'ctypes.wintypes.DWORD', (['(0)'], {}), '(0)\n', (36483, 36486), False, 'import ctypes\n'), ((36741, 36758), 'ctypes.byref', 'ctypes.byref', (['buf'], {}), '(buf)\n', (36753, 36758), False, 'import ctypes\n'), ((36852, 36883), 'ctypes.POINTER', 'ctypes.POINTER', (['ctypes.c_uint32'], {}), '(ctypes.c_uint32)\n', (36866, 36883), False, 'import ctypes\n'), ((37178, 37215), 'ctypes.POINTER', 'ctypes.POINTER', (['ctypes.wintypes.DWORD'], {}), '(ctypes.wintypes.DWORD)\n', (37192, 37215), False, 'import ctypes\n'), ((37217, 37254), 'ctypes.POINTER', 'ctypes.POINTER', (['ctypes.wintypes.DWORD'], {}), '(ctypes.wintypes.DWORD)\n', (37231, 37254), False, 'import ctypes\n'), ((37663, 37694), 'ctypes.POINTER', 'ctypes.POINTER', (['ctypes.c_uint32'], {}), '(ctypes.c_uint32)\n', (37677, 37694), False, 'import ctypes\n'), ((37747, 37771), 'ctypes.wintypes.DWORD', 'ctypes.wintypes.DWORD', (['(0)'], {}), '(0)\n', (37768, 37771), False, 'import ctypes\n'), ((38026, 38043), 'ctypes.byref', 'ctypes.byref', (['buf'], {}), '(buf)\n', (38038, 38043), False, 'import ctypes\n'), ((38137, 38168), 'ctypes.POINTER', 'ctypes.POINTER', (['ctypes.c_uint32'], {}), '(ctypes.c_uint32)\n', (38151, 38168), False, 'import ctypes\n'), ((38463, 38500), 'ctypes.POINTER', 'ctypes.POINTER', (['ctypes.wintypes.DWORD'], {}), '(ctypes.wintypes.DWORD)\n', (38477, 38500), False, 'import ctypes\n'), ((38502, 38539), 'ctypes.POINTER', 'ctypes.POINTER', (['ctypes.wintypes.DWORD'], {}), '(ctypes.wintypes.DWORD)\n', (38516, 38539), False, 'import ctypes\n'), ((39069, 39100), 'ctypes.POINTER', 'ctypes.POINTER', (['ctypes.c_uint32'], {}), '(ctypes.c_uint32)\n', (39083, 39100), False, 'import ctypes\n'), ((39153, 39177), 'ctypes.wintypes.DWORD', 'ctypes.wintypes.DWORD', (['(0)'], {}), '(0)\n', (39174, 39177), False, 'import ctypes\n'), ((39432, 39449), 'ctypes.byref', 'ctypes.byref', (['buf'], {}), '(buf)\n', (39444, 39449), False, 'import ctypes\n'), ((39543, 39574), 'ctypes.POINTER', 'ctypes.POINTER', (['ctypes.c_uint32'], {}), '(ctypes.c_uint32)\n', (39557, 39574), False, 'import ctypes\n'), ((39898, 39935), 'ctypes.POINTER', 'ctypes.POINTER', (['ctypes.wintypes.DWORD'], {}), '(ctypes.wintypes.DWORD)\n', (39912, 39935), False, 'import ctypes\n'), ((39937, 39974), 'ctypes.POINTER', 'ctypes.POINTER', (['ctypes.wintypes.DWORD'], {}), '(ctypes.wintypes.DWORD)\n', (39951, 39974), False, 'import ctypes\n'), ((40504, 40535), 'ctypes.POINTER', 'ctypes.POINTER', (['ctypes.c_uint32'], {}), '(ctypes.c_uint32)\n', (40518, 40535), False, 'import ctypes\n'), ((40588, 40612), 'ctypes.wintypes.DWORD', 'ctypes.wintypes.DWORD', (['(0)'], {}), '(0)\n', (40609, 40612), False, 'import ctypes\n'), ((40867, 40884), 'ctypes.byref', 'ctypes.byref', (['buf'], {}), '(buf)\n', (40879, 40884), False, 'import ctypes\n'), ((40978, 41009), 'ctypes.POINTER', 'ctypes.POINTER', (['ctypes.c_uint32'], {}), '(ctypes.c_uint32)\n', (40992, 41009), False, 'import ctypes\n'), ((15230, 15261), 'ctypes.POINTER', 'ctypes.POINTER', (['ctypes.c_uint32'], {}), '(ctypes.c_uint32)\n', (15244, 15261), False, 'import ctypes\n'), ((15321, 15345), 'ctypes.wintypes.DWORD', 'ctypes.wintypes.DWORD', (['(0)'], {}), '(0)\n', (15342, 15345), False, 'import ctypes\n'), ((15616, 15633), 'ctypes.byref', 'ctypes.byref', (['buf'], {}), '(buf)\n', (15628, 15633), False, 'import ctypes\n'), ((20480, 20502), 'ctypes.wintypes.BOOL', 'ctypes.wintypes.BOOL', ([], {}), '()\n', (20500, 20502), False, 'import ctypes\n'), ((20708, 20744), 'ctypes.POINTER', 'ctypes.POINTER', (['ctypes.wintypes.BOOL'], {}), '(ctypes.wintypes.BOOL)\n', (20722, 20744), False, 'import ctypes\n'), ((20799, 20836), 'ctypes.POINTER', 'ctypes.POINTER', (['ctypes.wintypes.DWORD'], {}), '(ctypes.wintypes.DWORD)\n', (20813, 20836), False, 'import ctypes\n'), ((21044, 21061), 'ctypes.byref', 'ctypes.byref', (['buf'], {}), '(buf)\n', (21056, 21061), False, 'import ctypes\n'), ((23581, 23597), 'numpy.sqrt', 'np.sqrt', (['sqrtarg'], {}), '(sqrtarg)\n', (23588, 23597), True, 'import numpy as np\n'), ((26359, 26375), 'numpy.sqrt', 'np.sqrt', (['sqrtarg'], {}), '(sqrtarg)\n', (26366, 26375), True, 'import numpy as np\n'), ((29098, 29106), 'ctypes.wintypes.WORD', 'WORD', (['(64)'], {}), '(64)\n', (29102, 29106), False, 'from ctypes.wintypes import DWORD, WORD\n'), ((30018, 30026), 'ctypes.wintypes.WORD', 'WORD', (['(64)'], {}), '(64)\n', (30022, 30026), False, 'from ctypes.wintypes import DWORD, WORD\n'), ((30475, 30483), 'ctypes.wintypes.WORD', 'WORD', (['(64)'], {}), '(64)\n', (30479, 30483), False, 'from ctypes.wintypes import DWORD, WORD\n'), ((30731, 30748), 'ctypes.byref', 'ctypes.byref', (['buf'], {}), '(buf)\n', (30743, 30748), False, 'import ctypes\n'), ((30796, 30871), 'logging.warning', 'logging.warning', (["(__name__ + ' EPOS motor successfully disabled, proceeding')"], {}), "(__name__ + ' EPOS motor successfully disabled, proceeding')\n", (30811, 30871), False, 'import logging\n'), ((30906, 30976), 'logging.error', 'logging.error', (["(__name__ + ' EPOS motor was not successfully disabled!')"], {}), "(__name__ + ' EPOS motor was not successfully disabled!')\n", (30919, 30976), False, 'import logging\n'), ((33047, 33084), 'ctypes.POINTER', 'ctypes.POINTER', (['ctypes.wintypes.DWORD'], {}), '(ctypes.wintypes.DWORD)\n', (33061, 33084), False, 'import ctypes\n'), ((33290, 33307), 'ctypes.byref', 'ctypes.byref', (['buf'], {}), '(buf)\n', (33302, 33307), False, 'import ctypes\n'), ((34840, 34877), 'ctypes.POINTER', 'ctypes.POINTER', (['ctypes.wintypes.DWORD'], {}), '(ctypes.wintypes.DWORD)\n', (34854, 34877), False, 'import ctypes\n'), ((35410, 35427), 'ctypes.byref', 'ctypes.byref', (['buf'], {}), '(buf)\n', (35422, 35427), False, 'import ctypes\n'), ((23649, 23665), 'numpy.sqrt', 'np.sqrt', (['sqrtarg'], {}), '(sqrtarg)\n', (23656, 23665), True, 'import numpy as np\n'), ((26427, 26443), 'numpy.sqrt', 'np.sqrt', (['sqrtarg'], {}), '(sqrtarg)\n', (26434, 26443), True, 'import numpy as np\n')]
# File: Converting_RGB_to_GreyScale.py # Description: Opening RGB image as array, converting to GreyScale and saving result into new file # Environment: PyCharm and Anaconda environment # # MIT License # Copyright (c) 2018 <NAME> # github.com/sichkar-valentyn # # Reference to: # <NAME>. Image processing in Python // GitHub platform. DOI: 10.5281/zenodo.1343603 # Opening RGB image as array, converting to GreyScale and saving result into new file # Importing needed libraries import numpy as np from PIL import Image import matplotlib.pyplot as plt from skimage import color from skimage import io import scipy.misc # Creating an array from image data image_RGB = Image.open("images/eagle.jpg") image_np = np.array(image_RGB) # Checking the type of the array print(type(image_np)) # <class 'numpy.ndarray'> # Checking the shape of the array print(image_np.shape) # Showing image with every channel separately channel_R = image_np[:, :, 0] channel_G = image_np[:, :, 1] channel_B = image_np[:, :, 2] # Creating a figure with subplots f, ax = plt.subplots(nrows=2, ncols=2) # ax is (2, 2) np array and to make it easier to read we use 'flatten' function # Or we can call each time ax[0, 0] ax0, ax1, ax2, ax3 = ax.flatten() # Adjusting first subplot ax0.imshow(channel_R, cmap='Reds') ax0.set_xlabel('') ax0.set_ylabel('') ax0.set_title('Red channel') # Adjusting second subplot ax1.imshow(channel_G, cmap='Greens') ax1.set_xlabel('') ax1.set_ylabel('') ax1.set_title('Green channel') # Adjusting third subplot ax2.imshow(channel_B, cmap='Blues') ax2.set_xlabel('') ax2.set_ylabel('') ax2.set_title('Blue channel') # Adjusting fourth subplot ax3.imshow(image_np) ax3.set_xlabel('') ax3.set_ylabel('') ax3.set_title('Original image') # Function to make distance between figures plt.tight_layout() # Giving the name to the window with figure f.canvas.set_window_title('Eagle image in three channels R, G and B') # Showing the plots plt.show() # Converting RGB image into GrayScale image # Using formula: # Y' = 0.299 R + 0.587 G + 0.114 B image_RGB = Image.open("images/eagle.jpg") image_np = np.array(image_RGB) image_GreyScale = image_np[:, :, 0] * 0.299 + image_np[:, :, 1] * 0.587 + image_np[:, :, 2] * 0.114 # Checking the type of the array print(type(image_GreyScale)) # <class 'numpy.ndarray'> # Checking the shape of the array print(image_GreyScale.shape) # Giving the name to the window with figure plt.figure('GreyScaled image from RGB') # Showing the image by using obtained array plt.imshow(image_GreyScale, cmap='Greys') plt.show() # Preparing array for saving - creating three channels with the same data in each # Firstly, creating array with zero elements # And by 'image_GreyScale.shape + tuple([3])' we add one more element '3' to the tuple # Now the shape will be (1080, 1920, 3) - which is tuple type image_GreyScale_with_3_channels = np.zeros(image_GreyScale.shape + tuple([3])) # Secondly, reshaping GreyScale image from 2D to 3D x = image_GreyScale.reshape((1080, 1920, 1)) # Finally, writing all data in three channels image_GreyScale_with_3_channels[:, :, 0] = x[:, :, 0] image_GreyScale_with_3_channels[:, :, 1] = x[:, :, 0] image_GreyScale_with_3_channels[:, :, 2] = x[:, :, 0] # Saving image into a file from obtained 3D array scipy.misc.imsave("images/result_1.jpg", image_GreyScale_with_3_channels) # Checking that image was written with three channels and they are identical result_1 = Image.open("images/result_1.jpg") result_1_np = np.array(result_1) print(result_1_np.shape) print(np.array_equal(result_1_np[:, :, 0], result_1_np[:, :, 1])) print(np.array_equal(result_1_np[:, :, 1], result_1_np[:, :, 2])) # Showing saved resulted image # Giving the name to the window with figure plt.figure('GreyScaled image from RGB') # Here we don't need to specify the map like cmap='Greys' plt.imshow(result_1_np) plt.show() # Another way to convert RGB image into GreyScale image image_RGB = io.imread("images/eagle.jpg") image_GreyScale = color.rgb2gray(image_RGB) # Checking the type of the array print(type(image_GreyScale)) # <class 'numpy.ndarray'> # Checking the shape of the array print(image_GreyScale.shape) # Giving the name to the window with figure plt.figure('GreyScaled image from RGB') # Showing the image by using obtained array plt.imshow(image_GreyScale, cmap='Greys') plt.show() # Saving converted image into a file from processed array scipy.misc.imsave("images/result_2.jpg", image_GreyScale) # One more way for converting image_RGB_as_GreyScale = io.imread("images/eagle.jpg", as_gray=True) # Checking the type of the array print(type(image_RGB_as_GreyScale)) # <class 'numpy.ndarray'> # Checking the shape of the array print(image_RGB_as_GreyScale.shape) # Giving the name to the window with figure plt.figure('GreyScaled image from RGB') # Showing the image by using obtained array plt.imshow(image_RGB_as_GreyScale, cmap='Greys') plt.show() # Saving converted image into a file from processed array scipy.misc.imsave("images/result_3.jpg", image_RGB_as_GreyScale)
[ "matplotlib.pyplot.imshow", "skimage.color.rgb2gray", "PIL.Image.open", "numpy.array", "matplotlib.pyplot.figure", "skimage.io.imread", "numpy.array_equal", "matplotlib.pyplot.tight_layout", "matplotlib.pyplot.subplots", "matplotlib.pyplot.show" ]
[((673, 703), 'PIL.Image.open', 'Image.open', (['"""images/eagle.jpg"""'], {}), "('images/eagle.jpg')\n", (683, 703), False, 'from PIL import Image\n'), ((715, 734), 'numpy.array', 'np.array', (['image_RGB'], {}), '(image_RGB)\n', (723, 734), True, 'import numpy as np\n'), ((1054, 1084), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': '(2)', 'ncols': '(2)'}), '(nrows=2, ncols=2)\n', (1066, 1084), True, 'import matplotlib.pyplot as plt\n'), ((1793, 1811), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (1809, 1811), True, 'import matplotlib.pyplot as plt\n'), ((1946, 1956), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1954, 1956), True, 'import matplotlib.pyplot as plt\n'), ((2067, 2097), 'PIL.Image.open', 'Image.open', (['"""images/eagle.jpg"""'], {}), "('images/eagle.jpg')\n", (2077, 2097), False, 'from PIL import Image\n'), ((2109, 2128), 'numpy.array', 'np.array', (['image_RGB'], {}), '(image_RGB)\n', (2117, 2128), True, 'import numpy as np\n'), ((2425, 2464), 'matplotlib.pyplot.figure', 'plt.figure', (['"""GreyScaled image from RGB"""'], {}), "('GreyScaled image from RGB')\n", (2435, 2464), True, 'import matplotlib.pyplot as plt\n'), ((2509, 2550), 'matplotlib.pyplot.imshow', 'plt.imshow', (['image_GreyScale'], {'cmap': '"""Greys"""'}), "(image_GreyScale, cmap='Greys')\n", (2519, 2550), True, 'import matplotlib.pyplot as plt\n'), ((2551, 2561), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2559, 2561), True, 'import matplotlib.pyplot as plt\n'), ((3434, 3467), 'PIL.Image.open', 'Image.open', (['"""images/result_1.jpg"""'], {}), "('images/result_1.jpg')\n", (3444, 3467), False, 'from PIL import Image\n'), ((3482, 3500), 'numpy.array', 'np.array', (['result_1'], {}), '(result_1)\n', (3490, 3500), True, 'import numpy as np\n'), ((3733, 3772), 'matplotlib.pyplot.figure', 'plt.figure', (['"""GreyScaled image from RGB"""'], {}), "('GreyScaled image from RGB')\n", (3743, 3772), True, 'import matplotlib.pyplot as plt\n'), ((3831, 3854), 'matplotlib.pyplot.imshow', 'plt.imshow', (['result_1_np'], {}), '(result_1_np)\n', (3841, 3854), True, 'import matplotlib.pyplot as plt\n'), ((3855, 3865), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3863, 3865), True, 'import matplotlib.pyplot as plt\n'), ((3936, 3965), 'skimage.io.imread', 'io.imread', (['"""images/eagle.jpg"""'], {}), "('images/eagle.jpg')\n", (3945, 3965), False, 'from skimage import io\n'), ((3984, 4009), 'skimage.color.rgb2gray', 'color.rgb2gray', (['image_RGB'], {}), '(image_RGB)\n', (3998, 4009), False, 'from skimage import color\n'), ((4206, 4245), 'matplotlib.pyplot.figure', 'plt.figure', (['"""GreyScaled image from RGB"""'], {}), "('GreyScaled image from RGB')\n", (4216, 4245), True, 'import matplotlib.pyplot as plt\n'), ((4290, 4331), 'matplotlib.pyplot.imshow', 'plt.imshow', (['image_GreyScale'], {'cmap': '"""Greys"""'}), "(image_GreyScale, cmap='Greys')\n", (4300, 4331), True, 'import matplotlib.pyplot as plt\n'), ((4332, 4342), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4340, 4342), True, 'import matplotlib.pyplot as plt\n'), ((4516, 4559), 'skimage.io.imread', 'io.imread', (['"""images/eagle.jpg"""'], {'as_gray': '(True)'}), "('images/eagle.jpg', as_gray=True)\n", (4525, 4559), False, 'from skimage import io\n'), ((4770, 4809), 'matplotlib.pyplot.figure', 'plt.figure', (['"""GreyScaled image from RGB"""'], {}), "('GreyScaled image from RGB')\n", (4780, 4809), True, 'import matplotlib.pyplot as plt\n'), ((4854, 4902), 'matplotlib.pyplot.imshow', 'plt.imshow', (['image_RGB_as_GreyScale'], {'cmap': '"""Greys"""'}), "(image_RGB_as_GreyScale, cmap='Greys')\n", (4864, 4902), True, 'import matplotlib.pyplot as plt\n'), ((4903, 4913), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4911, 4913), True, 'import matplotlib.pyplot as plt\n'), ((3532, 3590), 'numpy.array_equal', 'np.array_equal', (['result_1_np[:, :, 0]', 'result_1_np[:, :, 1]'], {}), '(result_1_np[:, :, 0], result_1_np[:, :, 1])\n', (3546, 3590), True, 'import numpy as np\n'), ((3598, 3656), 'numpy.array_equal', 'np.array_equal', (['result_1_np[:, :, 1]', 'result_1_np[:, :, 2]'], {}), '(result_1_np[:, :, 1], result_1_np[:, :, 2])\n', (3612, 3656), True, 'import numpy as np\n')]
import math import numpy as np import pandas as pd from sklearn.base import BaseEstimator import sys import os sys.path.append(os.path.abspath('../DecisionTree')) from DecisionTree import DecisionTree class RandomForest(BaseEstimator): """ Simple implementation of Random Forest. This class has implementation for Random Forest classifier and regressor. Dataset bagging is done by simple numpy random choice with replacement. For classification the prediction is by majority vote. For regression tree the prediction is averge of all estimator predictions. Args: n_estimators Number of base estimators (Decision Trees here) max_features Maximum features to be used to construct tree. Default: - If classifier, default is square root of total features. - If regressor, default is total number of features. max_depth The maximum depth to which estimators needs to be constructed. Default: np.inf min_samples_split Minimum number of samples need to present for split at the node. Default: 2 criterion criterion to be used for split. For classification tree following criterion are supported: - gini - entropy For regression tree following criterion are supported: - mse (mean squared error) - mae (mean absolute error) Default: gini random_seed random seed value for numpy operations. Default: 0 """ def __init__(self, n_estimators, max_features=0, max_depth=np.inf, min_samples_split=2, criterion='gini', random_seed=0): self.n_estimators = n_estimators self.max_features = max_features self.max_depth = max_depth self.min_samples_split = min_samples_split self.criterion = criterion self.random_seed = random_seed self.idxs = [] self.trees = [] for i in range(self.n_estimators): self.trees.append(DecisionTree(max_depth= self.max_depth, min_samples_split=self.min_samples_split, max_features = self.max_features, criterion=self.criterion, random_seed = self.random_seed)) self.is_classification_forest = False if self.criterion == 'gini' or self.criterion == 'entropy': self.is_classification_forest = True elif self.criterion == 'mse' or self.criterion == 'mae': self.is_classification_forest = False else: raise Exception("Invalid criterion: {}".format(self.criterion)) def get_subsets(self, X, y, num=1): subsets = [] if len(np.shape(y)) == 1: y = np.expand_dims(y, axis=1) Xy = np.concatenate((X, y), axis=1) num_samples = X.shape[0] np.random.shuffle(Xy) rng = np.random.default_rng(seed= self.random_seed) for _ in range(num): idx = rng.choice( range(num_samples), size = np.shape(range(int(num_samples)), ), replace=True ) subsets.append([X[idx], y[idx]]) return subsets def fit(self, X, y): np.random.seed(self.random_seed) if isinstance(X, pd.DataFrame): X = X.to_numpy() subsets = self.get_subsets(X, y, self.n_estimators) if self.max_features == 0: if self.is_classification_forest: self.max_features = int(math.sqrt(X.shape[1])) else: self.max_features = int(X.shape[1]) # Bagging - choose random features for each estimator # if max_features is provided, else use square root of # total number of features. for i, _ in enumerate(self.trees): self.trees[i].max_features = self.max_features X_sub, y_sub = subsets[i] self.trees[i].fit(X_sub, y_sub) def predict(self, X): all_preds = np.empty((X.shape[0], self.n_estimators)) for i, tree in enumerate(self.trees): preds = tree.predict(X) all_preds[:, i] = preds y_preds = [] for preds in all_preds: if self.is_classification_forest: y_preds.append(np.bincount(preds.astype('int')).argmax()) else: y_preds.append(np.average(preds)) return y_preds
[ "numpy.random.default_rng", "numpy.average", "math.sqrt", "DecisionTree.DecisionTree", "numpy.empty", "numpy.random.seed", "numpy.concatenate", "numpy.expand_dims", "os.path.abspath", "numpy.shape", "numpy.random.shuffle" ]
[((127, 161), 'os.path.abspath', 'os.path.abspath', (['"""../DecisionTree"""'], {}), "('../DecisionTree')\n", (142, 161), False, 'import os\n'), ((3279, 3309), 'numpy.concatenate', 'np.concatenate', (['(X, y)'], {'axis': '(1)'}), '((X, y), axis=1)\n', (3293, 3309), True, 'import numpy as np\n'), ((3351, 3372), 'numpy.random.shuffle', 'np.random.shuffle', (['Xy'], {}), '(Xy)\n', (3368, 3372), True, 'import numpy as np\n'), ((3387, 3431), 'numpy.random.default_rng', 'np.random.default_rng', ([], {'seed': 'self.random_seed'}), '(seed=self.random_seed)\n', (3408, 3431), True, 'import numpy as np\n'), ((3750, 3782), 'numpy.random.seed', 'np.random.seed', (['self.random_seed'], {}), '(self.random_seed)\n', (3764, 3782), True, 'import numpy as np\n'), ((4556, 4597), 'numpy.empty', 'np.empty', (['(X.shape[0], self.n_estimators)'], {}), '((X.shape[0], self.n_estimators))\n', (4564, 4597), True, 'import numpy as np\n'), ((3239, 3264), 'numpy.expand_dims', 'np.expand_dims', (['y'], {'axis': '(1)'}), '(y, axis=1)\n', (3253, 3264), True, 'import numpy as np\n'), ((2374, 2552), 'DecisionTree.DecisionTree', 'DecisionTree', ([], {'max_depth': 'self.max_depth', 'min_samples_split': 'self.min_samples_split', 'max_features': 'self.max_features', 'criterion': 'self.criterion', 'random_seed': 'self.random_seed'}), '(max_depth=self.max_depth, min_samples_split=self.\n min_samples_split, max_features=self.max_features, criterion=self.\n criterion, random_seed=self.random_seed)\n', (2386, 2552), False, 'from DecisionTree import DecisionTree\n'), ((3204, 3215), 'numpy.shape', 'np.shape', (['y'], {}), '(y)\n', (3212, 3215), True, 'import numpy as np\n'), ((4034, 4055), 'math.sqrt', 'math.sqrt', (['X.shape[1]'], {}), '(X.shape[1])\n', (4043, 4055), False, 'import math\n'), ((4940, 4957), 'numpy.average', 'np.average', (['preds'], {}), '(preds)\n', (4950, 4957), True, 'import numpy as np\n')]
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Authors : <NAME> (<EMAIL>) & <NAME> (<EMAIL>) # @Paper : Rethinking Graph Autoencoder Models for Attributed Graph Clustering # @License : MIT License import torch import numpy as np import torch.nn as nn import scipy.sparse as sp import torch.nn.functional as F from tqdm import tqdm from torch.optim import Adam from sklearn.mixture import GaussianMixture from torch.optim.lr_scheduler import StepLR from preprocessing import sparse_to_tuple from sklearn.neighbors import NearestNeighbors from sklearn import metrics from munkres import Munkres def random_uniform_init(input_dim, output_dim): init_range = np.sqrt(6.0 / (input_dim + output_dim)) initial = torch.rand(input_dim, output_dim)*2*init_range - init_range return nn.Parameter(initial) def q_mat(X, centers, alpha=1.0): X = X.detach().numpy() centers = centers.detach().numpy() if X.size == 0: q = np.array([]) else: q = 1.0 / (1.0 + (np.sum(np.square(np.expand_dims(X, 1) - centers), axis=2) / alpha)) q = q ** ((alpha + 1.0) / 2.0) q = np.transpose(np.transpose(q) / np.sum(q, axis=1)) return q def generate_unconflicted_data_index(emb, centers_emb, beta1, beta2): unconf_indices = [] conf_indices = [] q = q_mat(emb, centers_emb, alpha=1.0) confidence1 = q.max(1) confidence2 = np.zeros((q.shape[0],)) a = np.argsort(q, axis=1) for i in range(q.shape[0]): confidence1[i] = q[i,a[i,-1]] confidence2[i] = q[i,a[i,-2]] if (confidence1[i]) > beta1 and (confidence1[i] - confidence2[i]) > beta2: unconf_indices.append(i) else: conf_indices.append(i) unconf_indices = np.asarray(unconf_indices, dtype=int) conf_indices = np.asarray(conf_indices, dtype=int) return unconf_indices, conf_indices class clustering_metrics(): def __init__(self, true_label, predict_label): self.true_label = true_label self.pred_label = predict_label def clusteringAcc(self): # best mapping between true_label and predict label l1 = list(set(self.true_label)) numclass1 = len(l1) l2 = list(set(self.pred_label)) numclass2 = len(l2) if numclass1 != numclass2: print('Class Not equal, Error!!!!') return 0 cost = np.zeros((numclass1, numclass2), dtype=int) for i, c1 in enumerate(l1): mps = [i1 for i1, e1 in enumerate(self.true_label) if e1 == c1] for j, c2 in enumerate(l2): mps_d = [i1 for i1 in mps if self.pred_label[i1] == c2] cost[i][j] = len(mps_d) # match two clustering results by Munkres algorithm m = Munkres() cost = cost.__neg__().tolist() indexes = m.compute(cost) # get the match results new_predict = np.zeros(len(self.pred_label)) for i, c in enumerate(l1): # correponding label in l2: c2 = l2[indexes[i][1]] # ai is the index with label==c2 in the pred_label list ai = [ind for ind, elm in enumerate(self.pred_label) if elm == c2] new_predict[ai] = c acc = metrics.accuracy_score(self.true_label, new_predict) f1_macro = metrics.f1_score(self.true_label, new_predict, average='macro') precision_macro = metrics.precision_score(self.true_label, new_predict, average='macro') recall_macro = metrics.recall_score(self.true_label, new_predict, average='macro') f1_micro = metrics.f1_score(self.true_label, new_predict, average='micro') precision_micro = metrics.precision_score(self.true_label, new_predict, average='micro') recall_micro = metrics.recall_score(self.true_label, new_predict, average='micro') return acc, f1_macro, precision_macro, recall_macro, f1_micro, precision_micro, recall_micro def evaluationClusterModelFromLabel(self): nmi = metrics.normalized_mutual_info_score(self.true_label, self.pred_label) adjscore = metrics.adjusted_rand_score(self.true_label, self.pred_label) acc, f1_macro, precision_macro, recall_macro, f1_micro, precision_micro, recall_micro = self.clusteringAcc() print('ACC=%f, f1_macro=%f, precision_macro=%f, recall_macro=%f, f1_micro=%f, precision_micro=%f, recall_micro=%f, NMI=%f, ADJ_RAND_SCORE=%f' % (acc, f1_macro, precision_macro, recall_macro, f1_micro, precision_micro, recall_micro, nmi, adjscore)) fh = open('recoder.txt', 'a') fh.write('ACC=%f, f1_macro=%f, precision_macro=%f, recall_macro=%f, f1_micro=%f, precision_micro=%f, recall_micro=%f, NMI=%f, ADJ_RAND_SCORE=%f' % (acc, f1_macro, precision_macro, recall_macro, f1_micro, precision_micro, recall_micro, nmi, adjscore) ) fh.write('\r\n') fh.flush() fh.close() return acc, nmi, adjscore, f1_macro, precision_macro, f1_micro, precision_micro class GraphConvSparse(nn.Module): def __init__(self, input_dim, output_dim, activation = F.relu, **kwargs): super(GraphConvSparse, self).__init__(**kwargs) self.weight = random_uniform_init(input_dim, output_dim) self.activation = activation def forward(self, inputs, adj): x = inputs x = torch.mm(x,self.weight) x = torch.mm(adj, x) outputs = self.activation(x) return outputs class ReGMM_VGAE(nn.Module): def __init__(self, **kwargs): super(ReGMM_VGAE, self).__init__() self.num_neurons = kwargs['num_neurons'] self.num_features = kwargs['num_features'] self.embedding_size = kwargs['embedding_size'] self.nClusters = kwargs['nClusters'] # VGAE training parameters self.base_gcn = GraphConvSparse( self.num_features, self.num_neurons) self.gcn_mean = GraphConvSparse( self.num_neurons, self.embedding_size, activation = lambda x:x) self.gcn_logstddev = GraphConvSparse( self.num_neurons, self.embedding_size, activation = lambda x:x) # GMM training parameters self.pi = nn.Parameter(torch.ones(self.nClusters)/self.nClusters, requires_grad=True) self.mu_c = nn.Parameter(torch.randn(self.nClusters, self.embedding_size),requires_grad=True) self.log_sigma2_c = nn.Parameter(torch.randn(self.nClusters, self.embedding_size),requires_grad=True) def pretrain(self, adj, features, adj_label, y, weight_tensor, norm, epochs, lr, save_path, dataset): opti = Adam(self.parameters(), lr=lr) epoch_bar = tqdm(range(epochs)) gmm = GaussianMixture(n_components = self.nClusters , covariance_type = 'diag') for _ in epoch_bar: opti.zero_grad() _,_, z = self.encode(features, adj) x_ = self.decode(z) loss = norm*F.binary_cross_entropy(x_.view(-1), adj_label.to_dense().view(-1), weight = weight_tensor) loss.backward() opti.step() gmm.fit_predict(z.detach().numpy()) self.pi.data = torch.from_numpy(gmm.weights_) self.mu_c.data = torch.from_numpy(gmm.means_) self.log_sigma2_c.data = torch.log(torch.from_numpy(gmm.covariances_)) self.logstd = self.mean def ELBO_Loss(self, features, adj, x_, adj_label, weight_tensor, norm, z_mu, z_sigma2_log, emb, L=1): pi = self.pi mu_c = self.mu_c log_sigma2_c = self.log_sigma2_c det = 1e-2 Loss = 1e-2 * norm * F.binary_cross_entropy(x_.view(-1), adj_label, weight = weight_tensor) Loss = Loss * features.size(0) yita_c = torch.exp(torch.log(pi.unsqueeze(0))+self.gaussian_pdfs_log(emb,mu_c,log_sigma2_c))+det yita_c = yita_c / (yita_c.sum(1).view(-1,1)) KL1 = 0.5 * torch.mean(torch.sum(yita_c*torch.sum(log_sigma2_c.unsqueeze(0)+ torch.exp(z_sigma2_log.unsqueeze(1)-log_sigma2_c.unsqueeze(0))+ (z_mu.unsqueeze(1)-mu_c.unsqueeze(0)).pow(2)/torch.exp(log_sigma2_c.unsqueeze(0)),2),1)) Loss1 = KL1 KL2= torch.mean(torch.sum(yita_c*torch.log(pi.unsqueeze(0)/(yita_c)),1))+0.5*torch.mean(torch.sum(1+z_sigma2_log,1)) Loss1 -= KL2 return Loss, Loss1, Loss+Loss1 def generate_centers(self, emb_unconf): y_pred = self.predict(emb_unconf) nn = NearestNeighbors(n_neighbors= 1, algorithm='ball_tree').fit(emb_unconf.detach().numpy()) _, indices = nn.kneighbors(self.mu_c.detach().numpy()) return indices[y_pred] def update_graph(self, adj, labels, emb, unconf_indices, conf_indices): k = 0 y_pred = self.predict(emb) emb_unconf = emb[unconf_indices] adj = adj.tolil() idx = unconf_indices[self.generate_centers(emb_unconf)] for i, k in enumerate(unconf_indices): adj_k = adj[k].tocsr().indices if not(np.isin(idx[i], adj_k)) and (y_pred[k] == y_pred[idx[i]]) : adj[k, idx[i]] = 1 for j in adj_k: if np.isin(j, unconf_indices) and (np.isin(idx[i], adj_k)) and (y_pred[k] != y_pred[j]): adj[k, j] = 0 adj = adj.tocsr() adj_label = adj + sp.eye(adj.shape[0]) adj_label = sparse_to_tuple(adj_label) adj_label = torch.sparse.FloatTensor(torch.LongTensor(adj_label[0].T), torch.FloatTensor(adj_label[1]), torch.Size(adj_label[2])) weight_mask = adj_label.to_dense().view(-1) == 1 weight_tensor = torch.ones(weight_mask.size(0)) pos_weight_orig = float(adj.shape[0] * adj.shape[0] - adj.sum()) / adj.sum() weight_tensor[weight_mask] = pos_weight_orig return adj, adj_label, weight_tensor def train(self, adj_norm, adj, features, y, norm, epochs, lr, beta1, beta2, save_path, dataset): self.load_state_dict(torch.load(save_path + dataset + '/pretrain/model.pk')) opti = Adam(self.parameters(), lr=lr, weight_decay = 0.089) lr_s = StepLR(opti, step_size=10, gamma=0.9) import os, csv epoch_bar = tqdm(range(epochs)) previous_unconflicted = [] previous_conflicted = [] epoch_stable = 0 for epoch in epoch_bar: opti.zero_grad() z_mu, z_sigma2_log, emb = self.encode(features, adj_norm) x_ = self.decode(emb) unconflicted_ind, conflicted_ind = generate_unconflicted_data_index(emb, self.mu_c, beta1, beta2) if epoch == 0: adj, adj_label, weight_tensor = self.update_graph(adj, y, emb, unconflicted_ind, conflicted_ind) if len(previous_unconflicted) < len(unconflicted_ind) : z_mu = z_mu[unconflicted_ind] z_sigma2_log = z_sigma2_log[unconflicted_ind] emb_unconf = emb[unconflicted_ind] emb_conf = emb[conflicted_ind] previous_conflicted = conflicted_ind previous_unconflicted = unconflicted_ind else : epoch_stable += 1 z_mu = z_mu[previous_unconflicted] z_sigma2_log = z_sigma2_log[previous_unconflicted] emb_unconf = emb[previous_unconflicted] emb_conf = emb[previous_conflicted] if epoch_stable >= 15: epoch_stable = 0 beta1 = beta1 * 0.96 beta2 = beta2 * 0.98 if epoch % 50 == 0 and epoch <= 200 : adj, adj_label, weight_tensor = self.update_graph(adj, y, emb, unconflicted_ind, conflicted_ind) loss, loss1, elbo_loss = self.ELBO_Loss(features, adj_norm, x_, adj_label.to_dense().view(-1), weight_tensor, norm, z_mu , z_sigma2_log, emb_unconf) epoch_bar.write('Loss={:.4f}'.format(elbo_loss.detach().numpy())) y_pred = self.predict(emb) cm = clustering_metrics(y, y_pred) acc, nmi, adjscore, f1_macro, precision_macro, f1_micro, precision_micro = cm.evaluationClusterModelFromLabel() elbo_loss.backward() opti.step() lr_s.step() def gaussian_pdfs_log(self,x,mus,log_sigma2s): G=[] for c in range(self.nClusters): G.append(self.gaussian_pdf_log(x,mus[c:c+1,:],log_sigma2s[c:c+1,:]).view(-1,1)) return torch.cat(G,1) def gaussian_pdf_log(self,x,mu,log_sigma2): c = -0.5 * torch.sum(np.log(np.pi*2)+log_sigma2+(x-mu).pow(2)/torch.exp(log_sigma2),1) return c def predict(self, z): pi = self.pi log_sigma2_c = self.log_sigma2_c mu_c = self.mu_c det = 1e-2 yita_c = torch.exp(torch.log(pi.unsqueeze(0))+self.gaussian_pdfs_log(z,mu_c,log_sigma2_c))+det yita = yita_c.detach().numpy() return np.argmax(yita, axis=1) def encode(self, x_features, adj): hidden = self.base_gcn(x_features, adj) self.mean = self.gcn_mean(hidden, adj) self.logstd = self.gcn_logstddev(hidden, adj) gaussian_noise = torch.randn(x_features.size(0), self.embedding_size) sampled_z = gaussian_noise * torch.exp(self.logstd) + self.mean return self.mean, self.logstd ,sampled_z @staticmethod def decode(z): A_pred = torch.sigmoid(torch.matmul(z,z.t())) return A_pred
[ "numpy.sqrt", "torch.LongTensor", "numpy.log", "sklearn.metrics.adjusted_rand_score", "torch.from_numpy", "sklearn.metrics.precision_score", "numpy.argsort", "numpy.array", "sklearn.metrics.recall_score", "torch.exp", "torch.sum", "numpy.isin", "sklearn.metrics.normalized_mutual_info_score", "scipy.sparse.eye", "numpy.asarray", "sklearn.neighbors.NearestNeighbors", "torch.randn", "sklearn.mixture.GaussianMixture", "torch.rand", "numpy.argmax", "numpy.transpose", "torch.Size", "sklearn.metrics.accuracy_score", "torch.cat", "sklearn.metrics.f1_score", "torch.load", "torch.optim.lr_scheduler.StepLR", "torch.mm", "numpy.sum", "numpy.zeros", "torch.nn.Parameter", "munkres.Munkres", "numpy.expand_dims", "torch.FloatTensor", "preprocessing.sparse_to_tuple", "torch.ones" ]
[((664, 703), 'numpy.sqrt', 'np.sqrt', (['(6.0 / (input_dim + output_dim))'], {}), '(6.0 / (input_dim + output_dim))\n', (671, 703), True, 'import numpy as np\n'), ((789, 810), 'torch.nn.Parameter', 'nn.Parameter', (['initial'], {}), '(initial)\n', (801, 810), True, 'import torch.nn as nn\n'), ((1386, 1409), 'numpy.zeros', 'np.zeros', (['(q.shape[0],)'], {}), '((q.shape[0],))\n', (1394, 1409), True, 'import numpy as np\n'), ((1418, 1439), 'numpy.argsort', 'np.argsort', (['q'], {'axis': '(1)'}), '(q, axis=1)\n', (1428, 1439), True, 'import numpy as np\n'), ((1738, 1775), 'numpy.asarray', 'np.asarray', (['unconf_indices'], {'dtype': 'int'}), '(unconf_indices, dtype=int)\n', (1748, 1775), True, 'import numpy as np\n'), ((1795, 1830), 'numpy.asarray', 'np.asarray', (['conf_indices'], {'dtype': 'int'}), '(conf_indices, dtype=int)\n', (1805, 1830), True, 'import numpy as np\n'), ((944, 956), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (952, 956), True, 'import numpy as np\n'), ((2375, 2418), 'numpy.zeros', 'np.zeros', (['(numclass1, numclass2)'], {'dtype': 'int'}), '((numclass1, numclass2), dtype=int)\n', (2383, 2418), True, 'import numpy as np\n'), ((2757, 2766), 'munkres.Munkres', 'Munkres', ([], {}), '()\n', (2764, 2766), False, 'from munkres import Munkres\n'), ((3245, 3297), 'sklearn.metrics.accuracy_score', 'metrics.accuracy_score', (['self.true_label', 'new_predict'], {}), '(self.true_label, new_predict)\n', (3267, 3297), False, 'from sklearn import metrics\n'), ((3326, 3389), 'sklearn.metrics.f1_score', 'metrics.f1_score', (['self.true_label', 'new_predict'], {'average': '"""macro"""'}), "(self.true_label, new_predict, average='macro')\n", (3342, 3389), False, 'from sklearn import metrics\n'), ((3416, 3486), 'sklearn.metrics.precision_score', 'metrics.precision_score', (['self.true_label', 'new_predict'], {'average': '"""macro"""'}), "(self.true_label, new_predict, average='macro')\n", (3439, 3486), False, 'from sklearn import metrics\n'), ((3510, 3577), 'sklearn.metrics.recall_score', 'metrics.recall_score', (['self.true_label', 'new_predict'], {'average': '"""macro"""'}), "(self.true_label, new_predict, average='macro')\n", (3530, 3577), False, 'from sklearn import metrics\n'), ((3597, 3660), 'sklearn.metrics.f1_score', 'metrics.f1_score', (['self.true_label', 'new_predict'], {'average': '"""micro"""'}), "(self.true_label, new_predict, average='micro')\n", (3613, 3660), False, 'from sklearn import metrics\n'), ((3687, 3757), 'sklearn.metrics.precision_score', 'metrics.precision_score', (['self.true_label', 'new_predict'], {'average': '"""micro"""'}), "(self.true_label, new_predict, average='micro')\n", (3710, 3757), False, 'from sklearn import metrics\n'), ((3781, 3848), 'sklearn.metrics.recall_score', 'metrics.recall_score', (['self.true_label', 'new_predict'], {'average': '"""micro"""'}), "(self.true_label, new_predict, average='micro')\n", (3801, 3848), False, 'from sklearn import metrics\n'), ((4012, 4082), 'sklearn.metrics.normalized_mutual_info_score', 'metrics.normalized_mutual_info_score', (['self.true_label', 'self.pred_label'], {}), '(self.true_label, self.pred_label)\n', (4048, 4082), False, 'from sklearn import metrics\n'), ((4102, 4163), 'sklearn.metrics.adjusted_rand_score', 'metrics.adjusted_rand_score', (['self.true_label', 'self.pred_label'], {}), '(self.true_label, self.pred_label)\n', (4129, 4163), False, 'from sklearn import metrics\n'), ((5338, 5362), 'torch.mm', 'torch.mm', (['x', 'self.weight'], {}), '(x, self.weight)\n', (5346, 5362), False, 'import torch\n'), ((5374, 5390), 'torch.mm', 'torch.mm', (['adj', 'x'], {}), '(adj, x)\n', (5382, 5390), False, 'import torch\n'), ((6689, 6757), 'sklearn.mixture.GaussianMixture', 'GaussianMixture', ([], {'n_components': 'self.nClusters', 'covariance_type': '"""diag"""'}), "(n_components=self.nClusters, covariance_type='diag')\n", (6704, 6757), False, 'from sklearn.mixture import GaussianMixture\n'), ((7134, 7164), 'torch.from_numpy', 'torch.from_numpy', (['gmm.weights_'], {}), '(gmm.weights_)\n', (7150, 7164), False, 'import torch\n'), ((7190, 7218), 'torch.from_numpy', 'torch.from_numpy', (['gmm.means_'], {}), '(gmm.means_)\n', (7206, 7218), False, 'import torch\n'), ((9426, 9452), 'preprocessing.sparse_to_tuple', 'sparse_to_tuple', (['adj_label'], {}), '(adj_label)\n', (9441, 9452), False, 'from preprocessing import sparse_to_tuple\n'), ((10231, 10268), 'torch.optim.lr_scheduler.StepLR', 'StepLR', (['opti'], {'step_size': '(10)', 'gamma': '(0.9)'}), '(opti, step_size=10, gamma=0.9)\n', (10237, 10268), False, 'from torch.optim.lr_scheduler import StepLR\n'), ((12602, 12617), 'torch.cat', 'torch.cat', (['G', '(1)'], {}), '(G, 1)\n', (12611, 12617), False, 'import torch\n'), ((13070, 13093), 'numpy.argmax', 'np.argmax', (['yita'], {'axis': '(1)'}), '(yita, axis=1)\n', (13079, 13093), True, 'import numpy as np\n'), ((6269, 6317), 'torch.randn', 'torch.randn', (['self.nClusters', 'self.embedding_size'], {}), '(self.nClusters, self.embedding_size)\n', (6280, 6317), False, 'import torch\n'), ((6379, 6427), 'torch.randn', 'torch.randn', (['self.nClusters', 'self.embedding_size'], {}), '(self.nClusters, self.embedding_size)\n', (6390, 6427), False, 'import torch\n'), ((7263, 7297), 'torch.from_numpy', 'torch.from_numpy', (['gmm.covariances_'], {}), '(gmm.covariances_)\n', (7279, 7297), False, 'import torch\n'), ((9385, 9405), 'scipy.sparse.eye', 'sp.eye', (['adj.shape[0]'], {}), '(adj.shape[0])\n', (9391, 9405), True, 'import scipy.sparse as sp\n'), ((9498, 9530), 'torch.LongTensor', 'torch.LongTensor', (['adj_label[0].T'], {}), '(adj_label[0].T)\n', (9514, 9530), False, 'import torch\n'), ((9569, 9600), 'torch.FloatTensor', 'torch.FloatTensor', (['adj_label[1]'], {}), '(adj_label[1])\n', (9586, 9600), False, 'import torch\n'), ((9638, 9662), 'torch.Size', 'torch.Size', (['adj_label[2]'], {}), '(adj_label[2])\n', (9648, 9662), False, 'import torch\n'), ((10092, 10146), 'torch.load', 'torch.load', (["(save_path + dataset + '/pretrain/model.pk')"], {}), "(save_path + dataset + '/pretrain/model.pk')\n", (10102, 10146), False, 'import torch\n'), ((718, 751), 'torch.rand', 'torch.rand', (['input_dim', 'output_dim'], {}), '(input_dim, output_dim)\n', (728, 751), False, 'import torch\n'), ((1125, 1140), 'numpy.transpose', 'np.transpose', (['q'], {}), '(q)\n', (1137, 1140), True, 'import numpy as np\n'), ((1143, 1160), 'numpy.sum', 'np.sum', (['q'], {'axis': '(1)'}), '(q, axis=1)\n', (1149, 1160), True, 'import numpy as np\n'), ((6173, 6199), 'torch.ones', 'torch.ones', (['self.nClusters'], {}), '(self.nClusters)\n', (6183, 6199), False, 'import torch\n'), ((8517, 8571), 'sklearn.neighbors.NearestNeighbors', 'NearestNeighbors', ([], {'n_neighbors': '(1)', 'algorithm': '"""ball_tree"""'}), "(n_neighbors=1, algorithm='ball_tree')\n", (8533, 8571), False, 'from sklearn.neighbors import NearestNeighbors\n'), ((13398, 13420), 'torch.exp', 'torch.exp', (['self.logstd'], {}), '(self.logstd)\n', (13407, 13420), False, 'import torch\n'), ((8328, 8358), 'torch.sum', 'torch.sum', (['(1 + z_sigma2_log)', '(1)'], {}), '(1 + z_sigma2_log, 1)\n', (8337, 8358), False, 'import torch\n'), ((9071, 9093), 'numpy.isin', 'np.isin', (['idx[i]', 'adj_k'], {}), '(idx[i], adj_k)\n', (9078, 9093), True, 'import numpy as np\n'), ((9213, 9239), 'numpy.isin', 'np.isin', (['j', 'unconf_indices'], {}), '(j, unconf_indices)\n', (9220, 9239), True, 'import numpy as np\n'), ((9245, 9267), 'numpy.isin', 'np.isin', (['idx[i]', 'adj_k'], {}), '(idx[i], adj_k)\n', (9252, 9267), True, 'import numpy as np\n'), ((12695, 12712), 'numpy.log', 'np.log', (['(np.pi * 2)'], {}), '(np.pi * 2)\n', (12701, 12712), True, 'import numpy as np\n'), ((12736, 12757), 'torch.exp', 'torch.exp', (['log_sigma2'], {}), '(log_sigma2)\n', (12745, 12757), False, 'import torch\n'), ((1010, 1030), 'numpy.expand_dims', 'np.expand_dims', (['X', '(1)'], {}), '(X, 1)\n', (1024, 1030), True, 'import numpy as np\n')]
import math import numpy as np import numpy.random as npr import torch import torch.utils.data as data import torch.utils.data.sampler as torch_sampler from torch.utils.data.dataloader import default_collate from torch._six import int_classes as _int_classes from core.config import cfg from roi_data.minibatch import get_minibatch import utils.blob as blob_utils # from model.rpn.bbox_transform import bbox_transform_inv, clip_boxes class RoiDataLoader(data.Dataset): def __init__(self, roidb, num_classes, training=True): self._roidb = roidb self._num_classes = num_classes self.training = training self.DATA_SIZE = len(self._roidb) def __getitem__(self, index_tuple): index, ratio = index_tuple single_db = [self._roidb[index]] blobs, valid = get_minibatch(single_db, self._num_classes) #TODO: Check if minibatch is valid ? If not, abandon it. # Need to change _worker_loop in torch.utils.data.dataloader.py. # Squeeze batch dim # for key in blobs: # if key != 'roidb': # blobs[key] = blobs[key].squeeze(axis=0) blobs['data'] = blobs['data'].squeeze(axis=0) return blobs def __len__(self): return self.DATA_SIZE def cal_minibatch_ratio(ratio_list): """Given the ratio_list, we want to make the RATIO same for each minibatch on each GPU. Note: this only work for 1) cfg.TRAIN.MAX_SIZE is ignored during `prep_im_for_blob` and 2) cfg.TRAIN.SCALES containing SINGLE scale. Since all prepared images will have same min side length of cfg.TRAIN.SCALES[0], we can pad and batch images base on that. """ DATA_SIZE = len(ratio_list) ratio_list_minibatch = np.empty((DATA_SIZE,)) num_minibatch = int(np.ceil(DATA_SIZE / cfg.TRAIN.IMS_PER_BATCH)) # Include leftovers for i in range(num_minibatch): left_idx = i * cfg.TRAIN.IMS_PER_BATCH right_idx = min((i+1) * cfg.TRAIN.IMS_PER_BATCH - 1, DATA_SIZE - 1) if ratio_list[right_idx] < 1: # for ratio < 1, we preserve the leftmost in each batch. target_ratio = ratio_list[left_idx] elif ratio_list[left_idx] > 1: # for ratio > 1, we preserve the rightmost in each batch. target_ratio = ratio_list[right_idx] else: # for ratio cross 1, we make it to be 1. target_ratio = 1 ratio_list_minibatch[left_idx:(right_idx+1)] = target_ratio return ratio_list_minibatch class MinibatchSampler(torch_sampler.Sampler): def __init__(self, ratio_list, ratio_index): self.ratio_list = ratio_list self.ratio_index = ratio_index self.num_data = len(ratio_list) def __iter__(self): rand_perm = npr.permutation(self.num_data) ratio_list = self.ratio_list[rand_perm] ratio_index = self.ratio_index[rand_perm] # re-calculate minibatch ratio list ratio_list_minibatch = cal_minibatch_ratio(ratio_list) return iter(zip(ratio_index.tolist(), ratio_list_minibatch.tolist())) def __len__(self): return self.num_data class BatchSampler(torch_sampler.BatchSampler): r"""Wraps another sampler to yield a mini-batch of indices. Args: sampler (Sampler): Base sampler. batch_size (int): Size of mini-batch. drop_last (bool): If ``True``, the sampler will drop the last batch if its size would be less than ``batch_size`` Example: >>> list(BatchSampler(range(10), batch_size=3, drop_last=False)) [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]] >>> list(BatchSampler(range(10), batch_size=3, drop_last=True)) [[0, 1, 2], [3, 4, 5], [6, 7, 8]] """ def __init__(self, sampler, batch_size, drop_last): if not isinstance(sampler, torch_sampler.Sampler): raise ValueError("sampler should be an instance of " "torch.utils.data.Sampler, but got sampler={}" .format(sampler)) if not isinstance(batch_size, _int_classes) or isinstance(batch_size, bool) or \ batch_size <= 0: raise ValueError("batch_size should be a positive integeral value, " "but got batch_size={}".format(batch_size)) if not isinstance(drop_last, bool): raise ValueError("drop_last should be a boolean value, but got " "drop_last={}".format(drop_last)) self.sampler = sampler self.batch_size = batch_size self.drop_last = drop_last def __iter__(self): batch = [] for idx in self.sampler: batch.append(idx) # Difference: batch.append(int(idx)) if len(batch) == self.batch_size: yield batch batch = [] if len(batch) > 0 and not self.drop_last: yield batch def __len__(self): if self.drop_last: return len(self.sampler) // self.batch_size else: return (len(self.sampler) + self.batch_size - 1) // self.batch_size def collate_minibatch(list_of_blobs): """Stack samples seperately and return a list of minibatches A batch contains NUM_GPUS minibatches and image size in different minibatch may be different. Hence, we need to stack smaples from each minibatch seperately. """ Batch = {key: [] for key in list_of_blobs[0]} # Because roidb consists of entries of variable length, it can't be batch into a tensor. # So we keep roidb in the type of "list of ndarray". lists = [] for blobs in list_of_blobs: lists.append({'data' : blobs.pop('data'), 'rois' : blobs.pop('rois'), 'labels' : blobs.pop('labels')}) for i in range(0, len(list_of_blobs), cfg.TRAIN.IMS_PER_BATCH): mini_list = lists[i:(i + cfg.TRAIN.IMS_PER_BATCH)] minibatch = default_collate(mini_list) for key in minibatch: Batch[key].append(minibatch[key]) return Batch
[ "torch.utils.data.dataloader.default_collate", "numpy.ceil", "roi_data.minibatch.get_minibatch", "numpy.empty", "numpy.random.permutation" ]
[((1746, 1768), 'numpy.empty', 'np.empty', (['(DATA_SIZE,)'], {}), '((DATA_SIZE,))\n', (1754, 1768), True, 'import numpy as np\n'), ((815, 858), 'roi_data.minibatch.get_minibatch', 'get_minibatch', (['single_db', 'self._num_classes'], {}), '(single_db, self._num_classes)\n', (828, 858), False, 'from roi_data.minibatch import get_minibatch\n'), ((1793, 1837), 'numpy.ceil', 'np.ceil', (['(DATA_SIZE / cfg.TRAIN.IMS_PER_BATCH)'], {}), '(DATA_SIZE / cfg.TRAIN.IMS_PER_BATCH)\n', (1800, 1837), True, 'import numpy as np\n'), ((2788, 2818), 'numpy.random.permutation', 'npr.permutation', (['self.num_data'], {}), '(self.num_data)\n', (2803, 2818), True, 'import numpy.random as npr\n'), ((5973, 5999), 'torch.utils.data.dataloader.default_collate', 'default_collate', (['mini_list'], {}), '(mini_list)\n', (5988, 5999), False, 'from torch.utils.data.dataloader import default_collate\n')]
""" Utility methods for parsing data returned from MapD """ import datetime from collections import namedtuple from sqlalchemy import text import mapd.ttypes as T from ._utils import seconds_to_time Description = namedtuple("Description", ["name", "type_code", "display_size", "internal_size", "precision", "scale", "null_ok"]) ColumnDetails = namedtuple("ColumnDetails", ["name", "type", "nullable", "precision", "scale", "comp_param"]) _typeattr = { 'SMALLINT': 'int', 'INT': 'int', 'BIGINT': 'int', 'TIME': 'int', 'TIMESTAMP': 'int', 'DATE': 'int', 'BOOL': 'int', 'FLOAT': 'real', 'DECIMAL': 'real', 'DOUBLE': 'real', 'STR': 'str', } _thrift_types_to_values = T.TDatumType._NAMES_TO_VALUES _thrift_values_to_types = T.TDatumType._VALUES_TO_NAMES def _extract_row_val(desc, val): # type: (T.TColumnType, T.TDatum) -> Any typename = T.TDatumType._VALUES_TO_NAMES[desc.col_type.type] if val.is_null: return None val = getattr(val.val, _typeattr[typename] + '_val') base = datetime.datetime(1970, 1, 1) if typename == 'TIMESTAMP': val = (base + datetime.timedelta(seconds=val)) elif typename == 'DATE': val = (base + datetime.timedelta(seconds=val)).date() elif typename == 'TIME': val = seconds_to_time(val) return val def _extract_col_vals(desc, val): # type: (T.TColumnType, T.TColumn) -> Any typename = T.TDatumType._VALUES_TO_NAMES[desc.col_type.type] nulls = val.nulls vals = getattr(val.data, _typeattr[typename] + '_col') vals = [None if null else v for null, v in zip(nulls, vals)] base = datetime.datetime(1970, 1, 1) if typename == 'TIMESTAMP': vals = [None if v is None else base + datetime.timedelta(seconds=v) for v in vals] elif typename == 'DATE': vals = [None if v is None else (base + datetime.timedelta(seconds=v)).date() for v in vals] elif typename == 'TIME': vals = [None if v is None else seconds_to_time(v) for v in vals] return vals def _extract_description(row_desc): # type: (List[T.TColumnType]) -> List[Description] """ Return a tuple of (name, type_code, display_size, internal_size, precision, scale, null_ok) https://www.python.org/dev/peps/pep-0249/#description """ return [Description(col.col_name, col.col_type.type, None, None, None, None, col.col_type.nullable) for col in row_desc] def _extract_column_details(row_desc): # For Connection.get_table_details return [ ColumnDetails(x.col_name, _thrift_values_to_types[x.col_type.type], x.col_type.nullable, x.col_type.precision, x.col_type.scale, x.col_type.comp_param) for x in row_desc ] def _is_columnar(data): # type: (T.TQueryResult) -> bool return data.row_set.is_columnar def _load_schema(buf): """ Load a `pyarrow.Schema` from a buffer written to shared memory Parameters ---------- buf : pyarrow.Buffer Returns ------- schema : pyarrow.Schema """ import pyarrow as pa reader = pa.RecordBatchStreamReader(buf) return reader.schema def _load_data(buf, schema): """ Load a `pandas.DataFrame` from a buffer written to shared memory Parameters ---------- buf : pyarrow.Buffer shcema : pyarrow.Schema Returns ------- df : pandas.DataFrame """ import pyarrow as pa message = pa.read_message(buf) rb = pa.read_record_batch(message, schema) return rb.to_pandas() def _parse_tdf_gpu(tdf): """ Parse the results of a select ipc_gpu into a GpuDataFrame Parameters ---------- tdf : TDataFrame Returns ------- gdf : GpuDataFrame """ import numpy as np from pygdf.gpuarrow import GpuArrowReader from pygdf.dataframe import DataFrame from numba import cuda from numba.cuda.cudadrv import drvapi from .shm import load_buffer ipc_handle = drvapi.cu_ipc_mem_handle(*tdf.df_handle) ipch = cuda.driver.IpcHandle(None, ipc_handle, size=tdf.df_size) ctx = cuda.current_context() dptr = ipch.open(ctx) schema_buffer = load_buffer(tdf.sm_handle, tdf.sm_size) # TODO: extra copy. schema_buffer = np.frombuffer(schema_buffer.to_pybytes(), dtype=np.uint8) dtype = np.dtype(np.byte) darr = cuda.devicearray.DeviceNDArray(shape=dptr.size, strides=dtype.itemsize, dtype=dtype, gpu_data=dptr) reader = GpuArrowReader(schema_buffer, darr) df = DataFrame() for k, v in reader.to_dict().items(): df[k] = v return df def _bind_parameters(operation, parameters): return (text(operation) .bindparams(**parameters) .compile(compile_kwargs={"literal_binds": True}))
[ "datetime.datetime", "pyarrow.read_message", "collections.namedtuple", "sqlalchemy.text", "pygdf.gpuarrow.GpuArrowReader", "pyarrow.read_record_batch", "numba.cuda.devicearray.DeviceNDArray", "pygdf.dataframe.DataFrame", "datetime.timedelta", "numba.cuda.cudadrv.drvapi.cu_ipc_mem_handle", "pyarrow.RecordBatchStreamReader", "numba.cuda.driver.IpcHandle", "numba.cuda.current_context", "numpy.dtype" ]
[((216, 334), 'collections.namedtuple', 'namedtuple', (['"""Description"""', "['name', 'type_code', 'display_size', 'internal_size', 'precision', 'scale',\n 'null_ok']"], {}), "('Description', ['name', 'type_code', 'display_size',\n 'internal_size', 'precision', 'scale', 'null_ok'])\n", (226, 334), False, 'from collections import namedtuple\n'), ((429, 526), 'collections.namedtuple', 'namedtuple', (['"""ColumnDetails"""', "['name', 'type', 'nullable', 'precision', 'scale', 'comp_param']"], {}), "('ColumnDetails', ['name', 'type', 'nullable', 'precision',\n 'scale', 'comp_param'])\n", (439, 526), False, 'from collections import namedtuple\n'), ((1222, 1251), 'datetime.datetime', 'datetime.datetime', (['(1970)', '(1)', '(1)'], {}), '(1970, 1, 1)\n', (1239, 1251), False, 'import datetime\n'), ((1827, 1856), 'datetime.datetime', 'datetime.datetime', (['(1970)', '(1)', '(1)'], {}), '(1970, 1, 1)\n', (1844, 1856), False, 'import datetime\n'), ((3456, 3487), 'pyarrow.RecordBatchStreamReader', 'pa.RecordBatchStreamReader', (['buf'], {}), '(buf)\n', (3482, 3487), True, 'import pyarrow as pa\n'), ((3804, 3824), 'pyarrow.read_message', 'pa.read_message', (['buf'], {}), '(buf)\n', (3819, 3824), True, 'import pyarrow as pa\n'), ((3834, 3871), 'pyarrow.read_record_batch', 'pa.read_record_batch', (['message', 'schema'], {}), '(message, schema)\n', (3854, 3871), True, 'import pyarrow as pa\n'), ((4335, 4375), 'numba.cuda.cudadrv.drvapi.cu_ipc_mem_handle', 'drvapi.cu_ipc_mem_handle', (['*tdf.df_handle'], {}), '(*tdf.df_handle)\n', (4359, 4375), False, 'from numba.cuda.cudadrv import drvapi\n'), ((4387, 4444), 'numba.cuda.driver.IpcHandle', 'cuda.driver.IpcHandle', (['None', 'ipc_handle'], {'size': 'tdf.df_size'}), '(None, ipc_handle, size=tdf.df_size)\n', (4408, 4444), False, 'from numba import cuda\n'), ((4455, 4477), 'numba.cuda.current_context', 'cuda.current_context', ([], {}), '()\n', (4475, 4477), False, 'from numba import cuda\n'), ((4680, 4697), 'numpy.dtype', 'np.dtype', (['np.byte'], {}), '(np.byte)\n', (4688, 4697), True, 'import numpy as np\n'), ((4709, 4812), 'numba.cuda.devicearray.DeviceNDArray', 'cuda.devicearray.DeviceNDArray', ([], {'shape': 'dptr.size', 'strides': 'dtype.itemsize', 'dtype': 'dtype', 'gpu_data': 'dptr'}), '(shape=dptr.size, strides=dtype.itemsize,\n dtype=dtype, gpu_data=dptr)\n', (4739, 4812), False, 'from numba import cuda\n'), ((4948, 4983), 'pygdf.gpuarrow.GpuArrowReader', 'GpuArrowReader', (['schema_buffer', 'darr'], {}), '(schema_buffer, darr)\n', (4962, 4983), False, 'from pygdf.gpuarrow import GpuArrowReader\n'), ((4993, 5004), 'pygdf.dataframe.DataFrame', 'DataFrame', ([], {}), '()\n', (5002, 5004), False, 'from pygdf.dataframe import DataFrame\n'), ((1306, 1337), 'datetime.timedelta', 'datetime.timedelta', ([], {'seconds': 'val'}), '(seconds=val)\n', (1324, 1337), False, 'import datetime\n'), ((1935, 1964), 'datetime.timedelta', 'datetime.timedelta', ([], {'seconds': 'v'}), '(seconds=v)\n', (1953, 1964), False, 'import datetime\n'), ((5139, 5154), 'sqlalchemy.text', 'text', (['operation'], {}), '(operation)\n', (5143, 5154), False, 'from sqlalchemy import text\n'), ((1390, 1421), 'datetime.timedelta', 'datetime.timedelta', ([], {'seconds': 'val'}), '(seconds=val)\n', (1408, 1421), False, 'import datetime\n'), ((2112, 2141), 'datetime.timedelta', 'datetime.timedelta', ([], {'seconds': 'v'}), '(seconds=v)\n', (2130, 2141), False, 'import datetime\n')]
import logging import warnings import dask.dataframe as dd import numpy as np import pandas as pd from featuretools import variable_types as vtypes from featuretools.utils.entity_utils import ( col_is_datetime, convert_all_variable_data, convert_variable_data, get_linked_vars, infer_variable_types ) from featuretools.utils.gen_utils import import_or_none, is_instance from featuretools.utils.wrangle import _check_time_type, _dataframes_equal from featuretools.variable_types import Text, find_variable_types ks = import_or_none('databricks.koalas') logger = logging.getLogger('featuretools.entityset') _numeric_types = vtypes.PandasTypes._pandas_numerics _categorical_types = [vtypes.PandasTypes._categorical] _datetime_types = vtypes.PandasTypes._pandas_datetimes class Entity(object): """Represents an entity in a Entityset, and stores relevant metadata and data An Entity is analogous to a table in a relational database See Also: :class:`.Relationship`, :class:`.Variable`, :class:`.EntitySet` """ def __init__(self, id, df, entityset, variable_types=None, index=None, time_index=None, secondary_time_index=None, last_time_index=None, already_sorted=False, make_index=False, verbose=False): """ Create Entity Args: id (str): Id of Entity. df (pd.DataFrame): Dataframe providing the data for the entity. entityset (EntitySet): Entityset for this Entity. variable_types (dict[str -> type/str/dict[str -> type]]) : An entity's variable_types dict maps string variable ids to types (:class:`.Variable`) or type_string (str) or (type, kwargs) to pass keyword arguments to the Variable. index (str): Name of id column in the dataframe. time_index (str): Name of time column in the dataframe. secondary_time_index (dict[str -> str]): Dictionary mapping columns in the dataframe to the time index column they are associated with. last_time_index (pd.Series): Time index of the last event for each instance across all child entities. make_index (bool, optional) : If True, assume index does not exist as a column in dataframe, and create a new column of that name using integers the (0, len(dataframe)). Otherwise, assume index exists in dataframe. """ _validate_entity_params(id, df, time_index) created_index, index, df = _create_index(index, make_index, df) self.id = id self.entityset = entityset self.data = {'df': df, 'last_time_index': last_time_index} self.created_index = created_index self._verbose = verbose secondary_time_index = secondary_time_index or {} self._create_variables(variable_types, index, time_index, secondary_time_index) self.df = df[[v.id for v in self.variables]] self.set_index(index) self.time_index = None if time_index: self.set_time_index(time_index, already_sorted=already_sorted) self.set_secondary_time_index(secondary_time_index) def __repr__(self): repr_out = u"Entity: {}\n".format(self.id) repr_out += u" Variables:" for v in self.variables: repr_out += u"\n {} (dtype: {})".format(v.id, v.type_string) shape = self.shape repr_out += u"\n Shape:\n (Rows: {}, Columns: {})".format( shape[0], shape[1]) return repr_out @property def shape(self): '''Shape of the entity's dataframe''' return self.df.shape def __eq__(self, other, deep=False): if self.index != other.index: return False if self.time_index != other.time_index: return False if self.secondary_time_index != other.secondary_time_index: return False if len(self.variables) != len(other.variables): return False if set(self.variables) != set(other.variables): return False if deep: if self.last_time_index is None and other.last_time_index is not None: return False elif self.last_time_index is not None and other.last_time_index is None: return False elif self.last_time_index is not None and other.last_time_index is not None: if not self.last_time_index.equals(other.last_time_index): return False if not _dataframes_equal(self.df, other.df): return False variables = {variable: (variable, ) for variable in self.variables} for variable in other.variables: variables[variable] += (variable, ) for self_var, other_var in variables.values(): if not self_var.__eq__(other_var, deep=True): return False return True def __sizeof__(self): return sum([value.__sizeof__() for value in self.data.values()]) @property def df(self): '''Dataframe providing the data for the entity.''' return self.data["df"] @df.setter def df(self, _df): self.data["df"] = _df @property def last_time_index(self): ''' Time index of the last event for each instance across all child entities. ''' return self.data["last_time_index"] @last_time_index.setter def last_time_index(self, lti): self.data["last_time_index"] = lti def __hash__(self): return id(self.id) def __getitem__(self, variable_id): return self._get_variable(variable_id) def _get_variable(self, variable_id): """Get variable instance Args: variable_id (str) : Id of variable to get. Returns: :class:`.Variable` : Instance of variable. Raises: RuntimeError : if no variable exist with provided id """ for v in self.variables: if v.id == variable_id: return v raise KeyError("Variable: %s not found in entity" % (variable_id)) @property def variable_types(self): '''Dictionary mapping variable id's to variable types''' return {v.id: type(v) for v in self.variables} def convert_variable_type(self, variable_id, new_type, convert_data=True, **kwargs): """Convert variable in dataframe to different type Args: variable_id (str) : Id of variable to convert. new_type (subclass of `Variable`) : Type of variable to convert to. entityset (:class:`.BaseEntitySet`) : EntitySet associated with this entity. convert_data (bool) : If True, convert underlying data in the EntitySet. Raises: RuntimeError : Raises if it cannot convert the underlying data Examples: >>> from featuretools.tests.testing_utils import make_ecommerce_entityset >>> es = make_ecommerce_entityset() >>> es["customers"].convert_variable_type("engagement_level", vtypes.Categorical) """ if convert_data: # first, convert the underlying data (or at least try to) self.df = convert_variable_data(df=self.df, column_id=variable_id, new_type=new_type, **kwargs) # replace the old variable with the new one, maintaining order variable = self._get_variable(variable_id) new_variable = new_type.create_from(variable) self.variables[self.variables.index(variable)] = new_variable def _create_variables(self, variable_types, index, time_index, secondary_time_index): """Extracts the variables from a dataframe Args: variable_types (dict[str -> types/str/dict[str -> type]]) : An entity's variable_types dict maps string variable ids to types (:class:`.Variable`) or type_strings (str) or (type, kwargs) to pass keyword arguments to the Variable. index (str): Name of index column time_index (str or None): Name of time_index column secondary_time_index (dict[str: [str]]): Dictionary of secondary time columns that each map to a list of columns that depend on that secondary time """ variables = [] variable_types = variable_types.copy() or {} string_to_class_map = find_variable_types() # TODO: Remove once Text has been removed from variable types string_to_class_map[Text.type_string] = Text for vid in variable_types.copy(): vtype = variable_types[vid] if isinstance(vtype, str): if vtype in string_to_class_map: variable_types[vid] = string_to_class_map[vtype] else: variable_types[vid] = string_to_class_map['unknown'] warnings.warn("Variable type {} was unrecognized, Unknown variable type was used instead".format(vtype)) if index not in variable_types: variable_types[index] = vtypes.Index link_vars = get_linked_vars(self) inferred_variable_types = infer_variable_types(self.df, link_vars, variable_types, time_index, secondary_time_index) inferred_variable_types.update(variable_types) for v in inferred_variable_types: # TODO document how vtype can be tuple vtype = inferred_variable_types[v] if isinstance(vtype, tuple): # vtype is (ft.Variable, dict_of_kwargs) _v = vtype[0](v, self, **vtype[1]) else: _v = inferred_variable_types[v](v, self) variables += [_v] # convert data once we've inferred self.df = convert_all_variable_data(df=self.df, variable_types=inferred_variable_types) # make sure index is at the beginning index_variable = [v for v in variables if v.id == index][0] self.variables = [index_variable] + [v for v in variables if v.id != index] def update_data(self, df, already_sorted=False, recalculate_last_time_indexes=True): '''Update entity's internal dataframe, optionaly making sure data is sorted, reference indexes to other entities are consistent, and last_time_indexes are consistent. ''' if len(df.columns) != len(self.variables): raise ValueError("Updated dataframe contains {} columns, expecting {}".format(len(df.columns), len(self.variables))) for v in self.variables: if v.id not in df.columns: raise ValueError("Updated dataframe is missing new {} column".format(v.id)) # Make sure column ordering matches variable ordering self.df = df[[v.id for v in self.variables]] self.set_index(self.index) if self.time_index is not None: self.set_time_index(self.time_index, already_sorted=already_sorted) self.set_secondary_time_index(self.secondary_time_index) if recalculate_last_time_indexes and self.last_time_index is not None: self.entityset.add_last_time_indexes(updated_entities=[self.id]) self.entityset.reset_data_description() def add_interesting_values(self, max_values=5, verbose=False): """ Find interesting values for categorical variables, to be used to generate "where" clauses Args: max_values (int) : Maximum number of values per variable to add. verbose (bool) : If True, print summary of interesting values found. Returns: None """ for variable in self.variables: # some heuristics to find basic 'where'-able variables if isinstance(variable, vtypes.Discrete): variable.interesting_values = pd.Series(dtype=variable.entity.df[variable.id].dtype) # TODO - consider removing this constraints # don't add interesting values for entities in relationships skip = False for r in self.entityset.relationships: if variable in [r.child_variable, r.parent_variable]: skip = True break if skip: continue counts = self.df[variable.id].value_counts() # find how many of each unique value there are; sort by count, # and add interesting values to each variable total_count = np.sum(counts) counts[:] = counts.sort_values()[::-1] for i in range(min(max_values, len(counts.index))): idx = counts.index[i] # add the value to interesting_values if it represents more than # 25% of the values we have not seen so far if len(counts.index) < 25: if verbose: msg = "Variable {}: Marking {} as an " msg += "interesting value" logger.info(msg.format(variable.id, idx)) variable.interesting_values = variable.interesting_values.append(pd.Series([idx])) else: fraction = counts[idx] / total_count if fraction > 0.05 and fraction < 0.95: if verbose: msg = "Variable {}: Marking {} as an " msg += "interesting value" logger.info(msg.format(variable.id, idx)) variable.interesting_values = variable.interesting_values.append(pd.Series([idx])) # total_count -= counts[idx] else: break self.entityset.reset_data_description() def delete_variables(self, variable_ids): """ Remove variables from entity's dataframe and from self.variables Args: variable_ids (list[str]): Variables to delete Returns: None """ # check if variable is not a list if not isinstance(variable_ids, list): raise TypeError('variable_ids must be a list of variable names') if len(variable_ids) == 0: return self.df = self.df.drop(variable_ids, axis=1) for v_id in variable_ids: v = self._get_variable(v_id) self.variables.remove(v) def set_time_index(self, variable_id, already_sorted=False): # check time type if not isinstance(self.df, pd.DataFrame) or self.df.empty: time_to_check = vtypes.DEFAULT_DTYPE_VALUES[self[variable_id]._default_pandas_dtype] else: time_to_check = self.df[variable_id].iloc[0] time_type = _check_time_type(time_to_check) if time_type is None: raise TypeError("%s time index not recognized as numeric or" " datetime" % (self.id)) if self.entityset.time_type is None: self.entityset.time_type = time_type elif self.entityset.time_type != time_type: raise TypeError("%s time index is %s type which differs from" " other entityset time indexes" % (self.id, time_type)) if is_instance(self.df, (dd, ks), 'DataFrame'): t = time_type # skip checking values already_sorted = True # skip sorting else: t = vtypes.NumericTimeIndex if col_is_datetime(self.df[variable_id]): t = vtypes.DatetimeTimeIndex # use stable sort if not already_sorted: # sort by time variable, then by index self.df = self.df.sort_values([variable_id, self.index]) self.convert_variable_type(variable_id, t, convert_data=False) self.time_index = variable_id def set_index(self, variable_id, unique=True): """ Args: variable_id (string) : Name of an existing variable to set as index. unique (bool) : Whether to assert that the index is unique. """ if isinstance(self.df, pd.DataFrame): self.df = self.df.set_index(self.df[variable_id], drop=False) self.df.index.name = None if unique: assert self.df.index.is_unique, "Index is not unique on dataframe " \ "(Entity {})".format(self.id) self.convert_variable_type(variable_id, vtypes.Index, convert_data=False) self.index = variable_id def set_secondary_time_index(self, secondary_time_index): for time_index, columns in secondary_time_index.items(): if is_instance(self.df, (dd, ks), 'DataFrame') or self.df.empty: time_to_check = vtypes.DEFAULT_DTYPE_VALUES[self[time_index]._default_pandas_dtype] else: time_to_check = self.df[time_index].head(1).iloc[0] time_type = _check_time_type(time_to_check) if time_type is None: raise TypeError("%s time index not recognized as numeric or" " datetime" % (self.id)) if self.entityset.time_type != time_type: raise TypeError("%s time index is %s type which differs from" " other entityset time indexes" % (self.id, time_type)) if time_index not in columns: columns.append(time_index) self.secondary_time_index = secondary_time_index def _create_index(index, make_index, df): '''Handles index creation logic base on user input''' created_index = None if index is None: # Case 1: user wanted to make index but did not specify column name assert not make_index, "Must specify an index name if make_index is True" # Case 2: make_index not specified but no index supplied, use first column warnings.warn(("Using first column as index. " "To change this, specify the index parameter")) index = df.columns[0] elif make_index and index in df.columns: # Case 3: user wanted to make index but column already exists raise RuntimeError("Cannot make index: index variable already present") elif index not in df.columns: if not make_index: # Case 4: user names index, it is not in df. does not specify # make_index. Make new index column and warn warnings.warn("index {} not found in dataframe, creating new " "integer column".format(index)) # Case 5: make_index with no errors or warnings # (Case 4 also uses this code path) if isinstance(df, dd.DataFrame): df[index] = 1 df[index] = df[index].cumsum() - 1 elif is_instance(df, ks, 'DataFrame'): df = df.koalas.attach_id_column('distributed-sequence', index) else: df.insert(0, index, range(len(df))) created_index = index # Case 6: user specified index, which is already in df. No action needed. return created_index, index, df def _validate_entity_params(id, df, time_index): '''Validation checks for Entity inputs''' assert isinstance(id, str), "Entity id must be a string" assert len(df.columns) == len(set(df.columns)), "Duplicate column names" for c in df.columns: if not isinstance(c, str): raise ValueError("All column names must be strings (Column {} " "is not a string)".format(c)) if time_index is not None and time_index not in df.columns: raise LookupError('Time index not found in dataframe')
[ "logging.getLogger", "pandas.Series", "featuretools.utils.entity_utils.convert_variable_data", "featuretools.utils.gen_utils.is_instance", "numpy.sum", "featuretools.utils.entity_utils.convert_all_variable_data", "featuretools.utils.entity_utils.col_is_datetime", "featuretools.utils.entity_utils.get_linked_vars", "featuretools.variable_types.find_variable_types", "featuretools.utils.wrangle._dataframes_equal", "featuretools.utils.entity_utils.infer_variable_types", "warnings.warn", "featuretools.utils.wrangle._check_time_type", "featuretools.utils.gen_utils.import_or_none" ]
[((539, 574), 'featuretools.utils.gen_utils.import_or_none', 'import_or_none', (['"""databricks.koalas"""'], {}), "('databricks.koalas')\n", (553, 574), False, 'from featuretools.utils.gen_utils import import_or_none, is_instance\n'), ((585, 628), 'logging.getLogger', 'logging.getLogger', (['"""featuretools.entityset"""'], {}), "('featuretools.entityset')\n", (602, 628), False, 'import logging\n'), ((8738, 8759), 'featuretools.variable_types.find_variable_types', 'find_variable_types', ([], {}), '()\n', (8757, 8759), False, 'from featuretools.variable_types import Text, find_variable_types\n'), ((9453, 9474), 'featuretools.utils.entity_utils.get_linked_vars', 'get_linked_vars', (['self'], {}), '(self)\n', (9468, 9474), False, 'from featuretools.utils.entity_utils import col_is_datetime, convert_all_variable_data, convert_variable_data, get_linked_vars, infer_variable_types\n'), ((9509, 9603), 'featuretools.utils.entity_utils.infer_variable_types', 'infer_variable_types', (['self.df', 'link_vars', 'variable_types', 'time_index', 'secondary_time_index'], {}), '(self.df, link_vars, variable_types, time_index,\n secondary_time_index)\n', (9529, 9603), False, 'from featuretools.utils.entity_utils import col_is_datetime, convert_all_variable_data, convert_variable_data, get_linked_vars, infer_variable_types\n'), ((10331, 10408), 'featuretools.utils.entity_utils.convert_all_variable_data', 'convert_all_variable_data', ([], {'df': 'self.df', 'variable_types': 'inferred_variable_types'}), '(df=self.df, variable_types=inferred_variable_types)\n', (10356, 10408), False, 'from featuretools.utils.entity_utils import col_is_datetime, convert_all_variable_data, convert_variable_data, get_linked_vars, infer_variable_types\n'), ((15713, 15744), 'featuretools.utils.wrangle._check_time_type', '_check_time_type', (['time_to_check'], {}), '(time_to_check)\n', (15729, 15744), False, 'from featuretools.utils.wrangle import _check_time_type, _dataframes_equal\n'), ((16247, 16290), 'featuretools.utils.gen_utils.is_instance', 'is_instance', (['self.df', '(dd, ks)', '"""DataFrame"""'], {}), "(self.df, (dd, ks), 'DataFrame')\n", (16258, 16290), False, 'from featuretools.utils.gen_utils import import_or_none, is_instance\n'), ((18919, 19013), 'warnings.warn', 'warnings.warn', (['"""Using first column as index. To change this, specify the index parameter"""'], {}), "(\n 'Using first column as index. To change this, specify the index parameter')\n", (18932, 19013), False, 'import warnings\n'), ((7438, 7527), 'featuretools.utils.entity_utils.convert_variable_data', 'convert_variable_data', ([], {'df': 'self.df', 'column_id': 'variable_id', 'new_type': 'new_type'}), '(df=self.df, column_id=variable_id, new_type=new_type,\n **kwargs)\n', (7459, 7527), False, 'from featuretools.utils.entity_utils import col_is_datetime, convert_all_variable_data, convert_variable_data, get_linked_vars, infer_variable_types\n'), ((16461, 16498), 'featuretools.utils.entity_utils.col_is_datetime', 'col_is_datetime', (['self.df[variable_id]'], {}), '(self.df[variable_id])\n', (16476, 16498), False, 'from featuretools.utils.entity_utils import col_is_datetime, convert_all_variable_data, convert_variable_data, get_linked_vars, infer_variable_types\n'), ((17925, 17956), 'featuretools.utils.wrangle._check_time_type', '_check_time_type', (['time_to_check'], {}), '(time_to_check)\n', (17941, 17956), False, 'from featuretools.utils.wrangle import _check_time_type, _dataframes_equal\n'), ((4631, 4667), 'featuretools.utils.wrangle._dataframes_equal', '_dataframes_equal', (['self.df', 'other.df'], {}), '(self.df, other.df)\n', (4648, 4667), False, 'from featuretools.utils.wrangle import _check_time_type, _dataframes_equal\n'), ((12627, 12681), 'pandas.Series', 'pd.Series', ([], {'dtype': 'variable.entity.df[variable.id].dtype'}), '(dtype=variable.entity.df[variable.id].dtype)\n', (12636, 12681), True, 'import pandas as pd\n'), ((13332, 13346), 'numpy.sum', 'np.sum', (['counts'], {}), '(counts)\n', (13338, 13346), True, 'import numpy as np\n'), ((17653, 17696), 'featuretools.utils.gen_utils.is_instance', 'is_instance', (['self.df', '(dd, ks)', '"""DataFrame"""'], {}), "(self.df, (dd, ks), 'DataFrame')\n", (17664, 17696), False, 'from featuretools.utils.gen_utils import import_or_none, is_instance\n'), ((19815, 19847), 'featuretools.utils.gen_utils.is_instance', 'is_instance', (['df', 'ks', '"""DataFrame"""'], {}), "(df, ks, 'DataFrame')\n", (19826, 19847), False, 'from featuretools.utils.gen_utils import import_or_none, is_instance\n'), ((14026, 14042), 'pandas.Series', 'pd.Series', (['[idx]'], {}), '([idx])\n', (14035, 14042), True, 'import pandas as pd\n'), ((14532, 14548), 'pandas.Series', 'pd.Series', (['[idx]'], {}), '([idx])\n', (14541, 14548), True, 'import pandas as pd\n')]
import numpy as np def get_position_of_minimum(matrix): return np.unravel_index(np.nanargmin(matrix), matrix.shape) def get_position_of_maximum(matrix): return np.unravel_index(np.nanargmax(matrix), matrix.shape) def get_distance_matrix(cell_grid_x, cell_grid_y, x, y): return np.sqrt((x - cell_grid_x) ** 2 + (y - cell_grid_y) ** 2) def get_distance_matrix_squared(cell_grid_x, cell_grid_y, x, y): return (x - cell_grid_x) ** 2 + (y - cell_grid_y) ** 2
[ "numpy.nanargmax", "numpy.nanargmin", "numpy.sqrt" ]
[((295, 351), 'numpy.sqrt', 'np.sqrt', (['((x - cell_grid_x) ** 2 + (y - cell_grid_y) ** 2)'], {}), '((x - cell_grid_x) ** 2 + (y - cell_grid_y) ** 2)\n', (302, 351), True, 'import numpy as np\n'), ((86, 106), 'numpy.nanargmin', 'np.nanargmin', (['matrix'], {}), '(matrix)\n', (98, 106), True, 'import numpy as np\n'), ((189, 209), 'numpy.nanargmax', 'np.nanargmax', (['matrix'], {}), '(matrix)\n', (201, 209), True, 'import numpy as np\n')]
import json import copy import pdb import numpy as np import pickle def listify_mat(matrix): matrix = np.array(matrix).astype(str) if len(matrix.shape) > 1: matrix_list = [] for row in matrix: try: matrix_list.append(list(row)) except: pdb.set_trace() return matrix_list else: return list(matrix) class Recorder(): def __init__(self): self._traj, self._cur_traj = [], [] return def pack_traj(self): self._traj.append(copy.deepcopy(self._cur_traj)) self._cur_traj = [] return def add(self, o, a, r, d): # self._cur_traj.append((o, a, r, d)) self._cur_traj.append( (listify_mat(o), listify_mat(a), listify_mat(r), d)) return def export_pickle(self, filename='traj'): if filename == '': raise ValueError('incorrect file name') traj = [] for t in self._traj: obs = np.array([tt[0] for tt in t]).astype(np.float32) act = np.array([tt[1] for tt in t]).astype(np.float32) rwd = np.array([tt[2] for tt in t]).astype(np.float32) done = np.array([tt[3] for tt in t]) # pdb.set_trace() traj.append({ 'observations': obs[:-1], 'next_observations': obs[1:], 'actions': act[:-1], 'rewards': rwd[:-1], 'terminals': done[:-1] }) with open('{}.pkl'.format(filename), 'wb') as outfile: pickle.dump(traj, outfile) return def export(self, filename='traj'): if filename == '': raise ValueError('incorrect file name') traj = {'traj': []} for t in self._traj: traj['traj'].append(t) # json.dumps(traj, sort_keys=True, indent=4) pdb.set_trace() with open('{}.json'.format(filename), 'w') as outfile: json.dump(traj, outfile) return
[ "pickle.dump", "numpy.array", "pdb.set_trace", "copy.deepcopy", "json.dump" ]
[((1905, 1920), 'pdb.set_trace', 'pdb.set_trace', ([], {}), '()\n', (1918, 1920), False, 'import pdb\n'), ((108, 124), 'numpy.array', 'np.array', (['matrix'], {}), '(matrix)\n', (116, 124), True, 'import numpy as np\n'), ((555, 584), 'copy.deepcopy', 'copy.deepcopy', (['self._cur_traj'], {}), '(self._cur_traj)\n', (568, 584), False, 'import copy\n'), ((1212, 1241), 'numpy.array', 'np.array', (['[tt[3] for tt in t]'], {}), '([tt[3] for tt in t])\n', (1220, 1241), True, 'import numpy as np\n'), ((1590, 1616), 'pickle.dump', 'pickle.dump', (['traj', 'outfile'], {}), '(traj, outfile)\n', (1601, 1616), False, 'import pickle\n'), ((1997, 2021), 'json.dump', 'json.dump', (['traj', 'outfile'], {}), '(traj, outfile)\n', (2006, 2021), False, 'import json\n'), ((318, 333), 'pdb.set_trace', 'pdb.set_trace', ([], {}), '()\n', (331, 333), False, 'import pdb\n'), ((1010, 1039), 'numpy.array', 'np.array', (['[tt[0] for tt in t]'], {}), '([tt[0] for tt in t])\n', (1018, 1039), True, 'import numpy as np\n'), ((1077, 1106), 'numpy.array', 'np.array', (['[tt[1] for tt in t]'], {}), '([tt[1] for tt in t])\n', (1085, 1106), True, 'import numpy as np\n'), ((1144, 1173), 'numpy.array', 'np.array', (['[tt[2] for tt in t]'], {}), '([tt[2] for tt in t])\n', (1152, 1173), True, 'import numpy as np\n')]
import torch from mmdet.datasets.pipelines.transforms import Pad from mmdet.datasets.pipelines.transforms import FilterBox import numpy as np import cv2 def test_pad(): raw = dict( img=np.zeros((200, 401, 3), dtype=np.uint8) ) cv2.imshow('raw', raw['img']) pad = Pad(square=True, pad_val=255) r = pad(raw) print(r['img'].shape) cv2.imshow('draw', r['img']) cv2.waitKey() raw = dict( img=np.zeros((402, 401, 3), dtype=np.uint8) ) cv2.imshow('raw', raw['img']) pad = Pad(square=True, pad_val=255) r = pad(raw) print(r['img'].shape) cv2.imshow('draw', r['img']) cv2.waitKey() def test_filter_box(): bboxes = np.array([[0, 0, 10, 10], [10, 10, 20, 20], [10, 10, 19, 20], [10, 10, 20, 19], [10, 10, 19, 19]]) gt_bboxes = np.array([[0, 0, 10, 9]]) result = dict(gt_bboxes=bboxes) fb = FilterBox((10, 10)) fb(result) if __name__ == '__main__': # test_pad() test_filter_box()
[ "cv2.imshow", "numpy.array", "numpy.zeros", "mmdet.datasets.pipelines.transforms.FilterBox", "mmdet.datasets.pipelines.transforms.Pad", "cv2.waitKey" ]
[((249, 278), 'cv2.imshow', 'cv2.imshow', (['"""raw"""', "raw['img']"], {}), "('raw', raw['img'])\n", (259, 278), False, 'import cv2\n'), ((289, 318), 'mmdet.datasets.pipelines.transforms.Pad', 'Pad', ([], {'square': '(True)', 'pad_val': '(255)'}), '(square=True, pad_val=255)\n', (292, 318), False, 'from mmdet.datasets.pipelines.transforms import Pad\n'), ((367, 395), 'cv2.imshow', 'cv2.imshow', (['"""draw"""', "r['img']"], {}), "('draw', r['img'])\n", (377, 395), False, 'import cv2\n'), ((400, 413), 'cv2.waitKey', 'cv2.waitKey', ([], {}), '()\n', (411, 413), False, 'import cv2\n'), ((493, 522), 'cv2.imshow', 'cv2.imshow', (['"""raw"""', "raw['img']"], {}), "('raw', raw['img'])\n", (503, 522), False, 'import cv2\n'), ((533, 562), 'mmdet.datasets.pipelines.transforms.Pad', 'Pad', ([], {'square': '(True)', 'pad_val': '(255)'}), '(square=True, pad_val=255)\n', (536, 562), False, 'from mmdet.datasets.pipelines.transforms import Pad\n'), ((611, 639), 'cv2.imshow', 'cv2.imshow', (['"""draw"""', "r['img']"], {}), "('draw', r['img'])\n", (621, 639), False, 'import cv2\n'), ((644, 657), 'cv2.waitKey', 'cv2.waitKey', ([], {}), '()\n', (655, 657), False, 'import cv2\n'), ((696, 799), 'numpy.array', 'np.array', (['[[0, 0, 10, 10], [10, 10, 20, 20], [10, 10, 19, 20], [10, 10, 20, 19], [10,\n 10, 19, 19]]'], {}), '([[0, 0, 10, 10], [10, 10, 20, 20], [10, 10, 19, 20], [10, 10, 20, \n 19], [10, 10, 19, 19]])\n', (704, 799), True, 'import numpy as np\n'), ((903, 928), 'numpy.array', 'np.array', (['[[0, 0, 10, 9]]'], {}), '([[0, 0, 10, 9]])\n', (911, 928), True, 'import numpy as np\n'), ((974, 993), 'mmdet.datasets.pipelines.transforms.FilterBox', 'FilterBox', (['(10, 10)'], {}), '((10, 10))\n', (983, 993), False, 'from mmdet.datasets.pipelines.transforms import FilterBox\n'), ((199, 238), 'numpy.zeros', 'np.zeros', (['(200, 401, 3)'], {'dtype': 'np.uint8'}), '((200, 401, 3), dtype=np.uint8)\n', (207, 238), True, 'import numpy as np\n'), ((443, 482), 'numpy.zeros', 'np.zeros', (['(402, 401, 3)'], {'dtype': 'np.uint8'}), '((402, 401, 3), dtype=np.uint8)\n', (451, 482), True, 'import numpy as np\n')]
#coding:utf-8 #0导入模块 ,生成模拟数据集 import tensorflow as tf import numpy as np import matplotlib.pyplot as plt import opt4_8_generateds import opt4_8_forward STEPS = 40000 BATCH_SIZE = 30 LEARNING_RATE_BASE = 0.001 LEARNING_RATE_DECAY = 0.999 REGULARIZER = 0.01 def backward(): x = tf.placeholder(tf.float32, shape=(None, 2)) y_ = tf.placeholder(tf.float32, shape=(None, 1)) X, Y_, Y_c = opt4_8_generateds.generateds() y = opt4_8_forward.forward(x, REGULARIZER) global_step = tf.Variable(0,trainable=False) learning_rate = tf.train.exponential_decay( LEARNING_RATE_BASE, global_step, 300/BATCH_SIZE, LEARNING_RATE_DECAY, staircase=True) #定义损失函数 loss_mse = tf.reduce_mean(tf.square(y-y_)) loss_total = loss_mse + tf.add_n(tf.get_collection('losses')) #定义反向传播方法:包含正则化 train_step = tf.train.AdamOptimizer(learning_rate).minimize(loss_total) with tf.Session() as sess: init_op = tf.global_variables_initializer() sess.run(init_op) for i in range(STEPS): start = (i*BATCH_SIZE) % 300 end = start + BATCH_SIZE sess.run(train_step, feed_dict={x: X[start:end], y_:Y_[start:end]}) if i % 2000 == 0: loss_v = sess.run(loss_total, feed_dict={x:X,y_:Y_}) print("After %d steps, loss is: %f" %(i, loss_v)) xx, yy = np.mgrid[-3:3:.01, -3:3:.01] grid = np.c_[xx.ravel(), yy.ravel()] probs = sess.run(y, feed_dict={x:grid}) probs = probs.reshape(xx.shape) plt.scatter(X[:,0], X[:,1], c=np.squeeze(Y_c)) plt.contour(xx, yy, probs, levels=[.5]) plt.show() if __name__=='__main__': backward()
[ "tensorflow.Variable", "opt4_8_generateds.generateds", "tensorflow.placeholder", "tensorflow.Session", "tensorflow.get_collection", "opt4_8_forward.forward", "numpy.squeeze", "tensorflow.global_variables_initializer", "matplotlib.pyplot.contour", "tensorflow.train.exponential_decay", "tensorflow.train.AdamOptimizer", "tensorflow.square", "matplotlib.pyplot.show" ]
[((280, 323), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '(None, 2)'}), '(tf.float32, shape=(None, 2))\n', (294, 323), True, 'import tensorflow as tf\n'), ((330, 373), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '(None, 1)'}), '(tf.float32, shape=(None, 1))\n', (344, 373), True, 'import tensorflow as tf\n'), ((389, 419), 'opt4_8_generateds.generateds', 'opt4_8_generateds.generateds', ([], {}), '()\n', (417, 419), False, 'import opt4_8_generateds\n'), ((426, 464), 'opt4_8_forward.forward', 'opt4_8_forward.forward', (['x', 'REGULARIZER'], {}), '(x, REGULARIZER)\n', (448, 464), False, 'import opt4_8_forward\n'), ((482, 513), 'tensorflow.Variable', 'tf.Variable', (['(0)'], {'trainable': '(False)'}), '(0, trainable=False)\n', (493, 513), True, 'import tensorflow as tf\n'), ((532, 650), 'tensorflow.train.exponential_decay', 'tf.train.exponential_decay', (['LEARNING_RATE_BASE', 'global_step', '(300 / BATCH_SIZE)', 'LEARNING_RATE_DECAY'], {'staircase': '(True)'}), '(LEARNING_RATE_BASE, global_step, 300 /\n BATCH_SIZE, LEARNING_RATE_DECAY, staircase=True)\n', (558, 650), True, 'import tensorflow as tf\n'), ((1457, 1497), 'matplotlib.pyplot.contour', 'plt.contour', (['xx', 'yy', 'probs'], {'levels': '[0.5]'}), '(xx, yy, probs, levels=[0.5])\n', (1468, 1497), True, 'import matplotlib.pyplot as plt\n'), ((1498, 1508), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1506, 1508), True, 'import matplotlib.pyplot as plt\n'), ((694, 711), 'tensorflow.square', 'tf.square', (['(y - y_)'], {}), '(y - y_)\n', (703, 711), True, 'import tensorflow as tf\n'), ((873, 885), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (883, 885), True, 'import tensorflow as tf\n'), ((907, 940), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (938, 940), True, 'import tensorflow as tf\n'), ((745, 772), 'tensorflow.get_collection', 'tf.get_collection', (['"""losses"""'], {}), "('losses')\n", (762, 772), True, 'import tensorflow as tf\n'), ((807, 844), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', (['learning_rate'], {}), '(learning_rate)\n', (829, 844), True, 'import tensorflow as tf\n'), ((1438, 1453), 'numpy.squeeze', 'np.squeeze', (['Y_c'], {}), '(Y_c)\n', (1448, 1453), True, 'import numpy as np\n')]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import numpy as np def remove_nan(xyzs): return xyzs[~np.isnan(xyzs).any(axis = 1)] def measure_twocores(core_xyz_ref, core_xyz_tar): ''' Measure the following aspects of two helical cores. - Interhelical distance vector between the centers. - Interhelical angle (0-90 degree) ''' # Obtain the centers... center_ref = np.nanmean(core_xyz_ref, axis = 0) center_tar = np.nanmean(core_xyz_tar, axis = 0) # Construct the interhelical distance vector... ih_dvec = center_tar - center_ref # Calculate the length of interhelical distance vector... norm_ih_dvec = np.linalg.norm(ih_dvec) # Obtain the helical core vectors... core_xyz_ref_nonan = remove_nan(core_xyz_ref) core_xyz_tar_nonan = remove_nan(core_xyz_tar) core_vec_ref = core_xyz_ref_nonan[-1] - core_xyz_ref_nonan[0] core_vec_tar = core_xyz_tar_nonan[-1] - core_xyz_tar_nonan[0] # Calculate the interhelical angle... core_vec_ref_unit = core_vec_ref / np.linalg.norm(core_vec_ref) core_vec_tar_unit = core_vec_tar / np.linalg.norm(core_vec_tar) ih_ang = np.arccos( np.dot(core_vec_ref_unit, core_vec_tar_unit) ) return ih_dvec, norm_ih_dvec, core_vec_ref_unit, core_vec_tar_unit, ih_ang def calc_interangle(core_xyz_ref, core_xyz_tar): ''' Measure the following aspects of two helical cores. - Interhelical angle (0-90 degree) ''' # Obtain the helical core vectors... core_xyz_ref_nonan = remove_nan(core_xyz_ref) core_xyz_tar_nonan = remove_nan(core_xyz_tar) core_vec_ref = core_xyz_ref_nonan[-1] - core_xyz_ref_nonan[0] core_vec_tar = core_xyz_tar_nonan[-1] - core_xyz_tar_nonan[0] # Calculate the interhelical angle... core_vec_ref_unit = core_vec_ref / np.linalg.norm(core_vec_ref) core_vec_tar_unit = core_vec_tar / np.linalg.norm(core_vec_tar) inter_angle = np.arccos( np.dot(core_vec_ref_unit, core_vec_tar_unit) ) if inter_angle > np.pi / 2.0: inter_angle = np.pi - inter_angle return inter_angle def calc_interdist(core_xyz_ref, core_xyz_tar): ''' Measure the following aspects of two helical cores. - Interhelical distance vector between the centers. Refers to http://geomalgorithms.com/a07-_distance.html for the method. Q is ref, P is tar. ''' # Obtain the helical core vectors... core_xyz_ref_nonan = remove_nan(core_xyz_ref) core_xyz_tar_nonan = remove_nan(core_xyz_tar) core_vec_ref = core_xyz_ref_nonan[-1] - core_xyz_ref_nonan[0] core_vec_tar = core_xyz_tar_nonan[-1] - core_xyz_tar_nonan[0] # Obtain the starting point... q0 = core_xyz_ref_nonan[0] p0 = core_xyz_tar_nonan[0] w0 = p0 - q0 # Obtain the directional vector with magnitude... v = core_vec_ref u = core_vec_tar # Math part... a = np.dot(u, u) b = np.dot(u, v) c = np.dot(v, v) d = np.dot(u, w0) e = np.dot(v, w0) de = a * c - b * b # Denominator if de == 0: sc, tc = 0, d / b else: sc, tc = (b * e - c * d) / de, (a * e - b * d) / de # Calculate distance... wc = w0 + sc * u - tc * v inter_dist = np.linalg.norm(wc) return inter_dist
[ "numpy.nanmean", "numpy.dot", "numpy.isnan", "numpy.linalg.norm" ]
[((402, 434), 'numpy.nanmean', 'np.nanmean', (['core_xyz_ref'], {'axis': '(0)'}), '(core_xyz_ref, axis=0)\n', (412, 434), True, 'import numpy as np\n'), ((454, 486), 'numpy.nanmean', 'np.nanmean', (['core_xyz_tar'], {'axis': '(0)'}), '(core_xyz_tar, axis=0)\n', (464, 486), True, 'import numpy as np\n'), ((662, 685), 'numpy.linalg.norm', 'np.linalg.norm', (['ih_dvec'], {}), '(ih_dvec)\n', (676, 685), True, 'import numpy as np\n'), ((2874, 2886), 'numpy.dot', 'np.dot', (['u', 'u'], {}), '(u, u)\n', (2880, 2886), True, 'import numpy as np\n'), ((2895, 2907), 'numpy.dot', 'np.dot', (['u', 'v'], {}), '(u, v)\n', (2901, 2907), True, 'import numpy as np\n'), ((2916, 2928), 'numpy.dot', 'np.dot', (['v', 'v'], {}), '(v, v)\n', (2922, 2928), True, 'import numpy as np\n'), ((2937, 2950), 'numpy.dot', 'np.dot', (['u', 'w0'], {}), '(u, w0)\n', (2943, 2950), True, 'import numpy as np\n'), ((2959, 2972), 'numpy.dot', 'np.dot', (['v', 'w0'], {}), '(v, w0)\n', (2965, 2972), True, 'import numpy as np\n'), ((3191, 3209), 'numpy.linalg.norm', 'np.linalg.norm', (['wc'], {}), '(wc)\n', (3205, 3209), True, 'import numpy as np\n'), ((1042, 1070), 'numpy.linalg.norm', 'np.linalg.norm', (['core_vec_ref'], {}), '(core_vec_ref)\n', (1056, 1070), True, 'import numpy as np\n'), ((1110, 1138), 'numpy.linalg.norm', 'np.linalg.norm', (['core_vec_tar'], {}), '(core_vec_tar)\n', (1124, 1138), True, 'import numpy as np\n'), ((1163, 1207), 'numpy.dot', 'np.dot', (['core_vec_ref_unit', 'core_vec_tar_unit'], {}), '(core_vec_ref_unit, core_vec_tar_unit)\n', (1169, 1207), True, 'import numpy as np\n'), ((1807, 1835), 'numpy.linalg.norm', 'np.linalg.norm', (['core_vec_ref'], {}), '(core_vec_ref)\n', (1821, 1835), True, 'import numpy as np\n'), ((1875, 1903), 'numpy.linalg.norm', 'np.linalg.norm', (['core_vec_tar'], {}), '(core_vec_tar)\n', (1889, 1903), True, 'import numpy as np\n'), ((1933, 1977), 'numpy.dot', 'np.dot', (['core_vec_ref_unit', 'core_vec_tar_unit'], {}), '(core_vec_ref_unit, core_vec_tar_unit)\n', (1939, 1977), True, 'import numpy as np\n'), ((104, 118), 'numpy.isnan', 'np.isnan', (['xyzs'], {}), '(xyzs)\n', (112, 118), True, 'import numpy as np\n')]
# https://medium.com/@kumon/how-to-realize-similarity-search-with-elasticsearch-3dd5641b9adb # https://docs.aws.amazon.com/opensearch-service/latest/developerguide/knn.html import sys import requests import h5py import numpy as np import json import aiohttp import asyncio import time import httpx from requests.auth import HTTPBasicAuth from statistics import mean # if len(sys.argv) != 2: # print("Type in the efSearch!") # sys.exit() # path = '/tmp/sift-128-euclidean.hdf5.1M' # float dataset # path = '/tmp/sift-128-euclidean.hdf5' # float dataset path = '/home/ubuntu/sift-128-euclidean.hdf5' # float dataset output_csv = '/tmp/sift-es.csv' # url = 'http://127.0.0.1:9200/sift-index/' host = 'https://vpc-....ap-southeast-1.es.amazonaws.com/' # single node # host = 'https://vpc-....ap-southeast-1.es.amazonaws.com/' # two nodes url = host + 'sift-index/' requestHeaders = {'content-type': 'application/json'} # https://stackoverflow.com/questions/51378099/content-type-header-not-supported auth = HTTPBasicAuth('admin', '<PASSWORD>') # Build an index #https://stackoverflow.com/questions/17301938/making-a-request-to-a-restful-api-using-python # PUT sift-index data = '''{ "settings": { "index": { "knn": true, "knn.space_type": "l2", "knn.algo_param.m": 6, "knn.algo_param.ef_construction": 50, "knn.algo_param.ef_search": 50, "refresh_interval": -1, "translog.flush_threshold_size": "10gb", "number_of_replicas": 0 } }, "mappings": { "properties": { "sift_vector": { "type": "knn_vector", "dimension": 128 } } } }''' # https://medium.com/@kumon/how-to-realize-similarity-search-with-elasticsearch-3dd5641b9adb response = requests.put(url, data=data, headers=requestHeaders, auth=HTTPBasicAuth('admin', 'I#vu7bTAHB')) # response = requests.put(url, data=data, verify=False, headers=requestHeaders, auth=auth) assert response.status_code==requests.codes.ok # cluster_url = 'http://127.0.0.1:9200/_cluster/settings' cluster_url = host + '_cluster/settings' cluster_data = '''{ "persistent" : { "knn.algo_param.index_thread_qty": 16 } } ''' response = requests.put(cluster_url, data=cluster_data, auth=HTTPBasicAuth('admin', 'I#vu7bTAHB'), headers=requestHeaders) assert response.status_code==requests.codes.ok # Bulkload into index bulk_template = '{ "index": { "_index": "sift-index", "_id": "%s" } }\n{ "sift_vector": [%s] }\n' hf = h5py.File(path, 'r') for key in hf.keys(): print("A key of hf is %s" % key) #Names of the groups in HDF5 file. vectors = np.array(hf["train"][:]) num_vectors, dim = vectors.shape print("num_vectors: %d" % num_vectors) print("dim: %d" % dim) bulk_data = "" start = time.time() for (id,vector) in enumerate(vectors): assert len(vector)==dim vector_str = "" for num in vector: vector_str += str(num) + ',' vector_str = vector_str[:-1] id_str = str(id) single_bulk_done = bulk_template % (id_str, vector_str) bulk_data += single_bulk_done if (id+1) % 100000 == 0: print(str(id+1)) # POST _bulk response = requests.put(url + '_bulk', data=bulk_data, auth=HTTPBasicAuth('admin', 'I#<PASSWORD>TAHB'), headers=requestHeaders) assert response.status_code==requests.codes.ok bulk_data = "" end = time.time() print("Insert Time: %d mins" % ((end - start) / 60.0)) # Unit: min # refresh_url = 'http://127.0.0.1:9200/sift-index/_settings' refresh_url = host + 'sift-index/_settings' refresh_data = '''{ "index" : { "refresh_interval": "1s" } } ''' response = requests.put(refresh_url, data=refresh_data, headers=requestHeaders, auth=HTTPBasicAuth('admin', 'I#vu7bTAHB')) assert response.status_code==requests.codes.ok # response = requests.post('http://127.0.0.1:9200/sift-index/_refresh', verify=False, headers=requestHeaders) # assert response.status_code==requests.codes.ok # merge_url = 'http://127.0.0.1:9200/sift-index/_forcemerge?max_num_segments=1' merge_url = host + 'sift-index/_forcemerge?max_num_segments=1' merge_response = requests.post(merge_url, headers=requestHeaders, auth=HTTPBasicAuth('admin', 'I#<PASSWORD>'), timeout=600) assert merge_response.status_code==requests.codes.ok # warmup_url = 'http://127.0.0.1:9200/_opendistro/_knn/warmup/sift-index' warmup_url = host + '_opendistro/_knn/warmup/sift-index' warmup_response = requests.get(warmup_url, headers=requestHeaders, auth=HTTPBasicAuth('admin', 'I<PASSWORD>')) assert warmup_response.status_code==requests.codes.ok # Send queries total_time = 0 # in ms hits = 0 # for recall calculation query_template = ''' { "size": 50, "query": {"knn": {"sift_vector": {"vector": [%s],"k": 50}}} } ''' queries = np.array(hf["test"][:]) nq = len(queries) neighbors = np.array(hf["neighbors"][:]) # distances = np.array(hf["distances"][:]) num_queries, q_dim = queries.shape print("num_queries: %d" % num_queries) print("q_dim: %d" % q_dim) assert q_dim==dim ef_search_list = [50, 100, 150, 200, 250, 300] for ef_search in ef_search_list: ef_data = '''{ "index": { "knn.algo_param.ef_search": %d } }''' ef_data = ef_data % ef_search ### Update Index Setting: efSearch response = requests.put(url + '_settings', data=ef_data, headers=requestHeaders, auth=HTTPBasicAuth('admin', '<PASSWORD>')) assert response.status_code==requests.codes.ok total_time_list = [] hits_list = [] for count in range(5): total_time = 0 # in ms hits = 0 # for recall calculation query_template = ''' ''' single_query = '''{}\n{"size": 50, "query": {"knn": {"sift_vector": {"vector": [%s],"k": 50}}}}\n''' for (id,query) in enumerate(queries): assert len(query)==dim query_str = "" for num in query: query_str += str(num) + ',' query_str = query_str[:-1] # GET sift-index/_search single_query_done = single_query % (query_str) query_template += single_query_done query_data = query_template # print(query_data) response = requests.get(url + '_msearch', data=query_data, headers=requestHeaders, auth=HTTPBasicAuth('admin', '<PASSWORD>'), stream=True) assert response.status_code==requests.codes.ok # print(response.text) result = json.loads(response.text) # QPS total_time = result['took'] # tooks = [] # for i in range(len(queries)): # for ele in result['responses']: # tooks.append(int(ele['took'])) for id in range(len(queries)): # Recall neighbor_id_from_result = [] for ele in result['responses'][id]['hits']['hits']: neighbor_id_from_result.append(int(ele['_id'])) assert len(neighbor_id_from_result)==50 # print("neighbor_id_from_result: ") # print(neighbor_id_from_result) neighbor_id_gt = neighbors[id][0:50] # topK=50 # print("neighbor_id_gt") # print(neighbor_id_gt) hits_q = len(list(set(neighbor_id_from_result) & set(neighbor_id_gt))) # print("# hits of this query with topk=50: %d" % hits_q) hits += hits_q total_time_list.append(total_time) hits_list.append(hits) print(total_time_list) total_time_avg = mean(total_time_list[2:-1]) hits_avg = mean(hits_list) QPS = 1.0 * nq / (total_time_avg / 1000.0) recall = 1.0 * hits_avg / (nq * 50) print(ef_search, QPS, recall)
[ "statistics.mean", "json.loads", "requests.auth.HTTPBasicAuth", "h5py.File", "numpy.array", "time.time" ]
[((1014, 1050), 'requests.auth.HTTPBasicAuth', 'HTTPBasicAuth', (['"""admin"""', '"""<PASSWORD>"""'], {}), "('admin', '<PASSWORD>')\n", (1027, 1050), False, 'from requests.auth import HTTPBasicAuth\n'), ((2465, 2485), 'h5py.File', 'h5py.File', (['path', '"""r"""'], {}), "(path, 'r')\n", (2474, 2485), False, 'import h5py\n'), ((2592, 2616), 'numpy.array', 'np.array', (["hf['train'][:]"], {}), "(hf['train'][:])\n", (2600, 2616), True, 'import numpy as np\n'), ((2737, 2748), 'time.time', 'time.time', ([], {}), '()\n', (2746, 2748), False, 'import time\n'), ((3302, 3313), 'time.time', 'time.time', ([], {}), '()\n', (3311, 3313), False, 'import time\n'), ((4703, 4726), 'numpy.array', 'np.array', (["hf['test'][:]"], {}), "(hf['test'][:])\n", (4711, 4726), True, 'import numpy as np\n'), ((4757, 4785), 'numpy.array', 'np.array', (["hf['neighbors'][:]"], {}), "(hf['neighbors'][:])\n", (4765, 4785), True, 'import numpy as np\n'), ((7146, 7173), 'statistics.mean', 'mean', (['total_time_list[2:-1]'], {}), '(total_time_list[2:-1])\n', (7150, 7173), False, 'from statistics import mean\n'), ((7187, 7202), 'statistics.mean', 'mean', (['hits_list'], {}), '(hits_list)\n', (7191, 7202), False, 'from statistics import mean\n'), ((1801, 1837), 'requests.auth.HTTPBasicAuth', 'HTTPBasicAuth', (['"""admin"""', '"""I#vu7bTAHB"""'], {}), "('admin', 'I#vu7bTAHB')\n", (1814, 1837), False, 'from requests.auth import HTTPBasicAuth\n'), ((2229, 2265), 'requests.auth.HTTPBasicAuth', 'HTTPBasicAuth', (['"""admin"""', '"""I#vu7bTAHB"""'], {}), "('admin', 'I#vu7bTAHB')\n", (2242, 2265), False, 'from requests.auth import HTTPBasicAuth\n'), ((3647, 3683), 'requests.auth.HTTPBasicAuth', 'HTTPBasicAuth', (['"""admin"""', '"""I#vu7bTAHB"""'], {}), "('admin', 'I#vu7bTAHB')\n", (3660, 3683), False, 'from requests.auth import HTTPBasicAuth\n'), ((4107, 4145), 'requests.auth.HTTPBasicAuth', 'HTTPBasicAuth', (['"""admin"""', '"""I#<PASSWORD>"""'], {}), "('admin', 'I#<PASSWORD>')\n", (4120, 4145), False, 'from requests.auth import HTTPBasicAuth\n'), ((4417, 4454), 'requests.auth.HTTPBasicAuth', 'HTTPBasicAuth', (['"""admin"""', '"""I<PASSWORD>"""'], {}), "('admin', 'I<PASSWORD>')\n", (4430, 4454), False, 'from requests.auth import HTTPBasicAuth\n'), ((6226, 6251), 'json.loads', 'json.loads', (['response.text'], {}), '(response.text)\n', (6236, 6251), False, 'import json\n'), ((5270, 5306), 'requests.auth.HTTPBasicAuth', 'HTTPBasicAuth', (['"""admin"""', '"""<PASSWORD>"""'], {}), "('admin', '<PASSWORD>')\n", (5283, 5306), False, 'from requests.auth import HTTPBasicAuth\n'), ((3157, 3199), 'requests.auth.HTTPBasicAuth', 'HTTPBasicAuth', (['"""admin"""', '"""I#<PASSWORD>TAHB"""'], {}), "('admin', 'I#<PASSWORD>TAHB')\n", (3170, 3199), False, 'from requests.auth import HTTPBasicAuth\n'), ((6084, 6120), 'requests.auth.HTTPBasicAuth', 'HTTPBasicAuth', (['"""admin"""', '"""<PASSWORD>"""'], {}), "('admin', '<PASSWORD>')\n", (6097, 6120), False, 'from requests.auth import HTTPBasicAuth\n')]
import numpy as np from ctypes import c_void_p from .Shader import Shader from .transforms import * from OpenGL.GL import * class Path: # position=[x1, y1, z1, ..., xn, yn, zn] ; rotation = [[Rx1, Ry1, Rz1], ..., [Rxn, Ryn, Rzn]] def __init__(self, position, rotation=None): self.loadPath(position) if rotation: assert len(position) == len(rotation) * 3 self.loadRotation(rotation) else: self.rotation = 'Pio è un figo' def loadPath(self, position): # compiling shader self.path_shader = Shader('src\\shaders\\path\\pathvert.glsl', 'src\\shaders\\path\\pathfrag.glsl').shaderProgram # setting path buffer self.vertices = position self.patharray = glGenVertexArrays(1) glBindVertexArray(self.patharray) self.lineBuffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self.lineBuffer) glBufferData(GL_ARRAY_BUFFER, np.array(self.vertices, dtype='float32'), GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * 4, c_void_p(0)) def loadRotation(self, rotation): self.rotation = rotation # compiling shader self.xpath_shader = Shader('src\\shaders\\path\\pathvert.glsl', 'src\\shaders\\path\\xpathfrag.glsl').shaderProgram self.ypath_shader = Shader('src\\shaders\\path\\pathvert.glsl', 'src\\shaders\\path\\ypathfrag.glsl').shaderProgram self.zpath_shader = Shader('src\\shaders\\path\\pathvert.glsl', 'src\\shaders\\path\\zpathfrag.glsl').shaderProgram # setting versors self.xvertices = [] self.yvertices = [] self.zvertices = [] for pos in range(len(rotation)): xversor = self.getVersorAtTime(np.array([1, 0, 0, 1], dtype='float32'), pos) yversor = self.getVersorAtTime(np.array([0, 1, 0, 1], dtype='float32'), pos) zversor = self.getVersorAtTime(np.array([0, 0, 1, 1], dtype='float32'), pos) pos = [self.vertices[pos*3], self.vertices[pos*3 + 1], self.vertices[pos*3 + 2]] self.xvertices.extend(pos) self.xvertices.extend([xversor[0], xversor[1], xversor[2]]) self.yvertices.extend(pos) self.yvertices.extend([yversor[0], yversor[1], yversor[2]]) self.zvertices.extend(pos) self.zvertices.extend([zversor[0], zversor[1], zversor[2]]) #setting xline bufer self.xpatharray = glGenVertexArrays(1) glBindVertexArray(self.xpatharray) self.xlineBuffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self.xlineBuffer) glBufferData(GL_ARRAY_BUFFER, np.array(self.xvertices, dtype='float32'), GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * 4, c_void_p(0)) # setting yline buffer self.ypatharray = glGenVertexArrays(1) glBindVertexArray(self.ypatharray) self.ylineBuffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self.ylineBuffer) glBufferData(GL_ARRAY_BUFFER, np.array(self.yvertices, dtype='float32'), GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * 4, c_void_p(0)) #setting xline bufer self.zpatharray = glGenVertexArrays(1) glBindVertexArray(self.zpatharray) self.zlineBuffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self.zlineBuffer) glBufferData(GL_ARRAY_BUFFER, np.array(self.zvertices, dtype='float32'), GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * 4, c_void_p(0)) def getVersorAtTime(self, versor, index): r_versor = np.dot(get_rot(self.rotation[index][0], 0), versor) r_versor = np.dot(get_rot(self.rotation[index][1], 1), r_versor) r_versor = np.dot(get_rot(self.rotation[index][2], 2), r_versor) t_versor = np.dot(get_traslation(self.vertices[index*3], self.vertices[index*3 + 1], self.vertices[index*3 + 2]), r_versor) return t_versor def renderPath(self, camera): model = np.identity(4) view = camera.view proj = camera.proj # rendering the path glBindVertexArray(self.patharray) glUseProgram(self.path_shader) modelLocation = glGetUniformLocation(self.path_shader, 'model') viewLocation = glGetUniformLocation(self.path_shader, 'view') projectionLocation = glGetUniformLocation(self.path_shader, 'projection') glUniformMatrix4fv(modelLocation, 1, GL_TRUE, model) glUniformMatrix4fv(viewLocation, 1, GL_TRUE, view) glUniformMatrix4fv(projectionLocation, 1, GL_FALSE, proj) glEnableVertexAttribArray(0) glDrawArrays(GL_LINE_STRIP, 0, int(len(self.vertices)/3)) glDisableVertexAttribArray(0) # rendering the xlines if self.rotation != 'Pio è un figo': glBindVertexArray(self.xpatharray) glUseProgram(self.xpath_shader) modelLocation = glGetUniformLocation(self.xpath_shader, 'model') viewLocation = glGetUniformLocation(self.xpath_shader, 'view') projectionLocation = glGetUniformLocation(self.xpath_shader, 'projection') glUniformMatrix4fv(modelLocation, 1, GL_TRUE, model) glUniformMatrix4fv(viewLocation, 1, GL_TRUE, view) glUniformMatrix4fv(projectionLocation, 1, GL_FALSE, proj) glEnableVertexAttribArray(0) glDrawArrays(GL_LINES, 0, int(len(self.xvertices)/3)) glDisableVertexAttribArray(0) # rendering the ylines glBindVertexArray(self.ypatharray) glUseProgram(self.ypath_shader) modelLocation = glGetUniformLocation(self.ypath_shader, 'model') viewLocation = glGetUniformLocation(self.ypath_shader, 'view') projectionLocation = glGetUniformLocation(self.ypath_shader, 'projection') glUniformMatrix4fv(modelLocation, 1, GL_TRUE, model) glUniformMatrix4fv(viewLocation, 1, GL_TRUE, view) glUniformMatrix4fv(projectionLocation, 1, GL_FALSE, proj) glEnableVertexAttribArray(0) glDrawArrays(GL_LINES, 0, int(len(self.xvertices)/3)) glDisableVertexAttribArray(0) # rendering the zlines glBindVertexArray(self.zpatharray) glUseProgram(self.zpath_shader) modelLocation = glGetUniformLocation(self.zpath_shader, 'model') viewLocation = glGetUniformLocation(self.zpath_shader, 'view') projectionLocation = glGetUniformLocation(self.zpath_shader, 'projection') glUniformMatrix4fv(modelLocation, 1, GL_TRUE, model) glUniformMatrix4fv(viewLocation, 1, GL_TRUE, view) glUniformMatrix4fv(projectionLocation, 1, GL_FALSE, proj) glEnableVertexAttribArray(0) glDrawArrays(GL_LINES, 0, int(len(self.xvertices)/3)) glDisableVertexAttribArray(0)
[ "numpy.identity", "numpy.array", "ctypes.c_void_p" ]
[((4234, 4248), 'numpy.identity', 'np.identity', (['(4)'], {}), '(4)\n', (4245, 4248), True, 'import numpy as np\n'), ((1016, 1056), 'numpy.array', 'np.array', (['self.vertices'], {'dtype': '"""float32"""'}), "(self.vertices, dtype='float32')\n", (1024, 1056), True, 'import numpy as np\n'), ((1137, 1148), 'ctypes.c_void_p', 'c_void_p', (['(0)'], {}), '(0)\n', (1145, 1148), False, 'from ctypes import c_void_p\n'), ((2842, 2883), 'numpy.array', 'np.array', (['self.xvertices'], {'dtype': '"""float32"""'}), "(self.xvertices, dtype='float32')\n", (2850, 2883), True, 'import numpy as np\n'), ((2964, 2975), 'ctypes.c_void_p', 'c_void_p', (['(0)'], {}), '(0)\n', (2972, 2975), False, 'from ctypes import c_void_p\n'), ((3236, 3277), 'numpy.array', 'np.array', (['self.yvertices'], {'dtype': '"""float32"""'}), "(self.yvertices, dtype='float32')\n", (3244, 3277), True, 'import numpy as np\n'), ((3358, 3369), 'ctypes.c_void_p', 'c_void_p', (['(0)'], {}), '(0)\n', (3366, 3369), False, 'from ctypes import c_void_p\n'), ((3628, 3669), 'numpy.array', 'np.array', (['self.zvertices'], {'dtype': '"""float32"""'}), "(self.zvertices, dtype='float32')\n", (3636, 3669), True, 'import numpy as np\n'), ((3750, 3761), 'ctypes.c_void_p', 'c_void_p', (['(0)'], {}), '(0)\n', (3758, 3761), False, 'from ctypes import c_void_p\n'), ((1922, 1961), 'numpy.array', 'np.array', (['[1, 0, 0, 1]'], {'dtype': '"""float32"""'}), "([1, 0, 0, 1], dtype='float32')\n", (1930, 1961), True, 'import numpy as np\n'), ((2011, 2050), 'numpy.array', 'np.array', (['[0, 1, 0, 1]'], {'dtype': '"""float32"""'}), "([0, 1, 0, 1], dtype='float32')\n", (2019, 2050), True, 'import numpy as np\n'), ((2100, 2139), 'numpy.array', 'np.array', (['[0, 0, 1, 1]'], {'dtype': '"""float32"""'}), "([0, 0, 1, 1], dtype='float32')\n", (2108, 2139), True, 'import numpy as np\n')]
# standard library imports import os # third party imports import numpy as np from PIL import Image import torch.nn as nn from torchvision import transforms # local imports import config from . import utils from . import geometric_transformer class GeoTransformationInfer(nn.Module): def __init__(self, output_dir="./output/results"): super(GeoTransformationInfer, self).__init__() self.output_dir = output_dir utils.ensure_folder(self.output_dir) def forward(self, model_apparel, warped_image, model_image, warped_model_image, random_product_image, random_product_image_warped, output_on_random_product, batch_index, epoch): batch_size = warped_image.shape[0] model_apparel = model_apparel.cpu().numpy() warped_image = warped_image.cpu().numpy() model_image = model_image.cpu().numpy() warped_model_image = warped_model_image.cpu().numpy() random_product_image = random_product_image.cpu().numpy() random_product_image_warped = random_product_image_warped.cpu().numpy() output_on_random_product = output_on_random_product.cpu().numpy() for i in range(batch_size): self._save_image_sheet( batch_index*config.PARAMS["batch_size"] + i, model_apparel[i], warped_image[i], model_image[i], warped_model_image[i], random_product_image[i], random_product_image_warped[i], output_on_random_product[i], epoch) def _save_image_sheet(self, idx, model_apparel, warped_image, model_image, warped_model_image, random_product_image, random_product_image_warped, output_on_random_product, epoch): # inverse normalization of the images along with channel first to channel last steps and finally converting np array to pillow format for saving model_apparel = np.moveaxis(model_apparel, 0, 2) * [0.229, 0.224, 0.225] + [0.485, 0.456, 0.406] model_apparel = Image.fromarray(np.uint8(model_apparel * 255)) warped_image = np.moveaxis(warped_image, 0, 2) * [0.229, 0.224, 0.225] + [0.485, 0.456, 0.406] warped_image = Image.fromarray(np.uint8(warped_image * 255)) model_image = np.moveaxis(model_image, 0, 2) * [0.229, 0.224, 0.225] + [0.485, 0.456, 0.406] model_image = Image.fromarray(np.uint8(model_image * 255)) warped_model_image = np.moveaxis(warped_model_image, 0, 2) * [0.229, 0.224, 0.225] + [0.485, 0.456, 0.406] warped_model_image = Image.fromarray(np.uint8(warped_model_image * 255)) random_product_image = np.moveaxis(random_product_image, 0, 2) * [0.229, 0.224, 0.225] + [0.485, 0.456, 0.406] random_product_image = Image.fromarray(np.uint8(random_product_image * 255)) random_product_image_warped = np.moveaxis(random_product_image_warped, 0, 2) * [0.229, 0.224, 0.225] + (0.485, 0.456, 0.406) random_product_image_warped = Image.fromarray(np.uint8(random_product_image_warped * 255)) output_on_random_product = np.moveaxis(output_on_random_product, 0, 2) * [0.229, 0.224, 0.225] + [0.485, 0.456, 0.406] output_on_random_product = Image.fromarray(np.uint8(output_on_random_product * 255)) sheet = Image.new('RGB', (1568, 224), 'white') sheet.paste(model_apparel, (0, 0)) sheet.paste(warped_image, (224, 0)) sheet.paste(model_image, (448, 0)) sheet.paste(warped_model_image, (672, 0)) sheet.paste(random_product_image, (896, 0)) sheet.paste(random_product_image_warped, (1120, 0)) sheet.paste(output_on_random_product, (1344, 0)) sheet.save(os.path.join(self.output_dir, "image_sheet_{}-epoch{}".format(idx, str(epoch).zfill(3)) + ".jpg"))
[ "numpy.uint8", "PIL.Image.new", "numpy.moveaxis" ]
[((3034, 3072), 'PIL.Image.new', 'Image.new', (['"""RGB"""', '(1568, 224)', '"""white"""'], {}), "('RGB', (1568, 224), 'white')\n", (3043, 3072), False, 'from PIL import Image\n'), ((1872, 1901), 'numpy.uint8', 'np.uint8', (['(model_apparel * 255)'], {}), '(model_apparel * 255)\n', (1880, 1901), True, 'import numpy as np\n'), ((2033, 2061), 'numpy.uint8', 'np.uint8', (['(warped_image * 255)'], {}), '(warped_image * 255)\n', (2041, 2061), True, 'import numpy as np\n'), ((2190, 2217), 'numpy.uint8', 'np.uint8', (['(model_image * 255)'], {}), '(model_image * 255)\n', (2198, 2217), True, 'import numpy as np\n'), ((2367, 2401), 'numpy.uint8', 'np.uint8', (['(warped_model_image * 255)'], {}), '(warped_model_image * 255)\n', (2375, 2401), True, 'import numpy as np\n'), ((2557, 2593), 'numpy.uint8', 'np.uint8', (['(random_product_image * 255)'], {}), '(random_product_image * 255)\n', (2565, 2593), True, 'import numpy as np\n'), ((2770, 2813), 'numpy.uint8', 'np.uint8', (['(random_product_image_warped * 255)'], {}), '(random_product_image_warped * 255)\n', (2778, 2813), True, 'import numpy as np\n'), ((2981, 3021), 'numpy.uint8', 'np.uint8', (['(output_on_random_product * 255)'], {}), '(output_on_random_product * 255)\n', (2989, 3021), True, 'import numpy as np\n'), ((1757, 1789), 'numpy.moveaxis', 'np.moveaxis', (['model_apparel', '(0)', '(2)'], {}), '(model_apparel, 0, 2)\n', (1768, 1789), True, 'import numpy as np\n'), ((1920, 1951), 'numpy.moveaxis', 'np.moveaxis', (['warped_image', '(0)', '(2)'], {}), '(warped_image, 0, 2)\n', (1931, 1951), True, 'import numpy as np\n'), ((2079, 2109), 'numpy.moveaxis', 'np.moveaxis', (['model_image', '(0)', '(2)'], {}), '(model_image, 0, 2)\n', (2090, 2109), True, 'import numpy as np\n'), ((2242, 2279), 'numpy.moveaxis', 'np.moveaxis', (['warped_model_image', '(0)', '(2)'], {}), '(warped_model_image, 0, 2)\n', (2253, 2279), True, 'import numpy as np\n'), ((2428, 2467), 'numpy.moveaxis', 'np.moveaxis', (['random_product_image', '(0)', '(2)'], {}), '(random_product_image, 0, 2)\n', (2439, 2467), True, 'import numpy as np\n'), ((2627, 2673), 'numpy.moveaxis', 'np.moveaxis', (['random_product_image_warped', '(0)', '(2)'], {}), '(random_product_image_warped, 0, 2)\n', (2638, 2673), True, 'import numpy as np\n'), ((2844, 2887), 'numpy.moveaxis', 'np.moveaxis', (['output_on_random_product', '(0)', '(2)'], {}), '(output_on_random_product, 0, 2)\n', (2855, 2887), True, 'import numpy as np\n')]
from pathlib import Path import h5py import numpy as np from torchvision.datasets.vision import VisionDataset from PIL import Image import requests import zipfile from tqdm import tqdm def download_file_from_google_drive(id, destination): URL = "https://docs.google.com/uc?export=download" session = requests.Session() response = session.get(URL, params = { 'id' : id }, stream = True) token = get_confirm_token(response) if token: params = { 'id' : id, 'confirm' : token } response = session.get(URL, params = params, stream = True) save_response_content(response, destination) def get_confirm_token(response): for key, value in response.cookies.items(): if key.startswith('download_warning'): return value return None def save_response_content(response, destination): CHUNK_SIZE = 32768 with open(destination, "wb") as f: for chunk in tqdm(response.iter_content(CHUNK_SIZE)): if chunk: # filter out keep-alive new chunks f.write(chunk) class Fonts(VisionDataset): url_id = '0B0GtwTQ6IF9AU3NOdzFzUWZ0aDQ' base_folder = 'fonts' def __init__(self, root, split='train', transform=None, target_transform=None, download=True, denoise=False, denoise_transform=None, num_fonts_pi=None, num_examples=2500): ''' Args: root (str): path num_train_domains (int): number of train domains up to 41443 test_mean_chars (bool): Use the mean characters as test set split (str): 'train', 'val', 'test' transform: input transformation target_transform: target transformation download (bool): download or not ''' super().__init__(root, transform=transform, target_transform=target_transform) self.split = split self.transform = transform self.target_transform = target_transform self.denoise = denoise self.denoise_transform = denoise_transform self.path = Path(self.root) / self.base_folder self.path.mkdir(parents=True, exist_ok=True) self.download_path = self.path / 'fonts.hdf5' if download: self.download() with h5py.File(str(self.download_path), 'r') as f: data_by_domain = f['fonts'][()] np.random.seed(484347) # limit the number of fonts num_fonts = 100 font_idxs = np.arange(len(data_by_domain)) np.random.shuffle(font_idxs) if not denoise: data_by_domain = data_by_domain[font_idxs[:num_fonts]] print(f"NUM FONTS: {num_fonts}") print(f"NUM CHARS: {data_by_domain.shape[1]}") num_classes = data_by_domain.shape[1] self.all_targets = np.concatenate( [np.arange(num_classes)]*num_fonts, axis=0) self.all_domain_labels = np.repeat(np.arange(num_fonts), num_classes) self.all_data = data_by_domain.reshape(data_by_domain.shape[0]*data_by_domain.shape[1], data_by_domain.shape[2], data_by_domain.shape[3]) idxs = np.arange(len(self.all_data)) np.random.shuffle(idxs) train_val_max = 2600 if num_examples > train_val_max: # to be able to heuristically test what happens if we have more training data train_val_max = 5000 if split == 'train': idxs = idxs[:num_examples] elif split == 'val': idxs = idxs[num_examples: train_val_max] else: idxs = idxs[train_val_max:] self.targets = self.all_targets[idxs] self.domain_labels = self.all_domain_labels[idxs] self.data = self.all_data[idxs] else: # get the train data train_dbd = data_by_domain[font_idxs[:num_fonts]] all_data = train_dbd.reshape(train_dbd.shape[0]*train_dbd.shape[1], train_dbd.shape[2], train_dbd.shape[3]) idxs = np.arange(len(all_data)) np.random.shuffle(idxs) idxs = idxs[:num_examples] train_data = all_data[idxs] if num_fonts_pi is not None: data_by_domain = data_by_domain[font_idxs[num_fonts:num_fonts+num_fonts_pi]] else: data_by_domain = data_by_domain[font_idxs[num_fonts:]] self.data = data_by_domain.reshape(data_by_domain.shape[0]*data_by_domain.shape[1], data_by_domain.shape[2], data_by_domain.shape[3]) self.data = np.concatenate([train_data, self.data], axis=0) def get_nearest_neighbor(self, all_imgs, x): idx = np.argmin(np.sum(np.square(all_imgs - x), axis=(1,2))) return self[idx] def download(self): if not self.download_path.exists(): download_file_from_google_drive(self.url_id, str(self.download_path)) def __getitem__(self, index): """ Args: index (int): Index Returns: tuple: (image, target) where target is index of the target class. """ if self.denoise: img = self.data[index] img = Image.fromarray(img) if self.transform is not None: tgt_img = self.transform(img) if self.denoise_transform is not None: src_img = self.denoise_transform(img) return src_img, tgt_img else: img, target = self.data[index], self.targets[index] domain_label = self.domain_labels[index] # doing this so that it is consistent with all other datasets # to return a PIL Image img = Image.fromarray(img) if self.transform is not None: img = self.transform(img) if self.target_transform is not None: target = self.target_transform(target) return img, target, domain_label def get_item_from_all(self, index): img, target = self.all_data[index], self.all_targets[index] domain_label = self.all_domain_labels[index] # doing this so that it is consistent with all other datasets # to return a PIL Image img = Image.fromarray(img) if self.transform is not None: img = self.transform(img) if self.target_transform is not None: target = self.target_transform(target) return img, target, domain_label def __len__(self): return len(self.data)
[ "PIL.Image.fromarray", "requests.Session", "pathlib.Path", "numpy.square", "numpy.random.seed", "numpy.concatenate", "numpy.arange", "numpy.random.shuffle" ]
[((312, 330), 'requests.Session', 'requests.Session', ([], {}), '()\n', (328, 330), False, 'import requests\n'), ((2396, 2418), 'numpy.random.seed', 'np.random.seed', (['(484347)'], {}), '(484347)\n', (2410, 2418), True, 'import numpy as np\n'), ((2538, 2566), 'numpy.random.shuffle', 'np.random.shuffle', (['font_idxs'], {}), '(font_idxs)\n', (2555, 2566), True, 'import numpy as np\n'), ((6284, 6304), 'PIL.Image.fromarray', 'Image.fromarray', (['img'], {}), '(img)\n', (6299, 6304), False, 'from PIL import Image\n'), ((2091, 2106), 'pathlib.Path', 'Path', (['self.root'], {}), '(self.root)\n', (2095, 2106), False, 'from pathlib import Path\n'), ((3215, 3238), 'numpy.random.shuffle', 'np.random.shuffle', (['idxs'], {}), '(idxs)\n', (3232, 3238), True, 'import numpy as np\n'), ((4117, 4140), 'numpy.random.shuffle', 'np.random.shuffle', (['idxs'], {}), '(idxs)\n', (4134, 4140), True, 'import numpy as np\n'), ((4614, 4661), 'numpy.concatenate', 'np.concatenate', (['[train_data, self.data]'], {'axis': '(0)'}), '([train_data, self.data], axis=0)\n', (4628, 4661), True, 'import numpy as np\n'), ((5235, 5255), 'PIL.Image.fromarray', 'Image.fromarray', (['img'], {}), '(img)\n', (5250, 5255), False, 'from PIL import Image\n'), ((5746, 5766), 'PIL.Image.fromarray', 'Image.fromarray', (['img'], {}), '(img)\n', (5761, 5766), False, 'from PIL import Image\n'), ((2968, 2988), 'numpy.arange', 'np.arange', (['num_fonts'], {}), '(num_fonts)\n', (2977, 2988), True, 'import numpy as np\n'), ((4743, 4766), 'numpy.square', 'np.square', (['(all_imgs - x)'], {}), '(all_imgs - x)\n', (4752, 4766), True, 'import numpy as np\n'), ((2878, 2900), 'numpy.arange', 'np.arange', (['num_classes'], {}), '(num_classes)\n', (2887, 2900), True, 'import numpy as np\n')]
# Copyright (c) 2020-2022, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys import argparse import re import numpy as np import torch ACTIVATION_AMAX_NUM = 72 INT8O_KERNEL_NUM = 5 INT8O_GEMM_NUM = 7 TRT_FUSED_MHA_AMAX_NUM = 3 SCALE_RESERVE_NUM = 8 def extract_amaxlist(init_dict, depths, ths_path='../lib/libpyt_swintransformer.so', verbose=True): # print("Quantizing checkpoint ...") torch.classes.load_library(ths_path) weight_quantize = torch.ops.fastertransformer.swin_weight_quantize layer_num = len(depths) amaxTotalNum = ACTIVATION_AMAX_NUM + INT8O_KERNEL_NUM + INT8O_GEMM_NUM + 1 + TRT_FUSED_MHA_AMAX_NUM + SCALE_RESERVE_NUM kernel_name_list = ["attn.qkv", "attn.proj", "mlp.fc1", "mlp.fc2"] amax_name_list = ["attn.qkv._input_quantizer", "attn.qkv._aftergemm_quantizer", "attn.proj._input_quantizer", "attn.proj._aftergemm_quantizer", "attn.matmul_q_input_quantizer", "attn.matmul_k_input_quantizer", "attn.matmul_v_input_quantizer", "attn.matmul_a_input_quantizer", "attn.softmax_input_quantizer", "mlp.fc1._input_quantizer", "mlp.fc1._aftergemm_quantizer", "mlp.fc2._input_quantizer", "mlp.fc2._aftergemm_quantizer", "add1_residual_input_quantizer", "add2_residual_input_quantizer" ] int8O_gemm_weight_amax_list = [0 for i in range(INT8O_GEMM_NUM)] int8O_gemm_weight_list = ["attn.qkv", "attn.proj", "mlp.fc1", "mlp.fc2", "attn.matmul_k_input_quantizer", "attn.matmul_v_input_quantizer"] int8O_gemm_input_amax_list = [0 for i in range(INT8O_GEMM_NUM)] int8O_gemm_input_list = ["attn.qkv._input_quantizer", "attn.proj._input_quantizer", "mlp.fc1._input_quantizer", "mlp.fc2._input_quantizer", "attn.matmul_q_input_quantizer", "attn.matmul_a_input_quantizer"] int8O_gemm_output_amax_list = [0 for i in range(INT8O_GEMM_NUM)] int8O_gemm_output_list = ["attn.qkv._aftergemm_quantizer", "attn.proj._aftergemm_quantizer", "mlp.fc1._aftergemm_quantizer", "mlp.fc2._aftergemm_quantizer", "attn.softmax_input_quantizer", "attn.proj._input_quantizer"] downsample_input = "downsample.reduction._input_quantizer" downsample_weight = "downsample.reduction._weight_quantizer" downsample_out = "downsample.reduction._aftergemm_quantizer" factor = 1000000.0 for i in range(layer_num): for depth in range(depths[i]): amaxList = np.zeros([amaxTotalNum]).astype(np.float32) amax_id = 0 for amax_name in amax_name_list: quant_max = init_dict["layers.{}.blocks.{}.{}._amax".format(i, depth, amax_name)].item() amax = abs(quant_max)#round(abs(quant_max)*factor)/factor if amax_name in int8O_gemm_input_list: int8O_gemm_input_amax_list[int8O_gemm_input_list.index(amax_name)] = amax if amax_name in int8O_gemm_output_list: int8O_gemm_output_amax_list[int8O_gemm_output_list.index(amax_name)] = amax if amax_name in int8O_gemm_weight_list: int8O_gemm_weight_amax_list[int8O_gemm_weight_list.index(amax_name)] = amax amaxList[amax_id] = amax amax_id += 1 amaxList[amax_id] = amax/127.0 amax_id += 1 amaxList[amax_id] = amax/127.0/127.0 amax_id += 1 amaxList[amax_id] = 127.0/amax amax_id += 1 # if verbose: # print(i, amax_name) # print('quant_max:', quant_max) # print('amax:', amax) if i != layer_num - 1: amax = init_dict["layers.{}.{}._amax".format(i, downsample_input)].item() amaxList[amax_id] = amax amax_id += 1 amaxList[amax_id] = amax/127.0 amax_id += 1 amaxList[amax_id] = amax/127.0/127.0 amax_id += 1 amaxList[amax_id] = 127.0/amax amax_id += 1 amax = init_dict["layers.{}.{}._amax".format(i, downsample_out)].item() amaxList[amax_id] = amax amax_id += 1 amaxList[amax_id] = amax/127.0 amax_id += 1 amaxList[amax_id] = amax/127.0/127.0 amax_id += 1 amaxList[amax_id] = 127.0/amax amax_id += 1 else: amax_id += 8 if verbose: print("done process layer_{} block_{} activation amax".format(i, depth)) #kernel amax starts from ACTIVATION_AMAX_NUM assert amax_id == 68 amax_id = ACTIVATION_AMAX_NUM for kernel_id, kernel_name in enumerate(kernel_name_list): kernel = init_dict["layers.{}.blocks.{}.{}.weight".format(i, depth, kernel_name)].transpose(-1, -2).contiguous() quant_max2 = init_dict["layers.{}.blocks.{}.{}._weight_quantizer._amax".format(i, depth, kernel_name)] amax2 = abs(quant_max2) # if (amax2.dim() == 0): # quant_max_processed = torch.full((kernel.size(1),), amax2.item(), dtype=amax2.dtype, device=amax2.device) # else: # quant_max_processed = amax2.view(-1) kernel_processed = weight_quantize(kernel, amax2.cuda()) init_dict["layers.{}.blocks.{}.{}.weight".format(i, depth, kernel_name)] = kernel_processed if kernel_name in int8O_gemm_weight_list: int8O_gemm_weight_amax_list[int8O_gemm_weight_list.index(kernel_name)] = amax2.item() amaxList[amax_id] = amax2 amax_id += 1 # if verbose: # print(i, kernel_name) # print('kernel:', kernel) # print('quant_max2:', quant_max2) # print('quant_max_processed_:', quant_max_processed) if i != layer_num - 1: amaxList[amax_id] = init_dict["layers.{}.downsample.reduction._weight_quantizer._amax".format(i)].item() amax_id += 1 assert amax_id == ACTIVATION_AMAX_NUM + INT8O_KERNEL_NUM #for int8O gemm deQuant for j in range(INT8O_GEMM_NUM - 1): amaxList[amax_id] = (int8O_gemm_input_amax_list[j]*int8O_gemm_weight_amax_list[j])/(127.0*int8O_gemm_output_amax_list[j]) # print('layernum:', i, 'j:', j, ' gemm_int8IO_scale:',amaxList[amax_id]) # print(int8O_gemm_input_amax_list[j], int8O_gemm_weight_amax_list[j], int8O_gemm_output_amax_list[j]) amax_id += 1 if i != layer_num - 1: patchMerge_i = init_dict["layers.{}.{}._amax".format(i, downsample_input)].item() patchMerge_w = init_dict["layers.{}.{}._amax".format(i, downsample_weight)].item() patchMerge_o = init_dict["layers.{}.{}._amax".format(i, downsample_out)].item() amaxList[amax_id] = (patchMerge_i * patchMerge_w) / (127 * patchMerge_o) amax_id += 1 assert amax_id == ACTIVATION_AMAX_NUM + INT8O_KERNEL_NUM + INT8O_GEMM_NUM amax_id += 1 #for trt fused MHA amax #### QKV_addBias_amax # amaxList[amax_id] = np.maximum(np.maximum(amaxList[16],amaxList[20]), amaxList[24]) # amax_id += 1 # #### softmax amax # amaxList[amax_id] = amaxList[28] # amax_id += 1 # #### bmm2 amax # amaxList[amax_id] = amaxList[8] # amax_id += 1 qkvMax = np.maximum(np.maximum(amaxList[16],amaxList[20]), amaxList[24]) amaxList[amax_id] = amaxList[16] * amaxList[20] / (127.0 * 127.0) amax_id += 1 amaxList[amax_id] = 127.0 / amaxList[28] amax_id += 1 amaxList[amax_id] = amaxList[24] * amaxList[28] / (127.0 * amaxList[8]) amax_id += 1 init_dict["layers.{}.blocks.{}.amaxList".format(i, depth)] = torch.tensor(amaxList, dtype=torch.float32) if verbose: print("done process layer_{} block_{} kernel weight".format(i, depth)) if i != layer_num - 1: kernel = init_dict["layers.{}.downsample.reduction.weight".format(i)] quant_max2 = init_dict["layers.{}.downsample.reduction._weight_quantizer._amax".format(i)] amax2 = abs(quant_max2) kernel = kernel.transpose(-1, -2).contiguous() kernel_processed = weight_quantize(kernel, amax2.cuda()) init_dict["layers.{}.downsample.reduction.weight".format(i)] = kernel_processed # print("Quantizing checkpoint done.") return init_dict if __name__ == '__main__': weights = torch.load('pytorch_model.bin') extract_amaxlist(weights, [2, 2, 6, 2])
[ "torch.load", "torch.tensor", "numpy.zeros", "torch.classes.load_library", "numpy.maximum" ]
[((946, 982), 'torch.classes.load_library', 'torch.classes.load_library', (['ths_path'], {}), '(ths_path)\n', (972, 982), False, 'import torch\n'), ((10265, 10296), 'torch.load', 'torch.load', (['"""pytorch_model.bin"""'], {}), "('pytorch_model.bin')\n", (10275, 10296), False, 'import torch\n'), ((9514, 9557), 'torch.tensor', 'torch.tensor', (['amaxList'], {'dtype': 'torch.float32'}), '(amaxList, dtype=torch.float32)\n', (9526, 9557), False, 'import torch\n'), ((9085, 9123), 'numpy.maximum', 'np.maximum', (['amaxList[16]', 'amaxList[20]'], {}), '(amaxList[16], amaxList[20])\n', (9095, 9123), True, 'import numpy as np\n'), ((3728, 3752), 'numpy.zeros', 'np.zeros', (['[amaxTotalNum]'], {}), '([amaxTotalNum])\n', (3736, 3752), True, 'import numpy as np\n')]
#/usr/bin/python __version__ = '1.0' __author__ = '<EMAIL>' ## ## Imports import string import os import errno import shutil import sys import glob import datetime import subprocess import logging as log import numpy as np import csv from io import StringIO import PyPDF2 from sklearn import preprocessing from collections import defaultdict from xml.etree import cElementTree from lxml import etree from reportlab.pdfgen import canvas class Colour: def __init__(self): pass purple = '\033[95m' cyan = '\033[96m' darkcyan = '\033[36m' blue = '\033[94m' green = '\033[92m' yellow = '\033[93m' red = '\033[91m' bold = '\033[1m' underline = '\033[4m' end = '\033[0m' class ConfigReader(object): """ The configuration file reader. Opens a configuration file, and if valid, converts the parameters within the file to a dictionary object, reader to be viewed through accessing the config_dict variable. """ def __init__(self, scriptdir, config_filename=None): ## ## Instance variables self.scriptdir = scriptdir self.config_filename = config_filename self.dtd_filename = scriptdir + "/config/config.dtd" ## ## Check for configuration file (just incase) if self.config_filename is None: log.error("No configuration file specified!") else: self.config_file = etree.parse(self.config_filename) ## ## Check config vs dtd, parse info to dictionary, validate vs ruleset self.validate_against_dtd() self.set_dictionary() self.validate_config() def validate_against_dtd(self): """ Validate input config against DTD ruleset i.e. confirms conformation of XML structure """ ## ## Open > etree.DTD object dtd_file = open(self.dtd_filename, 'r') dtd_object = etree.DTD(dtd_file) ## ## If validation fails, close the object (memory) and raise an error if not dtd_object.validate(self.config_file): dtd_file.close() log.error("DTD validation failure {0}: {1}".format(self.config_filename, dtd_object.error_log.filter_from_errors()[0])) sys.exit(2) dtd_file.close() def set_dictionary(self): """ Takes the now validated XML and extracts information from the tree into a python dictionary {key: value}. This dictionary will be used for variables within the pipeline. Recursion adapted from http://stackoverflow.com/a/9286702 """ def recursive_generation(t): d = {t.tag: {} if t.attrib else None} children = list(t) ## ## If list was populated, create dictionary, Append keys if children: dd = defaultdict(list) for dc in map(recursive_generation, children): for k, v in dc.items(): dd[k].append(v) d = {t.tag: {k: v[0] if len(v) == 1 else v for k, v in dd.items()}} ## ## Values for key if t.attrib: d[t.tag].update(('@' + k, v) for k, v in t.attrib.items()) if t.text: text = t.text.strip() if children or t.attrib: if text: d[t.tag]['#text'] = text else: d[t.tag] = text return d ## ## Takes the formatted xml doc, puts through generator, returns dictionary string_repr = etree.tostring(self.config_file, pretty_print=True) element_tree = cElementTree.XML(string_repr) self.config_dict = recursive_generation(element_tree) self.config_dict = self.config_dict[list(self.config_dict.keys())[0]] def validate_config(self): """ Method which validates the configuration file's contents. If all pass, guarantees that the settings dictionary is full of valid settings! """ trigger = False ## ## Main configuration instance settings data_directory = self.config_dict['@data_dir'] if not os.path.exists(data_directory): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified data directory could not be found.')) trigger = True for fqfile in glob.glob(os.path.join(data_directory, '*')): if not (fqfile.endswith('.fq') or fqfile.endswith('.fastq') or fqfile.endswith('.fq.gz') or fqfile.endswith('.fastq.gz')): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Non FastQ/GZ data detected in specified input directory.')) trigger = True forward_reference = self.config_dict['@forward_reference'] if not os.path.isfile(forward_reference): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified forward reference file could not be found.')) trigger = True if not (forward_reference.endswith('.fa') or forward_reference.endswith('.fasta')): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified forward reference file is not a fa/fas file.')) trigger = True reverse_reference = self.config_dict['@reverse_reference'] if not os.path.isfile(reverse_reference): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified reverse reference file could not be found.')) trigger = True if not (reverse_reference.endswith('fa') or reverse_reference.endswith('.fasta')): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified reverse reference file is not a fa/fas file.')) trigger = True if forward_reference.split('/')[-1] == reverse_reference.split('/')[-1]: log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: FW and RV references have identical filenames. Will create indexing issue.')) trigger = True ## ## Instance flag settings demultiplexing_flag = self.config_dict['instance_flags']['@demultiplex'] if not (demultiplexing_flag == 'True' or demultiplexing_flag == 'False'): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Demultiplexing flag is not set to True/False.')) trigger = True sequence_qc_flag = self.config_dict['instance_flags']['@quality_control'] if not (sequence_qc_flag == 'True' or sequence_qc_flag == 'False'): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Sequence Quality control flag is not set to True/False.')) trigger = True alignment_flag = self.config_dict['instance_flags']['@sequence_alignment'] if not (alignment_flag == 'True' or alignment_flag == 'False'): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Sequence Alignment flag is not set to True/False.')) trigger = True atypical_flag = self.config_dict['instance_flags']['@atypical_realignment'] if not (atypical_flag == 'True' or atypical_flag == 'False'): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Atypical Realignment flag is not True/False.')) trigger = True genotype_flag = self.config_dict['instance_flags']['@genotype_prediction'] if not (genotype_flag == 'True' or genotype_flag == 'False'): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Genotype Prediction control flag is not True/False.')) trigger = True snpcall_flag = self.config_dict['instance_flags']['@snp_calling'] if not (snpcall_flag == 'True' or snpcall_flag == 'False'): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: SNP Calling flag is not True/False.')) trigger = True ## ## Demultiplexing flag settings trim_adapter_base = ['A', 'G', 'C', 'T'] if demultiplexing_flag == 'True': forward_adapter = self.config_dict['demultiplex_flags']['@forward_adapter'] for charbase in forward_adapter: if charbase not in trim_adapter_base: log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Invalid character detected in forward_adapter demultiplexing flag.')) trigger = True forward_position = self.config_dict['demultiplex_flags']['@forward_position'] if forward_position not in ['5P', '3P', 'AP']: log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Given demultiplexing forward adapter position invalid! [5P, 3P, AP]')) trigger = True reverse_adapter = self.config_dict['demultiplex_flags']['@reverse_adapter'] for charbase in reverse_adapter: if charbase not in trim_adapter_base: log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Invalid character detected in reverse_adapter demultiplexing flag.')) trigger = True reverse_position = self.config_dict['demultiplex_flags']['@reverse_position'] if reverse_position not in ['5P', '3P', 'AP']: log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Given demultiplexing reverse adapter position invalid! [5P, 3P, AP]')) trigger = True error_rate = self.config_dict['demultiplex_flags']['@error_rate'] if not error_rate.isdigit(): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified error_rate is not a valid integer.')) trigger = True minimum_overlap = self.config_dict['demultiplex_flags']['@min_overlap'] if not minimum_overlap.isdigit(): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified min_overlap is not a valid integer.')) trigger = True minimum_length = self.config_dict['demultiplex_flags']['@min_length'] if not minimum_length == '': if not minimum_length.isdigit(): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified min_length is not a valid integer.')) trigger = True maximum_length = self.config_dict['demultiplex_flags']['@max_length'] if not maximum_length == '': if not maximum_length.isdigit(): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified max_length is not a valid integer.')) trigger = True ## ## Trimming flag settings if sequence_qc_flag == 'True': trimming_type = self.config_dict['trim_flags']['@trim_type'] if not (trimming_type == 'Quality' or trimming_type == 'Adapter' or trimming_type == 'Both'): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Trimming type is not Quality/Adapter/Both.')) trigger = True quality_threshold = self.config_dict['trim_flags']['@quality_threshold'] if not quality_threshold.isdigit(): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified quality threshold integer is invalid.')) trigger = True elif not int(quality_threshold) in range(0,39): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified quality threshold integer out of range (0-38).')) trigger = True trim_adapters = ['-a','-g','-a$','-g^','-b'] adapter_flag = self.config_dict['trim_flags']['@adapter_flag'] if not (adapter_flag in trim_adapters): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified trimming adapter not valid selection.')) trigger = True forward_adapter = self.config_dict['trim_flags']['@forward_adapter'] for charbase in forward_adapter: if charbase not in trim_adapter_base: log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Invalid character detected in FW adapter sequence.')) trigger = True reverse_adapter = self.config_dict['trim_flags']['@reverse_adapter'] for charbase in reverse_adapter: if charbase not in trim_adapter_base: log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Invalid character detected in RV adapter sequence.')) trigger = True error_tolerance = self.config_dict['trim_flags']['@error_tolerance'] if not isinstance(float(error_tolerance), float): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified error tolerance is not a valid float.')) trigger = True if not float(error_tolerance) in np.arange(0,1.1,0.01): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified error tolerance is not 0.0 < x < 1.0.')) trigger = True ## ## Alignment flag settings if alignment_flag == 'True': min_seed_length = self.config_dict['alignment_flags']['@min_seed_length'] if not min_seed_length.isdigit(): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified min_seed_length integer is invalid.')) trigger=True band_width = self.config_dict['alignment_flags']['@band_width'] if not band_width.isdigit(): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified band_width integer is invalid.')) trigger=True seed_length_extension = self.config_dict['alignment_flags']['@seed_length_extension'] if not isinstance(float(seed_length_extension), float): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified seed_length_extension float is invalid.')) trigger=True skip_seed_with_occurrence = self.config_dict['alignment_flags']['@skip_seed_with_occurrence'] if not skip_seed_with_occurrence.isdigit(): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified skip_seed_with_occurrence integer is invalid.')) trigger=True chain_drop = self.config_dict['alignment_flags']['@chain_drop'] if not isinstance(float(chain_drop), float): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified chain_drop float is invalid.')) trigger=True seeded_chain_drop = self.config_dict['alignment_flags']['@seeded_chain_drop'] if not seeded_chain_drop.isdigit(): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified seeded_chain_drop integer is invalid.')) trigger=True seq_match_score = self.config_dict['alignment_flags']['@seq_match_score'] if not seq_match_score.isdigit(): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified seq_match_score integer is invalid.')) trigger=True mismatch_penalty = self.config_dict['alignment_flags']['@mismatch_penalty'] if not mismatch_penalty.isdigit(): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified mismatch_penalty integer is invalid.')) trigger=True indel_penalty_raw = self.config_dict['alignment_flags']['@indel_penalty'] indel_penalty = indel_penalty_raw.split(',') for individual_indelpen in indel_penalty: if not individual_indelpen.isdigit(): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified indel_penalty integer(s) is(are) invalid.')) trigger=True gap_extend_penalty_raw = self.config_dict['alignment_flags']['@gap_extend_penalty'] gap_extend_penalty = gap_extend_penalty_raw.split(',') for individual_gaextend in gap_extend_penalty: if not individual_gaextend.isdigit(): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified gap_extend_penalty integer(s) is(are) invalid.')) trigger=True prime_clipping_penalty_raw = self.config_dict['alignment_flags']['@prime_clipping_penalty'] prime_clipping_penalty = prime_clipping_penalty_raw.split(',') for individual_prclip in prime_clipping_penalty: if not individual_prclip.isdigit(): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified prime_clipping_penalty integer(s) is(are) invalid.')) trigger=True unpaired_pairing_penalty = self.config_dict['alignment_flags']['@unpaired_pairing_penalty'] if not unpaired_pairing_penalty.isdigit(): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Specified unpaired_pairing_penalty integer is invalid.')) trigger=True ## ## Genotype prediction flag settings if genotype_flag == 'True': snp_observation_pcnt = self.config_dict['prediction_flags']['@snp_observation_threshold'] if not snp_observation_pcnt.isdigit(): if not int(snp_observation_pcnt) in range(1,5): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: SNP Observation value invalid! Please use 1-10.')) trigger = True quality_cutoff = self.config_dict['prediction_flags']['@quality_cutoff'] if not quality_cutoff.isdigit(): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: SNP Quality Cutoff value is not an integer.')) trigger = True if trigger: log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'XML Config: Failure, exiting.')) sys.exit(2) else: log.info('{}{}{}{}'.format(Colour.green, 'shd__ ', Colour.end, 'XML Config: Parsing parameters successful!')) class DataClump(dict): """Container object for datasets: dictionary-like object that exposes its keys as attributes.""" def __init__(self, **kwargs): dict.__init__(self, kwargs) self.__dict__ = self class DataLoader: def __init__(self, database, descriptor): self.database = database self.descriptor = descriptor def load_model(self): ## Loads description file for respective data set modeldescr_name = self.descriptor with open(modeldescr_name) as f: descr_text = f.read() ## Loads data set from csv, into objects in preparation for bunch() data_file_name = self.database with open(data_file_name) as f: data_file = csv.reader(f) temp = next(data_file) n_samples = int(temp[0]) n_features = int(temp[1]) data = np.empty((n_samples, n_features)) temp = next(data_file) feature_names = np.array(temp) labels = [] for i, d in enumerate(data_file): data[i] = d[:-1] label = d[-1] labels.append(label) le = preprocessing.LabelEncoder() le.fit(labels) hash_int_labels = le.transform(labels) return DataClump(DATA=data, TARGET=hash_int_labels, FTRNAME=feature_names[:-1], DESCR=descr_text, ENCDR=le) def parse_boolean(boolean_value): """ Given a string (boolean_value), returns a boolean value representing the string contents. For example, a string with 'true', 't', 'y' or 'yes' will yield True. """ boolean_value = string.lower(boolean_value) in ('yes', 'y', 'true', 't', '1') return boolean_value def empty_string_check(string, raise_exception=True): """ Simple check to see if the string provided by parameter string is empty. False indicates the string is NOT empty. Parameter raise_exception determines if a ValueError exception should be raised if the string is empty. If raise_exception is False and the string is empty, True is returned. """ if string != '': return False if raise_exception: raise ValueError("Empty string detected!") return True def sanitise_inputs(parsed_arguments): """ Utilises filesystem_exists_check and check_input_files if either return false, path is invalid or unsupported files present so, quit """ trigger = False ## ## Jobname prefix validity check if parsed_arguments.jobname: for character in parsed_arguments.jobname: if character is ' ' or character is '/': log.error('{}{}{}{}{}{}'.format(Colour.red,'shd__ ',Colour.end,'Specified Job Name has invalid characters: "', character, '"')) trigger = True ## ## Config mode check if parsed_arguments.config: if not filesystem_exists_check(parsed_arguments.config[0]): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'Specified config file could not be found.')) trigger = True for xmlfile in parsed_arguments.config: if not check_input_files('.xml',xmlfile): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'Specified config file is not an XML file.')) trigger = True return trigger def extract_data(input_data_directory): target_files = glob.glob(os.path.join(input_data_directory, '*')) for extract_target in target_files: if extract_target.lower().endswith(('.fq.gz', '.fastq.gz')): log.info('{}{}{}{}'.format(Colour.bold, 'shd__ ', Colour.end, 'Detected compressed input data. Extracting!')) break for extract_target in target_files: unzipd = subprocess.Popen(['gzip', '-q', '-f', '-d', extract_target], stderr=subprocess.PIPE) unzipd.wait() return True def sequence_pairings(data_path, instance_rundir): ## ## Get input files from data path ## Sort so that ordering isn't screwy on linux input_files = glob.glob(os.path.join(data_path, '*')) sorted_input = sorted(input_files) sequence_pairs = [] file_count = len(sorted_input) if not file_count % 2 == 0: log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'I/O: Non-even number of input files specified. Cannot continue without pairing!')) sys.exit(2) ## ## Optimise so code isn't recycled for i in range(0, len(sorted_input), 2): file_pair = {} forward_data = sorted_input[i] reverse_data = sorted_input[i+1] ## ## Check forward ends with R1 forward_data_name = sorted_input[i].split('/')[-1].split('.')[0] if not forward_data_name.endswith('_R1'): log.error('{}{}{}{}{}'.format(Colour.red,'shd__ ',Colour.end,'I/O: Forward input file does not end in _R1. ', forward_data)) sys.exit(2) ## ## Check reverse ends with R2 reverse_data_name = sorted_input[i+1].split('/')[-1].split('.')[0] if not reverse_data_name.endswith('_R2'): log.error('{}{}{}{}{}'.format(Colour.red,'shd__ ',Colour.end,'I/O: Reverse input file does not end in _R2. ', reverse_data)) sys.exit(2) ## ## Make Stage outputs for use in everywhere else in pipeline sample_root = '_'.join(forward_data_name.split('_')[:-1]) instance_path = os.path.join(instance_rundir) seq_qc_path = os.path.join(instance_rundir, sample_root, 'SeqQC') align_path = os.path.join(instance_rundir, sample_root, 'Align') predict_path = os.path.join(instance_rundir, sample_root, 'Predict') file_pair[sample_root] = [forward_data, reverse_data, instance_path, seq_qc_path, align_path, predict_path] sequence_pairs.append(file_pair) return sequence_pairs def filesystem_exists_check(path, raise_exception=True): """ Checks to see if the path, specified by parameter path, exists. Can be either a directory or file. If the path exists, True is returned. If the path does not exist, and raise_exception is set to True, an IOError is raised - else False is returned. """ if os.path.lexists(path): return True if raise_exception: log.error('{}{}{}{}'.format(Colour.red,'shd__ ',Colour.end,'Specified input path could not be found.')) return False def check_input_files(input_format, input_file): if input_file.endswith(input_format): return True return False def initialise_libraries(instance_params): trigger = False ## ## Subfunction for recycling code ## Calls UNIX type for checking binaries present ## Changed from WHICH as apparently type functions over different shells/config files def type_func(binary): binary_result = [] binary_string = 'type {}'.format(binary) binary_subprocess = subprocess.Popen([binary_string], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) binary_result = binary_subprocess.communicate() binary_subprocess.wait() if 'not found'.encode() in binary_result[0] or binary_result[1]: log.critical('{}{}{}{}{}{}'.format(Colour.red,'shd__ ',Colour.end,'Missing binary: ', binary, '!')) raise NameError ## ## To determine which binaries to check for ## AttributeError in the situation where instance_params origin differs ## try for -c style, except AttributeError for -b style try: quality_control = instance_params.config_dict['instance_flags']['@quality_control'] alignment = instance_params.config_dict['instance_flags']['@sequence_alignment'] genotyping = instance_params.config_dict['instance_flags']['@genotype_prediction'] snp_calling = instance_params.config_dict['instance_flags']['@snp_calling'] except AttributeError: quality_control = instance_params['quality_control'] alignment = instance_params['sequence_alignment'] genotyping = instance_params['genotype_prediction'] snp_calling = instance_params['snp_calling'] if quality_control == 'True': try:type_func('java') except NameError: trigger=True try:type_func('fastqc') except NameError: trigger=True try:type_func('cutadapt') except NameError: trigger=True if alignment == 'True': try:type_func('seqtk') except NameError: trigger=True try:type_func('bwa') except NameError: trigger=True try:type_func('samtools') except NameError: trigger=True try:type_func('generatr') except NameError: trigger=True if genotyping == 'True': try:type_func('samtools') except NameError: trigger=True try:type_func('generatr') except NameError: trigger=True if snp_calling == 'True': try: type_func('picard') except NameError: trigger=True try: type_func('freebayes') except NameError: trigger=True return trigger def sanitise_outputs(jobname, output_argument): run_dir = '' output_root = output_argument[0] if jobname: target_output = os.path.join(output_root, jobname) if not os.path.exists(target_output): log.info('{}{}{}{}{}'.format(Colour.bold, 'shd__ ', Colour.end, 'Creating Output with prefix: ', jobname)) run_dir = os.path.join(output_root, jobname) mkdir_p(run_dir) else: purge_choice = '' while True: purge_choice = input('{}{}{}{}'.format(Colour.bold, 'shd__ ', Colour.end, 'Job folder already exists. Delete existing folder? Y/N: ')) if not (purge_choice.lower() == 'y') and not (purge_choice.lower() == 'n'): log.info('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'Invalid input. Please input Y or N.')) continue else: break if purge_choice.lower() == 'y': log.info('{}{}{}{}{}'.format(Colour.bold, 'shd__ ', Colour.end, 'Clearing pre-existing Jobname Prefix: ', jobname)) run_dir = os.path.join(output_root, jobname) if os.path.exists(run_dir): shutil.rmtree(run_dir, ignore_errors=True) mkdir_p(run_dir) else: raise Exception('User chose not to delete pre-existing Job folder. Cannot write output.') else: ## Ensures root output is a real directory ## Generates folder name based on date (for run ident) date = datetime.date.today().strftime('%d-%m-%Y') walltime = datetime.datetime.now().strftime('%H%M%S') today = date + '-' + walltime ## If the user specified root doesn't exist, make it ## Then make the run directory for datetime if not os.path.exists(output_root): log.info('{}{}{}{}'.format(Colour.bold, 'shd__ ', Colour.end, 'Creating output root... ')) mkdir_p(output_root) run_dir = os.path.join(output_root, 'ScaleHDRun_'+today) log.info('{}{}{}{}'.format(Colour.bold, 'shd__ ', Colour.end, 'Creating instance run directory.. ')) mkdir_p(run_dir) ## Inform user it's all gonna be okaaaayyyy log.info('{}{}{}{}'.format(Colour.green, 'shd__ ', Colour.end, 'Output directories OK!')) return run_dir def replace_fqfile(mutate_list, target_fqfile, altered_path): if target_fqfile in mutate_list: loc = mutate_list.index(target_fqfile) mutate_list[loc] = altered_path return mutate_list def scrape_summary_data(stage, input_report_file): ## ## If the argument input_report_file is from trimming.. if stage == 'trim': with open(input_report_file, 'r') as trpf: trim_lines = trpf.readlines() ## ## Determine buffer size to slice from above array scraping_buffer = 8 if '-q' in trim_lines[1]: scraping_buffer += 1 ## ## Get Anchor summary_start = 0 for i in range(0, len(trim_lines)): if '== Summary ==' in trim_lines[i]: summary_start = i ## ## Slice and close summary_data = trim_lines[summary_start:summary_start + scraping_buffer] trpf.close() return summary_data[2:] ## ## If the argument input_report_file is from alignment.. if stage == 'align': with open(input_report_file, 'r') as alnrpf: align_lines = alnrpf.readlines() alnrpf.close() ## ## No ranges required, only skip first line return align_lines[1:] ## ## No need to tidy up report for genotyping ## since we already have the data from our own objects if stage == 'gtype': pass def generate_atypical_xml(label, allele_object, index_path, direction): """ :param allele_object: :param index_path: :return: """ ##TODO docstring atypical_path = os.path.join(index_path, '{}{}_{}.xml'.format(direction, label, allele_object.get_reflabel())) fp_flank = 'GCGACCCTGGAAAAGCTGATGAAGGCCTTCGAGTCCCTCAAGTCCTTC' cagstart = ''; cagend = '' intv = allele_object.get_intervening() ccgstart = ''; ccgend = '' ccglen = allele_object.get_ccg() cctlen = allele_object.get_cct() tp_flank = 'CAGCTTCCTCAGCCGCCGCCGCAGGCACAGCCGCTGCT' if direction == 'fw': cagstart = '1'; cagend = '200' ccgstart = '1'; ccgend = '20' if direction == 'rv': cagstart = '100'; cagend = '100' ccgstart = '1'; ccgend = '20' ## ## Create XML data_root = etree.Element('data') loci_root = etree.Element('loci', label=allele_object.get_reflabel()); data_root.append(loci_root) ## ## Loci Nodes fp_input = etree.Element('input', type='fiveprime', flank=fp_flank) cag_region = etree.Element('input', type='repeat_region', order='1', unit='CAG', start=cagstart, end=cagend) intervening = etree.Element('input', type='intervening', sequence=intv, prior='1') ccg_region = etree.Element('input', type='repeat_region', order='2', unit='CCG', start=ccgstart, end=ccgend) cct_region = etree.Element('input', type='repeat_region', order='3', unit='CCT', start=str(cctlen), end=str(cctlen)) tp_input = etree.Element('input', type='threeprime', flank=tp_flank) for node in [fp_input, cag_region, intervening, ccg_region, cct_region, tp_input]: loci_root.append(node) s = etree.tostring(data_root, pretty_print=True) with open(atypical_path, 'w') as xmlfi: xmlfi.write(s.decode()) xmlfi.close() return atypical_path def generate_reference(input_xml, index_path, ref_indexes, direction): ##TODO docstring label = input_xml.split('/')[-1].split('.')[0] target_output = os.path.join(index_path, label + '.fa') temp_output = os.path.join(index_path, label + '_concat.fa') gen_process = subprocess.Popen(['generatr', '-i', input_xml, '-o', target_output], stdout=subprocess.PIPE, stderr=subprocess.PIPE) gen_process.wait() ## ## Join typical and atypical reference into one file if direction == 'fw': toutfi = open(temp_output, 'w') cat_process = subprocess.Popen(['cat', target_output, ref_indexes[0]], stdout=toutfi, stderr=subprocess.PIPE) cat_process.wait() toutfi.close() target_output = temp_output return target_output def seek_target(input_list, target): for i in range(0, len(input_list)): if target in input_list[i]: return i def sanitise_trimming_output(input_object, input_list): if type(input_object) is int: cleanse_target = input_list[input_object].split(':')[1].lstrip().rstrip() return cleanse_target else: return '*' def sanitise_alignment_output(input_object, input_list, stage): if type(input_object) is int: if stage == 3: cleanse_target = input_list[input_object].lstrip().rstrip().split(' ')[0:1] return ''.join(cleanse_target) else: cleanse_target = input_list[input_object].lstrip().rstrip().split(' ')[0:2] return ' '.join(cleanse_target) else: return '*' def mkdir_p(path): try: os.makedirs(path) except OSError as exc: if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: raise
[ "sklearn.preprocessing.LabelEncoder", "numpy.array", "sys.exit", "logging.error", "lxml.etree.tostring", "numpy.arange", "os.path.exists", "xml.etree.cElementTree.XML", "subprocess.Popen", "os.path.lexists", "os.path.isdir", "numpy.empty", "lxml.etree.DTD", "csv.reader", "os.path.isfile", "datetime.date.today", "lxml.etree.Element", "os.makedirs", "lxml.etree.parse", "os.path.join", "datetime.datetime.now", "collections.defaultdict", "shutil.rmtree", "string.lower" ]
[((22060, 22081), 'os.path.lexists', 'os.path.lexists', (['path'], {}), '(path)\n', (22075, 22081), False, 'import os\n'), ((28633, 28654), 'lxml.etree.Element', 'etree.Element', (['"""data"""'], {}), "('data')\n", (28646, 28654), False, 'from lxml import etree\n'), ((28787, 28843), 'lxml.etree.Element', 'etree.Element', (['"""input"""'], {'type': '"""fiveprime"""', 'flank': 'fp_flank'}), "('input', type='fiveprime', flank=fp_flank)\n", (28800, 28843), False, 'from lxml import etree\n'), ((28858, 28958), 'lxml.etree.Element', 'etree.Element', (['"""input"""'], {'type': '"""repeat_region"""', 'order': '"""1"""', 'unit': '"""CAG"""', 'start': 'cagstart', 'end': 'cagend'}), "('input', type='repeat_region', order='1', unit='CAG', start=\n cagstart, end=cagend)\n", (28871, 28958), False, 'from lxml import etree\n'), ((28969, 29037), 'lxml.etree.Element', 'etree.Element', (['"""input"""'], {'type': '"""intervening"""', 'sequence': 'intv', 'prior': '"""1"""'}), "('input', type='intervening', sequence=intv, prior='1')\n", (28982, 29037), False, 'from lxml import etree\n'), ((29052, 29152), 'lxml.etree.Element', 'etree.Element', (['"""input"""'], {'type': '"""repeat_region"""', 'order': '"""2"""', 'unit': '"""CCG"""', 'start': 'ccgstart', 'end': 'ccgend'}), "('input', type='repeat_region', order='2', unit='CCG', start=\n ccgstart, end=ccgend)\n", (29065, 29152), False, 'from lxml import etree\n'), ((29278, 29335), 'lxml.etree.Element', 'etree.Element', (['"""input"""'], {'type': '"""threeprime"""', 'flank': 'tp_flank'}), "('input', type='threeprime', flank=tp_flank)\n", (29291, 29335), False, 'from lxml import etree\n'), ((29452, 29496), 'lxml.etree.tostring', 'etree.tostring', (['data_root'], {'pretty_print': '(True)'}), '(data_root, pretty_print=True)\n', (29466, 29496), False, 'from lxml import etree\n'), ((29760, 29799), 'os.path.join', 'os.path.join', (['index_path', "(label + '.fa')"], {}), "(index_path, label + '.fa')\n", (29772, 29799), False, 'import os\n'), ((29815, 29861), 'os.path.join', 'os.path.join', (['index_path', "(label + '_concat.fa')"], {}), "(index_path, label + '_concat.fa')\n", (29827, 29861), False, 'import os\n'), ((29877, 29998), 'subprocess.Popen', 'subprocess.Popen', (["['generatr', '-i', input_xml, '-o', target_output]"], {'stdout': 'subprocess.PIPE', 'stderr': 'subprocess.PIPE'}), "(['generatr', '-i', input_xml, '-o', target_output], stdout\n =subprocess.PIPE, stderr=subprocess.PIPE)\n", (29893, 29998), False, 'import subprocess\n'), ((1723, 1742), 'lxml.etree.DTD', 'etree.DTD', (['dtd_file'], {}), '(dtd_file)\n', (1732, 1742), False, 'from lxml import etree\n'), ((3064, 3115), 'lxml.etree.tostring', 'etree.tostring', (['self.config_file'], {'pretty_print': '(True)'}), '(self.config_file, pretty_print=True)\n', (3078, 3115), False, 'from lxml import etree\n'), ((3133, 3162), 'xml.etree.cElementTree.XML', 'cElementTree.XML', (['string_repr'], {}), '(string_repr)\n', (3149, 3162), False, 'from xml.etree import cElementTree\n'), ((17907, 17934), 'string.lower', 'string.lower', (['boolean_value'], {}), '(boolean_value)\n', (17919, 17934), False, 'import string\n'), ((19526, 19565), 'os.path.join', 'os.path.join', (['input_data_directory', '"""*"""'], {}), "(input_data_directory, '*')\n", (19538, 19565), False, 'import os\n'), ((19838, 19927), 'subprocess.Popen', 'subprocess.Popen', (["['gzip', '-q', '-f', '-d', extract_target]"], {'stderr': 'subprocess.PIPE'}), "(['gzip', '-q', '-f', '-d', extract_target], stderr=\n subprocess.PIPE)\n", (19854, 19927), False, 'import subprocess\n'), ((20118, 20146), 'os.path.join', 'os.path.join', (['data_path', '"""*"""'], {}), "(data_path, '*')\n", (20130, 20146), False, 'import os\n'), ((20417, 20428), 'sys.exit', 'sys.exit', (['(2)'], {}), '(2)\n', (20425, 20428), False, 'import sys\n'), ((21330, 21359), 'os.path.join', 'os.path.join', (['instance_rundir'], {}), '(instance_rundir)\n', (21342, 21359), False, 'import os\n'), ((21376, 21427), 'os.path.join', 'os.path.join', (['instance_rundir', 'sample_root', '"""SeqQC"""'], {}), "(instance_rundir, sample_root, 'SeqQC')\n", (21388, 21427), False, 'import os\n'), ((21443, 21494), 'os.path.join', 'os.path.join', (['instance_rundir', 'sample_root', '"""Align"""'], {}), "(instance_rundir, sample_root, 'Align')\n", (21455, 21494), False, 'import os\n'), ((21512, 21565), 'os.path.join', 'os.path.join', (['instance_rundir', 'sample_root', '"""Predict"""'], {}), "(instance_rundir, sample_root, 'Predict')\n", (21524, 21565), False, 'import os\n'), ((22705, 22802), 'subprocess.Popen', 'subprocess.Popen', (['[binary_string]'], {'shell': '(True)', 'stdout': 'subprocess.PIPE', 'stderr': 'subprocess.PIPE'}), '([binary_string], shell=True, stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n', (22721, 22802), False, 'import subprocess\n'), ((24730, 24764), 'os.path.join', 'os.path.join', (['output_root', 'jobname'], {}), '(output_root, jobname)\n', (24742, 24764), False, 'import os\n'), ((26316, 26364), 'os.path.join', 'os.path.join', (['output_root', "('ScaleHDRun_' + today)"], {}), "(output_root, 'ScaleHDRun_' + today)\n", (26328, 26364), False, 'import os\n'), ((30146, 30245), 'subprocess.Popen', 'subprocess.Popen', (["['cat', target_output, ref_indexes[0]]"], {'stdout': 'toutfi', 'stderr': 'subprocess.PIPE'}), "(['cat', target_output, ref_indexes[0]], stdout=toutfi,\n stderr=subprocess.PIPE)\n", (30162, 30245), False, 'import subprocess\n'), ((31056, 31073), 'os.makedirs', 'os.makedirs', (['path'], {}), '(path)\n', (31067, 31073), False, 'import os\n'), ((1227, 1272), 'logging.error', 'log.error', (['"""No configuration file specified!"""'], {}), "('No configuration file specified!')\n", (1236, 1272), True, 'import logging as log\n'), ((1303, 1336), 'lxml.etree.parse', 'etree.parse', (['self.config_filename'], {}), '(self.config_filename)\n', (1314, 1336), False, 'from lxml import etree\n'), ((2014, 2025), 'sys.exit', 'sys.exit', (['(2)'], {}), '(2)\n', (2022, 2025), False, 'import sys\n'), ((3600, 3630), 'os.path.exists', 'os.path.exists', (['data_directory'], {}), '(data_directory)\n', (3614, 3630), False, 'import os\n'), ((3802, 3835), 'os.path.join', 'os.path.join', (['data_directory', '"""*"""'], {}), "(data_directory, '*')\n", (3814, 3835), False, 'import os\n'), ((4192, 4225), 'os.path.isfile', 'os.path.isfile', (['forward_reference'], {}), '(forward_reference)\n', (4206, 4225), False, 'import os\n'), ((4689, 4722), 'os.path.isfile', 'os.path.isfile', (['reverse_reference'], {}), '(reverse_reference)\n', (4703, 4722), False, 'import os\n'), ((16299, 16310), 'sys.exit', 'sys.exit', (['(2)'], {}), '(2)\n', (16307, 16310), False, 'import sys\n'), ((17104, 17117), 'csv.reader', 'csv.reader', (['f'], {}), '(f)\n', (17114, 17117), False, 'import csv\n'), ((17215, 17248), 'numpy.empty', 'np.empty', (['(n_samples, n_features)'], {}), '((n_samples, n_features))\n', (17223, 17248), True, 'import numpy as np\n'), ((17296, 17310), 'numpy.array', 'np.array', (['temp'], {}), '(temp)\n', (17304, 17310), True, 'import numpy as np\n'), ((17443, 17471), 'sklearn.preprocessing.LabelEncoder', 'preprocessing.LabelEncoder', ([], {}), '()\n', (17469, 17471), False, 'from sklearn import preprocessing\n'), ((20877, 20888), 'sys.exit', 'sys.exit', (['(2)'], {}), '(2)\n', (20885, 20888), False, 'import sys\n'), ((21171, 21182), 'sys.exit', 'sys.exit', (['(2)'], {}), '(2)\n', (21179, 21182), False, 'import sys\n'), ((24774, 24803), 'os.path.exists', 'os.path.exists', (['target_output'], {}), '(target_output)\n', (24788, 24803), False, 'import os\n'), ((24928, 24962), 'os.path.join', 'os.path.join', (['output_root', 'jobname'], {}), '(output_root, jobname)\n', (24940, 24962), False, 'import os\n'), ((26157, 26184), 'os.path.exists', 'os.path.exists', (['output_root'], {}), '(output_root)\n', (26171, 26184), False, 'import os\n'), ((2507, 2524), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (2518, 2524), False, 'from collections import defaultdict\n'), ((25557, 25591), 'os.path.join', 'os.path.join', (['output_root', 'jobname'], {}), '(output_root, jobname)\n', (25569, 25591), False, 'import os\n'), ((25599, 25622), 'os.path.exists', 'os.path.exists', (['run_dir'], {}), '(run_dir)\n', (25613, 25622), False, 'import os\n'), ((25915, 25936), 'datetime.date.today', 'datetime.date.today', ([], {}), '()\n', (25934, 25936), False, 'import datetime\n'), ((25971, 25994), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (25992, 25994), False, 'import datetime\n'), ((31133, 31152), 'os.path.isdir', 'os.path.isdir', (['path'], {}), '(path)\n', (31146, 31152), False, 'import os\n'), ((11661, 11684), 'numpy.arange', 'np.arange', (['(0)', '(1.1)', '(0.01)'], {}), '(0, 1.1, 0.01)\n', (11670, 11684), True, 'import numpy as np\n'), ((25629, 25671), 'shutil.rmtree', 'shutil.rmtree', (['run_dir'], {'ignore_errors': '(True)'}), '(run_dir, ignore_errors=True)\n', (25642, 25671), False, 'import shutil\n')]
#! /usr/bin/env python # -*- coding: utf-8 -*- # # author: <NAME> # contact: <EMAIL> import torch import SimpleITK as sitk import numpy as np import nibabel as nib from torch.autograd import Variable from skimage.transform import resize from torchvision import transforms from time import gmtime, strftime from tqdm import tqdm import pdb import os from ..helpers.helper import * from os.path import expanduser home = expanduser("~") #======================================================================================== # prediction functions..................... bin_path = os.path.join('/opt/ANTs/bin/') class tumorSeg(): """ class performs segmentation for a given sequence of patient data. to main platform for segmentation mask estimation one for the patient data in brats format other with any random format step followed for in estimation of segmentation mask 1. ABLnet for reducing false positives outside the brain Air Brain Lesson model (2D model, 103 layered) 2. BNet3Dnet 3D network for inner class classification Dual Path way network 3. MNet2D 57 layered convolutional network for inner class classification 4. Tir3Dnet 57 layered 3D convolutional network for inner class classification more on training details and network information: (https://link.springer.com/chapter/10.1007/978-3-030-11726-9_43<Paste>) ========================= quick: True (just evaluates on Dual path network (BNet3D) else copmutes an ensumble over all four networks """ def __init__(self, quick = False, ants_path = bin_path): device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") # device = "cpu" map_location = device #======================================================================================== ckpt_tir2D = os.path.join(home, '.DeepBrainSeg/BestModels/Tramisu_2D_FC57_best_loss.pth.tar') ckpt_tir3D = os.path.join(home, '.DeepBrainSeg/BestModels/Tramisu_3D_FC57_best_acc.pth.tar') ckpt_BNET3D = os.path.join(home, '.DeepBrainSeg/BestModels/BrainNet_3D_best_acc.pth.tar') ckpt_ABL = os.path.join(home, '.DeepBrainSeg/BestModels/ABL_CE_best_model_loss_based.pth.tar') #======================================================================================== # air brain lesion segmentation.............. from .models.modelABL import FCDenseNet103 self.ABLnclasses = 3 self.ABLnet = FCDenseNet103(n_classes = self.ABLnclasses) ## intialize the graph saved_parms=torch.load(ckpt_ABL, map_location=map_location) self.ABLnet.load_state_dict(saved_parms['state_dict']) ## fill the model with trained params print ("=================================== ABLNET2D Loaded =================================") self.ABLnet.eval() self.ABLnet = self.ABLnet.to(device) #======================================================================================== # Tir2D net....................... from .models.modelTir2D import FCDenseNet57 self.Mnclasses = 4 self.MNET2D = FCDenseNet57(self.Mnclasses) ckpt = torch.load(ckpt_tir2D, map_location=map_location) self.MNET2D.load_state_dict(ckpt['state_dict']) print ("=================================== MNET2D Loaded ===================================") self.MNET2D.eval() self.MNET2D = self.MNET2D.to(device) #======================================================================================== if not quick: # BrainNet3D model...................... from .models.model3DBNET import BrainNet_3D_Inception self.B3Dnclasses = 5 self.BNET3Dnet = BrainNet_3D_Inception() ckpt = torch.load(ckpt_BNET3D, map_location=map_location) self.BNET3Dnet.load_state_dict(ckpt['state_dict']) print ("=================================== KAMNET3D Loaded =================================") self.BNET3Dnet.eval() self.BNET3Dnet = self.BNET3Dnet.to(device) #======================================================================================== # Tir3D model................... from .models.modelTir3D import FCDenseNet57 self.T3Dnclasses = 5 self.Tir3Dnet = FCDenseNet57(self.T3Dnclasses) ckpt = torch.load(ckpt_tir3D, map_location=map_location) self.Tir3Dnet.load_state_dict(ckpt['state_dict']) print ("================================== TIRNET2D Loaded =================================") self.Tir3Dnet.eval() self.Tir3Dnet = self.Tir3Dnet.to(device) #======================================================================================== self.device = device self.quick = quick self.ants_path = ants_path def get_ants_mask(self, t1_path): """ We make use of ants framework for generalized skull stripping t1_path: t1 volume path (str) saves the mask in the same location as t1 data directory returns: maskvolume (numpy uint8 type) """ mask_path = os.path.join(os.path.dirname(t1_path), 'mask.nii.gz') os.system(self.ants_path +'ImageMath 3 '+ mask_path +' Normalize '+ t1_path) os.system(self.ants_path +'ThresholdImage 3 '+ mask_path +' '+ mask_path +' 0.01 1') os.system(self.ants_path +'ImageMath 3 '+ mask_path +' MD '+ mask_path +' 1') os.system(self.ants_path +'ImageMath 3 '+ mask_path +' ME '+ mask_path +' 1') os.system(self.ants_path +'CopyImageHeaderInformation '+ t1_path+' '+ mask_path +' '+ mask_path +' 1 1 1') mask = np.uint8(nib.load(mask_path).get_data()) return mask def get_localization(self, t1_v, t1c_v, t2_v, flair_v, brain_mask): """ ABLnetwork output, finds the brain, Whole tumor region t1_v = t1 volume (numpy array) t1c_v = t1c volume (numpy array) t2_v = t2 volume (numpy array) flair_v = flair volume (numpy array) brain_mask = brain, whole tumor mask (numpy array, output of ANTs pieline) """ t1_v = normalize(t1_v, brain_mask) t1c_v = normalize(t1c_v, brain_mask) t2_v = normalize(t2_v, brain_mask) flair_v = normalize(flair_v, brain_mask) generated_output_logits = np.empty((self.ABLnclasses, flair_v.shape[0],flair_v.shape[1],flair_v.shape[2])) for slices in tqdm(range(flair_v.shape[2])): flair_slice = np.transpose(flair_v[:,:,slices]) t2_slice = np.transpose(t2_v[:,:,slices]) t1ce_slice = np.transpose(t1c_v[:,:,slices]) t1_slice = np.transpose(t1_v[:,:,slices]) array = np.zeros((flair_slice.shape[0],flair_slice.shape[1],4)) array[:,:,0] = flair_slice array[:,:,1] = t2_slice array[:,:,2] = t1ce_slice array[:,:,3] = t1_slice transformed_array = torch.from_numpy(convert_image(array)).float() transformed_array = transformed_array.unsqueeze(0) ## neccessary if batch size == 1 transformed_array = transformed_array.to(self.device) logits = self.ABLnet(transformed_array).detach().cpu().numpy()# 3 x 240 x 240 generated_output_logits[:,:,:, slices] = logits.transpose(0, 1, 3, 2) final_pred = apply_argmax_to_logits(generated_output_logits) final_pred = perform_postprocessing(final_pred) final_pred = adjust_classes_air_brain_tumour(np.uint8(final_pred)) return np.uint8(final_pred) def inner_class_classification_with_logits_NCube(self, t1, t1ce, t2, flair, brain_mask, mask, N = 64): """ output of 3D tiramisu model (tir3Dnet) mask = numpy array output of ABLnet N = patch size during inference """ t1 = normalize(t1, brain_mask) t1ce = normalize(t1ce, brain_mask) t2 = normalize(t2, brain_mask) flair = normalize(flair, brain_mask) shape = t1.shape # to exclude batch_size final_prediction = np.zeros((self.T3Dnclasses, shape[0], shape[1], shape[2])) x_min, x_max, y_min, y_max, z_min, z_max = bbox(mask, pad = N) x_min, x_max, y_min, y_max, z_min, z_max = x_min, min(shape[0] - N, x_max), y_min, min(shape[1] - N, y_max), z_min, min(shape[2] - N, z_max) with torch.no_grad(): for x in tqdm(range(x_min, x_max, N//2)): for y in range(y_min, y_max, N//2): for z in range(z_min, z_max, N//2): high = np.zeros((1, 4, N, N, N)) high[0, 0, :, :, :] = flair[x:x+N, y:y+N, z:z+N] high[0, 1, :, :, :] = t2[x:x+N, y:y+N, z:z+N] high[0, 2, :, :, :] = t1[x:x+N, y:y+N, z:z+N] high[0, 3, :, :, :] = t1ce[x:x+N, y:y+N, z:z+N] high = Variable(torch.from_numpy(high)).to(self.device).float() pred = torch.nn.functional.softmax(self.Tir3Dnet(high).detach().cpu()) pred = pred.data.numpy() final_prediction[:, x:x+N, y:y+N, z:z+N] = pred[0] final_prediction = convert5class_logitsto_4class(final_prediction) return final_prediction def inner_class_classification_with_logits_DualPath(self, t1, t1ce, t2, flair, brain_mask, mask=None, prediction_size = 9): """ output of BNet3D prediction_size = mid inference patch size """ t1 = normalize(t1, brain_mask) t1ce = normalize(t1ce, brain_mask) t2 = normalize(t2, brain_mask) flair = normalize(flair, brain_mask) shape = t1.shape # to exclude batch_size final_prediction = np.zeros((self.B3Dnclasses, shape[0], shape[1], shape[2])) x_min, x_max, y_min, y_max, z_min, z_max = bbox(mask, pad = prediction_size) # obtained by aspect ratio calculation high_res_size = prediction_size + 16 resize_to = int(prediction_size ** 0.5) + 16 low_res_size = int(51*resize_to/19) hl_pad = (high_res_size - prediction_size)//2 hr_pad = hl_pad + prediction_size ll_pad = (low_res_size - prediction_size)//2 lr_pad = ll_pad + prediction_size for x in tqdm(range(x_min, x_max - prediction_size, prediction_size)): for y in (range(y_min, y_max - prediction_size, prediction_size)): for z in (range(z_min, z_max - prediction_size, prediction_size)): high = np.zeros((1, 4, high_res_size, high_res_size, high_res_size)) low = np.zeros((1, 4, low_res_size, low_res_size, low_res_size)) low1 = np.zeros((1, 4, resize_to, resize_to, resize_to)) high[0, 0], high[0, 1], high[0, 2], high[0, 3] = high[0, 0] + flair[0,0,0], high[0, 1] + t2[0,0,0], high[0, 2] + t1[0,0,0], high[0, 2] + t1ce[0,0,0] low[0, 0], low[0, 1], low[0, 2], low[0, 3] = low[0, 0] + flair[0,0,0], low[0, 1] + t2[0,0,0], low[0, 2] + t1[0,0,0], low[0, 2] + t1ce[0,0,0] low1[0, 0], low1[0, 1], low1[0, 2], low1[0, 3] = low1[0, 0] + flair[0,0,0], low1[0, 1] + t2[0,0,0], low1[0, 2] + t1[0,0,0], low1[0, 2] + t1ce[0,0,0] # ========================================================================= vxf, vxt = max(0, x-hl_pad), min(shape[0], x+hr_pad) vyf, vyt = max(0, y-hl_pad), min(shape[1], y+hr_pad) vzf, vzt = max(0, z-hl_pad), min(shape[2], z+hr_pad) txf, txt = max(0, hl_pad-x), max(0, hl_pad-x) + vxt - vxf tyf, tyt = max(0, hl_pad-y), max(0, hl_pad-y) + vyt - vyf tzf, tzt = max(0, hl_pad-z), max(0, hl_pad-z) + vzt - vzf high[0, 0, txf:txt, tyf:tyt, tzf:tzt] = flair[vxf:vxt, vyf:vyt, vzf:vzt] high[0, 1, txf:txt, tyf:tyt, tzf:tzt] = t2[vxf:vxt, vyf:vyt, vzf:vzt] high[0, 2, txf:txt, tyf:tyt, tzf:tzt] = t1[vxf:vxt, vyf:vyt, vzf:vzt] high[0, 3, txf:txt, tyf:tyt, tzf:tzt] = t1ce[vxf:vxt, vyf:vyt, vzf:vzt] # ========================================================================= vxf, vxt = max(0, x-ll_pad), min(shape[0], x+lr_pad) vyf, vyt = max(0, y-ll_pad), min(shape[1], y+lr_pad) vzf, vzt = max(0, z-ll_pad), min(shape[2], z+lr_pad) txf, txt = max(0, ll_pad-x), max(0, ll_pad-x) + vxt - vxf tyf, tyt = max(0, ll_pad-y), max(0, ll_pad-y) + vyt - vyf tzf, tzt = max(0, ll_pad-z), max(0, ll_pad-z) + vzt - vzf low[0, 0, txf:txt, tyf:tyt, tzf:tzt] = flair[vxf:vxt, vyf:vyt, vzf:vzt] low[0, 1, txf:txt, tyf:tyt, tzf:tzt] = t2[vxf:vxt, vyf:vyt, vzf:vzt] low[0, 2, txf:txt, tyf:tyt, tzf:tzt] = t1[vxf:vxt, vyf:vyt, vzf:vzt] low[0, 3, txf:txt, tyf:tyt, tzf:tzt] = t1ce[vxf:vxt, vyf:vyt, vzf:vzt] # ========================================================================= low1[0] = [resize(low[0, i, :, :, :], (resize_to, resize_to, resize_to)) for i in range(4)] high = Variable(torch.from_numpy(high)).to(self.device).float() low1 = Variable(torch.from_numpy(low1)).to(self.device).float() pred = torch.nn.functional.softmax(self.BNET3Dnet(high, low1, pred_size=prediction_size).detach().cpu()) pred = pred.numpy() final_prediction[:, x:x+prediction_size, y:y+prediction_size, z:z+prediction_size] = pred[0] final_prediction = convert5class_logitsto_4class(final_prediction) return final_prediction def inner_class_classification_with_logits_2D(self, t1ce_volume, t2_volume, flair_volume): """ output of 2D tiramisu model (MNet) """ normalize = transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) transformList = [] transformList.append(transforms.ToTensor()) transformList.append(normalize) transformSequence=transforms.Compose(transformList) generated_output = np.empty((self.Mnclasses,flair_volume.shape[0],flair_volume.shape[1],flair_volume.shape[2])) for slices in tqdm(range(flair_volume.shape[2])): flair_slice = scale_every_slice_between_0_to_255(np.transpose(flair_volume[:,:,slices])) t2_slice = scale_every_slice_between_0_to_255(np.transpose(t2_volume[:,:,slices])) t1ce_slice = scale_every_slice_between_0_to_255(np.transpose(t1ce_volume[:,:,slices])) array = np.zeros((flair_slice.shape[0],flair_slice.shape[1],3)) array[:,:,0] = flair_slice array[:,:,1] = t2_slice array[:,:,2] = t1ce_slice array = np.uint8(array) transformed_array = transformSequence(array) transformed_array = transformed_array.unsqueeze(0) transformed_array = transformed_array.to(self.device) outs = torch.nn.functional.softmax(self.MNET2D(transformed_array).detach().cpu()).numpy() outs = np.swapaxes(generated_output,1, 2) return outs def get_segmentation(self, t1_path, t2_path, t1ce_path, flair_path, save_path = None): """ Generates segmentation for the data not in brats format if save_path provided function saves the prediction with DeepBrainSeg_Prediction.nii.qz name in the provided directory returns: segmentation mask """ t1 = nib.load(t1_path).get_data() t2 = nib.load(t2_path).get_data() t1ce = nib.load(t1ce_path).get_data() flair = nib.load(flair_path).get_data() affine = nib.load(flair_path).affine brain_mask = self.get_ants_mask(t2_path) mask = self.get_localization(t1, t1ce, t2, flair, brain_mask) # mask = np.swapaxes(mask,1, 0) if not self.quick: final_predictionTir3D_logits = self.inner_class_classification_with_logits_NCube(t1, t1ce, t2, flair, brain_mask, mask) final_predictionBNET3D_logits = self.inner_class_classification_with_logits_DualPath(t1, t1ce, t2, flair, brain_mask, mask) final_predictionMnet_logits = self.inner_class_classification_with_logits_2D(t1, t2, flair).transpose(0, 2, 1, 3) final_prediction_array = np.array([final_predictionTir3D_logits, final_predictionBNET3D_logits, final_predictionMnet_logits]) else: final_predictionMnet_logits = self.inner_class_classification_with_logits_2D(t1, t2, flair) final_prediction_array = np.array([final_predictionMnet_logits]) final_prediction_logits = combine_logits_AM(final_prediction_array) final_pred = postprocessing_pydensecrf(final_prediction_logits) final_pred = combine_mask_prediction(mask, final_pred) final_pred = perform_postprocessing(final_pred) final_pred = adjust_classes(final_pred) if save_path: os.makedirs(save_path, exist_ok=True) save_volume(final_pred, affine, os.path.join(save_path, 'DeepBrainSeg_Prediction')) return final_pred def get_segmentation_brats(self, path, save = True): """ Generates segmentation for the data in BraTs format if save True saves the prediction in the save directory in the patients data path returns : segmentation mask """ name = path.split("/")[-1] + "_" flair = nib.load(os.path.join(path, name + 'flair.nii.gz')).get_data() t1 = nib.load(os.path.join(path, name + 't1.nii.gz')).get_data() t1ce = nib.load(os.path.join(path, name + 't1ce.nii.gz')).get_data() t2 = nib.load(os.path.join(path, name + 't2.nii.gz')).get_data() affine= nib.load(os.path.join(path, name + 'flair.nii.gz')).affine print ("[INFO: DeepBrainSeg] (" + strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime()) + ") Working on: ", path) brain_mask = self.get_ants_mask(os.path.join(path, name + 't2.nii.gz')) # brain_mask = get_brain_mask(t1) mask = self.get_localization(t1, t1ce, t2, flair, brain_mask) mask = np.swapaxes(mask,1, 0) if not self.quick: final_predictionTir3D_logits = self.inner_class_classification_with_logits_NCube(t1, t1ce, t2, flair, brain_mask, mask) final_predictionBNET3D_logits = self.inner_class_classification_with_logits_DualPath(t1, t1ce, t2, flair, brain_mask, mask) final_predictionMnet_logits = self.inner_class_classification_with_logits_2D(t1, t2, flair) final_prediction_array = np.array([final_predictionTir3D_logits, final_predictionBNET3D_logits, final_predictionMnet_logits]) else: final_predictionMnet_logits = self.inner_class_classification_with_logits_2D(t1, t2, flair) final_prediction_array = np.array([final_predictionMnet_logits]) final_prediction_logits = combine_logits_AM(final_prediction_array) final_pred = postprocessing_pydensecrf(final_prediction_logits) final_pred = combine_mask_prediction(mask, final_pred) final_pred = perform_postprocessing(final_pred) final_pred = adjust_classes(final_pred) if save: save_volume(final_pred, affine, os.path.join(path, 'DeepBrainSeg_Prediction')) return final_pred # ======================================================================================== if __name__ == '__main__': ext = deepSeg(True) ext.get_segmentation_brats('../../sample_volume/Brats18_CBICA_AVG_1/')
[ "numpy.uint8", "nibabel.load", "torch.from_numpy", "numpy.array", "torch.cuda.is_available", "numpy.empty", "os.system", "torchvision.transforms.ToTensor", "os.path.expanduser", "os.path.dirname", "torchvision.transforms.Normalize", "skimage.transform.resize", "numpy.transpose", "torchvision.transforms.Compose", "time.gmtime", "os.makedirs", "torch.load", "os.path.join", "numpy.swapaxes", "numpy.zeros", "torch.no_grad" ]
[((422, 437), 'os.path.expanduser', 'expanduser', (['"""~"""'], {}), "('~')\n", (432, 437), False, 'from os.path import expanduser\n'), ((584, 614), 'os.path.join', 'os.path.join', (['"""/opt/ANTs/bin/"""'], {}), "('/opt/ANTs/bin/')\n", (596, 614), False, 'import os\n'), ((2026, 2111), 'os.path.join', 'os.path.join', (['home', '""".DeepBrainSeg/BestModels/Tramisu_2D_FC57_best_loss.pth.tar"""'], {}), "(home, '.DeepBrainSeg/BestModels/Tramisu_2D_FC57_best_loss.pth.tar'\n )\n", (2038, 2111), False, 'import os\n'), ((2131, 2210), 'os.path.join', 'os.path.join', (['home', '""".DeepBrainSeg/BestModels/Tramisu_3D_FC57_best_acc.pth.tar"""'], {}), "(home, '.DeepBrainSeg/BestModels/Tramisu_3D_FC57_best_acc.pth.tar')\n", (2143, 2210), False, 'import os\n'), ((2235, 2310), 'os.path.join', 'os.path.join', (['home', '""".DeepBrainSeg/BestModels/BrainNet_3D_best_acc.pth.tar"""'], {}), "(home, '.DeepBrainSeg/BestModels/BrainNet_3D_best_acc.pth.tar')\n", (2247, 2310), False, 'import os\n'), ((2335, 2422), 'os.path.join', 'os.path.join', (['home', '""".DeepBrainSeg/BestModels/ABL_CE_best_model_loss_based.pth.tar"""'], {}), "(home,\n '.DeepBrainSeg/BestModels/ABL_CE_best_model_loss_based.pth.tar')\n", (2347, 2422), False, 'import os\n'), ((2762, 2809), 'torch.load', 'torch.load', (['ckpt_ABL'], {'map_location': 'map_location'}), '(ckpt_ABL, map_location=map_location)\n', (2772, 2809), False, 'import torch\n'), ((3376, 3425), 'torch.load', 'torch.load', (['ckpt_tir2D'], {'map_location': 'map_location'}), '(ckpt_tir2D, map_location=map_location)\n', (3386, 3425), False, 'import torch\n'), ((5487, 5572), 'os.system', 'os.system', (["(self.ants_path + 'ImageMath 3 ' + mask_path + ' Normalize ' + t1_path)"], {}), "(self.ants_path + 'ImageMath 3 ' + mask_path + ' Normalize ' + t1_path\n )\n", (5496, 5572), False, 'import os\n'), ((5572, 5665), 'os.system', 'os.system', (["(self.ants_path + 'ThresholdImage 3 ' + mask_path + ' ' + mask_path + ' 0.01 1'\n )"], {}), "(self.ants_path + 'ThresholdImage 3 ' + mask_path + ' ' +\n mask_path + ' 0.01 1')\n", (5581, 5665), False, 'import os\n'), ((5665, 5751), 'os.system', 'os.system', (["(self.ants_path + 'ImageMath 3 ' + mask_path + ' MD ' + mask_path + ' 1')"], {}), "(self.ants_path + 'ImageMath 3 ' + mask_path + ' MD ' + mask_path +\n ' 1')\n", (5674, 5751), False, 'import os\n'), ((5751, 5837), 'os.system', 'os.system', (["(self.ants_path + 'ImageMath 3 ' + mask_path + ' ME ' + mask_path + ' 1')"], {}), "(self.ants_path + 'ImageMath 3 ' + mask_path + ' ME ' + mask_path +\n ' 1')\n", (5760, 5837), False, 'import os\n'), ((5837, 5955), 'os.system', 'os.system', (["(self.ants_path + 'CopyImageHeaderInformation ' + t1_path + ' ' + mask_path +\n ' ' + mask_path + ' 1 1 1')"], {}), "(self.ants_path + 'CopyImageHeaderInformation ' + t1_path + ' ' +\n mask_path + ' ' + mask_path + ' 1 1 1')\n", (5846, 5955), False, 'import os\n'), ((6645, 6732), 'numpy.empty', 'np.empty', (['(self.ABLnclasses, flair_v.shape[0], flair_v.shape[1], flair_v.shape[2])'], {}), '((self.ABLnclasses, flair_v.shape[0], flair_v.shape[1], flair_v.\n shape[2]))\n', (6653, 6732), True, 'import numpy as np\n'), ((7937, 7957), 'numpy.uint8', 'np.uint8', (['final_pred'], {}), '(final_pred)\n', (7945, 7957), True, 'import numpy as np\n'), ((8571, 8629), 'numpy.zeros', 'np.zeros', (['(self.T3Dnclasses, shape[0], shape[1], shape[2])'], {}), '((self.T3Dnclasses, shape[0], shape[1], shape[2]))\n', (8579, 8629), True, 'import numpy as np\n'), ((10468, 10526), 'numpy.zeros', 'np.zeros', (['(self.B3Dnclasses, shape[0], shape[1], shape[2])'], {}), '((self.B3Dnclasses, shape[0], shape[1], shape[2]))\n', (10476, 10526), True, 'import numpy as np\n'), ((14979, 15045), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['[0.485, 0.456, 0.406]', '[0.229, 0.224, 0.225]'], {}), '([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n', (14999, 15045), False, 'from torchvision import transforms\n'), ((15191, 15224), 'torchvision.transforms.Compose', 'transforms.Compose', (['transformList'], {}), '(transformList)\n', (15209, 15224), False, 'from torchvision import transforms\n'), ((15253, 15352), 'numpy.empty', 'np.empty', (['(self.Mnclasses, flair_volume.shape[0], flair_volume.shape[1], flair_volume\n .shape[2])'], {}), '((self.Mnclasses, flair_volume.shape[0], flair_volume.shape[1],\n flair_volume.shape[2]))\n', (15261, 15352), True, 'import numpy as np\n'), ((19604, 19627), 'numpy.swapaxes', 'np.swapaxes', (['mask', '(1)', '(0)'], {}), '(mask, 1, 0)\n', (19615, 19627), True, 'import numpy as np\n'), ((4017, 4067), 'torch.load', 'torch.load', (['ckpt_BNET3D'], {'map_location': 'map_location'}), '(ckpt_BNET3D, map_location=map_location)\n', (4027, 4067), False, 'import torch\n'), ((4644, 4693), 'torch.load', 'torch.load', (['ckpt_tir3D'], {'map_location': 'map_location'}), '(ckpt_tir3D, map_location=map_location)\n', (4654, 4693), False, 'import torch\n'), ((5438, 5462), 'os.path.dirname', 'os.path.dirname', (['t1_path'], {}), '(t1_path)\n', (5453, 5462), False, 'import os\n'), ((6806, 6841), 'numpy.transpose', 'np.transpose', (['flair_v[:, :, slices]'], {}), '(flair_v[:, :, slices])\n', (6818, 6841), True, 'import numpy as np\n'), ((6866, 6898), 'numpy.transpose', 'np.transpose', (['t2_v[:, :, slices]'], {}), '(t2_v[:, :, slices])\n', (6878, 6898), True, 'import numpy as np\n'), ((6923, 6956), 'numpy.transpose', 'np.transpose', (['t1c_v[:, :, slices]'], {}), '(t1c_v[:, :, slices])\n', (6935, 6956), True, 'import numpy as np\n'), ((6981, 7013), 'numpy.transpose', 'np.transpose', (['t1_v[:, :, slices]'], {}), '(t1_v[:, :, slices])\n', (6993, 7013), True, 'import numpy as np\n'), ((7068, 7125), 'numpy.zeros', 'np.zeros', (['(flair_slice.shape[0], flair_slice.shape[1], 4)'], {}), '((flair_slice.shape[0], flair_slice.shape[1], 4))\n', (7076, 7125), True, 'import numpy as np\n'), ((7899, 7919), 'numpy.uint8', 'np.uint8', (['final_pred'], {}), '(final_pred)\n', (7907, 7919), True, 'import numpy as np\n'), ((8872, 8887), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (8885, 8887), False, 'import torch\n'), ((15102, 15123), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (15121, 15123), False, 'from torchvision import transforms\n'), ((15731, 15788), 'numpy.zeros', 'np.zeros', (['(flair_slice.shape[0], flair_slice.shape[1], 3)'], {}), '((flair_slice.shape[0], flair_slice.shape[1], 3))\n', (15739, 15788), True, 'import numpy as np\n'), ((15920, 15935), 'numpy.uint8', 'np.uint8', (['array'], {}), '(array)\n', (15928, 15935), True, 'import numpy as np\n'), ((16243, 16278), 'numpy.swapaxes', 'np.swapaxes', (['generated_output', '(1)', '(2)'], {}), '(generated_output, 1, 2)\n', (16254, 16278), True, 'import numpy as np\n'), ((16956, 16976), 'nibabel.load', 'nib.load', (['flair_path'], {}), '(flair_path)\n', (16964, 16976), True, 'import nibabel as nib\n'), ((17629, 17733), 'numpy.array', 'np.array', (['[final_predictionTir3D_logits, final_predictionBNET3D_logits,\n final_predictionMnet_logits]'], {}), '([final_predictionTir3D_logits, final_predictionBNET3D_logits,\n final_predictionMnet_logits])\n', (17637, 17733), True, 'import numpy as np\n'), ((17893, 17932), 'numpy.array', 'np.array', (['[final_predictionMnet_logits]'], {}), '([final_predictionMnet_logits])\n', (17901, 17932), True, 'import numpy as np\n'), ((18336, 18373), 'os.makedirs', 'os.makedirs', (['save_path'], {'exist_ok': '(True)'}), '(save_path, exist_ok=True)\n', (18347, 18373), False, 'import os\n'), ((19423, 19461), 'os.path.join', 'os.path.join', (['path', "(name + 't2.nii.gz')"], {}), "(path, name + 't2.nii.gz')\n", (19435, 19461), False, 'import os\n'), ((20074, 20178), 'numpy.array', 'np.array', (['[final_predictionTir3D_logits, final_predictionBNET3D_logits,\n final_predictionMnet_logits]'], {}), '([final_predictionTir3D_logits, final_predictionBNET3D_logits,\n final_predictionMnet_logits])\n', (20082, 20178), True, 'import numpy as np\n'), ((20338, 20377), 'numpy.array', 'np.array', (['[final_predictionMnet_logits]'], {}), '([final_predictionMnet_logits])\n', (20346, 20377), True, 'import numpy as np\n'), ((1809, 1834), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (1832, 1834), False, 'import torch\n'), ((15465, 15505), 'numpy.transpose', 'np.transpose', (['flair_volume[:, :, slices]'], {}), '(flair_volume[:, :, slices])\n', (15477, 15505), True, 'import numpy as np\n'), ((15566, 15603), 'numpy.transpose', 'np.transpose', (['t2_volume[:, :, slices]'], {}), '(t2_volume[:, :, slices])\n', (15578, 15603), True, 'import numpy as np\n'), ((15664, 15703), 'numpy.transpose', 'np.transpose', (['t1ce_volume[:, :, slices]'], {}), '(t1ce_volume[:, :, slices])\n', (15676, 15703), True, 'import numpy as np\n'), ((16774, 16791), 'nibabel.load', 'nib.load', (['t1_path'], {}), '(t1_path)\n', (16782, 16791), True, 'import nibabel as nib\n'), ((16816, 16833), 'nibabel.load', 'nib.load', (['t2_path'], {}), '(t2_path)\n', (16824, 16833), True, 'import nibabel as nib\n'), ((16860, 16879), 'nibabel.load', 'nib.load', (['t1ce_path'], {}), '(t1ce_path)\n', (16868, 16879), True, 'import nibabel as nib\n'), ((16907, 16927), 'nibabel.load', 'nib.load', (['flair_path'], {}), '(flair_path)\n', (16915, 16927), True, 'import nibabel as nib\n'), ((18418, 18468), 'os.path.join', 'os.path.join', (['save_path', '"""DeepBrainSeg_Prediction"""'], {}), "(save_path, 'DeepBrainSeg_Prediction')\n", (18430, 18468), False, 'import os\n'), ((19204, 19245), 'os.path.join', 'os.path.join', (['path', "(name + 'flair.nii.gz')"], {}), "(path, name + 'flair.nii.gz')\n", (19216, 19245), False, 'import os\n'), ((20807, 20852), 'os.path.join', 'os.path.join', (['path', '"""DeepBrainSeg_Prediction"""'], {}), "(path, 'DeepBrainSeg_Prediction')\n", (20819, 20852), False, 'import os\n'), ((5968, 5987), 'nibabel.load', 'nib.load', (['mask_path'], {}), '(mask_path)\n', (5976, 5987), True, 'import nibabel as nib\n'), ((11280, 11341), 'numpy.zeros', 'np.zeros', (['(1, 4, high_res_size, high_res_size, high_res_size)'], {}), '((1, 4, high_res_size, high_res_size, high_res_size))\n', (11288, 11341), True, 'import numpy as np\n'), ((11369, 11427), 'numpy.zeros', 'np.zeros', (['(1, 4, low_res_size, low_res_size, low_res_size)'], {}), '((1, 4, low_res_size, low_res_size, low_res_size))\n', (11377, 11427), True, 'import numpy as np\n'), ((11456, 11505), 'numpy.zeros', 'np.zeros', (['(1, 4, resize_to, resize_to, resize_to)'], {}), '((1, 4, resize_to, resize_to, resize_to))\n', (11464, 11505), True, 'import numpy as np\n'), ((18891, 18932), 'os.path.join', 'os.path.join', (['path', "(name + 'flair.nii.gz')"], {}), "(path, name + 'flair.nii.gz')\n", (18903, 18932), False, 'import os\n'), ((18971, 19009), 'os.path.join', 'os.path.join', (['path', "(name + 't1.nii.gz')"], {}), "(path, name + 't1.nii.gz')\n", (18983, 19009), False, 'import os\n'), ((19048, 19088), 'os.path.join', 'os.path.join', (['path', "(name + 't1ce.nii.gz')"], {}), "(path, name + 't1ce.nii.gz')\n", (19060, 19088), False, 'import os\n'), ((19127, 19165), 'os.path.join', 'os.path.join', (['path', "(name + 't2.nii.gz')"], {}), "(path, name + 't2.nii.gz')\n", (19139, 19165), False, 'import os\n'), ((9082, 9107), 'numpy.zeros', 'np.zeros', (['(1, 4, N, N, N)'], {}), '((1, 4, N, N, N))\n', (9090, 9107), True, 'import numpy as np\n'), ((13995, 14056), 'skimage.transform.resize', 'resize', (['low[0, i, :, :, :]', '(resize_to, resize_to, resize_to)'], {}), '(low[0, i, :, :, :], (resize_to, resize_to, resize_to))\n', (14001, 14056), False, 'from skimage.transform import resize\n'), ((19345, 19353), 'time.gmtime', 'gmtime', ([], {}), '()\n', (19351, 19353), False, 'from time import gmtime, strftime\n'), ((14113, 14135), 'torch.from_numpy', 'torch.from_numpy', (['high'], {}), '(high)\n', (14129, 14135), False, 'import torch\n'), ((14198, 14220), 'torch.from_numpy', 'torch.from_numpy', (['low1'], {}), '(low1)\n', (14214, 14220), False, 'import torch\n'), ((9435, 9457), 'torch.from_numpy', 'torch.from_numpy', (['high'], {}), '(high)\n', (9451, 9457), False, 'import torch\n')]
import numpy as np from statsmodels.discrete.conditional_models import ( ConditionalLogit, ConditionalPoisson) from statsmodels.tools.numdiff import approx_fprime from numpy.testing import assert_allclose import pandas as pd def test_logit_1d(): y = np.r_[0, 1, 0, 1, 0, 1, 0, 1, 1, 1] g = np.r_[0, 0, 0, 1, 1, 1, 2, 2, 2, 2] x = np.r_[0, 1, 0, 0, 1, 1, 0, 0, 1, 0] x = x[:, None] model = ConditionalLogit(y, x, groups=g) # Check the gradient for the denominator of the partial likelihood for x in -1, 0, 1, 2: params = np.r_[x, ] _, grad = model._denom_grad(0, params) ngrad = approx_fprime(params, lambda x: model._denom(0, x)) assert_allclose(grad, ngrad) # Check the gradient for the loglikelihood for x in -1, 0, 1, 2: grad = approx_fprime(np.r_[x, ], model.loglike) score = model.score(np.r_[x, ]) assert_allclose(grad, score, rtol=1e-4) result = model.fit() # From Stata assert_allclose(result.params, np.r_[0.9272407], rtol=1e-5) assert_allclose(result.bse, np.r_[1.295155], rtol=1e-5) def test_logit_2d(): y = np.r_[0, 1, 0, 1, 0, 1, 0, 1, 1, 1] g = np.r_[0, 0, 0, 1, 1, 1, 2, 2, 2, 2] x1 = np.r_[0, 1, 0, 0, 1, 1, 0, 0, 1, 0] x2 = np.r_[0, 0, 1, 0, 0, 1, 0, 1, 1, 1] x = np.empty((10, 2)) x[:, 0] = x1 x[:, 1] = x2 model = ConditionalLogit(y, x, groups=g) # Check the gradient for the denominator of the partial likelihood for x in -1, 0, 1, 2: params = np.r_[x, -1.5*x] _, grad = model._denom_grad(0, params) ngrad = approx_fprime(params, lambda x: model._denom(0, x)) assert_allclose(grad, ngrad, rtol=1e-5) # Check the gradient for the loglikelihood for x in -1, 0, 1, 2: params = np.r_[-0.5*x, 0.5*x] grad = approx_fprime(params, model.loglike) score = model.score(params) assert_allclose(grad, score, rtol=1e-4) result = model.fit() # From Stata assert_allclose(result.params, np.r_[1.011074, 1.236758], rtol=1e-3) assert_allclose(result.bse, np.r_[1.420784, 1.361738], rtol=1e-5) result.summary() def test_formula(): for j in 0, 1: np.random.seed(34234) n = 200 y = np.random.randint(0, 2, size=n) x1 = np.random.normal(size=n) x2 = np.random.normal(size=n) g = np.random.randint(0, 25, size=n) x = np.hstack((x1[:, None], x2[:, None])) if j == 0: model1 = ConditionalLogit(y, x, groups=g) else: model1 = ConditionalPoisson(y, x, groups=g) result1 = model1.fit() df = pd.DataFrame({"y": y, "x1": x1, "x2": x2, "g": g}) if j == 0: model2 = ConditionalLogit.from_formula( "y ~ 0 + x1 + x2", groups="g", data=df) else: model2 = ConditionalPoisson.from_formula( "y ~ 0 + x1 + x2", groups="g", data=df) result2 = model2.fit() assert_allclose(result1.params, result2.params, rtol=1e-5) assert_allclose(result1.bse, result2.bse, rtol=1e-5) assert_allclose(result1.cov_params(), result2.cov_params(), rtol=1e-5) assert_allclose(result1.tvalues, result2.tvalues, rtol=1e-5) def test_poisson_1d(): y = np.r_[3, 1, 1, 4, 5, 2, 0, 1, 6, 2] g = np.r_[0, 0, 0, 0, 1, 1, 1, 1, 1, 1] x = np.r_[0, 1, 0, 0, 1, 1, 0, 0, 1, 0] x = x[:, None] model = ConditionalPoisson(y, x, groups=g) # Check the gradient for the loglikelihood for x in -1, 0, 1, 2: grad = approx_fprime(np.r_[x, ], model.loglike) score = model.score(np.r_[x, ]) assert_allclose(grad, score, rtol=1e-4) result = model.fit() # From Stata assert_allclose(result.params, np.r_[0.6466272], rtol=1e-4) assert_allclose(result.bse, np.r_[0.4170918], rtol=1e-5) def test_poisson_2d(): y = np.r_[3, 1, 4, 8, 2, 5, 4, 7, 2, 6] g = np.r_[0, 0, 0, 1, 1, 1, 2, 2, 2, 2] x1 = np.r_[0, 1, 0, 0, 1, 1, 0, 0, 1, 0] x2 = np.r_[2, 1, 0, 0, 1, 2, 3, 2, 0, 1] x = np.empty((10, 2)) x[:, 0] = x1 x[:, 1] = x2 model = ConditionalPoisson(y, x, groups=g) # Check the gradient for the loglikelihood for x in -1, 0, 1, 2: params = np.r_[-0.5*x, 0.5*x] grad = approx_fprime(params, model.loglike) score = model.score(params) assert_allclose(grad, score, rtol=1e-4) result = model.fit() # From Stata assert_allclose(result.params, np.r_[-.9478957, -.0134279], rtol=1e-3) assert_allclose(result.bse, np.r_[.3874942, .1686712], rtol=1e-5) result.summary() def test_lasso_logistic(): np.random.seed(3423948) n = 200 groups = np.arange(10) groups = np.kron(groups, np.ones(n // 10)) group_effects = np.random.normal(size=10) group_effects = np.kron(group_effects, np.ones(n // 10)) x = np.random.normal(size=(n, 4)) params = np.r_[0, 0, 1, 0] lin_pred = np.dot(x, params) + group_effects mean = 1 / (1 + np.exp(-lin_pred)) y = (np.random.uniform(size=n) < mean).astype(np.int) model0 = ConditionalLogit(y, x, groups=groups) result0 = model0.fit() # Should be the same as model0 model1 = ConditionalLogit(y, x, groups=groups) result1 = model1.fit_regularized(L1_wt=0, alpha=0) assert_allclose(result0.params, result1.params, rtol=1e-3) model2 = ConditionalLogit(y, x, groups=groups) result2 = model2.fit_regularized(L1_wt=1, alpha=0.05) # Rxegression test assert_allclose(result2.params, np.r_[0, 0, 0.55235152, 0], rtol=1e-4) # Test with formula df = pd.DataFrame({"y": y, "x1": x[:, 0], "x2": x[:, 1], "x3": x[:, 2], "x4": x[:, 3], "groups": groups}) fml = "y ~ 0 + x1 + x2 + x3 + x4" model3 = ConditionalLogit.from_formula(fml, groups="groups", data=df) result3 = model3.fit_regularized(L1_wt=1, alpha=0.05) assert_allclose(result2.params, result3.params) def test_lasso_poisson(): np.random.seed(342394) n = 200 groups = np.arange(10) groups = np.kron(groups, np.ones(n // 10)) group_effects = np.random.normal(size=10) group_effects = np.kron(group_effects, np.ones(n // 10)) x = np.random.normal(size=(n, 4)) params = np.r_[0, 0, 1, 0] lin_pred = np.dot(x, params) + group_effects mean = np.exp(lin_pred) y = np.random.poisson(mean) model0 = ConditionalPoisson(y, x, groups=groups) result0 = model0.fit() # Should be the same as model0 model1 = ConditionalPoisson(y, x, groups=groups) result1 = model1.fit_regularized(L1_wt=0, alpha=0) assert_allclose(result0.params, result1.params, rtol=1e-3) model2 = ConditionalPoisson(y, x, groups=groups) result2 = model2.fit_regularized(L1_wt=1, alpha=0.2) # Regression test assert_allclose(result2.params, np.r_[0, 0, 0.91697508, 0], rtol=1e-4) # Test with formula df = pd.DataFrame({"y": y, "x1": x[:, 0], "x2": x[:, 1], "x3": x[:, 2], "x4": x[:, 3], "groups": groups}) fml = "y ~ 0 + x1 + x2 + x3 + x4" model3 = ConditionalPoisson.from_formula(fml, groups="groups", data=df) result3 = model3.fit_regularized(L1_wt=1, alpha=0.2) assert_allclose(result2.params, result3.params)
[ "numpy.random.normal", "statsmodels.discrete.conditional_models.ConditionalLogit", "numpy.ones", "numpy.random.poisson", "numpy.hstack", "numpy.testing.assert_allclose", "statsmodels.discrete.conditional_models.ConditionalPoisson", "statsmodels.discrete.conditional_models.ConditionalPoisson.from_formula", "numpy.exp", "numpy.random.randint", "numpy.dot", "numpy.empty", "numpy.random.seed", "statsmodels.tools.numdiff.approx_fprime", "numpy.random.uniform", "pandas.DataFrame", "statsmodels.discrete.conditional_models.ConditionalLogit.from_formula", "numpy.arange" ]
[((420, 452), 'statsmodels.discrete.conditional_models.ConditionalLogit', 'ConditionalLogit', (['y', 'x'], {'groups': 'g'}), '(y, x, groups=g)\n', (436, 452), False, 'from statsmodels.discrete.conditional_models import ConditionalLogit, ConditionalPoisson\n'), ((997, 1057), 'numpy.testing.assert_allclose', 'assert_allclose', (['result.params', 'np.r_[0.9272407]'], {'rtol': '(1e-05)'}), '(result.params, np.r_[0.9272407], rtol=1e-05)\n', (1012, 1057), False, 'from numpy.testing import assert_allclose\n'), ((1061, 1117), 'numpy.testing.assert_allclose', 'assert_allclose', (['result.bse', 'np.r_[1.295155]'], {'rtol': '(1e-05)'}), '(result.bse, np.r_[1.295155], rtol=1e-05)\n', (1076, 1117), False, 'from numpy.testing import assert_allclose\n'), ((1328, 1345), 'numpy.empty', 'np.empty', (['(10, 2)'], {}), '((10, 2))\n', (1336, 1345), True, 'import numpy as np\n'), ((1393, 1425), 'statsmodels.discrete.conditional_models.ConditionalLogit', 'ConditionalLogit', (['y', 'x'], {'groups': 'g'}), '(y, x, groups=g)\n', (1409, 1425), False, 'from statsmodels.discrete.conditional_models import ConditionalLogit, ConditionalPoisson\n'), ((2017, 2086), 'numpy.testing.assert_allclose', 'assert_allclose', (['result.params', 'np.r_[1.011074, 1.236758]'], {'rtol': '(0.001)'}), '(result.params, np.r_[1.011074, 1.236758], rtol=0.001)\n', (2032, 2086), False, 'from numpy.testing import assert_allclose\n'), ((2090, 2156), 'numpy.testing.assert_allclose', 'assert_allclose', (['result.bse', 'np.r_[1.420784, 1.361738]'], {'rtol': '(1e-05)'}), '(result.bse, np.r_[1.420784, 1.361738], rtol=1e-05)\n', (2105, 2156), False, 'from numpy.testing import assert_allclose\n'), ((3488, 3522), 'statsmodels.discrete.conditional_models.ConditionalPoisson', 'ConditionalPoisson', (['y', 'x'], {'groups': 'g'}), '(y, x, groups=g)\n', (3506, 3522), False, 'from statsmodels.discrete.conditional_models import ConditionalLogit, ConditionalPoisson\n'), ((3789, 3850), 'numpy.testing.assert_allclose', 'assert_allclose', (['result.params', 'np.r_[0.6466272]'], {'rtol': '(0.0001)'}), '(result.params, np.r_[0.6466272], rtol=0.0001)\n', (3804, 3850), False, 'from numpy.testing import assert_allclose\n'), ((3853, 3910), 'numpy.testing.assert_allclose', 'assert_allclose', (['result.bse', 'np.r_[0.4170918]'], {'rtol': '(1e-05)'}), '(result.bse, np.r_[0.4170918], rtol=1e-05)\n', (3868, 3910), False, 'from numpy.testing import assert_allclose\n'), ((4123, 4140), 'numpy.empty', 'np.empty', (['(10, 2)'], {}), '((10, 2))\n', (4131, 4140), True, 'import numpy as np\n'), ((4188, 4222), 'statsmodels.discrete.conditional_models.ConditionalPoisson', 'ConditionalPoisson', (['y', 'x'], {'groups': 'g'}), '(y, x, groups=g)\n', (4206, 4222), False, 'from statsmodels.discrete.conditional_models import ConditionalLogit, ConditionalPoisson\n'), ((4519, 4592), 'numpy.testing.assert_allclose', 'assert_allclose', (['result.params', 'np.r_[-0.9478957, -0.0134279]'], {'rtol': '(0.001)'}), '(result.params, np.r_[-0.9478957, -0.0134279], rtol=0.001)\n', (4534, 4592), False, 'from numpy.testing import assert_allclose\n'), ((4594, 4662), 'numpy.testing.assert_allclose', 'assert_allclose', (['result.bse', 'np.r_[0.3874942, 0.1686712]'], {'rtol': '(1e-05)'}), '(result.bse, np.r_[0.3874942, 0.1686712], rtol=1e-05)\n', (4609, 4662), False, 'from numpy.testing import assert_allclose\n'), ((4716, 4739), 'numpy.random.seed', 'np.random.seed', (['(3423948)'], {}), '(3423948)\n', (4730, 4739), True, 'import numpy as np\n'), ((4766, 4779), 'numpy.arange', 'np.arange', (['(10)'], {}), '(10)\n', (4775, 4779), True, 'import numpy as np\n'), ((4847, 4872), 'numpy.random.normal', 'np.random.normal', ([], {'size': '(10)'}), '(size=10)\n', (4863, 4872), True, 'import numpy as np\n'), ((4943, 4972), 'numpy.random.normal', 'np.random.normal', ([], {'size': '(n, 4)'}), '(size=(n, 4))\n', (4959, 4972), True, 'import numpy as np\n'), ((5165, 5202), 'statsmodels.discrete.conditional_models.ConditionalLogit', 'ConditionalLogit', (['y', 'x'], {'groups': 'groups'}), '(y, x, groups=groups)\n', (5181, 5202), False, 'from statsmodels.discrete.conditional_models import ConditionalLogit, ConditionalPoisson\n'), ((5279, 5316), 'statsmodels.discrete.conditional_models.ConditionalLogit', 'ConditionalLogit', (['y', 'x'], {'groups': 'groups'}), '(y, x, groups=groups)\n', (5295, 5316), False, 'from statsmodels.discrete.conditional_models import ConditionalLogit, ConditionalPoisson\n'), ((5377, 5436), 'numpy.testing.assert_allclose', 'assert_allclose', (['result0.params', 'result1.params'], {'rtol': '(0.001)'}), '(result0.params, result1.params, rtol=0.001)\n', (5392, 5436), False, 'from numpy.testing import assert_allclose\n'), ((5450, 5487), 'statsmodels.discrete.conditional_models.ConditionalLogit', 'ConditionalLogit', (['y', 'x'], {'groups': 'groups'}), '(y, x, groups=groups)\n', (5466, 5487), False, 'from statsmodels.discrete.conditional_models import ConditionalLogit, ConditionalPoisson\n'), ((5574, 5646), 'numpy.testing.assert_allclose', 'assert_allclose', (['result2.params', 'np.r_[0, 0, 0.55235152, 0]'], {'rtol': '(0.0001)'}), '(result2.params, np.r_[0, 0, 0.55235152, 0], rtol=0.0001)\n', (5589, 5646), False, 'from numpy.testing import assert_allclose\n'), ((5679, 5784), 'pandas.DataFrame', 'pd.DataFrame', (["{'y': y, 'x1': x[:, 0], 'x2': x[:, 1], 'x3': x[:, 2], 'x4': x[:, 3],\n 'groups': groups}"], {}), "({'y': y, 'x1': x[:, 0], 'x2': x[:, 1], 'x3': x[:, 2], 'x4': x[\n :, 3], 'groups': groups})\n", (5691, 5784), True, 'import pandas as pd\n'), ((5854, 5914), 'statsmodels.discrete.conditional_models.ConditionalLogit.from_formula', 'ConditionalLogit.from_formula', (['fml'], {'groups': '"""groups"""', 'data': 'df'}), "(fml, groups='groups', data=df)\n", (5883, 5914), False, 'from statsmodels.discrete.conditional_models import ConditionalLogit, ConditionalPoisson\n'), ((5977, 6024), 'numpy.testing.assert_allclose', 'assert_allclose', (['result2.params', 'result3.params'], {}), '(result2.params, result3.params)\n', (5992, 6024), False, 'from numpy.testing import assert_allclose\n'), ((6058, 6080), 'numpy.random.seed', 'np.random.seed', (['(342394)'], {}), '(342394)\n', (6072, 6080), True, 'import numpy as np\n'), ((6107, 6120), 'numpy.arange', 'np.arange', (['(10)'], {}), '(10)\n', (6116, 6120), True, 'import numpy as np\n'), ((6188, 6213), 'numpy.random.normal', 'np.random.normal', ([], {'size': '(10)'}), '(size=10)\n', (6204, 6213), True, 'import numpy as np\n'), ((6284, 6313), 'numpy.random.normal', 'np.random.normal', ([], {'size': '(n, 4)'}), '(size=(n, 4))\n', (6300, 6313), True, 'import numpy as np\n'), ((6406, 6422), 'numpy.exp', 'np.exp', (['lin_pred'], {}), '(lin_pred)\n', (6412, 6422), True, 'import numpy as np\n'), ((6431, 6454), 'numpy.random.poisson', 'np.random.poisson', (['mean'], {}), '(mean)\n', (6448, 6454), True, 'import numpy as np\n'), ((6469, 6508), 'statsmodels.discrete.conditional_models.ConditionalPoisson', 'ConditionalPoisson', (['y', 'x'], {'groups': 'groups'}), '(y, x, groups=groups)\n', (6487, 6508), False, 'from statsmodels.discrete.conditional_models import ConditionalLogit, ConditionalPoisson\n'), ((6585, 6624), 'statsmodels.discrete.conditional_models.ConditionalPoisson', 'ConditionalPoisson', (['y', 'x'], {'groups': 'groups'}), '(y, x, groups=groups)\n', (6603, 6624), False, 'from statsmodels.discrete.conditional_models import ConditionalLogit, ConditionalPoisson\n'), ((6685, 6744), 'numpy.testing.assert_allclose', 'assert_allclose', (['result0.params', 'result1.params'], {'rtol': '(0.001)'}), '(result0.params, result1.params, rtol=0.001)\n', (6700, 6744), False, 'from numpy.testing import assert_allclose\n'), ((6758, 6797), 'statsmodels.discrete.conditional_models.ConditionalPoisson', 'ConditionalPoisson', (['y', 'x'], {'groups': 'groups'}), '(y, x, groups=groups)\n', (6776, 6797), False, 'from statsmodels.discrete.conditional_models import ConditionalLogit, ConditionalPoisson\n'), ((6882, 6954), 'numpy.testing.assert_allclose', 'assert_allclose', (['result2.params', 'np.r_[0, 0, 0.91697508, 0]'], {'rtol': '(0.0001)'}), '(result2.params, np.r_[0, 0, 0.91697508, 0], rtol=0.0001)\n', (6897, 6954), False, 'from numpy.testing import assert_allclose\n'), ((6987, 7092), 'pandas.DataFrame', 'pd.DataFrame', (["{'y': y, 'x1': x[:, 0], 'x2': x[:, 1], 'x3': x[:, 2], 'x4': x[:, 3],\n 'groups': groups}"], {}), "({'y': y, 'x1': x[:, 0], 'x2': x[:, 1], 'x3': x[:, 2], 'x4': x[\n :, 3], 'groups': groups})\n", (6999, 7092), True, 'import pandas as pd\n'), ((7162, 7224), 'statsmodels.discrete.conditional_models.ConditionalPoisson.from_formula', 'ConditionalPoisson.from_formula', (['fml'], {'groups': '"""groups"""', 'data': 'df'}), "(fml, groups='groups', data=df)\n", (7193, 7224), False, 'from statsmodels.discrete.conditional_models import ConditionalLogit, ConditionalPoisson\n'), ((7286, 7333), 'numpy.testing.assert_allclose', 'assert_allclose', (['result2.params', 'result3.params'], {}), '(result2.params, result3.params)\n', (7301, 7333), False, 'from numpy.testing import assert_allclose\n'), ((702, 730), 'numpy.testing.assert_allclose', 'assert_allclose', (['grad', 'ngrad'], {}), '(grad, ngrad)\n', (717, 730), False, 'from numpy.testing import assert_allclose\n'), ((820, 859), 'statsmodels.tools.numdiff.approx_fprime', 'approx_fprime', (['np.r_[x,]', 'model.loglike'], {}), '(np.r_[x,], model.loglike)\n', (833, 859), False, 'from statsmodels.tools.numdiff import approx_fprime\n'), ((909, 950), 'numpy.testing.assert_allclose', 'assert_allclose', (['grad', 'score'], {'rtol': '(0.0001)'}), '(grad, score, rtol=0.0001)\n', (924, 950), False, 'from numpy.testing import assert_allclose\n'), ((1681, 1721), 'numpy.testing.assert_allclose', 'assert_allclose', (['grad', 'ngrad'], {'rtol': '(1e-05)'}), '(grad, ngrad, rtol=1e-05)\n', (1696, 1721), False, 'from numpy.testing import assert_allclose\n'), ((1848, 1884), 'statsmodels.tools.numdiff.approx_fprime', 'approx_fprime', (['params', 'model.loglike'], {}), '(params, model.loglike)\n', (1861, 1884), False, 'from statsmodels.tools.numdiff import approx_fprime\n'), ((1929, 1970), 'numpy.testing.assert_allclose', 'assert_allclose', (['grad', 'score'], {'rtol': '(0.0001)'}), '(grad, score, rtol=0.0001)\n', (1944, 1970), False, 'from numpy.testing import assert_allclose\n'), ((2229, 2250), 'numpy.random.seed', 'np.random.seed', (['(34234)'], {}), '(34234)\n', (2243, 2250), True, 'import numpy as np\n'), ((2279, 2310), 'numpy.random.randint', 'np.random.randint', (['(0)', '(2)'], {'size': 'n'}), '(0, 2, size=n)\n', (2296, 2310), True, 'import numpy as np\n'), ((2324, 2348), 'numpy.random.normal', 'np.random.normal', ([], {'size': 'n'}), '(size=n)\n', (2340, 2348), True, 'import numpy as np\n'), ((2362, 2386), 'numpy.random.normal', 'np.random.normal', ([], {'size': 'n'}), '(size=n)\n', (2378, 2386), True, 'import numpy as np\n'), ((2399, 2431), 'numpy.random.randint', 'np.random.randint', (['(0)', '(25)'], {'size': 'n'}), '(0, 25, size=n)\n', (2416, 2431), True, 'import numpy as np\n'), ((2445, 2482), 'numpy.hstack', 'np.hstack', (['(x1[:, None], x2[:, None])'], {}), '((x1[:, None], x2[:, None]))\n', (2454, 2482), True, 'import numpy as np\n'), ((2671, 2721), 'pandas.DataFrame', 'pd.DataFrame', (["{'y': y, 'x1': x1, 'x2': x2, 'g': g}"], {}), "({'y': y, 'x1': x1, 'x2': x2, 'g': g})\n", (2683, 2721), True, 'import pandas as pd\n'), ((3029, 3088), 'numpy.testing.assert_allclose', 'assert_allclose', (['result1.params', 'result2.params'], {'rtol': '(1e-05)'}), '(result1.params, result2.params, rtol=1e-05)\n', (3044, 3088), False, 'from numpy.testing import assert_allclose\n'), ((3096, 3149), 'numpy.testing.assert_allclose', 'assert_allclose', (['result1.bse', 'result2.bse'], {'rtol': '(1e-05)'}), '(result1.bse, result2.bse, rtol=1e-05)\n', (3111, 3149), False, 'from numpy.testing import assert_allclose\n'), ((3236, 3297), 'numpy.testing.assert_allclose', 'assert_allclose', (['result1.tvalues', 'result2.tvalues'], {'rtol': '(1e-05)'}), '(result1.tvalues, result2.tvalues, rtol=1e-05)\n', (3251, 3297), False, 'from numpy.testing import assert_allclose\n'), ((3612, 3651), 'statsmodels.tools.numdiff.approx_fprime', 'approx_fprime', (['np.r_[x,]', 'model.loglike'], {}), '(np.r_[x,], model.loglike)\n', (3625, 3651), False, 'from statsmodels.tools.numdiff import approx_fprime\n'), ((3701, 3742), 'numpy.testing.assert_allclose', 'assert_allclose', (['grad', 'score'], {'rtol': '(0.0001)'}), '(grad, score, rtol=0.0001)\n', (3716, 3742), False, 'from numpy.testing import assert_allclose\n'), ((4350, 4386), 'statsmodels.tools.numdiff.approx_fprime', 'approx_fprime', (['params', 'model.loglike'], {}), '(params, model.loglike)\n', (4363, 4386), False, 'from statsmodels.tools.numdiff import approx_fprime\n'), ((4431, 4472), 'numpy.testing.assert_allclose', 'assert_allclose', (['grad', 'score'], {'rtol': '(0.0001)'}), '(grad, score, rtol=0.0001)\n', (4446, 4472), False, 'from numpy.testing import assert_allclose\n'), ((4809, 4825), 'numpy.ones', 'np.ones', (['(n // 10)'], {}), '(n // 10)\n', (4816, 4825), True, 'import numpy as np\n'), ((4916, 4932), 'numpy.ones', 'np.ones', (['(n // 10)'], {}), '(n // 10)\n', (4923, 4932), True, 'import numpy as np\n'), ((5019, 5036), 'numpy.dot', 'np.dot', (['x', 'params'], {}), '(x, params)\n', (5025, 5036), True, 'import numpy as np\n'), ((6150, 6166), 'numpy.ones', 'np.ones', (['(n // 10)'], {}), '(n // 10)\n', (6157, 6166), True, 'import numpy as np\n'), ((6257, 6273), 'numpy.ones', 'np.ones', (['(n // 10)'], {}), '(n // 10)\n', (6264, 6273), True, 'import numpy as np\n'), ((6360, 6377), 'numpy.dot', 'np.dot', (['x', 'params'], {}), '(x, params)\n', (6366, 6377), True, 'import numpy as np\n'), ((2523, 2555), 'statsmodels.discrete.conditional_models.ConditionalLogit', 'ConditionalLogit', (['y', 'x'], {'groups': 'g'}), '(y, x, groups=g)\n', (2539, 2555), False, 'from statsmodels.discrete.conditional_models import ConditionalLogit, ConditionalPoisson\n'), ((2591, 2625), 'statsmodels.discrete.conditional_models.ConditionalPoisson', 'ConditionalPoisson', (['y', 'x'], {'groups': 'g'}), '(y, x, groups=g)\n', (2609, 2625), False, 'from statsmodels.discrete.conditional_models import ConditionalLogit, ConditionalPoisson\n'), ((2762, 2831), 'statsmodels.discrete.conditional_models.ConditionalLogit.from_formula', 'ConditionalLogit.from_formula', (['"""y ~ 0 + x1 + x2"""'], {'groups': '"""g"""', 'data': 'df'}), "('y ~ 0 + x1 + x2', groups='g', data=df)\n", (2791, 2831), False, 'from statsmodels.discrete.conditional_models import ConditionalLogit, ConditionalPoisson\n'), ((2892, 2963), 'statsmodels.discrete.conditional_models.ConditionalPoisson.from_formula', 'ConditionalPoisson.from_formula', (['"""y ~ 0 + x1 + x2"""'], {'groups': '"""g"""', 'data': 'df'}), "('y ~ 0 + x1 + x2', groups='g', data=df)\n", (2923, 2963), False, 'from statsmodels.discrete.conditional_models import ConditionalLogit, ConditionalPoisson\n'), ((5074, 5091), 'numpy.exp', 'np.exp', (['(-lin_pred)'], {}), '(-lin_pred)\n', (5080, 5091), True, 'import numpy as np\n'), ((5102, 5127), 'numpy.random.uniform', 'np.random.uniform', ([], {'size': 'n'}), '(size=n)\n', (5119, 5127), True, 'import numpy as np\n')]
from abc import ABCMeta, abstractmethod import numpy as np class Agent(object): __metaclass__ = ABCMeta def __init__(self, name, id_, action_num, env): self.name = name self.id_ = id_ self.action_num = action_num # len(env.action_space[id_]) # self.opp_action_space = env.action_space[0:id_] + env.action_space[id_:-1] def set_pi(self, pi): # assert len(pi) == self.actin_num self.pi = pi def done(self, env): pass @abstractmethod def act(self, s, exploration, env): pass def update(self, s, a, o, r, s2, env): pass @staticmethod def format_time(n): return "" # s = humanfriendly.format_size(n) # return s.replace(' ', '').replace('bytes', '').replace('byte', '').rstrip('B') def full_name(self, env): return "{}_{}_{}".format(env.name, self.name, self.id_) class StationaryAgent(Agent): def __init__(self, id_, action_num, env, pi=None): super().__init__("stationary", id_, action_num, env) if pi is None: pi = np.random.dirichlet([1.0] * self.action_num) self.pi = np.array(pi, dtype=np.double) StationaryAgent.normalize(self.pi) def act(self, s, exploration, env): if self.verbose: print("pi of agent {}: {}".format(self.id_, self.pi)) return StationaryAgent.sample(self.pi) @staticmethod def normalize(pi): minprob = np.min(pi) if minprob < 0.0: pi -= minprob pi /= np.sum(pi) @staticmethod def sample(pi): return np.random.choice(pi.size, size=1, p=pi)[0] class RandomAgent(StationaryAgent): def __init__(self, id_, action_num, env): assert action_num > 0 super().__init__(id_, env, action_num, pi=[1.0 / action_num] * action_num) self.name = "random"
[ "numpy.random.choice", "numpy.array", "numpy.random.dirichlet", "numpy.sum", "numpy.min" ]
[((1170, 1199), 'numpy.array', 'np.array', (['pi'], {'dtype': 'np.double'}), '(pi, dtype=np.double)\n', (1178, 1199), True, 'import numpy as np\n'), ((1482, 1492), 'numpy.min', 'np.min', (['pi'], {}), '(pi)\n', (1488, 1492), True, 'import numpy as np\n'), ((1559, 1569), 'numpy.sum', 'np.sum', (['pi'], {}), '(pi)\n', (1565, 1569), True, 'import numpy as np\n'), ((1107, 1151), 'numpy.random.dirichlet', 'np.random.dirichlet', (['([1.0] * self.action_num)'], {}), '([1.0] * self.action_num)\n', (1126, 1151), True, 'import numpy as np\n'), ((1624, 1663), 'numpy.random.choice', 'np.random.choice', (['pi.size'], {'size': '(1)', 'p': 'pi'}), '(pi.size, size=1, p=pi)\n', (1640, 1663), True, 'import numpy as np\n')]
import unittest from musket_core import coders import numpy as np import pandas as pd import os import math fl=__file__ fl=os.path.dirname(fl) class TestCoders(unittest.TestCase): def test_binary_num(self): a=np.array([0,1,0,1]) bc=coders.get_coder("binary",a, None) self.assertEqual(bc[0], 0, "should be zero") self.assertEqual(bc[1], 1, "should be one") v=bc._decode(np.array([0.6])) self.assertEqual(v, 1, "should be one") v=bc._decode(np.array([0.2])) self.assertEqual(v, 0, "should be zero") pass def test_binary_str(self): a=np.array(["0","1","0","1"]) bc=coders.get_coder("binary",a, None) self.assertEqual(bc[0], 0, "should be zero") self.assertEqual(bc[1], 1, "should be one") v=bc._decode(np.array([0.6])) self.assertEqual(v, "1", "should be one") v=bc._decode(np.array([0.2])) self.assertEqual(v, "0", "should be zero") pass def test_binary_str2(self): a=np.array(["","1","","1"]) bc=coders.get_coder("binary",a, None) self.assertEqual(bc[0], 0, "should be zero") self.assertEqual(bc[1], 1, "should be one") v=bc._decode(np.array([0.6])) self.assertEqual(v, "1", "should be one") v=bc._decode(np.array([0.2])) self.assertEqual(v, "", "should be zero") pass def test_binary_bool(self): a=np.array([True,False,True,False]) bc=coders.get_coder("binary",a, None) self.assertEqual(bc[0], 1, "should be zero") self.assertEqual(bc[1], 0, "should be one") v=bc._decode(np.array([0.6])) self.assertEqual(v, True, "should be one") v=bc._decode(np.array([0.2])) self.assertEqual(v, False, "should be zero") pass def test_categorical_num(self): a=np.array([0,1,2,1]) bc=coders.get_coder("categorical_one_hot",a, None) self.assertEqual(bc[0][0], True, "should be zero") self.assertEqual(bc[0][1], False, "should be one") v=bc._decode(np.array([0.3,0.4,0.45])) self.assertEqual(v, 2, "should be one") v=bc._decode(np.array([0.2,0.1,0.1])) self.assertEqual(v, 0, "should be zero") pass def test_categorical_str(self): a=np.array(["a","b","c","b"]) bc=coders.get_coder("categorical_one_hot",a, None) self.assertEqual(bc[0][0], True, "should be zero") self.assertEqual(bc[0][1], False, "should be one") v=bc._decode(np.array([0.3,0.4,0.45])) self.assertEqual(v, "c", "should be one") v=bc._decode(np.array([0.2,0.1,0.1])) self.assertEqual(v, "a", "should be zero") pass def test_categorical_str2(self): a=np.array(["","b","c","b"]) bc=coders.get_coder("categorical_one_hot",a, None) self.assertEqual(bc[0][0], True, "should be zero") self.assertEqual(bc[0][1], False, "should be one") v=bc._decode(np.array([0.3,0.4,0.45])) self.assertEqual(v, "c", "should be one") v=bc._decode(np.array([0.2,0.1,0.1])) self.assertEqual(v, "", "should be zero") pass def test_categorical_pd(self): a=np.array([math.nan,1,2,1]) bc=coders.get_coder("categorical_one_hot",a, None) self.assertEqual(bc[0][2], True, "should be zero") self.assertEqual(bc[0][1], False, "should be one") v=bc._decode(np.array([0.3,0.4,0.45])) self.assertEqual(math.isnan(v),True, "should be one") v=bc._decode(np.array([0.2,0.1,0.1])) self.assertEqual(v, 1, "should be zero") pass def test_multiclass(self): a=np.array(["1 2","0 2","0",""]) bc=coders.get_coder("multi_class",a, None) val=bc[0] self.assertEqual((val==np.array([False,True,True])).sum(), 3,"Fixing format") for i in range(len(a)): val=bc[i] r=bc._decode(val) self.assertEqual(r, a[i], "Decoding should work also") pass def test_multiclass1(self): a=np.array(["1_2","0_2","0",""]) bc=coders.get_coder("multi_class",a, None) val=bc[0] self.assertEqual((val==np.array([False,True,True])).sum(), 3,"Fixing format") for i in range(len(a)): val=bc[i] r=bc._decode(val) self.assertEqual(r, a[i], "Decoding should work also") pass def test_multiclass2(self): a=np.array(["1","","",""]) bc=coders.get_coder("multi_class",a, None) val=bc[0] self.assertEqual((val==np.array([True])).sum(), 1,"Fixing format") for i in range(len(a)): val=bc[i] r=bc._decode(val) self.assertEqual(r, a[i], "Decoding should work also") pass
[ "os.path.dirname", "numpy.array", "musket_core.coders.get_coder", "math.isnan" ]
[((134, 153), 'os.path.dirname', 'os.path.dirname', (['fl'], {}), '(fl)\n', (149, 153), False, 'import os\n'), ((237, 259), 'numpy.array', 'np.array', (['[0, 1, 0, 1]'], {}), '([0, 1, 0, 1])\n', (245, 259), True, 'import numpy as np\n'), ((269, 304), 'musket_core.coders.get_coder', 'coders.get_coder', (['"""binary"""', 'a', 'None'], {}), "('binary', a, None)\n", (285, 304), False, 'from musket_core import coders\n'), ((645, 675), 'numpy.array', 'np.array', (["['0', '1', '0', '1']"], {}), "(['0', '1', '0', '1'])\n", (653, 675), True, 'import numpy as np\n'), ((685, 720), 'musket_core.coders.get_coder', 'coders.get_coder', (['"""binary"""', 'a', 'None'], {}), "('binary', a, None)\n", (701, 720), False, 'from musket_core import coders\n'), ((1066, 1094), 'numpy.array', 'np.array', (["['', '1', '', '1']"], {}), "(['', '1', '', '1'])\n", (1074, 1094), True, 'import numpy as np\n'), ((1104, 1139), 'musket_core.coders.get_coder', 'coders.get_coder', (['"""binary"""', 'a', 'None'], {}), "('binary', a, None)\n", (1120, 1139), False, 'from musket_core import coders\n'), ((1484, 1520), 'numpy.array', 'np.array', (['[True, False, True, False]'], {}), '([True, False, True, False])\n', (1492, 1520), True, 'import numpy as np\n'), ((1530, 1565), 'musket_core.coders.get_coder', 'coders.get_coder', (['"""binary"""', 'a', 'None'], {}), "('binary', a, None)\n", (1546, 1565), False, 'from musket_core import coders\n'), ((1924, 1946), 'numpy.array', 'np.array', (['[0, 1, 2, 1]'], {}), '([0, 1, 2, 1])\n', (1932, 1946), True, 'import numpy as np\n'), ((1956, 2004), 'musket_core.coders.get_coder', 'coders.get_coder', (['"""categorical_one_hot"""', 'a', 'None'], {}), "('categorical_one_hot', a, None)\n", (1972, 2004), False, 'from musket_core import coders\n'), ((2396, 2426), 'numpy.array', 'np.array', (["['a', 'b', 'c', 'b']"], {}), "(['a', 'b', 'c', 'b'])\n", (2404, 2426), True, 'import numpy as np\n'), ((2436, 2484), 'musket_core.coders.get_coder', 'coders.get_coder', (['"""categorical_one_hot"""', 'a', 'None'], {}), "('categorical_one_hot', a, None)\n", (2452, 2484), False, 'from musket_core import coders\n'), ((2881, 2910), 'numpy.array', 'np.array', (["['', 'b', 'c', 'b']"], {}), "(['', 'b', 'c', 'b'])\n", (2889, 2910), True, 'import numpy as np\n'), ((2920, 2968), 'musket_core.coders.get_coder', 'coders.get_coder', (['"""categorical_one_hot"""', 'a', 'None'], {}), "('categorical_one_hot', a, None)\n", (2936, 2968), False, 'from musket_core import coders\n'), ((3362, 3391), 'numpy.array', 'np.array', (['[math.nan, 1, 2, 1]'], {}), '([math.nan, 1, 2, 1])\n', (3370, 3391), True, 'import numpy as np\n'), ((3401, 3449), 'musket_core.coders.get_coder', 'coders.get_coder', (['"""categorical_one_hot"""', 'a', 'None'], {}), "('categorical_one_hot', a, None)\n", (3417, 3449), False, 'from musket_core import coders\n'), ((3850, 3883), 'numpy.array', 'np.array', (["['1 2', '0 2', '0', '']"], {}), "(['1 2', '0 2', '0', ''])\n", (3858, 3883), True, 'import numpy as np\n'), ((3893, 3933), 'musket_core.coders.get_coder', 'coders.get_coder', (['"""multi_class"""', 'a', 'None'], {}), "('multi_class', a, None)\n", (3909, 3933), False, 'from musket_core import coders\n'), ((4268, 4301), 'numpy.array', 'np.array', (["['1_2', '0_2', '0', '']"], {}), "(['1_2', '0_2', '0', ''])\n", (4276, 4301), True, 'import numpy as np\n'), ((4311, 4351), 'musket_core.coders.get_coder', 'coders.get_coder', (['"""multi_class"""', 'a', 'None'], {}), "('multi_class', a, None)\n", (4327, 4351), False, 'from musket_core import coders\n'), ((4686, 4713), 'numpy.array', 'np.array', (["['1', '', '', '']"], {}), "(['1', '', '', ''])\n", (4694, 4713), True, 'import numpy as np\n'), ((4723, 4763), 'musket_core.coders.get_coder', 'coders.get_coder', (['"""multi_class"""', 'a', 'None'], {}), "('multi_class', a, None)\n", (4739, 4763), False, 'from musket_core import coders\n'), ((433, 448), 'numpy.array', 'np.array', (['[0.6]'], {}), '([0.6])\n', (441, 448), True, 'import numpy as np\n'), ((521, 536), 'numpy.array', 'np.array', (['[0.2]'], {}), '([0.2])\n', (529, 536), True, 'import numpy as np\n'), ((849, 864), 'numpy.array', 'np.array', (['[0.6]'], {}), '([0.6])\n', (857, 864), True, 'import numpy as np\n'), ((939, 954), 'numpy.array', 'np.array', (['[0.2]'], {}), '([0.2])\n', (947, 954), True, 'import numpy as np\n'), ((1268, 1283), 'numpy.array', 'np.array', (['[0.6]'], {}), '([0.6])\n', (1276, 1283), True, 'import numpy as np\n'), ((1358, 1373), 'numpy.array', 'np.array', (['[0.2]'], {}), '([0.2])\n', (1366, 1373), True, 'import numpy as np\n'), ((1694, 1709), 'numpy.array', 'np.array', (['[0.6]'], {}), '([0.6])\n', (1702, 1709), True, 'import numpy as np\n'), ((1785, 1800), 'numpy.array', 'np.array', (['[0.2]'], {}), '([0.2])\n', (1793, 1800), True, 'import numpy as np\n'), ((2156, 2182), 'numpy.array', 'np.array', (['[0.3, 0.4, 0.45]'], {}), '([0.3, 0.4, 0.45])\n', (2164, 2182), True, 'import numpy as np\n'), ((2253, 2278), 'numpy.array', 'np.array', (['[0.2, 0.1, 0.1]'], {}), '([0.2, 0.1, 0.1])\n', (2261, 2278), True, 'import numpy as np\n'), ((2636, 2662), 'numpy.array', 'np.array', (['[0.3, 0.4, 0.45]'], {}), '([0.3, 0.4, 0.45])\n', (2644, 2662), True, 'import numpy as np\n'), ((2735, 2760), 'numpy.array', 'np.array', (['[0.2, 0.1, 0.1]'], {}), '([0.2, 0.1, 0.1])\n', (2743, 2760), True, 'import numpy as np\n'), ((3120, 3146), 'numpy.array', 'np.array', (['[0.3, 0.4, 0.45]'], {}), '([0.3, 0.4, 0.45])\n', (3128, 3146), True, 'import numpy as np\n'), ((3219, 3244), 'numpy.array', 'np.array', (['[0.2, 0.1, 0.1]'], {}), '([0.2, 0.1, 0.1])\n', (3227, 3244), True, 'import numpy as np\n'), ((3601, 3627), 'numpy.array', 'np.array', (['[0.3, 0.4, 0.45]'], {}), '([0.3, 0.4, 0.45])\n', (3609, 3627), True, 'import numpy as np\n'), ((3653, 3666), 'math.isnan', 'math.isnan', (['v'], {}), '(v)\n', (3663, 3666), False, 'import math\n'), ((3712, 3737), 'numpy.array', 'np.array', (['[0.2, 0.1, 0.1]'], {}), '([0.2, 0.1, 0.1])\n', (3720, 3737), True, 'import numpy as np\n'), ((3994, 4023), 'numpy.array', 'np.array', (['[False, True, True]'], {}), '([False, True, True])\n', (4002, 4023), True, 'import numpy as np\n'), ((4412, 4441), 'numpy.array', 'np.array', (['[False, True, True]'], {}), '([False, True, True])\n', (4420, 4441), True, 'import numpy as np\n'), ((4824, 4840), 'numpy.array', 'np.array', (['[True]'], {}), '([True])\n', (4832, 4840), True, 'import numpy as np\n')]
''' @file momentum_kinematics_optimizer.py @package momentumopt @author <NAME> (<EMAIL>) @license License BSD-3-Clause @copyright Copyright (c) 2019, New York University and Max Planck Gesellschaft. @date 2019-10-08 ''' import os import numpy as np from momentumopt.kinoptpy.qp import QpSolver from momentumopt.kinoptpy.inverse_kinematics import PointContactInverseKinematics from pinocchio import RobotWrapper import pinocchio as se3 from pinocchio.utils import zero from pymomentum import * from momentumopt.quadruped.quadruped_wrapper import QuadrupedWrapper from momentumopt.kinoptpy.min_jerk_traj import * from pymomentum import \ PlannerVectorParam_KinematicDefaultJointPositions, \ PlannerIntParam_NumTimesteps, \ PlannerDoubleParam_TimeStep class Contact(object): def __init__(self, position, start_time, end_time): self.pos = position self.init_time = start_time self.final_time = end_time def position(self): return self.pos def start_time(self): return self.init_time def end_time(self): return self.final_time def get_contact_plan(contact_states, effs): contacts = {} for i, eff in enumerate(effs): num_contacts = len(contact_states(i)) contacts[eff] = [] for j in range(num_contacts): contact_ = contact_states(i)[j] start_time = contact_.start_time end_time = contact_.end_time position = contact_.position contacts[eff].append(Contact(position, start_time, end_time)) return contacts def generate_eff_traj(contacts, z_offset): effs = contacts.keys() eff_traj_poly = {} for eff in effs: cnt = contacts[eff] num_contacts = len(cnt) poly_traj = [ PolynominalList(), PolynominalList(), PolynominalList() ] for i in range(num_contacts): # Create a constant polynominal for endeffector on the ground. t = [cnt[i].start_time(), cnt[i].end_time()] for idx in range(3): poly_traj[idx].append(t, constant_poly(cnt[i].position()[idx])) # If there is a contact following, add the transition between # the two contact points. if i < num_contacts - 1: t = [cnt[i].end_time(), cnt[i+1].start_time()] for idx in range(3): via = None if idx == 2: via = z_offset + cnt[i].position()[idx] poly = poly_points(t, cnt[i].position()[idx], cnt[i+1].position()[idx], via) poly_traj[idx].append(t, poly) eff_traj_poly[eff] = poly_traj # returns end eff trajectories return eff_traj_poly class EndeffectorTrajectoryGenerator(object): def __init__(self): self.z_offset = 0.1 def get_z_bound(self, mom_kin_optimizer): z_max = min(max(mom_kin_optimizer.com_dyn[:, 2]), self.max_bound) z_min = max(min(mom_kin_optimizer.com_dyn[:, 2]), self.min_bound) return z_max, z_min def __call__(self, mom_kin_optimizer): ''' Computes the endeffector positions and velocities. Returns endeff_pos_ref, endeff_vel_ref [0]: endeff_pos_ref: np.array, shape=[num_time_steps, num_eff, 3={x, y, z}] [1]: endeff_vel_ref: np.array, shape=[num_time_steps, num_eff, 3={x, y, z}] ''' dt = mom_kin_optimizer.dt num_eff = len(mom_kin_optimizer.eff_names) num_time_steps = mom_kin_optimizer.num_time_steps contacts = get_contact_plan(mom_kin_optimizer.contact_sequence.contact_states, mom_kin_optimizer.eff_names) # Generate minimum jerk trajectories eff_traj_poly = generate_eff_traj(contacts, self.z_offset) # Compute the endeffector position and velocity trajectories. endeff_pos_ref = np.zeros((num_time_steps, num_eff, 3)) endeff_vel_ref = np.zeros((num_time_steps, num_eff, 3)) endeff_contact = np.zeros((num_time_steps, num_eff)) for it in range(num_time_steps): for eff, name in enumerate(mom_kin_optimizer.eff_names): endeff_pos_ref[it][eff] = [eff_traj_poly[name][i].eval(it * dt) for i in range(3)] endeff_vel_ref[it][eff] = [eff_traj_poly[name][i].deval(it * dt) for i in range(3)] # HACK: If the velocity is zero, assume the endeffector is in # contact with the ground. if np.all(endeff_vel_ref[it][eff] == 0.): endeff_contact[it][eff] = 1. else: endeff_contact[it][eff] = 0. return endeff_pos_ref, endeff_vel_ref, endeff_contact class JointTrajectoryGenerator(object): def __init__(self): self.dt =.01 self.num_time_steps = None self.q_init = None self.poly_traj = None def joint_traj(self, q_via): self.poly_traj = [] for i in range(len(self.q_init)): self.poly_traj = np.append(self.poly_traj, [PolynominalList()]) for j in range(len(self.q_init)): for i in range (len(q_via[:,0])+1): if i==0: t = [0, q_via[0,0]/self.dt] poly = poly_points(t, self.q_init[j], q_via[i,j+1]) self.poly_traj[j].append(t, poly) elif(i==len(q_via[:,0])): t = [q_via[i-1,0]/self.dt, self.num_time_steps] poly = poly_points(t, q_via[i-1,j+1], self.q_init[j]) self.poly_traj[j].append(t, poly) else: t = [q_via[i-1,0]/self.dt, q_via[i,0]/self.dt] poly = poly_points(t, q_via[i-1,j+1], q_via[i,j+1]) self.poly_traj[j].append(t, poly) def eval_traj(self,t): q = np.zeros((1,len(self.q_init)),float) for j in range(len(self.q_init)): q[0,j] = self.poly_traj[j].eval(t) return np.matrix(q) class MomentumKinematicsOptimizer(object): def __init__(self): self.q_init = None self.dq_init = None self.reg_orientation = 1e-2 self.reg_joint_position = 2. self.joint_des = None def reset(self): self.kinematics_sequence = KinematicsSequence() self.kinematics_sequence.resize(self.planner_setting.get(PlannerIntParam_NumTimesteps), self.planner_setting.get(PlannerIntParam_NumDofs)) def initialize(self, planner_setting, max_iterations=50, eps=0.001, endeff_traj_generator=None, RobotWrapper=QuadrupedWrapper): self.planner_setting = planner_setting if endeff_traj_generator is None: endeff_traj_generator = EndeffectorTrajectoryGenerator() self.endeff_traj_generator = endeff_traj_generator self.dt = planner_setting.get(PlannerDoubleParam_TimeStep) self.num_time_steps = planner_setting.get(PlannerIntParam_NumTimesteps) self.max_iterations = max_iterations self.eps = eps self.robot = RobotWrapper() self.reset() # Holds dynamics and kinematics results self.com_dyn = np.zeros((self.num_time_steps, 3)) self.lmom_dyn = np.zeros((self.num_time_steps, 3)) self.amom_dyn = np.zeros((self.num_time_steps, 3)) self.com_kin = np.zeros((self.num_time_steps, 3)) self.lmom_kin = np.zeros((self.num_time_steps, 3)) self.amom_kin = np.zeros((self.num_time_steps, 3)) self.q_kin = np.zeros((self.num_time_steps, self.robot.model.nq)) self.dq_kin = np.zeros((self.num_time_steps, self.robot.model.nv)) self.hip_names = ['{}_HFE'.format(eff) for eff in self.robot.effs] self.hip_ids = [self.robot.model.getFrameId(name) for name in self.hip_names] self.eff_names = ['{}_{}'.format(eff, self.robot.joints_list[-1]) for eff in self.robot.effs] self.inv_kin = PointContactInverseKinematics(self.robot.model, self.eff_names) self.motion_eff = { 'trajectory': np.zeros((self.num_time_steps, 3 * self.inv_kin.ne)), 'velocity': np.zeros((self.num_time_steps, 3 * self.inv_kin.ne)), 'trajectory_wrt_base': np.zeros((self.num_time_steps, 3 * self.inv_kin.ne)), 'velocity_wrt_base': np.zeros((self.num_time_steps, 3 * self.inv_kin.ne)) } def fill_data_from_dynamics(self): # The centroidal information for it in range(self.num_time_steps): self.com_dyn[it] = self.dynamic_sequence.dynamics_states[it].com self.lmom_dyn[it] = self.dynamic_sequence.dynamics_states[it].lmom self.amom_dyn[it] = self.dynamic_sequence.dynamics_states[it].amom def fill_endeffector_trajectory(self): self.endeff_pos_ref, self.endeff_vel_ref, self.endeff_contact = \ self.endeff_traj_generator(self) def fill_kinematic_result(self, it, q, dq): def framesPos(frames): return np.vstack([data.oMf[idx].translation for idx in frames]).reshape(-1) def framesVel(frames): return np.vstack([ self.inv_kin.get_world_oriented_frame_jacobian(q, idx).dot(dq)[:3] for idx in frames ]).reshape(-1) data = self.inv_kin.robot.data hg = self.inv_kin.robot.centroidalMomentum(q, dq) # Storing on the internal array. self.com_kin[it] = self.inv_kin.robot.com(q).T self.lmom_kin[it] = hg.linear.T self.amom_kin[it] = hg.angular.T self.q_kin[it] = q.T self.dq_kin[it] = dq.T # The endeffector informations as well. self.motion_eff['trajectory'][it] = framesPos(self.inv_kin.endeff_ids) self.motion_eff['velocity'][it] = self.inv_kin.J[6:(self.inv_kin.ne + 2) * 3].dot(dq).T self.motion_eff['trajectory_wrt_base'][it] = \ self.motion_eff['trajectory'][it] - framesPos(self.hip_ids) self.motion_eff['velocity_wrt_base'][it] = \ self.motion_eff['velocity'][it] - framesVel(self.hip_ids) # Storing on the kinematic sequence. kinematic_state = self.kinematics_sequence.kinematics_states[it] kinematic_state.com = self.com_kin[it] kinematic_state.lmom = self.lmom_kin[it] kinematic_state.amom = self.amom_kin[it] kinematic_state.robot_posture.base_position = q[:3] kinematic_state.robot_posture.base_orientation = q[3:7] kinematic_state.robot_posture.joint_positions = q[7:] kinematic_state.robot_velocity.base_linear_velocity = dq[:3] kinematic_state.robot_velocity.base_angular_velocity = dq[3:6] kinematic_state.robot_velocity.joint_velocities = dq[6:] def optimize_initial_position(self, init_state): # Optimize the initial configuration q = se3.neutral(self.robot.model) plan_joint_init_pos = self.planner_setting.get( PlannerVectorParam_KinematicDefaultJointPositions) if len(plan_joint_init_pos) != self.robot.num_ctrl_joints: raise ValueError( 'Number of joints in config file not same as required for robot\n' + 'Got %d joints but robot expects %d joints.' % ( len(plan_joint_init_pos), self.robot.num_ctrl_joints)) q[7:] = np.matrix(plan_joint_init_pos).T q[2] = self.robot.floor_height + 0.32 dq = np.matrix(np.zeros(self.robot.robot.nv)).T com_ref = init_state.com lmom_ref = np.zeros(3) amom_ref = np.zeros(3) endeff_pos_ref = np.array([init_state.effPosition(i) for i in range(init_state.effNum())]) endeff_vel_ref = np.matrix(np.zeros((init_state.effNum(), 3))) endeff_contact = np.ones(init_state.effNum()) quad_goal = se3.Quaternion(se3.rpy.rpyToMatrix(np.matrix([0.0, 0, 0.]).T)) q[3:7] = quad_goal.coeffs() for iters in range(self.max_iterations): # Adding small P controller for the base orientation to always start with flat # oriented base. quad_q = se3.Quaternion(float(q[6]), float(q[3]), float(q[4]), float(q[5])) amom_ref = 1e-1 * se3.log((quad_goal * quad_q.inverse()).matrix()) res = self.inv_kin.compute(q, dq, com_ref, lmom_ref, amom_ref, endeff_pos_ref, endeff_vel_ref, endeff_contact, None) q = se3.integrate(self.robot.model, q, res) if np.linalg.norm(res) < 1e-3: print('Found initial configuration after {} iterations'.format(iters + 1)) break if iters == self.max_iterations - 1: print('Failed to converge for initial setup.') print("initial configuration: \n", q) self.q_init = q.copy() self.dq_init = dq.copy() def optimize(self, init_state, contact_sequence, dynamic_sequence, plotting=False): self.init_state = init_state self.contact_sequence = contact_sequence self.dynamic_sequence = dynamic_sequence self.q_via = None # Create array with centroidal and endeffector informations. self.fill_data_from_dynamics() self.fill_endeffector_trajectory() # Run the optimization for the initial configuration only once. if self.q_init is None: self.optimize_initial_position(init_state) # Get the desired joint trajectory # print "num_joint_via:",self.planner_setting.get(PlannerIntParam_NumJointViapoints) # print "joint_via:",self.planner_setting.get(PlannerCVectorParam_JointViapoints) # TODO: this is for jump, should go to config file # q_jump = [1., 0.1, -0.2 ,0.1, -0.2 ,-0.1, 0.2 ,-0.1, 0.2] # q_via = np.matrix([.75, np.pi/2, -np.pi, np.pi/2, -np.pi, -np.pi/2, np.pi, -np.pi/2, np.pi]).T # q_max = np.matrix([1.35, .7*np.pi/2, -.7*np.pi, .7*np.pi/2, -.7*np.pi, -.7*np.pi/2, .7*np.pi, -.7*np.pi/2, .7*np.pi]).T # q_via0 = np.vstack((q_via.T, q_jump)) # self.q_via = np.vstack((q_via0, q_max.T)) joint_traj_gen = JointTrajectoryGenerator() joint_traj_gen.num_time_steps = self.num_time_steps joint_traj_gen.q_init = self.q_init[7:] self.joint_des = np.zeros((len(self.q_init[7:]),self.num_time_steps), float) if self.q_via is None: for i in range (self.num_time_steps): self.joint_des[:,i] = self.q_init[7 : ].T else: joint_traj_gen.joint_traj(self.q_via) for it in range(self.num_time_steps): self.joint_des[:,it] = joint_traj_gen.eval_traj(it) # Compute inverse kinematics over the full trajectory. self.inv_kin.is_init_time = 0 q, dq = self.q_init.copy(), self.dq_init.copy() for it in range(self.num_time_steps): quad_goal = se3.Quaternion(se3.rpy.rpyToMatrix(np.matrix([0.0, 0, 0.]).T)) quad_q = se3.Quaternion(float(q[6]), float(q[3]), float(q[4]), float(q[5])) amom_ref = (self.reg_orientation * se3.log((quad_goal * quad_q.inverse()).matrix()).T + self.amom_dyn[it]).reshape(-1) joint_regularization_ref = self.reg_joint_position * (np.matrix(self.joint_des[:,it]).T - q[7 : ]) # joint_regularization_ref = self.reg_joint_position * (self.q_init[7 : ] - q[7 : ]) # Fill the kinematics results for it. self.inv_kin.forward_robot(q, dq) self.fill_kinematic_result(it, q, dq) dq = self.inv_kin.compute( q, dq, self.com_dyn[it], self.lmom_dyn[it], amom_ref, self.endeff_pos_ref[it], self.endeff_vel_ref[it], self.endeff_contact[it], joint_regularization_ref) # Integrate to the next state. q = se3.integrate(self.robot.model, q, dq * self.dt)
[ "numpy.all", "pinocchio.integrate", "pinocchio.neutral", "numpy.zeros", "pinocchio.RobotWrapper", "numpy.vstack", "numpy.linalg.norm", "numpy.matrix", "momentumopt.kinoptpy.inverse_kinematics.PointContactInverseKinematics" ]
[((3951, 3989), 'numpy.zeros', 'np.zeros', (['(num_time_steps, num_eff, 3)'], {}), '((num_time_steps, num_eff, 3))\n', (3959, 3989), True, 'import numpy as np\n'), ((4015, 4053), 'numpy.zeros', 'np.zeros', (['(num_time_steps, num_eff, 3)'], {}), '((num_time_steps, num_eff, 3))\n', (4023, 4053), True, 'import numpy as np\n'), ((4079, 4114), 'numpy.zeros', 'np.zeros', (['(num_time_steps, num_eff)'], {}), '((num_time_steps, num_eff))\n', (4087, 4114), True, 'import numpy as np\n'), ((6070, 6082), 'numpy.matrix', 'np.matrix', (['q'], {}), '(q)\n', (6079, 6082), True, 'import numpy as np\n'), ((7184, 7198), 'pinocchio.RobotWrapper', 'RobotWrapper', ([], {}), '()\n', (7196, 7198), False, 'from pinocchio import RobotWrapper\n'), ((7293, 7327), 'numpy.zeros', 'np.zeros', (['(self.num_time_steps, 3)'], {}), '((self.num_time_steps, 3))\n', (7301, 7327), True, 'import numpy as np\n'), ((7352, 7386), 'numpy.zeros', 'np.zeros', (['(self.num_time_steps, 3)'], {}), '((self.num_time_steps, 3))\n', (7360, 7386), True, 'import numpy as np\n'), ((7411, 7445), 'numpy.zeros', 'np.zeros', (['(self.num_time_steps, 3)'], {}), '((self.num_time_steps, 3))\n', (7419, 7445), True, 'import numpy as np\n'), ((7470, 7504), 'numpy.zeros', 'np.zeros', (['(self.num_time_steps, 3)'], {}), '((self.num_time_steps, 3))\n', (7478, 7504), True, 'import numpy as np\n'), ((7529, 7563), 'numpy.zeros', 'np.zeros', (['(self.num_time_steps, 3)'], {}), '((self.num_time_steps, 3))\n', (7537, 7563), True, 'import numpy as np\n'), ((7588, 7622), 'numpy.zeros', 'np.zeros', (['(self.num_time_steps, 3)'], {}), '((self.num_time_steps, 3))\n', (7596, 7622), True, 'import numpy as np\n'), ((7644, 7696), 'numpy.zeros', 'np.zeros', (['(self.num_time_steps, self.robot.model.nq)'], {}), '((self.num_time_steps, self.robot.model.nq))\n', (7652, 7696), True, 'import numpy as np\n'), ((7719, 7771), 'numpy.zeros', 'np.zeros', (['(self.num_time_steps, self.robot.model.nv)'], {}), '((self.num_time_steps, self.robot.model.nv))\n', (7727, 7771), True, 'import numpy as np\n'), ((8059, 8122), 'momentumopt.kinoptpy.inverse_kinematics.PointContactInverseKinematics', 'PointContactInverseKinematics', (['self.robot.model', 'self.eff_names'], {}), '(self.robot.model, self.eff_names)\n', (8088, 8122), False, 'from momentumopt.kinoptpy.inverse_kinematics import PointContactInverseKinematics\n'), ((10961, 10990), 'pinocchio.neutral', 'se3.neutral', (['self.robot.model'], {}), '(self.robot.model)\n', (10972, 10990), True, 'import pinocchio as se3\n'), ((11638, 11649), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (11646, 11649), True, 'import numpy as np\n'), ((11669, 11680), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (11677, 11680), True, 'import numpy as np\n'), ((8178, 8230), 'numpy.zeros', 'np.zeros', (['(self.num_time_steps, 3 * self.inv_kin.ne)'], {}), '((self.num_time_steps, 3 * self.inv_kin.ne))\n', (8186, 8230), True, 'import numpy as np\n'), ((8256, 8308), 'numpy.zeros', 'np.zeros', (['(self.num_time_steps, 3 * self.inv_kin.ne)'], {}), '((self.num_time_steps, 3 * self.inv_kin.ne))\n', (8264, 8308), True, 'import numpy as np\n'), ((8345, 8397), 'numpy.zeros', 'np.zeros', (['(self.num_time_steps, 3 * self.inv_kin.ne)'], {}), '((self.num_time_steps, 3 * self.inv_kin.ne))\n', (8353, 8397), True, 'import numpy as np\n'), ((8432, 8484), 'numpy.zeros', 'np.zeros', (['(self.num_time_steps, 3 * self.inv_kin.ne)'], {}), '((self.num_time_steps, 3 * self.inv_kin.ne))\n', (8440, 8484), True, 'import numpy as np\n'), ((11450, 11480), 'numpy.matrix', 'np.matrix', (['plan_joint_init_pos'], {}), '(plan_joint_init_pos)\n', (11459, 11480), True, 'import numpy as np\n'), ((12545, 12584), 'pinocchio.integrate', 'se3.integrate', (['self.robot.model', 'q', 'res'], {}), '(self.robot.model, q, res)\n', (12558, 12584), True, 'import pinocchio as se3\n'), ((15958, 16006), 'pinocchio.integrate', 'se3.integrate', (['self.robot.model', 'q', '(dq * self.dt)'], {}), '(self.robot.model, q, dq * self.dt)\n', (15971, 16006), True, 'import pinocchio as se3\n'), ((4566, 4604), 'numpy.all', 'np.all', (['(endeff_vel_ref[it][eff] == 0.0)'], {}), '(endeff_vel_ref[it][eff] == 0.0)\n', (4572, 4604), True, 'import numpy as np\n'), ((11552, 11581), 'numpy.zeros', 'np.zeros', (['self.robot.robot.nv'], {}), '(self.robot.robot.nv)\n', (11560, 11581), True, 'import numpy as np\n'), ((12601, 12620), 'numpy.linalg.norm', 'np.linalg.norm', (['res'], {}), '(res)\n', (12615, 12620), True, 'import numpy as np\n'), ((9113, 9169), 'numpy.vstack', 'np.vstack', (['[data.oMf[idx].translation for idx in frames]'], {}), '([data.oMf[idx].translation for idx in frames])\n', (9122, 9169), True, 'import numpy as np\n'), ((11960, 11984), 'numpy.matrix', 'np.matrix', (['[0.0, 0, 0.0]'], {}), '([0.0, 0, 0.0])\n', (11969, 11984), True, 'import numpy as np\n'), ((15040, 15064), 'numpy.matrix', 'np.matrix', (['[0.0, 0, 0.0]'], {}), '([0.0, 0, 0.0])\n', (15049, 15064), True, 'import numpy as np\n'), ((15354, 15386), 'numpy.matrix', 'np.matrix', (['self.joint_des[:, it]'], {}), '(self.joint_des[:, it])\n', (15363, 15386), True, 'import numpy as np\n')]
import torch import torch.nn as nn import numpy as np import matplotlib.pyplot as plt # NOT -> ParameterModule # NOT -> children_and_parameters # NOT -> flatten_model # NOT -> lr_range # NOT -> scheduling functions # NOT -> SmoothenValue # YES -> lr_find # NOT -> plot_lr_find # NOT TO BE MODIFIED class ParameterModule(nn.Module): "Register a lone parameter 'p' in a module" def __init__(self, p:nn.Parameter): super().__init__() self.val = p def forward(self, x): return x # NOT TO BE MODIFIED # To be used to flatten_model def children_and_parameters(m:nn.Module): "Return the children of `m` and its direct parameters not registered in modules." children = list(m.children()) children_p = sum([[id(p) for p in c.parameters()] for c in m.children()],[]) for p in m.parameters(): if id(p) not in children_p: children.append(ParameterModule(p)) return children # NOT TO BE MODIFIED flatten_model = lambda m: sum(map(flatten_model,children_and_parameters(m)),[]) if len(list(m.children())) else [m] # NOT TO BE MODIFIED def lr_range(model, lr): """ Build differential learning rate from lr. It will give you the Arguments: model :- torch.nn.Module lr :- float or slice Returns: Depending upon lr """ if not isinstance(lr, slice): return lr num_layer = len([nn.Sequential(*flatten_model(model))]) if lr.start: mult = lr.stop / lr.start step = mult**(1/(num_layer-1)) res = np.array([lr.start*(step**i) for i in range(num_layer)]) else: res = [lr.stop/10.]*(num_layer-1) + [lr.stop] return np.array(res) # NOT TO BE MODIFIED # These are the functions that would give us the values of lr. Liks for linearly # increasing lr we would use annealing_linear. # You can add your own custom function, for producing lr. # By defualt annealing_exp is used for both lr and momentum def annealing_no(start, end, pct:float): "No annealing, always return `start`." return start def annealing_linear(start, end, pct:float): "Linearly anneal from `start` to `end` as pct goes from 0.0 to 1.0." return start + pct * (end-start) def annealing_exp(start, end, pct:float): "Exponentially anneal from `start` to `end` as pct goes from 0.0 to 1.0." return start * (end/start) ** pct def annealing_cos(start, end, pct:float): "Cosine anneal from `start` to `end` as pct goes from 0.0 to 1.0." cos_out = np.cos(np.pi * pct) + 1 return end + (start-end)/2 * cos_out def do_annealing_poly(start, end, pct:float, degree): return end + (start-end) * (1-pct)**degree # NOT TO BE MODIFIED class Stepper(): """ Used to step from start, end ('vals') over 'n_iter' iterations on a schedule. We will create a stepper object and then use one of the above annelaing functions, to step from start lr to end lr. """ def __init__(self, vals, n_iter:int, func=None): self.start, self.end = (vals[0], vals[1]) if isinstance(vals, tuple) else (vals,0) self.n_iter = max(1, n_iter) if func is None: self.func = annealing_linear if isinstance(vals, tuple) else annealing_no else: self.func = func self.n = 0 def step(self): "Return next value along annealed schedule" self.n += 1 return self.func(self.start, self.end, self.n/self.n_iter) @property def is_done(self)->bool: "Return 'True' if schedule completed" return self.n >= self.n_iter # NOT TO BE MODIFIED class SmoothenValue(): "Create a smooth moving average for a value (loss, etc) using `beta`." def __init__(self, beta:float): self.beta,self.n,self.mov_avg = beta,0,0 def add_value(self, val:float)->None: "Add `val` to calculate updated smoothed value." self.n += 1 self.mov_avg = self.beta * self.mov_avg + (1 - self.beta) * val self.smooth = self.mov_avg / (1 - self.beta ** self.n) # TO BE MODIFIED IN SOME CASES def lr_find(data_loader, model, loss_fn, opt, wd:int=0, start_lr:float=1e-7, end_lr:float=10, num_it:int=100, stop_div:bool=True, smooth_beta:float=0.98, use_gpu:bool=True, device=torch.device('cuda'), anneal_func=annealing_exp): """ The main function that you will call to plot learning_rate vs losses graph. It is the only function from lr_find.py that you will call. By default it will use GPU. It assumes your model is already on GPU if you use use_gpu. Arguments:- data_loader :- torch.utils.data.DataLoader model :- torch.nn.Module loss_fn :- torch.nn.LossFunction opt :- torch.optim.Optimizer wd :- weight decay (default=0). start_lr :- The learning rate from where to start in lr_find (default=1e-7) end_lr :- The learning rate at which to end lr_find (default=10) num_it :- Number of iterations for lr_find (default=100) stop_div :- If the loss diverges, then stop early (default=True) smooth_beta :- The beta value to smoothen the running avergae of the loss function (default=0.98) use_gpu :- True (train on GPU) else CPU anneal_func :- The step function you want to use (default exp) device :- Torch device to use for training model (default GPU) Returns: losses :- list of smoothened version of losses lrs :- list of all lrs that we test """ model.train() stop = False flag = False best_loss = 0. iteration = 0 losses = [] lrs = [] lrs.append(start_lr) start_lr = lr_range(model, start_lr) start_lr = np.array(start_lr) if isinstance(start_lr, (tuple, list)) else start_lr end_lr = lr_range(model, end_lr) end_lr = np.array(end_lr) if isinstance(end_lr, (tuple, list)) else end_lr sched = Stepper((start_lr, end_lr), num_it, anneal_func) smoothener = SmoothenValue(smooth_beta) epochs = int(np.ceil(num_it/len(data_loader))) # save model_dict model_state = model.state_dict() opt_state = opt.state_dict() # Set optimizer learning_rate = start_lr for group in opt.param_groups: group['lr'] = sched.start for i in range(epochs): for data in data_loader: opt.zero_grad() ################### TO BE MODIFIED ################### # Depending on your model, you will have to modify your # data pipeline and how you give inputs to your model. inputs, labels = data if use_gpu: inputs = inputs.to(device) labels = labels.to(device) outputs = model(inputs) loss = loss_fn(outputs, labels) ##################################################### if use_gpu: smoothener.add_value(loss.detach().cpu()) else: smoothener.add_value(loss.detach()) smooth_loss = smoothener.smooth losses.append(smooth_loss) loss.backward() ################### TO BE MODIFIED ################### # For AdamW. If you want to use Adam, comment these lines for group in opt.param_groups: for param in group['params']: param.data = param.data.add(-wd * group['lr'], param.data) ##################################################### opt.step() # Change lr new_lr = sched.step() lrs.append(new_lr) for group in opt.param_groups: group['lr'] = new_lr ################### TO BE MODIFIED ################### # You necessarily don't want to change it. But in cases # when you are maximizing the loss, then you will have # to change it. if iteration == 0 or smooth_loss < best_loss: best_loss = smooth_loss iteration += 1 if sched.is_done or (stop_div and (smooth_loss > 4*best_loss or torch.isnan(loss))): flag = True break ##################################################### if iteration%10 == 0: print(f'Iteration: {iteration}') if flag: break # Load state dict model.load_state_dict(model_state) opt.load_state_dict(opt_state) lrs.pop() print(f'LR Finder is complete.') return losses, lrs # NOT TO BE MODIFIED def plot_lr_find(losses, lrs, skip_start:int=10, skip_end:int=5, suggestion:bool=False, return_fig:bool=None): """ It will take the losses and lrs returned by lr_find as input. Arguments:- skip_start -> It will skip skip_start lrs from the start skip_end -> It will skip skip_end lrs from the end suggestion -> If you want to see the point where the gradient changes most return_fig -> True then get the fig in the return statement """ lrs = lrs[skip_start:-skip_end] if skip_end > 0 else lrs[skip_start:] losses = losses[skip_start:-skip_end] if skip_end > 0 else losses[skip_start:] losses = [x.item() for x in losses] fig, ax = plt.subplots(1, 1) ax.plot(lrs, losses) ax.set_ylabel("Loss") ax.set_xlabel("Learning Rate") ax.set_xscale('log') ax.xaxis.set_major_formatter(plt.FormatStrFormatter('%.0e')) if suggestion: try: mg = (np.gradient(np.array(losses))).argmin() except: print("Failed to compute the gradients, there might not be enough points.") return print(f"Min numerical gradient: {lrs[mg]:.2E}") ax.plot(lrs[mg], losses[mg], markersize=10, marker='o', color='red') if return_fig is not None: return fig
[ "numpy.array", "matplotlib.pyplot.FormatStrFormatter", "numpy.cos", "torch.isnan", "matplotlib.pyplot.subplots", "torch.device" ]
[((1675, 1688), 'numpy.array', 'np.array', (['res'], {}), '(res)\n', (1683, 1688), True, 'import numpy as np\n'), ((4280, 4300), 'torch.device', 'torch.device', (['"""cuda"""'], {}), "('cuda')\n", (4292, 4300), False, 'import torch\n'), ((9315, 9333), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {}), '(1, 1)\n', (9327, 9333), True, 'import matplotlib.pyplot as plt\n'), ((2498, 2517), 'numpy.cos', 'np.cos', (['(np.pi * pct)'], {}), '(np.pi * pct)\n', (2504, 2517), True, 'import numpy as np\n'), ((5705, 5723), 'numpy.array', 'np.array', (['start_lr'], {}), '(start_lr)\n', (5713, 5723), True, 'import numpy as np\n'), ((5827, 5843), 'numpy.array', 'np.array', (['end_lr'], {}), '(end_lr)\n', (5835, 5843), True, 'import numpy as np\n'), ((9478, 9508), 'matplotlib.pyplot.FormatStrFormatter', 'plt.FormatStrFormatter', (['"""%.0e"""'], {}), "('%.0e')\n", (9500, 9508), True, 'import matplotlib.pyplot as plt\n'), ((8153, 8170), 'torch.isnan', 'torch.isnan', (['loss'], {}), '(loss)\n', (8164, 8170), False, 'import torch\n'), ((9573, 9589), 'numpy.array', 'np.array', (['losses'], {}), '(losses)\n', (9581, 9589), True, 'import numpy as np\n')]
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. """ Calibration Controller Performs calibration for hue, center of camera position, and servo offsets """ import os import cv2 import time import json import argparse import datetime import numpy as np import logging as log from env import MoabEnv from typing import Tuple from common import Vector2 from detector import hsv_detector from controllers import pid_controller from dataclasses import dataclass, astuple from hardware import plate_angles_to_servo_positions @dataclass class CalibHue: hue: int = 44 # Reasonable default success: bool = False early_quit: bool = False # If menu is pressed before the calibration is complete def __iter__(self): return iter(astuple(self)) @dataclass class CalibPos: position: Tuple[float, float] = (0.0, 0.0) success: bool = False early_quit: bool = False # If menu is pressed before the calibration is complete def __iter__(self): return iter(astuple(self)) @dataclass class CalibServos: servos: Tuple[float, float, float] = (0.0, 0.0, 0.0) success: bool = False early_quit: bool = False # If menu is pressed before the calibration is complete def __iter__(self): return iter(astuple(self)) def ball_close_enough(x, y, radius, max_ball_dist=0.045, min_ball_dist=0.01): # reject balls which are too far from the center and too small return ( np.abs(x) < max_ball_dist and np.abs(y) < max_ball_dist and radius > min_ball_dist ) def calibrate_hue(camera_fn, detector_fn, is_menu_down_fn): hue_low = 0 hue_high = 360 hue_steps = 41 # Is 41 instead of 40 so that the steps are even img_frame, elapsed_time = camera_fn() hue_options = list(np.linspace(hue_low, hue_high, hue_steps)) detected_hues = [] for hue in hue_options: if is_menu_down_fn(): return CalibHue(early_quit=True) img_frame, elapsed_time = camera_fn() ball_detected, ((x, y), radius) = detector_fn(img_frame, hue=hue, debug=True) # If we found a ball roughly in the center that is large enough if ball_detected and ball_close_enough(x, y, radius): log.info( f"hue={hue:0.3f}, ball_detected={ball_detected}, " f"(x, y)={x:0.3f} {y:0.3f}, radius={radius:0.3f}" ) detected_hues.append(hue) if len(detected_hues) > 0: # https://en.wikipedia.org/wiki/Mean_of_circular_quantities detected_hues_rad = np.radians(detected_hues) sines, cosines = np.sin(detected_hues_rad), np.cos(detected_hues_rad) sin_mean, cos_mean = np.mean(sines), np.mean(cosines) avg_hue_rad = np.arctan2(sin_mean, cos_mean) avg_hue = np.degrees(avg_hue_rad) % 360 # Convert back to [0, 360] print(f"Hues are: {detected_hues}") print(f"Hue calibrated: {avg_hue:0.2f}") print(f"Avg hue: {avg_hue:0.2f}") return CalibHue(hue=int(avg_hue), success=True) else: log.warning(f"Hue calibration failed.") return CalibHue() def calibrate_pos(camera_fn, detector_fn, hue, is_menu_down_fn): for i in range(10): # Try and detect for 10 frames before giving up if is_menu_down_fn(): return CalibPos(early_quit=True) img_frame, elapsed_time = camera_fn() ball_detected, ((x, y), radius) = detector_fn(img_frame, hue=hue) # If we found a ball roughly in the center that is large enough if ball_detected and ball_close_enough(x, y, radius): x_offset = round(x, 3) y_offset = round(y, 3) log.info(f"Offset calibrated: [{x_offset:.3f}, {y_offset:.3f}]") return CalibPos(position=(x_offset, y_offset), success=True) log.warning(f"Offset calibration failed.") return CalibPos() def calibrate_servo_offsets(pid_fn, env, stationary_vel=0.005, time_limit=20): start_time = time.time() action = Vector2(0, 0) # Initial high vel_history (to use the vel_hist[-100:] later) vel_x_hist = [1.0 for _ in range(100)] vel_y_hist = [1.0 for _ in range(100)] # Run until the ball has stabilized or the time limit was reached while time.time() < start_time + time_limit: state = env.step(action) action, info = pid_fn(state) (x, y, vel_x, vel_y, sum_x, sum_y), ball_detected, buttons = state # Quit on menu down if buttons.menu_button: return CalibServos(early_quit=True) if ball_detected: vel_x_hist.append(vel_x) vel_y_hist.append(vel_y) prev_100_x = np.mean(np.abs(vel_x_hist[-100:])) prev_100_y = np.mean(np.abs(vel_y_hist[-100:])) print("Prev 100: ", (prev_100_x, prev_100_y)) # If the average velocity for the last 100 timesteps is under the limit if (prev_100_x < stationary_vel) and (prev_100_y < stationary_vel): # Calculate offsets by calculating servo positions at the # current stable position and subtracting the `default` zeroed # position of the servos. servos = np.array(plate_angles_to_servo_positions(*action)) servos_zeroed = np.array(plate_angles_to_servo_positions(0, 0)) servo_offsets = list(servos - servos_zeroed) return CalibServos(servos=servo_offsets, success=True) # If the plate could be stabilized in time_limit seconds, quit log.warning(f"Servo calibration failed.") return CalibServos() def write_calibration(calibration_dict, calibration_file="bot.json"): log.info("Writing calibration.") # write out stuff with open(calibration_file, "w+") as outfile: log.info(f"Creating calibration file {calibration_file}") json.dump(calibration_dict, outfile, indent=4, sort_keys=True) def read_calibration(calibration_file="bot.json"): log.info("Reading previous calibration.") if os.path.isfile(calibration_file): with open(calibration_file, "r") as f: calibration_dict = json.load(f) else: # Use defaults calibration_dict = { "ball_hue": 44, "plate_offsets": (0.0, 0.0), "servo_offsets": (0.0, 0.0, 0.0), } return calibration_dict def wait_for_joystick_or_menu(hardware, sleep_time=1 / 30): """Waits for either the joystick or the menu. Returns the buttons""" while True: buttons = hardware.get_buttons() if buttons.menu_button or buttons.joy_button: return buttons time.sleep(sleep_time) def wait_for_menu(hardware, sleep_time=1 / 30): while True: menu_button, joy_button, joy_x, joy_y = hardware.get_buttons() time.sleep(sleep_time) if menu_button: return def run_calibration(env, pid_fn, calibration_file): # Get some hidden things from env hardware = env.hardware camera_fn = hardware.camera detector_fn = hardware.detector def is_menu_down(hardware=hardware) -> bool: return hardware.get_buttons().menu_button # lift plate up first hardware.set_angles(0, 0) # Display message and wait for joystick hardware.display( "put ball on stand\nclick joystick", # "Place ball in\ncenter using\nclear stand.\n\n" "Click joystick\nwhen ready." scrolling=True, ) buttons = wait_for_joystick_or_menu(hardware) if buttons.menu_button: # Early quit hardware.go_up() return hardware.display("Calibrating...") hue_calib = calibrate_hue(camera_fn, detector_fn, is_menu_down) if hue_calib.early_quit: hardware.go_up() return # Calibrate position pos_calib = calibrate_pos(camera_fn, detector_fn, hue_calib.hue, is_menu_down) if pos_calib.early_quit: hardware.go_up() return # Save calibration calibration_dict = read_calibration(calibration_file) calibration_dict["ball_hue"] = hue_calib.hue calibration_dict["plate_offsets"] = pos_calib.position x_offset, y_offset = pos_calib.position write_calibration(calibration_dict) # Update the environment to use the new calibration # Warning! This mutates the state! hardware.reset_calibration(calibration_file=calibration_file) if pos_calib.success and hue_calib.success: # and servo_calib.success: hardware.display(f"Ok! Ball hue={hue_calib.hue}\nClick menu...", scrolling=True) elif not (pos_calib.success or hue_calib.success): # or servo_calib.success): hardware.display("Calibration failed\nClick menu...", scrolling=True) else: hue_str = ( f"Hue calib:\nsuccessful\nBall hue = {hue_calib.hue}\n\n" if hue_calib.success else "Hue calib:\nfailed\n\n" ) pos_str = ( f"Position \ncalib:\nsuccessful\nPosition = \n({100*x_offset:.1f}, {100*y_offset:.1f})cm\n\n" if hue_calib.success else "(X, Y) calib:\nfailed\n\n" ) hardware.display( "Calibration\npartially succeeded\n\n" + hue_str + pos_str + "Click menu\nto return...\n", scrolling=True, ) # When the calibration is complete, save the image of what the moab camera # sees (useful for debugging when the hue calibration fails) # Have a nice filename with the time and whether it succeeded or failed time_of_day = datetime.datetime.now().strftime("%H%M%S") filename = "/tmp/hue" if hue_calib.success: filename += f".{hue_calib.hue}.{time_of_day}.jpg" else: filename += f".fail.{time_of_day}.jpg" img_frame, _ = camera_fn() # Huemask keeps an internal cache. By sending a new hue (hue + 1) invalidates # the cache. TODO: added this while searching for a state bug detector_fn(img_frame, hue=hue_calib.hue + 1, debug=True, filename=filename) hardware.go_up() def run_servo_calibration(env, pid_fn, calibration_file): # Warning: servo calib works but doesn't currently give a good calibration raise NotImplementedError # Get some hidden things from env hardware = env.hardware camera_fn = hardware.camera detector_fn = hardware.detector # Start the calibration with uncalibrated servos hardware.servo_offsets = (0, 0, 0) # lift plate up fist hardware.set_angles(0, 0) # Calibrate servo offsets hardware.display( "Calibarating\nservos\n\n" "Place ball in\ncenter without\n stand.\n\n" "Click joystick\nto continue.", scrolling=True, ) buttons = wait_for_joystick_or_menu(hardware) if buttons.menu_button: # Early quit hardware.go_up() return hardware.display("Calibrating\nservos...", scrolling=True) servo_calib = calibrate_servo_offsets(pid_fn, env) # Save calibration calibration_dict = read_calibration(calibration_file) calibration_dict["servo_offsets"] = servo_calib.servos s1, s2, s3 = servo_calib.servos write_calibration(calibration_dict) # Update the environment to use the new calibration # Warning! This mutates the state! env.reset_calibration(calibration_file=calibration_file) if servo_calib.success: hardware.display( f"servo offsets =\n({s1:.2f}, {s2:.2f}, {s3:.2f})\n\n" "Click menu\nto return...\n", scrolling=True, ) print(f"servo offsets =\n({s1:.2f}, {s2:.2f}, {s3:.2f})") else: hardware.display( "Calibration\nfailed\n\nClick menu\nto return...", scrolling=True ) hardware.go_up() def calibrate_controller(**kwargs): run_calibration( kwargs["env"], kwargs["pid_fn"], kwargs["calibration_file"], ) def wait_for_menu_and_stream(): # Get some hidden things from env to be able to stream the calib results env = kwargs["env"] hardware = env.hardware camera_fn = hardware.camera detector_fn = hardware.detector menu_button = False while not menu_button: img_frame, _ = camera_fn() detector_fn(img_frame, debug=True) # Save to streaming menu, joy, _, _ = hardware.get_buttons() if menu or joy: break env.hardware.go_up() return wait_for_menu_and_stream def main(calibration_file, frequency=30, debug=True): pid_fn = pid_controller(frequency=frequency) with MoabEnv(frequency=frequency, debug=debug) as env: env.step((0, 0)) time.sleep(0.2) env.hardware.enable_servos() time.sleep(0.2) env.hardware.set_servos(133, 133, 133) run_calibration(env, pid_fn, calibration_file) env.hardware.disable_servos() if __name__ == "__main__": # Parse command line args parser = argparse.ArgumentParser() parser.add_argument("-d", "--debug", action="store_true") parser.add_argument("-f", "--file", default="bot.json", type=str) args, _ = parser.parse_known_args() main(args.file, debug=args.debug)
[ "numpy.radians", "time.sleep", "numpy.arctan2", "numpy.sin", "logging.info", "hardware.plate_angles_to_servo_positions", "numpy.mean", "argparse.ArgumentParser", "env.MoabEnv", "numpy.linspace", "numpy.degrees", "numpy.abs", "controllers.pid_controller", "logging.warning", "os.path.isfile", "numpy.cos", "time.time", "dataclasses.astuple", "datetime.datetime.now", "common.Vector2", "json.load", "json.dump" ]
[((3843, 3885), 'logging.warning', 'log.warning', (['f"""Offset calibration failed."""'], {}), "(f'Offset calibration failed.')\n", (3854, 3885), True, 'import logging as log\n'), ((4006, 4017), 'time.time', 'time.time', ([], {}), '()\n', (4015, 4017), False, 'import time\n'), ((4031, 4044), 'common.Vector2', 'Vector2', (['(0)', '(0)'], {}), '(0, 0)\n', (4038, 4044), False, 'from common import Vector2\n'), ((5574, 5615), 'logging.warning', 'log.warning', (['f"""Servo calibration failed."""'], {}), "(f'Servo calibration failed.')\n", (5585, 5615), True, 'import logging as log\n'), ((5717, 5749), 'logging.info', 'log.info', (['"""Writing calibration."""'], {}), "('Writing calibration.')\n", (5725, 5749), True, 'import logging as log\n'), ((6017, 6058), 'logging.info', 'log.info', (['"""Reading previous calibration."""'], {}), "('Reading previous calibration.')\n", (6025, 6058), True, 'import logging as log\n'), ((6067, 6099), 'os.path.isfile', 'os.path.isfile', (['calibration_file'], {}), '(calibration_file)\n', (6081, 6099), False, 'import os\n'), ((12588, 12623), 'controllers.pid_controller', 'pid_controller', ([], {'frequency': 'frequency'}), '(frequency=frequency)\n', (12602, 12623), False, 'from controllers import pid_controller\n'), ((13005, 13030), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (13028, 13030), False, 'import argparse\n'), ((1801, 1842), 'numpy.linspace', 'np.linspace', (['hue_low', 'hue_high', 'hue_steps'], {}), '(hue_low, hue_high, hue_steps)\n', (1812, 1842), True, 'import numpy as np\n'), ((2574, 2599), 'numpy.radians', 'np.radians', (['detected_hues'], {}), '(detected_hues)\n', (2584, 2599), True, 'import numpy as np\n'), ((2762, 2792), 'numpy.arctan2', 'np.arctan2', (['sin_mean', 'cos_mean'], {}), '(sin_mean, cos_mean)\n', (2772, 2792), True, 'import numpy as np\n'), ((3080, 3119), 'logging.warning', 'log.warning', (['f"""Hue calibration failed."""'], {}), "(f'Hue calibration failed.')\n", (3091, 3119), True, 'import logging as log\n'), ((4279, 4290), 'time.time', 'time.time', ([], {}), '()\n', (4288, 4290), False, 'import time\n'), ((5831, 5888), 'logging.info', 'log.info', (['f"""Creating calibration file {calibration_file}"""'], {}), "(f'Creating calibration file {calibration_file}')\n", (5839, 5888), True, 'import logging as log\n'), ((5897, 5959), 'json.dump', 'json.dump', (['calibration_dict', 'outfile'], {'indent': '(4)', 'sort_keys': '(True)'}), '(calibration_dict, outfile, indent=4, sort_keys=True)\n', (5906, 5959), False, 'import json\n'), ((6681, 6703), 'time.sleep', 'time.sleep', (['sleep_time'], {}), '(sleep_time)\n', (6691, 6703), False, 'import time\n'), ((6849, 6871), 'time.sleep', 'time.sleep', (['sleep_time'], {}), '(sleep_time)\n', (6859, 6871), False, 'import time\n'), ((12634, 12675), 'env.MoabEnv', 'MoabEnv', ([], {'frequency': 'frequency', 'debug': 'debug'}), '(frequency=frequency, debug=debug)\n', (12641, 12675), False, 'from env import MoabEnv\n'), ((12717, 12732), 'time.sleep', 'time.sleep', (['(0.2)'], {}), '(0.2)\n', (12727, 12732), False, 'import time\n'), ((12778, 12793), 'time.sleep', 'time.sleep', (['(0.2)'], {}), '(0.2)\n', (12788, 12793), False, 'import time\n'), ((772, 785), 'dataclasses.astuple', 'astuple', (['self'], {}), '(self)\n', (779, 785), False, 'from dataclasses import dataclass, astuple\n'), ((1020, 1033), 'dataclasses.astuple', 'astuple', (['self'], {}), '(self)\n', (1027, 1033), False, 'from dataclasses import dataclass, astuple\n'), ((1281, 1294), 'dataclasses.astuple', 'astuple', (['self'], {}), '(self)\n', (1288, 1294), False, 'from dataclasses import dataclass, astuple\n'), ((1464, 1473), 'numpy.abs', 'np.abs', (['x'], {}), '(x)\n', (1470, 1473), True, 'import numpy as np\n'), ((1502, 1511), 'numpy.abs', 'np.abs', (['y'], {}), '(y)\n', (1508, 1511), True, 'import numpy as np\n'), ((2251, 2367), 'logging.info', 'log.info', (['f"""hue={hue:0.3f}, ball_detected={ball_detected}, (x, y)={x:0.3f} {y:0.3f}, radius={radius:0.3f}"""'], {}), "(\n f'hue={hue:0.3f}, ball_detected={ball_detected}, (x, y)={x:0.3f} {y:0.3f}, radius={radius:0.3f}'\n )\n", (2259, 2367), True, 'import logging as log\n'), ((2625, 2650), 'numpy.sin', 'np.sin', (['detected_hues_rad'], {}), '(detected_hues_rad)\n', (2631, 2650), True, 'import numpy as np\n'), ((2652, 2677), 'numpy.cos', 'np.cos', (['detected_hues_rad'], {}), '(detected_hues_rad)\n', (2658, 2677), True, 'import numpy as np\n'), ((2707, 2721), 'numpy.mean', 'np.mean', (['sines'], {}), '(sines)\n', (2714, 2721), True, 'import numpy as np\n'), ((2723, 2739), 'numpy.mean', 'np.mean', (['cosines'], {}), '(cosines)\n', (2730, 2739), True, 'import numpy as np\n'), ((2811, 2834), 'numpy.degrees', 'np.degrees', (['avg_hue_rad'], {}), '(avg_hue_rad)\n', (2821, 2834), True, 'import numpy as np\n'), ((3700, 3764), 'logging.info', 'log.info', (['f"""Offset calibrated: [{x_offset:.3f}, {y_offset:.3f}]"""'], {}), "(f'Offset calibrated: [{x_offset:.3f}, {y_offset:.3f}]')\n", (3708, 3764), True, 'import logging as log\n'), ((6179, 6191), 'json.load', 'json.load', (['f'], {}), '(f)\n', (6188, 6191), False, 'import json\n'), ((9582, 9605), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (9603, 9605), False, 'import datetime\n'), ((4707, 4732), 'numpy.abs', 'np.abs', (['vel_x_hist[-100:]'], {}), '(vel_x_hist[-100:])\n', (4713, 4732), True, 'import numpy as np\n'), ((4767, 4792), 'numpy.abs', 'np.abs', (['vel_y_hist[-100:]'], {}), '(vel_y_hist[-100:])\n', (4773, 4792), True, 'import numpy as np\n'), ((5247, 5287), 'hardware.plate_angles_to_servo_positions', 'plate_angles_to_servo_positions', (['*action'], {}), '(*action)\n', (5278, 5287), False, 'from hardware import plate_angles_to_servo_positions\n'), ((5330, 5367), 'hardware.plate_angles_to_servo_positions', 'plate_angles_to_servo_positions', (['(0)', '(0)'], {}), '(0, 0)\n', (5361, 5367), False, 'from hardware import plate_angles_to_servo_positions\n')]
import cv2 import os import numpy as np from PIL import Image def frame2video(im_dir, video_dir, fps): im_list = os.listdir(im_dir) im_list.sort(key=lambda x: int(x.replace("_RBPNF7", "").split('.')[0])) img = Image.open(os.path.join(im_dir, im_list[0])) img_size = img.size # 获得图片分辨率,im_dir文件夹下的图片分辨率需要一致 fourcc = cv2.VideoWriter_fourcc(*'XVID') videoWriter = cv2.VideoWriter(video_dir, fourcc, fps, img_size) for i in im_list: im_name = os.path.join(im_dir + i) frame = cv2.imdecode(np.fromfile(im_name, dtype=np.uint8), -1) videoWriter.write(frame) videoWriter.release() if __name__ == '__main__': im_dir = '/media/hy/Seagate Expansion Drive/Results/merge_dir/' # 帧存放路径 video_dir = '/media/hy/Seagate Expansion Drive/Results/sandy.mp4' # 合成视频存放的路径 fps = 15 # 帧率 frame2video(im_dir, video_dir, fps)
[ "numpy.fromfile", "os.listdir", "os.path.join", "cv2.VideoWriter", "cv2.VideoWriter_fourcc" ]
[((119, 137), 'os.listdir', 'os.listdir', (['im_dir'], {}), '(im_dir)\n', (129, 137), False, 'import os\n'), ((338, 369), 'cv2.VideoWriter_fourcc', 'cv2.VideoWriter_fourcc', (["*'XVID'"], {}), "(*'XVID')\n", (360, 369), False, 'import cv2\n'), ((388, 437), 'cv2.VideoWriter', 'cv2.VideoWriter', (['video_dir', 'fourcc', 'fps', 'img_size'], {}), '(video_dir, fourcc, fps, img_size)\n', (403, 437), False, 'import cv2\n'), ((235, 267), 'os.path.join', 'os.path.join', (['im_dir', 'im_list[0]'], {}), '(im_dir, im_list[0])\n', (247, 267), False, 'import os\n'), ((478, 502), 'os.path.join', 'os.path.join', (['(im_dir + i)'], {}), '(im_dir + i)\n', (490, 502), False, 'import os\n'), ((532, 568), 'numpy.fromfile', 'np.fromfile', (['im_name'], {'dtype': 'np.uint8'}), '(im_name, dtype=np.uint8)\n', (543, 568), True, 'import numpy as np\n')]
from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt import matplotlib.colors as colors from numpy import array from numpy import max map = Basemap(llcrnrlon=-0.5,llcrnrlat=39.8,urcrnrlon=4.,urcrnrlat=43., resolution='i', projection='tmerc', lat_0 = 39.5, lon_0 = 1) map.readshapefile('../sample_files/lightnings', 'lightnings') x = [] y = [] c = [] for info, lightning in zip(map.lightnings_info, map.lightnings): x.append(lightning[0]) y.append(lightning[1]) if float(info['amplitude']) < 0: c.append(-1 * float(info['amplitude'])) else: c.append(float(info['amplitude'])) plt.figure(0) map.drawcoastlines() map.readshapefile('../sample_files/comarques', 'comarques') map.hexbin(array(x), array(y)) map.colorbar(location='bottom') plt.figure(1) map.drawcoastlines() map.readshapefile('../sample_files/comarques', 'comarques') map.hexbin(array(x), array(y), gridsize=20, mincnt=1, cmap='summer', bins='log') map.colorbar(location='bottom', format='%.1f', label='log(# lightnings)') plt.figure(2) map.drawcoastlines() map.readshapefile('../sample_files/comarques', 'comarques') map.hexbin(array(x), array(y), gridsize=20, mincnt=1, cmap='summer', norm=colors.LogNorm()) cb = map.colorbar(location='bottom', format='%d', label='# lightnings') cb.set_ticks([1, 5, 10, 15, 20, 25, 30]) cb.set_ticklabels([1, 5, 10, 15, 20, 25, 30]) plt.figure(3) map.drawcoastlines() map.readshapefile('../sample_files/comarques', 'comarques') map.hexbin(array(x), array(y), C = array(c), reduce_C_function = max, gridsize=20, mincnt=1, cmap='YlOrBr', linewidths=0.5, edgecolors='k') map.colorbar(location='bottom', label='Mean amplitude (kA)') plt.show()
[ "matplotlib.pyplot.show", "numpy.array", "mpl_toolkits.basemap.Basemap", "matplotlib.pyplot.figure", "matplotlib.colors.LogNorm" ]
[((162, 293), 'mpl_toolkits.basemap.Basemap', 'Basemap', ([], {'llcrnrlon': '(-0.5)', 'llcrnrlat': '(39.8)', 'urcrnrlon': '(4.0)', 'urcrnrlat': '(43.0)', 'resolution': '"""i"""', 'projection': '"""tmerc"""', 'lat_0': '(39.5)', 'lon_0': '(1)'}), "(llcrnrlon=-0.5, llcrnrlat=39.8, urcrnrlon=4.0, urcrnrlat=43.0,\n resolution='i', projection='tmerc', lat_0=39.5, lon_0=1)\n", (169, 293), False, 'from mpl_toolkits.basemap import Basemap\n'), ((656, 669), 'matplotlib.pyplot.figure', 'plt.figure', (['(0)'], {}), '(0)\n', (666, 669), True, 'import matplotlib.pyplot as plt\n'), ((820, 833), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)'], {}), '(1)\n', (830, 833), True, 'import matplotlib.pyplot as plt\n'), ((1076, 1089), 'matplotlib.pyplot.figure', 'plt.figure', (['(2)'], {}), '(2)\n', (1086, 1089), True, 'import matplotlib.pyplot as plt\n'), ((1430, 1443), 'matplotlib.pyplot.figure', 'plt.figure', (['(3)'], {}), '(3)\n', (1440, 1443), True, 'import matplotlib.pyplot as plt\n'), ((1731, 1741), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1739, 1741), True, 'import matplotlib.pyplot as plt\n'), ((764, 772), 'numpy.array', 'array', (['x'], {}), '(x)\n', (769, 772), False, 'from numpy import array\n'), ((774, 782), 'numpy.array', 'array', (['y'], {}), '(y)\n', (779, 782), False, 'from numpy import array\n'), ((928, 936), 'numpy.array', 'array', (['x'], {}), '(x)\n', (933, 936), False, 'from numpy import array\n'), ((938, 946), 'numpy.array', 'array', (['y'], {}), '(y)\n', (943, 946), False, 'from numpy import array\n'), ((1184, 1192), 'numpy.array', 'array', (['x'], {}), '(x)\n', (1189, 1192), False, 'from numpy import array\n'), ((1194, 1202), 'numpy.array', 'array', (['y'], {}), '(y)\n', (1199, 1202), False, 'from numpy import array\n'), ((1538, 1546), 'numpy.array', 'array', (['x'], {}), '(x)\n', (1543, 1546), False, 'from numpy import array\n'), ((1548, 1556), 'numpy.array', 'array', (['y'], {}), '(y)\n', (1553, 1556), False, 'from numpy import array\n'), ((1247, 1263), 'matplotlib.colors.LogNorm', 'colors.LogNorm', ([], {}), '()\n', (1261, 1263), True, 'import matplotlib.colors as colors\n'), ((1562, 1570), 'numpy.array', 'array', (['c'], {}), '(c)\n', (1567, 1570), False, 'from numpy import array\n')]
# test_fluxqubit.py # meant to be run with 'pytest' # # This file is part of scqubits. # # Copyright (c) 2019 and later, <NAME> and <NAME> # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. ############################################################################ import numpy as np from scqubits import FluxQubit from scqubits.tests.conftest import StandardTests class TestFluxQubit(StandardTests): @classmethod def setup_class(cls): cls.qbt = None cls.qbt_type = FluxQubit cls.file_str = "fluxqubit" cls.op1_str = "n_1_operator" cls.op2_str = "n_2_operator" cls.param_name = "flux" cls.param_list = np.linspace(0.45, 0.55, 50)
[ "numpy.linspace" ]
[((788, 815), 'numpy.linspace', 'np.linspace', (['(0.45)', '(0.55)', '(50)'], {}), '(0.45, 0.55, 50)\n', (799, 815), True, 'import numpy as np\n')]
from calendar import c from typing import Dict, List, Union from zlib import DEF_BUF_SIZE import json_lines import numpy as np import re from sklearn.preprocessing import MultiLabelBinarizer from sklearn.manifold import TSNE from sklearn.preprocessing import StandardScaler import pandas as pd import json from scipy.sparse.linalg import svds from scipy.spatial import distance import os import streamlit as st def preprocess_ingredients(ingredients): processed_ingredients = [] for i in range(len(ingredients)): processed_ingredient = re.sub( r"\(([^)]*)\)|(([0-9]\d{0,2}(\.\d{1,3})*(,\d+)?)(%|mg|units))|(<\/?i>)|(\/.+)|(\\.+)|\[([^\]]*)\]", "", ingredients[i], ).strip() if ( processed_ingredient.lower() == "water" or processed_ingredient.lower() == "aqua" or processed_ingredient.lower() == "eau" ): processed_ingredient = "Water" processed_ingredients.append(processed_ingredient) return processed_ingredients @st.experimental_memo def content_recommender(opt, _item1, _item2, _item3, df) -> pd.DataFrame: content_df = df[df.category == opt] content_df["ingredients"] = content_df["ingredients"].map(preprocess_ingredients) mlb = MultiLabelBinarizer() output = mlb.fit_transform(content_df.ingredients.values) content_df = content_df.drop(["ingredients"], axis=1) model = TSNE(n_components=2, learning_rate=200) tsne_features = model.fit_transform(output) content_df["X"] = tsne_features[:, 0] content_df["Y"] = tsne_features[:, 1] content_df["dist"] = 0.0 item1 = content_df[content_df["product_name"] == _item1] item2 = content_df[content_df["product_name"] == _item2] item3 = content_df[content_df["product_name"] == _item3] p1 = np.array([item1["X"], item1["Y"]]).reshape(1, -1) p2 = np.array([item2["X"], item2["Y"]]).reshape(1, -1) p3 = np.array([item3["X"], item3["Y"]]).reshape(1, -1) for ind, item in content_df.iterrows(): pn = np.array([item.X, item.Y]).reshape(-1, 1) df.at[ind, "dist"] = min( distance.chebyshev(p1, pn), distance.chebyshev(p2, pn), distance.chebyshev(p3, pn), ) content_df = content_df[~content_df.product_name.isin([_item1, _item2, _item3])] content_df = content_df.sort_values("dist") return content_df @st.experimental_memo def collab_recommender(df_tmp, num_recs, username): reviews = df_tmp.explode("review_data") reviews["username"] = reviews["review_data"].apply(lambda x: x["UserNickname"]) reviews["rating"] = reviews["review_data"].apply(lambda x: x["Rating"]) grouped_reviews = reviews.groupby("username")["review_data"].apply(list) multiple_rating_users = set(grouped_reviews[grouped_reviews.map(len) > 1].index) multi_reviews = reviews[reviews.username.isin(multiple_rating_users)] products_reviewed_per_user = {u: set() for u in multiple_rating_users} product_index = dict(zip(df_tmp["url"].values, range(len(df_tmp["url"])))) username_index = dict(zip(multiple_rating_users, range(len(multiple_rating_users)))) matrix = np.zeros((len(multiple_rating_users), len(df_tmp["url"]))) for user, rating, url in zip( multi_reviews.username.values, multi_reviews.rating.values, multi_reviews.url.values, ): matrix[username_index[user]][product_index[url]] = rating products_reviewed_per_user[user].add(url) ss = StandardScaler() normatrix = ss.fit_transform(matrix) print(normatrix) U, S, V = svds(normatrix) all_user_predicted_rating = ss.inverse_transform(U @ np.diag(S) @ V) preds_df = pd.DataFrame( all_user_predicted_rating, columns=product_index, index=username_index ) sorted_user_preds = preds_df.loc[username].sort_values(ascending=False) sorted_user_preds = sorted_user_preds[ ~sorted_user_preds.index.isin(products_reviewed_per_user[username]) ] sorted_user_preds = sorted_user_preds.head(num_recs) # we want those that they haven't already tested collab_df = pd.merge( df_tmp, sorted_user_preds.to_frame(), left_on="url", right_index=True, how="right", ) collab_df.rename(columns={username: "pred_rating"}, inplace=True) return collab_df if __name__ == "__main__": file_path = os.path.dirname(__file__) if file_path != "": os.chdir(file_path) products: List[Dict[str, Union[str, List[str]]]] = [] # input data into List with open("../cbscraper/product_urls_with_reviews.jsonlines", "rb") as f: unique = set() lines = f.read().splitlines() df_inter = pd.DataFrame(lines) df_inter.columns = ["json_element"] df_inter["json_element"].apply(json.loads) df = pd.json_normalize(df_inter["json_element"].apply(json.loads)) # to save myself if i do something dumb and run the scraper without deleting the .jsonlines file df.drop_duplicates(subset=["url"], inplace=True) # option: category of product, eg cleanser categories = set(df.category.values) # filter data by given option print("Hello world!") print("Welcome!") print(categories) print("pls enter the category:") cat = str(input()) display_product_names = df[df.category == cat] print(display_product_names[["brand", "product_name"]]) print("pls enter your top 3 products indices, separated by a new line") item1 = int(input()) item2 = int(input()) item3 = int(input()) print("pls enter # of recs:") num_recs = int(input()) reviews = display_product_names.explode("review_data") reviews["username"] = reviews["review_data"].apply(lambda x: x["UserNickname"]) grouped_reviews = reviews.groupby("username")["review_data"].apply(list) multiple_rating_users = set(grouped_reviews[grouped_reviews.map(len) > 1].index) print(multiple_rating_users) print("pls enter sephora userid, if you don't have one just enter 'none':") username = str(input()) if username == "none": print("your ingredients based recommendations are:") cbf = content_recommender( cat, df.product_name.values[item1], df.product_name.values[item2], df.product_name.values[item3], num_recs, df, ) print(cbf[["brand", "product_name", "url", "avg_rating"]]) else: cbf = content_recommender( cat, df.product_name.values[item1], df.product_name.values[item2], df.product_name.values[item3], num_recs + 10, df, ) cf = collab_recommender(cbf, num_recs, username) print("your hybrid recommendations are:") print(cf[["brand", "product_name", "url", "pred_rating"]]) print("thank u for using this service :)")
[ "sklearn.manifold.TSNE", "numpy.diag", "sklearn.preprocessing.StandardScaler", "os.path.dirname", "os.chdir", "numpy.array", "scipy.sparse.linalg.svds", "scipy.spatial.distance.chebyshev", "pandas.DataFrame", "re.sub", "sklearn.preprocessing.MultiLabelBinarizer" ]
[((1288, 1309), 'sklearn.preprocessing.MultiLabelBinarizer', 'MultiLabelBinarizer', ([], {}), '()\n', (1307, 1309), False, 'from sklearn.preprocessing import MultiLabelBinarizer\n'), ((1442, 1481), 'sklearn.manifold.TSNE', 'TSNE', ([], {'n_components': '(2)', 'learning_rate': '(200)'}), '(n_components=2, learning_rate=200)\n', (1446, 1481), False, 'from sklearn.manifold import TSNE\n'), ((3533, 3549), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (3547, 3549), False, 'from sklearn.preprocessing import StandardScaler\n'), ((3626, 3641), 'scipy.sparse.linalg.svds', 'svds', (['normatrix'], {}), '(normatrix)\n', (3630, 3641), False, 'from scipy.sparse.linalg import svds\n'), ((3731, 3820), 'pandas.DataFrame', 'pd.DataFrame', (['all_user_predicted_rating'], {'columns': 'product_index', 'index': 'username_index'}), '(all_user_predicted_rating, columns=product_index, index=\n username_index)\n', (3743, 3820), True, 'import pandas as pd\n'), ((4434, 4459), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (4449, 4459), False, 'import os\n'), ((4492, 4511), 'os.chdir', 'os.chdir', (['file_path'], {}), '(file_path)\n', (4500, 4511), False, 'import os\n'), ((4756, 4775), 'pandas.DataFrame', 'pd.DataFrame', (['lines'], {}), '(lines)\n', (4768, 4775), True, 'import pandas as pd\n'), ((1838, 1872), 'numpy.array', 'np.array', (["[item1['X'], item1['Y']]"], {}), "([item1['X'], item1['Y']])\n", (1846, 1872), True, 'import numpy as np\n'), ((1897, 1931), 'numpy.array', 'np.array', (["[item2['X'], item2['Y']]"], {}), "([item2['X'], item2['Y']])\n", (1905, 1931), True, 'import numpy as np\n'), ((1956, 1990), 'numpy.array', 'np.array', (["[item3['X'], item3['Y']]"], {}), "([item3['X'], item3['Y']])\n", (1964, 1990), True, 'import numpy as np\n'), ((2152, 2178), 'scipy.spatial.distance.chebyshev', 'distance.chebyshev', (['p1', 'pn'], {}), '(p1, pn)\n', (2170, 2178), False, 'from scipy.spatial import distance\n'), ((2192, 2218), 'scipy.spatial.distance.chebyshev', 'distance.chebyshev', (['p2', 'pn'], {}), '(p2, pn)\n', (2210, 2218), False, 'from scipy.spatial import distance\n'), ((2232, 2258), 'scipy.spatial.distance.chebyshev', 'distance.chebyshev', (['p3', 'pn'], {}), '(p3, pn)\n', (2250, 2258), False, 'from scipy.spatial import distance\n'), ((554, 702), 're.sub', 're.sub', (['"""\\\\(([^)]*)\\\\)|(([0-9]\\\\d{0,2}(\\\\.\\\\d{1,3})*(,\\\\d+)?)(%|mg|units))|(<\\\\/?i>)|(\\\\/.+)|(\\\\\\\\.+)|\\\\[([^\\\\]]*)\\\\]"""', '""""""', 'ingredients[i]'], {}), "(\n '\\\\(([^)]*)\\\\)|(([0-9]\\\\d{0,2}(\\\\.\\\\d{1,3})*(,\\\\d+)?)(%|mg|units))|(<\\\\/?i>)|(\\\\/.+)|(\\\\\\\\.+)|\\\\[([^\\\\]]*)\\\\]'\n , '', ingredients[i])\n", (560, 702), False, 'import re\n'), ((2064, 2090), 'numpy.array', 'np.array', (['[item.X, item.Y]'], {}), '([item.X, item.Y])\n', (2072, 2090), True, 'import numpy as np\n'), ((3699, 3709), 'numpy.diag', 'np.diag', (['S'], {}), '(S)\n', (3706, 3709), True, 'import numpy as np\n')]
import functools import json from os.path import abspath, dirname, exists, join from typing import Dict, Sequence import numpy as np import pandas as pd import torch from pymatgen.core import Composition from torch.utils.data import Dataset class CompositionData(Dataset): def __init__( self, df: pd.DataFrame, task_dict: Dict[str, str], elem_emb: str = "matscholar200", inputs: Sequence[str] = ["composition"], identifiers: Sequence[str] = ["material_id", "composition"], ): """Data class for Roost models. Args: df (pd.DataFrame): Pandas dataframe holding input and target values. task_dict (dict[str, "regression" | "classification"]): Map from target names to task type. elem_emb (str, optional): One of "matscholar200", "cgcnn92", "megnet16", "onehot112" or path to a file with custom embeddings. Defaults to "matscholar200". inputs (list[str], optional): df column name holding material compositions. Defaults to ["composition"]. identifiers (list, optional): df columns for distinguishing data points. Will be copied over into the model's output CSV. Defaults to ["material_id", "composition"]. """ assert len(identifiers) == 2, "Two identifiers are required" assert len(inputs) == 1, "One input column required are required" self.inputs = inputs self.task_dict = task_dict self.identifiers = identifiers self.df = df if elem_emb in ["matscholar200", "cgcnn92", "megnet16", "onehot112"]: elem_emb = join( dirname(abspath(__file__)), f"../embeddings/element/{elem_emb}.json" ) else: assert exists(elem_emb), f"{elem_emb} does not exist!" with open(elem_emb) as f: self.elem_features = json.load(f) self.elem_emb_len = len(list(self.elem_features.values())[0]) self.n_targets = [] for target, task in self.task_dict.items(): if task == "regression": self.n_targets.append(1) elif task == "classification": n_classes = np.max(self.df[target].values) + 1 self.n_targets.append(n_classes) def __len__(self): return len(self.df) @functools.lru_cache(maxsize=None) # Cache data for faster training def __getitem__(self, idx): """[summary] Args: idx (int): dataset index Raises: AssertionError: [description] ValueError: [description] Returns: atom_weights: torch.Tensor shape (M, 1) weights of atoms in the material atom_fea: torch.Tensor shape (M, n_fea) features of atoms in the material self_fea_idx: torch.Tensor shape (M*M, 1) list of self indices nbr_fea_idx: torch.Tensor shape (M*M, 1) list of neighbor indices target: torch.Tensor shape (1,) target value for material cry_id: torch.Tensor shape (1,) input id for the material """ df_idx = self.df.iloc[idx] composition = df_idx[self.inputs][0] cry_ids = df_idx[self.identifiers].values comp_dict = Composition(composition).get_el_amt_dict() elements = list(comp_dict.keys()) weights = list(comp_dict.values()) weights = np.atleast_2d(weights).T / np.sum(weights) try: atom_fea = np.vstack([self.elem_features[element] for element in elements]) except AssertionError: raise AssertionError( f"cry-id {cry_ids[0]} [{composition}] contains element types not in embedding" ) except ValueError: raise ValueError( f"cry-id {cry_ids[0]} [{composition}] composition cannot be parsed into elements" ) nele = len(elements) self_fea_idx = [] nbr_fea_idx = [] for i, _ in enumerate(elements): self_fea_idx += [i] * nele nbr_fea_idx += list(range(nele)) # convert all data to tensors atom_weights = torch.Tensor(weights) atom_fea = torch.Tensor(atom_fea) self_fea_idx = torch.LongTensor(self_fea_idx) nbr_fea_idx = torch.LongTensor(nbr_fea_idx) targets = [] for target in self.task_dict: if self.task_dict[target] == "regression": targets.append(torch.Tensor([df_idx[target]])) elif self.task_dict[target] == "classification": targets.append(torch.LongTensor([df_idx[target]])) return ( (atom_weights, atom_fea, self_fea_idx, nbr_fea_idx), targets, *cry_ids, ) def collate_batch(dataset_list): """ Collate a list of data and return a batch for predicting crystal properties. Parameters ---------- dataset_list: list of tuples for each data point. (atom_fea, nbr_fea, nbr_fea_idx, target) atom_fea: torch.Tensor shape (n_i, atom_fea_len) nbr_fea: torch.Tensor shape (n_i, M, nbr_fea_len) self_fea_idx: torch.LongTensor shape (n_i, M) nbr_fea_idx: torch.LongTensor shape (n_i, M) target: torch.Tensor shape (1, ) cif_id: str or int Returns ------- N = sum(n_i); N0 = sum(i) batch_atom_weights: torch.Tensor shape (N, 1) batch_atom_fea: torch.Tensor shape (N, orig_atom_fea_len) Atom features from atom type batch_self_fea_idx: torch.LongTensor shape (N, M) Indices of mapping atom to copies of itself batch_nbr_fea_idx: torch.LongTensor shape (N, M) Indices of M neighbors of each atom crystal_atom_idx: list of torch.LongTensor of length N0 Mapping from the crystal idx to atom idx target: torch.Tensor shape (N, 1) Target value for prediction batch_comps: list batch_ids: list """ # define the lists batch_atom_weights = [] batch_atom_fea = [] batch_self_fea_idx = [] batch_nbr_fea_idx = [] crystal_atom_idx = [] batch_targets = [] batch_cry_ids = [] cry_base_idx = 0 for i, (inputs, target, *cry_ids) in enumerate(dataset_list): atom_weights, atom_fea, self_fea_idx, nbr_fea_idx = inputs # number of atoms for this crystal n_i = atom_fea.shape[0] # batch the features together batch_atom_weights.append(atom_weights) batch_atom_fea.append(atom_fea) # mappings from bonds to atoms batch_self_fea_idx.append(self_fea_idx + cry_base_idx) batch_nbr_fea_idx.append(nbr_fea_idx + cry_base_idx) # mapping from atoms to crystals crystal_atom_idx.append(torch.tensor([i] * n_i)) # batch the targets and ids batch_targets.append(target) batch_cry_ids.append(cry_ids) # increment the id counter cry_base_idx += n_i return ( ( torch.cat(batch_atom_weights, dim=0), torch.cat(batch_atom_fea, dim=0), torch.cat(batch_self_fea_idx, dim=0), torch.cat(batch_nbr_fea_idx, dim=0), torch.cat(crystal_atom_idx), ), tuple(torch.stack(b_target, dim=0) for b_target in zip(*batch_targets)), *zip(*batch_cry_ids), )
[ "os.path.exists", "numpy.atleast_2d", "torch.LongTensor", "torch.stack", "torch.Tensor", "pymatgen.core.Composition", "numpy.max", "numpy.sum", "torch.tensor", "numpy.vstack", "json.load", "functools.lru_cache", "os.path.abspath", "torch.cat" ]
[((2395, 2428), 'functools.lru_cache', 'functools.lru_cache', ([], {'maxsize': 'None'}), '(maxsize=None)\n', (2414, 2428), False, 'import functools\n'), ((4310, 4331), 'torch.Tensor', 'torch.Tensor', (['weights'], {}), '(weights)\n', (4322, 4331), False, 'import torch\n'), ((4351, 4373), 'torch.Tensor', 'torch.Tensor', (['atom_fea'], {}), '(atom_fea)\n', (4363, 4373), False, 'import torch\n'), ((4397, 4427), 'torch.LongTensor', 'torch.LongTensor', (['self_fea_idx'], {}), '(self_fea_idx)\n', (4413, 4427), False, 'import torch\n'), ((4450, 4479), 'torch.LongTensor', 'torch.LongTensor', (['nbr_fea_idx'], {}), '(nbr_fea_idx)\n', (4466, 4479), False, 'import torch\n'), ((1823, 1839), 'os.path.exists', 'exists', (['elem_emb'], {}), '(elem_emb)\n', (1829, 1839), False, 'from os.path import abspath, dirname, exists, join\n'), ((1939, 1951), 'json.load', 'json.load', (['f'], {}), '(f)\n', (1948, 1951), False, 'import json\n'), ((3581, 3596), 'numpy.sum', 'np.sum', (['weights'], {}), '(weights)\n', (3587, 3596), True, 'import numpy as np\n'), ((3634, 3698), 'numpy.vstack', 'np.vstack', (['[self.elem_features[element] for element in elements]'], {}), '([self.elem_features[element] for element in elements])\n', (3643, 3698), True, 'import numpy as np\n'), ((6901, 6924), 'torch.tensor', 'torch.tensor', (['([i] * n_i)'], {}), '([i] * n_i)\n', (6913, 6924), False, 'import torch\n'), ((7138, 7174), 'torch.cat', 'torch.cat', (['batch_atom_weights'], {'dim': '(0)'}), '(batch_atom_weights, dim=0)\n', (7147, 7174), False, 'import torch\n'), ((7188, 7220), 'torch.cat', 'torch.cat', (['batch_atom_fea'], {'dim': '(0)'}), '(batch_atom_fea, dim=0)\n', (7197, 7220), False, 'import torch\n'), ((7234, 7270), 'torch.cat', 'torch.cat', (['batch_self_fea_idx'], {'dim': '(0)'}), '(batch_self_fea_idx, dim=0)\n', (7243, 7270), False, 'import torch\n'), ((7284, 7319), 'torch.cat', 'torch.cat', (['batch_nbr_fea_idx'], {'dim': '(0)'}), '(batch_nbr_fea_idx, dim=0)\n', (7293, 7319), False, 'import torch\n'), ((7333, 7360), 'torch.cat', 'torch.cat', (['crystal_atom_idx'], {}), '(crystal_atom_idx)\n', (7342, 7360), False, 'import torch\n'), ((3407, 3431), 'pymatgen.core.Composition', 'Composition', (['composition'], {}), '(composition)\n', (3418, 3431), False, 'from pymatgen.core import Composition\n'), ((3554, 3576), 'numpy.atleast_2d', 'np.atleast_2d', (['weights'], {}), '(weights)\n', (3567, 3576), True, 'import numpy as np\n'), ((7387, 7415), 'torch.stack', 'torch.stack', (['b_target'], {'dim': '(0)'}), '(b_target, dim=0)\n', (7398, 7415), False, 'import torch\n'), ((1715, 1732), 'os.path.abspath', 'abspath', (['__file__'], {}), '(__file__)\n', (1722, 1732), False, 'from os.path import abspath, dirname, exists, join\n'), ((4626, 4656), 'torch.Tensor', 'torch.Tensor', (['[df_idx[target]]'], {}), '([df_idx[target]])\n', (4638, 4656), False, 'import torch\n'), ((2253, 2283), 'numpy.max', 'np.max', (['self.df[target].values'], {}), '(self.df[target].values)\n', (2259, 2283), True, 'import numpy as np\n'), ((4750, 4784), 'torch.LongTensor', 'torch.LongTensor', (['[df_idx[target]]'], {}), '([df_idx[target]])\n', (4766, 4784), False, 'import torch\n')]
# coding=utf-8 # Copyright 2019 The Tensor2Tensor 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. """PPO in JAX. Notation: B, scalar - batch size T, scalar - number of time-steps in a trajectory, or the value of the padded time-step dimension. OBS, tuple - shape of a singular observation from the environment. Ex: For CartPole-v0 this is (4,) and Pong-v0 it's (210, 160, 3) A, scalar - Number of actions, assuming a discrete space. Policy and Value function signatures: Policy Function :: [B, T] + OBS -> [B, T, A] Value Function :: [B, T] + OBS -> [B, T, 1] Policy and Value Function :: [B, T] + OBS -> ([B, T, A], [B, T, 1]) i.e. the policy net should take a batch of *trajectories* and at each time-step in each batch deliver a probability distribution over actions. NOTE: It doesn't return logits, rather the expectation is that it returns log-probabilities instead. NOTE: The policy and value functions need to take care to not take into account future time-steps while deciding the actions (or value) for the current time-step. Policy and Value Function produces a tuple of the expected output of a policy function and a value function. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import functools import os import pickle import time from absl import logging import gym from jax import grad from jax import jit from jax import lax from jax import numpy as np from jax import random as jax_random import numpy as onp from tensor2tensor.envs import env_problem from tensor2tensor.envs import env_problem_utils from tensor2tensor.trax import jaxboard from tensor2tensor.trax import layers from tensor2tensor.trax import optimizers as trax_opt from tensor2tensor.trax import trax from tensorflow.io import gfile DEBUG_LOGGING = False GAMMA = 0.99 LAMBDA = 0.95 EPSILON = 0.1 EPOCHS = 50 # 100 NUM_OPTIMIZER_STEPS = 100 PRINT_EVERY_OPTIMIZER_STEP = 20 BATCH_TRAJECTORIES = 32 def policy_and_value_net(rng_key, batch_observations_shape, num_actions, bottom_layers_fn=None, two_towers=True): """A policy and value net function.""" # Layers. # Now, with the current logits, one head computes action probabilities and the # other computes the value function. # NOTE: The LogSoftmax instead of the Softmax because of numerical stability. net = None if not two_towers: tower = [] if bottom_layers_fn is None else bottom_layers_fn() tower.extend([ layers.Branch( layers.Serial(layers.Dense(num_actions), layers.LogSoftmax()), layers.Dense(1)) ]) net = layers.Serial(*tower) else: tower1 = [] if bottom_layers_fn is None else bottom_layers_fn() tower2 = [] if bottom_layers_fn is None else bottom_layers_fn() tower1.extend([layers.Dense(num_actions), layers.LogSoftmax()]) tower2.extend([layers.Dense(1)]) net = layers.Branch( layers.Serial(*tower1), layers.Serial(*tower2), ) assert net return net.initialize(batch_observations_shape, rng_key), net def optimizer_fun(net_params, step_size=1e-3): opt = trax_opt.Adam(step_size=step_size, b1=0.9, b2=0.999, eps=1e-08) opt_init = lambda x: (x, opt.tree_init(x)) opt_update = lambda i, g, s: opt.tree_update(i, g, s[0], s[1]) get_params = lambda x: x[0] opt_state = opt_init(net_params) return opt_state, opt_update, get_params # Should this be collect 'n' trajectories, or # Run the env for 'n' steps and take completed trajectories, or # Any other option? # TODO(afrozm): Replace this with EnvProblem? def collect_trajectories(env, policy_fun, num_trajectories=1, policy=env_problem_utils.CATEGORICAL_SAMPLING, max_timestep=None, boundary=20, epsilon=0.1, reset=True, rng=None): """Collect trajectories with the given policy net and behaviour. Args: env: A gym env interface, for now this is not-batched. policy_fun: observations(B,T+1) -> log-probabs(B,T+1, A) callable. num_trajectories: int, number of trajectories. policy: string, "greedy", "epsilon-greedy", or "categorical-sampling" i.e. how to use the policy_fun to return an action. max_timestep: int or None, the index of the maximum time-step at which we return the trajectory, None for ending a trajectory only when env returns done. boundary: int, boundary for padding, used in EnvProblem envs. epsilon: float, the epsilon for `epsilon-greedy` policy. reset: bool, true if we want to reset the envs. The envs are also reset if max_max_timestep is None or < 0 rng: jax rng, splittable. Returns: A tuple (trajectory, number of trajectories that are done) trajectory: list of (observation, action, reward) tuples, where each element `i` is a tuple of numpy arrays with shapes as follows: observation[i] = (B, T_i + 1) action[i] = (B, T_i) reward[i] = (B, T_i) """ assert isinstance(env, env_problem.EnvProblem) # This is an env_problem, run its collect function. return env_problem_utils.play_env_problem_with_policy( env, policy_fun, num_trajectories=num_trajectories, max_timestep=max_timestep, boundary=boundary, policy_sampling=policy, eps=epsilon, reset=reset, rng=rng) # This function can probably be simplified, ask how? # Can we do something much simpler than lax.pad, maybe np.pad? # Others? def get_padding_value(dtype): """Returns the padding value given a dtype.""" padding_value = None if dtype == np.uint8: padding_value = np.uint8(0) elif dtype == np.uint16: padding_value = np.uint16(0) elif dtype == np.float32 or dtype == np.float64: padding_value = 0.0 else: padding_value = 0 assert padding_value is not None return padding_value # TODO(afrozm): Use np.pad instead and make jittable? def pad_trajectories(trajectories, boundary=20): """Pad trajectories to a bucket length that is a multiple of boundary. Args: trajectories: list[(observation, actions, rewards)], where each observation is shaped (t+1,) + OBS and actions & rewards are shaped (t,), with the length of the list being B (batch size). boundary: int, bucket length, the actions and rewards are padded to integer multiples of boundary. Returns: tuple: (padding lengths, reward_mask, padded_observations, padded_actions, padded_rewards) where padded_observations is shaped (B, T+1) + OBS and padded_actions, padded_rewards & reward_mask are shaped (B, T). Where T is max(t) rounded up to an integer multiple of boundary. padded_length is how much padding we've added and reward_mask is 1s for actual rewards and 0s for the padding. """ # Let's compute max(t) over all trajectories. t_max = max(r.shape[0] for (_, _, r) in trajectories) # t_max is rounded to the next multiple of `boundary` boundary = int(boundary) bucket_length = boundary * int(np.ceil(float(t_max) / boundary)) # So all obs will be padded to t_max + 1 and actions and rewards to t_max. padded_observations = [] padded_actions = [] padded_rewards = [] padded_lengths = [] reward_masks = [] for (o, a, r) in trajectories: # Determine the amount to pad, this holds true for obs, actions and rewards. num_to_pad = bucket_length + 1 - o.shape[0] padded_lengths.append(num_to_pad) if num_to_pad == 0: padded_observations.append(o) padded_actions.append(a) padded_rewards.append(r) reward_masks.append(onp.ones_like(r, dtype=np.int32)) continue # First pad observations. padding_config = [(0, num_to_pad, 0)] for _ in range(o.ndim - 1): padding_config.append((0, 0, 0)) padding_config = tuple(padding_config) padding_value = get_padding_value(o.dtype) action_padding_value = get_padding_value(a.dtype) reward_padding_value = get_padding_value(r.dtype) padded_obs = lax.pad(o, padding_value, padding_config) padded_observations.append(padded_obs) # Now pad actions and rewards. assert a.ndim == 1 and r.ndim == 1 padding_config = ((0, num_to_pad, 0),) padded_action = lax.pad(a, action_padding_value, padding_config) padded_actions.append(padded_action) padded_reward = lax.pad(r, reward_padding_value, padding_config) padded_rewards.append(padded_reward) # Also create the mask to use later. reward_mask = onp.ones_like(r, dtype=np.int32) reward_masks.append(lax.pad(reward_mask, 0, padding_config)) return padded_lengths, np.stack(reward_masks), np.stack( padded_observations), np.stack(padded_actions), np.stack(padded_rewards) # TODO(afrozm): JAX-ify this, this is too slow for pong. def rewards_to_go(rewards, mask, gamma=0.99): r"""Computes rewards to go. Reward to go is defined as follows, the discounted reward that we have to yet collect, going forward from this point, i.e.: r2g_t = \sum_{l=0}^{\infty} (\gamma^{l} * reward_{t+l}) Args: rewards: np.ndarray of shape (B, T) of rewards. mask: np.ndarray of shape (B, T) of mask for the rewards. gamma: float, discount factor. Returns: rewards to go, np.ndarray of shape (B, T). """ B, T = rewards.shape # pylint: disable=invalid-name,unused-variable masked_rewards = rewards * mask # (B, T) # We use the following recurrence relation, derived from the equation above: # # r2g[t+1] = (r2g[t] - r[t]) / gamma # # This means we'll need to calculate r2g[0] first and then r2g[1] and so on .. # # **However** this leads to overflows for long sequences: r2g[t] - r[t] > 0 # and gamma < 1.0, so the division keeps increasing. # # So we just run the recurrence in reverse, i.e. # # r2g[t] = r[t] + (gamma*r2g[t+1]) # # This is much better, but might have lost updates since the (small) rewards # at earlier time-steps may get added to a (very?) large sum. # Compute r2g_{T-1} at the start and then compute backwards in time. r2gs = [masked_rewards[:, -1]] # Go from T-2 down to 0. for t in reversed(range(T - 1)): r2gs.append(masked_rewards[:, t] + (gamma * r2gs[-1])) # The list should have length T. assert T == len(r2gs) # First we stack them in the correct way to make it (B, T), but these are # still from newest (T-1) to oldest (0), so then we flip it on time axis. return np.flip(np.stack(r2gs, axis=1), axis=1) @jit def value_loss_given_predictions(value_prediction, rewards, reward_mask, gamma=0.99, epsilon=0.2, value_prediction_old=None): """Computes the value loss given the prediction of the value function. Args: value_prediction: np.ndarray of shape (B, T+1, 1) rewards: np.ndarray of shape (B, T) of rewards. reward_mask: np.ndarray of shape (B, T), the mask over rewards. gamma: float, discount factor. epsilon: float, clip-fraction, used if value_value_prediction_old isn't None value_prediction_old: np.ndarray of shape (B, T+1, 1) of value predictions using the old parameters. If provided, we incorporate this in the loss as well. This is from the OpenAI baselines implementation. Returns: The average L2 value loss, averaged over instances where reward_mask is 1. """ B, T = rewards.shape # pylint: disable=invalid-name assert (B, T) == reward_mask.shape assert (B, T + 1, 1) == value_prediction.shape value_prediction = np.squeeze(value_prediction, axis=2) # (B, T+1) value_prediction = value_prediction[:, :-1] * reward_mask # (B, T) r2g = rewards_to_go(rewards, reward_mask, gamma=gamma) # (B, T) loss = (value_prediction - r2g)**2 # From the baselines implementation. if value_prediction_old is not None: value_prediction_old = np.squeeze(value_prediction_old, axis=2) # (B, T+1) value_prediction_old = value_prediction_old[:, :-1] * reward_mask # (B, T) v_clipped = value_prediction_old + np.clip( value_prediction - value_prediction_old, -epsilon, epsilon) v_clipped_loss = (v_clipped - r2g)**2 loss = np.maximum(v_clipped_loss, loss) # Take an average on only the points where mask != 0. return np.sum(loss) / np.sum(reward_mask) # TODO(afrozm): JAX-ify this, this is too slow for pong. def deltas(predicted_values, rewards, mask, gamma=0.99): r"""Computes TD-residuals from V(s) and rewards. Where a `delta`, i.e. a td-residual is defined as: delta_{b,t} = r_{b,t} + \gamma * v_{b,t+1} - v_{b,t}. Args: predicted_values: ndarray of shape (B, T+1). NOTE: Expects axis 2 was squeezed. These represent V(s_bt) for b < B and t < T+1 rewards: ndarray of shape (B, T) of rewards. mask: ndarray of shape (B, T) of mask for rewards. gamma: float, discount factor. Returns: ndarray of shape (B, T) of one-step TD-residuals. """ # `d`s are basically one-step TD residuals. d = [] _, T = rewards.shape # pylint: disable=invalid-name for t in range(T): d.append(rewards[:, t] + (gamma * predicted_values[:, t + 1]) - predicted_values[:, t]) return np.array(d).T * mask def gae_advantages(td_deltas, mask, lambda_=0.95, gamma=0.99): r"""Computes the GAE advantages given the one step TD-residuals. The formula for a GAE advantage estimator is as follows: A_{bt} = \sum_{l=0}^{\infty}(\gamma * \lambda)^{l}(\delta_{b,t+l}). Internally we just call rewards_to_go, since it is the same computation. Args: td_deltas: np.ndarray of shape (B, T) of one step TD-residuals. mask: np.ndarray of shape (B, T) of mask for the residuals. It maybe the case that the `td_deltas` are already masked correctly since they are produced by `deltas(...)` lambda_: float, lambda parameter for GAE estimators. gamma: float, lambda parameter for GAE estimators. Returns: GAE advantage estimates. """ return rewards_to_go(td_deltas, mask, lambda_ * gamma) def chosen_probabs(probab_observations, actions): """Picks out the probabilities of the actions along batch and time-steps. Args: probab_observations: ndarray of shape `[B, T+1, A]`, where probab_observations[b, t, i] contains the log-probability of action = i at the t^th time-step in the b^th trajectory. actions: ndarray of shape `[B, T]`, with each entry in [0, A) denoting which action was chosen in the b^th trajectory's t^th time-step. Returns: `[B, T]` ndarray with the log-probabilities of the chosen actions. """ B, T = actions.shape # pylint: disable=invalid-name assert (B, T + 1) == probab_observations.shape[:2] return probab_observations[np.arange(B)[:, None], np.arange(T), actions] def compute_probab_ratios(p_new, p_old, actions, reward_mask): """Computes the probability ratios for each time-step in a trajectory. Args: p_new: ndarray of shape [B, T+1, A] of the log-probabilities that the policy network assigns to all the actions at each time-step in each batch using the old parameters. p_old: ndarray of shape [B, T+1, A], same as above, but using old policy network parameters. actions: ndarray of shape [B, T] where each element is from [0, A). reward_mask: ndarray of shape [B, T] masking over probabilities. Returns: probab_ratios: ndarray of shape [B, T], where probab_ratios_{b,t} = p_new_{b,t,action_{b,t}} / p_old_{b,t,action_{b,t}} """ B, T = actions.shape # pylint: disable=invalid-name assert (B, T + 1) == p_old.shape[:2] assert (B, T + 1) == p_new.shape[:2] logp_old = chosen_probabs(p_old, actions) logp_new = chosen_probabs(p_new, actions) assert (B, T) == logp_old.shape assert (B, T) == logp_new.shape # Since these are log-probabilities, we just subtract them. probab_ratios = np.exp(logp_new - logp_old) * reward_mask assert (B, T) == probab_ratios.shape return probab_ratios def clipped_probab_ratios(probab_ratios, epsilon=0.2): return np.clip(probab_ratios, 1 - epsilon, 1 + epsilon) def clipped_objective(probab_ratios, advantages, reward_mask, epsilon=0.2): return np.minimum( probab_ratios * advantages, clipped_probab_ratios(probab_ratios, epsilon=epsilon) * advantages) * reward_mask @jit def ppo_loss_given_predictions(log_probab_actions_new, log_probab_actions_old, value_predictions_old, padded_actions, padded_rewards, reward_mask, gamma=0.99, lambda_=0.95, epsilon=0.2): """PPO objective, with an eventual minus sign, given predictions.""" B, T = padded_rewards.shape # pylint: disable=invalid-name assert (B, T) == padded_actions.shape assert (B, T) == reward_mask.shape _, _, A = log_probab_actions_old.shape # pylint: disable=invalid-name assert (B, T + 1, 1) == value_predictions_old.shape assert (B, T + 1, A) == log_probab_actions_old.shape assert (B, T + 1, A) == log_probab_actions_new.shape # (B, T) td_deltas = deltas( np.squeeze(value_predictions_old, axis=2), # (B, T+1) padded_rewards, reward_mask, gamma=gamma) # (B, T) advantages = gae_advantages( td_deltas, reward_mask, lambda_=lambda_, gamma=gamma) # Normalize the advantages. advantages = (advantages - np.mean(advantages)) / np.std(advantages) # (B, T) ratios = compute_probab_ratios(log_probab_actions_new, log_probab_actions_old, padded_actions, reward_mask) assert (B, T) == ratios.shape # (B, T) objective = clipped_objective( ratios, advantages, reward_mask, epsilon=epsilon) assert (B, T) == objective.shape # () average_objective = np.sum(objective) / np.sum(reward_mask) # Loss is negative objective. return -average_objective @jit def combined_loss_given_predictions(log_probab_actions_new, log_probab_actions_old, value_prediction_new, value_prediction_old, padded_actions, padded_rewards, reward_mask, gamma=0.99, lambda_=0.95, epsilon=0.2, c1=1.0, c2=0.01): """Computes the combined (clipped loss + value loss) given predictions.""" loss_value = value_loss_given_predictions( value_prediction_new, padded_rewards, reward_mask, gamma=gamma, value_prediction_old=value_prediction_old, epsilon=epsilon) loss_ppo = ppo_loss_given_predictions( log_probab_actions_new, log_probab_actions_old, value_prediction_old, padded_actions, padded_rewards, reward_mask, gamma=gamma, lambda_=lambda_, epsilon=epsilon) entropy_bonus = masked_entropy(log_probab_actions_new, reward_mask) return (loss_ppo + (c1 * loss_value) - (c2 * entropy_bonus), loss_ppo, loss_value, entropy_bonus) @functools.partial(jit, static_argnums=(3,)) def combined_loss(new_params, log_probab_actions_old, value_predictions_old, policy_and_value_net_apply, padded_observations, padded_actions, padded_rewards, reward_mask, gamma=0.99, lambda_=0.95, epsilon=0.2, c1=1.0, c2=0.01, rng=None): """Computes the combined (clipped loss + value loss) given observations.""" log_probab_actions_new, value_predictions_new = policy_and_value_net_apply( padded_observations, new_params, rng=rng) # (combined_loss, ppo_loss, value_loss, entropy_bonus) return combined_loss_given_predictions( log_probab_actions_new, log_probab_actions_old, value_predictions_new, value_predictions_old, padded_actions, padded_rewards, reward_mask, gamma=gamma, lambda_=lambda_, epsilon=epsilon, c1=c1, c2=c2) @functools.partial(jit, static_argnums=(2, 3, 4)) def policy_and_value_opt_step(i, opt_state, opt_update, get_params, policy_and_value_net_apply, log_probab_actions_old, value_predictions_old, padded_observations, padded_actions, padded_rewards, reward_mask, c1=1.0, c2=0.01, gamma=0.99, lambda_=0.95, epsilon=0.1, rng=None): """Policy and Value optimizer step.""" # Combined loss function given the new params. def policy_and_value_loss(params): """Returns the combined loss given just parameters.""" (loss, _, _, _) = combined_loss( params, log_probab_actions_old, value_predictions_old, policy_and_value_net_apply, padded_observations, padded_actions, padded_rewards, reward_mask, c1=c1, c2=c2, gamma=gamma, lambda_=lambda_, epsilon=epsilon, rng=rng) return loss new_params = get_params(opt_state) g = grad(policy_and_value_loss)(new_params) # TODO(afrozm): Maybe clip gradients? return opt_update(i, g, opt_state) def get_time(t1, t2=None): if t2 is None: t2 = time.time() return round((t2 - t1) * 1000, 2) def approximate_kl(log_prob_new, log_prob_old, mask): """Computes the approximate KL divergence between the old and new log-probs. Args: log_prob_new: (B, T+1, A) log probs new log_prob_old: (B, T+1, A) log probs old mask: (B, T) Returns: Approximate KL. """ diff = log_prob_old - log_prob_new # Cut the last time-step out. diff = diff[:, :-1] # Mask out the irrelevant part. diff *= mask[:, :, np.newaxis] # make mask (B, T, 1) # Average on non-masked part. return np.sum(diff) / np.sum(mask) def masked_entropy(log_probs, mask): """Computes the entropy for the given log-probs. Args: log_probs: (B, T+1, A) log probs mask: (B, T) mask. Returns: Entropy. """ # Cut the last time-step out. lp = log_probs[:, :-1] # Mask out the irrelevant part. lp *= mask[:, :, np.newaxis] # make mask (B, T, 1) p = np.exp(lp) * mask[:, :, np.newaxis] # (B, T, 1) # Average on non-masked part and take negative. return -(np.sum(lp * p) / np.sum(mask)) def evaluate_policy(eval_env, get_predictions, boundary, max_timestep=20000, rng=None): """Evaluate the policy.""" avg_rewards = {} for policy in [ env_problem_utils.CATEGORICAL_SAMPLING, env_problem_utils.GUMBEL_SAMPLING, env_problem_utils.EPSILON_GREEDY ]: trajs, _ = env_problem_utils.play_env_problem_with_policy( eval_env, get_predictions, boundary=boundary, max_timestep=max_timestep, reset=True, policy_sampling=policy, rng=rng) avg_rewards[policy] = float(sum( np.sum(traj[2]) for traj in trajs)) / len(trajs) return avg_rewards def maybe_restore_params(output_dir, policy_and_value_net_params): """Maybe restore the params from the checkpoint dir. Args: output_dir: Directory where saved model checkpoints are stored. policy_and_value_net_params: Default params, returned if model is'nt found. Returns: triple (restore (bool), params, iter(int)) where iter is the epoch from which we restored the params, 0 is restore = False. """ model_files = gfile.glob(os.path.join(output_dir, "model-??????.pkl")) if not model_files: return False, policy_and_value_net_params, 0 model_file = sorted(model_files)[-1] model_file_basename = os.path.basename(model_file) # model-??????.pkl i = int(filter(str.isdigit, model_file_basename)) with gfile.GFile(model_file, "rb") as f: policy_and_value_net_params = pickle.load(f) return True, policy_and_value_net_params, i def training_loop( env=None, epochs=EPOCHS, policy_and_value_net_fun=None, policy_and_value_optimizer_fun=None, batch_size=BATCH_TRAJECTORIES, num_optimizer_steps=NUM_OPTIMIZER_STEPS, print_every_optimizer_steps=PRINT_EVERY_OPTIMIZER_STEP, target_kl=0.01, boundary=20, max_timestep=None, max_timestep_eval=20000, random_seed=None, gamma=GAMMA, lambda_=LAMBDA, epsilon=EPSILON, c1=1.0, c2=0.01, output_dir=None, eval_every_n=1000, eval_env=None, done_frac_for_policy_save=0.5, enable_early_stopping=True, env_name=None, ): """Runs the training loop for PPO, with fixed policy and value nets.""" assert env assert output_dir assert env_name gfile.makedirs(output_dir) # Create summary writers and history. train_sw = jaxboard.SummaryWriter(os.path.join(output_dir, "train")) timing_sw = jaxboard.SummaryWriter(os.path.join(output_dir, "timing")) eval_sw = jaxboard.SummaryWriter(os.path.join(output_dir, "eval")) train_sw.text("env_name", env_name) timing_sw.text("env_name", env_name) eval_sw.text("env_name", env_name) jax_rng_key = trax.get_random_number_generator_and_set_seed(random_seed) # Batch Observations Shape = [-1, -1] + OBS, because we will eventually call # policy and value networks on shape [B, T] +_OBS batch_observations_shape = (-1, -1) + env.observation_space.shape assert isinstance(env.action_space, gym.spaces.Discrete) num_actions = env.action_space.n jax_rng_key, key1 = jax_random.split(jax_rng_key, num=2) # Initialize the policy and value network. policy_and_value_net_params, policy_and_value_net_apply = ( policy_and_value_net_fun(key1, batch_observations_shape, num_actions)) # Maybe restore the policy params. If there is nothing to restore, then # iteration = 0 and policy_and_value_net_params are returned as is. restore, policy_and_value_net_params, iteration = ( maybe_restore_params(output_dir, policy_and_value_net_params)) if restore: logging.info("Restored parameters from iteration [%d]", iteration) # We should start from the next iteration. iteration += 1 policy_and_value_net_apply = jit(policy_and_value_net_apply) # Initialize the optimizers. policy_and_value_optimizer = ( policy_and_value_optimizer_fun(policy_and_value_net_params)) (policy_and_value_opt_state, policy_and_value_opt_update, policy_and_value_get_params) = policy_and_value_optimizer num_trajectories_done = 0 last_saved_at = 0 logging.info("Starting the PPO training loop.") for i in range(iteration, epochs): epoch_start_time = time.time() # Params we'll use to collect the trajectories. policy_and_value_net_params = policy_and_value_get_params( policy_and_value_opt_state) # A function to get the policy and value predictions. def get_predictions(observations, rng=None): """Returns log-probs, value predictions and key back.""" key, key1 = jax_random.split(rng, num=2) log_probs, value_preds = policy_and_value_net_apply( observations, policy_and_value_net_params, rng=key1) return log_probs, value_preds, key # Evaluate the policy. policy_eval_start_time = time.time() if ((i + 1) % eval_every_n == 0) or (i == epochs - 1): jax_rng_key, key = jax_random.split(jax_rng_key, num=2) logging.vlog(1, "Epoch [% 6d] evaluating policy.", i) avg_reward = evaluate_policy( eval_env, get_predictions, boundary, max_timestep=max_timestep_eval, rng=key) for k, v in avg_reward.items(): eval_sw.scalar("eval/mean_reward/%s" % k, v, step=i) logging.info("Epoch [% 6d] Policy Evaluation [%s] = %10.2f", i, k, v) policy_eval_time = get_time(policy_eval_start_time) trajectory_collection_start_time = time.time() logging.vlog(1, "Epoch [% 6d] collecting trajectories.", i) jax_rng_key, key = jax_random.split(jax_rng_key) trajs, num_done = collect_trajectories( env, policy_fun=get_predictions, num_trajectories=batch_size, max_timestep=max_timestep, boundary=boundary, rng=key, reset=(i == 0) or restore, epsilon=(10.0 / (i + 10.0))) # this is a different epsilon. trajectory_collection_time = get_time(trajectory_collection_start_time) logging.vlog(1, "Collecting trajectories took %0.2f msec.", trajectory_collection_time) avg_reward = float(sum(np.sum(traj[2]) for traj in trajs)) / len(trajs) max_reward = max(np.sum(traj[2]) for traj in trajs) min_reward = min(np.sum(traj[2]) for traj in trajs) train_sw.scalar("train/mean_reward", avg_reward, step=i) logging.vlog(1, "Rewards avg=[%0.2f], max=[%0.2f], min=[%0.2f], all=%s", avg_reward, max_reward, min_reward, [float(np.sum(traj[2])) for traj in trajs]) logging.vlog(1, "Trajectory Length average=[%0.2f], max=[%0.2f], min=[%0.2f]", float(sum(len(traj[0]) for traj in trajs)) / len(trajs), max(len(traj[0]) for traj in trajs), min(len(traj[0]) for traj in trajs)) logging.vlog(2, "Trajectory Lengths: %s", [len(traj[0]) for traj in trajs]) padding_start_time = time.time() (_, reward_mask, padded_observations, padded_actions, padded_rewards) = pad_trajectories( trajs, boundary=boundary) padding_time = get_time(padding_start_time) logging.vlog(1, "Padding trajectories took %0.2f msec.", get_time(padding_start_time)) logging.vlog(1, "Padded Observations' shape [%s]", str(padded_observations.shape)) logging.vlog(1, "Padded Actions' shape [%s]", str(padded_actions.shape)) logging.vlog(1, "Padded Rewards' shape [%s]", str(padded_rewards.shape)) # Calculate log-probabilities and value predictions of the trajectories. # We'll pass these to the loss functions so as to not get recomputed. # NOTE: # There is a slight problem here, if the policy network contains # stochasticity in the log-probabilities (ex: dropout), then calculating # these again here is not going to be correct and should be done in the # collect function. log_prob_recompute_start_time = time.time() jax_rng_key, key = jax_random.split(jax_rng_key) log_probabs_traj, value_predictions_traj, _ = get_predictions( padded_observations, rng=key) log_prob_recompute_time = get_time(log_prob_recompute_start_time) # Some assertions. B, T = padded_actions.shape # pylint: disable=invalid-name assert (B, T) == padded_rewards.shape assert (B, T) == reward_mask.shape assert (B, T + 1) == padded_observations.shape[:2] assert (B, T + 1) + env.observation_space.shape == padded_observations.shape # Linear annealing from 0.1 to 0.0 # epsilon_schedule = epsilon if epochs == 1 else epsilon * (1.0 - # (i / # (epochs - 1))) # Constant epsilon. epsilon_schedule = epsilon # Compute value and ppo losses. jax_rng_key, key1 = jax_random.split(jax_rng_key, num=2) logging.vlog(2, "Starting to compute P&V loss.") loss_compute_start_time = time.time() cur_combined_loss, cur_ppo_loss, cur_value_loss, entropy_bonus = ( combined_loss( policy_and_value_net_params, log_probabs_traj, value_predictions_traj, policy_and_value_net_apply, padded_observations, padded_actions, padded_rewards, reward_mask, gamma=gamma, lambda_=lambda_, epsilon=epsilon_schedule, c1=c1, c2=c2, rng=key1)) loss_compute_time = get_time(loss_compute_start_time) logging.vlog( 1, "Calculating P&V loss [%10.2f(%10.2f, %10.2f, %10.2f)] took %0.2f msec.", cur_combined_loss, cur_value_loss, cur_ppo_loss, entropy_bonus, get_time(loss_compute_start_time)) jax_rng_key, key1 = jax_random.split(jax_rng_key, num=2) logging.vlog(1, "Policy and Value Optimization") optimization_start_time = time.time() keys = jax_random.split(key1, num=num_optimizer_steps) for j in range(num_optimizer_steps): k1, k2, k3 = jax_random.split(keys[j], num=3) t = time.time() # Update the optimizer state. policy_and_value_opt_state = policy_and_value_opt_step( j, policy_and_value_opt_state, policy_and_value_opt_update, policy_and_value_get_params, policy_and_value_net_apply, log_probabs_traj, value_predictions_traj, padded_observations, padded_actions, padded_rewards, reward_mask, c1=c1, c2=c2, gamma=gamma, lambda_=lambda_, epsilon=epsilon_schedule, rng=k1) # Compute the approx KL for early stopping. new_policy_and_value_net_params = policy_and_value_get_params( policy_and_value_opt_state) log_probab_actions_new, _ = policy_and_value_net_apply( padded_observations, new_policy_and_value_net_params, rng=k2) approx_kl = approximate_kl(log_probab_actions_new, log_probabs_traj, reward_mask) early_stopping = enable_early_stopping and approx_kl > 1.5 * target_kl if early_stopping: logging.vlog( 1, "Early stopping policy and value optimization at iter: %d, " "with approx_kl: %0.2f", j, approx_kl) # We don't return right-away, we want the below to execute on the last # iteration. t2 = time.time() if (((j + 1) % print_every_optimizer_steps == 0) or (j == num_optimizer_steps - 1) or early_stopping): # Compute and log the loss. (loss_combined, loss_ppo, loss_value, entropy_bonus) = ( combined_loss( new_policy_and_value_net_params, log_probabs_traj, value_predictions_traj, policy_and_value_net_apply, padded_observations, padded_actions, padded_rewards, reward_mask, gamma=gamma, lambda_=lambda_, epsilon=epsilon_schedule, c1=c1, c2=c2, rng=k3)) logging.vlog(1, "One Policy and Value grad desc took: %0.2f msec", get_time(t, t2)) logging.vlog( 1, "Combined Loss(value, ppo, entropy_bonus) [%10.2f] ->" " [%10.2f(%10.2f,%10.2f,%10.2f)]", cur_combined_loss, loss_combined, loss_value, loss_ppo, entropy_bonus) if early_stopping: break optimization_time = get_time(optimization_start_time) logging.vlog( 1, "Total Combined Loss reduction [%0.2f]%%", (100 * (cur_combined_loss - loss_combined) / np.abs(cur_combined_loss))) # Save parameters every time we see the end of at least a fraction of batch # number of trajectories that are done (not completed -- completed includes # truncated and done). # Also don't save too frequently, enforce a minimum gap. # Or if this is the last iteration. policy_save_start_time = time.time() num_trajectories_done += num_done if (((num_trajectories_done >= done_frac_for_policy_save * batch_size) and (i - last_saved_at > eval_every_n)) or (i == epochs - 1)): logging.vlog(1, "Epoch [% 6d] saving model.", i) params_file = os.path.join(output_dir, "model-%06d.pkl" % i) with gfile.GFile(params_file, "wb") as f: pickle.dump(policy_and_value_net_params, f) # Reset this number. num_trajectories_done = 0 last_saved_at = i policy_save_time = get_time(policy_save_start_time) epoch_time = get_time(epoch_start_time) logging.info( "Epoch [% 6d], Reward[min, max, avg] [%5.2f,%5.2f,%5.2f], Combined" " Loss(value, ppo, entropy) [%2.5f(%2.5f,%2.5f,%2.5f)]", i, min_reward, max_reward, avg_reward, loss_combined, loss_value, loss_ppo, entropy_bonus) timing_dict = { "epoch": epoch_time, "policy_eval": policy_eval_time, "trajectory_collection": trajectory_collection_time, "padding": padding_time, "log_prob_recompute": log_prob_recompute_time, "loss_compute": loss_compute_time, "optimization": optimization_time, "policy_save": policy_save_time, } for k, v in timing_dict.items(): timing_sw.scalar("timing/%s" % k, v, step=i) max_key_len = max(len(k) for k in timing_dict) timing_info_list = [ "%s : % 10.2f" % (k.rjust(max_key_len + 1), v) for k, v in sorted(timing_dict.items()) ] logging.info("Epoch [% 6d], Timings: \n%s", i, "\n".join(timing_info_list)) # Reset restore. restore = False # Flush summary writers once in a while. if (i+1) % 1000 == 0 or i == epochs - 1: train_sw.flush() timing_sw.flush() eval_sw.flush()
[ "jax.numpy.abs", "tensor2tensor.trax.trax.get_random_number_generator_and_set_seed", "absl.logging.info", "tensor2tensor.trax.optimizers.Adam", "jax.jit", "jax.numpy.mean", "jax.random.split", "tensor2tensor.trax.layers.LogSoftmax", "tensorflow.io.gfile.GFile", "jax.numpy.std", "absl.logging.vlog", "jax.numpy.uint8", "tensor2tensor.envs.env_problem_utils.play_env_problem_with_policy", "jax.numpy.uint16", "pickle.load", "tensor2tensor.trax.layers.Dense", "tensor2tensor.trax.layers.Serial", "jax.numpy.clip", "jax.numpy.stack", "time.time", "numpy.ones_like", "pickle.dump", "jax.numpy.arange", "jax.numpy.exp", "jax.lax.pad", "os.path.join", "jax.numpy.array", "tensorflow.io.gfile.makedirs", "jax.numpy.sum", "jax.numpy.maximum", "functools.partial", "os.path.basename", "jax.grad", "jax.numpy.squeeze" ]
[((20220, 20263), 'functools.partial', 'functools.partial', (['jit'], {'static_argnums': '(3,)'}), '(jit, static_argnums=(3,))\n', (20237, 20263), False, 'import functools\n'), ((21315, 21363), 'functools.partial', 'functools.partial', (['jit'], {'static_argnums': '(2, 3, 4)'}), '(jit, static_argnums=(2, 3, 4))\n', (21332, 21363), False, 'import functools\n'), ((3762, 3825), 'tensor2tensor.trax.optimizers.Adam', 'trax_opt.Adam', ([], {'step_size': 'step_size', 'b1': '(0.9)', 'b2': '(0.999)', 'eps': '(1e-08)'}), '(step_size=step_size, b1=0.9, b2=0.999, eps=1e-08)\n', (3775, 3825), True, 'from tensor2tensor.trax import optimizers as trax_opt\n'), ((5850, 6062), 'tensor2tensor.envs.env_problem_utils.play_env_problem_with_policy', 'env_problem_utils.play_env_problem_with_policy', (['env', 'policy_fun'], {'num_trajectories': 'num_trajectories', 'max_timestep': 'max_timestep', 'boundary': 'boundary', 'policy_sampling': 'policy', 'eps': 'epsilon', 'reset': 'reset', 'rng': 'rng'}), '(env, policy_fun,\n num_trajectories=num_trajectories, max_timestep=max_timestep, boundary=\n boundary, policy_sampling=policy, eps=epsilon, reset=reset, rng=rng)\n', (5896, 6062), False, 'from tensor2tensor.envs import env_problem_utils\n'), ((12385, 12421), 'jax.numpy.squeeze', 'np.squeeze', (['value_prediction'], {'axis': '(2)'}), '(value_prediction, axis=2)\n', (12395, 12421), True, 'from jax import numpy as np\n'), ((16885, 16933), 'jax.numpy.clip', 'np.clip', (['probab_ratios', '(1 - epsilon)', '(1 + epsilon)'], {}), '(probab_ratios, 1 - epsilon, 1 + epsilon)\n', (16892, 16933), True, 'from jax import numpy as np\n'), ((25327, 25355), 'os.path.basename', 'os.path.basename', (['model_file'], {}), '(model_file)\n', (25343, 25355), False, 'import os\n'), ((26310, 26336), 'tensorflow.io.gfile.makedirs', 'gfile.makedirs', (['output_dir'], {}), '(output_dir)\n', (26324, 26336), False, 'from tensorflow.io import gfile\n'), ((26723, 26781), 'tensor2tensor.trax.trax.get_random_number_generator_and_set_seed', 'trax.get_random_number_generator_and_set_seed', (['random_seed'], {}), '(random_seed)\n', (26768, 26781), False, 'from tensor2tensor.trax import trax\n'), ((27100, 27136), 'jax.random.split', 'jax_random.split', (['jax_rng_key'], {'num': '(2)'}), '(jax_rng_key, num=2)\n', (27116, 27136), True, 'from jax import random as jax_random\n'), ((27774, 27805), 'jax.jit', 'jit', (['policy_and_value_net_apply'], {}), '(policy_and_value_net_apply)\n', (27777, 27805), False, 'from jax import jit\n'), ((28111, 28158), 'absl.logging.info', 'logging.info', (['"""Starting the PPO training loop."""'], {}), "('Starting the PPO training loop.')\n", (28123, 28158), False, 'from absl import logging\n'), ((3260, 3281), 'tensor2tensor.trax.layers.Serial', 'layers.Serial', (['*tower'], {}), '(*tower)\n', (3273, 3281), False, 'from tensor2tensor.trax import layers\n'), ((6385, 6396), 'jax.numpy.uint8', 'np.uint8', (['(0)'], {}), '(0)\n', (6393, 6396), True, 'from jax import numpy as np\n'), ((8773, 8814), 'jax.lax.pad', 'lax.pad', (['o', 'padding_value', 'padding_config'], {}), '(o, padding_value, padding_config)\n', (8780, 8814), False, 'from jax import lax\n'), ((8997, 9045), 'jax.lax.pad', 'lax.pad', (['a', 'action_padding_value', 'padding_config'], {}), '(a, action_padding_value, padding_config)\n', (9004, 9045), False, 'from jax import lax\n'), ((9107, 9155), 'jax.lax.pad', 'lax.pad', (['r', 'reward_padding_value', 'padding_config'], {}), '(r, reward_padding_value, padding_config)\n', (9114, 9155), False, 'from jax import lax\n'), ((9257, 9289), 'numpy.ones_like', 'onp.ones_like', (['r'], {'dtype': 'np.int32'}), '(r, dtype=np.int32)\n', (9270, 9289), True, 'import numpy as onp\n'), ((9381, 9403), 'jax.numpy.stack', 'np.stack', (['reward_masks'], {}), '(reward_masks)\n', (9389, 9403), True, 'from jax import numpy as np\n'), ((9405, 9434), 'jax.numpy.stack', 'np.stack', (['padded_observations'], {}), '(padded_observations)\n', (9413, 9434), True, 'from jax import numpy as np\n'), ((9443, 9467), 'jax.numpy.stack', 'np.stack', (['padded_actions'], {}), '(padded_actions)\n', (9451, 9467), True, 'from jax import numpy as np\n'), ((9469, 9493), 'jax.numpy.stack', 'np.stack', (['padded_rewards'], {}), '(padded_rewards)\n', (9477, 9493), True, 'from jax import numpy as np\n'), ((11201, 11223), 'jax.numpy.stack', 'np.stack', (['r2gs'], {'axis': '(1)'}), '(r2gs, axis=1)\n', (11209, 11223), True, 'from jax import numpy as np\n'), ((12714, 12754), 'jax.numpy.squeeze', 'np.squeeze', (['value_prediction_old'], {'axis': '(2)'}), '(value_prediction_old, axis=2)\n', (12724, 12754), True, 'from jax import numpy as np\n'), ((13017, 13049), 'jax.numpy.maximum', 'np.maximum', (['v_clipped_loss', 'loss'], {}), '(v_clipped_loss, loss)\n', (13027, 13049), True, 'from jax import numpy as np\n'), ((13116, 13128), 'jax.numpy.sum', 'np.sum', (['loss'], {}), '(loss)\n', (13122, 13128), True, 'from jax import numpy as np\n'), ((13131, 13150), 'jax.numpy.sum', 'np.sum', (['reward_mask'], {}), '(reward_mask)\n', (13137, 13150), True, 'from jax import numpy as np\n'), ((16715, 16742), 'jax.numpy.exp', 'np.exp', (['(logp_new - logp_old)'], {}), '(logp_new - logp_old)\n', (16721, 16742), True, 'from jax import numpy as np\n'), ((18091, 18132), 'jax.numpy.squeeze', 'np.squeeze', (['value_predictions_old'], {'axis': '(2)'}), '(value_predictions_old, axis=2)\n', (18101, 18132), True, 'from jax import numpy as np\n'), ((18392, 18410), 'jax.numpy.std', 'np.std', (['advantages'], {}), '(advantages)\n', (18398, 18410), True, 'from jax import numpy as np\n'), ((18764, 18781), 'jax.numpy.sum', 'np.sum', (['objective'], {}), '(objective)\n', (18770, 18781), True, 'from jax import numpy as np\n'), ((18784, 18803), 'jax.numpy.sum', 'np.sum', (['reward_mask'], {}), '(reward_mask)\n', (18790, 18803), True, 'from jax import numpy as np\n'), ((22735, 22762), 'jax.grad', 'grad', (['policy_and_value_loss'], {}), '(policy_and_value_loss)\n', (22739, 22762), False, 'from jax import grad\n'), ((22907, 22918), 'time.time', 'time.time', ([], {}), '()\n', (22916, 22918), False, 'import time\n'), ((23464, 23476), 'jax.numpy.sum', 'np.sum', (['diff'], {}), '(diff)\n', (23470, 23476), True, 'from jax import numpy as np\n'), ((23479, 23491), 'jax.numpy.sum', 'np.sum', (['mask'], {}), '(mask)\n', (23485, 23491), True, 'from jax import numpy as np\n'), ((23833, 23843), 'jax.numpy.exp', 'np.exp', (['lp'], {}), '(lp)\n', (23839, 23843), True, 'from jax import numpy as np\n'), ((24351, 24523), 'tensor2tensor.envs.env_problem_utils.play_env_problem_with_policy', 'env_problem_utils.play_env_problem_with_policy', (['eval_env', 'get_predictions'], {'boundary': 'boundary', 'max_timestep': 'max_timestep', 'reset': '(True)', 'policy_sampling': 'policy', 'rng': 'rng'}), '(eval_env, get_predictions,\n boundary=boundary, max_timestep=max_timestep, reset=True,\n policy_sampling=policy, rng=rng)\n', (24397, 24523), False, 'from tensor2tensor.envs import env_problem_utils\n'), ((25146, 25190), 'os.path.join', 'os.path.join', (['output_dir', '"""model-??????.pkl"""'], {}), "(output_dir, 'model-??????.pkl')\n", (25158, 25190), False, 'import os\n'), ((25435, 25464), 'tensorflow.io.gfile.GFile', 'gfile.GFile', (['model_file', '"""rb"""'], {}), "(model_file, 'rb')\n", (25446, 25464), False, 'from tensorflow.io import gfile\n'), ((25505, 25519), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (25516, 25519), False, 'import pickle\n'), ((26414, 26447), 'os.path.join', 'os.path.join', (['output_dir', '"""train"""'], {}), "(output_dir, 'train')\n", (26426, 26447), False, 'import os\n'), ((26486, 26520), 'os.path.join', 'os.path.join', (['output_dir', '"""timing"""'], {}), "(output_dir, 'timing')\n", (26498, 26520), False, 'import os\n'), ((26557, 26589), 'os.path.join', 'os.path.join', (['output_dir', '"""eval"""'], {}), "(output_dir, 'eval')\n", (26569, 26589), False, 'import os\n'), ((27609, 27675), 'absl.logging.info', 'logging.info', (['"""Restored parameters from iteration [%d]"""', 'iteration'], {}), "('Restored parameters from iteration [%d]', iteration)\n", (27621, 27675), False, 'from absl import logging\n'), ((28219, 28230), 'time.time', 'time.time', ([], {}), '()\n', (28228, 28230), False, 'import time\n'), ((28823, 28834), 'time.time', 'time.time', ([], {}), '()\n', (28832, 28834), False, 'import time\n'), ((29455, 29466), 'time.time', 'time.time', ([], {}), '()\n', (29464, 29466), False, 'import time\n'), ((29471, 29530), 'absl.logging.vlog', 'logging.vlog', (['(1)', '"""Epoch [% 6d] collecting trajectories."""', 'i'], {}), "(1, 'Epoch [% 6d] collecting trajectories.', i)\n", (29483, 29530), False, 'from absl import logging\n'), ((29554, 29583), 'jax.random.split', 'jax_random.split', (['jax_rng_key'], {}), '(jax_rng_key)\n', (29570, 29583), True, 'from jax import random as jax_random\n'), ((29978, 30069), 'absl.logging.vlog', 'logging.vlog', (['(1)', '"""Collecting trajectories took %0.2f msec."""', 'trajectory_collection_time'], {}), "(1, 'Collecting trajectories took %0.2f msec.',\n trajectory_collection_time)\n", (29990, 30069), False, 'from absl import logging\n'), ((30915, 30926), 'time.time', 'time.time', ([], {}), '()\n', (30924, 30926), False, 'import time\n'), ((31924, 31935), 'time.time', 'time.time', ([], {}), '()\n', (31933, 31935), False, 'import time\n'), ((31959, 31988), 'jax.random.split', 'jax_random.split', (['jax_rng_key'], {}), '(jax_rng_key)\n', (31975, 31988), True, 'from jax import random as jax_random\n'), ((32845, 32881), 'jax.random.split', 'jax_random.split', (['jax_rng_key'], {'num': '(2)'}), '(jax_rng_key, num=2)\n', (32861, 32881), True, 'from jax import random as jax_random\n'), ((32886, 32934), 'absl.logging.vlog', 'logging.vlog', (['(2)', '"""Starting to compute P&V loss."""'], {}), "(2, 'Starting to compute P&V loss.')\n", (32898, 32934), False, 'from absl import logging\n'), ((32965, 32976), 'time.time', 'time.time', ([], {}), '()\n', (32974, 32976), False, 'import time\n'), ((33794, 33830), 'jax.random.split', 'jax_random.split', (['jax_rng_key'], {'num': '(2)'}), '(jax_rng_key, num=2)\n', (33810, 33830), True, 'from jax import random as jax_random\n'), ((33835, 33883), 'absl.logging.vlog', 'logging.vlog', (['(1)', '"""Policy and Value Optimization"""'], {}), "(1, 'Policy and Value Optimization')\n", (33847, 33883), False, 'from absl import logging\n'), ((33914, 33925), 'time.time', 'time.time', ([], {}), '()\n', (33923, 33925), False, 'import time\n'), ((33937, 33984), 'jax.random.split', 'jax_random.split', (['key1'], {'num': 'num_optimizer_steps'}), '(key1, num=num_optimizer_steps)\n', (33953, 33984), True, 'from jax import random as jax_random\n'), ((37087, 37098), 'time.time', 'time.time', ([], {}), '()\n', (37096, 37098), False, 'import time\n'), ((37695, 37934), 'absl.logging.info', 'logging.info', (['"""Epoch [% 6d], Reward[min, max, avg] [%5.2f,%5.2f,%5.2f], Combined Loss(value, ppo, entropy) [%2.5f(%2.5f,%2.5f,%2.5f)]"""', 'i', 'min_reward', 'max_reward', 'avg_reward', 'loss_combined', 'loss_value', 'loss_ppo', 'entropy_bonus'], {}), "(\n 'Epoch [% 6d], Reward[min, max, avg] [%5.2f,%5.2f,%5.2f], Combined Loss(value, ppo, entropy) [%2.5f(%2.5f,%2.5f,%2.5f)]'\n , i, min_reward, max_reward, avg_reward, loss_combined, loss_value,\n loss_ppo, entropy_bonus)\n", (37707, 37934), False, 'from absl import logging\n'), ((3566, 3588), 'tensor2tensor.trax.layers.Serial', 'layers.Serial', (['*tower1'], {}), '(*tower1)\n', (3579, 3588), False, 'from tensor2tensor.trax import layers\n'), ((3598, 3620), 'tensor2tensor.trax.layers.Serial', 'layers.Serial', (['*tower2'], {}), '(*tower2)\n', (3611, 3620), False, 'from tensor2tensor.trax import layers\n'), ((6444, 6456), 'jax.numpy.uint16', 'np.uint16', (['(0)'], {}), '(0)\n', (6453, 6456), True, 'from jax import numpy as np\n'), ((9314, 9353), 'jax.lax.pad', 'lax.pad', (['reward_mask', '(0)', 'padding_config'], {}), '(reward_mask, 0, padding_config)\n', (9321, 9353), False, 'from jax import lax\n'), ((12887, 12954), 'jax.numpy.clip', 'np.clip', (['(value_prediction - value_prediction_old)', '(-epsilon)', 'epsilon'], {}), '(value_prediction - value_prediction_old, -epsilon, epsilon)\n', (12894, 12954), True, 'from jax import numpy as np\n'), ((14032, 14043), 'jax.numpy.array', 'np.array', (['d'], {}), '(d)\n', (14040, 14043), True, 'from jax import numpy as np\n'), ((15596, 15608), 'jax.numpy.arange', 'np.arange', (['T'], {}), '(T)\n', (15605, 15608), True, 'from jax import numpy as np\n'), ((18369, 18388), 'jax.numpy.mean', 'np.mean', (['advantages'], {}), '(advantages)\n', (18376, 18388), True, 'from jax import numpy as np\n'), ((23943, 23957), 'jax.numpy.sum', 'np.sum', (['(lp * p)'], {}), '(lp * p)\n', (23949, 23957), True, 'from jax import numpy as np\n'), ((23960, 23972), 'jax.numpy.sum', 'np.sum', (['mask'], {}), '(mask)\n', (23966, 23972), True, 'from jax import numpy as np\n'), ((28572, 28600), 'jax.random.split', 'jax_random.split', (['rng'], {'num': '(2)'}), '(rng, num=2)\n', (28588, 28600), True, 'from jax import random as jax_random\n'), ((28919, 28955), 'jax.random.split', 'jax_random.split', (['jax_rng_key'], {'num': '(2)'}), '(jax_rng_key, num=2)\n', (28935, 28955), True, 'from jax import random as jax_random\n'), ((28963, 29016), 'absl.logging.vlog', 'logging.vlog', (['(1)', '"""Epoch [% 6d] evaluating policy."""', 'i'], {}), "(1, 'Epoch [% 6d] evaluating policy.', i)\n", (28975, 29016), False, 'from absl import logging\n'), ((34045, 34077), 'jax.random.split', 'jax_random.split', (['keys[j]'], {'num': '(3)'}), '(keys[j], num=3)\n', (34061, 34077), True, 'from jax import random as jax_random\n'), ((34088, 34099), 'time.time', 'time.time', ([], {}), '()\n', (34097, 34099), False, 'import time\n'), ((35450, 35461), 'time.time', 'time.time', ([], {}), '()\n', (35459, 35461), False, 'import time\n'), ((37290, 37338), 'absl.logging.vlog', 'logging.vlog', (['(1)', '"""Epoch [% 6d] saving model."""', 'i'], {}), "(1, 'Epoch [% 6d] saving model.', i)\n", (37302, 37338), False, 'from absl import logging\n'), ((37359, 37405), 'os.path.join', 'os.path.join', (['output_dir', "('model-%06d.pkl' % i)"], {}), "(output_dir, 'model-%06d.pkl' % i)\n", (37371, 37405), False, 'import os\n'), ((3446, 3471), 'tensor2tensor.trax.layers.Dense', 'layers.Dense', (['num_actions'], {}), '(num_actions)\n', (3458, 3471), False, 'from tensor2tensor.trax import layers\n'), ((3473, 3492), 'tensor2tensor.trax.layers.LogSoftmax', 'layers.LogSoftmax', ([], {}), '()\n', (3490, 3492), False, 'from tensor2tensor.trax import layers\n'), ((3514, 3529), 'tensor2tensor.trax.layers.Dense', 'layers.Dense', (['(1)'], {}), '(1)\n', (3526, 3529), False, 'from tensor2tensor.trax import layers\n'), ((8363, 8395), 'numpy.ones_like', 'onp.ones_like', (['r'], {'dtype': 'np.int32'}), '(r, dtype=np.int32)\n', (8376, 8395), True, 'import numpy as onp\n'), ((15573, 15585), 'jax.numpy.arange', 'np.arange', (['B'], {}), '(B)\n', (15582, 15585), True, 'from jax import numpy as np\n'), ((29289, 29358), 'absl.logging.info', 'logging.info', (['"""Epoch [% 6d] Policy Evaluation [%s] = %10.2f"""', 'i', 'k', 'v'], {}), "('Epoch [% 6d] Policy Evaluation [%s] = %10.2f', i, k, v)\n", (29301, 29358), False, 'from absl import logging\n'), ((30181, 30196), 'jax.numpy.sum', 'np.sum', (['traj[2]'], {}), '(traj[2])\n', (30187, 30196), True, 'from jax import numpy as np\n'), ((30237, 30252), 'jax.numpy.sum', 'np.sum', (['traj[2]'], {}), '(traj[2])\n', (30243, 30252), True, 'from jax import numpy as np\n'), ((35197, 35318), 'absl.logging.vlog', 'logging.vlog', (['(1)', '"""Early stopping policy and value optimization at iter: %d, with approx_kl: %0.2f"""', 'j', 'approx_kl'], {}), "(1,\n 'Early stopping policy and value optimization at iter: %d, with approx_kl: %0.2f'\n , j, approx_kl)\n", (35209, 35318), False, 'from absl import logging\n'), ((36302, 36484), 'absl.logging.vlog', 'logging.vlog', (['(1)', '"""Combined Loss(value, ppo, entropy_bonus) [%10.2f] -> [%10.2f(%10.2f,%10.2f,%10.2f)]"""', 'cur_combined_loss', 'loss_combined', 'loss_value', 'loss_ppo', 'entropy_bonus'], {}), "(1,\n 'Combined Loss(value, ppo, entropy_bonus) [%10.2f] -> [%10.2f(%10.2f,%10.2f,%10.2f)]'\n , cur_combined_loss, loss_combined, loss_value, loss_ppo, entropy_bonus)\n", (36314, 36484), False, 'from absl import logging\n'), ((36741, 36766), 'jax.numpy.abs', 'np.abs', (['cur_combined_loss'], {}), '(cur_combined_loss)\n', (36747, 36766), True, 'from jax import numpy as np\n'), ((37417, 37447), 'tensorflow.io.gfile.GFile', 'gfile.GFile', (['params_file', '"""wb"""'], {}), "(params_file, 'wb')\n", (37428, 37447), False, 'from tensorflow.io import gfile\n'), ((37462, 37505), 'pickle.dump', 'pickle.dump', (['policy_and_value_net_params', 'f'], {}), '(policy_and_value_net_params, f)\n', (37473, 37505), False, 'import pickle\n'), ((3226, 3241), 'tensor2tensor.trax.layers.Dense', 'layers.Dense', (['(1)'], {}), '(1)\n', (3238, 3241), False, 'from tensor2tensor.trax import layers\n'), ((30489, 30504), 'jax.numpy.sum', 'np.sum', (['traj[2]'], {}), '(traj[2])\n', (30495, 30504), True, 'from jax import numpy as np\n'), ((3165, 3190), 'tensor2tensor.trax.layers.Dense', 'layers.Dense', (['num_actions'], {}), '(num_actions)\n', (3177, 3190), False, 'from tensor2tensor.trax import layers\n'), ((3192, 3211), 'tensor2tensor.trax.layers.LogSoftmax', 'layers.LogSoftmax', ([], {}), '()\n', (3209, 3211), False, 'from tensor2tensor.trax import layers\n'), ((24618, 24633), 'jax.numpy.sum', 'np.sum', (['traj[2]'], {}), '(traj[2])\n', (24624, 24633), True, 'from jax import numpy as np\n'), ((30111, 30126), 'jax.numpy.sum', 'np.sum', (['traj[2]'], {}), '(traj[2])\n', (30117, 30126), True, 'from jax import numpy as np\n')]
""" Data: Temperature and Salinity time series from SIO Scripps Pier Salinity: measured in PSU at the surface (~0.5m) and at depth (~5m) Temp: measured in degrees C at the surface (~0.5m) and at depth (~5m) - Timestamp included beginning in 1990 """ # imports import sys,os import pandas as pd import numpy as np import matplotlib.pyplot as plt import datetime from scipy import signal import scipy.stats as ss import SIO_modules as SIO_mod from importlib import reload reload(SIO_mod) # read in temp and sal files sal_data = pd.read_csv('/Users/MMStoll/Python/Data/Ocean569_Data/SIO_Data/SIO_SALT_1916-201905.txt', sep='\t', skiprows = 27) temp_data = pd.read_csv('/Users/MMStoll/Python/Data/Ocean569_Data/SIO_Data/SIO_TEMP_1916_201905.txt', sep='\t', skiprows = 26) ENSO_data = pd.read_excel('/Users/MMStoll/Python/Data/Ocean569_Data/SIO_Data/NOAA_ENSO_data.xlsx') ENSO_data_recent = pd.read_excel('/Users/MMStoll/Python/Data/Ocean569_Data/SIO_Data/NOAA_ENSO_recent_data.xlsx') PDO_data = pd.read_csv('/Users/MMStoll/Python/Data/Ocean569_Data/SIO_Data/NOAA_PDO_data.csv', skiprows = 1) path_out = '/Users/MMStoll/Python/Output/Ocean569_Output/SIO_Output/' # convert year, month, day columns to single DATE column sal_data['DATE'] = pd.to_datetime(sal_data[['YEAR', 'MONTH', 'DAY']]) temp_data['DATE'] = pd.to_datetime(temp_data[['YEAR', 'MONTH', 'DAY']]) ENSO_data_all = ENSO_data.append(ENSO_data_recent[323:], ignore_index = True) PDO_data['DATE'] = pd.to_datetime(PDO_data['Date'], format='%Y%m') # remove uncertain data(SURF_FLAG between 1 and 4), replace with NaN, then interpolate for i in range(0,len(sal_data['SURF_SAL_PSU'])): if (sal_data['SURF_FLAG'][i] >= 1) and (sal_data['SURF_FLAG'][i] <=4): sal_data['SURF_SAL_PSU'][i] = np.nan for i in range(0,len(temp_data['SURF_TEMP_C'])): if (sal_data['SURF_FLAG'][i] >= 1) and (sal_data['SURF_FLAG'][i] <=4): sal_data['SURF_SAL_PSU'][i] = np.nan # interpolate missing temp and sal data sal_data['SURF_SAL_PSU'] = sal_data['SURF_SAL_PSU'].interpolate() temp_data['SURF_TEMP_C'] = temp_data['SURF_TEMP_C'].interpolate() sal_data['SURF_SAL_PSU'][0] = sal_data['SURF_SAL_PSU'][1] # remove the average from the sal and temp data and create new columns sal_data['SURF_SAL_PSU_NOAVG'] = sal_data['SURF_SAL_PSU'] - sal_data['SURF_SAL_PSU'].mean() temp_data['SURF_TEMP_C_NOAVG'] = temp_data['SURF_TEMP_C'] - temp_data['SURF_TEMP_C'].mean() # remove trends from the sal and temp data and create new columns sal_fit = np.polyfit(sal_data.index,sal_data['SURF_SAL_PSU_NOAVG'],1) sal_fit_fn = np.poly1d(sal_fit) temp_fit = np.polyfit(temp_data.index,temp_data['SURF_TEMP_C_NOAVG'],1) temp_fit_fn = np.poly1d(temp_fit) sal_fit_value = sal_fit_fn(sal_data.index) temp_fit_value = temp_fit_fn(temp_data.index) sal_data['SURF_SAL_PSU_DETREND'] = sal_data['SURF_SAL_PSU_NOAVG'] - sal_fit_value temp_data['SURF_TEMP_C_DETREND'] = temp_data['SURF_TEMP_C_NOAVG'] - temp_fit_value sal_tri = sal_data['SURF_SAL_PSU_DETREND'].rolling(center = True, window = 30, min_periods = 3, win_type = 'triang').mean() temp_tri = temp_data['SURF_TEMP_C_DETREND'].rolling(center = True, window = 30, min_periods = 3, win_type = 'triang').mean() # # 1. FFT the SIO Data # t_freq,t_spec,t_spec_amp,t_fft,t_delt,t_freq_T,t_freq_nyquist = SIO_mod.var_fft(temp_data['SURF_TEMP_C_DETREND']) # # 2. Apply butterworth filter to SIO data, with cutoff equal to nyquist freq of enso index # fs = 1 # sampling frequency, once per day # fc = 1/60 # cut-off frequency of the filter (cut off periods shorter than 60 days) # w = fc / (fs / 2) #normalize the frequency # b, a = signal.butter(4, w, 'low') # temp_output = signal.filtfilt(b, a, t_spec) # # 3. Inverse FFT of filtered SIO data # temp_ifft = np.fft.irfft(temp_output,n=len(temp_output)) # # 4. Subsample new SIO time series with same delta t as ENSO index (once per month) # temp_ifft_sampled = np.mean(temp_ifft[0:18750].reshape(-1, 30), axis=1) # temp_ifft_len = temp_ifft_sampled[0:618] # x = np.linspace(0,18770, 18770) # plt.figure() # plt.loglog(x, temp_ifft) # plt.show() # butterworth low pass filter for temperature and salinity fs = 1 # sampling frequency, once per day fc = 1/500 # cut-off frequency of the filter (cut off periods shorter than 500 days) w = fc / (fs / 2) #normalize the frequency b, a = signal.butter(4, w, 'low') temp_output = signal.filtfilt(b, a, temp_tri) sal_output = signal.filtfilt(b, a, sal_tri) temp_sampled = np.mean(temp_output[0:37530].reshape(-1, 30), axis=1) #length = 1251 # create dataframe with spectra for each variable spectra_temp_df = pd.DataFrame(columns = ['Temp_freq', 'Temp_spec', 'Temp_fft']) spectra_sal_df = pd.DataFrame(columns = ['Sal_freq', 'Sal_spec', 'Sal_fft']) spectra_PDO_df = pd.DataFrame(columns = ['PDO_freq', 'PDO_spec', 'PDO_fft']) spectra_ENSO_df = pd.DataFrame(columns = ['ENSO_freq', 'ENSO_spec', 'ENSO_fft']) # for coherence, start all records at 1916-01-01 # ENSO data [20:] 1916-09-01 onward, monthly// ends now, through 2019-05-01 [:1254] # Temp data [10:] 1916-09-01 onward, daily // ends 2019-05-31 # PDO data [752:] 1916-09-01 onward, monthly// ends now, thorugh 2019-05-01 [:1985] # compute spectral variables for each variable for j in range(0,4): data_sets = [temp_sampled, sal_data['SURF_SAL_PSU_DETREND'], PDO_data['Value'][743:], ENSO_data_all['VALUE'][14:]] freq, spec, spec_amp, fft, delt, freq_T, freq_nyquist = SIO_mod.var_fft(data_sets[j]) if j == 0: spectra_temp_df['Temp_freq'] = freq spectra_temp_df['Temp_spec'] = spec spectra_temp_df['Temp_fft'] = fft if j == 1: spectra_sal_df['Sal_freq'] = freq spectra_sal_df['Sal_spec'] = spec spectra_sal_df['Sal_fft'] = fft if j == 2: spectra_PDO_df['PDO_freq'] = freq spectra_PDO_df['PDO_spec'] = spec spectra_PDO_df['PDO_fft'] = fft if j == 3: spectra_ENSO_df['ENSO_freq'] = freq spectra_ENSO_df['ENSO_spec'] = spec spectra_ENSO_df['ENSO_fft'] = fft def band_average(fft_var1,fft_var2,frequency,n_av): # fft_var1 and fft_var2 are the inputs computed via fft # they can be the same variable or different variables # n_av is the number of bands to be used for smoothing (nice if it is an odd number) # this function is limnited to 100,000 points but can easily be modified nmax=100000 # T_length = (len(fft_var1) * 2 - 2) # define some variables and arrays n_spec=len(fft_var1) n_av2=int(n_av//2+1) #number of band averages/2 + 1 spec_amp_av=np.zeros(nmax) spec_phase_av=np.zeros(nmax) freq_av=np.zeros(nmax) # average the lowest frequency bands first (with half as many points in the average) sum_low_amp=0. sum_low_phase=0. count=0 spectrum_amp=np.absolute(fft_var1*np.conj(fft_var2))#/(2.*np.pi*T_length*delt) spectrum_phase=np.angle(fft_var1*np.conj(fft_var2),deg=True) #/(2.*np.pi*T_length*delt) don't know if I need the 2pi/Tdeltt here... # for i in range(0,n_av2): sum_low_amp+=spectrum_amp[i] sum_low_phase+=spectrum_phase[i] spec_amp_av[0]=sum_low_amp/n_av2 spec_phase_av[0]=sum_low_phase/n_av # compute the rest of the averages for i in range(n_av2,n_spec-n_av,n_av): count+=1 spec_amp_est=np.mean(spectrum_amp[i:i+n_av]) spec_phase_est=np.mean(spectrum_phase[i:i+n_av]) freq_est=frequency[i+n_av//2] spec_amp_av[count]=spec_amp_est spec_phase_av[count]=spec_phase_est freq_av[count]=freq_est # omega0 = 2.*np.pi/(T_length*delt) # contract the arrays spec_amp_av=spec_amp_av[0:count] spec_phase_av=spec_phase_av[0:count] freq_av=freq_av[0:count] return spec_amp_av,spec_phase_av,freq_av,count n_av = 5 # define terms to compute coherence between temp and ENSO t_freq,t_spec,t_spec_amp,t_fft,t_delt,t_freq_T,t_freq_nyquist = SIO_mod.var_fft(temp_sampled) #take fft/compute spectra of temp_sampled at 30 day intervals t_spec_b,t_phase_b,t_freq_av_b,count=band_average(t_fft,t_fft,t_freq,n_av) e_spec_b,e_phase_b,e_freq_av_b,count=band_average(spectra_ENSO_df['ENSO_fft'],spectra_ENSO_df['ENSO_fft'],spectra_ENSO_df['ENSO_freq'],n_av) e_fft_star = np.conj(spectra_ENSO_df['ENSO_fft']) cospec_amp2,cospec_phase2,freq_av2,count2=band_average(t_fft,e_fft_star,spectra_ENSO_df['ENSO_freq'],n_av) coh_sq2=cospec_amp2**2/(t_spec_b*e_spec_b) # define colors t_color = 'cadetblue' s_color = 'darkslateblue' p_color = 'seagreen' e_color = 'steelblue' freq_ann = 2*np.pi/365.25 # plot the coherence and phase between ENSO and temperature tstr = 'SIO Temperature and ENSO Index \nCoherence and Phase' im_name = 'SIO_TempENSO_CoherencePhase.jpg' NR = 2; NC = 1 fig, axes = plt.subplots(nrows = NR,ncols=NC,figsize = (10,7)) axes[0].semilogx(freq_av2,coh_sq2, color = e_color) axes[0].set_xlabel('$\omega$ (radians/day)') axes[0].set_ylabel('Squared Coherence $\it{T}$-$\it{ENSO}$') axes[0].axvline(t_freq_nyquist, color = 'black', linestyle = '--', alpha = 0.5) axes[0].text(0.075, 0.1,'$\omega_{max}$', alpha = 0.5) #transform = ax.transAxes) axes[0].axvline(t_freq_T, color = 'black', linestyle = '--', alpha = 0.5) axes[0].text(0.00018, 0.1,'$\omega_o$', alpha = 0.5) #transform = ax.transAxes) axes[0].axvline(freq_ann, color = 'black', linestyle = '--', alpha = 0.5) axes[0].text(0.0098, 0.1, 'Annual', alpha = 0.5)#transform = ax.transAxes) axes[1].semilogx(freq_av2, cospec_phase2, color = e_color) axes[1].set_xlabel('$\omega$ (radians/day)') axes[1].set_ylabel('Phase $\it{T}$-$\it{ENSO}$, degrees') axes[1].axvline(t_freq_nyquist, color = 'black', linestyle = '--', alpha = 0.5) axes[1].text(0.075, -110,'$\omega_{max}$', alpha = 0.5) #transform = ax.transAxes) axes[1].axvline(t_freq_T, color = 'black', linestyle = '--', alpha = 0.5) axes[1].text(0.00018, -110,'$\omega_o$', alpha = 0.5)#transform = ax.transAxes) axes[1].axvline(freq_ann, color = 'black', linestyle = '--', alpha = 0.5) axes[1].text(0.0098, -110, 'Annual', alpha = 0.5)#transform = ax.transAxes) fig.suptitle(tstr) # fig.tight_layout(pad=2.0) plt.savefig(path_out + im_name) plt.show() n_av = 5 # define terms to compute coherence between temp and ENSO #t_freq,t_spec,t_spec_amp,t_fft,t_delt,t_freq_T,t_freq_nyquist = SIO_mod.var_fft(temp_sampled) #take fft/compute spectra of temp_sampled at 30 day intervals #t_spec_b,t_phase_b,t_freq_av_b,count=band_average(t_fft,t_fft,t_freq,n_av) p_spec_b,p_phase_b,p_freq_av_b,count=band_average(spectra_PDO_df['PDO_fft'],spectra_PDO_df['PDO_fft'],spectra_PDO_df['PDO_freq'],n_av) p_fft_star = np.conj(spectra_PDO_df['PDO_fft']) cospec_amp2,cospec_phase2,freq_av2,count2=band_average(t_fft,p_fft_star,spectra_PDO_df['PDO_freq'],n_av) coh_sq2=cospec_amp2**2/(t_spec_b*p_spec_b) # plot the coherence and phase between ENSO and temperature tstr = 'SIO Temperature and PDO Index \nCoherence and Phase' im_name = 'SIO_TempPDO_CoherencePhase.jpg' NR = 2; NC = 1 fig, axes = plt.subplots(nrows = NR,ncols=NC,figsize = (10,7)) axes[0].semilogx(freq_av2,coh_sq2, color = p_color) axes[0].set_xlabel('$\omega$ (radians/day)') axes[0].set_ylabel('Squared Coherence $\it{T}$-$\it{PDO}$') axes[0].axvline(t_freq_nyquist, color = 'black', linestyle = '--', alpha = 0.5) axes[0].text(0.075, 0.1,'$\omega_{max}$', alpha = 0.5) #transform = ax.transAxes) axes[0].axvline(t_freq_T, color = 'black', linestyle = '--', alpha = 0.5) axes[0].text(0.00018, 0.1,'$\omega_o$', alpha = 0.5) #transform = ax.transAxes) axes[0].axvline(freq_ann, color = 'black', linestyle = '--', alpha = 0.5) axes[0].text(0.0098, 0.1, 'Annual', alpha = 0.5)#transform = ax.transAxes) axes[1].semilogx(freq_av2, cospec_phase2, color = p_color) axes[1].set_xlabel('$\omega$ (radians/day)') axes[1].set_ylabel('Phase $\it{T}$-$\it{PDO}$, degrees') axes[1].axvline(t_freq_nyquist, color = 'black', linestyle = '--', alpha = 0.5) axes[1].text(0.075, -110,'$\omega_{max}$', alpha = 0.5) #transform = ax.transAxes) axes[1].axvline(t_freq_T, color = 'black', linestyle = '--', alpha = 0.5) axes[1].text(0.00018, -110,'$\omega_o$', alpha = 0.5)#transform = ax.transAxes) axes[1].axvline(freq_ann, color = 'black', linestyle = '--', alpha = 0.5) axes[1].text(0.0098, -110, 'Annual', alpha = 0.5)#transform = ax.transAxes) fig.suptitle(tstr) # fig.tight_layout(pad=2.0) plt.savefig(path_out + im_name) plt.show()
[ "numpy.mean", "matplotlib.pyplot.savefig", "SIO_modules.var_fft", "pandas.read_csv", "numpy.polyfit", "scipy.signal.filtfilt", "pandas.DataFrame", "numpy.conj", "scipy.signal.butter", "numpy.zeros", "importlib.reload", "pandas.read_excel", "numpy.poly1d", "matplotlib.pyplot.subplots", "pandas.to_datetime", "matplotlib.pyplot.show" ]
[((482, 497), 'importlib.reload', 'reload', (['SIO_mod'], {}), '(SIO_mod)\n', (488, 497), False, 'from importlib import reload\n'), ((539, 661), 'pandas.read_csv', 'pd.read_csv', (['"""/Users/MMStoll/Python/Data/Ocean569_Data/SIO_Data/SIO_SALT_1916-201905.txt"""'], {'sep': '"""\t"""', 'skiprows': '(27)'}), "(\n '/Users/MMStoll/Python/Data/Ocean569_Data/SIO_Data/SIO_SALT_1916-201905.txt'\n , sep='\\t', skiprows=27)\n", (550, 661), True, 'import pandas as pd\n'), ((666, 788), 'pandas.read_csv', 'pd.read_csv', (['"""/Users/MMStoll/Python/Data/Ocean569_Data/SIO_Data/SIO_TEMP_1916_201905.txt"""'], {'sep': '"""\t"""', 'skiprows': '(26)'}), "(\n '/Users/MMStoll/Python/Data/Ocean569_Data/SIO_Data/SIO_TEMP_1916_201905.txt'\n , sep='\\t', skiprows=26)\n", (677, 788), True, 'import pandas as pd\n'), ((793, 884), 'pandas.read_excel', 'pd.read_excel', (['"""/Users/MMStoll/Python/Data/Ocean569_Data/SIO_Data/NOAA_ENSO_data.xlsx"""'], {}), "(\n '/Users/MMStoll/Python/Data/Ocean569_Data/SIO_Data/NOAA_ENSO_data.xlsx')\n", (806, 884), True, 'import pandas as pd\n'), ((899, 1002), 'pandas.read_excel', 'pd.read_excel', (['"""/Users/MMStoll/Python/Data/Ocean569_Data/SIO_Data/NOAA_ENSO_recent_data.xlsx"""'], {}), "(\n '/Users/MMStoll/Python/Data/Ocean569_Data/SIO_Data/NOAA_ENSO_recent_data.xlsx'\n )\n", (912, 1002), True, 'import pandas as pd\n'), ((1004, 1107), 'pandas.read_csv', 'pd.read_csv', (['"""/Users/MMStoll/Python/Data/Ocean569_Data/SIO_Data/NOAA_PDO_data.csv"""'], {'skiprows': '(1)'}), "(\n '/Users/MMStoll/Python/Data/Ocean569_Data/SIO_Data/NOAA_PDO_data.csv',\n skiprows=1)\n", (1015, 1107), True, 'import pandas as pd\n'), ((1248, 1298), 'pandas.to_datetime', 'pd.to_datetime', (["sal_data[['YEAR', 'MONTH', 'DAY']]"], {}), "(sal_data[['YEAR', 'MONTH', 'DAY']])\n", (1262, 1298), True, 'import pandas as pd\n'), ((1319, 1370), 'pandas.to_datetime', 'pd.to_datetime', (["temp_data[['YEAR', 'MONTH', 'DAY']]"], {}), "(temp_data[['YEAR', 'MONTH', 'DAY']])\n", (1333, 1370), True, 'import pandas as pd\n'), ((1468, 1515), 'pandas.to_datetime', 'pd.to_datetime', (["PDO_data['Date']"], {'format': '"""%Y%m"""'}), "(PDO_data['Date'], format='%Y%m')\n", (1482, 1515), True, 'import pandas as pd\n'), ((2490, 2551), 'numpy.polyfit', 'np.polyfit', (['sal_data.index', "sal_data['SURF_SAL_PSU_NOAVG']", '(1)'], {}), "(sal_data.index, sal_data['SURF_SAL_PSU_NOAVG'], 1)\n", (2500, 2551), True, 'import numpy as np\n'), ((2563, 2581), 'numpy.poly1d', 'np.poly1d', (['sal_fit'], {}), '(sal_fit)\n', (2572, 2581), True, 'import numpy as np\n'), ((2593, 2655), 'numpy.polyfit', 'np.polyfit', (['temp_data.index', "temp_data['SURF_TEMP_C_NOAVG']", '(1)'], {}), "(temp_data.index, temp_data['SURF_TEMP_C_NOAVG'], 1)\n", (2603, 2655), True, 'import numpy as np\n'), ((2668, 2687), 'numpy.poly1d', 'np.poly1d', (['temp_fit'], {}), '(temp_fit)\n', (2677, 2687), True, 'import numpy as np\n'), ((4317, 4343), 'scipy.signal.butter', 'signal.butter', (['(4)', 'w', '"""low"""'], {}), "(4, w, 'low')\n", (4330, 4343), False, 'from scipy import signal\n'), ((4358, 4389), 'scipy.signal.filtfilt', 'signal.filtfilt', (['b', 'a', 'temp_tri'], {}), '(b, a, temp_tri)\n', (4373, 4389), False, 'from scipy import signal\n'), ((4403, 4433), 'scipy.signal.filtfilt', 'signal.filtfilt', (['b', 'a', 'sal_tri'], {}), '(b, a, sal_tri)\n', (4418, 4433), False, 'from scipy import signal\n'), ((4589, 4649), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['Temp_freq', 'Temp_spec', 'Temp_fft']"}), "(columns=['Temp_freq', 'Temp_spec', 'Temp_fft'])\n", (4601, 4649), True, 'import pandas as pd\n'), ((4669, 4726), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['Sal_freq', 'Sal_spec', 'Sal_fft']"}), "(columns=['Sal_freq', 'Sal_spec', 'Sal_fft'])\n", (4681, 4726), True, 'import pandas as pd\n'), ((4746, 4803), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['PDO_freq', 'PDO_spec', 'PDO_fft']"}), "(columns=['PDO_freq', 'PDO_spec', 'PDO_fft'])\n", (4758, 4803), True, 'import pandas as pd\n'), ((4824, 4884), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['ENSO_freq', 'ENSO_spec', 'ENSO_fft']"}), "(columns=['ENSO_freq', 'ENSO_spec', 'ENSO_fft'])\n", (4836, 4884), True, 'import pandas as pd\n'), ((7778, 7807), 'SIO_modules.var_fft', 'SIO_mod.var_fft', (['temp_sampled'], {}), '(temp_sampled)\n', (7793, 7807), True, 'import SIO_modules as SIO_mod\n'), ((8099, 8135), 'numpy.conj', 'np.conj', (["spectra_ENSO_df['ENSO_fft']"], {}), "(spectra_ENSO_df['ENSO_fft'])\n", (8106, 8135), True, 'import numpy as np\n'), ((8615, 8664), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': 'NR', 'ncols': 'NC', 'figsize': '(10, 7)'}), '(nrows=NR, ncols=NC, figsize=(10, 7))\n', (8627, 8664), True, 'import matplotlib.pyplot as plt\n'), ((9965, 9996), 'matplotlib.pyplot.savefig', 'plt.savefig', (['(path_out + im_name)'], {}), '(path_out + im_name)\n', (9976, 9996), True, 'import matplotlib.pyplot as plt\n'), ((9997, 10007), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (10005, 10007), True, 'import matplotlib.pyplot as plt\n'), ((10457, 10491), 'numpy.conj', 'np.conj', (["spectra_PDO_df['PDO_fft']"], {}), "(spectra_PDO_df['PDO_fft'])\n", (10464, 10491), True, 'import numpy as np\n'), ((10833, 10882), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': 'NR', 'ncols': 'NC', 'figsize': '(10, 7)'}), '(nrows=NR, ncols=NC, figsize=(10, 7))\n', (10845, 10882), True, 'import matplotlib.pyplot as plt\n'), ((12181, 12212), 'matplotlib.pyplot.savefig', 'plt.savefig', (['(path_out + im_name)'], {}), '(path_out + im_name)\n', (12192, 12212), True, 'import matplotlib.pyplot as plt\n'), ((12213, 12223), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (12221, 12223), True, 'import matplotlib.pyplot as plt\n'), ((5409, 5438), 'SIO_modules.var_fft', 'SIO_mod.var_fft', (['data_sets[j]'], {}), '(data_sets[j])\n', (5424, 5438), True, 'import SIO_modules as SIO_mod\n'), ((6441, 6455), 'numpy.zeros', 'np.zeros', (['nmax'], {}), '(nmax)\n', (6449, 6455), True, 'import numpy as np\n'), ((6474, 6488), 'numpy.zeros', 'np.zeros', (['nmax'], {}), '(nmax)\n', (6482, 6488), True, 'import numpy as np\n'), ((6501, 6515), 'numpy.zeros', 'np.zeros', (['nmax'], {}), '(nmax)\n', (6509, 6515), True, 'import numpy as np\n'), ((7178, 7211), 'numpy.mean', 'np.mean', (['spectrum_amp[i:i + n_av]'], {}), '(spectrum_amp[i:i + n_av])\n', (7185, 7211), True, 'import numpy as np\n'), ((7233, 7268), 'numpy.mean', 'np.mean', (['spectrum_phase[i:i + n_av]'], {}), '(spectrum_phase[i:i + n_av])\n', (7240, 7268), True, 'import numpy as np\n'), ((6692, 6709), 'numpy.conj', 'np.conj', (['fft_var2'], {}), '(fft_var2)\n', (6699, 6709), True, 'import numpy as np\n'), ((6774, 6791), 'numpy.conj', 'np.conj', (['fft_var2'], {}), '(fft_var2)\n', (6781, 6791), True, 'import numpy as np\n')]
import numpy as np def normalize(x): return x / np.linalg.norm(x) def norm_sq(v): return np.dot(v,v) def norm(v): return np.linalg.norm(v) def get_sub_keys(v): if type(v) is not tuple and type(v) is not list: return [] return [k for k in v if type(k) is str] def to_vec3(v): if isinstance(v, (float, int)): return np.array([v, v, v], dtype=np.float32) elif len(get_sub_keys(v)) > 0: return v else: return np.array([v[0], v[1], v[2]], dtype=np.float32) def to_str(x): if type(x) is bool: return "1" if x else "0" elif isinstance(x, (list, tuple)): return vec3_str(x) else: return str(x) def float_str(x): if type(x) is str: return '_' + x else: return str(x) def vec3_str(v): if type(v) is str: return '_' + v elif isinstance(v, (float, int)): return 'vec3(' + str(v) + ')' else: return 'vec3(' + float_str(v[0]) + ',' + float_str(v[1]) + ',' + float_str(v[2]) + ')' def vec3_eq(v, val): if type(v) is str: return False for i in range(3): if v[i] != val[i]: return False return True def smin(a, b, k): h = min(max(0.5 + 0.5*(b - a)/k, 0.0), 1.0) return b*(1 - h) + a*h - k*h*(1.0 - h) def get_global(k): if type(k) is str: return _mandelbruh_GLOBAL_VARS[k] elif type(k) is tuple or type(k) is list: return np.array([get_global(i) for i in k], dtype=np.float32) else: return k def set_global_float(k): if type(k) is str: _mandelbruh_GLOBAL_VARS[k] = 0.0 return k def set_global_vec3(k): if type(k) is str: _mandelbruh_GLOBAL_VARS[k] = to_vec3((0,0,0)) return k elif isinstance(k, (float, int)): return to_vec3(k) else: sk = get_sub_keys(k) for i in sk: _mandelbruh_GLOBAL_VARS[i] = 0.0 return to_vec3(k) def cond_offset(p): if type(p) is str or np.count_nonzero(p) > 0: return ' - vec4(' + vec3_str(p) + ', 0)' return '' def cond_subtract(p): if type(p) is str or p > 0: return ' - ' + float_str(p) return '' def make_color(geo): if type(geo.color) is tuple or type(geo.color) is np.ndarray: return 'vec4(' + vec3_str(geo.color) + ', ' + geo.glsl() + ')' elif geo.color == 'orbit' or geo.color == 'o': return 'vec4(orbit, ' + geo.glsl() + ')' else: raise Exception("Invalid coloring type") _mandelbruh_GLOBAL_VARS = {}
[ "numpy.count_nonzero", "numpy.array", "numpy.dot", "numpy.linalg.norm" ]
[((93, 105), 'numpy.dot', 'np.dot', (['v', 'v'], {}), '(v, v)\n', (99, 105), True, 'import numpy as np\n'), ((127, 144), 'numpy.linalg.norm', 'np.linalg.norm', (['v'], {}), '(v)\n', (141, 144), True, 'import numpy as np\n'), ((50, 67), 'numpy.linalg.norm', 'np.linalg.norm', (['x'], {}), '(x)\n', (64, 67), True, 'import numpy as np\n'), ((329, 366), 'numpy.array', 'np.array', (['[v, v, v]'], {'dtype': 'np.float32'}), '([v, v, v], dtype=np.float32)\n', (337, 366), True, 'import numpy as np\n'), ((426, 472), 'numpy.array', 'np.array', (['[v[0], v[1], v[2]]'], {'dtype': 'np.float32'}), '([v[0], v[1], v[2]], dtype=np.float32)\n', (434, 472), True, 'import numpy as np\n'), ((1741, 1760), 'numpy.count_nonzero', 'np.count_nonzero', (['p'], {}), '(p)\n', (1757, 1760), True, 'import numpy as np\n')]
# -*- coding:utf-8 -*- # ------------------------ # written by <NAME> # 2018-10 # ------------------------ import os import skimage.io from skimage.color import rgb2gray import skimage.transform from scipy.io import loadmat import numpy as np import cv2 import math import warnings import random import torch import matplotlib.pyplot as plt warnings.filterwarnings("ignore") def gaussian_kernel(image, points): image_density = np.zeros(image.shape) h, w = image_density.shape if len(points) == 0: return image_density for j in range(len(points)): f_sz = 15 sigma = 4.0 # convert x, y to int x = min(w, max(0, int(points[j, 0]))) y = min(h, max(0, int(points[j, 1]))) gap = f_sz // 2 x1 = x - gap if x - gap > 0 else 0 x2 = x + gap if x + gap < w else w - 1 y1 = y - gap if y - gap > 0 else 0 y2 = y + gap if y + gap < h else h - 1 # generate 2d gaussian kernel kx = cv2.getGaussianKernel(y2 - y1 + 1, sigma=sigma) ky = cv2.getGaussianKernel(x2 - x1 + 1, sigma=sigma) gaussian = np.multiply(kx, ky.T) image_density[y1:y2 + 1, x1:x2 + 1] += gaussian return image_density def extract_data(mode="train", patch_number=9, part="A"): num_images = 300 if mode=="train" else 182 # original path dataset_path = "../data/original/part_{0}_final/".format(part) mode_data = os.path.join(dataset_path, "{0}_data".format(mode)) mode_images = os.path.join(mode_data, "images") mode_ground_truth = os.path.join(mode_data, "ground_truth") # preprocessed path preprocessed_mode = "../data/preprocessed/{0}/".format(mode) preprocessed_mode_density = "../data/preprocessed/{0}_density/".format(mode) if not os.path.exists("../data/preprocessed/"): os.mkdir("../data/preprocessed/") if not os.path.exists(preprocessed_mode): os.mkdir(preprocessed_mode) if not os.path.exists(preprocessed_mode_density): os.mkdir(preprocessed_mode_density) # convert images to gray-density for each for index in range(1, num_images + 1): if index % 10 == 9: print("{0} images have been processed".format(index + 1)) image_path = os.path.join(mode_images, "IMG_{0}.jpg".format(index)) ground_truth_path = os.path.join(mode_ground_truth, "GT_IMG_{0}.mat".format(index)) image = skimage.io.imread(image_path) # convert to gray map if image.shape[-1] == 3: image = rgb2gray(image) mat = loadmat(ground_truth_path) image_info = mat["image_info"] ann_points = image_info[0][0][0][0][0] # gaussian transfer image_density = gaussian_kernel(image, ann_points) # split image into 9 patches where patch is 1/4 size h, w = image.shape w_block = math.floor(w / 8) h_block = math.floor(h / 8) for j in range(patch_number): x = math.floor((w - 2 * w_block) * random.random() + w_block) y = math.floor((h - 2 * h_block) * random.random() + h_block) image_sample = image[y - h_block:y + h_block, x - w_block:x + w_block] image_density_sample = image_density[y - h_block:y + h_block, x - w_block:x + w_block] img_idx = "{0}_{1}".format(index, j) np.save(os.path.join(preprocessed_mode_density, "{0}.npy".format(img_idx)), image_density_sample) skimage.io.imsave(os.path.join(preprocessed_mode, "{0}.jpg".format(img_idx)), image_sample) def extract_test_data(part="A"): num_images = 183 if part == "A" else 317 test_data_path = "../data/original/part_{part}_final/test_data/images".format(part=part) test_ground_path = "../data/original/part_{part}_final/test_data/ground_truth".format(part=part) test_density_path = "../data/preprocessed/test_density" print("create directory........") if not os.path.exists(test_density_path): os.mkdir(test_density_path) print("begin to preprocess test data........") for index in range(1, num_images): if index % 10 == 0: print("{num} images are done".format(num=index)) image_path = os.path.join(test_data_path, "IMG_{0}.jpg".format(index)) ground_truth_path = os.path.join(test_ground_path, "GT_IMG_{0}.mat".format(index)) # load mat and image image = skimage.io.imread(image_path) if image.shape[-1] == 3: image = rgb2gray(image) mat = loadmat(ground_truth_path) image_info = mat["image_info"] # ann_points: points pixels mean people # number: number of people in the image ann_points = image_info[0][0][0][0][0] number = image_info[0][0][0][0][1] h = float(image.shape[0]) w = float(image.shape[1]) # convert images to density image_density = gaussian_kernel(image, ann_points) np.save(os.path.join(test_density_path, "IMG_{0}.npy".format(index)), image_density) extract_test_data()
[ "os.path.exists", "numpy.multiply", "skimage.color.rgb2gray", "math.floor", "scipy.io.loadmat", "os.path.join", "cv2.getGaussianKernel", "numpy.zeros", "os.mkdir", "random.random", "warnings.filterwarnings" ]
[((342, 375), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (365, 375), False, 'import warnings\n'), ((434, 455), 'numpy.zeros', 'np.zeros', (['image.shape'], {}), '(image.shape)\n', (442, 455), True, 'import numpy as np\n'), ((1505, 1538), 'os.path.join', 'os.path.join', (['mode_data', '"""images"""'], {}), "(mode_data, 'images')\n", (1517, 1538), False, 'import os\n'), ((1563, 1602), 'os.path.join', 'os.path.join', (['mode_data', '"""ground_truth"""'], {}), "(mode_data, 'ground_truth')\n", (1575, 1602), False, 'import os\n'), ((992, 1039), 'cv2.getGaussianKernel', 'cv2.getGaussianKernel', (['(y2 - y1 + 1)'], {'sigma': 'sigma'}), '(y2 - y1 + 1, sigma=sigma)\n', (1013, 1039), False, 'import cv2\n'), ((1053, 1100), 'cv2.getGaussianKernel', 'cv2.getGaussianKernel', (['(x2 - x1 + 1)'], {'sigma': 'sigma'}), '(x2 - x1 + 1, sigma=sigma)\n', (1074, 1100), False, 'import cv2\n'), ((1120, 1141), 'numpy.multiply', 'np.multiply', (['kx', 'ky.T'], {}), '(kx, ky.T)\n', (1131, 1141), True, 'import numpy as np\n'), ((1784, 1823), 'os.path.exists', 'os.path.exists', (['"""../data/preprocessed/"""'], {}), "('../data/preprocessed/')\n", (1798, 1823), False, 'import os\n'), ((1833, 1866), 'os.mkdir', 'os.mkdir', (['"""../data/preprocessed/"""'], {}), "('../data/preprocessed/')\n", (1841, 1866), False, 'import os\n'), ((1878, 1911), 'os.path.exists', 'os.path.exists', (['preprocessed_mode'], {}), '(preprocessed_mode)\n', (1892, 1911), False, 'import os\n'), ((1921, 1948), 'os.mkdir', 'os.mkdir', (['preprocessed_mode'], {}), '(preprocessed_mode)\n', (1929, 1948), False, 'import os\n'), ((1960, 2001), 'os.path.exists', 'os.path.exists', (['preprocessed_mode_density'], {}), '(preprocessed_mode_density)\n', (1974, 2001), False, 'import os\n'), ((2011, 2046), 'os.mkdir', 'os.mkdir', (['preprocessed_mode_density'], {}), '(preprocessed_mode_density)\n', (2019, 2046), False, 'import os\n'), ((2562, 2588), 'scipy.io.loadmat', 'loadmat', (['ground_truth_path'], {}), '(ground_truth_path)\n', (2569, 2588), False, 'from scipy.io import loadmat\n'), ((2868, 2885), 'math.floor', 'math.floor', (['(w / 8)'], {}), '(w / 8)\n', (2878, 2885), False, 'import math\n'), ((2904, 2921), 'math.floor', 'math.floor', (['(h / 8)'], {}), '(h / 8)\n', (2914, 2921), False, 'import math\n'), ((3937, 3970), 'os.path.exists', 'os.path.exists', (['test_density_path'], {}), '(test_density_path)\n', (3951, 3970), False, 'import os\n'), ((3980, 4007), 'os.mkdir', 'os.mkdir', (['test_density_path'], {}), '(test_density_path)\n', (3988, 4007), False, 'import os\n'), ((4517, 4543), 'scipy.io.loadmat', 'loadmat', (['ground_truth_path'], {}), '(ground_truth_path)\n', (4524, 4543), False, 'from scipy.io import loadmat\n'), ((2532, 2547), 'skimage.color.rgb2gray', 'rgb2gray', (['image'], {}), '(image)\n', (2540, 2547), False, 'from skimage.color import rgb2gray\n'), ((4487, 4502), 'skimage.color.rgb2gray', 'rgb2gray', (['image'], {}), '(image)\n', (4495, 4502), False, 'from skimage.color import rgb2gray\n'), ((3007, 3022), 'random.random', 'random.random', ([], {}), '()\n', (3020, 3022), False, 'import random\n'), ((3081, 3096), 'random.random', 'random.random', ([], {}), '()\n', (3094, 3096), False, 'import random\n')]
#! /usr/bin/env python import copy from copy import deepcopy import rospy import threading import quaternion import numpy as np from geometry_msgs.msg import Point from visualization_msgs.msg import * from franka_interface import ArmInterface from panda_robot import PandaArm import matplotlib.pyplot as plt from scipy.spatial.transform import Rotation np.set_printoptions(precision=2) """ This is a FORCE-BASED VARIABLE IMPEDANCE CONTROLLER based on [Huang1992: Compliant Motion Control of Robots by Using Variable Impedance] To achieve force tracking, the apparent stiffness (K) and damping (B) is dynamically adjusted through functions dependent on the error in position, velocity and force About the code/controller: 1] Only stiffness and damping in the 'z'-direction is adaptive, the rest are static 2] Due to the faulted joint velocities (read from rostopics), the more noisy, numerically derived derivatives of the joint position are prefered to be used in the controller { get_x_dot(..., numerically = True) } 3] You can now choose between perform_torque_Huang1992() and perform_torque_DeSchutter() - DeSchutter's control-law offers geometrically consitent stiffness and is more computationally expensive 4] The default desired motion- and force-trajectories are now made in a time-consistent matter, so that the PUBLISH RATE can be altered without messing up the desired behaviour. The number of iterations is calculated as a function of the controller's control-cycle, T: (max_num_it = duration(=15 s) / T) """ # --------- Constants ----------------------------- #print(robot.joint_ordered_angles()) #Read the robot's joint-angles #new_start = {'panda_joint1': 1.938963389436404, 'panda_joint2': 0.6757504724282993, 'panda_joint3': -0.43399745125475564, 'panda_joint4': -2.0375275954865573, 'panda_joint5': -0.05233040021194351, 'panda_joint6': 3.133254153457202, 'panda_joint7': 1.283328743909796} # Stiffness Kp = 30 Kpz = 30 #initial value (adaptive) Ko = 900 K = np.array([[Kp, 0, 0, 0, 0, 0], [0, Kp, 0, 0, 0, 0], [0, 0, Kpz, 0, 0, 0], [0, 0, 0, Ko, 0, 0], [0, 0, 0, 0, Ko, 0], [0, 0, 0, 0, 0, Ko]]) # Damping Bp = Kp/7 Bpz = Bp # #initial value (adaptive) Bo = 50 B = np.array([[Bp, 0, 0, 0, 0, 0], [0, Bp, 0, 0, 0, 0], [0, 0, Bpz, 0, 0, 0], [0, 0, 0, Bo, 0, 0], [0, 0, 0, 0, Bo, 0], [0, 0, 0, 0, 0, Bo]]) # Apparent inertia Mp = 10 Mo = 10 M_diag = np.array([Mp,Mp,Mp,Mo,Mo,Mo]) M = np.diagflat(M_diag) # Constant matrices appearing in equation (50) of [Huang1992] K_v = np.identity(6) P = np.identity(6) gamma = np.identity(18) #gamma_M = 12 gamma_B = 0.001 #2 # The damping's rate of adaptivity (high value = slow changes) gamma_K = 0.0005 #1 # The stiffness' rate of adaptivity (high value = slow changes) #gamma[2,2] = gamma_M gamma[8,8] = gamma_B gamma[14,14] = gamma_K duration = 15 #seconds SHOULD NOT BE ALTERED """Functions for generating desired MOTION trajectories""" #1 Generate a desired trajectory for the manipulator to follow def generate_desired_trajectory(iterations,T): a = np.zeros((6,iterations)) v = np.zeros((6,iterations)) p = np.zeros((3,iterations)) p[:,0] = get_p() if iterations > 300: a[2,0:100]=-0.00001/T**2 a[2,250:350]=0.00001/T**2 if iterations > 6500: a[0,4500:4510]=0.00001/T**2 a[0,6490:6500]=-0.00001/T**2 for i in range(max_num_it): if i>0: v[:,i]=v[:,i-1]+a[:,i-1]*T p[:,i]=p[:,i-1]+v[:3,i-1]*T return a,v,p #2 Generate a desired trajectory for the manipulator to follow def generate_desired_trajectory_express(iterations,T): a = np.zeros((6,iterations)) v = np.zeros((6,iterations)) p = np.zeros((3,iterations)) p[:,0] = get_p() if iterations > 175: a[2,0:50]=-0.00002/T**2 a[2,125:175]=0.00002/T**2 if iterations > 3250: a[0,2250:2255]=0.00002/T**2 a[0,3245:3250]=-0.00002/T**2 for i in range(max_num_it): if i>0: v[:,i]=v[:,i-1]+a[:,i-1]*T p[:,i]=p[:,i-1]+v[:3,i-1]*T return a,v,p #3 Generate a (time-consistent) desired motion trajectory def generate_desired_trajectory_tc(iterations,T,move_in_x=False): a = np.zeros((6,iterations)) v = np.zeros((6,iterations)) p = np.zeros((3,iterations)) p[:,0] = get_p() a[2,0:int(iterations/75)]=-1.25 a[2,int(iterations*2/75):int(iterations/25)]= 1.25 if move_in_x: a[0,int(iterations*3/5):int(iterations*451/750)]=1.25 a[0,int(iterations*649/750):int(iterations*13/15)]=-1.25 for i in range(max_num_it): if i>0: v[:,i]=v[:,i-1]+a[:,i-1]*T p[:,i]=p[:,i-1]+v[:3,i-1]*T return a,v,p """Functions for generating desired FORCE trajectories""" #1 Generate a desired force trajectory def generate_F_d(max_num_it,T): a = np.zeros((6,max_num_it)) v = np.zeros((6,max_num_it)) s = np.zeros((6,max_num_it)) a[2,0:100] = 0.0005/T**2 a[2,100:200] = - 0.0005/T**2 if max_num_it > 1100: a[2,500:550] = 0.0002/T**2 if max_num_it >4001: a[2,1500:1550]=-0.0002/T**2 it = 2000 while it <= 4000: a[2,it]= (-9*(np.pi**2)*(T/4)**2*np.sin(it*T/4*2*np.pi+np.pi/2))/T**2 it+=1 a[2,4001]=0.0001/T**2 for i in range(max_num_it): if i>0: v[2,i]=v[2,i-1]+a[2,i-1]*T s[2,i]=s[2,i-1]+v[2,i-1]*T return s #2 Generate an efficient desired force trajectory def generate_F_d_express(max_num_it,T): a = np.zeros((6,max_num_it)) v = np.zeros((6,max_num_it)) s = np.zeros((6,max_num_it)) a[2,0:50] = 0.0010/T**2 a[2,100:150] = - 0.0010/T**2 if max_num_it > 275: a[2,250:275] = 0.0008/T**2 if max_num_it >2001: a[2,750:775]=-0.0008/T**2 it = 1000 while it <= 2000: a[2,it]= (-9*(np.pi**2)*(T/4)**2*np.sin(2*it*T/4*2*np.pi+np.pi/2))/T**2 it+=1 a[2,2001]=0.0001/T**2 for i in range(max_num_it): if i>0: v[2,i]=v[2,i-1]+a[2,i-1]*T s[2,i]=s[2,i-1]+v[2,i-1]*T return s #3 Generate a (time-consistent) desired force trajectory def generate_F_d_tc(max_num_it,T): a = np.zeros((6,max_num_it)) v = np.zeros((6,max_num_it)) s = np.zeros((6,max_num_it)) a[2,0:int(max_num_it/75)] = 62.5 a[2,int(max_num_it/37.5):int(max_num_it/25)] = - 62.5 if max_num_it > 275: a[2,int(max_num_it/15):int(max_num_it*11/150)] = 50 if max_num_it >2001: a[2,int(max_num_it/5):int(max_num_it*31/150)]=-50 it = int(max_num_it*4/15) while it <= int(max_num_it*8/15): a[2,it]= (-9*(np.pi**2)*(T/4)**2*np.sin(2*it*T/4*2*np.pi+np.pi/2))/T**2 it+=1 a[2,int(max_num_it*8/15+1)]=6.25 for i in range(max_num_it): if i>0: v[2,i]=v[2,i-1]+a[2,i-1]*T s[2,i]=s[2,i-1]+v[2,i-1]*T return s # ------------ Helper functions -------------------------------- # Calculate the numerical derivative of a each row in a vector def get_derivative_of_vector(history,iteration,T): size = history.shape[0] if iteration > 0: return np.subtract(history[:,iteration],history[:,iteration-1])/T else: return np.zeros(size) # Saturation-function def ensure_limits(lower,upper,matrix): for i in range(6): if matrix[i,i] > upper: matrix[i,i] = upper elif matrix[i,i] < lower: matrix[i,i] = lower # Return the cartesian (task-space) inertia of the manipulator [alternatively the inverse of it] def get_W(inv = False): W = np.linalg.multi_dot([robot.jacobian(),np.linalg.inv(robot.joint_inertia_matrix()),robot.jacobian().T]) if inv == True: return np.linalg.inv(W) else: return W # Return the external forces (everything except for z-force is set to 0 due to offsets) def get_F_ext(two_dim = False): if two_dim == True: return np.array([0,0,robot.endpoint_effort()['force'][2],0,0,0]).reshape([6,1]) else: return np.array([0,0,robot.endpoint_effort()['force'][2],0,0,0]) # Return the position and (relative) orientation def get_x(goal_ori): pos_x = robot.endpoint_pose()['position'] rel_ori = quatdiff_in_euler_radians(goal_ori, np.asarray(robot.endpoint_pose()['orientation'])) return np.append(pos_x,rel_ori) # Return the linear and angular velocities # Numerically = True -> return the derivarive of the state-vector # Numerically = False -> read values from rostopic (faulty in sim when interacting with the environment) def get_x_dot(x_hist,i,T, numerically=False): if numerically == True: return get_derivative_of_vector(x_hist,i,T) else: return np.append(robot.endpoint_velocity()['linear'],robot.endpoint_velocity()['angular']) # Return the error in position and orientation def get_delta_x(goal_ori, p_d, two_dim = False): delta_pos = p_d - robot.endpoint_pose()['position'] delta_ori = quatdiff_in_euler_radians(np.asarray(robot.endpoint_pose()['orientation']), goal_ori) if two_dim == True: return np.array([np.append(delta_pos,delta_ori)]).reshape([6,1]) else: return np.append(delta_pos,delta_ori) # Return the error in linear and angular velocities def get_x_dot_delta(x_d_dot,x_dot, two_dim = True): if two_dim == True: return (x_d_dot - x_dot).reshape([6,1]) else: return x_d_dot - x_dot # Return the error in linear and angular acceleration def get_x_ddot_delta(x_d_ddot,v_history,i,T): a = get_derivative_of_vector(v_history,i,T) return x_d_ddot-a # Return the cartesian (task-space) position def get_p(two_dim=False): if two_dim == True: return robot.endpoint_pose()['position'].reshape([3,1]) else: return robot.endpoint_pose()['position'] # Compute difference between quaternions and return Euler angle in radians as difference def quatdiff_in_euler_radians(quat_curr, quat_des): curr_mat = quaternion.as_rotation_matrix(quat_curr) des_mat = quaternion.as_rotation_matrix(quat_des) rel_mat = des_mat.T.dot(curr_mat) rel_quat = quaternion.from_rotation_matrix(rel_mat) vec = quaternion.as_float_array(rel_quat)[1:] if rel_quat.w < 0.0: vec = -vec return -des_mat.dot(vec) # -------------- Main functions -------------------- # Get xi as it is described in equation (44) in [Huang1992] def get_xi(goal_ori, p_d, x_dot, x_d_dot, x_d_ddot, v_history, i, T): E = -get_delta_x(goal_ori, p_d) E_dot = -get_x_dot_delta(x_d_dot,x_dot, two_dim = False) E_ddot = -get_x_ddot_delta(x_d_ddot,v_history,i,T) E_diag = np.diagflat(E) E_dot_diag = np.diagflat(E_dot) E_ddot_diag = np.diagflat(E_ddot) return np.block([E_ddot_diag,E_dot_diag,E_diag]) # Calculate lambda_dot as in equation (50) in [Huang1992] def get_lambda_dot(gamma,xi,K_v,P,F_d): return np.linalg.multi_dot([-np.linalg.inv(gamma),xi.T,np.linalg.inv(K_v),P,get_F_ext(two_dim=True)-F_d.reshape([6,1])]) # Return the updated (adapted) Inertia, Damping and Stiffness matrices. def update_MBK_hat(lam,M,B,K): M_hat = M # + np.diagflat(lam[0:6]) M is chosen to be constant B_hat = B + np.diagflat(lam[6:12]) K_hat = K + np.diagflat(lam[12:18]) #ensure_limits(1,5000,M_hat) ensure_limits(1,5000,B_hat) ensure_limits(1,5000,K_hat) return M_hat, B_hat, K_hat # Calculate and perform the torque as in equation (10) in [Huang1992] def perform_torque_Huang1992(M, B, K, x_d_ddot, x_d_dot,x_dot, p_d, goal_ori): a = np.linalg.multi_dot([robot.jacobian().T,get_W(inv=True),np.linalg.inv(M)]) b = np.array([np.dot(M,x_d_ddot)]).reshape([6,1]) + np.array([np.dot(B,get_x_dot_delta(x_d_dot,x_dot))]).reshape([6,1]) + np.array([np.dot(K,get_delta_x(goal_ori,p_d,two_dim = True))]).reshape([6,1]) c = robot.coriolis_comp().reshape([7,1]) d = (np.identity(6)-np.dot(get_W(inv=True),np.linalg.inv(M))).reshape([6,6]) total_torque = np.array([np.dot(a,b)]).reshape([7,1]) + c + np.array([np.linalg.multi_dot([robot.jacobian().T,d,get_F_ext()])]).reshape([7,1]) robot.set_joint_torques(dict(list(zip(robot.joint_names(),total_torque)))) """ TESTING AREA (Functions needed to run an adaptive version of DeSchutter's impedance controller) [with geometrically consistent stiffness] """ def skew(vector): return np.array([[0, -vector[2], vector[1]], [vector[2], 0, -vector[0]], [-vector[1], vector[0], 0]]) def from_three_to_six_dim(matrix): return np.block([[matrix,np.zeros((3,3))],[np.zeros((3,3)),matrix]]) def get_K_Pt_dot(R_d,K_pt,R_e): return np.array([0.5*np.linalg.multi_dot([R_d,K_pt,R_d.T])+0.5*np.linalg.multi_dot([R_e,K_pt,R_e.T])]) def get_K_Pt_ddot(p_d,R_d,K_pt): return np.array([0.5*np.linalg.multi_dot([skew(p_d-robot.endpoint_pose()['position']),R_d,K_pt,R_d.T])]) def E_quat(quat_n,quat_e): return np.dot(quat_n,np.identity(3))-skew(quat_e) def get_K_Po_dot(quat_n,quat_e,R_e,K_po): return np.array([2*np.linalg.multi_dot([E_quat(quat_n,quat_e).T,R_e,K_po,R_e.T])]) def get_h_delta(K_pt_dot,K_pt_ddot,p_delta,K_po_dot,quat_e): f_delta_t = np.array([np.dot(K_pt_dot,p_delta)]) m_delta_t = np.array([np.dot(K_pt_ddot,p_delta)]) null = np.zeros((3,1)) m_delta_o = np.array([np.dot(K_po_dot,quat_e)]) return np.array([np.append(f_delta_t.T,m_delta_t.T)]).T + np.array([np.append(null.T,m_delta_o.T)]).T def perform_torque_DeSchutter(M, B, K, x_d_ddot, x_d_dot,x_dot, p_d, Rot_d): # must include Rot_d J = robot.jacobian() Rot_e = robot.endpoint_pose()['orientation_R'] Rot_e_bigdim = from_three_to_six_dim(Rot_e) Rot_e_dot = np.dot(skew(robot.endpoint_velocity()['angular']),Rot_e) #not a 100 % sure about this one Rot_e_dot_bigdim = from_three_to_six_dim(Rot_e_dot) quat = quaternion.from_rotation_matrix(np.dot(Rot_e.T,Rot_d)) #orientational displacement represented as a unit quaternion #quat = robot.endpoint_pose()['orientation'] quat_e_e = np.array([quat.x,quat.y,quat.z]) # vector part of the unit quaternion in the frame of the end effector quat_e = np.dot(Rot_e.T,quat_e_e) # ... in the base frame quat_n = quat.w p_delta = p_d-robot.endpoint_pose()['position'] K_Pt_dot = get_K_Pt_dot(Rot_d,K[:3,:3],Rot_e) K_Pt_ddot = get_K_Pt_ddot(p_d,Rot_d,K[:3,:3]) K_Po_dot = get_K_Po_dot(quat_n,quat_e,Rot_e,K[3:,3:]) h_delta_e = np.array(np.dot(Rot_e_bigdim,get_h_delta(K_Pt_dot,K_Pt_ddot,p_delta,K_Po_dot,quat_e))).reshape([6,1]) h_e = get_F_ext(two_dim=True) h_e_e = np.array(np.dot(Rot_e_bigdim,h_e)) a_d_e = np.dot(Rot_e_bigdim,x_d_ddot).reshape([6,1]) v_d_e = np.dot(Rot_e_bigdim,x_d_dot).reshape([6,1]) alpha_e = a_d_e + np.dot(np.linalg.inv(M),(np.dot(B,v_d_e.reshape([6,1])-np.dot(Rot_e_bigdim,x_dot).reshape([6,1]))+h_delta_e-h_e_e)).reshape([6,1]) alpha = np.dot(Rot_e_bigdim.T,alpha_e).reshape([6,1])+np.dot(Rot_e_dot_bigdim.T,np.dot(Rot_e_bigdim,x_dot)).reshape([6,1]) torque = np.linalg.multi_dot([J.T,get_W(inv=True),alpha]).reshape((7,1)) + np.array(robot.coriolis_comp().reshape((7,1))) + np.dot(J.T,h_e).reshape((7,1)) robot.set_joint_torques(dict(list(zip(robot.joint_names(),torque)))) """ TESTING AREA """ # -------------- Plotting ------------------------ def plot_result(v_num, v,p,p_d, delta_x, F_ext,F_d, z_dynamics,M,B,K, T): time_array = np.arange(len(p[0]))*T plt.subplot(211) plt.title("External force") plt.plot(time_array, F_ext[2], label="force z [N]") plt.plot(time_array, F_d[2], label="desired force z [N]", color='b',linestyle='dashed') plt.xlabel("Real time [s]") plt.legend() plt.subplot(212) plt.title("Position") plt.plot(time_array, p[0,:], label = "true x [m]") plt.plot(time_array, p[1,:], label = "true y [m]") plt.plot(time_array, p[2,:], label = "true z [m]") plt.plot(time_array, p_d[0,:], label = "desired x [m]", color='b',linestyle='dashed') plt.plot(time_array, p_d[1,:], label = "desired y [m]", color='C1',linestyle='dashed') plt.plot(time_array, p_d[2,:], label = "desired z [m]", color='g',linestyle='dashed') plt.xlabel("Real time [s]") plt.legend() """ plt.subplot(233) plt.title("Orientation error in Euler") plt.plot(time_array, delta_x[3]*(180/np.pi), label = "error Ori_x [degrees]") plt.plot(time_array, delta_x[4]*(180/np.pi), label = "error Ori_y [degrees]") plt.plot(time_array, delta_x[5]*(180/np.pi), label = "error Ori_z [degrees]") plt.xlabel("Real time [s]") plt.legend() plt.subplot(234) plt.title("Adaptive dynamics along the z-axis") plt.plot(time_array, z_dynamics[0], label = "inertia (M_z)") plt.plot(time_array, z_dynamics[1], label = "damping (B_z)") plt.plot(time_array, z_dynamics[2], label = "stiffness (K_z)") plt.axhline(y=M[2][2], label = "initial inertia (M_z)", color='b',linestyle='dashed') plt.axhline(y=B[2][2], label = "initial damping (B_z)", color='C1',linestyle='dashed') plt.axhline(y=K[2][2], label = "initial stiffness (K_z)", color='g',linestyle='dashed') plt.xlabel("Real time [s]") plt.legend() plt.subplot(235) plt.title("velocity read from rostopic") plt.plot(time_array, v[0], label = "vel x") plt.plot(time_array, v[1], label = "vel y") plt.plot(time_array, v[2], label = "vel z") plt.plot(time_array, v[3], label = "ang x") plt.plot(time_array, v[4], label = "ang y") plt.plot(time_array, v[5], label = "ang z") plt.xlabel("Real time [s]") plt.legend() plt.subplot(236) plt.title("numerically calculated velocity") plt.plot(time_array, v_num[0], label = "vel x") plt.plot(time_array, v_num[1], label = "vel y") plt.plot(time_array, v_num[2], label = "vel z") plt.plot(time_array, v_num[3], label = "ang x") plt.plot(time_array, v_num[4], label = "ang y") plt.plot(time_array, v_num[5], label = "ang z") plt.xlabel("Real time [s]") plt.legend() """ plt.show() if __name__ == "__main__": # ---------- Initialization ------------------- rospy.init_node("impedance_control") robot = PandaArm() publish_rate = 250 rate = rospy.Rate(publish_rate) T = 0.001*(1000/publish_rate) max_num_it = int(duration /T) #robot.move_to_joint_positions(new_start) robot.move_to_neutral() # List used to contain data needed for calculation of the torque output lam = np.zeros(18) v_history = np.zeros((6,max_num_it)) # Lists providing data for plotting p_history = np.zeros((3,max_num_it)) v_history_num = np.zeros((6,max_num_it)) x_history = np.zeros((6,max_num_it)) delta_x_history = np.zeros((6,max_num_it)) F_ext_history = np.zeros((6,max_num_it)) z_dynamics_history = np.zeros((3,max_num_it)) # Specify the desired behaviour of the robot x_d_ddot, x_d_dot, p_d = generate_desired_trajectory_tc(max_num_it,T,move_in_x = True) goal_ori = np.asarray(robot.endpoint_pose()['orientation']) # goal orientation = current (initial) orientation [remains the same the entire duration of the run] Rot_d = robot.endpoint_pose()['orientation_R'] # used by the DeSchutter implementation F_d = generate_F_d_tc(max_num_it,T) # ----------- The control loop ----------- for i in range(max_num_it): # update state-lists p_history[:,i] = get_p() x_history[:,i] = get_x(goal_ori) delta_x_history[:,i] = get_delta_x(goal_ori,p_d[:,i]) F_ext_history[:,i] = get_F_ext() x_dot = get_x_dot(x_history,i,T, numerically=False) #chose 'numerically' either 'True' or 'False' v_history_num[:,i] = get_x_dot(x_history,i,T, numerically=True) # only for plotting v_history[:,i] = get_x_dot(x_history,i,T) # for calculating error in acceleration # adapt M,B and K xi = get_xi(goal_ori, p_d[:,i],x_dot, x_d_dot[:,i], x_d_ddot[:,i], v_history, i, T) lam = lam.reshape([18,1]) + get_lambda_dot(gamma,xi,K_v,P,F_d[:,i]).reshape([18,1])*T M_hat,B_hat,K_hat = update_MBK_hat(lam,M,B,K) # Apply the resulting torque to the robot """CHOOSE ONE OF THE TWO CONTROLLERS BELOW""" perform_torque_Huang1992(M_hat, B_hat, K_hat, x_d_ddot[:,i], x_d_dot[:,i],x_dot, p_d[:,i], goal_ori) #perform_torque_DeSchutter(M_hat, B_hat, K_hat, x_d_ddot[:,i], x_d_dot[:,i],x_dot, p_d[:,i], Rot_d) rate.sleep() # plotting and printing z_dynamics_history[0][i]=M_hat[2][2] z_dynamics_history[1][i]=B_hat[2][2] z_dynamics_history[2][i]=K_hat[2][2] # Live printing to screen when the controller is running if i%100 == 0: print(i,'/',max_num_it,' = ',T*i,' [s] ) Force in z: ',F_ext_history[2,i]) print(K_hat[2][2]) print('') #Uncomment the block below to save plotting-data """ np.save('VIC_p_d.npy',p_d) np.save('VIC_p.npy',p_history) np.save('VIC_Fz_d.npy',F_d) np.save('VIC_Fz.npy',F_ext_history[2]) np.save('VIC_delta_x.npy',delta_x_history) #orientation error in radians np.save('VIC_adaptive_gains.npy',z_dynamics_history) """ plot_result(v_history_num,v_history, p_history, p_d, delta_x_history, F_ext_history, F_d, z_dynamics_history,M,B,K, T)
[ "numpy.block", "quaternion.as_float_array", "numpy.linalg.multi_dot", "rospy.init_node", "numpy.array", "rospy.Rate", "numpy.sin", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.plot", "numpy.subtract", "numpy.dot", "numpy.diagflat", "panda_robot.PandaArm", "numpy.identity", "quaternion.from_rotation_matrix", "matplotlib.pyplot.title", "matplotlib.pyplot.legend", "matplotlib.pyplot.show", "numpy.set_printoptions", "quaternion.as_rotation_matrix", "numpy.append", "numpy.zeros", "numpy.linalg.inv", "matplotlib.pyplot.subplot" ]
[((353, 385), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'precision': '(2)'}), '(precision=2)\n', (372, 385), True, 'import numpy as np\n'), ((2012, 2154), 'numpy.array', 'np.array', (['[[Kp, 0, 0, 0, 0, 0], [0, Kp, 0, 0, 0, 0], [0, 0, Kpz, 0, 0, 0], [0, 0, 0,\n Ko, 0, 0], [0, 0, 0, 0, Ko, 0], [0, 0, 0, 0, 0, Ko]]'], {}), '([[Kp, 0, 0, 0, 0, 0], [0, Kp, 0, 0, 0, 0], [0, 0, Kpz, 0, 0, 0], [\n 0, 0, 0, Ko, 0, 0], [0, 0, 0, 0, Ko, 0], [0, 0, 0, 0, 0, Ko]])\n', (2020, 2154), True, 'import numpy as np\n'), ((2301, 2443), 'numpy.array', 'np.array', (['[[Bp, 0, 0, 0, 0, 0], [0, Bp, 0, 0, 0, 0], [0, 0, Bpz, 0, 0, 0], [0, 0, 0,\n Bo, 0, 0], [0, 0, 0, 0, Bo, 0], [0, 0, 0, 0, 0, Bo]]'], {}), '([[Bp, 0, 0, 0, 0, 0], [0, Bp, 0, 0, 0, 0], [0, 0, Bpz, 0, 0, 0], [\n 0, 0, 0, Bo, 0, 0], [0, 0, 0, 0, Bo, 0], [0, 0, 0, 0, 0, Bo]])\n', (2309, 2443), True, 'import numpy as np\n'), ((2564, 2598), 'numpy.array', 'np.array', (['[Mp, Mp, Mp, Mo, Mo, Mo]'], {}), '([Mp, Mp, Mp, Mo, Mo, Mo])\n', (2572, 2598), True, 'import numpy as np\n'), ((2598, 2617), 'numpy.diagflat', 'np.diagflat', (['M_diag'], {}), '(M_diag)\n', (2609, 2617), True, 'import numpy as np\n'), ((2687, 2701), 'numpy.identity', 'np.identity', (['(6)'], {}), '(6)\n', (2698, 2701), True, 'import numpy as np\n'), ((2706, 2720), 'numpy.identity', 'np.identity', (['(6)'], {}), '(6)\n', (2717, 2720), True, 'import numpy as np\n'), ((2729, 2744), 'numpy.identity', 'np.identity', (['(18)'], {}), '(18)\n', (2740, 2744), True, 'import numpy as np\n'), ((3226, 3251), 'numpy.zeros', 'np.zeros', (['(6, iterations)'], {}), '((6, iterations))\n', (3234, 3251), True, 'import numpy as np\n'), ((3259, 3284), 'numpy.zeros', 'np.zeros', (['(6, iterations)'], {}), '((6, iterations))\n', (3267, 3284), True, 'import numpy as np\n'), ((3292, 3317), 'numpy.zeros', 'np.zeros', (['(3, iterations)'], {}), '((3, iterations))\n', (3300, 3317), True, 'import numpy as np\n'), ((3815, 3840), 'numpy.zeros', 'np.zeros', (['(6, iterations)'], {}), '((6, iterations))\n', (3823, 3840), True, 'import numpy as np\n'), ((3848, 3873), 'numpy.zeros', 'np.zeros', (['(6, iterations)'], {}), '((6, iterations))\n', (3856, 3873), True, 'import numpy as np\n'), ((3881, 3906), 'numpy.zeros', 'np.zeros', (['(3, iterations)'], {}), '((3, iterations))\n', (3889, 3906), True, 'import numpy as np\n'), ((4409, 4434), 'numpy.zeros', 'np.zeros', (['(6, iterations)'], {}), '((6, iterations))\n', (4417, 4434), True, 'import numpy as np\n'), ((4442, 4467), 'numpy.zeros', 'np.zeros', (['(6, iterations)'], {}), '((6, iterations))\n', (4450, 4467), True, 'import numpy as np\n'), ((4475, 4500), 'numpy.zeros', 'np.zeros', (['(3, iterations)'], {}), '((3, iterations))\n', (4483, 4500), True, 'import numpy as np\n'), ((5055, 5080), 'numpy.zeros', 'np.zeros', (['(6, max_num_it)'], {}), '((6, max_num_it))\n', (5063, 5080), True, 'import numpy as np\n'), ((5088, 5113), 'numpy.zeros', 'np.zeros', (['(6, max_num_it)'], {}), '((6, max_num_it))\n', (5096, 5113), True, 'import numpy as np\n'), ((5121, 5146), 'numpy.zeros', 'np.zeros', (['(6, max_num_it)'], {}), '((6, max_num_it))\n', (5129, 5146), True, 'import numpy as np\n'), ((5755, 5780), 'numpy.zeros', 'np.zeros', (['(6, max_num_it)'], {}), '((6, max_num_it))\n', (5763, 5780), True, 'import numpy as np\n'), ((5788, 5813), 'numpy.zeros', 'np.zeros', (['(6, max_num_it)'], {}), '((6, max_num_it))\n', (5796, 5813), True, 'import numpy as np\n'), ((5821, 5846), 'numpy.zeros', 'np.zeros', (['(6, max_num_it)'], {}), '((6, max_num_it))\n', (5829, 5846), True, 'import numpy as np\n'), ((6455, 6480), 'numpy.zeros', 'np.zeros', (['(6, max_num_it)'], {}), '((6, max_num_it))\n', (6463, 6480), True, 'import numpy as np\n'), ((6488, 6513), 'numpy.zeros', 'np.zeros', (['(6, max_num_it)'], {}), '((6, max_num_it))\n', (6496, 6513), True, 'import numpy as np\n'), ((6521, 6546), 'numpy.zeros', 'np.zeros', (['(6, max_num_it)'], {}), '((6, max_num_it))\n', (6529, 6546), True, 'import numpy as np\n'), ((8604, 8629), 'numpy.append', 'np.append', (['pos_x', 'rel_ori'], {}), '(pos_x, rel_ori)\n', (8613, 8629), True, 'import numpy as np\n'), ((10262, 10302), 'quaternion.as_rotation_matrix', 'quaternion.as_rotation_matrix', (['quat_curr'], {}), '(quat_curr)\n', (10291, 10302), False, 'import quaternion\n'), ((10317, 10356), 'quaternion.as_rotation_matrix', 'quaternion.as_rotation_matrix', (['quat_des'], {}), '(quat_des)\n', (10346, 10356), False, 'import quaternion\n'), ((10410, 10450), 'quaternion.from_rotation_matrix', 'quaternion.from_rotation_matrix', (['rel_mat'], {}), '(rel_mat)\n', (10441, 10450), False, 'import quaternion\n'), ((10924, 10938), 'numpy.diagflat', 'np.diagflat', (['E'], {}), '(E)\n', (10935, 10938), True, 'import numpy as np\n'), ((10956, 10974), 'numpy.diagflat', 'np.diagflat', (['E_dot'], {}), '(E_dot)\n', (10967, 10974), True, 'import numpy as np\n'), ((10993, 11012), 'numpy.diagflat', 'np.diagflat', (['E_ddot'], {}), '(E_ddot)\n', (11004, 11012), True, 'import numpy as np\n'), ((11024, 11067), 'numpy.block', 'np.block', (['[E_ddot_diag, E_dot_diag, E_diag]'], {}), '([E_ddot_diag, E_dot_diag, E_diag])\n', (11032, 11067), True, 'import numpy as np\n'), ((12647, 12746), 'numpy.array', 'np.array', (['[[0, -vector[2], vector[1]], [vector[2], 0, -vector[0]], [-vector[1],\n vector[0], 0]]'], {}), '([[0, -vector[2], vector[1]], [vector[2], 0, -vector[0]], [-vector[\n 1], vector[0], 0]])\n', (12655, 12746), True, 'import numpy as np\n'), ((13572, 13588), 'numpy.zeros', 'np.zeros', (['(3, 1)'], {}), '((3, 1))\n', (13580, 13588), True, 'import numpy as np\n'), ((14337, 14371), 'numpy.array', 'np.array', (['[quat.x, quat.y, quat.z]'], {}), '([quat.x, quat.y, quat.z])\n', (14345, 14371), True, 'import numpy as np\n'), ((14453, 14478), 'numpy.dot', 'np.dot', (['Rot_e.T', 'quat_e_e'], {}), '(Rot_e.T, quat_e_e)\n', (14459, 14478), True, 'import numpy as np\n'), ((15770, 15786), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(211)'], {}), '(211)\n', (15781, 15786), True, 'import matplotlib.pyplot as plt\n'), ((15791, 15818), 'matplotlib.pyplot.title', 'plt.title', (['"""External force"""'], {}), "('External force')\n", (15800, 15818), True, 'import matplotlib.pyplot as plt\n'), ((15823, 15874), 'matplotlib.pyplot.plot', 'plt.plot', (['time_array', 'F_ext[2]'], {'label': '"""force z [N]"""'}), "(time_array, F_ext[2], label='force z [N]')\n", (15831, 15874), True, 'import matplotlib.pyplot as plt\n'), ((15879, 15971), 'matplotlib.pyplot.plot', 'plt.plot', (['time_array', 'F_d[2]'], {'label': '"""desired force z [N]"""', 'color': '"""b"""', 'linestyle': '"""dashed"""'}), "(time_array, F_d[2], label='desired force z [N]', color='b',\n linestyle='dashed')\n", (15887, 15971), True, 'import matplotlib.pyplot as plt\n'), ((15971, 15998), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Real time [s]"""'], {}), "('Real time [s]')\n", (15981, 15998), True, 'import matplotlib.pyplot as plt\n'), ((16003, 16015), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (16013, 16015), True, 'import matplotlib.pyplot as plt\n'), ((16022, 16038), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(212)'], {}), '(212)\n', (16033, 16038), True, 'import matplotlib.pyplot as plt\n'), ((16043, 16064), 'matplotlib.pyplot.title', 'plt.title', (['"""Position"""'], {}), "('Position')\n", (16052, 16064), True, 'import matplotlib.pyplot as plt\n'), ((16069, 16118), 'matplotlib.pyplot.plot', 'plt.plot', (['time_array', 'p[0, :]'], {'label': '"""true x [m]"""'}), "(time_array, p[0, :], label='true x [m]')\n", (16077, 16118), True, 'import matplotlib.pyplot as plt\n'), ((16124, 16173), 'matplotlib.pyplot.plot', 'plt.plot', (['time_array', 'p[1, :]'], {'label': '"""true y [m]"""'}), "(time_array, p[1, :], label='true y [m]')\n", (16132, 16173), True, 'import matplotlib.pyplot as plt\n'), ((16179, 16228), 'matplotlib.pyplot.plot', 'plt.plot', (['time_array', 'p[2, :]'], {'label': '"""true z [m]"""'}), "(time_array, p[2, :], label='true z [m]')\n", (16187, 16228), True, 'import matplotlib.pyplot as plt\n'), ((16235, 16325), 'matplotlib.pyplot.plot', 'plt.plot', (['time_array', 'p_d[0, :]'], {'label': '"""desired x [m]"""', 'color': '"""b"""', 'linestyle': '"""dashed"""'}), "(time_array, p_d[0, :], label='desired x [m]', color='b', linestyle\n ='dashed')\n", (16243, 16325), True, 'import matplotlib.pyplot as plt\n'), ((16325, 16415), 'matplotlib.pyplot.plot', 'plt.plot', (['time_array', 'p_d[1, :]'], {'label': '"""desired y [m]"""', 'color': '"""C1"""', 'linestyle': '"""dashed"""'}), "(time_array, p_d[1, :], label='desired y [m]', color='C1',\n linestyle='dashed')\n", (16333, 16415), True, 'import matplotlib.pyplot as plt\n'), ((16416, 16506), 'matplotlib.pyplot.plot', 'plt.plot', (['time_array', 'p_d[2, :]'], {'label': '"""desired z [m]"""', 'color': '"""g"""', 'linestyle': '"""dashed"""'}), "(time_array, p_d[2, :], label='desired z [m]', color='g', linestyle\n ='dashed')\n", (16424, 16506), True, 'import matplotlib.pyplot as plt\n'), ((16506, 16533), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Real time [s]"""'], {}), "('Real time [s]')\n", (16516, 16533), True, 'import matplotlib.pyplot as plt\n'), ((16538, 16550), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (16548, 16550), True, 'import matplotlib.pyplot as plt\n'), ((18369, 18379), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (18377, 18379), True, 'import matplotlib.pyplot as plt\n'), ((18469, 18505), 'rospy.init_node', 'rospy.init_node', (['"""impedance_control"""'], {}), "('impedance_control')\n", (18484, 18505), False, 'import rospy\n'), ((18518, 18528), 'panda_robot.PandaArm', 'PandaArm', ([], {}), '()\n', (18526, 18528), False, 'from panda_robot import PandaArm\n'), ((18563, 18587), 'rospy.Rate', 'rospy.Rate', (['publish_rate'], {}), '(publish_rate)\n', (18573, 18587), False, 'import rospy\n'), ((18825, 18837), 'numpy.zeros', 'np.zeros', (['(18)'], {}), '(18)\n', (18833, 18837), True, 'import numpy as np\n'), ((18854, 18879), 'numpy.zeros', 'np.zeros', (['(6, max_num_it)'], {}), '((6, max_num_it))\n', (18862, 18879), True, 'import numpy as np\n'), ((18936, 18961), 'numpy.zeros', 'np.zeros', (['(3, max_num_it)'], {}), '((3, max_num_it))\n', (18944, 18961), True, 'import numpy as np\n'), ((18981, 19006), 'numpy.zeros', 'np.zeros', (['(6, max_num_it)'], {}), '((6, max_num_it))\n', (18989, 19006), True, 'import numpy as np\n'), ((19022, 19047), 'numpy.zeros', 'np.zeros', (['(6, max_num_it)'], {}), '((6, max_num_it))\n', (19030, 19047), True, 'import numpy as np\n'), ((19069, 19094), 'numpy.zeros', 'np.zeros', (['(6, max_num_it)'], {}), '((6, max_num_it))\n', (19077, 19094), True, 'import numpy as np\n'), ((19114, 19139), 'numpy.zeros', 'np.zeros', (['(6, max_num_it)'], {}), '((6, max_num_it))\n', (19122, 19139), True, 'import numpy as np\n'), ((19164, 19189), 'numpy.zeros', 'np.zeros', (['(3, max_num_it)'], {}), '((3, max_num_it))\n', (19172, 19189), True, 'import numpy as np\n'), ((7509, 7523), 'numpy.zeros', 'np.zeros', (['size'], {}), '(size)\n', (7517, 7523), True, 'import numpy as np\n'), ((8012, 8028), 'numpy.linalg.inv', 'np.linalg.inv', (['W'], {}), '(W)\n', (8025, 8028), True, 'import numpy as np\n'), ((9462, 9493), 'numpy.append', 'np.append', (['delta_pos', 'delta_ori'], {}), '(delta_pos, delta_ori)\n', (9471, 9493), True, 'import numpy as np\n'), ((10461, 10496), 'quaternion.as_float_array', 'quaternion.as_float_array', (['rel_quat'], {}), '(rel_quat)\n', (10486, 10496), False, 'import quaternion\n'), ((11481, 11503), 'numpy.diagflat', 'np.diagflat', (['lam[6:12]'], {}), '(lam[6:12])\n', (11492, 11503), True, 'import numpy as np\n'), ((11520, 11543), 'numpy.diagflat', 'np.diagflat', (['lam[12:18]'], {}), '(lam[12:18])\n', (11531, 11543), True, 'import numpy as np\n'), ((14189, 14211), 'numpy.dot', 'np.dot', (['Rot_e.T', 'Rot_d'], {}), '(Rot_e.T, Rot_d)\n', (14195, 14211), True, 'import numpy as np\n'), ((14916, 14941), 'numpy.dot', 'np.dot', (['Rot_e_bigdim', 'h_e'], {}), '(Rot_e_bigdim, h_e)\n', (14922, 14941), True, 'import numpy as np\n'), ((7425, 7486), 'numpy.subtract', 'np.subtract', (['history[:, iteration]', 'history[:, iteration - 1]'], {}), '(history[:, iteration], history[:, iteration - 1])\n', (7436, 7486), True, 'import numpy as np\n'), ((11226, 11244), 'numpy.linalg.inv', 'np.linalg.inv', (['K_v'], {}), '(K_v)\n', (11239, 11244), True, 'import numpy as np\n'), ((11887, 11903), 'numpy.linalg.inv', 'np.linalg.inv', (['M'], {}), '(M)\n', (11900, 11903), True, 'import numpy as np\n'), ((13232, 13246), 'numpy.identity', 'np.identity', (['(3)'], {}), '(3)\n', (13243, 13246), True, 'import numpy as np\n'), ((13480, 13505), 'numpy.dot', 'np.dot', (['K_pt_dot', 'p_delta'], {}), '(K_pt_dot, p_delta)\n', (13486, 13505), True, 'import numpy as np\n'), ((13533, 13559), 'numpy.dot', 'np.dot', (['K_pt_ddot', 'p_delta'], {}), '(K_pt_ddot, p_delta)\n', (13539, 13559), True, 'import numpy as np\n'), ((13614, 13638), 'numpy.dot', 'np.dot', (['K_po_dot', 'quat_e'], {}), '(K_po_dot, quat_e)\n', (13620, 13638), True, 'import numpy as np\n'), ((14955, 14985), 'numpy.dot', 'np.dot', (['Rot_e_bigdim', 'x_d_ddot'], {}), '(Rot_e_bigdim, x_d_ddot)\n', (14961, 14985), True, 'import numpy as np\n'), ((15012, 15041), 'numpy.dot', 'np.dot', (['Rot_e_bigdim', 'x_d_dot'], {}), '(Rot_e_bigdim, x_d_dot)\n', (15018, 15041), True, 'import numpy as np\n'), ((11200, 11220), 'numpy.linalg.inv', 'np.linalg.inv', (['gamma'], {}), '(gamma)\n', (11213, 11220), True, 'import numpy as np\n'), ((12164, 12178), 'numpy.identity', 'np.identity', (['(6)'], {}), '(6)\n', (12175, 12178), True, 'import numpy as np\n'), ((12851, 12867), 'numpy.zeros', 'np.zeros', (['(3, 3)'], {}), '((3, 3))\n', (12859, 12867), True, 'import numpy as np\n'), ((12869, 12885), 'numpy.zeros', 'np.zeros', (['(3, 3)'], {}), '((3, 3))\n', (12877, 12885), True, 'import numpy as np\n'), ((15221, 15252), 'numpy.dot', 'np.dot', (['Rot_e_bigdim.T', 'alpha_e'], {}), '(Rot_e_bigdim.T, alpha_e)\n', (15227, 15252), True, 'import numpy as np\n'), ((15464, 15480), 'numpy.dot', 'np.dot', (['J.T', 'h_e'], {}), '(J.T, h_e)\n', (15470, 15480), True, 'import numpy as np\n'), ((5424, 5466), 'numpy.sin', 'np.sin', (['(it * T / 4 * 2 * np.pi + np.pi / 2)'], {}), '(it * T / 4 * 2 * np.pi + np.pi / 2)\n', (5430, 5466), True, 'import numpy as np\n'), ((6120, 6166), 'numpy.sin', 'np.sin', (['(2 * it * T / 4 * 2 * np.pi + np.pi / 2)'], {}), '(2 * it * T / 4 * 2 * np.pi + np.pi / 2)\n', (6126, 6166), True, 'import numpy as np\n'), ((6935, 6981), 'numpy.sin', 'np.sin', (['(2 * it * T / 4 * 2 * np.pi + np.pi / 2)'], {}), '(2 * it * T / 4 * 2 * np.pi + np.pi / 2)\n', (6941, 6981), True, 'import numpy as np\n'), ((12202, 12218), 'numpy.linalg.inv', 'np.linalg.inv', (['M'], {}), '(M)\n', (12215, 12218), True, 'import numpy as np\n'), ((12953, 12992), 'numpy.linalg.multi_dot', 'np.linalg.multi_dot', (['[R_d, K_pt, R_d.T]'], {}), '([R_d, K_pt, R_d.T])\n', (12972, 12992), True, 'import numpy as np\n'), ((12995, 13034), 'numpy.linalg.multi_dot', 'np.linalg.multi_dot', (['[R_e, K_pt, R_e.T]'], {}), '([R_e, K_pt, R_e.T])\n', (13014, 13034), True, 'import numpy as np\n'), ((13666, 13701), 'numpy.append', 'np.append', (['f_delta_t.T', 'm_delta_t.T'], {}), '(f_delta_t.T, m_delta_t.T)\n', (13675, 13701), True, 'import numpy as np\n'), ((13717, 13747), 'numpy.append', 'np.append', (['null.T', 'm_delta_o.T'], {}), '(null.T, m_delta_o.T)\n', (13726, 13747), True, 'import numpy as np\n'), ((15085, 15101), 'numpy.linalg.inv', 'np.linalg.inv', (['M'], {}), '(M)\n', (15098, 15101), True, 'import numpy as np\n'), ((15293, 15320), 'numpy.dot', 'np.dot', (['Rot_e_bigdim', 'x_dot'], {}), '(Rot_e_bigdim, x_dot)\n', (15299, 15320), True, 'import numpy as np\n'), ((9388, 9419), 'numpy.append', 'np.append', (['delta_pos', 'delta_ori'], {}), '(delta_pos, delta_ori)\n', (9397, 9419), True, 'import numpy as np\n'), ((11924, 11943), 'numpy.dot', 'np.dot', (['M', 'x_d_ddot'], {}), '(M, x_d_ddot)\n', (11930, 11943), True, 'import numpy as np\n'), ((12265, 12277), 'numpy.dot', 'np.dot', (['a', 'b'], {}), '(a, b)\n', (12271, 12277), True, 'import numpy as np\n'), ((15133, 15160), 'numpy.dot', 'np.dot', (['Rot_e_bigdim', 'x_dot'], {}), '(Rot_e_bigdim, x_dot)\n', (15139, 15160), True, 'import numpy as np\n')]
""" transforms.py is for shape-preserving functions. """ import numpy as np def shift(values: np.ndarray, periods: int, axis: int, fill_value) -> np.ndarray: new_values = values if periods == 0 or values.size == 0: return new_values.copy() # make sure array sent to np.roll is c_contiguous f_ordered = values.flags.f_contiguous if f_ordered: new_values = new_values.T axis = new_values.ndim - axis - 1 if new_values.size: new_values = np.roll( new_values, np.intp(periods), axis=axis, ) axis_indexer = [slice(None)] * values.ndim if periods > 0: axis_indexer[axis] = slice(None, periods) else: axis_indexer[axis] = slice(periods, None) new_values[tuple(axis_indexer)] = fill_value # restore original order if f_ordered: new_values = new_values.T return new_values
[ "numpy.intp" ]
[((564, 580), 'numpy.intp', 'np.intp', (['periods'], {}), '(periods)\n', (571, 580), True, 'import numpy as np\n')]
import random import math from functools import partial import json import pysndfx import librosa import numpy as np import torch from ops.audio import ( read_audio, compute_stft, trim_audio, mix_audio_and_labels, shuffle_audio, cutout ) SAMPLE_RATE = 44100 class Augmentation: """A base class for data augmentation transforms""" pass class MapLabels: def __init__(self, class_map, drop_raw=True): self.class_map = class_map def __call__(self, dataset, **inputs): labels = np.zeros(len(self.class_map), dtype=np.float32) for c in inputs["raw_labels"]: labels[self.class_map[c]] = 1.0 transformed = dict(inputs) transformed["labels"] = labels transformed.pop("raw_labels") return transformed class MixUp(Augmentation): def __init__(self, p): self.p = p def __call__(self, dataset, **inputs): transformed = dict(inputs) if np.random.uniform() < self.p: first_audio, first_labels = inputs["audio"], inputs["labels"] random_sample = dataset.random_clean_sample() new_audio, new_labels = mix_audio_and_labels( first_audio, random_sample["audio"], first_labels, random_sample["labels"] ) transformed["audio"] = new_audio transformed["labels"] = new_labels return transformed class FlipAudio(Augmentation): def __init__(self, p): self.p = p def __call__(self, dataset, **inputs): transformed = dict(inputs) if np.random.uniform() < self.p: transformed["audio"] = np.flipud(inputs["audio"]) return transformed class AudioAugmentation(Augmentation): def __init__(self, p): self.p = p def __call__(self, dataset, **inputs): transformed = dict(inputs) if np.random.uniform() < self.p: effects_chain = ( pysndfx.AudioEffectsChain() .reverb( reverberance=random.randrange(50), room_scale=random.randrange(50), stereo_depth=random.randrange(50) ) .pitch(shift=random.randrange(-300, 300)) .overdrive(gain=random.randrange(2, 10)) .speed(random.uniform(0.9, 1.1)) ) transformed["audio"] = effects_chain(inputs["audio"]) return transformed class LoadAudio: def __init__(self): pass def __call__(self, dataset, **inputs): audio, sr = read_audio(inputs["filename"]) transformed = dict(inputs) transformed["audio"] = audio transformed["sr"] = sr return transformed class STFT: eps = 1e-4 def __init__(self, n_fft, hop_size): self.n_fft = n_fft self.hop_size = hop_size def __call__(self, dataset, **inputs): stft = compute_stft( inputs["audio"], window_size=self.n_fft, hop_size=self.hop_size, eps=self.eps) transformed = dict(inputs) transformed["stft"] = np.transpose(stft) return transformed class AudioFeatures: eps = 1e-4 def __init__(self, descriptor, verbose=True): name, *args = descriptor.split("_") self.feature_type = name if name == "stft": n_fft, hop_size = args self.n_fft = int(n_fft) self.hop_size = int(hop_size) self.n_features = self.n_fft // 2 + 1 self.padding_value = 0.0 if verbose: print( "\nUsing STFT features with params:\n", "n_fft: {}, hop_size: {}".format( n_fft, hop_size ) ) elif name == "mel": n_fft, hop_size, n_mel = args self.n_fft = int(n_fft) self.hop_size = int(hop_size) self.n_mel = int(n_mel) self.n_features = self.n_mel self.padding_value = 0.0 if verbose: print( "\nUsing mel features with params:\n", "n_fft: {}, hop_size: {}, n_mel: {}".format( n_fft, hop_size, n_mel ) ) elif name == "raw": self.n_features = 1 self.padding_value = 0.0 if verbose: print( "\nUsing raw waveform features." ) def __call__(self, dataset, **inputs): transformed = dict(inputs) if self.feature_type == "stft": # stft = compute_stft( # inputs["audio"], # window_size=self.n_fft, hop_size=self.hop_size, # eps=self.eps, log=True # ) transformed["signal"] = np.expand_dims(inputs["audio"], -1) elif self.feature_type == "mel": stft = compute_stft( inputs["audio"], window_size=self.n_fft, hop_size=self.hop_size, eps=self.eps, log=False ) transformed["signal"] = np.expand_dims(inputs["audio"], -1) elif self.feature_type == "raw": transformed["signal"] = np.expand_dims(inputs["audio"], -1) return transformed class SampleSegment(Augmentation): def __init__(self, ratio=(0.3, 0.9), p=1.0): self.min, self.max = ratio self.p = p def __call__(self, dataset, **inputs): transformed = dict(inputs) if np.random.uniform() < self.p: original_size = inputs["audio"].size target_size = int(np.random.uniform(self.min, self.max) * original_size) start = np.random.randint(original_size - target_size - 1) transformed["audio"] = inputs["audio"][start:start+target_size] return transformed class ShuffleAudio(Augmentation): def __init__(self, chunk_length=0.5, p=0.5): self.chunk_length = chunk_length self.p = p def __call__(self, dataset, **inputs): transformed = dict(inputs) if np.random.uniform() < self.p: transformed["audio"] = shuffle_audio( transformed["audio"], self.chunk_length, sr=transformed["sr"]) return transformed class CutOut(Augmentation): def __init__(self, area=0.25, p=0.5): self.area = area self.p = p def __call__(self, dataset, **inputs): transformed = dict(inputs) if np.random.uniform() < self.p: transformed["audio"] = cutout( transformed["audio"], self.area) return transformed class SampleLongAudio: def __init__(self, max_length): self.max_length = max_length def __call__(self, dataset, **inputs): transformed = dict(inputs) if (inputs["audio"].size / inputs["sr"]) > self.max_length: max_length = self.max_length * inputs["sr"] start = np.random.randint(0, inputs["audio"].size - max_length) transformed["audio"] = inputs["audio"][start:start+max_length] return transformed class OneOf: def __init__(self, transforms): self.transforms = transforms def __call__(self, dataset, **inputs): transform = random.choice(self.transforms) return transform(**inputs) class DropFields: def __init__(self, fields): self.to_drop = fields def __call__(self, dataset, **inputs): transformed = dict() for name, input in inputs.items(): if not name in self.to_drop: transformed[name] = input return transformed class RenameFields: def __init__(self, mapping): self.mapping = mapping def __call__(self, dataset, **inputs): transformed = dict(inputs) for old, new in self.mapping.items(): transformed[new] = transformed.pop(old) return transformed class Compose: def __init__(self, transforms): self.transforms = transforms def switch_off_augmentations(self): for t in self.transforms: if isinstance(t, Augmentation): t.p = 0.0 def __call__(self, dataset=None, **inputs): for t in self.transforms: inputs = t(dataset=dataset, **inputs) return inputs class Identity: def __call__(self, dataset=None, **inputs): return inputs
[ "random.uniform", "random.choice", "ops.audio.compute_stft", "numpy.flipud", "random.randrange", "ops.audio.mix_audio_and_labels", "numpy.random.randint", "ops.audio.shuffle_audio", "pysndfx.AudioEffectsChain", "ops.audio.read_audio", "numpy.random.uniform", "numpy.expand_dims", "numpy.transpose", "ops.audio.cutout" ]
[((2606, 2636), 'ops.audio.read_audio', 'read_audio', (["inputs['filename']"], {}), "(inputs['filename'])\n", (2616, 2636), False, 'from ops.audio import read_audio, compute_stft, trim_audio, mix_audio_and_labels, shuffle_audio, cutout\n'), ((2962, 3058), 'ops.audio.compute_stft', 'compute_stft', (["inputs['audio']"], {'window_size': 'self.n_fft', 'hop_size': 'self.hop_size', 'eps': 'self.eps'}), "(inputs['audio'], window_size=self.n_fft, hop_size=self.\n hop_size, eps=self.eps)\n", (2974, 3058), False, 'from ops.audio import read_audio, compute_stft, trim_audio, mix_audio_and_labels, shuffle_audio, cutout\n'), ((3157, 3175), 'numpy.transpose', 'np.transpose', (['stft'], {}), '(stft)\n', (3169, 3175), True, 'import numpy as np\n'), ((7418, 7448), 'random.choice', 'random.choice', (['self.transforms'], {}), '(self.transforms)\n', (7431, 7448), False, 'import random\n'), ((966, 985), 'numpy.random.uniform', 'np.random.uniform', ([], {}), '()\n', (983, 985), True, 'import numpy as np\n'), ((1164, 1264), 'ops.audio.mix_audio_and_labels', 'mix_audio_and_labels', (['first_audio', "random_sample['audio']", 'first_labels', "random_sample['labels']"], {}), "(first_audio, random_sample['audio'], first_labels,\n random_sample['labels'])\n", (1184, 1264), False, 'from ops.audio import read_audio, compute_stft, trim_audio, mix_audio_and_labels, shuffle_audio, cutout\n'), ((1601, 1620), 'numpy.random.uniform', 'np.random.uniform', ([], {}), '()\n', (1618, 1620), True, 'import numpy as np\n'), ((1666, 1692), 'numpy.flipud', 'np.flipud', (["inputs['audio']"], {}), "(inputs['audio'])\n", (1675, 1692), True, 'import numpy as np\n'), ((1902, 1921), 'numpy.random.uniform', 'np.random.uniform', ([], {}), '()\n', (1919, 1921), True, 'import numpy as np\n'), ((4940, 4975), 'numpy.expand_dims', 'np.expand_dims', (["inputs['audio']", '(-1)'], {}), "(inputs['audio'], -1)\n", (4954, 4975), True, 'import numpy as np\n'), ((5652, 5671), 'numpy.random.uniform', 'np.random.uniform', ([], {}), '()\n', (5669, 5671), True, 'import numpy as np\n'), ((5836, 5886), 'numpy.random.randint', 'np.random.randint', (['(original_size - target_size - 1)'], {}), '(original_size - target_size - 1)\n', (5853, 5886), True, 'import numpy as np\n'), ((6230, 6249), 'numpy.random.uniform', 'np.random.uniform', ([], {}), '()\n', (6247, 6249), True, 'import numpy as np\n'), ((6295, 6371), 'ops.audio.shuffle_audio', 'shuffle_audio', (["transformed['audio']", 'self.chunk_length'], {'sr': "transformed['sr']"}), "(transformed['audio'], self.chunk_length, sr=transformed['sr'])\n", (6308, 6371), False, 'from ops.audio import read_audio, compute_stft, trim_audio, mix_audio_and_labels, shuffle_audio, cutout\n'), ((6627, 6646), 'numpy.random.uniform', 'np.random.uniform', ([], {}), '()\n', (6644, 6646), True, 'import numpy as np\n'), ((6692, 6731), 'ops.audio.cutout', 'cutout', (["transformed['audio']", 'self.area'], {}), "(transformed['audio'], self.area)\n", (6698, 6731), False, 'from ops.audio import read_audio, compute_stft, trim_audio, mix_audio_and_labels, shuffle_audio, cutout\n'), ((7104, 7159), 'numpy.random.randint', 'np.random.randint', (['(0)', "(inputs['audio'].size - max_length)"], {}), "(0, inputs['audio'].size - max_length)\n", (7121, 7159), True, 'import numpy as np\n'), ((2349, 2373), 'random.uniform', 'random.uniform', (['(0.9)', '(1.1)'], {}), '(0.9, 1.1)\n', (2363, 2373), False, 'import random\n'), ((5038, 5145), 'ops.audio.compute_stft', 'compute_stft', (["inputs['audio']"], {'window_size': 'self.n_fft', 'hop_size': 'self.hop_size', 'eps': 'self.eps', 'log': '(False)'}), "(inputs['audio'], window_size=self.n_fft, hop_size=self.\n hop_size, eps=self.eps, log=False)\n", (5050, 5145), False, 'from ops.audio import read_audio, compute_stft, trim_audio, mix_audio_and_labels, shuffle_audio, cutout\n'), ((5240, 5275), 'numpy.expand_dims', 'np.expand_dims', (["inputs['audio']", '(-1)'], {}), "(inputs['audio'], -1)\n", (5254, 5275), True, 'import numpy as np\n'), ((5354, 5389), 'numpy.expand_dims', 'np.expand_dims', (["inputs['audio']", '(-1)'], {}), "(inputs['audio'], -1)\n", (5368, 5389), True, 'import numpy as np\n'), ((5761, 5798), 'numpy.random.uniform', 'np.random.uniform', (['self.min', 'self.max'], {}), '(self.min, self.max)\n', (5778, 5798), True, 'import numpy as np\n'), ((2301, 2324), 'random.randrange', 'random.randrange', (['(2)', '(10)'], {}), '(2, 10)\n', (2317, 2324), False, 'import random\n'), ((2240, 2267), 'random.randrange', 'random.randrange', (['(-300)', '(300)'], {}), '(-300, 300)\n', (2256, 2267), False, 'import random\n'), ((1978, 2005), 'pysndfx.AudioEffectsChain', 'pysndfx.AudioEffectsChain', ([], {}), '()\n', (2003, 2005), False, 'import pysndfx\n'), ((2064, 2084), 'random.randrange', 'random.randrange', (['(50)'], {}), '(50)\n', (2080, 2084), False, 'import random\n'), ((2117, 2137), 'random.randrange', 'random.randrange', (['(50)'], {}), '(50)\n', (2133, 2137), False, 'import random\n'), ((2172, 2192), 'random.randrange', 'random.randrange', (['(50)'], {}), '(50)\n', (2188, 2192), False, 'import random\n')]
#!/usr/env/bin python import os # os.environ['OMP_NUM_THREADS'] = '1' from newpoisson import poisson import numpy as np from fenics import set_log_level, File, RectangleMesh, Point mesh = RectangleMesh(Point(0,0), Point(1,1), 36, 36) # comm = mesh.mpi_comm() set_log_level(40) # ERROR=40 # from mpi4py import MPI # comm = MPI.COMM_WORLD # rank = comm.Get_rank() if __name__=='__main__': import argparse parser = argparse.ArgumentParser(description="Poisson Problem") parser.add_argument('-n', '--num', default = 10, type=int, help="Number of samples") parser.add_argument('-o', '--outfile', default='results', help="Output filename (no extension)") parser.add_argument('-i', '--input-dim', default=1, type=int) parser.add_argument('-d', '--dist', default='u', help='Distribution. `n` (normal), `u` (uniform, default)') args = parser.parse_args() num_samples = args.num dist = args.dist outfile = args.outfile.replace('.pkl','') inputdim = args.input_dim if inputdim == 1: # U[1,5] randsamples = 1 + 4*np.random.rand(num_samples) else: # N(0,1) if dist == 'n': randsamples = np.random.randn(num_samples, inputdim) elif dist == 'u': randsamples = -4*np.random.rand(num_samples, inputdim) else: raise ValueError("Improper distribution choice, use `n` (normal), `u` (uniform)") sample_seed_list = list(zip(range(num_samples), randsamples)) def wrapper(sample, outfile): g=sample[1] u = poisson(gamma=g, mesh=mesh) # Save solution fname = f"{outfile}-data/poisson-{int(sample[0]):06d}.xml" File(fname, 'w') << u return {int(sample[0]): {'u': fname, 'gamma': sample[1]}} results = [] for sample in sample_seed_list: r = wrapper(sample, outfile) results.append(r) # print(results) import pickle pickle.dump(results, open(f'{outfile}.pkl','wb'))
[ "fenics.Point", "numpy.random.rand", "argparse.ArgumentParser", "fenics.set_log_level", "numpy.random.randn", "fenics.File", "newpoisson.poisson" ]
[((261, 278), 'fenics.set_log_level', 'set_log_level', (['(40)'], {}), '(40)\n', (274, 278), False, 'from fenics import set_log_level, File, RectangleMesh, Point\n'), ((203, 214), 'fenics.Point', 'Point', (['(0)', '(0)'], {}), '(0, 0)\n', (208, 214), False, 'from fenics import set_log_level, File, RectangleMesh, Point\n'), ((215, 226), 'fenics.Point', 'Point', (['(1)', '(1)'], {}), '(1, 1)\n', (220, 226), False, 'from fenics import set_log_level, File, RectangleMesh, Point\n'), ((425, 479), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Poisson Problem"""'}), "(description='Poisson Problem')\n", (448, 479), False, 'import argparse\n'), ((1580, 1607), 'newpoisson.poisson', 'poisson', ([], {'gamma': 'g', 'mesh': 'mesh'}), '(gamma=g, mesh=mesh)\n', (1587, 1607), False, 'from newpoisson import poisson\n'), ((1206, 1244), 'numpy.random.randn', 'np.random.randn', (['num_samples', 'inputdim'], {}), '(num_samples, inputdim)\n', (1221, 1244), True, 'import numpy as np\n'), ((1708, 1724), 'fenics.File', 'File', (['fname', '"""w"""'], {}), "(fname, 'w')\n", (1712, 1724), False, 'from fenics import set_log_level, File, RectangleMesh, Point\n'), ((1109, 1136), 'numpy.random.rand', 'np.random.rand', (['num_samples'], {}), '(num_samples)\n', (1123, 1136), True, 'import numpy as np\n'), ((1300, 1337), 'numpy.random.rand', 'np.random.rand', (['num_samples', 'inputdim'], {}), '(num_samples, inputdim)\n', (1314, 1337), True, 'import numpy as np\n')]
import streamlit as st import math from scipy.stats import * import pandas as pd import numpy as np from plotnine import * def app(): # title of the app st.subheader("Proportions") st.sidebar.subheader("Proportion Settings") prop_choice = st.sidebar.radio("",["One Proportion","Two Proportions"]) if prop_choice == "One Proportion": c1,c2,c3 = st.columns(3) with c1: x = int(st.text_input("Hits",20)) n = int(st.text_input("Tries",25)) with c2: nullp = float(st.text_input("Null:",.7)) alpha = float(st.text_input("Alpha",.05)) with c3: st.markdown("Pick a test:") tail_choice = st.radio("",["Left Tail","Two Tails","Right Tail"]) one = st.columns(1) with one[0]: p_hat = x/n tsd = math.sqrt(nullp*(1-nullp)/n) cise = math.sqrt(p_hat*(1-p_hat)/n) z = (p_hat - nullp)/tsd x = np.arange(-4,4,.1) y = norm.pdf(x) ndf = pd.DataFrame({"x":x,"y":y}) normp = ggplot(ndf) + coord_fixed(ratio = 4) if tail_choice == "Left Tail": pv = norm.cdf(z) cz = norm.ppf(alpha) rcz = cz cl = 1 - 2*alpha normp = normp + stat_function(fun = norm.pdf, geom = "area",fill = "steelblue", xlim = (-4,z)) normp = normp + stat_function(fun = norm.pdf, geom = "area",fill = "orange", xlim = (-4,cz)) if tail_choice == "Two Tails": pv = 2*(1-norm.cdf(abs(z))) cz = abs(norm.ppf(alpha/2)) rcz = "±" + str(abs(norm.ppf(alpha/2))) cl = 1 - alpha normp = normp + stat_function(fun = norm.pdf, geom = "area",fill = "steelblue", xlim = (-4,-1*abs(z))) normp = normp + stat_function(fun = norm.pdf, geom = "area",fill = "steelblue", xlim = (abs(z),4)) normp = normp + stat_function(fun = norm.pdf, geom = "area",fill = "orange", xlim = (-4,-1*abs(cz))) normp = normp + stat_function(fun = norm.pdf, geom = "area",fill = "orange", xlim = (abs(cz),4)) if tail_choice == "Right Tail": pv = 1 - norm.cdf(z) cz = -1 * norm.ppf(alpha) rcz = cz cl = 1 - 2*alpha normp = normp + stat_function(fun = norm.pdf, geom = "area",fill = "steelblue", xlim = (z,4)) normp = normp + stat_function(fun = norm.pdf, geom = "area",fill = "orange", xlim = (cz,4)) me = cz * cise rme = "±" + str(abs(me)) data = pd.DataFrame({"p-Hat":p_hat,"z-Score":z,"p-Value":pv,"CV":rcz,"Test SD":tsd,"C-Level":cl,"CI SE":cise,"ME":rme},index = [0]) st.write(data) normp = normp + geom_segment(aes(x = z, y = 0, xend = z, yend = norm.pdf(z)),color="red") normp = normp + geom_line(aes(x=x,y=y)) st.pyplot(ggplot.draw(normp)) lower = p_hat - abs(me) upper = p_hat + abs(me) st.write(str(100*cl) + "'%' confidence interval is (" + str(lower) +", "+str(upper)+")") if prop_choice == "Two Proportions": c1,c2,c3 = st.columns(3) with c1: x1 = int(st.text_input("Hits 1",20)) n1 = int(st.text_input("Tries 1",25)) with c2: x2 = int(st.text_input("Hits 2",30)) n2 = int(st.text_input("Tries 2",50)) with c3: alpha = float(st.text_input("Alpha",.05)) st.markdown("Pick a test:") tail_choice = st.radio("",["Left Tail","Two Tails","Right Tail"]) one = st.columns(1) with one[0]: p_hat1 = x1/n1 q_hat1 = 1 -p_hat1 p_hat2 = x2/n2 q_hat2 = 1 - p_hat2 pp_hat = (x1+x2)/(n1+n2) dp_hat = p_hat1 - p_hat2 pq_hat = 1-pp_hat tsd = math.sqrt(pp_hat*pq_hat*(1/n1+1/n2)) cise = math.sqrt(p_hat1*q_hat1/n1+p_hat2*q_hat2/n2) z = (p_hat1 - p_hat2)/tsd x = np.arange(-4,4,.1) y = norm.pdf(x) ndf = pd.DataFrame({"x":x,"y":y}) normp = ggplot(ndf) + coord_fixed(ratio = 4) if tail_choice == "Left Tail": pv = norm.cdf(z) cz = norm.ppf(alpha) rcz = cz cl = 1 - 2*alpha normp = normp + stat_function(fun = norm.pdf, geom = "area",fill = "steelblue", xlim = (-4,z)) normp = normp + stat_function(fun = norm.pdf, geom = "area",fill = "orange", xlim = (-4,cz)) if tail_choice == "Two Tails": pv = 2*(1-norm.cdf(abs(z))) cz = abs(norm.ppf(alpha/2)) rcz = "±" + str(abs(norm.ppf(alpha/2))) cl = 1 - alpha normp = normp + stat_function(fun = norm.pdf, geom = "area",fill = "steelblue", xlim = (-4,-1*abs(z))) normp = normp + stat_function(fun = norm.pdf, geom = "area",fill = "steelblue", xlim = (abs(z),4)) normp = normp + stat_function(fun = norm.pdf, geom = "area",fill = "orange", xlim = (-4,-1*abs(cz))) normp = normp + stat_function(fun = norm.pdf, geom = "area",fill = "orange", xlim = (abs(cz),4)) if tail_choice == "Right Tail": pv = 1 - norm.cdf(z) cz = -1 * norm.ppf(alpha) rcz = cz cl = 1 - 2*alpha normp = normp + stat_function(fun = norm.pdf, geom = "area",fill = "steelblue", xlim = (z,4)) normp = normp + stat_function(fun = norm.pdf, geom = "area",fill = "orange", xlim = (cz,4)) me = cz * cise rme = "±" + str(abs(me)) data = pd.DataFrame({"p-Hat 1":p_hat1,"p-Hat 2":p_hat2,"Pooled p-Hat":pp_hat,"Diff p-Hat":dp_hat,"z-Score":z,"p-Value":pv,"CV":rcz,"Test SD":tsd,"C-Level":cl,"CI SE":cise,"ME":rme},index = [0]) st.write(data) normp = normp + geom_segment(aes(x = z, y = 0, xend = z, yend = norm.pdf(z)),color="red") normp = normp + geom_line(aes(x=x,y=y)) st.pyplot(ggplot.draw(normp)) lower = dp_hat - abs(me) upper = dp_hat + abs(me) st.write(str(100*cl) + "'%' confidence interval is (" + str(lower) +", "+str(upper)+")")
[ "streamlit.markdown", "math.sqrt", "streamlit.write", "streamlit.radio", "streamlit.sidebar.radio", "streamlit.sidebar.subheader", "streamlit.subheader", "streamlit.text_input", "pandas.DataFrame", "streamlit.columns", "numpy.arange" ]
[((162, 189), 'streamlit.subheader', 'st.subheader', (['"""Proportions"""'], {}), "('Proportions')\n", (174, 189), True, 'import streamlit as st\n'), ((194, 237), 'streamlit.sidebar.subheader', 'st.sidebar.subheader', (['"""Proportion Settings"""'], {}), "('Proportion Settings')\n", (214, 237), True, 'import streamlit as st\n'), ((256, 315), 'streamlit.sidebar.radio', 'st.sidebar.radio', (['""""""', "['One Proportion', 'Two Proportions']"], {}), "('', ['One Proportion', 'Two Proportions'])\n", (272, 315), True, 'import streamlit as st\n'), ((378, 391), 'streamlit.columns', 'st.columns', (['(3)'], {}), '(3)\n', (388, 391), True, 'import streamlit as st\n'), ((780, 793), 'streamlit.columns', 'st.columns', (['(1)'], {}), '(1)\n', (790, 793), True, 'import streamlit as st\n'), ((3287, 3300), 'streamlit.columns', 'st.columns', (['(3)'], {}), '(3)\n', (3297, 3300), True, 'import streamlit as st\n'), ((3754, 3767), 'streamlit.columns', 'st.columns', (['(1)'], {}), '(1)\n', (3764, 3767), True, 'import streamlit as st\n'), ((655, 682), 'streamlit.markdown', 'st.markdown', (['"""Pick a test:"""'], {}), "('Pick a test:')\n", (666, 682), True, 'import streamlit as st\n'), ((709, 763), 'streamlit.radio', 'st.radio', (['""""""', "['Left Tail', 'Two Tails', 'Right Tail']"], {}), "('', ['Left Tail', 'Two Tails', 'Right Tail'])\n", (717, 763), True, 'import streamlit as st\n'), ((857, 891), 'math.sqrt', 'math.sqrt', (['(nullp * (1 - nullp) / n)'], {}), '(nullp * (1 - nullp) / n)\n', (866, 891), False, 'import math\n'), ((905, 939), 'math.sqrt', 'math.sqrt', (['(p_hat * (1 - p_hat) / n)'], {}), '(p_hat * (1 - p_hat) / n)\n', (914, 939), False, 'import math\n'), ((986, 1007), 'numpy.arange', 'np.arange', (['(-4)', '(4)', '(0.1)'], {}), '(-4, 4, 0.1)\n', (995, 1007), True, 'import numpy as np\n'), ((1051, 1081), 'pandas.DataFrame', 'pd.DataFrame', (["{'x': x, 'y': y}"], {}), "({'x': x, 'y': y})\n", (1063, 1081), True, 'import pandas as pd\n'), ((2693, 2835), 'pandas.DataFrame', 'pd.DataFrame', (["{'p-Hat': p_hat, 'z-Score': z, 'p-Value': pv, 'CV': rcz, 'Test SD': tsd,\n 'C-Level': cl, 'CI SE': cise, 'ME': rme}"], {'index': '[0]'}), "({'p-Hat': p_hat, 'z-Score': z, 'p-Value': pv, 'CV': rcz,\n 'Test SD': tsd, 'C-Level': cl, 'CI SE': cise, 'ME': rme}, index=[0])\n", (2705, 2835), True, 'import pandas as pd\n'), ((2832, 2846), 'streamlit.write', 'st.write', (['data'], {}), '(data)\n', (2840, 2846), True, 'import streamlit as st\n'), ((3629, 3656), 'streamlit.markdown', 'st.markdown', (['"""Pick a test:"""'], {}), "('Pick a test:')\n", (3640, 3656), True, 'import streamlit as st\n'), ((3683, 3737), 'streamlit.radio', 'st.radio', (['""""""', "['Left Tail', 'Two Tails', 'Right Tail']"], {}), "('', ['Left Tail', 'Two Tails', 'Right Tail'])\n", (3691, 3737), True, 'import streamlit as st\n'), ((4028, 4074), 'math.sqrt', 'math.sqrt', (['(pp_hat * pq_hat * (1 / n1 + 1 / n2))'], {}), '(pp_hat * pq_hat * (1 / n1 + 1 / n2))\n', (4037, 4074), False, 'import math\n'), ((4084, 4138), 'math.sqrt', 'math.sqrt', (['(p_hat1 * q_hat1 / n1 + p_hat2 * q_hat2 / n2)'], {}), '(p_hat1 * q_hat1 / n1 + p_hat2 * q_hat2 / n2)\n', (4093, 4138), False, 'import math\n'), ((4196, 4217), 'numpy.arange', 'np.arange', (['(-4)', '(4)', '(0.1)'], {}), '(-4, 4, 0.1)\n', (4205, 4217), True, 'import numpy as np\n'), ((4261, 4291), 'pandas.DataFrame', 'pd.DataFrame', (["{'x': x, 'y': y}"], {}), "({'x': x, 'y': y})\n", (4273, 4291), True, 'import pandas as pd\n'), ((5915, 6129), 'pandas.DataFrame', 'pd.DataFrame', (["{'p-Hat 1': p_hat1, 'p-Hat 2': p_hat2, 'Pooled p-Hat': pp_hat, 'Diff p-Hat':\n dp_hat, 'z-Score': z, 'p-Value': pv, 'CV': rcz, 'Test SD': tsd,\n 'C-Level': cl, 'CI SE': cise, 'ME': rme}"], {'index': '[0]'}), "({'p-Hat 1': p_hat1, 'p-Hat 2': p_hat2, 'Pooled p-Hat': pp_hat,\n 'Diff p-Hat': dp_hat, 'z-Score': z, 'p-Value': pv, 'CV': rcz, 'Test SD':\n tsd, 'C-Level': cl, 'CI SE': cise, 'ME': rme}, index=[0])\n", (5927, 6129), True, 'import pandas as pd\n'), ((6116, 6130), 'streamlit.write', 'st.write', (['data'], {}), '(data)\n', (6124, 6130), True, 'import streamlit as st\n'), ((429, 454), 'streamlit.text_input', 'st.text_input', (['"""Hits"""', '(20)'], {}), "('Hits', 20)\n", (442, 454), True, 'import streamlit as st\n'), ((475, 501), 'streamlit.text_input', 'st.text_input', (['"""Tries"""', '(25)'], {}), "('Tries', 25)\n", (488, 501), True, 'import streamlit as st\n'), ((545, 572), 'streamlit.text_input', 'st.text_input', (['"""Null:"""', '(0.7)'], {}), "('Null:', 0.7)\n", (558, 572), True, 'import streamlit as st\n'), ((598, 626), 'streamlit.text_input', 'st.text_input', (['"""Alpha"""', '(0.05)'], {}), "('Alpha', 0.05)\n", (611, 626), True, 'import streamlit as st\n'), ((3339, 3366), 'streamlit.text_input', 'st.text_input', (['"""Hits 1"""', '(20)'], {}), "('Hits 1', 20)\n", (3352, 3366), True, 'import streamlit as st\n'), ((3388, 3416), 'streamlit.text_input', 'st.text_input', (['"""Tries 1"""', '(25)'], {}), "('Tries 1', 25)\n", (3401, 3416), True, 'import streamlit as st\n'), ((3468, 3495), 'streamlit.text_input', 'st.text_input', (['"""Hits 2"""', '(30)'], {}), "('Hits 2', 30)\n", (3481, 3495), True, 'import streamlit as st\n'), ((3517, 3545), 'streamlit.text_input', 'st.text_input', (['"""Tries 2"""', '(50)'], {}), "('Tries 2', 50)\n", (3530, 3545), True, 'import streamlit as st\n'), ((3589, 3617), 'streamlit.text_input', 'st.text_input', (['"""Alpha"""', '(0.05)'], {}), "('Alpha', 0.05)\n", (3602, 3617), True, 'import streamlit as st\n')]
#Answer Generation import csv import os import numpy as np from keras.models import * from keras.models import Model from keras.preprocessing import text def load_model(): print('\nLoading model...') # load json and create model json_file = open('models/MODEL.json', 'r') loaded_model_json = json_file.read() json_file.close() gate_model = model_from_json(loaded_model_json) # load weights into new model gate_model.load_weights('models/MODEL.h5', by_name=True) return gate_model train_ans, anslist = [], [] def ans_vec(): anslist = [] dataset = ['Train'] for data in dataset: f = open('data/raw/' + data + '.csv') lines = csv.reader(f) for line in lines: source_uri = line[4] anslist.append(source_uri) f.close() return anslist def generate_save_ans(): dic = 3 anslist = ans_vec() gate_model = load_model() test_title_feature = np.load('data/vectorized/Test_title.npy') test_summary_feature = np.load('data/vectorized/Test_summary.npy') tokenizer_a = text.Tokenizer(num_words=dic+1) tokenizer_a.fit_on_texts(anslist) dic_a = tokenizer_a.word_index ind_a ={value:key for key, value in dic_a.items()} num_test = len(open('data/raw/Test.csv', 'r').readlines()) ans = gate_model.predict([ test_title_feature, test_summary_feature]) fp = open('reports/Test.ans', 'w') for h in range(num_test): i = h if np.argmax(ans[i][0],axis=0) == 0: fp.write('indiatimes\n') #Low frequency words are replaced with "indiatimes" else: for j in range(dic): an = np.argmax(ans[i][j],axis=0) if j != dic-1: anext = np.argmax(ans[i][j+1],axis=0) if an != 0 and anext != 0: #Words before and after if an == anext: fp.write('') #Delete duplicate words else: fp.write(ind_a[an] + ' ') elif an != 0 and anext == 0: fp.write(ind_a[an]) elif an == 0 and anext != 0: fp.write(ind_a[anext]) else: fp.write('') else: if an != 0: fp.write(ind_a[an] + '\n') else: fp.write('\n') fp.close() def main(): load_model() print('\n\nGenerating answers...') if os.path.exists('reports') == False: os.mkdir('reports') if os.path.isfile('reports/Test.ans') == False: generate_save_ans() print('\nAnswer generation complete...\n\n') if __name__ == "__main__": main()
[ "os.path.exists", "keras.preprocessing.text.Tokenizer", "numpy.argmax", "os.path.isfile", "os.mkdir", "numpy.load", "csv.reader" ]
[((976, 1017), 'numpy.load', 'np.load', (['"""data/vectorized/Test_title.npy"""'], {}), "('data/vectorized/Test_title.npy')\n", (983, 1017), True, 'import numpy as np\n'), ((1045, 1088), 'numpy.load', 'np.load', (['"""data/vectorized/Test_summary.npy"""'], {}), "('data/vectorized/Test_summary.npy')\n", (1052, 1088), True, 'import numpy as np\n'), ((1108, 1141), 'keras.preprocessing.text.Tokenizer', 'text.Tokenizer', ([], {'num_words': '(dic + 1)'}), '(num_words=dic + 1)\n', (1122, 1141), False, 'from keras.preprocessing import text\n'), ((698, 711), 'csv.reader', 'csv.reader', (['f'], {}), '(f)\n', (708, 711), False, 'import csv\n'), ((2606, 2631), 'os.path.exists', 'os.path.exists', (['"""reports"""'], {}), "('reports')\n", (2620, 2631), False, 'import os\n'), ((2650, 2669), 'os.mkdir', 'os.mkdir', (['"""reports"""'], {}), "('reports')\n", (2658, 2669), False, 'import os\n'), ((2678, 2712), 'os.path.isfile', 'os.path.isfile', (['"""reports/Test.ans"""'], {}), "('reports/Test.ans')\n", (2692, 2712), False, 'import os\n'), ((1515, 1543), 'numpy.argmax', 'np.argmax', (['ans[i][0]'], {'axis': '(0)'}), '(ans[i][0], axis=0)\n', (1524, 1543), True, 'import numpy as np\n'), ((1707, 1735), 'numpy.argmax', 'np.argmax', (['ans[i][j]'], {'axis': '(0)'}), '(ans[i][j], axis=0)\n', (1716, 1735), True, 'import numpy as np\n'), ((1794, 1826), 'numpy.argmax', 'np.argmax', (['ans[i][j + 1]'], {'axis': '(0)'}), '(ans[i][j + 1], axis=0)\n', (1803, 1826), True, 'import numpy as np\n')]
"""Non-linear SPDE model on a periodic 1D spatial domain for laminar wave fronts. Based on the Kuramato--Sivashinsky PDE model [1, 2] which exhibits spatio-temporally chaotic dynamics. References: 1. Kuramoto and Tsuzuki. Persistent propagation of concentration waves in dissipative media far from thermal equilibrium. Progress in Theoretical Physcs, 55 (1976) pp. 356–369. 2. Sivashinsky. Nonlinear analysis of hydrodynamic instability in laminar flames I. Derivation of basic equations. Acta Astronomica, 4 (1977) pp. 1177–1206. """ from typing import Union, Optional, Sequence, Callable import numpy as np from dapy.models.base import AbstractDiagonalGaussianModel from dapy.models.spatial import SpatiallyExtendedModelMixIn from dapy.integrators.etdrk4 import FourierETDRK4Integrator from dapy.models.transforms import ( OneDimensionalFourierTransformedDiagonalGaussianModelMixIn, fft, real_array_to_rfft_coeff, rfft_coeff_to_real_array, ) class FourierLaminarFlameModel(AbstractDiagonalGaussianModel): """Non-linear SPDE model on a periodic 1D spatial domain for laminar flame fronts. This model class represents the state field by its the Fourier coefficients rather than values of the state field at the spatial mesh points. Based on the Kuramato--Sivashinsky PDE model [1, 2] which exhibits spatio-temporally chaotic dynamics. The governing stochastic partial differential equation (SPDE) is dX = -(∂⁴X/∂s⁴ + ∂²X/∂s² + X * ∂X/∂s + γ * X) dt + κ ⊛ dW where `s` is the spatial coordinate in a periodic domain `[0, S)`, `t` the time coordinate, `X(s, t)` the state field process, `γ` a coefficient controlling the degree of damping in the dynamics, `W(s, t)` a space-time white noise process, `κ(s)` a spatial smoothing kernel and `⊛` indicates circular convolution in the spatial coordinate. Using a spectral spatial discretisation, this corresponds to a non-linear system of stochastic differential equations (SDEs) in the Fourier coefficients X̃ₖ dX̃ₖ = (ωₖ² - ωₖ⁴ - γ) * X̃ₖ + (i * ωₖ / 2) * DFTₖ(IDFT(X̃)²) + κ̃ₖ * dW̃ₖ where `W̃ₖ` is a complex-valued Wiener process, `κ̃ₖ` the kth Fourier coefficient of the smoothing kernel `κ`, `ωₖ = 2 * pi * k / S` the kth spatial frequency and `i` the imaginary unit. A Fourier-domain exponential time-differencing integrator with 4th order Runge-- Kutta updates for non-linear terms [3, 4] is used to integrate the deterministic component of the SDE dynamics and an Euler-Maruyama discretisation used for the Wiener process increment. The smoothing kernel Fourier coefficients are assumed to be κ̃ₖ = σ * exp(-ωₖ² * ℓ²) * √(M / S) where `σ` is a parameter controlling the amplitude and `ℓ` a parameter controlling the length scale. References: 1. Kuramoto and Tsuzuki. Persistent propagation of concentration waves in dissipative media far from thermal equilibrium. Progress in Theoretical Physcs, 55 (1976) pp. 356–369. 2. Sivashinsky. Nonlinear analysis of hydrodynamic instability in laminar flames I. Derivation of basic equations. Acta Astronomica, 4 (1977) pp. 1177–1206. 3. Kassam, Aly-Khan and Trefethen, <NAME>. Fourth-order time-stepping for stiff PDEs. SIAM Journal on Scientific Computing 26.4 (2005): 1214-1233. 4. Cox, <NAME>. and Matthews, <NAME>. Exponential time differencing for stiff systems. Journal of Computational Physics 176.2 (2002): 430-455. """ def __init__( self, dim_state: int = 512, observation_space_indices: Union[slice, Sequence[int]] = slice(4, None, 8), observation_function: Optional[Callable[[np.ndarray, int], np.ndarray]] = None, time_step: float = 0.25, domain_extent: float = 32 * np.pi, damping_coeff: float = 1.0 / 6, observation_noise_std: float = 0.5, initial_state_amplitude: float = 1.0, state_noise_amplitude: float = 1.0, state_noise_length_scale: float = 1.0, num_roots_of_unity_etdrk4_integrator: int = 16, **kwargs ): """ Args: dim_state: Dimension of state which is equivalent here to number of mesh points in spatial discretization. observation_space_indices: Slice or sequence of integers specifying spatial mesh node indices (indices in to state vector) corresponding to observation points. observation_function: Function to apply to subsampled state field to compute mean of observation(s) given state(s) at a given time index. Defaults to identity function in first argument. time_step: Integrator time step. domain_extent: Extent (size) of spatial domain. damping_coeff: Coefficient (`γ` in description above) controlling degree of damping in dynamics. observation_noise_std: Standard deviation of additive Gaussian noise in observations. Either a scalar or array of shape `(dim_observation,)`. Noise in each dimension assumed to be independent i.e. a diagonal noise covariance. initial_state_amplitude: Amplitude scale parameter for initial random state field. Larger values correspond to larger magnitude values for the initial state. state_noise_amplitude: Amplitude scale parameter for additive state noise in model dynamics. Larger values correspond to larger magnitude additive noise in the state field. state_noise_length_scale: Length scale parameter for smoothed noise used to generate initial state and additive state noise fields. Larger values correspond to smoother fields. num_roots_of_unity_etdrk4_integrator: Number of roots of unity to use in approximating contour integrals in exponential time-differencing plus fourth-order Runge Kutta integrator. """ assert dim_state % 2 == 0, "State dimension `dim_state` must be even" self.time_step = time_step self.observation_space_indices = observation_space_indices self.observation_function = observation_function spatial_freqs = np.arange(dim_state // 2 + 1) * 2 * np.pi / domain_extent spatial_freqs_sq = spatial_freqs ** 2 spatial_freqs[dim_state // 2] = 0 state_noise_kernel = ( (time_step) ** 0.5 * state_noise_amplitude * np.exp(-0.5 * spatial_freqs_sq * state_noise_length_scale ** 2) * (dim_state / domain_extent) ** 0.5 ) state_noise_std = rfft_coeff_to_real_array( state_noise_kernel + 1j * state_noise_kernel, False ) initial_state_kernel = ( initial_state_amplitude * np.exp(-0.5 * spatial_freqs_sq * state_noise_length_scale ** 2) * (dim_state / domain_extent) ** 0.5 ) initial_state_std = rfft_coeff_to_real_array( initial_state_kernel + 1j * initial_state_kernel, False ) def linear_operator(freqs, freqs_sq): return freqs_sq - freqs_sq ** 2 - damping_coeff def nonlinear_operator(v, freqs, freqs_sq): return ( -0.5j * freqs * fft.rfft(fft.irfft(v, norm="ortho") ** 2, norm="ortho") ) self.integrator = FourierETDRK4Integrator( linear_operator=linear_operator, nonlinear_operator=nonlinear_operator, num_mesh_point=dim_state, domain_size=domain_extent, time_step=time_step, num_roots_of_unity=num_roots_of_unity_etdrk4_integrator, ) if observation_function is None: dim_observation = np.zeros(dim_state)[observation_space_indices].shape[0] else: dim_observation = observation_function( np.zeros(dim_state)[observation_space_indices], 0 ).shape[0] super().__init__( dim_state=dim_state, dim_observation=dim_observation, initial_state_std=initial_state_std, initial_state_mean=np.zeros(dim_state), state_noise_std=state_noise_std, observation_noise_std=observation_noise_std, **kwargs ) def _next_state_mean(self, states: np.ndarray, t: int) -> np.ndarray: return rfft_coeff_to_real_array( self.integrator.step(real_array_to_rfft_coeff(states)) ) def _observation_mean(self, states: np.ndarray, t: int) -> np.ndarray: subsampled_states = fft.irfft(real_array_to_rfft_coeff(states), norm="ortho")[ ..., self.observation_space_indices ] if self.observation_function is None: return subsampled_states else: return self.observation_function(subsampled_states, t) class SpatialLaminarFlameModel( SpatiallyExtendedModelMixIn, OneDimensionalFourierTransformedDiagonalGaussianModelMixIn, FourierLaminarFlameModel, ): """Non-linear SPDE model on a periodic 1D spatial domain for laminar flame fronts. This model class represents the state field by its values at the spatial mesh points rather than the corresponding Fourier coefficients. For more details see the docstring of `FourierLaminarFlameModel`. """ def __init__( self, dim_state: int = 512, observation_space_indices: Union[slice, Sequence[int]] = slice(4, None, 8), observation_function: Optional[Callable[[np.ndarray, int], np.ndarray]] = None, time_step: float = 0.25, domain_extent: float = 32 * np.pi, damping_coeff: float = 1.0 / 6, observation_noise_std: float = 0.5, initial_state_amplitude: float = 1.0, state_noise_amplitude: float = 1.0, state_noise_length_scale: float = 1.0, num_roots_of_unity_etdrk4_integrator: int = 16, ): """ Args: dim_state: Dimension of state which is equivalent here to number of mesh points in spatial discretization. observation_space_indices: Slice or sequence of integers specifying spatial mesh node indices (indices in to state vector) corresponding to observation points. observation_function: Function to apply to subsampled state field to compute mean of observation(s) given state(s) at a given time index. Defaults to identity function in first argument. time_step: Integrator time step. domain_extent: Extent (size) of spatial domain. damping_coeff: Coefficient (`γ` in description above) controlling degree of damping in dynamics. observation_noise_std: Standard deviation of additive Gaussian noise in observations. Either a scalar or array of shape `(dim_observation,)`. Noise in each dimension assumed to be independent i.e. a diagonal noise covariance. initial_state_amplitude: Amplitude scale parameter for initial random state field. Larger values correspond to larger magnitude values for the initial state. state_noise_amplitude: Amplitude scale parameter for additive state noise in model dynamics. Larger values correspond to larger magnitude additive noise in the state field. state_noise_length_scale: Length scale parameter for smoothed noise used to generate initial state and additive state noise fields. Larger values correspond to smoother fields. num_roots_of_unity_etdrk4_integrator: Number of roots of unity to use in approximating contour integrals in exponential time-differencing plus fourth-order Runge Kutta integrator. """ super().__init__( dim_state=dim_state, observation_space_indices=observation_space_indices, observation_function=observation_function, time_step=time_step, domain_extent=domain_extent, damping_coeff=damping_coeff, observation_noise_std=observation_noise_std, initial_state_amplitude=initial_state_amplitude, state_noise_amplitude=state_noise_amplitude, state_noise_length_scale=state_noise_length_scale, num_roots_of_unity_etdrk4_integrator=num_roots_of_unity_etdrk4_integrator, mesh_shape=(dim_state,), domain_extents=(domain_extent,), domain_is_periodic=True, observation_node_indices=observation_space_indices, )
[ "dapy.models.transforms.fft.irfft", "dapy.models.transforms.rfft_coeff_to_real_array", "numpy.exp", "dapy.integrators.etdrk4.FourierETDRK4Integrator", "numpy.zeros", "dapy.models.transforms.real_array_to_rfft_coeff", "numpy.arange" ]
[((6910, 6989), 'dapy.models.transforms.rfft_coeff_to_real_array', 'rfft_coeff_to_real_array', (['(state_noise_kernel + 1.0j * state_noise_kernel)', '(False)'], {}), '(state_noise_kernel + 1.0j * state_noise_kernel, False)\n', (6934, 6989), False, 'from dapy.models.transforms import OneDimensionalFourierTransformedDiagonalGaussianModelMixIn, fft, real_array_to_rfft_coeff, rfft_coeff_to_real_array\n'), ((7244, 7331), 'dapy.models.transforms.rfft_coeff_to_real_array', 'rfft_coeff_to_real_array', (['(initial_state_kernel + 1.0j * initial_state_kernel)', '(False)'], {}), '(initial_state_kernel + 1.0j * initial_state_kernel,\n False)\n', (7268, 7331), False, 'from dapy.models.transforms import OneDimensionalFourierTransformedDiagonalGaussianModelMixIn, fft, real_array_to_rfft_coeff, rfft_coeff_to_real_array\n'), ((7658, 7899), 'dapy.integrators.etdrk4.FourierETDRK4Integrator', 'FourierETDRK4Integrator', ([], {'linear_operator': 'linear_operator', 'nonlinear_operator': 'nonlinear_operator', 'num_mesh_point': 'dim_state', 'domain_size': 'domain_extent', 'time_step': 'time_step', 'num_roots_of_unity': 'num_roots_of_unity_etdrk4_integrator'}), '(linear_operator=linear_operator, nonlinear_operator\n =nonlinear_operator, num_mesh_point=dim_state, domain_size=\n domain_extent, time_step=time_step, num_roots_of_unity=\n num_roots_of_unity_etdrk4_integrator)\n', (7681, 7899), False, 'from dapy.integrators.etdrk4 import FourierETDRK4Integrator\n'), ((6761, 6824), 'numpy.exp', 'np.exp', (['(-0.5 * spatial_freqs_sq * state_noise_length_scale ** 2)'], {}), '(-0.5 * spatial_freqs_sq * state_noise_length_scale ** 2)\n', (6767, 6824), True, 'import numpy as np\n'), ((7093, 7156), 'numpy.exp', 'np.exp', (['(-0.5 * spatial_freqs_sq * state_noise_length_scale ** 2)'], {}), '(-0.5 * spatial_freqs_sq * state_noise_length_scale ** 2)\n', (7099, 7156), True, 'import numpy as np\n'), ((8434, 8453), 'numpy.zeros', 'np.zeros', (['dim_state'], {}), '(dim_state)\n', (8442, 8453), True, 'import numpy as np\n'), ((8737, 8769), 'dapy.models.transforms.real_array_to_rfft_coeff', 'real_array_to_rfft_coeff', (['states'], {}), '(states)\n', (8761, 8769), False, 'from dapy.models.transforms import OneDimensionalFourierTransformedDiagonalGaussianModelMixIn, fft, real_array_to_rfft_coeff, rfft_coeff_to_real_array\n'), ((8895, 8927), 'dapy.models.transforms.real_array_to_rfft_coeff', 'real_array_to_rfft_coeff', (['states'], {}), '(states)\n', (8919, 8927), False, 'from dapy.models.transforms import OneDimensionalFourierTransformedDiagonalGaussianModelMixIn, fft, real_array_to_rfft_coeff, rfft_coeff_to_real_array\n'), ((6503, 6532), 'numpy.arange', 'np.arange', (['(dim_state // 2 + 1)'], {}), '(dim_state // 2 + 1)\n', (6512, 6532), True, 'import numpy as np\n'), ((7570, 7596), 'dapy.models.transforms.fft.irfft', 'fft.irfft', (['v'], {'norm': '"""ortho"""'}), "(v, norm='ortho')\n", (7579, 7596), False, 'from dapy.models.transforms import OneDimensionalFourierTransformedDiagonalGaussianModelMixIn, fft, real_array_to_rfft_coeff, rfft_coeff_to_real_array\n'), ((8039, 8058), 'numpy.zeros', 'np.zeros', (['dim_state'], {}), '(dim_state)\n', (8047, 8058), True, 'import numpy as np\n'), ((8177, 8196), 'numpy.zeros', 'np.zeros', (['dim_state'], {}), '(dim_state)\n', (8185, 8196), True, 'import numpy as np\n')]
import matplotlib.pyplot as plt import numpy as np import sys sys.path.append('../../../software/models/') import dftModel as DFT import math k0 = 8.5 N = 64 w = np.ones(N) x = np.cos(2*np.pi*k0/N*np.arange(-N/2,N/2)) mX, pX = DFT.dftAnal(x, w, N) y = DFT.dftSynth(mX, pX, N) plt.figure(1, figsize=(9.5, 5)) plt.subplot(311) plt.title('positive freq. magnitude spectrum in dB: mX') plt.plot(np.arange(mX.size), mX, 'r', lw=1.5) plt.axis([0,mX.size, min(mX), max(mX)+1]) plt.subplot(312) plt.title('positive freq. phase spectrum: pX') plt.plot(np.arange(pX.size), pX, 'c', lw=1.5) plt.axis([0, pX.size,-np.pi,np.pi]) plt.subplot(313) plt.title('inverse spectrum: IDFT(X)') plt.plot(np.arange(-N/2, N/2), y,'b', lw=1.5) plt.axis([-N/2,N/2-1,min(y), max(y)]) plt.tight_layout() plt.savefig('idft.png') plt.show()
[ "matplotlib.pyplot.savefig", "numpy.ones", "numpy.arange", "matplotlib.pyplot.axis", "matplotlib.pyplot.subplot", "matplotlib.pyplot.figure", "dftModel.dftAnal", "matplotlib.pyplot.tight_layout", "matplotlib.pyplot.title", "sys.path.append", "dftModel.dftSynth", "matplotlib.pyplot.show" ]
[((63, 107), 'sys.path.append', 'sys.path.append', (['"""../../../software/models/"""'], {}), "('../../../software/models/')\n", (78, 107), False, 'import sys\n'), ((164, 174), 'numpy.ones', 'np.ones', (['N'], {}), '(N)\n', (171, 174), True, 'import numpy as np\n'), ((229, 249), 'dftModel.dftAnal', 'DFT.dftAnal', (['x', 'w', 'N'], {}), '(x, w, N)\n', (240, 249), True, 'import dftModel as DFT\n'), ((254, 277), 'dftModel.dftSynth', 'DFT.dftSynth', (['mX', 'pX', 'N'], {}), '(mX, pX, N)\n', (266, 277), True, 'import dftModel as DFT\n'), ((279, 310), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)'], {'figsize': '(9.5, 5)'}), '(1, figsize=(9.5, 5))\n', (289, 310), True, 'import matplotlib.pyplot as plt\n'), ((311, 327), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(311)'], {}), '(311)\n', (322, 327), True, 'import matplotlib.pyplot as plt\n'), ((328, 384), 'matplotlib.pyplot.title', 'plt.title', (['"""positive freq. magnitude spectrum in dB: mX"""'], {}), "('positive freq. magnitude spectrum in dB: mX')\n", (337, 384), True, 'import matplotlib.pyplot as plt\n'), ((474, 490), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(312)'], {}), '(312)\n', (485, 490), True, 'import matplotlib.pyplot as plt\n'), ((491, 537), 'matplotlib.pyplot.title', 'plt.title', (['"""positive freq. phase spectrum: pX"""'], {}), "('positive freq. phase spectrum: pX')\n", (500, 537), True, 'import matplotlib.pyplot as plt\n'), ((584, 621), 'matplotlib.pyplot.axis', 'plt.axis', (['[0, pX.size, -np.pi, np.pi]'], {}), '([0, pX.size, -np.pi, np.pi])\n', (592, 621), True, 'import matplotlib.pyplot as plt\n'), ((621, 637), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(313)'], {}), '(313)\n', (632, 637), True, 'import matplotlib.pyplot as plt\n'), ((638, 676), 'matplotlib.pyplot.title', 'plt.title', (['"""inverse spectrum: IDFT(X)"""'], {}), "('inverse spectrum: IDFT(X)')\n", (647, 676), True, 'import matplotlib.pyplot as plt\n'), ((762, 780), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (778, 780), True, 'import matplotlib.pyplot as plt\n'), ((781, 804), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""idft.png"""'], {}), "('idft.png')\n", (792, 804), True, 'import matplotlib.pyplot as plt\n'), ((805, 815), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (813, 815), True, 'import matplotlib.pyplot as plt\n'), ((394, 412), 'numpy.arange', 'np.arange', (['mX.size'], {}), '(mX.size)\n', (403, 412), True, 'import numpy as np\n'), ((547, 565), 'numpy.arange', 'np.arange', (['pX.size'], {}), '(pX.size)\n', (556, 565), True, 'import numpy as np\n'), ((686, 710), 'numpy.arange', 'np.arange', (['(-N / 2)', '(N / 2)'], {}), '(-N / 2, N / 2)\n', (695, 710), True, 'import numpy as np\n'), ((199, 223), 'numpy.arange', 'np.arange', (['(-N / 2)', '(N / 2)'], {}), '(-N / 2, N / 2)\n', (208, 223), True, 'import numpy as np\n')]
import pytest import numpy as np from fanok.selection import adaptive_significance_threshold @pytest.mark.parametrize( "w, q, offset, expected", [ ([1, 2, 3, 4, 5], 0.1, 0, 1), ([-1, 2, -3, 4, 5], 0.1, 0, 4), ([-3, -2, -1, 0, 1, 2, 3], 0.1, 0, np.inf), ([-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 0.1, 0, 4), ([-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 0.15, 0, 3), ( [-1.52, 1.93, -0.76, -0.35, 1.21, -0.39, 0.08, -1.45, 0.31, -1.38], 0.1, 0, 1.93, ), ], ) def test_adaptive_significance_threshold(w, q, offset, expected): w = np.array(w) threshold = adaptive_significance_threshold(w, q, offset=offset) assert threshold == expected
[ "fanok.selection.adaptive_significance_threshold", "pytest.mark.parametrize", "numpy.array" ]
[((98, 480), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""w, q, offset, expected"""', '[([1, 2, 3, 4, 5], 0.1, 0, 1), ([-1, 2, -3, 4, 5], 0.1, 0, 4), ([-3, -2, -1,\n 0, 1, 2, 3], 0.1, 0, np.inf), ([-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, \n 9, 10], 0.1, 0, 4), ([-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], \n 0.15, 0, 3), ([-1.52, 1.93, -0.76, -0.35, 1.21, -0.39, 0.08, -1.45, \n 0.31, -1.38], 0.1, 0, 1.93)]'], {}), "('w, q, offset, expected', [([1, 2, 3, 4, 5], 0.1, 0,\n 1), ([-1, 2, -3, 4, 5], 0.1, 0, 4), ([-3, -2, -1, 0, 1, 2, 3], 0.1, 0,\n np.inf), ([-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 0.1, 0, 4), (\n [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 0.15, 0, 3), ([-1.52, \n 1.93, -0.76, -0.35, 1.21, -0.39, 0.08, -1.45, 0.31, -1.38], 0.1, 0, 1.93)])\n", (121, 480), False, 'import pytest\n'), ((662, 673), 'numpy.array', 'np.array', (['w'], {}), '(w)\n', (670, 673), True, 'import numpy as np\n'), ((690, 742), 'fanok.selection.adaptive_significance_threshold', 'adaptive_significance_threshold', (['w', 'q'], {'offset': 'offset'}), '(w, q, offset=offset)\n', (721, 742), False, 'from fanok.selection import adaptive_significance_threshold\n')]
# Copyright 2019 <NAME> # License: Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) import math import numpy as np import torch as th import torch.nn as nn import torch.nn.functional as tf import librosa.filters as filters from aps.const import EPSILON from typing import Optional, Union, Tuple def init_window(wnd: str, frame_len: int) -> th.Tensor: """ Return window coefficient Args: wnd: window name frame_len: length of the frame """ def sqrthann(frame_len, periodic=True): return th.hann_window(frame_len, periodic=periodic)**0.5 if wnd not in ["bartlett", "hann", "hamm", "blackman", "rect", "sqrthann"]: raise RuntimeError(f"Unknown window type: {wnd}") wnd_tpl = { "sqrthann": sqrthann, "hann": th.hann_window, "hamm": th.hamming_window, "blackman": th.blackman_window, "bartlett": th.bartlett_window, "rect": th.ones } if wnd != "rect": # match with librosa c = wnd_tpl[wnd](frame_len, periodic=True) else: c = wnd_tpl[wnd](frame_len) return c def init_kernel(frame_len: int, frame_hop: int, window: str, round_pow_of_two: bool = True, normalized: bool = False, inverse: bool = False, mode: str = "librosa") -> th.Tensor: """ Return STFT kernels Args: frame_len: length of the frame frame_hop: hop size between frames window: window name round_pow_of_two: if true, choose round(#power_of_two) as the FFT size normalized: return normalized DFT matrix inverse: return iDFT matrix mode: framing mode (librosa or kaldi) """ if mode not in ["librosa", "kaldi"]: raise ValueError(f"Unsupported mode: {mode}") # FFT points B = 2**math.ceil(math.log2(frame_len)) if round_pow_of_two else frame_len # center padding window if needed if mode == "librosa" and B != frame_len: lpad = (B - frame_len) // 2 window = tf.pad(window, (lpad, B - frame_len - lpad)) if normalized: # make K^H * K = I S = B**0.5 else: S = 1 I = th.stack([th.eye(B), th.zeros(B, B)], dim=-1) # W x B x 2 K = th.fft(I / S, 1) if mode == "kaldi": K = K[:frame_len] if inverse and not normalized: # to make K^H * K = I K = K / B # 2 x B x W K = th.transpose(K, 0, 2) * window # 2B x 1 x W K = th.reshape(K, (B * 2, 1, K.shape[-1])) return K, window def mel_filter(frame_len: int, round_pow_of_two: bool = True, num_bins: Optional[int] = None, sr: int = 16000, num_mels: int = 80, fmin: float = 0.0, fmax: Optional[float] = None, norm: bool = False) -> th.Tensor: """ Return mel filter coefficients Args: frame_len: length of the frame round_pow_of_two: if true, choose round(#power_of_two) as the FFT size num_bins: number of the frequency bins produced by STFT num_mels: number of the mel bands fmin: lowest frequency (in Hz) fmax: highest frequency (in Hz) norm: normalize the mel filter coefficients """ # FFT points if num_bins is None: N = 2**math.ceil( math.log2(frame_len)) if round_pow_of_two else frame_len else: N = (num_bins - 1) * 2 # fmin & fmax freq_upper = sr // 2 if fmax is None: fmax = freq_upper else: fmax = min(fmax + freq_upper if fmax < 0 else fmax, freq_upper) fmin = max(0, fmin) # mel filter coefficients mel = filters.mel(sr, N, n_mels=num_mels, fmax=fmax, fmin=fmin, htk=True, norm="slaney" if norm else None) # num_mels x (N // 2 + 1) return th.tensor(mel, dtype=th.float32) def speed_perturb_filter(src_sr: int, dst_sr: int, cutoff_ratio: float = 0.95, num_zeros: int = 64) -> th.Tensor: """ Return speed perturb filters, reference: https://github.com/danpovey/filtering/blob/master/lilfilter/resampler.py Args: src_sr: sample rate of the source signal dst_sr: sample rate of the target signal Return: weight (Tensor): coefficients of the filter """ if src_sr == dst_sr: raise ValueError( f"src_sr should not be equal to dst_sr: {src_sr}/{dst_sr}") gcd = math.gcd(src_sr, dst_sr) src_sr = src_sr // gcd dst_sr = dst_sr // gcd if src_sr == 1 or dst_sr == 1: raise ValueError("do not support integer downsample/upsample") zeros_per_block = min(src_sr, dst_sr) * cutoff_ratio padding = 1 + int(num_zeros / zeros_per_block) # dst_sr x src_sr x K times = (np.arange(dst_sr)[:, None, None] / float(dst_sr) - np.arange(src_sr)[None, :, None] / float(src_sr) - np.arange(2 * padding + 1)[None, None, :] + padding) window = np.heaviside(1 - np.abs(times / padding), 0.0) * (0.5 + 0.5 * np.cos(times / padding * math.pi)) weight = np.sinc( times * zeros_per_block) * window * zeros_per_block / float(src_sr) return th.tensor(weight, dtype=th.float32) def splice_feature(feats: th.Tensor, lctx: int = 1, rctx: int = 1, subsampling_factor: int = 1, op: str = "cat") -> th.Tensor: """ Splice feature Args: feats (Tensor): N x ... x T x F, original feature lctx: left context rctx: right context subsampling_factor: subsampling factor op: operator on feature context Return: splice (Tensor): feature with context padded """ if lctx + rctx == 0: return feats if op not in ["cat", "stack"]: raise ValueError(f"Unknown op for feature splicing: {op}") # [N x ... x T x F, ...] ctx = [] T = feats.shape[-2] T = T - T % subsampling_factor for c in range(-lctx, rctx + 1): idx = th.arange(c, c + T, device=feats.device, dtype=th.int64) idx = th.clamp(idx, min=0, max=T - 1) ctx.append(th.index_select(feats, -2, idx)) if op == "cat": # N x ... x T x FD splice = th.cat(ctx, -1) else: # N x ... x T x F x D splice = th.stack(ctx, -1) return splice def _forward_stft( wav: th.Tensor, kernel: th.Tensor, output: str = "polar", pre_emphasis: float = 0, frame_hop: int = 256, onesided: bool = False, center: bool = False) -> Union[th.Tensor, Tuple[th.Tensor, th.Tensor]]: """ STFT inner function Args: wav (Tensor), N x (C) x S kernel (Tensor), STFT transform kernels, from init_kernel(...) output (str), output format: polar: return (magnitude, phase) pair complex: return (real, imag) pair real: return [real; imag] Tensor frame_hop: frame hop size in number samples pre_emphasis: factor of preemphasis onesided: return half FFT bins center: if true, we assumed to have centered frames Return: transform (Tensor or [Tensor, Tensor]), STFT transform results """ wav_dim = wav.dim() if output not in ["polar", "complex", "real"]: raise ValueError(f"Unknown output format: {output}") if wav_dim not in [2, 3]: raise RuntimeError(f"STFT expect 2D/3D tensor, but got {wav_dim:d}D") # if N x S, reshape N x 1 x S # else: reshape NC x 1 x S N, S = wav.shape[0], wav.shape[-1] wav = wav.view(-1, 1, S) # NC x 1 x S+2P if center: pad = kernel.shape[-1] // 2 # NOTE: match with librosa wav = tf.pad(wav, (pad, pad), mode="reflect") # STFT if pre_emphasis > 0: # NC x W x T frames = tf.unfold(wav[:, None], (1, kernel.shape[-1]), stride=frame_hop, padding=0) frames[:, 1:] = frames[:, 1:] - pre_emphasis * frames[:, :-1] # 1 x 2B x W, NC x W x T, NC x 2B x T packed = th.matmul(kernel[:, 0][None, ...], frames) else: packed = tf.conv1d(wav, kernel, stride=frame_hop, padding=0) # NC x 2B x T => N x C x 2B x T if wav_dim == 3: packed = packed.view(N, -1, packed.shape[-2], packed.shape[-1]) # N x (C) x B x T real, imag = th.chunk(packed, 2, dim=-2) # N x (C) x B/2+1 x T if onesided: num_bins = kernel.shape[0] // 4 + 1 real = real[..., :num_bins, :] imag = imag[..., :num_bins, :] if output == "complex": return (real, imag) elif output == "real": return th.stack([real, imag], dim=-1) else: mag = (real**2 + imag**2 + EPSILON)**0.5 pha = th.atan2(imag, real) return (mag, pha) def _inverse_stft(transform: Union[th.Tensor, Tuple[th.Tensor, th.Tensor]], kernel: th.Tensor, window: th.Tensor, input: str = "polar", frame_hop: int = 256, onesided: bool = False, center: bool = False) -> th.Tensor: """ iSTFT inner function Args: transform (Tensor or [Tensor, Tensor]), STFT transform results kernel (Tensor), STFT transform kernels, from init_kernel(...) input (str), input format: polar: return (magnitude, phase) pair complex: return (real, imag) pair real: return [real; imag] Tensor frame_hop: frame hop size in number samples onesided: return half FFT bins center: used in _forward_stft Return: wav (Tensor), N x S """ if input not in ["polar", "complex", "real"]: raise ValueError(f"Unknown output format: {input}") if input == "real": real, imag = transform[..., 0], transform[..., 1] elif input == "polar": real = transform[0] * th.cos(transform[1]) imag = transform[0] * th.sin(transform[1]) else: real, imag = transform # (N) x F x T imag_dim = imag.dim() if imag_dim not in [2, 3]: raise RuntimeError(f"Expect 2D/3D tensor, but got {imag_dim}D") # if F x T, reshape 1 x F x T if imag_dim == 2: real = th.unsqueeze(real, 0) imag = th.unsqueeze(imag, 0) if onesided: # [self.num_bins - 2, ..., 1] reverse = range(kernel.shape[0] // 4 - 1, 0, -1) # extend matrix: N x B x T real = th.cat([real, real[:, reverse]], 1) imag = th.cat([imag, -imag[:, reverse]], 1) # pack: N x 2B x T packed = th.cat([real, imag], dim=1) # N x 1 x T s = tf.conv_transpose1d(packed, kernel, stride=frame_hop, padding=0) # normalized audio samples # refer: https://github.com/pytorch/audio/blob/2ebbbf511fb1e6c47b59fd32ad7e66023fa0dff1/torchaudio/functional.py#L171 # 1 x W x T win = th.repeat_interleave(window[None, ..., None], packed.shape[-1], dim=-1) # W x 1 x W I = th.eye(window.shape[0], device=win.device)[:, None] # 1 x 1 x T norm = tf.conv_transpose1d(win**2, I, stride=frame_hop, padding=0) if center: pad = kernel.shape[-1] // 2 s = s[..., pad:-pad] norm = norm[..., pad:-pad] s = s / (norm + EPSILON) # N x S s = s.squeeze(1) return s def forward_stft( wav: th.Tensor, frame_len: int, frame_hop: int, output: str = "complex", window: str = "sqrthann", round_pow_of_two: bool = True, pre_emphasis: float = 0, normalized: bool = False, onesided: bool = True, center: bool = False, mode: str = "librosa") -> Union[th.Tensor, Tuple[th.Tensor, th.Tensor]]: """ STFT function implementation, equals to STFT layer Args: wav: source audio signal frame_len: length of the frame frame_hop: hop size between frames output: output type (complex, real, polar) window: window name center: center flag (similar with that in librosa.stft) round_pow_of_two: if true, choose round(#power_of_two) as the FFT size pre_emphasis: factor of preemphasis normalized: use normalized DFT kernel onesided: output onesided STFT inverse: using iDFT kernel (for iSTFT) mode: "kaldi"|"librosa", slight difference on applying window function """ K, _ = init_kernel(frame_len, frame_hop, init_window(window, frame_len), round_pow_of_two=round_pow_of_two, normalized=normalized, inverse=False, mode=mode) return _forward_stft(wav, K.to(wav.device), output=output, frame_hop=frame_hop, pre_emphasis=pre_emphasis, onesided=onesided, center=center) def inverse_stft(transform: Union[th.Tensor, Tuple[th.Tensor, th.Tensor]], frame_len: int, frame_hop: int, input: str = "complex", window: str = "sqrthann", round_pow_of_two: bool = True, normalized: bool = False, onesided: bool = True, center: bool = False, mode: str = "librosa") -> th.Tensor: """ iSTFT function implementation, equals to iSTFT layer Args: transform: results of STFT frame_len: length of the frame frame_hop: hop size between frames input: input format (complex, real, polar) window: window name center: center flag (similar with that in librosa.stft) round_pow_of_two: if true, choose round(#power_of_two) as the FFT size normalized: use normalized DFT kernel onesided: output onesided STFT mode: "kaldi"|"librosa", slight difference on applying window function """ if isinstance(transform, th.Tensor): device = transform.device else: device = transform[0].device K, w = init_kernel(frame_len, frame_hop, init_window(window, frame_len), round_pow_of_two=round_pow_of_two, normalized=normalized, inverse=True, mode=mode) return _inverse_stft(transform, K.to(device), w.to(device), input=input, frame_hop=frame_hop, onesided=onesided, center=center) class STFTBase(nn.Module): """ Base layer for (i)STFT Args: frame_len: length of the frame frame_hop: hop size between frames window: window name center: center flag (similar with that in librosa.stft) round_pow_of_two: if true, choose round(#power_of_two) as the FFT size normalized: use normalized DFT kernel pre_emphasis: factor of preemphasis mode: "kaldi"|"librosa", slight difference on applying window function onesided: output onesided STFT inverse: using iDFT kernel (for iSTFT) """ def __init__(self, frame_len: int, frame_hop: int, window: str = "sqrthann", round_pow_of_two: bool = True, normalized: bool = False, pre_emphasis: float = 0, onesided: bool = True, inverse: bool = False, center: bool = False, mode="librosa") -> None: super(STFTBase, self).__init__() K, w = init_kernel(frame_len, frame_hop, init_window(window, frame_len), round_pow_of_two=round_pow_of_two, normalized=normalized, inverse=inverse, mode=mode) self.K = nn.Parameter(K, requires_grad=False) self.w = nn.Parameter(w, requires_grad=False) self.frame_len = frame_len self.frame_hop = frame_hop self.onesided = onesided self.pre_emphasis = pre_emphasis self.center = center self.mode = mode self.num_bins = self.K.shape[0] // 4 + 1 self.expr = ( f"window={window}, stride={frame_hop}, onesided={onesided}, " + f"pre_emphasis={self.pre_emphasis}, normalized={normalized}, " + f"center={self.center}, mode={self.mode}, " + f"kernel_size={self.num_bins}x{self.K.shape[2]}") def num_frames(self, wav_len: th.Tensor) -> th.Tensor: """ Compute number of the frames """ if th.sum(wav_len <= self.frame_len): raise RuntimeError( f"Audio samples less than frame_len ({self.frame_len})") kernel_size = self.K.shape[-1] if self.center: wav_len += kernel_size return (wav_len - kernel_size) // self.frame_hop + 1 def extra_repr(self) -> str: return self.expr class STFT(STFTBase): """ Short-time Fourier Transform as a Layer """ def __init__(self, *args, **kwargs): super(STFT, self).__init__(*args, inverse=False, **kwargs) def forward( self, wav: th.Tensor, output: str = "polar" ) -> Union[th.Tensor, Tuple[th.Tensor, th.Tensor]]: """ Accept (single or multiple channel) raw waveform and output magnitude and phase Args wav (Tensor) input signal, N x (C) x S Return transform (Tensor or [Tensor, Tensor]), N x (C) x F x T """ return _forward_stft(wav, self.K, output=output, frame_hop=self.frame_hop, pre_emphasis=self.pre_emphasis, onesided=self.onesided, center=self.center) class iSTFT(STFTBase): """ Inverse Short-time Fourier Transform as a Layer """ def __init__(self, *args, **kwargs): super(iSTFT, self).__init__(*args, inverse=True, **kwargs) def forward(self, transform: Union[th.Tensor, Tuple[th.Tensor, th.Tensor]], input: str = "polar") -> th.Tensor: """ Accept phase & magnitude and output raw waveform Args transform (Tensor or [Tensor, Tensor]), STFT output Return s (Tensor), N x S """ return _inverse_stft(transform, self.K, self.w, input=input, frame_hop=self.frame_hop, onesided=self.onesided, center=self.center)
[ "torch.nn.functional.conv1d", "math.log2", "torch.hann_window", "torch.sin", "torch.cos", "torch.sum", "torch.nn.functional.pad", "torch.repeat_interleave", "torch.arange", "numpy.arange", "math.gcd", "torch.unsqueeze", "torch.eye", "torch.matmul", "numpy.abs", "torch.transpose", "librosa.filters.mel", "numpy.cos", "torch.reshape", "torch.clamp", "torch.cat", "torch.index_select", "torch.stack", "torch.atan2", "numpy.sinc", "torch.fft", "torch.tensor", "torch.chunk", "torch.nn.Parameter", "torch.nn.functional.conv_transpose1d", "torch.zeros", "torch.nn.functional.unfold" ]
[((2301, 2317), 'torch.fft', 'th.fft', (['(I / S)', '(1)'], {}), '(I / S, 1)\n', (2307, 2317), True, 'import torch as th\n'), ((2531, 2569), 'torch.reshape', 'th.reshape', (['K', '(B * 2, 1, K.shape[-1])'], {}), '(K, (B * 2, 1, K.shape[-1]))\n', (2541, 2569), True, 'import torch as th\n'), ((3742, 3847), 'librosa.filters.mel', 'filters.mel', (['sr', 'N'], {'n_mels': 'num_mels', 'fmax': 'fmax', 'fmin': 'fmin', 'htk': '(True)', 'norm': "('slaney' if norm else None)"}), "(sr, N, n_mels=num_mels, fmax=fmax, fmin=fmin, htk=True, norm=\n 'slaney' if norm else None)\n", (3753, 3847), True, 'import librosa.filters as filters\n'), ((4016, 4048), 'torch.tensor', 'th.tensor', (['mel'], {'dtype': 'th.float32'}), '(mel, dtype=th.float32)\n', (4025, 4048), True, 'import torch as th\n'), ((4687, 4711), 'math.gcd', 'math.gcd', (['src_sr', 'dst_sr'], {}), '(src_sr, dst_sr)\n', (4695, 4711), False, 'import math\n'), ((5445, 5480), 'torch.tensor', 'th.tensor', (['weight'], {'dtype': 'th.float32'}), '(weight, dtype=th.float32)\n', (5454, 5480), True, 'import torch as th\n'), ((8678, 8705), 'torch.chunk', 'th.chunk', (['packed', '(2)'], {'dim': '(-2)'}), '(packed, 2, dim=-2)\n', (8686, 8705), True, 'import torch as th\n'), ((10915, 10942), 'torch.cat', 'th.cat', (['[real, imag]'], {'dim': '(1)'}), '([real, imag], dim=1)\n', (10921, 10942), True, 'import torch as th\n'), ((10967, 11031), 'torch.nn.functional.conv_transpose1d', 'tf.conv_transpose1d', (['packed', 'kernel'], {'stride': 'frame_hop', 'padding': '(0)'}), '(packed, kernel, stride=frame_hop, padding=0)\n', (10986, 11031), True, 'import torch.nn.functional as tf\n'), ((11211, 11282), 'torch.repeat_interleave', 'th.repeat_interleave', (['window[None, ..., None]', 'packed.shape[-1]'], {'dim': '(-1)'}), '(window[None, ..., None], packed.shape[-1], dim=-1)\n', (11231, 11282), True, 'import torch as th\n'), ((11448, 11509), 'torch.nn.functional.conv_transpose1d', 'tf.conv_transpose1d', (['(win ** 2)', 'I'], {'stride': 'frame_hop', 'padding': '(0)'}), '(win ** 2, I, stride=frame_hop, padding=0)\n', (11467, 11509), True, 'import torch.nn.functional as tf\n'), ((2089, 2133), 'torch.nn.functional.pad', 'tf.pad', (['window', '(lpad, B - frame_len - lpad)'], {}), '(window, (lpad, B - frame_len - lpad))\n', (2095, 2133), True, 'import torch.nn.functional as tf\n'), ((2475, 2496), 'torch.transpose', 'th.transpose', (['K', '(0)', '(2)'], {}), '(K, 0, 2)\n', (2487, 2496), True, 'import torch as th\n'), ((6296, 6352), 'torch.arange', 'th.arange', (['c', '(c + T)'], {'device': 'feats.device', 'dtype': 'th.int64'}), '(c, c + T, device=feats.device, dtype=th.int64)\n', (6305, 6352), True, 'import torch as th\n'), ((6367, 6398), 'torch.clamp', 'th.clamp', (['idx'], {'min': '(0)', 'max': '(T - 1)'}), '(idx, min=0, max=T - 1)\n', (6375, 6398), True, 'import torch as th\n'), ((6515, 6530), 'torch.cat', 'th.cat', (['ctx', '(-1)'], {}), '(ctx, -1)\n', (6521, 6530), True, 'import torch as th\n'), ((6588, 6605), 'torch.stack', 'th.stack', (['ctx', '(-1)'], {}), '(ctx, -1)\n', (6596, 6605), True, 'import torch as th\n'), ((8010, 8049), 'torch.nn.functional.pad', 'tf.pad', (['wav', '(pad, pad)'], {'mode': '"""reflect"""'}), "(wav, (pad, pad), mode='reflect')\n", (8016, 8049), True, 'import torch.nn.functional as tf\n'), ((8124, 8199), 'torch.nn.functional.unfold', 'tf.unfold', (['wav[:, None]', '(1, kernel.shape[-1])'], {'stride': 'frame_hop', 'padding': '(0)'}), '(wav[:, None], (1, kernel.shape[-1]), stride=frame_hop, padding=0)\n', (8133, 8199), True, 'import torch.nn.functional as tf\n'), ((8388, 8430), 'torch.matmul', 'th.matmul', (['kernel[:, 0][None, ...]', 'frames'], {}), '(kernel[:, 0][None, ...], frames)\n', (8397, 8430), True, 'import torch as th\n'), ((8458, 8509), 'torch.nn.functional.conv1d', 'tf.conv1d', (['wav', 'kernel'], {'stride': 'frame_hop', 'padding': '(0)'}), '(wav, kernel, stride=frame_hop, padding=0)\n', (8467, 8509), True, 'import torch.nn.functional as tf\n'), ((10569, 10590), 'torch.unsqueeze', 'th.unsqueeze', (['real', '(0)'], {}), '(real, 0)\n', (10581, 10590), True, 'import torch as th\n'), ((10606, 10627), 'torch.unsqueeze', 'th.unsqueeze', (['imag', '(0)'], {}), '(imag, 0)\n', (10618, 10627), True, 'import torch as th\n'), ((10791, 10826), 'torch.cat', 'th.cat', (['[real, real[:, reverse]]', '(1)'], {}), '([real, real[:, reverse]], 1)\n', (10797, 10826), True, 'import torch as th\n'), ((10842, 10878), 'torch.cat', 'th.cat', (['[imag, -imag[:, reverse]]', '(1)'], {}), '([imag, -imag[:, reverse]], 1)\n', (10848, 10878), True, 'import torch as th\n'), ((11369, 11411), 'torch.eye', 'th.eye', (['window.shape[0]'], {'device': 'win.device'}), '(window.shape[0], device=win.device)\n', (11375, 11411), True, 'import torch as th\n'), ((16516, 16552), 'torch.nn.Parameter', 'nn.Parameter', (['K'], {'requires_grad': '(False)'}), '(K, requires_grad=False)\n', (16528, 16552), True, 'import torch.nn as nn\n'), ((16570, 16606), 'torch.nn.Parameter', 'nn.Parameter', (['w'], {'requires_grad': '(False)'}), '(w, requires_grad=False)\n', (16582, 16606), True, 'import torch.nn as nn\n'), ((17281, 17314), 'torch.sum', 'th.sum', (['(wav_len <= self.frame_len)'], {}), '(wav_len <= self.frame_len)\n', (17287, 17314), True, 'import torch as th\n'), ((543, 587), 'torch.hann_window', 'th.hann_window', (['frame_len'], {'periodic': 'periodic'}), '(frame_len, periodic=periodic)\n', (557, 587), True, 'import torch as th\n'), ((2241, 2250), 'torch.eye', 'th.eye', (['B'], {}), '(B)\n', (2247, 2250), True, 'import torch as th\n'), ((2252, 2266), 'torch.zeros', 'th.zeros', (['B', 'B'], {}), '(B, B)\n', (2260, 2266), True, 'import torch as th\n'), ((6418, 6449), 'torch.index_select', 'th.index_select', (['feats', '(-2)', 'idx'], {}), '(feats, -2, idx)\n', (6433, 6449), True, 'import torch as th\n'), ((8969, 8999), 'torch.stack', 'th.stack', (['[real, imag]'], {'dim': '(-1)'}), '([real, imag], dim=-1)\n', (8977, 8999), True, 'import torch as th\n'), ((9073, 9093), 'torch.atan2', 'th.atan2', (['imag', 'real'], {}), '(imag, real)\n', (9081, 9093), True, 'import torch as th\n'), ((1896, 1916), 'math.log2', 'math.log2', (['frame_len'], {}), '(frame_len)\n', (1905, 1916), False, 'import math\n'), ((5147, 5173), 'numpy.arange', 'np.arange', (['(2 * padding + 1)'], {}), '(2 * padding + 1)\n', (5156, 5173), True, 'import numpy as np\n'), ((5230, 5253), 'numpy.abs', 'np.abs', (['(times / padding)'], {}), '(times / padding)\n', (5236, 5253), True, 'import numpy as np\n'), ((5301, 5334), 'numpy.cos', 'np.cos', (['(times / padding * math.pi)'], {}), '(times / padding * math.pi)\n', (5307, 5334), True, 'import numpy as np\n'), ((5349, 5381), 'numpy.sinc', 'np.sinc', (['(times * zeros_per_block)'], {}), '(times * zeros_per_block)\n', (5356, 5381), True, 'import numpy as np\n'), ((10236, 10256), 'torch.cos', 'th.cos', (['transform[1]'], {}), '(transform[1])\n', (10242, 10256), True, 'import torch as th\n'), ((10287, 10307), 'torch.sin', 'th.sin', (['transform[1]'], {}), '(transform[1])\n', (10293, 10307), True, 'import torch as th\n'), ((3408, 3428), 'math.log2', 'math.log2', (['frame_len'], {}), '(frame_len)\n', (3417, 3428), False, 'import math\n'), ((5019, 5036), 'numpy.arange', 'np.arange', (['dst_sr'], {}), '(dst_sr)\n', (5028, 5036), True, 'import numpy as np\n'), ((5083, 5100), 'numpy.arange', 'np.arange', (['src_sr'], {}), '(src_sr)\n', (5092, 5100), True, 'import numpy as np\n')]
""" Module for plotting analyses """ import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np from copy import deepcopy import pickle, json import os from matplotlib.offsetbox import AnchoredOffsetbox try: basestring except NameError: basestring = str colorList = [[0.42, 0.67, 0.84], [0.90, 0.76, 0.00], [0.42, 0.83, 0.59], [0.90, 0.32, 0.00], [0.34, 0.67, 0.67], [0.90, 0.59, 0.00], [0.42, 0.82, 0.83], [1.00, 0.85, 0.00], [0.33, 0.67, 0.47], [1.00, 0.38, 0.60], [0.57, 0.67, 0.33], [0.50, 0.20, 0.00], [0.71, 0.82, 0.41], [0.00, 0.20, 0.50], [0.70, 0.32, 0.10]] * 3 class MetaFigure: """A class which defines a figure object""" def __init__(self, kind, sim=None, subplots=None, rcParams=None, autosize=0.35, **kwargs): if not sim: from .. import sim self.sim = sim self.kind = kind # Make a copy of the current matplotlib rcParams and update them self.orig_rcParams = deepcopy(mpl.rcParamsDefault) if rcParams: for rcParam in rcParams: if rcParam in mpl.rcParams: mpl.rcParams[rcParam] = rcParams[rcParam] else: print(rcParam, 'not found in matplotlib.rcParams') self.rcParams = rcParams else: self.rcParams = self.orig_rcParams # Set up any subplots if not subplots: nrows = 1 ncols = 1 elif type(subplots) == int: nrows = subplots ncols = 1 elif type(subplots) == list: nrows = subplots[0] ncols = subplots[1] # Create figure if 'figSize' in kwargs: figSize = kwargs['figSize'] else: figSize = self.rcParams['figure.figsize'] if 'dpi' in kwargs: dpi = kwargs['dpi'] else: dpi = self.rcParams['figure.dpi'] if autosize: maxplots = np.max([nrows, ncols]) figSize0 = figSize[0] + (maxplots-1)*(figSize[0]*autosize) figSize1 = figSize[1] + (maxplots-1)*(figSize[1]*autosize) figSize = [figSize0, figSize1] self.fig, self.ax = plt.subplots(nrows, ncols, figsize=figSize, dpi=dpi) self.plotters = [] def saveFig(self, sim=None, fileName=None, fileDesc=None, fileType='png', fileDir=None, overwrite=True, **kwargs): """ 'eps': 'Encapsulated Postscript', 'jpg': 'Joint Photographic Experts Group', 'jpeg': 'Joint Photographic Experts Group', 'pdf': 'Portable Document Format', 'pgf': 'PGF code for LaTeX', 'png': 'Portable Network Graphics', 'ps': 'Postscript', 'raw': 'Raw RGBA bitmap', 'rgba': 'Raw RGBA bitmap', 'svg': 'Scalable Vector Graphics', 'svgz': 'Scalable Vector Graphics', 'tif': 'Tagged Image File Format', 'tiff': 'Tagged Image File Format' """ if not sim: from .. import sim if fileDesc is not None: fileDesc = '_' + str(fileDesc) else: fileDesc = '_' + self.kind if fileType not in self.fig.canvas.get_supported_filetypes(): raise Exception('fileType not recognized in saveFig') else: fileExt = '.' + fileType if not fileName or not isinstance(fileName, basestring): fileName = self.sim.cfg.filename + fileDesc + fileExt else: if fileName.endswith(fileExt): fileName = fileName.split(fileExt)[0] + fileDesc + fileExt else: fileName = fileName + fileDesc + fileExt if fileDir is not None: fileName = os.path.join(fileDir, fileName) if not overwrite: while os.path.isfile(fileName): try: fileNumStr = fileName.split(fileExt)[0].split('_')[-1] fileNumStrNew = str(int(fileNumStr) + 1).zfill(2) fileName = fileName.split('_' + fileNumStr)[0] except: fileNumStr = fileNumStrNew = '01' fileName = fileName.split(fileExt)[0] fileName = fileName.split(fileNumStr)[0] + '_' + fileNumStrNew + fileExt self.fig.savefig(fileName) self.fileName = fileName return fileName def showFig(self, **kwargs): try: self.fig.show(block=False) except: self.fig.show() def addSuptitle(self, **kwargs): self.fig.suptitle(**kwargs) def finishFig(self, **kwargs): if 'suptitle' in kwargs: if kwargs['suptitle']: self.addSuptitle(**kwargs['suptitle']) if 'tightLayout' not in kwargs: plt.tight_layout() elif kwargs['tightLayout']: plt.tight_layout() if 'saveFig' in kwargs: if kwargs['saveFig']: self.saveFig(**kwargs) if 'showFig' in kwargs: if kwargs['showFig']: self.showFig(**kwargs) else: plt.close(self.fig) # Reset the matplotlib rcParams to their original settings mpl.style.use(self.orig_rcParams) class GeneralPlotter: """A class used for plotting""" def __init__(self, data, kind, axis=None, sim=None, rcParams=None, metafig=None, **kwargs): """ Parameters ---------- data : dict, str axis : matplotlib axis The axis to plot into. If axis is set to None, a new figure and axis are created and plotted into. If plotting into an existing axis, more options are available: xtwin, ytwin, """ self.kind = kind # Load data if type(data) == str: if os.path.isfile(data): self.data = self.loadData(data) else: raise Exception('In Plotter, if data is a string, it must be the path to a data file.') else: self.data = data if not sim: from .. import sim self.sim = sim self.axis = axis if metafig: self.metafig = metafig # If an axis is input, plot there; otherwise make a new figure and axis if self.axis is None: final = True self.metafig = MetaFigure(kind=self.kind, **kwargs) self.fig = self.metafig.fig self.axis = self.metafig.ax else: self.fig = self.axis.figure # Attach plotter to its MetaFigure self.metafig.plotters.append(self) def loadData(self, fileName, fileDir=None, sim=None): from ..analysis import loadData self.data = loadData(fileName=fileName, fileDir=fileDir, sim=None) def saveData(self, fileName=None, fileDesc=None, fileType=None, fileDir=None, sim=None, **kwargs): from ..analysis import saveData as saveFigData saveFigData(self.data, fileName=fileName, fileDesc=fileDesc, fileType=fileType, fileDir=fileDir, sim=sim, **kwargs) def formatAxis(self, **kwargs): if 'title' in kwargs: self.axis.set_title(kwargs['title']) if 'xlabel' in kwargs: self.axis.set_xlabel(kwargs['xlabel']) if 'ylabel' in kwargs: self.axis.set_ylabel(kwargs['ylabel']) if 'xlim' in kwargs: if kwargs['xlim'] is not None: self.axis.set_xlim(kwargs['xlim']) if 'ylim' in kwargs: if kwargs['ylim'] is not None: self.axis.set_ylim(kwargs['ylim']) if 'invert_yaxis' in kwargs: if kwargs['invert_yaxis'] is True: self.axis.invert_yaxis() def addLegend(self, handles=None, labels=None, **kwargs): legendParams = ['loc', 'bbox_to_anchor', 'fontsize', 'numpoints', 'scatterpoints', 'scatteryoffsets', 'markerscale', 'markerfirst', 'frameon', 'fancybox', 'shadow', 'framealpha', 'facecolor', 'edgecolor', 'mode', 'bbox_transform', 'title', 'title_fontsize', 'borderpad', 'labelspacing', 'handlelength', 'handletextpad', 'borderaxespad', 'columnspacing', 'handler_map'] # Check for and apply any legend parameters in the kwargs legendKwargs = {} for kwarg in kwargs: if kwarg in legendParams: legendKwargs[kwarg] = kwargs[kwarg] # If 'legendKwargs' is found in kwargs, use those values instead of the defaults if 'legendKwargs' in kwargs: legendKwargs_new = kwargs['legendKwargs'] for key in legendKwargs_new: if key in legendParams: legendKwargs[key] = legendKwargs_new[key] cur_handles, cur_labels = self.axis.get_legend_handles_labels() if not handles: handles = cur_handles if not labels: labels = cur_labels self.axis.legend(handles, labels, **legendKwargs) def addScalebar(self, matchx=True, matchy=True, hidex=True, hidey=True, unitsx=None, unitsy=None, scalex=1.0, scaley=1.0, xmax=None, ymax=None, space=None, **kwargs): add_scalebar(self.axis, matchx=matchx, matchy=matchy, hidex=hidex, hidey=hidey, unitsx=unitsx, unitsy=unitsy, scalex=scalex, scaley=scaley, xmax=xmax, ymax=ymax, space=space, **kwargs) def addColorbar(self, **kwargs): plt.colorbar(mappable=self.axis.get_images()[0], ax=self.axis, **kwargs) def finishAxis(self, **kwargs): self.formatAxis(**kwargs) if 'saveData' in kwargs: if kwargs['saveData']: self.saveData(**kwargs) if 'dpi' in kwargs: if kwargs['dpi']: self.fig.set_dpi(kwargs['dpi']) if 'figSize' in kwargs: if kwargs['figSize']: self.fig.set_size_inches(kwargs['figSize']) if 'legend' in kwargs: if kwargs['legend'] is True: self.addLegend(**kwargs) elif type(kwargs['legend']) == dict: self.addLegend(**kwargs['legend']) if 'scalebar' in kwargs: if kwargs['scalebar'] is True: self.addScalebar() elif type(kwargs['scalebar']) == dict: self.addScalebar(**kwargs['scalebar']) if 'colorbar' in kwargs: if kwargs['colorbar'] is True: self.addColorbar() elif type(kwargs['colorbar']) == dict: self.addColorbar(**kwargs['colorbar']) if 'grid' in kwargs: self.axis.minorticks_on() if kwargs['grid'] is True: self.axis.grid() elif type(kwargs['grid']) == dict: self.axis.grid(**kwargs['grid']) # If this is the only axis on the figure, finish the figure if type(self.metafig.ax) != list: self.metafig.finishFig(**kwargs) # Reset the matplotlib rcParams to their original settings mpl.style.use(self.metafig.orig_rcParams) class ScatterPlotter(GeneralPlotter): """A class used for scatter plotting""" def __init__(self, data, axis=None, **kwargs): super().__init__(data=data, axis=axis, **kwargs) self.kind = 'scatter' self.x = data.get('x') self.y = data.get('y') self.s = data.get('s') self.c = data.get('c') self.marker = data.get('marker') self.linewidth = data.get('linewidth') self.cmap = data.get('cmap') self.norm = data.get('norm') self.alpha = data.get('alpha') self.linewidths = data.get('linewidths') def plot(self, **kwargs): scatterPlot = self.axis.scatter(x=self.x, y=self.y, s=self.s, c=self.c, marker=self.marker, linewidth=self.linewidth, cmap=self.cmap, norm=self.norm, alpha=self.alpha, linewidths=self.linewidths) self.finishAxis(**kwargs) return self.fig class LinePlotter(GeneralPlotter): """A class used for plotting one line per subplot""" def __init__(self, data, axis=None, options={}, **kwargs): super().__init__(data=data, axis=axis, **kwargs) self.kind = 'line' self.x = np.array(data.get('x')) self.y = np.array(data.get('y')) self.color = data.get('color') self.marker = data.get('marker') self.markersize = data.get('markersize') self.linewidth = data.get('linewidth') self.alpha = data.get('alpha') def plot(self, **kwargs): linePlot = self.axis.plot(self.x, self.y, color=self.color, marker=self.marker, markersize=self.markersize, linewidth=self.linewidth, alpha=self.alpha) self.finishAxis(**kwargs) return self.fig class LinesPlotter(GeneralPlotter): """A class used for plotting multiple lines on the same axis""" def __init__(self, data, axis=None, options={}, **kwargs): super().__init__(data=data, axis=axis, **kwargs) self.kind = 'lines' self.x = np.array(data.get('x')) self.y = np.array(data.get('y')) self.color = data.get('color') self.marker = data.get('marker') self.markersize = data.get('markersize') self.linewidth = data.get('linewidth') self.alpha = data.get('alpha') self.label = data.get('label') def plot(self, **kwargs): numLines = len(self.y) if type(self.color) != list: colors = [self.color for line in range(numLines)] else: colors = self.color if type(self.marker) != list: markers = [self.marker for line in range(numLines)] else: markers = self.marker if type(self.markersize) != list: markersizes = [self.markersize for line in range(numLines)] else: markersizes = self.markersize if type(self.linewidth) != list: linewidths = [self.linewidth for line in range(numLines)] else: linewidths = self.linewidth if type(self.alpha) != list: alphas = [self.alpha for line in range(numLines)] else: alphas = self.alpha if self.label is None: labels = [None for line in range(numLines)] else: labels = self.label for index, line in enumerate(self.y): self.axis.plot( self.x, self.y[index], color=colors[index], marker=markers[index], markersize=markersizes[index], linewidth=linewidths[index], alpha=alphas[index], label=labels[index], ) self.finishAxis(**kwargs) return self.fig class HistPlotter(GeneralPlotter): """A class used for histogram plotting""" def __init__(self, data, axis=None, options={}, **kwargs): super().__init__(data=data, axis=axis, **kwargs) self.kind = 'histogram' self.x = data.get('x') self.bins = data.get('bins', None) self.range = data.get('range', None) self.density = data.get('density', False) self.weights = data.get('weights', None) self.cumulative = data.get('cumulative', False) self.bottom = data.get('bottom', None) self.histtype = data.get('histtype', 'bar') self.align = data.get('align', 'mid') self.orientation = data.get('orientation', 'vertical') self.rwidth = data.get('rwidth', None) self.log = data.get('log', False) self.color = data.get('color', None) self.alpha = data.get('alpha', None) self.label = data.get('label', None) self.stacked = data.get('stacked', False) self.data = data.get('data', None) def plot(self, **kwargs): histPlot = self.axis.hist(self.x, bins=self.bins, range=self.range, density=self.density, weights=self.weights, cumulative=self.cumulative, bottom=self.bottom, histtype=self.histtype, align=self.align, orientation=self.orientation, rwidth=self.rwidth, log=self.log, color=self.color, alpha=self.alpha, label=self.label, stacked=self.stacked, data=self.data) self.finishAxis(**kwargs) return self.fig class ImagePlotter(GeneralPlotter): """A class used for image plotting using plt.imshow""" def __init__(self, data, axis=None, options={}, **kwargs): super().__init__(data=data, axis=axis, **kwargs) self.kind = 'image' self.X = data.get('X') self.cmap = data.get('cmap', None) self.norm = data.get('norm', None) self.aspect = data.get('aspect', None) self.interpolation = data.get('interpolation', None) self.alpha = data.get('alpha', None) self.vmin = data.get('vmin', None) self.vmax = data.get('vmax', None) self.origin = data.get('origin', None) self.extent = data.get('extent', None) self.aspect = data.get('aspect', None) self.interpolation = data.get('interpolation', None) self.filternorm = data.get('filternorm', True) self.filterrad = data.get('filterrad', 4.0) self.resample = data.get('resample', None) self.url = data.get('url', None) self.data = data.get('data', None) def plot(self, **kwargs): imagePlot = self.axis.imshow(self.X, cmap=self.cmap, norm=self.norm, aspect=self.aspect, interpolation=self.interpolation, alpha=self.alpha, vmin=self.vmin, vmax=self.vmax, origin=self.origin, extent=self.extent, filternorm=self.filternorm, filterrad=self.filterrad, resample=self.resample, url=self.url, data=self.data) self.finishAxis(**kwargs) return self.fig class AnchoredScaleBar(AnchoredOffsetbox): """ A class used for adding scale bars to plots """ def __init__(self, axis, sizex=0, sizey=0, labelx=None, labely=None, loc=4, pad=0.1, borderpad=0.1, sep=2, prop=None, barcolor="black", barwidth=None, **kwargs): """ Draw a horizontal and/or vertical bar with the size in data coordinate of the give axes. A label will be drawn underneath (center-aligned). - transform : the coordinate frame (typically axes.transData) - sizex,sizey : width of x,y bar, in data units. 0 to omit - labelx,labely : labels for x,y bars; None to omit - loc : position in containing axes - pad, borderpad : padding, in fraction of the legend font size (or prop) - sep : separation between labels and bars in points. - **kwargs : additional arguments passed to base class constructor """ from matplotlib.patches import Rectangle from matplotlib.offsetbox import AuxTransformBox, VPacker, HPacker, TextArea, DrawingArea bars = AuxTransformBox(axis.transData) if sizex: if axis.xaxis_inverted(): sizex = -sizex bars.add_artist(Rectangle((0,0), sizex, 0, ec=barcolor, lw=barwidth, fc="none")) if sizey: if axis.yaxis_inverted(): sizey = -sizey bars.add_artist(Rectangle((0,0), 0, sizey, ec=barcolor, lw=barwidth, fc="none")) if sizex and labelx: self.xlabel = TextArea(labelx) bars = VPacker(children=[bars, self.xlabel], align="center", pad=0, sep=sep) if sizey and labely: self.ylabel = TextArea(labely) bars = HPacker(children=[self.ylabel, bars], align="center", pad=0, sep=sep) AnchoredOffsetbox.__init__(self, loc, pad=pad, borderpad=borderpad, child=bars, prop=prop, frameon=False, **kwargs) def add_scalebar(axis, matchx=True, matchy=True, hidex=True, hidey=True, unitsx=None, unitsy=None, scalex=1.0, scaley=1.0, xmax=None, ymax=None, space=None, **kwargs): """ Add scalebars to axes Adds a set of scale bars to *ax*, matching the size to the ticks of the plot and optionally hiding the x and y axes - axis : the axis to attach ticks to - matchx,matchy : if True, set size of scale bars to spacing between ticks, if False, set size using sizex and sizey params - hidex,hidey : if True, hide x-axis and y-axis of parent - **kwargs : additional arguments passed to AnchoredScaleBars Returns created scalebar object """ def get_tick_size(subaxis): tick_size = None tick_locs = subaxis.get_majorticklocs() if len(tick_locs)>1: tick_size = np.abs(tick_locs[1] - tick_locs[0]) return tick_size if matchx: sizex = get_tick_size(axis.xaxis) if matchy: sizey = get_tick_size(axis.yaxis) if 'sizex' in kwargs: sizex = kwargs['sizex'] if 'sizey' in kwargs: sizey = kwargs['sizey'] def autosize(value, maxvalue, scale, n=1, m=10): round_to_n = lambda value, n, m: int(np.ceil(round(value, -int(np.floor(np.log10(abs(value)))) + (n - 1)) / m)) * m while value > maxvalue: try: value = round_to_n(0.8 * maxvalue * scale, n, m) / scale except: value /= 10.0 m /= 10.0 return value if ymax is not None and sizey>ymax: sizey = autosize(sizey, ymax, scaley) if xmax is not None and sizex>xmax: sizex = autosize(sizex, xmax, scalex) kwargs['sizex'] = sizex kwargs['sizey'] = sizey if unitsx is None: unitsx = '' if unitsy is None: unitsy = '' if 'labelx' not in kwargs or kwargs['labelx'] is None: kwargs['labelx'] = '%.3g %s'%(kwargs['sizex'] * scalex, unitsx) if 'labely' not in kwargs or kwargs['labely'] is None: kwargs['labely'] = '%.3g %s'%(kwargs['sizey'] * scaley, unitsy) # add space for scalebar if space is not None: ylim0, ylim1 = axis.get_ylim() ylim = (ylim0 - space, ylim1) if ylim0 > ylim1: # if y axis is inverted ylim = (ylim0 + space, ylim1) axis.set_ylim(ylim) scalebar = AnchoredScaleBar(axis, **kwargs) axis.add_artist(scalebar) if hidex: axis.xaxis.set_visible(False) if hidey: axis.yaxis.set_visible(False) if hidex and hidey: axis.set_frame_on(False) return scalebar
[ "numpy.abs", "matplotlib.offsetbox.VPacker", "matplotlib.patches.Rectangle", "matplotlib.offsetbox.AuxTransformBox", "os.path.join", "numpy.max", "os.path.isfile", "matplotlib.pyplot.close", "matplotlib.offsetbox.TextArea", "matplotlib.offsetbox.AnchoredOffsetbox.__init__", "matplotlib.style.use", "matplotlib.offsetbox.HPacker", "matplotlib.pyplot.tight_layout", "copy.deepcopy", "matplotlib.pyplot.subplots" ]
[((970, 999), 'copy.deepcopy', 'deepcopy', (['mpl.rcParamsDefault'], {}), '(mpl.rcParamsDefault)\n', (978, 999), False, 'from copy import deepcopy\n'), ((2219, 2271), 'matplotlib.pyplot.subplots', 'plt.subplots', (['nrows', 'ncols'], {'figsize': 'figSize', 'dpi': 'dpi'}), '(nrows, ncols, figsize=figSize, dpi=dpi)\n', (2231, 2271), True, 'import matplotlib.pyplot as plt\n'), ((5283, 5316), 'matplotlib.style.use', 'mpl.style.use', (['self.orig_rcParams'], {}), '(self.orig_rcParams)\n', (5296, 5316), True, 'import matplotlib as mpl\n'), ((11099, 11140), 'matplotlib.style.use', 'mpl.style.use', (['self.metafig.orig_rcParams'], {}), '(self.metafig.orig_rcParams)\n', (11112, 11140), True, 'import matplotlib as mpl\n'), ((19358, 19389), 'matplotlib.offsetbox.AuxTransformBox', 'AuxTransformBox', (['axis.transData'], {}), '(axis.transData)\n', (19373, 19389), False, 'from matplotlib.offsetbox import AuxTransformBox, VPacker, HPacker, TextArea, DrawingArea\n'), ((20082, 20202), 'matplotlib.offsetbox.AnchoredOffsetbox.__init__', 'AnchoredOffsetbox.__init__', (['self', 'loc'], {'pad': 'pad', 'borderpad': 'borderpad', 'child': 'bars', 'prop': 'prop', 'frameon': '(False)'}), '(self, loc, pad=pad, borderpad=borderpad, child=\n bars, prop=prop, frameon=False, **kwargs)\n', (20108, 20202), False, 'from matplotlib.offsetbox import AnchoredOffsetbox\n'), ((1982, 2004), 'numpy.max', 'np.max', (['[nrows, ncols]'], {}), '([nrows, ncols])\n', (1988, 2004), True, 'import numpy as np\n'), ((3749, 3780), 'os.path.join', 'os.path.join', (['fileDir', 'fileName'], {}), '(fileDir, fileName)\n', (3761, 3780), False, 'import os\n'), ((3826, 3850), 'os.path.isfile', 'os.path.isfile', (['fileName'], {}), '(fileName)\n', (3840, 3850), False, 'import os\n'), ((4852, 4870), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (4868, 4870), True, 'import matplotlib.pyplot as plt\n'), ((5187, 5206), 'matplotlib.pyplot.close', 'plt.close', (['self.fig'], {}), '(self.fig)\n', (5196, 5206), True, 'import matplotlib.pyplot as plt\n'), ((5885, 5905), 'os.path.isfile', 'os.path.isfile', (['data'], {}), '(data)\n', (5899, 5905), False, 'import os\n'), ((19806, 19822), 'matplotlib.offsetbox.TextArea', 'TextArea', (['labelx'], {}), '(labelx)\n', (19814, 19822), False, 'from matplotlib.offsetbox import AuxTransformBox, VPacker, HPacker, TextArea, DrawingArea\n'), ((19842, 19911), 'matplotlib.offsetbox.VPacker', 'VPacker', ([], {'children': '[bars, self.xlabel]', 'align': '"""center"""', 'pad': '(0)', 'sep': 'sep'}), "(children=[bars, self.xlabel], align='center', pad=0, sep=sep)\n", (19849, 19911), False, 'from matplotlib.offsetbox import AuxTransformBox, VPacker, HPacker, TextArea, DrawingArea\n'), ((19967, 19983), 'matplotlib.offsetbox.TextArea', 'TextArea', (['labely'], {}), '(labely)\n', (19975, 19983), False, 'from matplotlib.offsetbox import AuxTransformBox, VPacker, HPacker, TextArea, DrawingArea\n'), ((20003, 20072), 'matplotlib.offsetbox.HPacker', 'HPacker', ([], {'children': '[self.ylabel, bars]', 'align': '"""center"""', 'pad': '(0)', 'sep': 'sep'}), "(children=[self.ylabel, bars], align='center', pad=0, sep=sep)\n", (20010, 20072), False, 'from matplotlib.offsetbox import AuxTransformBox, VPacker, HPacker, TextArea, DrawingArea\n'), ((21024, 21059), 'numpy.abs', 'np.abs', (['(tick_locs[1] - tick_locs[0])'], {}), '(tick_locs[1] - tick_locs[0])\n', (21030, 21059), True, 'import numpy as np\n'), ((4919, 4937), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (4935, 4937), True, 'import matplotlib.pyplot as plt\n'), ((19505, 19569), 'matplotlib.patches.Rectangle', 'Rectangle', (['(0, 0)', 'sizex', '(0)'], {'ec': 'barcolor', 'lw': 'barwidth', 'fc': '"""none"""'}), "((0, 0), sizex, 0, ec=barcolor, lw=barwidth, fc='none')\n", (19514, 19569), False, 'from matplotlib.patches import Rectangle\n'), ((19685, 19749), 'matplotlib.patches.Rectangle', 'Rectangle', (['(0, 0)', '(0)', 'sizey'], {'ec': 'barcolor', 'lw': 'barwidth', 'fc': '"""none"""'}), "((0, 0), 0, sizey, ec=barcolor, lw=barwidth, fc='none')\n", (19694, 19749), False, 'from matplotlib.patches import Rectangle\n')]
import os import time import cv2 import sys sys.path.append('..') import numpy as np from math import cos, sin from lib.FSANET_model import * import numpy as np from keras.layers import Average def draw_axis(img, yaw, pitch, roll, tdx=None, tdy=None, size = 50): print(yaw,roll,pitch) pitch = pitch * np.pi / 180 yaw = -(yaw * np.pi / 180) roll = roll * np.pi / 180 if tdx != None and tdy != None: tdx = tdx tdy = tdy else: height, width = img.shape[:2] tdx = width / 2 tdy = height / 2 # X-Axis pointing to right. drawn in red x1 = size * (cos(yaw) * cos(roll)) + tdx y1 = size * (cos(pitch) * sin(roll) + cos(roll) * sin(pitch) * sin(yaw)) + tdy # Y-Axis | drawn in green # v x2 = size * (-cos(yaw) * sin(roll)) + tdx y2 = size * (cos(pitch) * cos(roll) - sin(pitch) * sin(yaw) * sin(roll)) + tdy # Z-Axis (out of the screen) drawn in blue x3 = size * (sin(yaw)) + tdx y3 = size * (-cos(yaw) * sin(pitch)) + tdy cv2.line(img, (int(tdx), int(tdy)), (int(x1),int(y1)),(0,0,255),3) cv2.line(img, (int(tdx), int(tdy)), (int(x2),int(y2)),(0,255,0),3) cv2.line(img, (int(tdx), int(tdy)), (int(x3),int(y3)),(255,0,0),2) return img def draw_results_ssd(detected,input_img,faces,ad,img_size,img_w,img_h,model): # loop over the detections if detected.shape[2]>0: for i in range(0, detected.shape[2]): # extract the confidence (i.e., probability) associated with the # prediction confidence = detected[0, 0, i, 2] # filter out weak detections if confidence > 0.5: # compute the (x, y)-coordinates of the bounding box for # the face and extract the face ROI (h0, w0) = input_img.shape[:2] box = detected[0, 0, i, 3:7] * np.array([w0, h0, w0, h0]) (startX, startY, endX, endY) = box.astype("int") # print((startX, startY, endX, endY)) x1 = startX y1 = startY w = endX - startX h = endY - startY x2 = x1+w y2 = y1+h xw1 = max(int(x1 - ad * w), 0) yw1 = max(int(y1 - ad * h), 0) xw2 = min(int(x2 + ad * w), img_w - 1) yw2 = min(int(y2 + ad * h), img_h - 1) cv2.rectangle(input_img, (xw1,yw1), (xw2,yw2), (0, 0, 255), 2) start=time.time() faces[i,:,:,:] = cv2.resize(input_img[yw1:yw2 + 1, xw1:xw2 + 1, :], (img_size, img_size)) faces[i,:,:,:] = cv2.normalize(faces[i,:,:,:], None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX) face = np.expand_dims(faces[i,:,:,:], axis=0) p_result = model.predict(face) print('fangxiang',time.time()-start) face = face.squeeze() img = draw_axis(input_img[yw1:yw2 + 1, xw1:xw2 + 1, :], p_result[0][0], p_result[0][1], p_result[0][2]) input_img[yw1:yw2 + 1, xw1:xw2 + 1, :] = img return input_img def main(): os.makedirs('./img',exist_ok=True) img_size = 64 img_idx = 0 ad = 0.6 #Parameters num_capsule = 3 dim_capsule = 16 routings = 2 stage_num = [3,3,3] lambda_d = 1 num_classes = 3 image_size = 64 num_primcaps = 7*3 m_dim = 5 S_set = [num_capsule, dim_capsule, routings, num_primcaps, m_dim] model1 = FSA_net_Capsule(image_size, num_classes, stage_num, lambda_d, S_set)() model2 = FSA_net_Var_Capsule(image_size, num_classes, stage_num, lambda_d, S_set)() num_primcaps = 8*8*3 S_set = [num_capsule, dim_capsule, routings, num_primcaps, m_dim] model3 = FSA_net_noS_Capsule(image_size, num_classes, stage_num, lambda_d, S_set)() weight_file1 = '../pre-trained/300W_LP_models/fsanet_capsule_3_16_2_21_5/fsanet_capsule_3_16_2_21_5.h5' model1.load_weights(weight_file1) print('Finished loading model 1.') weight_file2 = '../pre-trained/300W_LP_models/fsanet_var_capsule_3_16_2_21_5/fsanet_var_capsule_3_16_2_21_5.h5' weight_file3 = '../pre-trained/300W_LP_models/fsanet_noS_capsule_3_16_2_192_5/fsanet_noS_capsule_3_16_2_192_5.h5' model2.load_weights(weight_file2) print('Finished loading model 2.') model3.load_weights(weight_file3) print('Finished loading model 3.') inputs = Input(shape=(64,64,3)) x1 = model1(inputs) #1x1 x2 = model2(inputs) #var x3 = model3(inputs) #w/o avg_model = Average()([x1,x2,x3]) model = Model(inputs=inputs, outputs=avg_model) # load our serialized face detector from disk print("[INFO] loading face detector...") protoPath = os.path.sep.join(["face_detector", "deploy.prototxt"]) modelPath = os.path.sep.join(["face_detector", "res10_300x300_ssd_iter_140000.caffemodel"]) net = cv2.dnn.readNetFromCaffe(protoPath, modelPath) # capture video cap = cv2.VideoCapture(0) # cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1024*1) # cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 768*1) while True: # get video frame ret, input_img = cap.read() img_idx = img_idx + 1 img_h, img_w, _ = np.shape(input_img) blob = cv2.dnn.blobFromImage(cv2.resize(input_img, (300, 300)), 1.0, (300, 300), (104.0, 177.0, 123.0)) net.setInput(blob) detected = net.forward() faces = np.empty((detected.shape[2], img_size, img_size, 3)) input_img = draw_results_ssd(detected,input_img,faces,ad,img_size,img_w,img_h,model) # cv2.imwrite('img/'+str(img_idx)+'.png',input_img) cv2.imshow("result", input_img) key = cv2.waitKey(1) if __name__ == '__main__': main()
[ "cv2.rectangle", "cv2.resize", "os.makedirs", "cv2.normalize", "cv2.dnn.readNetFromCaffe", "cv2.imshow", "math.cos", "numpy.array", "os.path.sep.join", "cv2.waitKey", "numpy.empty", "cv2.VideoCapture", "numpy.expand_dims", "time.time", "numpy.shape", "math.sin", "sys.path.append", "keras.layers.Average" ]
[((45, 66), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (60, 66), False, 'import sys\n'), ((3243, 3278), 'os.makedirs', 'os.makedirs', (['"""./img"""'], {'exist_ok': '(True)'}), "('./img', exist_ok=True)\n", (3254, 3278), False, 'import os\n'), ((4861, 4915), 'os.path.sep.join', 'os.path.sep.join', (["['face_detector', 'deploy.prototxt']"], {}), "(['face_detector', 'deploy.prototxt'])\n", (4877, 4915), False, 'import os\n'), ((4932, 5011), 'os.path.sep.join', 'os.path.sep.join', (["['face_detector', 'res10_300x300_ssd_iter_140000.caffemodel']"], {}), "(['face_detector', 'res10_300x300_ssd_iter_140000.caffemodel'])\n", (4948, 5011), False, 'import os\n'), ((5030, 5076), 'cv2.dnn.readNetFromCaffe', 'cv2.dnn.readNetFromCaffe', (['protoPath', 'modelPath'], {}), '(protoPath, modelPath)\n', (5054, 5076), False, 'import cv2\n'), ((5108, 5127), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\n', (5124, 5127), False, 'import cv2\n'), ((4675, 4684), 'keras.layers.Average', 'Average', ([], {}), '()\n', (4682, 4684), False, 'from keras.layers import Average\n'), ((5360, 5379), 'numpy.shape', 'np.shape', (['input_img'], {}), '(input_img)\n', (5368, 5379), True, 'import numpy as np\n'), ((5582, 5634), 'numpy.empty', 'np.empty', (['(detected.shape[2], img_size, img_size, 3)'], {}), '((detected.shape[2], img_size, img_size, 3))\n', (5590, 5634), True, 'import numpy as np\n'), ((5802, 5833), 'cv2.imshow', 'cv2.imshow', (['"""result"""', 'input_img'], {}), "('result', input_img)\n", (5812, 5833), False, 'import cv2\n'), ((5848, 5862), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (5859, 5862), False, 'import cv2\n'), ((970, 978), 'math.sin', 'sin', (['yaw'], {}), '(yaw)\n', (973, 978), False, 'from math import cos, sin\n'), ((5418, 5451), 'cv2.resize', 'cv2.resize', (['input_img', '(300, 300)'], {}), '(input_img, (300, 300))\n', (5428, 5451), False, 'import cv2\n'), ((619, 627), 'math.cos', 'cos', (['yaw'], {}), '(yaw)\n', (622, 627), False, 'from math import cos, sin\n'), ((630, 639), 'math.cos', 'cos', (['roll'], {}), '(roll)\n', (633, 639), False, 'from math import cos, sin\n'), ((805, 814), 'math.sin', 'sin', (['roll'], {}), '(roll)\n', (808, 814), False, 'from math import cos, sin\n'), ((1015, 1025), 'math.sin', 'sin', (['pitch'], {}), '(pitch)\n', (1018, 1025), False, 'from math import cos, sin\n'), ((2459, 2523), 'cv2.rectangle', 'cv2.rectangle', (['input_img', '(xw1, yw1)', '(xw2, yw2)', '(0, 0, 255)', '(2)'], {}), '(input_img, (xw1, yw1), (xw2, yw2), (0, 0, 255), 2)\n', (2472, 2523), False, 'import cv2\n'), ((2544, 2555), 'time.time', 'time.time', ([], {}), '()\n', (2553, 2555), False, 'import time\n'), ((2589, 2661), 'cv2.resize', 'cv2.resize', (['input_img[yw1:yw2 + 1, xw1:xw2 + 1, :]', '(img_size, img_size)'], {}), '(input_img[yw1:yw2 + 1, xw1:xw2 + 1, :], (img_size, img_size))\n', (2599, 2661), False, 'import cv2\n'), ((2695, 2784), 'cv2.normalize', 'cv2.normalize', (['faces[i, :, :, :]', 'None'], {'alpha': '(0)', 'beta': '(255)', 'norm_type': 'cv2.NORM_MINMAX'}), '(faces[i, :, :, :], None, alpha=0, beta=255, norm_type=cv2.\n NORM_MINMAX)\n', (2708, 2784), False, 'import cv2\n'), ((2825, 2866), 'numpy.expand_dims', 'np.expand_dims', (['faces[i, :, :, :]'], {'axis': '(0)'}), '(faces[i, :, :, :], axis=0)\n', (2839, 2866), True, 'import numpy as np\n'), ((664, 674), 'math.cos', 'cos', (['pitch'], {}), '(pitch)\n', (667, 674), False, 'from math import cos, sin\n'), ((677, 686), 'math.sin', 'sin', (['roll'], {}), '(roll)\n', (680, 686), False, 'from math import cos, sin\n'), ((714, 722), 'math.sin', 'sin', (['yaw'], {}), '(yaw)\n', (717, 722), False, 'from math import cos, sin\n'), ((794, 802), 'math.cos', 'cos', (['yaw'], {}), '(yaw)\n', (797, 802), False, 'from math import cos, sin\n'), ((839, 849), 'math.cos', 'cos', (['pitch'], {}), '(pitch)\n', (842, 849), False, 'from math import cos, sin\n'), ((852, 861), 'math.cos', 'cos', (['roll'], {}), '(roll)\n', (855, 861), False, 'from math import cos, sin\n'), ((888, 897), 'math.sin', 'sin', (['roll'], {}), '(roll)\n', (891, 897), False, 'from math import cos, sin\n'), ((1004, 1012), 'math.cos', 'cos', (['yaw'], {}), '(yaw)\n', (1007, 1012), False, 'from math import cos, sin\n'), ((1898, 1924), 'numpy.array', 'np.array', (['[w0, h0, w0, h0]'], {}), '([w0, h0, w0, h0])\n', (1906, 1924), True, 'import numpy as np\n'), ((689, 698), 'math.cos', 'cos', (['roll'], {}), '(roll)\n', (692, 698), False, 'from math import cos, sin\n'), ((701, 711), 'math.sin', 'sin', (['pitch'], {}), '(pitch)\n', (704, 711), False, 'from math import cos, sin\n'), ((864, 874), 'math.sin', 'sin', (['pitch'], {}), '(pitch)\n', (867, 874), False, 'from math import cos, sin\n'), ((877, 885), 'math.sin', 'sin', (['yaw'], {}), '(yaw)\n', (880, 885), False, 'from math import cos, sin\n'), ((2945, 2956), 'time.time', 'time.time', ([], {}), '()\n', (2954, 2956), False, 'import time\n')]
#!//anaconda/envs/py36/bin/python # # File name: kmc_pld.py # Date: 2018/08/03 09:07 # Author: <NAME> # # Description: # import numpy as np from collections import Counter class EventTree: """ Class maintaining a binary tree for random event type lookup and arrays for choosing specific event. """ def __init__(self, rates, events): self.rates = rates self.events = events self.__setup() def __build_tree(self, e_ratio): self.event_tree = [] # create event ratio array level 0 - bottom if len(e_ratio) % 2 == 1: e_ratio.extend([0.0]) # create the bottom level (rates*numbers) self.event_tree.append(np.array(e_ratio)) # create partial summs (iteratively) up to the 2nd highest level while len(e_ratio) > 2: e_ratio = [e_ratio[i]+e_ratio[i+1] for i in range(0, len(e_ratio), 2)] if len(e_ratio) % 2 == 1: e_ratio.extend([0.0]) self.event_tree.append(np.array(e_ratio)) # create top level = sum of all rates self.event_tree.append(np.array(sum(e_ratio))) def __setup(self): # Get dictionary of event type counts e_counts = Counter([e['type'] for e in self.events]) print(e_counts) # create a list of events based on event types self.event_counts = [[] for _ in range(len(self.rates))] for e in self.events: self.event_counts[e['type']].append(e) e_ratio = [e_counts.get(t, 0)*r for t, r in enumerate(self.rates)] print('e_ratio', e_ratio) self.__build_tree(e_ratio) def update_events(self, old_events, new_events): """ Update tree: remove old events and add new events """ pass def find_event(self): """Find and return an event""" # generate a random number [0,Rs) q = self.Rs*np.random.random() # cycle through levels (top->down) # start with top-level child (k-2) end with level above bottom (1) j = 0 for k in range(len(self.event_tree)-2, 0, -1): # left child value left = self.event_tree[k][j] if q < left: j = 2*j else: q -= left j = 2*j + 1 # bottom level - return selected event type if q < self.event_tree[0][j]: event_type = self.events[j] else: event_type = self.events[j+1] # select a random event index of a given type event_number = np.random.randint(len(self.event_counts[event_type])) # get the event object event = event_counts[event_type][event_number] return event
[ "collections.Counter", "numpy.array", "numpy.random.random" ]
[((1264, 1305), 'collections.Counter', 'Counter', (["[e['type'] for e in self.events]"], {}), "([e['type'] for e in self.events])\n", (1271, 1305), False, 'from collections import Counter\n'), ((724, 741), 'numpy.array', 'np.array', (['e_ratio'], {}), '(e_ratio)\n', (732, 741), True, 'import numpy as np\n'), ((1958, 1976), 'numpy.random.random', 'np.random.random', ([], {}), '()\n', (1974, 1976), True, 'import numpy as np\n'), ((1044, 1061), 'numpy.array', 'np.array', (['e_ratio'], {}), '(e_ratio)\n', (1052, 1061), True, 'import numpy as np\n')]
import os os.environ['CUDA_VISIBLE_DEVICES'] = '2' import torch torch.rand(10) import torch.nn as nn import torch.nn.functional as F import glob from tqdm import tqdm, trange print(torch.cuda.is_available()) print(torch.cuda.get_device_name()) print(torch.cuda.current_device()) device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') print('Using device:', device) print() #Additional Info when using cuda if device.type == 'cuda': print(torch.cuda.get_device_name(0)) print('Memory Usage:') print('Allocated:', round(torch.cuda.memory_allocated(0)/1024**3,1), 'GB') print('Cached: ', round(torch.cuda.memory_reserved(0)/1024**3,1), 'GB') import torch.backends.cudnn as cudnn import numpy as np import os, cv2 from tqdm import tqdm, trange import seaborn as sns from models.experimental import attempt_load from utils.datasets import LoadStreams, LoadImages from utils.general import ( check_img_size, non_max_suppression, apply_classifier, scale_coords, xyxy2xywh, plot_one_box, strip_optimizer) from utils.torch_utils import select_device, load_classifier, time_synchronized from my_utils import xyxy_2_xyxyo, draw_boxes # Initialize device = select_device('') half = device.type != 'cpu' # half precision only supported on CUDA def prepare_input(img1, img_size=416, half=True): img2 = cv2.resize(img1, (img_size, img_size)) # W x H img2 = img2.transpose(2,0,1) img2 = img2[np.newaxis, ...] img2 = torch.from_numpy(img2).to(device) # torch image is ch x H x W img2 = img2.half() if not half else img2.float() img2 /= 255.0 return img2 #%% # Directories out = '/home/user01/data_ssd/Talha/yolo/op/' weights = '/home/user01/data_ssd/Talha/yolo/ScaledYOLOv4/runs/exp2_yolov4-csp-results/weights/best_yolov4-csp-results.pt' source = '/home/user01/data_ssd/Talha/yolo/paprika_y5/valid/images/' imgsz = 416 conf_thres = 0.4 iou_thres = 0.5 classes = [0,1,2,3,4,5] class_names = ["blossom_end_rot", "graymold","powdery_mildew","spider_mite", "spotting_disease", "snails_and_slugs"] # deleting files in op_dir filelist = [ f for f in os.listdir(out)]# if f.endswith(".png") ] for f in tqdm(filelist, desc = 'Deleting old files fro directory'): os.remove(os.path.join(out, f)) # Load model model = attempt_load(weights, map_location=device) # load FP32 model imgsz = check_img_size(imgsz, s=model.stride.max()) # check img_size if half: model.half() # to FP16 # Load model model = attempt_load(weights, map_location=device) # load FP32 model imgsz = check_img_size(imgsz, s=model.stride.max()) # check img_size img_paths = glob.glob('/home/user01/data_ssd/Talha/yolo/paprika_y5/test/images/*.png') + \ glob.glob('/home/user01/data_ssd/Talha/yolo/paprika_y5/test/images/*.jpg') # Run inference if device.type != 'cpu': model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters()))) # run once #%% for i in trange(len(img_paths)): path = img_paths[i] img1 = cv2.imread(path) img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2RGB) img_h, img_w, _ = img1.shape img2 = prepare_input(img1, 416, half) # get file name name = os.path.basename(path)[:-4] # Inference t1 = time_synchronized() pred = model(img2, augment=False)[0] # Apply NMS pred = non_max_suppression(pred, conf_thres, iou_thres, classes=classes, agnostic=True) if pred[0] is not None: boxes = pred[0].cpu().detach().numpy() # <xmin><ymin><xmax><ymax><confd><class_id> else: boxes = np.array([10.0, 20.0, 30.0, 50.0, 0.75, 0]).reshape(1,6) # dummy values coords_minmax = np.zeros((boxes.shape[0], 4)) # droping 5th value confd = np.zeros((boxes.shape[0], 1)) class_ids = np.zeros((boxes.shape[0], 1)) # assign coords_minmax = boxes[:,0:4] # coords confd = boxes[:,4] # confidence class_ids = boxes[:,5] # class id coords_xyminmax = [] det_classes = [] for i in range(boxes.shape[0]): coords_xyminmax.append(xyxy_2_xyxyo(img_w, img_h, coords_minmax[i])) det_classes.append(class_names[int(class_ids[i])]) all_bounding_boxnind = [] for i in range(boxes.shape[0]): bounding_box = [0.0] * 6 bounding_box[0] = det_classes[i] bounding_box[1] = confd[i] bounding_box[2] = coords_xyminmax[i][0] bounding_box[3] = coords_xyminmax[i][1] bounding_box[4] = coords_xyminmax[i][2] bounding_box[5] = coords_xyminmax[i][3] bounding_box = str(bounding_box)[1:-1]# remove square brackets bounding_box = bounding_box.replace("'",'')# removing inverted commas around class name bounding_box = "".join(bounding_box.split())# remove spaces in between **here dont give space inbetween the inverted commas "". all_bounding_boxnind.append(bounding_box) all_bounding_boxnind = ' '.join(map(str, all_bounding_boxnind))# convert list to string all_bounding_boxnind=list(all_bounding_boxnind.split(' ')) # convert strin to list # replacing commas with spaces for i in range(len(all_bounding_boxnind)): all_bounding_boxnind[i] = all_bounding_boxnind[i].replace(',',' ') for i in range(len(all_bounding_boxnind)): # check if file exiscts else make new with open(out +'{}.txt'.format(name), "a+") as file_object: # Move read cursor to the start of file. file_object.seek(0) # If file is not empty then append '\n' data = file_object.read(100) if len(data) > 0 : file_object.write("\n") # Append text at the end of file file_object.write(all_bounding_boxnind[i]) #%% import glob, random import matplotlib.pyplot as plt import matplotlib as mpl mpl.rcParams['figure.dpi'] = 300 img_paths = glob.glob('/home/user01/data_ssd/Talha/yolo/paprika_y5/test/images/*.png') + \ glob.glob('/home/user01/data_ssd/Talha/yolo/paprika_y5/test/images/*.jpg') img_path = random.choice(img_paths) img1 = cv2.imread(img_path) img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2RGB) img_h, img_w, _ = img1.shape img2 = prepare_input(img1, 416, half) pred = model(img2, augment=False)[0] # Apply NMS pred = non_max_suppression(pred, conf_thres, iou_thres, classes=classes, agnostic=True) boxes = pred[0].cpu().detach().numpy() # <xmin><ymin><xmax><ymax><confd><class_id> coords_minmax = np.zeros((boxes.shape[0], 4)) # droping 5th value confd = np.zeros((boxes.shape[0], 1)) class_ids = np.zeros((boxes.shape[0], 1)) # assign coords_minmax = boxes[:,0:4] # coords confd = boxes[:,4] # confidence class_ids = boxes[:,5] # class id coords_xyminmax = [] det_classes = [] for i in range(boxes.shape[0]): coords_xyminmax.append(xyxy_2_xyxyo(img_w, img_h, coords_minmax[i])) det_classes.append(class_names[int(class_ids[i])]) t = np.asarray(coords_xyminmax) op = draw_boxes(img1, confd, t, det_classes, class_names, order='xy_minmax', analysis=False) plt.imshow(op) print('='*50) print('Image Name: ', os.path.basename(img_path),img1.shape) print('\nClass_name ', '| B_box Coords ', '| Confidence') print('_'*50) for k in range(len(det_classes)): print(det_classes[k], t[k], confd[k]) print('='*50)
[ "torch.from_numpy", "numpy.array", "torch.cuda.is_available", "matplotlib.pyplot.imshow", "os.listdir", "numpy.asarray", "torch.cuda.memory_reserved", "my_utils.xyxy_2_xyxyo", "torch.cuda.current_device", "glob.glob", "random.choice", "cv2.cvtColor", "cv2.resize", "cv2.imread", "utils.torch_utils.time_synchronized", "torch.cuda.get_device_name", "models.experimental.attempt_load", "my_utils.draw_boxes", "utils.torch_utils.select_device", "torch.cuda.memory_allocated", "tqdm.tqdm", "os.path.join", "numpy.zeros", "utils.general.non_max_suppression", "os.path.basename", "torch.zeros", "torch.rand" ]
[((64, 78), 'torch.rand', 'torch.rand', (['(10)'], {}), '(10)\n', (74, 78), False, 'import torch\n'), ((1189, 1206), 'utils.torch_utils.select_device', 'select_device', (['""""""'], {}), "('')\n", (1202, 1206), False, 'from utils.torch_utils import select_device, load_classifier, time_synchronized\n'), ((2183, 2238), 'tqdm.tqdm', 'tqdm', (['filelist'], {'desc': '"""Deleting old files fro directory"""'}), "(filelist, desc='Deleting old files fro directory')\n", (2187, 2238), False, 'from tqdm import tqdm, trange\n'), ((2300, 2342), 'models.experimental.attempt_load', 'attempt_load', (['weights'], {'map_location': 'device'}), '(weights, map_location=device)\n', (2312, 2342), False, 'from models.experimental import attempt_load\n'), ((2492, 2534), 'models.experimental.attempt_load', 'attempt_load', (['weights'], {'map_location': 'device'}), '(weights, map_location=device)\n', (2504, 2534), False, 'from models.experimental import attempt_load\n'), ((6058, 6082), 'random.choice', 'random.choice', (['img_paths'], {}), '(img_paths)\n', (6071, 6082), False, 'import glob, random\n'), ((6092, 6112), 'cv2.imread', 'cv2.imread', (['img_path'], {}), '(img_path)\n', (6102, 6112), False, 'import os, cv2\n'), ((6120, 6157), 'cv2.cvtColor', 'cv2.cvtColor', (['img1', 'cv2.COLOR_BGR2RGB'], {}), '(img1, cv2.COLOR_BGR2RGB)\n', (6132, 6157), False, 'import os, cv2\n'), ((6284, 6369), 'utils.general.non_max_suppression', 'non_max_suppression', (['pred', 'conf_thres', 'iou_thres'], {'classes': 'classes', 'agnostic': '(True)'}), '(pred, conf_thres, iou_thres, classes=classes, agnostic=True\n )\n', (6303, 6369), False, 'from utils.general import check_img_size, non_max_suppression, apply_classifier, scale_coords, xyxy2xywh, plot_one_box, strip_optimizer\n'), ((6465, 6494), 'numpy.zeros', 'np.zeros', (['(boxes.shape[0], 4)'], {}), '((boxes.shape[0], 4))\n', (6473, 6494), True, 'import numpy as np\n'), ((6523, 6552), 'numpy.zeros', 'np.zeros', (['(boxes.shape[0], 1)'], {}), '((boxes.shape[0], 1))\n', (6531, 6552), True, 'import numpy as np\n'), ((6565, 6594), 'numpy.zeros', 'np.zeros', (['(boxes.shape[0], 1)'], {}), '((boxes.shape[0], 1))\n', (6573, 6594), True, 'import numpy as np\n'), ((6916, 6943), 'numpy.asarray', 'np.asarray', (['coords_xyminmax'], {}), '(coords_xyminmax)\n', (6926, 6943), True, 'import numpy as np\n'), ((6949, 7040), 'my_utils.draw_boxes', 'draw_boxes', (['img1', 'confd', 't', 'det_classes', 'class_names'], {'order': '"""xy_minmax"""', 'analysis': '(False)'}), "(img1, confd, t, det_classes, class_names, order='xy_minmax',\n analysis=False)\n", (6959, 7040), False, 'from my_utils import xyxy_2_xyxyo, draw_boxes\n'), ((7037, 7051), 'matplotlib.pyplot.imshow', 'plt.imshow', (['op'], {}), '(op)\n', (7047, 7051), True, 'import matplotlib.pyplot as plt\n'), ((181, 206), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (204, 206), False, 'import torch\n'), ((214, 242), 'torch.cuda.get_device_name', 'torch.cuda.get_device_name', ([], {}), '()\n', (240, 242), False, 'import torch\n'), ((250, 277), 'torch.cuda.current_device', 'torch.cuda.current_device', ([], {}), '()\n', (275, 277), False, 'import torch\n'), ((1343, 1381), 'cv2.resize', 'cv2.resize', (['img1', '(img_size, img_size)'], {}), '(img1, (img_size, img_size))\n', (1353, 1381), False, 'import os, cv2\n'), ((2637, 2711), 'glob.glob', 'glob.glob', (['"""/home/user01/data_ssd/Talha/yolo/paprika_y5/test/images/*.png"""'], {}), "('/home/user01/data_ssd/Talha/yolo/paprika_y5/test/images/*.png')\n", (2646, 2711), False, 'import glob, random\n'), ((2728, 2802), 'glob.glob', 'glob.glob', (['"""/home/user01/data_ssd/Talha/yolo/paprika_y5/test/images/*.jpg"""'], {}), "('/home/user01/data_ssd/Talha/yolo/paprika_y5/test/images/*.jpg')\n", (2737, 2802), False, 'import glob, random\n'), ((3028, 3044), 'cv2.imread', 'cv2.imread', (['path'], {}), '(path)\n', (3038, 3044), False, 'import os, cv2\n'), ((3056, 3093), 'cv2.cvtColor', 'cv2.cvtColor', (['img1', 'cv2.COLOR_BGR2RGB'], {}), '(img1, cv2.COLOR_BGR2RGB)\n', (3068, 3093), False, 'import os, cv2\n'), ((3258, 3277), 'utils.torch_utils.time_synchronized', 'time_synchronized', ([], {}), '()\n', (3275, 3277), False, 'from utils.torch_utils import select_device, load_classifier, time_synchronized\n'), ((3347, 3432), 'utils.general.non_max_suppression', 'non_max_suppression', (['pred', 'conf_thres', 'iou_thres'], {'classes': 'classes', 'agnostic': '(True)'}), '(pred, conf_thres, iou_thres, classes=classes, agnostic=True\n )\n', (3366, 3432), False, 'from utils.general import check_img_size, non_max_suppression, apply_classifier, scale_coords, xyxy2xywh, plot_one_box, strip_optimizer\n'), ((3670, 3699), 'numpy.zeros', 'np.zeros', (['(boxes.shape[0], 4)'], {}), '((boxes.shape[0], 4))\n', (3678, 3699), True, 'import numpy as np\n'), ((3732, 3761), 'numpy.zeros', 'np.zeros', (['(boxes.shape[0], 1)'], {}), '((boxes.shape[0], 1))\n', (3740, 3761), True, 'import numpy as np\n'), ((3778, 3807), 'numpy.zeros', 'np.zeros', (['(boxes.shape[0], 1)'], {}), '((boxes.shape[0], 1))\n', (3786, 3807), True, 'import numpy as np\n'), ((5881, 5955), 'glob.glob', 'glob.glob', (['"""/home/user01/data_ssd/Talha/yolo/paprika_y5/test/images/*.png"""'], {}), "('/home/user01/data_ssd/Talha/yolo/paprika_y5/test/images/*.png')\n", (5890, 5955), False, 'import glob, random\n'), ((5972, 6046), 'glob.glob', 'glob.glob', (['"""/home/user01/data_ssd/Talha/yolo/paprika_y5/test/images/*.jpg"""'], {}), "('/home/user01/data_ssd/Talha/yolo/paprika_y5/test/images/*.jpg')\n", (5981, 6046), False, 'import glob, random\n'), ((7088, 7114), 'os.path.basename', 'os.path.basename', (['img_path'], {}), '(img_path)\n', (7104, 7114), False, 'import os, cv2\n'), ((312, 337), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (335, 337), False, 'import torch\n'), ((459, 488), 'torch.cuda.get_device_name', 'torch.cuda.get_device_name', (['(0)'], {}), '(0)\n', (485, 488), False, 'import torch\n'), ((2132, 2147), 'os.listdir', 'os.listdir', (['out'], {}), '(out)\n', (2142, 2147), False, 'import os, cv2\n'), ((2256, 2276), 'os.path.join', 'os.path.join', (['out', 'f'], {}), '(out, f)\n', (2268, 2276), False, 'import os, cv2\n'), ((3205, 3227), 'os.path.basename', 'os.path.basename', (['path'], {}), '(path)\n', (3221, 3227), False, 'import os, cv2\n'), ((6810, 6854), 'my_utils.xyxy_2_xyxyo', 'xyxy_2_xyxyo', (['img_w', 'img_h', 'coords_minmax[i]'], {}), '(img_w, img_h, coords_minmax[i])\n', (6822, 6854), False, 'from my_utils import xyxy_2_xyxyo, draw_boxes\n'), ((1467, 1489), 'torch.from_numpy', 'torch.from_numpy', (['img2'], {}), '(img2)\n', (1483, 1489), False, 'import torch\n'), ((4055, 4099), 'my_utils.xyxy_2_xyxyo', 'xyxy_2_xyxyo', (['img_w', 'img_h', 'coords_minmax[i]'], {}), '(img_w, img_h, coords_minmax[i])\n', (4067, 4099), False, 'from my_utils import xyxy_2_xyxyo, draw_boxes\n'), ((547, 577), 'torch.cuda.memory_allocated', 'torch.cuda.memory_allocated', (['(0)'], {}), '(0)\n', (574, 577), False, 'import torch\n'), ((626, 655), 'torch.cuda.memory_reserved', 'torch.cuda.memory_reserved', (['(0)'], {}), '(0)\n', (652, 655), False, 'import torch\n'), ((3573, 3616), 'numpy.array', 'np.array', (['[10.0, 20.0, 30.0, 50.0, 0.75, 0]'], {}), '([10.0, 20.0, 30.0, 50.0, 0.75, 0])\n', (3581, 3616), True, 'import numpy as np\n'), ((2855, 2886), 'torch.zeros', 'torch.zeros', (['(1)', '(3)', 'imgsz', 'imgsz'], {}), '(1, 3, imgsz, imgsz)\n', (2866, 2886), False, 'import torch\n')]
from . import model import numpy as np from scipy import special, stats class RoyleNicholsModel(model.UnmarkedModel): def __init__(self, det_formula, abun_formula, data): self.response = model.Response(data.y) abun = model.Submodel("Abundance", "abun", abun_formula, np.exp, data.site_covs) det = model.Submodel("Detection", "det", det_formula, special.expit, data.obs_covs) self.submodels = model.SubmodelDict(abun=abun, det=det) def negloglik(self, x, mod, K): x = np.array(x) beta_abun = x[mod["abun"].index] beta_det = x[mod["det"].index] y = mod.response.y N, J = y.shape lam = mod["abun"].predict(beta=beta_abun, interval=False) r = mod["det"].predict(beta=beta_det, interval=False).reshape(N, J) q = 1 - r nll = 0.0 for i in range(N): kvals = range(int(mod.response.Kmin[i]), int(K)+1) f = stats.poisson.pmf(kvals, lam[i]) ymat = np.tile(y[i,], (len(kvals), 1)) qmat = np.tile(q[i,], (len(kvals), 1)) kmat = np.tile(kvals, (J, 1)).transpose() pmat = 1 - qmat**kmat g = stats.binom.logpmf(ymat, 1, pmat).sum(axis=1) fg = f * np.exp(g) nll -= np.log(fg.sum()) return nll def simulate(self): N, J = self.response.y.shape lam = self.predict("abun", interval=False) q = 1 - self.predict("det", interval=False).reshape(N, J) z = np.random.poisson(lam, N) zrep = np.tile(z, (J,1)).transpose() p = 1 - q**zrep y = np.empty((N, J)) for i in range(N): y[i,] = np.random.binomial(1, p[i,], J) return y
[ "numpy.tile", "scipy.stats.poisson.pmf", "numpy.random.poisson", "numpy.exp", "numpy.array", "scipy.stats.binom.logpmf", "numpy.empty", "numpy.random.binomial" ]
[((522, 533), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (530, 533), True, 'import numpy as np\n'), ((1524, 1549), 'numpy.random.poisson', 'np.random.poisson', (['lam', 'N'], {}), '(lam, N)\n', (1541, 1549), True, 'import numpy as np\n'), ((1631, 1647), 'numpy.empty', 'np.empty', (['(N, J)'], {}), '((N, J))\n', (1639, 1647), True, 'import numpy as np\n'), ((948, 980), 'scipy.stats.poisson.pmf', 'stats.poisson.pmf', (['kvals', 'lam[i]'], {}), '(kvals, lam[i])\n', (965, 980), False, 'from scipy import special, stats\n'), ((1695, 1726), 'numpy.random.binomial', 'np.random.binomial', (['(1)', 'p[i,]', 'J'], {}), '(1, p[i,], J)\n', (1713, 1726), True, 'import numpy as np\n'), ((1255, 1264), 'numpy.exp', 'np.exp', (['g'], {}), '(g)\n', (1261, 1264), True, 'import numpy as np\n'), ((1565, 1583), 'numpy.tile', 'np.tile', (['z', '(J, 1)'], {}), '(z, (J, 1))\n', (1572, 1583), True, 'import numpy as np\n'), ((1103, 1125), 'numpy.tile', 'np.tile', (['kvals', '(J, 1)'], {}), '(kvals, (J, 1))\n', (1110, 1125), True, 'import numpy as np\n'), ((1188, 1221), 'scipy.stats.binom.logpmf', 'stats.binom.logpmf', (['ymat', '(1)', 'pmat'], {}), '(ymat, 1, pmat)\n', (1206, 1221), False, 'from scipy import special, stats\n')]
#Contains the functions needed to process both chords and regularized beards # proc_chords is used for chords #proc_beard_regularize for generating beards #proc_pdf saves pdfs of a variable below cloud base #Both have a large overlap, but I split them in two to keep the one script from getting to confusing. import numpy as np import math from netCDF4 import Dataset import os import time as ttiimmee from scipy.interpolate import interp1d from scipy.interpolate import interp2d #from scipy.interpolate import griddata #from mpl_toolkits.axes_grid1 import make_axes_locatable import pickle import sys #sys.path.insert(0, "/home/pgriewank/code/2019-chords-plumes/") #from unionfind import UnionFind from cusize_functions import * #import matplotlib.pyplot as plt import pandas as pd import gc import glob import xarray as xr #turned into a function #removed the possibility to loop over multiple dates, if you want to do that call the function repeatedly #Full list of variables to analyze is unclear, I will try to include everything available, but this might break the memory bank #want to keep the automatic x and y calculation #Scaling shouldn't be needed, as all chord properties should be indepenent of wind direction (right?) #Similarly, no basedefinition is needed, all values are relative to cloud base #Should be able to work for any variable in the column output, or for any 3D variable as long as it is named the same as the file. #Changing 3D output #Default is now to always go over x and y directions #TODO #plot_flag disabled for the mean time def proc_chords( date_str='20160611', directory_input='/data/testbed/lasso/sims/', directory_output='/data/testbed/lasso/chords/', data_dim_flag=1, base_percentile = 25, special_name='', chord_times = 0, N_it_min=0, N_it_max=1e9): # plot_curtains_flag: 0 nothing, 1 plots pre regularization plots, currently dissabled # data_dim_flag: 1 = column, 3 = 3D snapshot # chord_times: 0 use Neils values, use values that fit model output exactly with not gap possible # directory_input = '/data/testbed/lasso/sims/' #+date # N_it_max = maximum number of iterables, 3D timesteps or column files. Used for testing things quickly # N_it_min = start number of iterables, 3D timesteps or column files. Only reall makes sense for 3D to avoid some weird initial fields. time_begin = ttiimmee.time() dz = 25.0 #39.0625 #should be overwritten after the profile data is loaded dx = 25.0 date = date_str n_percentiles = 7 #Number of percentiles percentiles = np.array([5,10,35,50,65,90,95]) #1D clustering parameters in seconds, taken to agree with Lareau if chord_times == 0: t_gap = 20 t_min = 30 t_max = 1200*100 #Made a 100 times longer cell_min = 3 #Minimal number of cells needed per chord # #1D clustering parameters, #set super strict, but goes on for a loooong time as well if chord_times == 1: t_gap = 0. #should be pretty strict, no gaps allowed! t_min = 0.0 t_max = 1e9 cell_min = 3 #Minimal number of cells needed per chord ql_min = 1e-5 #value used to determine existence of cloud z_min = 10 #Index of minimum z_vlvl of the cbl print('looking into date: ',date) if data_dim_flag==1: filename_column = [] #uses glob to get all files which contain column. column_files = glob.glob(directory_input+date+'/*column*.nc') for c_file in column_files: filename_column.append(c_file) print('filename column included:',c_file) if data_dim_flag==3: filename_w = directory_input+date+'/w.nc' filename_l = directory_input+date+'/ql.nc' filename_qt = directory_input+date+'/qt.nc' filename_thl = directory_input+date+'/thl.nc' file_w = Dataset(filename_w,read='r') file_ql = Dataset(filename_l,read='r') file_thl = Dataset(filename_thl,read='r') file_qt = Dataset(filename_qt,read='r') [nz, nx, ny] = get_zxy_dimension(filename_l,'ql') filename_prof=glob.glob(directory_input+date+'/*default?0*.nc')[0] #if date=='bomex': # filename_prof=directory_input+date+'/bomex.default.0000000.nc' file_prof = Dataset(filename_prof,read='r') n_chords = 0 #I will try lists first, which I will then convert to arrays in the end before saving in pandas chord_timesteps = [] chord_length = [] chord_duration = [] chord_time = [] chord_height = [] #percentile of cloud base chord_w = [] chord_w_up = [] #mean over updrafts chord_w_base = [] chord_w_star = [] chord_thl_star = [] chord_qt_star = [] chord_thl = [] chord_thl_25 = [] chord_thl_75 = [] chord_qt = [] chord_qt_25 = [] chord_qt_75 = [] chord_w_flux = [] #Sum of w below #Coming next chord_w_per = np.zeros([0,n_percentiles]) chord_w_per_up = np.zeros([0,n_percentiles]) #This now a bit trickier then for the 3D version. Will have to calculate a vector for the lower time resolution of the profile, #Then latter apply the nearest value to the full 1d time vec #First loading surface variables from default profile print('calculating cbl height from profile file') T = file_prof['thl'][:,0] p = file_prof['p'][:,0]*0.0+99709 qt = file_prof['qt'][:,0] w2 = file_prof['w2'][:,:] thl_prof = file_prof['thl'][:,:] qt_prof = file_prof['qt'][:,:] nz_prof = w2.shape[1] z_prof = file_prof['z'][:] dz = z_prof[1]-z_prof[0] total_surf_buoy_flux = file_prof['bflux'][:,1] total_surf_thl_flux = file_prof['thlflux'][:,1] total_surf_qt_flux = file_prof['qtflux'][:,1] print('dz: ',dz) time_prof = file_prof['time'][:] cbl_1d_prof = time_prof*0.0 #Hack together the Lifting condensation level LCL qt_pressure = p*qt sat_qv = 6.112*100 * np.exp(17.67 * (T - 273.15) / (T - 29.65 )) #rel_hum = np.asmatrix(qt_pressure/sat_qv)[0] rel_hum = qt_pressure/sat_qv #Dewpoint A = 17.27 B = 237.7 alpha = ((A * (T- 273.15)) / (B + (T-273.15))) alpha = alpha + np.log(rel_hum) dewpoint = (B * alpha) / (A - alpha) dewpoint = dewpoint + 273.15 LCL = 125.*(T-dewpoint) LCL_index = np.floor(LCL/dz) #now calculate the cbl top for each profile time for tt in range(len(time_prof)): w_var = 1.0 z=z_min while w_var > 0.08: z += 1 w_var = w2[tt,z] #w_var = np.var(w_1d[z,:]) #Mimimum of LCL +100 or variance plus 300 m cbl_1d_prof[tt] = min(z+300/dz,LCL_index[tt]) #To avoid issues later on I set the maximum cbl height to 60 % of the domain height, but spit out a warning if it happens if cbl_1d_prof[tt]>0.6*nz_prof: print('warning, cbl height heigher than 0.6 domain height, could crash regularization later on, timestep: ',tt) cbl_1d_prof[tt] = math.floor(nz*0.6) print('resulting indexes of cbl over time: ',cbl_1d_prof) print('calculated LCL: ',LCL_index) #Now we either iterate over columns or timesteps if data_dim_flag==1: n_iter =len(filename_column) if data_dim_flag==3: n_iter =len(time_prof) #for col in filename_column: n_iter = min(n_iter,N_it_max) for it in range(N_it_min,n_iter): print('n_chords: ',n_chords) time1 = ttiimmee.time() if data_dim_flag ==1: print('loading column: ',filename_column[it]) file_col = Dataset(filename_column[it],read='r') w_2d = file_col.variables['w'][:] w_2d = w_2d.transpose() ql_2d = file_col.variables['ql'][:] ql_2d = ql_2d.transpose() t_1d = file_col.variables['time'][:] print('t_1d',t_1d) thl_2d = file_col.variables['thl'][:] thl_2d = thl_2d.transpose() qt_2d = file_col.variables['qt'][:] qt_2d = qt_2d.transpose() u_2d = file_col.variables['u'][:] u_2d = u_2d.transpose() v_2d = file_col.variables['v'][:] v_2d = v_2d.transpose() #lets try saving memory by closing files #file_col.close() #The needed cbl height cbl_1d = t_1d*0 #The needed surface_bouyancy_flux bflux_s_1d = t_1d*0 qtflux_s_1d = t_1d*0 thlflux_s_1d = t_1d*0 #Now we go through profile time snapshots and allocate the closest full time values to the profile values dt_2 = (time_prof[1]-time_prof[0])/2 for tt in range(len(time_prof)): cbl_1d[abs(t_1d-time_prof[tt])<dt_2] = cbl_1d_prof[tt] bflux_s_1d[abs(t_1d-time_prof[tt])<dt_2] = total_surf_buoy_flux[tt] qtflux_s_1d[abs(t_1d-time_prof[tt])<dt_2] = total_surf_qt_flux[tt] thlflux_s_1d[abs(t_1d-time_prof[tt])<dt_2] = total_surf_thl_flux[tt] #to get anomalies of thl and qt we subtract the closet mean profile for tt in range(len(time_prof)): #globals().update(locals()) tmp_matrix = thl_2d[:,abs(t_1d-time_prof[tt])<dt_2] tmp_vector = thl_prof[tt,:] #because the vectors don't perfectly align thl_2d[:,abs(t_1d-time_prof[tt])<dt_2] = (tmp_matrix.transpose() - tmp_vector).transpose() tmp_matrix = qt_2d[:,abs(t_1d-time_prof[tt])<dt_2] tmp_vector = qt_prof[tt,:] #because the vectors don't perfectly align qt_2d[:,abs(t_1d-time_prof[tt])<dt_2] = (tmp_matrix.transpose() - tmp_vector).transpose() # = var_2d[:,abs(t_1d-time_prof[tt])<dt_2]-var_prof[tt,:] if data_dim_flag ==3: if sum(file_prof['ql'][it,:])>0.0: print('loading timestep: ',it) ql_3d = grab_3d_field(file_ql ,it,'ql') w_3d = grab_3d_field(file_w ,it,'w') qt_3d = grab_3d_field(file_qt ,it,'qt') thl_3d = grab_3d_field(file_thl ,it,'thl') #Here we have to do all the fuckery to turn the 3D fields into 2d slices with an imaginary time vector w_2d = np.array(w_3d.reshape((nz,nx*ny))) ql_2d = np.array(ql_3d.reshape((nz,nx*ny))) qt_2d = np.array(qt_3d.reshape((nz,nx*ny))) thl_2d = np.array(thl_3d.reshape((nz,nx*ny))) #Now we do the same thing with the transposed field, use to be an either or, now just add it on w_3d = np.transpose( w_3d, (0, 2, 1)) ql_3d = np.transpose(ql_3d, (0, 2, 1)) qt_3d = np.transpose(qt_3d, (0, 2, 1)) thl_3d = np.transpose(thl_3d, (0, 2, 1)) w_2d = np.hstack([w_2d ,np.array(w_3d.reshape((nz,nx*ny)))]) ql_2d = np.hstack([ql_2d ,np.array(ql_3d.reshape((nz,nx*ny)))]) thl_2d = np.hstack([thl_2d ,np.array(thl_3d.reshape((nz,nx*ny)))]) qt_2d = np.hstack([qt_2d ,np.array(qt_3d.reshape((nz,nx*ny)))]) #Should now be able to delete 3d fields as they aren't needed anymore, not sure if that helps save any memory though del w_3d del ql_3d del thl_3d del qt_3d #hopefully this helps gc.collect() #Getting anomalies of thl and qt qt_2d[:,:] = (qt_2d.transpose() - qt_prof[it,:]).transpose() thl_2d[:,:] = (thl_2d.transpose() - thl_prof[it,:]).transpose() #to get the fake time vector we load the wind from the profile data, which devided by the grid spacing gives us a fake time resolution #we use the calculated cbl+300 meter or lcl as reference height ref_lvl = cbl_1d_prof[it] u_ref = file_prof['u'][it,ref_lvl] v_ref = file_prof['v'][it,ref_lvl] V_ref = np.sqrt(u_ref**2+v_ref**2) time_resolution = dx/V_ref print('time iterative, V_ref, time_resolution',it, str(V_ref)[:4], str(time_resolution)[:4] ) #fake t vector, t_1d = np.linspace(0,2*nx*ny*time_resolution,2*nx*ny)#+nx*ny*time_resolution*it #dt_1d = t_1d*0 #dt_1d[1:] = t_1d[1:]-t_1d[:-1] else: #If no clouds are present we pass a very short empty fields over to the chord searcher print('skipping timestep: ',it,' cause no clouds') ql_2d = np.zeros((nz,1)) w_2d = np.zeros((nz,1)) thl_2d = np.zeros((nz,1)) qt_2d = np.zeros((nz,1)) t_1d = np.zeros(1) #The needed cbl height, which constant everywhere cbl_1d = t_1d*0 cbl_1d[:] = cbl_1d_prof[it] #The needed surface buoyancy flux, which is constant everywhere bflux_s_1d = t_1d*0 + total_surf_buoy_flux[it] qtflux_s_1d = t_1d*0 + total_surf_qt_flux[it] thlflux_s_1d = t_1d*0 + total_surf_thl_flux[it] time2 = ttiimmee.time() print('loading time:',(time2-time1)*1.0,) ### Detecting lowest cloud cell is within 300 m of CBL nt = len(cbl_1d) cl_base = np.zeros(nt) #Detecting all cloudy cells #Use to have a different method using nans that doesn:t work anymore somehow. Now I just set it really high where there is no cloud. for t in range(nt): if np.max(ql_2d[:,t])>ql_min : cl_base[t]=np.argmax(ql_2d[:,t]>1e-6) else: cl_base[t]=10000000 cl_base=cl_base.astype(int) #Now find c base lower than the max height cbl_cl_idx = np.where((cl_base-cbl_1d[:nt])*dz<0)[0] cbl_cl_binary = cl_base*0 cbl_cl_binary[cbl_cl_idx]=1 t_cbl_cl=t_1d[cbl_cl_idx] ### Clustering 1D #Now we simply go through all cloudy timesteps and detect chords #If they fulful chord time requirements and have a number of values which fulfills cell_min they are counted as a chord #and their properties are calculatted immediately t_cloudy_idx = 0 #n_chords = 0 chord_idx_list = [] print('iterating through step ',it,'which contains ',len(cbl_cl_idx),'cloudy columns') chord_idx_list = [] while t_cloudy_idx < len(cbl_cl_idx)-1:# and n_curtain<100*it: ####################################GO HERE TO SET MAXIMUM CURTAIN #print(t_chord_begin) t_chord_begin = t_cloudy_idx #now connecting all cloudy indexes #Originally only cared if they fulfilled cloud criteria, but now I also hard coded that neighboring cells always count ##Check if the index of the next cloudy cell is the same as the next index in total, if so the cells are connected while t_cloudy_idx < len(cbl_cl_idx)-1 and (cbl_cl_idx[t_cloudy_idx+1]==cbl_cl_idx[t_cloudy_idx]+1 or t_cbl_cl[t_cloudy_idx+1]-t_cbl_cl[t_cloudy_idx]<t_gap): t_cloudy_idx += 1 t_chord_end = t_cloudy_idx #Checking if it fulfils chord criteria regaring time #we also added a minimum height of 100 m to screen out fog/dew stuff at the surface if t_chord_end-t_chord_begin>cell_min: chord_z_min = np.min(cl_base[cbl_cl_idx[t_chord_begin:t_chord_end]]) ch_duration = t_cbl_cl[t_chord_end]-t_cbl_cl[t_chord_begin] else: chord_z_min = 0 ch_duration = 0 if ch_duration>t_min and ch_duration<t_max and chord_z_min > 4: if t_chord_end-t_chord_begin>cell_min-1: n_chords += 1 #Getting the chord beginning and end idx_beg_chord = cbl_cl_idx[t_chord_begin] idx_end_chord = cbl_cl_idx[t_chord_end] time_beg_chord = t_1d[idx_beg_chord] time_end_chord = t_1d[idx_end_chord] #chord_idx_list.append(list(cbl_cl_idx[t_chord_begin:t_chord_end])) #list of relevant chord indexes ch_idx_l = list(cbl_cl_idx[t_chord_begin:t_chord_end]) #getting V_ref if data_dim_flag==1. Is calculated directly from the cloud base speeds if data_dim_flag==1: u_ref=np.mean(u_2d[cl_base[ch_idx_l],ch_idx_l]) v_ref=np.mean(v_2d[cl_base[ch_idx_l],ch_idx_l]) V_ref=np.sqrt(u_ref**2+v_ref**2) ### Now appending chord properties chord_timesteps.append(t_chord_end-t_chord_begin) chord_duration.append(ch_duration) chord_length.append(ch_duration*V_ref) tmp_base_height = np.percentile(cl_base[ch_idx_l],base_percentile)*dz chord_height.append(tmp_base_height) #25th percentile of cloud base surf_b_flux = np.mean(bflux_s_1d[idx_beg_chord:idx_end_chord]) w_star = (tmp_base_height*surf_b_flux)**(1./3.) surf_qt_flux = np.mean(qtflux_s_1d[idx_beg_chord:idx_end_chord]) qt_star = surf_qt_flux/w_star surf_thl_flux = np.mean(thlflux_s_1d[idx_beg_chord:idx_end_chord]) thl_star = surf_thl_flux/w_star chord_w_star.append(w_star ) chord_thl_star.append(thl_star ) chord_qt_star.append(qt_star ) chord_w_base.append(np.mean(w_2d[cl_base[ch_idx_l],ch_idx_l])) chord_w.append(np.mean(w_2d[cl_base[ch_idx_l]-1,ch_idx_l])) chord_thl.append(np.mean(thl_2d[cl_base[ch_idx_l]-1,ch_idx_l])) #get a fourth and 3/4 of the cloud base cl_base_25_idx = cl_base[ch_idx_l]*0 + int(np.percentile(cl_base[ch_idx_l],base_percentile)/4.) cl_base_75_idx = cl_base[ch_idx_l]*0 + int(np.percentile(cl_base[ch_idx_l],base_percentile)*3./4.) #print ('cl base idx:',np.percentile(cl_base[ch_idx_l],base_percentile),'clbase/4:',cl_base_25_idx[0],'clbase3/4:',cl_base_75_idx[0]) chord_thl_25.append(np.mean(thl_2d[cl_base_25_idx,ch_idx_l])) chord_thl_75.append(np.mean(thl_2d[cl_base_75_idx,ch_idx_l])) chord_qt.append(np.mean(qt_2d[cl_base[ch_idx_l]-1,ch_idx_l])) chord_qt_75.append(np.mean(qt_2d[cl_base_75_idx,ch_idx_l])) chord_qt_25.append(np.mean(qt_2d[cl_base_25_idx,ch_idx_l])) chord_w_flux.append(np.sum(w_2d[cl_base[ch_idx_l]-1,ch_idx_l])) w_base_vec = w_2d[cl_base[ch_idx_l]-1,ch_idx_l] chord_w_up.append(np.mean(w_base_vec[w_base_vec>0.0])) tmp_w_per = np.percentile(w_base_vec,percentiles) if len(w_base_vec[w_base_vec>0.0])>0: tmp_w_per_up = np.percentile(w_base_vec[w_base_vec>0.0],percentiles) else: tmp_w_per_up = np.zeros(n_percentiles) tmp_w_per_up[:] = 'nan' chord_w_per = np.vstack([chord_w_per,tmp_w_per]) chord_w_per_up = np.vstack([chord_w_per,tmp_w_per_up]) if data_dim_flag==1: chord_time.append(np.mean(t_1d[ch_idx_l])) if data_dim_flag==3: chord_time.append(time_prof[it]) t_cloudy_idx += 1 time3 = ttiimmee.time() print('iterable: ',it) print('n_chords: ',n_chords) print('number of time points included: ',len(cbl_cl_idx)) #Does it matter if I turn these from lists to arrays? Fuck it, will do it anyway chord_timesteps=np.asarray(chord_timesteps) chord_duration =np.asarray(chord_duration) chord_length =np.asarray(chord_length) chord_height =np.asarray(chord_height) chord_w_base =np.asarray(chord_w_base) chord_w_star =np.asarray(chord_w_star) chord_thl_star =np.asarray(chord_thl_star) chord_qt_star =np.asarray(chord_qt_star) chord_w =np.asarray(chord_w) chord_w_up =np.asarray(chord_w_up) chord_w_flux =np.asarray(chord_w_flux) chord_thl =np.asarray(chord_thl) chord_thl_25 =np.asarray(chord_thl_25) chord_thl_75 =np.asarray(chord_thl_75) chord_qt =np.asarray(chord_qt) chord_qt_25 =np.asarray(chord_qt_25) chord_qt_75 =np.asarray(chord_qt_75) chord_time =np.asarray(chord_time) #Saving print('all chords: ',len(chord_duration)) save_string_base = 'chord_prop_'+date+'_d'+str(data_dim_flag)+'_ct'+str(chord_times) if N_it_min>0: save_string_base = save_string_base+'_Nmin'+str(N_it_min) if N_it_max<1e9: save_string_base = save_string_base+'_Nmax'+str(n_iter) save_string_base = save_string_base+'_'+special_name+'_N'+str(n_chords) filename_chord_panda = directory_output+save_string_base+'.pkl' data_for_panda = list(zip(chord_timesteps,chord_duration,chord_length,chord_height,chord_w_base,chord_w,chord_w_flux,chord_time,chord_w_up,chord_w_per,chord_w_per_up, chord_w_star,chord_thl_star,chord_qt_star, chord_thl,chord_thl_25,chord_thl_75,chord_qt,chord_qt_25,chord_qt_75)) df = pd.DataFrame(data = data_for_panda, columns=['timesteps','duration','length','height','w_base','w','w_flux','time','w up','w per','w per up', 'w star','thl star','qt star', 'thl','thl 25','thl 75','qt','qt 25','qt 75']) df.to_pickle(filename_chord_panda) time_end = ttiimmee.time() print('total run time of proc_chords in minutes: ',(time_end-time_begin)/60.) print(':') print(':') print('chordlength properties saved as panda in ',filename_chord_panda) print(':') print(':') print(':') print(':') print(':') print(':') print(':') print(':') print(':') print(':') print(':') return #turned into a function #removed the possibility to loop over multiple dates, if you want to do that call the function repeatedly #Should be able to work for any variable in the column output, or for any 3D variable as long as it is named the same as the file. #If the input data is a 3D field it will always go over x and y directions #Two different scale_flags added to rotate the curtain to point upwind. #TODO #plot_flag disabled for the mean time def proc_beard_regularize(reg_var = 'w', date_str='20160611', directory_input='/data/testbed/lasso/sims/', directory_output = 'data_curtains/', data_dim_flag=1, base_smoothing_flag=2, plot_curtains_flag = 0, base_percentile = 25, special_name='', scale_flag=2, chord_times = 0, anomaly_flag = 0, N_it_max=1e9, N_it_min=0, size_bin_flag=0, N_bins=12, bin_size = 250, curtain_extra = 1.0, chord_max = 1e9, boundary_scaling_flag = 0 ): # reg_var = variable that will be regularized # plot_curtains_flag: 0 nothing, 1 plots pre and post regularization plots of reg_var # data_dim_flag: 1 = column, 3 = 3D snapshot # time_slice_curtain: 0 only puts out the total sums, 1: adds a seperate output for each time slice, is needed for scale_flag # scale_flag: If 0, nothing, if 1, it scales the output by u/sqrt(u^2+v^2) and flips the vector if u>0. Is set to 0 if data_dim_flag==1 # 1 the ref_lvl used is determined from the mean cloud base height # 2, similar to 1 but now using a profile # # base_smoothing_flag: 0 use mix of percentile and cloud base as done my Neil, 1: smooth out base after setting it with running average 2: just use percentile defined by base_percentile # base_percentile: percentile used to find chordlength bottom # chord_times: 0 use Neils values, use values that fit model output exactly with not gap possible # anomaly_flag: 0 use reg_var as it is. 1 use reg_var - profile. Works easiest for 3d output, 1d_flag needs to use the closet mean profile # directory_input = '/data/testbed/lasso/sims/' #+date # N_it_max = maximum number of iterables, 3D timesteps or column files. Used for testing things quickly # size_bin_flag bins the beards by their chord_lenth. Currently using 8 bins of 250 meters length to get started. The lowest bin should be empty, because we only calculate curtains when at least curtain_min is used # curtain_extra: Regularized chord length before and after in the curtain, default is 1 # chord_max: Maximum number of chords. If data_dim_flag=3 it will jump to the y direction when chord_max/2 is reached # boundary_scaling_flag: 0 nothing, 1 uses the surface fluxes and cloud base height to calculate either w/w*, thl'/thl*, or qt'/qt* time_begin = ttiimmee.time() dz = 25.0 #39.0625 #Is recalculated from the profile file later on dx = 25.0 date = date_str #1D clustering parameters in seconds, taken to agree with Lareau if chord_times == 0: t_gap = 20 t_min = 30 t_max = 120000 cell_min = 3 #Minimal number of cells needed per chord curtain_min = 10 #Minimal number of cells needed to convert into a curtain # #1D clustering parameters, #set super strict if chord_times == 1: t_gap = 0.#No gaps allowed! t_min = 0 t_max = 1e9 cell_min = 10 #Minimal number of cells needed per chord curtain_min = 10 #Minimal number of cells needed per curtain #value used to determine existence of cloud ql_min = 1e-5 z_min = 10 #Index of minimum z_vlvl of the cbl #z_min = 0 #Index of minimum z_vlvl of the cbl #Flag clean up if data_dim_flag==1: scale_flag=0 #Creating dictionary to save all properties settings_dict = { 'reg_var': reg_var, 'date_str':date_str, 'directory_input':directory_input, 'data_dim_flag':data_dim_flag, 'base_smoothing_flag':base_smoothing_flag, 'plot_curtains_flag' :plot_curtains_flag, 'base_percentile':base_percentile, 'special_name':special_name, 'scale_flag':scale_flag, 'chord_times':chord_times, 'anomaly_flag':anomaly_flag, 'N_it_max':N_it_max, 'N_it_min':N_it_min, 'size_bin_flag':size_bin_flag, 'bin_size':bin_size, 'N_bins':N_bins, 'curtain_extra':curtain_extra } #moved to an inner function to avoid issues with global and local variables def func_curtain_reg(input_2d_field): #function regularizes to cloud base #2019-03-20: added smoother to hopefully avoid impact of harsch jumps #2019-03-28: Added simplified version for base_smoothing_flag == 2 which gets rid of 1D pre interpolation #I originally used interp2d, tried griddata but it was a lot slower #Calculating the regularized t axis but for original resolution #It is expected to go a bit beyond -1.5 and 1.5, total width defined by curtain_extra #takes the original time vector, subtracts it by mean time, then scales it by 1/(time_end_chord-time_beg_chord) t_reg_orig = t_1d[idx_beg_curtain:idx_end_curtain]-(time_beg_chord+time_end_chord)/2. t_reg_orig = t_reg_orig/(time_end_chord-time_beg_chord) #Now we calculate the new regularized grid with the correct vertical but low/original horizontal/time resolution #mesh_t_low_z_high_x,mesh_t_low_z_high_z = np.meshgrid(t_reg_orig,z_reg_mid) #seems not to be needed var_t_low_z_high = np.zeros([curtain_cells,n_z_reg]) #introducing z_idx_base vector #Assigning reference cloud base where no cloud present z_idx_base=cl_base*1.0+0.0 z_idx_base[:] = z_idx_base_default for i in range(idx_beg_chord,idx_end_chord): if i>idx_beg_chord-1 and i<idx_end_chord and cl_base[i]<cbl_1d[i]: z_idx_base[i] = cl_base[i] #Here the smoother comes into play: #We started with a simple 5 cell running mean, #But now we are making it a function of the chordlength, using a 0.1 running mean if base_smoothing_flag ==1: z_idx_base_smooth = z_idx_base*1.0 N = int(np.floor(idx_end_chord-idx_beg_chord)*0.1) for i in range(idx_beg_chord-N,idx_end_chord+N): z_idx_base_smooth[i] = sum(z_idx_base[i-N:i+N])/(2*N) z_idx_base[:] = z_idx_base_smooth[:] if base_smoothing_flag==2: #just put the percentile back z_idx_base[:] = z_idx_base_default #default version for variable base height if base_smoothing_flag<2: #Now for each of the columns of the original curtain a vertical interpolation is done for i in range(idx_beg_curtain,idx_end_curtain): #assigining column value var_orig_col = input_2d_field[:,i] #Regularizing the z axes so that cloud base is at 1 d_z_tmp = 1.0/z_idx_base[i] nz = var_orig_col.shape[0] z_reg_orig_top = d_z_tmp*nz- d_z_tmp/2 z_reg_orig = np.linspace(0+d_z_tmp/2,z_reg_orig_top,nz) #HAve to add 0 to the z_reg_orig to enable interpolation z_reg_orig = np.hstack([[0],z_reg_orig]) var_orig_col = np.hstack([var_orig_col[0],var_orig_col]) #1D vertical interpolation to get the right columns and asign them one by one to w_x_low_z_high #f = interp1d(z_reg_orig, var_orig_col, kind='next') f = interp1d(z_reg_orig, var_orig_col, kind='nearest') try: var_reg_inter = f(z_reg_mid) except: print(z_idx_base[i]) print(z_reg_orig) print(z_reg_mid) var_t_low_z_high[i-idx_beg_curtain,:] = var_reg_inter #Now that w_x_low_z_high we have to interpolate 2D onto the rull regularized grid #print(t_reg_orig.shape,z_reg_mid.shape) f = interp2d(t_reg_orig, z_reg_mid, var_t_low_z_high.transpose(), kind='linear') var_curtain = f(t_reg_mid,z_reg_mid) #constant base height version if base_smoothing_flag==2: #Regularizing the z axes so that cloud base is at 1, since z_idx_base is the same everywhere I just use idx_beg_curtain as one. i=idx_beg_curtain d_z_tmp = 1.0/z_idx_base[i] var_orig_2d = input_2d_field[:,idx_beg_curtain:idx_end_curtain] nz = var_orig_2d.shape[0] z_reg_orig_top = d_z_tmp*nz- d_z_tmp/2 z_reg_orig = np.linspace(0+d_z_tmp/2,z_reg_orig_top,nz) #Have to add 0 to the z_reg_orig to enable interpolation z_reg_orig = np.hstack([[0],z_reg_orig]) var_orig_2d = np.vstack([var_orig_2d[0,:],var_orig_2d]) f = interp2d(t_reg_orig, z_reg_orig,var_orig_2d, kind='linear') var_curtain = f(t_reg_mid,z_reg_mid) return var_curtain #Creating regularized grid. d_reg = 0.005 n_z_reg = int(1.5/d_reg) n_t_reg = int((1+2*curtain_extra)/d_reg) t_reg_bound = np.linspace(-0.5-curtain_extra,0.5+curtain_extra ,n_t_reg+1) t_reg_mid = np.linspace(-0.5-curtain_extra+d_reg/2,0.5+curtain_extra-d_reg/2 ,n_t_reg) z_reg_bound = np.linspace(0,1.5 ,n_z_reg+1) z_reg_mid = np.linspace(0+d_reg/2,1.5-d_reg/2 ,n_z_reg) mesh_curtain_t,mesh_curtain_z = np.meshgrid(t_reg_mid,z_reg_mid) var_curtain = np.zeros([n_t_reg,n_z_reg]) var_curtain_sum = np.zeros([n_t_reg,n_z_reg]) var_curtain_up_sum = np.zeros([n_t_reg,n_z_reg]) var_curtain_dw_sum = np.zeros([n_t_reg,n_z_reg]) n_curtain = 0 n_curtain_up = 0 n_curtain_dw = 0 if size_bin_flag==1: N_bins = 12 n_curtain_bin = np.zeros([N_bins]) n_curtain_bin_up = np.zeros([N_bins]) n_curtain_bin_dw = np.zeros([N_bins]) var_curtain_bin_sum = np.zeros([N_bins,n_t_reg,n_z_reg]) var_curtain_bin_up_sum = np.zeros([N_bins,n_t_reg,n_z_reg]) var_curtain_bin_dw_sum = np.zeros([N_bins,n_t_reg,n_z_reg]) mid_bin_size = np.linspace(125,-125+N_bins*250,N_bins) print('mid_bin_size',mid_bin_size) print('looking into date: ',date) if data_dim_flag==1: filename_column = [] #uses glob to get all files which contain column. column_files = glob.glob(directory_input+date+'/*column*.nc') for c_file in column_files: filename_column.append(c_file) print('filename column included:',c_file) if data_dim_flag==3: filename_w = directory_input+date+'/w.nc' filename_l = directory_input+date+'/ql.nc' file_w = Dataset(filename_w,read='r') file_ql = Dataset(filename_l,read='r') [nz, nx, ny] = get_zxy_dimension(filename_l,'ql') #getting variable to be regularized filename_var = directory_input+date+'/'+reg_var+'.nc' file_var = Dataset(filename_var,read='r') filename_prof=glob.glob(directory_input+date+'/*default?0*.nc')[0] #if date=='bomex': # filename_prof=directory_input+date+'/bomex.default.0000000.nc' file_prof = Dataset(filename_prof,read='r') extra_string = '' n_chords = 0 #This now a bit trickier then for the 3D version. Will have to calculate a vector for the lower time resolution of the profile, #Then latter apply the nearest value to the full 1d time vec #First loading surface variables from default profile print('calculating cbl height from profile file') T = file_prof['thl'][:,0] p = file_prof['p'][:,0]*0.0+99709 qt = file_prof['qt'][:,0] w2 = file_prof['w2'][:,:] nz_prof = w2.shape[1] var_prof = file_prof[reg_var][:,:] #needed for anomaly processing #Just grabbing this to calculate dz z_prof = file_prof['z'][:] dz = z_prof[1]-z_prof[0] print('dz: ',dz) #for boundary scaling total_surf_buoy_flux = file_prof['bflux'][:,1] total_surf_thl_flux = file_prof['thlflux'][:,1] total_surf_qt_flux = file_prof['qtflux'][:,1] time_prof = file_prof['time'][:] cbl_1d_prof = time_prof*0.0 #Hack together the Lifting condensation level LCL qt_pressure = p*qt sat_qv = 6.112*100 * np.exp(17.67 * (T - 273.15) / (T - 29.65 )) #rel_hum = np.asmatrix(qt_pressure/sat_qv)[0] rel_hum = qt_pressure/sat_qv #Dewpoint A = 17.27 B = 237.7 alpha = ((A * (T- 273.15)) / (B + (T-273.15))) alpha = alpha + np.log(rel_hum) dewpoint = (B * alpha) / (A - alpha) dewpoint = dewpoint + 273.15 LCL = 125.*(T-dewpoint) LCL_index = np.floor(LCL/dz) #now calculate the cbl top for each profile time for tt in range(len(time_prof)): w_var = 1.0 z=z_min while w_var > 0.08: z += 1 w_var = w2[tt,z] #w_var = np.var(w_1d[z,:]) #Mimimum of LCL +100 or variance plus 300 m cbl_1d_prof[tt] = min(z+300/dz,LCL_index[tt]) #To avoid issues later on I set the maximum cbl height to 60 % of the domain height, but spit out a warning if it happens if cbl_1d_prof[tt]>0.6*nz_prof: print('warning, cbl height heigher than 0.6 domain height, could crash regularization later on, timestep: ',tt) cbl_1d_prof[tt] = math.floor(nz*0.6) print('resulting indexes of cbl over time: ',cbl_1d_prof) print('calculated LCL: ',LCL_index) #Now we either iterate over columns or timesteps if data_dim_flag==1: n_iter =len(filename_column) if data_dim_flag==3: n_iter =len(time_prof) #Setting curtains for var var_curtain_sum = np.zeros([n_t_reg,n_z_reg]) var_curtain_up_sum = np.zeros([n_t_reg,n_z_reg]) var_curtain_dw_sum = np.zeros([n_t_reg,n_z_reg]) n_curtain = 0 n_chord = 0 n_curtain_up = 0 n_curtain_dw = 0 #for col in filename_column: n_iter = min(n_iter,N_it_max) for it in range(N_it_min,n_iter): print('n_chords: ',n_chords) print('n_curtain: ',n_curtain) time1 = ttiimmee.time() if data_dim_flag ==1: print('loading column: ',filename_column[it]) file_col = Dataset(filename_column[it],read='r') w_2d = file_col.variables['w'][:] w_2d = w_2d.transpose() ql_2d = file_col.variables['ql'][:] ql_2d = ql_2d.transpose() t_1d = file_col.variables['time'][:] u_2d = file_col.variables['u'][:] u_2d = u_2d.transpose() v_2d = file_col.variables['v'][:] v_2d = v_2d.transpose() print('t_1d',t_1d) #Load the var file, even if means that we doable load w_2d or ql_2d var_2d = file_col.variables[reg_var][:] var_2d = var_2d.transpose() #The needed cbl height cbl_1d = t_1d*0 bflux_s_1d = t_1d*0 qtflux_s_1d = t_1d*0 thlflux_s_1d= t_1d*0 #Now we go through profile time snapshots and allocate the closest full time values to the profile values dt_2 = (time_prof[1]-time_prof[0])/2 for tt in range(len(time_prof)): cbl_1d[abs(t_1d-time_prof[tt])<dt_2] = cbl_1d_prof[tt] bflux_s_1d[abs(t_1d-time_prof[tt])<dt_2] = total_surf_buoy_flux[tt] qtflux_s_1d[abs(t_1d-time_prof[tt])<dt_2] = total_surf_qt_flux[tt] thlflux_s_1d[abs(t_1d-time_prof[tt])<dt_2] = total_surf_thl_flux[tt] #to get anomalies we subtract the closet mean profile if anomaly_flag==1: for tt in range(len(time_prof)): tmp_matrix = var_2d[:,abs(t_1d-time_prof[tt])<dt_2] tmp_vector = var_prof[tt,:] #because the vectors don't perfectly align var_2d[:,abs(t_1d-time_prof[tt])<dt_2] = (tmp_matrix.transpose() - tmp_vector).transpose() # = var_2d[:,abs(t_1d-time_prof[tt])<dt_2]-var_prof[tt,:] if data_dim_flag ==3: if sum(file_prof['ql'][it,:])>0.0: print('loading timestep: ',it) ql_3d = grab_3d_field(file_ql ,it,'ql') w_3d = grab_3d_field(file_w ,it,'w') var_3d = grab_3d_field(file_var ,it,reg_var) #Here we have to do all the fuckery to turn the 3D fields into 2d slices with an imaginary time vector w_2d = np.array(w_3d.reshape((nz,nx*ny))) ql_2d = np.array(ql_3d.reshape((nz,nx*ny))) var_2d = np.array(var_3d.reshape((nz,nx*ny))) #Now we do the same thing with the transposed field, use to be an either or, now just add it on w_3d = np.transpose( w_3d, (0, 2, 1)) ql_3d = np.transpose(ql_3d, (0, 2, 1)) var_3d = np.transpose(var_3d, (0, 2, 1)) #globals().update(locals()) w_2d = np.hstack([w_2d ,np.array(w_3d.reshape((nz,nx*ny)))]) ql_2d = np.hstack([ql_2d ,np.array(ql_3d.reshape((nz,nx*ny)))]) var_2d = np.hstack([var_2d ,np.array(var_3d.reshape((nz,nx*ny)))]) #Should now be able to delete 3d fields as they aren't needed anymore, not sure if that helps save any memory though del w_3d del ql_3d del var_3d gc.collect() #Switching to anomalies if anomaly flag is used if anomaly_flag==1: #because the vectors don't perfectly align var_2d[:,:] = (var_2d.transpose() - var_prof[it,:]).transpose() #to get the fake time vector we load the wind from the profile data, which devided by the grid spacing gives us a fake time resolution #we use the calculated cbl+300 meter or lcl as reference height ref_lvl = cbl_1d_prof[it] u_ref = file_prof['u'][it,ref_lvl] v_ref = file_prof['v'][it,ref_lvl] V_ref = np.sqrt(u_ref**2+v_ref**2) time_resolution = dx/V_ref print('time iterative, V_ref, time_resolution',it, V_ref, time_resolution ) print('ref_lvl used to determine reference winds',ref_lvl ) #fake t vector, t_1d = np.linspace(0,2*nx*ny*time_resolution,2*nx*ny)#+nx*ny*time_resolution*it else: #If no clouds are present we pass a very short empty fields over to the chord searcher print('skipping timestep: ',it,' cause no clouds') ql_2d = np.zeros((nz,1)) w_2d = np.zeros((nz,1)) var_2d = np.zeros((nz,1)) t_1d = np.zeros(1) #The needed cbl height, which constant everywhere cbl_1d = t_1d*0 cbl_1d[:] = cbl_1d_prof[it] #The needed surface buoyancy flux, which is constant everywhere bflux_s_1d = t_1d*0 + total_surf_buoy_flux[it] qtflux_s_1d = t_1d*0 + total_surf_qt_flux[it] thlflux_s_1d = t_1d*0 + total_surf_thl_flux[it] time2 = ttiimmee.time() print('loading time:',(time2-time1)*1.0,) ### Detecting lowest cloud cell is within 300 m of CBL nt = len(cbl_1d) cl_base = np.zeros(nt) #Detecting all cloudy cells #Use to have a different method using nans that doesn:t work anymore somehow. Now I just set it really high where there is no cloud. for t in range(nt): if np.max(ql_2d[:,t])>ql_min : cl_base[t]=np.argmax(ql_2d[:,t]>ql_min) else: cl_base[t]=10000000 cl_base=cl_base.astype(int) #Now find c base lower than the max height cbl_cl_idx = np.where((cl_base-cbl_1d[:nt])*dz<0)[0] cbl_cl_binary = cl_base*0 cbl_cl_binary[cbl_cl_idx]=1 t_cbl_cl=t_1d[cbl_cl_idx] #Scaling between x and y is calculated here if required. Is skipped if there are less than 2 timesteps, which is what is assigned when no clouds are present if scale_flag > 0 and t_1d.shape[0]>3: #calculate the profiles of u and v and their scaling u_ref_prof = file_prof['u'][it,:] v_ref_prof = file_prof['v'][it,:] V_ref_prof = np.sqrt(u_ref_prof**2+v_ref_prof**2) scaling_factor_x_prof = u_ref_prof/V_ref_prof scaling_factor_y_prof = v_ref_prof/V_ref_prof #Using the mean cloud base height as the reference lvl ref_idx = np.mean(cl_base[cbl_cl_idx]) if scale_flag == 1: #a new reference level is com scaling_factor_x = scaling_factor_x_prof[int(ref_idx)] scaling_factor_y = scaling_factor_y_prof[int(ref_idx)] print('Scaling flag 1: scaling factor_x: ',scaling_factor_x,' scaling factor_y: ',scaling_factor_y, ' int(ref_idx): ',int(ref_idx)) if scale_flag == 2: #Regularizing the scaling profiles and interpolation them onto the regularized z axis d_z_tmp = 1.0/ref_idx nz = scaling_factor_x_prof.shape[0] z_reg_orig_top = d_z_tmp*nz-d_z_tmp/2 z_reg_orig = np.linspace(0+d_z_tmp/2,z_reg_orig_top,nz) #HAve to add 0 to the z_reg_orig to enable interpolation z_reg_orig = np.hstack([[0],z_reg_orig]) scaling_factor_x_prof_ext = np.hstack([scaling_factor_x_prof[0],scaling_factor_x_prof]) scaling_factor_y_prof_ext = np.hstack([scaling_factor_y_prof[0],scaling_factor_y_prof]) #1D vertical interpolation to get the right columns and asign them one by one to w_x_low_z_high f_x = interp1d(z_reg_orig, scaling_factor_x_prof_ext, kind='nearest') f_y = interp1d(z_reg_orig, scaling_factor_y_prof_ext, kind='nearest') scaling_factor_x_inter = f_x(z_reg_mid) scaling_factor_y_inter = f_y(z_reg_mid) print('Scaling flag 2:, mean scaling_factor_x_inter: ',np.mean(scaling_factor_x_inter), ' mean scaling_factor_y_inter: ',np.mean(scaling_factor_y_inter)) ### Clustering 1D #Now we simply go through all cloudy timesteps #As long as the difference to the next cloudy timestep is lower than t_gap it counts as the same cloud #As an additional contraint, if the cloudy cells are right next to each other they are always counted as consecutive, not matter the time distance between them. #if the difference is larger than 20s the cloud is over, and a chordlength is created which is a list of all timesteps that below to that chordlength #However if the duration of the chordlength is lower than t_min or higher than t_max seconds it isn't #I added an additional constraint that each chord must include at least cell_min cells, because it is possible to get #Small chord lengths with more than t_min which are mostly gaps. t_cloudy_idx = 0 #n_chords = 0 chord_idx_list = [] print('iterating through step ',it,'which contains ',len(cbl_cl_idx),'cloudy columns') while t_cloudy_idx < len(cbl_cl_idx)-1 and n_chords<chord_max: #print('t_chord_begin',t_chord_begin) t_chord_begin = t_cloudy_idx #now connecting all cloudy indexes while t_cloudy_idx < len(cbl_cl_idx)-1 and (cbl_cl_idx[t_cloudy_idx+1]==cbl_cl_idx[t_cloudy_idx]+1 or t_cbl_cl[t_cloudy_idx+1]-t_cbl_cl[t_cloudy_idx]<t_gap): t_cloudy_idx += 1 t_chord_end = t_cloudy_idx #print('t_chord_end',t_chord_end) #Checking if it fulfils chord criteria regaring time #we also added a minimum height of 100 m to screen out fog/dew stuff at the surface if t_chord_end-t_chord_begin>cell_min: chord_z_min = np.min(cl_base[cbl_cl_idx[t_chord_begin:t_chord_end]]) chord_duration = t_cbl_cl[t_chord_end]-t_cbl_cl[t_chord_begin] else: chord_z_min = 0 chord_duration = 0 if chord_duration>t_min and chord_duration<t_max and chord_z_min > 4: if t_chord_end-t_chord_begin>cell_min-1: n_chords += 1 #chord_idx_list.append(list(cbl_cl_idx[t_chord_begin:t_cloudy_idx])) #Here we start the interpolation stuff #Getting the chord beginning and end idx_beg_chord = cbl_cl_idx[t_chord_begin] idx_end_chord = cbl_cl_idx[t_chord_end] time_beg_chord = t_1d[idx_beg_chord] time_end_chord = t_1d[idx_end_chord] #Calculate the beginning and end of the curtain, we add a bit to to each side to make interpolation easy idx_beg_curtain = (np.abs(t_1d - (time_beg_chord-curtain_extra*(time_end_chord-time_beg_chord)))).argmin()-1 idx_end_curtain = (np.abs(t_1d - (time_end_chord+curtain_extra*(time_end_chord-time_beg_chord)))).argmin()+2 idx_end_curtain = min(idx_end_curtain,nt-1) time_beg_curtain = t_1d[idx_beg_curtain] time_end_curtain = t_1d[idx_end_curtain] chord_cells = t_chord_end-t_chord_begin curtain_cells = idx_end_curtain-idx_beg_curtain #If curtain has more than curtain_min cells and curtain tail noes not extend beyond end of 2d field or the beginning extend before #I added 2 cells buffer at the beginning and end, because for the interpolation a bit of overlap is used. if idx_end_curtain<nt-2 and idx_beg_curtain>2 and len(cbl_cl_idx[t_chord_begin:t_chord_end])>curtain_min-1: n_curtain += 1 #First thing to do is calculate the chord base using the 25 percentile in agreement with Neil z_idx_base_default = math.floor(np.percentile(cl_base[cbl_cl_idx[t_chord_begin:t_cloudy_idx]],base_percentile)) #Regularized curtains, I am too lazy to pass on all my variables to func_curtain_reg so I instead made it a nested function var_curtain_tmp = (func_curtain_reg(var_2d)).transpose() if boundary_scaling_flag == 1: #Now adding the boundary scaling using w* surf_flux = np.mean(bflux_s_1d[idx_beg_chord:idx_end_chord]) base_height = z_idx_base_default*dz w_star=(base_height*surf_flux)**(1/3) if reg_var=='w': boundary_scaling = w_star if reg_var=='qt': surf_flux = np.mean(qtflux_s_1d[idx_beg_chord:idx_end_chord]) boundary_scaling = surf_flux/w_star if reg_var=='thl': thl_flux = np.mean(thlflux_s_1d[idx_beg_chord:idx_end_chord]) boundary_scaling = surf_flux/w_star var_curtain_tmp = var_curtain_tmp/boundary_scaling #Finally add it to the mean one and track one more curtain #detecting if chord base has a positive or negative w, then adds to the sum of up or downdraft chords w_tmp = w_2d[cl_base[cbl_cl_idx[t_chord_begin:t_cloudy_idx]]-1,cbl_cl_idx[t_chord_begin:t_chord_end]] #print(w_tmp) #Scaling is now added here, #Things are applied twice so that deviding by n it comes out fin #We assume here that n_x and n_y are roughly same #Could be made cleaner later on if scale_flag>0 and data_dim_flag==3: if scale_flag==1: #find out if we need scaling_factor_x or y by seeing if we are in the first or second half if idx_end_curtain<nt/2: scaling_factor = 2*scaling_factor_x else: scaling_factor = 2*scaling_factor_y if scaling_factor>0: var_curtain_tmp = var_curtain_tmp[::-1,:] var_curtain_tmp = abs(scaling_factor) * var_curtain_tmp if scale_flag==2: if idx_end_curtain<nt/2: scaling_factor_prof = 2*scaling_factor_x_inter else: scaling_factor_prof = 2*scaling_factor_y_inter for n_prof in range(scaling_factor_prof.shape[0]): if scaling_factor_prof[n_prof]>0: var_curtain_tmp[:,n_prof] = var_curtain_tmp[::-1,n_prof] var_curtain_tmp [:,n_prof]= abs(scaling_factor_prof[n_prof])*var_curtain_tmp[:,n_prof] #Now adding the var_curtain_tmp to the sums var_curtain_sum = var_curtain_sum+var_curtain_tmp if np.mean(w_tmp)>0.: n_curtain_up += 1 var_curtain_up_sum += var_curtain_tmp elif np.mean(w_tmp)<0.: n_curtain_dw += 1 var_curtain_dw_sum += var_curtain_tmp else: print('wtf how is this zero: ',np.mean(w_tmp),w_tmp) #globals().update(locals()) ############################################################################################################################################### ################## SIZE BINNING ############################################################################################################## ############################################################################################################################################### if size_bin_flag: #getting V_ref if data_dim_flag==1. Is calculated directly from the cloud base speeds if data_dim_flag==1: ch_idx_l = list(cbl_cl_idx[t_chord_begin:t_chord_end]) u_ref=np.mean(u_2d[cl_base[ch_idx_l],ch_idx_l]) v_ref=np.mean(v_2d[cl_base[ch_idx_l],ch_idx_l]) V_ref=np.sqrt(u_ref**2+v_ref**2) ch_duration = t_cbl_cl[t_chord_end]-t_cbl_cl[t_chord_begin] chord_length = ch_duration*V_ref #if scale_flag==0: # scaling_factor=1. #find index of bin close to mid size bin bin_idx = np.where(np.abs(chord_length-mid_bin_size)<125)[0] if bin_idx.size>0: #print('bin_idx,chord_length',bin_idx,chord_length) n_curtain_bin[bin_idx] += 1 var_curtain_bin_sum[bin_idx,:,:] = var_curtain_bin_sum[bin_idx,:,:] + var_curtain_tmp if np.mean(w_tmp)>0.: n_curtain_bin_up[bin_idx] += 1 var_curtain_bin_up_sum[bin_idx,:,:] += var_curtain_tmp elif np.mean(w_tmp)<0.: n_curtain_bin_dw[bin_idx] += 1 var_curtain_bin_dw_sum[bin_idx,:,:] += var_curtain_tmp else: print('wtf how is this zero: ',np.mean(w_tmp),w_tmp) ############################################################################################################################## #PLOTS ############################################################################################################################## #If the plot flag is set the pre regularization curtains are plotted. if plot_curtains_flag ==1: print('plotting not implemented yet') ############################################################################################################################## #switching to y direction if half of max chords reached ############################################################################################################################## if n_chords == int(chord_max/2): t_cloudy_idx = int(len(cbl_cl_idx)/2) t_cloudy_idx += 1 time3 = ttiimmee.time() print('curtain processing:',(time3-time2)/60.0,'minutes') print(':') print(':') print(':') time_end = ttiimmee.time() print('total run time of proc_beard_regularize in minutes: ',(time_end-time_begin)/60.) print(':') print(':') print(':') #Replacing saving with xarray xr_dataset = xr.Dataset( data_vars = {reg_var :(('regularized height', 'regularized time'), var_curtain_sum.transpose()/n_curtain), reg_var+'_up':(('regularized height', 'regularized time'), var_curtain_up_sum.transpose()/n_curtain_up), reg_var+'_dw':(('regularized height', 'regularized time'), var_curtain_dw_sum.transpose()/n_curtain_dw)}, coords={'regularized time':t_reg_mid, 'regularized height':z_reg_mid}) xr_dataset[reg_var].attrs['n']=n_curtain xr_dataset[reg_var+'_up'].attrs['n']=n_curtain_up xr_dataset[reg_var+'_dw'].attrs['n']=n_curtain_dw xr_dataset.attrs = settings_dict #Making save string save_string_base = '_beard_'+date+'_d'+str(data_dim_flag)+'_cb'+str(base_smoothing_flag)+'_an'+str(anomaly_flag)+'_ct'+str(chord_times)+'_ce'+str(int(curtain_extra)) if data_dim_flag==3: save_string_base = save_string_base+'_sf'+str(scale_flag) if N_it_min>0: save_string_base = save_string_base+'_Nmin'+str(N_it_min) if N_it_max<1e9: save_string_base = save_string_base+'_Nmax'+str(n_iter) if boundary_scaling_flag==1: save_string_base = 'star'+save_string_base save_string_base = save_string_base+'_'+special_name+'_N'+str(n_curtain) save_string = directory_output+ reg_var+save_string_base +'.nc' xr_dataset.to_netcdf(save_string) print('saved beard data to '+save_string) if size_bin_flag==1: xr_dataset = xr.Dataset( data_vars = {reg_var :(('regularized height', 'regularized time','length'), var_curtain_bin_sum.transpose()/n_curtain_bin), reg_var+'_up':(('regularized height', 'regularized time','length'), var_curtain_bin_up_sum.transpose()/n_curtain_bin_up), reg_var+'_dw':(('regularized height', 'regularized time','length'), var_curtain_bin_dw_sum.transpose()/n_curtain_bin_dw)}, coords={'regularized time':t_reg_mid, 'regularized height':z_reg_mid, 'length':mid_bin_size}) xr_dataset[reg_var].attrs['n'] =n_curtain_bin xr_dataset[reg_var+'_up'].attrs['n'] =n_curtain_bin_up xr_dataset[reg_var+'_dw'].attrs['n'] =n_curtain_bin_dw xr_dataset.attrs = settings_dict save_string = directory_output+ reg_var+save_string_base+'_sizebin.nc' xr_dataset.to_netcdf(save_string) print('saved size binned beards to '+save_string) print(':') print(':') print(':') print(':') print(':') return #A simple script which calculates a histogram below the cloud base and saves it #I will try to keep it at least somewhat general with a flexible variable def proc_pdf(reg_var = 'w', date_str='20160611', directory_input ='/data/testbed/lasso/sims/', directory_output ='data_pdfs/', data_dim_flag=3, special_name='', N_it_max=1e9, N_it_min=0, anomaly_flag =0, N_bins=400, base_percentile = 25, boundary_scaling_flag = 1, range_var = [-10,10] ): #We are starting out with histograms of w from -10 to 10 and a 0.1 spacing var_hist_sum=np.zeros(N_bins) date = date_str #value used to determine existence of cloud ql_min = 1e-5 z_min = 10 #Index of minimum z_vlvl of the cbl print('looking into date: ',date) if data_dim_flag==1: filename_column = [] #uses glob to get all files which contain column. column_files = glob.glob(directory_input+date+'/*.column.*.*.*.nc') for c_file in column_files: filename_column.append(c_file) print('filename column included:',c_file) if data_dim_flag==3: filename_w = directory_input+date+'/w.nc' filename_l = directory_input+date+'/ql.nc' file_w = Dataset(filename_w,read='r') file_ql = Dataset(filename_l,read='r') [nz, nx, ny] = get_zxy_dimension(filename_l,'ql') #getting variable to be regularized filename_var = directory_input+date+'/'+reg_var+'.nc' file_var = Dataset(filename_var,read='r') filename_prof=glob.glob(directory_input+date+'/testbed?default?0*.nc')[0] #filename_prof=directory_input+date+'/testbed.default.0000000.nc' if date=='bomex': filename_prof=directory_input+date+'/bomex.default.0000000.nc' file_prof = Dataset(filename_prof,read='r') extra_string = '' #This now a bit trickier then for the 3D version. Will have to calculate a vector for the lower time resolution of the profile, #Then latter apply the nearest value to the full 1d time vec #First loading surface variables from default profile print('calculating cbl height from profile file') T = file_prof['thl'][:,0] p = file_prof['p'][:,0]*0.0+99709 qt = file_prof['qt'][:,0] w2 = file_prof['w2'][:,:] nz_prof = w2.shape[1] var_prof = file_prof[reg_var][:,:] #needed for anomaly processing #Just grabbing this to calculate dz z_prof = file_prof['z'][:] dz = z_prof[1]-z_prof[0] print('dz: ',dz) #for boundary scaling total_surf_buoy_flux = file_prof['bflux'][:,1] total_surf_thl_flux = file_prof['thlflux'][:,1] total_surf_qt_flux = file_prof['qtflux'][:,1] time_prof = file_prof['time'][:] cbl_1d_prof = time_prof*0.0 #Hack together the Lifting condensation level LCL qt_pressure = p*qt sat_qv = 6.112*100 * np.exp(17.67 * (T - 273.15) / (T - 29.65 )) #rel_hum = np.asmatrix(qt_pressure/sat_qv)[0] rel_hum = qt_pressure/sat_qv #Dewpoint A = 17.27 B = 237.7 alpha = ((A * (T- 273.15)) / (B + (T-273.15))) alpha = alpha + np.log(rel_hum) dewpoint = (B * alpha) / (A - alpha) dewpoint = dewpoint + 273.15 LCL = 125.*(T-dewpoint) LCL_index = np.floor(LCL/dz) #now calculate the cbl top for each profile time for tt in range(len(time_prof)): w_var = 1.0 z=z_min while w_var > 0.08: z += 1 w_var = w2[tt,z] #w_var = np.var(w_1d[z,:]) #Mimimum of LCL +100 or variance plus 300 m cbl_1d_prof[tt] = min(z+300/dz,LCL_index[tt]) #To avoid issues later on I set the maximum cbl height to 60 % of the domain height, but spit out a warning if it happens if cbl_1d_prof[tt]>0.6*nz_prof: print('warning, cbl height heigher than 0.6 domain height, could crash regularization later on, timestep: ',tt) cbl_1d_prof[tt] = math.floor(nz*0.6) print('resulting indexes of cbl over time: ',cbl_1d_prof) print('calculated LCL: ',LCL_index) #Now we either iterate over columns or timesteps if data_dim_flag==1: n_iter =len(filename_column) if data_dim_flag==3: n_iter =len(time_prof) #for col in filename_column: n_iter = min(n_iter,N_it_max) for it in range(N_it_min,n_iter): time1 = ttiimmee.time() if data_dim_flag ==1: print('loading column: ',filename_column[it]) file_col = Dataset(filename_column[it],read='r') w_2d = file_col.variables['w'][:] w_2d = w_2d.transpose() ql_2d = file_col.variables['ql'][:] ql_2d = ql_2d.transpose() t_1d = file_col.variables['time'][:] print('t_1d',t_1d) #Load the var file, even if means that we doable load w_2d or ql_2d var_2d = file_col.variables[reg_var][:] var_2d = var_2d.transpose() #The needed cbl height cbl_1d = t_1d*0 bflux_s_1d = t_1d*0 qtflux_s_1d = t_1d*0 thlflux_s_1d= t_1d*0 #Now we go through profile time snapshots and allocate the closest full time values to the profile values dt_2 = (time_prof[1]-time_prof[0])/2 for tt in range(len(time_prof)): cbl_1d[abs(t_1d-time_prof[tt])<dt_2] = cbl_1d_prof[tt] bflux_s_1d[abs(t_1d-time_prof[tt])<dt_2] = total_surf_buoy_flux[tt] qtflux_s_1d[abs(t_1d-time_prof[tt])<dt_2] = total_surf_qt_flux[tt] thlflux_s_1d[abs(t_1d-time_prof[tt])<dt_2] = total_surf_thl_flux[tt] #to get anomalies we subtract the closet mean profile if anomaly_flag==1: for tt in range(len(time_prof)): tmp_matrix = var_2d[:,abs(t_1d-time_prof[tt])<dt_2] tmp_vector = var_prof[tt,:] #because the vectors don't perfectly align var_2d[:,abs(t_1d-time_prof[tt])<dt_2] = (tmp_matrix.transpose() - tmp_vector).transpose() # = var_2d[:,abs(t_1d-time_prof[tt])<dt_2]-var_prof[tt,:] if data_dim_flag ==3: if sum(file_prof['ql'][it,:])>0.0: print('loading timestep: ',it) ql_3d = grab_3d_field(file_ql ,it,'ql') w_3d = grab_3d_field(file_w ,it,'w') var_3d = grab_3d_field(file_var ,it,reg_var) #Here we have to do all the fuckery to turn the 3D fields into 2d slices with an imaginary time vector w_2d = np.array(w_3d.reshape((nz,nx*ny))) ql_2d = np.array(ql_3d.reshape((nz,nx*ny))) var_2d = np.array(var_3d.reshape((nz,nx*ny))) #Now we do the same thing with the transposed field, use to be an either or, now just add it on w_3d = np.transpose( w_3d, (0, 2, 1)) ql_3d = np.transpose(ql_3d, (0, 2, 1)) var_3d = np.transpose(var_3d, (0, 2, 1)) #globals().update(locals()) w_2d = np.hstack([w_2d ,np.array(w_3d.reshape((nz,nx*ny)))]) ql_2d = np.hstack([ql_2d ,np.array(ql_3d.reshape((nz,nx*ny)))]) var_2d = np.hstack([var_2d ,np.array(var_3d.reshape((nz,nx*ny)))]) #This might save a bit of memory if reg_var == 'w': var_2d = w_2d if reg_var == 'ql': var_2d = ql_2d #Should now be able to delete 3d fields as they aren't needed anymore, not sure if that helps save any memory though del w_3d del ql_3d del var_3d gc.collect() #fake t vector, t_1d = np.linspace(0,2*nx*ny,2*nx*ny) #Switching to anomalies if anomaly flag is used if anomaly_flag==1: #because the vectors don't perfectly align var_2d[:,:] = (var_2d.transpose() - var_prof[it,:]).transpose() #to get the fake time vector we load the wind from the profile data, which devided by the grid spacing gives us a fake time resolution #we use the calculated cbl+300 meter or lcl as reference height ref_lvl = cbl_1d_prof[it] else: #If no clouds are present we pass a very short empty fields over to the chord searcher print('skipping timestep: ',it,' cause no clouds') ql_2d = np.zeros((nz,1)) w_2d = np.zeros((nz,1)) var_2d = np.zeros((nz,1)) t_1d = np.zeros(1) #The needed cbl height, which constant everywhere cbl_1d = t_1d*0 cbl_1d[:] = cbl_1d_prof[it] #The needed surface buoyancy flux, which is constant everywhere bflux_s_1d = t_1d*0 + total_surf_buoy_flux[it] qtflux_s_1d = t_1d*0 + total_surf_qt_flux[it] thlflux_s_1d = t_1d*0 + total_surf_thl_flux[it] time2 = ttiimmee.time() print('loading time:',(time2-time1)*1.0,) ### Detecting lowest cloud cell is within 300 m of CBL nt = len(cbl_1d) cl_base = np.zeros(nt) #Detecting all cloudy cells #Use to have a different method using nans that doesn:t work anymore somehow. Now I just set it really high where there is no cloud. for t in range(nt): if np.max(ql_2d[:,t])>ql_min : cl_base[t]=np.argmax(ql_2d[:,t]>ql_min) else: cl_base[t]=10000000 cl_base=cl_base.astype(int) #Now find c base lower than the max height cbl_cl_idx = np.where((cl_base-cbl_1d[:nt])*dz<0)[0] cbl_cl_binary = cl_base*0 cbl_cl_binary[cbl_cl_idx]=1 print('iterating through step ',it,'which contains ',len(cbl_cl_idx),'cloudy columns') if len(cbl_cl_idx)>0: #Now calculating the var at cloud base var_cl_base=var_2d[cl_base[cbl_cl_idx]-1,cbl_cl_idx] #If boundary scaling is used, the variable is scaled accordingly #Only called if there are any clouds if boundary_scaling_flag == 1 and len(cbl_cl_idx)>1: #First thing to do is calculate the chord base using the 25 percentile in agreement with Neil if data_dim_flag==3: z_idx_base_default = math.floor(np.percentile(cl_base[cbl_cl_idx],base_percentile)) # Can't think of a good way to do this, will throw up an error for the mean time. if data_dim_flag==1: print('sorry, but I havent implemented star scaling for 1d data') sys.exit() #Now adding the boundary scaling using w* #Is a bit overcooked currently as it only works with 3D data and thus all surface fluxes are the same everywhere. surf_flux = np.mean(bflux_s_1d) base_height = z_idx_base_default*dz w_star=(base_height*surf_flux)**(1/3) if reg_var=='w': boundary_scaling = w_star if reg_var=='qt': surf_flux = np.mean(qtflux_s_1d) boundary_scaling = surf_flux/w_star if reg_var=='thl': thl_flux = np.mean(thlflux_s_1d) boundary_scaling = surf_flux/w_star var_cl_base = var_cl_base/boundary_scaling #Calculating the histogram, and adding it to the total histogram var_hist,bin_edges = np.histogram(var_cl_base,range=range_var,bins=N_bins) var_hist_sum = var_hist_sum+var_hist else: print('no cloudy columns apparently') var_pdf = var_hist_sum save_string_base = '_pdf_'+date+'_d'+str(data_dim_flag)+'_an'+str(anomaly_flag) if N_it_min>0: save_string_base = save_string_base+'_Nmin'+str(N_it_min) if N_it_max<1e9: save_string_base = save_string_base+'_Nmax'+str(n_iter) if boundary_scaling_flag==1: save_string_base = 'star'+save_string_base save_string = directory_output+ reg_var+save_string_base save_string = save_string+'.npz' np.savez(save_string,var_pdf=var_pdf,range_var=range_var) print('saved pdf with ', sum(var_pdf), 'points to '+save_string) print(':') print(':') print(':') print(':') print(':') print(':') print(':') print(':') print(':') print(':') print(':') return
[ "numpy.sqrt", "math.floor", "numpy.hstack", "numpy.log", "scipy.interpolate.interp1d", "numpy.array", "sys.exit", "scipy.interpolate.interp2d", "numpy.mean", "numpy.savez", "numpy.histogram", "numpy.where", "netCDF4.Dataset", "numpy.asarray", "numpy.max", "numpy.exp", "numpy.linspace", "numpy.vstack", "numpy.min", "pandas.DataFrame", "numpy.meshgrid", "glob.glob", "numpy.abs", "numpy.floor", "numpy.argmax", "gc.collect", "numpy.transpose", "time.time", "numpy.sum", "numpy.zeros", "numpy.percentile" ]
[((2599, 2614), 'time.time', 'ttiimmee.time', ([], {}), '()\n', (2612, 2614), True, 'import time as ttiimmee\n'), ((2799, 2836), 'numpy.array', 'np.array', (['[5, 10, 35, 50, 65, 90, 95]'], {}), '([5, 10, 35, 50, 65, 90, 95])\n', (2807, 2836), True, 'import numpy as np\n'), ((4604, 4636), 'netCDF4.Dataset', 'Dataset', (['filename_prof'], {'read': '"""r"""'}), "(filename_prof, read='r')\n", (4611, 4636), False, 'from netCDF4 import Dataset\n'), ((5507, 5535), 'numpy.zeros', 'np.zeros', (['[0, n_percentiles]'], {}), '([0, n_percentiles])\n', (5515, 5535), True, 'import numpy as np\n'), ((5567, 5595), 'numpy.zeros', 'np.zeros', (['[0, n_percentiles]'], {}), '([0, n_percentiles])\n', (5575, 5595), True, 'import numpy as np\n'), ((6928, 6946), 'numpy.floor', 'np.floor', (['(LCL / dz)'], {}), '(LCL / dz)\n', (6936, 6946), True, 'import numpy as np\n'), ((21605, 21632), 'numpy.asarray', 'np.asarray', (['chord_timesteps'], {}), '(chord_timesteps)\n', (21615, 21632), True, 'import numpy as np\n'), ((21653, 21679), 'numpy.asarray', 'np.asarray', (['chord_duration'], {}), '(chord_duration)\n', (21663, 21679), True, 'import numpy as np\n'), ((21700, 21724), 'numpy.asarray', 'np.asarray', (['chord_length'], {}), '(chord_length)\n', (21710, 21724), True, 'import numpy as np\n'), ((21745, 21769), 'numpy.asarray', 'np.asarray', (['chord_height'], {}), '(chord_height)\n', (21755, 21769), True, 'import numpy as np\n'), ((21790, 21814), 'numpy.asarray', 'np.asarray', (['chord_w_base'], {}), '(chord_w_base)\n', (21800, 21814), True, 'import numpy as np\n'), ((21835, 21859), 'numpy.asarray', 'np.asarray', (['chord_w_star'], {}), '(chord_w_star)\n', (21845, 21859), True, 'import numpy as np\n'), ((21880, 21906), 'numpy.asarray', 'np.asarray', (['chord_thl_star'], {}), '(chord_thl_star)\n', (21890, 21906), True, 'import numpy as np\n'), ((21927, 21952), 'numpy.asarray', 'np.asarray', (['chord_qt_star'], {}), '(chord_qt_star)\n', (21937, 21952), True, 'import numpy as np\n'), ((21973, 21992), 'numpy.asarray', 'np.asarray', (['chord_w'], {}), '(chord_w)\n', (21983, 21992), True, 'import numpy as np\n'), ((22013, 22035), 'numpy.asarray', 'np.asarray', (['chord_w_up'], {}), '(chord_w_up)\n', (22023, 22035), True, 'import numpy as np\n'), ((22056, 22080), 'numpy.asarray', 'np.asarray', (['chord_w_flux'], {}), '(chord_w_flux)\n', (22066, 22080), True, 'import numpy as np\n'), ((22101, 22122), 'numpy.asarray', 'np.asarray', (['chord_thl'], {}), '(chord_thl)\n', (22111, 22122), True, 'import numpy as np\n'), ((22143, 22167), 'numpy.asarray', 'np.asarray', (['chord_thl_25'], {}), '(chord_thl_25)\n', (22153, 22167), True, 'import numpy as np\n'), ((22188, 22212), 'numpy.asarray', 'np.asarray', (['chord_thl_75'], {}), '(chord_thl_75)\n', (22198, 22212), True, 'import numpy as np\n'), ((22233, 22253), 'numpy.asarray', 'np.asarray', (['chord_qt'], {}), '(chord_qt)\n', (22243, 22253), True, 'import numpy as np\n'), ((22274, 22297), 'numpy.asarray', 'np.asarray', (['chord_qt_25'], {}), '(chord_qt_25)\n', (22284, 22297), True, 'import numpy as np\n'), ((22318, 22341), 'numpy.asarray', 'np.asarray', (['chord_qt_75'], {}), '(chord_qt_75)\n', (22328, 22341), True, 'import numpy as np\n'), ((22362, 22384), 'numpy.asarray', 'np.asarray', (['chord_time'], {}), '(chord_time)\n', (22372, 22384), True, 'import numpy as np\n'), ((23253, 23499), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'data_for_panda', 'columns': "['timesteps', 'duration', 'length', 'height', 'w_base', 'w', 'w_flux',\n 'time', 'w up', 'w per', 'w per up', 'w star', 'thl star', 'qt star',\n 'thl', 'thl 25', 'thl 75', 'qt', 'qt 25', 'qt 75']"}), "(data=data_for_panda, columns=['timesteps', 'duration',\n 'length', 'height', 'w_base', 'w', 'w_flux', 'time', 'w up', 'w per',\n 'w per up', 'w star', 'thl star', 'qt star', 'thl', 'thl 25', 'thl 75',\n 'qt', 'qt 25', 'qt 75'])\n", (23265, 23499), True, 'import pandas as pd\n'), ((23633, 23648), 'time.time', 'ttiimmee.time', ([], {}), '()\n', (23646, 23648), True, 'import time as ttiimmee\n'), ((27299, 27314), 'time.time', 'ttiimmee.time', ([], {}), '()\n', (27312, 27314), True, 'import time as ttiimmee\n'), ((34082, 34149), 'numpy.linspace', 'np.linspace', (['(-0.5 - curtain_extra)', '(0.5 + curtain_extra)', '(n_t_reg + 1)'], {}), '(-0.5 - curtain_extra, 0.5 + curtain_extra, n_t_reg + 1)\n', (34093, 34149), True, 'import numpy as np\n'), ((34166, 34257), 'numpy.linspace', 'np.linspace', (['(-0.5 - curtain_extra + d_reg / 2)', '(0.5 + curtain_extra - d_reg / 2)', 'n_t_reg'], {}), '(-0.5 - curtain_extra + d_reg / 2, 0.5 + curtain_extra - d_reg /\n 2, n_t_reg)\n', (34177, 34257), True, 'import numpy as np\n'), ((34265, 34297), 'numpy.linspace', 'np.linspace', (['(0)', '(1.5)', '(n_z_reg + 1)'], {}), '(0, 1.5, n_z_reg + 1)\n', (34276, 34297), True, 'import numpy as np\n'), ((34338, 34390), 'numpy.linspace', 'np.linspace', (['(0 + d_reg / 2)', '(1.5 - d_reg / 2)', 'n_z_reg'], {}), '(0 + d_reg / 2, 1.5 - d_reg / 2, n_z_reg)\n', (34349, 34390), True, 'import numpy as np\n'), ((34423, 34456), 'numpy.meshgrid', 'np.meshgrid', (['t_reg_mid', 'z_reg_mid'], {}), '(t_reg_mid, z_reg_mid)\n', (34434, 34456), True, 'import numpy as np\n'), ((34478, 34506), 'numpy.zeros', 'np.zeros', (['[n_t_reg, n_z_reg]'], {}), '([n_t_reg, n_z_reg])\n', (34486, 34506), True, 'import numpy as np\n'), ((34528, 34556), 'numpy.zeros', 'np.zeros', (['[n_t_reg, n_z_reg]'], {}), '([n_t_reg, n_z_reg])\n', (34536, 34556), True, 'import numpy as np\n'), ((34586, 34614), 'numpy.zeros', 'np.zeros', (['[n_t_reg, n_z_reg]'], {}), '([n_t_reg, n_z_reg])\n', (34594, 34614), True, 'import numpy as np\n'), ((34639, 34667), 'numpy.zeros', 'np.zeros', (['[n_t_reg, n_z_reg]'], {}), '([n_t_reg, n_z_reg])\n', (34647, 34667), True, 'import numpy as np\n'), ((36299, 36331), 'netCDF4.Dataset', 'Dataset', (['filename_prof'], {'read': '"""r"""'}), "(filename_prof, read='r')\n", (36306, 36331), False, 'from netCDF4 import Dataset\n'), ((37773, 37791), 'numpy.floor', 'np.floor', (['(LCL / dz)'], {}), '(LCL / dz)\n', (37781, 37791), True, 'import numpy as np\n'), ((38812, 38840), 'numpy.zeros', 'np.zeros', (['[n_t_reg, n_z_reg]'], {}), '([n_t_reg, n_z_reg])\n', (38820, 38840), True, 'import numpy as np\n'), ((38865, 38893), 'numpy.zeros', 'np.zeros', (['[n_t_reg, n_z_reg]'], {}), '([n_t_reg, n_z_reg])\n', (38873, 38893), True, 'import numpy as np\n'), ((38918, 38946), 'numpy.zeros', 'np.zeros', (['[n_t_reg, n_z_reg]'], {}), '([n_t_reg, n_z_reg])\n', (38926, 38946), True, 'import numpy as np\n'), ((59961, 59976), 'time.time', 'ttiimmee.time', ([], {}), '()\n', (59974, 59976), True, 'import time as ttiimmee\n'), ((63607, 63623), 'numpy.zeros', 'np.zeros', (['N_bins'], {}), '(N_bins)\n', (63615, 63623), True, 'import numpy as np\n'), ((64852, 64884), 'netCDF4.Dataset', 'Dataset', (['filename_prof'], {'read': '"""r"""'}), "(filename_prof, read='r')\n", (64859, 64884), False, 'from netCDF4 import Dataset\n'), ((66301, 66319), 'numpy.floor', 'np.floor', (['(LCL / dz)'], {}), '(LCL / dz)\n', (66309, 66319), True, 'import numpy as np\n'), ((75612, 75671), 'numpy.savez', 'np.savez', (['save_string'], {'var_pdf': 'var_pdf', 'range_var': 'range_var'}), '(save_string, var_pdf=var_pdf, range_var=range_var)\n', (75620, 75671), True, 'import numpy as np\n'), ((3686, 3736), 'glob.glob', 'glob.glob', (["(directory_input + date + '/*column*.nc')"], {}), "(directory_input + date + '/*column*.nc')\n", (3695, 3736), False, 'import glob\n'), ((4136, 4165), 'netCDF4.Dataset', 'Dataset', (['filename_w'], {'read': '"""r"""'}), "(filename_w, read='r')\n", (4143, 4165), False, 'from netCDF4 import Dataset\n'), ((4188, 4217), 'netCDF4.Dataset', 'Dataset', (['filename_l'], {'read': '"""r"""'}), "(filename_l, read='r')\n", (4195, 4217), False, 'from netCDF4 import Dataset\n'), ((4240, 4271), 'netCDF4.Dataset', 'Dataset', (['filename_thl'], {'read': '"""r"""'}), "(filename_thl, read='r')\n", (4247, 4271), False, 'from netCDF4 import Dataset\n'), ((4294, 4324), 'netCDF4.Dataset', 'Dataset', (['filename_qt'], {'read': '"""r"""'}), "(filename_qt, read='r')\n", (4301, 4324), False, 'from netCDF4 import Dataset\n'), ((4423, 4476), 'glob.glob', 'glob.glob', (["(directory_input + date + '/*default?0*.nc')"], {}), "(directory_input + date + '/*default?0*.nc')\n", (4432, 4476), False, 'import glob\n'), ((6554, 6596), 'numpy.exp', 'np.exp', (['(17.67 * (T - 273.15) / (T - 29.65))'], {}), '(17.67 * (T - 273.15) / (T - 29.65))\n', (6560, 6596), True, 'import numpy as np\n'), ((6794, 6809), 'numpy.log', 'np.log', (['rel_hum'], {}), '(rel_hum)\n', (6800, 6809), True, 'import numpy as np\n'), ((8086, 8101), 'time.time', 'ttiimmee.time', ([], {}), '()\n', (8099, 8101), True, 'import time as ttiimmee\n'), ((14321, 14336), 'time.time', 'ttiimmee.time', ([], {}), '()\n', (14334, 14336), True, 'import time as ttiimmee\n'), ((14497, 14509), 'numpy.zeros', 'np.zeros', (['nt'], {}), '(nt)\n', (14505, 14509), True, 'import numpy as np\n'), ((21278, 21293), 'time.time', 'ttiimmee.time', ([], {}), '()\n', (21291, 21293), True, 'import time as ttiimmee\n'), ((30054, 30088), 'numpy.zeros', 'np.zeros', (['[curtain_cells, n_z_reg]'], {}), '([curtain_cells, n_z_reg])\n', (30062, 30088), True, 'import numpy as np\n'), ((34822, 34840), 'numpy.zeros', 'np.zeros', (['[N_bins]'], {}), '([N_bins])\n', (34830, 34840), True, 'import numpy as np\n'), ((34874, 34892), 'numpy.zeros', 'np.zeros', (['[N_bins]'], {}), '([N_bins])\n', (34882, 34892), True, 'import numpy as np\n'), ((34926, 34944), 'numpy.zeros', 'np.zeros', (['[N_bins]'], {}), '([N_bins])\n', (34934, 34944), True, 'import numpy as np\n'), ((34978, 35014), 'numpy.zeros', 'np.zeros', (['[N_bins, n_t_reg, n_z_reg]'], {}), '([N_bins, n_t_reg, n_z_reg])\n', (34986, 35014), True, 'import numpy as np\n'), ((35046, 35082), 'numpy.zeros', 'np.zeros', (['[N_bins, n_t_reg, n_z_reg]'], {}), '([N_bins, n_t_reg, n_z_reg])\n', (35054, 35082), True, 'import numpy as np\n'), ((35114, 35150), 'numpy.zeros', 'np.zeros', (['[N_bins, n_t_reg, n_z_reg]'], {}), '([N_bins, n_t_reg, n_z_reg])\n', (35122, 35150), True, 'import numpy as np\n'), ((35181, 35226), 'numpy.linspace', 'np.linspace', (['(125)', '(-125 + N_bins * 250)', 'N_bins'], {}), '(125, -125 + N_bins * 250, N_bins)\n', (35192, 35226), True, 'import numpy as np\n'), ((35449, 35499), 'glob.glob', 'glob.glob', (["(directory_input + date + '/*column*.nc')"], {}), "(directory_input + date + '/*column*.nc')\n", (35458, 35499), False, 'import glob\n'), ((35792, 35821), 'netCDF4.Dataset', 'Dataset', (['filename_w'], {'read': '"""r"""'}), "(filename_w, read='r')\n", (35799, 35821), False, 'from netCDF4 import Dataset\n'), ((35844, 35873), 'netCDF4.Dataset', 'Dataset', (['filename_l'], {'read': '"""r"""'}), "(filename_l, read='r')\n", (35851, 35873), False, 'from netCDF4 import Dataset\n'), ((36078, 36109), 'netCDF4.Dataset', 'Dataset', (['filename_var'], {'read': '"""r"""'}), "(filename_var, read='r')\n", (36085, 36109), False, 'from netCDF4 import Dataset\n'), ((36132, 36185), 'glob.glob', 'glob.glob', (["(directory_input + date + '/*default?0*.nc')"], {}), "(directory_input + date + '/*default?0*.nc')\n", (36141, 36185), False, 'import glob\n'), ((37399, 37441), 'numpy.exp', 'np.exp', (['(17.67 * (T - 273.15) / (T - 29.65))'], {}), '(17.67 * (T - 273.15) / (T - 29.65))\n', (37405, 37441), True, 'import numpy as np\n'), ((37639, 37654), 'numpy.log', 'np.log', (['rel_hum'], {}), '(rel_hum)\n', (37645, 37654), True, 'import numpy as np\n'), ((39250, 39265), 'time.time', 'ttiimmee.time', ([], {}), '()\n', (39263, 39265), True, 'import time as ttiimmee\n'), ((44797, 44812), 'time.time', 'ttiimmee.time', ([], {}), '()\n', (44810, 44812), True, 'import time as ttiimmee\n'), ((44973, 44985), 'numpy.zeros', 'np.zeros', (['nt'], {}), '(nt)\n', (44981, 44985), True, 'import numpy as np\n'), ((59808, 59823), 'time.time', 'ttiimmee.time', ([], {}), '()\n', (59821, 59823), True, 'import time as ttiimmee\n'), ((63945, 64001), 'glob.glob', 'glob.glob', (["(directory_input + date + '/*.column.*.*.*.nc')"], {}), "(directory_input + date + '/*.column.*.*.*.nc')\n", (63954, 64001), False, 'import glob\n'), ((64285, 64314), 'netCDF4.Dataset', 'Dataset', (['filename_w'], {'read': '"""r"""'}), "(filename_w, read='r')\n", (64292, 64314), False, 'from netCDF4 import Dataset\n'), ((64337, 64366), 'netCDF4.Dataset', 'Dataset', (['filename_l'], {'read': '"""r"""'}), "(filename_l, read='r')\n", (64344, 64366), False, 'from netCDF4 import Dataset\n'), ((64555, 64586), 'netCDF4.Dataset', 'Dataset', (['filename_var'], {'read': '"""r"""'}), "(filename_var, read='r')\n", (64562, 64586), False, 'from netCDF4 import Dataset\n'), ((64609, 64669), 'glob.glob', 'glob.glob', (["(directory_input + date + '/testbed?default?0*.nc')"], {}), "(directory_input + date + '/testbed?default?0*.nc')\n", (64618, 64669), False, 'import glob\n'), ((65927, 65969), 'numpy.exp', 'np.exp', (['(17.67 * (T - 273.15) / (T - 29.65))'], {}), '(17.67 * (T - 273.15) / (T - 29.65))\n', (65933, 65969), True, 'import numpy as np\n'), ((66167, 66182), 'numpy.log', 'np.log', (['rel_hum'], {}), '(rel_hum)\n', (66173, 66182), True, 'import numpy as np\n'), ((67409, 67424), 'time.time', 'ttiimmee.time', ([], {}), '()\n', (67422, 67424), True, 'import time as ttiimmee\n'), ((72305, 72320), 'time.time', 'ttiimmee.time', ([], {}), '()\n', (72318, 72320), True, 'import time as ttiimmee\n'), ((72481, 72493), 'numpy.zeros', 'np.zeros', (['nt'], {}), '(nt)\n', (72489, 72493), True, 'import numpy as np\n'), ((7619, 7639), 'math.floor', 'math.floor', (['(nz * 0.6)'], {}), '(nz * 0.6)\n', (7629, 7639), False, 'import math\n'), ((8213, 8251), 'netCDF4.Dataset', 'Dataset', (['filename_column[it]'], {'read': '"""r"""'}), "(filename_column[it], read='r')\n", (8220, 8251), False, 'from netCDF4 import Dataset\n'), ((14978, 15020), 'numpy.where', 'np.where', (['((cl_base - cbl_1d[:nt]) * dz < 0)'], {}), '((cl_base - cbl_1d[:nt]) * dz < 0)\n', (14986, 15020), True, 'import numpy as np\n'), ((33436, 33484), 'numpy.linspace', 'np.linspace', (['(0 + d_z_tmp / 2)', 'z_reg_orig_top', 'nz'], {}), '(0 + d_z_tmp / 2, z_reg_orig_top, nz)\n', (33447, 33484), True, 'import numpy as np\n'), ((33591, 33619), 'numpy.hstack', 'np.hstack', (['[[0], z_reg_orig]'], {}), '([[0], z_reg_orig])\n', (33600, 33619), True, 'import numpy as np\n'), ((33647, 33690), 'numpy.vstack', 'np.vstack', (['[var_orig_2d[0, :], var_orig_2d]'], {}), '([var_orig_2d[0, :], var_orig_2d])\n', (33656, 33690), True, 'import numpy as np\n'), ((33723, 33783), 'scipy.interpolate.interp2d', 'interp2d', (['t_reg_orig', 'z_reg_orig', 'var_orig_2d'], {'kind': '"""linear"""'}), "(t_reg_orig, z_reg_orig, var_orig_2d, kind='linear')\n", (33731, 33783), False, 'from scipy.interpolate import interp2d\n'), ((38464, 38484), 'math.floor', 'math.floor', (['(nz * 0.6)'], {}), '(nz * 0.6)\n', (38474, 38484), False, 'import math\n'), ((39377, 39415), 'netCDF4.Dataset', 'Dataset', (['filename_column[it]'], {'read': '"""r"""'}), "(filename_column[it], read='r')\n", (39384, 39415), False, 'from netCDF4 import Dataset\n'), ((45456, 45498), 'numpy.where', 'np.where', (['((cl_base - cbl_1d[:nt]) * dz < 0)'], {}), '((cl_base - cbl_1d[:nt]) * dz < 0)\n', (45464, 45498), True, 'import numpy as np\n'), ((46024, 46066), 'numpy.sqrt', 'np.sqrt', (['(u_ref_prof ** 2 + v_ref_prof ** 2)'], {}), '(u_ref_prof ** 2 + v_ref_prof ** 2)\n', (46031, 46066), True, 'import numpy as np\n'), ((46280, 46308), 'numpy.mean', 'np.mean', (['cl_base[cbl_cl_idx]'], {}), '(cl_base[cbl_cl_idx])\n', (46287, 46308), True, 'import numpy as np\n'), ((66992, 67012), 'math.floor', 'math.floor', (['(nz * 0.6)'], {}), '(nz * 0.6)\n', (67002, 67012), False, 'import math\n'), ((67536, 67574), 'netCDF4.Dataset', 'Dataset', (['filename_column[it]'], {'read': '"""r"""'}), "(filename_column[it], read='r')\n", (67543, 67574), False, 'from netCDF4 import Dataset\n'), ((72964, 73006), 'numpy.where', 'np.where', (['((cl_base - cbl_1d[:nt]) * dz < 0)'], {}), '((cl_base - cbl_1d[:nt]) * dz < 0)\n', (72972, 73006), True, 'import numpy as np\n'), ((74967, 75022), 'numpy.histogram', 'np.histogram', (['var_cl_base'], {'range': 'range_var', 'bins': 'N_bins'}), '(var_cl_base, range=range_var, bins=N_bins)\n', (74979, 75022), True, 'import numpy as np\n'), ((11505, 11534), 'numpy.transpose', 'np.transpose', (['w_3d', '(0, 2, 1)'], {}), '(w_3d, (0, 2, 1))\n', (11517, 11534), True, 'import numpy as np\n'), ((11562, 11592), 'numpy.transpose', 'np.transpose', (['ql_3d', '(0, 2, 1)'], {}), '(ql_3d, (0, 2, 1))\n', (11574, 11592), True, 'import numpy as np\n'), ((11619, 11649), 'numpy.transpose', 'np.transpose', (['qt_3d', '(0, 2, 1)'], {}), '(qt_3d, (0, 2, 1))\n', (11631, 11649), True, 'import numpy as np\n'), ((11676, 11707), 'numpy.transpose', 'np.transpose', (['thl_3d', '(0, 2, 1)'], {}), '(thl_3d, (0, 2, 1))\n', (11688, 11707), True, 'import numpy as np\n'), ((12420, 12432), 'gc.collect', 'gc.collect', ([], {}), '()\n', (12430, 12432), False, 'import gc\n'), ((13094, 13126), 'numpy.sqrt', 'np.sqrt', (['(u_ref ** 2 + v_ref ** 2)'], {}), '(u_ref ** 2 + v_ref ** 2)\n', (13101, 13126), True, 'import numpy as np\n'), ((13333, 13391), 'numpy.linspace', 'np.linspace', (['(0)', '(2 * nx * ny * time_resolution)', '(2 * nx * ny)'], {}), '(0, 2 * nx * ny * time_resolution, 2 * nx * ny)\n', (13344, 13391), True, 'import numpy as np\n'), ((13726, 13743), 'numpy.zeros', 'np.zeros', (['(nz, 1)'], {}), '((nz, 1))\n', (13734, 13743), True, 'import numpy as np\n'), ((13770, 13787), 'numpy.zeros', 'np.zeros', (['(nz, 1)'], {}), '((nz, 1))\n', (13778, 13787), True, 'import numpy as np\n'), ((13814, 13831), 'numpy.zeros', 'np.zeros', (['(nz, 1)'], {}), '((nz, 1))\n', (13822, 13831), True, 'import numpy as np\n'), ((13858, 13875), 'numpy.zeros', 'np.zeros', (['(nz, 1)'], {}), '((nz, 1))\n', (13866, 13875), True, 'import numpy as np\n'), ((13902, 13913), 'numpy.zeros', 'np.zeros', (['(1)'], {}), '(1)\n', (13910, 13913), True, 'import numpy as np\n'), ((14732, 14751), 'numpy.max', 'np.max', (['ql_2d[:, t]'], {}), '(ql_2d[:, t])\n', (14738, 14751), True, 'import numpy as np\n'), ((14787, 14817), 'numpy.argmax', 'np.argmax', (['(ql_2d[:, t] > 1e-06)'], {}), '(ql_2d[:, t] > 1e-06)\n', (14796, 14817), True, 'import numpy as np\n'), ((16654, 16708), 'numpy.min', 'np.min', (['cl_base[cbl_cl_idx[t_chord_begin:t_chord_end]]'], {}), '(cl_base[cbl_cl_idx[t_chord_begin:t_chord_end]])\n', (16660, 16708), True, 'import numpy as np\n'), ((31838, 31886), 'numpy.linspace', 'np.linspace', (['(0 + d_z_tmp / 2)', 'z_reg_orig_top', 'nz'], {}), '(0 + d_z_tmp / 2, z_reg_orig_top, nz)\n', (31849, 31886), True, 'import numpy as np\n'), ((31990, 32018), 'numpy.hstack', 'np.hstack', (['[[0], z_reg_orig]'], {}), '([[0], z_reg_orig])\n', (31999, 32018), True, 'import numpy as np\n'), ((32051, 32093), 'numpy.hstack', 'np.hstack', (['[var_orig_col[0], var_orig_col]'], {}), '([var_orig_col[0], var_orig_col])\n', (32060, 32093), True, 'import numpy as np\n'), ((32304, 32354), 'scipy.interpolate.interp1d', 'interp1d', (['z_reg_orig', 'var_orig_col'], {'kind': '"""nearest"""'}), "(z_reg_orig, var_orig_col, kind='nearest')\n", (32312, 32354), False, 'from scipy.interpolate import interp1d\n'), ((42099, 42128), 'numpy.transpose', 'np.transpose', (['w_3d', '(0, 2, 1)'], {}), '(w_3d, (0, 2, 1))\n', (42111, 42128), True, 'import numpy as np\n'), ((42156, 42186), 'numpy.transpose', 'np.transpose', (['ql_3d', '(0, 2, 1)'], {}), '(ql_3d, (0, 2, 1))\n', (42168, 42186), True, 'import numpy as np\n'), ((42213, 42244), 'numpy.transpose', 'np.transpose', (['var_3d', '(0, 2, 1)'], {}), '(var_3d, (0, 2, 1))\n', (42225, 42244), True, 'import numpy as np\n'), ((42886, 42898), 'gc.collect', 'gc.collect', ([], {}), '()\n', (42896, 42898), False, 'import gc\n'), ((43616, 43648), 'numpy.sqrt', 'np.sqrt', (['(u_ref ** 2 + v_ref ** 2)'], {}), '(u_ref ** 2 + v_ref ** 2)\n', (43623, 43648), True, 'import numpy as np\n'), ((43913, 43971), 'numpy.linspace', 'np.linspace', (['(0)', '(2 * nx * ny * time_resolution)', '(2 * nx * ny)'], {}), '(0, 2 * nx * ny * time_resolution, 2 * nx * ny)\n', (43924, 43971), True, 'import numpy as np\n'), ((44250, 44267), 'numpy.zeros', 'np.zeros', (['(nz, 1)'], {}), '((nz, 1))\n', (44258, 44267), True, 'import numpy as np\n'), ((44292, 44309), 'numpy.zeros', 'np.zeros', (['(nz, 1)'], {}), '((nz, 1))\n', (44300, 44309), True, 'import numpy as np\n'), ((44334, 44351), 'numpy.zeros', 'np.zeros', (['(nz, 1)'], {}), '((nz, 1))\n', (44342, 44351), True, 'import numpy as np\n'), ((44376, 44387), 'numpy.zeros', 'np.zeros', (['(1)'], {}), '(1)\n', (44384, 44387), True, 'import numpy as np\n'), ((45208, 45227), 'numpy.max', 'np.max', (['ql_2d[:, t]'], {}), '(ql_2d[:, t])\n', (45214, 45227), True, 'import numpy as np\n'), ((45263, 45294), 'numpy.argmax', 'np.argmax', (['(ql_2d[:, t] > ql_min)'], {}), '(ql_2d[:, t] > ql_min)\n', (45272, 45294), True, 'import numpy as np\n'), ((47015, 47063), 'numpy.linspace', 'np.linspace', (['(0 + d_z_tmp / 2)', 'z_reg_orig_top', 'nz'], {}), '(0 + d_z_tmp / 2, z_reg_orig_top, nz)\n', (47026, 47063), True, 'import numpy as np\n'), ((47163, 47191), 'numpy.hstack', 'np.hstack', (['[[0], z_reg_orig]'], {}), '([[0], z_reg_orig])\n', (47172, 47191), True, 'import numpy as np\n'), ((47237, 47297), 'numpy.hstack', 'np.hstack', (['[scaling_factor_x_prof[0], scaling_factor_x_prof]'], {}), '([scaling_factor_x_prof[0], scaling_factor_x_prof])\n', (47246, 47297), True, 'import numpy as np\n'), ((47343, 47403), 'numpy.hstack', 'np.hstack', (['[scaling_factor_y_prof[0], scaling_factor_y_prof]'], {}), '([scaling_factor_y_prof[0], scaling_factor_y_prof])\n', (47352, 47403), True, 'import numpy as np\n'), ((47539, 47602), 'scipy.interpolate.interp1d', 'interp1d', (['z_reg_orig', 'scaling_factor_x_prof_ext'], {'kind': '"""nearest"""'}), "(z_reg_orig, scaling_factor_x_prof_ext, kind='nearest')\n", (47547, 47602), False, 'from scipy.interpolate import interp1d\n'), ((47625, 47688), 'scipy.interpolate.interp1d', 'interp1d', (['z_reg_orig', 'scaling_factor_y_prof_ext'], {'kind': '"""nearest"""'}), "(z_reg_orig, scaling_factor_y_prof_ext, kind='nearest')\n", (47633, 47688), False, 'from scipy.interpolate import interp1d\n'), ((49765, 49819), 'numpy.min', 'np.min', (['cl_base[cbl_cl_idx[t_chord_begin:t_chord_end]]'], {}), '(cl_base[cbl_cl_idx[t_chord_begin:t_chord_end]])\n', (49771, 49819), True, 'import numpy as np\n'), ((69978, 70007), 'numpy.transpose', 'np.transpose', (['w_3d', '(0, 2, 1)'], {}), '(w_3d, (0, 2, 1))\n', (69990, 70007), True, 'import numpy as np\n'), ((70035, 70065), 'numpy.transpose', 'np.transpose', (['ql_3d', '(0, 2, 1)'], {}), '(ql_3d, (0, 2, 1))\n', (70047, 70065), True, 'import numpy as np\n'), ((70092, 70123), 'numpy.transpose', 'np.transpose', (['var_3d', '(0, 2, 1)'], {}), '(var_3d, (0, 2, 1))\n', (70104, 70123), True, 'import numpy as np\n'), ((70896, 70908), 'gc.collect', 'gc.collect', ([], {}), '()\n', (70906, 70908), False, 'import gc\n'), ((70969, 71009), 'numpy.linspace', 'np.linspace', (['(0)', '(2 * nx * ny)', '(2 * nx * ny)'], {}), '(0, 2 * nx * ny, 2 * nx * ny)\n', (70980, 71009), True, 'import numpy as np\n'), ((71758, 71775), 'numpy.zeros', 'np.zeros', (['(nz, 1)'], {}), '((nz, 1))\n', (71766, 71775), True, 'import numpy as np\n'), ((71800, 71817), 'numpy.zeros', 'np.zeros', (['(nz, 1)'], {}), '((nz, 1))\n', (71808, 71817), True, 'import numpy as np\n'), ((71842, 71859), 'numpy.zeros', 'np.zeros', (['(nz, 1)'], {}), '((nz, 1))\n', (71850, 71859), True, 'import numpy as np\n'), ((71884, 71895), 'numpy.zeros', 'np.zeros', (['(1)'], {}), '(1)\n', (71892, 71895), True, 'import numpy as np\n'), ((72716, 72735), 'numpy.max', 'np.max', (['ql_2d[:, t]'], {}), '(ql_2d[:, t])\n', (72722, 72735), True, 'import numpy as np\n'), ((72771, 72802), 'numpy.argmax', 'np.argmax', (['(ql_2d[:, t] > ql_min)'], {}), '(ql_2d[:, t] > ql_min)\n', (72780, 72802), True, 'import numpy as np\n'), ((74299, 74318), 'numpy.mean', 'np.mean', (['bflux_s_1d'], {}), '(bflux_s_1d)\n', (74306, 74318), True, 'import numpy as np\n'), ((18446, 18494), 'numpy.mean', 'np.mean', (['bflux_s_1d[idx_beg_chord:idx_end_chord]'], {}), '(bflux_s_1d[idx_beg_chord:idx_end_chord])\n', (18453, 18494), True, 'import numpy as np\n'), ((18598, 18647), 'numpy.mean', 'np.mean', (['qtflux_s_1d[idx_beg_chord:idx_end_chord]'], {}), '(qtflux_s_1d[idx_beg_chord:idx_end_chord])\n', (18605, 18647), True, 'import numpy as np\n'), ((18734, 18784), 'numpy.mean', 'np.mean', (['thlflux_s_1d[idx_beg_chord:idx_end_chord]'], {}), '(thlflux_s_1d[idx_beg_chord:idx_end_chord])\n', (18741, 18784), True, 'import numpy as np\n'), ((20439, 20477), 'numpy.percentile', 'np.percentile', (['w_base_vec', 'percentiles'], {}), '(w_base_vec, percentiles)\n', (20452, 20477), True, 'import numpy as np\n'), ((20901, 20936), 'numpy.vstack', 'np.vstack', (['[chord_w_per, tmp_w_per]'], {}), '([chord_w_per, tmp_w_per])\n', (20910, 20936), True, 'import numpy as np\n'), ((20984, 21022), 'numpy.vstack', 'np.vstack', (['[chord_w_per, tmp_w_per_up]'], {}), '([chord_w_per, tmp_w_per_up])\n', (20993, 21022), True, 'import numpy as np\n'), ((30790, 30829), 'numpy.floor', 'np.floor', (['(idx_end_chord - idx_beg_chord)'], {}), '(idx_end_chord - idx_beg_chord)\n', (30798, 30829), True, 'import numpy as np\n'), ((47873, 47904), 'numpy.mean', 'np.mean', (['scaling_factor_x_inter'], {}), '(scaling_factor_x_inter)\n', (47880, 47904), True, 'import numpy as np\n'), ((47961, 47992), 'numpy.mean', 'np.mean', (['scaling_factor_y_inter'], {}), '(scaling_factor_y_inter)\n', (47968, 47992), True, 'import numpy as np\n'), ((74051, 74061), 'sys.exit', 'sys.exit', ([], {}), '()\n', (74059, 74061), False, 'import sys\n'), ((74574, 74594), 'numpy.mean', 'np.mean', (['qtflux_s_1d'], {}), '(qtflux_s_1d)\n', (74581, 74594), True, 'import numpy as np\n'), ((74718, 74739), 'numpy.mean', 'np.mean', (['thlflux_s_1d'], {}), '(thlflux_s_1d)\n', (74725, 74739), True, 'import numpy as np\n'), ((17784, 17826), 'numpy.mean', 'np.mean', (['u_2d[cl_base[ch_idx_l], ch_idx_l]'], {}), '(u_2d[cl_base[ch_idx_l], ch_idx_l])\n', (17791, 17826), True, 'import numpy as np\n'), ((17856, 17898), 'numpy.mean', 'np.mean', (['v_2d[cl_base[ch_idx_l], ch_idx_l]'], {}), '(v_2d[cl_base[ch_idx_l], ch_idx_l])\n', (17863, 17898), True, 'import numpy as np\n'), ((17928, 17960), 'numpy.sqrt', 'np.sqrt', (['(u_ref ** 2 + v_ref ** 2)'], {}), '(u_ref ** 2 + v_ref ** 2)\n', (17935, 17960), True, 'import numpy as np\n'), ((18251, 18300), 'numpy.percentile', 'np.percentile', (['cl_base[ch_idx_l]', 'base_percentile'], {}), '(cl_base[ch_idx_l], base_percentile)\n', (18264, 18300), True, 'import numpy as np\n'), ((19093, 19135), 'numpy.mean', 'np.mean', (['w_2d[cl_base[ch_idx_l], ch_idx_l]'], {}), '(w_2d[cl_base[ch_idx_l], ch_idx_l])\n', (19100, 19135), True, 'import numpy as np\n'), ((19171, 19217), 'numpy.mean', 'np.mean', (['w_2d[cl_base[ch_idx_l] - 1, ch_idx_l]'], {}), '(w_2d[cl_base[ch_idx_l] - 1, ch_idx_l])\n', (19178, 19217), True, 'import numpy as np\n'), ((19253, 19301), 'numpy.mean', 'np.mean', (['thl_2d[cl_base[ch_idx_l] - 1, ch_idx_l]'], {}), '(thl_2d[cl_base[ch_idx_l] - 1, ch_idx_l])\n', (19260, 19301), True, 'import numpy as np\n'), ((19810, 19851), 'numpy.mean', 'np.mean', (['thl_2d[cl_base_25_idx, ch_idx_l]'], {}), '(thl_2d[cl_base_25_idx, ch_idx_l])\n', (19817, 19851), True, 'import numpy as np\n'), ((19892, 19933), 'numpy.mean', 'np.mean', (['thl_2d[cl_base_75_idx, ch_idx_l]'], {}), '(thl_2d[cl_base_75_idx, ch_idx_l])\n', (19899, 19933), True, 'import numpy as np\n'), ((19970, 20017), 'numpy.mean', 'np.mean', (['qt_2d[cl_base[ch_idx_l] - 1, ch_idx_l]'], {}), '(qt_2d[cl_base[ch_idx_l] - 1, ch_idx_l])\n', (19977, 20017), True, 'import numpy as np\n'), ((20055, 20095), 'numpy.mean', 'np.mean', (['qt_2d[cl_base_75_idx, ch_idx_l]'], {}), '(qt_2d[cl_base_75_idx, ch_idx_l])\n', (20062, 20095), True, 'import numpy as np\n'), ((20135, 20175), 'numpy.mean', 'np.mean', (['qt_2d[cl_base_25_idx, ch_idx_l]'], {}), '(qt_2d[cl_base_25_idx, ch_idx_l])\n', (20142, 20175), True, 'import numpy as np\n'), ((20216, 20261), 'numpy.sum', 'np.sum', (['w_2d[cl_base[ch_idx_l] - 1, ch_idx_l]'], {}), '(w_2d[cl_base[ch_idx_l] - 1, ch_idx_l])\n', (20222, 20261), True, 'import numpy as np\n'), ((20367, 20404), 'numpy.mean', 'np.mean', (['w_base_vec[w_base_vec > 0.0]'], {}), '(w_base_vec[w_base_vec > 0.0])\n', (20374, 20404), True, 'import numpy as np\n'), ((20595, 20651), 'numpy.percentile', 'np.percentile', (['w_base_vec[w_base_vec > 0.0]', 'percentiles'], {}), '(w_base_vec[w_base_vec > 0.0], percentiles)\n', (20608, 20651), True, 'import numpy as np\n'), ((20714, 20737), 'numpy.zeros', 'np.zeros', (['n_percentiles'], {}), '(n_percentiles)\n', (20722, 20737), True, 'import numpy as np\n'), ((73757, 73808), 'numpy.percentile', 'np.percentile', (['cl_base[cbl_cl_idx]', 'base_percentile'], {}), '(cl_base[cbl_cl_idx], base_percentile)\n', (73770, 73808), True, 'import numpy as np\n'), ((21107, 21130), 'numpy.mean', 'np.mean', (['t_1d[ch_idx_l]'], {}), '(t_1d[ch_idx_l])\n', (21114, 21130), True, 'import numpy as np\n'), ((52025, 52104), 'numpy.percentile', 'np.percentile', (['cl_base[cbl_cl_idx[t_chord_begin:t_cloudy_idx]]', 'base_percentile'], {}), '(cl_base[cbl_cl_idx[t_chord_begin:t_cloudy_idx]], base_percentile)\n', (52038, 52104), True, 'import numpy as np\n'), ((52518, 52566), 'numpy.mean', 'np.mean', (['bflux_s_1d[idx_beg_chord:idx_end_chord]'], {}), '(bflux_s_1d[idx_beg_chord:idx_end_chord])\n', (52525, 52566), True, 'import numpy as np\n'), ((55553, 55567), 'numpy.mean', 'np.mean', (['w_tmp'], {}), '(w_tmp)\n', (55560, 55567), True, 'import numpy as np\n'), ((19444, 19493), 'numpy.percentile', 'np.percentile', (['cl_base[ch_idx_l]', 'base_percentile'], {}), '(cl_base[ch_idx_l], base_percentile)\n', (19457, 19493), True, 'import numpy as np\n'), ((50839, 50926), 'numpy.abs', 'np.abs', (['(t_1d - (time_beg_chord - curtain_extra * (time_end_chord - time_beg_chord)))'], {}), '(t_1d - (time_beg_chord - curtain_extra * (time_end_chord -\n time_beg_chord)))\n', (50845, 50926), True, 'import numpy as np\n'), ((50968, 51055), 'numpy.abs', 'np.abs', (['(t_1d - (time_end_chord + curtain_extra * (time_end_chord - time_beg_chord)))'], {}), '(t_1d - (time_end_chord + curtain_extra * (time_end_chord -\n time_beg_chord)))\n', (50974, 51055), True, 'import numpy as np\n'), ((52894, 52943), 'numpy.mean', 'np.mean', (['qtflux_s_1d[idx_beg_chord:idx_end_chord]'], {}), '(qtflux_s_1d[idx_beg_chord:idx_end_chord])\n', (52901, 52943), True, 'import numpy as np\n'), ((53103, 53153), 'numpy.mean', 'np.mean', (['thlflux_s_1d[idx_beg_chord:idx_end_chord]'], {}), '(thlflux_s_1d[idx_beg_chord:idx_end_chord])\n', (53110, 53153), True, 'import numpy as np\n'), ((55714, 55728), 'numpy.mean', 'np.mean', (['w_tmp'], {}), '(w_tmp)\n', (55721, 55728), True, 'import numpy as np\n'), ((56948, 56990), 'numpy.mean', 'np.mean', (['u_2d[cl_base[ch_idx_l], ch_idx_l]'], {}), '(u_2d[cl_base[ch_idx_l], ch_idx_l])\n', (56955, 56990), True, 'import numpy as np\n'), ((57028, 57070), 'numpy.mean', 'np.mean', (['v_2d[cl_base[ch_idx_l], ch_idx_l]'], {}), '(v_2d[cl_base[ch_idx_l], ch_idx_l])\n', (57035, 57070), True, 'import numpy as np\n'), ((57108, 57140), 'numpy.sqrt', 'np.sqrt', (['(u_ref ** 2 + v_ref ** 2)'], {}), '(u_ref ** 2 + v_ref ** 2)\n', (57115, 57140), True, 'import numpy as np\n'), ((19560, 19609), 'numpy.percentile', 'np.percentile', (['cl_base[ch_idx_l]', 'base_percentile'], {}), '(cl_base[ch_idx_l], base_percentile)\n', (19573, 19609), True, 'import numpy as np\n'), ((55935, 55949), 'numpy.mean', 'np.mean', (['w_tmp'], {}), '(w_tmp)\n', (55942, 55949), True, 'import numpy as np\n'), ((58036, 58050), 'numpy.mean', 'np.mean', (['w_tmp'], {}), '(w_tmp)\n', (58043, 58050), True, 'import numpy as np\n'), ((57595, 57630), 'numpy.abs', 'np.abs', (['(chord_length - mid_bin_size)'], {}), '(chord_length - mid_bin_size)\n', (57601, 57630), True, 'import numpy as np\n'), ((58251, 58265), 'numpy.mean', 'np.mean', (['w_tmp'], {}), '(w_tmp)\n', (58258, 58265), True, 'import numpy as np\n'), ((58534, 58548), 'numpy.mean', 'np.mean', (['w_tmp'], {}), '(w_tmp)\n', (58541, 58548), True, 'import numpy as np\n')]
#! /usr/bin/env python3 """Parse through the simulated sequencing group specific kmer counts.""" import argparse as ap from collections import OrderedDict import glob import gzip import os import sys import time import numpy as np import multiprocessing as mp SAMPLES = OrderedDict() KMERS = {} HAMMING = OrderedDict() SAMPLE_COLS = [ 'sample', 'is_bcg', 'is_ba', 'has_lethal', 'simulated_coverage', 'group', 'total_kmers', 'tp', 'tn', 'fp', 'fn', 'kmer_cov_min', 'kmer_cov_mean', 'kmer_cov_median', 'kmer_cov_max', 'non_zero_kmer_cov_min', 'non_zero_kmer_cov_mean', 'non_zero_kmer_cov_median', 'non_zero_kmer_cov_max' ] KMER_COLS = [ 'kmer', 'simulated_coverage', 'group', 'hamming_distance', 'tp', 'tn', 'fp', 'fn', 'group_kmer_cov_min', 'group_kmer_cov_mean', 'group_kmer_cov_median', 'group_kmer_cov_max', 'non_zero_group_kmer_cov_min', 'non_zero_group_kmer_cov_mean', 'non_zero_group_kmer_cov_median', 'non_zero_group_kmer_cov_max', 'outgroup_kmer_cov_min', 'outgroup_kmer_cov_mean', 'outgroup_kmer_cov_median', 'outgroup_kmer_cov_max', 'non_zero_outgroup_kmer_cov_min', 'non_zero_outgroup_kmer_cov_mean', 'non_zero_outgroup_kmer_cov_median', 'non_zero_outgroup_kmer_cov_max' ] def get_group_status(sample, group): """Return if a sample is within a group or not.""" within_group = None if group == 'ba': within_group = True if SAMPLES[sample]['is_ba'] == 'True' else False elif group == 'bcg': within_group = True if SAMPLES[sample]['is_bcg'] == 'True' else False else: # lef within_group = True if SAMPLES[sample]['has_lethal'] else False return within_group def get_coverage_stats(coverage): """Return summary stats of a set of coverages.""" non_zero = [c for c in coverage if c] np_array = np.array(coverage) non_zero_array = np.array(non_zero) return { 'min': min(coverage) if coverage else 0, 'median': int(np.median(np_array)) if coverage else 0, 'mean': "{0:.4f}".format(np.mean(np_array)) if coverage else 0, 'max': max(coverage) if coverage else 0, 'non_zero_min': min(non_zero_array) if non_zero else 0, 'non_zero_median': int(np.median(non_zero_array)) if non_zero else 0, 'non_zero_mean': int(round(np.mean(non_zero_array))) if non_zero else 0, 'non_zero_max': max(non_zero_array) if non_zero else 0, } def reverse_complement(seq): """Reverse complement a DNA sequence.""" complement = { 'A': 'T', 'T': 'A', 'G': 'C', 'C': 'G', 'a': 't', 't': 'a', 'g': 'c', 'c': 'g' } return ''.join([complement[b] for b in seq[::-1]]) def parse_counts(counts, sample, coverage, group, skip_kmers=False, filter_kmers=False): """Parse kmer counts.""" within_group = get_group_status(sample, group) sample_row = {'coverages': [], 'tp': 0, 'tn': 0, 'fp': 0, 'fn': 0} with gzip.open(counts, 'r') as count_handle: for line in count_handle: kmer, count = line.decode().rstrip().split() count = int(count) parse = True if filter_kmers: parse = kmer in KMERS or reverse_complement(kmer) in KMERS elif not skip_kmers: if kmer not in KMERS: kmer = reverse_complement(kmer) if within_group: KMERS[kmer][coverage]['group_coverages'].append(count) if count: KMERS[kmer][coverage]['tp'] += 1 else: KMERS[kmer][coverage]['fn'] += 1 else: KMERS[kmer][coverage]['outgroup_coverages'].append(count) if count: KMERS[kmer][coverage]['fp'] += 1 else: KMERS[kmer][coverage]['tn'] += 1 if parse: sample_row['coverages'].append(count) if within_group: if count: sample_row['tp'] += 1 else: sample_row['fn'] += 1 else: if count: sample_row['fp'] += 1 else: sample_row['tn'] += 1 coverage_stats = get_coverage_stats(sample_row['coverages']) SAMPLES[sample]['results'].append({ 'simulated_coverage': coverage, 'within_group': within_group, 'tp': sample_row['tp'], 'tn': sample_row['tn'], 'fp': sample_row['fp'], 'fn': sample_row['fn'], 'kmer_cov_min': coverage_stats['min'], 'kmer_cov_mean': coverage_stats['mean'], 'kmer_cov_median': coverage_stats['median'], 'kmer_cov_max': coverage_stats['max'], 'non_zero_kmer_cov_min': coverage_stats['non_zero_min'], 'non_zero_kmer_cov_mean': coverage_stats['non_zero_mean'], 'non_zero_kmer_cov_median': coverage_stats['non_zero_median'], 'non_zero_kmer_cov_max': coverage_stats['non_zero_max'], }) def parse_kmers(kmers, coverages, skip_kmers=False, has_hamming=True): with open(kmers, 'r') as kmer_handle: for line in kmer_handle: if line.startswith(">"): line = line.rstrip().replace(">", "") kmer, distance = line.split("-") if not has_hamming: distance = False KMERS[kmer] = OrderedDict() HAMMING[kmer] = distance if not skip_kmers: for coverage in coverages: KMERS[kmer][coverage] = { 'group_coverages': [], 'outgroup_coverages': [], 'tp': 0, 'tn': 0, 'fp': 0, 'fn': 0 } def parse_summary(summary): """Parse Summary file.""" cols = None with open(summary, 'r') as summary_handle: # Column Names: # accession, gi, is_bcg, is_ba, species, genome_size, description for line in summary_handle: line = line.rstrip() if line.startswith('#'): cols = line.replace('#', '').split('\t') else: row = dict(zip(cols, line.split('\t'))) SAMPLES[row['accession']] = row if row['accession'] == 'NZ_CP009941': # NZ_CP009941 - Bacillus cereus w/ lef on chromosome SAMPLES[row['accession']]['has_lethal'] = True else: SAMPLES[row['accession']]['has_lethal'] = False SAMPLES[row['accession']]['results'] = [] def print_sample_summary(file_output): """Print the final per sample summaries.""" with open(file_output, 'w') as output_handle: output_handle.write(("\t".join(SAMPLE_COLS))) output_handle.write("\n") for sample in SAMPLES: if SAMPLES[sample]['results']: for result in SAMPLES[sample]['results']: row = { 'sample': sample, 'is_bcg': SAMPLES[sample]['is_bcg'], 'is_ba': SAMPLES[sample]['is_ba'], 'has_lethal': SAMPLES[sample]['has_lethal'], 'simulated_coverage': result['simulated_coverage'], 'group': args.group, 'within_group': result['within_group'], 'total_kmers': total_kmers, 'tp': result['tp'], 'tn': result['tn'], 'fp': result['fp'], 'fn': result['fn'], 'kmer_cov_min': result['kmer_cov_min'], 'kmer_cov_mean': result['kmer_cov_mean'], 'kmer_cov_median': result['kmer_cov_median'], 'kmer_cov_max': result['kmer_cov_max'], 'non_zero_kmer_cov_min': result['non_zero_kmer_cov_min'], 'non_zero_kmer_cov_mean': result['non_zero_kmer_cov_mean'], 'non_zero_kmer_cov_median': result['non_zero_kmer_cov_median'], 'non_zero_kmer_cov_max': result['non_zero_kmer_cov_max'] } output_handle.write(("\t".join([ str(row[col]) for col in SAMPLE_COLS ]))) output_handle.write("\n") def print_kmer_summary(file_output): """Print the final per kmer summaries.""" with open(file_output, 'w') as output_handle: output_handle.write(("\t".join(KMER_COLS))) output_handle.write("\n") for kmer, coverages in KMERS.items(): for coverage in coverages: within_group = get_coverage_stats( KMERS[kmer][coverage]['group_coverages'] ) outgroup = get_coverage_stats( KMERS[kmer][coverage]['outgroup_coverages'] ) row = { 'kmer': kmer, 'simulated_coverage': coverage, 'group': args.group, 'hamming_distance': HAMMING[kmer], 'tp': KMERS[kmer][coverage]['tp'], 'tn': KMERS[kmer][coverage]['tn'], 'fp': KMERS[kmer][coverage]['fp'], 'fn': KMERS[kmer][coverage]['fn'], 'group_kmer_cov_min': within_group['min'], 'group_kmer_cov_mean': within_group['mean'], 'group_kmer_cov_median': within_group['median'], 'group_kmer_cov_max': within_group['max'], 'non_zero_group_kmer_cov_min': within_group['non_zero_min'], 'non_zero_group_kmer_cov_mean': within_group['non_zero_mean'], 'non_zero_group_kmer_cov_median': within_group['non_zero_median'], 'non_zero_group_kmer_cov_max': within_group['non_zero_max'], 'outgroup_kmer_cov_min': outgroup['min'], 'outgroup_kmer_cov_mean': outgroup['mean'], 'outgroup_kmer_cov_median': outgroup['median'], 'outgroup_kmer_cov_max': outgroup['max'], 'non_zero_outgroup_kmer_cov_min': outgroup['non_zero_min'], 'non_zero_outgroup_kmer_cov_mean': outgroup['non_zero_mean'], 'non_zero_outgroup_kmer_cov_median': outgroup['non_zero_median'], 'non_zero_outgroup_kmer_cov_max': outgroup['non_zero_max'], } output_handle.write(("\t".join([ str(row[col]) for col in KMER_COLS ]))) output_handle.write("\n") def read_lines(input_file): """Return lines in a text file as a list.""" lines = [] with open(input_file, 'r') as input_handle: for line in input_handle: lines.append(line.rstrip()) return lines def parse_filter_kmers(kmers): with open(kmers, 'r') as kmer_handle: for line in kmer_handle: if line.startswith(">"): line = line.rstrip().replace(">", "") KMERS[line.split("-")[0]] = True if __name__ == '__main__': parser = ap.ArgumentParser( prog='summarize-kmer-counts.py', conflict_handler='resolve', description=("Summarize kmer counts of each simulation.") ) parser.add_argument('summary', type=str, metavar="SUMMARY", help='Summary of Bacillus genomes.') parser.add_argument('directory', type=str, metavar="SIMUALTION_DIR", help='Directory with group specific 31-mer counts.') parser.add_argument('group', type=str, metavar="GROUP", help='Which group to parse (ba, bcg or lef).') parser.add_argument('kmers', type=str, metavar="KMERS", help='Group specific k-mers.') parser.add_argument('coverages', type=str, metavar="COVERAGES", help=('Coverages to subsample to.')) parser.add_argument('outdir', type=str, metavar="OUTDIR", help='Directory to output to.') parser.add_argument('--cpu', default=1, type=int, metavar="INT", help='Number of cores to use (Default: 1)') parser.add_argument('--single_sample', type=str, metavar="STR", help='Process a single sample.') parser.add_argument('--skip_kmers', action='store_true', default=False, help='Skip kmer processing.') parser.add_argument('--filter', action='store_true', default=False, help='Filter counts based on input kmers.') args = parser.parse_args() if args.group not in ['ba', 'bcg', 'lef']: raise Exception("GROUPS must be 'ba', 'bcg' or 'lef'") coverages = read_lines(args.coverages) print("Parsing Summary") parse_summary(args.summary) print("Parsing Kmers") if args.filter: print("Filtering Kmers") args.skip_kmers = True parse_filter_kmers(args.kmers) else: print("Parsing Kmers") parse_kmers(args.kmers, coverages, skip_kmers=args.skip_kmers, has_hamming=False if args.group == 'lef' else True) total_kmers = len(KMERS) current = 1 samples = list(SAMPLES.keys()) if args.single_sample: samples = [args.single_sample] total = len(samples) for sample in samples: path = "{0}/{1}".format(args.directory, sample) if os.path.exists(path): print("Working on {0} ({1} of {2})".format(sample, current, total)) current += 1 count_files = sorted(glob.glob( "{0}/*-{1}.txt.gz".format(path, args.group) )) for count_file in count_files: coverage = os.path.basename(count_file).split('-')[1] parse_counts(count_file, sample, coverage, args.group, skip_kmers=args.skip_kmers, filter_kmers=args.filter) print("Output sample summary") if args.single_sample: print_sample_summary("{0}/count-summary-{1}-{2}.txt".format( args.outdir, args.single_sample, args.group )) else: print_sample_summary("{0}/count-summary-sample-{1}.txt".format( args.outdir, args.group )) if not args.skip_kmers: print("Output kmer summary") if args.single_sample: print_kmer_summary("{0}/count-summary-kmer-{1}-{2}.txt".format( args.outdir, args.single_sample, args.group )) else: print_kmer_summary("{0}/count-summary-kmer-{1}.txt".format( args.outdir, args.group ))
[ "os.path.exists", "collections.OrderedDict", "numpy.median", "numpy.mean", "argparse.ArgumentParser", "gzip.open", "numpy.array", "os.path.basename" ]
[((271, 284), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (282, 284), False, 'from collections import OrderedDict\n'), ((306, 319), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (317, 319), False, 'from collections import OrderedDict\n'), ((1866, 1884), 'numpy.array', 'np.array', (['coverage'], {}), '(coverage)\n', (1874, 1884), True, 'import numpy as np\n'), ((1906, 1924), 'numpy.array', 'np.array', (['non_zero'], {}), '(non_zero)\n', (1914, 1924), True, 'import numpy as np\n'), ((11465, 11605), 'argparse.ArgumentParser', 'ap.ArgumentParser', ([], {'prog': '"""summarize-kmer-counts.py"""', 'conflict_handler': '"""resolve"""', 'description': '"""Summarize kmer counts of each simulation."""'}), "(prog='summarize-kmer-counts.py', conflict_handler=\n 'resolve', description='Summarize kmer counts of each simulation.')\n", (11482, 11605), True, 'import argparse as ap\n'), ((2983, 3005), 'gzip.open', 'gzip.open', (['counts', '"""r"""'], {}), "(counts, 'r')\n", (2992, 3005), False, 'import gzip\n'), ((13773, 13793), 'os.path.exists', 'os.path.exists', (['path'], {}), '(path)\n', (13787, 13793), False, 'import os\n'), ((2009, 2028), 'numpy.median', 'np.median', (['np_array'], {}), '(np_array)\n', (2018, 2028), True, 'import numpy as np\n'), ((2083, 2100), 'numpy.mean', 'np.mean', (['np_array'], {}), '(np_array)\n', (2090, 2100), True, 'import numpy as np\n'), ((2266, 2291), 'numpy.median', 'np.median', (['non_zero_array'], {}), '(non_zero_array)\n', (2275, 2291), True, 'import numpy as np\n'), ((5548, 5561), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (5559, 5561), False, 'from collections import OrderedDict\n'), ((2348, 2371), 'numpy.mean', 'np.mean', (['non_zero_array'], {}), '(non_zero_array)\n', (2355, 2371), True, 'import numpy as np\n'), ((14089, 14117), 'os.path.basename', 'os.path.basename', (['count_file'], {}), '(count_file)\n', (14105, 14117), False, 'import os\n')]
#!/usr/bin/env python3 -u # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Train a new model on one or across multiple GPUs. """ import collections import logging import math import os import sys import numpy as np import torch from fairseq import ( checkpoint_utils, distributed_utils, options, quantization_utils, tasks, utils, ) from fairseq import meters from fairseq.checkpoint_utils import checkpoint_paths from fairseq.data import iterators from fairseq.file_io import PathManager from fairseq.logging import metrics, progress_bar from fairseq.model_parallel.megatron_trainer import MegatronTrainer from fairseq.trainer import Trainer logging.basicConfig( format="%(asctime)s | %(levelname)s | %(name)s | %(message)s", datefmt="%Y-%m-%d %H:%M:%S", level=os.environ.get("LOGLEVEL", "INFO").upper(), stream=sys.stdout, ) logger = logging.getLogger("fairseq_cli.train") class Saver: def __init__(self): self.best = None self.keep_best = [] def save_checkpoint(self, args, trainer, epoch_itr, val_loss): # only one worker should attempt to create the required dir if args.distributed_rank == 0: os.makedirs(args.save_dir, exist_ok=True) prev_best = val_loss if self.best is None else self.best if val_loss is not None: best_function = max if args.maximize_best_checkpoint_metric else min self.best = best_function(val_loss, prev_best) if args.no_save: return trainer.consolidate_optimizer() if not trainer.is_data_parallel_master: return def is_better(a, b): return a >= b if args.maximize_best_checkpoint_metric else a <= b write_timer = meters.StopwatchMeter() write_timer.start() epoch = epoch_itr.epoch end_of_epoch = epoch_itr.end_of_epoch() updates = trainer.get_num_updates() suffix = getattr(args, "checkpoint_suffix", "") checkpoint_conds = collections.OrderedDict() save_epoch_checkpoint = ( end_of_epoch and not args.no_epoch_checkpoints and epoch % args.save_interval == 0 ) checkpoint_conds["checkpoint{}{}.pt".format(epoch, suffix)] = save_epoch_checkpoint checkpoint_conds["checkpoint_{}_{}{}.pt".format(epoch, updates, suffix)] = ( not save_epoch_checkpoint and args.save_interval_updates > 0 and updates % args.save_interval_updates == 0 ) checkpoint_conds["checkpoint_best{}.pt".format(suffix)] = val_loss is not None and ( self.best is None or is_better(val_loss, self.best) ) checkpoint_conds[ "checkpoint_last{}.pt".format(suffix) ] = not args.no_last_checkpoints extra_state = {"train_iterator": epoch_itr.state_dict(), "val_loss": val_loss} if self.best is not None: extra_state.update({"best": self.best}) if args.keep_best_checkpoints > 0 and (len(self.keep_best) < args.keep_best_checkpoints or ( val_loss is not None and not is_better(self.keep_best[-1][0], val_loss))): ckpt_name = "checkpoint{}{}.best_{:.4f}.pt".format(epoch, suffix, val_loss) if save_epoch_checkpoint \ else "checkpoint_{}_{}{}.best_{:.4f}.pt".format(epoch, updates, suffix, val_loss) checkpoint_conds[ckpt_name] = True self.keep_best.append((val_loss, ckpt_name)) self.keep_best = sorted(self.keep_best) checkpoints = [ os.path.join(args.save_dir, fn) for fn, cond in checkpoint_conds.items() if cond ] if len(checkpoints) > 0: trainer.save_checkpoint(checkpoints[0], extra_state) for cp in checkpoints[1:]: PathManager.copy(checkpoints[0], cp, overwrite=True) write_timer.stop() logger.info( "saved checkpoint {} (epoch {} @ {} updates, score {}) (writing took {} seconds)".format( checkpoints[0], epoch, updates, val_loss, write_timer.sum ) ) if not end_of_epoch and args.keep_interval_updates > 0: # remove old checkpoints; checkpoints are sorted in descending order checkpoints = checkpoint_paths( args.save_dir, pattern=r"checkpoint_\d+_(\d+)\.pt" ) for old_chk in checkpoints[args.keep_interval_updates:]: if os.path.lexists(old_chk): os.remove(old_chk) if args.keep_last_epochs > 0: # remove old epoch checkpoints; checkpoints are sorted in descending order checkpoints = checkpoint_paths(args.save_dir, pattern=r"checkpoint(\d+)\.pt") for old_chk in checkpoints[args.keep_last_epochs:]: if os.path.lexists(old_chk): os.remove(old_chk) if len(self.keep_best) > args.keep_best_checkpoints: for _, x in self.keep_best[args.keep_best_checkpoints:]: x = os.path.join(args.save_dir, x) if os.path.lexists(x): os.remove(x) self.keep_best = self.keep_best[:args.keep_best_checkpoints] def main(args): saver = Saver() utils.import_user_module(args) assert ( args.max_tokens is not None or args.batch_size is not None ), "Must specify batch size either with --max-tokens or --batch-size" metrics.reset() np.random.seed(args.seed) utils.set_torch_seed(args.seed) if distributed_utils.is_master(args): checkpoint_utils.verify_checkpoint_directory(args.save_dir) # Print args logger.info(args) # Setup task, e.g., translation, language modeling, etc. task = tasks.setup_task(args) # Load valid dataset (we load training data below, based on the latest checkpoint) for valid_sub_split in args.valid_subset.split(","): task.load_dataset(valid_sub_split, combine=False, epoch=1) # Build model and criterion model = task.build_model(args) criterion = task.build_criterion(args) logger.info(model) logger.info("task: {} ({})".format(args.task, task.__class__.__name__)) logger.info("model: {} ({})".format(args.arch, model.__class__.__name__)) logger.info( "criterion: {} ({})".format(args.criterion, criterion.__class__.__name__) ) logger.info( "num. model params: {} (num. trained: {})".format( sum(p.numel() for p in model.parameters()), sum(p.numel() for p in model.parameters() if p.requires_grad), ) ) # (optionally) Configure quantization if args.quantization_config_path is not None: quantizer = quantization_utils.Quantizer( config_path=args.quantization_config_path, max_epoch=args.max_epoch, max_update=args.max_update, ) else: quantizer = None # Build trainer if args.model_parallel_size == 1: trainer = Trainer(args, task, model, criterion, quantizer) else: trainer = MegatronTrainer(args, task, model, criterion) logger.info( "training on {} devices (GPUs/TPUs)".format(args.distributed_world_size) ) logger.info( "max tokens per GPU = {} and max sentences per GPU = {}".format( args.max_tokens, args.batch_size ) ) # Load the latest checkpoint if one is available and restore the # corresponding train iterator extra_state, epoch_itr = checkpoint_utils.load_checkpoint( args, trainer, # don't cache epoch iterators for sharded datasets disable_iterator_cache=task.has_sharded_data("train"), ) # Train until the learning rate gets too small max_epoch = args.max_epoch or math.inf lr = trainer.get_lr() train_meter = meters.StopwatchMeter() train_meter.start() while lr > args.min_lr and epoch_itr.next_epoch_idx <= max_epoch: # train for one epoch valid_losses, should_stop = train(args, trainer, task, epoch_itr, saver) if should_stop: break # only use first validation loss to update the learning rate lr = trainer.lr_step(epoch_itr.epoch, valid_losses[0]) epoch_itr = trainer.get_train_iterator( epoch_itr.next_epoch_idx, # sharded data: get train iterator for next epoch load_dataset=task.has_sharded_data("train"), # don't cache epoch iterators for sharded datasets disable_iterator_cache=task.has_sharded_data("train"), ) train_meter.stop() logger.info("done training in {:.1f} seconds".format(train_meter.sum)) def should_stop_early(args, valid_loss): # skip check if no validation was done in the current epoch if valid_loss is None: return False if args.patience <= 0: return False def is_better(a, b): return a > b if args.maximize_best_checkpoint_metric else a < b prev_best = getattr(should_stop_early, "best", None) if prev_best is None or is_better(valid_loss, prev_best): should_stop_early.best = valid_loss should_stop_early.num_runs = 0 return False else: should_stop_early.num_runs += 1 if should_stop_early.num_runs >= args.patience: logger.info( "early stop since valid performance hasn't improved for last {} runs".format( args.patience ) ) return True else: return False @metrics.aggregate("train") def train(args, trainer, task, epoch_itr, saver): """Train the model for one epoch and return validation losses.""" # Initialize data iterator itr = epoch_itr.next_epoch_itr( fix_batches_to_gpus=args.fix_batches_to_gpus, shuffle=(epoch_itr.next_epoch_idx > args.curriculum), ) update_freq = ( args.update_freq[epoch_itr.epoch - 1] if epoch_itr.epoch <= len(args.update_freq) else args.update_freq[-1] ) itr = iterators.GroupedIterator(itr, update_freq) if getattr(args, "tpu", False): itr = utils.tpu_data_loader(itr) progress = progress_bar.progress_bar( itr, log_format=args.log_format, log_interval=args.log_interval, epoch=epoch_itr.epoch, tensorboard_logdir=( args.tensorboard_logdir if distributed_utils.is_master(args) else None ), default_log_format=("tqdm" if not args.no_progress_bar else "simple"), ) trainer.begin_epoch(epoch_itr.epoch) valid_losses = [None] valid_subsets = args.valid_subset.split(",") should_stop = False num_updates = trainer.get_num_updates() for i, samples in enumerate(progress): with metrics.aggregate("train_inner"), torch.autograd.profiler.record_function( "train_step-%d" % i ): log_output = trainer.train_step(samples) if log_output is not None: # not OOM, overflow, ... # log mid-epoch stats num_updates = trainer.get_num_updates() if num_updates % args.log_interval == 0: stats = get_training_stats(metrics.get_smoothed_values("train_inner")) progress.log(stats, tag="train_inner", step=num_updates) # reset mid-epoch stats after each log interval # the end-of-epoch stats will still be preserved metrics.reset_meters("train_inner") end_of_epoch = not itr.has_next() valid_losses, should_stop = validate_and_save( args, trainer, task, epoch_itr, valid_subsets, end_of_epoch, saver ) if should_stop: break # log end-of-epoch stats logger.info("end of epoch {} (average epoch stats below)".format(epoch_itr.epoch)) stats = get_training_stats(metrics.get_smoothed_values("train")) progress.print(stats, tag="train", step=num_updates) # reset epoch-level meters metrics.reset_meters("train") return valid_losses, should_stop def validate_and_save(args, trainer, task, epoch_itr, valid_subsets, end_of_epoch, saver): num_updates = trainer.get_num_updates() max_update = args.max_update or math.inf do_save = ( (end_of_epoch and epoch_itr.epoch % args.save_interval == 0) or num_updates >= max_update or ( args.save_interval_updates > 0 and num_updates > 0 and num_updates % args.save_interval_updates == 0 and num_updates >= args.validate_after_updates ) ) do_validate = ( (not end_of_epoch and do_save) # validate during mid-epoch saves or (end_of_epoch and epoch_itr.epoch % args.validate_interval == 0) or num_updates >= max_update or ( args.validate_interval_updates > 0 and num_updates > 0 and num_updates % args.validate_interval_updates == 0 ) ) and not args.disable_validation # Validate valid_losses = [None] if do_validate: valid_losses = validate(args, trainer, task, epoch_itr, valid_subsets, saver) # Stopping conditions should_stop = ( should_stop_early(args, valid_losses[0]) or num_updates >= max_update or ( args.stop_time_hours > 0 and trainer.cumulative_training_time() / (60 * 60) > args.stop_time_hours ) ) # Save checkpoint if do_save or should_stop: logger.info("begin save checkpoint") saver.save_checkpoint(args, trainer, epoch_itr, valid_losses[0]) return valid_losses, should_stop def get_training_stats(stats): stats["wall"] = round(metrics.get_meter("default", "wall").elapsed_time, 0) return stats def validate(args, trainer, task, epoch_itr, subsets, saver): """Evaluate the model on the validation set(s) and return the losses.""" if args.fixed_validation_seed is not None: # set fixed seed for every validation utils.set_torch_seed(args.fixed_validation_seed) trainer.begin_valid_epoch(epoch_itr.epoch) valid_losses = [] for subset in subsets: logger.info('begin validation on "{}" subset'.format(subset)) # Initialize data iterator itr = trainer.get_valid_iterator(subset).next_epoch_itr(shuffle=False) if getattr(args, "tpu", False): itr = utils.tpu_data_loader(itr) progress = progress_bar.progress_bar( itr, log_format=args.log_format, log_interval=args.log_interval, epoch=epoch_itr.epoch, prefix=f"valid on '{subset}' subset", tensorboard_logdir=( args.tensorboard_logdir if distributed_utils.is_master(args) else None ), default_log_format=("tqdm" if not args.no_progress_bar else "simple"), ) # create a new root metrics aggregator so validation metrics # don't pollute other aggregators (e.g., train meters) with metrics.aggregate(new_root=True) as agg: for sample in progress: trainer.valid_step(sample) # log validation stats stats = get_valid_stats(args, trainer, agg.get_smoothed_values(), saver) progress.print(stats, tag=subset, step=trainer.get_num_updates()) valid_losses.append(stats[args.best_checkpoint_metric]) return valid_losses def get_valid_stats(args, trainer, stats, saver): stats["num_updates"] = trainer.get_num_updates() if hasattr(saver.save_checkpoint, "best"): key = "best_{0}".format(args.best_checkpoint_metric) best_function = max if args.maximize_best_checkpoint_metric else min stats[key] = best_function( saver.save_checkpoint.best, stats[args.best_checkpoint_metric] ) return stats def cli_main(modify_parser=None): parser = options.get_training_parser() args = options.parse_args_and_arch(parser, modify_parser=modify_parser) if args.profile: with torch.cuda.profiler.profile(): with torch.autograd.profiler.emit_nvtx(): distributed_utils.call_main(args, main) else: distributed_utils.call_main(args, main) if __name__ == "__main__": cli_main()
[ "logging.getLogger", "fairseq.options.parse_args_and_arch", "fairseq.logging.metrics.get_meter", "fairseq.options.get_training_parser", "fairseq.checkpoint_utils.checkpoint_paths", "torch.autograd.profiler.record_function", "fairseq.logging.metrics.reset", "os.remove", "os.path.lexists", "torch.cuda.profiler.profile", "numpy.random.seed", "fairseq.file_io.PathManager.copy", "fairseq.logging.metrics.aggregate", "collections.OrderedDict", "fairseq.distributed_utils.call_main", "fairseq.trainer.Trainer", "fairseq.utils.import_user_module", "fairseq.data.iterators.GroupedIterator", "fairseq.checkpoint_utils.verify_checkpoint_directory", "fairseq.distributed_utils.is_master", "fairseq.quantization_utils.Quantizer", "fairseq.meters.StopwatchMeter", "torch.autograd.profiler.emit_nvtx", "os.makedirs", "fairseq.tasks.setup_task", "os.path.join", "os.environ.get", "fairseq.utils.set_torch_seed", "fairseq.model_parallel.megatron_trainer.MegatronTrainer", "fairseq.utils.tpu_data_loader", "fairseq.logging.metrics.get_smoothed_values", "fairseq.logging.metrics.reset_meters" ]
[((1010, 1048), 'logging.getLogger', 'logging.getLogger', (['"""fairseq_cli.train"""'], {}), "('fairseq_cli.train')\n", (1027, 1048), False, 'import logging\n'), ((9829, 9855), 'fairseq.logging.metrics.aggregate', 'metrics.aggregate', (['"""train"""'], {}), "('train')\n", (9846, 9855), False, 'from fairseq.logging import metrics, progress_bar\n'), ((5502, 5532), 'fairseq.utils.import_user_module', 'utils.import_user_module', (['args'], {}), '(args)\n', (5526, 5532), False, 'from fairseq import checkpoint_utils, distributed_utils, options, quantization_utils, tasks, utils\n'), ((5697, 5712), 'fairseq.logging.metrics.reset', 'metrics.reset', ([], {}), '()\n', (5710, 5712), False, 'from fairseq.logging import metrics, progress_bar\n'), ((5718, 5743), 'numpy.random.seed', 'np.random.seed', (['args.seed'], {}), '(args.seed)\n', (5732, 5743), True, 'import numpy as np\n'), ((5748, 5779), 'fairseq.utils.set_torch_seed', 'utils.set_torch_seed', (['args.seed'], {}), '(args.seed)\n', (5768, 5779), False, 'from fairseq import checkpoint_utils, distributed_utils, options, quantization_utils, tasks, utils\n'), ((5788, 5821), 'fairseq.distributed_utils.is_master', 'distributed_utils.is_master', (['args'], {}), '(args)\n', (5815, 5821), False, 'from fairseq import checkpoint_utils, distributed_utils, options, quantization_utils, tasks, utils\n'), ((6004, 6026), 'fairseq.tasks.setup_task', 'tasks.setup_task', (['args'], {}), '(args)\n', (6020, 6026), False, 'from fairseq import checkpoint_utils, distributed_utils, options, quantization_utils, tasks, utils\n'), ((8098, 8121), 'fairseq.meters.StopwatchMeter', 'meters.StopwatchMeter', ([], {}), '()\n', (8119, 8121), False, 'from fairseq import meters\n'), ((10333, 10376), 'fairseq.data.iterators.GroupedIterator', 'iterators.GroupedIterator', (['itr', 'update_freq'], {}), '(itr, update_freq)\n', (10358, 10376), False, 'from fairseq.data import iterators\n'), ((12293, 12322), 'fairseq.logging.metrics.reset_meters', 'metrics.reset_meters', (['"""train"""'], {}), "('train')\n", (12313, 12322), False, 'from fairseq.logging import metrics, progress_bar\n'), ((16463, 16492), 'fairseq.options.get_training_parser', 'options.get_training_parser', ([], {}), '()\n', (16490, 16492), False, 'from fairseq import checkpoint_utils, distributed_utils, options, quantization_utils, tasks, utils\n'), ((16504, 16568), 'fairseq.options.parse_args_and_arch', 'options.parse_args_and_arch', (['parser'], {'modify_parser': 'modify_parser'}), '(parser, modify_parser=modify_parser)\n', (16531, 16568), False, 'from fairseq import checkpoint_utils, distributed_utils, options, quantization_utils, tasks, utils\n'), ((1894, 1917), 'fairseq.meters.StopwatchMeter', 'meters.StopwatchMeter', ([], {}), '()\n', (1915, 1917), False, 'from fairseq import meters\n'), ((2155, 2180), 'collections.OrderedDict', 'collections.OrderedDict', ([], {}), '()\n', (2178, 2180), False, 'import collections\n'), ((5831, 5890), 'fairseq.checkpoint_utils.verify_checkpoint_directory', 'checkpoint_utils.verify_checkpoint_directory', (['args.save_dir'], {}), '(args.save_dir)\n', (5875, 5890), False, 'from fairseq import checkpoint_utils, distributed_utils, options, quantization_utils, tasks, utils\n'), ((6968, 7097), 'fairseq.quantization_utils.Quantizer', 'quantization_utils.Quantizer', ([], {'config_path': 'args.quantization_config_path', 'max_epoch': 'args.max_epoch', 'max_update': 'args.max_update'}), '(config_path=args.quantization_config_path,\n max_epoch=args.max_epoch, max_update=args.max_update)\n', (6996, 7097), False, 'from fairseq import checkpoint_utils, distributed_utils, options, quantization_utils, tasks, utils\n'), ((7253, 7301), 'fairseq.trainer.Trainer', 'Trainer', (['args', 'task', 'model', 'criterion', 'quantizer'], {}), '(args, task, model, criterion, quantizer)\n', (7260, 7301), False, 'from fairseq.trainer import Trainer\n'), ((7330, 7375), 'fairseq.model_parallel.megatron_trainer.MegatronTrainer', 'MegatronTrainer', (['args', 'task', 'model', 'criterion'], {}), '(args, task, model, criterion)\n', (7345, 7375), False, 'from fairseq.model_parallel.megatron_trainer import MegatronTrainer\n'), ((10427, 10453), 'fairseq.utils.tpu_data_loader', 'utils.tpu_data_loader', (['itr'], {}), '(itr)\n', (10448, 10453), False, 'from fairseq import checkpoint_utils, distributed_utils, options, quantization_utils, tasks, utils\n'), ((12162, 12198), 'fairseq.logging.metrics.get_smoothed_values', 'metrics.get_smoothed_values', (['"""train"""'], {}), "('train')\n", (12189, 12198), False, 'from fairseq.logging import metrics, progress_bar\n'), ((14568, 14616), 'fairseq.utils.set_torch_seed', 'utils.set_torch_seed', (['args.fixed_validation_seed'], {}), '(args.fixed_validation_seed)\n', (14588, 14616), False, 'from fairseq import checkpoint_utils, distributed_utils, options, quantization_utils, tasks, utils\n'), ((16762, 16801), 'fairseq.distributed_utils.call_main', 'distributed_utils.call_main', (['args', 'main'], {}), '(args, main)\n', (16789, 16801), False, 'from fairseq import checkpoint_utils, distributed_utils, options, quantization_utils, tasks, utils\n'), ((1328, 1369), 'os.makedirs', 'os.makedirs', (['args.save_dir'], {'exist_ok': '(True)'}), '(args.save_dir, exist_ok=True)\n', (1339, 1369), False, 'import os\n'), ((3775, 3806), 'os.path.join', 'os.path.join', (['args.save_dir', 'fn'], {}), '(args.save_dir, fn)\n', (3787, 3806), False, 'import os\n'), ((4517, 4587), 'fairseq.checkpoint_utils.checkpoint_paths', 'checkpoint_paths', (['args.save_dir'], {'pattern': '"""checkpoint_\\\\d+_(\\\\d+)\\\\.pt"""'}), "(args.save_dir, pattern='checkpoint_\\\\d+_(\\\\d+)\\\\.pt')\n", (4533, 4587), False, 'from fairseq.checkpoint_utils import checkpoint_paths\n'), ((4921, 4985), 'fairseq.checkpoint_utils.checkpoint_paths', 'checkpoint_paths', (['args.save_dir'], {'pattern': '"""checkpoint(\\\\d+)\\\\.pt"""'}), "(args.save_dir, pattern='checkpoint(\\\\d+)\\\\.pt')\n", (4937, 4985), False, 'from fairseq.checkpoint_utils import checkpoint_paths\n'), ((11066, 11098), 'fairseq.logging.metrics.aggregate', 'metrics.aggregate', (['"""train_inner"""'], {}), "('train_inner')\n", (11083, 11098), False, 'from fairseq.logging import metrics, progress_bar\n'), ((11100, 11160), 'torch.autograd.profiler.record_function', 'torch.autograd.profiler.record_function', (["('train_step-%d' % i)"], {}), "('train_step-%d' % i)\n", (11139, 11160), False, 'import torch\n'), ((14254, 14290), 'fairseq.logging.metrics.get_meter', 'metrics.get_meter', (['"""default"""', '"""wall"""'], {}), "('default', 'wall')\n", (14271, 14290), False, 'from fairseq.logging import metrics, progress_bar\n'), ((14957, 14983), 'fairseq.utils.tpu_data_loader', 'utils.tpu_data_loader', (['itr'], {}), '(itr)\n', (14978, 14983), False, 'from fairseq import checkpoint_utils, distributed_utils, options, quantization_utils, tasks, utils\n'), ((15590, 15622), 'fairseq.logging.metrics.aggregate', 'metrics.aggregate', ([], {'new_root': '(True)'}), '(new_root=True)\n', (15607, 15622), False, 'from fairseq.logging import metrics, progress_bar\n'), ((16603, 16632), 'torch.cuda.profiler.profile', 'torch.cuda.profiler.profile', ([], {}), '()\n', (16630, 16632), False, 'import torch\n'), ((932, 966), 'os.environ.get', 'os.environ.get', (['"""LOGLEVEL"""', '"""INFO"""'], {}), "('LOGLEVEL', 'INFO')\n", (946, 966), False, 'import os\n'), ((4019, 4071), 'fairseq.file_io.PathManager.copy', 'PathManager.copy', (['checkpoints[0]', 'cp'], {'overwrite': '(True)'}), '(checkpoints[0], cp, overwrite=True)\n', (4035, 4071), False, 'from fairseq.file_io import PathManager\n'), ((4704, 4728), 'os.path.lexists', 'os.path.lexists', (['old_chk'], {}), '(old_chk)\n', (4719, 4728), False, 'import os\n'), ((5068, 5092), 'os.path.lexists', 'os.path.lexists', (['old_chk'], {}), '(old_chk)\n', (5083, 5092), False, 'import os\n'), ((5284, 5314), 'os.path.join', 'os.path.join', (['args.save_dir', 'x'], {}), '(args.save_dir, x)\n', (5296, 5314), False, 'import os\n'), ((5334, 5352), 'os.path.lexists', 'os.path.lexists', (['x'], {}), '(x)\n', (5349, 5352), False, 'import os\n'), ((10684, 10717), 'fairseq.distributed_utils.is_master', 'distributed_utils.is_master', (['args'], {}), '(args)\n', (10711, 10717), False, 'from fairseq import checkpoint_utils, distributed_utils, options, quantization_utils, tasks, utils\n'), ((11748, 11783), 'fairseq.logging.metrics.reset_meters', 'metrics.reset_meters', (['"""train_inner"""'], {}), "('train_inner')\n", (11768, 11783), False, 'from fairseq.logging import metrics, progress_bar\n'), ((16651, 16686), 'torch.autograd.profiler.emit_nvtx', 'torch.autograd.profiler.emit_nvtx', ([], {}), '()\n', (16684, 16686), False, 'import torch\n'), ((16704, 16743), 'fairseq.distributed_utils.call_main', 'distributed_utils.call_main', (['args', 'main'], {}), '(args, main)\n', (16731, 16743), False, 'from fairseq import checkpoint_utils, distributed_utils, options, quantization_utils, tasks, utils\n'), ((4750, 4768), 'os.remove', 'os.remove', (['old_chk'], {}), '(old_chk)\n', (4759, 4768), False, 'import os\n'), ((5114, 5132), 'os.remove', 'os.remove', (['old_chk'], {}), '(old_chk)\n', (5123, 5132), False, 'import os\n'), ((5374, 5386), 'os.remove', 'os.remove', (['x'], {}), '(x)\n', (5383, 5386), False, 'import os\n'), ((11485, 11527), 'fairseq.logging.metrics.get_smoothed_values', 'metrics.get_smoothed_values', (['"""train_inner"""'], {}), "('train_inner')\n", (11512, 11527), False, 'from fairseq.logging import metrics, progress_bar\n'), ((15292, 15325), 'fairseq.distributed_utils.is_master', 'distributed_utils.is_master', (['args'], {}), '(args)\n', (15319, 15325), False, 'from fairseq import checkpoint_utils, distributed_utils, options, quantization_utils, tasks, utils\n')]
import torch import torch.nn as nn from torch.nn import functional as F from PIL import Image import cv2 as cv from matplotlib import cm import numpy as np class GradCAM: """ #### Args: layer_name: module name (not child name), if None, will use the last layer before average pooling , default is None """ def __init__(self, model, device, layer_name=None, close_some_grad=True): if layer_name is None: layer_name = self.get_layer_name(model) if layer_name is None: raise ValueError( "There is no global average pooling layer, plz specify 'layer_name'" ) for n, m in model.named_children(): if close_some_grad: m.requires_grad_(False) for sub_n, sub_m in m.named_modules(): if '.'.join((n, sub_n)) == layer_name: sub_m.register_forward_hook(self.forward_hook) sub_m.register_full_backward_hook(self.backward_hook) m.requires_grad_(True) break model = model.to(device) self.model = model self.device = device self.feature_maps = {} self.gradients = {} def get_heatmap(self, img, img_tensor): self.model.zero_grad() img_tensor = img_tensor.to(self.device) outputs = self.model(img_tensor) _, pred_label = outputs.max(1) # outputs shape = 1x2 outputs[0][pred_label].backward() with torch.no_grad(): feature_maps = self.feature_maps["output"] # "gradients" is a tuple with one item grad_weights = self.gradients["output"][0] h, w = grad_weights.size()[-2:] grad_weights = grad_weights.sum((2,3), True) / (h * w) cam = (grad_weights * feature_maps).sum(1) F.relu(cam, True) cam = cam / cam.max() * 255 cam = cam.to(dtype=torch.uint8, device="cpu") cam = cam.numpy().transpose(1,2,0) cam = cv.resize(cam, img.size[:2], interpolation=4) cam = np.uint8(255 * cm.get_cmap("jet")(cam.squeeze())) if not isinstance(img, np.ndarray): img = np.asarray(img) img_size = img.shape[:2][::-1] # w, h overlay = np.uint8(0.6*img + 0.4 * cam[:,:,:3]) overlay = Image.fromarray(overlay) if overlay.size != img_size: overlay = overlay.resize(img_size, Image.BILINEAR) return outputs.detach(), overlay def get_layer_name(self, model): layer_name = None for n, m in model.named_children(): for sub_n, sub_m in m.named_modules(): if isinstance(sub_m, (nn.AdaptiveAvgPool2d, nn.AvgPool2d)): layer_name = tmp tmp = '.'.join((n, sub_n)) return layer_name def forward_hook(self, module, x, y): #self.feature_maps["input"] = x self.feature_maps["output"] = y def backward_hook(self, module, x, y): #self.gradients["input"] = x self.gradients["output"] = y self.gradients["output"] = y
[ "numpy.uint8", "PIL.Image.fromarray", "numpy.asarray", "torch.nn.functional.relu", "torch.no_grad", "cv2.resize", "matplotlib.cm.get_cmap" ]
[((1644, 1659), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (1657, 1659), False, 'import torch\n'), ((2015, 2032), 'torch.nn.functional.relu', 'F.relu', (['cam', '(True)'], {}), '(cam, True)\n', (2021, 2032), True, 'from torch.nn import functional as F\n'), ((2200, 2245), 'cv2.resize', 'cv.resize', (['cam', 'img.size[:2]'], {'interpolation': '(4)'}), '(cam, img.size[:2], interpolation=4)\n', (2209, 2245), True, 'import cv2 as cv\n'), ((2481, 2522), 'numpy.uint8', 'np.uint8', (['(0.6 * img + 0.4 * cam[:, :, :3])'], {}), '(0.6 * img + 0.4 * cam[:, :, :3])\n', (2489, 2522), True, 'import numpy as np\n'), ((2542, 2566), 'PIL.Image.fromarray', 'Image.fromarray', (['overlay'], {}), '(overlay)\n', (2557, 2566), False, 'from PIL import Image\n'), ((2389, 2404), 'numpy.asarray', 'np.asarray', (['img'], {}), '(img)\n', (2399, 2404), True, 'import numpy as np\n'), ((2280, 2298), 'matplotlib.cm.get_cmap', 'cm.get_cmap', (['"""jet"""'], {}), "('jet')\n", (2291, 2298), False, 'from matplotlib import cm\n')]
"""Generates a random terrain at Minitaur gym environment reset.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os, inspect currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(os.path.dirname(currentdir)) parentdir = os.path.dirname(os.path.dirname(parentdir)) os.sys.path.insert(0, parentdir) import itertools import math import enum import numpy as np from pybullet_envs.minitaur.envs import env_randomizer_base _GRID_LENGTH = 15 _GRID_WIDTH = 10 _MAX_SAMPLE_SIZE = 30 _MIN_BLOCK_DISTANCE = 0.7 _MAX_BLOCK_LENGTH = _MIN_BLOCK_DISTANCE _MIN_BLOCK_LENGTH = _MAX_BLOCK_LENGTH / 2 _MAX_BLOCK_HEIGHT = 0.05 _MIN_BLOCK_HEIGHT = _MAX_BLOCK_HEIGHT / 2 class PoissonDisc2D(object): """Generates 2D points using Poisson disk sampling method. Implements the algorithm described in: http://www.cs.ubc.ca/~rbridson/docs/bridson-siggraph07-poissondisk.pdf Unlike the uniform sampling method that creates small clusters of points, Poisson disk method enforces the minimum distance between points and is more suitable for generating a spatial distribution of non-overlapping objects. """ def __init__(self, grid_length, grid_width, min_radius, max_sample_size): """Initializes the algorithm. Args: grid_length: The length of the bounding square in which points are sampled. grid_width: The width of the bounding square in which points are sampled. min_radius: The minimum distance between any pair of points. max_sample_size: The maximum number of sample points around a active site. See details in the algorithm description. """ self._cell_length = min_radius / math.sqrt(2) self._grid_length = grid_length self._grid_width = grid_width self._grid_size_x = int(grid_length / self._cell_length) + 1 self._grid_size_y = int(grid_width / self._cell_length) + 1 self._min_radius = min_radius self._max_sample_size = max_sample_size # Flattern the 2D grid as an 1D array. The grid is used for fast nearest # point searching. self._grid = [None] * self._grid_size_x * self._grid_size_y # Generate the first sample point and set it as an active site. first_sample = np.array(np.random.random_sample(2)) * [grid_length, grid_width] self._active_list = [first_sample] # Also store the sample point in the grid. self._grid[self._point_to_index_1d(first_sample)] = first_sample def _point_to_index_1d(self, point): """Computes the index of a point in the grid array. Args: point: A 2D point described by its coordinates (x, y). Returns: The index of the point within the self._grid array. """ return self._index_2d_to_1d(self._point_to_index_2d(point)) def _point_to_index_2d(self, point): """Computes the 2D index (aka cell ID) of a point in the grid. Args: point: A 2D point (list) described by its coordinates (x, y). Returns: x_index: The x index of the cell the point belongs to. y_index: The y index of the cell the point belongs to. """ x_index = int(point[0] / self._cell_length) y_index = int(point[1] / self._cell_length) return x_index, y_index def _index_2d_to_1d(self, index2d): """Converts the 2D index to the 1D position in the grid array. Args: index2d: The 2D index of a point (aka the cell ID) in the grid. Returns: The 1D position of the cell within the self._grid array. """ return index2d[0] + index2d[1] * self._grid_size_x def _is_in_grid(self, point): """Checks if the point is inside the grid boundary. Args: point: A 2D point (list) described by its coordinates (x, y). Returns: Whether the point is inside the grid. """ return (0 <= point[0] < self._grid_length) and (0 <= point[1] < self._grid_width) def _is_in_range(self, index2d): """Checks if the cell ID is within the grid. Args: index2d: The 2D index of a point (aka the cell ID) in the grid. Returns: Whether the cell (2D index) is inside the grid. """ return (0 <= index2d[0] < self._grid_size_x) and (0 <= index2d[1] < self._grid_size_y) def _is_close_to_existing_points(self, point): """Checks if the point is close to any already sampled (and stored) points. Args: point: A 2D point (list) described by its coordinates (x, y). Returns: True iff the distance of the point to any existing points is smaller than the min_radius """ px, py = self._point_to_index_2d(point) # Now we can check nearby cells for existing points for neighbor_cell in itertools.product(xrange(px - 1, px + 2), xrange(py - 1, py + 2)): if not self._is_in_range(neighbor_cell): continue maybe_a_point = self._grid[self._index_2d_to_1d(neighbor_cell)] if maybe_a_point is not None and np.linalg.norm(maybe_a_point - point) < self._min_radius: return True return False def sample(self): """Samples new points around some existing point. Removes the sampling base point and also stores the new jksampled points if they are far enough from all existing points. """ active_point = self._active_list.pop() for _ in xrange(self._max_sample_size): # Generate random points near the current active_point between the radius random_radius = np.random.uniform(self._min_radius, 2 * self._min_radius) random_angle = np.random.uniform(0, 2 * math.pi) # The sampled 2D points near the active point sample = random_radius * np.array([np.cos(random_angle), np.sin(random_angle)]) + active_point if not self._is_in_grid(sample): continue if self._is_close_to_existing_points(sample): continue self._active_list.append(sample) self._grid[self._point_to_index_1d(sample)] = sample def generate(self): """Generates the Poisson disc distribution of 2D points. Although the while loop looks scary, the algorithm is in fact O(N), where N is the number of cells within the grid. When we sample around a base point (in some base cell), new points will not be pushed into the base cell because of the minimum distance constraint. Once the current base point is removed, all future searches cannot start from within the same base cell. Returns: All sampled points. The points are inside the quare [0, grid_length] x [0, grid_width] """ while self._active_list: self.sample() all_sites = [] for p in self._grid: if p is not None: all_sites.append(p) return all_sites class TerrainType(enum.Enum): """The randomzied terrain types we can use in the gym env.""" RANDOM_BLOCKS = 1 TRIANGLE_MESH = 2 class MinitaurTerrainRandomizer(env_randomizer_base.EnvRandomizerBase): """Generates an uneven terrain in the gym env.""" def __init__(self, terrain_type=TerrainType.TRIANGLE_MESH, mesh_filename="robotics/reinforcement_learning/minitaur/envs/testdata/" "triangle_mesh_terrain/terrain9735.obj", mesh_scale=None): """Initializes the randomizer. Args: terrain_type: Whether to generate random blocks or load a triangle mesh. mesh_filename: The mesh file to be used. The mesh will only be loaded if terrain_type is set to TerrainType.TRIANGLE_MESH. mesh_scale: the scaling factor for the triangles in the mesh file. """ self._terrain_type = terrain_type self._mesh_filename = mesh_filename self._mesh_scale = mesh_scale if mesh_scale else [1.0, 1.0, 0.3] def randomize_env(self, env): """Generate a random terrain for the current env. Args: env: A minitaur gym environment. """ if self._terrain_type is TerrainType.TRIANGLE_MESH: self._load_triangle_mesh(env) if self._terrain_type is TerrainType.RANDOM_BLOCKS: self._generate_convex_blocks(env) def _load_triangle_mesh(self, env): """Represents the random terrain using a triangle mesh. It is possible for Minitaur leg to stuck at the common edge of two triangle pieces. To prevent this from happening, we recommend using hard contacts (or high stiffness values) for Minitaur foot in sim. Args: env: A minitaur gym environment. """ env.pybullet_client.removeBody(env.ground_id) terrain_collision_shape_id = env.pybullet_client.createCollisionShape( shapeType=env.pybullet_client.GEOM_MESH, fileName=self._mesh_filename, flags=1, meshScale=self._mesh_scale) env.ground_id = env.pybullet_client.createMultiBody( baseMass=0, baseCollisionShapeIndex=terrain_collision_shape_id, basePosition=[0, 0, 0]) def _generate_convex_blocks(self, env): """Adds random convex blocks to the flat ground. We use the Possion disk algorithm to add some random blocks on the ground. Possion disk algorithm sets the minimum distance between two sampling points, thus voiding the clustering effect in uniform N-D distribution. Args: env: A minitaur gym environment. """ poisson_disc = PoissonDisc2D(_GRID_LENGTH, _GRID_WIDTH, _MIN_BLOCK_DISTANCE, _MAX_SAMPLE_SIZE) block_centers = poisson_disc.generate() for center in block_centers: # We want the blocks to be in front of the robot. shifted_center = np.array(center) - [2, _GRID_WIDTH / 2] # Do not place blocks near the point [0, 0], where the robot will start. if abs(shifted_center[0]) < 1.0 and abs(shifted_center[1]) < 1.0: continue half_length = np.random.uniform(_MIN_BLOCK_LENGTH, _MAX_BLOCK_LENGTH) / (2 * math.sqrt(2)) half_height = np.random.uniform(_MIN_BLOCK_HEIGHT, _MAX_BLOCK_HEIGHT) / 2 box_id = env.pybullet_client.createCollisionShape( env.pybullet_client.GEOM_BOX, halfExtents=[half_length, half_length, half_height]) env.pybullet_client.createMultiBody( baseMass=0, baseCollisionShapeIndex=box_id, basePosition=[shifted_center[0], shifted_center[1], half_height])
[ "numpy.random.random_sample", "inspect.currentframe", "math.sqrt", "numpy.linalg.norm", "os.sys.path.insert", "os.path.dirname", "numpy.array", "numpy.cos", "numpy.random.uniform", "numpy.sin" ]
[((398, 430), 'os.sys.path.insert', 'os.sys.path.insert', (['(0)', 'parentdir'], {}), '(0, parentdir)\n', (416, 430), False, 'import os, inspect\n'), ((313, 340), 'os.path.dirname', 'os.path.dirname', (['currentdir'], {}), '(currentdir)\n', (328, 340), False, 'import os, inspect\n'), ((370, 396), 'os.path.dirname', 'os.path.dirname', (['parentdir'], {}), '(parentdir)\n', (385, 396), False, 'import os, inspect\n'), ((259, 281), 'inspect.currentframe', 'inspect.currentframe', ([], {}), '()\n', (279, 281), False, 'import os, inspect\n'), ((1776, 1788), 'math.sqrt', 'math.sqrt', (['(2)'], {}), '(2)\n', (1785, 1788), False, 'import math\n'), ((5485, 5542), 'numpy.random.uniform', 'np.random.uniform', (['self._min_radius', '(2 * self._min_radius)'], {}), '(self._min_radius, 2 * self._min_radius)\n', (5502, 5542), True, 'import numpy as np\n'), ((5564, 5597), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(2 * math.pi)'], {}), '(0, 2 * math.pi)\n', (5581, 5597), True, 'import numpy as np\n'), ((2328, 2354), 'numpy.random.random_sample', 'np.random.random_sample', (['(2)'], {}), '(2)\n', (2351, 2354), True, 'import numpy as np\n'), ((9556, 9572), 'numpy.array', 'np.array', (['center'], {}), '(center)\n', (9564, 9572), True, 'import numpy as np\n'), ((9785, 9840), 'numpy.random.uniform', 'np.random.uniform', (['_MIN_BLOCK_LENGTH', '_MAX_BLOCK_LENGTH'], {}), '(_MIN_BLOCK_LENGTH, _MAX_BLOCK_LENGTH)\n', (9802, 9840), True, 'import numpy as np\n'), ((9882, 9937), 'numpy.random.uniform', 'np.random.uniform', (['_MIN_BLOCK_HEIGHT', '_MAX_BLOCK_HEIGHT'], {}), '(_MIN_BLOCK_HEIGHT, _MAX_BLOCK_HEIGHT)\n', (9899, 9937), True, 'import numpy as np\n'), ((4986, 5023), 'numpy.linalg.norm', 'np.linalg.norm', (['(maybe_a_point - point)'], {}), '(maybe_a_point - point)\n', (5000, 5023), True, 'import numpy as np\n'), ((9848, 9860), 'math.sqrt', 'math.sqrt', (['(2)'], {}), '(2)\n', (9857, 9860), False, 'import math\n'), ((5692, 5712), 'numpy.cos', 'np.cos', (['random_angle'], {}), '(random_angle)\n', (5698, 5712), True, 'import numpy as np\n'), ((5755, 5775), 'numpy.sin', 'np.sin', (['random_angle'], {}), '(random_angle)\n', (5761, 5775), True, 'import numpy as np\n')]
""" VAE on the swirl task. Basically, VAEs don't work. It's probably because the prior isn't very good and/or because the learning signal is pretty weak when both the encoder and decoder change quickly. However, I tried also alternating between the two, and that didn't seem to help. """ from torch.distributions import Normal from torch.optim import Adam import torch import numpy as np import matplotlib.pyplot as plt from torch import nn as nn import railrl.torch.pytorch_util as ptu SWIRL_RATE = 1 T = 10 BS = 128 N_BATCHES = 2000 N_VIS = 1000 HIDDEN_SIZE = 32 VERBOSE = False def swirl_data(batch_size): t = np.random.uniform(size=batch_size, low=0, high=T) x = t * np.cos(t * SWIRL_RATE) / T y = t * np.sin(t * SWIRL_RATE) / T data = np.array([x, y]).T noise = np.random.randn(batch_size, 2) / (T * 2) return data + noise, t.reshape(-1, 1) def swirl_t_to_data(t): x = t * np.cos(t * SWIRL_RATE) / T y = t * np.sin(t * SWIRL_RATE) / T return np.array([x, y]).T def kl_to_prior(means, log_stds, stds): """ KL between a Gaussian and a standard Gaussian. https://stats.stackexchange.com/questions/60680/kl-divergence-between-two-multivariate-gaussians """ return 0.5 * ( - 2 * log_stds # log std_prior = 0 - 1 # d = 1 + stds ** 2 + means ** 2 ) class Encoder(nn.Sequential): def encode(self, x): return self.get_encoding_and_suff_stats(x)[0] def get_encoding_and_suff_stats(self, x): output = self(x) means, log_stds = ( output[:, 0:1], output[:, 1:2] ) stds = log_stds.exp() epsilon = ptu.Variable(torch.randn(*means.size())) latents = epsilon * stds + means latents = latents return latents, means, log_stds, stds class Decoder(nn.Sequential): def decode(self, latents): output = self(latents) means, log_stds = output[:, 0:2], output[:, 2:4] distribution = Normal(means, log_stds.exp()) return distribution.sample() def t_to_xy(t): if len(t.shape) == 2: t = t[:, 0] x = t * np.cos(t * SWIRL_RATE) / T y = t * np.sin(t * SWIRL_RATE) / T return np.array([x, y]).T def pretrain_encoder(encoder, opt): losses = [] for _ in range(1000): x_np, y_np = swirl_data(BS) x = ptu.np_to_var(x_np) y = ptu.np_to_var(y_np) y_hat = encoder.encode(x) loss = ((y_hat - y) ** 2).mean() opt.zero_grad() loss.backward() opt.step() losses.append(loss.data.numpy()) if VERBOSE: x_np, y_np = swirl_data(N_VIS) x = ptu.np_to_var(x_np) y_hat = encoder.encode(x) y_hat_np = y_hat.data.numpy() x_hat_np = t_to_xy(y_hat_np[:, 0]) plt.subplot(2, 1, 1) plt.plot(np.array(losses)) plt.title("Training Loss") plt.subplot(2, 1, 2) plt.plot(x_np[:, 0], x_np[:, 1], '.') plt.plot(x_hat_np[:, 0], x_hat_np[:, 1], '.') plt.title("Samples") plt.legend(["Samples", "Estimates"]) plt.show() def train_encoder(encoder, decoder, encoder_opt): batch, true_latents = swirl_data(BS) batch = ptu.np_to_var(batch) latents, means, log_stds, stds = encoder.get_encoding_and_suff_stats( batch ) kl = kl_to_prior(means, log_stds, stds) latents = encoder.encode(batch) decoder_output = decoder(latents) decoder_means = decoder_output[:, 0:2] decoder_log_stds = decoder_output[:, 2:4] distribution = Normal(decoder_means, decoder_log_stds.exp()) reconstruction_log_prob = distribution.log_prob(batch).sum(dim=1) # elbo = - kl + reconstruction_log_prob # loss = - elbo.mean() loss = - reconstruction_log_prob.mean() # This is the second place where we cheat: latent_loss = ((ptu.np_to_var(true_latents) - latents) ** 2).mean() loss = loss# + latent_loss encoder_opt.zero_grad() loss.backward() encoder_opt.step() return loss def train_decoder(encoder, decoder, decoder_opt): batch, true_latents = swirl_data(BS) batch = ptu.np_to_var(batch) latents = encoder.encode(batch) decoder_output = decoder(latents) decoder_means = decoder_output[:, 0:2] decoder_log_stds = decoder_output[:, 2:4] distribution = Normal(decoder_means, decoder_log_stds.exp()) reconstruction_log_prob = distribution.log_prob(batch).sum(dim=1) loss = - reconstruction_log_prob.mean() decoder_opt.zero_grad() loss.backward() decoder_opt.step() return loss def train_alternating(*_): encoder = Encoder( nn.Linear(2, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, 2), ) encoder_opt = Adam(encoder.parameters()) decoder = Decoder( nn.Linear(1, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, 4), ) decoder_opt = Adam(decoder.parameters()) encoder_losses = [] decoder_losses = [] for _ in range(100): for _ in range(N_BATCHES): encoder_losses.append( train_encoder(encoder, decoder, encoder_opt).data.numpy() ) for _ in range(N_BATCHES): decoder_losses.append( train_decoder(encoder, decoder, decoder_opt).data.numpy() ) # Visualize vis_samples_np, true_latents_np = swirl_data(N_VIS) vis_samples = ptu.np_to_var(vis_samples_np) true_xy_mean_np = t_to_xy(true_latents_np) latents = encoder.encode(vis_samples) reconstructed_samples = decoder.decode(latents).data.numpy() generated_samples = decoder.decode( ptu.Variable(torch.randn(*latents.shape)) ).data.numpy() plt.subplot(2, 2, 1) plt.plot(np.array(encoder_losses)) plt.title("Encoder Loss") plt.subplot(2, 2, 2) plt.plot(np.array(decoder_losses)) plt.title("Decoder Loss") plt.subplot(2, 3, 4) plt.plot(generated_samples[:, 0], generated_samples[:, 1], '.') plt.title("Generated Samples") plt.subplot(2, 3, 5) plt.plot(reconstructed_samples[:, 0], reconstructed_samples[:, 1], '.') estimated_means = t_to_xy(latents.data.numpy()) # plt.plot(estimated_means[:, 0], estimated_means[:, 1], '.') plt.title("Reconstruction") # plt.legend(["Samples", "Projected Latents"]) plt.subplot(2, 3, 6) plt.plot(vis_samples_np[:, 0], vis_samples_np[:, 1], '.') plt.plot(true_xy_mean_np[:, 0], true_xy_mean_np[:, 1], '.') plt.title("Original Samples") plt.legend(["Original", "True means"]) plt.show() def train(): encoder = Encoder( nn.Linear(2, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, 2), ) encoder_opt = Adam(encoder.parameters()) # This is the first place that we cheat. However, this pretraining isn't # needed if you just add the loss to the training (see below) # pretrain_encoder(encoder, encoder_opt) decoder = Decoder( nn.Linear(1, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, 4), ) decoder_opt = Adam(decoder.parameters()) print("Done training encoder") losses = [] kls = [] log_probs = [] for _ in range(N_BATCHES): batch, true_latents = swirl_data(BS) batch = ptu.np_to_var(batch) latents, means, log_stds, stds = encoder.get_encoding_and_suff_stats( batch ) kl = kl_to_prior(means, log_stds, stds) latents = encoder.encode(batch) # decoder_output = decoder(latents.detach()) decoder_output = decoder(latents) decoder_means = decoder_output[:, 0:2] decoder_log_stds = decoder_output[:, 2:4] distribution = Normal(decoder_means, decoder_log_stds.exp()) reconstruction_log_prob = distribution.log_prob(batch).sum(dim=1) elbo = - kl + reconstruction_log_prob loss = - elbo.mean() # This is the second place where we cheat: latent_loss = ((ptu.np_to_var(true_latents) - latents) ** 2).mean() loss = loss + latent_loss decoder_opt.zero_grad() encoder_opt.zero_grad() loss.backward() decoder_opt.step() encoder_opt.step() losses.append(loss.data.numpy()) kls.append(kl.mean().data.numpy()) log_probs.append(reconstruction_log_prob.mean().data.numpy()) # Visualize vis_samples_np, true_latents_np = swirl_data(N_VIS) vis_samples = ptu.np_to_var(vis_samples_np) true_xy_mean_np = t_to_xy(true_latents_np) latents = encoder.encode(vis_samples) reconstructed_samples = decoder.decode(latents).data.numpy() generated_samples = decoder.decode( ptu.Variable(torch.randn(*latents.shape)) ).data.numpy() plt.subplot(2, 3, 1) plt.plot(np.array(losses)) plt.title("Training Loss") plt.subplot(2, 3, 2) plt.plot(np.array(kls)) plt.title("KLs") plt.subplot(2, 3, 3) plt.plot(np.array(log_probs)) plt.title("Log Probs") plt.subplot(2, 3, 4) plt.plot(generated_samples[:, 0], generated_samples[:, 1], '.') plt.title("Generated Samples") plt.subplot(2, 3, 5) plt.plot(reconstructed_samples[:, 0], reconstructed_samples[:, 1], '.') estimated_means = t_to_xy(latents.data.numpy()) plt.plot(estimated_means[:, 0], estimated_means[:, 1], '.') plt.title("Reconstruction") plt.subplot(2, 3, 6) plt.plot(vis_samples_np[:, 0], vis_samples_np[:, 1], '.') plt.plot(true_xy_mean_np[:, 0], true_xy_mean_np[:, 1], '.') plt.title("Original Samples") plt.legend(["Original", "True means"]) plt.show() if __name__ == '__main__': train_alternating() # train()
[ "torch.nn.ReLU", "matplotlib.pyplot.plot", "railrl.torch.pytorch_util.np_to_var", "numpy.array", "numpy.random.randn", "numpy.cos", "torch.nn.Linear", "numpy.random.uniform", "numpy.sin", "matplotlib.pyplot.title", "matplotlib.pyplot.subplot", "torch.randn", "matplotlib.pyplot.legend", "matplotlib.pyplot.show" ]
[((621, 670), 'numpy.random.uniform', 'np.random.uniform', ([], {'size': 'batch_size', 'low': '(0)', 'high': 'T'}), '(size=batch_size, low=0, high=T)\n', (638, 670), True, 'import numpy as np\n'), ((3240, 3260), 'railrl.torch.pytorch_util.np_to_var', 'ptu.np_to_var', (['batch'], {}), '(batch)\n', (3253, 3260), True, 'import railrl.torch.pytorch_util as ptu\n'), ((4157, 4177), 'railrl.torch.pytorch_util.np_to_var', 'ptu.np_to_var', (['batch'], {}), '(batch)\n', (4170, 4177), True, 'import railrl.torch.pytorch_util as ptu\n'), ((5829, 5858), 'railrl.torch.pytorch_util.np_to_var', 'ptu.np_to_var', (['vis_samples_np'], {}), '(vis_samples_np)\n', (5842, 5858), True, 'import railrl.torch.pytorch_util as ptu\n'), ((6127, 6147), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(2)', '(1)'], {}), '(2, 2, 1)\n', (6138, 6147), True, 'import matplotlib.pyplot as plt\n'), ((6191, 6216), 'matplotlib.pyplot.title', 'plt.title', (['"""Encoder Loss"""'], {}), "('Encoder Loss')\n", (6200, 6216), True, 'import matplotlib.pyplot as plt\n'), ((6221, 6241), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(2)', '(2)'], {}), '(2, 2, 2)\n', (6232, 6241), True, 'import matplotlib.pyplot as plt\n'), ((6285, 6310), 'matplotlib.pyplot.title', 'plt.title', (['"""Decoder Loss"""'], {}), "('Decoder Loss')\n", (6294, 6310), True, 'import matplotlib.pyplot as plt\n'), ((6316, 6336), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(3)', '(4)'], {}), '(2, 3, 4)\n', (6327, 6336), True, 'import matplotlib.pyplot as plt\n'), ((6341, 6404), 'matplotlib.pyplot.plot', 'plt.plot', (['generated_samples[:, 0]', 'generated_samples[:, 1]', '"""."""'], {}), "(generated_samples[:, 0], generated_samples[:, 1], '.')\n", (6349, 6404), True, 'import matplotlib.pyplot as plt\n'), ((6409, 6439), 'matplotlib.pyplot.title', 'plt.title', (['"""Generated Samples"""'], {}), "('Generated Samples')\n", (6418, 6439), True, 'import matplotlib.pyplot as plt\n'), ((6444, 6464), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(3)', '(5)'], {}), '(2, 3, 5)\n', (6455, 6464), True, 'import matplotlib.pyplot as plt\n'), ((6469, 6540), 'matplotlib.pyplot.plot', 'plt.plot', (['reconstructed_samples[:, 0]', 'reconstructed_samples[:, 1]', '"""."""'], {}), "(reconstructed_samples[:, 0], reconstructed_samples[:, 1], '.')\n", (6477, 6540), True, 'import matplotlib.pyplot as plt\n'), ((6663, 6690), 'matplotlib.pyplot.title', 'plt.title', (['"""Reconstruction"""'], {}), "('Reconstruction')\n", (6672, 6690), True, 'import matplotlib.pyplot as plt\n'), ((6746, 6766), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(3)', '(6)'], {}), '(2, 3, 6)\n', (6757, 6766), True, 'import matplotlib.pyplot as plt\n'), ((6771, 6828), 'matplotlib.pyplot.plot', 'plt.plot', (['vis_samples_np[:, 0]', 'vis_samples_np[:, 1]', '"""."""'], {}), "(vis_samples_np[:, 0], vis_samples_np[:, 1], '.')\n", (6779, 6828), True, 'import matplotlib.pyplot as plt\n'), ((6833, 6892), 'matplotlib.pyplot.plot', 'plt.plot', (['true_xy_mean_np[:, 0]', 'true_xy_mean_np[:, 1]', '"""."""'], {}), "(true_xy_mean_np[:, 0], true_xy_mean_np[:, 1], '.')\n", (6841, 6892), True, 'import matplotlib.pyplot as plt\n'), ((6897, 6926), 'matplotlib.pyplot.title', 'plt.title', (['"""Original Samples"""'], {}), "('Original Samples')\n", (6906, 6926), True, 'import matplotlib.pyplot as plt\n'), ((6931, 6969), 'matplotlib.pyplot.legend', 'plt.legend', (["['Original', 'True means']"], {}), "(['Original', 'True means'])\n", (6941, 6969), True, 'import matplotlib.pyplot as plt\n'), ((6974, 6984), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6982, 6984), True, 'import matplotlib.pyplot as plt\n'), ((9252, 9281), 'railrl.torch.pytorch_util.np_to_var', 'ptu.np_to_var', (['vis_samples_np'], {}), '(vis_samples_np)\n', (9265, 9281), True, 'import railrl.torch.pytorch_util as ptu\n'), ((9550, 9570), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(3)', '(1)'], {}), '(2, 3, 1)\n', (9561, 9570), True, 'import matplotlib.pyplot as plt\n'), ((9606, 9632), 'matplotlib.pyplot.title', 'plt.title', (['"""Training Loss"""'], {}), "('Training Loss')\n", (9615, 9632), True, 'import matplotlib.pyplot as plt\n'), ((9637, 9657), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(3)', '(2)'], {}), '(2, 3, 2)\n', (9648, 9657), True, 'import matplotlib.pyplot as plt\n'), ((9690, 9706), 'matplotlib.pyplot.title', 'plt.title', (['"""KLs"""'], {}), "('KLs')\n", (9699, 9706), True, 'import matplotlib.pyplot as plt\n'), ((9711, 9731), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(3)', '(3)'], {}), '(2, 3, 3)\n', (9722, 9731), True, 'import matplotlib.pyplot as plt\n'), ((9770, 9792), 'matplotlib.pyplot.title', 'plt.title', (['"""Log Probs"""'], {}), "('Log Probs')\n", (9779, 9792), True, 'import matplotlib.pyplot as plt\n'), ((9798, 9818), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(3)', '(4)'], {}), '(2, 3, 4)\n', (9809, 9818), True, 'import matplotlib.pyplot as plt\n'), ((9823, 9886), 'matplotlib.pyplot.plot', 'plt.plot', (['generated_samples[:, 0]', 'generated_samples[:, 1]', '"""."""'], {}), "(generated_samples[:, 0], generated_samples[:, 1], '.')\n", (9831, 9886), True, 'import matplotlib.pyplot as plt\n'), ((9891, 9921), 'matplotlib.pyplot.title', 'plt.title', (['"""Generated Samples"""'], {}), "('Generated Samples')\n", (9900, 9921), True, 'import matplotlib.pyplot as plt\n'), ((9926, 9946), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(3)', '(5)'], {}), '(2, 3, 5)\n', (9937, 9946), True, 'import matplotlib.pyplot as plt\n'), ((9951, 10022), 'matplotlib.pyplot.plot', 'plt.plot', (['reconstructed_samples[:, 0]', 'reconstructed_samples[:, 1]', '"""."""'], {}), "(reconstructed_samples[:, 0], reconstructed_samples[:, 1], '.')\n", (9959, 10022), True, 'import matplotlib.pyplot as plt\n'), ((10079, 10138), 'matplotlib.pyplot.plot', 'plt.plot', (['estimated_means[:, 0]', 'estimated_means[:, 1]', '"""."""'], {}), "(estimated_means[:, 0], estimated_means[:, 1], '.')\n", (10087, 10138), True, 'import matplotlib.pyplot as plt\n'), ((10143, 10170), 'matplotlib.pyplot.title', 'plt.title', (['"""Reconstruction"""'], {}), "('Reconstruction')\n", (10152, 10170), True, 'import matplotlib.pyplot as plt\n'), ((10175, 10195), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(3)', '(6)'], {}), '(2, 3, 6)\n', (10186, 10195), True, 'import matplotlib.pyplot as plt\n'), ((10200, 10257), 'matplotlib.pyplot.plot', 'plt.plot', (['vis_samples_np[:, 0]', 'vis_samples_np[:, 1]', '"""."""'], {}), "(vis_samples_np[:, 0], vis_samples_np[:, 1], '.')\n", (10208, 10257), True, 'import matplotlib.pyplot as plt\n'), ((10262, 10321), 'matplotlib.pyplot.plot', 'plt.plot', (['true_xy_mean_np[:, 0]', 'true_xy_mean_np[:, 1]', '"""."""'], {}), "(true_xy_mean_np[:, 0], true_xy_mean_np[:, 1], '.')\n", (10270, 10321), True, 'import matplotlib.pyplot as plt\n'), ((10326, 10355), 'matplotlib.pyplot.title', 'plt.title', (['"""Original Samples"""'], {}), "('Original Samples')\n", (10335, 10355), True, 'import matplotlib.pyplot as plt\n'), ((10360, 10398), 'matplotlib.pyplot.legend', 'plt.legend', (["['Original', 'True means']"], {}), "(['Original', 'True means'])\n", (10370, 10398), True, 'import matplotlib.pyplot as plt\n'), ((10403, 10413), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (10411, 10413), True, 'import matplotlib.pyplot as plt\n'), ((760, 776), 'numpy.array', 'np.array', (['[x, y]'], {}), '([x, y])\n', (768, 776), True, 'import numpy as np\n'), ((791, 821), 'numpy.random.randn', 'np.random.randn', (['batch_size', '(2)'], {}), '(batch_size, 2)\n', (806, 821), True, 'import numpy as np\n'), ((989, 1005), 'numpy.array', 'np.array', (['[x, y]'], {}), '([x, y])\n', (997, 1005), True, 'import numpy as np\n'), ((2226, 2242), 'numpy.array', 'np.array', (['[x, y]'], {}), '([x, y])\n', (2234, 2242), True, 'import numpy as np\n'), ((2373, 2392), 'railrl.torch.pytorch_util.np_to_var', 'ptu.np_to_var', (['x_np'], {}), '(x_np)\n', (2386, 2392), True, 'import railrl.torch.pytorch_util as ptu\n'), ((2405, 2424), 'railrl.torch.pytorch_util.np_to_var', 'ptu.np_to_var', (['y_np'], {}), '(y_np)\n', (2418, 2424), True, 'import railrl.torch.pytorch_util as ptu\n'), ((2677, 2696), 'railrl.torch.pytorch_util.np_to_var', 'ptu.np_to_var', (['x_np'], {}), '(x_np)\n', (2690, 2696), True, 'import railrl.torch.pytorch_util as ptu\n'), ((2821, 2841), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(1)', '(1)'], {}), '(2, 1, 1)\n', (2832, 2841), True, 'import matplotlib.pyplot as plt\n'), ((2885, 2911), 'matplotlib.pyplot.title', 'plt.title', (['"""Training Loss"""'], {}), "('Training Loss')\n", (2894, 2911), True, 'import matplotlib.pyplot as plt\n'), ((2921, 2941), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(1)', '(2)'], {}), '(2, 1, 2)\n', (2932, 2941), True, 'import matplotlib.pyplot as plt\n'), ((2950, 2987), 'matplotlib.pyplot.plot', 'plt.plot', (['x_np[:, 0]', 'x_np[:, 1]', '"""."""'], {}), "(x_np[:, 0], x_np[:, 1], '.')\n", (2958, 2987), True, 'import matplotlib.pyplot as plt\n'), ((2996, 3041), 'matplotlib.pyplot.plot', 'plt.plot', (['x_hat_np[:, 0]', 'x_hat_np[:, 1]', '"""."""'], {}), "(x_hat_np[:, 0], x_hat_np[:, 1], '.')\n", (3004, 3041), True, 'import matplotlib.pyplot as plt\n'), ((3050, 3070), 'matplotlib.pyplot.title', 'plt.title', (['"""Samples"""'], {}), "('Samples')\n", (3059, 3070), True, 'import matplotlib.pyplot as plt\n'), ((3079, 3115), 'matplotlib.pyplot.legend', 'plt.legend', (["['Samples', 'Estimates']"], {}), "(['Samples', 'Estimates'])\n", (3089, 3115), True, 'import matplotlib.pyplot as plt\n'), ((3124, 3134), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3132, 3134), True, 'import matplotlib.pyplot as plt\n'), ((4669, 4694), 'torch.nn.Linear', 'nn.Linear', (['(2)', 'HIDDEN_SIZE'], {}), '(2, HIDDEN_SIZE)\n', (4678, 4694), True, 'from torch import nn as nn\n'), ((4704, 4713), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (4711, 4713), True, 'from torch import nn as nn\n'), ((4723, 4758), 'torch.nn.Linear', 'nn.Linear', (['HIDDEN_SIZE', 'HIDDEN_SIZE'], {}), '(HIDDEN_SIZE, HIDDEN_SIZE)\n', (4732, 4758), True, 'from torch import nn as nn\n'), ((4768, 4777), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (4775, 4777), True, 'from torch import nn as nn\n'), ((4787, 4822), 'torch.nn.Linear', 'nn.Linear', (['HIDDEN_SIZE', 'HIDDEN_SIZE'], {}), '(HIDDEN_SIZE, HIDDEN_SIZE)\n', (4796, 4822), True, 'from torch import nn as nn\n'), ((4832, 4841), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (4839, 4841), True, 'from torch import nn as nn\n'), ((4851, 4886), 'torch.nn.Linear', 'nn.Linear', (['HIDDEN_SIZE', 'HIDDEN_SIZE'], {}), '(HIDDEN_SIZE, HIDDEN_SIZE)\n', (4860, 4886), True, 'from torch import nn as nn\n'), ((4896, 4905), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (4903, 4905), True, 'from torch import nn as nn\n'), ((4915, 4940), 'torch.nn.Linear', 'nn.Linear', (['HIDDEN_SIZE', '(2)'], {}), '(HIDDEN_SIZE, 2)\n', (4924, 4940), True, 'from torch import nn as nn\n'), ((5024, 5049), 'torch.nn.Linear', 'nn.Linear', (['(1)', 'HIDDEN_SIZE'], {}), '(1, HIDDEN_SIZE)\n', (5033, 5049), True, 'from torch import nn as nn\n'), ((5059, 5068), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (5066, 5068), True, 'from torch import nn as nn\n'), ((5078, 5113), 'torch.nn.Linear', 'nn.Linear', (['HIDDEN_SIZE', 'HIDDEN_SIZE'], {}), '(HIDDEN_SIZE, HIDDEN_SIZE)\n', (5087, 5113), True, 'from torch import nn as nn\n'), ((5123, 5132), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (5130, 5132), True, 'from torch import nn as nn\n'), ((5142, 5177), 'torch.nn.Linear', 'nn.Linear', (['HIDDEN_SIZE', 'HIDDEN_SIZE'], {}), '(HIDDEN_SIZE, HIDDEN_SIZE)\n', (5151, 5177), True, 'from torch import nn as nn\n'), ((5187, 5196), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (5194, 5196), True, 'from torch import nn as nn\n'), ((5206, 5241), 'torch.nn.Linear', 'nn.Linear', (['HIDDEN_SIZE', 'HIDDEN_SIZE'], {}), '(HIDDEN_SIZE, HIDDEN_SIZE)\n', (5215, 5241), True, 'from torch import nn as nn\n'), ((5251, 5260), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (5258, 5260), True, 'from torch import nn as nn\n'), ((5270, 5295), 'torch.nn.Linear', 'nn.Linear', (['HIDDEN_SIZE', '(4)'], {}), '(HIDDEN_SIZE, 4)\n', (5279, 5295), True, 'from torch import nn as nn\n'), ((6161, 6185), 'numpy.array', 'np.array', (['encoder_losses'], {}), '(encoder_losses)\n', (6169, 6185), True, 'import numpy as np\n'), ((6255, 6279), 'numpy.array', 'np.array', (['decoder_losses'], {}), '(decoder_losses)\n', (6263, 6279), True, 'import numpy as np\n'), ((7031, 7056), 'torch.nn.Linear', 'nn.Linear', (['(2)', 'HIDDEN_SIZE'], {}), '(2, HIDDEN_SIZE)\n', (7040, 7056), True, 'from torch import nn as nn\n'), ((7066, 7075), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (7073, 7075), True, 'from torch import nn as nn\n'), ((7085, 7120), 'torch.nn.Linear', 'nn.Linear', (['HIDDEN_SIZE', 'HIDDEN_SIZE'], {}), '(HIDDEN_SIZE, HIDDEN_SIZE)\n', (7094, 7120), True, 'from torch import nn as nn\n'), ((7130, 7139), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (7137, 7139), True, 'from torch import nn as nn\n'), ((7149, 7184), 'torch.nn.Linear', 'nn.Linear', (['HIDDEN_SIZE', 'HIDDEN_SIZE'], {}), '(HIDDEN_SIZE, HIDDEN_SIZE)\n', (7158, 7184), True, 'from torch import nn as nn\n'), ((7194, 7203), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (7201, 7203), True, 'from torch import nn as nn\n'), ((7213, 7248), 'torch.nn.Linear', 'nn.Linear', (['HIDDEN_SIZE', 'HIDDEN_SIZE'], {}), '(HIDDEN_SIZE, HIDDEN_SIZE)\n', (7222, 7248), True, 'from torch import nn as nn\n'), ((7258, 7267), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (7265, 7267), True, 'from torch import nn as nn\n'), ((7277, 7302), 'torch.nn.Linear', 'nn.Linear', (['HIDDEN_SIZE', '(2)'], {}), '(HIDDEN_SIZE, 2)\n', (7286, 7302), True, 'from torch import nn as nn\n'), ((7574, 7599), 'torch.nn.Linear', 'nn.Linear', (['(1)', 'HIDDEN_SIZE'], {}), '(1, HIDDEN_SIZE)\n', (7583, 7599), True, 'from torch import nn as nn\n'), ((7609, 7618), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (7616, 7618), True, 'from torch import nn as nn\n'), ((7628, 7663), 'torch.nn.Linear', 'nn.Linear', (['HIDDEN_SIZE', 'HIDDEN_SIZE'], {}), '(HIDDEN_SIZE, HIDDEN_SIZE)\n', (7637, 7663), True, 'from torch import nn as nn\n'), ((7673, 7682), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (7680, 7682), True, 'from torch import nn as nn\n'), ((7692, 7727), 'torch.nn.Linear', 'nn.Linear', (['HIDDEN_SIZE', 'HIDDEN_SIZE'], {}), '(HIDDEN_SIZE, HIDDEN_SIZE)\n', (7701, 7727), True, 'from torch import nn as nn\n'), ((7737, 7746), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (7744, 7746), True, 'from torch import nn as nn\n'), ((7756, 7791), 'torch.nn.Linear', 'nn.Linear', (['HIDDEN_SIZE', 'HIDDEN_SIZE'], {}), '(HIDDEN_SIZE, HIDDEN_SIZE)\n', (7765, 7791), True, 'from torch import nn as nn\n'), ((7801, 7810), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (7808, 7810), True, 'from torch import nn as nn\n'), ((7820, 7845), 'torch.nn.Linear', 'nn.Linear', (['HIDDEN_SIZE', '(4)'], {}), '(HIDDEN_SIZE, 4)\n', (7829, 7845), True, 'from torch import nn as nn\n'), ((8074, 8094), 'railrl.torch.pytorch_util.np_to_var', 'ptu.np_to_var', (['batch'], {}), '(batch)\n', (8087, 8094), True, 'import railrl.torch.pytorch_util as ptu\n'), ((9584, 9600), 'numpy.array', 'np.array', (['losses'], {}), '(losses)\n', (9592, 9600), True, 'import numpy as np\n'), ((9671, 9684), 'numpy.array', 'np.array', (['kls'], {}), '(kls)\n', (9679, 9684), True, 'import numpy as np\n'), ((9745, 9764), 'numpy.array', 'np.array', (['log_probs'], {}), '(log_probs)\n', (9753, 9764), True, 'import numpy as np\n'), ((683, 705), 'numpy.cos', 'np.cos', (['(t * SWIRL_RATE)'], {}), '(t * SWIRL_RATE)\n', (689, 705), True, 'import numpy as np\n'), ((722, 744), 'numpy.sin', 'np.sin', (['(t * SWIRL_RATE)'], {}), '(t * SWIRL_RATE)\n', (728, 744), True, 'import numpy as np\n'), ((912, 934), 'numpy.cos', 'np.cos', (['(t * SWIRL_RATE)'], {}), '(t * SWIRL_RATE)\n', (918, 934), True, 'import numpy as np\n'), ((951, 973), 'numpy.sin', 'np.sin', (['(t * SWIRL_RATE)'], {}), '(t * SWIRL_RATE)\n', (957, 973), True, 'import numpy as np\n'), ((2149, 2171), 'numpy.cos', 'np.cos', (['(t * SWIRL_RATE)'], {}), '(t * SWIRL_RATE)\n', (2155, 2171), True, 'import numpy as np\n'), ((2188, 2210), 'numpy.sin', 'np.sin', (['(t * SWIRL_RATE)'], {}), '(t * SWIRL_RATE)\n', (2194, 2210), True, 'import numpy as np\n'), ((2859, 2875), 'numpy.array', 'np.array', (['losses'], {}), '(losses)\n', (2867, 2875), True, 'import numpy as np\n'), ((3882, 3909), 'railrl.torch.pytorch_util.np_to_var', 'ptu.np_to_var', (['true_latents'], {}), '(true_latents)\n', (3895, 3909), True, 'import railrl.torch.pytorch_util as ptu\n'), ((6074, 6101), 'torch.randn', 'torch.randn', (['*latents.shape'], {}), '(*latents.shape)\n', (6085, 6101), False, 'import torch\n'), ((8778, 8805), 'railrl.torch.pytorch_util.np_to_var', 'ptu.np_to_var', (['true_latents'], {}), '(true_latents)\n', (8791, 8805), True, 'import railrl.torch.pytorch_util as ptu\n'), ((9497, 9524), 'torch.randn', 'torch.randn', (['*latents.shape'], {}), '(*latents.shape)\n', (9508, 9524), False, 'import torch\n')]
class FoodClassifier: #Class Attributes: #model - the underlying keras model #labels - the labels to be associated with the activation of each output neuron. #Labels must be the same size as the output layer of the neural network. def __init__(self, modelpath, labels, min_confidence = 0.6): from keras.models import load_model from keras.applications.resnet50 import ResNet50 self.resnet = ResNet50(include_top=False,weights='imagenet',pooling='max',input_shape=(224,224,3)) self.extModel = load_model(modelpath) if(isinstance(labels,str)): #its a file path from os.path import exists if(exists(labels)): f = open(labels,'r') x = f.readlines() y = [] for i in x: y.append(i.split('\n')[0]) self.labels = y else: self.labels = labels self.num_classes = len(labels) self.min_confidence=min_confidence def predict(self,img): import os from PIL import Image from keras.preprocessing.image import img_to_array import numpy as np #check if image is a filepath if(isinstance(img,str)): if(not os.path.exists(img)): print("Error: Invalid File Path") return "" else: #if its a filepath, convert to PIL image img = Image.open(img) #resize image #shape from model input shape = self.resnet.input_shape imgr = img.resize(shape[1:3]) x = img_to_array(imgr).reshape((1,shape[1],shape[2],shape[3])) #predict features = self.resnet.predict(x) prediction = self.extModel.predict(features) #get max of predictions and return label(s) predIdx = np.argmax(prediction) if(prediction[0,predIdx]<self.min_confidence): return "" else: return self.labels[predIdx] def set_extModel(self,model): self.extModel = model def get_extModel(self): return self.extModel def set_labels(self,labels): self.labels = labels def get_labels(self): return self.labels def set_min_confidence(self,conf): self.min_confidence=conf def get_min_confidence(self): return self.min_confidence def generate_features_from_directory(location,target_image_count,model=None): #generates feature maps from the convolutional layers of ResNet50 using all #images from the directory #INPUT: #directory containing NESTED DIRECTORIES of images. (Very Important) #the number of feature maps to generate for each image class #OUTPUT: #a npy file containing the 2048-dimensional feature vector #produced by ResNet50's convolutional layers #data is generated in batches of 32 import numpy as np from keras.preprocessing.image import ImageDataGenerator from keras.applications.resnet50 import ResNet50 from os import listdir from os.path import isdir #create the model, if not defined if model==None: model = ResNet50(weights='imagenet',include_top=False,pooling='max') #create the data generation datagen = ImageDataGenerator() #for each directory in if(not isdir(location)): print("could not find location: " + location) return for label in listdir(location): #first check that its a directory label_path = location+'/'+label if(not isdir(label_path)): continue #create the data generator #Output size is 256x256 to fit the ResNet50 print("Generating feature maps for " + label + "...") generator = datagen.flow_from_directory( label_path, target_size = (224,224), batch_size = 32, class_mode=None) #use ResNet50 to create the features features = model.predict_generator(generator,target_image_count/32) #features = np.reshape(features,(features.shape[0],features.shape[3])) #save the features in a numpy binary np.save(location+'/'+label+'.npy', features) def create_data_set(data_path,output_folder,save_to_file=True): #combines all npy files into one large file with their respective labels #INPUTS: #a directory containing npy fils of all different classes #Outputs: #training array and training labels #label array is returned as a one hot encoding #label names from os.path import isdir from os import listdir import numpy as np #find out how many classes num_classes = 0 label_names = [] if(not isdir(data_path)): print("Could not find directory: "+ data_path) return data_contents = listdir(data_path) for f in data_contents: if(f.endswith('.npy')): num_classes +=1 label_names.append(f.split('.')[0]) if(num_classes==0): print("Could not find any data files in directory: "+data_path) return #generate one-hot label vectors labels = np.zeros([num_classes,num_classes]) for i in range(0,num_classes): labels[i][i]=1 #load all arrays into memory. #In the future, might need to do this on either a high ram machine #or find another way to concatenate data arrays = [] sizes = [] for f in data_contents: if(f.endswith('.npy')): arr = np.load(data_path+'/'+f) sizes.append(arr.shape[0]) arrays.append(arr) X = np.vstack([arr for arr in arrays]) #load the labels into memory labelcodes = [] for i in range(0,num_classes): labelcodes.append(np.vstack([labels[i]]*sizes[i])) y = np.vstack([l for l in labelcodes]) if(save_to_file): np.save(output_folder+'/data_set.npy',X) np.save(output_folder+'/label_codes.npy',y) with open(output_folder+"/labels.txt","w") as output: output.write("".join([label + '\n' for label in label_names])) return X,y,label_names def train_classifier_from_images(train_dir,train_size,val_dir,val_size,output_dir): #INPUTS: #train_dir is the directory containig the training images #test_dir is the directory containing the validation images #output_dir is the directory to save the trained model #train_size is the number of images to generate for each training class #val_size is the number of images to generate for each validation class #OUTPUTS #A model that takes as input a 2048-vector of feature maps and outputs #a prediction of what an image with those features might be. #The labels file is also placed in this directory #The model created is an SVM with softmax activation. from time import time from keras.applications.resnet50 import ResNet50 from keras.models import Sequential from keras.optimizers import SGD from keras.regularizers import l2 from keras.layers import Dense from sklearn.utils import shuffle from keras.callbacks import EarlyStopping, ModelCheckpoint #import ResNet50 without top layer print("Loading the ResNet50 Network...") resnet = ResNet50(weights='imagenet',include_top=False,pooling='max') #create the training and validation datasets for each class print("Generating Training Set...") generate_features_from_directory(train_dir,train_size,model=resnet) print("Generating Testing Set...") generate_features_from_directory(val_dir,val_size,model=resnet) #create the combined dataset print("Combining datasets...") X_train,y_train,labels = create_data_set(train_dir,output_dir+"/train",save_to_file=True) X_val,y_val,labels = create_data_set(val_dir,output_dir+"/validation",save_to_file=True) #shuffle the train data X_train,y_train = shuffle(X_train,y_train) num_classes = len(labels) #create the extension model print("Creating extension model...") extModel = Sequential() extModel.add(Dense(num_classes,input_shape=(2048,), activation='softmax', W_regularizer=l2(0.01))) extModel.compile(loss='hinge',optimizer=SGD(lr=0.01,momentum=0.9),metrics=["accuracy"]) #callbacks checkpoint = ModelCheckpoint(output_dir + "/extModel"+str(int(time()))+".h5", monitor='val_acc', verbose=1, save_best_only=True, save_weights_only=False, mode='auto', period=1) early = EarlyStopping(monitor='val_acc', min_delta=0, patience=10, verbose=1, mode='auto') with open(output_dir+"/labels.txt","w") as output: output.write("".join([label + '\n' for label in labels])) #train model print("Training...") extModel.fit(X_train,y_train, batch_size=32, epochs=50, validation_data=(X_val,y_val), callbacks = [checkpoint,early]) return extModel def add_to_train(train_dir,image,label, resnet): #INPUTS #Train_dir - the directory that all npy files are contained #image - the path to the image being added #resnet - the resnet model to be used for feature determination #label - the name of the item #Appends the features of the new item to the training set data for that label from PIL import Image from os.path import exists from keras.preprocessing.image import img_to_array if(isinstance(image,str)): if(not exists(image)): print("Error: Invalid File Path") return "" else: #if its a filepath, convert to PIL image img = Image.open(image) shape = resnet.input_shape imgr = img.resize(shape[1:3]) x = img_to_array(imgr).reshape((1,shape[1],shape[2],shape[3])) #predict features = resnet.predict(x) import numpy as np npyname = train_dir+'/'+label+'.npy' if(not exists(npyname)): np.save(npyname,features) else: fullset = np.load(npyname) newset = np.append(fullset,features,axis=0) np.save(npyname,newset)
[ "keras.preprocessing.image.img_to_array", "keras.preprocessing.image.ImageDataGenerator", "keras.optimizers.SGD", "numpy.save", "os.path.exists", "os.listdir", "os.path.isdir", "numpy.vstack", "keras.callbacks.EarlyStopping", "numpy.argmax", "keras.models.Sequential", "keras.applications.resnet50.ResNet50", "keras.regularizers.l2", "time.time", "PIL.Image.open", "keras.models.load_model", "sklearn.utils.shuffle", "numpy.append", "numpy.zeros", "numpy.load" ]
[((3487, 3507), 'keras.preprocessing.image.ImageDataGenerator', 'ImageDataGenerator', ([], {}), '()\n', (3505, 3507), False, 'from keras.preprocessing.image import ImageDataGenerator\n'), ((3656, 3673), 'os.listdir', 'listdir', (['location'], {}), '(location)\n', (3663, 3673), False, 'from os import listdir\n'), ((5158, 5176), 'os.listdir', 'listdir', (['data_path'], {}), '(data_path)\n', (5165, 5176), False, 'from os import listdir\n'), ((5483, 5519), 'numpy.zeros', 'np.zeros', (['[num_classes, num_classes]'], {}), '([num_classes, num_classes])\n', (5491, 5519), True, 'import numpy as np\n'), ((5950, 5984), 'numpy.vstack', 'np.vstack', (['[arr for arr in arrays]'], {}), '([arr for arr in arrays])\n', (5959, 5984), True, 'import numpy as np\n'), ((6145, 6179), 'numpy.vstack', 'np.vstack', (['[l for l in labelcodes]'], {}), '([l for l in labelcodes])\n', (6154, 6179), True, 'import numpy as np\n'), ((7644, 7706), 'keras.applications.resnet50.ResNet50', 'ResNet50', ([], {'weights': '"""imagenet"""', 'include_top': '(False)', 'pooling': '"""max"""'}), "(weights='imagenet', include_top=False, pooling='max')\n", (7652, 7706), False, 'from keras.applications.resnet50 import ResNet50\n'), ((8308, 8333), 'sklearn.utils.shuffle', 'shuffle', (['X_train', 'y_train'], {}), '(X_train, y_train)\n', (8315, 8333), False, 'from sklearn.utils import shuffle\n'), ((8461, 8473), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (8471, 8473), False, 'from keras.models import Sequential\n'), ((8882, 8969), 'keras.callbacks.EarlyStopping', 'EarlyStopping', ([], {'monitor': '"""val_acc"""', 'min_delta': '(0)', 'patience': '(10)', 'verbose': '(1)', 'mode': '"""auto"""'}), "(monitor='val_acc', min_delta=0, patience=10, verbose=1, mode=\n 'auto')\n", (8895, 8969), False, 'from keras.callbacks import EarlyStopping, ModelCheckpoint\n'), ((450, 544), 'keras.applications.resnet50.ResNet50', 'ResNet50', ([], {'include_top': '(False)', 'weights': '"""imagenet"""', 'pooling': '"""max"""', 'input_shape': '(224, 224, 3)'}), "(include_top=False, weights='imagenet', pooling='max', input_shape=\n (224, 224, 3))\n", (458, 544), False, 'from keras.applications.resnet50 import ResNet50\n'), ((559, 580), 'keras.models.load_model', 'load_model', (['modelpath'], {}), '(modelpath)\n', (569, 580), False, 'from keras.models import load_model\n'), ((1961, 1982), 'numpy.argmax', 'np.argmax', (['prediction'], {}), '(prediction)\n', (1970, 1982), True, 'import numpy as np\n'), ((3370, 3432), 'keras.applications.resnet50.ResNet50', 'ResNet50', ([], {'weights': '"""imagenet"""', 'include_top': '(False)', 'pooling': '"""max"""'}), "(weights='imagenet', include_top=False, pooling='max')\n", (3378, 3432), False, 'from keras.applications.resnet50 import ResNet50\n'), ((3552, 3567), 'os.path.isdir', 'isdir', (['location'], {}), '(location)\n', (3557, 3567), False, 'from os.path import isdir\n'), ((4431, 4481), 'numpy.save', 'np.save', (["(location + '/' + label + '.npy')", 'features'], {}), "(location + '/' + label + '.npy', features)\n", (4438, 4481), True, 'import numpy as np\n'), ((5044, 5060), 'os.path.isdir', 'isdir', (['data_path'], {}), '(data_path)\n', (5049, 5060), False, 'from os.path import isdir\n'), ((6215, 6258), 'numpy.save', 'np.save', (["(output_folder + '/data_set.npy')", 'X'], {}), "(output_folder + '/data_set.npy', X)\n", (6222, 6258), True, 'import numpy as np\n'), ((6264, 6310), 'numpy.save', 'np.save', (["(output_folder + '/label_codes.npy')", 'y'], {}), "(output_folder + '/label_codes.npy', y)\n", (6271, 6310), True, 'import numpy as np\n'), ((10372, 10387), 'os.path.exists', 'exists', (['npyname'], {}), '(npyname)\n', (10378, 10387), False, 'from os.path import exists\n'), ((10398, 10424), 'numpy.save', 'np.save', (['npyname', 'features'], {}), '(npyname, features)\n', (10405, 10424), True, 'import numpy as np\n'), ((10456, 10472), 'numpy.load', 'np.load', (['npyname'], {}), '(npyname)\n', (10463, 10472), True, 'import numpy as np\n'), ((10490, 10526), 'numpy.append', 'np.append', (['fullset', 'features'], {'axis': '(0)'}), '(fullset, features, axis=0)\n', (10499, 10526), True, 'import numpy as np\n'), ((10533, 10557), 'numpy.save', 'np.save', (['npyname', 'newset'], {}), '(npyname, newset)\n', (10540, 10557), True, 'import numpy as np\n'), ((709, 723), 'os.path.exists', 'exists', (['labels'], {}), '(labels)\n', (715, 723), False, 'from os.path import exists\n'), ((3772, 3789), 'os.path.isdir', 'isdir', (['label_path'], {}), '(label_path)\n', (3777, 3789), False, 'from os.path import isdir\n'), ((5842, 5870), 'numpy.load', 'np.load', (["(data_path + '/' + f)"], {}), "(data_path + '/' + f)\n", (5849, 5870), True, 'import numpy as np\n'), ((6104, 6137), 'numpy.vstack', 'np.vstack', (['([labels[i]] * sizes[i])'], {}), '([labels[i]] * sizes[i])\n', (6113, 6137), True, 'import numpy as np\n'), ((8621, 8647), 'keras.optimizers.SGD', 'SGD', ([], {'lr': '(0.01)', 'momentum': '(0.9)'}), '(lr=0.01, momentum=0.9)\n', (8624, 8647), False, 'from keras.optimizers import SGD\n'), ((9896, 9909), 'os.path.exists', 'exists', (['image'], {}), '(image)\n', (9902, 9909), False, 'from os.path import exists\n'), ((10065, 10082), 'PIL.Image.open', 'Image.open', (['image'], {}), '(image)\n', (10075, 10082), False, 'from PIL import Image\n'), ((10166, 10184), 'keras.preprocessing.image.img_to_array', 'img_to_array', (['imgr'], {}), '(imgr)\n', (10178, 10184), False, 'from keras.preprocessing.image import img_to_array\n'), ((1320, 1339), 'os.path.exists', 'os.path.exists', (['img'], {}), '(img)\n', (1334, 1339), False, 'import os\n'), ((1515, 1530), 'PIL.Image.open', 'Image.open', (['img'], {}), '(img)\n', (1525, 1530), False, 'from PIL import Image\n'), ((1693, 1711), 'keras.preprocessing.image.img_to_array', 'img_to_array', (['imgr'], {}), '(imgr)\n', (1705, 1711), False, 'from keras.preprocessing.image import img_to_array\n'), ((8566, 8574), 'keras.regularizers.l2', 'l2', (['(0.01)'], {}), '(0.01)\n', (8568, 8574), False, 'from keras.regularizers import l2\n'), ((8755, 8761), 'time.time', 'time', ([], {}), '()\n', (8759, 8761), False, 'from time import time\n')]
""" Created on Thu Oct 26 14:19:44 2017 @author: <NAME> - github.com/utkuozbulak """ import os import numpy as np import torch from torch.optim import SGD from torchvision import models from misc_functions import preprocess_image, recreate_image, save_image class ClassSpecificImageGeneration(): """ Produces an image that maximizes a certain class with gradient ascent """ def __init__(self, model, target_class): self.mean = [-0.485, -0.456, -0.406] self.std = [1/0.229, 1/0.224, 1/0.225] self.model = model self.model.eval() self.target_class = target_class # Generate a random image self.created_image = np.uint8(np.random.uniform(0, 255, (224, 224, 3))) # Create the folder to export images if not exists if not os.path.exists('../generated/class_'+str(self.target_class)): os.makedirs('../generated/class_'+str(self.target_class)) def generate(self, iterations=150): """Generates class specific image Keyword Arguments: iterations {int} -- Total iterations for gradient ascent (default: {150}) Returns: np.ndarray -- Final maximally activated class image """ initial_learning_rate = 6 for i in range(1, iterations): # Process image and return variable self.processed_image = preprocess_image(self.created_image, False) # Define optimizer for the image optimizer = SGD([self.processed_image], lr=initial_learning_rate) # Forward output = self.model(self.processed_image) # Target specific class class_loss = -output[0, self.target_class] if i % 10 == 0 or i == iterations-1: print('Iteration:', str(i), 'Loss', "{0:.2f}".format(class_loss.data.numpy())) # Zero grads self.model.zero_grad() # Backward class_loss.backward() # Update image optimizer.step() # Recreate image self.created_image = recreate_image(self.processed_image) if i % 10 == 0 or i == iterations-1: # Save image im_path = '../generated/class_'+str(self.target_class)+'/c_'+str(self.target_class)+'_'+'iter_'+str(i)+'.png' save_image(self.created_image, im_path) return self.processed_image if __name__ == '__main__': target_class = 130 # Flamingo pretrained_model = models.alexnet(pretrained=True) csig = ClassSpecificImageGeneration(pretrained_model, target_class) csig.generate()
[ "torch.optim.SGD", "misc_functions.recreate_image", "misc_functions.save_image", "misc_functions.preprocess_image", "torchvision.models.alexnet", "numpy.random.uniform" ]
[((2551, 2582), 'torchvision.models.alexnet', 'models.alexnet', ([], {'pretrained': '(True)'}), '(pretrained=True)\n', (2565, 2582), False, 'from torchvision import models\n'), ((698, 738), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(255)', '(224, 224, 3)'], {}), '(0, 255, (224, 224, 3))\n', (715, 738), True, 'import numpy as np\n'), ((1393, 1436), 'misc_functions.preprocess_image', 'preprocess_image', (['self.created_image', '(False)'], {}), '(self.created_image, False)\n', (1409, 1436), False, 'from misc_functions import preprocess_image, recreate_image, save_image\n'), ((1507, 1560), 'torch.optim.SGD', 'SGD', (['[self.processed_image]'], {'lr': 'initial_learning_rate'}), '([self.processed_image], lr=initial_learning_rate)\n', (1510, 1560), False, 'from torch.optim import SGD\n'), ((2130, 2166), 'misc_functions.recreate_image', 'recreate_image', (['self.processed_image'], {}), '(self.processed_image)\n', (2144, 2166), False, 'from misc_functions import preprocess_image, recreate_image, save_image\n'), ((2387, 2426), 'misc_functions.save_image', 'save_image', (['self.created_image', 'im_path'], {}), '(self.created_image, im_path)\n', (2397, 2426), False, 'from misc_functions import preprocess_image, recreate_image, save_image\n')]
#!/usr/bin/env python3 ###### # General Detector # 06.12.2018 / Last Update: 20.05.2021 # LRB ###### import numpy as np import os import sys import tensorflow as tf import hashlib import cv2 import magic import PySimpleGUI as sg import csv import imagehash import face_recognition import subprocess from itertools import groupby from distutils.version import StrictVersion from PIL import Image from datetime import datetime from time import strftime from time import gmtime from multiprocessing import Pool from Models.Face import detect_face from pathlib import Path from openvino.inference_engine import IENetwork, IECore from AudioAnalysis import audioAnalysis ###### # Worker function to check the input provided via the GUI ####### def validateInput(gui_input): error = False #Validate input # for element in gui_input[1][0:7]: # if element == '' or []: # error = True if gui_input[0] == "Cancel" or len(gui_input[1][8]) == 0: error = True if bool(gui_input[1][5]) == True and gui_input[1][12] == "": error = True if error == True: sg.Popup('You have not populated all required fields. Aborting!', title='Error', button_color=('black', 'red'), background_color=('grey')) exit() ###### # Worker function to update the progress bar ###### def updateProgressMeter(step, customText): if sg.OneLineProgressMeter('BKP Media Detector', step, 12, 'key', customText, orientation='h', size=(50, 25)) == False: exit() ###### # Worker function to prepare and reshape the input images into a Numpy array # and to calculate the MD5 hashes of them. ###### def load_image_into_numpy_array(image_path): try: image_path = str(image_path) # Open, measure and convert image to RGB channels image = Image.open(image_path) (im_width, im_height) = image.size if int(im_width) < 34 or int(im_height) < 34: logfile.write("Insufficient file dimensions: " + str(image_path) + "\n") return None if int(im_width) > 4512 or int(im_height) > 3008: maxheight = int(3008) maxwidth = int(4512) resize_ratio = min(maxwidth/im_width, maxheight/im_height) im_width = int(im_width * resize_ratio) im_height = int(im_height * resize_ratio) image = image.resize((im_width, im_height)) image = image.convert('RGB') np_array = np.array(image.getdata()).reshape( (im_height, im_width, 3)).astype(np.uint8) image.close() # Hash the image in byte-chunks of 4096 hash_md5 = hashlib.md5() with open(image_path, "rb") as f: for chunk in iter(lambda: f.read(4096), b""): hash_md5.update(chunk) f.close() hashvalue = hash_md5.hexdigest() return image_path, hashvalue, np_array #Throw errors to stdout except IOError or OSError: magictype = str(magic.from_file((image_path), mime=True)) # If image file cannot be read, check if it is a video if magictype[:5] == 'video': #or magictype[12:17] == 'octet': # If so, return a video flag instead of numpy array flag = "VIDEO" elif magictype[:5] == 'audio': flag = "AUDIO" elif magictype[12:17] == 'octet': flag = "OCTET" else: image_path = "Could not open file: " + str(image_path) + " (" + str(magictype) + ")\n" flag = "ERROR" return image_path, flag except: magictype = str(magic.from_file((image_path), mime=True)) logfile.write("General error with file: " + str(image_path) + " (" + str(magictype) + ")\n") def check_video_orientation(image_path): # Function to check video rotation with ffprobe and return corresponding CV2 rotation code try: cmnd = ['ffprobe', '-loglevel', 'error', '-select_streams', 'v:0', '-show_entries', 'stream_tags=rotate', '-of', 'default=nw=1:nk=1', image_path] p = subprocess.Popen(cmnd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() orientation = out.decode('utf-8') if orientation == '': rotation = 3 elif int(orientation) == 180: rotation = 1 elif int(orientation) == 90: rotation = 0 else: rotation = 2 return rotation except: logfile.write("Cannot determine video rotation: " + str(image_path) + "\n") ###### # Worker function to prepare and reshape the input videos to a Numpy array # and to calculate the MD5 hashes of them. # The function analyzes as much frames as indicated in the variable "frames_per_second" (Default = 0.5) ###### def load_video_into_numpy_array(image_path): videoframes = [] old_hash = None # Loading the video via the OpenCV framework try: rotation = check_video_orientation(image_path) vidcap = cv2.VideoCapture(image_path) im_width = int(vidcap.get(cv2.CAP_PROP_FRAME_WIDTH)) im_height = int(vidcap.get(cv2.CAP_PROP_FRAME_HEIGHT)) # Switch height/width if video is to be rotated 90/270 degrees if rotation == 0 or rotation == 2: im_width_new = im_height im_height_new = im_width im_width = im_width_new im_height = im_height_new # Calculating frames per second, total frame count and analyze rate fps = int(vidcap.get(cv2.CAP_PROP_FPS)) framecount = int(vidcap.get(cv2.CAP_PROP_FRAME_COUNT)) analyze_rate = int(framecount / fps * frames_per_second) if 0 < analyze_rate < max_frames_per_video: int(analyze_rate) elif analyze_rate >= int(max_frames_per_video): analyze_rate = int(max_frames_per_video) #Limiting maximum frames per video else: videoerror = 'Unable to extract frames from video: ' + str(image_path) + '\n' return videoerror # Hashing the video once hash_md5 = hashlib.md5() with open(image_path, "rb") as f: for chunk in iter(lambda: f.read(4096), b""): hash_md5.update(chunk) hashvalue = hash_md5.hexdigest() # Extracting the frames from the video for percentile in range(0, analyze_rate): vidcap.set(cv2.CAP_PROP_POS_FRAMES, (framecount / analyze_rate) * percentile) success, extracted_frame = vidcap.read() if rotation != 3: extracted_frame = cv2.rotate(extracted_frame, rotation) extracted_frame = cv2.cvtColor(extracted_frame, cv2.COLOR_BGR2RGB) timecode = ((framecount / analyze_rate) * percentile) / fps timecode = str(strftime("%H:%M:%S", gmtime(timecode))) # And reshape them into a numpy array np_array = np.array(extracted_frame).reshape( (im_height, im_width, 3)).astype(np.uint8) if video_sensitivity > 0: # Compare the frame with the previous one for similarity, and drop if similar frame_to_check = Image.fromarray(np_array) new_hash = imagehash.phash(frame_to_check) if old_hash is None or (new_hash - old_hash > video_sensitivity): cluster = str(image_path + ";" + str(timecode)), hashvalue, np_array videoframes.append(cluster) old_hash = new_hash else: cluster = str(image_path + ";" + str(timecode)), hashvalue, np_array videoframes.append(cluster) vidcap.release() return videoframes except cv2.error: videoerror = 'Could not process video: ' + str(image_path) + '\n' return videoerror except: videoerror = 'General error processing video: ' + str(image_path) + '\n' return videoerror ###### # Detection within loaded images with Tensorflow framework # Creation of output file with hashes, detection scores and class ###### def run_inference_for_multiple_images(image_paths, images, hashvalues): # Open the results file again detectionresults_path = PATH_TO_RESULTS / 'Detection_Results.csv' detectionresults = open(str(detectionresults_path), 'a') for y in range(0, len(graphlist)): # Create TF Session with loaded graph detection_graph = tf.Graph() with detection_graph.as_default(): od_graph_def = tf.GraphDef() logfile.write("*" + str(datetime.now()) + ": \tStarting detection with model " + str(y + 1) + " of " + str(len(graphlist)) + "*\n") # Update progress indicator updateProgressMeter(7 + y, 'Detecting with model {}'.format(graphlist[y])) # Load the respective detetion graph from file with tf.gfile.GFile(graphlist[y], 'rb') as fid: serialized_graph = fid.read() od_graph_def.ParseFromString(serialized_graph) tf.import_graph_def(od_graph_def, name='') # Create TF session with tf.Session() as sess: # Get handles to input and output tensors ops = tf.get_default_graph().get_operations() all_tensor_names = {output.name for op in ops for output in op.outputs} tensor_dict = {} for key in [ 'num_detections', 'detection_scores', 'detection_classes' ]: tensor_name = key + ':0' if tensor_name in all_tensor_names: tensor_dict[key] = tf.get_default_graph().get_tensor_by_name( tensor_name) image_tensor = tf.get_default_graph().get_tensor_by_name('image_tensor:0') # Setting the detection limit of the different models. if "ISLogo" not in graphlist[y]: detectionlimit = 0.5 else: detectionlimit = 0.90 # Loading the label map of the corresponding graph category_index = indexlist[y] # Conduct actual detection within single image for index, image in enumerate(images): updateProgressMeter(7 + y, str(graphlist[y]) + '\nFile ' + str(index) + ' of ' + str(len(images))) try: output_dict = sess.run(tensor_dict, feed_dict={image_tensor: np.expand_dims(image, 0)}) # all outputs are float32 numpy arrays, so convert types as appropriate output_dict['num_detections'] = int(output_dict['num_detections'][0]) output_dict['detection_scores'] = output_dict['detection_scores'][0] detectionhit = output_dict['num_detections'] output_dict['detection_classes'] = output_dict['detection_classes'][0] hashvalue = hashvalues[index] image_path = image_paths[index] # Validate against detection limit (default: 65%) and write hash/score if above for j in range(detectionhit): score = output_dict['detection_scores'][j] category = category_index[output_dict['detection_classes'][j]] # Validate against the preconfigured minimum detection assurance and write to result file if (score >= detectionlimit): scorestring = str(score) if REPORT_FORMAT[0] == 'Nuix': line = ",".join([category['name'], "md5:" + hashvalue]) else: line = ",".join([Path(image_path).name, hashvalue, scorestring, category['name']]) detectionresults.write(line + "\n") except tf.errors.InvalidArgumentError: logfile.write("Unable to process file dimensions of file with hash: \t" + str(hashvalue) + "\n") logfile.write("*" + str(datetime.now()) + ": \tFinished detection with model " + str(y + 1) + "*\n") detectionresults.flush() detectionresults.close() ###### # Detect and count faces in loaded images # Prepare and call age/gender detection once done ###### def faceDetection(image_paths, images, hashvalues): detectionresults_path = PATH_TO_RESULTS / 'Detection_Results.csv' detectionresults = open(str(detectionresults_path), 'a') # Updating progress bar and logfile updateProgressMeter(10, 'Detecting with Face/Age/Gender Detector') logfile.write("*" + str(datetime.now()) + ": \tStarting detection with face/age/gender detection model*\n") # Applying constants as defined in Facenet minsize = 20 threshold = [0.6, 0.7, 0.7] factor = 0.709 # Creating different TF Session with tf.Session() as sess: # read pnet, rnet, onet models from Models/Face directory facemodel_path = Path('Models/Face') pnet, rnet, onet = detect_face.create_mtcnn(sess, str(facemodel_path)) # Helperlists for age/gender detection facelist = [] imagelist = [] # Inference for all images for index, image in enumerate(images): updateProgressMeter(10, 'Detecting with Face/Age/Gender Detector' + '\nFile ' + str(index) + ' of ' + str(len(images))) try: bounding_boxes, _ = detect_face.detect_face(image, minsize, pnet, rnet, onet, threshold, factor) nrof_faces = bounding_boxes.shape[0] # If a face was detected, go on if nrof_faces > 0: detectedFaces = bounding_boxes[:, 0:4] detectedFacesArray = [] img_size = np.asarray(image.shape)[0:2] if nrof_faces > 1: for single_face in range(nrof_faces): detectedFacesArray.append(np.squeeze(detectedFaces[single_face])) else: detectedFacesArray.append(np.squeeze(detectedFaces)) # Crop the detected face and add it to the list to conduct age/gender identification for x, detectedFaces in enumerate(detectedFacesArray): detectedFaces = np.squeeze(detectedFaces) bb = np.zeros(4, dtype=np.int32) bb[0] = np.maximum(detectedFaces[0], 0) bb[1] = np.maximum(detectedFaces[1], 0) bb[2] = np.minimum(detectedFaces[2], img_size[1]) bb[3] = np.minimum(detectedFaces[3], img_size[0]) cropped_Face = image[bb[1]:bb[3], bb[0]:bb[2], :] facelist.append(cropped_Face) imagelist.append(index) # Write the results of the face detection into the resultsfile if not len(bounding_boxes) == 0: hashvalue = hashvalues[index] number_of_faces = len(bounding_boxes) if REPORT_FORMAT[0] == 'Nuix': line = "Face,md5:" + hashvalue else: line = str(Path(image_paths[index]).name) + "," + str(hashvalue) + ",FACES," + str( number_of_faces) + "Faces" detectionresults.write(line + "\n") except tf.errors.InvalidArgumentError: errorcount += 1 logfile.write("Unable to detect faces in file with hash: \t" + str(hashvalue) + "\n") # Conduct age/gender recognition based on the list of detected & cropped faces if len(facelist) != 0: age_gender_detection(imagelist, facelist, hashvalues, image_paths) logfile.write("*" + str(datetime.now()) + ": \tFinished detection with face/age/gender detection model*\n") detectionresults.flush() detectionresults.close() ###### # Detection with the OPEN VINO Framework # Evaluate Age & Gender based on input faces ###### def age_gender_detection(imagelist, facelist, hashvalues, image_paths): # Acquire the age-gender detection model model_path = Path('Models/OpenVINO/age-gender') model_xml = str(model_path / 'model.xml') model_bin = str(model_path / 'model.bin') # Reopen the results file detectionresults_path = PATH_TO_RESULTS / 'Detection_Results.csv' detectionresults = open(str(detectionresults_path), 'a') # Plugin initialization for specified device and load extensions library if specified ie = IECore() # Read IR net = IENetwork(model=model_xml, weights=model_bin) input_blob = next(iter(net.inputs)) net.batch_size = len(facelist) # Read and pre-process input images n, c, h, w = net.inputs[input_blob].shape images = np.ndarray(shape=(n, c, h, w)) # Loading model to the plugin exec_net = ie.load_network(network=net, device_name='CPU') # Resize and reshape input faces for i in range(n): image = facelist[i] if image.shape[:-1] != (62, 62): h, w = image.shape[:2] # interpolation method if h > 62 or w > 62: # shrinking image interp = cv2.INTER_AREA else: # stretching image interp = cv2.INTER_CUBIC # aspect ratio of image aspect = w / h # compute scaling and pad sizing if aspect > 1: # horizontal image new_w = 62 new_h = np.round(new_w / aspect).astype(int) pad_vert = (62 - new_h) / 2 pad_top, pad_bot = np.floor(pad_vert).astype(int), np.ceil(pad_vert).astype(int) pad_left, pad_right = 0, 0 elif aspect < 1: # vertical image new_h = 62 new_w = np.round(new_h * aspect).astype(int) pad_horz = (62 - new_w) / 2 pad_left, pad_right = np.floor(pad_horz).astype(int), np.ceil(pad_horz).astype(int) pad_top, pad_bot = 0, 0 else: # square image new_h, new_w = 62, 62 pad_left, pad_right, pad_top, pad_bot = 0, 0, 0, 0 # set pad color padColor = 0 if len(image.shape) is 3 and not isinstance(padColor, ( list, tuple, np.ndarray)): # color image but only one color provided padColor = [padColor] * 3 # scale and pad scaled_img = cv2.resize(image, (new_w, new_h), interpolation=interp) scaled_img = cv2.cvtColor(scaled_img, cv2.COLOR_BGR2RGB) scaled_img = cv2.copyMakeBorder(scaled_img, pad_top, pad_bot, pad_left, pad_right, borderType=cv2.BORDER_CONSTANT, value=padColor) image = scaled_img.transpose((2, 0, 1)) # Change data layout from HWC to CHW images[i] = image # Conduct inference res = exec_net.infer(inputs={input_blob: images}) # Process inference results for y in range(len(facelist)): probable_age = int(np.squeeze(res['age_conv3'][y]) * 100) if np.squeeze(res['prob'][y][0]) > 0.5: gender = "Female" else: gender = "Male" age_gender_combo = str(probable_age) + str(gender) # Write inference results to resultsfile hashvalue = hashvalues[imagelist[y]] if REPORT_FORMAT[0] == 'Nuix': line = str(age_gender_combo) + ",md5:" + hashvalue else: line = str(Path(image_paths[imagelist[y]]).name) + "," + str(hashvalue) + ",AGE-GENDER," + str( age_gender_combo) detectionresults.write(line + "\n") ###### # Detection with the OPEN VINO Framework # Creation of output file with hashes, detection scores and class ###### def run_inference_openvino(image_paths, images, hashvalue): # Update progress meter and reopen results file updateProgressMeter(6, 'Detecting with OpenVINO Object Detector') logfile.write("*" + str(datetime.now()) + ": \tStarting detection with OpenVINO object detection model*\n") detectionresults_path = PATH_TO_RESULTS / 'Detection_Results.csv' detectionresults = open(str(detectionresults_path), 'a') # Fetch paths for openvino model model_path = Path('Models/OpenVINO/vgg19') model_xml = str(model_path / 'model.xml') model_bin = str(model_path / 'model.bin') model_labels = str(model_path / 'model.labels') temp_bilder = images # Plugin initialization for specified device and load extensions library if specified ie = IECore() # Read IR net = IENetwork(model=model_xml, weights=model_bin) input_blob = next(iter(net.inputs)) out_blob = next(iter(net.outputs)) net.batch_size = 4000 # Read and pre-process input images n, c, h, w = net.inputs[input_blob].shape images = np.ndarray(shape=(n, c, h, w)) # Loading model to the plugin exec_net = ie.load_network(network=net, device_name='CPU') # Create batches to prevent RAM overload batches = tuple(temp_bilder[x:x + net.batch_size] for x in range(0, len(temp_bilder), net.batch_size)) # Start sync inference for batch in batches: for index, temp_pic in enumerate(batch): temp_pic = cv2.resize(temp_pic, (w, h)) temp_pic = temp_pic.transpose((2, 0, 1)) images[index] = temp_pic res = exec_net.infer(inputs={input_blob: images}) # Processing output blob res = res[out_blob] # Prepare label file with open(model_labels, 'r') as f: labels_map = [x.split(sep=' ', maxsplit=1)[-1].strip() for x in f] # Clean inference results and write them to resultsfile for i, probs in enumerate(res): probs = np.squeeze(probs) top_ind = np.argsort(probs)[-3:][::-1] for id in top_ind: if probs[id] >= 0.3: # det_label = labels_map[id] if labels_map else "{}".format(id) det_label = labels_map[id].split(sep=' ', maxsplit=1)[1] if REPORT_FORMAT[0] == 'Nuix': line = ",".join([det_label, "md5:" + hashvalue]) else: line = ",".join([Path(image_paths[i]).name, hashvalue[i], str(probs[id]), str(det_label)]) detectionresults.write(line + "\n") logfile.write("*" + str(datetime.now()) + ": \tFinished detection with OpenVINO object detection model*\n") ###### # Worker function to load and encode known faces and to compare them against # the provided input material ###### def faceRecognition(known_faces_path, image_paths, images, hashvalues): # Update progress bar updateProgressMeter(5, 'Conducting Face Recognition') known_face_counter = 0 # Open the results file detectionresults_path = PATH_TO_RESULTS / 'Detection_Results.csv' detectionresults = open(str(detectionresults_path), 'a') OutputPictureFolder = PATH_TO_RESULTS / 'DetectedFaces' if not OutputPictureFolder.exists(): os.mkdir(str(OutputPictureFolder)) # Initiate array to store known faces known_face_encodings = [] known_face_names = [] known_faces = Path.iterdir(Path(known_faces_path)) # Create encodings and store them with names for known_face in known_faces: known_person_image = face_recognition.load_image_file(known_face) known_face_encodings.extend(face_recognition.face_encodings(known_person_image)) known_face_names.append(Path(known_face).stem) logfile.write("*" + str(datetime.now()) + ": \tStarting face recognition with " + str(len(known_face_names)) + " known faces*\n") # Load images, detect faces, encode and compare them to the known faces for index, image_to_detect in enumerate(images): hashvalue = hashvalues[index] image_path = image_paths[index] updateProgressMeter(5, 'Face Reco Image ' + str(index) + ' of ' + str(len(images))) # Use GPU based model to detect & encode face_locations = face_recognition.face_locations(image_to_detect, model="cnn") face_encodings = face_recognition.face_encodings(image_to_detect, face_locations) # Loop through each face in this frame of video for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings): # See if the face is a match for the known face(s) matches = face_recognition.compare_faces(known_face_encodings, face_encoding, tolerance=facereq_tolerance) name = "Unknown" # Check the face distance and get best match face_distances = face_recognition.face_distance(known_face_encodings, face_encoding) best_match_index = np.argmin(face_distances) if matches[best_match_index]: name = known_face_names[best_match_index] # If there is a match, write it to the output file if name != "Unknown": known_face_counter += 1 if REPORT_FORMAT[0] == 'Nuix': line = ",".join([name, "md5:" + hashvalue]) else: line = ",".join([Path(image_path).name, hashvalue, "FACE-Match", name]) detectionresults.write(line + "\n") if output_detFaces: # Export detected face with bounding box cv2.rectangle(image_to_detect, (left, top), (right, bottom), (0, 0, 255), 2) # Draw a label with a name below the face cv2.rectangle(image_to_detect, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED) font = cv2.FONT_HERSHEY_DUPLEX cv2.putText(image_to_detect, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1) savePath = str(OutputPictureFolder / str(Path(image_path).name)) + '.jpg' detectedFace = Image.fromarray(image_to_detect) detectedFace.save(savePath) logfile.write("*" + str(datetime.now()) + ": \tFace Recognition completed.*\n") detectionresults.flush() detectionresults.close() # Return amount of detected known faces return known_face_counter ###### # Worker function to conduct speech detection in audio files # for all audio files detected ###### def audioSpeechDetection(audiolist): logfile.write("*" + str(datetime.now()) + ": \tStarting audio speech detection*\n") updateProgressMeter(11, 'Processing Audio Files') audiocounter = 0 # Open the results file detectionresults_path = PATH_TO_RESULTS / 'Detection_Results.csv' detectionresults = open(str(detectionresults_path), 'a') pool = Pool(maxtasksperchild=100) result = pool.map(audioAnalysis.segmentSpeechDetection, audiolist, chunksize=10) pool.close() # Synchronize after completion pool.join() pool.terminate() result = [x for x in result if x != None] for processedAudio in result: speechPercentage, audiopath = processedAudio # Check for the video flag if not isinstance(speechPercentage, float): logfile.write("Unsupported audio file: " + str(audiopath) + "\n") else: speechPercentage, audiopath = processedAudio # Hashing the video once hash_md5 = hashlib.md5() with open(audiopath, "rb") as f: for chunk in iter(lambda: f.read(4096), b""): hash_md5.update(chunk) hashvalue = hash_md5.hexdigest() audiocounter += 1 if REPORT_FORMAT[0] == 'Nuix': if speechPercentage != 0.0: line = ",".join(["AUDIO-SPEECH", "md5:" + hashvalue]) else: line = ",".join([Path(audiopath).name, hashvalue, str(speechPercentage), "AUDIO-SPEECH"]) detectionresults.write(line + "\n") logfile.write("*" + str(datetime.now()) + ": \tAudio speech detection completed.*\n") detectionresults.flush() detectionresults.close() return audiocounter ###### # Split the report file to allow seamless integration into XWays Hash Database per category ###### def createXWaysReport(): detectionresults_path = str(PATH_TO_RESULTS / 'Detection_Results.csv') xways_folder = PATH_TO_RESULTS / 'XWaysOutput' if not xways_folder.exists(): os.mkdir(str(xways_folder)) for key, rows in groupby(csv.reader(open(detectionresults_path)), lambda row: row[3]): # Replace special characters in categories if str(key) != 'category': key = str(key).replace("/","-") key = str(key).replace(".", "") key = str(key).replace("(", "") key = str(key).replace(")", "") key = key + '.txt' detectionresults_single_path = xways_folder / key with open(str(detectionresults_single_path), 'a') as rf: for row in rows: rf.write(row[1] + "\n") rf.flush() # Get a list of all files in results directory resultsfiles = os.listdir(str(xways_folder)) # Prepend them with MD5 for seamless import into XWays for file in resultsfiles: line = "md5" if file[-3:] == 'txt' and file != 'Logfile.txt': with open(str(xways_folder / file), 'r+') as ff: content = ff.read() ff.seek(0,0) ff.write(line.rstrip('\r\n') + '\n' + content) ###### # # Main program function # First initiates required parameters and variables, then loads the GUI # After which the image and video load functions are triggered based on the input parameters # Finally, the detection is executed and results written to the place requested # ###### # Prevent execution when externally called if __name__ == '__main__': ###### # Collecting parameters via GUI ###### sg.ChangeLookAndFeel('Dark') layout = [[sg.Text('General Settings', font=("Helvetica", 13), text_color='sea green')], [sg.Text('Please specify the folder holding the media data:')], [sg.Input(), sg.FolderBrowse('Browse', initial_folder='/home/b/Desktop/TestBilder', button_color=('black', 'grey'))], #Path.home() = Initial folder [sg.Text('Where shall I place the results?')], [sg.Input(), sg.FolderBrowse('Browse', initial_folder='/home/b/Desktop/TestResults', button_color=('black', 'grey'))], #Path.home() [sg.Text('TENSORFLOW DETECTORS')], [sg.Checkbox('Objects/Persons', size=(15, 2)), sg.Checkbox('Actions'), sg.Checkbox('IS Logos'), sg.Checkbox("Face Recognition")], [sg.Text('OPEN VINO DETECTORS')], [sg.Checkbox('Objects-fast', size=(15, 2)), sg.Checkbox('Faces/Age/Gender')], [sg.Text('Output Format:'), sg.Listbox(values=('Nuix', 'XWays', 'csv'), size=(29, 3))], [sg.Text('Video Settings', font=("Helvetica", 13), text_color='sea green')], [sg.Text('# of frames to be analyzed per Minute:', size=(36, 0))], [sg.Slider(range=(1, 120), orientation='h', size=(29, 20), default_value=30)], [sg.Text('Max. # of frames to be analyzed per Video:', size=(36, 0))], [sg.Slider(range=(1, 500), orientation='h', size=(29, 20), default_value=100)], [sg.Text('Check for & discard similar frames?'), sg.InputCombo(('Yes', 'No'), default_value='No', size=(10, 2))], [sg.Text('Face Recognition', font=("Helvetica", 13), text_color='sea green')], [sg.Text('Specify folder with known faces (if FaceReq selected): ')], [sg.Input(), sg.FolderBrowse('Browse', initial_folder='/home/b/Desktop/known', button_color=('black', 'grey'))], [sg.Text('Specify face recognition tolerance (Default: 60%):', size=(48, 0))], [sg.Slider(range=(0, 100), orientation='h', size=(29, 20), default_value=60)], [sg.Checkbox('Output detected faces as jpg', size=(25, 2))], [sg.Text('Audio Settings', font=("Helvetica", 13), text_color='sea green')], [sg.Text('AUDIO PROCESSING')], [sg.Checkbox('Speech Detection', size=(15, 2))], [sg.OK(button_color=('black', 'sea green')), sg.Cancel(button_color=('black', 'grey'))]] layout_progress = [[sg.Text('Detection in progress')], [sg.ProgressBar(12, orientation='h', size=(20, 20), key='progressbar')], [sg.Cancel()]] # Render the GUI gui_input = sg.Window('BKP Media Detector').Layout(layout).Read() error = False # Validate input validateInput(gui_input) # Initiating progress meter updateProgressMeter(1, 'Initializing variables & parameters...') startTime = datetime.now() # Variable to determine minimum GPU Processor requirement & to disable TF log output # os.environ['TF_MIN_GPU_MULTIPROCESSOR_COUNT'] = '5' os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # Validating TF version if StrictVersion(tf.__version__) < StrictVersion('1.9.0'): raise ImportError('Please upgrade your TensorFlow installation to v1.9.* or later!') # Defining multiple needed variables based on GUI input & adding TF/OpenVINO directory to path PATH_TO_INPUT = Path(gui_input[1][0]) TEST_IMAGE_PATHS = Path.iterdir(PATH_TO_INPUT) number_of_input = 0 for elements in Path.iterdir(PATH_TO_INPUT): number_of_input += 1 PATH_TO_RESULTS = Path(gui_input[1][1]) PATH_TO_OBJECT_DETECTION_DIR = '/home/b/Programs/tensorflow/models/research' # PLACEHOLDER-tobereplacedWithPathtoDirectory sys.path.append(PATH_TO_OBJECT_DETECTION_DIR) REPORT_FORMAT = gui_input[1][8] frames_per_second = gui_input[1][9] / 60 max_frames_per_video = gui_input[1][10] video_sensitivity_text = gui_input[1][11] KNOWN_FACES_PATH = gui_input[1][12] facereq_tolerance = int(gui_input[1][13])/100 output_detFaces = gui_input[1][14] if video_sensitivity_text == "Yes": video_sensitivity = 20 else: video_sensitivity = 0 # Check which models to apply and load their corresponding label maps from object_detection.utils import label_map_util graphlist = [] indexlist = [] MODEL1 = bool(gui_input[1][2]) if MODEL1: OPEN_IMAGES_GRAPH = str(Path('Models/OpenImages/openimages.pb')) OPEN_IMAGES_LABELS = str(OPEN_IMAGES_GRAPH)[:-3] + '.pbtxt' OPEN_IMAGES_INDEX = label_map_util.create_category_index_from_labelmap(OPEN_IMAGES_LABELS) graphlist.append(OPEN_IMAGES_GRAPH) indexlist.append(OPEN_IMAGES_INDEX) MODEL2 = bool(gui_input[1][3]) if MODEL2: AVA_GRAPH = str(Path('Models/AVA/ava.pb')) AVA_LABELS = str(AVA_GRAPH)[:-3] + '.pbtxt' AVA_INDEX = label_map_util.create_category_index_from_labelmap(AVA_LABELS) graphlist.append(AVA_GRAPH) indexlist.append(AVA_INDEX) MODEL3 = bool(gui_input[1][4]) if MODEL3: SPECIAL_DETECTOR_GRAPH = str(Path('Models/ISLogos/islogos.pb')) SPECIAL_DETECTOR_LABELS = str(SPECIAL_DETECTOR_GRAPH)[:-3] + '.pbtxt' SPECIAL_DETECTOR_INDEX = label_map_util.create_category_index_from_labelmap(SPECIAL_DETECTOR_LABELS) graphlist.append(SPECIAL_DETECTOR_GRAPH) indexlist.append(SPECIAL_DETECTOR_INDEX) FACE_RECOGNITION = bool(gui_input[1][5]) OPEN_VINO_vgg19 = bool(gui_input[1][6]) FACE_MODEL = bool(gui_input[1][7]) AUDIO_SPEECH_DETECTION = bool(gui_input[1][15]) # Update the progress indicator updateProgressMeter(2, 'Process started. Loading ' + str(number_of_input) + ' media files...') # Create logfile logfile = open(str(PATH_TO_RESULTS / 'Logfile.txt'), 'w') logfile.write('***DETECTION LOG***\n') logfile.write("*" + str(datetime.now()) + ': \tProcess started. Loading images...*\n') # Create resultsfile detectionresults_path = PATH_TO_RESULTS / 'Detection_Results.csv' detectionresults = open(str(detectionresults_path), 'w') if REPORT_FORMAT[0] == 'Nuix': detectionresults.write("tag,searchterm\n") else: detectionresults.write("name,hash,score,category\n") detectionresults.flush() detectionresults.close() # Initiate needed variables vidlist = [] audiolist = [] final_images = [] errors = [] # Multiprocess the image load function on all CPU cores available pool = Pool(maxtasksperchild=100) processed_images = pool.map(load_image_into_numpy_array, TEST_IMAGE_PATHS, chunksize=10) pool.close() # Synchronize after completion pool.join() pool.terminate() # Clean the result for None types (where image conversion failed) processed_images = [x for x in processed_images if x != None] # Check for the different flags set by mimetype for processed_image in processed_images: if str(processed_image[1]) == "VIDEO": # If present, populate the video list vidlist.append(processed_image[0]) elif str(processed_image[1]) == "AUDIO": audiolist.append(processed_image[0]) elif str(processed_image[1]) == "OCTET": if processed_image[0][-3:] in ["mp4", "mov", "mpg", "avi", "exo", "mkv", "m4v", "ebm"]: vidlist.append(processed_image[0]) else: audiolist.append(processed_image[0]) elif str(processed_image[1]) == "ERROR": errors.append(processed_image[0]) else: # If not, put it to the final images list final_images.append(processed_image) for error in errors: logfile.write(error) logfile.flush() # Count the number of images before adding the videoframes number_of_images = len(final_images) # Update the progress indicator updateProgressMeter(3, 'Loading ' + str(len(vidlist)) + ' Videos...') # Multiprocess the video load function on all CPU cores available pool = Pool(maxtasksperchild=10) videoframes = pool.map(load_video_into_numpy_array, vidlist, chunksize=2) pool.close() # Synchronize after completion pool.join() pool.terminate() number_of_videos = 0 # Clean the result for None types (where video conversion failed) for video in videoframes: if type(video) is str: errors.append(video) if type(video) is list: final_images.extend(video) number_of_videos += 1 for error in errors: logfile.write(error) logfile.flush() # Split the result from the loading function into hashes and image arrays if len(final_images) != 0: image_path, hashvalues, image_nps = zip(*final_images) # Update the progress indicator & logfile updateProgressMeter(4, 'Starting detection of ' + str(len(final_images)) + ' media files') logfile.write("*" + str(datetime.now()) + ": \tLoading completed. Detecting...*\n") # Conduct Face Recognition if needed if FACE_RECOGNITION: known_face_counter = faceRecognition(KNOWN_FACES_PATH, image_path, image_nps, hashvalues) # Conduct OpenVino VGG19 Model if needed if OPEN_VINO_vgg19: run_inference_openvino(image_path, image_nps, hashvalues) # Execute all other detection models if len(final_images) != 0: run_inference_for_multiple_images(image_path, image_nps, hashvalues) # Conduct face/age/gender detection if FACE_MODEL: faceDetection(image_path, image_nps, hashvalues) if AUDIO_SPEECH_DETECTION: audiofiles_processed = audioSpeechDetection(audiolist) else: audiofiles_processed = 0 # Check whether an Xways report needs to be created if REPORT_FORMAT[0] == 'XWays': createXWaysReport() # Write process statistics to logfile logfile.write("*Results:\t\t\t" + str(PATH_TO_RESULTS / 'Detection_Results.csv*\n')) logfile.write("*Total Amount of Files:\t\t" + str(number_of_input) + " (of which " + str(number_of_images + number_of_videos + audiofiles_processed) + " were processed.)*\n") logfile.write("*Processed Images:\t\t" + str(number_of_images) + "*\n") logfile.write("*Processed Videos: \t\t" + str(number_of_videos) + " (analyzed " + str(frames_per_second * 60) + " frames per minute, up to max. 500) with the check for content-based duplicates set to " + video_sensitivity_text + "\n") logfile.write("*Processed Audio Files:\t\t" + str(audiofiles_processed) + "*\n") logfile.write("*Applied models:\n") for y in range(0, len(graphlist)): logfile.write("\t\t\t\t" + graphlist[y] + "\n") if OPEN_VINO_vgg19: logfile.write("\t\t\t\tOpenVINO Object Detector\n") if FACE_MODEL: logfile.write("\t\t\t\tFace-Age-Gender Detector\n") if FACE_RECOGNITION: logfile.write("\t\t\t\tFace Recognition (Known faces detected: " + str(known_face_counter) + ")\n") logfile.write("*Processing time:\t\t" + str(datetime.now() - startTime) + "*\n") logfile.write("*Time per processed file:\t" + str((datetime.now() - startTime) / (number_of_images + number_of_videos + audiofiles_processed)) + "*\n") logfile.flush() logfile.close() # Update progress indicator sg.OneLineProgressMeter('BKP Media Detector', 12, 12, 'key', 'Detection finished',orientation='h',size=(100, 10)) # Deliver final success pop up to user sg.Popup('The detection was successful', 'The results are placed here:', 'Path: "{}"'.format(str(PATH_TO_RESULTS)))
[ "cv2.rectangle", "PySimpleGUI.OneLineProgressMeter", "numpy.argsort", "numpy.array", "face_recognition.load_image_file", "tensorflow.gfile.GFile", "PySimpleGUI.OK", "sys.path.append", "tensorflow.Graph", "PySimpleGUI.Popup", "PySimpleGUI.Slider", "pathlib.Path", "subprocess.Popen", "tensorflow.Session", "numpy.asarray", "tensorflow.GraphDef", "face_recognition.face_distance", "openvino.inference_engine.IECore", "PySimpleGUI.Input", "numpy.argmin", "numpy.maximum", "openvino.inference_engine.IENetwork", "tensorflow.get_default_graph", "numpy.round", "pathlib.Path.iterdir", "face_recognition.face_locations", "numpy.ceil", "hashlib.md5", "PySimpleGUI.Listbox", "magic.from_file", "numpy.floor", "PySimpleGUI.Text", "numpy.squeeze", "cv2.putText", "PySimpleGUI.InputCombo", "object_detection.utils.label_map_util.create_category_index_from_labelmap", "cv2.cvtColor", "imagehash.phash", "tensorflow.import_graph_def", "distutils.version.StrictVersion", "cv2.resize", "time.gmtime", "PIL.Image.fromarray", "PIL.Image.open", "numpy.minimum", "PySimpleGUI.FolderBrowse", "PySimpleGUI.Checkbox", "PySimpleGUI.Cancel", "cv2.copyMakeBorder", "PySimpleGUI.ProgressBar", "cv2.rotate", "datetime.datetime.now", "numpy.zeros", "numpy.ndarray", "multiprocessing.Pool", "cv2.VideoCapture", "face_recognition.face_encodings", "face_recognition.compare_faces", "Models.Face.detect_face.detect_face", "numpy.expand_dims", "PySimpleGUI.Window", "PySimpleGUI.ChangeLookAndFeel" ]
[((16564, 16598), 'pathlib.Path', 'Path', (['"""Models/OpenVINO/age-gender"""'], {}), "('Models/OpenVINO/age-gender')\n", (16568, 16598), False, 'from pathlib import Path\n'), ((16953, 16961), 'openvino.inference_engine.IECore', 'IECore', ([], {}), '()\n', (16959, 16961), False, 'from openvino.inference_engine import IENetwork, IECore\n'), ((16987, 17032), 'openvino.inference_engine.IENetwork', 'IENetwork', ([], {'model': 'model_xml', 'weights': 'model_bin'}), '(model=model_xml, weights=model_bin)\n', (16996, 17032), False, 'from openvino.inference_engine import IENetwork, IECore\n'), ((17208, 17238), 'numpy.ndarray', 'np.ndarray', ([], {'shape': '(n, c, h, w)'}), '(shape=(n, c, h, w))\n', (17218, 17238), True, 'import numpy as np\n'), ((20732, 20761), 'pathlib.Path', 'Path', (['"""Models/OpenVINO/vgg19"""'], {}), "('Models/OpenVINO/vgg19')\n", (20736, 20761), False, 'from pathlib import Path\n'), ((21032, 21040), 'openvino.inference_engine.IECore', 'IECore', ([], {}), '()\n', (21038, 21040), False, 'from openvino.inference_engine import IENetwork, IECore\n'), ((21066, 21111), 'openvino.inference_engine.IENetwork', 'IENetwork', ([], {'model': 'model_xml', 'weights': 'model_bin'}), '(model=model_xml, weights=model_bin)\n', (21075, 21111), False, 'from openvino.inference_engine import IENetwork, IECore\n'), ((21318, 21348), 'numpy.ndarray', 'np.ndarray', ([], {'shape': '(n, c, h, w)'}), '(shape=(n, c, h, w))\n', (21328, 21348), True, 'import numpy as np\n'), ((27234, 27260), 'multiprocessing.Pool', 'Pool', ([], {'maxtasksperchild': '(100)'}), '(maxtasksperchild=100)\n', (27238, 27260), False, 'from multiprocessing import Pool\n'), ((30475, 30503), 'PySimpleGUI.ChangeLookAndFeel', 'sg.ChangeLookAndFeel', (['"""Dark"""'], {}), "('Dark')\n", (30495, 30503), True, 'import PySimpleGUI as sg\n'), ((33467, 33481), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (33479, 33481), False, 'from datetime import datetime\n'), ((33979, 34000), 'pathlib.Path', 'Path', (['gui_input[1][0]'], {}), '(gui_input[1][0])\n', (33983, 34000), False, 'from pathlib import Path\n'), ((34024, 34051), 'pathlib.Path.iterdir', 'Path.iterdir', (['PATH_TO_INPUT'], {}), '(PATH_TO_INPUT)\n', (34036, 34051), False, 'from pathlib import Path\n'), ((34096, 34123), 'pathlib.Path.iterdir', 'Path.iterdir', (['PATH_TO_INPUT'], {}), '(PATH_TO_INPUT)\n', (34108, 34123), False, 'from pathlib import Path\n'), ((34176, 34197), 'pathlib.Path', 'Path', (['gui_input[1][1]'], {}), '(gui_input[1][1])\n', (34180, 34197), False, 'from pathlib import Path\n'), ((34330, 34375), 'sys.path.append', 'sys.path.append', (['PATH_TO_OBJECT_DETECTION_DIR'], {}), '(PATH_TO_OBJECT_DETECTION_DIR)\n', (34345, 34375), False, 'import sys\n'), ((37150, 37176), 'multiprocessing.Pool', 'Pool', ([], {'maxtasksperchild': '(100)'}), '(maxtasksperchild=100)\n', (37154, 37176), False, 'from multiprocessing import Pool\n'), ((38693, 38718), 'multiprocessing.Pool', 'Pool', ([], {'maxtasksperchild': '(10)'}), '(maxtasksperchild=10)\n', (38697, 38718), False, 'from multiprocessing import Pool\n'), ((41916, 42035), 'PySimpleGUI.OneLineProgressMeter', 'sg.OneLineProgressMeter', (['"""BKP Media Detector"""', '(12)', '(12)', '"""key"""', '"""Detection finished"""'], {'orientation': '"""h"""', 'size': '(100, 10)'}), "('BKP Media Detector', 12, 12, 'key',\n 'Detection finished', orientation='h', size=(100, 10))\n", (41939, 42035), True, 'import PySimpleGUI as sg\n'), ((1114, 1255), 'PySimpleGUI.Popup', 'sg.Popup', (['"""You have not populated all required fields. Aborting!"""'], {'title': '"""Error"""', 'button_color': "('black', 'red')", 'background_color': '"""grey"""'}), "('You have not populated all required fields. Aborting!', title=\n 'Error', button_color=('black', 'red'), background_color='grey')\n", (1122, 1255), True, 'import PySimpleGUI as sg\n'), ((1378, 1488), 'PySimpleGUI.OneLineProgressMeter', 'sg.OneLineProgressMeter', (['"""BKP Media Detector"""', 'step', '(12)', '"""key"""', 'customText'], {'orientation': '"""h"""', 'size': '(50, 25)'}), "('BKP Media Detector', step, 12, 'key', customText,\n orientation='h', size=(50, 25))\n", (1401, 1488), True, 'import PySimpleGUI as sg\n'), ((1812, 1834), 'PIL.Image.open', 'Image.open', (['image_path'], {}), '(image_path)\n', (1822, 1834), False, 'from PIL import Image\n'), ((2646, 2659), 'hashlib.md5', 'hashlib.md5', ([], {}), '()\n', (2657, 2659), False, 'import hashlib\n'), ((4073, 4143), 'subprocess.Popen', 'subprocess.Popen', (['cmnd'], {'stdout': 'subprocess.PIPE', 'stderr': 'subprocess.PIPE'}), '(cmnd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n', (4089, 4143), False, 'import subprocess\n'), ((5017, 5045), 'cv2.VideoCapture', 'cv2.VideoCapture', (['image_path'], {}), '(image_path)\n', (5033, 5045), False, 'import cv2\n'), ((6100, 6113), 'hashlib.md5', 'hashlib.md5', ([], {}), '()\n', (6111, 6113), False, 'import hashlib\n'), ((8471, 8481), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (8479, 8481), True, 'import tensorflow as tf\n'), ((13177, 13189), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (13187, 13189), True, 'import tensorflow as tf\n'), ((13291, 13310), 'pathlib.Path', 'Path', (['"""Models/Face"""'], {}), "('Models/Face')\n", (13295, 13310), False, 'from pathlib import Path\n'), ((23711, 23733), 'pathlib.Path', 'Path', (['known_faces_path'], {}), '(known_faces_path)\n', (23715, 23733), False, 'from pathlib import Path\n'), ((23849, 23893), 'face_recognition.load_image_file', 'face_recognition.load_image_file', (['known_face'], {}), '(known_face)\n', (23881, 23893), False, 'import face_recognition\n'), ((24547, 24608), 'face_recognition.face_locations', 'face_recognition.face_locations', (['image_to_detect'], {'model': '"""cnn"""'}), "(image_to_detect, model='cnn')\n", (24578, 24608), False, 'import face_recognition\n'), ((24634, 24698), 'face_recognition.face_encodings', 'face_recognition.face_encodings', (['image_to_detect', 'face_locations'], {}), '(image_to_detect, face_locations)\n', (24665, 24698), False, 'import face_recognition\n'), ((33710, 33739), 'distutils.version.StrictVersion', 'StrictVersion', (['tf.__version__'], {}), '(tf.__version__)\n', (33723, 33739), False, 'from distutils.version import StrictVersion\n'), ((33742, 33764), 'distutils.version.StrictVersion', 'StrictVersion', (['"""1.9.0"""'], {}), "('1.9.0')\n", (33755, 33764), False, 'from distutils.version import StrictVersion\n'), ((35178, 35248), 'object_detection.utils.label_map_util.create_category_index_from_labelmap', 'label_map_util.create_category_index_from_labelmap', (['OPEN_IMAGES_LABELS'], {}), '(OPEN_IMAGES_LABELS)\n', (35228, 35248), False, 'from object_detection.utils import label_map_util\n'), ((35511, 35573), 'object_detection.utils.label_map_util.create_category_index_from_labelmap', 'label_map_util.create_category_index_from_labelmap', (['AVA_LABELS'], {}), '(AVA_LABELS)\n', (35561, 35573), False, 'from object_detection.utils import label_map_util\n'), ((35880, 35955), 'object_detection.utils.label_map_util.create_category_index_from_labelmap', 'label_map_util.create_category_index_from_labelmap', (['SPECIAL_DETECTOR_LABELS'], {}), '(SPECIAL_DETECTOR_LABELS)\n', (35930, 35955), False, 'from object_detection.utils import label_map_util\n'), ((6671, 6719), 'cv2.cvtColor', 'cv2.cvtColor', (['extracted_frame', 'cv2.COLOR_BGR2RGB'], {}), '(extracted_frame, cv2.COLOR_BGR2RGB)\n', (6683, 6719), False, 'import cv2\n'), ((8552, 8565), 'tensorflow.GraphDef', 'tf.GraphDef', ([], {}), '()\n', (8563, 8565), True, 'import tensorflow as tf\n'), ((18904, 18959), 'cv2.resize', 'cv2.resize', (['image', '(new_w, new_h)'], {'interpolation': 'interp'}), '(image, (new_w, new_h), interpolation=interp)\n', (18914, 18959), False, 'import cv2\n'), ((18985, 19028), 'cv2.cvtColor', 'cv2.cvtColor', (['scaled_img', 'cv2.COLOR_BGR2RGB'], {}), '(scaled_img, cv2.COLOR_BGR2RGB)\n', (18997, 19028), False, 'import cv2\n'), ((19054, 19175), 'cv2.copyMakeBorder', 'cv2.copyMakeBorder', (['scaled_img', 'pad_top', 'pad_bot', 'pad_left', 'pad_right'], {'borderType': 'cv2.BORDER_CONSTANT', 'value': 'padColor'}), '(scaled_img, pad_top, pad_bot, pad_left, pad_right,\n borderType=cv2.BORDER_CONSTANT, value=padColor)\n', (19072, 19175), False, 'import cv2\n'), ((19561, 19590), 'numpy.squeeze', 'np.squeeze', (["res['prob'][y][0]"], {}), "(res['prob'][y][0])\n", (19571, 19590), True, 'import numpy as np\n'), ((21726, 21754), 'cv2.resize', 'cv2.resize', (['temp_pic', '(w, h)'], {}), '(temp_pic, (w, h))\n', (21736, 21754), False, 'import cv2\n'), ((22243, 22260), 'numpy.squeeze', 'np.squeeze', (['probs'], {}), '(probs)\n', (22253, 22260), True, 'import numpy as np\n'), ((23930, 23981), 'face_recognition.face_encodings', 'face_recognition.face_encodings', (['known_person_image'], {}), '(known_person_image)\n', (23961, 23981), False, 'import face_recognition\n'), ((24936, 25036), 'face_recognition.compare_faces', 'face_recognition.compare_faces', (['known_face_encodings', 'face_encoding'], {'tolerance': 'facereq_tolerance'}), '(known_face_encodings, face_encoding,\n tolerance=facereq_tolerance)\n', (24966, 25036), False, 'import face_recognition\n'), ((25149, 25216), 'face_recognition.face_distance', 'face_recognition.face_distance', (['known_face_encodings', 'face_encoding'], {}), '(known_face_encodings, face_encoding)\n', (25179, 25216), False, 'import face_recognition\n'), ((25248, 25273), 'numpy.argmin', 'np.argmin', (['face_distances'], {}), '(face_distances)\n', (25257, 25273), True, 'import numpy as np\n'), ((27868, 27881), 'hashlib.md5', 'hashlib.md5', ([], {}), '()\n', (27879, 27881), False, 'import hashlib\n'), ((30520, 30595), 'PySimpleGUI.Text', 'sg.Text', (['"""General Settings"""'], {'font': "('Helvetica', 13)", 'text_color': '"""sea green"""'}), "('General Settings', font=('Helvetica', 13), text_color='sea green')\n", (30527, 30595), True, 'import PySimpleGUI as sg\n'), ((30613, 30673), 'PySimpleGUI.Text', 'sg.Text', (['"""Please specify the folder holding the media data:"""'], {}), "('Please specify the folder holding the media data:')\n", (30620, 30673), True, 'import PySimpleGUI as sg\n'), ((30691, 30701), 'PySimpleGUI.Input', 'sg.Input', ([], {}), '()\n', (30699, 30701), True, 'import PySimpleGUI as sg\n'), ((30703, 30809), 'PySimpleGUI.FolderBrowse', 'sg.FolderBrowse', (['"""Browse"""'], {'initial_folder': '"""/home/b/Desktop/TestBilder"""', 'button_color': "('black', 'grey')"}), "('Browse', initial_folder='/home/b/Desktop/TestBilder',\n button_color=('black', 'grey'))\n", (30718, 30809), True, 'import PySimpleGUI as sg\n'), ((30853, 30896), 'PySimpleGUI.Text', 'sg.Text', (['"""Where shall I place the results?"""'], {}), "('Where shall I place the results?')\n", (30860, 30896), True, 'import PySimpleGUI as sg\n'), ((30914, 30924), 'PySimpleGUI.Input', 'sg.Input', ([], {}), '()\n', (30922, 30924), True, 'import PySimpleGUI as sg\n'), ((30926, 31033), 'PySimpleGUI.FolderBrowse', 'sg.FolderBrowse', (['"""Browse"""'], {'initial_folder': '"""/home/b/Desktop/TestResults"""', 'button_color': "('black', 'grey')"}), "('Browse', initial_folder='/home/b/Desktop/TestResults',\n button_color=('black', 'grey'))\n", (30941, 31033), True, 'import PySimpleGUI as sg\n'), ((31060, 31091), 'PySimpleGUI.Text', 'sg.Text', (['"""TENSORFLOW DETECTORS"""'], {}), "('TENSORFLOW DETECTORS')\n", (31067, 31091), True, 'import PySimpleGUI as sg\n'), ((31109, 31153), 'PySimpleGUI.Checkbox', 'sg.Checkbox', (['"""Objects/Persons"""'], {'size': '(15, 2)'}), "('Objects/Persons', size=(15, 2))\n", (31120, 31153), True, 'import PySimpleGUI as sg\n'), ((31170, 31192), 'PySimpleGUI.Checkbox', 'sg.Checkbox', (['"""Actions"""'], {}), "('Actions')\n", (31181, 31192), True, 'import PySimpleGUI as sg\n'), ((31209, 31232), 'PySimpleGUI.Checkbox', 'sg.Checkbox', (['"""IS Logos"""'], {}), "('IS Logos')\n", (31220, 31232), True, 'import PySimpleGUI as sg\n'), ((31249, 31280), 'PySimpleGUI.Checkbox', 'sg.Checkbox', (['"""Face Recognition"""'], {}), "('Face Recognition')\n", (31260, 31280), True, 'import PySimpleGUI as sg\n'), ((31298, 31328), 'PySimpleGUI.Text', 'sg.Text', (['"""OPEN VINO DETECTORS"""'], {}), "('OPEN VINO DETECTORS')\n", (31305, 31328), True, 'import PySimpleGUI as sg\n'), ((31346, 31387), 'PySimpleGUI.Checkbox', 'sg.Checkbox', (['"""Objects-fast"""'], {'size': '(15, 2)'}), "('Objects-fast', size=(15, 2))\n", (31357, 31387), True, 'import PySimpleGUI as sg\n'), ((31404, 31435), 'PySimpleGUI.Checkbox', 'sg.Checkbox', (['"""Faces/Age/Gender"""'], {}), "('Faces/Age/Gender')\n", (31415, 31435), True, 'import PySimpleGUI as sg\n'), ((31453, 31478), 'PySimpleGUI.Text', 'sg.Text', (['"""Output Format:"""'], {}), "('Output Format:')\n", (31460, 31478), True, 'import PySimpleGUI as sg\n'), ((31480, 31537), 'PySimpleGUI.Listbox', 'sg.Listbox', ([], {'values': "('Nuix', 'XWays', 'csv')", 'size': '(29, 3)'}), "(values=('Nuix', 'XWays', 'csv'), size=(29, 3))\n", (31490, 31537), True, 'import PySimpleGUI as sg\n'), ((31555, 31628), 'PySimpleGUI.Text', 'sg.Text', (['"""Video Settings"""'], {'font': "('Helvetica', 13)", 'text_color': '"""sea green"""'}), "('Video Settings', font=('Helvetica', 13), text_color='sea green')\n", (31562, 31628), True, 'import PySimpleGUI as sg\n'), ((31646, 31709), 'PySimpleGUI.Text', 'sg.Text', (['"""# of frames to be analyzed per Minute:"""'], {'size': '(36, 0)'}), "('# of frames to be analyzed per Minute:', size=(36, 0))\n", (31653, 31709), True, 'import PySimpleGUI as sg\n'), ((31727, 31802), 'PySimpleGUI.Slider', 'sg.Slider', ([], {'range': '(1, 120)', 'orientation': '"""h"""', 'size': '(29, 20)', 'default_value': '(30)'}), "(range=(1, 120), orientation='h', size=(29, 20), default_value=30)\n", (31736, 31802), True, 'import PySimpleGUI as sg\n'), ((31820, 31887), 'PySimpleGUI.Text', 'sg.Text', (['"""Max. # of frames to be analyzed per Video:"""'], {'size': '(36, 0)'}), "('Max. # of frames to be analyzed per Video:', size=(36, 0))\n", (31827, 31887), True, 'import PySimpleGUI as sg\n'), ((31905, 31981), 'PySimpleGUI.Slider', 'sg.Slider', ([], {'range': '(1, 500)', 'orientation': '"""h"""', 'size': '(29, 20)', 'default_value': '(100)'}), "(range=(1, 500), orientation='h', size=(29, 20), default_value=100)\n", (31914, 31981), True, 'import PySimpleGUI as sg\n'), ((31999, 32045), 'PySimpleGUI.Text', 'sg.Text', (['"""Check for & discard similar frames?"""'], {}), "('Check for & discard similar frames?')\n", (32006, 32045), True, 'import PySimpleGUI as sg\n'), ((32062, 32124), 'PySimpleGUI.InputCombo', 'sg.InputCombo', (["('Yes', 'No')"], {'default_value': '"""No"""', 'size': '(10, 2)'}), "(('Yes', 'No'), default_value='No', size=(10, 2))\n", (32075, 32124), True, 'import PySimpleGUI as sg\n'), ((32142, 32217), 'PySimpleGUI.Text', 'sg.Text', (['"""Face Recognition"""'], {'font': "('Helvetica', 13)", 'text_color': '"""sea green"""'}), "('Face Recognition', font=('Helvetica', 13), text_color='sea green')\n", (32149, 32217), True, 'import PySimpleGUI as sg\n'), ((32235, 32301), 'PySimpleGUI.Text', 'sg.Text', (['"""Specify folder with known faces (if FaceReq selected): """'], {}), "('Specify folder with known faces (if FaceReq selected): ')\n", (32242, 32301), True, 'import PySimpleGUI as sg\n'), ((32319, 32329), 'PySimpleGUI.Input', 'sg.Input', ([], {}), '()\n', (32327, 32329), True, 'import PySimpleGUI as sg\n'), ((32331, 32432), 'PySimpleGUI.FolderBrowse', 'sg.FolderBrowse', (['"""Browse"""'], {'initial_folder': '"""/home/b/Desktop/known"""', 'button_color': "('black', 'grey')"}), "('Browse', initial_folder='/home/b/Desktop/known',\n button_color=('black', 'grey'))\n", (32346, 32432), True, 'import PySimpleGUI as sg\n'), ((32446, 32521), 'PySimpleGUI.Text', 'sg.Text', (['"""Specify face recognition tolerance (Default: 60%):"""'], {'size': '(48, 0)'}), "('Specify face recognition tolerance (Default: 60%):', size=(48, 0))\n", (32453, 32521), True, 'import PySimpleGUI as sg\n'), ((32539, 32614), 'PySimpleGUI.Slider', 'sg.Slider', ([], {'range': '(0, 100)', 'orientation': '"""h"""', 'size': '(29, 20)', 'default_value': '(60)'}), "(range=(0, 100), orientation='h', size=(29, 20), default_value=60)\n", (32548, 32614), True, 'import PySimpleGUI as sg\n'), ((32632, 32689), 'PySimpleGUI.Checkbox', 'sg.Checkbox', (['"""Output detected faces as jpg"""'], {'size': '(25, 2)'}), "('Output detected faces as jpg', size=(25, 2))\n", (32643, 32689), True, 'import PySimpleGUI as sg\n'), ((32707, 32780), 'PySimpleGUI.Text', 'sg.Text', (['"""Audio Settings"""'], {'font': "('Helvetica', 13)", 'text_color': '"""sea green"""'}), "('Audio Settings', font=('Helvetica', 13), text_color='sea green')\n", (32714, 32780), True, 'import PySimpleGUI as sg\n'), ((32798, 32825), 'PySimpleGUI.Text', 'sg.Text', (['"""AUDIO PROCESSING"""'], {}), "('AUDIO PROCESSING')\n", (32805, 32825), True, 'import PySimpleGUI as sg\n'), ((32843, 32888), 'PySimpleGUI.Checkbox', 'sg.Checkbox', (['"""Speech Detection"""'], {'size': '(15, 2)'}), "('Speech Detection', size=(15, 2))\n", (32854, 32888), True, 'import PySimpleGUI as sg\n'), ((32906, 32948), 'PySimpleGUI.OK', 'sg.OK', ([], {'button_color': "('black', 'sea green')"}), "(button_color=('black', 'sea green'))\n", (32911, 32948), True, 'import PySimpleGUI as sg\n'), ((32950, 32991), 'PySimpleGUI.Cancel', 'sg.Cancel', ([], {'button_color': "('black', 'grey')"}), "(button_color=('black', 'grey'))\n", (32959, 32991), True, 'import PySimpleGUI as sg\n'), ((33019, 33051), 'PySimpleGUI.Text', 'sg.Text', (['"""Detection in progress"""'], {}), "('Detection in progress')\n", (33026, 33051), True, 'import PySimpleGUI as sg\n'), ((33078, 33147), 'PySimpleGUI.ProgressBar', 'sg.ProgressBar', (['(12)'], {'orientation': '"""h"""', 'size': '(20, 20)', 'key': '"""progressbar"""'}), "(12, orientation='h', size=(20, 20), key='progressbar')\n", (33092, 33147), True, 'import PySimpleGUI as sg\n'), ((33174, 33185), 'PySimpleGUI.Cancel', 'sg.Cancel', ([], {}), '()\n', (33183, 33185), True, 'import PySimpleGUI as sg\n'), ((35041, 35080), 'pathlib.Path', 'Path', (['"""Models/OpenImages/openimages.pb"""'], {}), "('Models/OpenImages/openimages.pb')\n", (35045, 35080), False, 'from pathlib import Path\n'), ((35412, 35437), 'pathlib.Path', 'Path', (['"""Models/AVA/ava.pb"""'], {}), "('Models/AVA/ava.pb')\n", (35416, 35437), False, 'from pathlib import Path\n'), ((35734, 35767), 'pathlib.Path', 'Path', (['"""Models/ISLogos/islogos.pb"""'], {}), "('Models/ISLogos/islogos.pb')\n", (35738, 35767), False, 'from pathlib import Path\n'), ((2990, 3028), 'magic.from_file', 'magic.from_file', (['image_path'], {'mime': '(True)'}), '(image_path, mime=True)\n', (3005, 3028), False, 'import magic\n'), ((3600, 3638), 'magic.from_file', 'magic.from_file', (['image_path'], {'mime': '(True)'}), '(image_path, mime=True)\n', (3615, 3638), False, 'import magic\n'), ((6602, 6639), 'cv2.rotate', 'cv2.rotate', (['extracted_frame', 'rotation'], {}), '(extracted_frame, rotation)\n', (6612, 6639), False, 'import cv2\n'), ((7193, 7218), 'PIL.Image.fromarray', 'Image.fromarray', (['np_array'], {}), '(np_array)\n', (7208, 7218), False, 'from PIL import Image\n'), ((7246, 7277), 'imagehash.phash', 'imagehash.phash', (['frame_to_check'], {}), '(frame_to_check)\n', (7261, 7277), False, 'import imagehash\n'), ((8915, 8949), 'tensorflow.gfile.GFile', 'tf.gfile.GFile', (['graphlist[y]', '"""rb"""'], {}), "(graphlist[y], 'rb')\n", (8929, 8949), True, 'import tensorflow as tf\n'), ((9083, 9125), 'tensorflow.import_graph_def', 'tf.import_graph_def', (['od_graph_def'], {'name': '""""""'}), "(od_graph_def, name='')\n", (9102, 9125), True, 'import tensorflow as tf\n'), ((9176, 9188), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (9186, 9188), True, 'import tensorflow as tf\n'), ((13751, 13827), 'Models.Face.detect_face.detect_face', 'detect_face.detect_face', (['image', 'minsize', 'pnet', 'rnet', 'onet', 'threshold', 'factor'], {}), '(image, minsize, pnet, rnet, onet, threshold, factor)\n', (13774, 13827), False, 'from Models.Face import detect_face\n'), ((19511, 19542), 'numpy.squeeze', 'np.squeeze', (["res['age_conv3'][y]"], {}), "(res['age_conv3'][y])\n", (19521, 19542), True, 'import numpy as np\n'), ((24015, 24031), 'pathlib.Path', 'Path', (['known_face'], {}), '(known_face)\n', (24019, 24031), False, 'from pathlib import Path\n'), ((6840, 6856), 'time.gmtime', 'gmtime', (['timecode'], {}), '(timecode)\n', (6846, 6856), False, 'from time import gmtime\n'), ((12931, 12945), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (12943, 12945), False, 'from datetime import datetime\n'), ((16185, 16199), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (16197, 16199), False, 'from datetime import datetime\n'), ((20462, 20476), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (20474, 20476), False, 'from datetime import datetime\n'), ((22284, 22301), 'numpy.argsort', 'np.argsort', (['probs'], {}), '(probs)\n', (22294, 22301), True, 'import numpy as np\n'), ((22893, 22907), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (22905, 22907), False, 'from datetime import datetime\n'), ((25907, 25983), 'cv2.rectangle', 'cv2.rectangle', (['image_to_detect', '(left, top)', '(right, bottom)', '(0, 0, 255)', '(2)'], {}), '(image_to_detect, (left, top), (right, bottom), (0, 0, 255), 2)\n', (25920, 25983), False, 'import cv2\n'), ((26067, 26164), 'cv2.rectangle', 'cv2.rectangle', (['image_to_detect', '(left, bottom - 35)', '(right, bottom)', '(0, 0, 255)', 'cv2.FILLED'], {}), '(image_to_detect, (left, bottom - 35), (right, bottom), (0, 0,\n 255), cv2.FILLED)\n', (26080, 26164), False, 'import cv2\n'), ((26232, 26325), 'cv2.putText', 'cv2.putText', (['image_to_detect', 'name', '(left + 6, bottom - 6)', 'font', '(1.0)', '(255, 255, 255)', '(1)'], {}), '(image_to_detect, name, (left + 6, bottom - 6), font, 1.0, (255,\n 255, 255), 1)\n', (26243, 26325), False, 'import cv2\n'), ((26453, 26485), 'PIL.Image.fromarray', 'Image.fromarray', (['image_to_detect'], {}), '(image_to_detect)\n', (26468, 26485), False, 'from PIL import Image\n'), ((26563, 26577), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (26575, 26577), False, 'from datetime import datetime\n'), ((26926, 26940), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (26938, 26940), False, 'from datetime import datetime\n'), ((28470, 28484), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (28482, 28484), False, 'from datetime import datetime\n'), ((33226, 33257), 'PySimpleGUI.Window', 'sg.Window', (['"""BKP Media Detector"""'], {}), "('BKP Media Detector')\n", (33235, 33257), True, 'import PySimpleGUI as sg\n'), ((36526, 36540), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (36538, 36540), False, 'from datetime import datetime\n'), ((39601, 39615), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (39613, 39615), False, 'from datetime import datetime\n'), ((9278, 9300), 'tensorflow.get_default_graph', 'tf.get_default_graph', ([], {}), '()\n', (9298, 9300), True, 'import tensorflow as tf\n'), ((9825, 9847), 'tensorflow.get_default_graph', 'tf.get_default_graph', ([], {}), '()\n', (9845, 9847), True, 'import tensorflow as tf\n'), ((14099, 14122), 'numpy.asarray', 'np.asarray', (['image.shape'], {}), '(image.shape)\n', (14109, 14122), True, 'import numpy as np\n'), ((14648, 14673), 'numpy.squeeze', 'np.squeeze', (['detectedFaces'], {}), '(detectedFaces)\n', (14658, 14673), True, 'import numpy as np\n'), ((14703, 14730), 'numpy.zeros', 'np.zeros', (['(4)'], {'dtype': 'np.int32'}), '(4, dtype=np.int32)\n', (14711, 14730), True, 'import numpy as np\n'), ((14763, 14794), 'numpy.maximum', 'np.maximum', (['detectedFaces[0]', '(0)'], {}), '(detectedFaces[0], 0)\n', (14773, 14794), True, 'import numpy as np\n'), ((14827, 14858), 'numpy.maximum', 'np.maximum', (['detectedFaces[1]', '(0)'], {}), '(detectedFaces[1], 0)\n', (14837, 14858), True, 'import numpy as np\n'), ((14891, 14932), 'numpy.minimum', 'np.minimum', (['detectedFaces[2]', 'img_size[1]'], {}), '(detectedFaces[2], img_size[1])\n', (14901, 14932), True, 'import numpy as np\n'), ((14965, 15006), 'numpy.minimum', 'np.minimum', (['detectedFaces[3]', 'img_size[0]'], {}), '(detectedFaces[3], img_size[0])\n', (14975, 15006), True, 'import numpy as np\n'), ((17917, 17941), 'numpy.round', 'np.round', (['(new_w / aspect)'], {}), '(new_w / aspect)\n', (17925, 17941), True, 'import numpy as np\n'), ((41646, 41660), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (41658, 41660), False, 'from datetime import datetime\n'), ((6933, 6958), 'numpy.array', 'np.array', (['extracted_frame'], {}), '(extracted_frame)\n', (6941, 6958), True, 'import numpy as np\n'), ((14400, 14425), 'numpy.squeeze', 'np.squeeze', (['detectedFaces'], {}), '(detectedFaces)\n', (14410, 14425), True, 'import numpy as np\n'), ((18033, 18051), 'numpy.floor', 'np.floor', (['pad_vert'], {}), '(pad_vert)\n', (18041, 18051), True, 'import numpy as np\n'), ((18065, 18082), 'numpy.ceil', 'np.ceil', (['pad_vert'], {}), '(pad_vert)\n', (18072, 18082), True, 'import numpy as np\n'), ((18236, 18260), 'numpy.round', 'np.round', (['(new_h * aspect)'], {}), '(new_h * aspect)\n', (18244, 18260), True, 'import numpy as np\n'), ((24067, 24081), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (24079, 24081), False, 'from datetime import datetime\n'), ((28320, 28335), 'pathlib.Path', 'Path', (['audiopath'], {}), '(audiopath)\n', (28324, 28335), False, 'from pathlib import Path\n'), ((41738, 41752), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (41750, 41752), False, 'from datetime import datetime\n'), ((9709, 9731), 'tensorflow.get_default_graph', 'tf.get_default_graph', ([], {}), '()\n', (9729, 9731), True, 'import tensorflow as tf\n'), ((14284, 14322), 'numpy.squeeze', 'np.squeeze', (['detectedFaces[single_face]'], {}), '(detectedFaces[single_face])\n', (14294, 14322), True, 'import numpy as np\n'), ((18355, 18373), 'numpy.floor', 'np.floor', (['pad_horz'], {}), '(pad_horz)\n', (18363, 18373), True, 'import numpy as np\n'), ((18387, 18404), 'numpy.ceil', 'np.ceil', (['pad_horz'], {}), '(pad_horz)\n', (18394, 18404), True, 'import numpy as np\n'), ((25682, 25698), 'pathlib.Path', 'Path', (['image_path'], {}), '(image_path)\n', (25686, 25698), False, 'from pathlib import Path\n'), ((10620, 10644), 'numpy.expand_dims', 'np.expand_dims', (['image', '(0)'], {}), '(image, 0)\n', (10634, 10644), True, 'import numpy as np\n'), ((19964, 19995), 'pathlib.Path', 'Path', (['image_paths[imagelist[y]]'], {}), '(image_paths[imagelist[y]])\n', (19968, 19995), False, 'from pathlib import Path\n'), ((22734, 22754), 'pathlib.Path', 'Path', (['image_paths[i]'], {}), '(image_paths[i])\n', (22738, 22754), False, 'from pathlib import Path\n'), ((12364, 12378), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (12376, 12378), False, 'from datetime import datetime\n'), ((26384, 26400), 'pathlib.Path', 'Path', (['image_path'], {}), '(image_path)\n', (26388, 26400), False, 'from pathlib import Path\n'), ((8602, 8616), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (8614, 8616), False, 'from datetime import datetime\n'), ((12007, 12023), 'pathlib.Path', 'Path', (['image_path'], {}), '(image_path)\n', (12011, 12023), False, 'from pathlib import Path\n'), ((15587, 15611), 'pathlib.Path', 'Path', (['image_paths[index]'], {}), '(image_paths[index])\n', (15591, 15611), False, 'from pathlib import Path\n')]
""" Laplacian of a compressed-sparse graph """ # Authors: <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # License: BSD import numpy as np from scipy.sparse import isspmatrix, coo_matrix ############################################################################### # Graph laplacian def laplacian(csgraph, normed=False, return_diag=False): """ Return the Laplacian matrix of a directed graph. For non-symmetric graphs the out-degree is used in the computation. Parameters ---------- csgraph : array_like or sparse matrix, 2 dimensions compressed-sparse graph, with shape (N, N). normed : bool, optional If True, then compute normalized Laplacian. return_diag : bool, optional If True, then return diagonal as well as laplacian. Returns ------- lap : ndarray The N x N laplacian matrix of graph. diag : ndarray The length-N diagonal of the laplacian matrix. diag is returned only if return_diag is True. Notes ----- The Laplacian matrix of a graph is sometimes referred to as the "Kirchoff matrix" or the "admittance matrix", and is useful in many parts of spectral graph theory. In particular, the eigen-decomposition of the laplacian matrix can give insight into many properties of the graph. For non-symmetric directed graphs, the laplacian is computed using the out-degree of each node. Examples -------- >>> from scipy.sparse import csgraph >>> G = np.arange(5) * np.arange(5)[:, np.newaxis] >>> G array([[ 0, 0, 0, 0, 0], [ 0, 1, 2, 3, 4], [ 0, 2, 4, 6, 8], [ 0, 3, 6, 9, 12], [ 0, 4, 8, 12, 16]]) >>> csgraph.laplacian(G, normed=False) array([[ 0, 0, 0, 0, 0], [ 0, 9, -2, -3, -4], [ 0, -2, 16, -6, -8], [ 0, -3, -6, 21, -12], [ 0, -4, -8, -12, 24]]) """ if csgraph.ndim != 2 or csgraph.shape[0] != csgraph.shape[1]: raise ValueError('csgraph must be a square matrix or array') if normed and (np.issubdtype(csgraph.dtype, np.int) or np.issubdtype(csgraph.dtype, np.uint)): csgraph = csgraph.astype(np.float) if isspmatrix(csgraph): return _laplacian_sparse(csgraph, normed=normed, return_diag=return_diag) else: return _laplacian_dense(csgraph, normed=normed, return_diag=return_diag) def _laplacian_sparse(graph, normed=False, return_diag=False): n_nodes = graph.shape[0] if not graph.format == 'coo': lap = (-graph).tocoo() else: lap = -graph.copy() diag_mask = (lap.row == lap.col) if not diag_mask.sum() == n_nodes: # The sparsity pattern of the matrix has holes on the diagonal, # we need to fix that diag_idx = lap.row[diag_mask] diagonal_holes = list(set(range(n_nodes)).difference( diag_idx)) new_data = np.concatenate([lap.data, np.ones(len(diagonal_holes))]) new_row = np.concatenate([lap.row, diagonal_holes]) new_col = np.concatenate([lap.col, diagonal_holes]) lap = coo_matrix((new_data, (new_row, new_col)), shape=lap.shape) diag_mask = (lap.row == lap.col) lap.data[diag_mask] = 0 w = -np.asarray(lap.sum(axis=1)).squeeze() if normed: w = np.sqrt(w) w_zeros = (w == 0) w[w_zeros] = 1 lap.data /= w[lap.row] lap.data /= w[lap.col] lap.data[diag_mask] = (1 - w_zeros[lap.row[diag_mask]]).astype(lap.data.dtype) else: lap.data[diag_mask] = w[lap.row[diag_mask]] if return_diag: return lap, w return lap def _laplacian_dense(graph, normed=False, return_diag=False): n_nodes = graph.shape[0] lap = -np.asarray(graph) # minus sign leads to a copy # set diagonal to zero lap.flat[::n_nodes + 1] = 0 w = -lap.sum(axis=0) if normed: w = np.sqrt(w) w_zeros = (w == 0) w[w_zeros] = 1 lap /= w lap /= w[:, np.newaxis] lap.flat[::n_nodes + 1] = 1 - w_zeros else: lap.flat[::n_nodes + 1] = w if return_diag: return lap, w return lap
[ "scipy.sparse.isspmatrix", "numpy.sqrt", "numpy.asarray", "numpy.issubdtype", "numpy.concatenate", "scipy.sparse.coo_matrix" ]
[((2298, 2317), 'scipy.sparse.isspmatrix', 'isspmatrix', (['csgraph'], {}), '(csgraph)\n', (2308, 2317), False, 'from scipy.sparse import isspmatrix, coo_matrix\n'), ((3169, 3210), 'numpy.concatenate', 'np.concatenate', (['[lap.row, diagonal_holes]'], {}), '([lap.row, diagonal_holes])\n', (3183, 3210), True, 'import numpy as np\n'), ((3229, 3270), 'numpy.concatenate', 'np.concatenate', (['[lap.col, diagonal_holes]'], {}), '([lap.col, diagonal_holes])\n', (3243, 3270), True, 'import numpy as np\n'), ((3285, 3344), 'scipy.sparse.coo_matrix', 'coo_matrix', (['(new_data, (new_row, new_col))'], {'shape': 'lap.shape'}), '((new_data, (new_row, new_col)), shape=lap.shape)\n', (3295, 3344), False, 'from scipy.sparse import isspmatrix, coo_matrix\n'), ((3489, 3499), 'numpy.sqrt', 'np.sqrt', (['w'], {}), '(w)\n', (3496, 3499), True, 'import numpy as np\n'), ((3923, 3940), 'numpy.asarray', 'np.asarray', (['graph'], {}), '(graph)\n', (3933, 3940), True, 'import numpy as np\n'), ((4083, 4093), 'numpy.sqrt', 'np.sqrt', (['w'], {}), '(w)\n', (4090, 4093), True, 'import numpy as np\n'), ((2148, 2184), 'numpy.issubdtype', 'np.issubdtype', (['csgraph.dtype', 'np.int'], {}), '(csgraph.dtype, np.int)\n', (2161, 2184), True, 'import numpy as np\n'), ((2207, 2244), 'numpy.issubdtype', 'np.issubdtype', (['csgraph.dtype', 'np.uint'], {}), '(csgraph.dtype, np.uint)\n', (2220, 2244), True, 'import numpy as np\n')]
from .base import Controller from .base import Action import numpy as np import pandas as pd import logging from collections import namedtuple from tqdm import tqdm logger = logging.getLogger(__name__) CONTROL_QUEST = 'simglucose/params/Quest.csv' PATIENT_PARA_FILE = 'simglucose/params/vpatient_params.csv' ParamTup = namedtuple('ParamTup', ['basal', 'cf', 'cr']) class BBController(Controller): """ This is a Basal-Bolus Controller that is typically practiced by a Type-1 Diabetes patient. The performance of this controller can serve as a baseline when developing a more advanced controller. """ def __init__(self, target=140): self.quest = pd.read_csv(CONTROL_QUEST) self.patient_params = pd.read_csv(PATIENT_PARA_FILE) self.target = target def policy(self, observation, reward, done, **kwargs): sample_time = kwargs.get('sample_time', 1) pname = kwargs.get('patient_name') meal = kwargs.get('meal') # unit: g/min action = self._bb_policy(pname, meal, observation.CGM, sample_time) return action def _bb_policy(self, name, meal, glucose, env_sample_time): """ Helper function to compute the basal and bolus amount. The basal insulin is based on the insulin amount to keep the blood glucose in the steady state when there is no (meal) disturbance. basal = u2ss (pmol/(L*kg)) * body_weight (kg) / 6000 (U/min) The bolus amount is computed based on the current glucose level, the target glucose level, the patient's correction factor and the patient's carbohydrate ratio. bolus = ((carbohydrate / carbohydrate_ratio) + (current_glucose - target_glucose) / correction_factor) / sample_time NOTE the bolus computed from the above formula is in unit U. The simulator only accepts insulin rate. Hence the bolus is converted to insulin rate. """ if any(self.quest.Name.str.match(name)): quest = self.quest[self.quest.Name.str.match(name)] params = self.patient_params[self.patient_params.Name.str.match( name)] u2ss = params.u2ss.values.item() # unit: pmol/(L*kg) BW = params.BW.values.item() # unit: kg else: quest = pd.DataFrame([['Average', 13.5, 23.52, 50, 30]], columns=['Name', 'CR', 'CF', 'TDI', 'Age']) u2ss = 1.43 # unit: pmol/(L*kg) BW = 57.0 # unit: kg basal = u2ss * BW / 6000 # unit: U/min if meal > 0: logger.info('Calculating bolus ...') logger.info(f'Meal = {meal} g/min') logger.info(f'glucose = {glucose}') bolus = ( (meal * env_sample_time) / quest.CR.values + (glucose > 150) * (glucose - self.target) / quest.CF.values).item() # unit: U else: bolus = 0 # unit: U # This is to convert bolus in total amount (U) to insulin rate (U/min). # The simulation environment does not treat basal and bolus # differently. The unit of Action.basal and Action.bolus are the same # (U/min). bolus = bolus / env_sample_time # unit: U/min return Action(basal=basal, bolus=bolus) def reset(self): pass class ManualBBController(Controller): def __init__(self, target, cr, cf, basal, sample_rate=5, use_cf=True, use_bol=True, cooldown=0, corrected=True, use_low_lim=False, low_lim=70): super().__init__(self) self.target = target self.orig_cr = self.cr = cr self.orig_cf = self.cf = cf self.orig_basal = self.basal = basal self.sample_rate = sample_rate self.use_cf = use_cf self.use_bol = use_bol self.cooldown = cooldown self.last_cf = np.inf self.corrected = corrected self.use_low_lim = use_low_lim self.low_lim = low_lim def increment(self, cr_incr=0, cf_incr=0, basal_incr=0): self.cr += cr_incr self.cf += cf_incr self.basal += basal_incr def policy(self, observation, reward, done, **kwargs): carbs = kwargs.get('carbs') glucose = kwargs.get('glucose') action = self.manual_bb_policy(carbs, glucose) return action def manual_bb_policy(self, carbs, glucose, log=False): if carbs > 0: if self.corrected: carb_correct = carbs / self.cr else: # assuming carbs are already multiplied by sampling rate carb_correct = (carbs/self.sample_rate) / self.cr hyper_correct = (glucose > self.target) * (glucose - self.target) / self.cf hypo_correct = (glucose < self.low_lim) * (self.low_lim - glucose) / self.cf bolus = 0 if self.use_low_lim: bolus -= hypo_correct if self.use_cf: if self.last_cf > self.cooldown and hyper_correct > 0: bolus += hyper_correct self.last_cf = 0 if self.use_bol: bolus += carb_correct bolus = bolus / self.sample_rate else: bolus = 0 carb_correct = 0 hyper_correct = 0 hypo_correct = 0 self.last_cf += self.sample_rate if log: return Action(basal=self.basal, bolus=bolus), hyper_correct, hypo_correct, carb_correct else: return Action(basal=self.basal, bolus=bolus) def get_params(self): return ParamTup(basal=self.basal, cf=self.cf, cr=self.cr) def adjust(self, basal_adj, cr_adj): self.basal += self.orig_basal + basal_adj self.cr = self.orig_cr * cr_adj def reset(self): self.cr = self.orig_cr self.cf = self.orig_cf self.basal = self.orig_basal self.last_cf = np.inf def bb_test(bbc, env, n_days, seed, full_save=False): env.seeds['sensor'] = seed env.seeds['scenario'] = seed env.seeds['patient'] = seed env.reset() full_patient_state = [] carb_error_mean = 0 carb_error_std = 0.2 carb_miss_prob = 0.05 action = bbc.manual_bb_policy(carbs=0, glucose=140) for _ in tqdm(range(n_days*288)): obs, reward, done, info = env.step(action=action.basal+action.bolus) bg = env.env.CGM_hist[-1] carbs = info['meal'] if np.random.uniform() < carb_miss_prob: carbs = 0 err = np.random.normal(carb_error_mean, carb_error_std) carbs = carbs + carbs * err action = bbc.manual_bb_policy(carbs=carbs, glucose=bg) full_patient_state.append(info['patient_state']) full_patient_state = np.stack(full_patient_state) if full_save: return env.env.show_history(), full_patient_state else: return {'hist': env.env.show_history()[288:]}
[ "logging.getLogger", "numpy.random.normal", "collections.namedtuple", "pandas.read_csv", "numpy.stack", "numpy.random.uniform", "pandas.DataFrame" ]
[((175, 202), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (192, 202), False, 'import logging\n'), ((320, 365), 'collections.namedtuple', 'namedtuple', (['"""ParamTup"""', "['basal', 'cf', 'cr']"], {}), "('ParamTup', ['basal', 'cf', 'cr'])\n", (330, 365), False, 'from collections import namedtuple\n'), ((6854, 6882), 'numpy.stack', 'np.stack', (['full_patient_state'], {}), '(full_patient_state)\n', (6862, 6882), True, 'import numpy as np\n'), ((679, 705), 'pandas.read_csv', 'pd.read_csv', (['CONTROL_QUEST'], {}), '(CONTROL_QUEST)\n', (690, 705), True, 'import pandas as pd\n'), ((736, 766), 'pandas.read_csv', 'pd.read_csv', (['PATIENT_PARA_FILE'], {}), '(PATIENT_PARA_FILE)\n', (747, 766), True, 'import pandas as pd\n'), ((6623, 6672), 'numpy.random.normal', 'np.random.normal', (['carb_error_mean', 'carb_error_std'], {}), '(carb_error_mean, carb_error_std)\n', (6639, 6672), True, 'import numpy as np\n'), ((2387, 2483), 'pandas.DataFrame', 'pd.DataFrame', (["[['Average', 13.5, 23.52, 50, 30]]"], {'columns': "['Name', 'CR', 'CF', 'TDI', 'Age']"}), "([['Average', 13.5, 23.52, 50, 30]], columns=['Name', 'CR',\n 'CF', 'TDI', 'Age'])\n", (2399, 2483), True, 'import pandas as pd\n'), ((6549, 6568), 'numpy.random.uniform', 'np.random.uniform', ([], {}), '()\n', (6566, 6568), True, 'import numpy as np\n')]
from torch.utils.data import DataLoader from dataset.wiki_dataset import BERTDataset from models.bert_model import * from tqdm import tqdm import numpy as np import pandas as pd import os config = {} config['train_corpus_path'] = './corpus/train_wiki.txt' config['test_corpus_path'] = './corpus/test_wiki.txt' config['word2idx_path'] = './corpus/bert_word2idx_extend.json' config['output_path'] = './output_wiki_bert' config['batch_size'] = 1 config['max_seq_len'] = 200 config['vocab_size'] = 32162 config['lr'] = 2e-6 config['num_workers'] = 0 class Pretrainer: def __init__(self, bert_model, vocab_size, max_seq_len, batch_size, lr, with_cuda=True): # 词量, 注意这里实际字(词)汇量 = vocab_size - 20 # 因为前20个token用来做一些特殊功能,如padding等 self.vocab_size = vocab_size self.batch_size = batch_size self.lr = lr cuda_condition = torch.cuda.is_available() and with_cuda self.device = torch.device('cuda:0' if cuda_condition else 'cpu') # 限定单句最大长度 self.max_seq_len = max_seq_len # 初始化超参数的配置 bertconfig = BertConfig(vocab_size=config['vocab_size']) # 初始化bert模型 self.bert_model = bert_model(config=bertconfig) self.bert_model.to(self.device) # 初始化训练数据集 train_dataset = BERTDataset(corpus_path=config['train_corpus_path'], word2idx_path=config['word2idx_path'], seq_len=self.max_seq_len, hidden_dim=bertconfig.hidden_size, on_memory=False) # 初始化训练dataloader self.train_dataloader = DataLoader(train_dataset, batch_size=config['batch_size'], num_workers=config['num_workers'], collate_fn=lambda x:x) # 初始化测试数据集 test_dataset = BERTDataset(corpus_path=config['test_corpus_path'], word2idx_path=config['word2idx_path'], seq_len=self.max_seq_len, hidden_dim=bertconfig.hidden_size, on_memory=True) # 初始化测试dataloader self.test_dataloader = DataLoader(test_dataset, batch_size=self.batch_size, num_workers=config['num_workers'], collate_fn=lambda x: x) # 初始化positional_encoding [max_seq_len, hidden_size] self.positional_enc = self.init_positional_encoding(hidden_dim=bertconfig.hidden_size, max_seq_len=self.max_seq_len) # 拓展positional_encoding的维度为[1, max_seq_len, hidden_size] self.positional_enc = torch.unsqueeze(self.positional_enc, dim=0) # 列举需要优化的参数并传入优化器 optim_parameters = list(self.bert_model.parameters()) self.optimizer = torch.optim.Adam(optim_parameters, lr=self.lr) print('Total Parameters:', sum(p.nelement() for p in self.bert_model.parameters())) def init_positional_encoding(self, hidden_dim, max_seq_len): position_enc = np.array([ [pos / np.power(10000, 2 * i / hidden_dim) for i in range(hidden_dim)] if pos != 0 else np.zeros(hidden_dim) for pos in range(max_seq_len) ]) # dim=2i position_enc[1:, 0::2] = np.sin(position_enc[1:, 0::2]) # dim=2i+1 position_enc[1:, 1::2] = np.sin(position_enc[1:, 1::2]) # todo 归一化处理 why? 用位置嵌入的每一行除以它的模长 denominator = np.sqrt(np.sum(position_enc**2, axis=1, keepdims=True)) # 作为分母 position_enc /= (denominator + 1e-8) position_enc = torch.from_numpy(position_enc).type(torch.FloatTensor) return position_enc def test(self, epoch, df_path='./output_wiki_bert/df_log.pickle'): self.bert_model.eval() with torch.no_grad(): return self.iteration(epoch, self.test_dataloader, train=False, df_path=df_path) def load_model(self, model, dir_path='./output'): # 加载模型 checkpoint_dir = self.find_most_recent_state_dict(dir_path) checkpoint = torch.load(checkpoint_dir) # todo key在哪保存的 model.load_state_dict(checkpoint['model_state_dict'], strict=False) torch.cuda.empty_cache() model.to(self.device) print('{} loaded for training!'.format(checkpoint_dir)) def train(self, epoch, df_path='./output_wiki_bert/df_log.pickle'): self.bert_model.train() self.iteration(epoch, self.train_dataloader, train=True, df_path=df_path) def compute_loss(self, preditions, labels, num_class=2, ignore_index=None): if ignore_index is None: loss_func = CrossEntropyLoss() else: loss_func = CrossEntropyLoss(ignore_index=ignore_index) return loss_func(preditions.view(-1, num_class), labels.view(-1)) def get_mlm_accuracy(self, predictions, labels): # predictions [batch_size, seq_len, vocab_size] predictions = torch.argmax(predictions, dim=-1, keepdim=False) # predictions: [batch_size, seq_len] # labels: [batch_size, seq_len] mask = (labels > 0) # 只考虑被MASK的token # 预测正确的数量 pred_correct = torch.sum((predictions == labels) * mask).float() # accuracy mlm_accuracy = pred_correct / (torch.sum(mask).float() + 1e-8) return mlm_accuracy.item() def padding(self, output_dic_list): # todo output_dic_list的格式 # [batch_size, seq_len, embed_dim] bert_input = [i['bert_input'] for i in output_dic_list] bert_label = [i['bert_label'] for i in output_dic_list] segment_label = [i['segment_label'] for i in output_dic_list] # padding bert_input = torch.nn.utils.rnn.pad_sequence(bert_input, batch_first=True) bert_label = torch.nn.utils.rnn.pad_sequence(bert_label, batch_first=True) segment_label = torch.nn.utils.rnn.pad_sequence(segment_label, batch_first=True) # [batch_size] is_next = torch.cat([i['is_next'] for i in output_dic_list]) return { 'bert_input': bert_input, 'bert_label': bert_label, 'segment_label': segment_label, 'is_next': is_next } def find_most_recent_state_dict(self, dir_path): if not os.path.exists(dir_path): os.mkdir(dir_path) dic_list = [i for i in os.listdir(dir_path)] if len(dic_list) == 0: raise FileNotFoundError('can not find any state dict in {}'.format(dir_path)) # todo model什么时候存放的? dic_list = [i for i in dic_list if 'model' in i] dic_list = sorted(dic_list, key=lambda k: int(k.split('.')[-1])) return dir_path + '/' + dic_list[-1] def iteration(self, epoch, data_loader, train=True, df_path='./output_wiki_bert/df_log.pickle'): if not os.path.isfile(df_path) and epoch != 0: raise RuntimeError("log DataFrame path not found and can't create a new one because we're not training from scratch!") if not os.path.isfile(df_path) and epoch == 0: df = pd.DataFrame(columns=['epoch', 'train_next_sen_loss', 'train_mlm_loss', 'train_next_sen_acc', 'train_mlm_acc', 'test_next_sen_loss', 'test_mlm_loss', 'test_next_sen_acc', 'test_mlm_acc']) df.to_pickle(df_path) print('log DataFrame created!') str_code = 'train' if train else 'test' # 设置进度条,得到迭代器对象 data_iter = tqdm(enumerate(data_loader), desc='EP_%s:%d' % (str_code, epoch), total=len(data_loader), bar_format='{l_bar}{r_bar}') total_next_sen_loss = 0 total_mlm_loss = 0 total_next_sen_acc = 0 total_mlm_acc = 0 total_element = 0 for i, data in data_iter: data = self.padding(data) # 0. batch_data will be sent into the device data = {key: value.to(self.device) for key, value in data.items()} # todo data['bert_input'] 的维度 positional_enc = self.positional_enc[:, :data['bert_input'].size()[-1], :].to(self.device) # 1. forward the next_sentence_prediction and masked_lm_model # mlm_preds: [batch_size, seq_len, vocab_size] # next_sen_preds: [batch_size, seq_len] mlm_preds, next_sen_preds = self.bert_model.forward(input_ids=data['bert_input'], positional_enc=positional_enc, token_type_ids=data['segment_label']) mlm_acc = self.get_mlm_accuracy(mlm_preds, data['bert_label']) next_sen_acc = next_sen_preds.argmax(dim=-1, keepdim=False).eq(data['is_next']).sum().item() mlm_loss = self.compute_loss(mlm_preds, data['bert_label'], self.vocab_size, ignore_index=0) next_sen_loss = self.compute_loss(next_sen_preds, data['is_next']) # 两个任务联合训练 loss = mlm_loss + next_sen_loss # 3. 反向传播和梯度更新 if train: self.optimizer.zero_grad() loss.backward() self.optimizer.step() total_next_sen_loss += next_sen_loss.item() total_mlm_loss += mlm_loss.item() total_next_sen_acc += next_sen_acc total_element += data['is_next'].nelement() total_mlm_acc += mlm_acc if train: log_dict = { 'epoch': epoch, 'train_next_sen_loss': total_next_sen_loss / (i + 1), 'train_mlm_loss': total_mlm_loss / (i + 1), 'train_next_sen_acc': total_next_sen_acc / total_element, 'train_mlm_acc': total_mlm_acc / (i + 1), 'test_next_sen_loss': 0, 'test_mlm_loss':0, 'test_next_sen_acc':0, 'test_mlm_acc':0 } else: log_dict = { 'epoch': epoch, 'test_next_sen_loss': total_next_sen_loss / (i + 1), 'test_mlm_loss': total_mlm_loss / (i + 1), 'test_next_sen_acc': total_next_sen_acc / total_element, 'test_mlm_acc': total_mlm_acc / (i + 1), 'train_next_sen_loss': 0, 'train_mlm_loss': 0, 'train_next_sen_acc': 0, 'train_mlm_acc': 0 } if i % 10 == 0: data_iter.write(str({k: v for k, v in log_dict.items() if v != 0 and k != 'epoch'})) if train: df = pd.read_pickle(df_path) # 将日志信息追加到df中 df = df.append([log_dict]) # 重置索引 df.reset_index(inplace=True, drop=True) # 保存到本地 df.to_pickle(df_path) else: log_dict = {k: v for k, v in log_dict.items() if v != 0 and k != 'epoch'} df = pd.read_pickle(df_path) df.reset_index(inplace=True, drop=True) for k, v in log_dict.items(): df.at[epoch, k] = v df.to_pickle(df_path) return float(log_dict['test_next_sen_loss']) + float(log_dict['test_mlm_loss']) def save_state_dict(self, model, epoch, dir_path='./output', file_path='bert.model'): if not os.path.exists(dir_path): os.mkdir(dir_path) save_path = dir_path + '/' + file_path + '.epoch.{}'.format(str(epoch)) model.to('cpu') torch.save({'model_state_dict': model.state_dict()}, save_path) print('{} saved!'.format(save_path)) model.to(self.device) if __name__ == '__main__': def init_trainer(dynamic_lr, load_model=False): trainer = Pretrainer(BertForPreTraining, vocab_size=config['vocab_size'], max_seq_len=config['max_seq_len'], batch_size=config['batch_size'], lr=dynamic_lr, with_cuda=True) if load_model: trainer.load_model(trainer.bert_model, dir_path=config['output_path']) return trainer start_epoch = 3 train_epoches = 1 trainer = init_trainer(config['lr'], load_model=True) all_loss = [] threshold = 0 patient = 10 best_f1 = 0 dynamic_lr = config['lr'] # todo start_epoch 为什么要从3开始 for epoch in range(start_epoch, start_epoch + train_epoches): print('train with learning rate {}'.format(str(dynamic_lr))) trainer.train(epoch) trainer.save_state_dict(trainer.bert_model, epoch, dir_path=config['output_path'], file_path='bert.model') trainer.test(epoch)
[ "pandas.read_pickle", "os.path.exists", "os.listdir", "dataset.wiki_dataset.BERTDataset", "pandas.DataFrame", "numpy.power", "os.path.isfile", "numpy.sum", "numpy.zeros", "os.mkdir", "torch.utils.data.DataLoader", "numpy.sin" ]
[((1318, 1497), 'dataset.wiki_dataset.BERTDataset', 'BERTDataset', ([], {'corpus_path': "config['train_corpus_path']", 'word2idx_path': "config['word2idx_path']", 'seq_len': 'self.max_seq_len', 'hidden_dim': 'bertconfig.hidden_size', 'on_memory': '(False)'}), "(corpus_path=config['train_corpus_path'], word2idx_path=config[\n 'word2idx_path'], seq_len=self.max_seq_len, hidden_dim=bertconfig.\n hidden_size, on_memory=False)\n", (1329, 1497), False, 'from dataset.wiki_dataset import BERTDataset\n'), ((1690, 1812), 'torch.utils.data.DataLoader', 'DataLoader', (['train_dataset'], {'batch_size': "config['batch_size']", 'num_workers': "config['num_workers']", 'collate_fn': '(lambda x: x)'}), "(train_dataset, batch_size=config['batch_size'], num_workers=\n config['num_workers'], collate_fn=lambda x: x)\n", (1700, 1812), False, 'from torch.utils.data import DataLoader\n'), ((1978, 2155), 'dataset.wiki_dataset.BERTDataset', 'BERTDataset', ([], {'corpus_path': "config['test_corpus_path']", 'word2idx_path': "config['word2idx_path']", 'seq_len': 'self.max_seq_len', 'hidden_dim': 'bertconfig.hidden_size', 'on_memory': '(True)'}), "(corpus_path=config['test_corpus_path'], word2idx_path=config[\n 'word2idx_path'], seq_len=self.max_seq_len, hidden_dim=bertconfig.\n hidden_size, on_memory=True)\n", (1989, 2155), False, 'from dataset.wiki_dataset import BERTDataset\n'), ((2343, 2459), 'torch.utils.data.DataLoader', 'DataLoader', (['test_dataset'], {'batch_size': 'self.batch_size', 'num_workers': "config['num_workers']", 'collate_fn': '(lambda x: x)'}), "(test_dataset, batch_size=self.batch_size, num_workers=config[\n 'num_workers'], collate_fn=lambda x: x)\n", (2353, 2459), False, 'from torch.utils.data import DataLoader\n'), ((3503, 3533), 'numpy.sin', 'np.sin', (['position_enc[1:, 0::2]'], {}), '(position_enc[1:, 0::2])\n', (3509, 3533), True, 'import numpy as np\n'), ((3586, 3616), 'numpy.sin', 'np.sin', (['position_enc[1:, 1::2]'], {}), '(position_enc[1:, 1::2])\n', (3592, 3616), True, 'import numpy as np\n'), ((3689, 3737), 'numpy.sum', 'np.sum', (['(position_enc ** 2)'], {'axis': '(1)', 'keepdims': '(True)'}), '(position_enc ** 2, axis=1, keepdims=True)\n', (3695, 3737), True, 'import numpy as np\n'), ((6486, 6510), 'os.path.exists', 'os.path.exists', (['dir_path'], {}), '(dir_path)\n', (6500, 6510), False, 'import os\n'), ((6524, 6542), 'os.mkdir', 'os.mkdir', (['dir_path'], {}), '(dir_path)\n', (6532, 6542), False, 'import os\n'), ((7282, 7477), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['epoch', 'train_next_sen_loss', 'train_mlm_loss', 'train_next_sen_acc',\n 'train_mlm_acc', 'test_next_sen_loss', 'test_mlm_loss',\n 'test_next_sen_acc', 'test_mlm_acc']"}), "(columns=['epoch', 'train_next_sen_loss', 'train_mlm_loss',\n 'train_next_sen_acc', 'train_mlm_acc', 'test_next_sen_loss',\n 'test_mlm_loss', 'test_next_sen_acc', 'test_mlm_acc'])\n", (7294, 7477), True, 'import pandas as pd\n'), ((10945, 10968), 'pandas.read_pickle', 'pd.read_pickle', (['df_path'], {}), '(df_path)\n', (10959, 10968), True, 'import pandas as pd\n'), ((11276, 11299), 'pandas.read_pickle', 'pd.read_pickle', (['df_path'], {}), '(df_path)\n', (11290, 11299), True, 'import pandas as pd\n'), ((11663, 11687), 'os.path.exists', 'os.path.exists', (['dir_path'], {}), '(dir_path)\n', (11677, 11687), False, 'import os\n'), ((11701, 11719), 'os.mkdir', 'os.mkdir', (['dir_path'], {}), '(dir_path)\n', (11709, 11719), False, 'import os\n'), ((6574, 6594), 'os.listdir', 'os.listdir', (['dir_path'], {}), '(dir_path)\n', (6584, 6594), False, 'import os\n'), ((7038, 7061), 'os.path.isfile', 'os.path.isfile', (['df_path'], {}), '(df_path)\n', (7052, 7061), False, 'import os\n'), ((7225, 7248), 'os.path.isfile', 'os.path.isfile', (['df_path'], {}), '(df_path)\n', (7239, 7248), False, 'import os\n'), ((3390, 3410), 'numpy.zeros', 'np.zeros', (['hidden_dim'], {}), '(hidden_dim)\n', (3398, 3410), True, 'import numpy as np\n'), ((3297, 3332), 'numpy.power', 'np.power', (['(10000)', '(2 * i / hidden_dim)'], {}), '(10000, 2 * i / hidden_dim)\n', (3305, 3332), True, 'import numpy as np\n')]
#!/usr/bin/env python # # Author: <NAME> <<EMAIL>> # ''' A simple example to run MCSCF with background charges. ''' import numpy from pyscf import gto, scf, mcscf, qmmm mol = gto.M(atom=''' C 1.1879 -0.3829 0.0000 C 0.0000 0.5526 0.0000 O -1.1867 -0.2472 0.0000 H -1.9237 0.3850 0.0000 H 2.0985 0.2306 0.0000 H 1.1184 -1.0093 0.8869 H 1.1184 -1.0093 -0.8869 H -0.0227 1.1812 0.8852 H -0.0227 1.1812 -0.8852 ''', basis='3-21g', verbose=4) numpy.random.seed(1) coords = numpy.random.random((5,3)) * 10 charges = (numpy.arange(5) + 1.) * -.1 # # There are two ways to add background charges to MCSCF method. # The recommended one is to initialize it in SCF calculation. The MCSCF # calculation takes the information from SCF objects. # mf = qmmm.mm_charge(scf.RHF(mol), coords, charges).run() mc = mcscf.CASSCF(mf, 6, 6) mc.run() mc = mcscf.CASCI(mf, 6, 6) mc.run() # # The other method is to patch the MCSCF object with the background charges. # Note: it updates the underlying SCF object inplace. # mo_init = mf.mo_coeff mf = scf.RHF(mol) mc = mcscf.CASSCF(mf, 6, 6) mc = qmmm.mm_charge(mc, coords, charges) mc.run(mo_init) mf = scf.RHF(mol) mc = mcscf.CASCI(mf, 6, 6) mc = qmmm.mm_charge(mc, coords, charges) mc.run(mo_init)
[ "pyscf.qmmm.mm_charge", "pyscf.gto.M", "numpy.random.random", "pyscf.mcscf.CASSCF", "pyscf.mcscf.CASCI", "numpy.random.seed", "pyscf.scf.RHF", "numpy.arange" ]
[((178, 526), 'pyscf.gto.M', 'gto.M', ([], {'atom': '"""\nC 1.1879 -0.3829 0.0000\nC 0.0000 0.5526 0.0000\nO -1.1867 -0.2472 0.0000\nH -1.9237 0.3850 0.0000\nH 2.0985 0.2306 0.0000\nH 1.1184 -1.0093 0.8869\nH 1.1184 -1.0093 -0.8869\nH -0.0227 1.1812 0.8852\nH -0.0227 1.1812 -0.8852\n """', 'basis': '"""3-21g"""', 'verbose': '(4)'}), '(atom=\n """\nC 1.1879 -0.3829 0.0000\nC 0.0000 0.5526 0.0000\nO -1.1867 -0.2472 0.0000\nH -1.9237 0.3850 0.0000\nH 2.0985 0.2306 0.0000\nH 1.1184 -1.0093 0.8869\nH 1.1184 -1.0093 -0.8869\nH -0.0227 1.1812 0.8852\nH -0.0227 1.1812 -0.8852\n """\n , basis=\'3-21g\', verbose=4)\n', (183, 526), False, 'from pyscf import gto, scf, mcscf, qmmm\n'), ((542, 562), 'numpy.random.seed', 'numpy.random.seed', (['(1)'], {}), '(1)\n', (559, 562), False, 'import numpy\n'), ((901, 923), 'pyscf.mcscf.CASSCF', 'mcscf.CASSCF', (['mf', '(6)', '(6)'], {}), '(mf, 6, 6)\n', (913, 923), False, 'from pyscf import gto, scf, mcscf, qmmm\n'), ((939, 960), 'pyscf.mcscf.CASCI', 'mcscf.CASCI', (['mf', '(6)', '(6)'], {}), '(mf, 6, 6)\n', (950, 960), False, 'from pyscf import gto, scf, mcscf, qmmm\n'), ((1134, 1146), 'pyscf.scf.RHF', 'scf.RHF', (['mol'], {}), '(mol)\n', (1141, 1146), False, 'from pyscf import gto, scf, mcscf, qmmm\n'), ((1152, 1174), 'pyscf.mcscf.CASSCF', 'mcscf.CASSCF', (['mf', '(6)', '(6)'], {}), '(mf, 6, 6)\n', (1164, 1174), False, 'from pyscf import gto, scf, mcscf, qmmm\n'), ((1180, 1215), 'pyscf.qmmm.mm_charge', 'qmmm.mm_charge', (['mc', 'coords', 'charges'], {}), '(mc, coords, charges)\n', (1194, 1215), False, 'from pyscf import gto, scf, mcscf, qmmm\n'), ((1238, 1250), 'pyscf.scf.RHF', 'scf.RHF', (['mol'], {}), '(mol)\n', (1245, 1250), False, 'from pyscf import gto, scf, mcscf, qmmm\n'), ((1256, 1277), 'pyscf.mcscf.CASCI', 'mcscf.CASCI', (['mf', '(6)', '(6)'], {}), '(mf, 6, 6)\n', (1267, 1277), False, 'from pyscf import gto, scf, mcscf, qmmm\n'), ((1283, 1318), 'pyscf.qmmm.mm_charge', 'qmmm.mm_charge', (['mc', 'coords', 'charges'], {}), '(mc, coords, charges)\n', (1297, 1318), False, 'from pyscf import gto, scf, mcscf, qmmm\n'), ((572, 599), 'numpy.random.random', 'numpy.random.random', (['(5, 3)'], {}), '((5, 3))\n', (591, 599), False, 'import numpy\n'), ((615, 630), 'numpy.arange', 'numpy.arange', (['(5)'], {}), '(5)\n', (627, 630), False, 'import numpy\n'), ((858, 870), 'pyscf.scf.RHF', 'scf.RHF', (['mol'], {}), '(mol)\n', (865, 870), False, 'from pyscf import gto, scf, mcscf, qmmm\n')]
import numpy as np import time import cv2 import colorsys import tensorflow as tf from tensorflow.keras import backend as K from tensorflow.keras.layers import Activation, ReLU, Multiply # Custom objects from backbones package https://github.com/david8862/keras-YOLOv3-model-set/tree/master/common/backbones def mish(x): return x * K.tanh(K.softplus(x)) def hard_swish(x): return Multiply()([Activation(hard_sigmoid)(x), x]) def hard_sigmoid(x): return ReLU(6.)(x + 3.) * (1. / 6.) def swish(x): """Swish activation function. # Arguments x: Input tensor. # Returns The Swish activation: `x * sigmoid(x)`. # References [Searching for Activation Functions](https://arxiv.org/abs/1710.05941) """ if K.backend() == 'tensorflow': try: # The native TF implementation has a more # memory-efficient gradient implementation return K.tf.nn.swish(x) except AttributeError: pass return x * K.sigmoid(x) def get_custom_objects(): ''' form up a custom_objects dict so that the customized layer/function call could be correctly parsed when keras .h5 model is loading or converting ''' custom_objects_dict = { 'tf': tf, 'swish': swish, 'hard_sigmoid': hard_sigmoid, 'hard_swish': hard_swish, 'mish': mish } return custom_objects_dict def get_multiscale_list(): input_shape_list = [(320, 320), (352, 352), (384, 384), (416, 416), (448, 448), (480, 480), (512, 512), (544, 544), (576, 576), (608, 608)] return input_shape_list def resize_anchors(base_anchors, target_shape, base_shape=(416, 416)): ''' original anchor size is clustered from COCO dataset under input shape (416,416). We need to resize it to our train input shape for better performance ''' return np.around(base_anchors*target_shape[::-1]/base_shape[::-1]) def get_classes(classes_path): '''loads the classes''' with open(classes_path) as f: class_names = f.readlines() class_names = [c.strip() for c in class_names] return class_names def get_anchors(anchors_path): '''loads the anchors from a file''' with open(anchors_path) as f: anchors = f.readline() anchors = [float(x) for x in anchors.split(',')] return np.array(anchors).reshape(-1, 2) def get_colors(class_names): # Generate colors for drawing bounding boxes. hsv_tuples = [(x / len(class_names), 1., 1.) for x in range(len(class_names))] colors = list(map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples)) colors = list( map(lambda x: (int(x[0] * 255), int(x[1] * 255), int(x[2] * 255)), colors)) np.random.seed(10101) # Fixed seed for consistent colors across runs. # Shuffle colors to decorrelate adjacent classes. np.random.shuffle(colors) np.random.seed(None) # Reset seed to default. return colors def get_dataset(annotation_file, shuffle=True): with open(annotation_file) as f: lines = f.readlines() lines = [line.strip() for line in lines] if shuffle: np.random.seed(int(time.time())) np.random.shuffle(lines) # np.random.seed(None) return lines def draw_label(image, text, color, coords): font = cv2.FONT_HERSHEY_PLAIN font_scale = 1. (text_width, text_height) = cv2.getTextSize( text, font, fontScale=font_scale, thickness=1)[0] padding = 5 rect_height = text_height + padding * 2 rect_width = text_width + padding * 2 (x, y) = coords cv2.rectangle(image, (x, y), (x + rect_width, y - rect_height), color, cv2.FILLED) cv2.putText(image, text, (x + padding, y - text_height + padding), font, fontScale=font_scale, color=(255, 255, 255), lineType=cv2.LINE_AA) return image def draw_boxes(image, boxes, classes, scores, class_names, colors, show_score=True): if boxes is None or len(boxes) == 0: return image if classes is None or len(classes) == 0: return image for box, cls, score in zip(boxes, classes, scores): xmin, ymin, xmax, ymax = map(int, box) class_name = class_names[cls] if show_score: label = '{} {:.2f}'.format(class_name, score) else: label = '{}'.format(class_name) #print(label, (xmin, ymin), (xmax, ymax)) # if no color info, use black(0,0,0) if colors is None: color = (0, 0, 0) else: color = colors[cls] cv2.rectangle(image, (xmin, ymin), (xmax, ymax), color, 1, cv2.LINE_AA) image = draw_label(image, label, color, (xmin, ymin)) return image
[ "cv2.rectangle", "tensorflow.keras.layers.Activation", "tensorflow.keras.layers.Multiply", "tensorflow.keras.layers.ReLU", "tensorflow.keras.backend.backend", "colorsys.hsv_to_rgb", "cv2.putText", "numpy.array", "tensorflow.keras.backend.sigmoid", "numpy.random.seed", "numpy.around", "tensorflow.keras.backend.tf.nn.swish", "cv2.getTextSize", "time.time", "tensorflow.keras.backend.softplus", "numpy.random.shuffle" ]
[((1919, 1982), 'numpy.around', 'np.around', (['(base_anchors * target_shape[::-1] / base_shape[::-1])'], {}), '(base_anchors * target_shape[::-1] / base_shape[::-1])\n', (1928, 1982), True, 'import numpy as np\n'), ((2790, 2811), 'numpy.random.seed', 'np.random.seed', (['(10101)'], {}), '(10101)\n', (2804, 2811), True, 'import numpy as np\n'), ((2919, 2944), 'numpy.random.shuffle', 'np.random.shuffle', (['colors'], {}), '(colors)\n', (2936, 2944), True, 'import numpy as np\n'), ((2949, 2969), 'numpy.random.seed', 'np.random.seed', (['None'], {}), '(None)\n', (2963, 2969), True, 'import numpy as np\n'), ((3656, 3743), 'cv2.rectangle', 'cv2.rectangle', (['image', '(x, y)', '(x + rect_width, y - rect_height)', 'color', 'cv2.FILLED'], {}), '(image, (x, y), (x + rect_width, y - rect_height), color, cv2.\n FILLED)\n', (3669, 3743), False, 'import cv2\n'), ((3761, 3904), 'cv2.putText', 'cv2.putText', (['image', 'text', '(x + padding, y - text_height + padding)', 'font'], {'fontScale': 'font_scale', 'color': '(255, 255, 255)', 'lineType': 'cv2.LINE_AA'}), '(image, text, (x + padding, y - text_height + padding), font,\n fontScale=font_scale, color=(255, 255, 255), lineType=cv2.LINE_AA)\n', (3772, 3904), False, 'import cv2\n'), ((393, 403), 'tensorflow.keras.layers.Multiply', 'Multiply', ([], {}), '()\n', (401, 403), False, 'from tensorflow.keras.layers import Activation, ReLU, Multiply\n'), ((765, 776), 'tensorflow.keras.backend.backend', 'K.backend', ([], {}), '()\n', (774, 776), True, 'from tensorflow.keras import backend as K\n'), ((1016, 1028), 'tensorflow.keras.backend.sigmoid', 'K.sigmoid', (['x'], {}), '(x)\n', (1025, 1028), True, 'from tensorflow.keras import backend as K\n'), ((3246, 3270), 'numpy.random.shuffle', 'np.random.shuffle', (['lines'], {}), '(lines)\n', (3263, 3270), True, 'import numpy as np\n'), ((3452, 3514), 'cv2.getTextSize', 'cv2.getTextSize', (['text', 'font'], {'fontScale': 'font_scale', 'thickness': '(1)'}), '(text, font, fontScale=font_scale, thickness=1)\n', (3467, 3514), False, 'import cv2\n'), ((4671, 4742), 'cv2.rectangle', 'cv2.rectangle', (['image', '(xmin, ymin)', '(xmax, ymax)', 'color', '(1)', 'cv2.LINE_AA'], {}), '(image, (xmin, ymin), (xmax, ymax), color, 1, cv2.LINE_AA)\n', (4684, 4742), False, 'import cv2\n'), ((346, 359), 'tensorflow.keras.backend.softplus', 'K.softplus', (['x'], {}), '(x)\n', (356, 359), True, 'from tensorflow.keras import backend as K\n'), ((472, 481), 'tensorflow.keras.layers.ReLU', 'ReLU', (['(6.0)'], {}), '(6.0)\n', (476, 481), False, 'from tensorflow.keras.layers import Activation, ReLU, Multiply\n'), ((935, 951), 'tensorflow.keras.backend.tf.nn.swish', 'K.tf.nn.swish', (['x'], {}), '(x)\n', (948, 951), True, 'from tensorflow.keras import backend as K\n'), ((2386, 2403), 'numpy.array', 'np.array', (['anchors'], {}), '(anchors)\n', (2394, 2403), True, 'import numpy as np\n'), ((405, 429), 'tensorflow.keras.layers.Activation', 'Activation', (['hard_sigmoid'], {}), '(hard_sigmoid)\n', (415, 429), False, 'from tensorflow.keras.layers import Activation, ReLU, Multiply\n'), ((2633, 2656), 'colorsys.hsv_to_rgb', 'colorsys.hsv_to_rgb', (['*x'], {}), '(*x)\n', (2652, 2656), False, 'import colorsys\n'), ((3224, 3235), 'time.time', 'time.time', ([], {}), '()\n', (3233, 3235), False, 'import time\n')]
import matplotlib.pyplot as plt import numpy as np import pickle # import csv # from collections import namedtuple # from mpl_toolkits.mplot3d import Axes3D # import matplotlib.animation as animation # import matplotlib.colors as mc class FEModel: def __init__(self, name=None, hist_data=None): self.name = name self.hist_outs = hist_data def tuple2dict(self, data): """ Used to convert the load-displacement data exported from models to a dictionary """ ld_data = [] for specimen in data: sp_dict = dict() load = [] disp = [] for action in specimen[0]: load.append(action[1]) for action in specimen[1]: disp.append(action[1]) sp_dict["Load"] = np.array(load) sp_dict["Disp"] = -1 * np.array(disp) ld_data.append(sp_dict) def plot_history(self, x_axis, y_axis): """ XXXXXXXXXXXXXXXXXXXXXXXXXX """ plt.figure() plt.plot(self.hist_outs[x_axis], self.hist_outs[y_axis]) @classmethod def from_hist_pkl(cls, filename): """ Creates an object and imports history output data. """ with open(filename, "rb") as fh: history_data = pickle.load(fh) return cls(name=filename, hist_data=history_data) # # class ParametricDB: # def __init__(self, dimensions, responses): # self.responses = responses # self.dimensions = dimensions # # @classmethod # def from_file(cls, filename): # """ # Create from file. # # The file should be comma separated, first row titles, subsequent rows only numbers. # # Parameters # ---------- # filename : str # Relative path/filename. # # Return # ------ # ParametricDB # # """ # # with open(filename, 'rU') as infile: # # reader = csv.reader(infile) # # n_dim = int(next(reader)[0].split()[0]) # # db = {c[0]: c[1:] for c in zip(*reader)} # # with open(filename, 'rU') as infile: # reader = csv.reader(infile, delimiter=";") # n_dim = int(next(reader)[0].split()[0]) # db = [c for c in zip(*reader)] # # all_responses = {i[0]: i[1:] for i in db[n_dim:]} # # dim_ticks = np.array([i[1:] for i in db[:n_dim]]).T # dim_lengths = [len(set(dim_ticks[:, i])) for i in range(n_dim)] # dim_names = [db[i][0] for i in range(n_dim)] # # # with open(filename, 'r') as infile: # # all_lines = [[c.split(sep=":")[0]] + c.split(sep=":")[1].split(sep=",") for c in infile] # # db = {c[0]: c[1:] for c in zip(*all_lines)} # # # for key in db.keys(): # # if len(key.split(",")) > 1: # # n_dim = len(key.split(",")) # # dim_str = key # # dim_ticks = np.array([c.split(sep=",") for c in db[dim_str]]) # # dim_lengths = [len(set(dim_ticks[:, i])) for i in range(n_dim)] # # dim_names = dim_str.split(sep=",") # full_list = {i[0]: i[1:][0] for i in zip(dim_names, dim_ticks.T)} # # # del db[dim_str] # # #df = pd.DataFrame(full_dict) # # Address = namedtuple("map", " ".join(dim_names)) # args = [tuple(sorted(set(dim_ticks[:, i]))) for i, j in enumerate(dim_names)] # addressbook = Address(*args) # # mtx = {i: np.empty(dim_lengths) for i in all_responses.keys()} # for response in all_responses.keys(): # for i, response_value in enumerate(all_responses[response]): # current_idx = tuple(addressbook[idx].index(full_list[name][i]) for idx, name in enumerate(dim_names)) # mtx[response][current_idx] = response_value # mtx[response].flags.writeable = False # # return cls(addressbook, mtx) # # def get_slice(self, slice_at, response): # """ # Get a slice of the database. # # Parameters # ---------- # slice_at : dict of int # A dictionary of the keys to be sliced at the assigned values. # response : str # The name of the requested response to be sliced. # # """ # # idx_arr = [0]*len(self.dimensions) # # for key in self.dimensions._fields: # if key not in slice_at.keys(): # idx_arr[self.get_idx(key)] = slice(None, None) # for name, value in zip(slice_at.keys(), slice_at.values()): # idx_arr[self.get_idx(name)] = value # # return self.responses[response][idx_arr] # # def get_idx(self, attrname): # """ # Get the index number of a parameter (dimension) in the database. # # Parameters # ---------- # attrname : str # # """ # return(self.dimensions.index(self.dimensions.__getattribute__(attrname))) # # def contour_2d(self, slice_at, response, transpose=False, fig=None, sbplt=None): # """ # Contour plot. # :param slice_at: # :return: # """ # plt.rc('text', usetex=True) # if fig is None: # fig = plt.figure() # if sbplt is None: # ax = fig.add_subplot(111) # else: # ax = fig.add_subplot(sbplt) # else: # if sbplt is None: # ax = fig.add_subplot(111) # else: # ax = fig.add_subplot(sbplt) # # axes = [key for key in self.dimensions._fields if key not in slice_at.keys()] # # if transpose: # X, Y = np.meshgrid(self.dimensions[self.get_idx(axes[1])], self.dimensions[self.get_idx(axes[0])]) # Z = self.get_slice(slice_at, response).T # x_label, y_label = axes[1], axes[0] # else: # X, Y = np.meshgrid(self.dimensions[self.get_idx(axes[0])], self.dimensions[self.get_idx(axes[1])]) # Z = self.get_slice(slice_at, response) # x_label, y_label = axes[0], axes[1] # # ttl_values = [self.dimensions[self.get_idx(i)][slice_at[i]] for i in slice_at.keys()] # # # levels = np.arange(0, 2., 0.025) # # sbplt = ax.contour(X.astype(np.float), Y.astype(np.float), Z.T, vmin=0.4, vmax=1., levels=levels, cmap=plt.cm.inferno) # sbplt = ax.contour(X.astype(np.float), Y.astype(np.float), Z.T, cmap=plt.cm.gray_r) # sbplt2 = ax.contourf(X.astype(np.float), Y.astype(np.float), Z.T, cmap=plt.cm.inferno) # plt.clabel(sbplt, inline=1, fontsize=10) # ttl = [i for i in zip(slice_at.keys(), ttl_values)] # ttl = ", ".join(["=".join(i) for i in ttl]) # ax.set_title("$" + response + "$" + " for : " + "$" + ttl + "$") # ax.set_xlabel("$"+x_label+"$") # ax.set_ylabel("$"+y_label+"$") # # return fig # # def surf_3d(self, slice_at, response, transpose=False, fig=None, sbplt=None): # """ # Surface plot. # :param slice_at: # :return: # """ # #Convenient window dimensions # # one subplot: # # 2 side by side: Bbox(x0=0.0, y0=0.0, x1=6.79, y1=2.57) # # azim elev = -160 30 # # 3 subplots side by side # # 4 subplots: Bbox(x0=0.0, y0=0.0, x1=6.43, y1=5.14) # #azim elev -160 30 # plt.rc('text', usetex=True) # if fig is None: # fig = plt.figure() # if sbplt is None: # ax = fig.add_subplot(111, projection='3d') # else: # ax = fig.add_subplot(sbplt, projection='3d') # else: # if sbplt is None: # ax = fig.add_subplot(111, projection='3d') # else: # ax = fig.add_subplot(sbplt, projection='3d') # # # axes = [key for key in self.dimensions._fields if key not in slice_at.keys()] # # if transpose: # X, Y = np.meshgrid(self.dimensions[self.get_idx(axes[1])], self.dimensions[self.get_idx(axes[0])]) # Z = self.get_slice(slice_at, response).T # x_label, y_label = axes[1], axes[0] # else: # X, Y = np.meshgrid(self.dimensions[self.get_idx(axes[0])], self.dimensions[self.get_idx(axes[1])]) # Z = self.get_slice(slice_at, response) # x_label, y_label = axes[0], axes[1] # # ttl_values = [self.dimensions[self.get_idx(i)][slice_at[i]] for i in slice_at.keys()] # # sbplt = ax.plot_surface(X.astype(np.float), Y.astype(np.float), Z.T, cmap=plt.cm.inferno) # # plt.clabel(sbplt, inline=1, fontsize=10) # ttl = [i for i in zip(slice_at.keys(), ttl_values)] # ttl = ", ".join(["=".join(i) for i in ttl]) # ax.set_title("$" + response + "$" + " for : " + "$" + ttl + "$") # ax.set_xlabel("$"+x_label+"$") # ax.set_ylabel("$"+y_label+"$") # # return fig # # def match_viewports(fig=None): # if fig is None: # fig = plt.gcf() # fig.axes[1].view_init(azim=fig.axes[0].azim, elev=fig.axes[0].elev) def main(): lambda01 = ParametricDB.from_file("data/fem/fem-results_lambda01.dat") fig, ax = plt.subplots(nrows=2, ncols=3) fig.suptitle("fab_class: fcA, f_yield: 355 MPa, lambda_flex: 0.1") lambda01.contour_2d({"plate_imp": 0, "fab_class": 0, "f_yield": 0}, "lpf", ax=ax[0, 0]) lambda01.contour_2d({"plate_imp": 1, "fab_class": 0, "f_yield": 0}, "lpf", ax=ax[0, 1]) lambda01.contour_2d({"plate_imp": 2, "fab_class": 0, "f_yield": 0}, "lpf", ax=ax[0, 2]) lambda01.contour_2d({"plate_imp": 3, "fab_class": 0, "f_yield": 0}, "lpf", ax=ax[1, 0]) lambda01.contour_2d({"plate_imp": 4, "fab_class": 0, "f_yield": 0}, "lpf", ax=ax[1, 1]) lambda01.contour_2d({"plate_imp": 5, "fab_class": 0, "f_yield": 0}, "lpf", ax=ax[1, 2]) fig, ax = plt.subplots(nrows=2, ncols=3) fig.suptitle("fab_class: fcB, f_yield: 355 MPa, lambda_flex: 0.1") lambda01.contour_2d({"plate_imp": 0, "fab_class": 1, "f_yield": 0}, "lpf", ax=ax[0, 0]) lambda01.contour_2d({"plate_imp": 1, "fab_class": 1, "f_yield": 0}, "lpf", ax=ax[0, 1]) lambda01.contour_2d({"plate_imp": 2, "fab_class": 1, "f_yield": 0}, "lpf", ax=ax[0, 2]) lambda01.contour_2d({"plate_imp": 3, "fab_class": 1, "f_yield": 0}, "lpf", ax=ax[1, 0]) lambda01.contour_2d({"plate_imp": 4, "fab_class": 1, "f_yield": 0}, "lpf", ax=ax[1, 1]) lambda01.contour_2d({"plate_imp": 5, "fab_class": 1, "f_yield": 0}, "lpf", ax=ax[1, 2]) fig, ax = plt.subplots(nrows=2, ncols=3) fig.suptitle("fab_class: fcC, f_yield: 355 MPa, lambda_flex: 0.1") lambda01.contour_2d({"plate_imp": 0, "fab_class": 2, "f_yield": 0}, "lpf", ax=ax[0, 0]) lambda01.contour_2d({"plate_imp": 1, "fab_class": 2, "f_yield": 0}, "lpf", ax=ax[0, 1]) lambda01.contour_2d({"plate_imp": 2, "fab_class": 2, "f_yield": 0}, "lpf", ax=ax[0, 2]) lambda01.contour_2d({"plate_imp": 3, "fab_class": 2, "f_yield": 0}, "lpf", ax=ax[1, 0]) lambda01.contour_2d({"plate_imp": 4, "fab_class": 2, "f_yield": 0}, "lpf", ax=ax[1, 1]) lambda01.contour_2d({"plate_imp": 5, "fab_class": 2, "f_yield": 0}, "lpf", ax=ax[1, 2]) fig, ax = plt.subplots(nrows=2, ncols=3) fig.suptitle("fab_class: fcA, f_yield: 700 MPa, lambda_flex: 0.1") lambda01.contour_2d({"plate_imp": 0, "fab_class": 0, "f_yield": 1}, "lpf", ax=ax[0, 0]) lambda01.contour_2d({"plate_imp": 1, "fab_class": 0, "f_yield": 1}, "lpf", ax=ax[0, 1]) lambda01.contour_2d({"plate_imp": 2, "fab_class": 0, "f_yield": 1}, "lpf", ax=ax[0, 2]) lambda01.contour_2d({"plate_imp": 3, "fab_class": 0, "f_yield": 1}, "lpf", ax=ax[1, 0]) lambda01.contour_2d({"plate_imp": 4, "fab_class": 0, "f_yield": 1}, "lpf", ax=ax[1, 1]) lambda01.contour_2d({"plate_imp": 5, "fab_class": 0, "f_yield": 1}, "lpf", ax=ax[1, 2]) fig, ax = plt.subplots(nrows=2, ncols=3) fig.suptitle("fab_class: fcB, f_yield: 700 MPa, lambda_flex: 0.1") lambda01.contour_2d({"plate_imp": 0, "fab_class": 1, "f_yield": 1}, "lpf", ax=ax[0, 0]) lambda01.contour_2d({"plate_imp": 1, "fab_class": 1, "f_yield": 1}, "lpf", ax=ax[0, 1]) lambda01.contour_2d({"plate_imp": 2, "fab_class": 1, "f_yield": 1}, "lpf", ax=ax[0, 2]) lambda01.contour_2d({"plate_imp": 3, "fab_class": 1, "f_yield": 1}, "lpf", ax=ax[1, 0]) lambda01.contour_2d({"plate_imp": 4, "fab_class": 1, "f_yield": 1}, "lpf", ax=ax[1, 1]) lambda01.contour_2d({"plate_imp": 5, "fab_class": 1, "f_yield": 1}, "lpf", ax=ax[1, 2]) fig, ax = plt.subplots(nrows=2, ncols=3) fig.suptitle("fab_class: fcC, f_yield: 700 MPa, lambda_flex: 0.1") lambda01.contour_2d({"plate_imp": 0, "fab_class": 2, "f_yield": 1}, "lpf", ax=ax[0, 0]) lambda01.contour_2d({"plate_imp": 1, "fab_class": 2, "f_yield": 1}, "lpf", ax=ax[0, 1]) lambda01.contour_2d({"plate_imp": 2, "fab_class": 2, "f_yield": 1}, "lpf", ax=ax[0, 2]) lambda01.contour_2d({"plate_imp": 3, "fab_class": 2, "f_yield": 1}, "lpf", ax=ax[1, 0]) lambda01.contour_2d({"plate_imp": 4, "fab_class": 2, "f_yield": 1}, "lpf", ax=ax[1, 1]) lambda01.contour_2d({"plate_imp": 5, "fab_class": 2, "f_yield": 1}, "lpf", ax=ax[1, 2]) lambda02 = ParametricDB.from_file("data/fem/fem-results-lambda02.dat") fig, ax = plt.subplots(nrows=2, ncols=3) fig.suptitle("fab_class: fcA, f_yield: 355 MPa, lambda_flex: 0.2") lambda02.contour_2d({"plate_imp": 0, "fab_class": 0, "f_yield": 0}, "lpf", ax=ax[0, 0]) lambda02.contour_2d({"plate_imp": 1, "fab_class": 0, "f_yield": 0}, "lpf", ax=ax[0, 1]) lambda02.contour_2d({"plate_imp": 2, "fab_class": 0, "f_yield": 0}, "lpf", ax=ax[0, 2]) lambda02.contour_2d({"plate_imp": 3, "fab_class": 0, "f_yield": 0}, "lpf", ax=ax[1, 0]) lambda02.contour_2d({"plate_imp": 4, "fab_class": 0, "f_yield": 0}, "lpf", ax=ax[1, 1]) lambda02.contour_2d({"plate_imp": 5, "fab_class": 0, "f_yield": 0}, "lpf", ax=ax[1, 2]) fig, ax = plt.subplots(nrows=2, ncols=3) fig.suptitle("fab_class: fcB, f_yield: 355 MPa, lambda_flex: 0.2") lambda02.contour_2d({"plate_imp": 0, "fab_class": 1, "f_yield": 0}, "lpf", ax=ax[0, 0]) lambda02.contour_2d({"plate_imp": 1, "fab_class": 1, "f_yield": 0}, "lpf", ax=ax[0, 1]) lambda02.contour_2d({"plate_imp": 2, "fab_class": 1, "f_yield": 0}, "lpf", ax=ax[0, 2]) lambda02.contour_2d({"plate_imp": 3, "fab_class": 1, "f_yield": 0}, "lpf", ax=ax[1, 0]) lambda02.contour_2d({"plate_imp": 4, "fab_class": 1, "f_yield": 0}, "lpf", ax=ax[1, 1]) lambda02.contour_2d({"plate_imp": 5, "fab_class": 1, "f_yield": 0}, "lpf", ax=ax[1, 2]) fig, ax = plt.subplots(nrows=2, ncols=3) fig.suptitle("fab_class: fcC, f_yield: 355 MPa, lambda_flex: 0.2") lambda02.contour_2d({"plate_imp": 0, "fab_class": 2, "f_yield": 0}, "lpf", ax=ax[0, 0]) lambda02.contour_2d({"plate_imp": 1, "fab_class": 2, "f_yield": 0}, "lpf", ax=ax[0, 1]) lambda02.contour_2d({"plate_imp": 2, "fab_class": 2, "f_yield": 0}, "lpf", ax=ax[0, 2]) lambda02.contour_2d({"plate_imp": 3, "fab_class": 2, "f_yield": 0}, "lpf", ax=ax[1, 0]) lambda02.contour_2d({"plate_imp": 4, "fab_class": 2, "f_yield": 0}, "lpf", ax=ax[1, 1]) lambda02.contour_2d({"plate_imp": 5, "fab_class": 2, "f_yield": 0}, "lpf", ax=ax[1, 2]) fig, ax = plt.subplots(nrows=2, ncols=3) fig.suptitle("fab_class: fcA, f_yield: 700 MPa, lambda_flex: 0.2") lambda02.contour_2d({"plate_imp": 0, "fab_class": 0, "f_yield": 1}, "lpf", ax=ax[0, 0]) lambda02.contour_2d({"plate_imp": 1, "fab_class": 0, "f_yield": 1}, "lpf", ax=ax[0, 1]) lambda02.contour_2d({"plate_imp": 2, "fab_class": 0, "f_yield": 1}, "lpf", ax=ax[0, 2]) lambda02.contour_2d({"plate_imp": 3, "fab_class": 0, "f_yield": 1}, "lpf", ax=ax[1, 0]) lambda02.contour_2d({"plate_imp": 4, "fab_class": 0, "f_yield": 1}, "lpf", ax=ax[1, 1]) lambda02.contour_2d({"plate_imp": 5, "fab_class": 0, "f_yield": 1}, "lpf", ax=ax[1, 2]) fig, ax = plt.subplots(nrows=2, ncols=3) fig.suptitle("fab_class: fcB, f_yield: 700 MPa, lambda_flex: 0.2") lambda02.contour_2d({"plate_imp": 0, "fab_class": 1, "f_yield": 1}, "lpf", ax=ax[0, 0]) lambda02.contour_2d({"plate_imp": 1, "fab_class": 1, "f_yield": 1}, "lpf", ax=ax[0, 1]) lambda02.contour_2d({"plate_imp": 2, "fab_class": 1, "f_yield": 1}, "lpf", ax=ax[0, 2]) lambda02.contour_2d({"plate_imp": 3, "fab_class": 1, "f_yield": 1}, "lpf", ax=ax[1, 0]) lambda02.contour_2d({"plate_imp": 4, "fab_class": 1, "f_yield": 1}, "lpf", ax=ax[1, 1]) lambda02.contour_2d({"plate_imp": 5, "fab_class": 1, "f_yield": 1}, "lpf", ax=ax[1, 2]) fig, ax = plt.subplots(nrows=2, ncols=3) fig.suptitle("fab_class: fcC, f_yield: 700 MPa, lambda_flex: 0.2") lambda02.contour_2d({"plate_imp": 0, "fab_class": 2, "f_yield": 1}, "lpf", ax=ax[0, 0]) lambda02.contour_2d({"plate_imp": 1, "fab_class": 2, "f_yield": 1}, "lpf", ax=ax[0, 1]) lambda02.contour_2d({"plate_imp": 2, "fab_class": 2, "f_yield": 1}, "lpf", ax=ax[0, 2]) lambda02.contour_2d({"plate_imp": 3, "fab_class": 2, "f_yield": 1}, "lpf", ax=ax[1, 0]) lambda02.contour_2d({"plate_imp": 4, "fab_class": 2, "f_yield": 1}, "lpf", ax=ax[1, 1]) lambda02.contour_2d({"plate_imp": 5, "fab_class": 2, "f_yield": 1}, "lpf", ax=ax[1, 2]) return
[ "matplotlib.pyplot.plot", "pickle.load", "numpy.array", "matplotlib.pyplot.figure", "matplotlib.pyplot.subplots" ]
[((9287, 9317), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': '(2)', 'ncols': '(3)'}), '(nrows=2, ncols=3)\n', (9299, 9317), True, 'import matplotlib.pyplot as plt\n'), ((9955, 9985), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': '(2)', 'ncols': '(3)'}), '(nrows=2, ncols=3)\n', (9967, 9985), True, 'import matplotlib.pyplot as plt\n'), ((10623, 10653), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': '(2)', 'ncols': '(3)'}), '(nrows=2, ncols=3)\n', (10635, 10653), True, 'import matplotlib.pyplot as plt\n'), ((11292, 11322), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': '(2)', 'ncols': '(3)'}), '(nrows=2, ncols=3)\n', (11304, 11322), True, 'import matplotlib.pyplot as plt\n'), ((11960, 11990), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': '(2)', 'ncols': '(3)'}), '(nrows=2, ncols=3)\n', (11972, 11990), True, 'import matplotlib.pyplot as plt\n'), ((12628, 12658), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': '(2)', 'ncols': '(3)'}), '(nrows=2, ncols=3)\n', (12640, 12658), True, 'import matplotlib.pyplot as plt\n'), ((13375, 13405), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': '(2)', 'ncols': '(3)'}), '(nrows=2, ncols=3)\n', (13387, 13405), True, 'import matplotlib.pyplot as plt\n'), ((14043, 14073), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': '(2)', 'ncols': '(3)'}), '(nrows=2, ncols=3)\n', (14055, 14073), True, 'import matplotlib.pyplot as plt\n'), ((14711, 14741), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': '(2)', 'ncols': '(3)'}), '(nrows=2, ncols=3)\n', (14723, 14741), True, 'import matplotlib.pyplot as plt\n'), ((15380, 15410), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': '(2)', 'ncols': '(3)'}), '(nrows=2, ncols=3)\n', (15392, 15410), True, 'import matplotlib.pyplot as plt\n'), ((16048, 16078), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': '(2)', 'ncols': '(3)'}), '(nrows=2, ncols=3)\n', (16060, 16078), True, 'import matplotlib.pyplot as plt\n'), ((16716, 16746), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': '(2)', 'ncols': '(3)'}), '(nrows=2, ncols=3)\n', (16728, 16746), True, 'import matplotlib.pyplot as plt\n'), ((1031, 1043), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1041, 1043), True, 'import matplotlib.pyplot as plt\n'), ((1052, 1108), 'matplotlib.pyplot.plot', 'plt.plot', (['self.hist_outs[x_axis]', 'self.hist_outs[y_axis]'], {}), '(self.hist_outs[x_axis], self.hist_outs[y_axis])\n', (1060, 1108), True, 'import matplotlib.pyplot as plt\n'), ((818, 832), 'numpy.array', 'np.array', (['load'], {}), '(load)\n', (826, 832), True, 'import numpy as np\n'), ((1316, 1331), 'pickle.load', 'pickle.load', (['fh'], {}), '(fh)\n', (1327, 1331), False, 'import pickle\n'), ((868, 882), 'numpy.array', 'np.array', (['disp'], {}), '(disp)\n', (876, 882), True, 'import numpy as np\n')]
import numpy as np from sources import BaseSource from sources.base import BaseSourceWrapper from sources.preloaded import PreLoadedSource import json class WordsSource(BaseSource): def __init__(self, source): self._source = source def __len__(self): return len(self._source) def _remove_apostrpohs(self, seq): res = ''.join(seq.split('&apos;')) res = ''.join(res.split('&quot;')) return res def _clean(self, seq): s = '' for ch in seq.strip(): if ch.isalpha(): s += ch return s def get_sequences(self): for seq_in, transcription in self._source.get_sequences(): transcription = self._remove_apostrpohs(transcription) words = [self._clean(word) for word in transcription.split(' ')] yield seq_in, words class LabelSource(BaseSource): def __init__(self, source, mapping_table): self._source = source self._mapping_table = mapping_table def __len__(self): return len(self._source) def get_sequences(self): for seq_in, seq_out in self._source.get_sequences(): label_seq = [self._mapping_table.encode(ch) for ch in seq_out] yield seq_in, label_seq class CTCAdaptedSource(BaseSource): def __init__(self, source, padding_value=0): self._source = source self._padding = padding_value def __len__(self): return len(self._source) def get_sequences(self): for seq_in, seq_out in self._source.get_sequences(): seqs_in_pad = list(seq_in) while len(seqs_in_pad) <= 2 * len(seq_out) + 1: n = len(seqs_in_pad[0]) seqs_in_pad.append([self._padding] * n) yield seqs_in_pad, seq_out class Normalizer: def __init__(self): self._mu = None self._sd = None @staticmethod def from_json(path): with open(path, 'r') as f: s = f.read() d = json.loads(s) normalizer = Normalizer() mu = np.array(d['mu']) sd = np.array(d['sd']) normalizer.set_mean(mu) normalizer.set_deviation(sd) return normalizer def to_json(self, path): d = { 'mu': np.array(self.mu).tolist(), 'sd': np.array(self.sd).tolist() } with open(path, 'w') as f: f.write(json.dumps(d)) def set_mean(self, mu): self._mu = mu def set_deviation(self, sd): self._sd = sd @property def mu(self): return self._mu @property def sd(self): return self._sd def fit(self, X): sequence = [] for x in X: sequence.extend(x) self._mu = np.mean(sequence, axis=0) self._sd = np.std(sequence, axis=0) def preprocess(self, X): res = [] for x in X: x_norm = (x - self._mu) / self._sd # we do not want to normalize END-OF-STROKE flag which is last in the tuple x_norm[:, -1] = np.array(x)[:, -1] res.append(x_norm.tolist()) return res class OffsetPointsSource(BaseSource): def __init__(self, source): self._source = source def __len__(self): return len(self._source) def get_sequences(self): for strokes, transcription in self._source.get_sequences(): x0, y0, t0 = strokes[0].points[0] new_seq = [] for stroke in strokes: points = [] for x, y, t in stroke.points: points.append((x - x0, y - y0, t - t0, 0)) points[-1] = points[-1][:-1] + (1,) new_seq.extend(points) yield new_seq, transcription class NormalizedSource(BaseSource): def __init__(self, source, normalizer): self._source = source self._normalizer = normalizer def __len__(self): return len(self._source) def get_sequences(self): for points, transcription in self._source.get_sequences(): norm = self._normalizer.preprocess([points])[0] yield norm, transcription class DenormalizedSource(BaseSource): def __init__(self, source, normalizer): self._source = source self._normalizer = normalizer def __len__(self): return len(self._source) def get_sequences(self): mu = self._normalizer.mu sd = self._normalizer.sd for points, transcription in self._source.get_sequences(): denormalized = [(p * sd + mu).tolist() for p in points] for i, p in enumerate(denormalized): p[3] = points[i][3] yield denormalized, transcription class H5pySource(BaseSource): def __init__(self, h5py_ds, random_order=True): self._h5py = h5py_ds self._random = random_order def __len__(self): return len(self._h5py) def get_sequences(self): return self._h5py.get_data(random_order=self._random) class PreprocessedSource(BaseSourceWrapper): def __init__(self, source, preprocessor): super().__init__(source) self._preprocessor = preprocessor def get_sequences(self): for xs, ys in self._source.get_sequences(): yield self._preprocessor.pre_process_example(xs, ys) class ConstrainedSource(BaseSourceWrapper): def __init__(self, source, num_lines): super().__init__(source) self._num_lines = num_lines self._use_all = (num_lines == 0) def get_sequences(self): for j, (seq_in, seq_out) in enumerate(self._source.get_sequences()): #print(j, seq_out) if j % 500 == 0: print('Fetched {} examples'.format(j)) if j >= self._num_lines and not self._use_all: break yield seq_in, seq_out class PlainListSource(BaseSourceWrapper): def get_sequences(self): for strokes, t in self._source.get_sequences(): points = [stroke.points for stroke in strokes] yield points, t
[ "numpy.mean", "json.loads", "json.dumps", "numpy.array", "numpy.std" ]
[((2030, 2043), 'json.loads', 'json.loads', (['s'], {}), '(s)\n', (2040, 2043), False, 'import json\n'), ((2091, 2108), 'numpy.array', 'np.array', (["d['mu']"], {}), "(d['mu'])\n", (2099, 2108), True, 'import numpy as np\n'), ((2122, 2139), 'numpy.array', 'np.array', (["d['sd']"], {}), "(d['sd'])\n", (2130, 2139), True, 'import numpy as np\n'), ((2787, 2812), 'numpy.mean', 'np.mean', (['sequence'], {'axis': '(0)'}), '(sequence, axis=0)\n', (2794, 2812), True, 'import numpy as np\n'), ((2832, 2856), 'numpy.std', 'np.std', (['sequence'], {'axis': '(0)'}), '(sequence, axis=0)\n', (2838, 2856), True, 'import numpy as np\n'), ((2435, 2448), 'json.dumps', 'json.dumps', (['d'], {}), '(d)\n', (2445, 2448), False, 'import json\n'), ((3088, 3099), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (3096, 3099), True, 'import numpy as np\n'), ((2297, 2314), 'numpy.array', 'np.array', (['self.mu'], {}), '(self.mu)\n', (2305, 2314), True, 'import numpy as np\n'), ((2343, 2360), 'numpy.array', 'np.array', (['self.sd'], {}), '(self.sd)\n', (2351, 2360), True, 'import numpy as np\n')]
import numpy as np import torch import matplotlib.pyplot as plt from torch import optim, nn from pytorch.xor.multilayer_perceptron import MultilayerPerceptron from pytorch.xor.utils import LABELS, get_toy_data, visualize_results, plot_intermediate_representations input_size = 2 output_size = len(set(LABELS)) num_hidden_layers = 0 hidden_size = 2 # isn't ever used but we still set it seed = 24 torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) np.random.seed(seed) mlp1 = MultilayerPerceptron(input_size=input_size, hidden_size=hidden_size, num_hidden_layers=num_hidden_layers, output_size=output_size) print(mlp1) batch_size = 1000 x_data_static, y_truth_static = get_toy_data(batch_size) fig, ax = plt.subplots(1, 1, figsize=(10,5)) visualize_results(mlp1, x_data_static, y_truth_static, ax=ax, title='Initial Perceptron State', levels=[0.5]) plt.axis('off') plt.savefig('images/perceptron_initial.png') plt.show() losses = [] batch_size = 10000 n_batches = 10 max_epochs = 10 loss_change = 1.0 last_loss = 10.0 change_threshold = 1e-3 epoch = 0 all_imagefiles = [] lr = 0.01 optimizer = optim.Adam(params=mlp1.parameters(), lr=lr) cross_ent_loss = nn.CrossEntropyLoss() def early_termination(loss_change, change_threshold, epoch, max_epochs): terminate_for_loss_change = loss_change < change_threshold terminate_for_epochs = epoch > max_epochs # return terminate_for_loss_change or return terminate_for_epochs while not early_termination(loss_change, change_threshold, epoch, max_epochs): for _ in range(n_batches): # step 0: fetch the data x_data, y_target = get_toy_data(batch_size) # step 1: zero the gradients mlp1.zero_grad() # step 2: run the forward pass y_pred = mlp1(x_data).squeeze() # step 3: compute the loss loss = cross_ent_loss(y_pred, y_target.long()) # step 4: compute the backward pass loss.backward() # step 5: have the optimizer take an optimization step optimizer.step() # auxillary: bookkeeping loss_value = loss.item() losses.append(loss_value) loss_change = abs(last_loss - loss_value) last_loss = loss_value print("epoch: {}: loss_value: {}".format(epoch, loss_value)) fig, ax = plt.subplots(1, 1, figsize=(10, 5)) visualize_results(mlp1, x_data_static, y_truth_static, ax=ax, epoch=epoch, title=f"{loss_value:0.2f}; {loss_change:0.4f}") plt.axis('off') epoch += 1 all_imagefiles.append(f'images/perceptron_epoch{epoch}_toylearning.png') plt.savefig(all_imagefiles[-1]) _, ax = plt.subplots(1,1,figsize=(10,5)) visualize_results(mlp1, x_data_static, y_truth_static, epoch=None, levels=[0.5], ax=ax) plt.axis('off'); plt.savefig('images/perceptron_final.png') plot_intermediate_representations(mlp1, "The Perceptron's Input and Intermediate Representation", figsize=(9, 3)) plt.savefig("images/perceptron_intermediate.png") plt.savefig("images/figure_4_5.pdf")
[ "torch.cuda.manual_seed_all", "torch.manual_seed", "matplotlib.pyplot.savefig", "torch.nn.CrossEntropyLoss", "pytorch.xor.utils.get_toy_data", "pytorch.xor.utils.plot_intermediate_representations", "pytorch.xor.multilayer_perceptron.MultilayerPerceptron", "pytorch.xor.utils.visualize_results", "numpy.random.seed", "matplotlib.pyplot.axis", "matplotlib.pyplot.subplots", "matplotlib.pyplot.show" ]
[((401, 424), 'torch.manual_seed', 'torch.manual_seed', (['seed'], {}), '(seed)\n', (418, 424), False, 'import torch\n'), ((425, 457), 'torch.cuda.manual_seed_all', 'torch.cuda.manual_seed_all', (['seed'], {}), '(seed)\n', (451, 457), False, 'import torch\n'), ((458, 478), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (472, 478), True, 'import numpy as np\n'), ((487, 621), 'pytorch.xor.multilayer_perceptron.MultilayerPerceptron', 'MultilayerPerceptron', ([], {'input_size': 'input_size', 'hidden_size': 'hidden_size', 'num_hidden_layers': 'num_hidden_layers', 'output_size': 'output_size'}), '(input_size=input_size, hidden_size=hidden_size,\n num_hidden_layers=num_hidden_layers, output_size=output_size)\n', (507, 621), False, 'from pytorch.xor.multilayer_perceptron import MultilayerPerceptron\n'), ((765, 789), 'pytorch.xor.utils.get_toy_data', 'get_toy_data', (['batch_size'], {}), '(batch_size)\n', (777, 789), False, 'from pytorch.xor.utils import LABELS, get_toy_data, visualize_results, plot_intermediate_representations\n'), ((800, 835), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': '(10, 5)'}), '(1, 1, figsize=(10, 5))\n', (812, 835), True, 'import matplotlib.pyplot as plt\n'), ((835, 949), 'pytorch.xor.utils.visualize_results', 'visualize_results', (['mlp1', 'x_data_static', 'y_truth_static'], {'ax': 'ax', 'title': '"""Initial Perceptron State"""', 'levels': '[0.5]'}), "(mlp1, x_data_static, y_truth_static, ax=ax, title=\n 'Initial Perceptron State', levels=[0.5])\n", (852, 949), False, 'from pytorch.xor.utils import LABELS, get_toy_data, visualize_results, plot_intermediate_representations\n'), ((964, 979), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (972, 979), True, 'import matplotlib.pyplot as plt\n'), ((980, 1024), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""images/perceptron_initial.png"""'], {}), "('images/perceptron_initial.png')\n", (991, 1024), True, 'import matplotlib.pyplot as plt\n'), ((1025, 1035), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1033, 1035), True, 'import matplotlib.pyplot as plt\n'), ((1273, 1294), 'torch.nn.CrossEntropyLoss', 'nn.CrossEntropyLoss', ([], {}), '()\n', (1292, 1294), False, 'from torch import optim, nn\n'), ((2748, 2783), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': '(10, 5)'}), '(1, 1, figsize=(10, 5))\n', (2760, 2783), True, 'import matplotlib.pyplot as plt\n'), ((2781, 2873), 'pytorch.xor.utils.visualize_results', 'visualize_results', (['mlp1', 'x_data_static', 'y_truth_static'], {'epoch': 'None', 'levels': '[0.5]', 'ax': 'ax'}), '(mlp1, x_data_static, y_truth_static, epoch=None, levels=[\n 0.5], ax=ax)\n', (2798, 2873), False, 'from pytorch.xor.utils import LABELS, get_toy_data, visualize_results, plot_intermediate_representations\n'), ((2869, 2884), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (2877, 2884), True, 'import matplotlib.pyplot as plt\n'), ((2886, 2928), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""images/perceptron_final.png"""'], {}), "('images/perceptron_final.png')\n", (2897, 2928), True, 'import matplotlib.pyplot as plt\n'), ((2930, 3047), 'pytorch.xor.utils.plot_intermediate_representations', 'plot_intermediate_representations', (['mlp1', '"""The Perceptron\'s Input and Intermediate Representation"""'], {'figsize': '(9, 3)'}), '(mlp1,\n "The Perceptron\'s Input and Intermediate Representation", figsize=(9, 3))\n', (2963, 3047), False, 'from pytorch.xor.utils import LABELS, get_toy_data, visualize_results, plot_intermediate_representations\n'), ((3112, 3161), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""images/perceptron_intermediate.png"""'], {}), "('images/perceptron_intermediate.png')\n", (3123, 3161), True, 'import matplotlib.pyplot as plt\n'), ((3162, 3198), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""images/figure_4_5.pdf"""'], {}), "('images/figure_4_5.pdf')\n", (3173, 3198), True, 'import matplotlib.pyplot as plt\n'), ((2406, 2441), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': '(10, 5)'}), '(1, 1, figsize=(10, 5))\n', (2418, 2441), True, 'import matplotlib.pyplot as plt\n'), ((2446, 2572), 'pytorch.xor.utils.visualize_results', 'visualize_results', (['mlp1', 'x_data_static', 'y_truth_static'], {'ax': 'ax', 'epoch': 'epoch', 'title': 'f"""{loss_value:0.2f}; {loss_change:0.4f}"""'}), "(mlp1, x_data_static, y_truth_static, ax=ax, epoch=epoch,\n title=f'{loss_value:0.2f}; {loss_change:0.4f}')\n", (2463, 2572), False, 'from pytorch.xor.utils import LABELS, get_toy_data, visualize_results, plot_intermediate_representations\n'), ((2595, 2610), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (2603, 2610), True, 'import matplotlib.pyplot as plt\n'), ((2707, 2738), 'matplotlib.pyplot.savefig', 'plt.savefig', (['all_imagefiles[-1]'], {}), '(all_imagefiles[-1])\n', (2718, 2738), True, 'import matplotlib.pyplot as plt\n'), ((1726, 1750), 'pytorch.xor.utils.get_toy_data', 'get_toy_data', (['batch_size'], {}), '(batch_size)\n', (1738, 1750), False, 'from pytorch.xor.utils import LABELS, get_toy_data, visualize_results, plot_intermediate_representations\n')]
import cv2 from PIL import Image import argparse from pathlib import Path from multiprocessing import Process, Pipe,Value,Array import torch from config import get_config from mtcnn import MTCNN from Learner_trans_tf import face_learner from utils import load_facebank, draw_box_name, prepare_facebank, save_label_score, label_binarize from sklearn.metrics import roc_curve, auc, precision_recall_curve, average_precision_score from sklearn.model_selection import KFold import os import glob import shutil import numpy as np import matplotlib.pyplot as plt import matplotlib.colors as mcolors import datetime if __name__ == '__main__': parser = argparse.ArgumentParser(description='for face verification') parser.add_argument("-ds", "--dataset_dir", help="where to get data", default="noonan", type=str) parser.add_argument('-sd','--stored_result_dir',help='where to store data as np arrays', default="results/trans/", type=str) parser.add_argument("-k", "--kfold", help="returns the number of splitting iterations in the cross-validator.", default=10, type=int) parser.add_argument("-e", "--epochs", help="training epochs", default=20, type=int) parser.add_argument("-n", "--names_considered", help="names for different types considered, separated by commas", default="normal,noonan,others", type=str) parser.add_argument("-g", "--gpu_id", help="gpu id to use", default="", type=str) parser.add_argument("-s", "--use_shuffled_kfold", help="whether to use shuffled kfold.", action="store_true") parser.add_argument("-rs", "--random_seed", help="random seed used for k-fold split.", default=6, type=int) parser.add_argument("-tta", "--tta", help="whether test time augmentation",action="store_true") parser.add_argument("-a", "--additional_data_dir", help="where to get the additional data", default="", type=str) parser.add_argument("-ta", "--additional_test_or_train", help="use additional data in only train, or test, or both", default="", type=str) parser.add_argument("-as", "--stylegan_data_dir", help="where to get the additional data", default="", type=str) parser.add_argument("-ts", "--stylegan_test_or_train", help="use stylegan data in only train, or test, or both", default="", type=str) parser.add_argument("-tf", "--transfer", help="how many layer(s) used for transfer learning, " "but 0 means retraining the whole network.", default=0, type=int) parser.add_argument("-ac", "--arch", help="types of model used for encoder", default="mobile", type=str) args = parser.parse_args() for arg in vars(args): print(arg+':', getattr(args, arg)) emore_dir = 'faces_emore' conf = get_config(True, args) conf.emore_folder = conf.data_path/emore_dir mtcnn = MTCNN() print('mtcnn loaded') names_considered = args.names_considered.strip().split(',') exp_name = args.dataset_dir[:4] if args.additional_data_dir: if 'LAG' in args.additional_data_dir: exp_name += '_lag' elif 'literature' in args.additional_data_dir: exp_name += '_ltr' if args.kfold != 10: exp_name += ('_k' + str(args.kfold)) if args.epochs != 20: exp_name += ('_e' + str(args.epochs)) if args.transfer != 0 and args.transfer != 1: exp_name += ('_td' + str(args.transfer)) if args.use_shuffled_kfold: exp_name += ('_s' + str(args.random_seed)) print(exp_name) # prepare folders raw_dir = 'raw_112' verify_type = 'trans' if args.use_shuffled_kfold: verify_type += '_shuffled' # train_dir = conf.facebank_path/args.dataset_dir/verify_type/'train' train_dir = conf.emore_folder/'imgs' test_dir = conf.emore_folder/'test' conf.facebank_path = train_dir if os.path.exists(train_dir): shutil.rmtree(train_dir) if os.path.exists(test_dir): shutil.rmtree(test_dir) os.mkdir(train_dir) os.mkdir(test_dir) for name in names_considered: os.makedirs(str(train_dir) + '/' + name, exist_ok=True) os.makedirs(str(test_dir) + '/' + name, exist_ok=True) if args.stylegan_data_dir: #e.g. smile_refine_mtcnn_112_divi full_stylegan_dir = str(conf.data_path/'facebank'/'stylegan'/args.stylegan_data_dir) stylegan_folders = os.listdir(full_stylegan_dir) if args.additional_data_dir: full_additional_dir = str(conf.data_path/'facebank'/args.additional_data_dir) # init kfold if args.use_shuffled_kfold: kf = KFold(n_splits=args.kfold, shuffle=True, random_state=args.random_seed) else: kf = KFold(n_splits=args.kfold, shuffle=False, random_state=None) # collect and split raw data data_dict = {} idx_gen = {} for name in names_considered: tmp_list = glob.glob(str(conf.data_path/'facebank'/args.dataset_dir/raw_dir) + '/' + name + '*') if 'innm' in args.stylegan_data_dir: tmp_list = tmp_list + glob.glob(str(full_stylegan_dir) + '/' + name + '*') stylegan_folders = [] print(str(conf.data_path/'facebank'/args.dataset_dir/raw_dir)) data_dict[name] = np.array(tmp_list) idx_gen[name] = kf.split(data_dict[name]) if 'literature' in args.additional_data_dir: data_dict['ltr'] = np.array(glob.glob(str(full_additional_dir) + '/*')) idx_gen['ltr'] = kf.split(data_dict['ltr']) score_names = [] scores = [] wrong_names = [] args.stored_result_path = args.stored_result_dir + os.sep + str(datetime.datetime.now())[:19] if not os.path.exists(args.stored_result_path): os.mkdir(args.stored_result_path) # for fold_idx, (train_index, test_index) in enumerate(kf.split(data_dict[names_considered[0]])): for fold_idx in range(args.kfold): train_set = {} test_set = {} for name in names_considered: (train_index, test_index) = next(idx_gen[name]) train_set[name], test_set[name] = data_dict[name][train_index], data_dict[name][test_index] if 'ltr' in data_dict.keys(): (train_index, test_index) = next(idx_gen['ltr']) train_set['ltr'], test_set['ltr'] = data_dict['ltr'][train_index], data_dict['ltr'][test_index] if 'train' in args.additional_test_or_train: train_set['noonan'] = np.concatenate((train_set['noonan'], train_set['ltr'])) if 'test' in args.additional_test_or_train: test_set['noonan'] = np.concatenate((test_set['noonan'], test_set['ltr'])) # remove previous data prev = glob.glob(str(train_dir) + '/*/*') for p in prev: os.remove(p) prev = glob.glob(str(test_dir) + '/*/*') for p in prev: os.remove(p) # save trains to conf.facebank_path/args.dataset_dir/'train' and # tests to conf.data_path/'facebank'/args.dataset_dir/'test' # count unbalanced data train_count = {} test_count = {} for name in names_considered: train_count[name] = 0 for i in range(len(train_set[name])): img_folder = str(train_set[name][i]) for img in os.listdir(img_folder): shutil.copy(img_folder + os.sep + str(img), os.path.join(str(train_dir), name, str(img))) train_count[name] += 1 # addition data from stylegan if 'interp' not in data_dict.keys(): folder = os.path.basename(train_set[name][i]) if args.stylegan_data_dir and ('train' in args.stylegan_test_or_train) and (folder in stylegan_folders): for img in os.listdir(full_stylegan_dir + os.sep + folder): shutil.copy(os.path.join(full_stylegan_dir, folder, str(img)), os.path.join(str(train_dir), name, str(img))) # ('/'.join(train_set[name][i].strip().split('/')[:-2]) + # '/' + verify_type + '/train/' + name + os.sep + img)) train_count[name] += 1 # test for i in range(len(test_set[name])): test_count[name] = 0 img_folder = str(test_set[name][i]) for img in os.listdir(img_folder): shutil.copy(img_folder + os.sep + str(img), os.path.join(str(test_dir), name, str(img))) test_count[name] += 1 # addition data from stylegan if 'interp' not in data_dict.keys(): folder = os.path.basename(test_set[name][i]) if args.stylegan_data_dir and ('test' in args.stylegan_test_or_train) and (folder in stylegan_folders): # and # (folder not in ['noonan7','noonan19','noonan23','normal9','normal20','normal23'])): for img in os.listdir(full_stylegan_dir + os.sep + folder): shutil.copy(os.path.join(full_stylegan_dir, folder, str(img)), os.path.join(str(test_dir), name, str(img))) test_count[name] += 1 print(train_count, test_count) # deal with unbalanced data """ if train_count['normal'] // train_count['noonan'] > 1: aug_num = train_count['normal'] // train_count['noonan'] - 1 for img in os.listdir(os.path.join(str(train_dir), 'noonan')): for aug_idx in range(aug_num): aug_img = img[:img.rfind('.')] + '_' + str(aug_idx) + img[img.rfind('.'):] shutil.copy(os.path.join(str(train_dir), 'noonan', img), os.path.join(str(train_dir), 'noonan', aug_img)) """ if 'fake' in args.additional_data_dir: fake_dict = {'noonan':'normal', 'normal':'noonan'} full_additional_dir = conf.data_path/'facebank'/'noonan+normal'/args.additional_data_dir add_data = glob.glob(str(full_additional_dir) + os.sep + '*.png') print('additional:', args.additional_data_dir, len(add_data)) for name in names_considered: for img_f in add_data: if name in img_f.strip().split(os.sep)[-1]: # print('source:', img_f) # print('copy to:', img_f.replace(str(full_additional_dir), # str(train_dir) + os.sep + fake_dict[name])) # print('copy to:', img_f.replace(args.additional_data_dir, # verify_type + '/train/' + name)) shutil.copy(img_f, os.path.join(str(train_dir), fake_dict[name], os.path.basename(img_f))) print(fold_idx) print('datasets ready') conf_train = get_config(True, args) conf_train.emore_folder = conf.data_path/emore_dir conf_train.stored_result_dir = args.stored_result_path learner = face_learner(conf=conf_train, transfer=args.transfer, ext=exp_name+'_'+str(fold_idx)) # conf, inference=False, transfer=0 if args.transfer != 0: learner.load_state(conf.save_path, False, True) print('learner loaded') learner.train(conf_train, args.epochs) print('learner retrained.') learner.save_state() print('Model is saved') # prepare_facebank targets, names, names_idx = prepare_facebank(conf, learner.model, mtcnn, tta = args.tta) print('names_classes:', names) noonan_idx = names_idx['noonan'] print('facebank updated') for path in test_dir.iterdir(): if path.is_file(): continue # print(path) for fil in path.iterdir(): # print(fil) orig_name = ''.join([i for i in fil.name.strip().split('.')[0].split('_')[0] if not i.isdigit()]) for name in names_idx.keys(): if name in orig_name: score_names.append(names_idx[name]) """ if orig_name not in names_considered: print("Un-considered name:", fil.name) continue """ frame = cv2.imread(str(fil)) image = Image.fromarray(frame) faces = [image,] distance = learner.binfer(conf, faces, targets, args.tta) label = score_names[-1] score = np.exp(distance.dot(-1)) pred = np.argmax(score, 1) if pred != label: wrong_names.append(orig_name) scores.append(score) score_names = np.array(score_names) wrong_names = np.array(wrong_names) score_np = np.squeeze(np.array(scores)) n_classes = score_np.shape[1] score_names = label_binarize(score_names, classes=range(n_classes)) score_sum = np.zeros([score_np.shape[0], 1]) for i in range(n_classes): score_sum += score_np[:, i, None] # keep the dimension relative_scores = (score_np / score_sum) total_scores = relative_scores.ravel() total_names = score_names.ravel() name_path = os.path.join(args.stored_result_path, 'wrong_names.npy') save_label_score(name_path, wrong_names) label_path = os.path.join(args.stored_result_path, 'labels_trans.npy') save_label_score(label_path, score_names) score_path = os.path.join(args.stored_result_path, 'scores_trans.npy') save_label_score(score_path, relative_scores) print('saved!') # Compute ROC curve and ROC area for noonan fpr, tpr, _ = roc_curve(total_names, total_scores) #scores_np[:, noonan_idx] roc_auc = auc(fpr, tpr) # For PR curve precision, recall, _ = precision_recall_curve(total_names, total_scores) average_precision = average_precision_score(total_names, total_scores) # plots plt.figure() colors = list(mcolors.TABLEAU_COLORS) lw = 2 plt.plot(fpr, tpr, color='darkorange', lw=lw, label='ROC curve (area = %0.4f)' % roc_auc) plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('ROC_{}'.format(exp_name)) plt.legend(loc="lower right") plt.savefig(args.stored_result_path + os.sep + '/fp_tp_{}.png'.format(exp_name)) plt.close() # plt.show() plt.figure() plt.step(recall, precision, where='post') plt.xlabel('Recall') plt.ylabel('Precision') plt.ylim([0.0, 1.05]) plt.xlim([0.0, 1.0]) plt.title('Average precision score ({}): AP={:0.4f}'.format(exp_name, average_precision)) plt.savefig(args.stored_result_path + os.sep + '/pr_{}.png'.format(exp_name)) plt.close()
[ "matplotlib.pyplot.ylabel", "sklearn.metrics.auc", "numpy.array", "sklearn.metrics.roc_curve", "sklearn.model_selection.KFold", "utils.prepare_facebank", "os.remove", "os.path.exists", "os.listdir", "argparse.ArgumentParser", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.plot", "matplotlib.pyplot.close", "os.mkdir", "numpy.concatenate", "matplotlib.pyplot.ylim", "mtcnn.MTCNN", "sklearn.metrics.average_precision_score", "sklearn.metrics.precision_recall_curve", "numpy.argmax", "matplotlib.pyplot.xlim", "matplotlib.pyplot.legend", "matplotlib.pyplot.step", "PIL.Image.fromarray", "utils.save_label_score", "os.path.join", "config.get_config", "numpy.zeros", "matplotlib.pyplot.figure", "datetime.datetime.now", "os.path.basename", "shutil.rmtree" ]
[((651, 711), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""for face verification"""'}), "(description='for face verification')\n", (674, 711), False, 'import argparse\n'), ((2874, 2896), 'config.get_config', 'get_config', (['(True)', 'args'], {}), '(True, args)\n', (2884, 2896), False, 'from config import get_config\n'), ((2959, 2966), 'mtcnn.MTCNN', 'MTCNN', ([], {}), '()\n', (2964, 2966), False, 'from mtcnn import MTCNN\n'), ((3979, 4004), 'os.path.exists', 'os.path.exists', (['train_dir'], {}), '(train_dir)\n', (3993, 4004), False, 'import os\n'), ((4046, 4070), 'os.path.exists', 'os.path.exists', (['test_dir'], {}), '(test_dir)\n', (4060, 4070), False, 'import os\n'), ((4108, 4127), 'os.mkdir', 'os.mkdir', (['train_dir'], {}), '(train_dir)\n', (4116, 4127), False, 'import os\n'), ((4132, 4150), 'os.mkdir', 'os.mkdir', (['test_dir'], {}), '(test_dir)\n', (4140, 4150), False, 'import os\n'), ((13241, 13262), 'numpy.array', 'np.array', (['score_names'], {}), '(score_names)\n', (13249, 13262), True, 'import numpy as np\n'), ((13281, 13302), 'numpy.array', 'np.array', (['wrong_names'], {}), '(wrong_names)\n', (13289, 13302), True, 'import numpy as np\n'), ((13470, 13502), 'numpy.zeros', 'np.zeros', (['[score_np.shape[0], 1]'], {}), '([score_np.shape[0], 1])\n', (13478, 13502), True, 'import numpy as np\n'), ((13742, 13798), 'os.path.join', 'os.path.join', (['args.stored_result_path', '"""wrong_names.npy"""'], {}), "(args.stored_result_path, 'wrong_names.npy')\n", (13754, 13798), False, 'import os\n'), ((13803, 13843), 'utils.save_label_score', 'save_label_score', (['name_path', 'wrong_names'], {}), '(name_path, wrong_names)\n', (13819, 13843), False, 'from utils import load_facebank, draw_box_name, prepare_facebank, save_label_score, label_binarize\n'), ((13861, 13918), 'os.path.join', 'os.path.join', (['args.stored_result_path', '"""labels_trans.npy"""'], {}), "(args.stored_result_path, 'labels_trans.npy')\n", (13873, 13918), False, 'import os\n'), ((13923, 13964), 'utils.save_label_score', 'save_label_score', (['label_path', 'score_names'], {}), '(label_path, score_names)\n', (13939, 13964), False, 'from utils import load_facebank, draw_box_name, prepare_facebank, save_label_score, label_binarize\n'), ((13982, 14039), 'os.path.join', 'os.path.join', (['args.stored_result_path', '"""scores_trans.npy"""'], {}), "(args.stored_result_path, 'scores_trans.npy')\n", (13994, 14039), False, 'import os\n'), ((14044, 14089), 'utils.save_label_score', 'save_label_score', (['score_path', 'relative_scores'], {}), '(score_path, relative_scores)\n', (14060, 14089), False, 'from utils import load_facebank, draw_box_name, prepare_facebank, save_label_score, label_binarize\n'), ((14181, 14217), 'sklearn.metrics.roc_curve', 'roc_curve', (['total_names', 'total_scores'], {}), '(total_names, total_scores)\n', (14190, 14217), False, 'from sklearn.metrics import roc_curve, auc, precision_recall_curve, average_precision_score\n'), ((14259, 14272), 'sklearn.metrics.auc', 'auc', (['fpr', 'tpr'], {}), '(fpr, tpr)\n', (14262, 14272), False, 'from sklearn.metrics import roc_curve, auc, precision_recall_curve, average_precision_score\n'), ((14320, 14369), 'sklearn.metrics.precision_recall_curve', 'precision_recall_curve', (['total_names', 'total_scores'], {}), '(total_names, total_scores)\n', (14342, 14369), False, 'from sklearn.metrics import roc_curve, auc, precision_recall_curve, average_precision_score\n'), ((14394, 14444), 'sklearn.metrics.average_precision_score', 'average_precision_score', (['total_names', 'total_scores'], {}), '(total_names, total_scores)\n', (14417, 14444), False, 'from sklearn.metrics import roc_curve, auc, precision_recall_curve, average_precision_score\n'), ((14462, 14474), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (14472, 14474), True, 'import matplotlib.pyplot as plt\n'), ((14532, 14626), 'matplotlib.pyplot.plot', 'plt.plot', (['fpr', 'tpr'], {'color': '"""darkorange"""', 'lw': 'lw', 'label': "('ROC curve (area = %0.4f)' % roc_auc)"}), "(fpr, tpr, color='darkorange', lw=lw, label=\n 'ROC curve (area = %0.4f)' % roc_auc)\n", (14540, 14626), True, 'import matplotlib.pyplot as plt\n'), ((14639, 14700), 'matplotlib.pyplot.plot', 'plt.plot', (['[0, 1]', '[0, 1]'], {'color': '"""navy"""', 'lw': 'lw', 'linestyle': '"""--"""'}), "([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')\n", (14647, 14700), True, 'import matplotlib.pyplot as plt\n'), ((14705, 14725), 'matplotlib.pyplot.xlim', 'plt.xlim', (['[0.0, 1.0]'], {}), '([0.0, 1.0])\n', (14713, 14725), True, 'import matplotlib.pyplot as plt\n'), ((14730, 14751), 'matplotlib.pyplot.ylim', 'plt.ylim', (['[0.0, 1.05]'], {}), '([0.0, 1.05])\n', (14738, 14751), True, 'import matplotlib.pyplot as plt\n'), ((14756, 14789), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""False Positive Rate"""'], {}), "('False Positive Rate')\n", (14766, 14789), True, 'import matplotlib.pyplot as plt\n'), ((14794, 14826), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""True Positive Rate"""'], {}), "('True Positive Rate')\n", (14804, 14826), True, 'import matplotlib.pyplot as plt\n'), ((14872, 14901), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""lower right"""'}), "(loc='lower right')\n", (14882, 14901), True, 'import matplotlib.pyplot as plt\n'), ((14991, 15002), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (15000, 15002), True, 'import matplotlib.pyplot as plt\n'), ((15025, 15037), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (15035, 15037), True, 'import matplotlib.pyplot as plt\n'), ((15042, 15083), 'matplotlib.pyplot.step', 'plt.step', (['recall', 'precision'], {'where': '"""post"""'}), "(recall, precision, where='post')\n", (15050, 15083), True, 'import matplotlib.pyplot as plt\n'), ((15088, 15108), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Recall"""'], {}), "('Recall')\n", (15098, 15108), True, 'import matplotlib.pyplot as plt\n'), ((15113, 15136), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Precision"""'], {}), "('Precision')\n", (15123, 15136), True, 'import matplotlib.pyplot as plt\n'), ((15141, 15162), 'matplotlib.pyplot.ylim', 'plt.ylim', (['[0.0, 1.05]'], {}), '([0.0, 1.05])\n', (15149, 15162), True, 'import matplotlib.pyplot as plt\n'), ((15167, 15187), 'matplotlib.pyplot.xlim', 'plt.xlim', (['[0.0, 1.0]'], {}), '([0.0, 1.0])\n', (15175, 15187), True, 'import matplotlib.pyplot as plt\n'), ((15368, 15379), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (15377, 15379), True, 'import matplotlib.pyplot as plt\n'), ((4014, 4038), 'shutil.rmtree', 'shutil.rmtree', (['train_dir'], {}), '(train_dir)\n', (4027, 4038), False, 'import shutil\n'), ((4080, 4103), 'shutil.rmtree', 'shutil.rmtree', (['test_dir'], {}), '(test_dir)\n', (4093, 4103), False, 'import shutil\n'), ((4507, 4536), 'os.listdir', 'os.listdir', (['full_stylegan_dir'], {}), '(full_stylegan_dir)\n', (4517, 4536), False, 'import os\n'), ((4719, 4790), 'sklearn.model_selection.KFold', 'KFold', ([], {'n_splits': 'args.kfold', 'shuffle': '(True)', 'random_state': 'args.random_seed'}), '(n_splits=args.kfold, shuffle=True, random_state=args.random_seed)\n', (4724, 4790), False, 'from sklearn.model_selection import KFold\n'), ((4814, 4874), 'sklearn.model_selection.KFold', 'KFold', ([], {'n_splits': 'args.kfold', 'shuffle': '(False)', 'random_state': 'None'}), '(n_splits=args.kfold, shuffle=False, random_state=None)\n', (4819, 4874), False, 'from sklearn.model_selection import KFold\n'), ((5392, 5410), 'numpy.array', 'np.array', (['tmp_list'], {}), '(tmp_list)\n', (5400, 5410), True, 'import numpy as np\n'), ((5813, 5852), 'os.path.exists', 'os.path.exists', (['args.stored_result_path'], {}), '(args.stored_result_path)\n', (5827, 5852), False, 'import os\n'), ((5862, 5895), 'os.mkdir', 'os.mkdir', (['args.stored_result_path'], {}), '(args.stored_result_path)\n', (5870, 5895), False, 'import os\n'), ((11323, 11345), 'config.get_config', 'get_config', (['(True)', 'args'], {}), '(True, args)\n', (11333, 11345), False, 'from config import get_config\n'), ((11951, 12009), 'utils.prepare_facebank', 'prepare_facebank', (['conf', 'learner.model', 'mtcnn'], {'tta': 'args.tta'}), '(conf, learner.model, mtcnn, tta=args.tta)\n', (11967, 12009), False, 'from utils import load_facebank, draw_box_name, prepare_facebank, save_label_score, label_binarize\n'), ((13329, 13345), 'numpy.array', 'np.array', (['scores'], {}), '(scores)\n', (13337, 13345), True, 'import numpy as np\n'), ((6909, 6921), 'os.remove', 'os.remove', (['p'], {}), '(p)\n', (6918, 6921), False, 'import os\n'), ((7006, 7018), 'os.remove', 'os.remove', (['p'], {}), '(p)\n', (7015, 7018), False, 'import os\n'), ((5772, 5795), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (5793, 5795), False, 'import datetime\n'), ((6588, 6643), 'numpy.concatenate', 'np.concatenate', (["(train_set['noonan'], train_set['ltr'])"], {}), "((train_set['noonan'], train_set['ltr']))\n", (6602, 6643), True, 'import numpy as np\n'), ((6737, 6790), 'numpy.concatenate', 'np.concatenate', (["(test_set['noonan'], test_set['ltr'])"], {}), "((test_set['noonan'], test_set['ltr']))\n", (6751, 6790), True, 'import numpy as np\n'), ((7447, 7469), 'os.listdir', 'os.listdir', (['img_folder'], {}), '(img_folder)\n', (7457, 7469), False, 'import os\n'), ((8642, 8664), 'os.listdir', 'os.listdir', (['img_folder'], {}), '(img_folder)\n', (8652, 8664), False, 'import os\n'), ((12839, 12861), 'PIL.Image.fromarray', 'Image.fromarray', (['frame'], {}), '(frame)\n', (12854, 12861), False, 'from PIL import Image\n'), ((13081, 13100), 'numpy.argmax', 'np.argmax', (['score', '(1)'], {}), '(score, 1)\n', (13090, 13100), True, 'import numpy as np\n'), ((7784, 7820), 'os.path.basename', 'os.path.basename', (['train_set[name][i]'], {}), '(train_set[name][i])\n', (7800, 7820), False, 'import os\n'), ((8978, 9013), 'os.path.basename', 'os.path.basename', (['test_set[name][i]'], {}), '(test_set[name][i])\n', (8994, 9013), False, 'import os\n'), ((7981, 8028), 'os.listdir', 'os.listdir', (['(full_stylegan_dir + os.sep + folder)'], {}), '(full_stylegan_dir + os.sep + folder)\n', (7991, 8028), False, 'import os\n'), ((9314, 9361), 'os.listdir', 'os.listdir', (['(full_stylegan_dir + os.sep + folder)'], {}), '(full_stylegan_dir + os.sep + folder)\n', (9324, 9361), False, 'import os\n'), ((11217, 11240), 'os.path.basename', 'os.path.basename', (['img_f'], {}), '(img_f)\n', (11233, 11240), False, 'import os\n')]
import numpy as np DEFAULT_FILE_PATH = "utils/datasets/glove.6B.50d.txt" def loadWordVectors(tokens, filepath=DEFAULT_FILE_PATH, dimensions=50): """Read pretrained GloVe vectors""" wordVectors = np.zeros((len(tokens), dimensions)) with open(filepath) as ifs: for line in ifs: line = line.strip() if not line: continue row = line.split() token = row[0] if token not in tokens: continue data = [float(x) for x in row[1:]] if len(data) != dimensions: raise RuntimeError("wrong number of dimensions") wordVectors[tokens[token]] = np.asarray(data) return wordVectors
[ "numpy.asarray" ]
[((692, 708), 'numpy.asarray', 'np.asarray', (['data'], {}), '(data)\n', (702, 708), True, 'import numpy as np\n')]
import argparse import numpy as np from .._helpers import read, reader_map from ._helpers import _get_version_text def info(argv=None): # Parse command line arguments. parser = _get_info_parser() args = parser.parse_args(argv) # read mesh data mesh = read(args.infile, file_format=args.input_format) print(mesh) # check if the cell arrays are consistent with the points is_consistent = True for cells in mesh.cells: if np.any(cells.data > mesh.points.shape[0]): print("\nATTENTION: Inconsistent mesh. Cells refer to nonexistent points.") is_consistent = False break # check if there are redundant points if is_consistent: point_is_used = np.zeros(mesh.points.shape[0], dtype=bool) for cells in mesh.cells: point_is_used[cells.data] = True if np.any(~point_is_used): print("ATTENTION: Some points are not part of any cell.") def _get_info_parser(): parser = argparse.ArgumentParser( description=("Print mesh info."), formatter_class=argparse.RawTextHelpFormatter ) parser.add_argument("infile", type=str, help="mesh file to be read from") parser.add_argument( "--input-format", "-i", type=str, choices=sorted(list(reader_map.keys())), help="input file format", default=None, ) parser.add_argument( "--version", "-v", action="version", version=_get_version_text(), help="display version information", ) return parser
[ "numpy.any", "numpy.zeros", "argparse.ArgumentParser" ]
[((1006, 1113), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Print mesh info."""', 'formatter_class': 'argparse.RawTextHelpFormatter'}), "(description='Print mesh info.', formatter_class=\n argparse.RawTextHelpFormatter)\n", (1029, 1113), False, 'import argparse\n'), ((469, 510), 'numpy.any', 'np.any', (['(cells.data > mesh.points.shape[0])'], {}), '(cells.data > mesh.points.shape[0])\n', (475, 510), True, 'import numpy as np\n'), ((741, 783), 'numpy.zeros', 'np.zeros', (['mesh.points.shape[0]'], {'dtype': 'bool'}), '(mesh.points.shape[0], dtype=bool)\n', (749, 783), True, 'import numpy as np\n'), ((873, 895), 'numpy.any', 'np.any', (['(~point_is_used)'], {}), '(~point_is_used)\n', (879, 895), True, 'import numpy as np\n')]
import sys import os import argparse import logging import json import time import subprocess from shutil import copyfile import numpy as np from sklearn import metrics from easydict import EasyDict as edict import torch from torch.utils.data import DataLoader import torch.nn.functional as F from torch.nn import DataParallel from vit_pytorch import ViT from tensorboardX import SummaryWriter sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../') torch.manual_seed(0) torch.cuda.manual_seed_all(0) from data.dataset import ImageDataset # noqa from model.classifier import Classifier # noqa from utils.misc import lr_schedule # noqa from model.utils import get_optimizer # noqa parser = argparse.ArgumentParser(description='Train model') parser.add_argument('cfg_path', default=None, metavar='CFG_PATH', type=str, help="Path to the config file in yaml format") parser.add_argument('save_path', default=None, metavar='SAVE_PATH', type=str, help="Path to the saved models") parser.add_argument('--num_workers', default=8, type=int, help="Number of " "workers for each data loader") parser.add_argument('--device_ids', default='0,1,2,3', type=str, help="GPU indices ""comma separated, e.g. '0,1' ") parser.add_argument('--pre_train', default=None, type=str, help="If get" "parameters from pretrained model") parser.add_argument('--resume', default=0, type=int, help="If resume from " "previous run") parser.add_argument('--logtofile', default=False, type=bool, help="Save log " "in save_path/log.txt if set True") parser.add_argument('--verbose', default=False, type=bool, help="Detail info") def get_loss(output, target, index, device, cfg): if cfg.criterion == 'BCE': for num_class in cfg.num_classes: assert num_class == 1 target = target[:, index].view(-1) pos_weight = torch.from_numpy( np.array(cfg.pos_weight, dtype=np.float32)).to(device).type_as(target) if cfg.batch_weight: if target.sum() == 0: loss = torch.tensor(0., requires_grad=True).to(device) else: weight = (target.size()[0] - target.sum()) / target.sum() loss = F.binary_cross_entropy_with_logits( output[index].view(-1), target, pos_weight=weight) else: loss = F.binary_cross_entropy_with_logits( output[index].view(-1), target, pos_weight=pos_weight[index]) label = torch.sigmoid(output[index].view(-1)).ge(0.5).float() acc = (target == label).float().sum() / len(label) else: raise Exception('Unknown criterion : {}'.format(cfg.criterion)) return (loss, acc) def train_epoch(summary, summary_dev, cfg, args, model, dataloader, dataloader_dev, optimizer, summary_writer, best_dict, dev_header): torch.set_grad_enabled(True) model.train() device_ids = list(map(int, args.device_ids.split(','))) device = torch.device('cuda:{}'.format(device_ids[0])) steps = len(dataloader) dataiter = iter(dataloader) label_header = dataloader.dataset._label_header num_tasks = len(cfg.num_classes) time_now = time.time() loss_sum = np.zeros(num_tasks) acc_sum = np.zeros(num_tasks) for step in range(steps): image, target = next(dataiter) image = image.to(device) target = target.to(device) # output, logit_map = model(image) output = model(image) output = [torch.unsqueeze(i, 1) for i in output.T] # different number of tasks loss = 0 for t in range(num_tasks): loss_t, acc_t = get_loss(output, target, t, device, cfg) loss += loss_t loss_sum[t] += loss_t.item() acc_sum[t] += acc_t.item() optimizer.zero_grad() loss.backward() optimizer.step() summary['step'] += 1 if summary['step'] % cfg.log_every == 0: time_spent = time.time() - time_now time_now = time.time() loss_sum /= cfg.log_every acc_sum /= cfg.log_every loss_str = ' '.join(map(lambda x: '{:.5f}'.format(x), loss_sum)) acc_str = ' '.join(map(lambda x: '{:.3f}'.format(x), acc_sum)) logging.info( '{}, Train, Epoch : {}, Step : {}, Loss : {}, ' 'Acc : {}, Run Time : {:.2f} sec' .format(time.strftime("%Y-%m-%d %H:%M:%S"), summary['epoch'] + 1, summary['step'], loss_str, acc_str, time_spent)) for t in range(num_tasks): summary_writer.add_scalar( 'train/loss_{}'.format(label_header[t]), loss_sum[t], summary['step']) summary_writer.add_scalar( 'train/acc_{}'.format(label_header[t]), acc_sum[t], summary['step']) loss_sum = np.zeros(num_tasks) acc_sum = np.zeros(num_tasks) if summary['step'] % cfg.test_every == 0: time_now = time.time() summary_dev, predlist, true_list = test_epoch( summary_dev, cfg, args, model, dataloader_dev) time_spent = time.time() - time_now auclist = [] for i in range(len(cfg.num_classes)): y_pred = predlist[i] y_true = true_list[i] fpr, tpr, thresholds = metrics.roc_curve( y_true, y_pred, pos_label=1) auc = metrics.auc(fpr, tpr) auclist.append(auc) summary_dev['auc'] = np.array(auclist) loss_dev_str = ' '.join(map(lambda x: '{:.5f}'.format(x), summary_dev['loss'])) acc_dev_str = ' '.join(map(lambda x: '{:.3f}'.format(x), summary_dev['acc'])) auc_dev_str = ' '.join(map(lambda x: '{:.3f}'.format(x), summary_dev['auc'])) logging.info( '{}, Dev, Step : {}, Loss : {}, Acc : {}, Auc : {},' 'Mean auc: {:.3f} ''Run Time : {:.2f} sec' .format( time.strftime("%Y-%m-%d %H:%M:%S"), summary['step'], loss_dev_str, acc_dev_str, auc_dev_str, summary_dev['auc'].mean(), time_spent)) for t in range(len(cfg.num_classes)): summary_writer.add_scalar( 'dev/loss_{}'.format(dev_header[t]), summary_dev['loss'][t], summary['step']) summary_writer.add_scalar( 'dev/acc_{}'.format(dev_header[t]), summary_dev['acc'][t], summary['step']) summary_writer.add_scalar( 'dev/auc_{}'.format(dev_header[t]), summary_dev['auc'][t], summary['step']) save_best = False mean_acc = summary_dev['acc'][cfg.save_index].mean() if mean_acc >= best_dict['acc_dev_best']: best_dict['acc_dev_best'] = mean_acc if cfg.best_target == 'acc': save_best = True mean_auc = summary_dev['auc'][cfg.save_index].mean() if mean_auc >= best_dict['auc_dev_best']: best_dict['auc_dev_best'] = mean_auc if cfg.best_target == 'auc': save_best = True mean_loss = summary_dev['loss'][cfg.save_index].mean() if mean_loss <= best_dict['loss_dev_best']: best_dict['loss_dev_best'] = mean_loss if cfg.best_target == 'loss': save_best = True if save_best: torch.save( {'epoch': summary['epoch'], 'step': summary['step'], 'acc_dev_best': best_dict['acc_dev_best'], 'auc_dev_best': best_dict['auc_dev_best'], 'loss_dev_best': best_dict['loss_dev_best'], 'state_dict': model.module.state_dict()}, os.path.join(args.save_path, 'best{}.ckpt'.format( best_dict['best_idx'])) ) best_dict['best_idx'] += 1 if best_dict['best_idx'] > cfg.save_top_k: best_dict['best_idx'] = 1 logging.info( '{}, Best, Step : {}, Loss : {}, Acc : {},Auc :{},' 'Best Auc : {:.3f}' .format( time.strftime("%Y-%m-%d %H:%M:%S"), summary['step'], loss_dev_str, acc_dev_str, auc_dev_str, best_dict['auc_dev_best'])) model.train() torch.set_grad_enabled(True) summary['epoch'] += 1 return summary, best_dict def test_epoch(summary, cfg, args, model, dataloader): torch.set_grad_enabled(False) model.eval() device_ids = list(map(int, args.device_ids.split(','))) device = torch.device('cuda:{}'.format(device_ids[0])) steps = len(dataloader) dataiter = iter(dataloader) num_tasks = len(cfg.num_classes) loss_sum = np.zeros(num_tasks) acc_sum = np.zeros(num_tasks) predlist = list(x for x in range(len(cfg.num_classes))) true_list = list(x for x in range(len(cfg.num_classes))) for step in range(steps): image, target = next(dataiter) image = image.to(device) target = target.to(device) output = model(image) output = [torch.unsqueeze(i, 1) for i in output.T] # different number of tasks for t in range(len(cfg.num_classes)): loss_t, acc_t = get_loss(output, target, t, device, cfg) # AUC output_tensor = torch.sigmoid( output[t].view(-1)).cpu().detach().numpy() target_tensor = target[:, t].view(-1).cpu().detach().numpy() if step == 0: predlist[t] = output_tensor true_list[t] = target_tensor else: predlist[t] = np.append(predlist[t], output_tensor) true_list[t] = np.append(true_list[t], target_tensor) loss_sum[t] += loss_t.item() acc_sum[t] += acc_t.item() summary['loss'] = loss_sum / steps summary['acc'] = acc_sum / steps return summary, predlist, true_list def run(args): with open(args.cfg_path) as f: cfg = edict(json.load(f)) if args.verbose is True: print(json.dumps(cfg, indent=4)) if not os.path.exists(args.save_path): os.mkdir(args.save_path) if args.logtofile is True: logging.basicConfig(filename=args.save_path + '/log.txt', filemode="w", level=logging.INFO) else: logging.basicConfig(level=logging.INFO) if not args.resume: with open(os.path.join(args.save_path, 'cfg.json'), 'w') as f: json.dump(cfg, f, indent=1) device_ids = list(map(int, args.device_ids.split(','))) num_devices = torch.cuda.device_count() if num_devices < len(device_ids): raise Exception( '#available gpu : {} < --device_ids : {}' .format(num_devices, len(device_ids))) device = torch.device('cuda:{}'.format(device_ids[0])) # model = Classifier(cfg) model = ViT( cfg = cfg, image_size=cfg.width, patch_size=32, num_classes=5, dim=1024, depth=6, heads=8, mlp_dim=512, dropout=0.3, emb_dropout=0.3, channels=3 ) if args.verbose is True: from torchsummary import summary if cfg.fix_ratio: h, w = cfg.long_side, cfg.long_side else: h, w = cfg.height, cfg.width summary(model.to(device), (3, h, w)) model = DataParallel(model, device_ids=device_ids).to(device).train() if args.pre_train is not None: if os.path.exists(args.pre_train): ckpt = torch.load(args.pre_train, map_location=device) model.module.load_state_dict(ckpt) optimizer = get_optimizer(model.parameters(), cfg) src_folder = os.path.dirname(os.path.abspath(__file__)) + '/../' dst_folder = os.path.join(args.save_path, 'classification') rc, size = subprocess.getstatusoutput('du --max-depth=0 %s | cut -f1' % src_folder) if rc != 0: raise Exception('Copy folder error : {}'.format(rc)) rc, err_msg = subprocess.getstatusoutput('cp -R %s %s' % (src_folder, dst_folder)) if rc != 0: raise Exception('copy folder error : {}'.format(err_msg)) copyfile(cfg.train_csv, os.path.join(args.save_path, 'train.csv')) copyfile(cfg.dev_csv, os.path.join(args.save_path, 'dev.csv')) dataloader_train = DataLoader( ImageDataset(cfg.train_csv, cfg, mode='train'), batch_size=cfg.train_batch_size, num_workers=args.num_workers, drop_last=True, shuffle=True) dataloader_dev = DataLoader( ImageDataset(cfg.dev_csv, cfg, mode='dev'), batch_size=cfg.dev_batch_size, num_workers=args.num_workers, drop_last=False, shuffle=False) dev_header = dataloader_dev.dataset._label_header summary_train = {'epoch': 0, 'step': 0} summary_dev = {'loss': float('inf'), 'acc': 0.0} summary_writer = SummaryWriter(args.save_path) epoch_start = 0 best_dict = { "acc_dev_best": 0.0, "auc_dev_best": 0.0, "loss_dev_best": float('inf'), "fused_dev_best": 0.0, "best_idx": 1} if args.resume: ckpt_path = os.path.join(args.save_path, 'train.ckpt') ckpt = torch.load(ckpt_path, map_location=device) model.module.load_state_dict(ckpt['state_dict']) summary_train = {'epoch': ckpt['epoch'], 'step': ckpt['step']} best_dict['acc_dev_best'] = ckpt['acc_dev_best'] best_dict['loss_dev_best'] = ckpt['loss_dev_best'] best_dict['auc_dev_best'] = ckpt['auc_dev_best'] epoch_start = ckpt['epoch'] for epoch in range(epoch_start, cfg.epoch): lr = lr_schedule(cfg.lr, cfg.lr_factor, summary_train['epoch'], cfg.lr_epochs) for param_group in optimizer.param_groups: param_group['lr'] = lr summary_train, best_dict = train_epoch( summary_train, summary_dev, cfg, args, model, dataloader_train, dataloader_dev, optimizer, summary_writer, best_dict, dev_header) time_now = time.time() summary_dev, predlist, true_list = test_epoch( summary_dev, cfg, args, model, dataloader_dev) time_spent = time.time() - time_now auclist = [] for i in range(len(cfg.num_classes)): y_pred = predlist[i] y_true = true_list[i] fpr, tpr, thresholds = metrics.roc_curve( y_true, y_pred, pos_label=1) auc = metrics.auc(fpr, tpr) auclist.append(auc) summary_dev['auc'] = np.array(auclist) loss_dev_str = ' '.join(map(lambda x: '{:.5f}'.format(x), summary_dev['loss'])) acc_dev_str = ' '.join(map(lambda x: '{:.3f}'.format(x), summary_dev['acc'])) auc_dev_str = ' '.join(map(lambda x: '{:.3f}'.format(x), summary_dev['auc'])) logging.info( '{}, Dev, Step : {}, Loss : {}, Acc : {}, Auc : {},' 'Mean auc: {:.3f} ''Run Time : {:.2f} sec' .format( time.strftime("%Y-%m-%d %H:%M:%S"), summary_train['step'], loss_dev_str, acc_dev_str, auc_dev_str, summary_dev['auc'].mean(), time_spent)) for t in range(len(cfg.num_classes)): summary_writer.add_scalar( 'dev/loss_{}'.format(dev_header[t]), summary_dev['loss'][t], summary_train['step']) summary_writer.add_scalar( 'dev/acc_{}'.format(dev_header[t]), summary_dev['acc'][t], summary_train['step']) summary_writer.add_scalar( 'dev/auc_{}'.format(dev_header[t]), summary_dev['auc'][t], summary_train['step']) save_best = False mean_acc = summary_dev['acc'][cfg.save_index].mean() if mean_acc >= best_dict['acc_dev_best']: best_dict['acc_dev_best'] = mean_acc if cfg.best_target == 'acc': save_best = True mean_auc = summary_dev['auc'][cfg.save_index].mean() if mean_auc >= best_dict['auc_dev_best']: best_dict['auc_dev_best'] = mean_auc if cfg.best_target == 'auc': save_best = True mean_loss = summary_dev['loss'][cfg.save_index].mean() if mean_loss <= best_dict['loss_dev_best']: best_dict['loss_dev_best'] = mean_loss if cfg.best_target == 'loss': save_best = True if save_best: torch.save( {'epoch': summary_train['epoch'], 'step': summary_train['step'], 'acc_dev_best': best_dict['acc_dev_best'], 'auc_dev_best': best_dict['auc_dev_best'], 'loss_dev_best': best_dict['loss_dev_best'], 'state_dict': model.module.state_dict()}, os.path.join(args.save_path, 'best{}.ckpt'.format(best_dict['best_idx'])) ) best_dict['best_idx'] += 1 if best_dict['best_idx'] > cfg.save_top_k: best_dict['best_idx'] = 1 logging.info( '{}, Best, Step : {}, Loss : {}, Acc : {},' 'Auc :{},Best Auc : {:.3f}' .format( time.strftime("%Y-%m-%d %H:%M:%S"), summary_train['step'], loss_dev_str, acc_dev_str, auc_dev_str, best_dict['auc_dev_best'])) torch.save({'epoch': summary_train['epoch'], 'step': summary_train['step'], 'acc_dev_best': best_dict['acc_dev_best'], 'auc_dev_best': best_dict['auc_dev_best'], 'loss_dev_best': best_dict['loss_dev_best'], 'state_dict': model.module.state_dict()}, os.path.join(args.save_path, 'train.ckpt')) summary_writer.close() def main(): args = parser.parse_args() if args.verbose is True: print('Using the specified args:') print(args) run(args) if __name__ == '__main__': main()
[ "sklearn.metrics.auc", "torch.cuda.device_count", "numpy.array", "sklearn.metrics.roc_curve", "os.path.exists", "tensorboardX.SummaryWriter", "argparse.ArgumentParser", "torch.unsqueeze", "json.dumps", "os.mkdir", "subprocess.getstatusoutput", "utils.misc.lr_schedule", "time.time", "data.dataset.ImageDataset", "torch.cuda.manual_seed_all", "torch.manual_seed", "logging.basicConfig", "torch.load", "time.strftime", "os.path.join", "torch.nn.DataParallel", "vit_pytorch.ViT", "json.load", "numpy.append", "numpy.zeros", "torch.tensor", "os.path.abspath", "torch.set_grad_enabled", "json.dump" ]
[((466, 486), 'torch.manual_seed', 'torch.manual_seed', (['(0)'], {}), '(0)\n', (483, 486), False, 'import torch\n'), ((487, 516), 'torch.cuda.manual_seed_all', 'torch.cuda.manual_seed_all', (['(0)'], {}), '(0)\n', (513, 516), False, 'import torch\n'), ((711, 761), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Train model"""'}), "(description='Train model')\n", (734, 761), False, 'import argparse\n'), ((3011, 3039), 'torch.set_grad_enabled', 'torch.set_grad_enabled', (['(True)'], {}), '(True)\n', (3033, 3039), False, 'import torch\n'), ((3342, 3353), 'time.time', 'time.time', ([], {}), '()\n', (3351, 3353), False, 'import time\n'), ((3369, 3388), 'numpy.zeros', 'np.zeros', (['num_tasks'], {}), '(num_tasks)\n', (3377, 3388), True, 'import numpy as np\n'), ((3403, 3422), 'numpy.zeros', 'np.zeros', (['num_tasks'], {}), '(num_tasks)\n', (3411, 3422), True, 'import numpy as np\n'), ((9269, 9298), 'torch.set_grad_enabled', 'torch.set_grad_enabled', (['(False)'], {}), '(False)\n', (9291, 9298), False, 'import torch\n'), ((9548, 9567), 'numpy.zeros', 'np.zeros', (['num_tasks'], {}), '(num_tasks)\n', (9556, 9567), True, 'import numpy as np\n'), ((9582, 9601), 'numpy.zeros', 'np.zeros', (['num_tasks'], {}), '(num_tasks)\n', (9590, 9601), True, 'import numpy as np\n'), ((11437, 11462), 'torch.cuda.device_count', 'torch.cuda.device_count', ([], {}), '()\n', (11460, 11462), False, 'import torch\n'), ((11733, 11884), 'vit_pytorch.ViT', 'ViT', ([], {'cfg': 'cfg', 'image_size': 'cfg.width', 'patch_size': '(32)', 'num_classes': '(5)', 'dim': '(1024)', 'depth': '(6)', 'heads': '(8)', 'mlp_dim': '(512)', 'dropout': '(0.3)', 'emb_dropout': '(0.3)', 'channels': '(3)'}), '(cfg=cfg, image_size=cfg.width, patch_size=32, num_classes=5, dim=1024,\n depth=6, heads=8, mlp_dim=512, dropout=0.3, emb_dropout=0.3, channels=3)\n', (11736, 11884), False, 'from vit_pytorch import ViT\n'), ((12629, 12675), 'os.path.join', 'os.path.join', (['args.save_path', '"""classification"""'], {}), "(args.save_path, 'classification')\n", (12641, 12675), False, 'import os\n'), ((12691, 12763), 'subprocess.getstatusoutput', 'subprocess.getstatusoutput', (["('du --max-depth=0 %s | cut -f1' % src_folder)"], {}), "('du --max-depth=0 %s | cut -f1' % src_folder)\n", (12717, 12763), False, 'import subprocess\n'), ((12901, 12969), 'subprocess.getstatusoutput', 'subprocess.getstatusoutput', (["('cp -R %s %s' % (src_folder, dst_folder))"], {}), "('cp -R %s %s' % (src_folder, dst_folder))\n", (12927, 12969), False, 'import subprocess\n'), ((13821, 13850), 'tensorboardX.SummaryWriter', 'SummaryWriter', (['args.save_path'], {}), '(args.save_path)\n', (13834, 13850), False, 'from tensorboardX import SummaryWriter\n'), ((9122, 9150), 'torch.set_grad_enabled', 'torch.set_grad_enabled', (['(True)'], {}), '(True)\n', (9144, 9150), False, 'import torch\n'), ((10940, 10970), 'os.path.exists', 'os.path.exists', (['args.save_path'], {}), '(args.save_path)\n', (10954, 10970), False, 'import os\n'), ((10980, 11004), 'os.mkdir', 'os.mkdir', (['args.save_path'], {}), '(args.save_path)\n', (10988, 11004), False, 'import os\n'), ((11044, 11139), 'logging.basicConfig', 'logging.basicConfig', ([], {'filename': "(args.save_path + '/log.txt')", 'filemode': '"""w"""', 'level': 'logging.INFO'}), "(filename=args.save_path + '/log.txt', filemode='w',\n level=logging.INFO)\n", (11063, 11139), False, 'import logging\n'), ((11182, 11221), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO'}), '(level=logging.INFO)\n', (11201, 11221), False, 'import logging\n'), ((12341, 12371), 'os.path.exists', 'os.path.exists', (['args.pre_train'], {}), '(args.pre_train)\n', (12355, 12371), False, 'import os\n'), ((13143, 13184), 'os.path.join', 'os.path.join', (['args.save_path', '"""train.csv"""'], {}), "(args.save_path, 'train.csv')\n", (13155, 13184), False, 'import os\n'), ((13212, 13251), 'os.path.join', 'os.path.join', (['args.save_path', '"""dev.csv"""'], {}), "(args.save_path, 'dev.csv')\n", (13224, 13251), False, 'import os\n'), ((13297, 13343), 'data.dataset.ImageDataset', 'ImageDataset', (['cfg.train_csv', 'cfg'], {'mode': '"""train"""'}), "(cfg.train_csv, cfg, mode='train')\n", (13309, 13343), False, 'from data.dataset import ImageDataset\n'), ((13495, 13537), 'data.dataset.ImageDataset', 'ImageDataset', (['cfg.dev_csv', 'cfg'], {'mode': '"""dev"""'}), "(cfg.dev_csv, cfg, mode='dev')\n", (13507, 13537), False, 'from data.dataset import ImageDataset\n'), ((14081, 14123), 'os.path.join', 'os.path.join', (['args.save_path', '"""train.ckpt"""'], {}), "(args.save_path, 'train.ckpt')\n", (14093, 14123), False, 'import os\n'), ((14139, 14181), 'torch.load', 'torch.load', (['ckpt_path'], {'map_location': 'device'}), '(ckpt_path, map_location=device)\n', (14149, 14181), False, 'import torch\n'), ((14581, 14654), 'utils.misc.lr_schedule', 'lr_schedule', (['cfg.lr', 'cfg.lr_factor', "summary_train['epoch']", 'cfg.lr_epochs'], {}), "(cfg.lr, cfg.lr_factor, summary_train['epoch'], cfg.lr_epochs)\n", (14592, 14654), False, 'from utils.misc import lr_schedule\n'), ((15001, 15012), 'time.time', 'time.time', ([], {}), '()\n', (15010, 15012), False, 'import time\n'), ((15506, 15523), 'numpy.array', 'np.array', (['auclist'], {}), '(auclist)\n', (15514, 15523), True, 'import numpy as np\n'), ((428, 453), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (443, 453), False, 'import os\n'), ((3651, 3672), 'torch.unsqueeze', 'torch.unsqueeze', (['i', '(1)'], {}), '(i, 1)\n', (3666, 3672), False, 'import torch\n'), ((4188, 4199), 'time.time', 'time.time', ([], {}), '()\n', (4197, 4199), False, 'import time\n'), ((5118, 5137), 'numpy.zeros', 'np.zeros', (['num_tasks'], {}), '(num_tasks)\n', (5126, 5137), True, 'import numpy as np\n'), ((5160, 5179), 'numpy.zeros', 'np.zeros', (['num_tasks'], {}), '(num_tasks)\n', (5168, 5179), True, 'import numpy as np\n'), ((5254, 5265), 'time.time', 'time.time', ([], {}), '()\n', (5263, 5265), False, 'import time\n'), ((5807, 5824), 'numpy.array', 'np.array', (['auclist'], {}), '(auclist)\n', (5815, 5824), True, 'import numpy as np\n'), ((9909, 9930), 'torch.unsqueeze', 'torch.unsqueeze', (['i', '(1)'], {}), '(i, 1)\n', (9924, 9930), False, 'import torch\n'), ((10836, 10848), 'json.load', 'json.load', (['f'], {}), '(f)\n', (10845, 10848), False, 'import json\n'), ((11330, 11357), 'json.dump', 'json.dump', (['cfg', 'f'], {'indent': '(1)'}), '(cfg, f, indent=1)\n', (11339, 11357), False, 'import json\n'), ((12392, 12439), 'torch.load', 'torch.load', (['args.pre_train'], {'map_location': 'device'}), '(args.pre_train, map_location=device)\n', (12402, 12439), False, 'import torch\n'), ((12576, 12601), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (12591, 12601), False, 'import os\n'), ((15148, 15159), 'time.time', 'time.time', ([], {}), '()\n', (15157, 15159), False, 'import time\n'), ((15341, 15387), 'sklearn.metrics.roc_curve', 'metrics.roc_curve', (['y_true', 'y_pred'], {'pos_label': '(1)'}), '(y_true, y_pred, pos_label=1)\n', (15358, 15387), False, 'from sklearn import metrics\n'), ((15423, 15444), 'sklearn.metrics.auc', 'metrics.auc', (['fpr', 'tpr'], {}), '(fpr, tpr)\n', (15434, 15444), False, 'from sklearn import metrics\n'), ((18958, 19000), 'os.path.join', 'os.path.join', (['args.save_path', '"""train.ckpt"""'], {}), "(args.save_path, 'train.ckpt')\n", (18970, 19000), False, 'import os\n'), ((4142, 4153), 'time.time', 'time.time', ([], {}), '()\n', (4151, 4153), False, 'import time\n'), ((5413, 5424), 'time.time', 'time.time', ([], {}), '()\n', (5422, 5424), False, 'import time\n'), ((5626, 5672), 'sklearn.metrics.roc_curve', 'metrics.roc_curve', (['y_true', 'y_pred'], {'pos_label': '(1)'}), '(y_true, y_pred, pos_label=1)\n', (5643, 5672), False, 'from sklearn import metrics\n'), ((5716, 5737), 'sklearn.metrics.auc', 'metrics.auc', (['fpr', 'tpr'], {}), '(fpr, tpr)\n', (5727, 5737), False, 'from sklearn import metrics\n'), ((10458, 10495), 'numpy.append', 'np.append', (['predlist[t]', 'output_tensor'], {}), '(predlist[t], output_tensor)\n', (10467, 10495), True, 'import numpy as np\n'), ((10527, 10565), 'numpy.append', 'np.append', (['true_list[t]', 'target_tensor'], {}), '(true_list[t], target_tensor)\n', (10536, 10565), True, 'import numpy as np\n'), ((10901, 10926), 'json.dumps', 'json.dumps', (['cfg'], {'indent': '(4)'}), '(cfg, indent=4)\n', (10911, 10926), False, 'import json\n'), ((11265, 11305), 'os.path.join', 'os.path.join', (['args.save_path', '"""cfg.json"""'], {}), "(args.save_path, 'cfg.json')\n", (11277, 11305), False, 'import os\n'), ((16059, 16093), 'time.strftime', 'time.strftime', (['"""%Y-%m-%d %H:%M:%S"""'], {}), "('%Y-%m-%d %H:%M:%S')\n", (16072, 16093), False, 'import time\n'), ((4593, 4627), 'time.strftime', 'time.strftime', (['"""%Y-%m-%d %H:%M:%S"""'], {}), "('%Y-%m-%d %H:%M:%S')\n", (4606, 4627), False, 'import time\n'), ((6400, 6434), 'time.strftime', 'time.strftime', (['"""%Y-%m-%d %H:%M:%S"""'], {}), "('%Y-%m-%d %H:%M:%S')\n", (6413, 6434), False, 'import time\n'), ((12233, 12275), 'torch.nn.DataParallel', 'DataParallel', (['model'], {'device_ids': 'device_ids'}), '(model, device_ids=device_ids)\n', (12245, 12275), False, 'from torch.nn import DataParallel\n'), ((18355, 18389), 'time.strftime', 'time.strftime', (['"""%Y-%m-%d %H:%M:%S"""'], {}), "('%Y-%m-%d %H:%M:%S')\n", (18368, 18389), False, 'import time\n'), ((2185, 2222), 'torch.tensor', 'torch.tensor', (['(0.0)'], {'requires_grad': '(True)'}), '(0.0, requires_grad=True)\n', (2197, 2222), False, 'import torch\n'), ((8851, 8885), 'time.strftime', 'time.strftime', (['"""%Y-%m-%d %H:%M:%S"""'], {}), "('%Y-%m-%d %H:%M:%S')\n", (8864, 8885), False, 'import time\n'), ((2007, 2049), 'numpy.array', 'np.array', (['cfg.pos_weight'], {'dtype': 'np.float32'}), '(cfg.pos_weight, dtype=np.float32)\n', (2015, 2049), True, 'import numpy as np\n')]
"""Coordinate changes in state space models.""" import abc try: # cached_property is only available in Python >=3.8 from functools import cached_property except ImportError: from cached_property import cached_property import numpy as np import scipy.special # for vectorised factorial from probnum import config, linops, randvars def apply_precon(precon, rv): # public (because it is needed in some integrator implementations), # but not exposed to the 'randprocs' namespace # (i.e. not imported in any __init__.py). # There is no way of checking whether `rv` has its Cholesky factor computed already or not. # Therefore, since we need to update the Cholesky factor for square-root filtering, # we also update the Cholesky factor for non-square-root algorithms here, # which implies additional cost. # See Issues #319 and #329. # When they are resolved, this function here will hopefully be superfluous. new_mean = precon @ rv.mean new_cov_cholesky = precon @ rv.cov_cholesky # precon is diagonal, so this is valid new_cov = new_cov_cholesky @ new_cov_cholesky.T return randvars.Normal(new_mean, new_cov, cov_cholesky=new_cov_cholesky) class Preconditioner(abc.ABC): """Coordinate change transformations as preconditioners in state space models. For some models, this makes the filtering and smoothing steps more numerically stable. """ @abc.abstractmethod def __call__(self, step) -> np.ndarray: # if more than step is needed, add them into the signature in the future raise NotImplementedError @cached_property def inverse(self) -> "Preconditioner": raise NotImplementedError class NordsieckLikeCoordinates(Preconditioner): """Nordsieck-like coordinates. Similar to Nordsieck coordinates (which store the Taylor coefficients instead of the derivatives), but better for ODE filtering and smoothing. Used in integrator-transitions, e.g. in :class:`IntegratedWienerTransition`. """ def __init__(self, powers, scales, dimension): # Clean way of assembling these coordinates cheaply, # because the powers and scales of the inverse # are better read off than inverted self.powers = powers self.scales = scales self.dimension = dimension @classmethod def from_order(cls, order, dimension): # used to conveniently initialise in the beginning powers = np.arange(order, -1, -1) scales = scipy.special.factorial(powers) return cls( powers=powers + 0.5, scales=scales, dimension=dimension, ) def __call__(self, step): scaling_vector = np.abs(step) ** self.powers / self.scales if config.matrix_free: return linops.Kronecker( A=linops.Identity(self.dimension), B=linops.Scaling(factors=scaling_vector), ) return np.kron(np.eye(self.dimension), np.diag(scaling_vector)) @cached_property def inverse(self) -> "NordsieckLikeCoordinates": return NordsieckLikeCoordinates( powers=-self.powers, scales=1.0 / self.scales, dimension=self.dimension, )
[ "numpy.abs", "numpy.eye", "probnum.randvars.Normal", "probnum.linops.Scaling", "numpy.diag", "probnum.linops.Identity", "numpy.arange" ]
[((1145, 1210), 'probnum.randvars.Normal', 'randvars.Normal', (['new_mean', 'new_cov'], {'cov_cholesky': 'new_cov_cholesky'}), '(new_mean, new_cov, cov_cholesky=new_cov_cholesky)\n', (1160, 1210), False, 'from probnum import config, linops, randvars\n'), ((2482, 2506), 'numpy.arange', 'np.arange', (['order', '(-1)', '(-1)'], {}), '(order, -1, -1)\n', (2491, 2506), True, 'import numpy as np\n'), ((2991, 3013), 'numpy.eye', 'np.eye', (['self.dimension'], {}), '(self.dimension)\n', (2997, 3013), True, 'import numpy as np\n'), ((3015, 3038), 'numpy.diag', 'np.diag', (['scaling_vector'], {}), '(scaling_vector)\n', (3022, 3038), True, 'import numpy as np\n'), ((2735, 2747), 'numpy.abs', 'np.abs', (['step'], {}), '(step)\n', (2741, 2747), True, 'import numpy as np\n'), ((2863, 2894), 'probnum.linops.Identity', 'linops.Identity', (['self.dimension'], {}), '(self.dimension)\n', (2878, 2894), False, 'from probnum import config, linops, randvars\n'), ((2914, 2952), 'probnum.linops.Scaling', 'linops.Scaling', ([], {'factors': 'scaling_vector'}), '(factors=scaling_vector)\n', (2928, 2952), False, 'from probnum import config, linops, randvars\n')]
import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torchvision import datasets from torch.autograd import Variable from sklearn.model_selection import train_test_split import time import pandas as pd import numpy as np import csv batch_size = 128 NUM_EPOCHS = 30 LR = 0.001 TIME_STEP = 4 class CCRNN(nn.Module): def __init__(self): # 继承RNN super(CCRNN, self).__init__() self.ccLSTM = nn.LSTM( input_size=4, hidden_size=128, num_layers=4, bidirectional=True, batch_first=True ) self.ccCNN22 = nn.Conv2d( in_channels=1, out_channels=1, kernel_size=2, stride=2, padding=0 ) self.ccCNN14 = nn.Conv2d( in_channels=1, out_channels=1, kernel_size=(1, 4), stride=1, padding=0 ) self.ccCNN41 = nn.Conv2d( in_channels=1, out_channels=1, kernel_size=(4, 1), stride=1, padding=0 ) self.CNN22toFC = nn.Linear(4, 64) self.CNN41toFC = nn.Linear(4, 32) self.CNN14toFC = nn.Linear(4, 32) self.LSTMtoFC = nn.Linear(256, 128) self.FCtoOut = nn.Linear(256, 4) def forward(self, x): LSTM_out, (h_n, c_n) = self.ccLSTM(x, None) CNN_in = torch.unsqueeze(x[:, 0:4, :], 1) CNN_out22 = self.ccCNN22(CNN_in) CNN_out41 = self.ccCNN41(CNN_in) CNN_out14 = self.ccCNN14(CNN_in) CNN22_reshape = CNN_out22.view(-1, 4) CNN14_reshape = CNN_out41.view(-1, 4) CNN41_reshape = CNN_out14.view(-1, 4) CNN22toFC = self.CNN22toFC(CNN22_reshape) CNN14toFC = self.CNN14toFC(CNN14_reshape) CNN41toFC = self.CNN41toFC(CNN41_reshape) LSTMtoFC = self.LSTMtoFC(LSTM_out[:, -1, :]) CNNandLSTM = torch.cat((CNN22toFC, CNN41toFC, CNN14toFC, LSTMtoFC), 1) out = self.FCtoOut(CNNandLSTM) return out #------------------读入数据----------------------------- csv_data = pd.read_csv('./drive/My Drive/DATA.csv') csv_data = csv_data.values A = csv_data.shape[0] board_data = csv_data[:,0:16] # X = np.log2(X) X = torch.FloatTensor(board_data) X = np.int64(board_data) # 转置后拼接 X = np.reshape(X, (-1,4,4)) XT = X.transpose(0,2,1) X = np.concatenate((X,XT),axis=1) print(X.shape) direction_data = csv_data[:,16] Y = np.int64(direction_data) #------------------------------------------------------- X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2,shuffle=False) X_train = torch.FloatTensor(X_train) X_test = torch.FloatTensor(X_test) Y_train = torch.LongTensor(Y_train) Y_test = torch.LongTensor(Y_test) train_dataset = torch.utils.data.TensorDataset(X_train,Y_train) # test_dataset = torch.utils.data.TensorDataset(X_test,Y_test) train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True ) # test_loader = torch.utils.data.DataLoader(dataset=test_dataset, # batch_size=batch_size, # shuffle=False # ) batch_size = 128 NUM_EPOCHS = 30 LR = 0.001 TIME_STEP = 4 #------------------读入数据----------------------------- csv_data = pd.read_csv('./drive/My Drive/DATA.csv') csv_data = csv_data.values A = csv_data.shape[0] board_data = csv_data[:,0:16] # X = np.log2(X) X = torch.FloatTensor(board_data) X = np.int64(board_data) # 转置后拼接 X = np.reshape(X, (-1,4,4)) XT = X.transpose(0,2,1) X = np.concatenate((X,XT),axis=1) print(X.shape) direction_data = csv_data[:,16] Y = np.int64(direction_data) model = CCRNN() model = model.cuda() optimizer = optim.Adam(model.parameters(), lr = 0.001) def train(epoch): for batch_idx, (data, target) in enumerate(train_loader): data, target = Variable(data).cuda(), Variable(target).cuda() data = data/11.0 optimizer.zero_grad() output = model(data) loss = F.cross_entropy(output, target) loss.backward() optimizer.step() if batch_idx % 50 == 0: print('Train Epoch: {} [{}/{} ({:.0f}%)]\t Loss: {:.6f}'.format( epoch, batch_idx * len(data), len(train_loader.dataset), 100. * batch_idx / len(train_loader), loss.item())) torch.save(self.model, 'rnn_model_' + str(epoch) + '.pkl') if __name__ == '__main__': for epoch in range(0, NUM_EPOCHS): train(epoch)
[ "numpy.int64", "numpy.reshape", "pandas.read_csv", "sklearn.model_selection.train_test_split", "torch.LongTensor", "torch.nn.LSTM", "torch.unsqueeze", "torch.utils.data.TensorDataset", "torch.nn.Conv2d", "numpy.concatenate", "torch.utils.data.DataLoader", "torch.nn.Linear", "torch.nn.functional.cross_entropy", "torch.autograd.Variable", "torch.FloatTensor", "torch.cat" ]
[((2241, 2281), 'pandas.read_csv', 'pd.read_csv', (['"""./drive/My Drive/DATA.csv"""'], {}), "('./drive/My Drive/DATA.csv')\n", (2252, 2281), True, 'import pandas as pd\n'), ((2387, 2416), 'torch.FloatTensor', 'torch.FloatTensor', (['board_data'], {}), '(board_data)\n', (2404, 2416), False, 'import torch\n'), ((2422, 2442), 'numpy.int64', 'np.int64', (['board_data'], {}), '(board_data)\n', (2430, 2442), True, 'import numpy as np\n'), ((2459, 2484), 'numpy.reshape', 'np.reshape', (['X', '(-1, 4, 4)'], {}), '(X, (-1, 4, 4))\n', (2469, 2484), True, 'import numpy as np\n'), ((2515, 2546), 'numpy.concatenate', 'np.concatenate', (['(X, XT)'], {'axis': '(1)'}), '((X, XT), axis=1)\n', (2529, 2546), True, 'import numpy as np\n'), ((2601, 2625), 'numpy.int64', 'np.int64', (['direction_data'], {}), '(direction_data)\n', (2609, 2625), True, 'import numpy as np\n'), ((2728, 2780), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'Y'], {'test_size': '(0.2)', 'shuffle': '(False)'}), '(X, Y, test_size=0.2, shuffle=False)\n', (2744, 2780), False, 'from sklearn.model_selection import train_test_split\n'), ((2791, 2817), 'torch.FloatTensor', 'torch.FloatTensor', (['X_train'], {}), '(X_train)\n', (2808, 2817), False, 'import torch\n'), ((2828, 2853), 'torch.FloatTensor', 'torch.FloatTensor', (['X_test'], {}), '(X_test)\n', (2845, 2853), False, 'import torch\n'), ((2865, 2890), 'torch.LongTensor', 'torch.LongTensor', (['Y_train'], {}), '(Y_train)\n', (2881, 2890), False, 'import torch\n'), ((2901, 2925), 'torch.LongTensor', 'torch.LongTensor', (['Y_test'], {}), '(Y_test)\n', (2917, 2925), False, 'import torch\n'), ((2945, 2993), 'torch.utils.data.TensorDataset', 'torch.utils.data.TensorDataset', (['X_train', 'Y_train'], {}), '(X_train, Y_train)\n', (2975, 2993), False, 'import torch\n'), ((3075, 3166), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', ([], {'dataset': 'train_dataset', 'batch_size': 'batch_size', 'shuffle': '(True)'}), '(dataset=train_dataset, batch_size=batch_size,\n shuffle=True)\n', (3102, 3166), False, 'import torch\n'), ((3506, 3546), 'pandas.read_csv', 'pd.read_csv', (['"""./drive/My Drive/DATA.csv"""'], {}), "('./drive/My Drive/DATA.csv')\n", (3517, 3546), True, 'import pandas as pd\n'), ((3652, 3681), 'torch.FloatTensor', 'torch.FloatTensor', (['board_data'], {}), '(board_data)\n', (3669, 3681), False, 'import torch\n'), ((3687, 3707), 'numpy.int64', 'np.int64', (['board_data'], {}), '(board_data)\n', (3695, 3707), True, 'import numpy as np\n'), ((3724, 3749), 'numpy.reshape', 'np.reshape', (['X', '(-1, 4, 4)'], {}), '(X, (-1, 4, 4))\n', (3734, 3749), True, 'import numpy as np\n'), ((3780, 3811), 'numpy.concatenate', 'np.concatenate', (['(X, XT)'], {'axis': '(1)'}), '((X, XT), axis=1)\n', (3794, 3811), True, 'import numpy as np\n'), ((3866, 3890), 'numpy.int64', 'np.int64', (['direction_data'], {}), '(direction_data)\n', (3874, 3890), True, 'import numpy as np\n'), ((490, 584), 'torch.nn.LSTM', 'nn.LSTM', ([], {'input_size': '(4)', 'hidden_size': '(128)', 'num_layers': '(4)', 'bidirectional': '(True)', 'batch_first': '(True)'}), '(input_size=4, hidden_size=128, num_layers=4, bidirectional=True,\n batch_first=True)\n', (497, 584), True, 'import torch.nn as nn\n'), ((685, 761), 'torch.nn.Conv2d', 'nn.Conv2d', ([], {'in_channels': '(1)', 'out_channels': '(1)', 'kernel_size': '(2)', 'stride': '(2)', 'padding': '(0)'}), '(in_channels=1, out_channels=1, kernel_size=2, stride=2, padding=0)\n', (694, 761), True, 'import torch.nn as nn\n'), ((864, 949), 'torch.nn.Conv2d', 'nn.Conv2d', ([], {'in_channels': '(1)', 'out_channels': '(1)', 'kernel_size': '(1, 4)', 'stride': '(1)', 'padding': '(0)'}), '(in_channels=1, out_channels=1, kernel_size=(1, 4), stride=1,\n padding=0)\n', (873, 949), True, 'import torch.nn as nn\n'), ((1048, 1133), 'torch.nn.Conv2d', 'nn.Conv2d', ([], {'in_channels': '(1)', 'out_channels': '(1)', 'kernel_size': '(4, 1)', 'stride': '(1)', 'padding': '(0)'}), '(in_channels=1, out_channels=1, kernel_size=(4, 1), stride=1,\n padding=0)\n', (1057, 1133), True, 'import torch.nn as nn\n'), ((1234, 1250), 'torch.nn.Linear', 'nn.Linear', (['(4)', '(64)'], {}), '(4, 64)\n', (1243, 1250), True, 'import torch.nn as nn\n'), ((1277, 1293), 'torch.nn.Linear', 'nn.Linear', (['(4)', '(32)'], {}), '(4, 32)\n', (1286, 1293), True, 'import torch.nn as nn\n'), ((1320, 1336), 'torch.nn.Linear', 'nn.Linear', (['(4)', '(32)'], {}), '(4, 32)\n', (1329, 1336), True, 'import torch.nn as nn\n'), ((1362, 1381), 'torch.nn.Linear', 'nn.Linear', (['(256)', '(128)'], {}), '(256, 128)\n', (1371, 1381), True, 'import torch.nn as nn\n'), ((1406, 1423), 'torch.nn.Linear', 'nn.Linear', (['(256)', '(4)'], {}), '(256, 4)\n', (1415, 1423), True, 'import torch.nn as nn\n'), ((1524, 1556), 'torch.unsqueeze', 'torch.unsqueeze', (['x[:, 0:4, :]', '(1)'], {}), '(x[:, 0:4, :], 1)\n', (1539, 1556), False, 'import torch\n'), ((2055, 2112), 'torch.cat', 'torch.cat', (['(CNN22toFC, CNN41toFC, CNN14toFC, LSTMtoFC)', '(1)'], {}), '((CNN22toFC, CNN41toFC, CNN14toFC, LSTMtoFC), 1)\n', (2064, 2112), False, 'import torch\n'), ((4250, 4281), 'torch.nn.functional.cross_entropy', 'F.cross_entropy', (['output', 'target'], {}), '(output, target)\n', (4265, 4281), True, 'import torch.nn.functional as F\n'), ((4100, 4114), 'torch.autograd.Variable', 'Variable', (['data'], {}), '(data)\n', (4108, 4114), False, 'from torch.autograd import Variable\n'), ((4123, 4139), 'torch.autograd.Variable', 'Variable', (['target'], {}), '(target)\n', (4131, 4139), False, 'from torch.autograd import Variable\n')]
#!/usr/bin/python3 from PIL import Image from numpy import complex, array from tqdm import tqdm import colorsys W=512 #W=142 def mandelbrot(x, y): def get_colors(i): color = 255 * array(colorsys.hsv_to_rgb(i / 255.0, 1.0, 0.5)) return tuple(color.astype(int)) c, cc = 0, complex(x, y) for i in range(1, 1000): if abs(c) > 2: return get_colors(i) c = c * c + cc return 0,0,0 if __name__ == "__main__": img = Image.new("RGB", (W, int(W / 2))) pixels = img.load() for x in tqdm(range(img.size[0])): for y in tqdm(range(img.size[1])): xx = (x - (0.75 * W)) / (W / 4) yy = (y - (W / 4)) / (W / 4) pixels[x, y] = mandelbrot(xx, yy) img.show() img.save("mandelbrot.jpg")
[ "numpy.complex", "colorsys.hsv_to_rgb" ]
[((300, 313), 'numpy.complex', 'complex', (['x', 'y'], {}), '(x, y)\n', (307, 313), False, 'from numpy import complex, array\n'), ((202, 242), 'colorsys.hsv_to_rgb', 'colorsys.hsv_to_rgb', (['(i / 255.0)', '(1.0)', '(0.5)'], {}), '(i / 255.0, 1.0, 0.5)\n', (221, 242), False, 'import colorsys\n')]
#!/usr/bin/env python # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # <NAME> # California Institute of Technology # (C) 2006-2010 All Rights Reserved # # {LicenseText} # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # standalone = True import unittestX as unittest import journal debug = journal.debug( "Broadened_E_Q_Kernel_TestCase" ) warning = journal.warning( "Broadened_E_Q_Kernel_TestCase" ) import mcni from mccomposite import mccompositebp from mccomponents import mccomponentsbp class TestCase(unittest.TestCase): def test(self): E_Q = "Q*Q/3." S_Q = "1" sigma_Q = "Q/2." Qmin = 0; Qmax = 10 absorption_coefficient = scattering_coefficient = 1. kernel = mccomponentsbp.create_Broadened_E_Q_Kernel( E_Q, S_Q, sigma_Q, Qmin, Qmax, absorption_coefficient, scattering_coefficient, ) ei = 500 # meV from mcni.utils import conversion vil = conversion.e2v(ei) vi = (0,0,vil) import numpy.linalg as nl import numpy as np for i in range(10): event = mcni.neutron( r = (0,0,0), v = vi, prob = 1, time = 0 ) kernel.scatter( event ); vf = np.array(event.state.velocity) diffv = vi - vf Q = conversion.v2k(nl.norm(diffv)) ef = conversion.v2e(nl.norm(vf)) E = ei - ef # print E, Q, event E1 = eval(E_Q) continue return pass # end of TestCase def main(): unittest.main() return if __name__ == "__main__": main() # version __id__ = "$Id: TestCase.py 696 2010-11-09 06:23:06Z linjiao $" # End of file
[ "journal.debug", "unittestX.main", "mcni.utils.conversion.e2v", "numpy.array", "mcni.neutron", "numpy.linalg.norm", "journal.warning", "mccomponents.mccomponentsbp.create_Broadened_E_Q_Kernel" ]
[((445, 491), 'journal.debug', 'journal.debug', (['"""Broadened_E_Q_Kernel_TestCase"""'], {}), "('Broadened_E_Q_Kernel_TestCase')\n", (458, 491), False, 'import journal\n'), ((504, 552), 'journal.warning', 'journal.warning', (['"""Broadened_E_Q_Kernel_TestCase"""'], {}), "('Broadened_E_Q_Kernel_TestCase')\n", (519, 552), False, 'import journal\n'), ((1769, 1784), 'unittestX.main', 'unittest.main', ([], {}), '()\n', (1782, 1784), True, 'import unittestX as unittest\n'), ((877, 1002), 'mccomponents.mccomponentsbp.create_Broadened_E_Q_Kernel', 'mccomponentsbp.create_Broadened_E_Q_Kernel', (['E_Q', 'S_Q', 'sigma_Q', 'Qmin', 'Qmax', 'absorption_coefficient', 'scattering_coefficient'], {}), '(E_Q, S_Q, sigma_Q, Qmin, Qmax,\n absorption_coefficient, scattering_coefficient)\n', (919, 1002), False, 'from mccomponents import mccomponentsbp\n'), ((1142, 1160), 'mcni.utils.conversion.e2v', 'conversion.e2v', (['ei'], {}), '(ei)\n', (1156, 1160), False, 'from mcni.utils import conversion\n'), ((1294, 1341), 'mcni.neutron', 'mcni.neutron', ([], {'r': '(0, 0, 0)', 'v': 'vi', 'prob': '(1)', 'time': '(0)'}), '(r=(0, 0, 0), v=vi, prob=1, time=0)\n', (1306, 1341), False, 'import mcni\n'), ((1438, 1468), 'numpy.array', 'np.array', (['event.state.velocity'], {}), '(event.state.velocity)\n', (1446, 1468), True, 'import numpy as np\n'), ((1528, 1542), 'numpy.linalg.norm', 'nl.norm', (['diffv'], {}), '(diffv)\n', (1535, 1542), True, 'import numpy.linalg as nl\n'), ((1576, 1587), 'numpy.linalg.norm', 'nl.norm', (['vf'], {}), '(vf)\n', (1583, 1587), True, 'import numpy.linalg as nl\n')]
# -*- coding: utf-8 -*- """ Created on Mon Sep 7 11:48:59 2020 @author: mazal """ """ ========================================= Support functions of pydicom (Not sourced) ========================================= Purpose: Create support functions for the pydicom project """ """ Test mode 1 | Basics testMode = True reportMode = False Test mode 2 | Function Report testMode = False reportMode = True Commisionning mode testMode = False reportMode = False """ testMode = False reportMode = False """ ========================================= Function 1: Aleatory Sampling ========================================= Purpose: Build an aleatory sample given a train dataset of Kaggle for competition and a sample size Raw code reference (see Tester.py): Test 5 """ def trainDatasetSampler(samplingSize,testMode,reportMode): # Set sampling size (% of the train population) samplingSize = 5 # Build a Sampling dataset | Phase 1: Determine: (1) the source path of the train data; (2) the location path of the sampling import os import pandas as pd path_source = 'Y:/Kaggle_OSIC/2-Data/train/' path_source_test = 'Y:/Kaggle_OSIC/2-Data/test/' path_destination = 'Y:/Kaggle_OSIC/4-Data (Sampling)/train/' path_destination_test = 'Y:/Kaggle_OSIC/4-Data (Sampling)/test/' path_destination_outcome = 'Y:/Kaggle_OSIC/4-Data (Sampling)/outcome/' # Build a Sampling dataset | Phase 2: Build dataset using the following features from train data: (1) ID; (2) # of DICOM files per ID (including percentage). ## Improvement: (3) # of other registers (not related to DICOM files) os.chdir(path_source) ID_list = os.listdir(path_source) ID_list_range = len(ID_list) DICOMFile_list = [] DICOMFileNumber_list = [] for i in range(0,ID_list_range): path_ID = path_source + ID_list[i] + '/' DICOMFile_list_unitary = os.listdir(path_ID) DICOMFile_list = DICOMFile_list + [DICOMFile_list_unitary] DICOMFileNumber_list_unitary = len(DICOMFile_list_unitary) DICOMFileNumber_list = DICOMFileNumber_list + [DICOMFileNumber_list_unitary] Population_Dictionary = {'ID':ID_list,'NumberDicomFiles':DICOMFileNumber_list,'DicomFIles':DICOMFile_list} Population_DataFrame = pd.DataFrame(data = Population_Dictionary) DICOMFilePercentage_list = [] TotalNumberDicomFiles = sum(Population_DataFrame.NumberDicomFiles) for j in range(0,ID_list_range): Percentage = Population_DataFrame['NumberDicomFiles'][j] / TotalNumberDicomFiles * 100 Percentage = round(Percentage,6) DICOMFilePercentage_list = DICOMFilePercentage_list + [Percentage] Population_Percentage_Dictionary = {'Percentage':DICOMFilePercentage_list} Population_Percentage_DataFrame = pd.DataFrame(data=Population_Percentage_Dictionary) Population_DataFrame = pd.concat([Population_DataFrame, Population_Percentage_DataFrame],axis=1, sort=False) filename_population = 'populationDataset.csv' path_population = path_destination_outcome Population_DataFrame.to_csv(path_population+filename_population) # Build a Sampling dataset | Phase 3: Get an aleatory grouping of IDs (just tags) import random Population_DataFrame_IndexToSample=[] Population_DataFrame_IDToSample=[] Population_DataFrame_PercentageToSample=[] samplingSizeGoal = 0 while (samplingSizeGoal <= samplingSize): randomNumberTermination = len(Population_DataFrame.ID) randomNumber = random.randrange(0,randomNumberTermination,1) if (randomNumber not in Population_DataFrame_IndexToSample): Population_DataFrame_IndexToSample = Population_DataFrame_IndexToSample + [randomNumber] ID_unitary = Population_DataFrame.ID[randomNumber] Population_DataFrame_IDToSample = Population_DataFrame_IDToSample + [ID_unitary] Percentage_unitary = Population_DataFrame.Percentage[randomNumber] Population_DataFrame_PercentageToSample = Population_DataFrame_PercentageToSample + [Percentage_unitary] samplingSize_unitary = Population_DataFrame.Percentage[randomNumber] samplingSizeGoal = samplingSizeGoal + samplingSize_unitary samplingDataset_Dictionary = {'Index':Population_DataFrame_IndexToSample,'ID':Population_DataFrame_IDToSample,'Percentage':Population_DataFrame_PercentageToSample} samplingDataset_DataFrame = pd.DataFrame(data=samplingDataset_Dictionary) filename_sampling = 'samplingDataset.csv' path_sampling = path_destination_outcome samplingDataset_DataFrame.to_csv(path_sampling+filename_sampling) # Build a Sampling dataset | Phase 3: Get train dataset (an aleatory grouping of IDs; tree-copy task) from distutils.dir_util import create_tree from distutils.dir_util import remove_tree from distutils.dir_util import copy_tree remove_tree(path_destination) create_tree(path_destination,[]) if testMode == True: print("=========================================") print("Building the Sampling Dataset given the Train Dataset of Kaggle for competition") print("=========================================") for k in Population_DataFrame_IDToSample: path_source_unitary = path_source + k + '/' path_destination_unitary = path_destination + k + '/' create_tree(path_destination_unitary,[]) copy_tree(path_source_unitary,path_destination_unitary) if testMode == True: print("ID tree copied: ",k) # Build a Sampling dataset | Phase 4: Get test dataset (tree-copy task) ## Assumption: The complete test dataset is copied. from distutils.dir_util import create_tree from distutils.dir_util import remove_tree from distutils.dir_util import copy_tree remove_tree(path_destination_test) create_tree(path_destination_test,[]) if testMode == True: print("=========================================") print("Building the Test Dataset given the Test Dataset of Kaggle for competition") print("=========================================") IDList_test = os.listdir(path_source_test) for l in IDList_test: path_source_unitary = path_source + l + '/' path_destination_unitary = path_destination_test + l + '/' create_tree(path_destination_unitary,[]) copy_tree(path_source_unitary,path_destination_unitary) if testMode == True: print("ID tree copied: ",l) if (testMode == False and reportMode == True): from datetime import date reportDate = date.today() print("=========================================") print("Function Report | Date:",reportDate.year,'/',reportDate.month,'/',reportDate.day,'/' ) print("=========================================") print("Function: trainDatasetSampler(samplingSize,testMode)") print("=========================================") print("(1) Inputs") print("=========================================") print("-Sampling Size :", samplingSize, "%") print("-Test Mode : False") print("=========================================") print("(2) Outputs") print("=========================================") print("-Type of sample: Aleatory based on IDs") print("-Train dataset percentage to sample (base): ", round(abs(samplingSize),6),"%") print("-Train dataset percentage to sample (adjustment): ", round(abs(samplingSizeGoal-samplingSize),6),"%") print("-Train dataset percentage to sample (fitted): ", round(samplingSizeGoal,6),"%") print("-Population of Train dataset (just information) available in file: ", filename_population) print("-Sample of Train dataset (just information) available in file: ", filename_sampling) print("=========================================") print("(2) Outcomes:") print("=========================================") print("Being the outcome expressed under the variable result, outcomes are as follows:") print("result[0] -> Dataframe for Population") print("result[1] -> Dataframe for Sample") print("result[2] -> Test Mode") print("result[3] -> Rerport Mode") print("=========================================") return Population_DataFrame, samplingDataset_DataFrame, testMode, reportMode if testMode == True: samplingSize = 5 resultFunction1 = trainDatasetSampler(samplingSize,testMode,reportMode) print("=========================================") print("Population dataset:") print("=========================================") print(resultFunction1[0]) print("=========================================") print("Population dataset:") print("=========================================") print(resultFunction1[1]) print("=========================================") print("Test result Function 1: Success") print("=========================================") """ ========================================= Function 2: Submission Builder ========================================= Purpose: Build a submission CSV file Raw code reference (see Tester.py): Test 8 """ def SubmissionBuilder(ProductType,filename,testMode): import os import pandas as pd # Set ProductType path_ProductType = 'Y:/Kaggle_OSIC/2-Data/' # Set productType and splitType if ProductType == 'population': path_ProductType = 'Y:/Kaggle_OSIC/2-Data/' if ProductType == 'prototype': path_ProductType = 'Y:/Kaggle_OSIC/3-Data (Prototype)/' if ProductType == 'sampling': path_ProductType = 'Y:/Kaggle_OSIC/4-Data (Sampling)/' # Set outcome path_outcome = path_ProductType + 'outcome/' # Get raw data as a DataFrame os.chdir(path_outcome) rawFile_DataFrame = pd.read_csv('submissionRawFile_2020_09_19.csv') # Get submission file template as a DataFrame os.chdir(path_ProductType) submissionFile_DataFrame = pd.read_csv('sample_submission.csv') # Get submission data as required in submission file submissionNumber_range = len(rawFile_DataFrame.index) IDcases_List = submissionFile_DataFrame.Patient_Week.copy() IDcases_List = IDcases_List[0:5] IDcases_List_range = len(IDcases_List) for i in range (0,IDcases_List_range): IDcases_List[i] = IDcases_List[i][:-4] # Get submission data as required in submission file | FVC FVCDataList = [] for k in range(0,submissionNumber_range): for j in IDcases_List: # Get datum in raw data IDlabel_rawFile = str(j)+str('_FVC') datum = rawFile_DataFrame[IDlabel_rawFile][k] datum = round(datum,0) # Set datum in submission file FVCDataList = FVCDataList + [datum] submissionFile_DataFrame['FVC'] = FVCDataList # Get submission data as required in submission file | Confidence CONDataList = [] for k in range(0,submissionNumber_range): for j in IDcases_List: # Get datum in raw data IDlabel_rawFile = str(j)+str('_CON') datum = rawFile_DataFrame[IDlabel_rawFile][k] datum = round(datum,0) # Set datum in submission file CONDataList = CONDataList + [datum] submissionFile_DataFrame['Confidence'] = CONDataList # Save file | Get directory path_destination = path_outcome+'submissions/' try: os.chdir(path_destination) GetCreation = True except FileNotFoundError: GetCreation = False if GetCreation == False: from distutils.dir_util import mkpath mkpath(path_destination) os.chdir(path_destination) submissionList = os.listdir(path_destination) number = len(submissionList) filename = 'submission_'+str(number+1)+'.csv' submissionFile_DataFrame.to_csv(filename, index=False) return submissionFile_DataFrame, filename, testMode if testMode == True: ProductType = 'population' filename = 'submissionRawFile_2020_09_19.csv' resultFunction2 = SubmissionBuilder(ProductType,filename,testMode) print("=========================================") print("Product Type:") print("=========================================") print(ProductType) print("=========================================") print("Submission File saved as:") print("=========================================") print(resultFunction2[1]) print("=========================================") print("Test result Function 2: Success") print("=========================================") """ ========================================= Function 3: Dataset builder (Stacking solution case) to process with ML models ========================================= Purpose: Build an input dataset to be processed with an stacking solution Raw code reference (see Tester.py): Test 15 """ def stacking_Dataset_Builder(ProductType, PydicomMode, reportMode, testMode): # Set Product Type and its corresponding path if ProductType == 'population': path_ProductType = 'Y:/Kaggle_OSIC/2-Data/' if ProductType == 'prototype': path_ProductType = 'Y:/Kaggle_OSIC/3-Data (Prototype)/' if ProductType == 'sampling': path_ProductType = 'Y:/Kaggle_OSIC/4-Data (Sampling)/' # Set working directory import os os.chdir(path_ProductType) # Get train dataset and test dataset import pandas as pd filename_trainDataset = 'train.csv' train_dataset = pd.read_csv(path_ProductType+filename_trainDataset) filename_testDataset = 'test.csv' test_dataset = pd.read_csv(path_ProductType+filename_testDataset) # Get submission dataset (template) import numpy as np path_resources = 'Y:/Kaggle_OSIC/3-Data (Prototype)/resources/' if (PydicomMode == False): filename_submissionDataset = 'submissionInputDataset.csv' else: filename_submissionDataset = 'submissionInputDataset_pydicom.csv' submission_dataset = pd.read_csv(path_resources+filename_submissionDataset) submission_dataset = submission_dataset.replace(np.nan,'iNaN') # Adjust train dataset | Phase 1: Get ID list of the test dataset IDList = list(test_dataset.Patient) # Adjust train dataset | Phase 2: Get submission instances from train dataset instancesPopulation = len(train_dataset.Patient) indexList = [] for i in IDList: for j in range(0,instancesPopulation): if i == train_dataset.Patient[j]: indexToInclude = train_dataset.index[j] indexList = indexList + [indexToInclude] # Adjust train dataset | Phase 3: Create an adjusted train dataset | a. Remove test instances from train dataset and reset index train_dataset_adjusted = train_dataset.drop(indexList) train_dataset_adjusted.reset_index # Adjust train dataset | Phase 3: Create an adjusted train dataset | b. Get Transferring data from train dataset instanceToTrasferList_index = [] for k in range(0,instancesPopulation): for l in IDList: if train_dataset.Patient[k] == l: instanceToTransfer_Index = train_dataset.index[k] instanceToTrasferList_index = instanceToTrasferList_index + [instanceToTransfer_Index] train_dataset_instancesToTransfer = train_dataset.take(instanceToTrasferList_index) train_dataset_instancesToTransfer.index train_dataset_instancesToTransfer = train_dataset_instancesToTransfer.reset_index() train_dataset_instancesToTransfer.drop(columns='index') # Adjust train dataset | Phase 3: Create an adjusted train dataset | c. Update the submission dataset with the transferring data in b. submission_dataset_range = len(submission_dataset.Patient) train_dataset_instancesToTransfer_range = len(train_dataset_instancesToTransfer.Patient) Patient_List = [] Week_List = [] FVC_List = [] Percent_List = [] Age_List = [] Sex_List = [] SmokingStatus_List = [] for m in range (0,submission_dataset_range): timesCopy = 0 if(submission_dataset.Patient[m] in IDList): referenceWeek = submission_dataset.Weeks[m] for n in range (0,train_dataset_instancesToTransfer_range): if(train_dataset_instancesToTransfer.Patient[n] == submission_dataset.Patient[m] and train_dataset_instancesToTransfer.Weeks[n] == referenceWeek): if (timesCopy == 0): submission_dataset.FVC[m] = train_dataset_instancesToTransfer.FVC[n] submission_dataset.Percent[m] = train_dataset_instancesToTransfer.Percent[n] submission_dataset.Age[m] = train_dataset_instancesToTransfer.Age[n] submission_dataset.Sex[m] = train_dataset_instancesToTransfer.Sex[n] submission_dataset.SmokingStatus[m] = train_dataset_instancesToTransfer.SmokingStatus[n] timesCopy = timesCopy + 1 else: # Additional instances to include Patient_List = Patient_List + [train_dataset_instancesToTransfer.Patient[n]] Week_List = Week_List + [train_dataset_instancesToTransfer.Weeks[n]] FVC_List = FVC_List + [train_dataset_instancesToTransfer.FVC[n]] Percent_List = Percent_List + [train_dataset_instancesToTransfer.Percent[n]] Age_List = Age_List + [train_dataset_instancesToTransfer.Age[n]] Sex_List = Sex_List + [train_dataset_instancesToTransfer.Sex[n]] SmokingStatus_List = SmokingStatus_List + [train_dataset_instancesToTransfer.SmokingStatus[n]] # Adjust train dataset | Phase 3: Create an adjusted train dataset | d. Add common values to submission dataset given those from the test dataset (Features: Age, Sex, SmokingStatus) submission_dataset_range = len(submission_dataset.Patient) for o in range(0,submission_dataset_range): if(submission_dataset.Patient[o] in IDList): for p in range(0,train_dataset_instancesToTransfer_range): if(submission_dataset.Patient[o] == train_dataset_instancesToTransfer.Patient[p]): submission_dataset.Age[o] = train_dataset_instancesToTransfer.Age[p] submission_dataset.Sex[o] = train_dataset_instancesToTransfer.Sex[p] submission_dataset.SmokingStatus[o] = train_dataset_instancesToTransfer.SmokingStatus[p] # Scenario to replace NaN values: Average FVC for a given Patient averageFVC = train_dataset_instancesToTransfer.FVC[train_dataset_instancesToTransfer.Patient == train_dataset_instancesToTransfer.Patient[p]].mean() submission_dataset.FVC[o] = averageFVC # Adjust train dataset | Phase 4: Create an adjusted train dataset | e. Concatenate the submission dataset (and additional instance) and the adjusted train dataset additionalDictionary = {submission_dataset.columns[0]:Patient_List, submission_dataset.columns[1]:Week_List, submission_dataset.columns[2]:FVC_List, submission_dataset.columns[3]:Percent_List, submission_dataset.columns[4]:Age_List, submission_dataset.columns[5]:Sex_List, submission_dataset.columns[6]:SmokingStatus_List} additional_dataset = pd.DataFrame(data=additionalDictionary) frames = [train_dataset_adjusted,submission_dataset,additional_dataset] train_dataset_adjusted = pd.concat(frames) train_dataset_adjusted = train_dataset_adjusted.reset_index() train_dataset_adjusted = train_dataset_adjusted.drop(columns='index') # Adjust train dataset with pydicom train dataset) | Phase 1: Get pydicom train dataset if(PydicomMode == True): filename_pydicom = 'train_pydicom.csv' path_ProductType_pydicom = path_ProductType + 'outcome/' train_dataset_pydicom = pd.read_csv(path_ProductType_pydicom + filename_pydicom) # Adjust train dataset with pydicom train dataset) | Phase 2: Include values from train_adjusted_pydicom.py into adjusted train dataset if(PydicomMode == True): instancesToInclude_List = list(train_dataset_pydicom.Patient) InstanceToInclude_Patient = i newIndex = len(train_dataset_adjusted.Patient) for i in instancesToInclude_List: # Get instance to transfer InstanceToInclude_Patient = i InstanceToInclude_Week = list(train_dataset_pydicom[train_dataset_pydicom.Patient == i].Weeks)[0] InstanceToInclude_indexType1_Exhalation = list(train_dataset_pydicom[train_dataset_pydicom.Patient == i].indexType1_Exhalation)[0] InstanceToInclude_indexType1_Inhalation = list(train_dataset_pydicom[train_dataset_pydicom.Patient == i].indexType1_Inhalation)[0] InstanceToInclude_ImageType = list(train_dataset_pydicom[train_dataset_pydicom.Patient == i].ImageType)[0] # Put instance into train_dataset_adjusted DataFrame if (0 in list(train_dataset_adjusted[train_dataset_adjusted.Patient == i].Weeks)): # Get index indexToComplete = list(train_dataset_adjusted[train_dataset_adjusted.Weeks == 0].Patient[train_dataset_adjusted.Patient == i].index) # Complete instance train_dataset_adjusted.indexType1_Exhalation[indexToComplete] = InstanceToInclude_indexType1_Exhalation train_dataset_adjusted.indexType1_Inhalation[indexToComplete] = InstanceToInclude_indexType1_Inhalation train_dataset_adjusted.ImageType[indexToComplete] = str(InstanceToInclude_ImageType) else: # Add new instance ## Get repeatable instances repeatableInstance1 = list(train_dataset_adjusted[train_dataset_adjusted.Patient == i].FVC)[0] repeatableInstance2 = list(train_dataset_adjusted[train_dataset_adjusted.Patient == i].Percent)[0] repeatableInstance3 = list(train_dataset_adjusted[train_dataset_adjusted.Patient == i].Age)[0] repeatableInstance4 = list(train_dataset_adjusted[train_dataset_adjusted.Patient == i].Sex)[0] repeatableInstance5 = list(train_dataset_adjusted[train_dataset_adjusted.Patient == i].SmokingStatus)[0] ## Get Dictionary DictionaryToInclude = {} DictionaryToInclude['Patient'] = InstanceToInclude_Patient DictionaryToInclude['Weeks'] = InstanceToInclude_Week DictionaryToInclude['FVC'] = repeatableInstance1 DictionaryToInclude['Percent'] = repeatableInstance2 DictionaryToInclude['Age'] = repeatableInstance3 DictionaryToInclude['Sex'] = repeatableInstance4 DictionaryToInclude['SmokingStatus'] = repeatableInstance5 DictionaryToInclude['indexType1_Exhalation'] = InstanceToInclude_indexType1_Exhalation DictionaryToInclude['indexType1_Inhalation'] = InstanceToInclude_indexType1_Inhalation DictionaryToInclude['ImageType'] = str(InstanceToInclude_ImageType) ## Get DataFrame DataFrameToInclude = pd.DataFrame(data = DictionaryToInclude, index=[newIndex]) newIndex = newIndex + 1 ## Concatenate DataFrame train_dataset_adjusted = pd.concat([train_dataset_adjusted, DataFrameToInclude]) # nan filling train_dataset_adjusted = train_dataset_adjusted.replace('iNaN',np.nan) # Specifying dtype train_dataset_adjusted.astype({'Patient': 'O'}).dtypes train_dataset_adjusted.astype({'Weeks': 'float64'}).dtypes train_dataset_adjusted.astype({'Percent': 'float64'}).dtypes train_dataset_adjusted.astype({'Age': 'float64'}).dtypes train_dataset_adjusted.astype({'Sex': 'O'}).dtypes train_dataset_adjusted.astype({'SmokingStatus': 'O'}).dtypes train_dataset_adjusted.astype({'FVC': 'float64'}).dtypes if(PydicomMode == True): train_dataset_adjusted.astype({'indexType1_Exhalation': 'float64'}).dtypes train_dataset_adjusted.astype({'indexType1_Inhalation': 'float64'}).dtypes train_dataset_adjusted.astype({'ImageType': 'O'}).dtypes # Get CSV file path_output = path_ProductType +'outcome/' if(PydicomMode == False): filename_output = 'train_adjusted.csv' else: filename_output = 'train_adjusted_pydicom.csv' train_dataset_adjusted.to_csv(path_output+filename_output) # Function Result resultFunction = train_dataset_adjusted,path_output,filename_output # Report Mode if reportMode == True: print("=========================================") print("Function Report") print("=========================================") print("DataFrame") print("=========================================") print(resultFunction[0]) print("=========================================") print("Product Type: ", ProductType) print("=========================================") print("Pydicom Mode: ", PydicomMode) print("=========================================") print("Location of Input File:", resultFunction[1]) print("=========================================") print("Input File saved as:", resultFunction[2]) print("=========================================") print("Data type of the dataset") print("=========================================") print(resultFunction[0].dtypes) print("=========================================") print("Test result Function 3: Success") print("=========================================") return resultFunction if testMode == True: ProductType = 'prototype' PydicomMode = True reportMode = False resultFunction3 = stacking_Dataset_Builder(ProductType, PydicomMode, reportMode, testMode) print("=========================================") print("Function Report") print("=========================================") print("DataFrame") print("=========================================") print(resultFunction3[0]) print("=========================================") print("=========================================") print("Product Type: ", ProductType) print("=========================================") print("Pydicom Mode: ", PydicomMode) print("=========================================") print("Location of Input File:", resultFunction3[1]) print("=========================================") print("Input File saved as:", resultFunction3[2]) print("=========================================") print("Data type of the dataset") print("=========================================") print(resultFunction3[0].dtypes) print("=========================================") print("Test result Function 3: Success") print("=========================================") """ ========================================= Function 4: Submission dataset builder (Stacking solution case) after ML outcome ========================================= Purpose: Build a submission CSV file (Stacking solution case) Raw code reference (see Tester.py): Test 17 About the Shape Parameter: It amounts to c = 0.12607421874999922 for every instance in the oject of concern. c value has been computed deeming the following data fitting scope: (1) Data: FVC predictions; (2) Probability density function as follows (staistical function in scipy renowend as scipy.stats.loglaplace): loglaplace.pdf(x, c, loc=0, scale=1). """ def Stacking_Submission_Dataset_Builder(ProductType,shapeParameter_DataFrame,pydicomMode,testMode): # Set Product Type and its corresponding path if ProductType == 'population': path_ProductType = 'Y:/Kaggle_OSIC/2-Data/' if ProductType == 'prototype': path_ProductType = 'Y:/Kaggle_OSIC/3-Data (Prototype)/' if ProductType == 'sampling': path_ProductType = 'Y:/Kaggle_OSIC/4-Data (Sampling)/' # Set working directory import os os.chdir(path_ProductType + 'outcome/') # Get result data and test dataset import pandas as pd if(pydicomMode == True): filename_resultDataset = 'result_pydicom.csv' else: filename_resultDataset = 'result.csv' result_dataset = pd.read_csv(path_ProductType+'outcome/'+filename_resultDataset) filename_testDataset = 'test.csv' test_dataset = pd.read_csv(path_ProductType+filename_testDataset) # Get submission instances | Phase 1: Index IDList = list(test_dataset.Patient) IDList_index_dictionary = {} for i in IDList: itemToInclude = result_dataset.Patient[result_dataset.Patient==i].index IDList_index_dictionary[i] = itemToInclude # Get submission instances | Phase 2: Extract submission instances from result dataset IDList_index = [] IDList_columns = ['Patient', 'Weeks', 'Random Forest', 'Lasso', 'Gradient Boosting', 'Stacking Regressor'] for j in IDList: IDList_index = IDList_index + list(IDList_index_dictionary[j]) submission_dataset = result_dataset.loc[IDList_index] # Get submission instances | Phase 3: Extract duplicated instances submission_dataset = submission_dataset.drop_duplicates(subset=['Patient','Weeks']) # Get submission instances | Phase 4: Sort submission instances by Weeks (ascending) and reset index submission_dataset = submission_dataset.sort_values(by=['Weeks','Patient']) submission_dataset = submission_dataset.reset_index() submission_dataset = submission_dataset.drop(columns=['Unnamed: 0','index']) # Get confidence measure | Phase 1: Get shape Parameter DataFrame by default ## When shapeParameter_DataFrame==[], parameter c = 0.126074 is assigned by default per model and ID if (shapeParameter_DataFrame == []): shapeParameter_dictionary = {} shapeParameter = 0.126074 MLModelList = IDList_columns[2:] for l in MLModelList: keyShapeParameter = 'c Parameter_'+l shapeParameter_dictionary[keyShapeParameter] = [shapeParameter,shapeParameter,shapeParameter,shapeParameter,shapeParameter] shapeParameter_DataFrame = pd.DataFrame(data = shapeParameter_dictionary, index = IDList) # Get confidence measure | Phase 2: Get standard-deviation-clipped per instance ## Metric - Part 1: standard_deviation_clipped = max(standard_deviation, 70) ## Build a DataFrame with standard-deviation-clipped values given an ID and a ML Model: standardDeviationClipped_DataFrame standardDeviationClipped_DataFrame = shapeParameter_DataFrame.copy() columnLabels = list(standardDeviationClipped_DataFrame.columns) columnLabels_SDC_dictionary = {} for i in columnLabels: columnLabels_item ='SD_Clipped'+i[11:] columnLabels_SDC_dictionary[i]=columnLabels_item standardDeviationClipped_DataFrame = standardDeviationClipped_DataFrame.rename(columns=columnLabels_SDC_dictionary) import numpy as np standardDeviationClipped_DataFrame = standardDeviationClipped_DataFrame.replace(3,np.nan) ID_List = list(standardDeviationClipped_DataFrame.index) SDModel_List = list(standardDeviationClipped_DataFrame.columns) CParameter_List = list(shapeParameter_DataFrame.columns) numy = 0 from scipy.stats import loglaplace for j in ID_List: for k in SDModel_List: itemToInclude = CParameter_List[numy] c = shapeParameter_DataFrame[itemToInclude][j] sd_LL = loglaplace.std(c, loc=0, scale=100) standardDeviationClipped_DataFrame[k][j] = max(70,sd_LL) # j: index is ID | k: SD_Clipped_(ML Model) numy = numy + 1 numy = 0 # Get confidence measure | Phase 3: Get metric axe per model: |FVC_true - FVC_predicted| ## Metric - Part 1: |FVC_true - FVC_pred| if(pydicomMode == True): variableNumber = 10 else: variableNumber = 7 MLModelList = list(submission_dataset.columns[variableNumber:]) metric_dictionary = {} for j in MLModelList: metric_differential = abs(submission_dataset.FVC - submission_dataset[j]) metric_differential = list(metric_differential) keyToInclude = 'metric_'+j metric_dictionary[keyToInclude] = metric_differential metric_DataFrame = pd.DataFrame(data=metric_dictionary) # Get confidence measure | Phase 4: Get metric axe per model: min(|FVC_true - FVC_predicted|, 1000) ## metric per instance ## Metric - Part 2: min(|FVC_true - FVC_pred|,1000) metricLabels = list(metric_DataFrame.columns) instancesNumber = len(submission_dataset.index) for i in metricLabels: j = 0 while (j<instancesNumber): metric_DataFrame[i][j] = min(metric_DataFrame[i][j],1000) j = j+1 submission_dataset = submission_dataset.join(metric_DataFrame) # Get confidence measure | Phase 5: Get metric axe per model: (-1 * differential * 2^0.5 / SDC ) - ln(2^0.5 * SCD) ## metric per instance ## differential = min(|FVC_true - FVC_predicted|, 1000) ## SDC: Standard Deviation Clipped ## Metric - Part 2: min(|FVC_true - FVC_pred|,1000) IDList = list(test_dataset.Patient) SDModel_List = list(standardDeviationClipped_DataFrame.columns) SDModel_index_List = list(standardDeviationClipped_DataFrame.index) metric_lists = list(metric_DataFrame.columns) metric_index_lists = list(metric_DataFrame.index) submission_dataset_index_List = list(submission_dataset.index) instancesNumber = len(submission_dataset_index_List) indexPerID_dictionary = {} ### Step 1: Get index per ID to compute for i in IDList: listToInclude = list(submission_dataset.Patient[submission_dataset.Patient == i].index) indexPerID_dictionary[i] = listToInclude indexPerID_DataFrame = pd.DataFrame(data=indexPerID_dictionary) ### Step 3: Compute metric import math from math import log1p for k in IDList: for i in metric_lists: for j in list(indexPerID_DataFrame[k]): differential = submission_dataset[i][j] SDC_Label = 'SD_Clipped_' + i[7:] SDC = standardDeviationClipped_DataFrame[SDC_Label][k] metric_part1 = -1* 2**0.5 * differential / SDC metric_part2 = -1 * math.log1p(2**0.5 * SDC) metric = metric_part1 + metric_part2 submission_dataset[i][j] = metric # Result function specification resultFunction = submission_dataset,shapeParameter_DataFrame,standardDeviationClipped_DataFrame # Get submission files | Phase 1: Get submission file template filename = 'sample_submission.csv' submissionFile = pd.read_csv(path_ProductType+filename) ## Get submission files | Phase 2: Create directory try: path_output = path_ProductType + 'submission/' os.chdir(path_output) except FileNotFoundError: import distutils.ccompiler path_output = path_ProductType + 'submission/' distutils.dir_util.mkpath(path_output) ## Get submission files | Phase 3: Get correlative files_list = os.listdir(path_output) try: maxNumber = max(files_list) maxNumber = maxNumber[:-4] maxNumber = int(maxNumber) nextNumber = maxNumber+1 except ValueError: nextNumber = 0 ## Get submission files | Phase 4: Get models to include and their corresponding metrics ModelToInclude = IDList_columns[2:] ## Get submission files | Phase 5: Build Files for i in ModelToInclude: filename = 'sample_submission.csv' submissionFile = pd.read_csv(path_ProductType+filename) submissionFile_columns = list(submissionFile.columns) fvc_array = np.array(submission_dataset[i]) confidence_array = np.array(submission_dataset['metric_'+i]) submissionFile['FVC'] = fvc_array submissionFile['Confidence'] = confidence_array filename_output = str(nextNumber)+'.csv' path_output = path_ProductType +'submission/' submissionFile.to_csv(path_output+filename_output,columns=submissionFile_columns,index=False) nextNumber = nextNumber + 1 return resultFunction if testMode == True: # Set Product type ProductType = 'prototype' # ShapeParameter_Dataframe example = False if (example == True): import pandas as pd shapeParameter_IDList = ['ID00419637202311204720264','ID00421637202311550012437','ID00422637202311677017371','ID00423637202312137826377','ID00426637202313170790466'] c_List1 = [3,3,3,3,3] c_List2 = [3,3,3,3,3] c_List3 = [3,3,3,3,3] c_List4 = [3,3,3,3,3] shapeParameter_dictionary = {'Random Forest':c_List1, 'Lasso':c_List2, 'Gradient Boosting':c_List3, 'Stacking Regressor':c_List4} shapeParameter_DataFrame = pd.DataFrame(data = shapeParameter_dictionary, index = shapeParameter_IDList) else: shapeParameter_DataFrame = [] # Set Pydicom mode pydicomMode = True resultFunction4 = Stacking_Submission_Dataset_Builder(ProductType,shapeParameter_DataFrame,pydicomMode,testMode) print("=========================================") print("Shape Parameter - Laplace Log Likelihood:") print("=========================================") print(resultFunction4[1]) print("Standard Deviation Clipped - Laplace Log Likelihood:") print("=========================================") print(resultFunction4[2]) print("=========================================") print("Test result Function 4: Success") print("=========================================") """ ========================================= Function 5: Get parameters given a must-usage of a log-laplace distribution (i.e. Laplace Log Likelihood) ========================================= Purpose: Get shape parameter visualization for loglaplace Raw code reference (see Tester.py): Test 17 """ def shapeParameter_visualizer(ProductType,testMode): import numpy as np from scipy.stats import loglaplace import matplotlib.pyplot as plt fig, ax = plt.subplots(4, 5, sharex=False, sharey=False, figsize=(32, 24)) ## Get IDs to test import os import pandas as pd ## Set Product Type and its corresponding path if ProductType == 'population': path_ProductType = 'Y:/Kaggle_OSIC/2-Data/' if ProductType == 'prototype': path_ProductType = 'Y:/Kaggle_OSIC/3-Data (Prototype)/' if ProductType == 'sampling': path_ProductType = 'Y:/Kaggle_OSIC/4-Data (Sampling)/' ## Get probabilities from predicted values grouping by ID and Model path = path_ProductType + 'outcome/' filename = 'result.csv' y_pred = pd.read_csv(path+filename) ## Get IDs to test path = path_ProductType filename = 'test.csv' test_dataset = pd.read_csv(path+filename) ID_List = list(test_dataset.Patient) ## Get models model_List = ['Random Forest', 'Lasso', 'Gradient Boosting', 'Stacking Regressor'] ## Grouping task k = 0 l = 0 for i in ID_List: k = 0 for j in model_List: # Data Fit task #r = y_pred[y_pred.Patient==i][j]/sum(y_pred[y_pred.Patient==i][j]) r = y_pred[y_pred.Patient==i][j] r = np.array(r) c1, loc1, scale1 = loglaplace.fit(r,floc=0,fscale=1) c = c1 # # Calculate a few first moments # mean, var, skew, kurt = loglaplace.stats(c, moments='mvsk') # Display the probability density function (pdf): x = np.linspace(loglaplace.ppf(0.01, c), loglaplace.ppf(0.99, c), num=100) ax[k,l].plot(x, loglaplace.pdf(x, c),'r-', lw=5, alpha=0.6, label='loglaplace pdf') # Freeze the distribution and display the frozen pdf: rv = loglaplace(c) ax[k,l].plot(x, rv.pdf(x), 'k-', lw=2, label='frozen pdf') # Generate random numbers: r = loglaplace.rvs(c1, loc=0, scale=1, size=1000) # And compare the histogram: #ax[k,l].hist(r, density=True, histtype='stepfilled', alpha=0.2) ax[k,l].legend(loc='best', frameon=False) # Set limits #ax[k,l].set_xlim(0,0.1) #ax[k,l].set_ylim(0,4) ax[k,l].set_xlabel('x') ax[k,l].set_ylabel('f(x,c)') # Check Accuracy vals = loglaplace.ppf([0.001, 0.5, 0.999], c) accuracy = np.allclose([0.001, 0.5, 0.999], loglaplace.cdf(vals, c)) # Returns True if two arrays are element-wise equal within a tolerance. if(accuracy == True): accuracy = 'Equal case' else: accuracy = 'Unequal case' # Set title title = str('Probability density function for loglaplace'+'\n'+i + '\n' + j + ' | Accuracy:'+accuracy) ax[k,l].set_title(title) k = k + 1 l = l + 1 plt.tight_layout() plt.show() resultFunction = c return resultFunction if testMode == True: # Set Product type ProductType = 'prototype' # ShapeParameter_Dataframe resultFunction5 = shapeParameter_visualizer(ProductType, testMode = True) print("=========================================") print("Shape Parameter - Laplace Log Likelihood:") print("=========================================") print(resultFunction5) print("=========================================") print("Test result Function 4: Success") print("=========================================") # """ # ========================================= # Function : Dataset builder 2 (Stacking solution case) to process with ML models # ========================================= # Purpose: Build an input dataset to be processed with an stacking solution but including Pydicom image-processing solution # Raw code reference (see Tester.py): 15 # """ # def stacking_Dataset_Builder_PydicomSolution(productType, testMode): # # Set Product Type and its corresponding path # if ProductType == 'population': # path_ProductType = 'Y:/Kaggle_OSIC/2-Data/' # if ProductType == 'prototype': # path_ProductType = 'Y:/Kaggle_OSIC/3-Data (Prototype)/' # if ProductType == 'sampling': # path_ProductType = 'Y:/Kaggle_OSIC/4-Data (Sampling)/'
[ "distutils.dir_util.mkpath", "distutils.dir_util.create_tree", "distutils.dir_util.copy_tree", "math.log1p", "pandas.read_csv", "numpy.array", "scipy.stats.loglaplace", "os.listdir", "scipy.stats.loglaplace.ppf", "pandas.DataFrame", "random.randrange", "scipy.stats.loglaplace.std", "scipy.stats.loglaplace.cdf", "datetime.date.today", "scipy.stats.loglaplace.pdf", "matplotlib.pyplot.show", "scipy.stats.loglaplace.fit", "os.chdir", "scipy.stats.loglaplace.rvs", "distutils.dir_util.remove_tree", "matplotlib.pyplot.tight_layout", "pandas.concat", "matplotlib.pyplot.subplots" ]
[((1713, 1734), 'os.chdir', 'os.chdir', (['path_source'], {}), '(path_source)\n', (1721, 1734), False, 'import os\n'), ((1756, 1779), 'os.listdir', 'os.listdir', (['path_source'], {}), '(path_source)\n', (1766, 1779), False, 'import os\n'), ((2403, 2443), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'Population_Dictionary'}), '(data=Population_Dictionary)\n', (2415, 2443), True, 'import pandas as pd\n'), ((2942, 2993), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'Population_Percentage_Dictionary'}), '(data=Population_Percentage_Dictionary)\n', (2954, 2993), True, 'import pandas as pd\n'), ((3028, 3118), 'pandas.concat', 'pd.concat', (['[Population_DataFrame, Population_Percentage_DataFrame]'], {'axis': '(1)', 'sort': '(False)'}), '([Population_DataFrame, Population_Percentage_DataFrame], axis=1,\n sort=False)\n', (3037, 3118), True, 'import pandas as pd\n'), ((4653, 4698), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'samplingDataset_Dictionary'}), '(data=samplingDataset_Dictionary)\n', (4665, 4698), True, 'import pandas as pd\n'), ((5141, 5170), 'distutils.dir_util.remove_tree', 'remove_tree', (['path_destination'], {}), '(path_destination)\n', (5152, 5170), False, 'from distutils.dir_util import remove_tree\n'), ((5176, 5209), 'distutils.dir_util.create_tree', 'create_tree', (['path_destination', '[]'], {}), '(path_destination, [])\n', (5187, 5209), False, 'from distutils.dir_util import create_tree\n'), ((6107, 6141), 'distutils.dir_util.remove_tree', 'remove_tree', (['path_destination_test'], {}), '(path_destination_test)\n', (6118, 6141), False, 'from distutils.dir_util import remove_tree\n'), ((6147, 6185), 'distutils.dir_util.create_tree', 'create_tree', (['path_destination_test', '[]'], {}), '(path_destination_test, [])\n', (6158, 6185), False, 'from distutils.dir_util import create_tree\n'), ((6455, 6483), 'os.listdir', 'os.listdir', (['path_source_test'], {}), '(path_source_test)\n', (6465, 6483), False, 'import os\n'), ((10323, 10345), 'os.chdir', 'os.chdir', (['path_outcome'], {}), '(path_outcome)\n', (10331, 10345), False, 'import os\n'), ((10371, 10418), 'pandas.read_csv', 'pd.read_csv', (['"""submissionRawFile_2020_09_19.csv"""'], {}), "('submissionRawFile_2020_09_19.csv')\n", (10382, 10418), True, 'import pandas as pd\n'), ((10481, 10507), 'os.chdir', 'os.chdir', (['path_ProductType'], {}), '(path_ProductType)\n', (10489, 10507), False, 'import os\n'), ((10540, 10576), 'pandas.read_csv', 'pd.read_csv', (['"""sample_submission.csv"""'], {}), "('sample_submission.csv')\n", (10551, 10576), True, 'import pandas as pd\n'), ((12487, 12515), 'os.listdir', 'os.listdir', (['path_destination'], {}), '(path_destination)\n', (12497, 12515), False, 'import os\n'), ((14228, 14254), 'os.chdir', 'os.chdir', (['path_ProductType'], {}), '(path_ProductType)\n', (14236, 14254), False, 'import os\n'), ((14390, 14443), 'pandas.read_csv', 'pd.read_csv', (['(path_ProductType + filename_trainDataset)'], {}), '(path_ProductType + filename_trainDataset)\n', (14401, 14443), True, 'import pandas as pd\n'), ((14501, 14553), 'pandas.read_csv', 'pd.read_csv', (['(path_ProductType + filename_testDataset)'], {}), '(path_ProductType + filename_testDataset)\n', (14512, 14553), True, 'import pandas as pd\n'), ((14914, 14970), 'pandas.read_csv', 'pd.read_csv', (['(path_resources + filename_submissionDataset)'], {}), '(path_resources + filename_submissionDataset)\n', (14925, 14970), True, 'import pandas as pd\n'), ((20686, 20725), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'additionalDictionary'}), '(data=additionalDictionary)\n', (20698, 20725), True, 'import pandas as pd\n'), ((20845, 20862), 'pandas.concat', 'pd.concat', (['frames'], {}), '(frames)\n', (20854, 20862), True, 'import pandas as pd\n'), ((30038, 30077), 'os.chdir', 'os.chdir', (["(path_ProductType + 'outcome/')"], {}), "(path_ProductType + 'outcome/')\n", (30046, 30077), False, 'import os\n'), ((30320, 30387), 'pandas.read_csv', 'pd.read_csv', (["(path_ProductType + 'outcome/' + filename_resultDataset)"], {}), "(path_ProductType + 'outcome/' + filename_resultDataset)\n", (30331, 30387), True, 'import pandas as pd\n'), ((30443, 30495), 'pandas.read_csv', 'pd.read_csv', (['(path_ProductType + filename_testDataset)'], {}), '(path_ProductType + filename_testDataset)\n', (30454, 30495), True, 'import pandas as pd\n'), ((36230, 36270), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'indexPerID_dictionary'}), '(data=indexPerID_dictionary)\n', (36242, 36270), True, 'import pandas as pd\n'), ((37262, 37302), 'pandas.read_csv', 'pd.read_csv', (['(path_ProductType + filename)'], {}), '(path_ProductType + filename)\n', (37273, 37302), True, 'import pandas as pd\n'), ((37716, 37739), 'os.listdir', 'os.listdir', (['path_output'], {}), '(path_output)\n', (37726, 37739), False, 'import os\n'), ((40874, 40938), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(4)', '(5)'], {'sharex': '(False)', 'sharey': '(False)', 'figsize': '(32, 24)'}), '(4, 5, sharex=False, sharey=False, figsize=(32, 24))\n', (40886, 40938), True, 'import matplotlib.pyplot as plt\n'), ((41538, 41566), 'pandas.read_csv', 'pd.read_csv', (['(path + filename)'], {}), '(path + filename)\n', (41549, 41566), True, 'import pandas as pd\n'), ((41667, 41695), 'pandas.read_csv', 'pd.read_csv', (['(path + filename)'], {}), '(path + filename)\n', (41678, 41695), True, 'import pandas as pd\n'), ((44060, 44078), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (44076, 44078), True, 'import matplotlib.pyplot as plt\n'), ((44084, 44094), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (44092, 44094), True, 'import matplotlib.pyplot as plt\n'), ((2004, 2023), 'os.listdir', 'os.listdir', (['path_ID'], {}), '(path_ID)\n', (2014, 2023), False, 'import os\n'), ((3711, 3758), 'random.randrange', 'random.randrange', (['(0)', 'randomNumberTermination', '(1)'], {}), '(0, randomNumberTermination, 1)\n', (3727, 3758), False, 'import random\n'), ((5644, 5685), 'distutils.dir_util.create_tree', 'create_tree', (['path_destination_unitary', '[]'], {}), '(path_destination_unitary, [])\n', (5655, 5685), False, 'from distutils.dir_util import create_tree\n'), ((5694, 5750), 'distutils.dir_util.copy_tree', 'copy_tree', (['path_source_unitary', 'path_destination_unitary'], {}), '(path_source_unitary, path_destination_unitary)\n', (5703, 5750), False, 'from distutils.dir_util import copy_tree\n'), ((6654, 6695), 'distutils.dir_util.create_tree', 'create_tree', (['path_destination_unitary', '[]'], {}), '(path_destination_unitary, [])\n', (6665, 6695), False, 'from distutils.dir_util import create_tree\n'), ((6704, 6760), 'distutils.dir_util.copy_tree', 'copy_tree', (['path_source_unitary', 'path_destination_unitary'], {}), '(path_source_unitary, path_destination_unitary)\n', (6713, 6760), False, 'from distutils.dir_util import copy_tree\n'), ((6933, 6945), 'datetime.date.today', 'date.today', ([], {}), '()\n', (6943, 6945), False, 'from datetime import date\n'), ((12169, 12195), 'os.chdir', 'os.chdir', (['path_destination'], {}), '(path_destination)\n', (12177, 12195), False, 'import os\n'), ((12394, 12418), 'distutils.dir_util.mkpath', 'mkpath', (['path_destination'], {}), '(path_destination)\n', (12400, 12418), False, 'from distutils.dir_util import mkpath\n'), ((12428, 12454), 'os.chdir', 'os.chdir', (['path_destination'], {}), '(path_destination)\n', (12436, 12454), False, 'import os\n'), ((21287, 21343), 'pandas.read_csv', 'pd.read_csv', (['(path_ProductType_pydicom + filename_pydicom)'], {}), '(path_ProductType_pydicom + filename_pydicom)\n', (21298, 21343), True, 'import pandas as pd\n'), ((32296, 32354), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'shapeParameter_dictionary', 'index': 'IDList'}), '(data=shapeParameter_dictionary, index=IDList)\n', (32308, 32354), True, 'import pandas as pd\n'), ((34569, 34605), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'metric_dictionary'}), '(data=metric_dictionary)\n', (34581, 34605), True, 'import pandas as pd\n'), ((37439, 37460), 'os.chdir', 'os.chdir', (['path_output'], {}), '(path_output)\n', (37447, 37460), False, 'import os\n'), ((38249, 38289), 'pandas.read_csv', 'pd.read_csv', (['(path_ProductType + filename)'], {}), '(path_ProductType + filename)\n', (38260, 38289), True, 'import pandas as pd\n'), ((38382, 38413), 'numpy.array', 'np.array', (['submission_dataset[i]'], {}), '(submission_dataset[i])\n', (38390, 38413), True, 'import numpy as np\n'), ((38442, 38485), 'numpy.array', 'np.array', (["submission_dataset['metric_' + i]"], {}), "(submission_dataset['metric_' + i])\n", (38450, 38485), True, 'import numpy as np\n'), ((39557, 39630), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'shapeParameter_dictionary', 'index': 'shapeParameter_IDList'}), '(data=shapeParameter_dictionary, index=shapeParameter_IDList)\n', (39569, 39630), True, 'import pandas as pd\n'), ((33697, 33732), 'scipy.stats.loglaplace.std', 'loglaplace.std', (['c'], {'loc': '(0)', 'scale': '(100)'}), '(c, loc=0, scale=100)\n', (33711, 33732), False, 'from scipy.stats import loglaplace\n'), ((42182, 42193), 'numpy.array', 'np.array', (['r'], {}), '(r)\n', (42190, 42193), True, 'import numpy as np\n'), ((42240, 42275), 'scipy.stats.loglaplace.fit', 'loglaplace.fit', (['r'], {'floc': '(0)', 'fscale': '(1)'}), '(r, floc=0, fscale=1)\n', (42254, 42275), False, 'from scipy.stats import loglaplace\n'), ((42806, 42819), 'scipy.stats.loglaplace', 'loglaplace', (['c'], {}), '(c)\n', (42816, 42819), False, 'from scipy.stats import loglaplace\n'), ((42975, 43020), 'scipy.stats.loglaplace.rvs', 'loglaplace.rvs', (['c1'], {'loc': '(0)', 'scale': '(1)', 'size': '(1000)'}), '(c1, loc=0, scale=1, size=1000)\n', (42989, 43020), False, 'from scipy.stats import loglaplace\n'), ((43443, 43481), 'scipy.stats.loglaplace.ppf', 'loglaplace.ppf', (['[0.001, 0.5, 0.999]', 'c'], {}), '([0.001, 0.5, 0.999], c)\n', (43457, 43481), False, 'from scipy.stats import loglaplace\n'), ((24892, 24948), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'DictionaryToInclude', 'index': '[newIndex]'}), '(data=DictionaryToInclude, index=[newIndex])\n', (24904, 24948), True, 'import pandas as pd\n'), ((25093, 25148), 'pandas.concat', 'pd.concat', (['[train_dataset_adjusted, DataFrameToInclude]'], {}), '([train_dataset_adjusted, DataFrameToInclude])\n', (25102, 25148), True, 'import pandas as pd\n'), ((42559, 42582), 'scipy.stats.loglaplace.ppf', 'loglaplace.ppf', (['(0.01)', 'c'], {}), '(0.01, c)\n', (42573, 42582), False, 'from scipy.stats import loglaplace\n'), ((42584, 42607), 'scipy.stats.loglaplace.ppf', 'loglaplace.ppf', (['(0.99)', 'c'], {}), '(0.99, c)\n', (42598, 42607), False, 'from scipy.stats import loglaplace\n'), ((42647, 42667), 'scipy.stats.loglaplace.pdf', 'loglaplace.pdf', (['x', 'c'], {}), '(x, c)\n', (42661, 42667), False, 'from scipy.stats import loglaplace\n'), ((43539, 43562), 'scipy.stats.loglaplace.cdf', 'loglaplace.cdf', (['vals', 'c'], {}), '(vals, c)\n', (43553, 43562), False, 'from scipy.stats import loglaplace\n'), ((36804, 36830), 'math.log1p', 'math.log1p', (['(2 ** 0.5 * SDC)'], {}), '(2 ** 0.5 * SDC)\n', (36814, 36830), False, 'import math\n')]
#!/usr/bin/env python3 import sys import re import numpy as np from PIL import Image moves = { 'e': (2, 0), 'se': (1, 2), 'sw': (-1, 2), 'w': (-2, 0), 'nw': (-1, -2), 'ne': (1, -2) } # Save (x, y): True/False in tiles. True = black, False = white. tiles = {} for line in open(sys.argv[1]).read().splitlines(): pos = np.array((0, 0)) for d in re.findall(r'e|se|sw|w|nw|ne', line): pos += moves[d] t = tuple(pos) if t in tiles: tiles[t] = not tiles[t] else: tiles[t] = True # Part 1 print('black:', sum(val == True for val in tiles.values())) # -- Part 2 -- # take a chance on how wide it needs to be width = 300 heigth = 300 board = np.zeros(width * heigth, dtype=np.int8) board = board.reshape(heigth, width) # Fill in tiles, move to center for key, value in tiles.items(): x, y = key x += width // 2 y += heigth // 2 board[y][x] = value def black_neighbours(y, x, b): num = 0 for m in moves.values(): num += b[(y + m[1], x + m[0])] return num def game(): board_copy = np.copy(board) w, h = board.shape # Don't do outer edge (to avoid special cases) for y in range(2, h - 2): for x in range(2, w - 2): tile = board_copy[(y, x)] n = black_neighbours(y, x, board_copy) if tile: # black if n == 0 or n > 2: board[(y, x)] = False else: # white if n == 2: board[(y, x)] = True def save_image(day): colours = [(0, 0, 0), (255, 255, 255)] im = Image.new('RGB', (width, heigth)) for y in range(heigth): for x in range(width): c = colours[board[y][x]] im.putpixel((x, y), c) im.save('img%03d.png' % (day)) save_image(0) for day in range(1, 101): game() save_image(day) print('Day %d: %d' % (day, len(np.where(board == True)[0]))) ys, xs = np.where(board) print(min(ys), max(ys), min(xs), max(xs))
[ "numpy.copy", "numpy.where", "PIL.Image.new", "numpy.array", "numpy.zeros", "re.findall" ]
[((683, 722), 'numpy.zeros', 'np.zeros', (['(width * heigth)'], {'dtype': 'np.int8'}), '(width * heigth, dtype=np.int8)\n', (691, 722), True, 'import numpy as np\n'), ((1959, 1974), 'numpy.where', 'np.where', (['board'], {}), '(board)\n', (1967, 1974), True, 'import numpy as np\n'), ((324, 340), 'numpy.array', 'np.array', (['(0, 0)'], {}), '((0, 0))\n', (332, 340), True, 'import numpy as np\n'), ((354, 389), 're.findall', 're.findall', (['"""e|se|sw|w|nw|ne"""', 'line'], {}), "('e|se|sw|w|nw|ne', line)\n", (364, 389), False, 'import re\n'), ((1063, 1077), 'numpy.copy', 'np.copy', (['board'], {}), '(board)\n', (1070, 1077), True, 'import numpy as np\n'), ((1612, 1645), 'PIL.Image.new', 'Image.new', (['"""RGB"""', '(width, heigth)'], {}), "('RGB', (width, heigth))\n", (1621, 1645), False, 'from PIL import Image\n'), ((1919, 1942), 'numpy.where', 'np.where', (['(board == True)'], {}), '(board == True)\n', (1927, 1942), True, 'import numpy as np\n')]
import numpy as np import eyekit import algorithms import core data = eyekit.io.load(core.FIXATIONS / 'sample.json') passages = eyekit.io.load(core.DATA / 'passages.json') original_sequence = data['trial_5']['fixations'] fixation_XY = np.array([fixation.xy for fixation in original_sequence], dtype=int) word_XY = np.array([word.center for word in passages['1B'].words(alphabetical_only=False)], dtype=int) start_times = np.array([i*100 for i in range(len(word_XY))], dtype=int) expected_sequence = eyekit.FixationSequence(np.column_stack([word_XY, start_times, start_times+100])) diagram = eyekit.vis.Image(1920, 1080) diagram.draw_text_block(passages['1B'], mask_text=True) diagram.draw_fixation_sequence(expected_sequence, color='#E32823', fixation_radius=6) diagram.draw_fixation_sequence(original_sequence, color='#205E84', fixation_radius=6) _, warping_path = algorithms.dynamic_time_warping(fixation_XY, word_XY) for fixation, mapped_words in zip(original_sequence, warping_path): for word_i in mapped_words: word_x, word_y = word_XY[word_i] diagram.draw_line(fixation.xy, (word_x, word_y), color='black', stroke_width=0.5, dashed=True) fig = eyekit.vis.Figure() fig.add_image(diagram) fig.set_crop_margin(2) fig.set_padding(vertical=2, horizontal=3, edge=1) fig.set_enumeration(False) fig.save(core.VISUALS / 'illustration_warp.pdf', width=83) # fig.save(core.FIGS / 'fig02_single_column.eps', width=83)
[ "eyekit.vis.Image", "eyekit.vis.Figure", "numpy.column_stack", "algorithms.dynamic_time_warping", "eyekit.io.load", "numpy.array" ]
[((71, 117), 'eyekit.io.load', 'eyekit.io.load', (["(core.FIXATIONS / 'sample.json')"], {}), "(core.FIXATIONS / 'sample.json')\n", (85, 117), False, 'import eyekit\n'), ((129, 172), 'eyekit.io.load', 'eyekit.io.load', (["(core.DATA / 'passages.json')"], {}), "(core.DATA / 'passages.json')\n", (143, 172), False, 'import eyekit\n'), ((238, 306), 'numpy.array', 'np.array', (['[fixation.xy for fixation in original_sequence]'], {'dtype': 'int'}), '([fixation.xy for fixation in original_sequence], dtype=int)\n', (246, 306), True, 'import numpy as np\n'), ((596, 624), 'eyekit.vis.Image', 'eyekit.vis.Image', (['(1920)', '(1080)'], {}), '(1920, 1080)\n', (612, 624), False, 'import eyekit\n'), ((872, 925), 'algorithms.dynamic_time_warping', 'algorithms.dynamic_time_warping', (['fixation_XY', 'word_XY'], {}), '(fixation_XY, word_XY)\n', (903, 925), False, 'import algorithms\n'), ((1163, 1182), 'eyekit.vis.Figure', 'eyekit.vis.Figure', ([], {}), '()\n', (1180, 1182), False, 'import eyekit\n'), ((527, 585), 'numpy.column_stack', 'np.column_stack', (['[word_XY, start_times, start_times + 100]'], {}), '([word_XY, start_times, start_times + 100])\n', (542, 585), True, 'import numpy as np\n')]
#!/usr/bin/python3 ''' This script follows formulas put forth in Kislyuk et al. (2011) to calculate genome fluidity of a pangenome dataset. Variance and standard error are estimated as total variance containing both the variance due to subsampling all possible combinations (without replacement) of N genomes from the total pool of genomes and the variance due to the limited number of sampled genomes (variance of the pangenome)(Kislyuk et al. 2011). However, the script has a default max number of subsamples set to 250,000 for each N genomes. This can be altered with the -max_sub / --max_subsamples flag or turned off with the --max_off flag. Turning the max_off will force calculations to be done on all possible subsample combinations of N genomes. For samples of N genomes that were stopped at the max number of subsamples the subsamples are sampled WITH replacement and variance is calculated with a degree of freedom = 1 (i.e. n - 1). Results are a text file of fluidity, variance, and standard error for all N genome samples and a figure of pangenome fluidity with shaded regions showing total standard error with a exponential regression fit. Notes 1. This will only work if you have at least 5 isolates to make up your pangenome. 2. If you have 5 isolates your graph will probably not look pretty as it's difficult to fit with such a low number of samples. ''' import os, sys, re, argparse, random, itertools, scipy, warnings, subprocess import numpy as np import pandas as pd import matplotlib.pyplot as plt from multiprocessing import Pool from itertools import combinations from collections import OrderedDict from collections.abc import Iterable from scipy.optimize import curve_fit, differential_evolution rundir = os.getcwd() class MyFormatter(argparse.RawTextHelpFormatter): def __init__(self, prog): super(MyFormatter, self).__init__(prog, max_help_position=48) parser = argparse.ArgumentParser( usage='./%(prog)s [options] -i orthogroups -o output_folder', description = ''' Performs multiple bootstraps and calculates genome fluidity from a pangenome dataset (orthogroups).''', epilog = """Written by <NAME> (2019)""", formatter_class = MyFormatter) parser.add_argument( '-i', '--input', required = True, help = 'Orthogroups file, see format in READ.me', metavar='' ) parser.add_argument( '-o', '--out', required = True, help = 'Output folder', metavar='' ) parser.add_argument( '-c', '--cpus', type=int, default=1, help = 'Number of cores to use for multiprocessing [default: 1]', metavar='' ) parser.add_argument( '-max_sub', '--max_subsamples', type=int, default=250000, help = 'Max number of subsamples to run on N genomes sampled. [default: 250000]', metavar='' ) parser.add_argument( '--max_off', action='store_true', help = 'Turn off the max subsamples. This will cause the script sample ALL possible combinations'\ 'for N genomes', ) parser.add_argument( '-p', '--prefix', help = 'Prefix to append to the result files (such as Genus, species, etc.)', metavar='' ) args=parser.parse_args() if not os.path.isdir(args.out): os.makedirs(os.path.join(args.out)) result_dir = os.path.abspath(os.path.join(rundir, args.out)) if args.input: input_file = os.path.abspath(args.input) else: print('ERROR: No orthogroups file was provided please provide on, -i or --input') sys.exit() if args.prefix: fluid_results = os.path.abspath(os.path.join(result_dir, args.prefix+'_fluidity.txt')) fluid_fig = os.path.abspath(os.path.join(result_dir, args.prefix+'_fluidity.png')) else: fluid_results = os.path.abspath(os.path.join(result_dir, 'Pangenome_fluidity.txt')) fluid_fig = os.path.abspath(os.path.join(result_dir, 'Pangenome_fluidity.png')) def create_ortho_dictionary(ortho_file): # create dictionary of gene clusters and isolates per cluster '''Genereate dictionary of Orthogroups.''' print('Creating ortholog dictionary') ortho_isolates_dict = OrderedDict() # {Protein Cluster : list of isolates represented in cluster} with open(ortho_file, 'r') as infile: ortho_list = [item.strip() for item in sorted(infile)] for line in ortho_list: iso_list = [] if ':' in line: cluster, genes = line.split(':') elif '\t' in line: cluster, genes = line.split('\t', 1) else: cluster, genes = line.split(' ', 1) for match in re.finditer(r'([^\s]+)', genes): isolate = match.group(0).split('_')[0] iso_list.append(isolate) ortho_isolates_dict[cluster] = list(set(iso_list)) return ortho_isolates_dict def create_pair_dictionary(ortho_dictionary): '''Create all possible unique pairs of isolates and get their unique sum gene clusters.''' print('Creating dictionary of paired ratio values') pair_dict = {} # {(Isolate1, Isolate2) : [ratio of sum(unique clusters)/sum(all clusters)]} for i in range(0, len(iso_list)): for x in range(0, len(iso_list)): if not iso_list[i] == iso_list[x]: pair = tuple(sorted([iso_list[i], iso_list[x]])) if not pair in pair_dict.keys(): cogs = {'Shared' : 0, 'Uk' : 0, 'Ul' : 0} for k,v in ortho_dictionary.items(): if pair[0] in v and pair[1] in v: cogs['Shared'] += 1 elif pair[0] in v and pair[1] not in v: cogs['Uk'] += 1 elif pair[0] not in v and pair[1] in v: cogs['Ul'] += 1 else: pass # don't need to count a cluster if both isolates are not present unique_pair = cogs['Uk'] + cogs['Ul'] all_pair = (cogs['Uk'] + cogs['Shared']) + (cogs['Ul'] + cogs['Shared']) pair_dict[pair] = unique_pair/all_pair return pair_dict def compute_fluidity_all_genomes(): ''' Computes the fluidity and variance for the pangenome in question from the max number of genomes in the pangenome. ''' N = iso_num fluidity_list = [ratio for ratio in pair_dict.values()] # list of ratios pangenome_fluidity = (2/(N*(N-1)))*sum(fluidity_list) # get fluidity from average of all ratios jack_samples = list(combinations(iso_list, N - 1)) # get list of all combos of N-1 from max num of genomes fluidity_i_list = [] for sample in jack_samples: jack_pairs = tuple(combinations(sample,2)) # get all pairs from current jackknife sample jack_sample_fluidity = [pair_dict[tuple(sorted(p))] for p in jack_pairs] # get ratios from pair_dict fluidity_i = (2/((N-1)*(N-2)))*sum(jack_sample_fluidity) # calculate fluidity_i fluidity_i_list.append(fluidity_i) fluidity_i_mean = np.mean(fluidity_i_list) # calculate fluidity_i_mean from all fluidity_i's fluidity_variance = ((N-1)/N)*sum([(i-fluidity_i_mean)**2 for i in fluidity_i_list]) # calculate variance return pangenome_fluidity, fluidity_variance def subsample_multiprocess(combo_list): ''' Takes portions of the full combo_list and runs them on separate threads for faster processing. Calcualtes fluidity for each sample and returns list of fluidities. ''' N = len(combo_list[0]) # get N from number of genomes present sample_process_list = [] for sample in combo_list: pairs = tuple(combinations(sample,2)) pair_fluidity_list = [pair_dict[tuple(sorted(p))] for p in pairs] sample_fluidity = (2/(N*(N-1)))*sum(pair_fluidity_list) sample_process_list.append(sample_fluidity) return sample_process_list def genome_subsamples_fluidities(perm_list): ''' Compute fluidities from all possible combinations of genomes from 3 to N randomly sampled genomes (N is the max number of gneomes in sample, so only sampled once). Has a cut off of max subsamples at which point variances are calcualted as sample variances (n-1) instead of full population variances. ''' sub_fluid_dict = {} # {N genomes sampled : [list of fluidities from subsamples]} for N in range(3, iso_num + 1): sub_fluid_dict[N] = [] N_combos = list(combinations(iso_list, N)) if args.max_off: combos = N_combos else: if len(N_combos) > args.max_subsamples: combos = random.choices(N_combos, k=args.max_subsamples) perm_list.append(N) else: combos = N_combos print('Performing fluidity calculations on {} subsample combinations of {} genomes'.format(len(combos),N)) if not len(N_combos) == 1: chunk = round(len(combos)/args.cpus) split_combos = [combos[i:i + chunk] for i in range(0, len(combos), chunk)] pool = Pool(processes=args.cpus) results = pool.imap(subsample_multiprocess, split_combos) pool.close() pool.join() sub_fluid_dict[N].append(results) else: last_run = subsample_multiprocess(N_combos) sub_fluid_dict[N].append(last_run) sub_fluid_dict[N]=list(flatten(sub_fluid_dict[N])) print(len(sub_fluid_dict[N])) return sub_fluid_dict def flatten(lis): for item in lis: if isinstance(item, Iterable) and not isinstance(item, str): for x in flatten(item): yield x else: yield item def exponential(x, a, b, c): return a * np.exp(b * x) + c def neg_exponential(x, a, b, c): return a * np.exp(-b * x) + c def sumOfSquaredError(parameterTuple, x_values, y_curve_values, func): warnings.filterwarnings("ignore") # do not print warnings by genetic algorithm val = func(x_values, *parameterTuple) return np.sum((y_curve_values - val) ** 2.0) def generate_Initial_Parameters(x_values, y_curve_values, func): # min and max used for bounds maxX = max(x_values) minX = min(x_values) maxY = max(y_curve_values) minY = min(y_curve_values) maxXY = max(maxX, maxY) parameterBounds = [] parameterBounds.append([-maxXY, maxXY]) # seach bounds for a parameterBounds.append([-maxXY, maxXY]) # seach bounds for b parameterBounds.append([-maxXY, maxXY]) # seach bounds for c # "seed" the numpy random number generator for repeatable results result = differential_evolution(sumOfSquaredError, parameterBounds, args=(x_values,y_curve_values, func), seed=3) return result.x def create_fluidity_results(figure_output, results_output): total_variance = [] for i in range(3, iso_num + 1): if i in permutation_list: total_variance.append(np.var(sub_fluid_dict[i], ddof = 1) + pan_variance) else: total_variance.append(np.var(sub_fluid_dict[i]) + pan_variance) total_variance = np.array(total_variance) total_stderr = np.array([x**(1/2) for x in total_variance]) y_fluidity_values = np.array([pan_fluidity for i in range(3, iso_num + 1)]) x_labels = np.array([i for i in range(3, iso_num + 1)]) stderr_bottom = np.array([(pan_fluidity - v) for v in total_stderr]) stderr_top = np.array([(pan_fluidity + v) for v in total_stderr]) fig, ax = plt.subplots() try: # Still had problems sometimes with fitting curves, this solution works best for now geneticParameters_top = generate_Initial_Parameters(x_labels, stderr_top, exponential) geneticParameters_bottom = generate_Initial_Parameters(x_labels, stderr_bottom, exponential) popt_t, pcov = curve_fit(exponential, x_labels, stderr_top, geneticParameters_top, maxfev=10000) popt_b, pcov = curve_fit(exponential, x_labels, stderr_bottom, geneticParameters_bottom, maxfev=10000) if len(set(exponential(x_labels, *popt_t))) > 3 and len(set(exponential(x_labels, *popt_b))) > 3: plt.fill_between(x_labels, exponential(x_labels, *popt_t), exponential(x_labels, *popt_b), facecolor='blue', alpha=0.6) top_curve = exponential(x_labels, *popt_t) bottom_curve = exponential(x_labels, *popt_b) if len(set(exponential(x_labels, *popt_t))) <= 3: geneticParameters_top = generate_Initial_Parameters(x_labels, stderr_top, neg_exponential) popt_t, pcov = curve_fit(neg_exponential, x_labels, stderr_top, geneticParameters_top, maxfev=10000) plt.fill_between(x_labels, neg_exponential(x_labels, *popt_t), exponential(x_labels, *popt_b), facecolor='blue', alpha=0.6) top_curve = neg_exponential(x_labels, *popt_t) bottom_curve = exponential(x_labels, *popt_b) else: pass if len(set(exponential(x_labels, *popt_b))) <= 3: geneticParameters_bottom = generate_Initial_Parameters(x_labels, stderr_bottom, neg_exponential) popt_b, pcov = curve_fit(neg_exponential, x_labels, stderr_bottom, geneticParameters_bottom, maxfev=10000) plt.fill_between(x_labels, exponential(x_labels, *popt_t), neg_exponential(x_labels, *popt_b), facecolor='blue', alpha=0.6) top_curve = exponential(x_labels, *popt_t) bottom_curve = neg_exponential(x_labels, *popt_b) else: pass except: pass ax.set_axisbelow(True) plt.minorticks_on() plt.grid(which='minor', axis='y', color='white', linestyle='--', alpha=0.3) ax.yaxis.grid(True, linestyle='-', linewidth='1', which='major', color='white') ax.xaxis.grid(True, linestyle='-', linewidth='1', which='major', color='white', alpha=0.5) ax.tick_params(axis='x', which='minor', bottom=False) ax.set_facecolor('gainsboro') plt.plot(x_labels, y_fluidity_values, ls='--', lw=1, color='black') # plot y-values of fluidity plt.xticks(np.arange(x_labels[0], x_labels[len(x_labels)-1]+1, 1.0)) # make sure x interval is 1 plt.xlim(x_labels[0], x_labels[len(x_labels)-1]) # adjust x limit so it starts with 3 at 0 max_y = max(stderr_top) min_y = min(stderr_bottom) plt.ylim((min_y - min_y*0.15), (max_y + max_y*0.15)) plt.xlabel('Number of genomes sampled') plt.ylabel('Fluidity, '+u'\u03C6') plt.tight_layout() plt.savefig(figure_output) with open(results_output, 'w') as results: # print out fluidity results results.write('Genomes_Sampled\tFluidity\tTotal_Variance\tTotal_Stderr\tExponential_top\tExponential_bottom\n') r_out = [] for i in range(0, iso_num-2): r_out.append([str(i+3), str(pan_fluidity), str(total_variance[i]), str(total_stderr[i]), str(top_curve[i]), str(bottom_curve[i])]) for line in r_out: results.write('\t'.join(line) + '\n') if __name__ == "__main__": ortho_dict = create_ortho_dictionary(input_file) iso_num = max([len(v) for v in ortho_dict.values()]) iso_list = list(set(itertools.chain.from_iterable([v for v in ortho_dict.values() if len(v) == iso_num]))) pair_dict = create_pair_dictionary(ortho_dict) pan_results = compute_fluidity_all_genomes() pan_fluidity = pan_results[0] pan_variance = pan_results[1] permutation_list = [] sub_fluid_dict = genome_subsamples_fluidities(permutation_list) create_fluidity_results(fluid_fig, fluid_results)
[ "matplotlib.pyplot.grid", "scipy.optimize.differential_evolution", "matplotlib.pyplot.ylabel", "numpy.array", "random.choices", "sys.exit", "numpy.mean", "argparse.ArgumentParser", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.plot", "matplotlib.pyplot.minorticks_on", "numpy.exp", "os.path.isdir", "re.finditer", "matplotlib.pyplot.ylim", "collections.OrderedDict", "matplotlib.pyplot.savefig", "warnings.filterwarnings", "scipy.optimize.curve_fit", "os.path.join", "os.getcwd", "itertools.combinations", "numpy.sum", "multiprocessing.Pool", "matplotlib.pyplot.tight_layout", "os.path.abspath", "matplotlib.pyplot.subplots", "numpy.var" ]
[((1749, 1760), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (1758, 1760), False, 'import os, sys, re, argparse, random, itertools, scipy, warnings, subprocess\n'), ((1921, 2213), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'usage': '"""./%(prog)s [options] -i orthogroups -o output_folder"""', 'description': '""" Performs multiple bootstraps and calculates genome fluidity \n from a pangenome dataset (orthogroups)."""', 'epilog': '"""Written by <NAME> (2019)"""', 'formatter_class': 'MyFormatter'}), '(usage=\n \'./%(prog)s [options] -i orthogroups -o output_folder\', description=\n """ Performs multiple bootstraps and calculates genome fluidity \n from a pangenome dataset (orthogroups)."""\n , epilog=\'Written by <NAME> (2019)\', formatter_class=MyFormatter)\n', (1944, 2213), False, 'import os, sys, re, argparse, random, itertools, scipy, warnings, subprocess\n'), ((3207, 3230), 'os.path.isdir', 'os.path.isdir', (['args.out'], {}), '(args.out)\n', (3220, 3230), False, 'import os, sys, re, argparse, random, itertools, scipy, warnings, subprocess\n'), ((3301, 3331), 'os.path.join', 'os.path.join', (['rundir', 'args.out'], {}), '(rundir, args.out)\n', (3313, 3331), False, 'import os, sys, re, argparse, random, itertools, scipy, warnings, subprocess\n'), ((3366, 3393), 'os.path.abspath', 'os.path.abspath', (['args.input'], {}), '(args.input)\n', (3381, 3393), False, 'import os, sys, re, argparse, random, itertools, scipy, warnings, subprocess\n'), ((3490, 3500), 'sys.exit', 'sys.exit', ([], {}), '()\n', (3498, 3500), False, 'import os, sys, re, argparse, random, itertools, scipy, warnings, subprocess\n'), ((4093, 4106), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (4104, 4106), False, 'from collections import OrderedDict\n'), ((7049, 7073), 'numpy.mean', 'np.mean', (['fluidity_i_list'], {}), '(fluidity_i_list)\n', (7056, 7073), True, 'import numpy as np\n'), ((9904, 9937), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (9927, 9937), False, 'import os, sys, re, argparse, random, itertools, scipy, warnings, subprocess\n'), ((10036, 10073), 'numpy.sum', 'np.sum', (['((y_curve_values - val) ** 2.0)'], {}), '((y_curve_values - val) ** 2.0)\n', (10042, 10073), True, 'import numpy as np\n'), ((10618, 10727), 'scipy.optimize.differential_evolution', 'differential_evolution', (['sumOfSquaredError', 'parameterBounds'], {'args': '(x_values, y_curve_values, func)', 'seed': '(3)'}), '(sumOfSquaredError, parameterBounds, args=(x_values,\n y_curve_values, func), seed=3)\n', (10640, 10727), False, 'from scipy.optimize import curve_fit, differential_evolution\n'), ((11095, 11119), 'numpy.array', 'np.array', (['total_variance'], {}), '(total_variance)\n', (11103, 11119), True, 'import numpy as np\n'), ((11139, 11189), 'numpy.array', 'np.array', (['[(x ** (1 / 2)) for x in total_variance]'], {}), '([(x ** (1 / 2)) for x in total_variance])\n', (11147, 11189), True, 'import numpy as np\n'), ((11344, 11396), 'numpy.array', 'np.array', (['[(pan_fluidity - v) for v in total_stderr]'], {}), '([(pan_fluidity - v) for v in total_stderr])\n', (11352, 11396), True, 'import numpy as np\n'), ((11414, 11466), 'numpy.array', 'np.array', (['[(pan_fluidity + v) for v in total_stderr]'], {}), '([(pan_fluidity + v) for v in total_stderr])\n', (11422, 11466), True, 'import numpy as np\n'), ((11481, 11495), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (11493, 11495), True, 'import matplotlib.pyplot as plt\n'), ((13537, 13556), 'matplotlib.pyplot.minorticks_on', 'plt.minorticks_on', ([], {}), '()\n', (13554, 13556), True, 'import matplotlib.pyplot as plt\n'), ((13561, 13636), 'matplotlib.pyplot.grid', 'plt.grid', ([], {'which': '"""minor"""', 'axis': '"""y"""', 'color': '"""white"""', 'linestyle': '"""--"""', 'alpha': '(0.3)'}), "(which='minor', axis='y', color='white', linestyle='--', alpha=0.3)\n", (13569, 13636), True, 'import matplotlib.pyplot as plt\n'), ((13912, 13979), 'matplotlib.pyplot.plot', 'plt.plot', (['x_labels', 'y_fluidity_values'], {'ls': '"""--"""', 'lw': '(1)', 'color': '"""black"""'}), "(x_labels, y_fluidity_values, ls='--', lw=1, color='black')\n", (13920, 13979), True, 'import matplotlib.pyplot as plt\n'), ((14267, 14319), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(min_y - min_y * 0.15)', '(max_y + max_y * 0.15)'], {}), '(min_y - min_y * 0.15, max_y + max_y * 0.15)\n', (14275, 14319), True, 'import matplotlib.pyplot as plt\n'), ((14324, 14363), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Number of genomes sampled"""'], {}), "('Number of genomes sampled')\n", (14334, 14363), True, 'import matplotlib.pyplot as plt\n'), ((14368, 14399), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (["('Fluidity, ' + u'φ')"], {}), "('Fluidity, ' + u'φ')\n", (14378, 14399), True, 'import matplotlib.pyplot as plt\n'), ((14407, 14425), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (14423, 14425), True, 'import matplotlib.pyplot as plt\n'), ((14430, 14456), 'matplotlib.pyplot.savefig', 'plt.savefig', (['figure_output'], {}), '(figure_output)\n', (14441, 14456), True, 'import matplotlib.pyplot as plt\n'), ((3248, 3270), 'os.path.join', 'os.path.join', (['args.out'], {}), '(args.out)\n', (3260, 3270), False, 'import os, sys, re, argparse, random, itertools, scipy, warnings, subprocess\n'), ((3554, 3609), 'os.path.join', 'os.path.join', (['result_dir', "(args.prefix + '_fluidity.txt')"], {}), "(result_dir, args.prefix + '_fluidity.txt')\n", (3566, 3609), False, 'import os, sys, re, argparse, random, itertools, scipy, warnings, subprocess\n'), ((3641, 3696), 'os.path.join', 'os.path.join', (['result_dir', "(args.prefix + '_fluidity.png')"], {}), "(result_dir, args.prefix + '_fluidity.png')\n", (3653, 3696), False, 'import os, sys, re, argparse, random, itertools, scipy, warnings, subprocess\n'), ((3738, 3788), 'os.path.join', 'os.path.join', (['result_dir', '"""Pangenome_fluidity.txt"""'], {}), "(result_dir, 'Pangenome_fluidity.txt')\n", (3750, 3788), False, 'import os, sys, re, argparse, random, itertools, scipy, warnings, subprocess\n'), ((3822, 3872), 'os.path.join', 'os.path.join', (['result_dir', '"""Pangenome_fluidity.png"""'], {}), "(result_dir, 'Pangenome_fluidity.png')\n", (3834, 3872), False, 'import os, sys, re, argparse, random, itertools, scipy, warnings, subprocess\n'), ((6545, 6574), 'itertools.combinations', 'combinations', (['iso_list', '(N - 1)'], {}), '(iso_list, N - 1)\n', (6557, 6574), False, 'from itertools import combinations\n'), ((11809, 11895), 'scipy.optimize.curve_fit', 'curve_fit', (['exponential', 'x_labels', 'stderr_top', 'geneticParameters_top'], {'maxfev': '(10000)'}), '(exponential, x_labels, stderr_top, geneticParameters_top, maxfev=\n 10000)\n', (11818, 11895), False, 'from scipy.optimize import curve_fit, differential_evolution\n'), ((11914, 12005), 'scipy.optimize.curve_fit', 'curve_fit', (['exponential', 'x_labels', 'stderr_bottom', 'geneticParameters_bottom'], {'maxfev': '(10000)'}), '(exponential, x_labels, stderr_bottom, geneticParameters_bottom,\n maxfev=10000)\n', (11923, 12005), False, 'from scipy.optimize import curve_fit, differential_evolution\n'), ((4588, 4619), 're.finditer', 're.finditer', (['"""([^\\\\s]+)"""', 'genes'], {}), "('([^\\\\s]+)', genes)\n", (4599, 4619), False, 'import os, sys, re, argparse, random, itertools, scipy, warnings, subprocess\n'), ((6716, 6739), 'itertools.combinations', 'combinations', (['sample', '(2)'], {}), '(sample, 2)\n', (6728, 6739), False, 'from itertools import combinations\n'), ((7659, 7682), 'itertools.combinations', 'combinations', (['sample', '(2)'], {}), '(sample, 2)\n', (7671, 7682), False, 'from itertools import combinations\n'), ((8461, 8486), 'itertools.combinations', 'combinations', (['iso_list', 'N'], {}), '(iso_list, N)\n', (8473, 8486), False, 'from itertools import combinations\n'), ((9075, 9100), 'multiprocessing.Pool', 'Pool', ([], {'processes': 'args.cpus'}), '(processes=args.cpus)\n', (9079, 9100), False, 'from multiprocessing import Pool\n'), ((9742, 9755), 'numpy.exp', 'np.exp', (['(b * x)'], {}), '(b * x)\n', (9748, 9755), True, 'import numpy as np\n'), ((9809, 9823), 'numpy.exp', 'np.exp', (['(-b * x)'], {}), '(-b * x)\n', (9815, 9823), True, 'import numpy as np\n'), ((12541, 12630), 'scipy.optimize.curve_fit', 'curve_fit', (['neg_exponential', 'x_labels', 'stderr_top', 'geneticParameters_top'], {'maxfev': '(10000)'}), '(neg_exponential, x_labels, stderr_top, geneticParameters_top,\n maxfev=10000)\n', (12550, 12630), False, 'from scipy.optimize import curve_fit, differential_evolution\n'), ((13105, 13200), 'scipy.optimize.curve_fit', 'curve_fit', (['neg_exponential', 'x_labels', 'stderr_bottom', 'geneticParameters_bottom'], {'maxfev': '(10000)'}), '(neg_exponential, x_labels, stderr_bottom,\n geneticParameters_bottom, maxfev=10000)\n', (13114, 13200), False, 'from scipy.optimize import curve_fit, differential_evolution\n'), ((8634, 8681), 'random.choices', 'random.choices', (['N_combos'], {'k': 'args.max_subsamples'}), '(N_combos, k=args.max_subsamples)\n', (8648, 8681), False, 'import os, sys, re, argparse, random, itertools, scipy, warnings, subprocess\n'), ((10932, 10965), 'numpy.var', 'np.var', (['sub_fluid_dict[i]'], {'ddof': '(1)'}), '(sub_fluid_dict[i], ddof=1)\n', (10938, 10965), True, 'import numpy as np\n'), ((11032, 11057), 'numpy.var', 'np.var', (['sub_fluid_dict[i]'], {}), '(sub_fluid_dict[i])\n', (11038, 11057), True, 'import numpy as np\n')]
# Licensed under a 3-clause BSD style license - see LICENSE.rst """Tools to create profiles (i.e. 1D "slices" from 2D images).""" import numpy as np import scipy.ndimage from astropy import units as u from astropy.convolution import Box1DKernel, Gaussian1DKernel from astropy.coordinates import Angle from astropy.table import Table from .core import Estimator __all__ = ["ImageProfile", "ImageProfileEstimator"] # TODO: implement measuring profile along arbitrary directions # TODO: think better about error handling. e.g. MC based methods class ImageProfileEstimator(Estimator): """Estimate profile from image. Parameters ---------- x_edges : `~astropy.coordinates.Angle` Coordinate edges to define a custom measument grid (optional). method : ['sum', 'mean'] Compute sum or mean within profile bins. axis : ['lon', 'lat', 'radial'] Along which axis to estimate the profile. center : `~astropy.coordinates.SkyCoord` Center coordinate for the radial profile option. Examples -------- This example shows how to compute a counts profile for the Fermi galactic center region:: import matplotlib.pyplot as plt from gammapy.maps import ImageProfileEstimator from gammapy.maps import Map from astropy import units as u # load example data filename = '$GAMMAPY_DATA/fermi-3fhl-gc/fermi-3fhl-gc-counts.fits.gz' fermi_cts = Map.read(filename) # set up profile estimator and run p = ImageProfileEstimator(axis='lon', method='sum') profile = p.run(fermi_cts) # smooth profile and plot smoothed = profile.smooth(kernel='gauss') smoothed.peek() plt.show() """ tag = "ImageProfileEstimator" def __init__(self, x_edges=None, method="sum", axis="lon", center=None): self._x_edges = x_edges if method not in ["sum", "mean"]: raise ValueError("Not a valid method, choose either 'sum' or 'mean'") if axis not in ["lon", "lat", "radial"]: raise ValueError("Not a valid axis, choose either 'lon' or 'lat'") if method == "radial" and center is None: raise ValueError("Please provide center coordinate for radial profiles") self.parameters = {"method": method, "axis": axis, "center": center} def _get_x_edges(self, image): if self._x_edges is not None: return self._x_edges p = self.parameters coordinates = image.geom.get_coord(mode="edges").skycoord if p["axis"] == "lat": x_edges = coordinates[:, 0].data.lat elif p["axis"] == "lon": lon = coordinates[0, :].data.lon x_edges = lon.wrap_at("180d") elif p["axis"] == "radial": rad_step = image.geom.pixel_scales.mean() corners = [0, 0, -1, -1], [0, -1, 0, -1] rad_max = coordinates[corners].separation(p["center"]).max() x_edges = Angle(np.arange(0, rad_max.deg, rad_step.deg), unit="deg") return x_edges def _estimate_profile(self, image, image_err, mask): p = self.parameters labels = self._label_image(image, mask) profile_err = None index = np.arange(1, len(self._get_x_edges(image))) if p["method"] == "sum": profile = scipy.ndimage.sum(image.data, labels.data, index) if image.unit.is_equivalent("counts"): profile_err = np.sqrt(profile) elif image_err: # gaussian error propagation err_sum = scipy.ndimage.sum(image_err.data ** 2, labels.data, index) profile_err = np.sqrt(err_sum) elif p["method"] == "mean": # gaussian error propagation profile = scipy.ndimage.mean(image.data, labels.data, index) if image_err: N = scipy.ndimage.sum(~np.isnan(image_err.data), labels.data, index) err_sum = scipy.ndimage.sum(image_err.data ** 2, labels.data, index) profile_err = np.sqrt(err_sum) / N return profile, profile_err def _label_image(self, image, mask=None): p = self.parameters coordinates = image.geom.get_coord().skycoord x_edges = self._get_x_edges(image) if p["axis"] == "lon": lon = coordinates.data.lon.wrap_at("180d") data = np.digitize(lon.degree, x_edges.deg) elif p["axis"] == "lat": lat = coordinates.data.lat data = np.digitize(lat.degree, x_edges.deg) elif p["axis"] == "radial": separation = coordinates.separation(p["center"]) data = np.digitize(separation.degree, x_edges.deg) if mask is not None: # assign masked values to background data[mask.data] = 0 return image.copy(data=data) def run(self, image, image_err=None, mask=None): """Run image profile estimator. Parameters ---------- image : `~gammapy.maps.Map` Input image to run profile estimator on. image_err : `~gammapy.maps.Map` Input error image to run profile estimator on. mask : `~gammapy.maps.Map` Optional mask to exclude regions from the measurement. Returns ------- profile : `ImageProfile` Result image profile object. """ p = self.parameters if image.unit.is_equivalent("count"): image_err = image.copy(data=np.sqrt(image.data)) profile, profile_err = self._estimate_profile(image, image_err, mask) result = Table() x_edges = self._get_x_edges(image) result["x_min"] = x_edges[:-1] result["x_max"] = x_edges[1:] result["x_ref"] = (x_edges[:-1] + x_edges[1:]) / 2 result["profile"] = profile * image.unit if profile_err is not None: result["profile_err"] = profile_err * image.unit result.meta["PROFILE_TYPE"] = p["axis"] return ImageProfile(result) class ImageProfile: """Image profile class. The image profile data is stored in `~astropy.table.Table` object, with the following columns: * `x_ref` Coordinate bin center (required). * `x_min` Coordinate bin minimum (optional). * `x_max` Coordinate bin maximum (optional). * `profile` Image profile data (required). * `profile_err` Image profile data error (optional). Parameters ---------- table : `~astropy.table.Table` Table instance with the columns specified as above. """ def __init__(self, table): self.table = table def smooth(self, kernel="box", radius="0.1 deg", **kwargs): r"""Smooth profile with error propagation. Smoothing is described by a convolution: .. math:: x_j = \sum_i x_{(j - i)} h_i Where :math:`h_i` are the coefficients of the convolution kernel. The corresponding error on :math:`x_j` is then estimated using Gaussian error propagation, neglecting correlations between the individual :math:`x_{(j - i)}`: .. math:: \Delta x_j = \sqrt{\sum_i \Delta x^{2}_{(j - i)} h^{2}_i} Parameters ---------- kernel : {'gauss', 'box'} Kernel shape radius : `~astropy.units.Quantity`, str or float Smoothing width given as quantity or float. If a float is given it is interpreted as smoothing width in pixels. If an (angular) quantity is given it is converted to pixels using `xref[1] - x_ref[0]`. kwargs : dict Keyword arguments passed to `~scipy.ndimage.uniform_filter` ('box') and `~scipy.ndimage.gaussian_filter` ('gauss'). Returns ------- profile : `ImageProfile` Smoothed image profile. """ table = self.table.copy() profile = table["profile"] radius = u.Quantity(radius) radius = np.abs(radius / np.diff(self.x_ref))[0] width = 2 * radius.value + 1 if kernel == "box": smoothed = scipy.ndimage.uniform_filter( profile.astype("float"), width, **kwargs ) # renormalize data if table["profile"].unit.is_equivalent("count"): smoothed *= int(width) smoothed_err = np.sqrt(smoothed) elif "profile_err" in table.colnames: profile_err = table["profile_err"] # use gaussian error propagation box = Box1DKernel(width) err_sum = scipy.ndimage.convolve(profile_err ** 2, box.array ** 2) smoothed_err = np.sqrt(err_sum) elif kernel == "gauss": smoothed = scipy.ndimage.gaussian_filter( profile.astype("float"), width, **kwargs ) # use gaussian error propagation if "profile_err" in table.colnames: profile_err = table["profile_err"] gauss = Gaussian1DKernel(width) err_sum = scipy.ndimage.convolve(profile_err ** 2, gauss.array ** 2) smoothed_err = np.sqrt(err_sum) else: raise ValueError("Not valid kernel choose either 'box' or 'gauss'") table["profile"] = smoothed * self.table["profile"].unit if "profile_err" in table.colnames: table["profile_err"] = smoothed_err * self.table["profile"].unit return self.__class__(table) def plot(self, ax=None, **kwargs): """Plot image profile. Parameters ---------- ax : `~matplotlib.axes.Axes` Axes object **kwargs : dict Keyword arguments passed to `~matplotlib.axes.Axes.plot` Returns ------- ax : `~matplotlib.axes.Axes` Axes object """ import matplotlib.pyplot as plt if ax is None: ax = plt.gca() y = self.table["profile"].data x = self.x_ref.value ax.plot(x, y, **kwargs) ax.set_xlabel("lon") ax.set_ylabel("profile") ax.set_xlim(x.max(), x.min()) return ax def plot_err(self, ax=None, **kwargs): """Plot image profile error as band. Parameters ---------- ax : `~matplotlib.axes.Axes` Axes object **kwargs : dict Keyword arguments passed to plt.fill_between() Returns ------- ax : `~matplotlib.axes.Axes` Axes object """ import matplotlib.pyplot as plt if ax is None: ax = plt.gca() y = self.table["profile"].data ymin = y - self.table["profile_err"].data ymax = y + self.table["profile_err"].data x = self.x_ref.value # plotting defaults kwargs.setdefault("alpha", 0.5) ax.fill_between(x, ymin, ymax, **kwargs) ax.set_xlabel("x (deg)") ax.set_ylabel("profile") return ax @property def x_ref(self): """Reference x coordinates.""" return self.table["x_ref"].quantity @property def x_min(self): """Min. x coordinates.""" return self.table["x_min"].quantity @property def x_max(self): """Max. x coordinates.""" return self.table["x_max"].quantity @property def profile(self): """Image profile quantity.""" return self.table["profile"].quantity @property def profile_err(self): """Image profile error quantity.""" try: return self.table["profile_err"].quantity except KeyError: return None def peek(self, figsize=(8, 4.5), **kwargs): """Show image profile and error. Parameters ---------- **kwargs : dict Keyword arguments passed to `ImageProfile.plot_profile()` Returns ------- ax : `~matplotlib.axes.Axes` Axes object """ import matplotlib.pyplot as plt fig = plt.figure(figsize=figsize) ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) ax = self.plot(ax, **kwargs) if "profile_err" in self.table.colnames: ax = self.plot_err(ax, color=kwargs.get("c")) return ax def normalize(self, mode="peak"): """Normalize profile to peak value or integral. Parameters ---------- mode : ['integral', 'peak'] Normalize image profile so that it integrates to unity ('integral') or the maximum value corresponds to one ('peak'). Returns ------- profile : `ImageProfile` Normalized image profile. """ table = self.table.copy() profile = self.table["profile"] if mode == "peak": norm = np.nanmax(profile) elif mode == "integral": norm = np.nansum(profile) else: raise ValueError(f"Invalid normalization mode: {mode!r}") table["profile"] /= norm if "profile_err" in table.colnames: table["profile_err"] /= norm return self.__class__(table)
[ "numpy.sqrt", "astropy.table.Table", "numpy.arange", "numpy.digitize", "matplotlib.pyplot.gca", "numpy.diff", "astropy.convolution.Gaussian1DKernel", "matplotlib.pyplot.figure", "numpy.isnan", "numpy.nanmax", "astropy.convolution.Box1DKernel", "numpy.nansum", "astropy.units.Quantity" ]
[((5684, 5691), 'astropy.table.Table', 'Table', ([], {}), '()\n', (5689, 5691), False, 'from astropy.table import Table\n'), ((8050, 8068), 'astropy.units.Quantity', 'u.Quantity', (['radius'], {}), '(radius)\n', (8060, 8068), True, 'from astropy import units as u\n'), ((12194, 12221), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': 'figsize'}), '(figsize=figsize)\n', (12204, 12221), True, 'import matplotlib.pyplot as plt\n'), ((4433, 4469), 'numpy.digitize', 'np.digitize', (['lon.degree', 'x_edges.deg'], {}), '(lon.degree, x_edges.deg)\n', (4444, 4469), True, 'import numpy as np\n'), ((10069, 10078), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (10076, 10078), True, 'import matplotlib.pyplot as plt\n'), ((10757, 10766), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (10764, 10766), True, 'import matplotlib.pyplot as plt\n'), ((12982, 13000), 'numpy.nanmax', 'np.nanmax', (['profile'], {}), '(profile)\n', (12991, 13000), True, 'import numpy as np\n'), ((3497, 3513), 'numpy.sqrt', 'np.sqrt', (['profile'], {}), '(profile)\n', (3504, 3513), True, 'import numpy as np\n'), ((4562, 4598), 'numpy.digitize', 'np.digitize', (['lat.degree', 'x_edges.deg'], {}), '(lat.degree, x_edges.deg)\n', (4573, 4598), True, 'import numpy as np\n'), ((8478, 8495), 'numpy.sqrt', 'np.sqrt', (['smoothed'], {}), '(smoothed)\n', (8485, 8495), True, 'import numpy as np\n'), ((13053, 13071), 'numpy.nansum', 'np.nansum', (['profile'], {}), '(profile)\n', (13062, 13071), True, 'import numpy as np\n'), ((3702, 3718), 'numpy.sqrt', 'np.sqrt', (['err_sum'], {}), '(err_sum)\n', (3709, 3718), True, 'import numpy as np\n'), ((4716, 4759), 'numpy.digitize', 'np.digitize', (['separation.degree', 'x_edges.deg'], {}), '(separation.degree, x_edges.deg)\n', (4727, 4759), True, 'import numpy as np\n'), ((5566, 5585), 'numpy.sqrt', 'np.sqrt', (['image.data'], {}), '(image.data)\n', (5573, 5585), True, 'import numpy as np\n'), ((8102, 8121), 'numpy.diff', 'np.diff', (['self.x_ref'], {}), '(self.x_ref)\n', (8109, 8121), True, 'import numpy as np\n'), ((8668, 8686), 'astropy.convolution.Box1DKernel', 'Box1DKernel', (['width'], {}), '(width)\n', (8679, 8686), False, 'from astropy.convolution import Box1DKernel, Gaussian1DKernel\n'), ((8801, 8817), 'numpy.sqrt', 'np.sqrt', (['err_sum'], {}), '(err_sum)\n', (8808, 8817), True, 'import numpy as np\n'), ((9143, 9166), 'astropy.convolution.Gaussian1DKernel', 'Gaussian1DKernel', (['width'], {}), '(width)\n', (9159, 9166), False, 'from astropy.convolution import Box1DKernel, Gaussian1DKernel\n'), ((9283, 9299), 'numpy.sqrt', 'np.sqrt', (['err_sum'], {}), '(err_sum)\n', (9290, 9299), True, 'import numpy as np\n'), ((3009, 3048), 'numpy.arange', 'np.arange', (['(0)', 'rad_max.deg', 'rad_step.deg'], {}), '(0, rad_max.deg, rad_step.deg)\n', (3018, 3048), True, 'import numpy as np\n'), ((4096, 4112), 'numpy.sqrt', 'np.sqrt', (['err_sum'], {}), '(err_sum)\n', (4103, 4112), True, 'import numpy as np\n'), ((3935, 3959), 'numpy.isnan', 'np.isnan', (['image_err.data'], {}), '(image_err.data)\n', (3943, 3959), True, 'import numpy as np\n')]
import open3d as o3d import numpy as np pc_load_pathname = '/home/caizhongang/github/waymo_kitti_converter/007283-000.bin' pc = np.fromfile(pc_load_pathname, dtype=np.float32).reshape(-1, 3) pcd = o3d.geometry.PointCloud() pcd.points = o3d.utility.Vector3dVector(pc) axis = o3d.geometry.TriangleMesh.create_coordinate_frame(size=1, origin=[0,0,0]) visual = [pcd, axis] o3d.visualization.draw_geometries(visual)
[ "numpy.fromfile", "open3d.visualization.draw_geometries", "open3d.geometry.PointCloud", "open3d.geometry.TriangleMesh.create_coordinate_frame", "open3d.utility.Vector3dVector" ]
[((199, 224), 'open3d.geometry.PointCloud', 'o3d.geometry.PointCloud', ([], {}), '()\n', (222, 224), True, 'import open3d as o3d\n'), ((239, 269), 'open3d.utility.Vector3dVector', 'o3d.utility.Vector3dVector', (['pc'], {}), '(pc)\n', (265, 269), True, 'import open3d as o3d\n'), ((278, 353), 'open3d.geometry.TriangleMesh.create_coordinate_frame', 'o3d.geometry.TriangleMesh.create_coordinate_frame', ([], {'size': '(1)', 'origin': '[0, 0, 0]'}), '(size=1, origin=[0, 0, 0])\n', (327, 353), True, 'import open3d as o3d\n'), ((375, 416), 'open3d.visualization.draw_geometries', 'o3d.visualization.draw_geometries', (['visual'], {}), '(visual)\n', (408, 416), True, 'import open3d as o3d\n'), ((129, 176), 'numpy.fromfile', 'np.fromfile', (['pc_load_pathname'], {'dtype': 'np.float32'}), '(pc_load_pathname, dtype=np.float32)\n', (140, 176), True, 'import numpy as np\n')]
#!/usr/bin/env python """ Compute diffusion coefficient from MSD data. Time interval, DT, is obtained from in.pmd in the same directory. Usage: msd2diff.py [options] MSD_FILE Options: -h, --help Show this message and exit. -o, --offset OFFSET Offset of given data. [default: 0] --plot Plot a fitted graph. [default: False] """ from __future__ import print_function import os,sys from docopt import docopt import numpy as np __author__ = "<NAME>" __version__ = "191212" def read_out_msd(fname='out.msd',offset=0,specorder=[],spc=None): if specorder == [] or spc not in specorder: index = 1 else: index = specorder.index(spc) +1 with open(fname,'r') as f: lines = f.readlines() try: dname = os.path.dirname(fname) dt = dt_from_inpmd(fname=dname+'/in.pmd') except Exception as e: raise RuntimeError('Failed to read in.pmd.') ts = [] msds = [] n0 = 0 msd0 = 0.0 for il,line in enumerate(lines): if line[0] == '#': continue data = line.split() if il < offset: n0 = int(data[0]) msd0 = float(data[index]) continue n = int(data[0]) msd = float(data[index]) ts.append((n-n0)*dt) msds.append(msd-msd0) return np.array(ts),np.array(msds) def dt_from_inpmd(fname='in.pmd'): with open(fname,'r') as f: lines = f.readlines() for line in lines: if 'time_interval' in line: time_interval = abs(float(line.split()[1])) elif 'num_iteration' in line: num_iteration = int(line.split()[1]) elif 'num_out_pos' in line or 'num_out_pmd' in line: num_out_pos = int(line.split()[1]) return time_interval*num_iteration/num_out_pos def msd2D(ts,msds,fac,dim=3): """ Compute diffusion coefficient from time [fs] vs MSD [Ang^2] data by solving least square problem using numpy. Return diffusion coefficient multiplied by FAC. """ A= np.array([ts, np.ones(len(ts))]) A = A.T xvar = np.var(A[:,0]) p,res,_,_ = np.linalg.lstsq(A,msds,rcond=None) a = p[0] b = p[1] # fac = 1.0e-16 /1.e-15 a = a *fac /(2.0*dim) b = b *fac # print(res[0],xvar,np.mean(A[:,0]),len(ts)) std = np.sqrt(res[0]/len(ts)/xvar) *fac /(2.0*dim) return a,b,std if __name__ == "__main__": args = docopt(__doc__) fname = args['MSD_FILE'] offset = int(args['--offset']) plot = args['--plot'] ts,msds = read_out_msd(fname,offset) #...Assuming input MSD unit in A^2/fs and output in cm^2/s fac = 1.0e-16 /1.0e-15 #...Least square a,b,std = msd2D(ts,msds,fac) print(' Diffusion coefficient = {0:12.4e}'.format(a)+ ' +/- {0:12.4e} [cm^2/s]'.format(std)) if plot: import matplotlib.pyplot as plt import seaborn as sns sns.set(context='talk',style='ticks') #...Original time unit == fs unit = 'fs' tfac = 1.0 if ts[-1] > 1.0e+5: #...if max t > 100ps, time unit in ps unit = 'ps' tfac = 1.0e-3 plt.xlabel('Time ({0:s})'.format(unit)) plt.ylabel('MSD (A^2/{0:s})'.format(unit)) fvals = np.array([ (t*a+b)/fac for t in ts ]) plt.plot(ts*tfac,msds/tfac,'b-',label='MSD data') plt.plot(ts*tfac,fvals/tfac,'r-',label='Fitted curve') plt.savefig("graph_msd2D.png", format='png', dpi=300, bbox_inches='tight') print(' Wrote graph_msd2D.png')
[ "seaborn.set", "matplotlib.pyplot.savefig", "matplotlib.pyplot.plot", "os.path.dirname", "numpy.array", "numpy.linalg.lstsq", "docopt.docopt", "numpy.var" ]
[((2111, 2126), 'numpy.var', 'np.var', (['A[:, 0]'], {}), '(A[:, 0])\n', (2117, 2126), True, 'import numpy as np\n'), ((2142, 2178), 'numpy.linalg.lstsq', 'np.linalg.lstsq', (['A', 'msds'], {'rcond': 'None'}), '(A, msds, rcond=None)\n', (2157, 2178), True, 'import numpy as np\n'), ((2436, 2451), 'docopt.docopt', 'docopt', (['__doc__'], {}), '(__doc__)\n', (2442, 2451), False, 'from docopt import docopt\n'), ((780, 802), 'os.path.dirname', 'os.path.dirname', (['fname'], {}), '(fname)\n', (795, 802), False, 'import os, sys\n'), ((1339, 1351), 'numpy.array', 'np.array', (['ts'], {}), '(ts)\n', (1347, 1351), True, 'import numpy as np\n'), ((1352, 1366), 'numpy.array', 'np.array', (['msds'], {}), '(msds)\n', (1360, 1366), True, 'import numpy as np\n'), ((2927, 2965), 'seaborn.set', 'sns.set', ([], {'context': '"""talk"""', 'style': '"""ticks"""'}), "(context='talk', style='ticks')\n", (2934, 2965), True, 'import seaborn as sns\n'), ((3272, 3315), 'numpy.array', 'np.array', (['[((t * a + b) / fac) for t in ts]'], {}), '([((t * a + b) / fac) for t in ts])\n', (3280, 3315), True, 'import numpy as np\n'), ((3318, 3374), 'matplotlib.pyplot.plot', 'plt.plot', (['(ts * tfac)', '(msds / tfac)', '"""b-"""'], {'label': '"""MSD data"""'}), "(ts * tfac, msds / tfac, 'b-', label='MSD data')\n", (3326, 3374), True, 'import matplotlib.pyplot as plt\n'), ((3376, 3437), 'matplotlib.pyplot.plot', 'plt.plot', (['(ts * tfac)', '(fvals / tfac)', '"""r-"""'], {'label': '"""Fitted curve"""'}), "(ts * tfac, fvals / tfac, 'r-', label='Fitted curve')\n", (3384, 3437), True, 'import matplotlib.pyplot as plt\n'), ((3439, 3513), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""graph_msd2D.png"""'], {'format': '"""png"""', 'dpi': '(300)', 'bbox_inches': '"""tight"""'}), "('graph_msd2D.png', format='png', dpi=300, bbox_inches='tight')\n", (3450, 3513), True, 'import matplotlib.pyplot as plt\n')]
import pytest import numbers import numpy as np from numpy.testing import assert_raises from numpy.testing import assert_array_equal from numpy.testing import assert_equal from numpy.testing import assert_raises_regex from skopt.space import LogN, Normalize @pytest.mark.fast_test def test_logn2_integer(): transformer = LogN(2) for X in range(2, 31): X_orig = transformer.inverse_transform(transformer.transform(X)) assert_array_equal(int(np.round(X_orig)), X) @pytest.mark.fast_test def test_logn10_integer(): transformer = LogN(2) for X in range(2, 31): X_orig = transformer.inverse_transform(transformer.transform(X)) assert_array_equal(int(np.round(X_orig)), X) @pytest.mark.fast_test def test_normalize_integer(): transformer = Normalize(1, 20, is_int=True) assert transformer.transform(19.8) == 1.0 assert transformer.transform(20.2) == 1.0 assert transformer.transform(1.2) == 0.0 assert transformer.transform(0.9) == 0.0 assert_raises(ValueError, transformer.transform, 20.6) assert_raises(ValueError, transformer.transform, 0.4) assert transformer.inverse_transform(0.99) == 20 assert transformer.inverse_transform(0.01) == 1 assert_raises(ValueError, transformer.inverse_transform, 1. + 1e-8) assert_raises(ValueError, transformer.transform, 0. - 1e-8) @pytest.mark.fast_test def test_normalize(): transformer = Normalize(1, 20, is_int=False) assert transformer.transform(20.) == 1.0 assert transformer.transform(1.) == 0.0 assert_raises(ValueError, transformer.transform, 20. + 1e-7) assert_raises(ValueError, transformer.transform, 1.0 - 1e-7) assert_raises(ValueError, transformer.inverse_transform, 1. + 1e-8) assert_raises(ValueError, transformer.transform, 0. - 1e-8)
[ "numpy.round", "skopt.space.LogN", "numpy.testing.assert_raises", "skopt.space.Normalize" ]
[((328, 335), 'skopt.space.LogN', 'LogN', (['(2)'], {}), '(2)\n', (332, 335), False, 'from skopt.space import LogN, Normalize\n'), ((559, 566), 'skopt.space.LogN', 'LogN', (['(2)'], {}), '(2)\n', (563, 566), False, 'from skopt.space import LogN, Normalize\n'), ((793, 822), 'skopt.space.Normalize', 'Normalize', (['(1)', '(20)'], {'is_int': '(True)'}), '(1, 20, is_int=True)\n', (802, 822), False, 'from skopt.space import LogN, Normalize\n'), ((1009, 1063), 'numpy.testing.assert_raises', 'assert_raises', (['ValueError', 'transformer.transform', '(20.6)'], {}), '(ValueError, transformer.transform, 20.6)\n', (1022, 1063), False, 'from numpy.testing import assert_raises\n'), ((1068, 1121), 'numpy.testing.assert_raises', 'assert_raises', (['ValueError', 'transformer.transform', '(0.4)'], {}), '(ValueError, transformer.transform, 0.4)\n', (1081, 1121), False, 'from numpy.testing import assert_raises\n'), ((1232, 1301), 'numpy.testing.assert_raises', 'assert_raises', (['ValueError', 'transformer.inverse_transform', '(1.0 + 1e-08)'], {}), '(ValueError, transformer.inverse_transform, 1.0 + 1e-08)\n', (1245, 1301), False, 'from numpy.testing import assert_raises\n'), ((1304, 1365), 'numpy.testing.assert_raises', 'assert_raises', (['ValueError', 'transformer.transform', '(0.0 - 1e-08)'], {}), '(ValueError, transformer.transform, 0.0 - 1e-08)\n', (1317, 1365), False, 'from numpy.testing import assert_raises\n'), ((1429, 1459), 'skopt.space.Normalize', 'Normalize', (['(1)', '(20)'], {'is_int': '(False)'}), '(1, 20, is_int=False)\n', (1438, 1459), False, 'from skopt.space import LogN, Normalize\n'), ((1553, 1615), 'numpy.testing.assert_raises', 'assert_raises', (['ValueError', 'transformer.transform', '(20.0 + 1e-07)'], {}), '(ValueError, transformer.transform, 20.0 + 1e-07)\n', (1566, 1615), False, 'from numpy.testing import assert_raises\n'), ((1618, 1679), 'numpy.testing.assert_raises', 'assert_raises', (['ValueError', 'transformer.transform', '(1.0 - 1e-07)'], {}), '(ValueError, transformer.transform, 1.0 - 1e-07)\n', (1631, 1679), False, 'from numpy.testing import assert_raises\n'), ((1683, 1752), 'numpy.testing.assert_raises', 'assert_raises', (['ValueError', 'transformer.inverse_transform', '(1.0 + 1e-08)'], {}), '(ValueError, transformer.inverse_transform, 1.0 + 1e-08)\n', (1696, 1752), False, 'from numpy.testing import assert_raises\n'), ((1755, 1816), 'numpy.testing.assert_raises', 'assert_raises', (['ValueError', 'transformer.transform', '(0.0 - 1e-08)'], {}), '(ValueError, transformer.transform, 0.0 - 1e-08)\n', (1768, 1816), False, 'from numpy.testing import assert_raises\n'), ((467, 483), 'numpy.round', 'np.round', (['X_orig'], {}), '(X_orig)\n', (475, 483), True, 'import numpy as np\n'), ((698, 714), 'numpy.round', 'np.round', (['X_orig'], {}), '(X_orig)\n', (706, 714), True, 'import numpy as np\n')]
import os import json import numpy as np import pickle from typing import Any from pycocotools.coco import COCO from torch.utils.data import Dataset class DetectionMSCOCODataset(Dataset): def __init__(self, annotation_file: str, image_dir: str): self._annotation_file = annotation_file self._image_dir = image_dir self._cache_file = self._annotation_file + ".cache" self._coco = COCO(self._annotation_file) self._img_ids = self._coco.getImgIds() self._cat_ids = self._coco.getCatIds() self._ann_ids = self._coco.getAnnIds() self._data = "coco" self._classes = { ind: cat_id for ind, cat_id in enumerate(self._cat_ids) } self._coco_to_class_map = { value: key for key, value in self._classes.items() } self._load_data() self._db_inds = np.arange(len(self._image_names)) self._load_coco_data() def _load_data(self): print("loading from cache file: {}".format(self._cache_file)) if not os.path.exists(self._cache_file): print("No cache file found...") self._extract_data() with open(self._cache_file, "wb") as f: pickle.dump([self._detections, self._image_names], f) print("Cache file created") else: with open(self._cache_file, "rb") as f: self._detections, self._image_names = pickle.load(f) def _load_coco_data(self): with open(self._annotation_file, "r") as f: data = json.load(f) coco_ids = self._coco.getImgIds() eval_ids = { self._coco.loadImgs(coco_id)[0]["file_name"]: coco_id for coco_id in coco_ids } self._coco_categories = data["categories"] self._coco_eval_ids = eval_ids def class_name(self, cid): cat_id = self._classes[cid] cat = self._coco.loadCats([cat_id])[0] return cat["name"] def _extract_data(self): self._image_names = [ self._coco.loadImgs(img_id)[0]["file_name"] for img_id in self._img_ids ] self._detections = {} for ind, (coco_image_id, image_name) in enumerate(zip(self._img_ids, self._image_names)): image = self._coco.loadImgs(coco_image_id)[0] bboxes = [] categories = [] for cat_id in self._cat_ids: annotation_ids = self._coco.getAnnIds(imgIds=image["id"], catIds=cat_id) annotations = self._coco.loadAnns(annotation_ids) category = self._coco_to_class_map[cat_id] for annotation in annotations: bbox = np.array(annotation["bbox"]) bbox[[2, 3]] += bbox[[0, 1]] bboxes.append(bbox) categories.append(category) self._detections[image_name] = [{ 'bbox': bbox.astype(np.float32), 'category_id': category, 'category_name': self.class_name(category) } for bbox, category in zip(bboxes, categories)] def __getitem__(self, ind: int) -> Any: image_name = self._image_names[ind] return { 'image_name': os.path.join(self._image_dir, image_name), 'detections': self._detections[image_name] } def __len__(self) -> int: return len(self._img_ids) def get_num_classes(self) -> int: return len(self._cat_ids)
[ "os.path.exists", "pickle.dump", "pycocotools.coco.COCO", "os.path.join", "pickle.load", "numpy.array", "json.load" ]
[((420, 447), 'pycocotools.coco.COCO', 'COCO', (['self._annotation_file'], {}), '(self._annotation_file)\n', (424, 447), False, 'from pycocotools.coco import COCO\n'), ((1061, 1093), 'os.path.exists', 'os.path.exists', (['self._cache_file'], {}), '(self._cache_file)\n', (1075, 1093), False, 'import os\n'), ((1572, 1584), 'json.load', 'json.load', (['f'], {}), '(f)\n', (1581, 1584), False, 'import json\n'), ((3290, 3331), 'os.path.join', 'os.path.join', (['self._image_dir', 'image_name'], {}), '(self._image_dir, image_name)\n', (3302, 3331), False, 'import os\n'), ((1240, 1293), 'pickle.dump', 'pickle.dump', (['[self._detections, self._image_names]', 'f'], {}), '([self._detections, self._image_names], f)\n', (1251, 1293), False, 'import pickle\n'), ((1454, 1468), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (1465, 1468), False, 'import pickle\n'), ((2733, 2761), 'numpy.array', 'np.array', (["annotation['bbox']"], {}), "(annotation['bbox'])\n", (2741, 2761), True, 'import numpy as np\n')]
# usr/bin/env python """Functions to cluster using UPGMA upgma takes an dictionary of pair tuples mapped to distances as input. UPGMA_cluster takes an array and a list of PhyloNode objects corresponding to the array as input. Can also generate this type of input from a DictArray using inputs_from_dict_array function. Both return a PhyloNode object of the UPGMA cluster """ import numpy from numpy import argmin, array, average, diag, ma, ravel, sum, take from cogent3.core.tree import PhyloNode from cogent3.util.dict_array import DictArray __author__ = "<NAME>" __copyright__ = "Copyright 2007-2020, The Cogent Project" __credits__ = ["<NAME>", "<NAME>", "<NAME>"] __license__ = "BSD-3" __version__ = "2020.7.2a" __maintainer__ = "<NAME>" __email__ = "<EMAIL>" __status__ = "Production" numerictypes = numpy.core.numerictypes.sctype2char Float = numerictypes(float) BIG_NUM = 1e305 def upgma(pairwise_distances): """Uses the UPGMA algorithm to cluster sequences pairwise_distances: a dictionary with pair tuples mapped to a distance returns a PhyloNode object of the UPGMA cluster """ darr = DictArray(pairwise_distances) matrix_a, node_order = inputs_from_dict_array(darr) tree = UPGMA_cluster(matrix_a, node_order, BIG_NUM) index = 0 for node in tree.traverse(): if not node.parent: node.name = "root" elif not node.name: node.name = "edge." + str(index) index += 1 return tree def find_smallest_index(matrix): """returns the index of the smallest element in a numpy array for UPGMA clustering elements on the diagonal should first be substituted with a very large number so that they are always larger than the rest if the values in the array.""" # get the shape of the array as a tuple (e.g. (3,3)) shape = matrix.shape # turn into a 1 by x array and get the index of the lowest number matrix1D = ravel(matrix) lowest_index = argmin(matrix1D) # convert the lowest_index derived from matrix1D to one for the original # square matrix and return row_len = shape[0] return divmod(lowest_index, row_len) def condense_matrix(matrix, smallest_index, large_value): """converges the rows and columns indicated by smallest_index Smallest index is returned from find_smallest_index. For both the rows and columns, the values for the two indices are averaged. The resulting vector replaces the first index in the array and the second index is replaced by an array with large numbers so that it is never chosen again with find_smallest_index. """ first_index, second_index = smallest_index # get the rows and make a new vector that has their average rows = take(matrix, smallest_index, 0) new_vector = average(rows, 0) # replace info in the row and column for first index with new_vector matrix[first_index] = new_vector matrix[:, first_index] = new_vector # replace the info in the row and column for the second index with # high numbers so that it is ignored matrix[second_index] = large_value matrix[:, second_index] = large_value return matrix def condense_node_order(matrix, smallest_index, node_order): """condenses two nodes in node_order based on smallest_index info This function is used to create a tree while condensing a matrix with the condense_matrix function. The smallest_index is retrieved with find_smallest_index. The first index is replaced with a node object that combines the two nodes corresponding to the indices in node order. The second index in smallest_index is replaced with None. Also sets the branch length of the nodes to 1/2 of the distance between the nodes in the matrix""" index1, index2 = smallest_index node1 = node_order[index1] node2 = node_order[index2] # get the distance between the nodes and assign 1/2 the distance to the # lengthproperty of each node distance = matrix[index1, index2] nodes = [node1, node2] d = distance / 2.0 for n in nodes: if n.children: n.length = d - n.children[0].TipLength else: n.length = d n.TipLength = d # combine the two nodes into a new PhyloNode object new_node = PhyloNode() new_node.children.append(node1) new_node.children.append(node2) node1.parent = new_node node2.parent = new_node # replace the object at index1 with the combined node node_order[index1] = new_node # replace the object at index2 with None node_order[index2] = None return node_order def UPGMA_cluster(matrix, node_order, large_number): """cluster with UPGMA matrix is a numpy array. node_order is a list of PhyloNode objects corresponding to the matrix. large_number will be assigned to the matrix during the process and should be much larger than any value already in the matrix. WARNING: Changes matrix in-place. WARNING: Expects matrix to already have diagonals assigned to large_number before this function is called. """ num_entries = len(node_order) tree = None for i in range(num_entries - 1): smallest_index = find_smallest_index(matrix) index1, index2 = smallest_index # if smallest_index is on the diagonal set the diagonal to large_number if index1 == index2: matrix[diag([True] * len(matrix))] = large_number smallest_index = find_smallest_index(matrix) row_order = condense_node_order(matrix, smallest_index, node_order) matrix = condense_matrix(matrix, smallest_index, large_number) tree = node_order[smallest_index[0]] return tree def inputs_from_dict_array(darr): """makes inputs for UPGMA_cluster from a DictArray object """ darr.array += numpy.eye(darr.shape[0]) * BIG_NUM nodes = list(map(PhyloNode, darr.keys())) return darr.array, nodes
[ "numpy.eye", "numpy.average", "cogent3.core.tree.PhyloNode", "cogent3.util.dict_array.DictArray", "numpy.take", "numpy.argmin", "numpy.ravel" ]
[((1128, 1157), 'cogent3.util.dict_array.DictArray', 'DictArray', (['pairwise_distances'], {}), '(pairwise_distances)\n', (1137, 1157), False, 'from cogent3.util.dict_array import DictArray\n'), ((1944, 1957), 'numpy.ravel', 'ravel', (['matrix'], {}), '(matrix)\n', (1949, 1957), False, 'from numpy import argmin, array, average, diag, ma, ravel, sum, take\n'), ((1977, 1993), 'numpy.argmin', 'argmin', (['matrix1D'], {}), '(matrix1D)\n', (1983, 1993), False, 'from numpy import argmin, array, average, diag, ma, ravel, sum, take\n'), ((2754, 2785), 'numpy.take', 'take', (['matrix', 'smallest_index', '(0)'], {}), '(matrix, smallest_index, 0)\n', (2758, 2785), False, 'from numpy import argmin, array, average, diag, ma, ravel, sum, take\n'), ((2803, 2819), 'numpy.average', 'average', (['rows', '(0)'], {}), '(rows, 0)\n', (2810, 2819), False, 'from numpy import argmin, array, average, diag, ma, ravel, sum, take\n'), ((4301, 4312), 'cogent3.core.tree.PhyloNode', 'PhyloNode', ([], {}), '()\n', (4310, 4312), False, 'from cogent3.core.tree import PhyloNode\n'), ((5862, 5886), 'numpy.eye', 'numpy.eye', (['darr.shape[0]'], {}), '(darr.shape[0])\n', (5871, 5886), False, 'import numpy\n')]
import numpy as np from coffeine.covariance_transformers import ( Diag, LogDiag, ExpandFeatures, Riemann, RiemannSnp, NaiveVec) from coffeine.spatial_filters import ( ProjIdentitySpace, ProjCommonSpace, ProjLWSpace, ProjRandomSpace, ProjSPoCSpace) from sklearn.compose import make_column_transformer from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler from sklearn.linear_model import RidgeCV, LogisticRegression def make_filter_bank_transformer(names, method='riemann', projection_params=None, vectorization_params=None, categorical_interaction=None): """Generate pipeline for filterbank models. Prepare filter bank models as used in [1]_. These models take as input sensor-space covariance matrices computed from M/EEG signals in different frequency bands. Then transformations are applied to improve the applicability of linear regression techniques by reducing the impact of field spread. In terms of implementation, this involves 1) projection (e.g. spatial filters) and 2) vectorization (e.g. taking the log on the diagonal). .. note:: The resulting model expects as inputs data frames in which different covarances (e.g. for different frequencies) are stored inside columns indexed by ``names``. Other columns will be passed through by the underlying column transformers. The pipeline also supports fitting categorical interaction effects after projection and vectorization steps are performed. .. note:: All essential methods from [1]_ are implemented here. In practice, we recommend comparing `riemann', `spoc' and `diag' as a baseline. Parameters ---------- names : list of str The column names of the data frame corresponding to different covariances. method : str The method used for extracting features from covariances. Defaults to ``'riemann'``. Can be ``'riemann'``, ``'lw_riemann'``, ``'diag'``, ``'log_diag'``, ``'random'``, ``'naive'``, ``'spoc'``, ``'riemann_wasserstein'``. projection_params : dict | None The parameters for the projection step. vectorization_params : dict | None The parameters for the vectorization step. categorical_interaction : str The column in the input data frame containing a binary descriptor used to fit 2-way interaction effects. References ---------- [1] <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>. Predictive regression modeling with MEG/EEG: from source power to signals and cognitive states. *NeuroImage*, page 116893,2020. ISSN 1053-8119. https://doi.org/10.1016/j.neuroimage.2020.116893 """ # put defaults here for projection and vectorization step projection_defaults = { 'riemann': dict(scale=1, n_compo='full', reg=1.e-05), 'lw_riemann': dict(shrink=1), 'diag': dict(), 'log_diag': dict(), 'random': dict(n_compo='full'), 'naive': dict(), 'spoc': dict(n_compo='full', scale='auto', reg=1.e-05, shrink=1), 'riemann_wasserstein': dict() } vectorization_defaults = { 'riemann': dict(metric='riemann'), 'lw_riemann': dict(metric='riemann'), 'diag': dict(), 'log_diag': dict(), 'random': dict(), 'naive': dict(method='upper'), 'spoc': dict(), 'riemann_wasserstein': dict(rank='full') } assert set(projection_defaults) == set(vectorization_defaults) if method not in projection_defaults: raise ValueError( f"The `method` ('{method}') you specified is unknown.") # update defaults projection_params_ = projection_defaults[method] if projection_params is not None: projection_params_.update(**projection_params) vectorization_params_ = vectorization_defaults[method] if vectorization_params is not None: vectorization_params_.update(**vectorization_params) def _get_projector_vectorizer(projection, vectorization): return [(make_pipeline(* [projection(**projection_params_), vectorization(**vectorization_params_)]), name) for name in names] # setup pipelines (projection + vectorization step) steps = tuple() if method == 'riemann': steps = (ProjCommonSpace, Riemann) elif method == 'lw_riemann': steps = (ProjLWSpace, Riemann) elif method == 'diag': steps = (ProjIdentitySpace, Diag) elif method == 'log_diag': steps = (ProjIdentitySpace, LogDiag) elif method == 'random': steps = (ProjRandomSpace, LogDiag) elif method == 'naive': steps = (ProjIdentitySpace, NaiveVec) elif method == 'spoc': steps = (ProjSPoCSpace, LogDiag) elif method == 'riemann_wasserstein': steps = (ProjIdentitySpace, RiemannSnp) filter_bank_transformer = make_column_transformer( *_get_projector_vectorizer(*steps), remainder='passthrough') if categorical_interaction is not None: filter_bank_transformer = ExpandFeatures( filter_bank_transformer, expander_column=categorical_interaction) return filter_bank_transformer def make_filter_bank_regressor(names, method='riemann', projection_params=None, vectorization_params=None, categorical_interaction=None, scaling=None, estimator=None): """Generate pipeline for regression with filter bank model. Prepare filter bank models as used in [1]_. These models take as input sensor-space covariance matrices computed from M/EEG signals in different frequency bands. Then transformations are applied to improve the applicability of linear regression techniques by reducing the impact of field spread. In terms of implementation, this involves 1) projection (e.g. spatial filters) and 2) vectorization (e.g. taking the log on the diagonal). .. note:: The resulting model expects as inputs data frames in which different covarances (e.g. for different frequencies) are stored inside columns indexed by ``names``. Other columns will be passed through by the underlying column transformers. The pipeline also supports fitting categorical interaction effects after projection and vectorization steps are performed. .. note:: All essential methods from [1]_ are implemented here. In practice, we recommend comparing `riemann', `spoc' and `diag' as a baseline. Parameters ---------- names : list of str The column names of the data frame corresponding to different covariances. method : str The method used for extracting features from covariances. Defaults to ``'riemann'``. Can be ``'riemann'``, ``'lw_riemann'``, ``'diag'``, ``'log_diag'``, ``'random'``, ``'naive'``, ``'spoc'``, ``'riemann_wasserstein'``. projection_params : dict | None The parameters for the projection step. vectorization_params : dict | None The parameters for the vectorization step. categorical_interaction : str The column in the input data frame containing a binary descriptor used to fit 2-way interaction effects. scaling : scikit-learn Transformer object | None Method for re-rescaling the features. Defaults to None. If None, StandardScaler is used. estimator : scikit-learn Estimator object. The estimator object. Defaults to None. If None, RidgeCV is performed with default values. References ---------- [1] <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>. Predictive regression modeling with MEG/EEG: from source power to signals and cognitive states. *NeuroImage*, page 116893,2020. ISSN 1053-8119. https://doi.org/10.1016/j.neuroimage.2020.116893 """ filter_bank_transformer = make_filter_bank_transformer( names=names, method=method, projection_params=projection_params, vectorization_params=vectorization_params, categorical_interaction=categorical_interaction ) scaling_ = scaling if scaling_ is None: scaling_ = StandardScaler() estimator_ = estimator if estimator_ is None: estimator_ = RidgeCV(alphas=np.logspace(-3, 5, 100)) filter_bank_regressor = make_pipeline( filter_bank_transformer, scaling_, estimator_ ) return filter_bank_regressor def make_filter_bank_classifier(names, method='riemann', projection_params=None, vectorization_params=None, categorical_interaction=None, scaling=None, estimator=None): """Generate pipeline for classification with filter bank model. Prepare filter bank models as used in [1]_. These models take as input sensor-space covariance matrices computed from M/EEG signals in different frequency bands. Then transformations are applied to improve the applicability of linear regression techniques by reducing the impact of field spread. In terms of implementation, this involves 1) projection (e.g. spatial filters) and 2) vectorization (e.g. taking the log on the diagonal). .. note:: The resulting model expects as inputs data frames in which different covarances (e.g. for different frequencies) are stored inside columns indexed by ``names``. Other columns will be passed through by the underlying column transformers. The pipeline also supports fitting categorical interaction effects after projection and vectorization steps are performed. .. note:: All essential methods from [1]_ are implemented here. In practice, we recommend comparing `riemann', `spoc' and `diag' as a baseline. Parameters ---------- names : list of str The column names of the data frame corresponding to different covariances. method : str The method used for extracting features from covariances. Defaults to ``'riemann'``. Can be ``'riemann'``, ``'lw_riemann'``, ``'diag'``, ``'log_diag'``, ``'random'``, ``'naive'``, ``'spoc'``, ``'riemann_wasserstein'``. projection_params : dict | None The parameters for the projection step. vectorization_params : dict | None The parameters for the vectorization step. categorical_interaction : str The column in the input data frame containing a binary descriptor used to fit 2-way interaction effects. scaling : scikit-learn Transformer object | None Method for re-rescaling the features. Defaults to None. If None, StandardScaler is used. estimator : scikit-learn Estimator object. The estimator object. Defaults to None. If None, LogisticRegression is performed with default values. References ---------- [1] <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>. Predictive regression modeling with MEG/EEG: from source power to signals and cognitive states. *NeuroImage*, page 116893,2020. ISSN 1053-8119. https://doi.org/10.1016/j.neuroimage.2020.116893 """ filter_bank_transformer = make_filter_bank_transformer( names=names, method=method, projection_params=projection_params, vectorization_params=vectorization_params, categorical_interaction=categorical_interaction ) scaling_ = scaling if scaling_ is None: scaling_ = StandardScaler() estimator_ = estimator if estimator_ is None: estimator_ = LogisticRegression(solver='liblinear') filter_bank_regressor = make_pipeline( filter_bank_transformer, scaling_, estimator_ ) return filter_bank_regressor
[ "coffeine.covariance_transformers.ExpandFeatures", "sklearn.linear_model.LogisticRegression", "sklearn.preprocessing.StandardScaler", "sklearn.pipeline.make_pipeline", "numpy.logspace" ]
[((8747, 8807), 'sklearn.pipeline.make_pipeline', 'make_pipeline', (['filter_bank_transformer', 'scaling_', 'estimator_'], {}), '(filter_bank_transformer, scaling_, estimator_)\n', (8760, 8807), False, 'from sklearn.pipeline import make_pipeline\n'), ((12164, 12224), 'sklearn.pipeline.make_pipeline', 'make_pipeline', (['filter_bank_transformer', 'scaling_', 'estimator_'], {}), '(filter_bank_transformer, scaling_, estimator_)\n', (12177, 12224), False, 'from sklearn.pipeline import make_pipeline\n'), ((5344, 5429), 'coffeine.covariance_transformers.ExpandFeatures', 'ExpandFeatures', (['filter_bank_transformer'], {'expander_column': 'categorical_interaction'}), '(filter_bank_transformer, expander_column=categorical_interaction\n )\n', (5358, 5429), False, 'from coffeine.covariance_transformers import Diag, LogDiag, ExpandFeatures, Riemann, RiemannSnp, NaiveVec\n'), ((8585, 8601), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (8599, 8601), False, 'from sklearn.preprocessing import StandardScaler\n'), ((12003, 12019), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (12017, 12019), False, 'from sklearn.preprocessing import StandardScaler\n'), ((12096, 12134), 'sklearn.linear_model.LogisticRegression', 'LogisticRegression', ([], {'solver': '"""liblinear"""'}), "(solver='liblinear')\n", (12114, 12134), False, 'from sklearn.linear_model import RidgeCV, LogisticRegression\n'), ((8693, 8716), 'numpy.logspace', 'np.logspace', (['(-3)', '(5)', '(100)'], {}), '(-3, 5, 100)\n', (8704, 8716), True, 'import numpy as np\n')]
import os import df2img import disnake import numpy as np import pandas as pd from menus.menu import Menu from PIL import Image import discordbot.config_discordbot as cfg from discordbot.config_discordbot import gst_imgur, logger from discordbot.helpers import autocrop_image from gamestonk_terminal.stocks.options import yfinance_model async def chain_command( ctx, ticker: str = None, expiry: str = None, opt_type: str = None, min_sp: float = None, max_sp: float = None, ): """Show calls/puts for given ticker and expiration""" try: # Debug if cfg.DEBUG: logger.debug( "opt-chain %s %s %s %s %s", ticker, expiry, opt_type, min_sp, max_sp ) # Check for argument if not ticker: raise Exception("Stock ticker is required") dates = yfinance_model.option_expirations(ticker) if not dates: raise Exception("Stock ticker is invalid") options = yfinance_model.get_option_chain(ticker, str(expiry)) calls_df = options.calls puts_df = options.puts column_map = {"openInterest": "oi", "volume": "vol", "impliedVolatility": "iv"} columns = [ "strike", "bid", "ask", "volume", "openInterest", "impliedVolatility", ] if opt_type == "Calls": df = calls_df[columns].rename(columns=column_map) if opt_type == "Puts": df = puts_df[columns].rename(columns=column_map) min_strike = np.percentile(df["strike"], 1) max_strike = np.percentile(df["strike"], 100) if min_sp: min_strike = min_sp if max_sp: max_strike = max_sp if min_sp > max_sp: # type: ignore min_sp, max_sp = max_strike, min_strike df = df[df["strike"] >= min_strike] df = df[df["strike"] <= max_strike] df["iv"] = pd.to_numeric(df["iv"].astype(float)) formats = {"iv": "{:.2f}"} for col, f in formats.items(): df[col] = df[col].map(lambda x: f.format(x)) # pylint: disable=W0640 df.set_index("strike", inplace=True) title = f"Stocks: {opt_type} Option Chain for {ticker.upper()} on {expiry} [yfinance]" embeds: list = [] # Weekly Calls Pages i, i2, end = 0, 0, 20 df_pg = [] embeds_img = [] dindex = len(df.index) while i < dindex: df_pg = df.iloc[i:end] df_pg.append(df_pg) figp = df2img.plot_dataframe( df_pg, fig_size=(1000, (40 + (40 * 20))), col_width=[3, 3, 3, 3], tbl_cells=dict( height=35, ), font=dict( family="Consolas", size=20, ), template="plotly_dark", paper_bgcolor="rgba(0, 0, 0, 0)", ) imagefile = f"opt-chain{i}.png" df2img.save_dataframe(fig=figp, filename=imagefile) image = Image.open(imagefile) image = autocrop_image(image, 0) image.save(imagefile, "PNG", quality=100) uploaded_image = gst_imgur.upload_image(imagefile, title="something") image_link = uploaded_image.link embeds_img.append( f"{image_link}", ) embeds.append( disnake.Embed( title=title, colour=cfg.COLOR, ), ) i2 += 1 i += 20 end += 20 os.remove(imagefile) # Author/Footer for i in range(0, i2): embeds[i].set_author( name=cfg.AUTHOR_NAME, url=cfg.AUTHOR_URL, icon_url=cfg.AUTHOR_ICON_URL, ) embeds[i].set_footer( text=cfg.AUTHOR_NAME, icon_url=cfg.AUTHOR_ICON_URL, ) i = 0 for i in range(0, i2): embeds[i].set_image(url=embeds_img[i]) i += 1 embeds[0].set_footer(text=f"Page 1 of {len(embeds)}") options = [ disnake.SelectOption(label="Home", value="0", emoji="🟢"), ] await ctx.send(embed=embeds[0], view=Menu(embeds, options)) except Exception as e: embed = disnake.Embed( title="ERROR Stock-Options: Expirations", colour=cfg.COLOR, description=e, ) embed.set_author( name=cfg.AUTHOR_NAME, icon_url=cfg.AUTHOR_ICON_URL, ) await ctx.send(embed=embed, delete_after=30.0)
[ "gamestonk_terminal.stocks.options.yfinance_model.option_expirations", "disnake.Embed", "PIL.Image.open", "discordbot.helpers.autocrop_image", "df2img.save_dataframe", "discordbot.config_discordbot.logger.debug", "disnake.SelectOption", "menus.menu.Menu", "os.remove", "numpy.percentile", "discordbot.config_discordbot.gst_imgur.upload_image" ]
[((860, 901), 'gamestonk_terminal.stocks.options.yfinance_model.option_expirations', 'yfinance_model.option_expirations', (['ticker'], {}), '(ticker)\n', (893, 901), False, 'from gamestonk_terminal.stocks.options import yfinance_model\n'), ((1587, 1617), 'numpy.percentile', 'np.percentile', (["df['strike']", '(1)'], {}), "(df['strike'], 1)\n", (1600, 1617), True, 'import numpy as np\n'), ((1639, 1671), 'numpy.percentile', 'np.percentile', (["df['strike']", '(100)'], {}), "(df['strike'], 100)\n", (1652, 1671), True, 'import numpy as np\n'), ((621, 707), 'discordbot.config_discordbot.logger.debug', 'logger.debug', (['"""opt-chain %s %s %s %s %s"""', 'ticker', 'expiry', 'opt_type', 'min_sp', 'max_sp'], {}), "('opt-chain %s %s %s %s %s', ticker, expiry, opt_type, min_sp,\n max_sp)\n", (633, 707), False, 'from discordbot.config_discordbot import gst_imgur, logger\n'), ((3090, 3141), 'df2img.save_dataframe', 'df2img.save_dataframe', ([], {'fig': 'figp', 'filename': 'imagefile'}), '(fig=figp, filename=imagefile)\n', (3111, 3141), False, 'import df2img\n'), ((3162, 3183), 'PIL.Image.open', 'Image.open', (['imagefile'], {}), '(imagefile)\n', (3172, 3183), False, 'from PIL import Image\n'), ((3204, 3228), 'discordbot.helpers.autocrop_image', 'autocrop_image', (['image', '(0)'], {}), '(image, 0)\n', (3218, 3228), False, 'from discordbot.helpers import autocrop_image\n'), ((3313, 3365), 'discordbot.config_discordbot.gst_imgur.upload_image', 'gst_imgur.upload_image', (['imagefile'], {'title': '"""something"""'}), "(imagefile, title='something')\n", (3335, 3365), False, 'from discordbot.config_discordbot import gst_imgur, logger\n'), ((3725, 3745), 'os.remove', 'os.remove', (['imagefile'], {}), '(imagefile)\n', (3734, 3745), False, 'import os\n'), ((4313, 4369), 'disnake.SelectOption', 'disnake.SelectOption', ([], {'label': '"""Home"""', 'value': '"""0"""', 'emoji': '"""🟢"""'}), "(label='Home', value='0', emoji='🟢')\n", (4333, 4369), False, 'import disnake\n'), ((4494, 4586), 'disnake.Embed', 'disnake.Embed', ([], {'title': '"""ERROR Stock-Options: Expirations"""', 'colour': 'cfg.COLOR', 'description': 'e'}), "(title='ERROR Stock-Options: Expirations', colour=cfg.COLOR,\n description=e)\n", (4507, 4586), False, 'import disnake\n'), ((3532, 3576), 'disnake.Embed', 'disnake.Embed', ([], {'title': 'title', 'colour': 'cfg.COLOR'}), '(title=title, colour=cfg.COLOR)\n', (3545, 3576), False, 'import disnake\n'), ((4427, 4448), 'menus.menu.Menu', 'Menu', (['embeds', 'options'], {}), '(embeds, options)\n', (4431, 4448), False, 'from menus.menu import Menu\n')]