repo_name
stringlengths
8
130
hexsha
sequence
file_path
sequence
code
sequence
apis
sequence
RickyMexx/ML-weather
[ "6d0a1b718b7b946ebb0c5df6ae990de9724ca5a0" ]
[ "weather_class.py" ]
[ "# *************** SETTINGS *************** #\nMODEL_NAME = 'VGG16-TL'\nBATCH_SIZE = 6\n\nEPOCHS = 100\nEXIF_FLAG = 0 # Set on 1 if the program is running for the first time with a dataset D, 0 otherwise.\n\nMODELS_DIR = 'models/'\ntrainingset = \"Train_New/\"\n\ntestset1 = \"Test_New/\"\ntestset2 = \"Weather_Testset/\"\nblindtest = \"BlindTest/\"\nmytestset = \"MyTestSet/\"\n\nimgstype = \"*/*.jpg\"\n\ncsv_file = '1743168.csv'\n\nimg_w = 136\nimg_h = 136\n# **************************************** #\n\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nimport os, glob\nfrom PIL import Image\nimport csv\nimport scikitplot as skplt\n\n# Clear info and warnings, showing errors\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n\n# Fix for TensorFlow2 + CUDA 10.1 + CUDNN 7.6.5 + Python 3.7.5\ngpu_options = tf.compat.v1.GPUOptions(allow_growth=True)\nsession = tf.compat.v1.InteractiveSession(config=tf.compat.v1.ConfigProto(gpu_options=gpu_options))\n\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.models import Sequential, load_model, Model\nfrom tensorflow.keras.layers import Dense, Activation, Dropout, Flatten, Conv2D, MaxPooling2D, AveragePooling2D, Input\nfrom tensorflow.keras.layers import BatchNormalization\nfrom tensorflow.keras import optimizers, applications, callbacks\nfrom tensorflow.keras import backend as K\nfrom tensorflow.keras.applications.inception_v3 import InceptionV3\nfrom tensorflow.keras.optimizers import SGD, RMSprop, Adam\n\nimport numpy as np\nfrom sklearn.metrics import classification_report, confusion_matrix\n\ndef savemodel(model, problem):\n filename = os.path.join(MODELS_DIR, '%s.h5' % problem)\n model.save(filename)\n print(\"\\nModel saved successfully on file %s\\n\" % filename)\n\ndef loadmodel(problem):\n filename = os.path.join(MODELS_DIR, '%s.h5' % problem)\n try:\n model = load_model(filename)\n print(\"\\nModel loaded successfully from file %s\\n\" % filename)\n except OSError:\n print(\"\\nModel file %s not found!!!\\n\" % filename)\n model = None\n return model\n\n# batch_size = 64\ndef RickyNet(input_shape, num_classes):\n model = Sequential()\n\n model.add(AveragePooling2D(pool_size=(3, 3), strides=(3, 3), input_shape=input_shape))\n\n model.add(Conv2D(32, kernel_size=(1, 1), activation=\"relu\", padding=\"valid\"))\n model.add(Conv2D(64, kernel_size=(1, 1), activation=\"relu\", padding=\"valid\"))\n model.add(Conv2D(128, kernel_size=(2, 2), activation=\"relu\", padding=\"valid\"))\n\n model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))\n\n model.add(Flatten())\n\n model.add(Dropout(0.45))\n model.add(Dense(512, activation=\"relu\"))\n\n model.add(Dropout(0.35))\n model.add(Dense(128, activation=\"relu\"))\n\n model.add(Dense(num_classes, activation=\"softmax\"))\n\n model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\n return model\n\ndef delCorruptEXIF(files):\n for f in files:\n if(os.stat(f).st_size):\n print(files.index(f),\" ---- \", f)\n image = Image.open(f).convert('RGB')\n data = list(image.getdata())\n image_without_exif = Image.new(image.mode, image.size)\n image_without_exif.putdata(data)\n image_without_exif.save(f)\n else:\n os.remove(f)\n\ndef processData(batch_size):\n trd = ImageDataGenerator(\n rescale=1. / 255,\n zoom_range=0.3,\n rotation_range=7,\n width_shift_range=0.2,\n height_shift_range=0.2,\n horizontal_flip=True,\n vertical_flip=False,\n validation_split=0.1,\n fill_mode=\"reflect\")\n\n trg = trd.flow_from_directory(\n directory=trainingset,\n target_size=(img_h, img_w),\n color_mode=\"rgb\",\n batch_size=batch_size,\n class_mode=\"categorical\",\n shuffle=True,\n subset='training'\n )\n\n teg = trd.flow_from_directory(\n directory=trainingset,\n target_size=(img_h, img_w),\n color_mode=\"rgb\",\n batch_size=batch_size,\n class_mode=\"categorical\",\n shuffle=False,\n subset='validation'\n )\n\n return trg, teg\n\ndef processTest(batch_size, test_dir):\n ted = ImageDataGenerator(\n rescale=1. / 255)\n\n teg = ted.flow_from_directory(\n directory=test_dir,\n target_size=(img_h, img_w),\n color_mode=\"rgb\",\n batch_size=batch_size,\n class_mode=\"categorical\",\n shuffle=False\n )\n\n return teg\n\ndef plot_history(history, name):\n # Accuracy\n plt.plot(history.history['accuracy'])\n plt.plot(history.history['val_accuracy'])\n plt.title(name+' accuracy')\n plt.ylabel('accuracy')\n plt.xlabel('epoch')\n plt.legend(['train', 'test'], loc='upper left')\n plt.show()\n\n # Loss\n plt.plot(history.history['loss'])\n plt.plot(history.history['val_loss'])\n plt.title(name+' loss')\n plt.ylabel('loss')\n plt.xlabel('epoch')\n plt.legend(['train', 'test'], loc='upper left')\n plt.show()\n\ndef printSinglePredictions(model, teg3, classnames):\n x, y = teg3.next()\n for i in range(len(x)):\n pred = classnames[model.predict(x)[i].argmax()]\n print(\"Class of the image:\", classnames[y[i].argmax()], \"\\t RickyNet prediction:\", pred)\n plt.imshow(x[i])\n plt.show()\n\ndef savePredictions(model, teg3, classnames):\n i = 0\n\n while i <= teg3.batch_index and i < 1:\n data= teg3.next()\n pred = model.predict(data)\n\n for k in range(BATCH_SIZE):\n plt.imshow(data[0][k])\n plt.title(classnames[pred[k].argmax()])\n plt.savefig('PREDICTIONS/img'+str(k)+'.png')\n i+=1\n\ndef solveBlind(model, teg3, classnames):\n i = 0\n lines = [None] * teg3.n\n while i <= teg3.batch_index:\n data = teg3.next()\n pred = model.predict(data)\n\n for k in range(BATCH_SIZE):\n idx = BATCH_SIZE*i + k\n pred_label = classnames[pred[k].argmax()]\n lines[idx] = [pred_label]\n # print(str(int((idx/teg3.n)*100)) + \"%\")\n i += 1\n\n with open(csv_file, \"w\") as fw:\n wr = csv.writer(fw)\n wr.writerows(lines)\n\ndef load_backbone_net(input_shape):\n # define input tensor\n input0 = Input(shape=input_shape)\n\n #model = applications.VGG19(weights=\"imagenet\", include_top=False, input_tensor=input0)\n #model= applications.InceptionV3(weights=\"imagenet\", include_top=False, input_tensor=input0)\n model = applications.vgg16.VGG16(include_top=False, weights='imagenet', input_tensor=input0)\n\n feature_extractor = Model(inputs=input0, outputs=model.output)\n optimizer = 'adam' # alternative 'SGD'\n\n feature_extractor.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['accuracy'])\n\n return feature_extractor\n return model\n\ndef transferNet(feature_extractor, num_classes, output_layer_name, trainable_layers):\n # get the original input layer tensor\n input_t = feature_extractor.get_layer(index=0).input\n\n # set the feature extractor layers as non-trainable\n for idx, layer in enumerate(feature_extractor.layers):\n if layer.name in trainable_layers:\n layer.trainable = True\n else:\n layer.trainable = False\n\n # get the output tensor from a layer of the feature extractor\n output_extractor = feature_extractor.get_layer(name=output_layer_name).output\n\n #output_extractor = MaxPooling2D(pool_size=(4,4))(output_extractor)\n output_extractor = AveragePooling2D(pool_size=(3, 3), strides=(3, 3))(output_extractor)\n\n # flat the output of a Conv layer\n flatten = Flatten()(output_extractor)\n flatten_norm = BatchNormalization()(flatten)\n\n # add a Dense layer\n dense = Dropout(0.4)(flatten_norm)\n dense = Dense(200, activation='relu')(dense)\n dense = BatchNormalization()(dense)\n\n # add a Dense layer\n dense = Dropout(0.4)(dense)\n dense = Dense(100, activation='relu')(dense)\n dense = BatchNormalization()(dense)\n\n # add the final output layer\n dense = BatchNormalization()(dense)\n dense = Dense(num_classes, activation='softmax')(dense)\n\n model = Model(inputs=input_t, outputs=dense, name=\"transferNet\")\n\n model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n\n return model\n\n\nif __name__ == \"__main__\":\n\n # Removing corrupt EXIF data\n if(EXIF_FLAG):\n delCorruptEXIF(glob.glob(trainingset + imgstype))\n\n batch_size = BATCH_SIZE\n train_generator, test_generator = processData(batch_size)\n\n num_samples = train_generator.n\n num_classes = train_generator.num_classes\n input_shape = train_generator.image_shape\n\n classnames = [k for k, v in train_generator.class_indices.items()]\n\n print(\"Image input %s\" % str(input_shape))\n print(\"Classes: %r\" % classnames)\n\n stopping = callbacks.EarlyStopping(monitor='val_accuracy', patience=6)\n\n # ------------------------------- Train the model ----------------------------------- #\n print(\"Generating the model\")\n model = RickyNet(input_shape, num_classes)\n\n print(model.summary())\n\n steps_per_epoch = train_generator.n // train_generator.batch_size\n val_steps = test_generator.n // test_generator.batch_size + 1\n\n try:\n history = model.fit_generator(train_generator, epochs=EPOCHS, verbose=1, callbacks=[stopping],\n steps_per_epoch=steps_per_epoch,\n validation_data=test_generator,\n validation_steps=val_steps)\n except KeyboardInterrupt:\n pass\n\n\n\n savemodel(model, MODEL_NAME)\n \n plot_history(history, MODEL_NAME)\n # ---------------------------------------------------------------------------------- #\n\n\n # -------------------------------- Load a model ------------------------------------ #\n # model = loadmodel(MODEL_NAME)\n # ---------------------------------------------------------------------------------- #\n\n\n # ------------------------------ Evaluation tests ---------------------------------- #\n print(\"\\nAcc and Loss on Test_New:\")\n teg1 = processTest(batch_size, testset1)\n val_steps1 = teg1.n // teg1.batch_size + 1\n # Accuracy + Loss\n loss, acc = model.evaluate_generator(teg1, verbose=1, steps=val_steps1)\n print('Test loss: %f' % loss)\n print('Test accuracy: %f' % acc)\n\n print(\"\\nAcc and Loss on Weather_Test:\")\n teg2 = processTest(batch_size, testset2)\n val_steps2 = teg2.n // teg2.batch_size + 1\n # Accuracy + Loss\n loss, acc = model.evaluate_generator(teg2, verbose=1, steps=val_steps2)\n print('Test loss: %f' % loss)\n print('Test accuracy: %f' % acc)\n\n # Confusion Matrix\n Y_pred = model.predict_generator(teg2, val_steps2)\n y_pred = np.argmax(Y_pred, axis=1)\n skplt.metrics.plot_confusion_matrix(teg2.classes, y_pred, normalize=True, title=\"RickyNet\")\n plt.ylim([3.5, -.5])\n plt.tight_layout()\n plt.show()\n\n # Precision Recall Curve\n skplt.metrics.plot_precision_recall_curve(teg2.classes, Y_pred, title=\"RickyNet\")\n plt.show()\n \n # Precision + Recall + f1-score\n preds = model.predict_generator(teg2, verbose=1, steps=val_steps2)\n Ypred = np.argmax(preds, axis=1)\n Ytest = teg2.classes\n print(classification_report(Ytest, Ypred, labels=None, target_names=classnames, digits=3))\n # ---------------------------------------------------------------------------------- #\n\n\n\n\n # ------------------------------ Transfer learning + Fine tuning ---------------------------------- #\n # load the pre-trained model\n feature_extractor = load_backbone_net(input_shape)\n feature_extractor.summary()\n\n # VGG16\n name_output_extractor = \"block5_pool\"\n trainable_layers = [\"block5_conv3\"]\n\n # build the transfer model\n transfer_model = transferNet(feature_extractor, num_classes, name_output_extractor, trainable_layers)\n transfer_model.summary()\n\n\n steps_per_epoch = train_generator.n // train_generator.batch_size\n val_steps = test_generator.n // test_generator.batch_size + 1\n\n try:\n history_transfer = transfer_model.fit_generator(train_generator, epochs=EPOCHS, verbose=1, callbacks=[stopping], \\\n steps_per_epoch=steps_per_epoch, \\\n validation_data=test_generator, \\\n validation_steps=val_steps)\n except KeyboardInterrupt:\n pass\n\n savemodel(transfer_model, MODEL_NAME)\n plot_history(history_transfer, MODEL_NAME)\n # ------------------------------------------------------------------------------------------------- #\n\n # -------------------------------- Load a TL model ------------------------------------ #\n # transfer_model = loadmodel(MODEL_NAME)\n # ------------------------------------------------------------------------------------- #\n\n # ------------------------------ TF Evaluation tests ---------------------------------- #\n print(\"\\nAcc and Loss on Test_New:\")\n teg1 = processTest(batch_size, testset1)\n val_steps1 = teg1.n // teg1.batch_size + 1\n # Accuracy + Loss\n loss, acc = transfer_model.evaluate_generator(teg1, verbose=1, steps=val_steps1)\n print('Test loss: %f' % loss)\n print('Test accuracy: %f' % acc)\n\n print(\"\\nAcc and Loss on Weather_Test:\")\n teg2 = processTest(batch_size, testset2)\n val_steps2 = teg2.n // teg2.batch_size + 1\n # Accuracy + Loss\n loss, acc = transfer_model.evaluate_generator(teg2, verbose=1, steps=val_steps2)\n print('Test loss: %f' % loss)\n print('Test accuracy: %f' % acc)\n\n # Precision + Recall + f1-score\n preds = transfer_model.predict_generator(teg2, verbose=1, steps=val_steps2)\n Ypred = np.argmax(preds, axis=1)\n Ytest = teg2.classes\n print(classification_report(Ytest, Ypred[:teg2.n], labels=None, target_names=classnames, digits=3))\n\n # Confusion Matrix\n Y_pred = transfer_model.predict_generator(teg2, val_steps2)\n y_pred = np.argmax(Y_pred, axis=1)\n skplt.metrics.plot_confusion_matrix(teg2.classes, y_pred[:teg2.n], normalize=True, title=MODEL_NAME)\n plt.ylim([3.5, -.5])\n plt.tight_layout()\n plt.show()\n\n # Precision Recall Curve\n skplt.metrics.plot_precision_recall_curve(teg2.classes, Y_pred[:teg2.n], title=MODEL_NAME)\n plt.show()\n # ------------------------------------------------------------------------------------ #\n\n # ---------------------------------- Blind test -------------------------------------- #\n tegb = processTest(batch_size, blindtest)\n solveBlind(transfer_model, tegb, classnames)\n # ------------------------------------------------------------------------------------ #\n\n" ]
[ [ "tensorflow.keras.layers.Flatten", "sklearn.metrics.classification_report", "tensorflow.keras.preprocessing.image.ImageDataGenerator", "matplotlib.pyplot.tight_layout", "tensorflow.keras.models.Model", "matplotlib.pyplot.imshow", "matplotlib.pyplot.ylabel", "tensorflow.keras.callbacks.EarlyStopping", "tensorflow.keras.layers.Conv2D", "matplotlib.pyplot.plot", "tensorflow.keras.layers.AveragePooling2D", "matplotlib.pyplot.title", "tensorflow.keras.layers.BatchNormalization", "tensorflow.keras.layers.Dense", "tensorflow.keras.layers.Dropout", "tensorflow.compat.v1.GPUOptions", "tensorflow.keras.layers.MaxPooling2D", "numpy.argmax", "matplotlib.pyplot.ylim", "tensorflow.keras.models.Sequential", "matplotlib.pyplot.legend", "tensorflow.compat.v1.ConfigProto", "tensorflow.keras.models.load_model", "tensorflow.keras.applications.vgg16.VGG16", "matplotlib.pyplot.show", "matplotlib.pyplot.xlabel", "tensorflow.keras.layers.Input" ] ]
pkozakowski/trax
[ "31215c378017347e0b66ba51c37cd3cbedf60b17" ]
[ "trax/supervised/trainer_lib_test.py" ]
[ "# coding=utf-8\n# Copyright 2021 The Trax Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Tests for trax.supervised.trainer_lib.\"\"\"\n\nimport functools\nimport os\n\nfrom absl.testing import absltest\nfrom absl.testing import parameterized\nfrom jax import test_util # pylint: disable=unused-import\nfrom jax.config import config\nfrom jax.lib import xla_bridge\nimport tensorflow.compat.v2 as tf\nfrom trax import fastmath\nfrom trax import layers as tl\nfrom trax import models\nfrom trax import optimizers as trax_opt\nfrom trax import shapes as trax_shapes\nfrom trax import test_utils\nfrom trax.data import inputs as inputs_lib\nfrom trax.fastmath import numpy as jnp\nfrom trax.supervised import lr_schedules as lr\nfrom trax.supervised import trainer_lib\nfrom trax.tf_numpy import extensions as npe\nfrom trax.tf_numpy import numpy as tf_np\n\n\n\ndef _test_inputs(n_classes, with_weights=False, input_shape=(6, 6, 3)):\n \"\"\"Make trainer_lib.inputs.Inputs.\"\"\"\n batch_size = 2 * xla_bridge.device_count()\n\n def input_stream(n_devices):\n del n_devices\n key = fastmath.random.get_prng(0)\n while True:\n keys = fastmath.random.split(key, 4)\n key = keys[0]\n inputs = fastmath.random.uniform(\n keys[1], [batch_size] + list(input_shape))\n targets = fastmath.random.randint(\n keys[2], [batch_size], dtype=jnp.int32, minval=0, maxval=n_classes)\n weights = fastmath.random.uniform(keys[3], [batch_size])\n if with_weights:\n yield inputs, targets, weights\n else:\n yield inputs, targets\n\n def input_stream_masked(n_devices):\n return inputs_lib.add_loss_weights(input_stream(n_devices))\n\n return inputs_lib.Inputs(input_stream_masked)\n\n\ndef _test_inputs_lm(vocab_size, seq_len, per_device_batch_size=2):\n \"\"\"Make trainer_lib.inputs.Inputs for language model.\"\"\"\n batch_size = per_device_batch_size * xla_bridge.device_count()\n\n def input_stream(_):\n def make_batch(key):\n return fastmath.random.randint(\n key, [batch_size, seq_len], dtype=jnp.int32, minval=0,\n maxval=vocab_size)\n key = fastmath.random.get_prng(0)\n while True:\n keys = fastmath.random.split(key, 3)\n key = keys[0]\n inputs = make_batch(keys[1])\n targets = make_batch(keys[2])\n yield inputs, targets\n\n def input_stream_masked(n_devices):\n return inputs_lib.add_loss_weights(input_stream(n_devices))\n\n return inputs_lib.Inputs(input_stream_masked)\n\n\n\nBACKENDS = [fastmath.Backend.JAX, fastmath.Backend.TFNP]\n\n\ndef short_name(b):\n if b == fastmath.Backend.JAX:\n return 'jax'\n else:\n return 'tf'\n\n\ndef opt_name(opt):\n if opt is None:\n return 'None'\n return opt.__name__\n\n\ndef _pure_lsh_self_attention_fn(n_chunks_after=0):\n return functools.partial(\n tl.PureLSHSelfAttentionWrapper,\n attention_dropout=0.1,\n chunk_len=16,\n n_buckets=[32, 32],\n n_chunks_after=n_chunks_after,\n n_chunks_before=1,\n n_hashes=2,\n n_parallel_heads=1,\n max_length_for_buckets=1024,\n predict_drop_len=128,\n predict_mem_len=1024,\n num_weights=2,\n bias=False,\n pure_lsh_implementation=tl.PureLSHSelfAttention,\n )\n\n\ndef _mixed_lsh_self_attention_fn(n_chunks_after=0):\n return functools.partial(\n tl.PureLSHSelfAttentionWrapper,\n attention_dropout=0.1,\n chunk_len=16,\n n_buckets=[32, 32],\n n_chunks_after=n_chunks_after,\n n_chunks_before=1,\n n_hashes=2,\n n_parallel_heads=1,\n max_length_for_buckets=1024,\n predict_drop_len=128,\n predict_mem_len=1024,\n num_weights=2,\n bias=False,\n pure_lsh_implementation=tl.MixedLSHSelfAttention,\n )\n\n\nclass TraxTest(parameterized.TestCase):\n\n def __init__(self, methodName='runTest'): # pylint: disable=invalid-name\n super().__init__(methodName)\n if npe.tpu_devices():\n # Initialize TPU for TF\n resolver = tf.distribute.cluster_resolver.TPUClusterResolver(tpu='local')\n tf.tpu.experimental.initialize_tpu_system(resolver)\n\n def setUp(self):\n super().setUp()\n test_utils.ensure_flag('test_tmpdir')\n self._old_is_allow_float64 = tf_np.is_allow_float64()\n tf_np.set_allow_float64(False)\n\n def tearDown(self):\n tf_np.set_allow_float64(self._old_is_allow_float64)\n super().tearDown()\n\n def _test_train_eval_predict(self, backend, model_name='Simple',\n optimizer=None):\n with fastmath.use_backend(backend):\n # Prepare model and inputs\n steps = 2\n eval_steps = 2\n\n if model_name == 'Simple':\n n_classes = 4\n # Adds Dropout and BatchNorm to test state handling.\n def model_fn(mode='train'):\n return tl.Serial(\n tl.Dropout(mode=mode, rate=0.1),\n tl.BatchNorm(mode=mode),\n models.MLP(layer_widths=(16, 16, n_classes), mode=mode))\n inputs = _test_inputs(n_classes)\n n_in = 1\n elif model_name == 'Resnet50':\n n_classes = 4\n model_fn = models.Resnet50\n inputs = _test_inputs(n_classes, input_shape=(224, 224, 3))\n n_in = 1\n elif model_name == 'Transformer':\n vocab_size = 32\n seq_len = 16\n inputs = _test_inputs_lm(vocab_size, seq_len)\n model_fn = functools.partial(\n models.Transformer,\n input_vocab_size=vocab_size)\n n_in = 2\n else:\n raise ValueError('Unrecognized model name: ' + model_name)\n\n kwargs = {}\n if optimizer is not None:\n kwargs['optimizer'] = optimizer\n\n # Train and evaluate\n output_dir = self.create_tempdir().full_path\n loop = trainer_lib.train(\n output_dir,\n model=model_fn,\n inputs=inputs,\n steps=steps,\n eval_steps=eval_steps,\n eval_frequency=1, # eval at every step.\n **kwargs)\n\n # Assert total train steps\n self.assertEqual(steps, loop.step)\n\n inputs = inputs.train_stream(1)\n\n # Predict with final weights\n model = model_fn()\n weights = loop.model.weights\n state = loop.model.state\n model(next(inputs)[:n_in], weights=weights, state=state)\n\n # Predict with weights loaded from file.\n model = model_fn()\n model.init_from_file(os.path.join(output_dir, 'model.pkl.gz'))\n model(next(inputs)[:n_in])\n\n @parameterized.named_parameters(\n ('_%s_%s_%s' % (short_name(backend), model_name, opt_name(opt)), # pylint: disable=g-complex-comprehension\n backend, model_name, opt)\n for backend, configs in [\n (fastmath.Backend.JAX, [('Simple', None)]),\n (fastmath.Backend.TFNP, [('Simple', None),\n ('Resnet50', trax_opt.Momentum),\n ('Transformer', trax_opt.Adam)])]\n for model_name, opt in configs)\n def test_train_eval_predict(self, backend, model_name, opt):\n self._test_train_eval_predict(backend, model_name, opt)\n\n @parameterized.parameters(BACKENDS)\n def test_train_eval_predict_sm3(self, backend):\n self._test_train_eval_predict(backend, 'Simple', trax_opt.SM3)\n\n @parameterized.parameters(BACKENDS)\n def test_train_restart(self, backend):\n with fastmath.use_backend(backend):\n # Prepare model and inputs\n n_classes = 4\n steps = 2\n eval_steps = 2\n model_fn = functools.partial(models.MLP,\n layer_widths=(16, 16, n_classes))\n inputs = _test_inputs(n_classes)\n\n # Train and evaluate\n output_dir = self.create_tempdir().full_path\n trainer_lib.train(\n output_dir,\n model=model_fn,\n inputs=inputs,\n steps=steps,\n eval_steps=eval_steps,\n eval_frequency=1)\n\n # Restart training\n loop = trainer_lib.train(\n output_dir,\n model=model_fn,\n inputs=inputs,\n steps=(2 * steps),\n eval_steps=eval_steps,\n eval_frequency=1)\n\n # Assert total train steps\n self.assertEqual(loop.step, 2 * steps)\n\n @parameterized.parameters(BACKENDS)\n def test_train_permanent_checkpoints(self, backend):\n with fastmath.use_backend(backend):\n # Prepare model and inputs\n n_classes = 4\n steps = 5\n eval_steps = 2\n model_fn = functools.partial(models.MLP,\n layer_widths=(16, 16, n_classes))\n inputs = _test_inputs(n_classes)\n\n # Train and evaluate\n output_dir = self.create_tempdir().full_path\n\n # Steps 1 -> 5\n loop = trainer_lib.train(\n output_dir,\n model=model_fn,\n inputs=inputs,\n steps=steps,\n eval_steps=eval_steps,\n eval_frequency=1,\n permanent_checkpoint_frequency=2)\n\n # Steps 6 -> 10\n loop = trainer_lib.train(\n output_dir,\n model=model_fn,\n inputs=inputs,\n steps=(2 * steps),\n eval_steps=eval_steps,\n eval_frequency=1,\n permanent_checkpoints_at=[7, 8, 10])\n\n path = os.path.join(output_dir, 'model.pkl.gz')\n self.assertTrue(tf.io.gfile.exists(path))\n\n for step in range(11):\n filename = 'model_{}.pkl.gz'.format(step)\n path = os.path.join(output_dir, filename)\n if step in [1, 2, 4, 7, 8, 10]:\n self.assertTrue(tf.io.gfile.exists(path),\n msg='No model for step: {} in dir {}.'.format(\n step, tf.io.gfile.listdir(output_dir)))\n else:\n self.assertFalse(tf.io.gfile.exists(path),\n msg='Model for step: {} in dir {}.'.format(\n step, tf.io.gfile.listdir(output_dir)))\n\n # Assert total train steps\n self.assertEqual(loop.step, 10)\n\n @parameterized.parameters(BACKENDS)\n def test_train_restart_with_same_steps(self, backend):\n with fastmath.use_backend(backend):\n # Prepare model and inputs\n n_classes = 4\n steps = 2\n eval_steps = 2\n model_fn = functools.partial(models.MLP,\n layer_widths=(16, 16, n_classes))\n inputs = _test_inputs(n_classes)\n\n # Train and evaluate\n output_dir = self.create_tempdir().full_path\n trainer_lib.train(\n output_dir,\n model=model_fn,\n inputs=inputs,\n steps=steps,\n eval_steps=eval_steps,\n eval_frequency=1)\n\n # Restart training\n loop = trainer_lib.train(\n output_dir,\n model=model_fn,\n inputs=inputs,\n steps=steps,\n eval_steps=eval_steps,\n eval_frequency=1)\n\n # Assert total train steps\n self.assertEqual(loop.step, steps)\n\n def test_train_with_pure_lsh_attention(self, backend=fastmath.Backend.JAX):\n with fastmath.use_backend(backend):\n # Prepare model and inputs\n def model(mode='train'):\n return models.Reformer2(\n mode=mode,\n d_model=16,\n d_ff=16,\n n_heads=2,\n dropout=0.05,\n n_decoder_layers=1,\n n_encoder_layers=1,\n input_vocab_size=256,\n encoder_attention_type=_pure_lsh_self_attention_fn(),\n encoder_decoder_attention_type=_pure_lsh_self_attention_fn(),\n )\n\n max_len = 128\n inputs = _test_inputs_lm(vocab_size=256, seq_len=max_len)\n\n steps = 1\n eval_steps = 1\n\n # Train and evaluate\n output_dir = self.create_tempdir().full_path\n trainer_lib.train(\n output_dir,\n model=model,\n inputs=inputs,\n steps=steps,\n eval_steps=eval_steps,\n eval_frequency=1)\n\n # Read checkpoint\n model_file = os.path.join(output_dir, 'model.pkl.gz')\n\n shape11 = trax_shapes.ShapeDtype((1, 1), dtype=jnp.int32)\n shape1l = trax_shapes.ShapeDtype((1, max_len), dtype=jnp.int32)\n\n model_predict = model(mode='predict')\n model_predict.init_from_file(\n model_file, weights_only=True, input_signature=(shape1l, shape11))\n\n def test_train_with_mixed_lsh_attention(self, backend=fastmath.Backend.JAX):\n with fastmath.use_backend(backend):\n # Prepare model and inputs\n\n def model(mode='train'):\n return models.Reformer2(\n mode=mode,\n d_model=16,\n d_ff=16,\n n_heads=2,\n dropout=0.05,\n n_decoder_layers=1,\n n_encoder_layers=1,\n input_vocab_size=256,\n encoder_attention_type=_mixed_lsh_self_attention_fn(),\n encoder_decoder_attention_type=_mixed_lsh_self_attention_fn(),\n )\n\n max_len = 128\n inputs = _test_inputs_lm(vocab_size=256, seq_len=max_len)\n\n steps = 1\n eval_steps = 1\n\n # Train and evaluate\n output_dir = self.create_tempdir().full_path\n trainer_lib.train(\n output_dir,\n model=model,\n inputs=inputs,\n steps=steps,\n eval_steps=eval_steps,\n eval_frequency=1)\n\n # Read checkpoint\n model_file = os.path.join(output_dir, 'model.pkl.gz')\n\n shape11 = trax_shapes.ShapeDtype((1, 1), dtype=jnp.int32)\n shape1l = trax_shapes.ShapeDtype((1, max_len), dtype=jnp.int32)\n\n model_predict = model(mode='predict')\n model_predict.init_from_file(model_file, weights_only=True,\n input_signature=(shape1l, shape11))\n\n @parameterized.parameters(BACKENDS)\n def test_train_fills_in_missing_eval_metrics(self, backend):\n with fastmath.use_backend(backend):\n # Prepare model and inputs\n n_classes = 4\n steps = 2\n eval_steps = 2\n model_fn = functools.partial(models.MLP, layer_widths=(16, 16, n_classes))\n inputs = _test_inputs(n_classes)\n additional_eval_stream = trainer_lib.NamedStream(\n # deliberately duplicating eval data\n stream=inputs.eval_stream(1),\n name='additional_eval_task')\n\n # Train and evaluate\n output_dir = self.create_tempdir().full_path\n loop = trainer_lib.train(\n output_dir,\n model=model_fn,\n inputs=inputs,\n steps=steps,\n eval_steps=eval_steps,\n eval_frequency=1,\n additional_eval_streams=[additional_eval_stream])\n\n self.assertLen(loop.eval_tasks, 2)\n eval_task_1, eval_task_2 = loop.eval_tasks\n self.assertCountEqual(eval_task_1.metrics, eval_task_2.metrics)\n self.assertCountEqual(eval_task_1.metric_names, eval_task_2.metric_names)\n\n @parameterized.named_parameters(\n ('_%s' % short_name(backend), backend)\n for backend in BACKENDS)\n def test_train_with_weights(self, backend):\n with fastmath.use_backend(backend):\n # Prepare model and inputs\n n_classes = 4\n steps = 2\n eval_steps = 2\n model_fn = functools.partial(models.MLP,\n layer_widths=(16, 16, n_classes))\n inputs = _test_inputs(n_classes, with_weights=True)\n\n # Train and evaluate\n output_dir = self.create_tempdir().full_path\n state = trainer_lib.train(\n output_dir,\n model=model_fn,\n inputs=inputs,\n steps=steps,\n eval_steps=eval_steps)\n\n # Assert total train steps\n self.assertEqual(state.step, steps)\n\n @parameterized.parameters(BACKENDS)\n def test_reset_twice(self, backend):\n with fastmath.use_backend(backend):\n n_classes = 4\n model_fn = functools.partial(models.MLP,\n layer_widths=(16, 16, n_classes))\n inputs = _test_inputs(n_classes)\n\n trainer = trainer_lib.Trainer(\n model=model_fn,\n loss_fn=tl.WeightedCategoryCrossEntropy(),\n optimizer=trax_opt.SM3,\n lr_schedule=lr.multifactor(),\n inputs=inputs,\n )\n\n output_dir1 = self.create_tempdir(name='output_dir1').full_path\n trainer.reset(output_dir1)\n trainer.evaluate(1)\n output_dir2 = self.create_tempdir(name='output_dir2').full_path\n trainer.reset(output_dir2)\n trainer.evaluate(1)\n\n def test_tf_xla_forced_compile(self):\n # TODO(wangpeng): re-enable this test\n self.skipTest('Needs --config=cuda to pass this test')\n old_flag = fastmath.tf.tf_xla_forced_compile_enabled()\n fastmath.tf.set_tf_xla_forced_compile(True)\n self._test_train_eval_predict('tf')\n fastmath.tf.set_tf_xla_forced_compile(old_flag)\n\n def test_no_int32_or_uint32_returned(self):\n \"\"\"Tests that Trainer._jit_update_fn doesn't return int32 or uint32.\n\n TF pins int32/uint32 tensors to CPU, which will cause XLA-forced-compiled\n computation to copy int32/uint32 outputs to CPU. This test makes sure that\n won't happen.\n \"\"\"\n with fastmath.use_backend(fastmath.Backend.TFNP):\n n_classes = 1001\n model_fn = functools.partial(models.Resnet50,\n n_output_classes=n_classes)\n inputs = _test_inputs(n_classes, input_shape=(224, 224, 3))\n trainer = trainer_lib.Trainer(\n model=model_fn,\n loss_fn=tl.WeightedCategoryCrossEntropy(),\n optimizer=trax_opt.SM3,\n lr_schedule=lr.multifactor(),\n inputs=inputs,\n )\n output_dir = self.create_tempdir().full_path\n trainer.reset(output_dir)\n trainer.train_epoch(1, 0)\n # Those are the things returned by Trainer._jit_update_fn\n arrays = (trainer._opt_state.weights, trainer._opt_state.slots,\n trainer._model_state, trainer._rngs)\n arrays = tf.nest.flatten(arrays)\n for x in arrays:\n if isinstance(x, jnp.ndarray) and (x.dtype == jnp.int32 or\n x.dtype == jnp.uint32):\n raise ValueError('Found an array of int32 or uint32: %s' % x)\n\n\n\nclass EpochsTest(absltest.TestCase):\n\n def test_cuts_epoch_when_total_steps_reached(self):\n epoch_steps = trainer_lib.epochs(\n total_steps=5, steps_to_skip=0, epoch_steps=[1, 2, 3])\n self.assertEqual(list(epoch_steps), [1, 2, 2])\n\n def test_skips_full_epoch(self):\n epoch_steps = trainer_lib.epochs(\n total_steps=4, steps_to_skip=2, epoch_steps=[2, 2])\n self.assertEqual(list(epoch_steps), [2])\n\n def test_skips_part_of_epoch(self):\n epoch_steps = trainer_lib.epochs(\n total_steps=4, steps_to_skip=1, epoch_steps=[2, 2])\n self.assertEqual(list(epoch_steps), [1, 2])\n\n\nif __name__ == '__main__':\n config.config_with_absl()\n tf.compat.v1.enable_eager_execution()\n absltest.main()\n" ]
[ [ "tensorflow.compat.v2.compat.v1.enable_eager_execution", "tensorflow.compat.v2.tpu.experimental.initialize_tpu_system", "tensorflow.compat.v2.nest.flatten", "tensorflow.compat.v2.io.gfile.listdir", "tensorflow.compat.v2.distribute.cluster_resolver.TPUClusterResolver", "tensorflow.compat.v2.io.gfile.exists" ] ]
liyongsheng-tech/pkuseg
[ "e5bd8a4f7e2589a3c132c291433abd3be5c69dba" ]
[ "libs/networks/builder.py" ]
[ "import importlib\n\nimport torch\nfrom torch import nn\nfrom torch.nn import functional as F\n\nfrom heads import FCNHead\n\n\nclass ModelBuilder(nn.Module):\n def __init__(self, net_config, aux_config=None):\n super(ModelBuilder, self).__init__()\n\n num_classes = net_config['num_classes']\n out_planes = int(net_config['out_planes'])\n self.use_aux = aux_config is not None\n\n if self.use_aux:\n in_planes = int(aux_config['in_planes'])\n out_planes = int(aux_config['out_planes'])\n self.aux = FCNHead(in_planes, out_planes)\n self.aux_clsf = nn.Conv2d(out_planes, num_classes)\n\n self.encoder = self._build_module(net_config, 'encoder')\n self.seg_head = self._build_module(net_config, 'seg_head')\n self.decoder = self._build_module(net_config, 'decoder')\n assert self.encoder is not None, 'There must be an encoder!'\n\n if out_planes >= 256:\n self.clsf = nn.Sequential(\n nn.Dropout2d(0.1),\n nn.Conv2d(out_planes, num_classes, 1))\n else:\n self.clsf = nn.Conv2d(out_planes, num_classes)\n\n\n def _build_module(self, net_config, key):\n cls_config = net_config.get(key, None)\n if cls_config is None:\n return None\n\n cls_type = cls_config['type']\n mod_name, cls_name = cls_type.rsplit('.', 1)\n mod = importlib.import_module(mod_name)\n cls = getattr(mod, cls_name)\n return cls(**cls_config.get('args', dict()))\n\n def forward(self, x):\n h, w = x.size()[-2:]\n xs = self.encoder(x)\n\n if self.seg_head is not None:\n xs[-1] = self.seg_head(xs[-1])\n\n if self.decoder is not None:\n x = self.decoder(xs)\n else:\n x = xs[-1]\n\n pred = self.clsf(x)\n pred = F.interpolate(pred, size=(h, w), mode='bilinear', \n align_corners=True)\n\n if not self.use_aux:\n return [pred, None]\n\n aux = self.aux(xs[-2])\n aux = self.aux_clsf(aux)\n aux = F.interpolate(aux, size=(h, w), mode='bilinear', \n align_corners=True)\n\n return [pred, aux]\n\n\nif __name__ == '__main__':\n net_config = {\n 'num_classes': 19,\n 'out_planes': 512,\n 'encoder': {\n 'type': 'resnet.resnet50',\n },\n 'seg_head': {\n 'type': 'heads.ASPP',\n 'args': {\n 'in_planes': 2048,\n }\n },\n }\n model = ModelBuilder(net_config)\n print(model)\n input = torch.Tensor(2, 3, 513, 513)\n outputs = model(input)\n for output in outputs:\n if output is not None:\n print(output.size())\n\n" ]
[ [ "torch.nn.functional.interpolate", "torch.nn.Conv2d", "torch.nn.Dropout2d", "torch.Tensor" ] ]
Eccsx/CVRP-Genetic-Tournament
[ "8b428ec8ef976489bd701e2d11253249fe46ff88" ]
[ "src/population.py" ]
[ "from math import floor\nfrom numpy import delete, fliplr\nfrom itertools import chain\nfrom random import random, sample\nfrom copy import deepcopy\nfrom chromosome import fitness, pmx, obx\nfrom utils import create_shuffle_array\nfrom genetic import POPULATION_SIZE, PROBABILITY_ELITISM, \\\n NUMBER_TOURNAMENT_SELECTION, CROSSOVER_METHOD, PROBABILITY_MUTATION, \\\n MUTATION_METHOD\n\n\ndef create_population(\n vehicles_capacity,\n customers\n):\n # Initialization\n chromosomes = [\n create_shuffle_array(len(customers)) for _ in range(POPULATION_SIZE)\n ]\n\n # Chromosomes validity\n chromosomes = separate_by_capacity(\n chromosomes,\n vehicles_capacity,\n customers\n )\n\n return chromosomes\n\n\ndef separate_by_capacity(\n chromosomes,\n vehicles_capacity,\n customers\n):\n new_chromosomes = []\n\n for chromosome in chromosomes:\n new_chromosome = []\n gene = []\n total_demand = 0\n\n for node in chromosome:\n demand = customers[node][2]\n\n # We only care about the chromosome parts respecting\n # the capacity constraint\n if (total_demand + demand) > vehicles_capacity:\n # Add new gene to the new chromosome\n new_chromosome.append(gene.copy())\n\n # Reset total demand\n total_demand = 0\n\n # Clear gene\n del gene[:]\n\n # Update total demand\n total_demand += demand\n\n # Add node to gene\n gene.append(node)\n\n # Append new gene to new chromosome\n new_chromosome.append(gene.copy())\n\n new_chromosomes.append(new_chromosome)\n\n return new_chromosomes\n\n\ndef elistism(\n chromosomes,\n customers,\n COORDINATES_DEPOT\n):\n elites = []\n\n while len(chromosomes) < floor(PROBABILITY_ELITISM * len(chromosomes)) + 1:\n best = chromosomes[0]\n pos = 0\n for i in range(len(chromosomes)):\n if fitness(chromosomes[i], customers, COORDINATES_DEPOT) \\\n < fitness(best, customers, COORDINATES_DEPOT):\n pos = i\n best = chromosomes[i]\n elites.append(\n list(chain.from_iterable(best.copy()))\n )\n chromosomes = delete(chromosomes, [pos], axis=0)\n\n return elites\n\n\ndef crossover(\n chromosomes,\n customers,\n vehicles_capacity,\n COORDINATES_DEPOT\n):\n crossed_chromosomes = []\n chromosomes_copy = chromosomes.copy()\n\n # Elitism\n crossed_chromosomes = elistism(chromosomes, customers, COORDINATES_DEPOT)\n\n # Number of chromosomes to create\n num_chromosomes = len(chromosomes)\n\n if num_chromosomes % 2 == 0:\n num_chromosomes = int(num_chromosomes / 2)\n else:\n crossed_chromosomes.append((list(chain.from_iterable(chromosomes[0]))))\n delete(chromosomes, 0)\n num_chromosomes = int((num_chromosomes - 1) / 2)\n\n # Breeding process\n for _ in range(num_chromosomes):\n positions = sample(range(0, len(chromosomes_copy)), 2)\n\n # Crossover\n if CROSSOVER_METHOD == 'RANDOM':\n if random() >= 0.5:\n aa, bb = pmx(\n deepcopy(chromosomes_copy[positions[0]]),\n deepcopy(chromosomes_copy[positions[1]]),\n len(customers)\n )\n else:\n aa, bb = obx(\n deepcopy(chromosomes_copy[positions[0]]),\n deepcopy(chromosomes_copy[positions[1]]),\n len(customers)\n )\n\n elif CROSSOVER_METHOD == 'PMX':\n aa, bb = pmx(\n deepcopy(chromosomes_copy[positions[0]]),\n deepcopy(chromosomes_copy[positions[1]]),\n len(customers)\n )\n elif CROSSOVER_METHOD == 'OBX':\n aa, bb = obx(\n deepcopy(chromosomes_copy[positions[0]]),\n deepcopy(chromosomes_copy[positions[1]]),\n len(customers)\n )\n\n # append selected\n crossed_chromosomes.append(aa.copy())\n crossed_chromosomes.append(bb.copy())\n\n # return\n return separate_by_capacity(\n crossed_chromosomes,\n vehicles_capacity,\n customers\n )\n\n\ndef tournament_selection(\n chromosomes,\n customers,\n COORDINATES_DEPOT\n):\n selection = []\n\n # Select by elitism\n while len(selection) < floor(PROBABILITY_ELITISM * len(chromosomes)) + 1:\n # Take first chromosome as reference\n best = chromosomes[0]\n index = 0\n\n # Compare all chromosomes to keep the best one\n for i in range(len(chromosomes)):\n if fitness(chromosomes[i], customers, COORDINATES_DEPOT) \\\n < fitness(best, customers, COORDINATES_DEPOT):\n index = i\n best = chromosomes[i]\n\n selection.append(best.copy())\n chromosomes = delete(chromosomes, [index], axis=0)\n\n # Gene recombination\n for _ in range(0, len(chromosomes)):\n\n # Pick random positions\n positions = sample(\n range(0, len(chromosomes)),\n NUMBER_TOURNAMENT_SELECTION\n )\n\n # Define genes to compare\n compare = chromosomes[positions[0]]\n\n # Keep best genes\n for position in positions:\n if fitness(chromosomes[position], customers, COORDINATES_DEPOT) \\\n < fitness(compare, customers, COORDINATES_DEPOT):\n compare = chromosomes[position]\n\n selection.append(compare)\n\n return selection\n\n\ndef mutation(\n chromosomes,\n customers,\n vehicles_capacity,\n COORDINATES_DEPOT\n):\n mutated_chromosomes = []\n\n # Elitism\n while len(mutated_chromosomes) \\\n < floor(PROBABILITY_ELITISM * len(chromosomes)) + 1:\n best = chromosomes[0]\n pos = 0\n for i in range(len(chromosomes)):\n if fitness(chromosomes[i], customers, COORDINATES_DEPOT) \\\n < fitness(best, customers, COORDINATES_DEPOT):\n pos = i\n best = chromosomes[i]\n\n mutated_chromosomes.append(list(chain.from_iterable(best.copy())))\n chromosomes = delete(chromosomes, [pos], axis=0)\n\n # Number of chromosomes to create\n num_chromosomes = len(chromosomes)\n\n # Mutate chromosomes\n for a in range(num_chromosomes):\n if random() <= PROBABILITY_MUTATION:\n if MUTATION_METHOD == 'RANDOM':\n if random() <= 0.5:\n pass\n else:\n pass\n elif MUTATION_METHOD == 'EXC':\n # get cut positions\n positions = sample(range(0, len(customers)), 2)\n\n # sort postions\n positions.sort()\n\n # concatenate\n concatenated_chromosome = \\\n list(chain.from_iterable(chromosomes[a]))\n\n # get and reverse range\n aux = concatenated_chromosome[positions[0]]\n\n # set reversed interval\n concatenated_chromosome[positions[0]] \\\n = concatenated_chromosome[positions[1]]\n\n # set seconda value\n concatenated_chromosome[positions[1]] = aux\n\n # set new value\n mutated_chromosomes.append(concatenated_chromosome)\n\n # if reverse\n elif MUTATION_METHOD == 'INV':\n # get cut positions\n positions = sample(range(1, len(customers) - 1), 2)\n\n # sort postions\n positions.sort()\n\n # concatenate\n concatenated_chromosome = \\\n list(chain.from_iterable(chromosomes[a]))\n\n # get and reverse range\n aux = concatenated_chromosome[positions[0]:(positions[1] + 1)]\n\n # set seconda value\n concatenated_chromosome[positions[0]:(\n positions[1] + 1)], = fliplr([aux])\n\n # set new value\n mutated_chromosomes.append(concatenated_chromosome)\n else:\n mutated_chromosomes.append(\n list(chain.from_iterable(chromosomes[a]))\n )\n\n # return\n return separate_by_capacity(\n mutated_chromosomes,\n vehicles_capacity,\n customers\n )\n" ]
[ [ "numpy.fliplr", "numpy.delete" ] ]
segasai/imf
[ "9a33b9e68b0af677dab86511e343d6099d9ea530" ]
[ "imf/tests/test_distributions.py" ]
[ "import numpy as np\nimport scipy.interpolate\nfrom .. import distributions as D\nnp.random.seed(1)\n\n\ndef sampltest(distr, left=None, right=None, bounds=None):\n\n # check that mean and stddev from the generated sample\n # match what we get from integrating the PDF\n\n def FF1(x):\n return distr.pdf(x) * x\n\n def FF2(x):\n return distr.pdf(x) * x**2\n\n if left is None:\n left = 0\n if right is None:\n right = np.inf\n if bounds is None:\n mom1, _ = scipy.integrate.quad(FF1, left, right)\n mom2, _ = scipy.integrate.quad(FF2, left, right)\n else:\n mom1, mom2 = 0, 0\n for curb in bounds:\n cmom1, _ = scipy.integrate.quad(FF1, curb[0], curb[1])\n cmom2, _ = scipy.integrate.quad(FF2, curb[0], curb[1])\n mom1 += cmom1\n mom2 += cmom2\n\n std = np.sqrt(mom2 - mom1**2)\n assert (mom2 > mom1**2)\n N = int(1e6)\n samps = distr.rvs(N)\n assert ((samps.mean() - mom1) < 5 * std / np.sqrt(N))\n assert ((samps.std() - std) < 20 * std / np.sqrt(2 * (N - 1)))\n\n\ndef ppftest(distr):\n # test that ppf is inverse of cdf\n xs = np.random.uniform(0, 1, size=100)\n eps = 1e-5\n assert (np.all(np.abs(distr.cdf(distr.ppf(xs)) - xs) < eps))\n # test on scalar\n assert (np.abs(distr.cdf(distr.ppf(xs[0])) - xs[0]) < eps)\n assert (np.isnan(distr.ppf(-0.1)))\n assert (np.isnan(distr.ppf(1.1)))\n\n\ndef test_lognorm():\n ln = D.LogNormal(1, 1)\n ln.pdf(1.)\n ln.cdf(1)\n ln.rvs(1000)\n ppftest(ln)\n sampltest(ln)\n\n for i in range(10):\n N = 100000\n mean = np.random.uniform(0.1, 10)\n sig = np.random.uniform(0.1, 10)\n ln2 = D.LogNormal(mean, sig)\n samp = ln2.rvs(N)\n # check that the means and sigmas are correct\n assert (np.abs(np.log(samp).mean() - np.log(mean)) < 0.01 * sig)\n assert (np.abs(np.log(samp).std() - sig) < 0.01 * sig)\n\n\ndef test_broken_plaw():\n ln = D.BrokenPowerLaw([-2, -1.1, -3], [0.1, 1, 2, 100])\n ln.pdf(1.)\n ln.cdf(1)\n ln.rvs(1000)\n ppftest(ln)\n sampltest(ln, 0.05, 120, bounds=[[0.05, 1], [1, 2], [2, 120]])\n # test values in each range\n assert (np.abs(ln.ppf(ln.cdf(0.5)) - 0.5) < 1e-5)\n assert (np.abs(ln.ppf(ln.cdf(1.5)) - 1.5) < 1e-5)\n assert (np.abs(ln.ppf(ln.cdf(2.5)) - 2.5) < 1e-5)\n\n\ndef test_distr():\n ln = D.TruncatedLogNormal(1, 1, 2, 3)\n ln.pdf(1.)\n ln.cdf(1)\n ln.rvs(1000)\n ppftest(ln)\n sampltest(ln, 1, 4)\n ln = D.PowerLaw(-2, 2, 6)\n ln.pdf(1.)\n ln.cdf(1)\n ln.rvs(1000)\n ppftest(ln)\n sampltest(ln, 1, 7)\n\n\ndef test_composite():\n ln = D.CompositeDistribution([\n D.TruncatedLogNormal(1, 1, 2, 3),\n D.PowerLaw(-2, 3, 4),\n D.TruncatedLogNormal(1, 1, 4, 5),\n D.PowerLaw(-3.5, 5, np.inf)\n ])\n ln.pdf(2.5)\n ln.cdf(2.5)\n ln.rvs(1000)\n ppftest(ln)\n # test values in each break\n assert (np.abs(ln.ppf(ln.cdf(2.5)) - 2.5) < 1e-5)\n assert (np.abs(ln.ppf(ln.cdf(3.5)) - 3.5) < 1e-5)\n assert (np.abs(ln.ppf(ln.cdf(4.5)) - 4.5) < 1e-5)\n assert (np.abs(ln.ppf(ln.cdf(5.5)) - 5.5) < 1e-5)\n\n sampltest(ln, 1, np.inf, bounds=[[1, 3], [3, 4], [4, 5], [5, np.inf]])\n\n\ndef test_bounds():\n left, right = 1, 2\n tleft, tright = 0.5, 3\n ln = D.TruncatedLogNormal(1, 1, left, right)\n assert (ln.pdf(tleft) == 0)\n assert (ln.pdf(tright) == 0)\n assert (ln.cdf(tleft) == 0)\n assert (ln.cdf(tright) == 1)\n\n ln = D.PowerLaw(-3, left, right)\n assert (ln.pdf(tleft) == 0)\n assert (ln.pdf(tright) == 0)\n assert (ln.cdf(tleft) == 0)\n assert (ln.cdf(tright) == 1)\n\n ln = D.BrokenPowerLaw(\n [-2, -1.1, -3],\n [left, .6 * left + .3 * right, .3 * left + .6 * right, right])\n assert (ln.pdf(tleft) == 0)\n assert (ln.pdf(tright) == 0)\n assert (ln.cdf(tleft) == 0)\n assert (ln.cdf(tright) == 1)\n\n ln = D.CompositeDistribution([\n D.TruncatedLogNormal(1, 1, left, .75 * left + .25 * right),\n D.PowerLaw(-2, .75 * left + .25 * right, .5 * left + .5 * right),\n D.TruncatedLogNormal(1, 1, .5 * left + .5 * right,\n .25 * left + .75 * right),\n D.PowerLaw(-2, .25 * left + .75 * right, right)\n ])\n assert (ln.pdf(tleft) == 0)\n assert (ln.pdf(tright) == 0)\n assert (ln.cdf(tleft) == 0)\n assert (ln.cdf(tright) == 1)\n\n\ndef integralcheck(distr, left, x, val):\n I, EI = scipy.integrate.quad(lambda y: distr.pdf(y), left, x)\n assert (np.abs(val - I) < 1e-6)\n\n\ndef integralcheck_many(distr, left, right):\n integralcheck(distr, left, right, 1)\n N = 100\n xs = np.random.uniform(left, right, size=N)\n for x in xs:\n integralcheck(distr, left, x, distr.cdf(x))\n\n\ndef test_integral():\n # test that the numerically integrated pdf is within 3 sigma of 1\n # for different kind of pdfs\n\n left, right = 2, 3\n distrs = [\n D.TruncatedLogNormal(1, 1, left, right),\n D.PowerLaw(-2, left, right),\n D.BrokenPowerLaw([-2, -1.1, -3],\n [left, .6 * left + .3 * right, .3 * left + .6 * right, right]),\n D.CompositeDistribution([\n D.TruncatedLogNormal(1, 1, left, .75 * left + .25 * right),\n D.PowerLaw(-2, .75 * left + .25 * right, .5 * left + .5 * right),\n D.TruncatedLogNormal(1, 1,\n .5 * left + .5 * right,\n .25 * left + .75 * right),\n D.PowerLaw(-2, .25 * left + .75 * right, right)]\n )\n ]\n for curd in distrs:\n integralcheck_many(curd, left, right)\n" ]
[ [ "numpy.random.uniform", "numpy.random.seed", "numpy.abs", "numpy.log", "numpy.sqrt" ] ]
Seanny123/ARS
[ "f445a870feac13286fe2d8b14ee508f789c9ef7d" ]
[ "arsrl/ars.py" ]
[ "'''\nParallel implementation of the Augmented Random Search method.\nHoria Mania --- [email protected]\nAurelia Guy\nBenjamin Recht\n'''\n\nimport os\nimport socket\nimport time\n\nimport gym\nimport numpy as np\nimport ray\n\nfrom arsrl import utils, logz, optimizers\nfrom arsrl.policies import LinearPolicy\nfrom arsrl.shared_noise import SharedNoiseTable, create_shared_noise\n\n\[email protected]\nclass Worker(object):\n \"\"\"\n Object class for parallel rollout generation.\n \"\"\"\n\n def __init__(self, env_seed,\n env_name='',\n policy_params=None,\n deltas=None,\n rollout_length=1000,\n delta_std=0.02):\n\n # initialize OpenAI environment for each worker\n self.env = gym.make(env_name)\n self.env.seed(env_seed)\n\n # each worker gets access to the shared noise table\n # with independent random streams for sampling\n # from the shared noise table.\n self.deltas = SharedNoiseTable(deltas, env_seed + 7)\n self.policy_params = policy_params\n if policy_params['type'] == 'linear':\n self.policy = LinearPolicy(policy_params)\n else:\n raise NotImplementedError\n\n self.delta_std = delta_std\n self.rollout_length = rollout_length\n\n def get_weights_plus_stats(self):\n \"\"\"\n Get current policy weights and current statistics of past states.\n \"\"\"\n assert self.policy_params['type'] == 'linear'\n return self.policy.get_weights_plus_stats()\n\n def rollout(self, shift=0., rollout_length=None):\n \"\"\"\n Performs one rollout of maximum length rollout_length.\n At each time-step it substracts shift from the reward.\n \"\"\"\n\n if rollout_length is None:\n rollout_length = self.rollout_length\n\n total_reward = 0.\n steps = 0\n\n ob = self.env.reset()\n for i in range(rollout_length):\n action = self.policy.act(ob)\n ob, reward, done, _ = self.env.step(action)\n steps += 1\n total_reward += (reward - shift)\n if done:\n break\n\n return total_reward, steps\n\n def do_rollouts(self, w_policy, num_rollouts=1, shift=1, evaluate=False):\n \"\"\"\n Generate multiple rollouts with a policy parametrized by w_policy.\n \"\"\"\n\n rollout_rewards, deltas_idx = [], []\n steps = 0\n\n for i in range(num_rollouts):\n\n if evaluate:\n self.policy.update_weights(w_policy)\n deltas_idx.append(-1)\n\n # set to false so that evaluation rollouts are not used for updating state statistics\n self.policy.update_filter = False\n\n # for evaluation we do not shift the rewards (shift = 0) and we use the\n # default rollout length (1000 for the MuJoCo locomotion tasks)\n reward, r_steps = self.rollout(shift=0., rollout_length=self.env.spec.timestep_limit)\n rollout_rewards.append(reward)\n\n else:\n idx, delta = self.deltas.get_delta(w_policy.size)\n\n delta = (self.delta_std * delta).reshape(w_policy.shape)\n deltas_idx.append(idx)\n\n # set to true so that state statistics are updated\n self.policy.update_filter = True\n\n # compute reward and number of timesteps used for positive perturbation rollout\n self.policy.update_weights(w_policy + delta)\n pos_reward, pos_steps = self.rollout(shift=shift)\n\n # compute reward and number of timesteps used for negative pertubation rollout\n self.policy.update_weights(w_policy - delta)\n neg_reward, neg_steps = self.rollout(shift = shift)\n steps += pos_steps + neg_steps\n\n rollout_rewards.append([pos_reward, neg_reward])\n\n return {'deltas_idx': deltas_idx, 'rollout_rewards': rollout_rewards, \"steps\" : steps}\n\n def stats_increment(self):\n self.policy.observation_filter.stats_increment()\n return\n\n def get_weights(self):\n return self.policy.get_weights()\n\n def get_filter(self):\n return self.policy.observation_filter\n\n def sync_filter(self, other):\n self.policy.observation_filter.sync(other)\n return\n\n\nclass ARSLearner(object):\n \"\"\"\n Object class implementing the ARS algorithm.\n \"\"\"\n\n def __init__(self, env_name='HalfCheetah-v1',\n policy_params=None,\n num_workers=32,\n num_deltas=320,\n deltas_used=320,\n delta_std=0.02,\n logdir=None,\n rollout_length=1000,\n step_size=0.01,\n shift='constant zero',\n params=None,\n seed=123):\n\n logz.configure_output_dir(logdir)\n logz.save_params(params)\n\n env = gym.make(env_name)\n\n self.timesteps = 0\n self.action_size = env.action_space.shape[0]\n self.ob_size = env.observation_space.shape[0]\n self.num_deltas = num_deltas\n self.deltas_used = deltas_used\n self.rollout_length = rollout_length\n self.step_size = step_size\n self.delta_std = delta_std\n self.logdir = logdir\n self.shift = shift\n self.params = params\n self.max_past_avg_reward = float('-inf')\n self.num_episodes_used = float('inf')\n\n # create shared table for storing noise\n print(\"Creating deltas table.\")\n deltas_id = create_shared_noise.remote()\n self.deltas = SharedNoiseTable(ray.get(deltas_id), seed = seed + 3)\n print('Created deltas table.')\n\n # initialize workers with different random seeds\n print('Initializing workers.')\n self.num_workers = num_workers\n self.workers = [Worker.remote(seed + 7 * i,\n env_name=env_name,\n policy_params=policy_params,\n deltas=deltas_id,\n rollout_length=rollout_length,\n delta_std=delta_std) for i in range(num_workers)]\n\n # initialize policy\n if policy_params['type'] == 'linear':\n self.policy = LinearPolicy(policy_params)\n self.w_policy = self.policy.get_weights()\n else:\n raise NotImplementedError\n\n # initialize optimization algorithm\n self.optimizer = optimizers.SGD(self.w_policy, self.step_size)\n print(\"Initialization of ARS complete.\")\n\n def aggregate_rollouts(self, num_rollouts = None, evaluate = False):\n \"\"\"\n Aggregate update step from rollouts generated in parallel.\n \"\"\"\n\n if num_rollouts is None:\n num_deltas = self.num_deltas\n else:\n num_deltas = num_rollouts\n\n # put policy weights in the object store\n policy_id = ray.put(self.w_policy)\n\n t1 = time.time()\n num_rollouts = int(num_deltas / self.num_workers)\n\n # parallel generation of rollouts\n rollout_ids_one = [worker.do_rollouts.remote(policy_id,\n num_rollouts=num_rollouts,\n shift=self.shift,\n evaluate=evaluate) for worker in self.workers]\n\n rollout_ids_two = [worker.do_rollouts.remote(policy_id,\n num_rollouts=1,\n shift=self.shift,\n evaluate=evaluate) for worker in\n self.workers[:(num_deltas % self.num_workers)]]\n\n # gather results\n results_one = ray.get(rollout_ids_one)\n results_two = ray.get(rollout_ids_two)\n\n rollout_rewards, deltas_idx = [], []\n\n for result in results_one:\n if not evaluate:\n self.timesteps += result[\"steps\"]\n deltas_idx += result['deltas_idx']\n rollout_rewards += result['rollout_rewards']\n\n for result in results_two:\n if not evaluate:\n self.timesteps += result[\"steps\"]\n deltas_idx += result['deltas_idx']\n rollout_rewards += result['rollout_rewards']\n\n deltas_idx = np.array(deltas_idx)\n rollout_rewards = np.array(rollout_rewards, dtype = np.float64)\n\n print('Maximum reward of collected rollouts:', rollout_rewards.max())\n t2 = time.time()\n\n print('Time to generate rollouts:', t2 - t1)\n\n if evaluate:\n return rollout_rewards\n\n # select top performing directions if deltas_used < num_deltas\n max_rewards = np.max(rollout_rewards, axis=1)\n if self.deltas_used > self.num_deltas:\n self.deltas_used = self.num_deltas\n\n idx = np.arange(max_rewards.size)[\n max_rewards >= np.percentile(max_rewards, 100 * (1 - (self.deltas_used / self.num_deltas)))]\n deltas_idx = deltas_idx[idx]\n rollout_rewards = rollout_rewards[idx, :]\n\n # normalize rewards by their standard deviation\n rollout_rewards /= np.std(rollout_rewards)\n\n t1 = time.time()\n # aggregate rollouts to form g_hat, the gradient used to compute SGD step\n g_hat, count = utils.batched_weighted_sum(rollout_rewards[:, 0] - rollout_rewards[:, 1],\n (self.deltas.get(idx, self.w_policy.size)\n for idx in deltas_idx),\n batch_size=500)\n g_hat /= deltas_idx.size\n t2 = time.time()\n print('time to aggregate rollouts', t2 - t1)\n return g_hat\n\n def train_step(self):\n \"\"\"\n Perform one update step of the policy weights.\n \"\"\"\n\n g_hat = self.aggregate_rollouts()\n print(\"Euclidean norm of update step:\", np.linalg.norm(g_hat))\n self.w_policy -= self.optimizer._compute_step(g_hat).reshape(self.w_policy.shape)\n return\n\n def train(self, num_iter):\n\n start = time.time()\n for i in range(num_iter):\n\n t1 = time.time()\n self.train_step()\n t2 = time.time()\n print('total time of one step', t2 - t1)\n print('iter ', i, ' done')\n\n # record statistics every 10 iterations\n if (i + 1) % 10 == 0:\n rewards = self.aggregate_rollouts(num_rollouts=100, evaluate=True)\n w = ray.get(self.workers[0].get_weights_plus_stats.remote())\n np.savez(self.logdir + \"/lin_policy_plus\", w)\n\n print(sorted(self.params.items()))\n logz.log_tabular(\"Time\", time.time() - start)\n logz.log_tabular(\"Iteration\", i + 1)\n logz.log_tabular(\"AverageReward\", np.mean(rewards))\n logz.log_tabular(\"StdRewards\", np.std(rewards))\n logz.log_tabular(\"MaxRewardRollout\", np.max(rewards))\n logz.log_tabular(\"MinRewardRollout\", np.min(rewards))\n logz.log_tabular(\"timesteps\", self.timesteps)\n logz.dump_tabular()\n\n t1 = time.time()\n # get statistics from all workers\n for j in range(self.num_workers):\n self.policy.observation_filter.update(ray.get(self.workers[j].get_filter.remote()))\n self.policy.observation_filter.stats_increment()\n\n # make sure master filter buffer is clear\n self.policy.observation_filter.clear_buffer()\n # sync all workers\n filter_id = ray.put(self.policy.observation_filter)\n setting_filters_ids = [worker.sync_filter.remote(filter_id) for worker in self.workers]\n # waiting for sync of all workers\n ray.get(setting_filters_ids)\n\n increment_filters_ids = [worker.stats_increment.remote() for worker in self.workers]\n # waiting for increment of all workers\n ray.get(increment_filters_ids)\n t2 = time.time()\n print('Time to sync statistics:', t2 - t1)\n\n return\n\n\ndef run_ars(params):\n\n dir_path = params['dir_path']\n\n if not(os.path.exists(dir_path)):\n os.makedirs(dir_path)\n logdir = dir_path\n if not(os.path.exists(logdir)):\n os.makedirs(logdir)\n\n env = gym.make(params['env_name'])\n ob_dim = env.observation_space.shape[0]\n ac_dim = env.action_space.shape[0]\n\n # set policy parameters. Possible filters: 'MeanStdFilter' for v2, 'NoFilter' for v1.\n policy_params = {'type': 'linear',\n 'ob_filter': params['filter'],\n 'ob_dim': ob_dim,\n 'ac_dim': ac_dim}\n\n ARS = ARSLearner(env_name=params['env_name'],\n policy_params=policy_params,\n num_workers=params['n_workers'],\n num_deltas=params['n_directions'],\n deltas_used=params['deltas_used'],\n step_size=params['step_size'],\n delta_std=params['delta_std'],\n logdir=logdir,\n rollout_length=params['rollout_length'],\n shift=params['shift'],\n params=params,\n seed = params['seed'])\n\n ARS.train(params['n_iter'])\n\n return\n\n\nif __name__ == '__main__':\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument('--env_name', type=str, default='HalfCheetah-v1')\n parser.add_argument('--n_iter', '-n', type=int, default=1000)\n parser.add_argument('--n_directions', '-nd', type=int, default=8)\n parser.add_argument('--deltas_used', '-du', type=int, default=8)\n parser.add_argument('--step_size', '-s', type=float, default=0.02)\n parser.add_argument('--delta_std', '-std', type=float, default=.03)\n parser.add_argument('--n_workers', '-e', type=int, default=18)\n parser.add_argument('--rollout_length', '-r', type=int, default=1000)\n\n # for Swimmer-v1 and HalfCheetah-v1 use shift = 0\n # for Hopper-v1, Walker2d-v1, and Ant-v1 use shift = 1\n # for Humanoid-v1 used shift = 5\n parser.add_argument('--shift', type=float, default=0)\n parser.add_argument('--seed', type=int, default=237)\n parser.add_argument('--policy_type', type=str, default='linear')\n parser.add_argument('--dir_path', type=str, default='data')\n\n # for ARS V1 use filter = 'NoFilter'\n parser.add_argument('--filter', type=str, default='MeanStdFilter')\n\n local_ip = socket.gethostbyname(socket.gethostname())\n ray.init(redis_address=local_ip + ':6379')\n\n args = parser.parse_args()\n params = vars(args)\n run_ars(params)\n" ]
[ [ "numpy.savez", "numpy.arange", "numpy.max", "numpy.min", "numpy.array", "numpy.std", "numpy.linalg.norm", "numpy.percentile", "numpy.mean" ] ]
vitek2577/Multi-Tacotron-Voice-Cloning-GST
[ "a47d7f8412add19f7a154d70cc55698e2bb0a6da" ]
[ "synthesizer/audio.py" ]
[ "import librosa\nimport librosa.filters\nimport numpy as np\nimport tensorflow as tf\nfrom scipy import signal\nfrom scipy.io import wavfile\n\n\ndef load_wav(path, sr):\n return librosa.core.load(path, sr=sr)[0]\n\ndef save_wav(wav, path, sr):\n wav *= 32767 / max(0.01, np.max(np.abs(wav)))\n #proposed by @dsmiller\n wavfile.write(path, sr, wav.astype(np.int16))\n\ndef save_wavenet_wav(wav, path, sr):\n librosa.output.write_wav(path, wav, sr=sr)\n\ndef preemphasis(wav, k, preemphasize=True):\n if preemphasize:\n return signal.lfilter([1, -k], [1], wav)\n return wav\n\ndef inv_preemphasis(wav, k, inv_preemphasize=True):\n if inv_preemphasize:\n return signal.lfilter([1], [1, -k], wav)\n return wav\n\n#From https://github.com/r9y9/wavenet_vocoder/blob/master/audio.py\ndef start_and_end_indices(quantized, silence_threshold=2):\n for start in range(quantized.size):\n if abs(quantized[start] - 127) > silence_threshold:\n break\n for end in range(quantized.size - 1, 1, -1):\n if abs(quantized[end] - 127) > silence_threshold:\n break\n \n assert abs(quantized[start] - 127) > silence_threshold\n assert abs(quantized[end] - 127) > silence_threshold\n \n return start, end\n\ndef get_hop_size(hparams):\n hop_size = hparams.hop_size\n if hop_size is None:\n assert hparams.frame_shift_ms is not None\n hop_size = int(hparams.frame_shift_ms / 1000 * hparams.sample_rate)\n return hop_size\n\ndef linearspectrogram(wav, hparams):\n D = _stft(preemphasis(wav, hparams.preemphasis, hparams.preemphasize), hparams)\n S = _amp_to_db(np.abs(D), hparams) - hparams.ref_level_db\n \n if hparams.signal_normalization:\n return _normalize(S, hparams)\n return S\n\ndef melspectrogram(wav, hparams):\n D = _stft(preemphasis(wav, hparams.preemphasis, hparams.preemphasize), hparams)\n S = _amp_to_db(_linear_to_mel(np.abs(D), hparams), hparams) - hparams.ref_level_db\n \n if hparams.signal_normalization:\n return _normalize(S, hparams)\n return S\n\ndef inv_linear_spectrogram(linear_spectrogram, hparams):\n \"\"\"Converts linear spectrogram to waveform using librosa\"\"\"\n if hparams.signal_normalization:\n D = _denormalize(linear_spectrogram, hparams)\n else:\n D = linear_spectrogram\n \n S = _db_to_amp(D + hparams.ref_level_db) #Convert back to linear\n \n if hparams.use_lws:\n processor = _lws_processor(hparams)\n D = processor.run_lws(S.astype(np.float64).T ** hparams.power)\n y = processor.istft(D).astype(np.float32)\n return inv_preemphasis(y, hparams.preemphasis, hparams.preemphasize)\n else:\n return inv_preemphasis(_griffin_lim(S ** hparams.power, hparams), hparams.preemphasis, hparams.preemphasize)\n\ndef inv_mel_spectrogram(mel_spectrogram, hparams):\n \"\"\"Converts mel spectrogram to waveform using librosa\"\"\"\n if hparams.signal_normalization:\n D = _denormalize(mel_spectrogram, hparams)\n else:\n D = mel_spectrogram\n #print(D)\n S = _mel_to_linear(_db_to_amp(D + hparams.ref_level_db), hparams) # Convert back to linear\n #print(S) \n if hparams.use_lws:\n processor = _lws_processor(hparams)\n D = processor.run_lws(S.astype(np.float64).T ** hparams.power)\n y = processor.istft(D).astype(np.float32)\n return inv_preemphasis(y, hparams.preemphasis, hparams.preemphasize)\n else:\n return inv_preemphasis(_griffin_lim(S ** hparams.power, hparams), hparams.preemphasis, hparams.preemphasize)\n\ndef _lws_processor(hparams):\n import lws\n return lws.lws(hparams.n_fft, get_hop_size(hparams), fftsize=hparams.win_size, mode=\"speech\")\n\ndef _griffin_lim(S, hparams):\n \"\"\"librosa implementation of Griffin-Lim\n Based on https://github.com/librosa/librosa/issues/434\n \"\"\"\n angles = np.exp(2j * np.pi * np.random.rand(*S.shape))\n S_complex = np.abs(S).astype(np.complex)\n y = _istft(S_complex * angles, hparams)\n for i in range(hparams.griffin_lim_iters):\n angles = np.exp(1j * np.angle(_stft(y, hparams)))\n y = _istft(S_complex * angles, hparams)\n return y\n\ndef _stft(y, hparams):\n if hparams.use_lws:\n return _lws_processor(hparams).stft(y).T\n else:\n return librosa.stft(y=y, n_fft=hparams.n_fft, hop_length=get_hop_size(hparams), win_length=hparams.win_size)\n\ndef _istft(y, hparams):\n return librosa.istft(y, hop_length=get_hop_size(hparams), win_length=hparams.win_size)\n\n##########################################################\n#Those are only correct when using lws!!! (This was messing with Wavenet quality for a long time!)\ndef num_frames(length, fsize, fshift):\n \"\"\"Compute number of time frames of spectrogram\n \"\"\"\n pad = (fsize - fshift)\n if length % fshift == 0:\n M = (length + pad * 2 - fsize) // fshift + 1\n else:\n M = (length + pad * 2 - fsize) // fshift + 2\n return M\n\n\ndef pad_lr(x, fsize, fshift):\n \"\"\"Compute left and right padding\n \"\"\"\n M = num_frames(len(x), fsize, fshift)\n pad = (fsize - fshift)\n T = len(x) + 2 * pad\n r = (M - 1) * fshift + fsize - T\n return pad, pad + r\n##########################################################\n#Librosa correct padding\ndef librosa_pad_lr(x, fsize, fshift):\n return 0, (x.shape[0] // fshift + 1) * fshift - x.shape[0]\n\n# Conversions\n_mel_basis = None\n_inv_mel_basis = None\n\ndef _linear_to_mel(spectogram, hparams):\n global _mel_basis\n if _mel_basis is None:\n _mel_basis = _build_mel_basis(hparams)\n return np.dot(_mel_basis, spectogram)\n\ndef _mel_to_linear(mel_spectrogram, hparams):\n global _inv_mel_basis\n if _inv_mel_basis is None:\n _inv_mel_basis = np.linalg.pinv(_build_mel_basis(hparams))\n return np.maximum(1e-10, np.dot(_inv_mel_basis, mel_spectrogram))\n\ndef _build_mel_basis(hparams):\n assert hparams.fmax <= hparams.sample_rate // 2\n print(hparams.sample_rate, hparams.n_fft, hparams.num_mels, hparams.fmin, hparams.fmax)\n return librosa.filters.mel(hparams.sample_rate, hparams.n_fft, n_mels=hparams.num_mels,\n fmin=hparams.fmin, fmax=hparams.fmax)\n\ndef _amp_to_db(x, hparams):\n min_level = np.exp(hparams.min_level_db / 20 * np.log(10))\n return 20 * np.log10(np.maximum(min_level, x))\n\ndef _db_to_amp(x):\n return np.power(10.0, (x) * 0.05)\n\ndef _normalize(S, hparams):\n if hparams.allow_clipping_in_normalization:\n if hparams.symmetric_mels:\n return np.clip((2 * hparams.max_abs_value) * ((S - hparams.min_level_db) / (-hparams.min_level_db)) - hparams.max_abs_value,\n -hparams.max_abs_value, hparams.max_abs_value)\n else:\n return np.clip(hparams.max_abs_value * ((S - hparams.min_level_db) / (-hparams.min_level_db)), 0, hparams.max_abs_value)\n \n assert S.max() <= 0 and S.min() - hparams.min_level_db >= 0\n if hparams.symmetric_mels:\n return (2 * hparams.max_abs_value) * ((S - hparams.min_level_db) / (-hparams.min_level_db)) - hparams.max_abs_value\n else:\n return hparams.max_abs_value * ((S - hparams.min_level_db) / (-hparams.min_level_db))\n\ndef _denormalize(D, hparams):\n if hparams.allow_clipping_in_normalization:\n if hparams.symmetric_mels:\n return (((np.clip(D, -hparams.max_abs_value,\n hparams.max_abs_value) + hparams.max_abs_value) * -hparams.min_level_db / (2 * hparams.max_abs_value))\n + hparams.min_level_db)\n else:\n return ((np.clip(D, 0, hparams.max_abs_value) * -hparams.min_level_db / hparams.max_abs_value) + hparams.min_level_db)\n \n if hparams.symmetric_mels:\n return (((D + hparams.max_abs_value) * -hparams.min_level_db / (2 * hparams.max_abs_value)) + hparams.min_level_db)\n else:\n return ((D * -hparams.min_level_db / hparams.max_abs_value) + hparams.min_level_db)\n" ]
[ [ "numpy.abs", "scipy.signal.lfilter", "numpy.power", "numpy.log", "numpy.random.rand", "numpy.clip", "numpy.maximum", "numpy.dot" ] ]
tacaswell/pandas
[ "81c57e20da278494dfebc2f1043f5ff361a234f3" ]
[ "pandas/tseries/tools.py" ]
[ "from datetime import datetime, timedelta, time\nimport numpy as np\nfrom collections import MutableMapping\n\nimport pandas.lib as lib\nimport pandas.tslib as tslib\n\nfrom pandas.types.common import (_ensure_object,\n is_datetime64_ns_dtype,\n is_datetime64_dtype,\n is_datetime64tz_dtype,\n is_integer_dtype,\n is_list_like)\nfrom pandas.types.generic import (ABCIndexClass, ABCSeries,\n ABCDataFrame)\nfrom pandas.types.missing import notnull\n\nimport pandas.compat as compat\n\n_DATEUTIL_LEXER_SPLIT = None\ntry:\n # Since these are private methods from dateutil, it is safely imported\n # here so in case this interface changes, pandas will just fallback\n # to not using the functionality\n from dateutil.parser import _timelex\n\n if hasattr(_timelex, 'split'):\n def _lexer_split_from_str(dt_str):\n # The StringIO(str(_)) is for dateutil 2.2 compatibility\n return _timelex.split(compat.StringIO(str(dt_str)))\n\n _DATEUTIL_LEXER_SPLIT = _lexer_split_from_str\nexcept (ImportError, AttributeError):\n pass\n\n\ndef _infer_tzinfo(start, end):\n def _infer(a, b):\n tz = a.tzinfo\n if b and b.tzinfo:\n if not (tslib.get_timezone(tz) == tslib.get_timezone(b.tzinfo)):\n raise AssertionError('Inputs must both have the same timezone,'\n ' {0} != {1}'.format(tz, b.tzinfo))\n return tz\n\n tz = None\n if start is not None:\n tz = _infer(start, end)\n elif end is not None:\n tz = _infer(end, start)\n return tz\n\n\ndef _guess_datetime_format(dt_str, dayfirst=False,\n dt_str_parse=compat.parse_date,\n dt_str_split=_DATEUTIL_LEXER_SPLIT):\n \"\"\"\n Guess the datetime format of a given datetime string.\n\n Parameters\n ----------\n dt_str : string, datetime string to guess the format of\n dayfirst : boolean, default False\n If True parses dates with the day first, eg 20/01/2005\n Warning: dayfirst=True is not strict, but will prefer to parse\n with day first (this is a known bug).\n dt_str_parse : function, defaults to `compat.parse_date` (dateutil)\n This function should take in a datetime string and return\n a `datetime.datetime` guess that the datetime string represents\n dt_str_split : function, defaults to `_DATEUTIL_LEXER_SPLIT` (dateutil)\n This function should take in a datetime string and return\n a list of strings, the guess of the various specific parts\n e.g. '2011/12/30' -> ['2011', '/', '12', '/', '30']\n\n Returns\n -------\n ret : datetime format string (for `strftime` or `strptime`)\n \"\"\"\n if dt_str_parse is None or dt_str_split is None:\n return None\n\n if not isinstance(dt_str, compat.string_types):\n return None\n\n day_attribute_and_format = (('day',), '%d', 2)\n\n # attr name, format, padding (if any)\n datetime_attrs_to_format = [\n (('year', 'month', 'day'), '%Y%m%d', 0),\n (('year',), '%Y', 0),\n (('month',), '%B', 0),\n (('month',), '%b', 0),\n (('month',), '%m', 2),\n day_attribute_and_format,\n (('hour',), '%H', 2),\n (('minute',), '%M', 2),\n (('second',), '%S', 2),\n (('microsecond',), '%f', 6),\n (('second', 'microsecond'), '%S.%f', 0),\n ]\n\n if dayfirst:\n datetime_attrs_to_format.remove(day_attribute_and_format)\n datetime_attrs_to_format.insert(0, day_attribute_and_format)\n\n try:\n parsed_datetime = dt_str_parse(dt_str, dayfirst=dayfirst)\n except:\n # In case the datetime can't be parsed, its format cannot be guessed\n return None\n\n if parsed_datetime is None:\n return None\n\n try:\n tokens = dt_str_split(dt_str)\n except:\n # In case the datetime string can't be split, its format cannot\n # be guessed\n return None\n\n format_guess = [None] * len(tokens)\n found_attrs = set()\n\n for attrs, attr_format, padding in datetime_attrs_to_format:\n # If a given attribute has been placed in the format string, skip\n # over other formats for that same underlying attribute (IE, month\n # can be represented in multiple different ways)\n if set(attrs) & found_attrs:\n continue\n\n if all(getattr(parsed_datetime, attr) is not None for attr in attrs):\n for i, token_format in enumerate(format_guess):\n token_filled = tokens[i].zfill(padding)\n if (token_format is None and\n token_filled == parsed_datetime.strftime(attr_format)):\n format_guess[i] = attr_format\n tokens[i] = token_filled\n found_attrs.update(attrs)\n break\n\n # Only consider it a valid guess if we have a year, month and day\n if len(set(['year', 'month', 'day']) & found_attrs) != 3:\n return None\n\n output_format = []\n for i, guess in enumerate(format_guess):\n if guess is not None:\n # Either fill in the format placeholder (like %Y)\n output_format.append(guess)\n else:\n # Or just the token separate (IE, the dashes in \"01-01-2013\")\n try:\n # If the token is numeric, then we likely didn't parse it\n # properly, so our guess is wrong\n float(tokens[i])\n return None\n except ValueError:\n pass\n\n output_format.append(tokens[i])\n\n guessed_format = ''.join(output_format)\n\n # rebuild string, capturing any inferred padding\n dt_str = ''.join(tokens)\n if parsed_datetime.strftime(guessed_format) == dt_str:\n return guessed_format\n\n\ndef _guess_datetime_format_for_array(arr, **kwargs):\n # Try to guess the format based on the first non-NaN element\n non_nan_elements = notnull(arr).nonzero()[0]\n if len(non_nan_elements):\n return _guess_datetime_format(arr[non_nan_elements[0]], **kwargs)\n\n\ndef to_datetime(arg, errors='raise', dayfirst=False, yearfirst=False,\n utc=None, box=True, format=None, exact=True,\n unit=None, infer_datetime_format=False):\n \"\"\"\n Convert argument to datetime.\n\n Parameters\n ----------\n arg : integer, float, string, datetime, list, tuple, 1-d array, Series\n\n .. versionadded: 0.18.1\n\n or DataFrame/dict-like\n\n errors : {'ignore', 'raise', 'coerce'}, default 'raise'\n\n - If 'raise', then invalid parsing will raise an exception\n - If 'coerce', then invalid parsing will be set as NaT\n - If 'ignore', then invalid parsing will return the input\n dayfirst : boolean, default False\n Specify a date parse order if `arg` is str or its list-likes.\n If True, parses dates with the day first, eg 10/11/12 is parsed as\n 2012-11-10.\n Warning: dayfirst=True is not strict, but will prefer to parse\n with day first (this is a known bug, based on dateutil behavior).\n yearfirst : boolean, default False\n Specify a date parse order if `arg` is str or its list-likes.\n\n - If True parses dates with the year first, eg 10/11/12 is parsed as\n 2010-11-12.\n - If both dayfirst and yearfirst are True, yearfirst is preceded (same\n as dateutil).\n\n Warning: yearfirst=True is not strict, but will prefer to parse\n with year first (this is a known bug, based on dateutil beahavior).\n\n .. versionadded: 0.16.1\n\n utc : boolean, default None\n Return UTC DatetimeIndex if True (converting any tz-aware\n datetime.datetime objects as well).\n box : boolean, default True\n\n - If True returns a DatetimeIndex\n - If False returns ndarray of values.\n format : string, default None\n strftime to parse time, eg \"%d/%m/%Y\", note that \"%f\" will parse\n all the way up to nanoseconds.\n exact : boolean, True by default\n\n - If True, require an exact format match.\n - If False, allow the format to match anywhere in the target string.\n\n unit : string, default 'ns'\n unit of the arg (D,s,ms,us,ns) denote the unit in epoch\n (e.g. a unix timestamp), which is an integer/float number.\n infer_datetime_format : boolean, default False\n If True and no `format` is given, attempt to infer the format of the\n datetime strings, and if it can be inferred, switch to a faster\n method of parsing them. In some cases this can increase the parsing\n speed by ~5-10x.\n\n Returns\n -------\n ret : datetime if parsing succeeded.\n Return type depends on input:\n\n - list-like: DatetimeIndex\n - Series: Series of datetime64 dtype\n - scalar: Timestamp\n\n In case when it is not possible to return designated types (e.g. when\n any element of input is before Timestamp.min or after Timestamp.max)\n return will have datetime.datetime type (or correspoding array/Series).\n\n Examples\n --------\n\n Assembling a datetime from multiple columns of a DataFrame. The keys can be\n common abbreviations like ['year', 'month', 'day', 'minute', 'second',\n 'ms', 'us', 'ns']) or plurals of the same\n\n >>> df = pd.DataFrame({'year': [2015, 2016],\n 'month': [2, 3],\n 'day': [4, 5]})\n >>> pd.to_datetime(df)\n 0 2015-02-04\n 1 2016-03-05\n dtype: datetime64[ns]\n\n If a date does not meet the `timestamp limitations\n <http://pandas.pydata.org/pandas-docs/stable/timeseries.html\n #timeseries-timestamp-limits>`_, passing errors='ignore'\n will return the original input instead of raising any exception.\n\n Passing errors='coerce' will force an out-of-bounds date to NaT,\n in addition to forcing non-dates (or non-parseable dates) to NaT.\n\n >>> pd.to_datetime('13000101', format='%Y%m%d', errors='ignore')\n datetime.datetime(1300, 1, 1, 0, 0)\n >>> pd.to_datetime('13000101', format='%Y%m%d', errors='coerce')\n NaT\n\n Passing infer_datetime_format=True can often-times speedup a parsing\n if its not an ISO8601 format exactly, but in a regular format.\n\n >>> s = pd.Series(['3/11/2000', '3/12/2000', '3/13/2000']*1000)\n\n >>> s.head()\n 0 3/11/2000\n 1 3/12/2000\n 2 3/13/2000\n 3 3/11/2000\n 4 3/12/2000\n dtype: object\n\n >>> %timeit pd.to_datetime(s,infer_datetime_format=True)\n 100 loops, best of 3: 10.4 ms per loop\n\n >>> %timeit pd.to_datetime(s,infer_datetime_format=False)\n 1 loop, best of 3: 471 ms per loop\n\n \"\"\"\n\n from pandas.tseries.index import DatetimeIndex\n\n tz = 'utc' if utc else None\n\n def _convert_listlike(arg, box, format, name=None, tz=tz):\n\n if isinstance(arg, (list, tuple)):\n arg = np.array(arg, dtype='O')\n\n # these are shortcutable\n if is_datetime64tz_dtype(arg):\n if not isinstance(arg, DatetimeIndex):\n return DatetimeIndex(arg, tz=tz, name=name)\n if utc:\n arg = arg.tz_convert(None).tz_localize('UTC')\n return arg\n\n elif is_datetime64_ns_dtype(arg):\n if box and not isinstance(arg, DatetimeIndex):\n try:\n return DatetimeIndex(arg, tz=tz, name=name)\n except ValueError:\n pass\n\n return arg\n\n elif unit is not None:\n if format is not None:\n raise ValueError(\"cannot specify both format and unit\")\n arg = getattr(arg, 'values', arg)\n result = tslib.array_with_unit_to_datetime(arg, unit,\n errors=errors)\n if box:\n if errors == 'ignore':\n from pandas import Index\n return Index(result)\n\n return DatetimeIndex(result, tz=tz, name=name)\n return result\n elif getattr(arg, 'ndim', 1) > 1:\n raise TypeError('arg must be a string, datetime, list, tuple, '\n '1-d array, or Series')\n\n arg = _ensure_object(arg)\n require_iso8601 = False\n\n if infer_datetime_format and format is None:\n format = _guess_datetime_format_for_array(arg, dayfirst=dayfirst)\n\n if format is not None:\n # There is a special fast-path for iso8601 formatted\n # datetime strings, so in those cases don't use the inferred\n # format because this path makes process slower in this\n # special case\n format_is_iso8601 = _format_is_iso(format)\n if format_is_iso8601:\n require_iso8601 = not infer_datetime_format\n format = None\n\n try:\n result = None\n\n if format is not None:\n # shortcut formatting here\n if format == '%Y%m%d':\n try:\n result = _attempt_YYYYMMDD(arg, errors=errors)\n except:\n raise ValueError(\"cannot convert the input to \"\n \"'%Y%m%d' date format\")\n\n # fallback\n if result is None:\n try:\n result = tslib.array_strptime(arg, format, exact=exact,\n errors=errors)\n except tslib.OutOfBoundsDatetime:\n if errors == 'raise':\n raise\n result = arg\n except ValueError:\n # if format was inferred, try falling back\n # to array_to_datetime - terminate here\n # for specified formats\n if not infer_datetime_format:\n if errors == 'raise':\n raise\n result = arg\n\n if result is None and (format is None or infer_datetime_format):\n result = tslib.array_to_datetime(\n arg,\n errors=errors,\n utc=utc,\n dayfirst=dayfirst,\n yearfirst=yearfirst,\n require_iso8601=require_iso8601\n )\n\n if is_datetime64_dtype(result) and box:\n result = DatetimeIndex(result, tz=tz, name=name)\n return result\n\n except ValueError as e:\n try:\n values, tz = tslib.datetime_to_datetime64(arg)\n return DatetimeIndex._simple_new(values, name=name, tz=tz)\n except (ValueError, TypeError):\n raise e\n\n if arg is None:\n return arg\n elif isinstance(arg, tslib.Timestamp):\n return arg\n elif isinstance(arg, ABCSeries):\n from pandas import Series\n values = _convert_listlike(arg._values, False, format)\n return Series(values, index=arg.index, name=arg.name)\n elif isinstance(arg, (ABCDataFrame, MutableMapping)):\n return _assemble_from_unit_mappings(arg, errors=errors)\n elif isinstance(arg, ABCIndexClass):\n return _convert_listlike(arg, box, format, name=arg.name)\n elif is_list_like(arg):\n return _convert_listlike(arg, box, format)\n\n return _convert_listlike(np.array([arg]), box, format)[0]\n\n\n# mappings for assembling units\n_unit_map = {'year': 'year',\n 'years': 'year',\n 'month': 'month',\n 'months': 'month',\n 'day': 'day',\n 'days': 'day',\n 'hour': 'h',\n 'hours': 'h',\n 'minute': 'm',\n 'minutes': 'm',\n 'second': 's',\n 'seconds': 's',\n 'ms': 'ms',\n 'millisecond': 'ms',\n 'milliseconds': 'ms',\n 'us': 'us',\n 'microsecond': 'us',\n 'microseconds': 'us',\n 'ns': 'ns',\n 'nanosecond': 'ns',\n 'nanoseconds': 'ns'\n }\n\n\ndef _assemble_from_unit_mappings(arg, errors):\n \"\"\"\n assemble the unit specifed fields from the arg (DataFrame)\n Return a Series for actual parsing\n\n Parameters\n ----------\n arg : DataFrame\n errors : {'ignore', 'raise', 'coerce'}, default 'raise'\n\n - If 'raise', then invalid parsing will raise an exception\n - If 'coerce', then invalid parsing will be set as NaT\n - If 'ignore', then invalid parsing will return the input\n\n Returns\n -------\n Series\n \"\"\"\n from pandas import to_timedelta, to_numeric, DataFrame\n arg = DataFrame(arg)\n if not arg.columns.is_unique:\n raise ValueError(\"cannot assemble with duplicate keys\")\n\n # replace passed unit with _unit_map\n def f(value):\n if value in _unit_map:\n return _unit_map[value]\n\n # m is case significant\n if value.lower() in _unit_map:\n return _unit_map[value.lower()]\n\n return value\n\n unit = {k: f(k) for k in arg.keys()}\n unit_rev = {v: k for k, v in unit.items()}\n\n # we require at least Ymd\n required = ['year', 'month', 'day']\n req = sorted(list(set(required) - set(unit_rev.keys())))\n if len(req):\n raise ValueError(\"to assemble mappings requires at \"\n \"least that [year, month, day] be specified: \"\n \"[{0}] is missing\".format(','.join(req)))\n\n # keys we don't recognize\n excess = sorted(list(set(unit_rev.keys()) - set(_unit_map.values())))\n if len(excess):\n raise ValueError(\"extra keys have been passed \"\n \"to the datetime assemblage: \"\n \"[{0}]\".format(','.join(excess)))\n\n def coerce(values):\n # we allow coercion to if errors allows\n values = to_numeric(values, errors=errors)\n\n # prevent overflow in case of int8 or int16\n if is_integer_dtype(values):\n values = values.astype('int64', copy=False)\n return values\n\n values = (coerce(arg[unit_rev['year']]) * 10000 +\n coerce(arg[unit_rev['month']]) * 100 +\n coerce(arg[unit_rev['day']]))\n try:\n values = to_datetime(values, format='%Y%m%d', errors=errors)\n except (TypeError, ValueError) as e:\n raise ValueError(\"cannot assemble the \"\n \"datetimes: {0}\".format(e))\n\n for u in ['h', 'm', 's', 'ms', 'us', 'ns']:\n value = unit_rev.get(u)\n if value is not None and value in arg:\n try:\n values += to_timedelta(coerce(arg[value]),\n unit=u,\n errors=errors)\n except (TypeError, ValueError) as e:\n raise ValueError(\"cannot assemble the datetimes \"\n \"[{0}]: {1}\".format(value, e))\n\n return values\n\n\ndef _attempt_YYYYMMDD(arg, errors):\n \"\"\" try to parse the YYYYMMDD/%Y%m%d format, try to deal with NaT-like,\n arg is a passed in as an object dtype, but could really be ints/strings\n with nan-like/or floats (e.g. with nan)\n\n Parameters\n ----------\n arg : passed value\n errors : 'raise','ignore','coerce'\n \"\"\"\n\n def calc(carg):\n # calculate the actual result\n carg = carg.astype(object)\n parsed = lib.try_parse_year_month_day(carg / 10000,\n carg / 100 % 100,\n carg % 100)\n return tslib.array_to_datetime(parsed, errors=errors)\n\n def calc_with_mask(carg, mask):\n result = np.empty(carg.shape, dtype='M8[ns]')\n iresult = result.view('i8')\n iresult[~mask] = tslib.iNaT\n result[mask] = calc(carg[mask].astype(np.float64).astype(np.int64)). \\\n astype('M8[ns]')\n return result\n\n # try intlike / strings that are ints\n try:\n return calc(arg.astype(np.int64))\n except:\n pass\n\n # a float with actual np.nan\n try:\n carg = arg.astype(np.float64)\n return calc_with_mask(carg, notnull(carg))\n except:\n pass\n\n # string with NaN-like\n try:\n mask = ~lib.ismember(arg, tslib._nat_strings)\n return calc_with_mask(arg, mask)\n except:\n pass\n\n return None\n\n\ndef _format_is_iso(f):\n \"\"\"\n Does format match the iso8601 set that can be handled by the C parser?\n Generally of form YYYY-MM-DDTHH:MM:SS - date separator can be different\n but must be consistent. Leading 0s in dates and times are optional.\n \"\"\"\n iso_template = '%Y{date_sep}%m{date_sep}%d{time_sep}%H:%M:%S.%f'.format\n excluded_formats = ['%Y%m%d', '%Y%m', '%Y']\n\n for date_sep in [' ', '/', '\\\\', '-', '.', '']:\n for time_sep in [' ', 'T']:\n if (iso_template(date_sep=date_sep,\n time_sep=time_sep\n ).startswith(f) and f not in excluded_formats):\n return True\n return False\n\n\ndef parse_time_string(arg, freq=None, dayfirst=None, yearfirst=None):\n \"\"\"\n Try hard to parse datetime string, leveraging dateutil plus some extra\n goodies like quarter recognition.\n\n Parameters\n ----------\n arg : compat.string_types\n freq : str or DateOffset, default None\n Helps with interpreting time string if supplied\n dayfirst : bool, default None\n If None uses default from print_config\n yearfirst : bool, default None\n If None uses default from print_config\n\n Returns\n -------\n datetime, datetime/dateutil.parser._result, str\n \"\"\"\n from pandas.core.config import get_option\n if not isinstance(arg, compat.string_types):\n return arg\n\n from pandas.tseries.offsets import DateOffset\n if isinstance(freq, DateOffset):\n freq = freq.rule_code\n\n if dayfirst is None:\n dayfirst = get_option(\"display.date_dayfirst\")\n if yearfirst is None:\n yearfirst = get_option(\"display.date_yearfirst\")\n\n return tslib.parse_datetime_string_with_reso(arg, freq=freq,\n dayfirst=dayfirst,\n yearfirst=yearfirst)\n\n\nDateParseError = tslib.DateParseError\nnormalize_date = tslib.normalize_date\n\n# Fixed time formats for time parsing\n_time_formats = [\"%H:%M\", \"%H%M\", \"%I:%M%p\", \"%I%M%p\",\n \"%H:%M:%S\", \"%H%M%S\", \"%I:%M:%S%p\", \"%I%M%S%p\"]\n\n\ndef _guess_time_format_for_array(arr):\n # Try to guess the format based on the first non-NaN element\n non_nan_elements = notnull(arr).nonzero()[0]\n if len(non_nan_elements):\n element = arr[non_nan_elements[0]]\n for time_format in _time_formats:\n try:\n datetime.strptime(element, time_format)\n return time_format\n except ValueError:\n pass\n\n return None\n\n\ndef to_time(arg, format=None, infer_time_format=False, errors='raise'):\n \"\"\"\n Parse time strings to time objects using fixed strptime formats (\"%H:%M\",\n \"%H%M\", \"%I:%M%p\", \"%I%M%p\", \"%H:%M:%S\", \"%H%M%S\", \"%I:%M:%S%p\",\n \"%I%M%S%p\")\n\n Use infer_time_format if all the strings are in the same format to speed\n up conversion.\n\n Parameters\n ----------\n arg : string in time format, datetime.time, list, tuple, 1-d array, Series\n format : str, default None\n Format used to convert arg into a time object. If None, fixed formats\n are used.\n infer_time_format: bool, default False\n Infer the time format based on the first non-NaN element. If all\n strings are in the same format, this will speed up conversion.\n errors : {'ignore', 'raise', 'coerce'}, default 'raise'\n - If 'raise', then invalid parsing will raise an exception\n - If 'coerce', then invalid parsing will be set as None\n - If 'ignore', then invalid parsing will return the input\n\n Returns\n -------\n datetime.time\n \"\"\"\n from pandas.core.series import Series\n\n def _convert_listlike(arg, format):\n\n if isinstance(arg, (list, tuple)):\n arg = np.array(arg, dtype='O')\n\n elif getattr(arg, 'ndim', 1) > 1:\n raise TypeError('arg must be a string, datetime, list, tuple, '\n '1-d array, or Series')\n\n arg = _ensure_object(arg)\n\n if infer_time_format and format is None:\n format = _guess_time_format_for_array(arg)\n\n times = []\n if format is not None:\n for element in arg:\n try:\n times.append(datetime.strptime(element, format).time())\n except (ValueError, TypeError):\n if errors == 'raise':\n raise ValueError(\"Cannot convert %s to a time with \"\n \"given format %s\" % (element, format))\n elif errors == 'ignore':\n return arg\n else:\n times.append(None)\n else:\n formats = _time_formats[:]\n format_found = False\n for element in arg:\n time_object = None\n for time_format in formats:\n try:\n time_object = datetime.strptime(element,\n time_format).time()\n if not format_found:\n # Put the found format in front\n fmt = formats.pop(formats.index(time_format))\n formats.insert(0, fmt)\n format_found = True\n break\n except (ValueError, TypeError):\n continue\n\n if time_object is not None:\n times.append(time_object)\n elif errors == 'raise':\n raise ValueError(\"Cannot convert arg {arg} to \"\n \"a time\".format(arg=arg))\n elif errors == 'ignore':\n return arg\n else:\n times.append(None)\n\n return times\n\n if arg is None:\n return arg\n elif isinstance(arg, time):\n return arg\n elif isinstance(arg, Series):\n values = _convert_listlike(arg._values, format)\n return Series(values, index=arg.index, name=arg.name)\n elif isinstance(arg, ABCIndexClass):\n return _convert_listlike(arg, format)\n elif is_list_like(arg):\n return _convert_listlike(arg, format)\n\n return _convert_listlike(np.array([arg]), format)[0]\n\n\ndef format(dt):\n \"\"\"Returns date in YYYYMMDD format.\"\"\"\n return dt.strftime('%Y%m%d')\n\n\nOLE_TIME_ZERO = datetime(1899, 12, 30, 0, 0, 0)\n\n\ndef ole2datetime(oledt):\n \"\"\"function for converting excel date to normal date format\"\"\"\n val = float(oledt)\n\n # Excel has a bug where it thinks the date 2/29/1900 exists\n # we just reject any date before 3/1/1900.\n if val < 61:\n raise ValueError(\"Value is outside of acceptable range: %s \" % val)\n\n return OLE_TIME_ZERO + timedelta(days=val)\n" ]
[ [ "pandas.Series", "pandas.tseries.index.DatetimeIndex._simple_new", "pandas.tslib.array_with_unit_to_datetime", "pandas.types.common.is_datetime64_ns_dtype", "pandas.tslib.get_timezone", "pandas.types.missing.notnull", "pandas.lib.ismember", "pandas.core.config.get_option", "pandas.types.common.is_datetime64tz_dtype", "pandas.to_numeric", "pandas.types.common.is_list_like", "pandas.tseries.index.DatetimeIndex", "pandas.tslib.array_to_datetime", "pandas.types.common.is_datetime64_dtype", "pandas.types.common.is_integer_dtype", "pandas.lib.try_parse_year_month_day", "pandas.Index", "numpy.array", "pandas.tslib.datetime_to_datetime64", "pandas.tslib.parse_datetime_string_with_reso", "numpy.empty", "pandas.DataFrame", "pandas.types.common._ensure_object", "pandas.tslib.array_strptime" ] ]
Lalf-Klein/megnet
[ "e3977ce372b74380268659e964c85bf59c1aac34" ]
[ "megnet/utils/tests/test_general.py" ]
[ "import unittest\nimport numpy as np\n\nfrom megnet.utils.general import expand_1st, to_list, fast_label_binarize\n\n\nclass TestGeneralUtils(unittest.TestCase):\n def test_expand_dim(self):\n x = np.array([1, 2, 3])\n self.assertListEqual(list(expand_1st(x).shape), [1, 3])\n\n def test_to_list(self):\n x = 1\n y = [1]\n z = tuple([1, 2, 3])\n v = np.array([1, 2, 3])\n k = np.array([[1, 2], [3, 4]])\n for k in [x, y, z, v, k]:\n self.assertTrue(type(to_list(k)), list)\n\n def test_fast_label_binarize(self):\n binaries = fast_label_binarize(1, [0, 1])\n self.assertListEqual(binaries, [0])\n binaries = fast_label_binarize(1, [0, 1, 2])\n self.assertListEqual(binaries, [0, 1, 0])\n\n\nif __name__ == \"__main__\":\n unittest.main()\n" ]
[ [ "numpy.array" ] ]
benoitLemoine/stage2A
[ "a81de38deaf786227e6d34c04803da5e5854c9f1" ]
[ "detection/yolov3/yolov3.py" ]
[ "import tensorflow as tf\nimport cv2 as cv\nimport numpy as np\n\nfrom PIL import Image\nfrom core import utils\n\nclassesPath = \"../../data/coco.names\"\nmodelPath = \"../../checkpoint/yolov3_cpu_nms.pb\"\n\nIMAGE_H, IMAGE_W = 416, 416\nclasses = utils.read_coco_names(classesPath)\nnum_classes = len(classes)\ninput_tensor, output_tensors = utils.read_pb_return_tensors(tf.get_default_graph(), modelPath,\n [\"Placeholder:0\", \"concat_9:0\", \"mul_6:0\"])\n\n\nclass YoloV3Net:\n def __init__(self):\n self.sess = tf.Session()\n\n def run(self, img):\n # Processing frame\n img_resized = self._preprocessFrame(img)\n\n boxes, scores = self.sess.run(output_tensors, feed_dict={input_tensor: np.expand_dims(img_resized, axis=0)})\n boxes, scores, labels = utils.cpu_nms(boxes, scores, num_classes, score_thresh=0.4, iou_thresh=0.5)\n\n # Keeping only box labelled \"person\"\n if boxes is not None:\n boxes = self._getOnlyDetectedPeople(boxes, labels)\n\n return boxes\n\n def __del__(self):\n self.sess.close()\n\n @staticmethod\n def _getOnlyDetectedPeople(boxes, labels):\n pBoxes = []\n for i in np.arange(len(boxes)):\n if labels[i] == 0:\n pBoxes.append(boxes[i])\n return pBoxes\n\n @staticmethod\n def _preprocessFrame(frame):\n frameRGB = cv.cvtColor(frame, cv.COLOR_BGR2RGB)\n image = Image.fromarray(frameRGB)\n img_resized = np.array(image.resize(size=(IMAGE_H, IMAGE_W)), dtype=np.float32)\n return img_resized / 255.\n" ]
[ [ "tensorflow.Session", "numpy.expand_dims", "tensorflow.get_default_graph" ] ]
JamesWang007/Dive-into-DL-PyTorch
[ "267b54168322ab37da44e83008fba4f24b70fa9f" ]
[ "mycode/test_03_ch5_4.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Mar 25 23:09:40 2020\n 5.4 池化层\n https://tangshusen.me/Dive-into-DL-PyTorch/#/chapter05_CNN/5.4_pooling\n@author: bejin\n\"\"\"\n\n\nimport torch\nfrom torch import nn\n\n\ndef pool2d(X, pool_size, mode='max'):\n X = X.float()\n p_h, p_w = pool_size\n Y = torch.zeros(X.shape[0] - p_h + 1, X.shape[1] - p_w + 1)\n for i in range(Y.shape[0]):\n for j in range(Y.shape[1]):\n if mode == 'max':\n Y[i, j] = X[i: i + p_h, j: j + p_w].max()\n elif mode == 'avg':\n Y[i, j] = X[i: i + p_h, j: j + p_w].mean() \n return Y\n\n\nX = torch.tensor([[0, 1, 2], [3, 4, 5], [6, 7, 8]])\npool2d(X, (2, 2))\n\n\n\npool2d(X, (2, 2), 'avg')\n\n\n\n# 5.4.2 填充和步幅\nX = torch.arange(16, dtype=torch.float).view((1, 1, 4, 4))\nX\n\n\n\npool2d = nn.MaxPool2d(3)\npool2d(X) \n\n\n\npool2d = nn.MaxPool2d(3, padding=1, stride=2)\npool2d(X)\n\n\n\npool2d = nn.MaxPool2d((2, 4), padding=(1, 2), stride=(2, 3))\npool2d(X)\n\n\n# 5.4.3 多通道\nX = torch.cat((X, X + 1), dim=1)\nX\n\n\npool2d = nn.MaxPool2d(3, padding=1, stride=2)\npool2d(X)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" ]
[ [ "torch.nn.MaxPool2d", "torch.tensor", "torch.arange", "torch.zeros", "torch.cat" ] ]
dheerajgupta0001/rtm_daily_report_generator
[ "591a21ed1888df8b50eb8e873e03387df5d5a6e7" ]
[ "src/app/section_3/sectionWrInjGraph.py" ]
[ "import datetime as dt\nfrom src.repos.metricsData.metricsDataRepo import MetricsDataRepo\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nplt.rcParams.update({'figure.max_open_warning': 0})\nimport matplotlib.dates as mdates\n\n\ndef fetchWrInjGraphContext(appDbConnStr: str, startDt: dt.datetime, endDt: dt.datetime) -> bool:\n mRepo = MetricsDataRepo(appDbConnStr)\n\n # get iex rtm data for the range between start date and end date\n wbesRtmIexVals = mRepo.getWbesRtmIexBeneficiaryBlockWiseData(startDt, endDt,beneficiary='West ',beneficiary_type=' Injection ')\n\n wbesRtmPxiVals = mRepo.getWbesRtmPxiBeneficiaryBlockWiseData(startDt, endDt,beneficiary='West ',beneficiary_type=' Injection ')\n wbesPxIexVals = mRepo.getWbesPxIexBeneficiaryBlockWiseData(startDt, endDt,beneficiary='West ',beneficiary_type=' Injection ')\n\n wbesPxPxiVals = mRepo.getWbesPxPxiBeneficiaryBlockWiseData(startDt, endDt,beneficiary='West ',beneficiary_type=' Injection ')\n\n wbesRtmIexDf = pd.DataFrame(wbesRtmIexVals)\n wbesRtmPxiDf = pd.DataFrame(wbesRtmPxiVals)\n wbesPxIexDf = pd.DataFrame(wbesPxIexVals)\n wbesPxPxiDf = pd.DataFrame(wbesPxPxiVals)\n\n # wbesRtmPxiDf['date']=wbesRtmPxiDf['time_stamp'].dt.date\n # wbesRtmPxiDf['time']=wbesRtmPxiDf['time_stamp'].dt.time\n wbesRtmPxiDf.drop(['beneficiary','beneficiary_type'],axis=1,inplace=True)\n # wbesRtmPxiDf = wbesRtmPxiDf.pivot(index='time',columns='date', values='data_value')\n\n\n # wbesRtmIexDf['date'] = wbesRtmIexDf['time_stamp'].dt.date\n # wbesRtmIexDf['time'] = wbesRtmIexDf['time_stamp'].dt.time\n wbesRtmIexDf.drop(['beneficiary', 'beneficiary_type'], axis=1, inplace=True)\n # wbesRtmIexDf = wbesRtmIexDf.pivot(index='time', columns='date', values='data_value')\n wbesPxIexDf.drop(['beneficiary','beneficiary_type'],axis=1,inplace=True)\n wbesPxPxiDf.drop(['beneficiary','beneficiary_type'],axis=1,inplace=True)\n wbesPxDf = wbesRtmPxiDf.append(wbesPxIexDf,ignore_index=False).groupby(['time_stamp']).sum().reset_index()\n wbesRtmDf = wbesRtmPxiDf.append(wbesRtmIexDf,ignore_index=False).groupby(['time_stamp']).sum().reset_index()\n wbesRtmDf['time_stamp']=wbesRtmDf['time_stamp'].dt.date\n wbesPxDf['time_stamp']=wbesPxDf['time_stamp'].dt.date\n\n wbesRtmDfMax = wbesRtmDf.groupby(['time_stamp']).max().reset_index()\n wbesRtmDfMin = wbesRtmDf.groupby(['time_stamp']).min().reset_index()\n mergewbesRtmDf=pd.merge(wbesRtmDfMax,wbesRtmDfMin,on='time_stamp')\n mergewbesRtmDf.set_index(['time_stamp'],inplace=True)\n mergewbesRtmDf = mergewbesRtmDf.rename(columns={'data_value_x': 'RTM_MAX','data_value_y':'RTM_MIN'})\n\n wbesPxDfMax = wbesPxDf.groupby(['time_stamp']).max().reset_index()\n wbesPxDfMin = wbesPxDf.groupby(['time_stamp']).min().reset_index()\n mergeWbesPxDf=pd.merge(wbesPxDfMax,wbesPxDfMin,on='time_stamp')\n mergeWbesPxDf.set_index(['time_stamp'],inplace=True)\n mergeWbesPxDf = mergeWbesPxDf.rename(columns={'data_value_x': 'DAM_MAX','data_value_y':'DAM_MIN'})\n\n # derive plot title\n pltTitle = 'WR Sell RTM vs DAM'\n\n # create a plotting area and get the figure, axes handle in return\n fig, ax = plt.subplots(figsize=(7.5, 4.5))\n # instantiate a second axes that shares the same x-axis\n ax2 = ax.twinx()\n # set plot title\n ax.set_title(pltTitle)\n ax.set_ylabel('MW')\n ax2.set_ylabel('RTM SELL MIN(MW)')\n ax.set_facecolor(\"#474747\")\n # fig.patch.set_facecolor('#d9ccff')\n\n clr = ['#66b3ff', '#df80ff', '#ff6666', '#00b359']\n\n # plot data and get the line artist object in return\n laThisMonth, = ax.plot(\n mergewbesRtmDf.index.values, mergewbesRtmDf['RTM_MAX'].values, color='#66b3ff')\n laThisMonth.set_label('RTM Sell Max')\n\n laLastYear, = ax.plot(\n mergeWbesPxDf.index.values, mergeWbesPxDf['DAM_MAX'].values, color='#df80ff')\n laLastYear.set_label('DAM Sell Max')\n\n laPrevMonth, = ax2.plot(\n mergewbesRtmDf.index.values, mergewbesRtmDf['RTM_MIN'].values, color='#00b359')\n laPrevMonth.set_label('RTM Sell Min')\n\n laPrevMonth, = ax.plot(\n mergeWbesPxDf.index.values, mergeWbesPxDf['DAM_MIN'].values, color='#ff6666')\n laPrevMonth.set_label('DAM Sell Min')\n # plt.show()\n # ax.set_xlim((1, 31), auto=True)\n # enable legends\n ax.legend(bbox_to_anchor=(0.0, -0.3, 1, 0), loc='best',\n ncol=3, mode=\"expand\", borderaxespad=0.)\n ax2.legend(bbox_to_anchor=(0.0, -0.3, 1, 0), loc='lower right',\n ncol=3, mode=\"expand\", borderaxespad=0.)\n fig.subplots_adjust(bottom=0.25, top=0.8)\n fig.savefig('assets/section_3_1.png')\n\n plt.close()\n\n\n return True\n" ]
[ [ "pandas.DataFrame", "matplotlib.pyplot.subplots", "matplotlib.pyplot.rcParams.update", "pandas.merge", "matplotlib.pyplot.close" ] ]
ii-research-yu/pgbm
[ "d050a5f71f1a458d8269c4f5201744c0d7c4d487" ]
[ "examples/pytorch/example04_housing_validation.py" ]
[ "\"\"\"\n Copyright (c) 2021 Olivier Sprangers as part of Airlab Amsterdam\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n https://github.com/elephaint/pgbm/blob/main/LICENSE\n\n\"\"\"\n\n#%% Load packages\nimport torch\nfrom pgbm import PGBM\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.datasets import fetch_california_housing\nimport matplotlib.pyplot as plt\n#%% Objective for pgbm\ndef mseloss_objective(yhat, y, sample_weight=None):\n gradient = (yhat - y)\n hessian = torch.ones_like(yhat)\n\n return gradient, hessian\n\ndef rmseloss_metric(yhat, y, sample_weight=None):\n loss = (yhat - y).pow(2).mean().sqrt()\n\n return loss\n#%% Load data\nX, y = fetch_california_housing(return_X_y=True)\n#%% Parameters\nparams = {'min_split_gain':0,\n 'min_data_in_leaf':2,\n 'max_leaves':8,\n 'max_bin':64,\n 'learning_rate':0.1,\n 'n_estimators':2000,\n 'verbose':2,\n 'early_stopping_rounds':100,\n 'feature_fraction':1,\n 'bagging_fraction':1,\n 'seed':1,\n 'reg_lambda':1,\n 'device':'gpu',\n 'gpu_device_id':0,\n 'derivatives':'exact',\n 'distribution':'normal'}\n\nn_forecasts = 1000\nn_splits = 2\nbase_estimators = 2000\n#%% Validation loop\nrmse, crps = torch.zeros(n_splits), torch.zeros(n_splits)\nfor i in range(n_splits):\n print(f'Fold {i+1}/{n_splits}')\n # Split for model validation\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=i)\n X_train_val, X_val, y_train_val, y_val = train_test_split(X_train, y_train, test_size=0.2, random_state=i)\n # Build datasets\n train_data = (X_train, y_train)\n train_val_data = (X_train_val, y_train_val)\n valid_data = (X_val, y_val)\n # Train to retrieve best iteration\n print('PGBM Validating on partial dataset...')\n params['n_estimators'] = base_estimators\n model = PGBM()\n model.train(train_val_data, objective=mseloss_objective, metric=rmseloss_metric, valid_set=valid_data, params=params)\n # Set iterations to best iteration\n params['n_estimators'] = model.best_iteration\n # Retrain on full set \n print('PGBM Training on full dataset...')\n model = PGBM()\n model.train(train_data, objective=mseloss_objective, metric=rmseloss_metric, params=params)\n #% Predictions\n print('PGBM Prediction...')\n yhat_point = model.predict(X_test)\n yhat_dist = model.predict_dist(X_test, n_forecasts=n_forecasts)\n # Scoring\n rmse[i] = model.metric(yhat_point.cpu(), y_test)\n crps[i] = model.crps_ensemble(yhat_dist.cpu(), y_test).mean() \n # Print scores current fold\n print(f'RMSE Fold {i+1}, {rmse[i]:.2f}')\n print(f'CRPS Fold {i+1}, {crps[i]:.2f}')\n \n# Print final scores\nprint(f'RMSE {rmse.mean():.2f}+-{rmse.std():.2f}')\nprint(f'CRPS {crps.mean():.2f}+-{crps.std():.2f}')\n#%% Plot all samples\nplt.plot(y_test, 'o', label='Actual')\nplt.plot(yhat_point.cpu(), 'ko', label='Point prediction PGBM')\nplt.plot(yhat_dist.cpu().max(dim=0).values, 'k--', label='Max bound PGBM')\nplt.plot(yhat_dist.cpu().min(dim=0).values, 'k--', label='Min bound PGBM')\nplt.legend()" ]
[ [ "torch.ones_like", "matplotlib.pyplot.legend", "torch.zeros", "matplotlib.pyplot.plot", "sklearn.model_selection.train_test_split", "sklearn.datasets.fetch_california_housing" ] ]
zhangkaifang/cp_decomposition
[ "75eb5f3df302c08ad2e62f41e6d93bb990a16797" ]
[ "matrix_cp_one.py" ]
[ "#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n'''=====================================\n@Author :Kaifang Zhang\n@Time :2021/7/5 1:31\n@Contact: [email protected]\n========================================'''\nimport numpy as np\n\n\ndef LFM_grad_desc(R, K, max_iter, alpha=1e-4, lamda=1e-4):\n \"\"\"\n 实现矩阵缺失元素补全使用梯度下降法!\n \"\"\"\n # 基本维度参数定义\n M = len(R)\n N = len(R[0])\n\n # P、Q初始值,随机生成\n P = np.random.rand(M, K)\n Q = np.random.rand(N, K)\n Q = Q.T\n # 开始迭代\n for step in range(max_iter):\n # 对所有的用户u、物品i做遍历,对应的特征向量Pu,Qi梯度下降\n for u in range(M):\n for i in range(N):\n # 对于每一个大于0的评分,求出预测的评分误差\n if R[u][i] > 0:\n eui = np.dot(P[u, :], Q[:, i]) - R[u][i]\n\n # 带入公式,按照梯度下降算法更新当前的Pu与Qi\n for k in range(K):\n P[u][k] = P[u][k] - alpha * (2 * eui * Q[k][i] + 2 * lamda * P[u][k])\n Q[k][i] = Q[k][i] - alpha * (2 * eui * P[u][k] + 2 * lamda * Q[k][i])\n\n # u、i遍历完成,所有的特征向量更新完成,可以得到P、Q,可以计算预测评分矩阵\n predR = np.dot(P, Q)\n\n # 计算当前损失函数\n cost = 0\n for u in range(M):\n for i in range(N):\n if R[u][i] > 0:\n cost += (np.dot(P[u, :], Q[:, i]) - R[u][i]) ** 2\n # 加上正则化项\n for k in range(K):\n cost += lamda * (P[u][k] ** 2 + Q[k][i] ** 2)\n if step % 1000 == 0:\n print(\"迭代次数:\", step, \"损失函数:\", cost)\n if cost < 0.001:\n break\n\n return P, Q.T, cost\n\n\nif __name__ == '__main__':\n '''\n @输入参数\n R:M*N的评分矩阵\n K:隐特征向量维度\n max_iter:最大迭代次数\n alpha:步长\n lamda:正则化系数\n @输出\n 分解之后的P、Q\n P:初始化用户特征矩阵M*k\n Q:初始化物品特征矩阵N*K\n '''\n # 评分矩阵R\n R = np.array([[4, 0, 2, 0, 1],\n [0, 0, 2, 3, 1],\n [4, 1, 2, 0, 1],\n [4, 1, 2, 5, 1],\n [3, 0, 5, 0, 2],\n [1, 0, 3, 0, 4]])\n\n # 给定超参数\n K = 5\n max_iter = 100000\n alpha = 1e-4\n lamda = 1e-3\n P, Q, cost = LFM_grad_desc(R, K, max_iter, alpha, lamda)\n predR = P.dot(Q.T)\n # 预测矩阵\n print(predR)\n" ]
[ [ "numpy.array", "numpy.dot", "numpy.random.rand" ] ]
EmiCareOfCell44/BigDL
[ "6278ee8eed09b5072da53dab3a99530cf5f69ba2" ]
[ "python/nano/src/bigdl/nano/pytorch/onnx/onnxrt_inference.py" ]
[ "#\n# Copyright 2016 The BigDL Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nfrom pytorch_lightning import LightningModule\nimport onnxruntime as ort\nfrom functools import partial\nimport warnings\nimport torch\nimport math\nimport numpy as np\n\n\nONNXRT_BINDED_COMPONENTS = ['_ortsess_up_to_date',\n '_ortsess',\n '_build_ortsess',\n 'update_ortsess',\n 'predict_step',\n 'inference']\n\n\ndef bind_onnxrt_methods(pl_model: LightningModule):\n # class type check\n assert isinstance(pl_model, LightningModule),\\\n \"onnxruntime support is only valid for a LightningModule.\"\n\n # check conflicts\n for component in ONNXRT_BINDED_COMPONENTS:\n if component in dir(pl_model):\n warnings.warn(f\"{component} method/property will be replaced.\")\n\n # additional attributes\n pl_model._ortsess_up_to_date = False # indicate if we need to build ortsess again\n pl_model._ortsess = None # ortsess instance\n\n # internal function to build an ortsess\n def _build_ortsess(self,\n input_sample=None,\n file_path=\"model.onnx\",\n sess_options=None,\n **kwargs):\n '''\n Internal function to build a ortsess and bind to the lightningmodule.\n\n :param input_sample: torch.Tensor for the model tracing.\n :param file_path: The path to save onnx model file.\n :param sess_options: ortsess options in ort.SessionOptions type\n :param **kwargs: will be passed to torch.onnx.export function.\n '''\n\n if input_sample is None and self.example_input_array is not None:\n input_sample = self.example_input_array # use internal example_input_array\n else:\n self.example_input_array = input_sample # set example_input_array for future usage\n\n assert input_sample is not None,\\\n 'You should set either input_sample or self.example_input_array'\n\n default_onnx_export_args = {'export_params': True,\n 'opset_version': 10,\n 'do_constant_folding': True,\n 'input_names': ['input'],\n 'output_names': ['output'],\n 'dynamic_axes': {'input': {0: 'batch_size'},\n 'output': {0: 'batch_size'}}}\n default_onnx_export_args.update(kwargs)\n\n self.to_onnx(file_path,\n input_sample,\n **default_onnx_export_args)\n\n self._ortsess = ort.InferenceSession(file_path, sess_options=sess_options)\n self._ortsess_up_to_date = True\n\n pl_model._build_ortsess = partial(_build_ortsess, pl_model)\n\n # external method to update(& rebuild) ortsess\n def update_ortsess(self,\n input_sample=None,\n file_path=\"model.onnx\",\n sess_options=None,\n **kwargs):\n '''\n Update the onnxruntime session options and rebuild the session.\n Users may also want to call this method before `inference(..., onnx=True`)`\n to avoid implicit building.\n\n :param input_sample: torch.Tensor for the model tracing.\n :param file_path: The path to save onnx model file.\n :param sess_options: ortsess options in ort.SessionOptions type.\n :param **kwargs: will be passed to torch.onnx.export function.\n '''\n self._build_ortsess(input_sample=input_sample,\n file_path=file_path,\n sess_options=sess_options,\n **kwargs)\n\n pl_model.update_ortsess = partial(update_ortsess, pl_model)\n\n # on_fit_start (LightningModule method override)\n def on_fit_start_additional(function):\n def wrapped(*args, **kwargs):\n args[0]._ortsess_up_to_date = False\n return function(**kwargs) # drop *args because that pl_model function has self binded\n return wrapped\n pl_model.on_fit_start = partial(on_fit_start_additional(pl_model.on_fit_start), pl_model)\n\n # predict_step (LightningModule method overwrite)\n # note: this overwrite users' customized predict_step if valid\n def predict_step(self, batch, batch_idx):\n # use batch[0] because that we assume data loader will have 2 outputs in format of (x, y)\n return self.inference(batch[0].numpy())\n\n pl_model.predict_step = partial(predict_step, pl_model)\n\n # inference (new API to unifying users' inference method)\n def inference(self,\n input_data,\n batch_size=None,\n file_path=\"model.onnx\",\n sess_options=None,\n backend=\"onnx\",\n **kwargs):\n '''\n Inference with/without onnxruntime.\n This method will implicitly build onnxruntime session if it has never been built\n or out-of-date.\n\n :param input_data: input data for prediction. If backend is set to \"onnx\",\n the data type should be a numpy ndarray, where the first dim should be batch size.\n If backend is NOT set to \"onnx\", a torch tensor is needed and the pytorch\n forwarding method will be called.\n :param batch_size: int, inferencing batch_size. This value should not affect the\n final inferencing result but will affect resources cost(e.g. memory and time).\n Default to None, which takes all input_data in one batch.\n :param file_path: The path to save onnx model file.\n :param sess_options: ortsess options in ort.SessionOptions type.\n :param backend: str, to set the backend library. \"onnx\" for onnxruntime, which\n provides lower latency and any other value will make `inference` call\n the pytorch forwarding method.\n :param **kwargs: any other keywords that will be passed to onnx session's building.\n '''\n\n if backend == \"onnx\":\n if not self._ortsess_up_to_date:\n warnings.warn(\"Onnxruntime session will be built implicitly,\"\n \" this may harm your inference latency.\")\n input_sample = torch.Tensor(input_data)\n self._build_ortsess(input_sample=input_sample,\n file_path=file_path,\n sess_options=sess_options,\n **kwargs)\n input_name = self._ortsess.get_inputs()[0].name\n if batch_size is None:\n # this branch is only to speed up the inferencing when batch_size is set to None.\n ort_inputs = {input_name: input_data}\n ort_outs = self._ortsess.run(None, ort_inputs)\n return ort_outs[0]\n else:\n yhat_list = []\n sample_num = input_data.shape[0] # the first dim should be sample_num\n batch_num = math.ceil(sample_num / batch_size)\n for batch_id in range(batch_num):\n ort_inputs = {input_name: input_data[batch_id * batch_size:\n (batch_id + 1) * batch_size]}\n ort_outs = self._ortsess.run(None, ort_inputs)\n yhat_list.append(ort_outs[0])\n # this operation may cause performance degradation\n yhat = np.concatenate(yhat_list, axis=0)\n return yhat\n else:\n # inference w/o onnxruntime (fallback to pytorch native forward)\n self.eval()\n with torch.no_grad():\n yhat_list = []\n sample_num = input_data.shape[0] # the first dim should be sample_num\n batch_size = batch_size if batch_size else sample_num\n batch_num = math.ceil(sample_num / batch_size)\n for batch_id in range(batch_num):\n yhat_list.append(self(input_data[batch_id * batch_size:\n (batch_id + 1) * batch_size]))\n yhat = torch.cat(yhat_list, axis=0)\n return yhat\n\n pl_model.inference = partial(inference, pl_model)\n\n return pl_model\n" ]
[ [ "numpy.concatenate", "torch.no_grad", "torch.cat", "torch.Tensor" ] ]
gavinmacaulay/echopype
[ "1698b6076a16506f638e691d4d014c8649cc735d" ]
[ "echopype/convert/set_groups_ad2cp.py" ]
[ "from typing import List, Optional\n\nimport numpy as np\nimport xarray as xr\n\nfrom .parse_ad2cp import Ad2cpDataPacket, Field, HeaderOrDataRecordFormats\nfrom .set_groups_base import SetGroupsBase, set_encodings\n\n\ndef merge_attrs(datasets: List[xr.Dataset]) -> List[xr.Dataset]:\n \"\"\"\n Merges attrs from a list of datasets.\n Prioritizes keys from later datsets.\n \"\"\"\n\n total_attrs = dict()\n for ds in datasets:\n total_attrs.update(ds.attrs)\n for ds in datasets:\n ds.attrs = total_attrs\n return datasets\n\n\nclass SetGroupsAd2cp(SetGroupsBase):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.pulse_compressed = self.parser_obj.get_pulse_compressed()\n self.combine_packets()\n\n def combine_packets(self):\n self.ds = None\n\n # # TODO: where to put string data in output?\n\n # pad raw samples so that \"sample\" dimenion has same length\n max_samples = 0\n for packet in self.parser_obj.echosounder_raw_packets:\n # both _r and _i have same dimensions\n max_samples = max(\n max_samples, packet.data[\"echosounder_raw_samples_i\"].shape[0]\n )\n for packet in self.parser_obj.echosounder_raw_packets:\n packet.data[\"echosounder_raw_samples_i\"] = np.pad(\n packet.data[\"echosounder_raw_samples_i\"],\n ((0, max_samples - packet.data[\"echosounder_raw_samples_i\"].shape[0])),\n )\n packet.data[\"echosounder_raw_samples_q\"] = np.pad(\n packet.data[\"echosounder_raw_samples_q\"],\n ((0, max_samples - packet.data[\"echosounder_raw_samples_q\"].shape[0])),\n )\n\n def make_dataset(\n packets: List[Ad2cpDataPacket], ping_time_dim: str\n ) -> Optional[xr.Dataset]:\n for i in range(len(packets)):\n packet = packets[i]\n data_vars = dict()\n for field_name, field_value in packet.data.items():\n # add dimension names to data vars for xarray\n # TODO might not work with altimeter_spare\n field = HeaderOrDataRecordFormats.data_record_format(\n packet.data_record_type\n ).get_field(field_name)\n if field is not None:\n dims = field.dimensions(packet.data_record_type)\n units = field.units()\n else:\n dims = Field.default_dimensions()\n units = None\n if units:\n data_vars[field_name] = (\n tuple(dim.value for dim in dims),\n [field_value],\n {\"Units\": units},\n )\n else:\n data_vars[field_name] = (\n tuple(dim.value for dim in dims),\n [field_value],\n )\n coords = {\n \"ping_time\": [packet.timestamp],\n ping_time_dim: [packet.timestamp],\n }\n if \"beams\" in packet.data_exclude:\n coords[\"beam\"] = packet.data_exclude[\"beams\"]\n new_packet = xr.Dataset(data_vars=data_vars, coords=coords)\n\n # modify in place to reduce memory consumption\n packets[i] = new_packet\n if len(packets) > 0:\n packets = merge_attrs(packets)\n return xr.combine_by_coords(\n packets,\n data_vars=\"minimal\",\n coords=\"minimal\",\n combine_attrs=\"override\",\n )\n else:\n return None\n\n burst_ds = make_dataset(\n self.parser_obj.burst_packets, ping_time_dim=\"ping_time_burst\"\n )\n average_ds = make_dataset(\n self.parser_obj.average_packets, ping_time_dim=\"ping_time_average\"\n )\n echosounder_ds = make_dataset(\n self.parser_obj.echosounder_packets, ping_time_dim=\"ping_time_echosounder\"\n )\n echosounder_raw_ds = make_dataset(\n self.parser_obj.echosounder_raw_packets,\n ping_time_dim=\"ping_time_echosounder_raw\",\n )\n echosounder_raw_transmit_ds = make_dataset(\n self.parser_obj.echosounder_raw_transmit_packets,\n ping_time_dim=\"ping_time_echosounder_raw_transmit\",\n )\n\n datasets = [\n ds\n for ds in (\n burst_ds,\n average_ds,\n echosounder_ds,\n echosounder_raw_ds,\n echosounder_raw_transmit_ds,\n )\n if ds\n ]\n\n for dataset in datasets:\n if \"offset_of_data\" in dataset:\n print(dataset[\"offset_of_data\"])\n\n datasets = merge_attrs(datasets)\n self.ds = xr.merge(datasets)\n\n def set_env(self) -> xr.Dataset:\n ds = xr.Dataset(\n data_vars={\n \"sound_speed_indicative\": self.ds.get(\"speed_of_sound\"),\n \"temperature\": self.ds.get(\"temperature\"),\n \"pressure\": self.ds.get(\"pressure\"),\n },\n coords={\n \"ping_time\": self.ds.get(\"ping_time\"),\n \"ping_time_burst\": self.ds.get(\"ping_time_burst\", []),\n \"ping_time_average\": self.ds.get(\"ping_time_average\", []),\n \"ping_time_echosounder\": self.ds.get(\"ping_time_echosounder\", []),\n },\n )\n\n # FIXME: this is a hack because the current file saving\n # mechanism requires that the env group have ping_time as a dimension,\n # but ping_time might not be a dimension if the dataset is completely\n # empty\n if \"ping_time\" not in ds.dims:\n ds = ds.expand_dims(dim=\"ping_time\")\n\n return set_encodings(ds)\n\n def set_platform(self) -> xr.Dataset:\n ds = xr.Dataset(\n data_vars={\n \"heading\": self.ds.get(\"heading\"),\n \"pitch\": self.ds.get(\"pitch\"),\n \"roll\": self.ds.get(\"roll\"),\n \"magnetometer_raw_x\": self.ds.get(\"magnetometer_raw_x\"),\n \"magnetometer_raw_y\": self.ds.get(\"magnetometer_raw_y\"),\n \"magnetometer_raw_z\": self.ds.get(\"magnetometer_raw_z\"),\n },\n coords={\n \"ping_time\": self.ds.get(\"ping_time\"),\n \"ping_time_burst\": self.ds.get(\"ping_time_burst\"),\n \"ping_time_average\": self.ds.get(\"ping_time_average\"),\n \"ping_time_echosounder\": self.ds.get(\"ping_time_echosounder\"),\n \"beam\": self.ds.get(\"beam\"),\n \"range_bin_burst\": self.ds.get(\"range_bin_burst\"),\n \"range_bin_average\": self.ds.get(\"range_bin_average\"),\n \"range_bin_echosounder\": self.ds.get(\"range_bin_echosounder\"),\n },\n attrs={\n \"platform_name\": self.ui_param[\"platform_name\"],\n \"platform_type\": self.ui_param[\"platform_type\"],\n \"platform_code_ICES\": self.ui_param[\"platform_code_ICES\"],\n },\n )\n return set_encodings(ds)\n\n def set_beam(self) -> xr.Dataset:\n # TODO: should we divide beam into burst/average (e.g., beam_burst, beam_average)\n # like was done for range_bin (we have range_bin_burst, range_bin_average,\n # and range_bin_echosounder)?\n data_vars = {\n \"number_of_beams\": self.ds.get(\"num_beams\"),\n \"coordinate_system\": self.ds.get(\"coordinate_system\"),\n \"number_of_cells\": self.ds.get(\"num_cells\"),\n \"blanking\": self.ds.get(\"blanking\"),\n \"cell_size\": self.ds.get(\"cell_size\"),\n \"velocity_range\": self.ds.get(\"velocity_range\"),\n \"echosounder_frequency\": self.ds.get(\"echosounder_frequency\"),\n \"ambiguity_velocity\": self.ds.get(\"ambiguity_velocity\"),\n \"data_set_description\": self.ds.get(\"dataset_description\"),\n \"transmit_energy\": self.ds.get(\"transmit_energy\"),\n \"velocity_scaling\": self.ds.get(\"velocity_scaling\"),\n \"velocity_burst\": self.ds.get(\"velocity_data_burst\"),\n \"velocity_average\": self.ds.get(\"velocity_data_average\"),\n # \"velocity_echosounder\": self.ds.get(\"velocity_data_echosounder\"),\n \"amplitude_burst\": self.ds.get(\"amplitude_data_burst\"),\n \"amplitude_average\": self.ds.get(\"amplitude_data_average\"),\n # \"amplitude_echosounder\": self.ds.get(\"amplitude_data_echosounder\"),\n \"correlation_burst\": self.ds.get(\"correlation_data_burst\"),\n \"correlation_average\": self.ds.get(\"correlation_data_average\"),\n \"correlation_echosounder\": self.ds.get(\"correlation_data_echosounder\"),\n # \"echosounder\": self.ds.get(\"echosounder_data\"),\n \"amplitude_echosounder\": self.ds.get(\"echosounder_data\"),\n \"figure_of_merit\": self.ds.get(\"figure_of_merit_data\"),\n \"altimeter_distance\": self.ds.get(\"altimeter_distance\"),\n \"altimeter_quality\": self.ds.get(\"altimeter_quality\"),\n \"ast_distance\": self.ds.get(\"ast_distance\"),\n \"ast_quality\": self.ds.get(\"ast_quality\"),\n \"ast_offset_100us\": self.ds.get(\"ast_offset_100us\"),\n \"ast_pressure\": self.ds.get(\"ast_pressure\"),\n \"altimeter_spare\": self.ds.get(\"altimeter_spare\"),\n \"altimeter_raw_data_num_samples\": self.ds.get(\n \"altimeter_raw_data_num_samples\"\n ),\n \"altimeter_raw_data_sample_distance\": self.ds.get(\n \"altimeter_raw_data_sample_distance\"\n ),\n \"altimeter_raw_data_samples\": self.ds.get(\"altimeter_raw_data_samples\"),\n }\n\n ds = xr.Dataset(\n data_vars=data_vars,\n coords={\n \"ping_time\": self.ds.get(\"ping_time\"),\n \"ping_time_burst\": self.ds.get(\"ping_time_burst\"),\n \"ping_time_average\": self.ds.get(\"ping_time_average\"),\n \"ping_time_echosounder\": self.ds.get(\"ping_time_echosounder\"),\n \"beam\": self.ds.get(\"beam\"),\n \"range_bin_burst\": self.ds.get(\"range_bin_burst\"),\n \"range_bin_average\": self.ds.get(\"range_bin_average\"),\n \"range_bin_echosounder\": self.ds.get(\"range_bin_echosounder\"),\n \"altimeter_sample_bin\": self.ds.get(\"altimeter_sample_bin\"),\n },\n attrs={\"pulse_compressed\": self.pulse_compressed},\n )\n\n # FIXME: this is a hack because the current file saving\n # mechanism requires that the beam group have ping_time as a dimension,\n # but ping_time might not be a dimension if the dataset is completely\n # empty\n if \"ping_time\" not in ds.dims:\n ds = ds.expand_dims(dim=\"ping_time\")\n\n return set_encodings(ds)\n\n def set_vendor(self) -> xr.Dataset:\n attrs = {\n \"pressure_sensor_valid\": self.ds.get(\"pressure_sensor_valid\"),\n \"temperature_sensor_valid\": self.ds.get(\"temperature_sensor_valid\"),\n \"compass_sensor_valid\": self.ds.get(\"compass_sensor_valid\"),\n \"tilt_sensor_valid\": self.ds.get(\"tilt_sensor_valid\"),\n }\n attrs = {\n field_name: field_value.data[0]\n for field_name, field_value in attrs.items()\n if field_value is not None\n }\n ds = xr.Dataset(\n data_vars={\n \"data_record_version\": self.ds.get(\"version\"),\n \"error\": self.ds.get(\"error\"),\n \"status\": self.ds.get(\"status\"),\n \"status0\": self.ds.get(\"status0\"),\n \"battery_voltage\": self.ds.get(\"battery_voltage\"),\n \"power_level\": self.ds.get(\"power_level\"),\n \"temperature_of_pressure_sensor\": self.ds.get(\n \"temperature_from_pressure_sensor\"\n ),\n \"nominal_correlation\": self.ds.get(\"nominal_correlation\"),\n \"magnetometer_temperature\": self.ds.get(\"magnetometer_temperature\"),\n \"real_ping_time_clock_temperature\": self.ds.get(\n \"real_ping_time_clock_temperature\"\n ),\n \"ensemble_counter\": self.ds.get(\"ensemble_counter\"),\n \"ahrs_rotation_matrix_mij\": (\n (\"mij\", \"ping_time\")\n if \"ahrs_rotation_matrix_m11\" in self.ds\n else \"mij\",\n [\n self.ds.get(\"ahrs_rotation_matrix_m11\"),\n self.ds.get(\"ahrs_rotation_matrix_m12\"),\n self.ds.get(\"ahrs_rotation_matrix_m13\"),\n self.ds.get(\"ahrs_rotation_matrix_m21\"),\n self.ds.get(\"ahrs_rotation_matrix_m22\"),\n self.ds.get(\"ahrs_rotation_matrix_m23\"),\n self.ds.get(\"ahrs_rotation_matrix_m31\"),\n self.ds.get(\"ahrs_rotation_matrix_m32\"),\n self.ds.get(\"ahrs_rotation_matrix_m33\"),\n ],\n ),\n \"ahrs_quaternions_wxyz\": (\n (\"wxyz\", \"ping_time\")\n if \"ahrs_quaternions_w\" in self.ds\n else \"wxyz\",\n [\n self.ds.get(\"ahrs_quaternions_w\"),\n self.ds.get(\"ahrs_quaternions_x\"),\n self.ds.get(\"ahrs_quaternions_y\"),\n self.ds.get(\"ahrs_quaternions_z\"),\n ],\n ),\n \"ahrs_gyro_xyz\": (\n (\"xyz\", \"ping_time\") if \"ahrs_gyro_x\" in self.ds else \"xyz\",\n [\n self.ds.get(\"ahrs_gyro_x\"),\n self.ds.get(\"ahrs_gyro_y\"),\n self.ds.get(\"ahrs_gyro_z\"),\n ],\n ),\n \"percentage_good_data\": self.ds.get(\"percentage_good_data\"),\n \"std_dev_pitch\": self.ds.get(\"std_dev_pitch\"),\n \"std_dev_roll\": self.ds.get(\"std_dev_roll\"),\n \"std_dev_heading\": self.ds.get(\"std_dev_heading\"),\n \"std_dev_pressure\": self.ds.get(\"std_dev_pressure\"),\n \"echosounder_raw_samples_i\": self.ds.get(\"echosounder_raw_samples_i\"),\n \"echosounder_raw_samples_q\": self.ds.get(\"echosounder_raw_samples_q\"),\n \"echosounder_raw_transmit_samples_i\": self.ds.get(\n \"echosounder_raw_transmit_samples_i\"\n ),\n \"echosounder_raw_transmit_samples_q\": self.ds.get(\n \"echosounder_raw_transmit_samples_q\"\n ),\n \"echosounder_raw_beam\": self.ds.get(\"echosounder_raw_beam\"),\n \"echosounder_raw_echogram\": self.ds.get(\"echosounder_raw_echogram\"),\n },\n coords={\n \"ping_time\": self.ds.get(\"ping_time\"),\n \"ping_time_burst\": self.ds.get(\"ping_time_burst\"),\n \"ping_time_average\": self.ds.get(\"ping_time_average\"),\n \"ping_time_echosounder\": self.ds.get(\"ping_time_echosounder\"),\n \"ping_time_echosounder_raw\": self.ds.get(\"ping_time_echosounder_raw\"),\n \"ping_time_echosounder_raw_transmit\": self.ds.get(\n \"ping_time_echosounder_raw_transmit\"\n ),\n \"sample\": self.ds.get(\"sample\"),\n \"sample_transmit\": self.ds.get(\"sample_transmit\"),\n \"beam\": self.ds.get(\"beam\"),\n \"range_bin_average\": self.ds.get(\"range_bin_average\"),\n \"range_bin_burst\": self.ds.get(\"range_bin_burst\"),\n \"range_bin_echosounder\": self.ds.get(\"range_bin_echosounder\"),\n },\n attrs={**attrs, \"pulse_compressed\": self.pulse_compressed},\n )\n ds = ds.reindex(\n {\n \"mij\": np.array([\"11\", \"12\", \"13\", \"21\", \"22\", \"23\", \"31\", \"32\", \"33\"]),\n \"wxyz\": np.array([\"w\", \"x\", \"y\", \"z\"]),\n \"xyz\": np.array([\"x\", \"y\", \"z\"]),\n }\n )\n\n # FIXME: this is a hack because the current file saving\n # mechanism requires that the vendor group have ping_time as a dimension,\n # but ping_time might not be a dimension if the dataset is completely\n # empty\n if \"ping_time\" not in ds.dims:\n ds = ds.expand_dims(dim=\"ping_time\")\n\n return set_encodings(ds)\n\n def set_sonar(self) -> xr.Dataset:\n ds = xr.Dataset(\n attrs={\n \"sonar_manufacturer\": \"Nortek\",\n \"sonar_model\": \"AD2CP\",\n \"sonar_serial_number\": \"\",\n \"sonar_software_name\": \"\",\n \"sonar_software_version\": \"\",\n \"sonar_firmware_version\": \"\",\n \"sonar_type\": \"acoustic Doppler current profiler (ADCP)\",\n }\n )\n if \"serial_number\" in self.ds:\n ds.attrs[\"sonar_serial_number\"] = int(self.ds[\"serial_number\"].data[0])\n firmware_version = self.parser_obj.get_firmware_version()\n if firmware_version is not None:\n ds.attrs[\"sonar_firmware_version\"] = \", \".join(\n [f\"{k}:{v}\" for k, v in firmware_version.items()]\n )\n return ds\n" ]
[ [ "numpy.array", "numpy.pad" ] ]
nenb/cycling_in_france
[ "6cddc433a2136f52be996719db0a1d876fcf5c59" ]
[ "cycling_in_france/helper_func.py" ]
[ "import regionmask\nimport numpy as np\nimport dask\n\n\ndef create_windmax_dict(u, v, names, borders, longitude, latitude):\n \"\"\"Produce a dictionary of masked maximum wind speeds in units of mph.\"\"\"\n\n if u.units != \"m s**-1\":\n raise ValueError(\"U field does not have units m/s\")\n if v.units != \"m s**-1\":\n raise ValueError(\"V field does not have units m/s\")\n metre_to_mile = 3600.0 / 1609.3\n speed = np.sqrt(u ** 2 + v ** 2) * metre_to_mile\n\n windmax_dict = {}\n for i, regname in enumerate(names):\n # Modify index in case any entries have been dropped e.g. Corsica\n idx = names.index[i]\n # Create object from 'borders' for masking gridded data\n regmask = regionmask.Regions(name=regname, outlines=list(borders[idx]))\n # Apply mask to dataset coordinates\n mask_zeros = regmask.mask(longitude, latitude)\n # Replace zeros with ones for matrix multiplication\n mask_ones = mask_zeros.where(np.isnan(mask_zeros.values), 1)\n # Use Dask dataframes for lazy execution\n mask_ones = dask.array.from_array(mask_ones)\n speed_mask = speed * mask_ones\n # Compute maximum over lat-lon grid\n windmax_dict[regname] = speed_mask.max(dim=[\"longitude\", \"latitude\"])\n return windmax_dict\n" ]
[ [ "numpy.sqrt", "numpy.isnan" ] ]
AldrickF/SlicerRegularizedFastMarching
[ "8a04a594cf5dd6c98e1f9dd93e61af6e6852339f" ]
[ "RegularizedFastMarching/RegularizedFastMarchingLib/Regularization.py" ]
[ "def regularization(InputImage, StructuringElementRadius=3):\n \"\"\"\n Compute the 3D scalar field that will be used to regularize the seeds propagation\n Inputs:\n * InputImage: the 3D image that will be segmented. Must be a 3D numpy array.\n * StructuringElementRadius: A structuring element of size (1+2*StructuringElementRadius) x (1+2*StructuringElementRadius) x (1+2*StructuringElementRadius) will be used\n Outputs:\n * R: The 3D numpy array having the same size as InputImage, used for the regularization\n \"\"\"\n\n from scipy import ndimage\n MSE = StructuringElementRadius\n return ndimage.morphological_gradient(InputImage, size=(MSE, MSE, MSE))" ]
[ [ "scipy.ndimage.morphological_gradient" ] ]
wohlbier/GraphSAINT
[ "cea64e77d97b77d76b05fba17cbfaa0d985d9aa3" ]
[ "graphsaint/setup.py" ]
[ "# cython: language_level=3\nfrom distutils.core import setup, Extension\nfrom Cython.Build import cythonize\nimport numpy\n# import cython_utils\n\nimport os\nos.environ[\"CC\"] = \"g++\"\nos.environ[\"CXX\"] = \"g++\"\n\nsetup(ext_modules = cythonize([\"graphsaint/cython_sampler.pyx\",\"graphsaint/cython_utils.pyx\",\"graphsaint/norm_aggr.pyx\"]), include_dirs = [numpy.get_include()])\n# to compile: python graphsaint/setup.py build_ext --inplace\n" ]
[ [ "numpy.get_include" ] ]
YoshimitsuMatsutaIe/ans_2021
[ "a04cd9b9541583aaa8a6dc5ece323ae1cf706c3b" ]
[ "example_py/example_2.py" ]
[ "### SciPyを使った実装 ###\nimport numpy as np\nfrom scipy.integrate import solve_ivp\nimport matplotlib.pyplot as plt\n\n\ndef diff_eq(x, t, a):\n \"\"\"微分方程式\"\"\"\n return a * x\n\ndef do_example_2():\n time_list = np.arange(0.0, 2.0, 0.01) # 時間のリスト\n x_init = [1.0] # 初期値\n \n a = 1\n \n # 解く\n sol = solve_ivp(\n fun = diff_eq,\n y0 = x_init,\n t_span=(0.0, 2.0),\n t_eval = time_list,\n method = 'RK45',\n args = (a,)\n ) # scipy.integrate.odeintソルバー.他のソルバーもある.\n \n # グラフ化\n fig = plt.figure() # figureインスタンスを作成\n ax = fig.add_subplot(111) #figureオブジェクトにaxesを追加\n ax.plot(list(time_list), sol.y[0], label = \"solution\") # プロットを入れる\n ax.set_xlabel('time') # x軸にラベルを追加\n ax.set_ylabel('x') # y軸にラベルを追加\n ax.grid(True) # グリッドを入れる\n ax.legend() # 凡例を入れる\n ax.set_aspect('equal', adjustable='box') # 軸を揃える\n \n plt.show() # プロットを表示\n\n\nif __name__ == '__main__':\n do_example_2()" ]
[ [ "numpy.arange", "matplotlib.pyplot.figure", "scipy.integrate.solve_ivp", "matplotlib.pyplot.show" ] ]
LLNL/XNAS
[ "62f90bb29b492a3b993d7a866d229634a2d95057" ]
[ "experiments/mnist/load_data.py" ]
[ "\"\"\"\nMIT License\n\nCopyright (c) 2022, Lawrence Livermore National Security, LLC\nWritten by Zachariah Carmichael et al.\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\"\"\"\nfrom xnas.utils import get_logger\n\nlogger = get_logger(__name__)\n\n\ndef preprocess(image, label):\n import tensorflow as tf\n\n mean = [0.13066044]\n std = [0.3081079]\n\n # converting dtype changes uint8 [0..255] to float [0.,1.]\n image = tf.image.convert_image_dtype(image, dtype=tf.float32)\n image = (image - tf.reshape(mean, [1, 1, 1])) / tf.reshape(std, [1, 1, 1])\n\n label = tf.one_hot(label, depth=10, dtype=tf.int32)\n\n return image, label\n\n\ndef augment(image, label):\n import tensorflow as tf\n import tensorflow_addons as tfa\n\n pad = 4\n # random crop with zero-padding\n image = tf.image.resize_with_crop_or_pad(image,\n 28 + pad * 2,\n 28 + pad * 2)\n image = tf.image.random_crop(image, size=[28, 28, 1])\n # random LR flip\n image = tf.image.random_flip_left_right(image)\n # cutout\n image = tfa.image.random_cutout(tf.expand_dims(image, 0), (8, 8))\n image = tf.squeeze(image, axis=0)\n return image, label\n\n\ndef load_data():\n def load_train():\n import tensorflow as tf\n import tensorflow_datasets as tfds\n\n ds_train = tfds.load('mnist', as_supervised=True, split='train')\n ds_train = (\n ds_train\n .map(preprocess, num_parallel_calls=tf.data.AUTOTUNE)\n .cache()\n .map(augment, num_parallel_calls=tf.data.AUTOTUNE)\n )\n return ds_train\n\n def load_test():\n import tensorflow as tf\n import tensorflow_datasets as tfds\n\n ds_test = tfds.load('mnist', as_supervised=True, split='test')\n ds_test = (\n ds_test\n .map(preprocess, num_parallel_calls=tf.data.AUTOTUNE)\n .cache()\n )\n return ds_test\n\n train_size, valid_size = 60000, 10000\n\n return {\n 'train_gen': load_train,\n 'train_size': train_size,\n 'valid_gen': load_test,\n 'valid_size': valid_size,\n 'types': ({'input_0': 'float32'}, 'int32'),\n 'shapes': ({'input_0': (28, 28, 1)}, (10,)),\n }\n" ]
[ [ "tensorflow.image.random_flip_left_right", "tensorflow.reshape", "tensorflow.image.random_crop", "tensorflow.expand_dims", "tensorflow.squeeze", "tensorflow.image.convert_image_dtype", "tensorflow.one_hot", "tensorflow.image.resize_with_crop_or_pad" ] ]
EpistasisLab/penn-ml-benchmarks
[ "ac4ae198e62a7828cb9ff957d805bc33197dca28" ]
[ "pmlb/pmlb.py" ]
[ "# -*- coding: utf-8 -*-\n\n\"\"\"\nPMLB was primarily developed at the University of Pennsylvania by:\n - Randal S. Olson ([email protected])\n - William La Cava ([email protected])\n - Weixuan Fu ([email protected])\n - and many more generous open source contributors\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software\nand associated documentation files (the \"Software\"), to deal in the Software without restriction,\nincluding without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,\nand/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial\nportions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT\nLIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\nWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\"\"\"\n\nimport pandas as pd\nimport os\nfrom .dataset_lists import (\n dataset_names,\n classification_dataset_names, \n regression_dataset_names)\nimport requests\nimport warnings\nimport subprocess\nimport pathlib\n\nfrom sklearn.neighbors import NearestNeighbors\nfrom sklearn.preprocessing import StandardScaler\nfrom .support_funcs import (\n generate_summarystats, \n get_dataset_stats,\n last_commit_message\n)\nimport numpy as np\n\nGITHUB_URL = 'https://github.com/EpistasisLab/pmlb/raw/master/datasets'\nsuffix = '.tsv.gz'\n\ndef fetch_data(dataset_name, return_X_y=False, local_cache_dir=None, dropna=True):\n \"\"\"Download a data set from the PMLB, (optionally) store it locally, and return the data set.\n\n You must be connected to the internet if you are fetching a data set that is not cached locally.\n\n Parameters\n ----------\n dataset_name: str\n The name of the data set to load from PMLB.\n return_X_y: bool (default: False)\n Whether to return the data in scikit-learn format, with the features \n and labels stored in separate NumPy arrays.\n local_cache_dir: str (default: None)\n The directory on your local machine to store the data files.\n If None, then the local data cache will not be used.\n dropna: bool\n If True, pmlb will drop NAs in exported dataset.\n\n Returns\n ----------\n dataset: pd.DataFrame or (array-like, array-like)\n if return_X_y == False: A pandas DataFrame containing the fetched data set.\n if return_X_y == True: A tuple of NumPy arrays containing (features, labels)\n\n \"\"\"\n\n if local_cache_dir is None:\n if dataset_name not in dataset_names:\n raise ValueError('Dataset not found in PMLB.')\n dataset_url = get_dataset_url(GITHUB_URL,\n dataset_name, suffix)\n dataset = pd.read_csv(dataset_url, sep='\\t', compression='gzip')\n else:\n dataset_path = os.path.join(local_cache_dir, dataset_name,\n dataset_name+suffix)\n\n # Use the local cache if the file already exists there\n if os.path.exists(dataset_path):\n dataset = pd.read_csv(dataset_path, sep='\\t', compression='gzip')\n # Download the data to the local cache if it is not already there\n else:\n if dataset_name not in dataset_names:\n raise ValueError('Dataset not found in PMLB.')\n dataset_url = get_dataset_url(GITHUB_URL,\n dataset_name, suffix)\n dataset = pd.read_csv(dataset_url, sep='\\t', compression='gzip')\n dataset_dir = os.path.split(dataset_path)[0]\n if not os.path.isdir(dataset_dir):\n os.makedirs(dataset_dir)\n dataset.to_csv(dataset_path, sep='\\t', compression='gzip',\n index=False)\n\n if dropna:\n dataset.dropna(inplace=True)\n if return_X_y:\n X = dataset.drop('target', axis=1).values\n y = dataset['target'].values\n return (X, y)\n else:\n return dataset\n\n\ndef get_dataset_url(GITHUB_URL, dataset_name, suffix):\n dataset_url = '{GITHUB_URL}/{DATASET_NAME}/{DATASET_NAME}{SUFFIX}'.format(\n GITHUB_URL=GITHUB_URL,\n DATASET_NAME=dataset_name,\n SUFFIX=suffix\n )\n\n re = requests.get(dataset_url)\n if re.status_code != 200:\n raise ValueError('Dataset not found in PMLB.')\n return dataset_url\n\ndef get_updated_datasets(local_cache_dir='datasets'):\n \"\"\"Looks at commit and returns a list of datasets that were updated.\"\"\"\n cmd = 'git diff --name-only HEAD HEAD~1'\n res = subprocess.check_output(cmd.split(), universal_newlines=True).rstrip()\n changed_datasets = set()\n changed_metadatas = set()\n for path in res.splitlines():\n path = pathlib.Path(path)\n if path.parts[0] != 'datasets':\n continue\n if path.name.endswith('.tsv.gz'):\n changed_datasets.add(path.parts[-2])\n if path.name == 'metadata.yaml':\n changed_metadatas.add(path.parts[-2])\n \n datasets_remain = [x.name for x in pathlib.Path(local_cache_dir).iterdir()]\n changed_metadatas &= set(datasets_remain)\n changed_datasets &= set(datasets_remain)\n\n changed_datasets = sorted(changed_datasets)\n changed_metadatas = sorted(changed_metadatas)\n print(\n f'changed datasets: {changed_datasets}\\n'\n f'changed metadata: {changed_metadatas}'\n )\n return {'changed_datasets': changed_datasets,\n 'changed_metadatas': changed_metadatas}\n\ndef nearest_datasets(X, y=None, task='classification', n=1, \n dimensions=['n_instances', 'n_features']):\n \"\"\"\n X: numpy array or pandas DataFrame\n an n_samples x n_features array of independent variables\n y: numpy array or None (default: None)\n a n_samples array of dependent variables\n task: 'regression' or 'classification' (default: 'classification')\n specify the task.\n n: int (default: 1)\n the number of dataset names to return\n dimensions: list of str or str (default: ['NumberOfInstances',\n 'NumberOfFeatures'])\n a list of dataset characteristics to include in similarity calculation.\n Dimensions must correspond to columns of datasets/all_summary_stats.csv.\n If 'all', uses all numeric columns.\n \"\"\"\n if isinstance(X, np.ndarray):\n if y == None:\n ValueError('the target (y) must be specified if a np array '\n 'is passed.')\n df = pd.DataFrame({**{'x_'+str(i):x for i,x in enumerate(X.transpose)}\n **{'target':y}})\n elif isinstance(X, pd.DataFrame):\n df = X\n \n return fetch_nearest_dataset_names(df, task, n, dimensions)\n\ndef fetch_nearest_dataset_names(df, task, n, dimensions):\n \"\"\"Returns names of most similar datasets to df, in order of similarity. \n\n Parameters\n ----------\n df: pandas Dataframe \n a dataframe of n_samples x n_features+1 with a target column labeled\n 'target'\n task: str \n specify classification or regression for summary stat generation. \n n: int (default: 1)\n the number of dataset names to return\n dimensions: list of str or str (default: ['NumberOfInstances',\n 'NumberOfFeatures'])\n a list of dataset characteristics to include in similarity calculation.\n Dimensions must correspond to columns of datasets/all_summary_stats.csv.\n If 'all', uses all numeric columns.\n\n Returns\n -------\n dataset_names: an n-element list of dataset names in order of most similar \n to least similar.\n \"\"\"\n\n # load pmlb summary stats\n path = pathlib.Path(__file__).parent / \"all_summary_stats.tsv\"\n pmlb_stats = pd.read_csv(path, sep = '\\t')\n # restrict to same task\n pmlb_stats = pmlb_stats.loc[pmlb_stats.task==task]\n all_names = pmlb_stats['dataset'].values\n # restrict to floating point data in stats\n pmlb_stats = pmlb_stats.apply(\n lambda x: pd.to_numeric(x,errors='coerce')).dropna(axis=1,how='all')\n\n if dimensions=='all':\n dimensions = list(pmlb_stats.columns)\n else:\n pmlb_stats = pmlb_stats[dimensions] \n assert(all([d in pmlb_stats.columns for d in dimensions]))\n\n dataset_stats_tmp = get_dataset_stats(df)\n dataset_stats_tmp['yaml_task'] = task\n dataset_stats = generate_summarystats('dataset', dataset_stats_tmp, \n write_summary=False)\n dataset_stats = dataset_stats[dimensions]\n\n\n # #categorical and #continuous features columns\n ss = StandardScaler()\n pmlb_stats_norm = ss.fit_transform(pmlb_stats) \n\n # find nearest neighbors\n nn = NearestNeighbors(n_neighbors=n).fit(pmlb_stats_norm)\n distances, ds = nn.kneighbors(ss.transform(dataset_stats), n_neighbors=n, \n return_distance=True)\n # print([(name, dist) for name, dist in zip(all_names[ds.flatten()],\n # distances.flatten())])\n dataset_names = all_names[ds.flatten()]\n\n return dataset_names\n\ndef get_reviewed_datasets(dataset_names, local_cache_dir = 'datasets/'):\n reviewed_datasets = []\n\n for dataset_name in dataset_names:\n if local_cache_dir != None:\n meta_path = pathlib.Path(f'{local_cache_dir}{dataset_name}/metadata.yaml')\n if meta_path.exists():\n with open(meta_path, 'r') as f:\n header = f.readline()\n else:\n meta_url = '{GITHUB_URL}/{DATASET_NAME}/metadata.yaml'.format(\n GITHUB_URL=GITHUB_URL,\n DATASET_NAME=dataset_name\n )\n header = requests.get(meta_url).text.splitlines()[0] + '\\n'\n\n if header != '# Reviewed by [your name here]\\n':\n reviewed_datasets.append(dataset_name)\n \n return sorted(reviewed_datasets)\n\ndef select_datasets(obs_min = None, obs_max = None, feat_min = None, feat_max = None, class_min = None, class_max = None, endpt = None, max_imbalance = None, task = None):\n \"\"\"Filters existing datasets by given parameters, and returns a list of their names.\n\n Parameters\n ----------\n obs_min: int (default: None)\n The minimum acceptable number of observations/instances in the dataset\n obs_Max: int (default: None)\n The maximum acceptable number of observations/instances in the dataset\n feat_min: int (default: None)\n The minimum acceptable number of features in the dataset\n feat_max: int (default: None)\n The maximum acceptable number of features in the dataset\n class_min: int (default: None)\n The minimum acceptable number of classes in the dataset\n class_max: int (default: None)\n The maximum acceptable number of classes in the dataset\n max_imbalance: float (default: None)\n Maximum acceptable imbalance value for the dataset\n endpt: str (default: None)\n Whether the dataset endpoint type should be discrete, continuous, categorical, or binary\n task: str (default: None)\n Whether the dataset is suited for classification or regression problems\n Returns\n ----------\n list (str): \n list of names of datasets within filters. Will return an empty list if no datasets match.\n\n\n \"\"\"\n\n path = pathlib.Path(__file__).parent / \"all_summary_stats.tsv\"\n tempdf = pd.read_csv(path, sep = '\\t')\n if obs_min is not None:\n tempdf = tempdf.loc[tempdf['n_instances'] >= obs_min]\n if obs_max is not None:\n tempdf = tempdf.loc[tempdf['n_instances'] <= obs_max]\n if feat_min is not None:\n tempdf = tempdf.loc[tempdf['n_features'] >= feat_min]\n if feat_max is not None:\n tempdf = tempdf.loc[tempdf['n_features'] <= feat_max]\n if class_min is not None:\n tempdf = tempdf.loc[tempdf['n_classes'] >= class_min]\n if class_max is not None:\n tempdf = tempdf.loc[tempdf['n_classes'] <= class_max]\n if max_imbalance is not None:\n tempdf = tempdf.loc[tempdf['imbalance'] < max_imbalance]\n if endpt is not None:\n tempdf = tempdf.loc[tempdf['endpoint_type'] == endpt]\n if task is not None:\n tempdf = tempdf.loc[tempdf['task'] == task]\n return list(tempdf['dataset'].values)\n" ]
[ [ "pandas.read_csv", "sklearn.neighbors.NearestNeighbors", "pandas.to_numeric", "sklearn.preprocessing.StandardScaler" ] ]
haroldship/SCLPsolver
[ "70b79acb074f51d4a269993f6a1fcf04a8196a89" ]
[ "SCLPsolver/tests/MCQN_test_mpc.py" ]
[ "# Copyright 2020 IBM Corporation\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport sys\nimport numpy as np\nimport os\nproj = os.path.realpath(os.path.join(os.path.dirname(os.path.realpath(__file__)), '..'))\nsys.path.append(proj)\nfrom SCLP import SCLP, SCLP_settings\nfrom doe.data_generators.MCQN import generate_MCQN_data\nfrom subroutines.utils import relative_to_project\nfrom doe.results_producer import write_results_to_csv\n\nK = 400\nI = 40\nimport time\nsolver_settings = SCLP_settings(find_alt_line=False, check_intermediate_solution=False, memory_management= False, suppress_printing = False)\n\nsettings = {'alpha_rate': 1, 'cost_scale':2, 'a_rate' : 0.05, 'sum_rate':0.95, 'nz': 0.5,\n 'gamma_rate':0, 'c_scale': 0, 'h_rate': 0.2}\nseed = 1009\nG, H, F, gamma, c, d, alpha, a, b, TT, total_buffer_cost, buffer_cost = generate_MCQN_data(seed, K, I, **settings)\nTT = 100\n\n# import cProfile, pstats, io\n# pr = cProfile.Profile()\n#pr.enable()\nresult = {'servers': I, 'buffers': K, 'seed': seed}\nstart_time = time.time()\nsolution, STEPCOUNT, param_line, res = SCLP(G, H, F, a, b, c, d, alpha, gamma, 3/12 * TT, solver_settings)\nt, x, q, u, p, pivots, obj, err, NN, tau, maxT = solution.get_final_solution(True)\n#pr.disable()\nprint(obj, err, maxT)\ntime1 = time.time() - start_time\nprint(\"--- %s seconds ---\" % time1)\nresult['time1'] = time1\nresult['STEPCOUNT1'] = STEPCOUNT\nt0 = 1/12 * TT\nlast_breakpoint = np.where(t<=t0)[0][-1]\ndelta_t = t0 - t[last_breakpoint]\nnew_x0 = x[:, last_breakpoint] + solution._state.dx[:, last_breakpoint] * delta_t + 0.1 * a * t0\nstart_time = time.time()\nSTEPCOUNT, pivot_problem = solution.recalculate(param_line, t0, 4/12 * TT, new_x0, solver_settings, 10E-11, mm = None)\nt, x, q, u, p, pivots, obj, err, NN, tau, maxT = solution.get_final_solution(True)\nprint(obj, err, maxT)\ntime2 = time.time() - start_time\nprint(\"--- %s seconds ---\" % time2)\nresult['time2'] = time2\nresult['STEPCOUNT2'] = STEPCOUNT\nalpha = new_x0\nstart_time = time.time()\nsolution, STEPCOUNT, param_line, res = SCLP(G, H, F, a, b, c, d, alpha, gamma, 3/12 * TT, solver_settings)\nt, x, q, u, p, pivots, obj, err, NN, tau, maxT = solution.get_final_solution(True)\n#pr.disable()\nprint(obj, err, maxT)\ntime3 = time.time() - start_time\nprint(\"--- %s seconds ---\" % time3)\nresult['time3'] = time3\nresult['STEPCOUNT3'] = STEPCOUNT\n# start_time = time.time()\n# STEPCOUNT, pivot_problem =solution.recalculate(param_line, 1/12 * TT, 4/12 * TT, None, solver_settings, 10E-11, mm = None)\n# t, x, q, u, p, pivots, obj, err, NN, tau, maxT = solution.get_final_solution(True)\n# print(obj, err, maxT)\n# time3 = time.time() - start_time\n# print(\"--- %s seconds ---\" % time3)\n# result['time3'] = time3\n# result['STEPCOUNT3'] = STEPCOUNT\n# start_time = time.time()\n# STEPCOUNT, pivot_problem = solution.recalculate(param_line, 1/12 * TT, 4/12 * TT, None, solver_settings, 10E-11, mm = None)\n# t, x, q, u, p, pivots, obj, err, NN, tau, maxT = solution.get_final_solution(True)\n# print(obj, err, maxT)\n# time4 = time.time() - start_time\n# print(\"--- %s seconds ---\" % time4)\n# result['time4'] = time4\n# result['STEPCOUNT4'] = STEPCOUNT\n# results = [result]\n# res_file = relative_to_project('online_results.csv')\n# write_results_to_csv(results, res_file)\n# # s = io.StringIO()\n# # ps = pstats.Stats(pr, stream=s)\n# # ps.print_stats()\n# # print(s.getvalue())" ]
[ [ "numpy.where" ] ]
dennis-l/so_pysm_models
[ "da21d51fd09ef409542862a773d22ed1656bb1bb" ]
[ "so_pysm_models/alms.py" ]
[ "import numpy as np\nimport healpy as hp\n\ntry:\n from pixell import curvedsky, enmap\nexcept:\n pass\n\ntry: # PySM >= 3.2.1\n import pysm3.units as u\n import pysm3 as pysm\nexcept ImportError:\n import pysm.units as u\n import pysm\n\n\nclass PrecomputedAlms(object):\n def __init__(\n self,\n filename,\n input_units=\"uK_CMB\",\n input_reference_frequency=None,\n nside=None,\n target_shape=None,\n target_wcs=None,\n from_cl=False,\n from_cl_seed=None,\n precompute_output_map=True,\n has_polarization=True,\n map_dist=None,\n ):\n \"\"\"Generic component based on Precomputed Alms\n\n Load a set of Alms from a FITS file and generate maps at the requested\n resolution and frequency assuming the CMB black body spectrum.\n A single set of Alms is used for all frequencies requested by PySM,\n consider that PySM expects the output of components to be in uK_RJ.\n See more details at https://so-pysm-models.readthedocs.io/en/latest/so_pysm_models/models.html\n\n Also note that the Alms are clipped to 3*nside-1 to avoid\n artifacts from high-ell components which cannot be properly represented\n by a low-nside map.\n\n Parameters\n ----------\n filename : string\n Path to the input Alms in FITS format\n input_units : string\n Input unit strings as defined by pysm.convert_units, e.g. K_CMB, uK_RJ, MJysr\n input_reference_frequency: float\n If input units are K_RJ or Jysr, the reference frequency\n nside : int\n HEALPix NSIDE of the output maps\n from_cl : bool\n If True, the input file contains C_ell instead of a_lm,\n they should provided with the healpy old ordering TT, TE, TB, EE, EB, BB, sorry.\n from_cl_seed : int\n Seed set just before synalm to simulate the alms from the C_ell,\n necessary to set it in order to get the same input map for different runs\n only used if `from_cl` is True\n precompute_output_map : bool\n If True (default), Alms are transformed into a map in the constructor,\n if False, the object only stores the Alms and generate the map at each\n call of the signal method, this is useful to generate maps convolved\n with different beams\n has_polarization : bool\n whether or not to simulate also polarization maps\n Default: True\n \"\"\"\n\n self.nside = nside\n self.shape = target_shape\n self.wcs = target_wcs\n self.filename = filename\n self.input_units = u.Unit(input_units)\n self.has_polarization = has_polarization\n\n if from_cl:\n np.random.seed(from_cl_seed)\n cl = hp.read_cl(self.filename)\n if not self.has_polarization and cl.ndim > 1:\n cl = cl[0]\n # using healpy old ordering TT, TE, TB, EE, EB, BB\n alm = hp.synalm(cl, new=False, verbose=False)\n else:\n alm = np.complex128(\n hp.read_alm(\n self.filename, hdu=(1, 2, 3) if self.has_polarization else 1\n )\n )\n\n self.equivalencies = (\n None\n if input_reference_frequency is None\n else u.cmb_equivalencies(input_reference_frequency)\n )\n if precompute_output_map:\n self.output_map = self.compute_output_map(alm)\n\n else:\n self.alm = alm\n\n def compute_output_map(self, alm):\n\n lmax = hp.Alm.getlmax(alm.shape[-1]) # we assume mmax = lmax\n if self.nside is None:\n assert (self.shape is not None) and (self.wcs is not None)\n n_comp = 3 if self.has_polarization else 1\n output_map = enmap.empty((n_comp,) + self.shape[-2:], self.wcs)\n curvedsky.alm2map(alm, output_map, spin=[0, 2], verbose=True)\n elif self.nside is not None:\n if lmax > 3*self.nside-1:\n clip = np.ones(3*self.nside)\n if alm.ndim == 1:\n alm_clipped = hp.almxfl(alm, clip)\n else:\n alm_clipped = [hp.almxfl(each, clip) for each in alm]\n else:\n alm_clipped = alm\n output_map = hp.alm2map(alm_clipped, self.nside)\n else:\n raise ValueError(\"You must specify either nside or both of shape and wcs\")\n return (output_map << self.input_units).to(\n u.uK_CMB, equivalencies=self.equivalencies\n )\n\n @u.quantity_input\n def get_emission(\n self,\n freqs: u.GHz,\n fwhm: [u.arcmin, None] = None,\n weights=None,\n output_units=u.uK_RJ,\n ):\n \"\"\"Return map in uK_RJ at given frequency or array of frequencies\n\n Parameters\n ----------\n freqs : list or ndarray\n Frequency or frequencies in GHz at which compute the signal\n fwhm : float (optional)\n Smooth the input alms before computing the signal, this can only be used\n if the class was initialized with `precompute_output_map` to False.\n output_units : str\n Output units, as defined in `pysm.convert_units`, by default this is\n \"uK_RJ\" as expected by PySM.\n Returns\n -------\n output_maps : ndarray\n Output maps array with the shape (num_freqs, 1 or 3 (I or IQU), npix)\n \"\"\"\n\n freqs = pysm.utils.check_freq_input(freqs)\n weights = pysm.utils.normalize_weights(freqs, weights)\n\n try:\n output_map = self.output_map\n except AttributeError:\n if fwhm is None:\n alm = self.alm\n else:\n alm = hp.smoothalm(\n self.alm, fwhm=fwhm.to_value(u.radian), pol=True, inplace=False\n )\n\n output_map = self.compute_output_map(alm)\n\n output_units = u.Unit(output_units)\n assert output_units in [u.uK_RJ, u.uK_CMB]\n if output_units == u.uK_RJ:\n\n convert_to_uK_RJ = (\n np.ones(len(freqs), dtype=np.double) * u.uK_CMB\n ).to_value(u.uK_RJ, equivalencies=u.cmb_equivalencies(freqs * u.GHz))\n\n if len(freqs) == 1:\n scaling_factor = convert_to_uK_RJ[0]\n else:\n scaling_factor = np.trapz(convert_to_uK_RJ * weights, x=freqs)\n\n return output_map.value * scaling_factor << u.uK_RJ\n elif output_units == output_map.unit:\n return output_map\n" ]
[ [ "numpy.trapz", "numpy.random.seed", "numpy.ones" ] ]
zzpwahaha/DataCrylsis
[ "b4436435d6ead3322ce54d22e048077732e39e57" ]
[ "ExpFile.py" ]
[ "# created by mark brown\nimport h5py as h5\nfrom colorama import Fore, Style\nfrom numpy import array as arr\nimport numpy as np\nimport Miscellaneous as misc\nimport datetime\ndataAddress = None\ncurrentVersion = 1\n\ndef annotate(fileID=None, expFile_version=currentVersion, useBaseA=True):\n #hashNum = int(input(\"Title-Level: \"))\n hashNum = 3\n #titleStr = ''.join('#' for _ in range(hashNum)) + ' ' + title\n with ExpFile(expFile_version=expFile_version) as file:\n print('annotating file ' + str(fileID));\n file.open_hdf5(fileID, openFlag='a', useBase=useBaseA)\n if checkAnnotation(fileID, force=False, expFile_version=expFile_version): \n title, notes, num = getAnnotation(fileID, expFile_version=expFile_version, useBaseA=useBaseA)\n title = input(\"Run Title (\\\"q\\\" to Quit) (prev was \\\"\"+title+\"\\\"):\")\n if title == 'q':\n raise RuntimeError(\"Annotation Quit\")\n notes = input(\"Experiment Notes (\\\"q\\\" to Quit)(prev was \\\"\"+notes+\"\\\"):\")\n if notes == 'q':\n raise RuntimeError(\"Annotation Quit\")\n else:\n title = input(\"Run Title (\\\"q\\\" to Quit):\")\n if title == 'q':\n raise RuntimeError(\"Annotation Quit\")\n notes = input(\"Experiment Notes (\\\"q\\\" to Quit):\")\n if notes == 'q':\n raise RuntimeError(\"Annotation Quit\")\n\n if 'Experiment_Notes' in file.f['Miscellaneous'].keys():\n del file.f['Miscellaneous']['Experiment_Notes']\n dset2 = file.f['Miscellaneous'].create_dataset(\"Experiment_Notes\", shape=(1,), dtype=\"S\"+str(len(notes))) \n dset2[0] = np.string_(notes)\n \n if 'Experiment_Title' in file.f['Miscellaneous'].keys():\n del file.f['Miscellaneous']['Experiment_Title']\n dset3 = file.f['Miscellaneous'].create_dataset(\"Experiment_Title\", shape=(1,), dtype=\"S\"+str(len(title))) \n dset3[0] = np.string_(title)\n \n if 'Experiment_Title_Level' in file.f['Miscellaneous'].keys():\n del file.f['Miscellaneous']['Experiment_Title_Level']\n dset4 = file.f['Miscellaneous'].create_dataset(\"Experiment_Title_Level\", shape=(1,), dtype=\"i8\") \n dset4[0] = hashNum\n\n \ndef checkAnnotation(fileNum, force=True, quiet=False, expFile_version=currentVersion):\n try:\n with ExpFile(fileNum, expFile_version=expFile_version) as f:\n if ( 'Experiment_Notes' not in f.f['Miscellaneous']\n or 'Experiment_Title' not in f.f['Miscellaneous']):\n #pass\n if force:\n raise RuntimeError('HDF5 File number ' + str(fileNum) + ' Has not been annotated. Please call exp.annotate() to annotate the file.')\n else:\n print('HDF5 File number ' + str(fileNum) + ' Has not been annotated. Please call exp.annotate() to annotate the file.')\n return False\n except OSError:\n # failed to open file probably, nothing to annotate.\n return False\n except KeyError:\n # file failed to open, probably a special run\n return False\n return True\n\n\ndef getAnnotation(fid, expFile_version=currentVersion, useBaseA=True):\n with ExpFile() as f:\n f.open_hdf5(fid, useBase=useBaseA)\n f_misc = f.f['Miscellaneous']\n if ( 'Experiment_Notes' not in f_misc\n or 'Experiment_Title' not in f_misc):\n raise RuntimeError('HDF5 File number ' + str(fid) + ' Has not been annotated. Please call exp.annotate() to annotate the file.')\n if 'Experiment_Title_Level' not in f_misc:\n expTitleLevel = 0\n else:\n expTitleLevel = f_misc['Experiment_Title_Level'][0]\n return (f_misc['Experiment_Title'][0].decode(\"utf-8\"), \n f_misc['Experiment_Notes'][0].decode(\"utf-8\"),\n expTitleLevel)\n \ndef getConfiguration(fid, expFile_version=currentVersion, useBaseA=True):\n with ExpFile() as file:\n file.open_hdf5(fid, useBase=useBaseA)\n f_MI = file.f['Master-Input']\n if ('Configuration' not in f_MI):\n return \"\"\n return ''.join([char.decode('utf-8') for char in f_MI['Configuration']])\n \n#\"J:\\\\Data repository\\\\New Data Repository\"\ndef setPath(day, month, year, repoAddress=\"\\\\\\\\jilafile.colorado.edu\\\\scratch\\\\regal\\\\common\\\\LabData\\\\NewRb\\\\CryoData\"):\n \"\"\"\n This function sets the location of where all of the data files are stored. It is occasionally called more\n than once in a notebook if the user needs to work past midnight.\n\n :param day: A number string, e.g. '11'.\n :param month: The name of a month, e.g. 'November' (must match file path capitalization).\n :param year: A number string, e.g. '2017'.\n :return:\n \"\"\"\n global dataAddress\n if type(day) == int:\n day = str(day)\n if type(year) == int:\n year = str(year)\n dataAddress = repoAddress + \"\\\\\" + year + \"\\\\\" + month + \"\\\\\" + month + \" \" + day + \"\\\\Raw Data\\\\\"\n #print(\"Setting new data address:\" + dataAddress)\n return dataAddress\n\n\ndef addNote(fileID=None):\n notes = input(\"New Experiment Note:\")\n with ExpFile() as file:\n noteNum = 1\n file.open_hdf5(fileID, openFlag='a')\n while noteNum < 1000:\n if 'Experiment_Note_' + str(noteNum) not in file.f['Miscellaneous'].keys():\n dset2 = file.f['Miscellaneous'].create_dataset(\"Experiment_Note_\" + str(noteNum), shape=(1,), dtype=\"S\"+str(len(notes))) \n dset2[0] = np.string_(notes)\n break\n else:\n noteNum += 1\n\ndef getStartDatetime(fileID):\n with ExpFile() as file:\n file.open_hdf5(fileID)\n file.exp_start_date, file.exp_start_time, file.exp_stop_date, file.exp_stop_time = file.get_experiment_time_and_date()\n dt = datetime.datetime.strptime(file.exp_start_date + \" \" + file.exp_start_time[:-1], '%Y-%m-%d %H:%M:%S')\n return dt\n \n# Exp is short for experiment here.\nclass ExpFile:\n \"\"\"\n a wrapper around an hdf5 file for easier handling and management.\n \"\"\"\n def __init__(self, file_id=None, expFile_version=currentVersion, useBaseA=True, keyParameter=None):\n \"\"\"\n if you give the constructor a file_id, it will automatically fill the relevant member variables.\n \"\"\"\n if expFile_version is None:\n expFile_version = currentVersion\n #print('expfile version:', expFile_version)\n # copy the current value of the address\n self.version = expFile_version\n self.f = None\n self.key_name = None\n self.key = None \n self.pics = None\n self.reps = None\n self.exp_start_time = None\n self.exp_start_date = None\n self.exp_stop_time = None\n self.exp_stop_date = None\n self.data_addr = dataAddress\n if file_id is not None:\n self.f = self.open_hdf5(fileID=file_id, useBase=useBaseA)\n self.key_name, self.key = self.get_key(keyParameter=keyParameter)\n self.pics = self.get_pics()\n self.reps = self.get_reps()\n self.exp_start_date, self.exp_start_time, self.exp_stop_date, self.exp_stop_time = self.get_experiment_time_and_date()\n \n \n def __enter__(self):\n return self\n\n \n def __exit__(self, exc_type, exc_value, traceback):\n try:\n return self.f.close()\n except AttributeError:\n return\n \n \n def open_hdf5(self, fileID=None, useBase=True, openFlag='r'): \n \n if type(fileID) == int:\n path = self.data_addr + \"data_\" + str(fileID) + \".h5\"\n elif useBase:\n # assume a file address itself\n path = self.data_addr + fileID + \".h5\"\n else:\n path = fileID\n try:\n file = h5.File(path, openFlag) \n except OSError as err:\n raise OSError(\"Failed to open file! file address was \\\"\" + path + \"\\\". OSError: \" + str(err))\n self.f = file\n return file\n \n def get_reps(self):\n # call this one.\n self.reps = self.f['Master-Runtime']['Repetitions'][0]\n return self.reps \n\n def get_params(self):\n return self.f['Master-Runtime']['Parameters'] \n \n def get_key(self, keyParameter=None):\n \"\"\"\n :param file:\n :return:\n \"\"\"\n keyNames = []\n keyValues = []\n foundOne = False\n nokeyreturn = 'No-Variation', arr([1])\n try:\n params = self.get_params()\n for var in params:\n if not params[var]['Is Constant'][0]:\n foundOne = True\n keyNames.append(''.join([char.decode('utf-8') for char in params[var]['Name']]))\n keyValues.append(arr(params[var]['Key Values']))\n\n if foundOne:\n if len(keyNames) > 1:\n return keyNames, arr(misc.transpose(arr(keyValues)))\n else:\n return keyNames[0], arr(keyValues[0])\n else:\n if keyParameter is None:\n return nokeyreturn\n else:\n for var in params:\n name = ''.join([char.decode('utf-8') for char in params[var]['Name']])\n print(name)\n if name == keyParameter:\n return name , arr(params[var]['Key Values'])\n return \"Key not found!\", arr([1])\n except KeyError:\n return nokeyreturn\n \n def get_pics(self):\n p_t = arr(self.f['Andor']['Pictures'])\n pics = p_t.reshape((p_t.shape[0], p_t.shape[2], p_t.shape[1]))\n return pics\n \n def get_mako_pics(self):\n p_t = arr(self.f['Mako']['Pictures'])\n pics = p_t.reshape((p_t.shape[0], p_t.shape[2], p_t.shape[1]))\n return pics\n \n def get_basler_pics(self):\n p_t = arr(self.f['Basler']['Pictures'])\n pics = p_t.reshape((p_t.shape[0], p_t.shape[2], p_t.shape[1]))\n return pics\n \n def get_avg_pic(self):\n pics = self.get_pics()\n avg_pic = np.zeros(pics[0].shape)\n for p in pics:\n avg_pic += p\n avg_pic /= len(pics)\n return avg_pic\n\n def get_avg_mako_pic(self):\n pics = self.get_mako_pics()\n avg_pic = np.zeros(pics[0].shape)\n for p in pics:\n avg_pic += p\n avg_pic /= len(pics)\n return avg_pic\n\n def get_avg_basler_pic(self):\n pics = self.get_basler_pics()\n avg_pic = np.zeros(pics[0].shape)\n for p in pics:\n avg_pic += p\n avg_pic /= len(pics)\n return avg_pic\n \n def get_binning(self, type):\n if type == 'andor':\n binH = self.f['Andor']['Image-Dimensions']['Horizontal-Binning'][()][0]\n binV = self.f['Andor']['Image-Dimensions']['Vertical-Binning'][()][0]\n elif type == 'mako':\n binH = self.f['Mako']['Image-Dimensions']['Horizontal-Binning'][()][0]\n binV = self.f['Mako']['Image-Dimensions']['Vertical-Binning'][()][0]\n else:\n raise ValueError('Bad value for CameraType.')\n return binH, binV \n\n def print_all(self):\n self.__print_hdf5_obj(self.f,'')\n \n def print_all_groups(self):\n self.__print_groups(self.f,'')\n\n \n def print_parameters(self):\n self.__print_hdf5_obj(self.get_params(),'')\n \n def __print_groups(self, obj, prefix):\n \"\"\"\n Used recursively to print the structure of the file.\n obj can be a single file or a group or dataset within.\n \"\"\"\n for o in obj:\n if o == 'Functions':\n print(prefix, o)\n self.print_functions(prefix=prefix+'\\t')\n elif o == 'Master-Script' or o == \"Seq. 1 NIAWG-Script\":\n print(prefix,o)\n elif type(obj[o]) == h5._hl.group.Group:\n print(prefix, o)\n self.__print_groups(obj[o], prefix + '\\t')\n elif type(obj[o]) == h5._hl.dataset.Dataset:\n print(prefix, o)\n #else:\n # raise TypeError('???')\n \n def __print_hdf5_obj(self, obj, prefix):\n \"\"\"\n Used recursively in other print functions.\n obj can be a single file or a group or dataset within.\n \"\"\"\n for o in obj:\n if o == 'Functions':\n print(prefix, o)\n self.print_functions(prefix=prefix+'\\t')\n elif o == 'Master-Script' or o == \"Seq. 1 NIAWG-Script\":\n print(prefix,o)\n self.print_script(obj[o])\n elif type(obj[o]) == h5._hl.group.Group:\n print(prefix, o)\n self.__print_hdf5_obj(obj[o], prefix + '\\t')\n elif type(obj[o]) == h5._hl.dataset.Dataset:\n print(prefix, o, ':',end='')\n self.__print_ds(obj[o],prefix+'\\t')\n else:\n raise TypeError('???')\n \n def print_functions(self, brief=True, prefix='', which=None):\n \"\"\"\n print the list of all functions which were created at the time of the experiment.\n if not brief, print the contents of every function.\n \"\"\"\n funcList = self.f['Master-Input']['Functions']\n for func in funcList:\n if which is not None:\n if func != which:\n print(func)\n continue\n print(prefix,'-',func,end='')\n if not brief:\n print(': \\n---------------------------------------')\n # I think it's a bug that this is nested like this.\n indvFunc = funcList[func]\n for x in indvFunc:\n for y in indvFunc[x]:\n # print(Style.DIM, y.decode('utf-8'), end='') for some reason the \n # DIM isn't working at the moment on the data analysis comp...\n print(y.decode('utf-8'), end='')\n print('\\n---------------------------------------\\ncount=')\n print('')\n\n def print_master_script(self):\n # A shortcut\n self.print_script(self.f['Master-Input']['Master-Script'])\n\n def print_niawg_script(self):\n # A shortcut\n self.print_script(self.f['NIAWG']['Seq. 1 NIAWG-Script'])\n\n \n def print_script(self, script):\n \"\"\"\n special formatting used for printing long scripts which are stored as normal numpy bytes.\n \"\"\"\n print(Fore.GREEN,'\\n--------------------------------------------')\n for x in script:\n print(x.decode('UTF-8'),end='')\n print('\\n--------------------------------------------\\n\\n', Style.RESET_ALL)\n \n def __print_ds(self, ds, prefix):\n \"\"\"\n Print dataset\n \"\"\"\n if type(ds) != h5._hl.dataset.Dataset:\n raise TypeError('Tried to print non dataset as dataset.')\n else:\n if len(ds) > 0:\n if type(ds[0]) == np.bytes_:\n print(' \"',end='')\n for x in ds:\n print(x.decode('UTF-8'),end='')\n print(' \"',end='')\n elif type(ds[0]) in [np.uint8, np.uint16, np.uint32, np.uint64, \n np.int8, np.int16, np.int32, np.int64, \n np.float32, np.float64]:\n for x in ds:\n print(x,end=' ')\n else:\n print(' type:', type(ds[0]), ds[0])\n print('')\n \n def get_pic_info(self):\n infoStr = 'Number of Pictures: ' + str(self.pics.shape[0]) + '; '\n infoStr += 'Picture Dimensions: ' + str(self.pics.shape[1]) + ' x ' + str(self.pics.shape[2]) + '\\n'\n return infoStr\n \n \n def get_basic_info(self):\n \"\"\"\n Some quick easy to read summary info\n \"\"\"\n infoStr = self.get_pic_info()\n \n infoStr += 'Variations: ' + str(len(self.key)) + ';\\t'\n infoStr += 'Repetitions: ' + str(self.reps) + ';\\tExp File Version: ' + str(self.version) + ';''\\n'\n infoStr += 'Experiment started at (H:M:S) ' + str(self.exp_start_time) + ' on (Y-M-D) ' + str(self.exp_start_date) + ', '\n infoStr += 'And ended at ' + str(self.exp_stop_time) + ' on ' + str(self.exp_stop_date) + '\\n'\n if 'Experiment_Notes' in self.f['Miscellaneous'].keys():\n infoStr += 'Experiment Notes: ' + str(self.f['Miscellaneous']['Experiment_Notes'][0].decode(\"utf-8\")) + '\\n'\n else:\n infoStr += 'Experiment Notes: HDF5 NOT ANNOTATED: please call exp.Annotate() to annotate this file.\\n'\n if 'Experiment_Rationale' in self.f['Miscellaneous'].keys():\n infoStr += '(Old Notes format:) Experiment Rationale: ' + str(self.f['Miscellaneous']['Experiment_Rationale'][0].decode(\"utf-8\")) + '\\n'\n if 'Experiment_Result' in self.f['Miscellaneous'].keys():\n infoStr += '(Old Notes format:) Experiment Result: ' + str(self.f['Miscellaneous']['Experiment_Result'][0].decode(\"utf-8\")) + '\\n'\n expNoteNum = 1\n while expNoteNum < 1000:\n if 'Experiment_Note_' + str(expNoteNum) in self.f['Miscellaneous'].keys():\n infoStr += \"Extra Experiment Note #\" + str(expNoteNum) + \": \" + str(self.f['Miscellaneous']['Experiment_Note_' + str(expNoteNum)][0].decode(\"utf-8\")) + '\\n'\n expNoteNum += 1\n else: \n break\n print(infoStr)\n return infoStr\n\n def get_experiment_time_and_date(self):\n start_date, stop_date, start_time, stop_time = '','','',''\n try:\n start_date = ''.join([x.decode('UTF-8') for x in self.f['Miscellaneous']['Start-Date']])\n except KeyError:\n pass\n try:\n start_time = ''.join([x.decode('UTF-8') for x in self.f['Miscellaneous']['Start-Time']])\n except KeyError:\n pass\n try:\n stop_date = ''.join([x.decode('UTF-8') for x in self.f['Miscellaneous']['Stop-Date']])\n except KeyError:\n pass\n try:\n stop_time = ''.join([x.decode('UTF-8') for x in self.f['Miscellaneous']['Stop-Time']])\n except KeyError:\n pass\n return start_date, start_time, stop_date, stop_time\n #return \"\",\"\",\"\",\"\"\n\nif __name__ == \"__main__\":\n print(\"I am expfile\")\nif __name__==\"ExpFile\":\n print(\"I am imported expfile\")" ]
[ [ "numpy.array", "numpy.string_", "numpy.zeros" ] ]
yotammarton/TransformDF2Numpy
[ "3528fe2f207089186865290b9f5cbd14d91e8c82" ]
[ "tests/test_one_hot_encode.py" ]
[ "import unittest\nimport numpy as np\nimport pandas as pd\nimport df2numpy\nfrom df2numpy import TransformDF2Numpy, one_hot_encode, NAN_CATEGORY, DROPPED_CATEGORY\nfrom df2numpy.errors import *\n\n\ndf = pd.DataFrame({\n \"A\": [\"Aa\", \"Ab\", \"Ac\", \"Aa\", \"Ac\", \"Aa\", \"Aa\", \"Aa\"], # uniques: 3, to_be_thresholded: \"Ab\"\n \"B\": [1., -3., 0., 2, 3, 0, -1.3, 0.192],\n \"C\": [\"Ca\", np.nan, \"Cc\", \"Ca\", \"Cc\", \"Ca\", \"Cc\", \"Cc\"], # uniques: 2, nan: 1, (must be numerical)\n \"D\": [\"Da\", \"Db\", \"Dc\", \"Db\", \"Dc\", \"Da\", np.nan, \"Dc\"], # uniques: 3, nan: 1\n \"E\": [1., -3., np.nan, 2, np.nan, 0, -16.9, 20],\n \"Drop\": [\"x\", \"x\", \"x\", \"x\", \"x\", \"x\", \"x\", \"x\"], # must be dropped\n \"F\": [\"Fa\", \"Fb\", \"Fc\", \"Fd\", \"Fa\", \"Fb\", \"Fc\", \"Fd\"], # uniques: 4\n})\n\ntest_df = pd.DataFrame({\n \"A\": [\"Ac\", \"Aa\"],\n \"B\": [1.4, 0.],\n \"C\": [\"Cc\", \"Ca\"],\n \"D\": [\"Dc\", \"Db\"],\n \"E\": [4.3, 2],\n \"Drop\": [\"x\", \"x\"],\n \"F\": [\"Fd\", \"Fc\"]\n})\n\ntest_df_only1data = pd.DataFrame({\n \"A\": [\"Ac\"],\n \"B\": [1.4],\n \"C\": [\"Cc\"],\n \"D\": [\"Dc\"],\n \"E\": [4.3],\n \"Drop\": [\"x\"],\n \"F\": [\"Fd\"]\n})\n\ntest_df_with_nan = pd.DataFrame({\n \"A\": [\"Ac\", np.nan],\n \"B\": [np.nan, 1.4],\n \"C\": [np.nan, \"Cc\"],\n \"D\": [\"Dc\", np.nan],\n \"E\": [4.3, np.nan],\n \"Drop\": [\"x\", np.nan],\n \"F\": [np.nan, \"Fd\"]\n})\n\ntest_df_with_new_category = pd.DataFrame({\n \"A\": [\"Ac\", \"Anew\"], # should be in DROPPED_CATEGORY\n \"B\": [1.4, 0.],\n \"C\": [\"Cc\", \"Ca\"],\n \"D\": [\"Dnew\", \"Db\"], # should be in NAN_CATEGORY\n \"E\": [4.3, 2],\n \"Drop\": [\"x\", \"x\"],\n \"F\": [\"Fd\", \"Fnew\"] # should be in the most frequent category 'Fd'\n})\n\ntest_df_wrong_const1 = pd.DataFrame({\n \"A\": [\"Ac\", \"Aa\"],\n \"B\": [1.4, 0.],\n \"Wrong\": [\"wtf\", \"???\"],\n \"D\": [\"Dc\", \"Db\"],\n \"E\": [4.3, 2],\n \"Drop\": [\"x\", \"x\"],\n \"F\": [\"Fd\", \"Fc\"]\n})\n\ntest_df_wrong_const2 = pd.DataFrame({\n \"A\": [\"Ac\", \"Aa\"],\n \"C\": [\"Cc\", \"Ca\"],\n \"B\": [1.4, 0.],\n \"D\": [\"Dc\", \"Db\"],\n \"E\": [4.3, 2],\n \"Drop\": [\"x\", \"x\"],\n \"F\": [\"Fd\", \"Fc\"]\n})\n\ntest_df_wrong_const3 = pd.DataFrame({\n \"A\": [\"Ac\", \"Aa\"],\n \"B\": [1.4, 0.],\n \"D\": [\"Dc\", \"Db\"],\n \"E\": [4.3, 2],\n \"Drop\": [\"x\", \"x\"],\n \"F\": [\"Fd\", \"Fc\"]\n})\n\n\nclass TestOneHotEncode(unittest.TestCase):\n\n def setUp(self) -> None:\n pass\n\n def test_one_hot_encode_scaled(self):\n t = TransformDF2Numpy(min_category_count=2,\n numerical_scaling=True,\n fillnan=True,\n objective_col=\"B\")\n\n x, y = t.fit_transform(df)\n\n x_one_hot, var_names = one_hot_encode(t, x)\n\n self.assertTrue(x_one_hot.shape == (8, 13))\n\n self.assertListEqual(var_names, ['A_Aa', 'A_TransformDF2Numpy_dropped_category', 'A_Ac', 'D_Da',\n 'D_Db', 'D_Dc', 'D_TransformDF2Numpy_NaN_category', 'F_Fa', 'F_Fb',\n 'F_Fc', 'F_Fd', 'C', 'E'])\n\n for i, name in enumerate(var_names):\n self.assertTrue(-0.00001 < x_one_hot[:, i].mean() < 0.00001)\n self.assertTrue(0.9999 < x_one_hot[:, i].std() < 1.00001)\n\n def test_one_hot_encode_fillnan_false(self):\n t = TransformDF2Numpy(min_category_count=2,\n fillnan=False,\n objective_col=\"B\")\n\n x, y = t.fit_transform(df)\n\n x_one_hot, var_names = one_hot_encode(t, x)\n\n self.assertListEqual(var_names, ['A_Aa', 'A_TransformDF2Numpy_dropped_category', 'A_Ac', 'D_Da', 'D_Db',\n 'D_Dc', 'F_Fa', 'F_Fb', 'F_Fc', 'F_Fd', 'C', 'E'])\n\n self.assertTrue(x_one_hot.shape == (8, 12))\n\n self.assertListEqual(list(x_one_hot[6, 3:6]), [0., 0., 0.])\n\n def test_one_hot_encode_eliminate_verbose_feature(self):\n t = TransformDF2Numpy(min_category_count=2,\n fillnan=False,\n objective_col=\"B\")\n\n x, y = t.fit_transform(df)\n\n x_one_hot, var_names = one_hot_encode(t, x, elim_verbose=True)\n\n self.assertListEqual(var_names, ['A_Aa', 'A_TransformDF2Numpy_dropped_category', 'D_Da', 'D_Db',\n 'F_Fa', 'F_Fb', 'F_Fc', 'C', 'E'])\n\n self.assertTrue(x_one_hot.shape == (8, 9))\n\n x_one_hot_verbose, _ = one_hot_encode(t, x)\n self.assertTrue(np.alltrue(x_one_hot[:, 0:-2] == x_one_hot_verbose[:, [0,1,3,4,6,7,8]]))\n\n\n\n\n\n\n\n\n" ]
[ [ "numpy.alltrue", "pandas.DataFrame" ] ]
chrisjuniorli/pytorch-image-models
[ "bb815fa90c46b1f5f2f59a0dcddab8ce69f91dcf" ]
[ "validate.py" ]
[ "#!/usr/bin/env python3\n\"\"\" ImageNet Validation Script\n\nThis is intended to be a lean and easily modifiable ImageNet validation script for evaluating pretrained\nmodels or training checkpoints against ImageNet or similarly organized image datasets. It prioritizes\ncanonical PyTorch, standard Python style, and good performance. Repurpose as you see fit.\n\nHacked together by Ross Wightman (https://github.com/rwightman)\n\"\"\"\nimport argparse\nimport os\nimport csv\nimport glob\nimport time\nimport logging\nimport torch\nimport torch.nn as nn\nimport torch.nn.parallel\nfrom collections import OrderedDict\nfrom contextlib import suppress\n\nfrom timm.models import create_model, apply_test_time_pool, load_checkpoint, is_model, list_models\nfrom timm.data import create_dataset, create_loader, resolve_data_config, RealLabelsImagenet\nfrom timm.utils import accuracy, AverageMeter, natural_key, setup_default_logging, set_jit_legacy\nfrom ptflops import get_model_complexity_info\nimport pdb\nhas_apex = False\ntry:\n from apex import amp\n has_apex = True\nexcept ImportError:\n pass\n\nhas_native_amp = False\ntry:\n if getattr(torch.cuda.amp, 'autocast') is not None:\n has_native_amp = True\nexcept AttributeError:\n pass\n\ntorch.backends.cudnn.benchmark = True\n_logger = logging.getLogger('validate')\n\n\nparser = argparse.ArgumentParser(description='PyTorch ImageNet Validation')\nparser.add_argument('data', metavar='DIR',\n help='path to dataset')\nparser.add_argument('--dataset', '-d', metavar='NAME', default='',\n help='dataset type (default: ImageFolder/ImageTar if empty)')\nparser.add_argument('--split', metavar='NAME', default='validation',\n help='dataset split (default: validation)')\nparser.add_argument('--model', '-m', metavar='NAME', default='dpn92',\n help='model architecture (default: dpn92)')\nparser.add_argument('-j', '--workers', default=4, type=int, metavar='N',\n help='number of data loading workers (default: 2)')\nparser.add_argument('-b', '--batch-size', default=256, type=int,\n metavar='N', help='mini-batch size (default: 256)')\nparser.add_argument('--img-size', default=None, type=int,\n metavar='N', help='Input image dimension, uses model default if empty')\nparser.add_argument('--input-size', default=None, nargs=3, type=int,\n metavar='N N N', help='Input all image dimensions (d h w, e.g. --input-size 3 224 224), uses model default if empty')\nparser.add_argument('--crop-pct', default=None, type=float,\n metavar='N', help='Input image center crop pct')\nparser.add_argument('--mean', type=float, nargs='+', default=None, metavar='MEAN',\n help='Override mean pixel value of dataset')\nparser.add_argument('--std', type=float, nargs='+', default=None, metavar='STD',\n help='Override std deviation of of dataset')\nparser.add_argument('--interpolation', default='', type=str, metavar='NAME',\n help='Image resize interpolation type (overrides model)')\nparser.add_argument('--num-classes', type=int, default=None,\n help='Number classes in dataset')\nparser.add_argument('--class-map', default='', type=str, metavar='FILENAME',\n help='path to class to idx mapping file (default: \"\")')\nparser.add_argument('--gp', default=None, type=str, metavar='POOL',\n help='Global pool type, one of (fast, avg, max, avgmax, avgmaxc). Model default if None.')\nparser.add_argument('--log-freq', default=10, type=int,\n metavar='N', help='batch logging frequency (default: 10)')\nparser.add_argument('--checkpoint', default='', type=str, metavar='PATH',\n help='path to latest checkpoint (default: none)')\nparser.add_argument('--pretrained', dest='pretrained', action='store_true',\n help='use pre-trained model')\nparser.add_argument('--num-gpu', type=int, default=1,\n help='Number of GPUS to use')\nparser.add_argument('--no-test-pool', dest='no_test_pool', action='store_true',\n help='disable test time pool')\nparser.add_argument('--no-prefetcher', action='store_true', default=False,\n help='disable fast prefetcher')\nparser.add_argument('--pin-mem', action='store_true', default=False,\n help='Pin CPU memory in DataLoader for more efficient (sometimes) transfer to GPU.')\nparser.add_argument('--channels-last', action='store_true', default=False,\n help='Use channels_last memory layout')\nparser.add_argument('--amp', action='store_true', default=False,\n help='Use AMP mixed precision. Defaults to Apex, fallback to native Torch AMP.')\nparser.add_argument('--apex-amp', action='store_true', default=False,\n help='Use NVIDIA Apex AMP mixed precision')\nparser.add_argument('--native-amp', action='store_true', default=False,\n help='Use Native Torch AMP mixed precision')\nparser.add_argument('--tf-preprocessing', action='store_true', default=False,\n help='Use Tensorflow preprocessing pipeline (require CPU TF installed')\nparser.add_argument('--use-ema', dest='use_ema', action='store_true',\n help='use ema version of weights if present')\nparser.add_argument('--torchscript', dest='torchscript', action='store_true',\n help='convert model torchscript for inference')\nparser.add_argument('--legacy-jit', dest='legacy_jit', action='store_true',\n help='use legacy jit mode for pytorch 1.5/1.5.1/1.6 to get back fusion performance')\nparser.add_argument('--results-file', default='', type=str, metavar='FILENAME',\n help='Output csv file for validation results (summary)')\nparser.add_argument('--real-labels', default='', type=str, metavar='FILENAME',\n help='Real labels JSON file for imagenet evaluation')\nparser.add_argument('--valid-labels', default='', type=str, metavar='FILENAME',\n help='Valid label indices txt file for validation of partial label space')\nparser.add_argument('--params', action='store_true', default=False,\n help='only caculate params')\n\ndef validate(args):\n # might as well try to validate something\n args.pretrained = args.pretrained or not args.checkpoint\n args.prefetcher = not args.no_prefetcher\n amp_autocast = suppress # do nothing\n if args.amp:\n if has_native_amp:\n args.native_amp = True\n elif has_apex:\n args.apex_amp = True\n else:\n _logger.warning(\"Neither APEX or Native Torch AMP is available.\")\n assert not args.apex_amp or not args.native_amp, \"Only one AMP mode should be set.\"\n if args.native_amp:\n amp_autocast = torch.cuda.amp.autocast\n _logger.info('Validating in mixed precision with native PyTorch AMP.')\n elif args.apex_amp:\n _logger.info('Validating in mixed precision with NVIDIA APEX AMP.')\n else:\n _logger.info('Validating in float32. AMP not enabled.')\n\n if args.legacy_jit:\n set_jit_legacy()\n\n # create model\n model = create_model(\n args.model,\n pretrained=args.pretrained,\n num_classes=args.num_classes,\n in_chans=3,\n global_pool=args.gp,\n scriptable=args.torchscript)\n if args.num_classes is None:\n assert hasattr(model, 'num_classes'), 'Model must have `num_classes` attr if not set on cmd line/config.'\n args.num_classes = model.num_classes\n\n if args.checkpoint:\n load_checkpoint(model, args.checkpoint, args.use_ema)\n\n param_count = sum([m.numel() for m in model.parameters()])\n _logger.info('Model %s created, param count: %d' % (args.model, param_count))\n\n data_config = resolve_data_config(vars(args), model=model, use_test_size=True, verbose=True)\n test_time_pool = False\n if not args.no_test_pool:\n model, test_time_pool = apply_test_time_pool(model, data_config, use_test_size=True)\n\n if args.torchscript:\n torch.jit.optimized_execution(True)\n model = torch.jit.script(model)\n\n model = model.cuda()\n if args.apex_amp:\n model = amp.initialize(model, opt_level='O1')\n\n if args.channels_last:\n model = model.to(memory_format=torch.channels_last)\n\n if args.num_gpu > 1:\n model = torch.nn.DataParallel(model, device_ids=list(range(args.num_gpu)))\n\n criterion = nn.CrossEntropyLoss().cuda()\n\n dataset = create_dataset(\n root=args.data, name=args.dataset, split=args.split,\n load_bytes=args.tf_preprocessing, class_map=args.class_map)\n\n if args.valid_labels:\n with open(args.valid_labels, 'r') as f:\n valid_labels = {int(line.rstrip()) for line in f}\n valid_labels = [i in valid_labels for i in range(args.num_classes)]\n else:\n valid_labels = None\n\n if args.real_labels:\n real_labels = RealLabelsImagenet(dataset.filenames(basename=True), real_json=args.real_labels)\n else:\n real_labels = None\n\n crop_pct = 1.0 if test_time_pool else data_config['crop_pct']\n #pdb.set_trace()\n loader = create_loader(\n dataset,\n input_size=data_config['input_size'],\n batch_size=args.batch_size,\n use_prefetcher=args.prefetcher,\n interpolation=data_config['interpolation'],\n mean=data_config['mean'],\n std=data_config['std'],\n num_workers=args.workers,\n crop_pct=crop_pct,\n pin_memory=args.pin_mem,\n tf_preprocessing=args.tf_preprocessing)\n\n batch_time = AverageMeter()\n losses = AverageMeter()\n top1 = AverageMeter()\n top5 = AverageMeter()\n\n model.eval()\n with torch.no_grad():\n # warmup, reduce variability of first batch time, especially for comparing torchscript vs non\n input = torch.randn((args.batch_size,) + tuple(data_config['input_size'])).cuda()\n if args.channels_last:\n input = input.contiguous(memory_format=torch.channels_last)\n model(input)\n end = time.time()\n macs, params = get_model_complexity_info(model, data_config['input_size'], as_strings=False, print_per_layer_stat=True, verbose=True)\n if args.params:\n _logger.info('Params ({:}) Macs ({:})'.format(params, macs))\n return\n for batch_idx, (input, target) in enumerate(loader):\n if args.no_prefetcher:\n target = target.cuda()\n input = input.cuda()\n if args.channels_last:\n input = input.contiguous(memory_format=torch.channels_last)\n\n # compute output\n with amp_autocast():\n output = model(input)\n\n if valid_labels is not None:\n output = output[:, valid_labels]\n loss = criterion(output, target)\n\n if real_labels is not None:\n real_labels.add_result(output)\n\n # measure accuracy and record loss\n acc1, acc5 = accuracy(output.detach(), target, topk=(1, 5))\n losses.update(loss.item(), input.size(0))\n top1.update(acc1.item(), input.size(0))\n top5.update(acc5.item(), input.size(0))\n\n # measure elapsed time\n batch_time.update(time.time() - end)\n end = time.time()\n\n if batch_idx % args.log_freq == 0:\n _logger.info(\n 'Test: [{0:>4d}/{1}] '\n 'Time: {batch_time.val:.3f}s ({batch_time.avg:.3f}s, {rate_avg:>7.2f}/s) '\n 'Loss: {loss.val:>7.4f} ({loss.avg:>6.4f}) '\n 'Acc@1: {top1.val:>7.3f} ({top1.avg:>7.3f}) '\n 'Acc@5: {top5.val:>7.3f} ({top5.avg:>7.3f})'.format(\n batch_idx, len(loader), batch_time=batch_time,\n rate_avg=input.size(0) / batch_time.avg,\n loss=losses, top1=top1, top5=top5))\n \n #macs, params = get_model_complexity_info(model, (3,224,224), as_strings=False, print_per_layer_stat=True, verbose=True)\n\n if real_labels is not None:\n # real labels mode replaces topk values at the end\n top1a, top5a = real_labels.get_accuracy(k=1), real_labels.get_accuracy(k=5)\n else:\n top1a, top5a = top1.avg, top5.avg\n results = OrderedDict(\n top1=round(top1a, 4), top1_err=round(100 - top1a, 4),\n top5=round(top5a, 4), top5_err=round(100 - top5a, 4),\n param_count=round(param_count / 1e6, 2),\n img_size=data_config['input_size'][-1],\n cropt_pct=crop_pct,\n interpolation=data_config['interpolation'])\n #pdb.set_trace()\n _logger.info(' * Acc@1 {:.3f} ({:.3f}) Acc@5 {:.3f} ({:.3f}) Params ({:}) Macs ({:})'.format(results['top1'], results['top1_err'], results['top5'], results['top5_err'], params, macs))\n\n return results\n\n\ndef main():\n setup_default_logging()\n args = parser.parse_args()\n model_cfgs = []\n model_names = []\n if os.path.isdir(args.checkpoint):\n # validate all checkpoints in a path with same model\n checkpoints = glob.glob(args.checkpoint + '/*.pth.tar')\n checkpoints += glob.glob(args.checkpoint + '/*.pth')\n model_names = list_models(args.model)\n model_cfgs = [(args.model, c) for c in sorted(checkpoints, key=natural_key)]\n else:\n if args.model == 'all':\n # validate all models in a list of names with pretrained checkpoints\n args.pretrained = True\n model_names = list_models(pretrained=True, exclude_filters=['*_in21k', '*_in22k'])\n model_cfgs = [(n, '') for n in model_names]\n elif not is_model(args.model):\n # model name doesn't exist, try as wildcard filter\n model_names = list_models(args.model)\n model_cfgs = [(n, '') for n in model_names]\n\n if len(model_cfgs):\n results_file = args.results_file or './results-all.csv'\n _logger.info('Running bulk validation on these pretrained models: {}'.format(', '.join(model_names)))\n results = []\n try:\n start_batch_size = args.batch_size\n for m, c in model_cfgs:\n batch_size = start_batch_size\n args.model = m\n args.checkpoint = c\n result = OrderedDict(model=args.model)\n r = {}\n while not r and batch_size >= args.num_gpu:\n torch.cuda.empty_cache()\n try:\n args.batch_size = batch_size\n print('Validating with batch size: %d' % args.batch_size)\n r = validate(args)\n except RuntimeError as e:\n if batch_size <= args.num_gpu:\n print(\"Validation failed with no ability to reduce batch size. Exiting.\")\n raise e\n batch_size = max(batch_size // 2, args.num_gpu)\n print(\"Validation failed, reducing batch size by 50%\")\n result.update(r)\n if args.checkpoint:\n result['checkpoint'] = args.checkpoint\n results.append(result)\n except KeyboardInterrupt as e:\n pass\n results = sorted(results, key=lambda x: x['top1'], reverse=True)\n if len(results):\n write_results(results_file, results)\n else:\n validate(args)\n\n\ndef write_results(results_file, results):\n with open(results_file, mode='w') as cf:\n dw = csv.DictWriter(cf, fieldnames=results[0].keys())\n dw.writeheader()\n for r in results:\n dw.writerow(r)\n cf.flush()\n\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "torch.cuda.empty_cache", "torch.jit.script", "torch.no_grad", "torch.nn.CrossEntropyLoss", "torch.jit.optimized_execution" ] ]
mcnoat/pymc3
[ "8b1f64cce32db3357301b88bbe9f7108733ac70a" ]
[ "pymc3/step_methods/metropolis.py" ]
[ "# Copyright 2020 The PyMC Developers\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport numpy as np\nimport numpy.random as nr\nimport scipy.linalg\nimport theano\n\nimport pymc3 as pm\n\nfrom pymc3.distributions import draw_values\nfrom pymc3.step_methods.arraystep import (\n ArrayStep,\n ArrayStepShared,\n Competence,\n PopulationArrayStepShared,\n metrop_select,\n)\nfrom pymc3.theanof import floatX\n\n__all__ = [\n \"Metropolis\",\n \"DEMetropolis\",\n \"DEMetropolisZ\",\n \"BinaryMetropolis\",\n \"BinaryGibbsMetropolis\",\n \"CategoricalGibbsMetropolis\",\n \"NormalProposal\",\n \"CauchyProposal\",\n \"LaplaceProposal\",\n \"PoissonProposal\",\n \"MultivariateNormalProposal\",\n]\n\n# Available proposal distributions for Metropolis\n\n\nclass Proposal:\n def __init__(self, s):\n self.s = s\n\n\nclass NormalProposal(Proposal):\n def __call__(self):\n return nr.normal(scale=self.s)\n\n\nclass UniformProposal(Proposal):\n def __call__(self):\n return nr.uniform(low=-self.s, high=self.s, size=len(self.s))\n\n\nclass CauchyProposal(Proposal):\n def __call__(self):\n return nr.standard_cauchy(size=np.size(self.s)) * self.s\n\n\nclass LaplaceProposal(Proposal):\n def __call__(self):\n size = np.size(self.s)\n return (nr.standard_exponential(size=size) - nr.standard_exponential(size=size)) * self.s\n\n\nclass PoissonProposal(Proposal):\n def __call__(self):\n return nr.poisson(lam=self.s, size=np.size(self.s)) - self.s\n\n\nclass MultivariateNormalProposal(Proposal):\n def __init__(self, s):\n n, m = s.shape\n if n != m:\n raise ValueError(\"Covariance matrix is not symmetric.\")\n self.n = n\n self.chol = scipy.linalg.cholesky(s, lower=True)\n\n def __call__(self, num_draws=None):\n if num_draws is not None:\n b = np.random.randn(self.n, num_draws)\n return np.dot(self.chol, b).T\n else:\n b = np.random.randn(self.n)\n return np.dot(self.chol, b)\n\n\nclass Metropolis(ArrayStepShared):\n \"\"\"\n Metropolis-Hastings sampling step\n\n Parameters\n ----------\n vars: list\n List of variables for sampler\n S: standard deviation or covariance matrix\n Some measure of variance to parameterize proposal distribution\n proposal_dist: function\n Function that returns zero-mean deviates when parameterized with\n S (and n). Defaults to normal.\n scaling: scalar or array\n Initial scale factor for proposal. Defaults to 1.\n tune: bool\n Flag for tuning. Defaults to True.\n tune_interval: int\n The frequency of tuning. Defaults to 100 iterations.\n model: PyMC Model\n Optional model for sampling step. Defaults to None (taken from context).\n mode: string or `Mode` instance.\n compilation mode passed to Theano functions\n \"\"\"\n\n name = \"metropolis\"\n\n default_blocked = False\n generates_stats = True\n stats_dtypes = [\n {\n \"accept\": np.float64,\n \"accepted\": np.bool,\n \"tune\": np.bool,\n \"scaling\": np.float64,\n }\n ]\n\n def __init__(\n self,\n vars=None,\n S=None,\n proposal_dist=None,\n scaling=1.0,\n tune=True,\n tune_interval=100,\n model=None,\n mode=None,\n **kwargs\n ):\n\n model = pm.modelcontext(model)\n\n if vars is None:\n vars = model.vars\n vars = pm.inputvars(vars)\n\n if S is None:\n S = np.ones(sum(v.dsize for v in vars))\n\n if proposal_dist is not None:\n self.proposal_dist = proposal_dist(S)\n elif S.ndim == 1:\n self.proposal_dist = NormalProposal(S)\n elif S.ndim == 2:\n self.proposal_dist = MultivariateNormalProposal(S)\n else:\n raise ValueError(\"Invalid rank for variance: %s\" % S.ndim)\n\n self.scaling = np.atleast_1d(scaling).astype(\"d\")\n self.tune = tune\n self.tune_interval = tune_interval\n self.steps_until_tune = tune_interval\n self.accepted = 0\n\n # Determine type of variables\n self.discrete = np.concatenate(\n [[v.dtype in pm.discrete_types] * (v.dsize or 1) for v in vars]\n )\n self.any_discrete = self.discrete.any()\n self.all_discrete = self.discrete.all()\n\n # remember initial settings before tuning so they can be reset\n self._untuned_settings = dict(\n scaling=self.scaling, steps_until_tune=tune_interval, accepted=self.accepted\n )\n\n self.mode = mode\n\n shared = pm.make_shared_replacements(vars, model)\n self.delta_logp = delta_logp(model.logpt, vars, shared)\n super().__init__(vars, shared)\n\n def reset_tuning(self):\n \"\"\"Resets the tuned sampler parameters to their initial values.\"\"\"\n for attr, initial_value in self._untuned_settings.items():\n setattr(self, attr, initial_value)\n return\n\n def astep(self, q0):\n if not self.steps_until_tune and self.tune:\n # Tune scaling parameter\n self.scaling = tune(self.scaling, self.accepted / float(self.tune_interval))\n # Reset counter\n self.steps_until_tune = self.tune_interval\n self.accepted = 0\n\n delta = self.proposal_dist() * self.scaling\n\n if self.any_discrete:\n if self.all_discrete:\n delta = np.round(delta, 0).astype(\"int64\")\n q0 = q0.astype(\"int64\")\n q = (q0 + delta).astype(\"int64\")\n else:\n delta[self.discrete] = np.round(delta[self.discrete], 0)\n q = q0 + delta\n else:\n q = floatX(q0 + delta)\n\n accept = self.delta_logp(q, q0)\n q_new, accepted = metrop_select(accept, q, q0)\n self.accepted += accepted\n\n self.steps_until_tune -= 1\n\n stats = {\n \"tune\": self.tune,\n \"scaling\": self.scaling,\n \"accept\": np.exp(accept),\n \"accepted\": accepted,\n }\n\n return q_new, [stats]\n\n @staticmethod\n def competence(var, has_grad):\n return Competence.COMPATIBLE\n\n\ndef tune(scale, acc_rate):\n \"\"\"\n Tunes the scaling parameter for the proposal distribution\n according to the acceptance rate over the last tune_interval:\n\n Rate Variance adaptation\n ---- -------------------\n <0.001 x 0.1\n <0.05 x 0.5\n <0.2 x 0.9\n >0.5 x 1.1\n >0.75 x 2\n >0.95 x 10\n\n \"\"\"\n if acc_rate < 0.001:\n # reduce by 90 percent\n return scale * 0.1\n elif acc_rate < 0.05:\n # reduce by 50 percent\n return scale * 0.5\n elif acc_rate < 0.2:\n # reduce by ten percent\n return scale * 0.9\n elif acc_rate > 0.95:\n # increase by factor of ten\n return scale * 10.0\n elif acc_rate > 0.75:\n # increase by double\n return scale * 2.0\n elif acc_rate > 0.5:\n # increase by ten percent\n return scale * 1.1\n\n return scale\n\n\nclass BinaryMetropolis(ArrayStep):\n \"\"\"Metropolis-Hastings optimized for binary variables\n\n Parameters\n ----------\n vars: list\n List of variables for sampler\n scaling: scalar or array\n Initial scale factor for proposal. Defaults to 1.\n tune: bool\n Flag for tuning. Defaults to True.\n tune_interval: int\n The frequency of tuning. Defaults to 100 iterations.\n model: PyMC Model\n Optional model for sampling step. Defaults to None (taken from context).\n\n \"\"\"\n\n name = \"binary_metropolis\"\n\n generates_stats = True\n stats_dtypes = [\n {\n \"accept\": np.float64,\n \"tune\": np.bool,\n \"p_jump\": np.float64,\n }\n ]\n\n def __init__(self, vars, scaling=1.0, tune=True, tune_interval=100, model=None):\n\n model = pm.modelcontext(model)\n\n self.scaling = scaling\n self.tune = tune\n self.tune_interval = tune_interval\n self.steps_until_tune = tune_interval\n self.accepted = 0\n\n if not all([v.dtype in pm.discrete_types for v in vars]):\n raise ValueError(\"All variables must be Bernoulli for BinaryMetropolis\")\n\n super().__init__(vars, [model.fastlogp])\n\n def astep(self, q0, logp):\n\n # Convert adaptive_scale_factor to a jump probability\n p_jump = 1.0 - 0.5 ** self.scaling\n\n rand_array = nr.random(q0.shape)\n q = np.copy(q0)\n # Locations where switches occur, according to p_jump\n switch_locs = rand_array < p_jump\n q[switch_locs] = True - q[switch_locs]\n\n accept = logp(q) - logp(q0)\n q_new, accepted = metrop_select(accept, q, q0)\n self.accepted += accepted\n\n stats = {\n \"tune\": self.tune,\n \"accept\": np.exp(accept),\n \"p_jump\": p_jump,\n }\n\n return q_new, [stats]\n\n @staticmethod\n def competence(var):\n \"\"\"\n BinaryMetropolis is only suitable for binary (bool)\n and Categorical variables with k=1.\n \"\"\"\n distribution = getattr(var.distribution, \"parent_dist\", var.distribution)\n if isinstance(distribution, pm.Bernoulli) or (var.dtype in pm.bool_types):\n return Competence.COMPATIBLE\n elif isinstance(distribution, pm.Categorical) and (distribution.k == 2):\n return Competence.COMPATIBLE\n return Competence.INCOMPATIBLE\n\n\nclass BinaryGibbsMetropolis(ArrayStep):\n \"\"\"A Metropolis-within-Gibbs step method optimized for binary variables\n\n Parameters\n ----------\n vars: list\n List of variables for sampler\n order: list or 'random'\n List of integers indicating the Gibbs update order\n e.g., [0, 2, 1, ...]. Default is random\n transit_p: float\n The diagonal of the transition kernel. A value > .5 gives anticorrelated proposals,\n which resulting in more efficient antithetical sampling.\n model: PyMC Model\n Optional model for sampling step. Defaults to None (taken from context).\n\n \"\"\"\n\n name = \"binary_gibbs_metropolis\"\n\n def __init__(self, vars, order=\"random\", transit_p=0.8, model=None):\n\n model = pm.modelcontext(model)\n\n # transition probabilities\n self.transit_p = transit_p\n\n self.dim = sum(v.dsize for v in vars)\n\n if order == \"random\":\n self.shuffle_dims = True\n self.order = list(range(self.dim))\n else:\n if sorted(order) != list(range(self.dim)):\n raise ValueError(\"Argument 'order' has to be a permutation\")\n self.shuffle_dims = False\n self.order = order\n\n if not all([v.dtype in pm.discrete_types for v in vars]):\n raise ValueError(\"All variables must be binary for BinaryGibbsMetropolis\")\n\n super().__init__(vars, [model.fastlogp])\n\n def astep(self, q0, logp):\n order = self.order\n if self.shuffle_dims:\n nr.shuffle(order)\n\n q = np.copy(q0)\n logp_curr = logp(q)\n\n for idx in order:\n # No need to do metropolis update if the same value is proposed,\n # as you will get the same value regardless of accepted or reject\n if nr.rand() < self.transit_p:\n curr_val, q[idx] = q[idx], True - q[idx]\n logp_prop = logp(q)\n q[idx], accepted = metrop_select(logp_prop - logp_curr, q[idx], curr_val)\n if accepted:\n logp_curr = logp_prop\n\n return q\n\n @staticmethod\n def competence(var):\n \"\"\"\n BinaryMetropolis is only suitable for Bernoulli\n and Categorical variables with k=2.\n \"\"\"\n distribution = getattr(var.distribution, \"parent_dist\", var.distribution)\n if isinstance(distribution, pm.Bernoulli) or (var.dtype in pm.bool_types):\n return Competence.IDEAL\n elif isinstance(distribution, pm.Categorical) and (distribution.k == 2):\n return Competence.IDEAL\n return Competence.INCOMPATIBLE\n\n\nclass CategoricalGibbsMetropolis(ArrayStep):\n \"\"\"A Metropolis-within-Gibbs step method optimized for categorical variables.\n This step method works for Bernoulli variables as well, but it is not\n optimized for them, like BinaryGibbsMetropolis is. Step method supports\n two types of proposals: A uniform proposal and a proportional proposal,\n which was introduced by Liu in his 1996 technical report\n \"Metropolized Gibbs Sampler: An Improvement\".\n \"\"\"\n\n name = \"categorical_gibbs_metropolis\"\n\n def __init__(self, vars, proposal=\"uniform\", order=\"random\", model=None):\n\n model = pm.modelcontext(model)\n vars = pm.inputvars(vars)\n\n dimcats = []\n # The above variable is a list of pairs (aggregate dimension, number\n # of categories). For example, if vars = [x, y] with x being a 2-D\n # variable with M categories and y being a 3-D variable with N\n # categories, we will have dimcats = [(0, M), (1, M), (2, N), (3, N), (4, N)].\n for v in vars:\n distr = getattr(v.distribution, \"parent_dist\", v.distribution)\n if isinstance(distr, pm.Categorical):\n k = draw_values([distr.k])[0]\n elif isinstance(distr, pm.Bernoulli) or (v.dtype in pm.bool_types):\n k = 2\n else:\n raise ValueError(\n \"All variables must be categorical or binary\" + \"for CategoricalGibbsMetropolis\"\n )\n start = len(dimcats)\n dimcats += [(dim, k) for dim in range(start, start + v.dsize)]\n\n if order == \"random\":\n self.shuffle_dims = True\n self.dimcats = dimcats\n else:\n if sorted(order) != list(range(len(dimcats))):\n raise ValueError(\"Argument 'order' has to be a permutation\")\n self.shuffle_dims = False\n self.dimcats = [dimcats[j] for j in order]\n\n if proposal == \"uniform\":\n self.astep = self.astep_unif\n elif proposal == \"proportional\":\n # Use the optimized \"Metropolized Gibbs Sampler\" described in Liu96.\n self.astep = self.astep_prop\n else:\n raise ValueError(\"Argument 'proposal' should either be 'uniform' or 'proportional'\")\n\n super().__init__(vars, [model.fastlogp])\n\n def astep_unif(self, q0, logp):\n dimcats = self.dimcats\n if self.shuffle_dims:\n nr.shuffle(dimcats)\n\n q = np.copy(q0)\n logp_curr = logp(q)\n\n for dim, k in dimcats:\n curr_val, q[dim] = q[dim], sample_except(k, q[dim])\n logp_prop = logp(q)\n q[dim], accepted = metrop_select(logp_prop - logp_curr, q[dim], curr_val)\n if accepted:\n logp_curr = logp_prop\n return q\n\n def astep_prop(self, q0, logp):\n dimcats = self.dimcats\n if self.shuffle_dims:\n nr.shuffle(dimcats)\n\n q = np.copy(q0)\n logp_curr = logp(q)\n\n for dim, k in dimcats:\n logp_curr = self.metropolis_proportional(q, logp, logp_curr, dim, k)\n\n return q\n\n def metropolis_proportional(self, q, logp, logp_curr, dim, k):\n given_cat = int(q[dim])\n log_probs = np.zeros(k)\n log_probs[given_cat] = logp_curr\n candidates = list(range(k))\n for candidate_cat in candidates:\n if candidate_cat != given_cat:\n q[dim] = candidate_cat\n log_probs[candidate_cat] = logp(q)\n probs = softmax(log_probs)\n prob_curr, probs[given_cat] = probs[given_cat], 0.0\n probs /= 1.0 - prob_curr\n proposed_cat = nr.choice(candidates, p=probs)\n accept_ratio = (1.0 - prob_curr) / (1.0 - probs[proposed_cat])\n if not np.isfinite(accept_ratio) or nr.uniform() >= accept_ratio:\n q[dim] = given_cat\n return logp_curr\n q[dim] = proposed_cat\n return log_probs[proposed_cat]\n\n @staticmethod\n def competence(var):\n \"\"\"\n CategoricalGibbsMetropolis is only suitable for Bernoulli and\n Categorical variables.\n \"\"\"\n distribution = getattr(var.distribution, \"parent_dist\", var.distribution)\n if isinstance(distribution, pm.Categorical):\n if distribution.k > 2:\n return Competence.IDEAL\n return Competence.COMPATIBLE\n elif isinstance(distribution, pm.Bernoulli) or (var.dtype in pm.bool_types):\n return Competence.COMPATIBLE\n return Competence.INCOMPATIBLE\n\n\nclass DEMetropolis(PopulationArrayStepShared):\n \"\"\"\n Differential Evolution Metropolis sampling step.\n\n Parameters\n ----------\n lamb: float\n Lambda parameter of the DE proposal mechanism. Defaults to 2.38 / sqrt(2 * ndim)\n vars: list\n List of variables for sampler\n S: standard deviation or covariance matrix\n Some measure of variance to parameterize proposal distribution\n proposal_dist: function\n Function that returns zero-mean deviates when parameterized with\n S (and n). Defaults to Uniform(-S,+S).\n scaling: scalar or array\n Initial scale factor for epsilon. Defaults to 0.001\n tune: str\n Which hyperparameter to tune. Defaults to None, but can also be 'scaling' or 'lambda'.\n tune_interval: int\n The frequency of tuning. Defaults to 100 iterations.\n model: PyMC Model\n Optional model for sampling step. Defaults to None (taken from context).\n mode: string or `Mode` instance.\n compilation mode passed to Theano functions\n\n References\n ----------\n .. [Braak2006] Cajo C.F. ter Braak (2006).\n A Markov Chain Monte Carlo version of the genetic algorithm\n Differential Evolution: easy Bayesian computing for real parameter spaces.\n Statistics and Computing\n `link <https://doi.org/10.1007/s11222-006-8769-1>`__\n \"\"\"\n\n name = \"DEMetropolis\"\n\n default_blocked = True\n generates_stats = True\n stats_dtypes = [\n {\n \"accept\": np.float64,\n \"accepted\": np.bool,\n \"tune\": np.bool,\n \"scaling\": np.float64,\n \"lambda\": np.float64,\n }\n ]\n\n def __init__(\n self,\n vars=None,\n S=None,\n proposal_dist=None,\n lamb=None,\n scaling=0.001,\n tune=None,\n tune_interval=100,\n model=None,\n mode=None,\n **kwargs\n ):\n\n model = pm.modelcontext(model)\n\n if vars is None:\n vars = model.cont_vars\n vars = pm.inputvars(vars)\n\n if S is None:\n S = np.ones(model.ndim)\n\n if proposal_dist is not None:\n self.proposal_dist = proposal_dist(S)\n else:\n self.proposal_dist = UniformProposal(S)\n\n self.scaling = np.atleast_1d(scaling).astype(\"d\")\n if lamb is None:\n # default to the optimal lambda for normally distributed targets\n lamb = 2.38 / np.sqrt(2 * model.ndim)\n self.lamb = float(lamb)\n if tune not in {None, \"scaling\", \"lambda\"}:\n raise ValueError('The parameter \"tune\" must be one of {None, scaling, lambda}')\n self.tune = tune\n self.tune_interval = tune_interval\n self.steps_until_tune = tune_interval\n self.accepted = 0\n\n self.mode = mode\n\n shared = pm.make_shared_replacements(vars, model)\n self.delta_logp = delta_logp(model.logpt, vars, shared)\n super().__init__(vars, shared)\n\n def astep(self, q0):\n if not self.steps_until_tune and self.tune:\n if self.tune == \"scaling\":\n self.scaling = tune(self.scaling, self.accepted / float(self.tune_interval))\n elif self.tune == \"lambda\":\n self.lamb = tune(self.lamb, self.accepted / float(self.tune_interval))\n # Reset counter\n self.steps_until_tune = self.tune_interval\n self.accepted = 0\n\n epsilon = self.proposal_dist() * self.scaling\n\n # differential evolution proposal\n # select two other chains\n ir1, ir2 = np.random.choice(self.other_chains, 2, replace=False)\n r1 = self.bij.map(self.population[ir1])\n r2 = self.bij.map(self.population[ir2])\n # propose a jump\n q = floatX(q0 + self.lamb * (r1 - r2) + epsilon)\n\n accept = self.delta_logp(q, q0)\n q_new, accepted = metrop_select(accept, q, q0)\n self.accepted += accepted\n\n self.steps_until_tune -= 1\n\n stats = {\n \"tune\": self.tune,\n \"scaling\": self.scaling,\n \"lambda\": self.lamb,\n \"accept\": np.exp(accept),\n \"accepted\": accepted,\n }\n\n return q_new, [stats]\n\n @staticmethod\n def competence(var, has_grad):\n if var.dtype in pm.discrete_types:\n return Competence.INCOMPATIBLE\n return Competence.COMPATIBLE\n\n\nclass DEMetropolisZ(ArrayStepShared):\n \"\"\"\n Adaptive Differential Evolution Metropolis sampling step that uses the past to inform jumps.\n\n Parameters\n ----------\n lamb: float\n Lambda parameter of the DE proposal mechanism. Defaults to 2.38 / sqrt(2 * ndim)\n vars: list\n List of variables for sampler\n S: standard deviation or covariance matrix\n Some measure of variance to parameterize proposal distribution\n proposal_dist: function\n Function that returns zero-mean deviates when parameterized with\n S (and n). Defaults to Uniform(-S,+S).\n scaling: scalar or array\n Initial scale factor for epsilon. Defaults to 0.001\n tune: str\n Which hyperparameter to tune. Defaults to 'lambda', but can also be 'scaling' or None.\n tune_interval: int\n The frequency of tuning. Defaults to 100 iterations.\n tune_drop_fraction: float\n Fraction of tuning steps that will be removed from the samplers history when the tuning ends.\n Defaults to 0.9 - keeping the last 10% of tuning steps for good mixing while removing 90% of\n potentially unconverged tuning positions.\n model: PyMC Model\n Optional model for sampling step. Defaults to None (taken from context).\n mode: string or `Mode` instance.\n compilation mode passed to Theano functions\n\n References\n ----------\n .. [Braak2006] Cajo C.F. ter Braak (2006).\n Differential Evolution Markov Chain with snooker updater and fewer chains.\n Statistics and Computing\n `link <https://doi.org/10.1007/s11222-008-9104-9>`__\n \"\"\"\n\n name = \"DEMetropolisZ\"\n\n default_blocked = True\n generates_stats = True\n stats_dtypes = [\n {\n \"accept\": np.float64,\n \"accepted\": np.bool,\n \"tune\": np.bool,\n \"scaling\": np.float64,\n \"lambda\": np.float64,\n }\n ]\n\n def __init__(\n self,\n vars=None,\n S=None,\n proposal_dist=None,\n lamb=None,\n scaling=0.001,\n tune=\"lambda\",\n tune_interval=100,\n tune_drop_fraction: float = 0.9,\n model=None,\n mode=None,\n **kwargs\n ):\n model = pm.modelcontext(model)\n\n if vars is None:\n vars = model.cont_vars\n vars = pm.inputvars(vars)\n\n if S is None:\n S = np.ones(model.ndim)\n\n if proposal_dist is not None:\n self.proposal_dist = proposal_dist(S)\n else:\n self.proposal_dist = UniformProposal(S)\n\n self.scaling = np.atleast_1d(scaling).astype(\"d\")\n if lamb is None:\n # default to the optimal lambda for normally distributed targets\n lamb = 2.38 / np.sqrt(2 * model.ndim)\n self.lamb = float(lamb)\n if tune not in {None, \"scaling\", \"lambda\"}:\n raise ValueError('The parameter \"tune\" must be one of {None, scaling, lambda}')\n self.tune = True\n self.tune_target = tune\n self.tune_interval = tune_interval\n self.tune_drop_fraction = tune_drop_fraction\n self.steps_until_tune = tune_interval\n self.accepted = 0\n\n # cache local history for the Z-proposals\n self._history = []\n # remember initial settings before tuning so they can be reset\n self._untuned_settings = dict(\n scaling=self.scaling,\n lamb=self.lamb,\n steps_until_tune=tune_interval,\n accepted=self.accepted,\n )\n\n self.mode = mode\n\n shared = pm.make_shared_replacements(vars, model)\n self.delta_logp = delta_logp(model.logpt, vars, shared)\n super().__init__(vars, shared)\n\n def reset_tuning(self):\n \"\"\"Resets the tuned sampler parameters and history to their initial values.\"\"\"\n # history can't be reset via the _untuned_settings dict because it's a list\n self._history = []\n for attr, initial_value in self._untuned_settings.items():\n setattr(self, attr, initial_value)\n return\n\n def astep(self, q0):\n # same tuning scheme as DEMetropolis\n if not self.steps_until_tune and self.tune:\n if self.tune_target == \"scaling\":\n self.scaling = tune(self.scaling, self.accepted / float(self.tune_interval))\n elif self.tune_target == \"lambda\":\n self.lamb = tune(self.lamb, self.accepted / float(self.tune_interval))\n # Reset counter\n self.steps_until_tune = self.tune_interval\n self.accepted = 0\n\n epsilon = self.proposal_dist() * self.scaling\n\n it = len(self._history)\n # use the DE-MCMC-Z proposal scheme as soon as the history has 2 entries\n if it > 1:\n # differential evolution proposal\n # select two other chains\n iz1 = np.random.randint(it)\n iz2 = np.random.randint(it)\n while iz2 == iz1:\n iz2 = np.random.randint(it)\n\n z1 = self._history[iz1]\n z2 = self._history[iz2]\n # propose a jump\n q = floatX(q0 + self.lamb * (z1 - z2) + epsilon)\n else:\n # propose just with noise in the first 2 iterations\n q = floatX(q0 + epsilon)\n\n accept = self.delta_logp(q, q0)\n q_new, accepted = metrop_select(accept, q, q0)\n self.accepted += accepted\n self._history.append(q_new)\n\n self.steps_until_tune -= 1\n\n stats = {\n \"tune\": self.tune,\n \"scaling\": self.scaling,\n \"lambda\": self.lamb,\n \"accept\": np.exp(accept),\n \"accepted\": accepted,\n }\n\n return q_new, [stats]\n\n def stop_tuning(self):\n \"\"\"At the end of the tuning phase, this method removes the first x% of the history\n so future proposals are not informed by unconverged tuning iterations.\n \"\"\"\n it = len(self._history)\n n_drop = int(self.tune_drop_fraction * it)\n self._history = self._history[n_drop:]\n return super().stop_tuning()\n\n @staticmethod\n def competence(var, has_grad):\n if var.dtype in pm.discrete_types:\n return Competence.INCOMPATIBLE\n return Competence.COMPATIBLE\n\n\ndef sample_except(limit, excluded):\n candidate = nr.choice(limit - 1)\n if candidate >= excluded:\n candidate += 1\n return candidate\n\n\ndef softmax(x):\n e_x = np.exp(x - np.max(x))\n return e_x / np.sum(e_x, axis=0)\n\n\ndef delta_logp(logp, vars, shared):\n [logp0], inarray0 = pm.join_nonshared_inputs([logp], vars, shared)\n\n tensor_type = inarray0.type\n inarray1 = tensor_type(\"inarray1\")\n\n logp1 = pm.CallableTensor(logp0)(inarray1)\n\n f = theano.function([inarray1, inarray0], logp1 - logp0)\n f.trust_input = True\n return f\n" ]
[ [ "numpy.sum", "numpy.ones", "numpy.copy", "numpy.size", "numpy.isfinite", "numpy.concatenate", "numpy.random.choice", "numpy.random.rand", "numpy.random.standard_exponential", "numpy.random.uniform", "numpy.sqrt", "numpy.zeros", "numpy.random.normal", "numpy.max", "numpy.random.shuffle", "numpy.random.randn", "numpy.exp", "numpy.atleast_1d", "numpy.random.random", "numpy.round", "numpy.dot", "numpy.random.randint" ] ]
wodxyj/plpp
[ "cd74916536cf180a37b088ec61ea2a12a63719f2" ]
[ "src/main.py" ]
[ "import os\nimport shutil\nimport time\n\nimport configargparse\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.nn.parallel\nimport torch.optim as optim\nimport torch.utils.data\nfrom tensorboardX import SummaryWriter\nfrom torch.optim.lr_scheduler import MultiStepLR\nfrom tqdm import tqdm\n\nimport disp_models\nimport logger\nimport models\nimport utils_func\nfrom dataloader import KITTILoader3D\nfrom dataloader import KITTILoader_dataset3d\nfrom dataloader import SceneFlowLoader\nfrom dataloader import listflowfile\n\nparser = configargparse.ArgParser(description='PSMNet')\nparser.add('-c', '--config', required=True,\n is_config_file=True, help='config file')\n\nparser.add_argument('--save_path', type=str, default='',\n help='path to save the log, tensorbaord and checkpoint')\n# network\nparser.add_argument('--data_type', default='depth', choices=['disparity', 'depth'],\n help='the network can predict either disparity or depth')\nparser.add_argument('--arch', default='SDNet', choices=['SDNet', 'PSMNet'],\n help='Model Name, default: SDNet.')\nparser.add_argument('--maxdisp', type=int, default=192,\n help='maxium disparity, the range of the disparity cost volume: [0, maxdisp-1]')\nparser.add_argument('--down', type=float, default=2,\n help='reduce x times resolution when build the depth cost volume')\nparser.add_argument('--maxdepth', type=int, default=80,\n help='the range of the depth cost volume: [1, maxdepth]')\n# dataset\nparser.add_argument('--kitti2015', action='store_true',\n help='If false, use 3d kitti dataset. If true, use kitti stereo 2015, default: False')\nparser.add_argument('--dataset', default='kitti', choices=['sceneflow', 'kitti'],\n help='train with sceneflow or kitti')\nparser.add_argument('--datapath', default='',\n help='root folder of the dataset')\nparser.add_argument('--split_train', default='Kitti/object/train.txt',\n help='data splitting file for training')\nparser.add_argument('--split_val', default='Kitti/object/subval.txt',\n help='data splitting file for validation')\nparser.add_argument('--epochs', type=int, default=300,\n help='number of training epochs')\nparser.add_argument('--btrain', type=int, default=3,\n help='training batch size')\nparser.add_argument('--bval', type=int, default=1,\n help='validation batch size')\nparser.add_argument('--workers', type=int, default=8,\n help='number of dataset workers')\n# learning rate\nparser.add_argument('--lr', type=float, default=0.001,\n help='learning rate')\nparser.add_argument('--lr_stepsize', nargs='+', type=int, default=[200],\n help='drop lr in each step')\nparser.add_argument('--lr_gamma', default=0.1, type=float,\n help='gamma of the learning rate scheduler')\n# resume\nparser.add_argument('--resume', default=None,\n help='path to a checkpoint')\nparser.add_argument('--pretrain', default=None,\n help='path to pretrained model')\nparser.add_argument('--start_epoch', type=int, default=0,\n help='start epoch')\n# evaluate\nparser.add_argument('--evaluate', action='store_true',\n help='do evaluation')\nparser.add_argument('--calib_value', type=float, default=1017,\n help='manually define focal length. (sceneflow does not have configuration)')\nparser.add_argument('--dynamic_bs', action='store_true',\n help='If true, dynamically calculate baseline from calibration file. If false, use 0.54')\nparser.add_argument('--eval_interval', type=int, default=50,\n help='evaluate model every n epochs')\nparser.add_argument('--checkpoint_interval', type=int, default=5,\n help='save checkpoint every n epoch.')\nparser.add_argument('--generate_depth_map', action='store_true',\n help='if true, generate depth maps and save the in save_path/depth_maps/{data_tag}/')\nparser.add_argument('--data_list', default=None,\n help='generate depth maps for all the data in this list')\nparser.add_argument('--data_tag', default=None,\n help='the suffix of the depth maps folder')\nargs = parser.parse_args()\nbest_RMSE = 1e10\n\n\ndef main():\n global best_RMSE\n\n # set logger\n log = logger.setup_logger(os.path.join(args.save_path, 'training.log'))\n for key, value in sorted(vars(args).items()):\n log.info(str(key) + ': ' + str(value))\n\n # set tensorboard\n writer = SummaryWriter(args.save_path + '/tensorboardx')\n\n # Data Loader\n if args.generate_depth_map:\n TrainImgLoader = None\n import dataloader.KITTI_submission_loader as KITTI_submission_loader\n TestImgLoader = torch.utils.data.DataLoader(\n KITTI_submission_loader.SubmiteDataset(args.datapath, args.data_list, args.dynamic_bs),\n batch_size=args.bval, shuffle=False, num_workers=args.workers, drop_last=False)\n elif args.dataset == 'kitti':\n train_data, val_data = KITTILoader3D.dataloader(args.datapath, args.split_train, args.split_val,\n kitti2015=args.kitti2015)\n TrainImgLoader = torch.utils.data.DataLoader(\n KITTILoader_dataset3d.myImageFloder(train_data, True, kitti2015=args.kitti2015, dynamic_bs=args.dynamic_bs),\n batch_size=args.btrain, shuffle=True, num_workers=args.workers, drop_last=False, pin_memory=True)\n TestImgLoader = torch.utils.data.DataLoader(\n KITTILoader_dataset3d.myImageFloder(val_data, False, kitti2015=args.kitti2015, dynamic_bs=args.dynamic_bs),\n batch_size=args.bval, shuffle=False, num_workers=args.workers, drop_last=False, pin_memory=True)\n else:\n train_data, val_data = listflowfile.dataloader(args.datapath)\n TrainImgLoader = torch.utils.data.DataLoader(\n SceneFlowLoader.myImageFloder(train_data, True, calib=args.calib_value),\n batch_size=args.btrain, shuffle=True, num_workers=args.workers, drop_last=False)\n TestImgLoader = torch.utils.data.DataLoader(\n SceneFlowLoader.myImageFloder(val_data, False, calib=args.calib_value),\n batch_size=args.bval, shuffle=False, num_workers=args.workers, drop_last=False)\n\n # Load Model\n if args.data_type == 'disparity':\n model = disp_models.__dict__[args.arch](maxdisp=args.maxdisp)\n elif args.data_type == 'depth':\n model = models.__dict__[args.arch](maxdepth=args.maxdepth, maxdisp=args.maxdisp, down=args.down)\n else:\n log.info('Model is not implemented')\n assert False\n\n # Number of parameters\n log.info('Number of model parameters: {}'.format(sum([p.data.nelement() for p in model.parameters()])))\n model = nn.DataParallel(model).cuda()\n torch.backends.cudnn.benchmark = True\n\n # Optimizer\n optimizer = optim.Adam(model.parameters(), lr=args.lr, betas=(0.9, 0.999))\n scheduler = MultiStepLR(optimizer, milestones=args.lr_stepsize, gamma=args.lr_gamma)\n\n if args.pretrain:\n if os.path.isfile(args.pretrain):\n log.info(\"=> loading pretrain '{}'\".format(args.pretrain))\n checkpoint = torch.load(args.pretrain)\n model.load_state_dict(checkpoint['state_dict'])\n else:\n log.info('[Attention]: Can not find checkpoint {}'.format(args.pretrain))\n\n if args.resume:\n if os.path.isfile(args.resume):\n log.info(\"=> loading checkpoint '{}'\".format(args.resume))\n checkpoint = torch.load(args.resume)\n model.load_state_dict(checkpoint['state_dict'])\n args.start_epoch = checkpoint['epoch']\n optimizer.load_state_dict(checkpoint['optimizer'])\n best_RMSE = checkpoint['best_RMSE']\n scheduler.load_state_dict(checkpoint['scheduler'])\n log.info(\"=> loaded checkpoint '{}' (epoch {})\"\n .format(args.resume, checkpoint['epoch']))\n else:\n log.info('[Attention]: Can not find checkpoint {}'.format(args.resume))\n\n if args.generate_depth_map:\n os.makedirs(args.save_path + '/depth_maps/' + args.data_tag, exist_ok=True)\n\n tqdm_eval_loader = tqdm(TestImgLoader, total=len(TestImgLoader))\n for batch_idx, (imgL_crop, imgR_crop, calib, H, W, filename) in enumerate(tqdm_eval_loader):\n pred_disp = inference(imgL_crop, imgR_crop, calib, model)\n for idx, name in enumerate(filename):\n np.save(args.save_path + '/depth_maps/' + args.data_tag + '/' + name, pred_disp[idx][-H[idx]:, :W[idx]])\n import sys\n sys.exit()\n\n # evaluation\n if args.evaluate:\n evaluate_metric = utils_func.Metric()\n ## training ##\n for batch_idx, (imgL_crop, imgR_crop, disp_crop_L, calib) in enumerate(TestImgLoader):\n start_time = time.time()\n test(imgL_crop, imgR_crop, disp_crop_L, calib, evaluate_metric, model)\n\n log.info(evaluate_metric.print(batch_idx, 'EVALUATE') + ' Time:{:.3f}'.format(time.time() - start_time))\n import sys\n sys.exit()\n\n for epoch in range(args.start_epoch, args.epochs):\n scheduler.step()\n\n ## training ##\n train_metric = utils_func.Metric()\n tqdm_train_loader = tqdm(TrainImgLoader, total=len(TrainImgLoader))\n for batch_idx, (imgL_crop, imgR_crop, disp_crop_L, calib) in enumerate(tqdm_train_loader):\n # start_time = time.time()\n train(imgL_crop, imgR_crop, disp_crop_L, calib, train_metric, optimizer, model)\n # log.info(train_metric.print(batch_idx, 'TRAIN') + ' Time:{:.3f}'.format(time.time() - start_time))\n log.info(train_metric.print(0, 'TRAIN Epoch' + str(epoch)))\n train_metric.tensorboard(writer, epoch, token='TRAIN')\n # lw.update(train_metric.get_info(), epoch, 'Train')\n\n ## testing ##\n is_best = False\n if (epoch % args.eval_interval) == 0:\n test_metric = utils_func.Metric()\n tqdm_test_loader = tqdm(TestImgLoader, total=len(TestImgLoader))\n for batch_idx, (imgL_crop, imgR_crop, disp_crop_L, calib) in enumerate(tqdm_test_loader):\n # start_time = time.time()\n test(imgL_crop, imgR_crop, disp_crop_L, calib, test_metric, model)\n # log.info(test_metric.print(batch_idx, 'TEST') + ' Time:{:.3f}'.format(time.time() - start_time))\n log.info(test_metric.print(0, 'TEST Epoch' + str(epoch)))\n test_metric.tensorboard(writer, epoch, token='TEST')\n\n # SAVE\n is_best = test_metric.RMSELIs.avg < best_RMSE\n best_RMSE = min(test_metric.RMSELIs.avg, best_RMSE)\n save_checkpoint({\n 'epoch': epoch + 1,\n 'arch': args.arch,\n 'state_dict': model.state_dict(),\n 'best_RMSE': best_RMSE,\n 'scheduler': scheduler.state_dict(),\n 'optimizer': optimizer.state_dict(),\n }, is_best, epoch, folder=args.save_path)\n # lw.done()\n\n\ndef save_checkpoint(state, is_best, epoch, filename='checkpoint.pth.tar', folder='result/default'):\n torch.save(state, folder + '/' + filename)\n if is_best:\n shutil.copyfile(folder + '/' + filename, folder + '/model_best.pth.tar')\n if args.checkpoint_interval > 0 and (epoch + 1) % args.checkpoint_interval == 0:\n shutil.copyfile(folder + '/' + filename, folder + '/checkpoint_{}.pth.tar'.format(epoch + 1))\n\n\ndef train(imgL, imgR, depth, calib, metric_log, optimizer, model):\n model.train()\n calib = calib.float()\n\n imgL, imgR, depth, calib = imgL.cuda(), imgR.cuda(), depth.cuda(), calib.cuda()\n\n # ---------\n mask = (depth >= 1) * (depth <= 80)\n mask.detach_()\n # ----\n\n optimizer.zero_grad()\n\n output1, output2, output3 = model(imgL, imgR, calib)\n output1 = torch.squeeze(output1, 1)\n output2 = torch.squeeze(output2, 1)\n output3 = torch.squeeze(output3, 1)\n if args.data_type == 'disparity':\n output1 = disp2depth(output1, calib)\n output2 = disp2depth(output2, calib)\n output3 = disp2depth(output3, calib)\n loss = 0.5 * F.smooth_l1_loss(output1[mask], depth[mask], size_average=True) + 0.7 * F.smooth_l1_loss(\n output2[mask], depth[mask], size_average=True) + F.smooth_l1_loss(output3[mask], depth[mask],\n size_average=True)\n\n metric_log.calculate(depth, output3, loss=loss.item())\n loss.backward()\n optimizer.step()\n\n\ndef inference(imgL, imgR, calib, model):\n model.eval()\n imgL, imgR, calib = imgL.cuda(), imgR.cuda(), calib.float().cuda()\n\n with torch.no_grad():\n output = model(imgL, imgR, calib)\n if args.data_type == 'disparity':\n output = disp2depth(output, calib)\n pred_disp = output.data.cpu().numpy()\n\n return pred_disp\n\n\ndef test(imgL, imgR, depth, calib, metric_log, model):\n model.eval()\n calib = calib.float()\n imgL, imgR, calib, depth = imgL.cuda(), imgR.cuda(), calib.cuda(), depth.cuda()\n\n mask = (depth >= 1) * (depth <= 80)\n mask.detach_()\n with torch.no_grad():\n output3 = model(imgL, imgR, calib)\n output3 = torch.squeeze(output3, 1)\n\n if args.data_type == 'disparity':\n output3 = disp2depth(output3, calib)\n loss = F.smooth_l1_loss(output3[mask], depth[mask], size_average=True)\n\n metric_log.calculate(depth, output3, loss=loss.item())\n\n torch.cuda.empty_cache()\n return\n\n\ndef disp2depth(disp, calib):\n depth = calib[:, None, None] / disp.clamp(min=1e-8)\n return depth\n\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "torch.cuda.empty_cache", "numpy.save", "torch.load", "torch.save", "torch.no_grad", "torch.nn.functional.smooth_l1_loss", "torch.optim.lr_scheduler.MultiStepLR", "torch.nn.DataParallel", "torch.squeeze" ] ]
wangyuan249/Mymmt767
[ "6b9bb566d290bd3157350f6496fcb5df8c2b515c" ]
[ "mmt/models/resnet.py" ]
[ "from __future__ import absolute_import\n\nfrom torch import nn\nfrom torch.nn import functional as F\nfrom torch.nn import init\nimport torchvision\nimport torch\nimport pdb\nfrom .layers import (\n SpatialAttention2d,\n WeightedSum2d)\n\n\n__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',\n 'resnet152']\n\n\nclass ResNet(nn.Module):\n __factory = {\n 18: torchvision.models.resnet18,\n 34: torchvision.models.resnet34,\n 50: torchvision.models.resnet50,\n 101: torchvision.models.resnet101,\n 152: torchvision.models.resnet152,\n }\n\n def __init__(self, depth, pretrained=True, cut_at_pooling=False, is_select=False,\n num_features=0, norm=False, dropout=0, num_classes=0):\n super(ResNet, self).__init__()\n self.pretrained = pretrained\n self.depth = depth\n self.cut_at_pooling = cut_at_pooling\n self.is_select = is_select\n # Construct base (pretrained) resnet\n if depth not in ResNet.__factory:\n raise KeyError(\"Unsupported depth:\", depth)\n resnet = ResNet.__factory[depth](pretrained=pretrained)\n resnet.layer4[0].conv2.stride = (1,1)\n resnet.layer4[0].downsample[0].stride = (1,1)\n self.base = nn.Sequential(\n resnet.conv1, resnet.bn1, resnet.maxpool, # no relu\n resnet.layer1, resnet.layer2, resnet.layer3, resnet.layer4)\n self.gap = nn.AdaptiveAvgPool2d(1)\n\n if not self.cut_at_pooling:\n self.num_features = num_features\n self.norm = norm\n self.dropout = dropout\n self.has_embedding = num_features > 0 # false\n self.num_classes = num_classes\n\n out_planes = resnet.fc.in_features\n\n # Append new layers\n if self.has_embedding: # false\n self.feat = nn.Linear(out_planes, self.num_features)\n self.feat_bn = nn.BatchNorm1d(self.num_features)\n init.kaiming_normal_(self.feat.weight, mode='fan_out')\n init.constant_(self.feat.bias, 0)\n else: # 进入这里\n # Change the num_features to CNN output channels\n self.num_features = out_planes # out_planes = 2048 num_features 重新被赋值 2048\n self.num_features_delg = 512\n self.feat_bn = nn.BatchNorm1d(self.num_features_delg)\n self.feat_bn.bias.requires_grad_(False)\n if self.dropout > 0:\n self.drop = nn.Dropout(self.dropout)\n if self.num_classes > 0:\n self.classifier = nn.Linear(self.num_features_delg, self.num_classes, bias=False)\n init.normal_(self.classifier.weight, std=0.001)\n\n ## wangzy add attention\n self.attention = SpatialAttention2d(in_c=self.num_features, act_fn='relu')\n self.weightSum = WeightedSum2d()\n\n init.constant_(self.feat_bn.weight, 1)\n init.constant_(self.feat_bn.bias, 0)\n\n if not pretrained:\n self.reset_params()\n\n def forward(self, x, feature_withbn=False):\n x = self.base(x) # b x c x H x w C = 2048 即:32 2048 16 8\n # 1*1 conv 512\n original_fea = x\n # x = self.gap(x)\n # x = x.view(x.size(0), -1)\n '''wangzy add attention'''\n\n x, att_score = self.attention(x) # 32 1 16 8 比如说取前64个\n # x torch.Size([32, 512, 16, 8]) att_score torch.Size([32, 1, 16, 8])\n # print(att_score)\n # x = self.weightSum([x,att_score])#回乘att_score分数\n x = self.gap(x) # 32*512*1*1\n # print('------------------------------------------------------------')\n # print(x)\n x = x.view(-1, x.size()[1]) # 32 512\n features = x\n # print(\"features:\",features.shape)\n # pdb.set_trace()\n\n if self.cut_at_pooling: # False\n return features\n if self.has_embedding: # false\n bn_x = self.feat_bn(self.feat(features))\n else: # 进入这里\n bn_x = self.feat_bn(features)\n\n # print(\"training:\", self.training) ### 不确定!\n if self.training is False: ## 分情况 pretrain的时候 应该是 true target finetune 确定是 false\n prob = self.classifier(bn_x)\n bn_x = F.normalize(bn_x)\n return bn_x, prob, original_fea, att_score ### !!!! finetune 的时候从这里 return\n # return bn_x, self.feat_bn(original_fea), att_score ### !!!! finetune 的时候从这里 return\n\n if self.norm: # False\n bn_x = F.normalize(bn_x)\n elif self.has_embedding:\n bn_x = F.relu(bn_x)\n\n if self.dropout > 0: # False\n bn_x = self.drop(bn_x)\n\n if self.num_classes > 0: # True\n prob = self.classifier(bn_x)\n else:\n return x, bn_x\n\n if feature_withbn: # False\n return bn_x, prob\n\n return features, prob, original_fea, att_score\n #att_score (16,1,16,8)\n #original_fea(16,2048,16,8)\n #prob (16,12936)\n #features (16,2048)\n\n\n def reset_params(self):\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n init.kaiming_normal_(m.weight, mode='fan_out')\n if m.bias is not None:\n init.constant_(m.bias, 0)\n elif isinstance(m, nn.BatchNorm2d):\n init.constant_(m.weight, 1)\n init.constant_(m.bias, 0)\n elif isinstance(m, nn.BatchNorm1d):\n init.constant_(m.weight, 1)\n init.constant_(m.bias, 0)\n elif isinstance(m, nn.Linear):\n init.normal_(m.weight, std=0.001)\n if m.bias is not None:\n init.constant_(m.bias, 0)\n\n resnet = ResNet.__factory[self.depth](pretrained=self.pretrained)\n self.base[0].load_state_dict(resnet.conv1.state_dict())\n self.base[1].load_state_dict(resnet.bn1.state_dict())\n self.base[2].load_state_dict(resnet.maxpool.state_dict())\n self.base[3].load_state_dict(resnet.layer1.state_dict())\n self.base[4].load_state_dict(resnet.layer2.state_dict())\n self.base[5].load_state_dict(resnet.layer3.state_dict())\n self.base[6].load_state_dict(resnet.layer4.state_dict())\n\ndef resnet18(**kwargs):\n return ResNet(18, **kwargs)\n\n\ndef resnet34(**kwargs):\n return ResNet(34, **kwargs)\n\n\ndef resnet50(**kwargs):\n return ResNet(50, **kwargs)\n\n\ndef resnet101(**kwargs):\n return ResNet(101, **kwargs)\n\n\ndef resnet152(**kwargs):\n return ResNet(152, **kwargs)\n" ]
[ [ "torch.nn.init.kaiming_normal_", "torch.nn.Linear", "torch.nn.init.constant_", "torch.nn.BatchNorm1d", "torch.nn.functional.normalize", "torch.nn.AdaptiveAvgPool2d", "torch.nn.init.normal_", "torch.nn.functional.relu", "torch.nn.Sequential", "torch.nn.Dropout" ] ]
KyGao/pygame_tracker
[ "c1c4cc4a74c478e6655aa02aa4950d2ab97f6eae" ]
[ "shmup_detect/fhog.py" ]
[ "# -*- coding: utf-8 -*\n\nimport numpy as np \nimport cv2\nfrom numba import njit\nimport time\n\nNUM_SECTOR = 9\nFLT_EPSILON = 1e-07\n\n\n@njit\ndef func1(dx, dy, boundary_x, boundary_y, height, width, numChannels):\n r = np.zeros((height, width), dtype=np.float32)\n alfa = np.zeros((height, width, 2), np.int32)\n\n for j in range(1, height-1):\n for i in range(1, width-1):\n c = 0\n x = dx[j, i, c]\n y = dy[j, i, c]\n r[j, i] = np.sqrt(x*x + y*y)\n\n for ch in range(1, numChannels):\n tx = dx[j, i, ch]\n ty = dy[j, i, ch]\n magnitude = np.sqrt(tx*tx + ty*ty)\n if(magnitude > r[j, i]):\n r[j, i] = magnitude\n c = ch\n x = tx\n y = ty\n\n mmax = boundary_x[0]*x + boundary_y[0]*y\n maxi = 0\n\n for kk in range(0, NUM_SECTOR):\n dotProd = boundary_x[kk]*x + boundary_y[kk]*y\n if(dotProd > mmax):\n mmax = dotProd\n maxi = kk\n elif(-dotProd > mmax):\n mmax = -dotProd\n maxi = kk + NUM_SECTOR\n\n alfa[j, i, 0] = maxi % NUM_SECTOR\n alfa[j, i, 1] = maxi\n return r, alfa\n#梯度计算,参考了https://blog.csdn.net/bisheng250/article/details/53672247\n@njit\ndef func2(dx, dy, boundary_x, boundary_y, r, alfa, nearest, w, k, height, width, sizeX, sizeY, p, stringSize):\n mapp = np.zeros((sizeX*sizeY*p), np.float32)\n for i in range(sizeY):\n for j in range(sizeX):\n for ii in range(k):\n for jj in range(k):\n if((i * k + ii > 0) and (i * k + ii < height - 1) and (j * k + jj > 0) and (j * k + jj < width - 1)):\n mapp[i*stringSize + j*p + alfa[k*i+ii,j*k+jj,0]] += r[k*i+ii,j*k+jj] * w[ii,0] * w[jj,0]\n mapp[i*stringSize + j*p + alfa[k*i+ii,j*k+jj,1] + NUM_SECTOR] += r[k*i+ii,j*k+jj] * w[ii,0] * w[jj,0]\n if((i + nearest[ii] >= 0) and (i + nearest[ii] <= sizeY - 1)):\n mapp[(i+nearest[ii])*stringSize + j*p + alfa[k*i+ii,j*k+jj,0]] += r[k*i+ii,j*k+jj] * w[ii,1] * w[jj,0]\n mapp[(i+nearest[ii])*stringSize + j*p + alfa[k*i+ii,j*k+jj,1] + NUM_SECTOR] += r[k*i+ii,j*k+jj] * w[ii,1] * w[jj,0]\n if((j + nearest[jj] >= 0) and (j + nearest[jj] <= sizeX - 1)):\n mapp[i*stringSize + (j+nearest[jj])*p + alfa[k*i+ii,j*k+jj,0]] += r[k*i+ii,j*k+jj] * w[ii,0] * w[jj,1]\n mapp[i*stringSize + (j+nearest[jj])*p + alfa[k*i+ii,j*k+jj,1] + NUM_SECTOR] += r[k*i+ii,j*k+jj] * w[ii,0] * w[jj,1]\n if((i + nearest[ii] >= 0) and (i + nearest[ii] <= sizeY - 1) and (j + nearest[jj] >= 0) and (j + nearest[jj] <= sizeX - 1)):\n mapp[(i+nearest[ii])*stringSize + (j+nearest[jj])*p + alfa[k*i+ii,j*k+jj,0]] += r[k*i+ii,j*k+jj] * w[ii,1] * w[jj,1]\n mapp[(i+nearest[ii])*stringSize + (j+nearest[jj])*p + alfa[k*i+ii,j*k+jj,1] + NUM_SECTOR] += r[k*i+ii,j*k+jj] * w[ii,1] * w[jj,1]\n return mapp\n\n@njit\n#计算四邻域的归一化\ndef func3(partOfNorm, mappmap, sizeX, sizeY, p, xp, pp):\n\tnewData = np.zeros((sizeY*sizeX*pp), np.float32)\n\tfor i in range(1, sizeY+1):\n\t\tfor j in range(1, sizeX+1):\n\t\t\tpos1 = i * (sizeX+2) * xp + j * xp\n\t\t\tpos2 = (i-1) * sizeX * pp + (j-1) * pp\n\n\t\t\tvalOfNorm = np.sqrt(partOfNorm[(i )*(sizeX + 2) + (j )] +\n \t\t\t\tpartOfNorm[(i )*(sizeX + 2) + (j + 1)] +\n \t\t\t\tpartOfNorm[(i + 1)*(sizeX + 2) + (j )] +\n \t\t\t\tpartOfNorm[(i + 1)*(sizeX + 2) + (j + 1)]) + FLT_EPSILON\n\t\t\tnewData[pos2:pos2+p] = mappmap[pos1:pos1+p] / valOfNorm\n\t\t\tnewData[pos2+4*p:pos2+6*p] = mappmap[pos1+p:pos1+3*p] / valOfNorm\n\n\t\t\tvalOfNorm = np.sqrt(partOfNorm[(i )*(sizeX + 2) + (j )] +\n\t\t\t\t partOfNorm[(i )*(sizeX + 2) + (j + 1)] +\n\t\t\t\t partOfNorm[(i - 1)*(sizeX + 2) + (j )] +\n\t\t\t\t partOfNorm[(i - 1)*(sizeX + 2) + (j + 1)]) + FLT_EPSILON\n\t\t\tnewData[pos2+p:pos2+2*p] = mappmap[pos1:pos1+p] / valOfNorm\n\t\t\tnewData[pos2+6*p:pos2+8*p] = mappmap[pos1+p:pos1+3*p] / valOfNorm\n\n\t\t\tvalOfNorm = np.sqrt(partOfNorm[(i )*(sizeX + 2) + (j )] +\n\t\t\t\t partOfNorm[(i )*(sizeX + 2) + (j - 1)] +\n\t\t\t\t partOfNorm[(i + 1)*(sizeX + 2) + (j )] +\n\t\t\t\t partOfNorm[(i + 1)*(sizeX + 2) + (j - 1)]) + FLT_EPSILON\n\t\t\tnewData[pos2+2*p:pos2+3*p] = mappmap[pos1:pos1+p] / valOfNorm\n\t\t\tnewData[pos2+8*p:pos2+10*p] = mappmap[pos1+p:pos1+3*p] / valOfNorm\n\n\t\t\tvalOfNorm = np.sqrt(partOfNorm[(i )*(sizeX + 2) + (j )] +\n\t\t\t\t partOfNorm[(i )*(sizeX + 2) + (j - 1)] +\n\t\t\t\t partOfNorm[(i - 1)*(sizeX + 2) + (j )] +\n\t\t\t\t partOfNorm[(i - 1)*(sizeX + 2) + (j - 1)]) + FLT_EPSILON\n\t\t\tnewData[pos2+3*p:pos2+4*p] = mappmap[pos1:pos1+p] / valOfNorm\n\t\t\tnewData[pos2+10*p:pos2+12*p] = mappmap[pos1+p:pos1+3*p] / valOfNorm\n\treturn newData\n\n@njit\ndef func4(mappmap, p, sizeX, sizeY, pp, yp, xp, nx, ny):\n\tnewData = np.zeros((sizeX*sizeY*pp), np.float32)\n\tfor i in range(sizeY):\n\t\tfor j in range(sizeX):\n\t\t\tpos1 = (i*sizeX + j) * p\n\t\t\tpos2 = (i*sizeX + j) * pp\n\n\t\t\tfor jj in range(2 * xp): # 2*9的有符号梯度\n\t\t\t\tnewData[pos2 + jj] = np.sum(mappmap[pos1 + yp*xp + jj : pos1 + 3*yp*xp + jj : 2*xp]) * ny\n\t\t\tfor jj in range(xp): # 9无符号\n\t\t\t\tnewData[pos2 + 2*xp + jj] = np.sum(mappmap[pos1 + jj : pos1 + jj + yp*xp : xp]) * ny\n\t\t\tfor ii in range(yp): # 4无符号\n\t\t\t\tnewData[pos2 + 3*xp + ii] = np.sum(mappmap[pos1 + yp*xp + ii*xp*2 : pos1 + yp*xp + ii*xp*2 + 2*xp]) * nx\n\treturn newData\n\n\n\ndef getFeatureMaps(image, k, mapp):#k为cell大小,返回map为特征\n\tkernel = np.array([[-1., 0., 1.]], np.float32)\n\n\theight = image.shape[0]\n\twidth = image.shape[1]\n\t#要求为3通道\n\tassert(image.ndim==3 and image.shape[2])\n\tnumChannels = 3\n\n\tsizeX = width // k\n\tsizeY = height // k\n\tpx = 3 * NUM_SECTOR\n\tp = px\n\tstringSize = sizeX * p\n\n\tmapp['sizeX'] = sizeX\n\tmapp['sizeY'] = sizeY\n\tmapp['numFeatures'] = p\n\tmapp['map'] = np.zeros((mapp['sizeX']*mapp['sizeY']*mapp['numFeatures']), np.float32)\n\t#两个方向梯度\n\tdx = cv2.filter2D(np.float32(image), -1, kernel)\n\tdy = cv2.filter2D(np.float32(image), -1, kernel.T)\n #初始化cos和sin函数\n\targ_vector = np.arange(NUM_SECTOR+1).astype(np.float32) * np.pi / NUM_SECTOR\n\tboundary_x = np.cos(arg_vector) \n\tboundary_y = np.sin(arg_vector)\n\n\t\n\t#计算像素梯度的大小和方向\n\tstime=time.time()\n\tr, alfa = func1(dx, dy, boundary_x, boundary_y, height, width, numChannels) #with @jit\n\tdtime=time.time()-stime\n\t# print('func1:{}s'.format(dtime))\n\tnearest = np.ones((k), np.int)\n\tnearest[0:k//2] = -1\n\n\tw = np.zeros((k, 2), np.float32)\n\ta_x = np.concatenate((k/2 - np.arange(k/2) - 0.5, np.arange(k/2,k) - k/2 + 0.5)).astype(np.float32)\n\tb_x = np.concatenate((k/2 + np.arange(k/2) + 0.5, -np.arange(k/2,k) + k/2 - 0.5 + k)).astype(np.float32)\n\tw[:, 0] = 1.0 / a_x * ((a_x*b_x) / (a_x+b_x))\n\tw[:, 1] = 1.0 / b_x * ((a_x*b_x) / (a_x+b_x))\n #梯度计算准备\n\tmapp['map'] = func2(dx, dy, boundary_x, boundary_y, r, alfa, nearest, w, k, height, width, sizeX, sizeY, p, stringSize) #with @jit\n\n\treturn mapp\n\n#归一化截断\ndef normalizeAndTruncate(mapp, alfa):\n\tsizeX = mapp['sizeX']\n\tsizeY = mapp['sizeY']\n\n\tp = NUM_SECTOR\n\txp = NUM_SECTOR * 3\n\tpp = NUM_SECTOR * 12\n\n\t'''\n\t### \n\tpartOfNorm = np.zeros((sizeY*sizeX), np.float32)\n\n\tfor i in range(sizeX*sizeY):\n\t\tpos = i * mapp['numFeatures']\n\t\tpartOfNorm[i] = np.sum(mapp['map'][pos:pos+p]**2) ###\n\t'''\n\t### \n\tidx = np.arange(0, sizeX*sizeY*mapp['numFeatures'], mapp['numFeatures']).reshape((sizeX*sizeY, 1)) + np.arange(p)\n\tpartOfNorm = np.sum(mapp['map'][idx] ** 2, axis=1) ### \n\n\tsizeX, sizeY = sizeX-2, sizeY-2\n\t\n\n\t\n\t### \n\tnewData = func3(partOfNorm, mapp['map'], sizeX, sizeY, p, xp, pp) \n\t###\n\n\t# \n\tnewData[newData > alfa] = alfa\n\n\tmapp['numFeatures'] = pp\n\tmapp['sizeX'] = sizeX\n\tmapp['sizeY'] = sizeY\n\tmapp['map'] = newData\n\n\treturn mapp\n\n\ndef PCAFeatureMaps(mapp):\n\tsizeX = mapp['sizeX']\n\tsizeY = mapp['sizeY']\n\n\tp = mapp['numFeatures']\n\tpp = NUM_SECTOR * 3 + 4\n\typ = 4\n\txp = NUM_SECTOR\n\n\tnx = 1.0 / np.sqrt(xp*2)\n\tny = 1.0 / np.sqrt(yp)\n\n\tnewData = func4(mapp['map'], p, sizeX, sizeY, pp, yp, xp, nx, ny) \n\t###\n\n\tmapp['numFeatures'] = pp\n\tmapp['map'] = newData\n\n\treturn mapp\n" ]
[ [ "numpy.sqrt", "numpy.ones", "numpy.sum", "numpy.zeros", "numpy.float32", "numpy.cos", "numpy.arange", "numpy.array", "numpy.sin" ] ]
wylloong/TDMOA-USV
[ "3a8690559f6df76f0ed457a89dcec2ec268db34f" ]
[ "COLREGsBasedRiskDomain/RiskSubjection.py" ]
[ "# -*- coding: utf-8 -*-\r\n\r\nimport math\r\nfrom matplotlib import pyplot as plt\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\nimport numpy as np\r\nimport GeoCommonBase as CoordinateBase\r\n\r\n# 危险隶属度函数,障碍物周围隶属度函数随着方向和速度逐渐变小\r\n# 改进:隶属度范围和速度大小有关\r\ndef riskSubjection(boatPnt,currPnt,boatVelo,boatOrien,evaluTime,impactFactor):\r\n #考虑求解半径\r\n evaluDistance=boatVelo*evaluTime\r\n #评估点与船的距离\r\n realDistance=CoordinateBase.Distance(boatPnt,currPnt)\r\n if(realDistance<=evaluDistance):\r\n # 评估点与船只在范围内,返回隶属函数\r\n # currPnt相对于boatPnt的向量\r\n relativeVector = CoordinateBase.Point(currPnt.x - boatPnt.x, currPnt.y - boatPnt.y)\r\n # currPnt与船行驶方向的夹角\r\n interAngle=CoordinateBase.IntersectionAngle(boatOrien,relativeVector) # 返回角度和向量的夹角\r\n # 方向影响量\r\n orienFactor = velocityDirectionFactor(interAngle,impactFactor)\r\n return 1-realDistance/(evaluDistance*orienFactor)\r\n else:\r\n return 0\r\n\r\n# 速度方向影响因子\r\ndef velocityDirectionFactor(interangle,impactFactor):\r\n # 方向影响量\r\n delta = math.cos(CoordinateBase.angle2radian(interangle))\r\n orienFactor = 1 + impactFactor * (1 / (1 + math.e ** (-delta * 3.5))) ** 3.5 * (1 + delta) # Sigmoid函数\r\n return orienFactor\r\n\r\n#求解隶属度函数值,不考虑速度方向\r\ndef subordinateFunctionWithoutOri(basePnt,currPnt,semidiameter):\r\n #考虑求解半径 semidiameter\r\n #判断是否在范围semidiameter内\r\n if(CoordinateBase.Distance(basePnt,currPnt)<=semidiameter):\r\n #在一定范围内,调用隶属函数,currPnt相对于basePnt的向量\r\n return 1-CoordinateBase.Distance(basePnt,currPnt)/semidiameter\r\n else:\r\n return 0\r\n\r\n# 绕点旋转公式\r\ndef RotationWayPnt(rotIni_x,rotIni_y,edit_x,edit_y,rotaAngle):\r\n #点绕点旋转公式,逆时针 旋转原点rotIni,待计算点edit,逆时针旋转角度rotaAngle\r\n Rotaradian=rotaAngle*math.pi/180\r\n newX=(edit_x-rotIni_x)*math.cos(Rotaradian)-(edit_y-rotIni_y)*math.sin(Rotaradian)+rotIni_x\r\n newY=(edit_x-rotIni_x)*math.sin(Rotaradian)+(edit_y-rotIni_y)*math.cos(Rotaradian)+rotIni_y\r\n return CoordinateBase.Point(newX,newY)\r\n\r\nif __name__==\"__main__\":\r\n boatLocation=CoordinateBase.Point(0,0)\r\n currLocation=CoordinateBase.Point(10,10)\r\n boatVelo=10\r\n boatOrien=45\r\n evaluTime=10\r\n impactFactor=0.7\r\n subjection=riskSubjection(boatLocation,currLocation,boatVelo,boatOrien,evaluTime,impactFactor)\r\n print (subjection)\r\n # 绘制等高线\r\n fig = plt.figure(1) # 创建图表1\r\n ax = Axes3D(fig)\r\n X = np.arange(-150, 150, 2)\r\n Y = np.arange(-150, 150, 2)\r\n X, Y = np.meshgrid(X, Y)\r\n zs = np.array([riskSubjection(boatLocation,CoordinateBase.Point(x, y),boatVelo,boatOrien,evaluTime,impactFactor) for x, y in zip(np.ravel(X), np.ravel(Y))])\r\n Z = zs.reshape(X.shape)\r\n surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='hot')\r\n ax.set_xlabel('X')\r\n ax.set_ylabel('Y')\r\n ax.set_zlabel('Z')\r\n\r\n contourfig = plt.figure(2) # 创建图表2,等高线图\r\n coutax = contourfig.add_subplot(1, 1, 1)\r\n #plt.text(15, -13, \"V\", fontsize=15, verticalalignment=\"bottom\", horizontalalignment=\"left\")\r\n plt.contour(X, Y, Z,20)\r\n # coutax.set_xlabel('X Label')\r\n # coutax.set_ylabel('Y Label')\r\n\r\n ratioPlt = plt.figure(3) # 创建图表2,等高线图\r\n ax2 = ratioPlt.add_subplot(3, 3, 3)\r\n x=0\r\n while x<math.pi:\r\n orienFactor = velocityDirectionFactor(x*180/math.pi,impactFactor)\r\n ax2.scatter(x, orienFactor, c='r', marker='.') # 航路\r\n x+=math.pi/100\r\n plt.show()\r\n" ]
[ [ "matplotlib.pyplot.figure", "numpy.arange", "numpy.ravel", "matplotlib.pyplot.contour", "matplotlib.pyplot.show", "numpy.meshgrid" ] ]
nchlis/image_captioning
[ "e1ac6ae9ed9b398417a91563f1cfe316705c8e58" ]
[ "train_model_LSTM.py" ]
[ "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu May 3 19:22:59 2018\n\n@author: nikos\n\"\"\"\n\nimport os\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom scipy.io import loadmat\nfrom skimage.transform import rescale, resize, downscale_local_mean\nfrom lmfit.models import GaussianModel, ConstantModel\nfrom keras.preprocessing import image\n#from keras.applications.imagenet_utils import preprocess_input\nfrom keras.applications.resnet50 import preprocess_input, decode_predictions, ResNet50\n\nfrom keras.models import Model, load_model\nfrom keras.layers import Input, Embedding, Dense, Activation, LSTM, GRU, Dropout\nfrom keras.layers.merge import concatenate\nfrom keras.callbacks import CSVLogger, ModelCheckpoint, EarlyStopping\nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras.utils import to_categorical, plot_model\n\nfrom sklearn.model_selection import train_test_split\nimport random\nimport sys\nimport time\nfrom keras.preprocessing.text import Tokenizer#map words to integers\nfrom keras.backend import clear_session\n#clear_session();print('Cleared Keras session to load new model')\nimport pickle\n\n#%% load the data\nfilenames = np.load('Flickr8k_images_filenames.npy')#8091 filenames\nimages = np.load('Flickr8k_images_encoded.npy')#8091 images\ncaptions = np.load('captions.npy').item()#5 captions per image\nassert np.array_equal(np.sort(filenames),np.sort(np.array(list(captions.keys()))))\n\n#%% Tokenize the captions: map each word/token to an integer\nfilenames_tr = pd.read_csv('./Flickr8k_text/Flickr_8k.trainImages.txt',header=None)\nfilenames_tr = np.array(filenames_tr.values.tolist())#convert to array with dtype='<U25'\ncaptions_per_image=5\n\n#find the training captions to fit the tokenizer on\ncaptions_tr = list()\nfor f in filenames_tr:\n #captions_tr.append(captions[f[0]])\n captions_tr=captions_tr+captions[f[0]]\nassert len(captions_tr) == len(filenames_tr)*captions_per_image\n#max caption length in training data set\nmax_caption_length=max([len(x.split()) for x in captions_tr])\nprint('Maximum caption length:',max_caption_length,'words/tokens.')\n#consider removing '.' from the filters\ntokenizer = Tokenizer(num_words=None,filters='!\"#$%&()*+,-./:;=?@[\\]^_`{|}~',\n lower=False, split=' ', char_level=False)\ntokenizer.fit_on_texts(captions_tr)\nvocab_size = len(tokenizer.word_index.keys())+1\nprint('Vocabulary size after tokenizer:',vocab_size,'unique words.')\n\n#%% set up a generator function to train on one image at a time (conserve RAM)\n\ndef data_generator(input_filenames=None):\n '''\n Generate online training data, one image at a time.\n Note: one image produces several \"datapoints\", since every token of each\n caption is a different output target.\n Yields:\n X_img: (#timesteps,#imagefeatures):image feature input\n X_txt: (#timesteps,#max_caption_length):text input, each word is an integer\n y: (#timesteps,#vocab_size):one-hot encoded output word to predict\n '''\n #filenames_gen = pd.read_csv(input_filepath,header=None)\n #filenames_gen = np.array(filenames_gen.values.tolist())#convert to array with dtype='<U25'\n #print('Generator for:',input_filepath)\n filenames_gen = input_filenames\n print('files total:',len(filenames_gen))\n while True:\n for f in filenames_gen:\n X_img, X_txt, y = list(), list(), list()#new list for every image\n ix = np.where(filenames==f)[0][0]#find the index of the image\n img = images[ix,:]#load the image features using the index\n img_captions = captions[f[0]]#load the captions of the image\n for c in img_captions:\n # encode the sequence\n seq = tokenizer.texts_to_sequences([c])[0]\n # split one sequence into multiple X,y pairs\n for i in range(1, len(seq)):\n # split into input and output pair\n in_seq, out_seq = seq[:i], seq[i]\n # pad input sequence\n in_seq = pad_sequences([in_seq], maxlen=max_caption_length)[0]\n # encode output sequence\n out_seq = to_categorical([out_seq], num_classes=vocab_size)#[0]\n # store\n X_img.append(img)#append the image features\n X_txt.append(in_seq)\n y.append(out_seq)\n yield([[np.array(X_img), np.array(X_txt)], np.array(y)]) \n \n#%% Specify the model\n\nnembedding = 128\nndense = 128\nnlstm = 128\ndropout_rate=0.0\n#dropout_rate=0.25\n# feature extractor model\ninput_img = Input(shape=(2048,))\nx_img = Dropout(dropout_rate)(input_img)\nx_img = Dense(ndense, activation='relu')(x_img)\n\n# sequence model\ninput_txt = Input(shape=(max_caption_length,))\nx_txt = Embedding(vocab_size, nembedding, mask_zero=True)(input_txt)\nx_txt = Dropout(dropout_rate)(x_txt)\nx_txt = LSTM(nlstm)(x_txt)\n\n# decoder model\nx_merge = concatenate([x_img, x_txt])\nx_merge = Dropout(dropout_rate)(x_merge)\nx_merge = Dense(ndense, activation='relu')(x_merge)\n#x_merge = Dropout(dropout_rate)(x_merge)\noutput = Dense(vocab_size, activation='softmax')(x_merge)\n# tie it together [image, seq] [word]\nmodel = Model(inputs=[input_img, input_txt], outputs=output)\nmodel.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n# summarize model\nprint(model.summary())\n\n#%% train the model\n#generator for training data\nfilenames_tr = pd.read_csv('./Flickr8k_text/Flickr_8k.trainImages.txt',header=None)\nfilenames_tr = np.array(filenames_tr.values.tolist())#convert to array with dtype='<U25'\ngen_train = data_generator(input_filenames=filenames_tr)\nsteps_per_epoch_tr = len(filenames_tr)\n#generator for validation data\nfilenames_val = pd.read_csv('./Flickr8k_text/Flickr_8k.devImages.txt',header=None)\nfilenames_val = np.array(filenames_val.values.tolist())#convert to array with dtype='<U25'\ngen_val = data_generator(input_filenames=filenames_val)\nsteps_per_epoch_val = len(filenames_val)\n\nfilepath='./saved_models/model128_LSTM_dropout'+str(dropout_rate) #to save the weights\n#save model architecture as a .png file\nplot_model(model, to_file=filepath+'.png', show_shapes=True)\n#save tokenizer to use on new datasets\nwith open(filepath+'_tokenizer.pkl', 'wb') as handle:\n pickle.dump(tokenizer, handle, protocol=pickle.HIGHEST_PROTOCOL)\n##how to load the tokenizer\n#with open('tokenizer.pkl', 'rb') as handle:\n# tokenizer = pickle.load(handle)\n\ncheckpoint = ModelCheckpoint(filepath+'.hdf5', monitor='val_loss', verbose=1, save_best_only=True, mode='auto')\ncsvlog = CSVLogger(filepath+'_train_log.csv',append=True)\nearly_stopping = EarlyStopping(monitor='val_loss', min_delta=0, patience=5)\n\ntic=time.time()\nmodel.fit_generator(generator=gen_train,steps_per_epoch=steps_per_epoch_tr,\n validation_data=gen_val,validation_steps=steps_per_epoch_val,\n epochs=10, verbose=2,\n initial_epoch=0,callbacks=[checkpoint, csvlog, early_stopping])\ntoc=time.time()\nmodel.save(filepath+'_model.hdf5')\nfile = open(filepath+'_time.txt','w')\nfile.write('training time:'+format(toc-tic, '.2f')+'seconds')\nfile.close()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" ]
[ [ "numpy.load", "pandas.read_csv", "numpy.sort", "numpy.where", "numpy.array" ] ]
cda-group/baloo
[ "f6e05e35b73a75e8a300754c6bdc575e5f2d53b9" ]
[ "tests/core/indexes/test_base.py" ]
[ "import numpy as np\nimport pytest\n\nfrom baloo import Index\n\n\ndef assert_index_equal(actual, expected, sort=False):\n actual = actual.evaluate()\n expected = expected.evaluate()\n\n actual_values = actual.values\n expected_values = expected.values\n if sort:\n actual_values = np.sort(actual_values)\n expected_values = np.sort(expected_values)\n np.testing.assert_array_equal(actual_values, expected_values)\n\n assert actual.dtype.char == expected.dtype.char\n assert actual._length == expected._length\n # might seem redundant but testing the __len__ function\n assert len(actual) == len(expected)\n assert actual.name == expected.name\n\n\nclass TestBaseIndex(object):\n def test_init_list(self):\n data = [1, 2, 3]\n actual = Index(data)\n expected = Index(np.array(data))\n\n assert_index_equal(actual, expected)\n\n def test_evaluate(self, data_i64):\n actual = Index(data_i64)\n expected = Index(data_i64, np.dtype(np.int64), None)\n\n assert_index_equal(actual, expected)\n\n def test_len_raw(self, data_i64):\n ind = Index(data_i64, np.dtype(np.int64))\n\n actual = len(ind)\n expected = 5\n\n assert actual == expected\n\n def test_len_lazy(self, data_i64_lazy):\n ind = Index(data_i64_lazy, np.dtype(np.int64))\n\n actual = len(ind)\n expected = 5\n\n assert actual == expected\n\n def test_comparison(self, index_i64):\n actual = index_i64 < 3\n expected = Index(np.array([True, True, True, False, False]))\n\n assert_index_equal(actual, expected)\n\n def test_filter(self, index_i64):\n actual = index_i64[Index(np.array([False, True, True, False, False]))]\n expected = Index(np.array([1, 2]), np.dtype(np.int64))\n\n assert_index_equal(actual, expected)\n\n def test_slice(self, index_i64):\n actual = index_i64[1:3]\n expected = Index(np.array([1, 2]), np.dtype(np.int64))\n\n assert_index_equal(actual, expected)\n\n def test_head(self, index_i64):\n actual = index_i64.head(2)\n expected = Index(np.array([0, 1]), np.dtype(np.int64))\n\n assert_index_equal(actual, expected)\n\n def test_tail(self, index_i64):\n actual = index_i64.tail(2)\n expected = Index(np.array([3, 4]), np.dtype(np.int64))\n\n assert_index_equal(actual, expected)\n\n # implicitly tests if one can apply operation with Series too\n @pytest.mark.parametrize('operation, expected_data', [\n ('+', np.arange(3, 8, dtype=np.float32)),\n ('-', np.arange(-1, 4, dtype=np.float32)),\n ('*', np.arange(2, 11, 2, dtype=np.float32)),\n ('/', np.array([0.5, 1, 1.5, 2, 2.5], dtype=np.float32)),\n ('**', np.array([1, 4, 9, 16, 25], dtype=np.float32))\n ])\n def test_op_array(self, operation, expected_data, data_f32, op_array_other):\n data = Index(data_f32)\n\n actual = eval('data {} op_array_other'.format(operation))\n expected = Index(expected_data, np.dtype(np.float32))\n\n assert_index_equal(actual, expected)\n\n @pytest.mark.parametrize('operation, expected_data', [\n ('+', np.arange(3, 8, dtype=np.float32)),\n ('-', np.arange(-1, 4, dtype=np.float32)),\n ('*', np.arange(2, 11, 2, dtype=np.float32)),\n ('/', np.array([0.5, 1, 1.5, 2, 2.5], dtype=np.float32)),\n ('**', np.array([1, 4, 9, 16, 25], dtype=np.float32))\n ])\n def test_op_scalar(self, operation, expected_data, data_f32):\n ind = Index(data_f32)\n\n actual = eval('ind {} 2'.format(operation))\n expected = Index(expected_data, np.dtype(np.float32))\n\n assert_index_equal(actual, expected)\n\n def test_isna(self):\n ind = Index([3, 2, -999, 4, -999])\n\n actual = ind.isna()\n expected = Index([False, False, True, False, True], np.dtype(np.bool))\n\n assert_index_equal(actual, expected)\n\n def test_dropna(self):\n ind = Index([3, 2, -999, 4, -999])\n\n actual = ind.dropna()\n expected = Index([3, 2, 4], np.dtype(np.int64))\n\n assert_index_equal(actual, expected)\n\n def test_fillna(self):\n ind = Index([3, 2, -999, 4, -999])\n\n actual = ind.fillna(15)\n expected = Index([3, 2, 15, 4, 15], np.dtype(np.int64))\n\n assert_index_equal(actual, expected)\n" ]
[ [ "numpy.dtype", "numpy.testing.assert_array_equal", "numpy.arange", "numpy.sort", "numpy.array" ] ]
EdgarLefevre/wnet_pytorch
[ "ba8fa5465f72351f349c18fe7df20a60a7c7f3c5" ]
[ "wnet/utils/soft_n_cut_loss.py" ]
[ "# Some methods in this file ported to Pytorch from https://github.com/Ashish77IITM/W-Net/\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom scipy.stats import norm\nfrom torch import Tensor\n\n# The weight matrix w is a measure of the weight between each pixel and\n# every other pixel. so w[u][v] is a measure of\n# (a) Distance between the brightness of the two pixels.\n# (b) Distance in positon between the two pixels\n\n# The NCut loss metric is then:\n# (a) association: sum(weight_connection) * P(both pixels in the connection are in the class)\n# (b) disassociation: sum(weight_connection) * P(first pixel is in the class)\n# N Cut loss = disassociation / association\n\ndef soft_n_cut_loss(inputs, segmentations):\n # We don't do n_cut_loss batch wise -- split it up and do it instance wise\n loss = 0\n for i in range(inputs.shape[0]):\n flatten_image = torch.mean(inputs[i], dim=0)\n flatten_image = flatten_image.reshape(flatten_image.shape[0] ** 2)\n loss += soft_n_cut_loss_(flatten_image, segmentations[i], 2, 512,\n 512) # last 3 = k, size, size -> take from args\n loss /= inputs.shape[0]\n return loss\n\n\ndef soft_n_cut_loss_(flatten_image, prob, k, rows, cols):\n '''\n Inputs:\n prob : (rows*cols*k) tensor\n k : number of classes (integer)\n flatten_image : 1 dim tf array of the row flattened image ( intensity is the average of the three channels)\n rows : number of the rows in the original image\n cols : number of the cols in the original image\n Output :\n soft_n_cut_loss tensor for a single image\n '''\n\n soft_n_cut_loss = k\n weights = edge_weights(flatten_image, rows, cols)\n\n for t in range(k):\n soft_n_cut_loss = soft_n_cut_loss - (numerator(prob[t, :, ], weights) / denominator(prob[t, :, :], weights))\n\n return soft_n_cut_loss\n\n\ndef edge_weights(flatten_image, rows, cols, std_intensity=3, std_position=1, radius=5):\n '''\n Inputs :\n flatten_image : 1 dim tf array of the row flattened image ( intensity is the average of the three channels)\n std_intensity : standard deviation for intensity\n std_position : standard devistion for position\n radius : the length of the around the pixel where the weights\n is non-zero\n rows : rows of the original image (unflattened image)\n cols : cols of the original image (unflattened image)\n Output :\n weights : 2d tf array edge weights in the pixel graph\n Used parameters :\n n : number of pixels\n '''\n ones = torch.ones_like(flatten_image, dtype=torch.float)\n if torch.cuda.is_available():\n ones = ones.cuda()\n\n A = outer_product(flatten_image, ones)\n A_T = torch.t(A)\n d = torch.div((A - A_T), std_intensity)\n intensity_weight = torch.exp(-1 * torch.mul(d, d))\n\n xx, yy = torch.meshgrid(torch.arange(rows, dtype=torch.float), torch.arange(cols, dtype=torch.float))\n xx = xx.reshape(rows * cols)\n yy = yy.reshape(rows * cols)\n if torch.cuda.is_available():\n xx = xx.cuda()\n yy = yy.cuda()\n ones_xx = torch.ones_like(xx, dtype=torch.float)\n ones_yy = torch.ones_like(yy, dtype=torch.float)\n if torch.cuda.is_available():\n ones_yy = ones_yy.cuda()\n ones_xx = ones_xx.cuda()\n A_x = outer_product(xx, ones_xx)\n A_y = outer_product(yy, ones_yy)\n\n xi_xj = A_x - torch.t(A_x)\n yi_yj = A_y - torch.t(A_y)\n\n sq_distance_matrix = torch.mul(xi_xj, xi_xj) + torch.mul(yi_yj, yi_yj)\n\n # Might have to consider casting as float32 instead of creating meshgrid as float32\n\n dist_weight = torch.exp(-torch.div(sq_distance_matrix, std_position ** 2))\n # ele_diff = tf.reshape(ele_diff, (rows, cols))\n # w = ele_diff + distance_matrix\n return torch.mul(intensity_weight, dist_weight)\n\n\ndef outer_product(v1, v2):\n '''\n Inputs:\n v1 : m*1 tf array\n v2 : m*1 tf array\n Output :\n v1 x v2 : m*m array\n '''\n v1 = v1.reshape(-1)\n v2 = v2.reshape(-1)\n v1 = torch.unsqueeze(v1, dim=0)\n v2 = torch.unsqueeze(v2, dim=0)\n return torch.matmul(torch.t(v1), v2)\n\n\ndef numerator(k_class_prob, weights):\n '''\n Inputs :\n k_class_prob : k_class pixelwise probability (rows*cols) tensor\n weights : edge weights n*n tensor\n '''\n k_class_prob = k_class_prob.reshape(-1)\n a = torch.mul(weights, outer_product(k_class_prob, k_class_prob))\n return torch.sum(a)\n\n\ndef denominator(k_class_prob, weights):\n '''\n Inputs:\n k_class_prob : k_class pixelwise probability (rows*cols) tensor\n weights : edge weights\tn*n tensor\n '''\n k_class_prob = k_class_prob.view(-1)\n return torch.sum(\n torch.mul(\n weights,\n outer_product(\n k_class_prob,\n torch.ones_like(k_class_prob)\n )\n )\n )\n\n\ndef gaussian_kernel(radius: int = 3, sigma: float = 4, device='cpu'):\n x_2 = np.linspace(-radius, radius, 2 * radius + 1) ** 2\n dist = np.sqrt(x_2.reshape(-1, 1) + x_2.reshape(1, -1)) / sigma\n kernel = norm.pdf(dist) / norm.pdf(0)\n kernel = torch.from_numpy(kernel.astype(np.float32))\n kernel = kernel.view((1, 1, kernel.shape[0], kernel.shape[1]))\n\n if device == 'cuda':\n kernel = kernel.cuda()\n\n return kernel\n\n\nclass NCutLoss2D(nn.Module):\n r\"\"\"Implementation of the continuous N-Cut loss, as in:\n 'W-Net: A Deep Model for Fully Unsupervised Image Segmentation', by Xia, Kulis (2017)\"\"\"\n\n def __init__(self, radius: int = 4, sigma_1: float = 5, sigma_2: float = 1):\n r\"\"\"\n :param radius: Radius of the spatial interaction term\n :param sigma_1: Standard deviation of the spatial Gaussian interaction\n :param sigma_2: Standard deviation of the pixel value Gaussian interaction\n \"\"\"\n super(NCutLoss2D, self).__init__()\n self.radius = radius\n self.sigma_1 = sigma_1 # Spatial standard deviation\n self.sigma_2 = sigma_2 # Pixel value standard deviation\n\n def forward(self, inputs: Tensor, labels: Tensor) -> Tensor:\n r\"\"\"Computes the continuous N-Cut loss, given a set of class probabilities (labels) and raw images (inputs).\n Small modifications have been made here for efficiency -- specifically, we compute the pixel-wise weights\n relative to the class-wide average, rather than for every individual pixel.\n :param labels: Predicted class probabilities\n :param inputs: Raw images\n :return: Continuous N-Cut loss\n \"\"\"\n num_classes = labels.shape[1]\n kernel = gaussian_kernel(radius=self.radius, sigma=self.sigma_1, device=labels.device.type)\n loss = 0\n\n for k in range(num_classes):\n # Compute the average pixel value for this class, and the difference from each pixel\n class_probs = labels[:, k].unsqueeze(1)\n class_mean = torch.mean(inputs * class_probs, dim=(2, 3), keepdim=True) / \\\n torch.add(torch.mean(class_probs, dim=(2, 3), keepdim=True), 1e-5)\n diff = (inputs - class_mean).pow(2).sum(dim=1).unsqueeze(1)\n\n # Weight the loss by the difference from the class average.\n weights = torch.exp(diff.pow(2).mul(-1 / self.sigma_2 ** 2))\n\n # Compute N-cut loss, using the computed weights matrix, and a Gaussian spatial filter\n numerator = torch.sum(class_probs * F.conv2d(class_probs * weights, kernel, padding=self.radius))\n denominator = torch.sum(class_probs * F.conv2d(weights, kernel, padding=self.radius))\n loss += nn.L1Loss()(numerator / torch.add(denominator, 1e-6), torch.zeros_like(numerator))\n\n return num_classes - loss\n" ]
[ [ "torch.ones_like", "torch.unsqueeze", "torch.sum", "torch.add", "torch.nn.functional.conv2d", "torch.nn.L1Loss", "scipy.stats.norm.pdf", "torch.zeros_like", "torch.t", "torch.div", "torch.mul", "torch.cuda.is_available", "torch.arange", "numpy.linspace", "torch.mean" ] ]
LCOGT/image_align
[ "12ddfb924301039a3cba5007106f6f8ff27f925e" ]
[ "quad.py" ]
[ "import numpy as np\nimport os\nfrom astropy.io import fits\nimport operator\nimport itertools\n\nclass ImgCat:\n \"\"\"\n Represent an individual image and its associated catalog, starlist, quads etc.\n \"\"\"\n\n def __init__(self, filepath, hdu=0, cat=None):\n \"\"\"\n\n :param filepath: Path to the FITS file, or alternatively just a string to identify the image.\n :type filepath: string\n\n :param cat: Catalog generated by SExtractor (if available -- if not, we'll make our own)\n :type cat: asciidata catalog\n\n :param hdu: The hdu containing the science data from which I should build the catalog. 0 is primary. If multihdu, 1 is usually science.\n\n \"\"\"\n self.filepath = filepath\n\n (imgdir, filename) = os.path.split(filepath)\n (common, ext) = os.path.splitext(filename)\n self.name = common\n\n self.hdu = hdu\n self.cat = cat\n self.starlist = []\n self.mindist = 0.0\n self.xlim = (0.0, 0.0) # Will be set using the catalog -- no need for the FITS image.\n self.ylim = (0.0, 0.0)\n\n self.quadlist = []\n self.quadlevel = 0 # encodes what kind of quads have already been computed\n\n def makestarlist(self, skipsaturated=False, n=200):\n if skipsaturated:\n maxflag = 3\n else:\n maxflag = 7\n hdu = fits.open(self.filepath)\n cats = hdu[2].data\n self.starlist = sortstarlistbyflux(cats)[:n]\n (xmin, xmax, ymin, ymax) = area(cats, border=0.01)\n self.xlim = (xmin, xmax)\n self.ylim = (ymin, ymax)\n\n # Given this starlists, what is a good minimal distance for stars in quads ?\n self.mindist = min(min(xmax - xmin, ymax - ymin) / 10.0, 30.0)\n\n def makemorequads(self, verbose=True):\n \"\"\"\n We add more quads, following the quadlevel.\n \"\"\"\n #if not add:\n # self.quadlist = []\n if verbose:\n print(\"Making more quads, from quadlevel %i ...\" % self.quadlevel)\n if self.quadlevel == 0:\n self.quadlist.extend(makequads1(self.starlist, n=7, d=self.mindist, verbose=verbose))\n elif self.quadlevel == 1:\n self.quadlist.extend(makequads2(self.starlist, f=3, n=5, d=self.mindist, verbose=verbose))\n elif self.quadlevel == 2:\n self.quadlist.extend(makequads2(self.starlist, f=6, n=5, d=self.mindist, verbose=verbose))\n elif self.quadlevel == 3:\n self.quadlist.extend(makequads2(self.starlist, f=12, n=5, d=self.mindist, verbose=verbose))\n elif self.quadlevel == 4:\n self.quadlist.extend(makequads2(self.starlist, f=10, n=6, s=3, d=self.mindist, verbose=verbose))\n\n else:\n return False\n\n self.quadlist = removeduplicates(self.quadlist, verbose=verbose)\n self.quadlevel += 1\n return True\n\nclass Quad:\n \"\"\"\n A geometric \"hash\", or asterism, as used in Astrometry.net :\n http://adsabs.harvard.edu/cgi-bin/bib_query?arXiv:0910.2233\n It is made out of 4 stars, and it is shift / scale / rotation invariant\n \"\"\"\n\n def __init__(self, fourstars):\n \"\"\"\n fourstars is a list of four stars\n\n We make the following attributes :\n self.hash\n self.stars (in the order A, B, C, D)\n\n \"\"\"\n assert len(fourstars) == 4\n\n tests = [(0,1), (0,2), (0,3), (1,2), (1,3), (2,3)]\n other = [(2,3), (1,3), (1,2), (0,3), (0,2), (0,1)]\n dists = np.array([np.linalg.norm(np.array(fourstars[0]['x'], fourstars[0]['y']) - np.array(fourstars[1]['x'], fourstars[1]['y'])) for (i,j) in tests])\n assert np.min(dists) > 1.0\n\n maxindex = np.argmax(dists)\n (Ai, Bi) = tests[maxindex] # Indexes of stars A and B\n (Ci, Di) = other[maxindex] # Indexes of stars C and D\n A = fourstars[Ai]\n B = fourstars[Bi]\n C = fourstars[Ci]\n D = fourstars[Di]\n\n # We look for matrix transform [[a -b], [b a]] + [c d] that brings A and B to 00 11 :\n x = B['x'] - A['x']\n y = B['y'] - A['y']\n b = (x-y)/(x*x + y*y)\n a = (1.0/x) * (1.0 + b*y)\n c = b*A['y'] - a*A['x']\n d = - (b*A['x'] + a*A['y'])\n\n t = SimpleTransform((a, b, c, d))\n\n # Test\n #print(t.apply((A['x'], A['y'])))\n #print(t.apply((B.x, B['y'])))\n\n (xC, yC) = t.apply(x = C['x'], y = C['y'])\n (xD, yD) = t.apply(x = D['x'], y = D['y'])\n\n # Normal case\n self.hash = (xC, yC, xD, yD)\n\n # Break symmetries :\n testa = xC > xD\n testb = xC + xD > 1\n\n if testa and not testb: # we switch C and D\n #print(\"a\")\n self.hash = (xD, yD, xC, yC)\n (C, D) = (D, C)\n\n if testb and not testa: # We switch A and B\n #print(\"b\")\n self.hash = (1.0-xD, 1.0-yD, 1.0-xC, 1.0-yC)\n (A, B) = (B, A)\n (C, D) = (D, C)\n\n if testa and testb:\n #print(\"a + b\")\n self.hash = (1.0-xC, 1.0-yC, 1.0-xD, 1.0-yD)\n (A, B) = (B, A)\n\n # Checks :\n assert self.hash[0] <= self.hash[2]\n assert self.hash[0] + self.hash[2] <= 1\n\n self.stars = [A, B, C, D] # Order might be different from the fourstars !\n\n\n def __str__(self):\n return \"Hash : %6.3f %6.3f %6.3f %6.3f / IDs : (%s, %s, %s, %s)\" % (\n self.hash[0], self.hash[1], self.hash[2], self.hash[3],\n self.stars[0].name, self.stars[1].name, self.stars[2].name, self.stars[3].name)\n\nclass SimpleTransform:\n \"\"\"\n Represents an affine transformation consisting of rotation, isotropic scaling, and shift.\n [x', y'] = [[a -b], [b a]] * [x, y] + [c d]\n \"\"\"\n\n def __init__(self, v = (1, 0, 0, 0)):\n \"\"\"\n v = (a, b, c, d)\n \"\"\"\n self.v = np.asarray(v)\n\n def getscaling(self):\n return math.sqrt(self.v[0]*self.v[0] + self.v[1]*self.v[1])\n\n def getrotation(self):\n \"\"\"\n The CCW rotation angle, in degrees\n \"\"\"\n return math.atan2(self.v[1], self.v[0]) * (180.0/math.pi)# % 360.0\n\n def __str__(self):\n return \"Rotation %+11.6f [deg], scale %8.6f\" % (self.getrotation(), self.getscaling())\n\n\n def inverse(self):\n \"\"\"\n Returns the inverse transform !\n \"\"\"\n\n # To represent affine transformations with matrices, we can use homogeneous coordinates.\n homo = np.array([\n [self.v[0], -self.v[1], self.v[2]],\n [self.v[1], self.v[0], self.v[3]],\n [0.0, 0.0, 1.0]\n ])\n\n inv = np.linalg.inv(homo)\n #print(inv)\n\n return SimpleTransform((inv[0,0], inv[1,0], inv[0,2], inv[1,2]))\n\n\n\n def matrixform(self):\n \"\"\"\n Special output for scipy.ndimage.interpolation.affine_transform\n Returns (matrix, offset)\n \"\"\"\n\n return (np.array([[self.v[0], -self.v[1]], [self.v[1], self.v[0]]]), self.v[2:4])\n\n\n def apply(self, x, y):\n \"\"\"\n Applies the transform to a point (x, y)\n \"\"\"\n xn = self.v[0]*x -self.v[1]*y + self.v[2]\n yn = self.v[1]*x +self.v[0]*y + self.v[3]\n return (xn, yn)\n\n def applystar(self, star):\n transstar = star.copy()\n (transstar.x, transstar.y) = self.apply((transstar.x, transstar.y))\n return transstar\n\n def applystarlist(self, starlist):\n return [self.applystar(star) for star in starlist]\n\ndef sortstarlistbyflux(starlist):\n \"\"\"\n We sort starlist according to flux : highest flux first !\n \"\"\"\n sortedstarlist = sorted(starlist, key=operator.itemgetter('flux'))\n sortedstarlist.reverse()\n return sortedstarlist\n\ndef area(stars, border=0.01):\n \"\"\"\n Returns the area covered by the stars.\n Border is relative to max-min\n \"\"\"\n if len(stars) == 0:\n return np.array([0, 1, 0, 1])\n\n if len(stars) == 1:\n star = stars[0]\n return np.array([star['x'] - 0.5, star['x'] + 0.5, star['y'] - 0.5, star['y'] + 0.5])\n\n (xmin, xmax) = (np.min(stars['x']), np.max(stars['x']))\n (ymin, ymax) = (np.min(stars['y']), np.max(stars['y']))\n xw = xmax - xmin\n yw = ymax - ymin\n xmin = xmin - border*xw\n xmax = xmax + border*xw\n ymin = ymin - border*yw\n ymax = ymax + border*yw\n return np.array([xmin, xmax, ymin, ymax])\n\ndef makequads1(starlist, n=7, s=0, d=50.0, verbose=True):\n \"\"\"\n First trivial quad maker.\n Makes combis of the n brightest stars.\n\n :param n: number of stars to consider (brightest ones).\n :type n: int\n :param s: how many of the brightest stars should I skip ?\n This feature is useful to avoid building quads with nearly saturated stars that are not\n available in other exposures.\n :type s: int\n :param d: minimal distance between stars\n :type d: float\n\n \"\"\"\n quadlist = []\n sortedstars = sortstarlistbyflux(starlist)\n\n for fourstars in itertools.combinations(sortedstars[s:s+n], 4):\n if mindist(fourstars) > d:\n quadlist.append(Quad(fourstars))\n\n if verbose:\n print(\"Made %4i quads from %4i stars (combi n=%i s=%i d=%.1f)\" % (len(quadlist), len(starlist), n, s, d))\n\n return quadlist\n\ndef mindist(cats):\n \"\"\"\n Function that tests if 4 stars are suitable to make a good quad...\n \"\"\"\n tests = [(0,1), (0,2), (0,3), (1,2), (1,3), (2,3)]\n dists = np.array([np.linalg.norm(np.array(cats[0]['x'], cats[0]['y']) - np.array(cats[1]['x'], cats[1]['y'])) for (i,j) in tests])\n return np.min(dists)\n\ndef removeduplicates(quadlist, verbose=True):\n \"\"\"\n Returns a quadlist without quads with identical hashes...\n \"\"\"\n # To avoid crash in lexsort if quadlist is too small :\n if len(quadlist) < 2:\n return quadlist\n hasharray = np.array([q.hash for q in quadlist])\n\n order = np.lexsort(hasharray.T)\n hasharray = hasharray[order]\n #diff = np.diff(hasharray, axis=0)\n diff = np.fabs(np.diff(hasharray, axis=0))\n #diff = np.sum(diff, axis=1)\n ui = np.ones(len(hasharray), 'bool')\n ui[1:] = (diff >= 0.000001).any(axis=1)\n #print(hasharray[ui==False])\n if verbose:\n print(\"Removing %i/%i duplicates\" % (len(quadlist) - np.sum(ui), len(quadlist)))\n\n return [quad for (quad, u) in zip(quadlist, ui) if u == True]\n" ]
[ [ "numpy.sum", "numpy.diff", "numpy.linalg.inv", "numpy.asarray", "numpy.argmax", "numpy.lexsort", "numpy.max", "numpy.min", "numpy.array" ] ]
ANCL/QuadPPO
[ "b7ed0574467bd321f4259175621a12ff7aeb7d12" ]
[ "spinup/algos/tf1/td3/core.py" ]
[ "import numpy as np\nimport tensorflow as tf\n\n\ndef placeholder(dim=None):\n return tf.placeholder(dtype=tf.float32, shape=(None,dim) if dim else (None,))\n\ndef placeholders(*args):\n return [placeholder(dim) for dim in args]\n\ndef mlp(x, hidden_sizes=(32,), activation=tf.tanh, output_activation=None):\n for h in hidden_sizes[:-1]:\n x = tf.layers.dense(x, units=h, activation=activation)\n return tf.layers.dense(x, units=hidden_sizes[-1], activation=output_activation)\n\ndef get_vars(scope):\n return [x for x in tf.global_variables() if scope in x.name]\n\ndef count_vars(scope):\n v = get_vars(scope)\n return sum([np.prod(var.shape.as_list()) for var in v])\n\n\"\"\"\nActor-Critics\n\"\"\"\ndef mlp_actor_critic(x, a, hidden_sizes=(256,256), activation=tf.nn.relu, \n output_activation=tf.tanh, action_space=None):\n act_dim = a.shape.as_list()[-1]\n act_limit = action_space.high[0]\n with tf.variable_scope('pi'):\n pi = act_limit * mlp(x, list(hidden_sizes)+[act_dim], activation, output_activation)\n with tf.variable_scope('q1'):\n q1 = tf.squeeze(mlp(tf.concat([x,a], axis=-1), list(hidden_sizes)+[1], activation, None), axis=1)\n with tf.variable_scope('q2'):\n q2 = tf.squeeze(mlp(tf.concat([x,a], axis=-1), list(hidden_sizes)+[1], activation, None), axis=1)\n with tf.variable_scope('q1', reuse=True):\n q1_pi = tf.squeeze(mlp(tf.concat([x,pi], axis=-1), list(hidden_sizes)+[1], activation, None), axis=1)\n return pi, q1, q2, q1_pi\n" ]
[ [ "tensorflow.placeholder", "tensorflow.variable_scope", "tensorflow.global_variables", "tensorflow.concat", "tensorflow.layers.dense" ] ]
kunalq/Cirq
[ "de0c5e855069bba71e55b070fc9b06f58c07a861", "e73c9bef672e83143ab04e7f169988149055d630" ]
[ "cirq/ion/convert_to_ion_gates_test.py", "cirq/linalg/transformations.py" ]
[ "# Copyright 2018 The Cirq Developers\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport pytest\n\nimport numpy as np\n\nimport cirq\n\n\nclass OtherX(cirq.SingleQubitGate):\n def _unitary_(self) -> np.ndarray:\n return np.array([[0, 1], [1, 0]])\n\n\nclass NoUnitary(cirq.SingleQubitGate):\n pass\n\n\nclass OtherCNOT(cirq.TwoQubitGate):\n def _unitary_(self) -> np.ndarray:\n return np.array([[1, 0, 0, 0],\n [0, 1, 0, 0],\n [0, 0, 0, 1],\n [0, 0, 1, 0]])\n\n\ndef test_convert_to_ion_gates():\n q0 = cirq.GridQubit(0, 0)\n q1 = cirq.GridQubit(0, 1)\n op = cirq.CNOT(q0, q1)\n circuit = cirq.Circuit()\n\n with pytest.raises(TypeError):\n cirq.ion.ConvertToIonGates().convert_one(circuit)\n\n with pytest.raises(TypeError):\n cirq.ion.ConvertToIonGates().convert_one(NoUnitary().on(q0))\n\n no_unitary_op = NoUnitary().on(q0)\n assert cirq.ion.ConvertToIonGates(ignore_failures=True).convert_one(\n no_unitary_op) == [no_unitary_op]\n\n rx = cirq.ion.ConvertToIonGates().convert_one(OtherX().on(q0))\n rop = cirq.ion.ConvertToIonGates().convert_one(op)\n rcnot = cirq.ion.ConvertToIonGates().convert_one(OtherCNOT().on(q0, q1))\n assert rx == [\n cirq.PhasedXPowGate(phase_exponent=1).on(cirq.GridQubit(0, 0))\n ]\n assert rop == [cirq.Ry(np.pi/2).on(op.qubits[0]),\n cirq.ion.MS(np.pi/4).on(op.qubits[0], op.qubits[1]),\n cirq.ops.Rx(-1*np.pi/2).on(op.qubits[0]),\n cirq.ops.Rx(-1*np.pi/2).on(op.qubits[1]),\n cirq.ops.Ry(-1*np.pi/2).on(op.qubits[0])]\n assert rcnot == [\n cirq.PhasedXPowGate(phase_exponent=-0.75,\n exponent=0.5).on(cirq.GridQubit(0, 0)),\n cirq.PhasedXPowGate(phase_exponent=1,\n exponent=0.25).on(cirq.GridQubit(0, 1)),\n cirq.T.on(cirq.GridQubit(0, 0)),\n cirq.MS(-0.5 * np.pi / 2).on(cirq.GridQubit(0, 0), cirq.GridQubit(0,\n 1)),\n (cirq.Y**0.5).on(cirq.GridQubit(0, 0)),\n cirq.PhasedXPowGate(phase_exponent=1,\n exponent=0.25).on(cirq.GridQubit(0, 1)),\n (cirq.Z**-0.75).on(cirq.GridQubit(0, 0))\n ]\n\n\ndef test_convert_to_ion_circuit():\n q0 = cirq.LineQubit(0)\n q1 = cirq.LineQubit(1)\n us = cirq.Duration(nanos=1000)\n ion_device = cirq.IonDevice(us, us, us, [q0, q1])\n\n clifford_circuit_1 = cirq.Circuit()\n clifford_circuit_1.append([cirq.X(q0), cirq.H(q1),\n cirq.MS(np.pi/4).on(q0, q1)])\n ion_circuit_1 = cirq.ion.ConvertToIonGates().convert_circuit(\n clifford_circuit_1)\n\n ion_device.validate_circuit(ion_circuit_1)\n cirq.testing.assert_circuits_with_terminal_measurements_are_equivalent(\n clifford_circuit_1, ion_circuit_1, atol=1e-6)\n clifford_circuit_2 = cirq.Circuit()\n clifford_circuit_2.append([cirq.X(q0), cirq.CNOT(q1, q0), cirq.MS(\n np.pi/4).on(q0, q1)])\n ion_circuit_2 = cirq.ion.ConvertToIonGates().convert_circuit(\n clifford_circuit_2)\n ion_device.validate_circuit(ion_circuit_2)\n cirq.testing.assert_circuits_with_terminal_measurements_are_equivalent(\n clifford_circuit_2, ion_circuit_2, atol=1e-6)\n", "# Copyright 2018 The Cirq Developers\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Utility methods for transforming matrices.\"\"\"\n\nfrom typing import Tuple, Optional, Sequence, List, Union, TypeVar\n\nimport numpy as np\n\nfrom cirq.protocols.approximate_equality import approx_eq\nfrom cirq.linalg import predicates\n\n# This is a special indicator value used by the subwavefunction method to\n# determine whether or not the caller provided a 'default' argument. It must be\n# of type np.ndarray to ensure the method has the correct type signature in that\n# case. It is checked for using `is`, so it won't have a false positive if the\n# user provides a different np.array([]) value.\nRaiseValueErrorIfNotProvided = np.array([]) # type: np.ndarray\n\nTDefault = TypeVar('TDefault')\n\n\ndef reflection_matrix_pow(reflection_matrix: np.ndarray, exponent: float):\n \"\"\"Raises a matrix with two opposing eigenvalues to a power.\n\n Args:\n reflection_matrix: The matrix to raise to a power.\n exponent: The power to raise the matrix to.\n\n Returns:\n The given matrix raised to the given power.\n \"\"\"\n\n # The eigenvalues are x and -x for some complex unit x. Determine x.\n squared_phase = np.dot(reflection_matrix[:, 0],\n reflection_matrix[0, :])\n phase = complex(np.sqrt(squared_phase))\n\n # Extract +x and -x eigencomponents of the matrix.\n i = np.eye(reflection_matrix.shape[0]) * phase\n pos_part = (i + reflection_matrix) * 0.5\n neg_part = (i - reflection_matrix) * 0.5\n\n # Raise the matrix to a power by raising its eigencomponents to that power.\n pos_factor = phase**(exponent - 1)\n neg_factor = pos_factor * complex(-1)**exponent\n pos_part_raised = pos_factor * pos_part\n neg_part_raised = neg_part * neg_factor\n return pos_part_raised + neg_part_raised\n\n\ndef match_global_phase(a: np.ndarray,\n b: np.ndarray\n ) -> Tuple[np.ndarray, np.ndarray]:\n \"\"\"Phases the given matrices so that they agree on the phase of one entry.\n\n To maximize precision, the position with the largest entry from one of the\n matrices is used when attempting to compute the phase difference between\n the two matrices.\n\n Args:\n a: A numpy array.\n b: Another numpy array.\n\n Returns:\n A tuple (a', b') where a' == b' implies a == b*exp(i t) for some t.\n \"\"\"\n\n # Not much point when they have different shapes.\n if a.shape != b.shape or a.size == 0:\n return np.copy(a), np.copy(b)\n\n # Find the entry with the largest magnitude in one of the matrices.\n k = max(np.ndindex(*a.shape), key=lambda t: abs(b[t]))\n\n def dephase(v):\n r = np.real(v)\n i = np.imag(v)\n\n # Avoid introducing floating point error when axis-aligned.\n if i == 0:\n return -1 if r < 0 else 1\n if r == 0:\n return 1j if i < 0 else -1j\n\n return np.exp(-1j * np.arctan2(i, r))\n\n # Zero the phase at this entry in both matrices.\n return a * dephase(a[k]), b * dephase(b[k])\n\n\ndef targeted_left_multiply(left_matrix: np.ndarray,\n right_target: np.ndarray,\n target_axes: Sequence[int],\n out: Optional[np.ndarray] = None\n ) -> np.ndarray:\n \"\"\"Left-multiplies the given axes of the target tensor by the given matrix.\n\n Note that the matrix must have a compatible tensor structure.\n\n For example, if you have an 6-qubit state vector `input_state` with shape\n (2, 2, 2, 2, 2, 2), and a 2-qubit unitary operation `op` with shape\n (2, 2, 2, 2), and you want to apply `op` to the 5'th and 3'rd qubits\n within `input_state`, then the output state vector is computed as follows:\n\n output_state = cirq.targeted_left_multiply(op, input_state, [5, 3])\n\n This method also works when the right hand side is a matrix instead of a\n vector. If a unitary circuit's matrix is `old_effect`, and you append\n a CNOT(q1, q4) operation onto the circuit, where the control q1 is the qubit\n at offset 1 and the target q4 is the qubit at offset 4, then the appended\n circuit's unitary matrix is computed as follows:\n\n new_effect = cirq.targeted_left_multiply(\n left_matrix=cirq.unitary(cirq.CNOT).reshape((2, 2, 2, 2)),\n right_target=old_effect,\n target_axes=[1, 4])\n\n Args:\n left_matrix: What to left-multiply the target tensor by.\n right_target: A tensor to carefully broadcast a left-multiply over.\n target_axes: Which axes of the target are being operated on.\n out: The buffer to store the results in. If not specified or None, a new\n buffer is used. Must have the same shape as right_target.\n\n Returns:\n The output tensor.\n \"\"\"\n k = len(target_axes)\n d = len(right_target.shape)\n work_indices = tuple(range(k))\n data_indices = tuple(range(k, k + d))\n used_data_indices = tuple(data_indices[q] for q in target_axes)\n input_indices = work_indices + used_data_indices\n output_indices = list(data_indices)\n for w, t in zip(work_indices, target_axes):\n output_indices[t] = w\n\n all_indices = set(input_indices + data_indices + tuple(output_indices))\n\n return np.einsum(left_matrix, input_indices,\n right_target, data_indices,\n output_indices,\n # We would prefer to omit 'optimize=' (it's faster),\n # but this is a workaround for a bug in numpy:\n # https://github.com/numpy/numpy/issues/10926\n optimize=len(all_indices) >= 26,\n # And this is workaround for *another* bug!\n # Supposed to be able to just say 'old=old'.\n **({'out': out} if out is not None else {}))\n\n\ndef targeted_conjugate_about(tensor: np.ndarray,\n target: np.ndarray,\n indices: Sequence[int],\n conj_indices: Sequence[int] = None,\n buffer: Optional[np.ndarray] = None,\n out: Optional[np.ndarray] = None) -> np.ndarray:\n r\"\"\"Conjugates the given tensor about the target tensor.\n\n This method computes a target tensor conjugated by another tensor.\n Here conjugate is used in the sense of conjugating by a matrix, i.a.\n A conjugated about B is $A B A^\\dagger$ where $\\dagger$ represents the\n conjugate transpose.\n\n Abstractly this compute $A \\cdot B \\cdot A^\\dagger$ where A and B are\n multi-dimensional arrays, and instead of matrix multiplication $\\cdot$\n is a contraction between the given indices (indices for first $\\cdot$,\n conj_indices for second $\\cdot$).\n\n More specifically this computes\n sum tensor_{i_0,...,i_{r-1},j_0,...,j_{r-1}}\n * target_{k_0,...,k_{r-1},l_0,...,l_{r-1}\n * tensor_{m_0,...,m_{r-1},n_0,...,n_{r-1}}^*\n where the sum is over indices where j_s = k_s and s is in `indices`\n and l_s = m_s and s is in `conj_indices`.\n\n Args:\n tensor: The tensor that will be conjugated about the target tensor.\n target: The tensor that will receive the conjugation.\n indices: The indices which will be contracted between the tensor and\n target.\n conj_indices; The indices which will be contracted between the\n complex conjugate of the tensor and the target. If this is None,\n then these will be the values in indices plus half the number\n of dimensions of the target (`ndim`). This is the most common case\n and corresponds to the case where the target is an operator on\n a n-dimensional tensor product space (here `n` would be `ndim`).\n buffer: A buffer to store partial results in. If not specified or None,\n a new buffer is used.\n out: The buffer to store the results in. If not specified or None, a new\n buffer is used. Must have the same shape as target.\n\n Returns:\n The result the conjugation.\n \"\"\"\n conj_indices = conj_indices or [i + target.ndim // 2 for i in indices]\n first_multiply = targeted_left_multiply(tensor, target, indices, out=buffer)\n return targeted_left_multiply(np.conjugate(tensor),\n first_multiply,\n conj_indices,\n out=out)\n\n\n_TSliceAtom = Union[int, slice, 'ellipsis']\n_TSlice = Union[_TSliceAtom, Sequence[_TSliceAtom]]\n\n\ndef apply_matrix_to_slices(\n target: np.ndarray,\n matrix: np.ndarray,\n slices: List[_TSlice],\n *,\n out: Optional[np.ndarray] = None) -> np.ndarray:\n \"\"\"Left-multiplies an NxN matrix onto N slices of a numpy array.\n\n Example:\n The 4x4 matrix of a fractional SWAP gate can be expressed as\n\n [ 1 ]\n [ X**t ]\n [ 1 ]\n\n Where X is the 2x2 Pauli X gate and t is the power of the swap with t=1\n being a full swap. X**t is a power of the Pauli X gate's matrix.\n Applying the fractional swap is equivalent to applying a fractional X\n within the inner 2x2 subspace; the rest of the matrix is identity. This\n can be expressed using `apply_matrix_to_slices` as follows:\n\n def fractional_swap(target):\n assert target.shape == (4,)\n return apply_matrix_to_slices(\n target=target,\n matrix=cirq.unitary(cirq.X**t),\n slices=[1, 2]\n )\n\n Args:\n target: The input array with slices that need to be left-multiplied.\n matrix: The linear operation to apply to the subspace defined by the\n slices.\n slices: The parts of the tensor that correspond to the \"vector entries\"\n that the matrix should operate on. May be integers or complicated\n multi-dimensional slices into a tensor. The slices must refer to\n non-overlapping sections of the input all with the same shape.\n out: Where to write the output. If not specified, a new numpy array is\n created, with the same shape and dtype as the target, to store the\n output.\n\n Returns:\n The transformed array.\n \"\"\"\n # Validate arguments.\n if out is target:\n raise ValueError(\"Can't write output over the input.\")\n if matrix.shape != (len(slices), len(slices)):\n raise ValueError(\"matrix.shape != (len(slices), len(slices))\")\n\n # Fill in default values and prepare space.\n if out is None:\n out = np.copy(target)\n else:\n out[...] = target[...]\n\n # Apply operation.\n for i, s_i in enumerate(slices):\n out[s_i] *= matrix[i, i]\n for j, s_j in enumerate(slices):\n if i != j:\n out[s_i] += target[s_j] * matrix[i, j]\n\n return out\n\n\ndef partial_trace(tensor: np.ndarray,\n keep_indices: List[int]) -> np.ndarray:\n \"\"\"Takes the partial trace of a given tensor.\n\n The input tensor must have shape `(d_0, ..., d_{k-1}, d_0, ..., d_{k-1})`.\n The trace is done over all indices that are not in keep_indices. The\n resulting tensor has shape `(d_{i_0}, ..., d_{i_r}, d_{i_0}, ..., d_{i_r})`\n where `i_j` is the `j`th element of `keep_indices`.\n\n Args:\n tensor: The tensor to sum over. This tensor must have a shape\n `(d_0, ..., d_{k-1}, d_0, ..., d_{k-1})`.\n keep_indices: Which indices to not sum over. These are only the indices\n of the first half of the tensors indices (i.e. all elements must\n be between `0` and `tensor.ndims / 2 - 1` inclusive).\n\n Raises:\n ValueError: if the tensor is not of the correct shape or the indices\n are not from the first half of valid indices for the tensor.\n \"\"\"\n ndim = tensor.ndim // 2\n if not all(tensor.shape[i] == tensor.shape[i + ndim] for i in range(ndim)):\n raise ValueError('Tensors must have shape (d_0,...,d_{{k-1}},d_0,...,'\n 'd_{{k-1}}) but had shape ({}).'.format(tensor.shape))\n if not all(i < ndim for i in keep_indices):\n raise ValueError('keep_indices were {} but must be in first half, '\n 'i.e. have index less that {}.'.format(keep_indices,\n ndim))\n keep_set = set(keep_indices)\n keep_map = dict(zip(keep_indices, sorted(keep_indices)))\n left_indices = [keep_map[i] if i in keep_set else i for i in range(ndim)]\n right_indices = [ndim + i if i in keep_set else i for i in left_indices]\n return np.einsum(tensor, left_indices + right_indices)\n\n\ndef wavefunction_partial_trace_as_mixture(\n wavefunction: np.ndarray,\n keep_indices: List[int],\n *,\n atol: Union[int, float] = 1e-8) -> Tuple[Tuple[float, np.ndarray], ...]:\n \"\"\"Returns a mixture representing a wavefunction with only some qubits kept.\n\n The input wavefunction must have shape `(2,) * n` or `(2 ** n)` where\n `wavefunction` is expressed over n qubits. States in the output mixture will\n retain the same type of shape as the input wavefunction, either `(2 ** k)`\n or `(2,) * k` where k is the number of qubits kept.\n\n If the wavefunction cannot be factored into a pure state over `keep_indices`\n then eigendecomposition is used and the output mixture will not be unique.\n\n Args:\n wavefunction: A wavefunction to express over a qubit subset.\n keep_indices: Which indices to express the wavefunction on.\n atol: The tolerance for determining that a factored state is pure.\n\n Returns:\n A single-component mixture in which the factored wavefunction has\n probability '1' if the factored state is pure, or else a mixture of the\n default eigendecomposition of the mixed state's partial trace.\n\n Raises:\n ValueError: if the input wavefunction is not an array of length\n `(2 ** n)` or a tensor with a shape of `(2,) * n`\n \"\"\"\n\n # Attempt to do efficient state factoring.\n state = subwavefunction(wavefunction, keep_indices, default=None, atol=atol)\n if state is not None:\n return ((1.0, state),)\n\n # Fall back to a (non-unique) mixture representation.\n keep_dims = 1 << len(keep_indices)\n ret_shape: Union[Tuple[int], Tuple[int, ...]]\n if wavefunction.shape == (wavefunction.size,):\n ret_shape = (keep_dims,)\n elif all(e == 2 for e in wavefunction.shape):\n ret_shape = tuple(2 for _ in range(len(keep_indices)))\n\n rho = np.kron(\n np.conj(wavefunction.reshape(-1, 1)).T,\n wavefunction.reshape(-1, 1)).reshape(\n (2, 2) * int(np.log2(wavefunction.size)))\n keep_rho = partial_trace(rho, keep_indices).reshape((keep_dims,) * 2)\n eigvals, eigvecs = np.linalg.eigh(keep_rho)\n mixture = tuple(zip(eigvals, [vec.reshape(ret_shape) for vec in eigvecs.T]))\n return tuple([\n (float(p[0]), p[1]) for p in mixture if not approx_eq(p[0], 0.0)\n ])\n\n\ndef subwavefunction(wavefunction: np.ndarray,\n keep_indices: List[int],\n *,\n default: TDefault = RaiseValueErrorIfNotProvided,\n atol: Union[int, float] = 1e-8) -> np.ndarray:\n r\"\"\"Attempts to factor a wavefunction into two parts and return one of them.\n\n The input wavefunction must have shape `(2,) * n` or `(2 ** n)` where\n `wavefunction` is expressed over n qubits. The returned array will retain\n the same type of shape as the input wavefunction, either `(2 ** k)` or\n `(2,) * k` where k is the number of qubits kept.\n\n If a wavefunction $|\\psi\\rangle$ defined on n qubits is an outer product\n of kets like $|\\psi\\rangle$ = $|x\\rangle \\otimes |y\\rangle$, and\n $|x\\rangle$ is defined over the subset `keep_indices` of k qubits, then\n this method will factor $|\\psi\\rangle$ into $|x\\rangle$ and $|y\\rangle$ and\n return $|x\\rangle$. Note that $|x\\rangle$ is not unique, because $(e^{i\n \\theta} |y\\rangle) \\otimes (|x\\rangle) = (|y\\rangle) \\otimes (e^{i \\theta}\n |x\\rangle)$ . This method randomizes the global phase of $|x\\rangle$ in\n order to avoid accidental reliance on it.\n\n If the provided wavefunction cannot be factored into a pure state over\n `keep_indices`, the method will fall back to return `default`. If `default`\n is not provided, the method will fail and raise `ValueError`.\n\n Args:\n wavefunction: A wavefunction to express over a qubit subset.\n keep_indices: Which indices to express the wavefunction on.\n default: Determines the fallback behavior when `wavefunction` doesn't\n have a pure state factorization. If the factored state is not pure\n and `default` is not set, a ValueError is raised. If default is set\n to a value, that value is returned.\n atol: The minimum tolerance for comparing the output state's coherence\n measure to 1.\n\n Returns:\n The wavefunction expressed over the desired subset of qubits.\n\n Raises:\n ValueError: if the wavefunction is not of the correct shape or the\n indices are not a valid subset of the input wavefunction's indices, or\n the result of factoring is not a pure state.\n \"\"\"\n\n if not np.log2(wavefunction.size).is_integer():\n raise ValueError(\"Input wavefunction of size {} does not represent a \"\n \"state over qubits.\".format(wavefunction.size))\n\n n_qubits = int(np.log2(wavefunction.size))\n keep_dims = 1 << len(keep_indices)\n ret_shape: Union[Tuple[int], Tuple[int, ...]]\n if wavefunction.shape == (wavefunction.size,):\n ret_shape = (keep_dims,)\n wavefunction = wavefunction.reshape((2,) * n_qubits)\n elif wavefunction.shape == (2,) * n_qubits:\n ret_shape = tuple(2 for _ in range(len(keep_indices)))\n else:\n raise ValueError(\n \"Input wavefunction must be shaped like (2 ** n,) or (2,) * n\")\n\n keep_dims = 1 << len(keep_indices)\n if not np.isclose(np.linalg.norm(wavefunction), 1):\n raise ValueError(\"Input state must be normalized.\")\n if len(set(keep_indices)) != len(keep_indices):\n raise ValueError(\n \"keep_indices were {} but must be unique.\".format(keep_indices))\n if any([ind >= n_qubits for ind in keep_indices]):\n raise ValueError(\n \"keep_indices {} are an invalid subset of the input wavefunction.\")\n\n other_qubits = sorted(set(range(n_qubits)) - set(keep_indices))\n candidates = [\n wavefunction[predicates.slice_for_qubits_equal_to(other_qubits,\n k)].reshape(keep_dims)\n for k in range(1 << len(other_qubits))\n ]\n # The coherence measure is computed using unnormalized candidates.\n best_candidate = max(candidates, key=lambda c: np.linalg.norm(c, 2))\n best_candidate = best_candidate / np.linalg.norm(best_candidate)\n left = np.conj(best_candidate.reshape((keep_dims,))).T\n coherence_measure = sum(\n [abs(np.dot(left, c.reshape((keep_dims,))))**2 for c in candidates])\n\n if approx_eq(coherence_measure, 1, atol=atol):\n return np.exp(\n 2j * np.pi * np.random.random()) * best_candidate.reshape(ret_shape)\n\n # Method did not yield a pure state. Fall back to `default` argument.\n if default is not RaiseValueErrorIfNotProvided:\n return default\n\n raise ValueError(\n \"Input wavefunction could not be factored into pure state over \"\n \"indices {}\".format(keep_indices))\n" ]
[ [ "numpy.array" ], [ "numpy.sqrt", "numpy.eye", "numpy.log2", "numpy.arctan2", "numpy.einsum", "numpy.conjugate", "numpy.linalg.eigh", "numpy.copy", "numpy.random.random", "numpy.array", "numpy.dot", "numpy.linalg.norm", "numpy.real", "numpy.ndindex", "numpy.imag" ] ]
garymm/tensorflow-onnx
[ "a8f78ac7903493dee579304b7b1717aa9ec9706f" ]
[ "tf2onnx/rewriter/quantization_ops_rewriter.py" ]
[ "# SPDX-License-Identifier: Apache-2.0\n\n\n\"\"\"\ntf2onnx.rewriter - rewrite tensorflow QuantizeAndDequantizeV2|QuantizeAndDequantizeV3|QuantizeAndDequantizeV4 op\n\"\"\"\n\nimport numpy as np\nfrom onnx import TensorProto, helper\nfrom tf2onnx.graph_matcher import OpTypePattern, GraphMatcher\nfrom tf2onnx import utils\n\n# pylint: disable=missing-docstring\n\ndef extract_numpy_array(node):\n return np.frombuffer(node.attr[\"value\"].t.raw_data, dtype=\"float32\")\n\ndef create_qdq_nodes(g, match_results):\n\n for match in match_results:\n qdq_node = match.get_op('output')\n qdq_node_output_dtype = g.get_dtype(qdq_node.output[0])\n qdq_node_output_shape = g.get_shape(qdq_node.output[0])\n\n # Get the attributes of qdq node\n narrow_range = qdq_node.attr['narrow_range'].i\n signed_input = qdq_node.attr['signed_input'].i\n range_given = qdq_node.get_attr_value(\"range_given\", qdq_node.type != \"QuantizeAndDequantizeV2\" or \\\n qdq_node.type != \"QuantizeAndDequantizeV4\")\n\n min_quantized, max_quantized = [-127, 127]\n if not narrow_range and signed_input:\n min_quantized = -128\n\n if not signed_input:\n min_quantized, max_quantized = [0, 255]\n\n # Get axis attribute for per channel implementation.\n axis = qdq_node.get_attr_value('axis', -1)\n q_attrs = {}\n\n quantized_np_dtype = np.int8 if signed_input else np.uint8\n quantized_dtype = TensorProto.INT8 if signed_input else TensorProto.UINT8\n\n if axis != -1:\n utils.make_sure(g.opset >= 13, \"Opset >= 13 is required for per channel quantization\")\n q_attrs['axis'] = axis\n\n if not range_given:\n min_np = np.array(min_quantized, np.float32)\n max_np = np.array(max_quantized, np.float32)\n max_quantized_const = g.make_const(utils.make_name(\"max_const\"), max_np).output[0]\n if signed_input:\n min_quantized_const = g.make_const(utils.make_name(\"min_const\"), min_np).output[0]\n reduce_attr = {'keepdims': 0}\n if axis != -1:\n inp_rank = g.get_rank(qdq_node.input[0])\n utils.make_sure(inp_rank is not None, \"Input rank cannot be unknown for qdq op %s\", qdq_node.name)\n reduce_axes = [i for i in range(inp_rank) if i != axis]\n reduce_attr['axes'] = reduce_axes\n\n max_value = g.make_node(\"ReduceMax\", [qdq_node.input[0]], attr=reduce_attr).output[0]\n if signed_input:\n min_value = g.make_node(\"ReduceMin\", [qdq_node.input[0]], attr=reduce_attr).output[0]\n\n scale_from_max_side = g.make_node(\"Div\", [max_value, max_quantized_const]).output[0]\n if signed_input:\n scale_from_min_side = g.make_node(\"Div\", [min_value, min_quantized_const]).output[0]\n scale = g.make_node(\"Max\", [scale_from_min_side, scale_from_max_side]).output[0]\n else:\n scale = scale_from_max_side\n\n if axis == -1:\n zero_point_np = np.zeros([], dtype=quantized_np_dtype)\n zero_point = g.make_const(utils.make_name(\"zero_point\"), zero_point_np).output[0]\n else:\n zero_tensor = helper.make_tensor(\"value\", quantized_dtype, dims=[1], vals=[0])\n scale_shape = g.make_node(\"Shape\", [scale]).output[0]\n zero_point = g.make_node(\"ConstantOfShape\", inputs=[scale_shape], attr={\"value\": zero_tensor}).output[0]\n else:\n # Get the min and max value of the inputs to QDQ op\n min_value = extract_numpy_array(qdq_node.inputs[1])\n max_value = extract_numpy_array(qdq_node.inputs[2])\n\n num_channels = min_value.shape[0]\n scales = np.zeros(num_channels, dtype=np.float32)\n\n for i in range(num_channels):\n # Calculate scales from the min and max values\n scale_from_min_side = min_value[i] / min_quantized if min_quantized < 0 else 0\n scale_from_max_side = max_value[i] / max_quantized if max_quantized > 0 else 0\n\n if scale_from_min_side > scale_from_max_side:\n scale = scale_from_min_side\n else:\n scale = scale_from_max_side\n\n utils.make_sure(scale > 0, \"Quantize/Dequantize scale must be greater than zero\")\n scales[i] = np.float32(scale)\n\n # Set scalars for scale and zero point for per layer quantization\n if num_channels == 1:\n scales = scales[0]\n zero_point_np = np.zeros([], dtype=quantized_np_dtype)\n else:\n utils.make_sure(axis != -1, \"Axis must be specified for per channel quantization\")\n zero_point_np = np.zeros([num_channels], dtype=quantized_np_dtype)\n\n # Split it into QuantizeLinear and DequantizeLinear and remove the QDQ node reference\n cast_scale = scales.astype(np.float32)\n scale = g.make_const(name=utils.make_name(\"quant_scale\"), np_val=cast_scale).output[0]\n zero_point = g.make_const(utils.make_name(\"zero_point\"), zero_point_np).output[0]\n\n quant_node = g.make_node(op_type=\"QuantizeLinear\",\n inputs=[qdq_node.input[0], scale, zero_point],\n shapes=[qdq_node_output_shape],\n attr=q_attrs,\n dtypes=[quantized_dtype],\n name=utils.make_name(\"QuantLinearNode\"))\n\n g.set_shape(quant_node.output[0], qdq_node_output_shape)\n\n g.remove_node(qdq_node.name)\n\n dequant_node = g.make_node(op_type=\"DequantizeLinear\",\n inputs=[quant_node.output[0], scale, zero_point],\n outputs=[qdq_node.output[0]],\n shapes=[qdq_node_output_shape],\n attr=q_attrs,\n dtypes=[qdq_node_output_dtype],\n name=utils.make_name(\"DequantLinearNode\"))\n g.set_shape(dequant_node.output[0], qdq_node_output_shape)\n\n return g.get_nodes()\n\ndef rewrite_quantize_and_dequantize(g, ops):\n\n pattern_for_qdq_v2 = \\\n OpTypePattern('QuantizeAndDequantizeV2', name='output', inputs=[\n OpTypePattern(\"*\"),\n OpTypePattern(None),\n OpTypePattern(None),\n ])\n pattern_for_qdq_v3 = \\\n OpTypePattern('QuantizeAndDequantizeV3', name='output', inputs=[\n OpTypePattern(\"*\"),\n OpTypePattern(None),\n OpTypePattern(None),\n OpTypePattern(None),\n ])\n pattern_for_qdq_v4 = \\\n OpTypePattern('QuantizeAndDequantizeV4', name='output', inputs=[\n OpTypePattern(\"*\"),\n OpTypePattern(None),\n OpTypePattern(None),\n ])\n\n # Match all the patterns for QDQ ops\n patterns = [pattern_for_qdq_v2, pattern_for_qdq_v3, pattern_for_qdq_v4]\n match_results = []\n for pattern in patterns:\n matcher = GraphMatcher(pattern)\n results = list(matcher.match_ops(ops))\n match_results.extend(results)\n\n return create_qdq_nodes(g, match_results)\n" ]
[ [ "numpy.array", "numpy.zeros", "numpy.float32", "numpy.frombuffer" ] ]
ChengF-Lab/scIVA
[ "f70a927531dd16236dff30decbe77f0552ad4f2d" ]
[ "sciva/loss.py" ]
[ "#!/usr/bin/env python\n\"\"\"\n#\n#\n\n# File Name: loss_function.py\n# Description:\n\n\"\"\"\nimport torch\nimport torch.nn.functional as F\n\nimport math\n\ndef kl_divergence(mu, logvar):\n \"\"\"\n Computes the KL-divergence of\n some element z.\n\n KL(q||p) = -∫ q(z) log [ p(z) / q(z) ]\n = -E[log p(z) - log q(z)]\n \"\"\"\n return -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp(), dim=1)\n\n\ndef binary_cross_entropy(recon_x, x):\n return -torch.sum(x * torch.log(recon_x + 1e-8) + (1 - x) * torch.log(1 - recon_x + 1e-8), dim=-1)\n\n\ndef elbo(recon_x, x, z_params, binary=True):\n \"\"\"\n elbo = likelihood - kl_divergence\n L = -elbo\n\n Params:\n recon_x:\n x:\n \"\"\"\n mu, logvar = z_params\n kld = kl_divergence(mu, logvar)\n if binary:\n likelihood = -binary_cross_entropy(recon_x, x)\n else:\n likelihood = -F.mse_loss(recon_x, x)\n return torch.sum(likelihood), torch.sum(kld)\n # return likelihood, kld\n\n\ndef elbo_scIVA(recon_x, x, gamma, c_params, z_params, binary=True):\n \"\"\"\n L elbo(x) = Eq(z,c|x)[ log p(x|z) ] - KL(q(z,c|x)||p(z,c))\n = Eq(z,c|x)[ log p(x|z) + log p(z|c) + log p(c) - log q(z|x) - log q(c|x) ]\n \"\"\"\n mu_c, var_c, pi = c_params; #print(mu_c.size(), var_c.size(), pi.size())\n n_centroids = pi.size(1)\n mu, logvar = z_params\n mu_expand = mu.unsqueeze(2).expand(mu.size(0), mu.size(1), n_centroids)\n logvar_expand = logvar.unsqueeze(2).expand(logvar.size(0), logvar.size(1), n_centroids)\n\n # log p(x|z)\n if binary:\n likelihood = -binary_cross_entropy(recon_x, x) #;print(logvar_expand.size()) #, torch.exp(logvar_expand)/var_c)\n else:\n likelihood = -F.mse_loss(recon_x, x)\n\n # log p(z|c)\n logpzc = -0.5*torch.sum(gamma*torch.sum(math.log(2*math.pi) + \\\n torch.log(var_c) + \\\n torch.exp(logvar_expand)/var_c + \\\n (mu_expand-mu_c)**2/var_c, dim=1), dim=1)\n # log p(c)\n logpc = torch.sum(gamma*torch.log(pi), 1)\n\n # log q(z|x) or q entropy \n qentropy = -0.5*torch.sum(1+logvar+math.log(2*math.pi), 1)\n\n # log q(c|x)\n logqcx = torch.sum(gamma*torch.log(gamma), 1)\n\n kld = -logpzc - logpc + qentropy + logqcx\n\n return torch.sum(likelihood), torch.sum(kld)\n\n\n" ]
[ [ "torch.sum", "torch.nn.functional.mse_loss", "torch.log", "torch.exp" ] ]
sighingnow/tensorflow
[ "12579f9a795da54db405b5918f709665e2a7c07f" ]
[ "tensorflow/python/framework/function_def_to_graph.py" ]
[ "# Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# =============================================================================\n\"\"\"Utility to convert FunctionDef to GraphDef and Graph.\"\"\"\n\nimport itertools\n\n\nfrom tensorflow.core.framework import function_pb2\nfrom tensorflow.core.framework import graph_pb2\nfrom tensorflow.core.framework import tensor_shape_pb2\nfrom tensorflow.core.framework import types_pb2\nfrom tensorflow.core.framework import versions_pb2\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.framework import cpp_shape_inference_pb2\nfrom tensorflow.python.framework import importer\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import versions\nfrom tensorflow.python.framework.func_graph import FuncGraph\nfrom tensorflow.python.ops import resource_variable_ops\n\n\ndef function_def_to_graph(fdef,\n structured_input_signature=None,\n structured_outputs=None,\n input_shapes=None):\n \"\"\"Converts a FunctionDef to a FuncGraph (sub-class Graph).\n\n The returned FuncGraph's `name`, `inputs` and `outputs` fields will be set.\n The input tensors are represented as placeholders.\n\n Note: `FuncGraph.inputs` and `FuncGraph.captures` are not set and may be set\n by the caller.\n\n Args:\n fdef: FunctionDef.\n structured_input_signature: Optional. The structured input signature to\n use for initializing the FuncGraph. See the docstring for FuncGraph for\n more information.\n structured_outputs: Optional. The structured outputs to use for\n initializing the FuncGraph. See the docstring for FuncGraph for more\n information.\n input_shapes: Optional. A list of TensorShape objects of the shapes of\n function inputs. Defaults to the function's \"_input_shapes\" attribute. If\n specified, its length must match length of `fdef.signature.input_arg`. If\n a shape is None, the corresponding input placeholder will have unknown\n shape.\n\n Returns:\n A FuncGraph.\n \"\"\"\n func_graph = FuncGraph(fdef.signature.name,\n structured_input_signature=structured_input_signature,\n structured_outputs=structured_outputs)\n if input_shapes is None:\n input_shapes_attr = fdef.attr.get(\"_input_shapes\", None)\n if input_shapes_attr is not None:\n raw_input_shapes = input_shapes_attr.list.shape\n\n # Replace resource handle shapes, since they are always stored as a scalar\n # shape in the _input_shapes attribute.\n input_shapes = []\n for input_shape, arg_def in zip(raw_input_shapes,\n fdef.signature.input_arg):\n if arg_def.type == types_pb2.DT_RESOURCE and arg_def.handle_data:\n input_shapes.append(arg_def.handle_data[0].shape)\n else:\n input_shapes.append(input_shape)\n\n graph_def, nested_to_flat_tensor_name = function_def_to_graph_def(\n fdef, input_shapes)\n\n with func_graph.as_default():\n # Add all function nodes to the graph.\n importer.import_graph_def_for_function(graph_def, name=\"\")\n\n # Initialize fields specific to FuncGraph.\n\n # inputs\n input_tensor_names = [\n nested_to_flat_tensor_name[arg.name] for arg in fdef.signature.input_arg\n ]\n func_graph.inputs = [\n func_graph.get_tensor_by_name(name) for name in input_tensor_names\n ]\n\n # outputs\n output_tensor_names = [\n nested_to_flat_tensor_name[fdef.ret[arg.name]]\n for arg in fdef.signature.output_arg\n ]\n func_graph.outputs = [\n func_graph.get_tensor_by_name(name) for name in output_tensor_names\n ]\n func_graph.control_outputs = [\n func_graph.get_operation_by_name(fdef.control_ret[ret_name])\n for ret_name in fdef.signature.control_output\n ]\n\n _set_handle_data(func_graph, fdef)\n\n for node in graph_def.node:\n output_shapes = node.attr.get(\"_output_shapes\", None)\n if output_shapes is not None:\n op = func_graph.get_operation_by_name(node.name)\n # _output_shapes for functions can sometimes be too long because the\n # output-intermediates-for-gradients version of the function was\n # substituted before saving. We'll accept that here. (See b/133666530).\n for output_index, shape in enumerate(\n output_shapes.list.shape[:len(op.outputs)]):\n op.outputs[output_index].set_shape(shape)\n output_names = {}\n for ret_arg_def, tensor_name in zip(\n fdef.signature.output_arg, output_tensor_names):\n output_names[ops.tensor_id(\n func_graph.get_tensor_by_name(tensor_name))] = (\n ret_arg_def.name)\n func_graph._output_names = output_names # pylint: disable=protected-access\n return func_graph\n\n\ndef is_function(fname):\n \"\"\"Checks for a function definition with `fname` in the current context.\"\"\"\n if context.executing_eagerly():\n return context.context().has_function(fname)\n else:\n graph = ops.get_default_graph()\n while graph is not None:\n if graph._is_function(fname): # pylint: disable=protected-access\n return True\n if hasattr(graph, \"outer_graph\"):\n graph = graph.outer_graph\n else:\n return False\n\n\ndef function_def_to_graph_def(fdef, input_shapes=None):\n \"\"\"Convert a FunctionDef to a GraphDef.\n\n Steps:\n 1. Creates placeholder nodes corresponding to inputs in\n `FunctionDef.signature.input_arg`.\n 2. Adds NodeDefs in `FunctionDef.node_def` to `GraphDef.node`.\n 3. Renames inputs of all nodes to use the convention of GraphDef instead of\n FunctionDef. See comment on `FunctionDef.node_def` on how the tensor naming\n in FunctionDefs is different from GraphDefs.\n\n Args:\n fdef: FunctionDef.\n input_shapes: Optional. A list of TensorShape objects of the shapes of\n function inputs. If specified, its length must match length of\n `fdef.signature.input_arg`. If a shape is None, the corresponding input\n placeholder will have unknown shape.\n\n Returns:\n A tuple of (GraphDef, dict<string, string>). The dict contains a mapping\n from nested tensor names (in FunctionDef) to flattened names (in GraphDef).\n\n Raises:\n ValueError: If the length of input_shapes does not match the number of\n input_args or if the FunctionDef is invalid.\n \"\"\"\n graph_def = graph_pb2.GraphDef()\n graph_def.versions.CopyFrom(\n versions_pb2.VersionDef(\n producer=versions.GRAPH_DEF_VERSION,\n min_consumer=versions.GRAPH_DEF_VERSION_MIN_CONSUMER))\n\n default_graph = ops.get_default_graph()\n\n copied_functions = set()\n\n if input_shapes and len(input_shapes) != len(fdef.signature.input_arg):\n raise ValueError(\"Length of `input_shapes` must match the number \"\n f\"of `input_arg`s in `fdef`. Got \"\n f\"{len(input_shapes)} `input_shapes` and \"\n f\"{len(fdef.signature.input_arg)} `input_arg`s.\")\n\n # 1. Create placeholders for input nodes.\n for i, arg_def in enumerate(fdef.signature.input_arg):\n node_def = graph_def.node.add()\n node_def.name = arg_def.name\n node_def.op = \"Placeholder\"\n node_def.attr[\"dtype\"].type = arg_def.type\n if input_shapes and input_shapes[i] is not None:\n input_shape = input_shapes[i]\n if not isinstance(input_shape, tensor_shape_pb2.TensorShapeProto):\n input_shape = input_shape.as_proto()\n node_def.attr[\"shape\"].shape.CopyFrom(input_shape)\n arg_attrs = fdef.arg_attr[i].attr\n for k in arg_attrs:\n # Only copy internal attributes. Normal attributes for nodes cannot be\n # applied to these Placeholder nodes.\n if k == \"_output_shapes\":\n if arg_attrs[k].WhichOneof(\"value\") == \"list\":\n node_def.attr[\"shape\"].shape.CopyFrom(arg_attrs[k].list.shape[0])\n elif arg_attrs[k].WhichOneof(\"value\") == \"shape\":\n node_def.attr[\"shape\"].shape.CopyFrom(arg_attrs[k].shape)\n elif k.startswith(\"_\"):\n node_def.attr[k].CopyFrom(arg_attrs[k])\n\n # 2. Copy all body NodeDefs to the GraphDef.\n graph_def.node.extend(fdef.node_def)\n\n # 3. Perform the renaming.\n\n # Build the tensor name mapping then flatten the tensor names.\n # See comment on `FunctionDef.node_def` on how the tensor naming in\n # FunctionDefs is different from GraphDefs.\n nested_to_flat_tensor_name = {}\n\n for arg_def in fdef.signature.input_arg:\n nested_to_flat_tensor_name[arg_def.name] = \"{}:0\".format(arg_def.name)\n control_name = \"^\" + arg_def.name\n nested_to_flat_tensor_name[control_name] = control_name\n\n for node_def in fdef.node_def:\n graph = default_graph\n while True:\n f = graph._functions.get(node_def.op, None) # pylint: disable=protected-access\n if f is not None or not hasattr(graph, \"outer_graph\"):\n break\n graph = graph.outer_graph\n\n if f is not None:\n op_def = f.definition.signature\n if node_def.op not in copied_functions:\n # Since this function is referenced as an op type, we have no choice but\n # to copy it into the GraphDef if we want downstream tools to process\n # it.\n graph_def.library.function.add().CopyFrom(f.definition)\n copied_functions.add(node_def.op)\n if f.grad_func_name:\n grad_def = function_pb2.GradientDef()\n grad_def.function_name = f.name\n grad_def.gradient_func = f.grad_func_name\n graph_def.library.gradient.extend([grad_def])\n else:\n op_def = default_graph._get_op_def(node_def.op) # pylint: disable=protected-access\n\n for attr in op_def.attr:\n if attr.type == \"func\":\n fname = node_def.attr[attr.name].func.name\n if not is_function(fname):\n raise ValueError(f\"Function {fname} was not found. Please make sure \"\n \"the FunctionDef `fdef` is correct.\")\n elif attr.type == \"list(func)\":\n for fn in node_def.attr[attr.name].list.func:\n fname = fn.name\n if not is_function(fname):\n raise ValueError(f\"Function {fname} was not found. Please make \"\n \"sure the FunctionDef `fdef` is correct.\")\n\n # Iterate over output_args in op_def to build the map.\n # Index of the output tensor in the flattened list of *all* output\n # tensors of the op.\n flattened_index = 0\n for arg_def in op_def.output_arg:\n num_args = _get_num_args(arg_def, node_def)\n for i in range(num_args):\n # Map tensor names from \"node_name:output_arg_name:index\" to\n # \"node_name:flattened_index\".\n nested_name = \"{}:{}:{}\".format(node_def.name, arg_def.name, i)\n flat_name = \"{}:{}\".format(node_def.name, flattened_index)\n nested_to_flat_tensor_name[nested_name] = flat_name\n flattened_index += 1\n control_name = \"^\" + node_def.name\n nested_to_flat_tensor_name[control_name] = control_name\n\n # Update inputs of all nodes in graph.\n for node_def in graph_def.node:\n for i in range(len(node_def.input)):\n node_def.input[i] = nested_to_flat_tensor_name[node_def.input[i]]\n\n return graph_def, nested_to_flat_tensor_name\n\n\n# Based on implementation in core/framework/node_def_util.cc::ComputeArgRange.\ndef _get_num_args(arg_def, node_def):\n if arg_def.number_attr:\n return node_def.attr[arg_def.number_attr].i\n elif arg_def.type_list_attr:\n return len(node_def.attr[arg_def.type_list_attr].list.type)\n elif arg_def.type_attr or arg_def.type != types_pb2.DT_INVALID:\n return 1\n else:\n raise ValueError(f\"Invalid arg_def:\\n\\n{arg_def}. Please make sure the \"\n \"FunctionDef `fdef` is correct.\")\n\n\ndef _set_handle_data(func_graph, fdef):\n \"\"\"Adds handle data for resource type inputs and outputs.\"\"\"\n for tensor, arg_def in itertools.chain(\n zip(func_graph.inputs, fdef.signature.input_arg),\n zip(func_graph.outputs, fdef.signature.output_arg)):\n if arg_def.handle_data:\n shape_and_dtype = arg_def.handle_data[0]\n handle_data = cpp_shape_inference_pb2.CppShapeInferenceResult.HandleData()\n handle_data.is_set = True\n handle_data.shape_and_type.append(\n cpp_shape_inference_pb2.CppShapeInferenceResult.HandleShapeAndType(\n shape=shape_and_dtype.shape, dtype=shape_and_dtype.dtype))\n resource_variable_ops._set_handle_shapes_and_types( # pylint: disable=protected-access\n tensor, handle_data, True)\n" ]
[ [ "tensorflow.core.framework.function_pb2.GradientDef", "tensorflow.core.framework.versions_pb2.VersionDef", "tensorflow.python.framework.importer.import_graph_def_for_function", "tensorflow.python.framework.ops.get_default_graph", "tensorflow.python.framework.cpp_shape_inference_pb2.CppShapeInferenceResult.HandleData", "tensorflow.python.eager.context.context", "tensorflow.python.ops.resource_variable_ops._set_handle_shapes_and_types", "tensorflow.python.framework.cpp_shape_inference_pb2.CppShapeInferenceResult.HandleShapeAndType", "tensorflow.python.eager.context.executing_eagerly", "tensorflow.python.framework.func_graph.FuncGraph", "tensorflow.core.framework.graph_pb2.GraphDef" ] ]
KosingZhu/tensorflow
[ "60028072a1c3b4376e145b6fea8e4ccd3324377f" ]
[ "tensorflow/python/kernel_tests/array_ops/denormal_test.py" ]
[ "# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for denormal handling.\"\"\"\n\nimport numpy as np\nimport platform\n\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.platform import test\n\n\nclass DenormalTest(test.TestCase):\n\n def testPythonHasDenormals(self):\n \"\"\"Non-tf numpy code should treat denormals correctly.\"\"\"\n for dtype in np.float32, np.float64:\n tiny = np.finfo(dtype).tiny\n self.assertEqual(tiny, tiny / 16 * 16)\n\n def _flushDenormalsTest(self, dtypes):\n if (platform.machine() == \"ppc64le\" or platform.machine() == \"s390x\" or\n platform.machine() == \"aarch64\"):\n # Disabled denormal_test on power/s390x/aarch64 platform\n # Check relevant discussion - https://github.com/tensorflow/tensorflow/issues/11902\n return\n for dtype in dtypes:\n tiny = np.finfo(dtype).tiny\n # Small shape to test main thread, large shape to test thread pool\n for shape in (), (1 << 20,):\n flush = 0.1 * constant_op.constant(tiny, shape=shape)\n self.assertAllEqual(self.evaluate(flush), np.zeros(shape))\n # Make sure the flags don't leak out\n self.testPythonHasDenormals()\n\n @test_util.run_in_graph_and_eager_modes(use_gpu=False)\n def testFlushDenormalsCPU(self):\n # On CPUs, the processor flags flush for both single and double precision.\n self._flushDenormalsTest(dtypes=(np.float32, np.float64))\n\n @test_util.run_in_graph_and_eager_modes(use_gpu=True)\n def testFlushDenormalsGPU(self):\n # On GPUs, only single precision can flush to zero.\n self._flushDenormalsTest(dtypes=(np.float32,))\n\n\nif __name__ == \"__main__\":\n test.main()\n" ]
[ [ "numpy.zeros", "tensorflow.python.framework.test_util.run_in_graph_and_eager_modes", "tensorflow.python.platform.test.main", "numpy.finfo", "tensorflow.python.framework.constant_op.constant" ] ]
UCL/xclim
[ "118441f89d221cfffbd2e1fd0b966517e731378d" ]
[ "xclim/indices/_conversion.py" ]
[ "# noqa: D100\nfrom typing import Optional, Tuple\n\nimport numpy as np\nimport xarray as xr\n\nfrom xclim.core.calendar import date_range, datetime_to_decimal_year\nfrom xclim.core.units import amount2rate, convert_units_to, declare_units, units2pint\n\n__all__ = [\n \"humidex\",\n \"tas\",\n \"uas_vas_2_sfcwind\",\n \"sfcwind_2_uas_vas\",\n \"saturation_vapor_pressure\",\n \"relative_humidity\",\n \"specific_humidity\",\n \"snowfall_approximation\",\n \"rain_approximation\",\n \"wind_chill_index\",\n \"clausius_clapeyron_scaled_precipitation\",\n \"potential_evapotranspiration\",\n]\n\n\n@declare_units(tas=\"[temperature]\", tdps=\"[temperature]\", hurs=\"[]\")\ndef humidex(\n tas: xr.DataArray,\n tdps: Optional[xr.DataArray] = None,\n hurs: Optional[xr.DataArray] = None,\n) -> xr.DataArray:\n r\"\"\"Humidex index.\n\n The humidex indicates how hot the air feels to an average person, accounting for the effect of humidity. It\n can be loosely interpreted as the equivalent perceived temperature when the air is dry.\n\n Parameters\n ----------\n tas : xarray.DataArray\n Air temperature.\n tdps : xarray.DataArray,\n Dewpoint temperature.\n hurs : xarray.DataArray\n Relative humidity.\n\n Returns\n -------\n xarray.DataArray, [temperature]\n The humidex index.\n\n Notes\n -----\n The humidex is usually computed using hourly observations of dry bulb and dewpoint temperatures. It is computed\n using the formula based on [masterton79]_:\n\n .. math::\n\n T + {\\frac {5}{9}}\\left[e - 10\\right]\n\n where :math:`T` is the dry bulb air temperature (°C). The term :math:`e` can be computed from the dewpoint\n temperature :math:`T_{dewpoint}` in °K:\n\n .. math::\n\n e = 6.112 \\times \\exp(5417.7530\\left({\\frac {1}{273.16}}-{\\frac {1}{T_{\\text{dewpoint}}}}\\right)\n\n where the constant 5417.753 reflects the molecular weight of water, latent heat of vaporization,\n and the universal gas constant ([mekis15]_). Alternatively, the term :math:`e` can also be computed from\n the relative humidity `h` expressed in percent using [sirangelo20]_:\n\n .. math::\n\n e = \\frac{h}{100} \\times 6.112 * 10^{7.5 T/(T + 237.7)}.\n\n The humidex *comfort scale* ([eccc]_) can be interpreted as follows:\n\n - 20 to 29 : no discomfort;\n - 30 to 39 : some discomfort;\n - 40 to 45 : great discomfort, avoid exertion;\n - 46 and over : dangerous, possible heat stroke;\n\n References\n ----------\n .. [masterton79] Masterton, J. M., & Richardson, F. A. (1979). HUMIDEX, A method of quantifying human discomfort due to excessive heat and humidity, CLI 1-79. Downsview, Ontario: Environment Canada, Atmospheric Environment Service.\n .. [mekis15] Éva Mekis, Lucie A. Vincent, Mark W. Shephard & Xuebin Zhang (2015) Observed Trends in Severe Weather Conditions Based on Humidex, Wind Chill, and Heavy Rainfall Events in Canada for 1953–2012, Atmosphere-Ocean, 53:4, 383-397, DOI: 10.1080/07055900.2015.1086970\n .. [sirangelo20] Sirangelo, B., Caloiero, T., Coscarelli, R. et al. Combining stochastic models of air temperature and vapour pressure for the analysis of the bioclimatic comfort through the Humidex. Sci Rep 10, 11395 (2020). https://doi.org/10.1038/s41598-020-68297-4\n .. [eccc] https://climate.weather.gc.ca/glossary_e.html\n \"\"\"\n if (tdps is None) == (hurs is None):\n raise ValueError(\n \"At least one of `tdps` or `hurs` must be given, and not both.\"\n )\n\n # Vapour pressure in hPa\n if tdps is not None:\n # Convert dewpoint temperature to Kelvins\n tdps = convert_units_to(tdps, \"kelvin\")\n e = 6.112 * np.exp(5417.7530 * (1 / 273.16 - 1.0 / tdps))\n\n elif hurs is not None:\n # Convert dry bulb temperature to Celsius\n tasC = convert_units_to(tas, \"celsius\")\n e = hurs / 100 * 6.112 * 10 ** (7.5 * tasC / (tasC + 237.7))\n\n # Temperature delta due to humidity in delta_degC\n h = 5 / 9 * (e - 10)\n h.attrs[\"units\"] = \"delta_degree_Celsius\"\n\n # Get delta_units for output\n du = (1 * units2pint(tas) - 0 * units2pint(tas)).units\n h = convert_units_to(h, du)\n\n # Add the delta to the input temperature\n out = h + tas\n out.attrs[\"units\"] = tas.units\n return out\n\n\n@declare_units(tasmin=\"[temperature]\", tasmax=\"[temperature]\")\ndef tas(tasmin: xr.DataArray, tasmax: xr.DataArray) -> xr.DataArray:\n \"\"\"Average temperature from minimum and maximum temperatures.\n\n We assume a symmetrical distribution for the temperature and retrieve the average value as Tg = (Tx + Tn) / 2\n\n Parameters\n ----------\n tasmin : xarray.DataArray\n Minimum (daily) temperature\n tasmax : xarray.DataArray\n Maximum (daily) temperature\n\n Returns\n -------\n xarray.DataArray\n Mean (daily) temperature [same units as tasmin]\n \"\"\"\n tasmax = convert_units_to(tasmax, tasmin)\n tas = (tasmax + tasmin) / 2\n tas.attrs[\"units\"] = tasmin.attrs[\"units\"]\n return tas\n\n\n@declare_units(uas=\"[speed]\", vas=\"[speed]\", calm_wind_thresh=\"[speed]\")\ndef uas_vas_2_sfcwind(\n uas: xr.DataArray, vas: xr.DataArray, calm_wind_thresh: str = \"0.5 m/s\"\n) -> Tuple[xr.DataArray, xr.DataArray]:\n \"\"\"Wind speed and direction from the eastward and northward wind components.\n\n Computes the magnitude and angle of the wind vector from its northward and eastward components,\n following the meteorological convention that sets calm wind to a direction of 0° and northerly wind to 360°.\n\n Parameters\n ----------\n uas : xr.DataArray\n Eastward wind velocity\n vas : xr.DataArray\n Northward wind velocity\n calm_wind_thresh : str\n The threshold under which winds are considered \"calm\" and for which the direction\n is set to 0. On the Beaufort scale, calm winds are defined as < 0.5 m/s.\n\n Returns\n -------\n wind : xr.DataArray, [m s-1]\n Wind velocity\n wind_from_dir : xr.DataArray, [°]\n Direction from which the wind blows, following the meteorological convention where\n 360 stands for North and 0 for calm winds.\n\n Notes\n -----\n Winds with a velocity less than `calm_wind_thresh` are given a wind direction of 0°,\n while stronger northerly winds are set to 360°.\n \"\"\"\n # Converts the wind speed to m s-1\n uas = convert_units_to(uas, \"m/s\")\n vas = convert_units_to(vas, \"m/s\")\n wind_thresh = convert_units_to(calm_wind_thresh, \"m/s\")\n\n # Wind speed is the hypotenuse of \"uas\" and \"vas\"\n wind = np.hypot(uas, vas)\n wind.attrs[\"units\"] = \"m s-1\"\n\n # Calculate the angle\n wind_from_dir_math = np.degrees(np.arctan2(vas, uas))\n\n # Convert the angle from the mathematical standard to the meteorological standard\n wind_from_dir = (270 - wind_from_dir_math) % 360.0\n\n # According to the meteorological standard, calm winds must have a direction of 0°\n # while northerly winds have a direction of 360°\n # On the Beaufort scale, calm winds are defined as < 0.5 m/s\n wind_from_dir = xr.where(wind_from_dir.round() == 0, 360, wind_from_dir)\n wind_from_dir = xr.where(wind < wind_thresh, 0, wind_from_dir)\n wind_from_dir.attrs[\"units\"] = \"degree\"\n return wind, wind_from_dir\n\n\n@declare_units(sfcWind=\"[speed]\", sfcWindfromdir=\"[]\")\ndef sfcwind_2_uas_vas(\n sfcWind: xr.DataArray, sfcWindfromdir: xr.DataArray # noqa\n) -> Tuple[xr.DataArray, xr.DataArray]:\n \"\"\"Eastward and northward wind components from the wind speed and direction.\n\n Compute the eastward and northward wind components from the wind speed and direction.\n\n Parameters\n ----------\n sfcWind : xr.DataArray\n Wind velocity\n sfcWindfromdir : xr.DataArray\n Direction from which the wind blows, following the meteorological convention\n where 360 stands for North.\n\n Returns\n -------\n uas : xr.DataArray, [m s-1]\n Eastward wind velocity.\n vas : xr.DataArray, [m s-1]\n Northward wind velocity.\n\n \"\"\"\n # Converts the wind speed to m s-1\n sfcWind = convert_units_to(sfcWind, \"m/s\") # noqa\n\n # Converts the wind direction from the meteorological standard to the mathematical standard\n wind_from_dir_math = (-sfcWindfromdir + 270) % 360.0\n\n # TODO: This commented part should allow us to resample subdaily wind, but needs to be cleaned up and put elsewhere.\n # if resample is not None:\n # wind = wind.resample(time=resample).mean(dim='time', keep_attrs=True)\n #\n # # nb_per_day is the number of values each day. This should be calculated\n # wind_from_dir_math_per_day = wind_from_dir_math.reshape((len(wind.time), nb_per_day))\n # # Averages the subdaily angles around a circle, i.e. mean([0, 360]) = 0, not 180\n # wind_from_dir_math = np.concatenate([[degrees(phase(sum(rect(1, radians(d)) for d in angles) / len(angles)))]\n # for angles in wind_from_dir_math_per_day])\n\n uas = sfcWind * np.cos(np.radians(wind_from_dir_math))\n vas = sfcWind * np.sin(np.radians(wind_from_dir_math))\n uas.attrs[\"units\"] = \"m s-1\"\n vas.attrs[\"units\"] = \"m s-1\"\n return uas, vas\n\n\n@declare_units(tas=\"[temperature]\", ice_thresh=\"[temperature]\")\ndef saturation_vapor_pressure(\n tas: xr.DataArray, ice_thresh: str = None, method: str = \"sonntag90\" # noqa\n) -> xr.DataArray:\n \"\"\"Saturation vapor pressure from temperature.\n\n Parameters\n ----------\n tas : xr.DataArray\n Temperature array.\n ice_thresh : str\n Threshold temperature under which to switch to equations in reference to ice instead of water.\n If None (default) everything is computed with reference to water.\n method : {\"dewpoint\", \"goffgratch46\", \"sonntag90\", \"tetens30\", \"wmo08\"}\n Which method to use, see notes.\n\n Returns\n -------\n xarray.DataArray, [Pa]\n Saturation vapor pressure.\n\n Notes\n -----\n In all cases implemented here :math:`log(e_{sat})` is an empirically fitted function (usually a polynomial)\n where coefficients can be different when ice is taken as reference instead of water. Available methods are:\n\n - \"goffgratch46\" or \"GG46\", based on [goffgratch46]_, values and equation taken from [voemel]_.\n - \"sonntag90\" or \"SO90\", taken from [sonntag90]_.\n - \"tetens30\" or \"TE30\", based on [tetens30]_, values and equation taken from [voemel]_.\n - \"wmo08\" or \"WMO08\", taken from [wmo08]_.\n\n References\n ----------\n .. [goffgratch46] Goff, J. A., and S. Gratch (1946) Low-pressure properties of water from -160 to 212 °F, in Transactions of the American Society of Heating and Ventilating Engineers, pp 95-122, presented at the 52nd annual meeting of the American Society of Heating and Ventilating Engineers, New York, 1946.\n .. [sonntag90] Sonntag, D. (1990). Important new values of the physical constants of 1986, vapour pressure formulations based on the ITS-90, and psychrometer formulae. Zeitschrift für Meteorologie, 40(5), 340-344.\n .. [tetens30] Tetens, O. 1930. Über einige meteorologische Begriffe. Z. Geophys 6: 207-309.\n .. [voemel] https://cires1.colorado.edu/~voemel/vp.html\n .. [wmo08] World Meteorological Organization. (2008). Guide to meteorological instruments and methods of observation. Geneva, Switzerland: World Meteorological Organization. https://www.weather.gov/media/epz/mesonet/CWOP-WMO8.pdf\n \"\"\"\n if ice_thresh is not None:\n thresh = convert_units_to(ice_thresh, \"degK\")\n else:\n thresh = convert_units_to(\"0 K\", \"degK\")\n ref_is_water = tas > thresh\n\n if method in [\"sonntag90\", \"SO90\"]:\n e_sat = xr.where(\n ref_is_water,\n 100\n * np.exp( # Where ref_is_water is True, x100 is to convert hPa to Pa\n -6096.9385 / tas # type: ignore\n + 16.635794\n + -2.711193e-2 * tas # type: ignore\n + 1.673952e-5 * tas ** 2\n + 2.433502 * np.log(tas) # numpy's log is ln\n ),\n 100\n * np.exp( # Where ref_is_water is False (thus ref is ice)\n -6024.5282 / tas # type: ignore\n + 24.7219\n + 1.0613868e-2 * tas # type: ignore\n + -1.3198825e-5 * tas ** 2\n + -0.49382577 * np.log(tas)\n ),\n )\n elif method in [\"tetens30\", \"TE30\"]:\n e_sat = xr.where(\n ref_is_water,\n 610.78 * np.exp(17.269388 * (tas - 273.16) / (tas - 35.86)),\n 610.78 * np.exp(21.8745584 * (tas - 273.16) / (tas - 7.66)),\n )\n elif method in [\"goffgratch46\", \"GG46\"]:\n Tb = 373.16 # Water boiling temp [K]\n eb = 101325 # e_sat at Tb [Pa]\n Tp = 273.16 # Triple-point temperature [K]\n ep = 611.73 # e_sat at Tp [Pa]\n e_sat = xr.where(\n ref_is_water,\n eb\n * 10\n ** (\n -7.90298 * ((Tb / tas) - 1) # type: ignore\n + 5.02808 * np.log10(Tb / tas) # type: ignore\n + -1.3817e-7 * (10 ** (11.344 * (1 - tas / Tb)) - 1)\n + 8.1328e-3 * (10 ** (-3.49149 * ((Tb / tas) - 1)) - 1) # type: ignore\n ),\n ep\n * 10\n ** (\n -9.09718 * ((Tp / tas) - 1) # type: ignore\n + -3.56654 * np.log10(Tp / tas) # type: ignore\n + 0.876793 * (1 - tas / Tp)\n ),\n )\n elif method in [\"wmo08\", \"WMO08\"]:\n e_sat = xr.where(\n ref_is_water,\n 611.2 * np.exp(17.62 * (tas - 273.16) / (tas - 30.04)),\n 611.2 * np.exp(22.46 * (tas - 273.16) / (tas - 0.54)),\n )\n else:\n raise ValueError(\n f\"Method {method} is not in ['sonntag90', 'tetens30', 'goffgratch46', 'wmo08']\"\n )\n\n e_sat.attrs[\"units\"] = \"Pa\"\n return e_sat\n\n\n@declare_units(\n tas=\"[temperature]\",\n tdps=\"[temperature]\",\n huss=\"[]\",\n ps=\"[pressure]\",\n ice_thresh=\"[temperature]\",\n)\ndef relative_humidity(\n tas: xr.DataArray,\n tdps: xr.DataArray = None,\n huss: xr.DataArray = None,\n ps: xr.DataArray = None,\n ice_thresh: str = None,\n method: str = \"sonntag90\",\n invalid_values: str = \"clip\",\n) -> xr.DataArray:\n r\"\"\"Relative humidity.\n\n Compute relative humidity from temperature and either dewpoint temperature or specific humidity and pressure through\n the saturation vapor pressure.\n\n Parameters\n ----------\n tas : xr.DataArray\n Temperature array\n tdps : xr.DataArray\n Dewpoint temperature, if specified, overrides huss and ps.\n huss : xr.DataArray\n Specific humidity.\n ps : xr.DataArray\n Air Pressure.\n ice_thresh : str\n Threshold temperature under which to switch to equations in reference to ice instead of water.\n If None (default) everything is computed with reference to water. Does nothing if 'method' is \"bohren98\".\n method : {\"bohren98\", \"goffgratch46\", \"sonntag90\", \"tetens30\", \"wmo08\"}\n Which method to use, see notes of this function and of `saturation_vapor_pressure`.\n invalid_values : {\"clip\", \"mask\", None}\n What to do with values outside the 0-100 range. If \"clip\" (default), clips everything to 0 - 100,\n if \"mask\", replaces values outside the range by np.nan, and if `None`, does nothing.\n\n Returns\n -------\n xr.DataArray, [%]\n Relative humidity.\n\n Notes\n -----\n In the following, let :math:`T`, :math:`T_d`, :math:`q` and :math:`p` be the temperature,\n the dew point temperature, the specific humidity and the air pressure.\n\n **For the \"bohren98\" method** : This method does not use the saturation vapor pressure directly,\n but rather uses an approximation of the ratio of :math:`\\frac{e_{sat}(T_d)}{e_{sat}(T)}`.\n With :math:`L` the enthalpy of vaporization of water and :math:`R_w` the gas constant for water vapor,\n the relative humidity is computed as:\n\n .. math::\n\n RH = e^{\\frac{-L (T - T_d)}{R_wTT_d}}\n\n From [BohrenAlbrecht1998]_, formula taken from [Lawrence2005]_. :math:`L = 2.5\\times 10^{-6}` J kg-1, exact for :math:`T = 273.15` K, is used.\n\n **Other methods**: With :math:`w`, :math:`w_{sat}`, :math:`e_{sat}` the mixing ratio,\n the saturation mixing ratio and the saturation vapor pressure.\n If the dewpoint temperature is given, relative humidity is computed as:\n\n .. math::\n\n RH = 100\\frac{e_{sat}(T_d)}{e_{sat}(T)}\n\n Otherwise, the specific humidity and the air pressure must be given so relative humidity can be computed as:\n\n .. math::\n\n RH = 100\\frac{w}{w_{sat}}\n w = \\frac{q}{1-q}\n w_{sat} = 0.622\\frac{e_{sat}}{P - e_{sat}}\n\n The methods differ by how :math:`e_{sat}` is computed. See the doc of :py:meth:`xclim.core.utils.saturation_vapor_pressure`.\n\n References\n ----------\n .. [Lawrence2005] Lawrence, M.G. (2005). The Relationship between Relative Humidity and the Dewpoint Temperature in Moist Air: A Simple Conversion and Applications. Bull. Amer. Meteor. Soc., 86, 225–234, https://doi.org/10.1175/BAMS-86-2-225\n .. [BohrenAlbrecht1998] Craig F. Bohren, Bruce A. Albrecht. Atmospheric Thermodynamics. Oxford University Press, 1998.\n \"\"\"\n if method in (\"bohren98\", \"BA90\"):\n if tdps is None:\n raise ValueError(\"To use method 'bohren98' (BA98), dewpoint must be given.\")\n tdps = convert_units_to(tdps, \"degK\")\n tas = convert_units_to(tas, \"degK\")\n L = 2.501e6\n Rw = (461.5,)\n hurs = 100 * np.exp(-L * (tas - tdps) / (Rw * tas * tdps)) # type: ignore\n elif tdps is not None:\n e_sat_dt = saturation_vapor_pressure(\n tas=tdps, ice_thresh=ice_thresh, method=method\n )\n e_sat_t = saturation_vapor_pressure(\n tas=tas, ice_thresh=ice_thresh, method=method\n )\n hurs = 100 * e_sat_dt / e_sat_t # type: ignore\n else:\n ps = convert_units_to(ps, \"Pa\")\n huss = convert_units_to(huss, \"\")\n tas = convert_units_to(tas, \"degK\")\n\n e_sat = saturation_vapor_pressure(tas=tas, ice_thresh=ice_thresh, method=method)\n\n w = huss / (1 - huss)\n w_sat = 0.62198 * e_sat / (ps - e_sat) # type: ignore\n hurs = 100 * w / w_sat\n\n if invalid_values == \"clip\":\n hurs = hurs.clip(0, 100)\n elif invalid_values == \"mask\":\n hurs = hurs.where((hurs <= 100) & (hurs >= 0))\n hurs.attrs[\"units\"] = \"%\"\n return hurs\n\n\n@declare_units(\n tas=\"[temperature]\",\n hurs=\"[]\",\n ps=\"[pressure]\",\n ice_thresh=\"[temperature]\",\n)\ndef specific_humidity(\n tas: xr.DataArray,\n hurs: xr.DataArray,\n ps: xr.DataArray,\n ice_thresh: str = None,\n method: str = \"sonntag90\",\n invalid_values: str = None,\n) -> xr.DataArray:\n r\"\"\"Specific humidity from temperature, relative humidity and pressure.\n\n Parameters\n ----------\n tas : xr.DataArray\n Temperature array\n hurs : xr.DataArray\n Relative Humidity.\n ps : xr.DataArray\n Air Pressure.\n ice_thresh : str\n Threshold temperature under which to switch to equations in reference to ice instead of water.\n If None (default) everything is computed with reference to water.\n method : {\"goffgratch46\", \"sonntag90\", \"tetens30\", \"wmo08\"}\n Which method to use, see notes of this function and of `saturation_vapor_pressure`.\n invalid_values : {\"clip\", \"mask\", None}\n What to do with values larger than the saturation specific humidity and lower than 0.\n If \"clip\" (default), clips everything to 0 - q_sat\n if \"mask\", replaces values outside the range by np.nan,\n if None, does nothing.\n\n Returns\n -------\n xarray.DataArray, [dimensionless]\n Specific humidity.\n\n Notes\n -----\n In the following, let :math:`T`, :math:`hurs` (in %) and :math:`p` be the temperature,\n the relative humidity and the air pressure. With :math:`w`, :math:`w_{sat}`, :math:`e_{sat}` the mixing ratio,\n the saturation mixing ratio and the saturation vapor pressure, specific humidity :math:`q` is computed as:\n\n .. math::\n\n w_{sat} = 0.622\\frac{e_{sat}}{P - e_{sat}}\n w = w_{sat} * hurs / 100\n q = w / (1 + w)\n\n The methods differ by how :math:`e_{sat}` is computed. See the doc of `xclim.core.utils.saturation_vapor_pressure`.\n\n If `invalid_values` is not `None`, the saturation specific humidity :math:`q_{sat}` is computed as:\n\n .. math::\n\n q_{sat} = w_{sat} / (1 + w_{sat})\n \"\"\"\n ps = convert_units_to(ps, \"Pa\")\n hurs = convert_units_to(hurs, \"\")\n tas = convert_units_to(tas, \"degK\")\n\n e_sat = saturation_vapor_pressure(tas=tas, ice_thresh=ice_thresh, method=method)\n\n w_sat = 0.62198 * e_sat / (ps - e_sat) # type: ignore\n w = w_sat * hurs\n q = w / (1 + w)\n\n if invalid_values is not None:\n q_sat = w_sat / (1 + w_sat)\n if invalid_values == \"clip\":\n q = q.clip(0, q_sat)\n elif invalid_values == \"mask\":\n q = q.where((q <= q_sat) & (q >= 0))\n q.attrs[\"units\"] = \"\"\n return q\n\n\n@declare_units(pr=\"[precipitation]\", tas=\"[temperature]\", thresh=\"[temperature]\")\ndef snowfall_approximation(\n pr: xr.DataArray,\n tas: xr.DataArray,\n thresh: str = \"0 degC\",\n method: str = \"binary\",\n) -> xr.DataArray:\n \"\"\"Snowfall approximation from total precipitation and temperature.\n\n Solid precipitation estimated from precipitation and temperature according to a given method.\n\n Parameters\n ----------\n pr : xarray.DataArray\n Mean daily precipitation flux.\n tas : xarray.DataArray, optional\n Mean, maximum, or minimum daily temperature.\n thresh : str,\n Threshold temperature, used by method \"binary\".\n method : {\"binary\", \"brown\", \"auer\"}\n Which method to use when approximating snowfall from total precipitation. See notes.\n\n Returns\n -------\n xarray.DataArray, [same units as pr]\n Solid precipitation flux.\n\n Notes\n -----\n The following methods are available to approximate snowfall and are drawn from the\n Canadian Land Surface Scheme (CLASS, [Verseghy09]_).\n\n - ``'binary'`` : When the temperature is under the freezing threshold, precipitation\n is assumed to be solid. The method is agnostic to the type of temperature used\n (mean, maximum or minimum).\n - ``'brown'`` : The phase between the freezing threshold goes from solid to liquid linearly\n over a range of 2°C over the freezing point.\n - ``'auer'`` : The phase between the freezing threshold goes from solid to liquid as a degree six\n polynomial over a range of 6°C over the freezing point.\n\n References\n ----------\n .. [Verseghy09] Diana Verseghy (2009), CLASS – The Canadian Land Surface Scheme (Version 3.4), Technical\n Documentation (Version 1.1), Environment Canada, Climate Research Division, Science and Technology Branch.\n https://gitlab.com/cccma/classic/-/blob/master/src/atmosphericVarsCalc.f90\n \"\"\"\n\n if method == \"binary\":\n thresh = convert_units_to(thresh, tas)\n prsn = pr.where(tas <= thresh, 0)\n\n elif method == \"brown\":\n # Freezing point + 2C in the native units\n upper = convert_units_to(convert_units_to(thresh, \"degC\") + 2, tas)\n thresh = convert_units_to(thresh, tas)\n\n # Interpolate fraction over temperature (in units of tas)\n t = xr.DataArray(\n [-np.inf, thresh, upper, np.inf], dims=(\"tas\",), attrs={\"units\": \"degC\"}\n )\n fraction = xr.DataArray([1.0, 1.0, 0.0, 0.0], dims=(\"tas\",), coords={\"tas\": t})\n\n # Multiply precip by snowfall fraction\n prsn = pr * fraction.interp(tas=tas, method=\"linear\")\n\n elif method == \"auer\":\n dtas = convert_units_to(tas, \"degK\") - convert_units_to(thresh, \"degK\")\n\n # Create nodes for the snowfall fraction: -inf, thresh, ..., thresh+6, inf [degC]\n t = np.concatenate(\n [[-273.15], np.linspace(0, 6, 100, endpoint=False), [6, 1e10]]\n )\n t = xr.DataArray(t, dims=\"tas\", name=\"tas\", coords={\"tas\": t})\n\n # The polynomial coefficients, valid between thresh and thresh + 6 (defined in CLASS)\n coeffs = xr.DataArray(\n [100, 4.6664, -15.038, -1.5089, 2.0399, -0.366, 0.0202],\n dims=(\"degree\",),\n coords={\"degree\": range(7)},\n )\n\n fraction = xr.polyval(t.tas, coeffs).clip(0, 100) / 100\n fraction[0] = 1\n fraction[-2:] = 0\n\n # Convert snowfall fraction coordinates to native tas units\n prsn = pr * fraction.interp(tas=dtas, method=\"linear\")\n\n else:\n raise ValueError(f\"Method {method} not one of 'binary', 'brown' or 'auer'.\")\n\n prsn.attrs[\"units\"] = pr.attrs[\"units\"]\n return prsn\n\n\n@declare_units(pr=\"[precipitation]\", tas=\"[temperature]\", thresh=\"[temperature]\")\ndef rain_approximation(\n pr: xr.DataArray,\n tas: xr.DataArray,\n thresh: str = \"0 degC\",\n method: str = \"binary\",\n) -> xr.DataArray:\n \"\"\"Rainfall approximation from total precipitation and temperature.\n\n Liquid precipitation estimated from precipitation and temperature according to a given method.\n This is a convenience method based on :py:func:`snowfall_approximation`, see the latter for details.\n\n Parameters\n ----------\n pr : xarray.DataArray\n Mean daily precipitation flux.\n tas : xarray.DataArray, optional\n Mean, maximum, or minimum daily temperature.\n thresh : str,\n Threshold temperature, used by method \"binary\".\n method : {\"binary\", \"brown\", \"auer\"}\n Which method to use when approximating snowfall from total precipitation. See notes.\n\n Returns\n -------\n xarray.DataArray, [same units as pr]\n Liquid precipitation rate.\n\n Notes\n -----\n This method computes the snowfall approximation and subtracts it from the total\n precipitation to estimate the liquid rain precipitation.\n\n See also\n --------\n snowfall_approximation\n \"\"\"\n prra = pr - snowfall_approximation(pr, tas, thresh=thresh, method=method)\n prra.attrs[\"units\"] = pr.attrs[\"units\"]\n return prra\n\n\n@declare_units(\n tas=\"[temperature]\",\n sfcWind=\"[speed]\",\n)\ndef wind_chill_index(\n tas: xr.DataArray,\n sfcWind: xr.DataArray,\n method: str = \"CAN\",\n mask_invalid: bool = True,\n):\n r\"\"\"Wind chill index.\n\n The Wind Chill Index is an estimation of how cold the weather feels to the average person.\n It is computed from the air temperature and the 10-m wind. As defined by the Environment and Climate Change Canada ([MVSZ15]_),\n two equations exist, the conventional one and one for slow winds (usually < 5 km/h), see Notes.\n\n Parameters\n ----------\n tas : xarray.DataArray\n Surface air temperature.\n sfcWind : xarray.DataArray\n Surface wind speed (10 m).\n method : {'CAN', 'US'}\n If \"CAN\" (default), a \"slow wind\" equation is used where winds are slower than 5 km/h, see Notes.\n mask_invalid : bool\n Whether to mask values when the inputs are outside their validity range. or not.\n If True (default), points where the temperature is above a threshold are masked.\n The threshold is 0°C for the canadian method and 50°F for the american one.\n With the latter method, points where sfcWind < 3 mph are also masked.\n\n Returns\n -------\n xarray.DataArray, [degC]\n Wind Chill Index.\n\n Notes\n -----\n Following the calculations of Environment and Climate Change Canada, this function switches from the standardized index\n to another one for slow winds. The standard index is the same as used by the National Weather Service of the USA. Given\n a temperature at surface :math:`T` (in °C) and 10-m wind speed :math:`V` (in km/h), the Wind Chill Index :math:`W` (dimensionless)\n is computed as:\n\n .. math::\n\n W = 13.12 + 0.6125*T - 11.37*V^0.16 + 0.3965*T*V^0.16\n\n Under slow winds (:math:`V < 5` km/h), and using the canadian method, it becomes:\n\n .. math::\n\n W = T + \\frac{-1.59 + 0.1345 * T}{5} * V\n\n\n Both equations are invalid for temperature over 0°C in the canadian method.\n\n The american Wind Chill Temperature index (WCT), as defined by USA's National Weather Service, is computed when\n `method='US'`. In that case, the maximal valid temperature is 50°F (10 °C) and minimal wind speed is 3 mph (4.8 km/h).\n\n References\n ----------\n .. [MVSZ15] Éva Mekis, Lucie A. Vincent, Mark W. Shephard & Xuebin Zhang (2015) Observed Trends in Severe Weather Conditions Based on Humidex, Wind Chill, and Heavy Rainfall Events in Canada for 1953–2012, Atmosphere-Ocean, 53:4, 383-397, DOI: 10.1080/07055900.2015.1086970\n Osczevski, R., & Bluestein, M. (2005). The New Wind Chill Equivalent Temperature Chart. Bulletin of the American Meteorological Society, 86(10), 1453–1458. https://doi.org/10.1175/BAMS-86-10-1453\n .. [NWS] Wind Chill Questions, Cold Resources, National Weather Service, retrieved 25-05-21. https://www.weather.gov/safety/cold-faqs\n \"\"\"\n tas = convert_units_to(tas, \"degC\")\n sfcWind = convert_units_to(sfcWind, \"km/h\")\n\n V = sfcWind ** 0.16\n W = 13.12 + 0.6215 * tas - 11.37 * V + 0.3965 * tas * V\n\n if method.upper() == \"CAN\":\n W = xr.where(sfcWind < 5, tas + sfcWind * (-1.59 + 0.1345 * tas) / 5, W)\n elif method.upper() != \"US\":\n raise ValueError(f\"`method` must be one of 'US' and 'CAN'. Got '{method}'.\")\n\n if mask_invalid:\n mask = {\"CAN\": tas <= 0, \"US\": (sfcWind > 4.828032) & (tas <= 10)}\n W = W.where(mask[method.upper()])\n\n W.attrs[\"units\"] = \"degC\"\n return W\n\n\n@declare_units(\n delta_tas=\"[temperature]\",\n pr_baseline=\"[precipitation]\",\n)\ndef clausius_clapeyron_scaled_precipitation(\n delta_tas: xr.DataArray,\n pr_baseline: xr.DataArray,\n cc_scale_factor: float = 1.07,\n) -> xr.DataArray:\n r\"\"\"Scale precipitation according to the Clausius-Clapeyron relation.\n\n Parameters\n ----------\n delta_tas : xarray.DataArray\n Difference in temperature between a baseline climatology and another climatology.\n pr_baseline : xarray.DataArray\n Baseline precipitation to adjust with Clausius-Clapeyron.\n cc_scale_factor : float (default = 1.07)\n Clausius Clapeyron scale factor.\n\n Returns\n -------\n DataArray\n Baseline precipitation scaled to other climatology using Clausius-Clapeyron relationship.\n\n Notes\n -----\n The Clausius-Clapeyron equation for water vapor under typical atmospheric conditions states that the saturation\n water vapor pressure :math:`e_s` changes approximately exponentially with temperature\n\n .. math::\n\n \\frac{\\\\mathrm{d}e_s(T)}{\\\\mathrm{d}T} \\approx 1.07 e_s(T)\n\n This function assumes that precipitation can be scaled by the same factor.\n\n Warnings\n --------\n Make sure that `delta_tas` is computed over a baseline compatible with `pr_baseline`. So for example,\n if `delta_tas` is the climatological difference between a baseline and a future period, then `pr_baseline`\n should be precipitations over a period within the same baseline.\n \"\"\"\n\n # Get difference in temperature. Time-invariant baseline temperature (from above) is broadcast.\n delta_tas = convert_units_to(delta_tas, \"delta_degreeC\")\n\n # Calculate scaled precipitation.\n pr_out = pr_baseline * (cc_scale_factor ** delta_tas)\n pr_out.attrs[\"units\"] = pr_baseline.attrs[\"units\"]\n\n return pr_out\n\n\n@declare_units(tasmin=\"[temperature]\", tasmax=\"[temperature]\", tas=\"[temperature]\")\ndef potential_evapotranspiration(\n tasmin: Optional[xr.DataArray] = None,\n tasmax: Optional[xr.DataArray] = None,\n tas: Optional[xr.DataArray] = None,\n method: str = \"BR65\",\n) -> xr.DataArray:\n \"\"\"Potential evapotranspiration.\n\n The potential for water evaporation from soil and transpiration by plants if the water supply is\n sufficient, according to a given method.\n\n Parameters\n ----------\n tasmin : xarray.DataArray\n Minimum daily temperature.\n tasmax : xarray.DataArray\n Maximum daily temperature.\n tas : xarray.DataArray\n Mean daily temperature.\n method : {\"baierrobertson65\", \"BR65\", \"hargreaves85\", \"HG85\", \"thornthwaite48\", \"TW48\"}\n Which method to use, see notes.\n\n Returns\n -------\n xarray.DataArray\n\n Notes\n -----\n Available methods are:\n\n - \"baierrobertson65\" or \"BR65\", based on [baierrobertson65]_. Requires tasmin and tasmax, daily [D] freq.\n - \"hargreaves85\" or \"HG85\", based on [hargreaves85]_. Requires tasmin and tasmax, daily [D] freq. (optional: tas can be given in addition of tasmin and tasmax).\n - \"thornthwaite48\" or \"TW48\", based on [thornthwaite48]_. Requires tasmin and tasmax, monthly [MS] or daily [D] freq. (optional: tas can be given instead of tasmin and tasmax).\n\n References\n ----------\n .. [baierrobertson65] Baier, W., & Robertson, G. W. (1965). Estimation of latent evaporation from simple weather observations. Canadian journal of plant science, 45(3), 276-284.\n .. [hargreaves85] Hargreaves, G. H., & Samani, Z. A. (1985). Reference crop evapotranspiration from temperature. Applied engineering in agriculture, 1(2), 96-99.\n .. [thornthwaite48] Thornthwaite, C. W. (1948). An approach toward a rational classification of climate. Geographical review, 38(1), 55-94.\n \"\"\"\n\n if method in [\"baierrobertson65\", \"BR65\"]:\n tasmin = convert_units_to(tasmin, \"degF\")\n tasmax = convert_units_to(tasmax, \"degF\")\n\n latr = (tasmin.lat * np.pi) / 180\n gsc = 0.082 # MJ/m2/min\n\n # julian day fraction\n jd_frac = (datetime_to_decimal_year(tasmin.time) % 1) * 2 * np.pi\n\n ds = 0.409 * np.sin(jd_frac - 1.39)\n dr = 1 + 0.033 * np.cos(jd_frac)\n omega = np.arccos(-np.tan(latr) * np.tan(ds))\n re = (\n (24 * 60 / np.pi)\n * gsc\n * dr\n * (\n omega * np.sin(latr) * np.sin(ds)\n + np.cos(latr) * np.cos(ds) * np.sin(omega)\n )\n ) # MJ/m2/day\n re = re / 4.1864e-2 # cal/cm2/day\n\n # Baier et Robertson(1965) formula\n out = 0.094 * (\n -87.03 + 0.928 * tasmax + 0.933 * (tasmax - tasmin) + 0.0486 * re\n )\n out = out.clip(0)\n\n elif method in [\"hargreaves85\", \"HG85\"]:\n tasmin = convert_units_to(tasmin, \"degC\")\n tasmax = convert_units_to(tasmax, \"degC\")\n if tas is None:\n tas = (tasmin + tasmax) / 2\n else:\n tas = convert_units_to(tas, \"degC\")\n\n latr = (tasmin.lat * np.pi) / 180\n gsc = 0.082 # MJ/m2/min\n lv = 2.5 # MJ/kg\n\n # julian day fraction\n jd_frac = (datetime_to_decimal_year(tasmin.time) % 1) * 2 * np.pi\n\n ds = 0.409 * np.sin(jd_frac - 1.39)\n dr = 1 + 0.033 * np.cos(jd_frac)\n omega = np.arccos(-np.tan(latr) * np.tan(ds))\n ra = (\n (24 * 60 / np.pi)\n * gsc\n * dr\n * (\n omega * np.sin(latr) * np.sin(ds)\n + np.cos(latr) * np.cos(ds) * np.sin(omega)\n )\n ) # MJ/m2/day\n\n # Hargreaves and Samani(1985) formula\n out = (0.0023 * ra * (tas + 17.8) * (tasmax - tasmin) ** 0.5) / lv\n out = out.clip(0)\n\n elif method in [\"thornthwaite48\", \"TW48\"]:\n if tas is None:\n tasmin = convert_units_to(tasmin, \"degC\")\n tasmax = convert_units_to(tasmax, \"degC\")\n tas = (tasmin + tasmax) / 2\n else:\n tas = convert_units_to(tas, \"degC\")\n tas = tas.clip(0)\n tas = tas.resample(time=\"MS\").mean(dim=\"time\")\n\n latr = (tas.lat * np.pi) / 180 # rad\n\n start = \"-\".join(\n [\n str(tas.time[0].dt.year.values),\n \"{:02d}\".format(tas.time[0].dt.month.values),\n \"01\",\n ]\n )\n\n end = \"-\".join(\n [\n str(tas.time[-1].dt.year.values),\n \"{:02d}\".format(tas.time[-1].dt.month.values),\n str(tas.time[-1].dt.daysinmonth.values),\n ]\n )\n\n time_v = xr.DataArray(\n date_range(start, end, freq=\"D\", calendar=\"standard\"),\n dims=\"time\",\n name=\"time\",\n )\n\n # julian day fraction\n jd_frac = (datetime_to_decimal_year(time_v) % 1) * 2 * np.pi\n\n ds = 0.409 * np.sin(jd_frac - 1.39)\n omega = np.arccos(-np.tan(latr) * np.tan(ds)) * 180 / np.pi # degrees\n\n # monthly-mean daytime length (multiples of 12 hours)\n dl = 2 * omega / (15 * 12)\n dl_m = dl.resample(time=\"MS\").mean(dim=\"time\")\n\n # annual heat index\n id_m = (tas / 5) ** 1.514\n id_y = id_m.resample(time=\"YS\").sum(dim=\"time\")\n\n tas_idy_a = []\n for base_time, indexes in tas.resample(time=\"YS\").groups.items():\n tas_y = tas.isel(time=indexes)\n id_v = id_y.sel(time=base_time)\n a = 6.75e-7 * id_v ** 3 - 7.71e-5 * id_v ** 2 + 0.01791 * id_v + 0.49239\n\n frac = (10 * tas_y / id_v) ** a\n tas_idy_a.append(frac)\n\n tas_idy_a = xr.concat(tas_idy_a, dim=\"time\")\n\n # Thornthwaite(1948) formula\n out = 1.6 * dl_m * tas_idy_a # cm/month\n out = 10 * out # mm/month\n\n else:\n raise NotImplementedError(f\"'{method}' method is not implemented.\")\n\n out.attrs[\"units\"] = \"mm\"\n return amount2rate(out, out_units=\"kg m-2 s-1\")\n" ]
[ [ "numpy.arctan2", "numpy.hypot", "numpy.cos", "numpy.exp", "numpy.tan", "numpy.log", "numpy.log10", "numpy.sin", "numpy.linspace", "numpy.radians" ] ]
AQ18/skimpy
[ "435fc50244f2ca815bbb39d525a82a4692f5c0ac" ]
[ "tests/test_ORACLE.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\n.. module:: skimpy\n :platform: Unix, Windows\n :synopsis: Simple Kinetic Models in Python\n\n.. moduleauthor:: SKiMPy team\n\n[---------]\n\nCopyright 2018 Laboratory of Computational Systems Biotechnology (LCSB),\nEcole Polytechnique Federale de Lausanne (EPFL), Switzerland\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\nhttp://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\n\"\"\"\n\nimport pytest\n\nimport numpy as np\n\nimport pytfa\nfrom pytfa.io import import_matlab_model, load_thermoDB\nfrom pytfa.io.viz import get_reaction_data\n\nfrom skimpy.utils.namespace import *\nfrom skimpy.sampling.simple_parameter_sampler import SimpleParameterSampler\nfrom skimpy.core.solution import ODESolutionPopulation\nfrom skimpy.io.generate_from_pytfa import FromPyTFA\nfrom skimpy.utils.general import sanitize_cobra_vars\nfrom skimpy.utils.tabdict import TabDict\n\nfrom skimpy.analysis.oracle import *\n\nfrom settings import this_directory\nfrom os.path import join\n\nCPLEX = 'optlang-cplex'\nGLPK = 'optlang-glpk'\n\nBASL_FLUX = 1e-6 # mmol/gDW/hr\nMIN_DISPLACEMENT = 1e-2\nSMALL_MOLECULES = ['h_c','h_e','h_m',\n 'h2o2_c','h2o2_e',\n 'co2_c','co2_r','co2_e',' co2_m',\n 'pi_c','pi_r','pi_e','pi_m',\n 'o2_c','o2_r','o2_e','o2_m',\n 'o2s_c', 'o2s_m', 'o2s_e',\n 'ppi_c','ppi_m','ppi_r',\n 'hco3_c','hco3_e','hco3_m',\n 'na1_c','na1_e']\n\ndef import_toy_model_from_cobra():\n path_to_model = join(this_directory, '..', 'models/toy_model.mat')\n\n cobra_model = import_matlab_model(path_to_model)\n #Test the model\n solution = cobra_model.optimize()\n\n return cobra_model\n\n\ndef convert_cobra_to_tfa(cobra_model):\n \"\"\"\n Make tfa analysis of the model\n \"\"\"\n path_to_data = join(this_directory, '..', 'data/thermo_data.thermodb')\n\n thermo_data = load_thermoDB(path_to_data)\n\n tmodel= pytfa.ThermoModel(thermo_data, cobra_model)\n # for comp in tmodel.compartments.values():\n # comp['c_min'] = 1e-8\n\n tmodel.prepare()\n tmodel.convert(add_displacement = True)\n\n # Set the solver\n tmodel.solver = GLPK\n # Set solver options\n # GLPK option optimality and integrality deprecated\n #tmodel.solver.configuration.tolerances.optimality = 1e-9\n #tmodel.solver.configuration.tolerances.integrality = 1e-9\n\n tmodel.solver.configuration.tolerances.feasibility = 1e-9\n\n\n # Find a solution\n solution = tmodel.optimize()\n\n\n return tmodel\n\n\ndef prepare_tfa_model_for_kinetic_import(tmodel):\n \"\"\"\n Prepare the model to sample parameters\n \"\"\"\n\n # Add minimum flux requirements basal fluxes 1e-6\n # safe: ensure that fluxes that cant obey the minimum requirement are removed\n\n tmodel = add_min_flux_requirements(tmodel, BASL_FLUX, inplace=True )\n solution = tmodel.optimize()\n\n # Fix the flux directionality profile (FDP)\n tmodel = fix_directionality(tmodel, solution, inplace=True)\n solution = tmodel.optimize()\n\n # Add dummy free energy constrains for reaction of unknown free energy\n tmodel = add_undefined_delta_g(tmodel, solution, delta_g_std=0.0, delta_g_std_err=10000.0, inplace=True)\n solution = tmodel.optimize()\n\n # Force a minimal thermodynamic displacement\n\n tmodel = add_min_log_displacement(tmodel, MIN_DISPLACEMENT)\n solution = tmodel.optimize()\n\n return tmodel, solution\n\n\ndef import_kinetic_model_from_tfa(tmodel,solution):\n\n model_gen = FromPyTFA(small_molecules=SMALL_MOLECULES)\n kmodel = model_gen.import_model(tmodel, solution.raw)\n\n return kmodel\n\ndef get_flux_and_concentration_data(tmodel, solution):\n # Map fluxes back to reaction variables\n this_flux_solution = get_reaction_data(tmodel, solution.raw)\n # Create the flux dict\n # Convert fluxes from mmol/gDW/hr to mol/L/s\n # eColi 0.39 gDW/L\n flux_dict = (0.39*1e-3*this_flux_solution[[i.id for i in tmodel.reactions]]).to_dict()\n\n # Create a concentration dict with consistent names\n variable_names = tmodel.log_concentration.list_attr('name')\n metabolite_ids = tmodel.log_concentration.list_attr('id')\n #Get conentrations in mol\n temp_concentration_dict = np.exp(solution.raw[variable_names]).to_dict()\n\n # Map concentration names\n mapping_dict = {k:sanitize_cobra_vars(v) for k,v in zip(variable_names,metabolite_ids)}\n concentration_dict = {mapping_dict[k]:v for k,v in temp_concentration_dict.items()}\n\n return concentration_dict, flux_dict\n\n\n\"\"\"\nPrep and import model\n\"\"\"\ncmodel = import_toy_model_from_cobra()\ntmodel = convert_cobra_to_tfa(cmodel)\ntmodel, solution = prepare_tfa_model_for_kinetic_import(tmodel)\nkmodel = import_kinetic_model_from_tfa(tmodel,solution)\nconcentration_dict, flux_dict = get_flux_and_concentration_data(tmodel,solution)\n\ndef test_compile_mca():\n \"\"\"\n Compile the model\n \"\"\"\n kmodel.prepare(mca=True)\n\n parameter_list = TabDict([(k, p.symbol) for k, p in kmodel.parameters.items()\n if p.name.startswith('vmax_forward')])\n\n kmodel.compile_mca(sim_type=QSSA, parameter_list=parameter_list)\n\n\[email protected](name=['test_parameter_sampling_linear_pathway','test_compile_mca'])\ndef test_oracle_parameter_sampling():\n\n # Initialize parameter sampler\n sampling_parameters = SimpleParameterSampler.Parameters(n_samples=100)\n sampler = SimpleParameterSampler(sampling_parameters)\n\n # Sample the model\n parameter_population = sampler.sample(kmodel, flux_dict, concentration_dict)\n\n\n\[email protected](name=['test_oracle_parameter_sampling','test_compile_mca'])\ndef test_oracle_flux_concentration_sampling():\n\n pass\n\n\n\[email protected](name=['test_oracle_parameter_sampling','test_compile_mca'])\ndef test_oracle_ode():\n\n # Initialize parameter sampler\n sampling_parameters = SimpleParameterSampler.Parameters(n_samples=1)\n sampler = SimpleParameterSampler(sampling_parameters)\n\n # Sample the model\n parameter_population = sampler.sample(kmodel, flux_dict, concentration_dict)\n\n\n kmodel.compile_ode(sim_type=QSSA)\n kmodel.initial_conditions = TabDict([(k,v)for k,v in concentration_dict.items()])\n\n solutions = []\n for parameters in parameter_population:\n kmodel.parameters = parameters\n this_sol_qssa = kmodel.solve_ode(np.linspace(0.0, 10.0, 1000), solver_type='cvode')\n solutions.append(this_sol_qssa)\n\n this_sol_qssa.plot('test.html')\n\n\n solpop = ODESolutionPopulation(solutions)\n\n\[email protected](name=['test_oracle_parameter_sampling','test_compile_mca'])\ndef test_oracle_mca():\n\n\n # Initialize parameter sampler\n sampling_parameters = SimpleParameterSampler.Parameters(n_samples=1)\n sampler = SimpleParameterSampler(sampling_parameters)\n\n # Sample the model\n parameter_population = sampler.sample(kmodel, flux_dict, concentration_dict)\n\n\n \"\"\"\n Calculate control coefficients \n \"\"\"\n flux_control_coeff = kmodel.flux_control_fun(flux_dict,\n concentration_dict,\n parameter_population)\n\n concentration_control_coeff = kmodel.concentration_control_fun(flux_dict,\n concentration_dict,\n parameter_population)\n\n\n" ]
[ [ "numpy.linspace", "numpy.exp" ] ]
alliecc/argoverse-api
[ "8d96ebd92195a4fdb228d45b4584fdc61d4522c9" ]
[ "argoverse/evaluation/eval_forecasting.py" ]
[ "# <Copyright 2019, Argo AI, LLC. Released under the MIT license.>\n\n\"\"\"This module evaluates the forecasted trajectories against the ground truth.\"\"\"\n\nimport math\nimport pickle as pkl\nfrom typing import Dict, List, Optional, Tuple\n\nimport numpy as np\n\nfrom argoverse.map_representation.map_api import ArgoverseMap\n\nLOW_PROB_THRESHOLD_FOR_METRICS = 0.05\n\n\ndef get_ade(forecasted_trajectory: np.ndarray, gt_trajectory: np.ndarray) -> float:\n \"\"\"Compute Average Displacement Error.\n\n Args:\n forecasted_trajectory: Predicted trajectory with shape (pred_len x 2)\n gt_trajectory: Ground truth trajectory with shape (pred_len x 2)\n\n Returns:\n ade: Average Displacement Error\n\n \"\"\"\n pred_len = forecasted_trajectory.shape[0]\n ade = float(\n sum(\n math.sqrt(\n (forecasted_trajectory[i, 0] - gt_trajectory[i, 0]) ** 2\n + (forecasted_trajectory[i, 1] - gt_trajectory[i, 1]) ** 2\n )\n for i in range(pred_len)\n )\n / pred_len\n )\n return ade\n\n\ndef get_fde(forecasted_trajectory: np.ndarray, gt_trajectory: np.ndarray) -> float:\n \"\"\"Compute Final Displacement Error.\n\n Args:\n forecasted_trajectory: Predicted trajectory with shape (pred_len x 2)\n gt_trajectory: Ground truth trajectory with shape (pred_len x 2)\n\n Returns:\n fde: Final Displacement Error\n\n \"\"\"\n fde = math.sqrt(\n (forecasted_trajectory[-1, 0] - gt_trajectory[-1, 0]) ** 2\n + (forecasted_trajectory[-1, 1] - gt_trajectory[-1, 1]) ** 2\n )\n return fde\n\n\ndef get_displacement_errors_and_miss_rate(\n forecasted_trajectories: Dict[int, List[np.ndarray]],\n gt_trajectories: Dict[int, np.ndarray],\n max_guesses: int,\n horizon: int,\n miss_threshold: float,\n forecasted_probabilities: Optional[Dict[int, List[float]]] = None,\n) -> Dict[str, float]:\n \"\"\"Compute min fde and ade for each sample.\n\n Note: Both min_fde and min_ade values correspond to the trajectory which has minimum fde.\n\n Args:\n forecasted_trajectories: Predicted top-k trajectory dict with key as seq_id and value as list of trajectories.\n Each element of the list is of shape (pred_len x 2).\n gt_trajectories: Ground Truth Trajectory dict with key as seq_id and values as trajectory of\n shape (pred_len x 2)\n max_guesses: Number of guesses allowed\n horizon: Prediction horizon\n miss_threshold: Distance threshold for the last predicted coordinate\n forecasted_probabilities: Probabilites associated with forecasted trajectories.\n\n Returns:\n metric_results: Metric values for minADE, minFDE, MR, p-minADE, p-minFDE, p-MR\n \"\"\"\n metric_results: Dict[str, float] = {}\n min_ade, prob_min_ade = [], []\n min_fde, prob_min_fde = [], []\n n_misses, prob_n_misses = [], []\n for k, v in gt_trajectories.items():\n curr_min_ade = float(\"inf\")\n curr_min_fde = float(\"inf\")\n min_idx = 0\n max_num_traj = min(max_guesses, len(forecasted_trajectories[k]))\n\n # If probabilities available, use the most likely trajectories, else use the first few\n if forecasted_probabilities is not None:\n sorted_idx = np.argsort([-x for x in forecasted_probabilities[k]], kind=\"stable\")\n # sorted_idx = np.argsort(forecasted_probabilities[k])[::-1]\n pruned_probabilities = [forecasted_probabilities[k][t] for t in sorted_idx[:max_num_traj]]\n # Normalize\n prob_sum = sum(pruned_probabilities)\n pruned_probabilities = [p / prob_sum for p in pruned_probabilities]\n else:\n sorted_idx = np.arange(len(forecasted_trajectories[k]))\n pruned_trajectories = [forecasted_trajectories[k][t] for t in sorted_idx[:max_num_traj]]\n\n for j in range(len(pruned_trajectories)):\n fde = get_fde(pruned_trajectories[j][:horizon], v[:horizon])\n if fde < curr_min_fde:\n min_idx = j\n curr_min_fde = fde\n curr_min_ade = get_ade(pruned_trajectories[min_idx][:horizon], v[:horizon])\n min_ade.append(curr_min_ade)\n min_fde.append(curr_min_fde)\n n_misses.append(curr_min_fde > miss_threshold)\n\n if forecasted_probabilities is not None:\n prob_n_misses.append(1.0 if curr_min_fde > miss_threshold else (1.0 - pruned_probabilities[min_idx]))\n prob_min_ade.append(\n min(-np.log(pruned_probabilities[min_idx]), -np.log(LOW_PROB_THRESHOLD_FOR_METRICS)) + curr_min_ade\n )\n prob_min_fde.append(\n min(-np.log(pruned_probabilities[min_idx]), -np.log(LOW_PROB_THRESHOLD_FOR_METRICS)) + curr_min_fde\n )\n metric_results[\"minADE\"] = sum(min_ade) / len(min_ade)\n metric_results[\"minFDE\"] = sum(min_fde) / len(min_fde)\n metric_results[\"MR\"] = sum(n_misses) / len(n_misses)\n if forecasted_probabilities is not None:\n metric_results[\"p-minADE\"] = sum(prob_min_ade) / len(prob_min_ade)\n metric_results[\"p-minFDE\"] = sum(prob_min_fde) / len(prob_min_fde)\n metric_results[\"p-MR\"] = sum(prob_n_misses) / len(prob_n_misses)\n return metric_results\n\n\ndef get_drivable_area_compliance(\n forecasted_trajectories: Dict[int, List[np.ndarray]], city_names: Dict[int, str], max_n_guesses: int\n) -> float:\n \"\"\"Compute drivable area compliance metric.\n\n Args:\n forecasted_trajectories: Predicted top-k trajectory dict with key as seq_id and value as list of trajectories.\n Each element of the list is of shape (pred_len x 2).\n city_names: Dict mapping sequence id to city name.\n max_n_guesses: Maximum number of guesses allowed.\n\n Returns:\n Mean drivable area compliance\n\n \"\"\"\n avm = ArgoverseMap()\n\n dac_score = []\n\n for seq_id, trajectories in forecasted_trajectories.items():\n city_name = city_names[seq_id]\n num_dac_trajectories = 0\n n_guesses = min(max_n_guesses, len(trajectories))\n for trajectory in trajectories[:n_guesses]:\n raster_layer = avm.get_raster_layer_points_boolean(trajectory, city_name, \"driveable_area\")\n if np.sum(raster_layer) == raster_layer.shape[0]:\n num_dac_trajectories += 1\n\n dac_score.append(num_dac_trajectories / n_guesses)\n\n return sum(dac_score) / len(dac_score)\n\n\ndef compute_forecasting_metrics(\n forecasted_trajectories: Dict[int, List[np.ndarray]],\n gt_trajectories: Dict[int, np.ndarray],\n city_names: Dict[int, str],\n max_n_guesses: int,\n horizon: int,\n miss_threshold: float,\n forecasted_probabilities: Optional[Dict[int, List[float]]] = None,\n) -> Dict[str, float]:\n \"\"\"Compute all the forecasting metrics.\n\n Args:\n forecasted_trajectories: Predicted top-k trajectory dict with key as seq_id and value as list of trajectories.\n Each element of the list is of shape (pred_len x 2).\n gt_trajectories: Ground Truth Trajectory dict with key as seq_id and values as trajectory of\n shape (pred_len x 2)\n city_names: Dict mapping sequence id to city name.\n max_n_guesses: Number of guesses allowed\n horizon: Prediction horizon\n miss_threshold: Miss threshold\n forecasted_probabilities: Normalized Probabilities associated with each of the forecasted trajectories.\n\n Returns:\n metric_results: Dictionary containing values for all metrics.\n \"\"\"\n metric_results = get_displacement_errors_and_miss_rate(\n forecasted_trajectories, gt_trajectories, max_n_guesses, horizon, miss_threshold, forecasted_probabilities\n )\n metric_results[\"DAC\"] = get_drivable_area_compliance(forecasted_trajectories, city_names, max_n_guesses)\n\n print(\"------------------------------------------------\")\n print(f\"Prediction Horizon : {horizon}, Max #guesses (K): {max_n_guesses}\")\n print(\"------------------------------------------------\")\n print(metric_results)\n print(\"------------------------------------------------\")\n\n return metric_results\n" ]
[ [ "numpy.sum", "numpy.log", "numpy.argsort" ] ]
rscalzo/sami
[ "7ac5632e018cdf2384f5ff067c503177684f61c8", "7ac5632e018cdf2384f5ff067c503177684f61c8" ]
[ "utils/cCirc.py", "samifitting.py" ]
[ "from __future__ import print_function\n\n\"\"\"\nWrapper for the C++ drizzle overlap code.\n\nHistory\n-------\n\nCreated by Jon Nielsen in 2012\nUpdated for the new cubing algorithm by Francesco D'Eugenio 16/02/2017\n\nNotes\n-----\nThis module contains a testing function. At the moment it requires that the libraries path be hardcoded (FDE).\n\"\"\"\n\nimport ctypes as C\nimport numpy as np\nimport os.path\n\n# Load the shared library\ntry:\n libcm = C.CDLL(os.path.join(os.path.dirname(__file__), \"libcCirc.so\"))\nexcept:\n raise ImportError\n pass\n #libcm = C.CDLL(os.path.join('/home/franz/software/dev/sami-software-dev/dr0.10/utils', 'libcCirc.so'))\n\n# Specify the arguments our function takes:\n# First argument is a 1D array of doubles. It must be contiguous in memory.\n# Second argument is a regular C long.\n# Third argument is a pointer to a double.\nlibcm.weight_map.argtypes = [\n C.c_long, C.c_long, C.c_double, C.c_double, C.c_double,\n np.ctypeslib.ndpointer(dtype='d', ndim=1, flags='C_CONTIGUOUS')]\n\n\n\ndef resample_circle(nx, ny, xc, yc, r, *args):\n output = np.zeros(nx*ny)\n libcm.weight_map(nx, ny, xc, yc, r, output)\n return output.reshape(ny, nx)\n\n\n\n\n# Specify the arguments our function takes:\n# First argument is a 1D array of doubles. It must be contiguous in memory.\n# Second argument is a regular C long.\n# Third argument is a pointer to a double.\nlibcm.weight_map_Gaussian.argtypes = [\n C.c_long, C.c_long, C.c_double, C.c_double, C.c_double, C.c_double,\n np.ctypeslib.ndpointer(dtype='d', ndim=1, flags='C_CONTIGUOUS')]\n\n\n\ndef inteGrauss2d(nx, ny, xc, yc, sigma, n_sigma):\n output = np.zeros(nx*ny)\n libcm.weight_map_Gaussian(nx, ny, xc, yc, sigma, n_sigma, output)\n return output.reshape(ny, nx)\n\n\n\nif __name__ == \"__main__\":\n\n import time\n import pylab as plt\n from mpl_toolkits.axes_grid1 import ImageGrid\n plt.switch_backend('pdf')\n\n try:\n from texttable import Texttable\n\n def print_table(headers, times):\n table = Texttable()\n headers = ['Method'] + headers\n times = [u'Elapsed time (\\u03bcs)'] + times\n table.add_rows([[h, t] for h, t in zip(headers, times)])\n table.set_cols_align([\"l\", \"c\"])\n\n print(table.draw())\n\n except ImportError:\n warnings.warn('To print formatted output, please install `texttable`')\n\n def print_table(headers, times):\n for h, e in zip(headers, elapsed):\n print(h, '{:8.2f}'.format(e/float(n_iterations)*1.e6),\n u'\\u03bc'+'s')\n\n\n from circ import resample_circle as rc_py\n from circ import inteGrauss2d as ig_py\n rc_C = resample_circle\n ig_C = inteGrauss2d\n\n # This circle show that the python implementation of cCirc wraps around,\n # which is dumb\n # (50, 50, 27.527636662069785, 2.716882503265406, 4.9423403572267581,\n # 2.0454945513296701))\n\n # Define some representative cases.\n # Each has (xpix, ypix, xc, yc, [r/sigma], [clip])\n tests = ((10, 10, 5, 5, 1, 3),\n (10, 10, 3, 5, 1, 3),\n (10, 10, 3.1, 5.7, 1, 3))\n tests = ((50, 50, 27.527636662069785, 23.716882503265406, 4.9423403572267581, 2.0454945513296701),\n (50, 50, 27.527636662069785, 2.716882503265406, 4.9423403572267581, 2.0454945513296701)) # <=\n\n # Define some circles to plot. Notice that for `resample_circle` the last\n # element of each tuple is ignored, while the penultimate is the radius.\n # for `inteGrauss2d` the last element defines the truncation and the\n # penultimate element defines the standard deviation of the Gaussian.\n tests = (\n (10, 10, 5., 1.0, 2., 2.),\n (10, 10, 5.65, 1.2, 2.31, 2.001))\n tests = ((50, 50, 9., 9., 1.6, 5.),)\n\n # Number of iterations for the benchmark.\n n_iterations = 10000\n\n n_tests = len(tests)\n\n plt.clf()\n fig = plt.figure(figsize=(18, 3 * n_tests))\n grid = ImageGrid(fig, 111, nrows_ncols=(n_tests, 6),\n cbar_location='top', cbar_mode='edge',\n cbar_pad='0%', cbar_size='5%', direction='row',\n axes_pad=(0, 0))\n \n wmaps = [[rc_py(*t), rc_C(*t), ig_py(*t), ig_C(*t)] for t in tests]\n wmaps = [[w[0], w[1], w[0]-w[1], w[2], w[3], w[2]-w[3]] for w in wmaps]\n wmaps = sum(wmaps, []) # Flatten the list.\n \n # Reformat `tests` so that we can iterate over it for each subplot.\n tests = ((t,)*6 for t in tests) # Repeat each test for every plot that uses it.\n tests = sum(tests, ()) # Flatten this tuple.\n \n\n y_labels = ['$\\mathrm{Test\\;'+ '{}'.format(n) + '}$'\n for n in range(1, n_tests+1)]\n x_labels = ['$\\mathrm{resample\\_circ \\; (python)}$',\n '$\\mathrm{resample\\_circ \\; (C++)}$',\n '$\\mathrm{residuals}$',\n '$\\mathrm{inteGrauss2d \\; (python)}$',\n '$\\mathrm{inteGrauss2d \\; (C++)}$',\n '$\\mathrm{residuals}$']\n\n for n, (wm, t, ax) in enumerate(zip(wmaps, tests, grid)):\n img = ax.imshow(wm, origin='lower', interpolation='none')\n ax.plot([t[2]-.5], [t[3]-.5], 'mx')\n if n >= (n_tests - 1) * 6: # Trigger the colourbar.\n cbar = ax.cax.colorbar(img)\n cbar.solids.set_edgecolor('face')\n\n if n % 6 == 0: # We are at the first column.\n ax.set_ylabel(y_labels[n // 6])\n if n // 6 >= (n_tests - 1): # We are at the bottom row.\n ax.set_xlabel(x_labels[n % 6])\n \n #plt.subplots_adjust(wspace=0., hspace=0.)\n plt.savefig('test_ccircs.pdf')\n \n \n \n # Benchmarking.\n \n # Create random tests to prevent system caching of interemdiate results in\n # the C implementation - that would be unfair.\n \n grid_size = np.repeat(50, n_iterations)\n xc, yc = np.random.uniform(10, 40, (2, n_iterations))\n radius = np.random.uniform(1, 5, n_iterations)\n n_sigma = np.random.uniform(1, 5, n_iterations)\n \n tests = [\n (xpix, ypix, x, y, r, ns)\n for xpix, ypix, x, y, r, ns in zip(\n grid_size, grid_size, xc, yc, radius, n_sigma)]\n \n start_time, elapsed, results = [], [], []\n \n print('Benchmarking function `resample_circle` (Top hat cubing, python)...')\n start_time.append(time.time())\n results.append(np.array([rc_py(*t) for t in tests]))\n elapsed.append(time.time() - start_time[-1])\n \n print('Benchmarking function `resample_circle` (Top hat cubing, C++)...')\n start_time.append(time.time())\n results.append(np.array([rc_C(*t) for t in tests]))\n elapsed.append(time.time() - start_time[-1])\n \n print('Benchmarking function `inteGrauss2d` (Gaussian cubing, python)...')\n start_time.append(time.time())\n results.append(np.array([ig_py(*t) for t in tests]))\n elapsed.append(time.time() - start_time[-1])\n \n print('Benchmarking function `inteGrauss2d` (Gaussian cubing, C++)...')\n start_time.append(time.time())\n results.append(np.array([ig_C(*t) for t in tests]))\n elapsed.append(time.time() - start_time[-1])\n \n print('Summary:')\n headers = ['`resample_circle` (Top hat cubing, python)',\n '`resample_circle` (Top hat cubing, C++)',\n '`inteGrauss2d` (Gaussian cubing, python)',\n '`inteGrauss2d` (Gaussian cubing, C++)']\n print_table(headers, elapsed)\n", "\"\"\"\r\nThis file contains various fitting functions for general use with SAMI codes.\r\n\r\nCurrently included:\r\n\r\nGaussFitter - Gaussian Fitter (1d)\r\nGaussHermiteFitter - Fits a truncated Gauss-Hermite expansion (1d)\r\nTwoDGaussFitter - Gaussian Fitter (2d, optionally w/ PA and different widths)\r\n\r\nWould be nice:\r\n\r\nExponential Fitter?\r\nOthers?\r\n\r\nExample of the class format is below. Should have a list of things that can\r\nbe accessed in all class definitions (chi-2 etc.)\r\n\r\nTo use these fitting classes, initialise them using the initial guesses of the\r\nparameters, along with the coordinates, data and (optionally) weights. Then\r\ncall the fit function to perform the fit. The best fit parameters are then\r\nstored in p. For example:\r\n\r\nmy_fitter = TwoDGaussFitter(initial_p, x, y, data, weights)\r\nmy_fitter.fit()\r\nbest_fit_p = my_fitter.p\r\n\r\nIf you want to integrate over each fibre, use the fibre_integrator function\r\n*before* performing the fit. The diameter must be provided in the same units\r\nthat x and y will be in. For example:\r\n\r\nmy_fitter = TwoDGaussFitter(initial_p, x, y, data, weights)\r\nfibre_integrator(my_fitter, 1.6)\r\nmy_fitter.fit()\r\nbest_fit_p = my_fitter.p\r\n\r\nFor integration over square pixels rather than round fibres, use:\r\nfibre_integrator(my_fitter, 0.7, pixel=True)\r\n\r\nCalling an instance of a fitter will return the model values at the provided\r\ncoordinates. So, after either of the above examples:\r\n\r\nmy_fitter(x, y)\r\n\r\nwould return the best-fit model values at the coordinates (x, y).\r\n\r\nTODO: Make a BaseFitter class containing the basic functionality that other\r\nclasses can inherit from.\r\n\r\nTODO: Implement limits in a better way, i.e. use a minimisation function\r\nthat incorporates limits rather than the \"return 1e99\" method used below.\r\n\r\nTODO: Rename this module to fitting, rather than samifitting.\r\n\"\"\"\r\nfrom __future__ import absolute_import, division, print_function, unicode_literals\r\n\r\nfrom scipy.optimize import leastsq\r\nimport scipy as sp\r\nimport numpy as np\r\n\r\nclass FittingException(Exception):\r\n \"\"\"Could I make this do something useful?\"\"\"\r\n pass\r\n\r\nclass GaussFitter:\r\n \"\"\" Fits a 1d Gaussian to data. Params in form list p (amplitude, mean, sigma, offset). Offset is optional.\"\"\"\r\n\r\n def __init__(self, p, x, y, weights=None):\r\n self.p_start = p\r\n self.p = p\r\n self.x = x\r\n self.y = y\r\n if weights == None:\r\n self.weights = sp.ones(len(self.y))\r\n else:\r\n self.weights = weights\r\n\r\n self.perr = 0.\r\n self.var_fit = 0.\r\n\r\n if len(p) == 4 and p[0]>0.:\r\n self.fitfunc = self.f1\r\n elif len(p) == 3:\r\n # no base\r\n self.fitfunc = self.f2\r\n elif len(p) == 4 and p[0] < 0.:\r\n self.p[0] = abs(self.p[0])\r\n self.fitfunc = self.f3\r\n \r\n def f1(self, p, x): \r\n return p[0]*sp.exp(-(p[1]-x)**2/(2*p[2]**2)) + p[3]\r\n \r\n def f2(self, p, x): \r\n return p[0]*sp.exp(-(p[1]-x)**2/(2*p[2]**2)) + 0.\r\n \r\n def f3(self, p, x): \r\n return -p[0]*sp.exp(-(p[1]-x)**2/(2*p[2]**2)) + p[3]\r\n\r\n def errfunc(self, p, x, y, weights):\r\n # if width < 0 return input\r\n if p[2] < 0. or p[0] < 0.:\r\n # if we get a negative sigma value then penalise massively because\r\n # that is silly.\r\n # This method isn't great, as it can make leastsq confused about\r\n # the convergence criteria. Would be better to use something like\r\n # scipy.optimize.minimize that properly incorporates limits. Same\r\n # goes for the other classes in this module.\r\n return 1e99\r\n else:\r\n return weights*(self.fitfunc(p, x) - y)\r\n\r\n def fit(self):\r\n\r\n self.p, self.cov_x, self.infodict, self.mesg, self.success = \\\r\n leastsq(self.errfunc, self.p, \\\r\n args=(self.x, self.y, self.weights), full_output=1)\r\n\r\n var_fit = (self.errfunc(self.p, self.x, \\\r\n self.y, self.weights)**2).sum()/(len(self.y)-len(self.p))\r\n\r\n self.var_fit = var_fit\r\n\r\n if self.cov_x is not None:\r\n self.perr = sp.sqrt(self.cov_x.diagonal())*self.var_fit\r\n\r\n if not self.success in [1,2,3,4]:\r\n print(\"Fit Failed\")\r\n #raise FittingException(\"Fit failed\") # This does nothing.\r\n \r\n self.linestr=self.p[0]*self.p[2]*sp.sqrt(2*sp.pi)\r\n #self.line_err=S.sqrt(self.linestr*self.linestr*((self.perr[0]/self.p[0])**2+(self.perr[2]/self.p[2])**2))\r\n\r\n def __call__(self, x):\r\n return self.fitfunc(self.p, x)\r\n\r\nclass GaussHermiteFitter:\r\n \"\"\"Parameters list p contains, in order, amplitude, mean, sigma, h3, h4, bias, where the bias is optional\"\"\"\r\n\r\n def __init__(self, p, x, y, weights=None):\r\n self.p_start = p\r\n self.p = p\r\n self.x = x\r\n self.y = y\r\n if weights == None:\r\n self.weights = S.ones(len(self.y))\r\n else:\r\n self.weights = weights\r\n\r\n self.perr = 0.\r\n self.var_fit = 0.\r\n\r\n # Which function to use depends on the input parameters \r\n if len(p) == 5 and p[0]>0.:\r\n # Fit a truncated Gauss-Hermite sequence.\r\n self.fitfunc = self.f1\r\n elif len(p) == 6 and p[0]>0.:\r\n # Fit a truncated Gauss-Hermite sequence with a bias.\r\n self.fitfunc = self.f2\r\n else:\r\n raise Exception\r\n \r\n def f1(self, p, x):\r\n w=(p[1]-x)/(p[2])\r\n H3=(p[3]*sp.sqrt(2)/sp.sqrt(6))*((2*w**3)-(3*w))\r\n H4=(p[4]/sp.sqrt(24))*(4*w**4-12*w**2+3)\r\n gauss=p[0]*sp.exp(-w**2/2)\r\n \r\n gh=gauss*(1+H3+H4)\r\n return gh\r\n\r\n def f2(self, p, x):\r\n w=(p[1]-x)/(p[2])\r\n H3=(p[3]*sp.sqrt(2)/sp.sqrt(6))*((2*w**3)-(3*w))\r\n H4=(p[4]/sp.sqrt(24))*(4*w**4-12*w**2+3)\r\n gauss=p[0]*sp.exp(-w**2/2)\r\n \r\n gh2=gauss*(1+H3+H4)+p[5]\r\n return gh2\r\n\r\n def errfunc(self, p, x, y, weights):\r\n if p[2] < 0. or p[0] < 0.:\r\n # if we get a negative sigma value then penalise massively because\r\n # that is silly.\r\n return 1e99\r\n else:\r\n return weights*(self.fitfunc(p, x) - y)\r\n\r\n def fit(self):\r\n\r\n self.p, self.cov_x, self.infodict, self.mesg, self.success = \\\r\n leastsq(self.errfunc, self.p, \\\r\n args=(self.x, self.y, self.weights), full_output=1)\r\n\r\n var_fit = (self.errfunc(self.p, self.x, \\\r\n self.y, self.weights)**2).sum()/(len(self.y)-len(self.p))\r\n\r\n self.var_fit = var_fit\r\n\r\n if self.cov_x is not None:\r\n self.perr = S.sqrt(self.cov_x.diagonal())*self.var_fit\r\n\r\n # Would like to return the linestrength and associated error\r\n gamma=self.p[0]*self.p[2]*S.sqrt(2*S.pi)\r\n gamma_err=S.sqrt(gamma*gamma*((self.perr[0]/self.p[0])**2+(self.perr[1]/self.p[1])**2))\r\n self.linestr=gamma*(1+S.sqrt(6)*self.p[4]/4)\r\n self.line_err=S.sqrt(gamma_err**2*(1+S.sqrt(6)*self.p[4]/4)**2+self.perr[4]**2*(S.sqrt(6)*gamma_err/4)**2)\r\n\r\n if not self.success in [1,2,3,4]:\r\n print(\"Fit Failed...\")\r\n #raise FittingException(\"Fit failed\")\r\n\r\n def __call__(self, x):\r\n return self.fitfunc(self.p, x)\r\n\r\nclass TwoDGaussFitter:\r\n \"\"\" Fits a 2d Gaussian with PA and ellipticity. Params in form (amplitude, mean_x, mean_y, sigma_x, sigma_y,\r\n rotation, offset). Offset is optional. To fit a circular Gaussian use (amplitude, mean_x, mean_y, sigma, offset),\r\n again offset is optional.\"\"\"\r\n\r\n def __init__(self, p, x, y, z, weights=None):\r\n self.p_start = p\r\n self.p = p\r\n self.x = x\r\n self.y = y\r\n self.z = z\r\n \r\n if weights == None:\r\n self.weights = sp.ones(len(self.z))\r\n else:\r\n self.weights = weights\r\n\r\n self.perr = 0.\r\n self.var_fit = 0.\r\n\r\n if len(p) == 7:\r\n # 2d elliptical Gaussian with offset.\r\n self.p[0] = abs(self.p[0]) # amplitude should be positive.\r\n self.fitfunc = self.f1\r\n \r\n elif len(p) == 6:\r\n # 2d elliptical Gaussian witout offset.\r\n self.p[0] = abs(self.p[0]) # amplitude should be positive.\r\n self.fitfunc = self.f2\r\n \r\n elif len(p) == 5:\r\n # 2d circular Gaussian with offset.\r\n self.p[0] = abs(self.p[0]) # amplitude should be positive.\r\n self.fitfunc = self.f3\r\n \r\n elif len(p) == 4:\r\n self.p[0] = abs(self.p[0])\r\n self.fitfunc = self.f4\r\n\r\n else:\r\n raise Exception\r\n\r\n def f1(self, p, x, y):\r\n # f1 is an elliptical Gaussian with PA and a bias level.\r\n\r\n rot_rad=p[5]*sp.pi/180 # convert rotation into radians.\r\n\r\n rc_x=p[1]*sp.cos(rot_rad)-p[2]*sp.sin(rot_rad)\r\n rc_y=p[1]*sp.sin(rot_rad)+p[2]*sp.cos(rot_rad)\r\n \r\n return p[0]*sp.exp(-(((rc_x-(x*sp.cos(rot_rad)-y*sp.sin(rot_rad)))/p[3])**2\\\r\n +((rc_y-(x*sp.sin(rot_rad)+y*sp.cos(rot_rad)))/p[4])**2)/2)+p[6]\r\n\r\n def f2(self, p, x, y):\r\n # f2 is an elliptical Gaussian with PA and no bias level.\r\n\r\n rot_rad=p[5]*sp.pi/180 # convert rotation into radians.\r\n\r\n rc_x=p[1]*sp.cos(rot_rad)-p[2]*sp.sin(rot_rad)\r\n rc_y=p[1]*sp.sin(rot_rad)+p[2]*sp.cos(rot_rad)\r\n \r\n return p[0]*sp.exp(-(((rc_x-(x*sp.cos(rot_rad)-y*sp.sin(rot_rad)))/p[3])**2\\\r\n +((rc_y-(x*sp.sin(rot_rad)+y*sp.cos(rot_rad)))/p[4])**2)/2)\r\n\r\n def f3(self, p, x, y):\r\n # f3 is a circular Gaussian, p in form (amplitude, mean_x, mean_y, sigma, offset).\r\n return p[0]*sp.exp(-(((p[1]-x)/p[3])**2+((p[2]-y)/p[3])**2)/2)+p[4]\r\n\r\n def f4(self, p, x, y):\r\n # f4 is a circular Gaussian as f3 but without an offset\r\n return p[0]*sp.exp(-(((p[1]-x)/p[3])**2+((p[2]-y)/p[3])**2)/2)\r\n\r\n def errfunc(self, p, x, y, z, weights):\r\n # if width < 0 return input\r\n #if p[3] < 0. or p[4] < 0. or p[0] < 0.: # This isn't valid for the circular case!\r\n # if we get negative sigma values then penalise massively because\r\n # that is silly.\r\n #return 1e99\r\n #else:\r\n return weights*(self.fitfunc(p, x, y) - z)\r\n\r\n def fit(self):\r\n\r\n #print(np.shape(self.x), np.shape(self.y), np.shape(self.z))\r\n\r\n self.p, self.cov_x, self.infodict, self.mesg, self.success = \\\r\n leastsq(self.errfunc, self.p, \\\r\n args=(self.x, self.y, self.z, self.weights), full_output=1)\r\n\r\n var_fit = (self.errfunc(self.p, self.x, \\\r\n self.y, self.z, self.weights)**2).sum()/(len(self.z)-len(self.p))\r\n\r\n self.var_fit = var_fit\r\n\r\n if self.cov_x is not None:\r\n self.perr = sp.sqrt(self.cov_x.diagonal())*self.var_fit\r\n\r\n if not self.success in [1,2,3,4]:\r\n print(\"Fit Failed...\")\r\n #raise ExpFittingException(\"Fit failed\")\r\n\r\n def __call__(self, x, y):\r\n return self.fitfunc(self.p, x, y)\r\n \r\ndef fibre_integrator(fitter, diameter, pixel=False):\r\n \"\"\"Edits a fitter's fitfunc so that it integrates over each SAMI fibre.\"\"\"\r\n\r\n # Save the diameter; not used here but could be useful later\r\n fitter.diameter = diameter\r\n\r\n # Define the subsampling points to use\r\n n_pix = 5 # Number of sampling points across the fibre\r\n # First make a 1d array of subsample points\r\n delta_x = np.linspace(-0.5 * (diameter * (1 - 1.0/n_pix)),\r\n 0.5 * (diameter * (1 - 1.0/n_pix)),\r\n num=n_pix)\r\n delta_y = delta_x\r\n # Then turn that into a 2d grid of (delta_x, delta_y) centred on (0, 0)\r\n delta_x = np.ravel(np.outer(delta_x, np.ones(n_pix)))\r\n delta_y = np.ravel(np.outer(np.ones(n_pix), delta_y))\r\n if pixel:\r\n # Square pixels; keep everything\r\n n_keep = n_pix**2\r\n else:\r\n # Round fibres; only keep the points within one radius\r\n keep = np.where(delta_x**2 + delta_y**2 < (0.5 * diameter)**2)[0]\r\n n_keep = np.size(keep)\r\n delta_x = delta_x[keep]\r\n delta_y = delta_y[keep]\r\n\r\n old_fitfunc = fitter.fitfunc\r\n\r\n def integrated_fitfunc(p, x, y):\r\n # The fitter's fitfunc will be replaced by this one\r\n n_fib = np.size(x)\r\n x_sub = (np.outer(delta_x, np.ones(n_fib)) +\r\n np.outer(np.ones(n_keep), x))\r\n y_sub = (np.outer(delta_y, np.ones(n_fib)) +\r\n np.outer(np.ones(n_keep), y))\r\n return np.mean(old_fitfunc(p, x_sub, y_sub), 0)\r\n\r\n # Replace the fitter's fitfunc\r\n fitter.fitfunc = integrated_fitfunc\r\n\r\n return\r\n\r\n" ]
[ [ "numpy.random.uniform", "numpy.ctypeslib.ndpointer", "numpy.repeat", "numpy.zeros" ], [ "scipy.sqrt", "numpy.ones", "scipy.cos", "scipy.exp", "scipy.optimize.leastsq", "numpy.size", "scipy.sin", "numpy.where", "numpy.linspace" ] ]
ShihanYang/dgl
[ "ec2e24be6dcc3bcc3d4ad5dff78212735f9db00f" ]
[ "tests/compute/test_transform.py" ]
[ "from scipy import sparse as spsp\nimport unittest\nimport networkx as nx\nimport numpy as np\nimport dgl\nimport dgl.function as fn\nimport backend as F\nfrom dgl.graph_index import from_scipy_sparse_matrix\nimport unittest\nfrom utils import parametrize_dtype\n\nD = 5\n\n# line graph related\n\ndef test_line_graph():\n N = 5\n G = dgl.DGLGraph(nx.star_graph(N))\n G.edata['h'] = F.randn((2 * N, D))\n n_edges = G.number_of_edges()\n L = G.line_graph(shared=True)\n assert L.number_of_nodes() == 2 * N\n L.ndata['h'] = F.randn((2 * N, D))\n # update node features on line graph should reflect to edge features on\n # original graph.\n u = [0, 0, 2, 3]\n v = [1, 2, 0, 0]\n eid = G.edge_ids(u, v)\n L.nodes[eid].data['h'] = F.zeros((4, D))\n assert F.allclose(G.edges[u, v].data['h'], F.zeros((4, D)))\n\n # adding a new node feature on line graph should also reflect to a new\n # edge feature on original graph\n data = F.randn((n_edges, D))\n L.ndata['w'] = data\n assert F.allclose(G.edata['w'], data)\n\n@parametrize_dtype\ndef test_hetero_linegraph(index_dtype):\n g = dgl.graph(([0, 1, 1, 2, 2],[2, 0, 2, 0, 1]),\n 'user', 'follows', index_dtype=index_dtype)\n lg = dgl.line_heterograph(g)\n assert lg.number_of_nodes() == 5\n assert lg.number_of_edges() == 8\n row, col = lg.edges()\n assert np.array_equal(F.asnumpy(row),\n np.array([0, 0, 1, 2, 2, 3, 4, 4]))\n assert np.array_equal(F.asnumpy(col),\n np.array([3, 4, 0, 3, 4, 0, 1, 2]))\n\n lg = dgl.line_heterograph(g, backtracking=False)\n assert lg.number_of_nodes() == 5\n assert lg.number_of_edges() == 4\n row, col = lg.edges()\n assert np.array_equal(F.asnumpy(row),\n np.array([0, 1, 2, 4]))\n assert np.array_equal(F.asnumpy(col),\n np.array([4, 0, 3, 1]))\n g = dgl.graph(([0, 1, 1, 2, 2],[2, 0, 2, 0, 1]),\n 'user', 'follows', restrict_format='csr', index_dtype=index_dtype)\n lg = dgl.line_heterograph(g)\n assert lg.number_of_nodes() == 5\n assert lg.number_of_edges() == 8\n row, col = lg.edges()\n assert np.array_equal(F.asnumpy(row),\n np.array([0, 0, 1, 2, 2, 3, 4, 4]))\n assert np.array_equal(F.asnumpy(col),\n np.array([3, 4, 0, 3, 4, 0, 1, 2]))\n\n g = dgl.graph(([0, 1, 1, 2, 2],[2, 0, 2, 0, 1]),\n 'user', 'follows', restrict_format='csc', index_dtype=index_dtype)\n lg = dgl.line_heterograph(g)\n assert lg.number_of_nodes() == 5\n assert lg.number_of_edges() == 8\n row, col, eid = lg.edges('all')\n row = F.asnumpy(row)\n col = F.asnumpy(col)\n eid = F.asnumpy(eid).astype(int)\n order = np.argsort(eid)\n assert np.array_equal(row[order],\n np.array([0, 0, 1, 2, 2, 3, 4, 4]))\n assert np.array_equal(col[order],\n np.array([3, 4, 0, 3, 4, 0, 1, 2]))\n\ndef test_no_backtracking():\n N = 5\n G = dgl.DGLGraph(nx.star_graph(N))\n L = G.line_graph(backtracking=False)\n assert L.number_of_nodes() == 2 * N\n for i in range(1, N):\n e1 = G.edge_id(0, i)\n e2 = G.edge_id(i, 0)\n assert not L.has_edge_between(e1, e2)\n assert not L.has_edge_between(e2, e1)\n\n# reverse graph related\ndef test_reverse():\n g = dgl.DGLGraph()\n g.add_nodes(5)\n # The graph need not to be completely connected.\n g.add_edges([0, 1, 2], [1, 2, 1])\n g.ndata['h'] = F.tensor([[0.], [1.], [2.], [3.], [4.]])\n g.edata['h'] = F.tensor([[5.], [6.], [7.]])\n rg = g.reverse()\n\n assert g.is_multigraph == rg.is_multigraph\n\n assert g.number_of_nodes() == rg.number_of_nodes()\n assert g.number_of_edges() == rg.number_of_edges()\n assert F.allclose(F.astype(rg.has_edges_between(\n [1, 2, 1], [0, 1, 2]), F.float32), F.ones((3,)))\n assert g.edge_id(0, 1) == rg.edge_id(1, 0)\n assert g.edge_id(1, 2) == rg.edge_id(2, 1)\n assert g.edge_id(2, 1) == rg.edge_id(1, 2)\n\n # test dgl.reverse_heterograph\n # test homogeneous graph\n g = dgl.graph((F.tensor([0, 1, 2]), F.tensor([1, 2, 0])))\n g.ndata['h'] = F.tensor([[0.], [1.], [2.]])\n g.edata['h'] = F.tensor([[3.], [4.], [5.]])\n g_r = dgl.reverse_heterograph(g)\n assert g.number_of_nodes() == g_r.number_of_nodes()\n assert g.number_of_edges() == g_r.number_of_edges()\n u_g, v_g, eids_g = g.all_edges(form='all')\n u_rg, v_rg, eids_rg = g_r.all_edges(form='all')\n assert F.array_equal(u_g, v_rg)\n assert F.array_equal(v_g, u_rg)\n assert F.array_equal(eids_g, eids_rg)\n assert F.array_equal(g.ndata['h'], g_r.ndata['h'])\n assert len(g_r.edata) == 0\n\n # without share ndata\n g_r = dgl.reverse_heterograph(g, copy_ndata=False)\n assert g.number_of_nodes() == g_r.number_of_nodes()\n assert g.number_of_edges() == g_r.number_of_edges()\n assert len(g_r.ndata) == 0\n assert len(g_r.edata) == 0\n\n # with share ndata and edata\n g_r = dgl.reverse_heterograph(g, copy_ndata=True, copy_edata=True)\n assert g.number_of_nodes() == g_r.number_of_nodes()\n assert g.number_of_edges() == g_r.number_of_edges()\n assert F.array_equal(g.ndata['h'], g_r.ndata['h'])\n assert F.array_equal(g.edata['h'], g_r.edata['h'])\n\n # add new node feature to g_r\n g_r.ndata['hh'] = F.tensor([0, 1, 2])\n assert ('hh' in g.ndata) is False\n assert ('hh' in g_r.ndata) is True\n\n # add new edge feature to g_r\n g_r.edata['hh'] = F.tensor([0, 1, 2])\n assert ('hh' in g.edata) is False\n assert ('hh' in g_r.edata) is True\n\n # test heterogeneous graph\n g = dgl.heterograph({\n ('user', 'follows', 'user'): ([0, 1, 2, 4, 3 ,1, 3], [1, 2, 3, 2, 0, 0, 1]),\n ('user', 'plays', 'game'): ([0, 0, 2, 3, 3, 4, 1], [1, 0, 1, 0, 1, 0, 0]),\n ('developer', 'develops', 'game'): ([0, 1, 1, 2], [0, 0, 1, 1])})\n g.nodes['user'].data['h'] = F.tensor([0, 1, 2, 3, 4])\n g.nodes['user'].data['hh'] = F.tensor([1, 1, 1, 1, 1])\n g.nodes['game'].data['h'] = F.tensor([0, 1])\n g.edges['follows'].data['h'] = F.tensor([0, 1, 2, 4, 3 ,1, 3])\n g.edges['follows'].data['hh'] = F.tensor([1, 2, 3, 2, 0, 0, 1])\n g_r = dgl.reverse_heterograph(g)\n\n for etype_g, etype_gr in zip(g.canonical_etypes, g_r.canonical_etypes):\n assert etype_g[0] == etype_gr[2]\n assert etype_g[1] == etype_gr[1]\n assert etype_g[2] == etype_gr[0]\n assert g.number_of_edges(etype_g) == g_r.number_of_edges(etype_gr)\n for ntype in g.ntypes:\n assert g.number_of_nodes(ntype) == g_r.number_of_nodes(ntype)\n assert F.array_equal(g.nodes['user'].data['h'], g_r.nodes['user'].data['h'])\n assert F.array_equal(g.nodes['user'].data['hh'], g_r.nodes['user'].data['hh'])\n assert F.array_equal(g.nodes['game'].data['h'], g_r.nodes['game'].data['h'])\n assert len(g_r.edges['follows'].data) == 0\n u_g, v_g, eids_g = g.all_edges(form='all', etype=('user', 'follows', 'user'))\n u_rg, v_rg, eids_rg = g_r.all_edges(form='all', etype=('user', 'follows', 'user'))\n assert F.array_equal(u_g, v_rg)\n assert F.array_equal(v_g, u_rg)\n assert F.array_equal(eids_g, eids_rg)\n u_g, v_g, eids_g = g.all_edges(form='all', etype=('user', 'plays', 'game'))\n u_rg, v_rg, eids_rg = g_r.all_edges(form='all', etype=('game', 'plays', 'user'))\n assert F.array_equal(u_g, v_rg)\n assert F.array_equal(v_g, u_rg)\n assert F.array_equal(eids_g, eids_rg)\n u_g, v_g, eids_g = g.all_edges(form='all', etype=('developer', 'develops', 'game'))\n u_rg, v_rg, eids_rg = g_r.all_edges(form='all', etype=('game', 'develops', 'developer'))\n assert F.array_equal(u_g, v_rg)\n assert F.array_equal(v_g, u_rg)\n assert F.array_equal(eids_g, eids_rg)\n\n # withour share ndata\n g_r = dgl.reverse_heterograph(g, copy_ndata=False)\n for etype_g, etype_gr in zip(g.canonical_etypes, g_r.canonical_etypes):\n assert etype_g[0] == etype_gr[2]\n assert etype_g[1] == etype_gr[1]\n assert etype_g[2] == etype_gr[0]\n assert g.number_of_edges(etype_g) == g_r.number_of_edges(etype_gr)\n for ntype in g.ntypes:\n assert g.number_of_nodes(ntype) == g_r.number_of_nodes(ntype)\n assert len(g_r.nodes['user'].data) == 0\n assert len(g_r.nodes['game'].data) == 0\n\n g_r = dgl.reverse_heterograph(g, copy_ndata=True, copy_edata=True)\n print(g_r)\n for etype_g, etype_gr in zip(g.canonical_etypes, g_r.canonical_etypes):\n assert etype_g[0] == etype_gr[2]\n assert etype_g[1] == etype_gr[1]\n assert etype_g[2] == etype_gr[0]\n assert g.number_of_edges(etype_g) == g_r.number_of_edges(etype_gr)\n assert F.array_equal(g.edges['follows'].data['h'], g_r.edges['follows'].data['h'])\n assert F.array_equal(g.edges['follows'].data['hh'], g_r.edges['follows'].data['hh'])\n\n # add new node feature to g_r\n g_r.nodes['user'].data['hhh'] = F.tensor([0, 1, 2, 3, 4])\n assert ('hhh' in g.nodes['user'].data) is False\n assert ('hhh' in g_r.nodes['user'].data) is True\n\n # add new edge feature to g_r\n g_r.edges['follows'].data['hhh'] = F.tensor([1, 2, 3, 2, 0, 0, 1])\n assert ('hhh' in g.edges['follows'].data) is False\n assert ('hhh' in g_r.edges['follows'].data) is True\n\n\ndef test_reverse_shared_frames():\n g = dgl.DGLGraph()\n g.add_nodes(3)\n g.add_edges([0, 1, 2], [1, 2, 1])\n g.ndata['h'] = F.tensor([[0.], [1.], [2.]])\n g.edata['h'] = F.tensor([[3.], [4.], [5.]])\n\n rg = g.reverse(share_ndata=True, share_edata=True)\n assert F.allclose(g.ndata['h'], rg.ndata['h'])\n assert F.allclose(g.edata['h'], rg.edata['h'])\n assert F.allclose(g.edges[[0, 2], [1, 1]].data['h'],\n rg.edges[[1, 1], [0, 2]].data['h'])\n\n rg.ndata['h'] = rg.ndata['h'] + 1\n assert F.allclose(rg.ndata['h'], g.ndata['h'])\n\n g.edata['h'] = g.edata['h'] - 1\n assert F.allclose(rg.edata['h'], g.edata['h'])\n\n src_msg = fn.copy_src(src='h', out='m')\n sum_reduce = fn.sum(msg='m', out='h')\n\n rg.update_all(src_msg, sum_reduce)\n assert F.allclose(g.ndata['h'], rg.ndata['h'])\n\ndef test_to_bidirected():\n # homogeneous graph\n g = dgl.graph((F.tensor([0, 1, 3, 1]), F.tensor([1, 2, 0, 2])))\n g.ndata['h'] = F.tensor([[0.], [1.], [2.], [1.]])\n g.edata['h'] = F.tensor([[3.], [4.], [5.], [6.]])\n bg = dgl.to_bidirected(g, copy_ndata=True, copy_edata=True)\n u, v = g.edges()\n ub, vb = bg.edges()\n assert F.array_equal(F.cat([u, v], dim=0), ub)\n assert F.array_equal(F.cat([v, u], dim=0), vb)\n assert F.array_equal(g.ndata['h'], bg.ndata['h'])\n assert F.array_equal(F.cat([g.edata['h'], g.edata['h']], dim=0), bg.edata['h'])\n bg.ndata['hh'] = F.tensor([[0.], [1.], [2.], [1.]])\n assert ('hh' in g.ndata) is False\n bg.edata['hh'] = F.tensor([[0.], [1.], [2.], [1.], [0.], [1.], [2.], [1.]])\n assert ('hh' in g.edata) is False\n\n # donot share ndata and edata\n bg = dgl.to_bidirected(g, copy_ndata=False, copy_edata=False)\n ub, vb = bg.edges()\n assert F.array_equal(F.cat([u, v], dim=0), ub)\n assert F.array_equal(F.cat([v, u], dim=0), vb)\n assert ('h' in bg.ndata) is False\n assert ('h' in bg.edata) is False\n\n # zero edge graph\n g = dgl.graph([])\n bg = dgl.to_bidirected(g, copy_ndata=True, copy_edata=True)\n\n # heterogeneous graph\n g = dgl.heterograph({\n ('user', 'wins', 'user'): (F.tensor([0, 2, 0, 2, 2]), F.tensor([1, 1, 2, 1, 0])),\n ('user', 'plays', 'game'): (F.tensor([1, 2, 1]), F.tensor([2, 1, 1])),\n ('user', 'follows', 'user'): (F.tensor([1, 2, 1]), F.tensor([0, 0, 0]))\n })\n g.nodes['game'].data['hv'] = F.ones((3, 1))\n g.nodes['user'].data['hv'] = F.ones((3, 1))\n g.edges['wins'].data['h'] = F.tensor([0, 1, 2, 3, 4])\n bg = dgl.to_bidirected(g, copy_ndata=True, copy_edata=True, ignore_bipartite=True)\n assert F.array_equal(g.nodes['game'].data['hv'], bg.nodes['game'].data['hv'])\n assert F.array_equal(g.nodes['user'].data['hv'], bg.nodes['user'].data['hv'])\n u, v = g.all_edges(order='eid', etype=('user', 'wins', 'user'))\n ub, vb = bg.all_edges(order='eid', etype=('user', 'wins', 'user'))\n assert F.array_equal(F.cat([u, v], dim=0), ub)\n assert F.array_equal(F.cat([v, u], dim=0), vb)\n assert F.array_equal(F.cat([g.edges['wins'].data['h'], g.edges['wins'].data['h']], dim=0),\n bg.edges['wins'].data['h'])\n u, v = g.all_edges(order='eid', etype=('user', 'follows', 'user'))\n ub, vb = bg.all_edges(order='eid', etype=('user', 'follows', 'user'))\n assert F.array_equal(F.cat([u, v], dim=0), ub)\n assert F.array_equal(F.cat([v, u], dim=0), vb)\n u, v = g.all_edges(order='eid', etype=('user', 'plays', 'game'))\n ub, vb = bg.all_edges(order='eid', etype=('user', 'plays', 'game'))\n assert F.array_equal(u, ub)\n assert F.array_equal(v, vb)\n assert len(bg.edges['plays'].data) == 0\n assert len(bg.edges['follows'].data) == 0\n\n # donot share ndata and edata\n bg = dgl.to_bidirected(g, copy_ndata=False, copy_edata=False, ignore_bipartite=True)\n assert len(bg.edges['wins'].data) == 0\n assert len(bg.edges['plays'].data) == 0\n assert len(bg.edges['follows'].data) == 0\n assert len(bg.nodes['game'].data) == 0\n assert len(bg.nodes['user'].data) == 0\n u, v = g.all_edges(order='eid', etype=('user', 'wins', 'user'))\n ub, vb = bg.all_edges(order='eid', etype=('user', 'wins', 'user'))\n assert F.array_equal(F.cat([u, v], dim=0), ub)\n assert F.array_equal(F.cat([v, u], dim=0), vb)\n u, v = g.all_edges(order='eid', etype=('user', 'follows', 'user'))\n ub, vb = bg.all_edges(order='eid', etype=('user', 'follows', 'user'))\n assert F.array_equal(F.cat([u, v], dim=0), ub)\n assert F.array_equal(F.cat([v, u], dim=0), vb)\n u, v = g.all_edges(order='eid', etype=('user', 'plays', 'game'))\n ub, vb = bg.all_edges(order='eid', etype=('user', 'plays', 'game'))\n assert F.array_equal(u, ub)\n assert F.array_equal(v, vb)\n\n\ndef test_simple_graph():\n elist = [(0, 1), (0, 2), (1, 2), (0, 1)]\n g = dgl.DGLGraph(elist, readonly=True)\n assert g.is_multigraph\n sg = dgl.to_simple_graph(g)\n assert not sg.is_multigraph\n assert sg.number_of_edges() == 3\n src, dst = sg.edges()\n eset = set(zip(list(F.asnumpy(src)), list(F.asnumpy(dst))))\n assert eset == set(elist)\n\n\ndef test_bidirected_graph():\n def _test(in_readonly, out_readonly):\n elist = [(0, 0), (0, 1), (1, 0),\n (1, 1), (2, 1), (2, 2)]\n num_edges = 7\n g = dgl.DGLGraph(elist, readonly=in_readonly)\n elist.append((1, 2))\n elist = set(elist)\n big = dgl.to_bidirected_stale(g, out_readonly)\n assert big.number_of_edges() == num_edges\n src, dst = big.edges()\n eset = set(zip(list(F.asnumpy(src)), list(F.asnumpy(dst))))\n assert eset == set(elist)\n\n _test(True, True)\n _test(True, False)\n _test(False, True)\n _test(False, False)\n\n\ndef test_khop_graph():\n N = 20\n feat = F.randn((N, 5))\n\n def _test(g):\n for k in range(4):\n g_k = dgl.khop_graph(g, k)\n # use original graph to do message passing for k times.\n g.ndata['h'] = feat\n for _ in range(k):\n g.update_all(fn.copy_u('h', 'm'), fn.sum('m', 'h'))\n h_0 = g.ndata.pop('h')\n # use k-hop graph to do message passing for one time.\n g_k.ndata['h'] = feat\n g_k.update_all(fn.copy_u('h', 'm'), fn.sum('m', 'h'))\n h_1 = g_k.ndata.pop('h')\n assert F.allclose(h_0, h_1, rtol=1e-3, atol=1e-3)\n\n # Test for random undirected graphs\n g = dgl.DGLGraph(nx.erdos_renyi_graph(N, 0.3))\n _test(g)\n # Test for random directed graphs\n g = dgl.DGLGraph(nx.erdos_renyi_graph(N, 0.3, directed=True))\n _test(g)\n\ndef test_khop_adj():\n N = 20\n feat = F.randn((N, 5))\n g = dgl.DGLGraph(nx.erdos_renyi_graph(N, 0.3))\n for k in range(3):\n adj = F.tensor(dgl.khop_adj(g, k))\n # use original graph to do message passing for k times.\n g.ndata['h'] = feat\n for _ in range(k):\n g.update_all(fn.copy_u('h', 'm'), fn.sum('m', 'h'))\n h_0 = g.ndata.pop('h')\n # use k-hop adj to do message passing for one time.\n h_1 = F.matmul(adj, feat)\n assert F.allclose(h_0, h_1, rtol=1e-3, atol=1e-3)\n\n\ndef test_laplacian_lambda_max():\n N = 20\n eps = 1e-6\n # test DGLGraph\n g = dgl.DGLGraph(nx.erdos_renyi_graph(N, 0.3))\n l_max = dgl.laplacian_lambda_max(g)\n assert (l_max[0] < 2 + eps)\n # test batched DGLGraph\n N_arr = [20, 30, 10, 12]\n bg = dgl.batch([\n dgl.DGLGraph(nx.erdos_renyi_graph(N, 0.3))\n for N in N_arr\n ])\n l_max_arr = dgl.laplacian_lambda_max(bg)\n assert len(l_max_arr) == len(N_arr)\n for l_max in l_max_arr:\n assert l_max < 2 + eps\n\n\ndef test_add_self_loop():\n g = dgl.DGLGraph()\n g.add_nodes(5)\n g.add_edges([0, 1, 2], [1, 1, 2])\n # Nodes 0, 3, 4 don't have self-loop\n new_g = dgl.transform.add_self_loop(g)\n assert F.allclose(new_g.edges()[0], F.tensor([0, 0, 1, 2, 3, 4]))\n assert F.allclose(new_g.edges()[1], F.tensor([1, 0, 1, 2, 3, 4]))\n\n\ndef test_remove_self_loop():\n g = dgl.DGLGraph()\n g.add_nodes(5)\n g.add_edges([0, 1, 2], [1, 1, 2])\n new_g = dgl.transform.remove_self_loop(g)\n assert F.allclose(new_g.edges()[0], F.tensor([0]))\n assert F.allclose(new_g.edges()[1], F.tensor([1]))\n\ndef create_large_graph_index(num_nodes):\n row = np.random.choice(num_nodes, num_nodes * 10)\n col = np.random.choice(num_nodes, num_nodes * 10)\n spm = spsp.coo_matrix((np.ones(len(row)), (row, col)))\n\n return from_scipy_sparse_matrix(spm, True)\n\ndef get_nodeflow(g, node_ids, num_layers):\n batch_size = len(node_ids)\n expand_factor = g.number_of_nodes()\n sampler = dgl.contrib.sampling.NeighborSampler(g, batch_size,\n expand_factor=expand_factor, num_hops=num_layers,\n seed_nodes=node_ids)\n return next(iter(sampler))\n\ndef test_partition_with_halo():\n g = dgl.DGLGraph(create_large_graph_index(1000), readonly=True)\n node_part = np.random.choice(4, g.number_of_nodes())\n subgs = dgl.transform.partition_graph_with_halo(g, node_part, 2)\n for part_id, subg in subgs.items():\n node_ids = np.nonzero(node_part == part_id)[0]\n lnode_ids = np.nonzero(F.asnumpy(subg.ndata['inner_node']))[0]\n nf = get_nodeflow(g, node_ids, 2)\n lnf = get_nodeflow(subg, lnode_ids, 2)\n for i in range(nf.num_layers):\n layer_nids1 = F.asnumpy(nf.layer_parent_nid(i))\n layer_nids2 = lnf.layer_parent_nid(i)\n layer_nids2 = F.asnumpy(F.gather_row(subg.ndata[dgl.NID], layer_nids2))\n assert np.all(np.sort(layer_nids1) == np.sort(layer_nids2))\n\n for i in range(nf.num_blocks):\n block_eids1 = F.asnumpy(nf.block_parent_eid(i))\n block_eids2 = lnf.block_parent_eid(i)\n block_eids2 = F.asnumpy(F.gather_row(subg.edata[dgl.EID], block_eids2))\n assert np.all(np.sort(block_eids1) == np.sort(block_eids2))\n\n subgs = dgl.transform.partition_graph_with_halo(g, node_part, 2, reshuffle=True)\n for part_id, subg in subgs.items():\n node_ids = np.nonzero(node_part == part_id)[0]\n lnode_ids = np.nonzero(F.asnumpy(subg.ndata['inner_node']))[0]\n assert np.all(np.sort(F.asnumpy(subg.ndata['orig_id'])[lnode_ids]) == node_ids)\n\[email protected](F._default_context_str == 'gpu', reason=\"METIS doesn't support GPU\")\ndef test_metis_partition():\n # TODO(zhengda) Metis fails to partition a small graph.\n g = dgl.DGLGraph(create_large_graph_index(1000), readonly=True)\n check_metis_partition(g, 0)\n check_metis_partition(g, 1)\n check_metis_partition(g, 2)\n check_metis_partition_with_constraint(g)\n\[email protected](F._default_context_str == 'gpu', reason=\"METIS doesn't support GPU\")\ndef test_hetero_metis_partition():\n # TODO(zhengda) Metis fails to partition a small graph.\n g = dgl.DGLGraph(create_large_graph_index(1000), readonly=True)\n g = dgl.as_heterograph(g)\n check_metis_partition(g, 0)\n check_metis_partition(g, 1)\n check_metis_partition(g, 2)\n check_metis_partition_with_constraint(g)\n\n\ndef check_metis_partition_with_constraint(g):\n ntypes = np.zeros((g.number_of_nodes(),), dtype=np.int32)\n ntypes[0:int(g.number_of_nodes()/4)] = 1\n ntypes[int(g.number_of_nodes()*3/4):] = 2\n subgs = dgl.transform.metis_partition(g, 4, extra_cached_hops=1, balance_ntypes=ntypes)\n if subgs is not None:\n for i in subgs:\n subg = subgs[i]\n parent_nids = F.asnumpy(subg.ndata[dgl.NID])\n sub_ntypes = ntypes[parent_nids]\n print('type0:', np.sum(sub_ntypes == 0))\n print('type1:', np.sum(sub_ntypes == 1))\n print('type2:', np.sum(sub_ntypes == 2))\n subgs = dgl.transform.metis_partition(g, 4, extra_cached_hops=1,\n balance_ntypes=ntypes, balance_edges=True)\n if subgs is not None:\n for i in subgs:\n subg = subgs[i]\n parent_nids = F.asnumpy(subg.ndata[dgl.NID])\n sub_ntypes = ntypes[parent_nids]\n print('type0:', np.sum(sub_ntypes == 0))\n print('type1:', np.sum(sub_ntypes == 1))\n print('type2:', np.sum(sub_ntypes == 2))\n\ndef check_metis_partition(g, extra_hops):\n subgs = dgl.transform.metis_partition(g, 4, extra_cached_hops=extra_hops)\n num_inner_nodes = 0\n num_inner_edges = 0\n if subgs is not None:\n for part_id, subg in subgs.items():\n lnode_ids = np.nonzero(F.asnumpy(subg.ndata['inner_node']))[0]\n ledge_ids = np.nonzero(F.asnumpy(subg.edata['inner_edge']))[0]\n num_inner_nodes += len(lnode_ids)\n num_inner_edges += len(ledge_ids)\n assert np.sum(F.asnumpy(subg.ndata['part_id']) == part_id) == len(lnode_ids)\n assert num_inner_nodes == g.number_of_nodes()\n print(g.number_of_edges() - num_inner_edges)\n\n if extra_hops == 0:\n return\n\n # partitions with node reshuffling\n subgs = dgl.transform.metis_partition(g, 4, extra_cached_hops=extra_hops, reshuffle=True)\n num_inner_nodes = 0\n num_inner_edges = 0\n edge_cnts = np.zeros((g.number_of_edges(),))\n if subgs is not None:\n for part_id, subg in subgs.items():\n lnode_ids = np.nonzero(F.asnumpy(subg.ndata['inner_node']))[0]\n ledge_ids = np.nonzero(F.asnumpy(subg.edata['inner_edge']))[0]\n num_inner_nodes += len(lnode_ids)\n num_inner_edges += len(ledge_ids)\n assert np.sum(F.asnumpy(subg.ndata['part_id']) == part_id) == len(lnode_ids)\n nids = F.asnumpy(subg.ndata[dgl.NID])\n\n # ensure the local node Ids are contiguous.\n parent_ids = F.asnumpy(subg.ndata[dgl.NID])\n parent_ids = parent_ids[:len(lnode_ids)]\n assert np.all(parent_ids == np.arange(parent_ids[0], parent_ids[-1] + 1))\n\n # count the local edges.\n parent_ids = F.asnumpy(subg.edata[dgl.EID])[ledge_ids]\n edge_cnts[parent_ids] += 1\n\n orig_ids = subg.ndata['orig_id']\n inner_node = F.asnumpy(subg.ndata['inner_node'])\n for nid in range(subg.number_of_nodes()):\n neighs = subg.predecessors(nid)\n old_neighs1 = F.gather_row(orig_ids, neighs)\n old_nid = F.asnumpy(orig_ids[nid])\n old_neighs2 = g.predecessors(old_nid)\n # If this is an inner node, it should have the full neighborhood.\n if inner_node[nid]:\n assert np.all(np.sort(F.asnumpy(old_neighs1)) == np.sort(F.asnumpy(old_neighs2)))\n # Normally, local edges are only counted once.\n assert np.all(edge_cnts == 1)\n\n assert num_inner_nodes == g.number_of_nodes()\n print(g.number_of_edges() - num_inner_edges)\n\[email protected](F._default_context_str == 'gpu', reason=\"It doesn't support GPU\")\ndef test_reorder_nodes():\n g = dgl.DGLGraph(create_large_graph_index(1000), readonly=True)\n new_nids = np.random.permutation(g.number_of_nodes())\n # TODO(zhengda) we need to test both CSR and COO.\n new_g = dgl.transform.reorder_nodes(g, new_nids)\n new_in_deg = new_g.in_degrees()\n new_out_deg = new_g.out_degrees()\n in_deg = g.in_degrees()\n out_deg = g.out_degrees()\n new_in_deg1 = F.scatter_row(in_deg, F.tensor(new_nids), in_deg)\n new_out_deg1 = F.scatter_row(out_deg, F.tensor(new_nids), out_deg)\n assert np.all(F.asnumpy(new_in_deg == new_in_deg1))\n assert np.all(F.asnumpy(new_out_deg == new_out_deg1))\n orig_ids = F.asnumpy(new_g.ndata['orig_id'])\n for nid in range(g.number_of_nodes()):\n neighs = F.asnumpy(g.successors(nid))\n new_neighs1 = new_nids[neighs]\n new_nid = new_nids[nid]\n new_neighs2 = new_g.successors(new_nid)\n assert np.all(np.sort(new_neighs1) == np.sort(F.asnumpy(new_neighs2)))\n\n for nid in range(new_g.number_of_nodes()):\n neighs = F.asnumpy(new_g.successors(nid))\n old_neighs1 = orig_ids[neighs]\n old_nid = orig_ids[nid]\n old_neighs2 = g.successors(old_nid)\n assert np.all(np.sort(old_neighs1) == np.sort(F.asnumpy(old_neighs2)))\n\n neighs = F.asnumpy(new_g.predecessors(nid))\n old_neighs1 = orig_ids[neighs]\n old_nid = orig_ids[nid]\n old_neighs2 = g.predecessors(old_nid)\n assert np.all(np.sort(old_neighs1) == np.sort(F.asnumpy(old_neighs2)))\n\[email protected](F._default_context_str == 'gpu', reason=\"GPU not implemented\")\n@parametrize_dtype\ndef test_in_subgraph(index_dtype):\n g1 = dgl.graph([(1,0),(2,0),(3,0),(0,1),(2,1),(3,1),(0,2)], 'user', 'follow', index_dtype=index_dtype)\n g2 = dgl.bipartite([(0,0),(0,1),(1,2),(3,2)], 'user', 'play', 'game', index_dtype=index_dtype)\n g3 = dgl.bipartite([(2,0),(2,1),(2,2),(1,0),(1,3),(0,0)], 'game', 'liked-by', 'user', index_dtype=index_dtype)\n g4 = dgl.bipartite([(0,0),(1,0),(2,0),(3,0)], 'user', 'flips', 'coin', index_dtype=index_dtype)\n hg = dgl.hetero_from_relations([g1, g2, g3, g4])\n subg = dgl.in_subgraph(hg, {'user' : [0,1], 'game' : 0})\n assert subg._idtype_str == index_dtype\n assert len(subg.ntypes) == 3\n assert len(subg.etypes) == 4\n u, v = subg['follow'].edges()\n edge_set = set(zip(list(F.asnumpy(u)), list(F.asnumpy(v))))\n assert F.array_equal(hg['follow'].edge_ids(u, v), subg['follow'].edata[dgl.EID])\n assert edge_set == {(1,0),(2,0),(3,0),(0,1),(2,1),(3,1)}\n u, v = subg['play'].edges()\n edge_set = set(zip(list(F.asnumpy(u)), list(F.asnumpy(v))))\n assert F.array_equal(hg['play'].edge_ids(u, v), subg['play'].edata[dgl.EID])\n assert edge_set == {(0,0)}\n u, v = subg['liked-by'].edges()\n edge_set = set(zip(list(F.asnumpy(u)), list(F.asnumpy(v))))\n assert F.array_equal(hg['liked-by'].edge_ids(u, v), subg['liked-by'].edata[dgl.EID])\n assert edge_set == {(2,0),(2,1),(1,0),(0,0)}\n assert subg['flips'].number_of_edges() == 0\n\[email protected](F._default_context_str == 'gpu', reason=\"GPU not implemented\")\n@parametrize_dtype\ndef test_out_subgraph(index_dtype):\n g1 = dgl.graph([(1,0),(2,0),(3,0),(0,1),(2,1),(3,1),(0,2)], 'user', 'follow', index_dtype=index_dtype)\n g2 = dgl.bipartite([(0,0),(0,1),(1,2),(3,2)], 'user', 'play', 'game', index_dtype=index_dtype)\n g3 = dgl.bipartite([(2,0),(2,1),(2,2),(1,0),(1,3),(0,0)], 'game', 'liked-by', 'user', index_dtype=index_dtype)\n g4 = dgl.bipartite([(0,0),(1,0),(2,0),(3,0)], 'user', 'flips', 'coin', index_dtype=index_dtype)\n hg = dgl.hetero_from_relations([g1, g2, g3, g4])\n subg = dgl.out_subgraph(hg, {'user' : [0,1], 'game' : 0})\n assert subg._idtype_str == index_dtype\n assert len(subg.ntypes) == 3\n assert len(subg.etypes) == 4\n u, v = subg['follow'].edges()\n edge_set = set(zip(list(F.asnumpy(u)), list(F.asnumpy(v))))\n assert edge_set == {(1,0),(0,1),(0,2)}\n assert F.array_equal(hg['follow'].edge_ids(u, v), subg['follow'].edata[dgl.EID])\n u, v = subg['play'].edges()\n edge_set = set(zip(list(F.asnumpy(u)), list(F.asnumpy(v))))\n assert edge_set == {(0,0),(0,1),(1,2)}\n assert F.array_equal(hg['play'].edge_ids(u, v), subg['play'].edata[dgl.EID])\n u, v = subg['liked-by'].edges()\n edge_set = set(zip(list(F.asnumpy(u)), list(F.asnumpy(v))))\n assert edge_set == {(0,0)}\n assert F.array_equal(hg['liked-by'].edge_ids(u, v), subg['liked-by'].edata[dgl.EID])\n u, v = subg['flips'].edges()\n edge_set = set(zip(list(F.asnumpy(u)), list(F.asnumpy(v))))\n assert edge_set == {(0,0),(1,0)}\n assert F.array_equal(hg['flips'].edge_ids(u, v), subg['flips'].edata[dgl.EID])\n\[email protected](F._default_context_str == 'gpu', reason=\"GPU compaction not implemented\")\n@parametrize_dtype\ndef test_compact(index_dtype):\n g1 = dgl.heterograph({\n ('user', 'follow', 'user'): [(1, 3), (3, 5)],\n ('user', 'plays', 'game'): [(2, 4), (3, 4), (2, 5)],\n ('game', 'wished-by', 'user'): [(6, 7), (5, 7)]},\n {'user': 20, 'game': 10}, index_dtype=index_dtype)\n\n g2 = dgl.heterograph({\n ('game', 'clicked-by', 'user'): [(3, 1)],\n ('user', 'likes', 'user'): [(1, 8), (8, 9)]},\n {'user': 20, 'game': 10}, index_dtype=index_dtype)\n\n g3 = dgl.graph([(0, 1), (1, 2)], num_nodes=10, ntype='user', index_dtype=index_dtype)\n g4 = dgl.graph([(1, 3), (3, 5)], num_nodes=10, ntype='user', index_dtype=index_dtype)\n\n def _check(g, new_g, induced_nodes):\n assert g.ntypes == new_g.ntypes\n assert g.canonical_etypes == new_g.canonical_etypes\n\n for ntype in g.ntypes:\n assert -1 not in induced_nodes[ntype]\n\n for etype in g.canonical_etypes:\n g_src, g_dst = g.all_edges(order='eid', etype=etype)\n g_src = F.asnumpy(g_src)\n g_dst = F.asnumpy(g_dst)\n new_g_src, new_g_dst = new_g.all_edges(order='eid', etype=etype)\n new_g_src_mapped = induced_nodes[etype[0]][F.asnumpy(new_g_src)]\n new_g_dst_mapped = induced_nodes[etype[2]][F.asnumpy(new_g_dst)]\n assert (g_src == new_g_src_mapped).all()\n assert (g_dst == new_g_dst_mapped).all()\n\n # Test default\n new_g1 = dgl.compact_graphs(g1)\n induced_nodes = {ntype: new_g1.nodes[ntype].data[dgl.NID] for ntype in new_g1.ntypes}\n induced_nodes = {k: F.asnumpy(v) for k, v in induced_nodes.items()}\n assert new_g1._idtype_str == index_dtype\n assert set(induced_nodes['user']) == set([1, 3, 5, 2, 7])\n assert set(induced_nodes['game']) == set([4, 5, 6])\n _check(g1, new_g1, induced_nodes)\n\n # Test with always_preserve given a dict\n new_g1 = dgl.compact_graphs(\n g1, always_preserve={'game': F.tensor([4, 7], dtype=getattr(F, index_dtype))})\n assert new_g1._idtype_str == index_dtype\n induced_nodes = {ntype: new_g1.nodes[ntype].data[dgl.NID] for ntype in new_g1.ntypes}\n induced_nodes = {k: F.asnumpy(v) for k, v in induced_nodes.items()}\n assert set(induced_nodes['user']) == set([1, 3, 5, 2, 7])\n assert set(induced_nodes['game']) == set([4, 5, 6, 7])\n _check(g1, new_g1, induced_nodes)\n\n # Test with always_preserve given a tensor\n new_g3 = dgl.compact_graphs(\n g3, always_preserve=F.tensor([1, 7], dtype=getattr(F, index_dtype)))\n induced_nodes = {ntype: new_g3.nodes[ntype].data[dgl.NID] for ntype in new_g3.ntypes}\n induced_nodes = {k: F.asnumpy(v) for k, v in induced_nodes.items()}\n\n assert new_g3._idtype_str == index_dtype\n assert set(induced_nodes['user']) == set([0, 1, 2, 7])\n _check(g3, new_g3, induced_nodes)\n\n # Test multiple graphs\n new_g1, new_g2 = dgl.compact_graphs([g1, g2])\n induced_nodes = {ntype: new_g1.nodes[ntype].data[dgl.NID] for ntype in new_g1.ntypes}\n induced_nodes = {k: F.asnumpy(v) for k, v in induced_nodes.items()}\n assert new_g1._idtype_str == index_dtype\n assert new_g2._idtype_str == index_dtype\n assert set(induced_nodes['user']) == set([1, 3, 5, 2, 7, 8, 9])\n assert set(induced_nodes['game']) == set([3, 4, 5, 6])\n _check(g1, new_g1, induced_nodes)\n _check(g2, new_g2, induced_nodes)\n\n # Test multiple graphs with always_preserve given a dict\n new_g1, new_g2 = dgl.compact_graphs(\n [g1, g2], always_preserve={'game': F.tensor([4, 7], dtype=getattr(F, index_dtype))})\n induced_nodes = {ntype: new_g1.nodes[ntype].data[dgl.NID] for ntype in new_g1.ntypes}\n induced_nodes = {k: F.asnumpy(v) for k, v in induced_nodes.items()}\n assert new_g1._idtype_str == index_dtype\n assert new_g2._idtype_str == index_dtype\n assert set(induced_nodes['user']) == set([1, 3, 5, 2, 7, 8, 9])\n assert set(induced_nodes['game']) == set([3, 4, 5, 6, 7])\n _check(g1, new_g1, induced_nodes)\n _check(g2, new_g2, induced_nodes)\n\n # Test multiple graphs with always_preserve given a tensor\n new_g3, new_g4 = dgl.compact_graphs(\n [g3, g4], always_preserve=F.tensor([1, 7], dtype=getattr(F, index_dtype)))\n induced_nodes = {ntype: new_g3.nodes[ntype].data[dgl.NID] for ntype in new_g3.ntypes}\n induced_nodes = {k: F.asnumpy(v) for k, v in induced_nodes.items()}\n\n assert new_g3._idtype_str == index_dtype\n assert new_g4._idtype_str == index_dtype\n assert set(induced_nodes['user']) == set([0, 1, 2, 3, 5, 7])\n _check(g3, new_g3, induced_nodes)\n _check(g4, new_g4, induced_nodes)\n\[email protected](F._default_context_str == 'gpu', reason=\"GPU to simple not implemented\")\n@parametrize_dtype\ndef test_to_simple(index_dtype):\n # homogeneous graph\n g = dgl.graph((F.tensor([0, 1, 2, 1]), F.tensor([1, 2, 0, 2])))\n g.ndata['h'] = F.tensor([[0.], [1.], [2.]])\n g.edata['h'] = F.tensor([[3.], [4.], [5.], [6.]])\n sg, wb = dgl.to_simple(g, writeback_mapping=True)\n u, v = g.all_edges(form='uv', order='eid')\n u = F.asnumpy(u).tolist()\n v = F.asnumpy(v).tolist()\n uv = list(zip(u, v))\n eid_map = F.asnumpy(wb)\n\n su, sv = sg.all_edges(form='uv', order='eid')\n su = F.asnumpy(su).tolist()\n sv = F.asnumpy(sv).tolist()\n suv = list(zip(su, sv))\n sc = F.asnumpy(sg.edata['count'])\n assert set(uv) == set(suv)\n for i, e in enumerate(suv):\n assert sc[i] == sum(e == _e for _e in uv)\n for i, e in enumerate(uv):\n assert eid_map[i] == suv.index(e)\n # shared ndata\n assert F.array_equal(sg.ndata['h'], g.ndata['h'])\n assert 'h' not in sg.edata\n # new ndata to sg\n sg.ndata['hh'] = F.tensor([[0.], [1.], [2.]])\n assert 'hh' not in g.ndata\n\n sg = dgl.to_simple(g, writeback_mapping=False, copy_ndata=False)\n assert 'h' not in sg.ndata\n assert 'h' not in sg.edata\n\n # heterogeneous graph\n g = dgl.heterograph({\n ('user', 'follow', 'user'): ([0, 1, 2, 1, 1, 1],\n [1, 3, 2, 3, 4, 4]),\n ('user', 'plays', 'game'): ([3, 2, 1, 1, 3, 2, 2], [5, 3, 4, 4, 5, 3, 3])},\n index_dtype=index_dtype)\n g.nodes['user'].data['h'] = F.tensor([0, 1, 2, 3, 4])\n g.nodes['user'].data['hh'] = F.tensor([0, 1, 2, 3, 4])\n g.edges['follow'].data['h'] = F.tensor([0, 1, 2, 3, 4, 5])\n sg, wb = dgl.to_simple(g, return_counts='weights', writeback_mapping=True, copy_edata=True)\n g.nodes['game'].data['h'] = F.tensor([0, 1, 2, 3, 4, 5])\n\n for etype in g.canonical_etypes:\n u, v = g.all_edges(form='uv', order='eid', etype=etype)\n u = F.asnumpy(u).tolist()\n v = F.asnumpy(v).tolist()\n uv = list(zip(u, v))\n eid_map = F.asnumpy(wb[etype])\n\n su, sv = sg.all_edges(form='uv', order='eid', etype=etype)\n su = F.asnumpy(su).tolist()\n sv = F.asnumpy(sv).tolist()\n suv = list(zip(su, sv))\n sw = F.asnumpy(sg.edges[etype].data['weights'])\n\n assert set(uv) == set(suv)\n for i, e in enumerate(suv):\n assert sw[i] == sum(e == _e for _e in uv)\n for i, e in enumerate(uv):\n assert eid_map[i] == suv.index(e)\n # shared ndata\n assert F.array_equal(sg.nodes['user'].data['h'], g.nodes['user'].data['h'])\n assert F.array_equal(sg.nodes['user'].data['hh'], g.nodes['user'].data['hh'])\n assert 'h' not in sg.nodes['game'].data\n # new ndata to sg\n sg.nodes['user'].data['hhh'] = F.tensor([0, 1, 2, 3, 4])\n assert 'hhh' not in g.nodes['user'].data\n # share edata\n feat_idx = F.asnumpy(wb[('user', 'follow', 'user')])\n _, indices = np.unique(feat_idx, return_index=True)\n assert np.array_equal(F.asnumpy(sg.edges['follow'].data['h']),\n F.asnumpy(g.edges['follow'].data['h'])[indices])\n\n sg = dgl.to_simple(g, writeback_mapping=False, copy_ndata=False)\n for ntype in g.ntypes:\n assert g.number_of_nodes(ntype) == sg.number_of_nodes(ntype)\n assert 'h' not in sg.nodes['user'].data\n assert 'hh' not in sg.nodes['user'].data\n\[email protected](F._default_context_str == 'gpu', reason=\"GPU compaction not implemented\")\n@parametrize_dtype\ndef test_to_block(index_dtype):\n def check(g, bg, ntype, etype, dst_nodes, include_dst_in_src=True):\n if dst_nodes is not None:\n assert F.array_equal(bg.dstnodes[ntype].data[dgl.NID], dst_nodes)\n n_dst_nodes = bg.number_of_nodes('DST/' + ntype)\n if include_dst_in_src:\n assert F.array_equal(\n bg.srcnodes[ntype].data[dgl.NID][:n_dst_nodes],\n bg.dstnodes[ntype].data[dgl.NID])\n\n g = g[etype]\n bg = bg[etype]\n induced_src = bg.srcdata[dgl.NID]\n induced_dst = bg.dstdata[dgl.NID]\n induced_eid = bg.edata[dgl.EID]\n bg_src, bg_dst = bg.all_edges(order='eid')\n src_ans, dst_ans = g.all_edges(order='eid')\n\n induced_src_bg = F.gather_row(induced_src, bg_src)\n induced_dst_bg = F.gather_row(induced_dst, bg_dst)\n induced_src_ans = F.gather_row(src_ans, induced_eid)\n induced_dst_ans = F.gather_row(dst_ans, induced_eid)\n\n assert F.array_equal(induced_src_bg, induced_src_ans)\n assert F.array_equal(induced_dst_bg, induced_dst_ans)\n\n def checkall(g, bg, dst_nodes, include_dst_in_src=True):\n for etype in g.etypes:\n ntype = g.to_canonical_etype(etype)[2]\n if dst_nodes is not None and ntype in dst_nodes:\n check(g, bg, ntype, etype, dst_nodes[ntype], include_dst_in_src)\n else:\n check(g, bg, ntype, etype, None, include_dst_in_src)\n\n g = dgl.heterograph({\n ('A', 'AA', 'A'): [(0, 1), (2, 3), (1, 2), (3, 4)],\n ('A', 'AB', 'B'): [(0, 1), (1, 3), (3, 5), (1, 6)],\n ('B', 'BA', 'A'): [(2, 3), (3, 2)]}, index_dtype=index_dtype)\n g.nodes['A'].data['x'] = F.randn((5, 10))\n g.nodes['B'].data['x'] = F.randn((7, 5))\n g.edges['AA'].data['x'] = F.randn((4, 3))\n g.edges['AB'].data['x'] = F.randn((4, 3))\n g.edges['BA'].data['x'] = F.randn((2, 3))\n g_a = g['AA']\n\n def check_features(g, bg):\n for ntype in bg.srctypes:\n for key in g.nodes[ntype].data:\n assert F.array_equal(\n bg.srcnodes[ntype].data[key],\n F.gather_row(g.nodes[ntype].data[key], bg.srcnodes[ntype].data[dgl.NID]))\n for ntype in bg.dsttypes:\n for key in g.nodes[ntype].data:\n assert F.array_equal(\n bg.dstnodes[ntype].data[key],\n F.gather_row(g.nodes[ntype].data[key], bg.dstnodes[ntype].data[dgl.NID]))\n for etype in bg.canonical_etypes:\n for key in g.edges[etype].data:\n assert F.array_equal(\n bg.edges[etype].data[key],\n F.gather_row(g.edges[etype].data[key], bg.edges[etype].data[dgl.EID]))\n\n bg = dgl.to_block(g_a)\n check(g_a, bg, 'A', 'AA', None)\n check_features(g_a, bg)\n assert bg.number_of_src_nodes() == 5\n assert bg.number_of_dst_nodes() == 4\n\n bg = dgl.to_block(g_a, include_dst_in_src=False)\n check(g_a, bg, 'A', 'AA', None, False)\n check_features(g_a, bg)\n assert bg.number_of_src_nodes() == 4\n assert bg.number_of_dst_nodes() == 4\n\n dst_nodes = F.tensor([4, 3, 2, 1], dtype=getattr(F, index_dtype))\n bg = dgl.to_block(g_a, dst_nodes)\n check(g_a, bg, 'A', 'AA', dst_nodes)\n check_features(g_a, bg)\n\n g_ab = g['AB']\n\n bg = dgl.to_block(g_ab)\n assert bg._idtype_str == index_dtype\n assert bg.number_of_nodes('SRC/B') == 4\n assert F.array_equal(bg.srcnodes['B'].data[dgl.NID], bg.dstnodes['B'].data[dgl.NID])\n assert bg.number_of_nodes('DST/A') == 0\n checkall(g_ab, bg, None)\n check_features(g_ab, bg)\n\n dst_nodes = {'B': F.tensor([5, 6, 3, 1], dtype=getattr(F, index_dtype))}\n bg = dgl.to_block(g, dst_nodes)\n assert bg.number_of_nodes('SRC/B') == 4\n assert F.array_equal(bg.srcnodes['B'].data[dgl.NID], bg.dstnodes['B'].data[dgl.NID])\n assert bg.number_of_nodes('DST/A') == 0\n checkall(g, bg, dst_nodes)\n check_features(g, bg)\n\n dst_nodes = {'A': F.tensor([4, 3, 2, 1], dtype=getattr(F, index_dtype)), 'B': F.tensor([3, 5, 6, 1], dtype=getattr(F, index_dtype))}\n bg = dgl.to_block(g, dst_nodes=dst_nodes)\n checkall(g, bg, dst_nodes)\n check_features(g, bg)\n\[email protected](F._default_context_str == 'gpu', reason=\"GPU not implemented\")\n@parametrize_dtype\ndef test_remove_edges(index_dtype):\n def check(g1, etype, g, edges_removed):\n src, dst, eid = g.edges(etype=etype, form='all')\n src1, dst1 = g1.edges(etype=etype, order='eid')\n if etype is not None:\n eid1 = g1.edges[etype].data[dgl.EID]\n else:\n eid1 = g1.edata[dgl.EID]\n src1 = F.asnumpy(src1)\n dst1 = F.asnumpy(dst1)\n eid1 = F.asnumpy(eid1)\n src = F.asnumpy(src)\n dst = F.asnumpy(dst)\n eid = F.asnumpy(eid)\n sde_set = set(zip(src, dst, eid))\n\n for s, d, e in zip(src1, dst1, eid1):\n assert (s, d, e) in sde_set\n assert not np.isin(edges_removed, eid1).any()\n assert g1.idtype == g.idtype\n\n for fmt in ['coo', 'csr', 'csc']:\n for edges_to_remove in [[2], [2, 2], [3, 2], [1, 3, 1, 2]]:\n g = dgl.graph([(0, 1), (2, 3), (1, 2), (3, 4)], restrict_format=fmt, index_dtype=index_dtype)\n g1 = dgl.remove_edges(g, F.tensor(edges_to_remove, getattr(F, index_dtype)))\n check(g1, None, g, edges_to_remove)\n\n g = dgl.graph(\n spsp.csr_matrix(([1, 1, 1, 1], ([0, 2, 1, 3], [1, 3, 2, 4])), shape=(5, 5)),\n restrict_format=fmt, index_dtype=index_dtype)\n g1 = dgl.remove_edges(g, F.tensor(edges_to_remove, getattr(F, index_dtype)))\n check(g1, None, g, edges_to_remove)\n\n g = dgl.heterograph({\n ('A', 'AA', 'A'): [(0, 1), (2, 3), (1, 2), (3, 4)],\n ('A', 'AB', 'B'): [(0, 1), (1, 3), (3, 5), (1, 6)],\n ('B', 'BA', 'A'): [(2, 3), (3, 2)]}, index_dtype=index_dtype)\n g2 = dgl.remove_edges(g, {'AA': F.tensor([2], getattr(F, index_dtype)), 'AB': F.tensor([3], getattr(F, index_dtype)), 'BA': F.tensor([1], getattr(F, index_dtype))})\n check(g2, 'AA', g, [2])\n check(g2, 'AB', g, [3])\n check(g2, 'BA', g, [1])\n\n g3 = dgl.remove_edges(g, {'AA': F.tensor([], getattr(F, index_dtype)), 'AB': F.tensor([3], getattr(F, index_dtype)), 'BA': F.tensor([1], getattr(F, index_dtype))})\n check(g3, 'AA', g, [])\n check(g3, 'AB', g, [3])\n check(g3, 'BA', g, [1])\n\n g4 = dgl.remove_edges(g, {'AB': F.tensor([3, 1, 2, 0], getattr(F, index_dtype))})\n check(g4, 'AA', g, [])\n check(g4, 'AB', g, [3, 1, 2, 0])\n check(g4, 'BA', g, [])\n\ndef test_cast():\n m = spsp.coo_matrix(([1, 1], ([0, 1], [1, 2])), (4, 4))\n g = dgl.DGLGraph(m, readonly=True)\n gsrc, gdst = g.edges(order='eid')\n ndata = F.randn((4, 5))\n edata = F.randn((2, 4))\n g.ndata['x'] = ndata\n g.edata['y'] = edata\n\n hg = dgl.as_heterograph(g, 'A', 'AA')\n assert hg.ntypes == ['A']\n assert hg.etypes == ['AA']\n assert hg.canonical_etypes == [('A', 'AA', 'A')]\n assert hg.number_of_nodes() == 4\n assert hg.number_of_edges() == 2\n hgsrc, hgdst = hg.edges(order='eid')\n assert F.array_equal(gsrc, hgsrc)\n assert F.array_equal(gdst, hgdst)\n\n g2 = dgl.as_immutable_graph(hg)\n assert g2.number_of_nodes() == 4\n assert g2.number_of_edges() == 2\n g2src, g2dst = hg.edges(order='eid')\n assert F.array_equal(g2src, gsrc)\n assert F.array_equal(g2dst, gdst)\n\nif __name__ == '__main__':\n # test_reorder_nodes()\n # test_line_graph()\n # test_no_backtracking()\n # test_reverse()\n # test_reverse_shared_frames()\n # test_to_bidirected()\n # test_simple_graph()\n # test_bidirected_graph()\n # test_khop_adj()\n # test_khop_graph()\n # test_laplacian_lambda_max()\n # test_remove_self_loop()\n # test_add_self_loop()\n # test_partition_with_halo()\n test_metis_partition()\n test_hetero_metis_partition()\n # test_hetero_linegraph('int32')\n # test_compact()\n # test_to_simple(\"int32\")\n # test_in_subgraph(\"int32\")\n # test_out_subgraph()\n # test_to_block(\"int32\")\n # test_remove_edges()\n" ]
[ [ "numpy.sum", "numpy.sort", "numpy.argsort", "numpy.random.choice", "scipy.sparse.csr_matrix", "numpy.arange", "scipy.sparse.coo_matrix", "numpy.isin", "numpy.all", "numpy.array", "numpy.nonzero", "numpy.unique" ] ]
iLuSIAnn/test
[ "10d0a20dc1a646b5c1f6c7bff2960e3f5df0510e" ]
[ "tests/sandbox/.venv_ccf_sandbox/lib/python3.8/site-packages/sklearn/base.py" ]
[ "\"\"\"\nBase classes for all estimators.\n\nUsed for VotingClassifier\n\"\"\"\n\n# Author: Gael Varoquaux <[email protected]>\n# License: BSD 3 clause\n\nimport copy\nimport warnings\nfrom collections import defaultdict\nimport platform\nimport inspect\nimport re\n\nimport numpy as np\n\nfrom . import __version__\nfrom ._config import get_config\nfrom .utils import _IS_32BIT\nfrom .utils.validation import check_X_y\nfrom .utils.validation import check_array\nfrom .utils._estimator_html_repr import estimator_html_repr\nfrom .utils.validation import _deprecate_positional_args\n\n_DEFAULT_TAGS = {\n 'non_deterministic': False,\n 'requires_positive_X': False,\n 'requires_positive_y': False,\n 'X_types': ['2darray'],\n 'poor_score': False,\n 'no_validation': False,\n 'multioutput': False,\n \"allow_nan\": False,\n 'stateless': False,\n 'multilabel': False,\n '_skip_test': False,\n '_xfail_checks': False,\n 'multioutput_only': False,\n 'binary_only': False,\n 'requires_fit': True,\n 'requires_y': False,\n }\n\n\n@_deprecate_positional_args\ndef clone(estimator, *, safe=True):\n \"\"\"Constructs a new estimator with the same parameters.\n\n Clone does a deep copy of the model in an estimator\n without actually copying attached data. It yields a new estimator\n with the same parameters that has not been fit on any data.\n\n Parameters\n ----------\n estimator : {list, tuple, set} of estimator objects or estimator object\n The estimator or group of estimators to be cloned.\n\n safe : bool, default=True\n If safe is false, clone will fall back to a deep copy on objects\n that are not estimators.\n\n \"\"\"\n estimator_type = type(estimator)\n # XXX: not handling dictionaries\n if estimator_type in (list, tuple, set, frozenset):\n return estimator_type([clone(e, safe=safe) for e in estimator])\n elif not hasattr(estimator, 'get_params') or isinstance(estimator, type):\n if not safe:\n return copy.deepcopy(estimator)\n else:\n if isinstance(estimator, type):\n raise TypeError(\"Cannot clone object. \" +\n \"You should provide an instance of \" +\n \"scikit-learn estimator instead of a class.\")\n else:\n raise TypeError(\"Cannot clone object '%s' (type %s): \"\n \"it does not seem to be a scikit-learn \"\n \"estimator as it does not implement a \"\n \"'get_params' method.\"\n % (repr(estimator), type(estimator)))\n\n klass = estimator.__class__\n new_object_params = estimator.get_params(deep=False)\n for name, param in new_object_params.items():\n new_object_params[name] = clone(param, safe=False)\n new_object = klass(**new_object_params)\n params_set = new_object.get_params(deep=False)\n\n # quick sanity check of the parameters of the clone\n for name in new_object_params:\n param1 = new_object_params[name]\n param2 = params_set[name]\n if param1 is not param2:\n raise RuntimeError('Cannot clone object %s, as the constructor '\n 'either does not set or modifies parameter %s' %\n (estimator, name))\n return new_object\n\n\ndef _pprint(params, offset=0, printer=repr):\n \"\"\"Pretty print the dictionary 'params'\n\n Parameters\n ----------\n params : dict\n The dictionary to pretty print\n\n offset : int, default=0\n The offset in characters to add at the begin of each line.\n\n printer : callable, default=repr\n The function to convert entries to strings, typically\n the builtin str or repr\n\n \"\"\"\n # Do a multi-line justified repr:\n options = np.get_printoptions()\n np.set_printoptions(precision=5, threshold=64, edgeitems=2)\n params_list = list()\n this_line_length = offset\n line_sep = ',\\n' + (1 + offset // 2) * ' '\n for i, (k, v) in enumerate(sorted(params.items())):\n if type(v) is float:\n # use str for representing floating point numbers\n # this way we get consistent representation across\n # architectures and versions.\n this_repr = '%s=%s' % (k, str(v))\n else:\n # use repr of the rest\n this_repr = '%s=%s' % (k, printer(v))\n if len(this_repr) > 500:\n this_repr = this_repr[:300] + '...' + this_repr[-100:]\n if i > 0:\n if (this_line_length + len(this_repr) >= 75 or '\\n' in this_repr):\n params_list.append(line_sep)\n this_line_length = len(line_sep)\n else:\n params_list.append(', ')\n this_line_length += 2\n params_list.append(this_repr)\n this_line_length += len(this_repr)\n\n np.set_printoptions(**options)\n lines = ''.join(params_list)\n # Strip trailing space to avoid nightmare in doctests\n lines = '\\n'.join(l.rstrip(' ') for l in lines.split('\\n'))\n return lines\n\n\nclass BaseEstimator:\n \"\"\"Base class for all estimators in scikit-learn\n\n Notes\n -----\n All estimators should specify all the parameters that can be set\n at the class level in their ``__init__`` as explicit keyword\n arguments (no ``*args`` or ``**kwargs``).\n \"\"\"\n\n @classmethod\n def _get_param_names(cls):\n \"\"\"Get parameter names for the estimator\"\"\"\n # fetch the constructor or the original constructor before\n # deprecation wrapping if any\n init = getattr(cls.__init__, 'deprecated_original', cls.__init__)\n if init is object.__init__:\n # No explicit constructor to introspect\n return []\n\n # introspect the constructor arguments to find the model parameters\n # to represent\n init_signature = inspect.signature(init)\n # Consider the constructor parameters excluding 'self'\n parameters = [p for p in init_signature.parameters.values()\n if p.name != 'self' and p.kind != p.VAR_KEYWORD]\n for p in parameters:\n if p.kind == p.VAR_POSITIONAL:\n raise RuntimeError(\"scikit-learn estimators should always \"\n \"specify their parameters in the signature\"\n \" of their __init__ (no varargs).\"\n \" %s with constructor %s doesn't \"\n \" follow this convention.\"\n % (cls, init_signature))\n # Extract and sort argument names excluding 'self'\n return sorted([p.name for p in parameters])\n\n def get_params(self, deep=True):\n \"\"\"\n Get parameters for this estimator.\n\n Parameters\n ----------\n deep : bool, default=True\n If True, will return the parameters for this estimator and\n contained subobjects that are estimators.\n\n Returns\n -------\n params : mapping of string to any\n Parameter names mapped to their values.\n \"\"\"\n out = dict()\n for key in self._get_param_names():\n try:\n value = getattr(self, key)\n except AttributeError:\n warnings.warn('From version 0.24, get_params will raise an '\n 'AttributeError if a parameter cannot be '\n 'retrieved as an instance attribute. Previously '\n 'it would return None.',\n FutureWarning)\n value = None\n if deep and hasattr(value, 'get_params'):\n deep_items = value.get_params().items()\n out.update((key + '__' + k, val) for k, val in deep_items)\n out[key] = value\n return out\n\n def set_params(self, **params):\n \"\"\"\n Set the parameters of this estimator.\n\n The method works on simple estimators as well as on nested objects\n (such as pipelines). The latter have parameters of the form\n ``<component>__<parameter>`` so that it's possible to update each\n component of a nested object.\n\n Parameters\n ----------\n **params : dict\n Estimator parameters.\n\n Returns\n -------\n self : object\n Estimator instance.\n \"\"\"\n if not params:\n # Simple optimization to gain speed (inspect is slow)\n return self\n valid_params = self.get_params(deep=True)\n\n nested_params = defaultdict(dict) # grouped by prefix\n for key, value in params.items():\n key, delim, sub_key = key.partition('__')\n if key not in valid_params:\n raise ValueError('Invalid parameter %s for estimator %s. '\n 'Check the list of available parameters '\n 'with `estimator.get_params().keys()`.' %\n (key, self))\n\n if delim:\n nested_params[key][sub_key] = value\n else:\n setattr(self, key, value)\n valid_params[key] = value\n\n for key, sub_params in nested_params.items():\n valid_params[key].set_params(**sub_params)\n\n return self\n\n def __repr__(self, N_CHAR_MAX=700):\n # N_CHAR_MAX is the (approximate) maximum number of non-blank\n # characters to render. We pass it as an optional parameter to ease\n # the tests.\n\n from .utils._pprint import _EstimatorPrettyPrinter\n\n N_MAX_ELEMENTS_TO_SHOW = 30 # number of elements to show in sequences\n\n # use ellipsis for sequences with a lot of elements\n pp = _EstimatorPrettyPrinter(\n compact=True, indent=1, indent_at_name=True,\n n_max_elements_to_show=N_MAX_ELEMENTS_TO_SHOW)\n\n repr_ = pp.pformat(self)\n\n # Use bruteforce ellipsis when there are a lot of non-blank characters\n n_nonblank = len(''.join(repr_.split()))\n if n_nonblank > N_CHAR_MAX:\n lim = N_CHAR_MAX // 2 # apprx number of chars to keep on both ends\n regex = r'^(\\s*\\S){%d}' % lim\n # The regex '^(\\s*\\S){%d}' % n\n # matches from the start of the string until the nth non-blank\n # character:\n # - ^ matches the start of string\n # - (pattern){n} matches n repetitions of pattern\n # - \\s*\\S matches a non-blank char following zero or more blanks\n left_lim = re.match(regex, repr_).end()\n right_lim = re.match(regex, repr_[::-1]).end()\n\n if '\\n' in repr_[left_lim:-right_lim]:\n # The left side and right side aren't on the same line.\n # To avoid weird cuts, e.g.:\n # categoric...ore',\n # we need to start the right side with an appropriate newline\n # character so that it renders properly as:\n # categoric...\n # handle_unknown='ignore',\n # so we add [^\\n]*\\n which matches until the next \\n\n regex += r'[^\\n]*\\n'\n right_lim = re.match(regex, repr_[::-1]).end()\n\n ellipsis = '...'\n if left_lim + len(ellipsis) < len(repr_) - right_lim:\n # Only add ellipsis if it results in a shorter repr\n repr_ = repr_[:left_lim] + '...' + repr_[-right_lim:]\n\n return repr_\n\n def __getstate__(self):\n try:\n state = super().__getstate__()\n except AttributeError:\n state = self.__dict__.copy()\n\n if type(self).__module__.startswith('sklearn.'):\n return dict(state.items(), _sklearn_version=__version__)\n else:\n return state\n\n def __setstate__(self, state):\n if type(self).__module__.startswith('sklearn.'):\n pickle_version = state.pop(\"_sklearn_version\", \"pre-0.18\")\n if pickle_version != __version__:\n warnings.warn(\n \"Trying to unpickle estimator {0} from version {1} when \"\n \"using version {2}. This might lead to breaking code or \"\n \"invalid results. Use at your own risk.\".format(\n self.__class__.__name__, pickle_version, __version__),\n UserWarning)\n try:\n super().__setstate__(state)\n except AttributeError:\n self.__dict__.update(state)\n\n def _more_tags(self):\n return _DEFAULT_TAGS\n\n def _get_tags(self):\n collected_tags = {}\n for base_class in reversed(inspect.getmro(self.__class__)):\n if hasattr(base_class, '_more_tags'):\n # need the if because mixins might not have _more_tags\n # but might do redundant work in estimators\n # (i.e. calling more tags on BaseEstimator multiple times)\n more_tags = base_class._more_tags(self)\n collected_tags.update(more_tags)\n return collected_tags\n\n def _check_n_features(self, X, reset):\n \"\"\"Set the `n_features_in_` attribute, or check against it.\n\n Parameters\n ----------\n X : {ndarray, sparse matrix} of shape (n_samples, n_features)\n The input samples.\n reset : bool\n If True, the `n_features_in_` attribute is set to `X.shape[1]`.\n Else, the attribute must already exist and the function checks\n that it is equal to `X.shape[1]`.\n \"\"\"\n n_features = X.shape[1]\n\n if reset:\n self.n_features_in_ = n_features\n else:\n if not hasattr(self, 'n_features_in_'):\n raise RuntimeError(\n \"The reset parameter is False but there is no \"\n \"n_features_in_ attribute. Is this estimator fitted?\"\n )\n if n_features != self.n_features_in_:\n raise ValueError(\n 'X has {} features, but this {} is expecting {} features '\n 'as input.'.format(n_features, self.__class__.__name__,\n self.n_features_in_)\n )\n\n def _validate_data(self, X, y=None, reset=True,\n validate_separately=False, **check_params):\n \"\"\"Validate input data and set or check the `n_features_in_` attribute.\n\n Parameters\n ----------\n X : {array-like, sparse matrix, dataframe} of shape \\\n (n_samples, n_features)\n The input samples.\n y : array-like of shape (n_samples,), default=None\n The targets. If None, `check_array` is called on `X` and\n `check_X_y` is called otherwise.\n reset : bool, default=True\n Whether to reset the `n_features_in_` attribute.\n If False, the input will be checked for consistency with data\n provided when reset was last True.\n validate_separately : False or tuple of dicts, default=False\n Only used if y is not None.\n If False, call validate_X_y(). Else, it must be a tuple of kwargs\n to be used for calling check_array() on X and y respectively.\n **check_params : kwargs\n Parameters passed to :func:`sklearn.utils.check_array` or\n :func:`sklearn.utils.check_X_y`. Ignored if validate_separately\n is not False.\n\n Returns\n -------\n out : {ndarray, sparse matrix} or tuple of these\n The validated input. A tuple is returned if `y` is not None.\n \"\"\"\n\n if y is None:\n if self._get_tags()['requires_y']:\n raise ValueError(\n f\"This {self.__class__.__name__} estimator \"\n f\"requires y to be passed, but the target y is None.\"\n )\n X = check_array(X, **check_params)\n out = X\n else:\n if validate_separately:\n # We need this because some estimators validate X and y\n # separately, and in general, separately calling check_array()\n # on X and y isn't equivalent to just calling check_X_y()\n # :(\n check_X_params, check_y_params = validate_separately\n X = check_array(X, **check_X_params)\n y = check_array(y, **check_y_params)\n else:\n X, y = check_X_y(X, y, **check_params)\n out = X, y\n\n if check_params.get('ensure_2d', True):\n self._check_n_features(X, reset=reset)\n\n return out\n\n @property\n def _repr_html_(self):\n \"\"\"HTML representation of estimator.\n\n This is redundant with the logic of `_repr_mimebundle_`. The latter\n should be favorted in the long term, `_repr_html_` is only\n implemented for consumers who do not interpret `_repr_mimbundle_`.\n \"\"\"\n if get_config()[\"display\"] != 'diagram':\n raise AttributeError(\"_repr_html_ is only defined when the \"\n \"'display' configuration option is set to \"\n \"'diagram'\")\n return self._repr_html_inner\n\n def _repr_html_inner(self):\n \"\"\"This function is returned by the @property `_repr_html_` to make\n `hasattr(estimator, \"_repr_html_\") return `True` or `False` depending\n on `get_config()[\"display\"]`.\n \"\"\"\n return estimator_html_repr(self)\n\n def _repr_mimebundle_(self, **kwargs):\n \"\"\"Mime bundle used by jupyter kernels to display estimator\"\"\"\n output = {\"text/plain\": repr(self)}\n if get_config()[\"display\"] == 'diagram':\n output[\"text/html\"] = estimator_html_repr(self)\n return output\n\n\nclass ClassifierMixin:\n \"\"\"Mixin class for all classifiers in scikit-learn.\"\"\"\n\n _estimator_type = \"classifier\"\n\n def score(self, X, y, sample_weight=None):\n \"\"\"\n Return the mean accuracy on the given test data and labels.\n\n In multi-label classification, this is the subset accuracy\n which is a harsh metric since you require for each sample that\n each label set be correctly predicted.\n\n Parameters\n ----------\n X : array-like of shape (n_samples, n_features)\n Test samples.\n\n y : array-like of shape (n_samples,) or (n_samples, n_outputs)\n True labels for X.\n\n sample_weight : array-like of shape (n_samples,), default=None\n Sample weights.\n\n Returns\n -------\n score : float\n Mean accuracy of self.predict(X) wrt. y.\n \"\"\"\n from .metrics import accuracy_score\n return accuracy_score(y, self.predict(X), sample_weight=sample_weight)\n\n def _more_tags(self):\n return {'requires_y': True}\n\n\nclass RegressorMixin:\n \"\"\"Mixin class for all regression estimators in scikit-learn.\"\"\"\n _estimator_type = \"regressor\"\n\n def score(self, X, y, sample_weight=None):\n \"\"\"Return the coefficient of determination R^2 of the prediction.\n\n The coefficient R^2 is defined as (1 - u/v), where u is the residual\n sum of squares ((y_true - y_pred) ** 2).sum() and v is the total\n sum of squares ((y_true - y_true.mean()) ** 2).sum().\n The best possible score is 1.0 and it can be negative (because the\n model can be arbitrarily worse). A constant model that always\n predicts the expected value of y, disregarding the input features,\n would get a R^2 score of 0.0.\n\n Parameters\n ----------\n X : array-like of shape (n_samples, n_features)\n Test samples. For some estimators this may be a\n precomputed kernel matrix or a list of generic objects instead,\n shape = (n_samples, n_samples_fitted),\n where n_samples_fitted is the number of\n samples used in the fitting for the estimator.\n\n y : array-like of shape (n_samples,) or (n_samples, n_outputs)\n True values for X.\n\n sample_weight : array-like of shape (n_samples,), default=None\n Sample weights.\n\n Returns\n -------\n score : float\n R^2 of self.predict(X) wrt. y.\n\n Notes\n -----\n The R2 score used when calling ``score`` on a regressor uses\n ``multioutput='uniform_average'`` from version 0.23 to keep consistent\n with default value of :func:`~sklearn.metrics.r2_score`.\n This influences the ``score`` method of all the multioutput\n regressors (except for\n :class:`~sklearn.multioutput.MultiOutputRegressor`).\n \"\"\"\n\n from .metrics import r2_score\n y_pred = self.predict(X)\n return r2_score(y, y_pred, sample_weight=sample_weight)\n\n def _more_tags(self):\n return {'requires_y': True}\n\n\nclass ClusterMixin:\n \"\"\"Mixin class for all cluster estimators in scikit-learn.\"\"\"\n _estimator_type = \"clusterer\"\n\n def fit_predict(self, X, y=None):\n \"\"\"\n Perform clustering on X and returns cluster labels.\n\n Parameters\n ----------\n X : array-like of shape (n_samples, n_features)\n Input data.\n\n y : Ignored\n Not used, present for API consistency by convention.\n\n Returns\n -------\n labels : ndarray of shape (n_samples,)\n Cluster labels.\n \"\"\"\n # non-optimized default implementation; override when a better\n # method is possible for a given clustering algorithm\n self.fit(X)\n return self.labels_\n\n\nclass BiclusterMixin:\n \"\"\"Mixin class for all bicluster estimators in scikit-learn\"\"\"\n\n @property\n def biclusters_(self):\n \"\"\"Convenient way to get row and column indicators together.\n\n Returns the ``rows_`` and ``columns_`` members.\n \"\"\"\n return self.rows_, self.columns_\n\n def get_indices(self, i):\n \"\"\"Row and column indices of the i'th bicluster.\n\n Only works if ``rows_`` and ``columns_`` attributes exist.\n\n Parameters\n ----------\n i : int\n The index of the cluster.\n\n Returns\n -------\n row_ind : ndarray, dtype=np.intp\n Indices of rows in the dataset that belong to the bicluster.\n col_ind : ndarray, dtype=np.intp\n Indices of columns in the dataset that belong to the bicluster.\n\n \"\"\"\n rows = self.rows_[i]\n columns = self.columns_[i]\n return np.nonzero(rows)[0], np.nonzero(columns)[0]\n\n def get_shape(self, i):\n \"\"\"Shape of the i'th bicluster.\n\n Parameters\n ----------\n i : int\n The index of the cluster.\n\n Returns\n -------\n shape : tuple (int, int)\n Number of rows and columns (resp.) in the bicluster.\n \"\"\"\n indices = self.get_indices(i)\n return tuple(len(i) for i in indices)\n\n def get_submatrix(self, i, data):\n \"\"\"Return the submatrix corresponding to bicluster `i`.\n\n Parameters\n ----------\n i : int\n The index of the cluster.\n data : array-like\n The data.\n\n Returns\n -------\n submatrix : ndarray\n The submatrix corresponding to bicluster i.\n\n Notes\n -----\n Works with sparse matrices. Only works if ``rows_`` and\n ``columns_`` attributes exist.\n \"\"\"\n from .utils.validation import check_array\n data = check_array(data, accept_sparse='csr')\n row_ind, col_ind = self.get_indices(i)\n return data[row_ind[:, np.newaxis], col_ind]\n\n\nclass TransformerMixin:\n \"\"\"Mixin class for all transformers in scikit-learn.\"\"\"\n\n def fit_transform(self, X, y=None, **fit_params):\n \"\"\"\n Fit to data, then transform it.\n\n Fits transformer to X and y with optional parameters fit_params\n and returns a transformed version of X.\n\n Parameters\n ----------\n X : {array-like, sparse matrix, dataframe} of shape \\\n (n_samples, n_features)\n\n y : ndarray of shape (n_samples,), default=None\n Target values.\n\n **fit_params : dict\n Additional fit parameters.\n\n Returns\n -------\n X_new : ndarray array of shape (n_samples, n_features_new)\n Transformed array.\n \"\"\"\n # non-optimized default implementation; override when a better\n # method is possible for a given clustering algorithm\n if y is None:\n # fit method of arity 1 (unsupervised transformation)\n return self.fit(X, **fit_params).transform(X)\n else:\n # fit method of arity 2 (supervised transformation)\n return self.fit(X, y, **fit_params).transform(X)\n\n\nclass DensityMixin:\n \"\"\"Mixin class for all density estimators in scikit-learn.\"\"\"\n _estimator_type = \"DensityEstimator\"\n\n def score(self, X, y=None):\n \"\"\"Return the score of the model on the data X\n\n Parameters\n ----------\n X : array-like of shape (n_samples, n_features)\n\n y : Ignored\n Not used, present for API consistency by convention.\n\n Returns\n -------\n score : float\n \"\"\"\n pass\n\n\nclass OutlierMixin:\n \"\"\"Mixin class for all outlier detection estimators in scikit-learn.\"\"\"\n _estimator_type = \"outlier_detector\"\n\n def fit_predict(self, X, y=None):\n \"\"\"Perform fit on X and returns labels for X.\n\n Returns -1 for outliers and 1 for inliers.\n\n Parameters\n ----------\n X : {array-like, sparse matrix, dataframe} of shape \\\n (n_samples, n_features)\n\n y : Ignored\n Not used, present for API consistency by convention.\n\n Returns\n -------\n y : ndarray of shape (n_samples,)\n 1 for inliers, -1 for outliers.\n \"\"\"\n # override for transductive outlier detectors like LocalOulierFactor\n return self.fit(X).predict(X)\n\n\nclass MetaEstimatorMixin:\n _required_parameters = [\"estimator\"]\n \"\"\"Mixin class for all meta estimators in scikit-learn.\"\"\"\n\n\nclass MultiOutputMixin:\n \"\"\"Mixin to mark estimators that support multioutput.\"\"\"\n def _more_tags(self):\n return {'multioutput': True}\n\n\nclass _UnstableArchMixin:\n \"\"\"Mark estimators that are non-determinstic on 32bit or PowerPC\"\"\"\n def _more_tags(self):\n return {'non_deterministic': (\n _IS_32BIT or platform.machine().startswith(('ppc', 'powerpc')))}\n\n\ndef is_classifier(estimator):\n \"\"\"Return True if the given estimator is (probably) a classifier.\n\n Parameters\n ----------\n estimator : object\n Estimator object to test.\n\n Returns\n -------\n out : bool\n True if estimator is a classifier and False otherwise.\n \"\"\"\n return getattr(estimator, \"_estimator_type\", None) == \"classifier\"\n\n\ndef is_regressor(estimator):\n \"\"\"Return True if the given estimator is (probably) a regressor.\n\n Parameters\n ----------\n estimator : object\n Estimator object to test.\n\n Returns\n -------\n out : bool\n True if estimator is a regressor and False otherwise.\n \"\"\"\n return getattr(estimator, \"_estimator_type\", None) == \"regressor\"\n\n\ndef is_outlier_detector(estimator):\n \"\"\"Return True if the given estimator is (probably) an outlier detector.\n\n Parameters\n ----------\n estimator : object\n Estimator object to test.\n\n Returns\n -------\n out : bool\n True if estimator is an outlier detector and False otherwise.\n \"\"\"\n return getattr(estimator, \"_estimator_type\", None) == \"outlier_detector\"\n" ]
[ [ "numpy.get_printoptions", "numpy.set_printoptions", "numpy.nonzero" ] ]
realchrisward/RodentPlethysmography
[ "6b27e08a65b4c0b399e5b20173c0d134f5dbca38" ]
[ "calm segment extractor py34 v5 20170918.py" ]
[ "#!usr/bin/env python3\r\n## /\\ compatability line\r\n\r\n## distribution notes - Calm Segment Extractor py34 v4.py\r\n\"\"\"\r\nCalm Segment Extractor by Chris Ward (C) 2015\r\nupdated for python 3.4 compatability by Chris Ward (C) 2016\r\nprovided free for non-commercial/fair use.\r\n\r\nThis program attempts to define periods of calm behavior\r\nby marking contiguous segments below a movement score\r\n(uses the output from the Movement Quantification script)\r\n\r\n\r\n*recommended versions for dependencies*\r\n*matplotlib [1.4.2]\r\n*numpy [1.9.1]\r\n\r\nUser inputs:\r\n*motion scores-tab delimited file containing movements scores by time\r\n*animal information-tab delimited file containing animal information for\r\nthe motion files to be analyzed\r\n*OutFile-name of the txt file to be output by this program\r\n\r\nCustomizable Settings:\r\n*padding - amount of time to subtract from 'calm bouts' to correct for time stamp\r\nand threshold inaccuracies when resumping calm behavior after an active bout\r\n*baseline percentile - percentile of overall motion score considered 'background noise'\r\n*relative threshhold - threshhold relative to baseline used to define calm vs avtive\r\n\r\nOutputs:\r\n*a tab delimited file with ...\r\n -animal information and time segments corresponding to 'calm behavior'\r\n\"\"\"\r\n\r\n## import modules\r\nimport datetime\r\nimport wardcode3 as wardcode\r\nimport matplotlib.pyplot as plt\r\nimport numpy\r\n\r\n## define functions\r\ndef AutoCallSegs(timestamps,movement,pd,bs,rt):\r\n # determin threshold level for movement\r\n timestamps=[float(i) for i in timestamps]\r\n movement=[float(i) for i in movement]\r\n thresh=numpy.percentile(movement,bs)*rt\r\n # calculate intervals above and below theshold\r\n crossings=wardcode.getbelowthresh(movement,thresh)\r\n diffcross=wardcode.getdifflist(crossings)\r\n starts=wardcode.getlistfromfilter(timestamps[1:],diffcross,1)\r\n stops=wardcode.getlistfromfilter(timestamps[1:],diffcross,-1)\r\n if len(starts)<1:starts=[timestamps[0]-1]\r\n if len(stops)<1:stops=[timestamps[-1]+1]\r\n #align lists\r\n if starts[0]>stops[0]:\r\n starts=[timestamps[0]-1]+starts\r\n if starts[-1]>stops[-1]:\r\n stops.append(timestamps[-1])\r\n #populate calmseg tuples and check padding\r\n calmsegs=[]\r\n segdur=[]\r\n for i in range(min(len(starts),len(stops))):\r\n calmsegs.append((starts[i]+pd,stops[i]-pd))\r\n segdur.append((stops[i]-pd)-(starts[i]+pd))\r\n goodsegs=wardcode.getabovethresh(segdur,0)\r\n calmsegsout=wardcode.getlistfromfilter(calmsegs,goodsegs,1)\r\n\r\n return calmsegsout,thresh\r\n \r\n \r\n\r\ndef checkExpActScores(expdict,exp,bs,rt):\r\n # expdict - dictionary containing data\r\n # exp - current experiment\r\n # bs - baseline\r\n # rt - relative threshold\r\n ##\r\n anikey=[int(i) for i in expdict[exp].keys()]\r\n anikey.sort()\r\n spx=int(numpy.ceil(len(anikey)/4))\r\n\r\n if len(anikey)<4:\r\n spy=len(anikey)\r\n else:\r\n spy=int(numpy.ceil(len(anikey)/spx))\r\n \r\n plt.figure(exp)\r\n \r\n for i in range(len(anikey)):\r\n animal=str(anikey[i])\r\n cs=expdict[exp][animal]['auto']['calmsegs']\r\n ts=[float(i) for i in expdict[exp][animal]['data']['timestamp']]\r\n y1=[float(i) for i in expdict[exp][animal]['data']['movement']]\r\n noise=numpy.percentile(y1,bs)\r\n thresh=noise*rt\r\n aniname=expdict[exp][animal]['line']+'-'+expdict[exp][animal]['id']\r\n\r\n plt.subplot(spx,spy,i+1)\r\n \r\n plt.plot(hold=False)\r\n plt.plot(hold=True)\r\n plt.plot((ts[0],ts[-1]),\r\n (thresh,thresh),'y-')\r\n plt.plot(ts,y1,'r-')\r\n plt.plot((ts[0],ts[-1]),\r\n (noise,noise),'b-')\r\n for j in cs:\r\n plt.plot(j,(thresh,thresh),'ko-')\r\n plt.title('|'+str(i+1)+'|'+aniname)\r\n plt.axis([ts[0],ts[-1],0,noise*4])\r\n \r\n plt.show()\r\n\r\n \r\n## define main\r\ndef main():\r\n ## get filenames\r\n # get motion scores\r\n MotionName=wardcode.guiOpenFileName({'title':'Open Motion Score File','filetypes':[('motion','.mtn'),('all files','.*')]})\r\n # get animal information\r\n AnimalName=wardcode.guiOpenFileName({'title':'Open Animal Information File','filetypes':[('animal list','.al'),('all files','.*')]})\r\n # get output filename\r\n outputname=wardcode.guiSaveFileName({'title':'Save Output As...'})\r\n \r\n ## set parameters\r\n PD=wardcode.getInt('pad inactive time by __ seconds:')\r\n BS=wardcode.getInt('consider baseline noise at __ percentile of movement signal (3% recommended)')\r\n RT=wardcode.getFloat('set relative threshold for movement at __ x of baseline noise (1.4x recommended)')\r\n CheckCalls=wardcode.getYN('Check calm segment calls? (y/n)')\r\n \r\n ## get data\r\n MotionDict=wardcode.dataDictUnfold(\r\n wardcode.dataParseTabDelToColumns(\r\n [i.lower() for i in wardcode.dataGrab(MotionName)]\r\n ,0)\r\n )\r\n AnimalDict=wardcode.dataDictUnfold(\r\n wardcode.dataParseTabDelToColumns(\r\n [i.lower() for i in wardcode.dataGrab(AnimalName)]\r\n ,0)\r\n )\r\n\r\n ## convert motion scores and timestamps to numbers\r\n for i in range(len(MotionDict['movement'])):\r\n MotionDict['movement'][i]=float(MotionDict['movement'][i])\r\n MotionDict['timestamp'][i]=float(MotionDict['timestamp'][i])\r\n \r\n ## parse MotionDict into experiment groups\r\n ExpDict={}\r\n # step through experiments to get animal information\r\n for Exp in set(MotionDict['filename']):\r\n ##\r\n print(str(datetime.datetime.now())+' : parsing data : '+Exp)\r\n ExpDict[Exp]={}\r\n CurAniDict={}\r\n CurAniDict[Exp]={}\r\n # populate current experiment animal information\r\n for k in AnimalDict.keys():\r\n CurAniDict[Exp][k]=wardcode.getlistfromfilter(AnimalDict[k],AnimalDict['video filename'],Exp)\r\n # iterate through animals in current video and get info\r\n ##\r\n filefilter=[1 if i==Exp else 0 for i in MotionDict['filename']]\r\n CurExp={}\r\n # populate CurExp dictionary with animal, timestamp, and movement data\r\n for k in ['animal','timestamp','movement']:\r\n CurExp[k]=wardcode.getlistfromfilter(MotionDict[k],filefilter,1)\r\n # grab the data from the current experiment - auto populate animals with motion data using \"set\" passing the current file filter\r\n for animal in set(\r\n wardcode.getlistfromfilter(\r\n MotionDict['animal'],MotionDict['filename'],Exp)\r\n ):\r\n \r\n ExpDict[Exp][animal]={}\r\n ExpDict[Exp][animal]['data']={}\r\n for k in AnimalDict.keys():\r\n try:\r\n ExpDict[Exp][animal][k]=''.join(\r\n wardcode.getlistfromfilter(\r\n CurAniDict[Exp][k],CurAniDict[Exp]['video chamber'],animal)\r\n )\r\n except:\r\n ExpDict[Exp][animal][k]='unk'\r\n animalfilter=[1 if i==animal else 0 for i in CurExp['animal']]\r\n for k in ['timestamp','movement']:#<-MotionDict.keys():\r\n \r\n ExpDict[Exp][animal]['data'][k]=wardcode.getlistfromfilter(\r\n CurExp[k],\r\n animalfilter,\r\n 1)\r\n \r\n ## auto call segments\r\n for Exp in ExpDict:\r\n print(str(datetime.datetime.now())+' : calling calm segs : '+Exp)\r\n for animal in ExpDict[Exp]:\r\n TS=ExpDict[Exp][animal]['data']['timestamp']\r\n ExpDict[Exp][animal]['auto']={'calmsegs':[],'thresh':0}\r\n ExpDict[Exp][animal]['auto']['calmsegs'],ExpDict[Exp][animal]['auto']['thresh']=AutoCallSegs(\r\n TS,ExpDict[Exp][animal]['data']['movement'],PD,BS,RT)\r\n\r\n ExpDict[Exp][animal]['cBS']=BS\r\n ExpDict[Exp][animal]['cRT']=RT\r\n cBS=BS\r\n cRT=RT\r\n \r\n ##\r\n if CheckCalls=='y':\r\n while 1:\r\n checkExpActScores(ExpDict,Exp,cBS,cRT)\r\n if wardcode.getYN('Accept current results (\"N\" to try alternate settings)\\n')=='y':\r\n break\r\n cBS=wardcode.getInt('consider baseline noise at __ percentile of movement signal (3% recommended)')\r\n cRT=wardcode.getFloat('set relative threshold for movement at __ x of baseline noise (1.4x recommended)')\r\n for animal in ExpDict[Exp]:\r\n ExpDict[Exp][animal]['auto']['calmsegs'],ExpDict[Exp][animal]['auto']['thresh']=AutoCallSegs(\r\n TS,ExpDict[Exp][animal]['data']['movement'],PD,cBS,cRT) \r\n ExpDict[Exp][animal]['cBS']=cBS\r\n ExpDict[Exp][animal]['cRT']=cRT\r\n ## prepare header - asciifile, line, id, animalcode, subsegment, mainsegment, start, stop, base, relthresh, absthresh\r\n outheader=(\"{asciifile}\\t{videofile}\\t{line}\\t{idno}\\t{animalcode}\\t{subsegment}\\t{mainsegment}\\t{start}\\t{stop}\\t{base}\\t{relthresh}\\t{absthresh}\".format(\r\n asciifile='asciifile',videofile='videofile',line='line',idno='idno',animalcode='animalcode',\r\n subsegment='subsegment',mainsegment='mainsegment',start='start',stop='stop',\r\n base='base',relthresh='relthresh',absthresh='absthresh'))\r\n ## output data\r\n outlist=[]\r\n outlist.append(outheader)\r\n for Exp in ExpDict:\r\n for animal in ExpDict[Exp]:\r\n for startseg,stopseg in ExpDict[Exp][animal]['auto']['calmsegs']:\r\n nextline=(\"{asciifile}\\t{videofile}\\t{line}\\t{idno}\\t{animalcode}\\t{subsegment}\\t{mainsegment}\\t{start}\\t{stop}\\t{base}\\t{relthresh}\\t{absthresh}\".format(\r\n asciifile=ExpDict[Exp][animal]['filename'],videofile=Exp,\r\n line=ExpDict[Exp][animal]['line'],\r\n idno=ExpDict[Exp][animal]['id'],animalcode=ExpDict[Exp][animal]['chamber'],\r\n subsegment='calm',mainsegment='calm',start=startseg,stop=stopseg,\r\n base=ExpDict[Exp][animal]['cBS'],relthresh=ExpDict[Exp][animal]['cRT'],\r\n absthresh=ExpDict[Exp][animal]['auto']['thresh']))\r\n outlist.append(nextline)\r\n ## write results to output file\r\n with open(outputname+'.seg','w') as f:\r\n f.write('\\n'.join(outlist))\r\n f.close()\r\n \r\n input('finished calm segment extraction...\\npress ENTER to exit')\r\n\r\n## run main\r\nif __name__=='__main__':\r\n main()\r\n" ]
[ [ "matplotlib.pyplot.figure", "matplotlib.pyplot.axis", "matplotlib.pyplot.subplot", "matplotlib.pyplot.show", "matplotlib.pyplot.plot", "numpy.percentile" ] ]
ablotekar/irfu-python
[ "740cb51ca9ce2ab0d62cb6fef3a7a722d430d79e" ]
[ "pyrfu/mms/eis_skymap_combine_sc.py" ]
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# 3rd party imports\nimport numpy as np\nimport xarray as xr\n\n__author__ = \"Louis Richard\"\n__email__ = \"[email protected]\"\n__copyright__ = \"Copyright 2020-2021\"\n__license__ = \"MIT\"\n__version__ = \"2.3.7\"\n__status__ = \"Prototype\"\n\n\ndef _idx_closest(lst0, lst1):\n return [(np.abs(np.asarray(lst0) - k)).argmin() for k in lst1]\n\n\ndef eis_skymap_combine_sc(skymaps):\n r\"\"\"Generate composite skymap from the EIS sensors across the MMS\n spacecraft.\n\n Parameters\n ----------\n skymaps : list of xarray.DataArray\n Skymap distribution for all spacecraft.\n\n Returns\n -------\n out : xarray.Dataset\n Composite skymap distribution\n\n See Also\n --------\n pyrfu.mms.get_eis_allt, pyrfu.mms.eis_pad,\n pyrfu.mms.eis_spec_combine_sc, pyrfu.mms.eis_spec_combine_sc\n\n \"\"\"\n\n # Determine spacecraft with smallest number of time steps to use as\n # reference spacecraft\n time_size = [len(probe.time.data) for probe in skymaps]\n ref_sc_time_size, ref_sc_loc = [np.min(time_size), np.argmin(time_size)]\n ref_probe = skymaps[ref_sc_loc]\n\n # Define common energy grid across EIS instruments\n n_en_chans = [probe.energy.shape[1] for probe in skymaps]\n size_en, loc_ref_en = [np.min(n_en_chans), np.argmin(n_en_chans)]\n ref_energy = skymaps[loc_ref_en].energy.data[0, :]\n\n energy_data, e_plus, e_minu = [[], [], []]\n for probe in skymaps:\n idx = _idx_closest(probe.energy.data[0, :], ref_energy)\n energy_data.append(probe.energy.data[0, idx])\n e_minu.append(probe.attrs[\"energy_dminus\"][idx])\n e_plus.append(probe.attrs[\"energy_dplus\"][idx])\n\n energy_data = np.stack(energy_data)\n common_energy = np.nanmean(energy_data, axis=0)\n common_energy = np.tile(common_energy, (ref_sc_time_size, 1))\n\n #\n e_minu = np.stack(e_minu)\n e_plus = np.stack(e_plus)\n common_minu = np.nanmean(e_minu, axis=0)\n common_plus = np.nanmean(e_plus, axis=0)\n\n # Use azimuthal and elevation angle from reference spacecraft (in\n # practice they are the same for all spacecraft)\n phi = ref_probe.phi.data\n theta = ref_probe.theta.data\n\n allmms_skymap = np.zeros([ref_sc_time_size, size_en, phi.shape[1],\n len(theta), len(skymaps)])\n\n for p, skymap in enumerate(skymaps):\n idx_en = _idx_closest(skymap.energy.data[0, :], common_energy[0, :])\n allmms_skymap[..., p] = skymap.data[:ref_sc_time_size, idx_en, ...]\n\n # Average the four spacecraft\n allmms_skymap_avg = np.nanmean(allmms_skymap, axis=-1)\n\n # Create combined skymap\n out_dict = {\"time\": ref_probe.time.data,\n \"idx0\": range(common_energy.shape[1]),\n \"idx1\": range(phi.shape[1]), \"idx2\": range(len(theta)),\n \"data\": ([\"time\", \"idx0\", \"idx1\", \"idx2\"], allmms_skymap_avg),\n \"energy\": ([\"time\", \"idx0\"], common_energy),\n \"phi\": ([\"time\", \"idx1\"], phi), \"theta\": ([\"idx2\"], theta)}\n\n out = xr.Dataset(out_dict)\n\n out.attrs[\"energy_dminus\"] = common_minu\n out.attrs[\"energy_dplus\"] = common_plus\n\n return out\n" ]
[ [ "numpy.tile", "numpy.nanmean", "numpy.argmin", "numpy.asarray", "numpy.min", "numpy.stack" ] ]
RobertJaro/qt-solar-viewer
[ "dcecdc8040f457abf8d978a5ecbff61396358c32" ]
[ "solarviewer/app/plot.py" ]
[ "from abc import abstractmethod\n\nfrom matplotlib import pyplot as plt\nfrom matplotlib.backends.backend_qt5 import NavigationToolbar2QT\nfrom matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas\nfrom qtpy import QtWidgets\n\nfrom solarviewer.config.base import Viewer, DataModel\nfrom solarviewer.ui.plot import Ui_Plot\nfrom solarviewer.util import executeTask\n\n\nclass PlotWidget(Viewer):\n\n def __init__(self):\n Viewer.__init__(self)\n self.ui = Ui_Plot()\n self.ui.setupUi(self)\n\n self.initMainCanvas()\n self.rendered.clear()\n\n def initMainCanvas(self):\n self.figure = plt.figure()\n self.canvas = FigureCanvas(self.figure)\n self.toolbar = NavigationToolbar2QT(self.canvas, self)\n self.toolbar.setVisible(False)\n FigureCanvas.setSizePolicy(self.canvas,\n QtWidgets.QSizePolicy.Expanding,\n QtWidgets.QSizePolicy.Expanding)\n FigureCanvas.updateGeometry(self.canvas)\n self.canvas.hide()\n self.ui.verticalLayout.addWidget(self.canvas)\n\n def updateModel(self, model: DataModel):\n self._model = model\n self.redraw()\n\n def redraw(self):\n self.rendered.clear()\n self.canvas.hide()\n self.ui.progress.show()\n executeTask(self._redraw, [], self._afterRedraw)\n\n def _redraw(self):\n self.draw(self._model)\n self.canvas.draw()\n\n def _afterRedraw(self):\n self.ui.progress.hide()\n self.canvas.show()\n self.rendered.set()\n\n @abstractmethod\n def draw(self, data_model: DataModel):\n raise NotImplementedError\n" ]
[ [ "matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg", "matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg.updateGeometry", "matplotlib.backends.backend_qt5.NavigationToolbar2QT", "matplotlib.pyplot.figure", "matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg.setSizePolicy" ] ]
ducongju/HRNet
[ "8c6e1580d0410c439d16a9f220bf0ac48fb39e9a" ]
[ "lib/dataset/coco.py" ]
[ "# ------------------------------------------------------------------------------\n# Copyright (c) Microsoft\n# Licensed under the MIT License.\n# Written by Bin Xiao ([email protected])\n# ------------------------------------------------------------------------------\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom collections import defaultdict\nfrom collections import OrderedDict\nimport logging\nimport os\n\nfrom pycocotools.coco import COCO\nfrom pycocotools.cocoeval import COCOeval\n\"\"\"\njson文件:\n1. 以人类可读的格式存储和加载numpy数组。\n2. 存储和加载通用和定制的类实例。\n3. 将日期/时间存储并加载为字典(包括时区)。\n4. 使用OrderedDict保留地图顺序。\n5. 通过以#开头的行来允许json文件中的注释。\n\"\"\"\nimport json_tricks as json\nimport numpy as np\n\nfrom dataset.JointsDataset import JointsDataset\nfrom nms.nms import oks_nms\nfrom nms.nms import soft_oks_nms\n\n\n# TODO makefile用途是什么\nlogger = logging.getLogger(__name__)\n\n\nclass COCODataset(JointsDataset):\n '''\n \"keypoints\": {\n 0: \"nose\",\n 1: \"left_eye\",\n 2: \"right_eye\",\n 3: \"left_ear\",\n 4: \"right_ear\",\n 5: \"left_shoulder\",\n 6: \"right_shoulder\",\n 7: \"left_elbow\",\n 8: \"right_elbow\",\n 9: \"left_wrist\",\n 10: \"right_wrist\",\n 11: \"left_hip\",\n 12: \"right_hip\",\n 13: \"left_knee\",\n 14: \"right_knee\",\n 15: \"left_ankle\",\n 16: \"right_ankle\"\n },\n\t\"skeleton\": [\n [16,14],[14,12],[17,15],[15,13],[12,13],[6,12],[7,13], [6,7],[6,8],\n [7,9],[8,10],[9,11],[2,3],[1,2],[1,3],[2,4],[3,5],[4,6],[5,7]]\n '''\n def __init__(self, cfg, root, image_set, is_train, transform=None):\n super().__init__(cfg, root, image_set, is_train, transform)\n self.nms_thre = cfg.TEST.NMS_THRE\n self.image_thre = cfg.TEST.IMAGE_THRE\n self.soft_nms = cfg.TEST.SOFT_NMS\n self.oks_thre = cfg.TEST.OKS_THRE\n self.in_vis_thre = cfg.TEST.IN_VIS_THRE\n self.bbox_file = cfg.TEST.COCO_BBOX_FILE\n self.use_gt_bbox = cfg.TEST.USE_GT_BBOX\n self.image_width = cfg.MODEL.IMAGE_SIZE[0]\n self.image_height = cfg.MODEL.IMAGE_SIZE[1]\n self.aspect_ratio = self.image_width * 1.0 / self.image_height\n self.pixel_std = 200\n\n self.coco = COCO(self._get_ann_file_keypoint())\n\n # deal with class names\n cats = [cat['name']\n for cat in self.coco.loadCats(self.coco.getCatIds())]\n self.classes = ['__background__'] + cats\n logger.info('=> classes: {}'.format(self.classes))\n self.num_classes = len(self.classes)\n self._class_to_ind = dict(zip(self.classes, range(self.num_classes)))\n self._class_to_coco_ind = dict(zip(cats, self.coco.getCatIds()))\n self._coco_ind_to_class_ind = dict(\n [\n (self._class_to_coco_ind[cls], self._class_to_ind[cls])\n for cls in self.classes[1:]\n ]\n )\n\n # load image file names\n self.image_set_index = self._load_image_set_index()\n self.num_images = len(self.image_set_index)\n logger.info('=> num_images: {}'.format(self.num_images))\n\n self.num_joints = 17\n self.flip_pairs = [[1, 2], [3, 4], [5, 6], [7, 8],\n [9, 10], [11, 12], [13, 14], [15, 16]]\n self.parent_ids = None\n self.upper_body_ids = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)\n self.lower_body_ids = (11, 12, 13, 14, 15, 16)\n\n self.joints_weight = np.array(\n [\n 1., 1., 1., 1., 1., 1., 1., 1.2, 1.2,\n 1.5, 1.5, 1., 1., 1.2, 1.2, 1.5, 1.5\n ],\n dtype=np.float32\n ).reshape((self.num_joints, 1)) # TODO 处理细节: 不同关节设置不同权重\n\n self.db = self._get_db()\n\n if is_train and cfg.DATASET.SELECT_DATA:\n self.db = self.select_data(self.db)\n\n logger.info('=> load {} samples'.format(len(self.db)))\n\n def _get_ann_file_keypoint(self):\n \"\"\" self.root / annotations / person_keypoints_train2017.json \"\"\"\n prefix = 'person_keypoints' \\\n if 'test' not in self.image_set else 'image_info'\n return os.path.join(\n self.root,\n 'annotations',\n prefix + '_' + self.image_set + '.json'\n )\n\n def _load_image_set_index(self):\n \"\"\" image id: int \"\"\"\n image_ids = self.coco.getImgIds()\n return image_ids\n\n def _get_db(self):\n if self.is_train or self.use_gt_bbox:\n # use ground truth bbox\n gt_db = self._load_coco_keypoint_annotations()\n else:\n # use bbox from detection\n gt_db = self._load_coco_person_detection_results()\n return gt_db\n\n def _load_coco_keypoint_annotations(self):\n \"\"\" ground truth bbox and keypoints \"\"\"\n gt_db = []\n for index in self.image_set_index:\n gt_db.extend(self._load_coco_keypoint_annotation_kernal(index))\n return gt_db\n\n def _load_coco_keypoint_annotation_kernal(self, index):\n \"\"\"\n coco ann: [u'segmentation', u'area', u'iscrowd', u'image_id', u'bbox', u'category_id', u'id']\n iscrowd:\n crowd instances are handled by marking their overlaps with all categories to -1\n and later excluded in training\n bbox:\n [x1, y1, w, h]\n :param index: coco image id\n :return: db entry\n \"\"\"\n im_ann = self.coco.loadImgs(index)[0]\n width = im_ann['width']\n height = im_ann['height']\n\n annIds = self.coco.getAnnIds(imgIds=index, iscrowd=False)\n objs = self.coco.loadAnns(annIds)\n\n # sanitize bboxes\n valid_objs = []\n for obj in objs:\n x, y, w, h = obj['bbox']\n x1 = np.max((0, x))\n y1 = np.max((0, y))\n x2 = np.min((width - 1, x1 + np.max((0, w - 1))))\n y2 = np.min((height - 1, y1 + np.max((0, h - 1))))\n if obj['area'] > 0 and x2 >= x1 and y2 >= y1:\n obj['clean_bbox'] = [x1, y1, x2-x1, y2-y1]\n valid_objs.append(obj)\n objs = valid_objs\n\n rec = []\n for obj in objs:\n cls = self._coco_ind_to_class_ind[obj['category_id']]\n if cls != 1:\n continue\n\n # ignore objs without keypoints annotation\n if max(obj['keypoints']) == 0:\n continue\n\n joints_3d = np.zeros((self.num_joints, 3), dtype=np.float)\n joints_3d_vis = np.zeros((self.num_joints, 3), dtype=np.float)\n for ipt in range(self.num_joints):\n joints_3d[ipt, 0] = obj['keypoints'][ipt * 3 + 0]\n joints_3d[ipt, 1] = obj['keypoints'][ipt * 3 + 1]\n joints_3d[ipt, 2] = 0\n t_vis = obj['keypoints'][ipt * 3 + 2]\n if t_vis > 1:\n t_vis = 1\n joints_3d_vis[ipt, 0] = t_vis\n joints_3d_vis[ipt, 1] = t_vis\n joints_3d_vis[ipt, 2] = 0\n\n center, scale = self._box2cs(obj['clean_bbox'][:4])\n rec.append({\n 'image': self.image_path_from_index(index),\n 'center': center,\n 'scale': scale,\n 'joints_3d': joints_3d,\n 'joints_3d_vis': joints_3d_vis,\n 'filename': '',\n 'imgnum': 0,\n })\n\n return rec\n\n def _box2cs(self, box):\n x, y, w, h = box[:4]\n return self._xywh2cs(x, y, w, h)\n\n def _xywh2cs(self, x, y, w, h):\n center = np.zeros((2), dtype=np.float32)\n center[0] = x + w * 0.5\n center[1] = y + h * 0.5\n\n if w > self.aspect_ratio * h:\n h = w * 1.0 / self.aspect_ratio\n elif w < self.aspect_ratio * h:\n w = h * self.aspect_ratio\n scale = np.array(\n [w * 1.0 / self.pixel_std, h * 1.0 / self.pixel_std],\n dtype=np.float32)\n if center[0] != -1:\n scale = scale * 1.25\n\n return center, scale\n\n def image_path_from_index(self, index):\n \"\"\" example: images / train2017 / 000000119993.jpg \"\"\"\n file_name = '%012d.jpg' % index\n if '2014' in self.image_set:\n file_name = 'COCO_%s_' % self.image_set + file_name\n\n prefix = 'test2017' if 'test' in self.image_set else self.image_set\n\n data_name = prefix + '.zip@' if self.data_format == 'zip' else prefix\n\n image_path = os.path.join(\n self.root, 'images', data_name, file_name)\n\n return image_path\n\n def _load_coco_person_detection_results(self):\n all_boxes = None\n with open(self.bbox_file, 'r') as f:\n all_boxes = json.load(f)\n\n if not all_boxes:\n logger.error('=> Load %s fail!' % self.bbox_file)\n return None\n\n logger.info('=> Total boxes: {}'.format(len(all_boxes)))\n\n kpt_db = []\n num_boxes = 0\n for n_img in range(0, len(all_boxes)):\n det_res = all_boxes[n_img]\n if det_res['category_id'] != 1:\n continue\n img_name = self.image_path_from_index(det_res['image_id'])\n box = det_res['bbox']\n score = det_res['score']\n\n if score < self.image_thre:\n continue\n\n num_boxes = num_boxes + 1\n\n center, scale = self._box2cs(box)\n joints_3d = np.zeros((self.num_joints, 3), dtype=np.float)\n joints_3d_vis = np.ones(\n (self.num_joints, 3), dtype=np.float)\n kpt_db.append({\n 'image': img_name,\n 'center': center,\n 'scale': scale,\n 'score': score,\n 'joints_3d': joints_3d,\n 'joints_3d_vis': joints_3d_vis,\n })\n\n logger.info('=> Total boxes after fliter low score@{}: {}'.format(\n self.image_thre, num_boxes))\n return kpt_db\n\n def evaluate(self, cfg, preds, output_dir, all_boxes, img_path,\n *args, **kwargs):\n rank = cfg.RANK\n\n res_folder = os.path.join(output_dir, 'results')\n if not os.path.exists(res_folder):\n try:\n os.makedirs(res_folder)\n except Exception:\n logger.error('Fail to make {}'.format(res_folder))\n\n res_file = os.path.join(\n res_folder, 'keypoints_{}_results_{}.json'.format(\n self.image_set, rank)\n )\n\n # person x (keypoints)\n _kpts = []\n for idx, kpt in enumerate(preds):\n _kpts.append({\n 'keypoints': kpt,\n 'center': all_boxes[idx][0:2],\n 'scale': all_boxes[idx][2:4],\n 'area': all_boxes[idx][4],\n 'score': all_boxes[idx][5],\n 'image': int(img_path[idx][-16:-4])\n })\n # image x person x (keypoints)\n kpts = defaultdict(list)\n for kpt in _kpts:\n kpts[kpt['image']].append(kpt)\n\n # rescoring and oks nms\n num_joints = self.num_joints\n in_vis_thre = self.in_vis_thre\n oks_thre = self.oks_thre\n oks_nmsed_kpts = []\n for img in kpts.keys():\n img_kpts = kpts[img]\n for n_p in img_kpts:\n box_score = n_p['score']\n kpt_score = 0\n valid_num = 0\n for n_jt in range(0, num_joints):\n t_s = n_p['keypoints'][n_jt][2]\n if t_s > in_vis_thre:\n kpt_score = kpt_score + t_s\n valid_num = valid_num + 1\n if valid_num != 0:\n kpt_score = kpt_score / valid_num\n # rescoring\n n_p['score'] = kpt_score * box_score\n\n if self.soft_nms:\n keep = soft_oks_nms(\n [img_kpts[i] for i in range(len(img_kpts))],\n oks_thre\n )\n else:\n keep = oks_nms(\n [img_kpts[i] for i in range(len(img_kpts))],\n oks_thre\n )\n\n if len(keep) == 0:\n oks_nmsed_kpts.append(img_kpts)\n else:\n oks_nmsed_kpts.append([img_kpts[_keep] for _keep in keep])\n\n self._write_coco_keypoint_results(\n oks_nmsed_kpts, res_file)\n if 'test' not in self.image_set:\n info_str = self._do_python_keypoint_eval(\n res_file, res_folder)\n name_value = OrderedDict(info_str)\n return name_value, name_value['AP']\n else:\n return {'Null': 0}, 0\n\n def _write_coco_keypoint_results(self, keypoints, res_file):\n data_pack = [\n {\n 'cat_id': self._class_to_coco_ind[cls],\n 'cls_ind': cls_ind,\n 'cls': cls,\n 'ann_type': 'keypoints',\n 'keypoints': keypoints\n }\n for cls_ind, cls in enumerate(self.classes) if not cls == '__background__'\n ]\n\n results = self._coco_keypoint_results_one_category_kernel(data_pack[0])\n logger.info('=> writing results json to %s' % res_file)\n with open(res_file, 'w') as f:\n json.dump(results, f, sort_keys=True, indent=4)\n try:\n json.load(open(res_file))\n except Exception:\n content = []\n with open(res_file, 'r') as f:\n for line in f:\n content.append(line)\n content[-1] = ']'\n with open(res_file, 'w') as f:\n for c in content:\n f.write(c)\n\n def _coco_keypoint_results_one_category_kernel(self, data_pack):\n cat_id = data_pack['cat_id']\n keypoints = data_pack['keypoints']\n cat_results = []\n\n for img_kpts in keypoints:\n if len(img_kpts) == 0:\n continue\n\n _key_points = np.array([img_kpts[k]['keypoints']\n for k in range(len(img_kpts))])\n key_points = np.zeros(\n (_key_points.shape[0], self.num_joints * 3), dtype=np.float\n )\n\n for ipt in range(self.num_joints):\n key_points[:, ipt * 3 + 0] = _key_points[:, ipt, 0]\n key_points[:, ipt * 3 + 1] = _key_points[:, ipt, 1]\n key_points[:, ipt * 3 + 2] = _key_points[:, ipt, 2] # keypoints score.\n\n result = [\n {\n 'image_id': img_kpts[k]['image'],\n 'category_id': cat_id,\n 'keypoints': list(key_points[k]),\n 'score': img_kpts[k]['score'],\n 'center': list(img_kpts[k]['center']),\n 'scale': list(img_kpts[k]['scale'])\n }\n for k in range(len(img_kpts))\n ]\n cat_results.extend(result)\n\n return cat_results\n\n def _do_python_keypoint_eval(self, res_file, res_folder):\n coco_dt = self.coco.loadRes(res_file)\n coco_eval = COCOeval(self.coco, coco_dt, 'keypoints')\n coco_eval.params.useSegm = None\n coco_eval.evaluate()\n coco_eval.accumulate()\n coco_eval.summarize()\n\n stats_names = ['AP', 'Ap .5', 'AP .75', 'AP (M)', 'AP (L)', 'AR', 'AR .5', 'AR .75', 'AR (M)', 'AR (L)']\n\n info_str = []\n for ind, name in enumerate(stats_names):\n info_str.append((name, coco_eval.stats[ind]))\n\n return info_str\n" ]
[ [ "numpy.array", "numpy.ones", "numpy.max", "numpy.zeros" ] ]
frankdvd/curb-monitor
[ "a5ad37a9dd0ca93477dffc647d2dfe7a8d9361e0" ]
[ "scripts/extract_gps.py" ]
[ "from pathlib import Path\nimport os, sys, shutil\nimport subprocess\nimport pandas as pd\nimport string\n\nif len(sys.argv) != 2:\n print(\"Usage: ./extract_gps.py <video dir>\")\n sys.exit()\n\ndef convert_latlong(in_str):\n split_latlong = in_str.split(' ')\n return float(split_latlong[0]) + float(split_latlong[2][:-1])/60.0 + float(split_latlong[3][:-1])/3600.00\n\ndef on_bancroft(latitude, longitude):\n # Southwest corner of bancroft -- Intersection of Bancroft and oxford st.\n # lat_0 = 37.867745120011236\n # long_0 = 122.265914980762\n lat_0 = 37.86792981681717\n long_0 = 122.26526052183016\n # Northeast corner of bancroft -- Intersection of Bancroft and Piedmont Ave\n # lat_1 = 37.86974393324088\n # long_1 = 122.25221425754695\n lat_1 = 37.86956443944309\n long_1 = 122.25276142821582\n # Bounding box calculation\n return (latitude > lat_0 and latitude < lat_1) and (longitude > long_1 and longitude < long_0)\n\nvid_dir = sys.argv[1]\nvid_path = Path(vid_dir)\nout_path = vid_path/Path(\"out\")\nif os.path.exists(out_path):\n shutil.rmtree(out_path)\nos.makedirs(out_path)\n\nfor filename in os.listdir(vid_path):\n if not filename.endswith(\".MP4\") and not filename.endswith(\".mp4\"):\n continue\n # outfile = open(out_path/Path(filename[:-4]+\"out.txt\"), 'w')\n out_process = subprocess.run(args = [\"./exiftool.exe\", \"-a\", \"\\\"-gps*\\\"\", \"-ee\", str(vid_path) + \"/\" + filename], universal_newlines = True, stdout = subprocess.PIPE)\n output = out_process.stdout\n output_lines = output[output.index(\"Sample Time\"):].split('\\n')\n\n #gps_df = pd.dataframe({'Lat': [], 'Long': [], 'Speed': })\n lats = []\n longs = []\n speeds = []\n stimes = []\n sdurations = []\n datetimes = []\n vid_on_bancroft = False\n banc_ratio = 0.0\n for line in output_lines:\n if len(line) == 0:\n continue\n split_line = line.split(':')\n split_line[1] = split_line[1][1:]\n if line.startswith('Sample Time'):\n if len(split_line) == 2:\n stimes.append(float(split_line[1][:-2]))\n else:\n stimes.append(float(split_line[3]))\n if line.startswith('Sample Duration'):\n sdurations.append(split_line[1])\n if line.startswith('GPS Latitude'):\n lats.append(split_line[1])\n if line.startswith('GPS Longitude'):\n longs.append(split_line[1])\n # Can check the most recent latitude and longitude to see if the vid is on bancroft\n # Perform the check here since longitude measurement always comes after latitude measurement\n if on_bancroft(convert_latlong(lats[-1]), convert_latlong(longs[-1])):\n # print(convert_latlong(lats[-1]))\n # print(convert_latlong(longs[-1]))\n vid_on_bancroft = True\n banc_ratio += 1.0\n if line.startswith('GPS Speed'):\n speeds.append(split_line[1])\n if line.startswith('GPS Date/Time'):\n datetimes.append(line[line.index(': ')+2:])\n gps_df = pd.DataFrame( {'lat': pd.Series(lats), \n 'long': pd.Series(longs), \n 'speed': pd.Series(speeds),\n 'datetime': pd.Series(datetimes),\n 'sample_time': pd.Series(stimes),\n 'sample_dur': pd.Series(sdurations)\n } ).set_index('sample_time')\n\n # Since this is in the Berkeley area, N and W are implied for the latitude and longitude, respectively\n gps_df['converted_lat'] = gps_df['lat'].apply(convert_latlong)\n gps_df['converted_long'] = gps_df['long'].apply(convert_latlong)\n\n #print(gps_df[['converted_lat', 'converted_long', 'speed', 'datetime']].head())\n print(filename + \" on Bancroft Way: \" + str(vid_on_bancroft), end=\"\\t\")\n print(filename + \" Bancroft Ratio: \" + str(banc_ratio/59))\n #print(gps_df.head())\n #print(output_lines[:10])\n # outfile.close()\n" ]
[ [ "pandas.Series" ] ]
sgdread/autogluon
[ "fa95c72a07066dc5380fccf8bbce04b5c031fc68" ]
[ "text/src/autogluon/text/automm/optimization/utils.py" ]
[ "from typing import Optional, Union, Tuple, List, Dict\nimport functools\nfrom torch import nn\nfrom torch import optim\nfrom torch.nn import functional as F\nfrom transformers.trainer_pt_utils import get_parameter_names\nimport torchmetrics\nfrom .lr_scheduler import (\n get_cosine_schedule_with_warmup,\n get_polynomial_decay_schedule_with_warmup,\n get_linear_schedule_with_warmup,\n)\nfrom ..constants import (\n BINARY, MULTICLASS, REGRESSION, MAX, MIN, NORM_FIT, BIT_FIT,\n ACC, ACCURACY, RMSE, ROOT_MEAN_SQUARED_ERROR, R2, QUADRATIC_KAPPA,\n ROC_AUC, AVERAGE_PRECISION, LOG_LOSS, CROSS_ENTROPY,\n PEARSONR, SPEARMANR,\n)\nimport warnings\n\n\ndef get_loss_func(problem_type: str):\n \"\"\"\n Choose a suitable Pytorch loss module based on the provided problem type.\n\n Parameters\n ----------\n problem_type\n Type of problem.\n\n Returns\n -------\n A Pytorch loss module.\n \"\"\"\n if problem_type in [BINARY, MULTICLASS]:\n loss_func = nn.CrossEntropyLoss()\n elif problem_type == REGRESSION:\n loss_func = nn.MSELoss()\n else:\n raise NotImplementedError\n\n return loss_func\n\n\ndef get_metric(\n metric_name: str,\n problem_type: str,\n num_classes: Optional[int] = None,\n pos_label: Optional[int] = None,\n):\n \"\"\"\n Obtain a torchmerics.Metric from its name.\n Define a customized metric function in case that torchmetrics doesn't support some metric.\n\n Parameters\n ----------\n metric_name\n Name of metric\n problem_type\n The type of the problem.\n num_classes\n Number of classes, used in the quadratic_kappa metric for binary classification.\n pos_label\n The label (0 or 1) of binary classification's positive class, which is used in some metrics, e.g., AUROC.\n\n Returns\n -------\n torchmetrics.Metric\n A torchmetrics.Metric object.\n mode\n The min/max mode used in selecting model checkpoints.\n - min\n Its means that smaller metric is better.\n - max\n It means that larger metric is better.\n custom_metric_func\n A customized metric function.\n \"\"\"\n metric_name = metric_name.lower()\n if metric_name in [ACC, ACCURACY]:\n return torchmetrics.Accuracy(), MAX, None\n elif metric_name in [RMSE, ROOT_MEAN_SQUARED_ERROR]:\n return torchmetrics.MeanSquaredError(squared=False), MIN, None\n elif metric_name == R2:\n return torchmetrics.R2Score(), MAX, None\n elif metric_name == QUADRATIC_KAPPA:\n return torchmetrics.CohenKappa(num_classes=num_classes,\n weights=\"quadratic\"), MAX, None\n elif metric_name == ROC_AUC:\n return torchmetrics.AUROC(pos_label=pos_label), MAX, None\n elif metric_name == AVERAGE_PRECISION:\n return torchmetrics.AveragePrecision(pos_label=pos_label), MAX, None\n elif metric_name in [LOG_LOSS, CROSS_ENTROPY]:\n return torchmetrics.MeanMetric(), MIN, \\\n functools.partial(F.cross_entropy, reduction=\"none\")\n elif metric_name == PEARSONR:\n return torchmetrics.PearsonCorrCoef(), MAX, None\n elif metric_name == SPEARMANR:\n return torchmetrics.SpearmanCorrCoef(), MAX, None\n else:\n warnings.warn(f\"Currently, we cannot convert the metric: {metric_name} to a metric supported in torchmetrics. \"\n f\"Thus, we will fall-back to use accuracy for multi-class classification problems \"\n f\", ROC-AUC for binary classification problem, and MSE for regression problems.\", UserWarning)\n if problem_type == REGRESSION:\n return torchmetrics.MeanSquaredError(squared=False), MIN, None\n elif problem_type == MULTICLASS:\n return torchmetrics.Accuracy(), MAX, None\n elif problem_type == BINARY:\n return torchmetrics.AUROC(pos_label=pos_label), MAX, None\n else:\n raise ValueError(f'The problem_type={problem_type} is currently not supported')\n\n\ndef get_optimizer(\n optim_type: str,\n optimizer_grouped_parameters,\n lr: float,\n weight_decay: float,\n eps: Optional[float] = 1e-6,\n betas: Optional[Tuple[float, float]] = (0.9, 0.999),\n momentum: Optional[float] = 0.9,\n):\n \"\"\"\n Choose a Pytorch optimizer based on its name.\n\n Parameters\n ----------\n optim_type\n Name of optimizer.\n optimizer_grouped_parameters\n The model parameters to be optimized.\n lr\n Learning rate.\n weight_decay\n Optimizer weight decay.\n eps\n Optimizer eps.\n betas\n Optimizer betas.\n momentum\n Momentum used in the SGD optimizer.\n\n Returns\n -------\n A Pytorch optimizer.\n \"\"\"\n if optim_type == \"adamw\":\n optimizer = optim.AdamW(\n optimizer_grouped_parameters,\n lr=lr,\n weight_decay=weight_decay,\n eps=eps,\n betas=betas,\n )\n elif optim_type == \"adam\":\n optimizer = optim.Adam(\n optimizer_grouped_parameters,\n lr=lr,\n weight_decay=weight_decay,\n )\n elif optim_type == \"sgd\":\n optimizer = optim.SGD(\n optimizer_grouped_parameters,\n lr=lr,\n weight_decay=weight_decay,\n momentum=momentum,\n )\n else:\n raise ValueError(f\"unknown optimizer: {optim_type}\")\n\n return optimizer\n\n\ndef get_lr_scheduler(\n optimizer: optim.Optimizer,\n num_max_steps: int,\n num_warmup_steps: int,\n lr_schedule: str,\n end_lr: Union[float, int],\n):\n \"\"\"\n Get the learning rate scheduler from its name. Here we use our defined learning rate\n scheduler instead of those imported from \"transformers\" because we want to support\n Pytorch lightning's \"ddp_spawn\" training strategy.\n\n Parameters\n ----------\n optimizer\n A Pytorch optimizer.\n num_max_steps\n Number of maximum training steps.\n num_warmup_steps\n Number of steps to do learning rate warmup.\n lr_schedule\n Name of the learning rate scheduler.\n end_lr\n The final learning rate after decay.\n\n Returns\n -------\n A learning rate scheduler.\n \"\"\"\n if lr_schedule == \"cosine_decay\":\n scheduler = get_cosine_schedule_with_warmup(\n optimizer=optimizer,\n num_warmup_steps=num_warmup_steps,\n num_training_steps=num_max_steps,\n )\n elif lr_schedule == \"polynomial_decay\":\n scheduler = get_polynomial_decay_schedule_with_warmup(\n optimizer=optimizer,\n num_warmup_steps=num_warmup_steps,\n num_training_steps=num_max_steps,\n lr_end=end_lr,\n power=1,\n )\n elif lr_schedule == \"linear_decay\":\n scheduler = get_linear_schedule_with_warmup(\n optimizer=optimizer,\n num_warmup_steps=num_warmup_steps,\n num_training_steps=num_max_steps\n )\n else:\n raise ValueError(f\"unknown lr schedule: {lr_schedule}\")\n\n return scheduler\n\n\ndef get_weight_decay_param_names(model: nn.Module):\n \"\"\"\n Set the layer normalization parameters and other layers' bias parameters not to use weight decay.\n\n Parameters\n ----------\n model\n A Pytorch model.\n\n Returns\n -------\n A list of parameter names not using weight decay.\n \"\"\"\n # By default, we should not apply weight decay for all the norm layers\n decay_param_names = get_parameter_names(model,\n [nn.LayerNorm, nn.BatchNorm1d, nn.BatchNorm2d, nn.BatchNorm3d,\n nn.GroupNorm])\n decay_param_names = [name for name in decay_param_names if \"bias\" not in name]\n return decay_param_names\n\n\ndef get_norm_layer_param_names(model: nn.Module):\n \"\"\"\n Get parameters associated with the normalization layers\n\n Parameters\n ----------\n model\n A Pytorch model\n\n Returns\n -------\n norm_param_names\n A list of normalization parameter names\n \"\"\"\n all_param_names = [name for name, _ in model.named_parameters()]\n all_param_names_except_norm_names = get_parameter_names(\n model, [nn.LayerNorm, nn.BatchNorm1d, nn.BatchNorm2d, nn.BatchNorm3d, nn.GroupNorm])\n norm_param_names = [name for name in all_param_names if name not in all_param_names_except_norm_names]\n return norm_param_names\n\n\ndef apply_single_lr(\n model: nn.Module,\n lr: float,\n weight_decay: float,\n return_params: Optional[bool] = True,\n):\n \"\"\"\n Set to use a single learning rate for all parameters. Layer normalization parameters and other\n layers' bias parameters don't use weight decay.\n\n Parameters\n ----------\n model\n A Pytorch model.\n lr\n Learning rate.\n weight_decay\n Weight decay.\n return_params\n Whether to return parameters or their names. If you want to double-check\n whether the learning rate setup is as expected, you can set \"return_params=False\",\n and print the layer names along with their learning rates through\n \"print(\"Param groups = %s\" % json.dumps(optimizer_grouped_parameters, indent=2))\".\n\n Returns\n -------\n The grouped parameters or their names.\n \"\"\"\n decay_param_names = get_weight_decay_param_names(model)\n optimizer_grouped_parameters = [\n {\n \"params\": [p if return_params else n for n, p in model.named_parameters() if n in decay_param_names],\n \"weight_decay\": weight_decay,\n \"lr\": lr,\n },\n {\n \"params\": [p if return_params else n for n, p in model.named_parameters() if n not in decay_param_names],\n \"weight_decay\": 0.0,\n \"lr\": lr,\n },\n ]\n return optimizer_grouped_parameters\n\n\ndef apply_two_stages_lr(\n model: nn.Module,\n lr: float,\n lr_mult: Union[float, int],\n weight_decay: float,\n return_params: Optional[bool] = True,\n):\n \"\"\"\n Set up the pretrained backbone to use a smaller learning rate (lr * lr_mult).\n The newly added head layers use the normal learning rate (lr).\n Layer normalization parameters and other layers' bias parameters don't use weight decay.\n\n Parameters\n ----------\n model\n A Pytorch model.\n lr\n The learning rate.\n lr_mult\n The multiplier (0, 1) to scale down the learning rate.\n weight_decay\n Weight decay.\n return_params\n return_params\n Whether to return parameters or their names. If you want to double-check\n whether the learning rate setup is as expected, you can set \"return_params=False\",\n and print the layer names along with their learning rates through\n \"print(\"Param groups = %s\" % json.dumps(optimizer_grouped_parameters, indent=2))\".\n\n Returns\n -------\n The grouped parameters or their names.\n \"\"\"\n decay_param_names = get_weight_decay_param_names(model)\n\n optimizer_grouped_parameters = [\n {\n \"params\": [\n p if return_params else n\n for n, p in model.named_parameters()\n if n in decay_param_names\n and not any(bb in n for bb in model.head_layer_names)\n ],\n \"weight_decay\": weight_decay,\n \"lr\": lr,\n },\n {\n \"params\": [\n p if return_params else n\n for n, p in model.named_parameters()\n if n not in decay_param_names\n and not any(bb in n for bb in model.head_layer_names)\n ],\n \"weight_decay\": 0.0,\n \"lr\": lr,\n },\n {\n \"params\": [\n p if return_params else n\n for n, p in model.named_parameters()\n if n in decay_param_names\n and any(bb in n for bb in model.head_layer_names)\n ],\n \"weight_decay\": weight_decay,\n \"lr\": lr * lr_mult,\n },\n {\n \"params\": [\n p if return_params else n\n for n, p in model.named_parameters()\n if n not in decay_param_names\n and any(bb in n for bb in model.head_layer_names)\n ],\n \"weight_decay\": 0.0,\n \"lr\": lr * lr_mult,\n },\n ]\n\n return optimizer_grouped_parameters\n\n\ndef apply_layerwise_lr_decay(\n model: nn.Module,\n lr: float,\n lr_decay: float,\n weight_decay: float,\n efficient_finetune: Optional[str] = None,\n):\n \"\"\"\n Assign monotonically decreasing learning rates for layers from the output end to the input end.\n The intuition behind is that later layers are more task-related compared to the early layers.\n Layer normalization parameters and other layers' bias parameters don't use weight decay.\n If you want to double-check whether the learning rate setup is as expected,\n you can print the layer names along with their learning rates through\n \"print(\"Param groups = %s\" % json.dumps(parameter_group_names, indent=2))\".\n\n Parameters\n ----------\n model\n A Pytorch model.\n lr\n The learning rate.\n lr_decay\n The learning rate decay factor (0, 1).\n weight_decay\n Weight decay.\n efficient_finetune\n Efficient finetuning strategy. Can be \"bit_fit\", \"norm_fit\". It will only finetune part of the parameters\n\n Returns\n -------\n The grouped parameters based on their layer ids and whether using weight decay.\n \"\"\"\n parameter_group_names = {}\n parameter_group_vars = {}\n decay_param_names = get_weight_decay_param_names(model)\n norm_param_names = get_norm_layer_param_names(model)\n for name, param in model.named_parameters():\n if efficient_finetune == BIT_FIT:\n # For bit_fit, we disable tuning everything except the bias terms\n if 'bias' not in name:\n param.requires_grad = False\n elif efficient_finetune == NORM_FIT:\n # For norm-fit, we finetune all the normalization layers and bias layers\n if name not in norm_param_names and 'bias' not in name:\n param.requires_grad = False\n\n if not param.requires_grad:\n continue # frozen weights\n\n if name in decay_param_names:\n group_name = \"decay\"\n this_weight_decay = weight_decay\n else:\n group_name = \"no_decay\"\n this_weight_decay = 0.\n\n layer_id = model.name_to_id[name]\n group_name = \"layer_%d_%s\" % (layer_id, group_name)\n\n if group_name not in parameter_group_names:\n scale = lr_decay ** layer_id\n\n parameter_group_names[group_name] = {\n \"weight_decay\": this_weight_decay,\n \"params\": [],\n \"lr\": scale * lr\n }\n parameter_group_vars[group_name] = {\n \"weight_decay\": this_weight_decay,\n \"params\": [],\n \"lr\": scale * lr\n }\n\n parameter_group_vars[group_name][\"params\"].append(param)\n parameter_group_names[group_name][\"params\"].append(name)\n\n return list(parameter_group_vars.values())\n" ]
[ [ "torch.optim.SGD", "torch.nn.MSELoss", "torch.nn.CrossEntropyLoss", "torch.optim.Adam", "torch.optim.AdamW" ] ]
xiaohui-zhang/audio
[ "0ec482cedfe82b209d23769a286fcd7d3fd468d2" ]
[ "test/torchaudio_unittest/common_utils/data_utils.py" ]
[ "import os.path\nfrom typing import Union, Optional\n\nimport torch\n\n\n_TEST_DIR_PATH = os.path.realpath(os.path.join(os.path.dirname(__file__), \"..\"))\n\n\ndef get_asset_path(*paths):\n \"\"\"Return full path of a test asset\"\"\"\n return os.path.join(_TEST_DIR_PATH, \"assets\", *paths)\n\n\ndef convert_tensor_encoding(\n tensor: torch.tensor,\n dtype: torch.dtype,\n):\n \"\"\"Convert input tensor with values between -1 and 1 to integer encoding\n Args:\n tensor: input tensor, assumed between -1 and 1\n dtype: desired output tensor dtype\n Returns:\n Tensor: shape of (n_channels, sample_rate * duration)\n \"\"\"\n if dtype == torch.int32:\n tensor *= (tensor > 0) * 2147483647 + (tensor < 0) * 2147483648\n if dtype == torch.int16:\n tensor *= (tensor > 0) * 32767 + (tensor < 0) * 32768\n if dtype == torch.uint8:\n tensor *= (tensor > 0) * 127 + (tensor < 0) * 128\n tensor += 128\n tensor = tensor.to(dtype)\n return tensor\n\n\ndef get_whitenoise(\n *,\n sample_rate: int = 16000,\n duration: float = 1, # seconds\n n_channels: int = 1,\n seed: int = 0,\n dtype: Union[str, torch.dtype] = \"float32\",\n device: Union[str, torch.device] = \"cpu\",\n channels_first=True,\n scale_factor: float = 1,\n):\n \"\"\"Generate pseudo audio data with whitenoise\n Args:\n sample_rate: Sampling rate\n duration: Length of the resulting Tensor in seconds.\n n_channels: Number of channels\n seed: Seed value used for random number generation.\n Note that this function does not modify global random generator state.\n dtype: Torch dtype\n device: device\n channels_first: whether first dimension is n_channels\n scale_factor: scale the Tensor before clamping and quantization\n Returns:\n Tensor: shape of (n_channels, sample_rate * duration)\n \"\"\"\n if isinstance(dtype, str):\n dtype = getattr(torch, dtype)\n if dtype not in [torch.float64, torch.float32, torch.int32, torch.int16, torch.uint8]:\n raise NotImplementedError(f\"dtype {dtype} is not supported.\")\n # According to the doc, folking rng on all CUDA devices is slow when there are many CUDA devices,\n # so we only fork on CPU, generate values and move the data to the given device\n with torch.random.fork_rng([]):\n torch.random.manual_seed(seed)\n tensor = torch.randn([n_channels, int(sample_rate * duration)], dtype=torch.float32, device=\"cpu\")\n tensor /= 2.0\n tensor *= scale_factor\n tensor.clamp_(-1.0, 1.0)\n if not channels_first:\n tensor = tensor.t()\n\n tensor = tensor.to(device)\n\n return convert_tensor_encoding(tensor, dtype)\n\n\ndef get_sinusoid(\n *,\n frequency: float = 300,\n sample_rate: int = 16000,\n duration: float = 1, # seconds\n n_channels: int = 1,\n dtype: Union[str, torch.dtype] = \"float32\",\n device: Union[str, torch.device] = \"cpu\",\n channels_first: bool = True,\n):\n \"\"\"Generate pseudo audio data with sine wave.\n\n Args:\n frequency: Frequency of sine wave\n sample_rate: Sampling rate\n duration: Length of the resulting Tensor in seconds.\n n_channels: Number of channels\n dtype: Torch dtype\n device: device\n\n Returns:\n Tensor: shape of (n_channels, sample_rate * duration)\n \"\"\"\n if isinstance(dtype, str):\n dtype = getattr(torch, dtype)\n pie2 = 2 * 3.141592653589793\n end = pie2 * frequency * duration\n num_frames = int(sample_rate * duration)\n # Randomize the initial phase. (except the first channel)\n theta0 = pie2 * torch.randn(n_channels, 1, dtype=torch.float32, device=device)\n theta0[0, :] = 0\n theta = torch.linspace(0, end, num_frames, dtype=torch.float32, device=device)\n theta = theta0 + theta\n tensor = torch.sin(theta, out=None)\n if not channels_first:\n tensor = tensor.t()\n return convert_tensor_encoding(tensor, dtype)\n\n\ndef get_spectrogram(\n waveform,\n *,\n n_fft: int = 2048,\n hop_length: Optional[int] = None,\n win_length: Optional[int] = None,\n window: Optional[torch.Tensor] = None,\n center: bool = True,\n pad_mode: str = \"reflect\",\n power: Optional[float] = None,\n):\n \"\"\"Generate a spectrogram of the given Tensor\n\n Args:\n n_fft: The number of FFT bins.\n hop_length: Stride for sliding window. default: ``n_fft // 4``.\n win_length: The size of window frame and STFT filter. default: ``n_fft``.\n winwdow: Window function. default: Hann window\n center: Pad the input sequence if True. See ``torch.stft`` for the detail.\n pad_mode: Padding method used when center is True. Default: \"reflect\".\n power: If ``None``, raw spectrogram with complex values are returned,\n otherwise the norm of the spectrogram is returned.\n \"\"\"\n hop_length = hop_length or n_fft // 4\n win_length = win_length or n_fft\n window = torch.hann_window(win_length, device=waveform.device) if window is None else window\n spec = torch.stft(\n waveform,\n n_fft=n_fft,\n hop_length=hop_length,\n win_length=win_length,\n center=center,\n window=window,\n pad_mode=pad_mode,\n return_complex=True,\n )\n if power is not None:\n spec = spec.abs() ** power\n return spec\n" ]
[ [ "torch.randn", "torch.linspace", "torch.random.fork_rng", "torch.sin", "torch.random.manual_seed", "torch.hann_window", "torch.stft" ] ]
siddarthjha/Opencv
[ "ccf26ade18a4a04da464acbbc15f074904fab208" ]
[ "Image Processing/11_Template_Matching.py" ]
[ "import cv2\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nimg = cv2.imread('a.jpg',0)\nimg2 = img.copy()\ntemplate = cv2.imread('b.jpg',0)\nw, h = template.shape[::-1]\n\n# All the 6 methods for comparison in a list\nmethods = ['cv2.TM_CCOEFF', 'cv2.TM_CCOEFF_NORMED', 'cv2.TM_CCORR',\n 'cv2.TM_CCORR_NORMED', 'cv2.TM_SQDIFF', 'cv2.TM_SQDIFF_NORMED']\n\nfor meth in methods:\n img = img2.copy()\n method = eval(meth)\n\n # Apply template Matching\n res = cv2.matchTemplate(img,template,method)\n min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)\n\n # If the method is TM_SQDIFF or TM_SQDIFF_NORMED, take minimum\n if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]:\n top_left = min_loc\n else:\n top_left = max_loc\n bottom_right = (top_left[0] + w, top_left[1] + h)\n\n cv2.rectangle(img,top_left, bottom_right, 255, 2)\n\n plt.subplot(121),plt.imshow(res,cmap = 'gray')\n plt.title('Matching Result'), plt.xticks([]), plt.yticks([])\n plt.subplot(122),plt.imshow(img,cmap = 'gray')\n plt.title('Detected Point'), plt.xticks([]), plt.yticks([])\n plt.suptitle(meth)\n\n plt.show()\n" ]
[ [ "matplotlib.pyplot.xticks", "matplotlib.pyplot.title", "matplotlib.pyplot.subplot", "matplotlib.pyplot.show", "matplotlib.pyplot.imshow", "matplotlib.pyplot.suptitle", "matplotlib.pyplot.yticks" ] ]
terry97-guel/SMInet
[ "e4c158fb03096a12723bb474c3e468044eca46a6" ]
[ "evaluate.py" ]
[ "import torch\nfrom model import *\nfrom dataloader import *\nfrom utils.pyart import *\nimport argparse\nimport numpy as np\nfrom pathlib import Path\n\ndef main(args):\n print(\"Processing...\")\n\n # set device:\n if torch.cuda.is_available():\n device = torch.device('cuda:0')\n else:\n device = torch.device('cpu')\n\n # make save_dir\n Path(args.save_dir).mkdir(parents=True, exist_ok=True)\n\n # load checkpoint\n checkpoint = torch.load(args.checkpoint)\n branchNum = checkpoint['branchNum']\n input_dim = checkpoint['input_dim']\n branchLs = bnum2ls(branchNum)\n n_joint = len(branchLs)\n\n # load model\n model = Model(branchNum, input_dim)\n model.load_state_dict(checkpoint['state_dict'])\n model = model.to(device)\n model.eval()\n\n # load data\n IOScale = checkpoint['IOScale']\n test_data_loader = ToyDataloader(args.data_path, IOScale, n_workers = 1, batch = 1, shuffle=False)\n\n # get IOScale.txt\n (inputSigma,inputMean),(outputSigma,outputMean) = IOScale\n inputSigma,inputMean,outputSigma,outputMean = \\\n inputSigma.detach().numpy(),inputMean.detach().numpy(),outputSigma.detach().numpy(),outputMean.detach().numpy()\n\n ScaleInfo = np.array([]).reshape(-1,3)\n ScaleInfo = np.vstack((ScaleInfo, inputSigma))\n ScaleInfo = np.vstack((ScaleInfo, inputMean))\n ScaleInfo = np.vstack((ScaleInfo, outputSigma))\n ScaleInfo = np.vstack((ScaleInfo, outputMean))\n \n np.savetxt(args.save_dir+\"/IOScale.txt\",ScaleInfo)\n\n # get jointAngle.txt\n revAngle = np.array([]).reshape(-1,n_joint)\n priAngle = np.array([]).reshape(-1,n_joint)\n for input,_ in test_data_loader:\n input = input.to(device)\n rev_q_value, pri_q_value = model.q_layer(input)\n\n rev_q_value = rev_q_value.detach().cpu().numpy()\n pri_q_value = pri_q_value.detach().cpu().numpy()\n\n revAngle = np.vstack((revAngle,rev_q_value))\n priAngle = np.vstack((priAngle,pri_q_value))\n np.savetxt(args.save_dir+\"/revAngle.txt\", revAngle)\n np.savetxt(args.save_dir+\"/priAngle.txt\", priAngle)\n\n # get branchLs\n np.savetxt(args.save_dir+'/branchLs.txt',branchLs)\n\n # get targetPose.txt\n targetPose = test_data_loader.dataset.label\n targetPose = targetPose.detach().cpu().numpy()\n np.savetxt(args.save_dir+'/targetPose.txt', targetPose)\n\n # get outputPose.txt\n outputPose = np.array([]).reshape(-1,targetPose.shape[1])\n for input,_ in test_data_loader:\n input = input.to(device)\n outputPose_temp,_,_ = model(input)\n outputPose_temp = outputPose_temp[:,:,0:3,3]\n outputPose_temp = outputPose_temp.reshape(-1,outputPose_temp.size()[1]*outputPose_temp.size()[2])\n outputPose_temp = outputPose_temp.detach().cpu().numpy()[0]\n outputPose = np.vstack((outputPose,outputPose_temp))\n \n np.savetxt(args.save_dir+\"/outputPose.txt\", outputPose)\n\n print(\"Done...\")\nif __name__ == '__main__':\n args = argparse.ArgumentParser(description= 'parse for POENet')\n args.add_argument('--data_path', \\\n default= './data/Sorosim/SorosimPlot1.txt',type=str, \\\n help='path to model checkpoint') \n args.add_argument('--checkpoint', default= './output/0205/10ScaleSoro/checkpoint_100.pth',type=str,\n help='path to model checkpoint')\n args.add_argument('--save_dir', default='./2Visualize')\n args = args.parse_args()\n main(args)" ]
[ [ "numpy.vstack", "torch.load", "numpy.savetxt", "torch.cuda.is_available", "numpy.array", "torch.device" ] ]
levskaya/tensor2tensor
[ "4643800137f802693f880a1fab9e10de7ba32e66" ]
[ "tensor2tensor/layers/common_attention_test.py" ]
[ "# coding=utf-8\n# Copyright 2019 The Tensor2Tensor Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Tests for common attention.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom absl.testing import parameterized\nimport kfac\nimport numpy as np\n\nfrom tensor2tensor.layers import common_attention\nfrom tensor2tensor.layers import common_layers\nfrom tensor2tensor.utils import test_utils\n\nimport tensorflow as tf\ntf.compat.v1.enable_eager_execution()\n\n\nclass CommonAttentionTest(parameterized.TestCase, tf.test.TestCase):\n\n @test_utils.run_in_graph_and_eager_modes()\n def testAddPositionalEmbedding(self):\n x = np.random.rand(5, 3, 12)\n y = common_attention.add_positional_embedding(\n tf.constant(x, dtype=tf.float32),\n max_length=4,\n name=\"pos_embedding\")\n self.evaluate(tf.global_variables_initializer())\n res = self.evaluate(y)\n self.assertEqual(res.shape, (5, 3, 12))\n\n @parameterized.named_parameters(\n (\"hard_top_k\", 0.0),\n (\"sampled_top_k_default\", 1.0),\n (\"sampled_top_k_2\", 2.0),\n )\n @test_utils.run_in_graph_and_eager_modes()\n def testHardenAttentionWeights(self, gumbel_noise_weight):\n x = np.random.rand(5, 3, 12)\n y = common_attention.harden_attention_weights(\n tf.nn.softmax(tf.constant(x, dtype=tf.float32)), 3, gumbel_noise_weight)\n res = self.evaluate(y)\n self.assertEqual(res.shape, (5, 3, 12))\n\n @parameterized.named_parameters(\n (\"hard_top_k\", -0.5),\n (\"sampled_top_k\", 0.5),\n )\n @test_utils.run_in_graph_and_eager_modes()\n def testHardenAttentionAllZeros(self, gumbel_noise_weight):\n \"\"\"Check if the hardening code does not divide by zero for all zeros.\"\"\"\n x = np.zeros((5, 3, 12), dtype=np.float32)\n y = common_attention.harden_attention_weights(\n tf.constant(x, dtype=tf.float32), 3, gumbel_noise_weight)\n res = self.evaluate(y)\n if gumbel_noise_weight <= 0.0:\n self.assertAllClose(res, x)\n\n @parameterized.parameters(\n {\"input_shape\": (5, 3, 12)},\n {\"input_shape\": (5, 5, 5, 12)},\n {\"input_shape\": (5, 3, 3, 3, 12)},\n )\n @test_utils.run_in_graph_and_eager_modes()\n def testAddPositionalEmbeddingNd(self, input_shape):\n x = np.random.rand(*input_shape)\n y = common_attention.add_positional_embedding_nd(\n tf.constant(x, dtype=tf.float32),\n max_length=5,\n name=\"pos_embedding\")\n self.evaluate(tf.global_variables_initializer())\n res = self.evaluate(y)\n self.assertEqual(res.shape, input_shape)\n\n @test_utils.run_in_graph_and_eager_modes()\n def testDotProductAttention(self):\n x = np.random.rand(5, 7, 12, 32)\n y = np.random.rand(5, 7, 12, 32)\n a = common_attention.dot_product_attention(\n tf.constant(x, dtype=tf.float32),\n tf.constant(y, dtype=tf.float32),\n tf.constant(y, dtype=tf.float32), None)\n res = self.evaluate(a)\n self.assertEqual(res.shape, (5, 7, 12, 32))\n\n @parameterized.parameters(\n ([3, 10, 64], 4),\n ([3, 10, 20, 64], 2),\n ([3, 10, 20, 30, 64], 4),\n )\n def testSplitHeadsND(self, shape, num_heads):\n t = tf.zeros(shape)\n h = common_attention.split_heads_nd(t, num_heads)\n res = self.evaluate(h)\n self.assertEqual(\n res.shape,\n tuple(shape[:1] + [num_heads] + shape[1:-1] + [shape[-1] // num_heads]))\n\n @parameterized.parameters(\n ([3, 4, 10, 64],),\n ([3, 2, 10, 20, 64],),\n ([3, 4, 10, 20, 30, 64],),\n )\n def testCombineHeadsND(self, shape):\n t = tf.zeros(shape)\n h = common_attention.combine_heads_nd(t)\n res = self.evaluate(h)\n self.assertEqual(res.shape,\n tuple(shape[:1] + shape[2:-1] + [shape[-1] * shape[1]]))\n\n @parameterized.parameters(\n ([3, 4, 10, 64], (5,), (10,)),\n ([3, 4, 10, 10, 64], (5, 5), (5, 5)),\n ([3, 4, 10, 10, 10, 64], (5, 5, 5), (5, 5, 5)),\n )\n def testShapeMaskedLocalAttentionND(self, shape, query_shape, memory_flange):\n q = k = v = tf.reshape(tf.range(np.prod(shape), dtype=tf.float32), shape)\n val = common_attention.masked_local_attention_nd(q, k, v, query_shape,\n memory_flange)\n res = self.evaluate(val)\n self.assertEqual(res.shape, tuple(shape))\n\n @test_utils.run_in_graph_and_eager_modes()\n def testRightShiftBlockwiseND(self):\n tensor = tf.convert_to_tensor(np.array([[\n [[1], [2], [3], [4]],\n [[5], [6], [7], [8]],\n [[9], [10], [11], [12]],\n [[13], [14], [15], [16]],\n ]], dtype=np.float32))\n val = common_attention.right_shift_blockwise_nd(tensor, (2, 2))\n res = self.evaluate(val)\n expected_val = np.array([[\n [[0], [1], [6], [3]],\n [[2], [5], [4], [7]],\n [[8], [9], [14], [11]],\n [[10], [13], [12], [15]],\n ]], dtype=np.float32)\n self.assertAllClose(expected_val, res)\n\n @test_utils.run_in_graph_and_eager_modes()\n def testContentMaskedLocalAttentionND(self):\n def softmax(arr):\n return np.exp(arr) / np.sum(np.exp(arr))\n\n q = k = v = tf.convert_to_tensor(\n np.array([[[\n [[0.1], [0.1], [0.1], [0.1]],\n [[0.1], [1.0], [1.0], [0.1]],\n [[0.1], [1.0], [1.0], [0.1]],\n [[0.1], [0.1], [0.1], [0.1]],\n ]]], dtype=np.float32))\n attn_weights = np.array([[[[softmax([-1e9, -1e9, -1e9, -1e9, 0.01]),\n softmax([-1e9, -1e9, -1e9, 0.01, 0.01]),\n softmax([-1e9, -1e9, -1e9, 0.01, 0.01]),\n softmax([-1e9, -1e9, -1e9, 0.01, 0.01])\n ],\n [softmax([-1e9, 0.01, 0.01, -1e9, 0.01]),\n softmax([0.1, 0.1, 0.1, 0.1, 1.0]),\n softmax([0.1, 0.1, 0.1, 1.0, 1.0]),\n softmax([0.01, 0.01, -1e9, 0.1, 0.01])\n ],\n [softmax([-1e9, 0.01, 0.1, -1e9, 0.01]),\n softmax([0.1, 1.0, 1.0, 0.1, 1.0]),\n softmax([1.0, 1.0, 0.1, 1.0, 1.0]),\n softmax([0.1, 0.01, -1e9, 0.1, 0.01])\n ],\n [softmax([-1e9, 0.01, 0.1, -1e9, 0.01]),\n softmax([0.01, 0.1, 0.1, 0.01, 0.01]),\n softmax([0.1, 0.1, 0.01, 0.01, 0.01]),\n softmax([0.1, 0.01, -1e9, 0.01, 0.01])\n ]]]])\n blocked_v = np.array([[[[[0, 0, 0, 0, 0.1],\n [0, 0, 0, 0.1, 0.1],\n [0, 0, 0, 0.1, 0.1],\n [0, 0, 0, 0.1, 0.1]],\n [[0, 0.1, 0.1, 0, 0.1],\n [0.1, 0.1, 0.1, 0.1, 1],\n [0.1, 0.1, 0.1, 1, 1],\n [0.1, 0.1, 0, 1, 0.1]],\n [[0, 0.1, 1, 0, 0.1],\n [0.1, 1, 1, 0.1, 1],\n [1, 1, 0.1, 1, 1],\n [1, 0.1, 0, 1, 0.1]],\n [[0, 0.1, 1, 0, 0.1],\n [0.1, 1, 1, 0.1, 0.1],\n [1, 1, 0.1, 0.1, 0.1],\n [1, 0.1, 0, 0.1, 0.1]]]]])\n expected_val = np.expand_dims(\n np.sum(attn_weights * blocked_v, axis=4), axis=-1)\n val = common_attention.masked_local_attention_nd(q, k, v, (1, 1), (1, 1))\n res = self.evaluate(val)\n self.assertAllClose(expected_val, res)\n\n @test_utils.run_in_graph_and_eager_modes()\n def testSelectBlockForDecodeStep(self):\n tensor = tf.reshape(\n tf.range(2 * 6 * 6 * 4, dtype=tf.float32), [2, 6, 6, 4, 1])\n block = common_attention.select_block_for_decode_step(tensor, 20, (2, 2))\n expected_tensor = tensor[:, 0:1, 5:6, :, :]\n expected_value = self.evaluate(expected_tensor)\n res = self.evaluate(block)\n self.assertAllClose(expected_value, res)\n\n @parameterized.parameters(\n ((2, 6, 4, 10),),\n ((2, 6, 6, 4, 10),),\n ((2, 6, 6, 6, 4, 10),),\n )\n def testFlattenBlocksND(self, shape):\n tensor = tf.zeros(shape, dtype=tf.float32)\n value, _ = common_attention.flatten_blocks_nd(tensor)\n res = self.evaluate(value)\n self.assertAllClose(res.shape,\n (shape[0], np.prod(shape[1:-2]), shape[-2], shape[-1]))\n\n @parameterized.parameters(\n ((5,),),\n ((5, 10),),\n ((5, 10, 15),),\n )\n def testUnflattenBlocksND(self, blocks_per_dim):\n tensor = tf.zeros([2, np.prod(blocks_per_dim), 6, 10])\n value = common_attention.unflatten_blocks_nd(tensor, blocks_per_dim)\n res = self.evaluate(value)\n self.assertAllClose(res.shape, (2,) + blocks_per_dim + (6, 10))\n\n @test_utils.run_in_graph_and_eager_modes()\n def testBreakIntoMemoryBlocksND(self):\n tensor = tf.convert_to_tensor(\n np.array([[\n [[1], [2], [3], [4]],\n [[5], [6], [7], [8]],\n [[9], [10], [11], [12]],\n [[13], [14], [15], [16]],\n ]]))\n value = common_attention.break_into_memory_blocks_nd(tensor,\n (2, 2),\n (2, 2),\n masked=True)\n res = self.evaluate(value)\n expected_value = np.array([[\n [\n [\n [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0],\n [0], [0], [0], [0], [1], [2], [5], [6], [3], [4], [7], [8]\n ],\n [\n [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0],\n [1], [2], [5], [6], [3], [4], [7], [8], [0], [0], [0], [0]\n ]\n ],\n [\n [\n [0], [0], [0], [0], [1], [2], [5], [6], [3], [4], [7], [8], [0],\n [0], [0], [0], [9], [10], [13], [14], [11], [12], [15], [16]\n ],\n [\n [1], [2], [5], [6], [3], [4], [7], [8], [0], [0], [0], [0], [9],\n [10], [13], [14], [11], [12], [15], [16], [0], [0], [0], [0]\n ]\n ]]])\n self.assertAllClose(expected_value, res)\n\n @test_utils.run_in_graph_and_eager_modes()\n def testBreakIntoBlocksND(self):\n tensor = tf.convert_to_tensor(\n np.array([[\n [[1], [2], [3], [4]],\n [[5], [6], [7], [8]],\n [[9], [10], [11], [12]],\n [[13], [14], [15], [16]],\n ]]))\n value = common_attention.break_into_blocks_nd(tensor, (2, 2))\n res = self.evaluate(value)\n expected_value = np.array([[\n [[[1], [2], [5], [6]], [[3], [4], [7], [8]]],\n [[[9], [10], [13], [14]], [[11], [12], [15], [16]]]\n ]])\n self.assertAllClose(expected_value, res)\n\n @test_utils.run_in_graph_and_eager_modes()\n def testPutBackBlocksND(self):\n tensor = tf.convert_to_tensor(\n np.array([[\n [[[1], [2], [5], [6]], [[3], [4], [7], [8]]],\n [[[9], [10], [13], [14]], [[11], [12], [15], [16]]]\n ]]))\n value = common_attention.put_back_blocks_nd(tensor, (2, 2))\n res = self.evaluate(value)\n expected_value = np.array([[\n [[1], [2], [3], [4]],\n [[5], [6], [7], [8]],\n [[9], [10], [11], [12]],\n [[13], [14], [15], [16]],\n ]])\n self.assertAllClose(expected_value, res)\n\n @parameterized.parameters(\n ((2, 100, 5), (7,), (2, 105, 5)),\n ((2, 100, 100, 5), (5, 7), (2, 100, 105, 5)),\n ((2, 100, 100, 100, 5), (10, 20, 30), (2, 100, 100, 120, 5))\n )\n def testPadToMultipleND(self, tensor_shape, block_shape, expected_shape):\n tensor = tf.zeros(tensor_shape)\n value = common_attention.pad_to_multiple_nd(tensor, block_shape)\n res = self.evaluate(value)\n self.assertAllClose(res.shape, expected_shape)\n\n @test_utils.run_in_graph_and_eager_modes()\n def testCausalAttentionBiasND(self):\n bias = common_attention.causal_attention_bias_nd((2, 2), (2, 2))\n res = self.evaluate(bias)\n expected_val = np.array([[[\n [0] * 17 + [-1e9] * 7,\n [0] * 18 + [-1e9] * 6,\n [0] * 19 + [-1e9] * 5,\n [0] * 20 + [-1e9] * 4,\n ]]])\n self.assertAllClose(expected_val, res)\n\n @parameterized.parameters(\n ((1, 64, 10), (80,), (80,)),\n ((1, 64, 64, 10), (8, 8), (16, 16)),\n ((1, 5, 64, 64, 10), (1, 8, 8), (1, 8, 8))\n )\n def testMultiheadAttentionND(self, tensor_shape, query_shape, memory_flange):\n query_antecedent = tf.zeros(tensor_shape)\n value = common_attention.multihead_attention_nd(\n query_antecedent=query_antecedent,\n memory_antecedent=None,\n total_key_depth=256,\n total_value_depth=256,\n output_depth=256,\n num_heads=4,\n query_shape=query_shape,\n memory_flange=memory_flange,\n masked=True)\n res = self.evaluate(value)\n self.assertAllClose(res.shape, tensor_shape[:-1] + (256,))\n\n @parameterized.parameters(\n (15, (5,), (100,), (15,)),\n (10, (2, 2), (4, 4), (3, 0)),\n (25, (2, 2, 3), (10, 10, 12), (0, 0, 7))\n )\n def testDecodeStepToIndex(self, decode_step, query_shape, tensor_shape,\n expected_index):\n res = common_attention.decode_step_to_index(decode_step, query_shape,\n tensor_shape)\n self.assertAllClose(res, expected_index)\n\n @test_utils.run_in_graph_and_eager_modes()\n def testGetItemAtDecodeStep(self):\n tensor = tf.reshape(tf.range(25 * 25 * 4), [1, 4, 25, 25, 1])\n value = common_attention.get_item_at_decode_step(tensor, 100, (2, 5, 5))\n res = self.evaluate(value)\n expected_value = np.array([[[[[10]]]]])\n self.assertAllClose(expected_value, res)\n\n @test_utils.run_in_graph_and_eager_modes()\n def testPutItemAtDecodeStep(self):\n tensor = tf.zeros([1, 1, 10, 10, 1])\n item = tf.ones([1, 1, 1, 1, 1])\n value = common_attention.put_item_in_decode_step(tensor, item, 32, (2, 2))\n res = self.evaluate(value)\n expected_val = np.zeros([1, 1, 10, 10, 1])\n expected_val[0, 0, 2, 6, 0] = 1\n self.assertAllClose(expected_val, res)\n\n @parameterized.named_parameters(\n (\"\", 1, 1, 8, 4, 1, 2),\n (\"dynamic_batch\", None, 1, 8, 4, 1, 2),\n (\"batches\", 4, 3, 8, 4, 1, 2),\n (\"depth_v\", 1, 1, 8, 4, 3, 2),\n (\"block_length\", 1, 1, 8, 4, 1, 4),\n )\n def testMaskedWithinBlockLocalAttention1D(self, batch, heads, length,\n depth_k, depth_v, block_length):\n if batch is None:\n batch = tf.random_uniform([], minval=0, maxval=5, dtype=tf.int32)\n q = tf.random_normal([batch, heads, length, depth_k])\n k = tf.random_normal([batch, heads, length, depth_k])\n v = tf.random_normal([batch, heads, length, depth_v])\n output = common_attention.masked_within_block_local_attention_1d(\n q, k, v, block_length=block_length)\n if isinstance(batch, tf.Tensor):\n batch, res = self.evaluate([batch, output])\n else:\n res = self.evaluate(output)\n\n self.assertEqual(res.shape, (batch, heads, length, depth_v))\n\n @parameterized.named_parameters(\n (\"\", 1, 1, 8, 4, 1, 2),\n (\"dynamic_batch\", None, 1, 8, 4, 1, 2),\n (\"batches\", 4, 3, 8, 4, 1, 2),\n (\"depth_v\", 1, 1, 8, 4, 3, 2),\n (\"block_length\", 1, 1, 8, 4, 1, 4),\n )\n def testMaskedLocalAttention1D(self, batch, heads, length, depth_k, depth_v,\n block_length):\n if batch is None:\n batch = tf.random_uniform([], minval=0, maxval=5, dtype=tf.int32)\n q = tf.random_normal([batch, heads, length, depth_k])\n k = tf.random_normal([batch, heads, length, depth_k])\n v = tf.random_normal([batch, heads, length, depth_v])\n output = common_attention.masked_local_attention_1d(\n q, k, v, block_length=block_length)\n if isinstance(batch, tf.Tensor):\n batch, res = self.evaluate([batch, output])\n else:\n res = self.evaluate(output)\n\n self.assertEqual(res.shape, (batch, heads, length, depth_v))\n\n @parameterized.named_parameters(\n (\"\", 1, 1, 8, 4, 4, (2, 2)),\n (\"dynamic_batch\", None, 1, 8, 4, 4, (2, 2)),\n (\"batches\", 3, 2, 8, 4, 4, (2, 2)),\n # TODO(trandustin): Extend function to enable depth_k != depth_v.\n # (\"depth_v\", 1, 1, 8, 4, 1, (2, 2)),\n (\"query_shape\", 1, 1, 8, 4, 4, (4, 4)),\n )\n def testMaskedLocalAttention2D(self, batch, heads, length, depth_k, depth_v,\n query_shape):\n if batch is None:\n batch = tf.random_uniform([], minval=0, maxval=5, dtype=tf.int32)\n q = tf.random_normal([batch, heads, length, length, depth_k])\n k = tf.random_normal([batch, heads, length, length, depth_k])\n v = tf.random_normal([batch, heads, length, length, depth_v])\n output = common_attention.masked_local_attention_2d(\n q,\n k,\n v,\n query_shape=query_shape,\n memory_flange=(2, 2))\n if isinstance(batch, tf.Tensor):\n batch, res = self.evaluate([batch, output])\n else:\n res = self.evaluate(output)\n\n self.assertEqual(res.shape, (batch, heads, length, length, depth_v))\n\n @parameterized.named_parameters(\n (\"matching_block_length\", 3, 4, 25, 16, 16, 5),\n (\"unmatching_block_length\", 3, 4, 25, 16, 16, 4),\n (\"dynamic_batch\", None, 4, 25, 16, 16, 5),\n (\"different_depth_v\", 3, 4, 25, 16, 17, 5),\n )\n def testLocalUnmaskedAttention1D(self, batch, heads, length,\n depth_k, depth_v, block_length):\n if batch is None:\n batch = tf.random_uniform([], minval=0, maxval=5, dtype=tf.int32)\n q = tf.random_normal([batch, heads, length, depth_k])\n k = tf.random_normal([batch, heads, length, depth_k])\n v = tf.random_normal([batch, heads, length, depth_v])\n output = common_attention.local_attention_1d(\n q, k, v, block_length=block_length, filter_width=3)\n if isinstance(batch, tf.Tensor):\n batch, res = self.evaluate([batch, output])\n else:\n res = self.evaluate(output)\n\n self.assertEqual(res.shape, (batch, heads, length, depth_v))\n\n @parameterized.named_parameters(\n (\"matching_block_length\", 3, 4, 25, 16, 16, (4, 4)),\n (\"unmatching_block_length\", 3, 4, 25, 16, 16, (5, 5)),\n (\"dynamic_batch\", None, 4, 25, 16, 16, (4, 4)),\n # TODO(trandustin): Extend function to enable depth_k != depth_v.\n # (\"different_depth_v\", 3, 4, 25, 16, 17, (4, 4)),\n )\n def testLocalUnmaskedAttention2D(self, batch, heads, length,\n depth_k, depth_v, query_shape):\n if batch is None:\n batch = tf.random_uniform([], minval=0, maxval=5, dtype=tf.int32)\n q = tf.random_normal([batch, heads, length, length, depth_k])\n k = tf.random_normal([batch, heads, length, length, depth_k])\n v = tf.random_normal([batch, heads, length, length, depth_v])\n output = common_attention.local_attention_2d(\n q,\n k,\n v,\n query_shape=query_shape,\n memory_flange=(3, 3))\n if isinstance(batch, tf.Tensor):\n batch, res = self.evaluate([batch, output])\n else:\n res = self.evaluate(output)\n\n self.assertEqual(res.shape, (batch, heads, length, length, depth_v))\n\n @test_utils.run_in_graph_mode_only()\n def testMultiheadSelfAttentionMemoryEfficient(self):\n num_heads = 4\n io_size = 16\n batch = 2\n length = 7\n head_size = 5\n x = np.random.rand(batch, length, io_size)\n dy = np.random.rand(batch, length, io_size)\n with self.test_session() as session:\n x = tf.to_float(x)\n dy = tf.to_float(dy)\n bias = common_attention.attention_bias_lower_triangle(length)\n wqkv = tf.get_variable(\n \"wqkv\", [num_heads, 1, io_size, 3 * head_size],\n initializer=tf.random_normal_initializer(stddev=io_size**-0.5))\n wo = tf.get_variable(\n \"wo\", [num_heads, 1, head_size, io_size],\n initializer=tf.random_normal_initializer(\n stddev=(head_size * num_heads)**-0.5))\n norm_scale, norm_bias = common_layers.layer_norm_vars(io_size)\n y = common_attention.multihead_self_attention_memory_efficient(\n x, bias, num_heads, head_size=head_size, forget=False,\n test_vars=(wqkv, wo, norm_scale, norm_bias))\n y_forget = common_attention.multihead_self_attention_memory_efficient(\n x, bias, num_heads, head_size=head_size, forget=True,\n test_vars=(wqkv, wo, norm_scale, norm_bias))\n dx, dwqkv, dwo, dnorm_scale, dnorm_bias = tf.gradients(\n ys=[y], xs=[x, wqkv, wo, norm_scale, norm_bias], grad_ys=[dy])\n dx_f, dwqkv_f, dwo_f, dnorm_scale_f, dnorm_bias_f = tf.gradients(\n ys=[y_forget], xs=[x, wqkv, wo, norm_scale, norm_bias], grad_ys=[dy])\n session.run(tf.global_variables_initializer())\n (y, y_forget,\n dx, dwqkv, dwo, dnorm_scale, dnorm_bias,\n dx_f, dwqkv_f, dwo_f, dnorm_scale_f, dnorm_bias_f) = session.run(\n [y, y_forget,\n dx, dwqkv, dwo, dnorm_scale, dnorm_bias,\n dx_f, dwqkv_f, dwo_f, dnorm_scale_f, dnorm_bias_f])\n self.assertAllClose(y, y_forget)\n self.assertAllClose(dwo, dwo_f)\n self.assertAllClose(dwqkv, dwqkv_f)\n self.assertAllClose(dnorm_scale, dnorm_scale_f)\n self.assertAllClose(dnorm_bias, dnorm_bias_f)\n self.assertAllClose(dx, dx_f)\n\n @test_utils.run_in_graph_and_eager_modes()\n def test2dGatherAndScatterInvertibility(self):\n \"\"\"2d gather and scatter invertibility test.\"\"\"\n batch_size = 2\n num_heads = 2\n height = 4\n width = 6\n depth = 8\n query_shape = (2, 3)\n x = np.random.rand(batch_size, num_heads, height, width, depth)\n x_indices = common_attention.gather_indices_2d(\n x, query_shape, query_shape)\n gathered_x = common_attention.gather_blocks_2d(x, x_indices)\n x_shape = tf.constant([batch_size, num_heads, height, width, depth])\n scattered_x = common_attention.scatter_blocks_2d(\n gathered_x, x_indices, x_shape)\n res = self.evaluate(scattered_x)\n self.assertAllClose(x, res)\n\n @test_utils.run_in_graph_and_eager_modes()\n def test2dBlockRasterScanMask(self):\n \"\"\"Testing the 2d block raster scan mask.\"\"\"\n query_shape = (2, 3)\n memory_flange = (2, 1)\n mask = common_attention.make_2d_block_raster_mask(\n query_shape, memory_flange)\n res = self.evaluate(mask)\n correct_mask = np.array(\n [[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0,\n 1.0, 0.0, 1.0, 1.0, 1.0, 1.0],\n [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0,\n 1.0, 0.0, 1.0, 1.0, 1.0, 1.0],\n [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,\n 1.0, 0.0, 1.0, 1.0, 1.0, 1.0],\n [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,\n 1.0, 0.0, 0.0, 1.0, 1.0, 1.0],\n [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,\n 1.0, 0.0, 0.0, 0.0, 1.0, 1.0],\n [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,\n 1.0, 0.0, 0.0, 0.0, 0.0, 1.0]])\n self.assertAllClose(correct_mask, res)\n\n @test_utils.run_in_graph_and_eager_modes()\n def test2dGather(self):\n \"\"\"Testing 2d index gather and block gather functions.\"\"\"\n batch_size = 2\n num_heads = 2\n height = 4\n width = 6\n depth = 8\n query_shape = (2, 3)\n x = np.random.rand(batch_size, num_heads, height, width, depth)\n y = np.reshape(x, (batch_size, num_heads, -1, depth))\n correct_indices = [[0, 1, 2, 6, 7, 8],\n [3, 4, 5, 9, 10, 11],\n [12, 13, 14, 18, 19, 20],\n [15, 16, 17, 21, 22, 23]]\n correct_gathered_x = [[[y[0, 0, correct_indices[0]],\n y[0, 0, correct_indices[1]],\n y[0, 0, correct_indices[2]],\n y[0, 0, correct_indices[3]]],\n [y[0, 1, correct_indices[0]],\n y[0, 1, correct_indices[1]],\n y[0, 1, correct_indices[2]],\n y[0, 1, correct_indices[3]]]],\n [[y[1, 0, correct_indices[0]],\n y[1, 0, correct_indices[1]],\n y[1, 0, correct_indices[2]],\n y[1, 0, correct_indices[3]]],\n [y[1, 1, correct_indices[0]],\n y[1, 1, correct_indices[1]],\n y[1, 1, correct_indices[2]],\n y[1, 1, correct_indices[3]]]]]\n\n x_indices = common_attention.gather_indices_2d(\n x, query_shape, query_shape)\n gathered_x = common_attention.gather_blocks_2d(x, x_indices)\n x_indices, gathered_x = self.evaluate([x_indices, gathered_x])\n self.assertAllEqual(correct_indices, x_indices)\n self.assertAllClose(correct_gathered_x, gathered_x)\n\n @test_utils.run_in_graph_and_eager_modes()\n def testGetMemoryRegion(self):\n \"\"\"Testing the function that gathers the flanged memory region.\"\"\"\n np.set_printoptions(threshold=np.inf)\n batch_size = 2\n num_heads = 2\n height = 4\n width = 6\n depth = 3\n query_shape = (2, 3)\n memory_flange = (1, 1)\n\n x = np.random.rand(batch_size, num_heads, height, width, depth)\n y = np.reshape(x, (batch_size, num_heads, -1, depth))\n zeros = np.zeros((depth), dtype=np.float32)\n five_zeros = np.array([zeros]*5)\n seven_zeros = np.array([zeros]*7)\n two_zeros = np.array([zeros]*2)\n zeros = np.array([zeros])\n\n correct_x_flange = [[[seven_zeros,\n np.concatenate((five_zeros, y[0, 0, [2, 8]]),\n axis=0),\n np.concatenate((zeros, y[0, 0, [6, 7, 8, 9]],\n two_zeros), axis=0),\n np.concatenate((y[0, 0, [8, 9, 10, 11]], zeros,\n y[0, 0, [14, 20]]), axis=0)],\n [seven_zeros,\n np.concatenate((five_zeros, y[0, 1, [2, 8]]),\n axis=0),\n np.concatenate((zeros, y[0, 1, [6, 7, 8, 9]],\n two_zeros), axis=0),\n np.concatenate((y[0, 1, [8, 9, 10, 11]], zeros,\n y[0, 1, [14, 20]]), axis=0)]],\n [[seven_zeros,\n np.concatenate((five_zeros, y[1, 0, [2, 8]]),\n axis=0),\n np.concatenate((zeros, y[1, 0, [6, 7, 8, 9]],\n two_zeros), axis=0),\n np.concatenate((y[1, 0, [8, 9, 10, 11]], zeros,\n y[1, 0, [14, 20]]), axis=0)],\n [seven_zeros,\n np.concatenate((five_zeros, y[1, 1, [2, 8]]),\n axis=0),\n np.concatenate((zeros, y[1, 1, [6, 7, 8, 9]],\n two_zeros), axis=0),\n np.concatenate((y[1, 1, [8, 9, 10, 11]], zeros,\n y[1, 1, [14, 20]]), axis=0)]]]\n correct_x_flange = np.array(correct_x_flange)\n correct_x_center = [[[y[0, 0, [0, 1, 2, 6, 7, 8]],\n y[0, 0, [3, 4, 5, 9, 10, 11]],\n y[0, 0, [12, 13, 14, 18, 19, 20]],\n y[0, 0, [15, 16, 17, 21, 22, 23]]],\n [y[0, 1, [0, 1, 2, 6, 7, 8]],\n y[0, 1, [3, 4, 5, 9, 10, 11]],\n y[0, 1, [12, 13, 14, 18, 19, 20]],\n y[0, 1, [15, 16, 17, 21, 22, 23]]]],\n [[y[1, 0, [0, 1, 2, 6, 7, 8]],\n y[1, 0, [3, 4, 5, 9, 10, 11]],\n y[1, 0, [12, 13, 14, 18, 19, 20]],\n y[1, 0, [15, 16, 17, 21, 22, 23]]],\n [y[1, 1, [0, 1, 2, 6, 7, 8]],\n y[1, 1, [3, 4, 5, 9, 10, 11]],\n y[1, 1, [12, 13, 14, 18, 19, 20]],\n y[1, 1, [15, 16, 17, 21, 22, 23]]]]]\n correct_x_center = np.array(correct_x_center)\n x_indices = common_attention.gather_indices_2d(\n x, query_shape, query_shape)\n x_flange, x_center = common_attention.get_memory_region(\n tf.constant(x, dtype=tf.float32),\n query_shape,\n memory_flange,\n x_indices)\n [x_flange, x_center] = self.evaluate([x_flange, x_center])\n self.assertAllClose(correct_x_flange, x_flange)\n self.assertAllClose(correct_x_center, x_center)\n\n @test_utils.run_in_graph_and_eager_modes()\n def testGetShiftedCenterBlocks(self):\n \"\"\"Testing the function that gathers the flanged memory region.\"\"\"\n np.set_printoptions(threshold=np.inf)\n batch_size = 2\n num_heads = 2\n height = 4\n width = 6\n depth = 3\n query_shape = (2, 3)\n\n x = np.random.rand(batch_size, num_heads, height, width, depth)\n y = np.reshape(x, (batch_size, num_heads, -1, depth))\n zeros = np.zeros((depth), dtype=np.float32)\n zeros = np.array([zeros])\n\n correct_gathered_x = [[[np.concatenate((zeros, y[0, 0, [0, 1, 2, 6, 7]]),\n axis=0),\n np.concatenate((zeros, y[0, 0, [3, 4, 5, 9, 10]]),\n axis=0),\n np.concatenate((zeros,\n y[0, 0, [12, 13, 14, 18, 19]]),\n axis=0),\n np.concatenate((zeros,\n y[0, 0, [15, 16, 17, 21, 22]]),\n axis=0)],\n [np.concatenate((zeros, y[0, 1, [0, 1, 2, 6, 7]]),\n axis=0),\n np.concatenate((zeros, y[0, 1, [3, 4, 5, 9, 10]]),\n axis=0),\n np.concatenate((zeros,\n y[0, 1, [12, 13, 14, 18, 19]]),\n axis=0),\n np.concatenate((zeros,\n y[0, 1, [15, 16, 17, 21, 22]]),\n axis=0)]],\n [[np.concatenate((zeros, y[1, 0, [0, 1, 2, 6, 7]]),\n axis=0),\n np.concatenate((zeros, y[1, 0, [3, 4, 5, 9, 10]]),\n axis=0),\n np.concatenate((zeros,\n y[1, 0, [12, 13, 14, 18, 19]]),\n axis=0),\n np.concatenate((zeros,\n y[1, 0, [15, 16, 17, 21, 22]]),\n axis=0)],\n [np.concatenate((zeros, y[1, 1, [0, 1, 2, 6, 7]]),\n axis=0),\n np.concatenate((zeros, y[1, 1, [3, 4, 5, 9, 10]]),\n axis=0),\n np.concatenate((zeros,\n y[1, 1, [12, 13, 14, 18, 19]]),\n axis=0),\n np.concatenate((zeros,\n y[1, 1, [15, 16, 17, 21, 22]]),\n axis=0)]]]\n correct_gathered_x = np.array(correct_gathered_x)\n x_indices = common_attention.gather_indices_2d(\n x, query_shape, query_shape)\n gathered_x = common_attention.get_shifted_center_blocks(\n tf.constant(x, dtype=tf.float32),\n x_indices)\n x_indices, gathered_x = self.evaluate([x_indices, gathered_x])\n self.assertAllClose(correct_gathered_x, gathered_x)\n\n @test_utils.run_in_graph_and_eager_modes()\n def testDotProductAttentionRelative(self):\n x = np.random.rand(5, 7, 12, 32)\n y = np.random.rand(5, 7, 12, 32)\n a = common_attention.dot_product_attention_relative(\n tf.constant(x, dtype=tf.float32),\n tf.constant(y, dtype=tf.float32),\n tf.constant(y, dtype=tf.float32),\n None,\n max_relative_position=3)\n self.evaluate(tf.global_variables_initializer())\n res = self.evaluate(a)\n self.assertEqual(res.shape, (5, 7, 12, 32))\n\n @test_utils.run_in_graph_and_eager_modes()\n def testRelativeAttentionV2(self):\n # (batch, heads, length, depth)\n x = np.random.rand(5, 4, 16, 7)\n y = np.random.rand(5, 4, 16, 7)\n max_relative_position = 3\n a = common_attention.dot_product_self_attention_relative_v2(\n tf.constant(x, dtype=tf.float32),\n tf.constant(y, dtype=tf.float32),\n tf.constant(y, dtype=tf.float32),\n None,\n max_relative_position=max_relative_position,\n heads_share_relative_embedding=False)\n self.evaluate(tf.global_variables_initializer())\n res = self.evaluate(a)\n self.assertEqual(res.shape, (5, 4, 16, 7))\n\n @test_utils.run_in_graph_and_eager_modes()\n def testRelativeAttentionV2SharedRel(self):\n # (batch, heads, length, depth)\n x = np.random.rand(5, 4, 16, 7)\n y = np.random.rand(5, 4, 16, 7)\n max_relative_position = 3\n a = common_attention.dot_product_self_attention_relative_v2(\n tf.constant(x, dtype=tf.float32),\n tf.constant(y, dtype=tf.float32),\n tf.constant(y, dtype=tf.float32),\n None,\n max_relative_position=max_relative_position,\n heads_share_relative_embedding=True)\n self.evaluate(tf.global_variables_initializer())\n res = self.evaluate(a)\n self.assertEqual(res.shape, (5, 4, 16, 7))\n\n @test_utils.run_in_graph_and_eager_modes()\n def testRelativeAttentionV2MaxRelativeLargerThanLength(self):\n # (batch, heads, length, depth)\n x = np.random.rand(5, 4, 3, 7)\n y = np.random.rand(5, 4, 3, 7)\n max_relative_position = 16\n a = common_attention.dot_product_self_attention_relative_v2(\n tf.constant(x, dtype=tf.float32),\n tf.constant(y, dtype=tf.float32),\n tf.constant(y, dtype=tf.float32),\n None,\n max_relative_position=max_relative_position,\n heads_share_relative_embedding=False)\n self.evaluate(tf.global_variables_initializer())\n res = self.evaluate(a)\n self.assertEqual(res.shape, (5, 4, 3, 7))\n\n @test_utils.run_in_graph_and_eager_modes()\n def testDotProductUnMaskedAttentionRelativeV2(self):\n x = np.random.rand(5, 7, 12, 32)\n y = np.random.rand(5, 7, 12, 32)\n a = common_attention.dot_product_unmasked_self_attention_relative_v2(\n tf.constant(x, dtype=tf.float32),\n tf.constant(y, dtype=tf.float32),\n tf.constant(y, dtype=tf.float32),\n None,\n 35)\n self.evaluate(tf.global_variables_initializer())\n res = self.evaluate(a)\n self.assertEqual(res.shape, (5, 7, 12, 32))\n\n @tf.contrib.eager.run_test_in_graph_and_eager_modes()\n def testExtractblocks(self):\n\n batch_size = 1\n num_heads = 3\n height = 6\n width = 10\n depth = 15\n block_h = 3\n block_w = 2\n t = np.random.rand(batch_size * num_heads, height, width, depth)\n a = common_attention._extract_blocks(t, block_h, block_w)\n self.evaluate(tf.global_variables_initializer())\n res = self.evaluate(a)\n self.assertEqual(res.shape, (batch_size * num_heads, height//block_h,\n width//block_w, block_h, block_w, depth))\n # also check if the content is right\n out = np.zeros((batch_size*num_heads, height//block_h,\n width//block_w, block_h, block_w, depth))\n for b in range(batch_size*num_heads):\n for x in range(height//block_h):\n for y in range(width//block_w):\n for v in range(block_h):\n for w in range(block_w):\n out[b, x, y, v, w] = t[b, block_h*x+v, block_w*y+w]\n self.assertAllClose(res, out)\n\n def python_get_2d_local_memory(self, t, batch_size, num_heads, height, width,\n num_h_blocks, num_w_blocks, query_shape,\n memory_flange, depth):\n # also check if the content is right\n out = np.zeros((batch_size, num_heads, height//query_shape[0],\n width//query_shape[1], query_shape[0]+2*memory_flange[0],\n query_shape[1]+2*memory_flange[1], depth))\n memory_height = query_shape[0]+2*memory_flange[0]\n memory_width = query_shape[1]+2*memory_flange[1]\n t_padded = np.pad(t, ((0, 0), (0, 0), (memory_flange[0], memory_flange[0]),\n (memory_flange[1], memory_flange[1]), (0, 0)),\n \"constant\",\n constant_values=((0, 0), (0, 0), (0, 0), (0, 0), (0, 0)))\n for b in range(batch_size):\n for h in range(num_heads):\n for x in range(num_h_blocks):\n for y in range(num_w_blocks):\n for v in range(memory_height):\n for w in range(memory_width):\n memory_h_start = x*query_shape[0]\n memory_w_start = y*query_shape[1]\n memory_h_index = memory_h_start + v\n memory_w_index = memory_w_start + w\n out[b, h, x, y, v, w] = t_padded[b, h, memory_h_index,\n memory_w_index]\n return out\n\n @tf.contrib.eager.run_test_in_graph_and_eager_modes()\n def testGet2dLocalMemory(self):\n batch_size = 3\n num_heads = 3\n height = 6\n width = 6\n depth = 15\n num_h_blocks = 3\n num_w_blocks = 3\n memory_flange = [1, 1]\n query_shape = [2, 2]\n t = np.random.rand(batch_size, num_heads, height, width, depth)\n a = common_attention.get_2d_local_memory_v2(\n np.reshape(t, (batch_size*num_heads, height, width, depth)),\n query_shape, memory_flange)\n self.evaluate(tf.global_variables_initializer())\n res = self.evaluate(a)\n self.assertEqual(res.shape, (batch_size*num_heads,\n num_h_blocks,\n num_w_blocks,\n query_shape[0]+2*memory_flange[0],\n query_shape[1]+2*memory_flange[1], depth))\n out = self.python_get_2d_local_memory(t, batch_size, num_heads,\n height, width, num_h_blocks,\n num_w_blocks, query_shape,\n memory_flange, depth)\n out = np.reshape(out, (batch_size*num_heads,\n num_h_blocks,\n num_w_blocks,\n query_shape[0]+2*memory_flange[0],\n query_shape[1]+2*memory_flange[1], depth))\n\n self.assertAllClose(res, out)\n\n @tf.contrib.eager.run_test_in_graph_and_eager_modes()\n def testSplitAlongWidth(self):\n batch_size = 1\n num_heads = 3\n num_outer_h_blocks = 4\n num_outer_w_blocks = 8\n memory_flange = [2, 2]\n num_w_blocks = 3\n depth = 15\n t = np.random.rand(batch_size*num_heads, num_outer_h_blocks,\n num_outer_w_blocks, memory_flange[0], memory_flange[1],\n depth)\n a = common_attention._split_along_width(t)\n # self.evaluate(tf.global_variables_initializer())\n res_l, res_r = self.evaluate(a)\n # res = self.evaluate(a)\n self.assertEqual(res_l.shape, (batch_size*num_heads, num_outer_h_blocks,\n num_w_blocks, memory_flange[0],\n memory_flange[1], depth))\n self.assertEqual(res_r.shape, (batch_size*num_heads, num_outer_h_blocks,\n num_w_blocks, memory_flange[0],\n memory_flange[1], depth))\n # also check if the content is right\n out_l = np.zeros((batch_size*num_heads, num_outer_h_blocks, num_w_blocks,\n memory_flange[0], memory_flange[1], depth))\n out_r = np.zeros((batch_size*num_heads, num_outer_h_blocks, num_w_blocks,\n memory_flange[0], memory_flange[1], depth))\n block_h = memory_flange[0]\n block_w = memory_flange[1]\n for b in range(batch_size*num_heads):\n for x in range(num_outer_h_blocks):\n for y in range(num_w_blocks):\n for v in range(block_h):\n for w in range(block_w):\n # we should compute the index of the position in the\n out_l[b, x, y, v, w] = (\n t[b, x, 2*y, v, w]\n )\n out_r[b, x, y, v, w] = (\n t[b, x, 2*y+3, v, w]\n )\n self.assertAllClose(res_l, out_l)\n self.assertAllClose(res_r, out_r)\n\n @tf.contrib.eager.run_test_in_graph_and_eager_modes()\n def testGetLeftRightBlocks(self):\n batch_size = 1\n num_heads = 3\n num_outer_h_blocks = 6\n num_outer_w_blocks = 6\n memory_flange = [2, 2]\n num_h_blocks = 2\n num_w_blocks = 2\n depth = 15\n t = np.random.rand(batch_size*num_heads, num_outer_h_blocks,\n num_outer_w_blocks, memory_flange[0], memory_flange[1],\n depth)\n a = common_attention._get_left_right_blocks(t)\n self.evaluate(tf.global_variables_initializer())\n res_l, res_r = self.evaluate(a)\n self.assertEqual(res_l.shape, (batch_size*num_heads, num_h_blocks,\n num_w_blocks, memory_flange[0]*2,\n memory_flange[1], depth))\n self.assertEqual(res_r.shape, (batch_size*num_heads, num_h_blocks,\n num_w_blocks, memory_flange[0]*2,\n memory_flange[1], depth))\n # also check if the content is right\n block_h = memory_flange[0]*2\n block_w = memory_flange[1]\n out_l = np.zeros((batch_size*num_heads, num_h_blocks,\n num_w_blocks, memory_flange[0]*2, memory_flange[1],\n depth))\n out_r = np.zeros((batch_size*num_heads, num_h_blocks,\n num_w_blocks, memory_flange[0]*2, memory_flange[1],\n depth))\n block_h = memory_flange[0]*2\n block_w = memory_flange[1]\n for b in range(batch_size*num_heads):\n for x in range(num_h_blocks):\n for y in range(num_w_blocks):\n for v in range(block_h):\n for w in range(block_w):\n # we should compute the index of the position in the\n outer_block_h_index = (\n 1 + block_h//memory_flange[0]*x + v//2)\n h_index = v%memory_flange[0]\n left_outer_w_index = 2*y\n right_outer_w_index = 2*y + 3\n out_l[b, x, y, v, w] = (\n t[b, outer_block_h_index, left_outer_w_index, h_index,\n w]\n )\n out_r[b, x, y, v, w] = (\n t[b, outer_block_h_index, right_outer_w_index, h_index,\n w]\n )\n self.assertAllClose(res_l, out_l)\n self.assertAllClose(res_r, out_r)\n\n @tf.contrib.eager.run_test_in_graph_and_eager_modes()\n def testDotProductUnmaskedAttentionLocal2dTpu(self):\n batch_size = 1\n num_heads = 3\n height = 7\n width = 12\n depth = 15\n num_h_blocks = 4\n num_w_blocks = 6\n memory_flange = [1, 1]\n query_shape = [2, 2]\n memory_h = query_shape[0] + 2*memory_flange[0]\n memory_w = query_shape[1] + 2*memory_flange[1]\n\n q = np.random.rand(batch_size, num_heads, height, width, depth)\n k = np.random.rand(batch_size, num_heads, height, width, depth)\n v = np.random.rand(batch_size, num_heads, height, width, depth)\n a = common_attention.dot_product_unmasked_attention_local_2d_tpu(\n tf.constant(q, dtype=tf.float32),\n tf.constant(k, dtype=tf.float32),\n tf.constant(v, dtype=tf.float32), None, max_relative_position=None,\n query_shape=query_shape, dropout_rate=0.0, image_shapes=None,\n name=None, make_image_summary=False, dropout_broadcast_dims=None)\n self.evaluate(tf.global_variables_initializer())\n res = self.evaluate(a)\n self.assertEqual(res.shape, (batch_size, num_heads,\n height, width, depth))\n # now to check the content too\n # first pad q, k, ad v\n height_padding = -height % query_shape[0]\n width_padding = -width % query_shape[1]\n new_height = height + -height % query_shape[0]\n new_width = width + -width % query_shape[1]\n q = np.pad(q, ((0, 0), (0, 0), (0, height_padding),\n (0, width_padding), (0, 0)), \"constant\",\n constant_values=((0, 0), (0, 0), (0, 0), (0, 0), (0, 0)))\n k = np.pad(k, ((0, 0), (0, 0), (0, height_padding),\n (0, width_padding), (0, 0)), \"constant\",\n constant_values=((0, 0), (0, 0), (0, 0), (0, 0), (0, 0)))\n v = np.pad(v, ((0, 0), (0, 0), (0, height_padding),\n (0, width_padding), (0, 0)), \"constant\",\n constant_values=((0, 0), (0, 0), (0, 0), (0, 0), (0, 0)))\n queries = self.python_get_2d_local_memory(q, batch_size, num_heads,\n new_height, new_width,\n num_h_blocks, num_w_blocks,\n query_shape, [0, 0],\n depth)\n keys = self.python_get_2d_local_memory(k, batch_size, num_heads,\n new_height, new_width, num_h_blocks,\n num_w_blocks, query_shape,\n memory_flange, depth)\n values = self.python_get_2d_local_memory(v, batch_size, num_heads,\n new_height, new_width,\n num_h_blocks, num_w_blocks,\n query_shape,\n memory_flange, depth)\n logits = np.matmul(\n np.reshape(queries, (batch_size, num_heads,\n num_h_blocks, num_w_blocks,\n query_shape[0]*query_shape[1], depth)),\n np.transpose(\n np.reshape(keys, (batch_size, num_heads, num_h_blocks, num_w_blocks,\n memory_h*memory_w, depth)), (0, 1, 2, 3, 5, 4)))\n # now to do a softmax across the logits\n att = np.exp(logits) / np.sum(np.exp(logits), axis=-1, keepdims=True)\n att_output = np.matmul(att, np.reshape(\n values, (batch_size, num_heads, num_h_blocks, num_w_blocks,\n memory_h*memory_w, depth)))\n att_output = np.reshape(att_output,\n (batch_size, num_heads, num_h_blocks, num_w_blocks,\n query_shape[0], query_shape[1], depth))\n # putting the attention results back into the right place\n out = np.zeros((batch_size, num_heads, new_height, new_width, depth))\n for b in range(batch_size):\n for h in range(num_heads):\n for x in range(new_height):\n for y in range(new_width):\n h_block_index = x//query_shape[0]\n w_block_index = y//query_shape[1]\n inside_h_index = x%query_shape[0]\n inside_w_index = y%query_shape[1]\n out[b, h, x, y] = (\n att_output[b, h, h_block_index, w_block_index, inside_h_index,\n inside_w_index])\n out = out[:, :, :height, :width, :]\n self.assertAllClose(res, out)\n\n @tf.contrib.eager.run_test_in_graph_and_eager_modes()\n def testDotProductUnmaskedAttentionLocal2dTpuSimple(self):\n batch_size = 1\n num_heads = 3\n height = 8\n width = 12\n total_depth = 15\n num_h_blocks = 4\n num_w_blocks = 6\n depth = 5\n query_shape = [2, 2]\n\n x = np.random.rand(batch_size, height, width, total_depth)\n a = (\n common_attention.dot_product_unmasked_attention_local_2d_tpu_simple(\n tf.constant(x, dtype=tf.float32),\n None, total_depth, total_depth, num_heads,\n query_shape=query_shape))\n self.evaluate(tf.global_variables_initializer())\n res, q, k, v = self.evaluate(a)\n self.assertEqual(res.shape, (batch_size, height, width, total_depth))\n # reshape q, k, v from batch, heads, height*width to batch, heads,\n # num_h_blocks, num_w_blocks, query_shape[0], query_shape[1], depth\n resh_shape = (batch_size, num_h_blocks, num_w_blocks,\n num_heads, query_shape[0], query_shape[1],\n depth)\n resh = lambda l: np.reshape(l, resh_shape)\n q, k, v = map(resh, [q, k, v])\n trans = lambda l: np.transpose(l, (0, 3, 1, 2, 4, 5, 6))\n q, k, v = map(trans, [q, k, v])\n new_height = height + -height % query_shape[0]\n new_width = width + -width % query_shape[1]\n (queries, keys, values) = (q, k, v)\n logits = np.matmul(\n np.reshape(queries, (batch_size, num_heads,\n num_h_blocks, num_w_blocks,\n query_shape[0]*query_shape[1], depth)),\n np.transpose(\n np.reshape(keys, (batch_size, num_heads, num_h_blocks, num_w_blocks,\n query_shape[0]*query_shape[1], depth)),\n (0, 1, 2, 3, 5, 4)))\n # now to do a softmax across the logits\n att = np.exp(logits) / np.sum(np.exp(logits), axis=-1, keepdims=True)\n att_output = np.matmul(att, np.reshape(\n values, (batch_size, num_heads, num_h_blocks, num_w_blocks,\n query_shape[0]*query_shape[1], depth)))\n att_output = np.reshape(att_output,\n (batch_size, num_heads, num_h_blocks, num_w_blocks,\n query_shape[0], query_shape[1], depth))\n # putting the attention results back into the right place\n out = np.zeros((batch_size, num_heads, new_height, new_width, depth))\n for b in range(batch_size):\n for h in range(num_heads):\n for x in range(new_height):\n for y in range(new_width):\n h_block_index = x//query_shape[0]\n w_block_index = y//query_shape[1]\n inside_h_index = x%query_shape[0]\n inside_w_index = y%query_shape[1]\n out[b, h, x, y] = (\n att_output[b, h, h_block_index, w_block_index, inside_h_index,\n inside_w_index])\n out = np.transpose(out, (0, 2, 3, 1, 4))\n out = np.reshape(out, (batch_size, new_height, new_width, total_depth))\n out = out[:, :height, :width, :]\n\n self.assertAllClose(res, out)\n\n def python_relative_att(self, q, k, v, batch, num_heads, height, width,\n depth, height_key_relative_embeddings,\n width_key_relative_embeddings,\n heads_share_relative_embedding):\n \"\"\"Relative attention computation in numpy.\n\n For query index (i,j) and key index (l, m) the logit is\n q_i k_j^T + q_i rh_{l-i}^T + q_i rw_{m-j}^T, where rh and ry are the set of\n relative embeddings in height and width spatial dimensions, respectively.\n\n Args:\n q: [batch, heads, height, width, depth] tensor\n k: [batch, heads, height, width, depth] tensor\n v: [batch, heads, height, width, depth] tensor\n batch: int scalar\n num_heads: int scalar\n height: int scalar\n width: int scalar\n depth: int scalar\n height_key_relative_embeddings: a tensor of relative embeddings\n width_key_relative_embeddings: a tensor of relative embeddings\n heads_share_relative_embedding: a boolean\n\n Returns:\n att_output: A tensor\n \"\"\"\n\n logits = np.zeros((batch, num_heads, height*width, height*width))\n for b in range(batch):\n for h in range(num_heads):\n for i in range(height*width):\n q_col = i%width\n q_row = int((i-q_col)/width)\n for j in range(height*width):\n k_col = j%width\n k_row = int((j-k_col)/width)\n logit = np.dot(q[b][h][q_row][q_col], k[b][h][k_row][k_col])\n width_rel_dist = k_col - q_col\n width_rel_index = width-1 + width_rel_dist\n if heads_share_relative_embedding:\n width_rel_logit = (\n np.dot(q[b][h][q_row][q_col],\n width_key_relative_embeddings[width_rel_index]))\n else:\n width_rel_logit = (\n np.dot(q[b][h][q_row][q_col],\n width_key_relative_embeddings[h][width_rel_index]))\n height_rel_dist = k_row - q_row\n height_rel_index = height-1 + height_rel_dist\n if heads_share_relative_embedding:\n height_rel_logit = (\n np.dot(q[b][h][q_row][q_col],\n height_key_relative_embeddings[height_rel_index]))\n else:\n height_rel_logit = (\n np.dot(q[b][h][q_row][q_col],\n height_key_relative_embeddings[h][height_rel_index]))\n logits[b, h, i, j] = logit + width_rel_logit + height_rel_logit\n # now to do a softmax across the logits\n att = np.exp(logits) / np.sum(np.exp(logits), axis=-1, keepdims=True)\n # comparing the outputs\n att_output = np.matmul(att,\n np.reshape(v, (\n batch, num_heads, height*width, depth)))\n att_output = np.reshape(att_output,\n (batch, num_heads, height, width, depth))\n return att_output\n\n @test_utils.run_in_graph_and_eager_modes()\n def testDotProductUnMaskedAttentionRelative2d(self):\n batch = 1\n height = 3\n width = 3\n num_heads = 2\n max_relative_position = 6\n depth = 5\n heads_share_relative_embedding = False\n q = np.random.rand(batch, num_heads, height, width, depth)\n k = np.random.rand(batch, num_heads, height, width, depth)\n v = np.random.rand(batch, num_heads, height, width, depth)\n a = common_attention.dot_product_unmasked_self_attention_relative_2d(\n tf.constant(q, dtype=tf.float32),\n tf.constant(k, dtype=tf.float32),\n tf.constant(v, dtype=tf.float32),\n None,\n max_relative_position=max_relative_position,\n heads_share_relative_embedding=heads_share_relative_embedding)\n\n self.evaluate(tf.global_variables_initializer())\n res, height_key_relative_embeddings, width_key_relative_embeddings = (\n self.evaluate(a))\n att_output = self.python_relative_att(\n q, k, v, batch, num_heads, height, width, depth,\n height_key_relative_embeddings, width_key_relative_embeddings,\n heads_share_relative_embedding)\n self.assertEqual(res.shape, (batch, num_heads, height, width, depth))\n self.assertAllClose(res, att_output)\n\n @parameterized.parameters(\n (1, 10, 12, 2, 6, 3),\n (1, 1, 12, 2, 6, 3),\n (2, 10, 1, 2, 6, 3),\n (1, 10, 12, 2, 1, 1),\n (1, 10, 12, 2, 2, 8),\n (4, 10, 12, 2, 12, 10),\n )\n @test_utils.run_in_graph_and_eager_modes()\n def testDotProductUnMaskedAttentionRelative2dSharedOneRow(\n self, batch, height, width, num_heads, max_relative_position, depth):\n heads_share_relative_embedding = True\n q = np.random.rand(batch, num_heads, height, width, depth)\n k = np.random.rand(batch, num_heads, height, width, depth)\n v = np.random.rand(batch, num_heads, height, width, depth)\n\n a = common_attention.dot_product_unmasked_self_attention_relative_2d(\n tf.constant(q, dtype=tf.float32),\n tf.constant(k, dtype=tf.float32),\n tf.constant(v, dtype=tf.float32),\n None,\n max_relative_position=max_relative_position,\n heads_share_relative_embedding=heads_share_relative_embedding)\n\n self.evaluate(tf.global_variables_initializer())\n (res, height_key_relative_embeddings,\n width_key_relative_embeddings) = self.evaluate(a)\n att_output = self.python_relative_att(\n q, k, v, batch, num_heads, height, width, depth,\n height_key_relative_embeddings, width_key_relative_embeddings,\n heads_share_relative_embedding)\n self.assertEqual(res.shape,\n (batch, num_heads, height, width, depth))\n self.assertAllClose(res, att_output)\n\n @test_utils.run_in_graph_and_eager_modes()\n def testRelativeAttentionV2Unmasked(self):\n # (batch, heads, length, depth)\n x = np.random.rand(5, 4, 16, 7)\n y = np.random.rand(5, 4, 16, 7)\n max_relative_position = 3\n a = common_attention.dot_product_unmasked_self_attention_relative_v2(\n tf.constant(x, dtype=tf.float32),\n tf.constant(y, dtype=tf.float32),\n tf.constant(y, dtype=tf.float32),\n None,\n max_relative_position=max_relative_position,\n heads_share_relative_embedding=False)\n self.evaluate(tf.global_variables_initializer())\n res = self.evaluate(a)\n self.assertEqual(res.shape, (5, 4, 16, 7))\n\n @test_utils.run_in_graph_and_eager_modes()\n def testRelativeAttentionV2UnmaskedSharedRel(self):\n # (batch, heads, length, depth)\n x = np.random.rand(5, 4, 16, 7)\n y = np.random.rand(5, 4, 16, 7)\n max_relative_position = 3\n a = common_attention.dot_product_unmasked_self_attention_relative_v2(\n tf.constant(x, dtype=tf.float32),\n tf.constant(y, dtype=tf.float32),\n tf.constant(y, dtype=tf.float32),\n None,\n max_relative_position=max_relative_position,\n heads_share_relative_embedding=True)\n self.evaluate(tf.global_variables_initializer())\n res = self.evaluate(a)\n self.assertEqual(res.shape, (5, 4, 16, 7))\n\n @test_utils.run_in_graph_and_eager_modes()\n def testRelativeAttentionV2UnmaskedRelativeLargerThanLength(self):\n # (batch, heads, length, depth)\n x = np.random.rand(5, 4, 3, 7)\n y = np.random.rand(5, 4, 3, 7)\n max_relative_position = 16\n a = common_attention.dot_product_unmasked_self_attention_relative_v2(\n tf.constant(x, dtype=tf.float32),\n tf.constant(y, dtype=tf.float32),\n tf.constant(y, dtype=tf.float32),\n None,\n max_relative_position=max_relative_position,\n heads_share_relative_embedding=False)\n self.evaluate(tf.global_variables_initializer())\n res = self.evaluate(a)\n self.assertEqual(res.shape, (5, 4, 3, 7))\n\n @test_utils.run_in_graph_and_eager_modes()\n def testMaskedRelativeLocalAttentionV2(self):\n # (batch, heads, length, depth)\n x = np.random.rand(5, 4, 16, 7)\n y = np.random.rand(5, 4, 16, 7)\n block_length = 3\n a = common_attention.masked_relative_local_attention_1d(\n tf.constant(x, dtype=tf.float32),\n tf.constant(y, dtype=tf.float32),\n tf.constant(y, dtype=tf.float32),\n block_length=block_length,\n heads_share_relative_embedding=True,\n add_relative_to_values=False,\n name=\"masked_relative_local_attention_1d\")\n self.evaluate(tf.global_variables_initializer())\n res = self.evaluate(a)\n self.assertEqual(res.shape, (5, 4, 16, 7))\n\n @test_utils.run_in_graph_and_eager_modes()\n def testMaskedRelativeLocalAttentionV2AddRelativeValues(self):\n # (batch, heads, length, depth)\n x = np.random.rand(5, 4, 16, 7)\n y = np.random.rand(5, 4, 16, 7)\n block_length = 3\n a = common_attention.masked_relative_local_attention_1d(\n tf.constant(x, dtype=tf.float32),\n tf.constant(y, dtype=tf.float32),\n tf.constant(y, dtype=tf.float32),\n block_length=block_length,\n heads_share_relative_embedding=True,\n add_relative_to_values=False,\n name=\"masked_relative_local_attention_1d\")\n self.evaluate(tf.global_variables_initializer())\n res = self.evaluate(a)\n self.assertEqual(res.shape, (5, 4, 16, 7))\n\n @test_utils.run_in_graph_and_eager_modes()\n def testMaskedRelativeLocalAttentionV2SeqShorterThanBlockLength(self):\n # (batch, heads, length, depth)\n x = np.random.rand(5, 7, 2, 7)\n y = np.random.rand(5, 7, 2, 7)\n block_length = 3\n a = common_attention.masked_relative_local_attention_1d(\n tf.constant(x, dtype=tf.float32),\n tf.constant(y, dtype=tf.float32),\n tf.constant(y, dtype=tf.float32),\n block_length=block_length,\n heads_share_relative_embedding=True,\n name=\"masked_relative_local_attention_1d\")\n self.evaluate(tf.global_variables_initializer())\n res = self.evaluate(a)\n self.assertEqual(res.shape, (5, 7, 2, 7))\n\n @test_utils.run_in_graph_and_eager_modes()\n def testMaskedRelativeLocalAttentionV2SeqShorterThanTwiceBlockLength(self):\n # (batch, heads, length, depth)\n x = np.random.rand(5, 7, 5, 7)\n y = np.random.rand(5, 7, 5, 7)\n block_length = 3\n a = common_attention.masked_relative_local_attention_1d(\n tf.constant(x, dtype=tf.float32),\n tf.constant(y, dtype=tf.float32),\n tf.constant(y, dtype=tf.float32),\n block_length=block_length,\n heads_share_relative_embedding=True,\n name=\"masked_relative_local_attention_1d\")\n self.evaluate(tf.global_variables_initializer())\n res = self.evaluate(a)\n self.assertEqual(res.shape, (5, 7, 5, 7))\n\n def testBiasBatchCoordinates(self):\n \"\"\"Testing the batch coordinates mask.\"\"\"\n q = tf.constant([0, 0, 1, 1, 1, 1, 2, 2, 2], dtype=tf.int32)\n q = tf.expand_dims(q, axis=-1)\n\n k = tf.constant([0, 0, 0, 2, 2, 3, 3, 3], dtype=tf.int32)\n k = tf.expand_dims(k, axis=-1)\n\n ground_truth = np.array([\n [0, 0, 0, 1, 1, 1, 1, 1], # 0\n [0, 0, 0, 1, 1, 1, 1, 1],\n [1, 1, 1, 1, 1, 1, 1, 1], # 1 (just masked)\n [1, 1, 1, 1, 1, 1, 1, 1],\n [1, 1, 1, 1, 1, 1, 1, 1],\n [1, 1, 1, 1, 1, 1, 1, 1],\n [1, 1, 1, 0, 0, 1, 1, 1], # 2\n [1, 1, 1, 0, 0, 1, 1, 1],\n [1, 1, 1, 0, 0, 1, 1, 1],\n ], np.float32) * -1e9\n\n bias = common_attention.attention_bias_coordinates(q, k)\n self.assertAllClose(self.evaluate(bias), ground_truth)\n\n @test_utils.run_in_graph_and_eager_modes()\n def testBiasFuture(self):\n \"\"\"Testing the sequence order mask.\"\"\"\n q = tf.constant([0, 1, 2, 3, 0, 1, 2, 0, 1], dtype=tf.int32)\n q = tf.expand_dims(q, axis=-1)\n\n k = tf.constant([0, 1, 2, 3, 4, 0, 1, 2], dtype=tf.int32)\n k = tf.expand_dims(k, axis=-1)\n\n ground_truth = np.array([\n [0, 1, 1, 1, 1, 0, 1, 1], # 0\n [0, 0, 1, 1, 1, 0, 0, 1], # 1\n [0, 0, 0, 1, 1, 0, 0, 0], # 2\n [0, 0, 0, 0, 1, 0, 0, 0], # 3\n [0, 1, 1, 1, 1, 0, 1, 1], # 0\n [0, 0, 1, 1, 1, 0, 0, 1], # 1\n [0, 0, 0, 1, 1, 0, 0, 0], # 2\n [0, 1, 1, 1, 1, 0, 1, 1], # 0\n [0, 0, 1, 1, 1, 0, 0, 1], # 1\n ], np.float32) * -1e9\n\n bias = common_attention.attention_bias_future(q, k)\n self.assertAllClose(self.evaluate(bias), ground_truth)\n\n @test_utils.run_in_graph_mode_only()\n def testMultiheadAttentionWithLayerCollection(self):\n \"\"\"Testing multihead attention with layer collection for kfac.\"\"\"\n x = tf.zeros([3, 4, 5], tf.float32)\n layer_collection = kfac.LayerCollection()\n common_attention.multihead_attention(\n x, None, None, 10, 10, 10, 2, 0.2,\n layer_collection=layer_collection)\n self.assertLen(layer_collection.get_blocks(), 4)\n\n @parameterized.named_parameters(\n (\"\", 1, 1, 8, 4, 3),\n (\"dynamic_batch\", None, 1, 8, 4, 2),\n (\"batches\", 4, 3, 8, 4, 2),\n (\"block_length\", 1, 1, 8, 4, 4),\n )\n def testDilatedAttention(self, batch, heads, length, depth_v, block_length):\n if batch is None:\n batch = tf.random_uniform([], minval=0, maxval=5, dtype=tf.int32)\n q = tf.random_normal([batch, heads, length, depth_v])\n k = tf.random_normal([batch, heads, length, depth_v])\n v = tf.random_normal([batch, heads, length, depth_v])\n output = common_attention.dilated_self_attention_1d(\n q, k, v,\n query_block_size=block_length,\n memory_block_size=block_length,\n gap_size=2,\n num_memory_blocks=2)\n if isinstance(batch, tf.Tensor):\n batch, res = self.evaluate([batch, output])\n else:\n res = self.evaluate(output)\n\n self.assertEqual(res.shape, (batch, heads, length, depth_v))\n\n @parameterized.named_parameters(\n (\"\", 1, 1, 8, 4, 3),\n (\"dynamic_batch\", None, 1, 8, 4, 2),\n (\"batches\", 4, 3, 8, 4, 2),\n (\"block_length\", 1, 1, 8, 4, 4),\n )\n def testMaskedDilatedAttention(self, batch, heads, length, depth_v,\n block_length):\n if batch is None:\n batch = tf.random_uniform([], minval=0, maxval=5, dtype=tf.int32)\n q = tf.random_normal([batch, heads, length, depth_v])\n k = tf.random_normal([batch, heads, length, depth_v])\n v = tf.random_normal([batch, heads, length, depth_v])\n output = common_attention.masked_dilated_self_attention_1d(\n q, k, v,\n query_block_size=block_length,\n memory_block_size=block_length,\n gap_size=2,\n num_memory_blocks=2)\n if isinstance(batch, tf.Tensor):\n batch, res = self.evaluate([batch, output])\n else:\n res = self.evaluate(output)\n\n self.assertEqual(res.shape, (batch, heads, length, depth_v))\n\nif __name__ == \"__main__\":\n tf.test.main()\n" ]
[ [ "numpy.sum", "tensorflow.ones", "tensorflow.random_normal", "tensorflow.contrib.eager.run_test_in_graph_and_eager_modes", "numpy.transpose", "tensorflow.global_variables_initializer", "numpy.reshape", "numpy.set_printoptions", "tensorflow.random_normal_initializer", "numpy.random.rand", "tensorflow.constant", "tensorflow.test.main", "numpy.zeros", "numpy.dot", "tensorflow.to_float", "tensorflow.expand_dims", "tensorflow.random_uniform", "tensorflow.gradients", "numpy.prod", "tensorflow.compat.v1.enable_eager_execution", "numpy.pad", "tensorflow.zeros", "tensorflow.range", "numpy.exp", "numpy.array", "numpy.concatenate" ] ]
NCLPhD/FedML
[ "ffa15262ee963b9c856f34f0b2202f4dfeb3a76b" ]
[ "python/fedml/cross_silo/hierarchical/trainer_dist_adapter.py" ]
[ "from torch.nn.parallel import DistributedDataParallel as DDP\nimport torch.distributed as dist\n\nfrom .fedml_trainer import FedMLTrainer\nfrom .process_group_manager import ProcessGroupManager\nfrom torch.nn.parallel import DistributedDataParallel as DDP\nfrom .trainer.my_model_trainer_classification import MyModelTrainer as MyModelTrainerCLS\nfrom .trainer.my_model_trainer_nwp import MyModelTrainer as MyModelTrainerNWP\nfrom .trainer.my_model_trainer_tag_prediction import MyModelTrainer as MyModelTrainerTAG\nfrom ...utils.logging import logger\nfrom .fedml_trainer import FedMLTrainer\n# import torch\n# import time\n\n# from ...standalone.fedavg.my_model_trainer_classification import MyModelTrainer as MyModelTrainerCLS\n# from ...standalone.fedavg.my_model_trainer_nwp import MyModelTrainer as MyModelTrainerNWP\n# from ...standalone.fedavg.my_model_trainer_tag_prediction import MyModelTrainer as MyModelTrainerTAG\n# from .process_group_manager import ProcessGroupManager\n# from .utils import transform_list_to_tensor, post_complete_message_to_sweep_process\n# from .message_define import MyMessage\n# import logging\n# import os\n# import sys\n\n# sys.path.insert(0, os.path.abspath(os.path.join(os.getcwd(), \"../../../\")))\n# sys.path.insert(0, os.path.abspath(\n# os.path.join(os.getcwd(), \"../../../../FedML\")))\n\n# try:\n# from fedml_core.distributed.client.client_manager import ClientManager\n# from fedml_core.distributed.communication.message import Message\n# from fedml_core.distributed.communication.utils import log_round_start, log_round_end\n# except ImportError:\n# from fedml_core.distributed.client.client_manager import ClientManager\n# from fedml_core.distributed.communication.message import Message\n# from fedml_core.distributed.communication.utils import log_round_start, log_round_end\n\n\nclass TrainerDistAdapter:\n def __init__(\n self,\n args,\n device,\n client_rank,\n model,\n train_data_num,\n train_data_local_num_dict,\n train_data_local_dict,\n test_data_local_dict,\n model_trainer=None,\n ):\n\n only_gpu = args.using_gpu\n\n self.process_group_manager = ProcessGroupManager(\n args.silo_proc_rank, args.silo_proc_num, args.pg_master_address, args.pg_master_port, only_gpu\n )\n\n # if not args.is_mobile:\n model.to(device)\n model = DDP(model, device_ids=[device] if only_gpu else None)\n\n\n client_index = client_rank - 1\n if model_trainer is None:\n model_trainer = self.get_model_trainer(model, args)\n model_trainer.set_id(client_index)\n logger.info(\"Initiating Trainer\")\n trainer = self.get_trainer(\n client_index,\n train_data_local_dict,\n train_data_local_num_dict,\n test_data_local_dict,\n train_data_num,\n device,\n args,\n model_trainer,\n )\n self.client_index = client_index\n self.client_rank = client_rank\n self.device = device\n self.trainer = trainer\n self.args = args\n\n def get_trainer(\n self,\n client_index,\n train_data_local_dict,\n train_data_local_num_dict,\n test_data_local_dict,\n train_data_num,\n device,\n args,\n model_trainer,\n ):\n return FedMLTrainer(\n client_index,\n train_data_local_dict,\n train_data_local_num_dict,\n test_data_local_dict,\n train_data_num,\n device,\n args,\n model_trainer,\n )\n\n def get_model_trainer(self, model, args):\n\n if args.dataset == \"stackoverflow_lr\":\n model_trainer = MyModelTrainerTAG(model, args, args.enable_cuda_rpc)\n elif args.dataset in [\"fed_shakespeare\", \"stackoverflow_nwp\"]:\n model_trainer = MyModelTrainerNWP(model, args, args.enable_cuda_rpc)\n else: # default model trainer is for classification problem\n model_trainer = MyModelTrainerCLS(model, args, args.enable_cuda_rpc)\n return model_trainer\n\n def train(self, round_idx):\n\n # log_round_start(self.client_rank, round_idx)\n\n dist.barrier()\n weights, local_sample_num = self.trainer.train(round_idx)\n return weights, local_sample_num\n\n def update_model(self, model_params):\n self.trainer.update_model(model_params)\n\n def update_dataset(self, client_index=None):\n _client_index = client_index or self.client_index\n self.trainer.update_dataset(int(_client_index))\n\n def cleanup_pg(self):\n logger.info(\n \"Cleaningup process group for client %s in silo %s\" % (\n self.args.silo_proc_rank, self.args.client_rank)\n )\n self.process_group_manager.cleanup()\n" ]
[ [ "torch.distributed.barrier", "torch.nn.parallel.DistributedDataParallel" ] ]
alexjuda2/z-quantum-core
[ "c258100dbd091f0b22495b77b36399426ae9abac" ]
[ "src/python/zquantum/core/circuits/conversions/qiskit_conversions.py" ]
[ "import hashlib\nfrom typing import Dict, Iterable, List, NamedTuple, Sequence, Tuple, Union\n\nimport numpy as np\nimport qiskit\nimport sympy\n\nfrom .. import _builtin_gates, _circuit, _gates\nfrom ..symbolic.qiskit_expressions import QISKIT_DIALECT, expression_from_qiskit\nfrom ..symbolic.sympy_expressions import SYMPY_DIALECT, expression_from_sympy\nfrom ..symbolic.translations import translate_expression\n\nQiskitOperation = Tuple[\n qiskit.circuit.Instruction, List[qiskit.circuit.Qubit], List[qiskit.circuit.Clbit]\n]\n\n\ndef qiskit_qubit(index: int, num_qubits_in_circuit: int) -> qiskit.circuit.Qubit:\n return qiskit.circuit.Qubit(\n qiskit.circuit.QuantumRegister(num_qubits_in_circuit, \"q\"), index\n )\n\n\ndef _import_qiskit_qubit(qubit: qiskit.circuit.Qubit) -> int:\n return qubit.index\n\n\ndef _qiskit_expr_from_zquantum(expr):\n intermediate = expression_from_sympy(expr)\n return translate_expression(intermediate, QISKIT_DIALECT)\n\n\ndef _zquantum_expr_from_qiskit(expr):\n intermediate = expression_from_qiskit(expr)\n return translate_expression(intermediate, SYMPY_DIALECT)\n\n\nZQUANTUM_QISKIT_GATE_MAP = {\n _builtin_gates.X: qiskit.circuit.library.XGate,\n _builtin_gates.Y: qiskit.circuit.library.YGate,\n _builtin_gates.Z: qiskit.circuit.library.ZGate,\n _builtin_gates.S: qiskit.circuit.library.SGate,\n _builtin_gates.T: qiskit.circuit.library.TGate,\n _builtin_gates.H: qiskit.circuit.library.HGate,\n _builtin_gates.I: qiskit.circuit.library.IGate,\n _builtin_gates.CNOT: qiskit.circuit.library.CXGate,\n _builtin_gates.CZ: qiskit.circuit.library.CZGate,\n _builtin_gates.SWAP: qiskit.circuit.library.SwapGate,\n _builtin_gates.ISWAP: qiskit.circuit.library.iSwapGate,\n _builtin_gates.RX: qiskit.circuit.library.RXGate,\n _builtin_gates.RY: qiskit.circuit.library.RYGate,\n _builtin_gates.RZ: qiskit.circuit.library.RZGate,\n _builtin_gates.PHASE: qiskit.circuit.library.PhaseGate,\n _builtin_gates.CPHASE: qiskit.circuit.library.CPhaseGate,\n _builtin_gates.XX: qiskit.circuit.library.RXXGate,\n _builtin_gates.YY: qiskit.circuit.library.RYYGate,\n _builtin_gates.ZZ: qiskit.circuit.library.RZZGate,\n _builtin_gates.U3: qiskit.circuit.library.U3Gate,\n}\n\n\ndef _make_gate_instance(gate_ref, gate_params) -> _gates.Gate:\n \"\"\"Returns a gate instance that's applicable to qubits.\n For non-parametric gate refs like X, returns just the `X`\n For parametric gate factories like `RX`, returns the produced gate, like `RX(0.2)`\n \"\"\"\n if _gates.gate_is_parametric(gate_ref, gate_params):\n return gate_ref(*gate_params)\n else:\n return gate_ref\n\n\ndef _make_controlled_gate_prototype(wrapped_gate_ref, num_control_qubits=1):\n def _factory(*gate_params):\n return _gates.ControlledGate(\n _make_gate_instance(wrapped_gate_ref, gate_params), num_control_qubits\n )\n\n return _factory\n\n\nQISKIT_ZQUANTUM_GATE_MAP = {\n **{q_cls: z_ref for z_ref, q_cls in ZQUANTUM_QISKIT_GATE_MAP.items()},\n qiskit.circuit.library.CSwapGate: _builtin_gates.SWAP.controlled(1),\n qiskit.circuit.library.CRXGate: _make_controlled_gate_prototype(_builtin_gates.RX),\n qiskit.circuit.library.CRYGate: _make_controlled_gate_prototype(_builtin_gates.RY),\n qiskit.circuit.library.CRZGate: _make_controlled_gate_prototype(_builtin_gates.RZ),\n}\n\n\ndef export_to_qiskit(circuit: _circuit.Circuit) -> qiskit.QuantumCircuit:\n q_circuit = qiskit.QuantumCircuit(circuit.n_qubits)\n custom_names = {\n gate_def.gate_name for gate_def in circuit.collect_custom_gate_definitions()\n }\n q_triplets = [\n _export_gate_to_qiskit(\n gate_op.gate,\n applied_qubit_indices=gate_op.qubit_indices,\n n_qubits_in_circuit=circuit.n_qubits,\n custom_names=custom_names,\n )\n for gate_op in circuit.operations\n ]\n for q_gate, q_qubits, q_clbits in q_triplets:\n q_circuit.append(q_gate, q_qubits, q_clbits)\n return q_circuit\n\n\ndef _export_gate_to_qiskit(\n gate, applied_qubit_indices, n_qubits_in_circuit, custom_names\n):\n try:\n return _export_gate_via_mapping(\n gate, applied_qubit_indices, n_qubits_in_circuit, custom_names\n )\n except ValueError:\n pass\n\n try:\n return _export_controlled_gate(\n gate, applied_qubit_indices, n_qubits_in_circuit, custom_names\n )\n except ValueError:\n pass\n\n try:\n return _export_custom_gate(\n gate, applied_qubit_indices, n_qubits_in_circuit, custom_names\n )\n except ValueError:\n pass\n\n raise NotImplementedError(f\"Exporting gate {gate} to Qiskit is unsupported\")\n\n\ndef _export_gate_via_mapping(\n gate, applied_qubit_indices, n_qubits_in_circuit, custom_names\n):\n try:\n qiskit_cls = ZQUANTUM_QISKIT_GATE_MAP[\n _builtin_gates.builtin_gate_by_name(gate.name)\n ]\n except KeyError:\n raise ValueError(f\"Can't export gate {gate} to Qiskit via mapping\")\n\n qiskit_params = [_qiskit_expr_from_zquantum(param) for param in gate.params]\n qiskit_qubits = [\n qiskit_qubit(qubit_i, n_qubits_in_circuit) for qubit_i in applied_qubit_indices\n ]\n\n return qiskit_cls(*qiskit_params), qiskit_qubits, []\n\n\ndef _export_controlled_gate(\n gate: _gates.ControlledGate,\n applied_qubit_indices,\n n_qubits_in_circuit,\n custom_names,\n):\n if not isinstance(gate, _gates.ControlledGate):\n # Raising an exception here is redundant to the type hint, but it allows us\n # to handle exporting all gates in the same way, regardless of type\n raise ValueError(f\"Can't export gate {gate} as a controlled gate\")\n\n target_indices = applied_qubit_indices[gate.num_control_qubits :]\n target_gate, _, _ = _export_gate_to_qiskit(\n gate.wrapped_gate,\n applied_qubit_indices=target_indices,\n n_qubits_in_circuit=n_qubits_in_circuit,\n custom_names=custom_names,\n )\n controlled_gate = target_gate.control(gate.num_control_qubits)\n qiskit_qubits = [\n qiskit_qubit(qubit_i, n_qubits_in_circuit) for qubit_i in applied_qubit_indices\n ]\n return controlled_gate, qiskit_qubits, []\n\n\ndef _export_custom_gate(\n gate: _gates.MatrixFactoryGate,\n applied_qubit_indices,\n n_qubits_in_circuit,\n custom_names,\n):\n if gate.name not in custom_names:\n raise ValueError(\n f\"Can't export gate {gate} as a custom gate, the circuit is missing its \"\n \"definition\"\n )\n\n if gate.params:\n raise ValueError(\n f\"Can't export parametrized gate {gate}, Qiskit doesn't support \"\n \"parametrized custom gates\"\n )\n # At that time of writing it Qiskit doesn't support parametrized gates defined with\n # a symbolic matrix.\n # See https://github.com/Qiskit/qiskit-terra/issues/4751 for more info.\n\n qiskit_qubits = [\n qiskit_qubit(qubit_i, n_qubits_in_circuit) for qubit_i in applied_qubit_indices\n ]\n qiskit_matrix = np.array(gate.matrix)\n return (\n qiskit.extensions.UnitaryGate(qiskit_matrix, label=gate.name),\n qiskit_qubits,\n [],\n )\n\n\nclass AnonGateOperation(NamedTuple):\n gate_name: str\n matrix: sympy.Matrix\n qubit_indices: Tuple[int, ...]\n\n\nImportedOperation = Union[_gates.GateOperation, AnonGateOperation]\n\n\ndef _apply_custom_gate(\n anon_op: AnonGateOperation, custom_defs_map: Dict[str, _gates.CustomGateDefinition]\n) -> _gates.GateOperation:\n gate_def = custom_defs_map[anon_op.gate_name]\n # Qiskit doesn't support custom gates with parametrized matrices\n # so we can assume empty params list.\n gate_params: Tuple[sympy.Symbol, ...] = tuple()\n gate = gate_def(*gate_params)\n\n return gate(*anon_op.qubit_indices)\n\n\ndef import_from_qiskit(circuit: qiskit.QuantumCircuit) -> _circuit.Circuit:\n q_ops = [_import_qiskit_triplet(triplet) for triplet in circuit.data]\n anon_ops = [op for op in q_ops if isinstance(op, AnonGateOperation)]\n\n # Qiskit doesn't support custom gates with parametrized matrices\n # so we can assume empty params list.\n params_ordering: Tuple[sympy.Symbol, ...] = tuple()\n custom_defs = {\n anon_op.gate_name: _gates.CustomGateDefinition(\n gate_name=anon_op.gate_name,\n matrix=anon_op.matrix,\n params_ordering=params_ordering,\n )\n for anon_op in anon_ops\n }\n imported_ops = [\n _apply_custom_gate(op, custom_defs) if isinstance(op, AnonGateOperation) else op\n for op in q_ops\n ]\n return _circuit.Circuit(\n operations=imported_ops,\n n_qubits=circuit.num_qubits,\n )\n\n\ndef _import_qiskit_triplet(qiskit_triplet: QiskitOperation) -> ImportedOperation:\n qiskit_op, qiskit_qubits, _ = qiskit_triplet\n\n return _import_qiskit_op(qiskit_op, qiskit_qubits)\n\n\ndef _import_qiskit_op(qiskit_op, qiskit_qubits) -> ImportedOperation:\n # We always wanna try importing via mapping to handle complex gate structures\n # represented by a single class, like CNOT (Control + X) or CSwap (Control + Swap).\n try:\n return _import_qiskit_op_via_mapping(qiskit_op, qiskit_qubits)\n except ValueError:\n pass\n\n try:\n return _import_controlled_qiskit_op(qiskit_op, qiskit_qubits)\n except ValueError:\n pass\n\n return _import_custom_qiskit_gate(qiskit_op, qiskit_qubits)\n\n\ndef _import_qiskit_op_via_mapping(\n qiskit_gate: qiskit.circuit.Instruction,\n qiskit_qubits: Iterable[qiskit.circuit.Qubit],\n) -> _gates.GateOperation:\n try:\n gate_ref = QISKIT_ZQUANTUM_GATE_MAP[type(qiskit_gate)]\n except KeyError:\n raise ValueError(f\"Conversion of {qiskit_gate} from Qiskit is unsupported.\")\n\n # values to consider:\n # - gate matrix parameters (only parametric gates)\n # - gate application indices (all gates)\n zquantum_params = [\n _zquantum_expr_from_qiskit(param) for param in qiskit_gate.params\n ]\n qubit_indices = [_import_qiskit_qubit(qubit) for qubit in qiskit_qubits]\n gate = _make_gate_instance(gate_ref, zquantum_params)\n return _gates.GateOperation(gate=gate, qubit_indices=tuple(qubit_indices))\n\n\ndef _import_controlled_qiskit_op(\n qiskit_gate: qiskit.circuit.ControlledGate,\n qiskit_qubits: Sequence[qiskit.circuit.Qubit],\n) -> _gates.GateOperation:\n if not isinstance(qiskit_gate, qiskit.circuit.ControlledGate):\n # Raising an exception here is redundant to the type hint, but it allows us\n # to handle exporting all gates in the same way, regardless of type\n raise ValueError(f\"Can't import gate {qiskit_gate} as a controlled gate\")\n\n wrapped_qubits = qiskit_qubits[qiskit_gate.num_ctrl_qubits :]\n wrapped_op = _import_qiskit_op(qiskit_gate.base_gate, wrapped_qubits)\n qubit_indices = map(_import_qiskit_qubit, qiskit_qubits)\n if isinstance(wrapped_op, _gates.GateOperation):\n return wrapped_op.gate.controlled(qiskit_gate.num_ctrl_qubits)(*qubit_indices)\n else:\n raise NotImplementedError(\n \"Importing of controlled anonymous gates not yet supported.\"\n )\n\n\ndef _hash_hex(bytes_):\n return hashlib.sha256(bytes_).hexdigest()\n\n\ndef _custom_qiskit_gate_name(gate_label: str, gate_name: str, matrix: np.ndarray):\n matrix_hash = _hash_hex(matrix.tobytes())\n target_name = gate_label or gate_name\n return f\"{target_name}.{matrix_hash}\"\n\n\ndef _import_custom_qiskit_gate(\n qiskit_op: qiskit.circuit.Gate, qiskit_qubits\n) -> AnonGateOperation:\n value_matrix = qiskit_op.to_matrix()\n return AnonGateOperation(\n gate_name=_custom_qiskit_gate_name(\n qiskit_op.label, qiskit_op.name, value_matrix\n ),\n matrix=sympy.Matrix(value_matrix),\n qubit_indices=tuple(_import_qiskit_qubit(qubit) for qubit in qiskit_qubits),\n )\n" ]
[ [ "numpy.array" ] ]
aalaprana995/Turtlebot_Navigation_Non_Holonomic_Constrains-
[ "9978467def69080fcd4da7c856e54b6ebda98248" ]
[ "code/final_rrl.py" ]
[ "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Apr 28 00:33:10 2019\r\n\r\n@author: Aalap\r\n\"\"\"\r\n\r\n\r\n# -*- coding: utf-8 -*\r\n\"\"\"\r\nCreated on Thu Mar 28 18:47:25 2019\r\n\r\n@author: Aalap\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport math\r\n\r\nclass Node:\r\n def __init__(self, nodex, nodey,nodetheta, cost, parentnode,vx,vy,vt):\r\n self.nodex = nodex\r\n self.nodey = nodey\r\n self.nodetheta=nodetheta\r\n self.cost = cost\r\n self.parentnode = parentnode\r\n self.vx=vx\r\n self.vy=vy\r\n self.vt=vt\r\n def get_nodex(self):\r\n return self.nodex\r\n def get_nodey(self):\r\n return self.nodey\r\n def get_nodetheta(self):\r\n return self.nodetheta\r\n def get_vx(self):\r\n return vx\r\n def get_vy(self):\r\n return vy\r\n def get_vt(self):\r\n return vt\r\n\r\ndef motion(current_node,ur,ul,time):\r\n r=3.8\r\n l=23\r\n ur=0.104666667*ur\r\n ul=0.104666667*ul\r\n \r\n \r\n thetadot=(r/l)*(ur-ul)\r\n newnodetheta=thetadot*time+current_node.nodetheta\r\n xdot=(r/2)*(ur+ul)*(math.cos(current_node.nodetheta))\r\n ydot=(r/2)*(ur+ul)*(math.sin(current_node.nodetheta))\r\n d=math.sqrt((ydot)**2+(xdot)**2)\r\n #delta_x=d*math.cos(newnodetheta)\r\n #delta_y=d*math.sin(newnodetheta)\r\n cost=math.sqrt((xdot*time)**2+(ydot*time)**2)\r\n newcost=round(cost+current_node.cost)\r\n newnodex=round(xdot*time+current_node.nodex)\r\n newnodey=round(ydot*time+current_node.nodey)\r\n xvelocity=(ur)\r\n yvelocity=(ul)\r\n thetavelocity=thetadot\r\n newnodex,newnodey,newnodetheta,newcost,xvelocity,yvelocity,thetavelocity\r\n \r\n\r\n return newnodex,newnodey,newnodetheta,newcost,xvelocity,yvelocity,thetavelocity\r\n\r\n\r\n\r\n\r\n\r\ndef shortest_path(goalnode, visited, reso):\r\n #shortest path found until parent id is -1\r\n path_x = []#stroes path x coordinates\r\n path_y = []#stroes path x coordinates\r\n xvelocity = []\r\n yvelocity = []\r\n thetavelocity =[]\r\n path_x.append((goalnode.nodex))\r\n path_y.append((goalnode.nodey))\r\n xvelocity.append((goalnode.vx))\r\n yvelocity.append((goalnode.vy))\r\n thetavelocity.append((goalnode.vt))\r\n p = goalnode.parentnode\r\n \r\n print(p)\r\n while (p != -1):\r\n print('lll')\r\n tracknode = visited[p]\r\n path_x.append((tracknode.nodex))\r\n path_y.append((tracknode.nodey))\r\n xvelocity.append((tracknode.vx))\r\n yvelocity.append((tracknode.vy))\r\n thetavelocity.append((tracknode.vt))\r\n p = tracknode.parentnode\r\n return path_x, path_y,xvelocity,yvelocity,thetavelocity\r\n\r\ndef node_key(node):\r\n node_key = (node.nodex) * 250 + node.nodey#unique key generation by equation\r\n return node_key\r\n\r\ndef hd(node,goalnode):\r\n d=math.sqrt((node.nodex-goalnode.nodex)**2+(node.nodey-goalnode.nodey)**2)#cost to go\r\n return d \r\n\r\ndef check_node(node,obsmap,obs_x,obs_y):\r\n #check of node correctness\r\n if (node.nodex < (min(obs_x)) or node.nodex > (max(obs_x)) or node.nodey < (min(obs_y)) or node.nodey > (max(obs_y))):\r\n return False\r\n if (obsmap[node.nodex][node.nodey]):\r\n return False\r\n if (node.nodex < 0):\r\n return False\r\n if (node.nodex > 1110):\r\n return False\r\n if (node.nodey < 0):\r\n return False\r\n if (node.nodey > 1011):\r\n return False\r\n return True\r\n\r\ndef check_goal_node(node,goalnode):\r\n d=math.sqrt((node.nodex-goalnode.nodex)**2+(node.nodey-goalnode.nodey)**2)\r\n \r\n if(d<10):\r\n #check goalnode reached\r\n return True\r\n\r\ndef obstacle_map(obs_x, obs_y):\r\n max_x = round(max(obs_x))\r\n max_y = round(max(obs_y))\r\n min_x = round(min(obs_x))\r\n min_y = round(min(obs_y))\r\n\r\n obsmap = np.zeros((1111,1011))#make a world space which is all false \r\n for i in range(min_x,max_x):\r\n for j in range(min_y,max_y):\r\n obsmap[i][j]=False#make a obstacle space that is all false\r\n for index,i in enumerate(obs_x):\r\n obsmap[obs_x[index]][obs_y[index]] = True#update the obstacle space at points where there is obstacle to true\r\n return obsmap\r\n\r\ndef obstacle_space(r,c):\r\n points=[]#stores points of obstacle space\r\n obs_x=[]#stores x coordinates of obstacle space\r\n obs_y=[]#stores y coordinates of obstacle space\r\n e=r+c\r\n \r\n ##circular obstacle space\r\n print(\"computing circle1 obstacle\")\r\n k = 40.5 + (r) + c\r\n for i in range(e,(1111-e)):\r\n for j in range(e,(1011-e)):\r\n if (((i - 390) ** 2 + (j - 45) ** 2 - (k ** 2)) <= 0):\r\n obs_x.append(i)\r\n obs_y.append(j)\r\n points.append([i,j])\r\n print(\"circle1 obstacle computed\")\r\n #print(\"c1x\",obs_x)\r\n #print(\"c1y\",obs_y) \r\n \r\n print(\"computing circle2 obstacle\")\r\n k = 40.5 + (r) + c\r\n for i in range(e,(1111-e)):\r\n for j in range(e,(1011-e)):\r\n if (((i - 438) ** 2 + (j - 274) ** 2 - (k ** 2)) <= 0):\r\n obs_x.append(i)\r\n obs_y.append(j)\r\n points.append([i,j])\r\n print(\"circle2 obstacle computed\")\r\n #print(\"c2x\",obs_x)\r\n #print(\"c2y\",obs_y) \r\n \r\n print(\"computing circle3 obstacle\")\r\n k = 40.5 + (r) + c\r\n for i in range(e,(1111-e)):\r\n for j in range(e,(1011-e)):\r\n if (((i - 438) ** 2 + (j - 736) ** 2 - (k ** 2)) <= 0):\r\n obs_x.append(i)\r\n obs_y.append(j)\r\n points.append([i,j])\r\n print(\"circle3 obstacle computed\")\r\n #print(\"c3x\",obs_x)\r\n #print(\"c3y\",obs_y) \r\n \r\n \r\n print(\"computing circle4 obstacle\")\r\n k = 40.5 + (r) + c\r\n for i in range(e,(1111-e)):\r\n for j in range(e,(1011-e)):\r\n if (((i - 390) ** 2 + (j - 965) ** 2 - (k ** 2)) <= 0):\r\n obs_x.append(i)\r\n obs_y.append(j)\r\n points.append([i,j])\r\n print(\"circle4 obstacle computed\")\r\n #print(\"c4x\",obs_x)\r\n #print(\"c4y\",obs_y) \r\n \r\n print(\"computing rectangle1 obstacle\")\r\n for i in range(e,1111-e):\r\n for j in range(e,1011-e):\r\n if ((i - 1110-r-c <= 0) & (j - 35+r+c >= 0) & (j - 111-r-c <= 0) &(i -927+r+c >= 0)):\r\n obs_x.append(i)\r\n obs_y.append(j)\r\n points.append([i, j])\r\n print(\"computed rectangle1 obstacle\")\r\n \r\n print(\"computing rectangle2 obstacle\")\r\n for i in range(e,1111-e):\r\n for j in range(e,1011-e):\r\n if ((i - 896-r-c <= 0) & (j - 35+r+c >= 0) & (j - 93-r-c <= 0) &(i -779+r+c >= 0)):\r\n obs_x.append(i)\r\n obs_y.append(j)\r\n points.append([i, j])\r\n print(\"computed rectangle2 obstacle\")\r\n \r\n print(\"computing rectangle3 obstacle\")\r\n for i in range(e,1111-e):\r\n for j in range(e,1011-e):\r\n if ((i - 748-r-c <= 0) & (j - 35+r+c >= 0) & (j - 187-r-c <= 0) &(i -474+r+c >= 0)):\r\n obs_x.append(i)\r\n obs_y.append(j)\r\n points.append([i, j])\r\n print(\"computed rectangle3 obstacle\")\r\n \r\n print(\"computing rectangle4 obstacle\")\r\n for i in range(e,1111-e):\r\n for j in range(e,1011-e):\r\n if ((i - 1110-r-c <= 0) & (j - 621+r+c >= 0) & (j - 697-r-c <= 0) &(i -744+r+c >= 0)):\r\n obs_x.append(i)\r\n obs_y.append(j)\r\n points.append([i, j])\r\n print(\"computed rectangle4 obstacle\")\r\n \r\n print(\"computing rectangle5 obstacle\")\r\n for i in range(e,1111-e):\r\n for j in range(e,1011-e):\r\n if ((i - 1110-r-c <= 0) & (j - 448.5+r+c >= 0) & (j - 565.5-r-c <= 0) &(i -1052+r+c >= 0)):\r\n obs_x.append(i)\r\n obs_y.append(j)\r\n points.append([i, j])\r\n print(\"computed rectangle5 obstacle\")\r\n \r\n print(\"computing rectangle6 obstacle\")\r\n for i in range(e,1111-e):\r\n for j in range(e,1011-e):\r\n if ((i - 1110-r-c <= 0) & (j - 362.5+r+c >= 0) & (j - 448.5-r-c <= 0) &(i -1019+r+c >= 0)):\r\n obs_x.append(i)\r\n obs_y.append(j)\r\n points.append([i, j])\r\n print(\"computed rectangle6 obstacle\")\r\n \r\n print(\"computing rectangle7 obstacle\")\r\n for i in range(e,1111-e):\r\n for j in range(e,1011-e):\r\n if ((i - 1110-r-c <= 0) & (j - 178.25+r+c >= 0) & (j - 295.25-r-c <= 0) &(i -1052+r+c >= 0)):\r\n obs_x.append(i)\r\n obs_y.append(j)\r\n points.append([i, j])\r\n print(\"computed rectangle7 obstacle\")\r\n \r\n print(\"computing rectangle8 obstacle\")\r\n for i in range(e,1111-e):\r\n for j in range(e,1011-e):\r\n if ((i - 529-r-c <= 0) & (j - 314.5+r+c >= 0) & (j - 497.5-r-c <= 0) &(i -438+r+c >= 0)):\r\n obs_x.append(i)\r\n obs_y.append(j)\r\n points.append([i, j])\r\n print(\"computed rectangle8 obstacle\")\r\n \r\n print(\"computing rectangle9 obstacle\")\r\n for i in range(e,1111-e):\r\n for j in range(e,1011-e):\r\n if ((i - 712-r-c <= 0) & (j - 256+r+c >= 0) & (j - 332-r-c <= 0) &(i -529+r+c >= 0)):\r\n obs_x.append(i)\r\n obs_y.append(j)\r\n points.append([i, j])\r\n print(\"computed rectangle9 obstacle\")\r\n \r\n print(\"computing rectangle10 obstacle\")\r\n for i in range(e,1111-e):\r\n for j in range(e,1011-e):\r\n if ((i -1026 -r-c <= 0) & (j -919+r+c >= 0) & (j - 1010-r-c <= 0) &(i -983+r+c >= 0)):\r\n obs_x.append(i)\r\n obs_y.append(j)\r\n points.append([i, j])\r\n print(\"computed rectangle10 obstacle\")\r\n \r\n print(\"computing rectangle11 obstacle\")\r\n for i in range(e,1111-e):\r\n for j in range(e,1011-e):\r\n if ((i -918 -r-c <= 0) & (j -827+r+c >= 0) & (j - 1010-r-c <= 0) &(i -832+r+c >= 0)):\r\n obs_x.append(i)\r\n obs_y.append(j)\r\n points.append([i, j])\r\n print(\"computed rectangle11 obstacle\")\r\n \r\n print(\"computing rectangle12 obstacle\")\r\n for i in range(e,1111-e):\r\n for j in range(e,1011-e):\r\n if ((i -1110 -r-c <= 0) & (j -0+r+c >= 0) & (j - 58-r-c <= 0) &(i -585+r+c >= 0)):\r\n obs_x.append(i)\r\n obs_y.append(j)\r\n points.append([i, j])\r\n print(\"computed rectangle12 obstacle\")\r\n \r\n \r\n print(\"computing rectangle13 obstacle\")\r\n for i in range(e,1111-e):\r\n for j in range(e,1011-e):\r\n if ((i -936 -r-c <= 0) & (j -267+r+c >= 0) & (j - 384-r-c <= 0) &(i -784+r+c >= 0)):\r\n obs_x.append(i)\r\n obs_y.append(j)\r\n points.append([i, j])\r\n print(\"computed rectangle13 obstacle\")\r\n \r\n \r\n \r\n \r\n print(\"computing rectangle14 obstacle\")\r\n for i in range(e,1111-e):\r\n for j in range(e,1011-e):\r\n if ((i -309 -r-c <= 0) & (j -750+r+c >= 0) & (j - 910-r-c <= 0) &(i -150+r+c >= 0)):\r\n obs_x.append(i)\r\n obs_y.append(j)\r\n points.append([i, j])\r\n print(\"computed rectangle14 obstacle\")\r\n \r\n #semi circle\r\n print(\"computing semicircle5 obstacle\")\r\n k = 80 + (r) + c\r\n for i in range(e,(1111-e)):\r\n for j in range(e,(1011-e)):\r\n if (((i - 150) ** 2 + (j - 830) ** 2 - (k ** 2)) <= 0):\r\n obs_x.append(i)\r\n obs_y.append(j)\r\n points.append([i,j])\r\n print(\"semicircle5 obstacle computed\")\r\n \r\n print(\"computing semicircle6 obstacle\")\r\n k = 80 + (r) + c\r\n for i in range(e,(1111-e)):\r\n for j in range(e,(1011-e)):\r\n if (((i - 310) ** 2 + (j - 830) ** 2 - (k ** 2)) <= 0):\r\n obs_x.append(i)\r\n obs_y.append(j)\r\n points.append([i,j])\r\n print(\"semicircle6 obstacle computed\")\r\n #boundary obstacle space\r\n print(\"computing boundary \")\r\n if(r==0 and c==0):\r\n for i in range(1111):\r\n for j in range(1011):\r\n if(i==0 or i==1110 or j==1010 or j==0):\r\n obs_x.append(i)\r\n obs_y.append(j)\r\n points.append([i,j])\r\n else:\r\n \r\n e=r+c\r\n for i in range(e,1111-e):\r\n for j in range(e,1011-e):\r\n if(i==r+c or i==1110-r-c or j==1010-r-c or j==r+c):\r\n obs_x.append(i)\r\n obs_y.append(j)\r\n points.append([i,j])\r\n print(\"boundary computed\")\r\n print(min(obs_x))\r\n print(max(obs_x))\r\n print(min(obs_y))\r\n print(max(obs_y)) \r\n return obs_x,obs_y\r\n \r\n\r\ndef a_algo(startx,starty,starttheta,goalx,goaly,goaltheta,reso,r,c,time):\r\n show=True\r\n lx = []#used to store all explored node x\r\n ly = []#used to store all explored node y\r\n flag=0\r\n unvisited=dict()#dictionary to storedunvisited node\r\n visited=dict()#dictionary to stored visited node for back tracking\r\n moves = [[60, 0], [40, 0], [60, 40], [40, 60], [60, 60], [40, 40],\r\n [0,60], [0, 40]]#all possible moves allowed\r\n\r\n startnode = Node(round(startx / reso), round(starty / reso), 0,0, -1,0,0,0)#start node formation\r\n goalnode = Node(round(goalx / reso), round(goaly / reso), 0,1000, 0,0,0,0)#goal node formation\r\n obs_x, obs_y = obstacle_space(r, c)#obstacle space fromed \r\n #obstacle space in discretized formate\r\n obs_x = [round(x / reso) for x in obs_x]\r\n obs_y = [round(y / reso) for y in obs_y]\r\n #obstacle space converted to true false obstacle map \r\n obsmap= obstacle_map(obs_x,obs_y)\r\n #checking if the startnode or goalnode is not in obstacle or out of world space\r\n if not(startnode.nodex < min(obs_x) or startnode.nodex > max(obs_x) or startnode.nodey < min(obs_y) or startnode.nodey > max(obs_y)):\r\n if not(goalnode.nodex < min(obs_x) or goalnode.nodex > max(obs_x) or goalnode.nodey < min(obs_y) or goalnode.nodey > max(obs_y)):\r\n if not obsmap[startnode.nodex][startnode.nodey] and not obsmap[goalnode.nodex][goalnode.nodey]:\r\n flag = 1\r\n \r\n unvisited[node_key(startnode)] = startnode\r\n while (flag):\r\n current_node_id = min(unvisited, key=lambda o: unvisited[o].cost+hd(goalnode,unvisited[o]))#finding minimum cost node\r\n current_node = unvisited[current_node_id]#making it the current node\r\n visited[current_node_id] = current_node#putting current node to visited dictionary\r\n del unvisited[current_node_id]#removing current node from unvisited dictionary\r\n for i, _ in enumerate(moves):#node exploration\r\n newnodex,newnodey,newnodetheta,newcost,xvelocity,yvelocity,thetavelocity = motion(current_node , moves[i][0], moves[i][1],time)\r\n node=Node(newnodex,newnodey,newnodetheta,newcost,current_node_id,xvelocity,yvelocity,thetavelocity)\r\n lx.append(Node.get_nodex(node))#used get node to store new nodex in lx\r\n ly.append(Node.get_nodey(node))#used get node to store new nodey in ly\r\n \r\n if (len(lx)%1000==0):\r\n if(show):\r\n plt.plot(lx,ly,\".r\")\r\n plt.plot(obs_x, obs_y,\".k\")#obstacle space\r\n plt.show()\r\n plt.grid()\r\n \r\n if (check_goal_node(node, goalnode)):\r\n goalnode.nodex=node.nodex\r\n goalnode.parentnode=node.parentnode\r\n goalnode.nodey=node.nodey\r\n goalnode.cost=node.cost\r\n goalnode.vt=node.vt\r\n goalnode.vx=node.vx\r\n goalnode.vy=node.vy\r\n goalnode.nodetheta=node.nodetheta\r\n print(node.parentnode,\"sdaadsas\")\r\n \r\n flag=False\r\n break\r\n f = node_key(node)\r\n if not check_node(node, obsmap,obs_x,obs_y):#check the new node is not in obstacle\r\n continue\r\n if f in visited:#check new node in visited\r\n continue\r\n if f in unvisited:#check node in unvisited and update the parameters\r\n if (unvisited[f].cost > node.cost):\r\n unvisited[f].cost = node.cost\r\n unvisited[f].parentnode = node.parentnode\r\n else:\r\n unvisited[f] = node#add new node to unvisited dictionary\r\n print(visited) \r\n a, b,xvelocity,yvelocity,thetavelocity = shortest_path(goalnode, visited, reso)#return shortest path\r\n \r\n if(flag):\r\n print(\"shortest path aaya\")\r\n else:\r\n print(\"end\") \r\n return a, b, obs_x, obs_y, lx,ly,xvelocity,yvelocity,thetavelocity\r\n\r\n \r\n \r\n \r\n \r\n\r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\ndef main():\r\n print( \"astar algorithm start!!\")\r\n show=True#flag used to display the result\r\n \r\n startx = 50.0 # startx coordinate\r\n starty = 50.0 # starty coordinate\r\n starttheta=0\r\n goalx = 250.0 # goalx coordinate\r\n goaly = 250.0 # goaly coordinate\r\n goaltheta=0\r\n reso = 1 # resolution\r\n r = 24 #robot radius\r\n c= 0# clearance\r\n time=1\r\n if show:\r\n plt.plot(startx/reso, starty/reso, \"xc\")\r\n plt.plot(goalx/reso, goaly/reso, \"xb\")\r\n a,b, obs_x, obs_y, lx,ly,xvelocity,yvelocity,thetavelocity =a_algo(startx,starty,starttheta,goalx,goaly,goaltheta,reso,r,c,time)\r\n print(a)\r\n print(b)\r\n print(xvelocity)\r\n print(yvelocity)\r\n print(thetavelocity)\r\n \r\n \r\n \r\n \r\n if show:\r\n#displaying the result\r\n#if input or output is incorrect then only obstacle and start and goal is displayed \r\n print(\"final output for astar!!!!\")\r\n plt.plot(lx,ly,\".g\")#node explored\r\n plt.plot(obs_x, obs_y,\".k\")#obstacle space\r\n plt.plot(a, b, \"-r\")#shortest path\r\n plt.grid()\r\n plt.show()\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\nif __name__ == '__main__':\r\n main()# -*- coding: utf-8 -*-\r\n\"\"\"\r\nSpyder Editor\r\n\r\nThis is a temporary script file.\r\n\"\"\"\r\n\r\n" ]
[ [ "matplotlib.pyplot.plot", "matplotlib.pyplot.show", "matplotlib.pyplot.grid", "numpy.zeros" ] ]
plopresti/tensorflow
[ "8b0c84d30d957596cbb3bcac9245e114c3f0b65b" ]
[ "tensorflow/python/framework/func_graph.py" ]
[ "# Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"FuncGraph and related functionality.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections as py_collections\nimport itertools\nimport weakref\n\nfrom tensorflow.core.framework import attr_value_pb2\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.eager import execute\nfrom tensorflow.python.eager import tape\nfrom tensorflow.python.eager.graph_only_ops import graph_placeholder\nfrom tensorflow.python.framework import composite_tensor\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import tensor_spec\nfrom tensorflow.python.framework.auto_control_deps import AutomaticControlDependencies\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import custom_gradient\nfrom tensorflow.python.ops import resource_variable_ops\nfrom tensorflow.python.ops import tensor_array_ops\nfrom tensorflow.python.ops import variable_scope\nfrom tensorflow.python.util import compat\nfrom tensorflow.python.util import memory\nfrom tensorflow.python.util import nest\nfrom tensorflow.python.util import tf_contextlib\nfrom tensorflow.python.util import tf_decorator\nfrom tensorflow.python.util.lazy_loader import LazyLoader\n\n# This is to avoid a circular dependency:\n# function -> func_graph\nfunction = LazyLoader(\"function\", globals(),\n \"tensorflow.python.eager.function\")\ndef_function = LazyLoader(\n \"def_function\", globals(),\n \"tensorflow.python.eager.def_function\")\n\nWHITELIST_COLLECTIONS = [\n ops.GraphKeys.GLOBAL_VARIABLES,\n ops.GraphKeys.LOCAL_VARIABLES,\n ops.GraphKeys.TRAINABLE_VARIABLES,\n variable_scope._VARSTORE_KEY, # pylint: disable=protected-access\n variable_scope._VARSCOPESTORE_KEY # pylint: disable=protected-access\n]\n\n\nclass UnknownArgument(object):\n \"\"\"Signifies an argument which is not currently handled.\"\"\"\n pass\n\n\ndef convert_structure_to_signature(structure, arg_names=None):\n \"\"\"Convert a potentially nested structure to a signature.\n\n Args:\n structure: Structure to convert, where top level collection is a list or a\n tuple.\n arg_names: Optional list of arguments that has equal number of elements as\n `structure` and is used for naming corresponding TensorSpecs.\n\n Returns:\n Identical structure that has TensorSpec objects instead of Tensors and\n UknownArgument instead of any unsupported types.\n \"\"\"\n def encode_arg(arg, path):\n \"\"\"A representation for this argument, for converting into signatures.\"\"\"\n if isinstance(arg, ops.Tensor):\n user_specified_name = None\n try:\n user_specified_name = compat.as_str(\n arg.op.get_attr(\"_user_specified_name\"))\n except ValueError:\n pass\n\n if path and user_specified_name and user_specified_name != path[0]:\n # The user has explicitly named the argument differently than the name\n # of the function argument.\n name = user_specified_name\n else:\n name = \"/\".join([str(p) for p in path])\n return tensor_spec.TensorSpec(arg.shape, arg.dtype, name)\n if isinstance(arg, composite_tensor.CompositeTensor):\n # TODO(b/133606651) Do we need to inject arg_name?\n return arg._type_spec # pylint: disable=protected-access\n if isinstance(arg, (\n int,\n float,\n bool,\n type(None),\n dtypes.DType,\n tensor_spec.TensorSpec,\n )):\n return arg\n return UnknownArgument()\n\n # We are using the flattened paths to name the TensorSpecs. We need an\n # explicit name for them downstream.\n flattened = nest.flatten_with_tuple_paths(structure)\n if arg_names:\n if len(arg_names) != len(structure):\n raise ValueError(\n \"Passed in arg_names don't match actual signature (%s).\" % arg_names)\n # Replace all top-level names with their actual arg_names. If a path before\n # was \"(2,'a',1)\", it will become \"(arg_names[2],'a',1)\".\n flattened = [\n ((arg_names[path[0]],) + path[1:], arg) for path, arg in flattened\n ]\n\n mapped = [encode_arg(arg, path) for path, arg in flattened]\n return nest.pack_sequence_as(structure, mapped)\n\n\nclass FuncGraph(ops.Graph):\n \"\"\"Graph representing a function body.\n\n Attributes:\n name: The name of the function.\n inputs: Placeholder tensors representing the inputs to this function. The\n tensors are in this FuncGraph. This represents \"regular\" inputs as well as\n captured inputs (i.e. the values of self.captures), with the regular\n inputs coming first.\n outputs: Tensors that will be returned by this function. The tensors are in\n this FuncGraph.\n control_outputs: Operations that must be executed before the function\n represented by this graph can be said to have been executed.\n structured_input_signature: A tuple of (args, kwargs), which are both\n possibly-nested python objects that were received by this function. Note\n that these structures might contain Python `None`s.\n structured_outputs: A possibly-nested python object which will be returned\n by this function. The Tensors in this structure are the same as those of\n self.outputs. Note that this structure might contain Python `None`s.\n variables: Variables that should be watched during function execution.\n outer_graph: The graph this function is defined in. May be another FuncGraph\n or the global default Graph.\n captures: Maps external tensor -> internal tensor (i.e. input placeholder).\n The entries are in the order they were captured.\n deferred_captures: Maps arbitrary key -> (closure, nest of placeholders),\n where at function call time the value of closure() will be used to feed\n the nest of placeholders.\n control_captures: Set of external ops on which this graph has a control\n dependency.\n seed: The graph-level random seed.\n capture_by_value: If True, the func graph will capture Variables by value\n instead of reference.\n \"\"\"\n\n def __init__(self, name, collections=None, capture_by_value=None):\n \"\"\"Construct a new FuncGraph.\n\n The graph will inherit its graph key, collections, seed, and distribution\n strategy stack from the current context or graph.\n\n Args:\n name: the name of the function.\n collections: a dictionary of collections this FuncGraph should start\n with. If not specified (None), the FuncGraph will read (but not write\n to) the outer graph's collections that are not whitelisted, and both\n read and write to the outer graph's collections that are whitelisted.\n The current whitelisted collections are the global variables, the\n local variables, and the trainable variables.\n Defaults to None.\n capture_by_value: An optional boolean. If True, the func graph will\n capture Variables by value instead of reference. By default inherit\n from outer graphs, and failing that will default to False.\n \"\"\"\n super(FuncGraph, self).__init__()\n\n self.name = name\n self.inputs = []\n self.outputs = []\n self.control_outputs = []\n self.control_captures = set()\n self.structured_input_signature = None\n self.structured_outputs = None\n self._weak_variables = []\n self._watched_variables = weakref.WeakSet()\n self.outer_graph = ops.get_default_graph()\n self.captures = py_collections.OrderedDict()\n # If not None, records the names of output args of this function. Used to\n # preserve the output names in the signature of a serialized+deserialized\n # function. Private at the moment mostly because it's often out of date.\n self._output_names = None\n self.deferred_captures = py_collections.OrderedDict()\n # Inherit capture-by-value from outer graph.\n if capture_by_value is not None:\n self.capture_by_value = capture_by_value\n elif self.outer_graph is not None and isinstance(\n self.outer_graph, FuncGraph):\n self.capture_by_value = self.outer_graph.capture_by_value\n else:\n self.capture_by_value = False\n\n self._building_function = True\n # Map from resource tensor name to last op (in program order) which uses\n # this tensor. Used to enforce that execution order matches program order\n # for resource tensors.\n self._last_op_using_resource_tensor = {}\n\n graph = self.outer_graph\n\n if context.executing_eagerly():\n self.seed = context.global_seed()\n # [for tf-data user migration from TF1.0 to 2.0] seed_used keep track of\n # any None op_seed for random_op in the function, in which case we end up\n # using function seed, which could be unintended behavior for the op.\n self._seed_used = False\n else:\n self.seed = graph.seed\n self._seed_used = False\n # TODO(allenl): Figure out if we can remove colocation stack\n # specialization (currently used in cond_v2), here and in the cache key.\n self._colocation_stack = graph._colocation_stack.copy() # pylint: disable=protected-access\n\n if collections is None:\n for collection_name in graph.get_all_collection_keys():\n if collection_name not in WHITELIST_COLLECTIONS:\n self._collections[collection_name] = graph.get_collection(\n collection_name)\n for collection_name in WHITELIST_COLLECTIONS:\n self._collections[collection_name] = graph.get_collection_ref(\n collection_name)\n else:\n self._collections = collections\n\n def __str__(self):\n return \"FuncGraph(name=%s, id=%s)\" % (self.name, id(self))\n\n def watch_variable(self, v):\n \"\"\"Marks the variable v as accessed while building this graph.\"\"\"\n while self is not None and isinstance(self, FuncGraph):\n self._watched_variables.add(v)\n self = self.outer_graph\n\n def capture_call_time_value(self, closure, spec, key=None):\n \"\"\"Creates a placeholder which at call time has the value closure().\n\n Useful, for example, to respect TensorFlow context managers, which are often\n dynamically scoped.\n\n Args:\n closure: function which takes no arguments, to be evaluated at function\n call time, returning a nest of tensors compatible with `spec`.\n spec: nest of TypeSpec for the value to capture.\n key: optional. If not None, multiple calls to lazy_capture with the same\n key in the same graph will return the same placeholder, and the\n first closure will be used at function call time.\n\n Returns:\n Nest of placeholders which, at function call time, will be fed with the\n result of calling closure().\n\n Raises:\n ValueError: at function call time, if the return value of closure() is\n not compatible with `spec`.\n \"\"\"\n if key is None:\n key = object()\n if key not in self.deferred_captures:\n\n def convert_to_placeholder(s):\n if not isinstance(s, tensor_spec.TensorSpec):\n raise TypeError(\n \"Expected a nest of `TypeSpec` objects, found %s of type %s.\" %\n (s, type(s)))\n return array_ops.placeholder(dtype=s.dtype, shape=s.shape)\n\n placeholder = nest.map_structure(\n convert_to_placeholder, spec, expand_composites=True)\n\n def wrapped_closure():\n ret_nest = closure()\n nest.assert_same_structure(spec, ret_nest, expand_composites=True)\n # This uses the tensor dtype defined in `spec` when converting values\n # in `ret_nest` to tensors.\n # pylint: disable=protected-access\n y = nest.map_structure(lambda s, r: s._to_components(r), spec, ret_nest,\n expand_composites=False)\n # pylint: enable=protected-access\n return nest.flatten(y, expand_composites=True)\n\n self.deferred_captures[key] = (wrapped_closure, placeholder)\n return self.deferred_captures[key][1]\n\n def control_dependencies(self, control_inputs):\n \"\"\"Handles control dependencies.\n\n FuncGraph wraps Graph's control_dependencies logic by first filtering out\n any external tensors / operations and storing them in the graph's\n control_captures member. Any consumers of this function graph must then\n decide how to handle the control captures.\n\n Args:\n control_inputs: A list of `Operation` or `Tensor` objects which\n must be executed or computed before running the operations\n defined in the context. Can also be `None` to clear the control\n dependencies.\n\n Returns:\n A context manager that specifies control dependencies for all\n operations constructed within the context.\n\n Raises:\n TypeError: If `control_inputs` is not a list of `Operation` or\n `Tensor` objects.\n \"\"\"\n if control_inputs is None:\n return super(FuncGraph, self).control_dependencies(control_inputs)\n\n filtered_control_inputs = []\n for c in control_inputs:\n # Check for _UnreadVariable\n if (isinstance(c, ops.IndexedSlices) or\n (hasattr(c, \"_handle\") and hasattr(c, \"op\"))):\n c = c.op\n graph_element = ops._as_graph_element(c) # pylint: disable=protected-access\n if graph_element is None:\n graph_element = c\n if graph_element is not None and getattr(\n graph_element, \"graph\", None) is not self:\n self.control_captures.add(graph_element)\n else:\n filtered_control_inputs.append(graph_element)\n return super(FuncGraph, self).control_dependencies(filtered_control_inputs)\n\n def as_default(self):\n outer_cm = super(FuncGraph, self).as_default()\n\n @tf_contextlib.contextmanager\n def inner_cm():\n \"\"\"Context manager for copying distribute.Strategy scope information.\"\"\"\n graph = ops.get_default_graph()\n # pylint: disable=protected-access\n # TODO(b/112906995, nareshmodi): distribution strategy depends on\n # inheriting this stack from the default graph even in eager mode. Maybe\n # it should be part of the eager context? This would also allow us to\n # remove a get_default_graph() call from the function cache lookup.\n old_strategy_stack = self._distribution_strategy_stack\n self._distribution_strategy_stack = list(\n graph._distribution_strategy_stack)\n # We ignore device placements from any outer scopes while tracing the\n # function when possible, to avoid hard-coding them in the function\n # graph. \"Default\" placements come from the PartitionedCallOp's placement,\n # so that the same trace of the Python function may be placed on several\n # different devices and saved functions may be placed on new devices when\n # restored.\n old_device_stack = self._device_function_stack\n if context.executing_eagerly():\n if self._distribution_strategy_stack:\n self._device_function_stack = self._device_function_stack.copy()\n self._add_device_to_stack(context.context().device_name)\n else:\n if (self._distribution_strategy_stack\n or device_stack_has_callable(graph._device_function_stack)):\n # Hard-code devices from device functions in the function body\n self._device_function_stack = graph._device_function_stack.copy()\n\n old_creator_stack = self._variable_creator_stack\n self._variable_creator_stack = graph._variable_creator_stack\n # Inherit the graph key, since this is used for matching variables in\n # optimizers.\n old_graph_key = self._graph_key\n self._graph_key = graph._graph_key\n # Inherit the auto_cast_variable_read_dtype, since this should not change\n # inside a function.\n old_auto_cast_var_read_dtype = self._auto_cast_variable_read_dtype\n self._auto_cast_variable_read_dtype = graph._auto_cast_variable_read_dtype\n # pylint: enable=protected-access\n\n with outer_cm as g:\n try:\n yield g\n finally:\n self._distribution_strategy_stack = old_strategy_stack\n self._device_function_stack = old_device_stack\n self._variable_creator_stack = old_creator_stack\n self._graph_key = old_graph_key\n self._auto_cast_variable_read_dtype = old_auto_cast_var_read_dtype\n return inner_cm()\n\n @property\n def output_types(self):\n return [t.dtype for t in self.outputs]\n\n @property\n def output_shapes(self):\n return [t.shape for t in self.outputs]\n\n @property\n def variables(self):\n \"\"\"A list of variables accessed by this FuncGraph.\n\n Note that functions keep only weak references to variables. Calling the\n function after a variable it accesses has been deleted is an error.\n\n Yields:\n Strong references to variables accessed by this FuncGraph.\n \"\"\"\n for weak_v in self._weak_variables:\n v = weak_v()\n if v is None:\n raise AssertionError(\n \"Called a function referencing variables which have been deleted. \"\n \"This likely means that function-local variables were created and \"\n \"not referenced elsewhere in the program. This is generally a \"\n \"mistake; consider storing variables in an object attribute on \"\n \"first call.\")\n yield v\n\n @variables.setter\n def variables(self, var_list):\n self._weak_variables = [weakref.ref(v) for v in var_list]\n\n def _capture_by_value(\n self,\n op_type,\n inputs,\n dtypes, # pylint: disable=redefined-outer-name\n input_types=None,\n name=None,\n attrs=None,\n op_def=None,\n compute_device=True):\n # When capturing by value, do the read outside\n reverse_captures = dict((v, k) for k, v in self.captures.items())\n uncaptured_inputs = [reverse_captures.get(t, t) for t in inputs]\n with ops.init_scope():\n if context.executing_eagerly():\n attr_list = (\"dtype\", int(attrs[\"dtype\"].type))\n value, = execute.execute(\n compat.as_bytes(op_type), 1, uncaptured_inputs, attr_list,\n context.context())\n else:\n op = ops.get_default_graph()._create_op_internal( # pylint: disable=protected-access\n op_type,\n uncaptured_inputs,\n dtypes,\n input_types,\n name,\n attrs,\n op_def,\n compute_device)\n value = op.outputs[0]\n captured_value = self.capture(value)\n return captured_value.op\n\n def create_op(\n self,\n op_type,\n inputs,\n dtypes=None, # pylint: disable=redefined-outer-name\n input_types=None,\n name=None,\n attrs=None,\n op_def=None,\n compute_shapes=True,\n compute_device=True):\n \"\"\"Like Graph.create_op, except handles external input tensors.\n\n This overload adds functionality to create_op to \"capture\" any external\n input tensors, i.e. tensors from the eager context or outer function graphs\n if this is a nested function. See `capture` for more information.\n\n Args:\n op_type: The `Operation` type to create. This corresponds to the\n `OpDef.name` field for the proto that defines the operation.\n inputs: A list of `Tensor` objects that will be inputs to the `Operation`.\n dtypes: (Optional) A list of `DType` objects that will be the types of the\n tensors that the operation produces.\n input_types: (Optional.) A list of `DType`s that will be the types of\n the tensors that the operation consumes. By default, uses the base\n `DType` of each input in `inputs`. Operations that expect\n reference-typed inputs must specify `input_types` explicitly.\n name: (Optional.) A string name for the operation. If not specified, a\n name is generated based on `op_type`.\n attrs: (Optional.) A dictionary where the key is the attribute name (a\n string) and the value is the respective `attr` attribute of the\n `NodeDef` proto that will represent the operation (an `AttrValue`\n proto).\n op_def: (Optional.) The `OpDef` proto that describes the `op_type` that\n the operation will have.\n compute_shapes: (Optional.) Deprecated. Has no effect (shapes are always\n computed).\n compute_device: (Optional.) If True, device functions will be executed\n to compute the device property of the Operation.\n\n Returns:\n An `Operation` object.\n \"\"\"\n del compute_shapes\n if self.capture_by_value and op_type in [\"ReadVariableOp\",\n \"ResourceGather\"]:\n return self._capture_by_value(op_type, inputs, dtypes, input_types, name,\n attrs, op_def, compute_device)\n\n # This capturing logic interacts poorly with control flow contexts which\n # want to replace inputs of ops far too late in the process. This can lead\n # the context to get confused and try to create an Enter for an Enter. We\n # can detect this here and skip the additional Enter which can confuse loop\n # validation logic.\n if op_type == \"Enter\" and inputs[0].op.type == \"Enter\":\n if inputs[0].op.get_attr(\"frame_name\") == attrs[\"frame_name\"].s:\n return inputs[0].op\n # Calling AddValue on the control flow contexts to force creation of the\n # backward accumulators in the original graph before we create placeholders\n # to capture the inputs.\n ctxt = ops.get_default_graph()._control_flow_context # pylint: disable=protected-access\n for i, inp in enumerate(inputs):\n # TPU Estimator defines a control flow context with no AddValue method.\n if ctxt is not None and hasattr(ctxt, \"AddValue\"):\n inp = ctxt.AddValue(inp)\n inp = self.capture(inp)\n inputs[i] = inp\n return super(FuncGraph, self)._create_op_internal( # pylint: disable=protected-access\n op_type, inputs, dtypes, input_types, name, attrs, op_def,\n compute_device)\n\n def capture(self, tensor, name=None):\n \"\"\"Captures `tensor` if it's external to this graph.\n\n If `tensor` is from a different graph, returns a placeholder for it.\n `tensor` and the placeholder will appear in self.captures, and the\n placeholder will appear in self.inputs. Multiple calls to this method with\n the same `tensor` argument will return the same placeholder. If `tensor` is\n from this graph, returns `tensor`.\n\n Args:\n tensor: Tensor. May be from this FuncGraph or a different graph.\n name: Optional name if a placeholder is created.\n\n Returns:\n Tensor from this FuncGraph.\n \"\"\"\n # Note: _forward_func_graph is currently only set when building the gradient\n # graph graph of a defun call. If the backwards graph tries to capture\n # tensors those will be captured first in the forward graph. This\n # makes sure that any tensor needed by a custom_gradient is correctly\n # captured.\n\n # TODO(b/134097853): figure out a better way to check distributed variables\n if hasattr(tensor, \"_distribute_strategy\") and hasattr(tensor, \"_values\"):\n # This checks if the 'tensor' is a DistributedVariable. When it is a\n # DistributedVariable, we do not want to check its \"graph\" attr as the\n # following if branch does, because \"graph\" is not an attr for the\n # container DistributedVariable object, and the underlying components may\n # not have been initialized yet.\n # The reason we do not use isinstance() is due to cyclic dependency issue.\n if name is None:\n name = str(\"distributed_variable\")\n return self._capture_helper(tensor, name)\n if (getattr(tensor, \"graph\", None) is not self and\n hasattr(self, \"_forward_func_graph\") and\n isinstance(self._forward_func_graph, FuncGraph)):\n tensor = self._forward_func_graph.capture(tensor)\n if isinstance(tensor, ops.EagerTensor):\n if name is None:\n name = str(ops.uid())\n return self._capture_helper(tensor, name)\n if tensor.graph is not self:\n if name is None:\n name = tensor.op.name\n inner_graph = tensor.graph\n while inner_graph is not None and isinstance(inner_graph, FuncGraph):\n if inner_graph is self:\n raise ValueError(\n \"Trying to capture a tensor from an inner function. This can be \"\n \"caused by accessing a tensor defined inside a loop or \"\n \"conditional body, or a subfunction, from a calling function, \"\n \"without going through the proper return value mechanism. \"\n \"Consider using TensorFlow mechanisms such as TensorArrays \"\n \"to return tensors from inner functions or loop / conditional \"\n \"bodies. Tensor: %s; tensor graph: %s; this graph: %s\"\n % (tensor, tensor.graph, self))\n inner_graph = inner_graph.outer_graph\n return self._capture_helper(tensor, name)\n return tensor\n\n def _capture_helper(self, tensor, name):\n captured_tensor = self.captures.get(tensor, None)\n if captured_tensor is None:\n captured_tensor = _create_substitute_placeholder(tensor, name=name,\n dtype=tensor.dtype)\n self.captures[tensor] = captured_tensor\n self.inputs.append(captured_tensor)\n tape.record_operation(\"captured_value\", [captured_tensor], [tensor],\n lambda x: [x])\n return captured_tensor\n\n @property\n def external_captures(self):\n \"\"\"External tensors captured by this function.\"\"\"\n return list(self.captures.keys())\n\n @property\n def internal_captures(self):\n \"\"\"Placeholders in this function corresponding captured tensors.\"\"\"\n return list(self.captures.values())\n\n\ndef func_graph_from_py_func(name,\n python_func,\n args,\n kwargs,\n signature=None,\n func_graph=None,\n autograph=False,\n autograph_options=None,\n add_control_dependencies=True,\n arg_names=None,\n op_return_value=None,\n collections=None,\n capture_by_value=None,\n override_flat_arg_shapes=None):\n \"\"\"Returns a `FuncGraph` generated from `python_func`.\n\n Args:\n name: an identifier for the function.\n python_func: the Python function to trace.\n args: the positional args with which the Python function should be called;\n ignored if a signature is provided.\n kwargs: the keyword args with which the Python function should be called;\n ignored if a signature is provided.\n signature: a possibly nested sequence of `TensorSpecs` specifying the shapes\n and dtypes of the arguments. When a signature is provided, `args` and\n `kwargs` are ignored, and `python_func` is traced with Tensors conforming\n to `signature`. If `None`, the shapes and dtypes are inferred from the\n inputs.\n func_graph: Optional. An instance of FuncGraph. If provided, we will use\n this graph else a new one is built and returned.\n autograph: whether to use autograph to compile `python_func`.\n See https://www.tensorflow.org/guide/autograph for more information.\n autograph_options: additional knobs to control when `autograph=True`.\n See https://www.tensorflow.org/guide/autograph for more information.\n add_control_dependencies: If True, automatically adds control dependencies\n to ensure program order matches execution order and stateful ops always\n execute.\n arg_names: Optional list of argument names, used to give input placeholders\n recognizable names.\n op_return_value: Optional. A Tensor. If set and `python_func` returns\n Operations, those return values will be replaced with this value. If not\n set, returning an Operation triggers an error.\n collections: a dictionary of collections this FuncGraph should start\n with. If not specified (None), the FuncGraph will read (but not write to)\n the outer graph's collections that are not whitelisted, and both\n read and write to the outer graph's collections that are whitelisted.\n The current whitelisted collections are the global variables, the\n local variables, and the trainable variables.\n Defaults to None.\n capture_by_value: An optional boolean. If True, the func graph will capture\n Variables by value instead of reference. By default inherit from outer\n graphs, and failing that will default to False.\n override_flat_arg_shapes: An optional list of instances that are either\n `None` or `TensorShape`. The length must match that of\n `nest.flatten((args, kwargs), expand_composites=True)`. The entries\n containing value `None` must match entries in flattened arguments\n containing non-tensors, while entries containing a `TensorShape` must\n match entries in the flattened arguments containing tensors.\n\n Returns:\n A FuncGraph.\n\n Raises:\n TypeError: If any of `python_func`'s return values is neither `None` nor a\n `Tensor`.\n ValueError: If both `signature` and `override_flat_arg_shapes` are\n passed in.\n \"\"\"\n if op_return_value is not None:\n assert isinstance(op_return_value, ops.Tensor), op_return_value\n if func_graph is None:\n func_graph = FuncGraph(name, collections=collections,\n capture_by_value=capture_by_value)\n assert isinstance(func_graph, FuncGraph)\n if add_control_dependencies:\n control_manager = AutomaticControlDependencies()\n else:\n control_manager = ops.NullContextmanager()\n with func_graph.as_default(), control_manager as a:\n current_scope = variable_scope.get_variable_scope()\n default_use_recource = current_scope.use_resource\n current_scope.set_use_resource(True)\n\n if signature is not None and override_flat_arg_shapes is not None:\n raise ValueError(\n \"Passed both signature and override_flat_arg_shapes: %s and %s.\"\n % (signature, override_flat_arg_shapes))\n\n if signature is not None:\n args = signature\n kwargs = {}\n\n # Creates and names placeholders for all arguments.\n if override_flat_arg_shapes is not None:\n flat_args = nest.flatten(args, expand_composites=True)\n arg_shapes = override_flat_arg_shapes[:len(flat_args)]\n kwarg_shapes = override_flat_arg_shapes[len(flat_args):]\n else:\n arg_shapes = None\n kwarg_shapes = None\n func_args = _get_defun_inputs_from_args(\n args, arg_names, flat_shapes=arg_shapes)\n func_kwargs = _get_defun_inputs_from_kwargs(\n kwargs, flat_shapes=kwarg_shapes)\n\n # Convert all Tensors into TensorSpecs before saving the structured inputs.\n # If storing pure concrete functions that are not called through polymorphic\n # functions, we don't have access to FunctionSpec, so we need to call the\n # TensorSpecs by their `arg_names` for later binding.\n func_graph.structured_input_signature = (\n convert_structure_to_signature(func_args, arg_names),\n convert_structure_to_signature(func_kwargs))\n\n flat_func_args = nest.flatten(func_args, expand_composites=True)\n flat_func_kwargs = nest.flatten(func_kwargs, expand_composites=True)\n # Temporarily set inputs to allow graph building code to inspect\n # them. Reassigned below.\n func_graph.inputs = [arg for arg in flat_func_args + flat_func_kwargs\n if isinstance(arg, ops.Tensor)]\n\n # Note: `nest.flatten` sorts by keys, as does `_deterministic_dict_values`.\n # Variables to help check whether mutation happens in calling the function\n # Copy the recursive list, tuple and map structure, but not base objects\n func_args_before = nest.pack_sequence_as(func_args, flat_func_args,\n expand_composites=True)\n func_kwargs_before = nest.pack_sequence_as(\n func_kwargs, flat_func_kwargs, expand_composites=True)\n\n def convert(x):\n \"\"\"Converts a function output to a Tensor.\"\"\"\n if x is None:\n return None\n if op_return_value is not None and isinstance(x, ops.Operation):\n # TODO(b/79881896): we currently can't capture external control deps, so\n # this won't work if x needs to be captured (i.e. if python_func returns\n # captured Operations).\n with ops.control_dependencies([x]):\n x = array_ops.identity(op_return_value)\n elif not isinstance(x, tensor_array_ops.TensorArray):\n try:\n x = ops.convert_to_tensor_or_composite(x)\n except (ValueError, TypeError):\n raise TypeError(\n \"To be compatible with tf.contrib.eager.defun, Python functions \"\n \"must return zero or more Tensors; in compilation of %s, found \"\n \"return value of type %s, which is not a Tensor.\" %\n (str(python_func), type(x)))\n if add_control_dependencies:\n x = a.mark_as_return(x)\n return x\n\n try:\n if autograph:\n from tensorflow.python import autograph # pylint: disable=g-import-not-at-top\n _, original_func = tf_decorator.unwrap(python_func)\n\n def wrapper(*args, **kwargs):\n \"\"\"Calls a converted version of original_func.\"\"\"\n # TODO(mdan): Push this block higher in tf.function's call stack.\n try:\n return autograph.converted_call(\n original_func,\n autograph.ConversionOptions(\n recursive=True,\n optional_features=autograph_options,\n force_conversion=True,\n ), args, kwargs)\n except Exception as e: # pylint:disable=broad-except\n if hasattr(e, \"ag_error_metadata\"):\n raise e.ag_error_metadata.to_exception(type(e))\n else:\n raise\n\n # Wrapping around a decorator allows checks like tf_inspect.getargspec\n # to be accurate.\n converted_func = tf_decorator.make_decorator(original_func, wrapper)\n python_func = tf_decorator.rewrap(python_func, original_func,\n converted_func)\n\n func_outputs = python_func(*func_args, **func_kwargs)\n\n # invariant: `func_outputs` contains only Tensors, CompositeTensors,\n # TensorArrays and `None`s.\n func_outputs = nest.map_structure(convert, func_outputs,\n expand_composites=True)\n\n check_mutation(func_args_before, func_args)\n check_mutation(func_kwargs_before, func_kwargs)\n finally:\n current_scope.set_use_resource(default_use_recource)\n\n # Variables in `func_args`, `func_kwargs` should be explicit inputs\n # to the function, not captured inputs.\n graph_variables = list(func_graph._watched_variables) # pylint: disable=protected-access\n arg_variables = set()\n inputs = []\n for arg in (nest.flatten(func_args, expand_composites=True) +\n nest.flatten(func_kwargs, expand_composites=True)):\n if isinstance(arg, resource_variable_ops.BaseResourceVariable):\n # Even if an argument variable was not used in the function, we've\n # already manually captured the resource Tensor when creating argument\n # placeholders.\n resource_placeholder = func_graph.captures.pop(arg.handle, None)\n if resource_placeholder is None:\n continue\n arg_variables.add(arg)\n inputs.append(resource_placeholder)\n elif isinstance(arg, ops.Tensor):\n inputs.append(arg)\n variables = [v for v in graph_variables if v not in arg_variables]\n func_graph.inputs = (\n inputs +\n list(func_graph.captures.values()) +\n nest.flatten(\n [x[1] for x in func_graph.deferred_captures.values()],\n expand_composites=True))\n\n func_graph.structured_outputs = func_outputs\n # Returning a closed-over tensor does not trigger convert_to_tensor.\n func_graph.outputs.extend(\n func_graph.capture(x)\n for x in flatten(func_graph.structured_outputs)\n if x is not None)\n\n func_graph.variables = variables\n\n if add_control_dependencies:\n func_graph.control_outputs.extend(control_manager.ops_which_must_run)\n\n return func_graph\n\n\ndef maybe_captured(tensor):\n \"\"\"If t is a captured value placeholder, returns the original captured value.\n\n Args:\n tensor: Tensor.\n\n Returns:\n A tensor, potentially from a different Graph/FuncGraph.\n \"\"\"\n if (not isinstance(tensor, ops.EagerTensor) and\n tensor.op.graph.building_function and tensor.op.type == \"Placeholder\"):\n for input_t, placeholder_t in tensor.op.graph.captures.items():\n if tensor == placeholder_t:\n return maybe_captured(input_t)\n # pylint: enable=protected-access\n return tensor\n\n\ndef device_stack_has_callable(device_stack):\n \"\"\"Checks whether a device stack contains a callable.\"\"\"\n return any(callable(spec._device_name_or_function) # pylint: disable=protected-access\n for spec in device_stack.peek_objs())\n\n\ndef check_mutation(n1, n2):\n \"\"\"Check if two list of arguments are exactly the same.\"\"\"\n errmsg = (\"Function to be traced should not modify structure of input \"\n \"arguments. Check if your function has list and dictionary \"\n \"operations that alter input arguments, \"\n \"such as `list.pop`, `list.append`\")\n try:\n nest.assert_same_structure(n1, n2, expand_composites=True)\n except ValueError:\n raise ValueError(errmsg)\n\n for arg1, arg2 in zip(nest.flatten(n1, expand_composites=True),\n nest.flatten(n2, expand_composites=True)):\n if arg1 is not arg2:\n raise ValueError(errmsg)\n\n\n# TODO(edloper): If TensorArray becomes a CompositeTensor, then delete this.\ndef flatten(sequence):\n \"\"\"Like nest.flatten w/ expand_composites, but returns flow for TensorArrays.\n\n Args:\n sequence: A nested structure of Tensors, CompositeTensors, and\n TensorArrays.\n\n Returns:\n A list of tensors.\n \"\"\"\n flat_sequence = nest.flatten(sequence, expand_composites=True)\n return [\n item.flow if isinstance(item, tensor_array_ops.TensorArray) else item\n for item in flat_sequence]\n\n\n# TODO(edloper): If TensorArray becomes a CompositeTensor, then delete this.\ndef pack_sequence_as(structure, flat_sequence):\n \"\"\"Like `nest.pack_sequence_as` but also builds TensorArrays from flows.\n\n Args:\n structure: The structure to pack into. May contain Tensors,\n CompositeTensors, or TensorArrays.\n flat_sequence: An iterable containing tensors.\n\n Returns:\n A nested structure.\n\n Raises:\n AssertionError if `structure` and `flat_sequence` are not compatible.\n \"\"\"\n flat_sequence = list(flat_sequence)\n flattened_structure = nest.flatten(structure, expand_composites=True)\n if len(flattened_structure) != len(flat_sequence):\n raise ValueError(\"Mismatch in element count\")\n for i in range(len(flat_sequence)):\n if isinstance(flattened_structure[i], tensor_array_ops.TensorArray):\n flat_sequence[i] = tensor_array_ops.build_ta_with_new_flow(\n old_ta=flattened_structure[i], flow=flat_sequence[i])\n return nest.pack_sequence_as(structure, flat_sequence, expand_composites=True)\n\n\ndef _create_substitute_placeholder(value, name=None, dtype=None):\n \"\"\"Creates a placeholder for `value` and propagates shape info to it.\"\"\"\n # Note: setting ops.control_dependencies(None) ensures we always put\n # capturing placeholders outside of any control flow context.\n with ops.control_dependencies(None):\n placeholder = graph_placeholder(\n dtype=dtype or value.dtype, shape=value.shape, name=name)\n custom_gradient.copy_handle_data(value, placeholder)\n return placeholder\n\n\ndef _get_defun_inputs_from_args(args, names, flat_shapes=None):\n \"\"\"Maps Python function positional args to graph-construction inputs.\"\"\"\n return _get_defun_inputs(\n args, names, structure=args, flat_shapes=flat_shapes)\n\n\ndef _get_defun_inputs(args, names, structure, flat_shapes=None):\n \"\"\"Maps python function args to graph-construction inputs.\n\n Args:\n args: A flat list of user-specified arguments.\n names: A list of strings with user-specified argument names, same length as\n `args`. May be `None`, in which case a generic name is used.\n structure: The original argument list or dictionary.\n flat_shapes: A flat list of values that are either `None` or\n instances of `TensorShape`. If provided, then length must match\n that of `nest.flatten(args, expand_composites=True)`; and locations where\n `args` are instances of `Tensor` must have a corresponding `TensorShape`\n in `flat_shapes`. May be `None`, in which case exact shapes are read\n directly from the args.\n\n Returns:\n Placeholders with the same structure as `structure`.\n\n Raises:\n RuntimeError: if `flat_shapes` is provided, but\n `len(flat_shapes) != len(nest.flatten(args, expand_composites=True))`.\n RuntimeError: if a shape from `flat_shapes` is not None\n for an argument that is not a `Tensor`, `TensorSpec`,\n or `ResourceVariable`.\n \"\"\"\n func_graph = ops.get_default_graph()\n function_inputs = []\n if names is None:\n names = [None] * len(args)\n if flat_shapes is None:\n shapes_iter = itertools.repeat(None)\n else:\n len_flat_args = len(nest.flatten(args, expand_composites=True))\n if len_flat_args != len(flat_shapes):\n raise RuntimeError(\n \"Length of fully flat shapes (%d) must match that of \"\n \"flatten(args) (%d). args: %s, flat_shapes: %s\"\n % (len(flat_shapes),\n len_flat_args,\n args,\n flat_shapes))\n shapes_iter = iter(flat_shapes)\n for arg_value, name in zip(args, names):\n flattened = nest.flatten(arg_value, expand_composites=True)\n tensor_specs = [\n arg for arg in flattened if isinstance(arg, tensor_spec.TensorSpec)\n ]\n specified_names = [arg.name for arg in tensor_specs if arg.name]\n if specified_names and len(specified_names) < len(tensor_specs):\n raise ValueError(\"If specifying TensorSpec names for nested structures, \"\n \"either zero or all names have to be specified.\")\n\n for arg in flattened:\n # We have a shape entry for each arg, regadless of whether it's a real\n # Tensor or not. For non-tensor entries it should be None.\n shape = next(shapes_iter)\n if isinstance(arg, (ops.Tensor, tensor_spec.TensorSpec)):\n if isinstance(arg, tensor_spec.TensorSpec) and arg.name:\n requested_name = arg.name\n else:\n requested_name = name\n placeholder_shape = shape if shape is not None else arg.shape\n try:\n placeholder = graph_placeholder(\n arg.dtype, placeholder_shape,\n name=requested_name)\n except ValueError:\n # Sometimes parameter names are not valid op names, so fall back to\n # unnamed placeholders.\n placeholder = graph_placeholder(arg.dtype, placeholder_shape)\n if name is not None:\n # Record the requested/user-specified name in case it's different than\n # the uniquified name, for validation when exporting signatures.\n placeholder.op._set_attr( # pylint: disable=protected-access\n \"_user_specified_name\",\n attr_value_pb2.AttrValue(s=compat.as_bytes(requested_name)))\n function_inputs.append(placeholder)\n elif isinstance(arg, resource_variable_ops.BaseResourceVariable):\n # Capture arg variables to create placeholders for them. These will be\n # removed as captures after the function is traced (since otherwise we'd\n # just add it back with a new placeholder when the variable was\n # referenced).\n placeholder = func_graph.capture(arg.handle, name=name)\n placeholder.op._set_attr( # pylint: disable=protected-access\n \"_user_specified_name\",\n attr_value_pb2.AttrValue(s=compat.as_bytes(name)))\n function_inputs.append(arg)\n else:\n if shape is not None:\n raise RuntimeError(\n \"Expected provided shape override to be None for arg that isn't \"\n \"a Tensor, but saw arg: '%s', shape: '%s'. args: %s\"\n % (arg, shape, args))\n function_inputs.append(arg)\n return nest.pack_sequence_as(structure, function_inputs,\n expand_composites=True)\n\n\ndef _get_defun_inputs_from_kwargs(kwargs, flat_shapes):\n \"\"\"Maps Python function keyword args to graph-construction inputs.\"\"\"\n if kwargs:\n names, args = zip(*sorted(kwargs.items()))\n else:\n names = []\n args = []\n return _get_defun_inputs(\n args, names, structure=kwargs, flat_shapes=flat_shapes)\n\n\ndef dismantle_func_graph(func_graph):\n \"\"\"Removes reference cycles in `func_graph` FuncGraph.\n\n Helpful for making sure the garbage collector doesn't need to run when\n the FuncGraph goes out of scope, e.g. in tests using defun with\n @test_util.run_in_graph_and_eager_modes(assert_no_eager_garbage=True).\n\n Args:\n func_graph: A `FuncGraph` object to destroy. `func_graph` is unusable\n after this function.\n \"\"\"\n # TODO(b/115366440): Delete this method when a custom OrderedDict is added.\n # Clearing captures using clear() leaves some cycles around.\n while func_graph.captures:\n func_graph.captures.popitem()\n memory.dismantle_ordered_dict(func_graph.captures)\n while func_graph.deferred_captures:\n func_graph.deferred_captures.popitem()\n memory.dismantle_ordered_dict(func_graph.deferred_captures)\n ops.dismantle_graph(func_graph)\n" ]
[ [ "tensorflow.python.framework.ops.NullContextmanager", "tensorflow.python.framework.tensor_spec.TensorSpec", "tensorflow.python.util.tf_decorator.make_decorator", "tensorflow.python.util.nest.flatten", "tensorflow.python.eager.graph_only_ops.graph_placeholder", "tensorflow.python.util.nest.assert_same_structure", "tensorflow.python.framework.ops.convert_to_tensor_or_composite", "tensorflow.python.framework.ops.uid", "tensorflow.python.ops.custom_gradient.copy_handle_data", "tensorflow.python.ops.array_ops.placeholder", "tensorflow.python.autograph.ConversionOptions", "tensorflow.python.eager.context.global_seed", "tensorflow.python.framework.ops.dismantle_graph", "tensorflow.python.eager.tape.record_operation", "tensorflow.python.framework.ops._as_graph_element", "tensorflow.python.framework.auto_control_deps.AutomaticControlDependencies", "tensorflow.python.ops.tensor_array_ops.build_ta_with_new_flow", "tensorflow.python.util.memory.dismantle_ordered_dict", "tensorflow.python.util.tf_decorator.unwrap", "tensorflow.python.ops.array_ops.identity", "tensorflow.python.eager.context.context", "tensorflow.python.framework.ops.control_dependencies", "tensorflow.python.util.compat.as_bytes", "tensorflow.python.framework.ops.init_scope", "tensorflow.python.util.tf_decorator.rewrap", "tensorflow.python.ops.variable_scope.get_variable_scope", "tensorflow.python.framework.ops.get_default_graph", "tensorflow.python.util.nest.flatten_with_tuple_paths", "tensorflow.python.eager.context.executing_eagerly", "tensorflow.python.util.nest.map_structure", "tensorflow.python.util.nest.pack_sequence_as" ] ]
hanhou/map-ephys
[ "4262e1ba68671b342a77f386e4ebabcce138c453" ]
[ "pipeline/plot/unit_characteristic_plot.py" ]
[ "import numpy as np\nimport datajoint as dj\nfrom PIL import ImageColor\nfrom collections import Counter\n\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport itertools\nimport pandas as pd\n\nfrom pipeline import experiment, ephys, psth, lab, histology, ccf, psth_foraging\n\nfrom pipeline.plot.util import (_plot_with_sem, _extract_one_stim_dur,\n _plot_stacked_psth_diff, _plot_avg_psth, _jointplot_w_hue)\nfrom pipeline.plot import unit_psth\nfrom pipeline.util import (_get_units_hemisphere, _get_trial_event_times,\n _get_stim_onset_time, _get_clustering_method)\n\nfrom . import PhotostimError\n\n_plt_xmin = -3\n_plt_xmax = 2\n\n\ndef plot_clustering_quality(probe_insertion, clustering_method=None, axs=None):\n probe_insertion = probe_insertion.proj()\n\n if clustering_method is None:\n try:\n clustering_method = _get_clustering_method(probe_insertion)\n except ValueError as e:\n raise ValueError(str(e) + '\\nPlease specify one with the kwarg \"clustering_method\"')\n\n amp, snr, spk_rate, isi_violation = (ephys.Unit * ephys.UnitStat * ephys.ProbeInsertion.InsertionLocation\n & probe_insertion & {'clustering_method': clustering_method}).fetch(\n 'unit_amp', 'unit_snr', 'avg_firing_rate', 'isi_violation')\n\n metrics = {'amp': amp,\n 'snr': snr,\n 'isi': np.array(isi_violation) * 100, # to percentage\n 'rate': np.array(spk_rate)}\n label_mapper = {'amp': 'Amplitude',\n 'snr': 'Signal to noise ratio (SNR)',\n 'isi': 'ISI violation (%)',\n 'rate': 'Firing rate (spike/s)'}\n\n fig = None\n if axs is None:\n fig, axs = plt.subplots(2, 3, figsize = (12, 8))\n fig.subplots_adjust(wspace=0.4)\n\n assert axs.size == 6\n\n for (m1, m2), ax in zip(itertools.combinations(list(metrics.keys()), 2), axs.flatten()):\n ax.plot(metrics[m1], metrics[m2], '.k')\n ax.set_xlabel(label_mapper[m1])\n ax.set_ylabel(label_mapper[m2])\n\n # cosmetic\n ax.spines['right'].set_visible(False)\n ax.spines['top'].set_visible(False)\n\n return fig\n\n\ndef plot_unit_characteristic(probe_insertion, clustering_method=None, axs=None):\n probe_insertion = probe_insertion.proj()\n\n if clustering_method is None:\n try:\n clustering_method = _get_clustering_method(probe_insertion)\n except ValueError as e:\n raise ValueError(str(e) + '\\nPlease specify one with the kwarg \"clustering_method\"')\n\n if clustering_method in ('kilosort2'):\n q_unit = (ephys.Unit * ephys.ProbeInsertion.InsertionLocation.proj('depth') * ephys.UnitStat\n * lab.ElectrodeConfig.Electrode.proj() * lab.ProbeType.Electrode.proj('x_coord', 'y_coord')\n & probe_insertion & {'clustering_method': clustering_method} & 'unit_quality != \"all\"').proj(\n ..., x='x_coord', y='y_coord')\n else:\n q_unit = (ephys.Unit * ephys.ProbeInsertion.InsertionLocation.proj('depth') * ephys.UnitStat\n & probe_insertion & {'clustering_method': clustering_method} & 'unit_quality != \"all\"').proj(\n ..., x='unit_posx', y='unit_posy')\n\n amp, snr, spk_rate, x, y, insertion_depth = q_unit.fetch(\n 'unit_amp', 'unit_snr', 'avg_firing_rate', 'x', 'y', 'depth')\n\n metrics = pd.DataFrame(list(zip(*(amp/amp.max(), snr/snr.max(), spk_rate/spk_rate.max(),\n x, insertion_depth.astype(float) + y))))\n metrics.columns = ['amp', 'snr', 'rate', 'x', 'y']\n\n # --- prepare for plotting\n shank_count = (ephys.ProbeInsertion & probe_insertion).aggr(lab.ElectrodeConfig.Electrode * lab.ProbeType.Electrode,\n shank_count='count(distinct shank)').fetch1('shank_count')\n m_scale = get_m_scale(shank_count)\n\n ymin = metrics.y.min() - 100\n ymax = metrics.y.max() + 200\n xmax = 1.3 * metrics.x.max()\n xmin = -1/6*xmax\n cosmetic = {'legend': None,\n 'linewidth': 1.75,\n 'alpha': 0.9,\n 'facecolor': 'none', 'edgecolor': 'k'}\n\n # --- plot\n fig = None\n if axs is None:\n fig, axs = plt.subplots(1, 3, figsize=(10, 8))\n fig.subplots_adjust(wspace=0.6)\n\n assert axs.size == 3\n\n sns.scatterplot(data=metrics, x='x', y='y', s=metrics.amp*m_scale, ax=axs[0], **cosmetic)\n sns.scatterplot(data=metrics, x='x', y='y', s=metrics.snr*m_scale, ax=axs[1], **cosmetic)\n sns.scatterplot(data=metrics, x='x', y='y', s=metrics.rate*m_scale, ax=axs[2], **cosmetic)\n\n # manually draw the legend\n lg_ypos = ymax\n data = pd.DataFrame({'x': [0.1*xmax, 0.4*xmax, 0.75*xmax], 'y': [lg_ypos, lg_ypos, lg_ypos],\n 'size_ratio': np.array([0.2, 0.5, 0.8])})\n for ax, ax_maxval in zip(axs.flatten(), (amp.max(), snr.max(), spk_rate.max())):\n sns.scatterplot(data=data, x='x', y='y', s=data.size_ratio*m_scale, ax=ax, **dict(cosmetic, facecolor='k'))\n for _, r in data.iterrows():\n ax.text(r['x']-4, r['y']+70, (r['size_ratio']*ax_maxval).astype(int))\n\n # cosmetic\n for title, ax in zip(('Amplitude', 'SNR', 'Firing rate'), axs.flatten()):\n ax.spines['right'].set_visible(False)\n ax.spines['top'].set_visible(False)\n ax.set_title(title)\n ax.set_xlim((xmin, xmax))\n ax.plot([0.5*xmin, xmax], [lg_ypos-80, lg_ypos-80], '-k')\n ax.set_ylim((ymin, ymax + 150))\n\n return fig\n\n\ndef plot_unit_selectivity(probe_insertion, clustering_method=None, axs=None):\n probe_insertion = probe_insertion.proj()\n\n if clustering_method is None:\n try:\n clustering_method = _get_clustering_method(probe_insertion)\n except ValueError as e:\n raise ValueError(str(e) + '\\nPlease specify one with the kwarg \"clustering_method\"')\n\n if clustering_method in ('kilosort2'):\n q_unit = (psth.PeriodSelectivity * ephys.Unit * ephys.ProbeInsertion.InsertionLocation\n * lab.ElectrodeConfig.Electrode.proj() * lab.ProbeType.Electrode.proj('x_coord', 'y_coord')\n * experiment.Period & probe_insertion & {'clustering_method': clustering_method}\n & 'period_selectivity != \"non-selective\"').proj(..., x='unit_posx', y='unit_posy').proj(\n ..., x='x_coord', y='y_coord')\n else:\n q_unit = (psth.PeriodSelectivity * ephys.Unit * ephys.ProbeInsertion.InsertionLocation\n * experiment.Period & probe_insertion & {'clustering_method': clustering_method}\n & 'period_selectivity != \"non-selective\"').proj(..., x='unit_posx', y='unit_posy')\n\n attr_names = ['unit', 'period', 'period_selectivity', 'contra_firing_rate',\n 'ipsi_firing_rate', 'x', 'y', 'depth']\n selective_units = q_unit.fetch(*attr_names)\n selective_units = pd.DataFrame(selective_units).T\n selective_units.columns = attr_names\n selective_units.period_selectivity.astype('category')\n\n # --- account for insertion depth (manipulator depth)\n selective_units.y = selective_units.depth.values.astype(float) + selective_units.y\n\n # --- get ipsi vs. contra firing rate difference\n f_rate_diff = np.abs(selective_units.ipsi_firing_rate - selective_units.contra_firing_rate)\n selective_units['f_rate_diff'] = f_rate_diff / f_rate_diff.max()\n\n # --- prepare for plotting\n shank_count = (ephys.ProbeInsertion & probe_insertion).aggr(lab.ElectrodeConfig.Electrode * lab.ProbeType.Electrode,\n shank_count='count(distinct shank)').fetch1('shank_count')\n m_scale = get_m_scale(shank_count)\n\n cosmetic = {'legend': None,\n 'linewidth': 0.0001}\n ymin = selective_units.y.min() - 100\n ymax = selective_units.y.max() + 100\n xmax = 1.3 * selective_units.x.max()\n xmin = -1/6*xmax\n\n # a bit of hack to get the 'open circle'\n pts = np.linspace(0, np.pi * 2, 24)\n circ = np.c_[np.sin(pts) / 2, -np.cos(pts) / 2]\n vert = np.r_[circ, circ[::-1] * .7]\n\n open_circle = mpl.path.Path(vert)\n\n # --- plot\n fig = None\n if axs is None:\n fig, axs = plt.subplots(1, 3, figsize=(10, 8))\n fig.subplots_adjust(wspace=0.6)\n\n assert axs.size == 3\n\n for (title, df), ax in zip(((p, selective_units[selective_units.period == p])\n for p in ('sample', 'delay', 'response')), axs):\n sns.scatterplot(data=df, x='x', y='y',\n s=df.f_rate_diff.values.astype(float)*m_scale,\n hue='period_selectivity', marker=open_circle,\n palette={'contra-selective': 'b', 'ipsi-selective': 'r'},\n ax=ax, **cosmetic)\n contra_p = (df.period_selectivity == 'contra-selective').sum() / len(df) * 100\n # cosmetic\n ax.spines['right'].set_visible(False)\n ax.spines['top'].set_visible(False)\n ax.set_title(f'{title}\\n% contra: {contra_p:.2f}\\n% ipsi: {100-contra_p:.2f}')\n ax.set_xlim((xmin, xmax))\n ax.set_xlabel('x')\n ax.set_ylabel('y')\n ax.set_ylim((ymin, ymax))\n\n return fig\n\n\ndef plot_unit_bilateral_photostim_effect(probe_insertion, clustering_method=None, axs=None):\n probe_insertion = probe_insertion.proj()\n\n if not (psth.TrialCondition().get_trials('all_noearlylick_both_alm_stim') & probe_insertion):\n raise PhotostimError('No Bilateral ALM Photo-stimulation present')\n\n if clustering_method is None:\n try:\n clustering_method = _get_clustering_method(probe_insertion)\n except ValueError as e:\n raise ValueError(str(e) + '\\nPlease specify one with the kwarg \"clustering_method\"')\n\n dv_loc = (ephys.ProbeInsertion.InsertionLocation & probe_insertion).fetch1('depth')\n\n no_stim_cond = (psth.TrialCondition\n & {'trial_condition_name':\n 'all_noearlylick_nostim'}).fetch1('KEY')\n\n bi_stim_cond = (psth.TrialCondition\n & {'trial_condition_name':\n 'all_noearlylick_both_alm_stim'}).fetch1('KEY')\n\n units = ephys.Unit & probe_insertion & {'clustering_method': clustering_method} & 'unit_quality != \"all\"'\n\n metrics = pd.DataFrame(columns=['unit', 'x', 'y', 'frate_change'])\n\n # get photostim onset and duration\n stim_durs = np.unique((experiment.Photostim & experiment.PhotostimEvent\n * psth.TrialCondition().get_trials('all_noearlylick_both_alm_stim')\n & probe_insertion).fetch('duration'))\n stim_dur = _extract_one_stim_dur(stim_durs)\n stim_time = _get_stim_onset_time(units, 'all_noearlylick_both_alm_stim')\n\n # XXX: could be done with 1x fetch+join\n for u_idx, unit in enumerate(units.fetch('KEY', order_by='unit')):\n if clustering_method in ('kilosort2'):\n x, y = (ephys.Unit * lab.ElectrodeConfig.Electrode.proj()\n * lab.ProbeType.Electrode.proj('x_coord', 'y_coord') & unit).fetch1('x_coord', 'y_coord')\n else:\n x, y = (ephys.Unit & unit).fetch1('unit_posx', 'unit_posy')\n\n # obtain unit psth per trial, for all nostim and bistim trials\n nostim_trials = ephys.Unit.TrialSpikes & unit & psth.TrialCondition.get_trials(no_stim_cond['trial_condition_name'])\n bistim_trials = ephys.Unit.TrialSpikes & unit & psth.TrialCondition.get_trials(bi_stim_cond['trial_condition_name'])\n\n nostim_psths, nostim_edge = psth.compute_unit_psth(unit, nostim_trials.fetch('KEY'), per_trial=True)\n bistim_psths, bistim_edge = psth.compute_unit_psth(unit, bistim_trials.fetch('KEY'), per_trial=True)\n\n # compute the firing rate difference between contra vs. ipsi within the stimulation time window\n ctrl_frate = np.array([nostim_psth[np.logical_and(nostim_edge >= stim_time,\n nostim_edge <= stim_time + stim_dur)].mean()\n for nostim_psth in nostim_psths])\n stim_frate = np.array([bistim_psth[np.logical_and(bistim_edge >= stim_time,\n bistim_edge <= stim_time + stim_dur)].mean()\n for bistim_psth in bistim_psths])\n\n frate_change = (stim_frate.mean() - ctrl_frate.mean()) / ctrl_frate.mean()\n frate_change = abs(frate_change) if frate_change < 0 else 0.0001\n\n metrics.loc[u_idx] = (int(unit['unit']), x, float(dv_loc) + y, frate_change)\n\n metrics.frate_change = metrics.frate_change / metrics.frate_change.max()\n\n # --- prepare for plotting\n shank_count = (ephys.ProbeInsertion & probe_insertion).aggr(lab.ElectrodeConfig.Electrode * lab.ProbeType.Electrode,\n shank_count='count(distinct shank)').fetch1('shank_count')\n m_scale = get_m_scale(shank_count)\n\n fig = None\n if axs is None:\n fig, axs = plt.subplots(1, 1, figsize=(4, 8))\n\n xmax = 1.3 * metrics.x.max()\n xmin = -1/6*xmax\n\n cosmetic = {'legend': None,\n 'linewidth': 1.75,\n 'alpha': 0.9,\n 'facecolor': 'none', 'edgecolor': 'k'}\n\n sns.scatterplot(data=metrics, x='x', y='y', s=metrics.frate_change*m_scale,\n ax=axs, **cosmetic)\n\n axs.spines['right'].set_visible(False)\n axs.spines['top'].set_visible(False)\n axs.set_title('% change')\n axs.set_xlim((xmin, xmax))\n\n return fig\n\n\ndef plot_pseudocoronal_slice(probe_insertion, shank_no=1):\n # ---- Electrode sites ----\n annotated_electrodes = (lab.ElectrodeConfig.Electrode * lab.ProbeType.Electrode\n * ephys.ProbeInsertion\n * histology.ElectrodeCCFPosition.ElectrodePosition\n & probe_insertion & {'shank': shank_no})\n\n electrode_coords = np.array(list(zip(*annotated_electrodes.fetch(\n 'ccf_z', 'ccf_y', 'ccf_x', order_by='ccf_y')))) # (AP, DV, ML)\n probe_track_coords = np.array(list(zip(*(histology.LabeledProbeTrack.Point\n & probe_insertion & {'shank': shank_no}).fetch(\n 'ccf_z', 'ccf_y', 'ccf_x', order_by='ccf_y'))))\n\n voxel_res = ccf.CCFLabel.CCF_R3_20UM_RESOLUTION\n lr_max, dv_max, _ = ccf.get_ccf_xyz_max()\n\n pseudocoronal_points, shank_ccfs = histology.retrieve_pseudocoronal_slice(probe_insertion, shank_no)\n\n dv_pts, lr_pts, ap_pts, color_codes = pseudocoronal_points.T\n dv_pts = dv_pts.astype(int)\n lr_pts = lr_pts.astype(int)\n color_codes = color_codes.astype(str)\n\n # ---- paint annotation color code ----\n coronal_slice = np.full((dv_max + 1, lr_max + 1, 3), np.nan)\n for color in set(color_codes):\n matched_ind = np.where(color_codes == color)[0]\n dv_ind = dv_pts[matched_ind] # rows\n lr_ind = lr_pts[matched_ind] # cols\n try:\n c_rgb = ImageColor.getcolor(\"#\" + color, \"RGB\")\n except ValueError as e:\n print(str(e))\n continue\n coronal_slice[dv_ind, lr_ind, :] = np.full((len(matched_ind), 3), c_rgb)\n\n # ---- paint the interpolated track of this probe/shank in gray ----\n in_probe_range = np.logical_and(shank_ccfs[:, 1] >= probe_track_coords[:, 1].min(),\n shank_ccfs[:, 1] <= probe_track_coords[:, 1].max())\n in_electrode_range = np.logical_and(shank_ccfs[:, 1] >= electrode_coords[:, 1].min(),\n shank_ccfs[:, 1] <= electrode_coords[:, 1].max())\n\n tracks_coords = shank_ccfs[np.logical_and(in_probe_range, ~in_electrode_range), :]\n coronal_slice[tracks_coords[:, 1], tracks_coords[:, 0], :] = np.full(\n (tracks_coords.shape[0], 3), ImageColor.getcolor(\"#FFFFFF\", \"RGB\"))\n\n # ---- paint electrode sites on this probe/shank in black ----\n coronal_slice[electrode_coords[:, 1], electrode_coords[:, 2], :] = np.full(\n (electrode_coords.shape[0], 3), ImageColor.getcolor(\"#080808\", \"RGB\"))\n\n # ---- downsample the 2D slice to the voxel resolution ----\n coronal_slice = coronal_slice[::voxel_res, ::voxel_res, :]\n\n # paint outside region white\n nan_r, nan_c = np.where(np.nansum(coronal_slice, axis=2) == 0)\n coronal_slice[nan_r, nan_c, :] = np.full((len(nan_r), 3), ImageColor.getcolor(\"#FFFFFF\", \"RGB\"))\n\n # ---- plot ----\n fig, ax = plt.subplots(1, 1)\n ax.imshow(coronal_slice.astype(np.uint8), extent=[0, lr_max, dv_max, 0])\n\n ax.invert_xaxis()\n ax.set_xticks([])\n ax.set_yticks([])\n ax.spines['right'].set_visible(False)\n ax.spines['top'].set_visible(False)\n ax.spines['bottom'].set_visible(False)\n ax.spines['left'].set_visible(False)\n\n return fig\n\n\ndef plot_driftmap(probe_insertion, clustering_method=None, shank_no=1):\n probe_insertion = probe_insertion.proj()\n\n assert histology.InterpolatedShankTrack & probe_insertion\n\n if clustering_method is None:\n try:\n clustering_method = _get_clustering_method(probe_insertion)\n except ValueError as e:\n raise ValueError(str(e) + '\\nPlease specify one with the kwarg \"clustering_method\"')\n\n units = (ephys.Unit * lab.ElectrodeConfig.Electrode\n & probe_insertion & {'clustering_method': clustering_method}\n & 'unit_quality != \"all\"')\n units = (units.proj('spike_times', 'spike_depths', 'unit_posy')\n * ephys.ProbeInsertion.proj()\n * lab.ProbeType.Electrode.proj('shank') & {'shank': shank_no})\n\n # ---- ccf region ----\n annotated_electrodes = (lab.ElectrodeConfig.Electrode * lab.ProbeType.Electrode\n * ephys.ProbeInsertion\n * histology.ElectrodeCCFPosition.ElectrodePosition\n * ccf.CCFAnnotation * ccf.CCFBrainRegion.proj(..., annotation='region_name')\n & probe_insertion & {'shank': shank_no})\n pos_y, ccf_y, color_code = annotated_electrodes.fetch(\n 'y_coord', 'ccf_y', 'color_code', order_by='y_coord DESC')\n\n # CCF position of most ventral recording site\n last_electrode_site = np.array((histology.InterpolatedShankTrack.DeepestElectrodePoint\n & probe_insertion & {'shank': shank_no}).fetch1(\n 'ccf_x', 'ccf_y', 'ccf_z'))\n # CCF position of the brain surface where this shank crosses\n brain_surface_site = np.array((histology.InterpolatedShankTrack.BrainSurfacePoint\n & probe_insertion & {'shank': shank_no}).fetch1(\n 'ccf_x', 'ccf_y', 'ccf_z'))\n\n # CCF position of most ventral recording site, with respect to the brain surface\n y_ref = -np.linalg.norm(last_electrode_site - brain_surface_site)\n\n # ---- spikes ----brain_surface_site\n spike_times, spike_depths = units.fetch('spike_times', 'spike_depths', order_by='unit')\n\n spike_times = np.hstack(spike_times)\n spike_depths = np.hstack(spike_depths)\n\n # histogram\n # time_res = 10 # time resolution: 1sec\n # depth_res = 10 # depth resolution: 10um\n #\n # spike_bins = np.arange(0, spike_times.max() + time_res, time_res)\n # depth_bins = np.arange(spike_depths.min() - depth_res, spike_depths.max() + depth_res, depth_res)\n\n # time-depth 2D histogram\n time_bin_count = 1000\n depth_bin_count = 200\n\n spike_bins = np.linspace(0, spike_times.max(), time_bin_count)\n depth_bins = np.linspace(0, np.nanmax(spike_depths), depth_bin_count)\n\n spk_count, spk_edges, depth_edges = np.histogram2d(spike_times, spike_depths, bins=[spike_bins, depth_bins])\n spk_rates = spk_count / np.mean(np.diff(spike_bins))\n spk_edges = spk_edges[:-1]\n depth_edges = depth_edges[:-1]\n\n # region colorcode, by depths\n binned_hexcodes = []\n\n y_spacing = np.abs(np.nanmedian(np.where(np.diff(pos_y)==0, np.nan, np.diff(pos_y))))\n anno_depth_bins = np.arange(0, depth_bins[-1], y_spacing)\n for s, e in zip(anno_depth_bins[:-1], anno_depth_bins[1:]):\n hexcodes = color_code[np.logical_and(pos_y > s, pos_y <= e)]\n if len(hexcodes):\n binned_hexcodes.append(Counter(hexcodes).most_common()[0][0])\n else:\n binned_hexcodes.append('FFFFFF')\n\n region_rgba = np.array([list(ImageColor.getcolor(\"#\" + chex, \"RGBA\")) for chex in binned_hexcodes])\n region_rgba = np.repeat(region_rgba[:, np.newaxis, :], 10, axis=1)\n\n # canvas setup\n fig = plt.figure(figsize=(16, 8))\n grid = plt.GridSpec(12, 12)\n\n ax_main = plt.subplot(grid[1:, 0:9])\n ax_cbar = plt.subplot(grid[0, 0:9])\n ax_spkcount = plt.subplot(grid[1:, 9:11])\n ax_anno = plt.subplot(grid[1:, 11:])\n\n # -- plot main --\n im = ax_main.imshow(spk_rates.T, aspect='auto', cmap='gray_r',\n extent=[spike_bins[0], spike_bins[-1], depth_bins[-1], depth_bins[0]])\n # cosmetic\n ax_main.invert_yaxis()\n ax_main.set_xlabel('Time (sec)')\n ax_main.set_ylabel('Distance from tip sites (um)')\n ax_main.set_ylim(depth_edges[0], depth_edges[-1])\n ax_main.spines['right'].set_visible(False)\n ax_main.spines['top'].set_visible(False)\n\n cb = fig.colorbar(im, cax=ax_cbar, orientation='horizontal')\n cb.outline.set_visible(False)\n cb.ax.xaxis.tick_top()\n cb.set_label('Firing rate (Hz)')\n cb.ax.xaxis.set_label_position('top')\n\n # -- plot spikecount --\n ax_spkcount.plot(spk_count.sum(axis=0) / 10e3, depth_edges, 'k')\n ax_spkcount.set_xlabel('Spike count (x$10^3$)')\n ax_spkcount.set_yticks([])\n ax_spkcount.set_ylim(depth_edges[0], depth_edges[-1])\n\n ax_spkcount.spines['right'].set_visible(False)\n ax_spkcount.spines['top'].set_visible(False)\n ax_spkcount.spines['bottom'].set_visible(False)\n ax_spkcount.spines['left'].set_visible(False)\n\n # -- plot colored region annotation\n ax_anno.imshow(region_rgba, aspect='auto',\n extent=[0, 10, (anno_depth_bins[-1] + y_ref) / 1000, (anno_depth_bins[0] + y_ref) / 1000])\n\n ax_anno.invert_yaxis()\n\n ax_anno.spines['right'].set_visible(False)\n ax_anno.spines['top'].set_visible(False)\n ax_anno.spines['bottom'].set_visible(False)\n ax_anno.spines['left'].set_visible(False)\n\n ax_anno.set_xticks([])\n ax_anno.yaxis.tick_right()\n ax_anno.set_ylabel('Depth in the brain (mm)')\n ax_anno.yaxis.set_label_position('right')\n\n return fig\n\n\ndef plot_stacked_contra_ipsi_psth(units, axs=None):\n units = units.proj()\n\n # get event start times: sample, delay, response\n period_names, period_starts = _get_trial_event_times(['sample', 'delay', 'go'], units, 'good_noearlylick_hit')\n\n hemi = _get_units_hemisphere(units)\n\n conds_i = (psth.TrialCondition\n & {'trial_condition_name':\n 'good_noearlylick_left_hit' if hemi == 'left' else 'good_noearlylick_right_hit'}).fetch1('KEY')\n\n conds_c = (psth.TrialCondition\n & {'trial_condition_name':\n 'good_noearlylick_right_hit' if hemi == 'left' else 'good_noearlylick_left_hit'}).fetch1('KEY')\n\n sel_i = (ephys.Unit * psth.UnitSelectivity\n & 'unit_selectivity = \"ipsi-selective\"' & units)\n\n sel_c = (ephys.Unit * psth.UnitSelectivity\n & 'unit_selectivity = \"contra-selective\"' & units)\n\n # ipsi selective ipsi trials\n psth_is_it = (psth.UnitPsth * sel_i.proj('unit_posy') & conds_i).fetch(order_by='unit_posy desc')\n\n # ipsi selective contra trials\n psth_is_ct = (psth.UnitPsth * sel_i.proj('unit_posy') & conds_c).fetch(order_by='unit_posy desc')\n\n # contra selective contra trials\n psth_cs_ct = (psth.UnitPsth * sel_c.proj('unit_posy') & conds_c).fetch(order_by='unit_posy desc')\n\n # contra selective ipsi trials\n psth_cs_it = (psth.UnitPsth * sel_c.proj('unit_posy') & conds_i).fetch(order_by='unit_posy desc')\n\n fig = None\n if axs is None:\n fig, axs = plt.subplots(1, 2, figsize=(20, 20))\n assert axs.size == 2\n\n _plot_stacked_psth_diff(psth_cs_ct, psth_cs_it, ax=axs[0], vlines=period_starts, flip=True)\n\n axs[0].set_title('Contra-selective Units')\n axs[0].set_ylabel('Unit (by depth)')\n axs[0].set_xlabel('Time to go (s)')\n\n _plot_stacked_psth_diff(psth_is_it, psth_is_ct, ax=axs[1], vlines=period_starts)\n\n axs[1].set_title('Ipsi-selective Units')\n axs[1].set_ylabel('Unit (by depth)')\n axs[1].set_xlabel('Time to go (s)')\n\n return fig\n\n\ndef plot_avg_contra_ipsi_psth(units, axs=None):\n units = units.proj()\n\n # get event start times: sample, delay, response\n period_names, period_starts = _get_trial_event_times(['sample', 'delay', 'go'], units, 'good_noearlylick_hit')\n\n hemi = _get_units_hemisphere(units)\n\n good_unit = ephys.Unit & 'unit_quality != \"all\"'\n\n conds_i = (psth.TrialCondition\n & {'trial_condition_name':\n 'good_noearlylick_left_hit' if hemi == 'left' else 'good_noearlylick_right_hit'}).fetch('KEY')\n\n conds_c = (psth.TrialCondition\n & {'trial_condition_name':\n 'good_noearlylick_right_hit' if hemi == 'left' else 'good_noearlylick_left_hit'}).fetch('KEY')\n\n sel_i = (ephys.Unit * psth.UnitSelectivity\n & 'unit_selectivity = \"ipsi-selective\"' & units)\n\n sel_c = (ephys.Unit * psth.UnitSelectivity\n & 'unit_selectivity = \"contra-selective\"' & units)\n\n psth_is_it = (((psth.UnitPsth & conds_i)\n * ephys.Unit.proj('unit_posy'))\n & good_unit.proj() & sel_i.proj()).fetch(\n 'unit_psth', order_by='unit_posy desc')\n\n psth_is_ct = (((psth.UnitPsth & conds_c)\n * ephys.Unit.proj('unit_posy'))\n & good_unit.proj() & sel_i.proj()).fetch(\n 'unit_psth', order_by='unit_posy desc')\n\n psth_cs_ct = (((psth.UnitPsth & conds_c)\n * ephys.Unit.proj('unit_posy'))\n & good_unit.proj() & sel_c.proj()).fetch(\n 'unit_psth', order_by='unit_posy desc')\n\n psth_cs_it = (((psth.UnitPsth & conds_i)\n * ephys.Unit.proj('unit_posy'))\n & good_unit.proj() & sel_c.proj()).fetch(\n 'unit_psth', order_by='unit_posy desc')\n\n fig = None\n if axs is None:\n fig, axs = plt.subplots(1, 2, figsize=(16, 6))\n assert axs.size == 2\n\n _plot_avg_psth(psth_cs_it, psth_cs_ct, period_starts, axs[0],\n 'Contra-selective')\n _plot_avg_psth(psth_is_it, psth_is_ct, period_starts, axs[1],\n 'Ipsi-selective')\n\n ymax = max([ax.get_ylim()[1] for ax in axs])\n for ax in axs:\n ax.set_ylim((0, ymax))\n\n return fig\n\n\ndef plot_psth_photostim_effect(units, condition_name_kw=['both_alm'], axs=None):\n \"\"\"\n For the specified `units`, plot PSTH comparison between stim vs. no-stim with left/right trial instruction\n The stim location (or other appropriate search keywords) can be specified in `condition_name_kw` (default: both ALM)\n \"\"\"\n units = units.proj()\n\n fig = None\n if axs is None:\n fig, axs = plt.subplots(1, 2, figsize=(16, 6))\n assert axs.size == 2\n\n hemi = _get_units_hemisphere(units)\n\n # no photostim:\n psth_n_l = psth.TrialCondition.get_cond_name_from_keywords(['_nostim', '_left'])[0]\n psth_n_r = psth.TrialCondition.get_cond_name_from_keywords(['_nostim', '_right'])[0]\n\n psth_n_l = (psth.UnitPsth * psth.TrialCondition & units\n & {'trial_condition_name': psth_n_l} & 'unit_psth is not NULL').fetch('unit_psth')\n psth_n_r = (psth.UnitPsth * psth.TrialCondition & units\n & {'trial_condition_name': psth_n_r} & 'unit_psth is not NULL').fetch('unit_psth')\n\n # with photostim\n psth_s_l = psth.TrialCondition.get_cond_name_from_keywords(condition_name_kw + ['_stim_left'])[0]\n psth_s_r = psth.TrialCondition.get_cond_name_from_keywords(condition_name_kw + ['_stim_right'])[0]\n\n psth_s_l = (psth.UnitPsth * psth.TrialCondition & units\n & {'trial_condition_name': psth_s_l} & 'unit_psth is not NULL').fetch('unit_psth')\n psth_s_r = (psth.UnitPsth * psth.TrialCondition & units\n & {'trial_condition_name': psth_s_r} & 'unit_psth is not NULL').fetch('unit_psth')\n\n # get event start times: sample, delay, response\n period_names, period_starts = _get_trial_event_times(['sample', 'delay', 'go'], units, 'good_noearlylick_hit')\n\n # get photostim onset and duration\n stim_trial_cond_name = psth.TrialCondition.get_cond_name_from_keywords(condition_name_kw + ['_stim'])[0]\n stim_durs = np.unique((experiment.Photostim & experiment.PhotostimEvent\n * psth.TrialCondition().get_trials(stim_trial_cond_name)\n & units).fetch('duration'))\n stim_dur = _extract_one_stim_dur(stim_durs)\n stim_time = _get_stim_onset_time(units, stim_trial_cond_name)\n\n if hemi == 'left':\n psth_s_i = psth_s_l\n psth_n_i = psth_n_l\n psth_s_c = psth_s_r\n psth_n_c = psth_n_r\n else:\n psth_s_i = psth_s_r\n psth_n_i = psth_n_r\n psth_s_c = psth_s_l\n psth_n_c = psth_n_l\n\n _plot_avg_psth(psth_n_i, psth_n_c, period_starts, axs[0],\n 'Control')\n _plot_avg_psth(psth_s_i, psth_s_c, period_starts, axs[1],\n 'Photostim')\n\n # cosmetic\n ymax = max([ax.get_ylim()[1] for ax in axs])\n for ax in axs:\n ax.set_ylim((0, ymax))\n ax.set_xlim([_plt_xmin, _plt_xmax])\n\n # add shaded bar for photostim\n axs[1].axvspan(stim_time, stim_time + stim_dur, alpha=0.3, color='royalblue')\n\n return fig\n\n\ndef plot_coding_direction(units, time_period=None, label=None, axs=None):\n # get event start times: sample, delay, response\n period_names, period_starts = _get_trial_event_times(['sample', 'delay', 'go'], units, 'good_noearlylick_hit')\n\n _, proj_contra_trial, proj_ipsi_trial, time_stamps, _ = psth.compute_CD_projected_psth(\n units.fetch('KEY'), time_period=time_period)\n\n fig = None\n if axs is None:\n fig, axs = plt.subplots(1, 1, figsize=(8, 6))\n\n # plot\n _plot_with_sem(proj_contra_trial, time_stamps, ax=axs, c='b')\n _plot_with_sem(proj_ipsi_trial, time_stamps, ax=axs, c='r')\n\n for x in period_starts:\n axs.axvline(x=x, linestyle = '--', color = 'k')\n # cosmetic\n axs.spines['right'].set_visible(False)\n axs.spines['top'].set_visible(False)\n axs.set_ylabel('CD projection (a.u.)')\n axs.set_xlabel('Time (s)')\n if label:\n axs.set_title(label)\n\n return fig\n\n\ndef plot_paired_coding_direction(unit_g1, unit_g2, labels=None, time_period=None):\n \"\"\"\n Plot trial-to-trial CD-endpoint correlation between CD-projected trial-psth from two unit-groups (e.g. two brain regions)\n Note: coding direction is calculated on selective units, contra vs. ipsi, within the specified time_period\n \"\"\"\n _, proj_contra_trial_g1, proj_ipsi_trial_g1, time_stamps, unit_g1_hemi = psth.compute_CD_projected_psth(\n unit_g1.fetch('KEY'), time_period=time_period)\n _, proj_contra_trial_g2, proj_ipsi_trial_g2, time_stamps, unit_g2_hemi = psth.compute_CD_projected_psth(\n unit_g2.fetch('KEY'), time_period=time_period)\n\n # get event start times: sample, delay, response\n period_names, period_starts = _get_trial_event_times(['sample', 'delay', 'go'], unit_g1, 'good_noearlylick_hit')\n\n if labels:\n assert len(labels) == 2\n else:\n labels = ('unit group 1', 'unit group 2')\n\n # plot projected trial-psth\n fig, axs = plt.subplots(1, 2, figsize=(16, 6))\n\n _plot_with_sem(proj_contra_trial_g1, time_stamps, ax=axs[0], c='b')\n _plot_with_sem(proj_ipsi_trial_g1, time_stamps, ax=axs[0], c='r')\n _plot_with_sem(proj_contra_trial_g2, time_stamps, ax=axs[1], c='b')\n _plot_with_sem(proj_ipsi_trial_g2, time_stamps, ax=axs[1], c='r')\n\n # cosmetic\n for ax, label in zip(axs, labels):\n for x in period_starts:\n ax.axvline(x=x, linestyle = '--', color = 'k')\n ax.spines['right'].set_visible(False)\n ax.spines['top'].set_visible(False)\n ax.set_ylabel('CD projection (a.u.)')\n ax.set_xlabel('Time (s)')\n ax.set_title(label)\n\n # plot trial CD-endpoint correlation - if 2 unit-groups are from 2 hemispheres,\n # then contra-ipsi definition is based on the first group\n p_start, p_end = time_period\n contra_cdend_1 = proj_contra_trial_g1[:, np.logical_and(time_stamps >= p_start, time_stamps < p_end)].mean(axis=1)\n ipsi_cdend_1 = proj_ipsi_trial_g1[:, np.logical_and(time_stamps >= p_start, time_stamps < p_end)].mean(axis=1)\n if unit_g1_hemi == unit_g1_hemi:\n contra_cdend_2 = proj_contra_trial_g2[:, np.logical_and(time_stamps >= p_start, time_stamps < p_end)].mean(axis=1)\n ipsi_cdend_2 = proj_ipsi_trial_g2[:, np.logical_and(time_stamps >= p_start, time_stamps < p_end)].mean(axis=1)\n else:\n contra_cdend_2 = proj_ipsi_trial_g2[:, np.logical_and(time_stamps >= p_start, time_stamps < p_end)].mean(axis=1)\n ipsi_cdend_2 = proj_contra_trial_g2[:, np.logical_and(time_stamps >= p_start, time_stamps < p_end)].mean(axis=1)\n\n c_df = pd.DataFrame([contra_cdend_1, contra_cdend_2]).T\n c_df.columns = labels\n c_df['trial-type'] = 'contra'\n i_df = pd.DataFrame([ipsi_cdend_1, ipsi_cdend_2]).T\n i_df.columns = labels\n i_df['trial-type'] = 'ipsi'\n df = c_df.append(i_df)\n\n jplot = _jointplot_w_hue(data=df, x=labels[0], y=labels[1], hue= 'trial-type', colormap=['b', 'r'],\n figsize=(8, 6), fig=None, scatter_kws=None)\n jplot['fig'].show()\n\n return fig\n\n\n# ========== Foraging task ==========\ndef plot_unit_period_fit(linear_model='Q_rel + Q_tot + rpe'):\n#%%\n # linear_model='Q_c + Q_i + rpe'\n q_unit = ((ephys.Unit * ephys.ClusterMetric * ephys.UnitStat * ephys.MAPClusterMetric.DriftMetric)\n & 'presence_ratio > 0.95'\n & 'amplitude_cutoff < 0.1'\n & 'isi_violation < 0.5' \n & 'unit_amp > 70'\n # & 'drift_metric < 0.1'\n )\n\n q_hist = (q_unit * histology.ElectrodeCCFPosition.ElectrodePosition) * ccf.CCFAnnotation\n q_unit_n = dj.U('annotation').aggr(q_hist, area_num_units='count(*)')\n q_hist *= q_unit_n\n\n lvs = (psth_foraging.LinearModel.X & {'multi_linear_model': linear_model}).fetch('var_name')\n q_all = ((psth_foraging.UnitPeriodLinearFit\n * psth_foraging.UnitPeriodLinearFit.Param\n * q_hist)\n & {'multi_linear_model': linear_model}) \n\n#%%\n # -- Heatmap ---\n # for lv in zip(lvs):\n # fig, ax = plt.subplots(1, 1, figsize=(13, 15))\n\n # df = pd.DataFrame((q_all & {'var_name': lv}).proj('beta', 'p', 't', 'area_num_units').fetch())\n # df = df.pivot(index=['subject_id', 'session', 'insertion_number',\n # 'clustering_method', 'unit', 'annotation', 'area_num_units'], \n # columns='period', values='t')\n # df.sort_values(by=['area_num_units', 'iti_all'], ascending=False , inplace=True)\n # df = df.reset_index().drop(['subject_id', 'session', 'insertion_number', \n # 'clustering_method', 'unit', 'area_num_units'], axis=1)\n # df = df.set_index('annotation')\n # sns.heatmap(df, ax=ax, cmap='coolwarm')\n # ax.set_position([0.5, 0.1, 0.2, 0.8])\n\n#%%\n # -- t distribution --\n epochs = ['delay', 'go_to_end', 'iti_first_2', 'iti_last_2']\n fig, axs = plt.subplots(len(lvs), len(epochs), figsize=(4*len(epochs), 4*len(lvs)))\n areas = q_unit_n.fetch(order_by='area_num_units desc', format='frame')\n\n # Areas that have most number of neurons\n areas = list(areas.index[:10])\n\n for i, lv in enumerate(lvs):\n for j, ep in enumerate(epochs):\n ax = axs[i, j]\n ax.axhline(y=0.95, color='k', linestyle=':')\n ax.axvline(x=1.96, color='k', linestyle=':')\n\n for area in areas:\n this_ts = (q_all & {'var_name': lv, 'period': ep, 'annotation': area}).fetch('t')\n values, bin = np.histogram(np.abs(this_ts), 100)\n ax.plot(bin[:-1], np.cumsum(values)/len(this_ts), label=f'{area}, n = {len(this_ts)}')\n\n ax.set(xlim=(0, 10))\n ax.label_outer()\n\n if i == 0:\n ax.set_title(ep)\n if j == 0:\n ax.set_ylabel(lv)\n if i == len(lvs) - 1 and j == 0:\n ax.set_xlabel('|t value|')\n \n ax.legend(bbox_to_anchor=(-1,3), loc='upper left')\n\n#%%\n # -- ipsi and contra action value weights --\n fig, axs = plt.subplots(1,2, figsize=(8,4))\n if linear_model == 'Q_c + Q_i + rpe':\n lvs = ['ipsi_action_value', 'contra_action_value'] \n elif linear_model == 'Q_l + Q_r + rpe':\n lvs = ['left_action_value', 'right_action_value']\n else:\n lvs = ['relative_action_value_ic', 'total_action_value']\n\n for j, ep in enumerate(['go_to_end', 'iti_all']):\n ax = axs[j]\n\n for area in areas:\n # if not 'thalamus' in area:\n # continue\n\n ax.axhline(y=-2, color='k', ls='--', lw=.5)\n ax.axhline(y=2, color='k', ls='--', lw=.5)\n ax.axvline(x=-2, color='k', ls='--', lw=.5)\n ax.axvline(x=2, color='k', ls='--', lw=.5)\n\n df = pd.DataFrame((q_all\n & {'annotation': area}\n & {'period': ep}).proj('beta', 'p', 'area_num_units', 't').fetch())\n\n betas = df.pivot(index=['subject_id', 'session', 'insertion_number',\n 'clustering_method', 'unit', 'annotation', 'area_num_units'], \n columns='var_name', values='t')\n ps = df.pivot(index=['subject_id', 'session', 'insertion_number',\n 'clustering_method', 'unit', 'annotation', 'area_num_units'], \n columns='var_name', values='p')\n sizes = 2 + 2 * np.sum(ps.values < 0.05, axis=1)\n ax.scatter(x=betas[lvs[0]], y=betas[lvs[1]], s=sizes)\n ax.set_xlim([-20, 20])\n ax.set_ylim([-20, 20])\n ax.set_xlabel(lvs[0])\n ax.set_ylabel(lvs[1])\n ax.set_title(ep)\n ax.label_outer()\n\n # sns.scatterplot(data=betas, x='ipsi_action_value', y='contra_action_value',\n # hue='annotation', sizes=sizes, legend=False)\n\n\n#%%\n\ndef plot_example_cells(sort_lv = 'relative_action_value_ic', \n sort_ep = 'iti_all',\n best_n = 10, linear_model='Q_rel + Q_tot + rpe'):\n \n#%%\n q_unit = ((ephys.Unit * ephys.ClusterMetric * ephys.UnitStat * ephys.MAPClusterMetric.DriftMetric)\n & 'presence_ratio > 0.95'\n & 'amplitude_cutoff < 0.1'\n & 'isi_violation < 0.5' \n & 'unit_amp > 100'\n # & 'drift_metric < 0.1'\n )\n\n q_hist = (q_unit * histology.ElectrodeCCFPosition.ElectrodePosition) * ccf.CCFAnnotation\n q_unit_n = dj.U('annotation').aggr(q_hist, area_num_units='count(*)')\n q_hist *= q_unit_n\n\n lvs = (psth_foraging.LinearModel.X & {'multi_linear_model': linear_model}).fetch('var_name')\n q_all = ((psth_foraging.UnitPeriodLinearFit\n * psth_foraging.UnitPeriodLinearFit.Param\n * q_hist)\n & {'multi_linear_model': linear_model}) \n\n # Best n (absolute value)\n best_models = (q_all & f'var_name = \"{sort_lv}\"' & f'period = \"{sort_ep}\"').proj(\n 'actual_behavior_model', abs_t='abs(t)').fetch(order_by='abs_t desc', limit=best_n, format='frame')\n\n for unit_key in best_models.reset_index().to_dict('records'):\n unit_psth.plot_unit_psth_choice_outcome(unit_key)\n unit_psth.plot_unit_psth_latent_variable_quantile(unit_key, \n model_id=unit_key['actual_behavior_model'])\n unit_psth.plot_unit_period_tuning(unit_key)\n\n\n#%%\n# =========== HELPER ==============\n\ndef get_m_scale(shank_count):\n return 1350 - 150*shank_count\n" ]
[ [ "numpy.sum", "numpy.diff", "matplotlib.pyplot.GridSpec", "numpy.nansum", "matplotlib.path.Path", "matplotlib.pyplot.figure", "numpy.logical_and", "numpy.abs", "numpy.cos", "numpy.histogram2d", "numpy.where", "numpy.linspace", "numpy.repeat", "matplotlib.pyplot.subplots", "numpy.arange", "numpy.hstack", "numpy.linalg.norm", "numpy.cumsum", "numpy.nanmax", "pandas.DataFrame", "matplotlib.pyplot.subplot", "numpy.array", "numpy.sin", "numpy.full" ] ]
Azarattum/Jumpcutter
[ "f8439776689c7baecfc68516b2ef3afe743284db" ]
[ "jumpcutter.py" ]
[ "from contextlib import closing\nfrom PIL import Image\nimport subprocess\nfrom audiotsm import phasevocoder\nfrom audiotsm.io.wav import WavReader, WavWriter\nfrom scipy.io import wavfile\nimport numpy as np\nimport re\nimport math\nfrom shutil import copyfile, rmtree\nimport os\nimport argparse\nfrom pytube import YouTube\n\ndef downloadFile(url):\n name = YouTube(url).streams.first().download()\n newname = name.replace(' ','_')\n os.rename(name,newname)\n return newname\n\ndef getMaxVolume(s):\n maxv = float(np.max(s))\n minv = float(np.min(s))\n return max(maxv,-minv)\n\ndef copyFrame(inputFrame,outputFrame):\n src = TEMP_FOLDER+\"/frame{:06d}\".format(inputFrame+1)+\".jpg\"\n dst = TEMP_FOLDER+\"/newFrame{:06d}\".format(outputFrame+1)+\".jpg\"\n if not os.path.isfile(src):\n return False\n copyfile(src, dst)\n if outputFrame%20 == 19:\n print(str(outputFrame+1)+\" time-altered frames saved.\")\n return True\n\ndef inputToOutputFilename(filename):\n dotIndex = filename.rfind(\".\")\n return filename[:dotIndex]+\"_ALTERED\"+filename[dotIndex:]\n\ndef createPath(s):\n #assert (not os.path.exists(s)), \"The filepath \"+s+\" already exists. Don't want to overwrite it. Aborting.\"\n\n try: \n os.mkdir(s)\n except OSError: \n assert False, \"Creation of the directory %s failed. (The TEMP folder may already exist. Delete or rename it, and try again.)\"\n\ndef deletePath(s): # Dangerous! Watch out!\n try: \n rmtree(s,ignore_errors=False)\n except OSError: \n print (\"Deletion of the directory %s failed\" % s)\n print(OSError)\n\ndef writeELD(start, end, number):\n startFrame = int(start % frameRate)\n startSecond = int((start / frameRate) % 60)\n startMinute = int((start / frameRate / 60) % 60)\n startHour = int((start / frameRate / 60 / 60))\n\n endFrame = int(end % frameRate)\n endSecond = int((end / frameRate) % 60)\n endMinute = int((end / frameRate / 60) % 60)\n endHour = int((end / frameRate / 60 / 60))\n\n eld_file = open(OUTPUT_FILE, \"a\")\n eld_file.write(\"{0} 001 V C {4}:{3}:{2}:{1} {8}:{7}:{6}:{5} {4}:{3}:{2}:{1} {8}:{7}:{6}:{5}\\r\\n\".format(\n str(number).zfill(3),\n str(startFrame).zfill(2),\n str(startSecond).zfill(2),\n str(startMinute).zfill(2),\n str(startHour).zfill(2),\n str(endFrame).zfill(2),\n str(endSecond).zfill(2),\n str(endMinute).zfill(2),\n str(endHour).zfill(2)\n ))\n eld_file.close()\n\n\nparser = argparse.ArgumentParser(description='Modifies a video file to play at different speeds when there is sound vs. silence.')\nparser.add_argument('--input_file', type=str, help='the video file you want modified')\nparser.add_argument('--edl', type=bool, help='EDL export option. (Supports only cuts off)')\nparser.add_argument('--url', type=str, help='A youtube url to download and process')\nparser.add_argument('--output_file', type=str, default=\"\", help=\"the output file. (optional. if not included, it'll just modify the input file name)\")\nparser.add_argument('--silent_threshold', type=float, default=0.03, help=\"the volume amount that frames' audio needs to surpass to be consider \\\"sounded\\\". It ranges from 0 (silence) to 1 (max volume)\")\nparser.add_argument('--sounded_speed', type=float, default=1.00, help=\"the speed that sounded (spoken) frames should be played at. Typically 1.\")\nparser.add_argument('--silent_speed', type=float, default=5.00, help=\"the speed that silent frames should be played at. 999999 for jumpcutting.\")\nparser.add_argument('--frame_margin', type=float, default=1, help=\"some silent frames adjacent to sounded frames are included to provide context. How many frames on either the side of speech should be included? That's this variable.\")\nparser.add_argument('--sample_rate', type=float, default=44100, help=\"sample rate of the input and output videos\")\nparser.add_argument('--frame_rate', type=float, default=30, help=\"frame rate of the input and output videos. optional... I try to find it out myself, but it doesn't always work.\")\nparser.add_argument('--frame_quality', type=int, default=3, help=\"quality of frames to be extracted from input video. 1 is highest, 31 is lowest, 3 is the default.\")\n\nargs = parser.parse_args()\n\n\n\nframeRate = args.frame_rate\nSAMPLE_RATE = args.sample_rate\nSILENT_THRESHOLD = args.silent_threshold\nFRAME_SPREADAGE = args.frame_margin\nNEW_SPEED = [args.silent_speed, args.sounded_speed]\nif args.url != None:\n INPUT_FILE = downloadFile(args.url)\nelse:\n INPUT_FILE = args.input_file\nURL = args.url\nFRAME_QUALITY = args.frame_quality\nEDL = args.edl\n\nassert INPUT_FILE != None , \"why u put no input file, that dum\"\n \nOUTPUT_FILE = inputToOutputFilename(INPUT_FILE)\nif len(args.output_file) >= 1:\n OUTPUT_FILE = args.output_file\nelse:\n OUTPUT_FILE = inputToOutputFilename(INPUT_FILE)\n\nTEMP_FOLDER = \"TEMP\"\nAUDIO_FADE_ENVELOPE_SIZE = 400 # smooth out transitiion's audio by quickly fading in/out (arbitrary magic number whatever)\n \ncreatePath(TEMP_FOLDER)\n\nif not EDL:\n command = \"ffmpeg -i \"+INPUT_FILE+\" -qscale:v \"+str(FRAME_QUALITY)+\" \"+TEMP_FOLDER+\"/frame%06d.jpg -hide_banner\"\n subprocess.call(command, shell=True)\n\ncommand = \"ffmpeg -i \"+INPUT_FILE+\" -ab 160k -ac 2 -ar \"+str(SAMPLE_RATE)+\" -vn \"+TEMP_FOLDER+\"/audio.wav\"\n\nsubprocess.call(command, shell=True)\n\ncommand = \"ffmpeg -i \"+TEMP_FOLDER+\"/input.mp4 2>&1\"\nf = open(TEMP_FOLDER+\"/params.txt\", \"w\")\nsubprocess.call(command, shell=True, stdout=f)\n\n\n\nsampleRate, audioData = wavfile.read(TEMP_FOLDER+\"/audio.wav\")\naudioSampleCount = audioData.shape[0]\nmaxAudioVolume = getMaxVolume(audioData)\n\nf = open(TEMP_FOLDER+\"/params.txt\", 'r+')\npre_params = f.read()\nf.close()\nparams = pre_params.split('\\n')\nfor line in params:\n m = re.search('Stream #.*Video.* ([0-9]*) fps',line)\n if m is not None:\n frameRate = float(m.group(1))\n\nsamplesPerFrame = sampleRate/frameRate\n\naudioFrameCount = int(math.ceil(audioSampleCount/samplesPerFrame))\n\nhasLoudAudio = np.zeros((audioFrameCount))\n\n\n\nfor i in range(audioFrameCount):\n start = int(i*samplesPerFrame)\n end = min(int((i+1)*samplesPerFrame),audioSampleCount)\n audiochunks = audioData[start:end]\n maxchunksVolume = float(getMaxVolume(audiochunks))/maxAudioVolume\n if maxchunksVolume >= SILENT_THRESHOLD:\n hasLoudAudio[i] = 1\n\nchunks = [[0,0,0]]\nshouldIncludeFrame = np.zeros((audioFrameCount))\nfor i in range(audioFrameCount):\n start = int(max(0,i-FRAME_SPREADAGE))\n end = int(min(audioFrameCount,i+1+FRAME_SPREADAGE))\n shouldIncludeFrame[i] = np.max(hasLoudAudio[start:end])\n if (i >= 1 and shouldIncludeFrame[i] != shouldIncludeFrame[i-1]): # Did we flip?\n chunks.append([chunks[-1][1],i,shouldIncludeFrame[i-1]])\n\nchunks.append([chunks[-1][1],audioFrameCount,shouldIncludeFrame[i-1]])\nchunks = chunks[1:]\n\noutputAudioData = np.zeros((0,audioData.shape[1]))\noutputPointer = 0\n\nlastExistingFrame = None\nedlFrameNumber = 0\nif EDL and os.path.isfile(OUTPUT_FILE):\n os.remove(OUTPUT_FILE)\nfor chunk in chunks:\n if EDL:\n if (chunk[2] == True):\n edlFrameNumber += 1\n writeELD(chunk[0], chunk[1], edlFrameNumber)\n continue\n \n audioChunk = audioData[int(chunk[0]*samplesPerFrame):int(chunk[1]*samplesPerFrame)]\n \n sFile = TEMP_FOLDER+\"/tempStart.wav\"\n eFile = TEMP_FOLDER+\"/tempEnd.wav\"\n wavfile.write(sFile,SAMPLE_RATE,audioChunk)\n with WavReader(sFile) as reader:\n with WavWriter(eFile, reader.channels, reader.samplerate) as writer:\n tsm = phasevocoder(reader.channels, speed=NEW_SPEED[int(chunk[2])])\n tsm.run(reader, writer)\n _, alteredAudioData = wavfile.read(eFile)\n leng = alteredAudioData.shape[0]\n endPointer = outputPointer+leng\n outputAudioData = np.concatenate((outputAudioData,alteredAudioData/maxAudioVolume))\n\n #outputAudioData[outputPointer:endPointer] = alteredAudioData/maxAudioVolume\n\n # smooth out transitiion's audio by quickly fading in/out\n \n if leng < AUDIO_FADE_ENVELOPE_SIZE:\n outputAudioData[outputPointer:endPointer] = 0 # audio is less than 0.01 sec, let's just remove it.\n else:\n premask = np.arange(AUDIO_FADE_ENVELOPE_SIZE)/AUDIO_FADE_ENVELOPE_SIZE\n mask = np.repeat(premask[:, np.newaxis],2,axis=1) # make the fade-envelope mask stereo\n outputAudioData[outputPointer:outputPointer+AUDIO_FADE_ENVELOPE_SIZE] *= mask\n outputAudioData[endPointer-AUDIO_FADE_ENVELOPE_SIZE:endPointer] *= 1-mask\n\n startOutputFrame = int(math.ceil(outputPointer/samplesPerFrame))\n endOutputFrame = int(math.ceil(endPointer/samplesPerFrame))\n for outputFrame in range(startOutputFrame, endOutputFrame):\n inputFrame = int(chunk[0]+NEW_SPEED[int(chunk[2])]*(outputFrame-startOutputFrame))\n didItWork = copyFrame(inputFrame,outputFrame)\n if didItWork:\n lastExistingFrame = inputFrame\n else:\n copyFrame(lastExistingFrame,outputFrame)\n\n outputPointer = endPointer\n\nif not EDL:\n wavfile.write(TEMP_FOLDER+\"/audioNew.wav\",SAMPLE_RATE,outputAudioData)\n\n'''\noutputFrame = math.ceil(outputPointer/samplesPerFrame)\nfor endGap in range(outputFrame,audioFrameCount):\n copyFrame(int(audioSampleCount/samplesPerFrame)-1,endGap)\n'''\n\nif not EDL:\n command = \"ffmpeg -framerate \"+str(frameRate)+\" -i \"+TEMP_FOLDER+\"/newFrame%06d.jpg -i \"+TEMP_FOLDER+\"/audioNew.wav -strict -2 \"+OUTPUT_FILE\n subprocess.call(command, shell=True)\n\ndeletePath(TEMP_FOLDER)\n\n" ]
[ [ "numpy.zeros", "scipy.io.wavfile.write", "numpy.repeat", "numpy.arange", "numpy.max", "scipy.io.wavfile.read", "numpy.min", "numpy.concatenate" ] ]
nagachika/probability
[ "2a5609ceec01a388ec03b583b4f8e813cfbad981" ]
[ "tensorflow_probability/python/distributions/zipf.py" ]
[ "# Copyright 2018 The TensorFlow Probability Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\"\"\"The Zipf distribution class.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport tensorflow.compat.v2 as tf\n\nfrom tensorflow_probability.python.distributions import distribution\nfrom tensorflow_probability.python.distributions.seed_stream import SeedStream\nfrom tensorflow_probability.python.internal import assert_util\nfrom tensorflow_probability.python.internal import distribution_util\nfrom tensorflow_probability.python.internal import dtype_util\nfrom tensorflow_probability.python.internal import reparameterization\n\n\n__all__ = [\n \"Zipf\",\n]\n\n\nclass Zipf(distribution.Distribution):\n \"\"\"Zipf distribution.\n\n The Zipf distribution is parameterized by a `power` parameter.\n\n #### Mathematical Details\n\n The probability mass function (pmf) is,\n\n ```none\n pmf(k; alpha, k >= 0) = (k^(-alpha)) / Z\n Z = zeta(alpha).\n ```\n\n where `power = alpha` and Z is the normalization constant.\n `zeta` is the [Riemann zeta function](\n https://en.wikipedia.org/wiki/Riemann_zeta_function).\n\n Note that gradients with respect to the `power` parameter are not\n supported in the current implementation.\n \"\"\"\n\n def __init__(self,\n power,\n dtype=tf.int32,\n interpolate_nondiscrete=True,\n sample_maximum_iterations=100,\n validate_args=False,\n allow_nan_stats=False,\n name=\"Zipf\"):\n \"\"\"Initialize a batch of Zipf distributions.\n\n Args:\n power: `Float` like `Tensor` representing the power parameter. Must be\n strictly greater than `1`.\n dtype: The `dtype` of `Tensor` returned by `sample`.\n Default value: `tf.int32`.\n interpolate_nondiscrete: Python `bool`. When `False`, `log_prob` returns\n `-inf` (and `prob` returns `0`) for non-integer inputs. When `True`,\n `log_prob` evaluates the continuous function `-power log(k) -\n log(zeta(power))` , which matches the Zipf pmf at integer arguments `k`\n (note that this function is not itself a normalized probability\n log-density).\n Default value: `True`.\n sample_maximum_iterations: Maximum number of iterations of allowable\n iterations in `sample`. When `validate_args=True`, samples which fail to\n reach convergence (subject to this cap) are masked out with\n `self.dtype.min` or `nan` depending on `self.dtype.is_integer`.\n Default value: `100`.\n validate_args: Python `bool`, default `False`. When `True` distribution\n parameters are checked for validity despite possibly degrading runtime\n performance. When `False` invalid inputs may silently render incorrect\n outputs.\n Default value: `False`.\n allow_nan_stats: Python `bool`, default `True`. When `True`, statistics\n (e.g., mean, mode, variance) use the value \"`NaN`\" to indicate the\n result is undefined. When `False`, an exception is raised if one or more\n of the statistic's batch members are undefined.\n Default value: `False`.\n name: Python `str` name prefixed to Ops created by this class.\n Default value: `'Zipf'`.\n\n Raises:\n TypeError: if `power` is not `float` like.\n \"\"\"\n parameters = dict(locals())\n with tf.name_scope(name) as name:\n power = tf.convert_to_tensor(\n value=power,\n name=\"power\",\n dtype=dtype_util.common_dtype([power], preferred_dtype=tf.float32))\n if (not dtype_util.is_floating(power.dtype) or\n dtype_util.base_equal(power.dtype, tf.float16)):\n raise TypeError(\n \"power.dtype ({}) is not a supported `float` type.\".format(\n dtype_util.name(power.dtype)))\n runtime_assertions = []\n if validate_args:\n runtime_assertions.append(assert_util.assert_greater(\n power, np.ones([], power.dtype.as_numpy_dtype)))\n with tf.control_dependencies(runtime_assertions):\n self._power = tf.identity(power, name=\"power\")\n\n self._interpolate_nondiscrete = interpolate_nondiscrete\n self._sample_maximum_iterations = sample_maximum_iterations\n super(Zipf, self).__init__(\n dtype=dtype,\n reparameterization_type=reparameterization.NOT_REPARAMETERIZED,\n validate_args=validate_args,\n allow_nan_stats=allow_nan_stats,\n parameters=parameters,\n graph_parents=[self._power],\n name=name)\n\n @classmethod\n def _params_event_ndims(cls):\n return dict(power=0)\n\n @property\n def power(self):\n \"\"\"Exponent parameter.\"\"\"\n return self._power\n\n @property\n def interpolate_nondiscrete(self):\n \"\"\"Interpolate (log) probs on non-integer inputs.\"\"\"\n return self._interpolate_nondiscrete\n\n @property\n def sample_maximum_iterations(self):\n \"\"\"Maximum number of allowable iterations in `sample`.\"\"\"\n return self._sample_maximum_iterations\n\n def _batch_shape_tensor(self):\n return tf.shape(input=self.power)\n\n def _batch_shape(self):\n return self.power.shape\n\n def _event_shape_tensor(self):\n return tf.constant([], dtype=tf.int32)\n\n def _event_shape(self):\n return tf.TensorShape([])\n\n def _log_prob(self, x):\n # The log probability at positive integer points x is log(x^(-power) / Z)\n # where Z is the normalization constant. For x < 1 and non-integer points,\n # the log-probability is -inf.\n #\n # However, if interpolate_nondiscrete is True, we return the natural\n # continuous relaxation for x >= 1 which agrees with the log probability at\n # positive integer points.\n #\n # If interpolate_nondiscrete is False and validate_args is True, we check\n # that the sample point x is in the support. That is, x is equivalent to a\n # positive integer.\n x = tf.cast(x, self.power.dtype)\n if self.validate_args and not self.interpolate_nondiscrete:\n x = distribution_util.embed_check_integer_casting_closed(\n x, target_dtype=self.dtype, assert_positive=True)\n return self._log_unnormalized_prob(x) - self._log_normalization()\n\n def _cdf(self, x):\n # CDF(x) at positive integer x is the probability that the Zipf variable is\n # less than or equal to x; given by the formula:\n # CDF(x) = 1 - (zeta(power, x + 1) / Z)\n # For fractional x, the CDF is equal to the CDF at n = floor(x).\n # For x < 1, the CDF is zero.\n\n # If interpolate_nondiscrete is True, we return a continuous relaxation\n # which agrees with the CDF at integer points.\n x = tf.cast(x, self.power.dtype)\n safe_x = tf.maximum(x if self.interpolate_nondiscrete else tf.floor(x), 0.)\n\n cdf = 1. - (\n tf.math.zeta(self.power, safe_x + 1.) / tf.math.zeta(self.power, 1.))\n return tf.where(\n tf.broadcast_to(tf.less(x, 1.), tf.shape(input=cdf)),\n tf.zeros_like(cdf), cdf)\n\n def _log_normalization(self):\n return tf.math.log(tf.math.zeta(self.power, 1.))\n\n def _log_unnormalized_prob(self, x):\n safe_x = tf.maximum(x if self.interpolate_nondiscrete else tf.floor(x), 1.)\n y = -self.power * tf.math.log(safe_x)\n is_supported = tf.broadcast_to(tf.equal(x, safe_x), tf.shape(input=y))\n neg_inf = tf.fill(\n tf.shape(input=y), value=dtype_util.as_numpy_dtype(y.dtype)(-np.inf))\n return tf.where(is_supported, y, neg_inf)\n\n @distribution_util.AppendDocstring(\n \"\"\"Note: Zipf has an infinite mean when `power` <= 2.\"\"\")\n def _mean(self):\n zeta_p = tf.math.zeta(self.power[..., tf.newaxis] - [0., 1.], 1.)\n return zeta_p[..., 1] / zeta_p[..., 0]\n\n @distribution_util.AppendDocstring(\n \"\"\"Note: Zipf has infinite variance when `power` <= 3.\"\"\")\n def _variance(self):\n zeta_p = tf.math.zeta(self.power[..., tf.newaxis] - [0., 1., 2.], 1.)\n return ((zeta_p[..., 0] * zeta_p[..., 2]) - (zeta_p[..., 1]**2)) / (\n zeta_p[..., 0]**2)\n\n def _mode(self):\n return tf.ones_like(self.power, dtype=self.dtype)\n\n @distribution_util.AppendDocstring(\n \"\"\"The sampling algorithm is rejection-inversion; Algorithm ZRI of\n [Horman and Derflinger (1996)][1]. For simplicity, we don't use the\n squeeze function in our implementation.\n\n #### References\n [1]: W. Hormann , G. Derflinger, Rejection-inversion to generate variates\n from monotone discrete distributions, ACM Transactions on Modeling and\n Computer Simulation (TOMACS), v.6 n.3, p.169-184, July 1996.\n \"\"\")\n def _sample_n(self, n, seed=None):\n shape = tf.concat([[n], self.batch_shape_tensor()], axis=0)\n\n has_seed = seed is not None\n seed = SeedStream(seed, salt=\"zipf\")\n\n minval_u = self._hat_integral(0.5) + 1.\n maxval_u = self._hat_integral(tf.int64.max - 0.5)\n\n def loop_body(should_continue, k):\n \"\"\"Resample the non-accepted points.\"\"\"\n # The range of U is chosen so that the resulting sample K lies in\n # [0, tf.int64.max). The final sample, if accepted, is K + 1.\n u = tf.random.uniform(\n shape,\n minval=minval_u,\n maxval=maxval_u,\n dtype=self.power.dtype,\n seed=seed())\n\n # Sample the point X from the continuous density h(x) \\propto x^(-power).\n x = self._hat_integral_inverse(u)\n\n # Rejection-inversion requires a `hat` function, h(x) such that\n # \\int_{k - .5}^{k + .5} h(x) dx >= pmf(k + 1) for points k in the\n # support. A natural hat function for us is h(x) = x^(-power).\n #\n # After sampling X from h(x), suppose it lies in the interval\n # (K - .5, K + .5) for integer K. Then the corresponding K is accepted if\n # if lies to the left of x_K, where x_K is defined by:\n # \\int_{x_k}^{K + .5} h(x) dx = H(x_K) - H(K + .5) = pmf(K + 1),\n # where H(x) = \\int_x^inf h(x) dx.\n\n # Solving for x_K, we find that x_K = H_inverse(H(K + .5) + pmf(K + 1)).\n # Or, the acceptance condition is X <= H_inverse(H(K + .5) + pmf(K + 1)).\n # Since X = H_inverse(U), this simplifies to U <= H(K + .5) + pmf(K + 1).\n\n # Update the non-accepted points.\n # Since X \\in (K - .5, K + .5), the sample K is chosen as floor(X + 0.5).\n k = tf.where(should_continue, tf.floor(x + 0.5), k)\n accept = (u <= self._hat_integral(k + .5) + tf.exp(self._log_prob(k + 1)))\n\n return [should_continue & (~accept), k]\n\n should_continue, samples = tf.while_loop(\n cond=lambda should_continue, *ignore: tf.reduce_any(\n input_tensor=should_continue),\n body=loop_body,\n loop_vars=[\n tf.ones(shape, dtype=tf.bool), # should_continue\n tf.zeros(shape, dtype=self.power.dtype), # k\n ],\n parallel_iterations=1 if has_seed else 10,\n maximum_iterations=self.sample_maximum_iterations,\n )\n samples = samples + 1.\n\n if self.validate_args and dtype_util.is_integer(self.dtype):\n samples = distribution_util.embed_check_integer_casting_closed(\n samples, target_dtype=self.dtype, assert_positive=True)\n\n samples = tf.cast(samples, self.dtype)\n\n if self.validate_args:\n npdt = dtype_util.as_numpy_dtype(self.dtype)\n v = npdt(dtype_util.min(npdt) if dtype_util.is_integer(npdt) else np.nan)\n mask = tf.fill(shape, value=v)\n samples = tf.where(should_continue, mask, samples)\n\n return samples\n\n def _hat_integral(self, x):\n \"\"\"Integral of the `hat` function, used for sampling.\n\n We choose a `hat` function, h(x) = x^(-power), which is a continuous\n (unnormalized) density touching each positive integer at the (unnormalized)\n pmf. This function implements `hat` integral: H(x) = int_x^inf h(t) dt;\n which is needed for sampling purposes.\n\n Arguments:\n x: A Tensor of points x at which to evaluate H(x).\n\n Returns:\n A Tensor containing evaluation H(x) at x.\n \"\"\"\n x = tf.cast(x, self.power.dtype)\n t = self.power - 1.\n return tf.exp((-t) * tf.math.log1p(x) - tf.math.log(t))\n\n def _hat_integral_inverse(self, x):\n \"\"\"Inverse function of _hat_integral.\"\"\"\n x = tf.cast(x, self.power.dtype)\n t = self.power - 1.\n return tf.math.expm1(-(tf.math.log(t) + tf.math.log(x)) / t)\n" ]
[ [ "numpy.ones", "tensorflow.compat.v2.equal", "tensorflow.compat.v2.zeros", "tensorflow.compat.v2.where", "tensorflow.compat.v2.reduce_any", "tensorflow.compat.v2.ones_like", "tensorflow.compat.v2.name_scope", "tensorflow.compat.v2.constant", "tensorflow.compat.v2.math.log", "tensorflow.compat.v2.zeros_like", "tensorflow.compat.v2.floor", "tensorflow.compat.v2.less", "tensorflow.compat.v2.fill", "tensorflow.compat.v2.math.log1p", "tensorflow.compat.v2.identity", "tensorflow.compat.v2.cast", "tensorflow.compat.v2.shape", "tensorflow.compat.v2.control_dependencies", "tensorflow.compat.v2.ones", "tensorflow.compat.v2.math.zeta", "tensorflow.compat.v2.TensorShape" ] ]
profintegra/stumpy
[ "66b3402d91820005b466e1da6fe353b61e6246c5" ]
[ "stumpy/gpu_aamp.py" ]
[ "# STUMPY\n# Copyright 2019 TD Ameritrade. Released under the terms of the 3-Clause BSD license.\n# STUMPY is a trademark of TD Ameritrade IP Company, Inc. All rights reserved.\nimport logging\nimport math\nimport multiprocessing as mp\nimport os\n\nimport numpy as np\nfrom numba import cuda\n\nfrom . import core, config\n\nlogger = logging.getLogger(__name__)\n\n\[email protected](\n \"(i8, f8[:], f8[:], i8, f8[:], f8[:], f8[:], b1[:], b1[:],\"\n \"f8[:], f8[:], i8, b1, i8, f8[:, :], i8[:, :], b1)\"\n)\ndef _compute_and_update_PI_kernel(\n i,\n T_A,\n T_B,\n m,\n QT_even,\n QT_odd,\n QT_first,\n T_A_subseq_isfinite,\n T_B_subseq_isfinite,\n T_A_subseq_squared,\n T_B_subseq_squared,\n k,\n ignore_trivial,\n excl_zone,\n profile,\n indices,\n compute_QT,\n):\n \"\"\"\n A Numba CUDA kernel to update the non-normalized (i.e., without z-normalization)\n matrix profile and matrix profile indices\n\n Parameters\n ----------\n i : int\n sliding window `i`\n\n T_A : ndarray\n The time series or sequence for which to compute the dot product\n\n T_B : ndarray\n The time series or sequence that will be used to annotate T_A. For every\n subsequence in T_A, its nearest neighbor in T_B will be recorded.\n\n m : int\n Window size\n\n QT_even : ndarray\n The input QT array (dot product between the query sequence,`Q`, and\n time series, `T`) to use when `i` is even\n\n QT_odd : ndarray\n The input QT array (dot product between the query sequence,`Q`, and\n time series, `T`) to use when `i` is odd\n\n QT_first : ndarray\n Dot product between the first query sequence,`Q`, and time series, `T`\n\n T_A_subseq_isfinite : ndarray\n A boolean array that indicates whether a subsequence in `T_A` contains a\n `np.nan`/`np.inf` value (False)\n\n T_B_subseq_isfinite : ndarray\n A boolean array that indicates whether a subsequence in `T_B` contains a\n `np.nan`/`np.inf` value (False)\n\n T_A_subseq_squared : ndarray\n The squared subsequences of `T_A`\n\n T_B_subseq_squared : ndarray\n The squared subsequences of `T_B`\n\n k : int\n The total number of sliding windows to iterate over\n\n ignore_trivial : bool\n Set to `True` if this is a self-join. Otherwise, for AB-join, set this to\n `False`.\n\n excl_zone : int\n The half width for the exclusion zone relative to the current\n sliding window\n\n profile : ndarray\n Matrix profile. The first column consists of the global matrix profile,\n the second column consists of the left matrix profile, and the third\n column consists of the right matrix profile.\n\n indices : ndarray\n The first column consists of the matrix profile indices, the second\n column consists of the left matrix profile indices, and the third\n column consists of the right matrix profile indices.\n\n compute_QT : bool\n A boolean flag for whether or not to compute QT\n\n Returns\n -------\n None\n\n Notes\n -----\n `arXiv:1901.05708 \\\n <https://arxiv.org/pdf/1901.05708.pdf>`__\n\n See Algorithm 1\n\n Note that we have extended this algorithm for AB-joins as well.\n\n `DOI: 10.1109/ICDM.2016.0085 \\\n <https://www.cs.ucr.edu/~eamonn/STOMP_GPU_final_submission_camera_ready.pdf>`__\n\n See Table II, Figure 5, and Figure 6\n \"\"\"\n start = cuda.grid(1)\n stride = cuda.gridsize(1)\n\n if i % 2 == 0:\n QT_out = QT_even\n QT_in = QT_odd\n else:\n QT_out = QT_odd\n QT_in = QT_even\n\n for j in range(start, QT_out.shape[0], stride):\n zone_start = max(0, j - excl_zone)\n zone_stop = min(k, j + excl_zone)\n\n if compute_QT:\n QT_out[j] = (\n QT_in[j - 1] - T_B[i - 1] * T_A[j - 1] + T_B[i + m - 1] * T_A[j + m - 1]\n )\n\n QT_out[0] = QT_first[i]\n\n if not T_B_subseq_isfinite[i] or not T_A_subseq_isfinite[j]:\n D = np.inf\n else:\n D = T_B_subseq_squared[i] + T_A_subseq_squared[j] - 2.0 * QT_out[j]\n\n if D < config.STUMPY_D_SQUARED_THRESHOLD:\n D = 0\n\n if ignore_trivial:\n if i <= zone_stop and i >= zone_start:\n D = np.inf\n if D < profile[j, 1] and i < j:\n profile[j, 1] = D\n indices[j, 1] = i\n if D < profile[j, 2] and i > j:\n profile[j, 2] = D\n indices[j, 2] = i\n\n if D < profile[j, 0]:\n profile[j, 0] = D\n indices[j, 0] = i\n\n\ndef _gpu_aamp(\n T_A_fname,\n T_B_fname,\n m,\n range_stop,\n excl_zone,\n T_A_subseq_isfinite_fname,\n T_B_subseq_isfinite_fname,\n T_A_subseq_squared_fname,\n T_B_subseq_squared_fname,\n QT_fname,\n QT_first_fname,\n k,\n ignore_trivial=True,\n range_start=1,\n device_id=0,\n):\n \"\"\"\n A Numba CUDA version of AAMP for parallel computation of the non-normalized (i.e.,\n without z-normalization) matrix profile, matrix profile indices, left matrix profile\n indices, and right matrix profile indices.\n\n Parameters\n ----------\n T_A_fname : str\n The file name for the time series or sequence for which to compute\n the matrix profile\n\n T_B_fname : str\n The file name for the time series or sequence that will be used to annotate T_A.\n For every subsequence in T_A, its nearest neighbor in T_B will be recorded.\n\n m : int\n Window size\n\n range_stop : int\n The index value along T_B for which to stop the matrix profile\n calculation. This parameter is here for consistency with the\n distributed `stumped` algorithm.\n\n excl_zone : int\n The half width for the exclusion zone relative to the current\n sliding window\n\n T_A_subseq_isfinite_fname : str\n The file name for the boolean array that indicates whether a subsequence in\n `T_A` contains a `np.nan`/`np.inf` value (False)\n\n T_B_subseq_isfinite_fname : str\n The file name for the boolean array that indicates whether a subsequence in\n `T_B` contains a `np.nan`/`np.inf` value (False)\n\n T_A_subseq_squared_fname : str\n The file name for the squared subsequences of `T_A`\n\n T_B_subseq_squared_fname : str\n The file name for the squared subsequences of `T_B`\n\n QT_fname : str\n The file name for the dot product between some query sequence,`Q`,\n and time series, `T`\n\n QT_first_fname : str\n The file name for the QT for the first window relative to the current\n sliding window\n\n k : int\n The total number of sliding windows to iterate over\n\n ignore_trivial : bool, default True\n Set to `True` if this is a self-join. Otherwise, for AB-join, set this to\n `False`. Default is `True`.\n\n range_start : int, default 1\n The starting index value along T_B for which to start the matrix\n profile calculation. Default is 1.\n\n device_id : int, default 0\n The (GPU) device number to use. The default value is `0`.\n\n Returns\n -------\n profile_fname : str\n The file name for the matrix profile\n\n indices_fname : str\n The file name for the matrix profile indices. The first column of the\n array consists of the matrix profile indices, the second column consists\n of the left matrix profile indices, and the third column consists of the\n right matrix profile indices.\n\n Notes\n -----\n `arXiv:1901.05708 \\\n <https://arxiv.org/pdf/1901.05708.pdf>`__\n\n See Algorithm 1\n\n Note that we have extended this algorithm for AB-joins as well.\n\n `DOI: 10.1109/ICDM.2016.0085 \\\n <https://www.cs.ucr.edu/~eamonn/STOMP_GPU_final_submission_camera_ready.pdf>`__\n\n See Table II, Figure 5, and Figure 6\n \"\"\"\n threads_per_block = config.STUMPY_THREADS_PER_BLOCK\n blocks_per_grid = math.ceil(k / threads_per_block)\n\n T_A = np.load(T_A_fname, allow_pickle=False)\n T_B = np.load(T_B_fname, allow_pickle=False)\n QT = np.load(QT_fname, allow_pickle=False)\n QT_first = np.load(QT_first_fname, allow_pickle=False)\n T_A_subseq_isfinite = np.load(T_A_subseq_isfinite_fname, allow_pickle=False)\n T_B_subseq_isfinite = np.load(T_B_subseq_isfinite_fname, allow_pickle=False)\n T_A_subseq_squared = np.load(T_A_subseq_squared_fname, allow_pickle=False)\n T_B_subseq_squared = np.load(T_B_subseq_squared_fname, allow_pickle=False)\n\n with cuda.gpus[device_id]:\n device_T_A = cuda.to_device(T_A)\n device_T_A_subseq_isfinite = cuda.to_device(T_A_subseq_isfinite)\n device_T_A_subseq_squared = cuda.to_device(T_A_subseq_squared)\n device_QT_odd = cuda.to_device(QT)\n device_QT_even = cuda.to_device(QT)\n device_QT_first = cuda.to_device(QT_first)\n if ignore_trivial:\n device_T_B = device_T_A\n device_T_B_subseq_isfinite = device_T_A_subseq_isfinite\n device_T_B_subseq_squared = device_T_A_subseq_squared\n else:\n device_T_B = cuda.to_device(T_B)\n device_T_B_subseq_isfinite = cuda.to_device(T_B_subseq_isfinite)\n device_T_B_subseq_squared = cuda.to_device(T_B_subseq_squared)\n\n profile = np.full((k, 3), np.inf) # float64\n indices = np.full((k, 3), -1, dtype=np.int64) # int64\n\n device_profile = cuda.to_device(profile)\n device_indices = cuda.to_device(indices)\n _compute_and_update_PI_kernel[blocks_per_grid, threads_per_block](\n range_start - 1,\n device_T_A,\n device_T_B,\n m,\n device_QT_even,\n device_QT_odd,\n device_QT_first,\n device_T_A_subseq_isfinite,\n device_T_B_subseq_isfinite,\n device_T_A_subseq_squared,\n device_T_B_subseq_squared,\n k,\n ignore_trivial,\n excl_zone,\n device_profile,\n device_indices,\n False,\n )\n\n for i in range(range_start, range_stop):\n _compute_and_update_PI_kernel[blocks_per_grid, threads_per_block](\n i,\n device_T_A,\n device_T_B,\n m,\n device_QT_even,\n device_QT_odd,\n device_QT_first,\n device_T_A_subseq_isfinite,\n device_T_B_subseq_isfinite,\n device_T_A_subseq_squared,\n device_T_B_subseq_squared,\n k,\n ignore_trivial,\n excl_zone,\n device_profile,\n device_indices,\n True,\n )\n\n profile = device_profile.copy_to_host()\n indices = device_indices.copy_to_host()\n profile = np.sqrt(profile)\n\n profile_fname = core.array_to_temp_file(profile)\n indices_fname = core.array_to_temp_file(indices)\n\n return profile_fname, indices_fname\n\n\ndef gpu_aamp(T_A, m, T_B=None, ignore_trivial=True, device_id=0):\n \"\"\"\n Compute the non-normalized (i.e., without z-normalization) matrix profile with one\n or more GPU devices\n\n This is a convenience wrapper around the Numba `cuda.jit` `_gpu_aamp` function\n which computes the non-normalized matrix profile according to modified version\n GPU-STOMP.\n\n Parameters\n ----------\n T_A : ndarray\n The time series or sequence for which to compute the matrix profile\n\n m : int\n Window size\n\n T_B : ndarray, default None\n The time series or sequence that contain your query subsequences\n of interest. Default is `None` which corresponds to a self-join.\n\n ignore_trivial : bool, default True\n Set to `True` if this is a self-join. Otherwise, for AB-join, set this\n to `False`. Default is `True`.\n\n device_id : int or list, default 0\n The (GPU) device number to use. The default value is `0`. A list of\n valid device ids (int) may also be provided for parallel GPU-STUMP\n computation. A list of all valid device ids can be obtained by\n executing `[device.id for device in numba.cuda.list_devices()]`.\n\n Returns\n -------\n out : ndarray\n The first column consists of the matrix profile, the second column\n consists of the matrix profile indices, the third column consists of\n the left matrix profile indices, and the fourth column consists of\n the right matrix profile indices.\n\n Notes\n -----\n `arXiv:1901.05708 \\\n <https://arxiv.org/pdf/1901.05708.pdf>`__\n\n See Algorithm 1\n\n Note that we have extended this algorithm for AB-joins as well.\n\n `DOI: 10.1109/ICDM.2016.0085 \\\n <https://www.cs.ucr.edu/~eamonn/STOMP_GPU_final_submission_camera_ready.pdf>`__\n\n See Table II, Figure 5, and Figure 6\n \"\"\"\n if T_B is None: # Self join!\n T_B = T_A\n ignore_trivial = True\n\n T_A, T_A_subseq_isfinite = core.preprocess_non_normalized(T_A, m)\n T_B, T_B_subseq_isfinite = core.preprocess_non_normalized(T_B, m)\n\n T_A_subseq_squared = np.sum(core.rolling_window(T_A * T_A, m), axis=1)\n T_B_subseq_squared = np.sum(core.rolling_window(T_B * T_B, m), axis=1)\n\n if T_A.ndim != 1: # pragma: no cover\n raise ValueError(\n f\"T_A is {T_A.ndim}-dimensional and must be 1-dimensional. \"\n \"For multidimensional STUMP use `stumpy.mstump` or `stumpy.mstumped`\"\n )\n\n if T_B.ndim != 1: # pragma: no cover\n raise ValueError(\n f\"T_B is {T_B.ndim}-dimensional and must be 1-dimensional. \"\n \"For multidimensional STUMP use `stumpy.mstump` or `stumpy.mstumped`\"\n )\n\n core.check_window_size(m, max_size=min(T_A.shape[0], T_B.shape[0]))\n\n if ignore_trivial is False and core.are_arrays_equal(T_A, T_B): # pragma: no cover\n logger.warning(\"Arrays T_A, T_B are equal, which implies a self-join.\")\n logger.warning(\"Try setting `ignore_trivial = True`.\")\n\n if ignore_trivial and core.are_arrays_equal(T_A, T_B) is False: # pragma: no cover\n logger.warning(\"Arrays T_A, T_B are not equal, which implies an AB-join.\")\n logger.warning(\"Try setting `ignore_trivial = False`.\")\n\n n = T_B.shape[0]\n k = T_A.shape[0] - m + 1\n l = n - m + 1\n excl_zone = int(\n np.ceil(m / config.STUMPY_EXCL_ZONE_DENOM)\n ) # See Definition 3 and Figure 3\n\n T_A_fname = core.array_to_temp_file(T_A)\n T_B_fname = core.array_to_temp_file(T_B)\n T_A_subseq_isfinite_fname = core.array_to_temp_file(T_A_subseq_isfinite)\n T_B_subseq_isfinite_fname = core.array_to_temp_file(T_B_subseq_isfinite)\n T_A_subseq_squared_fname = core.array_to_temp_file(T_A_subseq_squared)\n T_B_subseq_squared_fname = core.array_to_temp_file(T_B_subseq_squared)\n\n out = np.empty((k, 4), dtype=object)\n\n if isinstance(device_id, int):\n device_ids = [device_id]\n else:\n device_ids = device_id\n\n profile = [None] * len(device_ids)\n indices = [None] * len(device_ids)\n\n for _id in device_ids:\n with cuda.gpus[_id]:\n if (\n cuda.current_context().__class__.__name__ != \"FakeCUDAContext\"\n ): # pragma: no cover\n cuda.current_context().deallocations.clear()\n\n step = 1 + l // len(device_ids)\n\n # Start process pool for multi-GPU request\n if len(device_ids) > 1: # pragma: no cover\n mp.set_start_method(\"spawn\", force=True)\n p = mp.Pool(processes=len(device_ids))\n results = [None] * len(device_ids)\n\n QT_fnames = []\n QT_first_fnames = []\n\n for idx, start in enumerate(range(0, l, step)):\n stop = min(l, start + step)\n\n QT, QT_first = core._get_QT(start, T_A, T_B, m)\n QT_fname = core.array_to_temp_file(QT)\n QT_first_fname = core.array_to_temp_file(QT_first)\n QT_fnames.append(QT_fname)\n QT_first_fnames.append(QT_first_fname)\n\n if len(device_ids) > 1 and idx < len(device_ids) - 1: # pragma: no cover\n # Spawn and execute in child process for multi-GPU request\n results[idx] = p.apply_async(\n _gpu_aamp,\n (\n T_A_fname,\n T_B_fname,\n m,\n stop,\n excl_zone,\n T_A_subseq_isfinite_fname,\n T_B_subseq_isfinite_fname,\n T_A_subseq_squared_fname,\n T_B_subseq_squared_fname,\n QT_fname,\n QT_first_fname,\n k,\n ignore_trivial,\n start + 1,\n device_ids[idx],\n ),\n )\n else:\n # Execute last chunk in parent process\n # Only parent process is executed when a single GPU is requested\n profile[idx], indices[idx] = _gpu_aamp(\n T_A_fname,\n T_B_fname,\n m,\n stop,\n excl_zone,\n T_A_subseq_isfinite_fname,\n T_B_subseq_isfinite_fname,\n T_A_subseq_squared_fname,\n T_B_subseq_squared_fname,\n QT_fname,\n QT_first_fname,\n k,\n ignore_trivial,\n start + 1,\n device_ids[idx],\n )\n\n # Clean up process pool for multi-GPU request\n if len(device_ids) > 1: # pragma: no cover\n p.close()\n p.join()\n\n # Collect results from spawned child processes if they exist\n for idx, result in enumerate(results):\n if result is not None:\n profile[idx], indices[idx] = result.get()\n\n os.remove(T_A_fname)\n os.remove(T_B_fname)\n os.remove(T_A_subseq_isfinite_fname)\n os.remove(T_B_subseq_isfinite_fname)\n os.remove(T_A_subseq_squared_fname)\n os.remove(T_B_subseq_squared_fname)\n for QT_fname in QT_fnames:\n os.remove(QT_fname)\n for QT_first_fname in QT_first_fnames:\n os.remove(QT_first_fname)\n\n for idx in range(len(device_ids)):\n profile_fname = profile[idx]\n indices_fname = indices[idx]\n profile[idx] = np.load(profile_fname, allow_pickle=False)\n indices[idx] = np.load(indices_fname, allow_pickle=False)\n os.remove(profile_fname)\n os.remove(indices_fname)\n\n for i in range(1, len(device_ids)):\n # Update all matrix profiles and matrix profile indices\n # (global, left, right) and store in profile[0] and indices[0]\n for col in range(profile[0].shape[1]): # pragma: no cover\n cond = profile[0][:, col] < profile[i][:, col]\n profile[0][:, col] = np.where(cond, profile[0][:, col], profile[i][:, col])\n indices[0][:, col] = np.where(cond, indices[0][:, col], indices[i][:, col])\n\n out[:, 0] = profile[0][:, 0]\n out[:, 1:4] = indices[0][:, :]\n\n threshold = 10e-6\n if core.are_distances_too_small(out[:, 0], threshold=threshold): # pragma: no cover\n logger.warning(f\"A large number of values are smaller than {threshold}.\")\n logger.warning(\"For a self-join, try setting `ignore_trivial = True`.\")\n\n return out\n" ]
[ [ "numpy.load", "numpy.ceil", "numpy.empty", "numpy.sqrt", "numpy.where", "numpy.full" ] ]
susantamoh84/TensorFlow-Book
[ "905bd82e6e58c373b566f4813859c5dfc1fa1aa4" ]
[ "ch09_cnn/cifar_tools.py" ]
[ "import cPickle\nimport numpy as np\n\n\ndef unpickle(file):\n fo = open(file, 'rb')\n dict = cPickle.load(fo)\n fo.close()\n return dict\n\n\ndef clean(data):\n imgs = data.reshape(data.shape[0], 3, 32, 32)\n grayscale_imgs = imgs.mean(1)\n cropped_imgs = grayscale_imgs[:, 4:28, 4:28]\n img_data = cropped_imgs.reshape(data.shape[0], -1)\n img_size = np.shape(img_data)[1]\n means = np.mean(img_data, axis=1)\n meansT = means.reshape(len(means), 1)\n stds = np.std(img_data, axis=1)\n stdsT = stds.reshape(len(stds), 1)\n adj_stds = np.maximum(stdsT, 1.0 / np.sqrt(img_size))\n normalized = (img_data - meansT) / adj_stds\n return normalized\n\n\ndef read_data(directory):\n names = unpickle('{}/batches.meta'.format(directory))['label_names']\n print('names', names)\n\n data, labels = [], []\n for i in range(1, 6):\n filename = '{}/data_batch_{}'.format(directory, i)\n batch_data = unpickle(filename)\n if len(data) > 0:\n data = np.vstack((data, batch_data['data']))\n labels = np.hstack((labels, batch_data['labels']))\n else:\n data = batch_data['data']\n labels = batch_data['labels']\n\n print(np.shape(data), np.shape(labels))\n\n data = clean(data)\n data = data.astype(np.float32)\n return names, data, labels\n" ]
[ [ "numpy.vstack", "numpy.hstack", "numpy.shape", "numpy.sqrt", "numpy.std", "numpy.mean" ] ]
joschout/Multi-Directional-Rule-Set-Learning
[ "ef0620b115f4e0fd7fba3e752d238a8020c1ca6b", "ef0620b115f4e0fd7fba3e752d238a8020c1ca6b" ]
[ "mdrsl/rule_generation/association_rule_mining/apyori_impl/mine_mt_rules_from_dataframe_with_apyori.py", "experiments/arcbench_data_preparation/arc_model_data_preparation.py" ]
[ "import random\n\nimport numpy as np\nfrom typing import List, Optional, Dict\nimport pandas as pd\nimport time\n\nfrom mdrsl.rule_generation.association_rule_mining.apyori_impl.mine_mt_rules_from_transactions_with_apyori import (\n mine_MCARs_from_transactions_using_apyori)\nfrom mdrsl.rule_generation.association_rule_mining.frequent_itemset_mining import (\n dataframe_to_list_of_transactions, run_fim_apriori, dataframe_to_list_of_transactions_with_encoding)\nfrom mdrsl.data_structures.rules.multi_target_class_association_rule import MCAR\n\n\ndef mine_MCARs_from_df_using_apyori(df,\n min_support: float = 0.1, min_confidence: float = 0.0, min_lift=0.0,\n max_length=None) -> List[MCAR]:\n transactions = dataframe_to_list_of_transactions(df)\n return mine_MCARs_from_transactions_using_apyori(\n transactions,\n min_support=min_support, min_confidence=min_confidence,\n min_lift=min_lift, max_length=max_length)\n\n\ndef mine_MCARs_from_df_using_apyori_with_encodings(df,\n min_support: float = 0.1, min_confidence: float = 0.0, min_lift=0.0,\n max_length=None) -> List[MCAR]:\n transactions, item_encoder = dataframe_to_list_of_transactions_with_encoding(df)\n return mine_MCARs_from_transactions_using_apyori(\n transactions,\n min_support=min_support, min_confidence=min_confidence,\n min_lift=min_lift, max_length=max_length, item_encoder=item_encoder)\n\n\ndef mine_MCARs(df, rule_cutoff: int,\n sample=False, random_seed=None,\n verbose: bool = True,\n **top_rules_kwargs) -> List[MCAR]:\n\n transactions: List[List[str]] = dataframe_to_list_of_transactions(df)\n mcars: Optional[List[MCAR]] = _top_rules_MIDS(transactions,\n target_rule_count=rule_cutoff,\n verbose=verbose)\n\n if mcars is None:\n raise Exception(\"no MCARs found as input for MIDS\")\n\n if len(mcars) > rule_cutoff:\n if sample:\n if random_seed is not None:\n random.seed(random_seed)\n mcars_subset = random.sample(mcars, rule_cutoff)\n else:\n mcars_subset = mcars[:rule_cutoff]\n else:\n mcars_subset = mcars\n return mcars_subset\n\n\nif __name__ == '__main__':\n\n df_total = pd.DataFrame({\n 'A': np.array([1] * 4, dtype='float32'),\n 'B': np.array([2] * 4, dtype='float32'),\n 'C': np.array([3] * 4, dtype='float32'),\n 'D': np.array([4] * 4, dtype='float32')\n })\n\n print(df_total)\n\n itemsets = dataframe_to_list_of_transactions(df_total)\n\n support_threshold = 0.1\n dataset_transactions = dataframe_to_list_of_transactions(df_total) # type: List[List[str]]\n\n cars = mine_MCARs_from_transactions_using_apyori(dataset_transactions, min_support=support_threshold)\n for car in cars:\n print(car)\n\n print(\"---\")\n fim_frequent_itemsets = run_fim_apriori(df_total, support_threshold)\n print(fim_frequent_itemsets)\n\n\ndef _top_rules_MIDS(transactions: List[List[str]],\n appearance: Optional[Dict] = None,\n\n target_rule_count: int = 1000,\n\n init_support: float = 0.05,\n init_confidence: float = 0.5,\n\n confidence_step: float = 0.05,\n support_step: float = 0.05,\n\n min_length: int = 2,\n init_max_length: int = 3,\n\n total_timeout: float = 100.0, # max time in seconds\n max_iterations: int = 30,\n verbose: bool = True\n ):\n \"\"\"\n Function for finding the best n (target_rule_count) rules from transaction list.\n PROBLEM: how to define 'best'?\n\n Iteratively:\n Search for the rules under the current mining parameters.\n Check the properties of the found rules.\n If there is still room for improvement,\n Then update the mining parameters,\n\n\n\n STOP if:\n - max nb of iterations is reached (default: 30).\n - the current nb of rules is more than the nb of rules we are looking for.\n - the time out is reach\n\n FIND all rules with as constraints:\n - min_support\n - min_confidence\n - max_length\n\n\n Parameters\n ----------\n :param transactions : 2D array of strings, e.g. [[\"a:=:1\", \"b:=:3\"], [\"a:=:4\", \"b:=:2\"]]\n :param appearance : dict - dictionary specifying rule appearance\n :param target_rule_count : int - target number of rules to mine\n :param init_support : float - support from which to start mining\n :param init_confidence : float - confidence from which to start mining\n :param confidence_step : float\n :param support_step : float\n :param min_length : int - minimum len of rules to mine\n :param init_max_length : int - maximum len from which to start mining\n :param total_timeout : float - maximum execution time of the function\n :param max_iterations : int - maximum iterations to try before stopping execution\n :param verbose : bool\n\n Returns\n -------\n list of mined rules. The rules are not ordered.\n\n \"\"\"\n\n if appearance is None:\n appearance = {}\n\n start_time: float = time.time()\n\n # the length of a rule is at most the length of a transaction. (All transactions have the same length.)\n\n # max_rule_length_wanted = 10\n # MAX_RULE_LEN: int = min(len(transactions[0]), max_rule_length_wanted)\n MAX_RULE_LEN: int = len(transactions[0])\n\n\n current_support: float = init_support\n current_confidence: float = init_confidence\n\n current_max_length: int = init_max_length\n\n keep_mining: bool = True\n\n is_max_length_decreased_due_timeout = False\n current_iteration = 0\n\n last_rule_count = -1\n rules: Optional[List[MCAR]] = None\n\n if verbose:\n print(\"STARTING top_rules\")\n while keep_mining:\n current_iteration += 1\n\n if current_iteration > max_iterations:\n if verbose:\n print(\"Max iterations reached\")\n break\n\n if verbose:\n print(f\"--- iteration {current_iteration} ---\")\n print((f\"Running apriori with setting: \"\n f\"confidence={current_confidence}, \"\n f\"support={current_support}, \"\n f\"min_length={min_length}, \"\n f\"max_length={current_max_length}, \"\n f\"MAX_RULE_LEN={MAX_RULE_LEN}\"\n ))\n\n current_rules: List[MCAR] = mine_MCARs_from_transactions_using_apyori(\n transactions, min_support=current_support, min_confidence=current_confidence, max_length=current_max_length)\n # rules_current = fim.arules(transactions, supp=support, conf=conf, mode=\"o\", report=\"sc\", appear=appearance,\n # zmax=maxlen, zmin=minlen)\n\n current_nb_of_rules = len(current_rules)\n\n # assign\n rules = current_rules\n\n if verbose:\n print(f\"Rule count: {current_nb_of_rules}, Iteration: {current_iteration}\")\n\n if current_nb_of_rules >= target_rule_count:\n keep_mining = False\n if verbose:\n print(f\"\\tTarget rule count satisfied: {target_rule_count}\")\n else:\n current_execution_time = time.time() - start_time\n\n # if timeout limit exceeded\n if current_execution_time > total_timeout:\n if verbose:\n print(\"Execution time exceeded:\", total_timeout)\n keep_mining = False\n\n # if we can still increase our rule length AND\n # the number of rules found has changed (increased?) since last time AND\n # there has\n elif current_max_length < MAX_RULE_LEN and last_rule_count != current_nb_of_rules and not is_max_length_decreased_due_timeout:\n current_max_length += 1\n last_rule_count = current_nb_of_rules\n if verbose:\n print(f\"\\tIncreasing max_length {current_max_length}\")\n\n # if we can still increase our rule length AND\n #\n # we can still increase our support\n # THEN:\n # increase our support\n # increment our max length\n elif current_max_length < MAX_RULE_LEN and is_max_length_decreased_due_timeout and current_support <= 1 - support_step:\n current_support += support_step\n current_max_length += 1\n last_rule_count = current_nb_of_rules\n is_max_length_decreased_due_timeout = False\n\n if verbose:\n print(f\"\\tIncreasing maxlen to {current_max_length}\")\n print(f\"\\tIncreasing minsup to {current_support}\")\n # IF we can still decrease our confidence\n # THEN decrease our confidence\n elif current_confidence > confidence_step:\n current_confidence -= confidence_step\n if verbose:\n print(f\"\\tDecreasing confidence to {current_confidence}\")\n else:\n if verbose:\n print(\"\\tAll options exhausted\")\n keep_mining = False\n if verbose:\n end_of_current_iteration_message = f\"--- end iteration {current_iteration} ---\"\n print(end_of_current_iteration_message)\n print(\"-\" * len(end_of_current_iteration_message))\n if verbose:\n print(f\"FINISHED top_rules after {current_iteration} iterations\")\n return rules\n", "import pandas as pd\n\nfrom experiments.arcbench_data_preparation.reworked_one_hot_encoding import get_original_data_fold_abs_file_name, \\\n TrainTestEnum\nfrom mdrsl.data_handling.nan_data_filtering import remove_instances_with_nans_in_column\nfrom mdrsl.data_handling.reorder_dataset_columns import reorder_columns\n\n\ndef prepare_arc_data(\n dataset_name: str,\n fold_i: int,\n target_attribute: str,\n train_test: TrainTestEnum\n) -> pd.DataFrame:\n # read in original (discretized) training/test data\n # reorder the data so the target column is last\n original_data_fold_abs_file_name = get_original_data_fold_abs_file_name(dataset_name, fold_i, train_test)\n df_original_column_order = pd.read_csv(original_data_fold_abs_file_name, delimiter=',')\n df_reordered = reorder_columns(df_original_column_order, target_attribute)\n\n # REMOVE INSTANCES WITH NAN AS TARGET VALUE:\n df_reordered = remove_instances_with_nans_in_column(df_reordered, target_attribute)\n return df_reordered\n" ]
[ [ "numpy.array" ], [ "pandas.read_csv" ] ]
ashishpatel26/ML-DL-scripts
[ "25f930630f6e546955ad13863d6e728c8c702d43" ]
[ "NLP/LSTM RNN/WSDM - Fake News Classification/Berd generate embeddings/3_bert_encode_ch_test.py" ]
[ "# Please run bert-serving-start before running this notebook\n# Setup: https://github.com/hanxiao/bert-as-service\n# Examples (change folders to your locals)\n# english cased: bert-serving-start -model_dir /bert-as-service/cased_L-24_H-1024_A-16/ -num_worker=4\n# multi cased: bert-serving-start -model_dir /bert-as-service/multi_cased_L-12_H-768_A-12/ -num_worker=4\n# chinese: bert-serving-start -model_dir /bert-as-service/chinese_L-12_H-768_A-12/ -num_worker=4\n\n# launch bert (valilenk): \n# english cased: bert-serving-start -model_dir /media/airvetra/1tb/valilenk/nlp/bert-as-service/cased_L-24_H-1024_A-16/ -num_worker=2\n# multi cased: bert-serving-start -model_dir /media/airvetra/1tb/valilenk/nlp/bert-as-service/multi_cased_L-12_H-768_A-12/ -num_worker=2\n# chinese: bert-serving-start -model_dir /media/airvetra/1tb/valilenk/nlp/bert-as-service/chinese_L-12_H-768_A-12/ -num_worker=2\n\nimport pandas as pd\nimport torch\nimport os\nfrom time import time\nfrom tqdm import tqdm\nfrom bert_serving.client import BertClient\n\ndata_folder = os.path.dirname(os.getcwd())+'/data'\ntest = pd.read_csv(data_folder+'/raw/test.csv')\n\nbc = BertClient()\ndef gen_encodings(df, column):\n t0 = time()\n _list = list(df.loc[:, column])\n for i, text in enumerate(_list):\n if not isinstance(_list[i], str):\n _list[i] = str(text)\n if not _list[i].strip():\n _list[i] = _list[i].strip()\n if len(_list[i]) == 0:\n _list[i] = 'temp'\n arr = bc.encode(_list)\n temp = pd.DataFrame(arr)\n temp.columns = [f'{column}_{c}' for c in range(len(arr[0]))]\n temp = temp.join(df.id)\n print(f'time: {time() - t0}')\n return temp\n\nencoded_test = gen_encodings(test, 'title1_zh')\nencoded_test.to_csv('encoded_ch_test1.csv')\nencoded_test = gen_encodings(test, 'title2_zh')\nencoded_test.to_csv('encoded_ch_test2.csv')" ]
[ [ "pandas.read_csv", "pandas.DataFrame" ] ]
sburgholzer/MSDS-Capstone-Project
[ "4f22149c7ebff5c3dc129bb785d56f161ab138a8" ]
[ "implementation/spcTornadoCounts.py" ]
[ "import pandas as pd\r\n\r\ndf = pd.read_csv('/mnt/data3/scott/1950-2018_actual_tornadoes.csv')\r\n\r\ndf['date'] = pd.to_datetime(df['date'])\r\nmask = (df['date'] >= '1979-1-1') & (df['date'] <= '2013-12-31')\r\ndf = df.loc[mask]\r\ndf.groupby('date').size()\r\ndf.groupby('date').size().to_csv('/mnt/data3/scott/tornadoCounts.csv')" ]
[ [ "pandas.read_csv", "pandas.to_datetime" ] ]
Harald-R/aw_nas
[ "8cf0cf48f7bcfd7893e6355dcc3ccbc83fd39783" ]
[ "aw_nas/final/rnn_model.py" ]
[ "#pylint: disable=invalid-name\n\nimport numpy as np\nimport torch\nfrom torch import nn\n\nfrom aw_nas import ops\nfrom aw_nas.utils.exception import expect, ConfigException\nfrom aw_nas.weights_manager.rnn_shared import RNNSharedNet, INIT_RANGE\n\nclass RNNGenotypeModel(RNNSharedNet):\n REGISTRY = \"final_model\"\n NAME = \"rnn_model\"\n def __init__(self, search_space, device, genotypes,\n num_tokens, num_emb=300, num_hid=300,\n tie_weight=True, decoder_bias=True,\n share_primitive_weights=False, share_from_weights=False,\n batchnorm_step=False,\n batchnorm_edge=False, batchnorm_out=True,\n # training\n max_grad_norm=5.0,\n # dropout probs\n dropout_emb=0., dropout_inp0=0., dropout_inp=0., dropout_hid=0., dropout_out=0.):\n\n self.genotypes = genotypes\n if isinstance(genotypes, str):\n self.genotypes = eval(\"search_space.genotype_type({})\".format(self.genotypes)) # pylint: disable=eval-used\n self.genotypes = list(self.genotypes._asdict().values())\n # check tos:\n _tos = [conn[2] for conn in self.genotypes[0]]\n (np.argsort(_tos) == np.arange(len(_tos))).all()\n expect((np.argsort(_tos) == np.arange(len(_tos))).all(),\n \"genotype must be ordered in the way that `to_node` monotonously increase\",\n ConfigException)\n\n super(RNNGenotypeModel, self).__init__(\n search_space, device,\n cell_cls=RNNGenotypeCell, op_cls=None,\n num_tokens=num_tokens, num_emb=num_emb, num_hid=num_hid,\n tie_weight=tie_weight, decoder_bias=decoder_bias,\n share_primitive_weights=share_primitive_weights, share_from_weights=share_from_weights,\n batchnorm_step=batchnorm_step,\n batchnorm_edge=batchnorm_edge, batchnorm_out=batchnorm_out,\n max_grad_norm=max_grad_norm,\n dropout_emb=dropout_emb, dropout_inp0=dropout_inp0, dropout_inp=dropout_inp,\n dropout_hid=dropout_hid, dropout_out=dropout_out,\n genotypes=self.genotypes) # this genotypes will be used for construction/forward\n\n self.logger.info(\"Genotype: %s\", self.genotypes)\n\n def forward(self, inputs, hiddens): #pylint: disable=arguments-differ\n # this genotypes will not be used\n return RNNSharedNet.forward(self, inputs, self.genotypes, hiddens)\n\n @classmethod\n def supported_rollout_types(cls):\n # this should not be called\n # assert 0, \"should not be called\"\n return []\n\n def assemble_candidate(self, *args, **kwargs): #pylint: disable=arguments-differ\n # this will not be called\n assert 0, \"should not be called\"\n\nclass RNNGenotypeCell(nn.Module):\n def __init__(self, search_space, device, op_cls, num_emb, num_hid,\n share_from_weights, batchnorm_step,\n batchnorm_edge, batchnorm_out, genotypes, **kwargs):\n super(RNNGenotypeCell, self).__init__()\n self.genotypes = genotypes\n\n self.search_space = search_space\n\n self.num_emb = num_emb\n self.num_hid = num_hid\n self.batchnorm_step = batchnorm_step\n self.batchnorm_edge = batchnorm_edge\n self.batchnorm_out = batchnorm_out\n self.share_from_w = share_from_weights\n self._steps = search_space.num_steps\n self._num_init = search_space.num_init_nodes\n\n # the first step, convert input x and previous hidden\n self.w_prev = nn.Linear(num_emb + num_hid, 2 * num_hid, bias=False)\n self.w_prev.weight.data.uniform_(-INIT_RANGE, INIT_RANGE)\n\n if self.batchnorm_edge:\n # batchnorm on each edge/connection\n # when `num_node_inputs==1`, there is `step + 1` edges\n # the first bn\n self.bn_prev = nn.BatchNorm1d(num_emb + num_hid, affine=True)\n # other bn\n self.bn_edges = nn.ModuleList([nn.BatchNorm1d(num_emb + num_hid, affine=True)\n for _ in range(len(self.genotypes[0]))])\n\n if self.batchnorm_step:\n # batchnorm after every step (as in darts's implementation)\n self.bn_steps = nn.ModuleList([nn.BatchNorm1d(num_hid, affine=False)\n for _ in range(self._steps+1)])\n\n if self.batchnorm_out:\n # the out bn\n self.bn_out = nn.BatchNorm1d(num_hid, affine=True)\n\n if self.share_from_w:\n # actually, as `num_node_inputs==1`, thus only one from node is used each step\n # `share_from_w==True/False` are equivalent in final training...\n self.step_weights = nn.ModuleList([\n nn.Linear(num_hid, 2*num_hid, bias=False)\n for _ in range(self._steps)])\n [mod.weight.data.uniform_(-INIT_RANGE, INIT_RANGE) for mod in self.step_weights]\n\n # initiatiate op on edges\n self.Ws = nn.ModuleList()\n self.ops = nn.ModuleList()\n genotype_, _ = self.genotypes\n\n for op_type, _, _ in genotype_:\n # edge weights\n op = ops.get_op(op_type)()\n self.ops.append(op)\n if not self.share_from_w:\n W = nn.Linear(self.num_hid, 2 * self.num_hid, bias=False)\n W.weight.data.uniform_(-INIT_RANGE, INIT_RANGE)\n self.Ws.append(W)\n\n def forward(self, inputs, hidden, x_mask, h_mask, genotypes): #pylint: disable=arguments-differ\n \"\"\"\n Cell forward, forward for one timestep.\n \"\"\"\n genotype, concat_ = self.genotypes # self.genotypes == genotypes\n\n s0 = self._compute_init_state(inputs, hidden, x_mask, h_mask)\n if self.batchnorm_step:\n s0 = self.bn_steps[0](s0)\n\n states = {0: s0}\n\n for i, (_, from_, to_) in enumerate(genotype):\n s_prev = states[from_]\n s_inputs = s_prev\n if self.training:\n s_inputs = s_prev * h_mask\n w = self.step_weights[to_-1] if self.share_from_w else self.Ws[i]\n ch = w(s_inputs)\n if self.batchnorm_edge:\n ch = self.bn_edges[i](ch)\n c, h = torch.split(ch, self.num_hid, dim=-1)\n c = c.sigmoid()\n h = self.ops[i](h)\n out = s_prev + c * (h - s_prev)\n if to_ in states:\n states[to_] = states[to_] + out\n else:\n states[to_] = out\n\n to_finish = i == len(genotype)-1 or genotype[i+1][2] != to_\n if self.batchnorm_step and to_finish:\n # if the calculation of the `to_` step finished, batch norm it\n states[to_] = self.bn_steps[to_](states[to_])\n\n # average the ends\n output = torch.mean(torch.stack([states[i] for i in concat_]), 0)\n if self.batchnorm_out:\n # batchnorm\n output = self.bn_out(output)\n return output\n\n def _compute_init_state(self, x, h, x_mask, h_mask):\n if self.training:\n xh_prev = torch.cat([x * x_mask, h * h_mask], dim=-1)\n else:\n xh_prev = torch.cat([x, h], dim=-1)\n xh_prev = self.w_prev(xh_prev)\n if self.batchnorm_edge:\n xh_prev = self.bn_prev(xh_prev)\n\n c0, h0 = torch.split(xh_prev, self.num_hid, dim=-1)\n c0 = c0.sigmoid()\n h0 = h0.tanh()\n s0 = h + c0 * (h0 - h)\n return s0\n" ]
[ [ "torch.stack", "torch.nn.Linear", "torch.split", "torch.nn.BatchNorm1d", "numpy.argsort", "torch.nn.ModuleList", "torch.cat" ] ]
UST-QuAntiL/qhana
[ "bf499d072dcc37f81efec1b8e17b7d5460db7a04" ]
[ "qhana/backend/elementComparer.py" ]
[ "from abc import ABCMeta\nfrom abc import abstractmethod\nfrom typing import Any\nimport enum\nimport networkx as nx\nfrom networkx import Graph\nfrom qhana.backend.taxonomie import Taxonomie\nfrom qhana.backend.logger import Logger\nimport numpy as np\nfrom qhana.backend.logger import Logger\nimport os\nimport json\nimport math\nfrom qhana.backend.timer import Timer\n\n\"\"\" \nDefines an enum to list up all available element comparer\n\"\"\"\nclass ElementComparerType(enum.Enum):\n wuPalmer = \"wuPalmer\"\n timeTanh = \"timeTanh\"\n\n \"\"\"\n Returns the name of the given ElementComparerType.\n \"\"\"\n @staticmethod\n def get_name(elementComparerType) -> str:\n name = \"\"\n if elementComparerType == ElementComparerType.wuPalmer:\n name += \"WuPalmer\"\n elif elementComparerType == ElementComparerType.timeTanh:\n name += \"TimeTanh\"\n else:\n Logger.error(\"No name for element comparer \\\"\" + str(elementComparerType) + \"\\\" specified\")\n raise ValueError(\"No name for element comparer \\\"\" + str(elementComparerType) + \"\\\" specified\")\n return name\n\n \"\"\"\n Returns the description of the given ElementComparerType.\n \"\"\"\n @staticmethod\n def get_description(elementComparerType) -> str:\n description = \"\"\n if elementComparerType == ElementComparerType.wuPalmer:\n description += \"Compares two elements based on a taxonomy \" \\\n + \"using the wu palmer similarity measure.\"\n elif elementComparerType == ElementComparerType.timeTanh:\n description += \"Compares two timecodes using the tanh function: \" \\\n + \"tanh(abs(a-b) / 7200). We normalize this function to 7200 seconds.\"\n else:\n Logger.error(\"No description for element comparer \\\"\" + str(elementComparerType) + \"\\\" specified\")\n raise ValueError(\"No description for element comparer \\\"\" + str(elementComparerType) + \"\\\" specified\")\n return description\n\n\"\"\" \nRepresents the abstract element comprarer base class\n\"\"\"\nclass ElementComparer(metaclass=ABCMeta):\n \"\"\" \n Returns the comparison value of first and second\n element based on the giben base\n \"\"\"\n @abstractmethod\n def compare(self, first: Any, second: Any, base: Any) -> float:\n pass\n\n \"\"\"\n Creates a full cache on file, i.e. calculates all pariwise similarities\n and safes the result in a file\n \"\"\"\n @abstractmethod\n def create_cache(self, base: Any) -> None:\n pass\n\"\"\" \nRepresents the factory to create an element comparer\n\"\"\"\nclass ElementComparerFactory:\n \"\"\"\n Static method for creating an element comparer\n \"\"\"\n @staticmethod\n def create(type: ElementComparerType) -> ElementComparer:\n if type == ElementComparerType.wuPalmer:\n return WuPalmer()\n elif type == ElementComparerType.timeTanh:\n return TimeTanh()\n else:\n raise Exception(\"Unknown type of element comparer\")\n return\n\n\"\"\"\nRepresents the conventional wu palmer similarity measure\n\"\"\"\nclass WuPalmer(ElementComparer):\n\n \"\"\"\n Constructor.\n \"\"\"\n def __init__(self):\n self.cache = None\n return\n\n \"\"\"\n Applies try to use cache first if available, if not,\n run compare_inner\n \"\"\"\n def compare(self, first: str, second: str, base: Taxonomie) -> float:\n # check if cache is available\n cache = dict()\n if self.cache is None:\n if os.path.isdir(\"cache\") != False:\n fileName = \"cache/\" + base.name + \".json\"\n if os.path.isfile(fileName) != False:\n self.cache = self.__loads_json(fileName)\n cache = self.cache\n else:\n cache = self.cache\n\n if (first, second) in cache:\n if (first, second) in cache:\n return self.cache[(first, second)]\n\n return self.compare_inner(first, second, base)\n\n \"\"\"\n Applies wu palmer similarity measure on two taxonomie elements\n \"\"\"\n def compare_inner(self, first: str, second: str, base: Taxonomie) -> float:\n # Get directed graph\n d_graph = base.graph\n\n # Get undirected graph\n ud_graph = d_graph.to_undirected()\n\n # Get lowest reachable node from both \n lowest_common_ancestor = nx.algorithms.lowest_common_ancestors.lowest_common_ancestor(d_graph, first, second)\n\n # Get root of graph\n root = [n for n,d in d_graph.in_degree() if d == 0][0]\n\n # Count edges - weight is 1 per default\n d1 = nx.algorithms.shortest_paths.generic.shortest_path_length(ud_graph, first, lowest_common_ancestor)\n d2 = nx.algorithms.shortest_paths.generic.shortest_path_length(ud_graph, second, lowest_common_ancestor)\n d3 = nx.algorithms.shortest_paths.generic.shortest_path_length(ud_graph, lowest_common_ancestor, root)\n\n # if first and second, both is the root\n if d1 + d2 + 2 * d3 == 0.0:\n return 0.0\n\n return 2 * d3 / (d1 + d2 + 2 * d3)\n\n \"\"\"\n Serializes a dict object with 2-tuples as key to json file\n \"\"\"\n def __dump_json(self, dic, fileName) -> None:\n with open(fileName, \"w\") as f:\n k = dic.keys()\n v = dic.values()\n k1 = [str(i) for i in k]\n json.dump(json.dumps(dict(zip(*[k1,v]))),f)\n \n \"\"\"\n Deserializes a json file to a dict object with 2-tuples as key\n \"\"\"\n def __loads_json(self, fileName) -> dict:\n with open(fileName, \"r\") as f:\n data = json.load(f)\n dic = json.loads(data)\n k = dic.keys()\n v = dic.values()\n k1 = [eval(i) for i in k]\n return dict(zip(*[k1,v]))\n\n \"\"\"\n Creates the cache for WuPalmer similarity, i.e. calculates pairwise values for\n taxonomy entries\n \"\"\"\n def create_cache(self, base: Taxonomie) -> None:\n fileName = \"cache/\" + base.name + \".json\"\n\n # check if cache already exist\n if os.path.isfile(fileName) and os.path.exists(fileName):\n Logger.debug(\"Cache for \" + base.name + \" already exist\")\n return\n\n # format ((first taxonomy entry, second taxonomy entry), value)\n cache = dict()\n\n amount = int(math.pow(len(base.graph.nodes()), 2))\n index = 1\n everyNSteps = 100\n\n timer: Timer = Timer()\n timer.start()\n\n for first in base.graph.nodes():\n for second in base.graph.nodes():\n cache[(first, second)] = self.compare_inner(first, second, base)\n index += 1\n if index % everyNSteps == 0:\n Logger.debug(str(index) + \" from \" + str(amount))\n\n if os.path.isdir(\"cache\") == False:\n os.mkdir(\"cache\")\n\n self.__dump_json(cache, fileName)\n\n timer.stop()\n\n return\n\n\"\"\"\nRepresents a timecode comparer using the tanh function.\n\"\"\"\nclass TimeTanh(ElementComparer):\n \"\"\"\n Applies the tanh function for comparing timecodes.\n \"\"\"\n def compare(self, first: int, second: int, base: Any) -> float:\n return np.tanh(np.abs( (first - second)) / 7200.0)\n " ]
[ [ "numpy.abs" ] ]
zhangxinzhou/play_game
[ "854448f8416b2d3f98bb2c3ed0f7d834a61593de" ]
[ "opencv_learn/charpter12/demo_12.06.py" ]
[ "import cv2\nimport numpy as np\n\no = cv2.imread(\"contours.bmp\")\ngray = cv2.cvtColor(o, cv2.COLOR_BGR2GRAY)\nret, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)\ncontours, hierarchy = cv2.findContours(binary, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)\ncv2.imshow(\"original\", o)\nn = len(contours)\ncontoursImg = []\nfor i in range(n):\n temp = np.zeros(o.shape, np.uint8)\n contoursImg.append(temp)\n contoursImg[i] = cv2.drawContours(contoursImg[i], contours, i, (255, 255, 255), 3)\n if cv2.contourArea(contours[i]) > 12000:\n cv2.imshow(\"contours[\" + str(i) + \"]\", contoursImg[i])\n\ncv2.waitKey()\ncv2.destroyAllWindows()\n" ]
[ [ "numpy.zeros" ] ]
bstriner/gym-learning-to-learn
[ "4cd93bf7a306255771a32e0d97b3d705b2666656" ]
[ "gym_learning_to_learn/envs/base_env.py" ]
[ "from gym import Env\nfrom gym.utils import seeding\nfrom gym import spaces\nimport numpy as np\nimport keras.backend as K\n\n\nclass BaseEnv(Env):\n metadata = {'render.modes': ['human', 'ansi']}\n\n def __init__(self, action_mapping):\n self._seed()\n self.verbose = 0\n self.viewer = None\n self.batch_size = 32\n self.optimizer = None\n self.model = None\n self.current_step = 0\n self.action_mapping = action_mapping\n self.action_space = action_mapping.action_space\n bounds = float('inf')\n self.observation_space = spaces.Box(-bounds, bounds, (4,))\n self.viewer = None\n self.best = None\n self.evaluate_test = False\n Env.__init__(self)\n\n def _seed(self, seed=None):\n self.np_random, seed = seeding.np_random(seed)\n return [seed]\n\n def create_model(self):\n pass\n\n def create_optimizer(self):\n pass\n\n def loss_scale(self, loss):\n return -np.log(loss)\n\n def _step(self, action):\n self.action_mapping.step(self.optimizer, action)\n loss_before = self.losses(self.data_val)\n if self.best is None:\n self.best = loss_before\n self.model.fit(self.data_train[0], self.data_train[1],\n validation_data=(self.data_val[0], self.data_val[1]),\n nb_epoch=1, verbose=self.verbose, batch_size=self.batch_size)\n loss_after = self.losses(self.data_val)\n self.current_step += 1\n observation = self._observation()\n if (loss_after > 1e10) or (not np.all(np.isfinite(observation))):\n print(\"Episode terminated due to NaN loss. Loss: {}, Obs: {}, Lr: {}\".format(loss_after, observation,\n K.get_value(\n self.optimizer.lr)))\n observation[0] = -1\n observation[1] = -1\n reward = np.float32(-10000)\n return observation, reward, True, {}\n # reward = (self.best - loss_after)\n # eps = 1e-8\n # reward = np.float32((1.0 / (eps + loss_after)))\n reward = self.loss_scale(loss_after)\n if self.verbose:\n print(\"LR: {}, Reward: {}, Loss: {}\".format(K.get_value(self.optimizer.lr), reward, loss_after))\n # reward = -loss_after\n assert np.all(np.isfinite(reward))\n if loss_after < self.best:\n self.best = loss_after\n done = self.current_step > self.max_steps\n # print(\"Step: {}\".format(observation))\n info = {}\n if self.evaluate_test:\n info[\"test_loss\"] = self.losses(self.data_test)\n return observation, reward, done, info\n\n def set_evaluate_test(self, evaluate_test):\n self.evaluate_test = evaluate_test\n\n def losses(self, data):\n loss = self.model.evaluate(data[0], data[1], verbose=self.verbose, batch_size=self.batch_size)\n return loss\n\n def _observation(self):\n # eps = 1e-8\n loss_train = self.loss_scale(self.losses(self.data_train))\n loss_val = self.loss_scale(self.losses(self.data_val))\n lr = K.get_value(self.optimizer.lr)\n nllr = -np.log(lr)\n ret = np.array([loss_train, loss_val, nllr, self.current_step])\n # assert np.all(np.isfinite(ret)), \"Lr: {}, Inf: {}\".format(lr, ret)\n return ret\n\n def observation_names(self):\n return [\"loss_train\", \"loss_val\", \"nl_lr\", \"step\"]\n\n def _reset(self):\n self.create_model()\n self.current_step = 0\n self.best = None\n observation = self._observation()\n return observation\n\n def _render(self, mode='human', close=False):\n if close:\n if self.viewer is not None:\n self.viewer.close()\n self.viewer = None\n return\n if mode == 'human':\n print(self._observation())\n elif mode == \"ansi\":\n return \"Observation: {}\\n\".format(self._observation())\n else:\n raise NotImplementedError(\"mode not supported: {}\".format(mode))\n" ]
[ [ "numpy.array", "numpy.log", "numpy.float32", "numpy.isfinite" ] ]
cocolord/SegmenTron
[ "940015dc35614c15bd303f91f611878efbab8796" ]
[ "segmentron/models/danet.py" ]
[ "from __future__ import division\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom .segbase import SegBaseModel\nfrom .model_zoo import MODEL_REGISTRY\nfrom ..modules import _FCNHead, PAM_Module, CAM_Module\n\n__all__ = ['DANet']\n\n\n@MODEL_REGISTRY.register()\nclass DANet(SegBaseModel):\n r\"\"\"DANet model from the paper `\"Dual Attention Network for Scene Segmentation\"\n <https://arxiv.org/abs/1809.02983.pdf>`\n \"\"\"\n def __init__(self):\n super(DANet, self).__init__()\n self.head = DANetHead(2048, self.nclass)\n if self.aux:\n self.auxlayer = _FCNHead(728, self.nclass)\n self.__setattr__('decoder', ['head', 'auxlayer'] if self.aux else ['head'])\n\n def forward(self, x):\n imsize = x.size()[2:]\n _, _, c3, c4 = self.encoder(x)\n\n x = self.head(c4)\n x = list(x)\n x[0] = F.interpolate(x[0], imsize, mode='bilinear', align_corners=True)\n x[1] = F.interpolate(x[1], imsize, mode='bilinear', align_corners=True)\n x[2] = F.interpolate(x[2], imsize, mode='bilinear', align_corners=True)\n\n outputs = list()\n outputs.append(x[0])\n outputs.append(x[1])\n outputs.append(x[2])\n\n return tuple(outputs)\n\n\nclass DANetHead(nn.Module):\n def __init__(self, in_channels, out_channels, norm_layer=nn.BatchNorm2d):\n super(DANetHead, self).__init__()\n inter_channels = in_channels // 4\n self.conv5a = nn.Sequential(nn.Conv2d(in_channels, inter_channels, 3, padding=1, bias=False),\n norm_layer(inter_channels),\n nn.ReLU())\n \n self.conv5c = nn.Sequential(nn.Conv2d(in_channels, inter_channels, 3, padding=1, bias=False),\n norm_layer(inter_channels),\n nn.ReLU())\n\n self.sa = PAM_Module(inter_channels)\n self.sc = CAM_Module(inter_channels)\n self.conv51 = nn.Sequential(nn.Conv2d(inter_channels, inter_channels, 3, padding=1, bias=False),\n norm_layer(inter_channels),\n nn.ReLU())\n self.conv52 = nn.Sequential(nn.Conv2d(inter_channels, inter_channels, 3, padding=1, bias=False),\n norm_layer(inter_channels),\n nn.ReLU())\n\n self.conv6 = nn.Sequential(nn.Dropout2d(0.1, False), nn.Conv2d(512, out_channels, 1))\n self.conv7 = nn.Sequential(nn.Dropout2d(0.1, False), nn.Conv2d(512, out_channels, 1))\n\n self.conv8 = nn.Sequential(nn.Dropout2d(0.1, False), nn.Conv2d(512, out_channels, 1))\n\n def forward(self, x):\n feat1 = self.conv5a(x)\n sa_feat = self.sa(feat1)\n sa_conv = self.conv51(sa_feat)\n sa_output = self.conv6(sa_conv)\n\n feat2 = self.conv5c(x)\n sc_feat = self.sc(feat2)\n sc_conv = self.conv52(sc_feat)\n sc_output = self.conv7(sc_conv)\n\n feat_sum = sa_conv+sc_conv\n \n sasc_output = self.conv8(feat_sum)\n\n output = [sasc_output]\n output.append(sa_output)\n output.append(sc_output)\n return tuple(output)\n\n" ]
[ [ "torch.nn.ReLU", "torch.nn.Conv2d", "torch.nn.Dropout2d", "torch.nn.functional.interpolate" ] ]
thisch/unyt
[ "27894c1edc275205a9ad2e0d9f47d11241e1f5c3" ]
[ "unyt/tests/test_units.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\nTest symbolic unit handling.\n\n\n\n\n\"\"\"\n\n# -----------------------------------------------------------------------------\n# Copyright (c) 2018, yt Development Team.\n#\n# Distributed under the terms of the Modified BSD License.\n#\n# The full license is in the LICENSE file, distributed with this software.\n# -----------------------------------------------------------------------------\n\n\nimport numpy as np\nfrom numpy.testing import (\n assert_almost_equal,\n assert_allclose,\n assert_array_almost_equal_nulp,\n assert_equal,\n)\nimport operator\nimport pickle\nimport pytest\nfrom sympy import Symbol\n\nfrom unyt.testing import assert_allclose_units\nfrom unyt.unit_registry import UnitRegistry\nfrom unyt.dimensions import (\n mass,\n length,\n time,\n temperature,\n energy,\n magnetic_field_cgs,\n magnetic_field_mks,\n power,\n rate,\n)\nfrom unyt.exceptions import InvalidUnitOperation, UnitsNotReducible, UnitConversionError\nfrom unyt.unit_object import default_unit_registry, Unit, UnitParseError\nfrom unyt.unit_systems import cgs_unit_system, UnitSystem\nfrom unyt._unit_lookup_table import (\n default_unit_symbol_lut,\n name_alternatives,\n unit_prefixes,\n)\nimport unyt.unit_symbols as unit_symbols\nfrom unyt._physical_ratios import (\n m_per_pc,\n sec_per_year,\n m_per_km,\n m_per_mpc,\n mass_sun_kg,\n)\n\n\ndef test_no_conflicting_symbols():\n \"\"\"\n Check unit symbol definitions for conflicts.\n\n \"\"\"\n full_set = set(default_unit_symbol_lut.keys())\n\n # go through all possible prefix combos\n for symbol in default_unit_symbol_lut.keys():\n if default_unit_symbol_lut[symbol][4]:\n keys = unit_prefixes.keys()\n else:\n keys = [symbol]\n for prefix in keys:\n new_symbol = \"%s%s\" % (prefix, symbol)\n\n # test if we have seen this symbol\n assert new_symbol not in full_set, \"Duplicate symbol: %s\" % new_symbol\n\n full_set.add(new_symbol)\n\n\ndef test_dimensionless():\n \"\"\"\n Create dimensionless unit and check attributes.\n\n \"\"\"\n u1 = Unit()\n\n assert u1.is_dimensionless\n assert u1.expr == 1\n assert u1.base_value == 1\n assert u1.dimensions == 1\n assert u1 != \"hello!\"\n assert (u1 == \"hello\") is False\n\n u2 = Unit(\"\")\n\n assert u2.is_dimensionless\n assert u2.expr == 1\n assert u2.base_value == 1\n assert u2.dimensions == 1\n\n assert_equal(u1.latex_repr, \"\")\n assert_equal(u2.latex_repr, \"\")\n\n\ndef test_create_from_string():\n \"\"\"\n Create units with strings and check attributes.\n\n \"\"\"\n\n u1 = Unit(\"kg * m**2 * s**-2\")\n assert u1.dimensions == energy\n assert u1.base_value == 1.0\n\n # make sure order doesn't matter\n u2 = Unit(\"m**2 * s**-2 * kg\")\n assert u2.dimensions == energy\n assert u2.base_value == 1.0\n\n # Test rationals\n u3 = Unit(\"kg**0.5 * m**-0.5 * s**-1\")\n assert u3.dimensions == magnetic_field_cgs\n assert u3.base_value == 1.0\n\n # sqrt functions\n u4 = Unit(\"sqrt(kg)/sqrt(m)/s\")\n assert u4.dimensions == magnetic_field_cgs\n assert u4.base_value == 1.0\n\n # commutative sqrt function\n u5 = Unit(\"sqrt(kg/m)/s\")\n assert u5.dimensions == magnetic_field_cgs\n assert u5.base_value == 1.0\n\n # nonzero CGS conversion factor\n u6 = Unit(\"Msun/pc**3\")\n assert u6.dimensions == mass / length ** 3\n assert_array_almost_equal_nulp(\n np.array([u6.base_value]), np.array([mass_sun_kg / m_per_pc ** 3])\n )\n\n with pytest.raises(UnitParseError):\n Unit(\"m**m\")\n with pytest.raises(UnitParseError):\n Unit(\"m**g\")\n with pytest.raises(UnitParseError):\n Unit(\"m+g\")\n with pytest.raises(UnitParseError):\n Unit(\"m-g\")\n with pytest.raises(UnitParseError):\n Unit(\"hello!\")\n with pytest.raises(UnitParseError):\n Unit(\"True\")\n with pytest.raises(UnitParseError):\n Unit(\"else\")\n with pytest.raises(UnitParseError):\n Unit(\"hello(37)\")\n with pytest.raises(UnitParseError):\n Unit(\"hello(foo=37)\")\n\n cm = Unit(\"cm\")\n data = 1 * cm\n\n assert Unit(data) == cm\n assert Unit(b\"cm\") == cm\n\n\ndef test_create_from_expr():\n \"\"\"\n Create units from sympy Exprs and check attributes.\n\n \"\"\"\n pc_mks = m_per_pc\n yr_mks = sec_per_year\n\n # Symbol expr\n s1 = Symbol(\"pc\", positive=True)\n s2 = Symbol(\"yr\", positive=True)\n # Mul expr\n s3 = s1 * s2\n # Pow expr\n s4 = s1 ** 2 * s2 ** (-1)\n\n u1 = Unit(s1)\n u2 = Unit(s2)\n u3 = Unit(s3)\n u4 = Unit(s4)\n\n assert u1.expr == s1\n assert u2.expr == s2\n assert u3.expr == s3\n assert u4.expr == s4\n\n assert_allclose_units(u1.base_value, pc_mks, 1e-12)\n assert_allclose_units(u2.base_value, yr_mks, 1e-12)\n assert_allclose_units(u3.base_value, pc_mks * yr_mks, 1e-12)\n assert_allclose_units(u4.base_value, pc_mks ** 2 / yr_mks, 1e-12)\n\n assert u1.dimensions == length\n assert u2.dimensions == time\n assert u3.dimensions == length * time\n assert u4.dimensions == length ** 2 / time\n\n\ndef test_create_with_duplicate_dimensions():\n \"\"\"\n Create units with overlapping dimensions. Ex: km/Mpc.\n\n \"\"\"\n\n u1 = Unit(\"J * s**-1\")\n u2 = Unit(\"km/s/Mpc\")\n km_mks = m_per_km\n Mpc_mks = m_per_mpc\n\n assert u1.base_value == 1\n assert u1.dimensions == power\n\n assert_allclose_units(u2.base_value, km_mks / Mpc_mks, 1e-12)\n assert u2.dimensions == rate\n\n\ndef test_create_new_symbol():\n \"\"\"\n Create unit with unknown symbol.\n\n \"\"\"\n u1 = Unit(\"abc\", base_value=42, dimensions=(mass / time))\n\n assert u1.expr == Symbol(\"abc\", positive=True)\n assert u1.base_value == 42\n assert u1.dimensions == mass / time\n\n u1 = Unit(\"abc\", base_value=42, dimensions=length ** 3)\n\n assert u1.expr == Symbol(\"abc\", positive=True)\n assert u1.base_value == 42\n assert u1.dimensions == length ** 3\n\n u1 = Unit(\"abc\", base_value=42, dimensions=length * (mass * length))\n\n assert u1.expr == Symbol(\"abc\", positive=True)\n assert u1.base_value == 42\n assert u1.dimensions == length ** 2 * mass\n\n with pytest.raises(UnitParseError):\n Unit(\"abc\", base_value=42, dimensions=length ** length)\n with pytest.raises(UnitParseError):\n Unit(\"abc\", base_value=42, dimensions=length ** (length * length))\n with pytest.raises(UnitParseError):\n Unit(\"abc\", base_value=42, dimensions=length - mass)\n with pytest.raises(UnitParseError):\n Unit(\"abc\", base_value=42, dimensions=length + mass)\n\n\ndef test_create_fail_on_unknown_symbol():\n \"\"\"\n Fail to create unit with unknown symbol, without base_value and dimensions.\n\n \"\"\"\n with pytest.raises(UnitParseError):\n Unit(Symbol(\"jigawatts\"))\n\n\ndef test_create_fail_on_bad_symbol_type():\n \"\"\"\n Fail to create unit with bad symbol type.\n\n \"\"\"\n with pytest.raises(UnitParseError):\n Unit([1]) # something other than Expr and str\n\n\ndef test_create_fail_on_bad_dimensions_type():\n \"\"\"\n Fail to create unit with bad dimensions type.\n\n \"\"\"\n with pytest.raises(UnitParseError):\n Unit(\"a\", base_value=1, dimensions=\"(mass)\")\n\n\ndef test_create_fail_on_dimensions_content():\n \"\"\"\n Fail to create unit with bad dimensions expr.\n\n \"\"\"\n a = Symbol(\"a\")\n with pytest.raises(UnitParseError):\n Unit(\"a\", base_value=1, dimensions=a)\n\n\ndef test_create_fail_on_base_value_type():\n \"\"\"\n Fail to create unit with bad base_value type.\n\n \"\"\"\n with pytest.raises(UnitParseError):\n Unit(\"a\", base_value=\"a\", dimensions=(mass / time))\n\n\ndef test_string_representation():\n \"\"\"\n Check unit string representation.\n\n \"\"\"\n pc = Unit(\"pc\")\n Myr = Unit(\"Myr\")\n speed = pc / Myr\n dimensionless = Unit()\n\n assert str(pc) == \"pc\"\n assert str(Myr) == \"Myr\"\n assert str(speed) == \"pc/Myr\"\n assert repr(speed) == \"pc/Myr\"\n assert str(dimensionless) == \"dimensionless\"\n assert repr(dimensionless) == \"(dimensionless)\"\n\n\ndef test_multiplication():\n \"\"\"\n Multiply two units.\n\n \"\"\"\n msun_mks = mass_sun_kg\n pc_mks = m_per_pc\n\n # Create symbols\n msun_sym = Symbol(\"Msun\", positive=True)\n pc_sym = Symbol(\"pc\", positive=True)\n s_sym = Symbol(\"s\", positive=True)\n\n # Create units\n u1 = Unit(\"Msun\")\n u2 = Unit(\"pc\")\n\n # Mul operation\n u3 = u1 * u2\n\n assert u3.expr == msun_sym * pc_sym\n assert_allclose_units(u3.base_value, msun_mks * pc_mks, 1e-12)\n assert u3.dimensions == mass * length\n\n # Pow and Mul operations\n u4 = Unit(\"pc**2\")\n u5 = Unit(\"Msun * s\")\n\n u6 = u4 * u5\n\n assert u6.expr == pc_sym ** 2 * msun_sym * s_sym\n assert_allclose_units(u6.base_value, pc_mks ** 2 * msun_mks, 1e-12)\n assert u6.dimensions == length ** 2 * mass * time\n\n\ndef test_division():\n \"\"\"\n Divide two units.\n\n \"\"\"\n pc_mks = m_per_pc\n km_mks = m_per_km\n\n # Create symbols\n pc_sym = Symbol(\"pc\", positive=True)\n km_sym = Symbol(\"km\", positive=True)\n s_sym = Symbol(\"s\", positive=True)\n\n # Create units\n u1 = Unit(\"pc\")\n u2 = Unit(\"km * s\")\n\n u3 = u1 / u2\n\n assert u3.expr == pc_sym / (km_sym * s_sym)\n assert_allclose_units(u3.base_value, pc_mks / km_mks, 1e-12)\n assert u3.dimensions == 1 / time\n\n\ndef test_power():\n \"\"\"\n Take units to some power.\n\n \"\"\"\n from sympy import nsimplify\n\n pc_mks = m_per_pc\n mK_mks = 1e-3\n u1_dims = mass * length ** 2 * time ** -3 * temperature ** 4\n u1 = Unit(\"kg * pc**2 * s**-3 * mK**4\")\n\n u2 = u1 ** 2\n\n assert u2.dimensions == u1_dims ** 2\n assert_allclose_units(u2.base_value, (pc_mks ** 2 * mK_mks ** 4) ** 2, 1e-12)\n\n u3 = u1 ** (-1.0 / 3)\n\n assert u3.dimensions == nsimplify(u1_dims ** (-1.0 / 3))\n assert_allclose_units(\n u3.base_value, (pc_mks ** 2 * mK_mks ** 4) ** (-1.0 / 3), 1e-12\n )\n\n\ndef test_equality():\n \"\"\"\n Check unit equality with different symbols, but same dimensions and\n base_value.\n\n \"\"\"\n u1 = Unit(\"km * s**-1\")\n u2 = Unit(\"m * ms**-1\")\n\n assert u1 == u2\n assert u1.copy() == u2\n\n\ndef test_invalid_operations():\n u1 = Unit(\"cm\")\n u2 = Unit(\"m\")\n\n with pytest.raises(InvalidUnitOperation):\n u1 + u2\n with pytest.raises(InvalidUnitOperation):\n u1 += u2\n with pytest.raises(InvalidUnitOperation):\n 1 + u1\n with pytest.raises(InvalidUnitOperation):\n u1 + 1\n with pytest.raises(InvalidUnitOperation):\n u1 - u2\n with pytest.raises(InvalidUnitOperation):\n u1 -= u2\n with pytest.raises(InvalidUnitOperation):\n 1 - u1\n with pytest.raises(InvalidUnitOperation):\n u1 - 1\n with pytest.raises(InvalidUnitOperation):\n u1 *= u2\n with pytest.raises(InvalidUnitOperation):\n u1 * \"hello!\"\n with pytest.raises(InvalidUnitOperation):\n u1 /= u2\n with pytest.raises(InvalidUnitOperation):\n u1 / \"hello!\"\n\n\ndef test_base_equivalent():\n \"\"\"\n Check base equivalent of a unit.\n\n \"\"\"\n Msun_mks = mass_sun_kg\n Mpc_mks = m_per_mpc\n\n u1 = Unit(\"Msun * Mpc**-3\")\n u2 = Unit(\"kg * m**-3\")\n u3 = u1.get_base_equivalent()\n\n assert u2.expr == u3.expr\n assert u2 == u3\n\n assert_allclose_units(u1.base_value, Msun_mks / Mpc_mks ** 3, 1e-12)\n assert u2.base_value == 1\n assert u3.base_value == 1\n\n mass_density = mass / length ** 3\n\n assert u1.dimensions == mass_density\n assert u2.dimensions == mass_density\n assert u3.dimensions == mass_density\n\n assert_allclose_units(\n u1.get_conversion_factor(u3)[0], Msun_mks / Mpc_mks ** 3, 1e-12\n )\n\n with pytest.raises(UnitConversionError):\n u1.get_conversion_factor(Unit(\"m\"))\n\n with pytest.raises(UnitConversionError):\n u1.get_conversion_factor(Unit(\"degF\"))\n\n reg = UnitRegistry(unit_system=cgs_unit_system)\n\n u = Unit(\"kg\", registry=reg)\n\n assert u.get_base_equivalent() == Unit(\"g\")\n\n u = Unit(\"kg\")\n\n assert u.get_base_equivalent() == Unit(\"kg\")\n\n u = Unit(\"A\")\n assert u.get_base_equivalent(unit_system=\"mks\") == Unit(\"A\")\n\n\ndef test_temperature_offsets():\n u1 = Unit(\"degC\")\n u2 = Unit(\"degF\")\n\n with pytest.raises(InvalidUnitOperation):\n operator.mul(u1, u2)\n with pytest.raises(InvalidUnitOperation):\n operator.truediv(u1, u2)\n\n\ndef test_latex_repr():\n registry = UnitRegistry()\n\n # create a fake comoving unit\n registry.add(\n \"pccm\",\n registry.lut[\"pc\"][0] / (1 + 2),\n length,\n \"\\\\rm{pc}/(1+z)\",\n prefixable=True,\n )\n\n test_unit = Unit(\"Mpccm\", registry=registry)\n assert_almost_equal(test_unit.base_value, m_per_mpc / 3)\n assert_equal(test_unit.latex_repr, r\"\\rm{Mpc}/(1+z)\")\n\n test_unit = Unit(\"cm**-3\", base_value=1.0, registry=registry)\n assert_equal(test_unit.latex_repr, \"\\\\frac{1}{\\\\rm{cm}^{3}}\")\n\n test_unit = Unit(\"m_geom/l_geom**3\")\n assert_equal(test_unit.latex_repr, \"\\\\frac{1}{M_\\\\odot^{2}}\")\n\n test_unit = Unit(\"1e9*cm\")\n assert_equal(test_unit.latex_repr, \"1.0 \\\\times 10^{9}\\\\ \\\\rm{cm}\")\n\n test_unit = Unit(\"1.0*cm\")\n assert_equal(test_unit.latex_repr, \"\\\\rm{cm}\")\n\n\ndef test_latitude_longitude():\n lat = unit_symbols.lat\n lon = unit_symbols.lon\n deg = unit_symbols.deg\n assert_equal(lat.units.base_offset, 90.0)\n assert_equal((deg * 90.0).in_units(\"lat\").value, 0.0)\n assert_equal((deg * 180).in_units(\"lat\").value, -90.0)\n assert_equal((lat * 0.0).in_units(\"deg\"), deg * 90.0)\n assert_equal((lat * -90).in_units(\"deg\"), deg * 180)\n\n assert_equal(lon.units.base_offset, -180.0)\n assert_equal((deg * 0.0).in_units(\"lon\").value, -180.0)\n assert_equal((deg * 90.0).in_units(\"lon\").value, -90.0)\n assert_equal((deg * 180).in_units(\"lon\").value, 0.0)\n assert_equal((deg * 360).in_units(\"lon\").value, 180.0)\n\n assert_equal((lon * -180.0).in_units(\"deg\"), deg * 0.0)\n assert_equal((lon * -90.0).in_units(\"deg\"), deg * 90.0)\n assert_equal((lon * 0.0).in_units(\"deg\"), deg * 180.0)\n assert_equal((lon * 180.0).in_units(\"deg\"), deg * 360)\n\n\ndef test_creation_from_ytarray():\n from unyt import electrostatic_unit, elementary_charge_cgs\n\n u1 = Unit(electrostatic_unit)\n assert_equal(str(u1), \"statC\")\n assert_equal(u1, Unit(\"esu\"))\n assert_equal(u1, electrostatic_unit.units)\n\n u2 = Unit(elementary_charge_cgs)\n assert_equal(str(u2), \"4.80320467299766e-10*statC\")\n assert_equal(u2, Unit(\"4.80320467299766e-10*statC\"))\n assert_equal(u1, elementary_charge_cgs.units)\n\n assert_allclose((u1 / u2).base_value, electrostatic_unit / elementary_charge_cgs)\n\n with pytest.raises(UnitParseError):\n Unit([1, 2, 3] * elementary_charge_cgs)\n\n\ndef test_list_same_dimensions():\n from unyt import m\n\n reg = default_unit_registry\n for equiv in reg.list_same_dimensions(m):\n assert Unit(equiv).dimensions is length\n\n\ndef test_decagram():\n dag = Unit(\"dag\")\n g = Unit(\"g\")\n assert dag.get_conversion_factor(g) == (10.0, None)\n\n\ndef test_pickle():\n cm = Unit(\"cm\")\n assert cm == pickle.loads(pickle.dumps(cm))\n\n\ndef test_preserve_offset():\n from unyt import degF, dimensionless\n\n new_unit = degF * dimensionless\n\n assert new_unit is not degF\n assert new_unit == degF\n assert new_unit.base_offset == degF.base_offset\n\n new_unit = degF / dimensionless\n\n assert new_unit is not degF\n assert new_unit == degF\n assert new_unit.base_offset == degF.base_offset\n\n with pytest.raises(InvalidUnitOperation):\n dimensionless / degF\n\n\ndef test_code_unit():\n from unyt import UnitRegistry\n\n ureg = UnitRegistry()\n ureg.add(\"code_length\", 10.0, length)\n ureg.add(\"code_magnetic_field\", 2.0, magnetic_field_mks)\n u = Unit(\"code_length\", registry=ureg)\n assert u.is_code_unit is True\n assert u.get_base_equivalent() == Unit(\"m\")\n u = Unit(\"cm\")\n assert u.is_code_unit is False\n\n u = Unit(\"code_magnetic_field\", registry=ureg)\n assert u.get_base_equivalent(\"mks\") == Unit(\"T\")\n with pytest.raises(UnitsNotReducible):\n assert u.get_base_equivalent(\"cgs\")\n\n # see issue #60\n u = Unit(\"s/m\")\n assert u.get_mks_equivalent() == Unit(\"s/m\")\n assert u.get_mks_equivalent() != Unit(\"ohm\")\n assert u.get_cgs_equivalent() == Unit(\"s/cm\")\n\n u = Unit(\"kC\")\n assert u.get_cgs_equivalent() == Unit(\"kesu\")\n assert u.get_cgs_equivalent().get_mks_equivalent() == u\n\n UnitSystem(ureg.unit_system_id, \"code_length\", \"kg\", \"s\", registry=ureg)\n\n u = Unit(\"cm\", registry=ureg)\n ue = u.get_base_equivalent(\"code\")\n\n assert str(ue) == \"code_length\"\n assert ue.base_value == 10\n assert ue.dimensions is length\n\n class FakeDataset(object):\n unit_registry = ureg\n\n ds = FakeDataset()\n\n UnitSystem(ds, \"code_length\", \"kg\", \"s\", registry=ureg)\n\n u = Unit(\"cm\", registry=ureg)\n ue = u.get_base_equivalent(ds)\n\n assert str(ue) == \"code_length\"\n assert ue.base_value == 10\n assert ue.dimensions is length\n\n with pytest.raises(UnitParseError):\n Unit(\"code_length\")\n\n\ndef test_bad_equivalence():\n from unyt import cm\n\n with pytest.raises(KeyError):\n cm.has_equivalent(\"dne\")\n\n\ndef test_em_unit_base_equivalent():\n from unyt import A, cm\n\n with pytest.raises(UnitsNotReducible):\n (A / cm).get_base_equivalent(\"cgs\")\n\n\ndef test_symbol_lut_length():\n for v in default_unit_symbol_lut.values():\n assert len(v) == 5\n\n\ndef test_simplify():\n import unyt as u\n\n answers = {\n u.Hz * u.s: \"dimensionless\",\n u.kg / u.g: \"1000\",\n u.Hz * u.s * u.km: \"km\",\n u.kHz * u.s: \"1000\",\n u.kHz * u.s * u.km: \"1000*km\",\n u.kHz * u.s ** 2: \"1000*s\",\n u.kHz * u.s ** 2 * u.km: \"1000*km*s\",\n u.Hz ** -1 * u.s: \"s/Hz\",\n u.Hz ** -1 * u.s * u.km: \"km*s/Hz\",\n u.Hz ** 1.5 * u.s ** 1.7: \"sqrt(Hz)*s**(7/10)\",\n u.Hz ** 1.5 * u.s ** 1.7 * u.km: \"sqrt(Hz)*km*s**(7/10)\",\n u.m ** 2 / u.cm ** 2: \"10000\",\n }\n\n for unit, answer in answers.items():\n assert str(unit.simplify()) == answer\n\n\ndef test_micro_prefix():\n import unyt as u\n\n # both versions of unicode mu work correctly\n assert u.um == u.µm\n assert u.um == u.μm\n\n # parsing both versions works as well\n assert u.ug == u.Unit(\"µg\")\n assert u.ug == u.Unit(\"μg\")\n\n\ndef test_name_alternatives():\n import unyt\n from unyt._unit_lookup_table import (\n default_unit_name_alternatives,\n name_alternatives,\n inv_name_alternatives,\n )\n\n # concatenated list of all alternative unit names\n allowed_names = sum(name_alternatives.values(), [])\n\n # ensure the values are all tuples and not e.g. strings\n for val in default_unit_name_alternatives.values():\n assert isinstance(val, tuple)\n\n # all names are unique\n assert len(set(allowed_names)) == len(allowed_names)\n # each allowed name has a key in the inverse dict\n assert len(inv_name_alternatives.keys()) == len(allowed_names)\n assert set(inv_name_alternatives.keys()) == set(allowed_names)\n\n for name in allowed_names:\n assert hasattr(unyt, name)\n assert hasattr(unyt.unit_symbols, name)\n\n\ndef test_attosecond():\n from unyt import Unit, attosecond, second\n\n assert Unit(\"as\") == attosecond\n assert str(Unit(\"as\")) == \"as\"\n assert Unit(\"as/s\") == attosecond / second\n\n\ndef test_micro():\n from unyt import Unit\n\n assert str(Unit(\"um\")) == \"µm\"\n assert str(Unit(\"us\")) == \"µs\"\n\n\ndef test_show_all_units_doc_table_ops():\n for name in set(name_alternatives.keys()):\n u = Unit(name)\n (1 * u).in_mks()\n try:\n (1 * u).in_cgs()\n except UnitsNotReducible:\n pass\n" ]
[ [ "numpy.testing.assert_equal", "numpy.array", "numpy.testing.assert_almost_equal", "numpy.testing.assert_allclose" ] ]
pierrick-giffard/parcels
[ "2447d4785b915e17f59f6c1f90703a35d2235c91" ]
[ "tests/test_kernel_language.py" ]
[ "from parcels import FieldSet, ParticleSet, ScipyParticle, JITParticle, Kernel, Variable, ErrorCode\nfrom parcels.kernels.seawaterdensity import polyTEOS10_bsq, UNESCO_Density\nfrom parcels import random as parcels_random\nimport numpy as np\nimport pytest\nimport random as py_random\nfrom os import path\nimport sys\n\n\nptype = {'scipy': ScipyParticle, 'jit': JITParticle}\n\n\ndef expr_kernel(name, pset, expr):\n pycode = \"\"\"def %s(particle, fieldset, time):\n particle.p = %s\"\"\" % (name, expr)\n return Kernel(pset.fieldset, pset.ptype, pyfunc=None,\n funccode=pycode, funcname=name,\n funcvars=['particle'])\n\n\ndef fieldset(xdim=20, ydim=20):\n \"\"\" Standard unit mesh fieldset \"\"\"\n lon = np.linspace(0., 1., xdim, dtype=np.float32)\n lat = np.linspace(0., 1., ydim, dtype=np.float32)\n U, V = np.meshgrid(lat, lon)\n data = {'U': np.array(U, dtype=np.float32), 'V': np.array(V, dtype=np.float32)}\n dimensions = {'lat': lat, 'lon': lon}\n return FieldSet.from_data(data, dimensions, mesh='flat', transpose=True)\n\n\[email protected](name=\"fieldset\")\ndef fieldset_fixture(xdim=20, ydim=20):\n return fieldset(xdim=xdim, ydim=ydim)\n\n\[email protected]('mode', ['scipy', 'jit'])\[email protected]('name, expr, result', [\n ('Add', '2 + 5', 7),\n ('Sub', '6 - 2', 4),\n ('Mul', '3 * 5', 15),\n ('Div', '24 / 4', 6),\n])\ndef test_expression_int(fieldset, mode, name, expr, result, npart=10):\n \"\"\" Test basic arithmetic expressions \"\"\"\n class TestParticle(ptype[mode]):\n p = Variable('p', dtype=np.float32)\n pset = ParticleSet(fieldset, pclass=TestParticle,\n lon=np.linspace(0., 1., npart),\n lat=np.zeros(npart) + 0.5)\n pset.execute(expr_kernel('Test%s' % name, pset, expr), endtime=1., dt=1.)\n assert(np.all(result == pset.p))\n\n\[email protected]('mode', ['scipy', 'jit'])\[email protected]('name, expr, result', [\n ('Add', '2. + 5.', 7),\n ('Sub', '6. - 2.', 4),\n ('Mul', '3. * 5.', 15),\n ('Div', '24. / 4.', 6),\n ('Pow', '2 ** 3', 8),\n])\ndef test_expression_float(fieldset, mode, name, expr, result, npart=10):\n \"\"\" Test basic arithmetic expressions \"\"\"\n class TestParticle(ptype[mode]):\n p = Variable('p', dtype=np.float32)\n pset = ParticleSet(fieldset, pclass=TestParticle,\n lon=np.linspace(0., 1., npart),\n lat=np.zeros(npart) + 0.5)\n pset.execute(expr_kernel('Test%s' % name, pset, expr), endtime=1., dt=1.)\n assert(np.all(result == pset.p))\n\n\[email protected]('mode', ['scipy', 'jit'])\[email protected]('name, expr, result', [\n ('True', 'True', True),\n ('False', 'False', False),\n ('And', 'True and False', False),\n ('Or', 'True or False', True),\n ('Equal', '5 == 5', True),\n ('Lesser', '5 < 3', False),\n ('LesserEq', '3 <= 5', True),\n ('Greater', '4 > 2', True),\n ('GreaterEq', '2 >= 4', False),\n])\ndef test_expression_bool(fieldset, mode, name, expr, result, npart=10):\n \"\"\" Test basic arithmetic expressions \"\"\"\n class TestParticle(ptype[mode]):\n p = Variable('p', dtype=np.float32)\n pset = ParticleSet(fieldset, pclass=TestParticle,\n lon=np.linspace(0., 1., npart),\n lat=np.zeros(npart) + 0.5)\n pset.execute(expr_kernel('Test%s' % name, pset, expr), endtime=1., dt=1.)\n if mode == 'jit':\n assert(np.all(result == (pset.p == 1)))\n else:\n assert(np.all(result == pset.p))\n\n\[email protected]('mode', ['scipy', 'jit'])\ndef test_while_if_break(fieldset, mode):\n \"\"\"Test while, if and break commands\"\"\"\n class TestParticle(ptype[mode]):\n p = Variable('p', dtype=np.float32, initial=0.)\n pset = ParticleSet(fieldset, pclass=TestParticle, lon=[0], lat=[0])\n\n def kernel(particle, fieldset, time):\n while particle.p < 30:\n if particle.p > 9:\n break\n particle.p += 1\n if particle.p > 5:\n particle.p *= 2.\n pset.execute(kernel, endtime=1., dt=1.)\n assert np.allclose(pset.p, 20., rtol=1e-12)\n\n\[email protected]('mode', ['scipy', 'jit'])\ndef test_nested_if(fieldset, mode):\n \"\"\"Test nested if commands\"\"\"\n class TestParticle(ptype[mode]):\n p0 = Variable('p0', dtype=np.int32, initial=0)\n p1 = Variable('p1', dtype=np.int32, initial=1)\n pset = ParticleSet(fieldset, pclass=TestParticle, lon=0, lat=0)\n\n def kernel(particle, fieldset, time):\n if particle.p1 >= particle.p0:\n var = particle.p0\n if var + 1 < particle.p1:\n particle.p1 = -1\n\n pset.execute(kernel, endtime=10, dt=1.)\n assert np.allclose([pset.p0[0], pset.p1[0]], [0, 1])\n\n\[email protected]('mode', ['scipy', 'jit'])\ndef test_pass(fieldset, mode):\n \"\"\"Test pass commands\"\"\"\n class TestParticle(ptype[mode]):\n p = Variable('p', dtype=np.int32, initial=0)\n pset = ParticleSet(fieldset, pclass=TestParticle, lon=0, lat=0)\n\n def kernel(particle, fieldset, time):\n particle.p = -1\n pass\n\n pset.execute(kernel, endtime=10, dt=1.)\n assert np.allclose(pset[0].p, -1)\n\n\[email protected]('mode', ['scipy', 'jit'])\ndef test_dt_as_variable_in_kernel(fieldset, mode):\n pset = ParticleSet(fieldset, pclass=ptype[mode], lon=0, lat=0)\n\n def kernel(particle, fieldset, time):\n dt = 1. # noqa\n\n pset.execute(kernel, endtime=10, dt=1.)\n\n\ndef test_parcels_tmpvar_in_kernel(fieldset):\n \"\"\"Tests for error thrown if vartiable with 'tmp' defined in custom kernel\"\"\"\n error_thrown = False\n pset = ParticleSet(fieldset, pclass=JITParticle, lon=0, lat=0)\n\n def kernel_tmpvar(particle, fieldset, time):\n parcels_tmpvar0 = 0 # noqa\n\n try:\n pset.execute(kernel_tmpvar, endtime=1, dt=1.)\n except NotImplementedError:\n error_thrown = True\n assert error_thrown\n\n\[email protected]('mode', ['scipy', 'jit'])\ndef test_if_withfield(fieldset, mode):\n \"\"\"Test combination of if and Field sampling commands\"\"\"\n class TestParticle(ptype[mode]):\n p = Variable('p', dtype=np.float32, initial=0.)\n pset = ParticleSet(fieldset, pclass=TestParticle, lon=[0], lat=[0])\n\n def kernel(particle, fieldset, time):\n u = fieldset.U[time, 0, 0, 1.]\n particle.p = 0\n if fieldset.U[time, 0, 0, 1.] == u:\n particle.p += 1\n if fieldset.U[time, 0, 0, 1.] == fieldset.U[time, 0, 0, 1.]:\n particle.p += 1\n if True:\n particle.p += 1\n if fieldset.U[time, 0, 0, 1.] == u and 1 == 1:\n particle.p += 1\n if fieldset.U[time, 0, 0, 1.] == fieldset.U[time, 0, 0, 1.] and fieldset.U[time, 0, 0, 1.] == fieldset.U[time, 0, 0, 1.]:\n particle.p += 1\n if fieldset.U[time, 0, 0, 1.] == u:\n particle.p += 1\n else:\n particle.p += 1000\n if fieldset.U[time, 0, 0, 1.] == 3:\n particle.p += 1000\n else:\n particle.p += 1\n\n pset.execute(kernel, endtime=1., dt=1.)\n assert np.allclose(pset.p, 7., rtol=1e-12)\n\n\[email protected](\n 'mode',\n ['scipy',\n pytest.param('jit',\n marks=pytest.mark.xfail(\n (sys.version_info >= (3, 0)) or (sys.platform == 'win32'),\n reason=\"py.test FD capturing does not work for jit on python3 or Win\"))\n ])\ndef test_print(fieldset, mode, capfd):\n \"\"\"Test print statements\"\"\"\n class TestParticle(ptype[mode]):\n p = Variable('p', dtype=np.float32, initial=0.)\n pset = ParticleSet(fieldset, pclass=TestParticle, lon=[0.5], lat=[0.5])\n\n def kernel(particle, fieldset, time):\n particle.p = fieldset.U[time, particle.depth, particle.lat, particle.lon]\n tmp = 5\n print(\"%d %f %f\" % (particle.id, particle.p, tmp))\n pset.execute(kernel, endtime=1., dt=1.)\n out, err = capfd.readouterr()\n lst = out.split(' ')\n tol = 1e-8\n assert abs(float(lst[0]) - pset.id[0]) < tol and abs(float(lst[1]) - pset.p[0]) < tol and abs(float(lst[2]) - 5) < tol\n\n def kernel2(particle, fieldset, time):\n tmp = 3\n print(\"%f\" % (tmp))\n pset.execute(kernel2, endtime=1., dt=1.)\n out, err = capfd.readouterr()\n lst = out.split(' ')\n assert abs(float(lst[0]) - 3) < tol\n\n\ndef random_series(npart, rngfunc, rngargs, mode):\n random = parcels_random if mode == 'jit' else py_random\n random.seed(1234)\n func = getattr(random, rngfunc)\n series = [func(*rngargs) for _ in range(npart)]\n random.seed(1234) # Reset the RNG seed\n return series\n\n\[email protected]('mode', ['scipy', 'jit'])\[email protected]('rngfunc, rngargs', [\n ('random', []),\n ('uniform', [0., 20.]),\n ('randint', [0, 20]),\n])\ndef test_random_float(fieldset, mode, rngfunc, rngargs, npart=10):\n \"\"\" Test basic random number generation \"\"\"\n class TestParticle(ptype[mode]):\n p = Variable('p', dtype=np.float32 if rngfunc == 'randint' else np.float32)\n pset = ParticleSet(fieldset, pclass=TestParticle,\n lon=np.linspace(0., 1., npart),\n lat=np.zeros(npart) + 0.5)\n series = random_series(npart, rngfunc, rngargs, mode)\n kernel = expr_kernel('TestRandom_%s' % rngfunc, pset,\n 'random.%s(%s)' % (rngfunc, ', '.join([str(a) for a in rngargs])))\n pset.execute(kernel, endtime=1., dt=1.)\n assert np.allclose(pset.p, series, atol=1e-9)\n\n\[email protected]('mode', ['scipy', 'jit'])\[email protected]('c_inc', ['str', 'file'])\ndef test_c_kernel(fieldset, mode, c_inc):\n coord_type = np.float32 if c_inc == 'str' else np.float64\n pset = ParticleSet(fieldset, pclass=ptype[mode], lon=[0.5], lat=[0],\n lonlatdepth_dtype=coord_type)\n\n def func(U, lon, dt):\n u = U.data[0, 2, 1]\n return lon + u * dt\n\n if c_inc == 'str':\n c_include = \"\"\"\n static inline ErrorCode func(CField *f, float *lon, double *dt)\n {\n float data2D[2][2][2];\n ErrorCode err = getCell2D(f, 1, 2, 0, data2D, 1); CHECKERROR(err);\n float u = data2D[0][0][0];\n *lon += u * *dt;\n return SUCCESS;\n }\n \"\"\"\n else:\n c_include = path.join(path.dirname(__file__), 'customed_header.h')\n\n def ckernel(particle, fieldset, time):\n func('parcels_customed_Cfunc_pointer_args', fieldset.U, particle.lon, particle.dt)\n\n def pykernel(particle, fieldset, time):\n particle.lon = func(fieldset.U, particle.lon, particle.dt)\n\n if mode == 'scipy':\n kernel = pset.Kernel(pykernel)\n else:\n kernel = pset.Kernel(ckernel, c_include=c_include)\n pset.execute(kernel, endtime=3., dt=3.)\n assert np.allclose(pset.lon[0], 0.81578948)\n\n\[email protected]('mode', ['scipy', 'jit'])\ndef test_dt_modif_by_kernel(fieldset, mode):\n class TestParticle(ptype[mode]):\n age = Variable('age', dtype=np.float32)\n pset = ParticleSet(fieldset, pclass=TestParticle, lon=[0.5], lat=[0])\n\n def modif_dt(particle, fieldset, time):\n particle.age += particle.dt\n particle.dt = 2\n\n endtime = 4\n pset.execute(modif_dt, endtime=endtime, dt=1.)\n assert np.isclose(pset.age[0], endtime)\n\n\[email protected]('mode', ['scipy', 'jit'])\[email protected]('dt', [1e-2, 1e-6])\ndef test_small_dt(fieldset, mode, dt, npart=10):\n pset = ParticleSet(fieldset, pclass=ptype[mode], lon=np.zeros(npart),\n lat=np.zeros(npart), time=np.arange(0, npart)*dt*10)\n\n def DoNothing(particle, fieldset, time):\n return ErrorCode.Success\n\n pset.execute(DoNothing, dt=dt, runtime=dt*100)\n assert np.allclose([p.time for p in pset], dt*100)\n\n\[email protected]('mode', ['scipy', 'jit'])\ndef test_seawaterdensity_kernels(mode):\n\n def generate_fieldset(xdim=2, ydim=2, zdim=2, tdim=1):\n lon = np.linspace(0., 10., xdim, dtype=np.float32)\n lat = np.linspace(0., 10., ydim, dtype=np.float32)\n depth = np.linspace(0, 2000, zdim, dtype=np.float32)\n time = np.zeros(tdim, dtype=np.float64)\n U = np.ones((tdim, zdim, ydim, xdim))\n V = np.ones((tdim, zdim, ydim, xdim))\n abs_salinity = 30 * np.ones((tdim, zdim, ydim, xdim))\n cons_temperature = 10 * np.ones((tdim, zdim, ydim, xdim))\n dimensions = {'lat': lat, 'lon': lon, 'depth': depth, 'time': time}\n data = {'U': np.array(U, dtype=np.float32), 'V': np.array(V, dtype=np.float32),\n 'abs_salinity': np.array(abs_salinity, dtype=np.float32),\n 'cons_temperature': np.array(cons_temperature, dtype=np.float32)}\n return (data, dimensions)\n\n data, dimensions = generate_fieldset()\n fieldset = FieldSet.from_data(data, dimensions)\n\n class DensParticle(ptype[mode]):\n density = Variable('density', dtype=np.float32)\n\n pset = ParticleSet(fieldset, pclass=DensParticle, lon=5, lat=5, depth=1000)\n\n pset.execute(polyTEOS10_bsq, runtime=0, dt=0)\n assert np.allclose(pset[0].density, 1022.85377)\n\n\[email protected]('mode', ['scipy', 'jit'])\[email protected]('pressure', [0, 10])\ndef test_UNESCOdensity_kernel(mode, pressure):\n\n def generate_fieldset(p, xdim=2, ydim=2, zdim=2, tdim=1):\n lon = np.linspace(0., 10., xdim, dtype=np.float32)\n lat = np.linspace(0., 10., ydim, dtype=np.float32)\n depth = np.linspace(0, 2000, zdim, dtype=np.float32)\n time = np.zeros(tdim, dtype=np.float64)\n U = np.ones((tdim, zdim, ydim, xdim))\n V = np.ones((tdim, zdim, ydim, xdim))\n psu_salinity = 8 * np.ones((tdim, zdim, ydim, xdim))\n cons_temperature = 10 * np.ones((tdim, zdim, ydim, xdim))\n cons_pressure = p * np.ones((tdim, zdim, ydim, xdim))\n dimensions = {'lat': lat, 'lon': lon, 'depth': depth, 'time': time}\n data = {'U': np.array(U, dtype=np.float32), 'V': np.array(V, dtype=np.float32),\n 'psu_salinity': np.array(psu_salinity, dtype=np.float32),\n 'cons_pressure': np.array(cons_pressure, dtype=np.float32),\n 'cons_temperature': np.array(cons_temperature, dtype=np.float32)}\n return (data, dimensions)\n\n data, dimensions = generate_fieldset(pressure)\n fieldset = FieldSet.from_data(data, dimensions)\n\n class DensParticle(ptype[mode]):\n density = Variable('density', dtype=np.float32)\n\n pset = ParticleSet(fieldset, pclass=DensParticle, lon=5, lat=5, depth=1000)\n\n pset.execute(UNESCO_Density, runtime=0, dt=0)\n\n if(pressure == 0):\n assert np.allclose(pset[0].density, 1005.9465)\n elif(pressure == 10):\n assert np.allclose(pset[0].density, 1006.4179)\n" ]
[ [ "numpy.allclose", "numpy.ones", "numpy.zeros", "numpy.isclose", "numpy.arange", "numpy.all", "numpy.array", "numpy.meshgrid", "numpy.linspace" ] ]
PudPawat/protest-detection-violence-estimation
[ "6469c3ae47a7d99308458174fe16bd2c5c7821aa" ]
[ "resnext_wsl.py" ]
[ "\n# Copyright (c) Facebook, Inc. and its affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n\n# Optional list of dependencies required by the package\n\n'''\n Code From : https://github.com/facebookresearch/WSL-Images/blob/master/hubconf.py\n'''\ndependencies = ['torch', 'torchvision']\n\ntry:\n from torch.hub import load_state_dict_from_url\nexcept ImportError:\n from torch.utils.model_zoo import load_url as load_state_dict_from_url\n \nfrom Res import ResNet, Bottleneck\n\n\nmodel_urls = {\n 'resnext101_32x8d': 'https://download.pytorch.org/models/ig_resnext101_32x8-c38310e5.pth',\n 'resnext101_32x16d': 'https://download.pytorch.org/models/ig_resnext101_32x16-c6f796b0.pth',\n 'resnext101_32x32d': 'https://download.pytorch.org/models/ig_resnext101_32x32-e4b90b00.pth',\n 'resnext101_32x48d': 'https://download.pytorch.org/models/ig_resnext101_32x48-3e41cc8a.pth',\n}\n\n\ndef _resnext(arch, block, layers, pretrained, progress, **kwargs):\n model = ResNet(block, layers, **kwargs)\n state_dict = load_state_dict_from_url(model_urls[arch], progress=progress)\n model.load_state_dict(state_dict)\n return model\n\n\ndef resnext101_32x8d_wsl(progress=True, **kwargs):\n \"\"\"Constructs a ResNeXt-101 32x8 model pre-trained on weakly-supervised data\n and finetuned on ImageNet from Figure 5 in\n `\"Exploring the Limits of Weakly Supervised Pretraining\" <https://arxiv.org/abs/1805.00932>`_\n Args:\n progress (bool): If True, displays a progress bar of the download to stderr.\n \"\"\"\n kwargs['groups'] = 32\n kwargs['width_per_group'] = 8\n return _resnext('resnext101_32x8d', Bottleneck, [3, 4, 23, 3], True, progress, **kwargs)\n\n\ndef resnext101_32x16d_wsl(progress=True, **kwargs):\n \"\"\"Constructs a ResNeXt-101 32x16 model pre-trained on weakly-supervised data\n and finetuned on ImageNet from Figure 5 in\n `\"Exploring the Limits of Weakly Supervised Pretraining\" <https://arxiv.org/abs/1805.00932>`_\n Args:\n progress (bool): If True, displays a progress bar of the download to stderr.\n \"\"\"\n kwargs['groups'] = 32\n kwargs['width_per_group'] = 16\n return _resnext('resnext101_32x16d', Bottleneck, [3, 4, 23, 3], True, progress, **kwargs)\n\n\ndef resnext101_32x32d_wsl(progress=True, **kwargs):\n \"\"\"Constructs a ResNeXt-101 32x32 model pre-trained on weakly-supervised data\n and finetuned on ImageNet from Figure 5 in\n `\"Exploring the Limits of Weakly Supervised Pretraining\" <https://arxiv.org/abs/1805.00932>`_\n Args:\n progress (bool): If True, displays a progress bar of the download to stderr.\n \"\"\"\n kwargs['groups'] = 32\n kwargs['width_per_group'] = 32\n return _resnext('resnext101_32x32d', Bottleneck, [3, 4, 23, 3], True, progress, **kwargs)\n\n\ndef resnext101_32x48d_wsl(progress=True, **kwargs):\n \"\"\"Constructs a ResNeXt-101 32x48 model pre-trained on weakly-supervised data\n and finetuned on ImageNet from Figure 5 in\n `\"Exploring the Limits of Weakly Supervised Pretraining\" <https://arxiv.org/abs/1805.00932>`_\n Args:\n progress (bool): If True, displays a progress bar of the download to stderr.\n \"\"\"\n kwargs['groups'] = 32\n kwargs['width_per_group'] = 48\n return _resnext('resnext101_32x48d', Bottleneck, [3, 4, 23, 3], True, progress, **kwargs)\n" ]
[ [ "torch.utils.model_zoo.load_url" ] ]
spetrescu/sesn
[ "43ecc5da7083364eea2c66742c17231c18465973" ]
[ "models/mnist_ses.py" ]
[ "'''MIT License. Copyright (c) 2020 Ivan Sosnovik, Michał Szmaja'''\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom .impl.ses_conv import SESMaxProjection\nfrom .impl.ses_conv import SESConv_Z2_H, SESConv_H_H\n\n\nclass MNIST_SES_Scalar(nn.Module):\n\n def __init__(self, pool_size=4, kernel_size=11, scales=[1.0], basis_type='A', **kwargs):\n super().__init__()\n C1, C2, C3 = 32, 63, 95\n self.main = nn.Sequential(\n SESConv_Z2_H(1, C1, kernel_size, 7, scales=scales,\n padding=kernel_size // 2, bias=True,\n basis_type=basis_type, **kwargs),\n SESMaxProjection(),\n nn.ReLU(True),\n nn.MaxPool2d(2),\n nn.BatchNorm2d(C1),\n\n SESConv_Z2_H(C1, C2, kernel_size, 7, scales=scales,\n padding=kernel_size // 2, bias=True,\n basis_type=basis_type, **kwargs),\n SESMaxProjection(),\n nn.ReLU(True),\n nn.MaxPool2d(2),\n nn.BatchNorm2d(C2),\n\n SESConv_Z2_H(C2, C3, kernel_size, 7, scales=scales,\n padding=kernel_size // 2, bias=True,\n basis_type=basis_type, **kwargs),\n SESMaxProjection(),\n nn.ReLU(True),\n nn.MaxPool2d(pool_size, padding=2),\n nn.BatchNorm2d(C3),\n )\n\n self.linear = nn.Sequential(\n nn.Linear(4 * C3, 256, bias=False),\n nn.BatchNorm1d(256),\n nn.ReLU(True),\n nn.Dropout(kwargs.get('dropout', 0.7)),\n nn.Linear(256, 10)\n )\n\n def forward(self, x):\n x = self.main(x)\n x = x.view(x.size(0), -1)\n x = self.linear(x)\n return x\n\n\nclass MNIST_SES_V(nn.Module):\n\n def __init__(self, pool_size=4, kernel_size=11, scales=[1.0], basis_type='A', dropout=0.7, **kwargs):\n super().__init__()\n C1, C2, C3 = 32, 63, 95\n self.main = nn.Sequential(\n SESConv_Z2_H(1, C1, kernel_size, 7, scales=scales,\n padding=kernel_size // 2, bias=True,\n basis_type=basis_type, **kwargs),\n nn.ReLU(True),\n nn.MaxPool3d([1, 2, 2], stride=[1, 2, 2]),\n nn.BatchNorm3d(C1),\n\n SESConv_H_H(C1, C2, 1, kernel_size, 7, scales=scales,\n padding=kernel_size // 2, bias=True,\n basis_type=basis_type, **kwargs),\n nn.ReLU(True),\n nn.MaxPool3d([1, 2, 2], stride=[1, 2, 2]),\n nn.BatchNorm3d(C2),\n\n SESConv_H_H(C2, C3, 1, kernel_size, 7, scales=scales,\n padding=kernel_size // 2, bias=True,\n basis_type=basis_type, **kwargs),\n SESMaxProjection(),\n nn.ReLU(True),\n nn.MaxPool2d(pool_size, padding=2),\n nn.BatchNorm2d(C3),\n )\n\n self.linear = nn.Sequential(\n nn.Linear(4 * C3, 256, bias=False),\n nn.BatchNorm1d(256),\n nn.ReLU(True),\n nn.Dropout(dropout),\n nn.Linear(256, 10)\n )\n\n def forward(self, x):\n x = self.main(x)\n x = x.view(x.size(0), -1)\n x = self.linear(x)\n return x\n\n\ndef mnist_ses_vector_56p(**kwargs):\n num_scales = 4\n factor = 2.0\n min_scale = 1.5\n mult = 1.4\n size = 13\n dropout = 0.7\n q = factor ** (1 / (num_scales - 1))\n scales = [min_scale * q**i for i in range(num_scales)]\n scales = [round(s, 2) for s in scales]\n model = MNIST_SES_V(pool_size=8, kernel_size=size, scales=scales,\n basis_type='B', mult=mult, max_order=4, dropout=dropout)\n return nn.Sequential(nn.Upsample(scale_factor=2), model)\n\n\ndef mnist_ses_vector_56(**kwargs):\n num_scales = 4\n factor = 2.0\n min_scale = 2.0\n mult = 1.5\n size = 15\n dropout = 0.7\n q = factor ** (1 / (num_scales - 1))\n scales = [min_scale * q**i for i in range(num_scales)]\n scales = [round(s, 2) for s in scales]\n model = MNIST_SES_V(pool_size=8, kernel_size=size, scales=scales,\n basis_type='B', mult=mult, max_order=4, dropout=dropout)\n return nn.Sequential(nn.Upsample(scale_factor=2), model)\n\n\ndef mnist_ses_scalar_56p(**kwargs):\n num_scales = 3\n factor = 3.0\n min_scale = 1.0\n mult = 1.4\n size = 17\n dropout = 0.7\n q = factor ** (1 / (num_scales - 1))\n scales = [min_scale * q**i for i in range(num_scales)]\n scales = [round(s, 2) for s in scales]\n model = MNIST_SES_Scalar(pool_size=8, kernel_size=size, scales=scales,\n basis_type='B', mult=mult, max_order=4, dropout=dropout)\n return nn.Sequential(nn.Upsample(scale_factor=2), model)\n\n\ndef mnist_ses_scalar_56(**kwargs):\n num_scales = 3\n factor = 2.0\n min_scale = 2.0\n mult = 1.4\n size = 15\n dropout = 0.7\n q = factor ** (1 / (num_scales - 1))\n scales = [min_scale * q**i for i in range(num_scales)]\n scales = [round(s, 2) for s in scales]\n model = MNIST_SES_Scalar(pool_size=8, kernel_size=size, scales=scales,\n basis_type='B', mult=mult, max_order=4, dropout=dropout)\n return nn.Sequential(nn.Upsample(scale_factor=2), model)\n\n\ndef mnist_ses_vector_28p(**kwargs):\n num_scales = 3\n factor = 3.0\n min_scale = 1.5\n mult = 1.4\n size = 15\n dropout = 0.7\n q = factor ** (1 / (num_scales - 1))\n scales = [min_scale * q**i for i in range(num_scales)]\n scales = [round(s, 2) for s in scales]\n model = MNIST_SES_V(pool_size=4, kernel_size=size, scales=scales,\n basis_type='B', mult=mult, max_order=4, dropout=dropout)\n return model\n\n\ndef mnist_ses_vector_28(**kwargs):\n num_scales = 3\n factor = 3.0\n min_scale = 1.5\n mult = 1.5\n size = 13\n dropout = 0.7\n q = factor ** (1 / (num_scales - 1))\n scales = [min_scale * q**i for i in range(num_scales)]\n scales = [round(s, 2) for s in scales]\n model = MNIST_SES_V(pool_size=4, kernel_size=size, scales=scales,\n basis_type='B', mult=mult, max_order=4, dropout=dropout)\n return model\n\n\ndef mnist_ses_scalar_28p(**kwargs):\n num_scales = 4\n factor = 3.0\n min_scale = 1.5\n mult = 1.4\n size = 13\n dropout = 0.7\n q = factor ** (1 / (num_scales - 1))\n scales = [min_scale * q**i for i in range(num_scales)]\n scales = [round(s, 2) for s in scales]\n model = MNIST_SES_Scalar(pool_size=4, kernel_size=size, scales=scales,\n basis_type='B', mult=mult, max_order=4, dropout=dropout)\n return model\n\n\ndef mnist_ses_scalar_28(**kwargs):\n num_scales = 4\n factor = 3.0\n min_scale = 1.7\n mult = 1.5\n size = 15\n dropout = 0.7\n q = factor ** (1 / (num_scales - 1))\n scales = [min_scale * q**i for i in range(num_scales)]\n scales = [round(s, 2) for s in scales]\n model = MNIST_SES_Scalar(pool_size=4, kernel_size=size, scales=scales,\n basis_type='B', mult=mult, max_order=4, dropout=dropout)\n return model\n" ]
[ [ "torch.nn.MaxPool2d", "torch.nn.BatchNorm2d", "torch.nn.Linear", "torch.nn.MaxPool3d", "torch.nn.BatchNorm3d", "torch.nn.BatchNorm1d", "torch.nn.Upsample", "torch.nn.ReLU", "torch.nn.Dropout" ] ]
tomaslovato/mocsy
[ "ede19cde4be5cd37ed192a3f3394e81302d11616" ]
[ "examples/test_mocsy.py" ]
[ "# -*- coding: utf-8 -*-\nimport sys\nimport numpy as np\nsys.path.append(\"../\")\nimport mocsy\n\n# Define input data (typical values at depth from 0 to 5000 meters)\ntemp = np.repeat(2.0, 6).astype('float32')\ndepth = np.arange (0, 6000, 1000).astype('float32')\nsal = np.repeat(35.0, 6).astype('float32')\nalk = np.repeat(2295.*1.e-6, 6).astype('float32')\ndic = np.repeat(2154.*1.e-6, 6).astype('float32')\nsil = phos = np.repeat(0.0, 6).astype('float32')\nPatm = np.repeat(1.0, 6).astype('float32')\noptK1K2 = 'l'\n\n# Create output arrays\n# --------------------\n\n# computed variables at 6 input points\nlat = np.zeros((6,)).astype('float32')\nph = np.zeros((6,)).astype('float32')\npco2 = np.zeros((6,)).astype('float32')\nfco2 = np.zeros((6,)).astype('float32')\nco2 = np.zeros((6,)).astype('float32')\nhco3 = np.zeros((6,)).astype('float32')\nco3 = np.zeros((6,)).astype('float32')\nOmegaA = np.zeros((6,)).astype('float32')\nOmegaC = np.zeros((6,)).astype('float32')\nBetaD = np.zeros((6,)).astype('float32')\nrhoSW = np.zeros((6,)).astype('float32')\np = np.zeros((6,)).astype('float32')\ntempis = np.zeros((6,)).astype('float32')\n# values of derivatives w/ respect to 6 input variables and at 6 input points\nph_deriv = np.zeros((6*6,)).astype('float32')\npco2_deriv = np.zeros((6*6,)).astype('float32')\nOmegaA_deriv = np.zeros((6*6,)).astype('float32')\nph_deriv = ph_deriv.reshape ((6,6), order='F')\npco2_deriv = pco2_deriv.reshape ((6,6), order='F')\nOmegaA_deriv = OmegaA_deriv.reshape ((6,6), order='F')\n\n# Run mocsy.vars()\n# Notice that option names are all lowercase\nph, pco2, fco2, co2, hco3, co3, OmegaA, OmegaC, BetaD, rhoSW, p, tempis = \\\n mocsy.mvars (temp, sal, alk, dic, sil, phos, Patm, depth, lat,\n optcon='mol/kg', optt='Tinsitu', optp='db', optb='l10', optk1k2=optK1K2, optkf='dg')\n\n# Compute automatic derivatives (using automatic differentiation)\nph_deriv, pco2_deriv, fco2_deriv, co2_deriv, hco3_deriv, co3_deriv, OmegaA_deriv, OmegaC_deriv = \\\n mocsy.mderivauto(temp, sal, alk, dic, sil, phos, Patm, depth, lat, # INPUT\n optcon='mol/kg', optt='Tinsitu', optp='db', optb='l10', optk1k2=optK1K2, optkf='dg') # INPUT OPTIONS\n\n# Compute buffer factors from Egleston\n# pco2_deriv[2,:] are derivatives of pCO2 w/ respect to DIC\n# pco2_deriv[1,:] are ... w/ respect to Alk\ngamma_DIC = pco2 / pco2_deriv[1,:]\ngamma_Alk = pco2 / pco2_deriv[0,:]\n\nbeta_DIC = -1. / (np.log(10.) * ph_deriv[1,:])\nbeta_Alk = -1. / (np.log(10.) * ph_deriv[0,:])\n\n# Here, we use Omega of Aragonite (use of Calcite would have been equaly valid)\nomega_DIC = OmegaA / OmegaA_deriv[1,:]\nomega_Alk = OmegaA / OmegaA_deriv[0,:]\n\n# print mocsy results\n# -------------------\n\nprint ('{:s}'.format('-' * 181))\nprint (\" pH pCO2 fCO2 CO2* HCO3- CO32- OmegaA OmegaC R Density Press Temperature gamma_DIC gamma_Alk beta_DIC beta_Alk omega_DIC omega_Alk\")\nprint (\"(total) (uatm) (uatm) (mol/kg) (mol/kg) (mol/kg) (kg/m3) (db) (C)\")\nprint ('{:s}'.format('-' * 181))\n\nprntstr=' {:6.4f} {:6.1f} {:6.1f} {:6.4E} {:6.4E} {:6.4E} {:6.2f} {:6.2f} {:6.2f} {:7.2f} {:6.1f} {:6.3f} {:12.9f} {:12.9f} {:12.9f} {:12.9f} {:12.9f} {:12.9f}'\nfor i in range (0, 6):\n print (prntstr.format(ph[i], pco2[i], fco2[i], co2[i], hco3[i], co3[i], OmegaA[i], OmegaC[i], BetaD[i], rhoSW[i], p[i], tempis[i], gamma_DIC[i], gamma_Alk[i], beta_DIC[i], beta_Alk[i], omega_DIC[i], omega_Alk[i]))\nprint ('{:s}'.format('-' * 181))\n\n# Print derivatives of pH with respect to phosphate, silicate, temperature and salinity\nprint (\"\")\nprint ('{:s}'.format('-' * 45))\nprint (\" dpH/dPhos dpH/dSil dpH/dT dpH/dS\")\nprint (\" pH/µMol pH/µMol pH/°C pH/psu\")\nprint ('{:s}'.format('-' * 45))\nprntstr=' {:10.4f} {:10.5f} {:10.6f} {:10.6f}'\nfor i in range (0, 6):\n print (prntstr.format(ph_deriv[2,i], ph_deriv[3,i], ph_deriv[4,i], ph_deriv[5,i]))\nprint ('{:s}'.format('-' * 45))\n" ]
[ [ "numpy.arange", "numpy.log", "numpy.repeat", "numpy.zeros" ] ]
JayChanHoi/adaptive_gradient_clipping
[ "ab9a7c88bf67843d87919dd51d7b722e063ad2b8" ]
[ "models/nfnet.py" ]
[ "\"\"\" Normalization Free Nets. NFNet, NF-RegNet, NF-ResNet (pre-activation) Models\n\nPaper: `Characterizing signal propagation to close the performance gap in unnormalized ResNets`\n - https://arxiv.org/abs/2101.08692\n\nPaper: `High-Performance Large-Scale Image Recognition Without Normalization`\n - https://arxiv.org/abs/2102.06171\n\nOfficial Deepmind JAX code: https://github.com/deepmind/deepmind-research/tree/master/nfnets\n\nStatus:\n* These models are a work in progress, experiments ongoing.\n* Pretrained weights for two models so far, more to come.\n* Model details updated to closer match official JAX code now that it's released\n* NF-ResNet, NF-RegNet-B, and NFNet-F models supported\n\nHacked together by / copyright Ross Wightman, 2021.\n\"\"\"\nimport math\nfrom dataclasses import dataclass, field\nfrom collections import OrderedDict\nfrom typing import Tuple, Optional\nfrom functools import partial\n\nimport torch\nimport torch.nn as nn\n\nfrom .helpers import build_model_with_cfg\n# from .registry import register_model\nfrom .layers import ClassifierHead, DropPath, AvgPool2dSame, ScaledStdConv2d, ScaledStdConv2dSame,\\\n get_act_layer, get_act_fn, get_attn, make_divisible\n\n\ndef _dcfg(url='', **kwargs):\n return {\n 'url': url,\n 'num_classes': 1000, 'input_size': (3, 224, 224), 'pool_size': (7, 7),\n 'crop_pct': 0.9, 'interpolation': 'bicubic',\n 'mean': (0.485, 0.456, 0.406), 'std': (0.229, 0.224, 0.225),\n 'first_conv': 'stem.conv1', 'classifier': 'head.fc',\n **kwargs\n }\n\n\ndefault_cfgs = dict(\n dm_nfnet_f0=_dcfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-dnf-weights/dm_nfnet_f0-604f9c3a.pth',\n pool_size=(6, 6), input_size=(3, 192, 192), test_input_size=(3, 256, 256), crop_pct=.9),\n dm_nfnet_f1=_dcfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-dnf-weights/dm_nfnet_f1-fc540f82.pth',\n pool_size=(7, 7), input_size=(3, 224, 224), test_input_size=(3, 320, 320), crop_pct=0.91),\n dm_nfnet_f2=_dcfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-dnf-weights/dm_nfnet_f2-89875923.pth',\n pool_size=(8, 8), input_size=(3, 256, 256), test_input_size=(3, 352, 352), crop_pct=0.92),\n dm_nfnet_f3=_dcfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-dnf-weights/dm_nfnet_f3-d74ab3aa.pth',\n pool_size=(10, 10), input_size=(3, 320, 320), test_input_size=(3, 416, 416), crop_pct=0.94),\n dm_nfnet_f4=_dcfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-dnf-weights/dm_nfnet_f4-0ac5b10b.pth',\n pool_size=(12, 12), input_size=(3, 384, 384), test_input_size=(3, 512, 512), crop_pct=0.951),\n dm_nfnet_f5=_dcfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-dnf-weights/dm_nfnet_f5-ecb20ab1.pth',\n pool_size=(13, 13), input_size=(3, 416, 416), test_input_size=(3, 544, 544), crop_pct=0.954),\n dm_nfnet_f6=_dcfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-dnf-weights/dm_nfnet_f6-e0f12116.pth',\n pool_size=(14, 14), input_size=(3, 448, 448), test_input_size=(3, 576, 576), crop_pct=0.956),\n\n nfnet_f0=_dcfg(\n url='', pool_size=(6, 6), input_size=(3, 192, 192), test_input_size=(3, 256, 256)),\n nfnet_f1=_dcfg(\n url='', pool_size=(7, 7), input_size=(3, 224, 224), test_input_size=(3, 320, 320)),\n nfnet_f2=_dcfg(\n url='', pool_size=(8, 8), input_size=(3, 256, 256), test_input_size=(3, 352, 352)),\n nfnet_f3=_dcfg(\n url='', pool_size=(10, 10), input_size=(3, 320, 320), test_input_size=(3, 416, 416)),\n nfnet_f4=_dcfg(\n url='', pool_size=(12, 12), input_size=(3, 384, 384), test_input_size=(3, 512, 512)),\n nfnet_f5=_dcfg(\n url='', pool_size=(13, 13), input_size=(3, 416, 416), test_input_size=(3, 544, 544)),\n nfnet_f6=_dcfg(\n url='', pool_size=(14, 14), input_size=(3, 448, 448), test_input_size=(3, 576, 576)),\n nfnet_f7=_dcfg(\n url='', pool_size=(15, 15), input_size=(3, 480, 480), test_input_size=(3, 608, 608)),\n\n nfnet_f0s=_dcfg(\n url='', pool_size=(6, 6), input_size=(3, 192, 192), test_input_size=(3, 256, 256)),\n nfnet_f1s=_dcfg(\n url='', pool_size=(7, 7), input_size=(3, 224, 224), test_input_size=(3, 320, 320)),\n nfnet_f2s=_dcfg(\n url='', pool_size=(8, 8), input_size=(3, 256, 256), test_input_size=(3, 352, 352)),\n nfnet_f3s=_dcfg(\n url='', pool_size=(10, 10), input_size=(3, 320, 320), test_input_size=(3, 416, 416)),\n nfnet_f4s=_dcfg(\n url='', pool_size=(12, 12), input_size=(3, 384, 384), test_input_size=(3, 512, 512)),\n nfnet_f5s=_dcfg(\n url='', pool_size=(13, 13), input_size=(3, 416, 416), test_input_size=(3, 544, 544)),\n nfnet_f6s=_dcfg(\n url='', pool_size=(14, 14), input_size=(3, 448, 448), test_input_size=(3, 576, 576)),\n nfnet_f7s=_dcfg(\n url='', pool_size=(15, 15), input_size=(3, 480, 480), test_input_size=(3, 608, 608)),\n\n nfnet_l0=_dcfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/nfnet_l0_ra2-45c6688d.pth',\n pool_size=(7, 7), input_size=(3, 224, 224), test_input_size=(3, 288, 288), crop_pct=1.0),\n eca_nfnet_l0=_dcfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/ecanfnet_l0_ra2-e3e9ac50.pth',\n hf_hub='timm/eca_nfnet_l0',\n pool_size=(7, 7), input_size=(3, 224, 224), test_input_size=(3, 288, 288), crop_pct=1.0),\n eca_nfnet_l1=_dcfg(\n url='',\n pool_size=(8, 8), input_size=(3, 256, 256), test_input_size=(3, 320, 320), crop_pct=1.0),\n\n nf_regnet_b0=_dcfg(\n url='', pool_size=(6, 6), input_size=(3, 192, 192), test_input_size=(3, 256, 256), first_conv='stem.conv'),\n nf_regnet_b1=_dcfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/nf_regnet_b1_256_ra2-ad85cfef.pth',\n pool_size=(8, 8), input_size=(3, 256, 256), test_input_size=(3, 288, 288), first_conv='stem.conv'), # NOT to paper spec\n nf_regnet_b2=_dcfg(\n url='', pool_size=(8, 8), input_size=(3, 240, 240), test_input_size=(3, 272, 272), first_conv='stem.conv'),\n nf_regnet_b3=_dcfg(\n url='', pool_size=(9, 9), input_size=(3, 288, 288), test_input_size=(3, 320, 320), first_conv='stem.conv'),\n nf_regnet_b4=_dcfg(\n url='', pool_size=(10, 10), input_size=(3, 320, 320), test_input_size=(3, 384, 384), first_conv='stem.conv'),\n nf_regnet_b5=_dcfg(\n url='', pool_size=(12, 12), input_size=(3, 384, 384), test_input_size=(3, 456, 456), first_conv='stem.conv'),\n\n nf_resnet26=_dcfg(url='', first_conv='stem.conv'),\n nf_resnet50=_dcfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/nf_resnet50_ra2-9f236009.pth',\n pool_size=(8, 8), input_size=(3, 256, 256), test_input_size=(3, 288, 288), crop_pct=0.94, first_conv='stem.conv'),\n nf_resnet101=_dcfg(url='', first_conv='stem.conv'),\n\n nf_seresnet26=_dcfg(url='', first_conv='stem.conv'),\n nf_seresnet50=_dcfg(url='', first_conv='stem.conv'),\n nf_seresnet101=_dcfg(url='', first_conv='stem.conv'),\n\n nf_ecaresnet26=_dcfg(url='', first_conv='stem.conv'),\n nf_ecaresnet50=_dcfg(url='', first_conv='stem.conv'),\n nf_ecaresnet101=_dcfg(url='', first_conv='stem.conv'),\n)\n\n\n@dataclass\nclass NfCfg:\n depths: Tuple[int, int, int, int]\n channels: Tuple[int, int, int, int]\n alpha: float = 0.2\n stem_type: str = '3x3'\n stem_chs: Optional[int] = None\n group_size: Optional[int] = None\n attn_layer: Optional[str] = None\n attn_kwargs: dict = None\n attn_gain: float = 2.0 # NF correction gain to apply if attn layer is used\n width_factor: float = 1.0\n bottle_ratio: float = 0.5\n num_features: int = 0 # num out_channels for final conv, no final_conv if 0\n ch_div: int = 8 # round channels % 8 == 0 to keep tensor-core use optimal\n reg: bool = False # enables EfficientNet-like options used in RegNet variants, expand from in_chs, se in middle\n extra_conv: bool = False # extra 3x3 bottleneck convolution for NFNet models\n gamma_in_act: bool = False\n same_padding: bool = False\n skipinit: bool = False # disabled by default, non-trivial performance impact\n zero_init_fc: bool = False\n act_layer: str = 'silu'\n\n\ndef _nfres_cfg(\n depths, channels=(256, 512, 1024, 2048), group_size=None, act_layer='relu', attn_layer=None, attn_kwargs=None):\n attn_kwargs = attn_kwargs or {}\n cfg = NfCfg(\n depths=depths, channels=channels, stem_type='7x7_pool', stem_chs=64, bottle_ratio=0.25,\n group_size=group_size, act_layer=act_layer, attn_layer=attn_layer, attn_kwargs=attn_kwargs)\n return cfg\n\n\ndef _nfreg_cfg(depths, channels=(48, 104, 208, 440)):\n num_features = 1280 * channels[-1] // 440\n attn_kwargs = dict(reduction_ratio=0.5, divisor=8)\n cfg = NfCfg(\n depths=depths, channels=channels, stem_type='3x3', group_size=8, width_factor=0.75, bottle_ratio=2.25,\n num_features=num_features, reg=True, attn_layer='se', attn_kwargs=attn_kwargs)\n return cfg\n\n\ndef _nfnet_cfg(\n depths, channels=(256, 512, 1536, 1536), group_size=128, bottle_ratio=0.5, feat_mult=2.,\n act_layer='gelu', attn_layer='se', attn_kwargs=None):\n num_features = int(channels[-1] * feat_mult)\n attn_kwargs = attn_kwargs if attn_kwargs is not None else dict(reduction_ratio=0.5, divisor=8)\n cfg = NfCfg(\n depths=depths, channels=channels, stem_type='deep_quad', stem_chs=128, group_size=group_size,\n bottle_ratio=bottle_ratio, extra_conv=True, num_features=num_features, act_layer=act_layer,\n attn_layer=attn_layer, attn_kwargs=attn_kwargs)\n return cfg\n\n\ndef _dm_nfnet_cfg(depths, channels=(256, 512, 1536, 1536), act_layer='gelu', skipinit=True):\n attn_kwargs = dict(reduction_ratio=0.5, divisor=8)\n cfg = NfCfg(\n depths=depths, channels=channels, stem_type='deep_quad', stem_chs=128, group_size=128,\n bottle_ratio=0.5, extra_conv=True, gamma_in_act=True, same_padding=True, skipinit=skipinit,\n num_features=int(channels[-1] * 2.0), act_layer=act_layer, attn_layer='se', attn_kwargs=attn_kwargs)\n return cfg\n\n\nmodel_cfgs = dict(\n # NFNet-F models w/ GELU compatible with DeepMind weights\n dm_nfnet_f0=_dm_nfnet_cfg(depths=(1, 2, 6, 3)),\n dm_nfnet_f1=_dm_nfnet_cfg(depths=(2, 4, 12, 6)),\n dm_nfnet_f2=_dm_nfnet_cfg(depths=(3, 6, 18, 9)),\n dm_nfnet_f3=_dm_nfnet_cfg(depths=(4, 8, 24, 12)),\n dm_nfnet_f4=_dm_nfnet_cfg(depths=(5, 10, 30, 15)),\n dm_nfnet_f5=_dm_nfnet_cfg(depths=(6, 12, 36, 18)),\n dm_nfnet_f6=_dm_nfnet_cfg(depths=(7, 14, 42, 21)),\n\n # NFNet-F models w/ GELU (I will likely deprecate/remove these models and just keep dm_ ver for GELU)\n nfnet_f0=_nfnet_cfg(depths=(1, 2, 6, 3)),\n nfnet_f1=_nfnet_cfg(depths=(2, 4, 12, 6)),\n nfnet_f2=_nfnet_cfg(depths=(3, 6, 18, 9)),\n nfnet_f3=_nfnet_cfg(depths=(4, 8, 24, 12)),\n nfnet_f4=_nfnet_cfg(depths=(5, 10, 30, 15)),\n nfnet_f5=_nfnet_cfg(depths=(6, 12, 36, 18)),\n nfnet_f6=_nfnet_cfg(depths=(7, 14, 42, 21)),\n nfnet_f7=_nfnet_cfg(depths=(8, 16, 48, 24)),\n\n # NFNet-F models w/ SiLU (much faster in PyTorch)\n nfnet_f0s=_nfnet_cfg(depths=(1, 2, 6, 3), act_layer='silu'),\n nfnet_f1s=_nfnet_cfg(depths=(2, 4, 12, 6), act_layer='silu'),\n nfnet_f2s=_nfnet_cfg(depths=(3, 6, 18, 9), act_layer='silu'),\n nfnet_f3s=_nfnet_cfg(depths=(4, 8, 24, 12), act_layer='silu'),\n nfnet_f4s=_nfnet_cfg(depths=(5, 10, 30, 15), act_layer='silu'),\n nfnet_f5s=_nfnet_cfg(depths=(6, 12, 36, 18), act_layer='silu'),\n nfnet_f6s=_nfnet_cfg(depths=(7, 14, 42, 21), act_layer='silu'),\n nfnet_f7s=_nfnet_cfg(depths=(8, 16, 48, 24), act_layer='silu'),\n\n # Experimental 'light' versions of NFNet-F that are little leaner\n nfnet_l0=_nfnet_cfg(\n depths=(1, 2, 6, 3), feat_mult=1.5, group_size=64, bottle_ratio=0.25,\n attn_kwargs=dict(reduction_ratio=0.25, divisor=8), act_layer='silu'),\n eca_nfnet_l0=_nfnet_cfg(\n depths=(1, 2, 6, 3), feat_mult=1.5, group_size=64, bottle_ratio=0.25,\n attn_layer='eca', attn_kwargs=dict(), act_layer='silu'),\n eca_nfnet_l1=_nfnet_cfg(\n depths=(2, 4, 12, 6), feat_mult=2, group_size=64, bottle_ratio=0.25,\n attn_layer='eca', attn_kwargs=dict(), act_layer='silu'),\n\n # EffNet influenced RegNet defs.\n # NOTE: These aren't quite the official ver, ch_div=1 must be set for exact ch counts. I round to ch_div=8.\n nf_regnet_b0=_nfreg_cfg(depths=(1, 3, 6, 6)),\n nf_regnet_b1=_nfreg_cfg(depths=(2, 4, 7, 7)),\n nf_regnet_b2=_nfreg_cfg(depths=(2, 4, 8, 8), channels=(56, 112, 232, 488)),\n nf_regnet_b3=_nfreg_cfg(depths=(2, 5, 9, 9), channels=(56, 128, 248, 528)),\n nf_regnet_b4=_nfreg_cfg(depths=(2, 6, 11, 11), channels=(64, 144, 288, 616)),\n nf_regnet_b5=_nfreg_cfg(depths=(3, 7, 14, 14), channels=(80, 168, 336, 704)),\n # FIXME add B6-B8\n\n # ResNet (preact, D style deep stem/avg down) defs\n nf_resnet26=_nfres_cfg(depths=(2, 2, 2, 2)),\n nf_resnet50=_nfres_cfg(depths=(3, 4, 6, 3)),\n nf_resnet101=_nfres_cfg(depths=(3, 4, 23, 3)),\n\n nf_seresnet26=_nfres_cfg(depths=(2, 2, 2, 2), attn_layer='se', attn_kwargs=dict(reduction_ratio=1/16)),\n nf_seresnet50=_nfres_cfg(depths=(3, 4, 6, 3), attn_layer='se', attn_kwargs=dict(reduction_ratio=1/16)),\n nf_seresnet101=_nfres_cfg(depths=(3, 4, 23, 3), attn_layer='se', attn_kwargs=dict(reduction_ratio=1/16)),\n\n nf_ecaresnet26=_nfres_cfg(depths=(2, 2, 2, 2), attn_layer='eca', attn_kwargs=dict()),\n nf_ecaresnet50=_nfres_cfg(depths=(3, 4, 6, 3), attn_layer='eca', attn_kwargs=dict()),\n nf_ecaresnet101=_nfres_cfg(depths=(3, 4, 23, 3), attn_layer='eca', attn_kwargs=dict()),\n\n)\n\n\nclass GammaAct(nn.Module):\n def __init__(self, act_type='relu', gamma: float = 1.0, inplace=False):\n super().__init__()\n self.act_fn = get_act_fn(act_type)\n self.gamma = gamma\n self.inplace = inplace\n\n def forward(self, x):\n return self.act_fn(x, inplace=self.inplace).mul_(self.gamma)\n\n\ndef act_with_gamma(act_type, gamma: float = 1.):\n def _create(inplace=False):\n return GammaAct(act_type, gamma=gamma, inplace=inplace)\n return _create\n\n\nclass DownsampleAvg(nn.Module):\n def __init__(\n self, in_chs, out_chs, stride=1, dilation=1, first_dilation=None, conv_layer=ScaledStdConv2d):\n \"\"\" AvgPool Downsampling as in 'D' ResNet variants. Support for dilation.\"\"\"\n super(DownsampleAvg, self).__init__()\n avg_stride = stride if dilation == 1 else 1\n if stride > 1 or dilation > 1:\n avg_pool_fn = AvgPool2dSame if avg_stride == 1 and dilation > 1 else nn.AvgPool2d\n self.pool = avg_pool_fn(2, avg_stride, ceil_mode=True, count_include_pad=False)\n else:\n self.pool = nn.Identity()\n self.conv = conv_layer(in_chs, out_chs, 1, stride=1)\n\n def forward(self, x):\n return self.conv(self.pool(x))\n\n\nclass NormFreeBlock(nn.Module):\n \"\"\"Normalization-Free pre-activation block.\n \"\"\"\n\n def __init__(\n self, in_chs, out_chs=None, stride=1, dilation=1, first_dilation=None,\n alpha=1.0, beta=1.0, bottle_ratio=0.25, group_size=None, ch_div=1, reg=True, extra_conv=False,\n skipinit=False, attn_layer=None, attn_gain=2.0, act_layer=None, conv_layer=None, drop_path_rate=0.):\n super().__init__()\n first_dilation = first_dilation or dilation\n out_chs = out_chs or in_chs\n # RegNet variants scale bottleneck from in_chs, otherwise scale from out_chs like ResNet\n mid_chs = make_divisible(in_chs * bottle_ratio if reg else out_chs * bottle_ratio, ch_div)\n groups = 1 if not group_size else mid_chs // group_size\n if group_size and group_size % ch_div == 0:\n mid_chs = group_size * groups # correct mid_chs if group_size divisible by ch_div, otherwise error\n self.alpha = alpha\n self.beta = beta\n self.attn_gain = attn_gain\n\n if in_chs != out_chs or stride != 1 or dilation != first_dilation:\n self.downsample = DownsampleAvg(\n in_chs, out_chs, stride=stride, dilation=dilation, first_dilation=first_dilation, conv_layer=conv_layer)\n else:\n self.downsample = None\n\n self.act1 = act_layer()\n self.conv1 = conv_layer(in_chs, mid_chs, 1)\n self.act2 = act_layer(inplace=True)\n self.conv2 = conv_layer(mid_chs, mid_chs, 3, stride=stride, dilation=first_dilation, groups=groups)\n if extra_conv:\n self.act2b = act_layer(inplace=True)\n self.conv2b = conv_layer(mid_chs, mid_chs, 3, stride=1, dilation=dilation, groups=groups)\n else:\n self.act2b = None\n self.conv2b = None\n if reg and attn_layer is not None:\n self.attn = attn_layer(mid_chs) # RegNet blocks apply attn btw conv2 & 3\n else:\n self.attn = None\n self.act3 = act_layer()\n self.conv3 = conv_layer(mid_chs, out_chs, 1, gain_init=1. if skipinit else 0.)\n if not reg and attn_layer is not None:\n self.attn_last = attn_layer(out_chs) # ResNet blocks apply attn after conv3\n else:\n self.attn_last = None\n self.drop_path = DropPath(drop_path_rate) if drop_path_rate > 0 else nn.Identity()\n self.skipinit_gain = nn.Parameter(torch.tensor(0.)) if skipinit else None\n\n def forward(self, x):\n out = self.act1(x) * self.beta\n\n # shortcut branch\n shortcut = x\n if self.downsample is not None:\n shortcut = self.downsample(out)\n\n # residual branch\n out = self.conv1(out)\n out = self.conv2(self.act2(out))\n if self.conv2b is not None:\n out = self.conv2b(self.act2b(out))\n if self.attn is not None:\n out = self.attn_gain * self.attn(out)\n out = self.conv3(self.act3(out))\n if self.attn_last is not None:\n out = self.attn_gain * self.attn_last(out)\n out = self.drop_path(out)\n\n if self.skipinit_gain is not None:\n out.mul_(self.skipinit_gain) # this slows things down more than expected, TBD\n out = out * self.alpha + shortcut\n return out\n\n\ndef create_stem(in_chs, out_chs, stem_type='', conv_layer=None, act_layer=None, preact_feature=True):\n stem_stride = 2\n stem_feature = dict(num_chs=out_chs, reduction=2, module='stem.conv')\n stem = OrderedDict()\n assert stem_type in ('', 'deep', 'deep_tiered', 'deep_quad', '3x3', '7x7', 'deep_pool', '3x3_pool', '7x7_pool')\n if 'deep' in stem_type:\n if 'quad' in stem_type:\n # 4 deep conv stack as in NFNet-F models\n assert not 'pool' in stem_type\n stem_chs = (out_chs // 8, out_chs // 4, out_chs // 2, out_chs)\n strides = (2, 1, 1, 2)\n stem_stride = 4\n stem_feature = dict(num_chs=out_chs // 2, reduction=2, module='stem.conv3')\n else:\n if 'tiered' in stem_type:\n stem_chs = (3 * out_chs // 8, out_chs // 2, out_chs) # 'T' resnets in resnet.py\n else:\n stem_chs = (out_chs // 2, out_chs // 2, out_chs) # 'D' ResNets\n strides = (2, 1, 1)\n stem_feature = dict(num_chs=out_chs // 2, reduction=2, module='stem.conv2')\n last_idx = len(stem_chs) - 1\n for i, (c, s) in enumerate(zip(stem_chs, strides)):\n stem[f'conv{i + 1}'] = conv_layer(in_chs, c, kernel_size=3, stride=s)\n if i != last_idx:\n stem[f'act{i + 2}'] = act_layer(inplace=True)\n in_chs = c\n elif '3x3' in stem_type:\n # 3x3 stem conv as in RegNet\n stem['conv'] = conv_layer(in_chs, out_chs, kernel_size=3, stride=2)\n else:\n # 7x7 stem conv as in ResNet\n stem['conv'] = conv_layer(in_chs, out_chs, kernel_size=7, stride=2)\n\n if 'pool' in stem_type:\n stem['pool'] = nn.MaxPool2d(3, stride=2, padding=1)\n stem_stride = 4\n\n return nn.Sequential(stem), stem_stride, stem_feature\n\n\n# from https://github.com/deepmind/deepmind-research/tree/master/nfnets\n_nonlin_gamma = dict(\n identity=1.0,\n celu=1.270926833152771,\n elu=1.2716004848480225,\n gelu=1.7015043497085571,\n leaky_relu=1.70590341091156,\n log_sigmoid=1.9193484783172607,\n log_softmax=1.0002083778381348,\n relu=1.7139588594436646,\n relu6=1.7131484746932983,\n selu=1.0008515119552612,\n sigmoid=4.803835391998291,\n silu=1.7881293296813965,\n softsign=2.338853120803833,\n softplus=1.9203323125839233,\n tanh=1.5939117670059204,\n)\n\n\nclass NormFreeNet(nn.Module):\n \"\"\" Normalization-Free Network\n\n As described in :\n `Characterizing signal propagation to close the performance gap in unnormalized ResNets`\n - https://arxiv.org/abs/2101.08692\n and\n `High-Performance Large-Scale Image Recognition Without Normalization` - https://arxiv.org/abs/2102.06171\n\n This model aims to cover both the NFRegNet-Bx models as detailed in the paper's code snippets and\n the (preact) ResNet models described earlier in the paper.\n\n There are a few differences:\n * channels are rounded to be divisible by 8 by default (keep tensor core kernels happy),\n this changes channel dim and param counts slightly from the paper models\n * activation correcting gamma constants are moved into the ScaledStdConv as it has less performance\n impact in PyTorch when done with the weight scaling there. This likely wasn't a concern in the JAX impl.\n * a config option `gamma_in_act` can be enabled to not apply gamma in StdConv as described above, but\n apply it in each activation. This is slightly slower, numerically different, but matches official impl.\n * skipinit is disabled by default, it seems to have a rather drastic impact on GPU memory use and throughput\n for what it is/does. Approx 8-10% throughput loss.\n \"\"\"\n def __init__(self, cfg: NfCfg, num_classes=1000, in_chans=3, global_pool='avg', output_stride=32,\n drop_rate=0., drop_path_rate=0.):\n super().__init__()\n self.num_classes = num_classes\n self.drop_rate = drop_rate\n assert cfg.act_layer in _nonlin_gamma, f\"Please add non-linearity constants for activation ({cfg.act_layer}).\"\n conv_layer = ScaledStdConv2dSame if cfg.same_padding else ScaledStdConv2d\n if cfg.gamma_in_act:\n act_layer = act_with_gamma(cfg.act_layer, gamma=_nonlin_gamma[cfg.act_layer])\n conv_layer = partial(conv_layer, eps=1e-4) # DM weights better with higher eps\n else:\n act_layer = get_act_layer(cfg.act_layer)\n conv_layer = partial(conv_layer, gamma=_nonlin_gamma[cfg.act_layer])\n attn_layer = partial(get_attn(cfg.attn_layer), **cfg.attn_kwargs) if cfg.attn_layer else None\n\n stem_chs = make_divisible((cfg.stem_chs or cfg.channels[0]) * cfg.width_factor, cfg.ch_div)\n self.stem, stem_stride, stem_feat = create_stem(\n in_chans, stem_chs, cfg.stem_type, conv_layer=conv_layer, act_layer=act_layer)\n\n self.feature_info = [stem_feat]\n drop_path_rates = [x.tolist() for x in torch.linspace(0, drop_path_rate, sum(cfg.depths)).split(cfg.depths)]\n prev_chs = stem_chs\n net_stride = stem_stride\n dilation = 1\n expected_var = 1.0\n stages = []\n for stage_idx, stage_depth in enumerate(cfg.depths):\n stride = 1 if stage_idx == 0 and stem_stride > 2 else 2\n if net_stride >= output_stride and stride > 1:\n dilation *= stride\n stride = 1\n net_stride *= stride\n first_dilation = 1 if dilation in (1, 2) else 2\n\n blocks = []\n for block_idx in range(cfg.depths[stage_idx]):\n first_block = block_idx == 0 and stage_idx == 0\n out_chs = make_divisible(cfg.channels[stage_idx] * cfg.width_factor, cfg.ch_div)\n blocks += [NormFreeBlock(\n in_chs=prev_chs, out_chs=out_chs,\n alpha=cfg.alpha,\n beta=1. / expected_var ** 0.5,\n stride=stride if block_idx == 0 else 1,\n dilation=dilation,\n first_dilation=first_dilation,\n group_size=cfg.group_size,\n bottle_ratio=1. if cfg.reg and first_block else cfg.bottle_ratio,\n ch_div=cfg.ch_div,\n reg=cfg.reg,\n extra_conv=cfg.extra_conv,\n skipinit=cfg.skipinit,\n attn_layer=attn_layer,\n attn_gain=cfg.attn_gain,\n act_layer=act_layer,\n conv_layer=conv_layer,\n drop_path_rate=drop_path_rates[stage_idx][block_idx],\n )]\n if block_idx == 0:\n expected_var = 1. # expected var is reset after first block of each stage\n expected_var += cfg.alpha ** 2 # Even if reset occurs, increment expected variance\n first_dilation = dilation\n prev_chs = out_chs\n self.feature_info += [dict(num_chs=prev_chs, reduction=net_stride, module=f'stages.{stage_idx}')]\n stages += [nn.Sequential(*blocks)]\n self.stages = nn.Sequential(*stages)\n\n if cfg.num_features:\n # The paper NFRegNet models have an EfficientNet-like final head convolution.\n self.num_features = make_divisible(cfg.width_factor * cfg.num_features, cfg.ch_div)\n self.final_conv = conv_layer(prev_chs, self.num_features, 1)\n self.feature_info[-1] = dict(num_chs=self.num_features, reduction=net_stride, module=f'final_conv')\n else:\n self.num_features = prev_chs\n self.final_conv = nn.Identity()\n self.final_act = act_layer(inplace=cfg.num_features > 0)\n\n self.head = ClassifierHead(self.num_features, num_classes, pool_type=global_pool, drop_rate=self.drop_rate)\n\n for n, m in self.named_modules():\n if 'fc' in n and isinstance(m, nn.Linear):\n if cfg.zero_init_fc:\n nn.init.zeros_(m.weight)\n else:\n nn.init.normal_(m.weight, 0., .01)\n if m.bias is not None:\n nn.init.zeros_(m.bias)\n elif isinstance(m, nn.Conv2d):\n nn.init.kaiming_normal_(m.weight, mode='fan_in', nonlinearity='linear')\n if m.bias is not None:\n nn.init.zeros_(m.bias)\n\n def get_classifier(self):\n return self.head.fc\n\n def reset_classifier(self, num_classes, global_pool='avg'):\n self.head = ClassifierHead(self.num_features, num_classes, pool_type=global_pool, drop_rate=self.drop_rate)\n\n def forward_features(self, x):\n x = self.stem(x)\n x = self.stages(x)\n x = self.final_conv(x)\n x = self.final_act(x)\n return x\n\n def forward(self, x):\n x = self.forward_features(x)\n x = self.head(x)\n return x\n\n\ndef _create_normfreenet(variant, pretrained=False, **kwargs):\n model_cfg = model_cfgs[variant]\n feature_cfg = dict(flatten_sequential=True)\n return build_model_with_cfg(\n NormFreeNet, variant, pretrained,\n default_cfg=default_cfgs[variant],\n model_cfg=model_cfg,\n feature_cfg=feature_cfg,\n **kwargs)\n\n\n# @register_model\ndef dm_nfnet_f0(pretrained=False, **kwargs):\n \"\"\" NFNet-F0 (DeepMind weight compatible)\n `High-Performance Large-Scale Image Recognition Without Normalization`\n - https://arxiv.org/abs/2102.06171\n \"\"\"\n return _create_normfreenet('dm_nfnet_f0', pretrained=pretrained, **kwargs)\n\n\n# @register_model\ndef dm_nfnet_f1(pretrained=False, **kwargs):\n \"\"\" NFNet-F1 (DeepMind weight compatible)\n `High-Performance Large-Scale Image Recognition Without Normalization`\n - https://arxiv.org/abs/2102.06171\n \"\"\"\n return _create_normfreenet('dm_nfnet_f1', pretrained=pretrained, **kwargs)\n\n\n# @register_model\ndef dm_nfnet_f2(pretrained=False, **kwargs):\n \"\"\" NFNet-F2 (DeepMind weight compatible)\n `High-Performance Large-Scale Image Recognition Without Normalization`\n - https://arxiv.org/abs/2102.06171\n \"\"\"\n return _create_normfreenet('dm_nfnet_f2', pretrained=pretrained, **kwargs)\n\n\n# @register_model\ndef dm_nfnet_f3(pretrained=False, **kwargs):\n \"\"\" NFNet-F3 (DeepMind weight compatible)\n `High-Performance Large-Scale Image Recognition Without Normalization`\n - https://arxiv.org/abs/2102.06171\n \"\"\"\n return _create_normfreenet('dm_nfnet_f3', pretrained=pretrained, **kwargs)\n\n\n# @register_model\ndef dm_nfnet_f4(pretrained=False, **kwargs):\n \"\"\" NFNet-F4 (DeepMind weight compatible)\n `High-Performance Large-Scale Image Recognition Without Normalization`\n - https://arxiv.org/abs/2102.06171\n \"\"\"\n return _create_normfreenet('dm_nfnet_f4', pretrained=pretrained, **kwargs)\n\n\n# @register_model\ndef dm_nfnet_f5(pretrained=False, **kwargs):\n \"\"\" NFNet-F5 (DeepMind weight compatible)\n `High-Performance Large-Scale Image Recognition Without Normalization`\n - https://arxiv.org/abs/2102.06171\n \"\"\"\n return _create_normfreenet('dm_nfnet_f5', pretrained=pretrained, **kwargs)\n\n\n# @register_model\ndef dm_nfnet_f6(pretrained=False, **kwargs):\n \"\"\" NFNet-F6 (DeepMind weight compatible)\n `High-Performance Large-Scale Image Recognition Without Normalization`\n - https://arxiv.org/abs/2102.06171\n \"\"\"\n return _create_normfreenet('dm_nfnet_f6', pretrained=pretrained, **kwargs)\n\n\n# @register_model\ndef nfnet_f0(pretrained=False, **kwargs):\n \"\"\" NFNet-F0\n `High-Performance Large-Scale Image Recognition Without Normalization`\n - https://arxiv.org/abs/2102.06171\n \"\"\"\n return _create_normfreenet('nfnet_f0', pretrained=pretrained, **kwargs)\n\n\n# @register_model\ndef nfnet_f1(pretrained=False, **kwargs):\n \"\"\" NFNet-F1\n `High-Performance Large-Scale Image Recognition Without Normalization`\n - https://arxiv.org/abs/2102.06171\n \"\"\"\n return _create_normfreenet('nfnet_f1', pretrained=pretrained, **kwargs)\n\n\n# @register_model\ndef nfnet_f2(pretrained=False, **kwargs):\n \"\"\" NFNet-F2\n `High-Performance Large-Scale Image Recognition Without Normalization`\n - https://arxiv.org/abs/2102.06171\n \"\"\"\n return _create_normfreenet('nfnet_f2', pretrained=pretrained, **kwargs)\n\n\n# @register_model\ndef nfnet_f3(pretrained=False, **kwargs):\n \"\"\" NFNet-F3\n `High-Performance Large-Scale Image Recognition Without Normalization`\n - https://arxiv.org/abs/2102.06171\n \"\"\"\n return _create_normfreenet('nfnet_f3', pretrained=pretrained, **kwargs)\n\n\n# @register_model\ndef nfnet_f4(pretrained=False, **kwargs):\n \"\"\" NFNet-F4\n `High-Performance Large-Scale Image Recognition Without Normalization`\n - https://arxiv.org/abs/2102.06171\n \"\"\"\n return _create_normfreenet('nfnet_f4', pretrained=pretrained, **kwargs)\n\n\n# @register_model\ndef nfnet_f5(pretrained=False, **kwargs):\n \"\"\" NFNet-F5\n `High-Performance Large-Scale Image Recognition Without Normalization`\n - https://arxiv.org/abs/2102.06171\n \"\"\"\n return _create_normfreenet('nfnet_f5', pretrained=pretrained, **kwargs)\n\n\n# @register_model\ndef nfnet_f6(pretrained=False, **kwargs):\n \"\"\" NFNet-F6\n `High-Performance Large-Scale Image Recognition Without Normalization`\n - https://arxiv.org/abs/2102.06171\n \"\"\"\n return _create_normfreenet('nfnet_f6', pretrained=pretrained, **kwargs)\n\n\n# @register_model\ndef nfnet_f7(pretrained=False, **kwargs):\n \"\"\" NFNet-F7\n `High-Performance Large-Scale Image Recognition Without Normalization`\n - https://arxiv.org/abs/2102.06171\n \"\"\"\n return _create_normfreenet('nfnet_f7', pretrained=pretrained, **kwargs)\n\n\n# @register_model\ndef nfnet_f0s(pretrained=False, **kwargs):\n \"\"\" NFNet-F0 w/ SiLU\n `High-Performance Large-Scale Image Recognition Without Normalization`\n - https://arxiv.org/abs/2102.06171\n \"\"\"\n return _create_normfreenet('nfnet_f0s', pretrained=pretrained, **kwargs)\n\n\n# @register_model\ndef nfnet_f1s(pretrained=False, **kwargs):\n \"\"\" NFNet-F1 w/ SiLU\n `High-Performance Large-Scale Image Recognition Without Normalization`\n - https://arxiv.org/abs/2102.06171\n \"\"\"\n return _create_normfreenet('nfnet_f1s', pretrained=pretrained, **kwargs)\n\n\n# @register_model\ndef nfnet_f2s(pretrained=False, **kwargs):\n \"\"\" NFNet-F2 w/ SiLU\n `High-Performance Large-Scale Image Recognition Without Normalization`\n - https://arxiv.org/abs/2102.06171\n \"\"\"\n return _create_normfreenet('nfnet_f2s', pretrained=pretrained, **kwargs)\n\n\n# @register_model\ndef nfnet_f3s(pretrained=False, **kwargs):\n \"\"\" NFNet-F3 w/ SiLU\n `High-Performance Large-Scale Image Recognition Without Normalization`\n - https://arxiv.org/abs/2102.06171\n \"\"\"\n return _create_normfreenet('nfnet_f3s', pretrained=pretrained, **kwargs)\n\n\n# @register_model\ndef nfnet_f4s(pretrained=False, **kwargs):\n \"\"\" NFNet-F4 w/ SiLU\n `High-Performance Large-Scale Image Recognition Without Normalization`\n - https://arxiv.org/abs/2102.06171\n \"\"\"\n return _create_normfreenet('nfnet_f4s', pretrained=pretrained, **kwargs)\n\n\n# @register_model\ndef nfnet_f5s(pretrained=False, **kwargs):\n \"\"\" NFNet-F5 w/ SiLU\n `High-Performance Large-Scale Image Recognition Without Normalization`\n - https://arxiv.org/abs/2102.06171\n \"\"\"\n return _create_normfreenet('nfnet_f5s', pretrained=pretrained, **kwargs)\n\n\n# @register_model\ndef nfnet_f6s(pretrained=False, **kwargs):\n \"\"\" NFNet-F6 w/ SiLU\n `High-Performance Large-Scale Image Recognition Without Normalization`\n - https://arxiv.org/abs/2102.06171\n \"\"\"\n return _create_normfreenet('nfnet_f6s', pretrained=pretrained, **kwargs)\n\n\n# @register_model\ndef nfnet_f7s(pretrained=False, **kwargs):\n \"\"\" NFNet-F7 w/ SiLU\n `High-Performance Large-Scale Image Recognition Without Normalization`\n - https://arxiv.org/abs/2102.06171\n \"\"\"\n return _create_normfreenet('nfnet_f7s', pretrained=pretrained, **kwargs)\n\n\n# @register_model\ndef nfnet_l0(pretrained=False, **kwargs):\n \"\"\" NFNet-L0b w/ SiLU\n My experimental 'light' model w/ F0 repeats, 1.5x final_conv mult, 64 group_size, .25 bottleneck & SE ratio\n \"\"\"\n return _create_normfreenet('nfnet_l0', pretrained=pretrained, **kwargs)\n\n\n# @register_model\ndef eca_nfnet_l0(pretrained=False, **kwargs):\n \"\"\" ECA-NFNet-L0 w/ SiLU\n My experimental 'light' model w/ F0 repeats, 1.5x final_conv mult, 64 group_size, .25 bottleneck & ECA attn\n \"\"\"\n return _create_normfreenet('eca_nfnet_l0', pretrained=pretrained, **kwargs)\n\n\n# @register_model\ndef eca_nfnet_l1(pretrained=False, **kwargs):\n \"\"\" ECA-NFNet-L1 w/ SiLU\n My experimental 'light' model w/ F1 repeats, 2.0x final_conv mult, 64 group_size, .25 bottleneck & ECA attn\n \"\"\"\n return _create_normfreenet('eca_nfnet_l1', pretrained=pretrained, **kwargs)\n\n\n# @register_model\ndef nf_regnet_b0(pretrained=False, **kwargs):\n \"\"\" Normalization-Free RegNet-B0\n `Characterizing signal propagation to close the performance gap in unnormalized ResNets`\n - https://arxiv.org/abs/2101.08692\n \"\"\"\n return _create_normfreenet('nf_regnet_b0', pretrained=pretrained, **kwargs)\n\n\n# @register_model\ndef nf_regnet_b1(pretrained=False, **kwargs):\n \"\"\" Normalization-Free RegNet-B1\n `Characterizing signal propagation to close the performance gap in unnormalized ResNets`\n - https://arxiv.org/abs/2101.08692\n \"\"\"\n return _create_normfreenet('nf_regnet_b1', pretrained=pretrained, **kwargs)\n\n\n# @register_model\ndef nf_regnet_b2(pretrained=False, **kwargs):\n \"\"\" Normalization-Free RegNet-B2\n `Characterizing signal propagation to close the performance gap in unnormalized ResNets`\n - https://arxiv.org/abs/2101.08692\n \"\"\"\n return _create_normfreenet('nf_regnet_b2', pretrained=pretrained, **kwargs)\n\n\n# @register_model\ndef nf_regnet_b3(pretrained=False, **kwargs):\n \"\"\" Normalization-Free RegNet-B3\n `Characterizing signal propagation to close the performance gap in unnormalized ResNets`\n - https://arxiv.org/abs/2101.08692\n \"\"\"\n return _create_normfreenet('nf_regnet_b3', pretrained=pretrained, **kwargs)\n\n\n# @register_model\ndef nf_regnet_b4(pretrained=False, **kwargs):\n \"\"\" Normalization-Free RegNet-B4\n `Characterizing signal propagation to close the performance gap in unnormalized ResNets`\n - https://arxiv.org/abs/2101.08692\n \"\"\"\n return _create_normfreenet('nf_regnet_b4', pretrained=pretrained, **kwargs)\n\n\n# @register_model\ndef nf_regnet_b5(pretrained=False, **kwargs):\n \"\"\" Normalization-Free RegNet-B5\n `Characterizing signal propagation to close the performance gap in unnormalized ResNets`\n - https://arxiv.org/abs/2101.08692\n \"\"\"\n return _create_normfreenet('nf_regnet_b5', pretrained=pretrained, **kwargs)\n\n\n# @register_model\ndef nf_resnet26(pretrained=False, **kwargs):\n \"\"\" Normalization-Free ResNet-26\n `Characterizing signal propagation to close the performance gap in unnormalized ResNets`\n - https://arxiv.org/abs/2101.08692\n \"\"\"\n return _create_normfreenet('nf_resnet26', pretrained=pretrained, **kwargs)\n\n\n# @register_model\ndef nf_resnet50(pretrained=False, **kwargs):\n \"\"\" Normalization-Free ResNet-50\n `Characterizing signal propagation to close the performance gap in unnormalized ResNets`\n - https://arxiv.org/abs/2101.08692\n \"\"\"\n return _create_normfreenet('nf_resnet50', pretrained=pretrained, **kwargs)\n\n\n# @register_model\ndef nf_resnet101(pretrained=False, **kwargs):\n \"\"\" Normalization-Free ResNet-101\n `Characterizing signal propagation to close the performance gap in unnormalized ResNets`\n - https://arxiv.org/abs/2101.08692\n \"\"\"\n return _create_normfreenet('nf_resnet101', pretrained=pretrained, **kwargs)\n\n\n# @register_model\ndef nf_seresnet26(pretrained=False, **kwargs):\n \"\"\" Normalization-Free SE-ResNet26\n \"\"\"\n return _create_normfreenet('nf_seresnet26', pretrained=pretrained, **kwargs)\n\n\n# @register_model\ndef nf_seresnet50(pretrained=False, **kwargs):\n \"\"\" Normalization-Free SE-ResNet50\n \"\"\"\n return _create_normfreenet('nf_seresnet50', pretrained=pretrained, **kwargs)\n\n\n# @register_model\ndef nf_seresnet101(pretrained=False, **kwargs):\n \"\"\" Normalization-Free SE-ResNet101\n \"\"\"\n return _create_normfreenet('nf_seresnet101', pretrained=pretrained, **kwargs)\n\n\n# @register_model\ndef nf_ecaresnet26(pretrained=False, **kwargs):\n \"\"\" Normalization-Free ECA-ResNet26\n \"\"\"\n return _create_normfreenet('nf_ecaresnet26', pretrained=pretrained, **kwargs)\n\n\n# @register_model\ndef nf_ecaresnet50(pretrained=False, **kwargs):\n \"\"\" Normalization-Free ECA-ResNet50\n \"\"\"\n return _create_normfreenet('nf_ecaresnet50', pretrained=pretrained, **kwargs)\n\n\n# @register_model\ndef nf_ecaresnet101(pretrained=False, **kwargs):\n \"\"\" Normalization-Free ECA-ResNet101\n \"\"\"\n return _create_normfreenet('nf_ecaresnet101', pretrained=pretrained, **kwargs)\n" ]
[ [ "torch.nn.MaxPool2d", "torch.nn.init.kaiming_normal_", "torch.tensor", "torch.nn.init.normal_", "torch.nn.Identity", "torch.nn.Sequential", "torch.nn.init.zeros_" ] ]
lesserwhirls/scipy-cwt
[ "ee673656d879d9356892621e23ed0ced3d358621" ]
[ "scipy/lib/lapack/setupscons.py" ]
[ "#!/usr/bin/env python\n\nimport os\nfrom glob import glob\n\ndef configuration(parent_package='',top_path=None):\n from numpy.distutils.misc_util import Configuration\n from numpy.distutils.system_info import get_info\n\n config = Configuration('lapack',parent_package,top_path)\n\n config.add_sconscript('SConstruct')\n config.add_data_dir('tests')\n\n return config\n\nif __name__ == '__main__':\n from numpy.distutils.core import setup\n\n setup(**configuration(top_path='').todict())\n" ]
[ [ "numpy.distutils.misc_util.Configuration" ] ]
old-school-kid/keras
[ "326cf80085a9d7d980b968ea1ca235490e32833b" ]
[ "keras/layers/dense_attention_test.py" ]
[ "# Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests dense attention layers.\"\"\"\n\nimport tensorflow.compat.v2 as tf\n\nfrom absl.testing import parameterized\nimport numpy as np\n\nimport keras\nfrom keras import combinations\nfrom keras import testing_utils\nfrom keras.layers import core\nfrom keras.layers import dense_attention\nfrom keras.mixed_precision import policy\n\n\[email protected](combinations.combine(mode=['graph', 'eager']))\nclass BaseDenseAttentionTest(tf.test.TestCase, parameterized.TestCase):\n\n def test_one_dim_with_mask(self):\n # Scores tensor of shape [1, 1, 1]\n scores = np.array([[[1.1]]], dtype=np.float32)\n # Value tensor of shape [1, 1, 1]\n v = np.array([[[1.6]]], dtype=np.float32)\n # Scores mask tensor of shape [1, 1, 1]\n scores_mask = np.array([[[True]]], dtype=np.bool_)\n actual, actual_scores = dense_attention.BaseDenseAttention()._apply_scores(\n scores=scores, value=v, scores_mask=scores_mask)\n\n # Expected softmax_scores = [[[1]]]\n expected_scores = np.array([[[1.]]], dtype=np.float32)\n self.assertAllClose(expected_scores, actual_scores)\n # Expected tensor of shape [1, 1, 1].\n # expected000 = softmax_scores[0, 0] * 1.6 = 1.6\n expected = np.array([[[1.6]]], dtype=np.float32)\n self.assertAllClose(expected, actual)\n\n def test_one_dim_no_mask(self):\n # Scores tensor of shape [1, 1, 1]\n scores = np.array([[[1.1]]], dtype=np.float32)\n # Value tensor of shape [1, 1, 1]\n v = np.array([[[1.6]]], dtype=np.float32)\n actual, actual_scores = dense_attention.BaseDenseAttention()._apply_scores(\n scores=scores, value=v)\n\n # Expected softmax_scores = [[[1]]]\n expected_scores = np.array([[[1.]]], dtype=np.float32)\n self.assertAllClose(expected_scores, actual_scores)\n # Expected tensor of shape [1, 1, 1].\n # expected000 = softmax_scores[0, 0] * 1.6 = 1.6\n expected = np.array([[[1.6]]], dtype=np.float32)\n self.assertAllClose(expected, actual)\n\n def test_multi_dim_with_mask(self):\n # Scores tensor of shape [1, 1, 3]\n scores = np.array([[[1., 0., 1.]]], dtype=np.float32)\n # Value tensor of shape [1, 3, 1]\n v = np.array([[[1.6], [0.7], [-0.8]]], dtype=np.float32)\n # Scores mask tensor of shape [1, 1, 3]\n scores_mask = np.array([[[True, True, False]]], dtype=np.bool_)\n actual, actual_scores = dense_attention.BaseDenseAttention()._apply_scores(\n scores=scores, value=v, scores_mask=scores_mask)\n\n # Expected softmax scores = softmax(scores) with zeros in positions where\n # v_mask == False.\n # => softmax_scores000 = exp(1)/(exp(1) + exp(0)) = 0.73105857863\n # softmax_scores001 = exp(0)/(exp(1) + exp(0)) = 0.26894142137\n # softmax_scores002 = 0\n expected_scores = np.array([[[0.73105857863, 0.26894142137, 0.]]],\n dtype=np.float32)\n self.assertAllClose(expected_scores, actual_scores)\n # Expected tensor of shape [1, 1, 1].\n # expected000 = 0.73105857863 * 1.6 + 0.26894142137 * 0.7 - 0 * 0.8\n # = 1.35795272077\n expected = np.array([[[1.35795272077]]], dtype=np.float32)\n self.assertAllClose(expected, actual)\n\n def test_multi_dim_no_mask(self):\n # Scores tensor of shape [1, 1, 3]\n scores = np.array([[[1., 0., 1.]]], dtype=np.float32)\n # Value tensor of shape [1, 3, 1]\n v = np.array([[[1.6], [0.7], [-0.8]]], dtype=np.float32)\n actual, actual_scores = dense_attention.BaseDenseAttention()._apply_scores(\n scores=scores, value=v)\n\n # Expected softmax_scores = softmax(scores).\n # => softmax_scores000 = exp(1)/(exp(1) + exp(0) + exp(1))\n # = 0.42231879825\n # softmax_scores001 = exp(0)/(exp(1) + exp(0) + exp(1))\n # = 0.15536240349\n # softmax_scores002 = exp(1)/(exp(1) + exp(0) + exp(1))\n # = 0.42231879825\n expected_scores = np.array(\n [[[0.42231879825, 0.15536240349, 0.42231879825]]], dtype=np.float32)\n self.assertAllClose(expected_scores, actual_scores)\n # Expected tensor of shape [1, 1, 1].\n # expected000 = 0.42231879825 * 1.6 + 0.15536240349 * 0.7\n # - 0.42231879825 * 0.8\n # = 0.44660872104\n expected = np.array([[[0.44660872104]]], dtype=np.float32)\n self.assertAllClose(expected, actual)\n\n def test_one_dim_batch_size_two(self):\n # Scores tensor of shape [2, 1, 1]\n scores = np.array([[[1.1]], [[2.1]]], dtype=np.float32)\n # Value tensor of shape [2, 1, 1]\n v = np.array([[[1.6]], [[2.6]]], dtype=np.float32)\n # Scpres mask tensor of shape [2, 1, 1]\n scores_mask = np.array([[[True]], [[True]]], dtype=np.bool_)\n actual, actual_scores = dense_attention.BaseDenseAttention()._apply_scores(\n scores=scores, value=v, scores_mask=scores_mask)\n\n # Expected softmax_scores = [[[1]], [[1]]]\n expected_scores = np.array([[[1.]], [[1.]]], dtype=np.float32)\n self.assertAllClose(expected_scores, actual_scores)\n # Expected tensor of shape [2, 1, 1].\n # expected000 = softmax_scores[0, 0] * 1.6 = 1.6\n # expected100 = softmax_scores[1, 0] * 2.6 = 2.6\n expected = np.array([[[1.6]], [[2.6]]], dtype=np.float32)\n self.assertAllClose(expected, actual)\n\n def test_shape_with_dropout(self):\n # scores: Scores float tensor of shape `[batch_size, tq, tv]`.\n # value: Value tensor of shape `[batch_size, tv, dim]`.\n batch_size = 4\n tq = 5\n tv = 6\n dim = 7\n scores = np.ones((batch_size, tq, tv))\n value = np.ones((batch_size, tv, dim))\n actual, actual_scores = dense_attention.BaseDenseAttention(\n dropout=0.1)._apply_scores(\n scores=scores, value=value, training=False)\n\n # Expected Tensor of shape `[batch_size, tq, tv]`.\n expected_scores_shape = [batch_size, tq, tv]\n self.assertAllEqual(expected_scores_shape, tf.shape(actual_scores))\n # Expected Tensor of shape `[batch_size, tq, dim]`.\n expected_shape = [batch_size, tq, dim]\n self.assertAllEqual(expected_shape, tf.shape(actual))\n\n def test_serialization(self):\n # Test serialization with causal\n layer = dense_attention.BaseDenseAttention(causal=True)\n\n config = keras.layers.serialize(layer)\n new_layer = keras.layers.deserialize(config)\n self.assertEqual(new_layer.causal, True)\n\n config = layer.get_config()\n new_layer = dense_attention.BaseDenseAttention.from_config(config)\n self.assertEqual(new_layer.causal, True)\n\n\[email protected](combinations.combine(mode=['graph', 'eager']))\nclass AttentionTest(tf.test.TestCase, parameterized.TestCase):\n\n def test_calculate_scores_one_dim(self):\n # Query tensor of shape [1, 1, 1]\n q = np.array([[[1.1]]], dtype=np.float32)\n # Key tensor of shape [1, 1, 1]\n k = np.array([[[1.6]]], dtype=np.float32)\n attention_layer = dense_attention.Attention()\n attention_layer.build(input_shape=([1, 1, 1], [1, 1, 1]))\n actual = attention_layer._calculate_scores(query=q, key=k)\n\n # Expected tensor of shape [1, 1, 1].\n # expected000 = 1.1*1.6 = 1.76\n expected = np.array([[[1.76]]], dtype=np.float32)\n self.assertAllClose(expected, actual)\n\n def test_calculate_scores_multi_dim(self):\n # Query tensor of shape [1, 2, 4]\n q = np.array([[[1., 1.1, 1.2, 1.3], [2., 2.1, 2.2, 2.3]]], dtype=np.float32)\n # Key tensor of shape [1, 3, 4]\n k = np.array(\n [[[1.5, 1.6, 1.7, 1.8], [2.5, 2.6, 2.7, 2.8], [3.5, 3.6, 3.7, 3.8]]],\n dtype=np.float32)\n attention_layer = dense_attention.Attention()\n attention_layer.build(input_shape=([1, 2, 4], [1, 3, 4]))\n actual = attention_layer._calculate_scores(query=q, key=k)\n\n # Expected tensor of shape [1, 2, 3].\n # expected000 = 1.*1.5+1.1*1.6+1.2*1.7+1.3*1.8 = 7.64\n # expected001 = 1.*2.5+1.1*2.6+1.2*2.7+1.3*2.8 = 12.24\n # expected002 = 1.*3.5+1.1*3.6+1.2*3.7+1.3*3.8 = 16.84\n # expected010 = 2.*1.5+2.1*1.6+2.2*1.7+2.3*1.8 = 14.24\n # expected011 = 2.*2.5+2.1*2.6+2.2*2.7+2.3*2.8 = 22.84\n # expected012 = 2.*3.5+2.1*3.6+2.2*3.7+2.3*3.8 = 31.44\n expected = np.array([[[7.64, 12.24, 16.84], [14.24, 22.84, 31.44]]],\n dtype=np.float32)\n self.assertAllClose(expected, actual)\n \n def test_calculate_scores_multi_dim_concat(self):\n # Query tensor of shape [1, 2, 4]\n q = np.array([[[1., 1.1, 1.2, 1.3], [2., 2.1, 2.2, 2.3]]], dtype=np.float32)\n # Key tensor of shape [1, 3, 4]\n k = np.array(\n [[[1.5, 1.6, 1.7, 1.8], [2.5, 2.6, 2.7, 2.8], [3.5, 3.6, 3.7, 3.8]]],\n dtype=np.float32)\n attention_layer = dense_attention.Attention(score_mode='concat')\n attention_layer.concat_score_weight = 1\n attention_layer.build(input_shape=([1, 2, 4], [1, 3, 4]))\n actual = keras.backend.get_value(\n attention_layer._calculate_scores(query=q, key=k))\n\n # pylint:disable=line-too-long\n # expected000 = tanh(1.+1.5) + tanh(1.1+1.6) + tanh(1.2+1.7) + tanh(1.3+1.8) = 3.96753427840\n # expected001 = tanh(1.+2.5) + tanh(1.1+2.6) + tanh(1.2+2.7) + tanh(1.3+2.8) = 3.99558784825\n # expected002 = tanh(1.+3.5) + tanh(1.1+3.6) + tanh(1.2+3.7) + tanh(1.3+3.8) = 3.99940254147\n # expected010 = tanh(2.+1.5) + tanh(2.1+1.6) + tanh(2.2+1.7) + tanh(2.3+1.8) = 3.99558784825\n # expected011 = tanh(2.+2.5) + tanh(2.1+2.6) + tanh(2.2+2.7) + tanh(2.3+2.8) = 3.99940254147\n # expected012 = tanh(2.+3.5) + tanh(2.1+3.6) + tanh(2.2+3.7) + tanh(2.3+3.8) = 3.99991913657\n expected = np.array([[[3.96753427840, 3.99558784825, 3.99940254147],\n [3.99558784825, 3.99940254147, 3.99991913657]]],\n dtype=np.float32)\n self.assertAllClose(expected, actual)\n\n def test_calculate_scores_one_dim_batch_size_two(self):\n # Query tensor of shape [2, 1, 1]\n q = np.array([[[1.1]], [[2.1]]], dtype=np.float32)\n # Key tensor of shape [2, 1, 1]\n k = np.array([[[1.6]], [[2.6]]], dtype=np.float32)\n attention_layer = dense_attention.Attention()\n attention_layer.build(input_shape=([2, 1, 1], [2, 1, 1]))\n actual = attention_layer._calculate_scores(query=q, key=k)\n\n # Expected tensor of shape [2, 1, 1].\n # expected000 = 1.1*1.6 = 1.76\n # expected100 = 2.1*2.6 = 5.46\n expected = np.array([[[1.76]], [[5.46]]], dtype=np.float32)\n self.assertAllClose(expected, actual)\n\n def test_calculate_scores_one_dim_with_scale(self):\n \"\"\"Tests that scores are multiplied by scale.\"\"\"\n # Query tensor of shape [1, 1, 1]\n q = np.array([[[1.1]]], dtype=np.float32)\n # Key tensor of shape [1, 1, 1]\n k = np.array([[[1.6]]], dtype=np.float32)\n attention_layer = dense_attention.Attention(use_scale=True)\n attention_layer.build(input_shape=([1, 1, 1], [1, 1, 1]))\n attention_layer.scale = -2.\n actual = attention_layer._calculate_scores(query=q, key=k)\n\n # Expected tensor of shape [1, 1, 1].\n # expected000 = -2*1.1*1.6 = -3.52\n expected = np.array([[[-3.52]]], dtype=np.float32)\n self.assertAllClose(expected, actual)\n \n def test_calculate_scores_one_dim_with_scale_concat(self):\n \"\"\"Tests that scores are multiplied by scale.\"\"\"\n # Query tensor of shape [1, 1, 1]\n q = np.array([[[1.1]]], dtype=np.float32)\n # Key tensor of shape [1, 1, 1]\n k = np.array([[[1.6]]], dtype=np.float32)\n attention_layer = dense_attention.Attention(use_scale=True, score_mode='concat')\n attention_layer.concat_score_weight = 1\n attention_layer.build(input_shape=([1, 1, 1], [1, 1, 1]))\n attention_layer.scale = 2.\n actual = keras.backend.get_value(\n attention_layer._calculate_scores(query=q, key=k))\n\n # Expected tensor of shape [1, 1, 1].\n # expected000 = tanh(2*(1.1+1.6)) = 0.9999592018254402\n expected = np.array([[[0.999959202]]], dtype=np.float32)\n self.assertAllClose(expected, actual)\n\n def test_shape(self):\n # Query tensor of shape [1, 2, 4]\n q = np.array([[[1., 1.1, 1.2, 1.3], [2., 2.1, 2.2, 2.3]]], dtype=np.float32)\n # Value tensor of shape [1, 3, 4]\n v = np.array(\n [[[1.5, 1.6, 1.7, 1.8], [2.5, 2.6, 2.7, 2.8], [3.5, 3.6, 3.7, 3.8]]],\n dtype=np.float32)\n # Value mask tensor of shape [1, 3]\n v_mask = np.array([[True, True, False]], dtype=np.bool_)\n attention_layer = dense_attention.Attention()\n actual = attention_layer([q, v], mask=[None, v_mask])\n\n expected_shape = [1, 2, 4]\n self.assertAllEqual(expected_shape, tf.shape(actual))\n \n def test_shape_concat(self):\n # Query tensor of shape [1, 2, 4]\n q = np.array([[[1., 1.1, 1.2, 1.3], [2., 2.1, 2.2, 2.3]]], dtype=np.float32)\n # Value tensor of shape [1, 3, 4]\n v = np.array(\n [[[1.5, 1.6, 1.7, 1.8], [2.5, 2.6, 2.7, 2.8], [3.5, 3.6, 3.7, 3.8]]],\n dtype=np.float32)\n # Value mask tensor of shape [1, 3]\n v_mask = np.array([[True, True, False]], dtype=np.bool_)\n attention_layer = dense_attention.Attention(score_mode='concat')\n attention_layer.concat_score_weight = 1\n actual = attention_layer([q, v], mask=[None, v_mask])\n\n expected_shape = [1, 2, 4]\n self.assertAllEqual(expected_shape, tf.shape(actual))\n\n def test_shape_with_key(self):\n # Query tensor of shape [1, 2, 4]\n q = np.array([[[1., 1.1, 1.2, 1.3], [2., 2.1, 2.2, 2.3]]], dtype=np.float32)\n # Value tensor of shape [1, 3, 4]\n v = np.array(\n [[[1.5, 1.6, 1.7, 1.8], [2.5, 2.6, 2.7, 2.8], [3.5, 3.6, 3.7, 3.8]]],\n dtype=np.float32)\n # Key tensor of shape [1, 3, 4]\n k = np.array(\n [[[1.5, 1.6, 1.7, 1.8], [2.5, 2.6, 2.7, 2.8], [3.5, 3.6, 3.7, 3.8]]],\n dtype=np.float32)\n # Value mask tensor of shape [1, 3]\n v_mask = np.array([[True, True, False]], dtype=np.bool_)\n attention_layer = dense_attention.Attention()\n actual = attention_layer([q, v, k], mask=[None, v_mask])\n\n expected_shape = [1, 2, 4]\n self.assertAllEqual(expected_shape, tf.shape(actual))\n \n def test_shape_with_key_concat(self):\n # Query tensor of shape [1, 2, 4]\n q = np.array([[[1., 1.1, 1.2, 1.3], [2., 2.1, 2.2, 2.3]]], dtype=np.float32)\n # Value tensor of shape [1, 3, 4]\n v = np.array(\n [[[1.5, 1.6, 1.7, 1.8], [2.5, 2.6, 2.7, 2.8], [3.5, 3.6, 3.7, 3.8]]],\n dtype=np.float32)\n # Key tensor of shape [1, 3, 4]\n k = np.array(\n [[[1.5, 1.6, 1.7, 1.8], [2.5, 2.6, 2.7, 2.8], [3.5, 3.6, 3.7, 3.8]]],\n dtype=np.float32)\n # Value mask tensor of shape [1, 3]\n v_mask = np.array([[True, True, False]], dtype=np.bool_)\n attention_layer = dense_attention.Attention(score_mode='concat')\n attention_layer.concat_score_weight = 1\n actual = attention_layer([q, v, k], mask=[None, v_mask])\n\n expected_shape = [1, 2, 4]\n self.assertAllEqual(expected_shape, tf.shape(actual))\n\n def test_multi_dim(self):\n # Query tensor of shape [1, 1, 1]\n q = np.array([[[1.1]]], dtype=np.float32)\n # Value tensor of shape [1, 3, 1]\n v = np.array([[[1.6], [0.7], [-0.8]]], dtype=np.float32)\n # Value mask tensor of shape [1, 3]\n v_mask = np.array([[True, True, False]], dtype=np.bool_)\n attention_layer = dense_attention.Attention()\n actual = attention_layer([q, v], mask=[None, v_mask])\n\n # Expected scores of shape [1, 1, 3]\n # scores = [[[1.1*1.6, 1.1*0.7, -1.1*0.8]]] = [[[1.76, 0.77, -0.88]]]\n # Expected attention distribution = softmax(scores) with zeros in\n # positions where v_mask == False.\n # => attention_distribution000 = exp(1.76)/(exp(1.76) + exp(0.77))\n # = 0.72908792234\n # attention_distribution001 = exp(0.77)/(exp(1.76) + exp(0.77))\n # = 0.27091207765\n # attention_distribution002 = 0\n #\n # Expected tensor of shape [1, 1, 1].\n # expected000 = 0.72908792234 * 1.6 + 0.27091207765 * 0.7 - 0 * 0.8\n # = 1.3561791301\n expected = np.array([[[1.3561791301]]], dtype=np.float32)\n self.assertAllClose(expected, actual)\n\n def test_multi_dim_with_key(self):\n # Query tensor of shape [1, 1, 1]\n q = np.array([[[1.1]]], dtype=np.float32)\n # Value tensor of shape [1, 3, 1]\n v = np.array([[[0.5], [0.8], [-0.3]]], dtype=np.float32)\n # Key tensor of shape [1, 3, 1]\n k = np.array([[[1.6], [0.7], [-0.8]]], dtype=np.float32)\n # Value mask tensor of shape [1, 3]\n v_mask = np.array([[True, True, False]], dtype=np.bool_)\n attention_layer = dense_attention.Attention()\n actual = attention_layer([q, v, k], mask=[None, v_mask])\n\n # Expected scores of shape [1, 1, 3]\n # scores = [[[1.1*1.6, 1.1*0.7, -1.1*0.8]]] = [[[1.76, 0.77, -0.88]]]\n # Expected attention distribution = softmax(scores) with zeros in\n # positions where v_mask == False.\n # => attention_distribution000 = exp(1.76)/(exp(1.76) + exp(0.77))\n # = 0.72908792234\n # attention_distribution001 = exp(0.77)/(exp(1.76) + exp(0.77))\n # = 0.27091207765\n # attention_distribution002 = 0\n #\n # Expected tensor of shape [1, 1, 1].\n # expected000 = 0.72908792234 * 0.5 + 0.27091207765 * 0.8 - 0 * 0.3\n # = 0.58127362329\n expected = np.array([[[0.58127362329]]], dtype=np.float32)\n self.assertAllClose(expected, actual)\n\n @parameterized.named_parameters(\n ('', False),\n ('return_attention_scores', True),\n )\n def test_multi_dim_with_query_mask(self, return_attention_scores):\n # Query tensor of shape [1, 2, 1]\n q = np.array([[[1.1], [-0.5]]], dtype=np.float32)\n # Value tensor of shape [1, 3, 1]\n v = np.array([[[1.6], [0.7], [-0.8]]], dtype=np.float32)\n # Query mask tensor of shape [1, 2]\n q_mask = np.array([[True, False]], dtype=np.bool_)\n # Value mask tensor of shape [1, 3]\n v_mask = np.array([[True, True, False]], dtype=np.bool_)\n attention_layer = dense_attention.Attention()\n if return_attention_scores:\n actual, actual_scores = attention_layer(\n [q, v],\n mask=[q_mask, v_mask],\n return_attention_scores=return_attention_scores)\n else:\n actual = attention_layer([q, v],\n mask=[q_mask, v_mask],\n return_attention_scores=return_attention_scores)\n\n # Expected scores of shape [1, 2, 3]\n # scores = [[[1.1*1.6, 1.1*0.7, -1.1*0.8], [-0.5*1.6, -0.5*0.7, 0.5*0.8]]]\n # = [[[1.76, 0.77, -0.88], [-0.8, -0.35, 0.4]]]\n # Expected attention distribution = softmax(scores) with zeros in\n # positions where v_mask == False.\n # => attention_distribution000 = exp(1.76)/(exp(1.76) + exp(0.77))\n # = 0.72908792234\n # attention_distribution001 = exp(0.77)/(exp(1.76) + exp(0.77))\n # = 0.27091207765\n # attention_distribution002 = 0\n # => attention_distribution010 = exp(-0.8)/(exp(-0.8) + exp(-0.35))\n # = 0.38936076605\n # attention_distribution011 = exp(-0.35)/(exp(-0.8) + exp(-0.35))\n # = 0.61063923394\n # attention_distribution012 = 0\n if return_attention_scores:\n expected_scores = np.array([[[0.72908792234, 0.27091207765, 0.],\n [0.38936076605, 0.61063923394, 0.]]],\n dtype=np.float32)\n self.assertAllClose(expected_scores, actual_scores)\n # Expected tensor of shape [1, 2, 1] with zeros where q_mask == False.\n # expected000 = 0.72908792234 * 1.6 + 0.27091207765 * 0.7 - 0 * 0.8\n # = 1.3561791301\n # expected000 = 0\n expected = np.array([[[1.3561791301], [0.]]], dtype=np.float32)\n self.assertAllClose(expected, actual)\n\n def test_scale_None(self):\n \"\"\"Tests that scale is None by default.\"\"\"\n attention_layer = dense_attention.Attention()\n attention_layer.build(input_shape=([1, 1, 1], [1, 1, 1]))\n self.assertIsNone(attention_layer.scale)\n\n def test_scale_init_eager(self):\n \"\"\"Tests that scale initializes to 1 when use_scale=True.\"\"\"\n if not tf.executing_eagerly():\n self.skipTest('Only run in eager mode')\n attention_layer = dense_attention.Attention(use_scale=True)\n attention_layer.build(input_shape=([1, 1, 1], [1, 1, 1]))\n self.assertAllClose(1., attention_layer.scale.value())\n\n def test_scale_init_graph(self):\n \"\"\"Tests that scale initializes to 1 when use_scale=True.\"\"\"\n with self.cached_session() as sess:\n attention_layer = dense_attention.Attention(use_scale=True)\n attention_layer.build(input_shape=([1, 1, 1], [1, 1, 1]))\n sess.run(attention_layer.scale.initializer)\n self.assertAllClose(1., attention_layer.scale.value())\n\n @parameterized.named_parameters(\n ('', False),\n ('return_attention_scores', True),\n )\n def test_self_attention_causal(self, return_attention_scores):\n # Query-value tensor of shape [1, 3, 1]\n q = np.array([[[0.5], [0.8], [-0.3]]], dtype=np.float32)\n attention_layer = dense_attention.Attention(causal=True)\n if return_attention_scores:\n actual, actual_scores = attention_layer(\n [q, q], return_attention_scores=return_attention_scores)\n else:\n actual = attention_layer([q, q],\n return_attention_scores=return_attention_scores)\n\n # Expected scores of shape [1, 3, 3]\n # scores = [[0.25, 0.4, -0.15], [0.4, 0.64, -0.24], [-0.15, -0.24, 0.09]]\n # Expected attention distribution = softmax(scores) lower triangular\n # => attention_distribution00 = [1., 0., 0.]\n # attention_distribution01\n # = [exp(0.4), exp(0.64), 0.] / (exp(0.4) + exp(0.64))\n # = [0.44028635073, 0.55971364926, 0.]\n # attention_distribution02\n # = [exp(-0.15), exp(-0.24), exp(0.09)]\n # / (exp(-0.15) + exp(-0.24) + exp(0.09))\n # = [0.31395396638, 0.28693232061, 0.399113713]\n if return_attention_scores:\n expected_scores = np.array(\n [[[1., 0., 0.], [0.44028635073, 0.55971364926, 0.],\n [0.31395396638, 0.28693232061, 0.399113713]]],\n dtype=np.float32)\n self.assertAllClose(expected_scores, actual_scores)\n # Expected tensor of shape [1, 3, 1].\n # expected000 = 0.5\n # expected010 = 0.44028635073 * 0.5 + 0.55971364926 * 0.8\n # = 0.66791409477\n # expected020 = 0.31395396638 * 0.5 +0.28693232061 * 0.8 -0.399113713 * 0.3\n # = 0.26678872577\n expected = np.array([[[0.5], [0.66791409477], [0.26678872577]]],\n dtype=np.float32)\n self.assertAllClose(expected, actual)\n\n def test_inputs_not_list(self):\n attention_layer = dense_attention.Attention()\n q = np.array([[[1.1]]], dtype=np.float32)\n with self.assertRaisesRegex(\n ValueError, 'Attention layer must be called on a list of inputs'):\n attention_layer(q)\n\n def test_inputs_too_short(self):\n attention_layer = dense_attention.Attention()\n q = np.array([[[1.1]]], dtype=np.float32)\n with self.assertRaisesRegex(\n ValueError, 'Attention layer accepts inputs list of length 2 or 3'):\n attention_layer([q])\n\n def test_inputs_too_long(self):\n attention_layer = dense_attention.Attention()\n q = np.array([[[1.1]]], dtype=np.float32)\n with self.assertRaisesRegex(\n ValueError, 'Attention layer accepts inputs list of length 2 or 3'):\n attention_layer([q, q, q, q])\n\n def test_mask_not_list(self):\n attention_layer = dense_attention.Attention()\n q = np.array([[[1.1]]], dtype=np.float32)\n mask = np.array([[True]], dtype=np.bool_)\n with self.assertRaisesRegex(ValueError,\n 'Attention layer mask must be a list'):\n attention_layer([q, q], mask=mask)\n\n def test_mask_too_short(self):\n attention_layer = dense_attention.Attention()\n q = np.array([[[1.1]]], dtype=np.float32)\n mask = np.array([[True]], dtype=np.bool_)\n with self.assertRaisesRegex(\n ValueError, 'Attention layer mask must be a list of length 2'):\n attention_layer([q, q], mask=[mask])\n\n def test_mask_too_long(self):\n attention_layer = dense_attention.Attention()\n q = np.array([[[1.1]]], dtype=np.float32)\n mask = np.array([[True]], dtype=np.bool_)\n with self.assertRaisesRegex(\n ValueError, 'Attention layer mask must be a list of length 2'):\n attention_layer([q, q], mask=[mask, mask, mask])\n\n def test_override_mask(self):\n attention_layer = dense_attention.Attention()\n q = core.Masking()(np.array([[[1.1]]], dtype=np.float32))\n mask = np.array([[False]], dtype=np.bool_)\n actual = attention_layer([q, q], mask=[mask, mask])\n self.assertAllClose([[[0]]], actual)\n\n def test_implicit_mask(self):\n attention_layer = dense_attention.Attention()\n q = core.Masking(1.1)(np.array([[[1.1], [1]]], dtype=np.float32))\n v = core.Masking(1.2)(np.array([[[1.2], [1]]], dtype=np.float32))\n actual = attention_layer([q, v])\n self.assertAllClose([[[0], [1]]], actual)\n\n @parameterized.named_parameters(\n ('', False),\n ('use_scale', True),\n )\n def test_serialization(self, use_scale):\n # Test serialization with use_scale\n layer = dense_attention.Attention(use_scale=use_scale)\n\n config = keras.layers.serialize(layer)\n new_layer = keras.layers.deserialize(config)\n self.assertEqual(new_layer.use_scale, use_scale)\n\n config = layer.get_config()\n new_layer = dense_attention.Attention.from_config(config)\n self.assertEqual(new_layer.use_scale, use_scale)\n\n\[email protected](combinations.combine(mode=['graph', 'eager']))\nclass AdditiveAttentionTest(tf.test.TestCase, parameterized.TestCase):\n\n def test_calculate_scores_one_dim(self):\n # Query tensor of shape [1, 1, 1]\n q = np.array([[[1.1]]], dtype=np.float32)\n # Key tensor of shape [1, 1, 1]\n k = np.array([[[1.6]]], dtype=np.float32)\n attention_layer = dense_attention.AdditiveAttention()\n attention_layer.build(input_shape=([1, 1, 1], [1, 1, 1]))\n # Scale tensor of shape [1]\n attention_layer.scale = np.array([[[0.5]]], dtype=np.float32)\n actual = attention_layer._calculate_scores(query=q, key=k)\n\n # Expected tensor of shape [1, 1, 1].\n # expected000 = 0.5 * tanh(1.1 + 1.6) = 0.49550372683\n expected = np.array([[[0.49550372683]]], dtype=np.float32)\n self.assertAllClose(expected, actual)\n\n def test_calculate_scores_multi_dim(self):\n # Query tensor of shape [1, 2, 4]\n q = np.array([[[1., 1.1, 1.2, 1.3], [2., 2.1, 2.2, 2.3]]], dtype=np.float32)\n # Key tensor of shape [1, 3, 4]\n k = np.array(\n [[[1.5, 1.6, 1.7, 1.8], [2.5, 2.6, 2.7, 2.8], [3.5, 3.6, 3.7, 3.8]]],\n dtype=np.float32)\n attention_layer = dense_attention.AdditiveAttention()\n attention_layer.build(input_shape=([1, 2, 4], [1, 3, 4]))\n # Scale tensor of shape [4]\n attention_layer.scale = np.array([[[0.5, 0.6, 0.7, 0.8]]], dtype=np.float32)\n actual = attention_layer._calculate_scores(query=q, key=k)\n\n # pylint:disable=line-too-long\n # expected000 = 0.5*tanh(1.+1.5) + 0.6*tanh(1.1+1.6) + 0.7*tanh(1.2+1.7) + 0.8*tanh(1.3+1.8) = 2.58044532581\n # expected001 = 0.5*tanh(1.+2.5) + 0.6*tanh(1.1+2.6) + 0.7*tanh(1.2+2.7) + 0.8*tanh(1.3+2.8) = 2.59734317449\n # expected002 = 0.5*tanh(1.+3.5) + 0.6*tanh(1.1+3.6) + 0.7*tanh(1.2+3.7) + 0.8*tanh(1.3+3.8) = 2.59964024652\n # expected010 = 0.5*tanh(2.+1.5) + 0.6*tanh(2.1+1.6) + 0.7*tanh(2.2+1.7) + 0.8*tanh(2.3+1.8) = 2.59734317449\n # expected011 = 0.5*tanh(2.+2.5) + 0.6*tanh(2.1+2.6) + 0.7*tanh(2.2+2.7) + 0.8*tanh(2.3+2.8) = 2.59964024652\n # expected012 = 0.5*tanh(2.+3.5) + 0.6*tanh(2.1+3.6) + 0.7*tanh(2.2+3.7) + 0.8*tanh(2.3+3.8) = 2.59995130916\n # pylint:enable=line-too-long\n expected = np.array([[[2.58044532581, 2.59734317449, 2.59964024652],\n [2.59734317449, 2.59964024652, 2.59995130916]]],\n dtype=np.float32)\n self.assertAllClose(expected, actual)\n\n def test_calculate_scores_one_dim_batch_size_two(self):\n # Query tensor of shape [2, 1, 1]\n q = np.array([[[1.1]], [[2.1]]], dtype=np.float32)\n # Key tensor of shape [2, 1, 1]\n k = np.array([[[1.6]], [[2.6]]], dtype=np.float32)\n attention_layer = dense_attention.AdditiveAttention()\n attention_layer.build(input_shape=([2, 1, 1], [2, 1, 1]))\n # Scale tensor of shape [1]\n attention_layer.scale = np.array([[[0.5]]], dtype=np.float32)\n actual = attention_layer._calculate_scores(query=q, key=k)\n\n # Expected tensor of shape [2, 1, 1].\n # expected000 = 0.5 * tanh(1.1 + 1.6) = 0.49550372683\n # expected100 = 0.5 * tanh(2.1 + 2.6) = 0.49991728277\n expected = np.array([[[0.49550372683]], [[0.49991728277]]],\n dtype=np.float32)\n self.assertAllClose(expected, actual)\n\n def test_shape(self):\n # Query tensor of shape [1, 2, 4]\n q = np.array([[[1., 1.1, 1.2, 1.3], [2., 2.1, 2.2, 2.3]]], dtype=np.float32)\n # Value tensor of shape [1, 3, 4]\n v = np.array(\n [[[1.5, 1.6, 1.7, 1.8], [2.5, 2.6, 2.7, 2.8], [3.5, 3.6, 3.7, 3.8]]],\n dtype=np.float32)\n # Value mask tensor of shape [1, 3]\n v_mask = np.array([[True, True, False]], dtype=np.bool_)\n attention_layer = dense_attention.AdditiveAttention()\n actual = attention_layer([q, v], mask=[None, v_mask])\n\n expected_shape = [1, 2, 4]\n self.assertAllEqual(expected_shape, tf.shape(actual))\n\n def test_shape_no_scale(self):\n # Query tensor of shape [1, 2, 4]\n q = np.array([[[1., 1.1, 1.2, 1.3], [2., 2.1, 2.2, 2.3]]], dtype=np.float32)\n # Value tensor of shape [1, 3, 4]\n v = np.array(\n [[[1.5, 1.6, 1.7, 1.8], [2.5, 2.6, 2.7, 2.8], [3.5, 3.6, 3.7, 3.8]]],\n dtype=np.float32)\n # Value mask tensor of shape [1, 3]\n v_mask = np.array([[True, True, False]], dtype=np.bool_)\n attention_layer = dense_attention.AdditiveAttention(use_scale=False)\n actual = attention_layer([q, v], mask=[None, v_mask])\n\n expected_shape = [1, 2, 4]\n self.assertAllEqual(expected_shape, tf.shape(actual))\n\n def test_shape_with_key(self):\n # Query tensor of shape [1, 2, 4]\n q = np.array([[[1., 1.1, 1.2, 1.3], [2., 2.1, 2.2, 2.3]]], dtype=np.float32)\n # Value tensor of shape [1, 3, 4]\n v = np.array(\n [[[1.5, 1.6, 1.7, 1.8], [2.5, 2.6, 2.7, 2.8], [3.5, 3.6, 3.7, 3.8]]],\n dtype=np.float32)\n # Key tensor of shape [1, 3, 4]\n k = np.array(\n [[[1.5, 1.6, 1.7, 1.8], [2.5, 2.6, 2.7, 2.8], [3.5, 3.6, 3.7, 3.8]]],\n dtype=np.float32)\n # Value mask tensor of shape [1, 3]\n v_mask = np.array([[True, True, False]], dtype=np.bool_)\n attention_layer = dense_attention.AdditiveAttention()\n actual = attention_layer([q, v, k], mask=[None, v_mask])\n\n expected_shape = [1, 2, 4]\n self.assertAllEqual(expected_shape, tf.shape(actual))\n\n def test_multi_dim(self):\n # Query tensor of shape [1, 1, 1]\n q = np.array([[[1.1]]], dtype=np.float32)\n # Value tensor of shape [1, 3, 1]\n v = np.array([[[1.6], [0.7], [-0.8]]], dtype=np.float32)\n # Value mask tensor of shape [1, 3]\n v_mask = np.array([[True, True, False]], dtype=np.bool_)\n attention_layer = dense_attention.AdditiveAttention()\n attention_layer.build(input_shape=([1, 1, 1], [1, 3, 1]))\n # Scale tensor of shape [1]\n attention_layer.scale = np.array([[[0.5]]], dtype=np.float32)\n actual = attention_layer([q, v], mask=[None, v_mask])\n\n # pylint:disable=line-too-long\n # Expected scores of shape [1, 1, 3]\n # scores = [[[0.5 * tanh(1.1 + 1.6), 0.5 * tanh(1.1 + 0.7), 0.5 * tanh(1.1 - 0.8)]]]\n # = [[[0.49550372683, 0.47340300642, 0.14565630622]]]\n # Expected attention distribution = softmax(scores) with zeros in\n # positions where v_mask == False.\n # => attention_distribution000\n # = exp(0.49550372683)/(exp(0.49550372683) + exp(0.47340300642))\n # = 0.50552495521\n # attention_distribution001\n # = exp(0.47340300642)/(exp(0.49550372683) + exp(0.47340300642))\n # = 0.49447504478\n # attention_distribution002 = 0\n #\n # Expected tensor of shape [1, 1, 1].\n # expected000 = 0.50552495521 * 1.6 + 0.49447504478 * 0.7 - 0 * 0.8\n # = 1.15497245968\n # pylint:enable=line-too-long\n expected = np.array([[[1.15497245968]]], dtype=np.float32)\n self.assertAllClose(expected, actual)\n\n def test_multi_dim_with_key(self):\n # Query tensor of shape [1, 1, 1]\n q = np.array([[[1.1]]], dtype=np.float32)\n # Value tensor of shape [1, 3, 1]\n v = np.array([[[0.5], [0.8], [-0.3]]], dtype=np.float32)\n # Key tensor of shape [1, 3, 1]\n k = np.array([[[1.6], [0.7], [-0.8]]], dtype=np.float32)\n # Value mask tensor of shape [1, 3]\n v_mask = np.array([[True, True, False]], dtype=np.bool_)\n attention_layer = dense_attention.AdditiveAttention()\n attention_layer.build(input_shape=([1, 1, 1], [1, 3, 1]))\n # Scale tensor of shape [1]\n attention_layer.scale = np.array([[[0.5]]], dtype=np.float32)\n actual = attention_layer([q, v, k], mask=[None, v_mask])\n\n # pylint:disable=line-too-long\n # Expected scores of shape [1, 1, 3]\n # scores = [[[0.5 * tanh(1.1 + 1.6), 0.5 * tanh(1.1 + 0.7), 0.5 * tanh(1.1 - 0.8)]]]\n # = [[[0.49550372683, 0.47340300642, 0.14565630622]]]\n # Expected attention distribution = softmax(scores) with zeros in\n # positions where v_mask == False.\n # => attention_distribution000\n # = exp(0.49550372683)/(exp(0.49550372683) + exp(0.47340300642))\n # = 0.50552495521\n # attention_distribution001\n # = exp(0.47340300642)/(exp(0.49550372683) + exp(0.47340300642))\n # = 0.49447504478\n # attention_distribution002 = 0\n #\n # Expected tensor of shape [1, 1, 1].\n # expected000 = 0.50552495521 * 0.5 + 0.49447504478 * 0.8 - 0 * 0.3\n # = 0.64834251342\n # pylint:enable=line-too-long\n expected = np.array([[[0.64834251342]]], dtype=np.float32)\n self.assertAllClose(expected, actual)\n\n def test_multi_dim_with_query_mask(self):\n # Query tensor of shape [1, 2, 1]\n q = np.array([[[1.1], [-0.5]]], dtype=np.float32)\n # Value tensor of shape [1, 3, 1]\n v = np.array([[[1.6], [0.7], [-0.8]]], dtype=np.float32)\n # Query mask tensor of shape [1, 2]\n q_mask = np.array([[True, False]], dtype=np.bool_)\n # Value mask tensor of shape [1, 3]\n v_mask = np.array([[True, True, False]], dtype=np.bool_)\n attention_layer = dense_attention.AdditiveAttention()\n attention_layer.build(input_shape=([1, 1, 1], [1, 3, 1]))\n # Scale tensor of shape [1]\n attention_layer.scale = np.array([[[0.5]]], dtype=np.float32)\n actual = attention_layer([q, v], mask=[q_mask, v_mask])\n\n # pylint:disable=line-too-long\n # Expected scores of shape [1, 2, 3]\n # scores = [[[0.5 * tanh(1.1 + 1.6), 0.5 * tanh(1.1 + 0.7), 0.5 * tanh(1.1 - 0.8)],\n # [0.5 * tanh(-0.5 + 1.6), 0.5 * tanh(-0.5 + 0.7), 0.5 * tanh(-0.5 - 0.8)]]]\n # = [[[0.49550372683, 0.47340300642, 0.14565630622],\n # [0.40024951088, 0.09868766011, -0.43086157965]]]\n # Expected attention distribution = softmax(scores) with zeros in\n # positions where v_mask == False.\n # => attention_distribution000\n # = exp(0.49550372683)/(exp(0.49550372683) + exp(0.47340300642))\n # = 0.50552495521\n # attention_distribution001\n # = exp(0.47340300642)/(exp(0.49550372683) + exp(0.47340300642))\n # = 0.49447504478\n # attention_distribution002 = 0\n # => attention_distribution010\n # = exp(0.40024951088)/(exp(0.40024951088) + exp(0.09868766011))\n # = 0.57482427975\n # attention_distribution011\n # = exp(0.09868766011)/(exp(0.40024951088) + exp(0.09868766011))\n # = 0.42517572025\n # attention_distribution012 = 0\n #\n # Expected tensor of shape [1, 2, 1] with zeros where q_mask == False.\n # expected000 = 0.50552495521 * 1.6 + 0.49447504478 * 0.7 - 0 * 0.8\n # = 1.15497245968\n # expected000 = 0\n # pylint:enable=line-too-long\n expected = np.array([[[1.15497245968], [0.]]], dtype=np.float32)\n self.assertAllClose(expected, actual)\n\n def test_serialization(self):\n # Test serialization with use_scale\n layer = dense_attention.AdditiveAttention(use_scale=True)\n\n config = keras.layers.serialize(layer)\n new_layer = keras.layers.deserialize(config)\n self.assertEqual(new_layer.use_scale, True)\n\n config = layer.get_config()\n new_layer = dense_attention.AdditiveAttention.from_config(config)\n self.assertEqual(new_layer.use_scale, True)\n\n @testing_utils.enable_v2_dtype_behavior\n def test_mixed_float16_policy(self):\n # Test case for GitHub issue:\n # https://github.com/tensorflow/tensorflow/issues/46064\n with policy.policy_scope('mixed_float16'):\n q = tf.cast(tf.random.uniform((2, 3, 4), seed=1), 'float16')\n v = tf.cast(tf.random.uniform((2, 3, 4), seed=2), 'float16')\n k = tf.cast(tf.random.uniform((2, 3, 4), seed=3), 'float16')\n layer = dense_attention.AdditiveAttention(causal=True)\n _ = layer([q, v, k])\n\n\[email protected](combinations.combine(mode=['graph', 'eager']))\nclass LowerTriangularMaskTest(tf.test.TestCase, parameterized.TestCase):\n\n def test_square_shape(self):\n actual = dense_attention._lower_triangular_mask([3, 3])\n expected = np.array(\n [[True, False, False], [True, True, False], [True, True, True]],\n dtype=np.bool_)\n self.assertAllEqual(expected, actual)\n\n def test_orthogonal_shape(self):\n actual = dense_attention._lower_triangular_mask([3, 2])\n expected = np.array([[True, False], [True, True], [True, True]],\n dtype=np.bool_)\n self.assertAllEqual(expected, actual)\n\n def test_three_dim(self):\n actual = dense_attention._lower_triangular_mask([1, 3, 3])\n expected = np.array(\n [[[True, False, False], [True, True, False], [True, True, True]]],\n dtype=np.bool_)\n self.assertAllEqual(expected, actual)\n\n\nif __name__ == '__main__':\n tf.test.main()\n" ]
[ [ "numpy.ones", "tensorflow.compat.v2.shape", "tensorflow.compat.v2.test.main", "numpy.array", "tensorflow.compat.v2.executing_eagerly", "tensorflow.compat.v2.random.uniform" ] ]
Fritingo/AlexNet_on_browser
[ "3e674dd84e25ee74f2efde77882b4faa788907c2" ]
[ "AlexNet/Alexnet_to_onnx.py" ]
[ "import torch\n\nfrom inference_Alexnet import AlexNet\n\n\ndef main():\n pytorch_model = AlexNet()\n pytorch_model.load_state_dict(torch.load('cifar100_Alexnet.pt'))\n pytorch_model.eval()\n dummy_input = torch.zeros(128*128*4)\n torch.onnx.export(pytorch_model, dummy_input, 'cifar100_Alexnet.onnx', verbose=True)\n\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "torch.zeros", "torch.onnx.export", "torch.load" ] ]
vincefn/silx
[ "4b239abfc90d2fa7d6ab61425f8bfc7b83c0f444" ]
[ "examples/plotStats.py" ]
[ "#!/usr/bin/env python\n# coding: utf-8\n# /*##########################################################################\n#\n# Copyright (c) 2016-2019 European Synchrotron Radiation Facility\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n#\n# ###########################################################################*/\n\"\"\"This script is a simple example of how to add your own statistic to a\n:class:`~silx.gui.plot.statsWidget.StatsWidget` from customs\n:class:`~silx.gui.plot.stats.Stats` and display it.\n\nOn this example we will:\n\n - show sum of values for each type\n - compute curve integrals (only for 'curve').\n - compute center of mass for all possible items\n\n.. note:: for now the possible types manged by the Stats are ('curve', 'image',\n 'scatter' and 'histogram')\n\"\"\"\n\n__authors__ = [\"H. Payno\"]\n__license__ = \"MIT\"\n__date__ = \"24/07/2018\"\n\n\nfrom silx.gui import qt\nfrom silx.gui.colors import Colormap\nfrom silx.gui.plot import Plot1D\nfrom silx.gui.plot.stats.stats import StatBase\nimport numpy\n\n\nclass Integral(StatBase):\n \"\"\"\n Simple calculation of the line integral\n \"\"\"\n def __init__(self):\n StatBase.__init__(self, name='integral', compatibleKinds=('curve',))\n\n def calculate(self, context):\n xData, yData = context.data\n return numpy.trapz(x=xData, y=yData)\n\n\nclass COM(StatBase):\n \"\"\"\n Compute data center of mass\n \"\"\"\n def __init__(self):\n StatBase.__init__(self, name='COM', description=\"Center of mass\")\n\n def calculate(self, context):\n if context.kind in ('curve', 'histogram'):\n xData, yData = context.data\n deno = numpy.sum(yData).astype(numpy.float32)\n if deno == 0.0:\n return 0.0\n else:\n return numpy.sum(xData * yData).astype(numpy.float32) / deno\n elif context.kind == 'scatter':\n xData, yData, values = context.data\n values = values.astype(numpy.float64)\n deno = numpy.sum(values)\n if deno == 0.0:\n return float('inf'), float('inf')\n else:\n comX = numpy.sum(xData * values) / deno\n comY = numpy.sum(yData * values) / deno\n return comX, comY\n\n\ndef main():\n app = qt.QApplication([])\n\n plot = Plot1D()\n\n x = numpy.arange(21)\n y = numpy.arange(21)\n plot.addCurve(x=x, y=y, legend='myCurve')\n plot.addCurve(x=x, y=(y + 5), legend='myCurve2')\n\n plot.setActiveCurve('myCurve')\n\n plot.addScatter(x=[0, 2, 5, 5, 12, 20],\n y=[2, 3, 4, 20, 15, 6],\n value=[5, 6, 7, 10, 90, 20],\n colormap=Colormap('viridis'),\n legend='myScatter')\n\n stats = [\n ('sum', numpy.sum),\n Integral(),\n (COM(), '{0:.2f}'),\n ]\n\n plot.getStatsWidget().setStats(stats)\n plot.getStatsWidget().parent().setVisible(True)\n\n plot.show()\n app.exec_()\n\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "numpy.arange", "numpy.trapz", "numpy.sum" ] ]
duncanmazza/ml_stock_prediction_api
[ "4cf6325ff1252511049b87bc46fa4d5b48acf4f3" ]
[ "src/CombinedModel.py" ]
[ "\"\"\"\nCode for the combined model approach.\n\n@author: Shashank Swaminathan\n\"\"\"\n\nfrom src.BayesReg import GPM\nfrom src.StockRNN import StockRNN\nimport pandas as pd\nimport numpy as np\nfrom datetime import datetime\nfrom datetime import date\n\nZERO_TIME = \" 00:00:00\"\n\nDEVICE = \"cuda\" # selects the gpu to be used\nTO_GPU_FAIL_MSG = \"Unable to successfully run model.to('{}'). If running in Collaboratory, make sure \" \\\n \"that you have enabled the GPU your settings\".format(DEVICE)\n\nclass CombinedModel:\n r\"\"\"\n Class for handling combined model operations.\n \"\"\"\n def __init__(self, ticker, comp_tickers):\n r\"\"\"\n init function. It will set up the StockRNN and GPM classes.\n\n :param ticker: Ticker of stocks to predict\n :param comp_tickers: List of tickers to compare desired ticker against. Used for StockRNN only.\n \"\"\"\n self.srnn = StockRNN(ticker, to_compare=comp_tickers,\n train_start_date=datetime(2012, 1, 1),\n train_end_date=datetime.today(),\n try_load_weights=False)\n self.cms = GPM(ticker)\n\n def train(self, start_date, pred_start, pred_end, mw=0.5, n_epochs=10):\n r\"\"\"\n Main training function. It runs both the LSTM and GP models and stores results in attributes.\n\n :param start_date: Training start date (for GP model only). Provide as datetime object.\n :param pred_start: Date to start predictions from. Provide as datetime object.\n :param pred_end: Date to end predictions. Provide as datetime object.\n :param mw: Model weight. Used to do weighted average between GP and LSTM. 0 is for only the LSTM, and 1 is for only the GP. Defaults to 0.5 (equal split).\n :param n_epochs: Number of epochs to train the LSTM. Defaults to 10.\n\n :returns: (Mean predictions [t, y], Upper/lower bounds of 2 std [t, y])\n \"\"\"\n dt_ps = date(pred_start.year, pred_start.month, pred_start.day)\n dt_pe = date(pred_end.year, pred_end.month, pred_end.day)\n self.n_days_pred = np.busday_count(dt_ps, dt_pe) + 1\n\n self.train_end = pred_start - pd.Timedelta(1, \"D\")\n return self._combo_shot(start_date, pred_start, pred_end,\n mw = mw, n_epochs = n_epochs)\n\n def _combo_shot(self, start_date, pred_start, pred_end, mw=0.5, n_epochs=10):\n r\"\"\"\n Helper function to actually do the combo model training. Runs the two models individually, aligns the two results in time, then adds the two generated distributions as a weighted sum. Sets attribute combo_vals equal to the result.\n\n :param start_date: Training start date (for GP model only). Provide as datetime object.\n :param pred_start: Date to start predictions from. Provide as datetime object.\n :param pred_end: Date to end predictions. Provide as datetime object.\n :param mw: Model weight. Used to do weighted average between GP and LSTM. 0 is for only the LSTM, and 1 is for only the GP. Defaults to 0.5 (equal split).\n :param n_epochs: Number of epochs to train the LSTM. Defaults to 10.\n \"\"\"\n self._srnn_train(pred_start, self.n_days_pred, n_epochs = n_epochs)\n self._cms_train(start_date, self.train_end, pred_end)\n m_combo = self.m_cms[-self.n_days_pred:]*(mw)+self.m_srnn*(1-mw)\n std_combo = self.std_cms[-self.n_days_pred:]*(mw)+self.std_srnn*(1-mw)\n\n xy_pred = [self.times, m_combo]\n upper = m_combo + 2*std_combo\n lower = m_combo - 2*std_combo\n band_x = np.append(self.times, self.times[::-1])\n band_y = np.append(lower, upper[::-1])\n std_bounds = [band_x, band_y]\n self.combo_vals = (xy_pred, std_bounds)\n\n def _srnn_train(self, pred_start, n_days_pred, n_epochs=10):\n r\"\"\"\n Helper function to train the LSTM using the StockRNN class. Generates upper and lower bounds of prediction based on mean and std. deviation. Sets attribute srnn_vals equal to result. Result is of form: ([time, mean prediction], [time, upper/lower bounds], [time, actual data prior to prediction], [time, actual data during prediction]).\n\n :param pred_start: Date to start predictions from. Provide as datetime object.\n :param n_days_pred: Number of days to predict ahead. Will only predict on business days.\n :param n_epochs: Number of epochs to train the LSTM. Defaults to 10.\n \"\"\"\n srdf = self.srnn.companies[0].data_frame\n srdfdt = pd.to_datetime(srdf.Date)\n raw_p_st_idx = srdfdt.searchsorted(pred_start)\n p_st_idx = raw_p_st_idx + srdf.index[0]\n raw_p_e_idx = raw_p_st_idx + self.n_days_pred\n try:\n self.srnn.to(DEVICE)\n self.srnn.__togpu__(True)\n except RuntimeError:\n print(TO_GPU_FAIL_MSG)\n except AssertionError:\n print(TO_GPU_FAIL_MSG)\n self.srnn.__togpu__(False)\n\n self.srnn.do_training(num_epochs=n_epochs)\n self.m_srnn, self.std_srnn = self.srnn.pred_in_conj(p_st_idx, n_days_pred)\n self.times = srdf.Date.iloc[raw_p_st_idx:raw_p_e_idx]\n self.m_srnn = np.array(self.m_srnn)\n self.std_srnn = np.array(self.std_srnn)\n\n times_td = srdf.Date.iloc[raw_p_st_idx-50:raw_p_st_idx-1]\n td_srnn = srdf.Close.iloc[raw_p_st_idx-50:raw_p_st_idx-1]\n a_srnn = srdf.Close.iloc[raw_p_st_idx:raw_p_e_idx]\n\n xy_pred = [self.times, self.m_srnn]\n upper = self.m_srnn + 2*self.std_srnn\n lower = self.m_srnn - 2*self.std_srnn\n band_x = np.append(self.times, self.times[::-1])\n band_y = np.append(lower, upper[::-1])\n std_bounds = [band_x, band_y]\n train_data = [times_td, td_srnn]\n test_data = [self.times, a_srnn]\n self.srnn_vals = (xy_pred, std_bounds, train_data, test_data)\n\n def _cms_train(self, start_date, train_end, pred_end):\n r\"\"\"\n Helper function to train the GP model using the GPM class. Sets attribute cms_vals equal to result. Result is of form: ([time, mean prediction], [time, upper/lower bounds], [time, actual data prior to prediction], [time, actual data during prediction]).\n\n :param start_date: Training start date (for GP model only). Provide as datetime object.\n :param train_end: Date to end training. Provide as datetime object.\n :param pred_end: Date to end predictions. Provide as datetime object. Assumes predictions begin right after training.\n \"\"\"\n xy_pred, std_bounds, train_data, test_data = self.cms.go(start_date=start_date,\n split_date=train_end,\n end_date=pred_end)\n self.m_cms = xy_pred[1]\n self.std_cms = xy_pred[2]\n self.cms_vals = (xy_pred, std_bounds, train_data, test_data)\n" ]
[ [ "numpy.busday_count", "numpy.append", "pandas.Timedelta", "pandas.to_datetime", "numpy.array" ] ]
naylor-b/OpenMDAO1
[ "49d82f6601b33db9bdcf7d146d030d55e3b62ef4" ]
[ "openmdao/solvers/test/test_ln_direct.py" ]
[ "\"\"\" Unit test for the DirectSolver linear solver. \"\"\"\n\nimport unittest\nimport numpy as np\n\nfrom openmdao.api import Group, Problem, IndepVarComp, ExecComp, DirectSolver, \\\n LinearGaussSeidel, Newton\nfrom openmdao.core.test.test_residual_sign import SimpleImplicitSL\nfrom openmdao.test.converge_diverge import ConvergeDiverge, SingleDiamond, \\\n ConvergeDivergeGroups, SingleDiamondGrouped\nfrom openmdao.test.sellar import SellarStateConnection\nfrom openmdao.test.simple_comps import SimpleCompDerivMatVec, FanOut, FanIn, \\\n FanOutGrouped, FanInGrouped, ArrayComp2D\nfrom openmdao.test.util import assert_rel_error\n\n\nclass TestDirectSolver(unittest.TestCase):\n\n def test_simple_matvec(self):\n group = Group()\n group.add('x_param', IndepVarComp('x', 1.0), promotes=['*'])\n group.add('mycomp', SimpleCompDerivMatVec(), promotes=['x', 'y'])\n\n prob = Problem()\n prob.root = group\n prob.root.ln_solver = DirectSolver()\n prob.setup(check=False)\n prob.run()\n\n J = prob.calc_gradient(['x'], ['y'], mode='fwd', return_format='dict')\n assert_rel_error(self, J['y']['x'][0][0], 2.0, 1e-6)\n\n J = prob.calc_gradient(['x'], ['y'], mode='rev', return_format='dict')\n assert_rel_error(self, J['y']['x'][0][0], 2.0, 1e-6)\n\n def test_simple_matvec_subbed(self):\n group = Group()\n group.add('mycomp', SimpleCompDerivMatVec(), promotes=['x', 'y'])\n\n prob = Problem()\n prob.root = Group()\n prob.root.add('x_param', IndepVarComp('x', 1.0), promotes=['*'])\n prob.root.add('sub', group, promotes=['*'])\n\n prob.root.ln_solver = DirectSolver()\n prob.setup(check=False)\n prob.run()\n\n J = prob.calc_gradient(['x'], ['y'], mode='fwd', return_format='dict')\n assert_rel_error(self, J['y']['x'][0][0], 2.0, 1e-6)\n\n J = prob.calc_gradient(['x'], ['y'], mode='rev', return_format='dict')\n assert_rel_error(self, J['y']['x'][0][0], 2.0, 1e-6)\n\n def test_array2D(self):\n group = Group()\n group.add('x_param', IndepVarComp('x', np.ones((2, 2))), promotes=['*'])\n group.add('mycomp', ArrayComp2D(), promotes=['x', 'y'])\n\n prob = Problem()\n prob.root = group\n prob.root.ln_solver = DirectSolver()\n prob.setup(check=False)\n prob.run()\n\n J = prob.calc_gradient(['x'], ['y'], mode='fwd', return_format='dict')\n Jbase = prob.root.mycomp._jacobian_cache\n diff = np.linalg.norm(J['y']['x'] - Jbase['y', 'x'])\n assert_rel_error(self, diff, 0.0, 1e-8)\n\n J = prob.calc_gradient(['x'], ['y'], mode='rev', return_format='dict')\n diff = np.linalg.norm(J['y']['x'] - Jbase['y', 'x'])\n assert_rel_error(self, diff, 0.0, 1e-8)\n\n def test_simple_in_group_matvec(self):\n group = Group()\n sub = group.add('sub', Group(), promotes=['x', 'y'])\n group.add('x_param', IndepVarComp('x', 1.0), promotes=['*'])\n sub.add('mycomp', SimpleCompDerivMatVec(), promotes=['x', 'y'])\n\n prob = Problem()\n prob.root = group\n prob.root.ln_solver = DirectSolver()\n prob.setup(check=False)\n prob.run()\n\n J = prob.calc_gradient(['x'], ['y'], mode='fwd', return_format='dict')\n assert_rel_error(self, J['y']['x'][0][0], 2.0, 1e-6)\n\n J = prob.calc_gradient(['x'], ['y'], mode='rev', return_format='dict')\n assert_rel_error(self, J['y']['x'][0][0], 2.0, 1e-6)\n\n def test_simple_jac(self):\n group = Group()\n group.add('x_param', IndepVarComp('x', 1.0), promotes=['*'])\n group.add('mycomp', ExecComp(['y=2.0*x']), promotes=['x', 'y'])\n\n prob = Problem()\n prob.root = group\n prob.root.ln_solver = DirectSolver()\n prob.setup(check=False)\n prob.run()\n\n J = prob.calc_gradient(['x'], ['y'], mode='fwd', return_format='dict')\n assert_rel_error(self, J['y']['x'][0][0], 2.0, 1e-6)\n\n J = prob.calc_gradient(['x'], ['y'], mode='rev', return_format='dict')\n assert_rel_error(self, J['y']['x'][0][0], 2.0, 1e-6)\n\n def test_fan_out(self):\n\n prob = Problem()\n prob.root = FanOut()\n prob.root.ln_solver = DirectSolver()\n prob.setup(check=False)\n prob.run()\n\n indep_list = ['p.x']\n unknown_list = ['comp2.y', \"comp3.y\"]\n\n J = prob.calc_gradient(indep_list, unknown_list, mode='fwd', return_format='dict')\n assert_rel_error(self, J['comp2.y']['p.x'][0][0], -6.0, 1e-6)\n assert_rel_error(self, J['comp3.y']['p.x'][0][0], 15.0, 1e-6)\n\n J = prob.calc_gradient(indep_list, unknown_list, mode='rev', return_format='dict')\n assert_rel_error(self, J['comp2.y']['p.x'][0][0], -6.0, 1e-6)\n assert_rel_error(self, J['comp3.y']['p.x'][0][0], 15.0, 1e-6)\n\n def test_fan_out_grouped(self):\n\n prob = Problem()\n prob.root = FanOutGrouped()\n prob.root.ln_solver = DirectSolver()\n prob.setup(check=False)\n prob.run()\n\n indep_list = ['p.x']\n unknown_list = ['sub.comp2.y', \"sub.comp3.y\"]\n\n J = prob.calc_gradient(indep_list, unknown_list, mode='fwd', return_format='dict')\n assert_rel_error(self, J['sub.comp2.y']['p.x'][0][0], -6.0, 1e-6)\n assert_rel_error(self, J['sub.comp3.y']['p.x'][0][0], 15.0, 1e-6)\n\n J = prob.calc_gradient(indep_list, unknown_list, mode='rev', return_format='dict')\n assert_rel_error(self, J['sub.comp2.y']['p.x'][0][0], -6.0, 1e-6)\n assert_rel_error(self, J['sub.comp3.y']['p.x'][0][0], 15.0, 1e-6)\n\n def test_fan_in(self):\n\n prob = Problem()\n prob.root = FanIn()\n prob.root.ln_solver = DirectSolver()\n prob.setup(check=False)\n prob.run()\n\n indep_list = ['p1.x1', 'p2.x2']\n unknown_list = ['comp3.y']\n\n J = prob.calc_gradient(indep_list, unknown_list, mode='fwd', return_format='dict')\n assert_rel_error(self, J['comp3.y']['p1.x1'][0][0], -6.0, 1e-6)\n assert_rel_error(self, J['comp3.y']['p2.x2'][0][0], 35.0, 1e-6)\n\n J = prob.calc_gradient(indep_list, unknown_list, mode='rev', return_format='dict')\n assert_rel_error(self, J['comp3.y']['p1.x1'][0][0], -6.0, 1e-6)\n assert_rel_error(self, J['comp3.y']['p2.x2'][0][0], 35.0, 1e-6)\n\n def test_fan_in_grouped(self):\n\n prob = Problem()\n prob.root = FanInGrouped()\n prob.root.ln_solver = DirectSolver()\n prob.setup(check=False)\n prob.run()\n\n indep_list = ['p1.x1', 'p2.x2']\n unknown_list = ['comp3.y']\n\n J = prob.calc_gradient(indep_list, unknown_list, mode='fwd', return_format='dict')\n assert_rel_error(self, J['comp3.y']['p1.x1'][0][0], -6.0, 1e-6)\n assert_rel_error(self, J['comp3.y']['p2.x2'][0][0], 35.0, 1e-6)\n\n J = prob.calc_gradient(indep_list, unknown_list, mode='rev', return_format='dict')\n assert_rel_error(self, J['comp3.y']['p1.x1'][0][0], -6.0, 1e-6)\n assert_rel_error(self, J['comp3.y']['p2.x2'][0][0], 35.0, 1e-6)\n\n def test_converge_diverge(self):\n\n prob = Problem()\n prob.root = ConvergeDiverge()\n prob.root.ln_solver = DirectSolver()\n prob.setup(check=False)\n prob.run()\n\n indep_list = ['p.x']\n unknown_list = ['comp7.y1']\n\n prob.run()\n\n # Make sure value is fine.\n assert_rel_error(self, prob['comp7.y1'], -102.7, 1e-6)\n\n J = prob.calc_gradient(indep_list, unknown_list, mode='fwd', return_format='dict')\n assert_rel_error(self, J['comp7.y1']['p.x'][0][0], -40.75, 1e-6)\n\n J = prob.calc_gradient(indep_list, unknown_list, mode='rev', return_format='dict')\n assert_rel_error(self, J['comp7.y1']['p.x'][0][0], -40.75, 1e-6)\n\n J = prob.calc_gradient(indep_list, unknown_list, mode='fd', return_format='dict')\n assert_rel_error(self, J['comp7.y1']['p.x'][0][0], -40.75, 1e-6)\n\n def test_converge_diverge_groups(self):\n\n prob = Problem()\n prob.root = ConvergeDivergeGroups()\n prob.root.ln_solver = DirectSolver()\n prob.setup(check=False)\n prob.run()\n\n # Make sure value is fine.\n assert_rel_error(self, prob['comp7.y1'], -102.7, 1e-6)\n\n indep_list = ['p.x']\n unknown_list = ['comp7.y1']\n\n J = prob.calc_gradient(indep_list, unknown_list, mode='fwd', return_format='dict')\n assert_rel_error(self, J['comp7.y1']['p.x'][0][0], -40.75, 1e-6)\n\n J = prob.calc_gradient(indep_list, unknown_list, mode='rev', return_format='dict')\n assert_rel_error(self, J['comp7.y1']['p.x'][0][0], -40.75, 1e-6)\n\n J = prob.calc_gradient(indep_list, unknown_list, mode='fd', return_format='dict')\n assert_rel_error(self, J['comp7.y1']['p.x'][0][0], -40.75, 1e-6)\n\n def test_single_diamond(self):\n\n prob = Problem()\n prob.root = SingleDiamond()\n prob.root.ln_solver = DirectSolver()\n prob.setup(check=False)\n prob.run()\n\n indep_list = ['p.x']\n unknown_list = ['comp4.y1', 'comp4.y2']\n\n J = prob.calc_gradient(indep_list, unknown_list, mode='fwd', return_format='dict')\n assert_rel_error(self, J['comp4.y1']['p.x'][0][0], 25, 1e-6)\n assert_rel_error(self, J['comp4.y2']['p.x'][0][0], -40.5, 1e-6)\n\n J = prob.calc_gradient(indep_list, unknown_list, mode='rev', return_format='dict')\n assert_rel_error(self, J['comp4.y1']['p.x'][0][0], 25, 1e-6)\n assert_rel_error(self, J['comp4.y2']['p.x'][0][0], -40.5, 1e-6)\n\n def test_single_diamond_grouped(self):\n\n prob = Problem()\n prob.root = SingleDiamondGrouped()\n prob.root.ln_solver = DirectSolver()\n prob.setup(check=False)\n prob.run()\n\n indep_list = ['p.x']\n unknown_list = ['comp4.y1', 'comp4.y2']\n\n J = prob.calc_gradient(indep_list, unknown_list, mode='fwd', return_format='dict')\n assert_rel_error(self, J['comp4.y1']['p.x'][0][0], 25, 1e-6)\n assert_rel_error(self, J['comp4.y2']['p.x'][0][0], -40.5, 1e-6)\n\n J = prob.calc_gradient(indep_list, unknown_list, mode='rev', return_format='dict')\n assert_rel_error(self, J['comp4.y1']['p.x'][0][0], 25, 1e-6)\n assert_rel_error(self, J['comp4.y2']['p.x'][0][0], -40.5, 1e-6)\n\n J = prob.calc_gradient(indep_list, unknown_list, mode='fd', return_format='dict')\n assert_rel_error(self, J['comp4.y1']['p.x'][0][0], 25, 1e-6)\n assert_rel_error(self, J['comp4.y2']['p.x'][0][0], -40.5, 1e-6)\n\n def test_sellar_derivs(self):\n\n prob = Problem()\n prob.root = SellarStateConnection()\n prob.root.ln_solver = DirectSolver()\n\n prob.root.nl_solver.options['atol'] = 1e-12\n prob.setup(check=False)\n prob.run()\n\n # Just make sure we are at the right answer\n assert_rel_error(self, prob['y1'], 25.58830273, .00001)\n assert_rel_error(self, prob['d1.y2'], 12.05848819, .00001)\n\n indep_list = ['x', 'z']\n unknown_list = ['obj', 'con1', 'con2']\n\n Jbase = {}\n Jbase['con1'] = {}\n Jbase['con1']['x'] = -0.98061433\n Jbase['con1']['z'] = np.array([-9.61002285, -0.78449158])\n Jbase['con2'] = {}\n Jbase['con2']['x'] = 0.09692762\n Jbase['con2']['z'] = np.array([1.94989079, 1.0775421 ])\n Jbase['obj'] = {}\n Jbase['obj']['x'] = 2.98061392\n Jbase['obj']['z'] = np.array([9.61001155, 1.78448534])\n\n J = prob.calc_gradient(indep_list, unknown_list, mode='fwd', return_format='dict')\n for key1, val1 in Jbase.items():\n for key2, val2 in val1.items():\n assert_rel_error(self, J[key1][key2], val2, .00001)\n\n J = prob.calc_gradient(indep_list, unknown_list, mode='rev', return_format='dict')\n for key1, val1 in Jbase.items():\n for key2, val2 in val1.items():\n assert_rel_error(self, J[key1][key2], val2, .00001)\n\n def test_implicit_solve_linear(self):\n\n p = Problem()\n p.root = Group()\n\n dvars = ( ('a', 3.), ('b', 10.))\n p.root.add('desvars', IndepVarComp(dvars), promotes=['a', 'b'])\n\n sg = p.root.add('sg', Group(), promotes=[\"*\"])\n sg.add('si', SimpleImplicitSL(), promotes=['a', 'b', 'x'])\n\n p.root.add('func', ExecComp('f = 2*x0+a'), promotes=['f', 'x0', 'a'])\n p.root.connect('x', 'x0', src_indices=[1])\n\n p.driver.add_objective('f')\n p.driver.add_desvar('a')\n\n p.root.nl_solver = Newton()\n p.root.nl_solver.options['rtol'] = 1e-10\n p.root.nl_solver.options['atol'] = 1e-10\n p.root.ln_solver = DirectSolver()\n\n p.setup(check=False)\n p['x'] = np.array([1.5, 2.])\n\n p.run()\n J = p.calc_gradient(['a'], ['f'], mode='rev')\n assert_rel_error(self, J[0][0], 1.57735, 1e-6)\n\n\nclass TestDirectSolverAssemble(unittest.TestCase):\n \"\"\" Tests the DirectSolver using the method that assembles a Jacobian.\"\"\"\n\n def test_simple_matvec(self):\n group = Group()\n group.add('x_param', IndepVarComp('x', 1.0), promotes=['*'])\n group.add('mycomp', SimpleCompDerivMatVec(), promotes=['x', 'y'])\n\n prob = Problem()\n prob.root = group\n prob.root.ln_solver = DirectSolver()\n prob.root.ln_solver.options['jacobian_method'] = 'assemble'\n prob.setup(check=False)\n prob.run()\n\n with self.assertRaises(RuntimeError) as cm:\n J = prob.calc_gradient(['x'], ['y'], mode='fwd', return_format='dict')\n\n expected_msg = \"The 'assemble' jacobian_method is not supported when \" + \\\n \"'apply_linear' is used on a component (mycomp).\"\n\n self.assertEqual(str(cm.exception), expected_msg)\n\n def test_simple_matvec_subbed(self):\n group = Group()\n group.add('mycomp', SimpleCompDerivMatVec(), promotes=['x', 'y'])\n\n prob = Problem()\n prob.root = Group()\n prob.root.add('x_param', IndepVarComp('x', 1.0), promotes=['*'])\n prob.root.add('sub', group, promotes=['*'])\n\n prob.root.ln_solver = DirectSolver()\n prob.root.ln_solver.options['jacobian_method'] = 'assemble'\n prob.setup(check=False)\n prob.run()\n\n with self.assertRaises(RuntimeError) as cm:\n J = prob.calc_gradient(['x'], ['y'], mode='fwd', return_format='dict')\n\n expected_msg = \"The 'assemble' jacobian_method is not supported when \" + \\\n \"'apply_linear' is used on a component (sub.mycomp).\"\n\n self.assertEqual(str(cm.exception), expected_msg)\n\n def test_array2D(self):\n group = Group()\n group.add('x_param', IndepVarComp('x', np.ones((2, 2))), promotes=['*'])\n group.add('mycomp', ArrayComp2D(), promotes=['x', 'y'])\n\n prob = Problem()\n prob.root = group\n prob.root.ln_solver = DirectSolver()\n prob.root.ln_solver.options['jacobian_method'] = 'assemble'\n prob.setup(check=False)\n prob.run()\n\n J = prob.calc_gradient(['x'], ['y'], mode='fwd', return_format='dict')\n Jbase = prob.root.mycomp._jacobian_cache\n diff = np.linalg.norm(J['y']['x'] - Jbase['y', 'x'])\n assert_rel_error(self, diff, 0.0, 1e-8)\n\n J = prob.calc_gradient(['x'], ['y'], mode='rev', return_format='dict')\n diff = np.linalg.norm(J['y']['x'] - Jbase['y', 'x'])\n assert_rel_error(self, diff, 0.0, 1e-8)\n\n def test_array2D_no_decompose(self):\n group = Group()\n group.add('x_param', IndepVarComp('x', np.ones((2, 2))), promotes=['*'])\n group.add('mycomp', ArrayComp2D(), promotes=['x', 'y'])\n\n prob = Problem()\n prob.root = group\n prob.root.ln_solver = DirectSolver()\n prob.root.ln_solver.options['jacobian_method'] = 'assemble'\n prob.root.ln_solver.options['solve_method'] = 'solve'\n prob.setup(check=False)\n prob.run()\n\n J = prob.calc_gradient(['x'], ['y'], mode='fwd', return_format='dict')\n Jbase = prob.root.mycomp._jacobian_cache\n diff = np.linalg.norm(J['y']['x'] - Jbase['y', 'x'])\n assert_rel_error(self, diff, 0.0, 1e-8)\n\n J = prob.calc_gradient(['x'], ['y'], mode='rev', return_format='dict')\n diff = np.linalg.norm(J['y']['x'] - Jbase['y', 'x'])\n assert_rel_error(self, diff, 0.0, 1e-8)\n\n def test_simple_in_group_matvec(self):\n group = Group()\n sub = group.add('sub', Group(), promotes=['x', 'y'])\n group.add('x_param', IndepVarComp('x', 1.0), promotes=['*'])\n sub.add('mycomp', SimpleCompDerivMatVec(), promotes=['x', 'y'])\n\n prob = Problem()\n prob.root = group\n prob.root.ln_solver = DirectSolver()\n prob.root.ln_solver.options['jacobian_method'] = 'assemble'\n prob.setup(check=False)\n prob.run()\n\n with self.assertRaises(RuntimeError) as cm:\n J = prob.calc_gradient(['x'], ['y'], mode='fwd', return_format='dict')\n\n expected_msg = \"The 'assemble' jacobian_method is not supported when \" + \\\n \"'apply_linear' is used on a component (sub.mycomp).\"\n\n self.assertEqual(str(cm.exception), expected_msg)\n\n def test_simple_jac(self):\n group = Group()\n group.add('x_param', IndepVarComp('x', 1.0), promotes=['*'])\n group.add('mycomp', ExecComp(['y=2.0*x']), promotes=['x', 'y'])\n\n prob = Problem()\n prob.root = group\n prob.root.ln_solver = DirectSolver()\n prob.root.ln_solver.options['jacobian_method'] = 'assemble'\n prob.setup(check=False)\n prob.run()\n\n J = prob.calc_gradient(['x'], ['y'], mode='fwd', return_format='dict')\n assert_rel_error(self, J['y']['x'][0][0], 2.0, 1e-6)\n\n J = prob.calc_gradient(['x'], ['y'], mode='rev', return_format='dict')\n assert_rel_error(self, J['y']['x'][0][0], 2.0, 1e-6)\n\n def test_fan_out(self):\n\n prob = Problem()\n prob.root = FanOut()\n prob.root.ln_solver = DirectSolver()\n prob.root.ln_solver.options['jacobian_method'] = 'assemble'\n prob.setup(check=False)\n prob.run()\n\n indep_list = ['p.x']\n unknown_list = ['comp2.y', \"comp3.y\"]\n\n J = prob.calc_gradient(indep_list, unknown_list, mode='fwd', return_format='dict')\n assert_rel_error(self, J['comp2.y']['p.x'][0][0], -6.0, 1e-6)\n assert_rel_error(self, J['comp3.y']['p.x'][0][0], 15.0, 1e-6)\n\n J = prob.calc_gradient(indep_list, unknown_list, mode='rev', return_format='dict')\n assert_rel_error(self, J['comp2.y']['p.x'][0][0], -6.0, 1e-6)\n assert_rel_error(self, J['comp3.y']['p.x'][0][0], 15.0, 1e-6)\n\n def test_fan_out_grouped(self):\n\n prob = Problem()\n prob.root = FanOutGrouped()\n prob.root.ln_solver = DirectSolver()\n prob.root.ln_solver.options['jacobian_method'] = 'assemble'\n prob.setup(check=False)\n prob.run()\n\n indep_list = ['p.x']\n unknown_list = ['sub.comp2.y', \"sub.comp3.y\"]\n\n J = prob.calc_gradient(indep_list, unknown_list, mode='fwd', return_format='dict')\n assert_rel_error(self, J['sub.comp2.y']['p.x'][0][0], -6.0, 1e-6)\n assert_rel_error(self, J['sub.comp3.y']['p.x'][0][0], 15.0, 1e-6)\n\n J = prob.calc_gradient(indep_list, unknown_list, mode='rev', return_format='dict')\n assert_rel_error(self, J['sub.comp2.y']['p.x'][0][0], -6.0, 1e-6)\n assert_rel_error(self, J['sub.comp3.y']['p.x'][0][0], 15.0, 1e-6)\n\n def test_fan_in(self):\n\n prob = Problem()\n prob.root = FanIn()\n prob.root.ln_solver = DirectSolver()\n prob.root.ln_solver.options['jacobian_method'] = 'assemble'\n prob.setup(check=False)\n prob.run()\n\n indep_list = ['p1.x1', 'p2.x2']\n unknown_list = ['comp3.y']\n\n J = prob.calc_gradient(indep_list, unknown_list, mode='fwd', return_format='dict')\n assert_rel_error(self, J['comp3.y']['p1.x1'][0][0], -6.0, 1e-6)\n assert_rel_error(self, J['comp3.y']['p2.x2'][0][0], 35.0, 1e-6)\n\n J = prob.calc_gradient(indep_list, unknown_list, mode='rev', return_format='dict')\n assert_rel_error(self, J['comp3.y']['p1.x1'][0][0], -6.0, 1e-6)\n assert_rel_error(self, J['comp3.y']['p2.x2'][0][0], 35.0, 1e-6)\n\n def test_fan_in_grouped(self):\n\n prob = Problem()\n prob.root = FanInGrouped()\n prob.root.ln_solver = DirectSolver()\n prob.root.ln_solver.options['jacobian_method'] = 'assemble'\n prob.setup(check=False)\n prob.run()\n\n indep_list = ['p1.x1', 'p2.x2']\n unknown_list = ['comp3.y']\n\n J = prob.calc_gradient(indep_list, unknown_list, mode='fwd', return_format='dict')\n assert_rel_error(self, J['comp3.y']['p1.x1'][0][0], -6.0, 1e-6)\n assert_rel_error(self, J['comp3.y']['p2.x2'][0][0], 35.0, 1e-6)\n\n J = prob.calc_gradient(indep_list, unknown_list, mode='rev', return_format='dict')\n assert_rel_error(self, J['comp3.y']['p1.x1'][0][0], -6.0, 1e-6)\n assert_rel_error(self, J['comp3.y']['p2.x2'][0][0], 35.0, 1e-6)\n\n def test_converge_diverge(self):\n\n prob = Problem()\n prob.root = ConvergeDiverge()\n prob.root.ln_solver = DirectSolver()\n prob.root.ln_solver.options['jacobian_method'] = 'assemble'\n prob.setup(check=False)\n prob.run()\n\n indep_list = ['p.x']\n unknown_list = ['comp7.y1']\n\n prob.run()\n\n # Make sure value is fine.\n assert_rel_error(self, prob['comp7.y1'], -102.7, 1e-6)\n\n J = prob.calc_gradient(indep_list, unknown_list, mode='fwd', return_format='dict')\n assert_rel_error(self, J['comp7.y1']['p.x'][0][0], -40.75, 1e-6)\n\n J = prob.calc_gradient(indep_list, unknown_list, mode='rev', return_format='dict')\n assert_rel_error(self, J['comp7.y1']['p.x'][0][0], -40.75, 1e-6)\n\n J = prob.calc_gradient(indep_list, unknown_list, mode='fd', return_format='dict')\n assert_rel_error(self, J['comp7.y1']['p.x'][0][0], -40.75, 1e-6)\n\n def test_converge_diverge_groups(self):\n\n prob = Problem()\n prob.root = ConvergeDivergeGroups()\n prob.root.ln_solver = DirectSolver()\n prob.root.ln_solver.options['jacobian_method'] = 'assemble'\n prob.setup(check=False)\n prob.run()\n\n # Make sure value is fine.\n assert_rel_error(self, prob['comp7.y1'], -102.7, 1e-6)\n\n indep_list = ['p.x']\n unknown_list = ['comp7.y1']\n\n J = prob.calc_gradient(indep_list, unknown_list, mode='fwd', return_format='dict')\n assert_rel_error(self, J['comp7.y1']['p.x'][0][0], -40.75, 1e-6)\n\n J = prob.calc_gradient(indep_list, unknown_list, mode='rev', return_format='dict')\n assert_rel_error(self, J['comp7.y1']['p.x'][0][0], -40.75, 1e-6)\n\n J = prob.calc_gradient(indep_list, unknown_list, mode='fd', return_format='dict')\n assert_rel_error(self, J['comp7.y1']['p.x'][0][0], -40.75, 1e-6)\n\n def test_single_diamond(self):\n\n prob = Problem()\n prob.root = SingleDiamond()\n prob.root.ln_solver = DirectSolver()\n prob.root.ln_solver.options['jacobian_method'] = 'assemble'\n prob.setup(check=False)\n prob.run()\n\n indep_list = ['p.x']\n unknown_list = ['comp4.y1', 'comp4.y2']\n\n J = prob.calc_gradient(indep_list, unknown_list, mode='fwd', return_format='dict')\n assert_rel_error(self, J['comp4.y1']['p.x'][0][0], 25, 1e-6)\n assert_rel_error(self, J['comp4.y2']['p.x'][0][0], -40.5, 1e-6)\n\n J = prob.calc_gradient(indep_list, unknown_list, mode='rev', return_format='dict')\n assert_rel_error(self, J['comp4.y1']['p.x'][0][0], 25, 1e-6)\n assert_rel_error(self, J['comp4.y2']['p.x'][0][0], -40.5, 1e-6)\n\n def test_single_diamond_grouped(self):\n\n prob = Problem()\n prob.root = SingleDiamondGrouped()\n prob.root.ln_solver = DirectSolver()\n prob.root.ln_solver.options['jacobian_method'] = 'assemble'\n prob.setup(check=False)\n prob.run()\n\n indep_list = ['p.x']\n unknown_list = ['comp4.y1', 'comp4.y2']\n\n J = prob.calc_gradient(indep_list, unknown_list, mode='fwd', return_format='dict')\n assert_rel_error(self, J['comp4.y1']['p.x'][0][0], 25, 1e-6)\n assert_rel_error(self, J['comp4.y2']['p.x'][0][0], -40.5, 1e-6)\n\n J = prob.calc_gradient(indep_list, unknown_list, mode='rev', return_format='dict')\n assert_rel_error(self, J['comp4.y1']['p.x'][0][0], 25, 1e-6)\n assert_rel_error(self, J['comp4.y2']['p.x'][0][0], -40.5, 1e-6)\n\n J = prob.calc_gradient(indep_list, unknown_list, mode='fd', return_format='dict')\n assert_rel_error(self, J['comp4.y1']['p.x'][0][0], 25, 1e-6)\n assert_rel_error(self, J['comp4.y2']['p.x'][0][0], -40.5, 1e-6)\n\n def test_sellar_derivs(self):\n\n prob = Problem()\n prob.root = SellarStateConnection()\n prob.root.ln_solver = DirectSolver()\n prob.root.ln_solver.options['jacobian_method'] = 'assemble'\n\n prob.root.nl_solver.options['atol'] = 1e-12\n prob.setup(check=False)\n prob.run()\n\n # Just make sure we are at the right answer\n assert_rel_error(self, prob['y1'], 25.58830273, .00001)\n assert_rel_error(self, prob['d1.y2'], 12.05848819, .00001)\n\n indep_list = ['x', 'z']\n unknown_list = ['obj', 'con1', 'con2']\n\n Jbase = {}\n Jbase['con1'] = {}\n Jbase['con1']['x'] = -0.98061433\n Jbase['con1']['z'] = np.array([-9.61002285, -0.78449158])\n Jbase['con2'] = {}\n Jbase['con2']['x'] = 0.09692762\n Jbase['con2']['z'] = np.array([1.94989079, 1.0775421 ])\n Jbase['obj'] = {}\n Jbase['obj']['x'] = 2.98061392\n Jbase['obj']['z'] = np.array([9.61001155, 1.78448534])\n\n J = prob.calc_gradient(indep_list, unknown_list, mode='fwd', return_format='dict')\n for key1, val1 in Jbase.items():\n for key2, val2 in val1.items():\n assert_rel_error(self, J[key1][key2], val2, .00001)\n\n J = prob.calc_gradient(indep_list, unknown_list, mode='rev', return_format='dict')\n for key1, val1 in Jbase.items():\n for key2, val2 in val1.items():\n assert_rel_error(self, J[key1][key2], val2, .00001)\n\n def test_sellar_derivs_under_lin_GS(self):\n\n prob = Problem()\n prob.root = Group()\n prob.root.ln_solver = LinearGaussSeidel()\n nest = prob.root.add('nest', SellarStateConnection())\n nest.ln_solver = DirectSolver()\n nest.ln_solver.options['jacobian_method'] = 'assemble'\n\n nest.nl_solver.options['atol'] = 1e-12\n prob.setup(check=False)\n prob.run()\n\n # Just make sure we are at the right answer\n assert_rel_error(self, prob['nest.y1'], 25.58830273, .00001)\n assert_rel_error(self, prob['nest.d1.y2'], 12.05848819, .00001)\n\n indep_list = ['nest.x', 'nest.z']\n unknown_list = ['nest.obj', 'nest.con1', 'nest.con2']\n\n Jbase = {}\n Jbase['nest.con1'] = {}\n Jbase['nest.con1']['nest.x'] = -0.98061433\n Jbase['nest.con1']['nest.z'] = np.array([-9.61002285, -0.78449158])\n Jbase['nest.con2'] = {}\n Jbase['nest.con2']['nest.x'] = 0.09692762\n Jbase['nest.con2']['nest.z'] = np.array([1.94989079, 1.0775421 ])\n Jbase['nest.obj'] = {}\n Jbase['nest.obj']['nest.x'] = 2.98061392\n Jbase['nest.obj']['nest.z'] = np.array([9.61001155, 1.78448534])\n\n J = prob.calc_gradient(indep_list, unknown_list, mode='fwd', return_format='dict')\n for key1, val1 in Jbase.items():\n for key2, val2 in val1.items():\n assert_rel_error(self, J[key1][key2], val2, .00001)\n\n J = prob.calc_gradient(indep_list, unknown_list, mode='rev', return_format='dict')\n for key1, val1 in Jbase.items():\n for key2, val2 in val1.items():\n assert_rel_error(self, J[key1][key2], val2, .00001)\n\n def test_implicit_solve_linear(self):\n\n p = Problem()\n p.root = Group()\n\n dvars = ( ('a', 3.), ('b', 10.))\n p.root.add('desvars', IndepVarComp(dvars), promotes=['a', 'b'])\n\n sg = p.root.add('sg', Group(), promotes=[\"*\"])\n sg.add('si', SimpleImplicitSL(), promotes=['a', 'b', 'x'])\n\n p.root.add('func', ExecComp('f = 2*x0+a'), promotes=['f', 'x0', 'a'])\n p.root.connect('x', 'x0', src_indices=[1])\n\n p.driver.add_objective('f')\n p.driver.add_desvar('a')\n\n p.root.nl_solver = Newton()\n p.root.nl_solver.options['rtol'] = 1e-10\n p.root.nl_solver.options['atol'] = 1e-10\n p.root.ln_solver = DirectSolver()\n p.root.ln_solver.options['jacobian_method'] = 'assemble'\n\n p.setup(check=False)\n p['x'] = np.array([1.5, 2.])\n\n p.run()\n J = p.calc_gradient(['a'], ['f'], mode='rev')\n assert_rel_error(self, J[0][0], 1.57735, 1e-6)\n\n def test_unrel_var_in_Jac(self):\n\n p = Problem()\n root = p.root = Group()\n root.add('p', IndepVarComp('x', 4.0))\n root.add('comp', ExecComp(['y1 = 1.5*x1 + 2.0*x2', 'y2 = 3.0*x1 - x2']))\n\n root.connect('p.x', 'comp.x1')\n p.driver.add_objective('comp.y1')\n p.driver.add_desvar('p.x')\n\n p.root.ln_solver = DirectSolver()\n p.root.ln_solver.options['jacobian_method'] = 'assemble'\n\n p.setup(check=False)\n p.run()\n\n J = p.calc_gradient(['p.x'], ['comp.y1'], mode='fwd')\n assert_rel_error(self, J[0][0], 1.5, 1e-6)\n\nif __name__ == \"__main__\":\n unittest.main()\n" ]
[ [ "numpy.array", "numpy.ones", "numpy.linalg.norm" ] ]
ad6398/Pointer-Generator-NW
[ "4bf997453fb8570fe04668318ca3861cb7d23ecf" ]
[ "utils/dataset.py" ]
[ "# -*- coding: utf-8 -*-\n\nimport csv\nimport glob\nimport time\nimport queue\nimport struct\nimport numpy as np\nimport tensorflow as tf\nfrom random import shuffle\nfrom threading import Thread\nfrom tensorflow.core.example import example_pb2\n\nfrom utils import utils\nfrom utils import config\n\nimport random\nrandom.seed(1234)\n\n\n# <s> and </s> are used in the data files to segment the abstracts into sentences. They don't receive vocab ids.\nSENTENCE_STA = '<s>'\nSENTENCE_END = '</s>'\n\nPAD_TOKEN = '[PAD]' # This has a vocab id, which is used to pad the encoder input, decoder input and target sequence\nUNK_TOKEN = '[UNK]' # This has a vocab id, which is used to represent out-of-vocabulary words\nBOS_TOKEN = '[BOS]' # This has a vocab id, which is used at the start of every decoder input sequence\nEOS_TOKEN = '[EOS]' # This has a vocab id, which is used at the end of untruncated target sequences\n# Note: none of <s>, </s>, [PAD], [UNK], [START], [STOP] should appear in the vocab file.\n\n\nclass Vocab(object):\n\n def __init__(self, file, max_size):\n self.word2idx = {}\n self.idx2word = {}\n self.count = 0 # keeps track of total number of words in the Vocab\n\n # [UNK], [PAD], [BOS] and [EOS] get the ids 0,1,2,3.\n for w in [UNK_TOKEN, PAD_TOKEN, BOS_TOKEN, EOS_TOKEN]:\n self.word2idx[w] = self.count\n self.idx2word[self.count] = w\n self.count += 1\n\n # Read the vocab file and add words up to max_size\n with open(file, 'r') as fin:\n for line in fin:\n items = line.split()\n if len(items) != 2:\n print('Warning: incorrectly formatted line in vocabulary file: %s' % line.strip())\n continue\n w = items[0]\n if w in [SENTENCE_STA, SENTENCE_END, UNK_TOKEN, PAD_TOKEN, BOS_TOKEN, EOS_TOKEN]:\n raise Exception(\n '<s>, </s>, [UNK], [PAD], [BOS] and [EOS] shouldn\\'t be in the vocab file, but %s is' % w)\n if w in self.word2idx:\n raise Exception('Duplicated word in vocabulary file: %s' % w)\n self.word2idx[w] = self.count\n self.idx2word[self.count] = w\n self.count += 1\n if max_size != 0 and self.count >= max_size:\n break\n print(\"Finished constructing vocabulary of %i total words. Last word added: %s\" % (\n self.count, self.idx2word[self.count - 1]))\n\n def word2id(self, word):\n if word not in self.word2idx:\n return self.word2idx[UNK_TOKEN]\n return self.word2idx[word]\n\n def id2word(self, word_id):\n if word_id not in self.idx2word:\n raise ValueError('Id not found in vocab: %d' % word_id)\n return self.idx2word[word_id]\n\n def size(self):\n return self.count\n\n def write_metadata(self, path):\n print( \"Writing word embedding metadata file to %s...\" % (path))\n with open(path, \"w\") as f:\n fieldnames = ['word']\n writer = csv.DictWriter(f, delimiter=\"\\t\", fieldnames=fieldnames)\n for i in range(self.size()):\n writer.writerow({\"word\": self.idx2word[i]})\n\nclass Example(object):\n\n def __init__(self, article, abstract_sentences, vocab):\n # Get ids of special tokens\n bos_decoding = vocab.word2id(BOS_TOKEN)\n eos_decoding = vocab.word2id(EOS_TOKEN)\n\n # Process the article\n article_words = article.decode().split()\n if len(article_words) > config.max_enc_steps:\n article_words = article_words[:config.max_enc_steps]\n self.enc_len = len(article_words) # store the length after truncation but before padding\n self.enc_inp = [vocab.word2id(w) for w in\n article_words] # list of word ids; OOVs are represented by the id for UNK token\n\n # Process the abstract\n abstract = ' '.encode().join(abstract_sentences).decode()\n abstract_words = abstract.split() # list of strings\n abs_ids = [vocab.word2id(w) for w in\n abstract_words] # list of word ids; OOVs are represented by the id for UNK token\n\n # Get the decoder input sequence and target sequence\n self.dec_inp, self.tgt = self.get_dec_seq(abs_ids, config.max_dec_steps, bos_decoding, eos_decoding)\n self.dec_len = len(self.dec_inp)\n\n # If using pointer-generator mode, we need to store some extra info\n if config.pointer_gen:\n # Store a version of the enc_input where in-article OOVs are represented by their temporary OOV id;\n # also store the in-article OOVs words themselves\n self.enc_inp_extend_vocab, self.article_oovs = utils.article2ids(article_words, vocab)\n\n # Get a verison of the reference summary where in-article OOVs are represented by their temporary article OOV id\n abs_ids_extend_vocab = utils.abstract2ids(abstract_words, vocab, self.article_oovs)\n\n # Overwrite decoder target sequence so it uses the temp article OOV ids\n _, self.tgt = self.get_dec_seq(abs_ids_extend_vocab, config.max_dec_steps, bos_decoding, eos_decoding)\n\n # Store the original strings\n self.original_article = article\n self.original_abstract = abstract\n self.original_abstract_sents = abstract_sentences\n\n def get_dec_seq(self, sequence, max_len, start_id, stop_id):\n src = [start_id] + sequence[:]\n tgt = sequence[:]\n if len(src) > max_len: # truncate\n src = src[:max_len]\n tgt = tgt[:max_len] # no end_token\n else: # no truncation\n tgt.append(stop_id) # end token\n assert len(src) == len(tgt)\n return src, tgt\n\n def pad_enc_seq(self, max_len, pad_id):\n while len(self.enc_inp) < max_len:\n self.enc_inp.append(pad_id)\n if config.pointer_gen:\n while len(self.enc_inp_extend_vocab) < max_len:\n self.enc_inp_extend_vocab.append(pad_id)\n\n def pad_dec_seq(self, max_len, pad_id):\n while len(self.dec_inp) < max_len:\n self.dec_inp.append(pad_id)\n while len(self.tgt) < max_len:\n self.tgt.append(pad_id)\n\n\nclass Batch(object):\n def __init__(self, example_list, vocab, batch_size):\n self.batch_size = batch_size\n self.pad_id = vocab.word2id(PAD_TOKEN) # id of the PAD token used to pad sequences\n self.init_encoder_seq(example_list) # initialize the input to the encoder\n self.init_decoder_seq(example_list) # initialize the input and targets for the decoder\n self.store_orig_strings(example_list) # store the original strings\n\n def init_encoder_seq(self, example_list):\n # Determine the maximum length of the encoder input sequence in this batch\n max_enc_seq_len = max([ex.enc_len for ex in example_list])\n\n # Pad the encoder input sequences up to the length of the longest sequence\n for ex in example_list:\n ex.pad_enc_seq(max_enc_seq_len, self.pad_id)\n\n # Initialize the numpy arrays\n # Note: our enc_batch can have different length (second dimension) for each batch because we use dynamic_rnn for the encoder.\n self.enc_batch = np.zeros((self.batch_size, max_enc_seq_len), dtype=np.int32)\n self.enc_lens = np.zeros((self.batch_size), dtype=np.int32)\n self.enc_padding_mask = np.zeros((self.batch_size, max_enc_seq_len), dtype=np.float32)\n\n # Fill in the numpy arrays\n for i, ex in enumerate(example_list):\n self.enc_batch[i, :] = ex.enc_inp[:]\n self.enc_lens[i] = ex.enc_len\n for j in range(ex.enc_len):\n self.enc_padding_mask[i][j] = 1\n\n # For pointer-generator mode, need to store some extra info\n if config.pointer_gen:\n # Determine the max number of in-article OOVs in this batch\n self.max_art_oovs = max([len(ex.article_oovs) for ex in example_list])\n # Store the in-article OOVs themselves\n self.art_oovs = [ex.article_oovs for ex in example_list]\n # Store the version of the enc_batch that uses the article OOV ids\n self.enc_batch_extend_vocab = np.zeros((self.batch_size, max_enc_seq_len), dtype=np.int32)\n for i, ex in enumerate(example_list):\n self.enc_batch_extend_vocab[i, :] = ex.enc_inp_extend_vocab[:]\n\n def init_decoder_seq(self, example_list):\n # Pad the inputs and targets\n for ex in example_list:\n ex.pad_dec_seq(config.max_dec_steps, self.pad_id)\n\n # Initialize the numpy arrays.\n self.dec_batch = np.zeros((self.batch_size, config.max_dec_steps), dtype=np.int32)\n self.tgt_batch = np.zeros((self.batch_size, config.max_dec_steps), dtype=np.int32)\n self.dec_padding_mask = np.zeros((self.batch_size, config.max_dec_steps), dtype=np.float32)\n self.dec_lens = np.zeros((self.batch_size), dtype=np.int32)\n\n # Fill in the numpy arrays\n for i, ex in enumerate(example_list):\n self.dec_batch[i, :] = ex.dec_inp[:]\n self.tgt_batch[i, :] = ex.tgt[:]\n self.dec_lens[i] = ex.dec_len\n for j in range(ex.dec_len):\n self.dec_padding_mask[i][j] = 1\n\n def store_orig_strings(self, example_list):\n self.original_articles = [ex.original_article for ex in example_list] # list of lists\n self.original_abstracts = [ex.original_abstract for ex in example_list] # list of lists\n self.original_abstracts_sents = [ex.original_abstract_sents for ex in example_list] # list of list of lists\n\n\nclass Batcher(object):\n BATCH_QUEUE_MAX = 100 # max number of batches the batch_queue can hold\n\n def __init__(self, vocab, data_path, batch_size, single_pass, mode):\n self._vocab = vocab\n self._data_path = data_path\n self.batch_size = batch_size\n self.single_pass = single_pass\n self.mode = mode\n\n # Initialize a queue of Batches waiting to be used, and a queue of Examples waiting to be batched\n self._batch_queue = queue.Queue(self.BATCH_QUEUE_MAX)\n self._example_queue = queue.Queue(self.BATCH_QUEUE_MAX * self.batch_size)\n\n # Different settings depending on whether we're in single_pass mode or not\n if single_pass:\n self._num_example_q_threads = 1 # just one thread, so we read through the dataset just once\n self._num_batch_q_threads = 1 # just one thread to batch examples\n self._bucketing_cache_size = 1 # only load one batch's worth of examples before bucketing\n self._finished_reading = False # this will tell us when we're finished reading the dataset\n else:\n self._num_example_q_threads = 1 # num threads to fill example queue\n self._num_batch_q_threads = 1 # num threads to fill batch queue\n self._bucketing_cache_size = 1 # how many batches-worth of examples to load into cache before bucketing\n\n # Start the threads that load the queues\n self._example_q_threads = []\n for _ in range(self._num_example_q_threads):\n self._example_q_threads.append(Thread(target=self.fill_example_queue))\n self._example_q_threads[-1].daemon = True\n self._example_q_threads[-1].start()\n self._batch_q_threads = []\n for _ in range(self._num_batch_q_threads):\n self._batch_q_threads.append(Thread(target=self.fill_batch_queue))\n self._batch_q_threads[-1].daemon = True\n self._batch_q_threads[-1].start()\n\n # Start a thread that watches the other threads and restarts them if they're dead\n if not single_pass: # We don't want a watcher in single_pass mode because the threads shouldn't run forever\n self._watch_thread = Thread(target=self.watch_threads)\n self._watch_thread.daemon = True\n self._watch_thread.start()\n\n def next_batch(self):\n # If the batch queue is empty, print a warning\n if self._batch_queue.qsize() == 0:\n tf.logging.warning(\n 'Bucket input queue is empty when calling next_batch. Bucket queue size: %i, Input queue size: %i',\n self._batch_queue.qsize(), self._example_queue.qsize())\n if self.single_pass and self._finished_reading:\n tf.logging.info(\"Finished reading dataset in single_pass mode.\")\n return None\n\n batch = self._batch_queue.get() # get the next Batch\n return batch\n\n def fill_example_queue(self):\n example_generator = self.example_generator(self._data_path, self.single_pass)\n input_gen = self.pair_generator(example_generator)\n\n while True:\n try:\n (article,\n abstract) = input_gen.__next__() # read the next example from file. article and abstract are both strings.\n except StopIteration: # if there are no more examples:\n tf.logging.info(\"The example generator for this example queue filling thread has exhausted data.\")\n if self.single_pass:\n tf.logging.info(\n \"single_pass mode is on, so we've finished reading dataset. This thread is stopping.\")\n self._finished_reading = True\n break\n else:\n raise Exception(\"single_pass mode is off but the example generator is out of data; error.\")\n\n abstract_sentences = [sent.strip() for sent in utils.abstract2sents(\n abstract)] # Use the <s> and </s> tags in abstract to get a list of sentences.\n example = Example(article, abstract_sentences, self._vocab)\n self._example_queue.put(example)\n\n def fill_batch_queue(self):\n while True:\n if self.mode == 'decode':\n # beam search decode mode single example repeated in the batch\n ex = self._example_queue.get()\n b = [ex for _ in range(self.batch_size)]\n self._batch_queue.put(Batch(b, self._vocab, self.batch_size))\n else:\n # Get bucketing_cache_size-many batches of Examples into a list, then sort\n inputs = []\n for _ in range(self.batch_size * self._bucketing_cache_size):\n inputs.append(self._example_queue.get())\n inputs = sorted(inputs, key=lambda inp: inp.enc_len, reverse=True) # sort by length of encoder sequence\n\n # Group the sorted Examples into batches, optionally shuffle the batches, and place in the batch queue.\n batches = []\n for i in range(0, len(inputs), self.batch_size):\n batches.append(inputs[i:i + self.batch_size])\n if not self.single_pass:\n shuffle(batches)\n for b in batches: # each b is a list of Example objects\n self._batch_queue.put(Batch(b, self._vocab, self.batch_size))\n\n def watch_threads(self):\n while True:\n tf.logging.info(\n 'Bucket queue size: %i, Input queue size: %i',\n self._batch_queue.qsize(), self._example_queue.qsize())\n\n time.sleep(60)\n for idx, t in enumerate(self._example_q_threads):\n if not t.is_alive(): # if the thread is dead\n tf.logging.error('Found example queue thread dead. Restarting.')\n new_t = Thread(target=self.fill_example_queue)\n self._example_q_threads[idx] = new_t\n new_t.daemon = True\n new_t.start()\n for idx, t in enumerate(self._batch_q_threads):\n if not t.is_alive(): # if the thread is dead\n tf.logging.error('Found batch queue thread dead. Restarting.')\n new_t = Thread(target=self.fill_batch_queue)\n self._batch_q_threads[idx] = new_t\n new_t.daemon = True\n new_t.start()\n\n def pair_generator(self, example_generator):\n while True:\n e = example_generator.__next__() # e is a tf.Example\n try:\n article_text = e.features.feature['article'].bytes_list.value[\n 0] # the article text was saved under the key 'article' in the data files\n abstract_text = e.features.feature['abstract'].bytes_list.value[\n 0] # the abstract text was saved under the key 'abstract' in the data files\n except ValueError:\n tf.logging.error('Failed to get article or abstract from example')\n continue\n if len(article_text) == 0: # See https://github.com/abisee/pointer-generator/issues/1\n # tf.logging.warning('Found an example with empty article text. Skipping it.')\n continue\n else:\n yield (article_text, abstract_text)\n\n def example_generator(self, data_path, single_pass):\n while True:\n filelist = glob.glob(data_path) # get the list of datafiles\n assert filelist, ('Error: Empty filelist at %s' % data_path) # check filelist isn't empty\n if single_pass:\n filelist = sorted(filelist)\n else:\n random.shuffle(filelist)\n for f in filelist:\n reader = open(f, 'rb')\n while True:\n len_bytes = reader.read(8)\n if not len_bytes: break # finished reading this file\n str_len = struct.unpack('q', len_bytes)[0]\n example_str = struct.unpack('%ds' % str_len, reader.read(str_len))[0]\n yield example_pb2.Example.FromString(example_str)\n if single_pass:\n print(\"example_generator completed reading all datafiles. No more data.\")\n break" ]
[ [ "tensorflow.logging.info", "tensorflow.logging.error", "numpy.zeros", "tensorflow.core.example.example_pb2.Example.FromString" ] ]
veterinarian-5300/Genious-Python-Code-Generator
[ "d78cd5f4b64221e8e4dc80d6e1f5ba0a4c613bcd", "d78cd5f4b64221e8e4dc80d6e1f5ba0a4c613bcd" ]
[ "practice/check.py", "Py_lab/Lab 1,2/plotting_unit_signals.py" ]
[ "import csv\r\nimport pandas as pd\r\n\r\none=pd.read_csv(\"pa_dashboards.csv\")\r\n\r\ntwo=pd.read_csv(\"pa_dashboards(1).csv\", squeeze=True)\r\n\r\npattern = '|'.join(two)\r\n\r\nexist=one['sentences'].str.contains(pattern, na=False)\r\n\r\nwith open('new.csv', 'w') as outFile:\r\n for cols in exist:\r\n if pattern in exist:\r\n outFile.write(exist, \"1\")\r\n", "### importing libraries\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nn = np.linspace(-5, 5, 11)\r\ndelta = 1*(n==0)\r\nu = 1*(n>=0)\r\nplt.stem(n, delta, use_line_collection = True)\r\n\r\n# naming the x axis\r\nplt.xlabel('n')\r\nplt.ylabel('x[n] = delta[n]')\r\n# giving a title to my graph\r\nplt.title('Unit Impulse Sequence')\r\nplt.show()\r\nplt.stem(n, u, use_line_collection = True)\r\nplt.xlabel('n')\r\nplt.ylabel('x[n] = u[n]')\r\n# giving a title to my graph\r\nplt.title('Unit Step Sequence')\r\n# naming the y axis\r\n\r\n# naming the x axis\r\n# naming the y axis\r\n\r\nplt.show()" ]
[ [ "pandas.read_csv" ], [ "matplotlib.pyplot.stem", "matplotlib.pyplot.title", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel", "numpy.linspace", "matplotlib.pyplot.xlabel" ] ]
csaid/bokeh
[ "4312b2de1a15fb24884fcd97eaf6442bf8b4bd7b" ]
[ "examples/plotting/server/boxplot.py" ]
[ "# The plot server must be running\n# Go to http://localhost:5006/bokeh to view this plot\n\nimport numpy as np\nimport pandas as pd\nfrom bokeh.plotting import *\n\n# Generate some synthetic time series for six different categories\ncats = list(\"abcdef\")\ny = np.random.randn(2000)\ng = np.random.choice(cats, 2000)\nfor i, l in enumerate(cats):\n y[g == l] += i // 2\ndf = pd.DataFrame(dict(score=y, group=g))\n\n# Find the quartiles and IQR foor each category\ngroups = df.groupby('group')\nq1 = groups.quantile(q=0.25)\nq2 = groups.quantile(q=0.5)\nq3 = groups.quantile(q=0.75)\niqr = q3 - q1\nupper = q2 + 1.5*iqr\nlower = q2 - 1.5*iqr\n\n# find the outliers for each category\ndef outliers(group):\n cat = group.name\n return group[(group.score > upper.loc[cat][0]) | (group.score < lower.loc[cat][0])]['score']\nout = groups.apply(outliers).dropna()\n\n# Prepare outlier data for plotting, we need coordinate for every outlier.\noutx = []\nouty = []\nfor cat in cats:\n for value in out[cat]:\n outx.append(cat)\n outy.append(value)\n\noutput_server('boxplot')\n\nfigure(tools=\"previewsave\", background_fill=\"#EFE8E2\", title=\"\")\n\nhold()\n\n# stems\nsegment(cats, upper.score, cats, q3.score, x_range=cats,\n line_width=2, line_color=\"black\", )\nsegment(cats, lower.score, cats, q1.score, x_range=cats,\n line_width=2, line_color=\"black\")\n# boxes\nrect(cats, (q3.score+q2.score)/2, 0.7, q3.score-q2.score,\n fill_color=\"#E08E79\", line_width=2, line_color=\"black\")\nrect(cats, (q2.score+q1.score)/2, 0.7, q2.score-q1.score,\n fill_color=\"#3B8686\", line_width=2, line_color=\"black\")\n\n# whisters (0-height rects simpler than segments)\nrect(cats, lower.score, 0.2, 0, line_color=\"black\")\nrect(cats, upper.score, 0.2, 0, line_color=\"black\")\n\n# outliers\ncircle(outx, outy, size=6, color=\"#F38630\", fill_alpha=0.6)\n\nxgrid().grid_line_color = None\nygrid().grid_line_color = \"white\"\nygrid().grid_line_width = 2\nxaxis().major_label_text_font_size=\"12pt\"\nshow()\n" ]
[ [ "numpy.random.randn", "numpy.random.choice" ] ]
valentinaschueller/sweet
[ "27e99c7a110c99deeadee70688c186d82b39ac90" ]
[ "benchmarks_sphere/paper_jrn_parco_rexi_nonlinear/compare_wt_dt_vs_accuracy_galewsky/postprocessing_consolidate.py" ]
[ "#! /usr/bin/env python3\n\nimport sys\nimport math\n\nfrom SWEET import *\nfrom mule.plotting.Plotting import *\nfrom mule.postprocessing.JobsData import *\nfrom mule.postprocessing.JobsDataConsolidate import *\n\nsys.path.append('../')\nimport pretty_plotting as pp\nsys.path.pop()\n\nmule_plotting_usetex(False)\n\ngroups = ['runtime.timestepping_method']\n\ntagnames_y = [\n\t'sphere_data_diff_prog_h.res_norm_l1',\n\t'sphere_data_diff_prog_h.res_norm_l2',\n\t'sphere_data_diff_prog_h.res_norm_linf',\n]\n\n\n\nj = JobsData('./job_bench_*', verbosity=0)\n\nc = JobsDataConsolidate(j)\nprint(\"\")\nprint(\"Groups:\")\njob_groups = c.create_groups(groups)\nfor key, g in job_groups.items():\n\tprint(key)\n\nfor tagname_y in tagnames_y:\n\n\tparams = []\n\tparams += [\n\t\t\t{\n\t\t\t\t'tagname_x': 'runtime.timestep_size',\n\t\t\t\t'xlabel': \"Timestep size (seconds)\",\n\t\t\t\t'ylabel': pp.latex_pretty_names[tagname_y],\n\t\t\t\t'title': 'Timestep size vs. error',\n\t\t\t\t'xscale': 'log',\n\t\t\t\t'yscale': 'log',\n\t\t\t},\n\t\t]\n\n\tparams += [\n\t\t\t{\n\t\t\t\t'tagname_x': 'output.simulation_benchmark_timings.main_timestepping',\n\t\t\t\t'xlabel': \"Wallclock time (seconds)\",\n\t\t\t\t'ylabel': pp.latex_pretty_names[tagname_y],\n\t\t\t\t'title': 'Wallclock time vs. error',\n\t\t\t\t'xscale': 'log',\n\t\t\t\t'yscale': 'log',\n\t\t\t},\n\t\t]\n\n\n\tfor param in params:\n\n\t\ttagname_x = param['tagname_x']\n\t\txlabel = param['xlabel']\n\t\tylabel = param['ylabel']\n\t\ttitle = param['title']\n\t\txscale = param['xscale']\n\t\tyscale = param['yscale']\n\n\t\tprint(\"*\"*80)\n\t\tprint(\"Processing tag \"+tagname_x)\n\t\tprint(\"*\"*80)\n\n\n\n\t\tif True:\n\t\t\t\"\"\"\n\t\t\tPlotting format\n\t\t\t\"\"\"\n\n\t\t\t# Filter out errors beyond this value!\n\t\t\tdef data_filter(x, y, jobdata):\n\t\t\t\tif y == None:\n\t\t\t\t\treturn True\n\n\t\t\t\tx = float(x)\n\t\t\t\ty = float(y)\n\n\t\t\t\tif math.isnan(y):\n\t\t\t\t\treturn True\n\n\t\t\t\tif 'prog_h' in tagname_y:\n\t\t\t\t\tif 'l1' in tagname_y:\n\t\t\t\t\t\tif y > 1e1:\n\t\t\t\t\t\t\tprint(\"Sorting out L1 data \"+str(y))\n\t\t\t\t\t\t\treturn True\n\t\t\t\t\telif 'l2' in tagname_y:\n\t\t\t\t\t\tif y > 1e1:\n\t\t\t\t\t\t\tprint(\"Sorting out L2 data \"+str(y))\n\t\t\t\t\t\t\treturn True\n\t\t\t\t\telif 'linf' in tagname_y:\n\t\t\t\t\t\tif y > 1e2:\n\t\t\t\t\t\t\tprint(\"Sorting out Linf data \"+str(y))\n\t\t\t\t\t\t\treturn True\n\t\t\t\t\telse:\n\t\t\t\t\t\traise Exception(\"Unknown y tag \"+tagname_y)\n\n\t\t\t\telse:\n\t\t\t\t\tprint(\"TODO\")\n\n\t\t\t\treturn False\n\n\n\n\t\t\td = JobsData_GroupsPlottingScattered(\n\t\t\t\t\tjob_groups,\n\t\t\t\t\ttagname_x,\n\t\t\t\t\ttagname_y,\n\t\t\t\t\tdata_filter = data_filter\n\t\t\t\t)\n\n\t\t\tfileid = \"output_plotting_\"+tagname_x.replace('.', '-').replace('_', '-')+\"_vs_\"+tagname_y.replace('.', '-').replace('_', '-')\n\n\n\t\t\tif True:\n\t\t\t\t#\n\t\t\t\t# Proper naming and sorting of each label\n\t\t\t\t#\n\n\t\t\t\t# new data dictionary\n\t\t\t\tdata_new = {}\n\t\t\t\tfor key, data in d.data.items():\n\t\t\t\t\t# generate nice tex label\n\t\t\t\t\t#data['label'] = pp.get_pretty_name(key)\n\t\t\t\t\tdata['label'] = key #pp.get_pretty_name(key)\n\n\t\t\t\t\tkey_new = pp.get_pretty_name_order(key)+'_'+key\n\n\t\t\t\t\t# copy data\n\t\t\t\t\tdata_new[key_new] = copy.copy(data)\n\n\t\t\t\t# Copy back new data table\n\t\t\t\td.data = data_new\n\n\t\t\tp = Plotting_ScatteredData()\n\n\n\t\t\tdef fun(p):\n\t\t\t\tfrom matplotlib import ticker\n\t\t\t\tfrom matplotlib.ticker import FormatStrFormatter\n\n\t\t\t\tplt.tick_params(axis='x', which='minor')\n\t\t\t\tp.ax.xaxis.set_minor_formatter(FormatStrFormatter(\"%.0f\"))\n\t\t\t\tp.ax.xaxis.set_major_formatter(FormatStrFormatter(\"%.0f\"))\n\n\t\t\t\tp.ax.xaxis.set_minor_locator(ticker.LogLocator(subs=[1.5, 2.0, 3.0, 5.0]))\n\n\t\t\t\tfor tick in p.ax.xaxis.get_minor_ticks():\n\t\t\t\t\ttick.label.set_fontsize(8) \n\n\n\t\t\t\tplt.tick_params(axis='y', which='minor')\n\t\t\t\tp.ax.yaxis.set_minor_formatter(FormatStrFormatter(\"%.1e\"))\n\t\t\t\tp.ax.yaxis.set_major_formatter(FormatStrFormatter(\"%.1e\"))\n \n\t\t\t\tp.ax.yaxis.set_minor_locator(ticker.LogLocator(subs=[1.5, 2.0, 3.0, 5.0]))\n\n\t\t\t\tfor tick in p.ax.yaxis.get_minor_ticks():\n\t\t\t\t\ttick.label.set_fontsize(6) \n\n\n\n\t\t\tannotate_text_template = \"{:.1f} / {:.3f}\"\n\t\t\tp.plot(\n\t\t\t\t\tdata_plotting = d.get_data_float(),\n\t\t\t\t\txlabel = xlabel,\n\t\t\t\t\tylabel = ylabel,\n\t\t\t\t\ttitle = title,\n\t\t\t\t\txscale = xscale,\n\t\t\t\t\tyscale = yscale,\n\t\t\t\t\t#annotate = True,\n\t\t\t\t\t#annotate_each_nth_value = 3,\n\t\t\t\t\t#annotate_fontsize = 6,\n\t\t\t\t\t#annotate_text_template = annotate_text_template,\n\t\t\t\t\tlegend_fontsize = 8,\n\t\t\t\t\tgrid = True,\n\t\t\t\t\toutfile = fileid+\".pdf\",\n\t\t\t\t\tlambda_fun = fun,\n\t\t\t\t)\n\n\t\t\tprint(\"Data plotting:\")\n\t\t\td.print()\n\t\t\td.write(fileid+\".csv\")\n\n\t\tprint(\"Info:\")\n\t\tprint(\"\tNaN: Errors in simulations\")\n\t\tprint(\"\tNone: No data available\")\n" ]
[ [ "matplotlib.ticker.LogLocator", "matplotlib.ticker.FormatStrFormatter" ] ]
NunoEdgarGFlowHub/cvxpy
[ "43270fcc8af8fc4742f1b3519800b0074f2e6693" ]
[ "cvxpy/atoms/max.py" ]
[ "\"\"\"\nCopyright 2013 Steven Diamond\n\nThis file is part of CVXPY.\n\nCVXPY is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nCVXPY is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with CVXPY. If not, see <http://www.gnu.org/licenses/>.\n\"\"\"\n\nfrom cvxpy.atoms.atom import Atom\nfrom cvxpy.atoms.axis_atom import AxisAtom\nimport cvxpy.lin_ops.lin_utils as lu\nimport numpy as np\n\n\nclass max(AxisAtom):\n \"\"\":math:`\\max_{i,j}\\{X_{i,j}\\}`.\n \"\"\"\n\n def __init__(self, x, axis=None, keepdims=False):\n super(max, self).__init__(x, axis=axis, keepdims=keepdims)\n\n @Atom.numpy_numeric\n def numeric(self, values):\n \"\"\"Returns the largest entry in x.\n \"\"\"\n return values[0].max(axis=self.axis, keepdims=self.keepdims)\n\n def _grad(self, values):\n \"\"\"Gives the (sub/super)gradient of the atom w.r.t. each argument.\n\n Matrix expressions are vectorized, so the gradient is a matrix.\n\n Args:\n values: A list of numeric values for the arguments.\n\n Returns:\n A list of SciPy CSC sparse matrices or None.\n \"\"\"\n return self._axis_grad(values)\n\n def _column_grad(self, value):\n \"\"\"Gives the (sub/super)gradient of the atom w.r.t. a column argument.\n\n Matrix expressions are vectorized, so the gradient is a matrix.\n\n Args:\n value: A numeric value for a column.\n\n Returns:\n A NumPy ndarray or None.\n \"\"\"\n # Grad: 1 for a largest index.\n value = np.matrix(value).A.ravel(order='F')\n idx = np.argmax(value)\n D = np.zeros((value.size, 1))\n D[idx] = 1\n return D\n\n def sign_from_args(self):\n \"\"\"Returns sign (is positive, is negative) of the expression.\n \"\"\"\n # Same as argument.\n return (self.args[0].is_nonneg(), self.args[0].is_nonpos())\n\n def is_atom_convex(self):\n \"\"\"Is the atom convex?\n \"\"\"\n return True\n\n def is_atom_concave(self):\n \"\"\"Is the atom concave?\n \"\"\"\n return False\n\n def is_incr(self, idx):\n \"\"\"Is the composition non-decreasing in argument idx?\n \"\"\"\n return True\n\n def is_decr(self, idx):\n \"\"\"Is the composition non-increasing in argument idx?\n \"\"\"\n return False\n\n def is_pwl(self):\n \"\"\"Is the atom piecewise linear?\n \"\"\"\n return self.args[0].is_pwl()\n\n @staticmethod\n def graph_implementation(arg_objs, shape, data=None):\n \"\"\"Reduces the atom to an affine expression and list of constraints.\n\n Parameters\n ----------\n arg_objs : list\n LinExpr for each argument.\n shape : tuple\n The shape of the resulting expression.\n data :\n Additional data required by the atom.\n\n Returns\n -------\n tuple\n (LinOp for objective, list of constraints)\n \"\"\"\n axis = data[0]\n if axis is None:\n t = lu.create_var((1, 1))\n promoted_t = lu.promote(t, arg_objs[0].shape)\n elif axis == 0:\n t = lu.create_var((1, arg_objs[0].shape[1]))\n const_shape = (arg_objs[0].shape[0], 1)\n ones = lu.create_const(np.ones(const_shape), const_shape)\n promoted_t = lu.mul_expr(ones, t, arg_objs[0].shape)\n else: # axis == 1\n t = lu.create_var((arg_objs[0].shape[0], 1))\n const_shape = (1, arg_objs[0].shape[1])\n ones = lu.create_const(np.ones(const_shape), const_shape)\n promoted_t = lu.rmul_expr(t, ones, arg_objs[0].shape)\n\n constraints = [lu.create_leq(arg_objs[0], promoted_t)]\n return (t, constraints)\n" ]
[ [ "numpy.zeros", "numpy.matrix", "numpy.ones", "numpy.argmax" ] ]
damien911224/augmentation-corruption
[ "4cf22bd3be1d100635fb6cd41e9b71a6949b5dd0" ]
[ "experiments/severity_scan_imagenet.py" ]
[ "# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport hydra\nfrom hydra.utils import instantiate\nimport logging\nfrom overlap.train_net import train_net\nfrom overlap.test_net import test_net\nimport numpy as np\nimport torch\nimport pickle\nimport os\nimport omegaconf\nfrom overlap.extract_features import extract_features\nimport submitit\n\nlog = logging.getLogger(__name__)\n\[email protected](config_path=\"conf/severity_scan_imagenet.yaml\")\ndef run(cfg):\n if cfg.num_gpus > 1:\n job_env = submitit.JobEnvironment()\n rank = job_env.global_rank\n world_size = job_env.num_tasks\n if rank != 0:\n logging.root.handlers = []\n try:\n torch.cuda.set_device(rank)\n torch.distributed.init_process_group(\n backend='nccl',\n init_method=\"tcp://{}:{}\".format('localhost', 10001),\n world_size=world_size,\n rank=rank\n )\n train(cfg, is_leader=(rank==0))\n except KeyboardInterrupt:\n pass\n finally:\n torch.distributed.destroy_process_group()\n else:\n train(cfg, is_leader=True)\n\ndef train(cfg, is_leader=True):\n\n np.random.seed(cfg.rng_seed)\n torch.manual_seed(cfg.rng_seed)\n\n log.info(cfg.pretty())\n cur_device = torch.cuda.current_device()\n model = instantiate(cfg.model).cuda(device=cur_device)\n if cfg.num_gpus > 1:\n model = torch.nn.parallel.DistributedDataParallel(\n module=model,\n device_ids=[cur_device],\n output_device=cur_device\n )\n optimizer = instantiate(cfg.optim, model.parameters())\n if cfg.optim.max_epoch > 0:\n train_dataset = instantiate(cfg.train)\n else:\n train_dataset = None\n test_dataset = instantiate(cfg.test)\n lr_policy = instantiate(cfg.optim.lr_policy)\n with omegaconf.open_dict(cfg):\n feature_extractor = instantiate(cfg.ft, num_gpus=cfg.num_gpus, is_leader=is_leader)\n feature_extractor.train()\n \n train_net(model=model,\n optimizer=optimizer,\n train_dataset=train_dataset,\n batch_size=cfg.train.batch_size,\n max_epoch=cfg.optim.max_epoch,\n loader_params=cfg.data_loader,\n lr_policy=lr_policy,\n save_period=cfg.train.checkpoint_period,\n weights=cfg.train.weights,\n num_gpus=cfg.num_gpus,\n is_leader=is_leader\n )\n\n err = test_net(model=model,\n test_dataset=test_dataset,\n batch_size=cfg.test.batch_size,\n loader_params=cfg.data_loader,\n output_name='test_epoch',\n num_gpus=cfg.num_gpus)\n\n if os.path.exists(cfg.feature_file):\n feature_dict = {k : v for k, v in np.load(cfg.feature_file).items()}\n else:\n feature_dict = {}\n indices = np.load(cfg.ft_corrupt.indices_file)\n for aug in cfg.aug_string.split(\"--\"):\n if len(aug.split(\"-\")) > 1:\n #log.info(\"Severity provided in corrupt.aug_string will be weighted by given severity.\")\n sev = aug.split(\"-\")[1]\n if len(sev.split(\"_\")) > 1:\n low = float(sev.split(\"_\")[0])\n high = float(sev.split(\"_\")[1])\n else:\n low = 0.0\n high = float(sev)\n\n sev_factor = (high - low) * cfg.severity / 10 + low\n else:\n sev_factor = cfg.severity\n aug = aug.split(\"-\")[0]\n aug_string = \"{}-{}\".format(aug, sev_factor)\n if aug_string in feature_dict:\n continue\n with omegaconf.open_dict(cfg.corrupt):\n corrupt_dataset = instantiate(cfg.corrupt, aug_string=aug_string)\n err = test_net(model=model,\n test_dataset=corrupt_dataset,\n batch_size=cfg.corrupt.batch_size,\n loader_params=cfg.data_loader,\n output_name=aug_string,\n num_gpus=cfg.num_gpus)\n with omegaconf.open_dict(cfg.ft_corrupt):\n ft_corrupt_dataset = instantiate(cfg.ft_corrupt, aug_string=aug_string)\n if cfg.ft_corrupt.params.num_transforms is not None:\n ft_corrupt_dataset = ft_corrupt_dataset.serialize(indices)\n else:\n ft_corrupt_dataset = torch.utils.data.Subset(ft_corrupt_dataset, indices)\n \n feature = extract_features(feature_extractor=feature_extractor,\n dataset=ft_corrupt_dataset,\n batch_size=cfg.ft_corrupt.batch_size,\n loader_params=cfg.data_loader,\n average=True,\n num_gpus=cfg.num_gpus)\n feature_dict[aug_string] = feature\n if is_leader:\n np.savez(cfg.feature_file, **feature_dict)\n\nif __name__==\"__main__\":\n run()\n" ]
[ [ "numpy.load", "torch.utils.data.Subset", "torch.manual_seed", "numpy.savez", "numpy.random.seed", "torch.cuda.current_device", "torch.nn.parallel.DistributedDataParallel", "torch.distributed.destroy_process_group", "torch.cuda.set_device" ] ]
francisengelmann/PyViz3D
[ "51e49788e2aafc522920cbde7c48e962aca8e7b5" ]
[ "examples/example_normals.py" ]
[ "import numpy as np\nimport pyviz3d.visualizer as viz\n\n\ndef create_color_palette():\n return np.array([\n (0, 0, 0),\n (174, 199, 232),\t\t# wall\n (152, 223, 138),\t\t# floor\n (31, 119, 180), \t\t# cabinet\n (255, 187, 120),\t\t# bed\n (188, 189, 34), \t\t# chair\n (140, 86, 75), \t\t# sofa\n (255, 152, 150),\t\t# table\n (214, 39, 40), \t\t# door\n (197, 176, 213),\t\t# window\n (148, 103, 189),\t\t# bookshelf\n (196, 156, 148),\t\t# picture\n (23, 190, 207), \t\t# counter\n (178, 76, 76),\n (247, 182, 210),\t\t# desk\n (66, 188, 102),\n (219, 219, 141),\t\t# curtain\n (140, 57, 197),\n (202, 185, 52),\n (51, 176, 203),\n (200, 54, 131),\n (92, 193, 61),\n (78, 71, 183),\n (172, 114, 82),\n (255, 127, 14), \t\t# refrigerator\n (91, 163, 138),\n (153, 98, 156),\n (140, 153, 101),\n (158, 218, 229),\t\t# shower curtain\n (100, 125, 154),\n (178, 127, 135),\n (120, 185, 128),\n (146, 111, 194),\n (44, 160, 44), \t\t# toilet\n (112, 128, 144),\t\t# sink\n (96, 207, 209),\n (227, 119, 194),\t\t# bathtub\n (213, 92, 176),\n (94, 106, 211),\n (82, 84, 163), \t\t# otherfurn\n (100, 85, 144)\n ], dtype=np.uint8)\n\n\ndef main():\n\n # First, we set up a visualizer\n v = viz.Visualizer()\n\n # Example with normals\n scene_name = 'scene0000_00_vh_clean_2'\n scene = np.load('examples/data/' + scene_name + '.npy')\n point_positions = scene[:, 0:3] - np.mean(scene[:, 0:3], axis=0)\n point_colors = scene[:, 3:6]\n point_labels = scene[:, -1].astype(int)\n point_normals = scene[:, 6:9]\n point_semantic_colors = create_color_palette()[point_labels]\n point_size = 35.0\n\n v.add_points('RGB Color', point_positions, point_colors, point_normals, point_size=point_size, visible=False)\n v.add_points('Semantics', point_positions, point_semantic_colors, point_normals, point_size=point_size)\n v.add_lines('Normals', point_positions, point_positions + point_normals/10, visible=True)\n\n # When we added everything we need to the visualizer, we save it.\n v.save('normals')\n\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "numpy.array", "numpy.load", "numpy.mean" ] ]
lyuwen/phono3py
[ "9e2adffa6c07abb4bdbe4e4188c460cb8a0462fd" ]
[ "phono3py/cui/settings.py" ]
[ "import numpy as np\nfrom phonopy.cui.settings import Settings, ConfParser, fracval\n\nclass Phono3pySettings(Settings):\n def __init__(self):\n Settings.__init__(self)\n\n self._boundary_mfp = 1.0e6 # In micrometre. The default value is\n # just set to avoid divergence.\n self._coarse_mesh_shifts = None\n self._const_ave_pp = None\n self._create_displacements = False\n self._cutoff_fc3_distance = None\n self._cutoff_pair_distance = None\n self._gamma_conversion_factor = None\n self._grid_addresses = None\n self._grid_points = None\n self._ion_clamped = False\n self._is_bterta = False\n self._is_compact_fc = False\n self._is_frequency_shift = False\n self._is_full_pp = False\n self._is_gruneisen = False\n self._is_imag_self_energy = False\n self._is_isotope = False\n self._is_joint_dos = False\n self._is_kappa_star = True\n self._is_lbte = False\n self._is_N_U = False\n self._is_reducible_collision_matrix = False\n self._is_symmetrize_fc2 = False\n self._is_symmetrize_fc3_q = False\n self._is_symmetrize_fc3_r = False\n self._mass_variances = None\n self._max_freepath = None\n self._mesh_divisors = None\n self._read_collision = None\n self._read_fc2 = False\n self._read_fc3 = False\n self._read_gamma = False\n self._read_phonon = False\n self._read_pp = False\n self._phonon_supercell_matrix = None\n self._pinv_cutoff = 1.0e-8\n self._pinv_solver = 0\n self._pp_conversion_factor = None\n self._scattering_event_class = None # scattering event class 1 or 2\n self._sigma_cutoff_width = None\n self._solve_collective_phonon = False\n self._use_ave_pp = False\n self._write_collision = False\n self._write_gamma_detail = False\n self._write_gamma = False\n self._write_phonon = False\n self._write_pp = False\n self._write_LBTE_solution = False\n\n def set_boundary_mfp(self, boundary_mfp):\n self._boundary_mfp = boundary_mfp\n\n def get_boundary_mfp(self):\n return self._boundary_mfp\n\n def set_coarse_mesh_shifts(self, coarse_mesh_shifts):\n self._coarse_mesh_shifts = coarse_mesh_shifts\n\n def get_coarse_mesh_shifts(self):\n return self._coarse_mesh_shifts\n\n def set_create_displacements(self, create_displacements):\n self._create_displacements = create_displacements\n\n def get_create_displacements(self):\n return self._create_displacements\n\n def set_constant_averaged_pp_interaction(self, ave_pp):\n self._const_ave_pp = ave_pp\n\n def get_constant_averaged_pp_interaction(self):\n return self._const_ave_pp\n\n def set_cutoff_fc3_distance(self, cutoff_fc3_distance):\n self._cutoff_fc3_distance = cutoff_fc3_distance\n\n def get_cutoff_fc3_distance(self):\n return self._cutoff_fc3_distance\n\n def set_cutoff_pair_distance(self, cutoff_pair_distance):\n self._cutoff_pair_distance = cutoff_pair_distance\n\n def get_cutoff_pair_distance(self):\n return self._cutoff_pair_distance\n\n def set_gamma_conversion_factor(self, gamma_conversion_factor):\n self._gamma_conversion_factor = gamma_conversion_factor\n\n def get_gamma_conversion_factor(self):\n return self._gamma_conversion_factor\n\n def set_grid_addresses(self, grid_addresses):\n self._grid_addresses = grid_addresses\n\n def get_grid_addresses(self):\n return self._grid_addresses\n\n def set_grid_points(self, grid_points):\n self._grid_points = grid_points\n\n def get_grid_points(self):\n return self._grid_points\n\n def set_ion_clamped(self, ion_clamped):\n self._ion_clamped = ion_clamped\n\n def get_ion_clamped(self):\n return self._ion_clamped\n\n def set_is_bterta(self, is_bterta):\n self._is_bterta = is_bterta\n\n def get_is_bterta(self):\n return self._is_bterta\n\n def set_is_compact_fc(self, is_compact_fc):\n self._is_compact_fc = is_compact_fc\n\n def get_is_compact_fc(self):\n return self._is_compact_fc\n\n def set_is_frequency_shift(self, is_frequency_shift):\n self._is_frequency_shift = is_frequency_shift\n\n def get_is_frequency_shift(self):\n return self._is_frequency_shift\n\n def set_is_full_pp(self, is_full_pp):\n self._is_full_pp = is_full_pp\n\n def get_is_full_pp(self):\n return self._is_full_pp\n\n def set_is_gruneisen(self, is_gruneisen):\n self._is_gruneisen = is_gruneisen\n\n def get_is_gruneisen(self):\n return self._is_gruneisen\n\n def set_is_imag_self_energy(self, is_imag_self_energy):\n self._is_imag_self_energy = is_imag_self_energy\n\n def get_is_imag_self_energy(self):\n return self._is_imag_self_energy\n\n def set_is_isotope(self, is_isotope):\n self._is_isotope = is_isotope\n\n def get_is_isotope(self):\n return self._is_isotope\n\n def set_is_joint_dos(self, is_joint_dos):\n self._is_joint_dos = is_joint_dos\n\n def get_is_joint_dos(self):\n return self._is_joint_dos\n\n def set_is_kappa_star(self, is_kappa_star):\n self._is_kappa_star = is_kappa_star\n\n def get_is_kappa_star(self):\n return self._is_kappa_star\n\n def set_is_lbte(self, is_lbte):\n self._is_lbte = is_lbte\n\n def get_is_lbte(self):\n return self._is_lbte\n\n def set_is_N_U(self, is_N_U):\n self._is_N_U = is_N_U\n\n def get_is_N_U(self):\n return self._is_N_U\n\n def set_is_reducible_collision_matrix(self, is_reducible_collision_matrix):\n self._is_reducible_collision_matrix = is_reducible_collision_matrix\n\n def get_is_reducible_collision_matrix(self):\n return self._is_reducible_collision_matrix\n\n def set_is_symmetrize_fc2(self, is_symmetrize_fc2):\n self._is_symmetrize_fc2 = is_symmetrize_fc2\n\n def get_is_symmetrize_fc2(self):\n return self._is_symmetrize_fc2\n\n def set_is_symmetrize_fc3_q(self, is_symmetrize_fc3_q):\n self._is_symmetrize_fc3_q = is_symmetrize_fc3_q\n\n def get_is_symmetrize_fc3_q(self):\n return self._is_symmetrize_fc3_q\n\n def set_is_symmetrize_fc3_r(self, is_symmetrize_fc3_r):\n self._is_symmetrize_fc3_r = is_symmetrize_fc3_r\n\n def get_is_symmetrize_fc3_r(self):\n return self._is_symmetrize_fc3_r\n\n def set_mass_variances(self, mass_variances):\n self._mass_variances = mass_variances\n\n def get_mass_variances(self):\n return self._mass_variances\n\n def set_max_freepath(self, max_freepath):\n self._max_freepath = max_freepath\n\n def get_max_freepath(self):\n return self._max_freepath\n\n def set_mesh_divisors(self, mesh_divisors):\n self._mesh_divisors = mesh_divisors\n\n def get_mesh_divisors(self):\n return self._mesh_divisors\n\n def set_phonon_supercell_matrix(self, matrix):\n self._phonon_supercell_matrix = matrix\n\n def get_phonon_supercell_matrix(self):\n return self._phonon_supercell_matrix\n\n def set_pinv_cutoff(self, pinv_cutoff):\n self._pinv_cutoff = pinv_cutoff\n\n def get_pinv_cutoff(self):\n return self._pinv_cutoff\n\n def set_pinv_solver(self, pinv_solver):\n self._pinv_solver = pinv_solver\n\n def get_pinv_solver(self):\n return self._pinv_solver\n\n def set_pp_conversion_factor(self, pp_conversion_factor):\n self._pp_conversion_factor = pp_conversion_factor\n\n def get_pp_conversion_factor(self):\n return self._pp_conversion_factor\n\n def set_read_collision(self, read_collision):\n self._read_collision = read_collision\n\n def get_read_collision(self):\n return self._read_collision\n\n def set_read_fc2(self, read_fc2):\n self._read_fc2 = read_fc2\n\n def get_read_fc2(self):\n return self._read_fc2\n\n def set_read_fc3(self, read_fc3):\n self._read_fc3 = read_fc3\n\n def get_read_fc3(self):\n return self._read_fc3\n\n def set_read_gamma(self, read_gamma):\n self._read_gamma = read_gamma\n\n def get_read_gamma(self):\n return self._read_gamma\n\n def set_read_phonon(self, read_phonon):\n self._read_phonon = read_phonon\n\n def get_read_phonon(self):\n return self._read_phonon\n\n def set_read_pp(self, read_pp):\n self._read_pp = read_pp\n\n def get_read_pp(self):\n return self._read_pp\n\n def set_scattering_event_class(self, scattering_event_class):\n self._scattering_event_class = scattering_event_class\n\n def get_scattering_event_class(self):\n return self._scattering_event_class\n\n def set_sigma_cutoff_width(self, sigma_cutoff_width):\n self._sigma_cutoff_width = sigma_cutoff_width\n\n def get_sigma_cutoff_width(self):\n return self._sigma_cutoff_width\n\n def set_solve_collective_phonon(self, solve_collective_phonon):\n self._solve_collective_phonon = solve_collective_phonon\n\n def get_solve_collective_phonon(self):\n return self._solve_collective_phonon\n\n def set_use_ave_pp(self, use_ave_pp):\n self._use_ave_pp = use_ave_pp\n\n def get_use_ave_pp(self):\n return self._use_ave_pp\n\n def set_write_collision(self, write_collision):\n self._write_collision = write_collision\n\n def get_write_collision(self):\n return self._write_collision\n\n def set_write_gamma_detail(self, write_gamma_detail):\n self._write_gamma_detail = write_gamma_detail\n\n def get_write_gamma_detail(self):\n return self._write_gamma_detail\n\n def set_write_gamma(self, write_gamma):\n self._write_gamma = write_gamma\n\n def get_write_gamma(self):\n return self._write_gamma\n\n def set_write_phonon(self, write_phonon):\n self._write_phonon = write_phonon\n\n def get_write_phonon(self):\n return self._write_phonon\n\n def set_write_pp(self, write_pp):\n self._write_pp = write_pp\n\n def get_write_pp(self):\n return self._write_pp\n\n def set_write_LBTE_solution(self, write_LBTE_solution):\n self._write_LBTE_solution = write_LBTE_solution\n\n def get_write_LBTE_solution(self):\n return self._write_LBTE_solution\n\n\nclass Phono3pyConfParser(ConfParser):\n def __init__(self, filename=None, args=None):\n self._settings = Phono3pySettings()\n confs = {}\n if filename is not None:\n ConfParser.__init__(self, filename=filename)\n self.read_file() # store .conf file setting in self._confs\n self._parse_conf()\n self._set_settings()\n confs.update(self._confs)\n if args is not None:\n ConfParser.__init__(self, args=args)\n self._read_options()\n self._parse_conf()\n self._set_settings()\n confs.update(self._confs)\n self._confs = confs\n\n def _read_options(self):\n self.read_options() # store data in self._confs\n if 'phonon_supercell_dimension' in self._args:\n dim_fc2 = self._args.phonon_supercell_dimension\n if dim_fc2 is not None:\n self._confs['dim_fc2'] = \" \".join(dim_fc2)\n\n if 'boundary_mfp' in self._args:\n if self._args.boundary_mfp is not None:\n self._confs['boundary_mfp'] = self._args.boundary_mfp\n\n if 'const_ave_pp' in self._args:\n const_ave_pp = self._args.const_ave_pp\n if const_ave_pp is not None:\n self._confs['const_ave_pp'] = const_ave_pp\n\n if 'cutoff_fc3_distance' in self._args:\n cutoff_fc3 = self._args.cutoff_fc3_distance\n if cutoff_fc3 is not None:\n self._confs['cutoff_fc3_distance'] = cutoff_fc3\n\n if 'cutoff_pair_distance' in self._args:\n cutoff_pair = self._args.cutoff_pair_distance\n if cutoff_pair is not None:\n self._confs['cutoff_pair_distance'] = cutoff_pair\n\n if 'gamma_conversion_factor' in self._args:\n g_conv_factor = self._args.gamma_conversion_factor\n if g_conv_factor is not None:\n self._confs['gamma_conversion_factor'] = g_conv_factor\n\n if 'grid_addresses' in self._args:\n grid_adrs = self._args.grid_addresses\n if grid_adrs is not None:\n self._confs['grid_addresses'] = \" \".join(grid_adrs)\n\n if 'grid_points' in self._args:\n if self._args.grid_points is not None:\n self._confs['grid_points'] = \" \".join(self._args.grid_points)\n\n if 'ion_clamped' in self._args:\n if self._args.ion_clamped:\n self._confs['ion_clamped'] = '.true.'\n\n if 'is_bterta' in self._args:\n if self._args.is_bterta:\n self._confs['bterta'] = '.true.'\n\n if 'is_compact_fc' in self._args:\n if self._args.is_compact_fc:\n self._confs['compact_fc'] = '.true.'\n\n if 'is_gruneisen' in self._args:\n if self._args.is_gruneisen:\n self._confs['gruneisen'] = '.true.'\n\n if 'is_displacement' in self._args:\n if self._args.is_displacement:\n self._confs['create_displacements'] = '.true.'\n\n if 'is_frequency_shift' in self._args:\n if self._args.is_frequency_shift:\n self._confs['frequency_shift'] = '.true.'\n\n if 'is_full_pp' in self._args:\n if self._args.is_full_pp:\n self._confs['full_pp'] = '.true.'\n\n if 'is_imag_self_energy' in self._args:\n if self._args.is_imag_self_energy:\n self._confs['imag_self_energy'] = '.true.'\n\n if 'is_isotope' in self._args:\n if self._args.is_isotope:\n self._confs['isotope'] = '.true.'\n\n if 'is_joint_dos' in self._args:\n if self._args.is_joint_dos:\n self._confs['joint_dos'] = '.true.'\n\n if 'no_kappa_stars' in self._args:\n if self._args.no_kappa_stars:\n self._confs['kappa_star'] = '.false.'\n\n if 'is_lbte' in self._args:\n if self._args.is_lbte:\n self._confs['lbte'] = '.true.'\n\n if 'is_N_U' in self._args:\n if self._args.is_N_U:\n self._confs['N_U'] = '.true.'\n\n if 'is_reducible_collision_matrix' in self._args:\n if self._args.is_reducible_collision_matrix:\n self._confs['reducible_collision_matrix'] = '.true.'\n\n if 'is_symmetrize_fc2' in self._args:\n if self._args.is_symmetrize_fc2:\n self._confs['symmetrize_fc2'] = '.true.'\n\n if 'is_symmetrize_fc3_q' in self._args:\n if self._args.is_symmetrize_fc3_q:\n self._confs['symmetrize_fc3_q'] = '.true.'\n\n if 'is_symmetrize_fc3_r' in self._args:\n if self._args.is_symmetrize_fc3_r:\n self._confs['symmetrize_fc3_r'] = '.true.'\n\n if 'mass_variances' in self._args:\n mass_variances = self._args.mass_variances\n if mass_variances is not None:\n self._confs['mass_variances'] = \" \".join(mass_variances)\n\n if 'max_freepath' in self._args:\n if self._args.max_freepath is not None:\n self._confs['max_freepath'] = self._args.max_freepath\n\n if 'mesh_divisors' in self._args:\n mesh_divisors = self._args.mesh_divisors\n if mesh_divisors is not None:\n self._confs['mesh_divisors'] = \" \".join(mesh_divisors)\n\n if 'pinv_cutoff' in self._args:\n if self._args.pinv_cutoff is not None:\n self._confs['pinv_cutoff'] = self._args.pinv_cutoff\n\n if 'pinv_solver' in self._args:\n if self._args.pinv_solver is not None:\n self._confs['pinv_solver'] = self._args.pinv_solver\n\n if 'pp_conversion_factor' in self._args:\n pp_conv_factor = self._args.pp_conversion_factor\n if pp_conv_factor is not None:\n self._confs['pp_conversion_factor'] = pp_conv_factor\n\n if 'read_fc2' in self._args:\n if self._args.read_fc2:\n self._confs['read_fc2'] = '.true.'\n\n if 'read_fc3' in self._args:\n if self._args.read_fc3:\n self._confs['read_fc3'] = '.true.'\n\n if 'read_gamma' in self._args:\n if self._args.read_gamma:\n self._confs['read_gamma'] = '.true.'\n\n if 'read_phonon' in self._args:\n if self._args.read_phonon:\n self._confs['read_phonon'] = '.true.'\n\n if 'read_pp' in self._args:\n if self._args.read_pp:\n self._confs['read_pp'] = '.true.'\n\n if 'read_collision' in self._args:\n if self._args.read_collision is not None:\n self._confs['read_collision'] = self._args.read_collision\n\n if 'scattering_event_class' in self._args:\n scatt_class = self._args.scattering_event_class\n if scatt_class is not None:\n self._confs['scattering_event_class'] = scatt_class\n\n if 'sigma_cutoff_width' in self._args:\n sigma_cutoff = self._args.sigma_cutoff_width\n if sigma_cutoff is not None:\n self._confs['sigma_cutoff_width'] = sigma_cutoff\n\n if 'solve_collective_phonon' in self._args:\n if self._args.solve_collective_phonon:\n self._confs['collective_phonon'] = '.true.'\n\n if 'use_ave_pp' in self._args:\n if self._args.use_ave_pp:\n self._confs['use_ave_pp'] = '.true.'\n\n if 'write_gamma_detail' in self._args:\n if self._args.write_gamma_detail:\n self._confs['write_gamma_detail'] = '.true.'\n\n if 'write_gamma' in self._args:\n if self._args.write_gamma:\n self._confs['write_gamma'] = '.true.'\n\n if 'write_collision' in self._args:\n if self._args.write_collision:\n self._confs['write_collision'] = '.true.'\n\n if 'write_phonon' in self._args:\n if self._args.write_phonon:\n self._confs['write_phonon'] = '.true.'\n\n if 'write_pp' in self._args:\n if self._args.write_pp:\n self._confs['write_pp'] = '.true.'\n\n if 'write_LBTE_solution' in self._args:\n if self._args.write_LBTE_solution:\n self._confs['write_LBTE_solution'] = '.true.'\n\n def _parse_conf(self):\n self.parse_conf()\n confs = self._confs\n\n for conf_key in confs.keys():\n if conf_key == 'create_displacements':\n if confs['create_displacements'].lower() == '.false.':\n self.set_parameter('create_displacements', False)\n elif confs['create_displacements'].lower() == '.true.':\n self.set_parameter('create_displacements', True)\n\n if conf_key == 'dim_fc2':\n matrix = [ int(x) for x in confs['dim_fc2'].split() ]\n if len(matrix) == 9:\n matrix = np.array(matrix).reshape(3, 3)\n elif len(matrix) == 3:\n matrix = np.diag(matrix)\n else:\n self.setting_error(\n \"Number of elements of dim2 has to be 3 or 9.\")\n\n if matrix.shape == (3, 3):\n if np.linalg.det(matrix) < 1:\n self.setting_error(\n \"Determinant of supercell matrix has \" +\n \"to be positive.\")\n else:\n self.set_parameter('dim_fc2', matrix)\n\n if conf_key == 'boundary_mfp':\n self.set_parameter('boundary_mfp',\n float(confs['boundary_mfp']))\n\n if conf_key in ('constant_averaged_pp_interaction'\n 'const_ave_pp'):\n self.set_parameter('const_ave_pp', float(confs['const_ave_pp']))\n\n if conf_key == 'cutoff_fc3_distance':\n self.set_parameter('cutoff_fc3_distance',\n float(confs['cutoff_fc3_distance']))\n\n if conf_key == 'cutoff_pair_distance':\n self.set_parameter('cutoff_pair_distance',\n float(confs['cutoff_pair_distance']))\n\n if conf_key == 'full_pp':\n if confs['full_pp'].lower() == '.false.':\n self.set_parameter('is_full_pp', False)\n elif confs['full_pp'].lower() == '.true.':\n self.set_parameter('is_full_pp', True)\n\n if conf_key == 'gamma_conversion_factor':\n self.set_parameter('gamma_conversion_factor',\n float(confs['gamma_conversion_factor']))\n\n if conf_key == 'grid_addresses':\n vals = [int(x) for x in\n confs['grid_addresses'].replace(',', ' ').split()]\n if len(vals) % 3 == 0 and len(vals) > 0:\n self.set_parameter('grid_addresses',\n np.reshape(vals, (-1, 3)))\n else:\n self.setting_error(\"Grid addresses are incorrectly set.\")\n\n if conf_key == 'grid_points':\n vals = [int(x) for x in\n confs['grid_points'].replace(',', ' ').split()]\n self.set_parameter('grid_points', vals)\n\n if conf_key == 'ion_clamped':\n if confs['ion_clamped'].lower() == '.false.':\n self.set_parameter('ion_clamped', False)\n elif confs['ion_clamped'].lower() == '.true.':\n self.set_parameter('ion_clamped', True)\n\n if conf_key == 'bterta':\n if confs['bterta'].lower() == '.false.':\n self.set_parameter('is_bterta', False)\n elif confs['bterta'].lower() == '.true.':\n self.set_parameter('is_bterta', True)\n\n if conf_key == 'compact_fc':\n if confs['compact_fc'].lower() == '.false.':\n self.set_parameter('is_compact_fc', False)\n elif confs['compact_fc'].lower() == '.true.':\n self.set_parameter('is_compact_fc', True)\n\n if conf_key == 'frequency_shift':\n if confs['frequency_shift'].lower() == '.false.':\n self.set_parameter('is_frequency_shift', False)\n elif confs['frequency_shift'].lower() == '.true.':\n self.set_parameter('is_frequency_shift', True)\n\n if conf_key == 'gruneisen':\n if confs['gruneisen'].lower() == '.false.':\n self.set_parameter('is_gruneisen', False)\n elif confs['gruneisen'].lower() == '.true.':\n self.set_parameter('is_gruneisen', True)\n\n if conf_key == 'imag_self_energy':\n if confs['imag_self_energy'].lower() == '.false.':\n self.set_parameter('is_imag_self_energy', False)\n elif confs['imag_self_energy'].lower() == '.true.':\n self.set_parameter('is_imag_self_energy', True)\n\n if conf_key == 'isotope':\n if confs['isotope'].lower() == '.false.':\n self.set_parameter('is_isotope', False)\n elif confs['isotope'].lower() == '.true.':\n self.set_parameter('is_isotope', True)\n\n if conf_key == 'joint_dos':\n if confs['joint_dos'].lower() == '.false.':\n self.set_parameter('is_joint_dos', False)\n elif confs['joint_dos'].lower() == '.true.':\n self.set_parameter('is_joint_dos', True)\n\n if conf_key == 'lbte':\n if confs['lbte'].lower() == '.false.':\n self.set_parameter('is_lbte', False)\n elif confs['lbte'].lower() == '.true.':\n self.set_parameter('is_lbte', True)\n\n if conf_key == 'N_U':\n if confs['N_U'].lower() == '.false.':\n self.set_parameter('is_N_U', False)\n elif confs['N_U'].lower() == '.true.':\n self.set_parameter('is_N_U', True)\n\n if conf_key == 'reducible_collision_matrix':\n if confs['reducible_collision_matrix'].lower() == '.false.':\n self.set_parameter('is_reducible_collision_matrix', False)\n elif confs['reducible_collision_matrix'].lower() == '.true.':\n self.set_parameter('is_reducible_collision_matrix', True)\n\n if conf_key == 'symmetrize_fc2':\n if confs['symmetrize_fc2'].lower() == '.false.':\n self.set_parameter('is_symmetrize_fc2', False)\n elif confs['symmetrize_fc2'].lower() == '.true.':\n self.set_parameter('is_symmetrize_fc2', True)\n\n if conf_key == 'symmetrize_fc3_q':\n if confs['symmetrize_fc3_q'].lower() == '.false.':\n self.set_parameter('is_symmetrize_fc3_q', False)\n elif confs['symmetrize_fc3_q'].lower() == '.true.':\n self.set_parameter('is_symmetrize_fc3_q', True)\n\n if conf_key == 'symmetrize_fc3_r':\n if confs['symmetrize_fc3_r'].lower() == '.false.':\n self.set_parameter('is_symmetrize_fc3_r', False)\n elif confs['symmetrize_fc3_r'].lower() == '.true.':\n self.set_parameter('is_symmetrize_fc3_r', True)\n\n if conf_key == 'mass_variances':\n vals = [fracval(x) for x in confs['mass_variances'].split()]\n if len(vals) < 1:\n self.setting_error(\"Mass variance parameters are incorrectly set.\")\n else:\n self.set_parameter('mass_variances', vals)\n\n if conf_key == 'max_freepath':\n self.set_parameter('max_freepath', float(confs['max_freepath']))\n\n if conf_key == 'mesh_divisors':\n vals = [x for x in confs['mesh_divisors'].split()]\n if len(vals) == 3:\n self.set_parameter('mesh_divisors', [int(x) for x in vals])\n elif len(vals) == 6:\n divs = [int(x) for x in vals[:3]]\n is_shift = [x.lower() == 't' for x in vals[3:]]\n for i in range(3):\n if is_shift[i] and (divs[i] % 2 != 0):\n is_shift[i] = False\n self.setting_error(\"Coarse grid shift along the \" +\n [\"first\", \"second\", \"third\"][i] +\n \" axis is not allowed.\")\n self.set_parameter('mesh_divisors', divs + is_shift)\n else:\n self.setting_error(\"Mesh divisors are incorrectly set.\")\n\n if conf_key == 'kappa_star':\n if confs['kappa_star'].lower() == '.false.':\n self.set_parameter('is_kappa_star', False)\n elif confs['kappa_star'].lower() == '.true.':\n self.set_parameter('is_kappa_star', True)\n\n if conf_key == 'pinv_cutoff':\n self.set_parameter('pinv_cutoff', float(confs['pinv_cutoff']))\n\n if conf_key == 'pinv_solver':\n self.set_parameter('pinv_solver', int(confs['pinv_solver']))\n\n if conf_key == 'pp_conversion_factor':\n self.set_parameter('pp_conversion_factor',\n float(confs['pp_conversion_factor']))\n\n if conf_key == 'read_collision':\n if confs['read_collision'] == 'all':\n self.set_parameter('read_collision', 'all')\n else:\n vals = [int(x) for x in confs['read_collision'].split()]\n self.set_parameter('read_collision', vals)\n\n if conf_key == 'read_fc2':\n if confs['read_fc2'].lower() == '.false.':\n self.set_parameter('read_fc2', False)\n elif confs['read_fc2'].lower() == '.true.':\n self.set_parameter('read_fc2', True)\n\n if conf_key == 'read_fc3':\n if confs['read_fc3'].lower() == '.false.':\n self.set_parameter('read_fc3', False)\n elif confs['read_fc3'].lower() == '.true.':\n self.set_parameter('read_fc3', True)\n\n if conf_key == 'read_gamma':\n if confs['read_gamma'].lower() == '.false.':\n self.set_parameter('read_gamma', False)\n elif confs['read_gamma'].lower() == '.true.':\n self.set_parameter('read_gamma', True)\n\n if conf_key == 'read_phonon':\n if confs['read_phonon'].lower() == '.false.':\n self.set_parameter('read_phonon', False)\n elif confs['read_phonon'].lower() == '.true.':\n self.set_parameter('read_phonon', True)\n\n if conf_key == 'read_pp':\n if confs['read_pp'].lower() == '.false.':\n self.set_parameter('read_pp', False)\n elif confs['read_pp'].lower() == '.true.':\n self.set_parameter('read_pp', True)\n\n if conf_key == 'scattering_event_class':\n self.set_parameter('scattering_event_class',\n confs['scattering_event_class'])\n\n if conf_key == 'sigma_cutoff_width':\n self.set_parameter('sigma_cutoff_width',\n float(confs['sigma_cutoff_width']))\n\n if conf_key == 'collective_phonon':\n if confs['collective_phonon'].lower() == '.false.':\n self.set_parameter('collective_phonon', False)\n elif confs['collective_phonon'].lower() == '.true.':\n self.set_parameter('collective_phonon', True)\n\n if conf_key == 'use_ave_pp':\n if confs['use_ave_pp'].lower() == '.false.':\n self.set_parameter('use_ave_pp', False)\n elif confs['use_ave_pp'].lower() == '.true.':\n self.set_parameter('use_ave_pp', True)\n\n if conf_key == 'write_gamma_detail':\n if confs['write_gamma_detail'].lower() == '.false.':\n self.set_parameter('write_gamma_detail', False)\n elif confs['write_gamma_detail'].lower() == '.true.':\n self.set_parameter('write_gamma_detail', True)\n\n if conf_key == 'write_gamma':\n if confs['write_gamma'].lower() == '.false.':\n self.set_parameter('write_gamma', False)\n elif confs['write_gamma'].lower() == '.true.':\n self.set_parameter('write_gamma', True)\n\n if conf_key == 'write_collision':\n if confs['write_collision'].lower() == '.false.':\n self.set_parameter('write_collision', False)\n elif confs['write_collision'].lower() == '.true.':\n self.set_parameter('write_collision', True)\n\n if conf_key == 'write_phonon':\n if confs['write_phonon'].lower() == '.false.':\n self.set_parameter('write_phonon', False)\n elif confs['write_phonon'].lower() == '.true.':\n self.set_parameter('write_phonon', True)\n\n if conf_key == 'write_pp':\n if confs['write_pp'].lower() == '.false.':\n self.set_parameter('write_pp', False)\n elif confs['write_pp'].lower() == '.true.':\n self.set_parameter('write_pp', True)\n\n if conf_key == 'write_LBTE_solution':\n if confs['write_LBTE_solution'].lower() == '.false.':\n self.set_parameter('write_LBTE_solution', False)\n elif confs['write_LBTE_solution'].lower() == '.true.':\n self.set_parameter('write_LBTE_solution', True)\n\n def _set_settings(self):\n self.set_settings()\n params = self._parameters\n\n # Is getting least displacements?\n if 'create_displacements' in params:\n if params['create_displacements']:\n self._settings.set_create_displacements('displacements')\n\n # Supercell dimension for fc2\n if 'dim_fc2' in params:\n self._settings.set_phonon_supercell_matrix(params['dim_fc2'])\n\n # Boundary mean free path for thermal conductivity calculation\n if 'boundary_mfp' in params:\n self._settings.set_boundary_mfp(params['boundary_mfp'])\n\n # Peierls type approximation for squared ph-ph interaction strength\n if 'const_ave_pp' in params:\n self._settings.set_constant_averaged_pp_interaction(\n params['const_ave_pp'])\n\n # Cutoff distance of third-order force constants. Elements where any\n # pair of atoms has larger distance than cut-off distance are set zero.\n if 'cutoff_fc3_distance' in params:\n self._settings.set_cutoff_fc3_distance(params['cutoff_fc3_distance'])\n\n # Cutoff distance between pairs of displaced atoms used for supercell\n # creation with displacements and making third-order force constants\n if 'cutoff_pair_distance' in params:\n self._settings.set_cutoff_pair_distance(\n params['cutoff_pair_distance'])\n\n # Gamma unit conversion factor\n if 'gamma_conversion_factor' in params:\n self._settings.set_gamma_conversion_factor(\n params['gamma_conversion_factor'])\n\n # Grid addresses (sets of three integer values)\n if 'grid_addresses' in params:\n self._settings.set_grid_addresses(params['grid_addresses'])\n\n # Grid points\n if 'grid_points' in params:\n self._settings.set_grid_points(params['grid_points'])\n\n # Atoms are clamped under applied strain in Gruneisen parameter calculation\n if 'ion_clamped' in params:\n self._settings.set_ion_clamped(params['ion_clamped'])\n\n # Calculate thermal conductivity in BTE-RTA\n if 'is_bterta' in params:\n self._settings.set_is_bterta(params['is_bterta'])\n\n # Compact force constants or full force constants\n if 'is_compact_fc' in params:\n self._settings.set_is_compact_fc(params['is_compact_fc'])\n\n # Calculate frequency_shifts\n if 'is_frequency_shift' in params:\n self._settings.set_is_frequency_shift(params['is_frequency_shift'])\n\n # Calculate full ph-ph interaction strength for RTA conductivity\n if 'is_full_pp' in params:\n self._settings.set_is_full_pp(params['is_full_pp'])\n\n # Calculate phonon-Gruneisen parameters\n if 'is_gruneisen' in params:\n self._settings.set_is_gruneisen(params['is_gruneisen'])\n\n # Calculate imaginary part of self energy\n if 'is_imag_self_energy' in params:\n self._settings.set_is_imag_self_energy(params['is_imag_self_energy'])\n\n # Calculate lifetime due to isotope scattering\n if 'is_isotope' in params:\n self._settings.set_is_isotope(params['is_isotope'])\n\n # Calculate joint-DOS\n if 'is_joint_dos' in params:\n self._settings.set_is_joint_dos(params['is_joint_dos'])\n\n # Calculate thermal conductivity in LBTE with Chaput's method\n if 'is_lbte' in params:\n self._settings.set_is_lbte(params['is_lbte'])\n\n # Calculate Normal and Umklapp processes\n if 'is_N_U' in params:\n self._settings.set_is_N_U(params['is_N_U'])\n\n # Solve reducible collision matrix but not reduced matrix\n if 'is_reducible_collision_matrix' in params:\n self._settings.set_is_reducible_collision_matrix(\n params['is_reducible_collision_matrix'])\n\n # Symmetrize fc2 by index exchange\n if 'is_symmetrize_fc2' in params:\n self._settings.set_is_symmetrize_fc2(params['is_symmetrize_fc2'])\n\n # Symmetrize phonon fc3 by index exchange\n if 'is_symmetrize_fc3_q' in params:\n self._settings.set_is_symmetrize_fc3_q(params['is_symmetrize_fc3_q'])\n\n # Symmetrize fc3 by index exchange\n if 'is_symmetrize_fc3_r' in params:\n self._settings.set_is_symmetrize_fc3_r(params['is_symmetrize_fc3_r'])\n\n # Mass variance parameters\n if 'mass_variances' in params:\n self._settings.set_mass_variances(params['mass_variances'])\n\n # Maximum mean free path\n if 'max_freepath' in params:\n self._settings.set_max_freepath(params['max_freepath'])\n\n # Divisors for mesh numbers\n if 'mesh_divisors' in params:\n self._settings.set_mesh_divisors(params['mesh_divisors'][:3])\n if len(params['mesh_divisors']) > 3:\n self._settings.set_coarse_mesh_shifts(\n params['mesh_divisors'][3:])\n\n # Cutoff frequency for pseudo inversion of collision matrix\n if 'pinv_cutoff' in params:\n self._settings.set_pinv_cutoff(params['pinv_cutoff'])\n\n # Switch for pseudo-inverse solver\n if 'pinv_solver' in params:\n self._settings.set_pinv_solver(params['pinv_solver'])\n\n # Ph-ph interaction unit conversion factor\n if 'pp_conversion_factor' in params:\n self._settings.set_pp_conversion_factor(params['pp_conversion_factor'])\n\n # Read phonon-phonon interaction amplitudes from hdf5\n if 'read_amplitude' in params:\n self._settings.set_read_amplitude(params['read_amplitude'])\n\n # Read collision matrix and gammas from hdf5\n if 'read_collision' in params:\n self._settings.set_read_collision(params['read_collision'])\n\n # Read fc2 from hdf5\n if 'read_fc2' in params:\n self._settings.set_read_fc2(params['read_fc2'])\n\n # Read fc3 from hdf5\n if 'read_fc3' in params:\n self._settings.set_read_fc3(params['read_fc3'])\n\n # Read gammas from hdf5\n if 'read_gamma' in params:\n self._settings.set_read_gamma(params['read_gamma'])\n\n # Read phonons from hdf5\n if 'read_phonon' in params:\n self._settings.set_read_phonon(params['read_phonon'])\n\n # Read ph-ph interaction strength from hdf5\n if 'read_pp' in params:\n self._settings.set_read_pp(params['read_pp'])\n\n # Sum partial kappa at q-stars\n if 'is_kappa_star' in params:\n self._settings.set_is_kappa_star(params['is_kappa_star'])\n\n # Scattering event class 1 or 2\n if 'scattering_event_class' in params:\n self._settings.set_scattering_event_class(\n params['scattering_event_class'])\n\n # Cutoff width of smearing function (ratio to sigma value)\n if 'sigma_cutoff_width' in params:\n self._settings.set_sigma_cutoff_width(params['sigma_cutoff_width'])\n\n # Solve collective phonons\n if 'collective_phonon' in params:\n self._settings.set_solve_collective_phonon(\n params['collective_phonon'])\n\n # Use averaged ph-ph interaction\n if 'use_ave_pp' in params:\n self._settings.set_use_ave_pp(params['use_ave_pp'])\n\n # Write detailed imag-part of self energy to hdf5\n if 'write_gamma_detail' in params:\n self._settings.set_write_gamma_detail(\n params['write_gamma_detail'])\n\n # Write imag-part of self energy to hdf5\n if 'write_gamma' in params:\n self._settings.set_write_gamma(params['write_gamma'])\n\n # Write collision matrix and gammas to hdf5\n if 'write_collision' in params:\n self._settings.set_write_collision(params['write_collision'])\n\n # Write all phonons on grid points to hdf5\n if 'write_phonon' in params:\n self._settings.set_write_phonon(params['write_phonon'])\n\n # Write phonon-phonon interaction amplitudes to hdf5\n if 'write_pp' in params:\n self._settings.set_write_pp(params['write_pp'])\n\n # Write direct solution of LBTE to hdf5 files\n if 'write_LBTE_solution' in params:\n self._settings.set_write_LBTE_solution(\n params['write_LBTE_solution'])\n" ]
[ [ "numpy.array", "numpy.linalg.det", "numpy.reshape", "numpy.diag" ] ]
bputman/schrutepy
[ "68f18a4e47a77bcfc92e0f76c3ba6bb135add65c" ]
[ "schrutepy/schrutepy.py" ]
[ "import pandas\n\n\ndef load_schrute():\n \"\"\"\n The entire script transcriptions from The Office in pandas dataframe format.\n \"\"\"\n\n full_path = \"https://github.com/bradlindblad/schrutepy/raw/master/data/schrute.csv\"\n\n df = pandas.read_csv(full_path)\n df = df.drop(\"Unnamed: 0\", axis=1)\n\n return df\n" ]
[ [ "pandas.read_csv" ] ]
joshrose/Horizon
[ "a2eb407b31a16560ae78aa6751eb83672a122a7e" ]
[ "ml/rl/test/gym/world_model/mdnrnn_gym.py" ]
[ "#!/usr/bin/env python3\n# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.\n\"\"\"\nLearn a world model on gym environments\n\"\"\"\nimport argparse\nimport json\nimport logging\nimport sys\nfrom typing import Dict, Optional\n\nimport ml.rl.types as rlt\nimport numpy as np\nimport torch\nfrom ml.rl.evaluation.world_model_evaluator import (\n FeatureImportanceEvaluator,\n FeatureSensitivityEvaluator,\n)\nfrom ml.rl.json_serialize import json_to_object\nfrom ml.rl.models.mdn_rnn import MDNRNNMemoryPool\nfrom ml.rl.models.world_model import MemoryNetwork\nfrom ml.rl.parameters import MDNRNNParameters, OpenAiGymParameters, OpenAiRunDetails\nfrom ml.rl.test.gym.open_ai_gym_environment import (\n EnvType,\n ModelType,\n OpenAIGymEnvironment,\n)\nfrom ml.rl.test.gym.run_gym import dict_to_np, get_possible_actions\nfrom ml.rl.training.rl_dataset import RLDataset\nfrom ml.rl.training.world_model.mdnrnn_trainer import MDNRNNTrainer\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef loss_to_num(losses):\n return {k: v.item() for k, v in losses.items()}\n\n\ndef multi_step_sample_generator(\n gym_env: OpenAIGymEnvironment,\n num_transitions: int,\n max_steps: Optional[int],\n multi_steps: int,\n include_shorter_samples_at_start: bool,\n include_shorter_samples_at_end: bool,\n):\n \"\"\"\n Convert gym env multi-step sample format to mdn-rnn multi-step sample format\n\n :param gym_env: The environment used to generate multi-step samples\n :param num_transitions: # of samples to return\n :param max_steps: An episode terminates when the horizon is beyond max_steps\n :param multi_steps: # of steps of states and actions per sample\n :param include_shorter_samples_at_start: Whether to keep samples of shorter steps\n which are generated at the beginning of an episode\n :param include_shorter_samples_at_end: Whether to keep samples of shorter steps\n which are generated at the end of an episode\n \"\"\"\n samples = gym_env.generate_random_samples(\n num_transitions=num_transitions,\n use_continuous_action=True,\n max_step=max_steps,\n multi_steps=multi_steps,\n include_shorter_samples_at_start=include_shorter_samples_at_start,\n include_shorter_samples_at_end=include_shorter_samples_at_end,\n )\n\n for j in range(num_transitions):\n sample_steps = len(samples.terminals[j]) # type: ignore\n state = dict_to_np(samples.states[j], np_size=gym_env.state_dim, key_offset=0)\n action = dict_to_np(\n samples.actions[j], np_size=gym_env.action_dim, key_offset=gym_env.state_dim\n )\n next_actions = np.float32( # type: ignore\n [\n dict_to_np(\n samples.next_actions[j][k],\n np_size=gym_env.action_dim,\n key_offset=gym_env.state_dim,\n )\n for k in range(sample_steps)\n ]\n )\n next_states = np.float32( # type: ignore\n [\n dict_to_np(\n samples.next_states[j][k], np_size=gym_env.state_dim, key_offset=0\n )\n for k in range(sample_steps)\n ]\n )\n rewards = np.float32(samples.rewards[j]) # type: ignore\n terminals = np.float32(samples.terminals[j]) # type: ignore\n not_terminals = np.logical_not(terminals)\n ordered_states = np.vstack((state, next_states))\n ordered_actions = np.vstack((action, next_actions))\n mdnrnn_states = ordered_states[:-1]\n mdnrnn_actions = ordered_actions[:-1]\n mdnrnn_next_states = ordered_states[-multi_steps:]\n mdnrnn_next_actions = ordered_actions[-multi_steps:]\n\n # Padding zeros so that all samples have equal steps\n # The general rule is to pad zeros at the end of sequences.\n # In addition, if the sequence only has one step (i.e., the\n # first state of an episode), pad one zero row ahead of the\n # sequence, which enables embedding generated properly for\n # one-step samples\n num_padded_top_rows = 1 if multi_steps > 1 and sample_steps == 1 else 0\n num_padded_bottom_rows = multi_steps - sample_steps - num_padded_top_rows\n sample_steps_next = len(mdnrnn_next_states)\n num_padded_top_rows_next = 0\n num_padded_bottom_rows_next = multi_steps - sample_steps_next\n yield (\n np.pad(\n mdnrnn_states,\n ((num_padded_top_rows, num_padded_bottom_rows), (0, 0)),\n \"constant\",\n constant_values=0.0,\n ),\n np.pad(\n mdnrnn_actions,\n ((num_padded_top_rows, num_padded_bottom_rows), (0, 0)),\n \"constant\",\n constant_values=0.0,\n ),\n np.pad(\n rewards,\n ((num_padded_top_rows, num_padded_bottom_rows)),\n \"constant\",\n constant_values=0.0,\n ),\n np.pad(\n mdnrnn_next_states,\n ((num_padded_top_rows_next, num_padded_bottom_rows_next), (0, 0)),\n \"constant\",\n constant_values=0.0,\n ),\n np.pad(\n mdnrnn_next_actions,\n ((num_padded_top_rows_next, num_padded_bottom_rows_next), (0, 0)),\n \"constant\",\n constant_values=0.0,\n ),\n np.pad(\n not_terminals,\n ((num_padded_top_rows, num_padded_bottom_rows)),\n \"constant\",\n constant_values=0.0,\n ),\n sample_steps,\n sample_steps_next,\n )\n\n\ndef get_replay_buffer(\n num_episodes: int, seq_len: int, max_step: int, gym_env: OpenAIGymEnvironment\n) -> MDNRNNMemoryPool:\n num_transitions = num_episodes * max_step\n replay_buffer = MDNRNNMemoryPool(max_replay_memory_size=num_transitions)\n for (\n mdnrnn_state,\n mdnrnn_action,\n rewards,\n next_states,\n _,\n not_terminals,\n _,\n _,\n ) in multi_step_sample_generator(\n gym_env,\n num_transitions=num_transitions,\n max_steps=max_step,\n multi_steps=seq_len,\n include_shorter_samples_at_start=False,\n include_shorter_samples_at_end=False,\n ):\n mdnrnn_state, mdnrnn_action, next_states, rewards, not_terminals = (\n torch.tensor(mdnrnn_state),\n torch.tensor(mdnrnn_action),\n torch.tensor(next_states),\n torch.tensor(rewards),\n torch.tensor(not_terminals),\n )\n replay_buffer.insert_into_memory(\n mdnrnn_state, mdnrnn_action, next_states, rewards, not_terminals\n )\n\n return replay_buffer\n\n\ndef main(args):\n parser = argparse.ArgumentParser(\n description=\"Train a Mixture-Density-Network RNN net to learn an OpenAI\"\n \" Gym environment, i.e., predict next state, reward, and\"\n \" terminal signal using current state and action\"\n )\n parser.add_argument(\"-p\", \"--parameters\", help=\"Path to JSON parameters file.\")\n parser.add_argument(\n \"-g\",\n \"--gpu_id\",\n help=\"If set, will use GPU with specified ID. Otherwise will use CPU.\",\n default=-1,\n )\n parser.add_argument(\n \"-l\",\n \"--log_level\",\n choices=[\"debug\", \"info\", \"warning\", \"error\", \"critical\"],\n help=\"If set, use logging level specified (debug, info, warning, error, \"\n \"critical). Else defaults to info.\",\n default=\"info\",\n )\n parser.add_argument(\n \"-f\",\n \"--feature_importance\",\n action=\"store_true\",\n help=\"If set, feature importance will be calculated after the training\",\n )\n parser.add_argument(\n \"-s\",\n \"--feature_sensitivity\",\n action=\"store_true\",\n help=\"If set, state feature sensitivity by varying actions will be\"\n \" calculated after the training\",\n )\n parser.add_argument(\n \"-e\",\n \"--save_embedding_to_path\",\n help=\"If a file path is provided, save a RLDataset with states embedded\"\n \" by the trained world model\",\n )\n args = parser.parse_args(args)\n\n logger.setLevel(getattr(logging, args.log_level.upper()))\n\n with open(args.parameters, \"r\") as f:\n params = json_to_object(f.read(), OpenAiGymParameters)\n if args.gpu_id != -1:\n params = params._replace(use_gpu=True)\n\n mdnrnn_gym(\n params,\n args.feature_importance,\n args.feature_sensitivity,\n args.save_embedding_to_path,\n )\n\n\ndef mdnrnn_gym(\n params: OpenAiGymParameters,\n feature_importance: bool = False,\n feature_sensitivity: bool = False,\n save_embedding_to_path: Optional[str] = None,\n seed: Optional[int] = None,\n):\n assert params.mdnrnn is not None\n use_gpu = params.use_gpu\n logger.info(\"Running gym with params\")\n logger.info(params)\n\n env_type = params.env\n env = OpenAIGymEnvironment(\n env_type, epsilon=1.0, softmax_policy=True, gamma=0.99, random_seed=seed\n )\n\n # create test data once\n assert params.run_details.max_steps is not None\n test_replay_buffer = get_replay_buffer(\n params.run_details.num_test_episodes,\n params.run_details.seq_len,\n params.run_details.max_steps,\n env,\n )\n test_batch = test_replay_buffer.sample_memories(\n test_replay_buffer.memory_size, use_gpu=use_gpu, batch_first=True\n )\n\n trainer = create_trainer(params, env, use_gpu)\n _, _, trainer = train_sgd(\n env,\n trainer,\n use_gpu,\n \"{} test run\".format(env_type),\n params.mdnrnn.minibatch_size,\n params.run_details,\n test_batch=test_batch,\n )\n feature_importance_map, feature_sensitivity_map, dataset = None, None, None\n if feature_importance:\n feature_importance_map = calculate_feature_importance(\n env, trainer, use_gpu, params.run_details, test_batch=test_batch\n )\n if feature_sensitivity:\n feature_sensitivity_map = calculate_feature_sensitivity_by_actions(\n env, trainer, use_gpu, params.run_details, test_batch=test_batch\n )\n if save_embedding_to_path:\n dataset = RLDataset(save_embedding_to_path)\n create_embed_rl_dataset(env, trainer, dataset, use_gpu, params.run_details)\n dataset.save()\n return env, trainer, feature_importance_map, feature_sensitivity_map, dataset\n\n\ndef calculate_feature_importance(\n gym_env: OpenAIGymEnvironment,\n trainer: MDNRNNTrainer,\n use_gpu: bool,\n run_details: OpenAiRunDetails,\n test_batch: rlt.PreprocessedTrainingBatch,\n):\n assert run_details.max_steps is not None\n assert run_details.num_test_episodes is not None\n assert run_details.seq_len is not None\n feature_importance_evaluator = FeatureImportanceEvaluator(\n trainer,\n discrete_action=gym_env.action_type == EnvType.DISCRETE_ACTION,\n state_feature_num=gym_env.state_dim,\n action_feature_num=gym_env.action_dim,\n sorted_action_feature_start_indices=list(range(gym_env.action_dim)),\n sorted_state_feature_start_indices=list(range(gym_env.state_dim)),\n )\n feature_loss_vector = feature_importance_evaluator.evaluate(test_batch)[\n \"feature_loss_increase\"\n ]\n feature_importance_map = {}\n for i in range(gym_env.action_dim):\n print(\n \"action {}, feature importance: {}\".format(i, feature_loss_vector[i].item())\n )\n feature_importance_map[f\"action{i}\"] = feature_loss_vector[i].item()\n for i in range(gym_env.state_dim):\n print(\n \"state {}, feature importance: {}\".format(\n i, feature_loss_vector[i + gym_env.action_dim].item()\n )\n )\n feature_importance_map[f\"state{i}\"] = feature_loss_vector[\n i + gym_env.action_dim\n ].item()\n return feature_importance_map\n\n\ndef create_embed_rl_dataset(\n gym_env: OpenAIGymEnvironment,\n trainer: MDNRNNTrainer,\n dataset: RLDataset,\n use_gpu: bool,\n run_details: OpenAiRunDetails,\n):\n assert run_details.max_steps is not None\n old_mdnrnn_mode = trainer.mdnrnn.mdnrnn.training\n trainer.mdnrnn.mdnrnn.eval()\n num_transitions = run_details.num_state_embed_episodes * run_details.max_steps\n device = torch.device(\"cuda\") if use_gpu else torch.device(\"cpu\") # type: ignore\n\n (\n state_batch,\n action_batch,\n reward_batch,\n next_state_batch,\n next_action_batch,\n not_terminal_batch,\n step_batch,\n next_step_batch,\n ) = map(\n list,\n zip(\n *multi_step_sample_generator(\n gym_env=gym_env,\n num_transitions=num_transitions,\n max_steps=run_details.max_steps,\n # +1 because MDNRNN embeds the first seq_len steps and then\n # the embedded state will be concatenated with the last step\n multi_steps=run_details.seq_len + 1,\n include_shorter_samples_at_start=True,\n include_shorter_samples_at_end=False,\n )\n ),\n )\n\n def concat_batch(batch):\n return torch.cat(\n [\n torch.tensor(\n np.expand_dims(x, axis=1), dtype=torch.float, device=device\n )\n for x in batch\n ],\n dim=1,\n )\n\n # shape: seq_len x batch_size x feature_dim\n mdnrnn_state = concat_batch(state_batch)\n next_mdnrnn_state = concat_batch(next_state_batch)\n mdnrnn_action = concat_batch(action_batch)\n next_mdnrnn_action = concat_batch(next_action_batch)\n\n mdnrnn_input = rlt.PreprocessedStateAction.from_tensors(\n state=mdnrnn_state, action=mdnrnn_action\n )\n next_mdnrnn_input = rlt.PreprocessedStateAction.from_tensors(\n state=next_mdnrnn_state, action=next_mdnrnn_action\n )\n # batch-compute state embedding\n mdnrnn_output = trainer.mdnrnn(mdnrnn_input)\n next_mdnrnn_output = trainer.mdnrnn(next_mdnrnn_input)\n\n for i in range(len(state_batch)):\n # Embed the state as the hidden layer's output\n # until the previous step + current state\n hidden_idx = 0 if step_batch[i] == 1 else step_batch[i] - 2 # type: ignore\n next_hidden_idx = next_step_batch[i] - 2 # type: ignore\n hidden_embed = (\n mdnrnn_output.all_steps_lstm_hidden[hidden_idx, i, :]\n .squeeze()\n .detach()\n .cpu()\n )\n state_embed = torch.cat(\n (hidden_embed, torch.tensor(state_batch[i][hidden_idx + 1])) # type: ignore\n )\n next_hidden_embed = (\n next_mdnrnn_output.all_steps_lstm_hidden[next_hidden_idx, i, :]\n .squeeze()\n .detach()\n .cpu()\n )\n next_state_embed = torch.cat(\n (\n next_hidden_embed,\n torch.tensor(next_state_batch[i][next_hidden_idx + 1]), # type: ignore\n )\n )\n\n logger.debug(\n \"create_embed_rl_dataset:\\nstate batch\\n{}\\naction batch\\n{}\\nlast \"\n \"action: {},reward: {}\\nstate embed {}\\nnext state embed {}\\n\".format(\n state_batch[i][: hidden_idx + 1], # type: ignore\n action_batch[i][: hidden_idx + 1], # type: ignore\n action_batch[i][hidden_idx + 1], # type: ignore\n reward_batch[i][hidden_idx + 1], # type: ignore\n state_embed,\n next_state_embed,\n )\n )\n\n terminal = 1 - not_terminal_batch[i][hidden_idx + 1] # type: ignore\n possible_actions, possible_actions_mask = get_possible_actions(\n gym_env, ModelType.PYTORCH_PARAMETRIC_DQN.value, False\n )\n possible_next_actions, possible_next_actions_mask = get_possible_actions(\n gym_env, ModelType.PYTORCH_PARAMETRIC_DQN.value, terminal\n )\n dataset.insert(\n state=state_embed,\n action=torch.tensor(action_batch[i][hidden_idx + 1]), # type: ignore\n reward=float(reward_batch[i][hidden_idx + 1]), # type: ignore\n next_state=next_state_embed,\n next_action=torch.tensor(\n next_action_batch[i][next_hidden_idx + 1] # type: ignore\n ),\n terminal=torch.tensor(terminal),\n possible_next_actions=possible_next_actions,\n possible_next_actions_mask=possible_next_actions_mask,\n time_diff=torch.tensor(1),\n possible_actions=possible_actions,\n possible_actions_mask=possible_actions_mask,\n policy_id=0,\n )\n logger.info(\n \"Insert {} transitions into a state embed dataset\".format(len(state_batch))\n )\n trainer.mdnrnn.mdnrnn.train(old_mdnrnn_mode)\n return dataset\n\n\ndef calculate_feature_sensitivity_by_actions(\n gym_env: OpenAIGymEnvironment,\n trainer: MDNRNNTrainer,\n use_gpu: bool,\n run_details: OpenAiRunDetails,\n test_batch: rlt.PreprocessedTrainingBatch,\n seq_len: int = 5,\n num_test_episodes: int = 100,\n):\n assert run_details.max_steps is not None\n feature_sensitivity_evaluator = FeatureSensitivityEvaluator(\n trainer,\n state_feature_num=gym_env.state_dim,\n sorted_state_feature_start_indices=list(range(gym_env.state_dim)),\n )\n feature_sensitivity_vector = feature_sensitivity_evaluator.evaluate(test_batch)[\n \"feature_sensitivity\"\n ]\n feature_sensitivity_map = {}\n for i in range(gym_env.state_dim):\n feature_sensitivity_map[\"state\" + str(i)] = feature_sensitivity_vector[i].item()\n print(\n \"state {}, feature sensitivity: {}\".format(\n i, feature_sensitivity_vector[i].item()\n )\n )\n return feature_sensitivity_map\n\n\ndef train_sgd(\n gym_env: OpenAIGymEnvironment,\n trainer: MDNRNNTrainer,\n use_gpu: bool,\n test_run_name: str,\n minibatch_size: int,\n run_details: OpenAiRunDetails,\n test_batch: rlt.PreprocessedTrainingBatch,\n):\n assert run_details.max_steps is not None\n train_replay_buffer = get_replay_buffer(\n run_details.num_train_episodes,\n run_details.seq_len,\n run_details.max_steps,\n gym_env,\n )\n valid_replay_buffer = get_replay_buffer(\n run_details.num_test_episodes,\n run_details.seq_len,\n run_details.max_steps,\n gym_env,\n )\n valid_batch = valid_replay_buffer.sample_memories(\n valid_replay_buffer.memory_size, use_gpu=use_gpu, batch_first=True\n )\n valid_loss_history = []\n\n num_batch_per_epoch = train_replay_buffer.memory_size // minibatch_size\n logger.info(\n \"Collected data {} transitions.\\n\"\n \"Training will take {} epochs, with each epoch having {} mini-batches\"\n \" and each mini-batch having {} samples\".format(\n train_replay_buffer.memory_size,\n run_details.train_epochs,\n num_batch_per_epoch,\n minibatch_size,\n )\n )\n\n for i_epoch in range(run_details.train_epochs):\n for i_batch in range(num_batch_per_epoch):\n training_batch = train_replay_buffer.sample_memories(\n minibatch_size, use_gpu=use_gpu, batch_first=True\n )\n losses = trainer.train(training_batch, batch_first=True)\n logger.info(\n \"{}-th epoch, {}-th minibatch: \\n\"\n \"loss={}, bce={}, gmm={}, mse={} \\n\"\n \"cum loss={}, cum bce={}, cum gmm={}, cum mse={}\\n\".format(\n i_epoch,\n i_batch,\n losses[\"loss\"],\n losses[\"bce\"],\n losses[\"gmm\"],\n losses[\"mse\"],\n np.mean(trainer.cum_loss),\n np.mean(trainer.cum_bce),\n np.mean(trainer.cum_gmm),\n np.mean(trainer.cum_mse),\n )\n )\n\n trainer.mdnrnn.mdnrnn.eval()\n valid_losses = trainer.get_loss(\n valid_batch, state_dim=gym_env.state_dim, batch_first=True\n )\n valid_losses = loss_to_num(valid_losses)\n valid_loss_history.append(valid_losses)\n trainer.mdnrnn.mdnrnn.train()\n logger.info(\n \"{}-th epoch, validate loss={}, bce={}, gmm={}, mse={}\".format(\n i_epoch,\n valid_losses[\"loss\"],\n valid_losses[\"bce\"],\n valid_losses[\"gmm\"],\n valid_losses[\"mse\"],\n )\n )\n latest_loss = valid_loss_history[-1][\"loss\"]\n recent_valid_loss_hist = valid_loss_history[\n -1 - run_details.early_stopping_patience : -1\n ]\n # earlystopping\n if len(valid_loss_history) > run_details.early_stopping_patience and all(\n (latest_loss >= v[\"loss\"] for v in recent_valid_loss_hist)\n ):\n break\n\n trainer.mdnrnn.mdnrnn.eval()\n test_losses = trainer.get_loss(\n test_batch, state_dim=gym_env.state_dim, batch_first=True\n )\n test_losses = loss_to_num(test_losses)\n logger.info(\n \"Test loss: {}, bce={}, gmm={}, mse={}\".format(\n test_losses[\"loss\"],\n test_losses[\"bce\"],\n test_losses[\"gmm\"],\n test_losses[\"mse\"],\n )\n )\n logger.info(\"Valid loss history: {}\".format(valid_loss_history))\n return test_losses, valid_loss_history, trainer\n\n\ndef create_trainer(\n params: OpenAiGymParameters, env: OpenAIGymEnvironment, use_gpu: bool\n):\n assert params.mdnrnn is not None\n assert params.run_details.max_steps is not None\n mdnrnn_params = params.mdnrnn\n mdnrnn_net = MemoryNetwork(\n state_dim=env.state_dim,\n action_dim=env.action_dim,\n num_hiddens=mdnrnn_params.hidden_size,\n num_hidden_layers=mdnrnn_params.num_hidden_layers,\n num_gaussians=mdnrnn_params.num_gaussians,\n )\n if use_gpu:\n mdnrnn_net = mdnrnn_net.cuda()\n\n cum_loss_hist_len = (\n params.run_details.num_train_episodes\n * params.run_details.max_steps\n // mdnrnn_params.minibatch_size\n )\n trainer = MDNRNNTrainer(\n mdnrnn_network=mdnrnn_net, params=mdnrnn_params, cum_loss_hist=cum_loss_hist_len\n )\n return trainer\n\n\nif __name__ == \"__main__\":\n logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)\n logging.getLogger().setLevel(logging.INFO)\n args = sys.argv\n main(args[1:])\n" ]
[ [ "numpy.vstack", "torch.tensor", "numpy.float32", "numpy.logical_not", "numpy.expand_dims", "numpy.pad", "torch.device", "numpy.mean" ] ]
Derikka/simulacrum
[ "99c4db9b15913c3c838532a86569645b3345fb83" ]
[ "model_service/model_service.py" ]
[ "#!/usr/bin/env python3\nimport os\nimport argparse\nimport sys\nimport pickle\nimport asyncio\nimport time\nimport numpy as np\nimport zmq\nimport pytao\nfrom p4p.nt import NTTable\nfrom p4p.server import Server as PVAServer\nfrom p4p.server.asyncio import SharedPV\nfrom zmq.asyncio import Context\nimport simulacrum\n\n\nmodel_service_dir = os.path.dirname(os.path.realpath(__file__))\n#set up python logger\nL = simulacrum.util.SimulacrumLog(os.path.splitext(os.path.basename(__file__))[0], level='INFO')\n\nclass ModelService:\n def __init__(self, init_file, name, enable_jitter=False, plot=False):\n self.name = name\n tao_lib = os.environ.get('TAO_LIB', '')\n self.tao = pytao.Tao(so_lib=tao_lib)\n L.debug(\"Initializing Tao...\")\n if plot: \n self.tao.init(\"-init {init_file}\".format(init_file=init_file))\n else:\n self.tao.init(\"-noplot -init {init_file}\".format(init_file=init_file))\n L.debug(\"Tao initialization complete!\")\n self.tao.cmd(\"set global lattice_calc_on = F\")\n self.tao.cmd('set global var_out_file = \" \"')\n self.ctx = Context.instance()\n self.model_broadcast_socket = zmq.Context().socket(zmq.PUB)\n self.model_broadcast_socket.bind(\"tcp://*:{}\".format(os.environ.get('MODEL_BROADCAST_PORT', 66666)))\n self.loop = asyncio.get_event_loop()\n self.jitter_enabled = enable_jitter\n self.twiss_table = NTTable([(\"element\", \"s\"), (\"device_name\", \"s\"),\n (\"s\", \"d\"), (\"length\", \"d\"), (\"p0c\", \"d\"),\n (\"alpha_x\", \"d\"), (\"beta_x\", \"d\"), (\"eta_x\", \"d\"), (\"etap_x\", \"d\"), (\"psi_x\", \"d\"),\n (\"alpha_y\", \"d\"), (\"beta_y\", \"d\"), (\"eta_y\", \"d\"), (\"etap_y\", \"d\"), (\"psi_y\", \"d\")])\n self.rmat_table = NTTable([(\"element\", \"s\"), (\"device_name\", \"s\"), (\"s\", \"d\"), (\"length\", \"d\"),\n (\"r11\", \"d\"), (\"r12\", \"d\"), (\"r13\", \"d\"), (\"r14\", \"d\"), (\"r15\", \"d\"), (\"r16\", \"d\"),\n (\"r21\", \"d\"), (\"r22\", \"d\"), (\"r23\", \"d\"), (\"r24\", \"d\"), (\"r25\", \"d\"), (\"r26\", \"d\"),\n (\"r31\", \"d\"), (\"r32\", \"d\"), (\"r33\", \"d\"), (\"r34\", \"d\"), (\"r35\", \"d\"), (\"r36\", \"d\"),\n (\"r41\", \"d\"), (\"r42\", \"d\"), (\"r43\", \"d\"), (\"r44\", \"d\"), (\"r45\", \"d\"), (\"r46\", \"d\"),\n (\"r51\", \"d\"), (\"r52\", \"d\"), (\"r53\", \"d\"), (\"r54\", \"d\"), (\"r55\", \"d\"), (\"r56\", \"d\"),\n (\"r61\", \"d\"), (\"r62\", \"d\"), (\"r63\", \"d\"), (\"r64\", \"d\"), (\"r65\", \"d\"), (\"r66\", \"d\")])\n initial_twiss_table, initial_rmat_table = self.get_twiss_table()\n sec, nanosec = divmod(float(time.time()), 1.0)\n initial_twiss_table = self.twiss_table.wrap(initial_twiss_table)\n initial_twiss_table['timeStamp']['secondsPastEpoch'] = sec\n initial_twiss_table['timeStamp']['nanoseconds'] = nanosec\n initial_rmat_table = self.rmat_table.wrap(initial_rmat_table)\n initial_rmat_table['timeStamp']['secondsPastEpoch'] = sec\n initial_rmat_table['timeStamp']['nanoseconds'] = nanosec\n self.live_twiss_pv = SharedPV(nt=self.twiss_table, \n initial=initial_twiss_table,\n loop=self.loop)\n self.design_twiss_pv = SharedPV(nt=self.twiss_table, \n initial=initial_twiss_table,\n loop=self.loop)\n self.live_rmat_pv = SharedPV(nt=self.rmat_table, \n initial=initial_rmat_table,\n loop=self.loop)\n self.design_rmat_pv = SharedPV(nt=self.rmat_table, \n initial=initial_rmat_table,\n loop=self.loop)\n self.recalc_needed = False\n self.pva_needs_refresh = False\n self.need_zmq_broadcast = False\n \n def start(self):\n L.info(\"Starting %s Model Service.\", self.name)\n pva_server = PVAServer(providers=[{f\"SIMULACRUM:SYS0:1:{self.name}:LIVE:TWISS\": self.live_twiss_pv,\n f\"SIMULACRUM:SYS0:1:{self.name}:DESIGN:TWISS\": self.design_twiss_pv,\n f\"SIMULACRUM:SYS0:1:{self.name}:LIVE:RMAT\": self.live_rmat_pv,\n f\"SIMULACRUM:SYS0:1:{self.name}:DESIGN:RMAT\": self.design_rmat_pv,}])\n try:\n zmq_task = self.loop.create_task(self.recv())\n pva_refresh_task = self.loop.create_task(self.refresh_pva_table())\n broadcast_task = self.loop.create_task(self.broadcast_model_changes())\n jitter_task = self.loop.create_task(self.add_jitter())\n self.loop.run_forever()\n except KeyboardInterrupt:\n L.info(\"Shutting down Model Service.\")\n zmq_task.cancel()\n pva_refresh_task.cancel()\n broadcast_task.cancel()\n pva_server.stop()\n finally:\n self.loop.close()\n L.info(\"Model Service shutdown complete.\")\n \n def get_twiss_table(self):\n \"\"\"\n Queries Tao for model and RMAT info.\n Returns: A (twiss_table, rmat_table) tuple.\n \"\"\"\n start_time = time.time()\n #First we get a list of all the elements.\n #NOTE: the \"-no_slaves\" option for python lat_list only works in Tao 2019_1112 or above.\n element_name_list = self.tao.cmd(\"python lat_list -track_only 1@0>>*|model ele.name\")\n L.debug(element_name_list)\n for row in element_name_list:\n assert \"ERROR\" not in element_name_list, \"Fetching element names failed. This is probably because a version of Tao older than 2019_1112 is being used.\"\n last_element_index = 0\n for i, row in enumerate(reversed(element_name_list)):\n if row == \"END\":\n last_element_index = len(element_name_list)-1-i\n break\n element_data = {}\n attrs = (\"ele.s\", \"ele.l\", \"orbit.energy\", \"ele.a.alpha\", \"ele.a.beta\", \"ele.x.eta\", \"ele.x.etap\", \"ele.a.phi\", \"ele.b.alpha\", \"ele.b.beta\", \"ele.y.eta\", \"ele.y.etap\", \"ele.b.phi\", \"ele.mat6\")\n for attr in attrs:\n element_data[attr] = self.tao.cmd_real(\"python lat_list -track_only 1@0>>*|model real:{}\".format(attr))\n if attr == 'ele.mat6':\n element_data[attr] = element_data[attr].reshape((-1, 6, 6))\n assert len(element_data[attr]) == len(element_name_list), \"Number of elements in model data for {} doesn't match number of element names.\".format(attr)\n \n combined_rmat = np.identity(6)\n twiss_table_rows = []\n rmat_table_rows = []\n for i in range(0,last_element_index+1):\n element_name = element_name_list[i]\n try:\n device_name = simulacrum.util.convert_element_to_device(element_name.split(\"#\")[0])\n except KeyError:\n device_name = \"\"\n element_rmat = element_data['ele.mat6'][i]\n rmat = np.matmul(element_rmat, combined_rmat)\n combined_rmat = rmat\n twiss_table_rows.append({\"element\": element_name, \"device_name\": device_name, \"s\": element_data['ele.s'][i], \"length\": element_data['ele.l'][i], \"p0c\": element_data['orbit.energy'][i],\n \"alpha_x\": element_data['ele.a.alpha'][i], \"beta_x\": element_data['ele.a.beta'][i], \"eta_x\": element_data['ele.x.eta'][i], \"etap_x\": element_data['ele.x.etap'][i], \"psi_x\": element_data['ele.a.phi'][i],\n \"alpha_y\": element_data['ele.b.alpha'][i], \"beta_y\": element_data['ele.b.beta'][i], \"eta_y\": element_data['ele.y.eta'][i], \"etap_y\": element_data['ele.y.etap'][i], \"psi_y\": element_data['ele.b.phi'][i]})\n rmat_table_rows.append({\n \"element\": element_name, \"device_name\": device_name, \"s\": element_data['ele.s'][i], \"length\": element_data['ele.l'][i],\n \"r11\": rmat[0,0], \"r12\": rmat[0,1], \"r13\": rmat[0,2], \"r14\": rmat[0,3], \"r15\": rmat[0,4], \"r16\": rmat[0,5],\n \"r21\": rmat[1,0], \"r22\": rmat[1,1], \"r23\": rmat[1,2], \"r24\": rmat[1,3], \"r25\": rmat[1,4], \"r26\": rmat[1,5],\n \"r31\": rmat[2,0], \"r32\": rmat[2,1], \"r33\": rmat[2,2], \"r34\": rmat[2,3], \"r35\": rmat[2,4], \"r36\": rmat[2,5],\n \"r41\": rmat[3,0], \"r42\": rmat[3,1], \"r43\": rmat[3,2], \"r44\": rmat[3,3], \"r45\": rmat[3,4], \"r46\": rmat[3,5],\n \"r51\": rmat[4,0], \"r52\": rmat[4,1], \"r53\": rmat[4,2], \"r54\": rmat[4,3], \"r55\": rmat[4,4], \"r56\": rmat[4,5],\n \"r61\": rmat[5,0], \"r62\": rmat[5,1], \"r63\": rmat[5,2], \"r64\": rmat[5,3], \"r65\": rmat[5,4], \"r66\": rmat[5,5]})\n end_time = time.time()\n L.debug(\"get_twiss_table took %f seconds\", end_time - start_time)\n return twiss_table_rows, rmat_table_rows\n \n async def refresh_pva_table(self):\n \"\"\"\n This loop continuously checks if the PVAccess table needs to be refreshed,\n and publishes a new table if it does. The pva_needs_refresh flag is\n usually set when a tao command beginning with 'set' occurs.\n \"\"\"\n while True:\n if self.pva_needs_refresh:\n sec, nanosec = divmod(float(time.time()), 1.0)\n new_twiss_table, new_rmat_table = self.get_twiss_table()\n new_twiss_table = self.twiss_table.wrap(new_twiss_table)\n new_twiss_table['timeStamp']['secondsPastEpoch'] = sec\n new_twiss_table['timeStamp']['nanoseconds'] = nanosec\n new_rmat_table = self.rmat_table.wrap(new_rmat_table)\n new_rmat_table['timeStamp']['secondsPastEpoch'] = sec\n new_rmat_table['timeStamp']['nanoseconds'] = nanosec\n self.live_twiss_pv.post(new_twiss_table)\n self.live_rmat_pv.post(new_rmat_table)\n self.pva_needs_refresh = False\n await asyncio.sleep(1.0)\n \n async def add_jitter(self):\n while True:\n if self.jitter_enabled:\n x0 = np.random.normal(0.0, 0.12*0.001)\n y0 = np.random.normal(0.0, 0.12*0.001)\n self.tao.cmd(f\"set particle_start x = {x0}\")\n self.tao.cmd(f\"set particle_start y = {y0}\")\n self.recalc_needed = True\n self.need_zmq_broadcast = True\n await asyncio.sleep(1.0)\n \n async def broadcast_model_changes(self):\n \"\"\"\n This loop broadcasts new orbits, twiss parameters, etc. over ZMQ.\n \"\"\"\n while True:\n if self.recalc_needed:\n self.tao.cmd(\"set global lattice_calc_on = T\")\n self.tao.cmd(\"set global lattice_calc_on = F\")\n self.recalc_needed = False\n if self.need_zmq_broadcast:\n try:\n self.send_orbit()\n except Exception as e:\n L.warning(\"SEND ORBIT FAILED: %s\", e)\n try:\n self.send_profiles_data()\n except Exception as e:\n L.warning(\"SEND PROF DATA FAILED: %s\", e)\n try:\n self.send_und_twiss()\n except Exception as e:\n L.warning(\"SEND UND TWISS FAILED: %s\", e)\n\n self.need_zmq_broadcast = False\n await asyncio.sleep(0.1)\n \n def model_changed(self):\n self.recalc_needed = True\n self.pva_needs_refresh = True\n self.need_zmq_broadcast = True\n \n def get_orbit(self):\n start_time = time.time()\n #Get X Orbit\n x_orb_text = self.tao_cmd(\"show data orbit.x\")[3:-2]\n x_orb = _orbit_array_from_text(x_orb_text)\n #Get Y Orbit\n y_orb_text = self.tao_cmd(\"show data orbit.y\")[3:-2]\n y_orb = _orbit_array_from_text(y_orb_text)\n #Get e_tot, which we use to see if the single particle beam is dead\n e_text = self.tao_cmd(\"show data orbit.e\")[3:-2]\n e = _orbit_array_from_text(e_text)\n end_time = time.time()\n L.debug(\"get_orbit took %f seconds\", end_time-start_time)\n return np.stack((x_orb, y_orb, e))\n\n def get_prof_orbit(self):\n #Get X Orbit\n x_orb_text = self.tao_cmd(\"show data orbit.profx\")[3:-2]\n x_orb = _orbit_array_from_text(x_orb_text)\n #Get Y Orbit\n y_orb_text = self.tao_cmd(\"show data orbit.profy\")[3:-2]\n y_orb = _orbit_array_from_text(y_orb_text)\n return np.stack((x_orb, y_orb))\n \n def get_twiss(self):\n twiss_text = self.tao_cmd(\"show lat -no_label_lines -at alpha_a -at beta_a -at alpha_b -at beta_b UNDSTART\")\n if \"ERROR\" in twiss_text[0]:\n twiss_text = self.tao_cmd(\"show lat -no_label_lines -at alpha_a -at beta_a -at alpha_b -at beta_b BEGUNDH\")\n if \"ERROR\" in twiss_text[0]:\n twiss_text = self.tao_cmd(\"show lat -no_label_lines -at alpha_a -at beta_a -at alpha_b -at beta_b BEGUNDS\")\n #format to list of comma separated values\n #msg='twiss from get_twiss: {}'.format(twiss_text)\n #L.info(msg)\n twiss = twiss_text[0].split()\n return twiss\n\n def old_get_orbit(self):\n #Get X Orbit\n x_orb_text = self.tao_cmd(\"python lat_list 1@0>>BPM*|model orbit.vec.1\")\n x_orb = _orbit_array_from_text(x_orb_text)\n #Get Y Orbit\n y_orb_text = self.tao_cmd(\"python lat_list 1@0>>BPM*|model orbit.vec.3\")\n y_orb = _orbit_array_from_text(y_orb_text)\n return np.stack((x_orb, y_orb))\n \n #information broadcast by the model is sent as two separate messages:\n #metadata message: sent first with 1) tag describing data for services to filter on, 2) type -optional, 3) size -optional\n #data message: sent either as a python object or a series of bits\n \n def send_orbit(self):\n orb = self.get_orbit()\n metadata = {\"tag\" : \"orbit\", \"dtype\": str(orb.dtype), \"shape\": orb.shape}\n self.model_broadcast_socket.send_pyobj(metadata, zmq.SNDMORE)\n self.model_broadcast_socket.send(orb)\n\n def send_profiles_data(self):\n twiss_text = self.tao_cmd(\"show lat -no_label_lines -at beta_a -at beta_b -at e_tot Monitor::OTR*,Monitor::YAG*\")\n prof_beta_x = [float(l.split()[5]) for l in twiss_text]\n prof_beta_y = [float(l.split()[6]) for l in twiss_text]\n prof_e = [float(l.split()[7]) for l in twiss_text]\n prof_names = [l.split()[1] for l in twiss_text]\n prof_orbit = self.get_prof_orbit()\n prof_data = np.concatenate((prof_orbit, np.array([prof_beta_x, prof_beta_y, prof_e, prof_names])))\n\n metadata = {\"tag\" : \"prof_data\", \"dtype\": str(prof_data.dtype), \"shape\": prof_data.shape}\n self.model_broadcast_socket.send_pyobj(metadata, zmq.SNDMORE)\n self.model_broadcast_socket.send(prof_data);\n\n def send_particle_positions(self):\n twiss_text = self.tao_cmd(\"show lat -no_label_lines -at beta_a -at beta_b -at e_tot Monitor::OTR*,Monitor::YAG*\")\n prof_names = [l.split()[1] for l in twiss_text]\n positions_all = {}\n for screen in prof_names:\n positions = self.get_particle_positions(screen);\n if not positions:\n continue\n positions_all[screen] = [[float(position.split()[1]), float(position.split()[3])] for position in positions]\n metadata = {\"tag\": \"part_positions\"}\n self.model_broadcast_socket.send_pyobj(metadata, zmq.SNDMORE)\n self.model_broadcast_socket.send_pyobj(positions_all)\n\n def get_particle_positions(self, screen):\n L.debug(\"Getting particle positions\")\n cmd = \"show particle -all -ele {screen}\".format(screen=screen)\n results = self.tao_cmd(cmd);\n if(len(results) < 3):\n return False\n return results[2:]\n\n def send_und_twiss(self):\n twiss = self.get_twiss()\n metadata = {\"tag\": \"und_twiss\"}\n self.model_broadcast_socket.send_pyobj(metadata, zmq.SNDMORE)\n self.model_broadcast_socket.send_pyobj(twiss)\n \n def tao_cmd(self, cmd):\n if cmd.startswith(\"exit\"):\n return \"Please stop trying to exit the model service's Tao, you jerk!\"\n result = self.tao.cmd(cmd)\n if cmd.startswith(\"set\"):\n self.model_changed()\n return result\n \n def tao_batch(self, cmds):\n L.info(\"Starting command batch.\")\n results = [self.tao_cmd(cmd) for cmd in cmds]\n L.info(\"Batch complete.\")\n return results\n \n async def recv(self):\n s = self.ctx.socket(zmq.REP)\n s.bind(\"tcp://*:{}\".format(os.environ.get('MODEL_PORT', \"12312\")))\n while True:\n p = await s.recv_pyobj()\n msg = \"Got a message: {}\".format(p)\n L.debug(msg)\n if p['cmd'] == 'tao':\n try:\n retval = self.tao_cmd(p['val'])\n await s.send_pyobj({'status': 'ok', 'result': retval})\n except Exception as e:\n await s.send_pyobj({'status': 'fail', 'err': e})\n elif p['cmd'] == 'send_orbit':\n self.model_changed() #Sets the flag that will cause an orbit broadcast\n await s.send_pyobj({'status': 'ok'})\n elif p['cmd'] == 'echo':\n await s.send_pyobj({'status': 'ok', 'result': p['val']})\n elif p['cmd'] == 'send_profiles_twiss':\n self.model_changed() #Sets the flag that will cause a prof broadcast\n #self.send_profiles_twiss()\n #self.send_prof_orbit()\n await s.send_pyobj({'status': 'ok'})\n elif p['cmd'] == 'send_und_twiss':\n self.model_changed() #Sets the flag that will cause an und twiss broadcast\n #self.send_und_twiss()\n await s.send_pyobj({'status': 'ok'})\n elif p['cmd'] == 'tao_batch':\n try:\n results = self.tao_batch(p['val'])\n await s.send_pyobj({'status': 'ok', 'result': results})\n except Exception as e:\n await s.send_pyobj({'status': 'fail', 'err': e})\n\ndef _orbit_array_from_text(text):\n return np.array([float(l.split()[5]) for l in text])*1000.0\n\ndef find_model(model_name):\n \"\"\"\n Helper routine to find models using standard environmental variables:\n $LCLS_CLASSIC_LATTICE should point to a checkout of https://github.com/slaclab/lcls-classic-lattice \n $LCLS_LATTICE should point to a checkout of https://github.com/slaclab/lcls-lattice\n \n Availble models:\n lcls_classic\n cu_hxr\n cu_spec\n cu_sxr\n sc_hxr\n sc_sxr\n \n \"\"\"\n if model_name == 'lcls_classic':\n tao_initfile = os.path.join(os.environ['LCLS_CLASSIC_LATTICE'], 'bmad/model/tao.init')\n elif model_name in ['cu_hxr', 'cu_sxr', 'cu_spec', 'sc_sxr', 'sc_hxr']:\n root = os.environ['LCLS_LATTICE']\n tao_initfile = os.path.join(root, 'bmad/models/', model_name, 'tao.init') \n else:\n raise ValueError('Not a valid model: {}'.format(model_name))\n assert os.path.exists(tao_initfile), 'Error: file does not exist: ' + tao_initfile\n return tao_initfile\n\nif __name__==\"__main__\":\n parser = argparse.ArgumentParser(description=\"Simulacrum Model Service\")\n parser.add_argument(\n 'model_name',\n help='Name of a Tao model from either lcls-lattice or lcls-classic-lattice. Must be one of: ' + \n 'lcls_classic, cu_hxr, cu_spec, cu_sxr, sc_sxr, or sc_hxr'\n )\n parser.add_argument(\n '--enable-jitter',\n action='store_true',\n help='Apply jitter on every model update tick (10 Hz). This will significantly increase CPU usage.'\n )\n parser.add_argument(\n '--plot',\n action='store_true',\n help='Show tao plot'\n )\n model_service_args = parser.parse_args()\n tao_init_file = find_model(model_service_args.model_name)\n serv = ModelService(init_file=tao_init_file, name=model_service_args.model_name.upper(), enable_jitter=model_service_args.enable_jitter, \n plot=model_service_args.plot)\n serv.start()\n\n" ]
[ [ "numpy.matmul", "numpy.array", "numpy.random.normal", "numpy.stack", "numpy.identity" ] ]
takuya-ki/wrs
[ "f6e1009b94332504042fbde9b39323410394ecde", "f6e1009b94332504042fbde9b39323410394ecde" ]
[ "basis/trimesh/io/stl.py", "drivers/devices/kinect_azure/helper.py" ]
[ "import numpy as np\n\nfrom ..util import is_binary_file\n\n# define a numpy datatype for the STL file\n_stl_dtype = np.dtype([('normals', np.float32, (3)), ('vertices', np.float32, (3, 3)), ('attributes', np.uint16)])\n_stl_dtype_header = np.dtype([('header', np.void, 80), ('face_count', np.int32)])\n\n\ndef load_stl(file_obj, file_type=None):\n if 'b' not in file_obj.mode:\n raise\n if is_binary_file(file_obj):\n return load_stl_binary(file_obj)\n else:\n return load_stl_ascii(file_obj)\n\n\ndef load_stl_binary(file_obj):\n \"\"\"\n Load a binary STL file into a trimesh object.\n Uses a single main struct.unpack call, and is significantly faster\n than looping methods or ASCII STL.\n :param file_obj:\n :return:\n \"\"\"\n header = np.fromstring(file_obj.read(84), dtype=_stl_dtype_header)\n # now we check the length from the header versus the length of the file\n # data_start should always be position 84, but hard coding that felt ugly\n data_start = file_obj.tell()\n # this seeks to the end of the file (position 0, relative to the end of the file 'whence=2')\n file_obj.seek(0, 2)\n # we save the location of the end of the file and seek back to where we started from\n data_end = file_obj.tell()\n file_obj.seek(data_start)\n # the binary format has a rigidly defined structure, and if the length\n # of the file doesn't match the header, the loaded version is almost\n # certainly going to be garbage. \n data_ok = (data_end - data_start) == (header['face_count'] * _stl_dtype.itemsize)\n\n # this check is to see if this really is a binary STL file. \n # if we don't do this and try to load a file that isn't structured properly \n # the struct.unpack call uses 100% memory until the whole thing crashes, \n # so it's much better to raise an exception here. \n if not data_ok:\n raise ValueError('Binary STL has incorrect length in header!')\n # all of our vertices will be loaded in order due to the STL format, \n # so faces are just sequential indices reshaped. \n faces = np.arange(header['face_count'] * 3).reshape((-1, 3))\n blob = np.fromstring(file_obj.read(), dtype=_stl_dtype)\n result = {'vertices': blob['vertices'].reshape((-1, 3)),\n 'face_normals': blob['normals'].reshape((-1, 3)),\n 'faces': faces}\n return result\n\n\ndef load_stl_ascii(file_obj):\n '''\n Load an ASCII STL file.\n '''\n header = file_obj.readline()\n\n text = file_obj.read()\n if hasattr(text, 'decode'):\n text = text.decode('utf-8')\n text = text.lower().split('endsolid')[0]\n blob = np.array(text.split())\n\n # there are 21 'words' in each face\n face_len = 21\n face_count = len(blob) / face_len\n if (len(blob) % face_len) != 0:\n raise ValueError('Incorrect number of values in STL file!')\n\n face_count = int(face_count)\n # this offset is to be added to a fixed set of indices that is tiled\n offset = face_len * np.arange(face_count).reshape((-1, 1))\n normal_index = np.tile([2, 3, 4], (face_count, 1)) + offset\n vertex_index = np.tile([8, 9, 10, 12, 13, 14, 16, 17, 18], (face_count, 1)) + offset\n\n # faces are groups of three sequential vertices, as vertices are not references\n faces = np.arange(face_count * 3).reshape((-1, 3))\n face_normals = blob[normal_index].astype(float)\n vertices = blob[vertex_index.reshape((-1, 3))].astype(float)\n\n return {'vertices': vertices,\n 'faces': faces,\n 'face_normals': face_normals}\n\n\ndef export_stl(mesh):\n '''\n Convert a Trimesh object into a binary STL file.\n Arguments\n ---------\n mesh: Trimesh object\n Returns\n ---------\n export: bytes, representing mesh in binary STL form\n '''\n header = np.zeros(1, dtype=_stl_dtype_header)\n header['face_count'] = len(mesh.faces)\n packed = np.zeros(len(mesh.faces), dtype=_stl_dtype)\n packed['normals'] = mesh.face_normals\n packed['vertices'] = mesh.triangles\n export = header.tostring()\n export += packed.tostring()\n return export\n\n\n_stl_loaders = {'stl': load_stl}\n", "import cv2\nimport numpy as np\nfrom drivers.devices.kinect_azure.pykinectazure import PyKinectAzure, _k4a\n\nmtx = np.array([[610.16101074, 0, 638.35681152], [0, 610.19384766, 367.82455444], [0, 0, 1]])\n\n\ndef get_images(pk_obj):\n while True:\n pk_obj.device_get_capture()\n color_image_handle = pk_obj.capture_get_color_image()\n depth_image_handle = pk_obj.capture_get_depth_image()\n if color_image_handle and depth_image_handle:\n color_image = pk_obj.image_convert_to_numpy(color_image_handle)\n depth_image = pk_obj.transform_depth_to_color(depth_image_handle, color_image_handle)\n pk_obj.image_release(color_image_handle)\n pk_obj.image_release(depth_image_handle)\n pk_obj.capture_release()\n return color_image, depth_image\n else:\n print(\"get color image failed\")\n pk_obj.capture_release()\n\n\ndef depth_to_point(mtx, pixel_pos, depth_image):\n img_x, img_y = pixel_pos\n rgbcam_fx = mtx[0][0]\n rgbcam_fy = mtx[1][1]\n rgbcam_cx = mtx[0][2]\n rgbcam_cy = mtx[1][2]\n world_x = (img_x - rgbcam_cx) * depth_image / (rgbcam_fx * 1000)\n world_y = (img_y - rgbcam_cy) * depth_image / (rgbcam_fy * 1000)\n world_z = depth_image / 1000\n return np.array([world_x, world_y, world_z])\n\n\ndef pcd_read(depth_image, mtx):\n image_size = depth_image.shape\n rgbcam_fx = mtx[0][0]\n rgbcam_fy = mtx[1][1]\n rgbcam_cx = mtx[0][2]\n rgbcam_cy = mtx[1][2]\n length = image_size[0] * image_size[1]\n kx = (np.arange(image_size[1]) - rgbcam_cx) / (rgbcam_fx * 1000)\n kx = np.tile(kx, image_size[0])\n ky = (np.arange(image_size[0]) - rgbcam_cy) / (rgbcam_fy * 1000)\n ky = ky.repeat(image_size[1])\n k = np.array(list(zip(kx, ky, np.ones(length, dtype=int) / 1000)))\n depth = depth_image.repeat(3).reshape(length, 3) + \\\n np.tile(np.array([rgbcam_fx, rgbcam_fy, 0]), length).reshape(length, 3)\n return k * depth\n\n\nif __name__ == \"__main__\":\n pk_obj = PyKinectAzure()\n pk_obj.device_open()\n device_config = pk_obj.config\n device_config.color_resolution = _k4a.K4A_COLOR_RESOLUTION_1080P\n device_config.depth_mode = _k4a.K4A_DEPTH_MODE_WFOV_2X2BINNED\n print(device_config)\n pk_obj.device_start_cameras(device_config)\n color, depth = get_images(pk_obj)\n cv2.imshow(\"color\", color)\n cv2.imshow(\"depth\", depth)\n cv2.waitKey(0)\n" ]
[ [ "numpy.arange", "numpy.dtype", "numpy.tile", "numpy.zeros" ], [ "numpy.array", "numpy.tile", "numpy.arange", "numpy.ones" ] ]
NathanLoPresto/UI-for-servicing-OP-AMPs
[ "75605aa8b2315c1bbf3e7eee0f8ad706fa7e4f14" ]
[ "Python/DDR.py" ]
[ "import ok\nfrom fpga import FPGA\nimport numpy as np\nimport time\nimport matplotlib.pyplot as plot\nimport struct\nfrom collections import namedtuple\n\nBLOCK_SIZE = (16384)\nWRITE_SIZE=(8*1024*1024)\nREAD_SIZE = (8*1024*1024)\ng_nMemSize = (8*1024*1024)\nsample_size = (524288)\nep = namedtuple('ep', 'addr bits type')\ncontrol = ep(0x00, [i for i in range(32)], 'wi') # note this is active low \n\n# wire outs for \"1 deep FIFO\" \none_deep_fifo = ep(0x20, [i for i in range(32)], 'wo')\n\n# triggers in \nvalid = ep(0x40, 0, 'ti')\nfpga_reset = ep(0x40, 1, 'ti')\nfifo_reset = ep(0x40, 2, 'ti')\n\n#given the amplitude, and the time between each step, returns array to be plotted\ndef make_flat_voltage(input_voltage):\n time_axis = np.arange (0, np.pi*2 , (1/sample_size*2*np.pi) )\n amplitude = np.arange (0, np.pi*2 , (1/sample_size*2*np.pi) )\n for x in range (len(amplitude)):\n amplitude[x] = input_voltage\n amplitude = amplitude.astype(np.int32)\n return time_axis, amplitude\n\n#Given the amplitude and period, returns an array to be plotted \ndef make_sin_wave(amplitude_shift, frequency_shift=16):\n time_axis = np.arange (0, np.pi*2 , (1/sample_size*2*np.pi) )\n print (\"length of time axis after creation \", len(time_axis))\n amplitude = (amplitude_shift*1000*np.sin(time_axis))\n y = len(amplitude)\n for x in range (y):\n amplitude[x]= amplitude[x]+(10000)\n for x in range (y):\n amplitude[x]= (int)(amplitude[x]/20000*16384)\n amplitude = amplitude.astype(np.int32)\n return time_axis, amplitude\n\n#given a buffer, it writes a bytearray to the DDR3\ndef writeSDRAM(g_buf):\n\n print (\"Length of buffer at the top of WriteSDRAM\", len(g_buf))\n #Reset FIFOs\n f.set_wire(0x30, 4)\n f.set_wire(0x03, 0)\n f.set_wire(0x03, 2)\n\n print (\"Writing to DDR...\")\n time1 = time.time()\n #for i in range ((int)(len(g_buf)/WRITE_SIZE)):\n r = f.xem.WriteToBlockPipeIn( epAddr= 0x80, blockSize= BLOCK_SIZE,\n data= g_buf[0:(len(g_buf))])\n print (\"The length of the write is \", r)\n \n time2 = time.time()\n time3 = (time2-time1)\n mbs = (int)(r/1024/1024/ time3)\n print (\"The speed of the write was \", mbs, \" MegaBytes per second\")\n\n #below sets the HDL into read mode\n f.set_wire(0x03, 4)\n f.set_wire(0x03, 0)\n f.set_wire(0x03, 1)\n\n#reads to an empty array passed to the function\ndef readSDRAM():\n amplitude = np.zeros((sample_size,), dtype=int)\n pass_buf = bytearray(amplitude)\n #Reset FIFOs\n #below sets the HDL into read mode\n f.set_wire(0x03, 4)\n f.set_wire(0x03, 0)\n f.set_wire(0x03, 1)\n\n print (\"Reading from DDR...\")\n #Address changed to A5\n for i in range ((int)(g_nMemSize/WRITE_SIZE)):\n r = f.xem.ReadFromBlockPipeOut( epAddr= 0xA0, blockSize= BLOCK_SIZE,\n data= pass_buf)\n print (\"The length of the read is:\", r)\n return pass_buf\n\n#given a buffer, it unpacks into into human readable float values\ndef unpack(buf):\n unpacked_var = []\n for x in range (sample_size):\n unpacked_var.append(struct.unpack('i', buf[(x*4):((x+1)*4)]))\n return unpacked_var\n\n#Given two arrays, plots the x and y axis with hardcoded axis names \ndef testplot(x_axis, y_axis):\n plot.plot(x_axis, y_axis)\n plot.title('The outputted wave should look like this')\n plot.xlabel('time')\n plot.ylabel('amplitude (millivolts)')\n plot.grid(True, which = 'both')\n plot.axhline(y=0, color = 'k')\n plot.show()\n\n#given an amplitude and a period, it will write a waveform to the DDR3\ndef write_sin_wave (a):\n time_axis, g_buf_init = make_sin_wave(a)\n print (\"The length of the array before casting \", len(g_buf_init))\n pass_buf = bytearray(g_buf_init)\n writeSDRAM(pass_buf)\n\n#given and amplitude and a period, it will write a step function to the DDR3 \ndef write_flat_voltage(input_voltage):\n time_axis, g_buf_init = make_flat_voltage(input_voltage)\n pass_buf2 = bytearray(g_buf_init)\n writeSDRAM(pass_buf2)\n\n#Reads and prints the contents of the DDR3\ndef print_DDR3():\n g_rbuf = readSDRAM()\n unpacked_g_rbuf = np.array(unpack(g_rbuf)).astype('float64')\n for x in range (len(unpacked_g_rbuf)):\n unpacked_g_rbuf[x] = (unpacked_g_rbuf[x]/1000)\n testplot(np.arange (0, sample_size, 1), unpacked_g_rbuf)\ndef send_trig(ep_bit):\n ''' \n expects a single bit, not yet implement for list of bits \n '''\n f.xem.ActivateTriggerIn(ep_bit.addr, ep_bit.bits)\n\nif __name__ == \"__main__\":\n\n f = FPGA(bitfile = '728.bit')\n if (False == f.init_device()):\n raise SystemExit\n \n #Wait for the configuration\n time.sleep(3)\n factor = (int)(sample_size/8)\n f.xem.SetWireInValue(0x04, factor)\n #f.xem.SetWireInValue(0x04, 0xFF)\n f.xem.UpdateWireIns()\n\n #Sample rate speed, to bits 18:9\n f.xem.SetWireInValue(0x02, 0x0000A000, 0x0003FF00 )\n f.xem.UpdateWireIns()\n write_sin_wave(2)\n f.xem.WriteRegister(0x80000010, 0x00003410)\n f.xem.ActivateTriggerIn(0x40, 8)\n #f.xem.UpdateWireOuts()\n #print (f.xem.GetWireOutValue(0x3E))\n\n '''\n time.sleep(2)\n dacs = [1,2,3,4]\n # SPI Master configuration: divide reg, ctrl reg, SS register \n # MSB: 8 - set address, 4 - write data \n\n # creg_val = 0x40003610 # Char length of 16; set both Tx_NEG, Rx_NEG; set ASS, IE. ADS7952\n creg_val = 0x40003010 # Char length of 16; clear both Tx_NEG, Rx_NEG; set ASS, IE. AD5453 \n # val = 0x40001fff # AD5453 (half-scale)\n\n for val in [0x80000051, 0x40000013, # divider (need to look into settings of 1 and 2 didn't show 16 clock cycles) \n 0x80000041, creg_val, # control register (CHAR_LEN = 16, bits 10,9, 13 and 12)\n 0x80000061, 0x40000001]: # slave select (just setting bit0)\n\n f.set_wire(0x00, val, mask = 0xffffffff)\n send_trig(valid) \n\n # now send SPI command \n value = 0x40003FFF # AD5453 (half-scale)\n\n for val in [0x80000001, value, # Tx register, data to send \n 0x80000041, creg_val | (1 << 8)]: # Control register - GO (bit 8)\n f.set_wire(0x00, val, mask = 0xffffffff)\n send_trig(valid) \n'''" ]
[ [ "numpy.sin", "numpy.zeros", "matplotlib.pyplot.grid", "matplotlib.pyplot.axhline", "numpy.arange", "matplotlib.pyplot.title", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.plot", "matplotlib.pyplot.xlabel" ] ]