repo_name
stringlengths 6
130
| hexsha
sequence | file_path
sequence | code
sequence | apis
sequence | possible_versions
list |
---|---|---|---|---|---|
riels89/gunpowder | [
"e523b49ca846a9fd46ab6fc0dd1040cc4a4d53b4",
"e523b49ca846a9fd46ab6fc0dd1040cc4a4d53b4",
"e523b49ca846a9fd46ab6fc0dd1040cc4a4d53b4"
] | [
"tests/cases/specified_location.py",
"gunpowder/contrib/nodes/add_gt_mask_exclusive_zone.py",
"tests/cases/hdf5_source.py"
] | [
"# from .provider_test import ProviderTest, TestSource\nfrom gunpowder import (BatchProvider, ArrayKeys, ArraySpec, Roi, Batch,\n Coordinate, SpecifiedLocation, build,\n BatchRequest, Array, ArrayKey)\nimport numpy as np\nimport unittest\n\n\nclass TestSourceSpecifiedLocation(BatchProvider):\n def __init__(self, roi, voxel_size):\n self.voxel_size = Coordinate(voxel_size)\n self.roi = roi\n size = self.roi.get_shape() / self.voxel_size\n self.data = np.arange(np.prod(size)).reshape(size)\n\n def setup(self):\n self.provides(\n ArrayKeys.RAW,\n ArraySpec(\n roi=self.roi,\n voxel_size=self.voxel_size))\n\n def provide(self, request):\n batch = Batch()\n\n spec = request[ArrayKeys.RAW].copy()\n spec.voxel_size = self.voxel_size\n size = spec.roi.get_shape() / spec.voxel_size\n offset = spec.roi.get_offset() / spec.voxel_size\n slce = tuple(slice(o, o + s) for o, s in zip(offset, size))\n\n batch.arrays[ArrayKeys.RAW] = Array(\n data=self.data[slce],\n spec=spec)\n\n return batch\n\n\nclass TestSpecifiedLocation(unittest.TestCase):\n\n def setUp(self):\n ArrayKey('RAW')\n\n def test_simple(self):\n\n locations = [\n [0, 0, 0],\n [100, 100, 100],\n [91, 20, 20],\n [42, 24, 57]\n ]\n\n pipeline = (\n TestSourceSpecifiedLocation(\n roi=Roi((0, 0, 0), (100, 100, 100)),\n voxel_size=(1, 1, 1)) +\n SpecifiedLocation(\n locations,\n choose_randomly=False,\n extra_data=None,\n jitter=None)\n )\n\n with build(pipeline):\n\n batch = pipeline.request_batch(\n BatchRequest(\n {\n ArrayKeys.RAW: ArraySpec(\n roi=Roi((0, 0, 0), (20, 20, 20)))\n }))\n # first three locations are skipped\n # fourth should start at [32, 14, 47] of self.data\n self.assertEqual(batch.arrays[ArrayKeys.RAW].data[0, 0, 0], 321447)\n\n def test_voxel_size(self):\n\n locations = [\n [0, 0, 0],\n [91, 20, 20],\n [42, 24, 57]\n ]\n\n pipeline = (\n TestSourceSpecifiedLocation(\n roi=Roi((0, 0, 0), (100, 100, 100)),\n voxel_size=(5, 2, 2)) +\n SpecifiedLocation(\n locations,\n choose_randomly=False,\n extra_data=None,\n jitter=None)\n )\n\n with build(pipeline):\n\n batch = pipeline.request_batch(\n BatchRequest(\n {\n ArrayKeys.RAW: ArraySpec(\n roi=Roi((0, 0, 0), (20, 20, 20)))\n }))\n # first locations is skipped\n # second should start at [80/5, 10/2, 10/2] = [16, 5, 5]\n self.assertEqual(batch.arrays[ArrayKeys.RAW].data[0, 0, 0], 40255)\n\n batch = pipeline.request_batch(\n BatchRequest(\n {\n ArrayKeys.RAW: ArraySpec(\n roi=Roi((0, 0, 0), (20, 20, 20)))\n }))\n # third should start at [30/5, 14/2, 48/2] = [6, 7, 23]\n self.assertEqual(batch.arrays[ArrayKeys.RAW].data[0, 0, 0], 15374)\n\n def test_jitter_and_random(self):\n\n locations = [\n [0, 0, 0],\n [91, 20, 20],\n [42, 24, 57]\n ]\n\n pipeline = (\n TestSourceSpecifiedLocation(\n roi=Roi((0, 0, 0), (100, 100, 100)),\n voxel_size=(5, 2, 2)) +\n SpecifiedLocation(\n locations,\n choose_randomly=True,\n extra_data=None,\n jitter=(5, 5, 5))\n )\n\n with build(pipeline):\n\n batch = pipeline.request_batch(\n BatchRequest(\n {\n ArrayKeys.RAW: ArraySpec(\n roi=Roi((0, 0, 0), (20, 20, 20)))\n }))\n # Unclear what result should be, so no errors means passing\n self.assertTrue(batch.arrays[ArrayKeys.RAW].data[0, 0, 0] > 0)\n",
"import copy\nimport logging\nimport numpy as np\nfrom scipy import ndimage\n\nfrom gunpowder.nodes.batch_filter import BatchFilter\nfrom gunpowder.array import Array, ArrayKeys\nfrom gunpowder.nodes.rasterize_points import RasterizationSettings\nfrom gunpowder.morphology import enlarge_binary_map\n\nlogger = logging.getLogger(__name__)\n\nclass AddGtMaskExclusiveZone(BatchFilter):\n ''' Create ExclusizeZone mask for a binary map in batch and add it as\n array to batch.\n\n An ExclusiveZone mask is a bianry mask [0,1] where locations which lie\n within a given distance to the ON (=1) regions (surrounding the ON regions)\n of the given binary map are set to 0, whereas all the others are set to 1.\n\n Args:\n\n EZ_masks_to_binary_map(dict, :class:``ArrayKey``->:class:``ArrayKey``):\n Arrays of exclusive zones (keys of dict) to create for which\n binary mask (values of dict).\n\n gaussian_sigma_for_zone(float, optional): Defines extend of exclusive\n zone around ON region in binary map. Defaults to 1.\n\n rasterization_setting(:class:``RasterizationSettings``, optional): Which\n rasterization setting to use.\n '''\n\n def __init__(\n self,\n EZ_masks_to_binary_map,\n gaussian_sigma_for_zone=1,\n rasterization_setting=None):\n\n self.EZ_masks_to_binary_map = EZ_masks_to_binary_map\n self.gaussian_sigma_for_zone = gaussian_sigma_for_zone\n if rasterization_setting is None:\n self.rasterization_setting = RasterizationSettings()\n else:\n self.rasterization_setting = rasterization_setting\n self.skip_next = False\n\n\n def setup(self):\n\n self.upstream_spec = self.get_upstream_provider().get_spec()\n self.spec = copy.deepcopy(self.upstream_spec)\n\n for EZ_mask_type, binary_map_type in self.EZ_masks_to_binary_map.items():\n if binary_map_type in self.upstream_spec.arrays:\n self.spec.arrays[EZ_mask_type] = self.spec.arrays[binary_map_type]\n\n\n def get_spec(self):\n return self.spec\n\n\n def prepare(self, request):\n\n self.EZ_masks_to_create = []\n for EZ_mask_type, binary_map_type in self.EZ_masks_to_binary_map.items():\n # do nothing if binary mask to create EZ mask around is not requested as well\n if EZ_mask_type in request.arrays:\n # assert that binary mask for which EZ mask is created for is requested\n assert binary_map_type in request.arrays, \\\n \"ExclusiveZone Mask for {}, can only be created if {} also requested.\".format(EZ_mask_type, binary_map_type)\n # assert that ROI of EZ lies within ROI of binary mask\n assert request.arrays[binary_map_type].contains(request.arrays[EZ_mask_type]),\\\n \"EZ mask for {} requested for ROI outside of source's ({}) ROI.\".format(EZ_mask_type,binary_map_type)\n\n self.EZ_masks_to_create.append(EZ_mask_type)\n del request.arrays[EZ_mask_type]\n\n if len(self.EZ_masks_to_create) == 0:\n logger.warn(\"no ExclusiveZone Masks requested, will do nothing\")\n self.skip_next = True\n\n\n def process(self, batch, request):\n\n # do nothing if no gt binary maps were requested\n if self.skip_next:\n self.skip_next = False\n return\n\n for EZ_mask_type in self.EZ_masks_to_create:\n binary_map_type = self.EZ_masks_to_binary_map[EZ_mask_type]\n binary_map = batch.arrays[binary_map_type].data\n resolution = batch.arrays[binary_map_type].resolution\n EZ_mask = self.__get_exclusivezone_mask(binary_map, shape_EZ_mask=request.arrays[EZ_mask_type].get_shape(),\n resolution=resolution)\n\n batch.arrays[EZ_mask_type] = Array(data= EZ_mask,\n roi=request.arrays[EZ_mask_type],\n resolution=resolution)\n\n def __get_exclusivezone_mask(self, binary_map, shape_EZ_mask, resolution=None):\n ''' Exclusive zone surrounds every synapse. Created by enlarging the ON regions of given binary map\n with different gaussian filter, make it binary and subtract the original binary map from it '''\n\n shape_diff = np.asarray(binary_map.shape - np.asarray(shape_EZ_mask))\n slices = [slice(diff, shape - diff) for diff, shape in zip(shape_diff, binary_map.shape)]\n relevant_binary_map = binary_map[slices]\n\n\n BM_enlarged_binary = enlarge_binary_map(relevant_binary_map,\n marker_size_voxel=self.rasterization_setting.marker_size_voxel,\n voxel_size=resolution,\n marker_size_physical=self.rasterization_setting.marker_size_physical)\n\n\n exclusive_zone = np.ones_like(BM_enlarged_binary) - (BM_enlarged_binary - relevant_binary_map)\n return exclusive_zone\n",
"from unittest import skipIf\n\nfrom .provider_test import ProviderTest\nfrom gunpowder import *\nimport numpy as np\nfrom gunpowder.ext import h5py, zarr, ZarrFile, z5py, NoSuchModule\n\n\nclass Hdf5LikeSourceTestMixin(object):\n \"\"\"This class is to be used as a mixin for ProviderTest classes testing HDF5, N5 and Zarr\n batch providers.\n\n Subclasses must define ``extension`` and ``SourceUnderTest`` class variables, and an\n ``_open_writable_file(self, path)`` method. See TestHdf5Source for examples.\n \"\"\"\n extension = None\n SourceUnderTest = None\n\n def _open_writable_file(self, path):\n raise NotImplementedError('_open_writable_file should be overridden')\n\n def _create_dataset(self, data_file, key, data, chunks=None, **kwargs):\n chunks = chunks or data.shape\n d = data_file.create_dataset(key, shape=data.shape, dtype=data.dtype, chunks=chunks)\n d[:] = data\n for key, value in kwargs.items():\n d.attrs[key] = value\n\n def test_output_2d(self):\n path = self.path_to('test_{0}_source.{0}'.format(self.extension))\n\n with self._open_writable_file(path) as f:\n self._create_dataset(f, 'raw', np.zeros((100, 100), dtype=np.float32))\n self._create_dataset(f, 'raw_low', np.zeros((10, 10), dtype=np.float32), resolution=(10, 10))\n self._create_dataset(f, 'seg', np.ones((100, 100), dtype=np.uint64))\n\n # read arrays\n raw = ArrayKey('RAW')\n raw_low = ArrayKey('RAW_LOW')\n seg = ArrayKey('SEG')\n source = self.SourceUnderTest(\n path,\n {\n raw: 'raw',\n raw_low: 'raw_low',\n seg: 'seg'\n }\n )\n\n with build(source):\n batch = source.request_batch(\n BatchRequest({\n raw: ArraySpec(roi=Roi((0, 0), (100, 100))),\n raw_low: ArraySpec(roi=Roi((0, 0), (100, 100))),\n seg: ArraySpec(roi=Roi((0, 0), (100, 100))),\n })\n )\n\n self.assertTrue(batch.arrays[raw].spec.interpolatable)\n self.assertTrue(batch.arrays[raw_low].spec.interpolatable)\n self.assertFalse(batch.arrays[seg].spec.interpolatable)\n\n def test_output_3d(self):\n path = self.path_to('test_{0}_source.{0}'.format(self.extension))\n\n # create a test file\n with self._open_writable_file(path) as f:\n self._create_dataset(f, 'raw', np.zeros((100, 100, 100), dtype=np.float32))\n self._create_dataset(f, 'raw_low', np.zeros((10, 10, 10), dtype=np.float32), resolution=(10, 10, 10))\n self._create_dataset(f, 'seg', np.ones((100, 100, 100), dtype=np.uint64))\n\n # read arrays\n raw = ArrayKey('RAW')\n raw_low = ArrayKey('RAW_LOW')\n seg = ArrayKey('SEG')\n source = self.SourceUnderTest(\n path,\n {\n raw: 'raw',\n raw_low: 'raw_low',\n seg: 'seg'\n }\n )\n\n with build(source):\n\n batch = source.request_batch(\n BatchRequest({\n raw: ArraySpec(roi=Roi((0, 0, 0), (100, 100, 100))),\n raw_low: ArraySpec(roi=Roi((0, 0, 0), (100, 100, 100))),\n seg: ArraySpec(roi=Roi((0, 0, 0), (100, 100, 100))),\n })\n )\n\n self.assertTrue(batch.arrays[raw].spec.interpolatable)\n self.assertTrue(batch.arrays[raw_low].spec.interpolatable)\n self.assertFalse(batch.arrays[seg].spec.interpolatable)\n\n\nclass TestHdf5Source(ProviderTest, Hdf5LikeSourceTestMixin):\n extension = 'hdf'\n SourceUnderTest = Hdf5Source\n\n def _open_writable_file(self, path):\n return h5py.File(path, 'w')\n\n\n@skipIf(isinstance(zarr, NoSuchModule), 'zarr is not installed')\nclass TestZarrSource(ProviderTest, Hdf5LikeSourceTestMixin):\n extension = 'zarr'\n SourceUnderTest = ZarrSource\n\n def _open_writable_file(self, path):\n return ZarrFile(path, mode='w')\n\n\n@skipIf(isinstance(z5py, NoSuchModule), 'z5py is not installed')\nclass TestN5Source(ProviderTest, Hdf5LikeSourceTestMixin):\n extension = 'n5'\n SourceUnderTest = N5Source\n\n def _open_writable_file(self, path):\n return z5py.File(path, use_zarr_format=False)\n"
] | [
[
"numpy.prod"
],
[
"numpy.asarray",
"numpy.ones_like"
],
[
"numpy.zeros",
"numpy.ones"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
joshes/ocp | [
"e04056d008616eaf5058b7851d8ac29b8f2da473"
] | [
"ocpmodels/trainers/forces_trainer.py"
] | [
"\"\"\"\nCopyright (c) Facebook, Inc. and its affiliates.\n\nThis source code is licensed under the MIT license found in the\nLICENSE file in the root directory of this source tree.\n\"\"\"\n\nimport os\nfrom collections import defaultdict\n\nimport numpy as np\nimport torch\nimport torch_geometric\nfrom torch.utils.data import DataLoader, DistributedSampler\nfrom tqdm import tqdm\n\nfrom ocpmodels.common import distutils\nfrom ocpmodels.common.data_parallel import ParallelCollater\nfrom ocpmodels.common.registry import registry\nfrom ocpmodels.common.relaxation.ml_relaxation import ml_relax\nfrom ocpmodels.common.utils import plot_histogram\nfrom ocpmodels.modules.evaluator import Evaluator\nfrom ocpmodels.modules.normalizer import Normalizer\nfrom ocpmodels.trainers.base_trainer import BaseTrainer\n\n\[email protected]_trainer(\"forces\")\nclass ForcesTrainer(BaseTrainer):\n \"\"\"\n Trainer class for the Structure to Energy & Force (S2EF) and Initial State to\n Relaxed State (IS2RS) tasks.\n\n .. note::\n\n Examples of configurations for task, model, dataset and optimizer\n can be found in `configs/ocp_s2ef <https://github.com/Open-Catalyst-Project/baselines/tree/master/configs/ocp_is2re/>`_\n and `configs/ocp_is2rs <https://github.com/Open-Catalyst-Project/baselines/tree/master/configs/ocp_is2rs/>`_.\n\n Args:\n task (dict): Task configuration.\n model (dict): Model configuration.\n dataset (dict): Dataset configuration. The dataset needs to be a SinglePointLMDB dataset.\n optimizer (dict): Optimizer configuration.\n identifier (str): Experiment identifier that is appended to log directory.\n run_dir (str, optional): Path to the run directory where logs are to be saved.\n (default: :obj:`None`)\n is_debug (bool, optional): Run in debug mode.\n (default: :obj:`False`)\n is_vis (bool, optional): Run in debug mode.\n (default: :obj:`False`)\n print_every (int, optional): Frequency of printing logs.\n (default: :obj:`100`)\n seed (int, optional): Random number seed.\n (default: :obj:`None`)\n logger (str, optional): Type of logger to be used.\n (default: :obj:`tensorboard`)\n local_rank (int, optional): Local rank of the process, only applicable for distributed training.\n (default: :obj:`0`)\n amp (bool, optional): Run using automatic mixed precision.\n (default: :obj:`False`)\n \"\"\"\n\n def __init__(\n self,\n task,\n model,\n dataset,\n optimizer,\n identifier,\n run_dir=None,\n is_debug=False,\n is_vis=False,\n print_every=100,\n seed=None,\n logger=\"tensorboard\",\n local_rank=0,\n amp=False,\n ):\n super().__init__(\n task=task,\n model=model,\n dataset=dataset,\n optimizer=optimizer,\n identifier=identifier,\n run_dir=run_dir,\n is_debug=is_debug,\n is_vis=is_vis,\n print_every=print_every,\n seed=seed,\n logger=logger,\n local_rank=local_rank,\n amp=amp,\n name=\"s2ef\",\n )\n\n def load_task(self):\n print(\"### Loading dataset: {}\".format(self.config[\"task\"][\"dataset\"]))\n\n self.parallel_collater = ParallelCollater(\n 1, self.config[\"model_attributes\"].get(\"otf_graph\", False)\n )\n if self.config[\"task\"][\"dataset\"] == \"trajectory_lmdb\":\n self.train_dataset = registry.get_dataset_class(\n self.config[\"task\"][\"dataset\"]\n )(self.config[\"dataset\"])\n\n self.train_loader = DataLoader(\n self.train_dataset,\n batch_size=self.config[\"optim\"][\"batch_size\"],\n shuffle=True,\n collate_fn=self.parallel_collater,\n num_workers=self.config[\"optim\"][\"num_workers\"],\n pin_memory=True,\n )\n\n self.val_loader = self.test_loader = None\n\n if \"val_dataset\" in self.config:\n self.val_dataset = registry.get_dataset_class(\n self.config[\"task\"][\"dataset\"]\n )(self.config[\"val_dataset\"])\n self.val_loader = DataLoader(\n self.val_dataset,\n self.config[\"optim\"].get(\"eval_batch_size\", 64),\n shuffle=False,\n collate_fn=self.parallel_collater,\n num_workers=self.config[\"optim\"][\"num_workers\"],\n pin_memory=True,\n )\n if \"test_dataset\" in self.config:\n self.test_dataset = registry.get_dataset_class(\n self.config[\"task\"][\"dataset\"]\n )(self.config[\"test_dataset\"])\n self.test_loader = DataLoader(\n self.test_dataset,\n self.config[\"optim\"].get(\"eval_batch_size\", 64),\n shuffle=False,\n collate_fn=self.parallel_collater,\n num_workers=self.config[\"optim\"][\"num_workers\"],\n pin_memory=True,\n )\n\n if \"relax_dataset\" in self.config[\"task\"]:\n assert os.path.isfile(\n self.config[\"task\"][\"relax_dataset\"][\"src\"]\n )\n\n self.relax_dataset = registry.get_dataset_class(\n \"single_point_lmdb\"\n )(self.config[\"task\"][\"relax_dataset\"])\n\n self.relax_sampler = DistributedSampler(\n self.relax_dataset,\n num_replicas=distutils.get_world_size(),\n rank=distutils.get_rank(),\n shuffle=False,\n )\n self.relax_loader = DataLoader(\n self.relax_dataset,\n batch_size=self.config[\"optim\"].get(\"eval_batch_size\", 64),\n collate_fn=self.parallel_collater,\n num_workers=self.config[\"optim\"][\"num_workers\"],\n pin_memory=True,\n sampler=self.relax_sampler,\n )\n\n else:\n self.dataset = registry.get_dataset_class(\n self.config[\"task\"][\"dataset\"]\n )(self.config[\"dataset\"])\n (\n self.train_loader,\n self.val_loader,\n self.test_loader,\n ) = self.dataset.get_dataloaders(\n batch_size=self.config[\"optim\"][\"batch_size\"],\n collate_fn=self.parallel_collater,\n )\n\n self.num_targets = 1\n\n # Normalizer for the dataset.\n # Compute mean, std of training set labels.\n self.normalizers = {}\n if self.config[\"dataset\"].get(\"normalize_labels\", False):\n if \"target_mean\" in self.config[\"dataset\"]:\n self.normalizers[\"target\"] = Normalizer(\n mean=self.config[\"dataset\"][\"target_mean\"],\n std=self.config[\"dataset\"][\"target_std\"],\n device=self.device,\n )\n else:\n self.normalizers[\"target\"] = Normalizer(\n tensor=self.train_loader.dataset.data.y[\n self.train_loader.dataset.__indices__\n ],\n device=self.device,\n )\n\n # If we're computing gradients wrt input, set mean of normalizer to 0 --\n # since it is lost when compute dy / dx -- and std to forward target std\n if self.config[\"model_attributes\"].get(\"regress_forces\", True):\n if self.config[\"dataset\"].get(\"normalize_labels\", False):\n if \"grad_target_mean\" in self.config[\"dataset\"]:\n self.normalizers[\"grad_target\"] = Normalizer(\n mean=self.config[\"dataset\"][\"grad_target_mean\"],\n std=self.config[\"dataset\"][\"grad_target_std\"],\n device=self.device,\n )\n else:\n self.normalizers[\"grad_target\"] = Normalizer(\n tensor=self.train_loader.dataset.data.y[\n self.train_loader.dataset.__indices__\n ],\n device=self.device,\n )\n self.normalizers[\"grad_target\"].mean.fill_(0)\n\n if (\n self.is_vis\n and self.config[\"task\"][\"dataset\"] != \"qm9\"\n and distutils.is_master()\n ):\n # Plot label distribution.\n plots = [\n plot_histogram(\n self.train_loader.dataset.data.y.tolist(),\n xlabel=\"{}/raw\".format(self.config[\"task\"][\"labels\"][0]),\n ylabel=\"# Examples\",\n title=\"Split: train\",\n ),\n plot_histogram(\n self.val_loader.dataset.data.y.tolist(),\n xlabel=\"{}/raw\".format(self.config[\"task\"][\"labels\"][0]),\n ylabel=\"# Examples\",\n title=\"Split: val\",\n ),\n plot_histogram(\n self.test_loader.dataset.data.y.tolist(),\n xlabel=\"{}/raw\".format(self.config[\"task\"][\"labels\"][0]),\n ylabel=\"# Examples\",\n title=\"Split: test\",\n ),\n ]\n self.logger.log_plots(plots)\n\n # Takes in a new data source and generates predictions on it.\n def predict(\n self, data_loader, per_image=True, results_file=None, disable_tqdm=True\n ):\n if distutils.is_master() and not disable_tqdm:\n print(\"### Predicting on test.\")\n assert isinstance(\n data_loader,\n (\n torch.utils.data.dataloader.DataLoader,\n torch_geometric.data.Batch,\n ),\n )\n rank = distutils.get_rank()\n\n if isinstance(data_loader, torch_geometric.data.Batch):\n data_loader = [[data_loader]]\n\n self.model.eval()\n if self.normalizers is not None and \"target\" in self.normalizers:\n self.normalizers[\"target\"].to(self.device)\n self.normalizers[\"grad_target\"].to(self.device)\n\n predictions = {\"id\": [], \"energy\": [], \"forces\": []}\n\n for i, batch_list in tqdm(\n enumerate(data_loader),\n total=len(data_loader),\n position=rank,\n desc=\"device {}\".format(rank),\n disable=disable_tqdm,\n ):\n with torch.cuda.amp.autocast(enabled=self.scaler is not None):\n out = self._forward(batch_list)\n\n if self.normalizers is not None and \"target\" in self.normalizers:\n out[\"energy\"] = self.normalizers[\"target\"].denorm(\n out[\"energy\"]\n )\n out[\"forces\"] = self.normalizers[\"grad_target\"].denorm(\n out[\"forces\"]\n )\n if per_image:\n atoms_sum = 0\n systemids = [\n str(i) + \"_\" + str(j)\n for i, j in zip(\n batch_list[0].sid.tolist(), batch_list[0].fid.tolist()\n )\n ]\n predictions[\"id\"].extend(systemids)\n predictions[\"energy\"].extend(\n out[\"energy\"].to(torch.float16).tolist()\n )\n batch_natoms = torch.cat(\n [batch.natoms for batch in batch_list]\n )\n batch_fixed = torch.cat([batch.fixed for batch in batch_list])\n for natoms in batch_natoms:\n forces = (\n out[\"forces\"][atoms_sum : natoms + atoms_sum]\n .cpu()\n .detach()\n .to(torch.float16)\n .numpy()\n )\n # evalAI only requires forces on free atoms\n if results_file is not None:\n _free_atoms = (\n batch_fixed[atoms_sum : natoms + atoms_sum] == 0\n ).tolist()\n forces = forces[_free_atoms]\n atoms_sum += natoms\n predictions[\"forces\"].append(forces)\n else:\n predictions[\"energy\"] = out[\"energy\"].detach()\n predictions[\"forces\"] = out[\"forces\"].detach()\n return predictions\n\n predictions[\"forces\"] = np.array(predictions[\"forces\"], dtype=object)\n predictions[\"energy\"] = np.array(predictions[\"energy\"])\n predictions[\"id\"] = np.array(predictions[\"id\"])\n self.save_results(predictions, results_file, keys=[\"energy\", \"forces\"])\n return predictions\n\n def train(self):\n self.best_val_metric = -1.0\n eval_every = self.config[\"optim\"].get(\"eval_every\", -1)\n primary_metric = self.config[\"task\"].get(\n \"primary_metric\", self.evaluator.task_primary_metric[self.name]\n )\n iters = 0\n self.metrics = {}\n for epoch in range(self.config[\"optim\"][\"max_epochs\"]):\n self.model.train()\n for i, batch in enumerate(self.train_loader):\n # Forward, loss, backward.\n with torch.cuda.amp.autocast(enabled=self.scaler is not None):\n out = self._forward(batch)\n loss = self._compute_loss(out, batch)\n loss = self.scaler.scale(loss) if self.scaler else loss\n self._backward(loss)\n scale = self.scaler.get_scale() if self.scaler else 1.0\n\n # Compute metrics.\n self.metrics = self._compute_metrics(\n out,\n batch,\n self.evaluator,\n self.metrics,\n )\n self.metrics = self.evaluator.update(\n \"loss\", loss.item() / scale, self.metrics\n )\n\n # Print metrics, make plots.\n log_dict = {k: self.metrics[k][\"metric\"] for k in self.metrics}\n log_dict.update(\n {\"epoch\": epoch + (i + 1) / len(self.train_loader)}\n )\n if (\n i % self.config[\"cmd\"][\"print_every\"] == 0\n and distutils.is_master()\n ):\n log_str = [\n \"{}: {:.4f}\".format(k, v) for k, v in log_dict.items()\n ]\n print(\", \".join(log_str))\n self.metrics = {}\n\n if self.logger is not None:\n self.logger.log(\n log_dict,\n step=epoch * len(self.train_loader) + i + 1,\n split=\"train\",\n )\n\n iters += 1\n\n # Evaluate on val set every `eval_every` iterations.\n if eval_every != -1 and iters % eval_every == 0:\n if self.val_loader is not None:\n val_metrics = self.validate(\n split=\"val\",\n epoch=epoch - 1 + (i + 1) / len(self.train_loader),\n )\n if (\n val_metrics[primary_metric][\"metric\"]\n > self.best_val_metric\n ):\n self.best_val_metric = val_metrics[primary_metric][\n \"metric\"\n ]\n current_epoch = epoch + (i + 1) / len(\n self.train_loader\n )\n self.save(current_epoch, val_metrics)\n if self.test_loader is not None:\n self.predict(\n self.test_loader,\n results_file=\"predictions\",\n disable_tqdm=False,\n )\n\n self.scheduler.step()\n torch.cuda.empty_cache()\n\n if eval_every == -1:\n if self.val_loader is not None:\n val_metrics = self.validate(split=\"val\", epoch=epoch)\n if (\n val_metrics[primary_metric][\"metric\"]\n > self.best_val_metric\n ):\n self.best_val_metric = val_metrics[primary_metric][\n \"metric\"\n ]\n self.save(epoch + 1, val_metrics)\n if self.test_loader is not None:\n self.predict(\n self.test_loader,\n results_file=\"predictions\",\n disable_tqdm=False,\n )\n else:\n self.save(epoch + 1, self.metrics)\n\n def _forward(self, batch_list):\n # forward pass.\n if self.config[\"model_attributes\"].get(\"regress_forces\", True):\n out_energy, out_forces = self.model(batch_list)\n else:\n out_energy = self.model(batch_list)\n\n if out_energy.shape[-1] == 1:\n out_energy = out_energy.view(-1)\n\n out = {\n \"energy\": out_energy,\n }\n\n if self.config[\"model_attributes\"].get(\"regress_forces\", True):\n out[\"forces\"] = out_forces\n\n return out\n\n def _compute_loss(self, out, batch_list):\n loss = []\n\n # Energy loss.\n energy_target = torch.cat(\n [batch.y.to(self.device) for batch in batch_list], dim=0\n )\n if self.config[\"dataset\"].get(\"normalize_labels\", False):\n energy_target = self.normalizers[\"target\"].norm(energy_target)\n energy_mult = self.config[\"optim\"].get(\"energy_coefficient\", 1)\n loss.append(energy_mult * self.criterion(out[\"energy\"], energy_target))\n\n # Force loss.\n if self.config[\"model_attributes\"].get(\"regress_forces\", True):\n force_target = torch.cat(\n [batch.force.to(self.device) for batch in batch_list], dim=0\n )\n if self.config[\"dataset\"].get(\"normalize_labels\", False):\n force_target = self.normalizers[\"grad_target\"].norm(\n force_target\n )\n\n # Force coefficient = 30 has been working well for us.\n force_mult = self.config[\"optim\"].get(\"force_coefficient\", 30)\n if self.config[\"task\"].get(\"train_on_free_atoms\", False):\n fixed = torch.cat(\n [batch.fixed.to(self.device) for batch in batch_list]\n )\n mask = fixed == 0\n loss.append(\n force_mult\n * self.criterion(out[\"forces\"][mask], force_target[mask])\n )\n else:\n loss.append(\n force_mult * self.criterion(out[\"forces\"], force_target)\n )\n\n # Sanity check to make sure the compute graph is correct.\n for lc in loss:\n assert hasattr(lc, \"grad_fn\")\n\n loss = sum(loss)\n return loss\n\n def _compute_metrics(self, out, batch_list, evaluator, metrics={}):\n natoms = torch.cat(\n [batch.natoms.to(self.device) for batch in batch_list], dim=0\n )\n\n target = {\n \"energy\": torch.cat(\n [batch.y.to(self.device) for batch in batch_list], dim=0\n ),\n \"forces\": torch.cat(\n [batch.force.to(self.device) for batch in batch_list], dim=0\n ),\n \"natoms\": natoms,\n }\n\n out[\"natoms\"] = natoms\n\n if self.config[\"task\"].get(\"eval_on_free_atoms\", True):\n fixed = torch.cat(\n [batch.fixed.to(self.device) for batch in batch_list]\n )\n mask = fixed == 0\n out[\"forces\"] = out[\"forces\"][mask]\n target[\"forces\"] = target[\"forces\"][mask]\n\n s_idx = 0\n natoms_free = []\n for natoms in target[\"natoms\"]:\n natoms_free.append(\n torch.sum(mask[s_idx : s_idx + natoms]).item()\n )\n s_idx += natoms\n target[\"natoms\"] = torch.LongTensor(natoms_free).to(self.device)\n out[\"natoms\"] = torch.LongTensor(natoms_free).to(self.device)\n\n if self.config[\"dataset\"].get(\"normalize_labels\", False):\n out[\"energy\"] = self.normalizers[\"target\"].denorm(out[\"energy\"])\n out[\"forces\"] = self.normalizers[\"grad_target\"].denorm(\n out[\"forces\"]\n )\n\n metrics = evaluator.eval(out, target, prev_metrics=metrics)\n return metrics\n\n def run_relaxations(self, split=\"val\", epoch=None):\n print(\"### Running ML-relaxations\")\n self.model.eval()\n\n evaluator, metrics = Evaluator(task=\"is2rs\"), {}\n\n if hasattr(self.relax_dataset[0], \"pos_relaxed\") and hasattr(\n self.relax_dataset[0], \"y_relaxed\"\n ):\n split = \"val\"\n else:\n split = \"test\"\n\n ids = []\n relaxed_positions = []\n for i, batch in tqdm(\n enumerate(self.relax_loader), total=len(self.relax_loader)\n ):\n relaxed_batch = ml_relax(\n batch=batch,\n model=self,\n steps=self.config[\"task\"].get(\"relaxation_steps\", 200),\n fmax=self.config[\"task\"].get(\"relaxation_fmax\", 0.0),\n relax_opt=self.config[\"task\"][\"relax_opt\"],\n device=self.device,\n transform=None,\n )\n\n if self.config[\"task\"].get(\"write_pos\", False):\n systemids = [str(i) for i in relaxed_batch.sid.tolist()]\n natoms = relaxed_batch.natoms.tolist()\n positions = torch.split(relaxed_batch.pos, natoms)\n batch_relaxed_positions = [pos.tolist() for pos in positions]\n\n relaxed_positions += batch_relaxed_positions\n ids += systemids\n\n if split == \"val\":\n mask = relaxed_batch.fixed == 0\n s_idx = 0\n natoms_free = []\n for natoms in relaxed_batch.natoms:\n natoms_free.append(\n torch.sum(mask[s_idx : s_idx + natoms]).item()\n )\n s_idx += natoms\n\n target = {\n \"energy\": relaxed_batch.y_relaxed,\n \"positions\": relaxed_batch.pos_relaxed[mask],\n \"cell\": relaxed_batch.cell,\n \"pbc\": torch.tensor([True, True, True]),\n \"natoms\": torch.LongTensor(natoms_free),\n }\n\n prediction = {\n \"energy\": relaxed_batch.y,\n \"positions\": relaxed_batch.pos[mask],\n \"cell\": relaxed_batch.cell,\n \"pbc\": torch.tensor([True, True, True]),\n \"natoms\": torch.LongTensor(natoms_free),\n }\n\n metrics = evaluator.eval(prediction, target, metrics)\n\n if self.config[\"task\"].get(\"write_pos\", False):\n rank = distutils.get_rank()\n pos_filename = os.path.join(\n self.config[\"cmd\"][\"results_dir\"], f\"relaxed_pos_{rank}.npz\"\n )\n np.savez_compressed(\n pos_filename,\n ids=ids,\n pos=np.array(relaxed_positions, dtype=object),\n )\n\n distutils.synchronize()\n if distutils.is_master():\n gather_results = defaultdict(list)\n full_path = os.path.join(\n self.config[\"cmd\"][\"results_dir\"],\n \"relaxed_positions.npz\",\n )\n\n for i in range(distutils.get_world_size()):\n rank_path = os.path.join(\n self.config[\"cmd\"][\"results_dir\"],\n f\"relaxed_pos_{i}.npz\",\n )\n rank_results = np.load(rank_path, allow_pickle=True)\n gather_results[\"ids\"].extend(rank_results[\"ids\"])\n gather_results[\"pos\"].extend(rank_results[\"pos\"])\n os.remove(rank_path)\n\n # Because of how distributed sampler works, some system ids\n # might be repeated to make no. of samples even across GPUs.\n _, idx = np.unique(gather_results[\"ids\"], return_index=True)\n gather_results[\"ids\"] = np.array(gather_results[\"ids\"])[idx]\n gather_results[\"pos\"] = np.array(\n gather_results[\"pos\"], dtype=object\n )[idx]\n\n print(f\"Writing results to {full_path}\")\n np.savez_compressed(full_path, **gather_results)\n\n if split == \"val\":\n aggregated_metrics = {}\n for k in metrics:\n aggregated_metrics[k] = {\n \"total\": distutils.all_reduce(\n metrics[k][\"total\"], average=False, device=self.device\n ),\n \"numel\": distutils.all_reduce(\n metrics[k][\"numel\"], average=False, device=self.device\n ),\n }\n aggregated_metrics[k][\"metric\"] = (\n aggregated_metrics[k][\"total\"]\n / aggregated_metrics[k][\"numel\"]\n )\n metrics = aggregated_metrics\n\n # Make plots.\n log_dict = {k: metrics[k][\"metric\"] for k in metrics}\n if self.logger is not None and epoch is not None:\n self.logger.log(\n log_dict,\n step=(epoch + 1) * len(self.train_loader),\n split=split,\n )\n\n if distutils.is_master():\n print(metrics)\n"
] | [
[
"torch.LongTensor",
"torch.cat",
"numpy.unique",
"torch.utils.data.DataLoader",
"torch.cuda.empty_cache",
"torch.sum",
"torch.cuda.amp.autocast",
"torch.tensor",
"numpy.savez_compressed",
"torch.split",
"numpy.load",
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
naivelogic/ZeroWaste3D | [
"915d4a37563db8481c8631ab0e34cfd0512941f8",
"915d4a37563db8481c8631ab0e34cfd0512941f8"
] | [
"DataManager/Legacy/create_dataset/generate_mask_db.py",
"research/AzureML/yolact_fcos_alm/yolact_fcos_alm_runner.py"
] | [
"#%%\nimport sys, os, glob\nimport numpy as np\nsys.path.append(\"../\") # go to parent dir\n\nfrom utils.coco_manager import MaskManager\n\n\n## Create Train/Val/Test/ Datasets\n#Train: 80% \n#Val: 18%\n#Test: 2%\n\n#%%\nDATASET_VERSON = 'ds2'\nDATASET_PATH = f'/mnt/zerowastepublic/02-datasets/{DATASET_VERSON}/'\nDATASET_RAW_FOLDER = f'/mnt/zerowastepublic/02-datasets/{DATASET_VERSON}/raw/'\n\n# debug for nocs - 7/15\nDATASET_PATH = f'/mnt/daredevildiag/6PACK/z3d/ds1/InstanceGroup2Desccamera_0camera_Shape0_iter0/'\nDATASET_RAW_FOLDER = f'/mnt/daredevildiag/6PACK/z3d/ds1/'\n\n# debug for water waste - 10/15/20\nDATASET_PATH = f'/home/redne/ZeroWaste3D/DataManager/create_dataset/sample_maya_raw/ds1/'\nDATASET_RAW_FOLDER = f'/home/redne/ZeroWaste3D/DataManager/create_dataset/sample_maya_raw/ds1/raw/'\n\n\n\nfrom sklearn.model_selection import train_test_split\ndir_list = os.listdir(DATASET_RAW_FOLDER)\ntrain, val = train_test_split(dir_list, test_size=0.2, random_state=31)\nval, test = train_test_split(val, test_size=0.1, random_state=31)\n\nprint(f'training dataset size: {len(train)}\\nvalidation dataset size: {len(val)}\\ntest dataset size: {len(test)}')\n\n\n\n#%%\n# debug for nocs - 7/15\n#train = ['/mnt/daredevildiag/6PACK/z3d/ds1/raw/InstanceGroup2Desccamera_0camera_Shape0_iter0/']\ntrain = ['InstanceGroup2Desccamera_0camera_Shape0_iter0']\n#DATASET_PATH = '/mnt/daredevildiag/6PACK/z3d/ds1/'\nDATASET_PATH = f'/home/redne/ZeroWaste3D/DataManager/create_dataset/sample_maya_raw/ds1/'\ndef mask_runner(dataset_paths, phase):\n m = MaskManager(DATASET_PATH)\n\n m.dataset_raw_folder = os.path.join(DATASET_PATH, 'raw')\n\n # save new mask & images\n m.custom_classes_flag = True\n m.resave_masks = True\n m.resave_mask_path = os.path.join(DATASET_PATH, 'masks')\n\n m.resave_images_flag = True\n m.resave_images_path = os.path.join(DATASET_PATH, 'images')\n\n\n m.custom_classes = {\n \"H_beveragebottle\": \"H_beveragebottle\",\n \"D_lid\": \"D_lid\",\n \"S_cup\": \"S_cup\"\n }\n m.colorMapping = {\n \"H_beveragebottle\": [0, 255, 0],\n 'D_lid': [255, 0, 0],\n 'S_cup': [0, 0, 255]\n }\n m.mask_colors = {\n \"H_beveragebottle\": (0, 255, 0),\n \"D_lid\": (255, 0, 0),\n \"S_cup\": (0, 0, 255),\n }\n m.super_categories = {\n \"H_beveragebottle\": \"H_beveragebottle\",\n \"D_lid\": \"D_lid\",\n \"S_cup\": \"S_cup\"\n }\n m.get_super_categories = {\n \"H_beveragebottle\": [\"H_beveragebottle\"],\n \"D_lid\": [\"D_lid\"],\n \"S_cup\": [\"S_cup\"]\n }\n \n m.start(phase=phase, mask_paths=dataset_paths)\n\n print(f'there are {len(m.masks)} images')\n m.show_mask_img(len(m.masks)-1)\n m.write_masks_to_json(phase=phase)\n\n#%%\nmask_runner(train, 'train') # debug for nocs - 7/15\n#mask_runner(train, 'ds2_3c_train')\n\n#%%\nmask_runner(test, 'ds2_3c_test')\n\n#%%\nmask_runner(val, 'ds2_3c_val')\n\n\n\"\"\"\npython coco_json_utils.py -md /mnt/zerowastepublic/02-datasets/ds2/dataset_config/ds2_3c_test_mask_definitions.json -di /home/redne/mnt/project_zero/project_zero/ds1/experiments/dataset_config/dataset_info.json -ph ds2_3c_test -dp /mnt/zerowastepublic/02-datasets/ds2/dataset_config/\n\n\npython coco_json_utils.py -md /mnt/daredevildiag/6PACK/z3d/ds1/dataset_config/train_mask_definitions.json -di dataset_info.json -ph train -dp /mnt/daredevildiag/6PACK/z3d/ds1/dataset_config/\n\"\"\"",
"# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\n# Modified by Youngwan Lee (ETRI), 2020. All Rights Reserved.\nimport logging\nimport os\nfrom collections import OrderedDict\nimport torch\nfrom torch.nn.parallel import DistributedDataParallel\n\nimport detectron2.utils.comm as comm\nfrom detectron2.data import MetadataCatalog, build_detection_train_loader\nfrom detectron2.data.dataset_mapper import DatasetMapper\nfrom detectron2.engine import DefaultTrainer, default_argument_parser, default_setup, hooks, launch\nfrom detectron2.evaluation import (\n # CityscapesEvaluator,\n COCOPanopticEvaluator,\n DatasetEvaluators,\n LVISEvaluator,\n PascalVOCDetectionEvaluator,\n SemSegEvaluator,\n verify_results,\n)\nfrom detectron2.modeling import GeneralizedRCNNWithTTA\nfrom detectron2.utils.events import EventStorage\nfrom fcos.checkpoint import AdetCheckpointer\nfrom fcos.config import get_cfg\nfrom fcos.evaluation import COCOEvaluator\n\nfrom detectron2.data.datasets import register_coco_instances\nimport argparse\n#import multiprocessing as mp #https://github.com/roym899/abandoned_bag_detection/blob/master/demo.py#L10\n\nclass Trainer(DefaultTrainer):\n \"\"\"\n This is the same Trainer except that we rewrite the\n `build_train_loader` method.\n \"\"\"\n\n def __init__(self, cfg):\n \"\"\"\n Args:\n cfg (CfgNode):\n Use the custom checkpointer, which loads other backbone models\n with matching heuristics.\n \"\"\"\n # Assume these objects must be constructed in this order.\n model = self.build_model(cfg)\n optimizer = self.build_optimizer(cfg, model)\n data_loader = self.build_train_loader(cfg)\n\n # For training, wrap with DDP. But don't need this for inference.\n if comm.get_world_size() > 1:\n model = DistributedDataParallel(\n model, device_ids=[comm.get_local_rank()], broadcast_buffers=False\n )\n super(DefaultTrainer, self).__init__(model, data_loader, optimizer)\n\n self.scheduler = self.build_lr_scheduler(cfg, optimizer)\n # Assume no other objects need to be checkpointed.\n # We can later make it checkpoint the stateful hooks\n self.checkpointer = AdetCheckpointer(\n # Assume you want to save checkpoints together with logs/statistics\n model,\n cfg.OUTPUT_DIR,\n optimizer=optimizer,\n scheduler=self.scheduler,\n )\n self.start_iter = 0\n self.max_iter = cfg.SOLVER.MAX_ITER\n self.cfg = cfg\n\n self.register_hooks(self.build_hooks())\n\n def train_loop(self, start_iter: int, max_iter: int):\n \"\"\"\n Args:\n start_iter, max_iter (int): See docs above\n \"\"\"\n logger = logging.getLogger(__name__)\n logger.info(\"Starting training from iteration {}\".format(start_iter))\n\n self.iter = self.start_iter = start_iter\n self.max_iter = max_iter\n\n with EventStorage(start_iter) as self.storage:\n self.before_train()\n for self.iter in range(start_iter, max_iter):\n self.before_step()\n self.run_step()\n self.after_step()\n self.after_train()\n\n def train(self):\n \"\"\"\n Run training.\n Returns:\n OrderedDict of results, if evaluation is enabled. Otherwise None.\n \"\"\"\n self.train_loop(self.start_iter, self.max_iter)\n if hasattr(self, \"_last_eval_results\") and comm.is_main_process():\n verify_results(self.cfg, self._last_eval_results)\n return self._last_eval_results\n\n @classmethod\n def build_train_loader(cls, cfg):\n \"\"\"\n Returns:\n iterable\n It calls :func:`detectron2.data.build_detection_train_loader` with a customized\n DatasetMapper, which adds categorical labels as a semantic mask.\n \"\"\"\n mapper = DatasetMapper(cfg, True)\n return build_detection_train_loader(cfg, mapper)\n\n @classmethod\n def build_evaluator(cls, cfg, dataset_name, output_folder=None):\n \"\"\"\n Create evaluator(s) for a given dataset.\n This uses the special metadata \"evaluator_type\" associated with each builtin dataset.\n For your own dataset, you can simply create an evaluator manually in your\n script and do not have to worry about the hacky if-else logic here.\n \"\"\"\n if output_folder is None:\n output_folder = os.path.join(cfg.OUTPUT_DIR, \"inference\")\n evaluator_list = []\n evaluator_type = MetadataCatalog.get(dataset_name).evaluator_type\n if evaluator_type in [\"sem_seg\", \"coco_panoptic_seg\"]:\n evaluator_list.append(\n SemSegEvaluator(\n dataset_name,\n distributed=True,\n num_classes=cfg.MODEL.SEM_SEG_HEAD.NUM_CLASSES,\n ignore_label=cfg.MODEL.SEM_SEG_HEAD.IGNORE_VALUE,\n output_dir=output_folder,\n )\n )\n if evaluator_type in [\"coco\", \"coco_panoptic_seg\"]:\n evaluator_list.append(COCOEvaluator(dataset_name, cfg, True, output_folder))\n if evaluator_type == \"coco_panoptic_seg\":\n evaluator_list.append(COCOPanopticEvaluator(dataset_name, output_folder))\n if evaluator_type == \"cityscapes\":\n assert (\n torch.cuda.device_count() >= comm.get_rank()\n ), \"CityscapesEvaluator currently do not work with multiple machines.\"\n return CityscapesEvaluator(dataset_name)\n if evaluator_type == \"pascal_voc\":\n return PascalVOCDetectionEvaluator(dataset_name)\n if evaluator_type == \"lvis\":\n return LVISEvaluator(dataset_name, cfg, True, output_folder)\n if len(evaluator_list) == 0:\n raise NotImplementedError(\n \"no Evaluator for the dataset {} with the type {}\".format(\n dataset_name, evaluator_type\n )\n )\n if len(evaluator_list) == 1:\n return evaluator_list[0]\n return DatasetEvaluators(evaluator_list)\n\n @classmethod\n def test_with_TTA(cls, cfg, model):\n logger = logging.getLogger(\"detectron2.trainer\")\n # In the end of training, run an evaluation with TTA\n # Only support some R-CNN models.\n logger.info(\"Running inference with test-time augmentation ...\")\n model = GeneralizedRCNNWithTTA(cfg, model)\n evaluators = [\n cls.build_evaluator(\n cfg, name, output_folder=os.path.join(cfg.OUTPUT_DIR, \"inference_TTA\")\n )\n for name in cfg.DATASETS.TEST\n ]\n res = cls.test(cfg, model, evaluators)\n res = OrderedDict({k + \"_TTA\": v for k, v in res.items()})\n return res\n\n\n\n\ndef get_parser():\n parser = argparse.ArgumentParser(description=\"ZeroWaste Detectron2 ML Training models\")\n parser.add_argument('--data-folder', type=str, dest='data_folder', help='data folder mounting point')\n parser.add_argument('--img-folder', type=str, dest='img_folder', help='data folder mounting point')\n parser.add_argument('--masks-folder', type=str, dest='masks_folder', help='data folder mounting point')\n parser.add_argument('--output-folder', type=str, dest='output_folder', help='data folder mounting point')\n parser.add_argument('--config-file', type=str, dest='config_file', help='training configuraiton ad parameters')\n parser.add_argument('--num-gpus', type=int, default=1, dest='num_gpus', help='number of gpus *per machine')\n parser.add_argument(\"--num-machines\", type=int, default=0,dest='num_machines', help=\"total number of machines\")\n parser.add_argument(\n \"--confidence-threshold\",\n type=float,\n default=0.9,\n help=\"Minimum score for instance predictions to be shown\",\n )\n parser.add_argument(\n \"--opts\",\n help=\"Modify config options using the command-line 'KEY VALUE' pairs\",\n default=[],\n nargs=argparse.REMAINDER,\n )\n return parser\n\n\n\ndef setup_cfg(args):\n # to improve check out - https://github.com/Julienbeaulieu/iMaterialist2020-Image-Segmentation-on-Detectron2/blob/master/imaterialist/config.py\n # load config from file and command-line arguments\n cfg = get_cfg()\n cfg.merge_from_file(args.config_file)\n cfg.merge_from_list(args.opts)\n MNT_OUTPUT_PATH = os.path.join(args.output_folder, cfg.OUTPUT_DIR)\n cfg.OUTPUT_DIR = MNT_OUTPUT_PATH\n cfg.freeze()\n\n os.makedirs(cfg.OUTPUT_DIR, exist_ok=True)\n default_setup(cfg, args)\n return cfg\n\n\ndef main(args):\n cfg = setup_cfg(args)\n\n if args.eval_only:\n model = Trainer.build_model(cfg)\n AdetCheckpointer(model, save_dir=cfg.OUTPUT_DIR).resume_or_load(\n cfg.MODEL.WEIGHTS, resume=args.resume\n )\n evaluators = [\n Trainer.build_evaluator(cfg, name)\n for name in cfg.DATASETS.TEST\n ]\n res = Trainer.test(cfg, model, evaluators)\n if comm.is_main_process():\n verify_results(cfg, res)\n if cfg.TEST.AUG.ENABLED:\n res.update(Trainer.test_with_TTA(cfg, model))\n return res\n\n \"\"\"\n If you'd like to do anything fancier than the standard training logic,\n consider writing your own training loop or subclassing the trainer.\n \"\"\"\n trainer = Trainer(cfg)\n trainer.resume_or_load(resume=args.resume)\n if cfg.TEST.AUG.ENABLED:\n trainer.register_hooks(\n [hooks.EvalHook(0, lambda: trainer.test_with_TTA(cfg, trainer.model))]\n )\n return trainer.train()\n\n\nif __name__ == \"__main__\":\n #mp.set_start_method(\"spawn\", force=True) # multi processing - https://github.com/roym899/abandoned_bag_detection/blob/master/demo.py\n #args = default_argument_parser().parse_args() # original - https://github.com/bongjoonhyun/fcos/blob/master/EE898_PA1_2020_rev2/skeleton/train_net.py\n args = get_parser().parse_args()\n\n # Register Custom Dataset\n MASKS_PATHS = args.masks_folder\n IMG_PATHS = args.img_folder\n \n TRAIN_PATH = os.path.join(MASKS_PATHS, 'ds2_3c_train_coco_instances.json')\n VAL_PATH = os.path.join(MASKS_PATHS, 'ds2_3c_val_coco_instances.json')\n TEST_PATH = os.path.join(MASKS_PATHS, 'ds2_3c_test_coco_instances.json')\n\n register_coco_instances(f\"custom_dataset_train\", {},TRAIN_PATH , IMG_PATHS)\n register_coco_instances(f\"custom_dataset_val\", {}, VAL_PATH, IMG_PATHS)\n register_coco_instances(f\"custom_dataset_test\", {}, TEST_PATH, IMG_PATHS)\n\n \n #setup_logger(name=\"fvcore\")\n #logger = setup_logger()\n #logger.info(\"Arguments: \" + str(args))\n # default_argument_parser().parse_args()\n \n print(\"Command Line Args:\", args)\n args.eval_only = False\n args.resume = False\n launch(\n main,\n args.num_gpus,\n num_machines=1,\n #machine_rank=args.machine_rank,\n machine_rank=0,\n #dist_url=args.dist_url,'tcp://127.0.0.1:50153'\n dist_url='tcp://127.0.0.1:49152',\n args=(args,),\n )\n"
] | [
[
"sklearn.model_selection.train_test_split"
],
[
"torch.cuda.device_count"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
bobrokerson/libraries | [
"996509d341af7108a24053eb88431ec6afbb0f25"
] | [
"assignment/min_nonsmooth_fun.py"
] | [
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jan 21 15:36:06 2022\n\n@author: bobrokerson\n\"\"\"\n# part of code from task #1\n\nfrom math import sin, exp\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef func(x):\n return sin(x / 5.) * exp(x / 10.) + 5. * exp(-x/ 2.)\n\n\nxarr = np.arange(1., 31.)\nprint(xarr)\nprint(\"x:\", xarr.shape)\nyarr = np.array([func(x) for x in xarr])\nprint(yarr)\nprint(\"y:\", yarr.shape)\n\nplt.plot(xarr, yarr)\nplt.grid(True)\nplt.axis([0, 30, -15, 5])\nplt.show()\n\n\n# 1.Теперь рассмотрим функцию h(x) = int(f(x)) на том же отрезке [1, 30], т.е. теперь каждое значение f(x) приводится к типу int и функция принимает только целые значения.\n# 2.Такая функция будет негладкой и даже разрывной, а ее график будет иметь ступенчатый вид. Убедитесь в этом, построив график h(x) с помощью matplotlib.\n# 3.Попробуйте найти минимум функции h(x) с помощью BFGS, взяв в качестве начального приближения x=30. Получившееся значение функции – ваш первый ответ в этой задаче.\n# 4.Теперь попробуйте найти минимум h(x) на отрезке [1, 30] с помощью дифференциальной эволюции. Значение функции h(x) в точке минимума – это ваш второй ответ в этом задании. Запишите его через пробел после предыдущего.\n# 5.Обратите внимание на то, что полученные ответы различаются. Это ожидаемый результат, ведь BFGS использует градиент (в одномерном случае – производную) и явно не пригоден для минимизации рассмотренной нами разрывной функции. Попробуйте понять, почему минимум, найденный BFGS, именно такой (возможно в этом вам поможет выбор разных начальных приближений).\n# 6.Выполнив это задание, вы увидели на практике, чем поиск минимума функции отличается от глобальной оптимизации, и когда может быть полезно применить вместо градиентного метода оптимизации метод, не использующий градиент. Кроме того, вы попрактиковались в использовании библиотеки SciPy для решения оптимизационных задач, и теперь знаете, насколько это просто и удобно.\n\nfrom scipy.optimize import minimize\nfrom scipy.optimize import differential_evolution\n\ndef funcnew(x): \n return int(func(x))\n\nxarrnew = np.arange(1., 31., 0.01)\nprint(xarrnew)\nprint(\"x:\", xarrnew.shape)\nyarrnew = np.array([funcnew(x) for x in xarrnew])\nprint(yarrnew)\nprint(\"y:\", yarrnew.shape)\n\n# create plot\nplt.plot(xarrnew, yarrnew)\nplt.grid(True)\nplt.axis([0, 30, -15, 5])\nplt.show()\n\n\nminFuncnewVal1 = minimize(funcnew, 30, method = 'BFGS')\nprint(\"Min f(x) BFGS method: \", round(minFuncnewVal1.fun, 3), \"for x = \", minFuncnewVal1.x)\nprint(\"Number: \", minFuncnewVal1.nit)\n\nminValR2 = np.zeros( (2) )\nminValR2 [0] = round(minFuncnewVal1.fun, 2)\nprint(minValR2)\n\n# searching min h(x)\n\nbounds = [(1, 30)]\nminFuncnewVal2 = differential_evolution(funcnew, bounds)\nprint(\"Min f(x) BFGS method: \", round(minFuncnewVal2.fun, 3), \"for x = \", minFuncnewVal2.x)\nprint(\"Number: \", minFuncnewVal2.nit)\n\nminValR2[1] = round(minFuncnewVal2.fun, 2)\nprint (minValR2)\n\nwith open(\"docvalue3.txt\", \"w\") as file:\n for item in minValR2:\n file.write(str(item) + ' ')\n S\n"
] | [
[
"scipy.optimize.differential_evolution",
"numpy.arange",
"matplotlib.pyplot.plot",
"scipy.optimize.minimize",
"matplotlib.pyplot.grid",
"matplotlib.pyplot.axis",
"matplotlib.pyplot.show",
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"1.6",
"1.10",
"0.15",
"1.4",
"1.3",
"1.9",
"0.19",
"1.5",
"0.18",
"1.2",
"1.7",
"1.0",
"0.17",
"0.16",
"1.8"
],
"tensorflow": []
}
] |
Poezedoez/NearestNeighBERT-Faiss | [
"802c9528105295abe28be8624c7582a3c0f68835"
] | [
"nearest_neighbert/evaluate.py"
] | [
"from sklearn.metrics import precision_recall_fscore_support as prfs\nimport numpy as np\nimport json\nimport argparse\nfrom typing import List, Tuple, Dict\nimport sys\n\n# From spert.evaluator class\n# https://github.com/markus-eberts/spert/blob/master/spert/evaluator.py\n\ndef _get_row(data, label):\n row = [label]\n for i in range(len(data) - 1):\n row.append(\"%.2f\" % (data[i] * 100))\n row.append(data[3])\n return tuple(row)\n\ndef _print_results(per_type: List, micro: List, macro: List, types: List):\n columns = ('type', 'precision', 'recall', 'f1-score', 'support')\n\n row_fmt = \"%20s\" + (\" %12s\" * (len(columns) - 1))\n results = [row_fmt % columns, '\\n']\n\n metrics_per_type = []\n for i, t in enumerate(types):\n metrics = []\n for j in range(len(per_type)):\n metrics.append(per_type[j][i])\n metrics_per_type.append(metrics)\n\n for m, t in zip(metrics_per_type, types):\n results.append(row_fmt % _get_row(m, t))\n results.append('\\n')\n\n results.append('\\n')\n\n # micro\n results.append(row_fmt % _get_row(micro, 'micro'))\n results.append('\\n')\n\n # macro\n results.append(row_fmt % _get_row(macro, 'macro'))\n\n results_str = ''.join(results)\n print(results_str)\n\ndef _compute_metrics(gt_all, pred_all, types, print_results: bool = False):\n labels = [t for t in types]\n per_type = prfs(gt_all, pred_all, labels=labels, average=None)\n micro = prfs(gt_all, pred_all, labels=labels, average='micro')[:-1]\n macro = prfs(gt_all, pred_all, labels=labels, average='macro')[:-1]\n total_support = sum(per_type[-1])\n\n if print_results:\n _print_results(per_type, list(micro) + [total_support], list(macro) + [total_support], types)\n\n return [m * 100 for m in micro + macro]\n\n## Tuple = (start, end, entity_type)\n\ndef _score(gt: List[List[Tuple]], pred: List[List[Tuple]], print_results: bool = False):\n assert len(gt) == len(pred)\n\n gt_flat = []\n pred_flat = []\n types = set()\n\n for (sample_gt, sample_pred) in zip(gt, pred):\n union = set()\n union.update(sample_gt)\n union.update(sample_pred)\n\n for s in union:\n if s in sample_gt:\n t = s[2]\n gt_flat.append(t)\n types.add(t)\n else:\n gt_flat.append(\"0\")\n\n if s in sample_pred:\n t = s[2]\n pred_flat.append(t)\n types.add(t)\n else:\n pred_flat.append(\"0\")\n metrics = _compute_metrics(gt_flat, pred_flat, types, print_results)\n\n return metrics\n\ndef _convert_span_tuples(sequence):\n span_tuples = []\n entities = sequence[\"entities\"]\n for span in entities:\n tuple_ = (span[\"start\"], span[\"end\"], span[\"type\"])\n span_tuples.append(tuple_)\n \n return span_tuples\n\ndef _convert_token_tuples(sequence):\n token_tuples = []\n entities = sequence[\"entities\"]\n string_tokens = sequence[\"tokens\"]\n for span in entities:\n span_range = range(span[\"start\"], span[\"end\"])\n for index in span_range:\n tuple_ = (index, index+1, span[\"type\"])\n token_tuples.append(tuple_)\n \n return token_tuples\n\ndef evaluate(gt_path, pred_path, tokenizer, print_results=True):\n with open(gt_path, 'r', encoding='utf-8') as f:\n gt_dataset = json.load(f)\n\n with open(pred_path, 'r', encoding='utf-8') as f:\n pred_dataset = json.load(f)\n\n gt_spans = []\n pred_spans = []\n gt_tokens = []\n pred_tokens = []\n\n for gt_sequence, pred_sequence in zip(gt_dataset, pred_dataset):\n gt_spans.append(_convert_span_tuples(gt_sequence))\n pred_spans.append(_convert_span_tuples(pred_sequence))\n gt_tokens.append(_convert_token_tuples(gt_sequence))\n pred_tokens.append(_convert_token_tuples(pred_sequence))\n \n \n print(\"\")\n print(\"--- Entities (named entity recognition (NER)) ---\")\n print(\"An entity span is considered correct if the entity type and span start/end is predicted correctly\")\n ner_span_eval = _score(gt_spans, pred_spans, print_results=print_results)[:3]\n print(\"\")\n print(\"An entity token is considered correct if the entity type is predicted correctly\")\n ner_token_eval = _score(gt_tokens, pred_tokens, print_results=print_results)[:3]\n print(\"\")\n\n return ner_span_eval, ner_token_eval\n\n\ndef compare_datasets(gt_path, pred_path, output_path=None):\n with open(gt_path, 'r', encoding='utf-8') as f:\n gt_dataset = json.load(f)\n\n with open(pred_path, 'r', encoding='utf-8') as f:\n pred_dataset = json.load(f)\n\n assert len(gt_dataset)==len(pred_dataset)\n\n file_object = open(output_path, 'w', encoding='utf-8') if output_path else sys.stdout\n for gt_sentence, pred_sentence in zip(gt_dataset, pred_dataset):\n gt_tokens = gt_sentence[\"tokens\"]\n print(\"|{}| {} \\n\".format(gt_sentence[\"orig_id\"], \" \".join(gt_tokens)), file=file_object)\n for entity in gt_sentence[\"entities\"]:\n entity_tokens = gt_tokens[entity[\"start\"]:entity[\"end\"]]\n line = \"[gold] \\t {} \\t {}\".format(\" \".join(entity_tokens), entity[\"type\"])\n print(line, file=file_object)\n pred_tokens = pred_sentence[\"tokens\"]\n for entity in pred_sentence[\"entities\"]:\n entity_tokens = pred_tokens[entity[\"start\"]:entity[\"end\"]]\n line = \"[pred] \\t {} \\t {}\".format(\" \".join(entity_tokens), entity[\"type\"])\n print(line, file=file_object)\n print('-'*50, file=file_object)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Evaluate spert json formatted dataset')\n parser.add_argument('gt_path', type=str, help='path to the ground truth dataset.json file')\n parser.add_argument('pred_path', type=str, help='path to the predicted dataset.json file')\n args = parser.parse_args()\n evaluate(args.gt_path, args.pred_path)\n "
] | [
[
"sklearn.metrics.precision_recall_fscore_support"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
eternagame/KaggleOpenVaccine | [
"de252988b92dc2c673a80347deb8827a12aa2ad8"
] | [
"data/mRNA_233x_data/reformat_kazuki2.py"
] | [
"import numpy as np\nimport pandas as pd\nimport gzip\n\ninput_file = 'predictions/2nd-place-233-seq.csv'\nnickname='kazuki2'\n\ndf = pd.read_csv('../233x_sequences_degdata_081120.csv')\ndf1 = pd.read_csv(input_file)\n\ndf1['ID'] = [int(x.split('_')[0]) for x in df1['id_seqpos']]\ndf1['seqpos'] = [int(x.split('_')[1]) for x in df1['id_seqpos']]\n\ndf1['startpos'] = df['startpos']\ndf1['endpos'] = df['endpos']\n\nfor data_type in ['reactivity', 'deg_Mg_pH10', 'deg_pH10', 'deg_Mg_50C','deg_50C']:\n output_array = np.ones([233,1588])*np.NaN\n\n for _, row in df1.iterrows():\n output_array[row['ID'],row['seqpos']] = row[data_type]\n\n np.savetxt('formatted_predictions/%s_%s_flat_FULL_233x.csv' % (nickname, data_type),output_array, delimiter=',')\n\n for i, row in df1.iterrows():\n if not np.isnan(row['startpos']):\n output_array[i, :int(row['startpos'])] = np.NaN\n output_array[i, int(row['endpos']):] = np.NaN\n \n np.savetxt('formatted_predictions/%s_%s_flat_PCR_233x.csv' % (nickname, data_type),output_array, delimiter=',')\n"
] | [
[
"numpy.savetxt",
"numpy.isnan",
"pandas.read_csv",
"numpy.ones"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
karl-zhao/benchmarking-gnns-pyg | [
"23d2c823f16ead554b22ff31c41d5bd8074b133e",
"23d2c823f16ead554b22ff31c41d5bd8074b133e"
] | [
"nets/SBMs_node_classification/mo_net.py",
"main_ogb_node_classification.py"
] | [
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n# from torch_scatter import scatter_add\n# from num_nodes import maybe_num_nodes\nimport dgl\nfrom torch_geometric.nn.conv import MessagePassing\nimport numpy as np\nimport torch.nn as nn\nfrom torch import Tensor\n# from torch_geometric.utils import degree\nfrom torch_scatter import scatter_add\n\n\"\"\"\n GMM: Gaussian Mixture Model Convolution layer\n Geometric Deep Learning on Graphs and Manifolds using Mixture Model CNNs (Federico Monti et al., CVPR 2017)\n https://arxiv.org/pdf/1611.08402.pdf\n\"\"\"\n\nfrom layers.gmm_layer import GMMLayer\nfrom layers.mlp_readout_layer import MLPReadout\nfrom torch_geometric.nn import GMMConv\n\nclass MoNet(nn.Module):\n def __init__(self, net_params):\n super().__init__()\n self.name = 'MoNet'\n in_dim = net_params['in_dim']\n hidden_dim = net_params['hidden_dim']\n out_dim = net_params['out_dim']\n kernel = net_params['kernel'] # for MoNet\n dim = net_params['pseudo_dim_MoNet'] # for MoNet\n n_classes = net_params['n_classes']\n dropout = net_params['dropout']\n n_layers = net_params['L']\n self.readout = net_params['readout'] \n batch_norm = net_params['batch_norm']\n residual = net_params['residual'] \n self.device = net_params['device']\n self.n_classes = n_classes\n \n aggr_type = \"sum\" # default for MoNet\n \n self.embedding_h = nn.Embedding(in_dim, hidden_dim)\n \n self.layers = nn.ModuleList()\n self.pseudo_proj = nn.ModuleList()\n\n # Hidden layer\n for _ in range(n_layers-1):\n self.layers.append(GMMLayer(hidden_dim, hidden_dim, dim, kernel, aggr_type,\n dropout, batch_norm, residual))\n self.pseudo_proj.append(nn.Sequential(nn.Linear(2, dim), nn.Tanh()))\n \n # Output layer\n self.layers.append(GMMLayer(hidden_dim, out_dim, dim, kernel, aggr_type,\n dropout, batch_norm, residual))\n self.pseudo_proj.append(nn.Sequential(nn.Linear(2, dim), nn.Tanh()))\n \n self.MLP_layer = MLPReadout(out_dim, n_classes)\n\n def forward(self, g, h, e):\n h = self.embedding_h(h)\n\n # computing the 'pseudo' named tensor which depends on node degrees\n g.ndata['deg'] = g.in_degrees()\n g.apply_edges(self.compute_pseudo)\n pseudo = g.edata['pseudo'].to(self.device).float()\n \n for i in range(len(self.layers)):\n h = self.layers[i](g, h, self.pseudo_proj[i](pseudo))\n\n return self.MLP_layer(h)\n \n def compute_pseudo(self, edges):\n # compute pseudo edge features for MoNet\n # to avoid zero division in case in_degree is 0, we add constant '1' in all node degrees denoting self-loop\n # srcs = 1/np.sqrt((edges.src['deg']+1).cpu())\n # dsts = 1/np.sqrt((edges.src['deg']+1).cpu())\n srcs = 1 / (edges.src['deg'] + 1).float().sqrt()\n dsts = 1 / (edges.src['deg'] + 1).float().sqrt()\n pseudo = torch.cat((srcs.unsqueeze(-1), dsts.unsqueeze(-1)), dim=1)\n return {'pseudo': pseudo}\n \n def loss(self, pred, label):\n\n # calculating label weights for weighted loss computation\n V = label.size(0)\n label_count = torch.bincount(label)\n label_count = label_count[label_count.nonzero()].squeeze()\n cluster_sizes = torch.zeros(self.n_classes).long().to(self.device)\n cluster_sizes[torch.unique(label)] = label_count\n weight = (V - cluster_sizes).float() / V\n weight *= (cluster_sizes>0).float()\n \n # weighted cross-entropy for unbalanced classes\n criterion = nn.CrossEntropyLoss(weight=weight)\n loss = criterion(pred, label)\n\n return loss\n\n\"\"\"\n GMM: Gaussian Mixture Model Convolution layer\n Geometric Deep Learning on Graphs and Manifolds using Mixture Model CNNs (Federico Monti et al., CVPR 2017)\n https://arxiv.org/pdf/1611.08402.pdf\n\"\"\"\nclass MoNetNet_pyg(MessagePassing):\n def __init__(self, net_params):\n super().__init__()\n self.name = 'MoNet'\n in_dim = net_params['in_dim']\n hidden_dim = net_params['hidden_dim']\n out_dim = net_params['out_dim']\n kernel = net_params['kernel'] # for MoNet\n dim = net_params['pseudo_dim_MoNet'] # for MoNet\n n_classes = net_params['n_classes']\n self.dropout = net_params['dropout']\n self.n_layers = net_params['L']\n self.readout = net_params['readout']\n self.batch_norm = net_params['batch_norm']\n self.residual = net_params['residual']\n self.device = net_params['device']\n self.n_classes = n_classes\n self.dim = dim\n # aggr_type = \"sum\" # default for MoNet\n aggr_type = \"mean\"\n\n self.embedding_h = nn.Embedding(in_dim, hidden_dim)\n self.layers = nn.ModuleList()\n self.pseudo_proj = nn.ModuleList()\n self.batchnorm_h = nn.ModuleList()\n # Hidden layer\n for _ in range(self.n_layers - 1):\n self.layers.append(GMMConv(hidden_dim, hidden_dim, dim, kernel, separate_gaussians = False ,aggr = aggr_type,\n root_weight = True, bias = True))\n if self.batch_norm:\n self.batchnorm_h.append(nn.BatchNorm1d(hidden_dim))\n self.pseudo_proj.append(nn.Sequential(nn.Linear(2, dim), nn.Tanh()))\n # Output layer\n self.layers.append(GMMConv(hidden_dim, out_dim, dim, kernel, separate_gaussians = False ,aggr = aggr_type,\n root_weight = True, bias = True))\n if self.batch_norm:\n self.batchnorm_h.append(nn.BatchNorm1d(out_dim))\n self.pseudo_proj.append(nn.Sequential(nn.Linear(2, dim), nn.Tanh()))\n self.MLP_layer = MLPReadout(out_dim, n_classes)\n # to do\n\n def forward(self, h, edge_index, e):\n h = self.embedding_h(h)\n edge_weight = torch.ones((edge_index.size(1),),\n device = edge_index.device)\n row, col = edge_index[0], edge_index[1]\n deg = scatter_add(edge_weight, row, dim=0, dim_size=h.size(0))\n deg_inv_sqrt = deg.pow_(-0.5)\n deg_inv_sqrt.masked_fill_(deg_inv_sqrt == float('inf'), 0)\n pseudo = torch.cat((deg_inv_sqrt[row].unsqueeze(-1), deg_inv_sqrt[col].unsqueeze(-1)), dim=1)\n\n for i in range(self.n_layers):\n h_in = h\n h = self.layers[i](h, edge_index, self.pseudo_proj[i](pseudo))\n if self.batch_norm:\n h = self.batchnorm_h[i](h) # batch normalization\n h = F.relu(h) # non-linear activation\n if self.residual:\n h = h_in + h # residual connection\n h = F.dropout(h, self.dropout, training=self.training)\n\n return self.MLP_layer(h)\n\n\n def loss(self, pred, label):\n\n # calculating label weights for weighted loss computation\n V = label.size(0)\n label_count = torch.bincount(label)\n label_count = label_count[label_count.nonzero()].squeeze()\n cluster_sizes = torch.zeros(self.n_classes).long().to(self.device)\n cluster_sizes[torch.unique(label)] = label_count\n weight = (V - cluster_sizes).float() / V\n weight *= (cluster_sizes > 0).float()\n\n # weighted cross-entropy for unbalanced classes\n criterion = nn.CrossEntropyLoss(weight=weight)\n loss = criterion(pred, label)\n\n return loss",
"\n\n\n\n\n\"\"\"\n IMPORTING LIBS\n\"\"\"\nimport dgl\n\nimport numpy as np\nimport os\nimport socket\nimport time\nimport random\nimport glob\nimport argparse, json\nimport pickle\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nimport torch.optim as optim\nfrom torch.utils.data import DataLoader\nfrom torch_geometric.data import DataLoader as DataLoaderpyg\nfrom tensorboardX import SummaryWriter\nfrom tqdm import tqdm\nimport torch_geometric.transforms as T\nfrom ogb.nodeproppred import Evaluator\nfrom torch_geometric.data import RandomNodeSampler\n\nclass DotDict(dict):\n def __init__(self, **kwds):\n self.update(kwds)\n self.__dict__ = self\n\n\"\"\"\n IMPORTING CUSTOM MODULES/METHODS\n\"\"\"\n\nfrom nets.ogb_node_classification.load_net import gnn_model # import GNNs\nfrom data.data import LoadData # import dataset\n\n\n\n\n\"\"\"\n GPU Setup\n\"\"\"\ndef gpu_setup(use_gpu, gpu_id):\n os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = str(gpu_id)\n if torch.cuda.is_available() and use_gpu:\n print('cuda available with GPU:',torch.cuda.get_device_name(gpu_id))\n device = torch.device(\"cuda:\"+ str(gpu_id))\n else:\n print('cuda not available')\n device = torch.device(\"cpu\")\n return device\n\n\n\n\n\n\n\n\n\n\n\"\"\"\n VIEWING MODEL CONFIG AND PARAMS\n\"\"\"\ndef view_model_param(MODEL_NAME, net_params):\n model = gnn_model(MODEL_NAME, net_params)\n total_param = 0\n print(\"MODEL DETAILS:\\n\")\n print(model)\n for param in model.parameters():\n # print(param.data.size())\n total_param += np.prod(list(param.data.size()))\n print('MODEL/Total parameters:', MODEL_NAME, total_param)\n return total_param\n\n\n\"\"\"\n TRAINING CODE\n\"\"\"\n\ndef train_val_pipeline(MODEL_NAME, dataset, params, net_params, dirs):\n \n start0 = time.time()\n per_epoch_time = []\n \n DATASET_NAME = dataset.name\n \n if MODEL_NAME in ['GCN', 'GAT']:\n if net_params['self_loop']:\n print(\"[!] Adding graph self-loops for GCN/GAT models (central node trick).\")\n dataset._add_self_loops()\n if not net_params['edge_feat']:\n edge_feat_dim = 1\n if DATASET_NAME == 'ogbn-mag':\n dataset.dataset.edge_attr = torch.ones(dataset.dataset[0].num_edges, edge_feat_dim).type(torch.float32)\n else:\n dataset.dataset.data.edge_attr = torch.ones(dataset.dataset[0].num_edges, edge_feat_dim).type(torch.float32)\n\n if net_params['pos_enc']:\n print(\"[!] Adding graph positional encoding.\")\n dataset._add_positional_encodings(net_params['pos_enc_dim'],DATASET_NAME)\n print('Time PE:',time.time()-start0)\n device = net_params['device']\n if DATASET_NAME == 'ogbn-mag':\n dataset.split_idx['train'], dataset.split_idx['valid'], dataset.split_idx['test'] = dataset.split_idx['train']['paper'],\\\n dataset.split_idx['valid']['paper'], \\\n dataset.split_idx['test']['paper']\n # else:\n # dataset.split_idx['train'], dataset.split_idx['valid'], dataset.split_idx['test'] = dataset.split_idx['train'].to(device), \\\n # dataset.split_idx['valid'].to(device), \\\n # dataset.split_idx['test'].to(device)\n\n # transform = T.ToSparseTensor() To do to save memory\n # self.train.graph_lists = [positional_encoding(g, pos_enc_dim, framework='pyg') for _, g in enumerate(dataset.train)]\n root_log_dir, root_ckpt_dir, write_file_name, write_config_file = dirs\n\n \n # Write network and optimization hyper-parameters in folder config/\n with open(write_config_file + '.txt', 'w') as f:\n f.write(\"\"\"Dataset: {},\\nModel: {}\\n\\nparams={}\\n\\nnet_params={}\\n\\n\\nTotal Parameters: {}\\n\\n\"\"\" .format(DATASET_NAME, MODEL_NAME, params, net_params, net_params['total_param']))\n \n log_dir = os.path.join(root_log_dir, \"RUN_\" + str(0))\n writer = SummaryWriter(log_dir=log_dir)\n\n # setting seeds\n random.seed(params['seed'])\n np.random.seed(params['seed'])\n torch.manual_seed(params['seed'])\n if device.type == 'cuda':\n torch.cuda.manual_seed(params['seed'])\n \n print(\"Training Graphs: \", dataset.split_idx['train'].size(0))\n print(\"Validation Graphs: \", dataset.split_idx['valid'].size(0))\n print(\"Test Graphs: \", dataset.split_idx['test'].size(0))\n print(\"Number of Classes: \", net_params['n_classes'])\n\n model = gnn_model(MODEL_NAME, net_params)\n model = model.to(device)\n\n optimizer = optim.Adam(model.parameters(), lr=params['init_lr'], weight_decay=params['weight_decay'])\n scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='min',\n factor=params['lr_reduce_factor'],\n patience=params['lr_schedule_patience'],\n verbose=True)\n evaluator = Evaluator(name = DATASET_NAME)\n epoch_train_losses, epoch_val_losses = [], []\n epoch_train_accs, epoch_val_accs = [], [] \n\n # import train functions for all other GCNs\n if DATASET_NAME == 'ogbn-mag' or DATASET_NAME == 'ogbn-products':\n from train.train_ogb_node_classification import train_epoch as train_epoch, evaluate_network as evaluate_network\n elif DATASET_NAME == 'ogbn-proteins':\n from train.train_ogb_node_classification import train_epoch_proteins as train_epoch, evaluate_network_proteins as evaluate_network\n data = dataset.dataset[0]\n # Set split indices to masks.\n for split in ['train', 'valid', 'test']:\n mask = torch.zeros(data.num_nodes, dtype=torch.bool)\n mask[dataset.split_idx[split]] = True\n data[f'{split}_mask'] = mask\n num_parts = 5 if DATASET_NAME == 'ogbn-mag' else 40\n train_loader = RandomNodeSampler(data, num_parts=num_parts, shuffle=True,\n num_workers=0)\n test_loader = RandomNodeSampler(data, num_parts=5, num_workers=0)\n # At any point you can hit Ctrl + C to break out of training early.\n try:\n with tqdm(range(params['epochs']),ncols= 0) as t:\n for epoch in t:\n\n t.set_description('Epoch %d' % epoch)\n\n start = time.time()\n\n\n # for all other models common train function\n epoch_train_loss = train_epoch(model, optimizer, device, train_loader, epoch)\n\n epoch_train_acc, epoch_val_acc, epoch_test_acc, epoch_val_loss = evaluate_network(model, device, test_loader, evaluator, epoch)\n # _, epoch_test_acc = evaluate_network(model, device, test_loader, epoch)\n \n epoch_train_losses.append(epoch_train_loss)\n epoch_val_losses.append(epoch_val_loss)\n epoch_train_accs.append(epoch_train_acc)\n epoch_val_accs.append(epoch_val_acc)\n\n writer.add_scalar('train/_loss', epoch_train_loss, epoch)\n writer.add_scalar('val/_loss', epoch_val_loss, epoch)\n writer.add_scalar('train/_acc', epoch_train_acc, epoch)\n writer.add_scalar('val/_acc', epoch_val_acc, epoch)\n writer.add_scalar('test/_acc', epoch_test_acc, epoch)\n writer.add_scalar('learning_rate', optimizer.param_groups[0]['lr'], epoch)\n\n t.set_postfix(time=time.time()-start, lr=optimizer.param_groups[0]['lr'],\n train_loss=epoch_train_loss, val_loss=epoch_val_loss,\n train_acc=epoch_train_acc, val_acc=epoch_val_acc,\n test_acc=epoch_test_acc)\n\n per_epoch_time.append(time.time()-start)\n\n # Saving checkpoint\n ckpt_dir = os.path.join(root_ckpt_dir, \"RUN_\")\n if not os.path.exists(ckpt_dir):\n os.makedirs(ckpt_dir)\n # the function to save the checkpoint\n # torch.save(model.state_dict(), '{}.pkl'.format(ckpt_dir + \"/epoch_\" + str(epoch)))\n\n files = glob.glob(ckpt_dir + '/*.pkl')\n for file in files:\n epoch_nb = file.split('_')[-1]\n epoch_nb = int(epoch_nb.split('.')[0])\n if epoch_nb < epoch-1:\n os.remove(file)\n\n scheduler.step(epoch_val_loss)\n # it used to test the scripts\n # if epoch == 1:\n # break\n\n if optimizer.param_groups[0]['lr'] < params['min_lr']:\n print(\"\\n!! LR SMALLER OR EQUAL TO MIN LR THRESHOLD.\")\n break\n \n # Stop training after params['max_time'] hours\n if time.time()-start0 > params['max_time']*3600:\n print('-' * 89)\n print(\"Max_time for training elapsed {:.2f} hours, so stopping\".format(params['max_time']))\n break\n \n except KeyboardInterrupt:\n print('-' * 89)\n print('Exiting from training early because of KeyboardInterrupt')\n\n train_acc, val_acc, test_acc, _ = evaluate_network(model, device, test_loader, evaluator, epoch)\n train_acc, val_acc, test_acc = 100 * train_acc, 100 * val_acc, 100 * test_acc\n print(\"Test Accuracy: {:.4f}\".format(test_acc))\n print(\"Val Accuracy: {:.4f}\".format(val_acc))\n print(\"Train Accuracy: {:.4f}\".format(train_acc))\n print(\"Convergence Time (Epochs): {:.4f}\".format(epoch))\n print(\"TOTAL TIME TAKEN: {:.4f}s\".format(time.time()-start0))\n print(\"AVG TIME PER EPOCH: {:.4f}s\".format(np.mean(per_epoch_time)))\n\n writer.close()\n\n \"\"\"\n Write the results in out_dir/results folder\n \"\"\"\n with open(write_file_name + '.txt', 'w') as f:\n f.write(\"\"\"Dataset: {},\\nModel: {}\\n\\nparams={}\\n\\nnet_params={}\\n\\n{}\\n\\nTotal Parameters: {}\\n\\n\n FINAL RESULTS\\nTEST ACCURACY: {:.4f}\\nval ACCURACY: {:.4f}\\nTRAIN ACCURACY: {:.4f}\\n\\n\n Convergence Time (Epochs): {:.4f}\\nTotal Time Taken: {:.4f} hrs\\nAverage Time Per Epoch: {:.4f} s\\n\\n\\n\"\"\"\\\n .format(DATASET_NAME, MODEL_NAME, params, net_params, model, net_params['total_param'],\n test_acc, val_acc,train_acc, epoch, (time.time()-start0)/3600, np.mean(per_epoch_time)))\n\n \n\n\n\n\ndef main(): \n \"\"\"\n USER CONTROLS\n \"\"\"\n \n parser = argparse.ArgumentParser()\n parser.add_argument('--config', help=\"Please give a config.json file with training/model/data/param details\")\n parser.add_argument('--framework', type=str, default= None, help=\"Please give a framework to use\")\n parser.add_argument('--gpu_id', help=\"Please give a value for gpu id\")\n parser.add_argument('--model', help=\"Please give a value for model name\")\n parser.add_argument('--dataset', help=\"Please give a value for dataset name\")\n parser.add_argument('--out_dir', help=\"Please give a value for out_dir\")\n parser.add_argument('--seed', help=\"Please give a value for seed\")\n parser.add_argument('--epochs', help=\"Please give a value for epochs\")\n parser.add_argument('--batch_size', help=\"Please give a value for batch_size\")\n parser.add_argument('--init_lr', help=\"Please give a value for init_lr\")\n parser.add_argument('--lr_reduce_factor', help=\"Please give a value for lr_reduce_factor\")\n parser.add_argument('--lr_schedule_patience', help=\"Please give a value for lr_schedule_patience\")\n parser.add_argument('--min_lr', help=\"Please give a value for min_lr\")\n parser.add_argument('--weight_decay', help=\"Please give a value for weight_decay\")\n parser.add_argument('--print_epoch_interval', help=\"Please give a value for print_epoch_interval\") \n parser.add_argument('--L', help=\"Please give a value for L\")\n parser.add_argument('--hidden_dim', help=\"Please give a value for hidden_dim\")\n parser.add_argument('--out_dim', help=\"Please give a value for out_dim\")\n parser.add_argument('--residual', help=\"Please give a value for residual\")\n parser.add_argument('--edge_feat', help=\"Please give a value for edge_feat\")\n parser.add_argument('--readout', help=\"Please give a value for readout\")\n parser.add_argument('--kernel', help=\"Please give a value for kernel\")\n parser.add_argument('--n_heads', help=\"Please give a value for n_heads\")\n parser.add_argument('--gated', help=\"Please give a value for gated\")\n parser.add_argument('--in_feat_dropout', help=\"Please give a value for in_feat_dropout\")\n parser.add_argument('--dropout', help=\"Please give a value for dropout\")\n parser.add_argument('--layer_norm', help=\"Please give a value for layer_norm\")\n parser.add_argument('--batch_norm', help=\"Please give a value for batch_norm\")\n parser.add_argument('--sage_aggregator', help=\"Please give a value for sage_aggregator\")\n parser.add_argument('--data_mode', help=\"Please give a value for data_mode\")\n parser.add_argument('--num_pool', help=\"Please give a value for num_pool\")\n parser.add_argument('--gnn_per_block', help=\"Please give a value for gnn_per_block\")\n parser.add_argument('--embedding_dim', help=\"Please give a value for embedding_dim\")\n parser.add_argument('--pool_ratio', help=\"Please give a value for pool_ratio\")\n parser.add_argument('--linkpred', help=\"Please give a value for linkpred\")\n parser.add_argument('--cat', help=\"Please give a value for cat\")\n parser.add_argument('--self_loop', help=\"Please give a value for self_loop\")\n parser.add_argument('--max_time', help=\"Please give a value for max_time\")\n parser.add_argument('--pos_enc_dim', help=\"Please give a value for pos_enc_dim\")\n parser.add_argument('--pos_enc', action='store_true', default=False, help=\"Please give a value for pos_enc\")\n parser.add_argument('--use_node_embedding', action='store_true', default=False)\n args = parser.parse_args()\n with open(args.config) as f:\n config = json.load(f)\n \n # device\n if args.gpu_id is not None:\n config['gpu']['id'] = int(args.gpu_id)\n config['gpu']['use'] = True\n device = gpu_setup(config['gpu']['use'], config['gpu']['id'])\n # model, dataset, out_dir\n if args.model is not None:\n MODEL_NAME = args.model\n else:\n MODEL_NAME = config['model']\n if args.dataset is not None:\n DATASET_NAME = args.dataset\n else:\n DATASET_NAME = config['dataset']\n # parameters\n params = config['params']\n params['framework'] = 'pyg' if MODEL_NAME[-3:] == 'pyg' else 'dgl'\n if args.framework is not None:\n params['framework'] = str(args.framework)\n if args.use_node_embedding is not None:\n params['use_node_embedding'] = True if args.use_node_embedding == True else False\n dataset = LoadData(DATASET_NAME = DATASET_NAME, use_node_embedding = params['use_node_embedding'])\n if args.out_dir is not None:\n out_dir = args.out_dir\n else:\n out_dir = config['out_dir']\n if args.seed is not None:\n params['seed'] = int(args.seed)\n if args.epochs is not None:\n params['epochs'] = int(args.epochs)\n if args.batch_size is not None:\n params['batch_size'] = int(args.batch_size)\n if args.init_lr is not None:\n params['init_lr'] = float(args.init_lr)\n if args.lr_reduce_factor is not None:\n params['lr_reduce_factor'] = float(args.lr_reduce_factor)\n if args.lr_schedule_patience is not None:\n params['lr_schedule_patience'] = int(args.lr_schedule_patience)\n if args.min_lr is not None:\n params['min_lr'] = float(args.min_lr)\n if args.weight_decay is not None:\n params['weight_decay'] = float(args.weight_decay)\n if args.print_epoch_interval is not None:\n params['print_epoch_interval'] = int(args.print_epoch_interval)\n if args.max_time is not None:\n params['max_time'] = float(args.max_time)\n\n # network parameters\n net_params = config['net_params']\n net_params['device'] = device\n net_params['gpu_id'] = config['gpu']['id']\n # net_params['batch_size'] = params['batch_size']\n if args.L is not None:\n net_params['L'] = int(args.L)\n if args.hidden_dim is not None:\n net_params['hidden_dim'] = int(args.hidden_dim)\n if args.out_dim is not None:\n net_params['out_dim'] = int(args.out_dim) \n if args.residual is not None:\n net_params['residual'] = True if args.residual=='True' else False\n if args.edge_feat is not None:\n net_params['edge_feat'] = True if args.edge_feat=='True' else False\n if args.readout is not None:\n net_params['readout'] = args.readout\n if args.kernel is not None:\n net_params['kernel'] = int(args.kernel)\n if args.n_heads is not None:\n net_params['n_heads'] = int(args.n_heads)\n if args.gated is not None:\n net_params['gated'] = True if args.gated=='True' else False\n if args.in_feat_dropout is not None:\n net_params['in_feat_dropout'] = float(args.in_feat_dropout)\n if args.dropout is not None:\n net_params['dropout'] = float(args.dropout)\n if args.layer_norm is not None:\n net_params['layer_norm'] = True if args.layer_norm=='True' else False\n if args.batch_norm is not None:\n net_params['batch_norm'] = True if args.batch_norm=='True' else False\n if args.sage_aggregator is not None:\n net_params['sage_aggregator'] = args.sage_aggregator\n if args.data_mode is not None:\n net_params['data_mode'] = args.data_mode\n if args.num_pool is not None:\n net_params['num_pool'] = int(args.num_pool)\n if args.gnn_per_block is not None:\n net_params['gnn_per_block'] = int(args.gnn_per_block)\n if args.embedding_dim is not None:\n net_params['embedding_dim'] = int(args.embedding_dim)\n if args.pool_ratio is not None:\n net_params['pool_ratio'] = float(args.pool_ratio)\n if args.linkpred is not None:\n net_params['linkpred'] = True if args.linkpred=='True' else False\n if args.cat is not None:\n net_params['cat'] = True if args.cat=='True' else False\n if args.self_loop is not None:\n net_params['self_loop'] = True if args.self_loop=='True' else False\n if args.pos_enc is not None:\n net_params['pos_enc'] = True if args.pos_enc==True else False\n if args.pos_enc_dim is not None:\n net_params['pos_enc_dim'] = int(args.pos_enc_dim)\n\n \n # arxiv 'ogbn-mag'\n net_params['in_dim'] = dataset.dataset[0].x.size(1)\n # dataset.dataset[0]\n # net_params['n_classes'] = torch.unique(dataset.dataset[0].y,dim=0).size(0)\n net_params['n_classes'] = dataset.dataset[0].y.size(1) if DATASET_NAME == 'ogbn-proteins' else torch.unique(dataset.dataset[0].y,dim=0).size(0)\n\n root_log_dir = out_dir + 'logs/' + MODEL_NAME + \"_\" + DATASET_NAME + \"_GPU\" + str(config['gpu']['id']) + \"_\" + time.strftime('%Hh%Mm%Ss_on_%b_%d_%Y')\n root_ckpt_dir = out_dir + 'checkpoints/' + MODEL_NAME + \"_\" + DATASET_NAME + \"_GPU\" + str(config['gpu']['id']) + \"_\" + time.strftime('%Hh%Mm%Ss_on_%b_%d_%Y')\n write_file_name = out_dir + 'results/result_' + MODEL_NAME + \"_\" + DATASET_NAME + \"_GPU\" + str(config['gpu']['id']) + \"_\" + time.strftime('%Hh%Mm%Ss_on_%b_%d_%Y')\n write_config_file = out_dir + 'configs/config_' + MODEL_NAME + \"_\" + DATASET_NAME + \"_GPU\" + str(config['gpu']['id']) + \"_\" + time.strftime('%Hh%Mm%Ss_on_%b_%d_%Y')\n dirs = root_log_dir, root_ckpt_dir, write_file_name, write_config_file\n\n if not os.path.exists(out_dir + 'results'):\n os.makedirs(out_dir + 'results')\n \n if not os.path.exists(out_dir + 'configs'):\n os.makedirs(out_dir + 'configs')\n\n net_params['total_param'] = view_model_param(MODEL_NAME, net_params)\n train_val_pipeline(MODEL_NAME, dataset, params, net_params, dirs)\n\n \n \n \n \n \n \nmain() \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"
] | [
[
"torch.nn.BatchNorm1d",
"torch.nn.CrossEntropyLoss",
"torch.nn.functional.dropout",
"torch.zeros",
"torch.nn.ModuleList",
"torch.nn.Embedding",
"torch.nn.Tanh",
"torch.nn.Linear",
"torch.nn.functional.relu",
"torch.unique",
"torch.bincount"
],
[
"torch.optim.lr_scheduler.ReduceLROnPlateau",
"torch.ones",
"numpy.random.seed",
"torch.cuda.manual_seed",
"torch.zeros",
"torch.manual_seed",
"torch.unique",
"numpy.mean",
"torch.cuda.is_available",
"torch.cuda.get_device_name",
"torch.device"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
teo-milea/federated | [
"ce0707a954a531860eb38864b44d7b748fd62aa7",
"ce0707a954a531860eb38864b44d7b748fd62aa7",
"ce0707a954a531860eb38864b44d7b748fd62aa7",
"ce0707a954a531860eb38864b44d7b748fd62aa7",
"ce0707a954a531860eb38864b44d7b748fd62aa7",
"ce0707a954a531860eb38864b44d7b748fd62aa7",
"ce0707a954a531860eb38864b44d7b748fd62aa7"
] | [
"tensorflow_federated/python/core/impl/execution_contexts/async_execution_context_test.py",
"tensorflow_federated/python/program/tensorboard_release_manager_test.py",
"tensorflow_federated/python/learning/templates/finalizers_test.py",
"tensorflow_federated/python/learning/keras_utils_test.py",
"tensorflow_federated/python/learning/model_examples_test.py",
"tensorflow_federated/python/program/file_release_manager_test.py",
"tensorflow_federated/python/learning/optimizers/adagrad_test.py"
] | [
"# Copyright 2021, The TensorFlow Federated 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\nimport asyncio\nimport numpy as np\nimport tensorflow as tf\n\nfrom tensorflow_federated.python.core.api import computations\nfrom tensorflow_federated.python.core.impl.context_stack import get_context_stack\nfrom tensorflow_federated.python.core.impl.execution_contexts import async_execution_context\nfrom tensorflow_federated.python.core.impl.executors import executor_stacks\nfrom tensorflow_federated.python.core.impl.executors import executors_errors\nfrom tensorflow_federated.python.core.impl.types import computation_types\nfrom tensorflow_federated.python.core.impl.types import placements\n\n\nclass RetryableErrorTest(tf.test.TestCase):\n\n def test_is_retryable_error(self):\n retryable_error = executors_errors.RetryableError()\n self.assertTrue(\n async_execution_context._is_retryable_error(retryable_error))\n self.assertFalse(async_execution_context._is_retryable_error(TypeError()))\n self.assertFalse(async_execution_context._is_retryable_error(1))\n self.assertFalse(async_execution_context._is_retryable_error('a'))\n self.assertFalse(async_execution_context._is_retryable_error(None))\n\n\nclass UnwrapValueTest(tf.test.TestCase):\n\n def test_tensor(self):\n result = async_execution_context._unwrap(tf.constant(1))\n self.assertIsInstance(result, np.int32)\n result = async_execution_context._unwrap(tf.constant([1, 2]))\n self.assertIsInstance(result, np.ndarray)\n self.assertAllEqual(result, [1, 2])\n\n def test_structure_of_tensors(self):\n result = async_execution_context._unwrap([tf.constant(x) for x in range(5)])\n self.assertIsInstance(result, list)\n for x in range(5):\n self.assertIsInstance(result[x], np.int32)\n self.assertEqual(result[x], x)\n\n\nclass AsyncContextInstallationTest(tf.test.TestCase):\n\n def test_install_and_execute_in_context(self):\n factory = executor_stacks.local_executor_factory()\n context = async_execution_context.AsyncExecutionContext(factory)\n\n @computations.tf_computation(tf.int32)\n def add_one(x):\n return x + 1\n\n with get_context_stack.get_context_stack().install(context):\n val_coro = add_one(1)\n self.assertTrue(asyncio.iscoroutine(val_coro))\n self.assertEqual(asyncio.run(val_coro), 2)\n\n def test_install_and_execute_computations_with_different_cardinalities(self):\n factory = executor_stacks.local_executor_factory()\n context = async_execution_context.AsyncExecutionContext(factory)\n\n @computations.federated_computation(\n computation_types.FederatedType(tf.int32, placements.CLIENTS))\n def repackage_arg(x):\n return [x, x]\n\n with get_context_stack.get_context_stack().install(context):\n single_val_coro = repackage_arg([1])\n second_val_coro = repackage_arg([1, 2])\n self.assertTrue(asyncio.iscoroutine(single_val_coro))\n self.assertTrue(asyncio.iscoroutine(second_val_coro))\n self.assertEqual(\n [asyncio.run(single_val_coro),\n asyncio.run(second_val_coro)], [[[1], [1]], [[1, 2], [1, 2]]])\n\n\nif __name__ == '__main__':\n tf.test.main()\n",
"# Copyright 2020, The TensorFlow Federated 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\nimport os.path\nfrom unittest import mock\n\nfrom absl.testing import absltest\nfrom absl.testing import parameterized\nimport numpy as np\nimport tensorflow as tf\n\nfrom tensorflow_federated.python.program import tensorboard_release_manager\nfrom tensorflow_federated.python.program import test_utils\n\n\nclass TensorBoardReleaseManagerInitTest(parameterized.TestCase):\n\n def test_creates_summary_dir(self):\n temp_dir = self.create_tempdir()\n summary_dir = os.path.join(temp_dir, 'test')\n self.assertFalse(os.path.exists(summary_dir))\n\n tensorboard_release_manager.TensorBoardReleaseManager(\n summary_dir=summary_dir)\n\n self.assertTrue(os.path.exists(summary_dir))\n\n def test_does_not_raise_type_error_with_root_dir_str(self):\n try:\n tensorboard_release_manager.TensorBoardReleaseManager(summary_dir='/tmp')\n except TypeError:\n self.fail('Raised TypeError unexpectedly.')\n\n def test_does_not_raise_type_error_with_summary_dir_path_like(self):\n temp_dir = self.create_tempdir()\n\n try:\n tensorboard_release_manager.TensorBoardReleaseManager(\n summary_dir=temp_dir)\n except TypeError:\n self.fail('Raised TypeError unexpectedly.')\n\n @parameterized.named_parameters(\n ('none', None),\n ('bool', True),\n ('int', 1),\n ('list', []),\n )\n def test_raises_type_error_with_summary_dir(self, summary_dir):\n with self.assertRaises(TypeError):\n tensorboard_release_manager.TensorBoardReleaseManager(\n summary_dir=summary_dir)\n\n def test_raises_value_error_with_summary_dir_empty(self):\n with self.assertRaises(ValueError):\n tensorboard_release_manager.TensorBoardReleaseManager(summary_dir='')\n\n\nclass TensorBoardReleaseManagerReleaseTest(parameterized.TestCase,\n tf.test.TestCase):\n\n # pyformat: disable\n @parameterized.named_parameters(\n ('bool', True, [('', True)]),\n ('int', 1, [('', 1)]),\n ('list', [True, 1, 'a'], [('0', True), ('1', 1)]),\n ('list_nested', [[True, 1], ['a']], [('0/0', True), ('0/1', 1)]),\n ('dict',\n {'a': True, 'b': 1, 'c': 'a'},\n [('a', True), ('b', 1)]),\n ('dict_nested',\n {'x': {'a': True, 'b': 1}, 'y': {'c': 'a'}},\n [('x/a', True), ('x/b', 1)]),\n ('attr',\n test_utils.TestAttrObject1(True, 1),\n [('a', True), ('b', 1)]),\n ('attr_nested',\n {'a': [test_utils.TestAttrObject1(True, 1)],\n 'b': test_utils.TestAttrObject2('a')},\n [('a/0/a', True), ('a/0/b', 1)]),\n ('tensor_int', tf.constant(1), [('', tf.constant(1))]),\n ('tensor_nested',\n {'a': [tf.constant(True), tf.constant(1)], 'b': [tf.constant('a')]},\n [('a/0', True), ('a/1', 1)]),\n ('numpy_int', np.int32(1), [('', np.int32(1))]),\n ('numpy_nested',\n {'a': [np.bool(True), np.int32(1)], 'b': [np.str_('a')]},\n [('a/0', True), ('a/1', 1)]),\n ('materializable_value_reference_tensor',\n test_utils.TestMaterializableValueReference(1),\n [('', 1)]),\n ('materializable_value_reference_nested',\n {'a': [test_utils.TestMaterializableValueReference(True),\n test_utils.TestMaterializableValueReference(1)],\n 'b': [test_utils.TestMaterializableValueReference('a')]\n },\n [('a/0', True), ('a/1', 1)]),\n ('materializable_value_reference_and_materialized_value',\n [1, test_utils.TestMaterializableValueReference(2)],\n [('0', 1), ('1', 2)]),\n )\n # pyformat: enable\n def test_writes_value_scalar(self, value, expected_names_and_values):\n temp_dir = self.create_tempdir()\n release_mngr = tensorboard_release_manager.TensorBoardReleaseManager(\n summary_dir=temp_dir)\n\n with mock.patch.object(tf.summary, 'scalar') as mock_scalar:\n release_mngr.release(value, 1)\n\n self.assertEqual(\n len(mock_scalar.mock_calls), len(expected_names_and_values))\n iterator = zip(mock_scalar.mock_calls, expected_names_and_values)\n for call, (expected_name, expected_value) in iterator:\n _, args, _ = call\n actual_name, actual_value = args\n self.assertEqual(actual_name, expected_name)\n self.assertEqual(actual_value, expected_value)\n\n # pyformat: disable\n @parameterized.named_parameters(\n ('tensor_2d', tf.ones((2, 3)), [('', tf.ones((2, 3)))]),\n ('numpy_2d', np.ones((2, 3)), [('', np.ones((2, 3)))]),\n ('materializable_value_reference_sequence',\n test_utils.TestMaterializableValueReference(\n tf.data.Dataset.from_tensor_slices([1, 2, 3])),\n [('', [1, 2, 3])]),\n )\n # pyformat: enable\n def test_writes_value_histogram(self, value, expected_names_and_values):\n temp_dir = self.create_tempdir()\n release_mngr = tensorboard_release_manager.TensorBoardReleaseManager(\n summary_dir=temp_dir)\n\n with mock.patch.object(tf.summary, 'histogram') as mock_histogram:\n release_mngr.release(value, 1)\n\n self.assertEqual(\n len(mock_histogram.mock_calls), len(expected_names_and_values))\n iterator = zip(mock_histogram.mock_calls, expected_names_and_values)\n for call, (expected_name, expected_value) in iterator:\n _, args, _ = call\n actual_name, actual_value = args\n self.assertEqual(actual_name, expected_name)\n self.assertAllEqual(actual_value, expected_value)\n\n def test_writes_value_scalar_and_histogram(self):\n temp_dir = self.create_tempdir()\n release_mngr = tensorboard_release_manager.TensorBoardReleaseManager(\n summary_dir=temp_dir)\n\n patched_scalar = mock.patch.object(tf.summary, 'scalar')\n patched_histogram = mock.patch.object(tf.summary, 'histogram')\n with patched_scalar as mock_scalar, patched_histogram as mock_histogram:\n release_mngr.release([1, tf.ones([1])], 1)\n\n mock_scalar.assert_called_once_with('0', 1, step=1)\n mock_histogram.assert_called_once_with('1', tf.ones([1]), step=1)\n\n @parameterized.named_parameters(\n ('none', None),\n ('str', 'a'),\n ('list_empty', []),\n ('dict_empty', {}),\n ('tensor_str', tf.constant('a')),\n )\n def test_does_not_write_value(self, value):\n temp_dir = self.create_tempdir()\n release_mngr = tensorboard_release_manager.TensorBoardReleaseManager(\n summary_dir=temp_dir)\n\n patch_scalar = mock.patch.object(tf.summary, 'scalar')\n patch_histogram = mock.patch.object(tf.summary, 'histogram')\n with patch_scalar as mock_scalar, patch_histogram as mock_histogram:\n release_mngr.release(value, 1)\n\n mock_scalar.assert_not_called()\n mock_histogram.assert_not_called()\n\n @parameterized.named_parameters(\n ('negative_1', -1),\n ('0', 0),\n ('1', 1),\n )\n def test_does_not_raise_with_key(self, key):\n temp_dir = self.create_tempdir()\n release_mngr = tensorboard_release_manager.TensorBoardReleaseManager(\n summary_dir=temp_dir)\n\n try:\n release_mngr.release(1, key)\n except TypeError:\n self.fail('Raised TypeError unexpectedly.')\n\n @parameterized.named_parameters(\n ('none', None),\n ('str', 'a'),\n ('list', []),\n )\n def test_raises_type_error_with_key(self, key):\n temp_dir = self.create_tempdir()\n release_mngr = tensorboard_release_manager.TensorBoardReleaseManager(\n summary_dir=temp_dir)\n\n with self.assertRaises(TypeError):\n release_mngr.release(1, key)\n\n\nif __name__ == '__main__':\n absltest.main()\n",
"# Copyright 2021, The TensorFlow Federated 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\nimport collections\n\nfrom absl.testing import parameterized\nimport tensorflow as tf\n\nfrom tensorflow_federated.python.core.api import computations\nfrom tensorflow_federated.python.core.api import test_case\nfrom tensorflow_federated.python.core.backends.native import execution_contexts\nfrom tensorflow_federated.python.core.impl.federated_context import intrinsics\nfrom tensorflow_federated.python.core.impl.types import computation_types\nfrom tensorflow_federated.python.core.impl.types import placements\nfrom tensorflow_federated.python.core.templates import errors\nfrom tensorflow_federated.python.core.templates import measured_process\nfrom tensorflow_federated.python.learning import model_utils\nfrom tensorflow_federated.python.learning.optimizers import optimizer as optimizer_base\nfrom tensorflow_federated.python.learning.optimizers import sgdm\nfrom tensorflow_federated.python.learning.templates import finalizers\n\nSERVER_INT = computation_types.FederatedType(tf.int32, placements.SERVER)\nSERVER_FLOAT = computation_types.FederatedType(tf.float32, placements.SERVER)\nCLIENTS_INT = computation_types.FederatedType(tf.int32, placements.CLIENTS)\nCLIENTS_FLOAT = computation_types.FederatedType(tf.float32, placements.CLIENTS)\nMODEL_WEIGHTS_TYPE = computation_types.at_server(\n computation_types.to_type(model_utils.ModelWeights(tf.float32, ())))\nMeasuredProcessOutput = measured_process.MeasuredProcessOutput\n\n\ndef server_zero():\n \"\"\"Returns zero integer placed at SERVER.\"\"\"\n return intrinsics.federated_value(0, placements.SERVER)\n\n\ndef federated_add(a, b):\n return intrinsics.federated_map(\n computations.tf_computation(lambda x, y: x + y), (a, b))\n\n\[email protected]_computation()\ndef test_initialize_fn():\n return server_zero()\n\n\ndef test_finalizer_result(weights, update):\n return intrinsics.federated_zip(\n model_utils.ModelWeights(federated_add(weights.trainable, update), ()))\n\n\[email protected]_computation(SERVER_INT, MODEL_WEIGHTS_TYPE,\n SERVER_FLOAT)\ndef test_next_fn(state, weights, update):\n return MeasuredProcessOutput(state, test_finalizer_result(weights, update),\n intrinsics.federated_value(1, placements.SERVER))\n\n\nclass FinalizerTest(test_case.TestCase):\n\n def test_construction_does_not_raise(self):\n try:\n finalizers.FinalizerProcess(test_initialize_fn, test_next_fn)\n except: # pylint: disable=bare-except\n self.fail('Could not construct a valid FinalizerProcess.')\n\n def test_construction_with_empty_state_does_not_raise(self):\n initialize_fn = computations.federated_computation()(\n lambda: intrinsics.federated_value((), placements.SERVER))\n\n @computations.federated_computation(initialize_fn.type_signature.result,\n MODEL_WEIGHTS_TYPE, SERVER_FLOAT)\n def next_fn(state, weights, update):\n return MeasuredProcessOutput(\n state, test_finalizer_result(weights, update),\n intrinsics.federated_value(1, placements.SERVER))\n\n try:\n finalizers.FinalizerProcess(initialize_fn, next_fn)\n except: # pylint: disable=bare-except\n self.fail('Could not construct an FinalizerProcess with empty state.')\n\n def test_init_not_tff_computation_raises(self):\n with self.assertRaisesRegex(TypeError, r'Expected .*\\.Computation, .*'):\n finalizers.FinalizerProcess(initialize_fn=lambda: 0, next_fn=test_next_fn)\n\n def test_next_not_tff_computation_raises(self):\n with self.assertRaisesRegex(TypeError, r'Expected .*\\.Computation, .*'):\n finalizers.FinalizerProcess(\n initialize_fn=test_initialize_fn,\n next_fn=lambda state, w, u: MeasuredProcessOutput(state, w + u, ()))\n\n def test_init_param_not_empty_raises(self):\n one_arg_initialize_fn = computations.federated_computation(SERVER_INT)(\n lambda x: x)\n with self.assertRaises(errors.TemplateInitFnParamNotEmptyError):\n finalizers.FinalizerProcess(one_arg_initialize_fn, test_next_fn)\n\n def test_init_state_not_assignable(self):\n float_initialize_fn = computations.federated_computation()(\n lambda: intrinsics.federated_value(0.0, placements.SERVER))\n with self.assertRaises(errors.TemplateStateNotAssignableError):\n finalizers.FinalizerProcess(float_initialize_fn, test_next_fn)\n\n def test_next_state_not_assignable(self):\n\n @computations.federated_computation(SERVER_INT, MODEL_WEIGHTS_TYPE,\n SERVER_FLOAT)\n def float_next_fn(state, weights, update):\n del state\n return MeasuredProcessOutput(\n intrinsics.federated_value(0.0, placements.SERVER),\n test_finalizer_result(weights, update),\n intrinsics.federated_value(1, placements.SERVER))\n\n with self.assertRaises(errors.TemplateStateNotAssignableError):\n finalizers.FinalizerProcess(test_initialize_fn, float_next_fn)\n\n def test_next_return_tuple_raises(self):\n\n @computations.federated_computation(SERVER_INT, MODEL_WEIGHTS_TYPE,\n SERVER_FLOAT)\n def tuple_next_fn(state, weights, update):\n return state, test_finalizer_result(weights, update), server_zero()\n\n with self.assertRaises(errors.TemplateNotMeasuredProcessOutputError):\n finalizers.FinalizerProcess(test_initialize_fn, tuple_next_fn)\n\n def test_next_return_namedtuple_raises(self):\n measured_process_output = collections.namedtuple(\n 'MeasuredProcessOutput', ['state', 'result', 'measurements'])\n\n @computations.federated_computation(SERVER_INT, MODEL_WEIGHTS_TYPE,\n SERVER_FLOAT)\n def namedtuple_next_fn(state, weights, update):\n return measured_process_output(state,\n test_finalizer_result(weights, update),\n server_zero())\n\n with self.assertRaises(errors.TemplateNotMeasuredProcessOutputError):\n finalizers.FinalizerProcess(test_initialize_fn, namedtuple_next_fn)\n\n def test_next_return_odict_raises(self):\n\n @computations.federated_computation(SERVER_INT, MODEL_WEIGHTS_TYPE,\n SERVER_FLOAT)\n def odict_next_fn(state, weights, update):\n return collections.OrderedDict(\n state=state,\n result=test_finalizer_result(weights, update),\n measurements=server_zero())\n\n with self.assertRaises(errors.TemplateNotMeasuredProcessOutputError):\n finalizers.FinalizerProcess(test_initialize_fn, odict_next_fn)\n\n # Tests specific only for the FinalizerProcess contract below.\n\n def test_non_federated_init_next_raises(self):\n initialize_fn = computations.tf_computation(lambda: 0)\n\n @computations.tf_computation(tf.int32,\n computation_types.to_type(\n model_utils.ModelWeights(tf.float32, ())),\n tf.float32)\n def next_fn(state, weights, update):\n new_weigths = model_utils.ModelWeights(weights.trainable + update, ())\n return MeasuredProcessOutput(state, new_weigths, 0)\n\n with self.assertRaises(errors.TemplateNotFederatedError):\n finalizers.FinalizerProcess(initialize_fn, next_fn)\n\n def test_init_tuple_of_federated_types_raises(self):\n initialize_fn = computations.federated_computation()(\n lambda: (server_zero(), server_zero()))\n\n @computations.federated_computation(initialize_fn.type_signature.result,\n MODEL_WEIGHTS_TYPE, SERVER_FLOAT)\n def next_fn(state, weights, update):\n return MeasuredProcessOutput(state,\n test_finalizer_result(weights, update),\n server_zero())\n\n with self.assertRaises(errors.TemplateNotFederatedError):\n finalizers.FinalizerProcess(initialize_fn, next_fn)\n\n def test_non_server_placed_init_state_raises(self):\n initialize_fn = computations.federated_computation(\n lambda: intrinsics.federated_value(0, placements.CLIENTS))\n\n @computations.federated_computation(CLIENTS_INT, MODEL_WEIGHTS_TYPE,\n SERVER_FLOAT)\n def next_fn(state, weights, update):\n return MeasuredProcessOutput(state,\n test_finalizer_result(weights, update),\n server_zero())\n\n with self.assertRaises(errors.TemplatePlacementError):\n finalizers.FinalizerProcess(initialize_fn, next_fn)\n\n def test_two_param_next_raises(self):\n\n @computations.federated_computation(SERVER_INT, MODEL_WEIGHTS_TYPE)\n def next_fn(state, weights):\n return MeasuredProcessOutput(state, weights, server_zero())\n\n with self.assertRaises(errors.TemplateNextFnNumArgsError):\n finalizers.FinalizerProcess(test_initialize_fn, next_fn)\n\n def test_non_server_placed_next_weight_param_raises(self):\n\n @computations.federated_computation(SERVER_INT,\n computation_types.at_clients(\n MODEL_WEIGHTS_TYPE.member),\n SERVER_FLOAT)\n def next_fn(state, weights, update):\n return MeasuredProcessOutput(\n state,\n test_finalizer_result(intrinsics.federated_sum(weights), update),\n server_zero())\n\n with self.assertRaises(errors.TemplatePlacementError):\n finalizers.FinalizerProcess(test_initialize_fn, next_fn)\n\n def test_constructs_with_non_model_weights_parameter(self):\n non_model_weights_type = computation_types.at_server(\n computation_types.to_type(\n collections.OrderedDict(trainable=tf.float32, non_trainable=())))\n\n @computations.federated_computation(SERVER_INT, non_model_weights_type,\n SERVER_FLOAT)\n def next_fn(state, weights, update):\n del update\n return MeasuredProcessOutput(state, weights, server_zero())\n\n try:\n finalizers.FinalizerProcess(test_initialize_fn, next_fn)\n except: # pylint: disable=bare-except\n self.fail('Could not construct a valid FinalizerProcess.')\n\n def test_non_server_placed_next_update_param_raises(self):\n\n @computations.federated_computation(SERVER_INT, MODEL_WEIGHTS_TYPE,\n CLIENTS_FLOAT)\n def next_fn(state, weights, update):\n return MeasuredProcessOutput(\n state, test_finalizer_result(weights,\n intrinsics.federated_sum(update)),\n server_zero())\n\n with self.assertRaises(errors.TemplatePlacementError):\n finalizers.FinalizerProcess(test_initialize_fn, next_fn)\n\n def test_non_server_placed_next_result_raises(self):\n\n @computations.federated_computation(SERVER_INT, MODEL_WEIGHTS_TYPE,\n SERVER_FLOAT)\n def next_fn(state, weights, update):\n return MeasuredProcessOutput(\n state,\n intrinsics.federated_broadcast(\n test_finalizer_result(weights, update)), server_zero())\n\n with self.assertRaises(errors.TemplatePlacementError):\n finalizers.FinalizerProcess(test_initialize_fn, next_fn)\n\n def test_result_not_assignable_to_weight_raises(self):\n bad_cast_fn = computations.tf_computation(\n lambda x: tf.nest.map_structure(lambda y: tf.cast(y, tf.float64), x))\n\n @computations.federated_computation(SERVER_INT, MODEL_WEIGHTS_TYPE,\n SERVER_FLOAT)\n def next_fn(state, weights, update):\n return MeasuredProcessOutput(\n state,\n intrinsics.federated_map(bad_cast_fn,\n test_finalizer_result(weights, update)),\n server_zero())\n\n with self.assertRaises(finalizers.FinalizerResultTypeError):\n finalizers.FinalizerProcess(test_initialize_fn, next_fn)\n\n def test_non_server_placed_next_measurements_raises(self):\n\n @computations.federated_computation(SERVER_INT, MODEL_WEIGHTS_TYPE,\n SERVER_FLOAT)\n def next_fn(state, weights, update):\n return MeasuredProcessOutput(\n state, test_finalizer_result(weights, update),\n intrinsics.federated_value(1.0, placements.CLIENTS))\n\n with self.assertRaises(errors.TemplatePlacementError):\n finalizers.FinalizerProcess(test_initialize_fn, next_fn)\n\n\nclass ApplyOptimizerFinalizerComputationTest(test_case.TestCase,\n parameterized.TestCase):\n\n def test_type_properties(self):\n mw_type = computation_types.to_type(\n model_utils.ModelWeights(\n trainable=(tf.float32, tf.float32), non_trainable=tf.float32))\n\n finalizer = finalizers.build_apply_optimizer_finalizer(\n sgdm.build_sgdm(1.0), mw_type)\n self.assertIsInstance(finalizer, finalizers.FinalizerProcess)\n\n expected_param_weights_type = computation_types.at_server(mw_type)\n expected_param_update_type = computation_types.at_server(mw_type.trainable)\n expected_result_type = computation_types.at_server(mw_type)\n expected_state_type = computation_types.at_server(\n computation_types.to_type(\n collections.OrderedDict([(optimizer_base.LEARNING_RATE_KEY,\n tf.float32)])))\n expected_measurements_type = computation_types.at_server(())\n\n expected_initialize_type = computation_types.FunctionType(\n parameter=None, result=expected_state_type)\n expected_initialize_type.check_equivalent_to(\n finalizer.initialize.type_signature)\n\n expected_next_type = computation_types.FunctionType(\n parameter=collections.OrderedDict(\n state=expected_state_type,\n weights=expected_param_weights_type,\n update=expected_param_update_type),\n result=MeasuredProcessOutput(expected_state_type, expected_result_type,\n expected_measurements_type))\n expected_next_type.check_equivalent_to(finalizer.next.type_signature)\n\n @parameterized.named_parameters(\n ('not_struct', computation_types.TensorType(tf.float32)),\n ('federated_type', MODEL_WEIGHTS_TYPE),\n ('model_weights_of_federated_types',\n computation_types.to_type(\n model_utils.ModelWeights(SERVER_FLOAT, SERVER_FLOAT))),\n ('not_model_weights', computation_types.to_type(\n (tf.float32, tf.float32))),\n ('function_type', computation_types.FunctionType(None,\n MODEL_WEIGHTS_TYPE)),\n ('sequence_type', computation_types.SequenceType(\n MODEL_WEIGHTS_TYPE.member)))\n def test_incorrect_value_type_raises(self, bad_type):\n with self.assertRaises(TypeError):\n finalizers.build_apply_optimizer_finalizer(sgdm.build_sgdm(1.0), bad_type)\n\n def test_unexpected_optimizer_fn_raises(self):\n optimizer = tf.keras.optimizers.SGD(1.0)\n with self.assertRaises(TypeError):\n finalizers.build_apply_optimizer_finalizer(optimizer,\n MODEL_WEIGHTS_TYPE.member)\n\n\nclass ApplyOptimizerFinalizerExecutionTest(test_case.TestCase):\n\n def test_execution_with_stateless_tff_optimizer(self):\n finalizer = finalizers.build_apply_optimizer_finalizer(\n sgdm.build_sgdm(1.0), MODEL_WEIGHTS_TYPE.member)\n\n weights = model_utils.ModelWeights(1.0, ())\n update = 0.1\n optimizer_state = finalizer.initialize()\n for i in range(5):\n output = finalizer.next(optimizer_state, weights, update)\n optimizer_state = output.state\n weights = output.result\n self.assertEqual(1.0, optimizer_state[optimizer_base.LEARNING_RATE_KEY])\n self.assertAllClose(1.0 - 0.1 * (i + 1), weights.trainable)\n self.assertEqual((), output.measurements)\n\n def test_execution_with_nearly_stateless_keras_optimizer(self):\n server_optimizer_fn = lambda: tf.keras.optimizers.SGD(learning_rate=1.0)\n # Note that SGD only maintains a counter of how many times it has been\n # called. No other state is used.\n finalizer = finalizers.build_apply_optimizer_finalizer(\n server_optimizer_fn, MODEL_WEIGHTS_TYPE.member)\n\n weights = model_utils.ModelWeights(1.0, ())\n update = 0.1\n optimizer_state = finalizer.initialize()\n for i in range(5):\n output = finalizer.next(optimizer_state, weights, update)\n optimizer_state = output.state\n weights = output.result\n # We check that the optimizer state is the number of calls.\n self.assertEqual([i + 1], optimizer_state)\n self.assertAllClose(1.0 - 0.1 * (i + 1), weights.trainable)\n self.assertEqual((), output.measurements)\n\n def test_execution_with_stateful_tff_optimizer(self):\n momentum = 0.5\n finalizer = finalizers.build_apply_optimizer_finalizer(\n sgdm.build_sgdm(1.0, momentum=momentum), MODEL_WEIGHTS_TYPE.member)\n\n weights = model_utils.ModelWeights(1.0, ())\n update = 0.1\n expected_velocity = 0.0\n optimizer_state = finalizer.initialize()\n for _ in range(5):\n output = finalizer.next(optimizer_state, weights, update)\n optimizer_state = output.state\n expected_velocity = expected_velocity * momentum + update\n self.assertNear(expected_velocity, optimizer_state['accumulator'], 1e-6)\n self.assertAllClose(weights.trainable - expected_velocity,\n output.result.trainable)\n self.assertEqual((), output.measurements)\n weights = output.result\n\n def test_execution_with_stateful_keras_optimizer(self):\n momentum = 0.5\n\n def server_optimizer_fn():\n return tf.keras.optimizers.SGD(learning_rate=1.0, momentum=0.5)\n\n finalizer = finalizers.build_apply_optimizer_finalizer(\n server_optimizer_fn, MODEL_WEIGHTS_TYPE.member)\n\n weights = model_utils.ModelWeights(1.0, ())\n update = 0.1\n expected_velocity = 0.0\n optimizer_state = finalizer.initialize()\n for i in range(5):\n output = finalizer.next(optimizer_state, weights, update)\n optimizer_state = output.state\n expected_velocity = expected_velocity * momentum + update\n # Keras stores the negative of the velocity term used by\n # tff.learning.optimizers.SGDM\n self.assertAllClose([i + 1, -expected_velocity], optimizer_state)\n self.assertAllClose(weights.trainable - expected_velocity,\n output.result.trainable)\n self.assertEqual((), output.measurements)\n weights = output.result\n\n\nif __name__ == '__main__':\n execution_contexts.set_local_python_execution_context()\n test_case.main()\n",
"# Copyright 2019, The TensorFlow Federated 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\"\"\"Tests for keras_utils.\n\nThese tests also serve as examples for users who are familiar with Keras.\n\"\"\"\n\nimport collections\nimport warnings\n\nfrom absl.testing import parameterized\nimport numpy as np\nimport tensorflow as tf\n\nfrom tensorflow_federated.python.core.api import computation_base\nfrom tensorflow_federated.python.core.api import computations\nfrom tensorflow_federated.python.core.api import test_case\nfrom tensorflow_federated.python.core.backends.native import execution_contexts\nfrom tensorflow_federated.python.core.impl.types import computation_types\nfrom tensorflow_federated.python.core.impl.types import type_conversions\nfrom tensorflow_federated.python.learning import keras_utils\nfrom tensorflow_federated.python.learning import model as model_lib\nfrom tensorflow_federated.python.learning import model_examples\nfrom tensorflow_federated.python.learning import model_utils\nfrom tensorflow_federated.python.learning.metrics import aggregator\nfrom tensorflow_federated.python.learning.metrics import counters\n\n\ndef _create_whimsy_types(feature_dims):\n \"\"\"Creates a whimsy batch of zeros.\"\"\"\n return collections.OrderedDict(\n x=tf.TensorSpec(shape=[1, feature_dims], dtype=tf.float32),\n y=tf.TensorSpec(shape=[1], dtype=tf.float32))\n\n\ndef _create_tff_model_from_keras_model_tuples():\n tuples = []\n for n_dims in [1, 3]:\n for name, model_fn in [\n ('functional',\n model_examples.build_linear_regression_keras_functional_model),\n ('sequential',\n model_examples.build_linear_regression_keras_sequential_model),\n ('sequential_regularized', model_examples\n .build_linear_regression_regularized_keras_sequential_model)\n ]:\n tuples.append(('{}_model_{}_dims'.format(name, n_dims), n_dims, model_fn))\n return tuples\n\n\ndef _create_input_spec_multiple_inputs_outputs():\n return collections.OrderedDict(\n x=[\n tf.TensorSpec(shape=[None, 1], dtype=tf.float32),\n tf.TensorSpec(shape=[None, 1], dtype=tf.float32)\n ],\n y=[\n tf.TensorSpec(shape=[None, 1], dtype=tf.float32),\n tf.TensorSpec(shape=[None, 1], dtype=tf.float32),\n tf.TensorSpec(shape=[None, 1], dtype=tf.float32)\n ])\n\n\ndef _create_test_batch(feature_dims):\n return collections.OrderedDict(\n x=np.stack([\n np.zeros(feature_dims, np.float32),\n np.ones(feature_dims, np.float32)\n ]),\n y=np.stack([\n np.zeros([1], np.float32),\n np.ones([1], np.float32),\n ]))\n\n\nclass KerasUtilsTest(test_case.TestCase, parameterized.TestCase):\n\n def setUp(self):\n tf.keras.backend.clear_session()\n super().setUp()\n\n def assertIsSubClass(self, cls1, cls2):\n if not issubclass(cls1, cls2):\n raise AssertionError('{} is not a subclass of {}'.format(cls1, cls2))\n\n def test_convert_fails_on_non_keras_model(self):\n with self.assertRaisesRegex(TypeError, r'keras\\..*\\.Model'):\n keras_utils.from_keras_model(\n keras_model=0, # not a tf.keras.Model\n input_spec=_create_whimsy_types(1),\n loss=tf.keras.losses.MeanSquaredError())\n\n # Test class for batches using namedtuple.\n _make_test_batch = collections.namedtuple('TestBatch', ['x', 'y'])\n\n @parameterized.named_parameters(\n ('container',\n collections.OrderedDict(\n x=tf.TensorSpec(shape=[None, 1], dtype=tf.float32),\n y=tf.TensorSpec(shape=[None, 1], dtype=tf.float32))),\n ('container_fn',\n _make_test_batch(\n x=tf.TensorSpec(shape=[1, 1], dtype=tf.float32),\n y=tf.TensorSpec(shape=[None, 1], dtype=tf.float32))),\n ('tff_struct_with_python_type',\n computation_types.StructWithPythonType(\n collections.OrderedDict(\n x=tf.TensorSpec(shape=[None, 1], dtype=tf.float32),\n y=tf.TensorSpec(shape=[None, 1], dtype=tf.float32)),\n container_type=collections.OrderedDict)))\n def test_input_spec_python_container(self, input_spec):\n keras_model = model_examples.build_linear_regression_keras_functional_model(\n feature_dims=1)\n tff_model = keras_utils.from_keras_model(\n keras_model=keras_model,\n input_spec=input_spec,\n loss=tf.keras.losses.MeanSquaredError())\n self.assertIsInstance(tff_model, model_lib.Model)\n tf.nest.map_structure(lambda x: self.assertIsInstance(x, tf.TensorSpec),\n tff_model.input_spec)\n\n def test_input_spec_struct(self):\n keras_model = model_examples.build_linear_regression_keras_functional_model(\n feature_dims=1)\n input_spec = computation_types.StructType(\n collections.OrderedDict(\n x=tf.TensorSpec(shape=[None, 1], dtype=tf.float32),\n y=tf.TensorSpec(shape=[None, 1], dtype=tf.float32)))\n tff_model = keras_utils.from_keras_model(\n keras_model=keras_model,\n input_spec=input_spec,\n loss=tf.keras.losses.MeanSquaredError())\n self.assertIsInstance(tff_model, model_lib.Model)\n self.assertIsInstance(tff_model.input_spec, collections.OrderedDict)\n tf.nest.map_structure(lambda x: self.assertIsInstance(x, tf.TensorSpec),\n tff_model.input_spec)\n\n def test_input_spec_ragged_tensor(self):\n keras_model = model_examples.build_ragged_tensor_input_keras_model()\n input_spec = collections.OrderedDict(\n x=tf.RaggedTensorSpec(shape=[3, None], dtype=tf.int32),\n y=tf.TensorSpec(shape=[1], dtype=tf.bool))\n tff_model = keras_utils.from_keras_model(\n keras_model=keras_model,\n input_spec=input_spec,\n loss=tf.keras.losses.BinaryCrossentropy(from_logits=True))\n self.assertIsInstance(tff_model, model_lib.Model)\n self.assertIsInstance(tff_model.input_spec['x'], tf.RaggedTensorSpec)\n\n batch = collections.OrderedDict(\n x=tf.ragged.constant([[1, 2, 3], [4], [5, 6]]),\n y=tf.constant([True, False, False]),\n )\n output = tff_model.forward_pass(batch)\n self.assertEqual(output.num_examples, 3)\n\n @parameterized.named_parameters(\n ('more_than_two_elements', [\n tf.TensorSpec(shape=[None, 1], dtype=tf.float32),\n tf.TensorSpec(shape=[None, 1], dtype=tf.float32),\n tf.TensorSpec(shape=[None, 1], dtype=tf.float32)\n ]),\n ('dict_with_key_not_named_x',\n collections.OrderedDict(\n foo=tf.TensorSpec(shape=[None, 1], dtype=tf.float32),\n y=tf.TensorSpec(shape=[None, 1], dtype=tf.float32))),\n ('dict_with_key_not_named_y',\n collections.OrderedDict(\n x=tf.TensorSpec(shape=[None, 1], dtype=tf.float32),\n bar=tf.TensorSpec(shape=[None, 1], dtype=tf.float32))),\n )\n def test_input_spec_batch_types_value_errors(self, input_spec):\n keras_model = model_examples.build_linear_regression_keras_functional_model(\n feature_dims=1)\n with self.assertRaises(ValueError):\n keras_utils.from_keras_model(\n keras_model=keras_model,\n input_spec=input_spec,\n loss=tf.keras.losses.MeanSquaredError())\n\n @parameterized.named_parameters(\n ('python_container_not_tensorspec',\n collections.OrderedDict(\n x=tf.constant(0.0, dtype=tf.float32),\n y=tf.TensorSpec(shape=[None, 1], dtype=tf.float32)),\n 'Expected input spec member to be of type.*TensorSpec'),\n ('tff_type_not_tensortype',\n computation_types.to_type(\n collections.OrderedDict(\n x=computation_types.SequenceType(\n computation_types.TensorType(tf.float32)),\n y=tf.TensorSpec(shape=[None, 1], dtype=tf.float32))),\n 'Expected a `tff.Type` with all the leaf nodes being `tff.TensorType`s'))\n def test_input_spec_batch_types_type_errors(self, input_spec, error_message):\n keras_model = model_examples.build_linear_regression_keras_functional_model(\n feature_dims=1)\n with self.assertRaisesRegex(TypeError, error_message):\n keras_utils.from_keras_model(\n keras_model=keras_model,\n input_spec=input_spec,\n loss=tf.keras.losses.MeanSquaredError())\n\n @parameterized.named_parameters(\n # Test cases for the cartesian product of all parameter values.\n *_create_tff_model_from_keras_model_tuples())\n def test_tff_model_from_keras_model(self, feature_dims, model_fn):\n keras_model = model_fn(feature_dims)\n tff_model = keras_utils.from_keras_model(\n keras_model=keras_model,\n input_spec=_create_whimsy_types(feature_dims),\n loss=tf.keras.losses.MeanSquaredError(),\n metrics=[tf.keras.metrics.MeanAbsoluteError()])\n self.assertIsInstance(tff_model, model_lib.Model)\n\n # Metrics should be zero, though the model wrapper internally executes the\n # forward pass once.\n self.assertSequenceEqual(tff_model.local_variables,\n [0.0, 0.0, 0.0, 0.0, 0, 0])\n\n batch = _create_test_batch(feature_dims)\n # from_model() was called without an optimizer which creates a tff.Model.\n # There is no train_on_batch() method available in tff.Model.\n with self.assertRaisesRegex(AttributeError,\n 'no attribute \\'train_on_batch\\''):\n tff_model.train_on_batch(batch)\n\n output = tff_model.forward_pass(batch)\n # Since the model initializes all weights and biases to zero, we expect\n # all predictions to be zero:\n # 0*x1 + 0*x2 + ... + 0 = 0\n self.assertAllEqual(output.predictions, [[0.0], [0.0]])\n # For the single batch:\n #\n # Example | Prediction | Label | Residual | Loss\n # --------+------------+-------+----------+ -----\n # 1 | 0.0 | 0.0 | 0.0 | 0.0\n # 2 | 0.0 | 1.0 | 1.0 | 1.0\n #\n # Note that though regularization might be applied, this has no effect on\n # the loss since all weights are 0.\n # Total loss: 1.0\n # Batch average loss: 0.5\n self.assertEqual(output.loss, 0.5)\n metrics = tff_model.report_local_unfinalized_metrics()\n self.assertEqual(metrics['num_batches'], [1])\n self.assertEqual(metrics['num_examples'], [2])\n self.assertGreater(metrics['loss'][0], 0)\n self.assertEqual(metrics['loss'][1], 2)\n self.assertGreater(metrics['mean_absolute_error'][0], 0)\n self.assertEqual(metrics['mean_absolute_error'][1], 2)\n\n def test_tff_model_from_keras_model_regularization(self):\n keras_model = model_examples.build_linear_regression_ones_regularized_keras_sequential_model(\n 3)\n tff_model = keras_utils.from_keras_model(\n keras_model=keras_model,\n input_spec=_create_whimsy_types(3),\n loss=tf.keras.losses.MeanSquaredError(),\n metrics=[tf.keras.metrics.MeanAbsoluteError()])\n self.assertIsInstance(tff_model, model_lib.Model)\n\n # Metrics should be zero, though the model wrapper internally executes the\n # forward pass once.\n self.assertSequenceEqual(tff_model.local_variables,\n [0.0, 0.0, 0.0, 0.0, 0, 0])\n\n batch = _create_test_batch(feature_dims=3)\n # from_model() was called without an optimizer which creates a tff.Model.\n # There is no train_on_batch() method available in tff.Model.\n with self.assertRaisesRegex(AttributeError,\n 'no attribute \\'train_on_batch\\''):\n tff_model.train_on_batch(batch)\n\n output = tff_model.forward_pass(batch)\n # Since the model initializes all weights and biases to zero, we expect\n # all predictions to be zero:\n # 0*x1 + 0*x2 + ... + 0 = 0\n self.assertAllEqual(output.predictions, [[1.0], [4.0]])\n # For the single batch:\n #\n # Example | Prediction | Label | Residual | Loss\n # --------+------------+-------+----------+ -----\n # 1 | 1.0 | 0.0 | 1.0 | 1.0\n # 2 | 4.0 | 1.0 | 3.0 | 9.0\n #\n # Regularization loss: with an L2 regularization constant of 0.01: kernel\n # regularizer loss is (3 * 1**2) * 0.01, bias regularizer loss is\n # 1**2 * 0.01, so total regularization loss is 0.04.\n # Total loss: 10.0\n # Batch average loss: 5.0\n # Total batch loss with regularization: 5.04\n self.assertAlmostEqual(output.loss, 5.04)\n metrics = tff_model.report_local_unfinalized_metrics()\n self.assertEqual(metrics['num_batches'], [1])\n self.assertEqual(metrics['num_examples'], [2])\n self.assertGreater(metrics['loss'][0], 0)\n self.assertEqual(metrics['loss'][1], 2)\n self.assertGreater(metrics['mean_absolute_error'][0], 0)\n self.assertEqual(metrics['mean_absolute_error'][1], 2)\n\n @parameterized.named_parameters(*_create_tff_model_from_keras_model_tuples())\n def test_tff_model_from_keras_model_input_spec(self, feature_dims, model_fn):\n keras_model = model_fn(feature_dims)\n tff_model = keras_utils.from_keras_model(\n keras_model=keras_model,\n loss=tf.keras.losses.MeanSquaredError(),\n metrics=[tf.keras.metrics.MeanAbsoluteError()],\n input_spec=_create_whimsy_types(feature_dims))\n self.assertIsInstance(tff_model, model_lib.Model)\n\n # Metrics should be zero, though the model wrapper internally executes the\n # forward pass once.\n self.assertSequenceEqual(tff_model.local_variables,\n [0.0, 0.0, 0.0, 0.0, 0, 0])\n\n batch = _create_test_batch(feature_dims)\n # from_model() was called without an optimizer which creates a tff.Model.\n # There is no train_on_batch() method available in tff.Model.\n with self.assertRaisesRegex(AttributeError,\n 'no attribute \\'train_on_batch\\''):\n tff_model.train_on_batch(batch)\n\n output = tff_model.forward_pass(batch)\n # Since the model initializes all weights and biases to zero, we expect\n # all predictions to be zero:\n # 0*x1 + 0*x2 + ... + 0 = 0\n self.assertAllEqual(output.predictions, [[0.0], [0.0]])\n # For the single batch:\n #\n # Example | Prediction | Label | Residual | Loss\n # --------+------------+-------+----------+ -----\n # 1 | 0.0 | 0.0 | 0.0 | 0.0\n # 2 | 0.0 | 1.0 | 1.0 | 1.0\n #\n # Total loss: 1.0\n # Batch average loss: 0.5\n self.assertEqual(output.loss, 0.5)\n metrics = tff_model.report_local_unfinalized_metrics()\n self.assertEqual(metrics['num_batches'], [1])\n self.assertEqual(metrics['num_examples'], [2])\n self.assertGreater(metrics['loss'][0], 0)\n self.assertEqual(metrics['loss'][1], 2)\n self.assertGreater(metrics['mean_absolute_error'][0], 0)\n self.assertEqual(metrics['mean_absolute_error'][1], 2)\n\n def test_tff_model_from_keras_model_with_custom_loss_with_integer_label(self):\n\n class _CustomLossRequiringLabelBeInteger(tf.keras.losses.Loss):\n\n def __init__(self):\n super().__init__(name='custom_loss_requiring_label_be_integer')\n\n def call(self, y_true, y_pred):\n # Note that this TF function requires that the label `y_true` be of an\n # integer dtype; a TypeError is thrown if `y_true` isn't int32 or int64.\n return tf.nn.sparse_softmax_cross_entropy_with_logits(y_true, y_pred)\n\n keras_model = tf.keras.Sequential(\n [tf.keras.Input(shape=(2,)),\n tf.keras.layers.Dense(units=10)])\n\n input_spec = [\n tf.TensorSpec(shape=[1, 2], dtype=tf.float32),\n tf.TensorSpec(shape=[1], dtype=tf.int64)\n ]\n\n tff_model = keras_utils.from_keras_model(\n keras_model=keras_model,\n loss=_CustomLossRequiringLabelBeInteger(),\n input_spec=input_spec)\n\n batch = collections.OrderedDict(\n x=tf.convert_to_tensor(np.ones((1, 2)), dtype=tf.float32),\n y=tf.convert_to_tensor([0], dtype=tf.int64))\n\n # Expect this call to .forward_pass to succeed (no Errors raised).\n tff_model.forward_pass(batch)\n\n def test_tff_model_type_spec_from_keras_model_unspecified_sequence_len(self):\n keras_model = tf.keras.Sequential([\n tf.keras.layers.InputLayer(input_shape=(None,)),\n tf.keras.layers.Embedding(input_dim=10, output_dim=10),\n tf.keras.layers.LSTM(1)\n ])\n input_spec = [\n tf.TensorSpec(shape=[None, None], dtype=tf.int64),\n tf.TensorSpec(shape=[None], dtype=tf.float32)\n ]\n tff_model = keras_utils.from_keras_model(\n keras_model=keras_model,\n loss=tf.keras.losses.MeanSquaredError(),\n input_spec=input_spec)\n self.assertIsInstance(tff_model, model_lib.Model)\n self.assertEqual(tff_model.input_spec, input_spec)\n\n batch = _create_test_batch(feature_dims=5)\n output = tff_model.forward_pass(batch)\n\n self.assertAllEqual(output.predictions.shape, [2, 1])\n\n # A batch with different sequence length should be processed in a similar\n # way\n batch = _create_test_batch(feature_dims=10)\n output = tff_model.forward_pass(batch)\n\n self.assertAllEqual(output.predictions.shape, [2, 1])\n\n def test_keras_model_using_embeddings(self):\n model = model_examples.build_embedding_keras_model()\n input_spec = collections.OrderedDict(\n x=tf.TensorSpec(shape=[None], dtype=tf.float32),\n y=tf.TensorSpec(shape=[None], dtype=tf.float32))\n tff_model = keras_utils.from_keras_model(\n keras_model=model,\n input_spec=input_spec,\n loss=tf.keras.losses.SparseCategoricalCrossentropy(),\n metrics=[tf.keras.metrics.MeanAbsoluteError()])\n\n # Create a batch with the size of the vocab. These examples will attempt to\n # train the embedding so that the model produces\n # i -> (i / output_size) + 5\n input_vocab_size = 10\n output_vocab_size = 5\n xs = []\n ys = []\n for input_id in range(input_vocab_size):\n xs.append(input_id)\n ys.append((input_id / output_vocab_size + 5) % output_vocab_size)\n batch = collections.OrderedDict(\n x=np.expand_dims(np.array(xs, dtype=np.int64), axis=-1),\n y=np.expand_dims(np.array(ys, dtype=np.int64), axis=-1))\n\n num_train_steps = 3\n for _ in range(num_train_steps):\n batch_output = tff_model.forward_pass(batch)\n self.assertGreater(batch_output.loss, 0.0)\n\n m = tff_model.report_local_unfinalized_metrics()\n self.assertEqual(m['num_batches'], [num_train_steps])\n self.assertEqual(m['num_examples'], [input_vocab_size * num_train_steps])\n self.assertGreater(m['loss'][0], 0.0)\n self.assertEqual(m['loss'][1], input_vocab_size * num_train_steps)\n self.assertGreater(m['mean_absolute_error'][0], 0)\n self.assertEqual(m['mean_absolute_error'][1], 300)\n\n def test_keras_model_multiple_inputs(self):\n input_spec = collections.OrderedDict(\n x=collections.OrderedDict(\n a=tf.TensorSpec(shape=[None, 1], dtype=tf.float32),\n b=tf.TensorSpec(shape=[1, 1], dtype=tf.float32)),\n y=tf.TensorSpec(shape=[None, 1], dtype=tf.float32))\n model = model_examples.build_multiple_inputs_keras_model()\n tff_model = keras_utils.from_keras_model(\n keras_model=model,\n input_spec=input_spec,\n loss=tf.keras.losses.MeanSquaredError(),\n metrics=[tf.keras.metrics.MeanAbsoluteError()])\n\n batch_size = 2\n real_batch = collections.OrderedDict(\n x=collections.OrderedDict(\n a=np.ones(shape=[batch_size, 1], dtype=np.float32),\n b=np.ones(shape=[batch_size, 1], dtype=np.float32)),\n y=np.asarray([[2.0], [2.0]]).astype(np.float32))\n\n num_train_steps = 2\n for _ in range(num_train_steps):\n tff_model.forward_pass(real_batch)\n\n m = tff_model.report_local_unfinalized_metrics()\n self.assertEqual(m['num_batches'], [num_train_steps])\n self.assertEqual(m['num_examples'], [batch_size * num_train_steps])\n self.assertGreater(m['loss'][0], 0.0)\n self.assertEqual(m['loss'][1], batch_size * num_train_steps)\n self.assertGreater(m['mean_absolute_error'][0], 0)\n self.assertEqual(m['mean_absolute_error'][1], 4)\n\n # Ensure we can assign the FL trained model weights to a new model.\n tff_weights = model_utils.ModelWeights.from_model(tff_model)\n keras_model = model_examples.build_multiple_inputs_keras_model()\n tff_weights.assign_weights_to(keras_model)\n loaded_model = keras_utils.from_keras_model(\n keras_model=keras_model,\n input_spec=input_spec,\n loss=tf.keras.losses.MeanSquaredError(),\n metrics=[tf.keras.metrics.MeanAbsoluteError()])\n\n orig_model_output = tff_model.forward_pass(real_batch)\n loaded_model_output = loaded_model.forward_pass(real_batch)\n self.assertAlmostEqual(orig_model_output.loss, loaded_model_output.loss)\n\n def test_keras_model_using_batch_norm_gets_warning(self):\n model = model_examples.build_conv_batch_norm_keras_model()\n input_spec = collections.OrderedDict(\n x=tf.TensorSpec(shape=[None, 28 * 28], dtype=tf.float32),\n y=tf.TensorSpec(shape=[None, 1], dtype=tf.int64))\n\n with warnings.catch_warnings(record=True) as warning:\n warnings.simplefilter('always')\n # Build a `tff.learning.Model` from a `tf.keras.Model`\n tff_model = keras_utils.from_keras_model(\n keras_model=model,\n input_spec=input_spec,\n loss=tf.keras.losses.SparseCategoricalCrossentropy(),\n metrics=[tf.keras.metrics.MeanAbsoluteError()])\n # Ensure we can get warning of Batch Normalization.\n self.assertLen(warning, 1)\n self.assertIsSubClass(warning[-1].category, UserWarning)\n self.assertRegex(str(warning[-1].message), 'Batch Normalization')\n\n batch_size = 2\n batch = collections.OrderedDict(\n x=np.random.uniform(low=0.0, high=1.0,\n size=[batch_size, 28 * 28]).astype(np.float32),\n y=np.random.random_integers(low=0, high=9, size=[batch_size,\n 1]).astype(np.int64))\n\n num_train_steps = 2\n for _ in range(num_train_steps):\n tff_model.forward_pass(batch)\n\n m = tff_model.report_local_unfinalized_metrics()\n self.assertEqual(m['num_batches'], [num_train_steps])\n self.assertEqual(m['num_examples'], [batch_size * num_train_steps])\n self.assertGreater(m['loss'][0], 0.0)\n self.assertEqual(m['loss'][1], batch_size * num_train_steps)\n self.assertGreater(m['mean_absolute_error'][0], 0)\n self.assertEqual(m['mean_absolute_error'][1], 4)\n\n # Ensure we can assign the FL trained model weights to a new model.\n tff_weights = model_utils.ModelWeights.from_model(tff_model)\n keras_model = model_examples.build_conv_batch_norm_keras_model()\n tff_weights.assign_weights_to(keras_model)\n\n def assert_all_weights_close(keras_weights, tff_weights):\n for keras_w, tff_w in zip(keras_weights, tff_weights):\n self.assertAllClose(\n keras_w, tff_w, atol=1e-4, msg='Variable [{}]'.format(keras_w.name))\n\n assert_all_weights_close(keras_model.trainable_weights,\n tff_weights.trainable)\n assert_all_weights_close(keras_model.non_trainable_weights,\n tff_weights.non_trainable)\n\n def test_keras_model_aggregated_metrics(self):\n feature_dims = 3\n num_train_steps = 3\n\n def _make_keras_model():\n keras_model = model_examples.build_linear_regression_keras_functional_model(\n feature_dims)\n return keras_model\n\n def _model_fn():\n return keras_utils.from_keras_model(\n keras_model=_make_keras_model(),\n input_spec=_create_whimsy_types(feature_dims),\n loss=tf.keras.losses.MeanSquaredError(),\n metrics=[tf.keras.metrics.MeanAbsoluteError()])\n\n @computations.tf_computation()\n def _train():\n # Create variables outside the tf.function.\n tff_model = _model_fn()\n optimizer = tf.keras.optimizers.SGD(0.1)\n\n @tf.function\n def _train_loop():\n for _ in range(num_train_steps):\n with tf.GradientTape() as tape:\n batch_output = tff_model.forward_pass(\n collections.OrderedDict(\n x=np.ones([2, feature_dims], dtype=np.float32),\n y=np.ones([2, 1], dtype=np.float32)))\n gradients = tape.gradient(batch_output.loss,\n tff_model.trainable_variables)\n optimizer.apply_gradients(\n zip(gradients, tff_model.trainable_variables))\n return (tff_model.report_local_unfinalized_metrics(),\n model_utils.ModelWeights.from_model(tff_model))\n\n return _train_loop()\n\n # Simulate 'CLIENT' local training.\n client_unfinalized_metrics, tff_weights = _train()\n\n # Simulate entering the 'SERVER' context.\n tf.keras.backend.clear_session()\n\n tff_model = _model_fn()\n metrics_aggregator = aggregator.sum_then_finalize\n unfinalized_metrics_type = type_conversions.type_from_tensors(\n tff_model.report_local_unfinalized_metrics())\n metrics_aggregation_computation = metrics_aggregator(\n tff_model.metric_finalizers(), unfinalized_metrics_type)\n aggregated_outputs = metrics_aggregation_computation(\n [client_unfinalized_metrics])\n self.assertEqual(aggregated_outputs['num_batches'], num_train_steps)\n self.assertEqual(aggregated_outputs['num_examples'], 2 * num_train_steps)\n self.assertGreater(aggregated_outputs['loss'], 0.0)\n self.assertGreater(aggregated_outputs['mean_absolute_error'], 0)\n\n keras_model = _make_keras_model()\n tff_weights.assign_weights_to(keras_model)\n\n def test_keras_model_metric_finalizers_work_with_report_local_unfinalized_metrics(\n self):\n feature_dims = 3\n tff_model = keras_utils.from_keras_model(\n keras_model=model_examples\n .build_linear_regression_keras_functional_model(feature_dims),\n input_spec=_create_whimsy_types(feature_dims),\n loss=tf.keras.losses.MeanSquaredError(),\n metrics=[\n counters.NumBatchesCounter(),\n counters.NumExamplesCounter(),\n tf.keras.metrics.MeanAbsoluteError()\n ])\n\n batch_input = collections.OrderedDict(\n x=np.ones([2, feature_dims], dtype=np.float32),\n y=np.ones([2, 1], dtype=np.float32))\n tff_model.forward_pass(batch_input)\n local_unfinalized_metrics = tff_model.report_local_unfinalized_metrics()\n\n # Creating a TFF computation is needed because the `tf.function`-decorated\n # `metric_finalizers` will create `tf.Variable`s on the non-first call (and\n # hence, will throw an error if it is directly invoked).\n @computations.tf_computation(\n type_conversions.type_from_tensors(local_unfinalized_metrics))\n def finalizer_computation(unfinalized_metrics):\n finalized_metrics = collections.OrderedDict()\n for metric_name, finalizer in tff_model.metric_finalizers().items():\n finalized_metrics[metric_name] = finalizer(\n unfinalized_metrics[metric_name])\n return finalized_metrics\n\n finalized_metrics = finalizer_computation(local_unfinalized_metrics)\n self.assertDictEqual(\n collections.OrderedDict(\n # The model is initialized with zeros, so `loss` (MeanSquaredError)\n # and `mean_absolute_error` are both 1.0.\n num_batches=1,\n num_examples=2,\n mean_absolute_error=1.0,\n loss=1.0),\n finalized_metrics)\n\n @parameterized.named_parameters(\n ('container', _create_input_spec_multiple_inputs_outputs()),\n ('container_fn',\n _make_test_batch(\n x=_create_input_spec_multiple_inputs_outputs()['x'],\n y=_create_input_spec_multiple_inputs_outputs()['y'])),\n ('tff_struct_with_python_type',\n computation_types.StructWithPythonType(\n _create_input_spec_multiple_inputs_outputs(),\n container_type=collections.OrderedDict)),\n ('tff_struct_type',\n computation_types.StructType(\n _create_input_spec_multiple_inputs_outputs())),\n )\n def test_keras_model_multiple_outputs(self, input_spec):\n keras_model = model_examples.build_multiple_outputs_keras_model()\n\n with self.subTest('loss_output_len_mismatch'):\n with self.assertRaises(ValueError):\n _ = keras_utils.from_keras_model(\n keras_model=keras_model,\n input_spec=input_spec,\n loss=[\n tf.keras.losses.MeanSquaredError(),\n tf.keras.losses.MeanSquaredError()\n ])\n\n with self.subTest('invalid_loss'):\n with self.assertRaises(TypeError):\n _ = keras_utils.from_keras_model(\n keras_model=keras_model, input_spec=input_spec, loss=3)\n\n with self.subTest('loss_as_dict_fails'):\n with self.assertRaises(TypeError):\n _ = keras_utils.from_keras_model(\n keras_model=keras_model,\n input_spec=input_spec,\n loss={\n 'dense_5': tf.keras.losses.MeanSquaredError(),\n 'dense_6': tf.keras.losses.MeanSquaredError(),\n 'whimsy': tf.keras.losses.MeanSquaredError()\n })\n\n with self.subTest('loss_list_no_opt'):\n tff_model = keras_utils.from_keras_model(\n keras_model=keras_model,\n input_spec=input_spec,\n loss=[\n tf.keras.losses.MeanSquaredError(),\n tf.keras.losses.MeanSquaredError(),\n tf.keras.losses.MeanSquaredError()\n ])\n\n self.assertIsInstance(tff_model, model_lib.Model)\n example_batch = collections.OrderedDict(\n x=[\n np.zeros([1, 1], dtype=np.float32),\n np.zeros([1, 1], dtype=np.float32)\n ],\n y=[\n np.zeros([1, 1], dtype=np.float32),\n np.ones([1, 1], dtype=np.float32),\n np.ones([1, 1], dtype=np.float32)\n ])\n output = tff_model.forward_pass(example_batch)\n self.assertAllClose(output.loss, 2.0)\n\n class CustomLoss(tf.keras.losses.Loss):\n\n def __init__(self):\n super().__init__(name='custom_loss')\n\n def call(self, y_true, y_pred):\n loss = tf.constant(0.0)\n for label, prediction in zip(y_true, y_pred):\n loss += tf.keras.losses.MeanSquaredError()(label, prediction)\n return loss\n\n keras_model = model_examples.build_multiple_outputs_keras_model()\n with self.subTest('single_custom_loss_can_work_with_multiple_outputs'):\n tff_model = keras_utils.from_keras_model(\n keras_model=keras_model, input_spec=input_spec, loss=CustomLoss())\n\n output = tff_model.forward_pass(example_batch)\n self.assertAllClose(output.loss, 2.0)\n\n keras_model = model_examples.build_multiple_outputs_keras_model()\n with self.subTest('loss_weights_as_list'):\n tff_model = keras_utils.from_keras_model(\n keras_model=keras_model,\n input_spec=input_spec,\n loss=[\n tf.keras.losses.MeanSquaredError(),\n tf.keras.losses.MeanSquaredError(),\n tf.keras.losses.MeanSquaredError()\n ],\n loss_weights=[0.1, 0.2, 0.3])\n\n output = tff_model.forward_pass(example_batch)\n self.assertAllClose(output.loss, 0.5)\n\n output = tff_model.forward_pass(example_batch)\n self.assertAllClose(output.loss, 0.5)\n\n with self.subTest('loss_weights_assert_fail_list'):\n with self.assertRaises(ValueError):\n _ = keras_utils.from_keras_model(\n keras_model=keras_model,\n input_spec=input_spec,\n loss=[\n tf.keras.losses.MeanSquaredError(),\n tf.keras.losses.MeanSquaredError(),\n tf.keras.losses.MeanSquaredError()\n ],\n loss_weights=[0.1, 0.2])\n\n with self.subTest('loss_weights_assert_fail_dict'):\n with self.assertRaises(TypeError):\n _ = keras_utils.from_keras_model(\n keras_model=keras_model,\n input_spec=input_spec,\n loss=[\n tf.keras.losses.MeanSquaredError(),\n tf.keras.losses.MeanSquaredError(),\n tf.keras.losses.MeanSquaredError()\n ],\n loss_weights={\n 'dense_5': 0.1,\n 'dense_6': 0.2,\n 'whimsy': 0.4\n })\n\n @parameterized.named_parameters(\n ('container', _create_input_spec_multiple_inputs_outputs()),\n ('container_fn',\n _make_test_batch(\n x=_create_input_spec_multiple_inputs_outputs()['x'],\n y=_create_input_spec_multiple_inputs_outputs()['y'])),\n ('tff_struct_with_python_type',\n computation_types.StructWithPythonType(\n _create_input_spec_multiple_inputs_outputs(),\n container_type=collections.OrderedDict)),\n ('tff_struct_type',\n computation_types.StructType(\n _create_input_spec_multiple_inputs_outputs())),\n )\n def test_regularized_keras_model_multiple_outputs(self, input_spec):\n keras_model = model_examples.build_multiple_outputs_regularized_keras_model(\n )\n\n with self.subTest('loss_output_len_mismatch'):\n with self.assertRaises(ValueError):\n _ = keras_utils.from_keras_model(\n keras_model=keras_model,\n input_spec=input_spec,\n loss=[\n tf.keras.losses.MeanSquaredError(),\n tf.keras.losses.MeanSquaredError()\n ])\n\n with self.subTest('invalid_loss'):\n with self.assertRaises(TypeError):\n _ = keras_utils.from_keras_model(\n keras_model=keras_model, input_spec=input_spec, loss=3)\n\n with self.subTest('loss_list_no_opt'):\n tff_model = keras_utils.from_keras_model(\n keras_model=keras_model,\n input_spec=input_spec,\n loss=[\n tf.keras.losses.MeanSquaredError(),\n tf.keras.losses.MeanSquaredError(),\n tf.keras.losses.MeanSquaredError()\n ])\n\n self.assertIsInstance(tff_model, model_lib.Model)\n example_batch = collections.OrderedDict(\n x=[\n np.zeros([1, 1], dtype=np.float32),\n np.zeros([1, 1], dtype=np.float32)\n ],\n y=[\n np.zeros([1, 1], dtype=np.float32),\n np.ones([1, 1], dtype=np.float32),\n np.ones([1, 1], dtype=np.float32)\n ])\n output = tff_model.forward_pass(example_batch)\n\n # Labels are (0, 1, 1), preds are (1, 1, 3).\n # Total MSE is 1**2 + 0**2 + 2**2 = 5.\n # Since all weights are initialized to ones and regularization constant is\n # 0.01, regularization loss is 0.01 * (num_params). There are 4 dense\n # layers that take in one input and produce one output, and these each\n # have a single weight and a single bias. There is one dense layer with\n # two inputs and one output, so it has two weights and a single bias.\n # So there are 11 params total and regularization loss is 0.11, for a\n # total batch loss of 5.11.\n self.assertAllClose(output.loss, 5.11)\n\n keras_model = model_examples.build_multiple_outputs_regularized_keras_model(\n )\n with self.subTest('loss_weights_as_list'):\n tff_model = keras_utils.from_keras_model(\n keras_model=keras_model,\n input_spec=input_spec,\n loss=[\n tf.keras.losses.MeanSquaredError(),\n tf.keras.losses.MeanSquaredError(),\n tf.keras.losses.MeanSquaredError()\n ],\n loss_weights=[0.1, 0.2, 0.3])\n\n output = tff_model.forward_pass(example_batch)\n\n # Labels are (0, 1, 1), preds are (1, 1, 3).\n # Weighted MSE is 0.1 * 1**2 + 0.2 * 0**2 + 0.3 * 2**2 = 1.3.\n # Regularization loss is 0.11 as before, for a total loss of 1.41.\n self.assertAllClose(output.loss, 1.41)\n\n output = tff_model.forward_pass(example_batch)\n self.assertAllClose(output.loss, 1.41)\n\n with self.subTest('loss_weights_assert_fail_list'):\n with self.assertRaises(ValueError):\n _ = keras_utils.from_keras_model(\n keras_model=keras_model,\n input_spec=input_spec,\n loss=[\n tf.keras.losses.MeanSquaredError(),\n tf.keras.losses.MeanSquaredError(),\n tf.keras.losses.MeanSquaredError()\n ],\n loss_weights=[0.1, 0.2])\n\n with self.subTest('loss_weights_assert_fail_dict'):\n with self.assertRaises(TypeError):\n _ = keras_utils.from_keras_model(\n keras_model=keras_model,\n input_spec=input_spec,\n loss=[\n tf.keras.losses.MeanSquaredError(),\n tf.keras.losses.MeanSquaredError(),\n tf.keras.losses.MeanSquaredError()\n ],\n loss_weights={\n 'dense_5': 0.1,\n 'dense_6': 0.2,\n 'whimsy': 0.4\n })\n\n def test_keras_model_lookup_table(self):\n model = model_examples.build_lookup_table_keras_model()\n input_spec = collections.OrderedDict(\n x=tf.TensorSpec(shape=[None, 1], dtype=tf.string),\n y=tf.TensorSpec(shape=[None, 1], dtype=tf.float32))\n tff_model = keras_utils.from_keras_model(\n keras_model=model,\n input_spec=input_spec,\n loss=tf.keras.losses.MeanSquaredError(),\n metrics=[tf.keras.metrics.MeanAbsoluteError()])\n\n batch_size = 3\n batch = collections.OrderedDict(\n x=tf.constant([['G'], ['B'], ['R']], dtype=tf.string),\n y=tf.constant([[1.0], [2.0], [3.0]], dtype=tf.float32))\n\n num_train_steps = 2\n for _ in range(num_train_steps):\n tff_model.forward_pass(batch)\n\n metrics = tff_model.report_local_unfinalized_metrics()\n self.assertEqual(metrics['num_batches'], [num_train_steps])\n self.assertEqual(metrics['num_examples'], [batch_size * num_train_steps])\n self.assertGreater(metrics['loss'][0], 0.0)\n self.assertEqual(metrics['loss'][1], batch_size * num_train_steps)\n self.assertGreater(metrics['mean_absolute_error'][0], 0)\n self.assertEqual(metrics['mean_absolute_error'][1], 6)\n\n # Ensure we can assign the FL trained model weights to a new model.\n tff_weights = model_utils.ModelWeights.from_model(tff_model)\n keras_model = model_examples.build_lookup_table_keras_model()\n tff_weights.assign_weights_to(keras_model)\n loaded_model = keras_utils.from_keras_model(\n keras_model=keras_model,\n input_spec=input_spec,\n loss=tf.keras.losses.MeanSquaredError(),\n metrics=[tf.keras.metrics.MeanAbsoluteError()])\n\n orig_model_output = tff_model.forward_pass(batch)\n loaded_model_output = loaded_model.forward_pass(batch)\n self.assertAlmostEqual(orig_model_output.loss, loaded_model_output.loss)\n\n def test_keras_model_preprocessing(self):\n self.skipTest('b/171254807')\n model = model_examples.build_preprocessing_lookup_keras_model()\n input_spec = collections.OrderedDict(\n x=tf.TensorSpec(shape=[None, 1], dtype=tf.string),\n y=tf.TensorSpec(shape=[None, 1], dtype=tf.float32))\n tff_model = keras_utils.from_keras_model(\n keras_model=model,\n input_spec=input_spec,\n loss=tf.keras.losses.MeanSquaredError(),\n metrics=[tf.keras.metrics.MeanAbsoluteError()])\n\n batch_size = 3\n batch = collections.OrderedDict(\n x=tf.constant([['A'], ['B'], ['A']], dtype=tf.string),\n y=tf.constant([[0], [1], [1]], dtype=tf.float32))\n\n num_train_steps = 2\n for _ in range(num_train_steps):\n tff_model.forward_pass(batch)\n\n metrics = tff_model.report_local_unfinalized_metrics()\n self.assertEqual(metrics['num_batches'], [num_train_steps])\n self.assertEqual(metrics['num_examples'], [batch_size * num_train_steps])\n self.assertGreater(metrics['loss'][0], 0.0)\n self.assertEqual(metrics['loss'][1], batch_size * num_train_steps)\n self.assertGreater(metrics['mean_absolute_error'][0], 0)\n self.assertEqual(metrics['mean_absolute_error'][1], 2)\n\n # Ensure we can assign the FL trained model weights to a new model.\n tff_weights = model_utils.ModelWeights.from_model(tff_model)\n keras_model = model_examples.build_lookup_table_keras_model()\n tff_weights.assign_weights_to(keras_model)\n loaded_model = keras_utils.from_keras_model(\n keras_model=keras_model,\n input_spec=input_spec,\n loss=tf.keras.losses.MeanSquaredError(),\n metrics=[tf.keras.metrics.MeanAbsoluteError()])\n\n orig_model_output = tff_model.forward_pass(batch)\n loaded_model_output = loaded_model.forward_pass(batch)\n self.assertAlmostEqual(orig_model_output.loss, loaded_model_output.loss)\n\n def test_keras_model_fails_compiled(self):\n feature_dims = 3\n keras_model = model_examples.build_linear_regression_keras_functional_model(\n feature_dims)\n\n keras_model.compile(loss=tf.keras.losses.MeanSquaredError())\n\n with self.assertRaisesRegex(ValueError, 'compile'):\n keras_utils.from_keras_model(\n keras_model=keras_model,\n input_spec=_create_whimsy_types(feature_dims),\n loss=tf.keras.losses.MeanSquaredError(),\n metrics=[tf.keras.metrics.MeanAbsoluteError()])\n\n def test_custom_keras_metric_with_extra_init_args_raises(self):\n\n class CustomCounter(tf.keras.metrics.Sum):\n \"\"\"A custom `tf.keras.metrics.Metric` with extra args in `__init__`.\"\"\"\n\n def __init__(self, name='new_counter', arg1=0, dtype=tf.int64):\n super().__init__(name, dtype)\n self._arg1 = arg1\n\n def update_state(self, y_true, y_pred, sample_weight=None):\n return super().update_state(1, sample_weight)\n\n feature_dims = 3\n keras_model = model_examples.build_linear_regression_keras_functional_model(\n feature_dims)\n tff_model = keras_utils.from_keras_model(\n keras_model=keras_model,\n input_spec=_create_whimsy_types(feature_dims),\n loss=tf.keras.losses.MeanSquaredError(),\n metrics=[CustomCounter(arg1=1)])\n metrics_aggregator = aggregator.sum_then_finalize\n unfinalized_metrics_type = type_conversions.type_from_tensors(\n tff_model.report_local_unfinalized_metrics())\n\n with self.assertRaisesRegex(TypeError, 'extra arguments'):\n metrics_aggregator(tff_model.metric_finalizers(),\n unfinalized_metrics_type)\n\n def test_custom_keras_metric_no_extra_init_args_builds(self):\n\n class CustomCounter(tf.keras.metrics.Sum):\n \"\"\"A custom `tf.keras.metrics.Metric` without extra args in `__init__`.\"\"\"\n\n def __init__(self, name='new_counter', arg1=0, dtype=tf.int64):\n super().__init__(name, dtype)\n self._arg1 = arg1\n\n def update_state(self, y_true, y_pred, sample_weight=None):\n return super().update_state(1, sample_weight)\n\n def get_config(self):\n config = super().get_config()\n config['arg1'] = self._arg1\n return config\n\n feature_dims = 3\n keras_model = model_examples.build_linear_regression_keras_functional_model(\n feature_dims)\n tff_model = keras_utils.from_keras_model(\n keras_model=keras_model,\n input_spec=_create_whimsy_types(feature_dims),\n loss=tf.keras.losses.MeanSquaredError(),\n metrics=[CustomCounter(arg1=1)])\n metrics_aggregator = aggregator.sum_then_finalize\n unfinalized_metrics_type = type_conversions.type_from_tensors(\n tff_model.report_local_unfinalized_metrics())\n federated_metrics_aggregation = metrics_aggregator(\n tff_model.metric_finalizers(), unfinalized_metrics_type)\n\n self.assertIsInstance(federated_metrics_aggregation,\n computation_base.Computation)\n\n @parameterized.named_parameters(\n # Test cases for the cartesian product of all parameter values.\n *_create_tff_model_from_keras_model_tuples())\n def test_keras_model_with_metric_constructors(self, feature_dims, model_fn):\n keras_model = model_fn(feature_dims)\n tff_model = keras_utils.from_keras_model(\n keras_model=keras_model,\n input_spec=_create_whimsy_types(feature_dims),\n loss=tf.keras.losses.MeanSquaredError(),\n metrics=[tf.keras.metrics.MeanAbsoluteError()])\n self.assertIsInstance(tff_model, model_lib.Model)\n\n # Metrics should be zero, though the model wrapper internally executes the\n # forward pass once.\n self.assertSequenceEqual(tff_model.local_variables,\n [0.0, 0.0, 0.0, 0.0, 0, 0])\n\n batch = _create_test_batch(feature_dims)\n # from_model() was called without an optimizer which creates a tff.Model.\n # There is no train_on_batch() method available in tff.Model.\n with self.assertRaisesRegex(AttributeError,\n 'no attribute \\'train_on_batch\\''):\n tff_model.train_on_batch(batch)\n\n output = tff_model.forward_pass(batch)\n # Since the model initializes all weights and biases to zero, we expect\n # all predictions to be zero:\n # 0*x1 + 0*x2 + ... + 0 = 0\n self.assertAllEqual(output.predictions, [[0.0], [0.0]])\n # For the single batch:\n #\n # Example | Prediction | Label | Residual | Loss\n # --------+------------+-------+----------+ -----\n # 1 | 0.0 | 0.0 | 0.0 | 0.0\n # 2 | 0.0 | 1.0 | 1.0 | 1.0\n #\n # Note that though regularization might be applied, this has no effect on\n # the loss since all weights are 0.\n # Total loss: 1.0\n # Batch average loss: 0.5\n self.assertEqual(output.loss, 0.5)\n metrics = tff_model.report_local_unfinalized_metrics()\n self.assertEqual(metrics['num_batches'], [1])\n self.assertEqual(metrics['num_examples'], [2])\n self.assertGreater(metrics['loss'][0], 0)\n self.assertEqual(metrics['loss'][1], 2)\n self.assertGreater(metrics['mean_absolute_error'][0], 0)\n self.assertEqual(metrics['mean_absolute_error'][1], 2)\n\n @parameterized.named_parameters(\n # Test cases for the cartesian product of all parameter values.\n *_create_tff_model_from_keras_model_tuples())\n def test_keras_model_without_input_metrics(self, feature_dims, model_fn):\n keras_model = model_fn(feature_dims)\n tff_model = keras_utils.from_keras_model(\n keras_model=keras_model,\n input_spec=_create_whimsy_types(feature_dims),\n loss=tf.keras.losses.MeanSquaredError())\n self.assertIsInstance(tff_model, model_lib.Model)\n\n # Metrics should be zero, though the model wrapper internally executes the\n # forward pass once.\n self.assertSequenceEqual(tff_model.local_variables, [0.0, 0.0, 0, 0])\n\n batch = _create_test_batch(feature_dims)\n # from_model() was called without an optimizer which creates a tff.Model.\n # There is no train_on_batch() method available in tff.Model.\n with self.assertRaisesRegex(AttributeError,\n 'no attribute \\'train_on_batch\\''):\n tff_model.train_on_batch(batch)\n\n output = tff_model.forward_pass(batch)\n # Since the model initializes all weights and biases to zero, we expect\n # all predictions to be zero:\n # 0*x1 + 0*x2 + ... + 0 = 0\n self.assertAllEqual(output.predictions, [[0.0], [0.0]])\n # For the single batch:\n #\n # Example | Prediction | Label | Residual | Loss\n # --------+------------+-------+----------+ -----\n # 1 | 0.0 | 0.0 | 0.0 | 0.0\n # 2 | 0.0 | 1.0 | 1.0 | 1.0\n #\n # Note that though regularization might be applied, this has no effect on\n # the loss since all weights are 0.\n # Total loss: 1.0\n # Batch average loss: 0.5\n self.assertEqual(output.loss, 0.5)\n metrics = tff_model.report_local_unfinalized_metrics()\n self.assertGreater(metrics['loss'][0], 0)\n self.assertEqual(metrics['loss'][1], 2)\n\n @parameterized.named_parameters(\n ('both_metrics_and_constructors',\n [counters.NumExamplesCounter,\n counters.NumBatchesCounter()], 'found both types'),\n ('non_callable', [tf.constant(1.0)], 'found a non-callable'),\n ('non_keras_metric_constructor', [tf.keras.losses.MeanSquaredError\n ], 'not a no-arg callable'))\n def test_keras_model_provided_invalid_metrics_raises(self, metrics,\n error_message):\n feature_dims = 3\n keras_model = model_examples.build_linear_regression_keras_functional_model(\n feature_dims)\n\n with self.assertRaisesRegex(TypeError, error_message):\n keras_utils.from_keras_model(\n keras_model=keras_model,\n input_spec=_create_whimsy_types(feature_dims),\n loss=tf.keras.losses.MeanSquaredError(),\n metrics=metrics)\n\n # The metric names are senseical normally, but we just want to assert that\n # our explicit metrics override the defaults.\n @parameterized.named_parameters(\n ('num_examples', tf.keras.metrics.MeanSquaredError('num_examples')),\n ('num_batches', tf.keras.metrics.MeanSquaredError('num_batches')),\n )\n def test_custom_metrics_override_defaults(self, metric):\n feature_dims = 3\n keras_model = model_examples.build_linear_regression_keras_functional_model(\n feature_dims)\n\n model = keras_utils.from_keras_model(\n keras_model=keras_model,\n input_spec=_create_whimsy_types(feature_dims),\n loss=tf.keras.losses.MeanSquaredError(),\n metrics=[metric])\n\n # By default the metrics have a single sum of count, but the test metrics\n # we add above have two values because they are a mean.\n self.assertLen(model.report_local_unfinalized_metrics()[metric.name], 2)\n\n @parameterized.named_parameters(\n # Test cases for the cartesian product of all parameter values.\n *_create_tff_model_from_keras_model_tuples())\n def test_tff_model_from_keras_model_resets_metrics(self, feature_dims,\n model_fn):\n keras_model = model_fn(feature_dims)\n tff_model = keras_utils.from_keras_model(\n keras_model=keras_model,\n input_spec=_create_whimsy_types(feature_dims),\n loss=tf.keras.losses.MeanSquaredError(),\n metrics=[tf.keras.metrics.MeanAbsoluteError()])\n self.assertIsInstance(tff_model, model_lib.Model)\n\n expected_initial_local_variables = [0.0, 0.0, 0.0, 0.0, 0, 0]\n self.assertSequenceEqual(tff_model.local_variables,\n expected_initial_local_variables)\n\n # Execute the forward pass once, and assert the metrics values are not zero.\n batch = _create_test_batch(feature_dims)\n output = tff_model.forward_pass(batch)\n self.assertEqual(output.loss, 0.5)\n metrics = tff_model.report_local_unfinalized_metrics()\n self.assertEqual(metrics['num_batches'], [1])\n self.assertEqual(metrics['num_examples'], [2])\n self.assertSequenceEqual(metrics['loss'], [1, 2])\n self.assertSequenceEqual(metrics['mean_absolute_error'], [1, 2])\n\n # Reset all of the metric state variables.\n tff_model.reset_metrics()\n self.assertSequenceEqual(tff_model.local_variables,\n expected_initial_local_variables)\n metrics = tff_model.report_local_unfinalized_metrics()\n self.assertEqual(metrics['num_batches'], [0])\n self.assertEqual(metrics['num_examples'], [0])\n self.assertSequenceEqual(metrics['loss'], [0, 0])\n self.assertSequenceEqual(metrics['mean_absolute_error'], [0, 0])\n\nif __name__ == '__main__':\n execution_contexts.set_local_python_execution_context()\n test_case.main()\n",
"# Copyright 2018, The TensorFlow Federated 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\nimport collections\n\nfrom absl.testing import parameterized\nimport tensorflow as tf\n\nfrom tensorflow_federated.python.core.api import computations\nfrom tensorflow_federated.python.core.api import test_case\nfrom tensorflow_federated.python.core.backends.native import execution_contexts\nfrom tensorflow_federated.python.learning import model_examples\n\n\nclass ModelExamplesTest(test_case.TestCase, parameterized.TestCase):\n\n @parameterized.named_parameters(('', 1), ('_three_features', 3))\n def test_linear_regression(self, feature_dim):\n model = model_examples.LinearRegression(feature_dim=feature_dim)\n\n expected_initial_local_variables = [0, 0, 0.0]\n self.assertSequenceEqual(model.local_variables,\n expected_initial_local_variables)\n\n batch = collections.OrderedDict(\n x=tf.constant([[0.0] * feature_dim, [1.0] * feature_dim]),\n y=tf.constant([[0.0], [1.0]]))\n\n output = model.forward_pass(batch)\n\n self.assertAllEqual(output.predictions, [[0.0], [0.0]])\n # The residuals are (0., 1.), so average loss is 0.5 * 0.5 * 1.\n self.assertEqual(output.loss, 0.25)\n unfinalized_metrics = model.report_local_unfinalized_metrics()\n self.assertEqual(unfinalized_metrics,\n collections.OrderedDict(loss=[0.5, 2.0], num_examples=2))\n finalized_metrics = collections.OrderedDict(\n (metric_name, finalizer(unfinalized_metrics[metric_name]))\n for metric_name, finalizer in model.metric_finalizers().items())\n self.assertEqual(finalized_metrics,\n collections.OrderedDict(loss=0.25, num_examples=2))\n\n # Ensure reset_metrics works.\n model.reset_metrics()\n self.assertSequenceEqual(model.local_variables,\n expected_initial_local_variables)\n unfinalized_metrics = model.report_local_unfinalized_metrics()\n self.assertEqual(unfinalized_metrics,\n collections.OrderedDict(loss=[0, 0], num_examples=0))\n\n def test_tff(self):\n feature_dim = 2\n\n @computations.tf_computation\n def forward_pass_and_output():\n model = model_examples.LinearRegression(feature_dim)\n\n @tf.function\n def _train(batch):\n batch_output = model.forward_pass(batch)\n unfinalized_metrics = model.report_local_unfinalized_metrics()\n return batch_output, unfinalized_metrics\n\n return _train(\n batch=collections.OrderedDict(\n x=tf.constant([[0.0, 0.0], [1.0, 1.0]]),\n y=tf.constant([[0.0], [1.0]])))\n\n batch_output, unfinalized_metrics = forward_pass_and_output()\n self.assertAllEqual(batch_output.predictions, [[0.0], [0.0]])\n self.assertEqual(batch_output.loss, 0.25)\n self.assertEqual(unfinalized_metrics,\n collections.OrderedDict(loss=[0.5, 2.0], num_examples=2))\n model = model_examples.LinearRegression(feature_dim)\n finalized_metrics = collections.OrderedDict(\n (metric_name, finalizer(unfinalized_metrics[metric_name]))\n for metric_name, finalizer in model.metric_finalizers().items())\n self.assertEqual(finalized_metrics,\n collections.OrderedDict(loss=0.25, num_examples=2))\n\n\nif __name__ == '__main__':\n execution_contexts.set_local_python_execution_context()\n test_case.main()\n",
"# Copyright 2021, The TensorFlow Federated 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\nimport csv\nimport os\nimport os.path\nimport shutil\nfrom typing import Any, Dict, Iterable, List, Mapping, Sequence, Tuple\nfrom unittest import mock\n\nfrom absl.testing import absltest\nfrom absl.testing import parameterized\nimport numpy as np\nimport tensorflow as tf\nimport tree\n\nfrom tensorflow_federated.python.program import file_release_manager\nfrom tensorflow_federated.python.program import file_utils\nfrom tensorflow_federated.python.program import test_utils\n\n\ndef _read_values_from_csv(\n file_path: os.PathLike) -> Tuple[List[str], List[Dict[str, Any]]]:\n with tf.io.gfile.GFile(file_path, 'r') as file:\n reader = csv.DictReader(file)\n fieldnames = list(reader.fieldnames)\n values = list(reader)\n return fieldnames, values\n\n\ndef _write_values_to_csv(file_path: os.PathLike, fieldnames: Sequence[str],\n values: Iterable[Mapping[str, Any]]):\n with tf.io.gfile.GFile(file_path, 'w') as file:\n writer = csv.DictWriter(file, fieldnames=fieldnames)\n writer.writeheader()\n for value in values:\n writer.writerow(value)\n\n\nclass CSVFileReleaseManagerInitTest(parameterized.TestCase):\n\n def test_creates_file_path(self):\n temp_file = self.create_tempfile()\n os.remove(temp_file)\n self.assertFalse(os.path.exists(temp_file))\n\n file_release_manager.CSVFileReleaseManager(file_path=temp_file)\n\n self.assertTrue(os.path.exists(temp_file))\n\n def test_creates_file_dir(self):\n temp_dir = self.create_tempdir()\n shutil.rmtree(temp_dir)\n self.assertFalse(os.path.exists(temp_dir))\n temp_file = os.path.join(temp_dir, 'a')\n\n file_release_manager.CSVFileReleaseManager(file_path=temp_file)\n\n self.assertTrue(os.path.exists(temp_file))\n\n def test_initializes_with_empty_file(self):\n temp_file = self.create_tempfile()\n _write_values_to_csv(file_path=temp_file, fieldnames=['key'], values=[])\n self.assertTrue(os.path.exists(temp_file))\n\n release_mngr = file_release_manager.CSVFileReleaseManager(\n file_path=temp_file)\n\n self.assertIsNone(release_mngr._latest_key)\n\n def test_initializes_with_existing_file(self):\n temp_file = self.create_tempfile()\n _write_values_to_csv(\n file_path=temp_file,\n fieldnames=['key', 'a', 'b'],\n values=[{\n 'key': 1,\n 'a': 10,\n 'b': 20\n }])\n self.assertTrue(os.path.exists(temp_file))\n\n release_mngr = file_release_manager.CSVFileReleaseManager(\n file_path=temp_file)\n\n self.assertEqual(release_mngr._latest_key, 1)\n\n def test_does_not_raise_type_error_with_file_path_str(self):\n temp_file = self.create_tempfile()\n os.remove(temp_file)\n\n try:\n file_release_manager.CSVFileReleaseManager(file_path=temp_file)\n except TypeError:\n self.fail('Raised TypeError unexpectedly.')\n\n def test_does_not_raise_type_error_with_file_path_path_like(self):\n temp_file = self.create_tempfile()\n os.remove(temp_file)\n\n try:\n file_release_manager.CSVFileReleaseManager(file_path=temp_file)\n except TypeError:\n self.fail('Raised TypeError unexpectedly.')\n\n @parameterized.named_parameters(\n ('none', None),\n ('bool', True),\n ('int', 1),\n ('list', []),\n )\n def test_raises_type_error_with_file_path(self, file_path):\n with self.assertRaises(TypeError):\n file_release_manager.CSVFileReleaseManager(file_path=file_path)\n\n def test_raises_value_error_with_file_path_empty(self):\n with self.assertRaises(ValueError):\n file_release_manager.CSVFileReleaseManager(file_path='')\n\n def test_does_not_raise_type_error_with_save_mode(self):\n temp_file = self.create_tempfile()\n os.remove(temp_file)\n\n try:\n file_release_manager.CSVFileReleaseManager(\n file_path=temp_file,\n save_mode=file_release_manager.CSVSaveMode.APPEND)\n except TypeError:\n self.fail('Raised TypeError unexpectedly.')\n\n @parameterized.named_parameters(\n ('none', None),\n ('bool', True),\n ('int', 1),\n ('str', 'a'),\n ('list', []),\n )\n def test_raises_type_error_with_save_mode(self, save_mode):\n temp_file = self.create_tempfile()\n os.remove(temp_file)\n\n with self.assertRaises(TypeError):\n file_release_manager.CSVFileReleaseManager(\n file_path=temp_file, save_mode=save_mode)\n\n def test_does_not_raise_type_error_with_key_fieldname(self):\n temp_file = self.create_tempfile()\n os.remove(temp_file)\n\n try:\n file_release_manager.CSVFileReleaseManager(\n file_path=temp_file, key_fieldname='z')\n except TypeError:\n self.fail('Raised TypeError unexpectedly.')\n\n @parameterized.named_parameters(\n ('none', None),\n ('bool', True),\n ('int', 1),\n ('list', []),\n )\n def test_raises_type_error_with_key_fieldname(self, key_fieldname):\n temp_file = self.create_tempfile()\n os.remove(temp_file)\n\n with self.assertRaises(TypeError):\n file_release_manager.CSVFileReleaseManager(\n file_path=temp_file, key_fieldname=key_fieldname)\n\n def test_raises_value_error_with_key_fieldname_empty(self):\n temp_file = self.create_tempfile()\n os.remove(temp_file)\n\n with self.assertRaises(ValueError):\n file_release_manager.CSVFileReleaseManager(\n file_path=temp_file, key_fieldname='')\n\n def test_raises_incompatible_file_error_with_unknown_key_fieldname(self):\n temp_file = self.create_tempfile()\n _write_values_to_csv(\n file_path=temp_file,\n fieldnames=['z', 'a', 'b'],\n values=[{\n 'z': 1,\n 'a': 10,\n 'b': 20\n }])\n\n with self.assertRaises(\n file_release_manager.FileReleaseManagerIncompatibleFileError):\n file_release_manager.CSVFileReleaseManager(file_path=temp_file)\n\n def test_raises_incompatible_file_error_with_unknown_file(self):\n temp_file = self.create_tempfile()\n\n with self.assertRaises(\n file_release_manager.FileReleaseManagerIncompatibleFileError):\n file_release_manager.CSVFileReleaseManager(file_path=temp_file)\n\n\nclass CSVFileReleaseManagerReadValuesTest(parameterized.TestCase):\n\n def test_returns_values_from_empty_file(self):\n temp_file = self.create_tempfile()\n os.remove(temp_file)\n release_mngr = file_release_manager.CSVFileReleaseManager(\n file_path=temp_file)\n\n fieldnames, values = release_mngr._read_values()\n\n self.assertEqual(fieldnames, ['key'])\n self.assertEqual(values, [])\n\n # pyformat: disable\n @parameterized.named_parameters(\n ('no_values', ['key', 'a', 'b'], []),\n ('one_value', ['key', 'a', 'b'], [{'key': 1, 'a': 10, 'b': 20}]),\n ('two_values', ['key', 'a', 'b'],\n [{'key': 1, 'a': 10, 'b': 20},\n {'key': 1, 'a': 11, 'b': 21}]),\n )\n # pyformat: enable\n def test_returns_values_from_existing_file(self, fieldnames, values):\n temp_file = self.create_tempfile()\n _write_values_to_csv(\n file_path=temp_file, fieldnames=fieldnames, values=values)\n release_mngr = file_release_manager.CSVFileReleaseManager(\n file_path=temp_file)\n\n actual_fieldnames, actual_values = release_mngr._read_values()\n\n self.assertEqual(actual_fieldnames, fieldnames)\n expected_values = tree.map_structure(str, values)\n self.assertEqual(actual_values, expected_values)\n\n\nclass CSVFileReleaseManagerWriteValuesTest(parameterized.TestCase):\n\n # pyformat: disable\n @parameterized.named_parameters(\n ('no_values', ['key', 'a', 'b'], []),\n ('one_value', ['key', 'a', 'b'], [{'key': 1, 'a': 10, 'b': 20}]),\n ('two_values', ['key', 'a', 'b'],\n [{'key': 1, 'a': 10, 'b': 20},\n {'key': 1, 'a': 11, 'b': 21}]),\n )\n # pyformat: enable\n def test_writes_values_to_empty_file(self, fieldnames, values):\n temp_file = self.create_tempfile()\n os.remove(temp_file)\n release_mngr = file_release_manager.CSVFileReleaseManager(\n file_path=temp_file)\n\n release_mngr._write_values(fieldnames=fieldnames, values=values)\n\n actual_fieldnames, actual_values = _read_values_from_csv(temp_file)\n self.assertEqual(actual_fieldnames, fieldnames)\n expected_values = tree.map_structure(str, values)\n self.assertEqual(actual_values, expected_values)\n\n # pyformat: disable\n @parameterized.named_parameters(\n ('no_values', ['key', 'a', 'b'], []),\n ('one_value', ['key', 'a', 'b'], [{'key': 1, 'a': 10, 'b': 20}]),\n ('two_values', ['key', 'a', 'b'],\n [{'key': 1, 'a': 10, 'b': 20},\n {'key': 1, 'a': 11, 'b': 21}]),\n )\n # pyformat: enable\n def test_writes_values_to_existing_file(self, fieldnames, values):\n temp_file = self.create_tempfile()\n _write_values_to_csv(\n file_path=temp_file,\n fieldnames=['key', 'a', 'b'],\n values=[{\n 'key': 1,\n 'a': 10,\n 'b': 20\n }])\n release_mngr = file_release_manager.CSVFileReleaseManager(\n file_path=temp_file)\n\n release_mngr._write_values(fieldnames=fieldnames, values=values)\n\n actual_fieldnames, actual_values = _read_values_from_csv(temp_file)\n self.assertEqual(actual_fieldnames, fieldnames)\n expected_values = tree.map_structure(str, values)\n self.assertEqual(actual_values, expected_values)\n\n\nclass CSVFileReleaseManagerWriteValueTest(parameterized.TestCase):\n\n # pyformat: disable\n @parameterized.named_parameters(\n ('empty', {}),\n ('more_fields', {'a': 11, 'b': 21, 'c': 31}),\n )\n # pyformat: enable\n def test_writes_value_to_empty_file(self, value):\n temp_file = self.create_tempfile()\n os.remove(temp_file)\n release_mngr = file_release_manager.CSVFileReleaseManager(\n file_path=temp_file, save_mode=file_release_manager.CSVSaveMode.WRITE)\n\n release_mngr._write_value(value)\n\n actual_fieldnames, actual_values = _read_values_from_csv(temp_file)\n expected_fieldnames = ['key']\n expected_fieldnames.extend(\n [x for x in value.keys() if x not in expected_fieldnames])\n self.assertEqual(actual_fieldnames, expected_fieldnames)\n expected_value = {name: '' for name in expected_fieldnames}\n expected_value.update(value)\n expected_values = [expected_value]\n expected_values = tree.map_structure(str, expected_values)\n self.assertEqual(actual_values, expected_values)\n\n # pyformat: disable\n @parameterized.named_parameters(\n ('empty', {}),\n ('same_fields', {'a': 11, 'b': 21}),\n ('less_fields', {'a': 11}),\n ('more_fields', {'a': 11, 'b': 21, 'c': 31}),\n )\n # pyformat: enable\n def test_writes_value_to_existing_file(self, value):\n temp_file = self.create_tempfile()\n existing_fieldnames = ['key', 'a', 'b']\n existing_value = {'key': 1, 'a': 10, 'b': 20}\n _write_values_to_csv(\n file_path=temp_file,\n fieldnames=existing_fieldnames,\n values=[existing_value])\n release_mngr = file_release_manager.CSVFileReleaseManager(\n file_path=temp_file, save_mode=file_release_manager.CSVSaveMode.WRITE)\n\n release_mngr._write_value(value)\n\n actual_fieldnames, actual_values = _read_values_from_csv(temp_file)\n expected_fieldnames = existing_fieldnames.copy()\n expected_fieldnames.extend(\n [x for x in value.keys() if x not in expected_fieldnames])\n self.assertEqual(actual_fieldnames, expected_fieldnames)\n expected_value1 = {name: '' for name in expected_fieldnames}\n expected_value1.update(existing_value)\n expected_value2 = {name: '' for name in expected_fieldnames}\n expected_value2.update(value)\n expected_values = [expected_value1, expected_value2]\n expected_values = tree.map_structure(str, expected_values)\n self.assertEqual(actual_values, expected_values)\n\n\nclass CSVFileReleaseManagerAppendValueTest(parameterized.TestCase):\n\n # pyformat: disable\n @parameterized.named_parameters(\n ('empty', {}),\n ('more_fields', {'a': 11, 'b': 21, 'c': 31}),\n )\n # pyformat: enable\n def test_appends_value_to_empty_file(self, value):\n temp_file = self.create_tempfile()\n os.remove(temp_file)\n release_mngr = file_release_manager.CSVFileReleaseManager(\n file_path=temp_file, save_mode=file_release_manager.CSVSaveMode.APPEND)\n\n release_mngr._append_value(value)\n\n actual_fieldnames, actual_values = _read_values_from_csv(temp_file)\n expected_fieldnames = ['key']\n expected_fieldnames.extend(\n [x for x in value.keys() if x not in expected_fieldnames])\n self.assertEqual(actual_fieldnames, expected_fieldnames)\n expected_value = {name: '' for name in expected_fieldnames}\n expected_value.update(value)\n expected_values = [expected_value]\n expected_values = tree.map_structure(str, expected_values)\n self.assertEqual(actual_values, expected_values)\n\n # pyformat: disable\n @parameterized.named_parameters(\n ('empty', {}),\n ('same_fields', {'a': 11, 'b': 21}),\n ('less_fields', {'a': 11}),\n ('more_fields', {'a': 11, 'b': 21, 'c': 31}),\n )\n # pyformat: enable\n def test_appends_value_to_existing_file(self, value):\n temp_file = self.create_tempfile()\n existing_fieldnames = ['key', 'a', 'b']\n existing_value = {'key': 1, 'a': 10, 'b': 20}\n _write_values_to_csv(\n file_path=temp_file,\n fieldnames=existing_fieldnames,\n values=[existing_value])\n release_mngr = file_release_manager.CSVFileReleaseManager(\n file_path=temp_file, save_mode=file_release_manager.CSVSaveMode.APPEND)\n\n release_mngr._append_value(value)\n\n actual_fieldnames, actual_values = _read_values_from_csv(temp_file)\n expected_fieldnames = existing_fieldnames.copy()\n expected_fieldnames.extend(\n [x for x in value.keys() if x not in expected_fieldnames])\n self.assertEqual(actual_fieldnames, expected_fieldnames)\n expected_value1 = {name: '' for name in expected_fieldnames}\n expected_value1.update(existing_value)\n expected_value2 = {name: '' for name in expected_fieldnames}\n expected_value2.update(value)\n expected_values = [expected_value1, expected_value2]\n expected_values = tree.map_structure(str, expected_values)\n self.assertEqual(actual_values, expected_values)\n\n def test_raises_permission_denied_error(self):\n temp_file = self.create_tempfile()\n os.remove(temp_file)\n release_mngr = file_release_manager.CSVFileReleaseManager(\n file_path=temp_file, save_mode=file_release_manager.CSVSaveMode.APPEND)\n\n with mock.patch.object(csv.DictWriter, 'writerow') as mock_writerow:\n mock_writerow.side_effect = csv.Error()\n\n with self.assertRaises(\n file_release_manager.FileReleaseManagerPermissionDeniedError):\n release_mngr._append_value({})\n\n\nclass CSVFileReleaseManagerRemoveValuesGreaterThanTest(parameterized.TestCase):\n\n @parameterized.named_parameters(\n ('0', 0),\n ('1', 1),\n )\n def test_removes_values_from_empty_file(self, key):\n temp_file = self.create_tempfile()\n os.remove(temp_file)\n release_mngr = file_release_manager.CSVFileReleaseManager(\n file_path=temp_file)\n\n release_mngr._remove_values_greater_than(key)\n\n actual_fieldnames, actual_values = _read_values_from_csv(temp_file)\n self.assertEqual(actual_fieldnames, ['key'])\n self.assertEqual(actual_values, [])\n\n @parameterized.named_parameters(\n ('0', 0),\n ('1', 1),\n ('2', 2),\n )\n def test_removes_values_from_existing_file(self, key):\n temp_file = self.create_tempfile()\n existing_fieldnames = ['key', 'a', 'b']\n existing_values = [\n {\n 'key': 1,\n 'a': 10,\n 'b': 20\n },\n {\n 'key': 2,\n 'a': 11,\n 'b': 21\n },\n ]\n _write_values_to_csv(\n file_path=temp_file,\n fieldnames=existing_fieldnames,\n values=existing_values)\n release_mngr = file_release_manager.CSVFileReleaseManager(\n file_path=temp_file)\n\n release_mngr._remove_values_greater_than(key)\n\n actual_fieldnames, actual_values = _read_values_from_csv(temp_file)\n if key == 0:\n expected_fieldnames = ['key']\n else:\n expected_fieldnames = existing_fieldnames\n self.assertEqual(actual_fieldnames, expected_fieldnames)\n expected_values = existing_values[0:key]\n expected_values = tree.map_structure(str, expected_values)\n self.assertEqual(actual_values, expected_values)\n\n @parameterized.named_parameters(\n ('none', None),\n ('str', 'a'),\n ('list', []),\n )\n def test_raises_type_error_with_key(self, key):\n temp_file = self.create_tempfile()\n os.remove(temp_file)\n release_mngr = file_release_manager.CSVFileReleaseManager(\n file_path=temp_file)\n\n with self.assertRaises(TypeError):\n release_mngr._remove_values_greater_than(key)\n\n\nclass CSVFileReleaseManagerReleaseTest(parameterized.TestCase):\n\n def test_calls_remove_values_greater_than_with_empty_file(self):\n temp_file = self.create_tempfile()\n os.remove(temp_file)\n release_mngr = file_release_manager.CSVFileReleaseManager(\n file_path=temp_file)\n\n with mock.patch.object(\n release_mngr,\n '_remove_values_greater_than') as mock_remove_values_greater_than:\n release_mngr.release({'a': 10, 'b': 20}, 1)\n\n mock_remove_values_greater_than.assert_called_with(0)\n\n self.assertEqual(release_mngr._latest_key, 1)\n\n def test_calls_remove_values_greater_than_with_existing_file(self):\n temp_file = self.create_tempfile()\n _write_values_to_csv(\n file_path=temp_file,\n fieldnames=['key', 'a', 'b'],\n values=[{\n 'key': 1,\n 'a': 10,\n 'b': 20\n }])\n release_mngr = file_release_manager.CSVFileReleaseManager(\n file_path=temp_file)\n\n with mock.patch.object(\n release_mngr,\n '_remove_values_greater_than') as mock_remove_values_greater_than:\n release_mngr.release({'a': 11, 'b': 21}, 1)\n\n mock_remove_values_greater_than.assert_called_with(0)\n\n self.assertEqual(release_mngr._latest_key, 1)\n\n # pyformat: disable\n @parameterized.named_parameters(\n ('empty', {}, 1),\n ('more_fields', {'a': 10, 'b': 20}, 1),\n )\n # pyformat: enable\n def test_calls_append_value(self, value, key):\n temp_file = self.create_tempfile()\n os.remove(temp_file)\n release_mngr = file_release_manager.CSVFileReleaseManager(\n file_path=temp_file, save_mode=file_release_manager.CSVSaveMode.APPEND)\n\n with mock.patch.object(release_mngr, '_append_value') as mock_append_value:\n release_mngr.release(value, key)\n\n mock_append_value.assert_called_once()\n call = mock_append_value.mock_calls[0]\n _, args, _ = call\n actual_value, = args\n expected_fieldnames = ['key']\n expected_fieldnames.extend(\n [x for x in value.keys() if x not in expected_fieldnames])\n expected_value = {name: '' for name in expected_fieldnames}\n expected_value.update({'key': key})\n expected_value.update(value)\n self.assertEqual(actual_value, expected_value)\n\n self.assertEqual(release_mngr._latest_key, key)\n\n # pyformat: disable\n @parameterized.named_parameters(\n ('empty', {}, 1),\n ('more_fields', {'a': 10, 'b': 20}, 1),\n )\n # pyformat: enable\n def test_calls_write_value(self, value, key):\n temp_file = self.create_tempfile()\n os.remove(temp_file)\n release_mngr = file_release_manager.CSVFileReleaseManager(\n file_path=temp_file, save_mode=file_release_manager.CSVSaveMode.WRITE)\n\n with mock.patch.object(release_mngr, '_write_value') as mock_write_value:\n release_mngr.release(value, key)\n\n mock_write_value.assert_called_once()\n call = mock_write_value.mock_calls[0]\n _, args, _ = call\n actual_value, = args\n expected_fieldnames = ['key']\n expected_fieldnames.extend(\n [x for x in value.keys() if x not in expected_fieldnames])\n expected_value = {name: '' for name in expected_fieldnames}\n expected_value.update({'key': key})\n expected_value.update(value)\n self.assertEqual(actual_value, expected_value)\n\n self.assertEqual(release_mngr._latest_key, key)\n\n # pyformat: disable\n @parameterized.named_parameters(\n ('none', None, [{'key': '1', '': ''}]),\n ('bool', True, [{'key': '1', '': 'True'}]),\n ('int', 1, [{'key': '1', '': '1'}]),\n ('str', 'a', [{'key': '1', '': 'a'}]),\n ('list',\n [True, 1, 'a'],\n [{'key': '1', '0': 'True', '1': '1', '2': 'a'}]),\n ('list_empty', [], [{'key': '1'}]),\n ('list_nested',\n [[True, 1], ['a']],\n [{'key': '1', '0/0': 'True', '0/1': '1', '1/0': 'a'}]),\n ('dict',\n {'a': True, 'b': 1, 'c': 'a'},\n [{'key': '1', 'a': 'True', 'b': '1', 'c': 'a'}]),\n ('dict_empty', {}, [{'key': '1'}]),\n ('dict_nested',\n {'x': {'a': True, 'b': 1}, 'y': {'c': 'a'}},\n [{'key': '1', 'x/a': 'True', 'x/b': '1', 'y/c': 'a'}]),\n ('attr',\n test_utils.TestAttrObject1(True, 1),\n [{'key': '1', 'a': 'True', 'b': '1'}]),\n ('attr_nested',\n {'a': [test_utils.TestAttrObject1(True, 1)],\n 'b': test_utils.TestAttrObject2('a')},\n [{'key': '1', 'a/0/a': 'True', 'a/0/b': '1', 'b/a': 'a'}]),\n ('tensor_int', tf.constant(1), [{'key': '1', '': '1'}]),\n ('tensor_str', tf.constant('a'), [{'key': '1', '': 'b\\'a\\''}]),\n ('tensor_2d',\n tf.ones((2, 3)),\n [{'key': '1', '': '[[1.0, 1.0, 1.0], [1.0, 1.0, 1.0]]'}]),\n ('tensor_nested',\n {'a': [tf.constant(True), tf.constant(1)], 'b': [tf.constant('a')]},\n [{'key': '1', 'a/0': 'True', 'a/1': '1', 'b/0': 'b\\'a\\''}]),\n ('numpy_int', np.int32(1), [{'key': '1', '': '1'}]),\n ('numpy_2d',\n np.ones((2, 3)),\n [{'key': '1', '': '[[1.0, 1.0, 1.0], [1.0, 1.0, 1.0]]'}]),\n ('numpy_nested',\n {'a': [np.bool(True), np.int32(1)], 'b': [np.str_('a')]},\n [{'key': '1', 'a/0': 'True', 'a/1': '1', 'b/0': 'a'}]),\n ('materializable_value_reference_tensor',\n test_utils.TestMaterializableValueReference(1),\n [{'key': '1', '': '1'}]),\n ('materializable_value_reference_sequence',\n test_utils.TestMaterializableValueReference(\n tf.data.Dataset.from_tensor_slices([1, 2, 3])),\n [{'key': '1', '': '[1, 2, 3]'}]),\n ('materializable_value_reference_nested',\n {'a': [test_utils.TestMaterializableValueReference(True),\n test_utils.TestMaterializableValueReference(1)],\n 'b': [test_utils.TestMaterializableValueReference('a')]},\n [{'key': '1', 'a/0': 'True', 'a/1': '1', 'b/0': 'a'}]),\n ('materializable_value_reference_and_materialized_value',\n [1, test_utils.TestMaterializableValueReference(2)],\n [{'key': '1', '0': '1', '1': '2'}]),\n )\n # pyformat: enable\n def test_writes_value(self, value, expected_value):\n temp_file = self.create_tempfile()\n os.remove(temp_file)\n release_mngr = file_release_manager.CSVFileReleaseManager(\n file_path=temp_file)\n\n release_mngr.release(value, 1)\n\n _, actual_value = _read_values_from_csv(temp_file)\n self.assertEqual(actual_value, expected_value)\n\n @parameterized.named_parameters(\n ('none', None),\n ('str', 'a'),\n ('list', []),\n )\n def test_raises_type_error_with_key(self, key):\n temp_file = self.create_tempfile()\n os.remove(temp_file)\n release_mngr = file_release_manager.CSVFileReleaseManager(\n file_path=temp_file)\n\n with self.assertRaises(TypeError):\n release_mngr.release({}, key)\n\n\nclass SavedModelFileReleaseManagerInitTest(parameterized.TestCase):\n\n def test_creates_root_dir(self):\n temp_dir = self.create_tempdir()\n shutil.rmtree(temp_dir)\n self.assertFalse(os.path.exists(temp_dir))\n\n file_release_manager.SavedModelFileReleaseManager(root_dir=temp_dir)\n\n self.assertTrue(os.path.exists(temp_dir))\n\n def test_does_not_raise_type_error_with_root_dir_str(self):\n temp_dir = self.create_tempdir()\n\n try:\n file_release_manager.SavedModelFileReleaseManager(\n root_dir=temp_dir, prefix='a_')\n except TypeError:\n self.fail('Raised TypeError unexpectedly.')\n\n def test_does_not_raise_type_error_with_root_dir_path_like(self):\n temp_dir = self.create_tempdir()\n\n try:\n file_release_manager.SavedModelFileReleaseManager(\n root_dir=temp_dir, prefix='a_')\n except TypeError:\n self.fail('Raised TypeError unexpectedly.')\n\n @parameterized.named_parameters(\n ('none', None),\n ('bool', True),\n ('int', 1),\n ('list', []),\n )\n def test_raises_type_error_with_root_dir(self, root_dir):\n with self.assertRaises(TypeError):\n file_release_manager.SavedModelFileReleaseManager(root_dir=root_dir)\n\n def test_raises_value_error_with_root_dir_empty(self):\n with self.assertRaises(ValueError):\n file_release_manager.SavedModelFileReleaseManager(root_dir='')\n\n @parameterized.named_parameters(\n ('none', None),\n ('bool', True),\n ('int', 1),\n ('list', []),\n )\n def test_raises_type_error_with_prefix(self, prefix):\n temp_dir = self.create_tempdir()\n\n with self.assertRaises(TypeError):\n file_release_manager.SavedModelFileReleaseManager(\n root_dir=temp_dir, prefix=prefix)\n\n\nclass SavedModelFileReleaseManagerGetPathForKeyTest(parameterized.TestCase):\n\n @parameterized.named_parameters(\n ('standard', '/tmp', 'a_', 123, '/tmp/a_123'),\n ('trailing_slash', '/tmp/', 'a_', 123, '/tmp/a_123'),\n ('no_prefix', '/tmp', '', 123, '/tmp/123'),\n )\n def test_returns_path_with_root_dir_and_prefix(self, root_dir, prefix, key,\n expected_path):\n release_mngr = file_release_manager.SavedModelFileReleaseManager(\n root_dir=root_dir, prefix=prefix)\n\n actual_path = release_mngr._get_path_for_key(key)\n\n self.assertEqual(actual_path, expected_path)\n\n @parameterized.named_parameters(\n ('none', None),\n ('str', 'a'),\n ('list', []),\n )\n def test_raises_type_error_with_key(self, key):\n temp_dir = self.create_tempdir()\n release_mngr = file_release_manager.SavedModelFileReleaseManager(\n root_dir=temp_dir, prefix='a_')\n\n with self.assertRaises(TypeError):\n release_mngr._get_path_for_key(key)\n\n\nclass SavedModelFileReleaseManagerReleaseTest(parameterized.TestCase,\n tf.test.TestCase):\n\n # pyformat: disable\n @parameterized.named_parameters(\n ('none', None, [None]),\n ('bool', True, [True]),\n ('int', 1, [1]),\n ('str', 'a', ['a']),\n ('list', [True, 1, 'a'], [True, 1, 'a']),\n ('list_empty', [], []),\n ('list_nested', [[True, 1], ['a']], [True, 1, 'a']),\n ('dict', {'a': True, 'b': 1, 'c': 'a'}, [True, 1, 'a']),\n ('dict_empty', {}, []),\n ('dict_nested',\n {'x': {'a': True, 'b': 1}, 'y': {'c': 'a'}},\n [True, 1, 'a']),\n ('attr', test_utils.TestAttrObject1(True, 1), [True, 1]),\n ('attr_nested',\n {'a': [test_utils.TestAttrObject1(True, 1)],\n 'b': test_utils.TestAttrObject2('a')},\n [True, 1, 'a']),\n ('tensor_int', tf.constant(1), [tf.constant(1)]),\n ('tensor_str', tf.constant('a'), [tf.constant('a')]),\n ('tensor_2d', tf.ones((2, 3)), [tf.ones((2, 3))]),\n ('tensor_nested',\n {'a': [tf.constant(True), tf.constant(1)], 'b': [tf.constant('a')]},\n [tf.constant(True), tf.constant(1), tf.constant('a')]),\n ('numpy_int', np.int32(1), [np.int32(1)]),\n ('numpy_2d', np.ones((2, 3)), [np.ones((2, 3))]),\n ('numpy_nested',\n {'a': [np.bool(True), np.int32(1)], 'b': [np.str_('a')]},\n [np.bool(True), np.int32(1), np.str_('a')]),\n ('materializable_value_reference_tensor',\n test_utils.TestMaterializableValueReference(1),\n [1]),\n ('materializable_value_reference_sequence',\n test_utils.TestMaterializableValueReference(\n tf.data.Dataset.from_tensor_slices([1, 2, 3])),\n [tf.data.Dataset.from_tensor_slices([1, 2, 3])]),\n ('materializable_value_reference_nested',\n {'a': [test_utils.TestMaterializableValueReference(True),\n test_utils.TestMaterializableValueReference(1)],\n 'b': [test_utils.TestMaterializableValueReference('a')]},\n [True, 1, 'a']),\n ('materialized_values_and_materializable_value_reference',\n [1, test_utils.TestMaterializableValueReference(2)],\n [1, 2]),\n )\n # pyformat: enable\n def test_writes_value(self, value, expected_value):\n temp_dir = self.create_tempdir()\n release_mngr = file_release_manager.SavedModelFileReleaseManager(\n root_dir=temp_dir, prefix='a_')\n\n release_mngr.release(value, 1)\n\n with mock.patch.object(file_utils,\n 'write_saved_model') as mock_write_saved_model:\n release_mngr.release(value, 1)\n\n mock_write_saved_model.assert_called_once()\n call = mock_write_saved_model.mock_calls[0]\n _, args, _ = call\n actual_value, _ = args\n\n def _to_list(value):\n if isinstance(value, tf.data.Dataset):\n return list(value)\n return value\n\n actual_value = tree.map_structure(_to_list, actual_value)\n expected_value = tree.map_structure(_to_list, expected_value)\n self.assertAllEqual(actual_value, expected_value)\n\n @parameterized.named_parameters(\n ('none', None),\n ('str', 'a'),\n ('list', []),\n )\n def test_raises_type_error_with_key(self, key):\n temp_dir = self.create_tempdir()\n release_mngr = file_release_manager.SavedModelFileReleaseManager(\n root_dir=temp_dir, prefix='a_')\n\n with self.assertRaises(TypeError):\n release_mngr.release(1, key)\n\n\nif __name__ == '__main__':\n absltest.main()\n",
"# Copyright 2021, The TensorFlow Federated 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\nfrom absl.testing import parameterized\nimport tensorflow as tf\n\nfrom tensorflow_federated.python.learning.optimizers import adagrad\nfrom tensorflow_federated.python.learning.optimizers import optimizer as optimizer_base\nfrom tensorflow_federated.python.learning.optimizers import optimizer_test_utils\n\n_SCALAR_SPEC = tf.TensorSpec([1], tf.float32)\n_STRUCT_SPEC = [tf.TensorSpec([2], tf.float32), tf.TensorSpec([3], tf.float32)]\n_NESTED_SPEC = [\n tf.TensorSpec([10], tf.float32),\n [tf.TensorSpec([20], tf.float32), [tf.TensorSpec([30], tf.float32)]]\n]\n\n\nclass AdagradTest(optimizer_test_utils.TestCase, parameterized.TestCase):\n\n def test_state_structure(self):\n optimizer = adagrad.build_adagrad(0.01)\n state = optimizer.initialize(_SCALAR_SPEC)\n self.assertLen(state, 3)\n self.assertIn(optimizer_base.LEARNING_RATE_KEY, state)\n self.assertIn(adagrad._EPSILON_KEY, state)\n self.assertIn(adagrad._PRECONDITIONER_KEY, state)\n\n def test_math_no_momentum(self):\n weights = tf.constant([1.0], tf.float32)\n gradients = tf.constant([2.0], tf.float32)\n optimizer = adagrad.build_adagrad(\n learning_rate=0.01, initial_preconditioner_value=0.0, epsilon=0.0)\n history = [weights]\n\n state = optimizer.initialize(_SCALAR_SPEC)\n\n for _ in range(4):\n state, weights = optimizer.next(state, weights, gradients)\n history.append(weights)\n self.assertAllClose(\n [\n [1.0], # w0\n [0.99], # w1 = w0 - 0.01 * 2.0 / sqrt(4)\n [0.9829289], # w2 = w1 - 0.01 * 2.0 / sqrt(8)\n [0.9771554], # w3 = w2 - 0.01 * 2.0 / sqrt(12)\n [0.9721554], # w4 = w3 - 0.01 * 2.0 / sqrt(16)\n ],\n history)\n\n @parameterized.named_parameters(\n ('scalar_spec', _SCALAR_SPEC),\n ('struct_spec', _STRUCT_SPEC),\n ('nested_spec', _NESTED_SPEC),\n )\n def test_executes_with(self, spec):\n weights = tf.nest.map_structure(lambda s: tf.ones(s.shape, s.dtype), spec)\n gradients = tf.nest.map_structure(lambda s: tf.ones(s.shape, s.dtype), spec)\n optimizer = adagrad.build_adagrad(0.01)\n\n state = optimizer.initialize(spec)\n for _ in range(10):\n state, weights = optimizer.next(state, weights, gradients)\n\n tf.nest.map_structure(lambda w: self.assertTrue(all(tf.math.is_finite(w))),\n weights)\n\n def test_executes_with_indexed_slices(self):\n # TF can represent gradients as tf.IndexedSlices. This test makes sure this\n # case is supported by the optimizer.\n weights = tf.ones([4, 2])\n gradients = tf.IndexedSlices(\n values=tf.constant([[1.0, 1.0], [1.0, 1.0]]),\n indices=tf.constant([0, 2]),\n dense_shape=tf.constant([4, 2]))\n optimizer = adagrad.build_adagrad(0.5, initial_preconditioner_value=0.0)\n\n state = optimizer.initialize(tf.TensorSpec([4, 2]))\n _, weights = optimizer.next(state, weights, gradients)\n self.assertAllClose([[0.5, 0.5], [1.0, 1.0], [0.5, 0.5], [1.0, 1.0]],\n weights)\n\n def test_convergence(self):\n init_w, fn, grad_fn = optimizer_test_utils.test_quadratic_problem()\n weights = init_w()\n self.assertGreater(fn(weights), 5.0)\n\n optimizer = adagrad.build_adagrad(0.5)\n state = optimizer.initialize(tf.TensorSpec(weights.shape, weights.dtype))\n\n for _ in range(100):\n gradients = grad_fn(weights)\n state, weights = optimizer.next(state, weights, gradients)\n self.assertLess(fn(weights), 0.005)\n\n def test_build_adagrad(self):\n optimizer = adagrad.build_adagrad(0.01)\n self.assertIsInstance(optimizer, optimizer_base.Optimizer)\n\n def test_match_keras(self):\n weight_spec = [\n tf.TensorSpec([10, 2], tf.float32),\n tf.TensorSpec([2], tf.float32)\n ]\n steps = 10\n genarator = tf.random.Generator.from_seed(2021)\n\n def random_vector():\n return [\n genarator.normal(shape=s.shape, dtype=s.dtype) for s in weight_spec\n ]\n\n intial_weight = random_vector()\n model_variables_fn = lambda: [tf.Variable(v) for v in intial_weight]\n gradients = [random_vector() for _ in range(steps)]\n tff_optimizer_fn = lambda: adagrad.build_adagrad(0.01)\n keras_optimizer_fn = lambda: tf.keras.optimizers.Adagrad(0.01)\n\n self.assert_optimizers_numerically_close(model_variables_fn, gradients,\n tff_optimizer_fn,\n keras_optimizer_fn)\n\n @parameterized.named_parameters(\n ('negative_lr', -1.0, 0.1, 1e-7, 'learning rate'),\n ('negative_preconditioner', 1.0, -0.1, 1e-7, 'preconditioner'),\n ('negative_epsilon', 1.0, 0.1, -1e-7, 'epsilon'),\n )\n def test_invalid_args_raises(self, lr, preconditioner, epsilon, regex):\n with self.assertRaisesRegex(ValueError, regex):\n adagrad.build_adagrad(lr, preconditioner, epsilon)\n\n def test_weights_gradients_mismatch_raises(self):\n optimizer = adagrad.build_adagrad(0.1)\n state = optimizer.initialize(_SCALAR_SPEC)\n with self.assertRaises(ValueError):\n optimizer.next(state, tf.zeros([1]), tf.zeros([2]))\n\n def test_initialize_next_weights_mismatch_raises(self):\n optimizer = adagrad.build_adagrad(0.1)\n state = optimizer.initialize(_SCALAR_SPEC)\n with self.assertRaises(ValueError):\n optimizer.next(state, tf.zeros([2]), tf.zeros([2]))\n\n\nif __name__ == '__main__':\n tf.test.main()\n"
] | [
[
"tensorflow.constant",
"tensorflow.test.main"
],
[
"tensorflow.constant",
"numpy.bool",
"tensorflow.data.Dataset.from_tensor_slices",
"numpy.int32",
"tensorflow.ones",
"numpy.ones",
"numpy.str_"
],
[
"tensorflow.cast",
"tensorflow.keras.optimizers.SGD"
],
[
"tensorflow.convert_to_tensor",
"numpy.asarray",
"tensorflow.ragged.constant",
"tensorflow.keras.layers.InputLayer",
"tensorflow.keras.backend.clear_session",
"tensorflow.keras.optimizers.SGD",
"tensorflow.keras.Input",
"tensorflow.keras.layers.Embedding",
"tensorflow.keras.metrics.MeanSquaredError",
"tensorflow.keras.losses.BinaryCrossentropy",
"numpy.zeros",
"tensorflow.keras.losses.MeanSquaredError",
"tensorflow.keras.layers.Dense",
"tensorflow.nn.sparse_softmax_cross_entropy_with_logits",
"numpy.random.random_integers",
"tensorflow.RaggedTensorSpec",
"numpy.array",
"tensorflow.GradientTape",
"tensorflow.constant",
"tensorflow.keras.losses.SparseCategoricalCrossentropy",
"numpy.ones",
"tensorflow.keras.layers.LSTM",
"tensorflow.keras.metrics.MeanAbsoluteError",
"numpy.random.uniform",
"tensorflow.TensorSpec"
],
[
"tensorflow.constant"
],
[
"tensorflow.constant",
"numpy.bool",
"tensorflow.io.gfile.GFile",
"tensorflow.data.Dataset.from_tensor_slices",
"numpy.int32",
"tensorflow.ones",
"numpy.ones",
"numpy.str_"
],
[
"tensorflow.math.is_finite",
"tensorflow.constant",
"tensorflow.Variable",
"tensorflow.zeros",
"tensorflow.test.main",
"tensorflow.ones",
"tensorflow.keras.optimizers.Adagrad",
"tensorflow.random.Generator.from_seed",
"tensorflow.TensorSpec"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"2.6",
"2.4",
"2.3",
"2.5",
"2.2"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.7",
"2.2",
"2.3",
"2.4",
"2.5",
"2.6"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"1.12",
"2.6",
"2.2",
"1.4",
"2.3",
"2.4",
"2.9",
"1.5",
"1.7",
"2.5",
"0.12",
"1.0",
"2.8",
"1.2",
"2.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.7",
"2.6",
"2.2",
"1.13",
"2.3",
"2.4",
"2.9",
"2.5",
"2.8",
"2.10"
]
}
] |
naylor-b/blue | [
"709401e535cf6933215abd942d4b4d49dbf61b2b",
"d7d7e8d63212c047a7a9b0625da98aa29ddc39b4",
"d7d7e8d63212c047a7a9b0625da98aa29ddc39b4"
] | [
"openmdao/matrices/dense_matrix.py",
"openmdao/components/tests/test_exec_comp.py",
"openmdao/core/tests/test_approx_derivs.py"
] | [
"\"\"\"Define the DenseMatrix class.\"\"\"\nfrom __future__ import division, print_function\nimport numpy as np\nfrom numpy import ndarray\nfrom six import iteritems\n\nfrom scipy.sparse import coo_matrix\n\nfrom openmdao.matrices.coo_matrix import COOMatrix\n\n# NOTE: DenseMatrix is inherited from COOMatrix so that we can easily handle use cases\n# where partials overlap the same matrix entries, as in the case of repeated\n# src_indices entries. This does require additional memory above storing just\n# the dense matrix, but it's worth it because the code is simpler and more robust.\n\n\nclass DenseMatrix(COOMatrix):\n \"\"\"\n Dense global matrix.\n \"\"\"\n\n def _build(self, num_rows, num_cols, in_ranges, out_ranges):\n \"\"\"\n Allocate the matrix.\n\n Parameters\n ----------\n num_rows : int\n number of rows in the matrix.\n num_cols : int\n number of cols in the matrix.\n in_ranges : dict\n Maps input var name to column range.\n out_ranges : dict\n Maps output var name to row range.\n \"\"\"\n super(DenseMatrix, self)._build(num_rows, num_cols, in_ranges, out_ranges)\n self._coo = self._matrix\n\n def _prod(self, in_vec, mode, ranges, mask=None):\n \"\"\"\n Perform a matrix vector product.\n\n Parameters\n ----------\n in_vec : ndarray[:]\n incoming vector to multiply.\n mode : str\n 'fwd' or 'rev'.\n ranges : (int, int, int, int)\n Min row, max row, min col, max col for the current system.\n mask : ndarray of type bool, or None\n Array used to mask out part of the input vector.\n\n Returns\n -------\n ndarray[:]\n vector resulting from the product.\n \"\"\"\n # when we have a derivative based solver at a level below the\n # group that owns the AssembledJacobian, we need to use only\n # the part of the matrix that is relevant to the lower level\n # system.\n if ranges is None:\n mat = self._matrix\n else:\n rstart, rend, cstart, cend = ranges\n mat = self._matrix[rstart:rend, cstart:cend]\n\n if mode == 'fwd':\n if mask is None:\n return mat.dot(in_vec)\n else:\n inputs_masked = np.ma.array(in_vec, mask=mask)\n\n # Use the special dot product function from masking module so that we\n # ignore masked parts.\n return np.ma.dot(mat, inputs_masked)\n else: # rev\n if mask is None:\n return mat.T.dot(in_vec)\n else:\n # Mask need to be applied to ext_mtx so that we can ignore multiplication\n # by certain columns.\n mat_T = mat.T\n arrmask = np.zeros(mat_T.shape, dtype=np.bool)\n arrmask[mask, :] = True\n masked_mtx = np.ma.array(mat_T, mask=arrmask, fill_value=0.0)\n\n masked_product = np.ma.dot(masked_mtx, in_vec).flatten()\n return np.ma.filled(masked_product, fill_value=0.0)\n\n def _create_mask_cache(self, d_inputs):\n \"\"\"\n Create masking array for this matrix.\n\n Note: this only applies when this Matrix is an 'ext_mtx' inside of a\n Jacobian object.\n\n Parameters\n ----------\n d_inputs : Vector\n The inputs linear vector.\n\n Returns\n -------\n ndarray or None\n The mask array or None.\n \"\"\"\n if len(d_inputs._views) > len(d_inputs._names):\n sub = d_inputs._names\n mask = np.ones(len(d_inputs), dtype=np.bool)\n for key, val in iteritems(self._metadata):\n if key[1] in sub:\n mask[val[1]] = False\n\n return mask\n\n def _pre_update(self):\n \"\"\"\n Do anything that needs to be done at the end of AssembledJacobian._update.\n \"\"\"\n self._matrix = self._coo\n\n def _post_update(self):\n \"\"\"\n Do anything that needs to be done at the end of AssembledJacobian._update.\n \"\"\"\n # this will add any repeated entries together\n self._matrix = self._coo.toarray()\n",
"from __future__ import print_function, division, absolute_import\n\nimport itertools\nimport unittest\nimport math\nfrom six import iteritems\n\nimport numpy as np\nfrom numpy.testing import assert_almost_equal\nimport scipy\n\ntry:\n from parameterized import parameterized\nexcept ImportError:\n from openmdao.utils.assert_utils import SkipParameterized as parameterized\n\nimport openmdao.api as om\nfrom openmdao.components.exec_comp import _expr_dict\nfrom openmdao.utils.assert_utils import assert_rel_error\n\n_ufunc_test_data = {\n 'abs': {\n 'str': 'f=abs(x)',\n 'check_func': np.abs,\n 'args': { 'f': {'value': np.zeros(6)},\n 'x': {'value': np.random.random(6)}}},\n 'acos': {\n 'str': 'f=acos(x)',\n 'check_func': np.arccos,\n 'args': {'f': {'value': np.zeros(6)},\n 'x': {'value': np.random.random(6) - 0.5}}},\n 'arccos': {\n 'str': 'f=arccos(x)',\n 'check_func': np.arccos,\n 'args': {'f': {'value': np.zeros(6)},\n 'x': {'value': np.random.random(6) - 0.5}}},\n 'arccosh': {\n 'str': 'f=arccosh(x)',\n 'check_func': np.arccosh,\n 'args': {'f': {'value': np.zeros(6)},\n 'x': {'value': 1.1 + np.random.random(6)}}},\n 'acosh': {\n 'str': 'f=acosh(x)',\n 'check_func': np.arccosh,\n 'args': {'f': {'value': np.zeros(6)},\n 'x': {'value': 1.1 + np.random.random(6)}}},\n 'arange': {\n 'str': 'f=arange(0,10,2)',\n 'check_val': np.arange(0, 10, 2),\n 'args': {'f': {'value': np.zeros(5)}}},\n 'arcsin': {\n 'str': 'f=arcsin(x)',\n 'check_func': np.arcsin,\n 'args': {'f': {'value': np.zeros(6)},\n 'x': {'value': np.random.random(6) - .5}}},\n 'arcsinh': {\n 'str': 'f=arcsinh(x)',\n 'check_func': np.arcsinh,\n 'args': {'f': {'value': np.zeros(6)},\n 'x': {'value': np.random.random(6)}}},\n 'asinh': {\n 'str': 'f=asinh(x)',\n 'check_func': np.arcsinh,\n 'args': {'f': {'value': np.zeros(6)},\n 'x': {'value': np.random.random(6)}}},\n 'asin': {\n 'str': 'f=asin(x)',\n 'check_func': np.arcsin,\n 'args': {'f': {'value': np.zeros(6)},\n 'x': {'value': np.random.random(6) - .5}}},\n 'arctan': {\n 'str': 'f=arctan(x)',\n 'check_func': np.arctan,\n 'args': {'f': {'value': np.zeros(6)},\n 'x': {'value': np.random.random(6)}}},\n 'atan': {\n 'str': 'f=atan(x)',\n 'check_func': np.arctan,\n 'args': {'f': {'value': np.zeros(6)},\n 'x': {'value': np.random.random(6)}}},\n 'cos': {\n 'str': 'f=cos(x)',\n 'check_func': np.cos,\n 'args': {'f': {'value': np.zeros(6)},\n 'x': {'value': np.random.random(6)}}},\n 'cosh': {\n 'str': 'f=cosh(x)',\n 'check_func': np.cosh,\n 'args': {'f': {'value': np.zeros(6)},\n 'x': {'value': np.random.random(6)}}},\n 'dot': {\n 'str': 'f=dot(x, y)',\n 'check_func': np.dot,\n 'args': {'f': {'value': np.zeros(6)},\n 'x': {'value': np.random.random(6)},\n 'y': {'value': np.random.random(6)}}},\n 'e': {\n 'str': 'f=e',\n 'check_val': np.e,\n 'args': {'f': {'value': 0.0}}},\n 'erf': {\n 'str': 'f=erf(x)',\n 'check_func': scipy.special.erf,\n 'args': {'f': {'value': np.zeros(6)},\n 'x': {'value': np.random.random(6)}}},\n 'erfc': {\n 'str': 'f=erfc(x)',\n 'check_func': scipy.special.erfc,\n 'args': {'f': {'value': np.zeros(6)},\n 'x': {'value': np.random.random(6)}}},\n 'exp': {\n 'str': 'f=exp(x)',\n 'check_func': np.exp,\n 'args': {'f': {'value': np.zeros(6)},\n 'x': {'value': np.random.random(6)}}},\n 'expm1': {\n 'str': 'f=expm1(x)',\n 'check_func': np.expm1,\n 'args': {'f': {'value': np.zeros(6)},\n 'x': {'value': np.random.random(6)}}},\n 'factorial': {\n 'str': 'f=factorial(x)',\n 'check_func': scipy.special.factorial,\n 'args': {'f': {'value': np.zeros(6)},\n 'x': {'value': np.random.random(6)}}},\n 'fmax': {\n 'str': 'f=fmax(x, y)',\n 'check_func': np.fmax,\n 'args': {'f': {'value': np.zeros(6)},\n 'x': {'value': np.random.random(6)},\n 'y': {'value': np.random.random(6)}}},\n 'fmin': {\n 'str': 'f=fmin(x, y)',\n 'check_func': np.fmin,\n 'args': {'f': {'value': np.zeros(6)},\n 'x': {'value': np.random.random(6)},\n 'y': {'value': np.random.random(6)}}},\n 'inner': {\n 'str': 'f=inner(x, y)',\n 'check_func': np.inner,\n 'args': {'f': {'value': np.zeros(6)},\n 'x': {'value': np.random.random(6)},\n 'y': {'value': np.random.random(6)}}},\n 'isinf': {\n 'str': 'f=isinf(x)',\n 'check_func': np.isinf,\n 'args': {'f': {'value': np.zeros(3)},\n 'x': {'value': [0, np.inf, 5.0]}}},\n 'isnan': {\n 'str': 'f=isnan(x)',\n 'check_func': np.isnan,\n 'args': {'f': {'value': np.zeros(3)},\n 'x': {'value': [0, np.nan, np.nan]}}},\n 'kron': {\n 'str': 'f=kron(x, y)',\n 'check_func': np.kron,\n 'args': {'f': {'value': np.zeros(36)},\n 'x': {'value': np.random.random(6)},\n 'y': {'value': np.random.random(6)}}},\n 'linspace': {\n 'str': 'f=linspace(0,10,50)',\n 'check_val': np.linspace(0, 10, 50),\n 'args': {'f': {'value': np.zeros(50)}}},\n 'log': {\n 'str': 'f=log(x)',\n 'check_func': np.log,\n 'args': {'f': {'value': np.zeros(6)},\n 'x': {'value': np.random.random(6) + 0.1}}},\n 'log10': {\n 'str': 'f=log10(x)',\n 'check_func': np.log10,\n 'args': {'f': {'value': np.zeros(6)},\n 'x': {'value': np.random.random(6) + 0.1}}},\n 'log1p': {\n 'str': 'f=log1p(x)',\n 'check_func': np.log1p,\n 'args': {'f': {'value': np.zeros(6)},\n 'x': {'value': np.random.random(6)}}},\n 'matmul': {\n 'str': 'f=matmul(x, y)',\n 'check_func': np.matmul,\n 'args': {'f': {'value': np.zeros((3, 1))},\n 'x': {'value': np.random.random((3, 3))},\n 'y': {'value': np.random.random((3, 1))}}},\n 'maximum': {\n 'str': 'f=maximum(x, y)',\n 'check_func': np.maximum,\n 'args': {'f': {'value': np.zeros(6)},\n 'x': {'value': np.random.random(6)},\n 'y': {'value': np.random.random(6)}}},\n 'minimum': {\n 'str': 'f=minimum(x, y)',\n 'check_func': np.minimum,\n 'args': {'f': {'value': np.zeros(6)},\n 'x': {'value': np.random.random(6)},\n 'y': {'value': np.random.random(6)}}},\n 'ones': {\n 'str': 'f=ones(21)',\n 'check_val': np.ones(21),\n 'args': {'f': {'value': np.zeros(21)}}},\n 'outer': {\n 'str': 'f=outer(x, y)',\n 'check_func': np.outer,\n 'args': {'f': {'value': np.zeros((6, 6))},\n 'x': {'value': np.random.random(6)},\n 'y': {'value': np.random.random(6)}}},\n 'pi': {\n 'str': 'f=pi',\n 'check_val': np.pi,\n 'args': {'f': {'value': 0.0}}},\n 'power': {\n 'str': 'f=power(x, y)',\n 'check_func': np.power,\n 'args': {'f': {'value': np.zeros(6)},\n 'x': {'value': np.random.random(6)},\n 'y': {'value': np.random.random(6) + 1.0}}},\n 'prod': {\n 'str': 'f=prod(x)',\n 'check_func': np.prod,\n 'args': {'f': {'value': 0.0},\n 'x': {'value': np.random.random(6)}}},\n 'sin': {\n 'str': 'f=sin(x)',\n 'check_func': np.sin,\n 'args': {'f': {'value': np.zeros(6)},\n 'x': {'value': np.random.random(6)}}},\n 'sinh': {\n 'str': 'f=sinh(x)',\n 'check_func': np.sinh,\n 'args': {'f': {'value': np.zeros(6)},\n 'x': {'value': np.random.random(6)}}},\n 'sum': {\n 'str': 'f=sum(x)',\n 'check_func': np.sum,\n 'args': {'f': {'value': 0.0},\n 'x': {'value': np.random.random(6)}}},\n 'tan': {\n 'str': 'f=tan(x)',\n 'check_func': np.tan,\n 'args': {'f': {'value': np.zeros(6)},\n 'x': {'value': np.random.random(6)}}},\n 'tanh': {\n 'str': 'f=tanh(x)',\n 'check_func': np.tanh,\n 'args': {'f': {'value': np.zeros(6)},\n 'x': {'value': np.random.random(6)}}},\n 'tensordot': {\n 'str': 'f=tensordot(x, y)',\n 'check_func': np.tensordot,\n 'args': {'f': {'value': 0.0},\n 'x': {'value': np.random.random((6, 6))},\n 'y': {'value': np.random.random((6, 6))}}},\n 'zeros': {\n 'str': 'f=zeros(21)',\n 'check_val': np.zeros(21),\n 'args': {'f': {'value': np.zeros(21)}}},\n}\n\n\nclass TestExecComp(unittest.TestCase):\n\n def test_no_expr(self):\n prob = om.Problem()\n prob.model.add_subsystem('C1', om.ExecComp())\n with self.assertRaises(Exception) as context:\n prob.setup()\n self.assertEqual(str(context.exception),\n \"C1: No valid expressions provided to ExecComp(): [].\")\n\n def test_colon_vars(self):\n prob = om.Problem()\n prob.model.add_subsystem('C1', om.ExecComp('y=foo:bar+1.'))\n with self.assertRaises(Exception) as context:\n prob.setup()\n self.assertEqual(str(context.exception),\n \"C1: failed to compile expression 'y=foo:bar+1.'.\")\n\n def test_bad_kwargs(self):\n prob = om.Problem()\n prob.model.add_subsystem('C1', om.ExecComp('y=x+1.', xx=2.0))\n with self.assertRaises(Exception) as context:\n prob.setup()\n self.assertEqual(str(context.exception),\n \"C1: arg 'xx' in call to ExecComp() does not refer to any variable \"\n \"in the expressions ['y=x+1.']\")\n\n def test_bad_kwargs_meta(self):\n prob = om.Problem()\n prob.model.add_subsystem('C1', om.ExecComp('y=x+1.',\n x={'val': 2, 'low': 0, 'high': 10, 'units': 'ft'}))\n with self.assertRaises(Exception) as context:\n prob.setup()\n self.assertEqual(str(context.exception),\n \"C1: the following metadata names were not recognized for \"\n \"variable 'x': ['high', 'low', 'val']\")\n\n def test_name_collision_const(self):\n prob = om.Problem()\n prob.model.add_subsystem('C1', om.ExecComp('e=x+1.'))\n with self.assertRaises(Exception) as context:\n prob.setup()\n self.assertEqual(str(context.exception),\n \"C1: cannot assign to variable 'e' because it's already defined \"\n \"as an internal function or constant.\")\n\n def test_name_collision_func(self):\n prob = om.Problem()\n prob.model.add_subsystem('C1', om.ExecComp('sin=x+1.'))\n with self.assertRaises(Exception) as context:\n prob.setup()\n self.assertEqual(str(context.exception),\n \"C1: cannot assign to variable 'sin' because it's already defined \"\n \"as an internal function or constant.\")\n\n def test_func_as_rhs_var(self):\n prob = om.Problem()\n prob.model.add_subsystem('C1', om.ExecComp('y=sin+1.'))\n with self.assertRaises(Exception) as context:\n prob.setup()\n self.assertEqual(str(context.exception),\n \"C1: cannot use 'sin' as a variable because it's already defined \"\n \"as an internal function.\")\n\n def test_mixed_type(self):\n prob = om.Problem()\n C1 = prob.model.add_subsystem('C1', om.ExecComp('y=sum(x)',\n x=np.arange(10, dtype=float)))\n prob.setup()\n\n # Conclude setup but don't run model.\n prob.final_setup()\n\n self.assertTrue('x' in C1._inputs)\n self.assertTrue('y' in C1._outputs)\n\n prob.set_solver_print(level=0)\n prob.run_model()\n\n assert_rel_error(self, C1._outputs['y'], 45.0, 0.00001)\n\n def test_simple(self):\n prob = om.Problem()\n C1 = prob.model.add_subsystem('C1', om.ExecComp('y=x+1.', x=2.0))\n\n prob.setup()\n\n # Conclude setup but don't run model.\n prob.final_setup()\n\n self.assertTrue('x' in C1._inputs)\n self.assertTrue('y' in C1._outputs)\n\n prob.set_solver_print(level=0)\n prob.run_model()\n\n assert_rel_error(self, C1._outputs['y'], 3.0, 0.00001)\n\n def test_for_spaces(self):\n prob = om.Problem()\n C1 = prob.model.add_subsystem('C1', om.ExecComp('y = pi * x', x=2.0))\n\n prob.setup()\n\n # Conclude setup but don't run model.\n prob.final_setup()\n\n self.assertTrue('x' in C1._inputs)\n self.assertTrue('y' in C1._outputs)\n self.assertTrue('pi' not in C1._inputs)\n\n prob.set_solver_print(level=0)\n prob.run_model()\n\n assert_rel_error(self, C1._outputs['y'], 2 * math.pi, 0.00001)\n\n def test_units(self):\n prob = om.Problem()\n prob.model.add_subsystem('indep', om.IndepVarComp('x', 100.0, units='cm'))\n C1 = prob.model.add_subsystem('C1', om.ExecComp('y=x+z+1.',\n x={'value': 2.0, 'units': 'm'},\n y={'units': 'm'},\n z=2.0))\n prob.model.connect('indep.x', 'C1.x')\n\n prob.setup()\n\n prob.set_solver_print(level=0)\n prob.run_model()\n\n assert_rel_error(self, C1._outputs['y'], 4.0, 0.00001)\n\n def test_units_varname(self):\n prob = om.Problem()\n\n with self.assertRaises(TypeError) as cm:\n prob.model.add_subsystem('C1', om.ExecComp('y=x+units+1.',\n x={'value': 2.0, 'units': 'm'},\n y={'units': 'm'},\n units=2.0))\n\n self.assertEqual(str(cm.exception),\n \"Value (2.0) of option 'units' has type 'float', \"\n \"but type 'str' was expected.\")\n\n def test_units_varname_str(self):\n prob = om.Problem()\n\n with self.assertRaises(ValueError) as cm:\n prob.model.add_subsystem('C1', om.ExecComp('y=x+units+1.',\n x={'value': 2.0, 'units': 'm'},\n y={'units': 'm'},\n units='two'))\n\n self.assertEqual(str(cm.exception), \"The units 'two' are invalid.\")\n\n def test_units_varname_novalue(self):\n prob = om.Problem()\n prob.model.add_subsystem('indep', om.IndepVarComp('x', 100.0, units='cm'))\n C1 = prob.model.add_subsystem('C1', om.ExecComp('y=x+units+1.',\n x={'value': 2.0, 'units': 'm'},\n y={'units': 'm'}))\n prob.model.connect('indep.x', 'C1.x')\n\n with self.assertRaises(NameError) as cm:\n prob.setup()\n\n self.assertEqual(str(cm.exception),\n \"C1: cannot use variable name 'units' because it's a reserved keyword.\")\n\n def test_common_units(self):\n # all variables in the ExecComp have the same units\n prob = om.Problem()\n\n prob.model.add_subsystem('indep', om.IndepVarComp('x', 100.0, units='cm'))\n prob.model.add_subsystem('comp', om.ExecComp('y=x+z+1.', units='m',\n x={'value': 2.0},\n z=2.0))\n prob.model.connect('indep.x', 'comp.x')\n\n prob.setup()\n prob.run_model()\n\n assert_rel_error(self, prob['comp.y'], 4.0, 0.00001)\n\n def test_common_units_no_meta(self):\n # make sure common units are assigned when no metadata is provided\n prob = om.Problem()\n\n prob.model.add_subsystem('indep', om.IndepVarComp('x', 2.0, units='km'))\n prob.model.add_subsystem('comp', om.ExecComp('y = x+1', units='m'))\n\n prob.model.connect('indep.x', 'comp.x')\n\n prob.setup()\n prob.run_model()\n\n assert_rel_error(self, prob['comp.y'], 2001., 0.00001)\n\n def test_conflicting_units(self):\n prob = om.Problem()\n prob.model.add_subsystem('indep', om.IndepVarComp('x', 100.0, units='cm'))\n C1 = prob.model.add_subsystem('C1', om.ExecComp('y=x+z+1.', units='m',\n x={'value': 2.0, 'units': 'km'},\n z=2.0))\n prob.model.connect('indep.x', 'C1.x')\n\n with self.assertRaises(RuntimeError) as cm:\n prob.setup()\n\n self.assertEqual(str(cm.exception),\n \"C1: units of 'km' have been specified for variable 'x', but \"\n \"units of 'm' have been specified for the entire component.\")\n\n def test_shape_and_value(self):\n p = om.Problem()\n model = p.model\n model.add_subsystem('indep', om.IndepVarComp('x', val=np.ones(5)))\n\n model.add_subsystem('comp', om.ExecComp('y=3.0*x + 2.5',\n x={'shape': (5,), 'value': np.zeros(5)},\n y={'shape': (5,), 'value': np.zeros(5)}))\n\n model.connect('indep.x', 'comp.x')\n\n p.setup()\n p.run_model()\n\n J = p.compute_totals(of=['comp.y'], wrt=['indep.x'], return_format='array')\n\n assert_almost_equal(J, np.eye(5)*3., decimal=6)\n\n def test_conflicting_shape(self):\n p = om.Problem()\n model = p.model\n model.add_subsystem('indep', om.IndepVarComp('x', val=np.ones(5)))\n\n model.add_subsystem('comp', om.ExecComp('y=3.0*x + 2.5',\n x={'shape': (5,), 'value': 5},\n y={'shape': (5,)}))\n\n model.connect('indep.x', 'comp.x')\n\n with self.assertRaises(Exception) as context:\n p.setup()\n\n self.assertEqual(str(context.exception).replace('L,', ','), # L on Windows\n \"comp: shape of (5,) has been specified for variable 'x', \"\n \"but a value of shape (1,) has been provided.\")\n\n def test_common_shape(self):\n p = om.Problem()\n model = p.model\n model.add_subsystem('indep', om.IndepVarComp('x', val=np.ones(5)))\n\n model.add_subsystem('comp', om.ExecComp('y=3.0*x + 2.5', shape=(5,)))\n\n model.connect('indep.x', 'comp.x')\n\n p.setup()\n p.run_model()\n\n J = p.compute_totals(of=['comp.y'], wrt=['indep.x'], return_format='array')\n\n assert_almost_equal(J, np.eye(5)*3., decimal=6)\n\n def test_common_shape_with_values(self):\n p = om.Problem()\n model = p.model\n model.add_subsystem('indep', om.IndepVarComp('x', val=np.ones(5)))\n\n model.add_subsystem('comp', om.ExecComp('y=3.0*x + 2.5', shape=(5,),\n x={'value': np.zeros(5)},\n y={'value': np.zeros(5)}))\n\n model.connect('indep.x', 'comp.x')\n\n p.setup()\n p.run_model()\n\n J = p.compute_totals(of=['comp.y'], wrt=['indep.x'], return_format='array')\n\n assert_almost_equal(J, np.eye(5)*3., decimal=6)\n\n def test_common_shape_conflicting_shape(self):\n p = om.Problem()\n model = p.model\n model.add_subsystem('indep', om.IndepVarComp('x', val=np.ones(5)))\n\n model.add_subsystem('comp', om.ExecComp('y=3.0*x + 2.5', shape=(5,),\n y={'shape': (10,)}))\n\n model.connect('indep.x', 'comp.x')\n\n with self.assertRaises(Exception) as context:\n p.setup()\n\n self.assertEqual(str(context.exception).replace('L,', ','), # L on Windows\n \"comp: shape of (10,) has been specified for variable 'y', \"\n \"but shape of (5,) has been specified for the entire component.\")\n\n def test_common_shape_conflicting_value(self):\n p = om.Problem()\n model = p.model\n model.add_subsystem('indep', om.IndepVarComp('x', val=np.ones(5)))\n\n model.add_subsystem('comp', om.ExecComp('y=3.0*x + 2.5', shape=(5,),\n x={'value': 5}))\n\n model.connect('indep.x', 'comp.x')\n\n with self.assertRaises(Exception) as context:\n p.setup()\n\n self.assertEqual(str(context.exception).replace('1L,', '1,'), # 1L on Windows\n \"comp: value of shape (1,) has been specified for variable 'x', \"\n \"but shape of (5,) has been specified for the entire component.\")\n\n def test_math(self):\n prob = om.Problem()\n C1 = prob.model.add_subsystem('C1', om.ExecComp('y=sin(x)', x=2.0))\n\n prob.setup()\n\n # Conclude setup but don't run model.\n prob.final_setup()\n\n self.assertTrue('x' in C1._inputs)\n self.assertTrue('y' in C1._outputs)\n\n prob.set_solver_print(level=0)\n prob.run_model()\n\n assert_rel_error(self, C1._outputs['y'], math.sin(2.0), 0.00001)\n\n def test_array(self):\n prob = om.Problem()\n C1 = prob.model.add_subsystem('C1', om.ExecComp('y=x[1]',\n x=np.array([1., 2., 3.]),\n y=0.0))\n\n prob.setup()\n\n # Conclude setup but don't run model.\n prob.final_setup()\n\n self.assertTrue('x' in C1._inputs)\n self.assertTrue('y' in C1._outputs)\n\n prob.set_solver_print(level=0)\n prob.run_model()\n\n assert_rel_error(self, C1._outputs['y'], 2.0, 0.00001)\n\n def test_array_lhs(self):\n prob = om.Problem()\n C1 = prob.model.add_subsystem('C1', om.ExecComp(['y[0]=x[1]', 'y[1]=x[0]'],\n x=np.array([1., 2., 3.]),\n y=np.array([0., 0.])))\n\n prob.setup()\n\n # Conclude setup but don't run model.\n prob.final_setup()\n\n self.assertTrue('x' in C1._inputs)\n self.assertTrue('y' in C1._outputs)\n\n prob.set_solver_print(level=0)\n prob.run_model()\n\n assert_rel_error(self, C1._outputs['y'], np.array([2., 1.]), 0.00001)\n\n def test_simple_array_model(self):\n prob = om.Problem()\n prob.model.add_subsystem('p1', om.IndepVarComp('x', np.ones([2])))\n prob.model.add_subsystem('comp', om.ExecComp(['y[0]=2.0*x[0]+7.0*x[1]',\n 'y[1]=5.0*x[0]-3.0*x[1]'],\n x=np.zeros([2]), y=np.zeros([2])))\n\n prob.model.connect('p1.x', 'comp.x')\n\n prob.setup()\n prob.set_solver_print(level=0)\n prob.run_model()\n\n data = prob.check_partials(out_stream=None)\n\n assert_rel_error(self, data['comp'][('y', 'x')]['abs error'][0], 0.0, 1e-5)\n assert_rel_error(self, data['comp'][('y', 'x')]['abs error'][1], 0.0, 1e-5)\n assert_rel_error(self, data['comp'][('y', 'x')]['abs error'][2], 0.0, 1e-5)\n assert_rel_error(self, data['comp'][('y', 'x')]['rel error'][0], 0.0, 1e-5)\n assert_rel_error(self, data['comp'][('y', 'x')]['rel error'][1], 0.0, 1e-5)\n assert_rel_error(self, data['comp'][('y', 'x')]['rel error'][2], 0.0, 1e-5)\n\n def test_simple_array_model2(self):\n prob = om.Problem()\n prob.model.add_subsystem('p1', om.IndepVarComp('x', np.ones([2])))\n prob.model.add_subsystem('comp', om.ExecComp('y = mat.dot(x)',\n x=np.zeros((2,)), y=np.zeros((2,)),\n mat=np.array([[2., 7.], [5., -3.]])))\n\n prob.model.connect('p1.x', 'comp.x')\n\n prob.setup()\n prob.set_solver_print(level=0)\n prob.run_model()\n\n data = prob.check_partials(out_stream=None)\n\n assert_rel_error(self, data['comp'][('y', 'x')]['abs error'][0], 0.0, 1e-5)\n assert_rel_error(self, data['comp'][('y', 'x')]['abs error'][1], 0.0, 1e-5)\n assert_rel_error(self, data['comp'][('y', 'x')]['abs error'][2], 0.0, 1e-5)\n assert_rel_error(self, data['comp'][('y', 'x')]['rel error'][0], 0.0, 1e-5)\n assert_rel_error(self, data['comp'][('y', 'x')]['rel error'][1], 0.0, 1e-5)\n assert_rel_error(self, data['comp'][('y', 'x')]['rel error'][2], 0.0, 1e-5)\n\n def test_complex_step(self):\n prob = om.Problem()\n C1 = prob.model.add_subsystem('C1', om.ExecComp(['y=2.0*x+1.'], x=2.0))\n\n prob.setup()\n\n # Conclude setup but don't run model.\n prob.final_setup()\n\n self.assertTrue('x' in C1._inputs)\n self.assertTrue('y' in C1._outputs)\n\n prob.set_solver_print(level=0)\n prob.run_model()\n\n assert_rel_error(self, C1._outputs['y'], 5.0, 0.00001)\n\n C1._linearize()\n\n assert_rel_error(self, C1._jacobian[('y', 'x')], [[2.0]], 0.00001)\n\n def test_complex_step2(self):\n prob = om.Problem(om.Group())\n prob.model.add_subsystem('p1', om.IndepVarComp('x', 2.0))\n prob.model.add_subsystem('comp', om.ExecComp('y=x*x + x*2.0'))\n prob.model.connect('p1.x', 'comp.x')\n prob.set_solver_print(level=0)\n\n prob.setup(check=False, mode='fwd')\n prob.run_model()\n\n J = prob.compute_totals(['comp.y'], ['p1.x'], return_format='flat_dict')\n assert_rel_error(self, J['comp.y', 'p1.x'], np.array([[6.0]]), 0.00001)\n\n prob.setup(check=False, mode='rev')\n prob.run_model()\n\n J = prob.compute_totals(['comp.y'], ['p1.x'], return_format='flat_dict')\n assert_rel_error(self, J['comp.y', 'p1.x'], np.array([[6.0]]), 0.00001)\n\n def test_abs_complex_step(self):\n prob = om.Problem()\n C1 = prob.model.add_subsystem('C1', om.ExecComp('y=2.0*abs(x)', x=-2.0))\n\n prob.setup()\n prob.set_solver_print(level=0)\n prob.run_model()\n\n assert_rel_error(self, C1._outputs['y'], 4.0, 0.00001)\n\n # any positive C1.x should give a 2.0 derivative for dy/dx\n C1._inputs['x'] = 1.0e-10\n C1._linearize()\n assert_rel_error(self, C1._jacobian['y', 'x'], [[2.0]], 0.00001)\n\n C1._inputs['x'] = -3.0\n C1._linearize()\n assert_rel_error(self, C1._jacobian['y', 'x'], [[-2.0]], 0.00001)\n\n C1._inputs['x'] = 0.0\n C1._linearize()\n assert_rel_error(self, C1._jacobian['y', 'x'], [[2.0]], 0.00001)\n\n def test_abs_array_complex_step(self):\n prob = om.Problem()\n C1 = prob.model.add_subsystem('C1', om.ExecComp('y=2.0*abs(x)',\n x=np.ones(3)*-2.0, y=np.zeros(3)))\n\n prob.setup()\n prob.set_solver_print(level=0)\n prob.run_model()\n\n assert_rel_error(self, C1._outputs['y'], np.ones(3)*4.0, 0.00001)\n\n # any positive C1.x should give a 2.0 derivative for dy/dx\n C1._inputs['x'] = np.ones(3)*1.0e-10\n C1._linearize()\n assert_rel_error(self, C1._jacobian['y', 'x'], np.eye(3)*2.0, 0.00001)\n\n C1._inputs['x'] = np.ones(3)*-3.0\n C1._linearize()\n assert_rel_error(self, C1._jacobian['y', 'x'], np.eye(3)*-2.0, 0.00001)\n\n C1._inputs['x'] = np.zeros(3)\n C1._linearize()\n assert_rel_error(self, C1._jacobian['y', 'x'], np.eye(3)*2.0, 0.00001)\n\n C1._inputs['x'] = np.array([1.5, -0.6, 2.4])\n C1._linearize()\n expect = np.zeros((3, 3))\n expect[0, 0] = 2.0\n expect[1, 1] = -2.0\n expect[2, 2] = 2.0\n\n assert_rel_error(self, C1._jacobian['y', 'x'], expect, 0.00001)\n\n def test_vectorize_error(self):\n p = om.Problem()\n model = p.model\n model.add_subsystem('indep', om.IndepVarComp('x', val=np.ones(3)))\n model.add_design_var('indep.x')\n\n mat = np.arange(15).reshape((3,5))\n model.add_subsystem('comp', om.ExecComp('y=A.dot(x)', vectorize=True, A=mat, x=np.ones(5), y=np.ones(3)))\n model.connect('indep.x', 'comp.x')\n\n with self.assertRaises(Exception) as context:\n p.setup()\n self.assertEqual(str(context.exception),\n \"comp: vectorize is True but partial(y, A) is not square (shape=(3, 15)).\")\n\n def test_vectorize_shape_only(self):\n p = om.Problem()\n model = p.model\n model.add_subsystem('indep', om.IndepVarComp('x', val=np.ones(5)))\n\n model.add_subsystem('comp', om.ExecComp('y=3.0*x + 2.5', vectorize=True,\n x={'shape': (5,)}, y={'shape': (5,)}))\n model.connect('indep.x', 'comp.x')\n\n p.setup()\n p.run_model()\n\n J = p.compute_totals(of=['comp.y'], wrt=['indep.x'], return_format='array')\n\n assert_almost_equal(J, np.eye(5)*3., decimal=6)\n\n def test_feature_vectorize(self):\n import numpy as np\n import openmdao.api as om\n\n p = om.Problem()\n model = p.model\n model.add_subsystem('indep', om.IndepVarComp('x', val=np.ones(5)))\n\n model.add_subsystem('comp', om.ExecComp('y=3.0*x + 2.5', vectorize=True, x=np.ones(5), y=np.ones(5)))\n model.connect('indep.x', 'comp.x')\n\n p.setup()\n p.run_model()\n\n J = p.compute_totals(of=['comp.y'], wrt=['indep.x'], return_format='array')\n\n assert_almost_equal(J, np.eye(5)*3., decimal=6)\n\n def test_feature_simple(self):\n import openmdao.api as om\n\n prob = om.Problem()\n model = prob.model\n\n model.add_subsystem('p', om.IndepVarComp('x', 2.0))\n model.add_subsystem('comp', om.ExecComp('y=x+1.'))\n\n model.connect('p.x', 'comp.x')\n\n prob.setup()\n\n prob.set_solver_print(level=0)\n prob.run_model()\n\n assert_rel_error(self, prob['comp.y'], 3.0, 0.00001)\n\n def test_feature_multi_output(self):\n import openmdao.api as om\n\n prob = om.Problem()\n model = prob.model\n\n model.add_subsystem('p', om.IndepVarComp('x', 2.0))\n model.add_subsystem('comp', om.ExecComp(['y1=x+1.', 'y2=x-1.']))\n\n model.connect('p.x', 'comp.x')\n\n prob.setup()\n\n prob.set_solver_print(level=0)\n prob.run_model()\n\n assert_rel_error(self, prob['comp.y1'], 3.0, 0.00001)\n assert_rel_error(self, prob['comp.y2'], 1.0, 0.00001)\n\n def test_feature_array(self):\n import numpy as np\n\n import openmdao.api as om\n\n prob = om.Problem()\n model = prob.model\n\n model.add_subsystem('p', om.IndepVarComp('x', np.array([1., 2., 3.])))\n model.add_subsystem('comp', om.ExecComp('y=x[1]',\n x=np.array([1., 2., 3.]),\n y=0.0))\n model.connect('p.x', 'comp.x')\n\n prob.setup()\n\n prob.set_solver_print(level=0)\n prob.run_model()\n\n assert_rel_error(self, prob['comp.y'], 2.0, 0.00001)\n\n def test_feature_math(self):\n import numpy as np\n\n import openmdao.api as om\n\n prob = om.Problem()\n model = prob.model\n\n model.add_subsystem('p1', om.IndepVarComp('x', np.pi/2.0))\n model.add_subsystem('p2', om.IndepVarComp('y', np.pi/2.0))\n model.add_subsystem('comp', om.ExecComp('z = sin(x)**2 + cos(y)**2'))\n\n model.connect('p1.x', 'comp.x')\n model.connect('p2.y', 'comp.y')\n\n prob.setup()\n\n prob.set_solver_print(level=0)\n prob.run_model()\n\n assert_rel_error(self, prob['comp.z'], 1.0, 0.00001)\n\n def test_feature_numpy(self):\n import numpy as np\n\n import openmdao.api as om\n\n prob = om.Problem()\n model = prob.model\n\n model.add_subsystem('p', om.IndepVarComp('x', np.array([1., 2., 3.])))\n model.add_subsystem('comp', om.ExecComp('y=sum(x)', x=np.zeros((3, ))))\n model.connect('p.x', 'comp.x')\n\n prob.setup()\n\n prob.set_solver_print(level=0)\n prob.run_model()\n\n assert_rel_error(self, prob['comp.y'], 6.0, 0.00001)\n\n def test_feature_metadata(self):\n import openmdao.api as om\n\n prob = om.Problem()\n model = prob.model\n\n model.add_subsystem('p1', om.IndepVarComp('x', 12.0, units='inch'))\n model.add_subsystem('p2', om.IndepVarComp('y', 1.0, units='ft'))\n model.add_subsystem('comp', om.ExecComp('z=x+y',\n x={'value': 0.0, 'units': 'inch'},\n y={'value': 0.0, 'units': 'inch'},\n z={'value': 0.0, 'units': 'inch'}))\n model.connect('p1.x', 'comp.x')\n model.connect('p2.y', 'comp.y')\n\n prob.setup()\n\n prob.set_solver_print(level=0)\n prob.run_model()\n\n assert_rel_error(self, prob['comp.z'], 24.0, 0.00001)\n\n def test_feature_options(self):\n import openmdao.api as om\n\n model = om.Group()\n\n indep = model.add_subsystem('indep', om.IndepVarComp('x', shape=(2,), units='cm'))\n xcomp = model.add_subsystem('comp', om.ExecComp('y=2*x', shape=(2,)))\n\n xcomp.options['units'] = 'm'\n\n model.connect('indep.x', 'comp.x')\n\n prob = om.Problem(model)\n prob.setup()\n\n prob['indep.x'] = [100., 200.]\n\n prob.run_model()\n\n assert_rel_error(self, prob['comp.y'], [2., 4.], 0.00001)\n\n\nclass TestExecCompParameterized(unittest.TestCase):\n\n @parameterized.expand(itertools.product([\n func_name for func_name in _expr_dict if not func_name.startswith('_')\n ]), name_func=lambda f, n, p: 'test_exec_comp_value_' + '_'.join(a for a in p.args))\n def test_exec_comp_value(self, f):\n test_data = _ufunc_test_data[f]\n\n prob = om.Problem()\n model = prob.model\n\n if len(test_data['args']) > 1:\n ivc = model.add_subsystem(name='ivc', subsys=om.IndepVarComp())\n for arg_name, arg_value in iteritems(test_data['args']):\n if arg_name == 'f':\n continue\n ivc.add_output(name=arg_name, val=arg_value['value'])\n model.connect('ivc.{0}'.format(arg_name), 'comp.{0}'.format(arg_name))\n\n model.add_subsystem('comp', om.ExecComp(test_data['str'], **test_data['args']),\n promotes_outputs=['f'])\n prob.setup()\n prob.run_model()\n\n if 'check_func' in test_data:\n check_args = []\n try:\n check_args.append(test_data['args']['x']['value'])\n except Exception:\n pass\n try:\n check_args.append(test_data['args']['y']['value'])\n except Exception:\n pass\n check_args = tuple(check_args)\n\n expected = test_data['check_func'](*check_args)\n else:\n expected = test_data['check_val']\n np.testing.assert_almost_equal(prob['f'], expected)\n\n if 'check_val' not in test_data:\n try:\n prob.check_partials(out_stream=None)\n except TypeError as e:\n print(f, 'does not support complex-step differentiation')\n\n @parameterized.expand(itertools.product([\n func_name for func_name in _expr_dict if not func_name.startswith('_')\n ]), name_func=lambda f, n, p: 'test_exec_comp_jac_' + '_'.join(a for a in p.args))\n def test_exec_comp_jac(self, f):\n test_data = _ufunc_test_data[f]\n\n prob = om.Problem()\n model = prob.model\n\n if len(test_data['args']) > 1:\n ivc = model.add_subsystem(name='ivc', subsys=om.IndepVarComp())\n for arg_name, arg_value in iteritems(test_data['args']):\n if arg_name == 'f':\n continue\n ivc.add_output(name=arg_name, val=arg_value['value'])\n model.connect('ivc.{0}'.format(arg_name),\n '{0}_comp.{1}'.format(f, arg_name))\n\n model.add_subsystem('{0}_comp'.format(f),\n om.ExecComp(test_data['str'], **test_data['args']),\n promotes_outputs=['f'])\n prob.setup()\n prob.run_model()\n\n if 'check_val' not in test_data:\n cpd = prob.check_partials(out_stream=None)\n\n for comp in cpd:\n for (var, wrt) in cpd[comp]:\n np.testing.assert_almost_equal(cpd[comp][var, wrt]['abs error'], 0, decimal=4)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n",
"\"\"\" Testing for group finite differencing.\"\"\"\nimport itertools\nimport unittest\nfrom six import iterkeys\nfrom six.moves import range\n\ntry:\n from parameterized import parameterized\nexcept ImportError:\n from openmdao.utils.assert_utils import SkipParameterized as parameterized\n\nimport numpy as np\n\nimport openmdao.api as om\nfrom openmdao.test_suite.components.impl_comp_array import TestImplCompArray, TestImplCompArrayDense\nfrom openmdao.test_suite.components.paraboloid import Paraboloid\nfrom openmdao.test_suite.components.sellar import SellarDis1withDerivatives, \\\n SellarDis2withDerivatives, SellarDis1CS, SellarDis2CS\nfrom openmdao.test_suite.components.simple_comps import DoubleArrayComp\nfrom openmdao.test_suite.components.unit_conv import SrcComp, TgtCompC, TgtCompF, TgtCompK\nfrom openmdao.test_suite.groups.parallel_groups import FanInSubbedIDVC\nfrom openmdao.test_suite.parametric_suite import parametric_suite\nfrom openmdao.utils.assert_utils import assert_rel_error\nfrom openmdao.utils.general_utils import set_pyoptsparse_opt\nfrom openmdao.utils.mpi import MPI\n\ntry:\n from openmdao.parallel_api import PETScVector\n vector_class = PETScVector\nexcept ImportError:\n vector_class = om.DefaultVector\n PETScVector = None\n\n# check that pyoptsparse is installed\n# if it is, try to use SNOPT but fall back to SLSQP\nOPT, OPTIMIZER = set_pyoptsparse_opt('SNOPT')\n\nif OPTIMIZER:\n from openmdao.drivers.pyoptsparse_driver import pyOptSparseDriver\n\n\nclass TestGroupFiniteDifference(unittest.TestCase):\n\n def test_paraboloid(self):\n prob = om.Problem()\n model = prob.model\n model.add_subsystem('p1', om.IndepVarComp('x', 0.0), promotes=['x'])\n model.add_subsystem('p2', om.IndepVarComp('y', 0.0), promotes=['y'])\n model.add_subsystem('comp', Paraboloid(), promotes=['x', 'y', 'f_xy'])\n\n model.linear_solver = om.ScipyKrylov()\n model.approx_totals()\n\n prob.setup(check=False, mode='fwd')\n prob.set_solver_print(level=0)\n prob.run_model()\n\n of = ['f_xy']\n wrt = ['x', 'y']\n derivs = prob.compute_totals(of=of, wrt=wrt)\n\n assert_rel_error(self, derivs['f_xy', 'x'], [[-6.0]], 1e-6)\n assert_rel_error(self, derivs['f_xy', 'y'], [[8.0]], 1e-6)\n\n # 1 output x 2 inputs\n self.assertEqual(len(model._approx_schemes['fd']._exec_dict), 2)\n\n def test_fd_count(self):\n # Make sure we aren't doing extra FD steps.\n\n class ParaboloidA(om.ExplicitComponent):\n def setup(self):\n self.add_input('x', val=0.0)\n self.add_input('y', val=0.0)\n\n self.add_output('f_xy', val=0.0)\n self.add_output('g_xy', val=0.0)\n\n # makes extra calls to the model with no actual steps\n self.declare_partials(of='*', wrt='*', method='fd', form='forward', step=1e-6)\n\n self.count = 0\n\n def compute(self, inputs, outputs):\n x = inputs['x']\n y = inputs['y']\n\n outputs['f_xy'] = (x-3.0)**2 + x*y + (y+4.0)**2 - 3.0\n g_xy = (x-3.0)**2 + x*y + (y+4.0)**2 - 3.0\n outputs['g_xy'] = g_xy * 3\n\n self.count += 1\n\n prob = om.Problem()\n model = prob.model\n model.add_subsystem('px', om.IndepVarComp('x', val=3.0))\n model.add_subsystem('py', om.IndepVarComp('y', val=5.0))\n model.add_subsystem('parab', ParaboloidA())\n\n model.connect('px.x', 'parab.x')\n model.connect('py.y', 'parab.y')\n\n model.add_design_var('px.x', lower=-50, upper=50)\n model.add_design_var('py.y', lower=-50, upper=50)\n model.add_objective('parab.f_xy')\n\n prob.setup()\n prob.run_model()\n J = prob.compute_totals(of=['parab.f_xy'], wrt=['px.x', 'py.y'])\n # print(J)\n\n # 1. run_model; 2. step x; 3. step y\n self.assertEqual(model.parab.count, 3)\n\n def test_fd_count_driver(self):\n # Make sure we aren't doing FD wrt any var that isn't in the driver desvar set.\n\n class ParaboloidA(om.ExplicitComponent):\n def setup(self):\n self.add_input('x', val=0.0)\n self.add_input('y', val=0.0)\n\n self.add_output('f_xy', val=0.0)\n self.add_output('g_xy', val=0.0)\n\n self.count = 0\n\n def compute(self, inputs, outputs):\n x = inputs['x']\n y = inputs['y']\n\n outputs['f_xy'] = (x-3.0)**2 + x*y + (y+4.0)**2 - 3.0\n g_xy = (x-3.0)**2 + x*y + (y+4.0)**2 - 3.0\n outputs['g_xy'] = g_xy * 3\n\n self.count += 1\n\n prob = om.Problem()\n model = prob.model\n model.add_subsystem('px', om.IndepVarComp('x', val=3.0))\n model.add_subsystem('py', om.IndepVarComp('y', val=5.0))\n model.add_subsystem('parab', ParaboloidA())\n\n model.connect('px.x', 'parab.x')\n model.connect('py.y', 'parab.y')\n\n model.add_design_var('px.x', lower=-50, upper=50)\n model.add_objective('parab.f_xy')\n\n model.approx_totals(method='fd')\n\n prob.setup()\n prob.run_model()\n\n prob.driver._compute_totals(of=['parab.f_xy'], wrt=['px.x'], global_names=True)\n\n # 1. run_model; 2. step x\n self.assertEqual(model.parab.count, 2)\n\n def test_paraboloid_subbed(self):\n prob = om.Problem()\n model = prob.model\n model.add_subsystem('p1', om.IndepVarComp('x', 0.0), promotes=['x'])\n model.add_subsystem('p2', om.IndepVarComp('y', 0.0), promotes=['y'])\n sub = model.add_subsystem('sub', om.Group(), promotes=['x', 'y', 'f_xy'])\n sub.add_subsystem('comp', Paraboloid(), promotes=['x', 'y', 'f_xy'])\n\n model.linear_solver = om.ScipyKrylov()\n sub.approx_totals()\n\n prob.setup(check=False, mode='fwd')\n prob.set_solver_print(level=0)\n prob.run_model()\n\n of = ['f_xy']\n wrt = ['x', 'y']\n derivs = prob.compute_totals(of=of, wrt=wrt)\n\n assert_rel_error(self, derivs['f_xy', 'x'], [[-6.0]], 1e-6)\n assert_rel_error(self, derivs['f_xy', 'y'], [[8.0]], 1e-6)\n\n Jfd = sub._jacobian\n assert_rel_error(self, Jfd['sub.comp.f_xy', 'sub.comp.x'], [[-6.0]], 1e-6)\n assert_rel_error(self, Jfd['sub.comp.f_xy', 'sub.comp.y'], [[8.0]], 1e-6)\n\n # 1 output x 2 inputs\n self.assertEqual(len(sub._approx_schemes['fd']._exec_dict), 2)\n\n def test_paraboloid_subbed_in_setup(self):\n class MyModel(om.Group):\n\n def setup(self):\n self.add_subsystem('comp', Paraboloid(), promotes=['x', 'y', 'f_xy'])\n\n self.approx_totals()\n\n prob = om.Problem()\n model = prob.model\n model.add_subsystem('p1', om.IndepVarComp('x', 0.0), promotes=['x'])\n model.add_subsystem('p2', om.IndepVarComp('y', 0.0), promotes=['y'])\n sub = model.add_subsystem('sub', MyModel(), promotes=['x', 'y', 'f_xy'])\n\n model.linear_solver = om.ScipyKrylov()\n\n prob.setup(check=False, mode='fwd')\n prob.set_solver_print(level=0)\n prob.run_model()\n\n of = ['f_xy']\n wrt = ['x', 'y']\n derivs = prob.compute_totals(of=of, wrt=wrt)\n\n assert_rel_error(self, derivs['f_xy', 'x'], [[-6.0]], 1e-6)\n assert_rel_error(self, derivs['f_xy', 'y'], [[8.0]], 1e-6)\n\n Jfd = sub._jacobian\n assert_rel_error(self, Jfd['sub.comp.f_xy', 'sub.comp.x'], [[-6.0]], 1e-6)\n assert_rel_error(self, Jfd['sub.comp.f_xy', 'sub.comp.y'], [[8.0]], 1e-6)\n\n # 1 output x 2 inputs\n self.assertEqual(len(sub._approx_schemes['fd']._exec_dict), 2)\n\n def test_paraboloid_subbed_with_connections(self):\n prob = om.Problem()\n model = prob.model\n model.add_subsystem('p1', om.IndepVarComp('x', 0.0))\n model.add_subsystem('p2', om.IndepVarComp('y', 0.0))\n sub = model.add_subsystem('sub', om.Group())\n sub.add_subsystem('bx', om.ExecComp('xout = xin'))\n sub.add_subsystem('by', om.ExecComp('yout = yin'))\n sub.add_subsystem('comp', Paraboloid())\n\n model.connect('p1.x', 'sub.bx.xin')\n model.connect('sub.bx.xout', 'sub.comp.x')\n model.connect('p2.y', 'sub.by.yin')\n model.connect('sub.by.yout', 'sub.comp.y')\n\n model.linear_solver = om.ScipyKrylov()\n sub.approx_totals()\n\n prob.setup(check=False, mode='fwd')\n prob.set_solver_print(level=0)\n prob.run_model()\n\n of = ['sub.comp.f_xy']\n wrt = ['p1.x', 'p2.y']\n derivs = prob.compute_totals(of=of, wrt=wrt)\n\n assert_rel_error(self, derivs['sub.comp.f_xy', 'p1.x'], [[-6.0]], 1e-6)\n assert_rel_error(self, derivs['sub.comp.f_xy', 'p2.y'], [[8.0]], 1e-6)\n\n Jfd = sub._jacobian\n assert_rel_error(self, Jfd['sub.comp.f_xy', 'sub.bx.xin'], [[-6.0]], 1e-6)\n assert_rel_error(self, Jfd['sub.comp.f_xy', 'sub.by.yin'], [[8.0]], 1e-6)\n\n # 3 outputs x 2 inputs\n n_entries = 0\n for k, v in sub._approx_schemes['fd']._exec_dict.items():\n n_entries += len(v)\n self.assertEqual(n_entries, 6)\n\n def test_array_comp(self):\n\n class DoubleArrayFD(DoubleArrayComp):\n\n def compute_partials(self, inputs, partials):\n \"\"\"\n Override deriv calculation.\n \"\"\"\n pass\n\n prob = om.Problem()\n model = prob.model\n\n model.add_subsystem('p1', om.IndepVarComp('x1', val=np.ones(2)))\n model.add_subsystem('p2', om.IndepVarComp('x2', val=np.ones(2)))\n comp = model.add_subsystem('comp', DoubleArrayFD())\n model.connect('p1.x1', 'comp.x1')\n model.connect('p2.x2', 'comp.x2')\n\n model.linear_solver = om.ScipyKrylov()\n model.approx_totals()\n\n prob.setup()\n prob.run_model()\n model.run_linearize()\n\n Jfd = model._jacobian\n assert_rel_error(self, Jfd['comp.y1', 'p1.x1'], comp.JJ[0:2, 0:2], 1e-6)\n assert_rel_error(self, Jfd['comp.y1', 'p2.x2'], comp.JJ[0:2, 2:4], 1e-6)\n assert_rel_error(self, Jfd['comp.y2', 'p1.x1'], comp.JJ[2:4, 0:2], 1e-6)\n assert_rel_error(self, Jfd['comp.y2', 'p2.x2'], comp.JJ[2:4, 2:4], 1e-6)\n\n def test_implicit_component_fd(self):\n # Somehow this wasn't tested in the original fd tests (which are mostly feature tests.)\n\n class TestImplCompArrayDense(TestImplCompArray):\n\n def setup(self):\n super(TestImplCompArrayDense, self).setup()\n self.declare_partials('*', '*', method='fd')\n\n prob = om.Problem()\n model = prob.model\n\n model.add_subsystem('p_rhs', om.IndepVarComp('rhs', val=np.ones(2)))\n sub = model.add_subsystem('sub', om.Group())\n comp = sub.add_subsystem('comp', TestImplCompArrayDense())\n model.connect('p_rhs.rhs', 'sub.comp.rhs')\n\n model.linear_solver = om.ScipyKrylov()\n\n prob.setup()\n prob.run_model()\n model.run_linearize()\n\n Jfd = comp._jacobian\n assert_rel_error(self, Jfd['sub.comp.x', 'sub.comp.rhs'], -np.eye(2), 1e-6)\n assert_rel_error(self, Jfd['sub.comp.x', 'sub.comp.x'], comp.mtx, 1e-6)\n\n def test_around_newton(self):\n # For a group that is set to FD that has a Newton solver, make sure it doesn't\n # try to FD itself while solving.\n\n class TestImplCompArrayDenseNoSolve(TestImplCompArrayDense):\n def solve_nonlinear(self, inputs, outputs):\n \"\"\" Disable local solve.\"\"\"\n pass\n\n prob = om.Problem()\n model = prob.model\n\n model.add_subsystem('p_rhs', om.IndepVarComp('rhs', val=np.array([2, 4])))\n model.add_subsystem('comp', TestImplCompArrayDenseNoSolve())\n model.connect('p_rhs.rhs', 'comp.rhs')\n\n model.nonlinear_solver = om.NewtonSolver()\n model.linear_solver = om.ScipyKrylov()\n model.approx_totals()\n\n prob.setup()\n prob.run_model()\n model.approx_totals()\n assert_rel_error(self, prob['comp.x'], [1.97959184, 4.02040816], 1e-5)\n\n model.run_linearize()\n\n of = ['comp.x']\n wrt = ['p_rhs.rhs']\n Jfd = prob.compute_totals(of=of, wrt=wrt)\n\n assert_rel_error(self, Jfd['comp.x', 'p_rhs.rhs'],\n [[1.01020408, -0.01020408], [-0.01020408, 1.01020408]], 1e-5)\n\n def test_step_size(self):\n # Test makes sure option metadata propagates to the fd function\n prob = om.Problem()\n model = prob.model\n model.add_subsystem('p1', om.IndepVarComp('x', 0.0), promotes=['x'])\n model.add_subsystem('p2', om.IndepVarComp('y', 0.0), promotes=['y'])\n model.add_subsystem('comp', Paraboloid(), promotes=['x', 'y', 'f_xy'])\n\n model.linear_solver = om.ScipyKrylov()\n\n # Worse step so that our answer will be off a wee bit.\n model.approx_totals(step=1e-2)\n\n prob.setup(check=False, mode='fwd')\n prob.set_solver_print(level=0)\n prob.run_model()\n\n of = ['f_xy']\n wrt = ['x', 'y']\n derivs = prob.compute_totals(of=of, wrt=wrt)\n\n assert_rel_error(self, derivs['f_xy', 'x'], [[-5.99]], 1e-6)\n assert_rel_error(self, derivs['f_xy', 'y'], [[8.01]], 1e-6)\n\n def test_unit_conv_group(self):\n\n prob = om.Problem()\n prob.model.add_subsystem('px1', om.IndepVarComp('x1', 100.0), promotes=['x1'])\n sub1 = prob.model.add_subsystem('sub1', om.Group())\n sub2 = prob.model.add_subsystem('sub2', om.Group())\n\n sub1.add_subsystem('src', SrcComp())\n sub2.add_subsystem('tgtF', TgtCompF())\n sub2.add_subsystem('tgtC', TgtCompC())\n sub2.add_subsystem('tgtK', TgtCompK())\n\n prob.model.connect('x1', 'sub1.src.x1')\n prob.model.connect('sub1.src.x2', 'sub2.tgtF.x2')\n prob.model.connect('sub1.src.x2', 'sub2.tgtC.x2')\n prob.model.connect('sub1.src.x2', 'sub2.tgtK.x2')\n\n sub2.approx_totals(method='fd')\n\n prob.setup()\n prob.run_model()\n\n assert_rel_error(self, prob['sub1.src.x2'], 100.0, 1e-6)\n assert_rel_error(self, prob['sub2.tgtF.x3'], 212.0, 1e-6)\n assert_rel_error(self, prob['sub2.tgtC.x3'], 100.0, 1e-6)\n assert_rel_error(self, prob['sub2.tgtK.x3'], 373.15, 1e-6)\n\n wrt = ['x1']\n of = ['sub2.tgtF.x3', 'sub2.tgtC.x3', 'sub2.tgtK.x3']\n J = prob.compute_totals(of=of, wrt=wrt, return_format='dict')\n\n assert_rel_error(self, J['sub2.tgtF.x3']['x1'][0][0], 1.8, 1e-6)\n assert_rel_error(self, J['sub2.tgtC.x3']['x1'][0][0], 1.0, 1e-6)\n assert_rel_error(self, J['sub2.tgtK.x3']['x1'][0][0], 1.0, 1e-6)\n\n # Check the total derivatives in reverse mode\n prob.setup(check=False, mode='rev')\n prob.run_model()\n J = prob.compute_totals(of=of, wrt=wrt, return_format='dict')\n\n assert_rel_error(self, J['sub2.tgtF.x3']['x1'][0][0], 1.8, 1e-6)\n assert_rel_error(self, J['sub2.tgtC.x3']['x1'][0][0], 1.0, 1e-6)\n assert_rel_error(self, J['sub2.tgtK.x3']['x1'][0][0], 1.0, 1e-6)\n\n def test_sellar(self):\n # Basic sellar test.\n\n prob = om.Problem()\n model = prob.model\n\n model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x'])\n model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z'])\n\n model.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2'])\n model.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2'])\n\n model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)',\n z=np.array([0.0, 0.0]), x=0.0),\n promotes=['obj', 'x', 'z', 'y1', 'y2'])\n\n model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1'])\n model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2'])\n\n prob.model.nonlinear_solver = om.NonlinearBlockGS()\n\n model.approx_totals(method='fd', step=1e-5)\n\n prob.setup()\n prob.set_solver_print(level=0)\n prob.run_model()\n\n assert_rel_error(self, prob['y1'], 25.58830273, .00001)\n assert_rel_error(self, prob['y2'], 12.05848819, .00001)\n\n wrt = ['z']\n of = ['obj']\n\n J = prob.compute_totals(of=of, wrt=wrt, return_format='flat_dict')\n assert_rel_error(self, J['obj', 'z'][0][0], 9.61001056, .00001)\n assert_rel_error(self, J['obj', 'z'][0][1], 1.78448534, .00001)\n\n def test_desvar_with_indices(self):\n # Just desvars on this one to cover code missed by desvar+response test.\n\n class ArrayComp2D(om.ExplicitComponent):\n \"\"\"\n A fairly simple array component.\n \"\"\"\n\n def setup(self):\n\n self.JJ = np.array([[1.0, 3.0, -2.0, 7.0],\n [6.0, 2.5, 2.0, 4.0],\n [-1.0, 0.0, 8.0, 1.0],\n [1.0, 4.0, -5.0, 6.0]])\n\n # Params\n self.add_input('x1', np.zeros([4]))\n\n # Unknowns\n self.add_output('y1', np.zeros([4]))\n\n # Derivatives\n self.declare_partials('*', '*')\n\n def compute(self, inputs, outputs):\n \"\"\"\n Execution.\n \"\"\"\n outputs['y1'] = self.JJ.dot(inputs['x1'])\n\n def compute_partials(self, inputs, partials):\n \"\"\"\n Analytical derivatives.\n \"\"\"\n partials[('y1', 'x1')] = self.JJ\n\n prob = om.Problem()\n model = prob.model\n model.add_subsystem('x_param1', om.IndepVarComp('x1', np.ones((4))),\n promotes=['x1'])\n mycomp = model.add_subsystem('mycomp', ArrayComp2D(), promotes=['x1', 'y1'])\n\n model.add_design_var('x1', indices=[1, 3])\n model.add_constraint('y1')\n\n prob.set_solver_print(level=0)\n model.approx_totals(method='fd')\n\n prob.setup(check=False, mode='fwd')\n prob.run_model()\n\n Jbase = mycomp.JJ\n of = ['y1']\n wrt = ['x1']\n\n J = prob.compute_totals(of=of, wrt=wrt, return_format='flat_dict')\n assert_rel_error(self, J['y1', 'x1'][0][0], Jbase[0, 1], 1e-8)\n assert_rel_error(self, J['y1', 'x1'][0][1], Jbase[0, 3], 1e-8)\n assert_rel_error(self, J['y1', 'x1'][2][0], Jbase[2, 1], 1e-8)\n assert_rel_error(self, J['y1', 'x1'][2][1], Jbase[2, 3], 1e-8)\n\n def test_desvar_and_response_with_indices(self):\n\n class ArrayComp2D(om.ExplicitComponent):\n \"\"\"\n A fairly simple array component.\n \"\"\"\n\n def setup(self):\n\n self.JJ = np.array([[1.0, 3.0, -2.0, 7.0],\n [6.0, 2.5, 2.0, 4.0],\n [-1.0, 0.0, 8.0, 1.0],\n [1.0, 4.0, -5.0, 6.0]])\n\n # Params\n self.add_input('x1', np.zeros([4]))\n\n # Unknowns\n self.add_output('y1', np.zeros([4]))\n\n self.declare_partials(of='*', wrt='*')\n\n def compute(self, inputs, outputs):\n \"\"\"\n Execution.\n \"\"\"\n outputs['y1'] = self.JJ.dot(inputs['x1'])\n\n def compute_partials(self, inputs, partials):\n \"\"\"\n Analytical derivatives.\n \"\"\"\n partials[('y1', 'x1')] = self.JJ\n\n prob = om.Problem()\n model = prob.model\n model.add_subsystem('x_param1', om.IndepVarComp('x1', np.ones((4))),\n promotes=['x1'])\n mycomp = model.add_subsystem('mycomp', ArrayComp2D(), promotes=['x1', 'y1'])\n\n model.add_design_var('x1', indices=[1, 3])\n model.add_constraint('y1', indices=[0, 2])\n\n prob.set_solver_print(level=0)\n model.approx_totals(method='fd')\n\n prob.setup(check=False, mode='fwd')\n prob.run_model()\n\n Jbase = mycomp.JJ\n of = ['y1']\n wrt = ['x1']\n\n J = prob.compute_totals(of=of, wrt=wrt, return_format='flat_dict')\n assert_rel_error(self, J['y1', 'x1'][0][0], Jbase[0, 1], 1e-8)\n assert_rel_error(self, J['y1', 'x1'][0][1], Jbase[0, 3], 1e-8)\n assert_rel_error(self, J['y1', 'x1'][1][0], Jbase[2, 1], 1e-8)\n assert_rel_error(self, J['y1', 'x1'][1][1], Jbase[2, 3], 1e-8)\n\n def test_full_model_fd(self):\n\n class DontCall(om.LinearRunOnce):\n def solve(self, vec_names, mode, rel_systems=None):\n raise RuntimeError(\"This solver should be ignored!\")\n\n class Simple(om.ExplicitComponent):\n def setup(self):\n self.add_input('x', val=0.0)\n self.add_output('y', val=0.0)\n\n self.declare_partials('y', 'x')\n\n def compute(self, inputs, outputs):\n x = inputs['x']\n outputs['y'] = 4.0*x\n\n prob = om.Problem()\n model = prob.model\n model.add_subsystem('p1', om.IndepVarComp('x', 0.0), promotes=['x'])\n model.add_subsystem('comp', Simple(), promotes=['x', 'y'])\n\n model.linear_solver = DontCall()\n model.approx_totals()\n\n model.add_design_var('x')\n model.add_objective('y')\n\n prob.setup(check=False, mode='fwd')\n prob.set_solver_print(level=0)\n prob.run_model()\n\n of = ['comp.y']\n wrt = ['p1.x']\n derivs = prob.driver._compute_totals(of=of, wrt=wrt, return_format='dict')\n\n assert_rel_error(self, derivs['comp.y']['p1.x'], [[4.0]], 1e-6)\n\n def test_newton_with_densejac_under_full_model_fd(self):\n # Basic sellar test.\n\n prob = om.Problem()\n model = prob.model = om.Group(assembled_jac_type='dense')\n sub = model.add_subsystem('sub', om.Group(), promotes=['*'])\n\n model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x'])\n model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z'])\n\n sub.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2'])\n sub.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2'])\n\n model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)',\n z=np.array([0.0, 0.0]), x=0.0),\n promotes=['obj', 'x', 'z', 'y1', 'y2'])\n\n model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1'])\n model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2'])\n\n sub.nonlinear_solver = om.NewtonSolver()\n sub.linear_solver = om.ScipyKrylov(assemble_jac=True)\n\n model.approx_totals(method='fd', step=1e-5)\n\n prob.setup()\n prob.set_solver_print(level=0)\n prob.run_model()\n\n assert_rel_error(self, prob['y1'], 25.58830273, .00001)\n assert_rel_error(self, prob['y2'], 12.05848819, .00001)\n\n wrt = ['z']\n of = ['obj']\n\n J = prob.compute_totals(of=of, wrt=wrt, return_format='flat_dict')\n assert_rel_error(self, J['obj', 'z'][0][0], 9.61001056, .00001)\n assert_rel_error(self, J['obj', 'z'][0][1], 1.78448534, .00001)\n\n def test_newton_with_cscjac_under_full_model_fd(self):\n # Basic sellar test.\n\n prob = om.Problem()\n model = prob.model\n sub = model.add_subsystem('sub', om.Group(), promotes=['*'])\n\n model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x'])\n model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z'])\n\n sub.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2'])\n sub.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2'])\n\n model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)',\n z=np.array([0.0, 0.0]), x=0.0),\n promotes=['obj', 'x', 'z', 'y1', 'y2'])\n\n model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1'])\n model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2'])\n\n sub.nonlinear_solver = om.NewtonSolver()\n sub.linear_solver = om.ScipyKrylov(assemble_jac=True)\n\n model.approx_totals(method='fd', step=1e-5)\n\n prob.setup()\n prob.set_solver_print(level=0)\n prob.run_model()\n\n assert_rel_error(self, prob['y1'], 25.58830273, .00001)\n assert_rel_error(self, prob['y2'], 12.05848819, .00001)\n\n wrt = ['z']\n of = ['obj']\n\n J = prob.compute_totals(of=of, wrt=wrt, return_format='flat_dict')\n assert_rel_error(self, J['obj', 'z'][0][0], 9.61001056, .00001)\n assert_rel_error(self, J['obj', 'z'][0][1], 1.78448534, .00001)\n\n def test_approx_totals_multi_input_constrained_desvar(self):\n p = om.Problem()\n\n indeps = p.model.add_subsystem('indeps', om.IndepVarComp(), promotes_outputs=['*'])\n\n indeps.add_output('x', np.array([ 0.55994437, -0.95923447, 0.21798656, -0.02158783, 0.62183717,\n 0.04007379, 0.46044942, -0.10129622, 0.27720413, -0.37107886]))\n indeps.add_output('y', np.array([ 0.52577864, 0.30894559, 0.8420792 , 0.35039912, -0.67290778,\n -0.86236787, -0.97500023, 0.47739414, 0.51174103, 0.10052582]))\n indeps.add_output('r', .7)\n\n arctan_yox = om.ExecComp('g=arctan(y/x)', vectorize=True,\n g=np.ones(10), x=np.ones(10), y=np.ones(10))\n\n p.model.add_subsystem('arctan_yox', arctan_yox)\n\n p.model.add_subsystem('circle', om.ExecComp('area=pi*r**2'))\n\n p.model.add_subsystem('r_con', om.ExecComp('g=x**2 + y**2 - r', vectorize=True,\n g=np.ones(10), x=np.ones(10), y=np.ones(10)))\n\n p.model.connect('r', ('circle.r', 'r_con.r'))\n p.model.connect('x', ['r_con.x', 'arctan_yox.x'])\n p.model.connect('y', ['r_con.y', 'arctan_yox.y'])\n\n p.model.approx_totals(method='cs')\n\n p.model.add_design_var('x')\n p.model.add_design_var('y')\n p.model.add_design_var('r', lower=.5, upper=10)\n p.model.add_constraint('y', equals=0, indices=[0,])\n p.model.add_objective('circle.area', ref=-1)\n\n p.setup(derivatives=True)\n\n p.run_model()\n # Formerly a KeyError\n derivs = p.check_totals(compact_print=True, out_stream=None)\n assert_rel_error(self, 0.0, derivs['indeps.y', 'indeps.x']['abs error'][0])\n\n # Coverage\n derivs = p.driver._compute_totals(return_format='dict')\n assert_rel_error(self, np.zeros((1, 10)), derivs['indeps.y']['indeps.x'])\n\n def test_opt_with_linear_constraint(self):\n # Test for a bug where we weren't re-initializing things in-between computing totals on\n # linear constraints, and the nonlinear ones.\n if OPT is None:\n raise unittest.SkipTest(\"pyoptsparse is not installed\")\n\n if OPTIMIZER is None:\n raise unittest.SkipTest(\"pyoptsparse is not providing SNOPT or SLSQP\")\n\n p = om.Problem()\n\n indeps = p.model.add_subsystem('indeps', om.IndepVarComp(), promotes_outputs=['*'])\n\n indeps.add_output('x', np.array([ 0.55994437, -0.95923447, 0.21798656, -0.02158783, 0.62183717,\n 0.04007379, 0.46044942, -0.10129622, 0.27720413, -0.37107886]))\n indeps.add_output('y', np.array([ 0.52577864, 0.30894559, 0.8420792 , 0.35039912, -0.67290778,\n -0.86236787, -0.97500023, 0.47739414, 0.51174103, 0.10052582]))\n indeps.add_output('r', .7)\n\n arctan_yox = om.ExecComp('g=arctan(y/x)', vectorize=True,\n g=np.ones(10), x=np.ones(10), y=np.ones(10))\n\n p.model.add_subsystem('arctan_yox', arctan_yox)\n\n p.model.add_subsystem('circle', om.ExecComp('area=pi*r**2'))\n\n p.model.add_subsystem('r_con', om.ExecComp('g=x**2 + y**2 - r', vectorize=True,\n g=np.ones(10), x=np.ones(10), y=np.ones(10)))\n\n thetas = np.linspace(0, np.pi/4, 10)\n p.model.add_subsystem('theta_con', om.ExecComp('g = x - theta', vectorize=True,\n g=np.ones(10), x=np.ones(10),\n theta=thetas))\n p.model.add_subsystem('delta_theta_con', om.ExecComp('g = even - odd', vectorize=True,\n g=np.ones(10//2), even=np.ones(10//2),\n odd=np.ones(10//2)))\n\n p.model.add_subsystem('l_conx', om.ExecComp('g=x-1', vectorize=True, g=np.ones(10), x=np.ones(10)))\n\n IND = np.arange(10, dtype=int)\n ODD_IND = IND[1::2] # all odd indices\n EVEN_IND = IND[0::2] # all even indices\n\n p.model.connect('r', ('circle.r', 'r_con.r'))\n p.model.connect('x', ['r_con.x', 'arctan_yox.x', 'l_conx.x'])\n p.model.connect('y', ['r_con.y', 'arctan_yox.y'])\n p.model.connect('arctan_yox.g', 'theta_con.x')\n p.model.connect('arctan_yox.g', 'delta_theta_con.even', src_indices=EVEN_IND)\n p.model.connect('arctan_yox.g', 'delta_theta_con.odd', src_indices=ODD_IND)\n\n p.driver = pyOptSparseDriver()\n p.driver.options['print_results'] = False\n p.model.approx_totals(method='fd')\n\n p.model.add_design_var('x')\n p.model.add_design_var('y')\n p.model.add_design_var('r', lower=.5, upper=10)\n\n # nonlinear constraints\n p.model.add_constraint('r_con.g', equals=0)\n\n p.model.add_constraint('theta_con.g', lower=-1e-5, upper=1e-5, indices=EVEN_IND)\n p.model.add_constraint('delta_theta_con.g', lower=-1e-5, upper=1e-5)\n p.model.add_constraint('l_conx.g', equals=0, linear=False, indices=[0,])\n p.model.add_constraint('y', equals=0, indices=[0,], linear=True)\n\n p.model.add_objective('circle.area', ref=-1)\n\n p.setup(mode='fwd', derivatives=True)\n\n p.run_driver()\n\n assert_rel_error(self, p['circle.area'], np.pi, 1e-6)\n\n\[email protected](MPI and not PETScVector, \"only run under MPI if we have PETSc.\")\nclass TestGroupFiniteDifferenceMPI(unittest.TestCase):\n\n N_PROCS = 2\n\n def test_indepvarcomp_under_par_sys(self):\n prob = om.Problem()\n prob.model = FanInSubbedIDVC()\n\n prob.setup(local_vector_class=vector_class, check=False, mode='rev')\n prob.model.approx_totals()\n prob.set_solver_print(level=0)\n prob.run_model()\n\n J = prob.compute_totals(wrt=['sub.sub1.p1.x', 'sub.sub2.p2.x'], of=['sum.y'])\n assert_rel_error(self, J['sum.y', 'sub.sub1.p1.x'], [[2.0]], 1.0e-6)\n assert_rel_error(self, J['sum.y', 'sub.sub2.p2.x'], [[4.0]], 1.0e-6)\n\n\[email protected](MPI and not PETScVector, \"only run under MPI if we have PETSc.\")\nclass TestGroupCSMPI(unittest.TestCase):\n\n N_PROCS = 2\n\n def test_indepvarcomp_under_par_sys_par_cs(self):\n prob = om.Problem()\n prob.model = FanInSubbedIDVC(num_par_fd=2)\n prob.model.approx_totals(method='cs')\n\n prob.setup(local_vector_class=vector_class, check=False, mode='rev')\n prob.set_solver_print(level=0)\n prob.run_model()\n\n J = prob.compute_totals(wrt=['sub.sub1.p1.x', 'sub.sub2.p2.x'], of=['sum.y'])\n assert_rel_error(self, J['sum.y', 'sub.sub1.p1.x'], [[2.0]], 1.0e-6)\n assert_rel_error(self, J['sum.y', 'sub.sub2.p2.x'], [[4.0]], 1.0e-6)\n\n def test_newton_with_direct_solver(self):\n # Make sure this works under mpi with bug fixed in norm calculation.\n\n if not PETScVector:\n raise unittest.SkipTest(\"PETSc is not installed\")\n\n prob = om.Problem()\n model = prob.model\n sub = model.add_subsystem('sub', om.Group(), promotes=['*'])\n\n model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x'])\n model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z'])\n\n sub.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2'])\n sub.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2'])\n\n model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)',\n z=np.array([0.0, 0.0]), x=0.0),\n promotes=['obj', 'x', 'z', 'y1', 'y2'])\n\n model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1'])\n model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2'])\n\n sub.nonlinear_solver = om.NewtonSolver()\n sub.linear_solver = om.DirectSolver(assemble_jac=False)\n sub.nonlinear_solver.options['atol'] = 1e-10\n sub.nonlinear_solver.options['rtol'] = 1e-10\n\n model.approx_totals(method='cs')\n\n prob.setup(check=False, local_vector_class=PETScVector)\n prob.set_solver_print(level=0)\n prob.run_model()\n\n assert_rel_error(self, prob['y1'], 25.58830273, .00001)\n assert_rel_error(self, prob['y2'], 12.05848819, .00001)\n\n wrt = ['z', 'x']\n of = ['obj', 'con1', 'con2']\n\n J = prob.compute_totals(of=of, wrt=wrt, return_format='flat_dict')\n assert_rel_error(self, J['obj', 'z'][0][0], 9.61001056, 1.0e-6)\n assert_rel_error(self, J['obj', 'z'][0][1], 1.78448534, 1.0e-6)\n assert_rel_error(self, J['obj', 'x'][0][0], 2.98061391, 1.0e-6)\n assert_rel_error(self, J['con1', 'z'][0][0], -9.61002186, 1.0e-6)\n assert_rel_error(self, J['con1', 'z'][0][1], -0.78449158, 1.0e-6)\n assert_rel_error(self, J['con1', 'x'][0][0], -0.98061448, 1.0e-6)\n\n\[email protected](MPI and not PETScVector, \"only run under MPI if we have PETSc.\")\nclass TestGroupFDMPI(unittest.TestCase):\n\n N_PROCS = 2\n\n def test_indepvarcomp_under_par_sys_par_fd(self):\n prob = om.Problem()\n prob.model = FanInSubbedIDVC(num_par_fd=2)\n\n prob.model.approx_totals(method='fd')\n prob.setup(local_vector_class=vector_class, check=False, mode='rev')\n prob.set_solver_print(level=0)\n prob.run_model()\n\n J = prob.compute_totals(wrt=['sub.sub1.p1.x', 'sub.sub2.p2.x'], of=['sum.y'])\n assert_rel_error(self, J['sum.y', 'sub.sub1.p1.x'], [[2.0]], 1.0e-6)\n assert_rel_error(self, J['sum.y', 'sub.sub2.p2.x'], [[4.0]], 1.0e-6)\n\n\ndef title(txt):\n \"\"\" Provide nice title for parameterized testing.\"\"\"\n return str(txt).split('.')[-1].replace(\"'\", '').replace('>', '')\n\n\nclass TestGroupComplexStep(unittest.TestCase):\n\n def setUp(self):\n\n self.prob = om.Problem()\n\n def tearDown(self):\n # Global stuff seems to not get cleaned up if test fails.\n try:\n self.prob.model._outputs._under_complex_step = False\n except Exception:\n pass\n\n @parameterized.expand(itertools.product([om.DefaultVector, PETScVector]),\n name_func=lambda f, n, p:\n 'test_paraboloid_'+'_'.join(title(a) for a in p.args))\n def test_paraboloid(self, vec_class):\n\n if not vec_class:\n raise unittest.SkipTest(\"PETSc is not installed\")\n\n prob = self.prob\n model = prob.model\n model.add_subsystem('p1', om.IndepVarComp('x', 0.0), promotes=['x'])\n model.add_subsystem('p2', om.IndepVarComp('y', 0.0), promotes=['y'])\n model.add_subsystem('comp', Paraboloid(), promotes=['x', 'y', 'f_xy'])\n\n model.linear_solver = om.ScipyKrylov()\n model.approx_totals(method='cs')\n\n prob.setup(check=False, mode='fwd', local_vector_class=vec_class)\n prob.set_solver_print(level=0)\n prob.run_model()\n\n of = ['f_xy']\n wrt = ['x', 'y']\n derivs = prob.compute_totals(of=of, wrt=wrt)\n\n assert_rel_error(self, derivs['f_xy', 'x'], [[-6.0]], 1e-6)\n assert_rel_error(self, derivs['f_xy', 'y'], [[8.0]], 1e-6)\n\n # 1 output x 2 inputs\n self.assertEqual(len(model._approx_schemes['cs']._exec_dict), 2)\n\n @parameterized.expand(itertools.product([om.DefaultVector, PETScVector]),\n name_func=lambda f, n, p:\n 'test_paraboloid_subbed_'+'_'.join(title(a) for a in p.args))\n def test_paraboloid_subbed(self, vec_class):\n\n if not vec_class:\n raise unittest.SkipTest(\"PETSc is not installed\")\n\n prob = self.prob\n model = prob.model\n model.add_subsystem('p1', om.IndepVarComp('x', 0.0), promotes=['x'])\n model.add_subsystem('p2', om.IndepVarComp('y', 0.0), promotes=['y'])\n sub = model.add_subsystem('sub', om.Group(), promotes=['x', 'y', 'f_xy'])\n sub.add_subsystem('comp', Paraboloid(), promotes=['x', 'y', 'f_xy'])\n\n model.linear_solver = om.ScipyKrylov()\n sub.approx_totals(method='cs')\n\n prob.setup(check=False, mode='fwd', local_vector_class=vec_class)\n prob.set_solver_print(level=0)\n prob.run_model()\n\n of = ['f_xy']\n wrt = ['x', 'y']\n derivs = prob.compute_totals(of=of, wrt=wrt)\n\n assert_rel_error(self, derivs['f_xy', 'x'], [[-6.0]], 1e-6)\n assert_rel_error(self, derivs['f_xy', 'y'], [[8.0]], 1e-6)\n\n Jfd = sub._jacobian\n assert_rel_error(self, Jfd['sub.comp.f_xy', 'sub.comp.x'], [[-6.0]], 1e-6)\n assert_rel_error(self, Jfd['sub.comp.f_xy', 'sub.comp.y'], [[8.0]], 1e-6)\n\n # 1 output x 2 inputs\n self.assertEqual(len(sub._approx_schemes['cs']._exec_dict), 2)\n\n @parameterized.expand(itertools.product([om.DefaultVector, PETScVector]),\n name_func=lambda f, n, p:\n 'test_parab_subbed_with_connections_'+'_'.join(title(a) for a in p.args))\n def test_paraboloid_subbed_with_connections(self, vec_class):\n\n if not vec_class:\n raise unittest.SkipTest(\"PETSc is not installed\")\n\n prob = self.prob\n model = prob.model\n model.add_subsystem('p1', om.IndepVarComp('x', 0.0))\n model.add_subsystem('p2', om.IndepVarComp('y', 0.0))\n sub = model.add_subsystem('sub', om.Group())\n sub.add_subsystem('bx', om.ExecComp('xout = xin'))\n sub.add_subsystem('by', om.ExecComp('yout = yin'))\n sub.add_subsystem('comp', Paraboloid())\n\n model.connect('p1.x', 'sub.bx.xin')\n model.connect('sub.bx.xout', 'sub.comp.x')\n model.connect('p2.y', 'sub.by.yin')\n model.connect('sub.by.yout', 'sub.comp.y')\n\n model.linear_solver = om.ScipyKrylov()\n sub.approx_totals(method='cs')\n\n prob.setup(check=False, mode='fwd', local_vector_class=vec_class)\n prob.set_solver_print(level=0)\n prob.run_model()\n\n of = ['sub.comp.f_xy']\n wrt = ['p1.x', 'p2.y']\n derivs = prob.compute_totals(of=of, wrt=wrt)\n\n assert_rel_error(self, derivs['sub.comp.f_xy', 'p1.x'], [[-6.0]], 1e-6)\n assert_rel_error(self, derivs['sub.comp.f_xy', 'p2.y'], [[8.0]], 1e-6)\n\n Jfd = sub._jacobian\n assert_rel_error(self, Jfd['sub.comp.f_xy', 'sub.bx.xin'], [[-6.0]], 1e-6)\n assert_rel_error(self, Jfd['sub.comp.f_xy', 'sub.by.yin'], [[8.0]], 1e-6)\n\n # 3 outputs x 2 inputs\n n_entries = 0\n for k, v in sub._approx_schemes['cs']._exec_dict.items():\n n_entries += len(v)\n self.assertEqual(n_entries, 6)\n\n @parameterized.expand(itertools.product([om.DefaultVector, PETScVector]),\n name_func=lambda f, n, p:\n 'test_array_comp_'+'_'.join(title(a) for a in p.args))\n def test_array_comp(self, vec_class):\n\n if not vec_class:\n raise unittest.SkipTest(\"PETSc is not installed\")\n\n class DoubleArrayFD(DoubleArrayComp):\n\n def compute_partials(self, inputs, partials):\n \"\"\"\n Override deriv calculation.\n \"\"\"\n pass\n\n prob = self.prob\n model = prob.model\n\n model.add_subsystem('p1', om.IndepVarComp('x1', val=np.ones(2)))\n model.add_subsystem('p2', om.IndepVarComp('x2', val=np.ones(2)))\n comp = model.add_subsystem('comp', DoubleArrayFD())\n model.connect('p1.x1', 'comp.x1')\n model.connect('p2.x2', 'comp.x2')\n\n model.linear_solver = om.ScipyKrylov()\n model.approx_totals(method='cs')\n\n prob.setup(check=False, local_vector_class=vec_class)\n prob.run_model()\n model.run_linearize()\n\n Jfd = model._jacobian\n assert_rel_error(self, Jfd['comp.y1', 'p1.x1'], comp.JJ[0:2, 0:2], 1e-6)\n assert_rel_error(self, Jfd['comp.y1', 'p2.x2'], comp.JJ[0:2, 2:4], 1e-6)\n assert_rel_error(self, Jfd['comp.y2', 'p1.x1'], comp.JJ[2:4, 0:2], 1e-6)\n assert_rel_error(self, Jfd['comp.y2', 'p2.x2'], comp.JJ[2:4, 2:4], 1e-6)\n\n @parameterized.expand(itertools.product([om.DefaultVector, PETScVector]),\n name_func=lambda f, n, p:\n 'test_unit_conv_group_'+'_'.join(title(a) for a in p.args))\n def test_unit_conv_group(self, vec_class):\n\n if not vec_class:\n raise unittest.SkipTest(\"PETSc is not installed\")\n\n prob = self.prob\n prob.model.add_subsystem('px1', om.IndepVarComp('x1', 100.0), promotes=['x1'])\n sub1 = prob.model.add_subsystem('sub1', om.Group())\n sub2 = prob.model.add_subsystem('sub2', om.Group())\n\n sub1.add_subsystem('src', SrcComp())\n sub2.add_subsystem('tgtF', TgtCompF())\n sub2.add_subsystem('tgtC', TgtCompC())\n sub2.add_subsystem('tgtK', TgtCompK())\n\n prob.model.connect('x1', 'sub1.src.x1')\n prob.model.connect('sub1.src.x2', 'sub2.tgtF.x2')\n prob.model.connect('sub1.src.x2', 'sub2.tgtC.x2')\n prob.model.connect('sub1.src.x2', 'sub2.tgtK.x2')\n\n sub2.approx_totals(method='cs')\n\n prob.setup(check=False, local_vector_class=vec_class)\n prob.run_model()\n\n assert_rel_error(self, prob['sub1.src.x2'], 100.0, 1e-6)\n assert_rel_error(self, prob['sub2.tgtF.x3'], 212.0, 1e-6)\n assert_rel_error(self, prob['sub2.tgtC.x3'], 100.0, 1e-6)\n assert_rel_error(self, prob['sub2.tgtK.x3'], 373.15, 1e-6)\n\n wrt = ['x1']\n of = ['sub2.tgtF.x3', 'sub2.tgtC.x3', 'sub2.tgtK.x3']\n J = prob.compute_totals(of=of, wrt=wrt, return_format='dict')\n\n assert_rel_error(self, J['sub2.tgtF.x3']['x1'][0][0], 1.8, 1e-6)\n assert_rel_error(self, J['sub2.tgtC.x3']['x1'][0][0], 1.0, 1e-6)\n assert_rel_error(self, J['sub2.tgtK.x3']['x1'][0][0], 1.0, 1e-6)\n\n # Check the total derivatives in reverse mode\n prob.setup(check=False, mode='rev', local_vector_class=vec_class)\n prob.run_model()\n J = prob.compute_totals(of=of, wrt=wrt, return_format='dict')\n\n assert_rel_error(self, J['sub2.tgtF.x3']['x1'][0][0], 1.8, 1e-6)\n assert_rel_error(self, J['sub2.tgtC.x3']['x1'][0][0], 1.0, 1e-6)\n assert_rel_error(self, J['sub2.tgtK.x3']['x1'][0][0], 1.0, 1e-6)\n\n @parameterized.expand(itertools.product([om.DefaultVector, PETScVector]),\n name_func=lambda f, n, p:\n 'test_sellar_'+'_'.join(title(a) for a in p.args))\n def test_sellar(self, vec_class):\n # Basic sellar test.\n\n if not vec_class:\n raise unittest.SkipTest(\"PETSc is not installed\")\n\n prob = self.prob\n model = prob.model\n\n model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x'])\n model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z'])\n\n model.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2'])\n model.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2'])\n\n model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)',\n z=np.array([0.0, 0.0]), x=0.0),\n promotes=['obj', 'x', 'z', 'y1', 'y2'])\n\n model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1'])\n model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2'])\n\n prob.model.nonlinear_solver = om.NonlinearBlockGS()\n prob.model.nonlinear_solver.options['atol'] = 1e-50\n prob.model.nonlinear_solver.options['rtol'] = 1e-50\n\n model.approx_totals(method='cs')\n\n prob.setup(check=False, local_vector_class=vec_class)\n prob.set_solver_print(level=0)\n prob.run_model()\n\n assert_rel_error(self, prob['y1'], 25.58830273, .00001)\n assert_rel_error(self, prob['y2'], 12.05848819, .00001)\n\n wrt = ['z']\n of = ['obj']\n\n J = prob.compute_totals(of=of, wrt=wrt, return_format='flat_dict')\n assert_rel_error(self, J['obj', 'z'][0][0], 9.61001056, .00001)\n assert_rel_error(self, J['obj', 'z'][0][1], 1.78448534, .00001)\n\n self.assertFalse(model._vectors['output']['linear']._alloc_complex,\n msg=\"Linear vector should not be allocated as complex.\")\n\n def test_desvar_and_response_with_indices(self):\n\n class ArrayComp2D(om.ExplicitComponent):\n \"\"\"\n A fairly simple array component.\n \"\"\"\n\n def setup(self):\n\n self.JJ = np.array([[1.0, 3.0, -2.0, 7.0],\n [6.0, 2.5, 2.0, 4.0],\n [-1.0, 0.0, 8.0, 1.0],\n [1.0, 4.0, -5.0, 6.0]])\n\n # Params\n self.add_input('x1', np.zeros([4]))\n\n # Unknowns\n self.add_output('y1', np.zeros([4]))\n\n self.declare_partials(of='*', wrt='*')\n\n def compute(self, inputs, outputs):\n \"\"\"\n Execution.\n \"\"\"\n outputs['y1'] = self.JJ.dot(inputs['x1'])\n\n def compute_partials(self, inputs, partials):\n \"\"\"\n Analytical derivatives.\n \"\"\"\n partials[('y1', 'x1')] = self.JJ\n\n prob = om.Problem()\n model = prob.model\n model.add_subsystem('x_param1', om.IndepVarComp('x1', np.ones((4))),\n promotes=['x1'])\n mycomp = model.add_subsystem('mycomp', ArrayComp2D(), promotes=['x1', 'y1'])\n\n model.add_design_var('x1', indices=[1, 3])\n model.add_constraint('y1', indices=[0, 2])\n\n prob.set_solver_print(level=0)\n model.approx_totals(method='cs')\n\n prob.setup(check=False, mode='fwd')\n prob.run_model()\n\n Jbase = mycomp.JJ\n of = ['y1']\n wrt = ['x1']\n\n J = prob.compute_totals(of=of, wrt=wrt, return_format='flat_dict')\n assert_rel_error(self, J['y1', 'x1'][0][0], Jbase[0, 1], 1e-8)\n assert_rel_error(self, J['y1', 'x1'][0][1], Jbase[0, 3], 1e-8)\n assert_rel_error(self, J['y1', 'x1'][1][0], Jbase[2, 1], 1e-8)\n assert_rel_error(self, J['y1', 'x1'][1][1], Jbase[2, 3], 1e-8)\n\n def test_desvar_with_indices(self):\n # Just desvars on this one to cover code missed by desvar+response test.\n\n class ArrayComp2D(om.ExplicitComponent):\n \"\"\"\n A fairly simple array component.\n \"\"\"\n\n def setup(self):\n\n self.JJ = np.array([[1.0, 3.0, -2.0, 7.0],\n [6.0, 2.5, 2.0, 4.0],\n [-1.0, 0.0, 8.0, 1.0],\n [1.0, 4.0, -5.0, 6.0]])\n\n # Params\n self.add_input('x1', np.zeros([4]))\n\n # Unknowns\n self.add_output('y1', np.zeros([4]))\n\n self.declare_partials(of='*', wrt='*')\n\n def compute(self, inputs, outputs):\n \"\"\"\n Execution.\n \"\"\"\n outputs['y1'] = self.JJ.dot(inputs['x1'])\n\n def compute_partials(self, inputs, partials):\n \"\"\"\n Analytical derivatives.\n \"\"\"\n partials[('y1', 'x1')] = self.JJ\n\n prob = om.Problem()\n model = prob.model\n model.add_subsystem('x_param1', om.IndepVarComp('x1', np.ones((4))),\n promotes=['x1'])\n mycomp = model.add_subsystem('mycomp', ArrayComp2D(), promotes=['x1', 'y1'])\n\n model.add_design_var('x1', indices=[1, 3])\n model.add_constraint('y1')\n\n prob.set_solver_print(level=0)\n model.approx_totals(method='cs')\n\n prob.setup(check=False, mode='fwd')\n prob.run_model()\n\n Jbase = mycomp.JJ\n of = ['y1']\n wrt = ['x1']\n\n J = prob.compute_totals(of=of, wrt=wrt, return_format='flat_dict')\n assert_rel_error(self, J['y1', 'x1'][0][0], Jbase[0, 1], 1e-8)\n assert_rel_error(self, J['y1', 'x1'][0][1], Jbase[0, 3], 1e-8)\n assert_rel_error(self, J['y1', 'x1'][2][0], Jbase[2, 1], 1e-8)\n assert_rel_error(self, J['y1', 'x1'][2][1], Jbase[2, 3], 1e-8)\n\n @parameterized.expand(itertools.product([om.DefaultVector, PETScVector]),\n name_func=lambda f, n, p:\n 'test_newton_with_direct_solver_'+'_'.join(title(a) for a in p.args))\n def test_newton_with_direct_solver(self, vec_class):\n # Basic sellar test.\n\n if not vec_class:\n raise unittest.SkipTest(\"PETSc is not installed\")\n\n prob = om.Problem()\n model = prob.model\n sub = model.add_subsystem('sub', om.Group(), promotes=['*'])\n\n model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x'])\n model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z'])\n\n sub.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2'])\n sub.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2'])\n\n model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)',\n z=np.array([0.0, 0.0]), x=0.0),\n promotes=['obj', 'x', 'z', 'y1', 'y2'])\n\n model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1'])\n model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2'])\n\n sub.nonlinear_solver = om.NewtonSolver()\n sub.linear_solver = om.DirectSolver(assemble_jac=False)\n sub.nonlinear_solver.options['atol'] = 1e-10\n sub.nonlinear_solver.options['rtol'] = 1e-10\n\n model.approx_totals(method='cs')\n\n prob.setup(check=False, local_vector_class=vec_class)\n prob.set_solver_print(level=0)\n prob.run_model()\n\n assert_rel_error(self, prob['y1'], 25.58830273, .00001)\n assert_rel_error(self, prob['y2'], 12.05848819, .00001)\n\n wrt = ['z', 'x']\n of = ['obj', 'con1', 'con2']\n\n J = prob.compute_totals(of=of, wrt=wrt, return_format='flat_dict')\n assert_rel_error(self, J['obj', 'z'][0][0], 9.61001056, 1.0e-6)\n assert_rel_error(self, J['obj', 'z'][0][1], 1.78448534, 1.0e-6)\n assert_rel_error(self, J['obj', 'x'][0][0], 2.98061391, 1.0e-6)\n assert_rel_error(self, J['con1', 'z'][0][0], -9.61002186, 1.0e-6)\n assert_rel_error(self, J['con1', 'z'][0][1], -0.78449158, 1.0e-6)\n assert_rel_error(self, J['con1', 'x'][0][0], -0.98061448, 1.0e-6)\n\n @parameterized.expand(itertools.product([om.DefaultVector, PETScVector]),\n name_func=lambda f, n, p:\n 'test_newton_with_direct_solver_dense_'+'_'.join(title(a) for a in p.args))\n def test_newton_with_direct_solver_dense(self, vec_class):\n # Basic sellar test.\n\n if not vec_class:\n raise unittest.SkipTest(\"PETSc is not installed\")\n\n prob = om.Problem()\n model = prob.model\n sub = model.add_subsystem('sub', om.Group(), promotes=['*'])\n\n model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x'])\n model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z'])\n\n sub.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2'])\n sub.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2'])\n\n model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)',\n z=np.array([0.0, 0.0]), x=0.0),\n promotes=['obj', 'x', 'z', 'y1', 'y2'])\n\n model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1'])\n model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2'])\n\n sub.nonlinear_solver = om.NewtonSolver()\n sub.linear_solver = om.DirectSolver()\n sub.options['assembled_jac_type'] = 'dense'\n\n sub.nonlinear_solver.options['atol'] = 1e-10\n sub.nonlinear_solver.options['rtol'] = 1e-10\n\n model.approx_totals(method='cs')\n\n prob.setup(check=False, local_vector_class=vec_class)\n prob.set_solver_print(level=0)\n prob.run_model()\n\n assert_rel_error(self, prob['y1'], 25.58830273, .00001)\n assert_rel_error(self, prob['y2'], 12.05848819, .00001)\n\n wrt = ['z', 'x']\n of = ['obj', 'con1', 'con2']\n\n J = prob.compute_totals(of=of, wrt=wrt, return_format='flat_dict')\n assert_rel_error(self, J['obj', 'z'][0][0], 9.61001056, 1.0e-6)\n assert_rel_error(self, J['obj', 'z'][0][1], 1.78448534, 1.0e-6)\n assert_rel_error(self, J['obj', 'x'][0][0], 2.98061391, 1.0e-6)\n assert_rel_error(self, J['con1', 'z'][0][0], -9.61002186, 1.0e-6)\n assert_rel_error(self, J['con1', 'z'][0][1], -0.78449158, 1.0e-6)\n assert_rel_error(self, J['con1', 'x'][0][0], -0.98061448, 1.0e-6)\n\n @parameterized.expand(itertools.product([om.DefaultVector, PETScVector]),\n name_func=lambda f, n, p:\n 'test_newton_with_direct_solver_csc_'+'_'.join(title(a) for a in p.args))\n def test_newton_with_direct_solver_csc(self, vec_class):\n # Basic sellar test.\n\n if not vec_class:\n raise unittest.SkipTest(\"PETSc is not installed\")\n\n prob = om.Problem()\n model = prob.model\n sub = model.add_subsystem('sub', om.Group(), promotes=['*'])\n\n model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x'])\n model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z'])\n\n sub.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2'])\n sub.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2'])\n\n model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)',\n z=np.array([0.0, 0.0]), x=0.0),\n promotes=['obj', 'x', 'z', 'y1', 'y2'])\n\n model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1'])\n model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2'])\n\n sub.nonlinear_solver = om.NewtonSolver()\n sub.linear_solver = om.DirectSolver()\n sub.options['assembled_jac_type'] = 'csc'\n\n sub.nonlinear_solver.options['atol'] = 1e-10\n sub.nonlinear_solver.options['rtol'] = 1e-10\n\n model.approx_totals(method='cs')\n\n prob.setup(check=False, local_vector_class=vec_class)\n prob.set_solver_print(level=0)\n prob.run_model()\n\n assert_rel_error(self, prob['y1'], 25.58830273, .00001)\n assert_rel_error(self, prob['y2'], 12.05848819, .00001)\n\n wrt = ['z', 'x']\n of = ['obj', 'con1', 'con2']\n\n J = prob.compute_totals(of=of, wrt=wrt, return_format='flat_dict')\n assert_rel_error(self, J['obj', 'z'][0][0], 9.61001056, 1.0e-6)\n assert_rel_error(self, J['obj', 'z'][0][1], 1.78448534, 1.0e-6)\n assert_rel_error(self, J['obj', 'x'][0][0], 2.98061391, 1.0e-6)\n assert_rel_error(self, J['con1', 'z'][0][0], -9.61002186, 1.0e-6)\n assert_rel_error(self, J['con1', 'z'][0][1], -0.78449158, 1.0e-6)\n assert_rel_error(self, J['con1', 'x'][0][0], -0.98061448, 1.0e-6)\n\n @parameterized.expand(itertools.product([om.DefaultVector, PETScVector]),\n name_func=lambda f, n, p:\n 'test_subbed_newton_gs_'+'_'.join(title(a) for a in p.args))\n def test_subbed_newton_gs(self, vec_class):\n\n if not vec_class:\n raise unittest.SkipTest(\"PETSc is not installed\")\n\n from openmdao.test_suite.components.sellar import SellarDis1withDerivatives, SellarDis2withDerivatives\n class SellarDerivatives(om.Group):\n\n def setup(self):\n self.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x'])\n self.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z'])\n\n self.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2'])\n self.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2'])\n sub = self.add_subsystem('sub', om.Group(), promotes=['*'])\n\n sub.linear_solver = om.DirectSolver(assemble_jac=True)\n sub.options['assembled_jac_type'] = 'csc'\n\n sub.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', obj=0.0,\n x=0.0, z=np.array([0.0, 0.0]), y1=0.0, y2=0.0),\n promotes=['obj', 'x', 'z', 'y1', 'y2'])\n\n sub.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1', con1=0.0, y1=0.0),\n promotes=['con1', 'y1'])\n sub.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0', con2=0.0, y2=0.0),\n promotes=['con2', 'y2'])\n\n self.nonlinear_solver = om.NewtonSolver()\n self.linear_solver = om.LinearBlockGS()\n self.linear_solver.options['maxiter'] = 25\n self.linear_solver.options['atol'] = 1e-16\n\n prob = om.Problem()\n prob.model = SellarDerivatives()\n\n prob.setup()\n\n prob.model.approx_totals(method='cs')\n\n prob.run_model()\n\n wrt = ['z', 'x']\n of = ['obj', 'con1', 'con2']\n\n J = prob.compute_totals(of=of, wrt=wrt, return_format='flat_dict')\n assert_rel_error(self, J['obj', 'z'][0][0], 9.61001056, 1.0e-6)\n assert_rel_error(self, J['obj', 'z'][0][1], 1.78448534, 1.0e-6)\n assert_rel_error(self, J['obj', 'x'][0][0], 2.98061391, 1.0e-6)\n assert_rel_error(self, J['con1', 'z'][0][0], -9.61002186, 1.0e-6)\n assert_rel_error(self, J['con1', 'z'][0][1], -0.78449158, 1.0e-6)\n assert_rel_error(self, J['con1', 'x'][0][0], -0.98061448, 1.0e-6)\n\n @parameterized.expand(itertools.product([om.DefaultVector, PETScVector]),\n name_func=lambda f, n, p:\n 'test_subbed_newton_gs_csc_external_mtx_'+'_'.join(title(a) for a in p.args))\n def test_subbed_newton_gs_csc_external_mtx(self, vec_class):\n\n if not vec_class:\n raise unittest.SkipTest(\"PETSc is not installed\")\n\n from openmdao.test_suite.components.sellar import SellarDis1withDerivatives, SellarDis2withDerivatives\n class SellarDerivatives(om.Group):\n\n def setup(self):\n self.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x'])\n self.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z'])\n\n self.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2'])\n self.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2'])\n sub = self.add_subsystem('sub', om.Group(), promotes=['*'])\n\n sub.linear_solver = om.DirectSolver(assemble_jac=True)\n sub.options['assembled_jac_type'] = 'csc'\n\n sub.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', obj=0.0,\n x=0.0, z=np.array([0.0, 0.0]), y1=0.0, y2=0.0),\n promotes=['obj', 'x', 'z', 'y1', 'y2'])\n\n sub.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1', con1=0.0, y1=0.0),\n promotes=['con1', 'y1'])\n sub.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0', con2=0.0, y2=0.0),\n promotes=['con2', 'y2'])\n\n self.nonlinear_solver = om.NewtonSolver()\n self.linear_solver = om.LinearBlockGS()\n self.linear_solver.options['maxiter'] = 25\n self.linear_solver.options['atol'] = 1e-16\n\n prob = om.Problem()\n prob.model = SellarDerivatives()\n\n prob.setup()\n\n prob.model.approx_totals(method='cs')\n\n prob.run_model()\n\n wrt = ['z', 'x']\n of = ['obj', 'con1', 'con2']\n\n J = prob.compute_totals(of=of, wrt=wrt, return_format='flat_dict')\n assert_rel_error(self, J['obj', 'z'][0][0], 9.61001056, 1.0e-6)\n assert_rel_error(self, J['obj', 'z'][0][1], 1.78448534, 1.0e-6)\n assert_rel_error(self, J['obj', 'x'][0][0], 2.98061391, 1.0e-6)\n assert_rel_error(self, J['con1', 'z'][0][0], -9.61002186, 1.0e-6)\n assert_rel_error(self, J['con1', 'z'][0][1], -0.78449158, 1.0e-6)\n assert_rel_error(self, J['con1', 'x'][0][0], -0.98061448, 1.0e-6)\n\n @parameterized.expand(itertools.product([om.DefaultVector, PETScVector]),\n name_func=lambda f, n, p:\n 'test_subbed_newton_gs_dense_external_mtx_'+'_'.join(title(a) for a in p.args))\n def test_subbed_newton_gs_dense_external_mtx(self, vec_class):\n\n if not vec_class:\n raise unittest.SkipTest(\"PETSc is not installed\")\n\n from openmdao.test_suite.components.sellar import SellarDis1withDerivatives, SellarDis2withDerivatives\n class SellarDerivatives(om.Group):\n\n def setup(self):\n self.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x'])\n self.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z'])\n\n self.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2'])\n self.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2'])\n sub = self.add_subsystem('sub', om.Group(), promotes=['*'])\n\n sub.linear_solver = om.DirectSolver(assemble_jac=True)\n sub.options['assembled_jac_type'] = 'dense'\n\n sub.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', obj=0.0,\n x=0.0, z=np.array([0.0, 0.0]), y1=0.0, y2=0.0),\n promotes=['obj', 'x', 'z', 'y1', 'y2'])\n\n sub.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1', con1=0.0, y1=0.0),\n promotes=['con1', 'y1'])\n sub.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0', con2=0.0, y2=0.0),\n promotes=['con2', 'y2'])\n\n self.nonlinear_solver = om.NewtonSolver()\n self.linear_solver = om.LinearBlockGS()\n self.linear_solver.options['maxiter'] = 25\n self.linear_solver.options['atol'] = 1e-16\n\n prob = om.Problem()\n prob.model = SellarDerivatives()\n\n prob.setup()\n\n prob.model.approx_totals(method='cs')\n\n prob.run_model()\n\n wrt = ['z', 'x']\n of = ['obj', 'con1', 'con2']\n\n J = prob.compute_totals(of=of, wrt=wrt, return_format='flat_dict')\n assert_rel_error(self, J['obj', 'z'][0][0], 9.61001056, 1.0e-6)\n assert_rel_error(self, J['obj', 'z'][0][1], 1.78448534, 1.0e-6)\n assert_rel_error(self, J['obj', 'x'][0][0], 2.98061391, 1.0e-6)\n assert_rel_error(self, J['con1', 'z'][0][0], -9.61002186, 1.0e-6)\n assert_rel_error(self, J['con1', 'z'][0][1], -0.78449158, 1.0e-6)\n assert_rel_error(self, J['con1', 'x'][0][0], -0.98061448, 1.0e-6)\n\n @parameterized.expand(itertools.product([om.DefaultVector, PETScVector]),\n name_func=lambda f, n, p:\n 'test_newton_with_krylov_solver_'+'_'.join(title(a) for a in p.args))\n def test_newton_with_krylov_solver(self, vec_class):\n # Basic sellar test.\n\n if not vec_class:\n raise unittest.SkipTest(\"PETSc is not installed\")\n\n prob = om.Problem()\n model = prob.model\n sub = model.add_subsystem('sub', om.Group(), promotes=['*'])\n\n model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x'])\n model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z'])\n\n sub.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2'])\n sub.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2'])\n\n model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)',\n z=np.array([0.0, 0.0]), x=0.0),\n promotes=['obj', 'x', 'z', 'y1', 'y2'])\n\n model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1'])\n model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2'])\n\n sub.nonlinear_solver = om.NewtonSolver()\n sub.linear_solver = om.ScipyKrylov()\n sub.nonlinear_solver.options['atol'] = 1e-10\n sub.nonlinear_solver.options['rtol'] = 1e-10\n sub.linear_solver.options['atol'] = 1e-15\n\n model.approx_totals(method='cs', step=1e-14)\n\n prob.setup(check=False, local_vector_class=vec_class)\n prob.set_solver_print(level=0)\n prob.run_model()\n\n assert_rel_error(self, prob['y1'], 25.58830273, .00001)\n assert_rel_error(self, prob['y2'], 12.05848819, .00001)\n\n wrt = ['z', 'x']\n of = ['obj', 'con1', 'con2']\n\n J = prob.compute_totals(of=of, wrt=wrt, return_format='flat_dict')\n assert_rel_error(self, J['obj', 'z'][0][0], 9.61001056, 1.0e-6)\n assert_rel_error(self, J['obj', 'z'][0][1], 1.78448534, 1.0e-6)\n assert_rel_error(self, J['obj', 'x'][0][0], 2.98061391, 1.0e-6)\n assert_rel_error(self, J['con1', 'z'][0][0], -9.61002186, 1.0e-6)\n assert_rel_error(self, J['con1', 'z'][0][1], -0.78449158, 1.0e-6)\n assert_rel_error(self, J['con1', 'x'][0][0], -0.98061448, 1.0e-6)\n\n def test_newton_with_cscjac_under_cs(self):\n # Basic sellar test.\n\n prob = om.Problem()\n model = prob.model\n sub = model.add_subsystem('sub', om.Group(), promotes=['*'])\n\n model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x'])\n model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z'])\n\n sub.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2'])\n sub.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2'])\n\n model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)',\n z=np.array([0.0, 0.0]), x=0.0),\n promotes=['obj', 'x', 'z', 'y1', 'y2'])\n\n model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1'])\n model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2'])\n\n sub.nonlinear_solver = om.NewtonSolver()\n sub.linear_solver = om.ScipyKrylov(assemble_jac=True)\n sub.nonlinear_solver.options['atol'] = 1e-20\n sub.nonlinear_solver.options['rtol'] = 1e-20\n\n model.approx_totals(method='cs', step=1e-12)\n\n prob.setup()\n prob.set_solver_print(level=0)\n prob.run_model()\n\n assert_rel_error(self, prob['y1'], 25.58830273, .00001)\n assert_rel_error(self, prob['y2'], 12.05848819, .00001)\n\n wrt = ['z', 'x']\n of = ['obj', 'con1']\n\n J = prob.compute_totals(of=of, wrt=wrt, return_format='flat_dict')\n assert_rel_error(self, J['obj', 'z'][0][0], 9.61001056, .00001)\n assert_rel_error(self, J['obj', 'z'][0][1], 1.78448534, .00001)\n assert_rel_error(self, J['obj', 'x'][0][0], 2.98061391, 1.0e-6)\n assert_rel_error(self, J['con1', 'z'][0][0], -9.61002186, 1.0e-6)\n assert_rel_error(self, J['con1', 'z'][0][1], -0.78449158, 1.0e-6)\n assert_rel_error(self, J['con1', 'x'][0][0], -0.98061448, 1.0e-6)\n\n def test_newton_with_fd_group(self):\n # Basic sellar test.\n\n prob = om.Problem()\n model = prob.model\n sub = model.add_subsystem('sub', om.Group(), promotes=['*'])\n subfd = sub.add_subsystem('subfd', om.Group(), promotes=['*'])\n\n model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x'])\n model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z'])\n\n subfd.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2'])\n subfd.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2'])\n\n model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)',\n z=np.array([0.0, 0.0]), x=0.0),\n promotes=['obj', 'x', 'z', 'y1', 'y2'])\n\n model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1'])\n model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2'])\n\n # Finite difference for the Newton linear solve only\n subfd.approx_totals(method='fd')\n\n sub.nonlinear_solver = om.NewtonSolver()\n sub.nonlinear_solver.options['maxiter'] = 12\n sub.linear_solver = om.DirectSolver(assemble_jac=False)\n sub.nonlinear_solver.options['atol'] = 1e-20\n sub.nonlinear_solver.options['rtol'] = 1e-20\n\n # Complex Step for top derivatives\n model.approx_totals(method='cs', step=1e-14)\n\n prob.setup()\n prob.set_solver_print(level=0)\n prob.run_model()\n\n assert_rel_error(self, prob['y1'], 25.58830273, .00001)\n assert_rel_error(self, prob['y2'], 12.05848819, .00001)\n\n wrt = ['z', 'x']\n of = ['obj', 'con1', 'con2']\n\n J = prob.compute_totals(of=of, wrt=wrt, return_format='flat_dict')\n assert_rel_error(self, J['obj', 'z'][0][0], 9.61001056, 1.0e-6)\n assert_rel_error(self, J['obj', 'z'][0][1], 1.78448534, 1.0e-6)\n assert_rel_error(self, J['obj', 'x'][0][0], 2.98061391, 1.0e-6)\n assert_rel_error(self, J['con1', 'z'][0][0], -9.61002186, 1.0e-6)\n assert_rel_error(self, J['con1', 'z'][0][1], -0.78449158, 1.0e-6)\n assert_rel_error(self, J['con1', 'x'][0][0], -0.98061448, 1.0e-6)\n\n def test_nested_complex_step_unsupported(self):\n # Basic sellar test.\n\n prob = self.prob = om.Problem()\n model = prob.model\n\n model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x'])\n model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z'])\n\n model.add_subsystem('d1', SellarDis1CS(), promotes=['x', 'z', 'y1', 'y2'])\n model.add_subsystem('d2', SellarDis2CS(), promotes=['z', 'y1', 'y2'])\n\n model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)',\n z=np.array([0.0, 0.0]), x=0.0),\n promotes=['obj', 'x', 'z', 'y1', 'y2'])\n\n model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1'])\n model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2'])\n\n prob.model.nonlinear_solver = om.NewtonSolver()\n prob.model.linear_solver = om.DirectSolver(assemble_jac=False)\n\n prob.model.approx_totals(method='cs')\n prob.setup()\n prob.set_solver_print(level=0)\n prob.run_model()\n\n assert_rel_error(self, prob['y1'], 25.58830273, .00001)\n assert_rel_error(self, prob['y2'], 12.05848819, .00001)\n\n wrt = ['z']\n of = ['obj']\n\n J = prob.compute_totals(of=of, wrt=wrt, return_format='flat_dict')\n\n assert_rel_error(self, J['obj', 'z'][0][0], 9.61001056, .00001)\n assert_rel_error(self, J['obj', 'z'][0][1], 1.78448534, .00001)\n\n outs = prob.model.list_outputs(residuals=True, out_stream=None)\n for j in range(len(outs)):\n val = np.linalg.norm(outs[j][1]['resids'])\n self.assertLess(val, 1e-8, msg=\"Check if CS cleans up after itself.\")\n\n\nclass TestComponentComplexStep(unittest.TestCase):\n\n def test_implicit_component(self):\n\n class TestImplCompArrayDense(TestImplCompArray):\n\n def setup(self):\n super(TestImplCompArrayDense, self).setup()\n self.declare_partials('*', '*', method='cs')\n\n prob = self.prob = om.Problem()\n model = prob.model\n\n model.add_subsystem('p_rhs', om.IndepVarComp('rhs', val=np.ones(2)))\n sub = model.add_subsystem('sub', om.Group())\n comp = sub.add_subsystem('comp', TestImplCompArrayDense())\n model.connect('p_rhs.rhs', 'sub.comp.rhs')\n\n model.linear_solver = om.ScipyKrylov()\n\n prob.setup()\n prob.run_model()\n model.run_linearize()\n\n Jfd = comp._jacobian\n assert_rel_error(self, Jfd['sub.comp.x', 'sub.comp.rhs'], -np.eye(2), 1e-6)\n assert_rel_error(self, Jfd['sub.comp.x', 'sub.comp.x'], comp.mtx, 1e-6)\n\n def test_reconfigure(self):\n # In this test, we switch to 'cs' when we reconfigure.\n\n class TestImplCompArrayDense(TestImplCompArray):\n\n def initialize(self):\n self.mtx = np.array([\n [0.99, 0.01],\n [0.01, 0.99],\n ])\n self.count = 0\n\n def setup(self):\n super(TestImplCompArrayDense, self).setup()\n if self.count > 0:\n self.declare_partials('*', '*', method='cs')\n else:\n self.declare_partials('*', '*', method='fd')\n self.count += 1\n\n prob = self.prob = om.Problem()\n model = prob.model\n\n model.add_subsystem('p_rhs', om.IndepVarComp('rhs', val=np.ones(2)))\n sub = model.add_subsystem('sub', om.Group())\n comp = sub.add_subsystem('comp', TestImplCompArrayDense())\n model.connect('p_rhs.rhs', 'sub.comp.rhs')\n\n model.linear_solver = om.ScipyKrylov()\n\n prob.setup()\n prob.run_model()\n\n with self.assertRaises(RuntimeError) as context:\n model.resetup(setup_mode='reconf')\n\n msg = \"In order to activate complex step during reconfiguration, \" \\\n \"you need to set 'force_alloc_complex' to True during setup. \" \\\n \"e.g. 'problem.setup(force_alloc_complex=True)'\"\n self.assertEqual(str(context.exception), msg)\n\n # This time, allocate complex in setup.\n prob.setup(check=False, force_alloc_complex=True)\n prob.run_model()\n model.resetup(setup_mode='reconf')\n prob.run_model()\n\n model.run_linearize()\n Jfd = comp._jacobian\n assert_rel_error(self, Jfd['sub.comp.x', 'sub.comp.rhs'], -np.eye(2), 1e-6)\n assert_rel_error(self, Jfd['sub.comp.x', 'sub.comp.x'], comp.mtx, 1e-6)\n\n def test_vector_methods(self):\n\n class KenComp(om.ExplicitComponent):\n\n def setup(self):\n\n self.add_input('x1', np.array([[7.0, 3.0], [2.4, 3.33]]))\n self.add_output('y1', np.zeros((2, 2)))\n\n self.declare_partials('*', '*', method='cs')\n\n def compute(self, inputs, outputs):\n\n x1 = inputs['x1']\n\n outputs['y1'] = x1\n\n outputs['y1'][0][0] += 14.0\n outputs['y1'][0][1] *= 3.0\n outputs['y1'][1][0] -= 6.67\n outputs['y1'][1][1] /= 2.34\n\n outputs['y1'] *= 1.0\n\n prob = self.prob = om.Problem()\n model = prob.model\n\n model.add_subsystem('px', om.IndepVarComp('x', val=np.array([[7.0, 3.0], [2.4, 3.33]])))\n model.add_subsystem('comp', KenComp())\n model.connect('px.x', 'comp.x1')\n\n prob.setup()\n prob.run_model()\n\n of = ['comp.y1']\n wrt = ['px.x']\n derivs = prob.compute_totals(of=of, wrt=wrt)\n\n assert_rel_error(self, derivs['comp.y1', 'px.x'][0][0], 1.0, 1e-6)\n assert_rel_error(self, derivs['comp.y1', 'px.x'][1][1], 3.0, 1e-6)\n assert_rel_error(self, derivs['comp.y1', 'px.x'][2][2], 1.0, 1e-6)\n assert_rel_error(self, derivs['comp.y1', 'px.x'][3][3], 1.0/2.34, 1e-6)\n\n def test_sellar_comp_cs(self):\n # Basic sellar test.\n\n prob = self.prob = om.Problem()\n model = prob.model\n\n model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x'])\n model.add_subsystem('pz', om.IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z'])\n\n model.add_subsystem('d1', SellarDis1CS(), promotes=['x', 'z', 'y1', 'y2'])\n model.add_subsystem('d2', SellarDis2CS(), promotes=['z', 'y1', 'y2'])\n\n model.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)',\n z=np.array([0.0, 0.0]), x=0.0),\n promotes=['obj', 'x', 'z', 'y1', 'y2'])\n\n model.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1'])\n model.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2'])\n\n prob.model.nonlinear_solver = om.NonlinearBlockGS()\n prob.model.linear_solver = om.DirectSolver(assemble_jac=False)\n\n prob.setup()\n prob.set_solver_print(level=0)\n prob.run_model()\n\n assert_rel_error(self, prob['y1'], 25.58830273, .00001)\n assert_rel_error(self, prob['y2'], 12.05848819, .00001)\n\n wrt = ['z']\n of = ['obj']\n\n J = prob.compute_totals(of=of, wrt=wrt, return_format='flat_dict')\n assert_rel_error(self, J['obj', 'z'][0][0], 9.61001056, .00001)\n assert_rel_error(self, J['obj', 'z'][0][1], 1.78448534, .00001)\n\n outs = prob.model.list_outputs(residuals=True, out_stream=None)\n for j in range(len(outs)):\n val = np.linalg.norm(outs[j][1]['resids'])\n self.assertLess(val, 1e-8, msg=\"Check if CS cleans up after itself.\")\n\n def test_stepsizes_under_complex_step(self):\n import openmdao.api as om\n\n class SimpleComp(om.ExplicitComponent):\n\n def setup(self):\n self.add_input('x', val=1.0)\n self.add_output('y', val=1.0)\n\n self.declare_partials(of='y', wrt='x', method='cs')\n self.count = 0\n\n def compute(self, inputs, outputs):\n outputs['y'] = 3.0*inputs['x']\n\n if self.under_complex_step:\n\n # Local cs\n if self.count == 0 and inputs['x'].imag != 1.0e-40:\n msg = \"Wrong stepsize for local CS\"\n raise RuntimeError(msg)\n\n # Global cs with default setting.\n if self.count == 1 and inputs['x'].imag != 1.0e-40:\n msg = \"Wrong stepsize for default global CS\"\n raise RuntimeError(msg)\n\n # Global cs with user setting.\n if self.count == 3 and inputs['x'].imag != 1.0e-12:\n msg = \"Wrong stepsize for user global CS\"\n raise RuntimeError(msg)\n\n # Check partials cs with default setting forward.\n if self.count == 4 and inputs['x'].imag != 1.0e-40:\n msg = \"Wrong stepsize for check partial default CS forward\"\n raise RuntimeError(msg)\n\n # Check partials cs with default setting.\n if self.count == 5 and inputs['x'].imag != 1.0e-40:\n msg = \"Wrong stepsize for check partial default CS\"\n raise RuntimeError(msg)\n\n # Check partials cs with user setting forward.\n if self.count == 6 and inputs['x'].imag != 1.0e-40:\n msg = \"Wrong stepsize for check partial user CS forward\"\n raise RuntimeError(msg)\n\n # Check partials cs with user setting.\n if self.count == 7 and inputs['x'].imag != 1.0e-14:\n msg = \"Wrong stepsize for check partial user CS\"\n raise RuntimeError(msg)\n\n self.count += 1\n\n def compute_partials(self, inputs, partials):\n partials['y', 'x'] = 3.\n\n prob = om.Problem()\n prob.model.add_subsystem('px', om.IndepVarComp('x', val=1.0))\n prob.model.add_subsystem('comp', SimpleComp())\n prob.model.connect('px.x', 'comp.x')\n\n prob.model.add_design_var('px.x', lower=-100, upper=100)\n prob.model.add_objective('comp.y')\n\n prob.setup(force_alloc_complex=True)\n\n prob.run_model()\n\n prob.check_totals(method='cs', out_stream=None)\n\n prob.check_totals(method='cs', step=1e-12, out_stream=None)\n\n prob.check_partials(method='cs', out_stream=None)\n\n prob.check_partials(method='cs', step=1e-14, out_stream=None)\n\n def test_feature_under_complex_step(self):\n import openmdao.api as om\n\n class SimpleComp(om.ExplicitComponent):\n\n def setup(self):\n self.add_input('x', val=1.0)\n self.add_output('y', val=1.0)\n\n self.declare_partials(of='y', wrt='x', method='cs')\n\n def compute(self, inputs, outputs):\n outputs['y'] = 3.0*inputs['x']\n\n if self.under_complex_step:\n print(\"Under complex step\")\n print(\"x\", inputs['x'])\n print(\"y\", outputs['y'])\n\n prob = om.Problem()\n prob.model.add_subsystem('px', om.IndepVarComp('x', val=1.0))\n prob.model.add_subsystem('comp', SimpleComp())\n prob.model.connect('px.x', 'comp.x')\n\n prob.model.add_design_var('px.x', lower=-100, upper=100)\n prob.model.add_objective('comp.y')\n\n prob.setup(force_alloc_complex=True)\n\n prob.run_model()\n\n prob.compute_totals(of=['comp.y'], wrt=['px.x'])\n\n\nclass ApproxTotalsFeature(unittest.TestCase):\n\n def test_basic(self):\n import numpy as np\n\n import openmdao.api as om\n\n class CompOne(om.ExplicitComponent):\n\n def setup(self):\n self.add_input('x', val=0.0)\n self.add_output('y', val=np.zeros(25))\n self._exec_count = 0\n\n def compute(self, inputs, outputs):\n x = inputs['x']\n outputs['y'] = np.arange(25) * x\n self._exec_count += 1\n\n class CompTwo(om.ExplicitComponent):\n\n def setup(self):\n self.add_input('y', val=np.zeros(25))\n self.add_output('z', val=0.0)\n self._exec_count = 0\n\n def compute(self, inputs, outputs):\n y = inputs['y']\n outputs['z'] = np.sum(y)\n self._exec_count += 1\n\n prob = om.Problem()\n model = prob.model\n model.add_subsystem('p1', om.IndepVarComp('x', 0.0), promotes=['x'])\n model.add_subsystem('comp1', CompOne(), promotes=['x', 'y'])\n comp2 = model.add_subsystem('comp2', CompTwo(), promotes=['y', 'z'])\n\n model.linear_solver = om.ScipyKrylov()\n model.approx_totals()\n\n prob.setup()\n prob.run_model()\n\n of = ['z']\n wrt = ['x']\n derivs = prob.compute_totals(of=of, wrt=wrt)\n\n assert_rel_error(self, derivs['z', 'x'], [[300.0]], 1e-6)\n self.assertEqual(comp2._exec_count, 2)\n\n def test_basic_cs(self):\n import numpy as np\n\n import openmdao.api as om\n\n class CompOne(om.ExplicitComponent):\n\n def setup(self):\n self.add_input('x', val=0.0)\n self.add_output('y', val=np.zeros(25))\n self._exec_count = 0\n\n def compute(self, inputs, outputs):\n x = inputs['x']\n outputs['y'] = np.arange(25) * x\n self._exec_count += 1\n\n class CompTwo(om.ExplicitComponent):\n\n def setup(self):\n self.add_input('y', val=np.zeros(25))\n self.add_output('z', val=0.0)\n self._exec_count = 0\n\n def compute(self, inputs, outputs):\n y = inputs['y']\n outputs['z'] = np.sum(y)\n self._exec_count += 1\n\n prob = om.Problem()\n model = prob.model\n model.add_subsystem('p1', om.IndepVarComp('x', 0.0), promotes=['x'])\n model.add_subsystem('comp1', CompOne(), promotes=['x', 'y'])\n model.add_subsystem('comp2', CompTwo(), promotes=['y', 'z'])\n\n model.linear_solver = om.ScipyKrylov()\n model.approx_totals(method='cs')\n\n prob.setup()\n prob.run_model()\n\n of = ['z']\n wrt = ['x']\n derivs = prob.compute_totals(of=of, wrt=wrt)\n\n assert_rel_error(self, derivs['z', 'x'], [[300.0]], 1e-6)\n\n def test_arguments(self):\n import numpy as np\n\n import openmdao.api as om\n\n class CompOne(om.ExplicitComponent):\n\n def setup(self):\n self.add_input('x', val=0.0)\n self.add_output('y', val=np.zeros(25))\n self._exec_count = 0\n\n def compute(self, inputs, outputs):\n x = inputs['x']\n outputs['y'] = np.arange(25) * x\n self._exec_count += 1\n\n class CompTwo(om.ExplicitComponent):\n\n def setup(self):\n self.add_input('y', val=np.zeros(25))\n self.add_output('z', val=0.0)\n self._exec_count = 0\n\n def compute(self, inputs, outputs):\n y = inputs['y']\n outputs['z'] = np.sum(y)\n self._exec_count += 1\n\n prob = om.Problem()\n model = prob.model\n model.add_subsystem('p1', om.IndepVarComp('x', 1.0), promotes=['x'])\n model.add_subsystem('comp1', CompOne(), promotes=['x', 'y'])\n model.add_subsystem('comp2', CompTwo(), promotes=['y', 'z'])\n\n model.linear_solver = om.ScipyKrylov()\n model.approx_totals(method='fd', step=1e-7, form='central', step_calc='rel')\n\n prob.setup()\n prob.run_model()\n\n of = ['z']\n wrt = ['x']\n derivs = prob.compute_totals(of=of, wrt=wrt)\n\n assert_rel_error(self, derivs['z', 'x'], [[300.0]], 1e-6)\n\n def test_sellarCS(self):\n # Just tests Newton on Sellar with FD derivs.\n import openmdao.api as om\n from openmdao.test_suite.components.sellar_feature import SellarNoDerivativesCS\n\n prob = om.Problem()\n prob.model = SellarNoDerivativesCS()\n\n prob.setup()\n prob.run_model()\n\n assert_rel_error(self, prob['y1'], 25.58830273, .00001)\n assert_rel_error(self, prob['y2'], 12.05848819, .00001)\n\n # Make sure we aren't iterating like crazy\n self.assertLess(prob.model.nonlinear_solver._iter_count, 8)\n\n\nclass ParallelFDParametricTestCase(unittest.TestCase):\n\n @parametric_suite(\n assembled_jac=[False],\n jacobian_type=['dense'],\n partial_type=['array'],\n partial_method=['fd', 'cs'],\n num_var=[3],\n var_shape=[(2, 3), (2,)],\n connection_type=['explicit'],\n run_by_default=True,\n )\n def test_subset(self, param_instance):\n param_instance.linear_solver_class = om.DirectSolver\n param_instance.linear_solver_options = {} # defaults not valid for DirectSolver\n\n param_instance.setup()\n problem = param_instance.problem\n model = problem.model\n\n expected_values = model.expected_values\n if expected_values:\n actual = {key: problem[key] for key in iterkeys(expected_values)}\n assert_rel_error(self, actual, expected_values, 1e-4)\n\n expected_totals = model.expected_totals\n if expected_totals:\n # Forward Derivatives Check\n totals = param_instance.compute_totals('fwd')\n assert_rel_error(self, totals, expected_totals, 1e-4)\n\n # Reverse Derivatives Check\n totals = param_instance.compute_totals('rev')\n assert_rel_error(self, totals, expected_totals, 1e-4)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n"
] | [
[
"numpy.ma.array",
"numpy.ma.filled",
"numpy.zeros",
"numpy.ma.dot"
],
[
"numpy.random.random",
"numpy.linspace",
"numpy.arange",
"numpy.eye",
"numpy.ones",
"numpy.testing.assert_almost_equal",
"numpy.array",
"numpy.zeros"
],
[
"numpy.linspace",
"numpy.arange",
"numpy.eye",
"numpy.linalg.norm",
"numpy.ones",
"numpy.array",
"numpy.zeros",
"numpy.sum"
]
] | [
{
"matplotlib": [],
"numpy": [
"1.10",
"1.12",
"1.11",
"1.19",
"1.13",
"1.16",
"1.9",
"1.18",
"1.20",
"1.7",
"1.15",
"1.14",
"1.17",
"1.8"
],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
WERimagin/baseline_CoQA | [
"d11d19283b4c9b9b15cfcdb96bf5cd262bb953e8"
] | [
"rc/models/drqa.py"
] | [
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom .layers import SeqAttnMatch, StackedBRNN, LinearSeqAttn, BilinearSeqAttn\nfrom .layers import weighted_avg, uniform_weights, dropout\n\n\nclass DrQA(nn.Module):\n \"\"\"Network for the Document Reader module of DrQA.\"\"\"\n _RNN_TYPES = {'lstm': nn.LSTM, 'gru': nn.GRU, 'rnn': nn.RNN}\n\n def __init__(self, config, w_embedding):\n \"\"\"Configuration, word embeddings\"\"\"\n super(DrQA, self).__init__()\n # Store config\n self.config = config\n self.w_embedding = w_embedding\n input_w_dim = self.w_embedding.embedding_dim\n q_input_size = input_w_dim\n if self.config['fix_embeddings']:\n for p in self.w_embedding.parameters():\n p.requires_grad = False\n\n # Projection for attention weighted question\n if self.config['use_qemb']:\n self.qemb_match = SeqAttnMatch(input_w_dim)\n\n # Input size to RNN: word emb + question emb + manual features\n doc_input_size = input_w_dim + self.config['num_features']\n if self.config['use_qemb']:\n doc_input_size += input_w_dim\n\n # Project document and question to the same size as their encoders\n if self.config['resize_rnn_input']:\n self.doc_linear = nn.Linear(doc_input_size, config['hidden_size'], bias=True)\n self.q_linear = nn.Linear(input_w_dim, config['hidden_size'], bias=True)\n doc_input_size = q_input_size = config['hidden_size']\n\n # RNN document encoder\n self.doc_rnn = StackedBRNN(\n input_size=doc_input_size,\n hidden_size=config['hidden_size'],\n num_layers=config['num_layers'],\n dropout_rate=config['dropout_rnn'],\n dropout_output=config['dropout_rnn_output'],\n variational_dropout=config['variational_dropout'],\n concat_layers=config['concat_rnn_layers'],\n rnn_type=self._RNN_TYPES[config['rnn_type']],\n padding=config['rnn_padding'],\n bidirectional=True,\n )\n\n # RNN question encoder\n self.question_rnn = StackedBRNN(\n input_size=q_input_size,\n hidden_size=config['hidden_size'],\n num_layers=config['num_layers'],\n dropout_rate=config['dropout_rnn'],\n dropout_output=config['dropout_rnn_output'],\n variational_dropout=config['variational_dropout'],\n concat_layers=config['concat_rnn_layers'],\n rnn_type=self._RNN_TYPES[config['rnn_type']],\n padding=config['rnn_padding'],\n bidirectional=True,\n )\n\n # Output sizes of rnn encoders\n doc_hidden_size = 2 * config['hidden_size']\n question_hidden_size = 2 * config['hidden_size']\n if config['concat_rnn_layers']:\n doc_hidden_size *= config['num_layers']\n question_hidden_size *= config['num_layers']\n\n if config['doc_self_attn']:\n self.doc_self_attn = SeqAttnMatch(doc_hidden_size)\n doc_hidden_size = doc_hidden_size + question_hidden_size\n\n # Question merging\n if config['question_merge'] not in ['avg', 'self_attn']:\n raise NotImplementedError('question_merge = %s' % config['question_merge'])\n if config['question_merge'] == 'self_attn':\n self.self_attn = LinearSeqAttn(question_hidden_size)\n\n # Bilinear attention for span start/end\n self.start_attn = BilinearSeqAttn(\n doc_hidden_size,\n question_hidden_size,\n )\n q_rep_size = question_hidden_size + doc_hidden_size if config['span_dependency'] else question_hidden_size\n self.end_attn = BilinearSeqAttn(\n doc_hidden_size,\n q_rep_size,\n )\n\n def forward(self, ex):\n \"\"\"Inputs:\n xq = question word indices (batch, max_q_len)\n xq_mask = question padding mask (batch, max_q_len)\n xd = document word indices (batch, max_d_len)\n xd_f = document word features indices (batch, max_d_len, nfeat)\n xd_mask = document padding mask (batch, max_d_len)\n targets = span targets (batch,)\n \"\"\"\n # Embed both document and question\n xq_emb = self.w_embedding(ex['xq']) # (batch, max_q_len, word_embed)\n xd_emb = self.w_embedding(ex['xd']) # (batch, max_d_len, word_embed)\n\n shared_axes = [2] if self.config['word_dropout'] else []\n xq_emb = dropout(xq_emb, self.config['dropout_emb'], shared_axes=shared_axes, training=self.training)\n xd_emb = dropout(xd_emb, self.config['dropout_emb'], shared_axes=shared_axes, training=self.training)\n xd_mask = ex['xd_mask']\n xq_mask = ex['xq_mask']\n\n\n # Add attention-weighted question representation\n if self.config['use_qemb']:\n xq_weighted_emb = self.qemb_match(xd_emb, xq_emb, xq_mask)\n drnn_input = torch.cat([xd_emb, xq_weighted_emb], 2)\n else:\n drnn_input = xd_emb\n\n if self.config[\"num_features\"] > 0:\n drnn_input = torch.cat([drnn_input, ex['xd_f']], 2)\n\n # Project document and question to the same size as their encoders\n if self.config['resize_rnn_input']:\n drnn_input = F.relu(self.doc_linear(drnn_input))\n xq_emb = F.relu(self.q_linear(xq_emb))\n if self.config['dropout_ff'] > 0:\n drnn_input = F.dropout(drnn_input, training=self.training)\n xq_emb = F.dropout(xq_emb, training=self.training)\n\n # Encode document with RNN\n doc_hiddens = self.doc_rnn(drnn_input, xd_mask) # (batch, max_d_len, hidden_size)\n\n # Document self attention\n if self.config['doc_self_attn']:\n xd_weighted_emb = self.doc_self_attn(doc_hiddens, doc_hiddens, xd_mask)\n doc_hiddens = torch.cat([doc_hiddens, xd_weighted_emb], 2)\n\n # Encode question with RNN + merge hiddens\n question_hiddens = self.question_rnn(xq_emb, xq_mask)\n if self.config['question_merge'] == 'avg':\n q_merge_weights = uniform_weights(question_hiddens, xq_mask)\n elif self.config['question_merge'] == 'self_attn':\n q_merge_weights = self.self_attn(question_hiddens.contiguous(), xq_mask)\n question_hidden = weighted_avg(question_hiddens, q_merge_weights)\n\n # Predict start and end positions\n #始点と終点の予測\n start_scores = self.start_attn(doc_hiddens, question_hidden, xd_mask)\n if self.config['span_dependency']:\n question_hidden = torch.cat([question_hidden, (doc_hiddens * start_scores.exp().unsqueeze(2)).sum(1)], 1)\n end_scores = self.end_attn(doc_hiddens, question_hidden, xd_mask)\n\n return {'score_s': start_scores,\n 'score_e': end_scores,\n 'targets': ex['targets']}\n"
] | [
[
"torch.nn.Linear",
"torch.nn.functional.dropout",
"torch.cat"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
YNYuan/OpenChem | [
"4364af6d92ae183aac0bea35726d7ae0ee518920"
] | [
"openchem/layers/ipd.py"
] | [
"# modified from https://github.com/tkipf/gae/blob/master/gae/layers.py\n\nimport torch\nimport torch.nn as nn\n\nclass InnerProductDecoder(nn.Module):\n \"\"\"Decoder model layer for link prediction.\"\"\"\n def __init__(self, input_dim, act=nn.functional.sigmoid):\n super(InnerProductDecoder, self).__init__()\n self.act = act\n\n def forward(self, inputs):\n x = inputs.transpose(1,2)\n x = torch.mm(inputs, x)\n x = x.view(-1)\n outputs = self.act(x)\n return outputs"
] | [
[
"torch.mm"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
TomLXXVI/pypeflow | [
"49e42621180ec3125afa238d3ca56ae9f3a7662a"
] | [
"source_code/pypeflow/utils/pump_curve.py"
] | [
"\"\"\"\n## Pump curve fitting and drawing\n\n- Establish an equation for the pump curve from measured points on the curve in the pump's data sheet\n- Get the coefficients of the 2nd order polynomial describing the pump curve and determined via curve fitting\n- Draw the pump curve in a diagram\n\n\"\"\"\nfrom typing import List, Tuple, Dict, Optional\nimport numpy as np\nimport quantities as qty\nfrom nummath.interpolation import PolyFit\nfrom nummath.graphing2 import LineGraph\n\n\nclass PumpCurve:\n\n def __init__(self, dest_units: Dict[str, str]):\n \"\"\"\n Create *PumpCurve* object.\n\n **Parameters:**\n\n - `dest_units`: (*Dict[str, str]*)<br>\n The measuring units in which the pump curve will be expressed. Keys:\n\n + 'flow_rate'\n + 'pressure'\n\n \"\"\"\n self._meas_points: List[Tuple[qty.VolumeFlowRate, qty.Pressure]] = []\n self._dest_units: Dict[str, str] = dest_units\n self._coefficients: Optional[np.array] = None\n\n def add_measuring_points(self, points: List[Tuple[float, float]], units: Dict[str, str]):\n \"\"\"\n Add some data points taken from the pump curve in the data sheet. This will execute the curve fitting\n algorithm that approaches the pump curve with a 2nd order polynomial.\n\n **Parameters:**\n\n - `points`: (*List[Tuple[float, float]]*)<br>\n List of tuples. The 1st element of the tuple is flow rate, the 2nd element is pressure.\n - `units`: (*Dict[str, str]*)<br>\n Dictionary that contains the measuring units in which the values of the data points are expressed. Keys:\n\n + 'flow_rate'\n + 'pressure'\n\n \"\"\"\n self._meas_points = [\n (qty.VolumeFlowRate(V, units['flow_rate']), qty.Pressure(p, units['pressure'])) for V, p in points\n ]\n self._curve_fitting()\n\n def _curve_fitting(self):\n pf = PolyFit(\n x_data=[V(self._dest_units['flow_rate']) for V, _ in self._meas_points],\n y_data=[p(self._dest_units['pressure']) for _, p in self._meas_points],\n m=2\n )\n self._coefficients = pf.solve()\n\n def get_coefficients(self, units: Optional[Dict[str, str]] = None) -> Optional[List[float]]:\n \"\"\"\n Get the coefficients of the 2nd order polynomial describing the pump curve.\n\n **Parameters:**\n\n - `units`: (*Optional[[Dict[str, str]]*)<br>\n Optional dictionary that contains the measuring units in which the returned coefficients must be expressed.\n Default is None, which means that the coefficients will be returned expressed in the measuring units passed in\n at the instantiation of the *PumpCurve* object. Keys:\n\n + 'flow_rate'\n + 'pressure'\n\n \"\"\"\n if units is not None:\n p_src = qty.Pressure(1.0, self._dest_units['pressure'])\n V_src = qty.VolumeFlowRate(1.0, self._dest_units['flow_rate'])\n p_des = p_src(units['pressure'])\n V_des = V_src(units['flow_rate'])\n else:\n p_des = 1.0\n V_des = 1.0\n a0 = self._coefficients[0] * p_des\n a1 = self._coefficients[1] * (p_des / V_des)\n a2 = self._coefficients[2] * (p_des / V_des ** 2)\n return [a0, a1, a2]\n\n def set_coefficients(self, coeff: Tuple[float, float, float], units: Dict[str, str]):\n \"\"\"\n Set the known coefficients of the 2nd order polynomial describing the pump curve.\n\n **Parameters:**\n\n - `coeff`: (*Tuple[float, float, float]*)<br>\n Tuple of 3 floats: a0, a1 and a2 as in the equation dp_pump = a0 + a1 * V + a2 * V **2\n - `units`: (*Dict[str, str]*)<br>\n Dictionary that contains the measuring units in which the pump coefficients are expressed. Keys:\n\n + 'flow_rate'\n + 'pressure'\n\n \"\"\"\n p_src = qty.Pressure(1.0, units['pressure'])\n V_src = qty.VolumeFlowRate(1.0, units['flow_rate'])\n p_des = p_src(self._dest_units['pressure'])\n V_des = V_src(self._dest_units['flow_rate'])\n a0 = coeff[0] * p_des\n a1 = coeff[1] * (p_des / V_des)\n a2 = coeff[2] * (p_des / V_des ** 2)\n self._coefficients = np.array([a0, a1, a2])\n\n def create_pump_curve(self, V_initial: qty.VolumeFlowRate, V_final: qty.VolumeFlowRate, num: int = 50):\n \"\"\"\n Calculate the pump curve between an initial and final flow rate.\n\n **Parameters:**\n\n - `V_initial`: (*quantities.VolumeFlowRate*) = initial flow rate\n - `V_final`: (*quantities.VolumeFlowRate*) = final flow rate\n - `num`: (*int*) = number of calculation points (default = 50)\n\n **Returns:** (*Tuple[np.array, np.array]*)\n Tuple with 1st element a numpy array of the flow rates and 2nd element a numpy array of the corresponding\n pressures, both expressed in the desired measuring units set at instantiation of the *PumpCurve*-object.\n\n \"\"\"\n V_i = V_initial(self._dest_units['flow_rate'])\n V_f = V_final(self._dest_units['flow_rate'])\n V = np.linspace(V_i, V_f, num, endpoint=True)\n a0 = self._coefficients[0]; a1 = self._coefficients[1]; a2 = self._coefficients[2]\n p = a0 + a1 * V + a2 * V ** 2\n return V, p\n\n def draw_pump_curve(self, V_initial: qty.VolumeFlowRate, V_final: qty.VolumeFlowRate, **kwargs):\n \"\"\"\n Draw the calculated pump curve.\n\n **Parameters:**\n\n - `V_initial`: (*quantities.VolumeFlowRate*) = initial flow rate\n - `V_final`: (*quantities.VolumeFlowRate*) = final flow rate\n - `kwargs`: optional keyword arguments\n + `fig_size`: (*Tuple[float, float]*) = the width and height of the figure in inches\n + `dpi`: (*int*) = dots per inch of the figure\n + `num`: (*int*) = number of calculated points to draw\n + `V_step`: (*quantities.VolumeFlowRate*) = step between ticks on the flow rate axis of the diagram\n + `V_max`: (*quantities.VolumeFlowRate*) = the maximum flow rate shown on the axis\n + `p_step`: (*quantities.Pressure*) = step between ticks on the pressure axis of the diagram\n + `p_max`: (*quantities.Pressure*) = maximum pressure shown on the axis\n + `working_point`: (*Tuple[qty.VolumeFlowRate, qty.Pressure]*) = working point of the pump (shown as a red\n dot on the diagram)\n\n **Returns:** (*nummath.graphing2.LineGraph*)<br>\n Call show() on the returned *LineGraph* object to show the diagram.\n \"\"\"\n if self._coefficients is not None:\n fig_size: Tuple[int, int] = kwargs.get('fig_size', (6, 4))\n dpi: int = kwargs.get('dpi', 96)\n num: int = kwargs.get('num', 50)\n V_step: qty.VolumeFlowRate = kwargs.get('V_step')\n V_max: qty.VolumeFlowRate = kwargs.get('V_max')\n p_step: qty.Pressure = kwargs.get('p_step')\n p_max: qty.Pressure = kwargs.get('p_max')\n working_point: Tuple[qty.VolumeFlowRate, qty.Pressure] = kwargs.get('working_point')\n V, p = self.create_pump_curve(V_initial, V_final, num)\n graph = LineGraph(fig_size=fig_size, dpi=dpi)\n graph.add_dataset(name=\"pump curve\", x1_data=V, y1_data=p)\n if self._meas_points:\n graph.add_dataset(\n name=\"measured points\",\n x1_data=[V(self._dest_units['flow_rate']) for V, _ in self._meas_points],\n y1_data=[p(self._dest_units['pressure']) for _, p in self._meas_points],\n layout={'marker': 'o', 'linestyle': 'None'}\n )\n if working_point:\n graph.add_dataset(\n name=\"working point\",\n x1_data=working_point[0](self._dest_units['flow_rate']),\n y1_data=working_point[1](self._dest_units['pressure']),\n layout={'marker': 'o', 'linestyle': 'None', 'color': 'red'}\n )\n graph.x1.set_title(f'flow rate [{self._dest_units[\"flow_rate\"]}]')\n if V_max is not None and V_step is not None:\n graph.x1.scale(\n lim_down=0.0,\n lim_up=V_max(self._dest_units['flow_rate']),\n step_size=V_step(self._dest_units['flow_rate'])\n )\n graph.y1.set_title(f'pressure [{self._dest_units[\"pressure\"]}]')\n if p_max is not None and p_step is not None:\n graph.y1.scale(\n lim_down=0.0,\n lim_up=p_max(self._dest_units['pressure']),\n step_size=p_step(self._dest_units['pressure'])\n )\n return graph\n\n def pump_head(self, V: qty.VolumeFlowRate) -> qty.Pressure:\n \"\"\"\n Get the pump head (*quantities.Pressure*) if the flow rate (*quantities.VolumeFlowRate*) is given.\n\n \"\"\"\n a0 = self._coefficients[0]\n a1 = self._coefficients[1]\n a2 = self._coefficients[2]\n V = V(self._dest_units['flow_rate'])\n return qty.Pressure(a0 + a1 * V + a2 * V ** 2, self._dest_units['pressure'])\n\n\nif __name__ == '__main__':\n\n pump_curve = PumpCurve(dest_units={'flow_rate': 'L/s', 'pressure': 'bar'})\n pump_curve.add_measuring_points(\n points=[(0.0, 60.0), (2.4, 52.0), (4.2, 48.0), (6.0, 36.0)],\n units={'flow_rate': 'm^3/h', 'pressure': 'm'}\n )\n\n coeff1 = pump_curve.get_coefficients(units={'pressure': 'Pa', 'flow_rate': 'm^3/s'})\n print(coeff1)\n coeff2 = pump_curve.get_coefficients(units={'pressure': 'bar', 'flow_rate': 'L/s'})\n print(coeff2)\n\n graph_ = pump_curve.draw_pump_curve(\n V_initial=qty.VolumeFlowRate(0.0, 'm^3/h'),\n V_final=qty.VolumeFlowRate(7.2, 'm^3/h'),\n fig_size=(10, 8),\n dpi=150,\n num=100,\n V_max=qty.VolumeFlowRate(3.0, 'L/s'),\n V_step=qty.VolumeFlowRate(0.5, 'L/s'),\n p_max=qty.Pressure(8.0, 'bar'),\n p_step=qty.Pressure(2.0, 'bar')\n )\n graph_.show()\n"
] | [
[
"numpy.array",
"numpy.linspace"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
junaid340/AnomalyDetection-In-SurveillanceVideos | [
"758cb507b8f106eb0d4366c3301ee7be355a40b3"
] | [
"Deploy_Model.py"
] | [
"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Apr 2 20:56:50 2020\r\n@author: junaid\r\n\"\"\"\r\nimport cv2\r\nimport Model_Wrapper as mp\r\nfrom tensorflow.keras.models import load_model\r\nfrom PreProcessing_V5 import Fit_Preprocessing, GlobalNormalization, ToJson\r\nfrom PreProcessing_V5 import ReadFileNames\r\nimport numpy as np\r\nimport tensorflow as tf\r\n\r\n\r\nprint('\\nTensorflow GPU installed: '+str(tf.test.is_built_with_cuda()))\r\nprint('Is Tensorflow using GPU: '+str(tf.test.is_gpu_available()))\r\n\r\n\r\ndef WriteInfo(err, text, norm_count, anom_count):\r\n '''\r\n The function to tag the predicted frames.\r\n\r\n Parameters\r\n ----------\r\n err : \r\n Mean Squared Error of that frame.\r\n text : \r\n What to write on the frame.\r\n norm_count :\r\n Count of normal frames.\r\n anom_count :\r\n Count of anomalous frames.\r\n\r\n Returns\r\n -------\r\n None.\r\n\r\n '''\r\n mp.PrintInline('{4}, Frame Status: {0}, Normal Frame Count: {1}/{2}, Anomaly Frame Count {3}/{2}'.format(text, norm_count, norm_count+anom_count, anom_count, err))\r\n\r\ndef get_model(model_path):\r\n '''\r\n A function to load the saved model.\r\n\r\n Parameters\r\n ----------\r\n model_path : \r\n Location where the trained model is saved.\r\n\r\n Returns\r\n -------\r\n model : \r\n Trained weights of the model.\r\n\r\n '''\r\n print('\\n\\n------- Loading Model: {0} ! -------'.format(model_path.split('/')[-1]))\r\n print('\\n--------------- This may take a while! ---------------\\n\\n')\r\n model=load_model(model_path)\r\n print('\\n\\n------- Model Loaded! {0} ! -------\\n\\n'.format(model_path.split('/')[-1]))\r\n return model\r\n\r\ndef RealTimeDetection(model, threshold, serve_type='real-time', vid_path=None, verbose=True):\r\n '''\r\n A function that will implement the model in real-time i.e you'll pass a video to the model\r\n and while the video is running the model will be predicting it.\r\n\r\n Parameters\r\n ----------\r\n model : \r\n Which model to load or use for implementation.\r\n threshold : \r\n Threshold for distinguishing anomalous frames from normal frames.\r\n serve_type : optional\r\n How do you want to implement the model 'real-time', 'video', 'frames' or 'numpy'.\r\n The default is 'real-time'.\r\n vid_path : optional\r\n Video path for the testing video. The default is None.\r\n verbose : optional\r\n An argument to report more information about the operation in the programe.The default is True.\r\n\r\n Raises\r\n ------\r\n TypeError\r\n If the serving type is set to video, then you must provide the video path.\r\n EOFError\r\n When the video is completed i.e time length is completed it ends by giving this End Of File error.\r\n\r\n Returns\r\n -------\r\n None.\r\n\r\n '''\r\n if serve_type=='real-time':\r\n cap=cv2.VideoCapture(0)\r\n elif serve_type=='video':\r\n if vid_path==None:\r\n raise TypeError('Value of `vid_path` argument cannot be `None`, when `serve_type` value is `video`. Provide valid path of `str` datatype.')\r\n cap=cv2.VideoCapture(vid_path)\r\n \r\n _,frame=cap.read()\r\n shape = np.shape(frame)\r\n ret=True\r\n norm_count = 0\r\n anom_count = 0\r\n test_history = {'Serving Type':serve_type, 'Loss':[], 'Normal Frames': [], \r\n 'Anomaly Frames':[], 'Total Frames':[]}\r\n print('\\n\\n------- Press q to exit the Real Time Detection! -------\\n')\r\n while(cap.isOpened()):\r\n img_lst=[]\r\n v_frames = np.zeros(shape=(10, shape[0], shape[1], shape[2]), dtype=np.uint8)\r\n for i in range(10):\r\n ret,frame=cap.read()\r\n if (ret != True):\r\n cv2.destroyAllWindows()\r\n raise EOFError('The Video is Completed Succefully!')\r\n #copy the orignal frame for display.\r\n v_frames[i]=frame\r\n gray = mp.ImgProcess(frame, shape=(227,227))\r\n img_lst.append(gray)\r\n img_arr = mp.Img_LstArr(img_lst, re_shape=(227, 227, 10))\r\n #making prediction\r\n pred = model.predict(img_arr)\r\n #computing error\r\n loss = mp.MSE(img_arr, pred)\r\n err = 'Loss: {0:.5f}'.format(loss)\r\n if ret==True:\r\n test_history['Loss'].append(loss); test_history['Normal Frames'].append(norm_count)\r\n test_history['Anomaly Frames'].append(anom_count)\r\n test_history['Total Frames'].append(norm_count+anom_count)\r\n ToJson(test_history, name='Test History.json')\r\n if loss>threshold:\r\n anom_count += 10\r\n text='Anomalies Detected'\r\n for j in range(len(v_frames)):\r\n mp.ShowVideo(cap, v_frames[j], text, fill = True)\r\n if verbose:\r\n WriteInfo(err, text, norm_count, anom_count)\r\n else:\r\n text='Normal'\r\n norm_count += 10\r\n for j in range(len(v_frames)):\r\n mp.ShowVideo(cap, v_frames[j], text, fill = False)\r\n if verbose:\r\n WriteInfo(err, text, norm_count, anom_count)\r\n\r\n\r\n\r\ndef StaticServing(path, model, threshold, frames_ext, serve_type='frames', verbose=True):\r\n '''\r\n This function implements the model on the frames i.e UCSD dataset, it predicts the model\r\n and displays them one by one so it seems to be a video, but in reality it is just \r\n displaying the predicted frames.\r\n\r\n Parameters\r\n ----------\r\n path : \r\n Path for the testing dataset.\r\n model : \r\n Which model to load.\r\n threshold : \r\n Threshold for distinguishing anomalous frames from normal frames.\r\n frames_ext : \r\n Extension of the frames.\r\n serve_type : optional\r\n How to serve the model. The default is 'frames'.\r\n verbose : optional\r\n An argument to report more information about the operation in the programe.The default is True.\r\n\r\n Returns\r\n -------\r\n test_history : \r\n A JASON file containing complete history of the testing. It consists of all MSE's of \r\n all the frames and their predicted results.\r\n\r\n '''\r\n if serve_type=='frames':\r\n onlyfiles, _, _ = ReadFileNames(path, frames_ext)\r\n all_files = mp.ListCopy(onlyfiles)\r\n num = 10\r\n ten_list = np.reshape(all_files, (len(all_files)//num, num))\r\n img_lst = Fit_Preprocessing(path, frames_ext)\r\n X_test = GlobalNormalization(img_lst, save_data=False) \r\n elif serve_type=='npy':\r\n X_test = np.load(path)\r\n \r\n X_test = mp.PrepareData(X_test)\r\n norm_count = 0\r\n anom_count = 0\r\n test_history = {'Serving Type':serve_type, 'Loss':[], 'Normal Frames': [], \r\n 'Anomaly Frames':[], 'Total Frames':[]}\r\n print('\\n\\t------------- Now Serving will begin! -------------\\n\\n')\r\n for number, bunch in enumerate(X_test):\r\n #Reshaping batch to 5 dimensions\r\n batch = np.expand_dims(bunch,axis=0)\r\n pred_batch = model.predict(batch)\r\n #computing loss\r\n loss = mp.MSE(batch, pred_batch)\r\n err = 'Loss: {0:.5f}'.format(loss)\r\n test_history['Loss'].append(loss); test_history['Normal Frames'].append(norm_count)\r\n test_history['Anomaly Frames'].append(anom_count)\r\n test_history['Total Frames'].append(norm_count+anom_count)\r\n ToJson(test_history, name='Test History.json')\r\n if loss>threshold:\r\n anom_count += 10\r\n text='Anomalies Detected'\r\n if serve_type=='frames':\r\n for j in range(len(ten_list[number])):\r\n v_frame = cv2.imread(ten_list[number][j])\r\n cap=None\r\n mp.ShowVideo(cap, v_frame, text, fill = True)\r\n if verbose:\r\n WriteInfo(err, text, norm_count, anom_count)\r\n else:\r\n text='Normal'\r\n norm_count += 10\r\n if serve_type=='frames':\r\n for j in range(len(ten_list[number])):\r\n v_frame = cv2.imread(ten_list[number][j])\r\n cap=None\r\n mp.ShowVideo(cap, v_frame, text, fill = False)\r\n if verbose:\r\n WriteInfo(err, text, norm_count, anom_count)\r\n print('\\n\\t------------- Serving is Completed! -------------\\n\\n')\r\n return test_history\r\n\r\ndef DeploySystem(serve_type, model_path, preset_threshold=True, data_model=None, verbose=True, path=None, frames_ext=None, threshold=None, config_gpu=False):\r\n '''\r\n A function to decide, how to implement the model.\r\n\r\n Parameters\r\n ----------\r\n serve_type : \r\n An integer which tells the function to acitvate specific serving type.\r\n model_path : \r\n Location for the saved model.\r\n preset_threshold : optional\r\n A preset threshold for the prediction. The default is True.\r\n data_model : optional\r\n Tells which data's model is being used i.e UCSD or Avenue. The default is None.\r\n verbose : optional\r\n An argument to report more information about the operation in the programe. The default is True.\r\n path : optional\r\n Path to read the test data. The default is None.\r\n frames_ext : optional\r\n Defining the extension of the frames. The default is None.\r\n threshold : optional\r\n Threshold for distinguishing anomalous frames from normal frames. The default is None.\r\n config_gpu : optional\r\n Configures the GPU of the system. The default is False.\r\n\r\n Raises\r\n ------\r\n TypeError\r\n While 'preset_threshold' is set to True, you must pass a value to 'threshold'.\r\n ValueError\r\n As the model is trained on 2 data sets, UCSD and Avenue, therefore it should either of them.\r\n\r\n Returns\r\n -------\r\n test_hist : \r\n A JASON file containing complete history of the testing. It consists of all MSE's of \r\n all the frames and their predicted results.\r\n \r\n '''\r\n serving_types = ['real-time', 'video', 'frames', 'npy']\r\n if preset_threshold:\r\n if threshold is not None:\r\n raise TypeError('Invalid value given to argument `threshold`, its value must be None when `preset_threshold` argument is set to True.')\r\n if data_model=='UCSD':\r\n threshold=0.00026\r\n elif data_model=='Avenue':\r\n threshold=0.00040\r\n else:\r\n raise ValueError('Invalid value given to the Argument `data_model`, it can be either `UCSD` or `Avenue`!')\r\n else:\r\n if threshold is None:\r\n raise TypeError('None value given to argument `threshold`, it cannot be None when `preset_threshold` argument is set to False, provide a value of `float` datype or set the `preset_threshold` argument to True, to use Preset Values of Threshold.')\r\n if serve_type!='real-time' and serve_type != None:\r\n if path is None:\r\n raise TypeError('None value given to argument `path`, it cannot be None when value of `serve_type` is other than None.')\r\n if config_gpu:\r\n #Setting up the GPU to avoid VRAM and other conflicts.\r\n #For refernce visit: https://github.com/irdanish11/AnomalyEventDetection/issues/1\r\n mp.TF_GPUsetup()\r\n #loading the model\r\n model = get_model(model_path)\r\n ####################### Different Serving Techinques ######################\r\n \r\n #Serve the Anomaly Detection from the WebCam or any video device that is attached.\r\n if serve_type=='real-time':\r\n RealTimeDetection(model, threshold, serve_type, verbose=verbose)\r\n test_hist = None\r\n #Serve the Anomaly Detection from the given video.\r\n elif serve_type=='video':\r\n RealTimeDetection(model, threshold, serve_type, vid_path=path, verbose=verbose)\r\n test_hist = None\r\n #Serve the Anomaly Detection from the directory which contain frames, the Hirerachy of \r\n #directories must be like this: <path>/*Directories/Here all the images\r\n #The path you provide must contain a further directory or directories and in those directories\r\n #should have the frames.\r\n elif serve_type=='frames':\r\n test_hist = StaticServing(path, model, threshold, frames_ext, serve_type, verbose=verbose)\r\n ##Serve the Anomaly Detection from the .npy file.\r\n elif serve_type=='npy':\r\n test_hist = StaticServing(path, model, threshold, frames_ext, serve_type, verbose=verbose)\r\n else:\r\n raise ValueError('Invalid value given to the `serve_type` argument. Possible values: {0}'.format(serving_types))\r\n return test_hist\r\n\r\n\r\n\r\nif __name__=='__main__':\r\n \r\n #model_path = 'checkpoints/Train_UCSDped1_Model.h5'\r\n model_path = 'checkpoints/Train_AvenueDataset_Model.h5'\r\n \r\n vid_path = './Avenue_Dataset/testing_videos/05.avi' #5,9\r\n \r\n frames_ext='.tif'\r\n frames_dir='Datasets/UCSDped1/Test'\r\n \r\n npy_file='./Test_Data/Test_AvenueDataset.npy'\r\n \r\n #possible serving types\r\n #0-->real time\r\n #1-->video\r\n #2-->frames\r\n #3-->numpy array\r\n serving_types = ['real-time', 'video', 'frames', 'npy']\r\n #Serving of Model\r\n serve_type = serving_types[1]\r\n test_hist = DeploySystem(serve_type, model_path, preset_threshold=True, data_model='Avenue', verbose=True, \r\n path=vid_path, frames_ext=frames_ext, threshold=None, config_gpu=False)\r\n "
] | [
[
"tensorflow.keras.models.load_model",
"numpy.expand_dims",
"tensorflow.test.is_built_with_cuda",
"numpy.load",
"numpy.shape",
"tensorflow.test.is_gpu_available",
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
utsav-akhaury/Computational-Electromagnetics-FDTD-Analysis | [
"add2df141ba9c6414b19ac55d24c4251bbd05430"
] | [
"homog_gau_abc.py"
] | [
"\r\n#------------------ Gaussian pulse propagation in a homogeneous medium terminated with Absorbing Boundary Condition (ABC)\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n#----- Medium ----------\r\nlength = 2 \r\neps0 = 8.854e-12\r\nmeu0 = 4*np.pi*1e-7\r\nepsr = 1\r\nmeur = 1\r\neps = eps0*epsr\r\nmeu = meu0*meur\r\n\r\n#---- Signal -----------\r\nc = 3e8\r\nv = c/np.sqrt(epsr*meur)\r\nfreq = 3e9\r\nlamda = v/freq\r\n\r\n#------ Cell length and time step---------\r\ndz = lamda/10\r\ndt = dz/v\r\nN_cells = int(length/dz)\r\nMid_cell = int(N_cells/2)\r\n\r\n#------ Multiplying constants --------\r\nconst_e = dt/(eps*dz)\r\nconst_h = dt/(meu*dz)\r\n\r\n#------- Initialise E and H arrays ------------\r\nex = np.zeros(N_cells)\r\nhy = np.zeros(N_cells)\r\n\r\n#------ Gaussian pulse ------------\r\nTs = 10*dt # pulse width\r\nt0 = 3*Ts # delay\r\nN_steps = 200 # maximum iteration steps\r\n\r\n#----------------------------------\r\nex_past = np.zeros(N_cells)\r\nconst_abc = (v*dt - dz)/(v*dt + dz)\r\n\r\n#************** Iteration loop ****************\r\n\r\nfor n in range (N_steps): \r\n time = n*dt \r\n \r\n #------- Gaussian pulse launched in the middle cell -----------\r\n pulse = (np.exp(-np.power(((time-t0)/Ts),2)))/dz \r\n ex[Mid_cell-1] = pulse \r\n \r\n #------------------------ compute H -------------------------\r\n k = np.linspace(0, N_cells-2, N_cells-1, dtype = int)\r\n hy[k] = hy[k]-const_h*(ex[k+1]-ex[k])\r\n \r\n #------------------------ compute E -------------------------\r\n k = np.linspace(1, N_cells-2, N_cells-2, dtype = int)\r\n ex[k] = ex[k]-const_e*(hy[k]-hy[k-1]) \r\n \r\n #------------------------- ABC ------------------------------\r\n ex[0] = ex_past[1] + const_abc*(ex[1]-ex[0])\r\n ex[N_cells-1] = ex_past[N_cells-2] + const_abc*(ex[N_cells-2]-ex[N_cells-1])\r\n ex_past = np.copy(ex)\r\n \r\n #------------------------ plot ------------------------------\r\n plt.plot(np.linspace(1, N_cells, N_cells, dtype = int),ex)\r\n plt.xlim(0,200)\r\n plt.ylim((-150,150))\r\n plt.grid()\r\n plt.show()\r\n"
] | [
[
"numpy.sqrt",
"numpy.linspace",
"numpy.power",
"matplotlib.pyplot.ylim",
"numpy.copy",
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.grid",
"matplotlib.pyplot.show",
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
lebrice/avalanche | [
"fe7e1e664ab20697343495fbe1328a20215feffb"
] | [
"avalanche/benchmarks/datasets/core50/core50.py"
] | [
"################################################################################\n# Copyright (c) 2021 ContinualAI. #\n# Copyrights licensed under the MIT License. #\n# See the accompanying LICENSE file for terms. #\n# #\n# Date: 10-10-2020 #\n# Author: Vincenzo Lomonaco #\n# E-mail: [email protected] #\n# Website: www.continualai.org #\n################################################################################\n\n\"\"\" CORe50 Pytorch Dataset \"\"\"\n\nimport os\nimport logging\nfrom torch.utils.data.dataset import Dataset\nfrom torchvision.transforms import ToTensor\nfrom PIL import Image\nimport pickle as pkl\nfrom os.path import expanduser\nfrom .core50_data import CORE50_DATA\n\n\ndef pil_loader(path):\n \"\"\" Load an Image with PIL \"\"\"\n # open path as file to avoid ResourceWarning\n # (https://github.com/python-pillow/Pillow/issues/835)\n with open(path, 'rb') as f:\n img = Image.open(f)\n return img.convert('RGB')\n\n\nclass CORe50(Dataset):\n \"\"\" CORe50 Pytorch Dataset \"\"\"\n\n def __init__(self, root=expanduser(\"~\")+\"/.avalanche/data/core50/\",\n train=True, transform=ToTensor(), target_transform=None,\n loader=pil_loader, download=True):\n\n self.train = train # training set or test set\n self.transform = transform\n self.target_transform = target_transform\n self.root = root\n self.loader = loader\n self.log = logging.getLogger(\"avalanche\")\n\n # any scenario and run is good here since we want just to load the\n # train images and targets with no particular order\n scen = 'ni'\n run = 0\n nbatch = 8\n\n if download:\n self.core_data = CORE50_DATA(data_folder=root)\n\n self.log.info(\"Loading paths...\")\n with open(os.path.join(root, 'paths.pkl'), 'rb') as f:\n self.train_test_paths = pkl.load(f)\n\n self.log.info(\"Loading labels...\")\n with open(os.path.join(root, 'labels.pkl'), 'rb') as f:\n self.all_targets = pkl.load(f)\n self.train_test_targets = []\n for i in range(nbatch + 1):\n self.train_test_targets += self.all_targets[scen][run][i]\n\n self.log.info(\"Loading LUP...\")\n with open(os.path.join(root, 'LUP.pkl'), 'rb') as f:\n self.LUP = pkl.load(f)\n\n self.idx_list = []\n if train:\n for i in range(nbatch + 1):\n self.idx_list += self.LUP[scen][run][i]\n else:\n self.idx_list = self.LUP[scen][run][-1]\n\n self.paths = []\n self.targets = []\n\n for idx in self.idx_list:\n self.paths.append(self.train_test_paths[idx])\n self.targets.append(self.train_test_targets[idx])\n\n def __getitem__(self, index):\n \"\"\"\n Args:\n index (int): Index\n\n Returns:\n tuple: (sample, target) where target is class_index of the target\n class.\n \"\"\"\n\n target = self.targets[index]\n img = self.loader(\n os.path.join(\n self.root, \"core50_128x128\", self.paths[index]\n )\n )\n if self.transform is not None:\n img = self.transform(img)\n if self.target_transform is not None:\n target = self.target_transform(target)\n\n return img, target\n\n def __len__(self):\n return len(self.targets)\n\n\nif __name__ == \"__main__\":\n\n # this litte example script can be used to visualize the first image\n # leaded from the dataset.\n from torch.utils.data.dataloader import DataLoader\n import matplotlib.pyplot as plt\n from torchvision import transforms\n import torch\n\n train_data = CORe50()\n test_data = CORe50(train=False)\n print(\"train size: \", len(train_data))\n print(\"Test size: \", len(test_data))\n dataloader = DataLoader(train_data, batch_size=1)\n\n for batch_data in dataloader:\n x, y = batch_data\n plt.imshow(\n transforms.ToPILImage()(torch.squeeze(x))\n )\n plt.show()\n print(x.size())\n print(len(y))\n break\n\n\n__all__ = [\n 'CORe50'\n]\n"
] | [
[
"torch.utils.data.dataloader.DataLoader",
"matplotlib.pyplot.show",
"torch.squeeze"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
LTHODAVDOPL/tensorflow | [
"73083d29afe770870742a9d19555686886e76f6d"
] | [
"tensorflow/python/framework/function_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 functions.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport re\nimport sys\nimport time\n\nimport numpy as np\n\nfrom tensorflow.core.framework import function_pb2\nfrom tensorflow.core.protobuf import config_pb2\nfrom tensorflow.core.protobuf import rewriter_config_pb2\nfrom tensorflow.python.client import session\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import errors_impl\nfrom tensorflow.python.framework import function\nfrom tensorflow.python.framework import graph_to_function_def\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.framework.errors import InvalidArgumentError\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import functional_ops\nfrom tensorflow.python.ops import gen_logging_ops\nfrom tensorflow.python.ops import gradients_impl\nfrom tensorflow.python.ops import init_ops\nfrom tensorflow.python.ops import linalg_ops\nfrom tensorflow.python.ops import logging_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import nn_ops\nfrom tensorflow.python.ops import random_ops\nfrom tensorflow.python.ops import variable_scope\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.platform import test\nfrom tensorflow.python.platform import tf_logging\n\n\ndef _OptimizerOptions():\n for cse in [False, True]:\n for inline in [False, True]:\n for cfold in [False, True]:\n cfg = config_pb2.ConfigProto(\n graph_options=config_pb2.GraphOptions(\n optimizer_options=config_pb2.OptimizerOptions(\n opt_level=config_pb2.OptimizerOptions.L0,\n do_common_subexpression_elimination=cse,\n do_function_inlining=inline,\n do_constant_folding=cfold)))\n if cse:\n cfg.graph_options.rewrite_options.arithmetic_optimization = (\n rewriter_config_pb2.RewriterConfig.ON)\n else:\n cfg.graph_options.rewrite_options.arithmetic_optimization = (\n rewriter_config_pb2.RewriterConfig.OFF)\n if inline:\n cfg.graph_options.rewrite_options.function_optimization = (\n rewriter_config_pb2.RewriterConfig.ON)\n else:\n cfg.graph_options.rewrite_options.function_optimization = (\n rewriter_config_pb2.RewriterConfig.OFF)\n if cfold:\n cfg.graph_options.rewrite_options.constant_folding = (\n rewriter_config_pb2.RewriterConfig.ON)\n else:\n cfg.graph_options.rewrite_options.constant_folding = (\n rewriter_config_pb2.RewriterConfig.OFF)\n yield cfg\n\n\n@test_util.with_c_shapes\nclass FunctionTest(test.TestCase):\n \"\"\"Test methods for verifying Function support.\n\n These test methods are used as mix-ins in two test cases: with\n and without C API support.\n \"\"\"\n\n def testIdentity(self):\n\n @function.Defun(dtypes.float32, func_name=\"MyIdentity\")\n def MyIdentityFunc(a):\n return a\n\n with ops.Graph().as_default():\n call = MyIdentityFunc([18.0])\n self.assertEqual(\"MyIdentity\", call.op.name)\n with session.Session() as sess:\n self.assertAllEqual([18.0], sess.run(call))\n\n def testIdentityImplicitDeref(self):\n\n @function.Defun(dtypes.float32, func_name=\"MyIdentity\")\n def MyIdentityFunc(a):\n return a\n\n with ops.Graph().as_default():\n var = variables.Variable([18.0])\n call = MyIdentityFunc(var._ref()) # pylint: disable=protected-access\n self.assertEqual(\"MyIdentity\", call.op.name)\n for cfg in _OptimizerOptions():\n with session.Session(config=cfg) as sess:\n sess.run(var.initializer)\n self.assertAllEqual([18.0], sess.run(call))\n\n def testIdentityOutputName(self):\n\n @function.Defun(\n dtypes.float32, func_name=\"MyIdentity\", out_names=[\"my_result_name\"])\n def MyIdentityFunc(a):\n return a\n\n with ops.Graph().as_default():\n call = MyIdentityFunc([18.0])\n self.assertEqual(\"MyIdentity\", call.op.name)\n with session.Session() as sess:\n self.assertAllEqual([18.0], sess.run(call))\n\n def testTooManyOutputNames(self):\n\n @function.Defun(\n dtypes.float32,\n func_name=\"MyIdentity\",\n out_names=[\"my_result1\", \"my_result2\"])\n def MyIdentityFunc(a):\n return a\n\n with ops.Graph().as_default():\n with self.assertRaisesRegexp(\n errors_impl.InvalidArgumentError,\n (r\"output names must be either empty or equal in size to outputs. \"\n \"output names size = 2 outputs size = 1\")):\n MyIdentityFunc([18.0])\n\n def testDefineFunction2Args(self):\n\n @function.Defun(dtypes.float32, dtypes.float32, func_name=\"APlus2B\")\n def APlus2B(a, b):\n return a + b * 2\n\n with ops.Graph().as_default():\n call = APlus2B([1.0], [2.0])\n self.assertEqual(\"APlus2B\", call.op.name)\n with session.Session() as sess:\n self.assertAllEqual([5.0], sess.run(call))\n\n def testFunctionWithNoOutput(self):\n\n @function.Defun(dtypes.float32, dtypes.float32)\n def APlus2B(a, b):\n c = a + b * 2 # Create some ops to have nodes in the body\n print(c) # Using 'print' to make lint happy\n\n with ops.Graph().as_default():\n # Call function. There should be no exceptions.\n APlus2B([1.0], [2.0])\n\n def testDefineFunction2ArgsOutputName(self):\n\n @function.Defun(\n dtypes.float32,\n dtypes.float32,\n func_name=\"APlus2B\",\n out_names=[\"my_result_name\"])\n def APlus2B(a, b):\n return a + b * 2\n\n # APlus2B is stateless.\n self.assertEqual([], APlus2B.stateful_ops)\n with ops.Graph().as_default():\n call = APlus2B([1.0], [2.0])\n self.assertEqual(\"APlus2B\", call.op.name)\n with session.Session() as sess:\n self.assertAllEqual([5.0], sess.run(call))\n\n def testDefineFunctionDuplicateOutputs(self):\n\n @function.Defun(dtypes.float32, func_name=\"Duplicate\")\n def Duplicate(a):\n b = a + 1.0\n return b, b\n\n g = ops.Graph()\n with g.as_default():\n Duplicate([3.0])\n func_sig = g.as_graph_def().library.function[0].signature\n # The names given to both outputs should be different\n # even though the same tensor is emitted to both.\n out_names = [a.name for a in func_sig.output_arg]\n self.assertEqual(2, len(out_names))\n self.assertNotEqual(out_names[0], out_names[1])\n\n def testGradientFunc(self):\n\n @function.Defun(dtypes.float32, func_name=\"XSquarePlusOneFn\")\n def XSquarePlusOne(x):\n return x * x + 1.0\n\n @function.Defun(dtypes.float32, dtypes.float32)\n def XSquarePlusOneGrad(x, dy):\n dx = functional_ops.symbolic_gradient(\n input=[x, dy], Tout=[dtypes.float32], f=\"XSquarePlusOneFn\", name=\"dx\")\n return dx\n\n g = ops.Graph()\n with g.as_default():\n call_f = XSquarePlusOne([2.0])\n call_g = XSquarePlusOneGrad([2.0], [0.1])\n\n with session.Session() as sess:\n self.assertAllClose([5.0], sess.run(call_f))\n self.assertAllClose([0.4], sess.run(call_g))\n\n def testTanhSymGrad(self):\n\n @function.Defun(dtypes.float32)\n def Forward(x):\n return math_ops.reduce_sum(math_ops.tanh(x))\n\n g = ops.Graph()\n with g.as_default():\n x = array_ops.placeholder(dtypes.float32)\n y = Forward(x)\n dx = gradients_impl.gradients([y], [x])\n\n inp = np.array([-1, 1, 2, -2], dtype=np.float32)\n feed = {x: inp}\n cfg = config_pb2.ConfigProto(\n graph_options=config_pb2.GraphOptions(\n optimizer_options=config_pb2.OptimizerOptions(\n opt_level=config_pb2.OptimizerOptions.L1,\n do_function_inlining=True)))\n with session.Session(graph=g, config=cfg) as sess:\n out, = sess.run(dx, feed)\n self.assertAllClose(1 - np.square(np.tanh(inp)), out)\n\n def testCustomGradient(self):\n dtype = dtypes.float32\n\n @function.Defun(dtype, dtype, dtype)\n def XentLossGrad(logits, labels, dloss):\n dlogits = array_ops.reshape(dloss, [-1, 1]) * (\n nn_ops.softmax(logits) - labels)\n dlabels = array_ops.zeros_like(labels)\n # Takes exp(dlogits) to differentiate it from the \"correct\" gradient.\n return math_ops.exp(dlogits), dlabels\n\n @function.Defun(dtype, dtype, grad_func=XentLossGrad)\n def XentLoss(logits, labels):\n return math_ops.reduce_sum(labels * math_ops.log(nn_ops.softmax(logits)),\n 1)\n\n g = ops.Graph()\n with g.as_default():\n logits = array_ops.placeholder(dtype)\n labels = array_ops.placeholder(dtype)\n loss = XentLoss(logits, labels)\n dlogits = gradients_impl.gradients([loss], [logits])\n\n x = np.random.uniform(-10., 10., size=(4, 9)).astype(np.float32)\n prob = np.exp(x) / np.sum(np.exp(x), 1, keepdims=1)\n y = np.random.uniform(-10., 10., size=(4, 9)).astype(np.float32)\n for cfg in _OptimizerOptions():\n tf_logging.info(\"cfg = %s\", cfg)\n with session.Session(graph=g, config=cfg) as sess:\n out, = sess.run(dlogits, {logits: x, labels: y})\n self.assertAllClose(out, np.exp(prob - y))\n\n def testCustomGradientError(self):\n dtype = dtypes.float32\n\n @function.Defun(dtype, dtype, dtype)\n def Grad(x, dy, dz):\n # Should have returned 1 result.\n return x, dy + dz\n\n @function.Defun(dtype, grad_func=Grad)\n def Forward(x):\n return x, x\n\n g = ops.Graph()\n with g.as_default():\n inp = array_ops.placeholder(dtype)\n out = math_ops.add_n(Forward(inp))\n dinp = gradients_impl.gradients(out, [inp])\n\n x = np.random.uniform(-10., 10., size=(4, 9)).astype(np.float32)\n with session.Session(graph=g) as sess:\n with self.assertRaisesRegexp(\n errors_impl.InvalidArgumentError,\n \"SymGrad expects to return 1.*but get 2.*instead\"):\n _ = sess.run(dinp, {inp: x})\n\n def testSymGradShape(self):\n g = ops.Graph()\n with g.as_default():\n x = array_ops.placeholder(dtypes.float32, [25, 4])\n y = array_ops.placeholder(dtypes.float32, [200, 100])\n dz = array_ops.placeholder(dtypes.float32, [1])\n # We assume Foo is a function of (x, y) -> (z) Then, Foo's\n # gradient function is (x, y, dz) -> (dx, dy). dx's shape\n # should be the same as x's; and dy's shape should be the same\n # as y's.\n dx, dy = functional_ops.symbolic_gradient(\n input=[x, y, dz], Tout=[dtypes.float32] * 2, f=\"Foo\")\n self.assertEqual(x.get_shape(), dx.get_shape())\n self.assertEqual(y.get_shape(), dy.get_shape())\n\n def testSymGradAttr(self):\n\n @function.Defun(noinline=True)\n def Foo(x):\n return x * 2\n\n self.assertTrue(\n Foo.instantiate([dtypes.float32]).definition.attr[\"_noinline\"].b)\n\n g = ops.Graph()\n with g.as_default():\n x = constant_op.constant(3.0)\n y = Foo(x)\n dx, = gradients_impl.gradients(y, [x])\n\n cfg = config_pb2.ConfigProto(\n graph_options=config_pb2.GraphOptions(\n optimizer_options=config_pb2.OptimizerOptions(\n opt_level=config_pb2.OptimizerOptions.L0,\n do_common_subexpression_elimination=True,\n do_function_inlining=True,\n do_constant_folding=True)))\n\n with self.session(graph=g, config=cfg):\n self.assertAllClose(y.eval(), 6.)\n self.assertAllClose(dx.eval(), 2.)\n\n def _testZNoDepOnY(self, use_const_grad_ys):\n\n @function.Defun(dtypes.float32, dtypes.float32)\n def Foo(x, y): # pylint: disable=unused-argument\n return x * 2\n\n with ops.Graph().as_default():\n # z = Foo(x, y). z doe\n x = constant_op.constant(1.0)\n y = constant_op.constant(2.0)\n z = Foo(x, y)\n if use_const_grad_ys:\n dx, dy = gradients_impl.gradients([z], [x, y], grad_ys=[1.0])\n else:\n dx, dy = gradients_impl.gradients([z], [x, y])\n with session.Session() as sess:\n dx_val, dy_val = sess.run([dx, dy])\n self.assertEqual([2.0], dx_val)\n self.assertEqual([0.0], dy_val)\n\n def testZNoDepOnY(self):\n self._testZNoDepOnY(False)\n\n def testZNoDepOnYConstGradYs(self):\n # Tests for constant folding of grad_ys\n self._testZNoDepOnY(True)\n\n def testDefineFunctionNoArgs(self):\n\n @function.Defun(func_name=\"AConstant\")\n def AConstant():\n return constant_op.constant([42])\n\n with ops.Graph().as_default():\n\n call = AConstant()\n self.assertEqual(\"AConstant\", call.op.name)\n with session.Session() as sess:\n self.assertAllEqual([42], sess.run(call))\n\n def testDefineFunctionNames(self):\n\n @function.Defun(dtypes.float32, func_name=\"Foo\")\n def Foo(a):\n return a + 1\n\n with ops.Graph().as_default():\n call1 = Foo([1.0])\n self.assertEqual(\"Foo\", call1.op.name)\n call2 = Foo([1.0])\n self.assertEqual(\"Foo_1\", call2.op.name)\n # pylint: disable=unexpected-keyword-arg\n call3 = Foo([1.0], name=\"mine\")\n self.assertEqual(\"mine\", call3.op.name)\n with ops.name_scope(\"my\"):\n call4 = Foo([1.0], name=\"precious\")\n self.assertEqual(\"my/precious\", call4.op.name)\n\n def testNoOp(self):\n\n @function.Defun(dtypes.float32)\n def Foo(x):\n y = logging_ops.Print(x, [], \"Hello\")\n with ops.control_dependencies([y]):\n z = control_flow_ops.no_op()\n with ops.control_dependencies([z]):\n return x * 2\n\n with ops.Graph().as_default(), self.cached_session():\n z = Foo(constant_op.constant(3.0))\n self.assertAllEqual(z.eval(), 6.0)\n\n def testAssertOp(self):\n\n @function.Defun(dtypes.float32)\n def Foo(x):\n check = gen_logging_ops._assert(math_ops.greater(x, 0), [x])\n with ops.control_dependencies([check]):\n return x * 2\n\n # Foo contains a stateful op (Assert).\n self.assertEqual([(\"Assert\", \"Assert\")], Foo.stateful_ops)\n g = ops.Graph()\n with g.as_default(), self.cached_session():\n self.assertAllEqual(Foo(constant_op.constant(3.0)).eval(), 6.0)\n with self.assertRaisesRegexp(errors_impl.InvalidArgumentError,\n \"assertion failed.*-3\"):\n self.assertAllEqual(Foo(constant_op.constant(-3.0)).eval(), 6.0)\n\n def testAssertWrapper(self):\n\n @function.Defun(dtypes.float32)\n def MyFn(x):\n with ops.control_dependencies(\n [control_flow_ops.Assert(math_ops.less_equal(x, 10.0), [x])]):\n return array_ops.identity(x)\n\n with self.cached_session():\n self.assertEqual(1.0, MyFn(1.0).eval())\n with self.assertRaisesRegexp(errors_impl.InvalidArgumentError,\n \"assertion\"):\n _ = MyFn(100.0).eval()\n\n def testWhileLoopCallsFunc(self):\n with self.test_session(use_gpu=True) as sess:\n\n @function.Defun(dtypes.float32)\n def Times2(x):\n constant_two = constant_op.constant(2, dtypes.int32)\n two_on_gpu = math_ops.cast(constant_two, dtypes.float32)\n return x * two_on_gpu\n\n def Body(x):\n x2 = Times2(x)\n x2.set_shape([])\n return x2\n\n loop = control_flow_ops.while_loop(lambda x: x < 1e5, Body, [1.0])\n\n ans = sess.run(loop)\n self.assertAllClose(ans, 131072.)\n\n def testControlFlowStrictness(self):\n \"\"\"Inlined functions must not execute in a untaken control flow branch.\"\"\"\n\n @function.Defun(dtypes.int32)\n def AssertFail(x):\n # Assertion that always fails and does not have a data dependency on `x`.\n assert_false = control_flow_ops.Assert(False, [42])\n with ops.control_dependencies([assert_false]):\n return array_ops.identity(x)\n\n with ops.device(\"CPU\"):\n pred = array_ops.placeholder(dtypes.bool)\n x = array_ops.placeholder(dtypes.int32)\n cond = control_flow_ops.cond(pred, lambda: x + 1, lambda: AssertFail(x))\n # pylint: disable=unnecessary-lambda\n loop = control_flow_ops.while_loop(lambda y: pred,\n lambda y: AssertFail(y), [x])\n # pylint: enable=unnecessary-lambda\n\n rewriter_config = rewriter_config_pb2.RewriterConfig(\n dependency_optimization=rewriter_config_pb2.RewriterConfig.OFF)\n # Enables inlining.\n config = config_pb2.ConfigProto(\n graph_options=config_pb2.GraphOptions(\n optimizer_options=config_pb2.OptimizerOptions(\n opt_level=config_pb2.OptimizerOptions.L0,\n do_common_subexpression_elimination=True,\n do_function_inlining=True,\n do_constant_folding=True),\n rewrite_options=rewriter_config))\n\n with session.Session(config=config) as sess:\n # Since the 'False' branch is not taken, the assertion should not fire.\n self.assertEqual(4, sess.run(cond, {pred: True, x: 3}))\n\n # The assertion should still fire if the False branch is taken.\n with self.assertRaisesRegexp(errors_impl.InvalidArgumentError,\n \"assertion\"):\n sess.run(cond, {pred: False, x: 3})\n\n # Similarly for loops.\n self.assertEqual(3, sess.run(loop, {pred: False, x: 3}))\n with self.assertRaisesRegexp(errors_impl.InvalidArgumentError,\n \"assertion\"):\n sess.run(loop, {pred: True, x: 3})\n\n def testVar(self):\n\n @function.Defun(dtypes.float32)\n def Foo(x):\n return x * x + 1\n\n g = ops.Graph()\n with g.as_default():\n v = variables.Variable(constant_op.constant(10.0))\n z = Foo(v)\n\n with self.session(graph=g):\n variables.global_variables_initializer().run()\n self.assertAllEqual(z.eval(), 101.)\n\n def testResourceVarAsImplicitInput(self):\n g = ops.Graph()\n with g.as_default(), ops.device(\"cpu:0\"):\n expected_type = dtypes.float32\n expected_shape = tensor_shape.TensorShape((4, 4))\n v = variable_scope.get_variable(\n \"var\", expected_shape, expected_type, use_resource=True)\n\n @function.Defun()\n def Foo():\n captured = array_ops.identity(v)\n self.assertEqual(expected_type, captured.dtype)\n self.assertEqual(expected_shape, captured.shape)\n return captured, array_ops.shape(captured)\n\n expected_val = v.value()\n actual_val, actual_shape = Foo()\n\n with self.session(graph=g):\n v.initializer.run()\n self.assertAllEqual(expected_val.eval(), actual_val.eval())\n self.assertAllEqual(expected_shape, actual_shape.eval())\n\n def testDefineErrors(self):\n with ops.Graph().as_default():\n with self.assertRaisesRegexp(ValueError, \"can not return None\"):\n\n @function.Defun()\n def TwoNone():\n return None, None\n\n _ = TwoNone.definition\n\n with self.assertRaisesRegexp(ValueError, \"are not supported\"):\n\n @function.Defun()\n def DefaultArg(unused_a=12):\n return constant_op.constant([1])\n\n _ = DefaultArg.definition\n with self.assertRaisesRegexp(ValueError, \"are not supported\"):\n\n @function.Defun()\n def KwArgs(**unused_kwargs):\n return constant_op.constant([1])\n\n _ = KwArgs.definition\n with self.assertRaisesRegexp(ValueError, \"specified input types\"):\n\n @function.Defun(dtypes.float32)\n def PlusMinusV2(a, b):\n return a + b, b - a\n\n _ = PlusMinusV2.definition\n with self.assertRaisesRegexp(ValueError, \"specified input types\"):\n\n @function.Defun(dtypes.float32, dtypes.float32, dtypes.float32)\n def PlusMinusV3(a, b):\n return a + b, b - a\n\n _ = PlusMinusV3.definition\n\n def testCallErrors(self):\n\n @function.Defun()\n def Const():\n return constant_op.constant(1)\n\n @function.Defun(dtypes.int32)\n def PlusOne(a):\n return a + 1\n\n @function.Defun(dtypes.int32, dtypes.int32)\n def PlusMinus(a, b):\n return a + b, b - a\n\n with ops.Graph().as_default():\n\n _ = Const()\n # pylint: disable=too-many-function-args\n # pylint: disable=unexpected-keyword-arg\n # pylint: disable=no-value-for-parameter\n with self.assertRaisesRegexp(ValueError, \"arguments: 0\"):\n _ = Const(1)\n with self.assertRaisesRegexp(ValueError, \"arguments: 0\"):\n _ = Const(1, 2)\n\n with self.assertRaisesRegexp(ValueError, \"arguments: 1\"):\n _ = PlusOne()\n _ = PlusOne(1)\n with self.assertRaisesRegexp(ValueError, \"arguments: 1\"):\n _ = PlusOne(1, 2)\n\n with self.assertRaisesRegexp(ValueError, \"arguments: 2\"):\n _ = PlusMinus()\n with self.assertRaisesRegexp(ValueError, \"arguments: 2\"):\n _ = PlusMinus(1)\n _ = PlusMinus(1, 2)\n\n _ = PlusOne(1, name=\"p1\")\n with self.assertRaisesRegexp(ValueError, \"Unknown keyword arguments\"):\n _ = PlusOne(1, device=\"/device:GPU:0\")\n\n def testFunctionDecorator(self):\n\n @function.Defun(dtypes.float32, func_name=\"Minus1\")\n def Minus1(b):\n return b - 1.0\n\n with ops.Graph().as_default():\n call1 = Minus1([2.])\n self.assertTrue(isinstance(Minus1, function._DefinedFunction))\n self.assertEqual(Minus1.name, \"Minus1\")\n # pylint: disable=unexpected-keyword-arg\n call2 = Minus1(call1, name=\"next\")\n # pylint: enable=unexpected-keyword-arg\n self.assertEqual(\"next\", call2.op.name)\n with session.Session() as sess:\n self.assertAllEqual([1], sess.run(call1))\n self.assertAllEqual([0], sess.run(call2))\n\n def testNestedFunction(self):\n\n @function.Defun(dtypes.float32)\n def Cube(x):\n return x * x * x\n\n @function.Defun(dtypes.float32, dtypes.float32)\n def CubeXPlusY(x, y):\n return Cube(x) + y\n\n with ops.Graph().as_default():\n z = CubeXPlusY(3.0, -2.0)\n with self.cached_session():\n self.assertAllEqual(z.eval(), 25.0)\n\n def testNestedDefinedFunction(self):\n\n @function.Defun(dtypes.float32, dtypes.float32)\n def CubeXPlusY(x, y):\n\n @function.Defun(dtypes.float32)\n def Cube(x):\n return x * x * x\n\n return Cube(x) + y\n\n with ops.Graph().as_default():\n z = CubeXPlusY(3.0, -2.0)\n with self.cached_session():\n self.assertAllEqual(z.eval(), 25.0)\n\n def testUnusedFunction(self):\n invoked = False\n # pylint: disable=unused-variable\n @function.Defun()\n def Unused():\n invoked = True\n return constant_op.constant(42.)\n\n self.assertFalse(invoked)\n g = ops.Graph()\n with g.as_default():\n\n @function.Defun()\n def Unused2():\n invoked = True\n return constant_op.constant(7.)\n\n constant_op.constant(3.)\n # pylint: enable=unused-variable\n self.assertFalse(invoked)\n gdef = g.as_graph_def()\n self.assertEqual(0, len(gdef.library.function))\n\n def testReduction(self):\n g = ops.Graph()\n\n # BN0 is computing batch normed matrix along rows.\n def BN0(x):\n mean = math_ops.reduce_mean(x, [0])\n var = math_ops.reduce_mean(math_ops.square(x - mean)) # biased var\n rstd = math_ops.rsqrt(var + 1e-8)\n return (x - mean) * rstd\n\n # Wraps BatchNorm in a tf function.\n @function.Defun(dtypes.float32)\n def BN1(x):\n return BN0(x)\n\n with g.as_default():\n x = array_ops.placeholder(dtypes.float32)\n y0 = BN0(x) # A plain graph\n y1 = BN1(x) # A tf function\n dx0, = gradients_impl.gradients([y0], [x])\n dx1, = gradients_impl.gradients([y1], [x])\n\n # Both should produce the same result and gradient.\n with self.session(graph=g) as sess:\n vals = sess.run([y0, y1, dx0, dx1], {x: np.random.uniform(size=(3, 7))})\n self.assertAllClose(vals[0], vals[1])\n self.assertAllClose(vals[2], vals[3])\n\n def testCapture(self):\n g = ops.Graph()\n with g.as_default():\n w = variables.Variable(constant_op.constant([[1.0]]))\n b = variables.Variable(constant_op.constant([2.0]))\n\n # Foo() captures w and b.\n @function.Defun(dtypes.float32)\n def Foo(x):\n\n # Plus() captures b.\n @function.Defun(dtypes.float32)\n def Plus(y):\n return y + b\n\n return Plus(math_ops.matmul(w, x))\n\n y = Foo(constant_op.constant([[10.]]))\n\n @function.Defun()\n def Bar():\n return w\n\n z = Bar()\n\n with self.session(graph=g):\n variables.global_variables_initializer().run()\n self.assertAllEqual(y.eval(), [[12.0]])\n self.assertAllEqual(z.eval(), [[1.0]])\n\n def testCaptureControls(self):\n g = ops.Graph()\n with g.as_default():\n x = constant_op.constant([10.0])\n x = logging_ops.Print(x, [x], \"outer\")\n\n @function.Defun(dtypes.float32)\n def Foo(y):\n with ops.control_dependencies([x]):\n y = logging_ops.Print(y, [y], \"inner\")\n return y\n\n with self.assertRaisesRegexp(ValueError, \"not an element of this graph.\"):\n # NOTE: We still do not support capturing control deps.\n _ = Foo(x)\n\n def testCaptureInWhileLoop(self):\n g = ops.Graph()\n with g.as_default():\n x = constant_op.constant(1)\n\n @function.Defun()\n def Foo():\n return control_flow_ops.while_loop(lambda i: i < 10, lambda i: i + x,\n [0])\n\n y = Foo()\n\n with self.session(graph=g) as sess:\n self.assertEqual(sess.run(y), 10)\n\n def testCaptureInCond(self):\n g = ops.Graph()\n with g.as_default():\n x = constant_op.constant(1)\n\n @function.Defun(dtypes.bool)\n def Foo(pred):\n return control_flow_ops.cond(pred, lambda: x, lambda: x + 1)\n\n y = Foo(True)\n z = Foo(False)\n\n with self.session(graph=g) as sess:\n self.assertEqual(sess.run(y), 1)\n self.assertEqual(sess.run(z), 2)\n\n def testStableName(self):\n\n @function.Defun()\n def Foo(x, y, z):\n return math_ops.tanh(math_ops.matmul(x, y) + z)\n\n if sys.byteorder == \"big\":\n self.assertEqual(\"Foo_kEdkAG8SJvg\",\n Foo.instantiate([dtypes.float32] * 3).name)\n else:\n self.assertEqual(\"Foo_aCYSbwBkR5A\",\n Foo.instantiate([dtypes.float32] * 3).name)\n\n def testSignatureHash(self):\n # Foo.Inner and Bar.Inner have identical function body but have\n # different signatures. They should be treated as two different functions.\n\n @function.Defun()\n def Foo(x):\n\n @function.Defun()\n def Inner(x):\n return x + 10.\n\n return Inner(x)\n\n @function.Defun()\n def Bar(x):\n\n @function.Defun()\n def Inner(x, unused_y, unused_z):\n return x + 10.\n\n return Inner(x, 2., 3.)\n\n g = ops.Graph()\n with g.as_default():\n x = constant_op.constant(10.0)\n y = Foo(x)\n z = Bar(x)\n\n with self.session(graph=g) as sess:\n v0, v1 = sess.run([y, z])\n self.assertAllEqual(v0, 20.)\n self.assertAllEqual(v1, 20.)\n\n def testShapeFunction(self):\n\n @function.Defun(\n dtypes.float32, shape_func=lambda op: [op.inputs[0].get_shape()])\n def Foo(x):\n return x + 1.0\n\n @function.Defun(\n shape_func=lambda op: [[1] + op.inputs[0].get_shape().as_list()])\n def Bar(x):\n return array_ops.stack([x])\n\n g = ops.Graph()\n with g.as_default():\n x = Foo([1.0, 2.0])\n self.assertEqual(x.get_shape().as_list(), [2])\n y = Bar(array_ops.zeros([1, 2, 3]))\n self.assertAllEqual(y.get_shape().as_list(), [1, 1, 2, 3])\n\n def testVariableReuse(self):\n\n def LinearWithReuse(input_tensor, reuse=None):\n size = input_tensor.shape.dims[1]\n with variable_scope.variable_scope(\"linear\", reuse=reuse):\n w = variable_scope.get_variable(\n \"w\", shape=[size, size], dtype=input_tensor.dtype)\n return math_ops.matmul(input_tensor, w)\n\n @function.Defun(dtypes.float32)\n def Foo(inputs):\n inputs = array_ops.reshape(inputs, [32, 100])\n hidden = LinearWithReuse(inputs)\n return LinearWithReuse(hidden, reuse=True)\n\n input_op = array_ops.placeholder(shape=[32, 100], dtype=dtypes.float32)\n output_op = Foo(input_op)\n\n global_vars = variables.global_variables()\n self.assertEqual(len(global_vars), 1)\n self.assertEqual(global_vars[0].name, \"linear/w:0\")\n\n with session.Session() as sess:\n sess.run(variables.global_variables_initializer())\n output_val = sess.run(\n output_op, feed_dict={input_op: np.random.rand(32, 100)})\n self.assertEqual(output_val.shape, (32, 100))\n\n def testFunctionCallInDifferentVariableScopes(self):\n\n @function.Defun(dtypes.float32)\n def Foo(inputs):\n var = variable_scope.get_variable(\n \"var\",\n shape=[10],\n dtype=dtypes.float32,\n initializer=init_ops.ones_initializer())\n return inputs + var\n\n input_op = array_ops.placeholder(shape=[10], dtype=dtypes.float32)\n with variable_scope.variable_scope(\"vs1\"):\n out1_op = Foo(input_op)\n\n with variable_scope.variable_scope(\"vs2\"):\n out2_op = Foo(input_op)\n\n global_vars = variables.global_variables()\n self.assertEqual(len(global_vars), 1)\n self.assertEqual(global_vars[0].name, \"vs1/var:0\")\n\n with session.Session() as sess:\n sess.run(variables.global_variables_initializer())\n out1, out2 = sess.run(\n [out1_op, out2_op], feed_dict={input_op: np.linspace(1, 10, 10)})\n self.assertAllEqual(out1, np.linspace(2, 11, 10))\n self.assertAllEqual(out2, np.linspace(2, 11, 10))\n\n def testTwoInputsSameOp(self):\n g = ops.Graph()\n with g.as_default():\n m = array_ops.placeholder(dtypes.float32)\n s, u, v = linalg_ops.svd(m)\n ss = math_ops.reduce_sum(s)\n uu = math_ops.reduce_sum(u)\n vv = math_ops.reduce_sum(v)\n result = ss + uu + vv\n f = graph_to_function_def.graph_to_function_def(\n g,\n g.get_operations()[1:], # skip the placeholder\n [s, u, v],\n [result])\n self.assertEqual(len(f.signature.input_arg), 3)\n\n def testGradientWithIntegerFunctionArgument(self):\n\n @function.Defun(dtypes.int32, dtypes.float32)\n def Foo(t, x):\n return x[t]\n\n g = ops.Graph()\n with g.as_default():\n inp = array_ops.placeholder(dtypes.float32)\n t = constant_op.constant(0, dtypes.int32)\n out = Foo(t, inp)\n dinp, = gradients_impl.gradients(out, [inp])\n\n x = np.zeros((2,)).astype(np.float32)\n with session.Session(graph=g) as sess:\n self.assertAllClose(\n np.array([1.0, 0.0]).astype(np.float32), sess.run(dinp, {inp: x}))\n\n def testFunctionMarkedStateful(self):\n\n @function.Defun(dtypes.int32, dtypes.float32)\n def Foo(t, x):\n return x[t]\n\n @function.Defun(dtypes.int64)\n def Bar(x):\n return x\n\n # NOTE(mrry): All functions are currently considered stateless by the\n # runtime, so we simulate a \"stateful\" function.\n # TODO(b/70565970): Remove this hack when we are able to build stateful\n # functions using the API.\n # pylint: disable=protected-access\n Foo._signature.is_stateful = True\n Bar._signature.is_stateful = True\n # pylint: enable=protected-access\n\n result_1 = Foo(3, [1.0, 2.0, 3.0, 4.0])\n result_2 = Bar(constant_op.constant(100, dtype=dtypes.int64))\n\n with session.Session() as sess:\n self.assertEqual(4.0, sess.run(result_1))\n self.assertEqual(100, sess.run(result_2))\n self.assertEqual((4.0, 100), sess.run((result_1, result_2)))\n\n def testStatefulFunction(self):\n\n @function.Defun()\n def FunctionWithStatelessOp():\n return constant_op.constant(42.0)\n\n @function.Defun()\n def FunctionWithStatefulOp():\n return random_ops.random_uniform([100], maxval=10, dtype=dtypes.int32)\n\n @function.Defun()\n def FunctionWithStatelessFunctionCall():\n return FunctionWithStatelessOp()\n\n @function.Defun()\n def FunctionWithStatefulFunctionCall():\n return FunctionWithStatefulOp()\n\n # Test that the `is_stateful` bit is propagated.\n self.assertFalse(FunctionWithStatelessOp.definition.signature.is_stateful)\n self.assertTrue(FunctionWithStatefulOp.definition.signature.is_stateful)\n self.assertFalse(\n FunctionWithStatelessFunctionCall.definition.signature.is_stateful)\n self.assertTrue(\n FunctionWithStatefulFunctionCall.definition.signature.is_stateful)\n\n # Ensure that two invocations of the same random-number-generating\n # function produce different results.\n result1 = FunctionWithStatefulFunctionCall()\n result2 = FunctionWithStatefulFunctionCall()\n\n # Statefulness affects how the function is treated by the various\n # optimization passes, so run the test in each optimizer\n # configuration.\n for config in _OptimizerOptions():\n with session.Session(config=config) as sess:\n val1, val2 = sess.run((result1, result2))\n self.assertFalse(all(val1 == val2))\n val3, val4 = sess.run((result1, result2))\n self.assertFalse(all(val3 == val1))\n self.assertFalse(all(val4 == val2))\n\n def testSameFunctionOnTwoDevices(self):\n\n @function.Defun(dtypes.float32)\n def AddOne(x):\n return x + 1.0\n\n with ops.device(\"/cpu:0\"):\n f_0 = AddOne(41.0)\n\n with ops.device(\"/cpu:1\"):\n f_1 = AddOne(43.0)\n\n for config in _OptimizerOptions():\n config.device_count[\"CPU\"] = 2\n with session.Session(config=config) as sess:\n self.assertEqual(42.0, sess.run(f_0))\n self.assertEqual(44.0, sess.run(f_1))\n self.assertEqual((42.0, 44.0), sess.run((f_0, f_1)))\n\n def testGuaranteedConstsAreCaptured(self):\n var = variables.Variable(1.0)\n const = array_ops.guarantee_const(var)\n also_const = array_ops.identity(const)\n still_const = array_ops.identity(also_const)\n not_const = still_const + var\n also_not_const = array_ops.placeholder(dtypes.float32)\n\n @function.Defun()\n def CapturesGuaranteedConst():\n output = const + also_const + still_const + not_const + also_not_const\n first, second, third, fourth, fifth = function.get_extra_args()\n self.assertEqual(\"GuaranteeConst\", first.consumers()[0].node_def.op)\n self.assertEqual(\"GuaranteeConst\", second.consumers()[0].node_def.op)\n self.assertEqual(\"GuaranteeConst\", third.consumers()[0].node_def.op)\n self.assertNotEqual(\"GuaranteeConst\", fourth.consumers()[0].node_def.op)\n self.assertNotEqual(\"GuaranteeConst\", fifth.consumers()[0].node_def.op)\n return output\n\n with self.test_session(use_gpu=False) as sess:\n sess.run(var.initializer)\n _ = sess.run(CapturesGuaranteedConst(), {also_not_const: 1.0})\n\n def testSameFunctionDifferentGrads(self):\n\n def PartOne(x):\n\n # Default grad is dx = dy * 2\n @function.Defun(dtypes.float32)\n def Foo(x):\n return x * 2\n\n return Foo(x)\n\n def PartTwo(x):\n\n @function.Defun(dtypes.float32, dtypes.float32)\n def Bar(x, dy):\n return x + dy # crazy backprop\n\n @function.Defun(dtypes.float32, grad_func=Bar)\n def Foo(x):\n return x * 2\n\n return Foo(x)\n\n def PartThree(x):\n\n def Bar(op, dy):\n return op.inputs[0] * dy / 2 # crazy backprop\n\n @function.Defun(dtypes.float32, python_grad_func=Bar)\n def Foo(x):\n return x * 2\n\n return Foo(x)\n\n g = ops.Graph()\n with g.as_default():\n x = constant_op.constant(100.)\n x0 = x\n y0 = PartOne(x0)\n dx0, = gradients_impl.gradients(ys=[y0], xs=[x0])\n x1 = x\n y1 = PartTwo(x1)\n dx1, = gradients_impl.gradients(ys=[y1], xs=[x1])\n x2 = x\n y2 = PartThree(x2)\n dx2, = gradients_impl.gradients(ys=[y2], xs=[x2])\n\n with self.session(graph=g) as sess:\n v0, v1, v2 = sess.run([dx0, dx1, dx2])\n\n self.assertAllEqual(v0, 2.)\n self.assertAllEqual(v1, 101.)\n self.assertAllEqual(v2, 50.)\n\n\n@test_util.with_c_shapes\nclass FunctionsFromProtos(test.TestCase):\n\n def expectFunctionsEqual(self, func, grad_func=None, new_func=None):\n if new_func is None:\n # Make a copy of func.definition to avoid any bugs masked by using the\n # same object\n serialized_fdef = func.definition.SerializeToString()\n # Serialize and then deserialize `func` to create `new_func`\n fdef = function_pb2.FunctionDef.FromString(serialized_fdef)\n new_func = function._from_definition(fdef, grad_func=grad_func)\n self.assertEqual(func.name, new_func.name)\n self.assertEqual(func.definition, new_func.definition)\n self.assertEqual(func.grad_func_name, new_func.grad_func_name)\n self.assertEqual(func.declared_input_types, new_func.declared_input_types)\n self.assertEqual(func.captured_inputs, new_func.captured_inputs)\n\n def testBasic(self):\n\n @function.Defun(dtypes.float32, dtypes.float32)\n def Foo(x, y):\n return x + y\n\n self.expectFunctionsEqual(Foo)\n\n def testGradFunc(self):\n\n @function.Defun(dtypes.float32, dtypes.float32)\n def G(x, dy):\n return x * dy\n\n @function.Defun(dtypes.float32, grad_func=G)\n def F(x):\n return math_ops.exp(x) - math_ops.exp(-x)\n\n self.expectFunctionsEqual(F, grad_func=G)\n\n def testCapturedInputs(self):\n c = constant_op.constant(10, dtypes.int64)\n\n @function.Defun(dtypes.int64)\n def Foo(x):\n return x + c\n\n new_func = function._from_definition(Foo.definition)\n\n self.assertEqual(Foo.name, new_func.name)\n self.assertEqual(Foo.definition, new_func.definition)\n self.assertEqual(Foo.grad_func_name, new_func.grad_func_name)\n\n # Captured inputs are added as regular inputs to the function definition\n self.assertEqual(new_func.declared_input_types,\n Foo.declared_input_types + (dtypes.int64,))\n self.assertEqual(len(new_func.captured_inputs), 0)\n\n def testNestedFunctions(self):\n\n @function.Defun(dtypes.float32)\n def Outer(x):\n\n @function.Defun(dtypes.float32)\n def Inner(y):\n return y + 1\n\n return Inner(Inner(x))\n\n self.expectFunctionsEqual(Outer)\n\n def testFromLibrary(self):\n # Define some functions with different gradient functions. Note that many of\n # the below functions are identical since function bodies don't matter for\n # this test.\n\n @function.Defun(dtypes.float32, dtypes.float32)\n def G1(x, dy):\n return x * dy\n\n @function.Defun(dtypes.float32, dtypes.float32)\n def G2(x, dy):\n return x * dy\n\n # F1 and F2 have the same gradient function\n @function.Defun(dtypes.float32, grad_func=G1)\n def F1(x):\n return math_ops.exp(x) - math_ops.exp(-x)\n\n @function.Defun(dtypes.float32, grad_func=G1)\n def F2(x):\n return math_ops.exp(x) - math_ops.exp(-x)\n\n # F3 has a different gradient function\n @function.Defun(dtypes.float32, grad_func=G2)\n def F3(x):\n return math_ops.exp(x) - math_ops.exp(-x)\n\n # F4 has no gradient function\n @function.Defun(dtypes.float32)\n def F4(x):\n return math_ops.exp(x) - math_ops.exp(-x)\n\n # Instantiate all functions\n g = ops.Graph()\n with g.as_default():\n c = constant_op.constant(1.0, dtypes.float32)\n f1 = F1(c)\n f2 = F2(c)\n f3 = F3(c)\n f4 = F4(c)\n gradients_impl.gradients([f1, f2, f3, f4], c)\n\n library = g.as_graph_def().library\n new_funcs = function._from_library(library)\n\n def CheckNewFunc(func):\n new_func = [f for f in new_funcs if f.name == func.name]\n self.assertEqual(len(new_func), 1)\n self.expectFunctionsEqual(func, new_func=new_func[0])\n\n CheckNewFunc(G1)\n CheckNewFunc(G2)\n CheckNewFunc(F1)\n CheckNewFunc(F2)\n CheckNewFunc(F3)\n CheckNewFunc(F4)\n\n def testFromLibraryEmptyLib(self):\n library = function_pb2.FunctionDefLibrary()\n self.assertEqual(len(function._from_library(library)), 0)\n\n def testFromLibraryMissingFuncDef(self):\n\n @function.Defun(dtypes.float32, dtypes.float32)\n def G1(x, dy):\n return x * dy\n\n @function.Defun(dtypes.float32)\n def F1(x):\n return math_ops.exp(x) - math_ops.exp(-x)\n\n gradient = function_pb2.GradientDef()\n gradient.function_name = F1.name\n gradient.gradient_func = G1.name\n\n # Create invalid function def that is missing G1 function def\n library = function_pb2.FunctionDefLibrary()\n library.gradient.extend([gradient])\n library.function.extend([F1.definition])\n\n with self.assertRaisesRegexp(\n ValueError,\n \"FunctionDefLibrary missing 'G1_[0-9a-zA-Z]{8,11}' FunctionDef\"):\n function._from_library(library)\n\n # Create invalid function def that is missing F1 function def\n library = function_pb2.FunctionDefLibrary()\n library.gradient.extend([gradient])\n library.function.extend([G1.definition])\n\n with self.assertRaisesRegexp(\n ValueError,\n \"FunctionDefLibrary missing 'F1_[0-9a-zA-Z]{8,11}' FunctionDef\"):\n function._from_library(library)\n\n def testFromLibraryCyclicGradFuncs(self):\n\n @function.Defun(dtypes.float32)\n def F1(x):\n return math_ops.exp(x) - math_ops.exp(-x)\n\n @function.Defun(dtypes.float32)\n def F2(x):\n return math_ops.exp(x) - math_ops.exp(-x)\n\n # Create invalid function def library where F1 has gradient function F2 and\n # F2 has gradient function F1\n library = function_pb2.FunctionDefLibrary()\n library.function.extend([F1.definition, F2.definition])\n\n gradient1 = function_pb2.GradientDef()\n gradient1.function_name = F1.name\n gradient1.gradient_func = F2.name\n\n gradient2 = function_pb2.GradientDef()\n gradient2.function_name = F2.name\n gradient2.gradient_func = F1.name\n\n library.gradient.extend([gradient1, gradient2])\n\n with self.assertRaisesRegexp(\n ValueError, \"FunctionDefLibrary contains cyclic gradient functions!\"):\n function._from_library(library)\n\n def testExperimentalAttrs(self):\n\n @function.Defun(dtypes.int32, experimental_tag=\"tag_value\")\n def FunctionWithStrAttr(i):\n return array_ops.identity(i)\n\n @function.Defun(dtypes.int32, experimental_tag=123)\n def FunctionWithIntAttr(i):\n return array_ops.identity(i)\n\n @function.Defun(dtypes.int32, experimental_tag=123.0)\n def FunctionWithFloatAttr(i):\n return array_ops.identity(i)\n\n @function.Defun(dtypes.int32, experimental_tag=True)\n def FunctionWithBoolAttr(i):\n return array_ops.identity(i)\n\n self.assertTrue(\"experimental_tag\" in FunctionWithStrAttr.definition.attr)\n self.assertEqual(FunctionWithStrAttr.definition.attr[\"experimental_tag\"].s,\n b\"tag_value\")\n self.assertTrue(\"experimental_tag\" in FunctionWithIntAttr.definition.attr)\n self.assertEqual(FunctionWithIntAttr.definition.attr[\"experimental_tag\"].i,\n 123)\n self.assertTrue(\"experimental_tag\" in FunctionWithFloatAttr.definition.attr)\n self.assertEqual(\n FunctionWithFloatAttr.definition.attr[\"experimental_tag\"].f, 123.0)\n self.assertTrue(\"experimental_tag\" in FunctionWithBoolAttr.definition.attr)\n self.assertEqual(FunctionWithBoolAttr.definition.attr[\"experimental_tag\"].b,\n True)\n\n\n@test_util.with_c_shapes\nclass FunctionOverloadTest(test.TestCase):\n\n def testBasic(self):\n\n @function.Defun()\n def Sinh(x):\n return 1 / 2. * (math_ops.exp(x) - math_ops.exp(-x))\n\n g = ops.Graph()\n with g.as_default():\n x = Sinh(constant_op.constant(0.25, dtypes.float32))\n y = Sinh(constant_op.constant(0.25, dtypes.float64))\n\n with self.session(graph=g):\n self.assertAllClose(x.eval(), np.sinh(0.25))\n self.assertAllClose(y.eval(), np.sinh(0.25))\n\n def testGradient(self):\n\n @function.Defun(func_name=\"Spec\")\n def G(x, dy):\n return x * dy\n\n @function.Defun(grad_func=G)\n def F(x):\n return math_ops.exp(x) - math_ops.exp(-x)\n\n for dtype in [dtypes.float32, dtypes.float64]:\n g = ops.Graph()\n with g.as_default():\n x = constant_op.constant(0.25, dtype)\n y = F(x)\n dx, = gradients_impl.gradients(y, x)\n\n with self.session(graph=g):\n self.assertAllClose(dx.eval(), 0.25)\n\n def testDocString(self):\n\n @function.Defun()\n def Foo(x):\n \"\"\"Successor of x.\"\"\"\n return x + 1\n\n g = ops.Graph()\n with g.as_default():\n _ = Foo(1)\n\n self.assertEqual(g.as_graph_def().library.function[0].signature.description,\n \"Successor of x.\")\n\n\n@test_util.with_c_shapes\nclass FunctionCaptureByValueTest(test.TestCase):\n\n def testCaptureByValue(self):\n g = ops.Graph()\n with g.as_default():\n w = constant_op.constant([[1.0]])\n b = constant_op.constant([2.0])\n\n # Foo() captures w and b.\n @function.Defun(dtypes.float32, capture_by_value=True)\n def Foo(x):\n\n # Plus() captures b.\n @function.Defun(dtypes.float32, capture_by_value=True)\n def Plus(y):\n return y + b\n\n self.assertEqual(0, len(Plus.captured_inputs))\n\n return Plus(math_ops.matmul(w, x))\n\n y = Foo(constant_op.constant([[10.]]))\n\n self.assertEqual(0, len(Foo.captured_inputs))\n\n with self.session(graph=g):\n self.assertAllEqual(y.eval(), [[12.0]])\n\n\n@test_util.with_c_shapes\nclass UnrollLSTMTest(test.TestCase):\n BATCH_SIZE = 16\n LSTM_DIMS = 32\n NUM_UNROLL = 20\n\n def _Weights(self):\n dims = self.LSTM_DIMS\n return random_ops.random_uniform([2 * dims, 4 * dims], -1, 1, seed=123456)\n\n def _Input(self):\n return random_ops.random_uniform(\n [self.NUM_UNROLL, self.BATCH_SIZE, self.LSTM_DIMS], seed=654321)\n\n # Helper to construct a LSTM cell graph.\n @classmethod\n def LSTMCell(cls, x, mprev, cprev, weights):\n xm = array_ops.concat([x, mprev], 1)\n i_i, i_g, f_g, o_g = array_ops.split(\n value=math_ops.matmul(xm, weights), num_or_size_splits=4, axis=1)\n new_c = math_ops.sigmoid(f_g) * cprev + math_ops.sigmoid(\n i_g) * math_ops.tanh(i_i)\n new_c = math_ops.maximum(math_ops.minimum(new_c, 50.0), -50.0)\n new_m = math_ops.sigmoid(o_g) * math_ops.tanh(new_c)\n return new_m, new_c\n\n def _BuildForward(self, weights, inp, mode=\"cell\"):\n\n def Loop(cell, w, i):\n x = array_ops.unstack(i, self.NUM_UNROLL)\n m = array_ops.zeros_like(x[0])\n c = array_ops.zeros_like(x[0])\n for i in range(self.NUM_UNROLL):\n m, c = cell(x[i], m, c, w)\n return m\n\n cell = UnrollLSTMTest.LSTMCell\n if mode == \"complete\":\n # Constructs the complete graph in python.\n return Loop(cell, weights, inp)\n\n cell = function.Defun(dtypes.float32, dtypes.float32, dtypes.float32,\n dtypes.float32)(\n cell)\n if mode == \"cell\":\n # Just represent the LSTM as a function.\n return Loop(cell, weights, inp)\n\n if mode == \"loop\":\n # Wraps the whole loop as a function.\n @function.Defun(dtypes.float32, dtypes.float32)\n def LSTMLoop(w, i):\n return Loop(cell, w, i)\n\n return LSTMLoop(weights, inp)\n\n if mode == \"loop10\":\n # Wraps 10 lstm steps into one function, and the whole loop\n # into another calling the formers.\n\n # Groups 10 steps at a time.\n @function.Defun(dtypes.float32, dtypes.float32, dtypes.float32,\n *([dtypes.float32] * 10))\n def Loop10(w, m, c, *args):\n for x in args:\n m, c = cell(x, m, c, w)\n return m, c\n\n @function.Defun(dtypes.float32, dtypes.float32)\n def LSTMLoop10(weights, inp):\n x = array_ops.unstack(inp, self.NUM_UNROLL)\n m = array_ops.zeros_like(x[0])\n c = array_ops.zeros_like(x[0])\n assert self.NUM_UNROLL % 10 == 0\n for i in range(0, self.NUM_UNROLL, 10):\n m, c = Loop10(weights, m, c, *x[i:i + 10])\n return m\n\n return LSTMLoop10(weights, inp)\n\n def testUnrollLSTM(self):\n # Run one step of the unrolled lstm graph.\n def RunForward(mode, cfg=None):\n tf_logging.info(\"mode = %s\", mode)\n g = ops.Graph()\n start = time.time()\n with g.as_default():\n weights = self._Weights()\n inp = self._Input()\n m = self._BuildForward(weights, inp, mode)\n gdef = g.as_graph_def()\n finish = time.time()\n tf_logging.info(\"time: %f txt size: %d gdef bin size: %d\", finish - start,\n len(str(gdef)), len(gdef.SerializeToString()))\n with g.as_default(), session.Session(config=cfg) as sess:\n return sess.run(m)\n\n mv0 = RunForward(\"complete\")\n for cfg in _OptimizerOptions():\n tf_logging.info(\"cfg = %s\", cfg)\n mv1 = RunForward(\"cell\", cfg)\n mv2 = RunForward(\"loop\", cfg)\n mv3 = RunForward(\"loop10\", cfg)\n self.assertAllClose(mv0, mv1, rtol=1e-4)\n self.assertAllClose(mv0, mv2, rtol=1e-4)\n self.assertAllClose(mv0, mv3, rtol=1e-4)\n\n def testUnrollLSTMGrad(self):\n # Run one step of the unrolled lstm graph.\n def RunForwardBackward(mode, cfg=None):\n tf_logging.info(\"mode = %s\", mode)\n g = ops.Graph()\n start = time.time()\n with g.as_default():\n weights = self._Weights()\n inp = self._Input()\n m = self._BuildForward(weights, inp, mode)\n loss = math_ops.reduce_sum(math_ops.square(m))\n dw = gradients_impl.gradients([loss], [weights])\n gdef = g.as_graph_def()\n finish = time.time()\n tf_logging.info(\"time: %f txt size: %d gdef bin size: %d\", finish - start,\n len(str(gdef)), len(gdef.SerializeToString()))\n with g.as_default(), session.Session(config=cfg) as sess:\n return sess.run(dw)\n\n d0 = RunForwardBackward(\"complete\")\n for cfg in _OptimizerOptions():\n tf_logging.info(\"cfg = %s\", cfg)\n d1 = RunForwardBackward(\"cell\", cfg)\n d2 = RunForwardBackward(\"loop\", cfg)\n d3 = RunForwardBackward(\"loop10\", cfg)\n self.assertAllClose(d0, d1, rtol=1e-4, atol=1e-4)\n self.assertAllClose(d0, d2, rtol=1e-4, atol=1e-4)\n self.assertAllClose(d0, d3, rtol=1e-4, atol=1e-4)\n\n\n@test_util.with_c_shapes\nclass FunctionInlineControlTest(test.TestCase):\n\n def testFoo(self):\n dtype = dtypes.float32\n cfg = config_pb2.ConfigProto(\n graph_options=config_pb2.GraphOptions(\n optimizer_options=config_pb2.OptimizerOptions(\n opt_level=config_pb2.OptimizerOptions.L0,\n do_common_subexpression_elimination=True,\n do_function_inlining=True,\n do_constant_folding=True)))\n cell_func_call_pattern = re.compile(r\"Cell[^/]*\\(\")\n for noinline in [False, True]:\n\n @function.Defun(dtype, noinline=noinline)\n def Cell(v):\n # If v is a vector [n, 1], x is a big square matrix.\n x = math_ops.tanh(v + array_ops.transpose(v, [1, 0]))\n return math_ops.reduce_sum(x, 1, keepdims=True)\n\n @function.Defun(dtype)\n def Forward(x):\n for _ in range(10):\n # pylint: disable=cell-var-from-loop\n x = Cell(x)\n return math_ops.reduce_sum(x, [0, 1])\n\n self.assertEqual(noinline, Cell.definition.attr[\"_noinline\"].b)\n\n g = ops.Graph()\n with g.as_default():\n x = array_ops.placeholder(dtype)\n y = Forward(x)\n dx, = gradients_impl.gradients([y], [x])\n\n np.random.seed(321)\n inp = np.random.uniform(-1, 1, [16, 1]).astype(np.float32)\n run_metadata = config_pb2.RunMetadata()\n with session.Session(graph=g, config=cfg) as sess:\n ans = sess.run(\n [y, dx], {x: inp},\n run_metadata=run_metadata,\n options=config_pb2.RunOptions(\n trace_level=config_pb2.RunOptions.FULL_TRACE))\n print(ans[0], np.sum(ans[1]))\n self.assertAllClose(ans[0], 255.971, rtol=1e-3)\n self.assertAllClose(np.sum(ans[1]), 13.0408, rtol=1e-3)\n\n def MetadataHasCell(run_metadata):\n for dev_stats in run_metadata.step_stats.dev_stats:\n for node_stats in dev_stats.node_stats:\n if cell_func_call_pattern.search(node_stats.timeline_label):\n return True\n return False\n\n self.assertEqual(MetadataHasCell(run_metadata), noinline)\n\n\[email protected](*[dtypes.float32] * 3)\ndef Linear(w, b, x):\n return nn_ops.relu(math_ops.matmul(x, w) + b)\n\n\[email protected](*[dtypes.float32] * 5)\ndef Linear2(w1, b1, w2, b2, x):\n return Linear(w2, b2, Linear(w1, b1, x))\n\n\[email protected](*[dtypes.float32] * 3)\ndef LinearWithCApi(w, b, x):\n return nn_ops.relu(math_ops.matmul(x, w) + b)\n\n\[email protected](*[dtypes.float32] * 5)\ndef Linear2WithCApi(w1, b1, w2, b2, x):\n return LinearWithCApi(w2, b2, LinearWithCApi(w1, b1, x))\n\n\nclass ModuleFunctionTest(test.TestCase):\n\n def testBasic(self):\n with ops.Graph().as_default():\n a, b, c, d, e = [\n constant_op.constant([[_]], dtype=dtypes.float32) for _ in range(5)\n ]\n y = LinearWithCApi(a, b, c)\n z = Linear2WithCApi(a, b, c, d, e)\n with session.Session() as sess:\n self.assertAllEqual([[1]], sess.run(y))\n self.assertAllEqual([[5]], sess.run(z))\n\n\n@test_util.with_c_shapes\nclass VariableHoistingTest(test.TestCase):\n\n def _testSimpleModel(self, use_forward_func, use_resource=False):\n\n def _Model(x):\n w = variable_scope.get_variable(\n \"w\", (64, 64),\n initializer=init_ops.random_uniform_initializer(seed=312),\n use_resource=use_resource)\n b = variable_scope.get_variable(\n \"b\", (64),\n initializer=init_ops.zeros_initializer(),\n use_resource=use_resource),\n return math_ops.sigmoid(math_ops.matmul(x, w) + b)\n\n @function.Defun()\n def Model(x):\n return _Model(x)\n\n cvars = []\n\n @function.Defun()\n def Grad(x, y0):\n if use_forward_func:\n y = Model(x)\n else:\n y = _Model(x)\n loss = math_ops.reduce_mean(\n math_ops.reduce_sum(y0 * math_ops.log(y), 1), 0)\n arg_w, arg_b = function.get_extra_args()\n self.assertEqual(arg_w.get_shape(), tensor_shape.TensorShape([64, 64]))\n self.assertEqual(arg_b.get_shape(), tensor_shape.TensorShape([64]))\n dw, db = gradients_impl.gradients(loss, [arg_w, arg_b])\n cvars.extend(function.get_extra_vars())\n return loss, dw, db\n\n g = ops.Graph()\n with g.as_default():\n x = random_ops.random_normal([64, 64], seed=100)\n y0 = random_ops.random_normal([64, 64], seed=200)\n with variable_scope.variable_scope(\"Foo\"):\n loss, dw, db = Grad(x, y0)\n\n self.assertEqual(2, len(cvars))\n w, b = cvars[:2]\n self.assertEqual(\"Foo/w\", w.op.name)\n self.assertEqual(\"Foo/b\", b.op.name)\n\n with self.session(graph=g) as sess:\n sess.run(variables.global_variables_initializer())\n w, b, x, y0, loss, dw, db = sess.run([w, b, x, y0, loss, dw, db])\n\n self.assertAllEqual(w.shape, (64, 64))\n self.assertAllClose(np.sum(w), 2050.44)\n self.assertAllEqual(b.shape, (64,))\n self.assertAllClose(np.sum(b), 0.0)\n self.assertAllClose(loss, -2.27, rtol=1e-2)\n self.assertAllEqual(dw.shape, (64, 64))\n self.assertAllClose(np.sum(dw), -1.04, rtol=1e-2)\n self.assertAllEqual(db.shape, (64,))\n self.assertAllClose(np.sum(db), 0.509, rtol=1e-2)\n\n def testBasic(self):\n self._testSimpleModel(True)\n self._testSimpleModel(False)\n\n def testBasicResource(self):\n self._testSimpleModel(True, use_resource=True)\n self._testSimpleModel(False, use_resource=True)\n\n\nclass DevicePlacementTest(test.TestCase):\n\n def testNoDeviceGraph(self):\n with ops.Graph().as_default():\n\n @function.Defun(*[dtypes.float32] * 2)\n def Matmul(a, b):\n return math_ops.matmul(a, b)\n\n Matmul(1., 2.)\n\n gdef = ops.get_default_graph().as_graph_def()\n self.assertAllEqual(len(gdef.library.function), 1)\n fdef = gdef.library.function[0]\n\n for node in fdef.node_def:\n self.assertAllEqual(node.device, \"\")\n\n def testNestedDevices(self):\n with ops.Graph().as_default(), ops.device(\"CPU:0\"):\n\n @function.Defun(*[dtypes.float32] * 2)\n def Matmul(a, b):\n return math_ops.matmul(a, b)\n\n with ops.device(\"CPU:1\"):\n\n @function.Defun(*[dtypes.float32] * 2)\n def Divide(a, b):\n return math_ops.divide(a, b)\n\n Divide(Matmul(1., 2.), 3.)\n\n gdef = ops.get_default_graph().as_graph_def()\n matmul_fdef = [\n f for f in gdef.library.function if \"Matmul\" in f.signature.name\n ]\n divide_fdef = [\n f for f in gdef.library.function if \"Divide\" in f.signature.name\n ]\n self.assertAllEqual(len(matmul_fdef), 1)\n self.assertAllEqual(len(divide_fdef), 1)\n for node in matmul_fdef[0].node_def:\n self.assertAllEqual(node.device, \"/device:CPU:0\")\n for node in divide_fdef[0].node_def:\n self.assertAllEqual(node.device, \"/device:CPU:1\")\n\n def _testNestedDeviceWithSameFunction(self, func_name):\n\n def MatmulWrap(a, b):\n\n @function.Defun(\n func_name=func_name, *[dtypes.int32] * 2)\n def Matmul(a, b):\n return math_ops.matmul(a, b)\n\n return Matmul(a, b)\n\n with ops.Graph().as_default(), ops.device(\"CPU:0\"):\n c = MatmulWrap(1, 2)\n\n with ops.device(\"CPU:1\"):\n MatmulWrap(c, 3)\n\n gdef = ops.get_default_graph().as_graph_def()\n\n devices = []\n for node in gdef.library.function[0].node_def:\n devices.append(node.device)\n for node in gdef.library.function[1].node_def:\n devices.append(node.device)\n\n self.assertAllEqual(sorted(devices), [\"/device:CPU:0\", \"/device:CPU:1\"])\n\n def testFunctionWithName(self):\n with self.assertRaises(InvalidArgumentError) as cm:\n self._testNestedDeviceWithSameFunction(\"MatmulTest\")\n self.assertEqual(\n cm.exception.message,\n \"Cannot add function \\'MatmulTest\\' because a different \"\n \"function with the same name already exists.\")\n\n def testFunctionWithoutName(self):\n self._testNestedDeviceWithSameFunction(None)\n\n\nif __name__ == \"__main__\":\n test.main()\n"
] | [
[
"tensorflow.python.ops.math_ops.log",
"tensorflow.core.protobuf.config_pb2.RunMetadata",
"tensorflow.python.framework.tensor_shape.TensorShape",
"tensorflow.core.framework.function_pb2.GradientDef",
"tensorflow.python.ops.array_ops.shape",
"numpy.linspace",
"tensorflow.python.ops.logging_ops.Print",
"tensorflow.python.ops.control_flow_ops.while_loop",
"tensorflow.python.ops.math_ops.rsqrt",
"tensorflow.python.ops.math_ops.greater",
"tensorflow.python.ops.math_ops.exp",
"tensorflow.python.ops.array_ops.placeholder",
"tensorflow.python.ops.variables.Variable",
"tensorflow.core.framework.function_pb2.FunctionDef.FromString",
"tensorflow.python.ops.math_ops.tanh",
"tensorflow.python.ops.array_ops.zeros",
"tensorflow.python.framework.function.get_extra_vars",
"tensorflow.python.ops.init_ops.random_uniform_initializer",
"tensorflow.python.framework.ops.device",
"tensorflow.python.ops.nn_ops.softmax",
"tensorflow.python.ops.control_flow_ops.no_op",
"tensorflow.python.ops.array_ops.identity",
"tensorflow.python.ops.gradients_impl.gradients",
"numpy.exp",
"tensorflow.python.ops.control_flow_ops.Assert",
"tensorflow.python.framework.function._from_library",
"tensorflow.python.ops.control_flow_ops.cond",
"tensorflow.python.ops.array_ops.transpose",
"tensorflow.python.ops.math_ops.divide",
"tensorflow.python.framework.function.Defun",
"tensorflow.python.ops.array_ops.unstack",
"tensorflow.python.ops.init_ops.ones_initializer",
"tensorflow.python.platform.test.main",
"tensorflow.python.ops.variable_scope.variable_scope",
"tensorflow.python.ops.math_ops.matmul",
"tensorflow.python.framework.ops.control_dependencies",
"numpy.zeros",
"tensorflow.python.ops.linalg_ops.svd",
"tensorflow.python.ops.math_ops.cast",
"tensorflow.python.framework.function.get_extra_args",
"tensorflow.python.ops.math_ops.minimum",
"tensorflow.python.ops.variables.global_variables",
"tensorflow.python.ops.math_ops.square",
"tensorflow.core.framework.function_pb2.FunctionDefLibrary",
"tensorflow.python.ops.array_ops.zeros_like",
"tensorflow.python.ops.math_ops.reduce_mean",
"tensorflow.python.client.session.Session",
"numpy.random.rand",
"numpy.array",
"numpy.tanh",
"tensorflow.python.ops.functional_ops.symbolic_gradient",
"tensorflow.python.ops.array_ops.stack",
"numpy.sum",
"tensorflow.core.protobuf.rewriter_config_pb2.RewriterConfig",
"tensorflow.python.ops.math_ops.sigmoid",
"tensorflow.python.ops.array_ops.concat",
"numpy.random.seed",
"tensorflow.python.ops.math_ops.less_equal",
"tensorflow.python.framework.ops.Graph",
"tensorflow.core.protobuf.config_pb2.RunOptions",
"tensorflow.python.ops.variable_scope.get_variable",
"tensorflow.python.platform.tf_logging.info",
"numpy.sinh",
"tensorflow.python.framework.function._from_definition",
"tensorflow.python.framework.ops.get_default_graph",
"tensorflow.python.ops.array_ops.reshape",
"tensorflow.python.framework.ops.name_scope",
"tensorflow.python.ops.init_ops.zeros_initializer",
"tensorflow.core.protobuf.config_pb2.OptimizerOptions",
"tensorflow.python.ops.random_ops.random_normal",
"numpy.random.uniform",
"tensorflow.python.ops.variables.global_variables_initializer",
"tensorflow.python.ops.array_ops.guarantee_const",
"tensorflow.python.ops.random_ops.random_uniform",
"tensorflow.python.ops.math_ops.reduce_sum",
"tensorflow.python.framework.constant_op.constant"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"1.12",
"2.6",
"2.2",
"1.13",
"2.3",
"2.4",
"2.9",
"1.5",
"1.7",
"2.5",
"2.8",
"2.10"
]
}
] |
kmakeev/RLs | [
"c47e9b504db157731c26d7c881719a4fb54cc355"
] | [
"mlagents/trainers/tests/test_ghost.py"
] | [
"import pytest\n\nimport numpy as np\n\nimport yaml\n\nfrom mlagents.trainers.ghost.trainer import GhostTrainer\nfrom mlagents.trainers.ghost.controller import GhostController\nfrom mlagents.trainers.behavior_id_utils import BehaviorIdentifiers\nfrom mlagents.trainers.ppo.trainer import PPOTrainer\nfrom mlagents.trainers.brain import BrainParameters\nfrom mlagents.trainers.agent_processor import AgentManagerQueue\nfrom mlagents.trainers.tests import mock_brain as mb\nfrom mlagents.trainers.tests.test_trajectory import make_fake_trajectory\n\n\[email protected]\ndef dummy_config():\n return yaml.safe_load(\n \"\"\"\n trainer: ppo\n batch_size: 32\n beta: 5.0e-3\n buffer_size: 512\n epsilon: 0.2\n hidden_units: 128\n lambd: 0.95\n learning_rate: 3.0e-4\n max_steps: 5.0e4\n normalize: true\n num_epoch: 5\n num_layers: 2\n time_horizon: 64\n sequence_length: 64\n summary_freq: 1000\n use_recurrent: false\n normalize: true\n memory_size: 8\n curiosity_strength: 0.0\n curiosity_enc_size: 1\n summary_path: test\n model_path: test\n reward_signals:\n extrinsic:\n strength: 1.0\n gamma: 0.99\n self_play:\n window: 5\n play_against_current_self_ratio: 0.5\n save_steps: 1000\n swap_steps: 1000\n \"\"\"\n )\n\n\nVECTOR_ACTION_SPACE = [1]\nVECTOR_OBS_SPACE = 8\nDISCRETE_ACTION_SPACE = [3, 3, 3, 2]\nBUFFER_INIT_SAMPLES = 513\nNUM_AGENTS = 12\n\n\[email protected](\"use_discrete\", [True, False])\ndef test_load_and_set(dummy_config, use_discrete):\n mock_brain = mb.setup_mock_brain(\n use_discrete,\n False,\n vector_action_space=VECTOR_ACTION_SPACE,\n vector_obs_space=VECTOR_OBS_SPACE,\n discrete_action_space=DISCRETE_ACTION_SPACE,\n )\n\n trainer_params = dummy_config\n trainer = PPOTrainer(mock_brain.brain_name, 0, trainer_params, True, False, 0, \"0\")\n trainer.seed = 1\n policy = trainer.create_policy(mock_brain.brain_name, mock_brain)\n policy.create_tf_graph()\n trainer.seed = 20 # otherwise graphs are the same\n to_load_policy = trainer.create_policy(mock_brain.brain_name, mock_brain)\n to_load_policy.create_tf_graph()\n to_load_policy.init_load_weights()\n\n weights = policy.get_weights()\n load_weights = to_load_policy.get_weights()\n try:\n for w, lw in zip(weights, load_weights):\n np.testing.assert_array_equal(w, lw)\n except AssertionError:\n pass\n\n to_load_policy.load_weights(weights)\n load_weights = to_load_policy.get_weights()\n\n for w, lw in zip(weights, load_weights):\n np.testing.assert_array_equal(w, lw)\n\n\ndef test_process_trajectory(dummy_config):\n brain_params_team0 = BrainParameters(\n brain_name=\"test_brain?team=0\",\n vector_observation_space_size=1,\n camera_resolutions=[],\n vector_action_space_size=[2],\n vector_action_descriptions=[],\n vector_action_space_type=0,\n )\n\n brain_name = BehaviorIdentifiers.from_name_behavior_id(\n brain_params_team0.brain_name\n ).brain_name\n\n brain_params_team1 = BrainParameters(\n brain_name=\"test_brain?team=1\",\n vector_observation_space_size=1,\n camera_resolutions=[],\n vector_action_space_size=[2],\n vector_action_descriptions=[],\n vector_action_space_type=0,\n )\n dummy_config[\"summary_path\"] = \"./summaries/test_trainer_summary\"\n dummy_config[\"model_path\"] = \"./models/test_trainer_models/TestModel\"\n ppo_trainer = PPOTrainer(brain_name, 0, dummy_config, True, False, 0, \"0\")\n controller = GhostController(100)\n trainer = GhostTrainer(\n ppo_trainer, brain_name, controller, 0, dummy_config, True, \"0\"\n )\n\n # first policy encountered becomes policy trained by wrapped PPO\n parsed_behavior_id0 = BehaviorIdentifiers.from_name_behavior_id(\n brain_params_team0.brain_name\n )\n policy = trainer.create_policy(parsed_behavior_id0, brain_params_team0)\n trainer.add_policy(parsed_behavior_id0, policy)\n trajectory_queue0 = AgentManagerQueue(brain_params_team0.brain_name)\n trainer.subscribe_trajectory_queue(trajectory_queue0)\n\n # Ghost trainer should ignore this queue because off policy\n parsed_behavior_id1 = BehaviorIdentifiers.from_name_behavior_id(\n brain_params_team1.brain_name\n )\n policy = trainer.create_policy(parsed_behavior_id1, brain_params_team1)\n trainer.add_policy(parsed_behavior_id1, policy)\n trajectory_queue1 = AgentManagerQueue(brain_params_team1.brain_name)\n trainer.subscribe_trajectory_queue(trajectory_queue1)\n\n time_horizon = 15\n trajectory = make_fake_trajectory(\n length=time_horizon,\n max_step_complete=True,\n vec_obs_size=1,\n num_vis_obs=0,\n action_space=[2],\n )\n trajectory_queue0.put(trajectory)\n trainer.advance()\n\n # Check that trainer put trajectory in update buffer\n assert trainer.trainer.update_buffer.num_experiences == 15\n\n trajectory_queue1.put(trajectory)\n trainer.advance()\n\n # Check that ghost trainer ignored off policy queue\n assert trainer.trainer.update_buffer.num_experiences == 15\n # Check that it emptied the queue\n assert trajectory_queue1.empty()\n\n\ndef test_publish_queue(dummy_config):\n brain_params_team0 = BrainParameters(\n brain_name=\"test_brain?team=0\",\n vector_observation_space_size=8,\n camera_resolutions=[],\n vector_action_space_size=[1],\n vector_action_descriptions=[],\n vector_action_space_type=0,\n )\n\n parsed_behavior_id0 = BehaviorIdentifiers.from_name_behavior_id(\n brain_params_team0.brain_name\n )\n\n brain_name = parsed_behavior_id0.brain_name\n\n brain_params_team1 = BrainParameters(\n brain_name=\"test_brain?team=1\",\n vector_observation_space_size=8,\n camera_resolutions=[],\n vector_action_space_size=[1],\n vector_action_descriptions=[],\n vector_action_space_type=0,\n )\n dummy_config[\"summary_path\"] = \"./summaries/test_trainer_summary\"\n dummy_config[\"model_path\"] = \"./models/test_trainer_models/TestModel\"\n ppo_trainer = PPOTrainer(brain_name, 0, dummy_config, True, False, 0, \"0\")\n controller = GhostController(100)\n trainer = GhostTrainer(\n ppo_trainer, brain_name, controller, 0, dummy_config, True, \"0\"\n )\n\n # First policy encountered becomes policy trained by wrapped PPO\n # This queue should remain empty after swap snapshot\n policy = trainer.create_policy(parsed_behavior_id0, brain_params_team0)\n trainer.add_policy(parsed_behavior_id0, policy)\n policy_queue0 = AgentManagerQueue(brain_params_team0.brain_name)\n trainer.publish_policy_queue(policy_queue0)\n\n # Ghost trainer should use this queue for ghost policy swap\n parsed_behavior_id1 = BehaviorIdentifiers.from_name_behavior_id(\n brain_params_team1.brain_name\n )\n policy = trainer.create_policy(parsed_behavior_id1, brain_params_team1)\n trainer.add_policy(parsed_behavior_id1, policy)\n policy_queue1 = AgentManagerQueue(brain_params_team1.brain_name)\n trainer.publish_policy_queue(policy_queue1)\n\n # check ghost trainer swap pushes to ghost queue and not trainer\n assert policy_queue0.empty() and policy_queue1.empty()\n trainer._swap_snapshots()\n assert policy_queue0.empty() and not policy_queue1.empty()\n # clear\n policy_queue1.get_nowait()\n\n mock_brain = mb.setup_mock_brain(\n False,\n False,\n vector_action_space=VECTOR_ACTION_SPACE,\n vector_obs_space=VECTOR_OBS_SPACE,\n discrete_action_space=DISCRETE_ACTION_SPACE,\n )\n\n buffer = mb.simulate_rollout(BUFFER_INIT_SAMPLES, mock_brain)\n # Mock out reward signal eval\n buffer[\"extrinsic_rewards\"] = buffer[\"environment_rewards\"]\n buffer[\"extrinsic_returns\"] = buffer[\"environment_rewards\"]\n buffer[\"extrinsic_value_estimates\"] = buffer[\"environment_rewards\"]\n buffer[\"curiosity_rewards\"] = buffer[\"environment_rewards\"]\n buffer[\"curiosity_returns\"] = buffer[\"environment_rewards\"]\n buffer[\"curiosity_value_estimates\"] = buffer[\"environment_rewards\"]\n buffer[\"advantages\"] = buffer[\"environment_rewards\"]\n trainer.trainer.update_buffer = buffer\n\n # when ghost trainer advance and wrapped trainer buffers full\n # the wrapped trainer pushes updated policy to correct queue\n assert policy_queue0.empty() and policy_queue1.empty()\n trainer.advance()\n assert not policy_queue0.empty() and policy_queue1.empty()\n\n\nif __name__ == \"__main__\":\n pytest.main()\n"
] | [
[
"numpy.testing.assert_array_equal"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
abdolence/analytics-zoo | [
"364856abcbe9aff7f7b6cf9b9f8648d51e07ca64",
"364856abcbe9aff7f7b6cf9b9f8648d51e07ca64"
] | [
"pyzoo/zoo/util/tf_graph_util.py",
"pyzoo/zoo/examples/anomalydetection/anomaly_detection.py"
] | [
"# This file is adapted from https://github.com/tensorflow/tensorflow/blob/master\n# /tensorflow/python/framework/graph_util_impl.py\n#\n# Copyright 2015 The TensorFlow Authors, 2019 Analytics Zoo Authors.\n# 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\"\"\"Helpers to manipulate a tensor graph in python.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nimport copy\nimport re\nimport six\n\nfrom tensorflow.core.framework import attr_value_pb2\nfrom tensorflow.core.framework import graph_pb2\nfrom tensorflow.core.framework import node_def_pb2\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import tensor_util\nfrom tensorflow.python.platform import tf_logging as logging\nfrom tensorflow.python.util import deprecation\nfrom tensorflow.python.util.tf_export import tf_export\n\n_VARIABLE_OPS = {\n \"Assign\",\n \"AssignAdd\",\n \"AssignSub\",\n \"Queue\",\n \"ScatterAdd\",\n \"ScatterSub\",\n \"ScatterUpdate\",\n \"TruncatedNormal\",\n \"Variable\",\n \"VariableV2\",\n}\n\n\ndef _is_variable_op(op):\n \"\"\"Returns true if 'op' refers to a Variable node.\"\"\"\n return op in _VARIABLE_OPS\n\n\[email protected](\n date=None,\n instructions=\"Use `tf.compat.v1.graph_util.must_run_on_cpu`\")\n@tf_export(v1=[\"graph_util.must_run_on_cpu\"])\ndef must_run_on_cpu(node, pin_variables_on_cpu=False):\n \"\"\"Returns True if the given node_def must run on CPU, otherwise False.\n Args:\n node: The node to be assigned to a device. Could be either an ops.Operation\n or NodeDef.\n pin_variables_on_cpu: If True, this function will return False if node_def\n represents a variable-related op.\n Returns:\n True if the given node must run on CPU, otherwise False.\n \"\"\"\n\n if isinstance(node, ops.Operation):\n node_def = node.node_def\n else:\n assert isinstance(node, node_def_pb2.NodeDef)\n node_def = node\n\n # If the op is a variable-related op, should we pin it on CPU?\n if pin_variables_on_cpu and _is_variable_op(node_def.op):\n return True\n\n # Constant operations producing a string or int32 must run on CPU.\n if node_def.op == \"Const\":\n # Get the value of the 'dtype' attr\n dtype = node_def.attr[\"dtype\"].type\n if dtype == dtypes.string or dtype == dtypes.int32:\n return True\n\n if node_def.op in [\"DynamicStitch\", \"ParallelDynamicStitch\"]:\n dtype = node_def.attr[\"T\"].type\n if dtype == dtypes.int32:\n # DynamicStitch on GPU only works for int32 values.\n return True\n\n if node_def.op in [\"Cast\"]:\n dtype = node_def.attr[\"SrcT\"].type\n if dtype == dtypes.int32:\n # Cast on GPU does not works for int32 values.\n return True\n return False\n\n\n################################################################################\n#\n# device functions for use in with g.device(...)\n#\n################################################################################\n\n\ndef _node_name(n):\n if n.startswith(\"^\"):\n return n[1:]\n else:\n return n.split(\":\")[0]\n\n\ndef _extract_graph_summary(graph_def):\n \"\"\"Extracts useful information from the graph and returns them.\"\"\"\n name_to_input_name = {} # Keyed by the dest node name.\n name_to_node = {} # Keyed by node name.\n\n # Keeps track of node sequences. It is important to still output the\n # operations in the original order.\n name_to_seq_num = {} # Keyed by node name.\n seq = 0\n for node in graph_def.node:\n n = _node_name(node.name)\n name_to_node[n] = node\n name_to_input_name[n] = [_node_name(x) for x in node.input]\n if \"_class\" in node.attr:\n for v in node.attr[\"_class\"].list.s:\n v_str = v.decode(\"utf-8\")\n if v_str.startswith(\"loc:@\"):\n colocated_node = v_str[5:]\n name_to_input_name[n].append(colocated_node)\n name_to_seq_num[n] = seq\n seq += 1\n return name_to_input_name, name_to_node, name_to_seq_num\n\n\ndef _assert_nodes_are_present(name_to_node, nodes):\n \"\"\"Assert that nodes are present in the graph.\"\"\"\n for d in nodes:\n assert d in name_to_node, \"%s is not in graph\" % d\n\n\ndef _bfs_for_reachable_nodes(target_nodes, name_to_input_name):\n \"\"\"Breadth first search for reachable nodes from target nodes.\"\"\"\n nodes_to_keep = set()\n # Breadth first search to find all the nodes that we should keep.\n next_to_visit = target_nodes[:]\n while next_to_visit:\n node = next_to_visit[0]\n del next_to_visit[0]\n if node in nodes_to_keep:\n # Already visited this node.\n continue\n nodes_to_keep.add(node)\n if node in name_to_input_name:\n next_to_visit += name_to_input_name[node]\n return nodes_to_keep\n\n\[email protected](\n date=None,\n instructions=\"Use `tf.compat.v1.graph_util.extract_sub_graph`\")\n@tf_export(v1=[\"graph_util.extract_sub_graph\"])\ndef extract_sub_graph(graph_def, dest_nodes):\n \"\"\"Extract the subgraph that can reach any of the nodes in 'dest_nodes'.\n Args:\n graph_def: A graph_pb2.GraphDef proto.\n dest_nodes: A list of strings specifying the destination node names.\n Returns:\n The GraphDef of the sub-graph.\n Raises:\n TypeError: If 'graph_def' is not a graph_pb2.GraphDef proto.\n \"\"\"\n\n if not isinstance(graph_def, graph_pb2.GraphDef):\n raise TypeError(\"graph_def must be a graph_pb2.GraphDef proto.\")\n\n if isinstance(dest_nodes, six.string_types):\n raise TypeError(\"dest_nodes must be a list.\")\n\n name_to_input_name, name_to_node, name_to_seq_num = _extract_graph_summary(\n graph_def)\n _assert_nodes_are_present(name_to_node, dest_nodes)\n\n nodes_to_keep = _bfs_for_reachable_nodes(dest_nodes, name_to_input_name)\n\n nodes_to_keep_list = sorted(\n list(nodes_to_keep), key=lambda n: name_to_seq_num[n])\n # Now construct the output GraphDef\n out = graph_pb2.GraphDef()\n for n in nodes_to_keep_list:\n out.node.extend([copy.deepcopy(name_to_node[n])])\n out.library.CopyFrom(graph_def.library)\n out.versions.CopyFrom(graph_def.versions)\n\n return out\n\n\[email protected](\n date=None,\n instructions=\"Use `tf.compat.v1.graph_util.tensor_shape_from_node_def_name`\"\n)\n@tf_export(v1=[\"graph_util.tensor_shape_from_node_def_name\"])\ndef tensor_shape_from_node_def_name(graph, input_name):\n \"\"\"Convenience function to get a shape from a NodeDef's input string.\"\"\"\n # To get a tensor, the name must be in the form <input>:<port>, for example\n # 'Mul:0'. The GraphDef input strings don't always have the port specified\n # though, so if there isn't a colon we need to add a default ':0' to the end.\n if \":\" not in input_name:\n canonical_name = input_name + \":0\"\n else:\n canonical_name = input_name\n tensor = graph.get_tensor_by_name(canonical_name)\n shape = tensor.get_shape()\n return shape\n\n\[email protected](\n date=None,\n instructions=\"Use `tf.compat.v1.graph_util.convert_variables_to_constants`\")\n@tf_export(v1=[\"graph_util.convert_variables_to_constants\"])\ndef convert_variables_to_constants(sess,\n input_graph_def,\n output_node_names,\n variable_names_whitelist=None,\n variable_names_blacklist=None):\n \"\"\"Replaces all the variables in a graph with constants of the same values.\n If you have a trained graph containing Variable ops, it can be convenient to\n convert them all to Const ops holding the same values. This makes it possible\n to describe the network fully with a single GraphDef file, and allows the\n removal of a lot of ops related to loading and saving the variables.\n Args:\n sess: Active TensorFlow session containing the variables.\n input_graph_def: GraphDef object holding the network.\n output_node_names: List of name strings for the result nodes of the graph.\n variable_names_whitelist: The set of variable names to convert (by default,\n all variables are converted).\n variable_names_blacklist: The set of variable names to omit converting\n to constants.\n Returns:\n GraphDef containing a simplified version of the original.\n \"\"\"\n\n def has_variable_as_input(node):\n \"\"\"Checks if the input node has a variable in `variables_data_map`.\"\"\"\n for name in node.input:\n if name in variables_data_map or\\\n (name in identity_ops_input_map\n and identity_ops_input_map[name] in variables_data_map):\n return True\n return False\n\n def dfs_find_variable(origin_name, name_to_nodes):\n\n if origin_name in variables_data_map:\n return origin_name, set()\n\n nodes_in_path = set()\n found_variables = set()\n\n def dfs(name):\n node = name_to_nodes[name]\n if node.op == \"Switch\":\n inputs = [node.input[0]]\n else:\n inputs = node.input\n for name in inputs:\n name = _node_name(name)\n if name in nodes_in_path:\n continue\n elif name in variables_data_map:\n found_variables.add(name)\n continue\n else:\n nodes_in_path.add(name)\n dfs(name)\n\n nodes_in_path.add(origin_name)\n dfs(origin_name)\n\n if len(found_variables) > 1:\n raise ValueError(\"found variables %s\" % found_variables)\n\n variable = None\n for v in found_variables:\n variable = v\n return variable, nodes_in_path\n\n def create_const_op(node_name, dtype, data, data_shape=None):\n \"\"\"Creates a Const op.\"\"\"\n output_node = node_def_pb2.NodeDef()\n output_node.op = \"Const\"\n output_node.name = node_name\n output_node.attr[\"dtype\"].CopyFrom(dtype)\n output_node.attr[\"value\"].CopyFrom(\n attr_value_pb2.AttrValue(\n tensor=tensor_util.make_tensor_proto(\n data, dtype=dtype.type, shape=data_shape)))\n return output_node\n\n # This graph only includes the nodes needed to evaluate the output nodes, and\n # removes unneeded nodes like those involved in saving and assignment.\n inference_graph = extract_sub_graph(input_graph_def, output_node_names)\n\n # Get list of variables.\n variable_names = []\n variable_dict_names = []\n identity_ops_input_map = {}\n name_to_node = {}\n for node in inference_graph.node:\n name_to_node[node.name] = node\n if node.op in [\"Variable\", \"VariableV2\", \"VarHandleOp\"]:\n variable_name = node.name\n if ((variable_names_whitelist is not None\n and variable_name not in variable_names_whitelist) or\n (variable_names_blacklist is not None\n and variable_name in variable_names_blacklist)):\n continue\n variable_dict_names.append(variable_name)\n if node.op == \"VarHandleOp\":\n variable_names.append(variable_name + \"/Read/ReadVariableOp:0\")\n else:\n variable_names.append(variable_name + \":0\")\n elif node.op == \"Identity\":\n # TODO(nupurgarg): Move and reuse get_name from lite/convert.py.\n # Creates a map of Identity node names to the input names.\n input_info = node.input[0].split(\":\")\n if (len(input_info) == 1 or\n (len(input_info) == 2 and int(input_info[1]) == 0)):\n identity_ops_input_map[node.name] = input_info[0]\n\n # Gets map of variables and the associated data.\n if variable_names:\n returned_variables = sess.run(variable_names)\n else:\n returned_variables = []\n variables_data_map = dict(zip(variable_dict_names, returned_variables))\n logging.info(\"Froze %d variables.\", len(returned_variables))\n\n # Reconstruct the graph with constants in place of variables.\n\n path_node_to_variables = {}\n output_graph_def = graph_pb2.GraphDef()\n how_many_converted = 0\n for input_node in inference_graph.node:\n output_node = node_def_pb2.NodeDef()\n if input_node.name in variables_data_map:\n data = variables_data_map[input_node.name]\n output_node = create_const_op(input_node.name, input_node.attr[\"dtype\"],\n data, data.shape)\n how_many_converted += 1\n elif input_node.op == \"ReadVariableOp\":\n variable, nodes_in_path = dfs_find_variable(input_node.input[0], name_to_node)\n if variable is not None:\n # The first branch converts all VarHandleOps of ResourceVariables to\n # constants, so we need to convert the associated ReadVariableOps to\n # Identity ops.\n #\n # Handles the following cases:\n # Variable --> ReadVariableOp\n # Variable --> Identity --> ReadVariableOp\n output_node.op = \"Identity\"\n output_node.name = input_node.name\n output_node.input.extend([input_node.input[0]])\n output_node.attr[\"T\"].CopyFrom(input_node.attr[\"dtype\"])\n if \"_class\" in input_node.attr:\n output_node.attr[\"_class\"].CopyFrom(input_node.attr[\"_class\"])\n for name in nodes_in_path:\n path_node_to_variables[name] = variable\n else:\n raise ValueError(\"Cannot find variable for %s\" % input_node.name)\n\n elif input_node.op == \"ResourceGather\":\n\n variable, nodes_in_path = dfs_find_variable(input_node.input[0], name_to_node)\n if variable is not None:\n # The first branch converts all VarHandleOps of ResourceGather to\n # constants, so we need to convert the associated ResourceGather to Gather\n # ops with a Const axis feeding into it.\n if input_node.attr[\"batch_dims\"].i != 0:\n raise ValueError(\"batch_dims != 0 is not supported by freeze_graph.\")\n axis_data = input_node.attr[\"batch_dims\"].i\n axis_node_name = input_node.name + \"/axis\"\n axis_dtype = input_node.attr[\"Tindices\"]\n output_axis_node = create_const_op(axis_node_name, axis_dtype, axis_data)\n output_graph_def.node.extend([output_axis_node])\n\n output_node.op = \"GatherV2\"\n output_node.name = input_node.name\n output_node.input.extend(\n [input_node.input[0], input_node.input[1], axis_node_name])\n output_node.attr[\"Tparams\"].CopyFrom(input_node.attr[\"dtype\"])\n output_node.attr[\"Tindices\"].CopyFrom(input_node.attr[\"Tindices\"])\n output_node.attr[\"Taxis\"].CopyFrom(axis_dtype)\n if \"_class\" in input_node.attr:\n output_node.attr[\"_class\"].CopyFrom(input_node.attr[\"_class\"])\n for name in nodes_in_path:\n path_node_to_variables[name] = variable\n else:\n raise ValueError(\"Cannot find variable for %s\" % input_node.name)\n elif input_node.op == \"VariableShape\":\n\n variable, nodes_in_path = dfs_find_variable(input_node.input[0], name_to_node)\n if variable is not None:\n input_variable = name_to_node[variable]\n output_node.op = \"Shape\"\n output_node.name = input_node.name\n output_node.input.extend([input_node.input[0]])\n output_node.attr[\"T\"].CopyFrom(input_variable.attr[\"dtype\"])\n output_node.attr[\"out_type\"].CopyFrom(input_node.attr[\"out_type\"])\n for name in nodes_in_path:\n path_node_to_variables[name] = variable\n else:\n raise ValueError(\"Cannot find variable for %s\" % input_node.name)\n else:\n output_node.CopyFrom(input_node)\n output_graph_def.node.extend([output_node])\n\n output_graph_def.library.CopyFrom(inference_graph.library)\n\n inference_graph = output_graph_def\n output_graph_def = graph_pb2.GraphDef()\n for input_node in inference_graph.node:\n output_node = node_def_pb2.NodeDef()\n if input_node.name in path_node_to_variables:\n input_variable = path_node_to_variables[input_node.name]\n input_variable = name_to_node[input_variable]\n output_node.op = input_node.op\n output_node.name = input_node.name\n if input_node.op == \"Enter\":\n output_node.input.extend([input_node.input[0]])\n output_node.attr[\"T\"].CopyFrom(input_variable.attr[\"dtype\"])\n output_node.attr[\"frame_name\"].CopyFrom(input_node.attr[\"frame_name\"])\n output_node.attr[\"is_constant\"].CopyFrom(input_node.attr[\"is_constant\"])\n output_node.attr[\"parallel_iterations\"]\\\n .CopyFrom(input_node.attr[\"parallel_iterations\"])\n elif input_node.op == \"Switch\":\n output_node.input.extend(input_node.input)\n output_node.attr[\"T\"].CopyFrom(input_variable.attr[\"dtype\"])\n else:\n raise ValueError(\"cannot do type: %s\" % input_node.op)\n else:\n output_node.CopyFrom(input_node)\n output_graph_def.node.extend([output_node])\n\n output_graph_def.library.CopyFrom(inference_graph.library)\n\n logging.info(\"Converted %d variables to const ops.\", how_many_converted)\n return output_graph_def\n\n\[email protected](\n date=None,\n instructions=\"Use `tf.compat.v1.graph_util.remove_training_nodes`\")\n@tf_export(v1=[\"graph_util.remove_training_nodes\"])\ndef remove_training_nodes(input_graph, protected_nodes=None):\n \"\"\"Prunes out nodes that aren't needed for inference.\n There are nodes like Identity and CheckNumerics that are only useful\n during training, and can be removed in graphs that will be used for\n nothing but inference. Here we identify and remove them, returning an\n equivalent graph. To be specific, CheckNumerics nodes are always removed, and\n Identity nodes that aren't involved in control edges are spliced out so that\n their input and outputs are directly connected.\n Args:\n input_graph: Model to analyze and prune.\n protected_nodes: An optional list of names of nodes to be kept\n unconditionally. This is for example useful to preserve Identity output\n nodes.\n Returns:\n A list of nodes with the unnecessary ones removed.\n \"\"\"\n if not protected_nodes:\n protected_nodes = []\n\n types_to_remove = {\"CheckNumerics\": True}\n\n input_nodes = input_graph.node\n names_to_remove = {}\n for node in input_nodes:\n if node.op in types_to_remove and node.name not in protected_nodes:\n names_to_remove[node.name] = True\n\n nodes_after_removal = []\n for node in input_nodes:\n if node.name in names_to_remove:\n continue\n new_node = node_def_pb2.NodeDef()\n new_node.CopyFrom(node)\n input_before_removal = node.input\n del new_node.input[:]\n for full_input_name in input_before_removal:\n input_name = re.sub(r\"^\\^\", \"\", full_input_name)\n if input_name in names_to_remove:\n continue\n new_node.input.append(full_input_name)\n nodes_after_removal.append(new_node)\n\n types_to_splice = {\"Identity\": True}\n control_input_names = set()\n node_names_with_control_input = set()\n for node in nodes_after_removal:\n for node_input in node.input:\n if \"^\" in node_input:\n control_input_names.add(node_input.replace(\"^\", \"\"))\n node_names_with_control_input.add(node.name)\n\n names_to_splice = {}\n for node in nodes_after_removal:\n if node.op in types_to_splice and node.name not in protected_nodes:\n # We don't want to remove nodes that have control edge inputs, because\n # they might be involved in subtle dependency issues that removing them\n # will jeopardize.\n if node.name not in node_names_with_control_input:\n names_to_splice[node.name] = node.input[0]\n\n # We also don't want to remove nodes which are used as control edge inputs.\n names_to_splice = {name: value for name, value in names_to_splice.items()\n if name not in control_input_names}\n\n nodes_after_splicing = []\n for node in nodes_after_removal:\n if node.name in names_to_splice:\n continue\n new_node = node_def_pb2.NodeDef()\n new_node.CopyFrom(node)\n input_before_removal = node.input\n del new_node.input[:]\n for full_input_name in input_before_removal:\n input_name = re.sub(r\"^\\^\", \"\", full_input_name)\n while input_name in names_to_splice:\n full_input_name = names_to_splice[input_name]\n input_name = re.sub(r\"^\\^\", \"\", full_input_name)\n new_node.input.append(full_input_name)\n nodes_after_splicing.append(new_node)\n\n output_graph = graph_pb2.GraphDef()\n output_graph.node.extend(nodes_after_splicing)\n return output_graph\n",
"#\n# Copyright 2018 Analytics Zoo 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 zoo.common.nncontext import init_nncontext\nfrom zoo.models.anomalydetection import AnomalyDetector\nimport pandas as pd\nfrom pyspark.sql import SQLContext\nfrom pyspark import sql\nfrom optparse import OptionParser\nimport sys\n\nif __name__ == \"__main__\":\n parser = OptionParser()\n parser.add_option(\"--input_dir\", dest=\"input_dir\")\n parser.add_option(\"-b\", \"--batch_size\", dest=\"batch_size\", default=\"1024\")\n parser.add_option(\"--nb_epoch\", dest=\"nb_epoch\", default=\"20\")\n parser.add_option(\"--unroll_len\", dest=\"unroll_len\", default=\"24\")\n\n (options, args) = parser.parse_args(sys.argv)\n sc = init_nncontext(\"Anomaly Detection Example\")\n\n sqlContext = sql.SQLContext(sc)\n\n def load_and_scale(input_path):\n df = pd.read_csv(input_path)\n df['datetime'] = pd.to_datetime(df['timestamp'])\n df['hours'] = df['datetime'].dt.hour\n df['awake'] = (((df['hours'] >= 6) & (df['hours'] <= 23)) | (df['hours'] == 0)).astype(int)\n print(df.head(10))\n sqlContext = SQLContext(sc)\n dfspark = sqlContext.createDataFrame(df[[\"value\", \"hours\", \"awake\"]])\n feature_size = len([\"value\", \"hours\", \"awake\"])\n return AnomalyDetector.standardScale(dfspark), feature_size\n\n dfscaled, feature_size = load_and_scale(options.input_dir)\n datardd = dfscaled.rdd.map(lambda row: [x for x in row])\n unrolled = AnomalyDetector.unroll(datardd, int(options.unroll_len), predict_step=1)\n [train, test] = AnomalyDetector.train_test_split(unrolled, 1000)\n\n model = AnomalyDetector(feature_shape=(int(options.unroll_len), feature_size),\n hidden_layers=[8, 32, 15], dropouts=[0.2, 0.2, 0.2])\n model.compile(loss='mse', optimizer='rmsprop', metrics=['mae'])\n model.fit(train, batch_size=int(options.batch_size), nb_epoch=int(options.nb_epoch),\n validation_data=test)\n test.cache()\n y_predict = model.predict(test).map(lambda x: float(x[0]))\n y_truth = test.map(lambda x: float(x.label.to_ndarray()[0]))\n anomalies = AnomalyDetector.detect_anomalies(y_predict, y_truth, 50)\n\n print(anomalies.take(10)[0:10])\n"
] | [
[
"tensorflow.python.platform.tf_logging.info",
"tensorflow.python.util.tf_export.tf_export",
"tensorflow.core.framework.node_def_pb2.NodeDef",
"tensorflow.python.framework.tensor_util.make_tensor_proto",
"tensorflow.core.framework.graph_pb2.GraphDef",
"tensorflow.python.util.deprecation.deprecated"
],
[
"pandas.read_csv",
"pandas.to_datetime"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"1.12",
"2.6",
"2.2",
"1.13",
"2.3",
"2.4",
"1.4",
"2.9",
"1.5",
"1.7",
"2.5",
"0.12",
"1.0",
"2.8",
"1.2",
"2.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
uzck/tf_net_parser | [
"5e9da1e8a317ef24c2f1577a56d6445e432b1f5d",
"5e9da1e8a317ef24c2f1577a56d6445e432b1f5d"
] | [
"utils.py",
"test/mnist_test.py"
] | [
"import os\nimport numpy as np \nimport matplotlib.image as mpimg\nimport matplotlib.pyplot as plt\nimport cv2\nimport tensorflow as tf\nfrom PIL import Image\n\ndef image_to_ndarray(image_path: str) -> np.ndarray:\n \"\"\"\n Args:\n image_path: 图片文件路径\n \"\"\"\n pass\n\ndef read_image(image_path: str):\n \"\"\"\n 读取图片\n \"\"\"\n if not os.path.exists(image_path):\n print('图片文件路径出错')\n image = mpimg.imread(image_path) # type: np.ndarray\n print(np.shape(image))\n return image\n\ndef show_image(image: np.ndarray):\n \"\"\"\n 显示图片\n \"\"\"\n plt.imshow(image)\n plt.show() \n\ndef save_image(target_path: str, image: np.ndarray):\n cv2.imwrite(target_path, image)\n # image = Image.fromarray(image * 255)\n # image = image.convert('RGB')\n # image.save(target_path)\n\ndef padding(origin: np.ndarray, padding_size, value=0):\n \"\"\"\n 填充图片\n \"\"\"\n return np.pad(origin, padding_size, 'constant')\n\ndef fix_pad_tensor(inputs, kernel_size, data_format='channels_last'):\n pad_total = kernel_size - 1\n pad_beg = pad_total // 2\n pad_end = pad_total - pad_beg\n\n if data_format == 'channels_first':\n padded_inputs = tf.pad(tensor=inputs,\n paddings=[[0, 0], [0, 0], [pad_beg, pad_end],\n [pad_beg, pad_end]])\n else:\n padded_inputs = tf.pad(tensor=inputs,\n paddings=[[0, 0], [pad_beg, pad_end],\n [pad_beg, pad_end], [0, 0]])\n return padded_inputs\n\ndef restore_graph(file_path: str, sess: tf.Session):\n \"\"\"\n 加载图模型\n \"\"\"\n saver = tf.train.Saver(max_to_keep=5)\n return saver.restore(sess, tf.train.latest_checkpoint('../save_model/'))\ndef save_model(file_path: str, sess: tf.Session, gloabl_step=100, max_model_count=5, keep_checkpoint_every_n_hours=0.5, write_meta_graph=False):\n \"\"\"\n 存储训练模型到指定路径\n \"\"\"\n saver = tf.train.Saver(max_to_keep=max_model_count, keep_checkpoint_every_n_hours=keep_checkpoint_every_n_hours) # type: tf.train.Saver\n saver.save(sess, file_path, global_step=gloabl_step, write_meta_graph=write_meta_graph)\n\ndef load_weigths_npz(file_path: str):\n \"\"\"\n 读取npz格式存储的权重文件\n \"\"\"\n npz_file = np.load(file_path)\n return npz_file\n\ndef save_to_npy(file_path:str, target):\n \"\"\"\n 存储指定的图或者权重变量到npy文件\n \"\"\"\n np.save(file_path, target)\n\ndef save_to_npz(file_path: str, target):\n np.savez(file_path, target)\n\ndef transfer_graph_to_network(graph):\n \"\"\"\n 把saver.restore重建的图解析成Network类\n \"\"\"\n pass\n\ndef trans_ckpt_to_pb(ckpt_dir_path: str, save_path: str):\n pass",
"import sys\nsys.path.append(\"../\")\nimport input_data\nimport tensorflow as tf\nimport numpy as np\nfrom net_parser import Parser\nfrom network import Network\nfrom network_builder import NetworkBuilder\nfrom train import TrainTool\nfrom layer import *\n\ndef main():\n parser = Parser('../data/alexnet.cfg')\n network_builder = NetworkBuilder(\"test\")\n mnist = input_data.read_data_sets(\"F:/tf_net_parser/datasets/MNIST_data/\", one_hot=True) # 读取数据\n network_builder.set_parser(parser)\n network = network_builder.build() # type: Network\n network.add_input_layer(InputLayer(tf.float32, [None, 28, 28, 1]))\n network.add_output_layer(OutputLayer())\n network.set_labels_placeholder(tf.placeholder(tf.float32, [None, 10]))\n network.connect_each_layer()\n network.set_accuracy()\n network.init_optimizer()\n train_tool = TrainTool()\n train_tool.bind_network(network)\n sess = tf.Session()\n sess.run(tf.initialize_all_variables())\n for i in range(300):\n batch = mnist.train.next_batch(100)\n feed_dict = {network.input: np.reshape(batch[0], [-1, 28, 28, 1]), network.labels: batch[1]}\n train_tool.train(sess, network.output, feed_dict=feed_dict)\n if (i+1) % 100 == 0:\n train_tool.print_accuracy(sess, feed_dict)\n train_tool.save_model_to_pb_file(sess, '../pb/alexnet-' + str(i+1) + '/' , input_data={'input': network.input}, output={'predict-result': network.output})\n # train_tool.save_ckpt_model('f:/tf_net_parser/save_model/model', sess, gloabl_step=(i+1))\n\n batch_test = mnist.test.next_batch(100)\n feed_dict = {network.input: np.reshape(batch_test[0], [100, 28, 28, 1]), network.labels: batch_test[1]}\n train_tool.print_test_accuracy(sess, feed_dict)\nif __name__ == '__main__':\n main()"
] | [
[
"matplotlib.pyplot.imshow",
"numpy.savez",
"tensorflow.train.latest_checkpoint",
"numpy.pad",
"numpy.save",
"matplotlib.image.imread",
"numpy.shape",
"tensorflow.pad",
"tensorflow.train.Saver",
"numpy.load",
"matplotlib.pyplot.show"
],
[
"numpy.reshape",
"tensorflow.initialize_all_variables",
"tensorflow.placeholder",
"tensorflow.Session"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"1.12",
"1.4",
"1.13",
"1.5",
"1.7",
"0.12",
"1.0",
"1.2"
]
}
] |
Kelvin-spacy/CogAlg | [
"e0f44a8746ba33a07864505d6e2ae959859024b0"
] | [
"frame_2D_alg/class_cluster.py"
] | [
"\"\"\"\nProvide a base class for cluster objects in CogAlg.\nFeatures:\n- Unique instance ids per class.\n- Instances are retrievable by ids via class.\n- Reduced memory usage compared to using dict.\n- Methods generated via string templates so overheads caused by\ndifferences in interfaces are mostly eliminated.\n- Can be extended/modified further to support main implementation better.\n\"\"\"\n\nimport weakref\nfrom numbers import Number\nfrom inspect import isclass\nimport numpy as np\n\nNoneType = type(None)\n\n# ----------------------------------------------------------------------------\n# Template for class method generation\n_methods_template = '''\n@property\ndef id(self):\n return self._id\n \ndef pack(self{pack_args}):\n \"\"\"Pack all fields/params back into {typename}.\"\"\"\n {pack_assignments}\n \ndef unpack(self):\n \"\"\"Unpack all fields/params back into the cluster.\"\"\"\n return ({param_vals})\ndef accumulate(self, **kwargs):\n \"\"\"Add a number to specified numerical fields/params.\"\"\"\n {accumulations}\ndef __contains__(self, item):\n return (item in {params})\ndef __delattr__(self, item):\n raise AttributeError(\"cannot delete attribute from \"\n \"'{typename}' object\")\ndef __repr__(self):\n return \"{typename}({repr_fmt})\" % ({numeric_param_vals})\n'''\n\n# ----------------------------------------------------------------------------\n# MetaCluster meta-class\nclass MetaCluster(type):\n \"\"\"\n Serve as a factory for creating new cluster classes.\n \"\"\"\n def __new__(mcs, typename, bases, attrs): # called right before a new class is created\n # get fields/params and numeric params\n replace = attrs.get('replace', {})\n\n # inherit params\n new_bases = []\n for base in bases:\n if issubclass(base, ClusterStructure):\n new_bases.append(base)\n for param in base.numeric_params:\n if param not in attrs: # prevents duplication of base params\n # not all inherited params are Cdm\n if param in replace:\n new_param, new_type = replace[param]\n if new_param is not None:\n attrs[new_param] = new_type\n else:\n attrs[param] = getattr(base,param+'_type') # if the param is not replaced, it will following type of base param\n else:\n print(f\"Warning: {base} is not a subclass of {ClusterStructure}\")\n\n bases = tuple(new_bases) # remove\n\n if len(bases)>1:\n bases=(bases[0],)\n\n # only ignore param names start with double underscore\n params = tuple(attr for attr in attrs\n if not attr.startswith('__') and\n isclass(attrs[attr]))\n\n numeric_params = tuple(param for param in params\n if (issubclass(attrs[param], Number)) and\n not (issubclass(attrs[param], bool))) # avoid accumulate bool, which is flag\n\n list_params = tuple(param for param in params\n if (issubclass(attrs[param], list)))\n\n dict_params = tuple(param for param in params\n if (issubclass(attrs[param], dict)))\n\n # Fill in the template\n methods_definitions = _methods_template.format(\n typename=typename,\n params=str(params),\n param_vals=', '.join(f'self.{param}'\n for param in params),\n numeric_param_vals=', '.join(f'self.{param}'\n for param in numeric_params),\n list_param_vals=', '.join(f'self.{param}'\n for param in list_params),\n dict_param_vals=', '.join(f'self.{param}'\n for param in dict_params),\n pack_args=', '.join(param for param in ('', *params)),\n pack_assignments='; '.join(f'self.{param} = {param}'\n for param in params)\n if params else 'pass',\n accumulations='; '.join(f\"self.{param} += \"\n f\"kwargs.get('{param}', 0)\"\n for param in numeric_params)\n if params else 'pass',\n repr_fmt=', '.join(f'{param}=%r' for param in numeric_params),\n )\n # Generate methods\n namespace = dict(print=print)\n exec(methods_definitions, namespace)\n # Replace irrelevant names\n namespace.pop('__builtins__')\n namespace.pop('print')\n\n # Update to attrs\n attrs.update(namespace)\n\n # Save default types for fields/params\n for param in params:\n attrs[param + '_type'] = attrs.pop(param)\n # attrs['params'] = params\n attrs['numeric_params'] = numeric_params\n attrs['list_params'] = list_params\n attrs['dict_params'] = dict_params\n\n # Add fields/params and other instance attributes\n attrs['__slots__'] = (('_id', 'hid', *params, '__weakref__')\n if not bases else ('_id', 'hid', *params))\n\n # Register the new class\n cls = super().__new__(mcs, typename, bases, attrs)\n\n # Create container for references to instances\n cls._instances = []\n\n return cls\n\n def __call__(cls, *args, **kwargs): # call right before a new instance is created\n # register new instance\n instance = super().__call__(*args, **kwargs)\n\n # initialize fields/params\n for param in cls.__slots__[2:]: # Exclude _id and __weakref__\n setattr(instance, param,\n kwargs.get(param,\n getattr(cls, param + '_type')()))\n\n # set inherited params\n if kwargs.get('inherit') is not None:\n\n excluded = []\n if kwargs.get('excluded') is not None:\n excluded = kwargs.get('excluded')\n\n for inherit_instance in kwargs.get('inherit'):\n for param in cls.numeric_params: # inherit numeric params\n if hasattr(inherit_instance,param) and (param not in excluded):\n setattr(instance, param, getattr(inherit_instance, param))\n\n for param in cls.list_params: # inherit list params\n if hasattr(inherit_instance,param) and (param not in excluded):\n list_param = getattr(inherit_instance, param)\n if len(list_param)>0: # not empty list\n setattr(instance, param, list_param )\n\n for param in cls.dict_params: # inherit dict params\n if hasattr(inherit_instance,param) and (param not in excluded):\n setattr(instance, param, getattr(inherit_instance, param))\n\n for param in cls.dict_params: # inherit dict params\n if hasattr(inherit_instance,param) and (param not in excluded):\n setattr(instance, param, getattr(inherit_instance, param))\n\n # Set id\n instance._id = len(cls._instances)\n # Create ref\n cls._instances.append(weakref.ref(instance))\n # no default higher cluster id, set to None\n instance.hid = None # higher cluster's id\n\n return instance\n\n # original\n '''\n def __call__(cls, *args, **kwargs): # call right before a new instance is created\n # register new instance\n instance = super().__call__(*args, **kwargs)\n # initialize fields/params\n for param in cls.__slots__[2:]: # Exclude _id and __weakref__\n setattr(instance, param,\n kwargs.get(param,\n getattr(cls, param + '_type')()))\n # Set id\n instance._id = len(cls._instances)\n # Create ref\n cls._instances.append(weakref.ref(instance))\n # no default higher cluster id, set to None\n instance.hid = None # higher cluster's id\n return instance\n '''\n\n def get_instance(cls, cluster_id):\n try:\n return cls._instances[cluster_id]()\n except IndexError:\n return None\n\n @property\n def instance_cnt(cls):\n return len(cls._instances)\n\n\n# ----------------------------------------------------------------------------\n# ClusterStructure class\nclass ClusterStructure(metaclass=MetaCluster):\n \"\"\"\n Class for cluster objects in CogAlg.\n Each time a new instance is created, four things are done:\n - Set initialize field/param.\n - Set id.\n - Save a weak reference of instance inside the class object.\n (meaning that if there's no other references to instance,\n it will be garbage collected, weakref to it will return None\n afterwards)\n - Set higher cluster id to None (no higher cluster structure yet)\n Examples\n --------\n >>> from class_cluster import ClusterStructure\n >>> class CP(ClusterStructure):\n >>> L = int # field/param name and default type\n >>> I = int\n >>>\n >>> P1 = CP(L=1, I=5) # initialized with values\n >>> print(P1)\n CP(L=1, I=5)\n >>> P2 = CP() # default initialization\n >>> print(P2)\n CP(L=0, I=0)\n >>> print(P1.id, P2.id) # instance's ids\n 0 1\n >>> # look for object by instance's ids\n >>> print(CP.get_instance(0), CP.get_instance(1))\n CP(L=1, I=5) CP(L=0, I=0)\n >>> P2.L += 1; P2.I += 10 # assignment, fields are mutable\n >>> print(P2)\n CP(L=1, I=10)\n >>> # Accumulate using accumulate()\n >>> P1.accumulate(L=1, I=2)\n >>> print(P1)\n CP(L=2, I=7)\n >>> # ... or accum_from()\n >>> P2.accum_from(P1)\n >>> print(P2)\n CP(L=3, I=17)\n >>> # field/param types are not constrained, so be careful!\n >>> P2.L = 'something'\n >>> print(P2)\n CP(L='something', I=10)\n \"\"\"\n\n def __init__(self, **kwargs):\n pass\n\n def accum_from(self, other, excluded=()):\n \"\"\"Accumulate params from another structure.\"\"\"\n\n # accumulate base params\n for param in self.numeric_params:\n if (param not in excluded) and (param in other.numeric_params):\n p = getattr(self,param)\n _p = getattr(other,param)\n setattr(self, param, p+_p)\n\n # accumulate layers 1 and above\n for layer_num in self.dict_params:\n if (layer_num in other.dict_params):\n\n layer = getattr(self,layer_num) # self layer params\n _layer = getattr(other,layer_num) # other layer params\n\n if len(layer) == len(_layer): # both layers have the same params\n for i, ((param_name,dert), (_param_name,_dert)) in enumerate(zip(layer.items(), _layer.items())):\n # accumulate _dert into dert\n if not isinstance(dert, Cdert) and isinstance(_dert, Cdert): # if base param < ave_comp?\n layer[param_name] = _dert\n elif isinstance(dert, Cdert) and isinstance(_dert, Cdert):\n dert.p += _dert.p\n dert.d += _dert.d\n dert.m += _dert.m\n elif len(_layer)>0: # _layer is not empty but layer is empty\n setattr(self,layer_num,_layer.copy())\n\n\nclass Cdert(Number): # Ppd and Ppdm might not relevant now, so remove it\n __slots__ = ('i','p','d','m')\n\n def __init__(self, i=0, p=0, d=0, m=0):\n self.i, self.p, self.d, self.m = i, d, m, p\n\n def __add__(self, other):\n return Cdert(self.i, self.p + other.p, self.d + other.d, self.m + other.m)\n\n def __repr__(self): # representation of object\n if isinstance(self.i, Cdert) or isinstance(self.p, Cdert) or isinstance(self.d, Cdert) or isinstance(self.m, Cdert):\n return \"Cdert(i=Cdert, p=Cdert, d=Cdert, m=Cdert)\"\n else:\n return \"Cdert(i={}, p={}, d={}, m={})\".format(self.i, self.p, self.d, self.m, self.p)\n\n\ndef comp_param(param, _param, param_name, ave):\n\n if isinstance(param,list): # vector\n sin, cos = param[0], param[1]\n _sin, _cos = _param[0], _param[1]\n # difference of dy and dx\n sin_da = (cos * _sin) - (sin * _cos) # sin(α - β) = sin α cos β - cos α sin β\n cos_da= (cos * _cos) + (sin * _sin) # cos(α - β) = cos α cos β + sin α sin β\n da = np.arctan2(sin_da, cos_da)\n ma = ave - abs(da) # indirect match\n dert = Cdert(i=param, p=param+_param, d=da, m=ma) # d=None? p=param+_param will sum lists?\n else: # numeric\n d = param - _param # difference\n if param_name == 'I':\n m = ave - abs(d) # indirect match\n else:\n m = min(param,_param) - abs(d)/2 - ave # direct match\n dert = Cdert(i=param, p=param+_param, d=d,m=m)\n\n return dert\n\n\nif __name__ == \"__main__\": # for tests\n\n\n # ---- root layer --------------------------------------------------------\n # using blob as example\n class CBlob(ClusterStructure):\n I = int\n Dy = int\n Dx = int\n G = int\n M = int\n Day = int\n Dax = int\n\n # blob derivatives\n class CderBlob(ClusterStructure):\n mB = int\n dB = int\n blob = object\n _blob = object\n\n class CBblob(CBlob, CderBlob):\n pass\n\n # ---- example -----------------------------------------------------------\n\n # root layer\n blob1 = CBlob(I=5, Dy=5, Dx=7, G=5, M=6, Day=4 + 5j, Dax=8 + 9j)\n derBlob1 = CderBlob(mB=5, dB=5)\n\n # example of value inheritance, bblob now will having parameter values from blob1 and derBlob1\n # In this example, Dy and Dx are excluded from the inheritance\n bblob = CBblob(inherit=[blob1, derBlob1], excluded=['Dy','Dx'])\n\n print(bblob)"
] | [
[
"numpy.arctan2"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
juvenilehex/ml2 | [
"57fa64660a87b2e432872c06414d1a86846ce380"
] | [
"hunkim/ml_lab_03_02.py"
] | [
"# 참고자료\n# 모두를 위한 머신러닝/딥러닝 강의\n# 홍콩과기대 김성훈\n# http://hunkim.github.io/ml\n\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\n\nx_data = [1., 2., 3.]\ny_data = [1., 2., 3.]\n\nW = tf.Variable(tf.random_uniform([1], -10.0, 10.0))\n\nX = tf.placeholder(tf.float32)\nY = tf.placeholder(tf.float32)\n\n\nhypothesis = W * X\n\ncost = tf.reduce_mean(tf.square(hypothesis - Y))\n\n# decent = W - tf.mul(0.1, tf.reduce_mean(tf.mul((tf.mul(W, X) - Y), X)))\ndecent = W - tf.multiply(0.1, tf.reduce_mean( ((W * X) - Y) * X) )\nupdate = W.assign(decent)\n\ninit = tf.global_variables_initializer()\n\nsess = tf.Session()\nsess.run(init)\n\narrStep = []\narrCost = []\narrWeight = []\n\nfor step in range(20):\n sess.run(update, feed_dict={X: x_data, Y: y_data})\n\n arrStep.append(step)\n arrCost.append(sess.run(cost, feed_dict={X: x_data, Y: y_data}))\n arrWeight.append(sess.run(W))\n\n print(step, arrCost[step], arrWeight[step])\n\nprint('10', sess.run(hypothesis, feed_dict={X: 10}))\nprint('100', sess.run(hypothesis, feed_dict={X: 100}))\n\n# print\nplt.plot(arrStep, arrCost)\nplt.xlabel('Step')\nplt.ylabel('Cost')\nplt.show()\n"
] | [
[
"tensorflow.reduce_mean",
"tensorflow.placeholder",
"matplotlib.pyplot.plot",
"tensorflow.global_variables_initializer",
"tensorflow.Session",
"tensorflow.square",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.show",
"tensorflow.random_uniform",
"matplotlib.pyplot.ylabel"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"1.12",
"1.4",
"1.5",
"1.7",
"0.12",
"1.0",
"1.2"
]
}
] |
fusion-flap/flap_apdcam | [
"fce208414044fb288328090ba697e8e2482e1c75"
] | [
"apdcam_control/apdcam10g_channel_map.py"
] | [
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Feb 27 12:51:00 2022\n\n@author: Zoletnik\n\"\"\"\nimport numpy as np\n\ndef apdcam10g_channel_map(camera_type=None,camera_version=1):\n \"\"\"\n Returns a 2D matrix with the ADC channel numbers as one looks onto the detector.\n\n Parameters\n ----------\n camera_type : string\n The camera type. Possible values:\n 4x32: 4 columns, 32 rows\n 8x8: 8x8 pixels\n 4x16: 4 columns, 16 rows\n 8x16: 8 columns, 16 rows (4 S8550 detectors horizontolly in one column)\n 8x16A: 8 columns, 16 rows (4 S8550 detectors verticallally tiled)\n FC: 64 channel fibre coupled (returns 1x64 array)\n camera_version : int, optional\n The detector panel and amplifier version. The default is 1.\n 0: 2014 version\n 1: 2016 version\n 2: Hybrid (2016 detector with 2014 amplifiers) \n\n Raises:\n ValueError: Unkniwn camera type of version\n Returns\n -------\n channel_map: Numpy array of ints\n The ADC channel numbers as one looks onto the detector from the camera front.\n channel_map[0,0] is upper left corner\n channel_map[nr,nc] is lower right corner if nr is number of rows, nc is number of columns\n\n \"\"\"\n \n if (camera_type == \"4x32\"):\n channel_map = np.ndarray((32,4),int)\n if (camera_version == 0):\n chmap = np.array([[ 20, 90, 75, 76],\n [ 18, 92, 1, 2],\n [ 70, 69, 29, 31],\n [ 16, 15, 87, 85],\n [ 19, 17, 4, 3],\n [ 89, 91, 74, 73],\n [ 13, 14, 30, 88],\n [ 71, 72, 32, 86],\n [ 54,128,104,103],\n [ 56,126, 46, 45],\n [ 41, 42,123,121],\n [ 99,100, 49, 51],\n [ 53, 55, 47, 48],\n [127,125,101,102],\n [ 98, 97,124, 50],\n [ 44, 43,122, 52], \n [116, 58,107,108],\n [114, 60, 33, 34],\n [ 38, 37, 61, 63],\n [112,111,119,117],\n [115,113, 36, 35],\n [ 57, 59,106,105],\n [109,110, 62,120],\n [ 39, 40, 64,118],\n [ 22, 96, 8, 7],\n [ 24, 94, 78, 77], \n [ 9, 10, 27, 25], \n [ 67, 68, 81, 83],\n [ 21, 23, 79, 80],\n [ 95, 93, 5, 6],\n [ 66, 65, 28, 82],\n [ 12, 11, 26, 84]\n ])\n elif (camera_version == 1):\n chmap = np.array([[ 59, 38,125,100],\n [115,110, 53, 44],\n\t\t\t\t \t\t\t [ 60, 37,126, 99],\n\t\t\t\t\t\t\t [116,109, 54, 43],\n\t\t\t\t\t\t\t [ 40, 57, 98,127],\n\t\t\t\t\t\t\t [112,113, 42, 55],\n\t\t\t\t\t\t\t [ 39, 58, 97,128],\n\t\t\t\t\t\t\t [111,114, 41, 56],\n\t\t\t\t\t\t\t [ 24, 9, 18, 15],\n\t\t\t\t\t\t\t [ 96, 65, 90, 71], \n\t\t\t\t\t\t\t [ 23, 10, 17, 16],\n\t\t\t\t\t\t\t [ 95, 66, 89, 72],\n\t\t\t\t\t\t\t [ 11, 22, 13, 20],\n\t\t\t\t\t\t\t [ 67, 94, 69, 92],\n\t\t\t\t\t\t\t [ 12, 21, 14, 19],\n\t\t\t\t\t\t\t [ 68, 93, 70, 91],\n\t\t\t\t\t\t\t [ 27, 6, 29, 4],\n\t\t\t\t\t\t\t [ 83, 78, 85, 76],\n\t\t\t\t\t\t\t [ 28, 5, 30, 3],\n\t\t\t\t\t\t\t [ 84, 77, 86, 75],\n\t\t\t\t\t\t\t [ 8, 25, 2, 31],\n\t\t\t\t\t\t\t [ 80, 81, 74, 87],\n\t\t\t\t\t\t\t [ 7, 26, 1, 32],\n\t\t\t\t\t\t\t [ 79, 82, 73, 88],\n\t\t\t\t\t\t\t [120,105, 50, 47],\n\t\t\t\t\t\t\t [ 64, 33,122,103],\n\t\t\t\t\t\t\t [119,106, 49, 48],\n\t\t\t\t\t\t\t [ 63, 34,121,104],\n\t\t\t\t\t\t\t [107,118, 45, 52],\n\t\t\t\t\t\t\t [ 35, 62,101,124],\n\t\t\t\t\t\t\t [108,117, 46, 51],\n\t\t\t\t\t\t\t [ 36, 61,102,123]\n\t\t\t\t\t\t ])\n else:\n raise ValueError(\"Version {:d} is not possible for camera type '{:s}'.\".format(camera_type))\n return np.transpose(chmap)\n\n elif (camera_type == \"8x8\"):\n channel_map = np.ndarray((8,8),int)\n if (camera_version == 0):\n chmap = np.array([[33, 9,24,22,60,58,39,16],\n [10,34,23,21,59,15,57,40],\n [11,63,36,61,19,17,13,37],\n [35,12,64,62,20,18,38,14],\n [46, 6,50,52,30,32,44, 3],\n [ 5,45,49,51,29, 4,31,43],\n [ 8,25,47,27,53,55, 2,42],\n [48, 7,26,28,54,56,41, 1]\n ])\n elif(camera_version == 1):\n chmap = np.array([[33, 9,63,64,58,57,39,16],\n [10,34,23,24,18,15,17,40],\n [11,62,36,61,59,60,13,37],\n [35,12,22,21,19,20,38,14],\n [46, 6,52,51,53,54,44, 3],\n [ 5,45,28,27,29, 4,30,43],\n [ 8,49,47,50,56,55, 2,42],\n [48, 7,25,26,32,31,41, 1]\n ])\n elif(camera_version == 2):\n chmap = np.array([[42,41,56,54,17,19, 2, 3],\n [43,44,55,53,18, 1,20, 4],\n [39,60,38,58,29,31,14,13],\n [40,37,59,57,30,32,15,16],\n [ 8, 7,24,22,49,51,48,45],\n [ 5, 6,23,21,50,47,52,46],\n [12,28, 9,26,61,63,36,35],\n [11,10,27,25,62,64,33,34]\n ])\n else:\n raise ValueError(\"Version {:d} is not possible for camera type '{:s}'.\".format(camera_type))\n return np.transpose(chmap)\n elif (camera_type == \"8x16\"): \n channel_map = np.ndarray((16,8),int)\n if (camera_version == 0):\n chmap = np.array([[ 14, 70, 18, 20, 30, 32, 76, 3],\n [ 69, 13, 17, 19, 29, 4, 31, 75],\n [ 72, 89, 15, 91, 85, 87, 2, 74],\n [ 16, 71, 90, 92, 86, 88, 73, 1],\n [ 97, 41, 56, 54,124,122,103, 48],\n [ 42, 98, 55, 53,123, 47,121,104],\n [ 43,127,100,125, 51, 49, 45,101],\n [ 99, 44,128,126, 52, 50,102, 46],\n [110, 38,114,116, 62, 64,108, 35],\n [ 37,109,113,115, 61, 36, 63,107],\n [ 40, 57,111, 59,117,119, 34,106],\n [112, 39, 58, 60,118,120,105, 33],\n [ 65, 9, 24, 22, 28, 26, 7, 80],\n [ 10, 66, 23, 21, 27, 79, 25, 8],\n [ 11, 95, 68, 93, 83, 81, 77, 5],\n [ 67, 12, 96, 94, 84, 82, 6, 78]\n ])\n elif (camera_version == 1):\n chmap = np.array([[110, 38,116,115, 53, 54, 44, 99],\n [ 37,109, 60, 59,125,100,126, 43],\n [ 40,113,111,114, 56, 55, 98, 42],\n [112, 39, 57, 58,128,127, 41, 97],\n [ 65, 9, 95, 96, 90, 89, 71, 16],\n [ 10, 66, 23, 24, 18, 15, 17, 72],\n [ 11, 94, 68, 93, 91, 92, 13, 69],\n [ 67, 12, 22, 21, 19, 20, 70, 14],\n [ 78, 6, 84, 83, 85, 86, 76, 3],\n [ 5, 77, 28, 27, 29, 4, 30, 75],\n [ 8, 81, 79, 82, 88, 87, 2, 74],\n [ 80, 7, 25, 26, 32, 31, 73, 1],\n [ 33,105, 63, 64,122,121,103, 48],\n [106, 34,119,120, 50, 47, 49,104],\n [107, 62, 36, 61,123,124, 45,101],\n [ 35,108,118,117, 51, 52,102, 46]\n ])\n else:\n raise ValueError(\"Version {:d} is not possible for camera type '{:s}'.\".format(camera_type))\n return np.transpose(chmap)\n elif (camera_type == \"4x16\"): \n channel_map = np.ndarray((16,4),int)\n if (camera_version == 0):\n chmap = np.array([[22,64,40,39],\n [24,62,14,13],\n [ 9,10,59,57],\n [35,36,17,19],\n [21,23,15,16],\n [63,61,37,38],\n [34,33,60,18],\n [12,11,58,20],\n [52,26,43,44],\n [50,28, 1, 2],\n [ 6, 5,29,31],\n [48,47,55,53],\n [51,49, 4, 3],\n [25,27,42,41],\n [45,46,30,56],\n [ 7, 8,32,54]\n ])\n elif (camera_version == 1):\n chmap = np.array([[ 24, 9, 18, 15],\n\t\t\t\t\t\t\t [ 64, 33, 58, 39], \n\t\t\t\t\t\t\t [ 23, 10, 17, 16],\n\t\t\t\t\t\t\t [ 63, 34, 57, 40],\n\t\t\t\t\t\t\t [ 11, 22, 13, 20],\n\t\t\t\t\t\t\t [ 35, 62, 37, 60],\n\t\t\t\t\t\t\t [ 12, 21, 14, 19],\n\t\t\t\t\t\t\t [ 36, 61, 38, 59],\n\t\t\t\t\t\t\t [ 27, 6, 29, 4],\n\t\t\t\t\t\t\t [ 51, 46, 53, 44],\n\t\t\t\t\t\t\t [ 28, 5, 30, 3],\n\t\t\t\t\t\t\t [ 52, 45, 54, 43],\n\t\t\t\t\t\t\t [ 8, 25, 2, 31],\n\t\t\t\t\t\t\t [ 48, 49, 42, 55],\n\t\t\t\t\t\t\t [ 7, 26, 1, 32],\n\t\t\t\t\t\t\t [ 47, 50, 41, 56]\t\t\t\t\t\t\t \n\t\t\t\t\t\t ])\n elif (camera_version == 2):\n chmap = np.array([[61,47,26, 6],\n [62,48,25, 5],\n [63,45,28, 8],\n [64,46,27, 7],\n [36,51,12,24],\n [35,52,11,23],\n [34,49,10,22],\n [33,50, 9,21],\n [29, 1,58,41],\n [30, 2,57,42],\n [31, 3,60,43],\n [32, 4,59,44],\n [14,19,38,56],\n [13,20,37,55],\n [16,17,40,54],\n [15,18,39,53]\n ])\n else:\n raise ValueError(\"Version {:d} is not possible for camera type '{:s}'.\".format(camera_type))\n return np.transpose(chmap)\n elif (camera_type == \"8x16A\"):\n channel_map = np.ndarray((16,8),int)\n if (camera_version == 1):\n chmap = np.array([[ 91, 19, 14, 70, 76, 4, 29, 85],\n [ 20, 92, 69, 16, 3, 75, 86, 31],\n [ 17, 89, 13, 72, 2, 74, 30, 87],\n [ 18, 90, 15, 71, 1, 73, 32, 88],\n [ 56,128, 41, 97,103, 47,122, 50],\n [ 55,126, 42, 98,104, 45,121, 49],\n [127, 54, 43, 99, 48,101,124, 52],\n [ 53,125,100, 44,102, 46, 51,123],\n [ 59,115,110, 38,108, 36, 61,117],\n [116, 60, 37,112, 35,107,118, 63],\n [113, 57,109, 40, 34,106, 62,119],\n [114, 58,111, 39, 33,105, 64,120],\n [ 24, 96, 9, 65, 7, 79, 26, 82],\n [ 23, 94, 10, 66, 8, 77, 25, 81],\n [ 95, 22, 11, 67, 80, 5, 28, 84],\n [ 21, 93, 68, 12, 6, 78, 83, 27]\n ])\n else:\n raise ValueError(\"Version {:d} is not possible for camera type '{:s}'.\".format(camera_version,camera_type))\n return np.transpose(chmap)\n elif (camera_type == \"FC\"):\n np.arange(64,dtype=int) \n else:\n raise ValueError('Unknown camera type:\"{:s}\"'.format(camera_type))"
] | [
[
"numpy.arange",
"numpy.array",
"numpy.ndarray",
"numpy.transpose"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
RulerOf/keras-yolo3 | [
"8d091cf42b2f126626ad8610adf31293225b7daa"
] | [
"scripts/evaluate.py"
] | [
"\"\"\"\nEvaluation of predictions againsts given dataset (in TXT format the same as training).\nWe expect that the predictions are in single folder and image names in dataset are the same\n\n python evaluate.py \\\n --path_dataset ../model_data/VOC_2007_train.txt \\\n --path_results ../results \\\n --confidence 0.5 \\\n --iou 0.5 \\\n --visual\n\nIt generates\n* statistic per image (mean over all classes)\n* statistic per class (mean over all images)\n\nSee:\n- https://github.com/rafaelpadilla/Object-Detection-Metrics\n\"\"\"\n\nimport os\nimport sys\nimport argparse\nimport logging\nfrom functools import partial\nfrom pathos.multiprocessing import ProcessPool\n\nimport tqdm\nimport pandas as pd\n\nsys.path += [os.path.abspath('.'), os.path.abspath('..')]\nfrom keras_yolo3.utils import check_params_path, nb_workers, image_open, update_path\nfrom keras_yolo3.model import compute_detect_metrics\nfrom keras_yolo3.visual import draw_bounding_box\n\nCSV_NAME_RESULTS_IMAGES = 'detection-results_conf=%.2f_iou=%.2f_stat-images.csv'\nCSV_NAME_RESULTS_CLASSES = 'detection-results_conf=%.2f_iou=%.2f_stat-classes.csv'\nANNOT_COLUMNS = ('xmin', 'ymin', 'xmax', 'ymax', 'class')\n# DETECT_COLUMNS = ('xmin', 'ymin', 'xmax', 'ymax', 'class', 'confidence')\nTEMP_IMAGE_NAME = '%s_visual.jpg'\n\n\ndef parse_params():\n # class YOLO defines the default value, so suppress any default HERE\n parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)\n parser.add_argument('-d', '--path_dataset', type=str, required=True,\n help='path to the dataset, with single instance per line')\n parser.add_argument('-r', '--path_results', type=str, required=True,\n help='path to the predictions')\n parser.add_argument('-c', '--confidence', type=float, required=False, default=0.5,\n help='detection confidence score')\n parser.add_argument('--iou', type=float, required=False, default=0.5,\n help='intersection over union')\n parser.add_argument('--nb_jobs', type=float, help='number of parallel processes',\n default=0.9, required=False)\n parser.add_argument('--visual', default=False, action='store_true',\n help='visualize annot & predict')\n arg_params = vars(parser.parse_args())\n arg_params = check_params_path(arg_params)\n logging.debug('PARAMETERS: \\n %s', repr(arg_params))\n return arg_params\n\n\ndef draw_export_bboxes(img_path, path_out, bboxes_anot, bboxes_pred):\n img_name, _ = os.path.splitext(os.path.basename(img_path))\n image = image_open(img_path)\n\n for bb in bboxes_anot:\n image = draw_bounding_box(image, bb[4], bb[:4], swap_xy=True,\n color=(0, 255, 0), thickness=2)\n for bb in bboxes_pred:\n image = draw_bounding_box(image, bb[4], bb[:4], swap_xy=True,\n color=(255, 0, 0), thickness=2)\n\n name_visu = TEMP_IMAGE_NAME % img_name\n path_visu = os.path.join(update_path(path_out), name_visu)\n image.save(path_visu)\n return path_visu\n\n\ndef eval_image(line, path_results, thr_confidence=0.5, thr_iou=0.5, path_out=None):\n line_elems = line.strip().split()\n img_path = line_elems[0]\n img_name, _ = os.path.splitext(os.path.basename(img_path))\n\n path_pred = os.path.join(path_results, '%s.csv' % img_name)\n if not os.path.isfile(path_pred):\n return None\n\n boxes = [list(map(int, el.split(','))) for el in line_elems[1:]]\n df_annot = pd.DataFrame(boxes, columns=list(ANNOT_COLUMNS))\n if df_annot.empty:\n df_annot = pd.DataFrame(columns=ANNOT_COLUMNS)\n df_preds = pd.read_csv(path_pred, index_col=None)\n if df_preds.empty:\n df_preds = pd.DataFrame(columns=ANNOT_COLUMNS)\n\n # old version uses `score` instead `confidence`\n if 'confidence' not in df_preds.columns and 'score' in df_preds.columns:\n cols = df_preds.columns.tolist()\n idx = cols.index('score')\n df_preds.columns = cols[:idx] + ['confidence'] + cols[idx + 1:]\n # if confidence/score is defined, filter detections\n if 'confidence' in df_preds.columns:\n df_preds = df_preds[df_preds['confidence'] >= thr_confidence]\n # if class detection is not defined, assume everything as 0\n if 'class' not in df_preds.columns:\n df_preds['class'] = 0\n # in case one of DF does not have required columns skip it...\n all_cols_in_annot = all([c in df_annot.columns for c in ANNOT_COLUMNS])\n all_cols_in_pred = all([c in df_preds.columns for c in ANNOT_COLUMNS])\n if not (all_cols_in_annot and all_cols_in_pred):\n return None\n\n stats = compute_detect_metrics(df_annot[list(ANNOT_COLUMNS)], df_preds[list(ANNOT_COLUMNS)],\n iou_thresh=thr_iou)\n\n if path_out and os.path.isdir(path_out):\n draw_export_bboxes(img_path, path_out,\n df_annot[list(ANNOT_COLUMNS)].values,\n df_preds[list(ANNOT_COLUMNS)].values)\n\n # stats['name'] = img_name\n return stats\n\n\ndef _main(path_dataset, path_results, confidence, iou, visual=False, nb_jobs=0.9):\n with open(path_dataset, 'r') as fp:\n dataset = fp.readlines()\n\n if not dataset:\n logging.warning('Dataset is empty - %s', path_dataset)\n return\n\n nb_jobs = nb_workers(nb_jobs)\n pool = ProcessPool(nb_jobs) if nb_jobs > 1 else None\n _wrap_eval = partial(eval_image, path_results=path_results,\n thr_confidence=confidence, thr_iou=iou,\n path_out=path_results if visual else None)\n # multiprocessing loading of batch data\n map_process = pool.imap if pool else map\n\n results_image, results_class = [], []\n for stat in tqdm.tqdm(map_process(_wrap_eval, dataset), desc='Evaluation'):\n if not stat:\n continue\n results_image.append(dict(pd.DataFrame(stat).mean()))\n results_class += stat\n\n df_results_image = pd.DataFrame(results_image)\n logging.info(df_results_image.describe())\n path_csv = os.path.join(path_results, CSV_NAME_RESULTS_IMAGES % (confidence, iou))\n logging.debug('exporting csv: %s', path_csv)\n df_results_image.to_csv(path_csv)\n\n df_results_class = pd.DataFrame()\n for gr, df_gr in pd.DataFrame(results_class).groupby('class'):\n df_results_class = df_results_class.append(df_gr.mean(), ignore_index=True)\n logging.info(df_results_class)\n path_csv = os.path.join(path_results, CSV_NAME_RESULTS_CLASSES % (confidence, iou))\n logging.debug('exporting csv: %s', path_csv)\n df_results_class.to_csv(path_csv)\n\n\nif __name__ == '__main__':\n logging.basicConfig(level=logging.INFO)\n pd.set_option(\"display.max_columns\", 25)\n arg_params = parse_params()\n _main(**arg_params)\n logging.info('Done')\n"
] | [
[
"pandas.set_option",
"pandas.read_csv",
"pandas.DataFrame"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
b2-hive/CONTRE | [
"9176861400fcc5887d8a8944ee2c636ba09aa239"
] | [
"contre/training.py"
] | [
"import root_pandas\nimport basf2_mva\nimport b2luigi\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\n\n\ndef split_sample(\n ntuple_file,\n train_size,\n test_size,\n random_seed=42):\n \"\"\"Split rootfile and return dataframes. Select 0th candidate.\"\"\"\n df = root_pandas.read_root(ntuple_file)\n try:\n train, test = train_test_split(\n df,\n test_size=test_size,\n train_size=train_size,\n random_state=random_seed)\n except ValueError:\n print(\n \"The dataframe was too small, the test and train sample are empty\")\n empty = {col: [] for col in df.columns}\n test = pd.DataFrame(empty)\n train = pd.DataFrame(empty)\n if train.get(\"__candidate__\") is not None:\n train = train[train[\"__candidate__\"] == 0]\n return train, test\n\n\nclass SplitSample(b2luigi.Task):\n \"\"\"Split a ntuple file to a training and test sample of given size.\n\n Shuffle events and create a random selected train and test sample.\n The function sklearn.utils.resample is used.\n Store samples as rootfiles (used by fastBDT).\n\n Parameters:\n ntuple_file (str): Path to the file\n train_size (float): between 0 and 1, size of train sample\n test_size (float): size of test sample\n \"\"\"\n ntuple_file = b2luigi.Parameter(hashed=True)\n tree_name = b2luigi.Parameter()\n train_size = b2luigi.FloatParameter()\n test_size = b2luigi.FloatParameter()\n queue = \"sx\"\n\n def output(self):\n yield self.add_to_output('train.root')\n yield self.add_to_output('test.root')\n\n def run(self):\n train, test = split_sample(\n ntuple_file=self.ntuple_file,\n train_size=self.train_size,\n test_size=self.test_size)\n\n # Store as Rootfile\n root_pandas.to_root(\n train, self.get_output_file_name('train.root'), key=self.tree_name)\n root_pandas.to_root(\n test, self.get_output_file_name('test.root'), key=self.tree_name)\n\n\nclass Training(b2luigi.Task):\n \"\"\"Train a fastBDT on train samples of the given off-resonance files and\n save bdt_weightfile to `bdt.xml`.\n\n Parameters:\n off_res_files (list): list of off-resonance files to be used for\n training,\n tree_name (str): name of the tree in the root file,\n training_variables (list): variables used for training,\n If you have multiple candidates in your selection, be aware that\n only the 0th candidate is used for training.\n This does not have any effect, if you only use event-based\n variables for training.\n training_parameters (dict): train- and test size,\n the following BDT hyper-parameters (optional): \"nTrees\",\n \"shrinkage\" and \"nLevels\".\n \"\"\"\n off_res_files = b2luigi.ListParameter(hashed=True)\n tree_name = b2luigi.ListParameter()\n training_variables = b2luigi.ListParameter(hashed=True)\n training_parameters = b2luigi.DictParameter(hashed=True)\n queue = \"sx\"\n\n def requires(self):\n train_size = self.training_parameters[\"train_size\"]\n test_size = self.training_parameters[\"test_size\"]\n\n for ntuple_file in self.off_res_files:\n yield self.clone(\n SplitSample,\n ntuple_file=ntuple_file,\n train_size=train_size,\n test_size=test_size)\n\n def output(self):\n yield self.add_to_output('bdt.xml')\n\n def run(self):\n bdt = self.get_output_file_name('bdt.xml')\n train_samples = self.get_input_file_names('train.root')\n\n # bdt options\n general_options = basf2_mva.GeneralOptions()\n general_options.m_datafiles = basf2_mva.vector(*train_samples)\n general_options.m_identifier = bdt\n general_options.m_treename = self.tree_name\n general_options.m_variables = basf2_mva.vector(\n *self.training_variables)\n general_options.m_target_variable = \"EventType\"\n\n fastbdt_options = basf2_mva.FastBDTOptions()\n training_parameters = self.training_parameters\n if training_parameters.get(\"nTrees\") is not None:\n fastbdt_options.m_nTrees = training_parameters[\"nTrees\"]\n if training_parameters.get(\"shrinkage\") is not None:\n fastbdt_options.m_shrinkage = training_parameters[\"shrinkage\"]\n if training_parameters.get(\"nLevels\") is not None:\n fastbdt_options.m_nLevels = training_parameters[\"nLevels\"]\n if training_parameters.get(\"nCuts\") is not None:\n fastbdt_options.m_nCuts = training_parameters[\"nCuts\"]\n\n # teacher\n basf2_mva.teacher(general_options, fastbdt_options)\n"
] | [
[
"sklearn.model_selection.train_test_split",
"pandas.DataFrame"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
masonng-astro/nicerpy_xrayanalysis | [
"c21c7c9bc5570c63c986197fb363ae80691515d5",
"c21c7c9bc5570c63c986197fb363ae80691515d5",
"c21c7c9bc5570c63c986197fb363ae80691515d5",
"c21c7c9bc5570c63c986197fb363ae80691515d5",
"c21c7c9bc5570c63c986197fb363ae80691515d5"
] | [
"Lv3_presto_candidates.py",
"Lv3_Z2_stat.py",
"Lv3_incoming.py",
"Lv2_presto_subroutines.py",
"take_at2018cow_candidates.py"
] | [
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jul 5 1:28pm 2019\n\nScript to automate getting pulsation candidates of a certain frequency range,\nand reporting other germane information?\n\n\"\"\"\nfrom __future__ import division, print_function\nimport numpy as np\nfrom scipy import stats, signal\nfrom tqdm import tqdm\nimport matplotlib.pyplot as plt\nfrom astropy.io import fits\nimport glob\nimport Lv0_dirs\n\nLv0_dirs.global_par()\n\ndef get_candidates(obsid,name_par_list,zmax,f1,f2):\n \"\"\"\n Getting pulsation candidates within some frequency range. If I want the full\n frequency range, just do f1 = 0, f2 = some large number.\n\n obsid - Observation ID of the object of interest (10-digit str)\n name_par_list - list of parameters specifying parameters like GTI number and/or energy range\n zmax - maximum acceleration\n f1 - lower limit of frequency range\n f2 - upper limit of frequency range\n\n name_par_list should be [GTI_true,E_true,GTIno,segment_length,PI1,PI2]\n \"\"\"\n if type(obsid) != str:\n raise TypeError(\"ObsID should be a string!\")\n if type(name_par_list) != list and type(name_par_list) != np.ndarray:\n raise TypeError(\"name_par_list should either be a list or an array!\")\n if len(name_par_list) != 6:\n raise ValueError(\"There seems to be fewer or more values in the list/array than there should be! You should have [GTI_true, E_true, GTIno, segment length, PI1, PI2]\")\n\n header1 = \" Summed Coherent Num Period Frequency FFT 'r' Freq Deriv FFT 'z' Accel \"\n header2 = \" Power / Raw FFT 'r' Pred 'r' FFT 'z' Pred 'z' Phase Centroid Purity \"\n\n obsid_file = Lv0_dirs.NICERSOFT_DATADIR + obsid + '_pipe/ni' + obsid + '_nicersoft_bary.evt'\n header_card = fits.open(obsid_file)[0].header\n date_obs = str(header_card['DATE-OBS'])\n date_end = str(header_card['DATE-END'])\n tstart = str(header_card['TSTART'])\n tstop = str(header_card['TSTOP'])\n\n if name_par_list[0] == True and name_par_list[1] == False: #if we're looking at just time segments!\n working_dir = Lv0_dirs.NICERSOFT_DATADIR + obsid + '_pipe/accelsearch_' + str(name_par_list[3]) + 's/'\n ACCEL_files = sorted(glob.glob(working_dir+'*_' + str(name_par_list[3]) + 's_ACCEL_' + str(zmax)))\n cands_txt = open(working_dir+'candidates_'+str(name_par_list[3])+'s_raw.txt','w')\n cands_txt.write('ObsID Start-date/time-of-obs End-date/time-of-obs MET_start MET_end seg_no MET_centroid Cand_No Sigma Frequency Freq_Deriv z Acceleration' + '\\n')\n \"\"\"\n JULY 8: Got to edit the below as appropriate! Mainly got to think about how to replace seg_no!\n ACTUALLY, BREAK THIS UP INTO 3 SEPARATE FUNCTIONS! Integrate into Lv3_presto_main as well...\n elif name_par_list[0] == False and name_par_list[1] == True: #if we're looking at just energy segments!\n working_dir = Lv0_dirs.NICERSOFT_DATADIR + obsid + '_pipe/'\n ACCEL_files = sorted(glob.glob(working_dir+'*E'+str(name_par_list[4]) + '-' + str(name_par_list[5])))\n cands_txt = open(working_dir+'candidates_raw.txt','w')\n cands_txt.write('ObsID Start-date/time-of-obs End-date/time-of-obs MET_start MET_end seg_no MET_centroid Cand_No Sigma Frequency Freq_Deriv z Acceleration' + '\\n')\n else: #if we're looking at BOTH time AND energy segments!\n working_dir = Lv0_dirs.NICERSOFT_DATADIR + obsid + '_pipe/accelsearch_' + str(name_par_list[3]) + 's/'\n ACCEL_files = sorted(glob.glob(working_dir+'*_' + str(name_par_list[3]) + 's_ACCEL_' + str(zmax)))\n cands_txt = open(working_dir+'candidates_raw.txt','w')\n cands_txt.write('ObsID Start-date/time-of-obs End-date/time-of-obs MET_start MET_end seg_no MET_centroid Cand_No Sigma Frequency Freq_Deriv z Acceleration' + '\\n')\n \"\"\"\n for i in range(len(ACCEL_files)):\n accel_textfile = np.array(open(ACCEL_files[i],'r').read().split('\\n')) #read the data from the ACCEL_$zmax files\n index_header1 = np.where(accel_textfile==header1)[0][0] #index for \"Summed, Coherent, Num, Period etc\n index_header2 = np.where(accel_textfile==header2)[0][0] #index for \"Power / Raw FFT 'r' etc\n no_cands = index_header2 - index_header1 - 5 #to obtain number of candidates\n\n segment_no = '0004'\n MET_centroid = '141080121.942' #test\n candidates = np.genfromtxt(ACCEL_files[i],dtype='str',skip_header=3,usecols=(0,1,6,8,9,10),unpack=True,max_rows=no_cands)\n if len(candidates) == candidates.size: #meaning if there's ONE pulsation candidate in the *ACCEL_$zmax file\n if (np.float(candidates[2][:-3]) > f1) and (np.float(candidates[2][:-3]) < f2):\n cands_txt.write(obsid + ' ' + date_obs + ' ' + date_end + ' ' + tstart + ' ' + tstop + ' ' + segment_no + ' ' + MET_centroid + ' ' + candidates[0].zfill(4) + ' ' + candidates[1] + ' ' + candidates[2] + ' ' + candidates[3] + ' ' + candidates[4] + ' ' + candidates[5] + '\\n')\n else: #if there are multiple pulsation candidates in the *ACCEL_$zmax file\n for j in range(candidates.shape[1]): #for EACH pulsation candidate\n if (np.float(candidates[2][j][:-3]) > f1) and (np.float(candidates[2][j][:-3]) < f2):\n cands_txt.write(obsid + ' ' + date_obs + ' ' + date_end + ' ' + tstart + ' ' + tstop + ' ' + segment_no + ' ' + MET_centroid + ' ' + candidates[0][j].zfill(4) + ' ' + candidates[1][j] + ' ' + candidates[2][j] + ' ' + candidates[3][j] + ' ' + candidates[4][j] + ' ' + candidates[5][j] + '\\n')\n\nif __name__ == \"__main__\":\n get_candidates('1200250101',[True,False,0,64,0,0],100,0,100)\n",
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thurs Oct 24th 9:54am 2019\n\nCalculates the Z^2 statistic given a list of ObsIDs, where the event files\nmust already have 'PULSE_PHASE' in them! The input will be a par file. Will also\nhave a way to iterate through a grid of orbital parameters.\n\n\"\"\"\nfrom __future__ import division, print_function\nfrom astropy.io import fits\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom pint.eventstats import sf_z2m,z2m,sig2sigma\nimport subprocess\nfrom tqdm import tqdm\nimport glob\nimport os,shutil\nimport Lv0_dirs,Lv2_mkdir\n\nLv0_dirs.global_par()\n\ndef get_Z2(obsid,model,par_file,m):\n \"\"\"\n Calculates the Z^2 statistic given the ObsID, binary model name (if there's one),\n and the parameter file.\n\n obsid - Observation ID of the object of interest (10-digit str)\n model - binary model being used (ELL1, BT, DD, or DDK for now)\n par_file - orbital parameter file for input into PINT's photonphase\n m - number of harmonics\n \"\"\"\n filename = Lv0_dirs.NICERSOFT_DATADIR + obsid + '_pipe/cleanfilt_phase'\n if model == '':\n filename = filename + '.evt'\n if model != 'ELL1' and model != 'BT' and model != 'DD' and model != 'DDK':\n raise ValueError(\"The model should be one of ELL1, BT, DD, or DDK! Update if a new model has been added to PINT.\")\n else:\n filename = filename + '_' + model + '.evt'\n\n event = fits.open(filename)\n if 'PULSE_PHASE' not in event[1].columns.names:\n raise ValueError('The PULSE_PHASE column is not in the PINT-processed event file! Check your steps again.')\n\n phases = event[1].data['PULSE_PHASE']\n z_vals = z2m(phases,m=m)\n probs = sf_z2m(z_vals)\n significances = sig2sigma(probs)\n\n return significances\n\ndef get_merged(merged_id,obsids,model,par_file,m,ratecut):\n \"\"\"\n Given the list of ObsIDs, make the merged file!\n Will have all the outputs of merge.py in the merged_id folder.\n\n merged_id - 6-digit ID for the merged event file\n obsids - list (or array) of ObsIDs\n model - binary model being used (ELL1, BT, DD, or DDK for now)\n par_file - orbital parameter file for input into PINT's photonphase\n m - number of harmonics\n ratecut - count rate cut in cts/s for cr_cut.py!\n \"\"\"\n if type(obsids) != list and type(obsids) != np.ndarray:\n raise TypeError(\"obsids should either be a list or an array!\")\n if type(merged_id) != str:\n raise TypeError(\"merged_id should be a string!\")\n if len(merged_id) != 6:\n raise ValueError(\"merged_id should have 6 digits in the string!\")\n\n merged_dir = Lv0_dirs.NICERSOFT_DATADIR + 'merged_events/merged' + merged_id + '/'\n Lv2_mkdir.makedir(merged_dir)### making directory for the merged_id\n\n ### create a text file which lists all the cleanfilt event files with PULSE_PHASE!\n cleanfilt_files = open(merged_dir + 'merged' + merged_id + '.txt','w')\n orb_files = open(merged_dir + 'merged' + merged_id + '_orb.txt','w')\n for i in range(len(obsids)):\n filename = Lv0_dirs.NICERSOFT_DATADIR + obsids[i] + '_pipe/cleanfilt_phase'\n if model == '':\n filename = filename + '.evt'\n if model != 'ELL1' and model != 'BT' and model != 'DD' and model != 'DDK':\n raise ValueError(\"The model should be one of ELL1, BT, DD, or DDK! Update if a new model has been added to PINT.\")\n else:\n filename = filename + '_' + model + '.evt'\n cleanfilt_files.write(filename + '\\n')\n\n orbs_filename = Lv0_dirs.NICERSOFT_DATADIR + obsids[i] + '_pipe/ni' + obsids[i] + '.orb'\n orb_files.write(orbs_filename + '\\n')\n\n cleanfilt_files.close()\n orb_files.close()\n\n ##### merging the files with merge.py\n infile = '@' + merged_dir + 'merged' + merged_id + '.txt'\n outroot = 'merged' + merged_id\n outdir = merged_dir\n orb = merged_dir + 'merged' + merged_id + '_orb.txt'\n\n subprocess.check_call(['merge.py',infile,outroot,outdir,'--par',par_file,'--orb',orb,'--cut','--cut_rate',str(ratecut)])\n #####\n\n return\n\ndef get_Z2(eventfile,m):\n \"\"\"\n Calculate the Z^2 significances given the event file and harmonic number m\n\n eventfile - name of event file\n m - number of harmonics\n \"\"\"\n phases = fits.open(eventfile)[1].data['PULSE_PHASE']\n\n z_vals = z2m(phases,m=m)\n probs = sf_z2m(z_vals)\n significances = sig2sigma(probs)\n\n return significances\n\ndef niextract(eventfile,E1,E2):\n \"\"\"\n Doing energy cuts only for the rate cut event file!\n\n eventfile - event file name\n E1 - lower energy bound (should be in a 4-digit PI string)\n E2 - upper energy bound (should be in a 4-digit PI string)\n \"\"\"\n new_event = eventfile[:-4] + '_' + E1 + '-' + E2 + '.evt'\n subprocess.check_call(['niextract-events',eventfile+'[PI='+str(int(E1))+':'+str(int(E2))+']',new_event])\n\n return\n\ndef edit_par(par_file,var_dict):\n \"\"\"\n Editing the input par file with updated parameter values in the form of a\n dictionary. Each key will have 1 value though.\n\n par_file - orbital parameter file for input into PINT's photonphase\n var_dict - dictionary, where each key corresponds to a variable to change in the par file, and has a 1-entry list!\n \"\"\"\n dict_keys = var_dict.keys() #the variables that we want to iterate over\n new_par = par_file[:-4] + '_iter.par'\n\n line_no_dict = {}\n contents = open(par_file,'r').read().split('\\n')\n for i in range(len(dict_keys)):\n line_no = [j for j in range(len(contents)) if dict_keys[i] in contents[j]][0] #finding indices for the variables we want to iterate over\n line_no_dict[dict_keys[i]] = [line_no] #dictionary key corresponds to a 1-entry list\n\n output_par = open(new_par,'w')\n for i in range(len(contents)):\n if contents[i].split(' ')[0] in dict_keys: #so if we reach a line corresponding to a variable we're iterating over\n output_par.write(contents[i].split(' ')[0] + ' '*10 + str(var_dict[contents[i].split(' ')[0]][0]) + '\\n')\n else:\n output_par.write(contents[i] + '\\n')\n output_par.close()\n\n return\n\ndef call_photonphase(obsid,model,par_file):\n \"\"\"\n Calls photonphase from PINT to calculate the phase value for each event.\n\n obsid - Observation ID of the object of interest (10-digit str)\n model - binary model being used (ELL1, BT, DD, or DDK for now)\n par_file - orbital parameter file for input into PINT's photonphase\n \"\"\"\n filename = Lv0_dirs.NICERSOFT_DATADIR + obsid + '_pipe/cleanfilt.evt'\n orbfile = Lv0_dirs.NICERSOFT_DATADIR + obsid + '_pipe/ni' + obsid + '.orb'\n\n if model == '':\n outfile_name = filename[:-4] + '_phase.evt'\n if model != 'ELL1' and model != 'BT' and model != 'DD' and model != 'DDK':\n raise ValueError(\"The model should be one of ELL1, BT, DD, or DDK! Update if a new model has been added to PINT.\")\n else:\n outfile_name = filename[:-4] + '_phase_' + model + '.evt'\n\n subprocess.check_call(['photonphase',filename,par_file,'--orbfile',orbfile,'--addphase','--barytime','--outfile',outfile_name])\n\n return\n\nif __name__ == \"__main__\":\n #print(get_Z2('1030180105','BT','',2))\n E_cut = [True,'0035','0150']\n obsids = ['2060060' + str(i) for i in range(351,372)]\n par_file = Lv0_dirs.NICERSOFT_DATADIR + 'J1231-1411_paul.par'\n #print(get_Z2_merged('000009',obsids,'ELL1',parfile,2))\n merged_id = '000012'\n source = 'J1231-1411'\n var = 'F0'\n merged_dir = Lv0_dirs.NICERSOFT_DATADIR+'/merged_events/merged' + merged_id\n m = 2 #harmonic number\n model = 'ELL1'\n\n #A1 = [round(i,2) for i in np.arange(2.03,2.05,0.01)]\n #PB = []\n F0 = [round(i,5) for i in np.arange(271.45295,271.45305,0.00001)]\n #TASC = []\n\n for i in tqdm(range(len(F0))): #for each TRIAL frequency\n if os.path.exists(merged_dir):\n shutil.rmtree(merged_dir) #so that I don't get millions of these folders!\n #If I want to get the optimized one, I can re-do them once I get the optimized set of parameters.\n edit_par(par_file,{'F0':[F0[i]]}) #change the parameter file\n for j in range(len(obsids)): #for each ObsID in the intended merge set\n call_photonphase(obsids[j],model,par_file[:-4]+'_iter.par') #call the iterated par file\n get_merged(merged_id,obsids,model,par_file[:-4]+'_iter.par',m,2.5)\n\n if E_cut[0] == False:\n merged_file = merged_dir + '/merged' + merged_id + '.evt'\n cut_merged_file = merged_dir + '/merged' + merged_id + '_cut.evt'\n new_merged_file = Lv0_dirs.NICERSOFT_DATADIR + source + '_' + var + '/merged' + merged_id + '_' + var + '_' + str(F0[i]) +'.evt'\n new_cut_file = Lv0_dirs.NICERSOFT_DATADIR + source + '_' + var + '/merged' + merged_id + '_cut_' + var + '_' + str(F0[i]) + '.evt'\n\n subprocess.check_call(['cp',merged_file,new_merged_file])\n subprocess.check_call(['cp',cut_merged_file,new_cut_file])\n\n else:\n original_cut = merged_dir + '/merged' + merged_id + '_cut.evt'\n cut_merged_file = original_cut[:-4] + '_' + E_cut[1] + '-' + E_cut[2] + '.evt'\n new_cut_file = Lv0_dirs.NICERSOFT_DATADIR + source + '_' + var + '/merged' + merged_id + '_cut_' + E_cut[1] + '-' + E_cut[2] + '_' + var + '_' + str(F0[i]) + '.evt'\n niextract(original_cut,E_cut[1],E_cut[2])\n\n subprocess.check_call(['cp',cut_merged_file,new_cut_file])\n\n Z2_table = open(Lv0_dirs.NICERSOFT_DATADIR + source + '_' + var + '.txt','w')\n for i in tqdm(range(len(F0))):\n if E_cut[0] == False:\n eventfile = Lv0_dirs.NICERSOFT_DATADIR + source + '_' + var + '/merged' + merged_id + '_cut_' + var + '_' + str(F0[i]) + '.evt'\n else:\n eventfile = Lv0_dirs.NICERSOFT_DATADIR + source + '_' + var + '/merged' + merged_id + '_cut_' + E_cut[1] + '-' + E_cut[2] + '_' + var + '_' + str(F0[i]) + '.evt'\n Z2_table.write('F0: ' + str(F0[i]) + ', Z^2 = ' + str(get_Z2(eventfile,m)) + '\\n')\n Z2_table.close()\n\n #throw event files into /NICERSOFT_DATADIR/J1231-1411_F0/ or something!\n",
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sunday Feb 16 4:25pm 2020\n\nPerforming pulsation search techniques on incoming data beyond quicklook but before archival.\n\nDon't need to search for burst candidates here - already have it in Lv3_TBOs.py!\n\nPretty similar to Lv3_quicklook.py, but takes as input a list of NICER observation directories.\n- semi-coherent searches\n\n\"\"\"\nfrom __future__ import division, print_function\nfrom astropy.io import fits\nimport numpy as np\nimport pathlib\nimport Lv0_dirs,Lv0_fits2dict,Lv0_scp\nimport Lv1_barycorr\nimport Lv2_preprocess,Lv2_lc,Lv2_ps,Lv2_color,Lv2_phase,Lv2_efsearch,Lv2_TBOs_method,Lv2_merging_events,Lv2_average_ps_methods,Lv2_presto_subroutines\nimport Lv3_E_boundary,Lv3_detection_level\nfrom matplotlib.backends.backend_pdf import PdfPages\nimport time\nimport matplotlib.pyplot as plt\nimport os\nfrom tqdm import tqdm\nimport subprocess\nimport glob\nimport time\n\nLv0_dirs.global_par() #obtaining the global parameters\n\nstart_time = time.time()\n\ndef nicerql(eventfile,extra_nicerql_args):\n \"\"\"\n Probably the second step in the process, but this is to generate the psrpipe\n diagnostic plots, to see if there are any obvious red flags in the data.\n\n Will just really need eventfile ; orb file and mkf file is assumed to be in the SAME folder\n\n eventfile - path to the event file. Will extract ObsID from this for the NICER files.\n extra_nicerql_args - extra arguments to the nicerql script\n \"\"\"\n parent_folder = str(pathlib.Path(eventfile).parent)\n orbfiles = glob.glob(parent_folder+'/*.orb')\n mkffiles = glob.glob(parent_folder+'/*.mkf*')\n if len(orbfiles) != 1 and len(mkffiles) != 1:\n raise ValueError(\"Either there's no orb/mkf file (in which case, make sure they're in the same folder as the event file!) or there are multiple files - do check!\")\n\n logfile = parent_folder + '/nicerql.log'\n print('Running nicerql now for ' + eventfile + ':')\n with open(logfile,'w') as logtextfile:\n output = subprocess.run(['nicerql.py',eventfile,'--orb',orbfiles[0],'--mkf',mkffiles[0]] + extra_nicerql_args,capture_output=True,text=True)\n logtextfile.write(output.stdout)\n logtextfile.write('*------------------------------* \\n')\n logtextfile.write(output.stderr)\n logtextfile.close()\n\n png_files = glob.glob('*evt*png')\n for i in range(len(png_files)):\n subprocess.run(['mv',png_files[i],parent_folder+'/'])\n\n return\n\ndef filtering(eventfile,outfile,maskdet,eventflags,rm_artifacts):\n \"\"\"\n Function that will filter out bad detectors and impose eventflag restrictions.\n Will expect to add to this function over time...\n\n eventfile - path to the event file. Will extract ObsID from this for the NICER files.\n outfile - output file from the filtering\n maskdet - list of DET_IDs to mask\n eventflags - NICER event flags to filter out (e.g., in the format '(EVENT_FLAGS==bx1x000)')\n rm_artifacts - a list of [start,end,start,end] times (specified in intervals) to REMOVE!\n Artifacts are defined as whatever you want to remove. Bursts are considered artifacts in the sense\n that they are not part of the persistent emission.\n \"\"\"\n outfile_parent_folder = str(pathlib.Path(outfile).parent)\n\n evfilt_expr = eventflags\n for i in range(len(maskdet)):\n evfilt_expr += '.and.(DET_ID!='+str(maskdet[i]) + ')'\n\n if len(rm_artifacts) != 0:\n intfile = outfile_parent_folder + '/intermediate_filt.evt'\n subprocess.run(['ftcopy',eventfile+'['+evfilt_expr+']',intfile,'clobber=yes','history=yes'])\n\n gtis = list(fits.open(intfile)[2].data)\n rm_artifacts = fits.open(intfile)[2].data['START'][0]+np.array(open( str(pathlib.Path(eventfile).parent)+'/rm_artifacts.txt','r').read().split('\\n')[:-1],dtype=np.float64)\n\n ### To identify GTIs that are not part of the artifacts (or bursts)\n gtis_remove = []\n print('Removing GTIs...')\n for i in tqdm(range(len(gtis))):\n for j in range(0,len(rm_artifacts)-1,2):\n if (gtis[i][0] >= rm_artifacts[j]) and (gtis[i][1] <= rm_artifacts[j+1]):\n gtis_remove.append(gtis[i])\n\n new_gtis = []\n print('Getting new GTIs...')\n for i in tqdm(range(len(gtis))):\n if gtis[i] not in np.array(gtis_remove):\n new_gtis.append(gtis[i])\n ###\n\n gtitxt = open(outfile_parent_folder + '/filtered_gtis.txt','w')\n for i in range(len(new_gtis)):\n gtitxt.write(str(new_gtis[i][0]) + ' ' + str(new_gtis[i][1]) + '\\n')\n gtitxt.close()\n\n gti_col_file = Lv0_dirs.NICER_DATADIR + 'gti_columns.txt'\n gti_header_file = Lv0_dirs.NICER_DATADIR + 'gti_header.txt'\n ftcreate_cmd = ['ftcreate',gti_col_file,outfile_parent_folder+'/filtered_gtis.txt',outfile_parent_folder+'/final_filtered.gti','headfile='+gti_header_file,'extname=\"GTI\"','clobber=yes']\n subprocess.run(ftcreate_cmd)\n\n subprocess.run(['niextract-events',intfile,outfile,'timefile='+outfile_parent_folder+'/final_filtered.gti'])\n\n else:\n subprocess.run(['ftcopy',eventfile+'['+evfilt_expr+']',outfile,'clobber=yes','history=yes'])\n\nif __name__ == \"__main__\":\n #eventfile = '/Volumes/Samsung_T5/NICER-data/maxij0556/2004131927.evt'\n #eventfile = Lv0_dirs.NICER_DATADIR + 'at2019wey/2008041401.evt'\n eventfile = Lv0_dirs.NICER_DATADIR + 'igrj17494-3030/2010270036.evt'\n #eventfile = Lv0_dirs.NICER_DATADIR + 'xtej1739_mostrec/2002131540.evt'\n\n############################# DIAGNOSTIC PARAMETERS ############################\n do_diagnostic = False\n extra_nicerql_args = ['--save','--emin','1.0','--emax','10']\n################################################################################\n\n############################# BARYCORR PARAMETERS ##############################\n do_bary = True\n #out_baryfile = Lv0_dirs.NICER_DATADIR + 'xtej1739_mostrec/2002131540_filt_bary.evt'\n out_baryfile = Lv0_dirs.NICER_DATADIR + 'igrj17494-3030/2010270036_bary.evt'\n #out_baryfile = Lv0_dirs.NICER_DATADIR + 'at2019wey/2008041401_filt_bary.evt'\n refframe = 'ICRS'\n #orbitfile = Lv0_dirs.NICER_DATADIR + 'maxij0556/2004131927.orb'\n orbitfile = Lv0_dirs.NICER_DATADIR + 'igrj17494-3030/2010270036.orb'\n #orbitfile = Lv0_dirs.NICER_DATADIR + 'at2019wey/2008041401.orb'\n parfile = ''\n output_folder = Lv0_dirs.NICER_DATADIR + 'igrj17494-3030/'\n #output_folder = Lv0_dirs.NICER_DATADIR + 'maxij0556/'\n #output_folder = Lv0_dirs.NICER_DATADIR + 'at2019wey/'\n custom_coords = np.array([])\n################################################################################\n\n############################# FILTERING PARAMETERS #############################\n do_filter = False\n if do_filter == True:\n filtfile = '/Volumes/Samsung_T5/NICER-data/at2019wey/2008041401_bary.evt'\n maskdets = [34,43]\n eventflags = '(EVENT_FLAGS==bx1x000)'\n\n timezero = fits.open(eventfile)[2].data['START'][0]\n rm_artifacts = timezero + np.array(open(str(pathlib.Path(eventfile).parent)+'/rm_artifacts.txt','r').read().split('\\n')[:-1],dtype=np.float64)\n################################################################################\n\n######################### LC_PS_PHASE_COLOR PARAMETERS #########################\n do_lc_ps_phase_color = False\n##### fill out the parameters below ; there are quite a number\n################################################################################\n\n############################### PRESTO PARAMETERS ##############################\n do_presto = True\n if do_presto == True:\n conv_fits2presto = False #only for process_all\n process_all = False #whether to process the ENTIRE observation or not\n\n preprocess_segments = True #whether to get GTI files, run niextract, edit_inf, edit_binary, nicerfits2presto\n process_segments = True #whether to make truncations to the data\n\n time_segments = False #truncate by time segments\n gti_segments = False #truncate by GTI segments\n gti_energy_segments = False #truncate by GTI AND energy range\n energy_segments = True #truncate by energy range\n time_energy_segments = False #truncate both by time segments and energy range\n\n accelsearch = True\n prepfold = True\n\n ### for gti_segments\n gap = 11 #seconds\n gtifile = 'bunched.gti'\n\n tbin = '0.0002' #time bin for PRESTO in seconds\n\n ##### For when we analyze the entire data set (no truncations in energy or time)\n accelsearch_flags = ['-numharm','4','-zmax','100','-photon','-flo','1','-fhi','1000']\n\n ##### Parameters for prepfold\n zmax = 100\n\n ##### From Lv2_presto_subroutines\n segment_lengths = ['GTI'] #desired length of segments in seconds\n PI1 = [100]\n PI2 = [1000]\n################################################################################\n\n############################ AVERAGE_PS PARAMETERS #############################\n do_average_ps = False\n if do_average_ps == True:\n demod = False\n preprocessing = True #getting GTIs, running niextract, nicerfits2presto, edit_inf, edit_bin, and realfft!\n time_segments = False\n time_energy_segments = True\n mode = 't'\n segment_lengths = [64] #desired length of segments in seconds\n PI1 = [100]\n PI2 = [1000]\n #t1 = [0,3315000,3500000,3615000,3860000,4045000,4295000,4430000]\n #t2 = [0,3490000,3605000,3850000,4040000,4290000,4420000,4695000]\n t1 = [0]\n t2 = [0]\n par_file = ''\n tbin = 0.0002 #bin size in s\n threshold = [100] #threshold for counts in each segment (in 1s bins; in terms of a percentage)\n W = [1] #number of consecutive Fourier bins to average over\n hist_min_sig = 2.5\n starting_freq = 10 #for the noise histogram\n xlims = np.array([0.01,1000])\n plot_mode = \"save\"\n\n################################################################################\n\n############################# SEARCH_BIN PARAMETERS ############################\n##### SIDEBAND SEARCHES\n do_searchbin = False\n fft_files = eventfile[:-3] + 'fft'\n ncand = 1000 #no. of candidates to try to return ; default 100 (1 to 1000)\n flo = 1 #the lowest frequency to check\n fhi = 1000 #the highest frequency to check\n overlap = 0.05\n extra_args = []\n################################################################################\n\n############################# EF_SEARCH PARAMETERS #############################\n##### EPOCH FOLDING\n do_efsearch = False\n if do_efsearch == True:\n n_segments = 100 #number of segments to break the epoch folding search into\n dper = 4.80 #Value for the period used in the folding. In 'efsearch' the\n #input period represents the centre of the range of the trial periods.\n nphase = 32 #Number of phases in the folded light curve(s). Typing 'INDEF'\n #forces the task to use the default value (see parameter \"nbdf\").\n nper = 64 #The number of periods over which the search is carried out\n dres = 1E-4 # The period resolution is the spacing between two contiguous periods in the search.\n #'INDEF' uses the default value of: half the Fourier resolution in the interval (e.g., P^2/T(i)/2 ; T(i) is interval duration)\n plot_efsearch = 'no' #to plot the results from efsearch ; do \"exit\" to see the next plot!\n\n################################################################################\n\n if do_diagnostic == True:\n ##### Quick look at diagnostic plots\n nicerql(eventfile,extra_nicerql_args)\n\n if do_bary == True:\n if do_filter == True:\n Lv1_barycorr.barycorr(eventfile,filtfile,refframe,orbitfile,parfile,output_folder,custom_coords)\n print('Done filtering and barycentering')\n else:\n Lv1_barycorr.barycorr(eventfile,out_baryfile,refframe,orbitfile,parfile,output_folder,custom_coords)\n\n if do_filter == True:\n ##### Filtering if needed\n filtering(filtfile,out_baryfile,maskdets,eventflags,rm_artifacts)\n\n if do_lc_ps_phase_color == True: #would only be useful for looking at the whole time series? Might be of limited usage depending on what I want to use it for.\n par_list = ['PI','PI_FAST','TIME'] #parameter list from event_cl\n tbin_size = 1 #how you want to bin the light curve data\n Ebin_size = 0.05 #in keV\n mode = 'show' #probably best to 'save' if using a LARGE set of ObsIDs!\n truncations = 'E' #'all', 't', 'E', or 'tE', depending on whether we want to look at entire time series (all), or truncation by time interval (t), or time truncation by energy range (E), or truncation by both (tE)\n\n lc = True\n ps = False\n phase = False\n color = False\n ###############################################################################\n\n #### DEFINE DESIRED TIME INTERVALS AND ENERGY RANGES HERE FOR:\n # Lv2_ps - partial_t, partial_E, partial_tE\n # Lv2_phase - partial_t, partial_E, partial_tE\n # Lv2_color - plotting_t\n\n t1 = 2629580\n t2 = 2630180\n E1 = 1\n E2 = 10\n\n #for Lv2_ps\n ps_type = 'manual' # 'period' (for periodogram) or 'manual' (for FFT) or 'both'\n oversampling = [False,5] # [False to NOT oversample, oversampling factor - 5 to oversample by factor of 5. (factor-1) sets of 0s are padded.]\n xlims = [False,0,5] # [False to NOT impose xlimit on plots; 2nd/3rd entries are the desired x-limits if needed.]\n vlines = [False,0.2081] # [False to NOT draw a vertical line on the plot; 2nd entry is the equation for the vertical line, e.g. x=2]\n\n #for Lv2_phase\n ### For an unknown observation, one should run JUST Lv2_lc and Lv2_ps first to get\n ### the pulsation frequencies. Pulse profiles come LATER.\n ### If I have pulse_pars[1] and pulse_pars[2] != 0, then time binning DOES NOT MATTER, i.e., it'll be counts/s!\n pulse_pars = [275.518,0,0]\n shift = 0.4 # how much to shift the pulse by in the phase axis. It only affects how the pulse profile is 'displaced'.\n no_phase_bins = 20 # number of phase bins desired\n\n #for Lv2_color\n E1_data = 0.3 #data is reliable between 0.3 and 12 keV\n E2_data = 12 # in keV\n cut_type = 'manual' # 'manual' cut for boundary energy, or 'median' - for half number of counts\n bound = 2.7 # boundary energy for when cut_type = 'manual'!\n\n E_bound = Lv3_E_boundary.E_bound(out_baryfile,par_list,E1_data,E2_data,cut_type,bound) #use Lv3_E_boundary to get boundary energy\n ############################ FOR WHOLE OBSERVATION ############################\n if truncations == 'all':\n if lc == True:\n Lv2_lc.whole(out_baryfile,par_list,tbin_size,mode) #light curve\n time.sleep(1)\n if ps == True:\n Lv2_ps.whole(out_baryfile,par_list,tbin_size,mode,ps_type,oversampling,xlims,vlines) #power spectra\n time.sleep(1)\n if phase == True:\n Lv2_phase.whole(out_baryfile,par_list,tbin_size,pulse_pars,shift,no_phase_bins,mode)\n time.sleep(1)\n if color == True:\n Lv2_color.plotting(out_baryfile,par_list,E_bound,tbin_size,mode)\n\n ########################## FOR DESIRED TIME INTERVAL ##########################\n if truncations == 't':\n if lc == True:\n Lv2_lc.partial_t(out_baryfile,par_list,tbin_size,t1,t2,mode) #light curve\n time.sleep(1)\n if ps == True:\n Lv2_ps.partial_t(out_baryfile,par_list,tbin_size,t1,t2,mode,ps_type,oversampling,xlims,vlines) #power spectra\n time.sleep(1)\n if phase == True:\n Lv2_phase.partial_t(out_baryfile,par_list,tbin_size,pulse_pars,shift,no_phase_bins,t1,t2,mode)\n time.sleep(1)\n if color == True:\n Lv2_color.plotting_t(out_baryfile,par_list,E_bound,tbin_size,t1,t2,mode)\n\n ########################### FOR DESIRED ENERGY RANGE ##########################\n # anticipate that this will be used much?\n if truncations == 'E':\n if lc == True:\n Lv2_lc.partial_E(out_baryfile,par_list,tbin_size,E1,E2,mode)\n time.sleep(1)\n if ps == True:\n Lv2_ps.partial_E(out_baryfile,par_list,tbin_size,Ebin_size,E1,E2,mode,ps_type,oversampling,xlims,vlines)\n time.sleep(1)\n if phase == True:\n Lv2_phase.partial_E(out_baryfile,par_list,tbin_size,Ebin_size,pulse_pars,shift,no_phase_bins,E1,E2,mode)\n\n ################# FOR DESIRED TIME INTERVAL AND ENERGY RANGE #################\n if truncations == 'tE':\n if lc == True:\n Lv2_lc.partial_tE(out_baryfile,par_list,tbin_size,Ebin_size,t1,t2,E1,E2,mode)\n time.sleep(1)\n if ps == True:\n Lv2_ps.partial_tE(out_baryfile,par_list,tbin_size,Ebin_size,t1,t2,E1,E2,mode,ps_type,oversampling,xlims,vlines)\n time.sleep(1)\n if phase == True:\n Lv2_phase.partial_tE(out_baryfile,par_list,tbin_size,Ebin_size,pulse_pars,shift,no_phase_bins,t1,t2,E1,E2,mode)\n time.sleep(1)\n if color == True:\n Lv2_color.plotting_t(out_baryfile,par_list,E_bound,tbin_size,t1,t2,mode)\n\n if do_average_ps == True:\n for k in range(0,len(PI1)):\n for j in range(len(segment_lengths)):\n N = Lv3_detection_level.N_trials(tbin,segment_lengths[j])\n\n if preprocessing == True:\n if time_segments == True or time_energy_segments == True:\n Lv2_presto_subroutines.get_gti_file(out_baryfile,segment_lengths[j])\n if time_segments == True:\n Lv2_presto_subroutines.niextract_gti_time(out_baryfile,segment_lengths[j])\n if time_energy_segments == True:\n Lv2_presto_subroutines.niextract_gti_time_energy(out_baryfile,segment_lengths[j],PI1[k],PI2[k])\n\n if demod == True:\n Lv2_average_ps_methods.do_demodulate(out_baryfile,segment_lengths[j],mode,par_file)\n\n Lv2_average_ps_methods.do_nicerfits2presto(out_baryfile,tbin,segment_lengths[j])\n Lv2_average_ps_methods.edit_inf(out_baryfile,tbin,segment_lengths[j])\n Lv2_average_ps_methods.edit_binary(out_baryfile,tbin,segment_lengths[j])\n Lv2_average_ps_methods.realfft(out_baryfile,segment_lengths[j])\n\n for z in range(len(t1)):\n for x in range(len(W)):\n for y in range(len(threshold)):\n Lv2_average_ps_methods.plotting(out_baryfile,segment_lengths[j],demod,tbin,threshold[y],PI1[k],PI2[k],t1[z],t2[z],starting_freq,W[x],hist_min_sig,N,xlims,plot_mode)\n\n if do_presto == True:\n if process_all == True:\n if conv_fits2presto == True:\n Lv2_presto_subroutines.do_nicerfits2presto(out_baryfile,tbin,0,'all')\n\n if accelsearch == True:\n print('Doing realfft/accelsearch now!')\n ### Running realfft and accelsearch from PRESTO\n Lv2_presto_subroutines.realfft(out_baryfile,0,'all')\n Lv2_presto_subroutines.accelsearch(out_baryfile,0,'all',accelsearch_flags)\n\n ## no_cand might be a list, if I'm processing multiple out_baryfiles at once...\n if prepfold == True:\n Lv2_presto_subroutines.prepfold(out_baryfile,0,'all',zmax)\n Lv2_presto_subroutines.ps2pdf(out_baryfile,0,'all')\n\n################################################################################\n############################### PRESTO_SEGMENTS ################################\n################################################################################\n\n if process_segments == True:\n if time_segments == True and preprocess_segments == True:\n for j in range(len(segment_lengths)):\n Lv2_presto_subroutines.get_gti_file(out_baryfile,segment_lengths[j]) #make GTI files for each segment\n Lv2_presto_subroutines.niextract_gti_time(out_baryfile,segment_lengths[j]) #performing niextract-events\n\n Lv2_presto_subroutines.do_nicerfits2presto(out_baryfile,tbin,segment_lengths[j],'t')\n Lv2_presto_subroutines.edit_inf(out_baryfile,tbin,segment_lengths[j])\n Lv2_presto_subroutines.edit_binary(out_baryfile,tbin,segment_lengths[j])\n\n # Lv3_duty_cycle.duty_cycle(out_baryfile,tbin,segment_lengths[j],duty_cycle_bin,threshold)\n # Lv3_duty_cycle.duty_cycle_dist(out_baryfile,tbin,segment_lengths[j],duty_cycle_bin,threshold)\n\n if gti_segments == True and preprocess_segments == True:\n Lv2_presto_subroutines.niextract_gti(out_baryfile,gap,gtifile)\n Lv2_presto_subroutines.do_nicerfits2presto(out_baryfile,tbin,0,'gtis')\n\n if gti_energy_segments == True and preprocess_segments == True:\n if len(PI1) != len(PI2):\n raise ValueError(\"Make sure that the length of PI1 and PI2 are the same! Need pairs of PI values.\")\n for j in range(len(PI1)):\n Lv2_presto_subroutines.niextract_gti_E(out_baryfile,gap,gtifile,PI1[j],PI2[j])\n Lv2_presto_subroutines.do_nicerfits2presto(out_baryfile,tbin,0,'gtis') #segment_length makes no sense, so 0 is a placeholder\n\n if energy_segments == True and preprocess_segments == True:\n if len(PI1) != len(PI2):\n raise ValueError(\"Make sure that the length of PI1 and PI2 are the same! Need pairs of PI values.\")\n for j in range(len(PI1)):\n Lv2_presto_subroutines.niextract_gti_energy(out_baryfile,PI1[j],PI2[j])\n Lv2_presto_subroutines.do_nicerfits2presto(out_baryfile,tbin,0,'E') #segment_length makes no sense, so 0 is a placeholder\n\n if time_energy_segments == True and preprocess_segments == True:\n for j in range(len(segment_lengths)):\n Lv2_presto_subroutines.get_gti_file(out_baryfile,segment_lengths[j]) #make GTI files for each segment\n for k in range(len(PI1)):\n Lv2_presto_subroutines.niextract_gti_time_energy(out_baryfile,segment_lengths[j],PI1[k],PI2[k])\n\n Lv2_presto_subroutines.do_nicerfits2presto(out_baryfile,tbin,segment_lengths[j],'t')\n Lv2_presto_subroutines.edit_inf(out_baryfile,tbin,segment_lengths[j])\n Lv2_presto_subroutines.edit_binary(out_baryfile,tbin,segment_lengths[j])\n\n #for k in range(len(PI1)):\n # Lv3_duty_cycle.duty_cycle_tE(out_baryfile,tbin,segment_lengths[j],PI1[k],PI2[k],duty_cycle_bin,threshold)\n # Lv3_duty_cycle.duty_cycle_tE_dist(out_baryfile,tbin,segment_lengths[j],PI1[k],PI2[k],duty_cycle_bin,threshold)\n\n ### Running realfft and accelsearch from PRESTO\n if accelsearch == True:\n if time_segments == True or time_energy_segments == True:\n for j in range(len(segment_lengths)):\n Lv2_presto_subroutines.realfft(out_baryfile,segment_lengths[j],'t')\n Lv2_presto_subroutines.accelsearch(out_baryfile,segment_lengths[j],'t',accelsearch_flags)\n if gti_segments == True or gti_energy_segments == True:\n Lv2_presto_subroutines.realfft(out_baryfile,0,'gtis')\n Lv2_presto_subroutines.accelsearch(out_baryfile,0,'gtis',accelsearch_flags)\n if energy_segments == True:\n Lv2_presto_subroutines.realfft(out_baryfile,0,'E')\n Lv2_presto_subroutines.accelsearch(out_baryfile,0,'E',accelsearch_flags)\n else:\n \"None of time_segments, gti_segments, gti_energy_segments, time_energy_segments, or energy_segments are True!\"\n\n ## no_cand might be a list, if I'm processing multiple out_baryfiles at once...\n if prepfold == True:\n print(\"Running prepfold now!\")\n if time_segments == True or time_energy_segments == True:\n for j in range(len(segment_lengths)):\n Lv2_presto_subroutines.prepfold(out_baryfile,segment_lengths[j],'t',zmax)\n if gti_segments == True or gti_energy_segments == True:\n Lv2_presto_subroutines.prepfold(out_baryfile,0,'gtis',zmax)\n if energy_segments == True:\n Lv2_presto_subroutines.prepfold(out_baryfile,0,'E',zmax)\n\n ### doing ps2pdf\n if time_segments == True or time_energy_segments == True:\n for j in range(len(segment_lengths)):\n Lv2_presto_subroutines.ps2pdf(out_baryfile,segment_lengths[j],'t')\n if gti_segments == True or gti_energy_segments == True:\n Lv2_presto_subroutines.ps2pdf(out_baryfile,0,'gtis')\n if energy_segments == True:\n Lv2_presto_subroutines.ps2pdf(out_baryfile,0,'E')\n\n else:\n \"None of time_segments, gti_segments, gti_energy_segments, time_energy_segments, or energy_segments are True!\"\n\n if do_searchbin == True:\n for i in range(len(fft_files)):\n search_bin_cmd = ['search_bin','-ncand',str(ncand),'-flo',str(flo),'-fhi',str(fhi),'-overlap',str(overlap)] + extra_args + [fft_files[i]]\n subprocess.run(search_bin_cmd)\n\n if do_efsearch == True:\n print('Doing epoch-folding searches!')\n eventfile_header = fits.open(out_baryfile)[1].header\n T = eventfile_header['TSTOP'] - eventfile_header['TSTART']\n nbint = int((T/(dper/nphase))/n_segments) # The number of newbins per interval used in the analysis. The\n #\"nbint\" together with the NEWBIN duration determines the length in time of an interval\n #and therefore the total number of intervals within the start and stop time over which the\n #analysis will be carried out. Typing 'INDEF' forces the task to use the default value\n #(see parameter \"nbdf\"). NOTE: By pressing return \"nbint\" is set to the value found in the\n #parameter file used in a previous run.\"\n outfile_root = nicer_obsids[i] + '_' + str(n_segments) + 'segs_' + str(nper)\n Lv2_efsearch.efsearch(out_baryfile,n_segments,dper,nphase,nbint,nper,dres,outfile_root,plot_efsearch)\n\nend_time = time.time()\n\nprint('Time elapsed: ' + str(end_time-start_time) + ' seconds.')\n",
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon May 27 6:22pm 2019\nProgram for doing mkgti, niextract-events, nicerfits2presto, padding, calculate duty cycle,\nrealfft, accelsearch, prepfold, and ps2pdf! This is for when we want to split\nthe original time series up into segments (whether by energy or time)\nUse Lv2_presto_all.py instead if you want to do the analysis for the whole time series.\n\"\"\"\nfrom __future__ import division, print_function\nimport numpy as np\nfrom astropy.io import fits\nimport Lv0_dirs,Lv1_data_gtis,Lv2_mkdir\nfrom scipy import stats\nfrom tqdm import tqdm\nimport os\nfrom os.path import relpath\nimport time\nimport pathlib\nimport subprocess\nimport glob\n\nLv0_dirs.global_par()\n\npowers_of_two = [2**i for i in range(31)] # for deciding number of FFT bins\n\ndef get_gti_file(eventfile,segment_length):\n \"\"\"\n Creating the individual .gti files for my data segments!\n eventfile - path to the event file. Will extract ObsID from this for the NICER files.\n segment_length - length of the individual segments for combining power spectra\n \"\"\"\n parent_folder = str(pathlib.Path(eventfile).parent)\n gtis = fits.open(eventfile)[2].data\n times = fits.open(eventfile)[1].data['TIME']\n\n Tobs_start = gtis[0][0] #MJD for the observation start time\n Tobs_end = gtis[-1][1] #MJD for the observation end time\n\n segment_times = np.arange(Tobs_start,Tobs_end+segment_length,segment_length) #array of time values, starting\n #Jul 10 2019: also added Tobs_end+segment_length instead of Tobs_end, to get that final piece of data\n\n binned_counts, bin_edges, binnumber = stats.binned_statistic(times,np.ones(len(times)),statistic='sum',bins=segment_times)\n #bin edges defined by left boundary\n\n gtilist = open(parent_folder + '/segment_GTI.list','w')\n\n gti_folder = parent_folder + '/gtis/'\n Lv2_mkdir.makedir(gti_folder)\n for i in tqdm(range(len(bin_edges)-1)):\n gtilist.write('GTI'+str(i).zfill(6)+ ' ' + str(bin_edges[i]) + '\\n')\n gti_file = gti_folder + str(segment_length).zfill(5) + 's_GTI' + str(i).zfill(6) + '.gti'\n if binned_counts[i] != 0 and os.path.exists(gti_file)==False: #prevents from processing GTIs with no counts\n #print(str(segment_times[i]),str(segment_times[i+1]))\n subprocess.run(['mkgti.py','--gtiname',gti_file,str(segment_times[i]),str(segment_times[i+1])] )\n #no need to do 'startmet=', 'stopmet=', but make sure I do it in the right order!\n\n gtilist.close()\n\n return\n\ndef niextract_gti(eventfile,gap,gtifile):\n \"\"\"\n Using niextract-events to get segmented data based on the individual GTIs created with\n GTI_bunching in Lv1_data_gtis.\n\n eventfile - path to the event file. Will extract ObsID from this for the NICER files.\n gap - maximum separation between end time of 1st GTI and start time of 2nd GTI allowed\n gtifile - name of GTI file\n \"\"\"\n parent_folder = str(pathlib.Path(eventfile).parent)\n Lv1_data_gtis.GTI_bunching(eventfile,gap,gtifile)\n\n gtis = list(fits.open(parent_folder+'/'+gtifile)[1].data)\n niextract_folder = parent_folder + '/accelsearch_GTIs/'\n Lv2_mkdir.makedir(niextract_folder)\n for i in tqdm(range(len(gtis))):\n gti_start = gtis[i][0]\n gti_end = gtis[i][1]\n if os.path.exists(niextract_folder+'GTI'+str(i+1).zfill(6)+'.gti') == False:\n subprocess.run(['mkgti.py','--gtiname',niextract_folder+'GTI'+str(i+1).zfill(6)+'.gti',str(gti_start),str(gti_end)])\n\n niextract_output = niextract_folder+str(pathlib.Path(eventfile).name)[:-4]+'_GTI'+str(i+1).zfill(6)+'.evt'\n if os.path.exists(niextract_output)==False:\n subprocess.run(['niextract-events',eventfile,niextract_output,'timefile='+niextract_folder+'GTI'+str(i+1).zfill(6)+'.gti'])\n\n return\n\ndef niextract_gti_E(eventfile,gap,gtifile,PI1,PI2):\n \"\"\"\n Using niextract-events to get segmented data based on the individual GTIs created with\n GTI_bunching in Lv1_data_gtis, AND with energy cuts\n\n eventfile - path to the event file. Will extract ObsID from this for the NICER files.\n gap - maximum separation between end time of 1st GTI and start time of 2nd GTI allowed\n gtifile - name of GTI file\n PI1 - lower bound of PI (not energy in keV!) desired for the energy range\n PI2 - upper bound of PI (not energy in keV!) desired for the energy range\n \"\"\"\n parent_folder = str(pathlib.Path(eventfile).parent)\n Lv1_data_gtis.GTI_bunching(eventfile,gap,gtifile)\n\n gtis = list(fits.open(parent_folder+'/'+gtifile)[1].data)\n niextract_folder = parent_folder + '/accelsearch_GTIs/'\n Lv2_mkdir.makedir(niextract_folder)\n for i in tqdm(range(len(gtis))):\n gti_start = gtis[i][0]\n gti_end = gtis[i][1]\n if os.path.exists(niextract_folder+'GTI'+str(i+1).zfill(6)+'.gti') == False:\n subprocess.run(['mkgti.py','--gtiname',niextract_folder+'GTI'+str(i+1).zfill(6)+'.gti',str(gti_start),str(gti_end)])\n\n niextract_output = niextract_folder+str(pathlib.Path(eventfile).name)[:-4]+'_GTI'+str(i+1).zfill(6)+'_E' + str(PI1).zfill(4) + '-' + str(PI2).zfill(4) + '.evt'\n if os.path.exists(niextract_output)==False:\n subprocess.run(['niextract-events',eventfile+'[PI='+str(PI1)+':'+str(PI2)+']',niextract_output,'timefile='+niextract_folder+'GTI'+str(i+1).zfill(6)+'.gti'])\n\n return\n\ndef niextract_gti_time(eventfile,segment_length):\n \"\"\"\n Using niextract-events to get segmented data based on the [segment_length]-length\n GTIs that were created above!\n eventfile - path to the event file. Will extract ObsID from this for the NICER files.\n segment_length - length of the individual segments for combining power spectra\n \"\"\"\n parent_folder = str(pathlib.Path(eventfile).parent)\n gtis = fits.open(eventfile)[2].data\n times = fits.open(eventfile)[1].data['TIME']\n\n event_header = fits.open(eventfile)[1].header\n obj_name = event_header['OBJECT']\n obsid = event_header['OBS_ID']\n\n Tobs_start = gtis[0][0] #MJD for the observation start time\n Tobs_end = gtis[-1][1] #MJD for the observation end time\n# Tobs_start = event[1].data['TIME'][0]\n# Tobs_end = event[1].data['TIME'][-1]\n\n segment_times = np.arange(Tobs_start,Tobs_end+segment_length,segment_length) #array of time values, starting\n #from the observation start time until the observation end time, in steps of segment length.\n #Also had Tobs_end+segment_length to get the last section of data. It's ok if it's short, will zero-pad in\n #edit_binary! Done Jul 10.\n\n binned_counts, bin_edges, binnumber = stats.binned_statistic(times,np.ones(len(times)),statistic='sum',bins=segment_times)\n #bin edges defined by left boundary\n\n niextract_folder = parent_folder + '/accelsearch_' + str(segment_length) + 's/'\n Lv2_mkdir.makedir(niextract_folder)\n for i in tqdm(range(len(segment_times)-1)):\n if binned_counts[i] != 0: #prevents from processing GTIs with no counts\n outputfile = niextract_folder + 'ni' + obsid + '_nicersoft_bary_GTI'+str(i).zfill(6)+'_'+str(segment_length).zfill(5)+'s.evt'\n if 'merged' in parent_folder:\n merged_id = str(pathlib.Path(eventfile).name)[:12]\n outputfile = niextract_folder + merged_id + '_nicersoft_bary_GTI' + str(i).zfill(6) + '_' + str(segment_length).zfill(5) + 's.evt'\n\n if os.path.exists(outputfile)==False:\n subprocess.run(['niextract-events',eventfile,outputfile,'timefile='+parent_folder+'/gtis/'+str(segment_length).zfill(5)+'s_GTI'+str(i).zfill(6)+'.gti'])\n\n return\n\ndef niextract_gti_energy(eventfile,PI1,PI2):\n \"\"\"\n Using niextract-events to get segmented data based on the energy range\n eventfile - path to the event file. Will extract ObsID from this for the NICER files.\n PI1 - lower bound of PI (not energy in keV!) desired for the energy range\n PI2 - upper bound of PI (not energy in keV!) desired for the energy range\n \"\"\"\n parent_folder = str(pathlib.Path(eventfile).parent)\n gtis = fits.open(eventfile)[2].data\n\n event_header = fits.open(eventfile)[1].header\n obj_name = event_header['OBJECT']\n obsid = event_header['OBS_ID']\n\n niextract_folder = parent_folder + '/accelsearch_E/'\n Lv2_mkdir.makedir(niextract_folder)\n output_file = niextract_folder + eventfile.split('/')[-1][:-4] + '_E'+str(PI1).zfill(4)+'-'+str(PI2).zfill(4)+'.evt'\n\n if os.path.exists(output_file)==False:\n subprocess.run(['niextract-events',eventfile+'[PI='+str(PI1)+':'+str(PI2)+']',output_file])\n\n return\n\ndef niextract_gti_time_energy(eventfile,segment_length,PI1,PI2):\n \"\"\"\n Using niextract-events to get segmented data based on [segment_length]-length\n GTIs that were created above, AND energy range!\n eventfile - path to the event file. Will extract ObsID from this for the NICER files.\n segment_length - length of the individual segments for combining power spectra\n PI1 - lower bound of PI (not energy in keV!) desired for the energy range\n PI2 - upper bound of PI (not energy in keV!) desired for the energy range\n \"\"\"\n parent_folder = str(pathlib.Path(eventfile).parent)\n gtis = fits.open(eventfile)[2].data\n times = fits.open(eventfile)[1].data['TIME']\n\n event_header = fits.open(eventfile)[1].header\n obj_name = event_header['OBJECT']\n obsid = event_header['OBS_ID']\n\n Tobs_start = gtis[0][0] #MJD for the observation start time\n Tobs_end = gtis[-1][1] #MJD for the observation end time\n\n# Tobs_start = event[1].data['TIME'][0]\n# Tobs_end = event[1].data['TIME'][-1]\n\n segment_times = np.arange(Tobs_start,Tobs_end+segment_length,segment_length) #array of time values, starting\n #Jul 10: added Tobs_end + segment_length to get that final piece of data\n\n binned_counts, bin_edges, binnumber = stats.binned_statistic(times,np.ones(len(times)),statistic='sum',bins=segment_times)\n #bin edges defined by left boundary\n\n niextract_folder = parent_folder + '/accelsearch_' + str(segment_length) + 's/'\n Lv2_mkdir.makedir(niextract_folder)\n\n for i in tqdm(range(len(segment_times)-1)):\n if binned_counts[i] != 0: #prevents from processing GTIs with no counts\n outputfile = niextract_folder + 'ni' + obsid + '_nicersoft_bary_GTI'+str(i).zfill(6)+'_'+str(segment_length).zfill(5)+'s_' + 'E'+str(PI1).zfill(4)+'-'+str(PI2).zfill(4)+'.evt'\n if 'merged' in parent_folder:\n merged_id = str(pathlib.Path(eventfile).name)[:12]\n outputfile = niextract_folder + merged_id + '_nicersoft_bary_GTI' + str(i).zfill(6) + '_' + str(segment_length).zfill(5) + 's_E' + str(PI1).zfill(4) + '-' + str(PI2).zfill(4) + '.evt'\n if os.path.exists(outputfile)==False:\n subprocess.run(['niextract-events',eventfile+'[PI='+str(PI1)+':'+str(PI2)+']',outputfile,'timefile='+parent_folder+'/gtis/'+str(segment_length).zfill(5)+'s_GTI'+str(i).zfill(6)+'.gti'])\n\n return\n\ndef do_nicerfits2presto(eventfile,tbin,segment_length,mode):\n \"\"\"\n Using nicerfits2presto.py to bin the data, and to convert into PRESTO-readable format.\n I can always move files to different folders to prevent repeats (especially for large files)\n eventfile - path to the event file. Will extract ObsID from this for the NICER files.\n tbin - size of the bins in time\n segment_length - length of the individual segments for combining power spectra\n mode - \"all\", \"t\", \"gtis\" or \"E\" ; basically to tell the function where to access files to run realfft for\n \"\"\"\n parent_folder = str(pathlib.Path(eventfile).parent)\n event_header = fits.open(eventfile)[1].header\n obj_name = event_header['OBJECT']\n obsid = event_header['OBS_ID']\n\n if mode == \"all\": #for non-segmented event file\n subprocess.run(['nicerfits2presto.py','--dt='+str(tbin),eventfile])\n\n if mode == \"E\":\n E_files = glob.glob(parent_folder+'/accelsearch_E/*.evt')\n if len(E_files) != 0: #if E_files is not empty\n for i in tqdm(range(len(E_files))):\n if os.path.exists(E_files[i][:-3] + 'dat'):\n continue\n try:\n subprocess.run(['nicerfits2presto.py','--dt='+str(tbin),E_files[i]])\n except (ValueError,subprocess.CalledProcessError):\n pass\n\n if mode == 't':\n time_files = glob.glob(parent_folder+'/accelsearch_' + str(segment_length) + 's/*.evt')\n if len(time_files) != 0:\n for i in tqdm(range(len(time_files))):\n if os.path.exists(time_files[i][:-3] + 'dat'):\n continue\n try:\n subprocess.run(['nicerfits2presto.py','--dt='+str(tbin),time_files[i]])\n except (ValueError,subprocess.CalledProcessError):\n pass\n\n if mode == \"gtis\":\n gti_files = glob.glob(parent_folder+'/accelsearch_GTIs/*.evt')\n if len(gti_files) != 0:\n for i in tqdm(range(len(gti_files))):\n if os.path.exists(gti_files[i][:-3] + 'dat'):\n continue\n try:\n subprocess.run(['nicerfits2presto.py','--dt='+str(tbin),gti_files[i]])\n except (ValueError,subprocess.CalledProcessError):\n pass\n\n ##### will probably remove once I know to either NOT work in nicerpy_xrayanalysis,\n ##### and/or install my packages such that I can run the scripts from anywhere\n ##### in the terminal!\n\n presto_files = glob.glob('*'+obsid+'*')\n if 'merged' in eventfile:\n presto_files = glob.glob('merged*')\n for i in range(len(presto_files)):\n if mode == \"all\":\n subprocess.run(['mv',presto_files[i],parent_folder+'/'])\n if mode == \"t\":\n subprocess.run(['mv',presto_files[i],parent_folder+'/accelsearch_' + str(segment_length) + 's/'])\n if mode == \"E\":\n subprocess.run(['mv',presto_files[i],parent_folder+'/accelsearch_E/'])\n if mode == \"gtis\":\n subprocess.run(['mv',presto_files[i],parent_folder+'/accelsearch_GTIs/'])\n\n return\n\ndef edit_inf(eventfile,tbin,segment_length):\n \"\"\"\n Editing the .inf file, as it seems like accelsearch uses some information from the .inf file!\n Mainly need to edit the \"Number of bins in the time series\".\n This is only for when we make segments by time though!\n eventfile - path to the event file. Will extract ObsID from this for the NICER files.\n tbin - size of the bins in time\n segment_length - length of the individual segments\n \"\"\"\n parent_folder = str(pathlib.Path(eventfile).parent)\n event_header = fits.open(eventfile)[1].header\n #obj_name = event_header['OBJECT']\n #obsid = event_header['OBS_ID']\n\n inf_files = sorted(glob.glob(parent_folder + '/accelsearch_' + str(segment_length) + 's/*GTI*' + str(segment_length).zfill(5)+'s*.inf')) #not the .evt file; some .evt files will be empty\n #inf_files = sorted(glob.glob(parent_folder + '/accelsearch_GTIs/*GTI*.inf')) #not the .evt file; some .evt files will be empty\n\n no_desired_bins = float(segment_length)/float(tbin)\n\n for i in range(len(inf_files)):\n inf_file = open(inf_files[i],'r')\n contents = inf_file.read()\n contents = contents.split('\\n')\n inf_file.close()\n\n nobins_equal = contents[9].index('=') #find the '=' sign for the \"Number of bins...\" line)\n newstring = contents[9][:nobins_equal+1] + ' ' + str(int(no_desired_bins)) #replace old line with new line containing updated number of bins!\n\n inf_file = open(inf_files[i],'w')\n for j in range(len(contents)):\n if j != 9:\n inf_file.write(contents[j]+'\\n')\n else:\n inf_file.write(newstring+'\\n')\n inf_file.close()\n\n return\n\ndef edit_binary(eventfile,tbin,segment_length):\n \"\"\"\n To pad the binary file so that it will be as long as the desired segment length.\n The value to pad with for each time bin, is the average count rate in THAT segment!\n Jul 10: Do zero-padding instead... so that number of counts is consistent!\n Again, this is only for when we make segments by time!\n eventfile - path to the event file. Will extract ObsID from this for the NICER files.\n tbin - size of the bins in time\n segment_length - length of the individual segments\n \"\"\"\n parent_folder = str(pathlib.Path(eventfile).parent)\n event_header = fits.open(eventfile)[1].header\n #obj_name = event_header['OBJECT']\n #obsid = event_header['OBS_ID']\n\n dat_files = sorted(glob.glob(parent_folder + '/accelsearch_' + str(segment_length) + 's/*GTI*' + str(segment_length).zfill(5) + 's*.dat')) #not that order matters here I think, but just in case\n #dat_files = sorted(glob.glob(parent_folder + '/accelsearch_GTIs/*GTI*.dat')) #not that order matters here I think, but just in case\n\n for i in tqdm(range(len(dat_files))):\n bins = np.fromfile(dat_files[i],dtype='<f',count=-1) #reads the binary file ; converts to little endian, count=-1 means grab everything\n# bins_with_data = len(bins[bins>0]) #number of bins with data (NOT the ones with averaged count rate!)\n# average_count_rate = sum(bins)/len(bins)\n\n no_desired_bins = float(segment_length)/float(tbin) #TOTAL number of desired bins for the segment\n no_padded = int(no_desired_bins - len(bins)) #number of bins needed to reach the TOTAL number of desired bins\n if no_padded >= 0:\n #padding = np.ones(no_padded,dtype=np.float32)*average_count_rate #generate the array of (averaged) counts needed to pad the original segment\n padding = np.zeros(no_padded,dtype=np.float32) #just in case this is ever needed...\n new_bins = np.array(list(bins) + list(padding))\n new_bins.tofile(dat_files[i]) #don't need to do mv since obsdir already has absolute path to the SSD\n else:\n new_bins = bins[:int(no_desired_bins)] #truncate the original series; say we had a 1000s segment, but\n #nicerfits2presto went up to 1008s, so take that last 8s away because there's no data in it anyways...\n new_bins.tofile(dat_files[i])\n\n return\n\ndef realfft(eventfile,segment_length,mode):\n \"\"\"\n Performing PRESTO's realfft on the binned data (.dat)\n eventfile - path to the event file. Will extract ObsID from this for the NICER files.\n segment_length - length of the individual segments\n mode - \"all\", \"t\", \"gtis\", or \"E\" ; basically to tell the function where to access files to run realfft for\n \"\"\"\n parent_folder = str(pathlib.Path(eventfile).parent)\n\n if mode == \"all\":\n dat_files = sorted(glob.glob(parent_folder+'/*.dat'))\n logfile = parent_folder + '/realfft_all.log'\n elif mode == \"t\":\n dat_files = sorted(glob.glob(parent_folder+'/accelsearch_'+str(segment_length)+'s/*.dat'))\n logfile = parent_folder + '/accelsearch_' + str(segment_length) + 's/realfft_t.log'\n elif mode == \"E\":\n dat_files = sorted(glob.glob(parent_folder+'/accelsearch_E/*.dat'))\n logfile = parent_folder + '/accelsearch_E/realfft_E.log'\n elif mode == \"gtis\":\n dat_files = sorted(glob.glob(parent_folder+'/accelsearch_GTIs/*.dat'))\n logfile = parent_folder + '/accelsearch_GTIs/realfft_gtis.log'\n else:\n raise ValueError(\"mode should either of 'all', 't', 'gtis', or 'E'!\")\n\n print(\"Running realfft now:\")\n with open(logfile,'w') as logtextfile:\n for i in tqdm(range(len(dat_files))):\n if os.path.exists(dat_files[i][:-3] + 'fft')==False:\n output = subprocess.run(['realfft',dat_files[i]],capture_output=True,text=True)\n logtextfile.write(output.stdout)\n logtextfile.write('*------------------------------* \\n')\n logtextfile.write(output.stderr)\n logtextfile.close()\n\n return\n\ndef accelsearch(eventfile,segment_length,mode,flags):\n \"\"\"\n Performing PRESTO's accelsearch on the FFT data (.fft)\n eventfile - path to the event file. Will extract ObsID from this for the NICER files.\n segment_length - length of the individual segments\n mode - \"all\", \"t\", \"gtis\" or \"E\" ; basically to tell the function where to access files to run accelsearch for\n flags - a LIST of input flags for accelsearch\n \"\"\"\n if type(flags) != list:\n raise TypeError(\"flags should be a list! Not even an array.\")\n\n parent_folder = str(pathlib.Path(eventfile).parent)\n\n if mode == \"all\":\n fft_files = sorted(glob.glob(parent_folder+'/*.fft'))\n logfile = parent_folder + '/accelsearch_all.log'\n elif mode == \"t\":\n fft_files = sorted(glob.glob(parent_folder+'/accelsearch_'+str(segment_length)+'s/*.fft'))\n logfile = parent_folder + '/accelsearch_' + str(segment_length) + 's/accelsearch_t.log'\n elif mode == \"E\":\n fft_files = sorted(glob.glob(parent_folder+'/accelsearch_E/*.fft'))\n logfile = parent_folder + '/accelsearch_E/accelsearch_E.log'\n elif mode == \"gtis\":\n fft_files = sorted(glob.glob(parent_folder+'/accelsearch_GTIs/*.fft'))\n logfile = parent_folder + '/accelsearch_GTIs/accelsearch_gtis.log'\n else:\n raise ValueError(\"mode should either of 'all', 't', 'gtis', or 'E'!\")\n\n zmax_index = flags.index('-zmax')\n zmax_num = str(flags[zmax_index+1])\n print(\"Running accelsearch now:\")\n with open(logfile,'w') as logtextfile:\n for i in tqdm(range(len(fft_files))):\n #if os.path.exists(fft_files[i][:-4] + '_ACCEL_' + zmax_num + '.txtcand') == False:\n command = ['accelsearch'] + flags + [fft_files[i]]\n output = subprocess.run(command,capture_output=True,text=True)\n logtextfile.write(output.stdout)\n logtextfile.write('*------------------------------* \\n')\n logtextfile.write(output.stderr)\n logtextfile.close()\n\n return\n\ndef prepfold(eventfile,segment_length,mode,zmax):\n \"\"\"\n Performing PRESTO's prepfold on the pulsation candidates.\n eventfile - path to the event file. Will extract ObsID from this for the NICER files.\n segment_length - length of the individual segments\n mode - \"all\", \"t\", \"gtis\", or \"E\" ; basically to tell the function where to access files to run prepfold for\n zmax - maximum acceleration\n \"\"\"\n parent_folder = str(pathlib.Path(eventfile).parent)\n\n if mode == \"all\":\n ACCEL_files = sorted(glob.glob(parent_folder+'/*ACCEL_'+str(zmax)))\n logfile = parent_folder + '/prepfold_all.log'\n elif mode == \"t\":\n ACCEL_files = sorted(glob.glob(parent_folder+'/accelsearch_'+str(segment_length)+'s/*ACCEL_'+str(zmax)))\n logfile = parent_folder + '/accelsearch_' + str(segment_length) + 's/prepfold_t.log'\n elif mode == \"E\":\n ACCEL_files = sorted(glob.glob(parent_folder+'/accelsearch_E/*ACCEL_'+str(zmax)))\n logfile = parent_folder + '/accelsearch_E/prepfold.log'\n elif mode == \"gtis\":\n ACCEL_files = sorted(glob.glob(parent_folder+'/accelsearch_GTIs/*ACCEL_'+str(zmax)))\n logfile = parent_folder + '/accelsearch_GTIs/prepfold.log'\n else:\n raise ValueError(\"mode should either of 'all', 't', 'gtis', or 'E'!\")\n\n cand_files = [ACCEL_files[i] + '.cand' for i in range(len(ACCEL_files))]\n if zmax < 10:\n events_files = [cand_files[i][:-13]+'.events' for i in range(len(cand_files))]\n if (zmax >= 10) & (zmax < 100):\n events_files = [cand_files[i][:-14]+'.events' for i in range(len(cand_files))]\n if (zmax >= 100) & (zmax < 999):\n events_files = [cand_files[i][:-15]+'.events' for i in range(len(cand_files))]\n else:\n events_files = [cand_files[i][:-16]+'.events' for i in range(len(cand_files))]\n\n header1 = \" Summed Coherent Num Period Frequency FFT 'r' Freq Deriv FFT 'z' Accel \"\n header2 = \" Power / Raw FFT 'r' Pred 'r' FFT 'z' Pred 'z' Phase Centroid Purity \"\n\n with open(logfile,'w') as logtextfile:\n for i in range(len(ACCEL_files)): #for each successful ACCEL_zmax file:\n accel_textfile = np.array(open(ACCEL_files[i],'r').read().split('\\n')) #read the data from the ACCEL_$zmax files\n index_header1 = np.where(accel_textfile==header1)[0][0] #index for \"Summed, Coherent, Num, Period etc\n index_header2 = np.where(accel_textfile==header2)[0][0] #index for \"Power / Raw FFT 'r' etc\n no_cands = index_header2 - index_header1 - 5 #to obtain number of candidates\n cand_relpath = relpath(cand_files[i],parent_folder) #relative path of .cand file ; PRESTO doesn't like using absolute paths\n events_relpath = relpath(events_files[i],parent_folder) #relative path of .events file ; PRESTO doesn't like using absolute paths\n\n for j in range(min(50,no_cands)): #to control the number of outputs! Sometimes there can be thousands of candidates - insane!\n command = 'cd ' + parent_folder + ' ; prepfold -double -events -noxwin -n 20 -accelcand ' + str(j+1) + ' -accelfile ' + cand_relpath + ' ' + events_relpath\n output = subprocess.run(command,shell=True,capture_output=True,text=True)\n logtextfile.write(output.stdout)\n logtextfile.write('*------------------------------* \\n')\n logtextfile.write(output.stderr)\n logtextfile.close()\n\n return\n\ndef filter_accelsearch(eventfile,mode,min_freq,zmax):\n \"\"\"\n Added on 8/31/2020. To filter out the ACCEL files by displaying a list of candidates\n that have met a frequency threshold (to avoid very low frequency candidates, really)\n\n The files will have been generated via prepfold already - perhaps in the future, I may\n only run prepfold on candidates I want! Maybe do this to avoid having too many candidates...\n\n eventfile - path to the event file. Will extract ObsID from this for the NICER files.\n mode - \"all\", \"t\", \"gtis\", or \"E\" ; basically to tell the function where to access files to run prepfold for\n min_freq - minimum frequency to include in the list\n zmax - maximum acceleration\n \"\"\"\n parent_folder = str(pathlib.Path(eventfile).parent)\n\n if mode == \"all\":\n ACCEL_files = sorted(glob.glob(parent_folder+'/*ACCEL_'+str(zmax)))\n elif mode == \"t\":\n ACCEL_files = sorted(glob.glob(parent_folder+'/accelsearch_'+str(segment_length)+'s/*ACCEL_'+str(zmax)))\n elif mode == \"E\":\n ACCEL_files = sorted(glob.glob(parent_folder+'/accelsearch_E/*ACCEL_'+str(zmax)))\n elif mode == \"gtis\":\n ACCEL_files = sorted(glob.glob(parent_folder+'/accelsearch_GTIs/*ACCEL_'+str(zmax)))\n else:\n raise ValueError(\"mode should either of 'all', 't', 'gtis', or 'E'!\")\n\n ### below are just the headers in the *ACCEL_100 files ; the intention is just to get the indices for these lines later on\n header1 = \" Summed Coherent Num Period Frequency FFT 'r' Freq Deriv FFT 'z' Accel \"\n header2 = \" Power / Raw FFT 'r' Pred 'r' FFT 'z' Pred 'z' Phase Centroid Purity \"\n\n output_file = open(str(pathlib.Path(ACCEL_files[0]).parent) + '/ACCEL_' + str(zmax) + '_cands_minfreq_' + str(min_freq) + '.txt','w')\n output_file.write(header1 + '\\n')\n\n for i in range(len(ACCEL_files)):\n freqs = []\n accel_textfile = np.array(open(ACCEL_files[i],'r').read().split('\\n')) #read the data from the ACCEL_$zmax files\n index_header1 = np.where(accel_textfile==header1)[0][0] #index for \"Summed, Coherent, Num, Period etc\n index_header2 = np.where(accel_textfile==header2)[0][0] #index for \"Power / Raw FFT 'r' etc\n no_cands = index_header2 - index_header1 - 5 #to obtain number of candidates\n for j in range(no_cands):\n freq = float(accel_textfile[j+3].split()[6][:-3])\n freqs.append(freq)\n if not any(np.array(freqs)>min_freq): #if none are above the minimum frequency\n continue\n else:\n output_file.write(str(pathlib.Path(ACCEL_files[i]).name) + '\\n')\n for j in range(no_cands):\n freq = float(accel_textfile[j+3].split()[6][:-3])\n if freq >= min_freq:\n output_file.write(accel_textfile[j+3] + '\\n')\n output_file.close()\n\ndef ps2pdf(eventfile,segment_length,mode):\n \"\"\"\n Converting from .ps to .pdf\n eventfile - path to the event file. Will extract ObsID from this for the NICER files.\n mode - \"all\", \"t\", \"gtis\", or \"E\" ; basically to tell the function where to access files to run ps2pdf for\n \"\"\"\n parent_folder = str(pathlib.Path(eventfile).parent)\n\n if mode == \"all\":\n ps_files = sorted(glob.glob(parent_folder+'/*ps'))\n elif mode == \"t\":\n ps_files = sorted(glob.glob(parent_folder+'/accelsearch_'+str(segment_length)+'s/*ps'))\n elif mode == \"E\":\n ps_files = sorted(glob.glob(parent_folder+'/accelsearch_E/*ps'))\n elif mode == \"gtis\":\n ps_files = sorted(glob.glob(parent_folder+'/accelsearch_GTIs/*ps'))\n else:\n raise ValueError(\"mode should either of 'all', 't', 'gtis', or 'E'!\")\n\n print('Running ps2pdf now!')\n for i in tqdm(range(len(ps_files))):\n pdf_file = ps_files[i][:-2]+'pdf' #replacing .ps to .pdf\n ps2pdf_command = ['ps2pdf',ps_files[i],pdf_file]\n subprocess.run(ps2pdf_command) #using ps2pdf to convert from ps to pdf ; not just a simple change in extension\n\n return\n\nif __name__ == \"__main__\":\n #eventfile = Lv0_dirs.NICERSOFT_DATADIR + '1034070101_pipe/ni1034070101_nicersoft_bary.evt'\n #eventfile = Lv0_dirs.NICER_DATADIR + 'xtej1739/2002131540_bary.evt'\n\n gap = 5\n gtifile = Lv0_dirs.NICER_DATADIR + 'xtej1739/bunched.gti'\n mode = 't'\n segment_length = 100\n PI1 = 100\n PI2 = 1000\n zmax = 100\n\n tbin = 0.025\n\n accelsearch_flags = ['-numharm','4','-zmax','100','-photon','-flo','1','-fhi','1000']\n\n #get_gti_file(eventfile,segment_length)\n #niextract_gti(eventfile,gap,gtifile)\n #niextract_gti_time(eventfile,segment_length)\n #niextract_gti_energy(eventfile,PI1,PI2)\n #niextract_gti_time_energy(eventfile,segment_length,PI1,PI2)\n #do_nicerfits2presto(eventfile,tbin,segment_length)\n #edit_inf(eventfile,tbin,segment_length)\n #edit_binary(eventfile,tbin,segment_length)\n #realfft(eventfile,segment_length,mode)\n #accelsearch(eventfile,segment_length,mode,accelsearch_flags)\n #prepfold(eventfile,mode,zmax)\n #ps2pdf(eventfile,mode)\n #testfile = '/Volumes/Samsung_T5/NICERsoft_outputs/1034070101_pipe/niextract/ni1034070101_nicersoft_bary_GTI0_100s.dat'\n #bins = np.fromfile(testfile,dtype='<f',count=-1)\n #print(len(bins))\n\n #####\n #eventfile = '/Volumes/Samsung_T5/NICERsoft_outputs/at2018cow_2020/at2018cow_filtered_highSNR.evt'\n #gap = 0\n #gtifile = 'bunched.gti'\n #niextract_gti(eventfile,gap,gtifile)\n\n #####\n eventfile = '/Volumes/Samsung_T5/NICER-data/at2019wey/2008041401_filt_bary.evt'\n mode = 'gtis'\n min_freq = 10\n zmax = 100\n\n filter_accelsearch(eventfile,mode,min_freq,zmax)\n",
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n\n\"\"\"\nfrom __future__ import division, print_function\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport glob\nimport subprocess\nimport os\nfrom os.path import relpath\nimport Lv0_dirs\n\nLv0_dirs.global_par()\n\n##### INITIAL LOOK AT THE HISTOGRAM\n\nobsids = ['12002501' + str(i+1).zfill(2) for i in range(26)]\ncands_file = open('candidates.txt','w')\nfor k in range(len(obsids)):\n nicersoft_output_folder = Lv0_dirs.NICERSOFT_DATADIR\n ACCEL_files = sorted(glob.glob(nicersoft_output_folder+obsids[k]+'_pipe/accelsearch_64s/ni'+obsids[k]+'_nicersoft_bary_*ACCEL_100')) #getting absolute paths for the *ACCEL_100 files\n header1 = \" Summed Coherent Num Period Frequency FFT 'r' Freq Deriv FFT 'z' Accel \"\n header2 = \" Power / Raw FFT 'r' Pred 'r' FFT 'z' Pred 'z' Phase Centroid Purity \"\n\n for i in range(len(ACCEL_files)): #for each successful ACCEL_zmax file:\n accel_textfile = np.array(open(ACCEL_files[i],'r').read().split('\\n')) #read the data from the ACCEL_$zmax files\n index_header1 = np.where(accel_textfile==header1)[0][0] #index for \"Summed, Coherent, Num, Period etc\n index_header2 = np.where(accel_textfile==header2)[0][0] #index for \"Power / Raw FFT 'r' etc\n no_cands = index_header2 - index_header1 - 5 #to obtain number of candidates\n\n candidates = np.genfromtxt(ACCEL_files[i],dtype='str',skip_header=3,usecols=6,unpack=True,max_rows=no_cands) #to obtain frequency values\n for j in range(candidates.size):\n if candidates.size == 1: #if there's only one candidate...\n cands_file.write(ACCEL_files[i] + ' ' + str(candidates)[:-3] + '\\n') #[:-3] takes away the uncertainty\n else:\n cands_file.write(ACCEL_files[i] + ' ' + candidates[j][:-3] + '\\n')\n\ncands_file.close()\n\ncandidates_file = 'candidates.txt'\ncheck_cands = np.genfromtxt(candidates_file,dtype='float',skip_footer=0) #get the frequency values\nfiltered_check_cands = check_cands[check_cands>1]\nprint(len(check_cands))\nprint(len(filtered_check_cands))\n\nplt.figure(1)\nplt.hist(filtered_check_cands,bins=100)\n\n##### NEXT, DOING THE SHUFFLING OF THE LIGHT CURVES!\n\"\"\"\nobsids = ['12002501' + str(i+1).zfill(2) for i in range(26)]\nat2018cow_noise = '/Volumes/Samsung_T5/NICERsoft_outputs/at2018cow_noise/'\n\nfor i in range(len(obsids)):\n nicersoft_output_folder = Lv0_dirs.NICERSOFT_DATADIR\n accelsearch_folder = nicersoft_output_folder + obsids[i] + '_pipe/accelsearch_64s/'\n ACCEL_files = sorted(glob.glob(nicersoft_output_folder+obsids[i]+'_pipe/accelsearch_64s/ni'+obsids[i]+'_nicersoft_bary_*ACCEL_100')) #getting absolute paths for the *ACCEL_100 files\n dat_files = [ACCEL_files[j][:-10] + '.dat' for j in range(len(ACCEL_files))] #get absolute paths of binary .dat files\n inf_files = [ACCEL_files[j][:-10] + '.inf' for j in range(len(ACCEL_files))] #get absolute paths of inf files (information files for PRESTO)\n\n for k in range(len(dat_files)): #for every .dat file\n counts = np.fromfile(dat_files[k],dtype='<f',count=-1) #read the binary data into Python\n np.random.shuffle(counts) #shuffle the counts in each 1ms bin\n filename = relpath(dat_files[k],accelsearch_folder) #get the relative path of the binary data file\n counts.tofile(at2018cow_noise + filename) #save the NEW file into the folder 'at2018cow_noise'\n\n for k in range(len(inf_files)): #to save the inf files into the same 'at2018cow_noise' folder as the data files. Need this for accelsearch\n inf_relpath = relpath(inf_files[k],accelsearch_folder)\n inf_newpath = at2018cow_noise + inf_relpath\n subprocess.check_output(['mv',inf_files[k],inf_newpath])\n\nall_dat_files = sorted(glob.glob(at2018cow_noise+'*.dat'))\nfor i in range(len(all_dat_files)):\n subprocess.check_output(['realfft',all_dat_files[i]]) #need to do FFT on the binary data file\n\nall_fft_files = sorted(glob.glob(at2018cow_noise+'*.fft'))\nlogfile = at2018cow_noise + 'accelsearch.log'\naccelsearch_flags = ['-numharm','8','-zmax','100','-photon','-flo','1','-fhi','500'] #accelsearch flags\nwith open(logfile,'w') as logtextfile:\n for i in range(len(all_fft_files)):\n logtextfile.write(subprocess.check_output(['accelsearch']+accelsearch_flags+[all_fft_files[i]]))\n logtextfile.close()\n\"\"\"\n##### GET THE HISTOGRAMS AGAIN\nat2018cow_noise = '/Volumes/Samsung_T5/NICERsoft_outputs/at2018cow_noise/'\n\ncands_file = open('candidates_noise.txt','w')\nACCEL_files = sorted(glob.glob(at2018cow_noise +'*ACCEL_100'))\nheader1 = \" Summed Coherent Num Period Frequency FFT 'r' Freq Deriv FFT 'z' Accel \"\nheader2 = \" Power / Raw FFT 'r' Pred 'r' FFT 'z' Pred 'z' Phase Centroid Purity \"\n\nfor i in range(len(ACCEL_files)): #for each successful ACCEL_zmax file:\n accel_textfile = np.array(open(ACCEL_files[i],'r').read().split('\\n')) #read the data from the ACCEL_$zmax files\n index_header1 = np.where(accel_textfile==header1)[0][0] #index for \"Summed, Coherent, Num, Period etc\n index_header2 = np.where(accel_textfile==header2)[0][0] #index for \"Power / Raw FFT 'r' etc\n no_cands = index_header2 - index_header1 - 5 #to obtain number of candidates\n\n candidates = np.genfromtxt(ACCEL_files[i],dtype='str',skip_header=3,usecols=6,unpack=True,max_rows=no_cands)\n for j in range(candidates.size):\n if candidates.size == 1:\n cands_file.write(ACCEL_files[i] + ' ' + str(candidates)[:-3] + '\\n')\n else:\n cands_file.write(ACCEL_files[i] + ' ' + candidates[j][:-3] + '\\n')\n\ncands_file.close()\n\nnoise_candidates_file = 'candidates_noise.txt'\nnoise_check_cands = np.genfromtxt(noise_candidates_file,dtype='float',skip_footer=0,usecols=1,unpack=True)\nnoise_filtered_check_cands = noise_check_cands[noise_check_cands>1]\nprint(len(noise_check_cands))\nprint(len(noise_filtered_check_cands))\n\n#plt.figure(2)\nplt.hist(noise_filtered_check_cands,bins=100)\n\nplt.legend(('Original search','Shuffled data'),loc='best')\n\nplt.axvline(x=260,lw=0.5,alpha=0.5)\nplt.axvline(x=200,lw=0.5,alpha=0.5)\nplt.axvline(x=100,lw=0.5,alpha=0.5)\nplt.axvline(x=130,lw=0.5,alpha=0.5)\nplt.axvline(x=50,lw=0.5,alpha=0.5)\nplt.axvline(x=65,lw=0.5,alpha=0.5)\n\nplt.xlabel('Frequency (Hz)',fontsize=12)\nplt.ylabel('Number',fontsize=12)\n\nplt.show()\n"
] | [
[
"numpy.where",
"numpy.float",
"numpy.genfromtxt"
],
[
"numpy.arange"
],
[
"numpy.array"
],
[
"numpy.fromfile",
"numpy.arange",
"numpy.array",
"numpy.zeros",
"numpy.where"
],
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.axvline",
"numpy.genfromtxt",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.show",
"numpy.where",
"matplotlib.pyplot.hist",
"matplotlib.pyplot.figure"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
gradientzero/dq0-sdk | [
"90856dd5ac56216971ffe33004447fd037a21660",
"90856dd5ac56216971ffe33004447fd037a21660"
] | [
"dq0/sdk/examples/newsgroups/_data/generate_preprocessed_dataset.py",
"dq0/sdk/examples/newsgroups/bayesian/model/user_model_old_needs_SOURCE.py"
] | [
"# -*- coding: utf-8 -*-\n\"\"\"20Newsgroups Data Source.\n\nThis is a data source example known from the Scikit-learn API:\nhttps://scikit-learn.org/stable/datasets/index.html#the-20-newsgroups-text-dataset\n\nThe 20 newsgroups dataset comprises around 18000 newsgroups posts on 20 topics\nsplit in two subsets: one for training (or development) and the other one\nfor testing (or for performance evaluation). The split between the train and\ntest set is based upon a messages posted before and after a specific date.\n\nCopyright 2020, Gradient Zero\nAll rights reserved\n\"\"\"\n\nfrom pathlib import Path\n\nfrom dq0.sdk.data.preprocessing import preprocessing\nfrom dq0.sdk.data.utils import util\nfrom dq0.sdk.examples.newsgroups._data.dump_text_labels_to_df_csv import \\\n _dump_text_and_labels_to_csv\n\nimport pandas as pd\n\nfrom sklearn.model_selection import train_test_split\n\n\ndef _generate_preprocessed_dataset(X, y):\n\n # fillna with empty strings (exist in original)\n X.fillna(\"\", inplace=True)\n\n # Split for preprocessing\n # If the input is sparse, the output will be a scipy.sparse.csr_matrix.\n # Otherwise, output type is the same as the input type.\n X_train_df, X_test_df, y_train_se, y_test_se = \\\n train_test_split(X, y, test_size=0.1)\n\n X_train_sp_matr, X_test_sp_matr, feature_names_list = \\\n preprocessing.extract_count_features_from_text_corpus(\n X_train_df.values.tolist(),\n X_test_df.values.tolist()\n )\n\n # Set the number of features for feature extraction\n #\n # WARNING!!! when setting num_top_ranked_feats_to_keep to 20k,\n # DP fitting takes more than an hour\n #\n num_top_ranked_feats_to_keep = int(5e3) # set to 'all' to skip feat sel.\n if str(num_top_ranked_feats_to_keep).lower() != 'all':\n technique_for_feat_sel = 'chi-squared test' # 'mutual information'\n\n if str(num_top_ranked_feats_to_keep).lower() != 'all':\n X_train_sp_matr, X_test_sp_matr, feature_names_list = \\\n preprocessing.univariate_feature_selection(\n num_top_ranked_feats_to_keep,\n X_train_sp_matr,\n y_train_se,\n X_test_sp_matr,\n technique=technique_for_feat_sel,\n feature_names_list=feature_names_list\n )\n\n sparse_representation = False\n X_train_df = util.sparse_scipy_matrix_to_Pandas_df(\n X_train_sp_matr,\n sparse_representation,\n columns_names_list=feature_names_list)\n\n X_test_df = util.sparse_scipy_matrix_to_Pandas_df(\n X_test_sp_matr,\n sparse_representation,\n columns_names_list=feature_names_list)\n\n X = pd.concat([X_train_df, X_test_df], ignore_index=True)\n y = pd.concat([y_train_se, y_test_se], ignore_index=True)\n y.name = 'label'\n df = pd.concat([X, y], axis=1)\n\n print('\\nGenerated dataset for 20Newsgroups:')\n print('\\tfeature matrix shape:', X.shape)\n print('\\tclass-labels vector shape:', y.shape)\n print('\\tnum classes:', y.nunique())\n print('\\tShape of DataFrame saved in file:', df.shape)\n\n return df\n\n\nif __name__ == '__main__':\n\n # fetch raw text data\n raw_data_csv = '../dq0-sdk/dq0/sdk/examples/newsgroups/_data' \\\n '/20newsgroups_text_label_df.csv'\n\n if not Path(raw_data_csv).is_file():\n # file does not exists\n _dump_text_and_labels_to_csv(raw_data_csv)\n\n dataset = pd.read_csv(raw_data_csv)\n\n df = _generate_preprocessed_dataset(dataset.iloc[:, 0], dataset.iloc[:, 1])\n\n df.to_csv(\n '../dq0-sdk/dq0/sdk/examples/newsgroups/_data/preprocessed_dataset'\n '.csv', index=False\n )\n\n # preprocessed_dataset.csv size is 366MB, so it is not kept in the\n # repository.\n",
"# -*- coding: utf-8 -*-\n\"\"\"Multinomial Naive Bayesian Model example for the 20Newsgroups dataset.\n\nCopyright 2020, Gradient Zero\nAll rights reserved\n\"\"\"\n\nimport logging\n\nfrom dq0.sdk.errors.errors import fatal_error\nfrom dq0.sdk.models.bayes.naive_bayesian_model import NaiveBayesianModel\n\nimport numpy as np\n\nimport pandas as pd\n\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.preprocessing import LabelEncoder\n\n\nlogger = logging.getLogger()\n\n\nclass UserModel(NaiveBayesianModel):\n \"\"\"Multinomial Naive Bayesian classifier for the \"20 Newsgroups\" dataset\n\n SDK users instantiate this class to create and train the model.\n \"\"\"\n\n def __init__(self):\n super().__init__()\n self.label_encoder = None\n\n def setup_model(self):\n \"\"\"Setup model.\n\n Define the model here.\n \"\"\"\n self._classifier_type = 'MultinomialNB' # just for better-quality\n # printings\n\n self.model = MultinomialNB()\n # set smoothing prior\n self.model.set_params(alpha=.01)\n\n self.metrics = ['accuracy']\n\n print('Set up a ' + self._classifier_type + ' classifier.')\n\n def setup_data(self):\n \"\"\"Setup data function\n\n This function can be used to prepare data or perform\n other tasks for the training run.\n\n At runtime the selected datset is attached to this model. It\n is available as the `data_source` attribute.\n\n For local testing call `model.attach_data_source(some_data_source)`\n manually before calling `setup_data()`.\n\n Use `self.data_source.read()` to read the attached data.\n \"\"\"\n # get the input dataset\n if self.data_source is None:\n fatal_error('No data source found', logger=logger)\n\n X, y = self.data_source.read()\n\n # check data format\n if isinstance(X, pd.DataFrame):\n X = X.values\n else:\n if not isinstance(X, np.ndarray):\n raise Exception('X is not np.ndarray')\n\n if isinstance(y, pd.Series):\n y = y.values\n else:\n if not isinstance(y, np.ndarray):\n raise Exception('y is not np.ndarray')\n\n # prepare data\n if y.ndim == 2:\n # make non-dimensional array (just to avoid Warnings by Sklearn)\n y = np.ravel(y)\n\n # LabelEncoder() encodes target labels with value between 0 and\n # n_classes - 1\n # if self.label_encoder is None:\n # print('Retraining')\n self.label_encoder = LabelEncoder()\n y = self.label_encoder.fit_transform(y)\n\n # back to column vector. Transform one-dimensional array into column\n # vector via newaxis\n y = y[:, np.newaxis]\n\n # set attributes\n self.X_train = X\n self.y_train = y\n self.X_test = None\n self.y_test = None\n\n print('\\nAttached train dataset to user model. Feature matrix '\n 'shape:',\n self.X_train.shape)\n print('Class-labels vector shape:', self.y_train.shape)\n\n if self.X_test is not None:\n print('\\nAttached test dataset to user model. Feature matrix '\n 'shape:', self.X_test.shape)\n print('Class-labels vector shape:', self.y_test.shape)\n"
] | [
[
"pandas.concat",
"pandas.read_csv",
"sklearn.model_selection.train_test_split"
],
[
"numpy.ravel",
"sklearn.naive_bayes.MultinomialNB",
"sklearn.preprocessing.LabelEncoder"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
village-people/flying-pig | [
"c86b589aadb02dbfd42a917a388c2b8488ecd338",
"c86b589aadb02dbfd42a917a388c2b8488ecd338"
] | [
"ai_challenge/methods/dqn.py",
"ai_challenge/worker_scripts/collect_from_malmo.py"
] | [
"\"\"\" Deep Q-Learning policy evaluation and improvement\n\"\"\"\nimport torch\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\nimport torch.optim as optim\n\nfrom termcolor import colored as clr\n\n\nclass DQNPolicyImprovement(object):\n \"\"\" Deep Q-Learning training method. \"\"\"\n\n def __init__(self, policy, target_policy, cfg, ddqn=False):\n self.name = \"DQN-PI\"\n self.policy = policy\n self.target_policy = target_policy\n\n self.lr = cfg.training.lr\n self.gamma = cfg.agent.gamma\n\n self.optimizer = optim.Adam(self.policy.parameters(), lr=self.lr)\n self.optimizer.zero_grad()\n\n self.decouple_grad = False\n self.grads_decoupled = False\n self.ddqn = ddqn\n\n def accumulate_gradient(self, batch_sz, states, actions, rewards,\n next_states, mask, next_actions=None):\n \"\"\" Compute the temporal difference error.\n td_error = (r + gamma * max Q(s_,a)) - Q(s,a)\n \"\"\"\n states = Variable(states)\n actions = Variable(actions)\n rewards = Variable(rewards)\n next_states = Variable(next_states, volatile=True)\n if self.ddqn:\n next_actions = Variable(next_actions)\n\n # Compute Q(s, a)\n policy_val = self.policy(states)\n q_values = policy_val.gather(1, actions.unsqueeze(1))\n\n # Compute Q(s_, a)\n q_target_values = None\n if next_states.is_cuda:\n q_target_values = Variable(torch.zeros(batch_sz).cuda())\n else:\n q_target_values = Variable(torch.zeros(batch_sz))\n\n # Bootstrap for non-terminal states\n real_mask = Variable(mask)\n target_q_values = self.target_policy(next_states)\n\n if self.ddqn:\n policy_next_state = target_q_values.gather(\n 1, next_actions.unsqueeze(1)).squeeze()\n else:\n policy_next_state = target_q_values.max(1)[0].view(-1)\n\n q_target_values.scatter_(0, real_mask, policy_next_state)\n\n q_target_values.volatile = False # So we don't mess the huber loss\n expected_q_values = (q_target_values * self.gamma) + rewards\n\n # Compute Huber loss\n loss = F.smooth_l1_loss(q_values, expected_q_values)\n loss.data.clamp_(-1, 1)\n # print(\"Loss: {:.6f}\".format(loss.data[0]))\n # Accumulate gradients\n loss.backward()\n\n def update_model(self):\n for param in self.policy.parameters():\n param.grad.data.clamp_(-1, 1)\n if not self.grads_decoupled and self.decouple_grad:\n param.grad.data = param.grad.data.clone()\n self.grads_decoupled = True\n\n self.optimizer.step()\n self.optimizer.zero_grad()\n\n def update_target_net(self):\n \"\"\" Update the target net with the parameters in the online model.\"\"\"\n self.target_policy.load_state_dict(self.policy.state_dict())\n\n def get_model_stats(self):\n if self.grads_decoupled or not self.decouple_grad:\n param_abs_mean = 0\n grad_abs_mean = 0\n t_param_abs_mean = 0\n n_params = 0\n for p in self.policy.parameters():\n param_abs_mean += p.data.abs().sum()\n grad_abs_mean += p.grad.data.abs().sum()\n n_params += p.data.nelement()\n for t in self.target_policy.parameters():\n t_param_abs_mean += t.data.abs().sum()\n\n print(\"Wm: %.9f | Gm: %.9f | Tm: %.9f\" % (\n param_abs_mean / n_params,\n grad_abs_mean / n_params,\n t_param_abs_mean / n_params))\n\n def _debug_transitions(self, mask, reward_batch):\n if mask[0] == 0:\n r = reward_batch[0, 0]\n if r == 1.0:\n print(r)\n\n def _debug_states(self, state_batch, next_state_batch, mask):\n for i in range(24):\n for j in range(24):\n px = state_batch[0, 0, i, j]\n if px < 0.90:\n print(clr(\"%.2f \" % px, 'magenta'), end=\"\")\n else:\n print((\"%.2f \" % px), end=\"\")\n print()\n for i in range(24):\n for j in range(24):\n px = next_state_batch[0, 0, i, j]\n if px < 0.90:\n print(clr(\"%.2f \" % px, 'magenta'), end=\"\")\n else:\n print(clr(\"%.2f \" % px, 'white'), end=\"\")\n print()\n if mask[0] == 0:\n print(clr(\"Done batch ............\", 'magenta'))\n else:\n print(\".......................\")\n",
"# Village People, 2017\n\nfrom pig_chase.common import ENV_ACTIONS\nfrom pig_chase.agent import PigChaseChallengeAgent\nfrom pig_chase.common import ENV_AGENT_NAMES\nfrom pig_chase.environment import PigChaseEnvironment, \\\n PigChaseSymbolicStateBuilder\n\nfrom env.VillagePeopleBuilders import PigChaseVillagePeopleBuilder18Binary\nimport torch\n\nfrom time import sleep\n\nfrom agents import get_agent\nimport torch.multiprocessing as mp\n\nfrom termcolor import colored as clr\n\n\ndef print_info(message):\n print(clr(\"[QUEUE_COLLECT] \", \"magenta\") + message)\n\n\ndef start_minecraft():\n raise NotImplementedError\n\n\ndef restart_minecraft():\n raise NotImplementedError\n\n\ndef collect_from_malmo(id_, shared_objects, cfg):\n clients = cfg.envs.minecraft.ports\n my_id = id_\n reset = shared_objects[\"reset\"]\n session_id = shared_objects[\"session\"]\n queue = shared_objects[\"queue\"]\n\n if \"predict_queue\" in shared_objects:\n use_predict_queue = True\n predict_queue = shared_objects[\"predict_queue\"]\n answer_queue = shared_objects[\"answer_pipe\"][my_id]\n else:\n use_predict_queue = False\n\n # ----------------------- Run Challenge agent ------------------------------\n challenger_stopped = mp.Value(\"i\", 0)\n shared_obj_ = {\"stopped\": challenger_stopped}\n p = mp.Process(target=run_challenge_agent, args=(id_, clients, shared_obj_))\n p.start()\n sleep(5)\n\n # ----------------------- Run VillageP Agent -------------------------------\n # --- Start agent\n\n agent_role = 1\n cfg.general.use_cuda = True\n\n if not use_predict_queue:\n agent_actor = get_agent(cfg.agent.type)(cfg.agent.name, ENV_ACTIONS,\n cfg,\n shared_objects)\n # SET Not max predictor\n agent_actor.predict_max = False\n\n # agent = PigChaseVillagePopleAgent(ENV_AGENT_NAMES[agent_role], ENV_ACTIONS,\n # agent_actor,\n # use_cuda=cfg.general.use_cuda)\n\n state_builder = PigChaseVillagePeopleBuilder18Binary(agent_role)\n print(\"A3C: \", clients)\n env = PigChaseEnvironment(clients, state_builder,\n role=1, randomize_positions=True)\n\n agent_done = False\n reward = 0\n episode = 0\n step = 0\n obs = env.reset()\n received_none = 0\n\n while obs is None:\n # this can happen if the episode ended with the first\n # action of the other agent\n # print('Warning: received obs == None.')\n received_none += 1\n if received_none == 10:\n print(\"[[{}]] Panic !!! > Received {} None in a row\"\n .format(id_, received_none))\n\n if received_none == 100:\n print(\"[[{}]] Panic! Challenger stopped.\"\n \" Received {} None in a row\"\n .format(id_, received_none))\n return -1\n\n print(\"[[{}]] Born an playing!\".format(id_))\n\n ep_states = []\n crt_session_id = session_id.value\n while True:\n step += 1\n # check if env needs reset\n # print(\"AGENT123123\")\n\n if env.done or agent_done:\n # print(\"[[{}]] Done ep {}.\".format(id_, episode))\n\n if challenger_stopped.value < 0:\n print(\"[[{}]] Child process ended!!\".format(id_))\n pass\n\n if reset.value == 1:\n # --- Master is training network\n\n # ---- Restart ----------------------\n # TODO restart MInecraft process\n\n while reset.value == 1:\n sleep(0.1)\n ep_states.clear()\n\n if session_id.value != crt_session_id:\n ep_states.clear()\n crt_session_id = session_id.value\n\n if len(ep_states) > 0:\n # --- Will be restarted\n state_ = torch.LongTensor(obs).unsqueeze(0)\n done_ = torch.LongTensor([int(agent_done)])\n reward_ = torch.FloatTensor([reward])\n if use_predict_queue:\n predict_queue.put(\n (my_id, state_.cpu().numpy(), done_.cpu().numpy(), 23))\n (act, _) = answer_queue.recv()\n act = torch.LongTensor([act])\n else:\n act = agent_actor.act(state_.cuda(), reward_.cuda(),\n done_.cuda(), False)\n # act = agent_actor.act(state_, reward_, done_, False)\n ep_states.append((state_.cpu().numpy(),\n reward_.cpu().numpy(),\n done_.cpu().numpy(),\n act.cpu().numpy()))\n\n queue.put(ep_states)\n ep_states = []\n\n obs = env.reset()\n received_none = 0\n while obs is None:\n # this can happen if the episode ended with the first\n # action of the other agent\n # print('Warning: received obs == None.')\n received_none += 1\n if received_none == 10:\n print(\"[[{}]] Panic !!! > Received {} None in a row\"\n .format(id_, received_none))\n\n if received_none == 10000:\n print(\"[[{}]] Panic! Challenger stopped.\"\n \" Received {} None in a row\"\n .format(id_, received_none))\n sleep(5)\n obs = env.reset()\n\n episode += 1\n\n state_ = torch.LongTensor(obs).unsqueeze(0)\n reward_ = torch.FloatTensor([reward])\n done_ = torch.LongTensor([int(agent_done)])\n\n if not agent_done:\n if use_predict_queue:\n predict_queue.put((my_id, state_.cpu().numpy(),\n done_.cpu().numpy(), 23))\n (act, _) = answer_queue.recv()\n act = torch.LongTensor([act])\n else:\n act = agent_actor.act(state_.cuda(), reward_.cuda(),\n done_.cuda(), False)\n else:\n reward_[0] = 0\n done_[0] = 0\n if use_predict_queue:\n predict_queue.put((my_id, state_.cpu().numpy(),\n done_.cpu().numpy(), 23))\n (act, _) = answer_queue.recv()\n act = torch.LongTensor([act])\n else:\n act = agent_actor.act(state_.cuda(), reward_.cuda(),\n done_.cuda(), False)\n # act = agent_actor.act(state_, reward_, done_, False)\n\n ep_states.append((state_.cpu().numpy(),\n reward_.cpu().numpy(),\n done_.cpu().numpy(),\n act.cpu().numpy()))\n\n obs, reward, agent_done = env.do(act[0])\n\n\ndef run_challenge_agent(id_, clients, shared_objects):\n # print(\"AGENT2\")\n builder = PigChaseSymbolicStateBuilder()\n print(\"Challanger: \", clients)\n env = PigChaseEnvironment(clients, builder, role=0,\n randomize_positions=True)\n agent = PigChaseChallengeAgent(ENV_AGENT_NAMES[0])\n # agent = RandomAgent(ENV_AGENT_NAMES[0])\n\n agent_done = False\n reward = 0\n episode = 0\n obs = env.reset()\n\n stop_ = shared_objects[\"stopped\"]\n # print(\"AGENT22\")\n while True:\n # check if env needs reset\n if env.done:\n\n obs = env.reset()\n received_none = 0\n while obs is None:\n # this can happen if the episode ended with the first\n # action of the other agent\n # print('Warning: received obs == None.')\n received_none += 1\n if received_none == 10:\n print(\"[[{}]] Panic !!! > Received {} None in a row\"\n .format(id_, received_none))\n\n if received_none == 30:\n print(\"[[{}]] Panic! Challenger stopped.\"\n \" Received {} None in a row\"\n .format(id_, received_none))\n stop_.value = -1\n return -1\n\n obs = env.reset()\n\n episode += 1\n\n # select an action\n action = agent.act(obs, reward, agent_done, is_training=False)\n # take a step\n obs, reward, agent_done = env.do(action)\n"
] | [
[
"torch.zeros",
"torch.nn.functional.smooth_l1_loss",
"torch.autograd.Variable"
],
[
"torch.LongTensor",
"torch.FloatTensor",
"torch.multiprocessing.Value",
"torch.multiprocessing.Process"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
cnavarreteliz/Datos-COVID19 | [
"4383c6a82f5ec41d55875daf6ce2d2ed71785aa4"
] | [
"src/bulk_producto2.py"
] | [
"import pandas as pd\nimport glob\nimport re\n\ndf = []\nfor file in glob.glob(\"../output/producto2/*.csv\"):\n date = re.search(\"\\d{4}-\\d{2}-\\d{2}\", file).group(0).replace(\"-\", \"/\")\n fragment = pd.read_csv(file)\n fragment[\"Fecha\"] = date\n df.append(fragment)\n\ndf = pd.concat(df)\n\n# Reemplaza nombres de comuna, para coincidir con los publicados por SUBDERE\ndf[\"Comuna\"] = df[\"Comuna\"].replace({\"Coyhaique\": \"Coihaique\", \"OHiggins\": \"O'Higgins\"})\n\n# Lee IDs de comunas desde página web oficial de SUBDERE\ndf_dim_comunas = pd.read_excel(\"http://www.subdere.gov.cl/sites/default/files/documentos/cut_2018_v03.xls\", encoding=\"utf-8\")\n\n# Crea columna sin tildes, para hacer merge con datos publicados\ndf_dim_comunas[\"Comuna\"] = df_dim_comunas[\"Nombre Comuna\"].str.normalize(\"NFKD\").str.encode(\"ascii\", errors=\"ignore\").str.decode(\"utf-8\")\n\ndf = df.merge(df_dim_comunas, on=\"Comuna\", how=\"outer\")\n\ndf = df.drop(columns=[\"Comuna\", \"Region\", \"Codigo region\", \"Codigo comuna\"])\ndf = df.rename(columns={\n \"Nombre Región\": \"Region\",\n \"Nombre Provincia\": \"Provincia\", \n \"Nombre Comuna\": \"Comuna\",\n \"Código Región\": \"Region ID\",\n \"Código Provincia\": \"Provincia ID\",\n \"Código Comuna 2017\": \"Comuna ID\"\n})\n\ndf[\"Casos Confirmados\"] = df[\"Casos Confirmados\"].fillna(\"-\")\n\ndf[\"Tasa\"] = df.apply(lambda x: (100000 * int(x[\"Casos Confirmados\"]) / x[\"Poblacion\"]) if x[\"Casos Confirmados\"] != \"-\" else \"-\", axis=1) \n\n# Crea output de datos en CSV / JSON\ndf.to_csv(\"../output/producto6/bulk/producto2.csv\", index=False)\ndf.to_json(\"../output/producto6/bulk/producto2.json\", orient=\"records\")"
] | [
[
"pandas.concat",
"pandas.read_excel",
"pandas.read_csv"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
streeve/PI3NN | [
"f7f08a195096e0388bb9230bc67c6acd6f41581a",
"f7f08a195096e0388bb9230bc67c6acd6f41581a",
"f7f08a195096e0388bb9230bc67c6acd6f41581a"
] | [
"NeurIPS_2021/Figure_1/DER_cubic/trainers/evidential_V2.py",
"NeurIPS_2021/Figure_1/DER_cubic/trainers/bbbp.py",
"ICLR_2022/Flight_delay/PIVEN/PIVEN_flight_delay.py"
] | [
"import numpy as np\nimport tensorflow as tf\nimport time\nimport datetime\nimport os\nimport sys\nimport h5py\nfrom pathlib import Path\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nimport evidential_deep_learning as edl\nfrom .util import normalize, gallery\n\nclass Evidential:\n def __init__(self, model, opts, dataset=\"\", learning_rate=1e-3, lam=0.0, epsilon=1e-2, maxi_rate=1e-4, tag=\"\", custom_plot_folder=\"\", custom_best_results_dat_folder=\"\"):\n self.nll_loss_function = edl.losses.NIG_NLL\n self.reg_loss_function = edl.losses.NIG_Reg\n\n self.model = model\n self.learning_rate = learning_rate\n self.maxi_rate = maxi_rate\n\n self.optimizer = tf.optimizers.Adam(self.learning_rate)\n self.lam = tf.Variable(lam)\n\n self.epsilon = epsilon\n\n self.min_rmse = self.running_rmse = float('inf')\n self.min_nll = self.running_nll = float('inf')\n self.min_vloss = self.running_vloss = float('inf')\n\n trainer = self.__class__.__name__\n current_time = datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\")\n self.save_dir = os.path.join('save','{}_{}_{}_{}'.format(current_time, dataset, trainer, tag))\n Path(self.save_dir).mkdir(parents=True, exist_ok=True)\n\n self.custom_plot_folder = custom_plot_folder\n Path(self.custom_plot_folder).mkdir(parents=True, exist_ok=True)\n ''' Create 4 folders for valid/test plots for Epistemic/Aleatoric uncertainty'''\n Path(self.custom_plot_folder + '/valid_epistemic').mkdir(parents=True, exist_ok=True)\n Path(self.custom_plot_folder + '/valid_aleatoric').mkdir(parents=True, exist_ok=True)\n Path(self.custom_plot_folder + '/test_epistemic').mkdir(parents=True, exist_ok=True)\n Path(self.custom_plot_folder + '/test_aleatoric').mkdir(parents=True, exist_ok=True)\n\n self.custom_best_results_dat_folder = custom_best_results_dat_folder\n Path(self.custom_best_results_dat_folder).mkdir(parents=True, exist_ok=True)\n\n train_log_dir = os.path.join('logs', '{}_{}_{}_{}_train'.format(current_time, dataset, trainer, tag))\n self.train_summary_writer = tf.summary.create_file_writer(train_log_dir)\n val_log_dir = os.path.join('logs', '{}_{}_{}_{}_val'.format(current_time, dataset, trainer, tag))\n self.val_summary_writer = tf.summary.create_file_writer(val_log_dir)\n\n def loss_function(self, y, mu, v, alpha, beta, reduce=True, return_comps=False):\n nll_loss = self.nll_loss_function(y, mu, v, alpha, beta, reduce=reduce)\n reg_loss = self.reg_loss_function(y, mu, v, alpha, beta, reduce=reduce)\n loss = nll_loss + self.lam * (reg_loss - self.epsilon)\n # loss = nll_loss\n\n return (loss, (nll_loss, reg_loss)) if return_comps else loss\n\n @tf.function\n def run_train_step(self, x, y):\n with tf.GradientTape() as tape:\n outputs = self.model(x, training=True)\n mu, v, alpha, beta = tf.split(outputs, 4, axis=-1)\n loss, (nll_loss, reg_loss) = self.loss_function(y, mu, v, alpha, beta, return_comps=True)\n\n grads = tape.gradient(loss, self.model.trainable_variables) #compute gradient\n self.optimizer.apply_gradients(zip(grads, self.model.trainable_variables))\n self.lam = self.lam.assign_add(self.maxi_rate * (reg_loss - self.epsilon)) #update lambda\n\n return loss, nll_loss, reg_loss, mu, v, alpha, beta\n\n @tf.function\n def evaluate(self, x, y):\n outputs = self.model(x, training=False)\n mu, v, alpha, beta = tf.split(outputs, 4, axis=-1)\n\n rmse = edl.losses.RMSE(y, mu)\n loss, (nll, reg_loss) = self.loss_function(y, mu, v, alpha, beta, return_comps=True)\n\n return mu, v, alpha, beta, loss, rmse, nll, reg_loss\n\n def normalize(self, x):\n return tf.divide(tf.subtract(x, tf.reduce_min(x)),\n tf.subtract(tf.reduce_max(x), tf.reduce_min(x)))\n\n\n def save_train_summary(self, loss, x, y, y_hat, v, alpha, beta):\n # np.random.seed(1234)\n with self.train_summary_writer.as_default():\n tf.summary.scalar('mse', tf.reduce_mean(edl.losses.MSE(y, y_hat)), step=self.iter)\n tf.summary.scalar('loss', tf.reduce_mean(self.loss_function(y, y_hat, v, alpha, beta)), step=self.iter)\n # pass\n idx = np.random.choice(int(tf.shape(x)[0]), 9) ### !!! give different model predictions !!!!!\n if tf.shape(x).shape==4:\n tf.summary.image(\"x\", [gallery(tf.gather(x,idx).numpy())], max_outputs=1, step=self.iter)\n\n if tf.shape(y).shape==4:\n tf.summary.image(\"y\", [gallery(tf.gather(y,idx).numpy())], max_outputs=1, step=self.iter)\n tf.summary.image(\"y_hat\", [gallery(tf.gather(y_hat,idx).numpy())], max_outputs=1, step=self.iter)\n\n # ''' Add additional saving for predicted y_hat and y_var '''\n # def save_train_summary_scalar(self, loss, x, y, y_hat, v, alpha, beta):\n # with self.train_summary_writer.as_default():\n # tf.summary.scalar('mse', tf.reduce_mean(edl.losses.MSE(y, y_hat)), step=self.iter)\n # tf.summary.scalar('loss', tf.reduce_mean(self.loss_function(y, y_hat, v, alpha, beta)), step=self.iter)\n # # tf.summary.scalar('y_hat_2', y_hat, step=self.iter)\n # # var = beta / (v * (alpha - 1))\n # # tf.summary.scalar('var', var, step=self.iter)\n # idx = np.random.choice(int(tf.shape(x)[0]), 9)\n # if tf.shape(x).shape == 4:\n # tf.summary.image(\"x\", [gallery(tf.gather(x, idx).numpy())], max_outputs=1, step=self.iter)\n #\n # if tf.shape(y).shape == 4:\n # tf.summary.image(\"y\", [gallery(tf.gather(y, idx).numpy())], max_outputs=1, step=self.iter)\n # tf.summary.image(\"y_hat\", [gallery(tf.gather(y_hat, idx).numpy())], max_outputs=1, step=self.iter)\n\n def save_val_summary(self, loss, x, y, mu, v, alpha, beta):\n with self.val_summary_writer.as_default():\n tf.summary.scalar('mse', tf.reduce_mean(edl.losses.MSE(y, mu)), step=self.iter)\n tf.summary.scalar('loss', tf.reduce_mean(self.loss_function(y, mu, v, alpha, beta)), step=self.iter)\n idx = np.random.choice(int(tf.shape(x)[0]), 9)\n\n # var = beta / (v * (alpha - 1))\n # print('--Type of v: {}'.format(type(v)))\n # print('--Type of alpha: {}'.format(type(alpha)))\n # print('--Type of beta: {}'.format(type(beta)))\n # print('--Type of var: {}'.format(type(var)))\n\n if tf.shape(x).shape==4:\n tf.summary.image(\"x\", [gallery(tf.gather(x,idx).numpy())], max_outputs=1, step=self.iter)\n\n if tf.shape(y).shape==4:\n tf.summary.image(\"y\", [gallery(tf.gather(y,idx).numpy())], max_outputs=1, step=self.iter)\n tf.summary.image(\"y_hat\", [gallery(tf.gather(mu,idx).numpy())], max_outputs=1, step=self.iter)\n var = beta/(v*(alpha-1))\n tf.summary.image(\"y_var\", [gallery(normalize(tf.gather(var,idx)).numpy())], max_outputs=1, step=self.iter)\n\n def get_batch(self, x, y, batch_size):\n idx = np.random.choice(x.shape[0], batch_size, replace=False)\n if isinstance(x, tf.Tensor):\n x_ = x[idx,...]\n y_ = y[idx,...]\n elif isinstance(x, np.ndarray) or isinstance(x, h5py.Dataset):\n idx = np.sort(idx)\n x_ = x[idx,...]\n y_ = y[idx,...]\n\n x_divisor = 255. if x_.dtype == np.uint8 else 1.0\n y_divisor = 255. if y_.dtype == np.uint8 else 1.0\n\n x_ = tf.convert_to_tensor(x_/x_divisor, tf.float32)\n y_ = tf.convert_to_tensor(y_/y_divisor, tf.float32)\n else:\n print(\"unknown dataset type {} {}\".format(type(x), type(y)))\n return x_, y_\n\n def save(self, name):\n self.model.save(os.path.join(self.save_dir, \"{}.h5\".format(name)))\n\n def update_running(self, previous, current, alpha=0.0):\n if previous == float('inf'):\n new = current\n else:\n new = alpha*previous + (1-alpha)*current\n return new\n\n\n ''' Siyan added for testing plot '''\n def plot_scatter_with_var_from_pandas(self, x_train, y_train, x_test, y_test, mu, var, path, n_stds=3, test_bounds=[[-7, +7]], show=True):\n plt.scatter(x_train, y_train, s=1., c='#463c3c', zorder=0, label='Train (x_train vs y_train)')\n for k in np.linspace(0, n_stds, 4):\n if k == 0:\n plt.fill_between(x_test[:, 0], (mu - k * var), (mu + k * var), alpha=0.3, edgecolor=None,\n facecolor='#00aeef', linewidth=0, antialiased=True, zorder=1, label='Unc.')\n else:\n plt.fill_between(x_test[:, 0], (mu - k * var), (mu + k * var), alpha=0.3, edgecolor=None,\n facecolor='#00aeef', linewidth=0, antialiased=True, zorder=1)\n\n plt.plot(x_test, y_test, 'r--', zorder=2, label='True (x_test vs y_test)')\n plt.plot(x_test, mu, color='#007cab', zorder=3, label='Pred (x_test vs mu)')\n plt.gca().set_xlim(*test_bounds)\n plt.gca().set_ylim(-150, 150)\n plt.title(path)\n plt.legend()\n # print('asdfsdafdsafdsafsdafdsaf')\n # print(path)\n plt.savefig(path, transparent=True)\n if show:\n plt.show()\n plt.clf()\n\n ''' Siyan added for testing plot V2 '''\n def plot_scatter_with_var_from_pandas_v2(self, iter, x_train, y_train, x_test, y_test, mu, var, path, n_stds=3, test_bounds=[[-7, +7]], evalType='valid', uq='epistemic', show=True, save=False):\n # print(path)\n plt.scatter(x_train, y_train, s=1., c='#463c3c', zorder=0, label='Train (x_train vs y_train)')\n idxx = np.argsort(x_test.flatten())\n x_test = x_test.flatten()[idxx]\n y_test = y_test.flatten()[idxx]\n # mu = mu.numpy().flatten()[idxx]\n mu = mu.flatten()[idxx]\n var = var.flatten()[idxx]\n for k in np.linspace(0, n_stds, 4):\n if k == 0:\n plt.fill_between(x_test, (mu - k * var), (mu + k * var), alpha=0.3, edgecolor=None,\n facecolor='#00aeef', linewidth=0, antialiased=True, zorder=1, label='Unc.')\n else:\n plt.fill_between(x_test, (mu - k * var), (mu + k * var), alpha=0.3, edgecolor=None,\n facecolor='#00aeef', linewidth=0, antialiased=True, zorder=1)\n\n # idxx = np.argsort(x_test.flatten())\n # print(idxx)\n # plt.plot(x_test.flatten()[idxx], y_test.flatten()[idxx], 'r--', zorder=2, label='True (x_test vs y_test)')\n # plt.plot(x_test.flatten()[idxx], mu.flatten()[idxx], color='#007cab', zorder=3, label='Pred (x_test vs mu)')\n\n if evalType == 'valid':\n plt.plot(x_test, y_test, 'r--', zorder=2, label='True (x_valid vs y_valid)')\n plt.plot(x_test, mu, color='#007cab', zorder=3, label='Pred (x_valid vs mu)')\n elif evalType == 'test':\n plt.plot(x_test, y_test, 'r--', zorder=2, label='True (x_test vs y_test)')\n plt.plot(x_test, mu, color='#007cab', zorder=3, label='Pred (x_test vs mu)')\n\n plt.gca().set_xlim(*test_bounds)\n plt.gca().set_ylim(-150, 150)\n plt.title(path)\n if uq == 'epistemic':\n plt.suptitle('Epistemic uncertainty of {} data (Iters: {})\\n'.format(evalType, iter), fontsize=18)\n elif uq == 'aleatoric':\n plt.suptitle('Aleatoric uncertainty of {} data (Iters: {})\\n'.format(evalType, iter), fontsize=18)\n\n plt.legend()\n if save:\n plt.savefig(path)\n if show:\n plt.show()\n plt.clf()\n\n\n\n def train(self, x_train, y_train, x_test, y_test, x_valid, y_valid, y_scale, batch_size=128, iters=10000, verbose=True):\n ''' Siyan added START '''\n # np.random.seed(1234)\n test_eval_count = 0\n valid_eval_count = 0\n test_best_iter_str = '0'\n valid_best_iter_str = '0'\n\n x_valid_input = tf.convert_to_tensor(x_valid, tf.float32)\n y_valid_input = tf.convert_to_tensor(y_valid, tf.float32)\n\n ''' Siyan added END '''\n tic = time.time()\n for self.iter in range(iters):\n x_input_batch, y_input_batch = self.get_batch(x_train, y_train, batch_size)\n loss, nll_loss, reg_loss, y_hat, v, alpha, beta = self.run_train_step(x_input_batch, y_input_batch)\n\n # if self.iter % 10 == 0:\n # # np.random.seed(1234)\n # self.save_train_summary(loss, x_input_batch, y_input_batch, y_hat, v, alpha, beta)\n # # self.save_train_summary_scalar(loss, x_input_batch, y_input_batch, y_hat, v, alpha, beta)\n #\n if self.iter % 10 == 0:\n x_test_batch, y_test_batch = self.get_batch(x_test, y_test, min(100, x_test.shape[0]))\n mu, v, alpha, beta, vloss, rmse, nll, reg_loss = self.evaluate(x_test_batch, y_test_batch)\n\n nll += np.log(y_scale[0, 0])\n rmse *= y_scale[0, 0]\n\n ## validation summary\n self.save_val_summary(vloss, x_test_batch, y_test_batch, mu, v, alpha, beta)\n\n self.running_rmse = self.update_running(self.running_rmse, rmse.numpy())\n if self.running_rmse < self.min_rmse:\n self.min_rmse = self.running_rmse\n # self.save(f\"model_rmse_{self.iter}\")\n\n self.running_nll = self.update_running(self.running_nll, nll.numpy())\n if self.running_nll < self.min_nll:\n self.min_nll = self.running_nll\n # self.save(f\"model_nll_{self.iter}\")\n\n self.running_vloss = self.update_running(self.running_vloss, vloss.numpy())\n if self.running_vloss < self.min_vloss:\n self.min_vloss = self.running_vloss\n # self.save(f\"model_vloss_{self.iter}\")\n\n # if verbose: print(\n # \"[A {}] RMSE: {:.4f} \\t NLL: {:.4f} \\t loss: {:.4f} \\t reg_loss: {:.4f} \\t lambda: {:.2f} \\t t: {:.2f} sec\".format(\n # self.iter, self.min_rmse, self.min_nll, vloss, reg_loss.numpy().mean(), self.lam.numpy(),\n # time.time() - tic))\n\n\n\n # ### Loss function for reference\n # def loss_function(self, y, mu, v, alpha, beta, reduce=True, return_comps=False):\n # nll_loss = self.nll_loss_function(y, mu, v, alpha, beta, reduce=reduce)\n # reg_loss = self.reg_loss_function(y, mu, v, alpha, beta, reduce=reduce)\n # loss = nll_loss + self.lam * (reg_loss - self.epsilon)\n # return (loss, (nll_loss, reg_loss)) if return_comps else loss\n\n\n if self.iter % 10 == 0:\n # self.save_train_summary(loss, x_input_batch, y_input_batch, y_hat, v, alpha, beta)\n\n\n ''' Siyan Test START --- (for entire test data instead of batch of test data)'''\n x_test_input = tf.convert_to_tensor(x_test, tf.float32)\n y_test_input = tf.convert_to_tensor(y_test, tf.float32)\n tmp_outputs_1 = self.model(x_test_input, training=False)\n test_mu, test_v, test_alpha, test_beta = tf.split(tmp_outputs_1, 4, axis=1)\n test_rmse = edl.losses.RMSE(y_test_input, test_mu)\n\n ### Calculate loss for all training data instead of a batch of training data\n test_loss, (test_nll_loss, test_reg_loss) = self.loss_function(y_test_input, test_mu, test_v, test_alpha, test_beta, return_comps=True)\n # print(test_reg_loss)\n if test_eval_count == 0:\n tmp_test_loss = test_loss\n else:\n if test_loss < tmp_test_loss:\n tmp_test_loss = test_loss\n print(\"[{}] Test loss: {:.6f} \\t RMSE: {:.4f} \\t NLL: {:.4f} \\t reg_loss: {:.4f} \\t lambda: {:.2f}\".\n format(self.iter, test_loss, test_rmse.numpy(), test_nll_loss.numpy(), test_reg_loss.numpy(), self.lam.numpy()))\n ### update the DataFrame\n test_results_df = pd.DataFrame({\n 'test_x': list(x_test.flatten()),\n 'test_y': list(y_test.flatten()),\n 'test_mu': list(test_mu.numpy().flatten()),\n 'test_v': list(test_v.numpy().flatten()),\n 'test_alpha': list(test_alpha.numpy().flatten()),\n 'test_beta': list(test_beta.numpy().flatten()),\n })\n test_best_iter_str = str(self.iter)\n test_eval_count += 1\n ''' Siyan Test END --- (for entire test data instead of batch of test data)'''\n\n ''' Siyan Test START --- (for entire validation data instead of batch of validation data)'''\n tmp_outputs_2 = self.model(x_valid_input, training=False)\n valid_mu, valid_v, valid_alpha, valid_beta = tf.split(tmp_outputs_2, 4, axis=1)\n valid_rmse = edl.losses.RMSE(y_valid_input, valid_mu)\n\n valid_loss, (valid_nll_loss, valid_reg_loss) = self.loss_function(y_valid_input, valid_mu, valid_v,\n valid_alpha, valid_beta,\n return_comps=True)\n\n # print(\"[{}] Valid loss: {:.6f} \\t RMSE: {:.4f} \\t NLL: {:.4f} \\t reg_loss: {:.4f} \\t lambda: {:.2f}\".\n # format(self.iter, valid_loss, valid_rmse.numpy(), valid_nll_loss.numpy(), valid_reg_loss.numpy(),\n # self.lam.numpy()))\n\n if valid_eval_count == 0:\n tmp_valid_loss = valid_loss\n # tmp_valid_rmse = valid_rmse\n else:\n if valid_loss < tmp_valid_loss:\n # if valid_rmse < tmp_valid_rmse:\n tmp_valid_loss = valid_loss\n # tmp_valid_rmse = valid_rmse\n print(\"[{}] Valid loss: {:.6f} \\t RMSE: {:.4f} \\t NLL: {:.4f} \\t reg_loss: {:.4f} \\t lambda: {:.2f}\".\n format(self.iter, valid_loss, valid_rmse.numpy(), valid_nll_loss.numpy(), valid_reg_loss.numpy(), self.lam.numpy()))\n ### update the DataFrame\n valid_results_df = pd.DataFrame({\n 'valid_x': list(x_valid.flatten()),\n 'valid_y': list(y_valid.flatten()),\n 'valid_mu': list(valid_mu.numpy().flatten()),\n 'valid_v': list(valid_v.numpy().flatten()),\n 'valid_alpha': list(valid_alpha.numpy().flatten()),\n 'valid_beta': list(valid_beta.numpy().flatten()),\n })\n valid_best_iter_str = str(self.iter)\n\n # valid_results_df = pd.DataFrame({\n # 'valid_x': list(x_valid.flatten()),\n # 'valid_y': list(y_valid.flatten()),\n # 'valid_mu': list(valid_mu.numpy().flatten()),\n # 'valid_v': list(valid_v.numpy().flatten()),\n # 'valid_alpha': list(valid_alpha.numpy().flatten()),\n # 'valid_beta': list(va.lid_beta.numpy().flatten()),\n # })\n valid_eval_count += 1\n\n ''' Siyan Test END --- (for entire validation data instead of batch of validation data)'''\n test_results_df.to_csv(self.custom_best_results_dat_folder + \"/best_test_results_iter_\"+test_best_iter_str+\".dat\", sep=\" \")\n print('--- Saved testing results to '+self.custom_best_results_dat_folder+'/best_test_results_iter_'+test_best_iter_str+\".dat\")\n valid_results_df.to_csv(self.custom_best_results_dat_folder + \"/best_valid_results_iter_\"+valid_best_iter_str+\".dat\", sep=\" \")\n print('--- Saved validation results to '+self.custom_best_results_dat_folder +'/best_valid_results_iter_'+valid_best_iter_str+\".dat\")\n\n ''' Test/validation results calculation and plotting:\n (1) Best train results; (2) Best validation results. And compare to the original results\n '''\n load_test_df = pd.read_csv(self.custom_best_results_dat_folder + \"/best_test_results_iter_\"+test_best_iter_str+\".dat\", sep=\" \")\n load_valid_df = pd.read_csv(self.custom_best_results_dat_folder + \"/best_valid_results_iter_\"+valid_best_iter_str+\".dat\", sep=\" \")\n\n epistemic_test = np.sqrt(load_test_df['test_beta'].values / (load_test_df['test_v'].values * (load_test_df['test_alpha'].values - 1)))\n epistemic_test = np.minimum(epistemic_test, 1e3) # clip the unc for vis\n\n print(load_test_df)\n epistemic_valid = np.sqrt(load_valid_df['valid_beta'].values / (load_valid_df['valid_v'].values * (load_valid_df['valid_alpha'].values - 1)))\n epistemic_valid = np.minimum(epistemic_valid, 1e3) # clip the unc for vis\n\n valid_bounds = [[-7, +7]]\n self.plot_scatter_with_var_from_pandas(x_train, y_train, x_valid, y_valid,\n load_test_df['test_mu'].values, epistemic_test, path=self.custom_plot_folder+\"/test_plot.pdf\", n_stds=3, test_bounds=valid_bounds, show=True)\n self.plot_scatter_with_var_from_pandas(x_train, y_train, x_valid, y_valid,\n load_valid_df['valid_mu'].values, epistemic_valid, path=self.custom_plot_folder+\"/valid_plot.pdf\", n_stds=3, test_bounds=valid_bounds, show=True)\n\n\n return self.model, self.min_rmse, self.min_nll\n\n\n # def train(self, x_train, y_train, x_test, y_test, x_valid, y_valid, y_scale, batch_size=128, iters=10000, verbose=True):\n def train_v2(self, x_train, y_train, x_valid, y_valid, x_test, y_test, y_scale, batch_size=128, iters=10000, verbose=True):\n ''' Siyan added START '''\n # np.random.seed(1234)\n valid_eval_count = 0\n valid_best_iter_str = '0'\n test_eval_count = 0\n test_best_iter_str = '0'\n\n x_test_input = tf.convert_to_tensor(x_test, tf.float32)\n y_test_input = tf.convert_to_tensor(y_test, tf.float32)\n\n ''' Siyan added END '''\n tic = time.time()\n for self.iter in range(iters):\n x_input_batch, y_input_batch = self.get_batch(x_train, y_train, batch_size)\n loss, nll_loss, reg_loss, y_hat, v, alpha, beta = self.run_train_step(x_input_batch, y_input_batch)\n\n if self.iter % 10 == 0:\n # np.random.seed(1234)\n self.save_train_summary(loss, x_input_batch, y_input_batch, y_hat, v, alpha, beta)\n # self.save_train_summary_scalar(loss, x_input_batch, y_input_batch, y_hat, v, alpha, beta)\n\n if self.iter % 10 == 0:\n x_valid_batch, y_valid_batch = self.get_batch(x_valid, y_valid, min(100, x_valid.shape[0]))\n mu, v, alpha, beta, vloss, rmse, nll, reg_loss = self.evaluate(x_valid_batch, y_valid_batch)\n\n nll += np.log(y_scale[0, 0])\n rmse *= y_scale[0, 0]\n\n ## validation summary\n self.save_val_summary(vloss, x_valid_batch, y_valid_batch, mu, v, alpha, beta)\n\n self.running_rmse = self.update_running(self.running_rmse, rmse.numpy())\n if self.running_rmse < self.min_rmse:\n self.min_rmse = self.running_rmse\n # self.save(f\"model_rmse_{self.iter}\")\n\n self.running_nll = self.update_running(self.running_nll, nll.numpy())\n if self.running_nll < self.min_nll:\n self.min_nll = self.running_nll\n # self.save(f\"model_nll_{self.iter}\")\n\n self.running_vloss = self.update_running(self.running_vloss, vloss.numpy())\n if self.running_vloss < self.min_vloss:\n self.min_vloss = self.running_vloss\n # self.save(f\"model_vloss_{self.iter}\")\n\n # if verbose: print(\n # \"[A {}] RMSE: {:.4f} \\t NLL: {:.4f} \\t loss: {:.4f} \\t reg_loss: {:.4f} \\t lambda: {:.2f} \\t t: {:.2f} sec\".format(\n # self.iter, self.min_rmse, self.min_nll, vloss, reg_loss.numpy().mean(), self.lam.numpy(),\n # time.time() - tic))\n\n # ### Loss function for reference\n # def loss_function(self, y, mu, v, alpha, beta, reduce=True, return_comps=False):\n # nll_loss = self.nll_loss_function(y, mu, v, alpha, beta, reduce=reduce)\n # reg_loss = self.reg_loss_function(y, mu, v, alpha, beta, reduce=reduce)\n # loss = nll_loss + self.lam * (reg_loss - self.epsilon)\n # return (loss, (nll_loss, reg_loss)) if return_comps else loss\n\n\n if self.iter % 10 == 0 or self.iter < 50 or self.iter >= iters - 50:\n # self.save_train_summary(loss, x_input_batch, y_input_batch, y_hat, v, alpha, beta)\n\n ''' Siyan Test START --- (for all validation dat)'''\n x_valid_input = tf.convert_to_tensor(x_valid, tf.float32)\n y_valid_input = tf.convert_to_tensor(y_valid, tf.float32)\n tmp_outputs_1 = self.model(x_valid_input, training=False)\n valid_mu, valid_v, valid_alpha, valid_beta = tf.split(tmp_outputs_1, 4, axis=1)\n valid_rmse = edl.losses.RMSE(y_valid_input, valid_mu)\n\n ### Calculate loss for batch validation data\n valid_loss, (valid_nll_loss, valid_reg_loss) = self.loss_function(y_valid_input, valid_mu, valid_v, valid_alpha, valid_beta, return_comps=True)\n\n\n ### Calculate Epistemic, Aleatoric uncertainty for validation data directly and plot\n ''' epistemic (Var[mu]) = beta/ (v(alpha - 1)) '''\n epistemic_valid = np.sqrt(valid_beta / (valid_v * (valid_alpha - 1)))\n aleatoric_sigma_valid = np.sqrt((epistemic_valid ** 2) * valid_v)\n epistemic_valid = np.minimum(epistemic_valid, 1e3) # clip the unc for vis\n aleatoric_sigma_valid = np.minimum(aleatoric_sigma_valid, 1e3) # clip the unc for vis\n test_bounds = [[-7, +7]]\n\n ### x_train, y_train: np_arr (size, 1)\n ### x_valid, y_valid: np_arr (size, 1)\n ### valid_mu: tf tensor (size, 1)\n ### epistemic_valid: np_arr (size, 1)\n valid_mu_np = valid_mu.numpy()\n self.plot_scatter_with_var_from_pandas_v2(self.iter, x_train, y_train, x_valid, y_valid, valid_mu_np, epistemic_valid,\n path=self.custom_plot_folder+\"/valid_epistemic\"+\"/valid_plot_iter_{}\".format(self.iter)+\".png\",\n n_stds=3, test_bounds=test_bounds, evalType='valid', uq='epistemic', show=False, save=True)\n self.plot_scatter_with_var_from_pandas_v2(self.iter, x_train, y_train, x_valid, y_valid, valid_mu_np, aleatoric_sigma_valid,\n path=self.custom_plot_folder+\"/valid_aleatoric\"+\"/valid_plot_iter_{}\".format(self.iter)+\".png\",\n n_stds=3, test_bounds=test_bounds, evalType='valid', uq='aleatoric', show=False, save=True)\n\n # # print(valid_reg_loss)\n if valid_eval_count == 0:\n tmp_valid_loss = valid_loss\n else:\n if valid_loss < tmp_valid_loss:\n tmp_valid_loss = valid_loss\n print(\"[{}] Valid loss: {:.6f} \\t RMSE: {:.4f} \\t NLL: {:.4f} \\t reg_loss: {:.4f} \\t lambda: {:.2f}\".\n format(self.iter, valid_loss, valid_rmse.numpy(), valid_nll_loss.numpy(), valid_reg_loss.numpy(), self.lam.numpy()))\n ### update the DataFrame\n valid_results_df = pd.DataFrame({\n 'valid_x': list(x_valid.flatten()),\n 'valid_y': list(y_valid.flatten()),\n 'valid_mu': list(valid_mu.numpy().flatten()),\n 'valid_v': list(valid_v.numpy().flatten()),\n 'valid_alpha': list(valid_alpha.numpy().flatten()),\n 'valid_beta': list(valid_beta.numpy().flatten()),\n })\n valid_best_iter_str = str(self.iter)\n valid_eval_count += 1\n ''' Siyan Test END --- (for all validation data)'''\n\n ''' Siyan Test START --- (for entire testing data)'''\n tmp_outputs_2 = self.model(x_test_input, training=False)\n test_mu, test_v, test_alpha, test_beta = tf.split(tmp_outputs_2, 4, axis=1)\n test_rmse = edl.losses.RMSE(y_test_input, test_mu)\n\n test_loss, (test_nll_loss, test_reg_loss) = self.loss_function(y_test_input, test_mu, test_v,\n test_alpha, test_beta,\n return_comps=True)\n\n ### Calculate Epistemic, Aleatoric uncertainty for test data directly and plot\n ''' epistemic (Var[mu]) = beta/ (v(alpha - 1)) '''\n epistemic_test = np.sqrt(test_beta / (test_v * (test_alpha - 1)))\n aleatoric_sigma_test = np.sqrt((epistemic_test ** 2) * test_v)\n epistemic_test = np.minimum(epistemic_test, 1e3) # clip the unc for vis\n aleatoric_sigma_test = np.minimum(aleatoric_sigma_test, 1e3) # clip the unc for vis\n test_bounds = [[-7, +7]]\n\n test_mu_np = test_mu.numpy()\n self.plot_scatter_with_var_from_pandas_v2(self.iter, x_train, y_train, x_test, y_test, test_mu_np, epistemic_test,\n path=self.custom_plot_folder+\"/test_epistemic\"+\"/test_plot_iter_{}\".format(self.iter)+\".png\",\n n_stds=3, test_bounds=test_bounds, evalType='test', uq='epistemic', show=False, save=True)\n self.plot_scatter_with_var_from_pandas_v2(self.iter, x_train, y_train, x_test, y_test, test_mu_np, aleatoric_sigma_test,\n path=self.custom_plot_folder+\"/test_aleatoric\"+\"/test_plot_iter_{}\".format(self.iter)+\".png\",\n n_stds=3, test_bounds=test_bounds, evalType='test', uq='aleatoric', show=False, save=True)\n\n # print(\"[{}] Valid loss: {:.6f} \\t RMSE: {:.4f} \\t NLL: {:.4f} \\t reg_loss: {:.4f} \\t lambda: {:.2f}\".\n # format(self.iter, valid_loss, valid_rmse.numpy(), valid_nll_loss.numpy(), valid_reg_loss.numpy(),\n # self.lam.numpy()))\n\n # test_mu_np = test_mu.numpy()\n # self.plot_scatter_with_var_from_pandas_v2(self.iter, x_train, y_train, x_test, y_test, test_mu_np, epistemic_test,\n # path=self.custom_plot_folder+\"/test_plot_iter_{}\".format(self.iter)+\".png\",\n # n_stds=3, test_bounds=test_bounds, evalType='test', uq='epistemic', show=False, save=True)\n\n if test_eval_count == 0:\n tmp_test_loss = test_loss\n # tmp_valid_rmse = valid_rmse\n else:\n if test_loss < tmp_test_loss:\n # if valid_rmse < tmp_valid_rmse:\n tmp_test_loss = test_loss\n # tmp_valid_rmse = valid_rmse\n print(\"[{}] Test loss: {:.6f} \\t RMSE: {:.4f} \\t NLL: {:.4f} \\t reg_loss: {:.4f} \\t lambda: {:.2f}\".\n format(self.iter, test_loss, test_rmse.numpy(), test_nll_loss.numpy(), test_reg_loss.numpy(), self.lam.numpy()))\n ### update the DataFrame\n test_results_df = pd.DataFrame({\n 'test_x': list(x_test.flatten()),\n 'test_y': list(y_test.flatten()),\n 'test_mu': list(test_mu.numpy().flatten()),\n 'test_v': list(test_v.numpy().flatten()),\n 'test_alpha': list(test_alpha.numpy().flatten()),\n 'test_beta': list(test_beta.numpy().flatten()),\n })\n test_best_iter_str = str(self.iter)\n test_eval_count += 1\n\n ''' Siyan Test END --- (for entire test data)'''\n\n valid_results_df.to_csv(self.custom_best_results_dat_folder + \"/best_valid_results_iter_\"+valid_best_iter_str+\".dat\", sep=\" \")\n print('--- Saved validation results to '+self.custom_best_results_dat_folder +'/best_valid_results_iter_'+valid_best_iter_str+\".dat\")\n test_results_df.to_csv(self.custom_best_results_dat_folder + \"/best_test_results_iter_\"+test_best_iter_str+\".dat\", sep=\" \")\n print('--- Saved testing results to '+self.custom_best_results_dat_folder+'/best_test_results_iter_'+test_best_iter_str+\".dat\")\n\n\n ''' Validation/test results calculation and plotting:\n (1) Best validation results; (2) Best testing results. And compare to the original results\n '''\n load_valid_df = pd.read_csv(self.custom_best_results_dat_folder + \"/best_valid_results_iter_\"+valid_best_iter_str+\".dat\", sep=\" \")\n load_test_df = pd.read_csv(self.custom_best_results_dat_folder + \"/best_test_results_iter_\"+test_best_iter_str+\".dat\", sep=\" \")\n\n ''' epistemic (Var[mu]) = beta/ (v(alpha - 1)) '''\n epistemic_valid = np.sqrt(load_valid_df['valid_beta'].values / (load_valid_df['valid_v'].values * (load_valid_df['valid_alpha'].values - 1)))\n epistemic_valid = np.minimum(epistemic_valid, 1e3) # clip the unc for vis\n\n epistemic_test = np.sqrt(load_test_df['test_beta'].values / (load_test_df['test_v'].values * (load_test_df['test_alpha'].values - 1)))\n epistemic_test = np.minimum(epistemic_test, 1e3) # clip the unc for vis\n\n ''' aleatoric (E[sigma^2]) = beta / (alpha - 1)'''\n # aleatoric_valid_sigma = np.sqrt()\n\n # print(load_test_df)\n\n # valid_bounds = [[-4, +4]]\n test_bounds = [[-7, +7]]\n\n # print(x_train.shape)\n # print(y_train.shape)\n # print(x_valid.shape)\n # print(y_valid.shape)\n # print(load_valid_df['valid_mu'].values.shape)\n # print(epistemic_valid.shape)\n\n\n # self.plot_scatter_with_var_from_pandas_v2(x_train, y_train, x_valid, y_valid,\n # load_valid_df['valid_mu'].values, epistemic_valid, path=self.custom_plot_folder+\"/valid_plot.pdf\", n_stds=3, test_bounds=test_bounds, show=True)\n\n #\n # self.plot_scatter_with_var_from_pandas_v2(x_train, y_train, x_test, y_test,\n # load_test_df['test_mu'].values, epistemic_test, path=self.custom_plot_folder+\"/test_plot.pdf\", n_stds=3, test_bounds=test_bounds, show=True)\n\n return self.model, self.min_rmse, self.min_nll\n",
"import numpy as np\nimport tensorflow as tf\nimport tensorflow_probability as tfp\nimport time\nimport datetime\nimport os\nimport sys\nimport h5py\nfrom pathlib import Path\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nimport evidential_deep_learning as edl\nfrom .util import normalize, gallery\n\nclass BBBP:\n def __init__(self, model, opts, dataset=\"\", learning_rate=1e-3, tag=\"\", custom_plot_folder=\"\", custom_best_results_dat_folder=\"\"):\n self.loss_function = edl.losses.MSE\n\n self.model = model\n\n self.optimizer = tf.optimizers.Adam(learning_rate)\n\n self.min_rmse = float('inf')\n self.min_nll = float('inf')\n self.min_vloss = float('inf')\n\n trainer = self.__class__.__name__\n current_time = datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\")\n self.save_dir = os.path.join('save','{}_{}_{}_{}'.format(current_time, dataset, trainer, tag))\n Path(self.save_dir).mkdir(parents=True, exist_ok=True)\n\n self.custom_plot_folder = custom_plot_folder\n Path(self.custom_plot_folder).mkdir(parents=True, exist_ok=True)\n\n self.custom_best_results_dat_folder = custom_best_results_dat_folder\n Path(self.custom_best_results_dat_folder).mkdir(parents=True, exist_ok=True)\n\n\n train_log_dir = os.path.join('logs', '{}_{}_{}_{}_train'.format(current_time, dataset, trainer, tag))\n self.train_summary_writer = tf.summary.create_file_writer(train_log_dir)\n val_log_dir = os.path.join('logs', '{}_{}_{}_{}_val'.format(current_time, dataset, trainer, tag))\n self.val_summary_writer = tf.summary.create_file_writer(val_log_dir)\n\n @tf.function\n def run_train_step(self, x, y):\n with tf.GradientTape() as tape:\n y_hat = self.model(x, training=True) #forward pass\n loss = self.loss_function(y, y_hat)\n loss += tf.reduce_mean(self.model.losses)\n\n grads = tape.gradient(loss, self.model.variables) #compute gradient\n self.optimizer.apply_gradients(zip(grads, self.model.variables))\n return loss, y_hat\n\n @tf.function\n def evaluate(self, x, y):\n preds = tf.stack([self.model(x, training=True) for _ in range(5)], axis=0) #forward pass\n mu, var = tf.nn.moments(preds, axes=0)\n rmse = edl.losses.RMSE(y, mu)\n nll = edl.losses.Gaussian_NLL(y, mu, tf.sqrt(var))\n loss = self.loss_function(y, mu)\n\n return mu, var, loss, rmse, nll\n\n @tf.function\n def siyan_bbbp_evaluate(self, x_input):\n preds = tf.stack([self.model(x_input, training=True) for _ in range(15)], axis=0) # forward pass\n mean_mu = tf.reduce_mean(preds, axis=0)\n epistemic = tf.math.reduce_std(preds, axis=0)\n return mean_mu, epistemic\n\n def save_train_summary(self, loss, x, y, y_hat):\n with self.train_summary_writer.as_default():\n # tf.summary.scalar('loss', tf.reduce_mean(loss), step=self.iter)\n tf.summary.scalar('mse', tf.reduce_mean(edl.losses.MSE(y, y_hat)), step=self.iter)\n idx = np.random.choice(int(tf.shape(x)[0]), 9)\n if tf.shape(x).shape==4:\n tf.summary.image(\"x\", [gallery(tf.gather(x,idx).numpy())], max_outputs=1, step=self.iter)\n\n if tf.shape(y).shape==4:\n tf.summary.image(\"y\", [gallery(tf.gather(y,idx).numpy())], max_outputs=1, step=self.iter)\n tf.summary.image(\"y_hat\", [gallery(tf.gather(y_hat,idx).numpy())], max_outputs=1, step=self.iter)\n\n def save_val_summary(self, loss, x, y, mu, var):\n with self.val_summary_writer.as_default():\n tf.summary.scalar('loss', tf.reduce_mean(self.loss_function(y, mu)), step=self.iter)\n tf.summary.scalar('mse', tf.reduce_mean(edl.losses.MSE(y, mu)), step=self.iter)\n idx = np.random.choice(int(tf.shape(x)[0]), 9)\n if tf.shape(x).shape==4:\n tf.summary.image(\"x\", [gallery(tf.gather(x,idx).numpy())], max_outputs=1, step=self.iter)\n\n if tf.shape(y).shape==4:\n tf.summary.image(\"y\", [gallery(tf.gather(y,idx).numpy())], max_outputs=1, step=self.iter)\n tf.summary.image(\"y_hat\", [gallery(tf.gather(mu,idx).numpy())], max_outputs=1, step=self.iter)\n tf.summary.image(\"y_var\", [gallery(normalize(tf.gather(var,idx)).numpy())], max_outputs=1, step=self.iter)\n\n def get_batch(self, x, y, batch_size):\n idx = np.random.choice(x.shape[0], batch_size, replace=False)\n if isinstance(x, tf.Tensor):\n x_ = x[idx,...]\n y_ = y[idx,...]\n elif isinstance(x, np.ndarray) or isinstance(x, h5py.Dataset):\n idx = np.sort(idx)\n x_ = x[idx,...]\n y_ = y[idx,...]\n\n x_divisor = 255. if x_.dtype == np.uint8 else 1.0\n y_divisor = 255. if y_.dtype == np.uint8 else 1.0\n\n x_ = tf.convert_to_tensor(x_/x_divisor, tf.float32)\n y_ = tf.convert_to_tensor(y_/y_divisor, tf.float32)\n else:\n print(\"unknown dataset type {} {}\".format(type(x), type(y)))\n return x_, y_\n\n def save(self, name):\n self.model.save(os.path.join(self.save_dir, \"{}.h5\".format(name)))\n # pass\n\n ''' Siyan added for testing plot '''\n def plot_scatter_with_var_from_pandas(self, x_train, y_train, x_test, y_test, mu, var, path, n_stds=3, test_bounds=[[-7, +7]], show=True):\n plt.scatter(x_train, y_train, s=1., c='#463c3c', zorder=0, label='Train (x_train vs y_train)')\n for k in np.linspace(0, n_stds, 4):\n if k == 0:\n plt.fill_between(x_test[:, 0], (mu - k * var), (mu + k * var), alpha=0.3, edgecolor=None,\n facecolor='#00aeef', linewidth=0, antialiased=True, zorder=1, label='Unc.')\n else:\n plt.fill_between(x_test[:, 0], (mu - k * var), (mu + k * var), alpha=0.3, edgecolor=None,\n facecolor='#00aeef', linewidth=0, antialiased=True, zorder=1)\n\n plt.plot(x_test, y_test, 'r--', zorder=2, label='True (x_test vs y_test)')\n plt.plot(x_test, mu, color='#007cab', zorder=3, label='Pred (x_test vs mu)')\n plt.gca().set_xlim(*test_bounds)\n plt.gca().set_ylim(-150, 150)\n plt.title(path)\n plt.legend()\n plt.savefig(path, transparent=True)\n if show:\n plt.show()\n plt.clf()\n\n def train(self, x_train, y_train, x_test, y_test, x_valid, y_valid, y_scale, batch_size=128, iters=10000, verbose=True):\n ''' Siyan added START '''\n # np.random.seed(1234)\n test_eval_count = 0\n valid_eval_count = 0\n test_best_iter_str = '0'\n valid_best_iter_str = '0'\n\n x_valid_input = tf.convert_to_tensor(x_valid, tf.float32)\n y_valid_input = tf.convert_to_tensor(y_valid, tf.float32)\n\n tic = time.time()\n for self.iter in range(iters):\n x_input_batch, y_input_batch = self.get_batch(x_train, y_train, batch_size)\n loss, y_hat = self.run_train_step(x_input_batch, y_input_batch)\n\n if self.iter % 10 == 0:\n self.save_train_summary(loss, x_input_batch, y_input_batch, y_hat)\n\n if self.iter % 100 == 0:\n x_test_batch, y_test_batch = self.get_batch(x_test, y_test, min(100, x_test.shape[0]))\n mu, var, vloss, rmse, nll = self.evaluate(x_test_batch, y_test_batch)\n nll += np.log(y_scale[0,0])\n rmse *= y_scale[0,0]\n\n self.save_val_summary(vloss, x_test_batch, y_test_batch, mu, var)\n\n if rmse.numpy() < self.min_rmse:\n self.min_rmse = rmse.numpy()\n print(\"SAVING\")\n self.save(\"model_rmse\")\n\n if nll.numpy() < self.min_nll:\n self.min_nll = nll.numpy()\n self.save(\"model_nll\")\n\n if vloss.numpy() < self.min_vloss:\n self.min_vloss = vloss.numpy()\n self.save(\"model_vloss\")\n\n # if verbose: print(\"[{}] \\t RMSE: {:.4f} \\t NLL: {:.4f} \\t train_loss: {:.4f} \\t t: {:.2f} sec\".format(self.iter, self.min_rmse, self.min_nll, vloss, time.time()-tic))\n # tic = time.time()\n\n ''' Siyan Test START --- (for entire test data instead of batch of test data)'''\n if self.iter % 10 == 0:\n x_test_input = tf.convert_to_tensor(x_test, tf.float32)\n y_test_input = tf.convert_to_tensor(y_test, tf.float32)\n test_mu, test_var, test_vloss, test_rmse, test_nll = self.evaluate(x_test_input, y_test_input)\n if test_eval_count == 0:\n tmp_test_loss = test_vloss\n else:\n if test_vloss < tmp_test_loss:\n tmp_test_loss = test_vloss\n print(\"[{}] Test loss: {:.6f} \\t RMSE: {:.4f} \\t NLL: {:.4f} \".\n format(self.iter, test_vloss, test_rmse.numpy(), test_nll.numpy()))\n\n test_mean_mu, test_epistemic = self.siyan_bbbp_evaluate(x_test_input)\n ### update the DataFrame\n test_results_df = pd.DataFrame({\n 'test_x': list(x_test.flatten()),\n 'test_y': list(y_test.flatten()),\n 'test_mean_mu': list(test_mean_mu.numpy().flatten()),\n 'test_epistemic': list(test_epistemic.numpy().flatten())\n # 'test_mu': list(test_mu.numpy().flatten()),\n # 'test_var': list(test_var.numpy().flatten())\n })\n test_best_iter_str = str(self.iter)\n test_eval_count += 1\n ''' Siyan Test END --- (for entire test data instead of batch of test data)'''\n\n ''' Siyan Test START --- (for entire validation data instead of batch of validation data)'''\n valid_mu, valid_var, valid_vloss, valid_rmse, valid_nll = self.evaluate(x_valid_input, y_valid_input)\n if valid_eval_count == 0:\n tmp_valid_loss = valid_vloss\n else:\n if valid_vloss < tmp_valid_loss:\n tmp_valid_loss = valid_vloss\n print(\"[{}] Validation loss: {:.6f} \\t RMSE: {:.4f} \\t NLL: {:.4f} \".\n format(self.iter, valid_vloss, valid_rmse.numpy(), valid_nll.numpy()))\n\n valid_mean_mu, valid_epistemic = self.siyan_bbbp_evaluate(x_valid_input)\n ### update the DataFrame\n valid_results_df = pd.DataFrame({\n 'valid_x': list(x_valid.flatten()),\n 'valid_y': list(y_valid.flatten()),\n 'valid_mean_mu': list(valid_mean_mu.numpy().flatten()),\n 'valid_epistemic': list(valid_epistemic.numpy().flatten())\n # 'valid_mean_var': list(valid_mean_var.numpy().flatten()),\n # 'valid_reduce_std_mu': list(valid_reduce_std_mu.numpy().flatten()),\n # 'valid_reduce_mean_var': list(valid_reduce_mean_var.numpy().flatten())\n })\n valid_best_iter_str = str(self.iter)\n\n valid_eval_count += 1\n ''' Siyan Test END --- (for entire validation data instead of batch of validation data)'''\n\n test_results_df.to_csv(self.custom_best_results_dat_folder + \"/best_test_results_iter_\"+test_best_iter_str+\".dat\", sep=\" \")\n print('--- Saved testing results to '+self.custom_best_results_dat_folder+'/best_test_results_iter_'+test_best_iter_str+\".dat\")\n valid_results_df.to_csv(self.custom_best_results_dat_folder + \"/best_valid_results_iter_\"+valid_best_iter_str+\".dat\", sep=\" \")\n print('--- Saved validation results to '+self.custom_best_results_dat_folder +'/best_valid_results_iter_'+valid_best_iter_str+\".dat\")\n\n ''' Test/validation results calculation and plotting:\n (1) Best train results; (2) Best validation results. And compare to the original results\n '''\n load_test_df = pd.read_csv(self.custom_best_results_dat_folder + \"/best_test_results_iter_\"+test_best_iter_str+\".dat\", sep=\" \")\n load_valid_df = pd.read_csv(self.custom_best_results_dat_folder + \"/best_valid_results_iter_\"+valid_best_iter_str+\".dat\", sep=\" \")\n\n valid_bounds = [[-7, +7]]\n self.plot_scatter_with_var_from_pandas(x_train, y_train, x_valid, y_valid,\n load_test_df['test_mean_mu'].values, load_test_df['test_epistemic'].values, path=self.custom_plot_folder+\"/test_plot.pdf\", n_stds=3, test_bounds=valid_bounds, show=True)\n self.plot_scatter_with_var_from_pandas(x_train, y_train, x_valid, y_valid,\n load_valid_df['valid_mean_mu'].values, load_valid_df['valid_epistemic'], path=self.custom_plot_folder+\"/valid_plot.pdf\", n_stds=3, test_bounds=valid_bounds, show=True)\n\n\n\n return self.model, self.min_rmse, self.min_nll\n",
"# -*- coding: utf-8 -*-\n\"\"\"\nRun method, and save results.\nRun as:\n python main.py --dataset <ds> --method <met>\n where dataset name should be in UCI_Datasets folder\n and method is piven, qd, deep-ens, mid or only-rmse.\n\"\"\"\nimport argparse\nimport json\nimport datetime\nimport tensorflow as tf\n# import tensorflow.compat.v1 as tf\nimport scipy.stats as stats\nimport itertools\nimport os\nimport random\nimport numpy as np\n\n\nimport data_loader\nfrom DataGen import DataGenerator\nfrom DeepNetPI import TfNetwork\nfrom utils import *\nfrom sklearn.model_selection import train_test_split\n\n\nstart_time = datetime.datetime.now()\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--dataset', type=str, default='flight_delay', metavar='',\n help='dataset name, flight_delay')\nparser.add_argument('--method', type=str, help='piven, qd, mid, only-rmse, deep-ens', required=True)\nargs = parser.parse_args()\nmethod = args.method\n\n############# added code start ############# \nprint(args)\nprint(args.dataset)\noriginal_data_path = '../flight_delay_data/' ## flight delay data\nresults_path = './Results/piven/'+args.dataset + '_PIVEN_UCI.txt'\n\n\nseed = 12345\nneurons = [100]\nlambda_in = 15.0\nsigma_in = 0.2\n\nrandom.seed(seed)\nnp.random.seed(seed)\ntf.compat.v1.random.set_random_seed(seed)\n# tf.random.set_random_seed(seed)\nh_size = neurons\n\n\n# n_runs = params['n_runs'] # number of runs\nn_runs = 1\nn_epoch = 500 # number epochs to train for\n# h_size = params['h_size'] # number of hidden units in network: [50]=layer_1 of 50, [8,4]=layer_1 of 8, layer_2 of 4\nl_rate = 0.01 # learning rate of optimizer\ndecay_rate = 0.99 # learning rate decay\nsoften = 160.0 # soften param in the loss\npatience = -1 # patience\nn_ensemble = 1 # number of individual NNs in ensemble # 5\nalpha = 0.05 # data points captured = (1 - alpha)\ntrain_prop = 0.9 # % of data to use as training\nin_ddof = 1 if n_runs > 1 else 0 # this is for results over runs only\nis_early_stop = patience != -1\n\nif args.dataset == 'YearPredictionMSD':\n n_batch = 1000 # batch size\n out_biases = [5., -5.]\nelse:\n n_batch = 100 # batch size\n out_biases = [2., -2.] # chose biases for output layer (for deep_ens is overwritten to 0,1)\n\n\nresults_runs = []\nrun = 0\nfail_times = 0\nfor run in range(0, n_runs):\n\n\n ''' ######### flight delay data loading ###############'''\n xTrain, yTrain, test_data_list = data_loader.load_flight_delays(original_data_path)\n\n # y_train = np.reshape(y_train, (-1, 1))\n # y_test = np.reshape(y_test, (-1, 1))\n\n '''choose the train/test dataset '''\n x_train = xTrain\n y_train = yTrain\n y_train = y_train.reshape(-1, 1)\n # y_scale = yTrain_scale\n test_idx = 0 # [0, 1, 2, 3] for test 1,2,3,4\n X_test = test_data_list[test_idx][0]\n y_test = test_data_list[test_idx][1]\n y_test = y_test.reshape(-1, 1)\n\n\n X_val = X_test\n y_val = y_test.reshape(-1, 1)\n\n\n y_pred_all = []\n y_pred_all_train = []\n\n i = 0\n while i < n_ensemble:\n is_failed_run = False\n\n tf.reset_default_graph()\n sess = tf.Session()\n\n print(f'\\nrun number {run+1} of {n_runs} -- ensemble number {i+1} of {n_ensemble}')\n\n # create network\n NN = TfNetwork(x_size=x_train.shape[1],\n y_size=2,\n h_size=h_size,\n alpha=alpha,\n soften=soften,\n lambda_in=lambda_in,\n sigma_in=sigma_in,\n out_biases=out_biases,\n method=method,\n patience=patience,\n dataset=args.dataset,\n rnd_seed=seed)\n\n # train\n NN.train(sess, x_train, y_train, X_val, y_val,\n n_epoch=n_epoch,\n l_rate=l_rate,\n decay_rate=decay_rate,\n is_early_stop=is_early_stop,\n n_batch=n_batch)\n\n # predict\n y_loss, y_pred = NN.predict(sess, X_test=X_test, y_test=y_test)\n\n # prediction for training data\n y_loss_train, y_pred_train = NN.predict(sess, X_test=x_train, y_test=y_train)\n\n # check whether the run failed or not\n if np.abs(y_loss) > 20. and fail_times < 1: # jump out of some endless failures\n # if False:\n is_failed_run = True\n fail_times+=1\n print('\\n\\n### one messed up! repeating ensemble ### failed {}/5 times!'.format(fail_times))\n continue # without saving result\n else:\n i += 1 # continue to next\n\n # save prediction\n y_pred_all.append(y_pred)\n y_pred_all_train.append(y_pred_train)\n sess.close()\n\n y_pred_all = np.array(y_pred_all)\n y_pred_all_train = np.array(y_pred_all_train)\n\n if method == 'deep-ens':\n y_pred_gauss_mid_all = y_pred_all[:, :, 0]\n # occasionally may get -ves for std dev so need to do max\n y_pred_gauss_dev_all = np.sqrt(np.maximum(np.log(1. + np.exp(y_pred_all[:, :, 1])), 10e-6))\n y_pred_gauss_mid, y_pred_gauss_dev, y_pred_U, \\\n y_pred_L = gauss_to_pi(y_pred_gauss_mid_all, y_pred_gauss_dev_all)\n\n else:\n ### for test data\n y_pred_gauss_mid, y_pred_gauss_dev, y_pred_U, y_pred_L, y_pred_v = pi_to_gauss(y_pred_all, method=method)\n ### for training data\n y_pred_gauss_mid_train, y_pred_gauss_dev_train, y_pred_U_train, y_pred_L_train, y_pred_v_train = pi_to_gauss(y_pred_all_train, method=method)\n \n\n ### calculate the confidence scores \n # for train\n y_U_cap_train = y_pred_U_train > y_train.reshape(-1)\n y_L_cap_train = y_pred_L_train < y_train.reshape(-1)\n MPIW_array_train = y_pred_U_train - y_pred_L_train \n MPIW_train = np.mean(MPIW_array_train)\n\n MPIW_array_test = y_pred_U - y_pred_L\n\n confidence_arr_test = [min(MPIW_train/test_width, 1.0) for test_width in MPIW_array_test]\n confidence_arr_train = [min(MPIW_train/train_width, 1.0) for train_width in MPIW_array_train]\n\n print('----------- OOD analysis --- confidence scores ----------------')\n print('--- Train conf_scores MEAN: {}, STD: {}'.format(np.mean(confidence_arr_train), np.std(confidence_arr_train)))\n print('--- Test: {} rank: {} conf_scores MEAN: {}, STD: {}'.format(test_idx+1, test_idx+1, np.mean(confidence_arr_test), np.std(confidence_arr_test)))\n\n dist_arr_train = np.sqrt(np.sum(x_train ** 2.0, axis=1))\n dist_arr_test = np.sqrt(np.sum(X_val ** 2.0, axis=1))\n\n confidence_arr_train = np.array(confidence_arr_train)\n confidence_arr_test = np.array(confidence_arr_test)\n\n PIVEN_OOD_train_np = np.hstack((dist_arr_train.reshape(-1, 1), confidence_arr_train.reshape(-1, 1)))\n PIVEN_OOD_test_np = np.hstack((dist_arr_test.reshape(-1, 1), confidence_arr_test.reshape(-1, 1)))\n\n np.savetxt('PIVEN_OOD_flight_delay_'+ str(test_idx+1) +'_train_np.txt', PIVEN_OOD_train_np, delimiter=',')\n np.savetxt('PIVEN_OOD_flight_delay_'+ str(test_idx+1) +'_test_np.txt', PIVEN_OOD_test_np, delimiter=',')\n\n # # work out metrics\n # y_U_cap = y_pred_U > y_test.reshape(-1)\n # y_L_cap = y_pred_L < y_test.reshape(-1)\n\n # y_all_cap = y_U_cap * y_L_cap\n # PICP = np.sum(y_all_cap) / y_L_cap.shape[0]\n # MPIW = np.mean(y_pred_U - y_pred_L)\n # y_pred_mid = np.mean((y_pred_U, y_pred_L), axis=0)\n # # MSE = np.mean(np.square(Gen.scale_c * (y_pred_mid - y_test[:, 0])))\n # # RMSE = np.sqrt(MSE)\n\n # if method == 'qd' or method == 'deep-ens':\n # RMSE_ELI = 0.0 # RMSE_PIVEN\n # else:\n # if method == 'piven':\n # y_piven = y_pred_v * y_pred_U + (1 - y_pred_v) * y_pred_L\n\n # elif method == 'mid':\n # y_piven = 0.5 * y_pred_U + 0.5 * y_pred_L\n\n # elif method == 'only-rmse':\n # y_piven = y_pred_v\n\n # MSE_ELI = np.mean(np.square(Gen.scale_c * (y_piven - y_test[:, 0])))\n # RMSE_ELI = np.sqrt(MSE_ELI) # RMSE_PIVEN\n\n # CWC = np_QD_loss(y_test, y_pred_L, y_pred_U, alpha, lambda_in) # from qd paper.\n # neg_log_like = gauss_neg_log_like(y_test, y_pred_gauss_mid, y_pred_gauss_dev, Gen.scale_c)\n # residuals = y_pred_mid - y_test[:, 0]\n # shapiro_W, shapiro_p = stats.shapiro(residuals[:])\n # results_runs.append((PICP, MPIW, CWC, RMSE, RMSE_ELI, neg_log_like, shapiro_W, shapiro_p))\n\n# # summarize results\n# results_path = f\"./Results/{method}/\"\n# results_path += f\"{params['dataset']}-{start_time.strftime('%d-%m-%H-%M')}-{method}.csv\"\n\n# results = np.array(results_runs)\n# results_to_csv(results_path, results, params, n_runs, n_ensemble, in_ddof)\n\n# timing info\nend_time = datetime.datetime.now()\ntotal_time = end_time - start_time\nprint('\\n\\nminutes taken:', round(total_time.total_seconds() / 60, 3),\n '\\nstart_time:', start_time.strftime('%H:%M:%S'),\n 'end_time:', end_time.strftime('%H:%M:%S'))\n"
] | [
[
"tensorflow.convert_to_tensor",
"matplotlib.pyplot.legend",
"numpy.minimum",
"numpy.sqrt",
"numpy.linspace",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.gca",
"pandas.read_csv",
"tensorflow.Variable",
"tensorflow.gather",
"numpy.log",
"matplotlib.pyplot.title",
"numpy.random.choice",
"tensorflow.shape",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.fill_between",
"tensorflow.optimizers.Adam",
"tensorflow.split",
"matplotlib.pyplot.show",
"tensorflow.GradientTape",
"tensorflow.reduce_max",
"matplotlib.pyplot.scatter",
"numpy.sort",
"tensorflow.reduce_min",
"matplotlib.pyplot.clf",
"tensorflow.summary.create_file_writer"
],
[
"tensorflow.convert_to_tensor",
"matplotlib.pyplot.legend",
"numpy.linspace",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.gca",
"pandas.read_csv",
"tensorflow.nn.moments",
"tensorflow.gather",
"numpy.log",
"matplotlib.pyplot.title",
"numpy.random.choice",
"tensorflow.shape",
"matplotlib.pyplot.savefig",
"tensorflow.math.reduce_std",
"matplotlib.pyplot.fill_between",
"tensorflow.optimizers.Adam",
"matplotlib.pyplot.show",
"tensorflow.GradientTape",
"matplotlib.pyplot.scatter",
"tensorflow.reduce_mean",
"numpy.sort",
"matplotlib.pyplot.clf",
"tensorflow.sqrt",
"tensorflow.summary.create_file_writer"
],
[
"numpy.abs",
"numpy.random.seed",
"tensorflow.compat.v1.random.set_random_seed",
"numpy.std",
"tensorflow.reset_default_graph",
"numpy.mean",
"tensorflow.Session",
"numpy.exp",
"numpy.array",
"numpy.sum"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"1.12",
"1.4",
"1.13",
"1.5",
"1.7",
"0.12",
"1.0",
"1.2"
]
}
] |
savindi-wijenayaka/transformer_old | [
"016960521eaaf5393c9fad1c4db15338455213f8"
] | [
"tests/test_modeling_prophetnet.py"
] | [
"# coding=utf-8\n# Copyright 2020 The HuggingFace Inc. team, The Microsoft Research team.\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\nimport copy\nimport tempfile\nimport unittest\n\nfrom transformers import is_torch_available\nfrom transformers.testing_utils import require_torch, slow, torch_device\n\nfrom .test_configuration_common import ConfigTester\nfrom .test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor\n\n\nif is_torch_available():\n import torch\n\n from transformers import (\n ProphetNetConfig,\n ProphetNetDecoder,\n ProphetNetEncoder,\n ProphetNetForCausalLM,\n ProphetNetForConditionalGeneration,\n ProphetNetModel,\n ProphetNetTokenizer,\n )\n\n\nclass ProphetNetModelTester:\n def __init__(\n self,\n parent,\n vocab_size=99,\n batch_size=13,\n hidden_size=16,\n encoder_seq_length=7,\n decoder_seq_length=9,\n # For common tests\n is_training=True,\n use_attention_mask=True,\n use_labels=True,\n decoder_start_token_id=0,\n encoder_ffn_dim=32,\n num_encoder_layers=4,\n num_encoder_attention_heads=4,\n decoder_ffn_dim=32,\n num_decoder_layers=4,\n num_decoder_attention_heads=4,\n max_position_embeddings=30,\n is_encoder_decoder=True,\n pad_token_id=0,\n bos_token_id=1,\n eos_token_id=2,\n ngram=2,\n num_buckets=32,\n relative_max_distance=128,\n disable_ngram_loss=False,\n scope=None,\n ):\n\n self.parent = parent\n self.batch_size = batch_size\n self.encoder_seq_length = encoder_seq_length\n self.decoder_seq_length = decoder_seq_length\n # For common tests\n self.seq_length = self.decoder_seq_length\n self.is_training = is_training\n self.use_attention_mask = use_attention_mask\n self.use_labels = use_labels\n\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_decoder_layers\n self.num_encoder_layers = num_encoder_layers\n self.num_decoder_layers = num_decoder_layers\n self.decoder_ffn_dim = decoder_ffn_dim\n self.encoder_ffn_dim = encoder_ffn_dim\n self.num_attention_heads = num_decoder_attention_heads\n self.num_encoder_attention_heads = num_encoder_attention_heads\n self.num_decoder_attention_heads = num_decoder_attention_heads\n self.eos_token_id = eos_token_id\n self.bos_token_id = bos_token_id\n self.pad_token_id = pad_token_id\n self.decoder_start_token_id = decoder_start_token_id\n self.ngram = ngram\n self.num_buckets = num_buckets\n self.relative_max_distance = relative_max_distance\n self.disable_ngram_loss = disable_ngram_loss\n self.max_position_embeddings = max_position_embeddings\n self.is_encoder_decoder = is_encoder_decoder\n\n self.scope = None\n self.decoder_key_length = decoder_seq_length\n self.base_model_out_len = 7\n self.num_hidden_states_types = 3 # encoder, decoder_main, decoder_ngram\n self.decoder_attention_idx = 2\n\n def prepare_config_and_inputs(self):\n input_ids = ids_tensor([self.batch_size, self.encoder_seq_length], self.vocab_size)\n decoder_input_ids = ids_tensor([self.batch_size, self.decoder_seq_length], self.vocab_size)\n\n attention_mask = None\n decoder_attention_mask = None\n if self.use_attention_mask:\n attention_mask = ids_tensor([self.batch_size, self.encoder_seq_length], vocab_size=2)\n decoder_attention_mask = ids_tensor([self.batch_size, self.decoder_seq_length], vocab_size=2)\n\n lm_labels = None\n if self.use_labels:\n lm_labels = ids_tensor([self.batch_size, self.decoder_seq_length], self.vocab_size)\n\n config = ProphetNetConfig(\n vocab_size=self.vocab_size,\n hidden_size=self.hidden_size,\n num_encoder_layers=self.num_encoder_layers,\n num_decoder_layers=self.num_decoder_layers,\n decoder_ffn_dim=self.decoder_ffn_dim,\n encoder_ffn_dim=self.encoder_ffn_dim,\n num_encoder_attention_heads=self.num_encoder_attention_heads,\n num_decoder_attention_heads=self.num_decoder_attention_heads,\n eos_token_id=self.eos_token_id,\n bos_token_id=self.bos_token_id,\n pad_token_id=self.pad_token_id,\n decoder_start_token_id=self.decoder_start_token_id,\n ngram=self.ngram,\n num_buckets=self.num_buckets,\n relative_max_distance=self.relative_max_distance,\n disable_ngram_loss=self.disable_ngram_loss,\n max_position_embeddings=self.max_position_embeddings,\n is_encoder_decoder=self.is_encoder_decoder,\n return_dict=True,\n )\n\n return (\n config,\n input_ids,\n decoder_input_ids,\n attention_mask,\n decoder_attention_mask,\n lm_labels,\n )\n\n def prepare_config_and_inputs_for_decoder(self):\n (\n config,\n input_ids,\n decoder_input_ids,\n attention_mask,\n decoder_attention_mask,\n lm_labels,\n ) = self.prepare_config_and_inputs()\n\n encoder_hidden_states = floats_tensor([self.batch_size, self.encoder_seq_length, self.hidden_size])\n encoder_attention_mask = ids_tensor([self.batch_size, self.encoder_seq_length], vocab_size=2)\n\n return (\n config,\n decoder_input_ids,\n decoder_attention_mask,\n encoder_hidden_states,\n encoder_attention_mask,\n lm_labels,\n )\n\n def check_prepare_lm_labels_via_shift_left(\n self,\n config,\n input_ids,\n decoder_input_ids,\n attention_mask,\n decoder_attention_mask,\n lm_labels,\n ):\n model = ProphetNetModel(config=config)\n model.to(torch_device)\n model.eval()\n\n # make sure that lm_labels are correctly padded from the right\n lm_labels.masked_fill_((lm_labels == self.decoder_start_token_id), self.eos_token_id)\n\n # add casaul pad token mask\n triangular_mask = torch.tril(lm_labels.new_ones(lm_labels.shape)).logical_not()\n lm_labels.masked_fill_(triangular_mask, self.pad_token_id)\n decoder_input_ids = model._shift_right(lm_labels)\n\n for i, (decoder_input_ids_slice, lm_labels_slice) in enumerate(zip(decoder_input_ids, lm_labels)):\n # first item\n self.parent.assertEqual(decoder_input_ids_slice[0].item(), self.decoder_start_token_id)\n if i < decoder_input_ids_slice.shape[-1]:\n if i < decoder_input_ids.shape[-1] - 1:\n # items before diagonal\n self.parent.assertListEqual(\n decoder_input_ids_slice[1 : i + 1].tolist(), lm_labels_slice[:i].tolist()\n )\n # pad items after diagonal\n if i < decoder_input_ids.shape[-1] - 2:\n self.parent.assertListEqual(\n decoder_input_ids_slice[i + 2 :].tolist(), lm_labels_slice[i + 1 : -1].tolist()\n )\n else:\n # all items after square\n self.parent.assertListEqual(decoder_input_ids_slice[1:].tolist(), lm_labels_slice[:-1].tolist())\n\n def create_and_check_model(\n self,\n config,\n input_ids,\n decoder_input_ids,\n attention_mask,\n decoder_attention_mask,\n lm_labels,\n ):\n model = ProphetNetModel(config=config)\n model.to(torch_device)\n model.eval()\n result = model(\n input_ids=input_ids,\n decoder_input_ids=decoder_input_ids,\n attention_mask=attention_mask,\n decoder_attention_mask=decoder_attention_mask,\n )\n result = model(input_ids=input_ids, decoder_input_ids=decoder_input_ids)\n decoder_output = result.last_hidden_state\n decoder_past = result.past_key_values\n encoder_output = result.encoder_last_hidden_state\n\n self.parent.assertEqual(encoder_output.size(), (self.batch_size, self.encoder_seq_length, self.hidden_size))\n self.parent.assertEqual(decoder_output.size(), (self.batch_size, self.decoder_seq_length, self.hidden_size))\n # There should be `num_layers` key value embeddings stored in decoder_past\n self.parent.assertEqual(len(decoder_past), config.num_decoder_layers)\n # There should be a self attn key, a self attn value, a cross attn key and a cross attn value stored in each decoder_past tuple\n self.parent.assertEqual(len(decoder_past[0]), 2) # cross-attention + uni-directional self-attention\n\n def create_and_check_with_lm_head(\n self,\n config,\n input_ids,\n decoder_input_ids,\n attention_mask,\n decoder_attention_mask,\n lm_labels,\n ):\n model = ProphetNetForConditionalGeneration(config=config).to(torch_device).eval()\n outputs = model(\n input_ids=input_ids,\n decoder_input_ids=decoder_input_ids,\n decoder_attention_mask=decoder_attention_mask,\n labels=lm_labels,\n )\n self.parent.assertEqual(len(outputs), 5)\n self.parent.assertEqual(outputs[\"logits\"].size(), (self.batch_size, self.decoder_seq_length, self.vocab_size))\n self.parent.assertEqual(outputs[\"loss\"].size(), ())\n\n def create_and_check_causal_lm_decoder(\n self,\n config,\n input_ids,\n decoder_input_ids,\n attention_mask,\n decoder_attention_mask,\n lm_labels,\n ):\n model = ProphetNetForCausalLM(config=config).to(torch_device).eval()\n outputs = model(\n input_ids=decoder_input_ids,\n attention_mask=decoder_attention_mask,\n labels=lm_labels,\n )\n self.parent.assertEqual(len(outputs), 4)\n self.parent.assertEqual(outputs[\"logits\"].size(), (self.batch_size, self.decoder_seq_length, self.vocab_size))\n self.parent.assertEqual(outputs[\"loss\"].size(), ())\n\n def create_and_check_generate_with_past_key_value_states(\n self,\n config,\n input_ids,\n decoder_input_ids,\n attention_mask,\n decoder_attention_mask,\n lm_labels,\n ):\n model = ProphetNetForConditionalGeneration(config=config).to(torch_device).eval()\n torch.manual_seed(0)\n output_without_past_cache = model.generate(\n input_ids[:1], num_beams=2, max_length=5, do_sample=True, use_cache=False\n )\n torch.manual_seed(0)\n output_with_past_cache = model.generate(input_ids[:1], num_beams=2, max_length=5, do_sample=True)\n self.parent.assertTrue(torch.all(output_with_past_cache == output_without_past_cache))\n\n def create_and_check_model_fp16_forward(\n self,\n config,\n input_ids,\n decoder_input_ids,\n attention_mask,\n decoder_attention_mask,\n lm_labels,\n ):\n model = ProphetNetModel(config=config).to(torch_device).half().eval()\n output = model(input_ids, decoder_input_ids=input_ids, attention_mask=attention_mask)[\"last_hidden_state\"]\n self.parent.assertFalse(torch.isnan(output).any().item())\n\n def create_and_check_encoder_decoder_shared_weights(\n self,\n config,\n input_ids,\n decoder_input_ids,\n attention_mask,\n decoder_attention_mask,\n lm_labels,\n ):\n for model_class in [ProphetNetModel, ProphetNetForConditionalGeneration]:\n torch.manual_seed(0)\n model = model_class(config=config).to(torch_device).eval()\n # load state dict copies weights but does not tie them\n\n if model_class == ProphetNetForConditionalGeneration:\n model.prophetnet.encoder.load_state_dict(model.prophetnet.decoder.state_dict(), strict=False)\n else:\n model.encoder.load_state_dict(model.decoder.state_dict(), strict=False)\n\n torch.manual_seed(0)\n tied_config = copy.deepcopy(config)\n tied_config.tie_encoder_decoder = True\n tied_model = model_class(config=tied_config).to(torch_device).eval()\n\n model_result = model(\n input_ids=input_ids,\n decoder_input_ids=decoder_input_ids,\n attention_mask=attention_mask,\n decoder_attention_mask=decoder_attention_mask,\n return_dict=True,\n )\n\n tied_model_result = tied_model(\n input_ids=input_ids,\n decoder_input_ids=decoder_input_ids,\n attention_mask=attention_mask,\n decoder_attention_mask=decoder_attention_mask,\n return_dict=True,\n )\n\n # check that models has less parameters\n self.parent.assertLess(\n sum(p.numel() for p in tied_model.parameters()), sum(p.numel() for p in model.parameters())\n )\n random_slice_idx = ids_tensor((1,), model_result[0].shape[-1]).item()\n\n # check that outputs are equal\n self.parent.assertTrue(\n torch.allclose(\n model_result[0][0, :, random_slice_idx], tied_model_result[0][0, :, random_slice_idx], atol=1e-4\n )\n )\n\n # check that outputs after saving and loading are equal\n with tempfile.TemporaryDirectory() as tmpdirname:\n tied_model.save_pretrained(tmpdirname)\n tied_model = model_class.from_pretrained(tmpdirname)\n tied_model.to(torch_device)\n tied_model.eval()\n\n # check that models has less parameters\n self.parent.assertLess(\n sum(p.numel() for p in tied_model.parameters()), sum(p.numel() for p in model.parameters())\n )\n random_slice_idx = ids_tensor((1,), model_result[0].shape[-1]).item()\n\n tied_model_result = tied_model(\n input_ids=input_ids,\n decoder_input_ids=decoder_input_ids,\n attention_mask=attention_mask,\n decoder_attention_mask=decoder_attention_mask,\n )\n\n # check that outputs are equal\n self.parent.assertTrue(\n torch.allclose(\n model_result[0][0, :, random_slice_idx],\n tied_model_result[0][0, :, random_slice_idx],\n atol=1e-4,\n )\n )\n\n def check_fast_integration(\n self,\n config,\n *args,\n ):\n input_ids = torch.tensor([[7, 4, 78, 0, 24, 52, 43]], device=torch_device, dtype=torch.long)\n decoder_input_ids = torch.tensor([[12, 62, 25, 11, 47, 15, 14]], device=torch_device, dtype=torch.long)\n attention_mask = torch.tensor([[1, 1, 1, 0, 1, 0, 0]], device=torch_device, dtype=torch.long)\n decoder_attention_mask = torch.tensor([[1, 1, 1, 0, 0, 1, 0]], device=torch_device, dtype=torch.long)\n lm_labels = torch.tensor([[62, 25, 11, 47, 15, 14, 24]], device=torch_device, dtype=torch.long)\n torch.manual_seed(0)\n config.ngram = 4\n model = ProphetNetForConditionalGeneration(config=config)\n model.to(torch_device)\n model.eval()\n with torch.no_grad():\n result = model(\n input_ids=input_ids,\n decoder_input_ids=decoder_input_ids,\n attention_mask=attention_mask,\n decoder_attention_mask=decoder_attention_mask,\n labels=lm_labels,\n return_dict=True,\n )\n self.parent.assertTrue(torch.allclose(result.loss, torch.tensor(128.2925, device=torch_device), atol=1e-3))\n\n expected_logit_slice = torch.tensor(\n [-0.1565, 0.0418, 0.1207, 0.0030, 0.0665, 0.0467, 0.0412], device=torch_device\n )\n self.parent.assertTrue(torch.allclose(result.logits[0, :, 1], expected_logit_slice, atol=1e-3))\n\n def check_model_with_attn_mask(self, config, input_ids, decoder_input_ids, *args):\n model = ProphetNetModel(config=config)\n model.to(torch_device)\n model.eval()\n\n outputs_no_mask = model(\n input_ids=input_ids[:, :5], decoder_input_ids=decoder_input_ids[:, :5], return_dict=True\n )\n attention_mask = torch.ones_like(input_ids)\n decoder_attention_mask = torch.ones_like(decoder_input_ids)\n\n attention_mask[:, 5:] = 0\n\n outputs_with_mask = model(\n input_ids=input_ids,\n attention_mask=attention_mask,\n decoder_input_ids=decoder_input_ids,\n decoder_attention_mask=decoder_attention_mask,\n return_dict=True,\n )\n\n # check encoder\n self.parent.assertTrue(\n torch.allclose(\n outputs_no_mask.encoder_last_hidden_state[0, :, 0],\n outputs_with_mask.encoder_last_hidden_state[0, :5, 0],\n atol=1e-3,\n )\n )\n\n # check decoder\n # main stream\n self.parent.assertTrue(\n torch.allclose(\n outputs_no_mask.last_hidden_state[0, :, 0], outputs_with_mask.last_hidden_state[0, :5, 0], atol=1e-3\n )\n )\n # predict stream\n self.parent.assertTrue(\n torch.allclose(\n outputs_no_mask.last_hidden_state_ngram[0, :5, 0],\n outputs_with_mask.last_hidden_state_ngram[0, :5, 0],\n atol=1e-3,\n )\n )\n\n def prepare_config_and_inputs_for_common(self):\n config_and_inputs = self.prepare_config_and_inputs()\n (\n config,\n input_ids,\n decoder_input_ids,\n attention_mask,\n decoder_attention_mask,\n lm_labels,\n ) = config_and_inputs\n\n inputs_dict = {\n \"input_ids\": input_ids,\n \"attention_mask\": attention_mask,\n \"decoder_input_ids\": decoder_input_ids,\n \"decoder_attention_mask\": decoder_attention_mask,\n \"use_cache\": False,\n }\n return config, inputs_dict\n\n\nclass ProphetNetStandaloneDecoderModelTester:\n def __init__(\n self,\n parent,\n vocab_size=99,\n batch_size=13,\n hidden_size=16,\n encoder_seq_length=7,\n decoder_seq_length=7,\n # For common tests\n is_training=True,\n is_decoder=True,\n use_attention_mask=True,\n add_cross_attention=False,\n use_cache=False,\n use_labels=True,\n decoder_start_token_id=0,\n encoder_ffn_dim=32,\n num_encoder_layers=4,\n num_encoder_attention_heads=4,\n decoder_ffn_dim=32,\n num_decoder_layers=4,\n num_decoder_attention_heads=4,\n max_position_embeddings=30,\n is_encoder_decoder=False,\n pad_token_id=0,\n bos_token_id=1,\n eos_token_id=2,\n ngram=2,\n return_dict=True,\n num_buckets=32,\n relative_max_distance=128,\n disable_ngram_loss=False,\n scope=None,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.encoder_seq_length = encoder_seq_length\n self.decoder_seq_length = decoder_seq_length\n # For common tests\n self.seq_length = self.decoder_seq_length\n self.is_training = is_training\n self.use_attention_mask = use_attention_mask\n self.use_labels = use_labels\n\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_decoder_layers\n self.num_encoder_layers = num_encoder_layers\n self.num_decoder_layers = num_decoder_layers\n self.decoder_ffn_dim = decoder_ffn_dim\n self.encoder_ffn_dim = encoder_ffn_dim\n self.num_attention_heads = num_decoder_attention_heads\n self.num_encoder_attention_heads = num_encoder_attention_heads\n self.num_decoder_attention_heads = num_decoder_attention_heads\n self.eos_token_id = eos_token_id\n self.bos_token_id = bos_token_id\n self.pad_token_id = pad_token_id\n self.decoder_start_token_id = decoder_start_token_id\n self.ngram = ngram\n self.num_buckets = num_buckets\n self.relative_max_distance = relative_max_distance\n self.use_cache = use_cache\n self.disable_ngram_loss = disable_ngram_loss\n self.max_position_embeddings = max_position_embeddings\n self.add_cross_attention = add_cross_attention\n self.is_encoder_decoder = is_encoder_decoder\n self.return_dict = return_dict\n\n self.scope = None\n self.decoder_key_length = decoder_seq_length\n self.base_model_out_len = 2\n self.num_hidden_states_types = 2 # decoder_main, decoder_ngram\n self.decoder_attention_idx = 1\n\n def prepare_config_and_inputs(self):\n input_ids = ids_tensor([self.batch_size, self.encoder_seq_length], self.vocab_size)\n\n attention_mask = None\n if self.use_attention_mask:\n attention_mask = ids_tensor([self.batch_size, self.encoder_seq_length], vocab_size=2)\n\n lm_labels = None\n if self.use_labels:\n lm_labels = ids_tensor([self.batch_size, self.encoder_seq_length], self.vocab_size)\n\n config = ProphetNetConfig(\n vocab_size=self.vocab_size,\n hidden_size=self.hidden_size,\n num_encoder_layers=self.num_encoder_layers,\n num_decoder_layers=self.num_decoder_layers,\n decoder_ffn_dim=self.decoder_ffn_dim,\n encoder_ffn_dim=self.encoder_ffn_dim,\n num_encoder_attention_heads=self.num_encoder_attention_heads,\n num_decoder_attention_heads=self.num_decoder_attention_heads,\n eos_token_id=self.eos_token_id,\n bos_token_id=self.bos_token_id,\n use_cache=self.use_cache,\n pad_token_id=self.pad_token_id,\n decoder_start_token_id=self.decoder_start_token_id,\n ngram=self.ngram,\n num_buckets=self.num_buckets,\n relative_max_distance=self.relative_max_distance,\n disable_ngram_loss=self.disable_ngram_loss,\n max_position_embeddings=self.max_position_embeddings,\n add_cross_attention=self.add_cross_attention,\n is_encoder_decoder=self.is_encoder_decoder,\n return_dict=self.return_dict,\n )\n\n return (\n config,\n input_ids,\n attention_mask,\n lm_labels,\n )\n\n def prepare_config_and_inputs_for_decoder(self):\n (\n config,\n input_ids,\n attention_mask,\n lm_labels,\n ) = self.prepare_config_and_inputs()\n\n encoder_hidden_states = floats_tensor([self.batch_size, self.encoder_seq_length, self.hidden_size])\n encoder_attention_mask = ids_tensor([self.batch_size, self.encoder_seq_length], vocab_size=2)\n\n return (\n config,\n input_ids,\n attention_mask,\n encoder_hidden_states,\n encoder_attention_mask,\n lm_labels,\n )\n\n def create_and_check_decoder_model_past(\n self,\n config,\n input_ids,\n attention_mask,\n lm_labels,\n ):\n config.use_cache = True\n model = ProphetNetDecoder(config=config).to(torch_device).eval()\n # first forward pass\n outputs = model(input_ids, use_cache=True)\n outputs_use_cache_conf = model(input_ids)\n outputs_no_past = model(input_ids, use_cache=False)\n\n self.parent.assertTrue(len(outputs) == len(outputs_use_cache_conf))\n self.parent.assertTrue(len(outputs) == len(outputs_no_past) + 1)\n\n past_key_values = outputs[\"past_key_values\"]\n\n # create hypothetical next token and extent to next_input_ids\n next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size)\n\n # append to next input_ids and\n next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)\n\n output_from_no_past = model(next_input_ids)[\"last_hidden_state\"]\n output_from_past = model(next_tokens, past_key_values=past_key_values)[\"last_hidden_state\"]\n\n # select random slice\n random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()\n output_from_no_past_slice = output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach()\n output_from_past_slice = output_from_past[:, 0, random_slice_idx].detach()\n\n # test that outputs are equal for slice\n assert torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3)\n\n def create_and_check_decoder_model_attention_mask_past(\n self,\n config,\n input_ids,\n attention_mask,\n lm_labels,\n ):\n model = ProphetNetDecoder(config=config).to(torch_device).eval()\n\n # create attention mask\n attn_mask = torch.ones(input_ids.shape, dtype=torch.long, device=torch_device)\n\n half_seq_length = input_ids.shape[-1] // 2\n attn_mask[:, half_seq_length:] = 0\n\n # first forward pass\n past_key_values = model(input_ids, attention_mask=attn_mask, use_cache=True)[\"past_key_values\"]\n\n # create hypothetical next token and extent to next_input_ids\n next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size)\n\n # change a random masked slice from input_ids\n random_seq_idx_to_change = ids_tensor((1,), half_seq_length).item() + 1\n random_other_next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size).squeeze(-1)\n input_ids[:, -random_seq_idx_to_change] = random_other_next_tokens\n\n # append to next input_ids and attn_mask\n next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)\n attn_mask = torch.cat(\n [attn_mask, torch.ones((attn_mask.shape[0], 1), dtype=torch.long, device=torch_device)],\n dim=1,\n )\n\n # get two different outputs\n output_from_no_past = model(next_input_ids)[\"last_hidden_state\"]\n output_from_past = model(next_tokens, past_key_values=past_key_values)[\"last_hidden_state\"]\n\n # select random slice\n random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()\n output_from_no_past_slice = output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach()\n output_from_past_slice = output_from_past[:, 0, random_slice_idx].detach()\n\n # test that outputs are equal for slice\n assert torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-2)\n\n def prepare_config_and_inputs_for_common(self):\n config_and_inputs = self.prepare_config_and_inputs()\n (\n config,\n input_ids,\n attention_mask,\n lm_labels,\n ) = config_and_inputs\n\n inputs_dict = {\n \"input_ids\": input_ids,\n \"attention_mask\": attention_mask,\n }\n return config, inputs_dict\n\n\nclass ProphetNetStandaloneEncoderModelTester:\n def __init__(\n self,\n parent,\n vocab_size=99,\n batch_size=13,\n hidden_size=16,\n encoder_seq_length=7,\n decoder_seq_length=7,\n # For common tests\n is_training=True,\n is_decoder=False,\n use_attention_mask=True,\n add_cross_attention=False,\n use_cache=False,\n use_labels=True,\n decoder_start_token_id=0,\n encoder_ffn_dim=32,\n num_encoder_layers=4,\n num_encoder_attention_heads=4,\n decoder_ffn_dim=32,\n num_decoder_layers=4,\n num_decoder_attention_heads=4,\n max_position_embeddings=30,\n is_encoder_decoder=False,\n pad_token_id=0,\n bos_token_id=1,\n eos_token_id=2,\n return_dict=True,\n num_buckets=32,\n relative_max_distance=128,\n disable_ngram_loss=False,\n scope=None,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.encoder_seq_length = encoder_seq_length\n self.decoder_seq_length = decoder_seq_length\n # For common tests\n self.seq_length = self.decoder_seq_length\n self.is_training = is_training\n self.use_attention_mask = use_attention_mask\n self.use_labels = use_labels\n\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_decoder_layers\n self.num_encoder_layers = num_encoder_layers\n self.num_decoder_layers = num_decoder_layers\n self.decoder_ffn_dim = decoder_ffn_dim\n self.encoder_ffn_dim = encoder_ffn_dim\n self.num_attention_heads = num_decoder_attention_heads\n self.num_encoder_attention_heads = num_encoder_attention_heads\n self.num_decoder_attention_heads = num_decoder_attention_heads\n self.eos_token_id = eos_token_id\n self.bos_token_id = bos_token_id\n self.pad_token_id = pad_token_id\n self.decoder_start_token_id = decoder_start_token_id\n self.num_buckets = num_buckets\n self.relative_max_distance = relative_max_distance\n self.use_cache = use_cache\n self.disable_ngram_loss = disable_ngram_loss\n self.max_position_embeddings = max_position_embeddings\n self.add_cross_attention = add_cross_attention\n self.is_encoder_decoder = is_encoder_decoder\n self.return_dict = return_dict\n\n self.scope = None\n self.decoder_key_length = decoder_seq_length\n self.base_model_out_len = 1\n self.num_hidden_states_types = 1\n self.decoder_attention_idx = 1\n\n def prepare_config_and_inputs(self):\n input_ids = ids_tensor([self.batch_size, self.encoder_seq_length], self.vocab_size)\n\n attention_mask = None\n if self.use_attention_mask:\n attention_mask = ids_tensor([self.batch_size, self.encoder_seq_length], vocab_size=2)\n\n config = ProphetNetConfig(\n vocab_size=self.vocab_size,\n hidden_size=self.hidden_size,\n num_encoder_layers=self.num_encoder_layers,\n num_decoder_layers=self.num_decoder_layers,\n decoder_ffn_dim=self.decoder_ffn_dim,\n encoder_ffn_dim=self.encoder_ffn_dim,\n num_encoder_attention_heads=self.num_encoder_attention_heads,\n num_decoder_attention_heads=self.num_decoder_attention_heads,\n eos_token_id=self.eos_token_id,\n bos_token_id=self.bos_token_id,\n use_cache=self.use_cache,\n pad_token_id=self.pad_token_id,\n decoder_start_token_id=self.decoder_start_token_id,\n num_buckets=self.num_buckets,\n relative_max_distance=self.relative_max_distance,\n disable_ngram_loss=self.disable_ngram_loss,\n max_position_embeddings=self.max_position_embeddings,\n add_cross_attention=self.add_cross_attention,\n is_encoder_decoder=self.is_encoder_decoder,\n return_dict=self.return_dict,\n )\n\n return (\n config,\n input_ids,\n attention_mask,\n )\n\n def prepare_config_and_inputs_for_common(self):\n config_and_inputs = self.prepare_config_and_inputs()\n (\n config,\n input_ids,\n attention_mask,\n ) = config_and_inputs\n\n inputs_dict = {\n \"input_ids\": input_ids,\n \"attention_mask\": attention_mask,\n }\n return config, inputs_dict\n\n\n@require_torch\nclass ProphetNetModelTest(ModelTesterMixin, unittest.TestCase):\n all_model_classes = (ProphetNetModel, ProphetNetForConditionalGeneration) if is_torch_available() else ()\n all_generative_model_classes = (ProphetNetForConditionalGeneration,) if is_torch_available() else ()\n test_pruning = False\n test_torchscript = False\n test_resize_embeddings = False\n test_headmasking = False\n is_encoder_decoder = True\n\n def setUp(self):\n self.model_tester = ProphetNetModelTester(self)\n self.config_tester = ConfigTester(self, config_class=ProphetNetConfig)\n\n def test_config(self):\n self.config_tester.run_common_tests()\n\n def test_model(self):\n config_and_inputs = self.model_tester.prepare_config_and_inputs()\n self.model_tester.create_and_check_model(*config_and_inputs)\n\n def test_lm_model(self):\n config_and_inputs = self.model_tester.prepare_config_and_inputs()\n self.model_tester.create_and_check_with_lm_head(*config_and_inputs)\n\n def test_only_decoder_causal_model(self):\n config_and_inputs = self.model_tester.prepare_config_and_inputs()\n self.model_tester.create_and_check_causal_lm_decoder(*config_and_inputs)\n\n def test_fast_integration(self):\n config_and_inputs = self.model_tester.prepare_config_and_inputs()\n self.model_tester.check_fast_integration(*config_and_inputs)\n\n def test_shared_weights(self):\n config_and_inputs = self.model_tester.prepare_config_and_inputs()\n self.model_tester.create_and_check_encoder_decoder_shared_weights(*config_and_inputs)\n\n def test_shift_labels_via_shift_left(self):\n config_and_inputs = self.model_tester.prepare_config_and_inputs()\n self.model_tester.check_prepare_lm_labels_via_shift_left(*config_and_inputs)\n\n def test_decoder_model_generate(self):\n config_and_inputs = self.model_tester.prepare_config_and_inputs()\n self.model_tester.create_and_check_generate_with_past_key_value_states(*config_and_inputs)\n\n def test_attn_mask_model(self):\n config_and_inputs = self.model_tester.prepare_config_and_inputs()\n self.model_tester.check_model_with_attn_mask(*config_and_inputs)\n\n def test_config_save(self):\n config = self.model_tester.prepare_config_and_inputs()[0]\n config.add_cross_attention = False\n with tempfile.TemporaryDirectory() as tmp_dirname:\n config.save_pretrained(tmp_dirname)\n config = ProphetNetConfig.from_pretrained(tmp_dirname)\n\n self.assertFalse(config.add_cross_attention)\n\n @unittest.skipIf(torch_device == \"cpu\", \"Cant do half precision\")\n def test_fp16_forward(self):\n config_and_inputs = self.model_tester.prepare_config_and_inputs()\n self.model_tester.create_and_check_model_fp16_forward(*config_and_inputs)\n\n\n@require_torch\nclass ProphetNetStandaloneDecoderModelTest(ModelTesterMixin, unittest.TestCase):\n all_model_classes = (ProphetNetDecoder, ProphetNetForCausalLM) if is_torch_available() else ()\n all_generative_model_classes = (ProphetNetForCausalLM,) if is_torch_available() else ()\n test_pruning = False\n test_torchscript = False\n test_resize_embeddings = False\n test_headmasking = False\n is_encoder_decoder = False\n\n def setUp(self):\n self.model_tester = ProphetNetStandaloneDecoderModelTester(self)\n self.config_tester = ConfigTester(self, config_class=ProphetNetConfig)\n\n def test_config(self):\n self.config_tester.run_common_tests()\n\n def test_decoder_model_past(self):\n config_and_inputs = self.model_tester.prepare_config_and_inputs()\n self.model_tester.create_and_check_decoder_model_past(*config_and_inputs)\n\n def test_decoder_model_attn_mask_past(self):\n config_and_inputs = self.model_tester.prepare_config_and_inputs()\n self.model_tester.create_and_check_decoder_model_attention_mask_past(*config_and_inputs)\n\n\n@require_torch\nclass ProphetNetStandaloneEncoderModelTest(ModelTesterMixin, unittest.TestCase):\n all_model_classes = (ProphetNetEncoder,) if is_torch_available() else ()\n test_pruning = False\n test_torchscript = False\n test_resize_embeddings = False\n test_headmasking = False\n is_encoder_decoder = False\n\n def setUp(self):\n self.model_tester = ProphetNetStandaloneEncoderModelTester(self)\n self.config_tester = ConfigTester(self, config_class=ProphetNetConfig)\n\n def test_config(self):\n self.config_tester.run_common_tests()\n\n\n@require_torch\nclass ProphetNetModelIntegrationTest(unittest.TestCase):\n @slow\n def test_pretrained_checkpoint_hidden_states(self):\n model = ProphetNetForConditionalGeneration.from_pretrained(\"microsoft/prophetnet-large-uncased\")\n model.to(torch_device)\n\n # encoder-decoder outputs\n encoder_ids = torch.tensor(\n [\n [\n 2871,\n 102,\n 2048,\n 3176,\n 2780,\n 1997,\n 2871,\n 26727,\n 2169,\n 2097,\n 12673,\n 1996,\n 8457,\n 2006,\n 2049,\n 8240,\n 2859,\n 2799,\n 1012,\n 2023,\n 6512,\n 2038,\n 2174,\n 13977,\n 2195,\n 25962,\n 1012,\n 102,\n ]\n ]\n ).to(torch_device)\n\n decoder_prev_ids = torch.tensor([[102, 2129, 2116, 2372, 2024, 2006, 2169, 1997, 2122, 2048, 2780, 1029]]).to(\n torch_device\n )\n output = model(\n input_ids=encoder_ids,\n attention_mask=None,\n encoder_outputs=None,\n decoder_input_ids=decoder_prev_ids,\n return_dict=True,\n )\n output_predited_logits = output[0]\n expected_shape = torch.Size((1, 12, 30522))\n self.assertEqual(output_predited_logits.shape, expected_shape)\n expected_slice = torch.tensor(\n [[[-7.6213, -7.9008, -7.9979], [-7.6834, -7.8467, -8.2187], [-7.5326, -7.4762, -8.1914]]]\n ).to(torch_device)\n # self.assertTrue(torch.allclose(output_predited_logits[:, :3, :3], expected_slice, atol=1e-4))\n assert torch.allclose(output_predited_logits[:, :3, :3], expected_slice, atol=1e-4)\n\n # encoder outputs\n encoder_outputs = model.prophetnet.encoder(encoder_ids)[0]\n expected_encoder_outputs_slice = torch.tensor(\n [[[-0.2526, -0.1951, -0.2185], [-0.8923, 0.2992, -0.4623], [-0.4585, 0.0165, -0.6652]]]\n ).to(torch_device)\n expected_shape_encoder = torch.Size((1, 28, 1024))\n self.assertEqual(encoder_outputs.shape, expected_shape_encoder)\n # self.assertTrue(torch.allclose(encoder_outputs[:, :3, :3], expected_encoder_outputs_slice, atol=1e-4))\n assert torch.allclose(encoder_outputs[:, :3, :3], expected_encoder_outputs_slice, atol=1e-4)\n\n # decoder outputs\n decoder_outputs = model.prophetnet.decoder(\n decoder_prev_ids, encoder_hidden_states=encoder_outputs, return_dict=True\n )\n predicting_streams = decoder_outputs[1].view(1, model.config.ngram, 12, -1)\n predicting_streams_logits = model.lm_head(predicting_streams)\n next_first_stream_logits = predicting_streams_logits[:, 0]\n # self.assertTrue(torch.allclose(next_first_stream_logits[:, :3, :3], expected_slice, atol=1e-4))\n assert torch.allclose(next_first_stream_logits[:, :3, :3], expected_slice, atol=1e-4)\n\n @slow\n def test_cnndm_inference(self):\n model = ProphetNetForConditionalGeneration.from_pretrained(\"microsoft/prophetnet-large-uncased-cnndm\")\n model.config.max_length = 512\n model.to(torch_device)\n\n tokenizer = ProphetNetTokenizer.from_pretrained(\"microsoft/prophetnet-large-uncased-cnndm\")\n\n ARTICLE_TO_SUMMARIZE = \"USTC was founded in Beijing by the Chinese Academy of Sciences (CAS) in September 1958. The Director of CAS, Mr. Guo Moruo was appointed the first president of USTC. USTC's founding mission was to develop a high-level science and technology workforce, as deemed critical for development of China's economy, defense, and science and technology education. The establishment was hailed as \\\"A Major Event in the History of Chinese Education and Science.\\\" CAS has supported USTC by combining most of its institutes with the departments of the university. USTC is listed in the top 16 national key universities, becoming the youngest national key university.\".lower()\n input_ids = tokenizer([ARTICLE_TO_SUMMARIZE], max_length=511, return_tensors=\"pt\").input_ids\n\n input_ids = input_ids.to(torch_device)\n\n summary_ids = model.generate(\n input_ids, num_beams=4, length_penalty=1.0, no_repeat_ngram_size=3, early_stopping=True\n )\n EXPECTED_SUMMARIZE_512 = \"us ##tc was founded by the chinese academy of sciences ( cas ) in 1958 . [X_SEP] us ##tc is listed in the top 16 national key universities .\"\n generated_titles = [\n \" \".join(tokenizer.convert_ids_to_tokens(g, skip_special_tokens=True)) for g in summary_ids\n ]\n self.assertListEqual(\n [EXPECTED_SUMMARIZE_512],\n generated_titles,\n )\n input_ids = tokenizer([ARTICLE_TO_SUMMARIZE], max_length=99, return_tensors=\"pt\").input_ids\n input_ids = input_ids.to(torch_device)\n # actually 98 tokens are used. max_length=100 contains bos and eos.\n summary_ids = model.generate(\n input_ids, num_beams=4, length_penalty=1.0, no_repeat_ngram_size=3, early_stopping=True\n )\n EXPECTED_SUMMARIZE_100 = (\n r\"us ##tc was founded in beijing by the chinese academy of sciences ( cas ) in 1958 . [X_SEP] us ##tc \"\n \"'\"\n ' s founding mission was to develop a high - level science and technology workforce . [X_SEP] establishment hailed as \" a major event in the history of chinese education and science \"'\n )\n generated_titles = [\n \" \".join(tokenizer.convert_ids_to_tokens(g, skip_special_tokens=True)) for g in summary_ids\n ]\n self.assertListEqual(\n [EXPECTED_SUMMARIZE_100],\n generated_titles,\n )\n\n @slow\n def test_question_gen_inference(self):\n model = ProphetNetForConditionalGeneration.from_pretrained(\"microsoft/prophetnet-large-uncased-squad-qg\")\n model.to(torch_device)\n\n tokenizer = ProphetNetTokenizer.from_pretrained(\"microsoft/prophetnet-large-uncased-squad-qg\")\n\n INPUTS = [\n \"Bill Gates [SEP] Microsoft was founded by Bill Gates and Paul Allen on April 4, 1975.\",\n \"1975 [SEP] Microsoft was founded by Bill Gates and Paul Allen on April 4, 1975.\",\n \"April 4, 1975 [SEP] Microsoft was founded by Bill Gates and Paul Allen on April 4, 1975.\",\n ]\n\n input_ids = tokenizer(INPUTS, truncation=True, padding=True, return_tensors=\"pt\").input_ids\n input_ids = input_ids.to(torch_device)\n\n gen_output = model.generate(input_ids, num_beams=5, early_stopping=True)\n generated_questions = tokenizer.batch_decode(gen_output, skip_special_tokens=True)\n\n EXPECTED_QUESTIONS = [\n \"along with paul allen, who founded microsoft?\",\n \"what year was microsoft founded?\",\n \"on what date was microsoft founded?\",\n ]\n\n self.assertListEqual(\n EXPECTED_QUESTIONS,\n generated_questions,\n )\n"
] | [
[
"torch.all",
"torch.Size",
"torch.ones",
"torch.isnan",
"torch.cat",
"torch.manual_seed",
"torch.tensor",
"torch.no_grad",
"torch.allclose",
"torch.ones_like"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
adityasaxena26/OpenAI-Gym-Taxi-v2-Task | [
"e6061b39134c511de47b490f034317466c3c892e"
] | [
"agent.py"
] | [
"import numpy as np\nfrom collections import defaultdict\n\nclass Agent:\n\n def __init__(self, nA=6):\n \"\"\"\n Initialize agent.\n\n Params\n ======\n nA: number of actions available to the agent\n \"\"\"\n self.nA = nA\n self.Q = defaultdict(lambda: np.zeros(self.nA))\n\n def select_action(self, state):\n \"\"\"\n Given the state, select an action.\n\n Params\n ======\n state: the current state of the environment\n\n Returns\n =======\n action: an integer, compatible with the task's action space\n \"\"\"\n return np.random.choice(self.nA)\n\n def step(self, state, action, reward, next_state, done):\n \"\"\"\n Update the agent's knowledge, using the most recently sampled tuple.\n\n Params\n ======\n state: the previous state of the environment\n action: the agent's previous choice of action\n reward: last reward received\n next_state: the current state of the environment\n done: whether the episode is complete (True or False)\n \"\"\"\n self.Q[state][action] += 1\n"
] | [
[
"numpy.zeros",
"numpy.random.choice"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
astrobeard/VICEdev | [
"c78804ec63b48a760ce3e50b8d3afc7b699ec75f"
] | [
"starbursts/plots/mpl.SFEoscil.py"
] | [
"\nimport visuals \nimport matplotlib.pyplot as plt \nfrom matplotlib.ticker import FormatStrFormatter \nimport vice \nimport sys \nimport warnings \nwarnings.filterwarnings(\"ignore\") \n\nif __name__ == \"__main__\": \n\taxes = visuals.subplots(1, 3, figsize = (21, 7)) \n\taxes.insert(1, visuals.append_subplot_below(axes[0])) \n\taxes[0].xaxis.set_ticks([0, 2, 4, 6, 8, 10]) \n\taxes[0].set_xlim([-1, 11]) \n\taxes[0].set_ylim([2.1, 3.6]) \n\taxes[1].set_ylim([1.3, 2.7]) \n\taxes[2].set_xlim([-1.7, 0.2]) \n\taxes[2].set_ylim([-0.1, 0.5]) \n\taxes[3].set_xlim([-0.1, 0.5]) \n\taxes[3].set_ylim([0.2, 50]) \n\tvisuals.set_labels_4axes(axes, \"O\") \n\tinset_xlim = [-0.26, -0.06] \n\tinset_ylim = [0.06, 0.16]\n\tvisuals.draw_box(axes[2], inset_xlim, inset_ylim) \n\tinset = visuals.zoom_box(axes[2], inset_xlim, inset_ylim, zoom = 3.8) \n\tvisuals.plot_output_4axes(axes, \n\t\t\"../../simulations/SFEoscil_amp0p2_per4\", \"crimson\", \"O\") \n\tvisuals.plot_output_4axes(axes, \n\t\t\"../../simulations/SFEoscil_amp0p4_per2\", \"blue\", \"O\") \n\tvisuals.plot_output_4axes(axes, \n\t\t\"../../simulations/SFEoscil_amp0p2_per2\", \"black\", \"O\") \n\tvisuals.plot_inset(inset, \n\t\t\"../../simulations/SFEoscil_amp0p2_per4\", \"crimson\") \n\tvisuals.plot_inset(inset, \n\t\t\"../../simulations/SFEoscil_amp0p4_per2\", \"blue\") \n\tvisuals.plot_inset(inset, \n\t\t\"../../simulations/SFEoscil_amp0p2_per2\", \"black\") \n\tvisuals.plot_inset(inset, \n\t\t\"../../simulations/default\", \"black\", linestyle = ':') \n\tvisuals.plot_reference(axes) \n\tvisuals.yticklabel_formatter(axes[-1])\n\tplt.tight_layout() \n\tplt.savefig(sys.argv[1]) \n\tplt.clf() \n\n"
] | [
[
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.clf"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ryanirl/ml-basics | [
"e143eacf6338877d8111d1c0ee56853475efa914"
] | [
"logistic_regression/logistic_regression.py"
] | [
"import numpy as np\nfrom sklearn.datasets import make_blobs\nimport matplotlib.pyplot as plt\n\n\n### --- Gather Dataset --- ###\n\nn = 100\nX, y = make_blobs(n_samples = n, centers = 2)\n\ny = y[:, np.newaxis]\n\n\n### --- Build Model --- ###\n\ndef sigmoid(z): \n return 1.0 / (1.0 + np.exp(-z))\n\nclass LogisticRegression:\n def predict(self, X, w, b):\n return sigmoid(X.dot(w) + b)\n\n def loss(self, pred, y):\n BCE = (y * np.log(pred + 1e-6) + (1 - y) * np.log(1 - pred + 1e-6)) \n return -np.sum(BCE) * (1.0 / self.m)\n\n def fit(self, X, y):\n eta = 0.01\n epochs = 5000\n\n self.m, self.n = X.shape\n\n self.weights = np.random.uniform(-1, 1, (self.n, 1))\n self.bias = np.random.uniform(-1, 1, (1, 1))\n\n for i in range(epochs):\n predicted = self.predict(X, self.weights, self.bias)\n\n if i % 100 == 0: print(\"Loss on step {} is: {}\".format(i, self.loss(predicted, y)))\n\n self.weights = self.weights - eta * X.T.dot(predicted - y)\n self.bias = self.bias - eta * np.sum(predicted - y)\n\n\n\n### --- Instantiate Model --- ###\n\nmodel = LogisticRegression()\nmodel.fit(X, y)\n\nweight0, weight1 = model.weights\nbias = model.bias[0][0]\n\n\n### --- Plot --- ###\n\nfor i in range(n):\n if (y[i] == 1):\n plt.scatter(X[:, 0][i], X[:, 1][i], color=\"green\") \n else:\n plt.scatter(X[:, 0][i], X[:, 1][i], color=\"blue\")\n\n \nx = np.linspace(-5, 5, 5)\n\nhyperplane = (-(weight0 / weight1) * x) - (bias / weight1)\n\nplt.suptitle(\"Logistic Regression\")\n\nplt.plot(x, hyperplane, '-', color = \"red\")\n\nplt.show()\n\n"
] | [
[
"numpy.log",
"numpy.linspace",
"sklearn.datasets.make_blobs",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.plot",
"numpy.exp",
"numpy.random.uniform",
"matplotlib.pyplot.suptitle",
"numpy.sum",
"matplotlib.pyplot.show"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
colliner/spektral | [
"b776200fd1fa820f05b559f0c1c6265e0eca4894",
"b776200fd1fa820f05b559f0c1c6265e0eca4894"
] | [
"spektral/layers/convolutional/gat_conv.py",
"tests/test_data/test_utils.py"
] | [
"import tensorflow as tf\nfrom tensorflow.keras import backend as K\nfrom tensorflow.keras import initializers, regularizers, constraints\nfrom tensorflow.keras.layers import Dropout\n\nfrom spektral.layers import ops\nfrom spektral.layers.convolutional.conv import Conv\nfrom spektral.layers.ops import modes\n\n\nclass GATConv(Conv):\n r\"\"\"\n A Graph Attention layer (GAT) from the paper\n\n > [Graph Attention Networks](https://arxiv.org/abs/1710.10903)<br>\n > Petar Veličković et al.\n\n **Mode**: single, disjoint, mixed, batch.\n\n **This layer expects dense inputs when working in batch mode.**\n\n This layer computes a convolution similar to `layers.GraphConv`, but\n uses the attention mechanism to weight the adjacency matrix instead of\n using the normalized Laplacian:\n $$\n \\X' = \\mathbf{\\alpha}\\X\\W + \\b\n $$\n where\n $$\n \\mathbf{\\alpha}_{ij} =\\frac{ \\exp\\left(\\mathrm{LeakyReLU}\\left(\n \\a^{\\top} [(\\X\\W)_i \\, \\| \\, (\\X\\W)_j]\\right)\\right)}{\\sum\\limits_{k\n \\in \\mathcal{N}(i) \\cup \\{ i \\}} \\exp\\left(\\mathrm{LeakyReLU}\\left(\n \\a^{\\top} [(\\X\\W)_i \\, \\| \\, (\\X\\W)_k]\\right)\\right)}\n $$\n where \\(\\a \\in \\mathbb{R}^{2F'}\\) is a trainable attention kernel.\n Dropout is also applied to \\(\\alpha\\) before computing \\(\\Z\\).\n Parallel attention heads are computed in parallel and their results are\n aggregated by concatenation or average.\n\n **Input**\n\n - Node features of shape `([batch], n_nodes, n_node_features)`;\n - Binary adjacency matrix of shape `([batch], n_nodes, n_nodes)`;\n\n **Output**\n\n - Node features with the same shape as the input, but with the last\n dimension changed to `channels`;\n - if `return_attn_coef=True`, a list with the attention coefficients for\n each attention head. Each attention coefficient matrix has shape\n `([batch], n_nodes, n_nodes)`.\n\n **Arguments**\n\n - `channels`: number of output channels;\n - `attn_heads`: number of attention heads to use;\n - `concat_heads`: bool, whether to concatenate the output of the attention\n heads instead of averaging;\n - `dropout_rate`: internal dropout rate for attention coefficients;\n - `return_attn_coef`: if True, return the attention coefficients for\n the given input (one n_nodes x n_nodes matrix for each head).\n - `activation`: activation function;\n - `use_bias`: bool, add a bias vector to the output;\n - `kernel_initializer`: initializer for the weights;\n - `attn_kernel_initializer`: initializer for the attention weights;\n - `bias_initializer`: initializer for the bias vector;\n - `kernel_regularizer`: regularization applied to the weights;\n - `attn_kernel_regularizer`: regularization applied to the attention kernels;\n - `bias_regularizer`: regularization applied to the bias vector;\n - `activity_regularizer`: regularization applied to the output;\n - `kernel_constraint`: constraint applied to the weights;\n - `attn_kernel_constraint`: constraint applied to the attention kernels;\n - `bias_constraint`: constraint applied to the bias vector.\n\n \"\"\"\n\n def __init__(self,\n channels,\n attn_heads=1,\n concat_heads=True,\n dropout_rate=0.5,\n return_attn_coef=False,\n activation=None,\n use_bias=True,\n kernel_initializer='glorot_uniform',\n bias_initializer='zeros',\n attn_kernel_initializer='glorot_uniform',\n kernel_regularizer=None,\n bias_regularizer=None,\n attn_kernel_regularizer=None,\n activity_regularizer=None,\n kernel_constraint=None,\n bias_constraint=None,\n attn_kernel_constraint=None,\n **kwargs):\n super().__init__(activation=activation,\n use_bias=use_bias,\n kernel_initializer=kernel_initializer,\n bias_initializer=bias_initializer,\n kernel_regularizer=kernel_regularizer,\n bias_regularizer=bias_regularizer,\n activity_regularizer=activity_regularizer,\n kernel_constraint=kernel_constraint,\n bias_constraint=bias_constraint,\n **kwargs)\n self.channels = channels\n self.attn_heads = attn_heads\n self.concat_heads = concat_heads\n self.dropout_rate = dropout_rate\n self.return_attn_coef = return_attn_coef\n self.attn_kernel_initializer = initializers.get(attn_kernel_initializer)\n self.attn_kernel_regularizer = regularizers.get(attn_kernel_regularizer)\n self.attn_kernel_constraint = constraints.get(attn_kernel_constraint)\n\n if concat_heads:\n self.output_dim = self.channels * self.attn_heads\n else:\n self.output_dim = self.channels\n\n def build(self, input_shape):\n assert len(input_shape) >= 2\n input_dim = input_shape[0][-1]\n\n self.kernel = self.add_weight(\n name='kernel',\n shape=[input_dim, self.attn_heads, self.channels],\n initializer=self.kernel_initializer,\n regularizer=self.kernel_regularizer,\n constraint=self.kernel_constraint,\n )\n self.attn_kernel_self = self.add_weight(\n name='attn_kernel_self',\n shape=[self.channels, self.attn_heads, 1],\n initializer=self.attn_kernel_initializer,\n regularizer=self.attn_kernel_regularizer,\n constraint=self.attn_kernel_constraint,\n )\n self.attn_kernel_neighs = self.add_weight(\n name='attn_kernel_neigh',\n shape=[self.channels, self.attn_heads, 1],\n initializer=self.attn_kernel_initializer,\n regularizer=self.attn_kernel_regularizer,\n constraint=self.attn_kernel_constraint,\n )\n if self.use_bias:\n self.bias = self.add_weight(\n shape=[self.output_dim],\n initializer=self.bias_initializer,\n regularizer=self.bias_regularizer,\n constraint=self.bias_constraint,\n name='bias'\n )\n\n self.dropout = Dropout(self.dropout_rate)\n self.built = True\n\n def call(self, inputs):\n x, a = inputs\n\n mode = ops.autodetect_mode(a, x)\n if mode == modes.SINGLE and K.is_sparse(a):\n output, attn_coef = self._call_single(x, a)\n else:\n output, attn_coef = self._call_dense(x, a)\n\n if self.concat_heads:\n shape = output.shape[:-2] + [self.attn_heads * self.channels]\n shape = [d if d is not None else -1 for d in shape]\n output = tf.reshape(output, shape)\n else:\n output = tf.reduce_mean(output, axis=-2)\n\n if self.use_bias:\n output += self.bias\n\n output = self.activation(output)\n\n if self.return_attn_coef:\n return output, attn_coef\n else:\n return output\n\n def _call_single(self, x, a):\n # Reshape kernels for efficient message-passing\n kernel = tf.reshape(self.kernel, (-1, self.attn_heads * self.channels))\n attn_kernel_self = ops.transpose(self.attn_kernel_self, (2, 1, 0))\n attn_kernel_neighs = ops.transpose(self.attn_kernel_neighs, (2, 1, 0))\n\n # Prepare message-passing\n indices = a.indices\n N = tf.shape(x, out_type=indices.dtype)[0]\n indices = ops.add_self_loops_indices(indices, N)\n targets, sources = indices[:, -2], indices[:, -1]\n\n # Update node features\n x = ops.dot(x, kernel)\n x = tf.reshape(x, (-1, self.attn_heads, self.channels))\n\n # Compute attention\n attn_for_self = tf.reduce_sum(x * attn_kernel_self, -1)\n attn_for_self = tf.gather(attn_for_self, targets)\n attn_for_neighs = tf.reduce_sum(x * attn_kernel_neighs, -1)\n attn_for_neighs = tf.gather(attn_for_neighs, sources)\n\n attn_coef = attn_for_self + attn_for_neighs\n attn_coef = tf.nn.leaky_relu(attn_coef, alpha=0.2)\n attn_coef = ops.unsorted_segment_softmax(attn_coef, targets, N)\n attn_coef = self.dropout(attn_coef)\n attn_coef = attn_coef[..., None]\n\n # Update representation\n output = attn_coef * tf.gather(x, sources)\n output = ops.scatter_sum(output, targets, N)\n\n return output, attn_coef\n\n def _call_dense(self, x, a):\n shape = tf.shape(a)[:-1]\n a = tf.linalg.set_diag(a, tf.zeros(shape, a.dtype))\n a = tf.linalg.set_diag(a, tf.ones(shape, a.dtype))\n x = tf.einsum(\"...NI , IHO -> ...NHO\", x, self.kernel)\n attn_for_self = tf.einsum(\"...NHI , IHO -> ...NHO\", x, self.attn_kernel_self)\n attn_for_neighs = tf.einsum(\"...NHI , IHO -> ...NHO\", x, self.attn_kernel_neighs)\n attn_for_neighs = tf.einsum(\"...ABC -> ...CBA\", attn_for_neighs)\n\n attn_coef = attn_for_self + attn_for_neighs\n attn_coef = tf.nn.leaky_relu(attn_coef, alpha=0.2)\n\n mask = -10e9 * (1.0 - a)\n attn_coef += mask[..., None, :]\n attn_coef = tf.nn.softmax(attn_coef, axis=-1)\n attn_coef_drop = self.dropout(attn_coef)\n\n output = tf.einsum(\"...NHM , ...MHI -> ...NHI\", attn_coef_drop, x)\n\n return output, attn_coef\n\n @property\n def config(self):\n return {\n 'channels': self.channels,\n 'attn_heads': self.attn_heads,\n 'concat_heads': self.concat_heads,\n 'dropout_rate': self.dropout_rate,\n 'return_attn_coef': self.return_attn_coef,\n 'attn_kernel_initializer': initializers.serialize(self.attn_kernel_initializer),\n 'attn_kernel_regularizer': regularizers.serialize(self.attn_kernel_regularizer),\n 'attn_kernel_constraint': constraints.serialize(self.attn_kernel_constraint),\n }\n",
"import numpy as np\nimport scipy.sparse as sp\n\nfrom spektral.data import Dataset, Graph\nfrom spektral.data.utils import to_disjoint, to_batch, batch_generator\n\nns = np.random.randint(3, 10, 10)\nf = 3\na_list = [sp.csr_matrix(np.ones((n, n))) for n in ns]\nx_list = [np.random.rand(n, f) for n in ns]\ny = [[0, 1]] * len(ns)\n\n\ndef test_to_batch():\n # TODO test e_list\n x = to_batch(x_list=x_list)\n a = to_batch(a_list=a_list)\n x, a = to_batch(x_list, a_list)\n assert x.ndim == 3\n assert a.ndim == 3\n assert x.shape[0] == a.shape[0]\n assert x.shape[1] == a.shape[1] == a.shape[2]\n\n\ndef test_to_disjoint():\n # TODO test e_list\n x, i = to_disjoint(x_list, None)\n a, i = to_disjoint(None, a_list)\n x, a, i = to_disjoint(x_list, a_list)\n assert x.ndim == 2\n assert a.ndim == 2\n assert x.shape[0] == a.shape[0] == a.shape[1]\n\n\ndef test_batch_generator():\n size = 10\n batch_size = 6\n a = list(range(size))\n b = np.arange(size)\n\n class TestDataset(Dataset):\n def read(self):\n return [\n Graph(x=np.random.rand(n, 2), a=np.random.randint(0, 2, (n, n)), y=np.array([0., 1.]))\n for n in range(size)\n ]\n\n c = TestDataset()\n\n batches = batch_generator([a, b, c], batch_size=batch_size, epochs=10)\n for batch in batches:\n a_, b_, c_ = batch\n for i in range(len(a_)):\n assert a_[i] == b_[i] == c_[i].n_nodes\n"
] | [
[
"tensorflow.keras.constraints.serialize",
"tensorflow.nn.softmax",
"tensorflow.keras.constraints.get",
"tensorflow.reduce_mean",
"tensorflow.shape",
"tensorflow.reduce_sum",
"tensorflow.zeros",
"tensorflow.keras.regularizers.get",
"tensorflow.reshape",
"tensorflow.ones",
"tensorflow.keras.initializers.serialize",
"tensorflow.einsum",
"tensorflow.keras.regularizers.serialize",
"tensorflow.gather",
"tensorflow.keras.layers.Dropout",
"tensorflow.keras.backend.is_sparse",
"tensorflow.keras.initializers.get",
"tensorflow.nn.leaky_relu"
],
[
"numpy.arange",
"numpy.ones",
"numpy.random.rand",
"numpy.array",
"numpy.random.randint"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Abrahamma97/keras-onnx | [
"c08d52bf4d4ec2bba69ec4ffd2ea14f47fecb1f5",
"e49ef6163e1f2be017fff96f908eaea819f6e0b4",
"e49ef6163e1f2be017fff96f908eaea819f6e0b4",
"e49ef6163e1f2be017fff96f908eaea819f6e0b4",
"e49ef6163e1f2be017fff96f908eaea819f6e0b4"
] | [
"applications/nightly_build/test_lsgan.py",
"tests/test_cgan.py",
"keras2onnx/_graph_cvt.py",
"keras2onnx/ke2onnx/common.py",
"applications/nightly_build/test_bgan.py"
] | [
"###############################################################################\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n###############################################################################\nimport os\nimport sys\nimport unittest\nimport keras2onnx\nimport onnx\nimport numpy as np\nfrom keras2onnx.proto import keras\nfrom os.path import dirname, abspath\nsys.path.insert(0, os.path.join(dirname(abspath(__file__)), '../../tests/'))\nfrom test_utils import run_onnx_runtime\n\nActivation = keras.layers.Activation\nBatchNormalization = keras.layers.BatchNormalization\nConv2D = keras.layers.Conv2D\nDense = keras.layers.Dense\nDropout = keras.layers.Dropout\nEmbedding = keras.layers.Embedding\nFlatten = keras.layers.Flatten\nInput = keras.layers.Input\nLeakyReLU = keras.layers.LeakyReLU\nmultiply = keras.layers.multiply\nReshape = keras.layers.Reshape\nUpSampling2D = keras.layers.UpSampling2D\nZeroPadding2D = keras.layers.ZeroPadding2D\n\nSequential = keras.models.Sequential\nModel = keras.models.Model\n\n# From https://github.com/eriklindernoren/Keras-GAN/blob/master/lsgan/lsgan.py\nclass LSGAN():\n def __init__(self):\n self.img_rows = 28\n self.img_cols = 28\n self.channels = 1\n self.img_shape = (self.img_rows, self.img_cols, self.channels)\n self.latent_dim = 100\n\n # Build and compile the discriminator\n self.discriminator = self.build_discriminator()\n\n # Build the generator\n self.generator = self.build_generator()\n\n # The generator takes noise as input and generated imgs\n z = Input(shape=(self.latent_dim,))\n img = self.generator(z)\n\n # For the combined model we will only train the generator\n self.discriminator.trainable = False\n\n # The valid takes generated images as input and determines validity\n valid = self.discriminator(img)\n\n # The combined model (stacked generator and discriminator)\n # Trains generator to fool discriminator\n self.combined = Model(z, valid)\n\n def build_generator(self):\n\n model = Sequential()\n\n model.add(Dense(256, input_dim=self.latent_dim))\n model.add(LeakyReLU(alpha=0.2))\n model.add(BatchNormalization(momentum=0.8))\n model.add(Dense(512))\n model.add(LeakyReLU(alpha=0.2))\n model.add(BatchNormalization(momentum=0.8))\n model.add(Dense(1024))\n model.add(LeakyReLU(alpha=0.2))\n model.add(BatchNormalization(momentum=0.8))\n model.add(Dense(np.prod(self.img_shape), activation='tanh'))\n model.add(Reshape(self.img_shape))\n\n noise = Input(shape=(self.latent_dim,))\n img = model(noise)\n\n return Model(noise, img)\n\n def build_discriminator(self):\n\n model = Sequential()\n\n model.add(Flatten(input_shape=self.img_shape))\n model.add(Dense(512))\n model.add(LeakyReLU(alpha=0.2))\n model.add(Dense(256))\n model.add(LeakyReLU(alpha=0.2))\n # (!!!) No softmax\n model.add(Dense(1))\n\n img = Input(shape=self.img_shape)\n validity = model(img)\n\n return Model(img, validity)\n\n\nclass TestLSGAN(unittest.TestCase):\n\n def setUp(self):\n self.model_files = []\n\n def tearDown(self):\n for fl in self.model_files:\n os.remove(fl)\n\n def test_LSGAN(self):\n keras_model = LSGAN().combined\n x = np.random.rand(5, 100).astype(np.float32)\n expected = keras_model.predict(x)\n onnx_model = keras2onnx.convert_keras(keras_model, keras_model.name)\n self.assertTrue(run_onnx_runtime(onnx_model.graph.name, onnx_model, x, expected, self.model_files))\n\n\nif __name__ == \"__main__\":\n unittest.main()\n",
"###############################################################################\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n###############################################################################\nimport pytest\nimport tensorflow as tf\nimport keras2onnx\nimport numpy as np\nfrom keras2onnx.proto import keras, is_tf_keras\nfrom distutils.version import StrictVersion\n\nActivation = keras.layers.Activation\nBatchNormalization = keras.layers.BatchNormalization\nDense = keras.layers.Dense\nDropout = keras.layers.Dropout\nEmbedding = keras.layers.Embedding\nFlatten = keras.layers.Flatten\nInput = keras.layers.Input\nLeakyReLU = keras.layers.LeakyReLU\nmultiply = keras.layers.multiply\nReshape = keras.layers.Reshape\nUpSampling2D = keras.layers.UpSampling2D\n\nSequential = keras.models.Sequential\nModel = keras.models.Model\n\n\n# From https://github.com/eriklindernoren/Keras-GAN/blob/master/cgan/cgan.py\nclass CGAN():\n def __init__(self):\n # Input shape\n self.img_rows = 28\n self.img_cols = 28\n self.channels = 1\n self.img_shape = (self.img_rows, self.img_cols, self.channels)\n self.num_classes = 10\n self.latent_dim = 100\n\n # Build and compile the discriminator\n self.discriminator = self.build_discriminator()\n\n # Build the generator\n self.generator = self.build_generator()\n\n # The generator takes noise and the target label as input\n # and generates the corresponding digit of that label\n noise = Input(shape=(self.latent_dim,))\n label = Input(shape=(1,))\n img = self.generator([noise, label])\n\n # For the combined model we will only train the generator\n self.discriminator.trainable = False\n\n # The discriminator takes generated image as input and determines validity\n # and the label of that image\n valid = self.discriminator([img, label])\n\n # The combined model (stacked generator and discriminator)\n # Trains generator to fool discriminator\n self.combined = Model([noise, label], valid)\n\n def get_model(self):\n return self.combined\n\n def build_generator(self):\n model = Sequential()\n\n model.add(Dense(256, input_dim=self.latent_dim))\n\n model.add(LeakyReLU(alpha=0.2))\n model.add(BatchNormalization(momentum=0.8))\n model.add(Dense(512))\n model.add(LeakyReLU(alpha=0.2))\n model.add(BatchNormalization(momentum=0.8))\n model.add(Dense(1024))\n model.add(LeakyReLU(alpha=0.2))\n model.add(BatchNormalization(momentum=0.8))\n\n model.add(Dense(np.prod(self.img_shape), activation='tanh'))\n model.add(Reshape(self.img_shape))\n\n noise = Input(shape=(self.latent_dim,))\n label = Input(shape=(1,), dtype='int32')\n label_embedding = Flatten()(Embedding(self.num_classes, self.latent_dim)(label))\n\n model_input = multiply([noise, label_embedding])\n img = model(model_input)\n\n return Model([noise, label], img)\n\n def build_discriminator(self):\n model = Sequential()\n\n model.add(Dense(512, input_dim=np.prod(self.img_shape)))\n model.add(LeakyReLU(alpha=0.2))\n model.add(Dense(512))\n model.add(LeakyReLU(alpha=0.2))\n model.add(Dropout(0.4))\n model.add(Dense(512))\n model.add(LeakyReLU(alpha=0.2))\n model.add(Dropout(0.4))\n model.add(Dense(1, activation='sigmoid'))\n\n model.add(Dense(1, activation='sigmoid'))\n\n img = Input(shape=self.img_shape)\n label = Input(shape=(1,), dtype='int32')\n\n label_embedding = Flatten()(Embedding(self.num_classes, np.prod(self.img_shape))(label))\n flat_img = Flatten()(img)\n\n model_input = multiply([flat_img, label_embedding])\n\n validity = model(model_input)\n\n return Model([img, label], validity)\n\n\[email protected](keras2onnx.proto.tfcompat.is_tf2 and is_tf_keras, reason=\"Tensorflow 1.x only tests.\")\[email protected](is_tf_keras and StrictVersion(tf.__version__.split('-')[0]) < StrictVersion(\"1.14.0\"),\n reason=\"Not supported before tensorflow 1.14.0 for tf_keras\")\ndef test_CGAN(runner):\n keras_model = CGAN().combined\n batch = 5\n x = np.random.rand(batch, 100).astype(np.float32)\n y = np.random.rand(batch, 1).astype(np.float32)\n expected = keras_model.predict([x, y])\n onnx_model = keras2onnx.convert_keras(keras_model, keras_model.name)\n assert runner(onnx_model.graph.name, onnx_model,\n {keras_model.input_names[0]: x, keras_model.input_names[1]: y}, expected)\n",
"# 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\"\"\"Helpers to convert variables to constants in TensorFlow 2.0.\"\"\"\n# flake8: noqa\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nfrom tensorflow.core.framework import attr_value_pb2\nfrom tensorflow.core.framework import graph_pb2\nfrom tensorflow.core.framework import tensor_shape_pb2\nfrom tensorflow.core.framework import variable_pb2\nfrom tensorflow.core.protobuf import config_pb2\nfrom tensorflow.core.protobuf import meta_graph_pb2\nfrom tensorflow.python.eager import wrap_function\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import tensor_util\nfrom tensorflow.python.grappler import tf_optimizer\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.util import object_identity\nfrom tensorflow.python.training.saver import export_meta_graph\n\n\n_CONDITIONAL_OPS = set([\"If\", \"StatelessIf\"])\n_LOOP_OPS = set([\"While\", \"StatelessWhile\"])\n_CONTROL_FLOW_OPS = _CONDITIONAL_OPS.union(_LOOP_OPS)\n\n\ndef disable_lower_using_switch_merge(graph_def):\n \"\"\"Set '_lower_using_switch_merge' attributes to False.\n\n Sets the attribute to False in the NodeDefs in the main graph and the NodeDefs\n in each function's graph.\n\n Args:\n graph_def: GraphDef proto.\n\n Returns:\n GraphDef\n \"\"\"\n output_graph_def = graph_pb2.GraphDef()\n output_graph_def.CopyFrom(graph_def)\n\n def disable_control_flow_lowering(node):\n if node.op in _CONTROL_FLOW_OPS:\n node.attr[\"_lower_using_switch_merge\"].b = False\n\n for node in output_graph_def.node:\n disable_control_flow_lowering(node)\n\n if output_graph_def.library:\n for func in output_graph_def.library.function:\n for node in func.node_def:\n disable_control_flow_lowering(node)\n return output_graph_def\n\n\ndef _run_inline_graph_optimization(func, lower_control_flow):\n \"\"\"Apply function inline optimization to the graph.\n\n Returns the GraphDef after Grappler's function inlining optimization is\n applied. This optimization does not work on models with control flow.\n\n Args:\n func: ConcreteFunction.\n lower_control_flow: Boolean indicating whether or not to lower control flow\n ops such as If and While. (default True)\n\n Returns:\n GraphDef\n \"\"\"\n graph_def = func.graph.as_graph_def()\n if not lower_control_flow:\n graph_def = disable_lower_using_switch_merge(graph_def)\n\n # In some cases, a secondary implementation of the function (e.g. for GPU) is\n # written to the \"api_implements\" attribute. (e.g. `tf.keras.layers.LSTM` in\n # TF2 produces a CuDNN-based RNN for GPU).\n # This function suppose to inline all functions calls, but \"api_implements\"\n # prevents this from happening. Removing the attribute solves the problem.\n # To learn more about \"api_implements\", see:\n # tensorflow/core/grappler/optimizers/implementation_selector.h\n for function in graph_def.library.function:\n if \"api_implements\" in function.attr:\n del function.attr[\"api_implements\"]\n\n meta_graph = export_meta_graph(graph_def=graph_def, graph=func.graph)\n\n # Clear the initializer_name for the variables collections, since they are not\n # needed after saved to saved_model.\n for name in [\n \"variables\", \"model_variables\", \"trainable_variables\", \"local_variables\"\n ]:\n raw_list = []\n for raw in meta_graph.collection_def[\"variables\"].bytes_list.value:\n variable = variable_pb2.VariableDef()\n variable.ParseFromString(raw)\n variable.ClearField(\"initializer_name\")\n raw_list.append(variable.SerializeToString())\n meta_graph.collection_def[name].bytes_list.value[:] = raw_list\n\n # Add a collection 'train_op' so that Grappler knows the outputs.\n fetch_collection = meta_graph_pb2.CollectionDef()\n for array in func.inputs + func.outputs:\n fetch_collection.node_list.value.append(array.name)\n meta_graph.collection_def[\"train_op\"].CopyFrom(fetch_collection)\n\n # Initialize RewriterConfig with everything disabled except function inlining.\n config = config_pb2.ConfigProto()\n rewrite_options = config.graph_options.rewrite_options\n rewrite_options.min_graph_nodes = -1 # do not skip small graphs\n rewrite_options.optimizers.append(\"function\")\n return tf_optimizer.OptimizeGraph(config, meta_graph)\n\n\ndef _get_tensor_name(name):\n \"\"\"Returns the name of the input tensor.\n\n Args:\n name: str\n\n Returns:\n str\n \"\"\"\n return name.split(\":\")[0]\n\n\ndef _get_new_function_name(name):\n \"\"\"Returns the function name with '_frozen' appended.\n\n Args:\n name: str\n\n Returns:\n str\n \"\"\"\n return name + \"_frozen\"\n\n\ndef _get_node_defs_list(graph_def):\n \"\"\"Returns a list of NodeDefs in the GraphDef.\n\n This list consists of all NodeDefs in the main graph as well as all control\n flow NodeDefs in the functions.\n\n The remaining NodeDefs in the functions are not included because the op names\n are not unique and the variables are handled differently than the main graph.\n The control flow ops need to be extracted because they are need their\n attributes to be updated similar to the control flow ops in the main graph.\n\n Args:\n graph_def: GraphDef proto.\n\n Returns:\n [NodeDef]\n \"\"\"\n node_defs = list(graph_def.node)\n\n if graph_def.library:\n for func in graph_def.library.function:\n node_defs.extend(\n [node for node in func.node_def if node.op in _CONTROL_FLOW_OPS])\n return node_defs\n\n\ndef _get_tensor_data(func):\n \"\"\"Gets the tensor data for all Placeholders in the model.\n\n Returns a dictionary that maps the tensor name to a dictionary containing:\n data: numpy data\n index: int index in func.graph.captures\n is_variable: bool indicating whether the tensor is a variable or not\n\n Args:\n func: ConcreteFunction.\n\n Returns:\n Dict\n \"\"\"\n tensor_data = {}\n map_index_to_variable = {}\n for var in func.graph.variables:\n for idx, captured_input in enumerate(func.captured_inputs):\n if var.handle is captured_input: # pylint: disable=protected-access\n map_index_to_variable[idx] = var\n break\n\n # Iterates through all captures which are represented as Placeholders.\n for idx, (val_tensor, name_tensor) in enumerate(func.graph.captures):\n tensor_name = _get_tensor_name(name_tensor.name)\n is_variable = idx in map_index_to_variable\n if is_variable:\n data = map_index_to_variable[idx].numpy()\n else:\n data = val_tensor.numpy()\n tensor_data[tensor_name] = {\n \"data\": data,\n \"index\": idx,\n \"is_variable\": is_variable,\n }\n return tensor_data\n\n\ndef _get_control_flow_function_data(node_defs, tensor_data, name_to_node):\n \"\"\"Gets the types and shapes for the parameters to the function.\n\n Creates a map from function name to a list of types and a list of shapes that\n correspond with the function arguments. The data is primarily determined from\n the corresponding \"If\" or \"While\" op. If the argument is a resource variable,\n then the type is determined from the type of the data contained within the\n Tensor. The shape data is only determined in the case of the \"While\" op.\n\n `is_also_output_type` is used to identify the \"While\" bodies that require the\n output types to be updated at the same time the input types are updated.\n\n Args:\n node_defs: List of NodeDefs.\n tensor_data: {str name : Tensor}.\n name_to_node: Dictionary mapping node name to node object.\n\n Returns:\n {str function name : {\"types\" : [int representing DataType],\n \"shapes\" : [[int] representing TensorShape]],\n \"is_also_output_type\" : bool}\n \"\"\"\n func_data = {}\n\n def get_source_node_name_through_identities(node_name):\n # Trace the source node along with a chain of Identity nodes.\n # For example, given Plaecholder -> Identity -> Identity -> node_name\n # The function will return the name of the Placeholder.\n while name_to_node[node_name].op == \"Identity\":\n node_name = _get_tensor_name(name_to_node[node_name].input[0])\n return node_name\n\n def get_resource_type(node_name):\n node_name = get_source_node_name_through_identities(node_name)\n\n numpy_type = tensor_data[node_name][\"data\"].dtype\n return dtypes.as_dtype(numpy_type).as_datatype_enum\n\n def get_resource_shape(node_name):\n node_name = get_source_node_name_through_identities(node_name)\n\n return tensor_shape_pb2.TensorShapeProto(dim=[\n tensor_shape_pb2.TensorShapeProto.Dim(size=dim)\n for dim in tensor_data[node_name][\"data\"].shape\n ])\n\n def add_value(func_name, arg_types, output_shapes, is_also_output_type):\n func_data[func_name] = {\n \"types\": arg_types,\n \"shapes\": output_shapes,\n \"is_also_output_type\": is_also_output_type\n }\n\n for node in node_defs:\n if node.op in _CONDITIONAL_OPS:\n arg_types = [dtype for dtype in node.attr[\"Tin\"].list.type]\n\n for idx in range(len(arg_types)):\n if arg_types[idx] == dtypes.resource:\n # Skip first index which represents the condition.\n arg_types[idx] = get_resource_type(node.input[idx + 1])\n\n add_value(node.attr[\"then_branch\"].func.name, arg_types, None, False)\n add_value(node.attr[\"else_branch\"].func.name, arg_types, None, False)\n elif node.op in _LOOP_OPS:\n arg_types = [dtype for dtype in node.attr[\"T\"].list.type]\n output_shapes = [shape for shape in node.attr[\"output_shapes\"].list.shape]\n\n for idx in range(len(arg_types)):\n if arg_types[idx] == dtypes.resource:\n input_name = node.input[idx]\n arg_types[idx] = get_resource_type(input_name)\n output_shapes[idx] = get_resource_shape(input_name)\n\n add_value(node.attr[\"body\"].func.name, arg_types, output_shapes, True)\n add_value(node.attr[\"cond\"].func.name, arg_types, output_shapes, False)\n return func_data\n\n\ndef _populate_const_op(output_node, node_name, dtype, data, data_shape):\n \"\"\"Creates a Const op.\n\n Args:\n output_node: TensorFlow NodeDef.\n node_name: str node name.\n dtype: AttrValue with a populated .type field.\n data: numpy data value.\n data_shape: Tuple of integers containing data shape.\n \"\"\"\n output_node.op = \"Const\"\n output_node.name = node_name\n output_node.attr[\"dtype\"].CopyFrom(dtype)\n tensor = tensor_util.make_tensor_proto(\n data, dtype=dtype.type, shape=data_shape)\n output_node.attr[\"value\"].tensor.CopyFrom(tensor)\n\n\ndef _populate_identity_op(output_node, input_node):\n \"\"\"Creates an Identity op from a ReadVariable op.\n\n Args:\n output_node: TensorFlow NodeDef.\n input_node: TensorFlow NodeDef.\n \"\"\"\n output_node.op = \"Identity\"\n output_node.name = input_node.name\n output_node.input.append(input_node.input[0])\n output_node.attr[\"T\"].CopyFrom(input_node.attr[\"dtype\"])\n if \"_class\" in input_node.attr:\n output_node.attr[\"_class\"].CopyFrom(input_node.attr[\"_class\"])\n\n\ndef _populate_if_op(output_node, input_node, function_data):\n \"\"\"Updates the type attributes and function names of If or StatelessIf.\n\n Args:\n output_node: TensorFlow NodeDef.\n input_node: TensorFlow NodeDef.\n function_data: Map of function names to the list of types and shapes that\n correspond with the function arguments.\n \"\"\"\n output_node.CopyFrom(input_node)\n then_func = input_node.attr[\"then_branch\"].func.name\n output_node.attr[\"then_branch\"].func.name = _get_new_function_name(then_func)\n output_node.attr[\"else_branch\"].func.name = _get_new_function_name(\n input_node.attr[\"else_branch\"].func.name)\n output_node.attr[\"Tin\"].list.CopyFrom(\n attr_value_pb2.AttrValue.ListValue(\n type=function_data[then_func][\"types\"]))\n\n\ndef _populate_while_op(output_node, input_node, function_data):\n \"\"\"Updates the type attributes and function names of While or StatelessWhile.\n\n Args:\n output_node: TensorFlow NodeDef.\n input_node: TensorFlow NodeDef.\n function_data: Map of function names to the list of types and shapes that\n correspond with the function arguments.\n \"\"\"\n output_node.CopyFrom(input_node)\n cond_func = input_node.attr[\"cond\"].func.name\n output_node.attr[\"cond\"].func.name = _get_new_function_name(cond_func)\n output_node.attr[\"body\"].func.name = _get_new_function_name(\n input_node.attr[\"body\"].func.name)\n output_node.attr[\"T\"].list.CopyFrom(\n attr_value_pb2.AttrValue.ListValue(\n type=function_data[cond_func][\"types\"]))\n output_node.attr[\"output_shapes\"].list.CopyFrom(\n attr_value_pb2.AttrValue.ListValue(\n shape=function_data[cond_func][\"shapes\"]))\n\n\ndef _construct_concrete_function(func, output_graph_def,\n converted_input_indices):\n \"\"\"Constructs a concrete function from the `output_graph_def`.\n\n Args:\n func: ConcreteFunction\n output_graph_def: GraphDef proto.\n converted_input_indices: Set of integers of input indices that were\n converted to constants.\n\n Returns:\n ConcreteFunction.\n \"\"\"\n # Create a ConcreteFunction from the new GraphDef.\n input_tensors = func.graph.internal_captures\n converted_inputs = object_identity.ObjectIdentitySet(\n [input_tensors[index] for index in converted_input_indices])\n not_converted_inputs = [\n tensor for tensor in func.inputs if tensor not in converted_inputs]\n not_converted_inputs_map = {\n tensor.name: tensor for tensor in not_converted_inputs\n }\n\n new_input_names = [tensor.name for tensor in not_converted_inputs]\n new_output_names = [tensor.name for tensor in func.outputs]\n new_func = wrap_function.function_from_graph_def(output_graph_def,\n new_input_names,\n new_output_names)\n\n # Manually propagate shape for input tensors where the shape is not correctly\n # propagated. Scalars shapes are lost when wrapping the function.\n for input_tensor in new_func.inputs:\n input_tensor.set_shape(not_converted_inputs_map[input_tensor.name].shape)\n return new_func\n\n\ndef convert_variables_to_constants_v2(func, lower_control_flow=True):\n \"\"\"Replaces all the variables in a graph with constants of the same values.\n\n TensorFlow 2.0 function for converting all Variable ops into Const ops holding\n the same values. This makes it possible to describe the network fully with a\n single GraphDef file, and allows the removal of a lot of ops related to\n loading and saving the variables. This function runs Grappler's function\n inlining optimization in order to return a single subgraph.\n\n The current implementation only works for graphs that do not contain any\n control flow or embedding related ops.\n\n Args:\n func: ConcreteFunction.\n lower_control_flow: Boolean indicating whether or not to lower control flow\n ops such as If and While. (default True)\n\n Returns:\n ConcreteFunction containing a simplified version of the original.\n \"\"\"\n # Inline the graph in order to remove functions when possible.\n graph_def = _run_inline_graph_optimization(func, lower_control_flow)\n\n # Gets list of all node defs include those in the library.\n node_defs = _get_node_defs_list(graph_def)\n\n # Get mapping from node name to node.\n name_to_node = {_get_tensor_name(node.name): node for node in node_defs}\n\n # Get mapping from node name to variable value.\n tensor_data = _get_tensor_data(func)\n\n # Get mapping from function name to argument types.\n function_data = _get_control_flow_function_data(\n node_defs, tensor_data, name_to_node)\n\n # Get variable data for all nodes in `node_defs`.\n reference_variables = {}\n resource_identities = {}\n placeholders = {}\n converted_input_indices = set()\n\n def _save_placeholder(node_name, dtype):\n placeholders[node_name] = {\n \"dtype\": dtype,\n \"data\": tensor_data[node_name][\"data\"],\n }\n converted_input_indices.add(tensor_data[node_name][\"index\"])\n\n for node in node_defs:\n if node.op in _CONDITIONAL_OPS:\n # Get dtype and data for resource Placeholders.\n then_func = node.attr[\"then_branch\"].func.name\n arg_types = function_data[then_func][\"types\"]\n for idx, input_tensor in enumerate(node.input[1:]):\n input_name = _get_tensor_name(input_tensor)\n if input_name in tensor_data:\n dtype = attr_value_pb2.AttrValue(type=arg_types[idx])\n _save_placeholder(_get_tensor_name(input_tensor), dtype)\n elif node.op in _LOOP_OPS:\n # Get dtype and data for resource Placeholders.\n cond_func = node.attr[\"cond\"].func.name\n arg_types = function_data[cond_func][\"types\"]\n for idx, input_tensor in enumerate(node.input):\n input_name = _get_tensor_name(input_tensor)\n if input_name in tensor_data:\n dtype = attr_value_pb2.AttrValue(type=arg_types[idx])\n _save_placeholder(_get_tensor_name(input_tensor), dtype)\n elif (node.op == \"Identity\" and node.attr[\"T\"].type == dtypes.resource and\n name_to_node[_get_tensor_name(node.input[0])].op in _LOOP_OPS):\n # Store the dtype for Identity resource ops that are outputs of While ops.\n while_node = name_to_node[_get_tensor_name(node.input[0])]\n body_func = while_node.attr[\"body\"].func.name\n input_data = node.input[0].split(\":\")\n idx = 0 if len(input_data) == 1 else int(input_data[1])\n\n dtype = attr_value_pb2.AttrValue(\n type=function_data[body_func][\"types\"][idx])\n resource_identities[node.name] = dtype\n elif node.op == \"VariableV2\":\n # Get data for VariableV2 ops (reference variables) that cannot be lifted.\n with func.graph.as_default():\n identity_node = array_ops.identity(\n func.graph.as_graph_element(node.name + \":0\"))\n reference_variables[node.name] = (\n func.prune([], [identity_node.name])()[0])\n elif node.name in tensor_data and not tensor_data[node.name][\"is_variable\"]:\n # Get dtype and data for non-variable Placeholders (ex. values for 1.X\n # Const ops that are loaded as Placeholders in 2.0)\n _save_placeholder(node.name, node.attr[\"dtype\"])\n elif node.op in [\"ReadVariableOp\", \"ResourceGather\", \"ResourceGatherNd\", \"AssignSubVariableOp\"]:\n # Get dtype and data for Placeholder ops associated with ReadVariableOp\n # and ResourceGather ops. There can be an Identity in between the\n # resource op and Placeholder. Store the dtype for the Identity ops.\n input_name = _get_tensor_name(node.input[0])\n while name_to_node[input_name].op == \"Identity\":\n resource_identities[input_name] = node.attr[\"dtype\"]\n input_name = _get_tensor_name(name_to_node[input_name].input[0])\n if name_to_node[input_name].op != \"Placeholder\":\n raise ValueError(\"Cannot find the Placeholder op that is an input \"\n \"to the ReadVariableOp.\")\n _save_placeholder(input_name, node.attr[\"dtype\"])\n\n # Reconstruct the graph with constants in place of variables.\n output_graph_def = graph_pb2.GraphDef()\n\n for input_node in graph_def.node:\n output_node = output_graph_def.node.add()\n # Convert VariableV2 ops to Const ops.\n if input_node.name in reference_variables:\n data = reference_variables[input_node.name]\n dtype = attr_value_pb2.AttrValue(type=data.dtype.as_datatype_enum)\n _populate_const_op(output_node, input_node.name, dtype, data.numpy(),\n data.shape)\n # Convert Placeholder ops to Const ops.\n elif input_node.name in placeholders:\n data = placeholders[input_node.name][\"data\"]\n dtype = placeholders[input_node.name][\"dtype\"]\n _populate_const_op(output_node, input_node.name, dtype, data, data.shape)\n # Update the dtype for Identity ops that are inputs to ReadVariableOps.\n elif input_node.name in resource_identities:\n output_node.CopyFrom(input_node)\n output_node.attr[\"T\"].CopyFrom(resource_identities[input_node.name])\n # Convert ReadVariableOps to Identity ops.\n elif input_node.op == \"ReadVariableOp\":\n _populate_identity_op(output_node, input_node)\n # Convert ResourceGather to Gather ops with a Const axis feeding into it.\n elif input_node.op == \"AssignSubVariableOp\":\n output_node.op = \"Sub\"\n output_node.name = input_node.name\n output_node.input.extend(input_node.input)\n output_node.attr[\"T\"].CopyFrom(input_node.attr[\"dtype\"])\n if \"_class\" in input_node.attr:\n output_node.attr[\"_class\"].CopyFrom(input_node.attr[\"_class\"])\n elif input_node.op == \"ResourceGather\":\n if input_node.attr[\"batch_dims\"].i != 0:\n raise ValueError(\"batch_dims != 0 is not supported by freeze_graph.\")\n output_axis_node = output_graph_def.node.add()\n axis_node_name = input_node.name + \"/axis\"\n axis_dtype = input_node.attr[\"Tindices\"]\n axis_data = np.array(input_node.attr[\"batch_dims\"].i)\n _populate_const_op(output_axis_node, axis_node_name, axis_dtype,\n axis_data, axis_data.shape)\n\n output_node.op = \"GatherV2\"\n output_node.name = input_node.name\n output_node.input.extend(\n [input_node.input[0], input_node.input[1], axis_node_name])\n output_node.attr[\"Tparams\"].CopyFrom(input_node.attr[\"dtype\"])\n output_node.attr[\"Tindices\"].CopyFrom(input_node.attr[\"Tindices\"])\n output_node.attr[\"Taxis\"].CopyFrom(axis_dtype)\n if \"_class\" in input_node.attr:\n output_node.attr[\"_class\"].CopyFrom(input_node.attr[\"_class\"])\n elif input_node.op == \"ResourceGatherNd\":\n output_node.op = \"GatherNd\"\n output_node.name = input_node.name\n output_node.input.extend(\n [input_node.input[0], input_node.input[1]])\n output_node.attr[\"Tparams\"].CopyFrom(input_node.attr[\"dtype\"])\n output_node.attr[\"Tindices\"].CopyFrom(input_node.attr[\"Tindices\"])\n if \"_class\" in input_node.attr:\n output_node.attr[\"_class\"].CopyFrom(input_node.attr[\"_class\"])\n # Update the function names and argument types for the conditional ops.\n elif input_node.op in _CONDITIONAL_OPS:\n _populate_if_op(output_node, input_node, function_data)\n elif input_node.op in _LOOP_OPS:\n _populate_while_op(output_node, input_node, function_data)\n else:\n output_node.CopyFrom(input_node)\n\n # Add functions to reconstructed graph.\n if graph_def.library:\n library = output_graph_def.library\n\n for input_library_func in graph_def.library.function:\n orig_func_name = input_library_func.signature.name\n new_func_name = _get_new_function_name(orig_func_name)\n\n # Do not copy any functions that aren't being used in the graph. Any\n # functions that are not used by control flow should have been inlined.\n if orig_func_name not in function_data:\n continue\n\n output_library_func = library.function.add()\n for key, value in input_library_func.ret.items():\n output_library_func.ret[key] = value\n for key, value in input_library_func.control_ret.items():\n output_library_func.control_ret[key] = value\n\n # Update the input types in the function signature. Update the output\n # types for functions that are while loop bodies.\n output_library_func.signature.CopyFrom(input_library_func.signature)\n output_library_func.signature.name = new_func_name\n for dtype, arg in zip(function_data[orig_func_name][\"types\"],\n output_library_func.signature.input_arg):\n arg.type = dtype\n if function_data[orig_func_name][\"is_also_output_type\"]:\n for dtype, arg in zip(function_data[orig_func_name][\"types\"],\n output_library_func.signature.output_arg):\n arg.type = dtype\n\n # Update the NodeDefs.\n func_variables = {\n node.name: node.input[0]\n for node in input_library_func.node_def\n if node.op in [\"ReadVariableOp\", \"AssignSubVariableOp\"]\n }\n\n for input_node in input_library_func.node_def:\n output_node = output_library_func.node_def.add()\n # Convert ReadVariableOps to Identity ops.\n if input_node.op == \"ReadVariableOp\":\n _populate_identity_op(output_node, input_node)\n # Update the function names and argument types for the conditional ops.\n elif input_node.op in _CONDITIONAL_OPS:\n _populate_if_op(output_node, input_node, function_data)\n elif input_node.op in _LOOP_OPS:\n _populate_while_op(output_node, input_node, function_data)\n else:\n output_node.CopyFrom(input_node)\n # Convert :value to :output for ops that use the ReadVariableOp.\n for idx, full_name in enumerate(input_node.input):\n input_name = _get_tensor_name(full_name)\n if input_name in func_variables:\n full_name_parts = full_name.split(\":\")\n full_name_parts[1] = \"output\"\n input_name = \":\".join(full_name_parts)\n output_node.input[idx] = input_name\n\n output_graph_def.versions.CopyFrom(graph_def.versions)\n return output_graph_def, converted_input_indices\n",
"###############################################################################\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n###############################################################################\n\nfrom ..proto import keras\nfrom ..proto.tfcompat import tensorflow as tf\nfrom ..common.onnx_ops import apply_relu_6, apply_softmax\nfrom .activation import activation_map\nfrom onnx.mapping import TENSOR_TYPE_TO_NP_TYPE\nimport numpy as np\nactivation_get = keras.activations.get\n\n\ndef get_permutation_config(n_dims):\n input_perm_axes = [0, n_dims + 1] + list(range(1, n_dims + 1))\n output_perm_axes = [0] + list(range(2, n_dims + 2)) + [1]\n return input_perm_axes, output_perm_axes\n\n\ndef activation_process(scope, operator, container, biased_tensor_name):\n # Create an activation function node and apply activation function to the intermediate tensor\n apply_activation_function = activation_map[operator.raw_operator.activation]\n if operator.raw_operator.activation in [activation_get('softmax'), keras.activations.softmax]:\n apply_softmax(scope, biased_tensor_name, operator.outputs[0].full_name, container, axis=-1)\n elif operator.raw_operator.activation in [tf.nn.relu6]:\n np_type = TENSOR_TYPE_TO_NP_TYPE[operator.inputs[0].type.to_onnx_type().tensor_type.elem_type]\n zero_value = np.zeros(shape=(1,), dtype=np_type)\n apply_relu_6(scope, biased_tensor_name, operator.outputs[0].full_name, container,\n zero_value=zero_value)\n else:\n apply_activation_function(scope, biased_tensor_name, operator.outputs[0].full_name, container)\n",
"###############################################################################\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n###############################################################################\nimport os\nimport sys\nimport unittest\nimport keras2onnx\nimport numpy as np\nfrom keras2onnx.proto import keras, is_tf_keras\nfrom os.path import dirname, abspath\nsys.path.insert(0, os.path.join(dirname(abspath(__file__)), '../../tests/'))\nfrom test_utils import run_onnx_runtime\n\nActivation = keras.layers.Activation\nBatchNormalization = keras.layers.BatchNormalization\nConv2D = keras.layers.Conv2D\nDense = keras.layers.Dense\nDropout = keras.layers.Dropout\nEmbedding = keras.layers.Embedding\nFlatten = keras.layers.Flatten\nInput = keras.layers.Input\nLeakyReLU = keras.layers.LeakyReLU\nmultiply = keras.layers.multiply\nReshape = keras.layers.Reshape\nUpSampling2D = keras.layers.UpSampling2D\nZeroPadding2D = keras.layers.ZeroPadding2D\n\nSequential = keras.models.Sequential\nModel = keras.models.Model\n\n# From https://github.com/eriklindernoren/Keras-GAN/blob/master/bgan/bgan.py\nclass BGAN():\n \"\"\"Reference: https://wiseodd.github.io/techblog/2017/03/07/boundary-seeking-gan/\"\"\"\n def __init__(self):\n self.img_rows = 28\n self.img_cols = 28\n self.channels = 1\n self.img_shape = (self.img_rows, self.img_cols, self.channels)\n self.latent_dim = 100\n\n # Build and compile the discriminator\n self.discriminator = self.build_discriminator()\n\n # Build the generator\n self.generator = self.build_generator()\n\n # The generator takes noise as input and generated imgs\n z = Input(shape=(self.latent_dim,))\n img = self.generator(z)\n\n # For the combined model we will only train the generator\n self.discriminator.trainable = False\n\n # The valid takes generated images as input and determines validity\n valid = self.discriminator(img)\n\n # The combined model (stacked generator and discriminator)\n # Trains the generator to fool the discriminator\n self.combined = Model(z, valid)\n\n def build_generator(self):\n\n model = Sequential()\n\n model.add(Dense(256, input_dim=self.latent_dim))\n model.add(LeakyReLU(alpha=0.2))\n model.add(BatchNormalization(momentum=0.8))\n model.add(Dense(512))\n model.add(LeakyReLU(alpha=0.2))\n model.add(BatchNormalization(momentum=0.8))\n model.add(Dense(1024))\n model.add(LeakyReLU(alpha=0.2))\n model.add(BatchNormalization(momentum=0.8))\n model.add(Dense(np.prod(self.img_shape), activation='tanh'))\n model.add(Reshape(self.img_shape))\n\n noise = Input(shape=(self.latent_dim,))\n img = model(noise)\n\n return Model(noise, img)\n\n def build_discriminator(self):\n\n model = Sequential()\n\n model.add(Flatten(input_shape=self.img_shape))\n model.add(Dense(512))\n model.add(LeakyReLU(alpha=0.2))\n model.add(Dense(256))\n model.add(LeakyReLU(alpha=0.2))\n model.add(Dense(1, activation='sigmoid'))\n\n img = Input(shape=self.img_shape)\n validity = model(img)\n\n return Model(img, validity)\n\nclass TestBGAN(unittest.TestCase):\n\n def setUp(self):\n self.model_files = []\n\n def tearDown(self):\n for fl in self.model_files:\n os.remove(fl)\n\n def test_BGAN(self):\n keras_model = BGAN().combined\n x = np.random.rand(5, 100).astype(np.float32)\n expected = keras_model.predict(x)\n onnx_model = keras2onnx.convert_keras(keras_model, keras_model.name)\n self.assertTrue(run_onnx_runtime(onnx_model.graph.name, onnx_model, x, expected, self.model_files))\n\n\nif __name__ == \"__main__\":\n unittest.main()\n"
] | [
[
"numpy.random.rand",
"numpy.prod"
],
[
"tensorflow.__version__.split",
"numpy.random.rand",
"numpy.prod"
],
[
"tensorflow.python.grappler.tf_optimizer.OptimizeGraph",
"tensorflow.core.framework.tensor_shape_pb2.TensorShapeProto.Dim",
"tensorflow.python.util.object_identity.ObjectIdentitySet",
"tensorflow.python.eager.wrap_function.function_from_graph_def",
"tensorflow.python.framework.dtypes.as_dtype",
"tensorflow.core.framework.attr_value_pb2.AttrValue.ListValue",
"tensorflow.python.framework.tensor_util.make_tensor_proto",
"tensorflow.core.protobuf.config_pb2.ConfigProto",
"tensorflow.core.framework.attr_value_pb2.AttrValue",
"tensorflow.python.training.saver.export_meta_graph",
"numpy.array",
"tensorflow.core.framework.variable_pb2.VariableDef",
"tensorflow.core.protobuf.meta_graph_pb2.CollectionDef",
"tensorflow.core.framework.graph_pb2.GraphDef"
],
[
"numpy.zeros"
],
[
"numpy.random.rand",
"numpy.prod"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Izecson/sockeye-1.16.6 | [
"f84044d4a64b2bcf744ccd4f94b16f8133d1f383",
"f84044d4a64b2bcf744ccd4f94b16f8133d1f383",
"f84044d4a64b2bcf744ccd4f94b16f8133d1f383"
] | [
"test/unit/test_attention.py",
"test/unit/test_data_io.py",
"sockeye/transformer.py"
] | [
"# Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may not\n# use this file except in compliance with the License. A copy of the License\n# is located at\n#\n# http://aws.amazon.com/apache2.0/\n# \n# or in the \"license\" file accompanying this file. This file is distributed on\n# an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n\nimport mxnet as mx\nimport numpy as np\nimport pytest\n\nimport sockeye.constants as C\nimport sockeye.coverage\nimport sockeye.rnn_attention\nfrom test.common import gaussian_vector, integer_vector\n\nattention_types = [C.ATT_BILINEAR, C.ATT_DOT, C.ATT_DOT_SCALED, C.ATT_LOC, C.ATT_MLP]\n\n\[email protected](\"attention_type\", attention_types)\ndef test_attention(attention_type,\n batch_size=1,\n encoder_num_hidden=2,\n decoder_num_hidden=2):\n # source: (batch_size, seq_len, encoder_num_hidden)\n source = mx.sym.Variable(\"source\")\n # source_length: (batch_size,)\n source_length = mx.sym.Variable(\"source_length\")\n source_seq_len = 3\n\n config_attention = sockeye.rnn_attention.AttentionConfig(type=attention_type,\n num_hidden=2,\n input_previous_word=False,\n source_num_hidden=2,\n query_num_hidden=2,\n layer_normalization=False,\n config_coverage=None)\n attention = sockeye.rnn_attention.get_attention(config_attention, max_seq_len=source_seq_len)\n\n attention_state = attention.get_initial_state(source_length, source_seq_len)\n attention_func = attention.on(source, source_length, source_seq_len)\n attention_input = attention.make_input(0, mx.sym.Variable(\"word_vec_prev\"), mx.sym.Variable(\"decoder_state\"))\n attention_state = attention_func(attention_input, attention_state)\n sym = mx.sym.Group([attention_state.context, attention_state.probs])\n\n executor = sym.simple_bind(ctx=mx.cpu(),\n source=(batch_size, source_seq_len, encoder_num_hidden),\n source_length=(batch_size,),\n decoder_state=(batch_size, decoder_num_hidden))\n\n # TODO: test for other inputs (that are not equal at each source position)\n executor.arg_dict[\"source\"][:] = np.asarray([[[1., 2.], [1., 2.], [3., 4.]]])\n executor.arg_dict[\"source_length\"][:] = np.asarray([2.0])\n executor.arg_dict[\"decoder_state\"][:] = np.asarray([[5, 6]])\n exec_output = executor.forward()\n context_result = exec_output[0].asnumpy()\n attention_prob_result = exec_output[1].asnumpy()\n\n # expecting uniform attention_weights of 0.5: 0.5 * seq1 + 0.5 * seq2\n assert np.isclose(context_result, np.asarray([[1., 2.]])).all()\n # equal attention to first two and no attention to third\n assert np.isclose(attention_prob_result, np.asarray([[0.5, 0.5, 0.]])).all()\n\n\ncoverage_cases = [(\"gru\", 10), (\"tanh\", 4), (\"count\", 1), (\"sigmoid\", 1), (\"relu\", 30)]\n\n\[email protected](\"attention_coverage_type,attention_coverage_num_hidden\", coverage_cases)\ndef test_coverage_attention(attention_coverage_type,\n attention_coverage_num_hidden,\n batch_size=3,\n encoder_num_hidden=2,\n decoder_num_hidden=2):\n # source: (batch_size, seq_len, encoder_num_hidden)\n source = mx.sym.Variable(\"source\")\n # source_length: (batch_size, )\n source_length = mx.sym.Variable(\"source_length\")\n source_seq_len = 10\n\n config_coverage = sockeye.coverage.CoverageConfig(type=attention_coverage_type,\n num_hidden=attention_coverage_num_hidden,\n layer_normalization=False)\n config_attention = sockeye.rnn_attention.AttentionConfig(type=\"coverage\",\n num_hidden=5,\n input_previous_word=False,\n source_num_hidden=encoder_num_hidden,\n query_num_hidden=decoder_num_hidden,\n layer_normalization=False,\n config_coverage=config_coverage)\n attention = sockeye.rnn_attention.get_attention(config_attention, max_seq_len=source_seq_len)\n\n attention_state = attention.get_initial_state(source_length, source_seq_len)\n attention_func = attention.on(source, source_length, source_seq_len)\n attention_input = attention.make_input(0, mx.sym.Variable(\"word_vec_prev\"), mx.sym.Variable(\"decoder_state\"))\n attention_state = attention_func(attention_input, attention_state)\n sym = mx.sym.Group([attention_state.context, attention_state.probs, attention_state.dynamic_source])\n\n source_shape = (batch_size, source_seq_len, encoder_num_hidden)\n source_length_shape = (batch_size,)\n decoder_state_shape = (batch_size, decoder_num_hidden)\n\n executor = sym.simple_bind(ctx=mx.cpu(),\n source=source_shape,\n source_length=source_length_shape,\n decoder_state=decoder_state_shape)\n\n source_length_vector = integer_vector(shape=source_length_shape, max_value=source_seq_len)\n executor.arg_dict[\"source\"][:] = gaussian_vector(shape=source_shape)\n executor.arg_dict[\"source_length\"][:] = source_length_vector\n executor.arg_dict[\"decoder_state\"][:] = gaussian_vector(shape=decoder_state_shape)\n exec_output = executor.forward()\n context_result = exec_output[0].asnumpy()\n attention_prob_result = exec_output[1].asnumpy()\n dynamic_source_result = exec_output[2].asnumpy()\n\n expected_probs = (1. / source_length_vector).reshape((batch_size, 1))\n\n assert context_result.shape == (batch_size, encoder_num_hidden)\n assert attention_prob_result.shape == (batch_size, source_seq_len)\n assert dynamic_source_result.shape == (batch_size, source_seq_len, attention_coverage_num_hidden)\n assert (np.sum(np.isclose(attention_prob_result, expected_probs), axis=1) == source_length_vector).all()\n\n\ndef test_last_state_attention(batch_size=1,\n encoder_num_hidden=2):\n \"\"\"\n EncoderLastStateAttention is a bit different from other attention mechanisms as it doesn't take a query argument\n and doesn't return a probability distribution over the inputs (aka alignment).\n \"\"\"\n # source: (batch_size, seq_len, encoder_num_hidden)\n source = mx.sym.Variable(\"source\")\n # source_length: (batch_size,)\n source_length = mx.sym.Variable(\"source_length\")\n source_seq_len = 3\n\n config_attention = sockeye.rnn_attention.AttentionConfig(type=\"fixed\",\n num_hidden=0,\n input_previous_word=False,\n source_num_hidden=2,\n query_num_hidden=2,\n layer_normalization=False,\n config_coverage=None)\n attention = sockeye.rnn_attention.get_attention(config_attention, max_seq_len=source_seq_len)\n\n attention_state = attention.get_initial_state(source_length, source_seq_len)\n attention_func = attention.on(source, source_length, source_seq_len)\n attention_input = attention.make_input(0, mx.sym.Variable(\"word_vec_prev\"), mx.sym.Variable(\"decoder_state\"))\n attention_state = attention_func(attention_input, attention_state)\n sym = mx.sym.Group([attention_state.context, attention_state.probs])\n\n executor = sym.simple_bind(ctx=mx.cpu(),\n source=(batch_size, source_seq_len, encoder_num_hidden),\n source_length=(batch_size,))\n\n # TODO: test for other inputs (that are not equal at each source position)\n executor.arg_dict[\"source\"][:] = np.asarray([[[1., 2.], [1., 2.], [3., 4.]]])\n executor.arg_dict[\"source_length\"][:] = np.asarray([2.0])\n exec_output = executor.forward()\n context_result = exec_output[0].asnumpy()\n attention_prob_result = exec_output[1].asnumpy()\n\n # expecting attention on last state based on source_length\n assert np.isclose(context_result, np.asarray([[1., 2.]])).all()\n assert np.isclose(attention_prob_result, np.asarray([[0., 1.0, 0.]])).all()\n\n\ndef test_get_context_and_attention_probs():\n source = mx.sym.Variable('source')\n source_length = mx.sym.Variable('source_length')\n attention_scores = mx.sym.Variable('scores')\n context, att_probs = sockeye.rnn_attention.get_context_and_attention_probs(source, source_length, attention_scores)\n sym = mx.sym.Group([context, att_probs])\n assert len(sym.list_arguments()) == 3\n\n batch_size, seq_len, num_hidden = 32, 50, 100\n\n # data\n source_nd = mx.nd.random_normal(shape=(batch_size, seq_len, num_hidden))\n source_length_np = np.random.randint(1, seq_len+1, (batch_size,))\n source_length_nd = mx.nd.array(source_length_np)\n scores_nd = mx.nd.zeros((batch_size, seq_len, 1))\n\n in_shapes, out_shapes, _ = sym.infer_shape(source=source_nd.shape,\n source_length=source_length_nd.shape,\n scores=scores_nd.shape)\n\n assert in_shapes == [(batch_size, seq_len, num_hidden), (batch_size, seq_len, 1), (batch_size,)]\n assert out_shapes == [(batch_size, num_hidden), (batch_size, seq_len)]\n\n context, probs = sym.eval(source=source_nd,\n source_length=source_length_nd,\n scores=scores_nd)\n\n expected_probs = (1. / source_length_nd).reshape((batch_size, 1)).asnumpy()\n assert (np.sum(np.isclose(probs.asnumpy(), expected_probs), axis=1) == source_length_np).all()\n",
"# Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may not\n# use this file except in compliance with the License. A copy of the License\n# is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on\n# an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n\nimport os\nimport random\nfrom tempfile import TemporaryDirectory\nfrom typing import Optional, List, Tuple\n\nimport mxnet as mx\nimport numpy as np\nimport pytest\n\nfrom sockeye import constants as C\nfrom sockeye import data_io\nfrom sockeye import vocab\nfrom sockeye.utils import SockeyeError, get_tokens, seedRNGs\nfrom test.common import tmp_digits_dataset\n\nseedRNGs(12)\n\ndefine_bucket_tests = [(50, 10, [10, 20, 30, 40, 50]),\n (50, 20, [20, 40, 50]),\n (50, 50, [50]),\n (5, 10, [5]),\n (11, 5, [5, 10, 11]),\n (19, 10, [10, 19])]\n\n\[email protected](\"max_seq_len, step, expected_buckets\", define_bucket_tests)\ndef test_define_buckets(max_seq_len, step, expected_buckets):\n buckets = data_io.define_buckets(max_seq_len, step=step)\n assert buckets == expected_buckets\n\n\ndefine_parallel_bucket_tests = [(50, 50, 10, 1.0, [(10, 10), (20, 20), (30, 30), (40, 40), (50, 50)]),\n (50, 50, 10, 0.5,\n [(10, 5), (20, 10), (30, 15), (40, 20), (50, 25), (50, 30), (50, 35), (50, 40),\n (50, 45), (50, 50)]),\n (10, 10, 10, 0.1,\n [(10, 2), (10, 3), (10, 4), (10, 5), (10, 6), (10, 7), (10, 8), (10, 9), (10, 10)]),\n (10, 5, 10, 0.01, [(10, 2), (10, 3), (10, 4), (10, 5)]),\n (50, 50, 10, 2.0,\n [(5, 10), (10, 20), (15, 30), (20, 40), (25, 50), (30, 50), (35, 50), (40, 50),\n (45, 50), (50, 50)]),\n (5, 10, 10, 10.0, [(2, 10), (3, 10), (4, 10), (5, 10)]),\n (5, 10, 10, 11.0, [(2, 10), (3, 10), (4, 10), (5, 10)]),\n (50, 50, 50, 0.5, [(50, 25), (50, 50)]),\n (50, 50, 50, 1.5, [(33, 50), (50, 50)]),\n (75, 75, 50, 1.5, [(33, 50), (66, 75), (75, 75)])]\n\n\[email protected](\"max_seq_len_source, max_seq_len_target, bucket_width, length_ratio, expected_buckets\",\n define_parallel_bucket_tests)\ndef test_define_parallel_buckets(max_seq_len_source, max_seq_len_target, bucket_width, length_ratio, expected_buckets):\n buckets = data_io.define_parallel_buckets(max_seq_len_source, max_seq_len_target, bucket_width=bucket_width,\n length_ratio=length_ratio)\n assert buckets == expected_buckets\n\n\nget_bucket_tests = [([10, 20, 30, 40, 50], 50, 50),\n ([10, 20, 30, 40, 50], 11, 20),\n ([10, 20, 30, 40, 50], 9, 10),\n ([10, 20, 30, 40, 50], 51, None),\n ([10, 20, 30, 40, 50], 1, 10),\n ([10, 20, 30, 40, 50], 0, 10),\n ([], 50, None)]\n\n\[email protected](\"buckets, length, expected_bucket\",\n get_bucket_tests)\ndef test_get_bucket(buckets, length, expected_bucket):\n bucket = data_io.get_bucket(length, buckets)\n assert bucket == expected_bucket\n\n\ntokens2ids_tests = [([\"a\", \"b\", \"c\"], {\"a\": 1, \"b\": 0, \"c\": 300, C.UNK_SYMBOL: 12}, [1, 0, 300]),\n ([\"a\", \"x\", \"c\"], {\"a\": 1, \"b\": 0, \"c\": 300, C.UNK_SYMBOL: 12}, [1, 12, 300])]\n\n\[email protected](\"tokens, vocab, expected_ids\", tokens2ids_tests)\ndef test_tokens2ids(tokens, vocab, expected_ids):\n ids = data_io.tokens2ids(tokens, vocab)\n assert ids == expected_ids\n\n\[email protected](\"tokens, expected_ids\", [([\"1\", \"2\", \"3\", \"0\"], [1, 2, 3, 0]), ([], [])])\ndef test_strids2ids(tokens, expected_ids):\n ids = data_io.strids2ids(tokens)\n assert ids == expected_ids\n\n\[email protected](\"ids, expected_string\", [([1, 2, 3, 0], \"1 2 3 0\"), ([], \"\")])\ndef test_ids2strids(ids, expected_string):\n string = data_io.ids2strids(ids)\n assert string == expected_string\n\n\nsequence_reader_tests = [([\"1 2 3\", \"2\", \"14\", \"2 2 2\"], False, False),\n ([\"a b c\", \"c\"], True, False),\n ([\"a b c\", \"c\"], True, True)]\n\n\[email protected](\"sequences, use_vocab, add_bos\", sequence_reader_tests)\ndef test_sequence_reader(sequences, use_vocab, add_bos):\n with TemporaryDirectory() as work_dir:\n path = os.path.join(work_dir, 'input')\n with open(path, 'w') as f:\n for sequence in sequences:\n f.write(sequence + \"\\n\")\n\n vocabulary = vocab.build_vocab(sequences) if use_vocab else None\n\n reader = data_io.SequenceReader(path, vocab=vocabulary, add_bos=add_bos)\n\n read_sequences = [s for s in reader]\n assert reader.is_done()\n assert len(read_sequences) == reader.count\n\n if vocabulary is None:\n with pytest.raises(SockeyeError) as e:\n _ = data_io.SequenceReader(path, vocab=vocabulary, add_bos=True)\n assert str(e.value) == \"Adding a BOS symbol requires a vocabulary\"\n\n expected_sequences = [data_io.strids2ids(get_tokens(s)) for s in sequences]\n assert read_sequences == expected_sequences\n else:\n expected_sequences = [data_io.tokens2ids(get_tokens(s), vocabulary) for s in sequences]\n if add_bos:\n expected_sequences = [[vocabulary[C.BOS_SYMBOL]] + s for s in expected_sequences]\n assert read_sequences == expected_sequences\n\n # check raise for multiple concurrent iters\n _ = iter(reader)\n with pytest.raises(SockeyeError) as e:\n iter(reader)\n assert str(e.value) == \"Can not iterate multiple times simultaneously.\"\n\n\ndef test_sample_based_define_bucket_batch_sizes():\n batch_by_words = False\n batch_size = 32\n max_seq_len = 100\n buckets = data_io.define_parallel_buckets(max_seq_len, max_seq_len, 10, 1.5)\n bucket_batch_sizes = data_io.define_bucket_batch_sizes(buckets=buckets,\n batch_size=batch_size,\n batch_by_words=batch_by_words,\n batch_num_devices=1,\n data_target_average_len=[None] * len(buckets))\n for bbs in bucket_batch_sizes:\n assert bbs.batch_size == batch_size\n assert bbs.average_words_per_batch == bbs.bucket[1] * batch_size\n\n\ndef test_word_based_define_bucket_batch_sizes():\n batch_by_words = True\n batch_num_devices = 1\n batch_size = 200\n max_seq_len = 100\n buckets = data_io.define_parallel_buckets(max_seq_len, max_seq_len, 10, 1.5)\n bucket_batch_sizes = data_io.define_bucket_batch_sizes(buckets=buckets,\n batch_size=batch_size,\n batch_by_words=batch_by_words,\n batch_num_devices=batch_num_devices,\n data_target_average_len=[None] * len(buckets))\n # last bucket batch size is different\n for bbs in bucket_batch_sizes[:-1]:\n expected_batch_size = round((batch_size / bbs.bucket[1]) / batch_num_devices)\n assert bbs.batch_size == expected_batch_size\n expected_average_words_per_batch = expected_batch_size * bbs.bucket[1]\n assert bbs.average_words_per_batch == expected_average_words_per_batch\n\n\ndef _get_random_bucketed_data(buckets: List[Tuple[int, int]],\n min_count: int,\n max_count: int,\n bucket_counts: Optional[List[Optional[int]]] = None):\n \"\"\"\n Get random bucket data.\n\n :param buckets: The list of buckets.\n :param min_count: The minimum number of samples that will be sampled if no exact count is given.\n :param max_count: The maximum number of samples that will be sampled if no exact count is given.\n :param bucket_counts: For each bucket an optional exact example count can be given. If it is not given it will be\n sampled.\n :return: The random source, target and label arrays.\n \"\"\"\n if bucket_counts is None:\n bucket_counts = [None for _ in buckets]\n bucket_counts = [random.randint(min_count, max_count) if given_count is None else given_count\n for given_count in bucket_counts]\n source = [mx.nd.array(np.random.randint(0, 10, (count, random.randint(1, bucket[0])))) for count, bucket in\n zip(bucket_counts, buckets)]\n target = [mx.nd.array(np.random.randint(0, 10, (count, random.randint(1, bucket[1])))) for count, bucket in\n zip(bucket_counts, buckets)]\n label = target\n return source, target, label\n\n\ndef test_parallel_data_set():\n buckets = data_io.define_parallel_buckets(100, 100, 10, 1.0)\n source, target, label = _get_random_bucketed_data(buckets, min_count=0, max_count=5)\n\n def check_equal(arrays1, arrays2):\n assert len(arrays1) == len(arrays2)\n for a1, a2 in zip(arrays1, arrays2):\n assert np.array_equal(a1.asnumpy(), a2.asnumpy())\n\n with TemporaryDirectory() as work_dir:\n dataset = data_io.ParallelDataSet(source, target, label)\n fname = os.path.join(work_dir, 'dataset')\n dataset.save(fname)\n dataset_loaded = data_io.ParallelDataSet.load(fname)\n check_equal(dataset.source, dataset_loaded.source)\n check_equal(dataset.target, dataset_loaded.target)\n check_equal(dataset.label, dataset_loaded.label)\n\n\ndef test_parallel_data_set_fill_up():\n batch_size = 32\n buckets = data_io.define_parallel_buckets(100, 100, 10, 1.0)\n bucket_batch_sizes = data_io.define_bucket_batch_sizes(buckets,\n batch_size,\n batch_by_words=False,\n batch_num_devices=1,\n data_target_average_len=[None] * len(buckets))\n dataset = data_io.ParallelDataSet(*_get_random_bucketed_data(buckets, min_count=1, max_count=5))\n\n dataset_filled_up = dataset.fill_up(bucket_batch_sizes, 'replicate')\n assert len(dataset_filled_up.source) == len(dataset.source)\n assert len(dataset_filled_up.target) == len(dataset.target)\n assert len(dataset_filled_up.label) == len(dataset.label)\n for bidx in range(len(dataset)):\n bucket_batch_size = bucket_batch_sizes[bidx].batch_size\n assert dataset_filled_up.source[bidx].shape[0] == bucket_batch_size\n assert dataset_filled_up.target[bidx].shape[0] == bucket_batch_size\n assert dataset_filled_up.label[bidx].shape[0] == bucket_batch_size\n\n\ndef test_get_permutations():\n data = [list(range(3)), list(range(1)), list(range(7)), []]\n bucket_counts = [len(d) for d in data]\n\n permutation, inverse_permutation = data_io.get_permutations(bucket_counts)\n assert len(permutation) == len(inverse_permutation) == len(bucket_counts) == len(data)\n\n for d, p, pi in zip(data, permutation, inverse_permutation):\n p = p.asnumpy().astype(np.int)\n pi = pi.asnumpy().astype(np.int)\n p_set = set(p)\n pi_set = set(pi)\n assert len(p_set) == len(p)\n assert len(pi_set) == len(pi)\n assert p_set - pi_set == set()\n if d:\n d = np.array(d)\n assert (d[p][pi] == d).all()\n else:\n assert len(p_set) == 1\n\n\ndef test_parallel_data_set_permute():\n batch_size = 5\n buckets = data_io.define_parallel_buckets(100, 100, 10, 1.0)\n bucket_batch_sizes = data_io.define_bucket_batch_sizes(buckets,\n batch_size,\n batch_by_words=False,\n batch_num_devices=1,\n data_target_average_len=[None] * len(buckets))\n dataset = data_io.ParallelDataSet(*_get_random_bucketed_data(buckets, min_count=0, max_count=5)).fill_up(\n bucket_batch_sizes, 'replicate')\n\n permutations, inverse_permutations = data_io.get_permutations(dataset.get_bucket_counts())\n\n assert len(permutations) == len(inverse_permutations) == len(dataset)\n dataset_restored = dataset.permute(permutations).permute(inverse_permutations)\n assert len(dataset) == len(dataset_restored)\n for buck_idx in range(len(dataset)):\n num_samples = dataset.source[buck_idx].shape[0]\n if num_samples:\n assert (dataset.source[buck_idx] == dataset_restored.source[buck_idx]).asnumpy().all()\n assert (dataset.target[buck_idx] == dataset_restored.target[buck_idx]).asnumpy().all()\n assert (dataset.label[buck_idx] == dataset_restored.label[buck_idx]).asnumpy().all()\n else:\n assert not dataset_restored.source[buck_idx]\n assert not dataset_restored.target[buck_idx]\n assert not dataset_restored.label[buck_idx]\n\n\ndef test_get_batch_indices():\n max_bucket_size = 50\n batch_size = 10\n buckets = data_io.define_parallel_buckets(100, 100, 10, 1.0)\n bucket_batch_sizes = data_io.define_bucket_batch_sizes(buckets,\n batch_size,\n batch_by_words=False,\n batch_num_devices=1,\n data_target_average_len=[None] * len(buckets))\n dataset = data_io.ParallelDataSet(*_get_random_bucketed_data(buckets=buckets,\n min_count=1,\n max_count=max_bucket_size))\n\n indices = data_io.get_batch_indices(dataset, bucket_batch_sizes=bucket_batch_sizes)\n\n # check for valid indices\n for buck_idx, start_pos in indices:\n assert 0 <= buck_idx < len(dataset)\n assert 0 <= start_pos < len(dataset.source[buck_idx]) - batch_size + 1\n\n # check that all indices are used for a filled-up dataset\n dataset = dataset.fill_up(bucket_batch_sizes, fill_up='replicate')\n indices = data_io.get_batch_indices(dataset, bucket_batch_sizes=bucket_batch_sizes)\n all_bucket_indices = set(list(range(len(dataset))))\n computed_bucket_indices = set([i for i, j in indices])\n\n assert not all_bucket_indices - computed_bucket_indices\n\n\[email protected](\"buckets, expected_default_bucket_key\",\n [([(10, 10), (20, 20), (30, 30), (40, 40), (50, 50)], (50, 50)),\n ([(5, 10), (10, 20), (15, 30), (25, 50), (20, 40)], (25, 50))])\ndef test_get_default_bucket_key(buckets, expected_default_bucket_key):\n default_bucket_key = data_io.get_default_bucket_key(buckets)\n assert default_bucket_key == expected_default_bucket_key\n\n\nget_parallel_bucket_tests = [([(10, 10), (20, 20), (30, 30), (40, 40), (50, 50)], 50, 50, 4, (50, 50)),\n ([(10, 10), (20, 20), (30, 30), (40, 40), (50, 50)], 50, 10, 4, (50, 50)),\n ([(10, 10), (20, 20), (30, 30), (40, 40), (50, 50)], 20, 10, 1, (20, 20)),\n ([(10, 10)], 20, 10, None, None),\n ([], 20, 10, None, None),\n ([(10, 11)], 11, 10, None, None),\n ([(11, 10)], 11, 10, 0, (11, 10))]\n\n\[email protected](\"buckets, source_length, target_length, expected_bucket_index, expected_bucket\",\n get_parallel_bucket_tests)\ndef test_get_parallel_bucket(buckets, source_length, target_length, expected_bucket_index, expected_bucket):\n bucket_index, bucket = data_io.get_parallel_bucket(buckets, source_length, target_length)\n assert bucket_index == expected_bucket_index\n assert bucket == expected_bucket\n\n\[email protected](\"source, target, expected_num_sents, expected_mean, expected_std\",\n [([[1, 1, 1], [2, 2, 2], [3, 3, 3]],\n [[1, 1, 1], [2, 2, 2], [3, 3, 3]], 3, 1.0, 0.0),\n ([[1, 1], [2, 2], [3, 3]],\n [[1, 1, 1], [2, 2, 2], [3, 3, 3]], 3, 1.5, 0.0),\n ([[1, 1, 1], [2, 2], [3, 3, 3, 3, 3, 3, 3]],\n [[1, 1, 1], [2], [3, 3, 3]], 2, 0.75, 0.25)])\ndef test_calculate_length_statistics(source, target, expected_num_sents, expected_mean, expected_std):\n length_statistics = data_io.calculate_length_statistics(source, target, 5, 5)\n assert len(source) == len(target)\n assert length_statistics.num_sents == expected_num_sents\n assert np.isclose(length_statistics.length_ratio_mean, expected_mean)\n assert np.isclose(length_statistics.length_ratio_std, expected_std)\n\n\ndef test_get_training_data_iters():\n train_line_count = 100\n train_max_length = 30\n dev_line_count = 20\n dev_max_length = 30\n expected_mean = 1.0\n expected_std = 0.0\n test_line_count = 20\n test_line_count_empty = 0\n test_max_length = 30\n batch_size = 5\n with tmp_digits_dataset(\"tmp_corpus\",\n train_line_count, train_max_length, dev_line_count, dev_max_length,\n test_line_count, test_line_count_empty, test_max_length) as data:\n # tmp common vocab\n vcb = vocab.build_from_paths([data['source'], data['target']])\n\n train_iter, val_iter, config_data = data_io.get_training_data_iters(data['source'], data['target'],\n data['validation_source'],\n data['validation_target'],\n vocab_source=vcb,\n vocab_target=vcb,\n vocab_source_path=None,\n vocab_target_path=None,\n shared_vocab=True,\n batch_size=batch_size,\n batch_by_words=False,\n batch_num_devices=1,\n fill_up=\"replicate\",\n max_seq_len_source=train_max_length,\n max_seq_len_target=train_max_length,\n bucketing=True,\n bucket_width=10)\n assert isinstance(train_iter, data_io.ParallelSampleIter)\n assert isinstance(val_iter, data_io.ParallelSampleIter)\n assert isinstance(config_data, data_io.DataConfig)\n assert config_data.source == data['source']\n assert config_data.target == data['target']\n assert config_data.vocab_source is None\n assert config_data.vocab_target is None\n assert config_data.data_statistics.max_observed_len_source == train_max_length - 1\n assert config_data.data_statistics.max_observed_len_target == train_max_length\n assert np.isclose(config_data.data_statistics.length_ratio_mean, expected_mean)\n assert np.isclose(config_data.data_statistics.length_ratio_std, expected_std)\n\n assert train_iter.batch_size == batch_size\n assert val_iter.batch_size == batch_size\n assert train_iter.default_bucket_key == (train_max_length, train_max_length)\n assert val_iter.default_bucket_key == (dev_max_length, dev_max_length)\n assert train_iter.dtype == 'float32'\n\n # test some batches\n bos_id = vcb[C.BOS_SYMBOL]\n expected_first_target_symbols = np.full((batch_size,), bos_id, dtype='float32')\n for epoch in range(2):\n while train_iter.iter_next():\n batch = train_iter.next()\n assert len(batch.data) == 2\n assert len(batch.label) == 1\n assert batch.bucket_key in train_iter.buckets\n source = batch.data[0].asnumpy()\n target = batch.data[1].asnumpy()\n label = batch.label[0].asnumpy()\n assert source.shape[0] == target.shape[0] == label.shape[0] == batch_size\n # target first symbol should be BOS\n assert np.array_equal(target[:, 0], expected_first_target_symbols)\n # label first symbol should be 2nd target symbol\n assert np.array_equal(label[:, 0], target[:, 1])\n # each label sequence contains one EOS symbol\n assert np.sum(label == vcb[C.EOS_SYMBOL]) == batch_size\n train_iter.reset()\n\n\ndef _data_batches_equal(db1, db2):\n # We just compare the data, should probably be enough\n equal = True\n for data1, data2 in zip(db1.data, db2.data):\n equal = equal and np.allclose(data1.asnumpy(), data2.asnumpy())\n return equal\n\n\ndef test_parallel_sample_iter():\n batch_size = 2\n buckets = data_io.define_parallel_buckets(100, 100, 10, 1.0)\n # The first bucket is going to be empty:\n bucket_counts = [0] + [None] * (len(buckets) - 1)\n bucket_batch_sizes = data_io.define_bucket_batch_sizes(buckets,\n batch_size,\n batch_by_words=False,\n batch_num_devices=1,\n data_target_average_len=[None] * len(buckets))\n\n dataset = data_io.ParallelDataSet(*_get_random_bucketed_data(buckets, min_count=0, max_count=5,\n bucket_counts=bucket_counts))\n it = data_io.ParallelSampleIter(dataset, buckets, batch_size, bucket_batch_sizes)\n\n with TemporaryDirectory() as work_dir:\n # Test 1\n it.next()\n expected_batch = it.next()\n\n fname = os.path.join(work_dir, \"saved_iter\")\n it.save_state(fname)\n\n it_loaded = data_io.ParallelSampleIter(dataset, buckets, batch_size, bucket_batch_sizes)\n it_loaded.reset()\n it_loaded.load_state(fname)\n loaded_batch = it_loaded.next()\n assert _data_batches_equal(expected_batch, loaded_batch)\n\n # Test 2\n it.reset()\n expected_batch = it.next()\n it.save_state(fname)\n\n it_loaded = data_io.ParallelSampleIter(dataset, buckets, batch_size, bucket_batch_sizes)\n it_loaded.reset()\n it_loaded.load_state(fname)\n\n loaded_batch = it_loaded.next()\n assert _data_batches_equal(expected_batch, loaded_batch)\n\n # Test 3\n it.reset()\n expected_batch = it.next()\n it.save_state(fname)\n it_loaded = data_io.ParallelSampleIter(dataset, buckets, batch_size, bucket_batch_sizes)\n it_loaded.reset()\n it_loaded.load_state(fname)\n\n loaded_batch = it_loaded.next()\n assert _data_batches_equal(expected_batch, loaded_batch)\n\n while it.iter_next():\n it.next()\n it_loaded.next()\n assert not it_loaded.iter_next()\n\n\ndef test_sharded_parallel_sample_iter():\n batch_size = 2\n buckets = data_io.define_parallel_buckets(100, 100, 10, 1.0)\n # The first bucket is going to be empty:\n bucket_counts = [0] + [None] * (len(buckets) - 1)\n bucket_batch_sizes = data_io.define_bucket_batch_sizes(buckets,\n batch_size,\n batch_by_words=False,\n batch_num_devices=1,\n data_target_average_len=[None] * len(buckets))\n\n dataset1 = data_io.ParallelDataSet(*_get_random_bucketed_data(buckets, min_count=0, max_count=5,\n bucket_counts=bucket_counts))\n dataset2 = data_io.ParallelDataSet(*_get_random_bucketed_data(buckets, min_count=0, max_count=5,\n bucket_counts=bucket_counts))\n\n with TemporaryDirectory() as work_dir:\n shard1_fname = os.path.join(work_dir, 'shard1')\n shard2_fname = os.path.join(work_dir, 'shard2')\n dataset1.save(shard1_fname)\n dataset2.save(shard2_fname)\n shard_fnames = [shard1_fname, shard2_fname]\n\n it = data_io.ShardedParallelSampleIter(shard_fnames, buckets, batch_size, bucket_batch_sizes, 'replicate')\n\n with TemporaryDirectory() as work_dir:\n # Test 1\n it.next()\n expected_batch = it.next()\n\n fname = os.path.join(work_dir, \"saved_iter\")\n it.save_state(fname)\n\n it_loaded = data_io.ShardedParallelSampleIter(shard_fnames, buckets, batch_size, bucket_batch_sizes,\n 'replicate')\n it_loaded.reset()\n it_loaded.load_state(fname)\n loaded_batch = it_loaded.next()\n assert _data_batches_equal(expected_batch, loaded_batch)\n\n # Test 2\n it.reset()\n expected_batch = it.next()\n it.save_state(fname)\n\n it_loaded = data_io.ShardedParallelSampleIter(shard_fnames, buckets, batch_size, bucket_batch_sizes,\n 'replicate')\n it_loaded.reset()\n it_loaded.load_state(fname)\n\n loaded_batch = it_loaded.next()\n assert _data_batches_equal(expected_batch, loaded_batch)\n\n # Test 3\n it.reset()\n expected_batch = it.next()\n it.save_state(fname)\n it_loaded = data_io.ShardedParallelSampleIter(shard_fnames, buckets, batch_size, bucket_batch_sizes,\n 'replicate')\n it_loaded.reset()\n it_loaded.load_state(fname)\n\n loaded_batch = it_loaded.next()\n assert _data_batches_equal(expected_batch, loaded_batch)\n\n while it.iter_next():\n it.next()\n it_loaded.next()\n assert not it_loaded.iter_next()\n\n\ndef test_sharded_parallel_sample_iter_num_batches():\n num_shards = 2\n batch_size = 2\n num_batches_per_bucket = 10\n buckets = data_io.define_parallel_buckets(100, 100, 10, 1.0)\n bucket_counts = [batch_size * num_batches_per_bucket for _ in buckets]\n num_batches_per_shard = num_batches_per_bucket * len(buckets)\n num_batches = num_shards * num_batches_per_shard\n bucket_batch_sizes = data_io.define_bucket_batch_sizes(buckets,\n batch_size,\n batch_by_words=False,\n batch_num_devices=1,\n data_target_average_len=[None] * len(buckets))\n\n dataset1 = data_io.ParallelDataSet(*_get_random_bucketed_data(buckets, min_count=0, max_count=5,\n bucket_counts=bucket_counts))\n dataset2 = data_io.ParallelDataSet(*_get_random_bucketed_data(buckets, min_count=0, max_count=5,\n bucket_counts=bucket_counts))\n with TemporaryDirectory() as work_dir:\n shard1_fname = os.path.join(work_dir, 'shard1')\n shard2_fname = os.path.join(work_dir, 'shard2')\n dataset1.save(shard1_fname)\n dataset2.save(shard2_fname)\n shard_fnames = [shard1_fname, shard2_fname]\n\n it = data_io.ShardedParallelSampleIter(shard_fnames, buckets, batch_size, bucket_batch_sizes,\n 'replicate')\n\n num_batches_seen = 0\n while it.iter_next():\n it.next()\n num_batches_seen += 1\n assert num_batches_seen == num_batches\n\n\ndef test_sharded_and_parallel_iter_same_num_batches():\n \"\"\" Tests that a sharded data iterator with just a single shard produces as many shards as an iterator directly\n using the same dataset. \"\"\"\n batch_size = 2\n num_batches_per_bucket = 10\n buckets = data_io.define_parallel_buckets(100, 100, 10, 1.0)\n bucket_counts = [batch_size * num_batches_per_bucket for _ in buckets]\n num_batches = num_batches_per_bucket * len(buckets)\n bucket_batch_sizes = data_io.define_bucket_batch_sizes(buckets,\n batch_size,\n batch_by_words=False,\n batch_num_devices=1,\n data_target_average_len=[None] * len(buckets))\n\n dataset = data_io.ParallelDataSet(*_get_random_bucketed_data(buckets, min_count=0, max_count=5,\n bucket_counts=bucket_counts))\n\n with TemporaryDirectory() as work_dir:\n shard_fname = os.path.join(work_dir, 'shard1')\n dataset.save(shard_fname)\n shard_fnames = [shard_fname]\n\n it_sharded = data_io.ShardedParallelSampleIter(shard_fnames, buckets, batch_size, bucket_batch_sizes,\n 'replicate')\n\n it_parallel = data_io.ParallelSampleIter(dataset, buckets, batch_size, bucket_batch_sizes)\n\n num_batches_seen = 0\n while it_parallel.iter_next():\n assert it_sharded.iter_next()\n it_parallel.next()\n it_sharded.next()\n num_batches_seen += 1\n assert num_batches_seen == num_batches\n\n print(\"Resetting...\")\n it_sharded.reset()\n it_parallel.reset()\n\n num_batches_seen = 0\n while it_parallel.iter_next():\n assert it_sharded.iter_next()\n it_parallel.next()\n it_sharded.next()\n\n num_batches_seen += 1\n\n assert num_batches_seen == num_batches\n",
"# Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may not\n# use this file except in compliance with the License. A copy of the License\n# is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on\n# an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n\nfrom typing import Dict, Optional, Tuple\n\nimport mxnet as mx\nimport numpy as np\n\nfrom . import config\nfrom . import constants as C\nfrom . import layers\n\n\nclass TransformerConfig(config.Config):\n\n def __init__(self,\n model_size: int,\n attention_heads: int,\n feed_forward_num_hidden: int,\n act_type: str,\n num_layers: int,\n dropout_attention: float,\n dropout_act: float,\n dropout_prepost: float,\n positional_embedding_type: str,\n preprocess_sequence: str,\n postprocess_sequence: str,\n max_seq_len_source: int,\n max_seq_len_target: int,\n conv_config: Optional['ConvolutionalEmbeddingConfig'] = None) -> None: # type: ignore\n super().__init__()\n self.model_size = model_size\n self.attention_heads = attention_heads\n self.feed_forward_num_hidden = feed_forward_num_hidden\n self.act_type = act_type\n self.num_layers = num_layers\n self.dropout_attention = dropout_attention\n self.dropout_act = dropout_act\n self.dropout_prepost = dropout_prepost\n self.positional_embedding_type = positional_embedding_type\n self.preprocess_sequence = preprocess_sequence\n self.postprocess_sequence = postprocess_sequence\n self.max_seq_len_source = max_seq_len_source\n self.max_seq_len_target = max_seq_len_target\n self.conv_config = conv_config\n\n\nclass TransformerEncoderBlock:\n \"\"\"\n A transformer encoder block consists self-attention and a feed-forward layer with pre/post process blocks\n in between.\n \"\"\"\n\n def __init__(self,\n config: TransformerConfig,\n prefix: str) -> None:\n self.pre_self_attention = TransformerProcessBlock(sequence=config.preprocess_sequence,\n num_hidden=config.model_size,\n dropout=config.dropout_prepost,\n prefix=\"%satt_self_pre_\" % prefix)\n self.self_attention = layers.MultiHeadSelfAttention(depth_att=config.model_size,\n heads=config.attention_heads,\n depth_out=config.model_size,\n dropout=config.dropout_attention,\n prefix=\"%satt_self_\" % prefix)\n self.post_self_attention = TransformerProcessBlock(sequence=config.postprocess_sequence,\n num_hidden=config.model_size,\n dropout=config.dropout_prepost,\n prefix=\"%satt_self_post_\" % prefix)\n\n self.pre_ff = TransformerProcessBlock(sequence=config.preprocess_sequence,\n num_hidden=config.model_size,\n dropout=config.dropout_prepost,\n prefix=\"%sff_pre_\" % prefix)\n self.ff = TransformerFeedForward(num_hidden=config.feed_forward_num_hidden,\n num_model=config.model_size,\n act_type=config.act_type,\n dropout=config.dropout_act,\n prefix=\"%sff_\" % prefix)\n self.post_ff = TransformerProcessBlock(sequence=config.postprocess_sequence,\n num_hidden=config.model_size,\n dropout=config.dropout_prepost,\n prefix=\"%sff_post_\" % prefix)\n\n def __call__(self, data: mx.sym.Symbol, bias: mx.sym.Symbol) -> mx.sym.Symbol:\n # self-attention\n data_self_att, enc_attention = self.self_attention(inputs=self.pre_self_attention(data, None),\n bias=bias,\n cache=None)\n data = self.post_self_attention(data_self_att, data)\n\n # feed-forward\n data_ff = self.ff(self.pre_ff(data, None))\n data = self.post_ff(data_ff, data)\n\n return data, enc_attention\n\n\nclass TransformerDecoderBlock:\n \"\"\"\n A transformer encoder block consists self-attention, encoder attention, and a feed-forward layer\n with pre/post process blocks in between.\n \"\"\"\n\n def __init__(self,\n config: TransformerConfig,\n prefix: str) -> None:\n self.prefix = prefix\n self.pre_self_attention = TransformerProcessBlock(sequence=config.preprocess_sequence,\n num_hidden=config.model_size,\n dropout=config.dropout_prepost,\n prefix=\"%satt_self_pre_\" % prefix)\n self.self_attention = layers.MultiHeadSelfAttention(depth_att=config.model_size,\n heads=config.attention_heads,\n depth_out=config.model_size,\n dropout=config.dropout_attention,\n prefix=\"%satt_self_\" % prefix)\n self.post_self_attention = TransformerProcessBlock(sequence=config.postprocess_sequence,\n num_hidden=config.model_size,\n dropout=config.dropout_prepost,\n prefix=\"%satt_self_post_\" % prefix)\n\n self.pre_enc_attention = TransformerProcessBlock(sequence=config.preprocess_sequence,\n num_hidden=config.model_size,\n dropout=config.dropout_prepost,\n prefix=\"%satt_enc_pre_\" % prefix)\n self.enc_attention = layers.MultiHeadAttention(depth_att=config.model_size,\n heads=config.attention_heads,\n depth_out=config.model_size,\n dropout=config.dropout_attention,\n prefix=\"%satt_enc_\" % prefix)\n self.post_enc_attention = TransformerProcessBlock(sequence=config.postprocess_sequence,\n num_hidden=config.model_size,\n dropout=config.dropout_prepost,\n prefix=\"%satt_enc_post_\" % prefix)\n\n self.pre_ff = TransformerProcessBlock(sequence=config.preprocess_sequence,\n num_hidden=config.model_size,\n dropout=config.dropout_prepost,\n prefix=\"%sff_pre_\" % prefix)\n self.ff = TransformerFeedForward(num_hidden=config.feed_forward_num_hidden,\n num_model=config.model_size,\n act_type=config.act_type,\n dropout=config.dropout_act,\n prefix=\"%sff_\" % prefix)\n self.post_ff = TransformerProcessBlock(sequence=config.postprocess_sequence,\n num_hidden=config.model_size,\n dropout=config.dropout_prepost,\n prefix=\"%sff_post_\" % prefix)\n\n def __call__(self,\n target: mx.sym.Symbol,\n target_bias: mx.sym.Symbol,\n source: mx.sym.Symbol,\n source_bias: mx.sym.Symbol,\n cache: Optional[Dict[str, Optional[mx.sym.Symbol]]] = None) -> Tuple[mx.sym.Symbol, mx.sym.Symbol, mx.sym.Symbol]:\n # self-attention\n target_self_att, dec_attention = self.self_attention(inputs=self.pre_self_attention(target, None),\n bias=target_bias,\n cache=cache)\n target = self.post_self_attention(target_self_att, target)\n\n # encoder attention\n target_enc_att, enc_attention = self.enc_attention(queries=self.pre_enc_attention(target, None),\n memory=source,\n bias=source_bias)\n target = self.post_enc_attention(target_enc_att, target)\n\n # feed-forward\n target_ff = self.ff(self.pre_ff(target, None))\n target = self.post_ff(target_ff, target)\n\n return target, enc_attention, dec_attention\n\n\nclass TransformerProcessBlock:\n \"\"\"\n Block to perform pre/post processing on layer inputs.\n The processing steps are determined by the sequence argument, which can contain one of the three operations:\n n: layer normalization\n r: residual connection\n d: dropout\n \"\"\"\n\n def __init__(self,\n sequence: str,\n num_hidden: int,\n dropout: float,\n prefix: str) -> None:\n self.sequence = sequence\n self.num_hidden = num_hidden\n self.dropout = dropout\n self.prefix = prefix\n self.layer_norm = None\n if \"n\" in sequence:\n self.layer_norm = layers.LayerNormalization(num_hidden=self.num_hidden, prefix=\"%snorm\" % self.prefix)\n\n def __call__(self,\n data: mx.sym.Symbol,\n prev: Optional[mx.sym.Symbol]) -> mx.sym.Symbol:\n \"\"\"\n Apply processing sequence to data with optional previous input.\n\n :param data: Input data. Shape: (batch, length, num_hidden).\n :param prev: Previous data. Shape: (batch, length, num_hidden).\n :return: Processed data. Shape: (batch, length, num_hidden).\n \"\"\"\n if not self.sequence:\n return data\n\n if prev is None:\n assert 'r' not in self.sequence, \"Residual connection not allowed if no previous value given.\"\n\n for step in self.sequence:\n\n if step == \"r\":\n data = mx.sym._internal._plus(data, prev, name=\"%sresidual\" % self.prefix)\n\n elif step == \"n\":\n data = self.layer_norm.normalize(data)\n\n elif step == \"d\":\n if self.dropout > 0.0:\n data = mx.sym.Dropout(data, p=self.dropout, name=\"%sdropout\" % self.prefix)\n else:\n raise ValueError(\"Unknown step in sequence: %s\" % step)\n\n return data\n\n\nclass TransformerFeedForward:\n \"\"\"\n Position-wise feed-forward network with activation.\n \"\"\"\n\n def __init__(self,\n num_hidden: int,\n num_model: int,\n act_type: str,\n dropout: float,\n prefix: str) -> None:\n self.num_hidden = num_hidden\n self.num_model = num_model\n self.dropout = dropout\n self.prefix = prefix\n self.act_type = act_type\n self.w_i2h = mx.sym.Variable('%si2h_weight' % prefix)\n self.b_i2h = mx.sym.Variable('%si2h_bias' % prefix)\n self.w_h2o = mx.sym.Variable('%sh2o_weight' % prefix)\n self.b_h2o = mx.sym.Variable('%sh2o_bias' % prefix)\n\n def __call__(self, x) -> mx.sym.Symbol:\n \"\"\"\n Position-wise feed-forward network with activation.\n\n :param x: Symbol of shape (batch_size, seq_len, num_hidden)\n :return: Symbol of shape (batch_size, seq_len, num_hidden)\n \"\"\"\n h = mx.sym.FullyConnected(data=x, num_hidden=self.num_hidden, weight=self.w_i2h, bias=self.b_i2h, flatten=False)\n h = layers.activation(h, act_type=self.act_type)\n if self.dropout > 0.0:\n h = mx.sym.Dropout(h, p=self.dropout)\n y = mx.sym.FullyConnected(data=h, num_hidden=self.num_model, weight=self.w_h2o, bias=self.b_h2o, flatten=False)\n return y\n\n\nclass VariableLengthBias(mx.operator.CustomOp):\n \"\"\"\n Returns bias/mask given a vector of sequence lengths.\n \"\"\"\n\n def __init__(self, max_length: int) -> None:\n super().__init__()\n self.max_length = max_length\n\n def forward(self, is_train, req, in_data, out_data, aux):\n # lengths: (batch_size,)\n lengths = in_data[0]\n\n # (max_length, batch_size)\n data = mx.nd.zeros((self.max_length, lengths.shape[0]), ctx=lengths.context)\n data = mx.nd.SequenceMask(data=data,\n use_sequence_length=True,\n sequence_length=lengths,\n value=C.LARGE_NEGATIVE_VALUE)\n # (batch_size, max_length)\n data = mx.nd.swapaxes(data, dim1=0, dim2=1)\n self.assign(out_data[0], req[0], data)\n\n def backward(self, req, out_grad, in_data, out_data, in_grad, aux):\n pass\n\n\[email protected](\"variable_length_bias\")\nclass VariableLengthBiasProp(mx.operator.CustomOpProp):\n\n def __init__(self, max_length: str) -> None:\n super().__init__()\n self.max_length = int(max_length)\n\n def list_arguments(self):\n return ['data']\n\n def list_outputs(self):\n return ['output']\n\n def infer_shape(self, in_shape):\n batch_size = in_shape[0][0]\n return in_shape, [(batch_size, self.max_length)], []\n\n def infer_type(self, in_type):\n return in_type, [np.float32], []\n\n def create_operator(self, ctx, shapes, dtypes):\n return VariableLengthBias(max_length=self.max_length)\n\n\ndef get_variable_length_bias(lengths: mx.sym.Symbol,\n max_length: int,\n num_heads: Optional[int] = None,\n fold_heads: bool = True,\n name: str = '') -> mx.sym.Symbol:\n \"\"\"\n Returns bias/mask for variable sequence lengths.\n\n :param lengths: Sequence lengths. Shape: (batch,).\n :param max_length: Maximum sequence length.\n :param num_heads: Number of attention heads.\n :param fold_heads: Whether to fold heads dimension into batch dimension.\n :param name: Name of symbol.\n :return: Bias symbol.\n \"\"\"\n # (batch_size, max_length)\n x = mx.symbol.Custom(data=lengths, max_length=max_length, op_type='variable_length_bias')\n if num_heads is not None:\n # (batch_size, heads, max_length) if fold_heads == False else (batch_size * heads, max_length)\n x = layers.broadcast_to_heads(x, num_heads, ndim=2, fold_heads=fold_heads)\n return mx.sym.BlockGrad(x, name='%sbias' % name)\n\n\ndef get_autoregressive_bias(max_length: int, name: str) -> mx.sym.Symbol:\n \"\"\"\n Returns bias/mask to ensure position i can only attend to positions <i.\n\n :param max_length: Sequence length.\n :param name: Name of symbol.\n :return: Bias symbol of shape (1, max_length, max_length).\n \"\"\"\n return mx.sym.BlockGrad(mx.symbol.Custom(length=max_length,\n name=name,\n op_type='auto_regressive_bias'))\n\n\nclass AutoRegressiveBias(mx.operator.CustomOp):\n \"\"\"\n Returns a symbol of shape (1, length, length) with cells above the main diagonal\n set to a large negative value, e.g.\n length=4\n\n 0 1 1 1\n 0 0 1 1 * -99999\n 0 0 0 1\n 0 0 0 0\n \"\"\"\n\n def __init__(self, length: int) -> None:\n super().__init__()\n self.bias = self.get_bias(length)\n\n @staticmethod\n def get_bias(length: int):\n # matrix with lower triangle and main diagonal set to 0, upper triangle set to 1\n upper_triangle = np.triu(np.ones((length, length)), k=1)\n # (1, length, length)\n bias = -99999999. * np.reshape(upper_triangle, (1, length, length))\n return mx.nd.array(bias)\n\n def forward(self, is_train, req, in_data, out_data, aux):\n self.assign(out_data[0], req[0], self.bias)\n\n def backward(self, req, out_grad, in_data, out_data, in_grad, aux):\n pass\n\n\[email protected](\"auto_regressive_bias\")\nclass AutoRegressiveBiasProp(mx.operator.CustomOpProp):\n\n def __init__(self, length: str) -> None:\n super().__init__()\n self.length = int(length)\n\n def list_arguments(self):\n return []\n\n def list_outputs(self):\n return ['output']\n\n def infer_shape(self, in_shape):\n return [], [(1, self.length, self.length)], []\n\n def infer_type(self, in_type):\n return [], [np.float32], []\n\n def create_operator(self, ctx, shapes, dtypes):\n return AutoRegressiveBias(length=self.length)\n"
] | [
[
"numpy.asarray",
"numpy.isclose",
"numpy.random.randint"
],
[
"numpy.array_equal",
"numpy.full",
"numpy.array",
"numpy.sum",
"numpy.isclose"
],
[
"numpy.reshape",
"numpy.ones"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
yileiCao/shareTheBest | [
"ef62396a7884954dd6464d2dd78e232273e1060b"
] | [
"trilinear_cpp/setup.py"
] | [
"from setuptools import setup\nimport torch\nfrom torch.utils.cpp_extension import BuildExtension, CUDAExtension, CppExtension\n\nif torch.cuda.is_available():\n print('Including CUDA code.')\n setup(\n name='trilinear',\n ext_modules=[\n CUDAExtension('trilinear', [\n 'src/trilinear_cuda.cpp',\n 'src/trilinear_kernel.cu',\n ])\n ],\n cmdclass={\n 'build_ext': BuildExtension\n })\nelse:\n print('NO CUDA is found. Fall back to CPU.')\n setup(name='trilinear',\n ext_modules=[CppExtension('trilinear', ['src/trilinear.cpp'])],\n cmdclass={'build_ext': BuildExtension})\n"
] | [
[
"torch.utils.cpp_extension.CUDAExtension",
"torch.utils.cpp_extension.CppExtension",
"torch.cuda.is_available"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jfajkowski/stock-market-forecasting | [
"6a0ae5a0cfe39263a0f448f062cd01283281a0d8",
"6a0ae5a0cfe39263a0f448f062cd01283281a0d8"
] | [
"scripts/model/bigram_svm/train_model.py",
"experiments/svm_doc2vec.py"
] | [
"import pandas as pd\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.svm import SVC\n\n# %% Load data\ndf = pd.read_csv('./data/interim/Classes_Changed.csv')\n\nraw = df.loc[:, 'Top1':'Top25'].apply(lambda x: ' '.join([str(s) for s in x]), axis=1)\ny = df['Class']\n\n# %% Split it into test and training sets\nraw_train, raw_test, y_train, y_test = train_test_split(raw, y, train_size=0.8, shuffle=False)\n\n# %% Define model\nclf = SVC(decision_function_shape='ovo', kernel='rbf', probability=True)\nmodel = Pipeline([\n ('vect', CountVectorizer(ngram_range=(2, 2), stop_words='english')),\n ('tfidf', TfidfTransformer(use_idf=False)),\n ('scale', StandardScaler(with_mean=False)),\n ('clf', clf),\n])\nmodel.fit(raw_train, y_train)\naccuracy_score(y_test, model.predict(raw_test))\n\n# %% Persist it\nimport pickle\nwith open('./models/raw_bigram_svm.mdl', mode='wb') as model_file:\n pickle.dump(model, model_file)\n\n\n\n",
"import pandas as pd\nfrom sklearn.metrics import accuracy_score, confusion_matrix\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.svm import SVC\nfrom sklearn.preprocessing import StandardScaler\n\ndf = pd.read_csv('../scripts/data/data/processed/Doc2Vec.csv', lineterminator='\\n', sep=',')\ndf.columns = df.columns.str.strip()\n\nprint('Number of samples:', len(df))\n\nX = df.loc[:, df.columns != 'Class'].values\ny = df['Class']\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.8, shuffle=False)\n\nclf = SVC(decision_function_shape='ovr', kernel='linear')\n\nmodel = Pipeline([\n ('scale', StandardScaler(with_mean=False)),\n ('clf', clf),\n])\nmodel.fit(X_train, y_train)\ny_pred = model.predict(X_test)\nprint(accuracy_score(y_test, model.predict(X_test)))\nprint(confusion_matrix(y_test, y_pred))"
] | [
[
"pandas.read_csv",
"sklearn.model_selection.train_test_split",
"sklearn.feature_extraction.text.CountVectorizer",
"sklearn.svm.SVC",
"sklearn.preprocessing.StandardScaler",
"sklearn.feature_extraction.text.TfidfTransformer"
],
[
"pandas.read_csv",
"sklearn.metrics.confusion_matrix",
"sklearn.model_selection.train_test_split",
"sklearn.svm.SVC",
"sklearn.preprocessing.StandardScaler"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
wilson1yan/SLM-Lab | [
"1f110288d2d3dde1fb00d415aeb95ce554170813"
] | [
"slm_lab/agent/algorithm/dqn.py"
] | [
"from slm_lab.agent import net\nfrom slm_lab.agent.algorithm import policy_util\nfrom slm_lab.agent.algorithm.sarsa import SARSA\nfrom slm_lab.agent.net import net_util\nfrom slm_lab.lib import logger, util\nfrom slm_lab.lib.decorator import lab_api\nimport numpy as np\nimport pydash as ps\nimport torch\n\nlogger = logger.get_logger(__name__)\n\n\nclass VanillaDQN(SARSA):\n '''\n Implementation of a simple DQN algorithm.\n Algorithm:\n 1. Collect some examples by acting in the environment and store them in a replay memory\n 2. Every K steps sample N examples from replay memory\n 3. For each example calculate the target (bootstrapped estimate of the discounted value of the state and action taken), y, using a neural network to approximate the Q function. s' is the next state following the action actually taken.\n y_t = r_t + gamma * argmax_a Q(s_t', a)\n 4. For each example calculate the current estimate of the discounted value of the state and action taken\n x_t = Q(s_t, a_t)\n 5. Calculate L(x, y) where L is a regression loss (eg. mse)\n 6. Calculate the gradient of L with respect to all the parameters in the network and update the network parameters using the gradient\n 7. Repeat steps 3 - 6 M times\n 8. Repeat steps 2 - 7 Z times\n 9. Repeat steps 1 - 8\n\n For more information on Q-Learning see Sergey Levine's lectures 6 and 7 from CS294-112 Fall 2017\n https://www.youtube.com/playlist?list=PLkFD6_40KJIznC9CDbVTjAF2oyt8_VAe3\n\n e.g. algorithm_spec\n \"algorithm\": {\n \"name\": \"VanillaDQN\",\n \"action_pdtype\": \"Argmax\",\n \"action_policy\": \"epsilon_greedy\",\n \"explore_var_spec\": {\n \"name\": \"linear_decay\",\n \"start_val\": 1.0,\n \"end_val\": 0.1,\n \"start_step\": 10,\n \"end_step\": 1000,\n },\n \"gamma\": 0.99,\n \"training_batch_epoch\": 8,\n \"training_epoch\": 4,\n \"training_frequency\": 10,\n \"training_start_step\": 10,\n \"normalize_state\": true\n }\n '''\n\n @lab_api\n def init_algorithm_params(self):\n # set default\n util.set_attr(self, dict(\n action_pdtype='Argmax',\n action_policy='epsilon_greedy',\n explore_var_spec=None,\n ))\n util.set_attr(self, self.algorithm_spec, [\n 'action_pdtype',\n 'action_policy',\n # explore_var is epsilon, tau or etc. depending on the action policy\n # these control the trade off between exploration and exploitaton\n 'explore_var_spec',\n 'gamma', # the discount factor\n 'training_batch_epoch', # how many gradient updates per batch\n 'training_epoch', # how many batches to train each time\n 'training_frequency', # how often to train (once a few timesteps)\n 'training_start_step', # how long before starting training\n 'normalize_state',\n ])\n super(VanillaDQN, self).init_algorithm_params()\n\n @lab_api\n def init_nets(self, global_nets=None):\n '''Initialize the neural network used to learn the Q function from the spec'''\n if self.algorithm_spec['name'] == 'VanillaDQN':\n assert all(k not in self.net_spec for k in ['update_type', 'update_frequency', 'polyak_coef']), 'Network update not available for VanillaDQN; use DQN.'\n if global_nets is None:\n in_dim = self.body.state_dim\n out_dim = net_util.get_out_dim(self.body)\n NetClass = getattr(net, self.net_spec['type'])\n self.net = NetClass(self.net_spec, in_dim, out_dim)\n self.net_names = ['net']\n else:\n util.set_attr(self, global_nets)\n self.net_names = list(global_nets.keys())\n self.post_init_nets()\n\n def calc_q_loss(self, batch):\n '''Compute the Q value loss using predicted and target Q values from the appropriate networks'''\n q_preds = self.net.wrap_eval(batch['states'])\n # q_preds = self.net(batch['states'])\n act_q_preds = q_preds.gather(-1, batch['actions'].long().unsqueeze(-1)).squeeze(-1)\n next_q_preds = self.net.wrap_eval(batch['next_states'])\n # Bellman equation: compute max_q_targets using reward and max estimated Q values (0 if no next_state)\n max_next_q_preds, _ = next_q_preds.max(dim=-1, keepdim=True)\n max_q_targets = batch['rewards'] + self.gamma * (1 - batch['dones']) * max_next_q_preds\n max_q_targets = max_q_targets.detach()\n q_loss = self.net.loss_fn(act_q_preds, max_q_targets)\n\n # TODO use the same loss_fn but do not reduce yet\n if 'Prioritized' in util.get_class_name(self.body.memory): # PER\n errors = torch.abs(max_q_targets - act_q_preds.detach())\n self.body.memory.update_priorities(errors)\n\n return q_loss\n\n @lab_api\n def act(self, state):\n '''Selects and returns a discrete action for body using the action policy'''\n return super(VanillaDQN, self).act(state)\n\n @lab_api\n def sample(self):\n '''Samples a batch from memory of size self.memory_spec['batch_size']'''\n batch = self.body.memory.sample()\n if self.normalize_state:\n batch = policy_util.normalize_states_and_next_states(self.body, batch)\n batch = util.to_torch_batch(batch, self.net.device, self.body.memory.is_episodic)\n return batch\n\n @lab_api\n def train(self):\n '''\n Completes one training step for the agent if it is time to train.\n i.e. the environment timestep is greater than the minimum training timestep and a multiple of the training_frequency.\n Each training step consists of sampling n batches from the agent's memory.\n For each of the batches, the target Q values (q_targets) are computed and a single training step is taken k times\n Otherwise this function does nothing.\n '''\n if util.get_lab_mode() in ('enjoy', 'eval'):\n self.body.flush()\n return np.nan\n clock = self.body.env.clock\n tick = clock.get(clock.max_tick_unit)\n self.to_train = (tick > self.training_start_step and tick % self.training_frequency == 0)\n if self.to_train == 1:\n total_loss = torch.tensor(0.0, device=self.net.device)\n for _ in range(self.training_epoch):\n batch = self.sample()\n for _ in range(self.training_batch_epoch):\n loss = self.calc_q_loss(batch)\n self.net.training_step(loss=loss, lr_clock=clock)\n total_loss += loss\n loss = total_loss / (self.training_epoch * self.training_batch_epoch)\n # reset\n self.to_train = 0\n self.body.flush()\n logger.debug(f'Trained {self.name} at epi: {clock.epi}, total_t: {clock.total_t}, t: {clock.t}, total_reward so far: {self.body.memory.total_reward}, loss: {loss:.8f}')\n return loss.item()\n else:\n return np.nan\n\n @lab_api\n def update(self):\n '''Update the agent after training'''\n return super(VanillaDQN, self).update()\n\n\nclass DQNBase(VanillaDQN):\n '''\n Implementation of the base DQN algorithm.\n The algorithm follows the same general approach as VanillaDQN but is more general since it allows\n for two different networks (through self.net and self.target_net).\n\n self.net is used to act, and is the network trained.\n self.target_net is used to estimate the maximum value of the Q-function in the next state when calculating the target (see VanillaDQN comments).\n self.target_net is updated periodically to either match self.net (self.net.update_type = \"replace\") or to be a weighted average of self.net and the previous self.target_net (self.net.update_type = \"polyak\")\n If desired, self.target_net can be updated slowly, and this can help to stabilize learning.\n\n It also allows for different nets to be used to select the action in the next state and to evaluate the value of that action through self.online_net and self.eval_net. This can help reduce the tendency of DQN's to overestimate the value of the Q-function. Following this approach leads to the DoubleDQN algorithm.\n\n Setting all nets to self.net reduces to the VanillaDQN case.\n '''\n\n @lab_api\n def init_nets(self, global_nets=None):\n '''Initialize networks'''\n if self.algorithm_spec['name'] == 'DQNBase':\n assert all(k not in self.net_spec for k in ['update_type', 'update_frequency', 'polyak_coef']), 'Network update not available for DQNBase; use DQN.'\n if global_nets is None:\n in_dim = self.body.state_dim\n out_dim = net_util.get_out_dim(self.body)\n NetClass = getattr(net, self.net_spec['type'])\n self.net = NetClass(self.net_spec, in_dim, out_dim)\n self.target_net = NetClass(self.net_spec, in_dim, out_dim)\n self.net_names = ['net', 'target_net']\n else:\n util.set_attr(self, global_nets)\n self.net_names = list(global_nets.keys())\n self.post_init_nets()\n self.online_net = self.target_net\n self.eval_net = self.target_net\n\n def calc_q_loss(self, batch):\n '''Compute the Q value loss using predicted and target Q values from the appropriate networks'''\n q_preds = self.net(batch['states'])\n act_q_preds = q_preds.gather(-1, batch['actions'].long().unsqueeze(-1)).squeeze(-1)\n # Use online_net to select actions in next state\n online_next_q_preds = self.online_net.wrap_eval(batch['next_states'])\n # Use eval_net to calculate next_q_preds for actions chosen by online_net\n next_q_preds = self.eval_net.wrap_eval(batch['next_states'])\n max_next_q_preds = next_q_preds.gather(-1, online_next_q_preds.argmax(dim=-1, keepdim=True)).squeeze(-1)\n max_q_targets = batch['rewards'] + self.gamma * (1 - batch['dones']) * max_next_q_preds\n max_q_targets = max_q_targets.detach()\n q_loss = self.net.loss_fn(act_q_preds, max_q_targets)\n\n # TODO use the same loss_fn but do not reduce yet\n if 'Prioritized' in util.get_class_name(self.body.memory): # PER\n errors = torch.abs(max_q_targets - act_q_preds.detach())\n self.body.memory.update_priorities(errors)\n return q_loss\n\n def update_nets(self):\n total_t = self.body.env.clock.total_t\n if self.net.update_type == 'replace':\n if total_t % self.net.update_frequency == 0:\n logger.debug('Updating target_net by replacing')\n net_util.copy(self.net, self.target_net)\n self.online_net = self.target_net\n self.eval_net = self.target_net\n elif self.net.update_type == 'polyak':\n logger.debug('Updating net by averaging')\n net_util.polyak_update(self.net, self.target_net, self.net.polyak_coef)\n self.online_net = self.target_net\n self.eval_net = self.target_net\n else:\n raise ValueError('Unknown net.update_type. Should be \"replace\" or \"polyak\". Exiting.')\n\n @lab_api\n def update(self):\n '''Updates self.target_net and the explore variables'''\n self.update_nets()\n return super(DQNBase, self).update()\n\n\nclass DQN(DQNBase):\n '''\n DQN class\n\n e.g. algorithm_spec\n \"algorithm\": {\n \"name\": \"DQN\",\n \"action_pdtype\": \"Argmax\",\n \"action_policy\": \"epsilon_greedy\",\n \"explore_var_spec\": {\n \"name\": \"linear_decay\",\n \"start_val\": 1.0,\n \"end_val\": 0.1,\n \"start_step\": 10,\n \"end_step\": 1000,\n },\n \"gamma\": 0.99,\n \"training_batch_epoch\": 8,\n \"training_epoch\": 4,\n \"training_frequency\": 10,\n \"training_start_step\": 10\n }\n '''\n @lab_api\n def init_nets(self, global_nets=None):\n super(DQN, self).init_nets(global_nets)\n\n\nclass DoubleDQN(DQN):\n '''\n Double-DQN (DDQN) class\n\n e.g. algorithm_spec\n \"algorithm\": {\n \"name\": \"DDQN\",\n \"action_pdtype\": \"Argmax\",\n \"action_policy\": \"epsilon_greedy\",\n \"explore_var_spec\": {\n \"name\": \"linear_decay\",\n \"start_val\": 1.0,\n \"end_val\": 0.1,\n \"start_step\": 10,\n \"end_step\": 1000,\n },\n \"gamma\": 0.99,\n \"training_batch_epoch\": 8,\n \"training_epoch\": 4,\n \"training_frequency\": 10,\n \"training_start_step\": 10\n }\n '''\n @lab_api\n def init_nets(self, global_nets=None):\n super(DoubleDQN, self).init_nets(global_nets)\n self.online_net = self.net\n self.eval_net = self.target_net\n\n def update_nets(self):\n res = super(DoubleDQN, self).update_nets()\n total_t = self.body.env.clock.total_t\n if self.net.update_type == 'replace':\n if total_t % self.net.update_frequency == 0:\n self.online_net = self.net\n self.eval_net = self.target_net\n elif self.net.update_type == 'polyak':\n self.online_net = self.net\n self.eval_net = self.target_net\n"
] | [
[
"torch.tensor"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Connossor/bokeh | [
"092e5dc0f62be13d87af5bf2b5a85ec57fd9f14e"
] | [
"examples/plotting/file/stocks.py"
] | [
"import numpy as np\n\nfrom bokeh.layouts import gridplot\nfrom bokeh.plotting import figure, show, output_file\nfrom bokeh.sampledata.stocks import AAPL, GOOG, IBM, MSFT\n\ndef datetime(x):\n return np.array(x, dtype=np.datetime64)\n\np1 = figure(x_axis_type=\"datetime\", title=\"Stock Closing Prices\")\np1.grid.grid_line_alpha=0.3\np1.xaxis.axis_label = 'Date'\np1.yaxis.axis_label = 'Price'\n\np1.line(datetime(AAPL['date']), AAPL['adj_close'], color='#A6CEE3', legend_label='AAPL')\np1.line(datetime(GOOG['date']), GOOG['adj_close'], color='#B2DF8A', legend_label='GOOG')\np1.line(datetime(IBM['date']), IBM['adj_close'], color='#33A02C', legend_label='IBM')\np1.line(datetime(MSFT['date']), MSFT['adj_close'], color='#FB9A99', legend_label='MSFT')\np1.legend.location = \"top_left\"\n\naapl = np.array(AAPL['adj_close'])\naapl_dates = np.array(AAPL['date'], dtype=np.datetime64)\n\nwindow_size = 30\nwindow = np.ones(window_size)/float(window_size)\naapl_avg = np.convolve(aapl, window, 'same')\n\np2 = figure(x_axis_type=\"datetime\", title=\"AAPL One-Month Average\")\np2.grid.grid_line_alpha = 0\np2.xaxis.axis_label = 'Date'\np2.yaxis.axis_label = 'Price'\np2.ygrid.band_fill_color = \"olive\"\np2.ygrid.band_fill_alpha = 0.1\n\np2.circle(aapl_dates, aapl, size=4, legend_label='close',\n color='darkgrey', alpha=0.2)\n\np2.line(aapl_dates, aapl_avg, legend_label='avg', color='navy')\np2.legend.location = \"top_left\"\n\noutput_file(\"stocks.html\", title=\"stocks.py example\")\n\nshow(gridplot([[p1,p2]], plot_width=400, plot_height=400)) # open a browser\n"
] | [
[
"numpy.convolve",
"numpy.array",
"numpy.ones"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
samtx/pyapprox | [
"c926d910e30fbcfed7d0621175d3b0268d59f852",
"c926d910e30fbcfed7d0621175d3b0268d59f852",
"c926d910e30fbcfed7d0621175d3b0268d59f852"
] | [
"pyapprox/optimization.py",
"pyapprox/tests/test_gaussian_process.py",
"tutorials/foundations/plot_sensitivity_analysis.py"
] | [
"import numpy as np\nfrom scipy.optimize import minimize, Bounds\nfrom functools import partial\nfrom scipy.stats import gaussian_kde as KDE\nfrom pyapprox.configure_plots import *\nimport scipy.stats as ss\nfrom pyapprox.utilities import get_all_sample_combinations\n\ndef approx_jacobian(func, x, *args, epsilon=np.sqrt(np.finfo(float).eps)):\n x0 = np.asfarray(x)\n assert x0.ndim == 1 or x0.shape[1] == 1\n f0 = np.atleast_1d(func(*((x0,)+args)))\n if f0.ndim == 2:\n assert f0.shape[1] == 1\n f0 = f0[:, 0]\n jac = np.zeros([len(x0), len(f0)])\n dx = np.zeros(x0.shape)\n for i in range(len(x0)):\n dx[i] = epsilon\n f1 = func(*((x0+dx,)+args))\n if f1.ndim==2:\n assert f1.shape[1] == 1\n f1 = f1[:,0]\n jac[i] = (f1 - f0)/epsilon\n dx[i] = 0.0\n\n return jac.transpose()\n \n\ndef eval_function_at_multiple_design_and_random_samples(function,uq_samples,design_samples):\n \"\"\"\n for functions which only take 1d arrays for uq_samples and design_samples\n loop over all combinations and evaluate function at each combination\n\n design_samples vary slowest and uq_samples vary fastest\n\n Let design samples = [[1,2],[2,3]]\n uq_samples = [[0, 0, 0],[0, 1, 2]]\n Then samples will be\n\n ([1, 2], [0, 0, 0])\n ([1, 2], [0, 1, 2])\n ([3, 4], [0, 0, 0])\n ([3, 4], [0, 1, 2])\n\n function(uq_samples,design_samples)\n \"\"\"\n vals = []\n # put design samples first so that samples iterates over uq_samples fastest\n samples = get_all_sample_combinations(design_samples,uq_samples)\n for xx,zz in zip(\n samples[:design_samples.shape[0]].T,\n samples[design_samples.shape[0]:].T):\n # flip xx,zz because functions assumed to take uq_samples then\n # design_samples\n vals.append(function(zz,xx))\n return np.asarray(vals)\n\ndef eval_mc_based_jacobian_at_multiple_design_samples(grad,stat_func,\n uq_samples,design_samples):\n \"\"\"\n Alternatively I could use\n jacobian = [np.mean([constraint_grad_single(z,x) for z in zz.T],axis=0) for x in xx.T]\n But I think this implementation will allow better use of concurent evaluations in the \n future. For example eval_function_at_multiple_design_and_random_samples could\n utilize an asynchronous call over all the sample combinations\n\n TODO combine uq_samples and design samples into one matrix and assume functions\n always take a single matrix and not two matrices\n \"\"\"\n grads = eval_function_at_multiple_design_and_random_samples(\n grad,uq_samples,design_samples)\n \n ndesign_samples = design_samples.shape[1]\n nuq_samples = uq_samples.shape[1]\n jacobian = np.array(\n [stat_func(grads[ii*nuq_samples:(ii+1)*nuq_samples])\n for ii in range(ndesign_samples)])\n return jacobian\n\ndef check_inputs(uq_samples,design_samples):\n if design_samples.ndim==1:\n design_samples = design_samples[:,np.newaxis]\n if uq_samples is not None and uq_samples.ndim==1:\n uq_samples = design_samples[:,np.newaxis]\n if (uq_samples is not None and\n (design_samples.shape[1]>1 and uq_samples.shape[1]>1)):\n assert design_samples.shape[1]==uq_samples.shape[1]\n return uq_samples,design_samples\n\ndef deterministic_lower_bound_constraint(constraint_function,lower_bound,\n uq_samples,design_samples):\n uq_samples,design_samples = check_inputs(uq_samples,design_samples)\n assert design_samples.shape[1]==1\n val = lower_bound-constraint_function(uq_samples,design_samples)\n # scipy minimize enforces constraints are non-negative so use negative here\n # to enforce upper bound\n return -val\n\ndef variance_lower_bound_constraint(constraint_function,lower_bound,uq_samples,\n design_samples):\n uq_samples,design_samples = check_inputs(uq_samples,design_samples)\n assert design_samples.shape[1]==1\n # scipy minimize enforces constraints are non-negative\n vals = constraint_function(uq_samples,design_samples)\n val = lower_bound-np.std(vals)**2\n # scipy minimize enforces constraints are non-negative so use negative here\n # to enforce upper bound\n return -val\n\ndef mean_lower_bound_constraint(constraint_function,lower_bound,uq_samples,\n design_samples):\n uq_samples,design_samples = check_inputs(uq_samples,design_samples)\n assert design_samples.shape[1]==1\n # scipy minimize enforces constraints are non-negative\n vals = constraint_function(uq_samples,design_samples)\n val = lower_bound-np.mean(vals)**2\n # scipy minimize enforces constraints are non-negative so use negative here\n # to enforce upper bound\n return -val\n\ndef mean_lower_bound_constraint_jacobian(constraint_function_jacobian,uq_samples,\n design_samples):\n uq_samples,design_samples = check_inputs(uq_samples,design_samples)\n assert design_samples.shape[1]==1\n # scipy minimize enforces constraints are non-negative\n vals = constraint_function_jacobian(uq_samples,design_samples)\n val = -np.mean(vals)**2\n # scipy minimize enforces constraints are non-negative so use negative here\n # to enforce upper bound\n return -val\n\ndef quantile_lower_bound_constraint(constraint_function,quantile,lower_bound,\n uq_samples,design_samples):\n uq_samples,design_samples = check_inputs(uq_samples,design_samples)\n assert design_samples.shape[1]==1\n vals = constraint_function(uq_samples,design_samples)\n val = (lower_bound-ss.mstats.mquantiles(vals,prob=[quantile]))\n # scipy minimize enforces constraints are non-negative so use negative here\n # to enforce lower bound\n return -val\n\nfrom pyapprox.cvar_regression import smooth_conditional_value_at_risk, \\\n conditional_value_at_risk\ndef cvar_lower_bound_constraint(constraint_function,quantile,lower_bound,eps,\n uq_samples,design_samples):\n uq_samples,design_samples = check_inputs(uq_samples,design_samples)\n assert design_samples.shape[1]==1\n vals = constraint_function(uq_samples,design_samples)\n # -vals because we want to minimize lower tail\n val = (lower_bound-smooth_conditional_value_at_risk(0,eps,quantile,-vals))\n #val = (lower_bound-conditional_value_at_risk(-vals,quantile))\n return val\n\nclass MultipleConstraints(object):\n def __init__(self,constraints):\n self.constraints=constraints\n\n def __call__(self,design_sample,constraint_idx=None):\n if constraint_idx is None:\n constraint_idx = np.arange(len(self.constraints))\n nconstraints = len(constraint_idx)\n vals = np.empty(nconstraints)\n for ii,jj in enumerate(constraint_idx):\n vals[ii]=self.constraints[jj](design_sample)\n return vals\n\nclass MCStatisticConstraint(object):\n def __init__(self,constraint_function,generate_samples,info):\n self.constraint_function = constraint_function\n self.generate_samples=generate_samples\n self.info=info\n\n def __call__(self,design_samples):\n uq_samples = self.generate_samples()\n constraint_type=self.info['type']\n if constraint_type=='quantile':\n quantile = self.info['quantile']\n lower_bound = self.info['lower_bound']\n return quantile_lower_bound_constraint(\n self.constraint_function,quantile,lower_bound,\n uq_samples,design_samples)\n elif constraint_type=='cvar':\n quantile = self.info['quantile']\n lower_bound = self.info['lower_bound']\n eps = self.info['smoothing_eps']\n return cvar_lower_bound_constraint(\n constraint_functions[ii], quantile, lower_bound, eps,\n uq_samples, design_samples)\n elif constraint_type=='var':\n var_lower_bound = self.info['lower_bound']\n return variance_lower_bound_constraint(\n constraint_functions[ii],lower_bound,uq_samples,design_samples)\n else:\n raise Exception(\n 'constraint type (%s) not implemented'%constraint_type[ii])\n\nclass DeterministicConstraint(object):\n def __init__(self,constraint_function,info):\n self.constraint_function = constraint_function\n self.info=info\n\n def __call__(self,design_samples):\n lower_bound = self.info['lower_bound']\n uq_nominal_sample = self.info['uq_nominal_sample']\n return deterministic_lower_bound_constraint(\n self.constraint_function,lower_bound,uq_nominal_sample,\n design_samples)\n \ndef setup_inequality_constraints(constraint_functions,constraints_info,\n uq_samples):\n constraints = []\n for ii in range(len(constraint_functions)):\n info = constraints_info[ii]\n constraint_type = info['type']\n if constraint_type=='quantile':\n quantile = info['quantile']\n quantile_lower_bound = info['quantile_lower_bound']\n ineq_cons_fun = partial(\n quantile_lower_bound_constraint, constraint_functions[ii],\n quantile, quantile_lower_bound, uq_samples)\n elif constraint_type=='cvar':\n quantile = info['quantile']\n quantile_lower_bound = info['cvar_lower_bound']\n eps = info['smoothing_eps']\n ineq_cons_fun = partial(\n cvar_lower_bound_constraint, constraint_functions[ii],\n quantile, quantile_lower_bound, eps, uq_samples)\n elif constraint_type=='var':\n var_lower_bound = info['var_lower_bound']\n ineq_cons_fun = partial(\n variance_lower_bound_constraint, constraint_functions[ii],\n var_lower_bound, uq_samples)\n elif constraint_type=='deterministic':\n lower_bound = info['lower_bound']\n ineq_cons_fun = partial(\n deterministic_lower_bound_constraint, constraint_functions[ii],\n lower_bound, uq_samples)\n else:\n raise Exception(\n 'constraint type (%s) not implemented'%constraint_type[ii])\n ineq_cons = {'type': 'ineq', 'fun' : ineq_cons_fun}\n constraints.append(ineq_cons)\n return constraints\n\ndef run_design(objective, init_design_sample,\n constraints, bounds, optim_options):\n\n opt_history = [init_design_sample[:,0]]\n def callback(xk):\n opt_history.append(xk)\n #print(objective(xk))\n #print([constraints[ii]['fun'](xk) for ii in [0,1]])\n\n # opt_method = 'SLSQP'\n # res = minimize(\n # objective, init_design_sample[:,0], method=opt_method, jac=None,\n # constraints=constraints,\n # options=optim_options,bounds=bounds,callback=callback)\n\n from scipy.optimize import fmin_slsqp\n res = fmin_slsqp(objective, init_design_sample[:,0], f_ieqcons=constraints,\n bounds=bounds, callback=callback, full_output=True)#, **optim_options)\n class result():\n def __init__(self,x,fun):\n self.x=np.atleast_1d(x)\n self.fun=fun\n res = result(res[0],res[1])\n\n opt_history = (np.array(opt_history)).T\n return res, opt_history\n\ndef plot_optimization_history(obj_function,constraints,uq_samples,opt_history,\n plot_limits):\n\n # fig,axs=plot_optimization_objective_and_constraints_2D(\n # [constraints[ii]['fun'] for ii in range(len(constraints))],\n # partial(obj_function,uq_samples[:,0]),plot_limits)\n\n fig,axs=plot_optimization_objective_and_constraints_2D(\n constraints,partial(obj_function,uq_samples[:,0]),plot_limits)\n # objective can only be evaluated at one uq_sample thus use of\n # uq_samples[:,0]\n \n for ii in range(len(axs)):\n axs[ii].plot(opt_history[0,:],opt_history[1,:],'ko')\n for jj, txt in enumerate(range(opt_history.shape[1])):\n axs[ii].annotate(\n '%d'%txt,(opt_history[0,jj],opt_history[1,jj]))\n return fig,axs\n\n#def plot_optimization_objective_and_constraints_2D(\n# constraint_functions,objective,plot_limits):\n\ndef plot_optimization_objective_and_constraints_2D(\n constraints,objective,plot_limits):\n from pyapprox.visualization import get_meshgrid_function_data\n num_pts_1d = 100; num_contour_levels=30\n fig,axs=plt.subplots(1,3,figsize=(3*8,6))\n #for ii in range(len(constraint_functions)+1):\n for ii in range(len(constraints.constraints)+1):\n\n #if ii==len(constraint_functions):\n if ii==len(constraints.constraints):\n function=objective\n else:\n # def function(design_samples):\n # vals = np.empty((design_samples.shape[1]))\n # for jj in range(design_samples.shape[1]):\n # vals[jj]=constraint_functions[ii](design_samples[:,jj])\n # return vals\n def function(design_samples):\n vals = np.empty((design_samples.shape[1]))\n for jj in range(design_samples.shape[1]):\n vals[jj]=constraints(design_samples[:,jj],[ii])\n return vals\n \n X,Y,Z = get_meshgrid_function_data(\n function, plot_limits, num_pts_1d)\n norm = None\n cset = axs[ii].contourf(\n X, Y, Z, levels=np.linspace(Z.min(),Z.max(),num_contour_levels),\n cmap=mpl.cm.coolwarm,\n norm=norm)\n #for kk in range(len(constraint_functions)):\n for kk in range(len(constraints.constraints)):\n if ii==kk:\n ls = '-'\n else:\n ls = '--'\n axs[kk].contour(X,Y,Z,levels=[0],colors='k',linestyles=ls)\n plt.colorbar(cset,ax=axs[ii])\n\n return fig,axs\n\ndef plot_constraint_pdfs(constraint_functions,uq_samples,design_sample,\n fig_pdf=None,axs_pdf=None,label=None,color=None):\n colors = ['b','gray']\n nconstraints = len(constraint_functions)\n if axs_pdf is None:\n fig_pdf,axs_pdf = plt.subplots(1,nconstraints,figsize=(nconstraints*8,6))\n for ii in range(nconstraints):\n # evaluate constraint function at each of the uq samples\n constraint_function_vals = constraint_functions[ii](\n uq_samples,design_sample)\n\n constraint_kde = KDE(constraint_function_vals)\n yy = np.linspace(constraint_function_vals.min(),\n constraint_function_vals.max(),101)\n\n axs_pdf[ii].fill_between(yy,0,constraint_kde(yy),alpha=0.5,label=label,\n color=color)\n axs_pdf[ii].axvline(0,color='k')\n #axs_pdf[ii].axvline(constraints[ii]['fun'](design_sample),color='r')\n return fig_pdf,axs_pdf\n \ndef plot_constraint_cdfs(constraints,constraint_functions,uq_samples,\n design_sample,quantile,fig_cdf,axs_cdf=None,label=None,\n color=None):\n nconstraints = len(constraint_functions)\n if axs_cdf is None:\n fig_cdf,axs_cdf = plt.subplots(\n 1,nconstraints,figsize=(nconstraints*8,6))\n\n for ii in range(nconstraints):\n constraint_function_vals = constraint_functions[ii](\n uq_samples,design_sample)\n\n cvar = (conditional_value_at_risk(-constraint_function_vals,0.9))\n cvars = (smooth_conditional_value_at_risk(0,1e-3,0.9,-constraint_function_vals))\n print ('cvar',cvar)\n print ('cvars',cvars)\n #constraint_val = constraints[ii]['fun'](design_sample)\n constraint_val = constraints(design_sample,[ii])\n constraint_function_vals.sort()\n cdf_vals = np.linspace(0,1,constraint_function_vals.shape[0]+1)[1:]\n axs_cdf[ii].plot(constraint_function_vals,cdf_vals,label=label,\n color=color)\n #I = np.where(constraint_function_vals<=constraint_val)[0]\n I = np.where(constraint_function_vals<=0)[0]\n axs_cdf[ii].fill_between(\n constraint_function_vals[I],0,cdf_vals[I],alpha=0.5,color=color)\n axs_cdf[ii].axvline(0,color='k')\n J = np.where(constraint_function_vals<=0)[0]\n #print (J.shape[0]/float(constraint_function_vals.shape[0]),'p failure',constraint_val,J.shape[0])\n # Compute the constraint value. This combines constraint_function_vals\n # into a scalar value\n #axs_cdf[ii].axvline(constraint_val,color='r')\n #axs_cdf[ii].plot(\n # np.linspace(constraint_function_vals[0],constraint_val,101),\n # quantile*np.ones(101),'-r')\n #axs_cdf[ii].set_yticks(list(axs_cdf[ii].get_yticks()) + [quantile])\n axs_cdf[ii].set_ylim(0,1.05)\n axs_cdf[ii].set_xlim(\n constraint_function_vals[0],constraint_function_vals[-1])\n return fig_cdf, axs_cdf\n\n\ndef check_gradients(fun, jac, zz, plot=False, disp=True, rel=True):\n \"\"\"\n Compare a user specified jacobian with the jacobian computed with finite\n difference with multiple step sizes.\n\n Parameters\n ---------\n fun : callable\n\n A function with signature\n\n ``fun(z) -> np.ndarray``\n\n where ``z`` is a 2D np.ndarray with shape (nvars, 1) and the\n output is a 2D np.ndarray with shape (nqoi, 1)\n\n jac : callable\n The jacobian of ``fun`` with signature\n\n ``jac(z) -> np.ndarray``\n\n where ``z`` is a 2D np.ndarray with shape (nvars, 1) and the\n output is a 2D np.ndarray with shape (nqoi, nvars)\n\n zz : np.ndarray (nvars, 1)\n A sample of ``z`` at which to compute the gradient\n\n plot : boolean\n Plot the errors as a function of the finite difference step size\n\n disp : boolean\n True - print the errors\n False - do not print\n\n rel : boolean\n True - compute the relative error in the directional derivative, \n i.e. the absolute error divided by the directional derivative using \n ``jac``.\n False - compute the absolute error in the directional derivative\n\n Returns\n -------\n errors : np.ndarray (14, nqoi)\n The errors in the directional derivative of ``fun`` at 14 different \n values of finite difference tolerance for each quantity of interest\n \"\"\"\n assert zz.ndim == 2\n assert zz.shape[1] == 1\n if callable(jac):\n function_val = fun(zz)\n grad_val = jac(zz)\n elif jac==True:\n function_val, grad_val = fun(zz)\n direction = np.random.normal(0, 1, (zz.shape[0], 1))\n direction /= np.linalg.norm(direction)\n directional_derivative = grad_val.squeeze().dot(direction).squeeze()\n fd_eps = np.logspace(-13, 0, 14)[::-1]\n errors = []\n row_format = \"{:<25} {:<25} {:<25}\"\n if disp:\n if rel:\n print(\n row_format.format(\n \"Eps\", \"Rel. Errors (max)\", \"Rel. Errors (min)\"))\n else:\n print(row_format.format(\"Eps\", \"Errors (max)\", \"Errors (min)\"))\n for ii in range(fd_eps.shape[0]):\n zz_perturbed = zz.copy()+fd_eps[ii]*direction\n perturbed_function_val = fun(zz_perturbed)\n if jac==True:\n perturbed_function_val = perturbed_function_val[0].squeeze()\n fd_directional_derivative = (\n perturbed_function_val-function_val).squeeze()/fd_eps[ii]\n errors.append(np.absolute(\n fd_directional_derivative.reshape(directional_derivative.shape)-\n directional_derivative))\n if rel:\n errors[-1]/=np.absolute(directional_derivative)\n if disp:\n print(row_format.format(fd_eps[ii], errors[ii].max(),\n errors[ii].min()))\n #print(fd_directional_derivative, directional_derivative)\n\n if plot:\n plt.loglog(fd_eps, errors, 'o-')\n plt.ylabel(r'$\\lvert\\nabla_\\epsilon f\\cdot p-\\nabla f\\cdot p\\rvert$')\n plt.xlabel(r'$\\epsilon$')\n plt.show()\n\n return np.asarray(errors)\n\ndef check_hessian(jac,hessian_matvec,zz,plot=False,disp=True):\n \"\"\"\n Compare a user specified Hessian matrix-vector product with the \n Hessian matrix vector produced computed with finite\n difference with multiple step sizes using a user specified jacobian.\n\n Parameters\n ---------\n jac : callable\n The jacobian with signature\n\n ``jac(z) -> np.ndarray``\n\n where ``z`` is a 2D np.ndarray with shape (nvars,1) and the\n output is a 2D np.ndarray with shape (nqoi,nvars)\n\n hessian_matvec : callable\n A function implementing the hessian matrix-vector product with signature\n\n ``hessian_matvec(z,p) -> np.ndarray``\n\n where ``z`` is a 2D np.ndarray with shape (nvars,1), ``p`` is\n an arbitrary vector with shape (nvars,1) and the\n output is a 2D np.ndarray with shape (nqoi,nvars)\n\n zz : np.ndarray (nvars,1)\n A sample of ``z`` at which to compute the gradient\n\n plot : boolean\n Plot the errors as a function of the finite difference step size\n\n disp : boolean\n True - print the errors\n False - do not print\n\n rel : boolean\n True - compute the relative error in the directional derivative, \n i.e. the absolute error divided by the directional derivative using \n ``jac``.\n False - compute the absolute error in the directional derivative\n\n Returns\n -------\n errors : np.ndarray (14,nqoi)\n The errors in the directional derivative of ``jac`` at 14 different \n values of finite difference tolerance for each quantity of interest\n \"\"\"\n assert zz.ndim==2\n assert zz.shape[1]==1\n grad = jac(zz)\n direction = np.random.normal(0,1,(zz.shape[0],1))\n direction /= np.linalg.norm(direction)\n directional_derivative = hessian_matvec(zz,direction)\n fd_eps = np.logspace(-13,0,14)[::-1]\n errors = []\n row_format = \"{:<25} {:<25} {:<25}\"\n if disp:\n print(row_format.format(\"Eps\",\"Errors (max)\",\"Errors (min)\"))\n for ii in range(fd_eps.shape[0]):\n zz_perturbed = zz.copy()+fd_eps[ii]*direction\n perturbed_grad = jac(zz_perturbed)\n fd_directional_derivative = (perturbed_grad-grad)/fd_eps[ii]\n errors.append(np.absolute(\n fd_directional_derivative-directional_derivative))\n if disp:\n print(row_format.format(fd_eps[ii],errors[ii].max(),\n errors[ii].min()))\n #print(fd_directional_derivative,directional_derivative)\n\n if plot:\n plt.loglog(fd_eps,errors,'o-')\n plt.ylabel(r'$\\lvert\\nabla^2_\\epsilon \\cdot p f-\\nabla^2 f\\cdot p\\rvert$')\n plt.xlabel(r'$\\epsilon$')\n plt.show()\n\n return np.asarray(errors)\n\ndef expectation_fun(values,weights):\n assert values.shape[0]%weights.shape[0]==0\n nqoi = values.shape[0]//weights.shape[0]\n nsamples = values.shape[0]//nqoi\n assert nqoi==1\n fun_vals = (values.T.dot(weights)).T\n return fun_vals\n\ndef expectation_jac(jac_values,weights):\n assert jac_values.shape[0]%weights.shape[0]==0\n nqoi = jac_values.shape[0]//weights.shape[0]\n nsamples = jac_values.shape[0]//nqoi\n num_vars = jac_values.shape[1]\n assert nqoi==1\n jac = (jac_values.T.dot(weights)).T\n return jac\n\nfrom pyapprox.cvar_regression import smooth_max_function_first_derivative,\\\n smooth_max_function_second_derivative\ndef smooth_prob_failure_fun(smoother_type,eps,tol,values,weights):\n assert values.shape[0]%weights.shape[0]==0\n nqoi = values.shape[0]//weights.shape[0]\n assert nqoi==1\n nsamples = values.shape[0]//nqoi\n heaviside_vals = smooth_max_function_first_derivative(\n smoother_type,eps,values-tol)\n fun_vals = (heaviside_vals.dot(weights)).T\n #print(fun_vals.shape)\n return fun_vals\n\ndef smooth_prob_failure_jac(smoother_type,eps,tol,jac_values,weights):\n assert jac_values.shape[0]%weights.shape[0]==0\n nqoi = jac_values.shape[0]//weights.shape[0]\n assert nqoi==1\n nsamples = jac_values.shape[0]//nqoi\n num_vars = jac_values.shape[1]\n grad_heaviside_vals = smooth_max_function_second_derivative(\n smoother_type,eps,jac_values-tol)\n jac = (grad_heaviside_vals*jac_values).T.dot(weights)[np.newaxis,:]\n print(jac_values.max(axis=0),'m',eps)\n\n return jac\n\ndef generate_monte_carlo_quadrature_data(\n generate_random_samples,num_vars,design_var_indices,fun,seed=None):\n if seed is not None:\n np.random.seed(seed)\n samples = generate_random_samples()\n weights = np.ones(samples.shape[1])/samples.shape[1]\n values = fun(samples)\n return samples,weights,values\n\nfrom pyapprox.models.wrappers import ActiveSetVariableModel\nclass StatisticalConstraint(object):\n \"\"\"\n Notes\n -----\n TODO ensure the following.\n\n This class unifies the jac=True and callable(jac)=True interfaces.\n The interface is used for passing to optimizers that need the fun and jac functions\n to be separate. This is often good practice as it avoids computing \n jac when only fun is required.\n If jac=True the jacobian is stored and returned when self.jac is called\n \"\"\"\n \n def __init__(self,fun,jac,stats_fun,stats_jac,num_vars,\n design_var_indices,generate_sample_data,bound=None,\n upper_bound=True,isobjective=False):\n self.fun,self.jac,self.stats_fun=fun,jac,stats_fun\n self.stats_jac=stats_jac\n self.num_vars=num_vars\n self.design_var_indices=design_var_indices\n self.random_var_indices = np.delete(\n np.arange(self.num_vars),self.design_var_indices)\n self.generate_sample_data=generate_sample_data\n self.bound=bound\n self.upper_bound=upper_bound\n self.isobjective=isobjective\n\n self.design_sample = None\n self.jac_values = None\n self.samples = None\n \n if self.stats_jac is not None and self.jac is None:\n msg = 'stats_jac requries jac to be defined'\n raise Exception(msg)\n if self.jac is not None and self.stats_jac is None:\n msg = 'jac will be ignored because stats_jac was not defined'\n raise Exception(msg)\n\n def generate_shared_data(self,design_sample):\n self.design_sample=design_sample.copy()\n\n fun = ActiveSetVariableModel(self.fun,self.num_vars,design_sample,\n self.random_var_indices)\n data = self.generate_sample_data(fun)\n self.samples,self.weights,self.fun_values = data[:3]\n assert self.samples.shape[0]==\\\n self.num_vars-self.design_var_indices.shape[0]\n assert self.samples.shape[1]==self.weights.shape[0]\n #assert self.samples.shape[1]==self.fun_values.shape[0]\n if not callable(self.jac) and self.jac:\n # consider whether to support self.jac=True. It seems appealing\n # if using gradients from adjoint PDE simulation which requires \n # data used to compute function values and thus better to do at the\n # time the function values are obtained. Challenge is defining the\n # correct output interface and only computing gradients if self.jac\n # has been called and not if self.__call__ is called.\n raise Exception (\"Not yet implemented\")\n self.jac_values = data[3]\n \n def __call__(self,design_sample):\n if design_sample.ndim==1:\n design_sample = design_sample[:,np.newaxis]\n self.generate_shared_data(design_sample)\n nsamples = self.weights.shape[0]\n nqoi = self.fun_values.shape[1]\n #print(self.fun_values)\n values = np.empty((nqoi))\n for ii in range(nqoi):\n values[ii] = self.stats_fun(\n self.fun_values[:,ii:ii+1],self.weights)\n \n #print('b',np.where(self.fun_values[:,ii:ii+1]>0)[0].shape[0]/nsamples)\n #print('c',values[ii])\n #print(self.fun_values.min(),self.fun_values.max())\n if self.bound is not None:\n values = values-self.bound\n if self.upper_bound:\n values *= -1\n if self.isobjective:\n values= values[0]\n return values\n\n def jacobian(self,design_sample):\n if design_sample.ndim==1:\n design_sample = design_sample[:,np.newaxis]\n if (np.array_equal(design_sample,self.design_sample) and\n self.jac_values is not None):\n jac_values = self.jac_values\n else:\n jac = ActiveSetVariableModel(\n self.jac,self.num_vars,self.samples,self.design_var_indices)\n jac_values = jac(design_sample)\n nsamples = self.weights.shape[0]\n nqoi = self.fun_values.shape[1]\n nvars = jac_values.shape[1]\n constraint_jac = np.empty((nqoi,nvars))\n for ii in range(nqoi):\n constraint_jac[ii] = self.stats_jac(\n jac_values[ii*nsamples:(ii+1)*nsamples,:],self.weights)\n if self.bound is not None and self.upper_bound:\n constraint_jac *= -1\n return constraint_jac.squeeze()\n\nclass PyapproxFunctionAsScipyMinimizeObjective(object):\n def __init__(self,fun):\n self.fun=fun\n def __call__(self,scipy_sample):\n assert scipy_sample.ndim==1\n data = self.fun(scipy_sample[:,np.newaxis])\n if not np.isscalar(data):\n assert len(data)==2\n val = data[0]\n assert np.isscalar(val)\n assert data[1].ndim==2 and data[1].shape[0]==1\n jac = data[1][0,:]\n return val,jac\n return data\n\nclass ScipyMinimizeObjectiveAsPyapproxFunction(object):\n def __init__(self,fun):\n self.fun=fun\n def __call__(self,pyapprox_sample):\n assert pyapprox_sample.ndim==2 and pyapprox_sample.shape[1]==1\n data = self.fun(pyapprox_sample[:,0])\n if not np.isscalar(data):\n assert len(data)==2\n val = data[0]\n assert np.isscalar(val)\n assert data[1].ndim==2 and data[1].shape[0]==1\n jac = data[1][0,:]\n return val,jac\n return data\n\nclass ScipyMinimizeObjectiveJacAsPyapproxJac(object):\n def __init__(self,jac):\n self.jac=jac\n def __call__(self,pyapprox_sample):\n assert pyapprox_sample.ndim==2 and pyapprox_sample.shape[1]==1\n grad = self.jac(pyapprox_sample[:,0])\n return grad[np.newaxis,:]\n",
"import unittest\nfrom pyapprox.gaussian_process import *\nfrom sklearn.gaussian_process.kernels import Matern, WhiteKernel, RBF\nimport pyapprox as pya\nfrom scipy import stats\nfrom scipy.linalg import solve_triangular\nfrom scipy.spatial.distance import cdist\nimport copy\nimport time\n\n\ndef compute_mean_and_variance_of_gaussian_process(gp, length_scale,\n train_samples,\n A_inv, kernel_var,\n train_vals, quad_samples,\n quad_weights):\n # just use for testing purposes\n # computing variance_of_variance requires splitting up terms\n # like done in code so no point computing this quantity as it cannot\n # test if the splitting procedure is correct.\n nvars = quad_samples.shape[0]\n gp_vals, gp_std = gp(quad_samples, return_std=True)\n gp_vals = gp_vals[:, 0]\n mean_of_mean = gp_vals.dot(quad_weights)\n quad_samples_WWXX = pya.get_all_sample_combinations(\n quad_samples, quad_samples)\n quad_weights_WWXX = pya.outer_product([quad_weights]*2)\n\n L = np.linalg.cholesky(A_inv)\n\n ww, xx = quad_samples_WWXX[:nvars], quad_samples_WWXX[nvars:]\n dists_ww_xx = np.sum((ww.T/length_scale-xx.T/length_scale)**2, axis=1)\n dists_ww_tt = cdist(train_samples.T/length_scale, ww.T/length_scale,\n metric='sqeuclidean')\n dists_xx_tt = cdist(train_samples.T/length_scale, xx.T/length_scale,\n metric='sqeuclidean')\n t_ww = np.exp(-.5*dists_ww_tt)\n t_xx = np.exp(-.5*dists_xx_tt)\n prior_cov_ww_xx = kernel_var*np.exp(-.5*dists_ww_xx)\n post_cov_ww_xx = prior_cov_ww_xx - kernel_var*np.sum(\n t_ww.T.dot(L)*t_xx.T.dot(L), axis=1)\n\n variance_of_mean = post_cov_ww_xx.dot(quad_weights_WWXX)\n\n mean_of_variance = (gp_vals**2+gp_std**2).dot(quad_weights) - (\n variance_of_mean+mean_of_mean**2)\n\n return mean_of_mean, variance_of_mean, mean_of_variance\n\n\ndef compute_intermediate_quantities_with_monte_carlo(mu_scalar, sigma_scalar,\n length_scale,\n train_samples,\n A_inv, kernel_var,\n train_vals):\n nsamples_mc = 20000\n nvars = length_scale.shape[0]\n xx = np.random.normal(mu_scalar, sigma_scalar, (nvars, nsamples_mc))\n yy = np.random.normal(mu_scalar, sigma_scalar, (nvars, nsamples_mc))\n zz = np.random.normal(mu_scalar, sigma_scalar, (nvars, nsamples_mc))\n dists_xx_tt = cdist(train_samples.T/length_scale, xx.T/length_scale,\n metric='sqeuclidean')\n dists_yy_tt = cdist(train_samples.T/length_scale, yy.T/length_scale,\n metric='sqeuclidean')\n dists_zz_tt = cdist(train_samples.T/length_scale, zz.T/length_scale,\n metric='sqeuclidean')\n dists_xx_yy = np.sum((xx.T/length_scale-yy.T/length_scale)**2, axis=1)\n dists_xx_zz = np.sum((xx.T/length_scale-zz.T/length_scale)**2, axis=1)\n t_xx = np.exp(-.5*dists_xx_tt)\n t_yy = np.exp(-.5*dists_yy_tt)\n t_zz = np.exp(-.5*dists_zz_tt)\n\n mean_gp_xx = t_xx.T.dot(A_inv.dot(train_vals))*kernel_var\n mean_gp_yy = t_yy.T.dot(A_inv.dot(train_vals))*kernel_var\n prior_cov_xx_xx = np.ones((xx.shape[1]))\n L = np.linalg.cholesky(A_inv)\n post_cov_xx_xx = prior_cov_xx_xx - np.sum(\n (t_xx.T.dot(L))**2, axis=1)\n prior_cov_xx_yy = np.exp(-.5*dists_xx_yy)\n post_cov_xx_yy = prior_cov_xx_yy - np.sum(\n t_xx.T.dot(L)*t_yy.T.dot(L), axis=1)\n # assert np.allclose(np.sum(\n # t_xx.T.dot(L)*t_yy.T.dot(L),axis=1),np.diag(t_xx.T.dot(A_inv).dot(t_yy)))\n prior_cov_xx_zz = np.exp(-.5*dists_xx_zz)\n post_cov_xx_zz = prior_cov_xx_zz - np.sum(\n t_xx.T.dot(L)*t_zz.T.dot(L), axis=1)\n\n eta_mc = mean_gp_xx.mean()\n varrho_mc = (mean_gp_xx*post_cov_xx_yy).mean()\n phi_mc = (mean_gp_xx*mean_gp_yy*post_cov_xx_yy).mean()\n CC_mc = (post_cov_xx_yy*post_cov_xx_zz).mean()\n chi_mc = (post_cov_xx_yy**2).mean()\n M_sq_mc = (mean_gp_xx**2).mean()\n v_sq_mc = (post_cov_xx_xx).mean()\n varsigma_sq_mc = (post_cov_xx_yy).mean()\n P_mc = (t_xx.dot(t_xx.T))/xx.shape[1]\n lamda_mc = (prior_cov_xx_yy*t_yy).mean(axis=1)\n CC1_mc = (prior_cov_xx_yy*prior_cov_xx_zz).mean()\n Pi_mc = np.zeros((train_samples.shape[1], train_samples.shape[1]))\n for ii in range(train_samples.shape[1]):\n for jj in range(ii, train_samples.shape[1]):\n Pi_mc[ii, jj] = (prior_cov_xx_yy*t_xx[ii, :]*t_yy[jj, :]).mean()\n Pi_mc[jj, ii] = Pi_mc[ii, jj]\n\n return eta_mc, varrho_mc, phi_mc, CC_mc, chi_mc, M_sq_mc, v_sq_mc, \\\n varsigma_sq_mc, P_mc, lamda_mc, CC1_mc, Pi_mc\n\n\ndef verify_quantities(reference_quantities, quantities, tols):\n assert len(reference_quantities) == len(quantities) == len(tols)\n ii = 0\n for q_ref, q, tol in zip(reference_quantities, quantities, tols):\n assert np.allclose(q_ref, q, rtol=tol), (ii, q_ref, q, tol)\n ii += 1\n\n\nclass TestGaussianProcess(unittest.TestCase):\n def setUp(self):\n np.random.seed(1)\n\n def test_gaussian_process_pointwise_variance(self):\n nvars = 1\n lb, ub = 0, 1\n ntrain_samples = 5\n def func(x): return np.sum(x**2, axis=0)[:, np.newaxis]\n\n train_samples = pya.cartesian_product(\n [np.linspace(lb, ub, ntrain_samples)]*nvars)\n train_vals = func(train_samples)\n\n kernel = Matern(0.4, length_scale_bounds='fixed', nu=np.inf)\n kernel = ConstantKernel(\n constant_value=2., constant_value_bounds='fixed')*kernel\n kernel += WhiteKernel(noise_level=1e-5, noise_level_bounds='fixed')\n gp = GaussianProcess(kernel)\n\n gp.fit(train_samples, train_vals)\n\n samples = np.random.uniform(0, 1, (nvars, 100))\n pred_vals, stdev1 = gp(samples, return_std=True)\n\n variance2 = gaussian_process_pointwise_variance(\n kernel, samples, train_samples)\n\n assert np.allclose(stdev1**2, variance2)\n\n def test_integrate_gaussian_process_gaussian(self):\n\n nvars = 2\n def func(x): return np.sum(x**2, axis=0)[:, np.newaxis]\n\n mu_scalar, sigma_scalar = 3, 1\n # mu_scalar, sigma_scalar = 0, 1\n\n univariate_variables = [stats.norm(mu_scalar, sigma_scalar)]*nvars\n variable = pya.IndependentMultivariateRandomVariable(\n univariate_variables)\n\n lb, ub = univariate_variables[0].interval(0.99999)\n\n ntrain_samples = 5\n # ntrain_samples = 20\n\n train_samples = pya.cartesian_product(\n [np.linspace(lb, ub, ntrain_samples)]*nvars)\n train_vals = func(train_samples)\n\n nu = np.inf\n nvars = train_samples.shape[0]\n length_scale = np.array([1]*nvars)\n kernel = Matern(length_scale, length_scale_bounds=(1e-2, 10), nu=nu)\n # fix kernel variance\n kernel = ConstantKernel(\n constant_value=2., constant_value_bounds='fixed')*kernel\n # optimize kernel variance\n # kernel = ConstantKernel(\n # constant_value=3,constant_value_bounds=(0.1, 10))*kernel\n # optimize gp noise\n # kernel += WhiteKernel(noise_level_bounds=(1e-8, 1))\n # fix gp noise\n kernel += WhiteKernel(noise_level=1e-5, noise_level_bounds='fixed')\n # white kernel K(x_i,x_j) is only nonzeros when x_i=x_j, i.e.\n # it is not used when calling gp.predict\n gp = GaussianProcess(kernel, n_restarts_optimizer=10)\n gp.fit(train_samples, train_vals)\n # print(gp.kernel_)\n\n # xx=np.linspace(lb,ub,101)\n # plt.plot(xx,func(xx[np.newaxis,:]))\n # gp_mean,gp_std = gp(xx[np.newaxis,:],return_std=True)\n # gp_mean = gp_mean[:,0]\n # plt.plot(xx,gp_mean)\n # plt.plot(train_samples[0,:],train_vals[:,0],'o')\n # plt.fill_between(xx,gp_mean-2*gp_std,gp_mean+2*gp_std,alpha=0.5)\n # plt.show()\n\n import time\n t0 = time.time()\n expected_random_mean, variance_random_mean, expected_random_var,\\\n variance_random_var, intermediate_quantities =\\\n integrate_gaussian_process(gp, variable, return_full=True)\n print('time', time.time()-t0)\n\n # mu and sigma should match variable\n kernel_types = [Matern]\n kernel = extract_covariance_kernel(gp.kernel_, kernel_types)\n length_scale = np.atleast_1d(kernel.length_scale)\n constant_kernel = extract_covariance_kernel(\n gp.kernel_, [ConstantKernel])\n if constant_kernel is not None:\n kernel_var = constant_kernel.constant_value\n else:\n kernel_var = 1\n\n Kinv_y = gp.alpha_\n mu = np.array([mu_scalar]*nvars)[:, np.newaxis]\n sigma = np.array([sigma_scalar]*nvars)[:, np.newaxis]\n # Notes sq exp kernel is exp(-dists/delta). Sklearn RBF kernel is\n # exp(-.5*dists/L**2)\n delta = 2*length_scale[:, np.newaxis]**2\n\n # Kinv_y is inv(kernel_var*A).dot(y). Thus multiply by kernel_var to\n # get formula in notes\n Ainv_y = Kinv_y*kernel_var\n L_inv = solve_triangular(gp.L_.T, np.eye(gp.L_.shape[0]), lower=False)\n K_inv = L_inv.dot(L_inv.T)\n # K_inv is inv(kernel_var*A). Thus multiply by kernel_var to get A_inv\n A_inv = K_inv*kernel_var\n\n # Verify quantities used to compute mean and variance of mean of GP\n # This is redundant know but helped to isolate incorrect terms\n # when initialing writing tests\n tau_true = gaussian_tau(train_samples, delta, mu, sigma)\n u_true = gaussian_u(delta, sigma)\n varpi_true = compute_varpi(tau_true, A_inv)\n varsigma_sq_true = compute_varsigma_sq(u_true, varpi_true)\n verify_quantities(\n [tau_true, u_true, varpi_true, varsigma_sq_true],\n intermediate_quantities[:4], [1e-8]*4)\n\n # Verify mean and variance of mean of GP\n true_expected_random_mean = tau_true.dot(Ainv_y)\n true_variance_random_mean = variance_of_mean(\n kernel_var, varsigma_sq_true)\n assert np.allclose(\n true_expected_random_mean, expected_random_mean)\n # print(true_variance_random_mean,variance_random_mean)\n assert np.allclose(\n true_variance_random_mean, variance_random_mean)\n\n # Verify quantities used to compute mean of variance of GP\n # This is redundant know but helped to isolate incorrect terms\n # when initialing writing tests\n P_true = gaussian_P(train_samples, delta, mu, sigma)\n v_sq_true = compute_v_sq(A_inv, P_true)\n zeta_true = compute_zeta(train_vals, A_inv, P_true)\n verify_quantities(\n [P_true, v_sq_true], intermediate_quantities[4:6], [1e-8]*2)\n\n true_expected_random_var = mean_of_variance(\n zeta_true, v_sq_true, kernel_var, true_expected_random_mean,\n true_variance_random_mean)\n assert np.allclose(true_expected_random_var, expected_random_var)\n\n # Verify quantities used to compute variance of variance of GP\n # This is redundant know but helped to isolate incorrect terms\n # when initialing writing tests\n nu_true = gaussian_nu(delta, sigma)\n varphi_true = compute_varphi(A_inv, P_true)\n Pi_true = gaussian_Pi(train_samples, delta, mu, sigma)\n psi_true = compute_psi(A_inv, Pi_true)\n chi_true = compute_chi(nu_true, varphi_true, psi_true)\n phi_true = compute_phi(train_vals, A_inv, Pi_true, P_true)\n lamda_true = gaussian_lamda(train_samples, delta, mu, sigma)\n varrho_true = compute_varrho(\n lamda_true, A_inv, train_vals, P_true, tau_true)\n xi_1_true = gaussian_xi_1(delta, sigma)\n xi_true = compute_xi(xi_1_true, lamda_true, tau_true, P_true, A_inv)\n verify_quantities(\n [zeta_true, nu_true, varphi_true, Pi_true, psi_true, chi_true,\n phi_true, lamda_true, varrho_true, xi_1_true, xi_true],\n intermediate_quantities[6:17], [1e-8]*11)\n\n if nvars == 1:\n nxx = 100\n else:\n nxx = 15\n xx, ww = pya.gauss_hermite_pts_wts_1D(nxx)\n xx = xx*sigma_scalar + mu_scalar\n quad_points = pya.cartesian_product([xx]*nvars)\n quad_weights = pya.outer_product([ww]*nvars)\n mean_of_mean_quad, variance_of_mean_quad, mean_of_variance_quad = \\\n compute_mean_and_variance_of_gaussian_process(\n gp, length_scale, train_samples, A_inv, kernel_var, train_vals,\n quad_points, quad_weights)\n\n assert np.allclose(mean_of_mean_quad, expected_random_mean)\n assert np.allclose(variance_of_mean_quad, variance_random_mean)\n assert np.allclose(mean_of_variance_quad, expected_random_var)\n\n nsamples = 4000\n random_means, random_variances = [], []\n random_I2sq, random_I4, random_I2Isq = [], [], []\n xx, ww = pya.gauss_hermite_pts_wts_1D(nxx)\n xx = xx*sigma_scalar + mu_scalar\n quad_points = pya.cartesian_product([xx]*nvars)\n quad_weights = pya.outer_product([ww]*nvars)\n for ii in range(nsamples):\n vals = gp.predict_random_realization(quad_points)[:, 0]\n I, I2 = vals.dot(quad_weights), (vals**2).dot(quad_weights)\n random_means.append(I)\n random_variances.append(I2-I**2)\n random_I2sq.append(I2**2)\n random_I2Isq.append(I2*I**2)\n random_I4.append(I**4)\n\n # print('MC expected random mean', np.mean(random_means))\n # print('MC variance random mean', np.var(random_means))\n # print('MC expected random variance', np.mean(random_variances))\n # print('MC variance random variance', np.var(random_variances))\n # print('expected random mean', expected_random_mean)\n # print('variance random mean', variance_random_mean)\n # print('expected random variance', expected_random_var)\n # print('variance random variance', variance_random_var)\n assert np.allclose(\n np.mean(random_means), expected_random_mean, rtol=1e-2)\n assert np.allclose(\n np.var(random_means), variance_random_mean, rtol=2.1e-2)\n assert np.allclose(\n expected_random_var, np.mean(random_variances), rtol=1e-2)\n assert np.allclose(\n variance_random_var, np.var(random_variances), rtol=2.2e-2)\n\n def test_integrate_gaussian_process_uniform(self):\n np.random.seed(1)\n nvars = 1\n def func(x): return np.sum(x**2, axis=0)[:, np.newaxis]\n\n ntrain_samples = 7\n train_samples = np.linspace(-1, 1, ntrain_samples)[np.newaxis, :]\n train_vals = func(train_samples)\n\n nu = np.inf\n kernel = Matern(length_scale_bounds=(1e-2, 10), nu=nu)\n # optimize variance\n # kernel = 1*kernel\n # optimize gp noise\n # kernel += WhiteKernel(noise_level_bounds=(1e-8, 1))\n gp = GaussianProcess(kernel, n_restarts_optimizer=1)\n gp.fit(train_samples, train_vals)\n\n univariate_variables = [stats.uniform(-1, 2)]\n variable = pya.IndependentMultivariateRandomVariable(\n univariate_variables)\n\n expected_random_mean, variance_random_mean, expected_random_var, \\\n variance_random_var = integrate_gaussian_process(gp, variable)\n\n true_mean = 1/3\n true_var = 1/5-1/3**2\n\n print('True mean', true_mean)\n print('Expected random mean', expected_random_mean)\n std_random_mean = np.sqrt(variance_random_mean)\n print('Variance random mean', variance_random_mean)\n print('Stdev random mean', std_random_mean)\n print('Expected random mean +/- 3 stdev',\n [expected_random_mean-3*std_random_mean,\n expected_random_mean+3*std_random_mean])\n assert np.allclose(true_mean, expected_random_mean, rtol=1e-2)\n\n print('True var', true_var)\n print('Expected random var', expected_random_var)\n assert np.allclose(expected_random_var, true_var, rtol=1e-2)\n\n nsamples = 1000\n random_means = []\n xx, ww = pya.gauss_jacobi_pts_wts_1D(100, 0, 0)\n quad_points = pya.cartesian_product([xx]*nvars)\n quad_weights = pya.outer_product([ww]*nvars)\n for ii in range(nsamples):\n vals = gp.predict_random_realization(quad_points)[:, 0]\n random_means.append(vals.dot(quad_weights))\n\n print('MC expected random mean', np.mean(random_means))\n print('MC variance random mean', np.var(random_means))\n assert np.allclose(\n np.mean(random_means), expected_random_mean, rtol=1e-2)\n assert np.allclose(\n np.var(random_means), variance_random_mean, rtol=1e-2)\n\n # xx=np.linspace(-1,1,101)\n # plt.plot(xx,func(xx[np.newaxis,:]))\n # gp_mean,gp_std = gp(xx[np.newaxis,:],return_std=True)\n # gp_mean = gp_mean[:,0]\n # plt.plot(xx,gp_mean)\n # plt.plot(train_samples[0,:],train_vals[:,0],'o')\n # plt.fill_between(xx,gp_mean-2*gp_std,gp_mean+2*gp_std,alpha=0.5)\n # vals = gp.predict_random_realization(xx[np.newaxis,:])\n # plt.plot(xx,vals)\n # plt.show()\n\n\nclass TestSamplers(unittest.TestCase):\n def setUp(self):\n np.random.seed(1)\n\n def test_cholesky_sampler_basic_restart(self):\n nvars = 1\n variables = pya.IndependentMultivariateRandomVariable(\n [stats.uniform(-1, 2)]*nvars)\n sampler = CholeskySampler(nvars, 100, variables)\n kernel = pya.Matern(1, length_scale_bounds='fixed', nu=np.inf)\n sampler.set_kernel(kernel)\n\n num_samples = 10\n samples = sampler(num_samples)[0]\n\n sampler2 = CholeskySampler(nvars, 100, variables)\n sampler2.set_kernel(kernel)\n samples2 = sampler2(num_samples//2)[0]\n samples2 = np.hstack([samples2, sampler2(num_samples)[0]])\n assert np.allclose(samples2, samples)\n\n def test_cholesky_sampler_restart_with_changed_kernel(self):\n nvars = 1\n variables = pya.IndependentMultivariateRandomVariable(\n [stats.uniform(-1, 2)]*nvars)\n kernel1 = pya.Matern(1, length_scale_bounds='fixed', nu=np.inf)\n kernel2 = pya.Matern(0.1, length_scale_bounds='fixed', nu=np.inf)\n\n num_samples = 10\n sampler = CholeskySampler(nvars, 100, variables)\n sampler.set_kernel(kernel1)\n samples = sampler(num_samples)[0]\n\n sampler2 = CholeskySampler(nvars, 100, variables)\n sampler2.set_kernel(kernel1)\n samples2 = sampler2(num_samples//2)[0]\n sampler2.set_kernel(kernel2)\n samples2 = np.hstack([samples2, sampler2(num_samples)[0]])\n\n # plt.plot(samples[0, :], samples[0, :]*0, 'o')\n # plt.plot(samples2[0, :], samples2[0, :]*0,'x')\n # plt.show()\n assert np.allclose(sampler2.pivots[:num_samples//2],\n sampler.pivots[:num_samples//2])\n assert not np.allclose(samples2, samples)\n\n def test_cholesky_sampler_restart_with_changed_weight_function(self):\n nvars = 1\n variables = pya.IndependentMultivariateRandomVariable(\n [stats.uniform(-1, 2)]*nvars)\n kernel1 = pya.Matern(1, length_scale_bounds='fixed', nu=np.inf)\n \n def wfunction1(x): return np.ones(x.shape[1])\n \n def wfunction2(x): return x[0, :]**2\n\n num_samples = 10\n sampler = CholeskySampler(nvars, 100, variables)\n sampler.set_kernel(kernel1)\n sampler.set_weight_function(wfunction1)\n samples = sampler(num_samples)[0]\n\n sampler2 = CholeskySampler(nvars, 100, variables)\n sampler2.set_kernel(kernel1)\n sampler2.set_weight_function(wfunction1)\n samples2 = sampler2(num_samples//2)[0]\n sampler2.set_weight_function(wfunction2)\n samples2 = np.hstack([samples2, sampler2(num_samples)[0]])\n\n assert np.allclose(sampler2.pivots[:num_samples//2],\n sampler.pivots[:num_samples//2])\n\n assert not np.allclose(samples2, samples)\n\n def test_cholesky_sampler_adaptive_gp_fixed_kernel(self):\n nvars = 1\n variables = pya.IndependentMultivariateRandomVariable(\n [stats.uniform(-1, 2)]*nvars)\n \n def func(samples): return np.array(\n [np.sum(samples**2, axis=0), np.sum(samples**3, axis=0)]).T\n\n validation_samples = np.random.uniform(0, 1, (nvars, 100))\n nsamples = 3\n\n kernel = pya.Matern(1, length_scale_bounds='fixed', nu=3.5)\n sampler1 = CholeskySampler(nvars, 100, None)\n sampler1.set_kernel(copy.deepcopy(kernel))\n gp1 = AdaptiveCholeskyGaussianProcessFixedKernel(sampler1, func)\n gp1.refine(nsamples)\n vals1 = gp1(validation_samples)\n\n # currently AdaptiveGaussianProcess can only handle scalar QoI\n # so only test first QoI of func.\n def func2(samples): return func(samples)[:, :1]\n \n sampler2 = CholeskySampler(nvars, 100, None)\n sampler2.set_kernel(copy.deepcopy(kernel))\n gp2 = AdaptiveGaussianProcess(kernel=kernel, alpha=1e-12)\n gp2.setup(func2, sampler2)\n gp2.refine(nsamples)\n vals2 = gp2(validation_samples)\n\n assert np.allclose(gp1.train_samples, gp2.X_train_.T)\n assert np.allclose(gp1.train_values[:, 0:1], gp2.y_train_)\n assert np.allclose(vals1[:, 0:1], vals2)\n\n # xx = np.linspace(0,1,101)\n # plt.plot(xx,gp1(xx[np.newaxis,:]),'-r')\n # plt.plot(xx,gp2(xx[np.newaxis,:]),'-k')\n # plt.plot(gp1.train_samples[0,:],gp1.train_values[:,0],'ro')\n # plt.plot(gp2.X_train_.T[0,:],gp2.y_train_,'ks')\n # plt.show()\n\n gp1.refine(2*nsamples)\n vals1 = gp1(validation_samples)\n gp2.refine(2*nsamples)\n vals2 = gp2(validation_samples)\n assert np.allclose(vals1[:, 0:1], vals2)\n\n def test_cholesky_sampler_adaptive_gp_fixed_kernel_II(self):\n np.random.seed(1)\n nvars = 10\n sampler_length_scale = 0.5\n sampler_matern_nu = np.inf\n ncandidate_samples = 1000\n\n alpha_stat, beta_stat = 20, 20\n variables = pya.IndependentMultivariateRandomVariable(\n [stats.beta(a=alpha_stat, b=beta_stat)]*nvars)\n\n generate_samples = partial(\n pya.generate_independent_random_samples, variables)\n\n weight_function = partial(\n pya.tensor_product_pdf,\n univariate_pdfs=partial(stats.beta.pdf, a=alpha_stat, b=beta_stat))\n\n def gp_mean_function(kernel, samples, alpha, X):\n return kernel(X.T, samples.T).dot(alpha)\n \n def random_gaussian_process(kernel, samples):\n alpha = np.random.normal(0, 1, (samples.shape[1], 1))\n return partial(gp_mean_function, kernel, samples, alpha)\n\n ntrials = 100\n lb, ub = 0, 1\n func_length_scale = sampler_length_scale\n func_matern_nu = sampler_matern_nu\n func_kernel = pya.Matern(\n func_length_scale, length_scale_bounds='fixed', nu=func_matern_nu)\n funcs = [random_gaussian_process(func_kernel, np.random.uniform(\n lb, ub, (nvars, 1000))) for n in range(ntrials)]\n\n def multiple_qoi_function(funcs, samples):\n return np.array([f(samples)[:,0] for f in funcs]).T\n \n func = partial(multiple_qoi_function, funcs)\n\n sampler_kernel = pya.Matern(\n sampler_length_scale, length_scale_bounds='fixed',\n nu=sampler_matern_nu)\n\n weight_function = None\n sampler = pya.CholeskySampler(\n nvars, ncandidate_samples, variables,\n generate_random_samples=generate_samples)\n sampler.set_kernel(copy.deepcopy(sampler_kernel))\n sampler.set_weight_function(weight_function)\n\n nvalidation_samples = 1000\n generate_validation_samples = generate_samples\n validation_samples = generate_validation_samples(nvalidation_samples)\n validation_values = func(validation_samples)\n\n class Callback(object):\n def __init__(self, validation_samples, validation_values,\n norm_ord=2):\n self.errors, self.nsamples, self.condition_numbers = [], [], []\n self.validation_samples = validation_samples\n self.validation_values = validation_values\n self.norm = partial(np.linalg.norm, ord=norm_ord)\n \n def __call__(self, approx):\n pred_values = approx(self.validation_samples)\n assert pred_values.shape == self.validation_values.shape\n error = self.norm(\n pred_values-self.validation_values,axis=0)/self.norm(\n self.validation_values, axis=0)\n self.errors.append(error)\n self.nsamples.append(approx.num_training_samples())\n self.condition_numbers.append(approx.condition_number())\n\n\n callback = Callback(validation_samples, validation_values)\n gp = pya.AdaptiveCholeskyGaussianProcessFixedKernel(sampler, func)\n\n #checkpoints = [5, 10, 100, 500]\n checkpoints = [5, 10, 20, 50, 100, 200, 300, 500, 1000]\n nsteps = len(checkpoints)\n for ii in range(nsteps):\n gp.refine(checkpoints[ii])\n callback(gp)\n\n assert np.median(callback.errors ,axis=1) < 1e-3\n \n #print(np.median(callback.errors,axis=1))\n #plt.loglog(checkpoints, np.median(callback.errors ,axis=1))\n #plt.show()\n\n \n \n def test_RBF_posterior_variance_gradient_wrt_samples(self):\n nvars = 2\n lb, ub = 0, 1\n ntrain_samples_1d = 10\n\n train_samples = pya.cartesian_product(\n [np.linspace(lb, ub, ntrain_samples_1d)]*nvars)\n\n length_scale = [0.1, 0.2][:nvars]\n kernel = RBF(length_scale, length_scale_bounds='fixed')\n\n pred_samples = np.random.uniform(0, 1, (nvars, 3))\n x0 = train_samples[:, :1]\n grad = RBF_gradient_wrt_samples(\n x0, pred_samples, length_scale)\n\n fd_grad = pya.approx_jacobian(\n lambda x: kernel(x, pred_samples.T)[0, :], x0[:,0])\n assert np.allclose(grad, fd_grad, atol=1e-6)\n errors = pya.check_gradients(\n lambda x: kernel(x.T, pred_samples.T)[0, :],\n lambda x: RBF_gradient_wrt_samples(\n x, pred_samples, length_scale), x0)\n assert errors.min()<1e-6\n\n jac = RBF_posterior_variance_jacobian_wrt_samples(\n train_samples, pred_samples, kernel)\n\n x0 = train_samples.flatten(order='F')\n assert np.allclose(\n train_samples, x0.reshape(train_samples.shape, order='F'))\n\n def func(x_flat):\n return gaussian_process_pointwise_variance(\n kernel, pred_samples, x_flat.reshape(\n train_samples.shape, order='F'))\n fd_jac = pya.approx_jacobian(func, x0)\n\n # print(jac, '\\n\\n',f d_jac)\n # print('\\n', np.absolute(jac-fd_jac).max())\n assert np.allclose(jac, fd_jac, atol=1e-5)\n\n errors = pya.check_gradients(\n func,\n lambda x: RBF_posterior_variance_jacobian_wrt_samples(\n x.reshape(nvars, x.shape[0]//nvars, order='F'),\n pred_samples, kernel), x0[:, np.newaxis])\n assert errors.min()<2e-6\n\n def check_matern_gradient_wrt_samples(self, nu):\n nvars = 2\n lb, ub = 0, 1\n ntrain_samples_1d = 3\n\n train_samples = pya.cartesian_product(\n [np.linspace(lb, ub, ntrain_samples_1d)]*nvars)\n\n length_scale = [0.1, 0.2][:nvars]\n kernel = Matern(length_scale, length_scale_bounds='fixed', nu=nu)\n\n pred_samples = np.random.uniform(lb, ub, (nvars, 1))\n x0 = train_samples[:, :1]\n grad = matern_gradient_wrt_samples(\n nu, x0, pred_samples, length_scale)\n K = kernel(x0.T, pred_samples.T)\n\n fd_grad = pya.approx_jacobian(\n lambda x: kernel(x, pred_samples.T)[0, :], x0[:,0])\n assert np.allclose(grad, fd_grad, atol=1e-6)\n errors = pya.check_gradients(\n lambda x: kernel(x.T, pred_samples.T)[0, :],\n lambda x: matern_gradient_wrt_samples(\n nu, x, pred_samples, length_scale), x0)\n assert errors.min()<1e-6\n\n def test_matern_gradient_wrt_samples(self):\n self.check_matern_gradient_wrt_samples(3/2)\n self.check_matern_gradient_wrt_samples(5/2)\n self.check_matern_gradient_wrt_samples(np.inf)\n\n def test_RBF_posterior_variance_gradient_wrt_samples_subset(\n self):\n nvars = 2\n lb, ub = 0, 1\n ntrain_samples_1d = 10\n def func(x): return np.sum(x**2, axis=0)[:, np.newaxis]\n\n train_samples = pya.cartesian_product(\n [np.linspace(lb, ub, ntrain_samples_1d)]*nvars)\n train_vals = func(train_samples)\n\n new_samples_index = train_samples.shape[1]-10\n\n length_scale = [0.1, 0.2][:nvars]\n kernel = RBF(length_scale, length_scale_bounds='fixed')\n\n pred_samples = np.random.uniform(0, 1, (nvars, 3))\n jac = RBF_posterior_variance_jacobian_wrt_samples(\n train_samples, pred_samples, kernel, new_samples_index)\n\n x0 = train_samples.flatten(order='F')\n assert np.allclose(\n train_samples, x0.reshape(train_samples.shape, order='F'))\n\n def func(x_flat):\n return gaussian_process_pointwise_variance(\n kernel, pred_samples, x_flat.reshape(\n train_samples.shape, order='F'))\n fd_jac = pya.approx_jacobian(func, x0)[:,new_samples_index*nvars:]\n\n # print(jac, '\\n\\n',f d_jac)\n #print('\\n', np.absolute(jac-fd_jac).max())\n assert np.allclose(jac, fd_jac, atol=1e-5)\n\n def test_integrate_grad_P(self):\n nvars = 2\n univariate_variables = [stats.norm()]*nvars\n #lb, ub = univariate_variables[0].interval(0.99999)\n lb, ub = -2, 2 \n\n ntrain_samples_1d = 2\n\n train_samples = pya.cartesian_product(\n [np.linspace(lb, ub, ntrain_samples_1d)]*nvars)\n\n length_scale = [0.5, 0.4][:nvars]\n kernel = RBF(length_scale, length_scale_bounds='fixed')\n\n # the shorter the length scale the larger the number of quadrature\n # points is needed\n xx_1d, ww_1d = pya.gauss_hermite_pts_wts_1D(100)\n grad_P = integrate_grad_P(\n [xx_1d]*nvars, [ww_1d]*nvars, train_samples, length_scale)[0]\n\n a, b = train_samples[:, 0]\n mu = [0]*nvars\n sigma = [1]*nvars\n term1 = gaussian_grad_P_diag_term1(a, length_scale[0], mu[0], sigma[0])\n term2 = gaussian_grad_P_diag_term2(b, length_scale[1], mu[1], sigma[1])\n assert np.allclose(\n term1,\n gaussian_grad_P_offdiag_term1(\n a, a, length_scale[0], mu[0], sigma[0]))\n assert np.allclose(\n term2,\n gaussian_grad_P_offdiag_term2(\n b, b, length_scale[1], mu[1], sigma[1]))\n assert np.allclose(\n term1,\n ((xx_1d-a)/length_scale[0]**2*np.exp(\n -(xx_1d-a)**2/(2*length_scale[0]**2))**2).dot(ww_1d))\n assert np.allclose(\n term2,(np.exp(-(xx_1d-b)**2/(2*length_scale[1]**2))**2).dot(ww_1d))\n\n pred_samples = pya.cartesian_product([xx_1d]*nvars)\n weights = pya.outer_product([ww_1d]*nvars)\n for ii in range(train_samples.shape[1]):\n x0 = train_samples[:, ii:ii+1]\n grad = RBF_gradient_wrt_samples(\n x0, pred_samples, length_scale)\n for jj in range(train_samples.shape[1]):\n x1 = train_samples[:, jj:jj+1]\n K = kernel(pred_samples.T, x1.T)\n for kk in range(nvars):\n grad_P_quad = (grad[:, kk:kk+1]*K).T.dot(weights)\n t1 = gaussian_grad_P_offdiag_term1(\n x0[kk, 0], x1[kk, 0], length_scale[kk],\n mu[kk], sigma[kk])\n t2 = gaussian_grad_P_offdiag_term2(\n x0[1-kk,0], x1[1-kk,0], length_scale[1-kk],\n mu[1-kk], sigma[1-kk])\n grad_P_exact = t1*t2\n if ii == jj:\n grad_P_quad *= 2\n grad_P_exact *= 2\n assert np.allclose(grad_P_quad, grad_P_exact)\n assert np.allclose(grad_P_quad, grad_P[nvars*ii+kk,jj])\n #assert False\n #assert np.allclose(grad_P_mc, grad_P[kk,ii,jj])\n\n def test_integrate_grad_P_II(self):\n nvars = 2\n univariate_variables = [stats.norm()]*nvars\n #lb, ub = univariate_variables[0].interval(0.99999)\n lb, ub = -2, 2 \n\n ntrain_samples_1d = 4\n\n train_samples = pya.cartesian_product(\n [np.linspace(lb, ub, ntrain_samples_1d)]*nvars)\n\n length_scale = [0.5, 0.4, 0.6][:nvars]\n kernel = RBF(length_scale, length_scale_bounds='fixed')\n\n # the shorter the length scale the larger the number of quadrature\n # points is needed\n xx_1d, ww_1d = pya.gauss_hermite_pts_wts_1D(100)\n grad_P, P = integrate_grad_P(\n [xx_1d]*nvars, [ww_1d]*nvars, train_samples, length_scale)\n\n def func1(xtr):\n xtr = xtr.reshape((nvars, train_samples.shape[1]), order='F')\n P = 1\n for kk in range(nvars):\n P *= integrate_tau_P(\n xx_1d, ww_1d, xtr[kk:kk+1, :], length_scale[kk])[1]\n\n vals = P.flatten(order='F')\n # vals = [P[0,0], P[1,0], ..., P[N-1,0], P[0,1], P[1,1], ... P[N-1,1]\n # ...]\n return vals\n\n x0 = train_samples.flatten(order='F')\n P_fd_jac = pya.approx_jacobian(func1, x0)\n ntrain_samples = train_samples.shape[1]\n assert np.allclose(\n P_fd_jac.shape, (ntrain_samples**2, nvars*ntrain_samples))\n P_fd_jac_res = P_fd_jac.reshape(\n (ntrain_samples, ntrain_samples, nvars*ntrain_samples), order='F')\n from sklearn.gaussian_process.kernels import _approx_fprime\n assert np.allclose(_approx_fprime(x0, lambda x: func1(x).reshape(ntrain_samples, ntrain_samples, order='F'), np.sqrt(np.finfo(float).eps)),P_fd_jac_res)\n\n # Consider 3 training samples with\n # P = P00 P01 P02\n # P10 P11 P12\n # P20 P21 P22\n # for kth training sample grad_P stores \n # Pk0 Pk1 Pk2\n # All entries not involving k are zero, e.g. for k=0 the terms\n # P11 P12 P21 P22 will be zero such that\n # dP/d(x[0,n]) = C00 C01 C02\n # C10 0 0\n # C20 0 0\n jac = np.empty_like(P_fd_jac)\n for kk in range(ntrain_samples):\n for nn in range(nvars):\n tmp = np.zeros((ntrain_samples, ntrain_samples))\n tmp[kk, :] = grad_P[kk*nvars+nn, :]\n tmp[:, kk] = tmp[kk, :]\n assert np.allclose(P_fd_jac_res[:, :, kk*nvars+nn], tmp)\n\n def func2(xtr):\n xtr = xtr.reshape((nvars, train_samples.shape[1]), order='F')\n A_inv = np.linalg.inv(kernel(xtr.T))\n return A_inv.flatten(order='F')\n\n def func3(xtr):\n xtr = xtr.reshape((nvars, train_samples.shape[1]), order='F')\n P = 1\n for kk in range(nvars):\n P *= integrate_tau_P(\n xx_1d, ww_1d, xtr[kk:kk+1, :], length_scale[kk])[1]\n A_inv = np.linalg.inv(kernel(xtr.T))\n val = np.sum(A_inv*P)\n return -val\n\n A_fd_jac = pya.approx_jacobian(func2, x0).reshape((\n ntrain_samples, ntrain_samples, nvars*ntrain_samples), order='F')\n assert np.allclose(_approx_fprime(x0, lambda x: func2(x).reshape(ntrain_samples, ntrain_samples, order='F'), np.sqrt(np.finfo(float).eps)),A_fd_jac)\n\n A_inv = np.linalg.inv(kernel(train_samples.T))\n assert np.allclose(func3(x0),-np.sum(A_inv*P))\n obj_fd_split = -np.sum(A_fd_jac*P[:,:,np.newaxis] + P_fd_jac_res*A_inv[:,:,np.newaxis],axis=(0,1))\n \n obj_fd_jac = pya.approx_jacobian(func3, x0)[0,:]\n assert np.allclose(obj_fd_split, obj_fd_jac)\n\n assert np.allclose(\n P, func1(x0).reshape((ntrain_samples, ntrain_samples), order='F'))\n jac = np.zeros((nvars*ntrain_samples))\n jac1 = np.zeros((nvars*ntrain_samples))\n AinvPAinv = (A_inv.dot(P).dot(A_inv))\n for kk in range(ntrain_samples):\n K_train_grad_all_train_points_kk = \\\n RBF_gradient_wrt_samples(\n train_samples[:, kk:kk+1], train_samples, length_scale)\n # Use the follow properties for tmp3 and tmp4\n # Do sparse matrix element wise product\n # 0 a 0 D00 D01 D02\n # a b c x D10 D11 D12\n # 0 c 0 D20 D21 D22\n # =2*(a*D01 b*D11 + c*D21)-b*D11\n #\n # Trace [RCRP] = Trace[RPRC] for symmetric matrices\n tmp3 = -2*np.sum(K_train_grad_all_train_points_kk.T*AinvPAinv[:, kk],\n axis=1)\n tmp3 -= -K_train_grad_all_train_points_kk[kk, :]*AinvPAinv[kk, kk]\n jac1[kk*nvars:(kk+1)*nvars] = -tmp3\n tmp4 = 2*np.sum(grad_P[kk*nvars:(kk+1)*nvars]*A_inv[:, kk], axis=1)\n tmp4 -= grad_P[kk*nvars:(kk+1)*nvars,kk]*A_inv[kk, kk]\n jac1[kk*nvars:(kk+1)*nvars] -= tmp4\n # check these numpy operations with an explicit loop calculation\n for nn in range(nvars):\n tmp1 = np.zeros((ntrain_samples, ntrain_samples))\n tmp1[kk, :] = grad_P[kk*nvars+nn, :]\n tmp1[:, kk] = tmp1[kk, :]\n assert np.allclose(P_fd_jac_res[:,:,kk*nvars+nn], tmp1)\n tmp2 = np.zeros((ntrain_samples, ntrain_samples))\n tmp2[kk, :] = K_train_grad_all_train_points_kk[:, nn]\n tmp2[:, kk] = tmp2[kk, :]\n tmp2 = -A_inv.dot(tmp2.dot(A_inv))\n assert np.allclose(A_fd_jac[:,:,kk*nvars+nn], tmp2, atol=1e-6)\n jac[kk*nvars+nn] -= np.sum(tmp2*P+A_inv*tmp1)\n\n assert np.allclose(jac, obj_fd_jac)\n assert np.allclose(jac1, obj_fd_jac)\n\n jac2 = \\\n RBF_integrated_posterior_variance_gradient_wrt_samples(\n train_samples, [xx_1d]*nvars, [ww_1d]*nvars, kernel)\n assert np.allclose(jac2, obj_fd_jac)\n\n def test_RBF_integrated_posterior_variance_gradient_wrt_sample_subset(self):\n nvars = 2\n lb, ub = -1, 1\n ntrain_samples_1d = 10\n def func(x): return np.sum(x**2, axis=0)[:, np.newaxis]\n\n train_samples = pya.cartesian_product(\n [np.linspace(lb, ub, ntrain_samples_1d)]*nvars)\n train_vals = func(train_samples)\n\n new_samples_index = train_samples.shape[1]-10\n\n length_scale = [0.1, 0.2][:nvars]\n kernel = RBF(length_scale, length_scale_bounds='fixed')\n\n xx_1d, ww_1d = pya.gauss_jacobi_pts_wts_1D(100, 0, 0)\n t0 = time.time()\n jac = RBF_integrated_posterior_variance_gradient_wrt_samples(\n train_samples, [xx_1d]*nvars, [ww_1d]*nvars, kernel,\n new_samples_index)\n print(time.time()-t0)\n\n x0 = train_samples.flatten(order='F')\n assert np.allclose(\n train_samples, x0.reshape(train_samples.shape, order='F'))\n\n def func(x_flat):\n xtr = x_flat.reshape((nvars, train_samples.shape[1]), order='F')\n P = 1\n for kk in range(nvars):\n P *= integrate_tau_P(\n xx_1d, ww_1d, xtr[kk:kk+1, :], length_scale[kk])[1]\n A_inv = np.linalg.inv(kernel(xtr.T))\n val = np.sum(A_inv*P)\n return -val\n\n t0 = time.time()\n fd_jac = pya.approx_jacobian(func, x0)[0,new_samples_index*nvars:]\n print(time.time()-t0)\n\n print(jac, '\\n\\n', fd_jac)\n #print('\\n', np.absolute(jac-fd_jac).max())\n assert np.allclose(jac, fd_jac, atol=1e-5)\n\n def test_monte_carlo_gradient_based_ivar_sampler(self):\n nvars = 2\n variables = pya.IndependentMultivariateRandomVariable(\n [stats.beta(20, 20)]*nvars)\n generate_random_samples = partial(\n pya.generate_independent_random_samples, variables)\n \n # correlation length affects ability to check gradient. As kerenl matrix\n # gets more ill conditioned then gradients get worse\n greedy_method = 'ivar'\n #greedy_method = 'chol'\n use_gauss_quadrature = False\n kernel = pya.Matern(.1, length_scale_bounds='fixed', nu=np.inf)\n sampler = IVARSampler(\n nvars, 1000, 1000, generate_random_samples, variables,\n greedy_method, use_gauss_quadrature=use_gauss_quadrature,\n nugget=1e-14)\n sampler.set_kernel(copy.deepcopy(kernel))\n\n def weight_function(samples):\n return np.prod([variables.all_variables()[ii].pdf(samples[ii,:])\n for ii in range(samples.shape[0])],axis=0)\n\n if greedy_method == 'chol':\n sampler.set_weight_function(weight_function)\n\n # nature of training samples affects ability to check gradient. As\n # training samples makes kernel matrix more ill conditioned then\n # gradients get worse\n ntrain_samples_1d = 10\n train_samples = pya.cartesian_product(\n [np.linspace(0, 1, ntrain_samples_1d)]*nvars)\n x0 = train_samples.flatten(order='F')\n if not use_gauss_quadrature:\n # gradients not currently implemented when using quadrature\n errors = pya.check_gradients(\n sampler.objective, sampler.objective_gradient, x0[:,np.newaxis],\n disp=False)\n assert errors.min()<4e-6\n\n gsampler = sampler.greedy_sampler\n #print(np.linalg.norm(gsampler.candidate_samples))\n #print(np.linalg.norm(sampler.pred_samples))\n\n ntrain_samples = 20\n new_samples1 = sampler(ntrain_samples)[0].copy()\n\n val1 = gaussian_process_pointwise_variance(\n sampler.greedy_sampler.kernel, sampler.pred_samples,\n sampler.training_samples).mean()\n val2 = gaussian_process_pointwise_variance(\n sampler.greedy_sampler.kernel, sampler.pred_samples,\n sampler.init_guess).mean()\n # can't just call sampler.objective here because self.training_points\n # has been updated and calling objective(sampler.training_samples)\n # will evaluate objective with training samples repeated twice.\n # Similarly init guess will be concatenated with self.training_samples\n # if passed to objective at this point\n print(val1, val2)\n assert (val1 < val2)\n\n new_samples2 = sampler(2*ntrain_samples)[0]\n # currently the following check will fail because a different set\n # of prediction samples will be generated by greedy sampler\n # assert np.allclose(\n # 1+sampler.greedy_sampler.best_obj_vals[ntrain_samples-1], val1)\n\n assert np.allclose(\n new_samples1, sampler.training_samples[:, :ntrain_samples],\n atol=1e-12)\n\n assert np.allclose(\n sampler.greedy_sampler.training_samples[:, :ntrain_samples],\n new_samples1, atol=1e-12)\n \n val1 = gaussian_process_pointwise_variance(\n sampler.greedy_sampler.kernel, sampler.pred_samples,\n sampler.training_samples).mean()\n # initial guess used by optimizer does not contain\n # fixed training points already selected so add here \n greedy_samples = np.hstack([sampler.training_samples[:,:ntrain_samples],\n sampler.init_guess])\n val2 = gaussian_process_pointwise_variance(\n sampler.greedy_sampler.kernel, sampler.pred_samples,\n greedy_samples).mean()\n print(val1, val2)\n assert (val1 < val2)\n \n # plt.plot(sampler.training_samples[0, :],\n # sampler.training_samples[1, :], 'o')\n # plt.plot(sampler.greedy_sampler.training_samples[0, :],\n # sampler.greedy_sampler.training_samples[1, :], 'x')\n # plt.plot(sampler.init_guess[0, :],\n # sampler.init_guess[1, :], '^')\n # plt.show()\n\n def test_quadrature_gradient_based_ivar_sampler(self):\n nvars = 2\n variables = pya.IndependentMultivariateRandomVariable(\n [stats.beta(20, 20)]*nvars)\n generate_random_samples = partial(\n pya.generate_independent_random_samples, variables)\n \n # correlation length affects ability to check gradient. As kerenl matrix\n # gets more ill conditioned then gradients get worse\n greedy_method = 'ivar'\n #greedy_method = 'chol'\n use_gauss_quadrature = True\n kernel = pya.Matern(.1, length_scale_bounds='fixed', nu=np.inf)\n sampler = IVARSampler(\n nvars, 1000, 1000, generate_random_samples, variables,\n greedy_method, use_gauss_quadrature=use_gauss_quadrature)\n sampler.set_kernel(copy.deepcopy(kernel))\n\n def weight_function(samples):\n return np.prod([variables.all_variables()[ii].pdf(samples[ii,:])\n for ii in range(samples.shape[0])],axis=0)\n\n if greedy_method == 'chol':\n sampler.set_weight_function(weight_function)\n\n # nature of training samples affects ability to check gradient. As\n # training samples makes kernel matrix more ill conditioned then\n # gradients get worse\n ntrain_samples_1d = 10\n train_samples = pya.cartesian_product(\n [np.linspace(0, 1, ntrain_samples_1d)]*nvars)\n x0 = train_samples.flatten(order='F')\n if not use_gauss_quadrature:\n # gradients not currently implemented when using quadrature\n errors = pya.check_gradients(\n sampler.objective, sampler.objective_gradient, x0[:,np.newaxis],\n disp=False)\n assert errors.min()<4e-6\n\n gsampler = sampler.greedy_sampler\n #print(np.linalg.norm(gsampler.candidate_samples))\n #print(np.linalg.norm(sampler.pred_samples))\n\n ntrain_samples = 20\n new_samples1 = sampler(ntrain_samples)[0].copy()\n\n A_inv = np.linalg.inv(kernel(sampler.training_samples.T))\n P = sampler.compute_P(sampler.training_samples)\n val1 = 1-np.trace(A_inv.dot(P))\n A_inv = np.linalg.inv(kernel(sampler.init_guess.T))\n P = sampler.compute_P(sampler.init_guess)\n val2 = 1-np.trace(A_inv.dot(P))\n \n # can't just call sampler.objective here because self.training_points\n # has been updated and calling objective(sampler.training_samples)\n # will evaluate objective with training samples repeated twice.\n # Similarly init guess will be concatenated with self.training_samples\n # if passed to objective at this point\n print(val1, val2)\n assert (val1 < val2)\n\n new_samples2 = sampler(2*ntrain_samples)[0]\n assert np.allclose(\n 1+sampler.greedy_sampler.best_obj_vals[ntrain_samples-1], val1)\n\n assert np.allclose(\n new_samples1, sampler.training_samples[:, :ntrain_samples],\n atol=1e-12)\n\n assert np.allclose(\n sampler.greedy_sampler.training_samples[:, :ntrain_samples],\n new_samples1, atol=1e-12)\n \n A_inv = np.linalg.inv(kernel(sampler.training_samples.T))\n P = sampler.compute_P(sampler.training_samples)\n val1 = 1-np.trace(A_inv.dot(P))\n\n #init guess used by optimizer does not contain\n #fixed trainign points already selected so add here \n greedy_samples = np.hstack([sampler.training_samples[:,:ntrain_samples],\n sampler.init_guess])\n A_inv = np.linalg.inv(kernel(greedy_samples.T))\n P = sampler.compute_P(greedy_samples)\n val2 = 1-np.trace(A_inv.dot(P))\n print(val1, val2)\n assert (val1 < val2)\n \n # plt.plot(sampler.training_samples[0, :],\n # sampler.training_samples[1, :], 'o')\n # plt.plot(sampler.greedy_sampler.training_samples[0, :],\n # sampler.greedy_sampler.training_samples[1, :], 'x')\n # plt.plot(sampler.init_guess[0, :],\n # sampler.init_guess[1, :], '^')\n # plt.show()\n\n def test_greedy_gauss_quadrature_ivar_sampler_I(self):\n nvars = 2\n variables = pya.IndependentMultivariateRandomVariable(\n [stats.beta(20, 20)]*nvars)\n generate_random_samples = partial(\n pya.generate_independent_random_samples, variables)\n\n kernel = pya.Matern(.1, length_scale_bounds='fixed', nu=np.inf)\n np.random.seed(1)\n sampler1 = GreedyIntegratedVarianceSampler(\n nvars, 100, 10, generate_random_samples,\n variables, use_gauss_quadrature=True, econ=True)\n sampler1.set_kernel(kernel)\n np.random.seed(1)\n sampler2 = GreedyIntegratedVarianceSampler(\n nvars, 100, 10, generate_random_samples,\n variables, use_gauss_quadrature=True, econ=False)\n sampler2.set_kernel(kernel)\n\n obj_vals1 = sampler1.objective_vals_econ()\n obj_vals2 = sampler2.objective_vals()\n assert np.allclose(obj_vals1, obj_vals2)\n pivot1 = sampler1.refine_econ()\n pivot2 = sampler2.refine_naive()\n assert np.allclose(pivot1, pivot2)\n\n for nsamples in range(1,5+1):\n #refine functions update internal variables so reset\n np.random.seed(1)\n sampler1 = GreedyIntegratedVarianceSampler(\n nvars, 50, 1000, generate_random_samples,\n variables, use_gauss_quadrature=True, econ=True)\n np.random.seed(1)\n sampler2 = GreedyIntegratedVarianceSampler(\n nvars, 50, 1000, generate_random_samples,\n variables, use_gauss_quadrature=True, econ=False)\n kernel = pya.Matern(.1, length_scale_bounds='fixed', nu=np.inf)\n sampler1.set_kernel(kernel)\n sampler2.set_kernel(kernel)\n #print('nsamples',nsamples)\n sampler1(nsamples)\n sampler2(nsamples)\n\n obj_vals1 = sampler1.objective_vals_econ()\n obj_vals2 = sampler2.objective_vals()\n obj_vals3 = sampler1.vectorized_objective_vals_econ()\n #print(obj_vals1, obj_vals2)\n #print(obj_vals1, obj_vals3)\n assert np.allclose(obj_vals1, obj_vals2)\n assert np.allclose(obj_vals1, obj_vals3)\n pivot1 = sampler1.refine_econ()\n pivot2 = sampler2.refine_naive()\n #print(pivot1, pivot2)\n assert np.allclose(pivot1, pivot2)\n\n def check_greedy_monte_carlo_ivar_sampler(\n self, nvars, kernel, kernels_1d):\n variables = pya.IndependentMultivariateRandomVariable(\n [stats.beta(20, 20)]*nvars)\n generate_random_samples = partial(\n pya.generate_independent_random_samples, variables)\n\n use_gauss_quadrature = False\n np.random.seed(1)\n sampler1 = GreedyIntegratedVarianceSampler(\n nvars, 2000, 1000, generate_random_samples,\n variables, use_gauss_quadrature=use_gauss_quadrature, econ=True,\n compute_cond_nums=True)\n sampler1.set_kernel(kernel, kernels_1d = kernels_1d)\n np.random.seed(1)\n sampler2 = GreedyIntegratedVarianceSampler(\n nvars, 2000, 1000, generate_random_samples,\n variables, use_gauss_quadrature=use_gauss_quadrature, econ=False,\n compute_cond_nums=True)\n sampler2.set_kernel(kernel, kernels_1d = kernels_1d)\n assert np.allclose(sampler1.pred_samples,sampler2.pred_samples)\n\n nsamples = 20\n # nsamples = 100\n \n t0 = time.time()\n samples1 = sampler1(nsamples)[0]\n assert np.allclose(\n sampler1.L[:nsamples, :nsamples],\n np.linalg.cholesky(kernel(sampler1.training_samples.T)))\n time1 = time.time()-t0\n print(time1)\n\n # samples = np.random.beta(20, 20, (nvars, 1000))\n samples = sampler1.pred_samples\n variance = gaussian_process_pointwise_variance(\n kernel, samples, sampler1.training_samples)\n assert np.allclose(variance.mean(), 1+sampler1.best_obj_vals[-1])\n\n t0 = time.time()\n samples2 = sampler2(nsamples)[0]\n time2 = time.time()-t0\n print(time1, time2)\n assert time1 < time2\n\n assert np.allclose(samples1, samples2)\n\n # if nvars !=2:\n # return\n # plt.plot(samples1[0,:], samples1[1,:], 'o')\n # plt.plot(samples2[0,:], samples2[1,:], 'x')\n # plt.figure()\n # print(np.arange(len(sampler1.cond_nums))+1,sampler1.cond_nums)\n # plt.loglog(np.arange(len(sampler1.cond_nums))+1,sampler1.cond_nums)\n # plt.loglog(np.arange(len(sampler2.cond_nums))+1,sampler2.cond_nums)\n # plt.show()\n\n def test_greedy_monte_carlo_ivar_sampler_II(self):\n #TODO Add check to IVAR and VarofMean samplers to make sure\n #kernel and 1d_kernels are consistent\n kernel = pya.Matern(.1, length_scale_bounds='fixed', nu=np.inf)\n kernels_1d = None\n self.check_greedy_monte_carlo_ivar_sampler(2, kernel, kernels_1d)\n\n kernel = pya.Matern(.1, length_scale_bounds='fixed', nu=2.5)\n kernels_1d = None\n self.check_greedy_monte_carlo_ivar_sampler(2, kernel, kernels_1d)\n\n def test_greedy_variance_of_mean_sampler(self):\n nvars = 2\n variables = pya.IndependentMultivariateRandomVariable(\n [stats.beta(20, 20)]*nvars)\n generate_random_samples = partial(\n pya.generate_independent_random_samples, variables)\n\n sampler = GreedyVarianceOfMeanSampler(\n nvars, 1000, 10, generate_random_samples,\n variables, use_gauss_quadrature=True, econ=True)\n kernel = pya.Matern(.4, length_scale_bounds='fixed', nu=np.inf)\n sampler.set_kernel(kernel)\n \n sampler.nmonte_carlo_samples = 100000\n sampler.precompute_monte_carlo()\n tau_mc = sampler.tau.copy()\n sampler.nmonte_carlo_samples = 50\n sampler.precompute_gauss_quadrature()\n tau_gq = sampler.tau.copy()\n #print((tau_mc-tau_gq)/tau_mc)\n assert np.allclose(tau_mc, tau_gq, rtol=1e-2)\n\n kernel = pya.Matern(.1, length_scale_bounds='fixed', nu=np.inf)\n\n use_gauss_quadrature = False\n nquad_samples = 10000\n # use_gauss_quadrature = True\n # nquad_samples = 50\n np.random.seed(1)\n sampler1 = GreedyVarianceOfMeanSampler(\n nvars, nquad_samples, 1000, generate_random_samples,\n variables, use_gauss_quadrature=use_gauss_quadrature, econ=True,\n compute_cond_nums=True)\n sampler1.set_kernel(kernel)\n \n ntrain_samples = 20\n new_samples11 = sampler1(ntrain_samples)[0]\n new_samples12 = sampler1(2*ntrain_samples)[0]\n\n np.random.seed(1)\n sampler2 = GreedyVarianceOfMeanSampler(\n nvars, nquad_samples, 1000, generate_random_samples,\n variables, use_gauss_quadrature=use_gauss_quadrature, econ=False,\n compute_cond_nums=True)\n sampler2.set_kernel(kernel)\n\n new_samples21 = sampler2(ntrain_samples)[0]\n new_samples22 = sampler2(2*ntrain_samples)[0]\n\n # plt.plot(sampler1.training_samples[0, :],\n # sampler1.training_samples[1, :], 'o')\n # plt.plot(sampler2.training_samples[0, :],\n # sampler2.training_samples[1, :], 'x')\n # plt.figure()\n # print(np.arange(len(sampler1.cond_nums))+1,sampler1.cond_nums)\n # plt.loglog(np.arange(len(sampler1.cond_nums))+1,sampler1.cond_nums)\n # plt.loglog(np.arange(len(sampler2.cond_nums))+1,sampler2.cond_nums)\n # plt.show()\n \n assert np.allclose(new_samples11, new_samples21)\n # Note: The sequences computed with econ on and off will diverge\n # when the sample sets produce a kernel matrix with a large condition\n # number\n assert np.allclose(new_samples12, new_samples22)\n \n def compare_ivar_samplers(self):\n nvars = 2\n variables = pya.IndependentMultivariateRandomVariable(\n [stats.beta(20, 20)]*nvars)\n generate_random_samples = partial(\n pya.generate_independent_random_samples, variables)\n\n # correlation length affects ability to check gradient. As kerenl matrix\n # gets more ill conditioned then gradients get worse\n kernel = pya.Matern(.1, length_scale_bounds='fixed', nu=np.inf)\n sampler = IVARSampler(\n nvars, 1000, 1000, generate_random_samples, variables, 'ivar')\n sampler.set_kernel(kernel)\n\n ntrain_samples = 10\n new_samples1 = sampler(ntrain_samples)[0]\n\n new_samples2 = sampler(2*ntrain_samples)[0]\n\n assert np.allclose(\n sampler.training_samples[:, :ntrain_samples], new_samples1,\n atol=1e-12)\n\n np.random.seed(1)\n sampler2 = IVARSampler(\n nvars, 1000, 1000, generate_random_samples, variables, 'chol')\n sampler2.set_kernel(kernel)\n \n def weight_function(samples):\n return np.prod([variables[ii].pdf(samples[ii,:])\n for ii in range(samples.shape[0])],axis=0)\n \n sampler2.set_weight_function(weight_function)\n \n sampler2(ntrain_samples)\n sampler2(ntrain_samples*2) \n \n # plt.plot(sampler.training_samples[0, :],\n # sampler.training_samples[1, :], 'o')\n # plt.plot(sampler2.training_samples[0, :],\n # sampler2.training_samples[1, :], 'x')\n # plt.show()\n\n \nif __name__ == \"__main__\":\n gaussian_process_test_suite = unittest.TestLoader().loadTestsFromTestCase(\n TestGaussianProcess)\n unittest.TextTestRunner(verbosity=2).run(gaussian_process_test_suite)\n sampler_test_suite = unittest.TestLoader().loadTestsFromTestCase(\n TestSamplers)\n unittest.TextTestRunner(verbosity=2).run(sampler_test_suite)\n \n \n",
"r\"\"\"\nSensitivity Analysis\n====================\nQuantifying the sensitivity of a model output :math:`f` to the model parameters :math:`\\rv` can be an important component of any modeling exercise. This section demonstrates how to use opoular local and global sensitivity analysis.\n\nSobol Indices\n-------------\nAny function :math:`f` with finite variance parameterized by a set of independent variables :math:`\\rv` with :math:`\\pdf(\\rv)=\\prod_{j=1}^d\\pdf(\\rv_j)` and support :math:`\\rvdom=\\bigotimes_{j=1}^d\\rvdom_j` can be decomposed into a finite sum, referred to as the ANOVA decomposition,\n\n.. math:: f(\\rv) = \\hat{f}_0 + \\sum_{i=1}^d \\hat{f}_i(\\rv_i)+ \\sum_{i,j=1}^d \\hat{f}_{i,j}(\\rv_i,\\rv_j) + \\cdots + \\hat{f}_{1,\\ldots,d}(\\rv_1,\\ldots,\\rv_d)\n\nor more compactly\n\n.. math:: f(\\rv)=\\sum_{\\V{u}\\subseteq\\mathcal{D}}\\hat{f}_{\\V{u}}(\\rv_{\\V{u}})\n\nwhere :math:`\\hat{f}_\\V{u}` quantifies the dependence of the function :math:`f` on the variable dimensions :math:`i\\in\\V{u}` and :math:`\\V{u}=(u_1,\\ldots,u_s)\\subseteq\\mathcal{D}=\\{1,\\ldots,d\\}`.\n\nThe functions :math:`\\hat{f}_\\V{u}` can be obtained by integration, specifically\n\n.. math:: \\hat{f}_\\V{u}(\\rv_\\V{u}) = \\int_{\\rvdom_{\\mathcal{D}\\setminus\\V{u}}}f(\\rv)\\dx{\\pdf_{\\mathcal{D} \\setminus \\V{u}}(\\rv)}-\\sum_{\\V{v}\\subset\\V{u}}\\hat{f}_\\V{v}(\\rv_\\V{v}),\n\nwhere :math:`\\dx{\\pdf_{\\mathcal{D} \\setminus \\V{u}}(\\rv)}=\\prod_{j\\notin\\V{u}}\\dx{\\pdf_j(\\rv)}` and :math:`\\rvdom_{\\mathcal{D} \\setminus \\V{u}}=\\bigotimes_{j\\notin\\V{u}}\\rvdom_j`.\n\nThe first-order terms :math:`\\hat{f}_{\\V{u}}(\\rv_i)`, :math:`\\lVert \\V{u}\\rVert_{0}=1` represent the effect of a single variable acting independently of all others. Similarly, the second-order terms :math:`\\lVert\\V{u}\\rVert_{0}=2` represent the contributions of two variables acting together, and so on.\n\n The terms of the ANOVA expansion are orthogonal, i.e. the weighted :math:`L^2` inner product :math:`(\\hat{f}_\\V{u},\\hat{f}_\\V{v})_{L^2_\\pdf}=0`, for :math:`\\V{u}\\neq\\V{v}`. This orthogonality facilitates the following decomposition of the variance of the function :math:`f` \n\n.. math:: \\var{f}=\\sum_{\\V{u}\\subseteq\\mathcal{D}}\\var{\\hat{f}_\\V{u}}, \\qquad \\var{\\hat{f}_\\V{u}} = \\int_{\\rvdom_{\\V{u}}} f^2_{\\V{u}} \\dx{\\pdf_\\V{u}},\n\nwhere :math:`\\dx{\\pdf_{\\V{u}}(\\rv)}=\\prod_{j\\in\\V{u}}\\dx{\\pdf_j(\\rv)}`.\n\nThe quantities :math:`\\var{\\hat{f}_\\V{u}}/ \\var{f}` are referred to as Sobol indices [SMCS2001]_ and are frequently used to estimate the sensitivity of :math:`f` to single, or combinations of input parameters. Note that this is a *global* sensitivity, reflecting a variance attribution over the range of the input parameters, as opposed to the local sensitivity reflected by a derivative. Two popular measures of sensitivity are the main effect and total effect indices given respectively by\n\n.. math:: S_{i} = \\frac{\\var{\\hat{f}_{\\V{e}_i}}}{\\var{f}}, \\qquad S^T_{i} = \\frac{\\sum_{\\V{u}\\in\\mathcal{J}}\\var{\\hat{f}_{\\V{u}}}}{\\var{f}}\n\nwhere :math:`\\V{e}_i` is the unit vector, with only one non-zero entry located at the :math:`i`-th element, and :math:`\\mathcal{J} = \\{\\V{u}:i\\in\\V{u}\\}`.\n\nSobol indices can be computed different ways. In the following we will use polynomial chaos expansions, as in [SRESS2008]_.\n\"\"\"\nimport numpy as np\nimport pyapprox as pya\nfrom pyapprox.benchmarks.benchmarks import setup_benchmark\nfrom pyapprox.approximate import approximate\nbenchmark = setup_benchmark(\"ishigami\",a=7,b=0.1)\n\nnum_samples = 1000\ntrain_samples=pya.generate_independent_random_samples(\n benchmark.variable,num_samples)\ntrain_vals = benchmark.fun(train_samples)\n\napprox_res = approximate(\n train_samples,train_vals,'polynomial_chaos',\n {'basis_type':'hyperbolic_cross','variable':benchmark.variable,\n 'options':{'max_degree':8}})\npce = approx_res.approx\n\nres = pya.analyze_sensitivity_polynomial_chaos(pce)\n\n#%%\n#Now lets compare the estimated values with the exact value\nprint(res.main_effects[:,0])\nprint(benchmark.main_effects[:,0])\n\n#%%\n#We can visualize the sensitivity indices using the following\n\nimport matplotlib.pyplot as plt\nfig,axs = plt.subplots(1,3,figsize=(3*8,6))\npya.plot_main_effects(benchmark.main_effects,axs[0])\npya.plot_total_effects(benchmark.total_effects,axs[1])\npya.plot_interaction_values(benchmark.sobol_indices,benchmark.sobol_interaction_indices,axs[2])\naxs[0].set_title(r'$\\mathrm{Main\\;Effects}$')\naxs[1].set_title(r'$\\mathrm{Total\\;Effects}$')\naxs[2].set_title(r'$\\mathrm{Sobol\\;Indices}$')\nplt.show()\n\n\n\n#%%\n#..\n# Morris One-at-a-time\n# --------------------\n# [MT1991]_\n\n\n#%%\n#References\n#^^^^^^^^^^\n#.. [SMCS2001] `I.M. Sobol. Global sensitivity indices for nonlinear mathematical models and their Monte Carlo estimates. Mathematics and Computers in Simulation, 55(3): 271-280, 2001. <https://doi.org/10.1016/S0378-4754(00)00270-6>`_\n#.. [SRESS2008] `B. Sudret. Global sensitivity analysis using polynomial chaos expansions. Reliability Engineering & System Safety, 93(7): 964-979, 2008. <https://doi.org/10.1016/j.ress.2007.04.002>`_\n#..\n# .. [MT1991] `M.D. Morris. Factorial Sampling Plans for Preliminary Computational Experiments, Technometrics, 33:2, 161-174, 1991 <https://doi.org/10.1080/00401706.1991.10484804>`_ \n\n"
] | [
[
"numpy.linspace",
"numpy.asarray",
"scipy.stats.gaussian_kde",
"numpy.mean",
"numpy.where",
"numpy.arange",
"numpy.finfo",
"numpy.asfarray",
"numpy.atleast_1d",
"numpy.std",
"scipy.optimize.fmin_slsqp",
"numpy.zeros",
"numpy.logspace",
"numpy.array",
"numpy.absolute",
"numpy.random.seed",
"numpy.array_equal",
"numpy.linalg.norm",
"numpy.ones",
"numpy.random.normal",
"numpy.isscalar",
"numpy.empty",
"scipy.stats.mstats.mquantiles"
],
[
"scipy.spatial.distance.cdist",
"scipy.stats.beta",
"scipy.stats.norm",
"scipy.stats.uniform",
"sklearn.gaussian_process.kernels.Matern",
"sklearn.gaussian_process.kernels.WhiteKernel",
"sklearn.gaussian_process.kernels.RBF"
],
[
"matplotlib.pyplot.show",
"matplotlib.pyplot.subplots"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"0.13",
"1.6",
"0.14",
"1.10",
"0.15",
"1.4",
"0.16",
"1.9",
"0.19",
"1.5",
"0.18",
"1.2",
"1.7",
"0.12",
"1.0",
"0.17",
"1.3",
"1.8"
],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
santisoler/xarray | [
"2bb5d20fb2b4158390ab05aa6bf598b78f2caa9d"
] | [
"xarray/tutorial.py"
] | [
"\"\"\"\nUseful for:\n\n* users learning xarray\n* building tutorials in the documentation.\n\n\"\"\"\nimport os\nimport pathlib\n\nimport numpy as np\n\nfrom .backends.api import open_dataset as _open_dataset\nfrom .backends.rasterio_ import open_rasterio as _open_rasterio\nfrom .core.dataarray import DataArray\nfrom .core.dataset import Dataset\n\n_default_cache_dir_name = \"xarray_tutorial_data\"\nbase_url = \"https://github.com/pydata/xarray-data\"\nversion = \"master\"\n\n\ndef _construct_cache_dir(path):\n import pooch\n\n if isinstance(path, pathlib.Path):\n path = os.fspath(path)\n elif path is None:\n path = pooch.os_cache(_default_cache_dir_name)\n\n return path\n\n\nexternal_urls = {} # type: dict\nexternal_rasterio_urls = {\n \"RGB.byte\": \"https://github.com/mapbox/rasterio/raw/1.2.1/tests/data/RGB.byte.tif\",\n \"shade\": \"https://github.com/mapbox/rasterio/raw/1.2.1/tests/data/shade.tif\",\n}\n\n\n# idea borrowed from Seaborn\ndef open_dataset(\n name,\n cache=True,\n cache_dir=None,\n **kws,\n):\n \"\"\"\n Open a dataset from the online repository (requires internet).\n\n If a local copy is found then always use that to avoid network traffic.\n\n Available datasets:\n\n * ``\"air_temperature\"``: NCEP reanalysis subset\n * ``\"rasm\"``: Output of the Regional Arctic System Model (RASM)\n * ``\"ROMS_example\"``: Regional Ocean Model System (ROMS) output\n * ``\"tiny\"``: small synthetic dataset with a 1D data variable\n * ``\"era5-2mt-2019-03-uk.grib\"``: ERA5 temperature data over the UK\n * ``\"eraint_uvz\"``: data from ERA-Interim reanalysis, monthly averages of upper level data\n\n Parameters\n ----------\n name : str\n Name of the file containing the dataset.\n e.g. 'air_temperature'\n cache_dir : path-like, optional\n The directory in which to search for and write cached data.\n cache : bool, optional\n If True, then cache data locally for use on subsequent calls\n **kws : dict, optional\n Passed to xarray.open_dataset\n\n See Also\n --------\n xarray.open_dataset\n \"\"\"\n try:\n import pooch\n except ImportError as e:\n raise ImportError(\n \"tutorial.open_dataset depends on pooch to download and manage datasets.\"\n \" To proceed please install pooch.\"\n ) from e\n\n logger = pooch.get_logger()\n logger.setLevel(\"WARNING\")\n\n cache_dir = _construct_cache_dir(cache_dir)\n if name in external_urls:\n url = external_urls[name]\n else:\n path = pathlib.Path(name)\n if not path.suffix:\n # process the name\n default_extension = \".nc\"\n path = path.with_suffix(default_extension)\n\n url = f\"{base_url}/raw/{version}/{path.name}\"\n\n # retrieve the file\n filepath = pooch.retrieve(url=url, known_hash=None, path=cache_dir)\n ds = _open_dataset(filepath, **kws)\n if not cache:\n ds = ds.load()\n pathlib.Path(filepath).unlink()\n\n return ds\n\n\ndef open_rasterio(\n name,\n engine=None,\n cache=True,\n cache_dir=None,\n **kws,\n):\n \"\"\"\n Open a rasterio dataset from the online repository (requires internet).\n\n If a local copy is found then always use that to avoid network traffic.\n\n Available datasets:\n\n * ``\"RGB.byte\"``: TIFF file derived from USGS Landsat 7 ETM imagery.\n * ``\"shade\"``: TIFF file derived from from USGS SRTM 90 data\n\n ``RGB.byte`` and ``shade`` are downloaded from the ``rasterio`` repository [1]_.\n\n Parameters\n ----------\n name : str\n Name of the file containing the dataset.\n e.g. 'RGB.byte'\n cache_dir : path-like, optional\n The directory in which to search for and write cached data.\n cache : bool, optional\n If True, then cache data locally for use on subsequent calls\n **kws : dict, optional\n Passed to xarray.open_rasterio\n\n See Also\n --------\n xarray.open_rasterio\n\n References\n ----------\n .. [1] https://github.com/mapbox/rasterio\n \"\"\"\n try:\n import pooch\n except ImportError as e:\n raise ImportError(\n \"tutorial.open_rasterio depends on pooch to download and manage datasets.\"\n \" To proceed please install pooch.\"\n ) from e\n\n logger = pooch.get_logger()\n logger.setLevel(\"WARNING\")\n\n cache_dir = _construct_cache_dir(cache_dir)\n url = external_rasterio_urls.get(name)\n if url is None:\n raise ValueError(f\"unknown rasterio dataset: {name}\")\n\n # retrieve the file\n filepath = pooch.retrieve(url=url, known_hash=None, path=cache_dir)\n arr = _open_rasterio(filepath, **kws)\n if not cache:\n arr = arr.load()\n pathlib.Path(filepath).unlink()\n\n return arr\n\n\ndef load_dataset(*args, **kwargs):\n \"\"\"\n Open, load into memory, and close a dataset from the online repository\n (requires internet).\n\n See Also\n --------\n open_dataset\n \"\"\"\n with open_dataset(*args, **kwargs) as ds:\n return ds.load()\n\n\ndef scatter_example_dataset():\n A = DataArray(\n np.zeros([3, 11, 4, 4]),\n dims=[\"x\", \"y\", \"z\", \"w\"],\n coords=[\n np.arange(3),\n np.linspace(0, 1, 11),\n np.arange(4),\n 0.1 * np.random.randn(4),\n ],\n )\n B = 0.1 * A.x ** 2 + A.y ** 2.5 + 0.1 * A.z * A.w\n A = -0.1 * A.x + A.y / (5 + A.z) + A.w\n ds = Dataset({\"A\": A, \"B\": B})\n ds[\"w\"] = [\"one\", \"two\", \"three\", \"five\"]\n\n ds.x.attrs[\"units\"] = \"xunits\"\n ds.y.attrs[\"units\"] = \"yunits\"\n ds.z.attrs[\"units\"] = \"zunits\"\n ds.w.attrs[\"units\"] = \"wunits\"\n\n ds.A.attrs[\"units\"] = \"Aunits\"\n ds.B.attrs[\"units\"] = \"Bunits\"\n\n return ds\n"
] | [
[
"numpy.arange",
"numpy.zeros",
"numpy.linspace",
"numpy.random.randn"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
hassenmorad/Home-to-Income-Ratio | [
"777754693150ed6f777d084dbace7b8189317c55"
] | [
"Scripts/mort_by_pop_den_5yr_0816.py"
] | [
"# Mortgagea share of income by population density\nimport pandas as pd\nimport numpy as np\nimport array\n\nfile = pd.read_csv('county_rent_mort_inc_units_5yr.csv')\n\nyrs_dict = {}\nfor year in range(2008, 2017):\n print(year)\n yr_df = file[file.Year == year].dropna(subset=['Housing_Den'])\n yr_df.Total_Owned = yr_df.Total_Owned.astype(int) # For np.full in line 32\n \n # FIPS grouped by county population density\n county1k = yr_df.FIPS[(yr_df.Year == year) & (yr_df.Pop_Den > 1000)].values\n county250 = yr_df.FIPS[(yr_df.Year == year) & (yr_df.Pop_Den > 250) & (yr_df.Pop_Den <= 1000)].values\n county100 = yr_df.FIPS[(yr_df.Year == year) & (yr_df.Pop_Den > 100) & (yr_df.Pop_Den <= 250)].values\n county50 = yr_df.FIPS[(yr_df.Year == year) & (yr_df.Pop_Den > 50) & (yr_df.Pop_Den <= 100)].values\n county25 = yr_df.FIPS[(yr_df.Year == year) & (yr_df.Pop_Den > 25) & (yr_df.Pop_Den <= 50)].values\n county10 = yr_df.FIPS[(yr_df.Year == year) & (yr_df.Pop_Den > 10) & (yr_df.Pop_Den <= 25)].values\n countyless10 = yr_df.FIPS[yr_df.Pop_Den <= 10].values\n \n groups_dict = {}\n fips_groups = [county1k, county250, county100, county50, county25, county10, countyless10]\n groups = ['1000', '250', '100', '50', '25', '10', 'Less10']\n counter = 0\n for fips_group in fips_groups:\n fips_mort = array.array('f')\n for fips in fips_group:\n med_mort = yr_df.Med_Mort[yr_df.FIPS == fips].iloc[0]\n home_count = yr_df.Total_Owned[yr_df.FIPS == fips].iloc[0]\n fips_mort.extend(np.full(home_count, med_mort))\n groups_dict[groups[counter]] = np.median(fips_mort).round(3)\n counter += 1\n yrs_dict[year] = groups_dict\n\ndf = pd.DataFrame(yrs_dict)\ndf = df.transpose()\ndf.columns = ['More than 1000', '250 to 1000', '100 to 250', '50 to 100', '25 to 50', '10 to 25', 'Less than 10']\ndf['Year'] = list(range(2008, 2017))\ndf = df.melt(id_vars='Year', var_name='Pop', value_name='Med_Mort')\ndf.to_csv('mort_by_pop_den_5yr_0816.csv', index=False)"
] | [
[
"numpy.median",
"pandas.read_csv",
"pandas.DataFrame",
"numpy.full"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
ryu57/pyHalo | [
"61b9ab49d76f3552f5680b2e457fbd3e49b9cc89",
"61b9ab49d76f3552f5680b2e457fbd3e49b9cc89"
] | [
"pyHalo/Rendering/MassFunctions/power_law.py",
"pyHalo/Rendering/SpatialDistributions/correlated.py"
] | [
"import numpy as np\nfrom pyHalo.Rendering.MassFunctions.mass_function_utilities import integrate_power_law_analytic\nfrom pyHalo.Rendering.MassFunctions.mass_function_utilities import WDM_suppression\n\nclass GeneralPowerLaw(object):\n\n \"\"\"\n This class handles computations of a double power law mass function of the form\n dn/dm = m^x * (1 + (a * m_c / m)^b)^c\n where a, b, and c are constants, and m_c is a characteristic mass scale.\n\n The keywords for a, b, c are a_wdm, b_wdm, and c_wdm, respectively\n\n Lovell 2020 fit this mass function to simulations of Warm Dark Matter cosmologies and find\n (a, b, c) = (2.3, 0.8, -1) for central halos and (4.2, 2.5, -0.2) for subhalos\n \"\"\"\n\n def __init__(self, log_mlow, log_mhigh, power_law_index, draw_poisson, normalization,\n log_mc, a_wdm, b_wdm, c_wdm):\n\n if a_wdm is None:\n assert b_wdm is None, 'If one of a_wdm, b_wdm, or c_wdm is not specified (None), all parameters must be None'\n assert c_wdm is None, 'If one of a_wdm, b_wdm, or c_wdm is not specified (None), all parameters must be None'\n else:\n assert b_wdm is not None, 'Must specify values for all three of a_wdm, b_wdm, c_wdm'\n assert c_wdm is not None, 'Must specify values for all three of a_wdm, b_wdm, c_wdm'\n if b_wdm is None:\n assert a_wdm is None, 'If one of a_wdm, b_wdm, or c_wdm is not specified (None), all parameters must be None'\n assert c_wdm is None, 'If one of a_wdm, b_wdm, or c_wdm is not specified (None), all parameters must be None'\n else:\n assert a_wdm is not None, 'Must specify values for all three of a_wdm, b_wdm, c_wdm'\n assert c_wdm is not None, 'Must specify values for all three of a_wdm, b_wdm, c_wdm'\n if c_wdm is None:\n assert a_wdm is None, 'If one of a_wdm, b_wdm, or c_wdm is not specified (None), all parameters must be None'\n assert b_wdm is None, 'If one of a_wdm, b_wdm, or c_wdm is not specified (None), all parameters must be None'\n else:\n assert a_wdm is not None, 'Must specify values for all three of a_wdm, b_wdm, c_wdm'\n assert b_wdm is not None, 'Must specify values for all three of a_wdm, b_wdm, c_wdm'\n\n if normalization < 0:\n raise Exception('normalization cannot be < 0.')\n if c_wdm is not None and c_wdm > 0:\n raise ValueError('c_wdm should be a negative number (otherwise mass function gets steeper (unphysical)')\n if a_wdm is not None and a_wdm < 0:\n raise ValueError('a_wdm should be a positive number for suppression factor: '\n '( 1 + (a_wdm * m/m_c)^b_wdm)^c_wdm')\n\n if np.any([a_wdm is None, b_wdm is None, c_wdm is None]):\n assert log_mc is None, 'If log_mc is specified, must also specify kwargs for a_wdm, b_wdm, c_wdm.' \\\n '(See documentation in pyHalo/Rendering/MassFunctions/Powerlaw/broken_powerlaw'\n\n self._log_mc = log_mc\n self._a_wdm = a_wdm\n self._b_wdm = b_wdm\n self._c_wdm = c_wdm\n\n self.draw_poisson = draw_poisson\n self._index = power_law_index\n self._mL = 10 ** log_mlow\n self._mH = 10 ** log_mhigh\n\n self._nhalos_mean_unbroken = integrate_power_law_analytic(normalization, 10 ** log_mlow, 10 ** log_mhigh, 0,\n power_law_index)\n\n def draw(self):\n\n \"\"\"\n Draws samples from a double power law distribution between mL and mH of the form\n m ^ power_law_index * (1 + (a*mc / m)^b )^c\n\n Physically, the second term multiplying m^power_law_index can be a suppression in the mass function on small\n scales.\n\n :param draw_poisson:\n :param _index:\n :param _mH:\n :param _mL:\n :param n_draw:\n :return:\n \"\"\"\n\n m = self._sample(self.draw_poisson, self._index, self._mH, self._mL, self._nhalos_mean_unbroken)\n\n if len(m) == 0 or self._log_mc is None:\n return m\n\n factor = WDM_suppression(m, 10 ** self._log_mc, self._a_wdm, self._b_wdm, self._c_wdm)\n u = np.random.rand(int(len(m)))\n inds = np.where(u < factor)\n\n return m[inds]\n\n def _sample(self, draw_poisson, index, mH, mL, n_draw):\n\n \"\"\"\n Draws samples from a power law distribution between mL and mH\n :param draw_poisson:\n :param _index:\n :param _mH:\n :param _mL:\n :param n_draw:\n :return:\n \"\"\"\n\n if draw_poisson:\n N = np.random.poisson(n_draw)\n else:\n N = int(round(np.round(n_draw)))\n\n x = np.random.rand(N)\n if index == -1:\n norm = np.log(mH / mL)\n X = mL * np.exp(norm * x)\n else:\n X = (x * (mH ** (1 + index) - mL ** (1 + index)) + mL ** (\n 1 + index)) ** (\n (1 + index) ** -1)\n\n return np.array(X)\n",
"import numpy as np\n\n\nclass Correlated2D(object):\n \"\"\"\n This class generates points from an arbitrary 2D probability distribution\n \"\"\"\n def __init__(self, geometry, smooth_scale=1.):\n\n \"\"\"\n :param geometry: an instance of Geometry\n :param smooth_scale: a smoothing scale that removes the regular grid\n pattern in the rendered points\n \"\"\"\n self._geo = geometry\n self._smooth_scale = smooth_scale\n\n def draw(self, n, r_max, density, z_plane, shift_x=0., shift_y=0.):\n\n \"\"\"\n\n :param n: the number of points to draw\n :param r_max: the radius in arcsec of the rendering area, should correspond to\n the angular size of density\n :param density: the 2D probability density to sample from\n :param z_plane: the redshift of the lens plane\n :param shift_x: moves the center of rendered points\n from (0, 0) to (shift_x, shift_y)\n :param shift_y: moves the center of rendered points\n from (0, 0) to (shift_x, shift_y)\n :return: x and y samples\n \"\"\"\n norm = np.sum(density)\n if norm == 0:\n raise Exception('2D probability distribution not normalizable')\n\n density = density / np.sum(density)\n\n s = density.shape[0]\n p = density.reshape(-1)\n\n values = np.arange(len(p))\n pairs = np.indices(dimensions=(s, s)).T\n\n x_coordinates_arcsec = np.linspace(-r_max, r_max, s)\n y_coordinates_arcsec = np.linspace(-r_max, r_max, s)\n\n inds = np.random.choice(values, p=p, size=n, replace=True)\n locations = pairs.reshape(-1, 2)[inds]\n x_sample_pixel, y_sample_pixel = locations[:, 0], locations[:, 1]\n\n x_sample_arcsec = x_coordinates_arcsec[x_sample_pixel]\n y_sample_arcsec = y_coordinates_arcsec[y_sample_pixel]\n\n smoothing = self._smooth_scale * r_max / s\n x_sample_arcsec += np.random.normal(0., smoothing, len(x_sample_arcsec))\n y_sample_arcsec += np.random.normal(0., smoothing, len(y_sample_arcsec))\n\n kpc_per_asec = self._geo.kpc_per_arcsec(z_plane)\n\n x_sample_arcsec += shift_x\n y_sample_arcsec += shift_y\n\n x_kpc, y_kpc = x_sample_arcsec * kpc_per_asec, y_sample_arcsec * kpc_per_asec\n\n return x_kpc, y_kpc\n"
] | [
[
"numpy.log",
"numpy.round",
"numpy.random.poisson",
"numpy.random.rand",
"numpy.any",
"numpy.exp",
"numpy.array",
"numpy.where"
],
[
"numpy.indices",
"numpy.sum",
"numpy.linspace",
"numpy.random.choice"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
shinylin/tw-stock-collect-forecast | [
"6af2715a848336d90aaf21f8f93ed1c3568c3fa8"
] | [
"collect/TwHistory.py"
] | [
"import calendar\nimport math\nimport pandas as pd\nimport time\nimport twstock\nimport requests\nfrom datetime import datetime, timedelta\nfrom dateutil import relativedelta\nfrom db.Connection import session\nfrom enum import Enum\nfrom model.StockHistory import StockHistory\nfrom sys import float_info\nfrom talib import abstract\n\nclass HistoryType(Enum):\n DAY = (\"0\", \"日\", \"短線\")\n WEEK = (\"1\", \"週\", \"中短線\")\n MONTH = (\"2\", \"月\", \"中長線\")\n\nclass HistoryTypeTo(Enum):\n DB = 0\n HUMAN = 1\n EXPLAIN = 2\n\nclass TwHistory:\n \"\"\"TwHistory class\"\"\"\n dateFormatForTwStock = None\n dateFormat = None\n rsiDict = None\n williamsDict = None\n macdDict = None\n bbandDict = None\n \n def __init__(self):\n self.dateFormatForTwStock = \"%Y/%m/%d\"\n self.dateFormat = \"%Y-%m-%d\"\n\n def transformStrToDateTimeForTwStock(self, targetStr):\n return datetime.strptime(targetStr, self.dateFormatForTwStock)\n\n def transformStrToDateTime(self, targetStr):\n return datetime.strptime(targetStr, self.dateFormat)\n \n def transformDateTimeToStr(self, date):\n return date.strftime(self.dateFormat)\n \n def retIfNaN(self, num):\n if math.isnan(num):\n return None\n else:\n return num\n \n def createDataFrame(self, history):\n df = pd.DataFrame([h.as_simple_dict() for h in history])\n df['date'] = pd.to_datetime(df['date'])\n df.set_index('date', inplace=True)\n return df\n \n def deleteHistory(self, code, type, startDate, endDate):\n session.query(StockHistory).\\\n filter(StockHistory.code == code).\\\n filter(StockHistory.type == type).\\\n filter(StockHistory.date >= self.transformDateTimeToStr(startDate)).\\\n filter(StockHistory.date <= self.transformDateTimeToStr(endDate)).\\\n delete()\n session.commit()\n\n def calculateRSI(self, df):\n rsi = abstract.RSI(df, timeperiod=5)\n self.rsiDict = {}\n for index, number in rsi.iteritems():\n self.rsiDict[self.transformDateTimeToStr(index)] = number\n\n def calculateWilliams(self, df):\n williams = abstract.WILLR(df, timeperiod=5)\n self.williamsDict = {}\n for index, number in williams.iteritems():\n self.williamsDict[self.transformDateTimeToStr(index)] = number\n\n def calculateMACD(self, df):\n macd = abstract.MACD(df)\n self.macdDict = {}\n for index, row in macd.iterrows():\n self.macdDict[self.transformDateTimeToStr(index)] = row\n\n def calculateBBAND(self, df):\n bband = abstract.BBANDS(df, timeperiod=22)\n self.bbandDict = {}\n for index, row in bband.iterrows():\n self.bbandDict[self.transformDateTimeToStr(index)] = row\n\n def updateHistoryTechnicalIndicator(self, history):\n date = history.date\n updateFlag = False\n if history.rsi is None:\n history.rsi = self.retIfNaN(self.rsiDict[date])\n updateFlag = updateFlag or history.rsi is not None\n if history.williams is None:\n history.williams = self.retIfNaN(self.williamsDict[date])\n updateFlag = updateFlag or history.williams is not None\n if history.macd is None:\n history.macd = self.retIfNaN(self.macdDict[date].macd)\n updateFlag = updateFlag or history.macd is not None\n if history.macdsignal is None:\n history.macdsignal = self.retIfNaN(self.macdDict[date].macdsignal)\n updateFlag = updateFlag or history.macdsignal is not None\n if history.macdhist is None:\n history.macdhist = self.retIfNaN(self.macdDict[date].macdhist)\n updateFlag = updateFlag or history.macdhist is not None\n if history.upperband is None:\n history.upperband = self.retIfNaN(self.bbandDict[date].upperband)\n updateFlag = updateFlag or history.upperband is not None\n if history.middleband is None:\n history.middleband = self.retIfNaN(self.bbandDict[date].middleband)\n updateFlag = updateFlag or history.middleband is not None\n if history.lowerband is None:\n history.lowerband = self.retIfNaN(self.bbandDict[date].lowerband)\n updateFlag = updateFlag or history.lowerband is not None\n if updateFlag:\n session.merge(history)\n\n def dayHistory(self):\n for k, v in twstock.codes.items():\n if self.isStockOrETF(v.type):\n print(\"dayHistory code: \" + k)\n dayType = self.translate(HistoryType.DAY, HistoryTypeTo.DB)\n history = session.query(StockHistory).\\\n filter(StockHistory.code == k).\\\n filter(StockHistory.type == dayType).\\\n order_by(StockHistory.date.desc()).\\\n first()\n nowDate = datetime.now()\n endDateStr = self.transformDateTimeToStr(nowDate)\n startDateStr = self.transformDateTimeToStr(self.transformStrToDateTimeForTwStock(v.start)) if history is None else history.date\n\n self.finmindtrade(k, startDateStr, endDateStr, dayType)\n\n def weekHistory(self):\n today = self.transformStrToDateTime(self.transformDateTimeToStr(datetime.now()))\n weekStart = today - timedelta(days=today.weekday())\n\n for k, v in twstock.codes.items():\n if self.isStockOrETF(v.type) and self.isHistoryExist(k):\n print(\"weekHistory code: \" + k)\n latestHistoryWeek = session.query(StockHistory).\\\n filter(StockHistory.code == k).\\\n filter(StockHistory.type == self.translate(HistoryType.WEEK, HistoryTypeTo.DB)).\\\n order_by(StockHistory.date.desc()).\\\n first()\n\n startdate = self.transformStrToDateTimeForTwStock(v.start) if latestHistoryWeek is None else self.transformStrToDateTime(latestHistoryWeek.date)\n weekStartPast = startdate - timedelta(days=startdate.weekday())\n weekEndPast = weekStartPast + timedelta(days=6)\n\n while weekStartPast <= weekStart:\n self.deleteHistory(k, self.translate(HistoryType.WEEK, HistoryTypeTo.DB), weekStartPast, weekEndPast)\n historyWeek = StockHistory(code=k, type=self.translate(HistoryType.WEEK, HistoryTypeTo.DB),\n capacity=0, turnover=0, high=0, low=float_info.max, close=0)\n firstFlag = True\n for historyDay in session.query(StockHistory).\\\n filter(StockHistory.code == k).\\\n filter(StockHistory.type == self.translate(HistoryType.DAY, HistoryTypeTo.DB)).\\\n filter(StockHistory.date >= self.transformDateTimeToStr(weekStartPast)).\\\n filter(StockHistory.date <= self.transformDateTimeToStr(weekEndPast)).\\\n order_by(StockHistory.date.asc()).\\\n all():\n historyWeek.date = self.transformDateTimeToStr(weekStartPast)\n historyWeek.close = historyDay.close\n historyWeek.capacity += historyDay.capacity\n historyWeek.turnover += historyDay.turnover\n if firstFlag:\n historyWeek.open = historyDay.open\n firstFlag = False\n historyWeek.high = max(historyWeek.high, historyDay.high)\n historyWeek.low = min(historyWeek.low, historyDay.low)\n if not firstFlag:\n session.merge(historyWeek)\n weekStartPast += timedelta(days=7)\n weekEndPast += timedelta(days=7)\n\n session.commit()\n\n def monthHistory(self):\n today = self.transformStrToDateTime(self.transformDateTimeToStr(datetime.now()))\n monthStart = today.replace(day=1)\n\n for k, v in twstock.codes.items():\n if self.isStockOrETF(v.type) and self.isHistoryExist(k):\n print(\"monthHistory code: \" + k)\n latestHistoryMonth = session.query(StockHistory).\\\n filter(StockHistory.code == k).\\\n filter(StockHistory.type == self.translate(HistoryType.MONTH, HistoryTypeTo.DB)).\\\n order_by(StockHistory.date.desc()).\\\n first()\n\n startdate = self.transformStrToDateTimeForTwStock(v.start) if latestHistoryMonth is None else self.transformStrToDateTime(latestHistoryMonth.date)\n monthStartPast = startdate.replace(day=1)\n monthEndPast = monthStartPast.replace(day=calendar.monthrange(monthStartPast.year, monthStartPast.month)[1])\n\n while monthStartPast <= monthStart:\n self.deleteHistory(k, self.translate(HistoryType.MONTH, HistoryTypeTo.DB), monthStartPast, monthEndPast)\n historyMonth = StockHistory(code=k, type=self.translate(HistoryType.MONTH, HistoryTypeTo.DB),\n capacity=0, turnover=0, high=0, low=float_info.max, close=0)\n firstFlag = True\n for historyDay in session.query(StockHistory).\\\n filter(StockHistory.code == k).\\\n filter(StockHistory.type == self.translate(HistoryType.DAY, HistoryTypeTo.DB)).\\\n filter(StockHistory.date >= self.transformDateTimeToStr(monthStartPast)).\\\n filter(StockHistory.date <= self.transformDateTimeToStr(monthEndPast)).\\\n order_by(StockHistory.date.asc()).\\\n all():\n historyMonth.date = self.transformDateTimeToStr(monthStartPast)\n historyMonth.close = historyDay.close\n historyMonth.capacity += historyDay.capacity\n historyMonth.turnover += historyDay.turnover\n if firstFlag:\n historyMonth.open = historyDay.open\n firstFlag = False\n historyMonth.high = max(historyMonth.high, historyDay.high)\n historyMonth.low = min(historyMonth.low, historyDay.low)\n if not firstFlag:\n session.merge(historyMonth)\n monthStartPast = monthStartPast + relativedelta.relativedelta(months=1)\n monthEndPast = monthStartPast.replace(day=calendar.monthrange(monthStartPast.year, monthStartPast.month)[1])\n\n session.commit()\n\n def technicalIndicator(self):\n for k, v in twstock.codes.items():\n if self.isStockOrETF(v.type) and self.isHistoryExist(k):\n for historyType in HistoryType:\n print(\"technicalIndicator code: \" + k + \", type: \" + self.translate(historyType, HistoryTypeTo.HUMAN))\n historyList = session.query(StockHistory).\\\n filter(StockHistory.code == k).\\\n filter(StockHistory.type == self.translate(historyType, HistoryTypeTo.DB)).\\\n order_by(StockHistory.date.asc()).\\\n all()\n if len(historyList) == 0:\n continue\n df = self.createDataFrame(historyList)\n\n self.calculateRSI(df)\n self.calculateWilliams(df)\n self.calculateMACD(df)\n self.calculateBBAND(df)\n\n for history in historyList:\n self.updateHistoryTechnicalIndicator(history)\n session.commit()\n\n def diverge(self, highRsi, lowRsi, highWilliams, lowWilliams):\n turnoverDict = {}\n nameDict = {}\n\n for k, v in twstock.codes.items():\n if self.isStockOrETF(v.type) and self.isHistoryExist(k):\n history = session.query(StockHistory).\\\n filter(StockHistory.code == k).\\\n filter(StockHistory.type == self.translate(HistoryType.DAY, HistoryTypeTo.DB)).\\\n order_by(StockHistory.date.desc()).\\\n first()\n turnoverDict[k] = history.turnover\n nameDict[k] = v.name\n\n rankDict = {k: v for k, v in sorted(turnoverDict.items(), key=lambda item: item[1], reverse=True)}\n\n print(\"按當日成交值由大至小排名,背離條件: rsi > \" + str(highRsi) + \" or rsi < \" + str(lowRsi))\n for rankIdx, code in enumerate(rankDict.keys()):\n closePrice = None\n divergeDict = {}\n for historyType in HistoryType:\n historyTypeHuman = self.translate(historyType, HistoryTypeTo.HUMAN)\n historyTypeExplain = self.translate(historyType, HistoryTypeTo.EXPLAIN)\n historyList = session.query(StockHistory).\\\n filter(StockHistory.code == code).\\\n filter(StockHistory.type == self.translate(historyType, HistoryTypeTo.DB)).\\\n filter(StockHistory.rsi.isnot(None)).\\\n order_by(StockHistory.date.desc()).\\\n limit(self.recentHistoryLimit(historyType)).\\\n all()\n historyListLength = len(historyList)\n if historyListLength > 0:\n closePrice = historyList[0].close\n if historyListLength > 1:\n if self.isHighRsi(highRsi, historyList) and historyList[0].rsi > historyList[1].rsi and historyList[0].williams < historyList[1].williams and historyList[0].upperband is not None and historyList[0].high > historyList[0].upperband and historyList[0].close < historyList[0].open:\n divergeDict[historyTypeHuman + \" 相鄰背離 \" + historyTypeExplain + \"看空\"] = \"rsi up williams down\"\n elif self.isLowRsi(lowRsi, historyList) and historyList[0].rsi < historyList[1].rsi and historyList[0].williams > historyList[1].williams and historyList[0].lowerband is not None and historyList[0].low < historyList[0].lowerband and historyList[0].close > historyList[0].open:\n divergeDict[historyTypeHuman + \" 相鄰背離 \" + historyTypeExplain + \"看多\"] = \"rsi down williams up\"\n# if historyListLength > 2:\n# highPeak = []\n# lowPeak = []\n# for i, history in enumerate(historyList):\n# if i == 0 or i == historyListLength - 1:\n# continue\n# if len(highPeak) < 2 and historyList[i-1].rsi < history.rsi and history.rsi > historyList[i+1].rsi:\n# highPeak.append(history)\n# if len(lowPeak) < 2 and historyList[i-1].rsi > history.rsi and history.rsi < historyList[i+1].rsi:\n# lowPeak.append(history)\n# if len(highPeak) == 2 and len(lowPeak) == 2:\n# break\n# if len(highPeak) == 2 and self.isHighRsi(highRsi, highPeak):\n# if highPeak[0].rsi > highPeak[1].rsi and highPeak[0].williams < highPeak[1].williams:\n# divergeDict[historyTypeHuman + \" 波峰背離 \" + historyTypeExplain + \"看空: \" + highPeak[1].date + \" and \" + highPeak[0].date] = \"rsi up williams down\"\n# elif highPeak[0].rsi < highPeak[1].rsi and highPeak[0].williams > highPeak[1].williams and highPeak[0].williams >= highWilliams:\n# for low in lowPeak:\n# if highPeak[0].date > low.date and highPeak[1].date < low.date and low.williams <= lowWilliams:\n# divergeDict[historyTypeHuman + \" 波峰背離 反彈不過前高 \" + historyTypeExplain + \"看空: \" + highPeak[1].date + \" and \" + highPeak[0].date] = \"rsi down williams fast up\"\n# break\n# if len(lowPeak) == 2 and self.isLowRsi(lowRsi, lowPeak):\n# if lowPeak[0].rsi < lowPeak[1].rsi and lowPeak[0].williams > lowPeak[1].williams:\n# divergeDict[historyTypeHuman + \" 波谷背離 \" + historyTypeExplain + \"看多: \" + lowPeak[1].date + \" and \" + lowPeak[0].date] = \"rsi down williams up\"\n# elif lowPeak[0].rsi > lowPeak[1].rsi and lowPeak[0].williams < lowPeak[1].williams and lowPeak[0].williams <= lowWilliams:\n# for high in highPeak:\n# if lowPeak[0].date > high.date and lowPeak[1].date < high.date and high.williams >= highWilliams:\n# divergeDict[historyTypeHuman + \" 波谷背離 回測不過前低 \" + historyTypeExplain + \"看多: \" + lowPeak[1].date + \" and \" + lowPeak[0].date] = \"rsi up williams fast down\"\n# break\n\n if len(divergeDict) > 0:\n print(\"code: \" + code + \", name: \" + nameDict[code] + \", rank: \" + str(rankIdx+1) + \"/\" + str(len(rankDict)) + \", close price: \" + str(closePrice))\n for k, v in divergeDict.items():\n print(k + \" => \" + v)\n print(\"\")\n print(\"========================================================================================\")\n\n def isStockOrETF(self, type):\n return type == \"股票\" or type == \"ETF\"\n\n def isHistoryExist(self, code):\n return session.query(StockHistory).\\\n filter(StockHistory.code == code).\\\n filter(StockHistory.type == self.translate(HistoryType.DAY, HistoryTypeTo.DB)).\\\n filter(StockHistory.date == self.transformDateTimeToStr(datetime.now())).\\\n first() is not None\n\n def isHighRsi(self, highRsi, historyList):\n for i, history in enumerate(historyList):\n if i < 2 and history.rsi < highRsi:\n return False\n elif i == 2:\n break\n return True\n\n def isLowRsi(self, lowRsi, historyList):\n for i, history in enumerate(historyList):\n if i < 2 and history.rsi > lowRsi:\n return False\n elif i == 2:\n break\n return True\n\n def recentHistoryLimit(self, historyType):\n if historyType == HistoryType.DAY:\n return 40\n elif historyType == HistoryType.WEEK:\n return 16\n else:\n return 6\n\n def translate(self, historyType, historyTypeTo):\n return historyType.value[historyTypeTo.value]\n\n def finmindtrade(self, code, start, end, dayType):\n url = \"https://api.finmindtrade.com/api/v4/data\"\n parameter = {\n \"dataset\": \"TaiwanStockPrice\",\n \"data_id\": code,\n \"start_date\": start,\n \"end_date\": end,\n \"token\": \"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJkYXRlIjoiMjAyMS0wOS0yMiAxMzo0MzoyOSIsInVzZXJfaWQiOiJzaGlueWxpbiIsImlwIjoiMjEwLjY0LjE4LjIifQ.0USWMl--2LhZ9W8nyEQncyyw3Jfm-hu5xzJrNOCuEUU\"\n }\n resp = requests.get(url, params=parameter)\n json = resp.json()\n if json is not None:\n for data in resp.json()[\"data\"]:\n history = StockHistory(code=code, type=dayType, date=data[\"date\"],\n capacity=data[\"Trading_Volume\"], turnover=data[\"Trading_money\"],\n open=data[\"open\"], high=data[\"max\"], low=data[\"min\"], close=data[\"close\"])\n session.merge(history)\n session.commit()\n time.sleep(6.1)\n\ntwHistory = TwHistory()\ntwHistory.dayHistory()\ntwHistory.weekHistory()\ntwHistory.monthHistory()\ntwHistory.technicalIndicator()\ntwHistory.diverge(90, 10, -20, -80)\ntwHistory.diverge(80, 20, -20, -80)\ntwHistory.diverge(70, 30, -20, -80)"
] | [
[
"pandas.to_datetime"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
erwinvanthiel/ASL | [
"1b8846919f4bcf7bf65881faf254395cb01f8ae3"
] | [
"mlc-pgd-multi-label.py"
] | [
"import os\nimport torch\nfrom src.helper_functions.helper_functions import parse_args\nfrom src.loss_functions.losses import AsymmetricLoss, AsymmetricLossOptimized\nfrom src.models import create_model\nimport argparse\nimport matplotlib\nimport torchvision.transforms as transforms\nfrom pgd import create_targeted_adversarial_examples\n# matplotlib.use('TkAgg')\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nimport numpy as np\nfrom src.helper_functions.helper_functions import mAP, CocoDetection, CocoDetectionFiltered, CutoutPIL, ModelEma, add_weight_decay\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\") # USE GPU\n\n########################## ARGUMENTS #############################################\n\nparser = argparse.ArgumentParser(description='ASL MS-COCO Inference on a single image')\n\nparser.add_argument('data', metavar='DIR', help='path to dataset', default='coco')\nparser.add_argument('--model_path', type=str, default='mlc-model-epoch50')\nparser.add_argument('--pic_path', type=str, default='./pics/test.jpg')\nparser.add_argument('--model_name', type=str, default='tresnet_m')\nparser.add_argument('--input_size', type=int, default=224)\nparser.add_argument('--dataset_type', type=str, default='MS-COCO')\n\n#IMPORTANT PARAMETER!\nparser.add_argument('--th', type=float, default=0.5)\n\n\nparser.add_argument('-b', '--batch-size', default=16, type=int,\n metavar='N', help='mini-batch size (default: 16)')\nparser.add_argument('-j', '--workers', default=8, type=int, metavar='N',\n help='number of data loading workers (default: 16)')\nargs = parse_args(parser)\n\n########################## SETUP THE MODEL AND LOAD THE DATA #####################\n\n# setup model\nprint('creating and loading the model...')\n# state = torch.load(args.model_path, map_location='cpu')\nargs.num_classes = 80\nmodel = create_model(args).cuda()\nmodel_state = torch.load(args.model_path, map_location='cpu')\nmodel.load_state_dict(model_state[\"state_dict\"])\nmodel.eval()\n\n\n# Load the data\ninstances_path = os.path.join(args.data, 'annotations/instances_train2014.json')\n# data_path_train = args.data\ndata_path = '{0}/train2014'.format(args.data)\n\n\n################ EXPERIMENT DETAILS ########################\n\nNUMBER_OF_BATCHES = 64\n# TARGET_LABELS = [0, 1, 11, 56, 78, 79]\nTARGET_LABELS = [0, 78]\nEPSILON_VALUES = [0, 0.005, 0.01, 0.02, 0.05, 0.1]\n\n########################## EXPERIMENT LOOP #####################\n\n\n\ndataset = CocoDetectionFiltered(data_path,\n instances_path,\n transforms.Compose([\n transforms.Resize((args.input_size, args.input_size)),\n transforms.ToTensor(),\n # normalize, # no need, toTensor does normalization\n ]), label_indices_positive=np.array(TARGET_LABELS))\n\n# Pytorch Data loader\ndata_loader = torch.utils.data.DataLoader(\n dataset, batch_size=args.batch_size, shuffle=True,\n num_workers=args.workers, pin_memory=True)\n\n# zero for each epsion value\nflipped_labels = np.zeros((len(EPSILON_VALUES), len(TARGET_LABELS)))\n\nfor i, (tensor_batch, labels) in enumerate(data_loader):\n tensor_batch = tensor_batch.to(device)\n\n if i >= NUMBER_OF_BATCHES:\n break;\n\n # process a batch and add the flipped labels for every epsilon\n for epsilon_index in range(len(EPSILON_VALUES)):\n\n # perform the pgd attack\n pred = torch.sigmoid(model(tensor_batch)) > args.th\n target = torch.clone(pred).detach()\n target[:, TARGET_LABELS] = 0\n adversarials = create_targeted_adversarial_examples(model, tensor_batch, target, eps=EPSILON_VALUES[epsilon_index], device=\"cuda\")\n\n # do inference again\n pred_after_attack = torch.sigmoid(model(adversarials)) > args.th\n \n # compare the attaced labels before and after the attack\n\n for _id, target_label in enumerate(TARGET_LABELS):\n flipped_labels[epsilon_index, _id] += (torch.sum(pred[:, target_label]).item() - torch.sum(pred_after_attack[:, target_label]).item())\n\n# plot and save the figures\n# plt.figure()\nfor _id, target_label in enumerate(TARGET_LABELS):\n plt.plot(EPSILON_VALUES, flipped_labels[:, _id], label='target {0}'.format(target_label))\nplt.xlabel(\"Epsilon\")\nplt.ylabel(\"Number of flipped labels\")\nplt.title(\"PGD multi-label flipdown attack\")\nplt.legend()\nplt.savefig('flipdown-pgd-multi-attack.png')\n\n\n\n\n\n\n# displaying image\n# print('showing image on screen...')\n# fig = plt.figure()\n# plt.imshow(im)\n# plt.axis('off')\n# plt.axis('tight')\n# # plt.rcParams[\"axes.titlesize\"] = 10\n# plt.title(\"detected classes: {}\".format(detected_classes))\n\n# plt.show()\n# print('done\\n')"
] | [
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.title",
"torch.load",
"torch.clone",
"torch.utils.data.DataLoader",
"torch.sum",
"matplotlib.pyplot.savefig",
"torch.cuda.is_available",
"matplotlib.pyplot.xlabel",
"numpy.array",
"matplotlib.pyplot.ylabel"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ZERO2ER0/OpticalNN | [
"56e34a02d9855951fc3a28d0bfddcdbad85a0c90"
] | [
"onn/onn.py"
] | [
"\"\"\"\nreplace first layer of AlexNet with optical setup\nAdapted other layers of AlexNet code from AlexNet.py, code written by Frederik Kratzert at\nhttps://kratzert.github.io/2017/02/24/finetuning-alexnet-with-tensorflow.html\n\"\"\"\nimport tensorflow as tf\nimport numpy as np\nIterator = tf.data.Iterator\n\n\n# xx, yy, Lambda, k_z_values can all be generated from onn_setup.ipynb.\nxx = np.load('xx.npy')\nyy = np.load('yy.npy')\nLambda = np.load('Lambda.npy')\nk_z_values = np.load('k_z_values.npy')\nx_tensor = tf.constant(xx, tf.float32)\ny_tensor = tf.constant(yy, tf.float32)\nLambda_tensor = tf.constant(Lambda, tf.float32)\nk_z = tf.constant(k_z_values, tf.complex64)\nf = tf.constant(0.3E-2)\n\n\ndef fftshift_tf(data):\n \"\"\"\n :param data: input tensor to do fftshift\n :return: after fftshift\n \"\"\"\n dims = tf.shape(data)\n num = dims[3]\n shift_amt = (num - 1) / 2\n shift_amt = tf.cast(shift_amt, np.int32)\n output = tf.manip.roll(data, shift=shift_amt, axis=2)\n output = tf.manip.roll(output, shift=shift_amt, axis=3)\n\n return output\n\n\ndef ifftshift_tf(data):\n \"\"\"\n Performs an ifftshift operation on the last two dimensions of a 4-D input tensor\n :param data: input tensor to do ifftshift\n :return: after ifftshift\n \"\"\"\n dims = tf.shape(data)\n num = dims[3]\n shift_amt = (num + 1) / 2\n shift_amt = tf.cast(shift_amt, np.int32)\n output = tf.manip.roll(data, shift=shift_amt, axis=2)\n output = tf.manip.roll(output, shift=shift_amt, axis=3)\n\n return output\n\n\ndef generate_phase():\n \"\"\"\n Generates the phase for a lens based on the focal length variable \"f\".\n Other referenced variables are global\n :return: phase generated\n \"\"\"\n phase = tf.constant(2 * np.pi, tf.float32)\\\n / Lambda * (tf.sqrt(tf.square(x_tensor) + tf.square(y_tensor) + tf.square(f)) - f)\n phase = tf.cast(phase, tf.complex64)\n return phase\n\n\ndef generate_propagator():\n \"\"\"\n Generates the Fourier space propagator based on the focal length variable \"f\".\n Other referenced variables are global\n :return: propagator generated\n \"\"\"\n propagator = tf.exp(1j * k_z * tf.cast(f, tf.complex64))\n propagator = ifftshift_tf(propagator)\n\n return propagator\n\n\ndef propagate(input_field, propagator):\n \"\"\"\n Propagate an input E-field distribution along the optical axis using the defined propagator\n :param input_field: input field for doing propagation\n :param propagator: generated propagator\n :return: result after propagation\n \"\"\"\n output = tf.ifft2d(tf.fft2d(input_field) * propagator)\n\n return output\n\n\ndef simulate_4f_system(input_field, kernel):\n \"\"\"\n Pass an image through a 4f system\n :param input_field: input field of our 4f system\n :param kernel: kernel for doing convolution\n :return: output of our 4f system\n \"\"\"\n # Calculate the lens phase\n lens_phase = generate_phase()\n\n # Calculate the propagator\n propagator = generate_propagator()\n\n # Propagate up to the first lens\n before_l1 = propagate(input_field, propagator)\n\n # Apply lens1 and propagate to the filter plane\n before_kernel = propagate(before_l1 * tf.keras.backend.exp(-1j * lens_phase), propagator)\n\n # Apply kernel and propagate to the second lens\n before_l2 = propagate(before_kernel * kernel, propagator)\n\n # Apply lens2 and propagate to the output plane\n output = propagate(before_l2 * tf.keras.backend.exp(-1j * lens_phase), propagator)\n\n # Return output of the 4f optical convolution\n return output\n\n\ndef convolve_with_all_kernels(image, batch_size, name):\n \"\"\"\n doing convolution with all kernels in frequency domain\n :param image: input image\n :param kernel_in: kernel for doing convolution\n :param name: scope name\n :return: result after doing convolution with all kernels\n \"\"\"\n with tf.variable_scope(name) as scope:\n kernel = tf.get_variable(name='weights', trainable=True,\n shape=[11, 11, 3, 96])\n # f = tf.get_variable(name ='f', initializer=0.3E-2, trainable=True)\n # Zero pad the kernels for subsequent Fourier processing\n kernels = tf.concat([kernel, tf.constant(np.zeros((11, 216, 3, 96)), tf.float32)], axis=1)\n kernels = tf.concat([kernels, tf.constant(np.zeros((216, 227, 3, 96)), tf.float32)], axis=0)\n\n # Align the kernels for Fourier transforming\n kernels = tf.transpose(kernels, perm=[3, 2, 0, 1])\n kernels = tf.cast(kernels, tf.complex64)\n kernels = tf.fft2d(kernels)\n kernels = ifftshift_tf(kernels)\n\n # Add an extra dimension for the batch size and duplicate\n # the kernels to apply equally to all images in the batch\n kernels = tf.expand_dims(kernels, axis=0)\n kernels = tf.tile(kernels, multiples=[batch_size, 1, 1, 1, 1])\n\n # Add a dimension to the input image tensor to\n # enable convolution with all 96 first layer kernels\n image = tf.cast(image, tf.complex64)\n image = tf.expand_dims(image, axis=1)\n image = tf.transpose(image, perm=[0, 1, 4, 2, 3])\n image = tf.tile(image, multiples=[1, 96, 1, 1, 1])\n\n # Simulate the 4f system output for all 96 kernels\n # for all color channels and sum the channel outputs\n output = tf.reduce_sum(tf.abs(simulate_4f_system(image, kernels)) ** 2, axis=2)\n\n # Transpose and flip the output for display purposes\n output = tf.transpose(output, perm=[0, 2, 3, 1])\n output = tf.image.flip_left_right(output)\n output = tf.image.flip_up_down(output)\n\n # Convert to float format\n output = tf.cast(output, tf.float32)\n\n # Return the output\n return output\n\n\nclass ONN(object):\n \"\"\"Implementation of ONN based on AlexNet implementation.\"\"\"\n\n def __init__(self, x, batch_size, keep_prob, num_classes, skip_layer, weights_path='DEFAULT'):\n \"\"\"Create the graph of the ONN model.\n\n Args:\n x: Placeholder for the input tensor.\n batch_size: batch_size for training\n keep_prob: Dropout probability.\n num_classes: Number of classes in the dataset.\n skip_layer: List of names of the layer, that get trained from\n scratch\n weights_path: Complete path to the pretrained weight file, if it\n isn't in the same folder as this code\n \"\"\"\n # Parse input arguments into class variables\n self.X = x\n self.NUM_CLASSES = num_classes\n self.BATCH_SIZE = batch_size\n self.SKIP_LAYER = skip_layer\n self.KEEP_PROB = keep_prob\n if weights_path == 'DEFAULT':\n self.WEIGHTS_PATH = 'kernel_alexnet.npy'\n else:\n self.WEIGHTS_PATH = weights_path\n\n # Call the create function to build the computational graph of AlexNet\n self.create()\n\n def create(self):\n \"\"\"Create the network graph.\"\"\"\n # 1st Layer: OP-conv\n conv1 = convolve_with_all_kernels(self.X, self.BATCH_SIZE, 'op')\n norm1 = lrn(conv1, 2, 1e-05, 0.75, name='norm1')\n pool1 = max_pool(norm1, 3, 3, 2, 2, padding='VALID', name='pool1')\n\n # 2nd Layer: Conv (w ReLu) -> Lrn -> Pool with 2 groups\n conv2 = conv(pool1, 5, 5, 256, 1, 1, groups=2, name='conv2')\n norm2 = lrn(conv2, 2, 1e-05, 0.75, name='norm2')\n pool2 = max_pool(norm2, 3, 3, 2, 2, padding='VALID', name='pool2')\n\n # 3rd Layer: Conv (w ReLu)\n conv3 = conv(pool2, 3, 3, 384, 1, 1, name='conv3')\n\n # 4th Layer: Conv (w ReLu) splitted into two groups\n conv4 = conv(conv3, 3, 3, 384, 1, 1, groups=2, name='conv4')\n\n # 5th Layer: Conv (w ReLu) -> Pool splitted into two groups\n conv5 = conv(conv4, 3, 3, 256, 1, 1, groups=2, name='conv5')\n pool5 = max_pool(conv5, 3, 3, 2, 2, padding='VALID', name='pool5')\n\n # 6th Layer: Flatten -> FC (w ReLu) -> Dropout\n flattened = tf.reshape(pool5, [-1, 27 * 27 * 256])\n fc6 = fc(flattened, 27 * 27 * 256, 4096, name='fc6')\n dropout6 = dropout(fc6, self.KEEP_PROB)\n\n # 7th Layer: FC (w ReLu) -> Dropout\n fc7 = fc(dropout6, 4096, 4096, name='fc7')\n dropout7 = dropout(fc7, self.KEEP_PROB)\n\n # 8th Layer: FC and return unscaled activations\n self.fc8 = fc(dropout7, 4096, self.NUM_CLASSES, relu=False, name='fc8')\n\n def load_initial_weights(self, session):\n \"\"\"\n load pre-trained kernel from first layer of AlexNet\n \"\"\"\n # Load the weights into memory\n kernel_pretrained = np.load(self.WEIGHTS_PATH, encoding='bytes')\n with tf.variable_scope('op', reuse=True):\n # Assign kernel to its corresponding tf variable\n var = tf.get_variable('weights', trainable=False)\n session.run(var.assign(kernel_pretrained))\n\n\ndef conv(x, filter_height, filter_width, num_filters, stride_y, stride_x, name,\n padding='SAME', groups=1):\n \"\"\"Create a convolution layer.\n Adapted from: https://github.com/ethereon/caffe-tensorflow\n \"\"\"\n # Get number of input channels\n input_channels = int(x.get_shape()[-1])\n\n # Create lambda function for the convolution\n convolve = lambda i, k: tf.nn.conv2d(i, k,\n strides=[1, stride_y, stride_x, 1],\n padding=padding)\n\n with tf.variable_scope(name) as scope:\n # Create tf variables for the weights and biases of the conv layer\n weights = tf.get_variable('weights', trainable=True, shape=[filter_height,\n filter_width,\n input_channels / groups,\n num_filters])\n biases = tf.get_variable('biases', trainable=True, shape=[num_filters])\n\n if groups == 1:\n conv = convolve(x, weights)\n\n # In the cases of multiple groups, split inputs & weights and\n else:\n # Split input and weights and convolve them separately\n input_groups = tf.split(axis=3, num_or_size_splits=groups, value=x)\n weight_groups = tf.split(axis=3, num_or_size_splits=groups,\n value=weights)\n output_groups = [convolve(i, k) for i, k in zip(input_groups, weight_groups)]\n\n # Concat the convolved output together again\n conv = tf.concat(axis=3, values=output_groups)\n\n # Add biases\n bias = tf.reshape(tf.nn.bias_add(conv, biases), tf.shape(conv))\n\n # Apply relu function\n relu = tf.nn.relu(bias, name=scope.name)\n\n return relu\n\n\ndef fc(x, num_in, num_out, name, relu=True):\n \"\"\"Create a fully connected layer.\"\"\"\n with tf.variable_scope(name) as scope:\n\n # Create tf variables for the weights and biases\n weights = tf.get_variable('weights', shape=[num_in, num_out], trainable=True)\n biases = tf.get_variable('biases', shape=[num_out], trainable=True)\n\n # Matrix multiply weights and inputs and add bias\n act = tf.nn.xw_plus_b(x, weights, biases, name=scope.name)\n\n if relu:\n # Apply ReLu non linearity\n relu = tf.nn.relu(act)\n return relu\n else:\n return act\n\n\ndef max_pool(x, filter_height, filter_width, stride_y, stride_x, name,\n padding='SAME'):\n \"\"\"Create a max pooling layer.\"\"\"\n return tf.nn.max_pool(x, ksize=[1, filter_height, filter_width, 1],\n strides=[1, stride_y, stride_x, 1],\n padding=padding, name=name)\n\n\ndef lrn(x, radius, alpha, beta, name, bias=1.0):\n \"\"\"Create a local response normalization layer.\"\"\"\n return tf.nn.local_response_normalization(x, depth_radius=radius,\n alpha=alpha, beta=beta,\n bias=bias, name=name)\n\n\ndef dropout(x, keep_prob):\n \"\"\"Create a dropout layer.\"\"\"\n return tf.nn.dropout(x, keep_prob)\n"
] | [
[
"tensorflow.get_variable",
"tensorflow.concat",
"tensorflow.nn.max_pool",
"tensorflow.cast",
"tensorflow.nn.conv2d",
"tensorflow.keras.backend.exp",
"tensorflow.square",
"numpy.load",
"numpy.zeros",
"tensorflow.tile",
"tensorflow.nn.dropout",
"tensorflow.nn.xw_plus_b",
"tensorflow.manip.roll",
"tensorflow.shape",
"tensorflow.fft2d",
"tensorflow.split",
"tensorflow.nn.bias_add",
"tensorflow.nn.relu",
"tensorflow.constant",
"tensorflow.transpose",
"tensorflow.reshape",
"tensorflow.expand_dims",
"tensorflow.image.flip_left_right",
"tensorflow.image.flip_up_down",
"tensorflow.variable_scope",
"tensorflow.nn.local_response_normalization"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
naviocean/imgclsmob | [
"f2993d3ce73a2f7ddba05da3891defb08547d504",
"f2993d3ce73a2f7ddba05da3891defb08547d504",
"f2993d3ce73a2f7ddba05da3891defb08547d504",
"f2993d3ce73a2f7ddba05da3891defb08547d504",
"f2993d3ce73a2f7ddba05da3891defb08547d504",
"f2993d3ce73a2f7ddba05da3891defb08547d504",
"f2993d3ce73a2f7ddba05da3891defb08547d504",
"f2993d3ce73a2f7ddba05da3891defb08547d504",
"f2993d3ce73a2f7ddba05da3891defb08547d504",
"f2993d3ce73a2f7ddba05da3891defb08547d504",
"f2993d3ce73a2f7ddba05da3891defb08547d504",
"f2993d3ce73a2f7ddba05da3891defb08547d504",
"f2993d3ce73a2f7ddba05da3891defb08547d504",
"f2993d3ce73a2f7ddba05da3891defb08547d504",
"f2993d3ce73a2f7ddba05da3891defb08547d504",
"f2993d3ce73a2f7ddba05da3891defb08547d504",
"f2993d3ce73a2f7ddba05da3891defb08547d504",
"f2993d3ce73a2f7ddba05da3891defb08547d504"
] | [
"gluon/gluoncv2/models/fdmobilenet.py",
"train_pt.py",
"train_ke.py",
"chainer_/chainercv2/models/seresnet_cifar.py",
"tensorflow2/tf2cv/models/inceptionresnetv1.py",
"pytorch/metrics/det_metrics.py",
"gluon/gluoncv2/models/fishnet.py",
"pytorch/pytorchcv/models/sknet.py",
"gluon/datasets/cityscapes_seg_dataset.py",
"pytorch/pytorchcv/models/others/_espnet.py",
"pytorch/pytorchcv/models/bamresnet.py",
"gluon/gluoncv2/models/ibppose_coco.py",
"tensorflow_/tensorflowcv/models/shufflenetv2.py",
"keras_/kerascv/models/shufflenetv2.py",
"pytorch/pytorchcv/models/wrn_cifar.py",
"tensorflow_/tensorflowcv/models/model_store.py",
"gluon/gluoncv2/models/lwopenpose_cmupan.py",
"gluon/gluoncv2/models/simplepose_coco.py"
] | [
"\"\"\"\n FD-MobileNet for ImageNet-1K, implemented in Gluon.\n Original paper: 'FD-MobileNet: Improved MobileNet with A Fast Downsampling Strategy,'\n https://arxiv.org/abs/1802.03750.\n\"\"\"\n\n__all__ = ['fdmobilenet_w1', 'fdmobilenet_w3d4', 'fdmobilenet_wd2', 'fdmobilenet_wd4', 'get_fdmobilenet']\n\nimport os\nfrom mxnet import cpu\nfrom .mobilenet import MobileNet\n\n\ndef get_fdmobilenet(width_scale,\n model_name=None,\n pretrained=False,\n ctx=cpu(),\n root=os.path.join(\"~\", \".mxnet\", \"models\"),\n **kwargs):\n \"\"\"\n Create FD-MobileNet model with specific parameters.\n\n Parameters:\n ----------\n width_scale : float\n Scale factor for width of layers.\n model_name : str or None, default None\n Model name for loading pretrained model.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n ctx : Context, default CPU\n The context in which to load the pretrained weights.\n root : str, default '~/.mxnet/models'\n Location for keeping the model parameters.\n \"\"\"\n channels = [[32], [64], [128, 128], [256, 256], [512, 512, 512, 512, 512, 1024]]\n first_stage_stride = True\n\n if width_scale != 1.0:\n channels = [[int(cij * width_scale) for cij in ci] for ci in channels]\n\n net = MobileNet(\n channels=channels,\n first_stage_stride=first_stage_stride,\n **kwargs)\n\n if pretrained:\n if (model_name is None) or (not model_name):\n raise ValueError(\"Parameter `model_name` should be properly initialized for loading pretrained model.\")\n from .model_store import get_model_file\n net.load_parameters(\n filename=get_model_file(\n model_name=model_name,\n local_model_store_dir_path=root),\n ctx=ctx)\n\n return net\n\n\ndef fdmobilenet_w1(**kwargs):\n \"\"\"\n FD-MobileNet 1.0x model from 'FD-MobileNet: Improved MobileNet with A Fast Downsampling Strategy,'\n https://arxiv.org/abs/1802.03750.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n ctx : Context, default CPU\n The context in which to load the pretrained weights.\n root : str, default '~/.mxnet/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_fdmobilenet(width_scale=1.0, model_name=\"fdmobilenet_w1\", **kwargs)\n\n\ndef fdmobilenet_w3d4(**kwargs):\n \"\"\"\n FD-MobileNet 0.75x model from 'FD-MobileNet: Improved MobileNet with A Fast Downsampling Strategy,'\n https://arxiv.org/abs/1802.03750.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n ctx : Context, default CPU\n The context in which to load the pretrained weights.\n root : str, default '~/.mxnet/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_fdmobilenet(width_scale=0.75, model_name=\"fdmobilenet_w3d4\", **kwargs)\n\n\ndef fdmobilenet_wd2(**kwargs):\n \"\"\"\n FD-MobileNet 0.5x model from 'FD-MobileNet: Improved MobileNet with A Fast Downsampling Strategy,'\n https://arxiv.org/abs/1802.03750.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n ctx : Context, default CPU\n The context in which to load the pretrained weights.\n root : str, default '~/.mxnet/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_fdmobilenet(width_scale=0.5, model_name=\"fdmobilenet_wd2\", **kwargs)\n\n\ndef fdmobilenet_wd4(**kwargs):\n \"\"\"\n FD-MobileNet 0.25x model from 'FD-MobileNet: Improved MobileNet with A Fast Downsampling Strategy,'\n https://arxiv.org/abs/1802.03750.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n ctx : Context, default CPU\n The context in which to load the pretrained weights.\n root : str, default '~/.mxnet/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_fdmobilenet(width_scale=0.25, model_name=\"fdmobilenet_wd4\", **kwargs)\n\n\ndef _test():\n import numpy as np\n import mxnet as mx\n\n pretrained = False\n\n models = [\n fdmobilenet_w1,\n fdmobilenet_w3d4,\n fdmobilenet_wd2,\n fdmobilenet_wd4,\n ]\n\n for model in models:\n\n net = model(pretrained=pretrained)\n\n ctx = mx.cpu()\n if not pretrained:\n net.initialize(ctx=ctx)\n\n net_params = net.collect_params()\n weight_count = 0\n for param in net_params.values():\n if (param.shape is None) or (not param._differentiable):\n continue\n weight_count += np.prod(param.shape)\n print(\"m={}, {}\".format(model.__name__, weight_count))\n assert (model != fdmobilenet_w1 or weight_count == 2901288)\n assert (model != fdmobilenet_w3d4 or weight_count == 1833304)\n assert (model != fdmobilenet_wd2 or weight_count == 993928)\n assert (model != fdmobilenet_wd4 or weight_count == 383160)\n\n x = mx.nd.zeros((1, 3, 224, 224), ctx=ctx)\n y = net(x)\n assert (y.shape == (1, 1000))\n\n\nif __name__ == \"__main__\":\n _test()\n",
"\"\"\"\r\n Script for training model on PyTorch.\r\n\"\"\"\r\n\r\nimport os\r\nimport time\r\nimport logging\r\nimport argparse\r\nimport random\r\nimport numpy as np\r\n\r\nimport torch.nn as nn\r\nimport torch.backends.cudnn as cudnn\r\nimport torch.utils.data\r\n\r\nfrom common.logger_utils import initialize_logging\r\nfrom common.train_log_param_saver import TrainLogParamSaver\r\nfrom pytorch.utils import prepare_pt_context, prepare_model, validate\r\nfrom pytorch.utils import report_accuracy, get_composite_metric, get_metric_name\r\n\r\nfrom pytorch.dataset_utils import get_dataset_metainfo\r\nfrom pytorch.dataset_utils import get_train_data_source, get_val_data_source\r\n\r\n\r\ndef add_train_cls_parser_arguments(parser):\r\n \"\"\"\r\n Create python script parameters (for training/classification specific subpart).\r\n\r\n Parameters:\r\n ----------\r\n parser : ArgumentParser\r\n ArgumentParser instance.\r\n \"\"\"\r\n parser.add_argument(\r\n \"--model\",\r\n type=str,\r\n required=True,\r\n help=\"type of model to use. see model_provider for options\")\r\n parser.add_argument(\r\n \"--use-pretrained\",\r\n action=\"store_true\",\r\n help=\"enable using pretrained model from github repo\")\r\n parser.add_argument(\r\n \"--resume\",\r\n type=str,\r\n default=\"\",\r\n help=\"resume from previously saved parameters if not None\")\r\n parser.add_argument(\r\n \"--resume-state\",\r\n type=str,\r\n default=\"\",\r\n help=\"resume from previously saved optimizer state if not None\")\r\n\r\n parser.add_argument(\r\n \"--num-gpus\",\r\n type=int,\r\n default=0,\r\n help=\"number of gpus to use\")\r\n parser.add_argument(\r\n \"-j\",\r\n \"--num-data-workers\",\r\n dest=\"num_workers\",\r\n default=4,\r\n type=int,\r\n help=\"number of preprocessing workers\")\r\n\r\n parser.add_argument(\r\n \"--batch-size\",\r\n type=int,\r\n default=512,\r\n help=\"training batch size per device (CPU/GPU)\")\r\n parser.add_argument(\r\n \"--batch-size-scale\",\r\n type=int,\r\n default=1,\r\n help=\"manual batch-size increasing factor\")\r\n parser.add_argument(\r\n \"--num-epochs\",\r\n type=int,\r\n default=120,\r\n help=\"number of training epochs\")\r\n parser.add_argument(\r\n \"--start-epoch\",\r\n type=int,\r\n default=1,\r\n help=\"starting epoch for resuming, default is 1 for new training\")\r\n parser.add_argument(\r\n \"--attempt\",\r\n type=int,\r\n default=1,\r\n help=\"current attempt number for training\")\r\n\r\n parser.add_argument(\r\n \"--optimizer-name\",\r\n type=str,\r\n default=\"nag\",\r\n help=\"optimizer name\")\r\n parser.add_argument(\r\n \"--lr\",\r\n type=float,\r\n default=0.1,\r\n help=\"learning rate\")\r\n parser.add_argument(\r\n \"--lr-mode\",\r\n type=str,\r\n default=\"cosine\",\r\n help=\"learning rate scheduler mode. options are step, poly and cosine\")\r\n parser.add_argument(\r\n \"--lr-decay\",\r\n type=float,\r\n default=0.1,\r\n help=\"decay rate of learning rate\")\r\n parser.add_argument(\r\n \"--lr-decay-period\",\r\n type=int,\r\n default=0,\r\n help=\"interval for periodic learning rate decays. default is 0 to disable\")\r\n parser.add_argument(\r\n \"--lr-decay-epoch\",\r\n type=str,\r\n default=\"40,60\",\r\n help=\"epoches at which learning rate decays\")\r\n parser.add_argument(\r\n \"--target-lr\",\r\n type=float,\r\n default=1e-8,\r\n help=\"ending learning rate\")\r\n parser.add_argument(\r\n \"--poly-power\",\r\n type=float,\r\n default=2,\r\n help=\"power value for poly LR scheduler\")\r\n parser.add_argument(\r\n \"--warmup-epochs\",\r\n type=int,\r\n default=0,\r\n help=\"number of warmup epochs\")\r\n parser.add_argument(\r\n \"--warmup-lr\",\r\n type=float,\r\n default=1e-8,\r\n help=\"starting warmup learning rate\")\r\n parser.add_argument(\r\n \"--warmup-mode\",\r\n type=str,\r\n default=\"linear\",\r\n help=\"learning rate scheduler warmup mode. options are linear, poly and constant\")\r\n parser.add_argument(\r\n \"--momentum\",\r\n type=float,\r\n default=0.9,\r\n help=\"momentum value for optimizer\")\r\n parser.add_argument(\r\n \"--wd\",\r\n type=float,\r\n default=0.0001,\r\n help=\"weight decay rate\")\r\n parser.add_argument(\r\n \"--gamma-wd-mult\",\r\n type=float,\r\n default=1.0,\r\n help=\"weight decay multiplier for batchnorm gamma\")\r\n parser.add_argument(\r\n \"--beta-wd-mult\",\r\n type=float,\r\n default=1.0,\r\n help=\"weight decay multiplier for batchnorm beta\")\r\n parser.add_argument(\r\n \"--bias-wd-mult\",\r\n type=float,\r\n default=1.0,\r\n help=\"weight decay multiplier for bias\")\r\n parser.add_argument(\r\n \"--grad-clip\",\r\n type=float,\r\n default=None,\r\n help=\"max_norm for gradient clipping\")\r\n parser.add_argument(\r\n \"--label-smoothing\",\r\n action=\"store_true\",\r\n help=\"use label smoothing\")\r\n\r\n parser.add_argument(\r\n \"--mixup\",\r\n action=\"store_true\",\r\n help=\"use mixup strategy\")\r\n parser.add_argument(\r\n \"--mixup-epoch-tail\",\r\n type=int,\r\n default=15,\r\n help=\"number of epochs without mixup at the end of training\")\r\n\r\n parser.add_argument(\r\n \"--log-interval\",\r\n type=int,\r\n default=50,\r\n help=\"number of batches to wait before logging\")\r\n parser.add_argument(\r\n \"--save-interval\",\r\n type=int,\r\n default=4,\r\n help=\"saving parameters epoch interval, best model will always be saved\")\r\n parser.add_argument(\r\n \"--save-dir\",\r\n type=str,\r\n default=\"\",\r\n help=\"directory of saved models and log-files\")\r\n parser.add_argument(\r\n \"--logging-file-name\",\r\n type=str,\r\n default=\"train.log\",\r\n help=\"filename of training log\")\r\n\r\n parser.add_argument(\r\n \"--seed\",\r\n type=int,\r\n default=-1,\r\n help=\"Random seed to be fixed\")\r\n parser.add_argument(\r\n \"--log-packages\",\r\n type=str,\r\n default=\"torch, torchvision\",\r\n help=\"list of python packages for logging\")\r\n parser.add_argument(\r\n \"--log-pip-packages\",\r\n type=str,\r\n default=\"\",\r\n help=\"list of pip packages for logging\")\r\n\r\n parser.add_argument(\r\n \"--tune-layers\",\r\n type=str,\r\n default=\"\",\r\n help=\"regexp for selecting layers for fine tuning\")\r\n\r\n\r\ndef parse_args():\r\n \"\"\"\r\n Parse python script parameters (common part).\r\n\r\n Returns:\r\n -------\r\n ArgumentParser\r\n Resulted args.\r\n \"\"\"\r\n parser = argparse.ArgumentParser(\r\n description=\"Train a model for image classification (PyTorch)\",\r\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\r\n parser.add_argument(\r\n \"--dataset\",\r\n type=str,\r\n default=\"ImageNet1K\",\r\n help=\"dataset name. options are ImageNet1K, CUB200_2011, CIFAR10, CIFAR100, SVHN\")\r\n parser.add_argument(\r\n \"--work-dir\",\r\n type=str,\r\n default=os.path.join(\"..\", \"imgclsmob_data\"),\r\n help=\"path to working directory only for dataset root path preset\")\r\n\r\n args, _ = parser.parse_known_args()\r\n dataset_metainfo = get_dataset_metainfo(dataset_name=args.dataset)\r\n dataset_metainfo.add_dataset_parser_arguments(\r\n parser=parser,\r\n work_dir_path=args.work_dir)\r\n\r\n add_train_cls_parser_arguments(parser)\r\n\r\n args = parser.parse_args()\r\n return args\r\n\r\n\r\ndef init_rand(seed):\r\n \"\"\"\r\n Initialize all random generators by seed.\r\n\r\n Parameters:\r\n ----------\r\n seed : int\r\n Seed value.\r\n\r\n Returns:\r\n -------\r\n int\r\n Generated seed value.\r\n \"\"\"\r\n if seed <= 0:\r\n seed = np.random.randint(10000)\r\n else:\r\n cudnn.deterministic = True\r\n logging.warning(\r\n \"You have chosen to seed training. This will turn on the CUDNN deterministic setting, which can slow down \"\r\n \"your training considerably! You may see unexpected behavior when restarting from checkpoints.\")\r\n random.seed(seed)\r\n np.random.seed(seed)\r\n torch.manual_seed(seed)\r\n return seed\r\n\r\n\r\ndef prepare_trainer(net,\r\n optimizer_name,\r\n wd,\r\n momentum,\r\n lr_mode,\r\n lr,\r\n lr_decay_period,\r\n lr_decay_epoch,\r\n lr_decay,\r\n num_epochs,\r\n state_file_path):\r\n \"\"\"\r\n Prepare trainer.\r\n\r\n Parameters:\r\n ----------\r\n net : Module\r\n Model.\r\n optimizer_name : str\r\n Name of optimizer.\r\n wd : float\r\n Weight decay rate.\r\n momentum : float\r\n Momentum value.\r\n lr_mode : str\r\n Learning rate scheduler mode.\r\n lr : float\r\n Learning rate.\r\n lr_decay_period : int\r\n Interval for periodic learning rate decays.\r\n lr_decay_epoch : str\r\n Epoches at which learning rate decays.\r\n lr_decay : float\r\n Decay rate of learning rate.\r\n num_epochs : int\r\n Number of training epochs.\r\n state_file_path : str\r\n Path for file with trainer state.\r\n\r\n Returns:\r\n -------\r\n Optimizer\r\n Optimizer.\r\n LRScheduler\r\n Learning rate scheduler.\r\n int\r\n Start epoch.\r\n \"\"\"\r\n optimizer_name = optimizer_name.lower()\r\n if (optimizer_name == \"sgd\") or (optimizer_name == \"nag\"):\r\n optimizer = torch.optim.SGD(\r\n params=net.parameters(),\r\n lr=lr,\r\n momentum=momentum,\r\n weight_decay=wd,\r\n nesterov=(optimizer_name == \"nag\"))\r\n else:\r\n raise ValueError(\"Usupported optimizer: {}\".format(optimizer_name))\r\n\r\n if state_file_path:\r\n checkpoint = torch.load(state_file_path)\r\n if type(checkpoint) == dict:\r\n optimizer.load_state_dict(checkpoint[\"optimizer\"])\r\n start_epoch = checkpoint[\"epoch\"]\r\n else:\r\n start_epoch = None\r\n else:\r\n start_epoch = None\r\n\r\n cudnn.benchmark = True\r\n\r\n lr_mode = lr_mode.lower()\r\n if lr_decay_period > 0:\r\n lr_decay_epoch = list(range(lr_decay_period, num_epochs, lr_decay_period))\r\n else:\r\n lr_decay_epoch = [int(i) for i in lr_decay_epoch.split(\",\")]\r\n if (lr_mode == \"step\") and (lr_decay_period != 0):\r\n lr_scheduler = torch.optim.lr_scheduler.StepLR(\r\n optimizer=optimizer,\r\n step_size=lr_decay_period,\r\n gamma=lr_decay,\r\n last_epoch=-1)\r\n elif (lr_mode == \"multistep\") or ((lr_mode == \"step\") and (lr_decay_period == 0)):\r\n lr_scheduler = torch.optim.lr_scheduler.MultiStepLR(\r\n optimizer=optimizer,\r\n milestones=lr_decay_epoch,\r\n gamma=lr_decay,\r\n last_epoch=-1)\r\n elif lr_mode == \"cosine\":\r\n for group in optimizer.param_groups:\r\n group.setdefault(\"initial_lr\", group[\"lr\"])\r\n lr_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(\r\n optimizer=optimizer,\r\n T_max=num_epochs,\r\n last_epoch=(num_epochs - 1))\r\n else:\r\n raise ValueError(\"Usupported lr_scheduler: {}\".format(lr_mode))\r\n\r\n return optimizer, lr_scheduler, start_epoch\r\n\r\n\r\ndef save_params(file_stem,\r\n state):\r\n \"\"\"\r\n Save current model/trainer parameters.\r\n\r\n Parameters:\r\n ----------\r\n file_stem : str\r\n File stem (with path).\r\n state : dict\r\n Whole state of model & trainer.\r\n trainer : Trainer\r\n Trainer.\r\n \"\"\"\r\n torch.save(\r\n obj=state[\"state_dict\"],\r\n f=(file_stem + \".pth\"))\r\n torch.save(\r\n obj=state,\r\n f=(file_stem + \".states\"))\r\n\r\n\r\ndef train_epoch(epoch,\r\n net,\r\n train_metric,\r\n train_data,\r\n use_cuda,\r\n L,\r\n optimizer,\r\n # lr_scheduler,\r\n batch_size,\r\n log_interval):\r\n \"\"\"\r\n Train model on particular epoch.\r\n\r\n Parameters:\r\n ----------\r\n epoch : int\r\n Epoch number.\r\n net : Module\r\n Model.\r\n train_metric : EvalMetric\r\n Metric object instance.\r\n train_data : DataLoader\r\n Data loader.\r\n use_cuda : bool\r\n Whether to use CUDA.\r\n L : Loss\r\n Loss function.\r\n optimizer : Optimizer\r\n Optimizer.\r\n batch_size : int\r\n Training batch size.\r\n log_interval : int\r\n Batch count period for logging.\r\n\r\n Returns:\r\n -------\r\n float\r\n Loss value.\r\n \"\"\"\r\n tic = time.time()\r\n net.train()\r\n train_metric.reset()\r\n train_loss = 0.0\r\n\r\n btic = time.time()\r\n for i, (data, target) in enumerate(train_data):\r\n if use_cuda:\r\n data = data.cuda(non_blocking=True)\r\n target = target.cuda(non_blocking=True)\r\n output = net(data)\r\n loss = L(output, target)\r\n optimizer.zero_grad()\r\n loss.backward()\r\n optimizer.step()\r\n\r\n train_loss += loss.item()\r\n\r\n train_metric.update(\r\n labels=target,\r\n preds=output)\r\n\r\n if log_interval and not (i + 1) % log_interval:\r\n speed = batch_size * log_interval / (time.time() - btic)\r\n btic = time.time()\r\n train_accuracy_msg = report_accuracy(metric=train_metric)\r\n logging.info(\"Epoch[{}] Batch [{}]\\tSpeed: {:.2f} samples/sec\\t{}\\tlr={:.5f}\".format(\r\n epoch + 1, i, speed, train_accuracy_msg, optimizer.param_groups[0][\"lr\"]))\r\n\r\n throughput = int(batch_size * (i + 1) / (time.time() - tic))\r\n logging.info(\"[Epoch {}] speed: {:.2f} samples/sec\\ttime cost: {:.2f} sec\".format(\r\n epoch + 1, throughput, time.time() - tic))\r\n\r\n train_loss /= (i + 1)\r\n train_accuracy_msg = report_accuracy(metric=train_metric)\r\n logging.info(\"[Epoch {}] training: {}\\tloss={:.4f}\".format(\r\n epoch + 1, train_accuracy_msg, train_loss))\r\n\r\n return train_loss\r\n\r\n\r\ndef train_net(batch_size,\r\n num_epochs,\r\n start_epoch1,\r\n train_data,\r\n val_data,\r\n net,\r\n optimizer,\r\n lr_scheduler,\r\n lp_saver,\r\n log_interval,\r\n num_classes,\r\n val_metric,\r\n train_metric,\r\n use_cuda):\r\n \"\"\"\r\n Main procedure for training model.\r\n\r\n Parameters:\r\n ----------\r\n batch_size : int\r\n Training batch size.\r\n num_epochs : int\r\n Number of training epochs.\r\n start_epoch1 : int\r\n Number of starting epoch (1-based).\r\n train_data : DataLoader\r\n Data loader (training subset).\r\n val_data : DataLoader\r\n Data loader (validation subset).\r\n net : Module\r\n Model.\r\n optimizer : Optimizer\r\n Optimizer.\r\n lr_scheduler : LRScheduler\r\n Learning rate scheduler.\r\n lp_saver : TrainLogParamSaver\r\n Model/trainer state saver.\r\n log_interval : int\r\n Batch count period for logging.\r\n num_classes : int\r\n Number of model classes.\r\n val_metric : EvalMetric\r\n Metric object instance (validation subset).\r\n train_metric : EvalMetric\r\n Metric object instance (training subset).\r\n use_cuda : bool\r\n Whether to use CUDA.\r\n \"\"\"\r\n assert (num_classes > 0)\r\n\r\n L = nn.CrossEntropyLoss()\r\n if use_cuda:\r\n L = L.cuda()\r\n\r\n assert (type(start_epoch1) == int)\r\n assert (start_epoch1 >= 1)\r\n if start_epoch1 > 1:\r\n logging.info(\"Start training from [Epoch {}]\".format(start_epoch1))\r\n validate(\r\n metric=val_metric,\r\n net=net,\r\n val_data=val_data,\r\n use_cuda=use_cuda)\r\n val_accuracy_msg = report_accuracy(metric=val_metric)\r\n logging.info(\"[Epoch {}] validation: {}\".format(start_epoch1 - 1, val_accuracy_msg))\r\n\r\n gtic = time.time()\r\n for epoch in range(start_epoch1 - 1, num_epochs):\r\n lr_scheduler.step()\r\n\r\n train_loss = train_epoch(\r\n epoch=epoch,\r\n net=net,\r\n train_metric=train_metric,\r\n train_data=train_data,\r\n use_cuda=use_cuda,\r\n L=L,\r\n optimizer=optimizer,\r\n # lr_scheduler,\r\n batch_size=batch_size,\r\n log_interval=log_interval)\r\n\r\n validate(\r\n metric=val_metric,\r\n net=net,\r\n val_data=val_data,\r\n use_cuda=use_cuda)\r\n val_accuracy_msg = report_accuracy(metric=val_metric)\r\n logging.info(\"[Epoch {}] validation: {}\".format(epoch + 1, val_accuracy_msg))\r\n\r\n if lp_saver is not None:\r\n state = {\r\n \"epoch\": epoch + 1,\r\n \"state_dict\": net.state_dict(),\r\n \"optimizer\": optimizer.state_dict(),\r\n }\r\n lp_saver_kwargs = {\"state\": state}\r\n val_acc_values = val_metric.get()[1]\r\n train_acc_values = train_metric.get()[1]\r\n val_acc_values = val_acc_values if type(val_acc_values) == list else [val_acc_values]\r\n train_acc_values = train_acc_values if type(train_acc_values) == list else [train_acc_values]\r\n lp_saver.epoch_test_end_callback(\r\n epoch1=(epoch + 1),\r\n params=(val_acc_values + train_acc_values + [train_loss, optimizer.param_groups[0][\"lr\"]]),\r\n **lp_saver_kwargs)\r\n\r\n logging.info(\"Total time cost: {:.2f} sec\".format(time.time() - gtic))\r\n if lp_saver is not None:\r\n opt_metric_name = get_metric_name(val_metric, lp_saver.acc_ind)\r\n logging.info(\"Best {}: {:.4f} at {} epoch\".format(\r\n opt_metric_name, lp_saver.best_eval_metric_value, lp_saver.best_eval_metric_epoch))\r\n\r\n\r\ndef main():\r\n \"\"\"\r\n Main body of script.\r\n \"\"\"\r\n args = parse_args()\r\n args.seed = init_rand(seed=args.seed)\r\n\r\n _, log_file_exist = initialize_logging(\r\n logging_dir_path=args.save_dir,\r\n logging_file_name=args.logging_file_name,\r\n script_args=args,\r\n log_packages=args.log_packages,\r\n log_pip_packages=args.log_pip_packages)\r\n\r\n use_cuda, batch_size = prepare_pt_context(\r\n num_gpus=args.num_gpus,\r\n batch_size=args.batch_size)\r\n\r\n net = prepare_model(\r\n model_name=args.model,\r\n use_pretrained=args.use_pretrained,\r\n pretrained_model_file_path=args.resume.strip(),\r\n use_cuda=use_cuda)\r\n real_net = net.module if hasattr(net, \"module\") else net\r\n assert (hasattr(real_net, \"num_classes\"))\r\n num_classes = real_net.num_classes\r\n\r\n ds_metainfo = get_dataset_metainfo(dataset_name=args.dataset)\r\n ds_metainfo.update(args=args)\r\n\r\n train_data = get_train_data_source(\r\n ds_metainfo=ds_metainfo,\r\n batch_size=batch_size,\r\n num_workers=args.num_workers)\r\n val_data = get_val_data_source(\r\n ds_metainfo=ds_metainfo,\r\n batch_size=batch_size,\r\n num_workers=args.num_workers)\r\n\r\n optimizer, lr_scheduler, start_epoch = prepare_trainer(\r\n net=net,\r\n optimizer_name=args.optimizer_name,\r\n wd=args.wd,\r\n momentum=args.momentum,\r\n lr_mode=args.lr_mode,\r\n lr=args.lr,\r\n lr_decay_period=args.lr_decay_period,\r\n lr_decay_epoch=args.lr_decay_epoch,\r\n lr_decay=args.lr_decay,\r\n num_epochs=args.num_epochs,\r\n state_file_path=args.resume_state)\r\n\r\n if args.save_dir and args.save_interval:\r\n param_names = ds_metainfo.val_metric_capts + ds_metainfo.train_metric_capts + [\"Train.Loss\", \"LR\"]\r\n lp_saver = TrainLogParamSaver(\r\n checkpoint_file_name_prefix=\"{}_{}\".format(ds_metainfo.short_label, args.model),\r\n last_checkpoint_file_name_suffix=\"last\",\r\n best_checkpoint_file_name_suffix=None,\r\n last_checkpoint_dir_path=args.save_dir,\r\n best_checkpoint_dir_path=None,\r\n last_checkpoint_file_count=2,\r\n best_checkpoint_file_count=2,\r\n checkpoint_file_save_callback=save_params,\r\n checkpoint_file_exts=(\".pth\", \".states\"),\r\n save_interval=args.save_interval,\r\n num_epochs=args.num_epochs,\r\n param_names=param_names,\r\n acc_ind=ds_metainfo.saver_acc_ind,\r\n # bigger=[True],\r\n # mask=None,\r\n score_log_file_path=os.path.join(args.save_dir, \"score.log\"),\r\n score_log_attempt_value=args.attempt,\r\n best_map_log_file_path=os.path.join(args.save_dir, \"best_map.log\"))\r\n else:\r\n lp_saver = None\r\n\r\n train_net(\r\n batch_size=batch_size,\r\n num_epochs=args.num_epochs,\r\n start_epoch1=args.start_epoch,\r\n train_data=train_data,\r\n val_data=val_data,\r\n net=net,\r\n optimizer=optimizer,\r\n lr_scheduler=lr_scheduler,\r\n lp_saver=lp_saver,\r\n log_interval=args.log_interval,\r\n num_classes=num_classes,\r\n val_metric=get_composite_metric(ds_metainfo.val_metric_names, ds_metainfo.val_metric_extra_kwargs),\r\n train_metric=get_composite_metric(ds_metainfo.train_metric_names, ds_metainfo.train_metric_extra_kwargs),\r\n use_cuda=use_cuda)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n",
"\"\"\"\n Script for training model on Keras.\n\"\"\"\n\nimport argparse\nimport time\nimport logging\nimport os\nimport numpy as np\nimport random\nimport keras\nfrom keras.models import load_model\nfrom keras.callbacks import ModelCheckpoint\nimport mxnet as mx\nfrom common.logger_utils import initialize_logging\nfrom keras_.utils import prepare_ke_context, prepare_model, get_data_rec, get_data_generator, backend_agnostic_compile\n\n\ndef parse_args():\n \"\"\"\n Parse python script parameters.\n\n Returns:\n -------\n ArgumentParser\n Resulted args.\n \"\"\"\n parser = argparse.ArgumentParser(\n description=\"Train a model for image classification (Keras)\",\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument(\n \"--rec-train\",\n type=str,\n default=\"../imgclsmob_data/imagenet_rec/train.rec\",\n help=\"the training data\")\n parser.add_argument(\n \"--rec-train-idx\",\n type=str,\n default=\"../imgclsmob_data/imagenet_rec/train.idx\",\n help='the index of training data')\n parser.add_argument(\n \"--rec-val\",\n type=str,\n default=\"../imgclsmob_data/imagenet_rec/val.rec\",\n help=\"the validation data\")\n parser.add_argument(\n \"--rec-val-idx\",\n type=str,\n default=\"../imgclsmob_data/imagenet_rec/val.idx\",\n help=\"the index of validation data\")\n\n parser.add_argument(\n \"--model\",\n type=str,\n required=True,\n help=\"type of model to use. see model_provider for options\")\n parser.add_argument(\n \"--use-pretrained\",\n action=\"store_true\",\n help=\"enable using pretrained model from github repo\")\n parser.add_argument(\n \"--dtype\",\n type=str,\n default=\"float32\",\n help=\"data type for training\")\n parser.add_argument(\n \"--resume\",\n type=str,\n default=\"\",\n help=\"resume from previously saved parameters if not None\")\n parser.add_argument(\n \"--resume-state\",\n type=str,\n default=\"\",\n help=\"resume from previously saved optimizer state if not None\")\n\n parser.add_argument(\n \"--input-size\",\n type=int,\n default=224,\n help=\"size of the input for model\")\n parser.add_argument(\n \"--resize-inv-factor\",\n type=float,\n default=0.875,\n help=\"inverted ratio for input image crop\")\n\n parser.add_argument(\n \"--num-gpus\",\n type=int,\n default=0,\n help=\"number of gpus to use\")\n parser.add_argument(\n \"-j\",\n \"--num-data-workers\",\n dest=\"num_workers\",\n default=4,\n type=int,\n help=\"number of preprocessing workers\")\n\n parser.add_argument(\n \"--batch-size\",\n type=int,\n default=512,\n help=\"training batch size per device (CPU/GPU)\")\n parser.add_argument(\n \"--num-epochs\",\n type=int,\n default=120,\n help=\"number of training epochs\")\n parser.add_argument(\n \"--start-epoch\",\n type=int,\n default=1,\n help=\"starting epoch for resuming, default is 1 for new training\")\n parser.add_argument(\n \"--attempt\",\n type=int,\n default=1,\n help=\"current number of training\")\n\n parser.add_argument(\n \"--optimizer-name\",\n type=str,\n default=\"nag\",\n help=\"optimizer name\")\n parser.add_argument(\n \"--lr\",\n type=float,\n default=0.1,\n help=\"learning rate\")\n parser.add_argument(\n \"--momentum\",\n type=float,\n default=0.9,\n help=\"momentum value for optimizer\")\n parser.add_argument(\n \"--wd\",\n type=float,\n default=0.0001,\n help=\"weight decay rate\")\n\n parser.add_argument(\n \"--log-interval\",\n type=int,\n default=50,\n help=\"number of batches to wait before logging\")\n parser.add_argument(\n \"--save-interval\",\n type=int,\n default=4,\n help=\"saving parameters epoch interval, best model will always be saved\")\n parser.add_argument(\n \"--save-dir\",\n type=str,\n default=\"\",\n help=\"directory of saved models and log-files\")\n parser.add_argument(\n \"--logging-file-name\",\n type=str,\n default=\"train.log\",\n help=\"filename of training log\")\n\n parser.add_argument(\n \"--seed\",\n type=int,\n default=-1,\n help=\"Random seed to be fixed\")\n parser.add_argument(\n \"--log-packages\",\n type=str,\n default=\"keras\",\n help=\"list of python packages for logging\")\n parser.add_argument(\n \"--log-pip-packages\",\n type=str,\n default=\"keras, keras-mxnet, keras-applications, keras-preprocessing\",\n help=\"list of pip packages for logging\")\n args = parser.parse_args()\n return args\n\n\ndef init_rand(seed):\n if seed <= 0:\n seed = np.random.randint(10000)\n random.seed(seed)\n np.random.seed(seed)\n mx.random.seed(seed)\n return seed\n\n\ndef prepare_trainer(net,\n optimizer_name,\n momentum,\n lr,\n num_gpus,\n state_file_path=None):\n\n optimizer_name = optimizer_name.lower()\n if (optimizer_name == \"sgd\") or (optimizer_name == \"nag\"):\n optimizer = keras.optimizers.SGD(\n lr=lr,\n momentum=momentum,\n nesterov=(optimizer_name == \"nag\"))\n else:\n raise ValueError(\"Usupported optimizer: {}\".format(optimizer_name))\n\n backend_agnostic_compile(\n model=net,\n loss=\"categorical_crossentropy\",\n optimizer=optimizer,\n metrics=[keras.metrics.categorical_accuracy, keras.metrics.top_k_categorical_accuracy],\n num_gpus=num_gpus)\n\n if (state_file_path is not None) and state_file_path and os.path.exists(state_file_path):\n net = load_model(filepath=state_file_path)\n return net\n\n\ndef train_net(net,\n train_gen,\n val_gen,\n train_num_examples,\n val_num_examples,\n num_epochs,\n checkpoint_filepath,\n start_epoch1):\n checkpointer = ModelCheckpoint(\n filepath=checkpoint_filepath,\n verbose=1,\n save_best_only=True)\n\n tic = time.time()\n\n net.fit_generator(\n generator=train_gen,\n samples_per_epoch=train_num_examples,\n epochs=num_epochs,\n verbose=True,\n callbacks=[checkpointer],\n validation_data=val_gen,\n validation_steps=val_num_examples,\n class_weight=None,\n max_queue_size=10,\n workers=1,\n use_multiprocessing=False,\n shuffle=True,\n initial_epoch=(start_epoch1 - 1))\n\n logging.info(\"Time cost: {:.4f} sec\".format(\n time.time() - tic))\n\n\ndef main():\n \"\"\"\n Main body of script.\n \"\"\"\n args = parse_args()\n args.seed = init_rand(seed=args.seed)\n\n _, log_file_exist = initialize_logging(\n logging_dir_path=args.save_dir,\n logging_file_name=args.logging_file_name,\n script_args=args,\n log_packages=args.log_packages,\n log_pip_packages=args.log_pip_packages)\n\n batch_size = prepare_ke_context(\n num_gpus=args.num_gpus,\n batch_size=args.batch_size)\n\n net = prepare_model(\n model_name=args.model,\n use_pretrained=args.use_pretrained,\n pretrained_model_file_path=args.resume.strip())\n num_classes = net.classes if hasattr(net, \"classes\") else 1000\n input_image_size = net.in_size if hasattr(net, \"in_size\") else (args.input_size, args.input_size)\n\n train_data, val_data = get_data_rec(\n rec_train=args.rec_train,\n rec_train_idx=args.rec_train_idx,\n rec_val=args.rec_val,\n rec_val_idx=args.rec_val_idx,\n batch_size=batch_size,\n num_workers=args.num_workers,\n input_image_size=input_image_size,\n resize_inv_factor=args.resize_inv_factor)\n train_gen = get_data_generator(\n data_iterator=train_data,\n num_classes=num_classes)\n val_gen = get_data_generator(\n data_iterator=val_data,\n num_classes=num_classes)\n\n net = prepare_trainer(\n net=net,\n optimizer_name=args.optimizer_name,\n momentum=args.momentum,\n lr=args.lr,\n num_gpus=args.num_gpus,\n state_file_path=args.resume_state)\n\n train_net(\n net=net,\n train_gen=train_gen,\n val_gen=val_gen,\n train_num_examples=1281167,\n val_num_examples=50048,\n num_epochs=args.num_epochs,\n checkpoint_filepath=os.path.join(args.save_dir, \"imagenet_{}.h5\".format(args.model)),\n start_epoch1=args.start_epoch)\n\n\nif __name__ == \"__main__\":\n main()\n",
"\"\"\"\n SE-ResNet for CIFAR/SVHN, implemented in Chainer.\n Original paper: 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.\n\"\"\"\n\n__all__ = ['CIFARSEResNet', 'seresnet20_cifar10', 'seresnet20_cifar100', 'seresnet20_svhn',\n 'seresnet56_cifar10', 'seresnet56_cifar100', 'seresnet56_svhn',\n 'seresnet110_cifar10', 'seresnet110_cifar100', 'seresnet110_svhn',\n 'seresnet164bn_cifar10', 'seresnet164bn_cifar100', 'seresnet164bn_svhn',\n 'seresnet272bn_cifar10', 'seresnet272bn_cifar100', 'seresnet272bn_svhn',\n 'seresnet542bn_cifar10', 'seresnet542bn_cifar100', 'seresnet542bn_svhn',\n 'seresnet1001_cifar10', 'seresnet1001_cifar100', 'seresnet1001_svhn',\n 'seresnet1202_cifar10', 'seresnet1202_cifar100', 'seresnet1202_svhn']\n\nimport os\nimport chainer.functions as F\nimport chainer.links as L\nfrom chainer import Chain\nfrom functools import partial\nfrom chainer.serializers import load_npz\nfrom .common import conv3x3_block, SimpleSequential\nfrom .seresnet import SEResUnit\n\n\nclass CIFARSEResNet(Chain):\n \"\"\"\n SE-ResNet model for CIFAR from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.\n\n Parameters:\n ----------\n channels : list of list of int\n Number of output channels for each unit.\n init_block_channels : int\n Number of output channels for the initial unit.\n bottleneck : bool\n Whether to use a bottleneck or simple block in units.\n in_channels : int, default 3\n Number of input channels.\n in_size : tuple of two ints, default (32, 32)\n Spatial size of the expected input image.\n classes : int, default 10\n Number of classification classes.\n \"\"\"\n def __init__(self,\n channels,\n init_block_channels,\n bottleneck,\n in_channels=3,\n in_size=(32, 32),\n classes=10):\n super(CIFARSEResNet, self).__init__()\n self.in_size = in_size\n self.classes = classes\n\n with self.init_scope():\n self.features = SimpleSequential()\n with self.features.init_scope():\n setattr(self.features, \"init_block\", conv3x3_block(\n in_channels=in_channels,\n out_channels=init_block_channels))\n in_channels = init_block_channels\n for i, channels_per_stage in enumerate(channels):\n stage = SimpleSequential()\n with stage.init_scope():\n for j, out_channels in enumerate(channels_per_stage):\n stride = 2 if (j == 0) and (i != 0) else 1\n setattr(stage, \"unit{}\".format(j + 1), SEResUnit(\n in_channels=in_channels,\n out_channels=out_channels,\n stride=stride,\n bottleneck=bottleneck,\n conv1_stride=False))\n in_channels = out_channels\n setattr(self.features, \"stage{}\".format(i + 1), stage)\n setattr(self.features, \"final_pool\", partial(\n F.average_pooling_2d,\n ksize=8,\n stride=1))\n\n self.output = SimpleSequential()\n with self.output.init_scope():\n setattr(self.output, \"flatten\", partial(\n F.reshape,\n shape=(-1, in_channels)))\n setattr(self.output, \"fc\", L.Linear(\n in_size=in_channels,\n out_size=classes))\n\n def __call__(self, x):\n x = self.features(x)\n x = self.output(x)\n return x\n\n\ndef get_seresnet_cifar(classes,\n blocks,\n bottleneck,\n model_name=None,\n pretrained=False,\n root=os.path.join(\"~\", \".chainer\", \"models\"),\n **kwargs):\n \"\"\"\n Create SE-ResNet model for CIFAR with specific parameters.\n\n Parameters:\n ----------\n classes : int\n Number of classification classes.\n blocks : int\n Number of blocks.\n bottleneck : bool\n Whether to use a bottleneck or simple block in units.\n model_name : str or None, default None\n Model name for loading pretrained model.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.chainer/models'\n Location for keeping the model parameters.\n \"\"\"\n assert (classes in [10, 100])\n\n if bottleneck:\n assert ((blocks - 2) % 9 == 0)\n layers = [(blocks - 2) // 9] * 3\n else:\n assert ((blocks - 2) % 6 == 0)\n layers = [(blocks - 2) // 6] * 3\n\n channels_per_layers = [16, 32, 64]\n init_block_channels = 16\n\n channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]\n\n if bottleneck:\n channels = [[cij * 4 for cij in ci] for ci in channels]\n\n net = CIFARSEResNet(\n channels=channels,\n init_block_channels=init_block_channels,\n bottleneck=bottleneck,\n classes=classes,\n **kwargs)\n\n if pretrained:\n if (model_name is None) or (not model_name):\n raise ValueError(\"Parameter `model_name` should be properly initialized for loading pretrained model.\")\n from .model_store import get_model_file\n load_npz(\n file=get_model_file(\n model_name=model_name,\n local_model_store_dir_path=root),\n obj=net)\n\n return net\n\n\ndef seresnet20_cifar10(classes=10, **kwargs):\n \"\"\"\n SE-ResNet-20 model for CIFAR-10 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.chainer/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_seresnet_cifar(classes=classes, blocks=20, bottleneck=False, model_name=\"seresnet20_cifar10\", **kwargs)\n\n\ndef seresnet20_cifar100(classes=100, **kwargs):\n \"\"\"\n SE-ResNet-20 model for CIFAR-100 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.\n\n Parameters:\n ----------\n classes : int, default 100\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.chainer/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_seresnet_cifar(classes=classes, blocks=20, bottleneck=False, model_name=\"seresnet20_cifar100\", **kwargs)\n\n\ndef seresnet20_svhn(classes=10, **kwargs):\n \"\"\"\n SE-ResNet-20 model for SVHN from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.chainer/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_seresnet_cifar(classes=classes, blocks=20, bottleneck=False, model_name=\"seresnet20_svhn\", **kwargs)\n\n\ndef seresnet56_cifar10(classes=10, **kwargs):\n \"\"\"\n SE-ResNet-56 model for CIFAR-10 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.chainer/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_seresnet_cifar(classes=classes, blocks=56, bottleneck=False, model_name=\"seresnet56_cifar10\", **kwargs)\n\n\ndef seresnet56_cifar100(classes=100, **kwargs):\n \"\"\"\n SE-ResNet-56 model for CIFAR-100 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.\n\n Parameters:\n ----------\n classes : int, default 100\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.chainer/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_seresnet_cifar(classes=classes, blocks=56, bottleneck=False, model_name=\"seresnet56_cifar100\", **kwargs)\n\n\ndef seresnet56_svhn(classes=10, **kwargs):\n \"\"\"\n SE-ResNet-56 model for SVHN from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.chainer/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_seresnet_cifar(classes=classes, blocks=56, bottleneck=False, model_name=\"seresnet56_svhn\", **kwargs)\n\n\ndef seresnet110_cifar10(classes=10, **kwargs):\n \"\"\"\n SE-ResNet-110 model for CIFAR-10 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.chainer/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_seresnet_cifar(classes=classes, blocks=110, bottleneck=False, model_name=\"seresnet110_cifar10\", **kwargs)\n\n\ndef seresnet110_cifar100(classes=100, **kwargs):\n \"\"\"\n SE-ResNet-110 model for CIFAR-100 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.\n\n Parameters:\n ----------\n classes : int, default 100\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.chainer/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_seresnet_cifar(classes=classes, blocks=110, bottleneck=False, model_name=\"seresnet110_cifar100\",\n **kwargs)\n\n\ndef seresnet110_svhn(classes=10, **kwargs):\n \"\"\"\n SE-ResNet-110 model for SVHN from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.chainer/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_seresnet_cifar(classes=classes, blocks=110, bottleneck=False, model_name=\"seresnet110_svhn\", **kwargs)\n\n\ndef seresnet164bn_cifar10(classes=10, **kwargs):\n \"\"\"\n SE-ResNet-164(BN) model for CIFAR-10 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.chainer/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_seresnet_cifar(classes=classes, blocks=164, bottleneck=True, model_name=\"seresnet164bn_cifar10\",\n **kwargs)\n\n\ndef seresnet164bn_cifar100(classes=100, **kwargs):\n \"\"\"\n SE-ResNet-164(BN) model for CIFAR-100 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.\n\n Parameters:\n ----------\n classes : int, default 100\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.chainer/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_seresnet_cifar(classes=classes, blocks=164, bottleneck=True, model_name=\"seresnet164bn_cifar100\",\n **kwargs)\n\n\ndef seresnet164bn_svhn(classes=10, **kwargs):\n \"\"\"\n SE-ResNet-164(BN) model for SVHN from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.chainer/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_seresnet_cifar(classes=classes, blocks=164, bottleneck=True, model_name=\"seresnet164bn_svhn\", **kwargs)\n\n\ndef seresnet272bn_cifar10(classes=10, **kwargs):\n \"\"\"\n SE-ResNet-272(BN) model for CIFAR-10 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.chainer/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_seresnet_cifar(classes=classes, blocks=272, bottleneck=True, model_name=\"seresnet272bn_cifar10\",\n **kwargs)\n\n\ndef seresnet272bn_cifar100(classes=100, **kwargs):\n \"\"\"\n SE-ResNet-272(BN) model for CIFAR-100 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.\n\n Parameters:\n ----------\n classes : int, default 100\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.chainer/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_seresnet_cifar(classes=classes, blocks=272, bottleneck=True, model_name=\"seresnet272bn_cifar100\",\n **kwargs)\n\n\ndef seresnet272bn_svhn(classes=10, **kwargs):\n \"\"\"\n SE-ResNet-272(BN) model for SVHN from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.chainer/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_seresnet_cifar(classes=classes, blocks=272, bottleneck=True, model_name=\"seresnet272bn_svhn\", **kwargs)\n\n\ndef seresnet542bn_cifar10(classes=10, **kwargs):\n \"\"\"\n SE-ResNet-542(BN) model for CIFAR-10 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.chainer/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_seresnet_cifar(classes=classes, blocks=542, bottleneck=True, model_name=\"seresnet542bn_cifar10\",\n **kwargs)\n\n\ndef seresnet542bn_cifar100(classes=100, **kwargs):\n \"\"\"\n SE-ResNet-542(BN) model for CIFAR-100 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.\n\n Parameters:\n ----------\n classes : int, default 100\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.chainer/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_seresnet_cifar(classes=classes, blocks=542, bottleneck=True, model_name=\"seresnet542bn_cifar100\",\n **kwargs)\n\n\ndef seresnet542bn_svhn(classes=10, **kwargs):\n \"\"\"\n SE-ResNet-542(BN) model for SVHN from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.chainer/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_seresnet_cifar(classes=classes, blocks=542, bottleneck=True, model_name=\"seresnet542bn_svhn\", **kwargs)\n\n\ndef seresnet1001_cifar10(classes=10, **kwargs):\n \"\"\"\n SE-ResNet-1001 model for CIFAR-10 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.chainer/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_seresnet_cifar(classes=classes, blocks=1001, bottleneck=True, model_name=\"seresnet1001_cifar10\",\n **kwargs)\n\n\ndef seresnet1001_cifar100(classes=100, **kwargs):\n \"\"\"\n SE-ResNet-1001 model for CIFAR-100 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.\n\n Parameters:\n ----------\n classes : int, default 100\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.chainer/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_seresnet_cifar(classes=classes, blocks=1001, bottleneck=True, model_name=\"seresnet1001_cifar100\",\n **kwargs)\n\n\ndef seresnet1001_svhn(classes=10, **kwargs):\n \"\"\"\n SE-ResNet-1001 model for SVHN from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.chainer/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_seresnet_cifar(classes=classes, blocks=1001, bottleneck=True, model_name=\"seresnet1001_svhn\", **kwargs)\n\n\ndef seresnet1202_cifar10(classes=10, **kwargs):\n \"\"\"\n SE-ResNet-1202 model for CIFAR-10 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.chainer/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_seresnet_cifar(classes=classes, blocks=1202, bottleneck=False, model_name=\"seresnet1202_cifar10\",\n **kwargs)\n\n\ndef seresnet1202_cifar100(classes=100, **kwargs):\n \"\"\"\n SE-ResNet-1202 model for CIFAR-100 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.\n\n Parameters:\n ----------\n classes : int, default 100\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.chainer/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_seresnet_cifar(classes=classes, blocks=1202, bottleneck=False, model_name=\"seresnet1202_cifar100\",\n **kwargs)\n\n\ndef seresnet1202_svhn(classes=10, **kwargs):\n \"\"\"\n SE-ResNet-1202 model for SVHN from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.chainer/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_seresnet_cifar(classes=classes, blocks=1202, bottleneck=False, model_name=\"seresnet1202_svhn\", **kwargs)\n\n\ndef _test():\n import numpy as np\n import chainer\n\n chainer.global_config.train = False\n\n pretrained = False\n\n models = [\n (seresnet20_cifar10, 10),\n (seresnet20_cifar100, 100),\n (seresnet20_svhn, 10),\n (seresnet56_cifar10, 10),\n (seresnet56_cifar100, 100),\n (seresnet56_svhn, 10),\n (seresnet110_cifar10, 10),\n (seresnet110_cifar100, 100),\n (seresnet110_svhn, 10),\n (seresnet164bn_cifar10, 10),\n (seresnet164bn_cifar100, 100),\n (seresnet164bn_svhn, 10),\n (seresnet272bn_cifar10, 10),\n (seresnet272bn_cifar100, 100),\n (seresnet272bn_svhn, 10),\n (seresnet542bn_cifar10, 10),\n (seresnet542bn_cifar100, 100),\n (seresnet542bn_svhn, 10),\n (seresnet1001_cifar10, 10),\n (seresnet1001_cifar100, 100),\n (seresnet1001_svhn, 10),\n (seresnet1202_cifar10, 10),\n (seresnet1202_cifar100, 100),\n (seresnet1202_svhn, 10),\n ]\n\n for model, classes in models:\n\n net = model(pretrained=pretrained)\n weight_count = net.count_params()\n print(\"m={}, {}\".format(model.__name__, weight_count))\n assert (model != seresnet20_cifar10 or weight_count == 274847)\n assert (model != seresnet20_cifar100 or weight_count == 280697)\n assert (model != seresnet20_svhn or weight_count == 274847)\n assert (model != seresnet56_cifar10 or weight_count == 862889)\n assert (model != seresnet56_cifar100 or weight_count == 868739)\n assert (model != seresnet56_svhn or weight_count == 862889)\n assert (model != seresnet110_cifar10 or weight_count == 1744952)\n assert (model != seresnet110_cifar100 or weight_count == 1750802)\n assert (model != seresnet110_svhn or weight_count == 1744952)\n assert (model != seresnet164bn_cifar10 or weight_count == 1906258)\n assert (model != seresnet164bn_cifar100 or weight_count == 1929388)\n assert (model != seresnet164bn_svhn or weight_count == 1906258)\n assert (model != seresnet272bn_cifar10 or weight_count == 3153826)\n assert (model != seresnet272bn_cifar100 or weight_count == 3176956)\n assert (model != seresnet272bn_svhn or weight_count == 3153826)\n assert (model != seresnet542bn_cifar10 or weight_count == 6272746)\n assert (model != seresnet542bn_cifar100 or weight_count == 6295876)\n assert (model != seresnet542bn_svhn or weight_count == 6272746)\n assert (model != seresnet1001_cifar10 or weight_count == 11574910)\n assert (model != seresnet1001_cifar100 or weight_count == 11598040)\n assert (model != seresnet1001_svhn or weight_count == 11574910)\n assert (model != seresnet1202_cifar10 or weight_count == 19582226)\n assert (model != seresnet1202_cifar100 or weight_count == 19588076)\n assert (model != seresnet1202_svhn or weight_count == 19582226)\n\n x = np.zeros((1, 3, 32, 32), np.float32)\n y = net(x)\n assert (y.shape == (1, classes))\n\n\nif __name__ == \"__main__\":\n _test()\n",
"\"\"\"\n InceptionResNetV1 for ImageNet-1K, implemented in TensorFlow.\n Original paper: 'Inception-v4, Inception-ResNet and the Impact of Residual Connections on Learning,'\n https://arxiv.org/abs/1602.07261.\n\"\"\"\n\n__all__ = ['InceptionResNetV1', 'inceptionresnetv1', 'InceptionAUnit', 'InceptionBUnit', 'InceptionCUnit',\n 'ReductionAUnit', 'ReductionBUnit']\n\nimport os\nimport tensorflow as tf\nimport tensorflow.keras.layers as nn\nfrom .common import MaxPool2d, BatchNorm, conv1x1, conv1x1_block, conv3x3_block, Concurrent, flatten,\\\n is_channels_first, SimpleSequential\nfrom .inceptionv3 import MaxPoolBranch, Conv1x1Branch, ConvSeqBranch\n\n\nclass InceptionAUnit(nn.Layer):\n \"\"\"\n InceptionResNetV1 type Inception-A unit.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels_list : list of int\n List for numbers of output channels.\n bn_eps : float\n Small float added to variance in Batch norm.\n data_format : str, default 'channels_last'\n The ordering of the dimensions in tensors.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels_list,\n bn_eps,\n data_format=\"channels_last\",\n **kwargs):\n super(InceptionAUnit, self).__init__(**kwargs)\n self.scale = 0.17\n\n self.branches = Concurrent(\n data_format=data_format,\n name=\"branches\")\n self.branches.children.append(Conv1x1Branch(\n in_channels=in_channels,\n out_channels=out_channels_list[0],\n bn_eps=bn_eps,\n data_format=data_format,\n name=\"branch1\"))\n self.branches.children.append(ConvSeqBranch(\n in_channels=in_channels,\n out_channels_list=out_channels_list[1:3],\n kernel_size_list=(1, 3),\n strides_list=(1, 1),\n padding_list=(0, 1),\n bn_eps=bn_eps,\n data_format=data_format,\n name=\"branch2\"))\n self.branches.children.append(ConvSeqBranch(\n in_channels=in_channels,\n out_channels_list=out_channels_list[3:6],\n kernel_size_list=(1, 3, 3),\n strides_list=(1, 1, 1),\n padding_list=(0, 1, 1),\n bn_eps=bn_eps,\n data_format=data_format,\n name=\"branch3\"))\n conv_in_channels = out_channels_list[0] + out_channels_list[2] + out_channels_list[5]\n self.conv = conv1x1(\n in_channels=conv_in_channels,\n out_channels=in_channels,\n use_bias=True,\n data_format=data_format,\n name=\"conv\")\n self.activ = nn.ReLU()\n\n def call(self, x, training=None):\n identity = x\n x = self.branches(x, training=training)\n x = self.conv(x, training=training)\n x = self.scale * x + identity\n x = self.activ(x)\n return x\n\n\nclass InceptionBUnit(nn.Layer):\n \"\"\"\n InceptionResNetV1 type Inception-B unit.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels_list : list of int\n List for numbers of output channels.\n bn_eps : float\n Small float added to variance in Batch norm.\n data_format : str, default 'channels_last'\n The ordering of the dimensions in tensors.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels_list,\n bn_eps,\n data_format=\"channels_last\",\n **kwargs):\n super(InceptionBUnit, self).__init__(**kwargs)\n self.scale = 0.10\n\n self.branches = Concurrent(\n data_format=data_format,\n name=\"branches\")\n self.branches.children.append(Conv1x1Branch(\n in_channels=in_channels,\n out_channels=out_channels_list[0],\n bn_eps=bn_eps,\n data_format=data_format,\n name=\"branch1\"))\n self.branches.children.append(ConvSeqBranch(\n in_channels=in_channels,\n out_channels_list=out_channels_list[1:4],\n kernel_size_list=(1, (1, 7), (7, 1)),\n strides_list=(1, 1, 1),\n padding_list=(0, (0, 3), (3, 0)),\n bn_eps=bn_eps,\n data_format=data_format,\n name=\"branch2\"))\n conv_in_channels = out_channels_list[0] + out_channels_list[3]\n self.conv = conv1x1(\n in_channels=conv_in_channels,\n out_channels=in_channels,\n use_bias=True,\n data_format=data_format,\n name=\"conv\")\n self.activ = nn.ReLU()\n\n def call(self, x, training=None):\n identity = x\n x = self.branches(x, training=training)\n x = self.conv(x, training=training)\n x = self.scale * x + identity\n x = self.activ(x)\n return x\n\n\nclass InceptionCUnit(nn.Layer):\n \"\"\"\n InceptionResNetV1 type Inception-C unit.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels_list : list of int\n List for numbers of output channels.\n bn_eps : float\n Small float added to variance in Batch norm.\n scale : float, default 1.0\n Scale value for residual branch.\n activate : bool, default True\n Whether activate the convolution block.\n data_format : str, default 'channels_last'\n The ordering of the dimensions in tensors.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels_list,\n bn_eps,\n scale=0.2,\n activate=True,\n data_format=\"channels_last\",\n **kwargs):\n super(InceptionCUnit, self).__init__(**kwargs)\n self.activate = activate\n self.scale = scale\n\n self.branches = Concurrent(\n data_format=data_format,\n name=\"branches\")\n self.branches.children.append(Conv1x1Branch(\n in_channels=in_channels,\n out_channels=out_channels_list[0],\n bn_eps=bn_eps,\n data_format=data_format,\n name=\"branch1\"))\n self.branches.children.append(ConvSeqBranch(\n in_channels=in_channels,\n out_channels_list=out_channels_list[1:4],\n kernel_size_list=(1, (1, 3), (3, 1)),\n strides_list=(1, 1, 1),\n padding_list=(0, (0, 1), (1, 0)),\n bn_eps=bn_eps,\n data_format=data_format,\n name=\"branch2\"))\n conv_in_channels = out_channels_list[0] + out_channels_list[3]\n self.conv = conv1x1(\n in_channels=conv_in_channels,\n out_channels=in_channels,\n use_bias=True,\n data_format=data_format,\n name=\"conv\")\n if self.activate:\n self.activ = nn.ReLU()\n\n def call(self, x, training=None):\n identity = x\n x = self.branches(x, training=training)\n x = self.conv(x, training=training)\n x = self.scale * x + identity\n if self.activate:\n x = self.activ(x)\n return x\n\n\nclass ReductionAUnit(nn.Layer):\n \"\"\"\n InceptionResNetV1 type Reduction-A unit.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels_list : list of int\n List for numbers of output channels.\n bn_eps : float\n Small float added to variance in Batch norm.\n data_format : str, default 'channels_last'\n The ordering of the dimensions in tensors.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels_list,\n bn_eps,\n data_format=\"channels_last\",\n **kwargs):\n super(ReductionAUnit, self).__init__(**kwargs)\n self.branches = Concurrent(\n data_format=data_format,\n name=\"branches\")\n self.branches.children.append(ConvSeqBranch(\n in_channels=in_channels,\n out_channels_list=out_channels_list[0:1],\n kernel_size_list=(3,),\n strides_list=(2,),\n padding_list=(0,),\n bn_eps=bn_eps,\n data_format=data_format,\n name=\"branch1\"))\n self.branches.children.append(ConvSeqBranch(\n in_channels=in_channels,\n out_channels_list=out_channels_list[1:4],\n kernel_size_list=(1, 3, 3),\n strides_list=(1, 1, 2),\n padding_list=(0, 1, 0),\n bn_eps=bn_eps,\n data_format=data_format,\n name=\"branch2\"))\n self.branches.children.append(MaxPoolBranch(\n data_format=data_format,\n name=\"branch3\"))\n\n def call(self, x, training=None):\n x = self.branches(x, training=training)\n return x\n\n\nclass ReductionBUnit(nn.Layer):\n \"\"\"\n InceptionResNetV1 type Reduction-B unit.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels_list : list of int\n List for numbers of output channels.\n bn_eps : float\n Small float added to variance in Batch norm.\n data_format : str, default 'channels_last'\n The ordering of the dimensions in tensors.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels_list,\n bn_eps,\n data_format=\"channels_last\",\n **kwargs):\n super(ReductionBUnit, self).__init__(**kwargs)\n self.branches = Concurrent(\n data_format=data_format,\n name=\"branches\")\n self.branches.children.append(ConvSeqBranch(\n in_channels=in_channels,\n out_channels_list=out_channels_list[0:2],\n kernel_size_list=(1, 3),\n strides_list=(1, 2),\n padding_list=(0, 0),\n bn_eps=bn_eps,\n data_format=data_format,\n name=\"branch1\"))\n self.branches.children.append(ConvSeqBranch(\n in_channels=in_channels,\n out_channels_list=out_channels_list[2:4],\n kernel_size_list=(1, 3),\n strides_list=(1, 2),\n padding_list=(0, 0),\n bn_eps=bn_eps,\n data_format=data_format,\n name=\"branch2\"))\n self.branches.children.append(ConvSeqBranch(\n in_channels=in_channels,\n out_channels_list=out_channels_list[4:7],\n kernel_size_list=(1, 3, 3),\n strides_list=(1, 1, 2),\n padding_list=(0, 1, 0),\n bn_eps=bn_eps,\n data_format=data_format,\n name=\"branch3\"))\n self.branches.children.append(MaxPoolBranch(\n data_format=data_format,\n name=\"branch4\"))\n\n def call(self, x, training=None):\n x = self.branches(x, training=training)\n return x\n\n\nclass InceptInitBlock(nn.Layer):\n \"\"\"\n InceptionResNetV1 specific initial block.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n bn_eps : float\n Small float added to variance in Batch norm.\n data_format : str, default 'channels_last'\n The ordering of the dimensions in tensors.\n \"\"\"\n def __init__(self,\n bn_eps,\n in_channels,\n data_format=\"channels_last\",\n **kwargs):\n super(InceptInitBlock, self).__init__(**kwargs)\n self.conv1 = conv3x3_block(\n in_channels=in_channels,\n out_channels=32,\n strides=2,\n padding=0,\n bn_eps=bn_eps,\n data_format=data_format,\n name=\"conv1\")\n self.conv2 = conv3x3_block(\n in_channels=32,\n out_channels=32,\n strides=1,\n padding=0,\n bn_eps=bn_eps,\n data_format=data_format,\n name=\"conv2\")\n self.conv3 = conv3x3_block(\n in_channels=32,\n out_channels=64,\n strides=1,\n padding=1,\n bn_eps=bn_eps,\n data_format=data_format,\n name=\"conv3\")\n self.pool = MaxPool2d(\n pool_size=3,\n strides=2,\n padding=0,\n data_format=data_format,\n name=\"pool\")\n self.conv4 = conv1x1_block(\n in_channels=64,\n out_channels=80,\n strides=1,\n padding=0,\n bn_eps=bn_eps,\n data_format=data_format,\n name=\"conv4\")\n self.conv5 = conv3x3_block(\n in_channels=80,\n out_channels=192,\n strides=1,\n padding=0,\n bn_eps=bn_eps,\n data_format=data_format,\n name=\"conv5\")\n self.conv6 = conv3x3_block(\n in_channels=192,\n out_channels=256,\n strides=2,\n padding=0,\n bn_eps=bn_eps,\n data_format=data_format,\n name=\"conv6\")\n\n def call(self, x, training=None):\n x = self.conv1(x, training=training)\n x = self.conv2(x, training=training)\n x = self.conv3(x, training=training)\n x = self.pool(x)\n x = self.conv4(x, training=training)\n x = self.conv5(x, training=training)\n x = self.conv6(x, training=training)\n return x\n\n\nclass InceptHead(nn.Layer):\n \"\"\"\n InceptionResNetV1 specific classification block.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n bn_eps : float\n Small float added to variance in Batch norm.\n dropout_rate : float\n Fraction of the input units to drop. Must be a number between 0 and 1.\n classes : int\n Number of classification classes.\n \"\"\"\n def __init__(self,\n in_channels,\n bn_eps,\n dropout_rate,\n classes,\n data_format=\"channels_last\",\n **kwargs):\n super(InceptHead, self).__init__(**kwargs)\n self.data_format = data_format\n self.use_dropout = (dropout_rate != 0.0)\n\n if dropout_rate > 0.0:\n self.dropout = nn.Dropout(\n rate=dropout_rate,\n name=\"dropout\")\n self.fc1 = nn.Dense(\n units=512,\n input_dim=in_channels,\n use_bias=False,\n name=\"fc1\")\n self.bn = BatchNorm(\n epsilon=bn_eps,\n data_format=data_format,\n name=\"bn\")\n self.fc2 = nn.Dense(\n units=classes,\n input_dim=512,\n name=\"fc2\")\n\n def call(self, x, training=None):\n x = flatten(x, self.data_format)\n if self.use_dropout:\n x = self.dropout(x, training=training)\n x = self.fc1(x)\n x = self.bn(x, training=training)\n x = self.fc2(x)\n return x\n\n\nclass InceptionResNetV1(tf.keras.Model):\n \"\"\"\n InceptionResNetV1 model from 'Inception-v4, Inception-ResNet and the Impact of Residual Connections on Learning,'\n https://arxiv.org/abs/1602.07261.\n\n Parameters:\n ----------\n dropout_rate : float, default 0.0\n Fraction of the input units to drop. Must be a number between 0 and 1.\n bn_eps : float, default 1e-5\n Small float added to variance in Batch norm.\n in_channels : int, default 3\n Number of input channels.\n in_size : tuple of two ints, default (299, 299)\n Spatial size of the expected input image.\n classes : int, default 1000\n Number of classification classes.\n data_format : str, default 'channels_last'\n The ordering of the dimensions in tensors.\n \"\"\"\n def __init__(self,\n dropout_rate=0.0,\n bn_eps=1e-5,\n in_channels=3,\n in_size=(299, 299),\n classes=1000,\n data_format=\"channels_last\",\n **kwargs):\n super(InceptionResNetV1, self).__init__(**kwargs)\n self.in_size = in_size\n self.classes = classes\n self.data_format = data_format\n layers = [5, 11, 7]\n in_channels_list = [256, 896, 1792]\n normal_out_channels_list = [[32, 32, 32, 32, 32, 32], [128, 128, 128, 128], [192, 192, 192, 192]]\n reduction_out_channels_list = [[384, 192, 192, 256], [256, 384, 256, 256, 256, 256, 256]]\n\n normal_units = [InceptionAUnit, InceptionBUnit, InceptionCUnit]\n reduction_units = [ReductionAUnit, ReductionBUnit]\n\n self.features = SimpleSequential(name=\"features\")\n self.features.add(InceptInitBlock(\n in_channels=in_channels,\n bn_eps=bn_eps,\n data_format=data_format,\n name=\"init_block\"))\n in_channels = in_channels_list[0]\n for i, layers_per_stage in enumerate(layers):\n stage = SimpleSequential(name=\"stage{}\".format(i + 1))\n for j in range(layers_per_stage):\n if (j == 0) and (i != 0):\n unit = reduction_units[i - 1]\n out_channels_list_per_stage = reduction_out_channels_list[i - 1]\n else:\n unit = normal_units[i]\n out_channels_list_per_stage = normal_out_channels_list[i]\n if (i == len(layers) - 1) and (j == layers_per_stage - 1):\n unit_kwargs = {\"scale\": 1.0, \"activate\": False}\n else:\n unit_kwargs = {}\n stage.add(unit(\n in_channels=in_channels,\n out_channels_list=out_channels_list_per_stage,\n bn_eps=bn_eps,\n data_format=data_format,\n name=\"unit{}\".format(j + 1),\n **unit_kwargs))\n if (j == 0) and (i != 0):\n in_channels = in_channels_list[i]\n self.features.add(stage)\n self.features.add(nn.AveragePooling2D(\n pool_size=8,\n strides=1,\n data_format=data_format,\n name=\"final_pool\"))\n\n self.output1 = InceptHead(\n in_channels=in_channels,\n bn_eps=bn_eps,\n dropout_rate=dropout_rate,\n classes=classes,\n name=\"output1\")\n\n def call(self, x, training=None):\n x = self.features(x, training=training)\n x = self.output1(x, training=training)\n return x\n\n\ndef get_inceptionresnetv1(model_name=None,\n pretrained=False,\n root=os.path.join(\"~\", \".tensorflow\", \"models\"),\n **kwargs):\n \"\"\"\n Create InceptionResNetV1 model with specific parameters.\n\n Parameters:\n ----------\n model_name : str or None, default None\n Model name for loading pretrained model.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n net = InceptionResNetV1(**kwargs)\n\n if pretrained:\n if (model_name is None) or (not model_name):\n raise ValueError(\"Parameter `model_name` should be properly initialized for loading pretrained model.\")\n from .model_store import get_model_file\n in_channels = kwargs[\"in_channels\"] if (\"in_channels\" in kwargs) else 3\n input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == \"channels_first\" else\\\n (1,) + net.in_size + (in_channels,)\n net.build(input_shape=input_shape)\n net.load_weights(\n filepath=get_model_file(\n model_name=model_name,\n local_model_store_dir_path=root))\n\n return net\n\n\ndef inceptionresnetv1(**kwargs):\n \"\"\"\n InceptionResNetV1 model from 'Inception-v4, Inception-ResNet and the Impact of Residual Connections on Learning,'\n https://arxiv.org/abs/1602.07261.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_inceptionresnetv1(model_name=\"inceptionresnetv1\", bn_eps=1e-3, **kwargs)\n\n\ndef _test():\n import numpy as np\n import tensorflow.keras.backend as K\n\n data_format = \"channels_last\"\n pretrained = False\n\n models = [\n inceptionresnetv1,\n ]\n\n for model in models:\n\n net = model(pretrained=pretrained, data_format=data_format)\n\n batch = 14\n x = tf.random.normal((batch, 3, 299, 299) if is_channels_first(data_format) else (batch, 299, 299, 3))\n y = net(x)\n assert (tuple(y.shape.as_list()) == (batch, 1000))\n\n weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights])\n print(\"m={}, {}\".format(model.__name__, weight_count))\n assert (model != inceptionresnetv1 or weight_count == 23995624)\n\n\nif __name__ == \"__main__\":\n _test()\n",
"\"\"\"\nEvaluation Metrics for Object Detection.\n\"\"\"\n\nimport warnings\nimport numpy as np\nimport mxnet as mx\n\n__all__ = ['CocoDetMApMetric']\n\n\nclass CocoDetMApMetric(mx.metric.EvalMetric):\n \"\"\"\n Detection metric for COCO bbox task.\n\n Parameters:\n ----------\n img_height : int\n Processed image height.\n coco_annotations_file_path : str\n COCO anotation file path.\n contiguous_id_to_json : list of int\n Processed IDs.\n validation_ids : bool, default False\n Whether to use temporary file for estimation.\n use_file : bool, default False\n Whether to use temporary file for estimation.\n score_thresh : float, default 0.05\n Detection results with confident scores smaller than `score_thresh` will be discarded before saving to results.\n data_shape : tuple of int, default is None\n If `data_shape` is provided as (height, width), we will rescale bounding boxes when saving the predictions.\n This is helpful when SSD/YOLO box predictions cannot be rescaled conveniently. Note that the data_shape must be\n fixed for all validation images.\n post_affine : a callable function with input signature (orig_w, orig_h, out_w, out_h)\n If not None, the bounding boxes will be affine transformed rather than simply scaled.\n name : str, default 'mAP'\n Name of this metric instance for display.\n \"\"\"\n def __init__(self,\n img_height,\n coco_annotations_file_path,\n contiguous_id_to_json,\n validation_ids=None,\n use_file=False,\n score_thresh=0.05,\n data_shape=None,\n post_affine=None,\n name=\"mAP\"):\n super(CocoDetMApMetric, self).__init__(name=name)\n self.img_height = img_height\n self.coco_annotations_file_path = coco_annotations_file_path\n self.contiguous_id_to_json = contiguous_id_to_json\n self.validation_ids = validation_ids\n self.use_file = use_file\n self.score_thresh = score_thresh\n\n self.current_idx = 0\n self.coco_result = []\n\n if isinstance(data_shape, (tuple, list)):\n assert len(data_shape) == 2, \"Data shape must be (height, width)\"\n elif not data_shape:\n data_shape = None\n else:\n raise ValueError(\"data_shape must be None or tuple of int as (height, width)\")\n self._data_shape = data_shape\n\n if post_affine is not None:\n assert self._data_shape is not None, \"Using post affine transform requires data_shape\"\n self._post_affine = post_affine\n else:\n self._post_affine = None\n\n from pycocotools.coco import COCO\n self.gt = COCO(self.coco_annotations_file_path)\n self._img_ids = sorted(self.gt.getImgIds())\n\n def reset(self):\n self.current_idx = 0\n self.coco_result = []\n\n def get(self):\n \"\"\"\n Get evaluation metrics.\n \"\"\"\n if self.current_idx != len(self._img_ids):\n warnings.warn(\"Recorded {} out of {} validation images, incomplete results\".format(\n self.current_idx, len(self._img_ids)))\n\n from pycocotools.coco import COCO\n gt = COCO(self.coco_annotations_file_path)\n\n import tempfile\n import json\n with tempfile.NamedTemporaryFile(mode=\"w\", suffix=\".json\") as f:\n json.dump(self.coco_result, f)\n f.flush()\n pred = gt.loadRes(f.name)\n\n from pycocotools.cocoeval import COCOeval\n coco_eval = COCOeval(gt, pred, \"bbox\")\n if self.validation_ids is not None:\n coco_eval.params.imgIds = self.validation_ids\n coco_eval.evaluate()\n coco_eval.accumulate()\n coco_eval.summarize()\n\n return self.name, tuple(coco_eval.stats[:3])\n\n def update2(self,\n pred_bboxes,\n pred_labels,\n pred_scores):\n \"\"\"\n Update internal buffer with latest predictions. Note that the statistics are not available until you call\n self.get() to return the metrics.\n\n Parameters:\n ----------\n pred_bboxes : mxnet.NDArray or numpy.ndarray\n Prediction bounding boxes with shape `B, N, 4`.\n Where B is the size of mini-batch, N is the number of bboxes.\n pred_labels : mxnet.NDArray or numpy.ndarray\n Prediction bounding boxes labels with shape `B, N`.\n pred_scores : mxnet.NDArray or numpy.ndarray\n Prediction bounding boxes scores with shape `B, N`.\n \"\"\"\n def as_numpy(a):\n \"\"\"\n Convert a (list of) mx.NDArray into numpy.ndarray\n \"\"\"\n if isinstance(a, (list, tuple)):\n out = [x.asnumpy() if isinstance(x, mx.nd.NDArray) else x for x in a]\n return np.concatenate(out, axis=0)\n elif isinstance(a, mx.nd.NDArray):\n a = a.asnumpy()\n return a\n\n for pred_bbox, pred_label, pred_score in zip(*[as_numpy(x) for x in [pred_bboxes, pred_labels, pred_scores]]):\n valid_pred = np.where(pred_label.flat >= 0)[0]\n pred_bbox = pred_bbox[valid_pred, :].astype(np.float)\n pred_label = pred_label.flat[valid_pred].astype(int)\n pred_score = pred_score.flat[valid_pred].astype(np.float)\n\n imgid = self._img_ids[self.current_idx]\n self.current_idx += 1\n affine_mat = None\n if self._data_shape is not None:\n entry = self.gt.loadImgs(imgid)[0]\n orig_height = entry[\"height\"]\n orig_width = entry[\"width\"]\n height_scale = float(orig_height) / self._data_shape[0]\n width_scale = float(orig_width) / self._data_shape[1]\n if self._post_affine is not None:\n affine_mat = self._post_affine(orig_width, orig_height, self._data_shape[1], self._data_shape[0])\n else:\n height_scale, width_scale = (1.0, 1.0)\n # for each bbox detection in each image\n for bbox, label, score in zip(pred_bbox, pred_label, pred_score):\n if label not in self.contiguous_id_to_json:\n # ignore non-exist class\n continue\n if score < self.score_thresh:\n continue\n category_id = self.contiguous_id_to_json[label]\n # rescale bboxes/affine transform bboxes\n if affine_mat is not None:\n bbox[0:2] = self.affine_transform(bbox[0:2], affine_mat)\n bbox[2:4] = self.affine_transform(bbox[2:4], affine_mat)\n else:\n bbox[[0, 2]] *= width_scale\n bbox[[1, 3]] *= height_scale\n # convert [xmin, ymin, xmax, ymax] to [xmin, ymin, w, h]\n bbox[2:4] -= (bbox[:2] - 1)\n self.coco_result.append({\"image_id\": imgid,\n \"category_id\": category_id,\n \"bbox\": bbox[:4].tolist(),\n \"score\": score})\n\n def update(self, labels, preds):\n \"\"\"\n Updates the internal evaluation result.\n\n Parameters:\n ----------\n labels : torch.Tensor\n The labels of the data.\n preds : torch.Tensor\n Predicted values.\n \"\"\"\n assert (labels is not None)\n # label = labels.cpu().detach().numpy()\n pred = preds.cpu().detach().numpy()\n\n det_bboxes = []\n det_ids = []\n det_scores = []\n\n bboxes = pred[:, :, :4]\n ids = pred[:, :, 4]\n scores = pred[:, :, 5]\n det_ids.append(ids)\n det_scores.append(scores)\n det_bboxes.append(bboxes.clip(0, self.img_height))\n\n self.update2(det_bboxes, det_ids, det_scores)\n\n @staticmethod\n def affine_transform(pt, t):\n \"\"\"\n Apply affine transform to a bounding box given transform matrix t.\n\n Parameters:\n ----------\n pt : numpy.ndarray\n Bounding box with shape (1, 2).\n t : numpy.ndarray\n Transformation matrix with shape (2, 3).\n\n Returns:\n -------\n numpy.ndarray\n New bounding box with shape (1, 2).\n \"\"\"\n new_pt = np.array([pt[0], pt[1], 1.], dtype=np.float32).T\n new_pt = np.dot(t, new_pt)\n return new_pt[:2]\n",
"\"\"\"\n FishNet for ImageNet-1K, implemented in Gluon.\n Original paper: 'FishNet: A Versatile Backbone for Image, Region, and Pixel Level Prediction,'\n http://papers.nips.cc/paper/7356-fishnet-a-versatile-backbone-for-image-region-and-pixel-level-prediction.pdf.\n\"\"\"\n\n__all__ = ['FishNet', 'fishnet99', 'fishnet150', 'ChannelSqueeze']\n\nimport os\nfrom mxnet import cpu\nfrom mxnet.gluon import nn, HybridBlock\nfrom mxnet.gluon.contrib.nn import Identity\nfrom .common import pre_conv1x1_block, pre_conv3x3_block, conv1x1, SesquialteralHourglass, InterpolationBlock\nfrom .preresnet import PreResActivation\nfrom .senet import SEInitBlock\n\n\ndef channel_squeeze(x,\n channels_per_group):\n \"\"\"\n Channel squeeze operation.\n\n Parameters:\n ----------\n x : NDArray\n Input tensor.\n channels_per_group : int\n Number of channels per group.\n\n Returns:\n -------\n NDArray\n Resulted tensor.\n \"\"\"\n return x.reshape((0, -4, channels_per_group, -1, -2)).sum(axis=2)\n\n\nclass ChannelSqueeze(HybridBlock):\n \"\"\"\n Channel squeeze layer. This is a wrapper over the same operation. It is designed to save the number of groups.\n\n Parameters:\n ----------\n channels : int\n Number of channels.\n groups : int\n Number of groups.\n \"\"\"\n def __init__(self,\n channels,\n groups,\n **kwargs):\n super(ChannelSqueeze, self).__init__(**kwargs)\n assert (channels % groups == 0)\n self.channels_per_group = channels // groups\n\n def hybrid_forward(self, F, x):\n return channel_squeeze(x, self.channels_per_group)\n\n\nclass PreSEAttBlock(HybridBlock):\n \"\"\"\n FishNet specific Squeeze-and-Excitation attention block.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n bn_use_global_stats : bool\n Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.\n reduction : int, default 16\n Squeeze reduction value.\n \"\"\"\n\n def __init__(self,\n in_channels,\n out_channels,\n bn_use_global_stats,\n reduction=16,\n **kwargs):\n super(PreSEAttBlock, self).__init__(**kwargs)\n mid_cannels = out_channels // reduction\n\n with self.name_scope():\n self.bn = nn.BatchNorm(\n in_channels=in_channels,\n use_global_stats=bn_use_global_stats)\n self.relu = nn.Activation(\"relu\")\n self.conv1 = conv1x1(\n in_channels=in_channels,\n out_channels=mid_cannels,\n use_bias=True)\n self.conv2 = conv1x1(\n in_channels=mid_cannels,\n out_channels=out_channels,\n use_bias=True)\n self.sigmoid = nn.Activation(\"sigmoid\")\n\n def hybrid_forward(self, F, x):\n x = self.bn(x)\n x = self.relu(x)\n x = F.contrib.AdaptiveAvgPooling2D(x, output_size=1)\n x = self.conv1(x)\n x = self.relu(x)\n x = self.conv2(x)\n x = self.sigmoid(x)\n return x\n\n\nclass FishBottleneck(HybridBlock):\n \"\"\"\n FishNet bottleneck block for residual unit.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n strides : int or tuple/list of 2 int\n Strides of the convolution.\n dilation : int or tuple/list of 2 int\n Dilation value for convolution layer.\n bn_use_global_stats : bool\n Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels,\n strides,\n dilation,\n bn_use_global_stats,\n **kwargs):\n super(FishBottleneck, self).__init__(**kwargs)\n mid_channels = out_channels // 4\n\n with self.name_scope():\n self.conv1 = pre_conv1x1_block(\n in_channels=in_channels,\n out_channels=mid_channels,\n bn_use_global_stats=bn_use_global_stats)\n self.conv2 = pre_conv3x3_block(\n in_channels=mid_channels,\n out_channels=mid_channels,\n strides=strides,\n padding=dilation,\n dilation=dilation,\n bn_use_global_stats=bn_use_global_stats)\n self.conv3 = pre_conv1x1_block(\n in_channels=mid_channels,\n out_channels=out_channels,\n bn_use_global_stats=bn_use_global_stats)\n\n def hybrid_forward(self, F, x):\n x = self.conv1(x)\n x = self.conv2(x)\n x = self.conv3(x)\n return x\n\n\nclass FishBlock(HybridBlock):\n \"\"\"\n FishNet block.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n strides : int or tuple/list of 2 int, default 1\n Strides of the convolution.\n dilation : int or tuple/list of 2 int, default 1\n Dilation value for convolution layer.\n bn_use_global_stats : bool, default False\n Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.\n squeeze : bool, default False\n Whether to use a channel squeeze operation.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels,\n strides=1,\n dilation=1,\n bn_use_global_stats=False,\n squeeze=False,\n **kwargs):\n super(FishBlock, self).__init__(**kwargs)\n self.squeeze = squeeze\n self.resize_identity = (in_channels != out_channels) or (strides != 1)\n\n with self.name_scope():\n self.body = FishBottleneck(\n in_channels=in_channels,\n out_channels=out_channels,\n strides=strides,\n dilation=dilation,\n bn_use_global_stats=bn_use_global_stats)\n if self.squeeze:\n assert (in_channels // 2 == out_channels)\n self.c_squeeze = ChannelSqueeze(\n channels=in_channels,\n groups=2)\n elif self.resize_identity:\n self.identity_conv = pre_conv1x1_block(\n in_channels=in_channels,\n out_channels=out_channels,\n strides=strides,\n bn_use_global_stats=bn_use_global_stats)\n\n def hybrid_forward(self, F, x):\n if self.squeeze:\n identity = self.c_squeeze(x)\n elif self.resize_identity:\n identity = self.identity_conv(x)\n else:\n identity = x\n x = self.body(x)\n x = x + identity\n return x\n\n\nclass DownUnit(HybridBlock):\n \"\"\"\n FishNet down unit.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels_list : list of int\n Number of output channels for each block.\n bn_use_global_stats : bool\n Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels_list,\n bn_use_global_stats,\n **kwargs):\n super(DownUnit, self).__init__(**kwargs)\n with self.name_scope():\n self.blocks = nn.HybridSequential(prefix=\"\")\n for i, out_channels in enumerate(out_channels_list):\n self.blocks.add(FishBlock(\n in_channels=in_channels,\n out_channels=out_channels,\n bn_use_global_stats=bn_use_global_stats))\n in_channels = out_channels\n self.pool = nn.MaxPool2D(\n pool_size=2,\n strides=2)\n\n def hybrid_forward(self, F, x):\n x = self.blocks(x)\n x = self.pool(x)\n return x\n\n\nclass UpUnit(HybridBlock):\n \"\"\"\n FishNet up unit.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels_list : list of int\n Number of output channels for each block.\n dilation : int or tuple/list of 2 int, default 1\n Dilation value for convolution layer.\n bn_use_global_stats : bool, default False\n Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels_list,\n dilation=1,\n bn_use_global_stats=False,\n **kwargs):\n super(UpUnit, self).__init__(**kwargs)\n with self.name_scope():\n self.blocks = nn.HybridSequential(prefix=\"\")\n for i, out_channels in enumerate(out_channels_list):\n squeeze = (dilation > 1) and (i == 0)\n self.blocks.add(FishBlock(\n in_channels=in_channels,\n out_channels=out_channels,\n dilation=dilation,\n bn_use_global_stats=bn_use_global_stats,\n squeeze=squeeze))\n in_channels = out_channels\n self.upsample = InterpolationBlock(scale_factor=2, bilinear=False)\n\n def hybrid_forward(self, F, x):\n x = self.blocks(x)\n x = self.upsample(x)\n return x\n\n\nclass SkipUnit(HybridBlock):\n \"\"\"\n FishNet skip connection unit.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels_list : list of int\n Number of output channels for each block.\n bn_use_global_stats : bool\n Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels_list,\n bn_use_global_stats,\n **kwargs):\n super(SkipUnit, self).__init__(**kwargs)\n with self.name_scope():\n self.blocks = nn.HybridSequential(prefix=\"\")\n for i, out_channels in enumerate(out_channels_list):\n self.blocks.add(FishBlock(\n in_channels=in_channels,\n out_channels=out_channels,\n bn_use_global_stats=bn_use_global_stats))\n in_channels = out_channels\n\n def hybrid_forward(self, F, x):\n x = self.blocks(x)\n return x\n\n\nclass SkipAttUnit(HybridBlock):\n \"\"\"\n FishNet skip connection unit with attention block.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels_list : list of int\n Number of output channels for each block.\n bn_use_global_stats : bool\n Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels_list,\n bn_use_global_stats,\n **kwargs):\n super(SkipAttUnit, self).__init__(**kwargs)\n mid_channels1 = in_channels // 2\n mid_channels2 = 2 * in_channels\n\n with self.name_scope():\n self.conv1 = pre_conv1x1_block(\n in_channels=in_channels,\n out_channels=mid_channels1,\n bn_use_global_stats=bn_use_global_stats)\n self.conv2 = pre_conv1x1_block(\n in_channels=mid_channels1,\n out_channels=mid_channels2,\n use_bias=True,\n bn_use_global_stats=bn_use_global_stats)\n in_channels = mid_channels2\n\n self.se = PreSEAttBlock(\n in_channels=mid_channels2,\n out_channels=out_channels_list[-1],\n bn_use_global_stats=bn_use_global_stats)\n\n self.blocks = nn.HybridSequential(prefix=\"\")\n for i, out_channels in enumerate(out_channels_list):\n self.blocks.add(FishBlock(\n in_channels=in_channels,\n out_channels=out_channels,\n bn_use_global_stats=bn_use_global_stats))\n in_channels = out_channels\n\n def hybrid_forward(self, F, x):\n x = self.conv1(x)\n x = self.conv2(x)\n w = self.se(x)\n x = self.blocks(x)\n x = F.broadcast_add(F.broadcast_mul(x, w), w)\n return x\n\n\nclass FishFinalBlock(HybridBlock):\n \"\"\"\n FishNet final block.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n bn_use_global_stats : bool\n Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.\n \"\"\"\n def __init__(self,\n in_channels,\n bn_use_global_stats,\n **kwargs):\n super(FishFinalBlock, self).__init__(**kwargs)\n mid_channels = in_channels // 2\n\n with self.name_scope():\n self.conv1 = pre_conv1x1_block(\n in_channels=in_channels,\n out_channels=mid_channels,\n bn_use_global_stats=bn_use_global_stats)\n self.preactiv = PreResActivation(\n in_channels=mid_channels,\n bn_use_global_stats=bn_use_global_stats)\n\n def hybrid_forward(self, F, x):\n x = self.conv1(x)\n x = self.preactiv(x)\n return x\n\n\nclass FishNet(HybridBlock):\n \"\"\"\n FishNet model from 'FishNet: A Versatile Backbone for Image, Region, and Pixel Level Prediction,'\n http://papers.nips.cc/paper/7356-fishnet-a-versatile-backbone-for-image-region-and-pixel-level-prediction.pdf.\n\n Parameters:\n ----------\n direct_channels : list of list of list of int\n Number of output channels for each unit along the straight path.\n skip_channels : list of list of list of int\n Number of output channels for each skip connection unit.\n init_block_channels : int\n Number of output channels for the initial unit.\n bn_use_global_stats : bool, default False\n Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.\n Useful for fine-tuning.\n in_channels : int, default 3\n Number of input channels.\n in_size : tuple of two ints, default (224, 224)\n Spatial size of the expected input image.\n classes : int, default 1000\n Number of classification classes.\n \"\"\"\n def __init__(self,\n direct_channels,\n skip_channels,\n init_block_channels,\n bn_use_global_stats=False,\n in_channels=3,\n in_size=(224, 224),\n classes=1000,\n **kwargs):\n super(FishNet, self).__init__(**kwargs)\n self.in_size = in_size\n self.classes = classes\n\n depth = len(direct_channels[0])\n down1_channels = direct_channels[0]\n up_channels = direct_channels[1]\n down2_channels = direct_channels[2]\n skip1_channels = skip_channels[0]\n skip2_channels = skip_channels[1]\n\n with self.name_scope():\n self.features = nn.HybridSequential(prefix=\"\")\n self.features.add(SEInitBlock(\n in_channels=in_channels,\n out_channels=init_block_channels,\n bn_use_global_stats=bn_use_global_stats))\n in_channels = init_block_channels\n\n down1_seq = nn.HybridSequential(prefix=\"\")\n skip1_seq = nn.HybridSequential(prefix=\"\")\n for i in range(depth + 1):\n skip1_channels_list = skip1_channels[i]\n if i < depth:\n skip1_seq.add(SkipUnit(\n in_channels=in_channels,\n out_channels_list=skip1_channels_list,\n bn_use_global_stats=bn_use_global_stats))\n down1_channels_list = down1_channels[i]\n down1_seq.add(DownUnit(\n in_channels=in_channels,\n out_channels_list=down1_channels_list,\n bn_use_global_stats=bn_use_global_stats))\n in_channels = down1_channels_list[-1]\n else:\n skip1_seq.add(SkipAttUnit(\n in_channels=in_channels,\n out_channels_list=skip1_channels_list,\n bn_use_global_stats=bn_use_global_stats))\n in_channels = skip1_channels_list[-1]\n\n up_seq = nn.HybridSequential(prefix=\"\")\n skip2_seq = nn.HybridSequential(prefix=\"\")\n for i in range(depth + 1):\n skip2_channels_list = skip2_channels[i]\n if i > 0:\n in_channels += skip1_channels[depth - i][-1]\n if i < depth:\n skip2_seq.add(SkipUnit(\n in_channels=in_channels,\n out_channels_list=skip2_channels_list,\n bn_use_global_stats=bn_use_global_stats))\n up_channels_list = up_channels[i]\n dilation = 2 ** i\n up_seq.add(UpUnit(\n in_channels=in_channels,\n out_channels_list=up_channels_list,\n dilation=dilation,\n bn_use_global_stats=bn_use_global_stats))\n in_channels = up_channels_list[-1]\n else:\n skip2_seq.add(Identity())\n\n down2_seq = nn.HybridSequential(prefix=\"\")\n for i in range(depth):\n down2_channels_list = down2_channels[i]\n down2_seq.add(DownUnit(\n in_channels=in_channels,\n out_channels_list=down2_channels_list,\n bn_use_global_stats=bn_use_global_stats))\n in_channels = down2_channels_list[-1] + skip2_channels[depth - 1 - i][-1]\n\n self.features.add(SesquialteralHourglass(\n down1_seq=down1_seq,\n skip1_seq=skip1_seq,\n up_seq=up_seq,\n skip2_seq=skip2_seq,\n down2_seq=down2_seq))\n self.features.add(FishFinalBlock(\n in_channels=in_channels,\n bn_use_global_stats=bn_use_global_stats))\n in_channels = in_channels // 2\n self.features.add(nn.AvgPool2D(\n pool_size=7,\n strides=1))\n\n self.output = nn.HybridSequential(prefix=\"\")\n self.output.add(conv1x1(\n in_channels=in_channels,\n out_channels=classes,\n use_bias=True))\n self.output.add(nn.Flatten())\n\n def hybrid_forward(self, F, x):\n x = self.features(x)\n x = self.output(x)\n return x\n\n\ndef get_fishnet(blocks,\n model_name=None,\n pretrained=False,\n ctx=cpu(),\n root=os.path.join(\"~\", \".mxnet\", \"models\"),\n **kwargs):\n \"\"\"\n Create FishNet model with specific parameters.\n\n Parameters:\n ----------\n blocks : int\n Number of blocks.\n model_name : str or None, default None\n Model name for loading pretrained model.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n ctx : Context, default CPU\n The context in which to load the pretrained weights.\n root : str, default '~/.mxnet/models'\n Location for keeping the model parameters.\n \"\"\"\n\n if blocks == 99:\n direct_layers = [[2, 2, 6], [1, 1, 1], [1, 2, 2]]\n skip_layers = [[1, 1, 1, 2], [4, 1, 1, 0]]\n elif blocks == 150:\n direct_layers = [[2, 4, 8], [2, 2, 2], [2, 2, 4]]\n skip_layers = [[2, 2, 2, 4], [4, 2, 2, 0]]\n else:\n raise ValueError(\"Unsupported FishNet with number of blocks: {}\".format(blocks))\n\n direct_channels_per_layers = [[128, 256, 512], [512, 384, 256], [320, 832, 1600]]\n skip_channels_per_layers = [[64, 128, 256, 512], [512, 768, 512, 0]]\n\n direct_channels = [[[b] * c for (b, c) in zip(*a)] for a in\n ([(ci, li) for (ci, li) in zip(direct_channels_per_layers, direct_layers)])]\n skip_channels = [[[b] * c for (b, c) in zip(*a)] for a in\n ([(ci, li) for (ci, li) in zip(skip_channels_per_layers, skip_layers)])]\n\n init_block_channels = 64\n\n net = FishNet(\n direct_channels=direct_channels,\n skip_channels=skip_channels,\n init_block_channels=init_block_channels,\n **kwargs)\n\n if pretrained:\n if (model_name is None) or (not model_name):\n raise ValueError(\"Parameter `model_name` should be properly initialized for loading pretrained model.\")\n from .model_store import get_model_file\n net.load_parameters(\n filename=get_model_file(\n model_name=model_name,\n local_model_store_dir_path=root),\n ctx=ctx)\n\n return net\n\n\ndef fishnet99(**kwargs):\n \"\"\"\n FishNet-99 model from 'FishNet: A Versatile Backbone for Image, Region, and Pixel Level Prediction,'\n http://papers.nips.cc/paper/7356-fishnet-a-versatile-backbone-for-image-region-and-pixel-level-prediction.pdf.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n ctx : Context, default CPU\n The context in which to load the pretrained weights.\n root : str, default '~/.mxnet/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_fishnet(blocks=99, model_name=\"fishnet99\", **kwargs)\n\n\ndef fishnet150(**kwargs):\n \"\"\"\n FishNet-150 model from 'FishNet: A Versatile Backbone for Image, Region, and Pixel Level Prediction,'\n http://papers.nips.cc/paper/7356-fishnet-a-versatile-backbone-for-image-region-and-pixel-level-prediction.pdf.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n ctx : Context, default CPU\n The context in which to load the pretrained weights.\n root : str, default '~/.mxnet/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_fishnet(blocks=150, model_name=\"fishnet150\", **kwargs)\n\n\ndef _test():\n import numpy as np\n import mxnet as mx\n\n pretrained = False\n\n models = [\n fishnet99,\n fishnet150,\n ]\n\n for model in models:\n\n net = model(pretrained=pretrained)\n\n ctx = mx.cpu()\n if not pretrained:\n net.initialize(ctx=ctx)\n\n # net.hybridize()\n net_params = net.collect_params()\n weight_count = 0\n for param in net_params.values():\n if (param.shape is None) or (not param._differentiable):\n continue\n weight_count += np.prod(param.shape)\n print(\"m={}, {}\".format(model.__name__, weight_count))\n assert (model != fishnet99 or weight_count == 16628904)\n assert (model != fishnet150 or weight_count == 24959400)\n\n x = mx.nd.zeros((1, 3, 224, 224), ctx=ctx)\n y = net(x)\n assert (y.shape == (1, 1000))\n\n\nif __name__ == \"__main__\":\n _test()\n",
"\"\"\"\n SKNet for ImageNet-1K, implemented in PyTorch.\n Original paper: 'Selective Kernel Networks,' https://arxiv.org/abs/1903.06586.\n\"\"\"\n\n__all__ = ['SKNet', 'sknet50', 'sknet101', 'sknet152']\n\nimport os\nimport torch.nn as nn\nimport torch.nn.init as init\nfrom .common import conv1x1, conv1x1_block, conv3x3_block, Concurrent\nfrom .resnet import ResInitBlock\n\n\nclass SKConvBlock(nn.Module):\n \"\"\"\n SKNet specific convolution block.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n stride : int or tuple/list of 2 int\n Strides of the convolution.\n groups : int, default 32\n Number of groups in branches.\n num_branches : int, default 2\n Number of branches (`M` parameter in the paper).\n reduction : int, default 16\n Reduction value for intermediate channels (`r` parameter in the paper).\n min_channels : int, default 32\n Minimal number of intermediate channels (`L` parameter in the paper).\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels,\n stride,\n groups=32,\n num_branches=2,\n reduction=16,\n min_channels=32):\n super(SKConvBlock, self).__init__()\n self.num_branches = num_branches\n self.out_channels = out_channels\n mid_channels = max(in_channels // reduction, min_channels)\n\n self.branches = Concurrent(stack=True)\n for i in range(num_branches):\n dilation = 1 + i\n self.branches.add_module(\"branch{}\".format(i + 2), conv3x3_block(\n in_channels=in_channels,\n out_channels=out_channels,\n stride=stride,\n padding=dilation,\n dilation=dilation,\n groups=groups))\n self.pool = nn.AdaptiveAvgPool2d(output_size=1)\n self.fc1 = conv1x1_block(\n in_channels=out_channels,\n out_channels=mid_channels)\n self.fc2 = conv1x1(\n in_channels=mid_channels,\n out_channels=(out_channels * num_branches))\n self.softmax = nn.Softmax(dim=1)\n\n def forward(self, x):\n y = self.branches(x)\n\n u = y.sum(dim=1)\n s = self.pool(u)\n z = self.fc1(s)\n w = self.fc2(z)\n\n batch = w.size(0)\n w = w.view(batch, self.num_branches, self.out_channels)\n w = self.softmax(w)\n w = w.unsqueeze(-1).unsqueeze(-1)\n\n y = y * w\n y = y.sum(dim=1)\n return y\n\n\nclass SKNetBottleneck(nn.Module):\n \"\"\"\n SKNet bottleneck block for residual path in SKNet unit.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n stride : int or tuple/list of 2 int\n Strides of the convolution.\n bottleneck_factor : int, default 2\n Bottleneck factor.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels,\n stride,\n bottleneck_factor=2):\n super(SKNetBottleneck, self).__init__()\n mid_channels = out_channels // bottleneck_factor\n\n self.conv1 = conv1x1_block(\n in_channels=in_channels,\n out_channels=mid_channels)\n self.conv2 = SKConvBlock(\n in_channels=mid_channels,\n out_channels=mid_channels,\n stride=stride)\n self.conv3 = conv1x1_block(\n in_channels=mid_channels,\n out_channels=out_channels,\n activation=None)\n\n def forward(self, x):\n x = self.conv1(x)\n x = self.conv2(x)\n x = self.conv3(x)\n return x\n\n\nclass SKNetUnit(nn.Module):\n \"\"\"\n SKNet unit.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n stride : int or tuple/list of 2 int\n Strides of the convolution.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels,\n stride):\n super(SKNetUnit, self).__init__()\n self.resize_identity = (in_channels != out_channels) or (stride != 1)\n\n self.body = SKNetBottleneck(\n in_channels=in_channels,\n out_channels=out_channels,\n stride=stride)\n if self.resize_identity:\n self.identity_conv = conv1x1_block(\n in_channels=in_channels,\n out_channels=out_channels,\n stride=stride,\n activation=None)\n self.activ = nn.ReLU(inplace=True)\n\n def forward(self, x):\n if self.resize_identity:\n identity = self.identity_conv(x)\n else:\n identity = x\n x = self.body(x)\n x = x + identity\n x = self.activ(x)\n return x\n\n\nclass SKNet(nn.Module):\n \"\"\"\n SKNet model from 'Selective Kernel Networks,' https://arxiv.org/abs/1903.06586.\n\n Parameters:\n ----------\n channels : list of list of int\n Number of output channels for each unit.\n init_block_channels : int\n Number of output channels for the initial unit.\n in_channels : int, default 3\n Number of input channels.\n in_size : tuple of two ints, default (224, 224)\n Spatial size of the expected input image.\n num_classes : int, default 1000\n Number of classification classes.\n \"\"\"\n def __init__(self,\n channels,\n init_block_channels,\n in_channels=3,\n in_size=(224, 224),\n num_classes=1000):\n super(SKNet, self).__init__()\n self.in_size = in_size\n self.num_classes = num_classes\n\n self.features = nn.Sequential()\n self.features.add_module(\"init_block\", ResInitBlock(\n in_channels=in_channels,\n out_channels=init_block_channels))\n in_channels = init_block_channels\n for i, channels_per_stage in enumerate(channels):\n stage = nn.Sequential()\n for j, out_channels in enumerate(channels_per_stage):\n stride = 2 if (j == 0) and (i != 0) else 1\n stage.add_module(\"unit{}\".format(j + 1), SKNetUnit(\n in_channels=in_channels,\n out_channels=out_channels,\n stride=stride))\n in_channels = out_channels\n self.features.add_module(\"stage{}\".format(i + 1), stage)\n self.features.add_module(\"final_pool\", nn.AvgPool2d(\n kernel_size=7,\n stride=1))\n\n self.output = nn.Linear(\n in_features=in_channels,\n out_features=num_classes)\n\n self._init_params()\n\n def _init_params(self):\n for name, module in self.named_modules():\n if isinstance(module, nn.Conv2d):\n init.kaiming_uniform_(module.weight)\n if module.bias is not None:\n init.constant_(module.bias, 0)\n\n def forward(self, x):\n x = self.features(x)\n x = x.view(x.size(0), -1)\n x = self.output(x)\n return x\n\n\ndef get_sknet(blocks,\n model_name=None,\n pretrained=False,\n root=os.path.join(\"~\", \".torch\", \"models\"),\n **kwargs):\n \"\"\"\n Create SKNet model with specific parameters.\n\n Parameters:\n ----------\n blocks : int\n Number of blocks.\n model_name : str or None, default None\n Model name for loading pretrained model.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.torch/models'\n Location for keeping the model parameters.\n \"\"\"\n\n if blocks == 50:\n layers = [3, 4, 6, 3]\n elif blocks == 101:\n layers = [3, 4, 23, 3]\n elif blocks == 152:\n layers = [3, 8, 36, 3]\n else:\n raise ValueError(\"Unsupported SKNet with number of blocks: {}\".format(blocks))\n\n init_block_channels = 64\n channels_per_layers = [256, 512, 1024, 2048]\n channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]\n\n net = SKNet(\n channels=channels,\n init_block_channels=init_block_channels,\n **kwargs)\n\n if pretrained:\n if (model_name is None) or (not model_name):\n raise ValueError(\"Parameter `model_name` should be properly initialized for loading pretrained model.\")\n from .model_store import download_model\n download_model(\n net=net,\n model_name=model_name,\n local_model_store_dir_path=root)\n\n return net\n\n\ndef sknet50(**kwargs):\n \"\"\"\n SKNet-50 model from 'Selective Kernel Networks,' https://arxiv.org/abs/1903.06586.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.torch/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_sknet(blocks=50, model_name=\"sknet50\", **kwargs)\n\n\ndef sknet101(**kwargs):\n \"\"\"\n SKNet-101 model from 'Selective Kernel Networks,' https://arxiv.org/abs/1903.06586.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.torch/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_sknet(blocks=101, model_name=\"sknet101\", **kwargs)\n\n\ndef sknet152(**kwargs):\n \"\"\"\n SKNet-152 model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.torch/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_sknet(blocks=152, model_name=\"sknet152\", **kwargs)\n\n\ndef _calc_width(net):\n import numpy as np\n net_params = filter(lambda p: p.requires_grad, net.parameters())\n weight_count = 0\n for param in net_params:\n weight_count += np.prod(param.size())\n return weight_count\n\n\ndef _test():\n import torch\n\n pretrained = False\n\n models = [\n sknet50,\n sknet101,\n sknet152,\n ]\n\n for model in models:\n\n net = model(pretrained=pretrained)\n\n # net.train()\n net.eval()\n weight_count = _calc_width(net)\n print(\"m={}, {}\".format(model.__name__, weight_count))\n assert (model != sknet50 or weight_count == 27479784)\n assert (model != sknet101 or weight_count == 48736040)\n assert (model != sknet152 or weight_count == 66295656)\n\n x = torch.randn(14, 3, 224, 224)\n y = net(x)\n y.sum().backward()\n assert (tuple(y.size()) == (14, 1000))\n\n\nif __name__ == \"__main__\":\n _test()\n",
"\"\"\"\n Cityscapes semantic segmentation dataset.\n\"\"\"\n\nimport os\nimport numpy as np\nimport mxnet as mx\nfrom PIL import Image\nfrom .seg_dataset import SegDataset\nfrom .voc_seg_dataset import VOCMetaInfo\n\n\nclass CityscapesSegDataset(SegDataset):\n \"\"\"\n Cityscapes semantic segmentation dataset.\n\n Parameters:\n ----------\n root : str\n Path to a folder with `leftImg8bit` and `gtFine` subfolders.\n mode : str, default 'train'\n 'train', 'val', 'test', or 'demo'.\n transform : callable, optional\n A function that transforms the image.\n \"\"\"\n def __init__(self,\n root,\n mode=\"train\",\n transform=None,\n **kwargs):\n super(CityscapesSegDataset, self).__init__(\n root=root,\n mode=mode,\n transform=transform,\n **kwargs)\n\n image_dir_path = os.path.join(root, \"leftImg8bit\")\n mask_dir_path = os.path.join(root, \"gtFine\")\n assert os.path.exists(image_dir_path) and os.path.exists(mask_dir_path), \"Please prepare dataset\"\n\n mode_dir_name = \"train\" if mode == \"train\" else \"val\"\n image_dir_path = os.path.join(image_dir_path, mode_dir_name)\n # mask_dir_path = os.path.join(mask_dir_path, mode_dir_name)\n\n self.images = []\n self.masks = []\n for image_subdir_path, _, image_file_names in os.walk(image_dir_path):\n for image_file_name in image_file_names:\n if image_file_name.endswith(\".png\"):\n image_file_path = os.path.join(image_subdir_path, image_file_name)\n mask_file_name = image_file_name.replace(\"leftImg8bit\", \"gtFine_labelIds\")\n mask_subdir_path = image_subdir_path.replace(\"leftImg8bit\", \"gtFine\")\n mask_file_path = os.path.join(mask_subdir_path, mask_file_name)\n if os.path.isfile(mask_file_path):\n self.images.append(image_file_path)\n self.masks.append(mask_file_path)\n else:\n print(\"Cannot find the mask: {}\".format(mask_file_path))\n\n assert (len(self.images) == len(self.masks))\n if len(self.images) == 0:\n raise RuntimeError(\"Found 0 images in subfolders of: {}\\n\".format(image_dir_path))\n\n def __getitem__(self, index):\n image = Image.open(self.images[index]).convert(\"RGB\")\n if self.mode == \"demo\":\n image = self._img_transform(image)\n if self.transform is not None:\n image = self.transform(image)\n return image, os.path.basename(self.images[index])\n mask = Image.open(self.masks[index])\n\n if self.mode == \"train\":\n image, mask = self._train_sync_transform(image, mask)\n elif self.mode == \"val\":\n image, mask = self._val_sync_transform(image, mask)\n else:\n assert (self.mode == \"test\")\n image = self._img_transform(image)\n mask = self._mask_transform(mask)\n\n if self.transform is not None:\n image = self.transform(image)\n return image, mask\n\n classes = 19\n vague_idx = 19\n use_vague = True\n background_idx = -1\n ignore_bg = False\n\n _key = np.array([-1, -1, -1, -1, -1, -1,\n -1, -1, 0, 1, -1, -1,\n 2, 3, 4, -1, -1, -1,\n 5, -1, 6, 7, 8, 9,\n 10, 11, 12, 13, 14, 15,\n -1, -1, 16, 17, 18])\n _mapping = np.array(range(-1, len(_key) - 1)).astype(np.int32)\n\n @staticmethod\n def _class_to_index(mask):\n values = np.unique(mask)\n for value in values:\n assert(value in CityscapesSegDataset._mapping)\n index = np.digitize(mask.ravel(), CityscapesSegDataset._mapping, right=True)\n return CityscapesSegDataset._key[index].reshape(mask.shape)\n\n @staticmethod\n def _mask_transform(mask):\n np_mask = np.array(mask).astype(np.int32)\n np_mask = CityscapesSegDataset._class_to_index(np_mask)\n np_mask[np_mask == -1] = CityscapesSegDataset.vague_idx\n return mx.nd.array(np_mask, mx.cpu())\n\n def __len__(self):\n return len(self.images)\n\n\nclass CityscapesMetaInfo(VOCMetaInfo):\n def __init__(self):\n super(CityscapesMetaInfo, self).__init__()\n self.label = \"Cityscapes\"\n self.short_label = \"voc\"\n self.root_dir_name = \"cityscapes\"\n self.dataset_class = CityscapesSegDataset\n self.num_classes = CityscapesSegDataset.classes\n self.test_metric_extra_kwargs = [\n {\"vague_idx\": CityscapesSegDataset.vague_idx,\n \"use_vague\": CityscapesSegDataset.use_vague,\n \"macro_average\": False},\n {\"num_classes\": CityscapesSegDataset.classes,\n \"vague_idx\": CityscapesSegDataset.vague_idx,\n \"use_vague\": CityscapesSegDataset.use_vague,\n \"bg_idx\": CityscapesSegDataset.background_idx,\n \"ignore_bg\": CityscapesSegDataset.ignore_bg,\n \"macro_average\": False}]\n",
"\"\"\"\n ESPNet for image segmentation, implemented in PyTorch.\n Original paper: 'ESPNet: Efficient Spatial Pyramid of Dilated Convolutions for Semantic Segmentation,'\n https://arxiv.org/abs/1803.06815.\n\"\"\"\n\n__all__ = ['ESPNet', 'espnet_cityscapes']\n\nimport os\nimport torch\nimport torch.nn as nn\nfrom common import conv1x1, conv3x3_block, NormActivation, DeconvBlock\nfrom espcnet import ESPCNet, ESPBlock\n\n\nclass ESPFinalBlock(nn.Module):\n \"\"\"\n ESPNet final block.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n bn_eps : float\n Small float added to variance in Batch norm.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels,\n bn_eps):\n super(ESPFinalBlock, self).__init__()\n self.conv = conv3x3_block(\n in_channels=in_channels,\n out_channels=out_channels,\n bn_eps=bn_eps,\n activation=(lambda: nn.PReLU(out_channels)))\n self.deconv = nn.ConvTranspose2d(\n in_channels=out_channels,\n out_channels=out_channels,\n kernel_size=2,\n stride=2,\n padding=0,\n output_padding=0,\n bias=False)\n\n def forward(self, x):\n x = self.conv(x)\n x = self.deconv(x)\n return x\n\n\nclass ESPNet(ESPCNet):\n \"\"\"\n ESPNet model from 'ESPNet: Efficient Spatial Pyramid of Dilated Convolutions for Semantic Segmentation,'\n https://arxiv.org/abs/1803.06815.\n\n Parameters:\n ----------\n layers : list of int\n Number of layers for each unit.\n channels : list of int\n Number of output channels for each unit (for y-branch).\n init_block_channels : int\n Number of output channels for the initial unit.\n cut_x : list of int\n Whether to concatenate with x-branch for each unit.\n bn_eps : float, default 1e-5\n Small float added to variance in Batch norm.\n aux : bool, default False\n Whether to output an auxiliary result.\n fixed_size : bool, default False\n Whether to expect fixed spatial size of input image.\n in_channels : int, default 3\n Number of input channels.\n in_size : tuple of two ints, default (1024, 2048)\n Spatial size of the expected input image.\n num_classes : int, default 19\n Number of segmentation classes.\n \"\"\"\n def __init__(self,\n layers,\n channels,\n init_block_channels,\n cut_x,\n bn_eps=1e-5,\n aux=False,\n fixed_size=False,\n in_channels=3,\n in_size=(1024, 2048),\n num_classes=19):\n super(ESPNet, self).__init__(\n layers=layers,\n channels=channels,\n init_block_channels=init_block_channels,\n cut_x=cut_x,\n bn_eps=bn_eps,\n aux=aux,\n fixed_size=fixed_size,\n in_channels=in_channels,\n in_size=in_size,\n num_classes=num_classes)\n assert (aux is not None)\n assert (fixed_size is not None)\n assert ((in_size[0] % 8 == 0) and (in_size[1] % 8 == 0))\n self.in_size = in_size\n self.num_classes = num_classes\n self.fixed_size = fixed_size\n\n self.skip1 = nn.BatchNorm2d(\n num_features=num_classes,\n eps=bn_eps)\n self.skip2 = conv1x1(\n in_channels=channels[1],\n out_channels=num_classes)\n\n self.up1 = nn.Sequential(nn.ConvTranspose2d(\n in_channels=num_classes,\n out_channels=num_classes,\n kernel_size=2,\n stride=2,\n padding=0,\n output_padding=0,\n bias=False))\n\n self.up2 = nn.Sequential()\n self.up2.add_module(\"block1\", NormActivation(\n in_channels=(2 * num_classes),\n bn_eps=bn_eps,\n activation=(lambda: nn.PReLU(2 * num_classes))))\n self.up2.add_module(\"block2\", ESPBlock(\n in_channels=(2 * num_classes),\n out_channels=num_classes,\n downsample=False,\n residual=False,\n bn_eps=bn_eps))\n self.up2.add_module(\"block3\", DeconvBlock(\n in_channels=num_classes,\n out_channels=num_classes,\n kernel_size=2,\n stride=2,\n padding=0,\n bn_eps=bn_eps,\n activation=(lambda: nn.PReLU(num_classes))))\n\n self.decoder_head = ESPFinalBlock(\n in_channels=(channels[0] + num_classes),\n out_channels=num_classes,\n bn_eps=bn_eps)\n\n self._init_params()\n\n def _init_params(self):\n for name, module in self.named_modules():\n if isinstance(module, nn.Conv2d):\n nn.init.kaiming_uniform_(module.weight)\n if module.bias is not None:\n nn.init.constant_(module.bias, 0)\n\n def forward(self, x):\n y0 = self.features.init_block(x)\n y1, x = self.features.stage1(y0, x)\n y2, x = self.features.stage2(y1, x)\n y3, x = self.features.stage3(y2, x)\n yh = self.head(y3)\n\n v1 = self.skip1(yh)\n z1 = self.up1(v1)\n v2 = self.skip2(y2)\n z2 = torch.cat((v2, z1), dim=1)\n z2 = self.up2(z2)\n z = torch.cat((z2, y1), dim=1)\n z = self.decoder_head(z)\n return z\n\n\ndef get_espnet(model_name=None,\n pretrained=False,\n root=os.path.join(\"~\", \".torch\", \"models\"),\n **kwargs):\n \"\"\"\n Create ESPNet model with specific parameters.\n\n Parameters:\n ----------\n model_name : str or None, default None\n Model name for loading pretrained model.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.torch/models'\n Location for keeping the model parameters.\n \"\"\"\n init_block_channels = 16\n layers = [0, 3, 4]\n channels = [19, 131, 256]\n cut_x = [1, 1, 0]\n bn_eps = 1e-3\n\n net = ESPNet(\n layers=layers,\n channels=channels,\n init_block_channels=init_block_channels,\n cut_x=cut_x,\n bn_eps=bn_eps,\n **kwargs)\n\n if pretrained:\n if (model_name is None) or (not model_name):\n raise ValueError(\"Parameter `model_name` should be properly initialized for loading pretrained model.\")\n from .model_store import download_model\n download_model(\n net=net,\n model_name=model_name,\n local_model_store_dir_path=root)\n\n return net\n\n\ndef espnet_cityscapes(num_classes=19, **kwargs):\n \"\"\"\n ESPNet model for Cityscapes from 'ESPNet: Efficient Spatial Pyramid of Dilated Convolutions for Semantic\n Segmentation,' https://arxiv.org/abs/1803.06815.\n\n Parameters:\n ----------\n num_classes : int, default 19\n Number of segmentation classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.torch/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_espnet(num_classes=num_classes, model_name=\"espnet_cityscapes\", **kwargs)\n\n\ndef _calc_width(net):\n import numpy as np\n net_params = filter(lambda p: p.requires_grad, net.parameters())\n weight_count = 0\n for param in net_params:\n weight_count += np.prod(param.size())\n return weight_count\n\n\ndef _test():\n pretrained = False\n fixed_size = True\n in_size = (1024, 2048)\n classes = 19\n\n models = [\n espnet_cityscapes,\n ]\n\n for model in models:\n\n net = model(pretrained=pretrained, in_size=in_size, fixed_size=fixed_size)\n\n # net.train()\n net.eval()\n weight_count = _calc_width(net)\n print(\"m={}, {}\".format(model.__name__, weight_count))\n assert (model != espnet_cityscapes or weight_count == 201542)\n\n batch = 4\n x = torch.randn(batch, 3, in_size[0], in_size[1])\n y = net(x)\n # y.sum().backward()\n assert (tuple(y.size()) == (batch, classes, in_size[0], in_size[1]))\n\n\nif __name__ == \"__main__\":\n _test()\n",
"\"\"\"\n BAM-ResNet for ImageNet-1K, implemented in PyTorch.\n Original paper: 'BAM: Bottleneck Attention Module,' https://arxiv.org/abs/1807.06514.\n\"\"\"\n\n__all__ = ['BamResNet', 'bam_resnet18', 'bam_resnet34', 'bam_resnet50', 'bam_resnet101', 'bam_resnet152']\n\nimport os\nimport torch.nn as nn\nimport torch.nn.init as init\nfrom .common import conv1x1, conv1x1_block, conv3x3_block\nfrom .resnet import ResInitBlock, ResUnit\n\n\nclass DenseBlock(nn.Module):\n \"\"\"\n Standard dense block with Batch normalization and ReLU activation.\n\n Parameters:\n ----------\n in_features : int\n Number of input features.\n out_features : int\n Number of output features.\n \"\"\"\n def __init__(self,\n in_features,\n out_features):\n super(DenseBlock, self).__init__()\n self.fc = nn.Linear(\n in_features=in_features,\n out_features=out_features)\n self.bn = nn.BatchNorm1d(num_features=out_features)\n self.activ = nn.ReLU(inplace=True)\n\n def forward(self, x):\n x = self.fc(x)\n x = self.bn(x)\n x = self.activ(x)\n return x\n\n\nclass ChannelGate(nn.Module):\n \"\"\"\n BAM channel gate block.\n\n Parameters:\n ----------\n channels : int\n Number of input/output channels.\n reduction_ratio : int, default 16\n Channel reduction ratio.\n num_layers : int, default 1\n Number of dense blocks.\n \"\"\"\n def __init__(self,\n channels,\n reduction_ratio=16,\n num_layers=1):\n super(ChannelGate, self).__init__()\n mid_channels = channels // reduction_ratio\n\n self.pool = nn.AdaptiveAvgPool2d(output_size=(1, 1))\n self.init_fc = DenseBlock(\n in_features=channels,\n out_features=mid_channels)\n self.main_fcs = nn.Sequential()\n for i in range(num_layers - 1):\n self.main_fcs.add_module(\"fc{}\".format(i + 1), DenseBlock(\n in_features=mid_channels,\n out_features=mid_channels))\n self.final_fc = nn.Linear(\n in_features=mid_channels,\n out_features=channels)\n\n def forward(self, x):\n input = x\n x = self.pool(x)\n x = x.view(x.size(0), -1)\n x = self.init_fc(x)\n x = self.main_fcs(x)\n x = self.final_fc(x)\n x = x.unsqueeze(2).unsqueeze(3).expand_as(input)\n return x\n\n\nclass SpatialGate(nn.Module):\n \"\"\"\n BAM spatial gate block.\n\n Parameters:\n ----------\n channels : int\n Number of input/output channels.\n reduction_ratio : int, default 16\n Channel reduction ratio.\n num_dil_convs : int, default 2\n Number of dilated convolutions.\n dilation : int, default 4\n Dilation/padding value for corresponding convolutions.\n \"\"\"\n def __init__(self,\n channels,\n reduction_ratio=16,\n num_dil_convs=2,\n dilation=4):\n super(SpatialGate, self).__init__()\n mid_channels = channels // reduction_ratio\n\n self.init_conv = conv1x1_block(\n in_channels=channels,\n out_channels=mid_channels,\n stride=1,\n bias=True)\n self.dil_convs = nn.Sequential()\n for i in range(num_dil_convs):\n self.dil_convs.add_module(\"conv{}\".format(i + 1), conv3x3_block(\n in_channels=mid_channels,\n out_channels=mid_channels,\n stride=1,\n padding=dilation,\n dilation=dilation,\n bias=True))\n self.final_conv = conv1x1(\n in_channels=mid_channels,\n out_channels=1,\n stride=1,\n bias=True)\n\n def forward(self, x):\n input = x\n x = self.init_conv(x)\n x = self.dil_convs(x)\n x = self.final_conv(x)\n x = x.expand_as(input)\n return x\n\n\nclass BamBlock(nn.Module):\n \"\"\"\n BAM attention block for BAM-ResNet.\n\n Parameters:\n ----------\n channels : int\n Number of input/output channels.\n \"\"\"\n def __init__(self,\n channels):\n super(BamBlock, self).__init__()\n self.ch_att = ChannelGate(channels=channels)\n self.sp_att = SpatialGate(channels=channels)\n self.sigmoid = nn.Sigmoid()\n\n def forward(self, x):\n att = 1 + self.sigmoid(self.ch_att(x) * self.sp_att(x))\n x = x * att\n return x\n\n\nclass BamResUnit(nn.Module):\n \"\"\"\n BAM-ResNet unit.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n stride : int or tuple/list of 2 int\n Strides of the convolution.\n bottleneck : bool\n Whether to use a bottleneck or simple block in units.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels,\n stride,\n bottleneck):\n super(BamResUnit, self).__init__()\n self.use_bam = (stride != 1)\n\n if self.use_bam:\n self.bam = BamBlock(channels=in_channels)\n self.res_unit = ResUnit(\n in_channels=in_channels,\n out_channels=out_channels,\n stride=stride,\n bottleneck=bottleneck,\n conv1_stride=False)\n\n def forward(self, x):\n if self.use_bam:\n x = self.bam(x)\n x = self.res_unit(x)\n return x\n\n\nclass BamResNet(nn.Module):\n \"\"\"\n BAM-ResNet model from 'BAM: Bottleneck Attention Module,' https://arxiv.org/abs/1807.06514.\n\n Parameters:\n ----------\n channels : list of list of int\n Number of output channels for each unit.\n init_block_channels : int\n Number of output channels for the initial unit.\n bottleneck : bool\n Whether to use a bottleneck or simple block in units.\n in_channels : int, default 3\n Number of input channels.\n in_size : tuple of two ints, default (224, 224)\n Spatial size of the expected input image.\n num_classes : int, default 1000\n Number of classification classes.\n \"\"\"\n def __init__(self,\n channels,\n init_block_channels,\n bottleneck,\n in_channels=3,\n in_size=(224, 224),\n num_classes=1000):\n super(BamResNet, self).__init__()\n self.in_size = in_size\n self.num_classes = num_classes\n\n self.features = nn.Sequential()\n self.features.add_module(\"init_block\", ResInitBlock(\n in_channels=in_channels,\n out_channels=init_block_channels))\n in_channels = init_block_channels\n for i, channels_per_stage in enumerate(channels):\n stage = nn.Sequential()\n for j, out_channels in enumerate(channels_per_stage):\n stride = 2 if (j == 0) and (i != 0) else 1\n stage.add_module(\"unit{}\".format(j + 1), BamResUnit(\n in_channels=in_channels,\n out_channels=out_channels,\n stride=stride,\n bottleneck=bottleneck))\n in_channels = out_channels\n self.features.add_module(\"stage{}\".format(i + 1), stage)\n self.features.add_module(\"final_pool\", nn.AvgPool2d(\n kernel_size=7,\n stride=1))\n\n self.output = nn.Linear(\n in_features=in_channels,\n out_features=num_classes)\n\n self._init_params()\n\n def _init_params(self):\n for name, module in self.named_modules():\n if isinstance(module, nn.Conv2d):\n init.kaiming_uniform_(module.weight)\n if module.bias is not None:\n init.constant_(module.bias, 0)\n\n def forward(self, x):\n x = self.features(x)\n x = x.view(x.size(0), -1)\n x = self.output(x)\n return x\n\n\ndef get_resnet(blocks,\n model_name=None,\n pretrained=False,\n root=os.path.join(\"~\", \".torch\", \"models\"),\n **kwargs):\n \"\"\"\n Create BAM-ResNet model with specific parameters.\n\n Parameters:\n ----------\n blocks : int\n Number of blocks.\n conv1_stride : bool\n Whether to use stride in the first or the second convolution layer in units.\n use_se : bool\n Whether to use SE block.\n width_scale : float\n Scale factor for width of layers.\n model_name : str or None, default None\n Model name for loading pretrained model.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.torch/models'\n Location for keeping the model parameters.\n \"\"\"\n\n if blocks == 18:\n layers = [2, 2, 2, 2]\n elif blocks == 34:\n layers = [3, 4, 6, 3]\n elif blocks == 50:\n layers = [3, 4, 6, 3]\n elif blocks == 101:\n layers = [3, 4, 23, 3]\n elif blocks == 152:\n layers = [3, 8, 36, 3]\n else:\n raise ValueError(\"Unsupported BAM-ResNet with number of blocks: {}\".format(blocks))\n\n init_block_channels = 64\n\n if blocks < 50:\n channels_per_layers = [64, 128, 256, 512]\n bottleneck = False\n else:\n channels_per_layers = [256, 512, 1024, 2048]\n bottleneck = True\n\n channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]\n\n net = BamResNet(\n channels=channels,\n init_block_channels=init_block_channels,\n bottleneck=bottleneck,\n **kwargs)\n\n if pretrained:\n if (model_name is None) or (not model_name):\n raise ValueError(\"Parameter `model_name` should be properly initialized for loading pretrained model.\")\n from .model_store import download_model\n download_model(\n net=net,\n model_name=model_name,\n local_model_store_dir_path=root)\n\n return net\n\n\ndef bam_resnet18(**kwargs):\n \"\"\"\n BAM-ResNet-18 model from 'BAM: Bottleneck Attention Module,' https://arxiv.org/abs/1807.06514.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.torch/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnet(blocks=18, model_name=\"bam_resnet18\", **kwargs)\n\n\ndef bam_resnet34(**kwargs):\n \"\"\"\n BAM-ResNet-34 model from 'BAM: Bottleneck Attention Module,' https://arxiv.org/abs/1807.06514.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.torch/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnet(blocks=34, model_name=\"bam_resnet34\", **kwargs)\n\n\ndef bam_resnet50(**kwargs):\n \"\"\"\n BAM-ResNet-50 model from 'BAM: Bottleneck Attention Module,' https://arxiv.org/abs/1807.06514.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.torch/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnet(blocks=50, model_name=\"bam_resnet50\", **kwargs)\n\n\ndef bam_resnet101(**kwargs):\n \"\"\"\n BAM-ResNet-101 model from 'BAM: Bottleneck Attention Module,' https://arxiv.org/abs/1807.06514.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.torch/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnet(blocks=101, model_name=\"bam_resnet101\", **kwargs)\n\n\ndef bam_resnet152(**kwargs):\n \"\"\"\n BAM-ResNet-152 model from 'BAM: Bottleneck Attention Module,' https://arxiv.org/abs/1807.06514.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.torch/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnet(blocks=152, model_name=\"bam_resnet152\", **kwargs)\n\n\ndef _calc_width(net):\n import numpy as np\n net_params = filter(lambda p: p.requires_grad, net.parameters())\n weight_count = 0\n for param in net_params:\n weight_count += np.prod(param.size())\n return weight_count\n\n\ndef _test():\n import torch\n\n pretrained = False\n\n models = [\n bam_resnet18,\n bam_resnet34,\n bam_resnet50,\n bam_resnet101,\n bam_resnet152,\n ]\n\n for model in models:\n\n net = model(pretrained=pretrained)\n\n # net.train()\n net.eval()\n weight_count = _calc_width(net)\n print(\"m={}, {}\".format(model.__name__, weight_count))\n assert (model != bam_resnet18 or weight_count == 11712503)\n assert (model != bam_resnet34 or weight_count == 21820663)\n assert (model != bam_resnet50 or weight_count == 25915099)\n assert (model != bam_resnet101 or weight_count == 44907227)\n assert (model != bam_resnet152 or weight_count == 60550875)\n\n x = torch.randn(1, 3, 224, 224)\n y = net(x)\n y.sum().backward()\n assert (tuple(y.size()) == (1, 1000))\n\n\nif __name__ == \"__main__\":\n _test()\n",
"\"\"\"\n IBPPose for COCO Keypoint, implemented in Gluon.\n Original paper: 'Simple Pose: Rethinking and Improving a Bottom-up Approach for Multi-Person Pose Estimation,'\n https://arxiv.org/abs/1911.10529.\n\"\"\"\n\n__all__ = ['IbpPose', 'ibppose_coco']\n\nimport os\nfrom mxnet import cpu\nfrom mxnet.gluon import nn, HybridBlock\nfrom .common import get_activation_layer, conv1x1_block, conv3x3_block, conv7x7_block, SEBlock, Hourglass,\\\n InterpolationBlock\n\n\nclass IbpResBottleneck(HybridBlock):\n \"\"\"\n Bottleneck block for residual path in the residual unit.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n strides : int or tuple/list of 2 int\n Strides of the convolution.\n use_bias : bool, default False\n Whether the layer uses a bias vector.\n bottleneck_factor : int, default 2\n Bottleneck factor.\n activation : function or str or None, default nn.Activation('relu')\n Activation function or name of activation function.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels,\n strides,\n use_bias=False,\n bottleneck_factor=2,\n activation=(lambda: nn.Activation(\"relu\")),\n **kwargs):\n super(IbpResBottleneck, self).__init__(**kwargs)\n mid_channels = out_channels // bottleneck_factor\n\n with self.name_scope():\n self.conv1 = conv1x1_block(\n in_channels=in_channels,\n out_channels=mid_channels,\n use_bias=use_bias,\n activation=activation)\n self.conv2 = conv3x3_block(\n in_channels=mid_channels,\n out_channels=mid_channels,\n strides=strides,\n use_bias=use_bias,\n activation=activation)\n self.conv3 = conv1x1_block(\n in_channels=mid_channels,\n out_channels=out_channels,\n use_bias=use_bias,\n activation=None)\n\n def hybrid_forward(self, F, x):\n x = self.conv1(x)\n x = self.conv2(x)\n x = self.conv3(x)\n return x\n\n\nclass IbpResUnit(HybridBlock):\n \"\"\"\n ResNet-like residual unit with residual connection.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n strides : int or tuple/list of 2 int, default 1\n Strides of the convolution.\n use_bias : bool, default False\n Whether the layer uses a bias vector.\n bottleneck_factor : int, default 2\n Bottleneck factor.\n activation : function or str or None, default nn.Activation('relu')\n Activation function or name of activation function.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels,\n strides=1,\n use_bias=False,\n bottleneck_factor=2,\n activation=(lambda: nn.Activation(\"relu\")),\n **kwargs):\n super(IbpResUnit, self).__init__(**kwargs)\n self.resize_identity = (in_channels != out_channels) or (strides != 1)\n\n with self.name_scope():\n self.body = IbpResBottleneck(\n in_channels=in_channels,\n out_channels=out_channels,\n strides=strides,\n use_bias=use_bias,\n bottleneck_factor=bottleneck_factor,\n activation=activation)\n if self.resize_identity:\n self.identity_conv = conv1x1_block(\n in_channels=in_channels,\n out_channels=out_channels,\n strides=strides,\n use_bias=use_bias,\n activation=None)\n self.activ = get_activation_layer(activation)\n\n def hybrid_forward(self, F, x):\n if self.resize_identity:\n identity = self.identity_conv(x)\n else:\n identity = x\n x = self.body(x)\n x = x + identity\n x = self.activ(x)\n return x\n\n\nclass IbpBackbone(HybridBlock):\n \"\"\"\n IBPPose backbone.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n activation : function or str or None\n Activation function or name of activation function.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels,\n activation,\n **kwargs):\n super(IbpBackbone, self).__init__(**kwargs)\n dilations = (3, 3, 4, 4, 5, 5)\n mid1_channels = out_channels // 4\n mid2_channels = out_channels // 2\n\n with self.name_scope():\n self.conv1 = conv7x7_block(\n in_channels=in_channels,\n out_channels=mid1_channels,\n strides=2,\n activation=activation)\n self.res1 = IbpResUnit(\n in_channels=mid1_channels,\n out_channels=mid2_channels,\n activation=activation)\n self.pool = nn.MaxPool2D(\n pool_size=2,\n strides=2)\n self.res2 = IbpResUnit(\n in_channels=mid2_channels,\n out_channels=mid2_channels,\n activation=activation)\n self.dilation_branch = nn.HybridSequential(prefix=\"\")\n for dilation in dilations:\n self.dilation_branch.add(conv3x3_block(\n in_channels=mid2_channels,\n out_channels=mid2_channels,\n padding=dilation,\n dilation=dilation,\n activation=activation))\n\n def hybrid_forward(self, F, x):\n x = self.conv1(x)\n x = self.res1(x)\n x = self.pool(x)\n x = self.res2(x)\n y = self.dilation_branch(x)\n x = F.concat(x, y, dim=1)\n return x\n\n\nclass IbpDownBlock(HybridBlock):\n \"\"\"\n IBPPose down block for the hourglass.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n activation : function or str or None\n Activation function or name of activation function.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels,\n activation,\n **kwargs):\n super(IbpDownBlock, self).__init__(**kwargs)\n with self.name_scope():\n self.down = nn.MaxPool2D(\n pool_size=2,\n strides=2)\n self.res = IbpResUnit(\n in_channels=in_channels,\n out_channels=out_channels,\n activation=activation)\n\n def hybrid_forward(self, F, x):\n x = self.down(x)\n x = self.res(x)\n return x\n\n\nclass IbpUpBlock(HybridBlock):\n \"\"\"\n IBPPose up block for the hourglass.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n use_bn : bool\n Whether to use BatchNorm layer.\n activation : function or str or None\n Activation function or name of activation function.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels,\n use_bn,\n activation,\n **kwargs):\n super(IbpUpBlock, self).__init__(**kwargs)\n with self.name_scope():\n self.res = IbpResUnit(\n in_channels=in_channels,\n out_channels=out_channels,\n activation=activation)\n self.up = InterpolationBlock(\n scale_factor=2,\n bilinear=False)\n self.conv = conv3x3_block(\n in_channels=out_channels,\n out_channels=out_channels,\n use_bias=(not use_bn),\n use_bn=use_bn,\n activation=activation)\n\n def hybrid_forward(self, F, x):\n x = self.res(x)\n x = self.up(x)\n x = self.conv(x)\n return x\n\n\nclass MergeBlock(HybridBlock):\n \"\"\"\n IBPPose merge block.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n use_bn : bool\n Whether to use BatchNorm layer.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels,\n use_bn,\n **kwargs):\n super(MergeBlock, self).__init__(**kwargs)\n with self.name_scope():\n self.conv = conv1x1_block(\n in_channels=in_channels,\n out_channels=out_channels,\n use_bias=(not use_bn),\n use_bn=use_bn,\n activation=None)\n\n def hybrid_forward(self, F, x):\n return self.conv(x)\n\n\nclass IbpPreBlock(HybridBlock):\n \"\"\"\n IBPPose preliminary decoder block.\n\n Parameters:\n ----------\n out_channels : int\n Number of output channels.\n use_bn : bool\n Whether to use BatchNorm layer.\n activation : function or str or None\n Activation function or name of activation function.\n \"\"\"\n def __init__(self,\n out_channels,\n use_bn,\n activation,\n **kwargs):\n super(IbpPreBlock, self).__init__(**kwargs)\n with self.name_scope():\n self.conv1 = conv3x3_block(\n in_channels=out_channels,\n out_channels=out_channels,\n use_bias=(not use_bn),\n use_bn=use_bn,\n activation=activation)\n self.conv2 = conv3x3_block(\n in_channels=out_channels,\n out_channels=out_channels,\n use_bias=(not use_bn),\n use_bn=use_bn,\n activation=activation)\n self.se = SEBlock(\n channels=out_channels,\n use_conv=False,\n mid_activation=activation)\n\n def hybrid_forward(self, F, x):\n x = self.conv1(x)\n x = self.conv2(x)\n x = self.se(x)\n return x\n\n\nclass IbpPass(HybridBlock):\n \"\"\"\n IBPPose single pass decoder block.\n\n Parameters:\n ----------\n channels : int\n Number of input/output channels.\n mid_channels : int\n Number of middle channels.\n depth : int\n Depth of hourglass.\n growth_rate : int\n Addition for number of channel for each level.\n use_bn : bool\n Whether to use BatchNorm layer.\n activation : function or str or None\n Activation function or name of activation function.\n \"\"\"\n def __init__(self,\n channels,\n mid_channels,\n depth,\n growth_rate,\n merge,\n use_bn,\n activation,\n **kwargs):\n super(IbpPass, self).__init__(**kwargs)\n self.merge = merge\n\n with self.name_scope():\n down_seq = nn.HybridSequential(prefix=\"\")\n up_seq = nn.HybridSequential(prefix=\"\")\n skip_seq = nn.HybridSequential(prefix=\"\")\n top_channels = channels\n bottom_channels = channels\n for i in range(depth + 1):\n skip_seq.add(IbpResUnit(\n in_channels=top_channels,\n out_channels=top_channels,\n activation=activation))\n bottom_channels += growth_rate\n if i < depth:\n down_seq.add(IbpDownBlock(\n in_channels=top_channels,\n out_channels=bottom_channels,\n activation=activation))\n up_seq.add(IbpUpBlock(\n in_channels=bottom_channels,\n out_channels=top_channels,\n use_bn=use_bn,\n activation=activation))\n top_channels = bottom_channels\n self.hg = Hourglass(\n down_seq=down_seq,\n up_seq=up_seq,\n skip_seq=skip_seq)\n\n self.pre_block = IbpPreBlock(\n out_channels=channels,\n use_bn=use_bn,\n activation=activation)\n self.post_block = conv1x1_block(\n in_channels=channels,\n out_channels=mid_channels,\n use_bias=True,\n use_bn=False,\n activation=None)\n\n if self.merge:\n self.pre_merge_block = MergeBlock(\n in_channels=channels,\n out_channels=channels,\n use_bn=use_bn)\n self.post_merge_block = MergeBlock(\n in_channels=mid_channels,\n out_channels=channels,\n use_bn=use_bn)\n\n def hybrid_forward(self, F, x, x_prev):\n x = self.hg(x)\n if x_prev is not None:\n x = x + x_prev\n y = self.pre_block(x)\n z = self.post_block(y)\n if self.merge:\n z = self.post_merge_block(z) + self.pre_merge_block(y)\n return z\n\n\nclass IbpPose(HybridBlock):\n \"\"\"\n IBPPose model from 'Simple Pose: Rethinking and Improving a Bottom-up Approach for Multi-Person Pose Estimation,'\n https://arxiv.org/abs/1911.10529.\n\n Parameters:\n ----------\n passes : int\n Number of passes.\n backbone_out_channels : int\n Number of output channels for the backbone.\n outs_channels : int\n Number of output channels for the backbone.\n depth : int\n Depth of hourglass.\n growth_rate : int\n Addition for number of channel for each level.\n use_bn : bool\n Whether to use BatchNorm layer.\n in_channels : int, default 3\n Number of input channels.\n in_size : tuple of two ints, default (256, 256)\n Spatial size of the expected input image.\n \"\"\"\n def __init__(self,\n passes,\n backbone_out_channels,\n outs_channels,\n depth,\n growth_rate,\n use_bn,\n in_channels=3,\n in_size=(256, 256),\n **kwargs):\n super(IbpPose, self).__init__(**kwargs)\n self.in_size = in_size\n activation = (lambda: nn.LeakyReLU(alpha=0.01))\n\n with self.name_scope():\n self.backbone = IbpBackbone(\n in_channels=in_channels,\n out_channels=backbone_out_channels,\n activation=activation)\n\n self.decoder = nn.HybridSequential(prefix=\"\")\n for i in range(passes):\n merge = (i != passes - 1)\n self.decoder.add(IbpPass(\n channels=backbone_out_channels,\n mid_channels=outs_channels,\n depth=depth,\n growth_rate=growth_rate,\n merge=merge,\n use_bn=use_bn,\n activation=activation))\n\n def hybrid_forward(self, F, x):\n x = self.backbone(x)\n x_prev = None\n for block in self.decoder._children.values():\n if x_prev is not None:\n x = x + x_prev\n x_prev = block(x, x_prev)\n return x_prev\n\n\ndef get_ibppose(model_name=None,\n pretrained=False,\n ctx=cpu(),\n root=os.path.join(\"~\", \".mxnet\", \"models\"),\n **kwargs):\n \"\"\"\n Create IBPPose model with specific parameters.\n\n Parameters:\n ----------\n model_name : str or None, default None\n Model name for loading pretrained model.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n ctx : Context, default CPU\n The context in which to load the pretrained weights.\n root : str, default '~/.mxnet/models'\n Location for keeping the model parameters.\n \"\"\"\n passes = 4\n backbone_out_channels = 256\n outs_channels = 50\n depth = 4\n growth_rate = 128\n use_bn = True\n\n net = IbpPose(\n passes=passes,\n backbone_out_channels=backbone_out_channels,\n outs_channels=outs_channels,\n depth=depth,\n growth_rate=growth_rate,\n use_bn=use_bn,\n **kwargs)\n\n if pretrained:\n if (model_name is None) or (not model_name):\n raise ValueError(\"Parameter `model_name` should be properly initialized for loading pretrained model.\")\n from .model_store import get_model_file\n net.load_parameters(\n filename=get_model_file(\n model_name=model_name,\n local_model_store_dir_path=root),\n ctx=ctx)\n\n return net\n\n\ndef ibppose_coco(**kwargs):\n \"\"\"\n IBPPose model for COCO Keypoint from 'Simple Pose: Rethinking and Improving a Bottom-up Approach for Multi-Person\n Pose Estimation,' https://arxiv.org/abs/1911.10529.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n ctx : Context, default CPU\n The context in which to load the pretrained weights.\n root : str, default '~/.mxnet/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_ibppose(model_name=\"ibppose_coco\", **kwargs)\n\n\ndef _test():\n import numpy as np\n import mxnet as mx\n\n in_size = (256, 256)\n pretrained = False\n\n models = [\n ibppose_coco,\n ]\n\n for model in models:\n\n net = model(pretrained=pretrained)\n\n ctx = mx.cpu()\n if not pretrained:\n net.initialize(ctx=ctx)\n\n net.hybridize()\n net_params = net.collect_params()\n weight_count = 0\n for param in net_params.values():\n if (param.shape is None) or (not param._differentiable):\n continue\n weight_count += np.prod(param.shape)\n print(\"m={}, {}\".format(model.__name__, weight_count))\n assert (model != ibppose_coco or weight_count == 95827784)\n\n batch = 14\n x = mx.nd.random.normal(shape=(batch, 3, in_size[0], in_size[1]), ctx=ctx)\n y = net(x)\n assert (y.shape == (batch, 50, in_size[0] // 4, in_size[0] // 4))\n\n\nif __name__ == \"__main__\":\n _test()\n",
"\"\"\"\n ShuffleNet V2 for ImageNet-1K, implemented in TensorFlow.\n Original paper: 'ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design,'\n https://arxiv.org/abs/1807.11164.\n\"\"\"\n\n__all__ = ['ShuffleNetV2', 'shufflenetv2_wd2', 'shufflenetv2_w1', 'shufflenetv2_w3d2', 'shufflenetv2_w2']\n\nimport os\nimport tensorflow as tf\nfrom .common import conv1x1, depthwise_conv3x3, conv1x1_block, conv3x3_block, batchnorm, channel_shuffle, maxpool2d,\\\n se_block, is_channels_first, get_channel_axis, flatten\n\n\ndef shuffle_unit(x,\n in_channels,\n out_channels,\n downsample,\n use_se,\n use_residual,\n training,\n data_format,\n name=\"shuffle_unit\"):\n \"\"\"\n ShuffleNetV2 unit.\n\n Parameters:\n ----------\n x : Tensor\n Input tensor.\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n downsample : bool\n Whether do downsample.\n use_se : bool\n Whether to use SE block.\n use_residual : bool\n Whether to use residual connection.\n training : bool, or a TensorFlow boolean scalar tensor\n Whether to return the output in training mode or in inference mode.\n data_format : str\n The ordering of the dimensions in tensors.\n name : str, default 'shuffle_unit'\n Unit name.\n\n Returns:\n -------\n Tensor\n Resulted tensor.\n \"\"\"\n mid_channels = out_channels // 2\n\n if downsample:\n y1 = depthwise_conv3x3(\n x=x,\n channels=in_channels,\n strides=2,\n data_format=data_format,\n name=name + \"/dw_conv4\")\n y1 = batchnorm(\n x=y1,\n training=training,\n data_format=data_format,\n name=name + \"/dw_bn4\")\n y1 = conv1x1(\n x=y1,\n in_channels=in_channels,\n out_channels=mid_channels,\n data_format=data_format,\n name=name + \"/expand_conv5/conv\")\n y1 = batchnorm(\n x=y1,\n training=training,\n data_format=data_format,\n name=name + \"/expand_bn5\")\n y1 = tf.nn.relu(y1, name=name + \"/expand_activ5\")\n x2 = x\n else:\n y1, x2 = tf.split(x, num_or_size_splits=2, axis=get_channel_axis(data_format))\n\n y2 = conv1x1(\n x=x2,\n in_channels=(in_channels if downsample else mid_channels),\n out_channels=mid_channels,\n data_format=data_format,\n name=name + \"/compress_conv1/conv\")\n y2 = batchnorm(\n x=y2,\n training=training,\n data_format=data_format,\n name=name + \"/compress_bn1\")\n y2 = tf.nn.relu(y2, name=name + \"/compress_activ1\")\n\n y2 = depthwise_conv3x3(\n x=y2,\n channels=mid_channels,\n strides=(2 if downsample else 1),\n data_format=data_format,\n name=name + \"/dw_conv2\")\n y2 = batchnorm(\n x=y2,\n training=training,\n data_format=data_format,\n name=name + \"/dw_bn2\")\n\n y2 = conv1x1(\n x=y2,\n in_channels=mid_channels,\n out_channels=mid_channels,\n data_format=data_format,\n name=name + \"/expand_conv3/conv\")\n y2 = batchnorm(\n x=y2,\n training=training,\n data_format=data_format,\n name=name + \"/expand_bn3\")\n y2 = tf.nn.relu(y2, name=name + \"/expand_activ3\")\n\n if use_se:\n y2 = se_block(\n x=y2,\n channels=mid_channels,\n data_format=data_format,\n name=name + \"/se\")\n\n if use_residual and not downsample:\n y2 = y2 + x2\n\n x = tf.concat([y1, y2], axis=get_channel_axis(data_format), name=name + \"/concat\")\n\n assert (mid_channels % 2 == 0)\n x = channel_shuffle(\n x=x,\n groups=2,\n data_format=data_format)\n\n return x\n\n\ndef shuffle_init_block(x,\n in_channels,\n out_channels,\n training,\n data_format,\n name=\"shuffle_init_block\"):\n \"\"\"\n ShuffleNetV2 specific initial block.\n\n Parameters:\n ----------\n x : Tensor\n Input tensor.\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n training : bool, or a TensorFlow boolean scalar tensor\n Whether to return the output in training mode or in inference mode.\n data_format : str\n The ordering of the dimensions in tensors.\n name : str, default 'shuffle_init_block'\n Block name.\n\n Returns:\n -------\n Tensor\n Resulted tensor.\n \"\"\"\n x = conv3x3_block(\n x=x,\n in_channels=in_channels,\n out_channels=out_channels,\n strides=2,\n training=training,\n data_format=data_format,\n name=name + \"/conv\")\n x = maxpool2d(\n x=x,\n pool_size=3,\n strides=2,\n padding=0,\n ceil_mode=True,\n data_format=data_format,\n name=name + \"/pool\")\n return x\n\n\nclass ShuffleNetV2(object):\n \"\"\"\n ShuffleNetV2 model from 'ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design,'\n https://arxiv.org/abs/1807.11164.\n\n Parameters:\n ----------\n channels : list of list of int\n Number of output channels for each unit.\n init_block_channels : int\n Number of output channels for the initial unit.\n final_block_channels : int\n Number of output channels for the final block of the feature extractor.\n use_se : bool, default False\n Whether to use SE block.\n use_residual : bool, default False\n Whether to use residual connections.\n in_channels : int, default 3\n Number of input channels.\n in_size : tuple of two ints, default (224, 224)\n Spatial size of the expected input image.\n classes : int, default 1000\n Number of classification classes.\n data_format : str, default 'channels_last'\n The ordering of the dimensions in tensors.\n \"\"\"\n def __init__(self,\n channels,\n init_block_channels,\n final_block_channels,\n use_se=False,\n use_residual=False,\n in_channels=3,\n in_size=(224, 224),\n classes=1000,\n data_format=\"channels_last\",\n **kwargs):\n super(ShuffleNetV2, self).__init__(**kwargs)\n assert (data_format in [\"channels_last\", \"channels_first\"])\n self.channels = channels\n self.init_block_channels = init_block_channels\n self.final_block_channels = final_block_channels\n self.use_se = use_se\n self.use_residual = use_residual\n self.in_channels = in_channels\n self.in_size = in_size\n self.classes = classes\n self.data_format = data_format\n\n def __call__(self,\n x,\n training=False):\n \"\"\"\n Build a model graph.\n\n Parameters:\n ----------\n x : Tensor\n Input tensor.\n training : bool, or a TensorFlow boolean scalar tensor, default False\n Whether to return the output in training mode or in inference mode.\n\n Returns:\n -------\n Tensor\n Resulted tensor.\n \"\"\"\n in_channels = self.in_channels\n x = shuffle_init_block(\n x=x,\n in_channels=in_channels,\n out_channels=self.init_block_channels,\n training=training,\n data_format=self.data_format,\n name=\"features/init_block\")\n in_channels = self.init_block_channels\n for i, channels_per_stage in enumerate(self.channels):\n for j, out_channels in enumerate(channels_per_stage):\n downsample = (j == 0)\n x = shuffle_unit(\n x=x,\n in_channels=in_channels,\n out_channels=out_channels,\n downsample=downsample,\n use_se=self.use_se,\n use_residual=self.use_residual,\n training=training,\n data_format=self.data_format,\n name=\"features/stage{}/unit{}\".format(i + 1, j + 1))\n in_channels = out_channels\n x = conv1x1_block(\n x=x,\n in_channels=in_channels,\n out_channels=self.final_block_channels,\n training=training,\n data_format=self.data_format,\n name=\"features/final_block\")\n x = tf.keras.layers.AveragePooling2D(\n pool_size=7,\n strides=1,\n data_format=self.data_format,\n name=\"features/final_pool\")(x)\n\n # x = tf.layers.flatten(x)\n x = flatten(\n x=x,\n data_format=self.data_format)\n x = tf.keras.layers.Dense(\n units=self.classes,\n name=\"output\")(x)\n\n return x\n\n\ndef get_shufflenetv2(width_scale,\n model_name=None,\n pretrained=False,\n root=os.path.join(\"~\", \".tensorflow\", \"models\"),\n **kwargs):\n \"\"\"\n Create ShuffleNetV2 model with specific parameters.\n\n Parameters:\n ----------\n width_scale : float\n Scale factor for width of layers.\n model_name : str or None, default None\n Model name for loading pretrained model.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n\n Returns:\n -------\n functor\n Functor for model graph creation with extra fields.\n \"\"\"\n\n init_block_channels = 24\n final_block_channels = 1024\n layers = [4, 8, 4]\n channels_per_layers = [116, 232, 464]\n\n channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]\n\n if width_scale != 1.0:\n channels = [[int(cij * width_scale) for cij in ci] for ci in channels]\n if width_scale > 1.5:\n final_block_channels = int(final_block_channels * width_scale)\n\n net = ShuffleNetV2(\n channels=channels,\n init_block_channels=init_block_channels,\n final_block_channels=final_block_channels,\n **kwargs)\n\n if pretrained:\n if (model_name is None) or (not model_name):\n raise ValueError(\"Parameter `model_name` should be properly initialized for loading pretrained model.\")\n from .model_store import download_state_dict\n net.state_dict, net.file_path = download_state_dict(\n model_name=model_name,\n local_model_store_dir_path=root)\n else:\n net.state_dict = None\n net.file_path = None\n\n return net\n\n\ndef shufflenetv2_wd2(**kwargs):\n \"\"\"\n ShuffleNetV2 0.5x model from 'ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design,'\n https://arxiv.org/abs/1807.11164.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n\n Returns:\n -------\n functor\n Functor for model graph creation with extra fields.\n \"\"\"\n return get_shufflenetv2(width_scale=(12.0 / 29.0), model_name=\"shufflenetv2_wd2\", **kwargs)\n\n\ndef shufflenetv2_w1(**kwargs):\n \"\"\"\n ShuffleNetV2 1x model from 'ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design,'\n https://arxiv.org/abs/1807.11164.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n\n Returns:\n -------\n functor\n Functor for model graph creation with extra fields.\n \"\"\"\n return get_shufflenetv2(width_scale=1.0, model_name=\"shufflenetv2_w1\", **kwargs)\n\n\ndef shufflenetv2_w3d2(**kwargs):\n \"\"\"\n ShuffleNetV2 1.5x model from 'ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design,'\n https://arxiv.org/abs/1807.11164.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n\n Returns:\n -------\n functor\n Functor for model graph creation with extra fields.\n \"\"\"\n return get_shufflenetv2(width_scale=(44.0 / 29.0), model_name=\"shufflenetv2_w3d2\", **kwargs)\n\n\ndef shufflenetv2_w2(**kwargs):\n \"\"\"\n ShuffleNetV2 2x model from 'ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design,'\n https://arxiv.org/abs/1807.11164.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n\n Returns:\n -------\n functor\n Functor for model graph creation with extra fields.\n \"\"\"\n return get_shufflenetv2(width_scale=(61.0 / 29.0), model_name=\"shufflenetv2_w2\", **kwargs)\n\n\ndef _test():\n import numpy as np\n\n data_format = \"channels_last\"\n pretrained = False\n\n models = [\n shufflenetv2_wd2,\n shufflenetv2_w1,\n shufflenetv2_w3d2,\n shufflenetv2_w2,\n ]\n\n for model in models:\n\n net = model(pretrained=pretrained, data_format=data_format)\n x = tf.placeholder(\n dtype=tf.float32,\n shape=(None, 3, 224, 224) if is_channels_first(data_format) else (None, 224, 224, 3),\n name=\"xx\")\n y_net = net(x)\n\n weight_count = np.sum([np.prod(v.get_shape().as_list()) for v in tf.trainable_variables()])\n print(\"m={}, {}\".format(model.__name__, weight_count))\n assert (model != shufflenetv2_wd2 or weight_count == 1366792)\n assert (model != shufflenetv2_w1 or weight_count == 2278604)\n assert (model != shufflenetv2_w3d2 or weight_count == 4406098)\n assert (model != shufflenetv2_w2 or weight_count == 7601686)\n\n with tf.Session() as sess:\n if pretrained:\n from .model_store import init_variables_from_state_dict\n init_variables_from_state_dict(sess=sess, state_dict=net.state_dict)\n else:\n sess.run(tf.global_variables_initializer())\n x_value = np.zeros((1, 3, 224, 224) if is_channels_first(data_format) else (1, 224, 224, 3), np.float32)\n y = sess.run(y_net, feed_dict={x: x_value})\n assert (y.shape == (1, 1000))\n tf.reset_default_graph()\n\n\nif __name__ == \"__main__\":\n _test()\n",
"\"\"\"\n ShuffleNet V2 for ImageNet-1K, implemented in Keras.\n Original paper: 'ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design,'\n https://arxiv.org/abs/1807.11164.\n\"\"\"\n\n__all__ = ['shufflenetv2', 'shufflenetv2_wd2', 'shufflenetv2_w1', 'shufflenetv2_w3d2', 'shufflenetv2_w2']\n\nimport os\nfrom keras import layers as nn\nfrom keras.models import Model\nfrom .common import conv1x1, depthwise_conv3x3, conv1x1_block, conv3x3_block, maxpool2d, channel_shuffle_lambda,\\\n se_block, batchnorm, is_channels_first, get_channel_axis, flatten\n\n\ndef shuffle_unit(x,\n in_channels,\n out_channels,\n downsample,\n use_se,\n use_residual,\n name=\"shuffle_unit\"):\n \"\"\"\n ShuffleNetV2 unit.\n\n Parameters:\n ----------\n x : keras.backend tensor/variable/symbol\n Input tensor/variable/symbol.\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n downsample : bool\n Whether do downsample.\n use_se : bool\n Whether to use SE block.\n use_residual : bool\n Whether to use residual connection.\n name : str, default 'shuffle_unit'\n Unit name.\n\n Returns:\n -------\n keras.backend tensor/variable/symbol\n Resulted tensor/variable/symbol.\n \"\"\"\n mid_channels = out_channels // 2\n\n if downsample:\n y1 = depthwise_conv3x3(\n x=x,\n channels=in_channels,\n strides=2,\n name=name + \"/dw_conv4\")\n y1 = batchnorm(\n x=y1,\n name=name + \"/dw_bn4\")\n y1 = conv1x1(\n x=y1,\n in_channels=in_channels,\n out_channels=mid_channels,\n name=name + \"/expand_conv5\")\n y1 = batchnorm(\n x=y1,\n name=name + \"/expand_bn5\")\n y1 = nn.Activation(\"relu\", name=name + \"/expand_activ5\")(y1)\n x2 = x\n else:\n in_split2_channels = in_channels // 2\n if is_channels_first():\n y1 = nn.Lambda(lambda z: z[:, 0:in_split2_channels, :, :])(x)\n x2 = nn.Lambda(lambda z: z[:, in_split2_channels:, :, :])(x)\n else:\n y1 = nn.Lambda(lambda z: z[:, :, :, 0:in_split2_channels])(x)\n x2 = nn.Lambda(lambda z: z[:, :, :, in_split2_channels:])(x)\n\n y2 = conv1x1(\n x=x2,\n in_channels=(in_channels if downsample else mid_channels),\n out_channels=mid_channels,\n name=name + \"/compress_conv1\")\n y2 = batchnorm(\n x=y2,\n name=name + \"/compress_bn1\")\n y2 = nn.Activation(\"relu\", name=name + \"/compress_activ1\")(y2)\n\n y2 = depthwise_conv3x3(\n x=y2,\n channels=mid_channels,\n strides=(2 if downsample else 1),\n name=name + \"/dw_conv2\")\n y2 = batchnorm(\n x=y2,\n name=name + \"/dw_bn2\")\n\n y2 = conv1x1(\n x=y2,\n in_channels=mid_channels,\n out_channels=mid_channels,\n name=name + \"/expand_conv3\")\n y2 = batchnorm(\n x=y2,\n name=name + \"/expand_bn3\")\n y2 = nn.Activation(\"relu\", name=name + \"/expand_activ3\")(y2)\n\n if use_se:\n y2 = se_block(\n x=y2,\n channels=mid_channels,\n name=name + \"/se\")\n\n if use_residual and not downsample:\n y2 = nn.add([y2, x2], name=name + \"/add\")\n\n x = nn.concatenate([y1, y2], axis=get_channel_axis(), name=name + \"/concat\")\n\n x = channel_shuffle_lambda(\n channels=out_channels,\n groups=2,\n name=name + \"/c_shuffle\")(x)\n\n return x\n\n\ndef shuffle_init_block(x,\n in_channels,\n out_channels,\n name=\"shuffle_init_block\"):\n \"\"\"\n ShuffleNetV2 specific initial block.\n\n Parameters:\n ----------\n x : keras.backend tensor/variable/symbol\n Input tensor/variable/symbol.\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n name : str, default 'shuffle_init_block'\n Block name.\n\n Returns:\n -------\n keras.backend tensor/variable/symbol\n Resulted tensor/variable/symbol.\n \"\"\"\n x = conv3x3_block(\n x=x,\n in_channels=in_channels,\n out_channels=out_channels,\n strides=2,\n name=name + \"/conv\")\n x = maxpool2d(\n x=x,\n pool_size=3,\n strides=2,\n padding=0,\n ceil_mode=True,\n name=name + \"/pool\")\n return x\n\n\ndef shufflenetv2(channels,\n init_block_channels,\n final_block_channels,\n use_se=False,\n use_residual=False,\n in_channels=3,\n in_size=(224, 224),\n classes=1000):\n \"\"\"\n ShuffleNetV2 model from 'ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design,'\n https://arxiv.org/abs/1807.11164.\n\n Parameters:\n ----------\n channels : list of list of int\n Number of output channels for each unit.\n init_block_channels : int\n Number of output channels for the initial unit.\n final_block_channels : int\n Number of output channels for the final block of the feature extractor.\n use_se : bool, default False\n Whether to use SE block.\n use_residual : bool, default False\n Whether to use residual connections.\n in_channels : int, default 3\n Number of input channels.\n in_size : tuple of two ints, default (224, 224)\n Spatial size of the expected input image.\n classes : int, default 1000\n Number of classification classes.\n \"\"\"\n input_shape = (in_channels, in_size[0], in_size[1]) if is_channels_first() else\\\n (in_size[0], in_size[1], in_channels)\n input = nn.Input(shape=input_shape)\n\n x = shuffle_init_block(\n x=input,\n in_channels=in_channels,\n out_channels=init_block_channels,\n name=\"features/init_block\")\n in_channels = init_block_channels\n for i, channels_per_stage in enumerate(channels):\n for j, out_channels in enumerate(channels_per_stage):\n downsample = (j == 0)\n x = shuffle_unit(\n x=x,\n in_channels=in_channels,\n out_channels=out_channels,\n downsample=downsample,\n use_se=use_se,\n use_residual=use_residual,\n name=\"features/stage{}/unit{}\".format(i + 1, j + 1))\n in_channels = out_channels\n x = conv1x1_block(\n x=x,\n in_channels=in_channels,\n out_channels=final_block_channels,\n name=\"features/final_block\")\n in_channels = final_block_channels\n x = nn.AvgPool2D(\n pool_size=7,\n strides=1,\n name=\"features/final_pool\")(x)\n\n # x = nn.Flatten()(x)\n x = flatten(x)\n x = nn.Dense(\n units=classes,\n input_dim=in_channels,\n name=\"output\")(x)\n\n model = Model(inputs=input, outputs=x)\n model.in_size = in_size\n model.classes = classes\n return model\n\n\ndef get_shufflenetv2(width_scale,\n model_name=None,\n pretrained=False,\n root=os.path.join(\"~\", \".keras\", \"models\"),\n **kwargs):\n \"\"\"\n Create ShuffleNetV2 model with specific parameters.\n\n Parameters:\n ----------\n width_scale : float\n Scale factor for width of layers.\n model_name : str or None, default None\n Model name for loading pretrained model.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.keras/models'\n Location for keeping the model parameters.\n \"\"\"\n\n init_block_channels = 24\n final_block_channels = 1024\n layers = [4, 8, 4]\n channels_per_layers = [116, 232, 464]\n\n channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]\n\n if width_scale != 1.0:\n channels = [[int(cij * width_scale) for cij in ci] for ci in channels]\n if width_scale > 1.5:\n final_block_channels = int(final_block_channels * width_scale)\n\n net = shufflenetv2(\n channels=channels,\n init_block_channels=init_block_channels,\n final_block_channels=final_block_channels,\n **kwargs)\n\n if pretrained:\n if (model_name is None) or (not model_name):\n raise ValueError(\"Parameter `model_name` should be properly initialized for loading pretrained model.\")\n from .model_store import download_model\n download_model(\n net=net,\n model_name=model_name,\n local_model_store_dir_path=root)\n\n return net\n\n\ndef shufflenetv2_wd2(**kwargs):\n \"\"\"\n ShuffleNetV2 0.5x model from 'ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design,'\n https://arxiv.org/abs/1807.11164.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.keras/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_shufflenetv2(width_scale=(12.0 / 29.0), model_name=\"shufflenetv2_wd2\", **kwargs)\n\n\ndef shufflenetv2_w1(**kwargs):\n \"\"\"\n ShuffleNetV2 1x model from 'ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design,'\n https://arxiv.org/abs/1807.11164.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.keras/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_shufflenetv2(width_scale=1.0, model_name=\"shufflenetv2_w1\", **kwargs)\n\n\ndef shufflenetv2_w3d2(**kwargs):\n \"\"\"\n ShuffleNetV2 1.5x model from 'ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design,'\n https://arxiv.org/abs/1807.11164.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.keras/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_shufflenetv2(width_scale=(44.0 / 29.0), model_name=\"shufflenetv2_w3d2\", **kwargs)\n\n\ndef shufflenetv2_w2(**kwargs):\n \"\"\"\n ShuffleNetV2 2x model from 'ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design,'\n https://arxiv.org/abs/1807.11164.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.keras/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_shufflenetv2(width_scale=(61.0 / 29.0), model_name=\"shufflenetv2_w2\", **kwargs)\n\n\ndef _test():\n import numpy as np\n import keras\n\n pretrained = False\n\n models = [\n shufflenetv2_wd2,\n shufflenetv2_w1,\n shufflenetv2_w3d2,\n shufflenetv2_w2,\n ]\n\n for model in models:\n\n net = model(pretrained=pretrained)\n # net.summary()\n weight_count = keras.utils.layer_utils.count_params(net.trainable_weights)\n print(\"m={}, {}\".format(model.__name__, weight_count))\n assert (model != shufflenetv2_wd2 or weight_count == 1366792)\n assert (model != shufflenetv2_w1 or weight_count == 2278604)\n assert (model != shufflenetv2_w3d2 or weight_count == 4406098)\n assert (model != shufflenetv2_w2 or weight_count == 7601686)\n\n if is_channels_first():\n x = np.zeros((1, 3, 224, 224), np.float32)\n else:\n x = np.zeros((1, 224, 224, 3), np.float32)\n y = net.predict(x)\n assert (y.shape == (1, 1000))\n\n\nif __name__ == \"__main__\":\n _test()\n",
"\"\"\"\n WRN for CIFAR/SVHN, implemented in PyTorch.\n Original paper: 'Wide Residual Networks,' https://arxiv.org/abs/1605.07146.\n\"\"\"\n\n__all__ = ['CIFARWRN', 'wrn16_10_cifar10', 'wrn16_10_cifar100', 'wrn16_10_svhn', 'wrn28_10_cifar10',\n 'wrn28_10_cifar100', 'wrn28_10_svhn', 'wrn40_8_cifar10', 'wrn40_8_cifar100', 'wrn40_8_svhn']\n\nimport os\nimport torch.nn as nn\nimport torch.nn.init as init\nfrom .common import conv3x3\nfrom .preresnet import PreResUnit, PreResActivation\n\n\nclass CIFARWRN(nn.Module):\n \"\"\"\n WRN model for CIFAR from 'Wide Residual Networks,' https://arxiv.org/abs/1605.07146.\n\n Parameters:\n ----------\n channels : list of list of int\n Number of output channels for each unit.\n init_block_channels : int\n Number of output channels for the initial unit.\n in_channels : int, default 3\n Number of input channels.\n in_size : tuple of two ints, default (32, 32)\n Spatial size of the expected input image.\n num_classes : int, default 10\n Number of classification classes.\n \"\"\"\n def __init__(self,\n channels,\n init_block_channels,\n in_channels=3,\n in_size=(32, 32),\n num_classes=10):\n super(CIFARWRN, self).__init__()\n self.in_size = in_size\n self.num_classes = num_classes\n\n self.features = nn.Sequential()\n self.features.add_module(\"init_block\", conv3x3(\n in_channels=in_channels,\n out_channels=init_block_channels))\n in_channels = init_block_channels\n for i, channels_per_stage in enumerate(channels):\n stage = nn.Sequential()\n for j, out_channels in enumerate(channels_per_stage):\n stride = 2 if (j == 0) and (i != 0) else 1\n stage.add_module(\"unit{}\".format(j + 1), PreResUnit(\n in_channels=in_channels,\n out_channels=out_channels,\n stride=stride,\n bottleneck=False,\n conv1_stride=False))\n in_channels = out_channels\n self.features.add_module(\"stage{}\".format(i + 1), stage)\n self.features.add_module(\"post_activ\", PreResActivation(in_channels=in_channels))\n self.features.add_module(\"final_pool\", nn.AvgPool2d(\n kernel_size=8,\n stride=1))\n\n self.output = nn.Linear(\n in_features=in_channels,\n out_features=num_classes)\n\n self._init_params()\n\n def _init_params(self):\n for name, module in self.named_modules():\n if isinstance(module, nn.Conv2d):\n init.kaiming_uniform_(module.weight)\n if module.bias is not None:\n init.constant_(module.bias, 0)\n\n def forward(self, x):\n x = self.features(x)\n x = x.view(x.size(0), -1)\n x = self.output(x)\n return x\n\n\ndef get_wrn_cifar(num_classes,\n blocks,\n width_factor,\n model_name=None,\n pretrained=False,\n root=os.path.join(\"~\", \".torch\", \"models\"),\n **kwargs):\n \"\"\"\n Create WRN model for CIFAR with specific parameters.\n\n Parameters:\n ----------\n num_classes : int\n Number of classification classes.\n blocks : int\n Number of blocks.\n width_factor : int\n Wide scale factor for width of layers.\n model_name : str or None, default None\n Model name for loading pretrained model.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.torch/models'\n Location for keeping the model parameters.\n \"\"\"\n\n assert ((blocks - 4) % 6 == 0)\n layers = [(blocks - 4) // 6] * 3\n channels_per_layers = [16, 32, 64]\n init_block_channels = 16\n\n channels = [[ci * width_factor] * li for (ci, li) in zip(channels_per_layers, layers)]\n\n net = CIFARWRN(\n channels=channels,\n init_block_channels=init_block_channels,\n num_classes=num_classes,\n **kwargs)\n\n if pretrained:\n if (model_name is None) or (not model_name):\n raise ValueError(\"Parameter `model_name` should be properly initialized for loading pretrained model.\")\n from .model_store import download_model\n download_model(\n net=net,\n model_name=model_name,\n local_model_store_dir_path=root)\n\n return net\n\n\ndef wrn16_10_cifar10(num_classes=10, **kwargs):\n \"\"\"\n WRN-16-10 model for CIFAR-10 from 'Wide Residual Networks,' https://arxiv.org/abs/1605.07146.\n\n Parameters:\n ----------\n num_classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.torch/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_wrn_cifar(num_classes=num_classes, blocks=16, width_factor=10, model_name=\"wrn16_10_cifar10\", **kwargs)\n\n\ndef wrn16_10_cifar100(num_classes=100, **kwargs):\n \"\"\"\n WRN-16-10 model for CIFAR-100 from 'Wide Residual Networks,' https://arxiv.org/abs/1605.07146.\n\n Parameters:\n ----------\n num_classes : int, default 100\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.torch/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_wrn_cifar(num_classes=num_classes, blocks=16, width_factor=10, model_name=\"wrn16_10_cifar100\", **kwargs)\n\n\ndef wrn16_10_svhn(num_classes=10, **kwargs):\n \"\"\"\n WRN-16-10 model for SVHN from 'Wide Residual Networks,' https://arxiv.org/abs/1605.07146.\n\n Parameters:\n ----------\n num_classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.torch/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_wrn_cifar(num_classes=num_classes, blocks=16, width_factor=10, model_name=\"wrn16_10_svhn\", **kwargs)\n\n\ndef wrn28_10_cifar10(num_classes=10, **kwargs):\n \"\"\"\n WRN-28-10 model for CIFAR-10 from 'Wide Residual Networks,' https://arxiv.org/abs/1605.07146.\n\n Parameters:\n ----------\n num_classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.torch/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_wrn_cifar(num_classes=num_classes, blocks=28, width_factor=10, model_name=\"wrn28_10_cifar10\", **kwargs)\n\n\ndef wrn28_10_cifar100(num_classes=100, **kwargs):\n \"\"\"\n WRN-28-10 model for CIFAR-100 from 'Wide Residual Networks,' https://arxiv.org/abs/1605.07146.\n\n Parameters:\n ----------\n num_classes : int, default 100\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.torch/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_wrn_cifar(num_classes=num_classes, blocks=28, width_factor=10, model_name=\"wrn28_10_cifar100\", **kwargs)\n\n\ndef wrn28_10_svhn(num_classes=10, **kwargs):\n \"\"\"\n WRN-28-10 model for SVHN from 'Wide Residual Networks,' https://arxiv.org/abs/1605.07146.\n\n Parameters:\n ----------\n num_classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.torch/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_wrn_cifar(num_classes=num_classes, blocks=28, width_factor=10, model_name=\"wrn28_10_svhn\", **kwargs)\n\n\ndef wrn40_8_cifar10(num_classes=10, **kwargs):\n \"\"\"\n WRN-40-8 model for CIFAR-10 from 'Wide Residual Networks,' https://arxiv.org/abs/1605.07146.\n\n Parameters:\n ----------\n num_classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.torch/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_wrn_cifar(num_classes=num_classes, blocks=40, width_factor=8, model_name=\"wrn40_8_cifar10\", **kwargs)\n\n\ndef wrn40_8_cifar100(num_classes=100, **kwargs):\n \"\"\"\n WRN-40-8 model for CIFAR-100 from 'Wide Residual Networks,' https://arxiv.org/abs/1605.07146.\n\n Parameters:\n ----------\n num_classes : int, default 100\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.torch/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_wrn_cifar(num_classes=num_classes, blocks=40, width_factor=8, model_name=\"wrn40_8_cifar100\", **kwargs)\n\n\ndef wrn40_8_svhn(num_classes=10, **kwargs):\n \"\"\"\n WRN-40-8 model for SVHN from 'Wide Residual Networks,' https://arxiv.org/abs/1605.07146.\n\n Parameters:\n ----------\n num_classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.torch/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_wrn_cifar(num_classes=num_classes, blocks=40, width_factor=8, model_name=\"wrn40_8_svhn\", **kwargs)\n\n\ndef _calc_width(net):\n import numpy as np\n net_params = filter(lambda p: p.requires_grad, net.parameters())\n weight_count = 0\n for param in net_params:\n weight_count += np.prod(param.size())\n return weight_count\n\n\ndef _test():\n import torch\n\n pretrained = False\n\n models = [\n (wrn16_10_cifar10, 10),\n (wrn16_10_cifar100, 100),\n (wrn16_10_svhn, 10),\n (wrn28_10_cifar10, 10),\n (wrn28_10_cifar100, 100),\n (wrn28_10_svhn, 10),\n (wrn40_8_cifar10, 10),\n (wrn40_8_cifar100, 100),\n (wrn40_8_svhn, 10),\n ]\n\n for model, num_classes in models:\n\n net = model(pretrained=pretrained)\n\n # net.train()\n net.eval()\n weight_count = _calc_width(net)\n print(\"m={}, {}\".format(model.__name__, weight_count))\n assert (model != wrn16_10_cifar10 or weight_count == 17116634)\n assert (model != wrn16_10_cifar100 or weight_count == 17174324)\n assert (model != wrn16_10_svhn or weight_count == 17116634)\n assert (model != wrn28_10_cifar10 or weight_count == 36479194)\n assert (model != wrn28_10_cifar100 or weight_count == 36536884)\n assert (model != wrn28_10_svhn or weight_count == 36479194)\n assert (model != wrn40_8_cifar10 or weight_count == 35748314)\n assert (model != wrn40_8_cifar100 or weight_count == 35794484)\n assert (model != wrn40_8_svhn or weight_count == 35748314)\n\n x = torch.randn(1, 3, 32, 32)\n y = net(x)\n y.sum().backward()\n assert (tuple(y.size()) == (1, num_classes))\n\n\nif __name__ == \"__main__\":\n _test()\n",
"\"\"\"\n Model store which provides pretrained models.\n\"\"\"\n\n__all__ = ['get_model_file', 'load_state_dict', 'download_state_dict', 'init_variables_from_state_dict']\n\nimport os\nimport zipfile\nimport logging\nimport hashlib\n\n_model_sha1 = {name: (error, checksum, repo_release_tag) for name, error, checksum, repo_release_tag in [\n ('alexnet', '1788', 'd3cd2a5a7dfb882c47153b5abffc2edfe8335838', 'v0.0.394'),\n ('alexnetb', '1853', '58a51cd1803929c52eed6e1c69a43328fcc1d1cb', 'v0.0.384'),\n ('zfnet', '1715', 'a18747efbec5ce849244a540651228e287d13296', 'v0.0.395'),\n ('zfnetb', '1482', '2624da317b57bec7d3ce73e7548caa6eca0a6ad6', 'v0.0.400'),\n ('vgg11', '1015', 'b87e9dbcbab308f671a69ef3ed67067e62c5429f', 'v0.0.381'),\n ('vgg13', '0946', 'f1411e1fdd5e75919d4e1a0f7b33ac06e0acb146', 'v0.0.388'),\n ('vgg16', '0830', 'e63ead2e896e1a5185840b8cc0973d0791b19d35', 'v0.0.401'),\n ('vgg19', '0768', 'cf2a33c6221e44432f38dd8bdcf1312efd208ae8', 'v0.0.420'),\n ('bn_vgg11', '0936', '4ff8667b2daba34bb4531744a50c000543e4e524', 'v0.0.339'),\n ('bn_vgg13', '0888', '0a49f8714fa647684940feb6cffb0a468290a5af', 'v0.0.353'),\n ('bn_vgg16', '0755', '9948c82dcb133081796d095ebd5cf8815d77f7d1', 'v0.0.359'),\n ('bn_vgg19', '0689', '8a3197c6a27aa4a271e31610ff6cc58c6b593a81', 'v0.0.360'),\n ('bn_vgg11b', '0979', '6a3890a42d0b7bab962582298ddaf6077eedf22d', 'v0.0.407'),\n ('bn_vgg13b', '1015', '999e47a6a5d4cb493d1af3e31de04d67d25176e8', 'v0.0.123'),\n ('bn_vgg16b', '0866', '1f8251aa987151e89a82f0f209c2a8bbde0f0c47', 'v0.0.123'),\n ('bn_vgg19b', '0817', '784e4c396e6de685727bc8fd30f5ed35c66a84a0', 'v0.0.123'),\n ('resnet10', '1390', '7fff13aee28ba7601c155907be64aff344530736', 'v0.0.248'),\n ('resnet12', '1300', '9539494f8fae66c454efed4e5abf26c273d3b285', 'v0.0.253'),\n ('resnet14', '1225', 'd1fb0f762258c9fd04a3ad469462f732333740fa', 'v0.0.256'),\n ('resnetbc14b', '1121', '45f5a6d8fd228863e13c89cb49c5101026e975c1', 'v0.0.309'),\n ('resnet16', '1086', '5ac8e7da9dcee268db9b7cf4ecfeceb8efca3005', 'v0.0.259'),\n ('resnet18_wd4', '1741', '4aafd009648dd6fc65b853361eb5e6b292246665', 'v0.0.262'),\n ('resnet18_wd2', '1287', 'dac8e632d3b5585897739d9b00833b1f953540ba', 'v0.0.263'),\n ('resnet18_w3d4', '1069', 'd22e6604e94940dfb948110bd32435e3c5d7ed1f', 'v0.0.266'),\n ('resnet18', '0956', 'b4fc7198d9bbcf6699b904824c839943871401bc', 'v0.0.153'),\n ('resnet26', '0838', 'f647811d7211d82344419b1590fb3ae73433efa7', 'v0.0.305'),\n ('resnetbc26b', '0757', '55c88013263af95b0d391069e34542a5d899cc7d', 'v0.0.313'),\n ('resnet34', '0742', '8faa0ab2cbb8ff4ad3bb62aa82da3dd1eb3ef05d', 'v0.0.291'),\n ('resnetbc38b', '0673', '324ac8fecba27d321703b8b51d988c212ef12d74', 'v0.0.328'),\n ('resnet50', '0605', '34177a2e963820ae5ee9c7b2bd233a2566928774', 'v0.0.329'),\n ('resnet50b', '0609', '4b68417369140303594ae69d5ac5891e9fe91267', 'v0.0.308'),\n ('resnet101', '0601', '3fc260bc67ab133b39f087862f5bc70cf6aa9442', 'v0.0.72'),\n ('resnet101b', '0507', '527dca370eb8a2a4a25025993f8ccce35b00c9ef', 'v0.0.357'),\n ('resnet152', '0535', 'b21844fcaea4e14a91fa17bfa870a3d056d258ea', 'v0.0.144'),\n ('resnet152b', '0485', '36964f4867125dd08fa722d4d639273d7d1874e1', 'v0.0.378'),\n ('preresnet10', '1401', '3a2eed3b9254d35ba546c9894cf9cc3c6d88aa5c', 'v0.0.249'),\n ('preresnet12', '1321', '0c424c407bd91c5135ec74660b5f001f07cec0df', 'v0.0.257'),\n ('preresnet14', '1216', 'fda0747fd40cad58e46dad53e68d3d06b8829829', 'v0.0.260'),\n ('preresnetbc14b', '1153', '00da991cf20381003795507a2e83b370adc71f01', 'v0.0.315'),\n ('preresnet16', '1082', '865af98bca8eee4b2d252500a79192e5204673d6', 'v0.0.261'),\n ('preresnet18_wd4', '1776', '82bea5e8928d6834a5dad19a6f7b6f30d492b992', 'v0.0.272'),\n ('preresnet18_wd2', '1318', '44f39f417fb5b5124fbb115509e3eeeb19844b1a', 'v0.0.273'),\n ('preresnet18_w3d4', '1071', '380470ee6733f47898da19916be9ab05a5ccf243', 'v0.0.274'),\n ('preresnet18', '0949', '692e6c11e738c11eaf818d60a214e7a905a873c1', 'v0.0.140'),\n ('preresnet26', '0833', '8de37e08f3c2dd054a1dc4099d4b398097999af6', 'v0.0.316'),\n ('preresnetbc26b', '0789', '993dd84a36d8f1417e2f5454ec5f3b3159f251c1', 'v0.0.325'),\n ('preresnet34', '0754', '9d5635846928420d41f7304e02a4d33160af45e7', 'v0.0.300'),\n ('preresnetbc38b', '0634', 'f22aa1c3b9f67717ecb5cb94256be8f2ee57d9c6', 'v0.0.348'),\n ('preresnet50', '0625', '06130b124a1abf96cc92f7d212ca9b524da02ddd', 'v0.0.330'),\n ('preresnet50b', '0631', '9fc00073139d763ef08e2fc810c2469c9b0182c9', 'v0.0.307'),\n ('preresnet101', '0572', 'cd61594e9e2fb758ca69a38baf31223351638c4f', 'v0.0.73'),\n ('preresnet101b', '0539', 'c0b9e129908051592393ba5e7939a4feb5b82b6c', 'v0.0.351'),\n ('preresnet152', '0529', 'b761f286ab284b916f388cc5d6af00e5ea049081', 'v0.0.73'),\n ('preresnet152b', '0500', '7ae9df4bbabbc12d32a35f4369d64269ba3c8e7b', 'v0.0.386'),\n ('preresnet200b', '0560', '881e0e2869428d89831bde0c7da219ed69236f16', 'v0.0.73'),\n ('preresnet269b', '0555', 'c799eaf246d3dccf72ac10cdec3f35bd8bf72e71', 'v0.0.239'),\n ('resnext14_16x4d', '1224', '3f603dde73c4581f60ada40499ed42d800847268', 'v0.0.370'),\n ('resnext14_32x2d', '1246', 'df7d6b8a824796742a0bb369d654135cd109dfb3', 'v0.0.371'),\n ('resnext14_32x4d', '1113', 'cac0dad52d391f9268c9fee6f95be59e14952fcc', 'v0.0.327'),\n ('resnext26_32x2d', '0849', '2dee5d79b8f093f1f6d1cf87b7f36e0481c6648f', 'v0.0.373'),\n ('resnext26_32x4d', '0717', '594567d27cea1f5e324a6ecfd93f209d30c148d9', 'v0.0.332'),\n ('resnext50_32x4d', '0546', 'c0817d9b70b46f067d4dc5c915e6cbdc3dd820af', 'v0.0.417'),\n ('resnext101_32x4d', '0493', 'de52ea63f204c839c176f6162ae73a19a33626c4', 'v0.0.417'),\n ('resnext101_64x4d', '0485', 'ddff97a9e6aa2ccd603a067c2158044cec8b8342', 'v0.0.417'),\n ('seresnet10', '1336', 'd4a0a9d3e2e2b4188aac06d3b6cc4132f05ac916', 'v0.0.354'),\n ('seresnet18', '0923', '7aa519d2ec4c721c61a9fd04a9b0ca745f12b24a', 'v0.0.355'),\n ('seresnet26', '0809', 'b2a8b74fe11edbfa798c35d882d6ebd5cfceb6ff', 'v0.0.363'),\n ('seresnetbc26b', '0681', '692ccde37b4dc19df0bc5b92256f0023228baf98', 'v0.0.366'),\n ('seresnetbc38b', '0578', '2d787dc45bd6775fa96b4048ab5ac191089a0ab0', 'v0.0.374'),\n ('seresnet50', '0643', 'e022e5b9e58e19c692d00394c85daa57ea943b82', 'v0.0.75'),\n ('seresnet50b', '0533', '539e58be15125cf7693cc6318d99592a2f956d48', 'v0.0.387'),\n ('seresnet101', '0589', '305d23018de942b25df59d8ac9d2dd14374d7d28', 'v0.0.75'),\n ('seresnet152', '0578', 'd06ab6d909129693da68c552b91f3f344795114f', 'v0.0.75'),\n ('sepreresnet10', '1309', 'b0162a2e1219911d8c386ba0fef741ab5b112940', 'v0.0.377'),\n ('sepreresnet18', '0941', '5606cb354b61974a97ae81807194638fc3ea0576', 'v0.0.380'),\n ('sepreresnetbc26b', '0634', 'd903397d7afafbf43b5c19da927601a128cafd0b', 'v0.0.399'),\n ('sepreresnetbc38b', '0564', '262a4a2e23d34ab244b107fe8397e776744e4fcb', 'v0.0.409'),\n ('seresnext50_32x4d', '0507', '982a4cb8190a4e7bb21d4582336c13d8363c4ece', 'v0.0.418'),\n ('seresnext101_32x4d', '0461', 'b84ec20adb9d67f56ac4cd6eb35b134f964c1936', 'v0.0.418'),\n ('seresnext101_64x4d', '0465', 'b16029e686fb50fd64ed59df22c9d3c5ed0470c1', 'v0.0.418'),\n ('senet16', '0803', '366c58ce2f47ded548734cf336d46b50517c78c4', 'v0.0.341'),\n ('senet28', '0594', '98ba8cc2068495fe192af40328f1838b1e835b6f', 'v0.0.356'),\n ('senet154', '0463', 'c86eaaed79c696a32ace4a8576fc0b50f0f93900', 'v0.0.86'),\n ('densenet121', '0688', 'e3bccdc5544f46352bb91671ac4cd7e2f788952b', 'v0.0.314'),\n ('densenet161', '0617', '9deca33a34a5c4a0a84f0a37920dbfd1cad85cb7', 'v0.0.77'),\n ('densenet169', '0606', 'fcbb5c869350e22cc79b15a0508f2f5598dacb90', 'v0.0.406'),\n ('densenet201', '0635', '5eda789595ba0b8b450705220704687fa8ea8788', 'v0.0.77'),\n ('darknet_tiny', '1751', '750ff8d9b17beb5ab88200aa787dfcb5b6ca8b36', 'v0.0.71'),\n ('darknet_ref', '1672', '3c8ed62a43b9e8934b4beb7c47ce4c7b2cdb7a64', 'v0.0.71'),\n ('darknet53', '0555', '49816dbf617b2cd14051c2d7cd0325ee3ebb63a2', 'v0.0.150'),\n ('squeezenet_v1_0', '1758', 'fc6384ff0f1294079721c28aef47ffa77265dc77', 'v0.0.128'),\n ('squeezenet_v1_1', '1739', '489455774b03affca336326665a031c380fd0068', 'v0.0.88'),\n ('squeezeresnet_v1_0', '1782', 'bafdf6ae72b2be228cc2d6d908c295891fd29c02', 'v0.0.178'),\n ('squeezeresnet_v1_1', '1792', '44c1792845488013cb3b9286c9cb7f868d590ab9', 'v0.0.79'),\n ('sqnxt23_w1', '2108', '6267020032ac7d6aa0905b916954864cdfea4934', 'v0.0.171'),\n ('sqnxt23v5_w1', '2077', 'ebc0c53dc0c39e72eb620b06c2eb07ba451fb28d', 'v0.0.172'),\n ('sqnxt23_w3d2', '1509', '8fbdcd6dde6a3fb2f8e8aab4d1eb828123becfb5', 'v0.0.210'),\n ('sqnxt23v5_w3d2', '1539', 'ae14d7b8685b23fcffeba96038e31255a7c718fa', 'v0.0.212'),\n ('sqnxt23_w2', '1235', 'ea1ae9b747fb40f670b32fad28844fdc2af5ea66', 'v0.0.240'),\n ('sqnxt23v5_w2', '1213', 'd12c9b338ec5a374a3e22fc9a48146197fa82ac6', 'v0.0.216'),\n ('shufflenet_g1_wd4', '3680', '3d9856357041fb69f4a6ddf0208e7821605487a9', 'v0.0.134'),\n ('shufflenet_g3_wd4', '3617', '8f00e642cfc2b7ab8b1a770513bb46190c3bcb7d', 'v0.0.135'),\n ('shufflenet_g1_wd2', '2231', 'd5356e3b04c4a30d568755807e996821098d8aae', 'v0.0.174'),\n ('shufflenet_g3_wd2', '2063', 'db302789f57d82520c13f4d0c39796801c3458b7', 'v0.0.167'),\n ('shufflenet_g1_w3d4', '1678', 'ca175843c5d78bf7d6c826142df810b1b721978b', 'v0.0.218'),\n ('shufflenet_g3_w3d4', '1613', 'f7a106be40b1cdcc68e1cf185451832aec3584fc', 'v0.0.219'),\n ('shufflenet_g1_w1', '1351', '2f36fdbc45ef00b49dd558b3b2e5b238be2e28ca', 'v0.0.223'),\n ('shufflenet_g2_w1', '1333', '24d32ea2da9d195f42c97b2c390b57ee1a9dbbd4', 'v0.0.241'),\n ('shufflenet_g3_w1', '1332', 'cc1781c4fa3bd9cf6b281e28d2c4532b502f9721', 'v0.0.244'),\n ('shufflenet_g4_w1', '1313', '25dd6c890e5f3de4a30f7ef13c3060eb8c0a4ba8', 'v0.0.245'),\n ('shufflenet_g8_w1', '1321', '854a60f45e6e0bbb1e7bd4664c13f1a3edc37e8f', 'v0.0.250'),\n ('shufflenetv2_wd2', '1844', '2bd8a314d4c21fb70496a9b263eea3bfe2cc39d4', 'v0.0.90'),\n ('shufflenetv2_w1', '1131', '6a728e21f405d52b0deade6878f4661089b47a51', 'v0.0.133'),\n ('shufflenetv2_w3d2', '0923', '6b8c6c3c93b578f57892feac309a91634a22b7dd', 'v0.0.288'),\n ('shufflenetv2_w2', '0821', '274b770f049c483f4bfedabe1692f2941c69393e', 'v0.0.301'),\n ('shufflenetv2b_wd2', '1784', 'fd5df5a33ba7a8940b2732f2f464522283438165', 'v0.0.158'),\n ('shufflenetv2b_w1', '1104', '6df32bad4c38e603dd75c89ba39c25d45162ab43', 'v0.0.161'),\n ('shufflenetv2b_w3d2', '0880', '9ce6d2b779f0f2483ffc8c8396a9c22af0ea712b', 'v0.0.203'),\n ('shufflenetv2b_w2', '0810', '164690eda8bf24de2f2835250646b8164b9de1dc', 'v0.0.242'),\n ('menet108_8x1_g3', '2032', '4e9e89e10f7bc055c83bbbb0e9f283f983546288', 'v0.0.89'),\n ('menet128_8x1_g4', '1915', '148105f444f44137b3df2d50ef63d811a9d1da82', 'v0.0.103'),\n ('menet160_8x1_g8', '2028', '7ff635d185d0228f147dc32c225da85c99763e9b', 'v0.0.154'),\n ('menet228_12x1_g3', '1292', 'e594e8bbce43babc8a527a330b245d0cfbf2f7d0', 'v0.0.131'),\n ('menet256_12x1_g4', '1219', '25b42dc0c636883ebd83116b59a871ba92c1c4e2', 'v0.0.152'),\n ('menet348_12x1_g3', '0935', 'bd4f050285cf4220db457266bbce395fab566f33', 'v0.0.173'),\n ('menet352_12x1_g8', '1169', 'c983d04f3f003b8bf9d86b034c980f0d393b5598', 'v0.0.198'),\n ('menet456_24x1_g3', '0779', 'adc7145f56e6f21eee3c84ae2549f5c2bf95f4cc', 'v0.0.237'),\n ('mobilenet_wd4', '2221', '15ee9820a315d20c732c085a4cd1edd0e3c0658a', 'v0.0.80'),\n ('mobilenet_wd2', '1331', '4c5b66f19994fc8ef85c1a65389bddc53ad114f2', 'v0.0.156'),\n ('mobilenet_w3d4', '1049', '3139bba77f5ae13a635f90c97cddeb803e80eb2c', 'v0.0.130'),\n ('mobilenet_w1', '0867', '83beb02ebb519880bfbd17ebd9cfce854c431d8f', 'v0.0.155'),\n ('fdmobilenet_wd4', '3050', 'e441d7154731e372131a4f5ad4bf9a0236d4a7e5', 'v0.0.177'),\n ('fdmobilenet_wd2', '1970', 'd778e6870a0c064e7f303899573237585e5b7498', 'v0.0.83'),\n ('fdmobilenet_w3d4', '1602', '91d5bf30d66a3982ed6b3e860571117f546dcccd', 'v0.0.159'),\n ('fdmobilenet_w1', '1318', 'da6a9808e4a40940fb2549b0a66fa1288e8a33c5', 'v0.0.162'),\n ('mobilenetv2_wd4', '2416', 'ae7e5137b9b9c01b35f16380afe7e1423541475e', 'v0.0.137'),\n ('mobilenetv2_wd2', '1446', '696501bd3e6df77a78e85756403a3da23839244b', 'v0.0.170'),\n ('mobilenetv2_w3d4', '1044', '0a8633acd058c0ea783796205a0767858939fe31', 'v0.0.230'),\n ('mobilenetv2_w1', '0862', '03daae54f799467152612138da07a8c221666d70', 'v0.0.213'),\n ('igcv3_wd4', '2835', 'b41fb3c75e090cc719962e1ca2debcbac241dc22', 'v0.0.142'),\n ('igcv3_wd2', '1705', 'de0b98d950a3892b6d15d1c3ea248d41a34adf00', 'v0.0.132'),\n ('igcv3_w3d4', '1096', 'b8650159ab15b118c0655002d9ce613b3a36dea1', 'v0.0.207'),\n ('igcv3_w1', '0903', 'a69c216fa5838dba316b01d347846812835650fe', 'v0.0.243'),\n ('mnasnet_b1', '0800', 'a21e7b11537a81d57be61b27761efa69b0b44728', 'v0.0.419'),\n ('mnasnet_a1', '0756', '2903749fb1ac67254487ccf1668cae064170ffd1', 'v0.0.419')]}\n\nimgclsmob_repo_url = 'https://github.com/osmr/imgclsmob'\n\n\ndef get_model_name_suffix_data(model_name):\n if model_name not in _model_sha1:\n raise ValueError(\"Pretrained model for {name} is not available.\".format(name=model_name))\n error, sha1_hash, repo_release_tag = _model_sha1[model_name]\n return error, sha1_hash, repo_release_tag\n\n\ndef get_model_file(model_name,\n local_model_store_dir_path=os.path.join(\"~\", \".tensorflow\", \"models\")):\n \"\"\"\n Return location for the pretrained on local file system. This function will download from online model zoo when\n model cannot be found or has mismatch. The root directory will be created if it doesn't exist.\n\n Parameters:\n ----------\n model_name : str\n Name of the model.\n local_model_store_dir_path : str, default $TENSORFLOW_HOME/models\n Location for keeping the model parameters.\n\n Returns:\n -------\n file_path\n Path to the requested pretrained model file.\n \"\"\"\n error, sha1_hash, repo_release_tag = get_model_name_suffix_data(model_name)\n short_sha1 = sha1_hash[:8]\n file_name = \"{name}-{error}-{short_sha1}.tf.npz\".format(\n name=model_name,\n error=error,\n short_sha1=short_sha1)\n local_model_store_dir_path = os.path.expanduser(local_model_store_dir_path)\n file_path = os.path.join(local_model_store_dir_path, file_name)\n if os.path.exists(file_path):\n if _check_sha1(file_path, sha1_hash):\n return file_path\n else:\n logging.warning(\"Mismatch in the content of model file detected. Downloading again.\")\n else:\n logging.info(\"Model file not found. Downloading to {}.\".format(file_path))\n\n if not os.path.exists(local_model_store_dir_path):\n os.makedirs(local_model_store_dir_path)\n\n zip_file_path = file_path + \".zip\"\n _download(\n url=\"{repo_url}/releases/download/{repo_release_tag}/{file_name}.zip\".format(\n repo_url=imgclsmob_repo_url,\n repo_release_tag=repo_release_tag,\n file_name=file_name),\n path=zip_file_path,\n overwrite=True)\n with zipfile.ZipFile(zip_file_path) as zf:\n zf.extractall(local_model_store_dir_path)\n os.remove(zip_file_path)\n\n if _check_sha1(file_path, sha1_hash):\n return file_path\n else:\n raise ValueError(\"Downloaded file has different hash. Please try again.\")\n\n\ndef _download(url, path=None, overwrite=False, sha1_hash=None, retries=5, verify_ssl=True):\n \"\"\"Download an given URL\n\n Parameters:\n ----------\n url : str\n URL to download\n path : str, optional\n Destination path to store downloaded file. By default stores to the\n current directory with same name as in url.\n overwrite : bool, optional\n Whether to overwrite destination file if already exists.\n sha1_hash : str, optional\n Expected sha1 hash in hexadecimal digits. Will ignore existing file when hash is specified\n but doesn't match.\n retries : integer, default 5\n The number of times to attempt the download in case of failure or non 200 return codes\n verify_ssl : bool, default True\n Verify SSL certificates.\n\n Returns:\n -------\n str\n The file path of the downloaded file.\n \"\"\"\n import warnings\n try:\n import requests\n except ImportError:\n class requests_failed_to_import(object):\n pass\n requests = requests_failed_to_import\n\n if path is None:\n fname = url.split(\"/\")[-1]\n # Empty filenames are invalid\n assert fname, \"Can't construct file-name from this URL. Please set the `path` option manually.\"\n else:\n path = os.path.expanduser(path)\n if os.path.isdir(path):\n fname = os.path.join(path, url.split(\"/\")[-1])\n else:\n fname = path\n assert retries >= 0, \"Number of retries should be at least 0\"\n\n if not verify_ssl:\n warnings.warn(\n \"Unverified HTTPS request is being made (verify_ssl=False). \"\n \"Adding certificate verification is strongly advised.\")\n\n if overwrite or not os.path.exists(fname) or (sha1_hash and not _check_sha1(fname, sha1_hash)):\n dirname = os.path.dirname(os.path.abspath(os.path.expanduser(fname)))\n if not os.path.exists(dirname):\n os.makedirs(dirname)\n while retries + 1 > 0:\n # Disable pyling too broad Exception\n # pylint: disable=W0703\n try:\n print(\"Downloading {} from {}...\".format(fname, url))\n r = requests.get(url, stream=True, verify=verify_ssl)\n if r.status_code != 200:\n raise RuntimeError(\"Failed downloading url {}\".format(url))\n with open(fname, \"wb\") as f:\n for chunk in r.iter_content(chunk_size=1024):\n if chunk: # filter out keep-alive new chunks\n f.write(chunk)\n if sha1_hash and not _check_sha1(fname, sha1_hash):\n raise UserWarning(\"File {} is downloaded but the content hash does not match.\"\n \" The repo may be outdated or download may be incomplete. \"\n \"If the `repo_url` is overridden, consider switching to \"\n \"the default repo.\".format(fname))\n break\n except Exception as e:\n retries -= 1\n if retries <= 0:\n raise e\n else:\n print(\"download failed, retrying, {} attempt{} left\"\n .format(retries, \"s\" if retries > 1 else \"\"))\n\n return fname\n\n\ndef _check_sha1(filename, sha1_hash):\n \"\"\"Check whether the sha1 hash of the file content matches the expected hash.\n\n Parameters:\n ----------\n filename : str\n Path to the file.\n sha1_hash : str\n Expected sha1 hash in hexadecimal digits.\n\n Returns:\n -------\n bool\n Whether the file content matches the expected hash.\n \"\"\"\n sha1 = hashlib.sha1()\n with open(filename, \"rb\") as f:\n while True:\n data = f.read(1048576)\n if not data:\n break\n sha1.update(data)\n\n return sha1.hexdigest() == sha1_hash\n\n\ndef load_state_dict(file_path):\n \"\"\"\n Load model state dictionary from a file.\n\n Parameters:\n ----------\n file_path : str\n Path to the file.\n\n Returns:\n -------\n state_dict : dict\n Dictionary with values of model variables.\n \"\"\"\n import numpy as np\n assert os.path.exists(file_path) and os.path.isfile(file_path)\n if file_path.endswith(\".npy\"):\n state_dict = np.load(file_path, encoding=\"latin1\").item()\n elif file_path.endswith(\".npz\"):\n state_dict = dict(np.load(file_path))\n else:\n raise NotImplementedError\n return state_dict\n\n\ndef download_state_dict(model_name,\n local_model_store_dir_path=os.path.join(\"~\", \".tensorflow\", \"models\")):\n \"\"\"\n Load model state dictionary from a file with downloading it if necessary.\n\n Parameters:\n ----------\n model_name : str\n Name of the model.\n local_model_store_dir_path : str, default $TENSORFLOW_HOME/models\n Location for keeping the model parameters.\n\n Returns:\n -------\n state_dict : dict\n Dictionary with values of model variables.\n file_path : str\n Path to the file.\n \"\"\"\n file_path = get_model_file(\n model_name=model_name,\n local_model_store_dir_path=local_model_store_dir_path)\n state_dict = load_state_dict(file_path=file_path)\n return state_dict, file_path\n\n\ndef init_variables_from_state_dict(sess,\n state_dict,\n ignore_extra=True):\n \"\"\"\n Initialize model variables from state dictionary.\n\n Parameters:\n ----------\n sess: Session\n A Session to use to load the weights.\n state_dict : dict\n Dictionary with values of model variables.\n ignore_extra : bool, default True\n Whether to silently ignore parameters from the file that are not present in this Module.\n \"\"\"\n import tensorflow as tf\n assert sess is not None\n if state_dict is None:\n raise Exception(\"The state dict is empty\")\n dst_params = {v.name: v for v in tf.global_variables()}\n sess.run(tf.global_variables_initializer())\n for src_key in state_dict.keys():\n if src_key in dst_params.keys():\n assert (state_dict[src_key].shape == tuple(dst_params[src_key].get_shape().as_list()))\n sess.run(dst_params[src_key].assign(state_dict[src_key]))\n elif not ignore_extra:\n raise Exception(\"The state dict is incompatible with the model\")\n else:\n print(\"Key `{}` is ignored\".format(src_key))\n",
"\"\"\"\n Lightweight OpenPose 2D/3D for CMU Panoptic, implemented in Gluon.\n Original paper: 'Real-time 2D Multi-Person Pose Estimation on CPU: Lightweight OpenPose,'\n https://arxiv.org/abs/1811.12004.\n\"\"\"\n\n__all__ = ['LwOpenPose', 'lwopenpose2d_mobilenet_cmupan_coco', 'lwopenpose3d_mobilenet_cmupan_coco',\n 'LwopDecoderFinalBlock']\n\nimport os\nfrom mxnet import cpu\nfrom mxnet.gluon import nn, HybridBlock\nfrom .common import conv1x1, conv1x1_block, conv3x3_block, dwsconv3x3_block\n\n\nclass LwopResBottleneck(HybridBlock):\n \"\"\"\n Bottleneck block for residual path in the residual unit.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n strides : int or tuple/list of 2 int\n Strides of the convolution.\n use_bias : bool, default True\n Whether the layer uses a bias vector.\n bn_use_global_stats : bool, default False\n Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.\n bottleneck_factor : int, default 2\n Bottleneck factor.\n squeeze_out : bool, default False\n Whether to squeeze the output channels.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels,\n strides,\n use_bias=True,\n bn_use_global_stats=False,\n bottleneck_factor=2,\n squeeze_out=False,\n **kwargs):\n super(LwopResBottleneck, self).__init__(**kwargs)\n mid_channels = out_channels // bottleneck_factor if squeeze_out else in_channels // bottleneck_factor\n\n with self.name_scope():\n self.conv1 = conv1x1_block(\n in_channels=in_channels,\n out_channels=mid_channels,\n use_bias=use_bias,\n bn_use_global_stats=bn_use_global_stats)\n self.conv2 = conv3x3_block(\n in_channels=mid_channels,\n out_channels=mid_channels,\n strides=strides,\n use_bias=use_bias,\n bn_use_global_stats=bn_use_global_stats)\n self.conv3 = conv1x1_block(\n in_channels=mid_channels,\n out_channels=out_channels,\n use_bias=use_bias,\n activation=None,\n bn_use_global_stats=bn_use_global_stats)\n\n def hybrid_forward(self, F, x):\n x = self.conv1(x)\n x = self.conv2(x)\n x = self.conv3(x)\n return x\n\n\nclass LwopResUnit(HybridBlock):\n \"\"\"\n ResNet-like residual unit with residual connection.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n strides : int or tuple/list of 2 int, default 1\n Strides of the convolution.\n use_bias : bool, default True\n Whether the layer uses a bias vector.\n bn_use_global_stats : bool, default False\n Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.\n bottleneck_factor : int, default 2\n Bottleneck factor.\n squeeze_out : bool, default False\n Whether to squeeze the output channels.\n activate : bool, default False\n Whether to activate the sum.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels,\n strides=1,\n use_bias=True,\n bn_use_global_stats=False,\n bottleneck_factor=2,\n squeeze_out=False,\n activate=False,\n **kwargs):\n super(LwopResUnit, self).__init__(**kwargs)\n self.activate = activate\n self.resize_identity = (in_channels != out_channels) or (strides != 1)\n\n with self.name_scope():\n self.body = LwopResBottleneck(\n in_channels=in_channels,\n out_channels=out_channels,\n strides=strides,\n use_bias=use_bias,\n bn_use_global_stats=bn_use_global_stats,\n bottleneck_factor=bottleneck_factor,\n squeeze_out=squeeze_out)\n if self.resize_identity:\n self.identity_conv = conv1x1_block(\n in_channels=in_channels,\n out_channels=out_channels,\n strides=strides,\n use_bias=use_bias,\n bn_use_global_stats=bn_use_global_stats,\n activation=None)\n if self.activate:\n self.activ = nn.Activation(\"relu\")\n\n def hybrid_forward(self, F, x):\n if self.resize_identity:\n identity = self.identity_conv(x)\n else:\n identity = x\n x = self.body(x)\n x = x + identity\n if self.activate:\n x = self.activ(x)\n return x\n\n\nclass LwopEncoderFinalBlock(HybridBlock):\n \"\"\"\n Lightweight OpenPose 2D/3D specific encoder final block.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n bn_use_global_stats : bool, default False\n Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels,\n bn_use_global_stats=False,\n **kwargs):\n super(LwopEncoderFinalBlock, self).__init__(**kwargs)\n with self.name_scope():\n self.pre_conv = conv1x1_block(\n in_channels=in_channels,\n out_channels=out_channels,\n use_bias=True,\n use_bn=False,\n bn_use_global_stats=bn_use_global_stats)\n self.body = nn.HybridSequential(prefix=\"\")\n for i in range(3):\n self.body.add(dwsconv3x3_block(\n in_channels=out_channels,\n out_channels=out_channels,\n dw_use_bn=False,\n pw_use_bn=False,\n bn_use_global_stats=bn_use_global_stats,\n dw_activation=(lambda: nn.ELU()),\n pw_activation=(lambda: nn.ELU())))\n self.post_conv = conv3x3_block(\n in_channels=out_channels,\n out_channels=out_channels,\n use_bias=True,\n use_bn=False,\n bn_use_global_stats=bn_use_global_stats)\n\n def hybrid_forward(self, F, x):\n x = self.pre_conv(x)\n x = x + self.body(x)\n x = self.post_conv(x)\n return x\n\n\nclass LwopRefinementBlock(HybridBlock):\n \"\"\"\n Lightweight OpenPose 2D/3D specific refinement block for decoder units.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n bn_use_global_stats : bool, default False\n Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels,\n bn_use_global_stats=False,\n **kwargs):\n super(LwopRefinementBlock, self).__init__(**kwargs)\n with self.name_scope():\n self.pre_conv = conv1x1_block(\n in_channels=in_channels,\n out_channels=out_channels,\n use_bias=True,\n use_bn=False,\n bn_use_global_stats=bn_use_global_stats)\n self.body = nn.HybridSequential(prefix=\"\")\n self.body.add(conv3x3_block(\n in_channels=out_channels,\n out_channels=out_channels,\n use_bias=True,\n bn_use_global_stats=bn_use_global_stats))\n self.body.add(conv3x3_block(\n in_channels=out_channels,\n out_channels=out_channels,\n padding=2,\n dilation=2,\n use_bias=True,\n bn_use_global_stats=bn_use_global_stats))\n\n def hybrid_forward(self, F, x):\n x = self.pre_conv(x)\n x = x + self.body(x)\n return x\n\n\nclass LwopDecoderBend(HybridBlock):\n \"\"\"\n Lightweight OpenPose 2D/3D specific decoder bend block.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n mid_channels : int\n Number of middle channels.\n out_channels : int\n Number of output channels.\n bn_use_global_stats : bool, default False\n Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.\n \"\"\"\n def __init__(self,\n in_channels,\n mid_channels,\n out_channels,\n bn_use_global_stats=False,\n **kwargs):\n super(LwopDecoderBend, self).__init__(**kwargs)\n with self.name_scope():\n self.conv1 = conv1x1_block(\n in_channels=in_channels,\n out_channels=mid_channels,\n use_bias=True,\n use_bn=False,\n bn_use_global_stats=bn_use_global_stats)\n self.conv2 = conv1x1(\n in_channels=mid_channels,\n out_channels=out_channels,\n use_bias=True)\n\n def hybrid_forward(self, F, x):\n x = self.conv1(x)\n x = self.conv2(x)\n return x\n\n\nclass LwopDecoderInitBlock(HybridBlock):\n \"\"\"\n Lightweight OpenPose 2D/3D specific decoder init block.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n keypoints : int\n Number of keypoints.\n bn_use_global_stats : bool, default False\n Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.\n \"\"\"\n def __init__(self,\n in_channels,\n keypoints,\n bn_use_global_stats=False,\n **kwargs):\n super(LwopDecoderInitBlock, self).__init__(**kwargs)\n num_heatmap = keypoints\n num_paf = 2 * keypoints\n bend_mid_channels = 512\n\n with self.name_scope():\n self.body = nn.HybridSequential(prefix=\"\")\n for i in range(3):\n self.body.add(conv3x3_block(\n in_channels=in_channels,\n out_channels=in_channels,\n use_bias=True,\n use_bn=False,\n bn_use_global_stats=bn_use_global_stats))\n self.heatmap_bend = LwopDecoderBend(\n in_channels=in_channels,\n mid_channels=bend_mid_channels,\n out_channels=num_heatmap,\n bn_use_global_stats=bn_use_global_stats)\n self.paf_bend = LwopDecoderBend(\n in_channels=in_channels,\n mid_channels=bend_mid_channels,\n out_channels=num_paf,\n bn_use_global_stats=bn_use_global_stats)\n\n def hybrid_forward(self, F, x):\n y = self.body(x)\n heatmap = self.heatmap_bend(y)\n paf = self.paf_bend(y)\n y = F.concat(x, heatmap, paf, dim=1)\n return y\n\n\nclass LwopDecoderUnit(HybridBlock):\n \"\"\"\n Lightweight OpenPose 2D/3D specific decoder init.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n keypoints : int\n Number of keypoints.\n bn_use_global_stats : bool, default False\n Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.\n \"\"\"\n def __init__(self,\n in_channels,\n keypoints,\n bn_use_global_stats=False,\n **kwargs):\n super(LwopDecoderUnit, self).__init__(**kwargs)\n num_heatmap = keypoints\n num_paf = 2 * keypoints\n self.features_channels = in_channels - num_heatmap - num_paf\n\n with self.name_scope():\n self.body = nn.HybridSequential(prefix=\"\")\n for i in range(5):\n self.body.add(LwopRefinementBlock(\n in_channels=in_channels,\n out_channels=self.features_channels,\n bn_use_global_stats=bn_use_global_stats))\n in_channels = self.features_channels\n self.heatmap_bend = LwopDecoderBend(\n in_channels=self.features_channels,\n mid_channels=self.features_channels,\n out_channels=num_heatmap,\n bn_use_global_stats=bn_use_global_stats)\n self.paf_bend = LwopDecoderBend(\n in_channels=self.features_channels,\n mid_channels=self.features_channels,\n out_channels=num_paf,\n bn_use_global_stats=bn_use_global_stats)\n\n def hybrid_forward(self, F, x):\n features = F.slice_axis(x, axis=1, begin=0, end=self.features_channels)\n y = self.body(x)\n heatmap = self.heatmap_bend(y)\n paf = self.paf_bend(y)\n y = F.concat(features, heatmap, paf, dim=1)\n return y\n\n\nclass LwopDecoderFeaturesBend(HybridBlock):\n \"\"\"\n Lightweight OpenPose 2D/3D specific decoder 3D features bend.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n mid_channels : int\n Number of middle channels.\n out_channels : int\n Number of output channels.\n bn_use_global_stats : bool, default False\n Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.\n \"\"\"\n def __init__(self,\n in_channels,\n mid_channels,\n out_channels,\n bn_use_global_stats=False,\n **kwargs):\n super(LwopDecoderFeaturesBend, self).__init__(**kwargs)\n with self.name_scope():\n self.body = nn.HybridSequential(prefix=\"\")\n for i in range(2):\n self.body.add(LwopRefinementBlock(\n in_channels=in_channels,\n out_channels=mid_channels,\n bn_use_global_stats=bn_use_global_stats))\n in_channels = mid_channels\n self.features_bend = LwopDecoderBend(\n in_channels=mid_channels,\n mid_channels=mid_channels,\n out_channels=out_channels,\n bn_use_global_stats=bn_use_global_stats)\n\n def hybrid_forward(self, F, x):\n x = self.body(x)\n x = self.features_bend(x)\n return x\n\n\nclass LwopDecoderFinalBlock(HybridBlock):\n \"\"\"\n Lightweight OpenPose 2D/3D specific decoder final block for calcualation 3D poses.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n keypoints : int\n Number of keypoints.\n bottleneck_factor : int\n Bottleneck factor.\n calc_3d_features : bool\n Whether to calculate 3D features.\n bn_use_global_stats : bool, default False\n Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.\n \"\"\"\n def __init__(self,\n in_channels,\n keypoints,\n bottleneck_factor,\n calc_3d_features,\n bn_use_global_stats=False,\n **kwargs):\n super(LwopDecoderFinalBlock, self).__init__(**kwargs)\n self.num_heatmap_paf = 3 * keypoints\n self.calc_3d_features = calc_3d_features\n features_out_channels = self.num_heatmap_paf\n features_in_channels = in_channels - features_out_channels\n\n if self.calc_3d_features:\n with self.name_scope():\n self.body = nn.HybridSequential(prefix=\"\")\n for i in range(5):\n self.body.add(LwopResUnit(\n in_channels=in_channels,\n out_channels=features_in_channels,\n bottleneck_factor=bottleneck_factor,\n bn_use_global_stats=bn_use_global_stats))\n in_channels = features_in_channels\n self.features_bend = LwopDecoderFeaturesBend(\n in_channels=features_in_channels,\n mid_channels=features_in_channels,\n out_channels=features_out_channels,\n bn_use_global_stats=bn_use_global_stats)\n\n def hybrid_forward(self, F, x):\n heatmap_paf_2d = F.slice_axis(x, axis=1, begin=-self.num_heatmap_paf, end=None)\n if not self.calc_3d_features:\n return heatmap_paf_2d\n x = self.body(x)\n x = self.features_bend(x)\n y = F.concat(heatmap_paf_2d, x, dim=1)\n return y\n\n\nclass LwOpenPose(HybridBlock):\n \"\"\"\n Lightweight OpenPose 2D/3D model from 'Real-time 2D Multi-Person Pose Estimation on CPU: Lightweight OpenPose,'\n https://arxiv.org/abs/1811.12004.\n\n Parameters:\n ----------\n encoder_channels : list of list of int\n Number of output channels for each encoder unit.\n encoder_paddings : list of list of int\n Padding/dilation value for each encoder unit.\n encoder_init_block_channels : int\n Number of output channels for the encoder initial unit.\n encoder_final_block_channels : int\n Number of output channels for the encoder final unit.\n refinement_units : int\n Number of refinement blocks in the decoder.\n calc_3d_features : bool\n Whether to calculate 3D features.\n return_heatmap : bool, default True\n Whether to return only heatmap.\n bn_use_global_stats : bool, default False\n Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.\n Useful for fine-tuning.\n in_channels : int, default 3\n Number of input channels.\n in_size : tuple of two ints, default (256, 192)\n Spatial size of the expected input image.\n keypoints : int, default 19\n Number of keypoints.\n \"\"\"\n def __init__(self,\n encoder_channels,\n encoder_paddings,\n encoder_init_block_channels,\n encoder_final_block_channels,\n refinement_units,\n calc_3d_features,\n return_heatmap=True,\n bn_use_global_stats=False,\n in_channels=3,\n in_size=(368, 368),\n keypoints=19,\n **kwargs):\n super(LwOpenPose, self).__init__(**kwargs)\n assert (in_channels == 3)\n self.in_size = in_size\n self.keypoints = keypoints\n self.return_heatmap = return_heatmap\n self.calc_3d_features = calc_3d_features\n num_heatmap_paf = 3 * keypoints\n\n with self.name_scope():\n self.encoder = nn.HybridSequential(prefix=\"\")\n backbone = nn.HybridSequential(prefix=\"\")\n backbone.add(conv3x3_block(\n in_channels=in_channels,\n out_channels=encoder_init_block_channels,\n strides=2,\n bn_use_global_stats=bn_use_global_stats))\n in_channels = encoder_init_block_channels\n for i, channels_per_stage in enumerate(encoder_channels):\n stage = nn.HybridSequential(prefix=\"stage{}_\".format(i + 1))\n with stage.name_scope():\n for j, out_channels in enumerate(channels_per_stage):\n strides = 2 if (j == 0) and (i != 0) else 1\n padding = encoder_paddings[i][j]\n stage.add(dwsconv3x3_block(\n in_channels=in_channels,\n out_channels=out_channels,\n strides=strides,\n padding=padding,\n dilation=padding,\n bn_use_global_stats=bn_use_global_stats))\n in_channels = out_channels\n backbone.add(stage)\n self.encoder.add(backbone)\n self.encoder.add(LwopEncoderFinalBlock(\n in_channels=in_channels,\n out_channels=encoder_final_block_channels,\n bn_use_global_stats=bn_use_global_stats))\n in_channels = encoder_final_block_channels\n\n self.decoder = nn.HybridSequential(prefix=\"\")\n self.decoder.add(LwopDecoderInitBlock(\n in_channels=in_channels,\n keypoints=keypoints,\n bn_use_global_stats=bn_use_global_stats))\n in_channels = encoder_final_block_channels + num_heatmap_paf\n for i in range(refinement_units):\n self.decoder.add(LwopDecoderUnit(\n in_channels=in_channels,\n keypoints=keypoints,\n bn_use_global_stats=bn_use_global_stats))\n self.decoder.add(LwopDecoderFinalBlock(\n in_channels=in_channels,\n keypoints=keypoints,\n bottleneck_factor=2,\n calc_3d_features=calc_3d_features,\n bn_use_global_stats=bn_use_global_stats))\n\n def hybrid_forward(self, F, x):\n x = self.encoder(x)\n x = self.decoder(x)\n if self.return_heatmap:\n return x\n else:\n return x\n\n\ndef get_lwopenpose(calc_3d_features,\n keypoints,\n model_name=None,\n pretrained=False,\n ctx=cpu(),\n root=os.path.join(\"~\", \".mxnet\", \"models\"),\n **kwargs):\n \"\"\"\n Create Lightweight OpenPose 2D/3D model with specific parameters.\n\n Parameters:\n ----------\n calc_3d_features : bool, default False\n Whether to calculate 3D features.\n keypoints : int\n Number of keypoints.\n model_name : str or None, default None\n Model name for loading pretrained model.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n ctx : Context, default CPU\n The context in which to load the pretrained weights.\n root : str, default '~/.mxnet/models'\n Location for keeping the model parameters.\n \"\"\"\n encoder_channels = [[64], [128, 128], [256, 256, 512, 512, 512, 512, 512, 512]]\n encoder_paddings = [[1], [1, 1], [1, 1, 1, 2, 1, 1, 1, 1]]\n encoder_init_block_channels = 32\n encoder_final_block_channels = 128\n refinement_units = 1\n\n net = LwOpenPose(\n encoder_channels=encoder_channels,\n encoder_paddings=encoder_paddings,\n encoder_init_block_channels=encoder_init_block_channels,\n encoder_final_block_channels=encoder_final_block_channels,\n refinement_units=refinement_units,\n calc_3d_features=calc_3d_features,\n keypoints=keypoints,\n **kwargs)\n\n if pretrained:\n if (model_name is None) or (not model_name):\n raise ValueError(\"Parameter `model_name` should be properly initialized for loading pretrained model.\")\n from .model_store import get_model_file\n net.load_parameters(\n filename=get_model_file(\n model_name=model_name,\n local_model_store_dir_path=root),\n ctx=ctx)\n\n return net\n\n\ndef lwopenpose2d_mobilenet_cmupan_coco(keypoints=19, **kwargs):\n \"\"\"\n Lightweight OpenPose 2D model on the base of MobileNet for CMU Panoptic from 'Real-time 2D Multi-Person Pose\n Estimation on CPU: Lightweight OpenPose,' https://arxiv.org/abs/1811.12004.\n\n Parameters:\n ----------\n keypoints : int, default 19\n Number of keypoints.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n ctx : Context, default CPU\n The context in which to load the pretrained weights.\n root : str, default '~/.mxnet/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_lwopenpose(calc_3d_features=False, keypoints=keypoints, model_name=\"lwopenpose2d_mobilenet_cmupan_coco\",\n **kwargs)\n\n\ndef lwopenpose3d_mobilenet_cmupan_coco(keypoints=19, **kwargs):\n \"\"\"\n Lightweight OpenPose 3D model on the base of MobileNet for CMU Panoptic from 'Real-time 2D Multi-Person Pose\n Estimation on CPU: Lightweight OpenPose,' https://arxiv.org/abs/1811.12004.\n\n Parameters:\n ----------\n keypoints : int, default 19\n Number of keypoints.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n ctx : Context, default CPU\n The context in which to load the pretrained weights.\n root : str, default '~/.mxnet/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_lwopenpose(calc_3d_features=True, keypoints=keypoints, model_name=\"lwopenpose3d_mobilenet_cmupan_coco\",\n **kwargs)\n\n\ndef _test():\n import numpy as np\n import mxnet as mx\n\n in_size = (368, 368)\n keypoints = 19\n return_heatmap = True\n pretrained = False\n\n models = [\n (lwopenpose2d_mobilenet_cmupan_coco, \"2d\"),\n (lwopenpose3d_mobilenet_cmupan_coco, \"3d\"),\n ]\n\n for model, model_dim in models:\n\n net = model(pretrained=pretrained, in_size=in_size, return_heatmap=return_heatmap)\n\n ctx = mx.cpu()\n if not pretrained:\n net.initialize(ctx=ctx)\n\n net.hybridize()\n net_params = net.collect_params()\n weight_count = 0\n for param in net_params.values():\n if (param.shape is None) or (not param._differentiable):\n continue\n weight_count += np.prod(param.shape)\n print(\"m={}, {}\".format(model.__name__, weight_count))\n assert (model != lwopenpose2d_mobilenet_cmupan_coco or weight_count == 4091698)\n assert (model != lwopenpose3d_mobilenet_cmupan_coco or weight_count == 5085983)\n\n batch = 14\n x = mx.nd.random.normal(shape=(batch, 3, in_size[0], in_size[1]), ctx=ctx)\n y = net(x)\n if model_dim == \"2d\":\n assert (y.shape == (batch, 3 * keypoints, in_size[0] // 8, in_size[0] // 8))\n else:\n assert (y.shape == (batch, 6 * keypoints, in_size[0] // 8, in_size[0] // 8))\n\n\nif __name__ == \"__main__\":\n _test()\n",
"\"\"\"\n SimplePose for COCO Keypoint, implemented in Gluon.\n Original paper: 'Simple Baselines for Human Pose Estimation and Tracking,' https://arxiv.org/abs/1804.06208.\n\"\"\"\n\n__all__ = ['SimplePose', 'simplepose_resnet18_coco', 'simplepose_resnet50b_coco', 'simplepose_resnet101b_coco',\n 'simplepose_resnet152b_coco', 'simplepose_resneta50b_coco', 'simplepose_resneta101b_coco',\n 'simplepose_resneta152b_coco', 'HeatmapMaxDetBlock']\n\nimport os\nfrom mxnet import cpu\nfrom mxnet.gluon import nn, HybridBlock\nfrom .common import DeconvBlock, conv1x1, HeatmapMaxDetBlock\nfrom .resnet import resnet18, resnet50b, resnet101b, resnet152b\nfrom .resneta import resneta50b, resneta101b, resneta152b\n\n\nclass SimplePose(HybridBlock):\n \"\"\"\n SimplePose model from 'Simple Baselines for Human Pose Estimation and Tracking,' https://arxiv.org/abs/1804.06208.\n\n Parameters:\n ----------\n backbone : nn.Sequential\n Feature extractor.\n backbone_out_channels : int\n Number of output channels for the backbone.\n channels : list of int\n Number of output channels for each decoder unit.\n bn_use_global_stats : bool, default False\n Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.\n Useful for fine-tuning.\n bn_cudnn_off : bool, default True\n Whether to disable CUDNN batch normalization operator.\n return_heatmap : bool, default False\n Whether to return only heatmap.\n fixed_size : bool, default True\n Whether to expect fixed spatial size of input image.\n in_channels : int, default 3\n Number of input channels.\n in_size : tuple of two ints, default (256, 192)\n Spatial size of the expected input image.\n keypoints : int, default 17\n Number of keypoints.\n \"\"\"\n def __init__(self,\n backbone,\n backbone_out_channels,\n channels,\n bn_use_global_stats=False,\n bn_cudnn_off=True,\n return_heatmap=False,\n fixed_size=True,\n in_channels=3,\n in_size=(256, 192),\n keypoints=17,\n **kwargs):\n super(SimplePose, self).__init__(**kwargs)\n assert (in_channels == 3)\n self.in_size = in_size\n self.keypoints = keypoints\n self.return_heatmap = return_heatmap\n\n with self.name_scope():\n self.backbone = backbone\n\n self.decoder = nn.HybridSequential(prefix=\"\")\n in_channels = backbone_out_channels\n for out_channels in channels:\n self.decoder.add(DeconvBlock(\n in_channels=in_channels,\n out_channels=out_channels,\n kernel_size=4,\n strides=2,\n padding=1,\n bn_use_global_stats=bn_use_global_stats,\n bn_cudnn_off=bn_cudnn_off))\n in_channels = out_channels\n self.decoder.add(conv1x1(\n in_channels=in_channels,\n out_channels=keypoints,\n use_bias=True))\n\n self.heatmap_max_det = HeatmapMaxDetBlock(\n channels=keypoints,\n in_size=(in_size[0] // 4, in_size[1] // 4),\n fixed_size=fixed_size)\n\n def hybrid_forward(self, F, x):\n x = self.backbone(x)\n heatmap = self.decoder(x)\n if self.return_heatmap:\n return heatmap\n else:\n keypoints = self.heatmap_max_det(heatmap)\n return keypoints\n\n\ndef get_simplepose(backbone,\n backbone_out_channels,\n keypoints,\n bn_cudnn_off,\n model_name=None,\n pretrained=False,\n ctx=cpu(),\n root=os.path.join(\"~\", \".mxnet\", \"models\"),\n **kwargs):\n \"\"\"\n Create SimplePose model with specific parameters.\n\n Parameters:\n ----------\n backbone : nn.Sequential\n Feature extractor.\n backbone_out_channels : int\n Number of output channels for the backbone.\n keypoints : int\n Number of keypoints.\n bn_cudnn_off : bool\n Whether to disable CUDNN batch normalization operator.\n model_name : str or None, default None\n Model name for loading pretrained model.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n ctx : Context, default CPU\n The context in which to load the pretrained weights.\n root : str, default '~/.mxnet/models'\n Location for keeping the model parameters.\n \"\"\"\n channels = [256, 256, 256]\n\n net = SimplePose(\n backbone=backbone,\n backbone_out_channels=backbone_out_channels,\n channels=channels,\n bn_cudnn_off=bn_cudnn_off,\n keypoints=keypoints,\n **kwargs)\n\n if pretrained:\n if (model_name is None) or (not model_name):\n raise ValueError(\"Parameter `model_name` should be properly initialized for loading pretrained model.\")\n from .model_store import get_model_file\n net.load_parameters(\n filename=get_model_file(\n model_name=model_name,\n local_model_store_dir_path=root),\n ctx=ctx)\n\n return net\n\n\ndef simplepose_resnet18_coco(pretrained_backbone=False, keypoints=17, bn_cudnn_off=True, **kwargs):\n \"\"\"\n SimplePose model on the base of ResNet-18 for COCO Keypoint from 'Simple Baselines for Human Pose Estimation and\n Tracking,' https://arxiv.org/abs/1804.06208.\n\n Parameters:\n ----------\n pretrained_backbone : bool, default False\n Whether to load the pretrained weights for feature extractor.\n keypoints : int, default 17\n Number of keypoints.\n bn_cudnn_off : bool, default True\n Whether to disable CUDNN batch normalization operator.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n ctx : Context, default CPU\n The context in which to load the pretrained weights.\n root : str, default '~/.mxnet/models'\n Location for keeping the model parameters.\n \"\"\"\n backbone = resnet18(pretrained=pretrained_backbone, bn_cudnn_off=bn_cudnn_off).features[:-1]\n return get_simplepose(backbone=backbone, backbone_out_channels=512, keypoints=keypoints, bn_cudnn_off=bn_cudnn_off,\n model_name=\"simplepose_resnet18_coco\", **kwargs)\n\n\ndef simplepose_resnet50b_coco(pretrained_backbone=False, keypoints=17, bn_cudnn_off=True, **kwargs):\n \"\"\"\n SimplePose model on the base of ResNet-50b for COCO Keypoint from 'Simple Baselines for Human Pose Estimation and\n Tracking,' https://arxiv.org/abs/1804.06208.\n\n Parameters:\n ----------\n pretrained_backbone : bool, default False\n Whether to load the pretrained weights for feature extractor.\n keypoints : int, default 17\n Number of keypoints.\n bn_cudnn_off : bool, default True\n Whether to disable CUDNN batch normalization operator.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n ctx : Context, default CPU\n The context in which to load the pretrained weights.\n root : str, default '~/.mxnet/models'\n Location for keeping the model parameters.\n \"\"\"\n backbone = resnet50b(pretrained=pretrained_backbone, bn_cudnn_off=bn_cudnn_off).features[:-1]\n return get_simplepose(backbone=backbone, backbone_out_channels=2048, keypoints=keypoints, bn_cudnn_off=bn_cudnn_off,\n model_name=\"simplepose_resnet50b_coco\", **kwargs)\n\n\ndef simplepose_resnet101b_coco(pretrained_backbone=False, keypoints=17, bn_cudnn_off=True, **kwargs):\n \"\"\"\n SimplePose model on the base of ResNet-101b for COCO Keypoint from 'Simple Baselines for Human Pose Estimation\n and Tracking,' https://arxiv.org/abs/1804.06208.\n\n Parameters:\n ----------\n pretrained_backbone : bool, default False\n Whether to load the pretrained weights for feature extractor.\n keypoints : int, default 17\n Number of keypoints.\n bn_cudnn_off : bool, default True\n Whether to disable CUDNN batch normalization operator.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n ctx : Context, default CPU\n The context in which to load the pretrained weights.\n root : str, default '~/.mxnet/models'\n Location for keeping the model parameters.\n \"\"\"\n backbone = resnet101b(pretrained=pretrained_backbone, bn_cudnn_off=bn_cudnn_off).features[:-1]\n return get_simplepose(backbone=backbone, backbone_out_channels=2048, keypoints=keypoints, bn_cudnn_off=bn_cudnn_off,\n model_name=\"simplepose_resnet101b_coco\", **kwargs)\n\n\ndef simplepose_resnet152b_coco(pretrained_backbone=False, keypoints=17, bn_cudnn_off=True, **kwargs):\n \"\"\"\n SimplePose model on the base of ResNet-152b for COCO Keypoint from 'Simple Baselines for Human Pose Estimation\n and Tracking,' https://arxiv.org/abs/1804.06208.\n\n Parameters:\n ----------\n pretrained_backbone : bool, default False\n Whether to load the pretrained weights for feature extractor.\n keypoints : int, default 17\n Number of keypoints.\n bn_cudnn_off : bool, default True\n Whether to disable CUDNN batch normalization operator.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n ctx : Context, default CPU\n The context in which to load the pretrained weights.\n root : str, default '~/.mxnet/models'\n Location for keeping the model parameters.\n \"\"\"\n backbone = resnet152b(pretrained=pretrained_backbone, bn_cudnn_off=bn_cudnn_off).features[:-1]\n return get_simplepose(backbone=backbone, backbone_out_channels=2048, keypoints=keypoints, bn_cudnn_off=bn_cudnn_off,\n model_name=\"simplepose_resnet152b_coco\", **kwargs)\n\n\ndef simplepose_resneta50b_coco(pretrained_backbone=False, keypoints=17, bn_cudnn_off=True, **kwargs):\n \"\"\"\n SimplePose model on the base of ResNet(A)-50b for COCO Keypoint from 'Simple Baselines for Human Pose Estimation\n and Tracking,' https://arxiv.org/abs/1804.06208.\n\n Parameters:\n ----------\n pretrained_backbone : bool, default False\n Whether to load the pretrained weights for feature extractor.\n keypoints : int, default 17\n Number of keypoints.\n bn_cudnn_off : bool, default True\n Whether to disable CUDNN batch normalization operator.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n ctx : Context, default CPU\n The context in which to load the pretrained weights.\n root : str, default '~/.mxnet/models'\n Location for keeping the model parameters.\n \"\"\"\n backbone = resneta50b(pretrained=pretrained_backbone, bn_cudnn_off=bn_cudnn_off).features[:-1]\n return get_simplepose(backbone=backbone, backbone_out_channels=2048, keypoints=keypoints, bn_cudnn_off=bn_cudnn_off,\n model_name=\"simplepose_resneta50b_coco\", **kwargs)\n\n\ndef simplepose_resneta101b_coco(pretrained_backbone=False, keypoints=17, bn_cudnn_off=True, **kwargs):\n \"\"\"\n SimplePose model on the base of ResNet(A)-101b for COCO Keypoint from 'Simple Baselines for Human Pose Estimation\n and Tracking,' https://arxiv.org/abs/1804.06208.\n\n Parameters:\n ----------\n pretrained_backbone : bool, default False\n Whether to load the pretrained weights for feature extractor.\n keypoints : int, default 17\n Number of keypoints.\n bn_cudnn_off : bool, default True\n Whether to disable CUDNN batch normalization operator.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n ctx : Context, default CPU\n The context in which to load the pretrained weights.\n root : str, default '~/.mxnet/models'\n Location for keeping the model parameters.\n \"\"\"\n backbone = resneta101b(pretrained=pretrained_backbone, bn_cudnn_off=bn_cudnn_off).features[:-1]\n return get_simplepose(backbone=backbone, backbone_out_channels=2048, keypoints=keypoints, bn_cudnn_off=bn_cudnn_off,\n model_name=\"simplepose_resneta101b_coco\", **kwargs)\n\n\ndef simplepose_resneta152b_coco(pretrained_backbone=False, keypoints=17, bn_cudnn_off=True, **kwargs):\n \"\"\"\n SimplePose model on the base of ResNet(A)-152b for COCO Keypoint from 'Simple Baselines for Human Pose Estimation\n and Tracking,' https://arxiv.org/abs/1804.06208.\n\n Parameters:\n ----------\n pretrained_backbone : bool, default False\n Whether to load the pretrained weights for feature extractor.\n keypoints : int, default 17\n Number of keypoints.\n bn_cudnn_off : bool, default True\n Whether to disable CUDNN batch normalization operator.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n ctx : Context, default CPU\n The context in which to load the pretrained weights.\n root : str, default '~/.mxnet/models'\n Location for keeping the model parameters.\n \"\"\"\n backbone = resneta152b(pretrained=pretrained_backbone, bn_cudnn_off=bn_cudnn_off).features[:-1]\n return get_simplepose(backbone=backbone, backbone_out_channels=2048, keypoints=keypoints, bn_cudnn_off=bn_cudnn_off,\n model_name=\"simplepose_resneta152b_coco\", **kwargs)\n\n\ndef _test():\n import numpy as np\n import mxnet as mx\n\n in_size = (256, 192)\n keypoints = 17\n return_heatmap = True\n pretrained = False\n\n models = [\n simplepose_resnet18_coco,\n simplepose_resnet50b_coco,\n simplepose_resnet101b_coco,\n simplepose_resnet152b_coco,\n simplepose_resneta50b_coco,\n simplepose_resneta101b_coco,\n simplepose_resneta152b_coco,\n ]\n\n for model in models:\n\n net = model(pretrained=pretrained, in_size=in_size, return_heatmap=return_heatmap)\n\n ctx = mx.cpu()\n if not pretrained:\n net.initialize(ctx=ctx)\n\n net.hybridize()\n net_params = net.collect_params()\n weight_count = 0\n for param in net_params.values():\n if (param.shape is None) or (not param._differentiable):\n continue\n weight_count += np.prod(param.shape)\n print(\"m={}, {}\".format(model.__name__, weight_count))\n assert (model != simplepose_resnet18_coco or weight_count == 15376721)\n assert (model != simplepose_resnet50b_coco or weight_count == 33999697)\n assert (model != simplepose_resnet101b_coco or weight_count == 52991825)\n assert (model != simplepose_resnet152b_coco or weight_count == 68635473)\n assert (model != simplepose_resneta50b_coco or weight_count == 34018929)\n assert (model != simplepose_resneta101b_coco or weight_count == 53011057)\n assert (model != simplepose_resneta152b_coco or weight_count == 68654705)\n\n batch = 14\n x = mx.nd.random.normal(shape=(batch, 3, in_size[0], in_size[1]), ctx=ctx)\n y = net(x)\n assert ((y.shape[0] == batch) and (y.shape[1] == keypoints))\n if return_heatmap:\n assert ((y.shape[2] == x.shape[2] // 4) and (y.shape[3] == x.shape[3] // 4))\n else:\n assert (y.shape[2] == 3)\n\n\nif __name__ == \"__main__\":\n _test()\n"
] | [
[
"numpy.prod"
],
[
"torch.nn.CrossEntropyLoss",
"numpy.random.seed",
"numpy.random.randint"
],
[
"numpy.random.seed",
"numpy.random.randint"
],
[
"numpy.zeros"
],
[
"tensorflow.keras.layers.AveragePooling2D",
"tensorflow.keras.layers.ReLU",
"tensorflow.keras.backend.get_value",
"tensorflow.keras.layers.Dense",
"tensorflow.keras.layers.Dropout"
],
[
"numpy.concatenate",
"numpy.dot",
"numpy.array",
"numpy.where"
],
[
"numpy.prod"
],
[
"torch.nn.Softmax",
"torch.nn.Sequential",
"torch.nn.init.constant_",
"torch.randn",
"torch.nn.init.kaiming_uniform_",
"torch.nn.Linear",
"torch.nn.AvgPool2d",
"torch.nn.AdaptiveAvgPool2d",
"torch.nn.ReLU"
],
[
"numpy.array",
"numpy.unique"
],
[
"torch.nn.Sequential",
"torch.nn.ConvTranspose2d",
"torch.cat",
"torch.nn.init.constant_",
"torch.randn",
"torch.nn.PReLU",
"torch.nn.init.kaiming_uniform_",
"torch.nn.BatchNorm2d"
],
[
"torch.nn.BatchNorm1d",
"torch.nn.Sequential",
"torch.nn.init.constant_",
"torch.randn",
"torch.nn.Sigmoid",
"torch.nn.init.kaiming_uniform_",
"torch.nn.Linear",
"torch.nn.AvgPool2d",
"torch.nn.AdaptiveAvgPool2d",
"torch.nn.ReLU"
],
[
"numpy.prod"
],
[
"tensorflow.nn.relu",
"tensorflow.keras.layers.AveragePooling2D",
"tensorflow.keras.layers.Dense",
"tensorflow.global_variables_initializer",
"tensorflow.reset_default_graph",
"tensorflow.Session",
"tensorflow.trainable_variables"
],
[
"numpy.zeros"
],
[
"torch.nn.Sequential",
"torch.nn.init.constant_",
"torch.randn",
"torch.nn.init.kaiming_uniform_",
"torch.nn.Linear",
"torch.nn.AvgPool2d"
],
[
"tensorflow.global_variables_initializer",
"tensorflow.global_variables",
"numpy.load"
],
[
"numpy.prod"
],
[
"numpy.prod"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"2.6",
"2.4",
"2.3",
"2.5",
"2.2"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"1.12",
"1.4",
"1.13",
"1.5",
"1.7",
"0.12",
"1.0",
"1.2"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
haowei01/translate | [
"e413a981667f1038ea9ab01bd9c6d0c013b03b0c"
] | [
"pytorch_translate/rnn.py"
] | [
"#!/usr/bin/env python3\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.onnx.operators\nfrom fairseq import utils\nfrom fairseq.models import (\n FairseqEncoder,\n FairseqModel,\n register_model,\n register_model_architecture,\n)\nfrom pytorch_translate import rnn_cell # noqa\nfrom pytorch_translate import (\n attention,\n data as pytorch_translate_data,\n dictionary as pytorch_translate_dictionary,\n utils as pytorch_translate_utils,\n vocab_reduction,\n word_dropout,\n)\nfrom pytorch_translate.common_layers import (\n DecoderWithOutputProjection,\n Embedding,\n Linear,\n RNNLayer,\n VariableTracker,\n)\nfrom pytorch_translate.multi_model import MultiDecoder, MultiEncoder\nfrom pytorch_translate.multilingual import MultilingualDecoder, MultilingualEncoder\nfrom pytorch_translate.ngram import NGramDecoder\nfrom pytorch_translate.utils import maybe_cat, maybe_cuda\nfrom torch.nn.utils.rnn import PackedSequence, pack_padded_sequence, pad_packed_sequence\n\n\ndef torch_find(index, query, vocab_size):\n \"\"\"\n Finds elements of query from index, outputting the last (max) index for each\n query.\n preconditions: (1) index and query are flat arrays (can be different sizes)\n (2) all tokens in index and query have values < vocab_size\n \"\"\"\n full_to_index = maybe_cuda(torch.zeros(vocab_size).long())\n index_shape_range = maybe_cuda(torch.arange(index.shape[0]).long())\n full_to_index[index] = index_shape_range\n result = full_to_index[query]\n return result\n\n\ndef reorder_encoder_output(encoder_out, new_order):\n \"\"\"Reorder all outputs according to new_order.\"\"\"\n (\n unpacked_output,\n final_hiddens,\n final_cells,\n src_lengths,\n src_tokens,\n src_embeddings,\n ) = encoder_out\n unpacked_output = unpacked_output.index_select(1, new_order)\n final_hiddens = final_hiddens.index_select(1, new_order)\n final_cells = final_cells.index_select(1, new_order)\n src_lengths = src_lengths.index_select(0, new_order)\n src_tokens = src_tokens.index_select(0, new_order)\n src_embeddings = src_embeddings.index_select(1, new_order)\n return (\n unpacked_output,\n final_hiddens,\n final_cells,\n src_lengths,\n src_tokens,\n src_embeddings,\n )\n\n\n@register_model(\"rnn\")\nclass RNNModel(FairseqModel):\n def __init__(self, task, encoder, decoder):\n super().__init__(encoder, decoder)\n self.task = task\n\n @staticmethod\n def add_args(parser):\n parser.add_argument(\n \"--dropout\",\n default=0.1,\n type=float,\n metavar=\"D\",\n help=\"dropout probability\",\n )\n parser.add_argument(\n \"--encoder-embed-dim\",\n default=0,\n type=int,\n metavar=\"N\",\n help=\"encoder embedding dimension\",\n )\n parser.add_argument(\n \"--encoder-pretrained-embed\",\n default=None,\n metavar=\"FILE\",\n help=\"path to pre-trained encoder embedding\",\n )\n parser.add_argument(\n \"--encoder-freeze-embed\",\n default=False,\n action=\"store_true\",\n help=(\n \"whether to freeze the encoder embedding or allow it to be \"\n \"updated during training\"\n ),\n )\n parser.add_argument(\n \"--encoder-hidden-dim\", type=int, metavar=\"N\", help=\"encoder cell num units\"\n )\n parser.add_argument(\n \"--encoder-layers\", type=int, metavar=\"N\", help=\"number of encoder layers\"\n )\n parser.add_argument(\n \"--encoder-bidirectional\",\n action=\"store_true\",\n help=\"whether the first layer is bidirectional or not\",\n )\n parser.add_argument(\n \"--averaging-encoder\",\n default=False,\n action=\"store_true\",\n help=(\n \"whether use mean encoder hidden states as decoder initial \"\n \"states or not\"\n ),\n )\n parser.add_argument(\n \"--decoder-embed-dim\",\n default=0,\n type=int,\n metavar=\"N\",\n help=\"decoder embedding dimension\",\n )\n parser.add_argument(\n \"--decoder-pretrained-embed\",\n default=None,\n metavar=\"FILE\",\n help=\"path to pre-trained decoder embedding\",\n )\n parser.add_argument(\n \"--decoder-freeze-embed\",\n default=False,\n action=\"store_true\",\n help=(\n \"whether to freeze the decoder embedding or allow it to be \"\n \"updated during training\"\n ),\n )\n parser.add_argument(\n \"--decoder-hidden-dim\", type=int, metavar=\"N\", help=\"decoder cell num units\"\n )\n parser.add_argument(\n \"--decoder-layers\", type=int, metavar=\"N\", help=\"number of decoder layers\"\n )\n parser.add_argument(\n \"--decoder-out-embed-dim\",\n type=int,\n metavar=\"N\",\n help=\"decoder output embedding dimension\",\n )\n parser.add_argument(\n \"--decoder-out-pretrained-embed\",\n default=None,\n metavar=\"FILE\",\n help=\"path to pre-trained decoder output embedding\",\n )\n parser.add_argument(\n \"--decoder-tie-embeddings\",\n default=False,\n action=\"store_true\",\n help=\"tie the decoder word embeddings with the output projection \"\n \"weights (requires that the embedding dims be of the same size)\",\n )\n parser.add_argument(\n \"--attention-type\",\n type=str,\n metavar=\"EXPR\",\n help=\"decoder attention, defaults to dot\",\n )\n parser.add_argument(\n \"--residual-level\",\n default=None,\n type=int,\n help=(\n \"First layer where to apply a residual connection. \"\n \"The value should be greater than 0 and smaller than the number of \"\n \"layers.\"\n ),\n )\n parser.add_argument(\n \"--cell-type\",\n default=\"lstm\",\n type=str,\n metavar=\"EXPR\",\n help=\"cell type, defaults to lstm, values:lstm, milstm, layer_norm_lstm\",\n )\n\n # Granular dropout settings (if not specified these default to --dropout)\n parser.add_argument(\n \"--encoder-dropout-in\",\n type=float,\n metavar=\"D\",\n help=\"dropout probability for encoder input embedding\",\n )\n parser.add_argument(\n \"--encoder-dropout-out\",\n type=float,\n metavar=\"D\",\n help=\"dropout probability for encoder output\",\n )\n parser.add_argument(\n \"--decoder-dropout-in\",\n type=float,\n metavar=\"D\",\n help=\"dropout probability for decoder input embedding\",\n )\n parser.add_argument(\n \"--decoder-dropout-out\",\n type=float,\n metavar=\"D\",\n help=\"dropout probability for decoder output\",\n )\n parser.add_argument(\n \"--sequence-lstm\",\n action=\"store_true\",\n help=\"use nn.LSTM implementation for encoder\",\n )\n parser.add_argument(\n \"--ngram-decoder\",\n default=None,\n type=int,\n nargs=\"+\",\n help=(\n \"A single integer, or a list of integers. If \"\n \"positive, the decoder is not recurrent but a feedforward \"\n \"network with target-side n-gram history as input. The decoder \"\n \"is still conditioned on the source side via attention. If \"\n \"this parameter is a list of integers, the n-th entry applies \"\n \"to the n-th decoder (for multilingual models and \"\n \"multi-decoders)\"\n ),\n )\n parser.add_argument(\n \"--ngram-activation-type\",\n default=\"relu\",\n type=str,\n metavar=\"EXPR\",\n help=(\n \"Activation in FF layers of the ngram decoder, defaults to \"\n \"relu, values: relu, tanh\"\n ),\n )\n parser.add_argument(\n \"--multi-encoder\",\n default=None,\n type=int,\n help=(\n \"If this is positive, train n encoder networks rather than \"\n \"only one. The outputs of the encoders are concatenated before \"\n \"passing them through to the decoder.\"\n ),\n )\n parser.add_argument(\n \"--multi-decoder\",\n default=None,\n type=int,\n help=(\n \"If this is positive, train n decoder networks rather than \"\n \"only one. The predictions are combined via the method in \"\n \"--multi-decoder-combination-strategy.\"\n ),\n )\n parser.add_argument(\n \"--multi-decoder-combination-strategy\",\n default=\"bottleneck\",\n type=str,\n metavar=\"EXPR\",\n help=(\n \"Only used if --multi-decoder is positive. Controls how the \"\n \"decoders are combined with each other.\\n\"\n \"- uniform: Separate projection layers, average predictions\\n\"\n \"- uniform-probspace: Separate projection layers, average \"\n \"in probability space.\\n\"\n \"- uniform-logprobspace: Separate projection layers, average \"\n \"in log-probability space.\\n\"\n \"- unprojected: Shared projection layer, unprojected \"\n \"decoder outputs are averaged.\\n\"\n \"- deepfusion: cf. https://arxiv.org/pdf/1503.03535.pdf \\n\"\n \"- coldfusion: cf. https://arxiv.org/pdf/1708.06426.pdf \\n\"\n \"- weighted: Separate projection layers, weighted average \"\n \"of logits. Weights are learned from unprojected decoder \"\n \"outputs.\\n\"\n \"- weighted-probspace: Like 'weighted', but average in \"\n \"probability space.\\n\"\n \"- weighted-logprobspace: Like 'weighted', but average in \"\n \"log-probability space.\\n\"\n \"- weighted-unprojected: Shared projection layer, weighted \"\n \"average of decoder outputs. Weights are learned from \"\n \"unprojected decoder outputs.\\n\"\n \"- concat: Shared projection layer, decoder outputs are \"\n \"concatenated.\\n\"\n \"- bottleneck: Like 'concat' but with an additional \"\n \"bottleneck layer to reduce the size of the output embedding \"\n \"matrix.\\n\"\n \"- deep_bottleneck: Like 'bottleneck' but with an additional \"\n \"non-linear layer.\\n\"\n \"- multiplicative-unprojected: Shared projection layer, element\"\n \"-wise product of decoder outputs after ReLU.\\n\"\n \"- max-unprojected: Shared projection layer, element\"\n \"-wise max of decoder outputs.\\n\"\n ),\n )\n parser.add_argument(\n \"--multi-model-fixed-weights\",\n default=None,\n type=float,\n nargs=\"+\",\n help=(\n \"Used for weighted* combination strategies. If specified, use \"\n \"these fixed model weights rather than a gating network.\"\n ),\n )\n parser.add_argument(\n \"--multi-model-training-schedule\",\n default=\"complete\",\n type=str,\n metavar=\"EXPR\",\n help=(\n \"Only used if --multi-decoder is positive.\\n\"\n \"- 'complete': Jointly train entire network on all batches.\\n\"\n \"- 'unfreeze_single': Freeze all submodels except one for each \"\n \"training batch.\\n\"\n \"- 'unfreeze_single_encoder': Freeze all encoders except one \"\n \"for each training batch.\\n\"\n \"- 'unfreeze_single_decoder': Freeze all decoders except one \"\n \"for each training batch.\\n\"\n \"- 'unfreeze_enc_N': Freeze N-th encoder.\\n\"\n \"- 'unfreeze_dec_N': Freeze N-th decoder.\\n\"\n \"- 'unfreeze_encdec_N': Freeze N-th encoder and N-th decoder.\\n\"\n \"- 'freeze_all': Freeze all submodels, only train combination \"\n \"strategy.\\n\"\n \"- 'freeze_all_encoders': Freeze all encoders.\\n\"\n \"- 'freeze_all_decoders': Freeze all decoders.\\n\"\n \"- 'separate': Each training batch is used for only one of the \"\n \"following: Train the n-th submodel, or train combination \"\n \"strategy.\"\n ),\n )\n parser.add_argument(\n \"--multi-decoder-is-lm\",\n default=None,\n type=int,\n nargs=\"+\",\n help=(\n \"If specified, sets --attention-type=no and --encoder-hidden-dim=0\"\n \"for the n-th decoder in an adaptive ensemble.\"\n ),\n )\n parser.add_argument(\n \"--att-weighted-source-embeds\",\n default=False,\n action=\"store_true\",\n help=(\n \"whether use attention weighted src embeddings to improve rare \"\n \"words translation or not\"\n ),\n )\n parser.add_argument(\n \"--att-weighted-activation-type\",\n default=\"tanh\",\n type=str,\n metavar=\"EXPR\",\n help=(\n \"Activation in FF layers of the attention weighted src embeddings, \"\n \"defaults to relu, values: relu, tanh\"\n ),\n )\n\n # Args for vocab reduction\n vocab_reduction.add_args(parser)\n # Args for word dropout\n word_dropout.add_args(parser)\n\n @staticmethod\n def build_single_encoder(args, src_dict):\n if not args.encoder_hidden_dim:\n return DummyEncoder(src_dict, num_layers=args.encoder_layers)\n if args.sequence_lstm:\n encoder_class = LSTMSequenceEncoder\n else:\n encoder_class = RNNEncoder\n return encoder_class(\n src_dict,\n embed_dim=args.encoder_embed_dim,\n freeze_embed=args.encoder_freeze_embed,\n cell_type=args.cell_type,\n num_layers=args.encoder_layers,\n hidden_dim=args.encoder_hidden_dim,\n dropout_in=args.encoder_dropout_in,\n dropout_out=args.encoder_dropout_out,\n residual_level=args.residual_level,\n bidirectional=bool(args.encoder_bidirectional),\n word_dropout_params=args.word_dropout_params,\n pretrained_embed=args.encoder_pretrained_embed,\n left_pad=args.left_pad_source,\n )\n\n @staticmethod\n def build_single_decoder(\n args, src_dict, dst_dict, ngram_decoder=None, project_output=True, is_lm=False\n ):\n attention_type = args.attention_type\n encoder_hidden_dim = args.encoder_hidden_dim\n if is_lm:\n attention_type = \"no\"\n encoder_hidden_dim = 0\n if ngram_decoder:\n if args.ngram_activation_type == \"relu\":\n activation_fn = nn.ReLU\n elif args.ngram_activation_type == \"tanh\":\n activation_fn = nn.Tanh\n else:\n raise Exception(\n \"ngram_activation_type '%s' not implemented\"\n % args.ngram_activation_type\n )\n decoder = NGramDecoder(\n src_dict=src_dict,\n dst_dict=dst_dict,\n n=ngram_decoder,\n encoder_hidden_dim=encoder_hidden_dim,\n embed_dim=args.decoder_embed_dim,\n freeze_embed=args.decoder_freeze_embed,\n out_embed_dim=args.decoder_out_embed_dim,\n num_layers=args.decoder_layers,\n hidden_dim=args.decoder_hidden_dim,\n attention_type=attention_type,\n dropout_in=args.decoder_dropout_in,\n dropout_out=args.decoder_dropout_out,\n residual_level=args.residual_level,\n activation_fn=activation_fn,\n project_output=project_output,\n pretrained_embed=args.decoder_pretrained_embed,\n projection_pretrained_embed=args.decoder_out_pretrained_embed,\n )\n else:\n decoder = RNNDecoder(\n src_dict=src_dict,\n dst_dict=dst_dict,\n vocab_reduction_params=args.vocab_reduction_params,\n encoder_hidden_dim=encoder_hidden_dim,\n embed_dim=args.decoder_embed_dim,\n freeze_embed=args.decoder_freeze_embed,\n out_embed_dim=args.decoder_out_embed_dim,\n cell_type=args.cell_type,\n num_layers=args.decoder_layers,\n hidden_dim=args.decoder_hidden_dim,\n attention_type=attention_type,\n dropout_in=args.decoder_dropout_in,\n dropout_out=args.decoder_dropout_out,\n residual_level=args.residual_level,\n averaging_encoder=args.averaging_encoder,\n project_output=project_output,\n pretrained_embed=args.decoder_pretrained_embed,\n projection_pretrained_embed=args.decoder_out_pretrained_embed,\n tie_embeddings=args.decoder_tie_embeddings,\n att_weighted_src_embeds=args.att_weighted_src_embeds,\n src_embed_dim=args.encoder_embed_dim,\n att_weighted_activation_type=args.att_weighted_activation_type,\n )\n return decoder\n\n @classmethod\n def build_encoder(cls, args, src_dict):\n \"\"\"Build a new (multi-)encoder instance.\"\"\"\n if args.multi_encoder is not None:\n encoders = [\n RNNModel.build_single_encoder(args, src_dict)\n for _ in range(args.multi_encoder)\n ]\n encoder = MultiEncoder(\n src_dict, encoders, training_schedule=args.multi_model_training_schedule\n )\n else:\n encoder = RNNModel.build_single_encoder(args, src_dict)\n return encoder\n\n @classmethod\n def build_decoder(cls, args, src_dict, dst_dict):\n \"\"\"Build a new (multi-)decoder instance.\"\"\"\n if args.multi_decoder is not None:\n ngram_decoder_args = [None] * args.multi_decoder\n if args.ngram_decoder is not None:\n ngram_decoder_args = args.ngram_decoder\n if len(ngram_decoder_args) == 1:\n ngram_decoder_args = [ngram_decoder_args[0]] * args.multi_decoder\n assert len(ngram_decoder_args) == args.multi_decoder\n is_lm_args = [False] * args.multi_decoder\n if args.multi_decoder_is_lm is not None:\n is_lm_args = list(map(bool, args.multi_decoder_is_lm))\n assert len(is_lm_args) == args.multi_decoder\n decoders = [\n RNNModel.build_single_decoder(\n args, src_dict, dst_dict, n, project_output=False, is_lm=is_lm\n )\n for is_lm, n in zip(is_lm_args, ngram_decoder_args)\n ]\n decoder = MultiDecoder(\n src_dict,\n dst_dict,\n decoders=decoders,\n combination_strategy=args.multi_decoder_combination_strategy,\n is_lm=is_lm_args,\n split_encoder=args.multi_encoder is not None,\n vocab_reduction_params=args.vocab_reduction_params,\n training_schedule=args.multi_model_training_schedule,\n fixed_weights=args.multi_model_fixed_weights,\n )\n else:\n if args.multi_encoder:\n args.encoder_hidden_dim *= args.multi_encoder\n n = args.ngram_decoder[0] if args.ngram_decoder else None\n decoder = RNNModel.build_single_decoder(args, src_dict, dst_dict, n)\n return decoder\n\n @classmethod\n def build_model(cls, args, task):\n \"\"\"Build a new model instance.\"\"\"\n base_architecture(args)\n # set default value for old checkpoints\n args.left_pad_source = getattr(args, \"left_pad_source\", True)\n if pytorch_translate_data.is_multilingual(args):\n return RNNModel.build_model_multilingual(args, task)\n src_dict, dst_dict = task.source_dictionary, task.target_dictionary\n encoder = RNNModel.build_encoder(args, src_dict)\n decoder = RNNModel.build_decoder(args, src_dict, dst_dict)\n return cls(task, encoder, decoder)\n\n @classmethod\n def build_model_multilingual(cls, args, task):\n \"\"\"Build a new multilingual model instance.\"\"\"\n encoders = []\n for lang in args.multiling_encoder_lang:\n d = task.source_dictionaries.get(lang, None)\n if d is not None:\n encoders.append(RNNModel.build_encoder(args, d))\n else:\n encoders.append(None)\n encoder = MultilingualEncoder(\n task.source_dictionary,\n encoders,\n hidden_dim=args.encoder_hidden_dim,\n num_layers=args.encoder_layers,\n embed_dim=args.encoder_embed_dim,\n rescale_grads=args.multiling_rescale_grads,\n )\n decoders = []\n for lang in args.multiling_decoder_lang:\n d = task.target_dictionaries.get(lang, None)\n if d is not None:\n decoders.append(RNNModel.build_decoder(args, None, d))\n else:\n decoders.append(None)\n decoder = MultilingualDecoder(\n task.target_dictionary,\n decoders,\n hidden_dim=args.encoder_hidden_dim,\n rescale_grads=args.multiling_rescale_grads,\n )\n return cls(task, encoder, decoder)\n\n def get_targets(self, sample, net_output):\n targets = sample[\"target\"].view(-1)\n possible_translation_tokens = net_output[-1]\n if possible_translation_tokens is not None:\n targets = torch_find(\n possible_translation_tokens, targets, len(self.task.target_dictionary)\n )\n return targets\n\n\nclass LSTMSequenceEncoder(FairseqEncoder):\n \"\"\"RNN encoder using nn.LSTM for cuDNN support / ONNX exportability.\"\"\"\n\n @staticmethod\n def LSTM(input_size, hidden_size, **kwargs):\n m = nn.LSTM(input_size, hidden_size, **kwargs)\n for name, param in m.named_parameters():\n if \"weight\" in name or \"bias\" in name:\n param.data.uniform_(-0.1, 0.1)\n return m\n\n def __init__(\n self,\n dictionary,\n embed_dim=512,\n freeze_embed=False,\n cell_type=\"lstm\",\n hidden_dim=512,\n num_layers=1,\n dropout_in=0.1,\n dropout_out=0.1,\n residual_level=None,\n bidirectional=False,\n pretrained_embed=None,\n word_dropout_params=None,\n padding_value=0,\n left_pad=True,\n ):\n assert cell_type == \"lstm\", 'sequence-lstm requires cell_type=\"lstm\"'\n\n super().__init__(dictionary)\n self.dictionary = dictionary\n self.dropout_in = dropout_in\n self.dropout_out = dropout_out\n self.residual_level = residual_level\n self.hidden_dim = hidden_dim\n self.bidirectional = bidirectional\n num_embeddings = len(dictionary)\n self.padding_idx = dictionary.pad()\n self.padding_value = padding_value\n self.left_pad = left_pad\n\n self.embed_tokens = Embedding(\n num_embeddings=num_embeddings,\n embedding_dim=embed_dim,\n padding_idx=self.padding_idx,\n freeze_embed=freeze_embed,\n )\n pytorch_translate_utils.load_embedding(\n embedding=self.embed_tokens,\n dictionary=dictionary,\n pretrained_embed=pretrained_embed,\n )\n self.word_dim = embed_dim\n\n self.layers = nn.ModuleList([])\n for layer in range(num_layers):\n is_layer_bidirectional = self.bidirectional and layer == 0\n self.layers.append(\n LSTMSequenceEncoder.LSTM(\n self.word_dim if layer == 0 else hidden_dim,\n hidden_dim // 2 if is_layer_bidirectional else hidden_dim,\n num_layers=1,\n dropout=self.dropout_out,\n bidirectional=is_layer_bidirectional,\n )\n )\n\n self.num_layers = len(self.layers)\n self.word_dropout_module = None\n if (\n word_dropout_params\n and word_dropout_params[\"word_dropout_freq_threshold\"] is not None\n and word_dropout_params[\"word_dropout_freq_threshold\"] > 0\n ):\n self.word_dropout_module = word_dropout.WordDropout(\n dictionary, word_dropout_params\n )\n\n # Variable tracker\n self.tracker = VariableTracker()\n\n # Initialize adversarial mode\n self.set_gradient_tracking_mode(False)\n\n def forward(self, src_tokens, src_lengths):\n if self.left_pad:\n # convert left-padding to right-padding\n src_tokens = utils.convert_padding_direction(\n src_tokens, self.padding_idx, left_to_right=True\n )\n\n # If we're generating adversarial examples we need to keep track of\n # some internal variables\n self.tracker.reset()\n\n if self.word_dropout_module is not None:\n src_tokens = self.word_dropout_module(src_tokens)\n\n bsz, seqlen = src_tokens.size()\n\n # embed tokens\n x = self.embed_tokens(src_tokens)\n # Track token embeddings\n self.tracker.track(x, \"token_embeddings\", retain_grad=self.track_gradients)\n\n x = F.dropout(x, p=self.dropout_in, training=self.training)\n\n # B x T x C -> T x B x C\n x = x.transpose(0, 1)\n embedded_words = x\n\n # Allows compatibility with Caffe2 inputs for tracing (int32)\n # as well as the current format of Fairseq-Py inputs (int64)\n if src_lengths.dtype is torch.int64:\n src_lengths = src_lengths.int()\n\n # Generate packed seq to deal with varying source seq length\n # packed_input is of type PackedSequence, which consists of:\n # element [0]: a tensor, the packed data, and\n # element [1]: a list of integers, the batch size for each step\n packed_input = pack_padded_sequence(x, src_lengths)\n\n final_hiddens, final_cells = [], []\n for i, rnn_layer in enumerate(self.layers):\n if self.bidirectional and i == 0:\n h0 = x.new(2, bsz, self.hidden_dim // 2).zero_()\n c0 = x.new(2, bsz, self.hidden_dim // 2).zero_()\n else:\n h0 = x.new(1, bsz, self.hidden_dim).zero_()\n c0 = x.new(1, bsz, self.hidden_dim).zero_()\n\n # apply LSTM along entire sequence\n current_output, (h_last, c_last) = rnn_layer(packed_input, (h0, c0))\n\n # final state shapes: (bsz, hidden_dim)\n if self.bidirectional and i == 0:\n # concatenate last states for forward and backward LSTM\n h_last = torch.cat((h_last[0, :, :], h_last[1, :, :]), dim=1)\n c_last = torch.cat((c_last[0, :, :], c_last[1, :, :]), dim=1)\n else:\n h_last = h_last.squeeze(dim=0)\n c_last = c_last.squeeze(dim=0)\n\n final_hiddens.append(h_last)\n final_cells.append(c_last)\n\n if self.residual_level is not None and i >= self.residual_level:\n packed_input[0] = packed_input.clone()[0] + current_output[0]\n else:\n packed_input = current_output\n\n # Reshape to [num_layer, batch_size, hidden_dim]\n final_hiddens = torch.cat(final_hiddens, dim=0).view(\n self.num_layers, *final_hiddens[0].size()\n )\n final_cells = torch.cat(final_cells, dim=0).view(\n self.num_layers, *final_cells[0].size()\n )\n\n # [max_seqlen, batch_size, hidden_dim]\n unpacked_output, _ = pad_packed_sequence(\n packed_input, padding_value=self.padding_value\n )\n\n return (\n unpacked_output,\n final_hiddens,\n final_cells,\n src_lengths,\n src_tokens,\n embedded_words,\n )\n\n def reorder_encoder_out(self, encoder_out, new_order):\n \"\"\"Reorder all outputs according to new_order.\"\"\"\n return reorder_encoder_output(encoder_out, new_order)\n\n def max_positions(self):\n \"\"\"Maximum input length supported by the encoder.\"\"\"\n return int(1e5) # an arbitrary large number\n\n def set_gradient_tracking_mode(self, mode=True):\n self.tracker.reset()\n self.track_gradients = mode\n\n\nclass DummyEncoder(FairseqEncoder):\n \"\"\"Dummy encoder which outputs None. Used for LM training.\"\"\"\n\n def __init__(self, dictionary, num_layers=1):\n super().__init__(dictionary)\n self.num_layers = num_layers\n\n def forward(self, src_tokens, src_lengths):\n bsz = src_lengths.size(0)\n ones = maybe_cuda(torch.ones((self.num_layers, bsz, 1)))\n dummy_out = torch.ones((1, bsz, 1))\n return dummy_out, ones, ones, src_lengths, src_tokens, dummy_out\n\n def max_positions(self):\n \"\"\"Maximum input length supported by the encoder.\"\"\"\n return int(1e5) # an arbitrary large number\n\n\nclass RNNEncoder(FairseqEncoder):\n \"\"\"RNN encoder.\"\"\"\n\n def __init__(\n self,\n dictionary,\n word_dropout_params=None,\n embed_dim=512,\n freeze_embed=False,\n hidden_dim=512,\n num_layers=1,\n cell_type=\"lstm\",\n dropout_in=0.1,\n dropout_out=0.1,\n residual_level=None,\n bidirectional=False,\n pretrained_embed=None,\n padding_value=0,\n left_pad=True,\n ):\n super().__init__(dictionary)\n self.dictionary = dictionary\n self.dropout_in = dropout_in\n self.dropout_out = dropout_out\n self.residual_level = residual_level\n self.hidden_dim = hidden_dim\n self.output_units = hidden_dim # fairseq LSTM compatibility\n self.bidirectional = bidirectional\n num_embeddings = len(dictionary)\n self.padding_idx = dictionary.pad()\n self.padding_value = padding_value\n self.left_pad = left_pad\n\n self.embed_tokens = Embedding(\n num_embeddings=num_embeddings,\n embedding_dim=embed_dim,\n padding_idx=self.padding_idx,\n freeze_embed=freeze_embed,\n )\n pytorch_translate_utils.load_embedding(\n embedding=self.embed_tokens,\n dictionary=dictionary,\n pretrained_embed=pretrained_embed,\n )\n self.word_dim = embed_dim\n\n self.cell_type = cell_type\n self.layers = nn.ModuleList([])\n for layer in range(num_layers):\n self.layers.append(\n RNNLayer(\n self.word_dim if layer == 0 else hidden_dim,\n hidden_dim,\n self.cell_type,\n True if bidirectional and layer == 0 else False,\n )\n )\n\n self.num_layers = len(self.layers)\n self.word_dropout_module = None\n if (\n word_dropout_params\n and word_dropout_params[\"word_dropout_freq_threshold\"] is not None\n and word_dropout_params[\"word_dropout_freq_threshold\"] > 0\n ):\n self.word_dropout_module = word_dropout.WordDropout(\n dictionary, word_dropout_params\n )\n\n def forward(self, src_tokens, src_lengths):\n if self.left_pad:\n # convert left-padding to right-padding\n src_tokens = utils.convert_padding_direction(\n src_tokens, self.padding_idx, left_to_right=True\n )\n if self.word_dropout_module is not None:\n src_tokens = self.word_dropout_module(src_tokens)\n bsz, seqlen = src_tokens.size()\n\n # embed tokens\n x = self.embed_tokens(src_tokens)\n x = F.dropout(x, p=self.dropout_in, training=self.training)\n\n # B x T x C -> T x B x C\n x = x.transpose(0, 1)\n embedded_words = x\n\n # Generate packed seq to deal with varying source seq length\n packed_input, batch_sizes = pack_padded_sequence(x, src_lengths)\n final_hiddens, final_cells = [], []\n next_hiddens = []\n for i, rnn_layer in enumerate(self.layers):\n current_hidden_size = (\n self.hidden_dim // 2 if rnn_layer.is_bidirectional else self.hidden_dim\n )\n\n if self.cell_type in [\"lstm\", \"milstm\", \"layer_norm_lstm\"]:\n prev_hidden = (\n x.new(bsz, current_hidden_size).zero_(),\n x.new(bsz, current_hidden_size).zero_(),\n )\n else:\n raise Exception(f\"{self.cell_type} not implemented\")\n\n hidden, current_output = rnn_layer.forward(\n packed_input, prev_hidden, batch_sizes\n )\n next_hiddens.append(hidden)\n prev_hidden = next_hiddens[-1]\n\n if self.dropout_out != 0:\n current_output = F.dropout(\n current_output, p=self.dropout_out, training=self.training\n )\n\n if self.residual_level is not None and i >= self.residual_level:\n packed_input = packed_input.clone() + current_output\n else:\n packed_input = current_output\n\n final_hiddens, final_cells = zip(*next_hiddens)\n # Reshape to [num_layer, batch_size, hidden_dim]\n final_hiddens = torch.cat(final_hiddens, dim=0).view(\n self.num_layers, *final_hiddens[0].size()\n )\n final_cells = torch.cat(final_cells, dim=0).view(\n self.num_layers, *final_cells[0].size()\n )\n\n # [max_seqlen, batch_size, hidden_dim]\n unpacked_output, _ = pad_packed_sequence(\n PackedSequence(packed_input, batch_sizes), padding_value=self.padding_value\n )\n\n return (\n unpacked_output,\n final_hiddens,\n final_cells,\n src_lengths,\n src_tokens,\n embedded_words,\n )\n\n def reorder_encoder_out(self, encoder_out, new_order):\n \"\"\"Reorder all outputs according to new_order.\"\"\"\n return reorder_encoder_output(encoder_out, new_order)\n\n def max_positions(self):\n \"\"\"Maximum input length supported by the encoder.\"\"\"\n return int(1e5) # an arbitrary large number\n\n\nclass RNNDecoder(DecoderWithOutputProjection):\n \"\"\"RNN decoder.\"\"\"\n\n def __init__(\n self,\n src_dict,\n dst_dict,\n vocab_reduction_params=None,\n encoder_hidden_dim=512,\n embed_dim=512,\n freeze_embed=False,\n hidden_dim=512,\n out_embed_dim=512,\n cell_type=\"lstm\",\n num_layers=1,\n dropout_in=0.1,\n dropout_out=0.1,\n attention_type=\"dot\",\n residual_level=None,\n averaging_encoder=False,\n project_output=True,\n tie_embeddings=False,\n pretrained_embed=None,\n projection_pretrained_embed=None,\n att_weighted_src_embeds=False,\n src_embed_dim=512,\n att_weighted_activation_type=\"tanh\",\n ):\n super().__init__(\n src_dict,\n dst_dict,\n vocab_reduction_params,\n out_embed_dim,\n project_output=project_output,\n pretrained_embed=projection_pretrained_embed,\n att_weighted_src_embeds=att_weighted_src_embeds,\n src_embed_dim=src_embed_dim,\n att_weighted_activation_type=att_weighted_activation_type,\n )\n encoder_hidden_dim = max(1, encoder_hidden_dim)\n self.encoder_hidden_dim = encoder_hidden_dim\n self.embed_dim = embed_dim\n self.hidden_dim = hidden_dim\n self.out_embed_dim = out_embed_dim\n self.dropout_in = dropout_in\n self.dropout_out = dropout_out\n self.attention_type = attention_type\n self.residual_level = residual_level\n self.tie_embeddings = tie_embeddings\n\n num_embeddings = len(dst_dict)\n padding_idx = dst_dict.pad()\n self.embed_tokens = Embedding(\n num_embeddings=num_embeddings,\n embedding_dim=embed_dim,\n padding_idx=padding_idx,\n freeze_embed=freeze_embed,\n )\n if self.tie_embeddings:\n assert self.embed_dim == self.out_embed_dim, (\n \"Input embeddings and output projections must have the same \"\n \"dimension for the weights to be tied\"\n )\n self.embed_tokens.weight = self.output_projection_w\n else:\n pytorch_translate_utils.load_embedding(\n embedding=self.embed_tokens,\n dictionary=dst_dict,\n pretrained_embed=pretrained_embed,\n )\n\n self.hidden_dim = hidden_dim\n self.averaging_encoder = averaging_encoder\n\n if cell_type == \"lstm\":\n cell_class = rnn_cell.LSTMCell\n elif cell_type == \"milstm\":\n cell_class = rnn_cell.MILSTMCell\n elif cell_type == \"layer_norm_lstm\":\n cell_class = rnn_cell.LayerNormLSTMCell\n\n if hidden_dim != encoder_hidden_dim:\n hidden_init_fc_list = []\n cell_init_fc_list = []\n for _ in range(num_layers):\n hidden_init_fc_list.append(Linear(encoder_hidden_dim, hidden_dim))\n cell_init_fc_list.append(Linear(encoder_hidden_dim, hidden_dim))\n self.hidden_init_fc_list = nn.ModuleList(hidden_init_fc_list)\n self.cell_init_fc_list = nn.ModuleList(cell_init_fc_list)\n\n self.attention = attention.build_attention(\n attention_type=attention_type,\n decoder_hidden_state_dim=hidden_dim,\n context_dim=encoder_hidden_dim,\n )\n if self.attention.context_dim:\n self.initial_attn_context = nn.Parameter(\n torch.Tensor(self.attention.context_dim).zero_()\n )\n self.combined_output_and_context_dim = self.attention.context_dim + hidden_dim\n\n layers = []\n for layer in range(num_layers):\n if layer == 0:\n cell_input_dim = embed_dim + self.attention.context_dim\n else:\n cell_input_dim = hidden_dim\n layers.append(cell_class(input_dim=cell_input_dim, hidden_dim=hidden_dim))\n self.layers = nn.ModuleList(layers)\n\n if self.combined_output_and_context_dim != out_embed_dim:\n self.additional_fc = Linear(\n self.combined_output_and_context_dim, out_embed_dim\n )\n\n def forward_unprojected(self, input_tokens, encoder_out, incremental_state=None):\n if incremental_state is not None:\n input_tokens = input_tokens[:, -1:]\n bsz, seqlen = input_tokens.size()\n\n # get outputs from encoder\n (\n encoder_outs,\n final_hidden,\n final_cell,\n src_lengths,\n src_tokens,\n _,\n ) = encoder_out\n\n # embed tokens\n x = self.embed_tokens(input_tokens)\n x = F.dropout(x, p=self.dropout_in, training=self.training)\n # B x T x C -> T x B x C\n x = x.transpose(0, 1)\n\n # initialize previous states (or get from cache during incremental generation)\n cached_state = utils.get_incremental_state(\n self, incremental_state, \"cached_state\"\n )\n input_feed = None\n if cached_state is not None:\n prev_hiddens, prev_cells, input_feed = cached_state\n else:\n # first time step, initialize previous states\n init_prev_states = self._init_prev_states(encoder_out)\n prev_hiddens = []\n prev_cells = []\n\n # init_prev_states may or may not include initial attention context\n for (h, c) in zip(init_prev_states[0::2], init_prev_states[1::2]):\n prev_hiddens.append(h)\n prev_cells.append(c)\n if self.attention.context_dim:\n input_feed = self.initial_attn_context.expand(\n bsz, self.attention.context_dim\n )\n\n attn_scores_per_step = []\n outs = []\n for j in range(seqlen):\n # input feeding: concatenate context vector from previous time step\n step_input = maybe_cat((x[j, :, :], input_feed), dim=1)\n previous_layer_input = step_input\n for i, rnn in enumerate(self.layers):\n # recurrent cell\n hidden, cell = rnn(step_input, (prev_hiddens[i], prev_cells[i]))\n\n # hidden state becomes the input to the next layer\n layer_output = F.dropout(\n hidden, p=self.dropout_out, training=self.training\n )\n\n if self.residual_level is not None and i >= self.residual_level:\n # TODO add an assert related to sizes here\n step_input = layer_output + previous_layer_input\n else:\n step_input = layer_output\n previous_layer_input = step_input\n\n # save state for next time step\n prev_hiddens[i] = hidden\n prev_cells[i] = cell\n\n out, step_attn_scores = self.attention(hidden, encoder_outs, src_lengths)\n input_feed = out\n attn_scores_per_step.append(step_attn_scores.unsqueeze(1))\n attn_scores = torch.cat(attn_scores_per_step, dim=1)\n # srclen x tgtlen x bsz -> bsz x tgtlen x srclen\n attn_scores = attn_scores.transpose(0, 2)\n combined_output_and_context = maybe_cat((hidden, out), dim=1)\n\n # save final output\n outs.append(combined_output_and_context)\n\n # cache previous states (no-op except during incremental generation)\n utils.set_incremental_state(\n self,\n incremental_state,\n \"cached_state\",\n (prev_hiddens, prev_cells, input_feed),\n )\n\n # collect outputs across time steps\n x = torch.cat(outs, dim=0).view(\n seqlen, bsz, self.combined_output_and_context_dim\n )\n\n # T x B x C -> B x T x C\n x = x.transpose(1, 0)\n\n # bottleneck layer\n if hasattr(self, \"additional_fc\"):\n x = self.additional_fc(x)\n x = F.dropout(x, p=self.dropout_out, training=self.training)\n return x, attn_scores\n\n def reorder_incremental_state(self, incremental_state, new_order):\n \"\"\"Reorder buffered internal state (for incremental generation).\"\"\"\n cached_state = utils.get_incremental_state(\n self, incremental_state, \"cached_state\"\n )\n if cached_state is None:\n return\n\n def reorder_state(state):\n if state is None:\n return None\n if isinstance(state, list):\n return [reorder_state(state_i) for state_i in state]\n return state.index_select(0, new_order)\n\n new_state = tuple(map(reorder_state, cached_state))\n utils.set_incremental_state(self, incremental_state, \"cached_state\", new_state)\n\n def max_positions(self):\n \"\"\"Maximum output length supported by the decoder.\"\"\"\n return int(1e5) # an arbitrary large number\n\n def _init_prev_states(self, encoder_out):\n (\n encoder_output,\n final_hiddens,\n final_cells,\n src_lengths,\n src_tokens,\n _,\n ) = encoder_out\n num_layers = len(self.layers)\n if self.averaging_encoder:\n # Use mean encoder hidden states\n prev_hiddens = [torch.mean(encoder_output, 0)] * num_layers\n else:\n # Simply return the final state of each layer\n prev_hiddens = [final_hiddens[i] for i in range(num_layers)]\n prev_cells = [final_cells[i] for i in range(num_layers)]\n\n if hasattr(self, \"hidden_init_fc_list\"):\n for i in range(num_layers):\n prev_hiddens[i] = self.hidden_init_fc_list[i](prev_hiddens[i])\n prev_cells[i] = self.cell_init_fc_list[i](prev_cells[i])\n\n prev_states = []\n for h, c in zip(prev_hiddens, prev_cells):\n prev_states.extend([h, c])\n if self.attention.context_dim:\n prev_states.append(self.initial_attn_context)\n\n return prev_states\n\n\n@register_model_architecture(\"rnn\", \"rnn\")\ndef base_architecture(args):\n # default architecture\n args.encoder_embed_dim = getattr(args, \"encoder_embed_dim\", 512)\n args.encoder_layers = getattr(args, \"encoder_layers\", 1)\n args.encoder_hidden_dim = getattr(args, \"encoder_hidden_dim\", 512)\n args.encoder_bidirectional = getattr(args, \"encoder_bidirectional\", False)\n args.encoder_dropout_in = getattr(args, \"encoder_dropout_in\", args.dropout)\n args.encoder_dropout_out = getattr(args, \"encoder_dropout_out\", args.dropout)\n args.encoder_pretrained_embed = getattr(args, \"encoder_pretrained_embed\", None)\n args.decoder_embed_dim = getattr(args, \"decoder_embed_dim\", 512)\n args.decoder_layers = getattr(args, \"decoder_layers\", 1)\n args.decoder_hidden_dim = getattr(args, \"decoder_hidden_dim\", 512)\n args.decoder_pretrained_embed = getattr(args, \"decoder_pretrained_embed\", None)\n args.decoder_out_embed_dim = getattr(args, \"decoder_out_embed_dim\", 512)\n args.decoder_out_pretrained_embed = getattr(\n args, \"decoder_out_pretrained_embed\", None\n )\n args.attention_type = getattr(args, \"attention_type\", \"dot\")\n args.decoder_dropout_in = getattr(args, \"decoder_dropout_in\", args.dropout)\n args.decoder_dropout_out = getattr(args, \"decoder_dropout_out\", args.dropout)\n args.averaging_encoder = getattr(args, \"averaging_encoder\", False)\n args.encoder_freeze_embed = getattr(args, \"encoder_freeze_embed\", False)\n args.decoder_freeze_embed = getattr(args, \"decoder_freeze_embed\", False)\n args.ngram_decoder = getattr(args, \"ngram_decoder\", None)\n args.multi_encoder = getattr(args, \"multi_encoder\", None)\n args.multi_decoder = getattr(args, \"multi_decoder\", None)\n args.multi_decoder_is_lm = getattr(args, \"multi_decoder_is_lm\", None)\n args.multiling_encoder_lang = getattr(args, \"multiling_encoder_lang\", None)\n args.multi_model_training_schedule = getattr(\n args, \"multi_model_training_schedule\", \"complete\"\n )\n args.multi_model_fixed_weights = getattr(args, \"multi_model_fixed_weights\", None)\n args.cell_type = getattr(args, \"cell_type\", \"lstm\")\n args.ngram_activation_type = getattr(args, \"ngram_activation_type\", \"relu\")\n vocab_reduction.set_arg_defaults(args)\n word_dropout.set_arg_defaults(args)\n args.sequence_lstm = getattr(args, \"sequence_lstm\", False)\n args.decoder_tie_embeddings = getattr(args, \"decoder_tie_embeddings\", False)\n args.encoder_pretrained_embed = getattr(args, \"encoder_pretrained_embed\", None)\n args.decoder_pretrained_embed = getattr(args, \"decoder_pretrained_embed\", None)\n args.decoder_out_pretrained_embed = getattr(\n args, \"decoder_out_pretrained_embed\", None\n )\n args.att_weighted_src_embeds = getattr(args, \"att_weighted_source_embeds\", False)\n args.att_weighted_activation_type = getattr(\n args, \"att_weighted_activation_type\", \"tanh\"\n )\n\n@register_model_architecture(\"rnn\", \"rnn_big_test\")\ndef rnn_big_test(args):\n base_architecture(args)\n args.encoder_embed_dim = 1024\n args.encoder_layers = 6\n args.encoder_hidden_dim = 1024\n args.decoder_embed_dim = 1024\n args.decoder_layers = 6\n args.decoder_hidden_dim = 1024\n args.decoder_out_embed_dim = 1024\n"
] | [
[
"torch.mean",
"torch.ones",
"torch.Tensor",
"torch.nn.functional.dropout",
"torch.nn.LSTM",
"torch.cat",
"torch.nn.ModuleList",
"torch.zeros",
"torch.nn.utils.rnn.pack_padded_sequence",
"torch.nn.utils.rnn.PackedSequence",
"torch.nn.utils.rnn.pad_packed_sequence",
"torch.arange"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
remo-rcm/pyremo2 | [
"59bd18d411944205db93c062439172f91ba99f83"
] | [
"pyremo/core/exp.py"
] | [
"\"\"\"Module for working and parsing Remo output files.\n\"\"\"\nimport os\nfrom pathlib import Path\n\nimport pandas as pd\nimport parse\nfrom tqdm import tqdm\n\nfile_pattern = \"e{usr_nr:3d}{exp_nr:3d}{type:1}{date}\"\nefile_pattern = \"e{usr_nr:3d}{exp_nr:3d}{type:1}_c{code:3d}_{date}\"\n\ndate_patterns = [\"%Y\", \"%Y%m\", \"%Y%m%d\", \"%Y%m%d\", \"%Y%m%d%H\", \"%Y%m%d%H%M\"]\n\npatterns = [efile_pattern, file_pattern]\n\n\ndef _find_files(dir, file_template=\"e*\", exclude=None):\n \"\"\"search a directory for remo output.\"\"\"\n pattern = file_template\n return [path.absolute() for path in Path(dir).rglob(pattern)]\n\n\ndef _parse_file(file):\n for pattern in patterns:\n finfo = parse.parse(pattern, file)\n if finfo:\n return finfo.named\n\n\ndef get_data_catalog(dir, parse_dates=False, exclude=None):\n filepathes = _find_files(dir, exclude=exclude)\n df_all = pd.DataFrame()\n for path in tqdm(filepathes):\n finfo = _parse_file(path.stem)\n if finfo is None:\n print(\"could not parse: \", path.stem)\n continue\n finfo[\"path\"] = str(path)\n finfo[\"suffix\"] = path.suffix\n df = pd.DataFrame(finfo, index=[0])\n if parse_dates:\n for dpat in date_patterns:\n try:\n df[\"date\"] = pd.to_datetime(df.date, format=dpat)\n break\n except Exception:\n pass\n df_all = df_all.append(df, ignore_index=True)\n try:\n df_all[\"code\"] = df_all.code.astype(pd.Int64Dtype())\n except Exception:\n pass\n return df_all\n\n\ndef move_data(sdir, tdir, **kwargs):\n \"\"\"move remo data according to type to different directories\"\"\"\n\n efile_dir = os.path.join(tdir, \"xe\")\n tfile_dir = os.path.join(tdir, \"xt\")\n ffile_dir = os.path.join(tdir, \"xf\")\n\n for dir in [efile_dir, tfile_dir, ffile_dir]:\n try:\n os.makedirs(dir)\n except Exception:\n print(\"Directory exists: {}\".format(dir))\n\n return get_data_catalog(tdir)\n\n\nclass RemoExpData:\n def __init__(self):\n pass\n"
] | [
[
"pandas.Int64Dtype",
"pandas.to_datetime",
"pandas.DataFrame"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
LemonLison/pystruct | [
"23c6d8f6ab34a88b63386a595debbfdfa13345fe",
"5606e643d1a0a3701b93b848a2a02c49e83c4f1e",
"5606e643d1a0a3701b93b848a2a02c49e83c4f1e",
"23c6d8f6ab34a88b63386a595debbfdfa13345fe",
"5606e643d1a0a3701b93b848a2a02c49e83c4f1e"
] | [
"pystruct/learners/n_slack_ssvm.py",
"pystruct/tests/test_models/test_node_type_edge_feature_graph_crf.py",
"benchmarks/random_tree_crf.py",
"pystruct/tests/test_models/test_multilabel_problem.py",
"pystruct/models/typed_crf.py"
] | [
"######################\n# (c) 2012 Andreas Mueller <[email protected]>\n# License: BSD 3-clause\n#\n# Implements structured SVM as described in Tsochantaridis et. al.\n# Support Vector Machines Learning for Interdependent\n# and Structures Output Spaces\n\nfrom time import time\n\nimport numpy as np\nimport cvxopt\nimport cvxopt.solvers\n\nfrom sklearn.externals.joblib import Parallel, delayed\nfrom sklearn.utils import gen_even_slices\n\nfrom .ssvm import BaseSSVM\nfrom ..utils import unwrap_pairwise, find_constraint\n\n\nclass NSlackSSVM(BaseSSVM):\n \"\"\"Structured SVM solver for the n-slack QP with l1 slack penalty.\n\n Implements margin rescaled structural SVM using\n the n-slack formulation and cutting plane method, solved using CVXOPT.\n The optimization is restarted in each iteration.\n\n Parameters\n ----------\n model : StructuredModel\n Object containing the model structure. Has to implement\n `loss`, `inference` and `loss_augmented_inference`.\n\n max_iter : int\n Maximum number of passes over dataset to find constraints.\n\n C : float\n Regularization parameter\n\n check_constraints : bool (default=True)\n Whether to check if the new \"most violated constraint\" is\n more violated than previous constraints. Helpful for stopping\n and debugging, but costly.\n\n verbose : int (default=0)\n Verbosity.\n\n negativity_constraint: list of ints\n Indices of parmeters that are constraint to be negative.\n This is useful for learning submodular CRFs (inference is formulated\n as maximization in SSVMs, flipping some signs).\n\n break_on_bad: bool (default=False)\n Whether to break (start debug mode) when inference was approximate.\n\n n_jobs : int, default=1\n Number of parallel jobs for inference. -1 means as many as cpus.\n\n show_loss_every : int, default=0\n Controlls how often the hamming loss is computed (for monitoring\n purposes). Zero means never, otherwise it will be computed very\n show_loss_every'th epoch.\n\n batch_size : int, default=100\n Number of constraints after which we solve the QP again.\n batch_size=-1 means that an update is performed only after going once\n over the whole training set.\n\n tol : float, default=-10\n Convergence tolerance. If dual objective decreases less than tol,\n learning is stopped. The default corresponds to ignoring the behavior\n of the dual objective and stop only if no more constraints can be\n found.\n\n inactive_threshold : float, default=1e-5\n Threshold for dual variable of a constraint to be considered inactive.\n\n inactive_window : float, default=50\n Window for measuring inactivity. If a constraint is inactive for\n ``inactive_window`` iterations, it will be pruned from the QP.\n If set to 0, no constraints will be removed.\n\n switch_to : None or string, default=None\n Switch to the given inference method if the previous method does not\n find any more constraints.\n\n logger : logger object, default=None\n Pystruct logger for storing the model or extracting additional\n information.\n\n Attributes\n ----------\n w : nd-array, shape=(model.size_joint_feature,)\n The learned weights of the SVM.\n\n old_solution : dict\n The last solution found by the qp solver.\n\n ``loss_curve_`` : list of float\n List of loss values if show_loss_every > 0.\n\n ``objective_curve_`` : list of float\n Cutting plane objective after each pass through the dataset.\n\n ``primal_objective_curve_`` : list of float\n Primal objective after each pass through the dataset.\n\n ``timestamps_`` : list of int\n Total training time stored before each iteration.\n\n References\n ----------\n * Tsochantaridis, Ioannis and Joachims, Thorsten and Hofmann, Thomas and\n Altun, Yasemin and Singer, Yoram: Large margin methods for structured\n and interdependent output variables, JMLR 2006\n\n * Joachims, Thorsten and Finley, Thomas and Yu, Chun-Nam John:\n Cutting-plane training of structural SVMs, JMLR 2009\n \"\"\"\n\n def __init__(self, model, max_iter=100, C=1.0, check_constraints=True,\n verbose=0, negativity_constraint=None, n_jobs=1,\n break_on_bad=False, show_loss_every=0, batch_size=100,\n tol=1e-3, inactive_threshold=1e-5,\n inactive_window=50, logger=None, switch_to=None):\n\n BaseSSVM.__init__(self, model, max_iter, C, verbose=verbose,\n n_jobs=n_jobs, show_loss_every=show_loss_every,\n logger=logger)\n\n self.negativity_constraint = negativity_constraint\n self.check_constraints = check_constraints\n self.break_on_bad = break_on_bad\n self.batch_size = batch_size\n self.tol = tol\n self.inactive_threshold = inactive_threshold\n self.inactive_window = inactive_window\n self.switch_to = switch_to\n\n def _solve_n_slack_qp(self, constraints, n_samples):\n C = self.C\n joint_features = [c[1] for sample in constraints for c in sample]\n losses = [c[2] for sample in constraints for c in sample]\n\n joint_feature_matrix = np.vstack(joint_features).astype(np.float)\n n_constraints = len(joint_features)\n P = cvxopt.matrix(np.dot(joint_feature_matrix, joint_feature_matrix.T))\n # q contains loss from margin-rescaling\n q = cvxopt.matrix(-np.array(losses, dtype=np.float))\n # constraints are a bit tricky. first, all alpha must be >zero\n idy = np.identity(n_constraints)\n tmp1 = np.zeros(n_constraints)\n # box constraint: sum of all alpha for one example must be <= C\n blocks = np.zeros((n_samples, n_constraints))\n first = 0\n for i, sample in enumerate(constraints):\n blocks[i, first: first + len(sample)] = 1\n first += len(sample)\n # positivity constraints:\n if self.negativity_constraint is None:\n #empty constraints\n zero_constr = np.zeros(0)\n joint_features_constr = np.zeros((0, n_constraints))\n else:\n joint_features_constr = joint_feature_matrix.T[self.negativity_constraint]\n zero_constr = np.zeros(len(self.negativity_constraint))\n\n # put together\n G = cvxopt.sparse(cvxopt.matrix(np.vstack((-idy, blocks,\n joint_features_constr))))\n tmp2 = np.ones(n_samples) * C\n h = cvxopt.matrix(np.hstack((tmp1, tmp2, zero_constr)))\n\n # solve QP model\n cvxopt.solvers.options['feastol'] = 1e-5\n try:\n solution = cvxopt.solvers.qp(P, q, G, h)\n except ValueError:\n solution = {'status': 'error'}\n if solution['status'] != \"optimal\":\n print(\"regularizing QP!\")\n P = cvxopt.matrix(np.dot(joint_feature_matrix, joint_feature_matrix.T)\n + 1e-8 * np.eye(joint_feature_matrix.shape[0]))\n solution = cvxopt.solvers.qp(P, q, G, h)\n if solution['status'] != \"optimal\":\n raise ValueError(\"QP solver failed. Try regularizing your QP.\")\n\n # Lagrange multipliers\n a = np.ravel(solution['x'])\n self.prune_constraints(constraints, a)\n self.old_solution = solution\n\n # Support vectors have non zero lagrange multipliers\n sv = a > self.inactive_threshold * C\n box = np.dot(blocks, a)\n if self.verbose > 1:\n print(\"%d support vectors out of %d points\" % (np.sum(sv),\n n_constraints))\n # calculate per example box constraint:\n print(\"Box constraints at C: %d\" % np.sum(1 - box / C < 1e-3))\n print(\"dual objective: %f\" % -solution['primal objective'])\n self.w = np.dot(a, joint_feature_matrix)\n return -solution['primal objective']\n\n def _check_bad_constraint(self, y_hat, slack, old_constraints):\n if slack < 1e-5:\n return True\n y_hat_plain = unwrap_pairwise(y_hat)\n\n already_active = np.any([True for y__, _, _ in old_constraints\n if np.all(y_hat_plain ==\n unwrap_pairwise(y__))])\n if already_active:\n return True\n\n # \"smart\" stopping criterion\n # check if most violated constraint is more violated\n # than previous ones by more then eps.\n # If it is less violated, inference was wrong/approximate\n if self.check_constraints:\n for con in old_constraints:\n # compute slack for old constraint\n slack_tmp = max(con[2] - np.dot(self.w, con[1]), 0)\n if self.verbose > 5:\n print(\"slack old constraint: %f\" % slack_tmp)\n # if slack of new constraint is smaller or not\n # significantly larger, don't add constraint.\n # if smaller, complain about approximate inference.\n if slack - slack_tmp < -1e-5:\n if self.verbose > 0:\n print(\"bad inference: %f\" % (slack_tmp - slack))\n if self.break_on_bad:\n raise ValueError(\"bad inference: %f\" % (slack_tmp -\n slack))\n return True\n\n return False\n\n def fit(self, X, Y, constraints=None, warm_start=None, initialize=True):\n \"\"\"Learn parameters using cutting plane method.\n\n Parameters\n ----------\n X : iterable\n Traing instances. Contains the structured input objects.\n No requirement on the particular form of entries of X is made.\n\n Y : iterable\n Training labels. Contains the strctured labels for inputs in X.\n Needs to have the same length as X.\n\n contraints : iterable\n Known constraints for warm-starts. List of same length as X.\n Each entry is itself a list of constraints for a given instance x .\n Each constraint is of the form [y_hat, delta_joint_feature, loss], where\n y_hat is a labeling, ``delta_joint_feature = joint_feature(x, y) - joint_feature(x, y_hat)``\n and loss is the loss for predicting y_hat instead of the true label\n y.\n\n initialize : boolean, default=True\n Whether to initialize the model for the data.\n Leave this true except if you really know what you are doing.\n \"\"\"\n if self.verbose:\n print(\"Training n-slack dual structural SVM\")\n cvxopt.solvers.options['show_progress'] = self.verbose > 3\n if initialize:\n self.model.initialize(X, Y)\n self.w = np.zeros(self.model.size_joint_feature)\n n_samples = len(X)\n stopping_criterion = False\n if constraints is None:\n # fresh start\n constraints = [[] for i in range(n_samples)]\n self.last_active = [[] for i in range(n_samples)]\n self.objective_curve_ = []\n self.primal_objective_curve_ = []\n self.timestamps_ = [time()]\n else:\n # warm start\n objective = self._solve_n_slack_qp(constraints, n_samples)\n try:\n # catch ctrl+c to stop training\n # we have to update at least once after going through the dataset\n for iteration in range(self.max_iter):\n # main loop\n self.timestamps_.append(time() - self.timestamps_[0])\n if self.verbose > 0:\n print(\"iteration %d\" % iteration)\n if self.verbose > 2:\n print(self)\n new_constraints = 0\n # generate slices through dataset from batch_size\n if self.batch_size < 1 and not self.batch_size == -1:\n raise ValueError(\"batch_size should be integer >= 1 or -1,\"\n \"got %s.\" % str(self.batch_size))\n batch_size = (self.batch_size if self.batch_size != -1 else\n len(X))\n n_batches = int(np.ceil(float(len(X)) / batch_size))\n slices = gen_even_slices(n_samples, n_batches)\n indices = np.arange(n_samples)\n slack_sum = 0\n for batch in slices:\n new_constraints_batch = 0\n verbose = max(0, self.verbose - 3)\n X_b = X[batch]\n Y_b = Y[batch]\n indices_b = indices[batch]\n candidate_constraints = Parallel(\n n_jobs=self.n_jobs, verbose=verbose)(\n delayed(find_constraint)(self.model, x, y, self.w)\n for x, y in zip(X_b, Y_b))\n\n # for each batch, gather new constraints\n for i, x, y, constraint in zip(indices_b, X_b, Y_b,\n candidate_constraints):\n # loop over samples in batch\n y_hat, delta_joint_feature, slack, loss = constraint\n slack_sum += slack\n\n if self.verbose > 3:\n print(\"current slack: %f\" % slack)\n\n if not loss > 0:\n # can have y != y_hat but loss = 0 in latent svm.\n # we need this here as djoint_feature is then != 0\n continue\n\n if self._check_bad_constraint(y_hat, slack,\n constraints[i]):\n continue\n\n constraints[i].append([y_hat, delta_joint_feature, loss])\n new_constraints_batch += 1\n\n # after processing the slice, solve the qp\n if new_constraints_batch:\n objective = self._solve_n_slack_qp(constraints,\n n_samples)\n new_constraints += new_constraints_batch\n\n self.objective_curve_.append(objective)\n self._compute_training_loss(X, Y, iteration)\n\n primal_objective = (self.C\n * slack_sum\n + np.sum(self.w ** 2) / 2)\n self.primal_objective_curve_.append(primal_objective)\n\n if self.verbose > 0:\n print(\"new constraints: %d, \"\n \"cutting plane objective: %f primal objective: %f\" %\n (new_constraints, objective, primal_objective))\n\n if new_constraints == 0:\n if self.verbose:\n print(\"no additional constraints\")\n stopping_criterion = True\n\n if (iteration > 1 and self.objective_curve_[-1]\n - self.objective_curve_[-2] < self.tol):\n if self.verbose:\n print(\"objective converged.\")\n stopping_criterion = True\n\n if stopping_criterion:\n if (self.switch_to is not None and\n self.model.inference_method != self.switch_to):\n if self.verbose:\n print(\"Switching to %s inference\" %\n str(self.switch_to))\n self.model.inference_method_ = \\\n self.model.inference_method\n self.model.inference_method = self.switch_to\n stopping_criterion = False\n continue\n else:\n break\n\n if self.verbose > 5:\n print(self.w)\n\n if self.logger is not None:\n self.logger(self, iteration)\n except KeyboardInterrupt:\n pass\n\n self.constraints_ = constraints\n if self.verbose and self.n_jobs == 1:\n print(\"calls to inference: %d\" % self.model.inference_calls)\n\n if verbose:\n print(\"Computing final objective.\")\n self.timestamps_.append(time() - self.timestamps_[0])\n self.primal_objective_curve_.append(self._objective(X, Y))\n self.objective_curve_.append(objective)\n if self.logger is not None:\n self.logger(self, 'final')\n return self\n\n def prune_constraints(self, constraints, a):\n # append list for new constraint\n # self.alpha is a list which has\n # an entry per sample. each sample has an int for each constraint,\n # saying when was it last used\n if self.inactive_window == 0:\n return\n k = 0\n for i, sample in enumerate(constraints):\n # if there are no constraints for this sample, do nothing:\n if not len(sample):\n continue\n # add self.last_active for any new constraint\n n_old_constraints_sample = len(self.last_active[i])\n if n_old_constraints_sample < len(sample):\n self.last_active[i] = np.hstack([self.last_active[i], [0]])\n # if inactive, count up\n inactive_this = (a[k:k + len(sample)] < self.inactive_threshold\n * self.C)\n self.last_active[i][inactive_this] += 1\n k += len(sample)\n assert(len(sample) == len(self.last_active[i]))\n\n # remove unused constraints:\n to_remove = self.last_active[i] > self.inactive_window\n self.last_active[i] = self.last_active[i][~to_remove]\n for j in np.where(to_remove)[0][::-1]:\n del sample[j]\n assert(len(sample) == len(self.last_active[i]))\n",
"import pytest\nimport numpy as np\nfrom numpy.testing import (assert_array_equal, assert_array_almost_equal,\n assert_almost_equal, assert_equal)\nfrom nose.tools import assert_raises\n\nfrom pystruct.models import NodeTypeEdgeFeatureGraphCRF, EdgeFeatureGraphCRF\n\nfrom pystruct.inference.linear_programming import lp_general_graph\nfrom pystruct.inference import compute_energy, get_installed\nfrom pystruct.utils import make_grid_edges, edge_list_to_features\nfrom pystruct.datasets import generate_blocks_multinomial\n\n\n\ndef test_checks():\n g = NodeTypeEdgeFeatureGraphCRF(\n 1 #how many node type?\n , [4] #how many labels per node type?\n , [3] #how many features per node type?\n , np.array([[3]]) #how many features per node type X node type? \n )\n\n g = NodeTypeEdgeFeatureGraphCRF(\n 2 #how many node type?\n , [2, 3 ] #how many labels per node type?\n , [4, 5] #how many features per node type?\n , np.array([[1, 2], [2,4]]) #how many features per node type X node type? \n )\n \n with pytest.raises(ValueError):\n g = NodeTypeEdgeFeatureGraphCRF(\n 3 #how many node type?\n , [2, 3 ] #how many labels per node type?\n , [4, 5] #how many features per node type?\n , np.array([[1, 2], [2,4]]) #how many features per node type X node type? \n )\n \n with pytest.raises(ValueError):\n g = NodeTypeEdgeFeatureGraphCRF(\n 2 #how many node type?\n , [2, 3 ] #how many labels per node type?\n , [4, 5, 3] #how many features per node type?\n , np.array([[1, 2], [2,4]]) #how many features per node type X node type? \n )\n\n with pytest.raises(ValueError):\n g = NodeTypeEdgeFeatureGraphCRF(\n 3 #how many node type?\n , [2, 3 ] #how many labels per node type?\n , [4, 5] #how many features per node type?\n , np.array([[1, 2], [2,4]]) #how many features per node type X node type? \n )\n\n with pytest.raises(ValueError):\n g = NodeTypeEdgeFeatureGraphCRF(\n 2 #how many node type?\n , [2, 3 ] #how many labels per node type?\n , [4, 5] #how many features per node type?\n , np.array([[1, 2, 3], [2,3,4]]) #how many features per node type X node type? \n )\n\n with pytest.raises(ValueError):\n g = NodeTypeEdgeFeatureGraphCRF(\n 2 #how many node type?\n , [2, 3 ] #how many labels per node type?\n , [4, 5] #how many features per node type?\n , np.array([[1, 2], [99,4]]) #how many features per node type X node type? \n )\n \ndef debug_joint_feature():\n # -------------------------------------------------------------------------------------------\n #print \"---MORE COMPLEX GRAPH :) ---------------------------------------------------------------------\"\n g = NodeTypeEdgeFeatureGraphCRF( \n 2 #how many node type?\n , [2, 3] #how many possible labels per node type?\n , [3, 4] #how many features per node type?\n , np.array([ [1, 2]\n , [2, 3]]) #how many features per node type X node type? \n )\n \n l_node_f = [ np.array([ [1,1,1], [2,2,2] ])\n , np.array([ [.11, .12, .13, .14], [.21, .22, .23, .24], [.31, .32, .33, .34]]) \n ]\n l_edges = [ np.array([[0, 1]]) #type 0 node 0 to type 0 node 0 \n , np.array([[0, 1]])\n , None\n , None\n ] \n l_edge_f = [ np.array([[.111]])\n , np.array([[.221, .222]])\n , None\n , None\n ]\n \n x = (l_node_f, l_edges, l_edge_f)\n #print \"- - - - - - - - - - - - - - - - - - - - - - - - - - - \"\n y = np.hstack([ np.array([0, 1]),\n np.array([0, 1, 2])\n ])\n #print y\n g.initialize(x, y)\n jf = g.joint_feature(x,y)\n #print \"joint_feature = \\n\", `jf`\n #print\n assert_array_equal(jf, jf)\n assert_array_almost_equal(jf\n , np.array(\n [ 1. , 1., 1. , 2., 2., 2. \n , 0.11 , 0.12 , 0.13 , 0.14 , 0.21 , 0.22 , 0.23 , 0.24 , 0.31 , 0.32 , 0.33 , 0.34 \n \n , 0. , 0.111, 0. , 0. , 0. , 0.221,\n 0. , 0. , 0. , 0. , 0. , 0.222, 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. \n ]))\n\n\ndef get_simple_graph_structure():\n g = NodeTypeEdgeFeatureGraphCRF(\n 1 #how many node type?\n , [4] #how many labels per node type?\n , [3] #how many features per node type?\n , np.array([[3]]) #how many features per node type X node type? \n )\n return g\n\ndef get_simple_graph():\n node_f = [ np.array([[1,1,1], \n [2,2,2]]) \n ]\n edges = [ np.array([[0,1]]) \n ] #an edge from 0 to 1\n edge_f = [ np.array([[3,3,3]]) \n ]\n return (node_f, edges, edge_f)\n\ndef get_simple_graph2():\n node_f = [ np.array([ [1,1,1]\n , [2,2,2]]) ]\n edges = [ np.array( [[0,1], #an edge from 0 to 1\n [0,0] #an edge from 0 to 0\n ]) ] \n edge_f = [ np.array([\n [3,3,3],\n [4,4,4]\n ]) ]\n return (node_f, edges, edge_f)\n\ndef test_flatten_unflattenY():\n \n g, (node_f, edges, edge_f) = get_simple_graph_structure(), get_simple_graph()\n y = np.array([1,2])\n l_nf = [ np.zeros((2,3)) ] #list of node feature , per type\n X = (l_nf, None, None) #we give no edge\n y_ref = [ np.array([1,2]) ]\n assert all( [ (y_typ1 == y_typ2).all() for y_typ1, y_typ2 in zip(g.unflattenY(X, y), y_ref) ])\n \n assert (y == g.flattenY(g.unflattenY(X, y))).all()\n\n #============================================ \n g, x, y = more_complex_graph()\n\n Y = [ np.array([0, 0]) \n , np.array([0, 0, 0]) #we start again at zero on 2nd type\n ]\n \n y = np.hstack([ np.array([0, 0]) \n , 2+np.array([0, 0, 0])\n ])\n l_nf = [ np.zeros( (2,3) ), np.zeros( (3, 4) )] #2 node with 3 features, 3 node with 4 features\n X = (l_nf, None, None) #we give no edge\n assert (g.flattenY(Y) == y).all()\n #print g.unflattenY(X, y)\n assert all( [ (y_typ1 == y_typ2).all() for y_typ1, y_typ2 in zip(g.unflattenY(X, y), Y) ])\n \n l_nf = [ np.zeros( (1,3) ), np.zeros( (3, 4) )] #2 node with 3 features, 3 node with 4 features\n X = (l_nf, None, None) #we give no edge\n assert_raises(ValueError, g.unflattenY, X, y)\n \ndef test_joint_feature():\n \n #print \"---SIMPLE---------------------------------------------------------------------\"\n g, (node_f, edges, edge_f) = get_simple_graph_structure(), get_simple_graph()\n \n x = (node_f, edges, edge_f)\n #print \"- - - - - - - - - - - - - - - - - - - - - - - - - - - \"\n y = np.array([1,2])\n \n# y = np.array([1,0])\n #print y\n g.initialize(x, y)\n jf = g.joint_feature(x,y)\n #print \"joint_feature = \\n\", `jf`\n #print\n assert_array_equal(g.joint_feature(x,y)\n , np.array([ 0., 0., 0., 1., 1., 1., 2., 2., 2., 0., 0., 0.\n , 0.,\n 0., 0., 0., 0., 0., 3., 0., 0., 0., 0., 0., 0., 0.,\n 0., 0., 0., 0., 0., 0., 0., 0., 3., 0., 0., 0., 0.,\n 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 3., 0.,\n 0., 0., 0., 0., 0., 0., 0., 0.])\n )\n \n #print \"- - - - - - - - - - - - - - - - - - - - - - - - - - - \"\n y = np.array([0,0])\n #print y\n g.initialize(x, y)\n jf = g.joint_feature(x,y)\n #print \"joint_feature = \\n\", `jf`\n #print\n assert_array_equal(g.joint_feature(x,y)\n , np.array([ 3., 3., 3., 0., 0., 0., 0., 0., 0., 0., 0., 0., 3.,\n 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,\n 0., 0., 3., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,\n 0., 0., 0., 0., 0., 3., 0., 0., 0., 0., 0., 0., 0.,\n 0., 0., 0., 0., 0., 0., 0., 0.])\n )\n\n #print \"- - - - - - - - - - - - - - - - - - - - - - - - - - - \"\n y = np.array([0,1])\n node_f = [ np.array([[1.1,1.2,1.3], [2.1,2.2,2.3]]) ]\n edge_f = [ np.array([[3.1,3.2,3.3]]) ]\n x = (node_f, edges, edge_f)\n g.initialize(x, y)\n jf = g.joint_feature(x,y)\n #print \"joint_feature = \\n\", `jf`\n \n assert_array_equal(g.joint_feature(x,y)\n , np.array([ 1.1, 1.2, 1.3, 2.1, 2.2, 2.3, 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 3.1, 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. , 0. , 0. , 3.2, 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ,\n 0. , 3.3, 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. ])\n )\n #print \"---SIMPLE + 2nd EDGE--------------------------------------------------------\"\n node_f, edges, edge_f = get_simple_graph2()\n\n x = (node_f, edges, edge_f)\n #print \"- - - - - - - - - - - - - - - - - - - - - - - - - - - \"\n y = np.array([1,2])\n #print y\n g.initialize(x, y)\n jf = g.joint_feature(x,y)\n #print \"joint_feature = \\n\", `jf`\n #print\n assert_array_equal(jf\n , np.array([ 0., 0., 0., 1., 1., 1., 2., 2., 2., 0., 0., 0., 0.,\n 0., 0., 0., 0., 4., 3., 0., 0., 0., 0., 0., 0., 0.,\n 0., 0., 0., 0., 0., 0., 0., 4., 3., 0., 0., 0., 0.,\n 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 4., 3., 0.,\n 0., 0., 0., 0., 0., 0., 0., 0.])\n )\n #print \"- - - - - - - - - - - - - - - - - - - - - - - - - - - \"\n y = np.array([0,0])\n #print y\n g.initialize(x, y)\n #print \"joint_feature = \\n\", `g.joint_feature(x,y)`\n #print\n assert_array_equal(g.joint_feature(x,y)\n , np.array([ 3., 3., 3., 0., 0., 0., 0., 0., 0., 0., 0., 0., 7.,\n 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,\n 0., 0., 7., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,\n 0., 0., 0., 0., 0., 7., 0., 0., 0., 0., 0., 0., 0.,\n 0., 0., 0., 0., 0., 0., 0., 0.])\n )\n\ndef more_complex_graph():\n g = NodeTypeEdgeFeatureGraphCRF( \n 2 #how many node type?\n , [2, 3] #how many labels per node type?\n , [3, 4] #how many features per node type?\n , np.array([ [1, 2]\n , [2, 3]]) #how many features per node type X node type? \n )\n \n# nodes = np.array( [[0,0], [0,1], [1, 0], [1, 1], [1, 2]] ) \n node_f = [ np.array([ [1,1,1], [2,2,2] ])\n , np.array([ [.11, .12, .13, .14], [.21, .22, .23, .24], [.31, .32, .33, .34]]) \n ]\n edges = [ np.array( [ [0,1] #an edge from 0 to 1\n ])\n , np.array( [ \n [0,0] #an edge from typ0:0 to typ1:0 \n ])\n , None\n , None\n ] \n edge_f = [ np.array([[.111]])\n , np.array([[.221, .222]])\n , None\n , None\n ]\n \n x = (node_f, edges, edge_f)\n y = np.hstack([ np.array([0, 0]) \n , 2+np.array([0, 0, 0])\n ])\n return g, x, y\n \ndef test_joint_feature2():\n\n # -------------------------------------------------------------------------------------------\n #print \"---MORE COMPLEX GRAPH :) ---------------------------------------------------------------------\"\n g, x, y = more_complex_graph()\n #print y\n \n \n g.initialize(x, y)\n jf = g.joint_feature(x,y)\n #print \"joint_feature = \\n\", `jf`\n #print\n assert_array_equal(jf, jf)\n assert_array_almost_equal(jf\n , np.array([ 3. , 3. , 3. , 0. , 0. , 0. , 0.63 , 0.66 ,\n 0.69 , 0.72 , 0. , 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0.111, 0. , 0. , 0. , 0.221, 0. ,\n 0. , 0. , 0. , 0. , 0.222, 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ]))\n\n #print \"---MORE COMPLEX GRAPH :) -- BIS -------------------------------------------------------------------\"\n g = NodeTypeEdgeFeatureGraphCRF( \n 2 #how many node type?\n , [2, 3] #how many labels per node type?\n , [3, 4] #how many features per node type?\n , np.array([ [1, 2]\n , [2, 3]]) #how many features per node type X node type? \n )\n \n node_f = [ np.array([ [1,1,1], [2,2,2] ])\n , np.array([ [.11, .12, .13, .14], [.21, .22, .23, .24], [.31, .32, .33, .34]]) \n ]\n edges = [ np.array( [ [0,1]] ), #an edge from 0 to 1\n np.array( [ [0,2]] ) #an edge from 0 to 2\n , None, None\n ] \n edge_f = [ np.array([[.111]])\n , np.array([[.221, .222]])\n , None\n , None\n ]\n \n x = ( node_f, edges, edge_f)\n #print \"- - - - - - - - - - - - - - - - - - - - - - - - - - - \"\n y = np.hstack([np.array([0, 1]),\n 2+np.array([0, 1, 2])])\n #print y\n g.initialize(x, y)\n jf = g.joint_feature(x,y)\n #print \"joint_feature = \\n\", `jf`\n #print\n assert_array_equal(jf, jf)\n assert_array_almost_equal(jf\n , np.array([ 1. , 1. , 1. , 2. , 2. , 2. , 0.11 , 0.12 ,\n 0.13 , 0.14 , 0.21 , 0.22 , 0.23 , 0.24 , 0.31 , 0.32 ,\n 0.33 , 0.34 , 0. , 0.111, 0. , 0. , 0. , 0. ,\n 0.221, 0. , 0. , 0. , 0. , 0. , 0.222, 0. ,\n 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ]))\n \n #print \"MORE COMPLEX GRAPH :) -- BIS OK\"\n #print \"--- REORDERED MORE COMPLEX GRAPH :) ---------------------------------------------------------------------\"\n node_f = [ np.array([ [2,2,2], [1,1,1] ])\n , np.array([ [.31, .32, .33, .34], [.11, .12, .13, .14], [.21, .22, .23, .24]]) \n ]\n edges = [ np.array( [ [1, 0]] ),\n np.array( [ [1,0]] ) #an edge from 0 to 2\n , None, None\n ] \n edge_f = [ np.array([[.111]])\n , np.array([[.221, .222]])\n , None\n , None\n ]\n \n x = ( node_f, edges, edge_f)\n #print \"- - - - - - - - - - - - - - - - - - - - - - - - - - - \"\n y = np.hstack([np.array([1, 0]),\n 2+np.array([2, 0, 1])])\n #print y\n g.initialize(x, y)\n jf = g.joint_feature(x,y)\n #print \"joint_feature = \\n\", `jf`\n #print\n assert_array_equal(jf, jf)\n assert_array_almost_equal(jf\n , np.array([ 1. , 1. , 1. , 2. , 2. , 2. , 0.11 , 0.12 ,\n 0.13 , 0.14 , 0.21 , 0.22 , 0.23 , 0.24 , 0.31 , 0.32 ,\n 0.33 , 0.34 , 0. , 0.111, 0. , 0. , 0. , 0. ,\n 0.221, 0. , 0. , 0. , 0. , 0. , 0.222, 0. ,\n 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ]))\n \ndef test_joint_feature3():\n\n # -------------------------------------------------------------------------------------------\n #print \"---MORE COMPLEX GRAPH AGAIN :) ---------------------------------------------------------------------\"\n g = NodeTypeEdgeFeatureGraphCRF( \n 2 #how many node type?\n , [2, 3] #how many labels per node type?\n , [3, 4] #how many features per node type?\n , np.array([ [0, 2]\n , [2, 3]]) #how many features per node type X node type? \n )\n \n# nodes = np.array( [[0,0], [0,1], [1, 0], [1, 1], [1, 2]] ) \n node_f = [ np.array([ [1,1,1], [2,2,2] ])\n , np.array([ [.11, .12, .13, .14], [.21, .22, .23, .24], [.31, .32, .33, .34]]) \n ]\n edges = [ None\n , np.array( [ \n [0,1] #an edge from typ0:0 to typ1:1 \n ])\n , None\n , np.array( [ \n [0,1], #an edge from typ0:0 to typ1:1 \n [1,2] #an edge from typ1:1 to typ1:2 \n ])\n ] \n edge_f = [ None\n , np.array([[.221, .222]])\n , None\n , np.array([[.01, .02, .03 ],\n [.001, .002, .003]])\n ]\n \n x = (node_f, edges, edge_f)\n #print \"- - - - - - - - - - - - - - - - - - - - - - - - - - - \"\n y = np.hstack([ np.array([0, 0]) \n , 2+np.array([0, 0, 0])\n ])\n #print y\n g.initialize(x, y)\n #print g.size_unaries\n #print g.size_pairwise\n jf = g.joint_feature(x,y)\n #print \"joint_feature = \\n\", `jf`\n #print\n assert_array_equal(jf, jf)\n assert_array_almost_equal(jf\n , np.array([ 3. , 3. , 3. , 0. , 0. , 0. , \n 0.63 , 0.66 , 0.69 , 0.72 , 0. , 0., 0., 0. , 0., 0., 0. , 0.,\n #edges 0 to 0 2x2 states\n #typ0 typ0 EMPTY\n #typ0 typ1\n .221, 0., 0., 0., 0., 0.,\n .222, 0., 0., 0., 0., 0.,\n #typ1 typ0\n 0., 0., 0., 0., 0., 0.,\n 0., 0., 0., 0., 0., 0.,\n #typ1 typ1\n 0.011, 0., 0., 0., 0., 0., 0., 0., 0., \n 0.022, 0., 0., 0., 0., 0., 0., 0., 0.,\n 0.033, 0., 0., 0., 0., 0., 0., 0., 0.\n ])\n )\n\n #print \"- - - - - - - - - - - - - - - - - - - - - - - - - - - \"\n y = np.hstack([ np.array([0, 1]) \n , 2+np.array([1, 1, 0])\n ])\n #print y\n g.initialize(x, y)\n jf = g.joint_feature(x,y)\n #print \"joint_feature = \\n\", `jf`\n #print\n assert_array_equal(jf, jf)\n assert_array_almost_equal(jf\n , np.array([ 1. , 1. , 1. , 2. , 2. , 2. , \n .31, .32, .33, .34 , .32, .34, .36, .38 , 0., 0., 0. , 0.,\n #edges 0 to 0 2x2 states\n #typ0 typ0 EMPTY\n #typ0 typ1\n 0., .221, 0., 0., 0., 0.,\n 0., .222, 0., 0., 0., 0.,\n #typ1 typ0\n 0., 0., 0., 0., 0., 0.,\n 0., 0., 0., 0., 0., 0.,\n #typ1 typ1\n 0., 0., 0., 0.001, 0.01, 0., 0., 0., 0., \n 0., 0., 0., 0.002, 0.02, 0., 0., 0., 0.,\n 0., 0., 0., 0.003, 0.03, 0., 0., 0., 0.\n ])\n )\n\n w = np.array([ 1,1,1, 2,2,2, 10,10,10,10, 20,20,20,20, 30,30,30,30 ]\n +[1.0]*51, dtype=np.float64\n )\n #print `w`\n ret_u = g._get_unary_potentials(x, w)\n #print `ret_u`\n assert len(ret_u) == 2\n assert_array_almost_equal(ret_u[0], np.array([ #n_nodes x n_states\n [3, 6],\n [6, 12]]))\n\n assert_array_almost_equal(ret_u[1], np.array([ #n_nodes x n_states\n [5, 10, 15],\n [9, 18, 27],\n [13, 26, 39]]))\n \n assert len(w) == g.size_joint_feature\n ret_pw = g._get_pairwise_potentials(x, w)\n # for _pw in ret_pw:\n # print \"_pw \", `_pw`\n pw00, pw01, pw10, pw11 = ret_pw\n assert len(pw00) == 0\n assert_array_almost_equal(pw01,np.array([ #n_edges, n_states, n_states\n [[0.443, 0.443, 0.443],\n [0.443, 0.443, 0.443]]\n ]))\n assert len(pw10) == 0\n \n assert_array_almost_equal(pw11,np.array([ #n_edges, n_states, n_states\n [[0.06 , 0.06 , 0.06],\n [0.06 , 0.06 , 0.06],\n [0.06 , 0.06 , 0.06]]\n ,\n [[0.006, 0.006, 0.006],\n [0.006, 0.006, 0.006],\n [0.006, 0.006, 0.006]] \n ]))\n\n\n\ndef test_unary_potentials():\n #print \"---SIMPLE---------------------------------------------------------------------\"\n #g, (node_f, edges, edge_f) = get_simple_graph_structure(), get_simple_graph()\n\n g = NodeTypeEdgeFeatureGraphCRF(\n 1 #how many node type?\n , [4] #how many labels per node type?\n , [3] #how many features per node type?\n , np.array([[3]]) #how many features per node type X node type? \n )\n node_f = [ np.array([[1,1,1], \n [2,2,2]]) \n ]\n edges = [ np.array([[0,1]]) \n ] #an edge from 0 to 1\n edge_f = [ np.array([[3,3,3]]) \n ]\n x = (node_f, edges, edge_f)\n #print \"- - - - - - - - - - - - - - - - - - - - - - - - - - - \"\n y = np.hstack([ np.array([1,2])])\n# y = np.array([1,0])\n #print y\n g.initialize(x, y)\n \n gref = EdgeFeatureGraphCRF(4,3,3)\n xref = (node_f[0], edges[0], edge_f[0])\n wref = np.arange(gref.size_joint_feature)\n potref = gref._get_unary_potentials(xref, wref)\n #print `potref`\n \n w = np.arange(g.size_joint_feature)\n pot = g._get_unary_potentials(x, w)\n #print `pot`\n assert_array_equal(pot, [potref])\n\n pwpotref = gref._get_pairwise_potentials(xref, wref)\n #print `pwpotref`\n pwpot = g._get_pairwise_potentials(x, w)\n #print `pwpot`\n assert_array_equal(pwpot, [pwpotref])\n \n# def test_inference_util():\n# g = NodeTypeEdgeFeatureGraphCRF( \n# 3 #how many node type?\n# , [2, 3, 1] #how many labels per node type?\n# , [3, 4, 1] #how many features per node type?\n# , np.array([ [1, 2, 2]\n# , [2, 3, 2]\n# , [2, 2, 1]]) #how many features per node type X node type? \n# )\n# node_f = [ np.array([ [2,2,2], [1,1,1] ])\n# , np.array([ [.31, .32, .33, .34], [.11, .12, .13, .14], [.21, .22, .23, .24]]) \n# , np.array([ [77], [88], [99]]) \n# ]\n# edges = [ np.array( [ [1, 0]] ),\n# np.array( [ [1,0]] ) #an edge from 0 to 2\n# , None\n# \n# , None\n# , None\n# , None\n# \n# , np.array( [[1,1]] )\n# , None\n# , None ] \n# \n# x = ( node_f, edges, None)\n# \n# reindexed_exdges = g._index_all_edges(x)\n# #print `reindexed_exdges`\n# assert_array_equal(reindexed_exdges,\n# np.array( [[1,0],\n# [1,2],\n# [6,1]]))\n# \n\n# def report_model_config(crf):\n# print crf.n_states\n# print crf.n_features\n# print crf.n_edge_features\n\ndef inference_data():\n \"\"\"\n Testing with a single type of nodes. Must do as well as EdgeFeatureGraphCRF\n \"\"\"\n # Test inference with different weights in different directions\n\n X, Y = generate_blocks_multinomial(noise=2, n_samples=1, seed=1)\n x, y = X[0], Y[0]\n n_states = x.shape[-1]\n\n edge_list = make_grid_edges(x, 4, return_lists=True)\n edges = np.vstack(edge_list)\n\n pw_horz = -1 * np.eye(n_states)\n xx, yy = np.indices(pw_horz.shape)\n # linear ordering constraint horizontally\n pw_horz[xx > yy] = 1\n\n # high cost for unequal labels vertically\n pw_vert = -1 * np.eye(n_states)\n pw_vert[xx != yy] = 1\n pw_vert *= 10\n\n # generate edge weights\n edge_weights_horizontal = np.repeat(pw_horz[np.newaxis, :, :],\n edge_list[0].shape[0], axis=0)\n edge_weights_vertical = np.repeat(pw_vert[np.newaxis, :, :],\n edge_list[1].shape[0], axis=0)\n edge_weights = np.vstack([edge_weights_horizontal, edge_weights_vertical])\n\n # do inference\n res = lp_general_graph(-x.reshape(-1, n_states), edges, edge_weights)\n\n edge_features = edge_list_to_features(edge_list)\n x = ([x.reshape(-1, n_states)], [edges], [edge_features])\n y = y.ravel()\n return x, y, pw_horz, pw_vert, res, n_states\n \ndef test_inference_ad3plus():\n \n x, y, pw_horz, pw_vert, res, n_states = inference_data()\n # same inference through CRF inferface\n crf = NodeTypeEdgeFeatureGraphCRF(1, [3], [3], [[2]]\n , inference_method=\"ad3+\") \n crf.initialize(x, y)\n #crf.initialize([x], [y])\n w = np.hstack([np.eye(3).ravel(), -pw_horz.ravel(), -pw_vert.ravel()])\n y_pred = crf.inference(x, w, relaxed=True)\n if isinstance(y_pred, tuple):\n # ad3 produces an integer result if it found the exact solution\n #np.set_printoptions(precision=2, threshold=9999)\n assert_array_almost_equal(res[0], y_pred[0][0].reshape(-1, n_states), 5)\n assert_array_almost_equal(res[1], y_pred[1][0], 5)\n assert_array_equal(y, np.argmax(y_pred[0][0], axis=-1), 5)\n\n # again, this time discrete predictions only\n crf = NodeTypeEdgeFeatureGraphCRF(1, [3], [3], [[2]]\n , inference_method=\"ad3+\") \n #crf.initialize([x], [y])\n w = np.hstack([np.eye(3).ravel(), -pw_horz.ravel(), -pw_vert.ravel()])\n crf.initialize(x)\n y_pred = crf.inference(x, w, relaxed=False)\n assert_array_equal(y, y_pred)\n\ndef test_inference_ad3():\n \n x, y, pw_horz, pw_vert, res, n_states = inference_data()\n # same inference through CRF inferface\n crf = NodeTypeEdgeFeatureGraphCRF(1, [3], [3], [[2]]\n , inference_method=\"ad3\") \n crf.initialize(x, y)\n #crf.initialize([x], [y])\n w = np.hstack([np.eye(3).ravel(), -pw_horz.ravel(), -pw_vert.ravel()])\n y_pred = crf.inference(x, w, relaxed=True)\n if isinstance(y_pred, tuple):\n # ad3 produces an integer result if it found the exact solution\n #np.set_printoptions(precision=2, threshold=9999)\n assert_array_almost_equal(res[0], y_pred[0][0].reshape(-1, n_states), 5)\n assert_array_almost_equal(res[1], y_pred[1][0], 5)\n assert_array_equal(y, np.argmax(y_pred[0][0], axis=-1), 5)\n\n # again, this time discrete predictions only\n crf = NodeTypeEdgeFeatureGraphCRF(1, [3], [3], [[2]]\n , inference_method=\"ad3\") \n #crf.initialize([x], [y])\n w = np.hstack([np.eye(3).ravel(), -pw_horz.ravel(), -pw_vert.ravel()])\n crf.initialize(x)\n y_pred = crf.inference(x, w, relaxed=False)\n assert_array_equal(y, y_pred)\n\ndef test_joint_feature_discrete():\n \"\"\"\n Testing with a single type of nodes. Must de aw well as EdgeFeatureGraphCRF\n \"\"\"\n X, Y = generate_blocks_multinomial(noise=2, n_samples=1, seed=1)\n x, y = X[0], Y[0]\n edge_list = make_grid_edges(x, 4, return_lists=True)\n edges = np.vstack(edge_list)\n edge_features = edge_list_to_features(edge_list)\n x = ([x.reshape(-1, 3)], [edges], [edge_features])\n y_flat = y.ravel()\n #for inference_method in get_installed([\"lp\", \"ad3\", \"qpbo\"]):\n if True:\n crf = NodeTypeEdgeFeatureGraphCRF(1, [3], [3], [[2]])\n joint_feature_y = crf.joint_feature(x, y_flat)\n assert_equal(joint_feature_y.shape, (crf.size_joint_feature,))\n # first horizontal, then vertical\n # we trust the unaries ;)\n n_states = crf.l_n_states[0]\n n_features = crf.l_n_features[0]\n pw_joint_feature_horz, pw_joint_feature_vert = joint_feature_y[n_states *\n n_features:].reshape(\n 2, n_states, n_states)\n assert_array_equal(pw_joint_feature_vert, np.diag([9 * 4, 9 * 4, 9 * 4]))\n vert_joint_feature = np.diag([10 * 3, 10 * 3, 10 * 3])\n vert_joint_feature[0, 1] = 10\n vert_joint_feature[1, 2] = 10\n assert_array_equal(pw_joint_feature_horz, vert_joint_feature)\n\ndef test_joint_feature_continuous():\n \"\"\"\n Testing with a single type of nodes. Must de aw well as EdgeFeatureGraphCRF\n \"\"\"\n # FIXME\n # first make perfect prediction, including pairwise part\n X, Y = generate_blocks_multinomial(noise=2, n_samples=1, seed=1)\n x, y = X[0], Y[0]\n n_states = x.shape[-1]\n edge_list = make_grid_edges(x, 4, return_lists=True)\n edges = np.vstack(edge_list)\n edge_features = edge_list_to_features(edge_list)\n #x = (x.reshape(-1, 3), edges, edge_features)\n x = ([x.reshape(-1, 3)], [edges], [edge_features])\n y = y.ravel()\n\n pw_horz = -1 * np.eye(n_states)\n xx, yy = np.indices(pw_horz.shape)\n # linear ordering constraint horizontally\n pw_horz[xx > yy] = 1\n\n # high cost for unequal labels vertically\n pw_vert = -1 * np.eye(n_states)\n pw_vert[xx != yy] = 1\n pw_vert *= 10\n\n # create crf, assemble weight, make prediction\n# for inference_method in get_installed([\"lp\", \"ad3\"]):\n# crf = EdgeFeatureGraphCRF(inference_method=inference_method)\n if True:\n crf = NodeTypeEdgeFeatureGraphCRF(1, [3], [3], [[2]])\n \n w = np.hstack([np.eye(3).ravel(), -pw_horz.ravel(), -pw_vert.ravel()])\n #crf.initialize([x], [y])\n #report_model_config(crf)\n crf.initialize(x, y)\n \n y_pred = crf.inference(x, w, relaxed=True)\n\n # compute joint_feature for prediction\n joint_feature_y = crf.joint_feature(x, y_pred)\n assert_equal(joint_feature_y.shape, (crf.size_joint_feature,))\n # FIXME\n # first horizontal, then vertical\n # we trust the unaries ;)\n #pw_joint_feature_horz, pw_joint_feature_vert = joint_feature_y[crf.n_states *\n #crf.n_features:].reshape(2,\n #crf.n_states,\n #crf.n_states)\n\ndef test_energy_continuous():\n # make sure that energy as computed by ssvm is the same as by lp\n np.random.seed(0)\n #for inference_method in get_installed([\"lp\", \"ad3\"]):\n if True:\n found_fractional = False\n crf = NodeTypeEdgeFeatureGraphCRF(1, [3], [3], [[2]])\n\n while not found_fractional:\n x = np.random.normal(size=(7, 8, 3))\n edge_list = make_grid_edges(x, 4, return_lists=True)\n edges = np.vstack(edge_list)\n edge_features = edge_list_to_features(edge_list)\n x = ([x.reshape(-1, 3)], [edges], [edge_features])\n\n unary_params = np.random.normal(size=(3, 3))\n pw1 = np.random.normal(size=(3, 3))\n pw2 = np.random.normal(size=(3, 3))\n w = np.hstack([unary_params.ravel(), pw1.ravel(), pw2.ravel()])\n crf.initialize(x)\n res, energy = crf.inference(x, w, relaxed=True, return_energy=True)\n found_fractional = np.any(np.max(res[0], axis=-1) != 1)\n joint_feature = crf.joint_feature(x, res)\n energy_svm = np.dot(joint_feature, w)\n\n assert_almost_equal(energy, -energy_svm)\n\ndef test_energy_discrete():\n# for inference_method in get_installed([\"qpbo\", \"ad3\"]):\n# crf = EdgeFeatureGraphCRF(n_states=3,\n# inference_method=inference_method,\n# n_edge_features=2, n_features=3)\n crf = NodeTypeEdgeFeatureGraphCRF(1, [3], [3], [[2]])\n \n for i in range(10):\n x = np.random.normal(size=(7, 8, 3))\n edge_list = make_grid_edges(x, 4, return_lists=True)\n edges = np.vstack(edge_list)\n edge_features = edge_list_to_features(edge_list)\n x = ([x.reshape(-1, 3)], [edges], [edge_features])\n\n unary_params = np.random.normal(size=(3, 3))\n pw1 = np.random.normal(size=(3, 3))\n pw2 = np.random.normal(size=(3, 3))\n w = np.hstack([unary_params.ravel(), pw1.ravel(), pw2.ravel()])\n crf.initialize(x)\n y_hat = crf.inference(x, w, relaxed=False)\n #flat_edges = crf._index_all_edges(x)\n energy = compute_energy(crf._get_unary_potentials(x, w)[0],\n crf._get_pairwise_potentials(x, w)[0], edges, #CAUTION: pass the flatened edges!!\n y_hat)\n\n joint_feature = crf.joint_feature(x, y_hat)\n energy_svm = np.dot(joint_feature, w)\n\n assert_almost_equal(energy, energy_svm)\n\n\nif __name__ == \"__main__\":\n np.set_printoptions(precision=3, linewidth=9999)\n\n if 0: \n debug_joint_feature()\n if 1:\n test_flatten_unflattenY()\n \n if 1:\n test_joint_feature()\n if 1:\n test_joint_feature2()\n if 1:\n test_joint_feature3()\n \n if 1: test_unary_potentials()\n# if 1: test_inference_util()\n if 1: test_inference_ad3()\n if 1: test_inference_ad3plus()\n if 1: test_joint_feature_discrete()\n if 1: test_joint_feature_continuous()\n if 1: test_energy_continuous()\n if 1: test_energy_discrete()\n \n #print \"OK\"\n",
"import numpy as np\nfrom scipy import sparse\n\ntry:\n from sklearn.model_selection import train_test_split\nexcept ImportError:\n from sklearn.cross_validation import train_test_split\n\nfrom scipy.sparse.csgraph import minimum_spanning_tree\n\nfrom pystruct.learners import SubgradientSSVM\nfrom pystruct.models import GraphCRF\n\n\ndef make_random_trees(n_samples=50, n_nodes=100, n_states=7, n_features=10):\n crf = GraphCRF(inference_method='max-product', n_states=n_states,\n n_features=n_features)\n weights = np.random.randn(crf.size_joint_feature)\n X, y = [], []\n for i in range(n_samples):\n distances = np.random.randn(n_nodes, n_nodes)\n features = np.random.randn(n_nodes, n_features)\n tree = minimum_spanning_tree(sparse.csr_matrix(distances))\n edges = np.c_[tree.nonzero()]\n X.append((features, edges))\n y.append(crf.inference(X[-1], weights))\n\n return X, y, weights\n\n\nX, y, weights = make_random_trees(n_nodes=1000)\n\nX_train, X_test, y_train, y_test = train_test_split(X, y)\n\n#tree_model = MultiLabelClf(edges=tree, inference_method=('ogm', {'alg': 'dyn'}))\ntree_model = GraphCRF(inference_method='max-product')\n\ntree_ssvm = SubgradientSSVM(tree_model, max_iter=4, C=1, verbose=10)\n\nprint(\"fitting tree model...\")\ntree_ssvm.fit(X_train, y_train)\n\nprint(\"Training loss tree model: %f\" % tree_ssvm.score(X_train, y_train))\nprint(\"Test loss tree model: %f\" % tree_ssvm.score(X_test, y_test))\n",
"import itertools\n\nimport numpy as np\nfrom numpy.testing import assert_array_equal, assert_array_almost_equal\nfrom nose.tools import assert_almost_equal, assert_equal, assert_raises\n\nfrom pystruct.models import MultiLabelClf\nfrom pystruct.inference import compute_energy\n\n\ndef test_initialization():\n x = np.random.normal(size=(13, 5))\n y = np.random.randint(2, size=(13, 3))\n # no edges make independent model\n model = MultiLabelClf()\n model.initialize(x, y)\n assert_equal(model.n_states, 2)\n assert_equal(model.n_labels, 3)\n assert_equal(model.n_features, 5)\n assert_equal(model.size_joint_feature, 5 * 3)\n\n # setting and then initializing is no-op\n model = MultiLabelClf(n_features=5, n_labels=3)\n model.initialize(x, y) # smoketest\n\n model = MultiLabelClf(n_features=3, n_labels=3)\n assert_raises(ValueError, model.initialize, X=x, Y=y)\n\n\ndef test_multilabel_independent():\n # test inference and energy with independent model\n edges = np.zeros((0, 2), dtype=np.int)\n n_features = 5\n n_labels = 4\n model = MultiLabelClf(n_labels=n_labels, n_features=n_features,\n edges=edges)\n rnd = np.random.RandomState(0)\n\n x = rnd.normal(size=5)\n w = rnd.normal(size=n_features * n_labels)\n # test inference\n y = model.inference(x, w)\n y_ = np.dot(w.reshape(n_labels, n_features), x) > 0\n assert_array_equal(y, y_)\n\n # test joint_feature / energy\n joint_feature = model.joint_feature(x, y)\n energy = compute_energy(model._get_unary_potentials(x, w),\n model._get_pairwise_potentials(x, w), edges, y)\n assert_almost_equal(energy, np.dot(joint_feature, w))\n\n # for continuous y\n y_continuous = np.zeros((n_labels, 2))\n y_continuous[np.arange(n_labels), y] = 1\n assert_array_almost_equal(\n joint_feature, model.joint_feature(x, (y_continuous, np.zeros((0, n_labels, n_labels)))))\n\n\ndef test_multilabel_fully():\n # test inference and energy with fully connected model\n n_features = 5\n n_labels = 4\n edges = np.vstack([x for x in itertools.combinations(range(n_labels), 2)])\n model = MultiLabelClf(n_labels=n_labels, n_features=n_features,\n edges=edges)\n rnd = np.random.RandomState(0)\n\n x = rnd.normal(size=n_features)\n w = rnd.normal(size=n_features * n_labels + 4 * len(edges))\n y = model.inference(x, w)\n\n # test joint_feature / energy\n joint_feature = model.joint_feature(x, y)\n energy = compute_energy(model._get_unary_potentials(x, w),\n model._get_pairwise_potentials(x, w), edges, y)\n assert_almost_equal(energy, np.dot(joint_feature, w))\n\n # for continuous y\n #y_cont = model.inference(x, w, relaxed=True)\n y_continuous = np.zeros((n_labels, 2))\n pairwise_marginals = []\n for edge in edges:\n # indicator of one of four possible states of the edge\n pw = np.zeros((2, 2))\n pw[y[edge[0]], y[edge[1]]] = 1\n pairwise_marginals.append(pw)\n\n pairwise_marginals = np.vstack(pairwise_marginals)\n\n y_continuous[np.arange(n_labels), y] = 1\n assert_array_almost_equal(\n joint_feature, model.joint_feature(x, (y_continuous, pairwise_marginals)))\n",
"# -*- coding: utf-8 -*-\n\n\"\"\"\n CRF with different types of nodes\n\n NOTE: this is an abstract class. Do not use directly.\n\n JL. Meunier\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\n Developed for the EU project READ. The READ project has received funding\n from the European Union's Horizon 2020 research and innovation programme\n under grant agreement No 674943.\n\n\"\"\"\nimport numpy as np\n\nfrom .crf import CRF\nfrom ..inference import get_installed\n\n\nclass InconsistentLabel(Exception):\n pass\n\n\nclass TypedCRF(CRF):\n \"\"\"Abstract base class\"\"\"\n def __init__(self,\n n_types, # how many node type?\n l_n_states, # how many labels per node type?\n l_n_features, # how many features per node type?\n inference_method=\"ad3\",\n l_class_weight=None): # class_weight per node type or None\n # <list of array-like> or None\n\n if inference_method is None:\n # get first in list that is installed\n inference_method = get_installed(['ad3+', 'ad3'])[0]\n self.setInferenceMethod(inference_method)\n\n self.inference_calls = 0\n # if inference cannot be done, raises an exception\n self.inference_exception = False\n\n if len(l_n_states) != n_types:\n raise ValueError(\"Expected 1 number of states per node type.\")\n if l_n_features is not None and len(l_n_features) != n_types:\n raise ValueError(\"Expected 1 number pf features per node type.\")\n self.n_types = n_types\n self.l_n_states = l_n_states\n self._n_states = sum(l_n_states) # total number of states\n self.l_n_features = l_n_features\n self._n_features = sum(self.l_n_features) # total number of node feat.\n\n # number of typextype states, or number of states per type of edge\n self.l_n_edge_states = [n1 * n2\n for n1 in self.l_n_states\n for n2 in self.l_n_states]\n\n # class weights:\n # either we get class weights for all types of nodes\n # , or for none of them!\n if l_class_weight:\n if len(l_class_weight) != self.n_types:\n raise ValueError(\"Expected 1 class weight list per node type.\")\n for i, n_states in enumerate(self.l_n_states):\n if len(l_class_weight[i]) != n_states:\n raise ValueError(\"Expected 1 class weight per state\"\n \" per node type. Wrong for type %d\" % i)\n\n # class weights are computed by type and simply concatenated\n self.l_class_weight = [np.asarray(class_weight)\n for class_weight in l_class_weight]\n else:\n self.l_class_weight = [np.ones(n) for n in self.l_n_states]\n self.class_weight = np.hstack(self.l_class_weight)\n\n self._set_size_joint_feature()\n\n # internal stuff\n # when putting node states in a single sequence, index of 1st state\n # for type i\n self._l_type_startindex = [sum(self.l_n_states[:i])\n for i in range(self.n_types+1)]\n\n # when putting edge states in a single sequence, index of 1st state of\n # an edge of type (typ1, typ2)\n self.a_startindex_by_typ_typ = np.zeros((self.n_types, self.n_types),\n dtype=np.uint32)\n i_state_start = 0\n for typ1, typ1_n_states in enumerate(self.l_n_states):\n for typ2, typ2_n_states in enumerate(self.l_n_states):\n self.a_startindex_by_typ_typ[typ1, typ2] = i_state_start\n i_state_start += typ1_n_states*typ2_n_states\n\n # -------------- CONVENIENCE --------------------------\n def setInferenceMethod(self, inference_method):\n if inference_method in [\"ad3\", \"ad3+\"]:\n self.inference_method = inference_method\n else:\n raise Exception(\"You must use ad3 or ad3+ as inference method\")\n\n def flattenY(self, lY_by_typ):\n \"\"\"\n It is more convenient to have the Ys grouped by type, as the Xs are,\n and to have the first label of each type encoded as 0.\n\n This method does the job. It returns a flat Y array, with unique code\n per class label, which can be passed to 'fit'\n \"\"\"\n lY = list()\n for n_start_state, Y_typ in zip(self._l_type_startindex, lY_by_typ):\n lY.append(np.asarray(Y_typ) + n_start_state)\n return np.hstack(lY)\n\n def unflattenY(self, X, flatY):\n \"\"\"\n predict returns a flat array of Y (same structure as for 'fit')\n This method structures the Y as a list of Y_per_type, where the first\n label of any type is 0\n \"\"\"\n lY = list()\n i_start_node = 0\n (l_node_features, l_edges, l_edge_features) = X\n for n_start_state, nf in zip(self._l_type_startindex, l_node_features):\n n_nodes = nf.shape[0]\n Y = flatY[i_start_node: i_start_node+n_nodes] - n_start_state\n lY.append(Y)\n i_start_node += n_nodes\n if flatY.shape != (i_start_node,):\n raise ValueError(\"The total number of label does not match the\"\n \" total number of nodes:\"\n \" %d != %d\" % (flatY.shape[0], i_start_node))\n return lY\n\n def initialize(self, X, Y=None):\n \"\"\"\n It is optional to call it. Does data checking only!\n \"\"\"\n if isinstance(X, list):\n map(self._check_size_x, X)\n if not (Y is None):\n map(self._check_size_xy, X, Y)\n else:\n self._check_size_x(X)\n self._check_size_xy(X, Y)\n\n def setInferenceException(self, bRaiseExceptionWhenInferenceNotSuccessful):\n \"\"\"\n set exception on or off when inference canoot be done.\n \"\"\"\n self.inference_exception = bRaiseExceptionWhenInferenceNotSuccessful\n return self.inference_exception\n\n # -------------- INTERNAL STUFF --------------------------\n def _set_size_joint_feature(self):\n \"\"\"\n We have:\n - 1 weight per node feature per label per node type\n \"\"\"\n self.size_unaries = sum(n_states * n_features for n_states, n_features\n in zip(self.l_n_states, self.l_n_features)\n )\n self.size_joint_feature = self.size_unaries\n\n def __repr__(self):\n return (\"%s(n_states: %s, inference_method: %s)\"\n % (type(self).__name__, self.l_n_states,\n self.inference_method))\n\n def _check_size_x(self, x):\n # node_features are [ i_in_typ -> features ]\n l_node_features = self._get_node_features(x)\n if len(l_node_features) != self.n_types:\n raise ValueError(\"Expected one node feature array per node type.\")\n\n for typ, typ_features in enumerate(l_node_features):\n if typ_features.shape[1] != self.l_n_features[typ]:\n raise ValueError(\"Expected %d features for type\"\n \" %d\" % (self.l_n_features[typ], typ))\n\n # edges\n l_edges = self._get_edges(x)\n for edges in l_edges:\n if edges is None:\n continue\n if edges.ndim != 2:\n raise ValueError(\"Expected a 2 dimensions edge arrays\")\n if edges.shape[1] != 2:\n raise ValueError(\"Expected 2 columns in edge arrays\")\n\n for typ1, typ2 in self._iter_type_pairs():\n edges = self._get_edges_by_type(x, typ1, typ2)\n\n if edges is None or len(edges) == 0:\n continue\n # edges should point to valid node indices\n nodes1, nodes2 = edges[:, 0], edges[:, 1]\n if min(nodes1) < 0 or min(nodes2) < 0:\n raise ValueError(\"At least one edge points to negative and\"\n \" therefore invalid node index:\"\n \" type %d to type %d\" % (typ1, typ2))\n if max(nodes1) >= l_node_features[typ1].shape[0]:\n raise ValueError(\"At least one edge starts from a non-existing\"\n \" node index:\"\n \" type %d to type %d\" % (typ1, typ2))\n if max(nodes2) >= l_node_features[typ2].shape[0]:\n raise ValueError(\"At least one edge points to a non-existing\"\n \" node index:\"\n \" type %d to type %d\" % (typ1, typ2))\n return True\n\n def _check_size_xy(self, X, Y):\n if Y is None:\n return\n\n # make sure Y has the proper length and acceptable labels\n l_node_features = self._get_node_features(X)\n\n nb_nodes = sum(nf.shape[0] for nf in l_node_features)\n if Y.shape[0] != nb_nodes:\n raise ValueError(\"Expected 1 label for each of the %d nodes. Got\"\n \" %d labels.\" % (nb_nodes, Y.shape[0]))\n\n i_start = 0\n for typ, nf, n_states in zip(range(self.n_types),\n l_node_features,\n self.l_n_states):\n nb_nodes = nf.shape[0]\n if nb_nodes == 0:\n continue\n Y_typ = Y[i_start:i_start+nb_nodes]\n if np.min(Y_typ) < 0:\n raise ValueError(\"Got a negative label for type %d\" % typ)\n if np.min(Y_typ) < self._l_type_startindex[typ]:\n raise InconsistentLabel(\"labels of type %d start at %d\"\n \"\" % (typ,\n self._l_type_startindex[typ]))\n if np.max(Y_typ) >= self._l_type_startindex[typ+1]:\n raise InconsistentLabel(\"labels of type %d end at %d\"\n \"\" % (typ,\n self._l_type_startindex[typ+1]-1)\n )\n i_start = i_start + nb_nodes\n return True\n\n def _get_node_features(self, x):\n # we replace None by empty array with proper shape\n return [np.empty((0, _n_feat)) if node_features is None\n else node_features\n for (node_features, _n_feat) in zip(x[0], self.l_n_features)]\n\n def _get_edges(self, x):\n return [np.empty((0, 2)) if edges is None or len(edges) == 0\n else edges for edges in x[1]]\n\n def _get_edges_by_type(self, x, typ1, typ2):\n return x[1][typ1 * self.n_types+typ2]\n\n def _iter_type_pairs(self):\n for typ1 in range(self.n_types):\n for typ2 in range(self.n_types):\n yield (typ1, typ2)\n return\n\n def _get_unary_potentials(self, x, w):\n \"\"\"Computes unary potentials for x and w.\n\n Parameters\n ----------\n x : tuple\n Instance Representation.\n\n w : ndarray, shape=(size_joint_feature,)\n Weight vector for CRF instance.\n\n Returns\n -------\n unaries : list of ndarray, shape=( n_nodes_typ, n_states_typ )\n Unary weights.\n \"\"\"\n self._check_size_w(w)\n l_node_features = self._get_node_features(x)\n\n l_unary_potentials = []\n\n i_w = 0\n for (features, n_states, n_features) in zip(l_node_features,\n self.l_n_states,\n self.l_n_features):\n n_w = n_states*n_features\n l_unary_potentials.append(\n np.dot(features,\n w[i_w:i_w+n_w].reshape(n_states,\n n_features).T\n )\n )\n i_w += n_w\n assert i_w == self.size_unaries\n\n # nodes x features . features x states --> nodes x states\n return l_unary_potentials\n\n def continuous_loss(self, y, l_y_hat):\n # continuous version of the loss\n # y is the result of linear programming\n # BUT, in multitype mode, y_hat is a list of unaries\n l_result = list()\n cum_n_node = 0\n cum_n_state = 0\n for y_hat in l_y_hat:\n n_node, n_state = y_hat.shape\n # all entries minus correct ones\n # select the correct range of labels and make the labels start at 0\n y_type = y[cum_n_node:cum_n_node+n_node] - cum_n_state\n gx = np.indices(y_type.shape)\n result = 1 - y_hat[gx, y_type]\n l_result.append(result)\n cum_n_node += n_node\n cum_n_state += n_state\n result = np.hstack(l_result)\n\n if hasattr(self, 'class_weight'):\n return np.sum(self.class_weight[y] * result)\n return np.sum(result)\n"
] | [
[
"numpy.dot",
"numpy.hstack",
"sklearn.externals.joblib.Parallel",
"numpy.arange",
"numpy.eye",
"sklearn.externals.joblib.delayed",
"numpy.ones",
"numpy.identity",
"numpy.where",
"sklearn.utils.gen_even_slices",
"numpy.ravel",
"numpy.array",
"numpy.zeros",
"numpy.sum",
"numpy.vstack"
],
[
"numpy.diag",
"numpy.testing.assert_equal",
"numpy.dot",
"numpy.random.seed",
"numpy.arange",
"numpy.set_printoptions",
"numpy.eye",
"numpy.indices",
"numpy.testing.assert_array_equal",
"numpy.testing.assert_almost_equal",
"numpy.random.normal",
"numpy.argmax",
"numpy.max",
"numpy.repeat",
"numpy.array",
"numpy.zeros",
"numpy.vstack",
"numpy.testing.assert_array_almost_equal"
],
[
"sklearn.cross_validation.train_test_split",
"numpy.random.randn",
"scipy.sparse.csr_matrix"
],
[
"numpy.dot",
"numpy.arange",
"numpy.testing.assert_array_equal",
"numpy.random.normal",
"numpy.random.RandomState",
"numpy.zeros",
"numpy.vstack",
"numpy.random.randint"
],
[
"numpy.hstack",
"numpy.min",
"numpy.asarray",
"numpy.indices",
"numpy.ones",
"numpy.max",
"numpy.zeros",
"numpy.sum",
"numpy.empty"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"1.7",
"1.0",
"0.10",
"1.2",
"0.14",
"0.19",
"1.5",
"0.12",
"0.17",
"0.13",
"1.6",
"1.4",
"1.9",
"1.3",
"1.10",
"0.15",
"0.18",
"0.16",
"1.8"
],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ANazaret/scVI | [
"94a4a31b48b468da63417ef191db35b8bc98fbc6"
] | [
"tests/dataset/test_dataset.py"
] | [
"from unittest import TestCase\n\nimport numpy as np\nimport copy\n\nfrom scvi.dataset import CortexDataset, GeneExpressionDataset\nfrom scvi.dataset.dataset import remap_categories, CellMeasurement\n\n\nclass TestGeneExpressionDataset(TestCase):\n def test_populate_from_data(self):\n data = np.ones((25, 10)) * 100\n dataset = GeneExpressionDataset()\n dataset.populate_from_data(data)\n\n self.assertEqual(dataset.nb_genes, 10)\n self.assertEqual(dataset.nb_cells, 25)\n # default batch_indices and labels\n self.assertListEqual([[0] for i in range(25)], dataset.batch_indices.tolist())\n self.assertListEqual([[0] for i in range(25)], dataset.labels.tolist())\n\n def test_populate_from_data_with_measurements(self):\n data = np.ones((25, 10)) * 100\n paired = np.ones((25, 4)) * np.arange(0, 4)\n pair_names = [\"gabou\", \"achille\", \"pedro\", \"oclivio\"]\n y = CellMeasurement(\n name=\"dev\", data=paired, columns_attr_name=\"dev_names\", columns=pair_names\n )\n dataset = GeneExpressionDataset()\n\n dataset.populate_from_data(data, Ys=[y])\n\n self.assertEqual(dataset.nb_genes, 10)\n self.assertEqual(dataset.nb_cells, 25)\n\n self.assertTrue(hasattr(dataset, \"dev\"))\n self.assertTrue(hasattr(dataset, \"dev_names\"))\n\n self.assertListEqual(dataset.dev_names.tolist(), pair_names)\n self.assertListEqual(dataset.dev[0].tolist(), [0, 1, 2, 3])\n\n ad = dataset.to_anndata()\n self.assertTrue(\"dev\" in ad.obsm)\n\n def test_populate_from_per_batch_list(self):\n data = [\n np.random.randint(1, 5, size=(7, 10)),\n np.random.randint(1, 5, size=(5, 10)),\n np.random.randint(1, 5, size=(3, 10)),\n ]\n dataset = GeneExpressionDataset()\n dataset.populate_from_per_batch_list(data)\n self.assertEqual(dataset.nb_cells, 15)\n self.assertEqual(dataset.nb_genes, 10)\n true_batch_indices = np.concatenate(\n [\n np.zeros((7, 1), dtype=int),\n np.ones((5, 1), dtype=int),\n 2 * np.ones((3, 1), dtype=int),\n ]\n )\n self.assertListEqual(\n true_batch_indices.tolist(), dataset.batch_indices.tolist()\n )\n\n def test_populate_from_per_label_list(self):\n data = [\n np.random.randint(1, 5, size=(7, 10)),\n np.random.randint(1, 5, size=(5, 10)),\n np.random.randint(1, 5, size=(3, 10)),\n ]\n dataset = GeneExpressionDataset()\n dataset.populate_from_per_label_list(data)\n self.assertEqual(dataset.nb_cells, 15)\n self.assertEqual(dataset.nb_genes, 10)\n true_labels = np.concatenate(\n [\n np.zeros((7, 1), dtype=int),\n np.ones((5, 1), dtype=int),\n 2 * np.ones((3, 1), dtype=int),\n ]\n )\n self.assertListEqual(dataset.labels.tolist(), true_labels.tolist())\n\n def test_populate_from_datasets_dummy_data(self):\n data1 = np.random.randint(1, 5, size=(5, 10))\n gene_names1 = np.array([\"gene_%d\" % i for i in range(10)])\n dataset1 = GeneExpressionDataset()\n dataset1.populate_from_data(data1, gene_names=gene_names1)\n data2 = np.random.randint(1, 5, size=(7, 3))\n gene_names2 = np.array([\"gene_%d\" % i for i in range(3)])\n dataset2 = GeneExpressionDataset()\n dataset2.populate_from_data(data2, gene_names=gene_names2)\n data3 = np.random.randint(1, 5, size=(2, 5))\n gene_names3 = np.array([\"gene_%d\" % i for i in range(5)])\n dataset3 = GeneExpressionDataset()\n dataset3.populate_from_data(data3, gene_names=gene_names3)\n\n dataset = GeneExpressionDataset()\n dataset.populate_from_datasets([dataset1, dataset2, dataset3])\n self.assertEqual(14, dataset.nb_cells)\n self.assertEqual(3, dataset.nb_genes)\n self.assertListEqual(\n [\"gene_0\", \"gene_1\", \"gene_2\"], dataset.gene_names.tolist()\n )\n\n # test for labels sharing\n dataset2.labels = [0, 0, 0, 1, 1, 1, 1]\n dataset2.initialize_mapped_attribute(\"labels\", \"cell_types\", [\"0\", \"1\"])\n dataset3.labels = [0, 1]\n dataset3.initialize_mapped_attribute(\"labels\", \"cell_types\", [\"0\", \"2\"])\n dataset = GeneExpressionDataset()\n dataset.populate_from_datasets([dataset2, dataset3], shared_labels=True)\n self.assertListEqual(\n np.squeeze(dataset.labels).tolist(), [0, 0, 0, 1, 1, 1, 1, 0, 2]\n )\n self.assertListEqual(dataset.cell_types, [\"0\", \"1\", \"2\"])\n\n dataset_unshared = GeneExpressionDataset()\n dataset_unshared.populate_from_datasets(\n [dataset2, dataset3], shared_labels=False\n )\n self.assertListEqual(\n np.squeeze(dataset_unshared.labels).tolist(), [0, 0, 0, 1, 1, 1, 1, 2, 3]\n )\n self.assertListEqual(dataset_unshared.cell_types, [\"0\", \"1\", \"0\", \"2\"])\n\n # test for batch_indices offsetting\n dataset2.batch_indices = [0, 0, 0, 1, 1, 1, 1]\n dataset2.initialize_mapped_attribute(\n \"batch_indices\", \"experiment\", [\"fish_2\", \"scrna_2\"]\n )\n dataset3.batch_indices = [0, 1]\n dataset3.initialize_mapped_attribute(\n \"batch_indices\", \"experiment\", [\"fish_3\", \"scrna_3\"]\n )\n dataset = GeneExpressionDataset()\n dataset.populate_from_datasets([dataset2, dataset3])\n self.assertListEqual(\n np.squeeze(dataset.batch_indices).tolist(), [0, 0, 0, 1, 1, 1, 1, 2, 3]\n )\n self.assertListEqual(\n getattr(dataset, \"experiment\"), [\"fish_2\", \"scrna_2\", \"fish_3\", \"scrna_3\"]\n )\n\n def test_populate_from_datasets_gene_attributes_merging(self):\n data = np.random.randint(1, 5, size=(5, 10))\n gene_names = np.array([\"gene_%d\" % i for i in range(10)])\n gene_attr1 = np.array([[\"1\"] for _ in range(10)])\n gene_attr2 = np.array([[\"2\"] for _ in range(10)])\n dataset1 = GeneExpressionDataset()\n dataset2 = GeneExpressionDataset()\n\n dataset1.populate_from_data(\n data, gene_names=gene_names, gene_attributes_dict={\"test\": gene_attr1}\n )\n dataset2.populate_from_data(\n data, gene_names=gene_names, gene_attributes_dict={\"test\": gene_attr2}\n )\n\n dataset = GeneExpressionDataset()\n dataset.populate_from_datasets([dataset1, dataset2])\n\n # Should keep the gene attribute of the first dataset\n self.assertEqual(dataset.test[0, 0], \"1\")\n\n def test_populate_from_datasets_cell_attributes_merging(self):\n data = np.random.randint(1, 5, size=(5, 10))\n gene_names = np.array([\"gene_%d\" % i for i in range(10)])\n cell_attr1 = np.array([[\"1\"] for _ in range(5)])\n cell_attr2 = np.array([[\"2\"] for _ in range(5)])\n dataset1 = GeneExpressionDataset()\n dataset2 = GeneExpressionDataset()\n\n dataset1.populate_from_data(\n data, gene_names=gene_names, cell_attributes_dict={\"test\": cell_attr1}\n )\n dataset2.populate_from_data(\n data, gene_names=gene_names, cell_attributes_dict={\"test\": cell_attr2}\n )\n\n dataset = GeneExpressionDataset()\n dataset.populate_from_datasets([dataset1, dataset2])\n self.assertTupleEqual(dataset.test.shape, (10, 1))\n self.assertListEqual(np.squeeze(dataset.test).tolist(), [\"1\"] * 5 + [\"2\"] * 5)\n\n def test_populate_from_datasets_with_measurments(self):\n data = np.random.randint(1, 5, size=(5, 10))\n gene_names = np.array([\"gene_%d\" % i for i in range(10)])\n\n paired1 = np.ones((5, 5)) * np.arange(0, 5)\n pair_names1 = [\"gabou\", \"achille\", \"pedro\", \"oclivio\", \"gayoso\"]\n y1 = CellMeasurement(\n name=\"dev\", data=paired1, columns_attr_name=\"dev_names\", columns=pair_names1\n )\n paired2 = np.ones((5, 4)) * np.arange(0, 4)\n pair_names2 = [\"gabou\", \"oclivio\", \"achille\", \"pedro\"]\n y2 = CellMeasurement(\n name=\"dev\", data=paired2, columns_attr_name=\"dev_names\", columns=pair_names2\n )\n\n dataset1 = GeneExpressionDataset()\n dataset2 = GeneExpressionDataset()\n\n dataset1.populate_from_data(data, Ys=[y1], gene_names=gene_names)\n dataset2.populate_from_data(data, Ys=[y2], gene_names=gene_names)\n\n dataset = GeneExpressionDataset()\n dataset.populate_from_datasets(\n [copy.deepcopy(dataset1), copy.deepcopy(dataset2)]\n )\n\n self.assertTrue(hasattr(dataset, \"dev\"))\n self.assertTrue(hasattr(dataset, \"dev_names\"))\n\n self.assertListEqual(\n dataset.dev_names.tolist(), [\"achille\", \"gabou\", \"oclivio\", \"pedro\"]\n )\n self.assertListEqual(dataset.dev[0].tolist(), [1, 0, 3, 2])\n self.assertListEqual(dataset.dev[5].tolist(), [2, 0, 1, 3])\n\n # Take union of dev columns, 0s fill remainder\n dataset = GeneExpressionDataset()\n dataset.populate_from_datasets(\n [copy.deepcopy(dataset1), copy.deepcopy(dataset2)],\n cell_measurement_intersection={\"dev\": False},\n )\n self.assertListEqual(\n dataset.dev_names.tolist(),\n [\"achille\", \"gabou\", \"gayoso\", \"oclivio\", \"pedro\"],\n )\n mask = dataset.get_batch_mask_cell_measurement(\"dev\")\n self.assertEqual(mask[1][2].astype(int), 0)\n\n def test_populate_from_datasets_cortex(self):\n cortex_dataset_1 = CortexDataset(save_path=\"tests/data\")\n cortex_dataset_1.subsample_genes(subset_genes=np.arange(0, 3), mode=\"variance\")\n cortex_dataset_1.filter_cell_types([\"microglia\", \"oligodendrocytes\"])\n cortex_dataset_2 = CortexDataset(save_path=\"tests/data\")\n cortex_dataset_2.subsample_genes(subset_genes=np.arange(1, 4), mode=\"variance\")\n cortex_dataset_2.filter_cell_types(\n [\"endothelial-mural\", \"interneurons\", \"microglia\", \"oligodendrocytes\"]\n )\n cortex_dataset_2.filter_cell_types([2, 0])\n dataset = GeneExpressionDataset()\n dataset.populate_from_datasets([cortex_dataset_1, cortex_dataset_2])\n self.assertEqual(2, dataset.nb_genes)\n\n def test_labels(self):\n data = np.ones((25, 10)) * 100\n labels = np.array(range(25))\n dataset = GeneExpressionDataset()\n dataset.populate_from_data(data, labels=labels)\n self.assertTupleEqual((25, 1), dataset.labels.shape)\n self.assertEqual(dataset.labels[5, 0], 5)\n\n labels = np.ones(25) * 5\n dataset = GeneExpressionDataset()\n dataset.populate_from_data(data, labels=labels)\n self.assertTupleEqual(dataset.labels.shape, (25, 1))\n self.assertEqual(dataset.labels[5, 0], 0)\n\n def test_remap_categorical_attributes(self):\n data = np.random.randint(1, 5, size=(7, 11))\n labels = [1, 1, 1, 1, 1, 2, 2]\n dataset = GeneExpressionDataset()\n dataset.populate_from_data(data, labels=labels)\n\n labels_true = [0, 0, 0, 0, 0, 1, 1]\n labels_true = [[i] for i in labels_true]\n self.assertListEqual(labels_true, dataset.labels.tolist())\n\n def test_compute_library_size_batch(self):\n data = np.exp(10) / 10 * np.ones((7, 10), dtype=int)\n dataset = GeneExpressionDataset()\n dataset.populate_from_data(data)\n\n local_means_true = [[10.0] for _ in range(7)]\n local_vars_true = [[0.0] for _ in range(7)]\n self.assertEqual(local_means_true, dataset.local_means.tolist())\n self.assertEqual(local_vars_true, dataset.local_vars.tolist())\n\n def test_subsample_genes(self):\n data = np.ones((25, 100)) * 100\n variable_data = data\n variable_data[0, :] = 2\n variable_data *= np.arange(0, 100)\n\n gene_names = np.array([\"gene_%d\" % i for i in range(100)])\n dataset = GeneExpressionDataset()\n dataset.populate_from_data(data, gene_names=gene_names)\n dataset.subsample_genes(new_ratio_genes=0.4, mode=\"variance\")\n self.assertTupleEqual(dataset.gene_names.shape, (40,))\n dataset.subsample_genes(new_n_genes=25, mode=\"variance\")\n self.assertTupleEqual(dataset.gene_names.shape, (25,))\n # The most variable genes should be in first position\n self.assertEqual(dataset.gene_names[0], \"gene_99\")\n dataset.subsample_genes(subset_genes=[1, 6, 7])\n self.assertEqual(dataset.gene_names[0], \"gene_98\")\n\n def test_filter_genes(self):\n data = np.random.randint(1, 5, size=(5, 10))\n gene_names = np.array([\"gene_%d\" % i for i in range(10)])\n\n dataset = GeneExpressionDataset()\n dataset.populate_from_data(data, gene_names=gene_names)\n gene_names_true = [\"gene_1\", \"gene_3\"]\n dataset.filter_genes_by_attribute(gene_names_true)\n self.assertListEqual(gene_names_true, dataset.gene_names.tolist())\n\n def test_reorder_genes(self):\n data = np.ones((25, 100)) * 100\n\n gene_names = np.array([\"gene_%d\" % i for i in range(100)])\n dataset = GeneExpressionDataset()\n dataset.populate_from_data(data, gene_names=gene_names)\n dataset.reorder_genes([\"gene_47\", \"gene_2\", \"gene_3\", \"gene_12\"])\n # New order should be 47, 2, 3, 12, 0, 1, ...\n self.assertListEqual(\n list(dataset.gene_names[0:6]),\n [\"gene_47\", \"gene_2\", \"gene_3\", \"gene_12\", \"gene_0\", \"gene_1\"],\n )\n\n self.assertRaises(KeyError, dataset.reorder_genes, [\"gene_101\"])\n\n def test_genes_to_idx(self):\n data = np.random.randint(1, 5, size=(5, 10))\n gene_names = np.array([\"gene_%d\" % i for i in range(10)])\n\n dataset = GeneExpressionDataset()\n dataset.populate_from_data(data, gene_names=gene_names)\n indices = dataset.genes_to_index([\"gene_%d\" % i for i in range(10)])\n self.assertListEqual([i for i in range(10)], indices.tolist())\n\n def test_subsample_cells(self):\n data = np.arange(1, 6)[:, None] * np.ones(7)[None, :]\n\n dataset = GeneExpressionDataset()\n dataset.populate_from_data(data)\n # default\n dataset.subsample_cells()\n self.assertEqual(5, dataset.nb_cells)\n # when size is a float\n dataset.subsample_cells(size=0.8)\n data_true = np.arange(5, 1, -1)[:, None] * np.ones(7)[None, :]\n self.assertListEqual(data_true.tolist(), dataset.X.tolist())\n # when size is an int\n dataset.subsample_cells(size=2)\n self.assertEqual(2, dataset.nb_cells)\n\n def test_filter_cells(self):\n data = np.ones((25, 10)) * 100\n data[4:6, :] = 0\n dataset = GeneExpressionDataset()\n dataset.populate_from_data(data)\n self.assertEqual(25, dataset.nb_cells)\n dataset.filter_cells_by_count()\n self.assertEqual(23, dataset.nb_cells)\n\n def test_filter_cell_types(self):\n data = np.random.randint(1, 5, size=(5, 10))\n labels = [0, 0, 1, 1, 1]\n cell_types = [\"0\", \"1\"]\n\n dataset = GeneExpressionDataset()\n dataset.populate_from_data(data, labels=labels, cell_types=cell_types)\n dataset.filter_cell_types([\"0\"])\n self.assertListEqual(data[:2].tolist(), dataset.X.tolist())\n\n def test_merge_cell_types(self):\n data = np.random.randint(1, 5, size=(8, 20))\n labels = [0, 0, 1, 2, 2, 1, 0, 1]\n cell_types = [\"0\", \"1\", \"2\"]\n\n dataset = GeneExpressionDataset()\n dataset.populate_from_data(data, labels=labels, cell_types=cell_types)\n dataset.merge_cell_types([\"0\", \"1\"], new_cell_type_name=\"0 and 1\")\n self.assertListEqual(\n [[3], [3], [3], [2], [2], [3], [3], [3]], dataset.labels.tolist()\n )\n dataset.remap_categorical_attributes()\n self.assertListEqual(\n [[1], [1], [1], [0], [0], [1], [1], [1]], dataset.labels.tolist()\n )\n self.assertListEqual([\"2\", \"0 and 1\"], dataset.cell_types.tolist())\n\n def test_map_cell_types(self):\n data = np.random.randint(1, 5, size=(7, 10))\n labels = [0, 0, 4, 4, 2, 3, 5]\n cell_types = [\"0\", \"1\", \"2\", \"3\", \"4\", \"5\"]\n\n dataset = GeneExpressionDataset()\n dataset.populate_from_data(data, labels=labels, cell_types=cell_types)\n dataset.map_cell_types({(\"0\", \"2\"): \"6\", (\"3\", \"4\"): \"7\"})\n dataset.remap_categorical_attributes()\n self.assertListEqual(dataset.cell_types.tolist(), [\"5\", \"6\", \"7\"])\n self.assertListEqual(np.squeeze(dataset.labels).tolist(), [1, 1, 2, 2, 1, 2, 0])\n\n\nclass TestCollate(TestCase):\n def test_collate_normal(self):\n data = np.ones((25, 2)) * np.arange(0, 25).reshape((-1, 1))\n batch_indices = np.arange(0, 25).reshape((-1, 1))\n dataset = GeneExpressionDataset()\n dataset.populate_from_data(data, batch_indices=batch_indices)\n\n collate_fn = dataset.collate_fn_builder()\n x, mean, var, batch, labels = collate_fn([1, 2])\n self.assertListEqual(x.tolist(), [[1.0, 1.0], [2.0, 2.0]])\n self.assertListEqual(batch.tolist(), [[1], [2]])\n\n def test_collate_add(self):\n data = np.ones((25, 2)) * np.arange(0, 25).reshape((-1, 1))\n batch_indices = np.arange(0, 25).reshape((-1, 1))\n x_coords = np.arange(0, 25).reshape((-1, 1))\n proteins = (\n np.ones((25, 3)) + np.arange(0, 25).reshape((-1, 1)) + np.arange(0, 3)\n )\n proteins_name = [\"A\", \"B\", \"C\"]\n dataset = GeneExpressionDataset()\n dataset.populate_from_data(\n data,\n batch_indices=batch_indices,\n cell_attributes_dict={\"x_coords\": x_coords},\n Ys=[\n CellMeasurement(\n name=\"proteins\",\n data=proteins,\n columns_attr_name=\"protein_names\",\n columns=proteins_name,\n )\n ],\n )\n\n collate_fn = dataset.collate_fn_builder(\n add_attributes_and_types={\"x_coords\": np.float32, \"proteins\": np.float32}\n )\n x, mean, var, batch, labels, x_coords_tensor, proteins_tensor = collate_fn(\n [1, 2]\n )\n self.assertListEqual(x_coords_tensor.tolist(), [[1.0], [2.0]])\n self.assertListEqual(\n proteins_tensor.tolist(), [[2.0, 3.0, 4.0], [3.0, 4.0, 5.0]]\n )\n\n\nclass TestRemapCategories(TestCase):\n def test_remap_categories(self):\n labels = [0, 0, 0, 2, 2, 3]\n labels, n_labels = remap_categories(labels)\n labels_true = [0, 0, 0, 1, 1, 2]\n self.assertListEqual(labels_true, labels.tolist())\n self.assertEqual(3, n_labels)\n\n # with absent categories and mappings\n labels = [2, 2, 3]\n mappings_dict = {\"cell_types\": [\"0\", \"1\", \"2\", \"3\"]}\n labels, n_labels, mappings = remap_categories(\n labels, mappings_dict=mappings_dict\n )\n labels_true = [0, 0, 1]\n self.assertListEqual(labels_true, labels.tolist())\n self.assertEqual(2, n_labels)\n self.assertListEqual([\"2\", \"3\"], mappings[\"cell_types\"].tolist())\n"
] | [
[
"numpy.arange",
"numpy.squeeze",
"numpy.ones",
"numpy.exp",
"numpy.zeros",
"numpy.random.randint"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
zhanglei1172/bbobenchmark | [
"841bffdddc1320ac2676e378d20f8b176a7e6cf7",
"841bffdddc1320ac2676e378d20f8b176a7e6cf7",
"841bffdddc1320ac2676e378d20f8b176a7e6cf7",
"841bffdddc1320ac2676e378d20f8b176a7e6cf7"
] | [
"examples/transfer_bo.py",
"examples/rosenbrock_cma-es.py",
"tests/smac3/comparison.py",
"xbbo/search_algorithm/cem_optimizer.py"
] | [
"import numpy as np\n# import matplotlib.pyplot as plt\nfrom xbbo.configspace.space import DenseConfiguration, DenseConfigurationSpace\nfrom ConfigSpace.hyperparameters import UniformFloatHyperparameter\nfrom ConfigSpace.conditions import LessThanCondition\n\n# from xbbo.search_algorithm.transfer_tst_optimizer import SMBO\n# from xbbo.search_algorithm.transfer_taf_optimizer import SMBO\n# from xbbo.search_algorithm.transfer_rgpe_mean_optimizer import SMBO\n# from xbbo.search_algorithm.transfer_taf_rgpe_optimizer import SMBO\n# from xbbo.search_algorithm.transfer_RMoGP_optimizer import SMBO\nfrom xbbo.search_algorithm.transfer_bo_optimizer import SMBO\n\nfrom xbbo.search_space.offline_hp import Model\nfrom xbbo.utils.constants import MAXINT\nfrom xbbo.surrogate.transfer.base_surrogate import BaseModel\n\ndef rosenbrock_2d(x):\n \"\"\" The 2 dimensional Rosenbrock function as a toy model\n The Rosenbrock function is well know in the optimization community and\n often serves as a toy problem. It can be defined for arbitrary\n dimensions. The minimium is always at x_i = 1 with a function value of\n zero. All input parameters are continuous. The search domain for\n all x's is the interval [-5, 10].\n \"\"\"\n\n x1 = x[\"x0\"]\n # x2 = x[\"x1\"]\n x2 = x.get('x1', x1)\n\n val = 100. * (x2 - x1 ** 2.) ** 2. + (1 - x1) ** 2.\n return val\n\ndef branin(config):\n x1, x2 = config['x1'], config['x2']\n y = (x2 - 5.1 / (4 * np.pi ** 2) * x1 ** 2 + 5 / np.pi * x1 - 6) ** 2 \\\n + 10 * (1 - 1 / (8 * np.pi)) * np.cos(x1) + 10\n return y\n\ndef build_space(rng):\n cs = DenseConfigurationSpace(seed=rng.randint(10000))\n x0 = UniformFloatHyperparameter(\"x0\", -5, 10, default_value=-3)\n x1 = UniformFloatHyperparameter(\"x1\", -5, 10, default_value=-4)\n cs.add_hyperparameters([x0, x1])\n con = LessThanCondition(x1, x0, 1.)\n cs.add_condition(con)\n return cs\n\ndef build_branin_space(rng):\n cs = DenseConfigurationSpace(seed=rng.randint(10000))\n x1 = UniformFloatHyperparameter(\"x1\", -5, 10, default_value=0)\n x2 = UniformFloatHyperparameter(\"x2\", 0, 15, default_value=0)\n cs.add_hyperparameters([x1, x2])\n return cs\n\nif __name__ == \"__main__\":\n MAX_CALL = 30\n rng = np.random.RandomState(42)\n\n test_model = Model(None, rng.randint(MAXINT), test_task='a6a', )\n\n cs = DenseConfigurationSpace(seed=rng.randint(MAXINT))\n confs = test_model.get_api_config()\n for conf in confs:\n cs.add_hyperparameter(UniformFloatHyperparameter(conf, confs[conf]['range'][0], confs[conf]['range'][1]))\n blackbox_func = test_model.evaluate\n base_models = []\n for i in range(len(test_model.old_D_x)):\n base_models.append(BaseModel(cs, rng=rng,do_optimize=False))\n base_models[-1].train(test_model.old_D_x[i], test_model.old_D_y[i])\n\n # use transfer\n # hpopt = SMBO(space=cs, seed=rng.randint(10000), total_limit=MAX_CALL, initial_design='sobol', surrogate='gp', acq_func='ei', weight_srategy='kernel', acq_opt='rs', base_models=base_models) # vanila bo\n # hpopt = SMBO(space=cs, seed=rng.randint(10000), total_limit=MAX_CALL, initial_design='sobol', surrogate='tst', acq_func='ei', weight_srategy='kernel', acq_opt='rs', base_models=base_models) # TST-R\n # hpopt = SMBO(space=cs, seed=rng.randint(10000), total_limit=MAX_CALL, initial_design='sobol', surrogate='gp', acq_func='taf', weight_srategy='kernel', acq_opt='rs', base_models=base_models) # TAF\n # hpopt = SMBO(space=cs, seed=rng.randint(10000), total_limit=MAX_CALL, initial_design='sobol', surrogate='tst', acq_func='ei', weight_srategy='rw', acq_opt='rs', base_models=base_models) # RGPE(mean)\n # hpopt = SMBO(space=cs, seed=rng.randint(10000), total_limit=MAX_CALL, initial_design='sobol', surrogate='gp', acq_func='taf', weight_srategy='rw', acq_opt='rs', base_models=base_models) # TAF(rw)\n hpopt = SMBO(space=cs, seed=rng.randint(10000), total_limit=MAX_CALL, initial_design='sobol', surrogate='gp', acq_func='mogp', weight_srategy='rw', acq_opt='rs', base_models=base_models) # RMoGP\n # not use transfer\n # hpopt = SMBO(space=cs, seed=rng.randint(10000), total_limit=MAX_CALL, initial_design='sobol', surrogate='gp', acq_opt='rs_ls', base_models=[]]) \n # Example call of the black-box function\n def_value = blackbox_func(cs.get_default_configuration())\n print(\"Default Value: %.2f\" % def_value)\n # ---- Begin BO-loop ----\n for i in range(MAX_CALL):\n # suggest\n trial_list = hpopt.suggest()\n # evaluate \n value = blackbox_func(trial_list[0].config_dict)\n # observe\n trial_list[0].add_observe_value(observe_value=value)\n hpopt.observe(trial_list=trial_list)\n \n print(value)\n \n # plt.plot(hpopt.trials.get_history()[0])\n # plt.savefig('./out/rosenbrock_bo_gp.png')\n # plt.show()\n print('find best value:{}'.format(hpopt.trials.get_best()[0]))\n\n",
"import numpy as np\n# import matplotlib.pyplot as plt\nfrom xbbo.search_space.fast_example_problem import build_space_hard, rosenbrock_2d_hard\n\nfrom xbbo.search_algorithm.cma_optimizer import CMAES\n\n\n\nif __name__ == \"__main__\":\n MAX_CALL = 1000\n rng = np.random.RandomState(42)\n\n # define black box function\n blackbox_func = rosenbrock_2d_hard\n # define search space\n cs = build_space_hard(rng)\n # define black box optimizer\n hpopt = CMAES(space=cs, seed=rng.randint(10000),)\n # Example call of the black-box function\n def_value = blackbox_func(cs.get_default_configuration())\n print(\"Default Value: %.2f\" % def_value)\n # ---- Begin BO-loop ----\n for i in range(MAX_CALL):\n # suggest\n trial_list = hpopt.suggest()\n # evaluate \n value = blackbox_func(trial_list[0].config_dict)\n # observe\n trial_list[0].add_observe_value(observe_value=value)\n hpopt.observe(trial_list=trial_list)\n \n print(value)\n \n # plt.plot(hpopt.trials.get_history()[0])\n # plt.savefig('./out/rosenbrock_bo_gp.png')\n # plt.show()\n print('find best value:{}'.format(hpopt.trials.get_best()[0]))\n\n",
"import numpy as np\nimport matplotlib.pyplot as plt\n\nfrom smac3_svm_cv import run_one_exp as smac3_svm_opt\nfrom xbbo_svm_cv import run_one_exp as xbbo_svm_opt\nfrom smac3_synthetic import run_one_exp as smac3_synthetic_opt\nfrom xbbo_synthetic import run_one_exp as xbbo_synthetic_opt\n\nif __name__ == \"__main__\":\n rng = np.random.RandomState(42)\n result_smac3 = []\n result_xbbo = []\n for i in range(3):\n seed = rng.randint(1e5)\n result_smac3.append(smac3_synthetic_opt(seed))\n result_xbbo.append(xbbo_synthetic_opt(seed))\n result_smac3 = np.array(result_smac3)\n result_xbbo = np.array(result_xbbo)\n plt.figure()\n plt.plot(range(1,31), np.mean(result_xbbo,axis=0)[:], label='XBBO')\n plt.plot(range(1,31), np.mean(result_smac3,axis=0)[:], label='SMAC3')\n plt.ylim([-0.1,1000])\n plt.xlabel('# of Evaluate')\n plt.ylabel('OBJ')\n plt.title('Average of cumulate best on 3 seeds')\n plt.legend()\n plt.savefig('./out/comp_with_smac3.png')\n plt.show()\n\n # rng = np.random.RandomState(42)\n # result_smac3 = []\n # result_xbbo = []\n # for i in range(3):\n # seed = rng.randint(1e5)\n # result_xbbo.append(xbbo_svm_opt(seed))\n # result_smac3.append(smac3_svm_opt(seed))\n # result_smac3 = np.array(result_smac3)\n # result_xbbo = np.array(result_xbbo)\n # plt.figure()\n # plt.plot(range(1,51), np.mean(result_xbbo,axis=0)[:], label='XBBO')\n # plt.plot(range(1,51), np.mean(result_smac3,axis=0)[:], label='SMAC3')\n # plt.ylim([0,0.1])\n # plt.xlabel('# of Evaluate')\n # plt.ylabel('OBJ')\n # plt.title('Average of cumulate best on 3 seeds')\n # plt.legend()\n # plt.savefig('./out/comp_with_smac3_2.png')\n # plt.show()\n",
"import math\nimport numpy as np\n\nfrom xbbo.search_algorithm.base import AbstractOptimizer\nfrom xbbo.configspace.space import DenseConfiguration, DenseConfigurationSpace\nfrom . import alg_register\n# from xbbo.configspace.feature_space import Uniform2Gaussian\nfrom xbbo.search_algorithm.base import AbstractOptimizer\nfrom xbbo.core.trials import Trial, Trials\n\n@alg_register.register('cem')\nclass CEM(AbstractOptimizer):\n def __init__(self,\n space: DenseConfigurationSpace,\n seed: int = 42,\n llambda=None,\n elite_ratio=0.3,\n sample_method: str = 'Gaussian',\n **kwargs):\n AbstractOptimizer.__init__(self, space, seed, **kwargs)\n # Uniform2Gaussian.__init__(self, )\n\n # configs = self.space.get_hyperparameters()\n self.dense_dimension = self.space.get_dimensions(sparse=False)\n self.sparse_dimension = self.space.get_dimensions(sparse=True)\n self.bounds = self.space.get_bounds()\n if sample_method == 'Gaussian':\n self.sampler = Gaussian_sampler(self.dense_dimension, self.bounds,\n self.rng)\n elif sample_method == 'Uniform':\n self.sampler = Uniform_sampler(self.dense_dimension, self.bounds,\n self.rng)\n\n self.buffer_x = []\n self.buffer_y = []\n self.llambda = llambda if llambda else 4 + math.floor(3 * math.log(self.dense_dimension))\n self.elite_ratio = elite_ratio\n self.trials = Trials(sparse_dim=self.sparse_dimension,\n dense_dim=self.dense_dimension)\n\n def suggest(self, n_suggestions=1):\n trial_list = []\n for n in range(n_suggestions):\n # new_individual = self.feature_to_array(new_individual, )\n new_individual = self.sampler.sample()\n\n config = DenseConfiguration.from_dense_array(\n self.space, new_individual)\n trial_list.append(\n Trial(config,\n config_dict=config.get_dictionary(),\n dense_array=new_individual,\n origin='CEM'))\n\n return trial_list\n\n def _get_elite(self):\n self.buffer_x = np.asarray(self.buffer_x)\n self.buffer_y = np.asarray(self.buffer_y)\n idx = np.argsort(self.buffer_y)[:int(self.llambda * self.elite_ratio)]\n return self.buffer_x[idx, :], self.buffer_y[idx]\n\n def observe(self, trial_list):\n for trial in trial_list:\n self.trials.add_a_trial(trial, permit_duplicate=True)\n self.buffer_x.append(trial.dense_array)\n self.buffer_y.append(trial.observe_value)\n if len(self.buffer_x) < self.llambda:\n return\n elite_x, elite_y = self._get_elite()\n self.sampler.update(elite_x, elite_y)\n self.buffer_x = []\n self.buffer_y = []\n\n\nclass Gaussian_sampler():\n def __init__(self, dim, bounds, rng) -> None:\n self.bounds = bounds\n u = bounds.ub\n l = bounds.lb\n self.mean = (u + l) / 2\n self.std = (u - l) / 6\n self.dim = dim\n self.rng = rng\n\n def update(self, elite_x, elite_y):\n self.mean = np.mean(elite_x, axis=0)\n self.std = np.std(elite_x, axis=0)\n\n def sample(self, ):\n new_individual = self.rng.normal(self.mean, self.std + 1e-17)\n new_individual = np.clip(new_individual, self.bounds.lb,\n self.bounds.ub)\n return new_individual\n\n\nclass Uniform_sampler():\n def __init__(self, dim, bounds, rng) -> None:\n self.bounds = bounds\n u = bounds.ub\n l = bounds.lb\n self.min = np.copy(l)\n self.max = np.copy(u)\n self.dim = dim\n self.rng = rng\n\n def update(self, elite_x, elite_y):\n self.min = np.amin(elite_x, axis=0)\n self.max = np.amax(elite_x, axis=0)\n\n def sample(self, ):\n new_individual = self.rng.uniform(self.min, self.max)\n new_individual = np.clip(new_individual, self.bounds.lb,\n self.bounds.ub)\n return new_individual\n\n\nopt_class = CEM"
] | [
[
"numpy.random.RandomState",
"numpy.cos"
],
[
"numpy.random.RandomState"
],
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.title",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.show",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.ylabel",
"numpy.mean",
"matplotlib.pyplot.xlabel",
"numpy.array",
"numpy.random.RandomState",
"matplotlib.pyplot.figure"
],
[
"numpy.amax",
"numpy.clip",
"numpy.asarray",
"numpy.amin",
"numpy.std",
"numpy.copy",
"numpy.mean",
"numpy.argsort"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Femi-Tofade/Plagiarism_detector | [
"026164ec11415bc566f4d817dc79c9cecf06a0c0"
] | [
"source_pytorch/predict.py"
] | [
"# import libraries\r\nimport os\r\nimport numpy as np\r\nimport torch\r\nfrom six import BytesIO\r\n\r\n# import model from model.py, by name\r\nfrom model import BinaryClassifier\r\n\r\n# default content type is numpy array\r\nNP_CONTENT_TYPE = 'application/x-npy'\r\n\r\n\r\n# Provided model load function\r\ndef model_fn(model_dir):\r\n \"\"\"Load the PyTorch model from the `model_dir` directory.\"\"\"\r\n print(\"Loading model.\")\r\n\r\n # First, load the parameters used to create the model.\r\n model_info = {}\r\n model_info_path = os.path.join(model_dir, 'model_info.pth')\r\n with open(model_info_path, 'rb') as f:\r\n model_info = torch.load(f)\r\n\r\n print(\"model_info: {}\".format(model_info))\r\n\r\n # Determine the device and construct the model.\r\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\r\n model = BinaryClassifier(model_info['input_features'], model_info['hidden_dim'], model_info['output_dim'])\r\n\r\n # Load the store model parameters.\r\n model_path = os.path.join(model_dir, 'model.pth')\r\n with open(model_path, 'rb') as f:\r\n model.load_state_dict(torch.load(f))\r\n\r\n # Prep for testing\r\n model.to(device).eval()\r\n\r\n print(\"Done loading model.\")\r\n return model\r\n\r\n\r\n# Provided input data loading\r\ndef input_fn(serialized_input_data, content_type):\r\n print('Deserializing the input data.')\r\n if content_type == NP_CONTENT_TYPE:\r\n stream = BytesIO(serialized_input_data)\r\n return np.load(stream)\r\n raise Exception('Requested unsupported ContentType in content_type: ' + content_type)\r\n\r\n# Provided output data handling\r\ndef output_fn(prediction_output, accept):\r\n print('Serializing the generated output.')\r\n if accept == NP_CONTENT_TYPE:\r\n stream = BytesIO()\r\n np.save(stream, prediction_output)\r\n return stream.getvalue(), accept\r\n raise Exception('Requested unsupported ContentType in Accept: ' + accept)\r\n\r\n\r\n# Provided predict function\r\ndef predict_fn(input_data, model):\r\n print('Predicting class labels for the input data...')\r\n\r\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\r\n \r\n # Process input_data so that it is ready to be sent to our model.\r\n data = torch.from_numpy(input_data.astype('float32'))\r\n data = data.to(device)\r\n\r\n # Put the model into evaluation mode\r\n model.eval()\r\n\r\n # Compute the result of applying the model to the input data\r\n # The variable `out_label` should be a rounded value, either 1 or 0\r\n out = model(data)\r\n out_np = out.cpu().detach().numpy()\r\n out_label = out_np.round()\r\n\r\n return out_label"
] | [
[
"numpy.load",
"torch.cuda.is_available",
"numpy.save",
"torch.load"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
rryoung98/pennylane | [
"0c1c805fd5dfce465a8955ee3faf81037023a23e"
] | [
"tests/templates/test_layers/test_particle_conserving_u2.py"
] | [
"# Copyright 2018-2021 Xanadu Quantum Technologies Inc.\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\"\"\"\nUnit tests for the ParticleConservingU2 template.\n\"\"\"\nimport pytest\nimport numpy as np\nimport pennylane as qml\nfrom pennylane import numpy as pnp\n\n\nclass TestDecomposition:\n \"\"\"Tests that the template defines the correct decomposition.\"\"\"\n\n @pytest.mark.parametrize(\n \"layers, qubits, init_state\",\n [\n (2, 4, np.array([1, 1, 0, 0])),\n (1, 6, np.array([1, 1, 0, 0, 0, 0])),\n (1, 5, np.array([1, 1, 0, 0, 0])),\n ],\n )\n def test_operations(self, layers, qubits, init_state):\n \"\"\"Test the correctness of the ParticleConservingU2 template including the gate count\n and order, the wires each operation acts on and the correct use of parameters\n in the circuit.\"\"\"\n weights = np.random.normal(0, 2 * np.pi, (layers, 2 * qubits - 1))\n\n n_gates = 1 + (qubits + (qubits - 1) * 3) * layers\n\n exp_gates = (\n [qml.RZ] * qubits + ([qml.CNOT] + [qml.CRX] + [qml.CNOT]) * (qubits - 1)\n ) * layers\n\n op = qml.templates.ParticleConservingU2(weights, wires=range(qubits), init_state=init_state)\n queue = op.expand().operations\n\n # number of gates\n assert len(queue) == n_gates\n\n # initialization\n assert isinstance(queue[0], qml.BasisState)\n\n # order of gates\n for op1, op2 in zip(queue[1:], exp_gates):\n assert isinstance(op1, op2)\n\n # gate parameter\n params = np.array(\n [queue[i].parameters for i in range(1, n_gates) if queue[i].parameters != []]\n )\n weights[:, qubits:] = weights[:, qubits:] * 2\n assert np.allclose(params.flatten(), weights.flatten())\n\n # gate wires\n wires = range(qubits)\n nm_wires = [wires[l : l + 2] for l in range(0, qubits - 1, 2)]\n nm_wires += [wires[l : l + 2] for l in range(1, qubits - 1, 2)]\n\n exp_wires = []\n for _ in range(layers):\n for i in range(qubits):\n exp_wires.append([wires[i]])\n for j in nm_wires:\n exp_wires.append(list(j))\n exp_wires.append(list(j[::-1]))\n exp_wires.append(list(j))\n\n res_wires = [queue[i].wires.tolist() for i in range(1, n_gates)]\n\n assert res_wires == exp_wires\n\n @pytest.mark.parametrize(\n (\"init_state\", \"exp_state\"),\n [\n (np.array([0, 0]), np.array([1.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j])),\n (\n np.array([0, 1]),\n np.array([0.0 + 0.0j, 0.862093 + 0.0j, 0.0 - 0.506749j, 0.0 + 0.0j]),\n ),\n (\n np.array([1, 0]),\n np.array([0.0 + 0.0j, 0.0 - 0.506749j, 0.862093 + 0.0j, 0.0 + 0.0j]),\n ),\n (np.array([1, 1]), np.array([0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 1.0 + 0.0j])),\n ],\n )\n def test_decomposition_u2ex(self, init_state, exp_state, tol):\n \"\"\"Test the decomposition of the U_{2, ex}` exchange gate by asserting the prepared\n state.\"\"\"\n\n N = 2\n wires = range(N)\n\n weight = 0.53141\n\n dev = qml.device(\"default.qubit\", wires=N)\n\n @qml.qnode(dev)\n def circuit(weight):\n qml.BasisState(init_state, wires=wires)\n qml.templates.layers.particle_conserving_u2.u2_ex_gate(weight, wires)\n return qml.expval(qml.PauliZ(0))\n\n circuit(weight)\n\n assert np.allclose(circuit.device.state, exp_state, atol=tol)\n\n def test_custom_wire_labels(self, tol):\n \"\"\"Test that template can deal with non-numeric, nonconsecutive wire labels.\"\"\"\n weights = np.random.random(size=(1, 5))\n init_state = np.array([1, 1, 0])\n\n dev = qml.device(\"default.qubit\", wires=3)\n dev2 = qml.device(\"default.qubit\", wires=[\"z\", \"a\", \"k\"])\n\n @qml.qnode(dev)\n def circuit():\n qml.templates.ParticleConservingU2(weights, wires=range(3), init_state=init_state)\n return qml.expval(qml.Identity(0))\n\n @qml.qnode(dev2)\n def circuit2():\n qml.templates.ParticleConservingU2(\n weights, wires=[\"z\", \"a\", \"k\"], init_state=init_state\n )\n return qml.expval(qml.Identity(\"z\"))\n\n circuit()\n circuit2()\n\n assert np.allclose(dev.state, dev2.state, atol=tol, rtol=0)\n\n\nclass TestInputs:\n \"\"\"Test inputs and pre-processing.\"\"\"\n\n @pytest.mark.parametrize(\n (\"weights\", \"wires\", \"msg_match\"),\n [\n (\n np.array([[-0.080, 2.629, -0.710, 5.383, 0.646, -2.872, -3.856]]),\n [0],\n \"This template requires the number of qubits to be greater than one\",\n ),\n (\n np.array([[-0.080, 2.629, -0.710, 5.383]]),\n [0, 1, 2, 3],\n \"Weights tensor must\",\n ),\n (\n np.array(\n [\n [-0.080, 2.629, -0.710, 5.383, 0.646, -2.872],\n [-0.080, 2.629, -0.710, 5.383, 0.646, -2.872],\n ]\n ),\n [0, 1, 2, 3],\n \"Weights tensor must\",\n ),\n (\n np.array([-0.080, 2.629, -0.710, 5.383, 0.646, -2.872]),\n [0, 1, 2, 3],\n \"Weights tensor must be 2-dimensional\",\n ),\n ],\n )\n def test_exceptions(self, weights, wires, msg_match):\n \"\"\"Test that ParticleConservingU2 throws an exception if the parameters have illegal\n shapes, types or values.\"\"\"\n N = len(wires)\n init_state = np.array([1, 1, 0, 0])\n\n dev = qml.device(\"default.qubit\", wires=N)\n\n @qml.qnode(dev)\n def circuit():\n qml.templates.ParticleConservingU2(\n weights=weights,\n wires=wires,\n init_state=init_state,\n )\n return qml.expval(qml.PauliZ(0))\n\n with pytest.raises(ValueError, match=msg_match):\n circuit()\n\n\nclass TestAttributes:\n \"\"\"Tests additional methods and attributes\"\"\"\n\n @pytest.mark.parametrize(\n \"n_layers, n_wires, expected_shape\",\n [\n (2, 3, (2, 5)),\n (2, 2, (2, 3)),\n (1, 3, (1, 5)),\n ],\n )\n def test_shape(self, n_layers, n_wires, expected_shape):\n \"\"\"Test that the shape method returns the correct shape of the weights tensor\"\"\"\n\n shape = qml.templates.ParticleConservingU2.shape(n_layers, n_wires)\n assert shape == expected_shape\n\n def test_shape_exception_not_enough_qubits(self):\n \"\"\"Test that the shape function warns if there are not enough qubits.\"\"\"\n\n with pytest.raises(ValueError, match=\"The number of qubits must be greater than one\"):\n qml.templates.ParticleConservingU2.shape(3, 1)\n\n\ndef circuit_template(weights):\n qml.templates.ParticleConservingU2(weights, range(2), init_state=np.array([1, 1]))\n return qml.expval(qml.PauliZ(0))\n\n\ndef circuit_decomposed(weights):\n qml.BasisState(np.array([1, 1]), wires=[0, 1])\n qml.RZ(weights[0, 0], wires=[0])\n qml.RZ(weights[0, 1], wires=[1])\n qml.CNOT(wires=[0, 1])\n qml.CRX(weights[0, 2], wires=[1, 0])\n qml.CNOT(wires=[0, 1])\n return qml.expval(qml.PauliZ(0))\n\n\nclass TestInterfaces:\n \"\"\"Tests that the template is compatible with all interfaces, including the computation\n of gradients.\"\"\"\n\n def test_list_and_tuples(self, tol):\n \"\"\"Tests common iterables as inputs.\"\"\"\n\n weights = [[0.1, -1.1, 0.2]]\n\n dev = qml.device(\"default.qubit\", wires=2)\n\n circuit = qml.QNode(circuit_template, dev)\n circuit2 = qml.QNode(circuit_decomposed, dev)\n\n res = circuit(weights)\n res2 = circuit2(weights)\n assert qml.math.allclose(res, res2, atol=tol, rtol=0)\n\n weights_tuple = [tuple(weights[0])]\n res = circuit(weights_tuple)\n res2 = circuit2(weights_tuple)\n assert qml.math.allclose(res, res2, atol=tol, rtol=0)\n\n def test_autograd(self, tol):\n \"\"\"Tests the autograd interface.\"\"\"\n\n weights = np.random.random(size=(1, 3))\n weights = pnp.array(weights, requires_grad=True)\n\n dev = qml.device(\"default.qubit\", wires=2)\n\n circuit = qml.QNode(circuit_template, dev)\n circuit2 = qml.QNode(circuit_decomposed, dev)\n\n res = circuit(weights)\n res2 = circuit2(weights)\n assert qml.math.allclose(res, res2, atol=tol, rtol=0)\n\n grad_fn = qml.grad(circuit)\n grads = grad_fn(weights)\n\n grad_fn2 = qml.grad(circuit2)\n grads2 = grad_fn2(weights)\n\n assert np.allclose(grads[0], grads2[0], atol=tol, rtol=0)\n\n def test_jax(self, tol):\n \"\"\"Tests the jax interface.\"\"\"\n\n jax = pytest.importorskip(\"jax\")\n import jax.numpy as jnp\n\n weights = jnp.array(np.random.random(size=(1, 3)))\n\n dev = qml.device(\"default.qubit\", wires=2)\n\n circuit = qml.QNode(circuit_template, dev, interface=\"jax\")\n circuit2 = qml.QNode(circuit_decomposed, dev, interface=\"jax\")\n\n res = circuit(weights)\n res2 = circuit2(weights)\n assert qml.math.allclose(res, res2, atol=tol, rtol=0)\n\n grad_fn = jax.grad(circuit)\n grads = grad_fn(weights)\n\n grad_fn2 = jax.grad(circuit2)\n grads2 = grad_fn2(weights)\n\n assert np.allclose(grads[0], grads2[0], atol=tol, rtol=0)\n\n def test_tf(self, tol):\n \"\"\"Tests the tf interface.\"\"\"\n\n tf = pytest.importorskip(\"tensorflow\")\n\n weights = tf.Variable(np.random.random(size=(1, 3)))\n\n dev = qml.device(\"default.qubit\", wires=2)\n\n circuit = qml.QNode(circuit_template, dev, interface=\"tf\")\n circuit2 = qml.QNode(circuit_decomposed, dev, interface=\"tf\")\n\n res = circuit(weights)\n res2 = circuit2(weights)\n assert qml.math.allclose(res, res2, atol=tol, rtol=0)\n\n with tf.GradientTape() as tape:\n res = circuit(weights)\n grads = tape.gradient(res, [weights])\n\n with tf.GradientTape() as tape2:\n res2 = circuit2(weights)\n grads2 = tape2.gradient(res2, [weights])\n\n assert np.allclose(grads[0], grads2[0], atol=tol, rtol=0)\n\n def test_torch(self, tol):\n \"\"\"Tests the torch interface.\"\"\"\n\n torch = pytest.importorskip(\"torch\")\n\n weights = torch.tensor(np.random.random(size=(1, 3)), requires_grad=True)\n\n dev = qml.device(\"default.qubit\", wires=2)\n\n circuit = qml.QNode(circuit_template, dev, interface=\"torch\")\n circuit2 = qml.QNode(circuit_decomposed, dev, interface=\"torch\")\n\n res = circuit(weights)\n res2 = circuit2(weights)\n assert qml.math.allclose(res, res2, atol=tol, rtol=0)\n\n res = circuit(weights)\n res.backward()\n grads = [weights.grad]\n\n res2 = circuit2(weights)\n res2.backward()\n grads2 = [weights.grad]\n\n assert np.allclose(grads[0], grads2[0], atol=tol, rtol=0)\n"
] | [
[
"numpy.random.normal",
"numpy.array",
"numpy.random.random",
"numpy.allclose"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
cce-bigdataintro-1160/spring2019 | [
"e55b24bda61bbc87ad39dfec93c68a8f2da77831"
] | [
"class5-notebook/6-pandas_creating_series.py"
] | [
"#!/usr/bin/env python3\n\nimport numpy as np\nimport pandas as pd\n\n\ndef pretty_print(name, to_print):\n print(f'{name}:')\n print(f'{to_print}\\n\\n')\n\n\norders = pd.Series(data=[300.50, 60, 123.40, 60, np.nan],\n index=['Customer 1', 'Customer 2', 'Customer 3', 'Customer 4', 'Customer 5'])\n\npretty_print(\"orders\", orders.to_string())\npretty_print(\"first row of orders\", orders.head(n=1))\npretty_print(\"orders indexes\", orders.index)\npretty_print(\"order types\", orders.dtypes)\npretty_print(\"orders shape\", orders.shape)\n\npretty_print(\"orders description with types\", orders.describe())\npretty_print(\"orders sorted values\", orders.sort_values())\npretty_print(\"orders counts of values\", orders.value_counts())\npretty_print(\"orders check for null elements\", orders.isnull())\n"
] | [
[
"pandas.Series"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
csherwood-usgs/CoastCam | [
"aa4de7c02ee0d719d89f13409319a44dba5eb768"
] | [
"original_code/calibration.py"
] | [
"import datetime\nfrom pathlib import Path\n\nimport numpy as np\nimport scipy.io\n\n\nclass CameraCalibration(object):\n \"\"\"Camera calibration saved in .mat file and method to assemble Projective (P) martrix.\n\n Notes:\n - Inspired by example code + notes from CiRC which are derived from Hartley and Zisserman (20030.)\n - Asssumes calibration saved in .mat file\n\n Args:\n calibration_file (str): Path to camera calibration file.\n\n Attributes:\n fname (str): Name of camera calibration file\n serial_number (int): Camera serial number\n camera_number (str): Camera number (e.g. 'c5')\n calibration_date (datetime): Date of camera calibration\n coordinate_system (str): Coordinate system used for calibration (e.g. 'xyz')\n beta (np.ndarray): Camera extrinsic calibration\n x (across shore), y (longshore), z (vertical), azimuth, tilt, roll\n lcp (dict): Lens Calibration Profile structure, the intrinsic camera calibration\n P (np.ndarray): Matrix containing intrinsic and extrinsic calibration\n \"\"\"\n def __init__(self, calibration_file):\n calibration_file = Path(calibration_file)\n self.fname = calibration_file.name\n sn, cn, dc, cs, _ = self.fname.split('_')\n self.serial_number = int(sn)\n self.camera_number = cn\n self.calibration_date = datetime.datetime.strptime(dc, '%Y%m%d')\n self.coordinate_system = cs\n\n mat_data = scipy.io.loadmat(calibration_file)\n self.beta = mat_data['beta'][0]\n self.lcp = self._load_lcp(mat_data['lcp'])\n self.P = self._assembleP()\n\n def _load_lcp(self, lcp):\n \"\"\"Return dict of lcp from lcp loaded from mat file\"\"\"\n NU = lcp[0, 0][0][0][0]\n NV = lcp[0, 0][1][0][0]\n c0U = lcp[0, 0][2][0][0]\n c0V = lcp[0, 0][3][0][0]\n fx = lcp[0, 0][4][0][0]\n fy = lcp[0, 0][5][0][0]\n d1 = lcp[0, 0][6][0][0]\n d2 = lcp[0, 0][7][0][0]\n d3 = lcp[0, 0][8][0][0]\n t1 = lcp[0, 0][9][0][0]\n t2 = lcp[0, 0][10][0][0]\n r = lcp[0, 0][11][0, :]\n caltech_fname = lcp[0, 0][12][0]\n fr = lcp[0, 0][13][0, :]\n x = lcp[0, 0][14][0, :]\n y = lcp[0, 0][15][0, :]\n dx = lcp[0, 0][16][:, :]\n dy = lcp[0, 0][17][:, :]\n\n return {\n 'NU': NU,\n 'NV': NV,\n 'c0U': c0U,\n 'c0V': c0V,\n 'fx': fx,\n 'fy': fy,\n 'd1': d1,\n 'd2': d2,\n 'd3': d3,\n 't1': t1,\n 't2': t2,\n 'r': r,\n 'fr': fr,\n 'caltech_fname': caltech_fname,\n 'x': x,\n 'y': y,\n 'dx': dx,\n 'dy': dy\n }\n\n def __repr__(self):\n msg = (\n f'serial_number: {self.serial_number}\\n'\n f'camera_number: {self.camera_number}\\n'\n f'calibration_date: {self.calibration_date}\\n'\n f'coordinate_system: {self.coordinate_system}\\n'\n f'beta: {self.beta}\\n'\n f\"sum of lcp r: {np.nansum(self.lcp['r'])}\"\n )\n return msg\n\n def __str__(self):\n msg = (\n f'serial_number: {self.serial_number}, '\n f'camera_number: {self.camera_number}, '\n f'calibration_date: {self.calibration_date}, '\n f'coordinate_system: {self.coordinate_system}'\n )\n return msg\n\n def _assembleP(self):\n \"\"\"Assembles and returns Projective (P) matrix from LCP and Beta values.\n\n Notes:\n - Derived from lcpBeta2P.m + CiRN notes\n - K converts angle away from the center of view into camera coordinates\n - R describes the 3D viewing direction of camera compared to world coordinates\n - beta[:3] camera location in world coordinates (x,y,z)\n - beta[3::] camera orientation (azimuth, tilt, roll)\n\n Returns:\n P (np.ndarray): Projective matrix\n \"\"\"\n # K: intrinsic matrix, puts image in pixel units of the specific camera\n K = np.array([\n [self.lcp['fx'], 0, self.lcp['c0U']],\n [0, -self.lcp['fy'], self.lcp['c0V']],\n [0, 0, 1]\n ])\n # R: rotation matrix, puts image in camera orientation\n R = angle2R(\n self.beta[3],\n self.beta[4],\n self.beta[5]\n )\n # I: identify matrix augmented by camera center, puts image in camera coordinates\n IC = np.vstack((\n np.eye(3),\n -self.beta[:3]\n )).T\n KR = np.matmul(K, R)\n P = np.matmul(KR, IC)\n\n # Make the matrix homogenous, methods use homogenous coordinates for easier math\n # - normalize to make last element equal 1\n P = P/P[-1, -1]\n\n return P\n\n\ndef angle2R(azimuth, tilt, swing):\n \"\"\"Assembles and returns a rotation matrix R from azimuth, tilt, and swing (roll)\n\n Notes:\n - derived from angles2R.m by Costal Imaging Research Network and Oregon State University\n - From p 612 of Wolf, 1983\n\n Arguments:\n azimuth (float): Azimuth\n tilt (float): Tilt\n swith (float): swing\n\n Returns:\n R (np.ndarray): Rotation matrix\n \"\"\"\n a = azimuth\n t = tilt\n s = swing\n R = np.zeros((3, 3))\n\n R[0, 0] = np.cos(a) * np.cos(s) + np.sin(a) * np.cos(t) * np.sin(s)\n R[0, 1] = -np.cos(s) * np.sin(a) + np.sin(s) * np.cos(t) * np.cos(a)\n R[0, 2] = np.sin(s) * np.sin(t)\n\n R[1, 0] = -np.sin(s) * np.cos(a) + np.cos(s) * np.cos(t) * np.sin(a)\n R[1, 1] = np.sin(s) * np.sin(a) + np.cos(s) * np.cos(t) * np.cos(a)\n R[1, 2] = np.cos(s) * np.sin(t)\n\n R[2, 0] = np.sin(t) * np.sin(a)\n R[2, 1] = np.sin(t) * np.cos(a)\n R[2, 2] = -np.cos(t)\n\n return R\n"
] | [
[
"numpy.eye",
"numpy.matmul",
"numpy.cos",
"numpy.sin",
"numpy.nansum",
"numpy.array",
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
fcole90/interactive_bayesian_optimization | [
"a7aabdd22e84e89e4e1a1c13afee2ba13cad2eb5"
] | [
"interactive_bayesian_optimisation/libs/io.py"
] | [
"\"\"\"Functions for input/output\"\"\"\n\nimport os\nimport logging\nfrom interactive_bayesian_optimisation import config\nfrom interactive_bayesian_optimisation.libs import utils\n\nimport numpy as np\nfrom flask import json\nimport simplejson.errors\nimport yaml\n\n\ndef get_file_item_max(file_dir, min_val=0):\n # Adding -1 to the list, allows to always find a max\n file_id_list = [int(session_id.split(\".\")[0]) for session_id in os.listdir(file_dir)] + [min_val - 1]\n return int(np.max(file_id_list))\n\n\ndef ensure_savedir_exists(save_dir=None, study_name=None, sub_path=None):\n if sub_path is None:\n os.makedirs(config.get_study_save_dir(save_dir, study_name), exist_ok=True)\n else:\n os.makedirs(os.path.join(config.get_study_save_dir(save_dir, study_name), sub_path), exist_ok=True)\n\n\ndef get_new_user_id(save_dir=None, study_name=None):\n study_dir = config.get_study_save_dir(save_dir, study_name)\n ensure_savedir_exists(save_dir, study_name)\n new_id = get_file_item_max(study_dir) + 1\n\n return str(new_id)\n\n\ndef get_new_session_id(user_id=None, save_dir=None, study_name=None):\n study_dir = os.path.join(config.get_study_save_dir(save_dir, study_name), str(user_id))\n ensure_savedir_exists(save_dir, study_name, str(user_id))\n new_id = get_file_item_max(study_dir) + 1\n\n return str(new_id)\n\n\ndef load_data(user_id, session_id, save_dir=None, study_name=None):\n study_dir = os.path.join(config.get_study_save_dir(save_dir, study_name), str(user_id))\n session_filename = str(session_id) + \".save.json\"\n session_file_path = os.path.join(study_dir, session_filename)\n with open(session_file_path, \"r\") as session_file:\n try:\n return json.load(session_file)\n except simplejson.errors.JSONDecodeError as e:\n logging.error(\"Possibly malformed JSON string:\\n\\n\"\n \"-----------------------------------\\n\"\n \"{}\\n\"\n \"-----------------------------------\".format(session_file.read()))\n raise e\n\n\n\ndef save_data(data, user_id, session_id, save_dir=None, study_name=None, incremental=False, override_name=None):\n extension = \".save.json\"\n study_dir = os.path.join(config.get_study_save_dir(save_dir, study_name), str(user_id))\n session_filename = str(session_id) + (\"\" if override_name is None else override_name)\n session_file_path = os.path.join(study_dir, session_filename)\n\n # Save JSONS in a list of JSON objects\n if incremental == False:\n session_file_path += extension\n\n if os.path.exists(session_file_path):\n save_data_list = load_data(user_id, session_id, study_name=study_name)\n else:\n save_data_list = list()\n\n save_data_list.append(data)\n\n with open(session_file_path, \"w\") as session_file:\n session_file.write(utils.remove_nan(json.dumps(save_data_list)))\n\n # Save JSON in a folder of JSON files (one per iteration)\n else: # incremental == True:\n ensure_savedir_exists(save_dir, study_name, os.path.join(str(user_id), str(session_id)))\n new_save_name = get_file_item_max(session_file_path) + 1\n session_file_path = os.path.join(session_file_path, str(new_save_name) + extension)\n with open(session_file_path, \"w\") as session_file:\n session_file.write(utils.remove_nan(json.dumps(data)))\n\n\n\n\ndef load_settings(settings_file_name):\n settings_file_path = os.path.join(config.SETTINGS_PATH, settings_file_name + \".yaml\")\n if os.path.exists(settings_file_path):\n with open(settings_file_path) as settings_file_name:\n return yaml.load(settings_file_name)\n else:\n logging.warning(\"Settings file {} was not found in {}.\".format(settings_file_name, config.SETTINGS_PATH))\n with open(os.path.join(config.SETTINGS_PATH, \"default.yaml\")) as settings_file_name:\n return yaml.load(settings_file_name)"
] | [
[
"numpy.max"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
BlairLee/dataset-insights | [
"892e2ed3a2facf97cfa3a883700830d959a0c49b"
] | [
"datasetinsights/estimators/deeplab.py"
] | [
"import copy\nimport logging\n\nimport numpy as np\nimport torch\nimport torchvision\nfrom ignite.metrics import Loss\nfrom torchvision import transforms as T\nfrom torchvision.transforms import functional as F\n\nimport datasetinsights.constants as const\nfrom datasetinsights.data.datasets import Dataset\nfrom datasetinsights.data.loader import create_loader\nfrom datasetinsights.data.transforms import Compose, RandomHorizontalFlip\nfrom datasetinsights.evaluation_metrics import EvaluationMetric\nfrom datasetinsights.visualization.plots import decode_segmap, grid_plot\n\nfrom .base import Estimator\n\nlogger = logging.getLogger(__name__)\n\n# Normalization constants (heuristics) from ImageNet dataset\n_IMGNET_MEAN = (0.485, 0.456, 0.406)\n_IMGNET_STD = (0.229, 0.224, 0.225)\n\n# Inverse Normalization constants\n_INV_IMGNET_MEAN = (-0.485 / 0.229, -0.456 / 0.224, -0.406 / 0.225)\n_INV_IMGNET_STD = (1.0 / 0.229, 1.0 / 0.224, 1.0 / 0.5)\n\n\ndef pad_if_smaller(img, size, fill=0):\n min_size = min(img.size)\n if min_size < size:\n ow, oh = img.size\n padh = size - oh if oh < size else 0\n padw = size - ow if ow < size else 0\n img = F.pad(img, (0, 0, padw, padh), fill=fill)\n\n return img\n\n\nclass RandomCrop:\n def __init__(self, size):\n self.size = size\n\n def __call__(self, image, target):\n image = pad_if_smaller(image, self.size)\n target = pad_if_smaller(target, self.size, fill=255)\n crop_params = T.RandomCrop.get_params(image, (self.size, self.size))\n image = F.crop(image, *crop_params)\n target = F.crop(target, *crop_params)\n\n return image, target\n\n\nclass ToTensor:\n \"\"\"Convert a pair of (image, target) to tensor\n \"\"\"\n\n def __call__(self, image, target):\n image = F.to_tensor(image)\n target = torch.as_tensor(np.asarray(target), dtype=torch.int64)\n\n return image, target\n\n\nclass Normalize:\n def __init__(self, mean, std):\n self.mean = mean\n self.std = std\n\n def __call__(self, image, target):\n image = F.normalize(image, mean=self.mean, std=self.std)\n\n return image, target\n\n\nclass DeeplabV3(Estimator):\n \"\"\" DeeplabV3 Model https://arxiv.org/abs/1706.05587\n\n Args:\n config (CfgNode): estimator config\n writer: Tensorboard writer object\n checkpointer: Model checkpointer callback to save models\n device: model training on device (cpu|cuda)\n Attributes:\n backbone: model backbone (resnet50|resnet101)\n num_classes: number of classes for semantic segmentation\n model: tensorflow or pytorch graph\n writer: Tensorboard writer object\n checkpointer: Model checkpointer callback to save models\n device: model training on device (cpu|cuda)\n optimizer: pytorch optimizer\n lr_scheduler: pytorch learning rate scheduler\n \"\"\"\n\n def __init__(self, *, config, writer, checkpointer, device, **kwargs):\n self.config = config\n\n self.backbone = config.backbone\n self.num_classes = config.num_classes\n\n model_name = \"deeplabv3_\" + self.backbone\n self.model = torchvision.models.segmentation.__dict__[model_name](\n num_classes=self.num_classes\n )\n\n self.writer = writer\n self.checkpointer = checkpointer\n self.device = device\n\n opname = config.optimizer.name\n if opname == \"Adam\":\n optimizer = torch.optim.Adam(\n self.model.parameters(), **config.optimizer.args\n )\n\n # use fixed learning rate when using Adam\n lr_scheduler = torch.optim.lr_scheduler.LambdaLR(\n optimizer, lambda x: 1.0\n )\n else:\n raise ValueError(f\"Unsupported optimizer type {opname}\")\n\n self.optimizer = optimizer\n self.lr_scheduler = lr_scheduler\n\n # load estimators from file if checkpoint_file exists\n ckpt_file = config.checkpoint_file\n if ckpt_file != const.NULL_STRING:\n checkpointer.load(self, ckpt_file)\n\n @staticmethod\n def _transforms(is_train=True, crop_size=769):\n \"\"\"Transformations for a pair of input and target image\n\n Args:\n is_train (bool): indicator whether this is a transformation\n during training (default: True)\n crop_size (int): crop size. Images will be cropped to\n (crop_size, crop_size)\n \"\"\"\n transforms = []\n if is_train:\n transforms.append(RandomHorizontalFlip(0.5))\n transforms.append(RandomCrop(crop_size))\n transforms.append(ToTensor())\n transforms.append(Normalize(mean=_IMGNET_MEAN, std=_IMGNET_STD))\n\n return Compose(transforms)\n\n @staticmethod\n def _loss_fn(outputs, target):\n \"\"\" Compute loss\n\n Args:\n outputs (dict): named output of deeplabv3 model. Since this\n implementation outpus two semantic segmentation images from two\n heads of the model, we are expecting dict of tow keys\n \"out\" and \"aux\" that corresponds to two pytorch tenor of images.\n target (torch.Tensor): ground truth 2D image tensor\n\n Returns:\n numerical value of loss\n \"\"\"\n losses = {}\n for name, x in outputs.items():\n losses[name] = torch.nn.functional.cross_entropy(\n x, target, ignore_index=255\n )\n\n if len(losses) == 1:\n return losses[\"out\"]\n\n return losses[\"out\"] + 0.5 * losses[\"aux\"]\n\n def _train_one_epoch(self, loader, epoch):\n \"\"\" Train one epoch\n\n Args:\n loader (DataLoader): pytorch dataloader\n epoch (int): the current epoch number\n \"\"\"\n logger.info(f\"Epoch[{epoch}] training started.\")\n self.model.train()\n n_batch = len(loader)\n accumulation_steps = self.config.train.accumulation_steps\n loss_metric = Loss(self._loss_fn)\n\n self.optimizer.zero_grad()\n for i, (image, target) in enumerate(loader):\n image, target = image.to(self.device), target.to(self.device)\n output = self.model(image)\n loss = self._loss_fn(output, target)\n loss.backward()\n\n # Accumulated Gradients are only updated after X steps.\n # This creates an effective batch size of\n # batch_size * accumulation_steps\n if (i + 1) % accumulation_steps == 0:\n self.optimizer.step()\n self.lr_scheduler.step()\n self.optimizer.zero_grad()\n\n loss_metric.update((output, target))\n\n iter_num = (i + 1) % n_batch\n logger.debug(\n f\"Epoch[{epoch}] Iteration[{iter_num}/{n_batch}] \"\n f\"Loss: {loss:.3f}\"\n )\n\n epoch_loss = loss_metric.compute()\n logger.info(\n f\"Epoch[{epoch}] training completed. Loss: {epoch_loss:.3f}\"\n )\n self.writer.add_scalar(\"training/loss\", epoch_loss, epoch)\n\n loss_metric.reset()\n\n def _evaluate_one_epoch(self, loader, epoch):\n \"\"\" Evaluate one epoch\n\n Args:\n loader (DataLoader): pytorch dataloader\n epoch (int): the current epoch number\n \"\"\"\n logger.info(f\"Epoch[{epoch}] evaluation started\")\n self.model.eval()\n loss_metric = Loss(self._loss_fn)\n\n # TODO: Support other metrics other than IoU and support multiple\n # mettics\n iou_metric = EvaluationMetric.create(\n self.config.metric, num_classes=self.num_classes\n )\n with torch.no_grad():\n for image, target in loader:\n image, target = image.to(self.device), target.to(self.device)\n output = self.model(image)\n\n loss_metric.update((output, target))\n iou_metric.update((output[\"out\"], target))\n\n loss = loss_metric.compute()\n iou = iou_metric.compute()\n\n # some classes are not used in cityscapes evaluation.\n # TODO: Move class masking logic to IoU metric class.\n keep_mask = [\n not c.ignore_in_eval\n for c in torchvision.datasets.Cityscapes.classes\n ]\n class_names = [c.name for c in torchvision.datasets.Cityscapes.classes]\n iou_info = {\n name: f\"{iou[i].item():.3f}\"\n for i, name in enumerate(class_names)\n if keep_mask[i]\n }\n miou = iou[keep_mask].mean()\n\n logger.info(\n f\"Epoch[{epoch}] evaluation completed. \"\n f\"Loss: {loss:.3f}, mIoU: {miou:.3f}\\n\"\n f\"IoU per class: {iou_info}\"\n )\n self.writer.add_scalar(\"validation/loss\", loss, epoch)\n self.writer.add_scalar(\"validation/miou\", miou, epoch)\n\n inv_normalize = T.Normalize(mean=_INV_IMGNET_MEAN, std=_INV_IMGNET_STD)\n # Visualize segmentation images from last mini-batch\n n_images = list(image.shape)[0]\n image_grid = []\n for i in range(n_images):\n img = inv_normalize(image[i, :]).permute(1, 2, 0).cpu().numpy()\n out = decode_segmap(output[\"out\"][i, :].max(0)[1].cpu().numpy())\n tgt = decode_segmap(target[i, :].cpu().numpy())\n image_grid.append([img, out, tgt])\n\n fig = grid_plot(image_grid)\n self.writer.add_figure(\"validation/visualize\", fig, epoch)\n\n loss_metric.reset()\n iou_metric.reset()\n\n def train(self, **kwargs):\n config = self.config\n train_dataset = Dataset.create(\n config.train.dataset,\n split=\"train\",\n data_root=config.system.data_root,\n transforms=self._transforms(\n is_train=True, crop_size=config.train.crop_size\n ),\n )\n train_loader = create_loader(\n train_dataset,\n batch_size=config.train.batch_size,\n num_workers=config.system.workers,\n dryrun=config.system.dryrun,\n )\n\n val_dataset = Dataset.create(\n config.val.dataset,\n split=\"val\",\n data_root=config.system.data_root,\n transforms=self._transforms(is_train=False),\n )\n val_loader = create_loader(\n val_dataset,\n batch_size=config.val.batch_size,\n num_workers=config.system.workers,\n dryrun=config.system.dryrun,\n )\n\n logger.info(\"Start training estimator: %s\", type(self).__name__)\n self.model.to(self.device)\n n_epochs = config.train.epochs\n val_interval = config.system.val_interval\n for epoch in range(1, n_epochs + 1):\n logger.info(f\"Training Epoch[{epoch}/{n_epochs}]\")\n self._train_one_epoch(train_loader, epoch)\n\n if epoch % val_interval == 0:\n self._evaluate_one_epoch(val_loader, epoch)\n\n self.checkpointer.save(self, epoch=epoch)\n\n def evaluate(self, **kwargs):\n config = self.config\n test_dataset = Dataset.create(\n config.test.dataset,\n split=\"test\",\n data_root=config.system.data_root,\n transforms=self._transforms(is_train=False),\n )\n test_loader = create_loader(\n test_dataset,\n batch_size=config.test.batch_size,\n num_workers=config.system.workers,\n dryrun=config.system.dryrun,\n )\n\n logger.info(\"Start evaluating estimator: %s\", type(self).__name__)\n self.model.to(self.device)\n self._evaluate_one_epoch(test_loader, epoch=1)\n\n def save(self, path):\n \"\"\" Serialize Estimator to path\n\n Args:\n path (str): full path to save serialized estimator\n\n Returns:\n saved full path of the serialized estimator\n \"\"\"\n save_dict = {\"model\": self.model.state_dict(), \"config\": self.config}\n torch.save(save_dict, path)\n\n return path\n\n def load(self, path):\n \"\"\" Load Estimator from path\n\n Args:\n path (str): full path to the serialized estimator\n \"\"\"\n checkpoint = torch.load(path)\n self.model.load_state_dict(checkpoint[\"model\"])\n\n loaded_config = copy.deepcopy(checkpoint[\"config\"])\n stored_config = copy.deepcopy(self.config)\n del stored_config[\"checkpoint_file\"]\n del loaded_config[\"checkpoint_file\"]\n if stored_config != loaded_config:\n logger.warning(\n f\"Found difference in estimator config.\"\n f\"Estimator loaded from {path} was trained using \"\n f\"config: \"\n f\"{loaded_config}. However, the current config is: \"\n f\"{self.config}.\"\n )\n"
] | [
[
"torch.optim.lr_scheduler.LambdaLR",
"torch.load",
"numpy.asarray",
"torch.nn.functional.cross_entropy",
"torch.no_grad",
"torch.save"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
pirun/waveform_analysis | [
"66809614b1fc985e694af1720341035316a5ac8e"
] | [
"waveform_analysis/_common.py"
] | [
"#!/usr/bin/env python\n\nfrom numpy import array_equal, polyfit, sqrt, mean, absolute, log10, arange\nimport numpy as np\nfrom scipy.stats import gmean\n\ntry:\n from soundfile import SoundFile\n wav_loader = 'pysoundfile'\nexcept:\n try:\n from scikits.audiolab import Sndfile\n wav_loader = 'scikits.audiolab'\n except:\n try:\n from scipy.io.wavfile import read\n wav_loader = 'scipy.io.wavfile'\n except:\n raise ImportError('No sound file loading package installed '\n '(PySoundFile, scikits.audiolab, or SciPy)')\n\n\ndef load(filename):\n \"\"\"\n Load a wave file and return the signal, sample rate and number of channels.\n\n Can be any format supported by the underlying library (libsndfile or SciPy)\n \"\"\"\n if wav_loader == 'pysoundfile':\n sf = SoundFile(filename)\n signal = sf.read()\n channels = sf.channels\n sample_rate = sf.samplerate\n sf.close()\n elif wav_loader == 'scikits.audiolab':\n sf = Sndfile(filename, 'r')\n signal = sf.read_frames(sf.nframes)\n channels = sf.channels\n sample_rate = sf.samplerate\n sf.close()\n elif wav_loader == 'scipy.io.wavfile':\n sample_rate, signal = read(filename)\n try:\n channels = signal.shape[1]\n except IndexError:\n channels = 1\n\n return signal, sample_rate, channels\n\n\ndef load_dict(filename):\n \"\"\"\n Load a wave file and return the signal, sample rate and number of channels.\n\n Can be any format supported by the underlying library (libsndfile or SciPy)\n \"\"\"\n soundfile = {}\n if wav_loader == 'pysoundfile':\n sf = SoundFile(filename)\n soundfile['signal'] = sf.read()\n soundfile['channels'] = sf.channels\n soundfile['fs'] = sf.samplerate\n soundfile['samples'] = len(sf)\n soundfile['format'] = sf.format_info + ' ' + sf.subtype_info\n sf.close()\n elif wav_loader == 'scikits.audiolab':\n sf = Sndfile(filename, 'r')\n soundfile['signal'] = sf.read_frames(sf.nframes)\n soundfile['channels'] = sf.channels\n soundfile['fs'] = sf.samplerate\n soundfile['samples'] = sf.nframes\n soundfile['format'] = sf.format\n sf.close()\n elif wav_loader == 'scipy.io.wavfile':\n soundfile['fs'], soundfile['signal'] = read(filename)\n try:\n soundfile['channels'] = soundfile['signal'].shape[1]\n except IndexError:\n soundfile['channels'] = 1\n soundfile['samples'] = soundfile['signal'].shape[0]\n soundfile['format'] = str(soundfile['signal'].dtype)\n\n return soundfile\n\n\ndef analyze_channels(filename, function):\n \"\"\"\n Given a filename, run the given analyzer function on each channel of the\n file\n \"\"\"\n signal, sample_rate, channels = load(filename)\n print('Analyzing \"' + filename + '\"...')\n\n if channels == 1:\n # Monaural\n function(signal, sample_rate)\n elif channels == 2:\n # Stereo\n if array_equal(signal[:, 0], signal[:, 1]):\n print('-- Left and Right channels are identical --')\n function(signal[:, 0], sample_rate)\n else:\n print('-- Left channel --')\n function(signal[:, 0], sample_rate)\n print('-- Right channel --')\n function(signal[:, 1], sample_rate)\n else:\n # Multi-channel\n for ch_no, channel in enumerate(signal.transpose()):\n print('-- Channel %d --' % (ch_no + 1))\n function(channel, sample_rate)\n\n\n# Copied from matplotlib.mlab:\n\ndef rms_flat(a):\n \"\"\"\n Return the root mean square of all the elements of *a*, flattened out.\n \"\"\"\n return sqrt(mean(absolute(a)**2))\n\n\ndef find(condition):\n \"Return the indices where ravel(condition) is true\"\n res, = np.nonzero(np.ravel(condition))\n return res\n\n\ndef dB(q):\n \"\"\"\n Return the level of a field quantity in decibels.\n \"\"\"\n return 20 * log10(q)\n\n\ndef spectral_flatness(spectrum):\n \"\"\"\n The spectral flatness is calculated by dividing the geometric mean of\n the power spectrum by the arithmetic mean of the power spectrum\n\n I'm not sure if the spectrum should be squared first...\n \"\"\"\n return gmean(spectrum)/mean(spectrum)\n\n\ndef parabolic(f, x):\n \"\"\"\n Quadratic interpolation for estimating the true position of an\n inter-sample maximum when nearby samples are known.\n\n f is a vector and x is an index for that vector.\n\n Returns (vx, vy), the coordinates of the vertex of a parabola that goes\n through point x and its two neighbors.\n\n Example:\n Defining a vector f with a local maximum at index 3 (= 6), find local\n maximum if points 2, 3, and 4 actually defined a parabola.\n\n In [3]: f = [2, 3, 1, 6, 4, 2, 3, 1]\n\n In [4]: parabolic(f, argmax(f))\n Out[4]: (3.2142857142857144, 6.1607142857142856)\n \"\"\"\n if int(x) != x:\n raise ValueError('x must be an integer sample index')\n else:\n x = int(x)\n xv = 1/2. * (f[x-1] - f[x+1]) / (f[x-1] - 2 * f[x] + f[x+1]) + x\n yv = f[x] - 1/4. * (f[x-1] - f[x+1]) * (xv - x)\n return (xv, yv)\n\n\ndef parabolic_polyfit(f, x, n):\n \"\"\"\n Use the built-in polyfit() function to find the peak of a parabola\n\n f is a vector and x is an index for that vector.\n\n n is the number of samples of the curve used to fit the parabola.\n \"\"\"\n a, b, c = polyfit(arange(x-n//2, x+n//2+1), f[x-n//2:x+n//2+1], 2)\n xv = -0.5 * b/a\n yv = a * xv**2 + b * xv + c\n return (xv, yv)\n"
] | [
[
"scipy.stats.gmean",
"numpy.absolute",
"numpy.array_equal",
"numpy.arange",
"numpy.log10",
"numpy.mean",
"numpy.ravel",
"scipy.io.wavfile.read"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"0.13",
"1.6",
"0.14",
"1.10",
"0.15",
"1.4",
"1.3",
"1.9",
"0.19",
"1.5",
"0.18",
"1.2",
"1.7",
"0.12",
"1.0",
"0.17",
"0.16",
"1.8"
],
"tensorflow": []
}
] |
luxufan/CS131_release | [
"e8a92582cfffee3ba6bb43f757bcb520785b6f04"
] | [
"hw1_release/filters.py"
] | [
"\"\"\"\nCS131 - Computer Vision: Foundations and Applications\nAssignment 1\nAuthor: Donsuk Lee ([email protected])\nDate created: 07/2017\nLast modified: 10/16/2017\nPython Version: 3.5+\n\"\"\"\n\nimport numpy as np\n\n\ndef conv_nested(image, kernel):\n \"\"\"A naive implementation of convolution filter.\n\n This is a naive implementation of convolution using 4 nested for-loops.\n This function computes convolution of an image with a kernel and outputs\n the result that has the same shape as the input image.\n\n Args:\n image: numpy array of shape (Hi, Wi).\n kernel: numpy array of shape (Hk, Wk).\n\n Returns:\n out: numpy array of shape (Hi, Wi).\n \"\"\"\n Hi, Wi = image.shape\n Hk, Wk = kernel.shape\n out = np.zeros((Hi, Wi))\n\n ### YOUR CODE HERE\n for i in range(Hi):\n for j in range(Wi):\n sum = 0\n for ii in range(-(Hk//2), Hk//2 + 1):\n for jj in range(-(Wk//2), Wk//2 + 1):\n sum += image[i - ii, j - jj] * kernel[ii + Hk // 2, jj + Wk // 2] \\\n if 0 <= i - ii < Hi and 0 <= j - jj < Wi else 0\n out[i, j] = sum\n ### END YOUR CODE\n\n return out\n\ndef zero_pad(image, pad_height, pad_width):\n \"\"\" Zero-pad an image.\n\n Ex: a 1x1 image [[1]] with pad_height = 1, pad_width = 2 becomes:\n\n [[0, 0, 0, 0, 0],\n [0, 0, 1, 0, 0],\n [0, 0, 0, 0, 0]] of shape (3, 5)\n\n Args:\n image: numpy array of shape (H, W).\n pad_width: width of the zero padding (left and right padding).\n pad_height: height of the zero padding (bottom and top padding).\n\n Returns:\n out: numpy array of shape (H+2*pad_height, W+2*pad_width).\n \"\"\"\n\n H, W = image.shape\n out = None\n\n ### YOUR CODE HERE\n out = np.pad(image, ((pad_height, pad_height), (pad_width, pad_width)), 'constant', constant_values = (0))\n pass\n ### END YOUR CODE\n return out\n\n\ndef conv_fast(image, kernel):\n \"\"\" An efficient implementation of convolution filter.\n\n This function uses element-wise multiplication and np.sum()\n to efficiently compute weighted sum of neighborhood at each\n pixel.\n\n Hints:\n - Use the zero_pad function you implemented above\n - There should be two nested for-loops\n - You may find np.flip() and np.sum() useful\n\n Args:\n image: numpy array of shape (Hi, Wi).\n kernel: numpy array of shape (Hk, Wk).\n\n Returns:\n out: numpy array of shape (Hi, Wi).\n \"\"\"\n Hi, Wi = image.shape\n Hk, Wk = kernel.shape\n out = np.zeros((Hi, Wi))\n\n ### YOUR CODE HERE\n image_pad = zero_pad(image, Hk // 2, Wk // 2)\n kernel_flip = np.flip(np.flip(kernel, axis=0), axis=1)\n for i in range(Hi):\n for j in range(Wi):\n out[i, j] = np.sum(image_pad[i:i + Hk, j:j + Wk] * kernel_flip)\n ### END YOUR CODE\n\n return out\n\ndef conv_faster(image, kernel):\n \"\"\"\n Args:\n image: numpy array of shape (Hi, Wi).\n kernel: numpy array of shape (Hk, Wk).\n\n Returns:\n out: numpy array of shape (Hi, Wi).\n \"\"\"\n Hi, Wi = image.shape\n Hk, Wk = kernel.shape\n out = np.zeros((Hi, Wi))\n\n ### YOUR CODE HERE\n out = image.copy()\n u, s, v = np.linalg.svd(kernel)\n kernel_u = (u.T[s > 1e-6]).T\n kernel_v = (v[s > 1e-6])\n for p in range(np.sum(s > 1e-6)):\n out = conv_fast(out, (kernel_u[:, p] * s[p]).reshape(Hk, 1))\n out = conv_fast(out, kernel_v[p].reshape(1, Wk))\n ### END YOUR CODE\n\n return out\n\ndef cross_correlation(f, g):\n \"\"\" Cross-correlation of f and g.\n\n Hint: use the conv_fast function defined above.\n\n Args:\n f: numpy array of shape (Hf, Wf).\n g: numpy array of shape (Hg, Wg).\n\n Returns:\n out: numpy array of shape (Hf, Wf).\n \"\"\"\n\n out = None\n ### YOUR CODE HERE\n out = conv_fast(f, np.flip(np.flip(g, axis=0), axis=1))\n ### END YOUR CODE\n\n return out\n\ndef zero_mean_cross_correlation(f, g):\n \"\"\" Zero-mean cross-correlation of f and g.\n\n Subtract the mean of g from g so that its mean becomes zero.\n\n Hint: you should look up useful numpy functions online for calculating the mean.\n\n Args:\n f: numpy array of shape (Hf, Wf).\n g: numpy array of shape (Hg, Wg).\n\n Returns:\n out: numpy array of shape (Hf, Wf).\n \"\"\"\n\n out = None\n ### YOUR CODE HERE\n zero_mean_g = g - np.mean(g)\n zero_mean_f = f - np.mean(g)\n out = conv_fast(zero_mean_f, np.flip(np.flip(zero_mean_g, axis=0), axis=1))\n ### END YOUR CODE\n\n return out\n\ndef normalized_cross_correlation(f, g):\n \"\"\" Normalized cross-correlation of f and g.\n\n Normalize the subimage of f and the template g at each step\n before computing the weighted sum of the two.\n\n Hint: you should look up useful numpy functions online for calculating\n the mean and standard deviation.\n\n Args:\n f: numpy array of shape (Hf, Wf).\n g: numpy array of shape (Hg, Wg).\n\n Returns:\n out: numpy array of shape (Hf, Wf).\n \"\"\"\n\n out = None\n ### YOUR CODE HERE\n Hf, Wf = f.shape\n out = np.zeros((Hf, Wf))\n g = g[:-1, :] if g.shape[0] % 2 == 0 else g\n g = g[:, :-1] if g.shape[1] % 2 == 0 else g\n Hg, Wg = g.shape\n normalized_filter = (g - np.mean(g)) / np.std(g)\n f = zero_pad(f, Hg // 2, Wg // 2)\n for i in range(Hf):\n for j in range(Wf):\n normalized_template = (f[i:i+Hg, j:j+Wg] - np.mean(f[i:i+Hg, j:j+Wg])) / np.std(f[i:i+Hg, j:j+Wg])\n out[i, j] = np.sum(normalized_template * g)\n ### END YOUR CODE\n\n return out\n"
] | [
[
"numpy.linalg.svd",
"numpy.pad",
"numpy.std",
"numpy.mean",
"numpy.flip",
"numpy.sum",
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
aaryapatil/specdims | [
"acfc644aa06b13c8b34cde984e207b42e948af41"
] | [
"delfiSpec/specproc.py"
] | [
"# Import dependencies\nimport numpy as np\nfrom apogee.spec import continuum\nfrom apogee.tools import bitmask as bm\n\nfrom .util import get_DR_slice, bitsNotSet\n\n# Future: Define a class for spectra - spectra, error and weight\n\ndef process_spectra(spectra_info=None, badcombpixmask=4351, minSNR=50.):\n cont_cannon = continuum.fit(spectra_info[:, 0], spectra_info[:, 1], type='cannon')\n\n spectra_info[:, 0] = spectra_info[:, 0]/cont_cannon\n spectra_info[:, 1] = spectra_info[:, 1]/cont_cannon\n\n # Get DR indices\n spec = get_DR_slice(spectra_info[:, 0])\n spec_err = get_DR_slice(spectra_info[:, 1])\n bitmask = (get_DR_slice(spectra_info[:, 2])).astype('int')\n\n maskbits = bm.bits_set(badcombpixmask)\n # Mask where SNR low or where something flagged in bitmask\n mask = (spec/spec_err < minSNR) | bitsNotSet(bitmask, maskbits)\n\n # Errors below 0.005 in APOGEE are not trusted \n spec_err[spec_err<0.005] = 0.005\n \n try:\n weight = 1.0 / spec_err**2\n except:\n # Handling zero errors\n zero_errors = np.where(spec_err==0)\n listOfCoordinates= list(zip(zero_errors[0], zero_errors[1]))\n for cord in listOfCoordinates:\n spec_err[cord] = np.median(spec_err)\n\n weight = 1.0 / spec_err**2\n\n np.place(weight, mask, 0)\n return np.squeeze(spec), np.squeeze(spec_err), np.squeeze(weight)"
] | [
[
"numpy.squeeze",
"numpy.place",
"numpy.where",
"numpy.median"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
yhCyan/graph-tensor-propagation | [
"b216fb24c5b9ea21d7b338ac24b272b0f346fcc3",
"b216fb24c5b9ea21d7b338ac24b272b0f346fcc3"
] | [
"exp_gqa/main.py",
"models_gqa/output_unit.py"
] | [
"import os\nimport json\nimport torch\nimport sys\nimport time\nimport random\nimport numpy as np\n\nfrom tqdm import tqdm, trange\nimport torch.multiprocessing as mp\nimport torch.distributed as dist\nfrom torch.utils.tensorboard import SummaryWriter\nfrom apex.parallel import DistributedDataParallel as DDP\nfrom apex import amp\n\nsys.path.append('..')\nfrom models_gqa.model import LCGNwrapper\nfrom models_gqa.config import build_cfg_from_argparse\nfrom util.gqa_train.data_reader import DataReader\n#from util.gqa_train.data_reader import gqa_convert_examples_to_features\n# Load config\n# cmd = '--cfg /home/xdjf/lcgn-pytorch/exp_gqa/cfgs/lcgn_spatial.yaml train True'.split()\n# sys.argv.extend(cmd)\n\n# Start session\n#os.environ[\"CUDA_VISIBLE_DEVICES\"] = cfg.GPUS\n# if len(cfg.GPUS.split(',')) > 1:\n# print('PyTorch implementation currently only supports single GPU')\nimport wandb\n\n\ndef load_train_data(cfg, rank, gpu, max_num=0, num_replicas=1):\n imdb_file = cfg.IMDB_FILE % cfg.TRAIN.SPLIT_VQA\n scene_graph_file = cfg.SCENE_GRAPH_FILE % \\\n cfg.TRAIN.SPLIT_VQA.replace('_balanced', '').replace('_all', '')\n #a = gqa_convert_examples_to_features(imdb_file, scene_graph_file, cfg)\n\n data_reader = DataReader(\n imdb_file, rank, gpu, num_replicas, shuffle=True, max_num=max_num,\n batch_size=cfg.TRAIN.BATCH_SIZE,\n vocab_question_file=cfg.VOCAB_QUESTION_FILE,\n T_encoder=cfg.T_ENCODER,\n N_encoder=cfg.N_ENCODER,\n O_encoder = cfg.O_ENCODER,\n vocab_answer_file=cfg.VOCAB_ANSWER_FILE,\n feature_type=cfg.FEAT_TYPE,\n spatial_feature_dir=cfg.SPATIAL_FEATURE_DIR,\n objects_feature_dir=cfg.OBJECTS_FEATURE_DIR,\n objects_max_num=cfg.W_FEAT,\n scene_graph_file=scene_graph_file,\n vocab_name_file=cfg.VOCAB_NAME_FILE,\n vocab_attr_file=cfg.VOCAB_ATTR_FILE,\n add_pos_enc=cfg.ADD_POS_ENC,\n pos_enc_dim=cfg.PE_DIM, \n pos_enc_scale=cfg.PE_SCALE)\n num_vocab = data_reader.batch_loader.vocab_dict.num_vocab\n num_choices = data_reader.batch_loader.answer_dict.num_vocab\n return data_reader, num_vocab, num_choices\n\n\ndef batch_to_data(batch):\n questionIndices = torch.from_numpy(\n batch['input_seq_batch'].astype(np.int64)).cuda() # 128 * 30\n questionLengths = torch.from_numpy(\n batch['seq_length_batch'].astype(np.int64)).cuda() # 128\n semanIndices = torch.from_numpy(\n batch['input_seman_batch'].astype(np.int64)).cuda() # 128 * 30\n semanLengths = torch.from_numpy(\n batch['seman_length_batch'].astype(np.int64)).cuda() # 128\n answerIndices = torch.from_numpy(\n batch['answer_label_batch'].astype(np.int64)).cuda() # 128\n nameIndices = torch.from_numpy(\n batch['input_name_batch'].astype(np.int64)).cuda()\n nameLengths = torch.from_numpy(\n batch['name_length_batch'].astype(np.int64)).cuda()\n images = torch.from_numpy(\n batch['image_feat_batch'].astype(np.float32)).cuda() # 128 * 49 * 2112\n imagesObjectNum = torch.from_numpy(\n np.sum(batch['image_valid_batch'].astype(np.int64), axis=1)).cuda() # 128\n\n\n return (questionIndices, questionLengths, semanIndices, semanLengths, answerIndices, nameIndices, nameLengths, images, imagesObjectNum)\n\ndef run_train_on_data(model, data_reader_train, cfg, rank, gpu, run_eval=False,\n data_reader_eval=None):\n model.train()\n\n global_step = 1\n lr = cfg.TRAIN.SOLVER.LR\n correct, total, loss_sum, batch_num = 0, 0, 0., 0\n tr_loss, logging_loss = 0.0, 0.0\n\n # if rank in [-1, 0]:\n # tb_writer = SummaryWriter()\n \n for batch, n_sample, e in data_reader_train.batches(one_pass=False):\n n_epoch = cfg.TRAIN.START_EPOCH + e\n if n_sample == 0 and n_epoch > cfg.TRAIN.START_EPOCH and rank in [-1, 0]:\n print('')\n # save snapshot\n snapshot_file = cfg.SNAPSHOT_FILE % (cfg.EXP_NAME, n_epoch)\n torch.save(model.state_dict(), snapshot_file)\n # run evaluation\n if run_eval:\n batch_eval = run_eval_on_data(cfg, model, data_reader_eval)\n #tb_writer.add_scalar(\"eval_loss\", batch_eval['loss'], global_step)\n model.train()\n if cfg.DEBUG == False:\n wandb.log({\"eval_loss\": batch_eval['loss'], \"eval_correct\": batch_eval['accuracy']})\n # clear stats\n correct, total, loss_sum, batch_num = 0, 0, 0., 0\n if n_epoch >= cfg.TRAIN.MAX_EPOCH:\n break\n\n batch_list = batch_to_data(batch)\n # if first and rank in [-1, 0]:\n # tb_writer.add_graph(model.model, (batch_list, ))\n # first = False\n \n batch_res = model.run_batch(batch_list, train=True, lr=lr)\n correct += batch_res['num_correct']\n total += batch_res['batch_size']\n loss_sum += batch_res['loss'].item()\n tr_loss += loss_sum\n batch_num += 1\n global_step += 1\n lr = batch_res['lr']\n \n if rank in [-1, 0] and cfg.logging_steps > 0 and global_step % cfg.logging_steps == 0 and cfg.DEBUG == False:\n wandb.log({\"lr\": batch_res['lr'], \"train_loss\": loss_sum/batch_num, \"train_correct\": correct/total})\n # tb_writer.add_scalar(\"lr\", batch_res['lr'], global_step)\n # tb_writer.add_scalar(\"loss\", (tr_loss - logging_loss) / cfg.logging_steps, global_step)\n\n if rank in [-1, 0]:\n print('\\rTrain E %d S %d: avgL=%.4f, avgA=%.4f, lr=%.1e' % (\n n_epoch+1, total, loss_sum/batch_num, correct/total, lr),\n end='')\n\n # if rank in [-1, 0]:\n # tb_writer.close()\n\n\ndef load_eval_data(cfg, rank, gpu, max_num=0):\n imdb_file = cfg.IMDB_FILE % cfg.TEST.SPLIT_VQA\n scene_graph_file = cfg.SCENE_GRAPH_FILE % \\\n cfg.TEST.SPLIT_VQA.replace('_balanced', '').replace('_all', '')\n data_reader = DataReader(\n imdb_file, rank, gpu, 1, shuffle=False, max_num=max_num,\n batch_size=cfg.TEST.BATCH_SIZE,\n vocab_question_file=cfg.VOCAB_QUESTION_FILE,\n T_encoder=cfg.T_ENCODER,\n N_encoder=cfg.N_ENCODER,\n O_encoder = cfg.O_ENCODER,\n vocab_answer_file=cfg.VOCAB_ANSWER_FILE,\n feature_type=cfg.FEAT_TYPE,\n spatial_feature_dir=cfg.SPATIAL_FEATURE_DIR,\n objects_feature_dir=cfg.OBJECTS_FEATURE_DIR,\n objects_max_num=cfg.W_FEAT,\n scene_graph_file=scene_graph_file,\n vocab_name_file=cfg.VOCAB_NAME_FILE,\n vocab_attr_file=cfg.VOCAB_ATTR_FILE,\n add_pos_enc=cfg.ADD_POS_ENC,\n pos_enc_dim=cfg.PE_DIM, pos_enc_scale=cfg.PE_SCALE)\n num_vocab = data_reader.batch_loader.vocab_dict.num_vocab\n num_choices = data_reader.batch_loader.answer_dict.num_vocab\n return data_reader, num_vocab, num_choices\n\n\ndef run_eval_on_data(cfg, model, data_reader_eval, pred=False):\n model.eval()\n predictions = []\n answer_tokens = data_reader_eval.batch_loader.answer_dict.word_list\n correct, total, loss_sum, batch_num = 0, 0, 0., 0\n for batch, _, _ in data_reader_eval.batches(one_pass=True):\n batch_list = batch_to_data(batch)\n batch_res = model.run_batch(batch_list, train=False)\n if pred:\n predictions.extend([\n {'questionId': q, 'prediction': answer_tokens[p]}\n for q, p in zip(batch['qid_list'], batch_res['predictions'])])\n correct += batch_res['num_correct']\n total += batch_res['batch_size']\n loss_sum += batch_res['loss'].item()\n batch_num += 1\n print('\\rEval S %d: avgL=%.4f, avgA=%.4f' % (\n total, loss_sum/batch_num, correct/total), end='')\n print('')\n eval_res = {\n 'correct': correct,\n 'total': total,\n 'accuracy': correct/total,\n 'loss': loss_sum/batch_num,\n 'predictions': predictions}\n return eval_res\n\n\ndef dump_prediction_to_file(cfg, predictions, res_dir):\n pred_file = os.path.join(res_dir, 'pred_%s_%04d_%s.json' % (\n cfg.EXP_NAME, cfg.TEST.EPOCH, cfg.TEST.SPLIT_VQA))\n with open(pred_file, 'w') as f:\n json.dump(predictions, f, indent=2)\n print('predictions written to %s' % pred_file)\n\n\ndef set_seed(args):\n random.seed(args.seed)\n np.random.seed(args.seed)\n torch.manual_seed(args.seed)\n if args.n_gpus > 0:\n torch.cuda.manual_seed_all(args.seed)\n\n\ndef train(gpu, cfg):\n\n rank = -1\n if gpu != -1:\n rank = cfg.nr * cfg.n_gpus + gpu\t \n dist.init_process_group( \n \tbackend='nccl', \n \t\tinit_method='env://', \n \tworld_size=cfg.world_size, \n \trank=rank \n ) \n if rank in [-1, 0, 1]:\n gpu = 0\n elif rank in [2, 3]:\n gpu = 1\n \n set_seed(cfg)\n\n print(f'rank: {rank} pid: {os.getpid()} is running...')\n num_replicas = cfg.world_size if rank != -1 else 1\n data_reader_train, num_vocab, num_choices = load_train_data(cfg, rank, gpu, num_replicas=num_replicas)\n data_reader_eval, _, _ = load_eval_data(cfg, rank, gpu, max_num=cfg.TRAIN.EVAL_MAX_NUM)\n # Load model\n\n model = LCGNwrapper(num_vocab, num_choices, cfg=cfg, rank=rank, gpu=gpu)\n # Save snapshot\n if rank in [-1, 0]:\n if cfg.DEBUG == False:\n name = time.strftime('%Y%m%d-%H%M%S')\n wandb.init(project=\"gtp\", notes=\"graph tensor propa\", name=name)\n wandb.watch(model.model, log=\"all\")\n wandb.config.update(cfg)\n snapshot_dir = os.path.dirname(cfg.SNAPSHOT_FILE % (cfg.EXP_NAME, 0))\n os.makedirs(snapshot_dir, exist_ok=True)\n with open(os.path.join(snapshot_dir, 'cfg.json'), 'w') as f:\n json.dump(cfg, f, indent=2)\n if cfg.TRAIN.START_EPOCH > 0 and rank in [-1, 0]:\n print('resuming from epoch %d' % cfg.TRAIN.START_EPOCH)\n model.load_state_dict(torch.load(\n cfg.SNAPSHOT_FILE % (cfg.EXP_NAME, cfg.TRAIN.START_EPOCH)))\n\n if rank in [-1, 0]:\n print('%s - train for %d epochs' % (cfg.EXP_NAME, cfg.TRAIN.MAX_EPOCH))\n run_train_on_data(\n model, data_reader_train, cfg, rank, gpu, run_eval=cfg.TRAIN.RUN_EVAL,\n data_reader_eval=data_reader_eval)\n if rank in [-1, 0]:\n print('%s - train (done)' % cfg.EXP_NAME)\n\n\ndef test(cfg):\n data_reader_eval, num_vocab, num_choices = load_eval_data(cfg, -1, 0)\n\n # Load model\n model = LCGNwrapper(num_vocab, num_choices, cfg)\n\n # Load test snapshot\n snapshot_file = cfg.SNAPSHOT_FILE % (cfg.EXP_NAME, cfg.TEST.EPOCH)\n model.load_state_dict(torch.load(snapshot_file))\n\n res_dir = cfg.TEST.RESULT_DIR % (cfg.EXP_NAME, cfg.TEST.EPOCH)\n vis_dir = os.path.join(\n res_dir, '%s_%s' % (cfg.TEST.VIS_DIR_PREFIX, cfg.TEST.SPLIT_VQA))\n os.makedirs(res_dir, exist_ok=True)\n os.makedirs(vis_dir, exist_ok=True)\n pred = cfg.TEST.DUMP_PRED\n if not pred:\n print('NOT writing predictions (set TEST.DUMP_PRED True to write)')\n\n print('%s - test epoch %d' % (cfg.EXP_NAME, cfg.TEST.EPOCH))\n eval_res = run_eval_on_data(cfg, model, data_reader_eval, pred=pred)\n print('%s - test epoch %d: accuracy = %.4f' % (\n cfg.EXP_NAME, cfg.TEST.EPOCH, eval_res['accuracy']))\n\n # write results\n if pred:\n dump_prediction_to_file(cfg, eval_res['predictions'], res_dir)\n eval_res.pop('predictions')\n res_file = os.path.join(res_dir, 'res_%s_%04d_%s.json' % (\n cfg.EXP_NAME, cfg.TEST.EPOCH, cfg.TEST.SPLIT_VQA))\n with open(res_file, 'w') as f:\n json.dump(eval_res, f)\n\n\nif __name__ == '__main__':\n\n cfg = build_cfg_from_argparse()\n start = time.time()\n print(f'pid: {os.getpid()} is running...')\n if cfg.train:\n if cfg.n_gpus > 1:\n os.environ['MASTER_ADDR'] = '127.0.0.1' \n os.environ['MASTER_PORT'] = '12801' \n cfg.world_size = cfg.n_gpus * cfg.nodes\n mp.spawn(train, nprocs=cfg.n_gpus, args=(cfg,))\n else:\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = cfg.GPUS\n train(-1, cfg)\n end_ = time.time()\n if cfg.DEBUG == False:\n wandb.log({\"training time\": int((end_ - start) / 60)})\n print(f'time has cost : {end_ - start}')\n else:\n test(cfg)\n",
"import torch\nfrom torch import nn\n\nfrom . import ops as ops\nfrom .config import cfg\n\n\nclass Classifier(nn.Module):\n def __init__(self, num_choices):\n super().__init__()\n self.outQuestion = ops.Linear(cfg.CMD_DIM, cfg.CTX_DIM)\n in_dim = 3 * cfg.CTX_DIM if cfg.OUT_QUESTION_MUL else 2 * cfg.CTX_DIM\n self.classifier_layer = nn.Sequential(\n nn.Dropout(1 - cfg.outputDropout),\n ops.Linear(in_dim, cfg.OUT_CLASSIFIER_DIM),\n nn.ELU(),\n nn.Dropout(1 - cfg.outputDropout),\n ops.Linear(cfg.OUT_CLASSIFIER_DIM, num_choices))\n\n def forward(self, x_att, vecQuestions):\n eQ = self.outQuestion(vecQuestions)\n if cfg.OUT_QUESTION_MUL:\n features = torch.cat([x_att, eQ, x_att*eQ], dim=-1)\n else:\n features = torch.cat([x_att, eQ], dim=-1)\n logits = self.classifier_layer(features)\n return logits\n\n\nclass BboxRegression(nn.Module):\n def __init__(self):\n super().__init__()\n self.bbox_offset_fcn = ops.Linear(cfg.CTX_DIM, 4)\n\n def forward(self, x_out, loc_scores):\n bbox_offset_fcn = self.bbox_offset_fcn(x_out)\n bbox_offset_flat = bbox_offset_fcn.view(-1, 4)\n\n assert len(x_out.size()) == 3\n batch_size = x_out.size(0)\n max_entity_num = x_out.size(1)\n slice_inds = (\n torch.arange(batch_size, device=x_out.device) * max_entity_num +\n torch.argmax(loc_scores, dim=-1))\n bbox_offset = bbox_offset_flat[slice_inds]\n\n return bbox_offset, bbox_offset_fcn\n"
] | [
[
"torch.distributed.init_process_group",
"numpy.random.seed",
"torch.load",
"torch.multiprocessing.spawn",
"torch.manual_seed",
"torch.cuda.manual_seed_all"
],
[
"torch.nn.Dropout",
"torch.cat",
"torch.nn.ELU",
"torch.arange",
"torch.argmax"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
tomelf/cnit-623 | [
"edf25f0b216b2480f7b651d3b94c1377dff721c0",
"edf25f0b216b2480f7b651d3b94c1377dff721c0"
] | [
"task3_doc2vec_svm.py",
"task3_ngrams_svm.py"
] | [
"import data_loader\nimport numpy as np\nimport pandas as pd\nimport re\nimport os.path\n\nfrom itertools import product\nfrom string import ascii_lowercase\n\nfrom sklearn.pipeline import Pipeline, FeatureUnion\nfrom sklearn.decomposition import PCA, TruncatedSVD\nfrom sklearn.metrics import roc_auc_score, accuracy_score, classification_report\nfrom sklearn.svm import SVC\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.feature_extraction.text import TfidfTransformer, TfidfVectorizer\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.externals import joblib\nfrom sklearn.linear_model import ElasticNet\n\ndef main():\n cols = [\"dim_{}\".format(i+1) for i in range(300)] + [\"label\"] + [\"meta_id\"]\n train_df = pd.read_csv(\"dataset/data_doc2vec_non-pretrained/train_docvec_lang_sentid.csv\", names=cols)\n dev_df = pd.read_csv(\"dataset/data_doc2vec_non-pretrained/dev_docvec_lang_sentid.csv\", names=cols)\n test_df = pd.read_csv(\"dataset/data_doc2vec_non-pretrained/test_docvec_lang_sentid.csv\", names=cols)\n \n train_actual = train_df[\"label\"].tolist()\n dev_actual = dev_df[\"label\"].tolist()\n test_actual = test_df[\"label\"].tolist()\n \n train_data_df = train_df.iloc[:,:(len(cols)-2)]\n dev_data_df = dev_df.iloc[:,:(len(cols)-2)]\n test_data_df = test_df.iloc[:,:(len(cols)-2)]\n \n print(\"Start pipeline\")\n pipeline = Pipeline([\n ('clf', SVC(decision_function_shape='ovo', C=20)),\n ])\n \n param_grid = dict(\n clf__kernel=['rbf'],\n clf__C=[0.1, 1, 10, 20])\n grid_search = GridSearchCV(pipeline, param_grid=param_grid, cv=5, verbose=10, return_train_score=True)\n \n train_pred = grid_search.fit(train_data_df, train_actual).predict(train_data_df)\n test_pred = grid_search.predict(test_data_df)\n \n with open(\"task3_test_doc2vec.txt\", \"w\") as output:\n output.write(\"Training results:\\n{}\\n\".format(classification_report(train_actual, train_pred)))\n output.write(\"Testing results:\\n{}\\n\".format(classification_report(test_actual, test_pred)))\n print(classification_report(train_actual, train_pred))\n print(classification_report(test_actual, test_pred))\n \n pd.DataFrame(grid_search.cv_results_).to_csv(\"task3_grid_search_doc2vec.csv\")\n\nif __name__ == \"__main__\":\n main()\n",
"import data_loader\nimport numpy as np\nimport pandas as pd\nimport re\nimport os.path\n\nfrom itertools import product\nfrom string import ascii_lowercase\n\nfrom sklearn.pipeline import Pipeline, FeatureUnion\nfrom sklearn.decomposition import PCA, TruncatedSVD\nfrom sklearn.metrics import roc_auc_score, accuracy_score, classification_report\nfrom sklearn.svm import SVC\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.feature_extraction.text import TfidfTransformer, TfidfVectorizer\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.externals import joblib\n\nfrom util.feature.CharNGrams import CharNGrams\nfrom util.feature.FunctionWords import FunctionWords\nfrom util.feature.ItemSelector import ItemSelector\n\ndef main():\n meta_list, data_list = data_loader.load_data(load_train=True, load_dev=False, load_test=True)\n train_meta, train_meta_corrected, \\\n test_meta, test_meta_corrected = meta_list\n train_data, train_data_corrected, \\\n test_data, test_data_corrected = data_list\n \n train_data_df = [[\" \".join(td[\"form\"].tolist()), \" \".join(td[\"upostag\"].tolist()), \" \".join(train_meta[\"errors\"].iloc[i])] for i, td in enumerate(train_data)]\n test_data_df = [[\" \".join(td[\"form\"].tolist()), \" \".join(td[\"upostag\"].tolist()), \" \".join(test_meta[\"errors\"].iloc[i])] for i, td in enumerate(test_data)]\n cols = [\"form\", \"upostag\", \"errors\"]\n train_data_df = pd.DataFrame(train_data_df, columns=cols)\n test_data_df = pd.DataFrame(test_data_df, columns=cols)\n train_actual = train_meta[\"native_language\"].tolist()\n test_actual = test_meta[\"native_language\"].tolist()\n \n print(\"Start pipeline\")\n # char_ngrams\n char_ngrams_md = CharNGrams(3)\n char_ngrams_vocabs = char_ngrams_md.get_features()\n # function words\n funcwords_md = FunctionWords(\"function_words.txt\")\n funcwords_vocabs = funcwords_md.get_features()\n \n pipeline = Pipeline([\n ('union', FeatureUnion(\n transformer_list = [\n ('errors', Pipeline([\n ('selector', ItemSelector(key='errors')),\n ('tfidf', TfidfVectorizer(analyzer=\"word\", \n ngram_range=(1,1), \n lowercase=True)\n )\n ])),\n ('funcwords', Pipeline([\n ('selector', ItemSelector(key='form')),\n ('tfidf', TfidfVectorizer(analyzer=\"word\", \n ngram_range=(1,4), \n lowercase=True, \n vocabulary=funcwords_vocabs)\n ),\n ('reduce_dim', TruncatedSVD()),\n ])),\n ('charngrams', Pipeline([\n ('selector', ItemSelector(key='form')),\n ('tfidf', TfidfVectorizer(analyzer=\"char\", \n ngram_range=(3,3), \n lowercase=True, \n vocabulary=char_ngrams_vocabs)\n ),\n ('reduce_dim', TruncatedSVD()),\n ])),\n ('wordngrams', Pipeline([\n ('selector', ItemSelector(key='form')),\n ('tfidf', TfidfVectorizer(analyzer=\"word\", \n ngram_range=(1,2), \n lowercase=True)\n ),\n ('reduce_dim', TruncatedSVD()),\n ])),\n ('posngrams', Pipeline([\n ('selector', ItemSelector(key='upostag')),\n ('tfidf', TfidfVectorizer(analyzer=\"word\", \n ngram_range=(2,2), \n lowercase=True)\n )\n ])),\n ],\n transformer_weights={\n 'errors': 1,\n 'funcwords': 1,\n 'charngrams': 1,\n 'wordngrams': 1,\n 'posngrams': 1,\n },\n )),\n ('clf', SVC(decision_function_shape='ovo', C=20)),\n ])\n \n param_grid = dict(\n union__errors__tfidf__norm=['l1', 'l2', None],\n union__funcwords__reduce_dim__n_components=[10, 50, 100],\n union__charngrams__reduce_dim__n_components=[50, 100, 200],\n union__wordngrams__reduce_dim__n_components=[50, 100, 200],\n union__wordngrams__tfidf__ngram_range=[(1,1), (2,2), (1,2)],\n union__posngrams__tfidf__ngram_range=[(1,1), (2,2), (3,3), (1,3)],\n clf__kernel=['linear', 'poly', 'rbf'],\n clf__C=[0.1, 1, 10, 20])\n grid_search = GridSearchCV(pipeline, param_grid=param_grid, cv=5, verbose=10, return_train_score=True)\n \n train_pred = grid_search.fit(train_data_df, train_actual).predict(train_data_df)\n test_pred = grid_search.predict(test_data_df)\n \n # with open(\"task3_test_errors.txt\", \"w\") as output:\n # with open(\"task3_test_funcwords.txt\", \"w\") as output:\n # with open(\"task3_test_charngrams.txt\", \"w\") as output:\n # with open(\"task3_test_wordngrams.txt\", \"w\") as output:\n # with open(\"task3_test_posngrams.txt\", \"w\") as output:\n with open(\"task3_test_all.txt\", \"w\") as output:\n output.write(\"Training results:\\n{}\\n\".format(classification_report(train_actual, train_pred)))\n output.write(\"Testing results:\\n{}\\n\".format(classification_report(test_actual, test_pred)))\n print(classification_report(train_actual, train_pred))\n print(classification_report(test_actual, test_pred))\n \n # pd.DataFrame(grid_search.cv_results_).to_csv(\"task3_grid_search_errors.csv\")\n # pd.DataFrame(grid_search.cv_results_).to_csv(\"task3_grid_search_funcwords.csv\")\n # pd.DataFrame(grid_search.cv_results_).to_csv(\"task3_grid_search_charngrams.csv\")\n # pd.DataFrame(grid_search.cv_results_).to_csv(\"task3_grid_search_wordngrams.csv\")\n # pd.DataFrame(grid_search.cv_results_).to_csv(\"task3_grid_search_posngrams.csv\")\n pd.DataFrame(grid_search.cv_results_).to_csv(\"task3_grid_search_all.csv\")\n\nif __name__ == \"__main__\":\n main()\n"
] | [
[
"sklearn.model_selection.GridSearchCV",
"pandas.read_csv",
"pandas.DataFrame",
"sklearn.svm.SVC",
"sklearn.metrics.classification_report"
],
[
"sklearn.decomposition.TruncatedSVD",
"sklearn.model_selection.GridSearchCV",
"pandas.DataFrame",
"sklearn.svm.SVC",
"sklearn.metrics.classification_report",
"sklearn.feature_extraction.text.TfidfVectorizer"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
srmainwaring/python-ignition | [
"720f2e6d8e675ed7e10488caf11ef7e93e519d58"
] | [
"python/rover_publisher.py"
] | [
"#!/usr/bin/env python\n\n# Copyright (C) 2022 Rhys Mainwaring\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\nfrom scipy.spatial.transform import Rotation as Rotation\nimport math\nimport time\n\nfrom ignition.msgs.header_pb2 import Header\nfrom ignition.msgs.pose_pb2 import Pose\nfrom ignition.msgs.quaternion_pb2 import Quaternion\nfrom ignition.msgs.time_pb2 import Time\nfrom ignition.msgs.twist_pb2 import Twist\nfrom ignition.msgs.vector3d_pb2 import Vector3d\n\nfrom ignition.transport import AdvertiseMessageOptions\nfrom ignition.transport import Node\n\ndef main():\n # Create a transport node and advertise a topic\n node = Node()\n pub_options = AdvertiseMessageOptions()\n\n pose_topic = \"/pose\"\n pose_msg_type_name = Pose.DESCRIPTOR.full_name\n\n pose_pub = node.advertise(\n pose_topic, pose_msg_type_name, pub_options)\n if pose_pub.valid():\n print(\"Advertising {} on topic [{}]\".format(\n pose_msg_type_name, pose_topic))\n else:\n print(\"Error advertising topic [{}]\".format(pose_topic))\n\n twist_topic = \"/twist\"\n twist_msg_type_name = Twist.DESCRIPTOR.full_name\n twist_pub = node.advertise(\n twist_topic, twist_msg_type_name, pub_options)\n if twist_pub.valid():\n print(\"Advertising {} on topic [{}]\".format(\n twist_msg_type_name, twist_topic))\n else:\n print(\"Error advertising topic [{}]\".format(twist_topic))\n\n # rover moving in a circle of radius with constant velocity\n radius = 5.0\n ang_vel = 0.1\n\n # publish messages at 2Hz\n start = time.time_ns()\n count = 0\n try:\n while True:\n # update time\n now = time.time_ns()\n time_ns = now - start\n time_s = int(time_ns/1.0E9)\n time_ns = int(time_ns % 1000000000)\n id = count\n count += 1\n\n # update position, orientation and velocity\n wz = ang_vel\n theta = wz * time_s\n c = math.cos(theta)\n s = math.sin(theta)\n x = radius * c\n y = radius * s\n vx = -1.0 * radius * wz * s\n vy = radius * wz * c\n rot = Rotation.from_euler(\"xyz\", [0.0, 0.0, theta])\n quat = rot.as_quat()\n\n # # Prepare the messages.\n time_msg = Time()\n time_msg.sec = time_s\n time_msg.nsec = time_ns\n\n header = Header()\n header.stamp.CopyFrom(time_msg)\n\n position = Vector3d()\n position.x = x\n position.y = y\n position.z = 0.0\n\n orientation = Quaternion() \n orientation.x = quat[0]\n orientation.y = quat[1]\n orientation.z = quat[2]\n orientation.w = quat[3]\n\n pose = Pose()\n pose.name = \"base_link\"\n pose.id = id\n pose.header.CopyFrom(header)\n pose.position.CopyFrom(position)\n pose.orientation.CopyFrom(orientation)\n\n lin_vel_msg = Vector3d() \n lin_vel_msg.x = vx\n lin_vel_msg.y = vy\n lin_vel_msg.z = 0.0\n\n ang_vel_msg = Vector3d() \n ang_vel_msg.x = 0.0\n ang_vel_msg.y = 0.0\n ang_vel_msg.z = wz\n\n twist = Twist()\n twist.header.CopyFrom(header)\n twist.linear.CopyFrom(lin_vel_msg)\n twist.angular.CopyFrom(ang_vel_msg)\n\n if not pose_pub.publish(pose):\n break\n\n if not twist_pub.publish(twist):\n break\n\n print(\"Publishing pose on topic [{}], twist on topic [{}]\".format(\n pose_topic, twist_topic))\n\n time.sleep(0.5)\n\n except KeyboardInterrupt:\n pass\n\n\nif __name__ == \"__main__\":\n main()\n\n"
] | [
[
"scipy.spatial.transform.Rotation.from_euler"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"1.5",
"1.2",
"1.3",
"1.4"
],
"tensorflow": []
}
] |
dima137/iact_dnn | [
"b0e71877cd3d6e9a1b8871dc0cbd85c16c29a84d"
] | [
"iact_dnn_utils.py"
] | [
"import numpy as np\nimport h5py\nimport time\nimport os\n\n\n# functions (to be moved to utils.py)\ndef add_meta_keys(fn, pars_keys, image_keys=[]):\n with h5py.File(fn, 'r') as f:\n for key in f.keys():\n if key not in pars_keys and key not in image_keys:\n pars_keys.append(key)\n return 0\n\n\ndef get_square_images_fn(cdict, file_number=None):\n # in the future: load the first n_events from a file with more images\n event_type = cdict['event_type']\n n_events = cdict['n_events']\n mode = cdict['mode']\n Etrue_min = cdict['Etrue_min']\n fn = '%s_%i_images_%s' % (event_type, n_events, mode)\n if Etrue_min is not None and Etrue_min != 'None':\n fn += '_Etrue_min%.1fTeV' % Etrue_min\n if cdict.get('tel') != None:\n fn += '_%s' % cdict['tel']\n if file_number is not None:\n fn += '_file%i' % file_number\n fn += '.h5'\n return fn\n\ndef get_images_fns(cdict, folder=None, exists=False, nfiles=200):\n ev_types = cdict['model_events']\n #n_events = cdict['n_events']\n #n_events_tot = cdict.get('n_events_tot', None)\n #if n_events_tot == None:\n # n_events_tot = n_events\n #nfiles = int(n_events_tot / n_events)\n out_dict = {}\n for k, event_type in enumerate(ev_types):\n cdict['event_type'] = event_type\n out_dict[event_type] = [get_square_images_fn(cdict, file_number=j+1) for j in range(nfiles)]\n if folder is not None and exists:\n out_dict[event_type] = [fn for fn in out_dict[event_type] if os.path.isfile(folder + fn)]\n return out_dict\n\ndef get_zeta_fns(cdict, folder=None, exists=False):\n out_dict = get_images_fns(cdict)\n for key in out_dict.keys():\n out_dict[key] = [fn.replace('.h5', '_zeta.h5') for fn in out_dict[key]]\n if folder is not None and exists:\n out_dict[key] = [fn for fn in out_dict[key] if os.path.isfile(folder + fn)]\n return out_dict\n\n\ndef load_images(folder, cdict):\n ev_types = cdict['model_events']\n n_events = cdict['n_events']\n n_events_tot = cdict.get('n_events_tot', None)\n if n_events_tot == None:\n n_events_tot = n_events\n nfiles = int(n_events_tot / n_events)\n data_key = cdict['data_key']\n print('load images')\n for k, event_type in enumerate(ev_types):\n print('load %s images' % event_type)\n cdict['event_type'] = event_type\n for j in range(nfiles):\n fn = folder + get_square_images_fn(cdict, file_number=j+1)\n with h5py.File(fn, 'r') as f:\n if k == 0 and j == 0:\n dims = f[data_key].shape\n out_dims = list(dims)\n out_dims[0] = n_events_tot * len(ev_types)\n images = np.zeros(out_dims, dtype=np.float32)\n ind_start = n_events_tot * k + dims[0] * j\n ind_end = n_events_tot * k + dims[0] * j + dims[0]\n fill_inds = list(range(ind_start, ind_end))\n images[fill_inds] = f[data_key][:]\n return images\n\n\ndef load_images_from_file(fn, key):\n with h5py.File(fn, 'r') as f:\n return f[key][:]\n\n\ndef get_group_key(key, f):\n for gkey in f.keys():\n if type(f[gkey]) != h5py._hl.dataset.Dataset and key in f[gkey].keys():\n return gkey\n return None\n\ndef load_meta_data(folder, cdict):\n ev_types = cdict['model_events']\n n_events = cdict['n_events']\n n_events_tot = cdict.get('n_events_tot', None)\n if n_events_tot == None:\n n_events_tot = n_events\n nfiles = int(n_events_tot / n_events)\n data_key = cdict['data_key']\n pars_keys = cdict['pars_keys']\n print('load meta data')\n for k, event_type in enumerate(ev_types):\n print(event_type)\n cdict['event_type'] = event_type\n for j in range(nfiles):\n fn = folder + get_square_images_fn(cdict, file_number=j+1)\n with h5py.File(fn, 'r') as f:\n if k == 0 and j == 0:\n pars_dict = {}\n for key in pars_keys:\n gkey = get_group_key(key, f)\n if gkey is None:\n dims = [n_events]\n out_dims = n_events_tot * len(ev_types)\n else:\n dims = f[gkey][key].shape\n out_dims = list(dims)\n out_dims[0] = n_events_tot * len(ev_types)\n pars_dict[key] = np.zeros(out_dims, dtype=np.float32)\n ind_start = n_events_tot * k + dims[0] * j\n ind_end = n_events_tot * k + dims[0] * j + dims[0]\n fill_inds = list(range(ind_start, ind_end))\n for key in pars_dict.keys():\n gkey = get_group_key(key, f)\n if key == 'CR_type':\n pars_dict[key][fill_inds] += int(event_type != 'proton')\n elif gkey is not None:\n pars_dict[key][fill_inds] = f[gkey][key][:]\n else:\n pass\n return pars_dict\n\ndef load_metadata_from_file(fn, key, event_type=None):\n with h5py.File(fn, 'r') as f:\n gkey = get_group_key(key, f)\n if key == 'CR_type' and event_type is not None:\n return int(event_type != 'proton')\n elif gkey is not None:\n return f[gkey][key][:]\n else:\n return None\n\n\n# crop images\ndef get_min_max_inds(center, half_size, nmax):\n imin = np.ceil(center - half_size)\n imax = np.ceil(center + half_size)\n shift = -imin * np.heaviside(-imin, 0.) - (imax - nmax) * np.heaviside(imax - nmax, 0.)\n imin = (imin + shift).astype(int)\n imax = (imax + shift).astype(int)\n return imin, imax, shift\n \n\ndef crop_images(images, size, test=False, crop_fraction=0.03, boundary=5):\n t0 = time.time()\n di = 0.5 * size\n nn, nx, ny = images.shape\n res_arr = np.zeros((nn, size, size))\n norm = np.sum(images, axis=(1,2)) + 1.e-15\n t1 = time.time()\n \n # center of gravity along x\n ix = np.sum(np.sum(images, axis=2) * np.arange(nx), axis=1) / norm\n ix_min, ix_max, x_shift = get_min_max_inds(ix, di, nx)\n # center of gravity along y\n iy = np.sum(np.sum(images, axis=1) * np.arange(ny), axis=1) / norm\n iy_min, iy_max, y_shift = get_min_max_inds(iy, di, ny)\n \n t2 = time.time()\n \n # if True - the image is not cropped\n #crop_mask = np.abs(x_shift) + np.abs(y_shift) == 0.\n crop_mask = np.ones(nn, dtype=bool)\n t3 = time.time()\n \n \n for i in range(nn):\n res_arr[i] = images[i, ix_min[i]:ix_max[i], iy_min[i]:iy_max[i]]\n test_image = 1. * images[i]\n in_sum = np.sum(res_arr[i])\n test_image[ix_min[i]:ix_max[i], iy_min[i]:iy_max[i]] = 0.\n out_sum = np.sum(test_image)\n if in_sum == 0. or out_sum / in_sum > crop_fraction:\n crop_mask[i] = False\n\n test_image = 1. * images[i]\n b = boundary\n in_sum = np.sum(test_image[b:-b, b:-b])\n test_image[b:-b, b:-b] = 0.\n out_sum = np.sum(test_image)\n if in_sum == 0. or out_sum / in_sum > crop_fraction:\n crop_mask[i] = False\n\n t4 = time.time()\n if test:\n print('create arrays: %.3f s' % (t1 - t0))\n print('Get indices: %.3f s' % (t2 - t1))\n print('Crop mask: %.3f s' % (t3 - t2))\n print('Create final array: %.3f s' % (t4 - t3))\n\n return res_arr, crop_mask\n\n\n\n\ndef flatten_tel_images(images):\n '''\n flatten the number of telescopes dimension of the images\n '''\n ntot, image_size, image_size, ntel = images.shape\n im_new = np.zeros((ntel*ntot, image_size, image_size), dtype=np.float32)\n for i in range(ntel):\n im_new[i::ntel] = images[:,:,:,i]\n return im_new.reshape((ntel*ntot, image_size, image_size, 1))\n\ndef deflatten_tel_images(images, ntel):\n '''\n deflatten the number of telescopes dimension of the images\n '''\n ntot, image_size, image_size = images.shape[:3]\n ntot = int(ntot / ntel)\n im_new = np.zeros((ntot, image_size, image_size, ntel), dtype=np.float32)\n for i in range(ntel):\n im_new[:,:,:,i] = images[i::ntel]\n return im_new\n\n\ndef flatten_meta_data(data, ntel=4):\n if data.ndim == 1:\n data_loc = np.outer(data, np.ones(ntel))\n else:\n data_loc = 1. * data\n return data.flatten()\n \n"
] | [
[
"numpy.heaviside",
"numpy.arange",
"numpy.ones",
"numpy.ceil",
"numpy.zeros",
"numpy.sum"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Enopoletus/enopoletus.github.io | [
"2701900dbc0f7f4dd1ec1c78d8be14095eafad28"
] | [
"employmonth.py"
] | [
"import pandas as pd\nimport matplotlib.pyplot as plt, mpld3\nimport numpy as np\nimport scipy.signal as sp\nimport matplotlib.ticker as plticker\ndf=pd.read_csv('numbers2.csv')\ndf.columns=['DATE', 'EMPLOYEES']\ndf.DATE=pd.to_datetime(df.DATE)\ndf.EMPLOYEES=np.log(df.EMPLOYEES)\ntrend=sp.savgol_filter(df.EMPLOYEES, 707, 4)\nunsp=df.EMPLOYEES-trend\nunep=abs(unsp)\nunyp=(sp.savgol_filter(unep, 707, 6))\nuns=-(unsp)*(.5/(np.log(2)-np.log(1)))\nune=abs(uns)\nuny=(sp.savgol_filter(une, 707, 6))\nunw=uns+uny-(uns+uny).min()\nfig, ax = plt.subplots()\nplt.plot(df.DATE, unw, color='blue', lw=2)\nstart, end = ax.get_xlim()\nplt.xticks(np.arange(start, end, 1825.5))\nplt.xticks(rotation=90)\naxes = plt.gca()\naxes.set_ylim([unw.min(), unw.max()])\naxes.set_xlim([df.DATE.min(), df.DATE.max()])\nplt.savefig('foom.png', bbox_inches='tight')\n"
] | [
[
"matplotlib.pyplot.gca",
"numpy.log",
"pandas.read_csv",
"pandas.to_datetime",
"numpy.arange",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.xticks",
"scipy.signal.savgol_filter"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [
"0.14",
"1.6",
"1.10",
"0.15",
"1.4",
"0.16",
"1.9",
"0.19",
"1.5",
"0.18",
"1.2",
"1.7",
"1.0",
"0.17",
"1.3",
"1.8"
],
"tensorflow": []
}
] |
dolaameng/tensorflow_cookbook | [
"ca9bcb892239e9276e9348689e06cd6d1edd19ef",
"ca9bcb892239e9276e9348689e06cd6d1edd19ef",
"ca9bcb892239e9276e9348689e06cd6d1edd19ef"
] | [
"02_TensorFlow_Way/01_Operations_as_a_Computational_Graph/01_operations_on_a_graph.py",
"09_Recurrent_Neural_Networks/02_Implementing_RNN_for_Spam_Prediction/02_implementing_rnn.py",
"10_Taking_TensorFlow_to_Production/02_Using_Multiple_Devices/02_using_multiple_devices.py"
] | [
"# Operations on a Computational Graph\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.python.framework import ops\nops.reset_default_graph()\n\n# Create graph\nsess = tf.Session()\n\n# Create tensors\n\n# Create data to feed in\nx_vals = np.array([1., 3., 5., 7., 9.])\nx_data = tf.placeholder(tf.float32)\nm = tf.constant(3.)\n\n# Multiplication\nprod = tf.mul(x_data, m)\nfor x_val in x_vals:\n print(sess.run(prod, feed_dict={x_data: x_val}))\n\nmerged = tf.merge_all_summaries()\nif not os.path.exists('tensorboard_logs/'):\n os.makedirs('tensorboard_logs/')\n\nmy_writer = tf.train.SummaryWriter('tensorboard_logs/', sess.graph)\n",
"# Implementing an RNN in TensorFlow\n#----------------------------------\n#\n# We implement an RNN in TensorFlow to predict spam/ham from texts\n#\n\nimport os\nimport re\nimport io\nimport requests\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom zipfile import ZipFile\nfrom tensorflow.python.framework import ops\nops.reset_default_graph()\n\n# Start a graph\nsess = tf.Session()\n\n# Set RNN parameters\nepochs = 20\nbatch_size = 250\nmax_sequence_length = 25\nrnn_size = 10\nembedding_size = 50\nmin_word_frequency = 10\nlearning_rate = 0.0005\ndropout_keep_prob = tf.placeholder(tf.float32)\n\n\n# Download or open data\ndata_dir = 'temp'\ndata_file = 'text_data.txt'\nif not os.path.exists(data_dir):\n os.makedirs(data_dir)\n\nif not os.path.isfile(os.path.join(data_dir, data_file)):\n zip_url = 'http://archive.ics.uci.edu/ml/machine-learning-databases/00228/smsspamcollection.zip'\n r = requests.get(zip_url)\n z = ZipFile(io.BytesIO(r.content))\n file = z.read('SMSSpamCollection')\n # Format Data\n text_data = file.decode()\n text_data = text_data.encode('ascii',errors='ignore')\n text_data = text_data.decode().split('\\n')\n\n # Save data to text file\n with open(os.path.join(data_dir, data_file), 'w') as file_conn:\n for text in text_data:\n file_conn.write(\"{}\\n\".format(text))\nelse:\n # Open data from text file\n text_data = []\n with open(os.path.join(data_dir, data_file), 'r') as file_conn:\n for row in file_conn:\n text_data.append(row)\n text_data = text_data[:-1]\n\ntext_data = [x.split('\\t') for x in text_data if len(x)>=1]\n[text_data_target, text_data_train] = [list(x) for x in zip(*text_data)]\n\n\n# Create a text cleaning function\ndef clean_text(text_string):\n text_string = re.sub(r'([^\\s\\w]|_|[0-9])+', '', text_string)\n text_string = \" \".join(text_string.split())\n text_string = text_string.lower()\n return(text_string)\n\n# Clean texts\ntext_data_train = [clean_text(x) for x in text_data_train]\n\n# Change texts into numeric vectors\nvocab_processor = tf.contrib.learn.preprocessing.VocabularyProcessor(max_sequence_length,\n min_frequency=min_word_frequency)\ntext_processed = np.array(list(vocab_processor.fit_transform(text_data_train)))\n\n# Shuffle and split data\ntext_processed = np.array(text_processed)\ntext_data_target = np.array([1 if x=='ham' else 0 for x in text_data_target])\nshuffled_ix = np.random.permutation(np.arange(len(text_data_target)))\nx_shuffled = text_processed[shuffled_ix]\ny_shuffled = text_data_target[shuffled_ix]\n\n# Split train/test set\nix_cutoff = int(len(y_shuffled)*0.80)\nx_train, x_test = x_shuffled[:ix_cutoff], x_shuffled[ix_cutoff:]\ny_train, y_test = y_shuffled[:ix_cutoff], y_shuffled[ix_cutoff:]\nvocab_size = len(vocab_processor.vocabulary_)\nprint(\"Vocabulary Size: {:d}\".format(vocab_size))\nprint(\"80-20 Train Test split: {:d} -- {:d}\".format(len(y_train), len(y_test)))\n\n# Create placeholders\nx_data = tf.placeholder(tf.int32, [None, max_sequence_length])\ny_output = tf.placeholder(tf.int32, [None])\n\n# Create embedding\nembedding_mat = tf.Variable(tf.random_uniform([vocab_size, embedding_size], -1.0, 1.0))\nembedding_output = tf.nn.embedding_lookup(embedding_mat, x_data)\n#embedding_output_expanded = tf.expand_dims(embedding_output, -1)\n\n\n# Define the RNN cell\ncell = tf.nn.rnn_cell.BasicRNNCell(num_units = rnn_size)\noutput, state = tf.nn.dynamic_rnn(cell, embedding_output, dtype=tf.float32)\noutput = tf.nn.dropout(output, dropout_keep_prob)\n\n# Get output of RNN sequence\noutput = tf.transpose(output, [1, 0, 2])\nlast = tf.gather(output, int(output.get_shape()[0]) - 1)\n\n\nweight = tf.Variable(tf.truncated_normal([rnn_size, 2], stddev=0.1))\nbias = tf.Variable(tf.constant(0.1, shape=[2]))\nlogits_out = tf.nn.softmax(tf.matmul(last, weight) + bias)\n\n# Loss function\nlosses = tf.nn.sparse_softmax_cross_entropy_with_logits(logits_out, y_output) # logits=float32, labels=int32\nloss = tf.reduce_mean(losses)\n\naccuracy = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(logits_out, 1), tf.cast(y_output, tf.int64)), tf.float32))\n\noptimizer = tf.train.RMSPropOptimizer(learning_rate)\ntrain_step = optimizer.minimize(loss)\n\ninit = tf.initialize_all_variables()\nsess.run(init)\n\ntrain_loss = []\ntest_loss = []\ntrain_accuracy = []\ntest_accuracy = []\n# Start training\nfor epoch in range(epochs):\n\n # Shuffle training data\n shuffled_ix = np.random.permutation(np.arange(len(x_train)))\n x_train = x_train[shuffled_ix]\n y_train = y_train[shuffled_ix]\n num_batches = int(len(x_train)/batch_size) + 1\n # TO DO CALCULATE GENERATIONS ExACTLY\n for i in range(num_batches):\n # Select train data\n min_ix = i * batch_size\n max_ix = np.min([len(x_train), ((i+1) * batch_size)])\n x_train_batch = x_train[min_ix:max_ix]\n y_train_batch = y_train[min_ix:max_ix]\n \n # Run train step\n train_dict = {x_data: x_train_batch, y_output: y_train_batch, dropout_keep_prob:0.5}\n sess.run(train_step, feed_dict=train_dict)\n \n # Run loss and accuracy for training\n temp_train_loss, temp_train_acc = sess.run([loss, accuracy], feed_dict=train_dict)\n train_loss.append(temp_train_loss)\n train_accuracy.append(temp_train_acc)\n \n # Run Eval Step\n test_dict = {x_data: x_test, y_output: y_test, dropout_keep_prob:1.0}\n temp_test_loss, temp_test_acc = sess.run([loss, accuracy], feed_dict=test_dict)\n test_loss.append(temp_test_loss)\n test_accuracy.append(temp_test_acc)\n print('Epoch: {}, Test Loss: {:.2}, Test Acc: {:.2}'.format(epoch+1, temp_test_loss, temp_test_acc))\n \n# Plot loss over time\nepoch_seq = np.arange(1, epochs+1)\nplt.plot(epoch_seq, train_loss, 'k--', label='Train Set')\nplt.plot(epoch_seq, test_loss, 'r-', label='Test Set')\nplt.title('Softmax Loss')\nplt.xlabel('Epochs')\nplt.ylabel('Softmax Loss')\nplt.legend(loc='upper left')\nplt.show()\n\n# Plot accuracy over time\nplt.plot(epoch_seq, train_accuracy, 'k--', label='Train Set')\nplt.plot(epoch_seq, test_accuracy, 'r-', label='Test Set')\nplt.title('Test Accuracy')\nplt.xlabel('Epochs')\nplt.ylabel('Accuracy')\nplt.legend(loc='upper left')\nplt.show()",
"# -*- coding: utf-8 -*-\n# Using Multiple Devices\n#----------------------------------\n#\n# This function gives us the ways to use\n# multiple devices (executors) in TensorFlow.\n\nimport tensorflow as tf\nfrom tensorflow.python.framework import ops\nops.reset_default_graph()\n\n# To find out where placement occurs, set 'log_device_placement'\nsess = tf.Session(config=tf.ConfigProto(log_device_placement=True))\n\na = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')\nb = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b')\nc = tf.matmul(a, b)\n\n# Runs the op.\nprint(sess.run(c))\n\n\n# If we load a graph and want device placement to be forgotten,\n# we set a parameter in our session:\nconfig = tf.ConfigProto()\nconfig.allow_soft_placement = True\nsess_soft = tf.Session(config=config)\n\n# GPUs\n#---------------------------------\n# Note that the GPU must have a compute capability > 3.5 for TF to use.\n# http://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#compute-capability\n\n\n# Careful with GPU memory allocation, TF never releases it. TF starts with almost\n# all of the GPU memory allocated. We can slowly grow to that limit with an\n# option setting:\n\nconfig.gpu_options.allow_growth = True\nsess_grow = tf.Session(config=config)\n\n# Also, we can limit the size of GPU memory used, with the following option\nconfig.gpu_options.per_process_gpu_memory_fraction = 0.4\nsess_limited = tf.Session(config=config)\n\n\n# How to set placements on multiple devices.\n# Here, assume we have three devies CPU:0, GPU:0, and GPU:1\nif tf.test.is_built_with_cuda():\n with tf.device('/cpu:0'):\n a = tf.constant([1.0, 3.0, 5.0], shape=[1, 3])\n b = tf.constant([2.0, 4.0, 6.0], shape=[3, 1])\n \n with tf.device('/gpu:1'):\n c = tf.matmul(a,b)\n c = tf.reshape(c, [-1])\n \n with tf.device('/gpu:2'):\n d = tf.matmul(b,a)\n flat_d = tf.reshape(d, [-1])\n \n combined = tf.mul(c, flat_d)\n print(sess.run(combined))"
] | [
[
"tensorflow.constant",
"tensorflow.merge_all_summaries",
"tensorflow.placeholder",
"tensorflow.mul",
"tensorflow.train.SummaryWriter",
"tensorflow.Session",
"numpy.array",
"tensorflow.python.framework.ops.reset_default_graph"
],
[
"tensorflow.random_uniform",
"matplotlib.pyplot.legend",
"tensorflow.nn.dynamic_rnn",
"tensorflow.cast",
"matplotlib.pyplot.plot",
"numpy.arange",
"tensorflow.initialize_all_variables",
"tensorflow.Session",
"tensorflow.argmax",
"tensorflow.python.framework.ops.reset_default_graph",
"tensorflow.nn.dropout",
"tensorflow.matmul",
"tensorflow.truncated_normal",
"tensorflow.train.RMSPropOptimizer",
"matplotlib.pyplot.title",
"tensorflow.placeholder",
"tensorflow.nn.sparse_softmax_cross_entropy_with_logits",
"numpy.array",
"matplotlib.pyplot.show",
"tensorflow.nn.embedding_lookup",
"matplotlib.pyplot.ylabel",
"tensorflow.transpose",
"tensorflow.constant",
"tensorflow.reduce_mean",
"matplotlib.pyplot.xlabel",
"tensorflow.contrib.learn.preprocessing.VocabularyProcessor",
"tensorflow.nn.rnn_cell.BasicRNNCell"
],
[
"tensorflow.matmul",
"tensorflow.device",
"tensorflow.constant",
"tensorflow.test.is_built_with_cuda",
"tensorflow.reshape",
"tensorflow.mul",
"tensorflow.ConfigProto",
"tensorflow.Session",
"tensorflow.python.framework.ops.reset_default_graph"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"1.12",
"1.4",
"1.13",
"1.5",
"1.7",
"0.12",
"1.0",
"1.2"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"1.12",
"1.4",
"1.13",
"1.5",
"1.7",
"0.12",
"1.0",
"1.2"
]
}
] |
glotzerlab/freud-examples | [
"589a66d7732ab1eeb097957938e766688c084ab1"
] | [
"archive/demos/afrl_helpers.py"
] | [
"import matplotlib.colors as mplColors\nimport numpy as np\nfrom bokeh.io import output_notebook\nfrom bokeh.plotting import figure\nfrom bokeh.resources import INLINE\nfrom freud import box\nfrom matplotlib import cm\n\noutput_notebook(resources=INLINE)\n\n# define vertices for hexagons\nverts = [\n [0.537284965911771, 0.31020161970069976],\n [3.7988742065678664e-17, 0.6204032394013997],\n [-0.5372849659117709, 0.31020161970070004],\n [-0.5372849659117711, -0.31020161970069976],\n [-1.1396622619703597e-16, -0.6204032394013997],\n [0.5372849659117711, -0.3102016197006997],\n]\nverts = np.array(verts)\n\n# define colors for our system\nc_list = [\n \"#30A2DA\",\n \"#FC4F30\",\n \"#E5AE38\",\n \"#6D904F\",\n \"#9757DB\",\n \"#188487\",\n \"#FF7F00\",\n \"#9A2C66\",\n \"#626DDA\",\n \"#8B8B8B\",\n]\nc_dict = dict()\nc_dict[6] = c_list[0]\nc_dict[5] = c_list[1]\nc_dict[4] = c_list[2]\nc_dict[3] = c_list[7]\nc_dict[2] = c_list[3]\nc_dict[1] = c_list[5]\nc_dict[0] = c_list[6]\nc_dict[7] = c_list[4]\n\n\nclass DemoData:\n \"\"\"docstring for DemoData\"\"\"\n\n def __init__(self, data_path):\n super().__init__()\n self.data_path = data_path\n self.verts = verts\n # load data\n self.load_data()\n\n def load_data(self):\n self.box_data = np.copy(np.load(f\"{self.data_path}/box_data.npy\"))\n self.pos_data = np.copy(np.load(f\"{self.data_path}/pos_data.npy\"))\n self.quat_data = np.copy(np.load(f\"{self.data_path}/quat_data.npy\"))\n self.n_frames = self.pos_data.shape[0]\n\n def freud_box(self, frame):\n l_box = self.box_data[frame]\n fbox = box.Box(Lx=l_box[\"Lx\"], Ly=l_box[\"Ly\"], is2D=True)\n return fbox\n\n def plot_frame(self, frame_idx, title=\"System Visualization\", linked_plot=None):\n l_box = self.box_data[frame_idx]\n l_pos = self.pos_data[frame_idx]\n l_quat = self.quat_data[frame_idx]\n l_ang = 2 * np.arctan2(np.copy(l_quat[:, 3]), np.copy(l_quat[:, 0]))\n fbox = box.Box(Lx=l_box[\"Lx\"], Ly=l_box[\"Ly\"], is2D=True)\n side_length = max(fbox.Lx, fbox.Ly)\n l_min = -side_length / 2.0\n l_min *= 1.1\n l_max = -l_min\n\n # take local vertices and rotate, translate into\n # system coordinates\n patches = local_to_global(verts, l_pos[:, 0:2], l_ang)\n\n if linked_plot is not None:\n x_range = linked_plot.x_range\n y_range = linked_plot.y_range\n else:\n x_range = (l_min, l_max)\n y_range = (l_min, l_max)\n\n # plot\n p = figure(title=title, x_range=x_range, y_range=y_range, height=300, width=300)\n p.patches(\n xs=patches[:, :, 0].tolist(),\n ys=patches[:, :, 1].tolist(),\n fill_color=(42, 126, 187),\n line_color=\"black\",\n line_width=1.5,\n ) # ,\n # legend=\"hexagons\")\n # box display\n p.patches(\n xs=[[-fbox.Lx / 2, fbox.Lx / 2, fbox.Lx / 2, -fbox.Lx / 2]],\n ys=[[-fbox.Ly / 2, -fbox.Ly / 2, fbox.Ly / 2, fbox.Ly / 2]],\n fill_color=(0, 0, 0, 0),\n line_color=\"black\",\n line_width=2,\n )\n # p.legend.location='bottom_center'\n # p.legend.orientation='horizontal'\n default_bokeh(p)\n # show(p)\n self.p = p\n return p\n\n def plot_single_neighbor(\n self,\n frame_idx,\n pidx,\n n_list,\n num_particles,\n title=\"Nearest Neighbor Visualization\",\n linked_plot=None,\n ):\n\n l_box = self.box_data[frame_idx]\n l_pos = self.pos_data[frame_idx]\n l_quat = self.quat_data[frame_idx]\n l_ang = 2 * np.arctan2(np.copy(l_quat[:, 3]), np.copy(l_quat[:, 0]))\n fbox = box.Box(Lx=l_box[\"Lx\"], Ly=l_box[\"Ly\"], is2D=True)\n side_length = max(fbox.Lx, fbox.Ly)\n l_min = -side_length / 2.0\n l_min *= 1.1\n l_max = -l_min\n\n if linked_plot is not None:\n x_range = linked_plot.x_range\n y_range = linked_plot.y_range\n else:\n x_range = (l_min, l_max)\n y_range = (l_min, l_max)\n\n n_idxs = n_list[pidx]\n # clip padded values\n n_idxs = n_idxs[np.where(n_idxs < num_particles)]\n n_neigh = len(n_idxs)\n\n # get position, orientation for the central particle\n center_pos = np.zeros(shape=(1, 3), dtype=np.float32)\n center_ang = np.zeros(shape=(1), dtype=np.float32)\n center_pos[:] = l_pos[pidx]\n center_ang[:] = l_ang[pidx]\n\n # get the positions, orientations for the neighbor particles\n neigh_pos = np.zeros(shape=(n_neigh, 3), dtype=np.float32)\n neigh_ang = np.zeros(shape=(n_neigh), dtype=np.float32)\n neigh_pos[:] = l_pos[n_idxs]\n neigh_ang[:] = l_ang[n_idxs]\n\n # render in bokeh\n # create array of transformed positions\n # all particles\n patches = local_to_global(verts, l_pos[:, 0:2], l_ang)\n # center particle\n c_patches = local_to_global(verts, center_pos[:, 0:2], center_ang)\n # neighbor particles\n n_patches = local_to_global(verts, neigh_pos[:, 0:2], neigh_ang)\n # turn into list of colors\n # bokeh (as of this version) requires hex colors, so convert rgb to hex\n center_color = np.array([c_list[0] for _ in range(center_pos.shape[0])])\n neigh_color = np.array([c_list[1] for _ in range(neigh_pos.shape[0])])\n\n # plot\n p = figure(title=title, x_range=x_range, y_range=y_range, height=300, width=300)\n p.patches(\n xs=patches[:, :, 0].tolist(),\n ys=patches[:, :, 1].tolist(),\n fill_color=(0, 0, 0, 0.1),\n line_color=\"black\",\n )\n p.patches(\n xs=n_patches[:, :, 0].tolist(),\n ys=n_patches[:, :, 1].tolist(),\n fill_color=neigh_color.tolist(),\n line_color=\"black\",\n legend=\"neighbors\",\n )\n p.patches(\n xs=c_patches[:, :, 0].tolist(),\n ys=c_patches[:, :, 1].tolist(),\n fill_color=center_color.tolist(),\n line_color=\"black\",\n legend=\"centers\",\n )\n # box display\n p.patches(\n xs=[[-fbox.Lx / 2, fbox.Lx / 2, fbox.Lx / 2, -fbox.Lx / 2]],\n ys=[[-fbox.Ly / 2, -fbox.Ly / 2, fbox.Ly / 2, fbox.Ly / 2]],\n fill_color=(0, 0, 0, 0),\n line_color=\"black\",\n line_width=2,\n )\n p.legend.location = \"bottom_center\"\n p.legend.orientation = \"horizontal\"\n default_bokeh(p)\n self.p = p\n return p\n\n def plot_neighbors(\n self,\n frame_idx,\n n_list,\n num_particles,\n n_neigh,\n title=\"Nearest Neighbor Visualization\",\n linked_plot=None,\n ):\n\n l_box = self.box_data[frame_idx]\n l_pos = self.pos_data[frame_idx]\n l_quat = self.quat_data[frame_idx]\n l_ang = 2 * np.arctan2(np.copy(l_quat[:, 3]), np.copy(l_quat[:, 0]))\n fbox = box.Box(Lx=l_box[\"Lx\"], Ly=l_box[\"Ly\"], is2D=True)\n side_length = max(fbox.Lx, fbox.Ly)\n l_min = -side_length / 2.0\n l_min *= 1.1\n l_max = -l_min\n\n if linked_plot is not None:\n x_range = linked_plot.x_range\n y_range = linked_plot.y_range\n else:\n x_range = (l_min, l_max)\n y_range = (l_min, l_max)\n\n # now for array manipulation magic\n # create an integer array of the same shape as the neighbor list array\n int_arr = np.ones(shape=n_list.shape, dtype=np.int32)\n # \"search\" for non-indexed particles (missing neighbors)\n # while it would be most accurate to use the UINTMAX value\n # provided by nn.getUINTMAX(), but this works just as well\n int_arr[n_list > (num_particles - 1)] = 0\n # sum along particle index axis to\n # determine the number of neighbors per particle\n n_neighbors = np.sum(int_arr, axis=1)\n # find the complement (if desired) to\n # find number of missing neighbors per particle\n # n_deficits = n_neigh - n_neighbors\n\n p = figure(title=title, x_range=x_range, y_range=y_range, height=300, width=300)\n for k in np.unique(n_neighbors):\n # find particles with k neighbors\n c_idxs = np.copy(np.where(n_neighbors == k)[0])\n center_pos = np.zeros(shape=(len(c_idxs), 3), dtype=np.float32)\n center_ang = np.zeros(shape=(len(c_idxs)), dtype=np.float32)\n center_pos = l_pos[c_idxs]\n center_ang = l_ang[c_idxs]\n c_patches = local_to_global(verts, center_pos[:, 0:2], center_ang)\n center_color = np.array([c_dict[k] for _ in range(center_pos.shape[0])])\n p.patches(\n xs=c_patches[:, :, 0].tolist(),\n ys=c_patches[:, :, 1].tolist(),\n fill_color=center_color.tolist(),\n line_color=\"black\",\n legend=f\"k={k}\",\n )\n p.patches(\n xs=[[-fbox.Lx / 2, fbox.Lx / 2, fbox.Lx / 2, -fbox.Lx / 2]],\n ys=[[-fbox.Ly / 2, -fbox.Ly / 2, fbox.Ly / 2, fbox.Ly / 2]],\n fill_color=(0, 0, 0, 0),\n line_color=\"black\",\n line_width=2,\n )\n p.legend.location = \"bottom_center\"\n p.legend.orientation = \"horizontal\"\n default_bokeh(p)\n self.p = p\n return p\n\n def plot_hexatic(\n self,\n frame_idx,\n psi_k,\n avg_psi_k,\n title=\"Hexatic Visualization\",\n linked_plot=None,\n ):\n\n l_box = self.box_data[frame_idx]\n l_pos = self.pos_data[frame_idx]\n l_quat = self.quat_data[frame_idx]\n l_ang = 2 * np.arctan2(np.copy(l_quat[:, 3]), np.copy(l_quat[:, 0]))\n fbox = box.Box(Lx=l_box[\"Lx\"], Ly=l_box[\"Ly\"], is2D=True)\n side_length = max(fbox.Lx, fbox.Ly)\n l_min = -side_length / 2.0\n l_min *= 1.1\n l_max = -l_min\n\n if linked_plot is not None:\n x_range = linked_plot.x_range\n y_range = linked_plot.y_range\n else:\n x_range = (l_min, l_max)\n y_range = (l_min, l_max)\n\n # create array of transformed positions\n patches = local_to_global(verts, l_pos[:, 0:2], l_ang)\n # create an array of angles relative to the average\n a = np.angle(psi_k) - np.angle(avg_psi_k)\n # turn into an rgb array of tuples\n color = [tuple(cubeellipse(x)) for x in a]\n # bokeh (as of this version) requires hex colors, so convert rgb to hex\n hex_color = [\n f\"#{clamp(r):02x}{clamp(g):02x}{clamp(b):02x}\" for (r, g, b) in color\n ]\n # plot\n p = figure(title=title, x_range=x_range, y_range=y_range, height=300, width=300)\n p.patches(\n xs=patches[:, :, 0].tolist(),\n ys=patches[:, :, 1].tolist(),\n fill_color=hex_color,\n line_color=\"black\",\n )\n default_bokeh(p)\n self.p = p\n return p\n\n def plot_orientation(\n self, frame_idx, title=\"Orientation Visualization\", linked_plot=None\n ):\n\n l_box = self.box_data[frame_idx]\n l_pos = self.pos_data[frame_idx]\n l_quat = self.quat_data[frame_idx]\n l_ang = 2 * np.arctan2(np.copy(l_quat[:, 3]), np.copy(l_quat[:, 0]))\n fbox = box.Box(Lx=l_box[\"Lx\"], Ly=l_box[\"Ly\"], is2D=True)\n side_length = max(fbox.Lx, fbox.Ly)\n l_min = -side_length / 2.0\n l_min *= 1.1\n l_max = -l_min\n\n if linked_plot is not None:\n x_range = linked_plot.x_range\n y_range = linked_plot.y_range\n else:\n x_range = (l_min, l_max)\n y_range = (l_min, l_max)\n\n # create array of transformed positions\n patches = local_to_global(verts, l_pos[:, 0:2], l_ang)\n # turn into an rgb array of tuples\n theta = l_ang * 6.0\n color = [tuple(cubeellipse(x, lam=0.5, h=2.0)) for x in theta]\n # bokeh (as of this version) requires hex colors, so convert rgb to hex\n hex_color = [\n f\"#{clamp(r):02x}{clamp(g):02x}{clamp(b):02x}\" for (r, g, b) in color\n ]\n # plot\n p = figure(title=title, x_range=x_range, y_range=y_range, height=300, width=300)\n p.patches(\n xs=patches[:, :, 0].tolist(),\n ys=patches[:, :, 1].tolist(),\n fill_color=hex_color,\n line_color=\"black\",\n )\n default_bokeh(p)\n self.p = p\n return p\n\n def plot_ld(\n self, frame_idx, ld, title=\"Local Density Visualization\", linked_plot=None\n ):\n\n l_box = self.box_data[frame_idx]\n l_pos = self.pos_data[frame_idx]\n l_quat = self.quat_data[frame_idx]\n l_ang = 2 * np.arctan2(np.copy(l_quat[:, 3]), np.copy(l_quat[:, 0]))\n fbox = box.Box(Lx=l_box[\"Lx\"], Ly=l_box[\"Ly\"], is2D=True)\n side_length = max(fbox.Lx, fbox.Ly)\n l_min = -side_length / 2.0\n l_min *= 1.1\n l_max = -l_min\n\n if linked_plot is not None:\n x_range = linked_plot.x_range\n y_range = linked_plot.y_range\n else:\n x_range = (l_min, l_max)\n y_range = (l_min, l_max)\n\n # create array of transformed positions\n patches = local_to_global(verts, l_pos[:, 0:2], l_ang)\n # create an array of angles relative to the average\n # a = np.angle(psi_k) - np.angle(avg_psi_k)\n a = ld\n # turn into an rgb array of tuples\n # handle the matplotlib colormap\n myNorm = mplColors.Normalize(vmin=0.5, vmax=0.8)\n color = [tuple(cm.RdYlBu(myNorm(x))[:3]) for x in a]\n # bokeh (as of this version) requires hex colors, so convert rgb to hex\n hex_color = [\n \"#{:02x}{:02x}{:02x}\".format(\n clamp(int(255 * r)), clamp(int(255 * g)), clamp(int(255 * b))\n )\n for (r, g, b) in color\n ]\n # plot\n p = figure(title=title, x_range=x_range, y_range=y_range, height=300, width=300)\n p.patches(\n xs=patches[:, :, 0].tolist(),\n ys=patches[:, :, 1].tolist(),\n fill_color=hex_color,\n line_color=\"black\",\n )\n default_bokeh(p)\n self.p = p\n return p\n\n\ndef default_bokeh(p):\n \"\"\"\n wrapper which takes the default bokeh outputs and changes them to more sensible values\n \"\"\"\n p.title.text_font_size = \"18pt\"\n p.title.align = \"center\"\n\n p.xaxis.axis_label_text_font_size = \"14pt\"\n p.yaxis.axis_label_text_font_size = \"14pt\"\n\n p.xaxis.major_tick_in = 10\n p.xaxis.major_tick_out = 0\n p.xaxis.minor_tick_in = 5\n p.xaxis.minor_tick_out = 0\n\n p.yaxis.major_tick_in = 10\n p.yaxis.major_tick_out = 0\n p.yaxis.minor_tick_in = 5\n p.yaxis.minor_tick_out = 0\n\n p.xaxis.major_label_text_font_size = \"12pt\"\n p.yaxis.major_label_text_font_size = \"12pt\"\n\n\ndef cubeellipse(theta, lam=0.6, gamma=1.0, s=4.0, r=1.0, h=1.2):\n \"\"\"Create an RGB colormap from an input angle theta. Takes lam (a list of\n intensity values, from 0 to 1), gamma (a nonlinear weighting power),\n s (starting angle), r (number of revolutions around the circle), and\n h (a hue factor).\"\"\"\n import numpy\n\n lam = lam ** gamma\n\n a = h * lam * (1 - lam) * 0.5\n v = numpy.array(\n [[-0.14861, 1.78277], [-0.29227, -0.90649], [1.97294, 0.0]], dtype=numpy.float32\n )\n ctarray = numpy.array(\n [numpy.cos(theta * r + s), numpy.sin(theta * r + s)], dtype=numpy.float32\n )\n # convert to 255 rgb\n ctarray = (lam + a * v.dot(ctarray)).T\n ctarray *= 255\n ctarray = ctarray.astype(dtype=np.int32)\n return ctarray\n\n\ndef local_to_global(verts, positions, orientations):\n \"\"\"\n Take a list of vertices, positions, and orientations and create\n a list of vertices in the \"global coordinate system\" for plotting\n in bokeh\n \"\"\"\n num_particles = len(positions)\n num_verts = len(verts)\n # create list of vertices in the \"local reference frame\" i.e.\n # centered at (0,0)\n l_verts = np.zeros(shape=(num_particles, num_verts, 2), dtype=np.float32)\n l_verts[:] = verts\n # create array of rotation matrices\n rot_mat = np.zeros(shape=(num_particles, 2, 2), dtype=np.float32)\n for i, theta in enumerate(orientations):\n rot_mat[i] = [[np.cos(theta), -np.sin(theta)], [np.sin(theta), np.cos(theta)]]\n # rotate; uses einsum for speed; please see numpy documentation\n # for more information\n r_verts = np.einsum(\"lij,lkj->lki\", rot_mat, l_verts)\n # now translate to global coordinates\n # need to create a position array with same shape as vertex array\n l_pos = np.zeros(shape=(num_particles, num_verts, 2), dtype=np.float32)\n for i in range(num_particles):\n for j in range(len(verts)):\n l_pos[i, j] = positions[i]\n # translate\n output_array = np.add(r_verts, l_pos)\n return output_array\n\n\ndef clamp(x):\n \"\"\"\n limit values between 0 and 255\n http://stackoverflow.com/questions/3380726/converting-a-rgb-color-tuple-to-a-six-digit-code-in-python\n \"\"\"\n return max(0, min(x, 255))\n\n\ndef demo1(l_box, l_pos, l_ang, verts, title=\"System Visualization\"):\n # create box\n fbox = box.Box(Lx=l_box[\"Lx\"], Ly=l_box[\"Ly\"], is2D=True)\n side_length = max(fbox.Lx, fbox.Ly)\n l_min = -side_length / 2.0\n l_min *= 1.1\n l_max = -l_min\n\n # take local vertices and rotate, translate into\n # system coordinates\n patches = local_to_global(verts, l_pos[:, 0:2], l_ang)\n\n # plot\n p = figure(\n title=title,\n x_range=(l_min, l_max),\n y_range=(l_min, l_max),\n height=300,\n width=300,\n )\n p.patches(\n xs=patches[:, :, 0].tolist(),\n ys=patches[:, :, 1].tolist(),\n fill_color=(42, 126, 187),\n line_color=\"black\",\n line_width=1.5,\n ) # ,\n # legend=\"hexagons\")\n # box display\n p.patches(\n xs=[[-fbox.Lx / 2, fbox.Lx / 2, fbox.Lx / 2, -fbox.Lx / 2]],\n ys=[[-fbox.Ly / 2, -fbox.Ly / 2, fbox.Ly / 2, fbox.Ly / 2]],\n fill_color=(0, 0, 0, 0),\n line_color=\"black\",\n line_width=2,\n )\n # p.legend.location='bottom_center'\n # p.legend.orientation='horizontal'\n default_bokeh(p)\n # show(p)\n return p\n"
] | [
[
"numpy.einsum",
"numpy.unique",
"numpy.load",
"numpy.cos",
"matplotlib.colors.Normalize",
"numpy.ones",
"numpy.sin",
"numpy.copy",
"numpy.where",
"numpy.add",
"numpy.angle",
"numpy.array",
"numpy.zeros",
"numpy.sum"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
umutcanceyhan7/python_survival_game | [
"43437c14be5e96817f96e4571000197acf5d90ac"
] | [
"ceng113_hw5_260201003.py"
] | [
"# Umutcan CEYHAN 260201003 \nimport numpy\n\nclass Game():\n def __init__(self,map_width,map_height,init_time, action_cost):\n # The Game initializes map parameters.\n self.mapwidth = map_width\n self.mapheight = map_height\n # The Game initializes its map with all empty squares.\n self.map = [['empty' for col in range(map_width)] for row in range(map_height)]\n # The Game creates its player object.\n self.player = Player()\n # The Game creates its time object.\n self.time = Time(0,init_time, action_cost)\n # The Game initializes the player icon.\n self.picon = person\n # The Game sets the continue state to true (still has time)\n self.cont = True\n # The Game sets the safe state to false (still not in shelter)\n self.safe = False\n # The Game initializes the list of squares that constitutes the shelter \n self.score_map = []\n # The Game randomly inserts wood, dirt or water on the map.\n self.generate_map()\n # The Game prints the current status on the screen.\n self.update_screen()\n\n # For each square, put wood with probability of 0.3, put dirt with probability of 0.3,\n # put water with probability of 0.2 or leave empty with probability of 0.2. You have\n # to use 'numpy.random.randint' function. \n def generate_map(self):\n for row in range(self.mapheight):\n for col in range(self.mapwidth):\n square = numpy.random.randint(0, 11)\n if( 1 >= square <= 3):\n self.map[row][col] = \"wood \"\n elif( 4 >= square <= 6):\n self.map[row][col] = \"dirt \"\n elif( 7 >= square <= 8):\n self.map[row][col] = \"water\"\n else:\n self.map[row][col] = \"empty\"\n \n def show_controls(self): \n print()\n print(\"**************************** Game Control ****************************\")\n print(\"w: up s: down a: left d: rigth\")\n print(\"1: put brick 2: put dirt 3: put plank 4: put water 5: put wood\")\n print(\"q: pick e: make plank r: make brick o: exit game\")\n print(\"plank: 2 woods brick: 2 dirt 1 water\")\n print(\"plank: 2 pts brick: 3 pts enclosed square: 3 pts\")\n print(\"**********************************************************************\")\n print()\n def show_map(self):\n ppy = self.player.pos[0]\n ppx = self.player.pos[1]\n print()\n for row in range(MAP_HEIGHT):\n color_row = [COLORS[self.map[row][c]] for c in range(MAP_WIDTH)]\n if row == ppy:\n color_row[ppx] = color_row[ppx].replace(' ',' '+self.picon+' ')\n print(''.join(color_row)) \n def update_screen(self):\n self.player.show_inventory()\n self.time.show_time()\n self.show_map()\n self.show_controls()\n def _flood_fill(self,wmf,ppx,ppy,source,target,conn8=True):\n if wmf[ppy,ppx]!=source:\n return\n wmf[ppy,ppx] = target\n if ppy>0: self._flood_fill(wmf,ppx,ppy-1,source,target,conn8)\n if ppy<wmf.shape[0]-1: self._flood_fill(wmf,ppx,ppy+1,source,target,conn8)\n if ppx>0: self._flood_fill(wmf,ppx-1,ppy,source,target,conn8)\n if ppx<wmf.shape[1]-1: self._flood_fill(wmf,ppx+1,ppy,source,target,conn8)\n if conn8:\n if ppy>0 and ppx>0: self._flood_fill(wmf,ppx-1,ppy-1,source,target,conn8)\n if ppy>0 and ppx<wmf.shape[1]-1: self._flood_fill(wmf,ppx+1,ppy-1,source,target,conn8)\n if ppy<wmf.shape[0]-1 and ppx>0: self._flood_fill(wmf,ppx-1,ppy+1,source,target),conn8\n if ppy<wmf.shape[0]-1 and ppx<wmf.shape[1]-1: self._flood_fill(wmf,ppx+1,ppy+1,source,target,conn8)\n def check_safety(self):\n # This function checks if the player is in a shelter. It should be called\n # at the end of each successfully executed action to check if the game \n # has finished.\n wall_map = numpy.zeros((game.mapwidth+2,game.mapheight+2)).astype(int)\n wall_map_bool = [numpy.in1d(row, ['brick','plank']) for row in game.map]\n wall_map[1:-1,1:-1] = numpy.array(wall_map_bool).astype(int)\n label = 2\n while((wall_map == 1).any()):\n py = numpy.where(wall_map==1)[0][0]\n px = numpy.where(wall_map==1)[1][0]\n self._flood_fill(wall_map, px, py, 1, label, False)\n label += 1\n ppx = game.player.pos[1]+1\n ppy = game.player.pos[0]+1\n if not wall_map[ppy,ppx]:\n for wall in range(2,label):\n wall_map_fill = (wall_map == wall).astype(int) \n self._flood_fill(wall_map_fill,ppx,ppy,0,label)\n edges = [wall_map_fill[0,:],wall_map_fill[-1,:], wall_map_fill[:,0],wall_map_fill[:,-1]]\n if label not in numpy.array(edges):\n self.safe = True\n self.score_map = wall_map_fill[1:-1,1:-1]\n self.picon = happy\n break\n def calc_score(self):\n final_map = (numpy.array(self.map) == 'brick').astype(int) + self.score_map\n unique, counts = numpy.unique(final_map, return_counts=True)\n score = counts[-1]*3 + counts[-2]*3 + counts[-3]*2 #area*3+brick*3+plank*2\n return score\n def move_player(self,direction):\n self.player.move(direction)\n self.update_screen()\n # Pick item using the player object's pick method and update the map if \n # there is an item to pick, otherwise print \"There is nothing to pick!\". \n def pick_item(self):\n ppx = self.player.pos[0] #Row\n ppy = self.player.pos[1] #Column\n if (self.map[ppx][ppy] == \"empty\"):\n print(\"There is nothing to pick!\")\n else:\n self.player.pick(self.map[ppx][ppy]) #Picks the item where it is\n self.map[ppx][ppy] = \"empty\"\n self.update_screen()\n # Put the given item using the player object's put method if the current\n # square is empty, otherwise print \"\"There is nowhere to put!\". If the\n # player scan successfully put the item, update the map. \n def put_item(self,item):\n ppx = self.player.pos[0]\n ppy = self.player.pos[1]\n if(self.map[ppx][ppy] == \"empty\"):\n self.player.put(item)\n self.update_screen()\n else:\n print(\"There is nowhere to put!\")\n \n # Make the given item using the player object's corresponding method. If\n # the player can not make the item, print \"Not enough material!\".\n def make(self,item):\n if(item == \"e\"):\n if(self.player.make_plank()):\n self.update_screen()\n else:\n print(\"Not enough material!\")\n else:\n if(self.player.make_brick()):\n self.update_screen()\n else:\n print(\"Not enough material!\")\n \n \n\nclass Player():\n def __init__(self):\n # Initialize the player position at the top left corner\n self.pos = [0,0]\n # Initialize the inventory as empty\n self.inventory = {'wood ':0,'dirt ':0,'water':0,'plank':0,'brick':0}\n def move(self, direction):\n # Update the player position with respect to move direction.\n if(direction == \"w\" ):\n if not(self.pos[0] == 0):\n self.pos[0] -= 1\n game.time.spend()\n else:\n print(\"Sorry I can not move up\")\n elif(direction == \"s\"):\n if not(self.pos[0] == MAP_HEIGHT-1):\n self.pos[0] += 1 \n game.time.spend()\n else:\n print(\"Sorry I can not move down\")\n elif(direction == \"a\"):\n if not(self.pos[1] == 0):\n self.pos[1] -= 1\n game.time.spend()\n else:\n print(\"Sorry I can not move left\")\n else:\n if not(self.pos[1] == MAP_WIDTH-1):\n self.pos[1] += 1\n game.time.spend()\n else:\n print(\"Sorry I can not move right\")\n return self.pos\n \n # Pick and update the player inventory with respect to the item.\n def pick(self, item):\n if(item == \"brick\"):\n self.inventory[\"brick\"] += 1 \n game.time.spend()\n elif(item == \"dirt \"):\n self.inventory[\"dirt \"] += 1\n game.time.spend()\n elif(item == \"plank\"):\n self.inventory[\"plank\"] += 1\n game.time.spend()\n elif(item == \"water\"):\n self.inventory[\"water\"] += 1\n game.time.spend()\n elif(item == \"wood \"):\n self.inventory[\"wood \"] += 1\n game.time.spend()\n \n # Put and update the player inventory with respect to the item, if the\n # player has one or more of that item in the inventory. Return true if\n # successfully put, otherwise false.\n def put(self,item):\n ppx = game.player.pos[0] #Row\n ppy = game.player.pos[1] #Column\n if(item == \"1\"):\n if(self.inventory[\"brick\"] >= 1):\n self.inventory[\"brick\"] -= 1\n game.map[ppx][ppy] = \"brick\"\n game.time.spend()\n return True\n else:\n print(\"There is nothing to put!\")\n return False \n elif(item == \"2\"):\n if(self.inventory[\"dirt \"] >= 1):\n self.inventory[\"dirt \"] -= 1\n game.map[ppx][ppy] = \"dirt \"\n game.time.spend()\n return True\n else:\n print(\"There is nothing to put!\")\n return False\n elif(item == \"3\"):\n if(self.inventory[\"plank\"] >= 1):\n self.inventory[\"plank\"] -= 1\n game.map[ppx][ppy] = \"plank\"\n game.time.spend()\n return True\n else:\n print(\"There is nothing to put!\")\n return False\n elif(item == \"4\"):\n if(self.inventory[\"water\"] >= 1):\n self.inventory[\"water\"] -= 1\n game.map[ppx][ppy] = \"water\" \n game.time.spend()\n return True\n else:\n print(\"There is nothing to put!\")\n return False\n else:\n if(self.inventory[\"wood \"] >= 1):\n self.inventory[\"wood \"] -= 1\n game.map[ppx][ppy] = \"wood \"\n game.time.spend()\n return True\n else:\n print(\"There is nothing to put!\")\n return False\n # Make plank and update the player inventory with respect to the action,\n # if the player has enough materials. Return true if plank is successfully \n # made, otherwise false. \n def make_plank(self):\n if(self.inventory[\"wood \"] >= 2):\n self.inventory[\"wood \"] -= 2 \n self.inventory[\"plank\"] += 1\n game.time.spend()\n return True\n return False\n # Make brick and update the player inventory with respect to the action,\n # if the player has enough materials. Return true if brick is successfully \n # made, otherwise false.\n def make_brick(self):\n if(self.inventory[\"dirt \"] >= 2 and self.inventory[\"water\"] >= 1):\n self.inventory[\"dirt \"] -= 2 \n self.inventory[\"water\"] -= 1 \n self.inventory[\"brick\"] += 1\n game.time.spend()\n return True\n return False\n \n # Shows the player inventory\n def show_inventory(self):\n print()\n c = 1\n for key in sorted(self.inventory.keys()):\n print(\"{}. {}\\t: {}\".format(c, key, (COLORS[key]+\" \")*self.inventory[key]))\n c += 1\n print() \n\nclass Time():\n def __init__(self, mins, hours, action_cost):\n self.mins = mins\n self.hours = hours\n self.action_cost = action_cost\n # Spend the action cost and update mins and/or hours. If the time is\n # up return False, otherwise True.\n def spend(self):\n if(self.hours > 0 and self.mins == 0):\n self.mins = 60\n self.mins -= self.action_cost\n self.hours -= 1\n return True\n else:\n self.mins -= self.action_cost\n if(self.hours == 0 and self.mins == 0):\n game.cont = False\n return False\n return True\n\n # Shows the remaning time in hours and mins format\n def show_time(self):\n print(\"{} hours {} minutes left!!!\".format(self.hours, self.mins))\n\n# CONSTANTS \nMAP_WIDTH = 10\nMAP_HEIGHT = 10\nACTION_COST = 15 #minutes\nINIT_TIME = 16 #hours\nperson =u\"\\u2687\" #character #u'U' #u'\\u267f' #u'\\u2687' \nhappy = u\"\\u263b\" # happy character\nCOLORS = {'empty':'\\033[40m \\033[0m', 'wood ':'\\033[42m \\033[0m',\n 'dirt ':'\\033[47m \\033[0m', 'water':'\\033[46m \\033[0m',\n 'plank':'\\033[43m \\033[0m', 'brick':'\\033[41m \\033[0m'}\n \n# Constant moves, items and products \nmoves = {\"w\":\"up\", \"s\":\"down\", \"a\":\"left\", \"d\":\"right\"}\nitems = {\"1\":\"brick\", \"2\":\"dirt \", \"3\":\"plank\", \"4\":\"water\", \"5\":\"wood \"}\nproducts = {\"e\":\"plank\", \"r\":\"brick\"}\n\n# A Game class is instantiated each time a new game begins.\n\n\ngame = Game(MAP_WIDTH, MAP_HEIGHT, INIT_TIME, ACTION_COST)\nout = False\n\n################## THIS PART CAUSES AN INFINITE LOOP!!! ##################\n# Implement the game play. Take the instructions from the user and execute them.\nwhile game.cont and not game.safe:\n instructions = input(\"Make your move : \")\n if(instructions == \"o\"):\n game.cont = False\n out = True\n elif(instructions == \"a\" or instructions == \"w\" or instructions == \"d\" or instructions == \"s\" ):\n game.move_player(instructions)\n elif(instructions == \"q\"):\n game.pick_item()\n elif(instructions == \"1\" or instructions == \"2\" or instructions == \"3\" or instructions == \"4\" or instructions == \"5\"):\n game.put_item(instructions)\n elif(instructions == \"e\" or instructions == \"r\"):\n game.make(instructions)\n game.check_safety()\n \nif game.safe:\n print(\"Congratulations! You are safe!!!\")\n print(\"Your score is {}.\".format(game.calc_score()))\nelif out:\n print(\"Bye!\")\nelse:\n print(\"Too late! They are coming!!!\") \n"
] | [
[
"numpy.unique",
"numpy.in1d",
"numpy.array",
"numpy.zeros",
"numpy.where",
"numpy.random.randint"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
shaoliangliang1996/pyBKT | [
"1354f95d7db6dd217c1a58cabc9c1352141ad4fd"
] | [
"source-py/pyBKT/util/metrics.py"
] | [
"import numpy as np\nimport sklearn.metrics as sk\n\nSUPPORTED_METRICS = ['accuracy', 'auc', 'rmse']\n\ndef error_check(flat_true_values, pred_values):\n if len(flat_true_values) != len(pred_values):\n raise ValueError(\"preds and true values need to have same shape\")\n\ndef accuracy(flat_true_values, pred_values):\n error_check(flat_true_values, pred_values)\n if len(flat_true_values) == 0:\n return np.nan\n correct = 0\n for i in range(len(pred_values)):\n if pred_values[i] >= 0.5 and flat_true_values[i] == 1:\n correct += 1\n if pred_values[i] < 0.5 and flat_true_values[i] == 0:\n correct += 1\n return correct/len([x for x in flat_true_values if (x == 0 or x == 1)])\n\ndef auc(flat_true_values, pred_values):\n error_check(flat_true_values, pred_values)\n # multiprior handling, remove phantom nondata\n if len(flat_true_values) == 0:\n return np.nan\n i = 0\n while i < len(flat_true_values):\n if (flat_true_values[i] != 1 and flat_true_values[i] != 0) or (pred_values[i] < 0 or pred_values[i] > 1):\n flat_true_values = np.delete(flat_true_values, i)\n pred_values = np.delete(pred_values, i)\n i -= 1\n i += 1\n if len(set(flat_true_values)) == 1:\n return np.nan\n\n auc = sk.roc_auc_score(flat_true_values, pred_values)\n return auc\n\ndef rmse(flat_true_values, pred_values):\n # represent correct as 1, incorrect as 0 for RMSE calculation\n if len(flat_true_values) == 0:\n return np.nan\n error_check(flat_true_values, pred_values)\n rmse, c = 0, 0\n for i in range(len(flat_true_values)):\n if flat_true_values[i] != -1:\n rmse += ((flat_true_values[i] - pred_values[i]) ** 2)\n c += 1\n rmse /= c\n rmse = rmse ** 0.5\n return rmse\n\n"
] | [
[
"sklearn.metrics.roc_auc_score",
"numpy.delete"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
tasbolat1/DGflow | [
"6ce22095a0d33f4da3c15f093aa365ba6cabbac9"
] | [
"conditional_batchnorm.py"
] | [
"import torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.nn import init\n\n\nclass ConditionalBatchNorm2d(nn.BatchNorm2d):\n\n \"\"\"Conditional Batch Normalization\"\"\"\n\n def __init__(self, num_features, eps=1e-05, momentum=0.1,\n affine=False, track_running_stats=True):\n super(ConditionalBatchNorm2d, self).__init__(\n num_features, eps, momentum, affine, track_running_stats\n )\n\n def forward(self, input, weight, bias, **kwargs):\n self._check_input_dim(input)\n\n exponential_average_factor = 0.0\n\n if self.training and self.track_running_stats:\n self.num_batches_tracked += 1\n if self.momentum is None: # use cumulative moving average\n exponential_average_factor = 1.0 /\\\n self.num_batches_tracked.item()\n else: # use exponential moving average\n exponential_average_factor = self.momentum\n\n output = F.batch_norm(input, self.running_mean, self.running_var,\n self.weight, self.bias,\n self.training or not self.track_running_stats,\n exponential_average_factor, self.eps)\n if weight.dim() == 1:\n weight = weight.unsqueeze(0)\n if bias.dim() == 1:\n bias = bias.unsqueeze(0)\n size = output.size()\n weight = weight.unsqueeze(-1).unsqueeze(-1).expand(size)\n bias = bias.unsqueeze(-1).unsqueeze(-1).expand(size)\n return weight * output + bias\n\n\nclass CategoricalConditionalBatchNorm2d(ConditionalBatchNorm2d):\n\n def __init__(self, num_classes, num_features, eps=1e-5, momentum=0.1,\n affine=False, track_running_stats=True):\n super(CategoricalConditionalBatchNorm2d, self).__init__(\n num_features, eps, momentum, affine, track_running_stats\n )\n self.weights = nn.Embedding(num_classes, num_features)\n self.biases = nn.Embedding(num_classes, num_features)\n\n self._initialize()\n\n def _initialize(self):\n init.ones_(self.weights.weight.data)\n init.zeros_(self.biases.weight.data)\n\n def forward(self, input, c, **kwargs):\n weight = self.weights(c)\n bias = self.biases(c)\n\n return super(CategoricalConditionalBatchNorm2d, self)\\\n .forward(input, weight, bias)\n\n\nif __name__ == '__main__':\n \"\"\"Forward computation check.\"\"\"\n import torch\n size = (3, 3, 12, 12)\n batch_size, num_features = size[:2]\n print('# Affirm embedding output')\n naive_bn = nn.BatchNorm2d(3)\n idx_input = torch.tensor([1, 2, 0], dtype=torch.long)\n embedding = nn.Embedding(3, 3)\n weights = embedding(idx_input)\n print('# weights size', weights.size())\n empty = torch.tensor((), dtype=torch.float)\n running_mean = empty.new_zeros((3,))\n running_var = empty.new_ones((3,))\n\n naive_bn_W = naive_bn.weight\n\n input = torch.rand(*size, dtype=torch.float32)\n print('input size', input.size())\n print('input ndim ', input.dim())\n\n _ = naive_bn(input)\n\n print('# batch_norm with given weights')\n\n try:\n with torch.no_grad():\n output = F.batch_norm(input, running_mean, running_var,\n weights, naive_bn.bias, False, 0.0, 1e-05)\n except Exception as e:\n print(\"\\tFailed to use given weights\")\n print('# Error msg:', e)\n print()\n else:\n print(\"Succeeded to use given weights\")\n\n print('\\n# Batch norm before use given weights')\n with torch.no_grad():\n tmp_out = F.batch_norm(input, running_mean, running_var,\n naive_bn_W, naive_bn.bias, False, .0, 1e-05)\n weights_cast = weights.unsqueeze(-1).unsqueeze(-1)\n weights_cast = weights_cast.expand(tmp_out.size())\n try:\n out = weights_cast * tmp_out\n except Exception:\n print(\"Failed\")\n else:\n print(\"Succeeded!\")\n print('\\t {}'.format(out.size()))\n print(type(tuple(out.size())))\n\n print('--- condBN and catCondBN ---')\n\n catCondBN = CategoricalConditionalBatchNorm2d(3, 3)\n output = catCondBN(input, idx_input)\n\n assert tuple(output.size()) == size\n\n condBN = ConditionalBatchNorm2d(3)\n\n idx = torch.tensor([1], dtype=torch.long)\n out = catCondBN(input, idx)\n\n print('cat cond BN weights\\n', catCondBN.weights.weight.data)\n print('cat cond BN biases\\n', catCondBN.biases.weight.data)\n"
] | [
[
"torch.nn.functional.batch_norm",
"torch.nn.Embedding",
"torch.tensor",
"torch.nn.init.ones_",
"torch.no_grad",
"torch.rand",
"torch.nn.BatchNorm2d",
"torch.nn.init.zeros_"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
timothymillar/sgkit | [
"a3a5e961b6b21ff7de235075955c0f797ad5027c",
"a3a5e961b6b21ff7de235075955c0f797ad5027c",
"a3a5e961b6b21ff7de235075955c0f797ad5027c",
"a3a5e961b6b21ff7de235075955c0f797ad5027c",
"a3a5e961b6b21ff7de235075955c0f797ad5027c"
] | [
"sgkit/model.py",
"sgkit/stats/conversion.py",
"sgkit/stats/regenie.py",
"sgkit/tests/test_variables.py",
"sgkit/distance/metrics.py"
] | [
"from typing import Any, Dict, Hashable, List, Optional\n\nimport numpy as np\nimport xarray as xr\n\nfrom .typing import ArrayLike\nfrom .utils import create_dataset\n\nDIM_VARIANT = \"variants\"\nDIM_SAMPLE = \"samples\"\nDIM_PLOIDY = \"ploidy\"\nDIM_ALLELE = \"alleles\"\nDIM_GENOTYPE = \"genotypes\"\n\n\ndef create_genotype_call_dataset(\n *,\n variant_contig_names: List[str],\n variant_contig: ArrayLike,\n variant_position: ArrayLike,\n variant_allele: ArrayLike,\n sample_id: ArrayLike,\n call_genotype: ArrayLike,\n call_genotype_phased: Optional[ArrayLike] = None,\n variant_id: Optional[ArrayLike] = None,\n mixed_ploidy: bool = False,\n) -> xr.Dataset:\n \"\"\"Create a dataset of genotype calls.\n\n Parameters\n ----------\n variant_contig_names\n The contig names.\n variant_contig\n [array_like, element type: int]\n The (index of the) contig for each variant.\n variant_position\n [array_like, element type: int]\n The reference position of the variant.\n variant_allele\n [array_like, element_type: zero-terminated bytes, e.g. \"S1\", or object]\n The possible alleles for the variant.\n sample_id\n [array_like, element type: str or object]\n The unique identifier of the sample.\n call_genotype\n [array_like, element type: int] Genotype, encoded as allele values\n (0 for the reference, 1 for the first allele, 2 for the second allele),\n or -1 to indicate a missing value.\n call_genotype_phased\n [array_like, element type: bool, optional] A flag for each call indicating if it is\n phased or not. If omitted all calls are unphased.\n variant_id\n [array_like, element type: str or object, optional]\n The unique identifier of the variant.\n mixed_ploidy\n Specify if the dataset contains genotype calls with a mixture of ploidy levels\n using the value -2 to indicate non-alleles.\n\n Returns\n -------\n The dataset of genotype calls.\n \"\"\"\n data_vars: Dict[Hashable, Any] = {\n \"variant_contig\": ([DIM_VARIANT], variant_contig),\n \"variant_position\": ([DIM_VARIANT], variant_position),\n \"variant_allele\": ([DIM_VARIANT, DIM_ALLELE], variant_allele),\n \"sample_id\": ([DIM_SAMPLE], sample_id),\n \"call_genotype\": (\n [DIM_VARIANT, DIM_SAMPLE, DIM_PLOIDY],\n call_genotype,\n {\"mixed_ploidy\": mixed_ploidy},\n ),\n \"call_genotype_mask\": (\n [DIM_VARIANT, DIM_SAMPLE, DIM_PLOIDY],\n call_genotype < 0,\n ),\n }\n if call_genotype_phased is not None:\n data_vars[\"call_genotype_phased\"] = (\n [DIM_VARIANT, DIM_SAMPLE],\n call_genotype_phased,\n )\n if mixed_ploidy is True:\n data_vars[\"call_genotype_non_allele\"] = (\n [DIM_VARIANT, DIM_SAMPLE, DIM_PLOIDY],\n call_genotype < -1,\n )\n if variant_id is not None:\n data_vars[\"variant_id\"] = ([DIM_VARIANT], variant_id)\n attrs: Dict[Hashable, Any] = {\"contigs\": variant_contig_names}\n return create_dataset(data_vars=data_vars, attrs=attrs)\n\n\ndef create_genotype_dosage_dataset(\n *,\n variant_contig_names: List[str],\n variant_contig: ArrayLike,\n variant_position: ArrayLike,\n variant_allele: ArrayLike,\n sample_id: ArrayLike,\n call_dosage: ArrayLike,\n call_genotype_probability: ArrayLike,\n variant_id: Optional[ArrayLike] = None,\n) -> xr.Dataset:\n \"\"\"Create a dataset of genotype dosages.\n\n Parameters\n ----------\n variant_contig_names\n The contig names.\n variant_contig\n [array_like, element type: int]\n The (index of the) contig for each variant.\n variant_position\n [array_like, element type: int]\n The reference position of the variant.\n variant_allele\n [array_like, element_type: zero-terminated bytes, e.g. \"S1\", or object]\n The possible alleles for the variant.\n sample_id\n [array_like, element type: str or object]\n The unique identifier of the sample.\n call_dosage\n [array_like, element type: float]\n Dosages, encoded as floats, with NaN indicating a\n missing value.\n call_genotype_probability\n [array_like, element type: float]\n Probabilities, encoded as floats, with NaN indicating a\n missing value.\n variant_id\n [array_like, element type: str or object, optional]\n The unique identifier of the variant.\n\n Returns\n -------\n The dataset of genotype calls.\n\n \"\"\"\n data_vars: Dict[Hashable, Any] = {\n \"variant_contig\": ([DIM_VARIANT], variant_contig),\n \"variant_position\": ([DIM_VARIANT], variant_position),\n \"variant_allele\": ([DIM_VARIANT, DIM_ALLELE], variant_allele),\n \"sample_id\": ([DIM_SAMPLE], sample_id),\n \"call_dosage\": ([DIM_VARIANT, DIM_SAMPLE], call_dosage),\n \"call_dosage_mask\": ([DIM_VARIANT, DIM_SAMPLE], np.isnan(call_dosage)),\n \"call_genotype_probability\": (\n [DIM_VARIANT, DIM_SAMPLE, DIM_GENOTYPE],\n call_genotype_probability,\n ),\n \"call_genotype_probability_mask\": (\n [DIM_VARIANT, DIM_SAMPLE, DIM_GENOTYPE],\n np.isnan(call_genotype_probability),\n ),\n }\n if variant_id is not None:\n data_vars[\"variant_id\"] = ([DIM_VARIANT], variant_id)\n attrs: Dict[Hashable, Any] = {\"contigs\": variant_contig_names}\n return create_dataset(data_vars=data_vars, attrs=attrs)\n",
"import dask.array as da\nimport numpy as np\nfrom numba import guvectorize\nfrom xarray import Dataset\n\nfrom sgkit import variables\nfrom sgkit.typing import ArrayLike\nfrom sgkit.utils import conditional_merge_datasets, create_dataset\n\n\n@guvectorize( # type: ignore\n [\n \"void(float64[:], uint8[:], float64, int8[:])\",\n \"void(float32[:], uint8[:], float64, int8[:])\",\n ],\n \"(p),(k),()->(k)\",\n nopython=True,\n cache=True,\n)\ndef _convert_probability_to_call(\n gp: ArrayLike, _: ArrayLike, threshold: float, out: ArrayLike\n) -> None: # pragma: no cover\n \"\"\"Generalized U-function for converting genotype probabilities to hard calls\n\n Parameters\n ----------\n gp\n Genotype probabilities of shape (genotypes,) containing unphased, biallelic\n probabilities in the order homozygous reference, heterozygous, homozygous alternate.\n _\n Dummy variable of type `uint8` and shape (ploidy,) used to define\n the ploidy of the resulting array\n threshold\n Probability threshold that must be met or exceeded by at least one genotype\n probability in order for any calls to be made -- all values will be -1 (missing)\n otherwise. Setting this value to less than 0 disables any effect it has.\n out\n Hard calls array of shape (ploidy,).\n \"\"\"\n # Ignore singleton array inputs used for metadata inference by dask\n if gp.shape[0] == 1 and out.shape[0] == 1:\n return\n if gp.shape[0] != 3 or out.shape[0] != 2:\n raise NotImplementedError(\n \"Hard call conversion only supported for diploid, biallelic genotypes.\"\n )\n out[:] = -1 # (ploidy,)\n # Return no call if any probability is absent\n if np.any(np.isnan(gp)):\n return\n i = np.argmax(gp)\n # Return no call if max probability does not exceed threshold\n if threshold > 0 and gp[i] < threshold:\n return\n # Return no call if max probability is not unique\n if (gp[i] == gp).sum() > 1:\n return\n # Homozygous reference\n if i == 0:\n out[:] = 0\n # Heterozygous\n elif i == 1:\n out[0] = 1\n out[1] = 0\n # Homozygous alternate\n else:\n out[:] = 1\n\n\ndef convert_probability_to_call(\n ds: Dataset,\n call_genotype_probability: str = variables.call_genotype_probability,\n threshold: float = 0.9,\n merge: bool = True,\n) -> Dataset:\n \"\"\"\n Convert genotype probabilities to hard calls.\n\n Parameters\n ----------\n ds\n Dataset containing genotype probabilities, such as from :func:`sgkit.io.bgen.read_bgen`.\n call_genotype_probability\n Genotype probability variable to be converted as defined by\n :data:`sgkit.variables.call_genotype_probability_spec`.\n threshold\n Probability threshold in [0, 1] that must be met or exceeded by at least one genotype\n probability in order for any calls to be made -- all values will be -1 (missing)\n otherwise. Setting this value to less than or equal to 0 disables any effect it has.\n Default value is 0.9.\n merge\n If True (the default), merge the input dataset and the computed\n output variables into a single dataset, otherwise return only\n the computed output variables.\n See :ref:`dataset_merge` for more details.\n\n Returns\n -------\n A dataset containing the following variables:\n\n - `call_genotype` (variants, samples, ploidy): Converted hard calls.\n Defined by :data:`sgkit.variables.call_genotype_spec`.\n\n - `call_genotype_mask` (variants, samples, ploidy): Mask for converted hard calls.\n Defined by :data:`sgkit.variables.call_genotype_mask_spec`.\n \"\"\"\n if not (0 <= threshold <= 1):\n raise ValueError(f\"Threshold must be float in [0, 1], not {threshold}.\")\n variables.validate(\n ds, {call_genotype_probability: variables.call_genotype_probability_spec}\n )\n if ds.dims[\"genotypes\"] != 3:\n raise NotImplementedError(\n f\"Hard call conversion only supported for diploid, biallelic genotypes; \"\n f\"num genotypes in provided probabilities array = {ds.dims['genotypes']}.\"\n )\n GP = da.asarray(ds[call_genotype_probability])\n # Remove chunking in genotypes dimension, if present\n if len(GP.chunks[2]) > 1:\n GP = GP.rechunk((None, None, -1))\n K = da.empty(2, dtype=np.uint8)\n GT = _convert_probability_to_call(GP, K, threshold)\n new_ds = create_dataset(\n {\n variables.call_genotype: ((\"variants\", \"samples\", \"ploidy\"), GT),\n variables.call_genotype_mask: ((\"variants\", \"samples\", \"ploidy\"), GT < 0),\n }\n )\n return conditional_merge_datasets(ds, new_ds, merge)\n",
"from typing import Any, Dict, Hashable, Optional, Sequence, Tuple, Union\n\nimport dask.array as da\nimport numpy as np\nimport xarray as xr\nfrom dask.array import Array\nfrom numpy import ndarray\nfrom xarray import Dataset\n\nfrom .. import variables\nfrom ..typing import ArrayLike\nfrom ..utils import conditional_merge_datasets, create_dataset, split_array_chunks\nfrom .utils import (\n assert_array_shape,\n assert_block_shape,\n assert_chunk_shape,\n concat_2d,\n r2_score,\n)\n\n\ndef index_array_blocks(\n x: Union[ArrayLike, Sequence[int]], size: int\n) -> Tuple[ndarray, ndarray]:\n \"\"\"Generate indexes for blocks that partition an array within groups.\n\n Given an array with monotonic increasing group assignments (as integers),\n this function will generate the indexes of blocks within those groups that\n are of at most `size` elements.\n\n Parameters\n ----------\n x\n Vector of group assignments, must be monotonic increasing.\n Resulting blocks will never cross these group assignments\n and the resulting `index` and `sizes` values constitute\n covering slices for any array of the same size as `x`.\n size\n Maximum block size.\n\n Examples\n --------\n >>> from sgkit.stats.regenie import index_array_blocks\n >>> index_array_blocks([0, 0, 0], 2) # doctest: +SKIP\n (array([0, 2]), array([2, 1]))\n >>> index_array_blocks([0, 0, 1, 1, 1], 2) # doctest: +SKIP\n (array([0, 2, 4]), array([2, 2, 1]))\n\n Returns\n -------\n index : ndarray\n Array of indexes for each block start\n sizes : ndarray\n Size of block such that `x[index[0]:(index[0] + sizes[0])]` contains\n every element in block 0\n\n Raises\n ------\n ValueError\n If `x` is not 1D.\n ValueError\n If `size` is <= 0.\n ValueError\n If `x` does not contain integers.\n ValueError\n If `x` is not monotonic increasing.\n \"\"\"\n x = np.asarray(x)\n if x.size == 0:\n return np.empty(0, dtype=int), np.empty(0, dtype=int)\n if x.ndim != 1:\n raise ValueError(f\"Array shape {x.shape} is not 1D\")\n if size <= 0:\n raise ValueError(f\"Block size {size} must be > 0\")\n if not np.issubdtype(x.dtype, np.integer):\n raise ValueError(\"Array to partition must contain integers\")\n if np.any(np.diff(x) < 0):\n raise ValueError(\"Array to partition must be monotonic increasing\")\n breaks = np.argwhere(np.diff(x, prepend=x[0]))[:, 0]\n breaks = np.concatenate(([0], breaks, [x.size]))\n index = np.concatenate(\n [np.arange(breaks[i], breaks[i + 1], size) for i in range(breaks.size - 1)]\n )\n sizes = np.diff(index, append=x.size)\n assert index.size == sizes.size\n return index, sizes\n\n\ndef index_block_sizes(\n sizes: Union[ArrayLike, Sequence[int]]\n) -> Tuple[ndarray, ndarray]:\n \"\"\"Generate indexes for blocks of specific sizes.\n\n Parameters\n ----------\n sizes\n Block sizes to generate indexes for.\n\n Examples\n --------\n >>> from sgkit.stats.regenie import index_block_sizes\n >>> index_block_sizes([3, 4, 5]) # doctest: +SKIP\n (array([0, 3, 7]), array([3, 4, 5]))\n\n Returns\n -------\n index : ndarray\n Array of indexes for each block start.\n sizes : ndarray\n Size of block such that `x[index[0]:(index[0] + sizes[0])]` contains\n every element in block 0.\n\n Raises\n ------\n ValueError\n If any value in `sizes` is <= 0.\n ValueError\n If `sizes` does not contain integers.\n \"\"\"\n sizes = np.asarray(sizes)\n if np.any(sizes <= 0):\n raise ValueError(\"All block sizes must be >= 0\")\n if not np.issubdtype(sizes.dtype, np.integer):\n raise ValueError(\"Block sizes must be integers\")\n chunks = np.concatenate([np.array([0]), sizes])\n index = np.cumsum(chunks)[:-1]\n assert index.size == sizes.size\n return index, sizes\n\n\ndef ridge_regression(\n XtX: ArrayLike,\n XtY: ArrayLike,\n alphas: Union[ArrayLike, Sequence[float]],\n n_zero_reg: Optional[int] = None,\n dtype: Any = None,\n) -> ArrayLike:\n \"\"\"Multi-outcome, multi-parameter ridge regression from CV intermediates.\"\"\"\n if XtX.shape[0] != XtX.shape[1]:\n raise ValueError(f\"First argument must be symmetric (shape = {XtX.shape})\")\n if XtX.shape[0] != XtY.shape[0]:\n raise ValueError(\"Array arguments must have same size in first dimension\")\n diags = []\n n_alpha, n_obs, n_outcome = len(alphas), XtX.shape[0], XtY.shape[1]\n for i in range(n_alpha):\n diag = np.ones(XtX.shape[1]) * alphas[i]\n if n_zero_reg:\n # Optionally fix regularization for leading covariates\n # TODO: This should probably be zero for consistency\n # with orthogonalization, see:\n # https://github.com/projectglow/glow/issues/266\n diag[:n_zero_reg] = 1\n diags.append(np.diag(diag))\n diags = np.stack(diags)\n B = np.linalg.inv(XtX + diags) @ XtY\n B = B.astype(dtype or XtX.dtype)\n assert_array_shape(B, n_alpha, n_obs, n_outcome)\n return B\n\n\ndef get_alphas(\n n_cols: int, heritability: Sequence[float] = [0.99, 0.75, 0.50, 0.25, 0.01]\n) -> ndarray:\n # https://github.com/projectglow/glow/blob/f3edf5bb8fe9c2d2e1a374d4402032ba5ce08e29/python/glow/wgr/linear_model/ridge_model.py#L80\n return np.array([n_cols / h for h in heritability])\n\n\ndef stack(x: Array) -> Array:\n \"\"\"Stack blocks as new leading array axis\"\"\"\n return da.stack([x.blocks[i] for i in range(x.numblocks[0])])\n\n\ndef unstack(x: Array) -> Array:\n \"\"\"Unstack leading array axis into blocks\"\"\"\n return da.concatenate([x.blocks[i][0] for i in range(x.numblocks[0])])\n\n\ndef _ridge_regression_cv(\n X: Array, Y: Array, alphas: ndarray, n_zero_reg: Optional[int] = None\n) -> Tuple[Array, Array, Array, Array]:\n assert alphas.ndim == 1\n assert X.ndim == 2\n assert Y.ndim == 2\n assert X.numblocks[1] == 1\n assert Y.numblocks[1] == 1\n assert X.chunks[0] == Y.chunks[0]\n n_block, n_obs, n_covar, n_outcome, n_alpha = (\n X.numblocks[0],\n X.shape[0],\n X.shape[1],\n Y.shape[1],\n alphas.shape[0],\n )\n obs_chunks = X.chunks[0]\n\n # Project samples and outcomes noting that resulting chunks are\n # of fixed size even if the chunks along the observation dim\n # are not uniform (i.e. |X.chunks[0]| != 1)\n XtX = stack(da.map_blocks(lambda x: x.T @ x, X, chunks=(X.shape[1],) * 2))\n assert_block_shape(XtX, n_block, 1, 1)\n assert_chunk_shape(XtX, 1, n_covar, n_covar)\n XtY = stack(da.map_blocks(lambda x, y: x.T @ y, X, Y, chunks=(n_covar, n_outcome)))\n assert_block_shape(XtY, n_block, 1, 1)\n assert_chunk_shape(XtY, 1, n_covar, n_outcome)\n\n # Invert the projections in each block so that each\n # contains data from all other blocks *except* itself\n XtX = unstack(XtX.sum(axis=0) - XtX)\n assert_block_shape(XtX, n_block, 1)\n assert_chunk_shape(XtX, n_covar, n_covar)\n XtY = unstack(XtY.sum(axis=0) - XtY)\n assert_block_shape(XtY, n_block, 1)\n assert_chunk_shape(XtY, n_covar, n_outcome)\n assert XtX.numblocks == XtY.numblocks\n\n # Regress for all outcomes/alphas and add new axis for ridge parameters\n B = da.map_blocks(\n ridge_regression,\n XtX,\n XtY,\n chunks=(n_alpha, n_covar, n_outcome),\n new_axis=[0],\n alphas=alphas,\n n_zero_reg=n_zero_reg,\n )\n assert_block_shape(B, 1, n_block, 1)\n assert_chunk_shape(B, n_alpha, n_covar, n_outcome)\n assert_array_shape(B, n_alpha, n_block * n_covar, n_outcome)\n\n # Generate predictions for all outcomes/alphas\n assert B.numblocks == (1,) + X.numblocks\n YP = da.map_blocks(\n lambda x, b: x @ b, X, B, chunks=(alphas.size, obs_chunks, n_outcome)\n )\n assert_block_shape(YP, 1, n_block, 1)\n assert_chunk_shape(YP, n_alpha, obs_chunks[0], n_outcome)\n assert_array_shape(YP, n_alpha, n_obs, n_outcome)\n\n return XtX, XtY, B, YP\n\n\ndef _stage_1(G: Array, X: Array, Y: Array, alphas: Optional[ndarray] = None) -> Array:\n \"\"\"Stage 1 - WGR Base Regression\n\n This stage will predict outcomes separately for each alpha parameter and variant\n block. This \"compresses\" the variant dimension into a smaller space that is\n much more amenable to efficient blockwise regressions in stage 2. Another\n interpretation for this operation is that all sample blocks are treated\n as folds in a K-fold CV fit within one single variant block. Predictions for\n any one combination of variant and sample block then correspond to a\n regression model fit all across sample blocks for that range of variants\n except for a single sample block. In other words, the predictions are\n out of sample which enables training of a stage 2 regressor based on\n these predictions, a technique commonly referred to as stacking.\n\n For more details, see the level 0 regression model described in step 1\n of [Mbatchou et al. 2020](https://www.biorxiv.org/content/10.1101/2020.06.19.162354v2).\n \"\"\"\n assert G.ndim == 2\n assert X.ndim == 2\n assert Y.ndim == 2\n # Check that chunking across samples is the same for all arrays\n assert G.shape[0] == X.shape[0] == Y.shape[0]\n assert G.numblocks[0] == X.numblocks[0] == Y.numblocks[0]\n assert G.chunks[0] == X.chunks[0] == Y.chunks[0]\n assert X.numblocks[1] == Y.numblocks[1] == 1\n if alphas is None:\n alphas = get_alphas(G.shape[1])\n # Extract shape statistics\n n_sample = G.shape[0]\n n_outcome = Y.shape[1]\n n_alpha = alphas.size\n n_sample_block = G.numblocks[0]\n n_variant_block = G.numblocks[1]\n sample_chunks = Y.chunks[0]\n\n YP = []\n for i in range(n_variant_block):\n # Extract all sample blocks for one variant block\n GB = G.blocks[:, i]\n # Prepend covariates and chunk along first dim only\n XGB = da.concatenate((X, GB), axis=1)\n XGB = XGB.rechunk(chunks=(None, -1))\n # Fit and predict folds for each parameter and outcome\n YPB = _ridge_regression_cv(XGB, Y, alphas, n_zero_reg=X.shape[1])[-1]\n assert_block_shape(YPB, 1, n_sample_block, 1)\n assert_chunk_shape(YPB, n_alpha, sample_chunks[0], n_outcome)\n assert_array_shape(YPB, n_alpha, n_sample, n_outcome)\n YP.append(YPB)\n # Stack as (n_variant_block, n_alpha, n_sample, n_outcome)\n YP = da.stack(YP, axis=0)\n assert_block_shape(YP, n_variant_block, 1, n_sample_block, 1)\n assert_chunk_shape(YP, 1, n_alpha, sample_chunks[0], n_outcome)\n assert_array_shape(YP, n_variant_block, n_alpha, n_sample, n_outcome)\n return YP\n\n\ndef _stage_2(\n YP: Array,\n X: Array,\n Y: Array,\n alphas: Optional[ndarray] = None,\n normalize: bool = True,\n _glow_adj_alpha: bool = False,\n _glow_adj_scaling: bool = False,\n) -> Tuple[Array, Array]:\n \"\"\"Stage 2 - WGR Meta Regression\n\n This stage will train separate ridge regression models for each outcome\n using the predictions from stage 1 for that same outcome as features. These\n predictions are then evaluated based on R2 score to determine an optimal\n \"meta\" estimator (see `_stage_1` for the \"base\" estimator description). Results\n then include only predictions and coefficients from this optimal model.\n\n For more details, see the level 1 regression model described in step 1\n of [Mbatchou et al. 2020](https://www.biorxiv.org/content/10.1101/2020.06.19.162354v2).\n \"\"\"\n assert YP.ndim == 4\n assert X.ndim == 2\n assert Y.ndim == 2\n # Check that chunking across samples is the same for all arrays\n assert YP.numblocks[2] == X.numblocks[0] == Y.numblocks[0]\n assert YP.chunks[2] == X.chunks[0] == Y.chunks[0]\n # Assert single chunks for covariates and outcomes\n assert X.numblocks[1] == Y.numblocks[1] == 1\n # Extract shape statistics\n n_variant_block, n_alpha_1 = YP.shape[:2]\n n_sample_block = Y.numblocks[0]\n n_sample, n_outcome = Y.shape\n n_covar = X.shape[1]\n n_indvar = n_covar + n_variant_block * n_alpha_1\n sample_chunks = Y.chunks[0]\n\n if normalize:\n assert_block_shape(YP, n_variant_block, 1, n_sample_block, 1)\n assert_chunk_shape(YP, 1, n_alpha_1, sample_chunks[0], n_outcome)\n # See: https://github.com/projectglow/glow/issues/260\n if _glow_adj_scaling:\n YP = da.map_blocks(\n lambda x: (x - x.mean(axis=2, keepdims=True))\n / x.std(axis=2, keepdims=True),\n YP,\n )\n else:\n YP = (YP - YP.mean(axis=2, keepdims=True)) / YP.std(axis=2, keepdims=True)\n # Tranpose for refit on level 1 predictions\n YP = YP.transpose((3, 2, 0, 1))\n assert_array_shape(YP, n_outcome, n_sample, n_variant_block, n_alpha_1)\n\n if alphas is None:\n # See: https://github.com/projectglow/glow/issues/255\n if _glow_adj_alpha:\n alphas = get_alphas(n_variant_block * n_alpha_1 * n_outcome)\n else:\n alphas = get_alphas(n_variant_block * n_alpha_1)\n n_alpha_2 = alphas.size\n\n YR = []\n BR = []\n for i in range(n_outcome):\n # Slice and reshape to new 2D covariate matrix;\n # The order of raveling in trailing dimensions is important\n # and later reshapes will assume variants, alphas order\n XPB = YP[i].reshape((n_sample, n_variant_block * n_alpha_1))\n # Prepend covariates and chunk along first dim only\n XPB = da.concatenate((X, XPB), axis=1)\n XPB = XPB.rechunk(chunks=(None, -1))\n assert_array_shape(XPB, n_sample, n_indvar)\n assert XPB.numblocks == (n_sample_block, 1)\n # Extract outcome vector\n YB = Y[:, [i]]\n assert XPB.ndim == YB.ndim == 2\n # Fit and predict folds for each parameter\n BB, YPB = _ridge_regression_cv(XPB, YB, alphas, n_zero_reg=n_covar)[-2:]\n assert_array_shape(BB, n_alpha_2, n_sample_block * n_indvar, 1)\n assert_array_shape(YPB, n_alpha_2, n_sample, 1)\n BR.append(BB)\n YR.append(YPB)\n\n # Concatenate predictions along outcome dimension\n YR = da.concatenate(YR, axis=2)\n assert_block_shape(YR, 1, n_sample_block, n_outcome)\n assert_chunk_shape(YR, n_alpha_2, sample_chunks[0], 1)\n assert_array_shape(YR, n_alpha_2, n_sample, n_outcome)\n # Move samples to last dim so all others are batch\n # dims for R2 calculations\n YR = da.transpose(YR, (0, 2, 1))\n assert_array_shape(YR, n_alpha_2, n_outcome, n_sample)\n YR = YR.rechunk((-1, -1, None))\n assert_block_shape(YR, 1, 1, n_sample_block)\n assert YR.shape[1:] == Y.T.shape\n\n # Concatenate betas along outcome dimension\n BR = da.concatenate(BR, axis=2)\n assert_block_shape(BR, 1, n_sample_block, n_outcome)\n assert_chunk_shape(BR, n_alpha_2, n_indvar, 1)\n assert_array_shape(BR, n_alpha_2, n_sample_block * n_indvar, n_outcome)\n\n # Compute R2 scores within each sample block for each outcome + alpha\n R2 = da.stack(\n [\n r2_score(YR.blocks[..., i], Y.T.blocks[..., i])\n # Avoid warnings on R2 calculations for blocks with single rows\n if YR.chunks[-1][i] > 1 else da.full(YR.shape[:-1], np.nan)\n for i in range(n_sample_block)\n ]\n )\n assert_array_shape(R2, n_sample_block, n_alpha_2, n_outcome)\n # Coerce to finite or nan before nan-aware mean\n R2 = da.where(da.isfinite(R2), R2, np.nan)\n # Find highest mean alpha score for each outcome across blocks\n R2M = da.nanmean(R2, axis=0)\n assert_array_shape(R2M, n_alpha_2, n_outcome)\n # Identify index for the alpha value with the highest mean score\n R2I = da.argmax(R2M, axis=0)\n assert_array_shape(R2I, n_outcome)\n\n # Choose the predictions corresponding to the model with best score\n YRM = da.stack([YR[R2I[i], i, :] for i in range(n_outcome)], axis=-1)\n YRM = YRM.rechunk((None, -1))\n assert_block_shape(YRM, n_sample_block, 1)\n assert_chunk_shape(YRM, sample_chunks[0], n_outcome)\n assert_array_shape(YRM, n_sample, n_outcome)\n # Choose the betas corresponding to the model with the best score\n BRM = da.stack([BR[R2I[i], :, i] for i in range(n_outcome)], axis=-1)\n BRM = BRM.rechunk((None, -1))\n assert_block_shape(BRM, n_sample_block, 1)\n assert_chunk_shape(BRM, n_indvar, n_outcome)\n assert_array_shape(BRM, n_sample_block * n_indvar, n_outcome)\n return BRM, YRM\n\n\ndef _stage_3(\n B: Array,\n YP: Array,\n X: Array,\n Y: Array,\n contigs: Array,\n variant_chunk_start: ndarray,\n) -> Optional[Array]:\n \"\"\"Stage 3 - Leave-one-chromosome-out (LOCO) Estimation\n\n This stage will use the coefficients for the optimal model in\n stage 2 to re-estimate predictions in a LOCO scheme. This scheme\n involves omitting coefficients that correspond to all variant\n blocks for a single chromosome in the stage 2 model and then\n recomputing predictions without those coefficients.\n\n For more details, see the \"LOCO predictions\" section of the Supplementary Methods\n in [Mbatchou et al. 2020](https://www.biorxiv.org/content/10.1101/2020.06.19.162354v2).\n \"\"\"\n assert B.ndim == 2\n assert YP.ndim == 4\n assert X.ndim == 2\n assert Y.ndim == 2\n # Check that chunking across samples is the same for all arrays\n assert B.numblocks[0] == YP.numblocks[2] == X.numblocks[0] == Y.numblocks[0]\n assert YP.chunks[2] == X.chunks[0] == Y.chunks[0]\n # Extract shape statistics\n sample_chunks = Y.chunks[0]\n n_covar = X.shape[1]\n n_variant_block, n_alpha_1 = YP.shape[:2]\n n_indvar = n_covar + n_variant_block * n_alpha_1\n n_sample_block = Y.numblocks[0]\n n_sample, n_outcome = Y.shape\n\n # Determine unique contigs to create LOCO estimates for\n contigs = np.asarray(contigs)\n unique_contigs = np.unique(contigs)\n n_contig = len(unique_contigs)\n if n_contig <= 1:\n # Return nothing w/o at least 2 contigs\n return None\n\n assert n_variant_block == len(variant_chunk_start)\n # Create vector of size `n_variant_block` where value\n # at index i corresponds to contig for variant block i\n variant_block_contigs = contigs[variant_chunk_start]\n\n # Transform coefficients (B) such that trailing dimensions\n # contain right half of matrix product for prediction:\n # (n_sample_block * n_indvar, n_outcome) ->\n # (n_outcome, n_sample_block, n_indvar)\n B = da.stack([B.blocks[i] for i in range(n_sample_block)], axis=0)\n assert_block_shape(B, n_sample_block, 1, 1)\n assert_chunk_shape(B, 1, n_indvar, n_outcome)\n assert_array_shape(B, n_sample_block, n_indvar, n_outcome)\n B = da.transpose(B, (2, 0, 1))\n assert_block_shape(B, 1, n_sample_block, 1)\n assert_chunk_shape(B, n_outcome, 1, n_indvar)\n assert_array_shape(B, n_outcome, n_sample_block, n_indvar)\n\n # Decompose coefficients (B) so that variant blocks can be sliced:\n # BX -> (n_outcome, n_sample_block, n_covar)\n # BYP -> (n_outcome, n_sample_block, n_variant_block, n_alpha_1)\n BX = B[..., :n_covar]\n assert_array_shape(BX, n_outcome, n_sample_block, n_covar)\n BYP = B[..., n_covar:]\n assert_array_shape(BYP, n_outcome, n_sample_block, n_variant_block * n_alpha_1)\n BYP = BYP.reshape((n_outcome, n_sample_block, n_variant_block, n_alpha_1))\n assert_block_shape(BYP, 1, n_sample_block, 1, 1)\n assert_chunk_shape(BYP, n_outcome, 1, n_variant_block, n_alpha_1)\n assert_array_shape(BYP, n_outcome, n_sample_block, n_variant_block, n_alpha_1)\n\n # Transform base predictions (YP) such that trailing dimensions\n # contain left half of matrix product for prediction as well\n # as variant blocks to slice on:\n # (n_variant_block, n_alpha_1, n_sample, n_outcome) ->\n # (n_outcome, n_sample, n_variant_block, n_alpha_1)\n YP = da.transpose(YP, (3, 2, 0, 1))\n assert_block_shape(YP, 1, n_sample_block, n_variant_block, 1)\n assert_chunk_shape(YP, n_outcome, sample_chunks[0], 1, n_alpha_1)\n assert_array_shape(YP, n_outcome, n_sample, n_variant_block, n_alpha_1)\n\n def apply(X: Array, YP: Array, BX: Array, BYP: Array) -> Array:\n # Collapse selected variant blocks and alphas into single\n # new covariate dimension\n assert YP.shape[2] == BYP.shape[2]\n n_group_covar = n_covar + BYP.shape[2] * n_alpha_1\n\n BYP = BYP.reshape((n_outcome, n_sample_block, -1))\n BG = da.concatenate((BX, BYP), axis=-1)\n BG = BG.rechunk((-1, None, -1))\n assert_block_shape(BG, 1, n_sample_block, 1)\n assert_chunk_shape(BG, n_outcome, 1, n_group_covar)\n assert_array_shape(BG, n_outcome, n_sample_block, n_group_covar)\n\n YP = YP.reshape((n_outcome, n_sample, -1))\n XYP = da.broadcast_to(X, (n_outcome, n_sample, n_covar))\n XG = da.concatenate((XYP, YP), axis=-1)\n XG = XG.rechunk((-1, None, -1))\n assert_block_shape(XG, 1, n_sample_block, 1)\n assert_chunk_shape(XG, n_outcome, sample_chunks[0], n_group_covar)\n assert_array_shape(XG, n_outcome, n_sample, n_group_covar)\n\n YG = da.map_blocks(\n # Block chunks:\n # (n_outcome, sample_chunks[0], n_group_covar) @\n # (n_outcome, n_group_covar, 1) [after transpose]\n lambda x, b: x @ b.transpose((0, 2, 1)),\n XG,\n BG,\n chunks=(n_outcome, sample_chunks, 1),\n )\n assert_block_shape(YG, 1, n_sample_block, 1)\n assert_chunk_shape(YG, n_outcome, sample_chunks[0], 1)\n assert_array_shape(YG, n_outcome, n_sample, 1)\n YG = da.squeeze(YG, axis=-1).T\n assert_block_shape(YG, n_sample_block, 1)\n assert_chunk_shape(YG, sample_chunks[0], n_outcome)\n assert_array_shape(YG, n_sample, n_outcome)\n return YG\n\n # For each contig, generate predictions for all sample+outcome\n # combinations using only betas from stage 2 results that\n # correspond to *other* contigs (i.e. LOCO)\n YC = []\n for contig in unique_contigs:\n # Define a variant block mask of size `n_variant_block`\n # determining which blocks correspond to this contig\n variant_block_mask = variant_block_contigs == contig\n BYPC = BYP[:, :, ~variant_block_mask, :]\n YPC = YP[:, :, ~variant_block_mask, :]\n YGC = apply(X, YPC, BX, BYPC)\n YC.append(YGC)\n YC = da.stack(YC, axis=0)\n assert_array_shape(YC, n_contig, n_sample, n_outcome)\n\n return YC\n\n\ndef _variant_block_indexes(\n variant_block_size: Union[int, Tuple[int, ...]], contigs: ArrayLike\n) -> Tuple[ndarray, ndarray]:\n if isinstance(variant_block_size, tuple):\n return index_block_sizes(variant_block_size)\n elif isinstance(variant_block_size, int):\n return index_array_blocks(contigs, variant_block_size)\n else:\n raise ValueError(\n f\"Variant block size type {type(variant_block_size)} \"\n \"must be tuple or int\"\n )\n\n\nDESC_BASE_PRED = \"\"\"Predictions from base ridge regressors for every variant block, alpha, sample and outcome\"\"\"\nDESC_META_PRED = (\n \"\"\"Predictions from best meta ridge model selected through CV over sample blocks\"\"\"\n)\nDESC_LOCO_PRED = \"\"\"Predictions from best meta ridge model omitting coefficients for variant blocks within individual contigs (LOCO approximation)\"\"\"\n\n\ndef regenie_transform(\n G: ArrayLike,\n X: ArrayLike,\n Y: ArrayLike,\n contigs: ArrayLike,\n *,\n variant_block_size: Optional[Union[int, Tuple[int, ...]]] = None,\n sample_block_size: Optional[Union[int, Tuple[int, ...]]] = None,\n alphas: Optional[ArrayLike] = None,\n add_intercept: bool = True,\n orthogonalize: bool = False,\n normalize: bool = False,\n _glow_adj_dof: bool = False,\n _glow_adj_alpha: bool = False,\n _glow_adj_scaling: bool = False,\n) -> Dataset:\n \"\"\"Regenie trait transformation.\n\n Parameters\n ----------\n G\n [array-like, shape: (M, N)]\n Genotype data array, `M` samples by `N` variants.\n X\n [array-like, shape: (M, C)]\n Covariate array, `M` samples by `C` covariates.\n Y\n [array-like, shape: (M, O)]\n Outcome array, `M` samples by `O` outcomes.\n contigs\n [array-like, shape: (N,)]\n Variant contigs as monotonic increasting integer contig index.\n\n See the `regenie` function for documentation on remaining fields.\n\n Returns\n -------\n A dataset containing the following variables:\n\n - `base_prediction` (blocks, alphas, samples, outcomes): Stage 1\n predictions from ridge regression reduction .\n - `meta_prediction` (samples, outcomes): Stage 2 predictions from\n the best meta estimator trained on the out-of-sample Stage 1\n predictions.\n - `loco_prediction` (contigs, samples, outcomes): LOCO predictions\n resulting from Stage 2 predictions ignoring effects for variant\n blocks on held out contigs. This will be absent if the\n data provided does not contain at least 2 contigs.\n\n Raises\n ------\n ValueError\n If `G`, `X`, and `Y` do not have the same size along\n the first (samples) dimension.\n \"\"\"\n if not G.shape[0] == X.shape[0] == Y.shape[0]:\n raise ValueError(\n \"All data arrays must have same size along first (samples) dimension \"\n f\"(shapes provided: G={G.shape}, X={X.shape}, Y={Y.shape})\"\n )\n n_sample = Y.shape[0]\n n_variant = G.shape[1]\n\n if alphas is not None:\n alphas = np.asarray(alphas)\n\n G, X, Y = da.asarray(G), da.asarray(X), da.asarray(Y)\n contigs = da.asarray(contigs)\n\n # Set default block sizes if not provided\n if variant_block_size is None:\n # Block in groups of 1000, unless dataset is small\n # enough to default to 2 blocks (typically for tests)\n variant_block_size = min(1000, n_variant // 2)\n if sample_block_size is None:\n # Break into 10 chunks of approximately equal size\n sample_block_size = tuple(split_array_chunks(n_sample, min(10, n_sample)))\n assert sum(sample_block_size) == n_sample\n\n if normalize:\n # See: https://github.com/projectglow/glow/issues/255\n dof = 1 if _glow_adj_dof else 0\n G = (G - G.mean(axis=0)) / G.std(axis=0, ddof=dof)\n Y = (Y - Y.mean(axis=0)) / Y.std(axis=0)\n X = (X - X.mean(axis=0)) / X.std(axis=0)\n\n if add_intercept:\n X = da.concatenate([da.ones((X.shape[0], 1), dtype=X.dtype), X], axis=1)\n\n # TODO: Test this after finding out whether or not there was a good reason\n # it was precluded in glow by unit covariate regularization:\n # https://github.com/projectglow/glow/issues/266\n if orthogonalize: # pragma: no cover\n G = G - X @ da.linalg.lstsq(X, G)[0]\n Y = Y - X @ da.linalg.lstsq(X, Y)[0]\n G = G / G.std(axis=0)\n Y = Y / Y.std(axis=0)\n X = da.zeros(shape=(n_sample, 0), dtype=G.dtype)\n\n variant_chunk_start, variant_chunk_size = _variant_block_indexes(\n variant_block_size, contigs\n )\n G = G.rechunk(chunks=(sample_block_size, tuple(variant_chunk_size)))\n X = X.rechunk(chunks=(sample_block_size, -1))\n Y = Y.rechunk(chunks=(sample_block_size, -1))\n\n YP1 = _stage_1(G, X, Y, alphas=alphas)\n B2, YP2 = _stage_2(\n YP1,\n X,\n Y,\n alphas=alphas,\n _glow_adj_alpha=_glow_adj_alpha,\n _glow_adj_scaling=_glow_adj_scaling,\n )\n YP3 = _stage_3(B2, YP1, X, Y, contigs, variant_chunk_start)\n\n data_vars: Dict[Hashable, Any] = {}\n data_vars[variables.base_prediction] = xr.DataArray(\n YP1,\n dims=(\"blocks\", \"alphas\", \"samples\", \"outcomes\"),\n attrs={\"description\": DESC_BASE_PRED},\n )\n data_vars[variables.meta_prediction] = xr.DataArray(\n YP2, dims=(\"samples\", \"outcomes\"), attrs={\"description\": DESC_META_PRED}\n )\n if YP3 is not None:\n data_vars[variables.loco_prediction] = xr.DataArray(\n YP3,\n dims=(\"contigs\", \"samples\", \"outcomes\"),\n attrs={\"description\": DESC_LOCO_PRED},\n )\n return create_dataset(data_vars)\n\n\ndef regenie(\n ds: Dataset,\n *,\n dosage: str,\n covariates: Union[Hashable, Sequence[Hashable]],\n traits: Union[Hashable, Sequence[Hashable]],\n variant_contig: Hashable = variables.variant_contig,\n variant_block_size: Optional[Union[int, Tuple[int, ...]]] = None,\n sample_block_size: Optional[Union[int, Tuple[int, ...]]] = None,\n alphas: Optional[Sequence[float]] = None,\n add_intercept: bool = True,\n normalize: bool = False,\n orthogonalize: bool = False,\n merge: bool = True,\n **kwargs: Any,\n) -> Dataset:\n \"\"\"Regenie trait transformation.\n\n `REGENIE <https://github.com/rgcgithub/regenie>`_ is a whole-genome\n regression technique that produces trait estimates for association\n tests. These estimates are subtracted from trait values and\n sampling statistics (p-values, standard errors, etc.) are evaluated\n against the residuals. See the REGENIE preprint [1] for more details.\n For a simpler technical overview, see [2] for a detailed description\n of the individual stages and separate regression models involved.\n\n Parameters\n ----------\n dosage\n Name of genetic dosage variable.\n Defined by :data:`sgkit.variables.dosage_spec`.\n covariates\n Names of covariate variables (1D or 2D).\n Defined by :data:`sgkit.variables.covariates_spec`.\n traits\n Names of trait variables (1D or 2D).\n Defined by :data:`sgkit.variables.traits_spec`.\n variant_contig\n Name of the variant contig input variable.\n Definied by :data:`sgkit.variables.variant_contig_spec`.\n variant_block_size\n Number of variants in each block.\n If int, this describes the number of variants in each block\n but the last which may be smaller.\n If Tuple[int, ...], this must describe the desired number of\n variants in each block individually.\n Defaults to 1000 or num variants // 2, whichever is smaller.\n sample_block_size\n Number of samples in each block.\n If int, this describes the number of samples in each block\n but the last which may be smaller.\n If Tuple[int, ...], this must describe the desired number of\n samples in each block individually.\n Defaults to 10 sample blocks split roughly across all possible\n samples or the number of samples, if that number is < 10.\n alphas\n List of alpha values to use for regularization, by default None.\n If not provided, these will be set automatically based on\n datasize and apriori heritability assumptions.\n add_intercept\n Whether or not to add intercept to covariates, by default True.\n normalize\n Rescale genotypes, traits, and covariates to have\n mean 0 and stdev 1, by default False.\n orthogonalize\n **Experimental**: Remove covariates through orthogonalization\n of genotypes and traits, by default False.\n merge\n If True (the default), merge the input dataset and the computed\n output variables into a single dataset, otherwise return only\n the computed output variables.\n See :ref:`dataset_merge` for more details.\n\n Warnings\n --------\n Binary traits are not yet supported so all outcomes provided\n must be continuous.\n\n Returns\n -------\n A dataset containing the following variables:\n\n - `base_prediction` (blocks, alphas, samples, outcomes): Stage 1\n predictions from ridge regression reduction. Defined by\n :data:`sgkit.variables.base_prediction_spec`.\n\n - `meta_prediction` (samples, outcomes): Stage 2 predictions from\n the best meta estimator trained on the out-of-sample Stage 1\n predictions. Defined by :data:`sgkit.variables.meta_prediction_spec`.\n\n - `loco_prediction` (contigs, samples, outcomes): LOCO predictions\n resulting from Stage 2 predictions ignoring effects for variant\n blocks on held out contigs. This will be absent if the\n data provided does not contain at least 2 contigs. Defined by\n :data:`sgkit.variables.loco_prediction_spec`.\n\n Raises\n ------\n ValueError\n If dosage, covariates, and trait arrays do not have the same number\n of samples.\n\n Examples\n --------\n\n >>> import numpy as np\n >>> from sgkit.testing import simulate_genotype_call_dataset\n >>> from sgkit.stats.regenie import regenie\n >>> n_variant, n_sample, n_contig, n_covariate, n_trait, seed = 100, 50, 2, 3, 5, 0\n >>> rs = np.random.RandomState(seed)\n >>> ds = simulate_genotype_call_dataset(n_variant=n_variant, n_sample=n_sample, n_contig=n_contig, seed=seed)\n >>> ds[\"call_dosage\"] = ((\"variants\", \"samples\"), rs.normal(size=(n_variant, n_sample)))\n >>> ds[\"sample_covariate\"] = ((\"samples\", \"covariates\"), rs.normal(size=(n_sample, n_covariate)))\n >>> ds[\"sample_trait\"] = ((\"samples\", \"traits\"), rs.normal(size=(n_sample, n_trait)))\n >>> res = regenie(ds, dosage=\"call_dosage\", covariates=\"sample_covariate\", traits=\"sample_trait\", merge=False)\n >>> res.compute() # doctest: +NORMALIZE_WHITESPACE\n <xarray.Dataset>\n Dimensions: (alphas: 5, blocks: 2, contigs: 2, outcomes: 5, samples: 50)\n Dimensions without coordinates: alphas, blocks, contigs, outcomes, samples\n Data variables:\n base_prediction (blocks, alphas, samples, outcomes) float64 0.3343 ... -...\n meta_prediction (samples, outcomes) float64 -0.4588 0.78 ... -0.3984 0.3734\n loco_prediction (contigs, samples, outcomes) float64 0.4886 ... -0.01498\n\n References\n ----------\n [1] - Mbatchou, J., L. Barnard, J. Backman, and A. Marcketta. 2020.\n “Computationally Efficient Whole Genome Regression for Quantitative and Binary\n Traits.” bioRxiv. https://www.biorxiv.org/content/10.1101/2020.06.19.162354v2.abstract.\n\n [2] - https://glow.readthedocs.io/en/latest/tertiary/whole-genome-regression.html\n \"\"\"\n if isinstance(covariates, Hashable):\n covariates = [covariates]\n if isinstance(traits, Hashable):\n traits = [traits]\n\n variables.validate(\n ds,\n {dosage: variables.dosage_spec, variant_contig: variables.variant_contig_spec},\n {c: variables.covariates_spec for c in covariates},\n {t: variables.traits_spec for t in traits},\n )\n\n G = ds[dosage]\n X = da.asarray(concat_2d(ds[list(covariates)], dims=(\"samples\", \"covariates\")))\n Y = da.asarray(concat_2d(ds[list(traits)], dims=(\"samples\", \"traits\")))\n contigs = ds[variant_contig]\n new_ds = regenie_transform(\n G.T,\n X,\n Y,\n contigs,\n variant_block_size=variant_block_size,\n sample_block_size=sample_block_size,\n alphas=alphas,\n add_intercept=add_intercept,\n normalize=normalize,\n orthogonalize=orthogonalize,\n **kwargs,\n )\n return conditional_merge_datasets(ds, new_ds, merge)\n",
"import numpy as np\nimport pytest\nimport xarray as xr\n\nfrom sgkit import variables\nfrom sgkit.variables import ArrayLikeSpec, SgkitVariables\n\n\ndef test_variables__variables_registered():\n assert len(SgkitVariables.registered_variables) > 0\n assert all(\n isinstance(x, ArrayLikeSpec)\n for x in SgkitVariables.registered_variables.values()\n )\n\n\[email protected]()\ndef dummy_ds():\n # foo is a data variable, bar is a coordinate\n return xr.Dataset(\n {\n \"foo\": (\"d1\", np.asarray([1, 2, 3])),\n \"bar\": np.asarray([1, 2, 3]),\n }\n )\n\n\ndef test_variables__no_spec(dummy_ds: xr.Dataset) -> None:\n with pytest.raises(ValueError, match=\"No array spec registered for foo\"):\n variables.validate(dummy_ds, \"foo\")\n variables.validate(dummy_ds, \"bar\") # no spec needed for coordinates or indexes\n\n\ndef test_variables__validate_by_name(dummy_ds: xr.Dataset) -> None:\n spec = ArrayLikeSpec(\"foo\", kind=\"i\", ndim=1)\n try:\n assert \"foo\" not in SgkitVariables.registered_variables\n name, spec_b = SgkitVariables.register_variable(spec)\n assert \"foo\" in SgkitVariables.registered_variables\n assert name == \"foo\"\n assert spec_b == spec\n variables.validate(dummy_ds, \"foo\")\n finally:\n SgkitVariables.registered_variables.pop(\"foo\", None)\n assert \"foo\" not in SgkitVariables.registered_variables\n\n\ndef test_variables__validate_by_dummy_spec(dummy_ds: xr.Dataset) -> None:\n spec = ArrayLikeSpec(\"foo\", kind=\"i\", ndim=1)\n variables.validate(dummy_ds, spec)\n\n\ndef test_variables__invalid_spec_fails(dummy_ds: xr.Dataset) -> None:\n invalid_spec = ArrayLikeSpec(\"foo\", kind=\"i\", ndim=2)\n with pytest.raises(ValueError, match=\"foo does not match the spec\"):\n variables.validate(dummy_ds, invalid_spec)\n\n\ndef test_variables__alternative_names(dummy_ds: xr.Dataset) -> None:\n spec = ArrayLikeSpec(\"baz\", kind=\"i\", ndim=1)\n variables.validate(dummy_ds, {\"foo\": spec, \"bar\": spec})\n\n\ndef test_variables__no_present_in_ds(dummy_ds: xr.Dataset) -> None:\n spec = ArrayLikeSpec(\"baz\", kind=\"i\", ndim=1)\n with pytest.raises(ValueError, match=\"foobarbaz not present in\"):\n variables.validate(dummy_ds, {\"foobarbaz\": spec})\n\n\ndef test_variables__multiple_specs(dummy_ds: xr.Dataset) -> None:\n spec = ArrayLikeSpec(\"baz\", kind=\"i\", ndim=1)\n invalid_spec = ArrayLikeSpec(\"baz\", kind=\"i\", ndim=2)\n variables.validate(dummy_ds, {\"foo\": spec, \"bar\": spec})\n variables.validate(dummy_ds, {\"foo\": spec})\n variables.validate(dummy_ds, {\"bar\": spec})\n with pytest.raises(ValueError, match=\"bar does not match the spec\"):\n variables.validate(dummy_ds, {\"bar\": invalid_spec})\n with pytest.raises(ValueError, match=\"bar does not match the spec\"):\n variables.validate(dummy_ds, {\"foo\": spec}, {\"bar\": invalid_spec})\n\n\ndef test_variables__whole_ds(dummy_ds: xr.Dataset) -> None:\n spec_foo = ArrayLikeSpec(\"foo\", kind=\"i\", ndim=1)\n spec_bar = ArrayLikeSpec(\"bar\", kind=\"i\", ndim=1)\n try:\n SgkitVariables.register_variable(spec_foo)\n with pytest.raises(ValueError, match=\"`foo` already registered\"):\n SgkitVariables.register_variable(spec_foo)\n SgkitVariables.register_variable(spec_bar)\n variables.validate(dummy_ds)\n finally:\n SgkitVariables.registered_variables.pop(\"foo\", None)\n SgkitVariables.registered_variables.pop(\"bar\", None)\n\n\ndef test_variables_in_multi_index(dummy_ds: xr.Dataset) -> None:\n # create a multi index\n ds = dummy_ds.set_index({\"ind\": (\"foo\", \"bar\")})\n\n spec = ArrayLikeSpec(\"foo\", kind=\"i\", ndim=1)\n variables.validate(ds, spec)\n",
"\"\"\"\nThis module implements various distance metrics. To implement a new distance\nmetric, two methods needs to be written, one of them suffixed by 'map' and other\nsuffixed by 'reduce'. An entry for the same should be added in the N_MAP_PARAM\ndictionary below.\n\"\"\"\n\nimport numpy as np\nfrom numba import guvectorize\n\nfrom sgkit.typing import ArrayLike\n\n# The number of parameters for the map step of the respective distance metric\nN_MAP_PARAM = {\n \"correlation\": 6,\n \"euclidean\": 1,\n}\n\n\n@guvectorize( # type: ignore\n [\n \"void(float32[:], float32[:], float32[:], float32[:])\",\n \"void(float64[:], float64[:], float64[:], float64[:])\",\n \"void(int8[:], int8[:], int8[:], float64[:])\",\n ],\n \"(n),(n),(p)->(p)\",\n nopython=True,\n cache=True,\n)\ndef euclidean_map(\n x: ArrayLike, y: ArrayLike, _: ArrayLike, out: ArrayLike\n) -> None: # pragma: no cover\n \"\"\"Euclidean distance \"map\" function for partial vector pairs.\n\n Parameters\n ----------\n x\n An array chunk, a partial vector\n y\n Another array chunk, a partial vector\n _\n A dummy variable to map the size of output\n out\n The output array, which has the squared sum of partial vector pairs.\n\n Returns\n -------\n An ndarray, which contains the output of the calculation of the application\n of euclidean distance on the given pair of chunks, without the aggregation.\n \"\"\"\n square_sum = 0.0\n m = x.shape[0]\n # Ignore missing values\n for i in range(m):\n if x[i] >= 0 and y[i] >= 0:\n square_sum += (x[i] - y[i]) ** 2\n out[:] = square_sum\n\n\ndef euclidean_reduce(v: ArrayLike) -> ArrayLike: # pragma: no cover\n \"\"\"Corresponding \"reduce\" function for euclidean distance.\n\n Parameters\n ----------\n v\n The euclidean array on which map step of euclidean distance has been\n applied.\n\n Returns\n -------\n An ndarray, which contains square root of the sum of the squared sums obtained from\n the map step of `euclidean_map`.\n \"\"\"\n out: ArrayLike = np.sqrt(np.einsum(\"ijkl -> ij\", v))\n return out\n\n\n@guvectorize( # type: ignore\n [\n \"void(float32[:], float32[:], float32[:], float32[:])\",\n \"void(float64[:], float64[:], float64[:], float64[:])\",\n \"void(int8[:], int8[:], int8[:], float64[:])\",\n ],\n \"(n),(n),(p)->(p)\",\n nopython=True,\n cache=True,\n)\ndef correlation_map(\n x: ArrayLike, y: ArrayLike, _: ArrayLike, out: ArrayLike\n) -> None: # pragma: no cover\n \"\"\"Pearson correlation \"map\" function for partial vector pairs.\n\n Parameters\n ----------\n x\n An array chunk, a partial vector\n y\n Another array chunk, a partial vector\n _\n A dummy variable to map the size of output\n out\n The output array, which has the output of pearson correlation.\n\n Returns\n -------\n An ndarray, which contains the output of the calculation of the application\n of pearson correlation on the given pair of chunks, without the aggregation.\n \"\"\"\n\n m = x.shape[0]\n valid_indices = np.zeros(m, dtype=np.float64)\n\n for i in range(m):\n if x[i] >= 0 and y[i] >= 0:\n valid_indices[i] = 1\n\n valid_shape = valid_indices.sum()\n _x = np.zeros(int(valid_shape), dtype=x.dtype)\n _y = np.zeros(int(valid_shape), dtype=y.dtype)\n\n # Ignore missing values\n valid_idx = 0\n for i in range(valid_indices.shape[0]):\n if valid_indices[i] > 0:\n _x[valid_idx] = x[i]\n _y[valid_idx] = y[i]\n valid_idx += 1\n\n out[:] = np.array(\n [\n np.sum(_x),\n np.sum(_y),\n np.sum(_x * _x),\n np.sum(_y * _y),\n np.sum(_x * _y),\n len(_x),\n ]\n )\n\n\n@guvectorize( # type: ignore\n [\n \"void(float32[:, :], float32[:])\",\n \"void(float64[:, :], float64[:])\",\n ],\n \"(p, m)->()\",\n nopython=True,\n cache=True,\n)\ndef correlation_reduce(v: ArrayLike, out: ArrayLike) -> None: # pragma: no cover\n \"\"\"Corresponding \"reduce\" function for pearson correlation\n Parameters\n ----------\n v\n The correlation array on which pearson corrections has been\n applied on chunks\n out\n An ndarray, which is a symmetric matrix of pearson correlation\n\n Returns\n -------\n An ndarray, which contains the result of the calculation of the application\n of euclidean distance on all the chunks.\n \"\"\"\n v = v.sum(axis=0)\n n = v[5]\n num = n * v[4] - v[0] * v[1]\n denom1 = np.sqrt(n * v[2] - v[0] ** 2)\n denom2 = np.sqrt(n * v[3] - v[1] ** 2)\n denom = denom1 * denom2\n value = np.nan\n if denom > 0:\n value = 1 - (num / denom)\n out[0] = value\n"
] | [
[
"numpy.isnan"
],
[
"numpy.isnan",
"numpy.argmax"
],
[
"numpy.diag",
"numpy.unique",
"numpy.asarray",
"numpy.linalg.inv",
"numpy.issubdtype",
"numpy.arange",
"numpy.cumsum",
"numpy.stack",
"numpy.ones",
"numpy.concatenate",
"numpy.diff",
"numpy.any",
"numpy.array",
"numpy.empty"
],
[
"numpy.asarray"
],
[
"numpy.sum",
"numpy.zeros",
"numpy.sqrt",
"numpy.einsum"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
fperez/nipy | [
"559f17150bd9fa8ead4fd088b330d7cf7db7aa79",
"559f17150bd9fa8ead4fd088b330d7cf7db7aa79",
"559f17150bd9fa8ead4fd088b330d7cf7db7aa79"
] | [
"nipy/io/tests/test_save.py",
"nipy/io/imageformats/nifti1.py",
"nipy/io/imageformats/tests/test_nifti1.py"
] | [
"# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-\n# vi: set ft=python sts=4 ts=4 sw=4 et:\nimport os\nfrom tempfile import mkstemp\nimport numpy as np\n\nfrom nipy.testing import assert_true, assert_false, assert_equal, \\\n assert_array_almost_equal, funcfile\n\n\nfrom nipy.io.api import load_image, save_image\nfrom nipy.core import api\n\nclass Tempfile():\n file = None\n\ntmpfile = Tempfile()\n\ndef setup():\n fd, tmpfile.name = mkstemp(suffix='.nii')\n tmpfile.file = open(tmpfile.name)\n\ndef teardown():\n tmpfile.file.close()\n os.unlink(tmpfile.name)\n\n\ndef test_save1():\n # A test to ensure that when a file is saved, the affine and the\n # data agree. This image comes from a NIFTI file\n\n img = load_image(funcfile)\n save_image(img, tmpfile.name)\n img2 = load_image(tmpfile.name)\n yield assert_true, np.allclose(img.affine, img2.affine)\n yield assert_equal, img.shape, img2.shape\n yield assert_true, np.allclose(np.asarray(img2), np.asarray(img))\n\n\ndef test_save2():\n # A test to ensure that when a file is saved, the affine and the\n # data agree. This image comes from a NIFTI file \n\n shape = (13,5,7,3)\n step = np.array([3.45,2.3,4.5,6.93])\n\n cmap = api.AffineTransform.from_start_step('ijkt', 'xyzt', [1,3,5,0], step)\n\n data = np.random.standard_normal(shape)\n img = api.Image(data, cmap)\n save_image(img, tmpfile.name)\n img2 = load_image(tmpfile.name)\n yield assert_true, np.allclose(img.affine, img2.affine)\n yield assert_equal, img.shape, img2.shape\n yield assert_true, np.allclose(np.asarray(img2), np.asarray(img))\n\n\ndef test_save2b():\n # A test to ensure that when a file is saved, the affine and the\n # data agree. This image comes from a NIFTI file This example has\n # a non-diagonal affine matrix for the spatial part, but is\n # 'diagonal' for the space part. this should raise a warnings\n # about 'non-diagonal' affine matrix\n\n # make a 5x5 transformatio\n step = np.array([3.45,2.3,4.5,6.9])\n A = np.random.standard_normal((4,4))\n B = np.diag(list(step)+[1])\n B[:4,:4] = A\n\n shape = (13,5,7,3)\n cmap = api.AffineTransform.from_params('ijkt', 'xyzt', B)\n\n data = np.random.standard_normal(shape)\n\n img = api.Image(data, cmap)\n\n save_image(img, tmpfile.name)\n img2 = load_image(tmpfile.name)\n yield assert_false, np.allclose(img.affine, img2.affine)\n yield assert_true, np.allclose(img.affine[:3,:3], img2.affine[:3,:3])\n yield assert_equal, img.shape, img2.shape\n yield assert_true, np.allclose(np.asarray(img2), np.asarray(img))\n\n# JT: nifti_ref doesn't reorder axes anymore so these tests\n# are no longer expected to work\n#\n# def test_save3():\n# # A test to ensure that when a file is saved, the affine\n# # and the data agree. In this case, things don't agree:\n# # i) the pixdim is off\n# # ii) makes the affine off\n\n# step = np.array([3.45,2.3,4.5,6.9])\n# shape = (13,5,7,3)\n# cmap = api.AffineTransform.from_start_step('jkli', 'tzyx', [0,3,5,1], step)\n\n# data = np.random.standard_normal(shape)\n# img = api.Image(data, cmap)\n# save_image(img, tmpfile.name)\n# img2 = load_image(tmpfile.name)\n\n# yield assert_equal, tuple([img.shape[l] for l in [3,0,1,2]]), img2.shape\n# a = np.transpose(np.asarray(img), [3,0,1,2])\n# yield assert_false, np.allclose(img.affine, img2.affine)\n# yield assert_true, np.allclose(a, np.asarray(img2))\n\n\n# def test_save4():\n# # Same as test_save3 except we have reordered the 'ijk' input axes.\n# shape = (13,5,7,3)\n# step = np.array([3.45,2.3,4.5,6.9])\n# # When the input coords are in the 'ljki' order, the affines get\n# # rearranged. Note that the 'start' below, must be 0 for\n# # non-spatial dimensions, because we have no way to store them in\n# # most cases. For example, a 'start' of [1,5,3,1] would be lost on\n# # reload\n# cmap = api.AffineTransform.from_start_step('lkji', 'tzyx', [2,5,3,1], step)\n# data = np.random.standard_normal(shape)\n# img = api.Image(data, cmap)\n# save_image(img, tmpfile.name)\n# img2 = load_image(tmpfile.name)\n# P = np.array([[0,0,0,1,0],\n# [0,0,1,0,0],\n# [0,1,0,0,0],\n# [1,0,0,0,0],\n# [0,0,0,0,1]])\n# res = np.dot(P, np.dot(img.affine, P.T))\n\n# # the step part of the affine should be set correctly\n# yield assert_array_almost_equal, res[:4,:4], img2.affine[:4,:4]\n\n# # start in the spatial dimensions should be set correctly\n# yield assert_array_almost_equal, res[:3,-1], img2.affine[:3,-1]\n\n# # start in the time dimension should not be 2 as in img, but 0\n# # because NIFTI dosen't have a time start\n\n# yield assert_false, (res[3,-1] == img2.affine[3,-1])\n# yield assert_true, (res[3,-1] == 2)\n# yield assert_true, (img2.affine[3,-1] == 0)\n\n# # shapes should be reversed because img has coordinates reversed\n\n\n# yield assert_equal, img.shape[::-1], img2.shape\n\n# # data should be transposed because coordinates are reversed\n\n# yield (assert_array_almost_equal, \n# np.transpose(np.asarray(img2),[3,2,1,0]),\n# np.asarray(img))\n\n# # coordinate names should be reversed as well\n\n# yield assert_equal, img2.coordmap.function_domain.coord_names, \\\n# img.coordmap.function_domain.coord_names[::-1]\n# yield assert_equal, img2.coordmap.function_domain.coord_names, \\\n# ['i', 'j', 'k', 'l']\n",
"# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-\n# vi: set ft=python sts=4 ts=4 sw=4 et:\n''' Header reading / writing functions for nifti1 image format\n\nAuthor: Matthew Brett\n'''\n\nimport numpy as np\nimport numpy.linalg as npl\n\nfrom nipy.io.imageformats.volumeutils import Recoder, make_dt_codes, \\\n HeaderDataError, HeaderTypeError, allopen\nfrom nipy.io.imageformats.batteryrunners import Report\nfrom nipy.io.imageformats.quaternions import fillpositive, quat2mat, mat2quat\nfrom nipy.io.imageformats import analyze # module import\nfrom nipy.io.imageformats.spm99analyze import SpmAnalyzeHeader\nfrom nipy.io.imageformats import filetuples # module import\nfrom nipy.io.imageformats.spatialimages import SpatialImage\n\nfrom nipy.io.imageformats.header_ufuncs import write_data, adapt_header\n\n# nifti1 flat header definition for Analyze-like first 348 bytes\n# first number in comments indicates offset in file header in bytes\nheader_dtd = [\n ('sizeof_hdr', 'i4'), # 0; must be 348\n ('data_type', 'S10'), # 4; unused\n ('db_name', 'S18'), # 14; unused\n ('extents', 'i4'), # 32; unused\n ('session_error', 'i2'), # 36; unused\n ('regular', 'S1'), # 38; unused\n ('dim_info', 'u1'), # 39; MRI slice ordering code\n ('dim', 'i2', 8), # 40; data array dimensions\n ('intent_p1', 'f4'), # 56; first intent parameter\n ('intent_p2', 'f4'), # 60; second intent parameter\n ('intent_p3', 'f4'), # 64; third intent parameter\n ('intent_code', 'i2'),# 68; NIFTI intent code\n ('datatype', 'i2'), # 70; it's the datatype\n ('bitpix', 'i2'), # 72; number of bits per voxel\n ('slice_start', 'i2'),# 74; first slice index \n ('pixdim', 'f4', 8), # 76; grid spacings (units below)\n ('vox_offset', 'f4'), # 108; offset to data in image file\n ('scl_slope', 'f4'), # 112; data scaling slope\n ('scl_inter', 'f4'), # 116; data scaling intercept\n ('slice_end', 'i2'), # 120; last slice index\n ('slice_code', 'u1'), # 122; slice timing order\n ('xyzt_units', 'u1'), # 123; inits of pixdim[1..4]\n ('cal_max', 'f4'), # 124; max display intensity\n ('cal_min', 'f4'), # 128; min display intensity\n ('slice_duration', 'f4'), # 132; time for 1 slice\n ('toffset', 'f4'), # 136; time axis shift\n ('glmax', 'i4'), # 140; unused\n ('glmin', 'i4'), # 144; unused\n ('descrip', 'S80'), # 148; any text\n ('aux_file', 'S24'), # 228; auxiliary filename\n ('qform_code', 'i2'), # 252; xform code\n ('sform_code', 'i2'), # 254; xform code\n ('quatern_b', 'f4'), # 256; quaternion b param\n ('quatern_c', 'f4'), # 260; quaternion c param\n ('quatern_d', 'f4'), # 264; quaternion d param\n ('qoffset_x', 'f4'), # 268; quaternion x shift\n ('qoffset_y', 'f4'), # 272; quaternion y shift\n ('qoffset_z', 'f4'), # 276; quaternion z shift\n ('srow_x', 'f4', 4), # 280; 1st row affine transform\n ('srow_y', 'f4', 4), # 296; 2nd row affine transform\n ('srow_z', 'f4', 4), # 312; 3rd row affine transform\n ('intent_name', 'S16'), # 328; name or meaning of data\n ('magic', 'S4') # 344; must be 'ni1\\0' or 'n+1\\0'\n ]\n\n# Full header numpy dtype\nheader_dtype = np.dtype(header_dtd)\n\n# datatypes not in analyze format, with codes\ntry:\n _float128t = np.float128\nexcept AttributeError:\n _float128t = np.void\ntry:\n _complex256t = np.complex256\nexcept AttributeError:\n _complex256t = np.void\n_added_dtdefs = ( # code, label, dtype definition\n (256, 'int8', np.int8),\n (512, 'uint16', np.uint16),\n (768, 'uint32', np.uint32),\n (1024,'int64', np.int64),\n (1280, 'uint64', np.uint64),\n (1536, 'float128', _float128t), # Only numpy defined on 64 bit\n (1792, 'complex128', np.complex128),\n (2048, 'complex256', _complex256t), # 64 bit again\n (2304, 'RGBA', np.dtype([('R','u1'),\n ('G', 'u1'),\n ('B', 'u1'),\n ('A', 'u1')]))\n )\n\n# Make full code alias bank, including dtype column\ndata_type_codes = make_dt_codes(analyze._dtdefs + _added_dtdefs)\n\n# Transform (qform, sform) codes\nxform_codes = Recoder(( # code, label\n (0, 'unknown'), # Code for transform unknown or absent\n (1, 'scanner'),\n (2, 'aligned'),\n (3, 'talairach'),\n (4, 'mni')), fields=('code', 'label'))\n\n# unit codes\nunit_codes = Recoder(( # code, label\n (0, 'unknown'), \n (1, 'meter'),\n (2, 'mm'),\n (3, 'micron'),\n (8, 'sec'),\n (16, 'msec'),\n (24, 'usec'),\n (32, 'hz'),\n (40, 'ppm'),\n (48, 'rads')), fields=('code', 'label'))\n\nslice_order_codes = Recoder(( # code, label\n (0, 'unknown'),\n (1, 'sequential increasing', 'seq inc'),\n (2, 'sequential decreasing', 'seq dec'),\n (3, 'alternating increasing', 'alt inc'),\n (4, 'alternating decreasing', 'alt dec'),\n (5, 'alternating increasing 2', 'alt inc 2'),\n (6, 'alternating decreasing 2', 'alt dec 2')),\n fields=('code', 'label'))\n\nintent_codes = Recoder((\n # code, label, parameters description tuple\n (0, 'none', ()),\n (2, 'correlation',('p1 = DOF',)),\n (3, 't test', ('p1 = DOF',)),\n (4, 'f test', ('p1 = numerator DOF', 'p2 = denominator DOF')),\n (5, 'z score', ()),\n (6, 'chi2', ('p1 = DOF',)),\n (7, 'beta', ('p1=a', 'p2=b')), # two parameter beta distribution\n (8, 'binomial', ('p1 = number of trials', 'p2 = probability per trial')),\n # Prob(x) = (p1 choose x) * p2^x * (1-p2)^(p1-x), for x=0,1,...,p1\n (9, 'gamma', ('p1 = shape, p2 = scale', 2)), # 2 parameter gamma\n (10, 'poisson', ('p1 = mean',)), # Density(x) proportional to x^(p1-1) * exp(-p2*x)\n (11, 'normal', ('p1 = mean', 'p2 = standard deviation',)),\n (12, 'non central f test', ('p1 = numerator DOF',\n 'p2 = denominator DOF',\n 'p3 = numerator noncentrality parameter',)),\n (13, 'non central chi2', ('p1 = DOF', 'p2 = noncentrality parameter',)),\n (14, 'logistic', ('p1 = location', 'p2 = scale',)),\n (15, 'laplace', ('p1 = location', 'p2 = scale')),\n (16, 'uniform', ('p1 = lower end', 'p2 = upper end')),\n (17, 'non central t test', ('p1 = DOF', 'p2 = noncentrality parameter')),\n (18, 'weibull', ('p1 = location', 'p2 = scale, p3 = power')),\n (19, 'chi', ('p1 = DOF',)),\n # p1 = 1 = 'half normal' distribution\n # p1 = 2 = Rayleigh distribution\n # p1 = 3 = Maxwell-Boltzmann distribution. */\n (20, 'inverse gaussian', ('pi = mu', 'p2 = lambda')),\n (21, 'extreme value 1', ('p1 = location', 'p2 = scale')),\n (22, 'p value', ()),\n (23, 'log p value', ()),\n (24, 'log10 p value', ()),\n (1001, 'estimate', ()),\n (1002, 'label', ()),\n (1003, 'neuroname', ()),\n (1004, 'general matrix', ('p1 = M', 'p2 = N')),\n (1005, 'symmetric matrix', ('p1 = M',)),\n (1006, 'displacement vector', ()),\n (1007, 'vector', ()),\n (1008, 'poinset', ()),\n (1009, 'triangle', ()),\n (1010, 'quaternion', ()),\n (1011, 'dimensionless', ()),\n (2001, 'time series', ()),\n (2002, 'node index', ()),\n (2003, 'rgb vector', ()),\n (2004, 'rgba vector', ()),\n (2005, 'shape', ())),\n fields=('code', 'label', 'parameters'))\n\n\nclass Nifti1Extension(object):\n \"\"\"Baseclass for NIfTI1 header extensions.\n\n This class is sufficient to handle very simple text-based extensions, such\n as `comment`. More sophisticated extensions should/will be supported by\n dedicated subclasses.\n \"\"\"\n def __init__(self, code, content):\n \"\"\"\n Parameters\n ----------\n code : int|str\n Canonical extension code as defined in the NIfTI standard, given\n either as integer or corresponding label\n (see :data:`~nifti.nifti1.extension_codes`)\n content : str\n Extension content as read from the NIfTI file header. This content is\n converted into a runtime representation.\n \"\"\"\n try:\n self._code = extension_codes.code[code]\n except KeyError:\n # XXX or fail or at least complain?\n self._code = code\n self._content = self._unmangle(content)\n\n def _unmangle(self, value):\n \"\"\"Convert the extension content into its runtime representation.\n\n The default implementation does nothing at all.\n\n Parameters\n ----------\n value : str\n Extension content as read from file.\n\n Returns\n -------\n The same object that was passed as `value`.\n\n Notes\n -----\n Subclasses should reimplement this method to provide the desired\n unmangling procedure and may return any type of object.\n \"\"\"\n return value\n\n def _mangle(self, value):\n \"\"\"Convert the extension content into NIfTI file header representation.\n\n The default implementation does nothing at all.\n\n Parameters\n ----------\n value : str\n Extension content in runtime form.\n\n Returns\n -------\n str\n\n Notes\n -----\n Subclasses should reimplement this method to provide the desired\n mangling procedure.\n \"\"\"\n return value\n\n def get_code(self):\n \"\"\"Return the canonical extension type code.\"\"\"\n return self._code\n\n def get_content(self):\n \"\"\"Return the extension content in its runtime representation.\"\"\"\n return self._content\n\n def get_sizeondisk(self):\n \"\"\"Return the size of the extension in the NIfTI file.\n \"\"\"\n # need raw value size plus 8 bytes for esize and ecode\n size = len(self._mangle(self._content))\n size += 8\n # extensions size has to be a multiple of 16 bytes\n size += 16 - (size % 16)\n return size\n\n def __repr__(self):\n try:\n code = extension_codes.label[self._code]\n except KeyError:\n # deal with unknown codes\n code = self._code\n\n s = \"Nifti1Extension('%s', '%s')\" % (code, self._content)\n return s\n\n def __eq__(self, other):\n if self._code != other._code \\\n or self._content != other._content:\n return False\n else:\n return True\n\n def write_to(self, fileobj):\n ''' Write header extensions to fileobj\n\n Write starts at fileobj current file position.\n\n Parameters\n ----------\n fileobj : file-like object\n Should implement ``write`` method\n\n Returns\n -------\n None\n '''\n extstart = fileobj.tell()\n rawsize = self.get_sizeondisk()\n # write esize and ecode first\n fileobj.write(np.array((rawsize, self._code),\n dtype=np.int32).tostring())\n # followed by the actual extension content\n # XXX if mangling upon load is implemented, it should be reverted here\n fileobj.write(self._mangle(self._content))\n # be nice and zero out remaining part of the extension till the\n # next 16 byte border\n fileobj.write('\\x00' * (extstart + rawsize - fileobj.tell()))\n\n\n# NIfTI header extension type codes (ECODE)\n# see nifti1_io.h for a complete list of all known extensions and\n# references to their description or contacts of the respective\n# initiators\nextension_codes = Recoder((\n (0, \"ignore\", Nifti1Extension),\n (2, \"dicom\", Nifti1Extension),\n (4, \"afni\", Nifti1Extension),\n (6, \"comment\", Nifti1Extension),\n (8, \"xcede\", Nifti1Extension),\n (10, \"jimdiminfo\", Nifti1Extension),\n (12, \"workflow_fwds\", Nifti1Extension),\n (14, \"freesurfer\", Nifti1Extension),\n (16, \"pypickle\", Nifti1Extension)\n ),\n fields=('code', 'label', 'handler'))\n\n\nclass Nifti1Extensions(list):\n \"\"\"Simple extension collection, implemented as a list-subclass.\n \"\"\"\n def count(self, ecode):\n \"\"\"Returns the number of extensions matching a given *ecode*.\n\n Parameter\n ---------\n code : int | str\n The ecode can be specified either literal or as numerical value.\n \"\"\"\n count = 0\n code = extension_codes.code[ecode]\n for e in self:\n if e.get_code() == code:\n count += 1\n return count\n\n def get_codes(self):\n \"\"\"Return a list of the extension code of all available extensions\"\"\"\n return [e.get_code() for e in self]\n\n def get_sizeondisk(self):\n \"\"\"Return the size of the complete header extensions in the NIfTI file.\n \"\"\"\n # add four bytes for the NIfTI extension flag!\n return np.sum([e.get_sizeondisk() for e in self]) + 4\n\n def __repr__(self):\n s = \"Nifti1Extensions(%s)\" \\\n % ', '.join([str(e) for e in self])\n return s\n\n def __eq__(self, other):\n for i, e in enumerate(self):\n if not e == other[i]:\n return False\n return True\n\n def write_to(self, fileobj):\n ''' Write header extensions to fileobj\n\n Write starts at fileobj current file position.\n\n Parameters\n ----------\n fileobj : file-like object\n Should implement ``write`` method\n\n Returns\n -------\n None\n '''\n # not extensions -> nothing to do\n if not len(self):\n return\n\n # since we have extensions write the appropriate flag\n fileobj.write(np.array((1,0,0,0), dtype=np.int8).tostring())\n # and now each extension\n for e in self:\n e.write_to(fileobj)\n\n @classmethod\n def from_fileobj(klass, fileobj, size):\n '''Read header extensions from a fileobj\n\n Parameters\n ----------\n fileobj : file-like object\n It is assumed to be positions right after the NIfTI magic field.\n size : int\n Number of bytes to read. If negative, fileobj will be read till its\n end.\n\n Returns\n -------\n An extension list. This list might be empty in case not extensions\n were present in fileobj.\n '''\n # make empty extension list\n extensions = klass()\n # assume the fileptr is just after header (magic field)\n # try reading the next 4 bytes after the initial header\n extension_status = fileobj.read(4)\n if not len(extension_status):\n # if there is nothing the NIfTI standard requires to assume zeros\n extension_status = np.zeros((4,), dtype=np.int8)\n else:\n extension_status = np.fromstring(extension_status, dtype=np.int8)\n\n # NIfTI1 says: if first element is non-zero there are extensions present\n # if not there is nothing left to do\n if not extension_status[0]:\n return extensions\n\n # note that we read the extension flag\n if not size < 0:\n size = size - 4\n # read until the whole header is parsed (each extension is a multiple\n # of 16 bytes) or in case of a separate header file till the end\n # (break inside the body)\n # XXX not sure if the separate header behavior is sane\n while size >= 16 or size < 0:\n # the next 8 bytes should have esize and ecode\n ext_def = fileobj.read(8)\n # nothing was read and instructed to read till the end\n # -> assume all extensions where parsed and break\n if not len(ext_def) and size < 0:\n break\n # otherwise there should be a full extension header\n if not len(ext_def) == 8:\n raise HeaderDataError('failed to read extension header')\n ext_def = np.fromstring(ext_def, dtype=np.int32)\n # be extra verbose\n ecode = ext_def[1]\n esize = ext_def[0]\n if esize % 16:\n raise HeaderDataError(\n 'extension size is not a multiple of 16 bytes')\n # read extension itself; esize includes the 8 bytes already read\n evalue = fileobj.read(esize - 8)\n if not len(evalue) == esize - 8:\n raise HeaderDataError('failed to read extension content')\n # note that we read a full extension\n size -= esize\n # store raw extension content, but strip trailing NULL chars\n evalue = evalue.rstrip('\\x00')\n # 'extension_codes' also knows the best implementation to handle\n # a particular extension type\n try:\n ext = extension_codes.handler[ecode](ecode, evalue)\n except KeyError:\n # unknown extension type\n # XXX complain or fail or go with a generic extension\n ext = Nifti1Extension(ecode, evalue)\n extensions.append(ext)\n return extensions\n\n\nclass Nifti1Header(SpmAnalyzeHeader):\n ''' Class for NIFTI1 header '''\n # Copies of module level definitions\n _dtype = header_dtype\n _data_type_codes = data_type_codes\n _xform_codes = xform_codes\n _unit_codes = unit_codes\n _intent_codes = intent_codes\n _slice_order_codes = slice_order_codes\n\n # data scaling capabilities\n has_data_slope = True\n has_data_intercept = True\n\n def get_best_affine(self):\n ''' Select best of available transforms '''\n hdr = self._header_data\n if hdr['sform_code']:\n return self.get_sform()\n if hdr['qform_code']:\n return self.get_qform()\n return self.get_base_affine()\n\n def _empty_headerdata(self, endianness=None):\n ''' Create empty header binary block with given endianness '''\n hdr_data = analyze.AnalyzeHeader._empty_headerdata(self, endianness)\n hdr_data['scl_slope'] = 1\n hdr_data['magic'] = 'n+1'\n hdr_data['vox_offset'] = 352\n return hdr_data\n\n def get_qform_quaternion(self):\n ''' Compute quaternion from b, c, d of quaternion\n\n Fills a value by assuming this is a unit quaternion\n '''\n hdr = self._header_data\n bcd = [hdr['quatern_b'], hdr['quatern_c'], hdr['quatern_d']]\n return fillpositive(bcd)\n\n def get_qform(self):\n ''' Return 4x4 affine matrix from qform parameters in header '''\n hdr = self._header_data\n quat = self.get_qform_quaternion()\n R = quat2mat(quat)\n vox = hdr['pixdim'][1:4].copy()\n if np.any(vox) < 0:\n raise HeaderDataError('pixdims[1,2,3] should be positive')\n qfac = hdr['pixdim'][0]\n if qfac not in (-1,1):\n raise HeaderDataError('qfac (pixdim[0]) should be 1 or -1')\n vox[-1] *= qfac\n S = np.diag(vox)\n M = np.dot(R, S)\n out = np.eye(4)\n out[0:3,0:3] = M\n out[0:3,3] = [hdr['qoffset_x'], hdr['qoffset_y'], hdr['qoffset_z']]\n return out\n\n def set_qform(self, affine, code=None):\n ''' Set qform header values from 4x4 affine\n\n Parameters\n ----------\n hdr : nifti1 header\n affine : 4x4 array\n affine transform to write into qform\n code : None, string or integer\n String or integer giving meaning of transform in *affine*.\n The default is None. If code is None, then {if current\n qform code is not 0, leave code as it is in the header; else\n set to 1 ('scanner')}.\n\n Notes\n -----\n The qform transform only encodes translations, rotations and\n zooms. If there are shear components to the *affine* transform,\n the written qform gives the closest approximation where the\n rotation matrix is orthogonal. This is to allow quaternion\n representation. The orthogonal representation enforces orthogonal\n axes.\n\n Examples\n --------\n >>> hdr = Nifti1Header()\n >>> int(hdr['qform_code']) # gives 0 - unknown\n 0\n >>> affine = np.diag([1,2,3,1])\n >>> np.all(hdr.get_qform() == affine)\n False\n >>> hdr.set_qform(affine)\n >>> np.all(hdr.get_qform() == affine)\n True\n >>> int(hdr['qform_code']) # gives 1 - scanner\n 1\n >>> hdr.set_qform(affine, code='talairach')\n >>> int(hdr['qform_code'])\n 3\n >>> hdr.set_qform(affine, code=None)\n >>> int(hdr['qform_code'])\n 3\n >>> hdr.set_qform(affine, code='scanner')\n >>> int(hdr['qform_code'])\n 1\n '''\n hdr = self._header_data\n if code is None:\n code = hdr['qform_code']\n if code == 0:\n hdr['qform_code'] = 1\n else:\n code = self._xform_codes[code]\n hdr['qform_code'] = code\n if not affine.shape == (4,4):\n raise TypeError('Need 4x4 affine as input')\n trans = affine[:3,3]\n RZS = affine[:3,:3]\n zooms = np.sqrt(np.sum(RZS * RZS, axis=0))\n R = RZS / zooms\n # Set qfac to make R determinant positive\n if npl.det(R) > 0:\n qfac = 1\n else:\n qfac = -1\n R[:,-1] *= -1\n # Make R orthogonal (to allow quaternion representation)\n # The orthogonal representation enforces orthogonal axes\n # (a subtle requirement of the NIFTI format qform transform)\n # Transform below is polar decomposition, returning the closest\n # orthogonal matrix PR, to input R\n P, S, Qs = npl.svd(R)\n PR = np.dot(P, Qs)\n # Convert to quaternion\n quat = mat2quat(PR)\n # Set into header\n hdr['qoffset_x'], hdr['qoffset_y'], hdr['qoffset_z'] = trans\n hdr['pixdim'][0] = qfac\n hdr['pixdim'][1:4] = zooms \n hdr['quatern_b'], hdr['quatern_c'], hdr['quatern_d'] = quat[1:]\n\n def get_sform(self):\n ''' Return sform 4x4 affine matrix from header '''\n hdr = self._header_data\n out = np.eye(4)\n out[0,:] = hdr['srow_x'][:]\n out[1,:] = hdr['srow_y'][:]\n out[2,:] = hdr['srow_z'][:]\n return out\n\n def set_sform(self, affine, code=None):\n ''' Set sform transform from 4x4 affine\n\n Parameters\n ----------\n hdr : nifti1 header\n affine : 4x4 array\n affine transform to write into sform\n code : None, string or integer\n String or integer giving meaning of transform in *affine*.\n The default is None. If code is None, then {if current\n sform code is not 0, leave code as it is in the header; else\n set to 1 ('scanner')}.\n\n Examples\n --------\n >>> hdr = Nifti1Header()\n >>> int(hdr['sform_code']) # gives 0 - unknown\n 0\n >>> affine = np.diag([1,2,3,1])\n >>> np.all(hdr.get_sform() == affine)\n False\n >>> hdr.set_sform(affine)\n >>> np.all(hdr.get_sform() == affine)\n True\n >>> int(hdr['sform_code']) # gives 1 - scanner\n 1\n >>> hdr.set_sform(affine, code='talairach')\n >>> int(hdr['sform_code'])\n 3\n >>> hdr.set_sform(affine, code=None)\n >>> int(hdr['sform_code'])\n 3\n >>> hdr.set_sform(affine, code='scanner')\n >>> int(hdr['sform_code'])\n 1\n '''\n hdr = self._header_data\n if code is None:\n code = hdr['sform_code']\n if code == 0:\n hdr['sform_code'] = 1\n else:\n code = self._xform_codes[code]\n hdr['sform_code'] = code\n hdr['srow_x'][:] = affine[0,:]\n hdr['srow_y'][:] = affine[1,:]\n hdr['srow_z'][:] = affine[2,:]\n\n def get_qform_code(self, code_repr='label'):\n ''' Return representation of qform code\n\n Parameters\n ----------\n code_repr : string\n string giving output form of intent code representation.\n Default is 'label'; use 'code' for integer representation.\n\n Returns\n -------\n qform_code : string or integer\n string label for qform code or code\n\n Examples\n --------\n >>> hdr = Nifti1Header()\n >>> hdr['qform_code'] = 3\n >>> hdr.get_qform_code()\n 'talairach'\n '''\n return self._get_code_field(\n code_repr,\n 'qform_code',\n self._xform_codes)\n\n def get_sform_code(self, code_repr='label'):\n ''' Return representation of sform code\n\n Parameters\n ----------\n code_repr : string\n string giving output form of intent code representation.\n Default is 'label'; use 'code' for integer representation.\n\n Returns\n -------\n sform_code : string or integer\n string label for sform code or code\n\n Examples\n --------\n >>> hdr = Nifti1Header()\n >>> hdr['sform_code'] = 3\n >>> hdr.get_sform_code()\n 'talairach'\n '''\n return self._get_code_field(\n code_repr,\n 'sform_code',\n self._xform_codes)\n\n def get_slope_inter(self):\n ''' Get data scaling (slope) and DC offset (intercept) from header data\n\n Parameters\n ----------\n self : header object\n Should have fields (keys)\n * scl_slope - slope\n * scl_inter - intercept\n\n Returns\n -------\n slope : None or float\n scaling (slope). None if there is no valid scaling from\n these fields\n inter : None or float\n offset (intercept). Also None if there is no valid scaling, offset\n\n Examples\n --------\n >>> fields = {'scl_slope':1,'scl_inter':0}\n >>> hdr = Nifti1Header()\n >>> hdr.get_slope_inter()\n (1.0, 0.0)\n >>> hdr['scl_slope'] = 0\n >>> hdr.get_slope_inter()\n (None, None)\n >>> hdr['scl_slope'] = np.nan\n >>> hdr.get_slope_inter()\n (None, None)\n >>> hdr['scl_slope'] = 1\n >>> hdr['scl_inter'] = 1\n >>> hdr.get_slope_inter()\n (1.0, 1.0)\n >>> hdr['scl_inter'] = np.inf\n >>> hdr.get_slope_inter()\n (1.0, 0.0)\n '''\n scale = float(self['scl_slope'])\n dc_offset = float(self['scl_inter'])\n if not scale or not np.isfinite(scale):\n return None, None\n if not np.isfinite(dc_offset):\n dc_offset = 0.0\n return scale, dc_offset\n\n def set_slope_inter(self, slope, inter):\n self._header_data['scl_slope'] = slope\n self._header_data['scl_inter'] = inter\n\n def get_dim_info(self):\n ''' Gets nifti MRI slice etc dimension information\n\n Returns\n -------\n freq : {None,0,1,2}\n Which data array axis is freqency encode direction\n phase : {None,0,1,2}\n Which data array axis is phase encode direction\n slice : {None,0,1,2}\n Which data array axis is slice encode direction\n\n where ``data array`` is the array returned by ``get_data``\n\n Because nifti1 files are natively Fortran indexed:\n 0 is fastest changing in file\n 1 is medium changing in file\n 2 is slowest changing in file\n\n ``None`` means the axis appears not to be specified.\n\n Examples\n --------\n See set_dim_info function\n\n '''\n hdr = self._header_data\n info = int(hdr['dim_info'])\n freq = info & 3\n phase = (info >> 2) & 3\n slice = (info >> 4) & 3\n return (freq-1 if freq else None,\n phase-1 if phase else None,\n slice-1 if slice else None)\n\n def set_dim_info_from_names(self, axisnames):\n \"\"\" Sets nifti dim_info from the \n names of the first three axes.\n \n Parameters\n ----------\n\n axisnames = [str]\n Names of up to the first three axes\n\n Returns\n -------\n\n None\n\n Examples\n --------\n\n >>> from nipy.testing import funcfile\n >>> import nipy.io.imageformats as formats\n >>> img = formats.load(funcfile)\n >>> hdr = img.get_header()\n >>> hdr.get_dim_info()\n (None, None, None)\n >>> hdr.set_dim_info_from_names(('frequency', 'i', 'slice'))\n >>> hdr.get_dim_info()\n (0, None, 2)\n >>> \n\n\n \"\"\"\n\n fps = []\n for n in ['frequency',\n 'phase',\n 'slice']:\n try:\n i = axisnames.index(n)\n fps.append(i)\n except ValueError: # axisnames is a tuple, not a list\n fps.append(None)\n pass\n self.set_dim_info(*fps)\n\n def set_dim_info(self, freq=None, phase=None, slice=None):\n ''' Sets nifti MRI slice etc dimension information\n\n Parameters\n ----------\n hdr : nifti1 header\n freq : {None, 0, 1, 2}\n axis of data array refering to freqency encoding\n phase : {None, 0, 1, 2}\n axis of data array refering to phase encoding\n slice : {None, 0, 1, 2}\n axis of data array refering to slice encoding\n\n ``None`` means the axis is not specified.\n\n Examples\n --------\n >>> hdr = Nifti1Header()\n >>> hdr.set_dim_info(1, 2, 0)\n >>> hdr.get_dim_info()\n (1, 2, 0)\n >>> hdr.set_dim_info(freq=1, phase=2, slice=0)\n >>> hdr.get_dim_info()\n (1, 2, 0)\n >>> hdr.set_dim_info()\n >>> hdr.get_dim_info()\n (None, None, None)\n >>> hdr.set_dim_info(freq=1, phase=None, slice=0)\n >>> hdr.get_dim_info()\n (1, None, 0)\n\n Notes\n -----\n This is stored in one byte in the header\n '''\n for inp in (freq, phase, slice):\n if inp not in (None, 0, 1, 2):\n raise HeaderDataError('Inputs must be in [None, 0, 1, 2]')\n info = 0\n if not freq is None:\n info = info | ((freq+1) & 3)\n if not phase is None:\n info = info | (((phase+1) & 3) << 2)\n if not slice is None:\n info = info | (((slice+1) & 3) << 4)\n self._header_data['dim_info'] = info\n\n def get_axis_renames(self):\n \"\"\"\n Return axis names based on dim_info specification.\n\n The keys of the axis are in ['frequency', 'phase' 'slice']\n and its values are integers.\n\n\n >>> from nipy.testing import funcfile\n >>> import nipy.io.imageformats as formats\n >>> img = formats.load(funcfile)\n >>> hdr = img.get_header()\n >>> hdr.get_axis_renames()\n {}\n >>> hdr.set_dim_info_from_names(('frequency', 'i', 'slice'))\n >>> hdr.get_axis_renames()\n {'frequency': 0, 'slice': 2}\n >>> \n \"\"\"\n\n fps = self.get_dim_info()\n fps_dict = dict(zip(fps, ['frequency', 'phase', 'slice']))\n if None in fps_dict:\n del(fps_dict[None])\n if fps_dict:\n return dict([(value, key) for key, value in fps_dict.items()])\n return {}\n\n def get_intent_code(self, code_repr='label'):\n ''' Return representation of intent code\n\n Parameters\n ----------\n code_repr : string\n string giving output form of intent code representation.\n Default is 'label'; use 'code' for integer representation.\n\n Returns\n -------\n intent_code : string or integer\n string label for intent code or code\n\n Examples\n --------\n >>> hdr = Nifti1Header()\n >>> hdr.set_intent('t test', (10,), name='some score')\n >>> hdr.get_intent_code()\n 't test'\n '''\n return self._get_code_field(\n code_repr,\n 'intent_code',\n self._intent_codes)\n\n def get_intent(self, code_repr='label'):\n ''' Get intent code, parameters and name\n\n Parameters\n ----------\n code_repr : string\n string giving output form of intent code representation.\n Default is 'label'; use 'code' for integer representation.\n\n Returns\n -------\n code : string or integer\n intent code, or string describing code\n parameters : tuple\n parameters for the intent\n name : string\n intent name\n\n Examples\n --------\n >>> hdr = Nifti1Header()\n >>> hdr.set_intent('t test', (10,), name='some score')\n >>> hdr.get_intent()\n ('t test', (10.0,), 'some score')\n >>> hdr.get_intent('code')\n (3, (10.0,), 'some score')\n '''\n hdr = self._header_data\n code = int(hdr['intent_code'])\n recode = self.get_intent_code(code_repr)\n n_params = len(self._intent_codes.parameters[code])\n params = (float(hdr['intent_p%d' % (i+1)]) for i in range(n_params))\n return recode, tuple(params), str(hdr['intent_name'])\n\n def set_intent(self, code, params=(), name=''):\n ''' Set the intent code, parameters and name\n\n If parameters are not specified, assumed to be all zero. Each\n intent code has a set number of parameters associated. If you\n specify any parameters, then it will need to be the correct number\n (e.g the \"f test\" intent requires 2). However, parameters can\n also be set in the file data, so we also allow not setting any\n parameters (empty parameter tuple).\n\n Parameters\n ----------\n code : integer or string\n code specifying nifti intent\n params : list, tuple of scalars\n parameters relating to intent (see intent_codes)\n defaults to (). Unspecified parameters are set to 0.0\n name : string\n intent name (description). Defaults to ''\n\n Returns\n -------\n None\n\n Examples\n --------\n >>> hdr = Nifti1Header()\n >>> hdr.set_intent(0) # unknown code\n >>> hdr.set_intent('z score')\n >>> hdr.get_intent()\n ('z score', (), '')\n >>> hdr.get_intent('code')\n (5, (), '')\n >>> hdr.set_intent('t test', (10,), name='some score')\n >>> hdr.get_intent()\n ('t test', (10.0,), 'some score')\n >>> hdr.set_intent('f test', (2, 10), name='another score')\n >>> hdr.get_intent()\n ('f test', (2.0, 10.0), 'another score')\n >>> hdr.set_intent('f test')\n >>> hdr.get_intent()\n ('f test', (0.0, 0.0), '')\n '''\n hdr = self._header_data\n icode = intent_codes.code[code]\n p_descr = intent_codes.parameters[code]\n if len(params) and len(params) != len(p_descr):\n raise HeaderDataError('Need params of form %s, or empty' % (p_descr,))\n all_params = [0] * 3\n all_params[:len(params)] = params[:]\n for i, param in enumerate(all_params):\n hdr['intent_p%d' % (i+1)] = param\n hdr['intent_code'] = icode\n hdr['intent_name'] = name\n\n def get_slice_duration(self):\n ''' Get slice duration\n\n Returns\n -------\n slice_duration : float\n time to acquire one slice\n\n Examples\n --------\n >>> hdr = Nifti1Header()\n >>> hdr.set_dim_info(slice=2)\n >>> hdr.set_slice_duration(0.3)\n >>> print \"%0.1f\" % hdr.get_slice_duration()\n 0.3\n\n Notes\n -----\n The Nifti1 spec appears to require the slice dimension to be\n defined for slice_duration to have meaning.\n '''\n _, _, slice_dim = self.get_dim_info()\n if slice_dim is None:\n raise HeaderDataError('Slice dimension must be set '\n 'for duration to be valid')\n return float(self._header_data['slice_duration'])\n\n def set_slice_duration(self, duration):\n ''' Set slice duration\n\n Parameters\n ----------\n duration : scalar\n time to acquire one slice\n\n Examples\n --------\n See ``get_slice_duration``\n '''\n _, _, slice_dim = self.get_dim_info()\n if slice_dim is None:\n raise HeaderDataError('Slice dimension must be set '\n 'for duration to be valid')\n self._header_data['slice_duration'] = duration\n\n def get_slice_code(self, code_repr='label'):\n ''' Return representation of slice order code\n\n Parameters\n ----------\n code_repr : string\n string giving output form of slice order code representation.\n Default is 'label'; use 'code' for integer representation.\n\n Returns\n -------\n slice_code : string or integer\n string label for slice ordering code or code\n\n Examples\n --------\n >>> hdr = Nifti1Header()\n >>> hdr['slice_code'] = 4 # alternating decreasing\n >>> hdr.get_slice_code()\n 'alternating decreasing'\n '''\n return self._get_code_field(\n code_repr,\n 'slice_code',\n self._slice_order_codes)\n\n def get_slice_times(self):\n ''' Get slice times from slice timing information\n\n Returns\n -------\n slice_times : tuple\n Times of acquisition of slices, where 0 is the beginning of\n the acquisition, ordered by position in file. nifti allows\n slices at the top and bottom of the volume to be excluded from\n the standard slice timing specification, and calls these\n \"padding slices\". We give padding slices ``None`` as a time\n of acquisition\n\n Examples\n --------\n >>> hdr = Nifti1Header()\n >>> hdr.set_dim_info(slice=2)\n >>> hdr.set_data_shape((1, 1, 7))\n >>> hdr.set_slice_duration(0.1)\n\n We need a function to print out the Nones and floating point\n values in a predictable way, for the tests below.\n\n >>> _stringer = lambda val: val is not None and '%2.1f' % val or None\n >>> _print_me = lambda s: map(_stringer, s)\n\n The following examples are from the nifti1.h documentation.\n\n >>> hdr['slice_code'] = slice_order_codes['sequential increasing']\n >>> _print_me(hdr.get_slice_times())\n ['0.0', '0.1', '0.2', '0.3', '0.4', '0.5', '0.6']\n >>> hdr['slice_start'] = 1\n >>> hdr['slice_end'] = 5\n >>> _print_me(hdr.get_slice_times())\n [None, '0.0', '0.1', '0.2', '0.3', '0.4', None]\n >>> hdr['slice_code'] = slice_order_codes['sequential decreasing']\n >>> _print_me(hdr.get_slice_times())\n [None, '0.4', '0.3', '0.2', '0.1', '0.0', None]\n >>> hdr['slice_code'] = slice_order_codes['alternating increasing']\n >>> _print_me(hdr.get_slice_times())\n [None, '0.0', '0.3', '0.1', '0.4', '0.2', None]\n >>> hdr['slice_code'] = slice_order_codes['alternating decreasing']\n >>> _print_me(hdr.get_slice_times())\n [None, '0.2', '0.4', '0.1', '0.3', '0.0', None]\n >>> hdr['slice_code'] = slice_order_codes['alternating increasing 2']\n >>> _print_me(hdr.get_slice_times())\n [None, '0.2', '0.0', '0.3', '0.1', '0.4', None]\n >>> hdr['slice_code'] = slice_order_codes['alternating decreasing 2']\n >>> _print_me(hdr.get_slice_times())\n [None, '0.4', '0.1', '0.3', '0.0', '0.2', None]\n '''\n hdr = self._header_data\n _, _, slice_dim = self.get_dim_info()\n shape = self.get_data_shape()\n slice_len = shape[slice_dim]\n duration = self.get_slice_duration()\n slabel = self.get_slice_code()\n if slabel == 'unknown':\n raise HeaderDataError('Cannot get slice times when '\n 'Slice code is \"unknown\"')\n slice_start, slice_end = (int(hdr['slice_start']),\n int(hdr['slice_end']))\n if slice_start < 0:\n raise HeaderDataError('slice_start should be >= 0')\n if slice_end == 0:\n slice_end = slice_len-1\n n_timed = slice_end - slice_start + 1\n if n_timed < 1:\n raise HeaderDataError('slice_end should be > slice_start')\n st_order = self._slice_time_order(slabel, n_timed)\n times = st_order * duration\n return ((None,)*slice_start +\n tuple(times) +\n (None,)*(slice_len-slice_end-1))\n\n def set_slice_times(self, slice_times):\n ''' Set slice times into *hdr*\n\n Parameters\n ----------\n slice_times : tuple\n tuple of slice times, one value per slice\n tuple can include None to indicate no slice time for that slice\n\n Examples\n --------\n >>> hdr = Nifti1Header()\n >>> hdr.set_dim_info(slice=2)\n >>> hdr.set_data_shape([1, 1, 7])\n >>> hdr.set_slice_duration(0.1)\n >>> times = [None, 0.2, 0.4, 0.1, 0.3, 0.0, None]\n >>> hdr.set_slice_times(times)\n >>> hdr.get_slice_code()\n 'alternating decreasing'\n >>> int(hdr['slice_start'])\n 1\n >>> int(hdr['slice_end'])\n 5\n '''\n # Check if number of slices matches header\n hdr = self._header_data\n _, _, slice_dim = self.get_dim_info()\n shape = self.get_data_shape()\n slice_len = shape[slice_dim]\n if slice_len != len(slice_times):\n raise HeaderDataError('Number of slice times does not '\n 'match number of slices')\n # Extract Nones at beginning and end. Check for others\n for ind, time in enumerate(slice_times):\n if time is not None:\n slice_start = ind\n break\n else:\n raise HeaderDataError('Not all slice times can be None')\n for ind, time in enumerate(slice_times[::-1]):\n if time is not None:\n slice_end = slice_len-ind-1\n break\n timed = slice_times[slice_start:slice_end+1]\n for time in timed:\n if time is None:\n raise HeaderDataError('Cannot have None in middle '\n 'of slice time vector')\n # Find slice duration, check times are compatible with single\n # duration\n tdiffs = np.diff(np.sort(timed))\n if not np.allclose(np.diff(tdiffs), 0):\n raise HeaderDataError('Slice times not compatible with '\n 'single slice duration')\n duration = np.mean(tdiffs)\n # To slice time order\n st_order = np.round(np.array(timed) / duration)\n # Check if slice times fit known schemes\n n_timed = len(timed)\n labels = self._slice_order_codes.value_set('label')\n labels.remove('unknown')\n for label in labels:\n if np.all(st_order == self._slice_time_order(\n label,\n n_timed)):\n break\n else:\n raise HeaderDataError('slice ordering of %s fits '\n 'with no known scheme' % st_order)\n # Set values into header\n hdr['slice_start'] = slice_start\n hdr['slice_end'] = slice_end\n hdr['slice_duration'] = duration\n hdr['slice_code'] = slice_order_codes.code[label]\n\n def for_file_pair(self, is_pair=True):\n ''' Adapt header to separate or same image and header file\n\n Parameters\n ----------\n is_pair : bool, optional\n True if adapting header to file pair state, False for single\n\n Returns\n -------\n hdr : Nifti1Header\n copied and possibly modified header\n\n Examples\n --------\n The header starts off as being for a single file\n\n >>> hdr = Nifti1Header()\n >>> str(hdr['magic'])\n 'n+1'\n >>> hdr.get_data_offset()\n 352\n\n But we can switch it to be for two files (a pair)\n\n >>> pair_hdr = hdr.for_file_pair()\n >>> str(pair_hdr['magic'])\n 'ni1'\n >>> pair_hdr.get_data_offset()\n 0\n\n The original header is not affected (a copy is returned)\n\n >>> hdr.get_data_offset()\n 352\n\n Back to single again\n\n >>> unpair_hdr = pair_hdr.for_file_pair(False)\n >>> str(unpair_hdr['magic'])\n 'n+1'\n >>> unpair_hdr.get_data_offset()\n 352\n '''\n hdr = self.copy()\n if not is_pair:\n # one file version\n if hdr['magic'] == 'n+1':\n if hdr['vox_offset'] < 352:\n hdr['vox_offset'] = 352\n return hdr\n hdr['magic'] = 'n+1'\n hdr['vox_offset'] = 352\n return hdr\n # two file version\n if hdr['magic'] == 'ni1':\n return hdr\n hdr['magic'] = 'ni1'\n hdr['vox_offset'] = 0\n return hdr\n\n def _slice_time_order(self, slabel, n_slices):\n ''' Supporting function to give time order of slices from label '''\n if slabel == 'sequential increasing':\n sp_ind_time_order = range(n_slices)\n elif slabel == 'sequential decreasing':\n sp_ind_time_order = range(n_slices)[::-1]\n elif slabel == 'alternating increasing':\n sp_ind_time_order = range(0,n_slices,2) + range(1, n_slices, 2)\n elif slabel == 'alternating decreasing':\n sp_ind_time_order = range(n_slices-1,-1,-2) + range(n_slices-2,-1,-2)\n elif slabel == 'alternating increasing 2':\n sp_ind_time_order = range(1,n_slices,2) + range(0, n_slices, 2)\n elif slabel == 'alternating decreasing 2':\n sp_ind_time_order = range(n_slices-2,-1,-2) + range(n_slices-1,-1,-2)\n else:\n raise HeaderDataError('We do not handle slice ordering \"%s\"'\n % slabel)\n return np.argsort(sp_ind_time_order)\n\n ''' Checks only below here '''\n\n @classmethod\n def _get_checks(klass):\n # We need to return our own versions of - e.g. chk_datatype, to\n # pick up the Nifti datatypes from our class\n return (klass._chk_sizeof_hdr,\n klass._chk_datatype,\n klass._chk_bitpix,\n klass._chk_pixdims,\n klass._chk_scale_slope,\n klass._chk_scale_inter,\n klass._chk_qfac,\n klass._chk_magic_offset,\n klass._chk_qform_code,\n klass._chk_sform_code)\n\n @staticmethod\n def _chk_scale_slope(hdr, fix=True):\n ret = Report(hdr, HeaderDataError)\n scale = hdr['scl_slope']\n if scale and np.isfinite(scale):\n return ret\n ret.problem_msg = '\"scl_slope\" is %s; should !=0 and be finite' % scale\n if fix:\n hdr['scl_slope'] = 1\n ret.fix_msg = 'setting \"scl_slope\" to 1'\n else:\n ret.problem_level = 30\n return ret\n\n @staticmethod\n def _chk_scale_inter(hdr, fix=True):\n ret = Report(hdr, HeaderDataError)\n scale = hdr['scl_inter']\n if np.isfinite(scale):\n return ret\n ret.problem_msg = '\"scl_inter\" is %s; should be finite' % scale\n if fix:\n hdr['scl_inter'] = 0\n ret.fix_msg = 'setting \"scl_inter\" to 0'\n else:\n ret.problem_level = 30\n return ret\n\n @staticmethod\n def _chk_qfac(hdr, fix=True):\n ret = Report(hdr, HeaderDataError)\n if hdr['pixdim'][0] in (-1, 1):\n return ret\n ret.problem_msg = 'pixdim[0] (qfac) should be 1 (default) or -1'\n if fix:\n hdr['pixdim'][0] = 1\n ret.fix_msg = 'setting qfac to 1'\n else:\n ret.problem_level = 20\n return ret\n\n @staticmethod\n def _chk_magic_offset(hdr, fix=True):\n ret = Report(hdr, HeaderDataError)\n magic = hdr['magic']\n offset = hdr['vox_offset']\n if magic == 'ni1': # two files\n if offset == 0:\n return ret\n ret.problem_msg = ('vox offset should be 0 (is %s)'\n 'with two-file nifti images' % offset)\n ret.problem_level = 40\n if fix: \n ret.fix_msg = 'leaving at current value'\n elif magic == 'n+1': # one file\n if offset >= 352:\n if not offset % 16:\n return ret\n else:\n # XXX Michael wonders, if this warning really valid? NIfTI\n # says that each extension's length has to be a multiple of\n # 16, therefore the test should be (offset-352) % 16 and\n # not offset % 16, or does SPM have additional artifical\n # limitations?\n ret.problem_msg = ('vox offset (=%s) not divisible '\n 'by 16, not SPM compatible' % offset)\n ret.problem_level = 30\n if fix:\n ret.fix_msg = 'leaving at current value'\n return ret\n ret.problem_msg = ('vox offset %d too low for '\n 'single file nifti1' % offset)\n if fix:\n hdr['vox_offset'] = 352 \n ret.fix_msg = 'setting to minimum value of 352'\n else:\n ret.problem_level = 50\n else: # unrecognized nii magic string, oh dear\n ret.problem_msg = 'magic string %s is not valid' % magic\n ret.problem_level = 50\n if fix:\n ret.fix_msg = 'leaving as is, but future errors are likely'\n return ret\n\n @classmethod\n def _chk_qform_code(klass, hdr, fix=True):\n ret = Report(hdr, HeaderDataError)\n code = int(hdr['qform_code'])\n if int(hdr['qform_code']) in klass._xform_codes.value_set():\n return ret\n ret.problem_msg = 'qform code %d not valid' % code\n if fix:\n hdr['qform_code'] = 0\n ret.fix_msg = 'setting to 0'\n else:\n ret.problem_level = 30\n return ret\n\n @classmethod\n def _chk_sform_code(klass, hdr, fix=True):\n ret = Report(hdr, HeaderDataError)\n code = int(hdr['sform_code'])\n if int(hdr['sform_code']) in klass._xform_codes.value_set():\n return ret\n ret.problem_msg = 'sform code %d not valid' % code\n if fix:\n hdr['sform_code'] = 0\n ret.fix_msg = 'setting to 0'\n else:\n ret.problem_level = 30\n return ret\n\n\nclass Nifti1Image(analyze.AnalyzeImage):\n _header_maker = Nifti1Header\n\n def _set_header(self, header=None):\n SpatialImage._set_header(self, header)\n\n @staticmethod\n def filespec_to_files(filespec):\n ft1 = filetuples.FileTuples(\n (('header', '.nii'), ('image', '.nii')),\n ignored_suffixes=('.gz', '.bz2')\n )\n ft2 = filetuples.FileTuples(\n (('header', '.hdr'), ('image', '.img')),\n ignored_suffixes=('.gz', '.bz2')\n )\n for ftups in (ft1, ft2):\n try:\n ftups.set_filenames(filespec)\n except filetuples.FileTuplesError:\n continue\n break\n else:\n raise ValueError('Filespec \"%s\" does not '\n 'look like Nifti1' % filespec)\n files = dict(zip(('header', 'image'), ftups.get_filenames()))\n return files\n\n @classmethod\n def from_files(klass, files):\n fname = files['header']\n fileobj = allopen(fname)\n header = klass._header_maker.from_fileobj(fileobj)\n extra = None\n\n # handle extensions\n # assume the fileptr is just after header (magic field)\n # determine how much to read when parsing the extensions\n if header['vox_offset'] == 0:\n # read till the end of the header\n extsize = -1\n else:\n extsize = header['vox_offset'] - fileobj.tell()\n extensions = Nifti1Extensions.from_fileobj(fileobj, extsize)\n # XXX maybe always do that?\n if len(extensions):\n extra = {'extensions': extensions}\n\n affine = header.get_best_affine()\n ret = klass(None, affine, header=header, extra=extra)\n ret._files = files\n return ret\n\n def to_files(self, files=None):\n ''' Write image to files passed, or self._files\n '''\n # XXX the whole method is candidate for refactoring, since it started as\n # verbatim copy of AnalyzeImage.to_files()\n if files is None:\n files = self._files\n if files is None:\n raise ValueError('Need files to write data')\n data = self.get_data()\n # Adapt header to possible two<->one file difference\n is_pair = files['header'] != files['image']\n hdr = self.get_header().for_file_pair(is_pair)\n # if any extensions, figure out necessary vox_offset for extensions to\n # fit\n if self.extra.has_key('extensions') and len(self.extra['extensions']):\n hdr['vox_offset'] = len(hdr.binaryblock) \\\n + self.extra['extensions'].get_sizeondisk()\n slope, inter, mn, mx = adapt_header(hdr, data)\n hdrf = allopen(files['header'], 'wb')\n hdr.write_to(hdrf)\n # write all extensions to file\n # assumes that the file ptr is right after the magic string\n if not self.extra.has_key('extensions'):\n # no extensions: be nice and write appropriate flag\n hdrf.write(np.array((0,0,0,0), dtype=np.int8).tostring())\n else:\n self.extra['extensions'].write_to(hdrf)\n if is_pair:\n imgf = allopen(files['image'], 'wb')\n else: # single file for header and image\n imgf = hdrf\n # streams like bz2 do not allow seeks, even forward. We\n # check where to go, and write zeros up until the data part\n # of the file\n offset = hdr.get_data_offset()\n diff = offset-hdrf.tell()\n if diff > 0:\n hdrf.write('\\x00' * diff)\n write_data(hdr, data, imgf, inter, slope, mn, mx)\n self._header = hdr\n self._files = files\n\n\n def _update_header(self):\n ''' Harmonize header with image data and affine\n\n See AnalyzeImage._update_header for more examples\n\n Examples\n --------\n >>> data = np.zeros((2,3,4))\n >>> affine = np.diag([1.0,2.0,3.0,1.0])\n >>> img = Nifti1Image(data, affine)\n >>> hdr = img.get_header()\n >>> np.all(hdr.get_qform() == affine)\n True\n >>> np.all(hdr.get_sform() == affine)\n True\n '''\n super(Nifti1Image, self)._update_header()\n hdr = self._header\n if not self._affine is None:\n hdr.set_sform(self._affine)\n hdr.set_qform(self._affine)\n\n\nload = Nifti1Image.load\nsave = Nifti1Image.instance_to_filename\n",
"# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-\n# vi: set ft=python sts=4 ts=4 sw=4 et:\n''' Tests for nifti reading package '''\nimport os\nimport tempfile\n\nfrom StringIO import StringIO\n\nimport numpy as np\n\nfrom numpy.testing import assert_array_equal\nfrom nose.tools import assert_true, assert_equal, assert_raises, ok_\n\nimport nipy.io.imageformats.testing as vit\n\nfrom nipy.io.imageformats.volumeutils import HeaderDataError\nimport nipy.io.imageformats.nifti1 as nifti1\nfrom nipy.io.imageformats.nifti1 import load, Nifti1Header, Nifti1Image, Nifti1Extension, \\\n data_type_codes, extension_codes\n\nfrom test_spm2analyze import TestSpm2AnalyzeHeader as _TSAH\nfrom test_analyze import TestAnalyzeHeader\n\ndata_path, _ = os.path.split(__file__)\ndata_path = os.path.join(data_path, 'data')\nheader_file = os.path.join(data_path, 'nifti1.hdr')\nimage_file = os.path.join(data_path, 'example4d.nii.gz')\n\n# Example transformation matrix\nR = [[0, -1, 0], [1, 0, 0], [0, 0, 1]] # rotation matrix\nZ = [2.0, 3.0, 4.0] # zooms\nT = [20, 30, 40] # translations\nA = np.eye(4)\nA[:3,:3] = np.array(R) * Z # broadcasting does the job\nA[:3,3] = T\n\nclass TestNiftiHeader(_TSAH):\n header_class = Nifti1Header\n example_file = header_file\n\n def test_empty(self):\n hdr = self.header_class()\n for tests in TestAnalyzeHeader.test_empty(self):\n yield tests\n yield vit.assert_equal, hdr['magic'], 'n+1'\n yield vit.assert_equal, hdr['scl_slope'], 1\n yield vit.assert_equal, hdr['vox_offset'], 352\n\n def test_from_eg_file(self):\n hdr = Nifti1Header.from_fileobj(open(self.example_file))\n yield vit.assert_equal, hdr.endianness, '<'\n yield vit.assert_equal, hdr['magic'], 'ni1'\n yield vit.assert_equal, hdr['sizeof_hdr'], 348\n\n\ndef test_datatypes():\n hdr = Nifti1Header()\n for code in data_type_codes.value_set():\n dt = data_type_codes.type[code]\n if dt == np.void:\n continue\n hdr.set_data_dtype(code)\n yield (assert_equal,\n hdr.get_data_dtype(),\n data_type_codes.dtype[code])\n # Check that checks also see new datatypes\n hdr.set_data_dtype(np.complex128)\n hdr.check_fix()\n\n\ndef test_quaternion():\n hdr = Nifti1Header()\n hdr['quatern_b'] = 0\n hdr['quatern_c'] = 0\n hdr['quatern_d'] = 0\n yield assert_true, np.allclose(hdr.get_qform_quaternion(),\n [1.0, 0, 0, 0])\n hdr['quatern_b'] = 1\n hdr['quatern_c'] = 0\n hdr['quatern_d'] = 0\n yield assert_true, np.allclose(hdr.get_qform_quaternion(),\n [0, 1, 0, 0])\n\n\ndef test_qform():\n # Test roundtrip case\n ehdr = Nifti1Header()\n ehdr.set_qform(A)\n qA = ehdr.get_qform()\n yield assert_true, np.allclose(A, qA, atol=1e-5)\n yield assert_true, np.allclose(Z, ehdr['pixdim'][1:4])\n xfas = nifti1.xform_codes\n yield assert_true, ehdr['qform_code'] == xfas['scanner']\n ehdr.set_qform(A, 'aligned')\n yield assert_true, ehdr['qform_code'] == xfas['aligned']\n ehdr.set_qform(A, xfas['aligned'])\n yield assert_true, ehdr['qform_code'] == xfas['aligned']\n\n\ndef test_sform():\n # Test roundtrip case\n ehdr = Nifti1Header()\n ehdr.set_sform(A)\n sA = ehdr.get_sform()\n yield assert_true, np.allclose(A, sA, atol=1e-5)\n xfas = nifti1.xform_codes\n yield assert_true, ehdr['sform_code'] == xfas['scanner']\n ehdr.set_sform(A, 'aligned')\n yield assert_true, ehdr['sform_code'] == xfas['aligned']\n ehdr.set_sform(A, xfas['aligned'])\n yield assert_true, ehdr['sform_code'] == xfas['aligned']\n\n'''\ndef test_checked():\n ehf = vn.empty_header\n ckdf = vn.checked\n sso = sys.stdout\n # test header gives no warnings at any severity\n log = StringIO()\n hdr2 = ckdf(hdr, log=log, severity=0.0)\n yield assert_equal, log.tell(), 0\n # our headers may break it though\n eh = ehf()\n eh['sizeof_hdr'] = 350 # severity 2.0\n ehc = ckdf(eh, sso, 2.1)\n yield assert_equal, ehc.sizeof_hdr, 348\n yield assert_raises, HeaderDataError, ckdf, eh, None, 2.0\n eh = ehf()\n eh.pixdim[0] = 0 # severity 1.0\n ehc = ckdf(eh, sso, 1.1)\n yield assert_equal, ehc.pixdim[0], 1\n yield assert_raises, HeaderDataError, ckdf, eh, None, 1.0\n eh = ehf()\n eh.pixdim[1] = -1 # severity 4.0\n ehc = ckdf(eh, sso, 4.1)\n yield assert_equal, ehc.pixdim[1], 1\n yield assert_raises, HeaderDataError, ckdf, eh, None, 4.0\n eh = ehf()\n eh.datatype = -1 # severity 9.0\n ehc = ckdf(eh, sso, 9.1)\n yield assert_equal, ehc.datatype, -1 # left as is\n yield assert_raises, HeaderDataError, ckdf, eh, None, 9.0\n eh = ehf()\n eh.datatype = 2\n eh.bitpix = 16 # severity 1.0\n ehc = ckdf(eh, sso, 1.1)\n yield assert_equal, ehc.bitpix, 8 \n yield assert_raises, HeaderDataError, ckdf, eh, None, 1.0\n eh = ehf()\n eh.magic = 'ni1'\n eh.vox_offset = 1 # severity 8.0\n ehc = ckdf(eh, sso, 8.1)\n yield assert_equal, ehc.vox_offset, 1\n yield assert_raises, HeaderDataError, ckdf, eh, None, 8.0\n eh.magic = 'n+1'\n # vox offset now wrong for single file - severity 9.0\n ehc = ckdf(eh, sso, 9.1)\n yield assert_equal, ehc.vox_offset, 352\n yield assert_raises, HeaderDataError, ckdf, eh, None, 9.0\n eh.vox_offset = 353\n # now theoretically valid but not for SPM -> 3.0\n ehc = ckdf(eh, sso, 3.1)\n yield assert_equal, ehc.vox_offset, 353\n yield assert_raises, HeaderDataError, ckdf, eh, None, 3.0\n # bad magic - severity 9.5\n eh = ehf()\n eh.magic = 'nul'\n ehc = ckdf(eh, sso, 9.6)\n yield assert_equal, ehc.magic, 'nul' # leave\n yield assert_raises, HeaderDataError, ckdf, eh, None, 9.5\n # qform, sform transforms, severity 3.0\n eh = ehf()\n eh.qform_code = -1\n ehc = ckdf(eh, sso, 3.1)\n yield assert_equal, ehc.qform_code, 0\n yield assert_raises, HeaderDataError, ckdf, eh, None, 3.0\n eh = ehf()\n eh.sform_code = -1\n ehc = ckdf(eh, sso, 3.1)\n yield assert_equal, ehc.sform_code, 0\n yield assert_raises, HeaderDataError, ckdf, eh, None, 3.0\n'''\n \n \ndef test_dim_info():\n ehdr = Nifti1Header()\n ehdr.set_dim_info(0, 2, 1)\n yield assert_true, ehdr.get_dim_info() == (0, 2, 1)\n\n\ndef test_intents():\n ehdr = Nifti1Header()\n ehdr.set_intent('t test', (10,), name='some score')\n yield assert_equal, ehdr.get_intent(), ('t test', (10.0,), 'some score')\n yield (assert_raises, KeyError,\n ehdr.set_intent, 'no intention') # invalid intent name\n yield (assert_raises, HeaderDataError,\n ehdr.set_intent, 't test', (10,10)) # too many parameters\n yield (assert_raises, HeaderDataError,\n ehdr.set_intent, 'f test', (10,)) # too few parameters\n # check unset parameters are set to 0, and name to ''\n ehdr.set_intent('t test')\n yield assert_equal, (ehdr['intent_p1'],\n ehdr['intent_p2'],\n ehdr['intent_p3']), (0,0,0)\n yield assert_equal, ehdr['intent_name'], ''\n ehdr.set_intent('t test', (10,))\n yield assert_equal, (ehdr['intent_p2'], ehdr['intent_p3']), (0,0)\n\n\ndef test_set_slice_times():\n hdr = Nifti1Header()\n hdr.set_dim_info(slice=2)\n hdr.set_data_shape([1, 1, 7])\n hdr.set_slice_duration(0.1)\n times = [0] * 6\n yield assert_raises, HeaderDataError, hdr.set_slice_times, times \n times = [None] * 7\n yield assert_raises, HeaderDataError, hdr.set_slice_times, times\n times = [None, 0, 1, None, 3, 4, None]\n yield assert_raises, HeaderDataError, hdr.set_slice_times, times\n times = [None, 0, 1, 2.1, 3, 4, None]\n yield assert_raises, HeaderDataError, hdr.set_slice_times, times\n times = [None, 0, 4, 3, 2, 1, None]\n yield assert_raises, HeaderDataError, hdr.set_slice_times, times\n times = [0, 1, 2, 3, 4, 5, 6]\n hdr.set_slice_times(times)\n yield assert_equal, hdr['slice_code'], 1\n yield assert_equal, hdr['slice_start'], 0\n yield assert_equal, hdr['slice_end'], 6\n yield assert_equal, hdr['slice_duration'], 1.0\n times = [None, 0, 1, 2, 3, 4, None]\n hdr.set_slice_times(times)\n yield assert_equal, hdr['slice_code'], 1\n yield assert_equal, hdr['slice_start'], 1\n yield assert_equal, hdr['slice_end'], 5\n yield assert_equal, hdr['slice_duration'], 1.0\n times = [None, 0.4, 0.3, 0.2, 0.1, 0, None]\n hdr.set_slice_times(times)\n yield assert_true, np.allclose(hdr['slice_duration'], 0.1)\n times = [None, 4, 3, 2, 1, 0, None]\n hdr.set_slice_times(times)\n yield assert_equal, hdr['slice_code'], 2\n times = [None, 0, 3, 1, 4, 2, None]\n hdr.set_slice_times(times)\n yield assert_equal, hdr['slice_code'], 3\n times = [None, 2, 4, 1, 3, 0, None]\n hdr.set_slice_times(times)\n yield assert_equal, hdr['slice_code'], 4\n times = [None, 2, 0, 3, 1, 4, None]\n hdr.set_slice_times(times)\n yield assert_equal, hdr['slice_code'], 5\n times = [None, 4, 1, 3, 0, 2, None]\n hdr.set_slice_times(times)\n yield assert_equal, hdr['slice_code'], 6\n\n\ndef test_nifti1_images():\n shape = (2, 4, 6)\n npt = np.float32\n data = np.arange(np.prod(shape), dtype=npt).reshape(shape)\n affine = np.diag([1, 2, 3, 1])\n img = Nifti1Image(data, affine)\n yield assert_equal, img.get_shape(), shape\n img.set_data_dtype(npt)\n stio = StringIO()\n files = {'header': stio, 'image': stio}\n img.to_files(files)\n stio.seek(0)\n img2 = Nifti1Image.from_files(files)\n yield assert_array_equal, img2.get_data(), data\n for ext in ('.gz', '.bz2'):\n try:\n _, fname = tempfile.mkstemp('.nii' + ext)\n img.to_filename(fname)\n img3 = Nifti1Image.load(fname)\n yield assert_true, isinstance(img3, img.__class__)\n yield assert_array_equal, img3.get_data(), data\n yield assert_equal, img3.get_header(), img.get_header()\n finally:\n os.unlink(fname)\n\n\ndef test_extension_basics():\n raw = '123'\n ext = Nifti1Extension('comment', raw)\n ok_(ext.get_sizeondisk() == 16)\n ok_(ext.get_content() == raw)\n ok_(ext.get_code() == 6)\n\n\ndef test_extension_codes():\n for k in extension_codes.keys():\n ext = Nifti1Extension(k, 'somevalue')\n\n\ndef test_nifti_extensions():\n nim = load(image_file)\n # basic checks of the available extensions\n ext = nim.extra['extensions']\n ok_(len(ext) == 2)\n ok_(ext.count('comment') == 2)\n ok_(ext.count('afni') == 0)\n ok_(ext.get_codes() == [6, 6])\n ok_((ext.get_sizeondisk() - 4) % 16 == 0)\n # first extension should be short one\n ok_(ext[0].get_content() == 'extcomment1')\n\n # add one\n afniext = Nifti1Extension('afni', '<xml></xml>')\n ext.append(afniext)\n ok_(ext.get_codes() == [6, 6, 4])\n ok_(ext.count('comment') == 2)\n ok_(ext.count('afni') == 1)\n ok_((ext.get_sizeondisk() - 4) % 16 == 0)\n\n # delete one\n del ext[1]\n ok_(ext.get_codes() == [6, 4])\n ok_(ext.count('comment') == 1)\n ok_(ext.count('afni') == 1)\n\n\ndef test_loadsavecycle():\n nim = load(image_file)\n # ensure we have extensions\n ok_(nim.extra.has_key('extensions'))\n ok_(len(nim.extra['extensions']))\n # write into the air ;-)\n stio = StringIO()\n files = {'header': stio, 'image': stio}\n nim.to_files(files)\n stio.seek(0)\n # reload\n lnim = Nifti1Image.from_files(files)\n ok_(lnim.extra.has_key('extensions'))\n ok_(nim.extra['extensions'] == lnim.extra['extensions'])\n"
] | [
[
"numpy.asarray",
"numpy.random.standard_normal",
"numpy.array",
"numpy.allclose"
],
[
"numpy.diag",
"numpy.dot",
"numpy.linalg.svd",
"numpy.isfinite",
"numpy.eye",
"numpy.dtype",
"numpy.sort",
"numpy.linalg.det",
"numpy.fromstring",
"numpy.mean",
"numpy.any",
"numpy.diff",
"numpy.argsort",
"numpy.array",
"numpy.zeros",
"numpy.sum"
],
[
"numpy.diag",
"numpy.allclose",
"numpy.eye",
"numpy.prod",
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
marcovirgolin/pyNSGP | [
"4a9634161012d6ab39ce3d304dba943b6f7d9b29"
] | [
"pynsgp/Selection/Selection.py"
] | [
"import numpy as np\nfrom copy import deepcopy\nfrom numpy.random import randint\n\ndef TournamentSelect( population, how_many_to_select, tournament_size=4 ):\n\tpop_size = len(population)\n\tselection = []\n\n\twhile len(selection) < how_many_to_select:\n\n\t\tbest = population[randint(pop_size)]\n\t\tfor i in range(tournament_size - 1):\n\t\t\tcontestant = population[randint(pop_size)]\n\t\t\tif (contestant.rank < best.rank) or (contestant.rank == best.rank and contestant.crowding_distance > best.crowding_distance):\n\t\t\t\tbest = contestant\n\n\t\tsurvivor = deepcopy(best)\n\t\tselection.append(survivor)\n\n\treturn selection"
] | [
[
"numpy.random.randint"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Aparna-Sakshi/sktime | [
"419d347f062320290fb65e4afec72b82179e63bf",
"419d347f062320290fb65e4afec72b82179e63bf"
] | [
"sktime/classification/feature_based/tests/test_fresh_prince.py",
"sktime/distances/_numba_utils.py"
] | [
"# -*- coding: utf-8 -*-\n\"\"\"FreshPRINCE test code.\"\"\"\nimport numpy as np\nfrom numpy import testing\nfrom sklearn.metrics import accuracy_score\n\nfrom sktime.classification.feature_based import FreshPRINCE\nfrom sktime.datasets import load_unit_test\n\n\ndef test_fresh_prince_on_unit_test_data():\n \"\"\"Test of FreshPRINCE on unit test data.\"\"\"\n # load unit test data\n X_train, y_train = load_unit_test(split=\"train\")\n X_test, y_test = load_unit_test(split=\"test\")\n indices = np.random.RandomState(0).choice(len(y_train), 10, replace=False)\n\n # train FreshPRINCE classifier\n fp = FreshPRINCE(\n random_state=0,\n default_fc_parameters=\"minimal\",\n n_estimators=10,\n save_transformed_data=True,\n )\n fp.fit(X_train, y_train)\n\n # assert probabilities are the same\n probas = fp.predict_proba(X_test.iloc[indices])\n testing.assert_array_almost_equal(probas, fp_classifier_unit_test_probas, decimal=2)\n\n # test train estimate\n train_probas = fp._get_train_probs(X_train, y_train)\n train_preds = fp.classes_[np.argmax(train_probas, axis=1)]\n assert accuracy_score(y_train, train_preds) >= 0.75\n\n\nfp_classifier_unit_test_probas = np.array(\n [\n [\n 0.2,\n 0.8,\n ],\n [\n 1.0,\n 0.0,\n ],\n [\n 0.1,\n 0.9,\n ],\n [\n 1.0,\n 0.0,\n ],\n [\n 0.9,\n 0.1,\n ],\n [\n 1.0,\n 0.0,\n ],\n [\n 0.9,\n 0.1,\n ],\n [\n 0.8,\n 0.2,\n ],\n [\n 0.9,\n 0.1,\n ],\n [\n 1.0,\n 0.0,\n ],\n ]\n)\n",
"# -*- coding: utf-8 -*-\nfrom typing import Callable\n\nimport numpy as np\nfrom numba import njit\n\nfrom sktime.distances.base import DistanceCallable\n\n\n@njit(cache=True)\ndef _check_numba_pairwise_series(x: np.ndarray) -> np.ndarray:\n \"\"\"Check a potential series being passed into pairwise.\n\n Parameters\n ----------\n x: np.ndarray\n A timeseries\n\n Returns\n -------\n np.ndarray\n Validated and reshaped (where appropriate) timeseries.\n \"\"\"\n if x.ndim == 2:\n shape = x.shape\n _x = np.reshape(x, (shape[0], shape[1], 1))\n else:\n _x = x\n return _x\n\n\ndef _compute_pairwise_distance(\n x: np.ndarray, y: np.ndarray, symmetric: bool, distance_callable: DistanceCallable\n) -> np.ndarray:\n \"\"\"Compute pairwise distance between two numpy arrays.\n\n Parameters\n ----------\n x: np.ndarray (2d or 3d array)\n First timeseries.\n y: np.ndarray (2d or 3d array)\n Second timeseries.\n symmetric: bool\n Boolean that is true when x == y and false when x != y. Used in some instances\n to speed up pairwise computation.\n distance_callable: Callable[[np.ndarray, np.ndarray], float]\n No_python distance callable to measure the distance between two 2d numpy\n arrays.\n\n Returns\n -------\n np.ndarray (2d of size mxn where m is len(x) and n is len(y)).\n Pairwise distance matrix between the two timeseries.\n \"\"\"\n _x = _check_numba_pairwise_series(x)\n _y = _check_numba_pairwise_series(y)\n\n x_size = _x.shape[0]\n y_size = _y.shape[0]\n\n pairwise_matrix = np.zeros((x_size, y_size))\n\n for i in range(x_size):\n curr_x = _x[i]\n for j in range(y_size):\n if symmetric and j < i:\n pairwise_matrix[i, j] = pairwise_matrix[j, i]\n else:\n pairwise_matrix[i, j] = distance_callable(curr_x, _y[j])\n\n return pairwise_matrix\n\n\ndef is_no_python_compiled_callable(\n no_python_callable: Callable, raise_error: bool = False\n):\n \"\"\"Check if a callable is no_python compiled.\n\n Parameters\n ----------\n no_python_callable: Callable\n Callable to check if no_python compiled.\n raise_error: bool, defaults = False\n Boolean that when True will raise an error if the callable is not no_python\n compiled.\n\n Returns\n -------\n bool\n True if the callable is no_python compiled, False if the callable is not\n no_python compiled\n\n Raises\n ------\n ValueError\n If the raise_error parameter is True and the callable passed is not no_python\n compiled.\n \"\"\"\n is_no_python_callable = hasattr(no_python_callable, \"signatures\")\n if raise_error and not is_no_python_callable:\n raise ValueError(\n f\"The callable provided must be no_python compiled. The callable that \"\n f\"caused\"\n f\"this error is named {no_python_callable.__name__}\"\n )\n\n return is_no_python_callable\n\n\ndef to_numba_pairwise_timeseries(x: np.ndarray) -> np.ndarray:\n \"\"\"Convert a timeseries to a valid timeseries for numba pairwise use.\n\n Parameters\n ----------\n x: np.ndarray (1d, 2d or 3d array)\n A timeseries.\n\n Returns\n -------\n np.ndarray (3d array)\n 3d array that is the formatted pairwise timeseries.\n\n Raises\n ------\n ValueError\n If the value provided is not a numpy array\n If the matrix provided is greater than 3 dimensions\n \"\"\"\n if not isinstance(x, np.ndarray):\n raise ValueError(\n f\"The value {x} is an invalid timeseries. To perform a \"\n f\"distance computation a numpy arrays must be provided.\"\n )\n\n _x = np.array(x, copy=True, dtype=np.float)\n num_dims = _x.ndim\n if num_dims == 1:\n shape = _x.shape\n _x = np.reshape(_x, (1, 1, shape[0]))\n elif num_dims == 2:\n shape = _x.shape\n _x = np.reshape(_x, (shape[0], shape[1], 1))\n elif num_dims == 3:\n shape = _x.shape\n _x = np.reshape(_x, (shape[0], shape[1], shape[2]))\n elif num_dims > 3:\n raise ValueError(\n \"The matrix provided has more than 3 dimensions. This is not\"\n \"supported. Please provide a matrix with less than \"\n \"3 dimensions\"\n )\n return _x\n\n\ndef to_numba_timeseries(x: np.ndarray) -> np.ndarray:\n \"\"\"Convert a timeseries to a valid timeseries for numba use.\n\n Parameters\n ----------\n x: np.ndarray (1d or 2d)\n A timeseries.\n\n Returns\n -------\n np.ndarray (2d array)\n 2d array that is the formatted timeseries.\n\n Raises\n ------\n ValueError\n If the value provided is not a numpy array\n If the matrix provided is greater than 2 dimensions\n \"\"\"\n if not isinstance(x, np.ndarray):\n raise ValueError(\n f\"The value {x} is an invalid time series. To perform a\"\n f\"distance computation a numpy array must be provided.\"\n )\n\n _x = np.array(x, copy=True, dtype=np.float)\n num_dims = _x.ndim\n shape = _x.shape\n if num_dims == 1:\n _x = np.reshape(_x, (shape[0], 1))\n if num_dims == 2 and shape[0] == 1:\n _x = np.reshape(_x, (shape[1], shape[0]))\n\n elif num_dims > 2:\n raise ValueError(\n \"The matrix provided has more than 2 dimensions. This is not\"\n \"supported. Please provide a matrix with less than \"\n \"2 dimensions\"\n )\n return _x\n"
] | [
[
"numpy.testing.assert_array_almost_equal",
"numpy.argmax",
"numpy.array",
"numpy.random.RandomState",
"sklearn.metrics.accuracy_score"
],
[
"numpy.reshape",
"numpy.array",
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
carderne/msoa-income | [
"2cfaef3e1942ba6f97b963cbc02472a154fae6d6"
] | [
"join.py"
] | [
"import sys\n\nimport pandas as pd\nimport geopandas as gpd\n\n\ndef main(csv, gpkg, out):\n df = pd.read_csv(csv).assign(\n Income=lambda x: pd.to_numeric(x.Income.str.replace(\",\", \"\"))\n )\n\n gpd.read_file(gpkg).get([\"MSOA01CD\", \"geometry\"]).merge(\n df, how=\"inner\", left_on=\"MSOA01CD\", right_on=\"MSOA\"\n ).to_file(out)\n\n\nif __name__ == \"__main__\":\n csv = sys.argv[1]\n gpkg = sys.argv[2]\n out = sys.argv[3]\n main(csv, gpkg, out)\n"
] | [
[
"pandas.read_csv"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
SamanKhamesian/Human-Activity-Recognition-Time-Series-Classification | [
"1b1d8474997ddf3c0f22791acecdfd823b9de5fd"
] | [
"Source/lstm.py"
] | [
"import os\n\nimport tensorflow as tf\nfrom keras.layers import LSTM, Dense, Dropout\nfrom keras.models import Sequential\n\nfrom Source.config import Model\nfrom Source.driver import Driver\n\ntf.logging.set_verbosity(tf.logging.ERROR)\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n\n\ndef run():\n dataset = Driver()\n\n n_time_steps = dataset.x_train.shape[1]\n n_output = dataset.y_train.shape[1]\n n_features = dataset.x_train.shape[2]\n\n model = LSTMModel(n_time_steps, n_output, n_features)\n model.fit(x_train=dataset.x_train, y_train=dataset.y_train)\n\n accuracy = model.evaluate(x_test=dataset.x_test, y_test=dataset.y_test)\n print('Accuracy = %{0:.4f}'.format(accuracy * 100))\n print(model.model.summary())\n\n\nclass LSTMModel:\n def __init__(self, n_time_steps, n_output, n_features):\n self.model = Sequential()\n self.model.add(LSTM(units=Model.N_NODES, input_shape=(n_time_steps, n_features)))\n # Use Dropout layer to reduce overfitting of the model to the training data\n self.model.add(Dropout(Model.DROPOUT_RATE))\n self.model.add(Dense(Model.N_NODES, activation='relu'))\n # Add output layer with 6 (Total number of classes) nodes with softmax activation function\n self.model.add(Dense(n_output, activation='softmax'))\n # Compile model\n self.model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n\n def fit(self, x_train, y_train, epochs=15, batch_size=64, verbose=0):\n self.model.fit(x=x_train, y=y_train, epochs=epochs, batch_size=batch_size, verbose=verbose)\n\n def predict(self, x_test, batch_size=64):\n return self.model.predict(x=x_test, batch_size=batch_size)\n\n def evaluate(self, x_test, y_test, batch_size=64, verbose=0):\n _, accuracy = self.model.evaluate(x=x_test, y=y_test, batch_size=batch_size, verbose=verbose)\n return accuracy\n\n\nif __name__ == '__main__':\n run()\n"
] | [
[
"tensorflow.logging.set_verbosity"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
UWSEDS-aut17/uwseds-group-maximize-savings-in-clean-energy | [
"c485c5e1f5bea1135b013835d28227f858a68c4d"
] | [
"sundial/price_model/parameter_tuning.py"
] | [
"import numpy as np\nfrom matplotlib import pyplot as plt\nimport seaborn as sns\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import linear_model\nfrom sklearn import neighbors\nfrom sklearn import svm\nfrom sklearn.model_selection import GridSearchCV\nfrom sundial.price_model.utils.file_utils import *\nfrom sundial.price_model.utils.settings import *\nimport multiprocessing\n\n\ndef get_train_test_data(df_price_frame):\n df_price_frame = df_price_frame.dropna()\n X_price_frame = df_price_frame.drop('lmp_value', axis=1).\\\n reset_index().drop('time', axis=1)\n Y_price_frame = df_price_frame['lmp_value']\n return train_test_split(X_price_frame, Y_price_frame, shuffle=False)\n\n\ndef tune_models(df_price_frame):\n \"\"\"\n tune models using different regressors\n :param df_price_frame:\n :return:\n \"\"\"\n x_train, x_test, y_train, y_test = \\\n get_train_test_data(df_price_frame)\n tune_svr(x_train, y_train, x_test, y_test)\n tune_knn(x_train, y_train, x_test, y_test)\n tune_lin_reg(x_train, y_train, x_test, y_test)\n\n\ndef tune_svr(x_train, y_train, x_test, y_test):\n \"\"\"\n SVR regressor with grid search\n :param x_train:\n :param y_train:\n :param x_test:\n :param y_test:\n :return:\n \"\"\"\n C_range = range(1000, 3000, 1000)\n tuned_parameters = [{\n \"C\": C_range,\n \"kernel\": [\"rbf\"]\n }]\n svr_reg = GridSearchCV(svm.SVR(gamma=0.001, epsilon=10),\n param_grid=tuned_parameters, verbose=1,\n n_jobs=multiprocessing.cpu_count())\n y_pred = svr_reg.fit(x_train, y_train).predict(x_test)\n\n print('Optimum parameters epsilon and kernel for SVR: ',\n svr_reg.best_params)\n\n print(\"The test score R2 for SVR: \", svr_reg.score(x_test, y_test))\n\n print(\"SVR mean squared error: %.2f\"\n % np.mean((y_test - svr_reg.predict(x_test)) ** 2))\n\n target_folder = os.path.join(PLOTS_FOLDER, \"svr\")\n make_dir(target_folder)\n plot_predictions(x_test, y_test, y_pred, \"svr\", target_folder)\n plot_pred_test_relation(y_test, y_pred, \"svr\", target_folder)\n\n\ndef tune_knn(x_train, y_train, x_test, y_test):\n \"\"\"\n KNN regressor with grid search\n :param x_train:\n :param y_train:\n :param x_test:\n :param y_test:\n :return:\n \"\"\"\n n_range = range(1, 10, 1)\n tuned_parameters = [{\n \"n_neighbors\": n_range\n }]\n knn_reg = GridSearchCV(neighbors.KNeighborsRegressor(),\n param_grid=tuned_parameters, verbose=1,\n n_jobs=multiprocessing.cpu_count())\n y_pred = knn_reg.fit(x_train, y_train).predict(x_test)\n\n print('Optimum parameters epsilon and kernel for KNN: ',\n knn_reg.best_params_)\n\n print(\"The test score R2 for KNN: \", knn_reg.score(x_test, y_test))\n\n print(\"KNN mean squared error: %.2f\"\n % np.mean((y_test - knn_reg.predict(x_test)) ** 2))\n\n target_folder = os.path.join(PLOTS_FOLDER, \"knn\")\n make_dir(target_folder)\n plot_predictions(x_test, y_test, y_pred, \"knn\", target_folder)\n plot_pred_test_relation(y_test, y_pred, \"knn\", target_folder)\n\n\ndef tune_lin_reg(x_train, y_train, x_test, y_test):\n \"\"\"\n Linear regressor with grid search\n :param x_train:\n :param y_train:\n :param x_test:\n :param y_test:\n :return:\n \"\"\"\n lin_reg = linear_model.LinearRegression(normalize=True)\n y_pred = lin_reg.fit(x_train, y_train).predict(x_test)\n\n print(\"The test score R2 for Lin Reg: \", lin_reg.score(x_test, y_test))\n\n print(\"Lin Reg mean squared error: %.2f\"\n % np.mean((y_test - lin_reg.predict(x_test)) ** 2))\n\n target_folder = os.path.join(PLOTS_FOLDER, \"lin\")\n make_dir(target_folder)\n plot_predictions(x_test, y_test, y_pred, \"lin\", target_folder)\n plot_pred_test_relation(y_test, y_pred, \"lin\", target_folder)\n\n\ndef plot_predictions(x_test, y_test, y_pred, model_name, path):\n \"\"\"\n plot predictions from models\n :param x_test:\n :param y_test:\n :param y_pred:\n :param model_name:\n :param path:\n :return:\n \"\"\"\n plt.figure(figsize=(15, 7))\n plt.scatter(x_test.index, y_test, c='k', label='Observed')\n plt.plot(x_test.index, y_pred, c='r', label='Predicted')\n plt.xlabel('data')\n plt.ylabel('lmp_value')\n plt.title(model_name)\n plt.legend()\n plt.savefig(os.path.join(path, \"{0}_predictions\".format(model_name)))\n\n\ndef plot_pred_test_relation(y_test, y_pred, model_name, path):\n \"\"\"\n plot the confusion matrix type graph\n :param y_test:\n :param y_pred:\n :param model_name:\n :param path:\n :return:\n \"\"\"\n plt.figure(figsize=(6, 6))\n plt.scatter(y_test, y_test, c='k')\n plt.scatter(y_test, y_pred, c='r')\n plt.xlabel('Observed Elec. Price (MWhr)')\n plt.ylabel(\"Predicted Elec. Price (MWWh): $\\hat{Y}_i$\")\n plt.title(\"Energy vs Predicted Energy: $Y_i$ vs $\\hat{Y}_i$ \" + model_name)\n plt.savefig(os.path.join(path, \"{0}_relation\".format(model_name)))\n\n\ndef main():\n price_frame = pd.read_csv(PRICE_DATA_FILENAME, index_col=0)\n df_price_frame = price_frame.set_index(\"time\")\n tune_models(df_price_frame)\n\n\nif __name__ == '__main__':\n main()\n"
] | [
[
"matplotlib.pyplot.legend",
"pandas.read_csv",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.title",
"sklearn.model_selection.train_test_split",
"matplotlib.pyplot.plot",
"sklearn.svm.SVR",
"matplotlib.pyplot.ylabel",
"sklearn.neighbors.KNeighborsRegressor",
"sklearn.linear_model.LinearRegression",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.figure"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
yosukefk/plotter | [
"16127ee7fc3105c717e92875ee3d61477bd41533"
] | [
"demo/work_pretty_trio.py"
] | [
"#!/usr/bin/env python3\nimport sys\n\nplotterdir = '..'\nsys.path.insert(0, plotterdir)\n\nfrom plotter import calpost_reader\nimport plotter.plotter_multi as plotter_multi\nfrom plotter.plotter_util import LambertConformalTCEQ\nfrom plotter.plotter_background import BackgroundManager\nimport cartopy.crs as ccrs\n\nimport geopandas as gpd\nimport matplotlib as mpl\nimport matplotlib.colors as colors\nfrom shapely.geometry import Polygon\nfrom adjustText import adjust_text\n\nimport numpy as np\n\nfrom pathlib import Path\nfrom multiprocessing import Pool\nimport shlex\nimport subprocess\nimport socket\nimport sys\n\n# save better resolution image \nmpl.rcParams['savefig.dpi'] = 300\n\n# input directory/file names\nddir = Path(plotterdir) / 'data'\n\n# input file names\nif len(sys.argv) > 1:\n site = sys.argv[1].upper()\nelse:\n site = 'S2'\nfnames = [\n 'tseries_ch4_1min_conc_toy_all.dat',\n f'tseries_ch4_1min_conc_un_co_{site.lower()}.dat', # continuous upset\n f'tseries_ch4_1min_conc_un_pu_{site.lower()}.dat', # pulsate upset\n ]\n\n# intermediate\nwdir = Path('./img9')\n\n# output\nodir = Path('.')\noname = f'tseries_ch4_1min_conc_co_all_un_{site.lower()}.mp4'\n\n# prep workdir\nif not wdir.is_dir():\n wdir.mkdir()\nelse:\n for f in wdir.glob('*.png'):\n try:\n f.unlink()\n except OSError as e:\n print(\"Error: %s : %s\" % (f, e.strerror))\n\n# aux inputs\nbgfile = Path(plotterdir) / 'resources/naip_toy_pmerc_5.tif'\nshpfile = Path(plotterdir) / 'resources/emitters.shp'\n\n\n# source locations\ndf_shp = gpd.read_file(shpfile)\ndf_shp = df_shp.to_crs('EPSG:3857')\n\n# title to use for each input\ntitles = ['Regular Sources', f'Unintended,\\nContinuous {site}',\n f'Unintended,\\nPulsated {site}']\n\n# read the data\ndata = []\nfor fname in fnames:\n with open(ddir / fname) as f:\n dat = calpost_reader.Reader(f)\n data.append(dat)\n\n# grab necessary info\narrays = [dat['v'] for dat in data]\ntstamps = data[0]['ts']\ngrid = data[0]['grid']\n\n# get horizontal extent \nextent = [\n grid['x0'], grid['x0'] + grid['nx'] * grid['dx'],\n grid['y0'], grid['y0'] + grid['ny'] * grid['dy'],\n]\n\n# distance in calpost is in km\nextent = [_ * 1000 for _ in extent]\nx = dat['x'] * 1000\ny = dat['y'] * 1000\n\n# convert unit of array from g/m3 tp ppb\n# mwt g/mol\n# molar volume m3/mol\narrays = [arr / 16.043 * 0.024465403697038 * 1e9 for arr in arrays]\n\n# Mrinali/Gary's surfer color scale\ncmap = colors.ListedColormap([\n '#D6FAFE', '#02FEFF', '#C4FFC4', '#01FE02',\n '#FFEE02', '#FAB979', '#EF6601', '#FC0100', ])\ncmap.set_under('#FFFFFF')\ncmap.set_over('#000000')\n# Define a normalization from values -> colors\nbndry = [1, 10, 50, 100, 200, 500, 1000, 2000]\nnorm = colors.BoundaryNorm(bndry, len(bndry))\n\nplotter_options = {\n 'background_manager': BackgroundManager(bgfile=bgfile,),\n 'contour_options': {\n 'levels': bndry,\n 'cmap': cmap,\n 'norm': norm,\n 'alpha': .5,\n 'extend': 'max',\n },\n 'title_options': {'fontsize': 'medium'},\n 'colorbar_options': None,\n 'customize_once': [\n # emission points\n lambda p: df_shp.plot(ax=p.ax, column='kls', categorical=True, legend=False, zorder=10,\n markersize=2,\n # got red/blue/yellow from colorbrewer's Set1\n cmap=colors.ListedColormap(['#e41a1c', '#377eb8', '#ffff33'])\n ),\n # Shannon's \"original\" box\n lambda p: p.ax.add_geometries(\n [Polygon([(-101.8834373, 31.71350603),\n (-101.8664281, 31.71727773),\n (-101.8748762, 31.75052556),\n (-101.8942724, 31.74599821),\n (-101.8834373, 31.71350603),\n ])],\n crs=ccrs.PlateCarree(), facecolor='none', edgecolor='white', lw=.6,\n ),\n # modeled box\n lambda p: p.ax.add_geometries(\n [Polygon([(extent[x], extent[y]) for x, y in ((0, 2), (0, 3), (1, 3), (1, 2), (0, 2))])],\n crs=LambertConformalTCEQ(), facecolor='none', edgecolor='white', lw=.6, ls='--',\n ),\n\n ]}\n\n# clone the options and let each has own title\nplotter_options = [{**plotter_options, 'title': title} for title in titles]\n\n# colorbar goes to entire figure\nfigure_options = {\n 'colorbar_options': {\n 'label': r'$CH_4$ (ppbV)',\n }\n }\n\n# make a plot template\np = plotter_multi.Plotter(arrays=arrays, tstamps=tstamps, \n x=x, y=y, projection=LambertConformalTCEQ(),\n plotter_options=plotter_options,\n figure_options=figure_options)\n\n\n# make single image file (for QA)\nntsteps = len(tstamps)\np.savefig((odir / oname).with_suffix('.png'), \n tidx=min(16*60,ntsteps-1))\n\n# make mpeg file\np.savemp4(odir / oname, wdir=wdir )\n"
] | [
[
"matplotlib.colors.ListedColormap"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
humans-to-robots-motion/lgp | [
"f62da0c0cb7a209eb90848cce8eddc91c14fa099"
] | [
"lgp/geometry/transform.py"
] | [
"import numpy as np\nfrom pyrieef.geometry.differentiable_geometry import DifferentiableMap\n\n\nclass LinearTranslation(DifferentiableMap):\n \"\"\"\n Simple linear translation\n \"\"\"\n\n def __init__(self, p0=np.zeros(2)):\n assert isinstance(p0, np.ndarray)\n self._p = p0\n\n def forward(self, q):\n assert q.shape[0] == self.input_dimension\n return self._p + q\n\n def backward(self, p): # p is coordinate in parent frame\n assert p.shape[0] == self.output_dimension\n return p - self._p\n\n def jacobian(self, q):\n assert q.shape[0] == self.input_dimension\n return np.eye(self.input_dimension)\n\n @property\n def input_dimension(self):\n return self._p.shape[0]\n\n @property\n def output_dimension(self):\n return self.input_dimension\n"
] | [
[
"numpy.eye",
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
MGarrod1/rgg_ensemble_analysis | [
"679ea7b11c0eae4d92eef9f08fe9c63dcfd3837c"
] | [
"rgg_ensemble_analysis/Statistics_Computation.py"
] | [
"\"\"\"\n\nFunctions to compute various statistics of the data\nand their associated errors.\n\n\"\"\"\n\n\n#Compute statistics about the variance of an estimator:\n\nimport numpy as np \nfrom scipy import stats\nimport math\n\n#The following functions as involved in estimating the standard \n\ndef Moment(Sample,k) :\n\n\t\"\"\"\n\tThis function computes the kth moment of the\n\tSample.\n\t\n\t\"\"\"\n\tMean = np.mean(Sample)\n\t\n\tMoment = 0.0\n\tfor i in range(0,len(Sample) ) :\n\t\tMoment = Moment + (Mean - Sample[i] )**k \n\t\t\n\treturn Moment/(len(Sample))\n\t\ndef D4(Sample) :\n\t\"\"\"Compute the fourth central moment of a sample\n\tSee: https://en.wikipedia.org/wiki/Central_moment\n\tfor defintion\"\"\"\n\tM = float( len(Sample) )\n\tD4 = ((M-1)/(M**3))*( (M**2 - 3*M + 3)*Moment(Sample,4) + 3*(2*M -3)*Moment(Sample,2)**2 )\n\t\n\treturn D4\n\t\ndef VarSE(Sample) :\n\n\n\t\"\"\"\n\tReturns the standard error on the variance of the sample given.\n\t\n\tFormula taken from: \n\tWonnapinij, Passorn, Patrick F. Chinnery, and David C. Samuels. \"Previous estimates of mitochondrial DNA mutation level variance \tdid not account for sampling error: comparing the mtDNA genetic bottleneck in mice and humans.\" The American Journal of Human \tGenetics 86.4 (2010): 540-550.\n\t\n\tParameters\n\t-----------\n\t\n\tSample : list\n\t\n\tlist of values\n\t\n\tReturns\n\t-----------\n\t\n\tSE : float\n\t\n\tStandard error on the variance of a sample\n\t\n\t\n\t\"\"\"\n\n\n\tM = float( len(Sample) )\n\t\n\tSE = ( (1.0/M)*(D4(Sample) - ( (M-3)/(M-1) )*np.var(Sample)**2 ) )**0.5\n\n\treturn SE\n\t\ndef CV(Sample) : \n\n\t\"\"\"\n\tComputes the coefficient of variation of the values.\n\t\n\tArguments\n\t------------\n\t\n\tSample : list\n\t\n\t\n\t\"\"\"\n\treturn np.std(Sample)/np.mean(Sample)\n\t\ndef CV_Error(Sample) :\n\t\"\"\"\n\tCompute the standard error on the coefficient of variation.\n\t\"\"\"\n\ttry :\n\t\tpart1 = (VarSE(Sample)/( 2.0*(np.var(Sample)**0.5)*np.mean(Sample) ) )**2\n\t\tpart2 = ( (((np.var(Sample))**0.5 )*stats.sem(Sample)/(np.mean(Sample)**2) ) )**2\n\t\tCoeff_ERR = ( part1 + part2 )**0.5\n\texcept :\n\t\tprint(\"Error encountered\")\n\t\tprint(\"Sample length = \" + str(len(Sample)))\n\t\tprint(\"Setting error to zero by defulat\")\n\t\tCoeff_ERR = 0.0\n\n\n\treturn Coeff_ERR\n\t\n\n\t\n#Bootsrapping Tools:\n\n#Given a sample we can estimate the standard error in the variance\ndef Bootstrap_SE(Sample,Redraws) :\n\tData_Points = len(Sample)\n\tVar = np.var(Sample)\n\n\tVars = [ ]\n\t\n\tfor j in range(0,Redraws) : \n\t\tSample2 = [ ]\n\t\tfor i in range(0,(len(Sample))) :\n\t\t\t#Draw a random integar less than the sample size\n\t\t\tEntry = int(math.floor( np.random.uniform(0, (len(Sample)), 1) ) )\n\t\t\tSample2.append(Sample[Entry]) \n\t\tNew_Var = np.var(Sample2)\n\t\tVars.append(New_Var)\n\t\n\t \n\t\n\tVar_SE = stats.sem(Vars)\n\t\t\n\treturn (Redraws**0.5)*Var_SE\n\t\ndef Bootstrap_Mean_SE(Sample,Redraws) :\n\tData_Points = len(Sample)\n\t\n\tMean = np.mean(Sample)\n\n\tMeans = [ ]\n\t\n\tfor j in range(0,Redraws) : \n\t\tSample2 = [ ]\n\t\t\n\t\tfor i in range(0,(len(Sample))) :\n\t\t\t#Draw a random integar less than the sample size\n\t\t\tEntry = int(math.floor( np.random.uniform(0, (len(Sample)), 1) ) )\n\t\t\tSample2.append(Sample[Entry]) \n\t\t\t\t\n\t\tNew_Mean = np.mean(Sample2)\n\t\tMeans.append(New_Mean)\n\t\n\t \n\t\n\tMean_SE = stats.sem(Means)\n\tBoot_Mean = np.mean(Means)\n\t\t\n\treturn (Redraws**0.5)*Mean_SE\n\t\n\n\ndef Get_Spearman_Correlation(Array_1, Array_2, P_Val_Threshold=(10 ** (-4))):\n\t\n\t\"\"\"\n\tReturns the correlation between two arrays.\n\n\tIf p val > 10^-4 we simply report the correlation as zero\n\t\n\tParameters\n\t--------------\n\t\n\tArray_1 : list\n\t\n\t\n\tArray_2 : list\n\t\n\tP_Val_Threshold :float\n\t\n\tSet a threshold for the p-value. If the p value\n\tif greater than this threshold then we can set\n\tthe correlation to zero (ie. we are not confident\n\tthat the correlation exists). \n\n\t\"\"\"\n\t\n\tP_Val_Threshold = 1.1\n\tCorrelation, pval = stats.spearmanr(Array_1, Array_2)\n\n\tif pval < P_Val_Threshold:\n\t\treturn Correlation\n\n\telse:\n\t\treturn 0.0\n\n\ndef Bootstrap_Correlation_Confid_Int(Sample_1, Sample_2, Redraws=50):\n\t\"\"\"\n\n\tUse the bootstrapping method to estimate the confidence interval on the\n\tSpearman Correlation\n\n\tReturns the 95% confidence interval by default\n\n\t(Does p-value threshold want to be an additional argument?)\n\n\tParameters\n\t--------------\n\n\tSample_1 : list\n\n\tFirst sample\n\n\tSample_2 : list\n\n\tSecond sample\n\n\tRedraws : int\n\n\tNumber of times to same with replacement from the joint distribution\n\tof sample_1 and sample_2\n\n\n\tReturns\n\t-----------\n\n\t95% confidence interval on the Spearman correlation.\n\n\t\"\"\"\n\n\tData_Points = len(Sample_1)\n\n\tOriginal_Correlation = Get_Spearman_Correlation(Sample_1, Sample_2, P_Val_Threshold=20.0)\n\n\tCorrelations = []\n\tDifferences = []\n\n\tfor j in range(0, Redraws):\n\t\tSample2 = []\n\n\t\tRedraw_Sample_1 = []\n\t\tRedraw_Sample_2 = []\n\n\t\t# Redraw the samples:\n\t\tfor i in range(0, (len(Sample_1))):\n\t\t\t#Redraw pairs of values:\n\t\t\tEntry = int(math.floor(np.random.uniform(0, (len(Sample_1)), 1)))\n\t\t\tRedraw_Sample_1.append(Sample_1[Entry])\n\t\t\tRedraw_Sample_2.append(Sample_2[Entry])\n\n\t\tRedrawn_Correlation = Get_Spearman_Correlation(Redraw_Sample_1, Redraw_Sample_2, P_Val_Threshold=20.0)\n\t\tCorrelations.append(Redrawn_Correlation)\n\t\tDifferences.append(Redrawn_Correlation - Original_Correlation)\n\n\t# sort the list of differences:\n\tSorted_Differences = np.sort(Differences)\n\t\n\treturn Sorted_Differences[int(math.ceil(0.95 * len(Differences)))]\n\n\n"
] | [
[
"numpy.sort",
"numpy.std",
"numpy.mean",
"numpy.var",
"scipy.stats.spearmanr",
"scipy.stats.sem"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"0.13",
"1.6",
"0.14",
"1.10",
"0.15",
"1.4",
"1.3",
"1.9",
"0.19",
"1.5",
"0.18",
"1.2",
"1.7",
"0.12",
"1.0",
"0.17",
"0.16",
"1.8"
],
"tensorflow": []
}
] |
liggest/RGBDFace | [
"75768b1848f03d3e9d53913546b19cce0b1ada67"
] | [
"RGBDFace/utils/face.py"
] | [
"import numpy as np\n# import open3d as o3d\nimport face_recognition\n# import cv2\nfrom skimage import draw #,morphology\n\n\n# from .depth import depthPreprocess\nfrom .image import getConvexHullMask,getMaskedImg2, maskClosing,maskDilation,maskErosion\n\ndef faceLandmarks(image):\n '''\n 人脸边框+特征点\n '''\n image=np.asarray(image)\n locations=face_recognition.face_locations(image)\n if not locations:\n return None,None\n landmarks=face_recognition.face_landmarks(image,face_locations=locations)\n return locations,landmarks\n\ndef getLandmarkPoints(landmarks):\n '''\n 将特征点变成列表形式\n '''\n facePoints=None\n for face in landmarks:\n for v in face.values():\n if facePoints is None:\n facePoints=np.asarray(v)\n else:\n facePoints=np.vstack([facePoints,np.asarray(v)])\n return facePoints\n\ndef depthFilter(points,depth,dthreshold=1.0):\n '''\n 过滤无深度的点,计算有深度的点在所有点中的比例\n '''\n depth=np.asarray(depth)\n imSize=depth.shape # h,w\n l=len(points)\n pnum=0\n #resultPoints=[None]*l\n resultPoints=[ np.asarray([np.nan,np.nan]) ]*l\n for i,p in enumerate(points):\n if 0<=p[1]<imSize[0] and 0<=p[0]<imSize[1] and 0<depth[p[1],p[0]]<=dthreshold:\n resultPoints[i]=p\n pnum+=1\n #resultPoints=np.asarray(resultPoints,dtype=np.object)\n resultPoints=np.asarray(resultPoints) # dtype:float64\n return resultPoints,pnum/l\n\ndef processFaceRGBD(rgbd,depthThreshold=1.0,rateThreshold=0.75):\n '''\n 从RGBD图像中得到人脸边框、特征点(语义字典)、特征点(点集)、深度筛选过的特征点、有深度特征点的比例\n '''\n return processFaceImgPair(rgbd.color,rgbd.depth,depthThreshold=depthThreshold,rateThreshold=rateThreshold)\n\ndef processFaceImgPair(color,depth,depthThreshold=1000,rateThreshold=0.75):\n '''\n 从color、depth图像对中得到人脸边框、特征点(语义字典)、特征点(点集)、深度筛选过的特征点、有深度特征点的比例\n '''\n locations,landmarks=faceLandmarks(color)\n if locations is None:\n print(\"未检测到人脸\")\n return False,None,None,None,None,None\n facePoints=getLandmarkPoints(landmarks)\n facePointsFilt,depthRate=depthFilter(facePoints,depth,dthreshold=depthThreshold)\n if depthRate<rateThreshold:\n print(\"脸部特征点中有深度的点所占比例小于阈值\")\n return False,None,None,None,None,None\n #facePoints=np.asarray(facePoints,dtype=np.object)\n return True,locations,landmarks,facePoints,facePointsFilt,depthRate\n\ndef getCorrespondence(points,points2):\n '''\n 得到两点集的对应点(下标相同且不为[nan,nan])\n '''\n minlen=min( points.shape[0],points2.shape[0] )\n points=points[:minlen,:]\n points2=points2[:minlen,:]\n return np.where( ~np.isnan(points).any(axis=1) & ~np.isnan(points2).any(axis=1) )[0]\n\n\n# def getCorrespondence2(points,points2):\n# '''\n# 得到两点集的对应点(下标相同且不为None)\n# '''\n# minlen=min(points.shape[0],points2.shape[0])\n# corrIdxs=[]\n# for i in range(minlen):\n# if not(points[i] is None or points2[i] is None):\n# corrIdxs.append(i)\n# return np.asarray(corrIdxs)\n\n\ndef getFaceCircle(img,facePoints,faceConvexHull,rRate=1.2):\n '''\n 通过人脸特征点,得到包裹脸的圆形遮罩\n '''\n idxs=np.asarray( np.where(faceConvexHull>0.5) )\n centroid=np.sum(idxs,axis=1)/idxs.shape[1] #质心\n distances=np.linalg.norm(facePoints-centroid[::-1],axis=1) #[x y]\n maxDistance=distances.max()\n r=maxDistance*rRate\n center=np.int_(centroid) # [y x]\n cr,cc=draw.disk(center,r,shape=img.shape) # [y x]\n mask=np.zeros_like(img,dtype=np.bool)\n mask[cr,cc]=True\n\n #试着在圆上接个方块\n # p1=np.asarray( [center[0],center[1]-int(r)],dtype=np.int64 )\n # p2=np.asarray( [-1,center[1]+int(r)],dtype=np.int64 )\n # cr,cc=draw.rectangle(start=p1,end=p2,shape=img.shape)\n # mask[cr,cc]=True\n mask[:center[0]+1,center[1]-int(r):center[1]+int(r)+1]=True\n\n return mask\n\ndef getFaceMask(depth,landmarks,facePoints=None,circleRate=1.2):\n '''\n 通过人脸特征点,得到包裹脸的圆形遮罩(除去眼、嘴)\n '''\n leftEye= np.asarray( landmarks[0][\"left_eye\"] )\n rightEye= np.asarray( landmarks[0][\"right_eye\"] )\n mouth= set(landmarks[0][\"top_lip\"]).union( set(landmarks[0][\"bottom_lip\"]) )\n mouth=np.asarray(list(mouth))\n leftEyeMask=getConvexHullMask(depth,leftEye)\n rightEyeMask=getConvexHullMask(depth,rightEye)\n mouthMask=getConvexHullMask(depth,mouth)\n fullMask=leftEyeMask | rightEyeMask | mouthMask\n # disk=morphology.disk(10)\n # disk=morphology.disk(12)\n # fullMaskDila=morphology.binary_dilation(fullMask,selem=disk) \n fullMaskDila=maskDilation(fullMask,size=12) #膨胀嘴、脸遮罩\n\n if facePoints is None:\n facePoints=getLandmarkPoints(landmarks)\n \n faceConvexHull=getConvexHullMask(depth,facePoints)\n faceCircleMask=getFaceCircle(np.asarray(depth),facePoints,faceConvexHull,rRate=circleRate)\n faceMask=faceCircleMask ^ fullMaskDila #取相异的部分,即圆里扣去眼、嘴\n return faceCircleMask,faceMask,faceConvexHull\n\ndef getFaceMeanMask(depth,faceConvexHull,depthMask,maxMeanDiff=100):\n '''\n 以人脸特征点组成的凸包为范围,求人脸的深度均值,得到能够滤除均值+-maxMeanDiff范围外深度的遮罩\n '''\n # disk=morphology.disk(5)\n # disk=morphology.disk(10)\n # faceConvexHulle=morphology.binary_erosion(faceConvexHull,selem=disk) \n faceConvexHulle=maskErosion(faceConvexHull,size=10) #腐蚀\n idxs=np.where(faceConvexHulle>0.5)\n faceMean= np.mean( depth[idxs[0],idxs[1]] )\n faceMeanMask=np.asarray( (depth>faceMean-maxMeanDiff )&(depth<faceMean+maxMeanDiff ) & depthMask )\n return faceMeanMask\n\n\n# def processDepth(depth,landmarks,facePoints,cropEyeMouth=True,\n# dmin=100,dmax=1000,filtSize=6,bifiltSize=5,circleRate=1.2,maxMeanDiff=100):\n# '''\n# 预处理深度图像,使用圆形遮罩切出头部,视情况施加遮罩切除眼、嘴 \n# 返回处理后的完整深度图、头部、剩余部分、遮罩列表(完整深度遮罩、脸部遮罩(切除眼、嘴)、脸部圆形遮罩) \n# '''\n# depth,depthMask=depthPreprocess(depth,dmin,dmax,filtSize,bifiltSize)\n# if cropEyeMouth:\n# faceCircleMask,faceMask,faceConvexHull=getFaceMask(depth,landmarks,facePoints,circleRate)\n# else:\n# faceConvexHull=getConvexHullMask(depth,facePoints)\n# faceCircleMask=getFaceCircle(depth,facePoints,faceConvexHull,circleRate)\n# faceMask=faceCircleMask\n\n# faceMeanMask=getFaceMeanMask(depth,faceConvexHull,depthMask,maxMeanDiff=maxMeanDiff) #在脸部均值 +-10cm以外的都会被切掉\n \n# depthMask &=faceMeanMask\n# disk=morphology.disk(2)\n# depthMask=morphology.binary_erosion(depthMask,selem=disk) #腐蚀\n# depthTmp=getMaskedImg2(depth,depthMask)\n\n# masked=getMaskedImg2(depthTmp,faceMask)\n# maskedReverse=getMaskedImg2(depthTmp,faceCircleMask,reverse=True)\n# depthTmp=depthTmp.astype(np.uint16)\n# masked=masked.astype(np.uint16)\n# maskedReverse=maskedReverse.astype(np.uint16)\n# return depthTmp,masked,maskedReverse,[depthMask,faceMask,faceCircleMask,faceConvexHull]\n\ndef processFaceDepth(depth,depthMask,landmarks,facePoints,cropEyeMouth=True,\n circleRate=1.2,maxMeanDiff=100):\n '''\n 预处理深度图像,使用圆形遮罩切出头部,视情况施加遮罩切除眼、嘴 \n 返回处理后的完整深度图、头部、剩余部分、遮罩列表(完整深度遮罩、脸部遮罩(切除眼、嘴)、脸部圆形遮罩) \n '''\n #depth,depthMask=depthPreprocess(depth,dmin,dmax,filtSize,bifiltSize)\n if cropEyeMouth:\n faceCircleMask,faceMask,faceConvexHull=getFaceMask(depth,landmarks,facePoints,circleRate)\n else:\n faceConvexHull=getConvexHullMask(depth,facePoints)\n faceCircleMask=getFaceCircle(depth,facePoints,faceConvexHull,circleRate)\n faceMask=faceCircleMask\n\n faceMeanMask=getFaceMeanMask(depth,faceConvexHull,depthMask,maxMeanDiff=maxMeanDiff) #在脸部均值 +-10cm以外的都会被切掉\n \n depthMask &=faceMeanMask\n # disk=morphology.disk(2)\n # depthMask=morphology.binary_erosion(depthMask,selem=disk) #腐蚀\n # depthMask=maskClosing(depthMask,size=4)\n depthMask=maskErosion(depthMask,size=2) #腐蚀\n depthTmp=getMaskedImg2(depth,depthMask)\n\n masked=getMaskedImg2(depthTmp,faceMask)\n maskedReverse=getMaskedImg2(depthTmp,faceCircleMask,reverse=True)\n depthTmp=depthTmp.astype(np.uint16)\n masked=masked.astype(np.uint16)\n maskedReverse=maskedReverse.astype(np.uint16)\n return depthTmp,masked,maskedReverse,[depthMask,faceMask,faceCircleMask,faceConvexHull]\n"
] | [
[
"numpy.asarray",
"numpy.isnan",
"numpy.linalg.norm",
"numpy.int_",
"numpy.zeros_like",
"numpy.mean",
"numpy.where",
"numpy.sum"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
defensetongxue/pyGAT | [
"5677b15be986b0650b883cdd20dbfb1bb486d6f5"
] | [
"utils.py"
] | [
"import numpy as np\nimport scipy.sparse as sp\nimport torch\nimport json as js\nimport pandas as pd \ndef encode_onehot(labels):\n # The classes must be sorted before encoding to enable static class encoding.\n # In other words, make sure the first class always maps to index 0.\n classes = sorted(list(set(labels)))\n classes_dict = {c: np.identity(len(classes))[i, :] for i, c in enumerate(classes)}\n labels_onehot = np.array(list(map(classes_dict.get, labels)), dtype=np.int32)\n return labels_onehot\n\n\ndef load_data(path=\"./data/cora/\", dataset=\"cora\"):\n \"\"\"Load citation network dataset (cora only for now)\"\"\"\n print('Loading {} dataset...'.format(dataset))\n if dataset=='cora':\n idx_features_labels = np.genfromtxt(\"{}{}.content\".format(path, dataset), dtype=np.dtype(str))\n features = sp.csr_matrix(idx_features_labels[:, 1:-1], dtype=np.float32)\n labels = encode_onehot(idx_features_labels[:, -1])\n\n # build graph\n idx = np.array(idx_features_labels[:, 0], dtype=np.int32)\n idx_map = {j: i for i, j in enumerate(idx)}\n edges_unordered = np.genfromtxt(\"{}{}.cites\".format(path, dataset), dtype=np.int32)\n edges = np.array(list(map(idx_map.get, edges_unordered.flatten())), dtype=np.int32).reshape(edges_unordered.shape)\n adj = sp.coo_matrix((np.ones(edges.shape[0]), (edges[:, 0], edges[:, 1])), shape=(labels.shape[0], labels.shape[0]), dtype=np.float32)\n\n # build symmetric adjacency matrix\n adj = adj + adj.T.multiply(adj.T > adj) - adj.multiply(adj.T > adj)\n\n idx_train = range(140)\n idx_val = range(200, 500)\n idx_test = range(500, 1500)\n \n else: # dataset is chamelon\n file_prefix='./data/chameleon/chameleon_'\n feature_file=open(file_prefix+'features.json','r')\n data=js.load(feature_file)\n features=[]\n node_number=2277\n for i in range(node_number):\n features.append(data[str(i)])\n file_label=open(file_prefix+'target.csv','r')\n labels=pd.read_csv(file_label)\n labels=np.array(labels.target)\n file_label=open(file_prefix+'edges.csv','r')\n edges=pd.read_csv(file_label)\n adj=np.eye(node_number)\n for i,j in zip(edges.id1,edges.id2):\n adj[i][j]=adj[j][i]=1\n \n features = normalize_features(features)\n adj = normalize_adj(adj + sp.eye(adj.shape[0]))\n \n \n adj = torch.FloatTensor(np.array(adj.todense()))\n features = torch.FloatTensor(np.array(features.todense()))\n labels = torch.LongTensor(np.where(labels)[1])\n\n idx_train = torch.LongTensor(idx_train)\n idx_val = torch.LongTensor(idx_val)\n idx_test = torch.LongTensor(idx_test)\n print(idx_train)\n return adj, features, labels, idx_train, idx_val, idx_test\n\n\ndef normalize_adj(mx):\n \"\"\"Row-normalize sparse matrix\"\"\"\n rowsum = np.array(mx.sum(1))\n r_inv_sqrt = np.power(rowsum, -0.5).flatten()\n r_inv_sqrt[np.isinf(r_inv_sqrt)] = 0.\n r_mat_inv_sqrt = sp.diags(r_inv_sqrt)\n return mx.dot(r_mat_inv_sqrt).transpose().dot(r_mat_inv_sqrt)\n\n\ndef normalize_features(mx):\n \"\"\"Row-normalize sparse matrix\"\"\"\n rowsum = np.array(mx.sum(1))\n r_inv = np.power(rowsum, -1).flatten()\n r_inv[np.isinf(r_inv)] = 0.\n r_mat_inv = sp.diags(r_inv)\n mx = r_mat_inv.dot(mx)\n return mx\n\n\ndef accuracy(output, labels):\n preds = output.max(1)[1].type_as(labels)\n correct = preds.eq(labels).double()\n correct = correct.sum()\n return correct / len(labels)\n\n"
] | [
[
"torch.LongTensor",
"pandas.read_csv",
"numpy.power",
"scipy.sparse.eye",
"numpy.eye",
"scipy.sparse.diags",
"scipy.sparse.csr_matrix",
"numpy.dtype",
"numpy.ones",
"numpy.array",
"numpy.where",
"numpy.isinf"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [
"0.13",
"1.6",
"0.14",
"1.10",
"0.15",
"1.4",
"0.16",
"1.9",
"0.19",
"1.5",
"0.18",
"1.2",
"1.7",
"0.12",
"1.0",
"0.17",
"1.3",
"1.8"
],
"tensorflow": []
}
] |
wnorris/models | [
"a5e4965d1f4e4b02d51aa344336b6fff53af7c17",
"a5e4965d1f4e4b02d51aa344336b6fff53af7c17",
"a5e4965d1f4e4b02d51aa344336b6fff53af7c17",
"a5e4965d1f4e4b02d51aa344336b6fff53af7c17"
] | [
"official/projects/yt8m/dataloaders/yt8m_input_test.py",
"official/vision/tasks/retinanet.py",
"official/vision/modeling/decoders/nasfpn.py",
"official/projects/edgetpu/nlp/modeling/edgetpu_layers.py"
] | [
"# Copyright 2022 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\nimport os\n\nfrom absl import logging\nfrom absl.testing import parameterized\nimport numpy as np\nimport tensorflow as tf\n\nfrom official.core import input_reader\nfrom official.projects.yt8m.configs import yt8m as yt8m_configs\nfrom official.projects.yt8m.dataloaders import utils\nfrom official.projects.yt8m.dataloaders import yt8m_input\nfrom official.vision.dataloaders import tfexample_utils\n\n\nclass Yt8mInputTest(parameterized.TestCase, tf.test.TestCase):\n\n def setUp(self):\n super().setUp()\n self._model_dir = os.path.join(self.get_temp_dir(), 'model_dir')\n tf.io.gfile.makedirs(self._model_dir)\n\n data_dir = os.path.join(self.get_temp_dir(), 'data')\n tf.io.gfile.makedirs(data_dir)\n self.data_path = os.path.join(data_dir, 'data.tfrecord')\n self.num_segment = 6\n examples = [utils.MakeYt8mExample(self.num_segment) for _ in range(8)]\n tfexample_utils.dump_to_tfrecord(self.data_path, tf_examples=examples)\n\n def create_input_reader(self, params):\n decoder = yt8m_input.Decoder(input_params=params)\n decoder_fn = decoder.decode\n parser = yt8m_input.Parser(input_params=params)\n parser_fn = parser.parse_fn(params.is_training)\n postprocess = yt8m_input.PostBatchProcessor(input_params=params)\n postprocess_fn = postprocess.post_fn\n transform_batch = yt8m_input.TransformBatcher(input_params=params)\n batch_fn = transform_batch.batch_fn\n\n return input_reader.InputReader(\n params,\n dataset_fn=tf.data.TFRecordDataset,\n decoder_fn=decoder_fn,\n parser_fn=parser_fn,\n postprocess_fn=postprocess_fn,\n transform_and_batch_fn=batch_fn)\n\n @parameterized.parameters((True,), (False,))\n def test_read_video_level_input(self, include_video_id):\n params = yt8m_configs.yt8m(is_training=False)\n params.global_batch_size = 4\n params.segment_labels = False\n params.input_path = self.data_path\n params.include_video_id = include_video_id\n reader = self.create_input_reader(params)\n\n dataset = reader.read()\n iterator = iter(dataset)\n example = next(iterator)\n\n for k, v in example.items():\n logging.info('DEBUG read example %r %r %r', k, v.shape, type(v))\n if include_video_id:\n self.assertCountEqual(\n ['video_matrix', 'labels', 'num_frames', 'video_ids'], example.keys())\n else:\n self.assertCountEqual(['video_matrix', 'labels', 'num_frames'],\n example.keys())\n batch_size = params.global_batch_size\n self.assertEqual(\n example['video_matrix'].shape.as_list(),\n [batch_size, params.max_frames, sum(params.feature_sizes)])\n self.assertEqual(example['labels'].shape.as_list(),\n [batch_size, params.num_classes])\n self.assertEqual(example['num_frames'].shape.as_list(), [batch_size, 1])\n if include_video_id:\n self.assertEqual(example['video_ids'].shape.as_list(), [batch_size, 1])\n\n @parameterized.parameters((True,), (False,))\n def test_read_segement_level_input(self, include_video_id):\n params = yt8m_configs.yt8m(is_training=False)\n params.global_batch_size = 4\n params.segment_labels = True\n params.input_path = self.data_path\n params.include_video_id = include_video_id\n reader = self.create_input_reader(params)\n\n dataset = reader.read()\n iterator = iter(dataset)\n example = next(iterator)\n\n for k, v in example.items():\n logging.info('DEBUG read example %r %r %r', k, v.shape, type(v))\n if include_video_id:\n self.assertCountEqual([\n 'video_matrix', 'labels', 'num_frames', 'label_weights', 'video_ids'\n ], example.keys())\n else:\n self.assertCountEqual(\n ['video_matrix', 'labels', 'num_frames', 'label_weights'],\n example.keys())\n batch_size = params.global_batch_size * self.num_segment\n self.assertEqual(\n example['video_matrix'].shape.as_list(),\n [batch_size, params.segment_size, sum(params.feature_sizes)])\n self.assertEqual(example['labels'].shape.as_list(),\n [batch_size, params.num_classes])\n self.assertEqual(example['num_frames'].shape.as_list(), [batch_size, 1])\n self.assertEqual(example['label_weights'].shape.as_list(),\n [batch_size, params.num_classes])\n if include_video_id:\n self.assertEqual(example['video_ids'].shape.as_list(), [batch_size])\n\n @parameterized.parameters((True,), (False,))\n def test_read_video_level_float_input(self, include_video_id):\n data_dir = os.path.join(self.get_temp_dir(), 'data2')\n tf.io.gfile.makedirs(data_dir)\n data_path = os.path.join(data_dir, 'data2.tfrecord')\n examples = [\n utils.MakeExampleWithFloatFeatures(self.num_segment) for _ in range(8)\n ]\n tfexample_utils.dump_to_tfrecord(data_path, tf_examples=examples)\n\n params = yt8m_configs.yt8m(is_training=False)\n params.global_batch_size = 4\n params.segment_labels = False\n params.input_path = data_path\n params.num_frames = 2\n params.max_frames = 2\n params.feature_names = ('VIDEO_EMBEDDING/context_feature/floats',\n 'FEATURE/feature/floats')\n params.feature_sources = ('context', 'feature')\n params.feature_dtypes = ('float32', 'float32')\n params.feature_sizes = (256, 2048)\n params.feature_from_bytes = (False, False)\n params.include_video_id = include_video_id\n reader = self.create_input_reader(params)\n\n dataset = reader.read()\n iterator = iter(dataset)\n example = next(iterator)\n\n for k, v in example.items():\n logging.info('DEBUG read example %r %r %r', k, v.shape, type(v))\n logging.info('DEBUG read example %r', example['video_matrix'][0, 0, :])\n if include_video_id:\n self.assertCountEqual(\n ['video_matrix', 'labels', 'num_frames', 'video_ids'], example.keys())\n else:\n self.assertCountEqual(['video_matrix', 'labels', 'num_frames'],\n example.keys())\n\n # Check tensor values.\n expected_context = examples[0].context.feature[\n 'VIDEO_EMBEDDING/context_feature/floats'].float_list.value\n expected_feature = examples[0].feature_lists.feature_list[\n 'FEATURE/feature/floats'].feature[0].float_list.value\n expected_labels = examples[0].context.feature[\n params.label_field].int64_list.value\n self.assertAllEqual(\n expected_feature,\n example['video_matrix'][0, 0, params.feature_sizes[0]:])\n self.assertAllEqual(\n expected_context,\n example['video_matrix'][0, 0, :params.feature_sizes[0]])\n self.assertAllEqual(\n np.nonzero(example['labels'][0, :].numpy())[0], expected_labels)\n\n # Check tensor shape.\n batch_size = params.global_batch_size\n self.assertEqual(\n example['video_matrix'].shape.as_list(),\n [batch_size, params.max_frames, sum(params.feature_sizes)])\n self.assertEqual(example['labels'].shape.as_list(),\n [batch_size, params.num_classes])\n self.assertEqual(example['num_frames'].shape.as_list(), [batch_size, 1])\n if include_video_id:\n self.assertEqual(example['video_ids'].shape.as_list(), [batch_size, 1])\n\nif __name__ == '__main__':\n tf.test.main()\n",
"# Copyright 2022 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\"\"\"RetinaNet task definition.\"\"\"\nfrom typing import Any, List, Mapping, Optional, Tuple\n\nfrom absl import logging\nimport tensorflow as tf\n\nfrom official.common import dataset_fn\nfrom official.core import base_task\nfrom official.core import task_factory\nfrom official.vision.configs import retinanet as exp_cfg\nfrom official.vision.dataloaders import input_reader_factory\nfrom official.vision.dataloaders import retinanet_input\nfrom official.vision.dataloaders import tf_example_decoder\nfrom official.vision.dataloaders import tfds_factory\nfrom official.vision.dataloaders import tf_example_label_map_decoder\nfrom official.vision.evaluation import coco_evaluator\nfrom official.vision.losses import focal_loss\nfrom official.vision.losses import loss_utils\nfrom official.vision.modeling import factory\n\n\n@task_factory.register_task_cls(exp_cfg.RetinaNetTask)\nclass RetinaNetTask(base_task.Task):\n \"\"\"A single-replica view of training procedure.\n\n RetinaNet task provides artifacts for training/evalution procedures, including\n loading/iterating over Datasets, initializing the model, calculating the loss,\n post-processing, and customized metrics with reduction.\n \"\"\"\n\n def build_model(self):\n \"\"\"Build RetinaNet model.\"\"\"\n\n input_specs = tf.keras.layers.InputSpec(\n shape=[None] + self.task_config.model.input_size)\n\n l2_weight_decay = self.task_config.losses.l2_weight_decay\n # Divide weight decay by 2.0 to match the implementation of tf.nn.l2_loss.\n # (https://www.tensorflow.org/api_docs/python/tf/keras/regularizers/l2)\n # (https://www.tensorflow.org/api_docs/python/tf/nn/l2_loss)\n l2_regularizer = (tf.keras.regularizers.l2(\n l2_weight_decay / 2.0) if l2_weight_decay else None)\n\n model = factory.build_retinanet(\n input_specs=input_specs,\n model_config=self.task_config.model,\n l2_regularizer=l2_regularizer)\n\n if self.task_config.freeze_backbone:\n model.backbone.trainable = False\n\n return model\n\n def initialize(self, model: tf.keras.Model):\n \"\"\"Loading pretrained checkpoint.\"\"\"\n if not self.task_config.init_checkpoint:\n return\n\n ckpt_dir_or_file = self.task_config.init_checkpoint\n if tf.io.gfile.isdir(ckpt_dir_or_file):\n ckpt_dir_or_file = tf.train.latest_checkpoint(ckpt_dir_or_file)\n\n # Restoring checkpoint.\n if self.task_config.init_checkpoint_modules == 'all':\n ckpt = tf.train.Checkpoint(**model.checkpoint_items)\n status = ckpt.read(ckpt_dir_or_file)\n status.expect_partial().assert_existing_objects_matched()\n else:\n ckpt_items = {}\n if 'backbone' in self.task_config.init_checkpoint_modules:\n ckpt_items.update(backbone=model.backbone)\n if 'decoder' in self.task_config.init_checkpoint_modules:\n ckpt_items.update(decoder=model.decoder)\n\n ckpt = tf.train.Checkpoint(**ckpt_items)\n status = ckpt.read(ckpt_dir_or_file)\n status.expect_partial().assert_existing_objects_matched()\n\n logging.info('Finished loading pretrained checkpoint from %s',\n ckpt_dir_or_file)\n\n def build_inputs(self,\n params: exp_cfg.DataConfig,\n input_context: Optional[tf.distribute.InputContext] = None):\n \"\"\"Build input dataset.\"\"\"\n\n if params.tfds_name:\n decoder = tfds_factory.get_detection_decoder(params.tfds_name)\n else:\n decoder_cfg = params.decoder.get()\n if params.decoder.type == 'simple_decoder':\n decoder = tf_example_decoder.TfExampleDecoder(\n regenerate_source_id=decoder_cfg.regenerate_source_id)\n elif params.decoder.type == 'label_map_decoder':\n decoder = tf_example_label_map_decoder.TfExampleDecoderLabelMap(\n label_map=decoder_cfg.label_map,\n regenerate_source_id=decoder_cfg.regenerate_source_id)\n else:\n raise ValueError('Unknown decoder type: {}!'.format(\n params.decoder.type))\n\n parser = retinanet_input.Parser(\n output_size=self.task_config.model.input_size[:2],\n min_level=self.task_config.model.min_level,\n max_level=self.task_config.model.max_level,\n num_scales=self.task_config.model.anchor.num_scales,\n aspect_ratios=self.task_config.model.anchor.aspect_ratios,\n anchor_size=self.task_config.model.anchor.anchor_size,\n dtype=params.dtype,\n match_threshold=params.parser.match_threshold,\n unmatched_threshold=params.parser.unmatched_threshold,\n aug_type=params.parser.aug_type,\n aug_rand_hflip=params.parser.aug_rand_hflip,\n aug_scale_min=params.parser.aug_scale_min,\n aug_scale_max=params.parser.aug_scale_max,\n skip_crowd_during_training=params.parser.skip_crowd_during_training,\n max_num_instances=params.parser.max_num_instances)\n\n reader = input_reader_factory.input_reader_generator(\n params,\n dataset_fn=dataset_fn.pick_dataset_fn(params.file_type),\n decoder_fn=decoder.decode,\n parser_fn=parser.parse_fn(params.is_training))\n dataset = reader.read(input_context=input_context)\n\n return dataset\n\n def build_attribute_loss(self,\n attribute_heads: List[exp_cfg.AttributeHead],\n outputs: Mapping[str, Any],\n labels: Mapping[str, Any],\n box_sample_weight: tf.Tensor) -> float:\n \"\"\"Computes attribute loss.\n\n Args:\n attribute_heads: a list of attribute head configs.\n outputs: RetinaNet model outputs.\n labels: RetinaNet labels.\n box_sample_weight: normalized bounding box sample weights.\n\n Returns:\n Attribute loss of all attribute heads.\n \"\"\"\n attribute_loss = 0.0\n for head in attribute_heads:\n if head.name not in labels['attribute_targets']:\n raise ValueError(f'Attribute {head.name} not found in label targets.')\n if head.name not in outputs['attribute_outputs']:\n raise ValueError(f'Attribute {head.name} not found in model outputs.')\n\n y_true_att = loss_utils.multi_level_flatten(\n labels['attribute_targets'][head.name], last_dim=head.size)\n y_pred_att = loss_utils.multi_level_flatten(\n outputs['attribute_outputs'][head.name], last_dim=head.size)\n if head.type == 'regression':\n att_loss_fn = tf.keras.losses.Huber(\n 1.0, reduction=tf.keras.losses.Reduction.SUM)\n att_loss = att_loss_fn(\n y_true=y_true_att,\n y_pred=y_pred_att,\n sample_weight=box_sample_weight)\n else:\n raise ValueError(f'Attribute type {head.type} not supported.')\n attribute_loss += att_loss\n\n return attribute_loss\n\n def build_losses(self,\n outputs: Mapping[str, Any],\n labels: Mapping[str, Any],\n aux_losses: Optional[Any] = None):\n \"\"\"Build RetinaNet losses.\"\"\"\n params = self.task_config\n attribute_heads = self.task_config.model.head.attribute_heads\n\n cls_loss_fn = focal_loss.FocalLoss(\n alpha=params.losses.focal_loss_alpha,\n gamma=params.losses.focal_loss_gamma,\n reduction=tf.keras.losses.Reduction.SUM)\n box_loss_fn = tf.keras.losses.Huber(\n params.losses.huber_loss_delta, reduction=tf.keras.losses.Reduction.SUM)\n\n # Sums all positives in a batch for normalization and avoids zero\n # num_positives_sum, which would lead to inf loss during training\n cls_sample_weight = labels['cls_weights']\n box_sample_weight = labels['box_weights']\n num_positives = tf.reduce_sum(box_sample_weight) + 1.0\n cls_sample_weight = cls_sample_weight / num_positives\n box_sample_weight = box_sample_weight / num_positives\n y_true_cls = loss_utils.multi_level_flatten(\n labels['cls_targets'], last_dim=None)\n y_true_cls = tf.one_hot(y_true_cls, params.model.num_classes)\n y_pred_cls = loss_utils.multi_level_flatten(\n outputs['cls_outputs'], last_dim=params.model.num_classes)\n y_true_box = loss_utils.multi_level_flatten(\n labels['box_targets'], last_dim=4)\n y_pred_box = loss_utils.multi_level_flatten(\n outputs['box_outputs'], last_dim=4)\n\n cls_loss = cls_loss_fn(\n y_true=y_true_cls, y_pred=y_pred_cls, sample_weight=cls_sample_weight)\n box_loss = box_loss_fn(\n y_true=y_true_box, y_pred=y_pred_box, sample_weight=box_sample_weight)\n\n model_loss = cls_loss + params.losses.box_loss_weight * box_loss\n\n if attribute_heads:\n model_loss += self.build_attribute_loss(attribute_heads, outputs, labels,\n box_sample_weight)\n\n total_loss = model_loss\n if aux_losses:\n reg_loss = tf.reduce_sum(aux_losses)\n total_loss = model_loss + reg_loss\n\n total_loss = params.losses.loss_weight * total_loss\n\n return total_loss, cls_loss, box_loss, model_loss\n\n def build_metrics(self, training: bool = True):\n \"\"\"Build detection metrics.\"\"\"\n metrics = []\n metric_names = ['total_loss', 'cls_loss', 'box_loss', 'model_loss']\n for name in metric_names:\n metrics.append(tf.keras.metrics.Mean(name, dtype=tf.float32))\n\n if not training:\n if self.task_config.validation_data.tfds_name and self.task_config.annotation_file:\n raise ValueError(\n \"Can't evaluate using annotation file when TFDS is used.\")\n if self._task_config.use_coco_metrics:\n self.coco_metric = coco_evaluator.COCOEvaluator(\n annotation_file=self.task_config.annotation_file,\n include_mask=False,\n per_category_metrics=self.task_config.per_category_metrics)\n if self._task_config.use_wod_metrics:\n # To use Waymo open dataset metrics, please install one of the pip\n # package `waymo-open-dataset-tf-*` from\n # https://github.com/waymo-research/waymo-open-dataset/blob/master/docs/quick_start.md#use-pre-compiled-pippip3-packages-for-linux\n # Note that the package is built with specific tensorflow version and\n # will produce error if it does not match the tf version that is\n # currently used.\n try:\n from official.vision.evaluation import wod_detection_evaluator # pylint: disable=g-import-not-at-top\n except ModuleNotFoundError:\n logging.error('waymo-open-dataset should be installed to enable Waymo'\n ' evaluator.')\n raise\n self.wod_metric = wod_detection_evaluator.WOD2dDetectionEvaluator()\n\n return metrics\n\n def train_step(self,\n inputs: Tuple[Any, Any],\n model: tf.keras.Model,\n optimizer: tf.keras.optimizers.Optimizer,\n metrics: Optional[List[Any]] = None):\n \"\"\"Does forward and backward.\n\n Args:\n inputs: a dictionary of input tensors.\n model: the model, forward pass definition.\n optimizer: the optimizer for this training step.\n metrics: a nested structure of metrics objects.\n\n Returns:\n A dictionary of logs.\n \"\"\"\n features, labels = inputs\n num_replicas = tf.distribute.get_strategy().num_replicas_in_sync\n with tf.GradientTape() as tape:\n outputs = model(features, training=True)\n outputs = tf.nest.map_structure(\n lambda x: tf.cast(x, tf.float32), outputs)\n\n # Computes per-replica loss.\n loss, cls_loss, box_loss, model_loss = self.build_losses(\n outputs=outputs, labels=labels, aux_losses=model.losses)\n scaled_loss = loss / num_replicas\n\n # For mixed_precision policy, when LossScaleOptimizer is used, loss is\n # scaled for numerical stability.\n if isinstance(optimizer, tf.keras.mixed_precision.LossScaleOptimizer):\n scaled_loss = optimizer.get_scaled_loss(scaled_loss)\n\n tvars = model.trainable_variables\n grads = tape.gradient(scaled_loss, tvars)\n # Scales back gradient when LossScaleOptimizer is used.\n if isinstance(optimizer, tf.keras.mixed_precision.LossScaleOptimizer):\n grads = optimizer.get_unscaled_gradients(grads)\n optimizer.apply_gradients(list(zip(grads, tvars)))\n\n logs = {self.loss: loss}\n\n all_losses = {\n 'total_loss': loss,\n 'cls_loss': cls_loss,\n 'box_loss': box_loss,\n 'model_loss': model_loss,\n }\n if metrics:\n for m in metrics:\n m.update_state(all_losses[m.name])\n logs.update({m.name: m.result()})\n\n return logs\n\n def validation_step(self,\n inputs: Tuple[Any, Any],\n model: tf.keras.Model,\n metrics: Optional[List[Any]] = None):\n \"\"\"Validatation step.\n\n Args:\n inputs: a dictionary of input tensors.\n model: the keras.Model.\n metrics: a nested structure of metrics objects.\n\n Returns:\n A dictionary of logs.\n \"\"\"\n features, labels = inputs\n\n outputs = model(features, anchor_boxes=labels['anchor_boxes'],\n image_shape=labels['image_info'][:, 1, :],\n training=False)\n loss, cls_loss, box_loss, model_loss = self.build_losses(\n outputs=outputs, labels=labels, aux_losses=model.losses)\n logs = {self.loss: loss}\n\n all_losses = {\n 'total_loss': loss,\n 'cls_loss': cls_loss,\n 'box_loss': box_loss,\n 'model_loss': model_loss,\n }\n\n if self._task_config.use_coco_metrics:\n coco_model_outputs = {\n 'detection_boxes': outputs['detection_boxes'],\n 'detection_scores': outputs['detection_scores'],\n 'detection_classes': outputs['detection_classes'],\n 'num_detections': outputs['num_detections'],\n 'source_id': labels['groundtruths']['source_id'],\n 'image_info': labels['image_info']\n }\n logs.update(\n {self.coco_metric.name: (labels['groundtruths'], coco_model_outputs)})\n if self.task_config.use_wod_metrics:\n wod_model_outputs = {\n 'detection_boxes': outputs['detection_boxes'],\n 'detection_scores': outputs['detection_scores'],\n 'detection_classes': outputs['detection_classes'],\n 'num_detections': outputs['num_detections'],\n 'source_id': labels['groundtruths']['source_id'],\n 'image_info': labels['image_info']\n }\n logs.update(\n {self.wod_metric.name: (labels['groundtruths'], wod_model_outputs)})\n\n if metrics:\n for m in metrics:\n m.update_state(all_losses[m.name])\n logs.update({m.name: m.result()})\n return logs\n\n def aggregate_logs(self, state=None, step_outputs=None):\n if self._task_config.use_coco_metrics:\n if state is None:\n self.coco_metric.reset_states()\n self.coco_metric.update_state(step_outputs[self.coco_metric.name][0],\n step_outputs[self.coco_metric.name][1])\n if self._task_config.use_wod_metrics:\n if state is None:\n self.wod_metric.reset_states()\n self.wod_metric.update_state(step_outputs[self.wod_metric.name][0],\n step_outputs[self.wod_metric.name][1])\n if state is None:\n # Create an arbitrary state to indicate it's not the first step in the\n # following calls to this function.\n state = True\n return state\n\n def reduce_aggregated_logs(self, aggregated_logs, global_step=None):\n logs = {}\n if self._task_config.use_coco_metrics:\n logs.update(self.coco_metric.result())\n if self._task_config.use_wod_metrics:\n logs.update(self.wod_metric.result())\n return logs\n",
"# Copyright 2022 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\"\"\"Contains definitions of NAS-FPN.\"\"\"\n\nfrom typing import Any, List, Mapping, Optional, Tuple\n\n# Import libraries\n\nfrom absl import logging\nimport tensorflow as tf\n\nfrom official.modeling import hyperparams\nfrom official.modeling import tf_utils\nfrom official.vision.modeling.decoders import factory\nfrom official.vision.ops import spatial_transform_ops\n\n\n# The fixed NAS-FPN architecture discovered by NAS.\n# Each element represents a specification of a building block:\n# (block_level, combine_fn, (input_offset0, input_offset1), is_output).\nNASFPN_BLOCK_SPECS = [\n (4, 'attention', (1, 3), False),\n (4, 'sum', (1, 5), False),\n (3, 'sum', (0, 6), True),\n (4, 'sum', (6, 7), True),\n (5, 'attention', (7, 8), True),\n (7, 'attention', (6, 9), True),\n (6, 'attention', (9, 10), True),\n]\n\n\nclass BlockSpec():\n \"\"\"A container class that specifies the block configuration for NAS-FPN.\"\"\"\n\n def __init__(self, level: int, combine_fn: str,\n input_offsets: Tuple[int, int], is_output: bool):\n self.level = level\n self.combine_fn = combine_fn\n self.input_offsets = input_offsets\n self.is_output = is_output\n\n\ndef build_block_specs(\n block_specs: Optional[List[Tuple[Any, ...]]] = None) -> List[BlockSpec]:\n \"\"\"Builds the list of BlockSpec objects for NAS-FPN.\"\"\"\n if not block_specs:\n block_specs = NASFPN_BLOCK_SPECS\n logging.info('Building NAS-FPN block specs: %s', block_specs)\n return [BlockSpec(*b) for b in block_specs]\n\n\[email protected]_keras_serializable(package='Vision')\nclass NASFPN(tf.keras.Model):\n \"\"\"Creates a NAS-FPN model.\n\n This implements the paper:\n Golnaz Ghiasi, Tsung-Yi Lin, Ruoming Pang, Quoc V. Le.\n NAS-FPN: Learning Scalable Feature Pyramid Architecture for Object Detection.\n (https://arxiv.org/abs/1904.07392)\n \"\"\"\n\n def __init__(\n self,\n input_specs: Mapping[str, tf.TensorShape],\n min_level: int = 3,\n max_level: int = 7,\n block_specs: List[BlockSpec] = build_block_specs(),\n num_filters: int = 256,\n num_repeats: int = 5,\n use_separable_conv: bool = False,\n activation: str = 'relu',\n use_sync_bn: bool = False,\n norm_momentum: float = 0.99,\n norm_epsilon: float = 0.001,\n kernel_initializer: str = 'VarianceScaling',\n kernel_regularizer: Optional[tf.keras.regularizers.Regularizer] = None,\n bias_regularizer: Optional[tf.keras.regularizers.Regularizer] = None,\n **kwargs):\n \"\"\"Initializes a NAS-FPN model.\n\n Args:\n input_specs: A `dict` of input specifications. A dictionary consists of\n {level: TensorShape} from a backbone.\n min_level: An `int` of minimum level in FPN output feature maps.\n max_level: An `int` of maximum level in FPN output feature maps.\n block_specs: a list of BlockSpec objects that specifies the NAS-FPN\n network topology. By default, the previously discovered architecture is\n used.\n num_filters: An `int` number of filters in FPN layers.\n num_repeats: number of repeats for feature pyramid network.\n use_separable_conv: A `bool`. If True use separable convolution for\n convolution in FPN layers.\n activation: A `str` name of the activation function.\n use_sync_bn: A `bool`. If True, use synchronized batch normalization.\n norm_momentum: A `float` of normalization momentum for the moving average.\n norm_epsilon: A `float` added to variance to avoid dividing by zero.\n kernel_initializer: A `str` name of kernel_initializer for convolutional\n layers.\n kernel_regularizer: A `tf.keras.regularizers.Regularizer` object for\n Conv2D. Default is None.\n bias_regularizer: A `tf.keras.regularizers.Regularizer` object for Conv2D.\n **kwargs: Additional keyword arguments to be passed.\n \"\"\"\n self._config_dict = {\n 'input_specs': input_specs,\n 'min_level': min_level,\n 'max_level': max_level,\n 'num_filters': num_filters,\n 'num_repeats': num_repeats,\n 'use_separable_conv': use_separable_conv,\n 'activation': activation,\n 'use_sync_bn': use_sync_bn,\n 'norm_momentum': norm_momentum,\n 'norm_epsilon': norm_epsilon,\n 'kernel_initializer': kernel_initializer,\n 'kernel_regularizer': kernel_regularizer,\n 'bias_regularizer': bias_regularizer,\n }\n self._min_level = min_level\n self._max_level = max_level\n self._block_specs = block_specs\n self._num_repeats = num_repeats\n self._conv_op = (tf.keras.layers.SeparableConv2D\n if self._config_dict['use_separable_conv']\n else tf.keras.layers.Conv2D)\n self._norm_op = (tf.keras.layers.experimental.SyncBatchNormalization\n if self._config_dict['use_sync_bn']\n else tf.keras.layers.BatchNormalization)\n if tf.keras.backend.image_data_format() == 'channels_last':\n self._bn_axis = -1\n else:\n self._bn_axis = 1\n self._norm_kwargs = {\n 'axis': self._bn_axis,\n 'momentum': self._config_dict['norm_momentum'],\n 'epsilon': self._config_dict['norm_epsilon'],\n }\n self._activation = tf_utils.get_activation(activation)\n\n # Gets input feature pyramid from backbone.\n inputs = self._build_input_pyramid(input_specs, min_level)\n\n # Projects the input features.\n feats = []\n for level in range(self._min_level, self._max_level + 1):\n if str(level) in inputs.keys():\n feats.append(self._resample_feature_map(\n inputs[str(level)], level, level, self._config_dict['num_filters']))\n else:\n feats.append(self._resample_feature_map(\n feats[-1], level - 1, level, self._config_dict['num_filters']))\n\n # Repeatly builds the NAS-FPN modules.\n for _ in range(self._num_repeats):\n output_feats = self._build_feature_pyramid(feats)\n feats = [output_feats[level]\n for level in range(self._min_level, self._max_level + 1)]\n\n self._output_specs = {\n str(level): output_feats[level].get_shape()\n for level in range(min_level, max_level + 1)\n }\n output_feats = {str(level): output_feats[level]\n for level in output_feats.keys()}\n super(NASFPN, self).__init__(inputs=inputs, outputs=output_feats, **kwargs)\n\n def _build_input_pyramid(self, input_specs: Mapping[str, tf.TensorShape],\n min_level: int):\n assert isinstance(input_specs, dict)\n if min(input_specs.keys()) > str(min_level):\n raise ValueError(\n 'Backbone min level should be less or equal to FPN min level')\n\n inputs = {}\n for level, spec in input_specs.items():\n inputs[level] = tf.keras.Input(shape=spec[1:])\n return inputs\n\n def _resample_feature_map(self,\n inputs,\n input_level,\n target_level,\n target_num_filters=256):\n x = inputs\n _, _, _, input_num_filters = x.get_shape().as_list()\n if input_num_filters != target_num_filters:\n x = self._conv_op(\n filters=target_num_filters,\n kernel_size=1,\n padding='same',\n **self._conv_kwargs)(x)\n x = self._norm_op(**self._norm_kwargs)(x)\n\n if input_level < target_level:\n stride = int(2 ** (target_level - input_level))\n return tf.keras.layers.MaxPool2D(\n pool_size=stride, strides=stride, padding='same')(x)\n if input_level > target_level:\n scale = int(2 ** (input_level - target_level))\n return spatial_transform_ops.nearest_upsampling(x, scale=scale)\n\n # Force output x to be the same dtype as mixed precision policy. This avoids\n # dtype mismatch when one input (by default float32 dtype) does not meet all\n # the above conditions and is output unchanged, while other inputs are\n # processed to have different dtype, e.g., using bfloat16 on TPU.\n compute_dtype = tf.keras.layers.Layer().dtype_policy.compute_dtype\n if (compute_dtype is not None) and (x.dtype != compute_dtype):\n return tf.cast(x, dtype=compute_dtype)\n else:\n return x\n\n @property\n def _conv_kwargs(self):\n if self._config_dict['use_separable_conv']:\n return {\n 'depthwise_initializer': tf.keras.initializers.VarianceScaling(\n scale=2, mode='fan_out', distribution='untruncated_normal'),\n 'pointwise_initializer': tf.keras.initializers.VarianceScaling(\n scale=2, mode='fan_out', distribution='untruncated_normal'),\n 'bias_initializer': tf.zeros_initializer(),\n 'depthwise_regularizer': self._config_dict['kernel_regularizer'],\n 'pointwise_regularizer': self._config_dict['kernel_regularizer'],\n 'bias_regularizer': self._config_dict['bias_regularizer'],\n }\n else:\n return {\n 'kernel_initializer': tf.keras.initializers.VarianceScaling(\n scale=2, mode='fan_out', distribution='untruncated_normal'),\n 'bias_initializer': tf.zeros_initializer(),\n 'kernel_regularizer': self._config_dict['kernel_regularizer'],\n 'bias_regularizer': self._config_dict['bias_regularizer'],\n }\n\n def _global_attention(self, feat0, feat1):\n m = tf.math.reduce_max(feat0, axis=[1, 2], keepdims=True)\n m = tf.math.sigmoid(m)\n return feat0 + feat1 * m\n\n def _build_feature_pyramid(self, feats):\n num_output_connections = [0] * len(feats)\n num_output_levels = self._max_level - self._min_level + 1\n feat_levels = list(range(self._min_level, self._max_level + 1))\n\n for i, block_spec in enumerate(self._block_specs):\n new_level = block_spec.level\n\n # Checks the range of input_offsets.\n for input_offset in block_spec.input_offsets:\n if input_offset >= len(feats):\n raise ValueError(\n 'input_offset ({}) is larger than num feats({})'.format(\n input_offset, len(feats)))\n input0 = block_spec.input_offsets[0]\n input1 = block_spec.input_offsets[1]\n\n # Update graph with inputs.\n node0 = feats[input0]\n node0_level = feat_levels[input0]\n num_output_connections[input0] += 1\n node0 = self._resample_feature_map(node0, node0_level, new_level)\n node1 = feats[input1]\n node1_level = feat_levels[input1]\n num_output_connections[input1] += 1\n node1 = self._resample_feature_map(node1, node1_level, new_level)\n\n # Combine node0 and node1 to create new feat.\n if block_spec.combine_fn == 'sum':\n new_node = node0 + node1\n elif block_spec.combine_fn == 'attention':\n if node0_level >= node1_level:\n new_node = self._global_attention(node0, node1)\n else:\n new_node = self._global_attention(node1, node0)\n else:\n raise ValueError('unknown combine_fn `{}`.'\n .format(block_spec.combine_fn))\n\n # Add intermediate nodes that do not have any connections to output.\n if block_spec.is_output:\n for j, (feat, feat_level, num_output) in enumerate(\n zip(feats, feat_levels, num_output_connections)):\n if num_output == 0 and feat_level == new_level:\n num_output_connections[j] += 1\n\n feat_ = self._resample_feature_map(feat, feat_level, new_level)\n new_node += feat_\n\n new_node = self._activation(new_node)\n new_node = self._conv_op(\n filters=self._config_dict['num_filters'],\n kernel_size=(3, 3),\n padding='same',\n **self._conv_kwargs)(new_node)\n new_node = self._norm_op(**self._norm_kwargs)(new_node)\n\n feats.append(new_node)\n feat_levels.append(new_level)\n num_output_connections.append(0)\n\n output_feats = {}\n for i in range(len(feats) - num_output_levels, len(feats)):\n level = feat_levels[i]\n output_feats[level] = feats[i]\n logging.info('Output feature pyramid: %s', output_feats)\n return output_feats\n\n def get_config(self) -> Mapping[str, Any]:\n return self._config_dict\n\n @classmethod\n def from_config(cls, config, custom_objects=None):\n return cls(**config)\n\n @property\n def output_specs(self) -> Mapping[str, tf.TensorShape]:\n \"\"\"A dict of {level: TensorShape} pairs for the model output.\"\"\"\n return self._output_specs\n\n\[email protected]_decoder_builder('nasfpn')\ndef build_nasfpn_decoder(\n input_specs: Mapping[str, tf.TensorShape],\n model_config: hyperparams.Config,\n l2_regularizer: Optional[tf.keras.regularizers.Regularizer] = None\n) -> tf.keras.Model:\n \"\"\"Builds NASFPN decoder from a config.\n\n Args:\n input_specs: A `dict` of input specifications. A dictionary consists of\n {level: TensorShape} from a backbone.\n model_config: A OneOfConfig. Model config.\n l2_regularizer: A `tf.keras.regularizers.Regularizer` instance. Default to\n None.\n\n Returns:\n A `tf.keras.Model` instance of the NASFPN decoder.\n\n Raises:\n ValueError: If the model_config.decoder.type is not `nasfpn`.\n \"\"\"\n decoder_type = model_config.decoder.type\n decoder_cfg = model_config.decoder.get()\n if decoder_type != 'nasfpn':\n raise ValueError(f'Inconsistent decoder type {decoder_type}. '\n 'Need to be `nasfpn`.')\n\n norm_activation_config = model_config.norm_activation\n return NASFPN(\n input_specs=input_specs,\n min_level=model_config.min_level,\n max_level=model_config.max_level,\n num_filters=decoder_cfg.num_filters,\n num_repeats=decoder_cfg.num_repeats,\n use_separable_conv=decoder_cfg.use_separable_conv,\n activation=norm_activation_config.activation,\n use_sync_bn=norm_activation_config.use_sync_bn,\n norm_momentum=norm_activation_config.norm_momentum,\n norm_epsilon=norm_activation_config.norm_epsilon,\n kernel_regularizer=l2_regularizer)\n",
"# Copyright 2022 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\"\"\"Customized MobileBERT-EdgeTPU layers.\n\nThere are two reasons for us to customize the layers instead of using the well-\ndefined layers used in baseline MobileBERT.\n1. The layer introduces compiler sharding failures. For example, the gather in\n OnDeviceEmbedding.\n2. The layer contains ops that need to have bounded input/output ranges. For\n example, softmax op.\n\"\"\"\nimport string\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom official.nlp.modeling import layers\n\n_CHR_IDX = string.ascii_lowercase\n\n\n# This function is directly copied from the tf.keras.layers.MultiHeadAttention\n# implementation.\ndef _build_attention_equation(rank, attn_axes):\n \"\"\"Builds einsum equations for the attention computation.\n\n Query, key, value inputs after projection are expected to have the shape as:\n `(bs, <non-attention dims>, <attention dims>, num_heads, channels)`.\n `bs` and `<non-attention dims>` are treated as `<batch dims>`.\n\n The attention operations can be generalized:\n (1) Query-key dot product:\n `(<batch dims>, <query attention dims>, num_heads, channels), (<batch dims>,\n <key attention dims>, num_heads, channels) -> (<batch dims>,\n num_heads, <query attention dims>, <key attention dims>)`\n (2) Combination:\n `(<batch dims>, num_heads, <query attention dims>, <key attention dims>),\n (<batch dims>, <value attention dims>, num_heads, channels) -> (<batch dims>,\n <query attention dims>, num_heads, channels)`\n\n Args:\n rank: Rank of query, key, value tensors.\n attn_axes: List/tuple of axes, `[-1, rank)`,\n that attention will be applied to.\n\n Returns:\n Einsum equations.\n \"\"\"\n target_notation = _CHR_IDX[:rank]\n # `batch_dims` includes the head dim.\n batch_dims = tuple(np.delete(range(rank), attn_axes + (rank - 1,)))\n letter_offset = rank\n source_notation = ''\n for i in range(rank):\n if i in batch_dims or i == rank - 1:\n source_notation += target_notation[i]\n else:\n source_notation += _CHR_IDX[letter_offset]\n letter_offset += 1\n\n product_notation = ''.join([target_notation[i] for i in batch_dims] +\n [target_notation[i] for i in attn_axes] +\n [source_notation[i] for i in attn_axes])\n dot_product_equation = '%s,%s->%s' % (source_notation, target_notation,\n product_notation)\n attn_scores_rank = len(product_notation)\n combine_equation = '%s,%s->%s' % (product_notation, source_notation,\n target_notation)\n return dot_product_equation, combine_equation, attn_scores_rank\n\n\[email protected]_keras_serializable(package='Text')\nclass EdgeTPUSoftmax(tf.keras.layers.Softmax):\n \"\"\"EdgeTPU/Quantization friendly implementation for the SoftMax.\n\n When export quant model, use -120 mask value.\n When export float model and run inference with bf16 on device, use -10000.\n \"\"\"\n\n def __init__(self,\n mask_value: int = -120,\n **kwargs):\n self._mask_value = mask_value\n super(EdgeTPUSoftmax, self).__init__(**kwargs)\n\n def get_config(self):\n config = {\n 'mask_value': self._mask_value\n }\n base_config = super(EdgeTPUSoftmax, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n def call(self, inputs, mask=None):\n if mask is not None:\n adder = (1.0 - tf.cast(mask, inputs.dtype)) * self._mask_value\n inputs += adder\n if isinstance(self.axis, (tuple, list)):\n if len(self.axis) > 1:\n return tf.exp(inputs - tf.reduce_logsumexp(\n inputs, axis=self.axis, keepdims=True))\n else:\n return tf.keras.backend.softmax(inputs, axis=self.axis[0])\n return tf.keras.backend.softmax(inputs, axis=self.axis)\n\n\[email protected]_keras_serializable(package='Text')\nclass EdgeTPUMultiHeadAttention(tf.keras.layers.MultiHeadAttention):\n \"\"\"Quantization friendly implementation for the MultiHeadAttention.\"\"\"\n\n def _build_attention(self, rank):\n \"\"\"Builds multi-head dot-product attention computations.\n\n This function builds attributes necessary for `_compute_attention` to\n customize attention computation to replace the default dot-product\n attention.\n\n Args:\n rank: the rank of query, key, value tensors.\n \"\"\"\n if self._attention_axes is None:\n self._attention_axes = tuple(range(1, rank - 2))\n else:\n self._attention_axes = tuple(self._attention_axes)\n self._dot_product_equation, self._combine_equation, attn_scores_rank = (\n _build_attention_equation(\n rank, attn_axes=self._attention_axes))\n norm_axes = tuple(\n range(attn_scores_rank - len(self._attention_axes), attn_scores_rank))\n self._softmax = EdgeTPUSoftmax(axis=norm_axes)\n self._dropout_layer = tf.keras.layers.Dropout(rate=self._dropout)\n\n\nclass EdgetpuMobileBertTransformer(layers.MobileBertTransformer):\n \"\"\"Quantization friendly MobileBertTransformer.\n\n Inherits from the MobileBertTransformer but use our customized MHA.\n \"\"\"\n\n def __init__(self, **kwargs):\n super(EdgetpuMobileBertTransformer, self).__init__(**kwargs)\n attention_head_size = int(\n self.intra_bottleneck_size / self.num_attention_heads)\n attention_layer = EdgeTPUMultiHeadAttention(\n num_heads=self.num_attention_heads,\n key_dim=attention_head_size,\n value_dim=attention_head_size,\n dropout=self.attention_probs_dropout_prob,\n output_shape=self.intra_bottleneck_size,\n kernel_initializer=self.initializer,\n name='attention')\n layer_norm = self.block_layers['attention'][1]\n self.block_layers['attention'] = [attention_layer, layer_norm]\n\n"
] | [
[
"tensorflow.io.gfile.makedirs",
"tensorflow.test.main"
],
[
"tensorflow.io.gfile.isdir",
"tensorflow.train.latest_checkpoint",
"tensorflow.train.Checkpoint",
"tensorflow.keras.regularizers.l2",
"tensorflow.reduce_sum",
"tensorflow.cast",
"tensorflow.keras.losses.Huber",
"tensorflow.one_hot",
"tensorflow.distribute.get_strategy",
"tensorflow.keras.layers.InputSpec",
"tensorflow.keras.metrics.Mean",
"tensorflow.GradientTape"
],
[
"tensorflow.keras.Input",
"tensorflow.keras.backend.image_data_format",
"tensorflow.math.reduce_max",
"tensorflow.zeros_initializer",
"tensorflow.cast",
"tensorflow.keras.utils.register_keras_serializable",
"tensorflow.keras.layers.MaxPool2D",
"tensorflow.math.sigmoid",
"tensorflow.keras.layers.Layer",
"tensorflow.keras.initializers.VarianceScaling"
],
[
"tensorflow.keras.backend.softmax",
"tensorflow.cast",
"tensorflow.keras.utils.register_keras_serializable",
"tensorflow.keras.layers.Dropout",
"tensorflow.reduce_logsumexp"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.7",
"2.2",
"2.3",
"2.4",
"2.5",
"2.6"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"2.6",
"2.4",
"2.3",
"2.5",
"2.2"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.7",
"2.6",
"2.4",
"2.3",
"2.5",
"2.2"
]
}
] |
ruoxinx/site-dust-detect | [
"f1b4c71f3ce5c325b25e26e9d663e3c1f7096ce7"
] | [
"demo/yolo.py"
] | [
"import colorsys\nimport os\n\nimport numpy as np\nfrom keras import backend as K\nfrom keras.layers import Input\nfrom keras.models import load_model\nfrom PIL import Image, ImageDraw, ImageFont\n\nfrom nets.yolo3 import yolo_body, yolo_eval\nfrom utils.utils import letterbox_image\n\nclass YOLO(object):\n _defaults = {\n \"model_path\" : '../model/trained_weights.h5',\n \"anchors_path\" : '../model/yolo_anchors.txt',\n \"classes_path\" : '../model/yolo_classes.txt',\n \"score\" : 0.5,\n \"iou\" : 0.3,\n \"max_boxes\" : 100,\n \"model_image_size\" : (416, 416),\n \"letterbox_image\" : False,\n }\n\n def get_defaults(cls, n):\n if n in cls._defaults:\n return cls._defaults[n]\n else:\n return \"Unrecognized attribute name '\" + n + \"'\"\n\n def __init__(self, **kwargs):\n self.__dict__.update(self._defaults)\n self.class_names = self._get_class()\n self.anchors = self._get_anchors()\n self.sess = K.get_session()\n self.boxes, self.scores, self.classes = self.generate()\n\n def _get_class(self):\n classes_path = os.path.expanduser(self.classes_path)\n with open(classes_path) as f:\n class_names = f.readlines()\n class_names = [c.strip() for c in class_names]\n return class_names\n\n def _get_anchors(self):\n anchors_path = os.path.expanduser(self.anchors_path)\n with open(anchors_path) as f:\n anchors = f.readline()\n anchors = [float(x) for x in anchors.split(',')]\n return np.array(anchors).reshape(-1, 2)\n\n def generate(self):\n model_path = os.path.expanduser(self.model_path)\n assert model_path.endswith('.h5'), 'Keras model or weights must be a .h5 file.'\n\n num_anchors = len(self.anchors)\n num_classes = len(self.class_names)\n\n try:\n self.yolo_model = load_model(model_path, compile=False)\n except:\n self.yolo_model = yolo_body(Input(shape=(None,None,3)), num_anchors//3, num_classes)\n self.yolo_model.load_weights(self.model_path)\n else:\n assert self.yolo_model.layers[-1].output_shape[-1] == \\\n num_anchors/len(self.yolo_model.output) * (num_classes + 5), \\\n 'Mismatch between model and given anchor and class sizes'\n\n hsv_tuples = [(x / len(self.class_names), 1., 1.)\n for x in range(len(self.class_names))]\n self.colors = list(map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples))\n self.colors = list(\n map(lambda x: (int(x[0] * 255), int(x[1] * 255), int(x[2] * 255)),\n self.colors))\n\n np.random.seed(10101)\n np.random.shuffle(self.colors)\n np.random.seed(None)\n\n self.input_image_shape = K.placeholder(shape=(2, ))\n\n boxes, scores, classes = yolo_eval(self.yolo_model.output, self.anchors,\n num_classes, self.input_image_shape, max_boxes = self.max_boxes,\n score_threshold = self.score, iou_threshold = self.iou, letterbox_image = self.letterbox_image)\n return boxes, scores, classes\n\n def detect_image(self, image):\n if self.letterbox_image:\n boxed_image = letterbox_image(image, (self.model_image_size[1],self.model_image_size[0]))\n else:\n boxed_image = image.convert('RGB')\n boxed_image = boxed_image.resize((self.model_image_size[1],self.model_image_size[0]), Image.BICUBIC)\n image_data = np.array(boxed_image, dtype='float32')\n image_data /= 255.\n image_data = np.expand_dims(image_data, 0)\n out_boxes, out_scores, out_classes = self.sess.run(\n [self.boxes, self.scores, self.classes],\n feed_dict={\n self.yolo_model.input: image_data,\n self.input_image_shape: [image.size[1], image.size[0]],\n K.learning_phase(): 0})\n\n font = ImageFont.truetype(font='simhei.ttf',\n size=np.floor(3e-2 * image.size[1] + 0.5).astype('int32'))\n thickness = max((image.size[0] + image.size[1]) // 300, 1)\n\n for i, c in list(enumerate(out_classes)):\n predicted_class = self.class_names[c]\n box = out_boxes[i]\n score = out_scores[i]\n\n top, left, bottom, right = box\n top = top - 5\n left = left - 5\n bottom = bottom + 5\n right = right + 5\n\n top = max(0, np.floor(top + 0.5).astype('int32'))\n left = max(0, np.floor(left + 0.5).astype('int32'))\n bottom = min(image.size[1], np.floor(bottom + 0.5).astype('int32'))\n right = min(image.size[0], np.floor(right + 0.5).astype('int32'))\n\n label = '{} {:.2f}'.format(predicted_class, score)\n draw = ImageDraw.Draw(image)\n label_size = draw.textsize(label, font)\n label = label.encode('utf-8')\n print(label, top, left, bottom, right)\n \n if top - label_size[1] >= 0:\n text_origin = np.array([left, top - label_size[1]])\n else:\n text_origin = np.array([left, top + 1])\n\n for i in range(thickness):\n draw.rectangle(\n [left + i, top + i, right - i, bottom - i],\n outline=self.colors[c])\n draw.rectangle(\n [tuple(text_origin), tuple(text_origin + label_size)],\n fill=self.colors[c])\n draw.text(text_origin, str(label,'UTF-8'), fill=(0, 0, 0), font=font)\n del draw\n\n return image\n\n def close_session(self):\n self.sess.close()\n"
] | [
[
"numpy.expand_dims",
"numpy.random.seed",
"numpy.random.shuffle",
"numpy.floor",
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
MuawizChaudhary/STARTUP | [
"5cfa6694a4ffa6ffd3cc22deceb4626fd008ee83"
] | [
"teacher_miniImageNet/datasets/cifar_few_shot.py"
] | [
"# This code is modified from https://github.com/facebookresearch/low-shot-shrink-hallucinate\n\nimport torch\nfrom PIL import Image\nimport numpy as np\nimport torchvision.transforms as transforms\nimport additional_transforms as add_transforms\nfrom abc import abstractmethod\nfrom torchvision.datasets import CIFAR100, CIFAR10\n\nidentity = lambda x:x\nclass SimpleDataset:\n def __init__(self, mode, dataset, transform, target_transform=identity):\n self.transform = transform\n self.dataset = dataset\n self.target_transform = target_transform\n\n self.meta = {}\n\n self.meta['image_names'] = []\n self.meta['image_labels'] = []\n if self.dataset == \"CIFAR100\":\n\n d = CIFAR100(\"./\", train=True, download=True)\n for i, (data, label) in enumerate(d):\n if mode == \"base\":\n if label % 3 == 0:\n self.meta['image_names'].append(data)\n self.meta['image_labels'].append(label)\n elif mode == \"val\":\n if label % 3 == 1:\n self.meta['image_names'].append(data)\n self.meta['image_labels'].append(label) \n else:\n if label % 3 == 2:\n self.meta['image_names'].append(data)\n self.meta['image_labels'].append(label) \n\n elif self.dataset == \"CIFAR10\":\n d = CIFAR10(\"./\", train=True, download=True)\n for i, (data, label) in enumerate(d):\n if mode == \"novel\":\n self.meta['image_names'].append(data)\n self.meta['image_labels'].append(label) \n\n def __getitem__(self, i):\n\n img = self.transform(self.meta['image_names'][i])\n target = self.target_transform(self.meta['image_labels'][i])\n\n return img, target\n\n def __len__(self):\n return len(self.meta['image_names'])\n\n\nclass SetDataset:\n def __init__(self, mode, dataset, batch_size, transform):\n\n self.sub_meta = {}\n self.cl_list = range(100)\n self.dataset = dataset\n\n if mode == \"base\":\n type_ = 0\n elif mode == \"val\":\n type_ = 1\n else:\n type_ = 2\n\n for cl in self.cl_list:\n if cl % 3 == type_:\n self.sub_meta[cl] = []\n\n if self.dataset == \"CIFAR100\":\n d = CIFAR100(\"./\", train=True, download=True)\n elif self.dataset == \"CIFAR10\":\n d = CIFAR10(\"./\", train=True, download=True)\n\n\n for i, (data, label) in enumerate(d):\n if label % 3 == type_:\n self.sub_meta[label].append(data)\n \n self.sub_dataloader = [] \n sub_data_loader_params = dict(batch_size = batch_size,\n shuffle = True,\n num_workers = 0, #use main thread only or may receive multiple batches\n pin_memory = False) \n for cl in self.cl_list:\n if cl % 3 == type_:\n sub_dataset = SubDataset(self.sub_meta[cl], cl, transform = transform )\n self.sub_dataloader.append( torch.utils.data.DataLoader(sub_dataset, **sub_data_loader_params) )\n\n def __getitem__(self,i):\n return next(iter(self.sub_dataloader[i]))\n\n def __len__(self):\n return len(self.sub_dataloader)\n\nclass SubDataset:\n def __init__(self, sub_meta, cl, transform=transforms.ToTensor(), target_transform=identity):\n self.sub_meta = sub_meta\n self.cl = cl \n self.transform = transform\n self.target_transform = target_transform\n\n def __getitem__(self,i):\n\n img = self.transform(self.sub_meta[i])\n target = self.target_transform(self.cl)\n return img, target\n\n def __len__(self):\n return len(self.sub_meta)\n\nclass EpisodicBatchSampler(object):\n def __init__(self, n_classes, n_way, n_episodes):\n self.n_classes = n_classes\n self.n_way = n_way\n self.n_episodes = n_episodes\n\n def __len__(self):\n return self.n_episodes\n\n def __iter__(self):\n for i in range(self.n_episodes):\n yield torch.randperm(self.n_classes)[:self.n_way]\n\nclass TransformLoader:\n def __init__(self, image_size, \n normalize_param = dict(mean= [0.485, 0.456, 0.406] , std=[0.229, 0.224, 0.225]),\n jitter_param = dict(Brightness=0.4, Contrast=0.4, Color=0.4)):\n self.image_size = image_size\n self.normalize_param = normalize_param\n self.jitter_param = jitter_param\n \n def parse_transform(self, transform_type):\n if transform_type=='ImageJitter':\n method = add_transforms.ImageJitter( self.jitter_param )\n return method\n method = getattr(transforms, transform_type)\n if transform_type=='RandomSizedCrop':\n return method(self.image_size) \n elif transform_type=='CenterCrop':\n return method(self.image_size) \n elif transform_type=='Scale':\n return method([int(self.image_size*1.15), int(self.image_size*1.15)])\n elif transform_type=='Normalize':\n return method(**self.normalize_param )\n else:\n return method()\n\n def get_composed_transform(self, aug = False):\n if aug:\n transform_list = ['RandomSizedCrop', 'ImageJitter', 'RandomHorizontalFlip', 'ToTensor', 'Normalize']\n else:\n transform_list = ['Scale','CenterCrop', 'ToTensor', 'Normalize']\n\n transform_funcs = [ self.parse_transform(x) for x in transform_list]\n transform = transforms.Compose(transform_funcs)\n return transform\n\nclass DataManager(object):\n @abstractmethod\n def get_data_loader(self, data_file, aug):\n pass \n\nclass SimpleDataManager(DataManager):\n def __init__(self, dataset, image_size, batch_size): \n super(SimpleDataManager, self).__init__()\n self.batch_size = batch_size\n self.trans_loader = TransformLoader(image_size)\n self.dataset = dataset\n\n def get_data_loader(self, mode, aug): #parameters that would change on train/val set\n transform = self.trans_loader.get_composed_transform(aug)\n dataset = SimpleDataset(mode, self.dataset, transform)\n\n data_loader_params = dict(batch_size = self.batch_size, shuffle = True, num_workers = 12, pin_memory = True) \n data_loader = torch.utils.data.DataLoader(dataset, **data_loader_params)\n\n return data_loader\n\nclass SetDataManager(DataManager):\n def __init__(self, mode, dataset, image_size, n_way=5, n_support=5, n_query=16, n_eposide = 100): \n super(SetDataManager, self).__init__()\n self.image_size = image_size\n self.n_way = n_way\n self.batch_size = n_support + n_query\n self.n_eposide = n_eposide\n self.mode = mode\n self.dataset = dataset\n\n self.trans_loader = TransformLoader(image_size)\n\n def get_data_loader(self, aug): #parameters that would change on train/val set\n transform = self.trans_loader.get_composed_transform(aug)\n dataset = SetDataset(self.mode, self.dataset, self.batch_size, transform)\n sampler = EpisodicBatchSampler(len(dataset), self.n_way, self.n_eposide ) \n data_loader_params = dict(batch_sampler = sampler, num_workers = 12, pin_memory = True) \n data_loader = torch.utils.data.DataLoader(dataset, **data_loader_params)\n return data_loader\n\nif __name__ == '__main__':\n pass"
] | [
[
"torch.randperm",
"torch.utils.data.DataLoader"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
thadanipaarth/Non-Invasive-Public-Safety-Detection-System | [
"760b79c295e31003c7d0e826fe9214a73245c344"
] | [
"Scripts/training_mask_detection_model.py"
] | [
"from tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.applications import MobileNetV2\nfrom tensorflow.keras.layers import AveragePooling2D\nfrom tensorflow.keras.layers import Dropout\nfrom tensorflow.keras.layers import Flatten\nfrom tensorflow.keras.layers import Dense\nfrom tensorflow.keras.layers import Input\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.applications.mobilenet_v2 import preprocess_input\nfrom tensorflow.keras.preprocessing.image import img_to_array\nfrom tensorflow.keras.preprocessing.image import load_img\nfrom tensorflow.keras.utils import to_categorical\nfrom sklearn.preprocessing import LabelBinarizer\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import classification_report\nfrom imutils import paths\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport argparse\nimport os\n\nINIT_LR = 1e-4\nEPOCHS = 20\nBS = 32\nimagePaths = list(paths.list_images('./Mask_Detection_Dataset/'))\ndata = []\nlabels = []\nfor imagePath in imagePaths:\n\tlabel = imagePath.split(os.path.sep)[-2]\n\timage = load_img(imagePath, target_size=(224, 224))\n\timage = img_to_array(image)\n\timage = preprocess_input(image)\n\tdata.append(image)\n\tlabels.append(label)\ndata = np.array(data, dtype=\"float32\")\nlabels = np.array(labels)\nlb = LabelBinarizer()\nlabels = lb.fit_transform(labels)\nlabels = to_categorical(labels)\n(trainX, testX, trainY, testY) = train_test_split(data, labels,\n\ttest_size=0.20, stratify=labels, random_state=42)\naug = ImageDataGenerator(\n\trotation_range=20,\n\tzoom_range=0.15,\n\twidth_shift_range=0.2,\n\theight_shift_range=0.2,\n\tshear_range=0.15,\n\thorizontal_flip=True,\n\tfill_mode=\"nearest\")\nbaseModel = MobileNetV2(weights=\"imagenet\", include_top=False,\n\tinput_tensor=Input(shape=(224, 224, 3)))\nheadModel = baseModel.output\nheadModel = AveragePooling2D(pool_size=(7, 7))(headModel)\nheadModel = Flatten(name=\"flatten\")(headModel)\nheadModel = Dense(128, activation=\"relu\")(headModel)\nheadModel = Dropout(0.5)(headModel)\nheadModel = Dense(2, activation=\"softmax\")(headModel)\nmodel = Model(inputs=baseModel.input, outputs=headModel)\nfor layer in baseModel.layers:\n\tlayer.trainable = False\nopt = Adam(lr=INIT_LR, decay=INIT_LR / EPOCHS)\nmodel.compile(loss=\"binary_crossentropy\", optimizer=opt,\n\tmetrics=[\"accuracy\"])\nH = model.fit(\n\taug.flow(trainX, trainY, batch_size=BS),\n\tsteps_per_epoch=len(trainX) // BS,\n\tvalidation_data=(testX, testY),\n\tvalidation_steps=len(testX) // BS,\n\tepochs=EPOCHS)\npredIdxs = model.predict(testX, batch_size=BS)\npredIdxs = np.argmax(predIdxs, axis=1)\nprint(classification_report(testY.argmax(axis=1), predIdxs,\n\ttarget_names=lb.classes_))\nmodel.save('mask_model', save_format=\"h5\")\n"
] | [
[
"tensorflow.keras.layers.AveragePooling2D",
"tensorflow.keras.preprocessing.image.img_to_array",
"tensorflow.keras.preprocessing.image.ImageDataGenerator",
"tensorflow.keras.models.Model",
"tensorflow.keras.preprocessing.image.load_img",
"tensorflow.keras.layers.Dense",
"tensorflow.keras.applications.mobilenet_v2.preprocess_input",
"sklearn.model_selection.train_test_split",
"tensorflow.keras.optimizers.Adam",
"numpy.argmax",
"sklearn.preprocessing.LabelBinarizer",
"tensorflow.keras.layers.Dropout",
"numpy.array",
"tensorflow.keras.layers.Flatten",
"tensorflow.keras.utils.to_categorical",
"tensorflow.keras.layers.Input"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.7",
"2.3",
"2.4",
"2.5",
"2.6"
]
}
] |
jaywilhelm/OpenUxAS | [
"76b08d94c4c51ca51d9f79c9db03d7344e9d6552",
"76b08d94c4c51ca51d9f79c9db03d7344e9d6552"
] | [
"examples/02_Example_WaterwaySearch/dubinsUAV.py",
"examples/02_Example_WaterwaySearch/lineSegmentAoE.py"
] | [
"from matplotlib import pyplot as plt\nfrom shapely.geometry import Point\nfrom shapely.geometry.polygon import Polygon\n#from lineSegmentAoE import *\nimport numpy as np\nimport sys\n\nclass dubinsUAV():\n\n def __init__(self, position, velocity, heading, dt=0.1):\n\n self.velocity = velocity\n self.turnRateLimited = True\n self.v = velocity\n self.dt = dt\n self.t = 0\n self.turnrate = np.deg2rad(20)\n #self.turn_radius = []\n\n\n #Current state\n self.x = position[0]\n self.y = position[1]\n self.vx = []\n self.vy = []\n self.lastDist = np.inf\n #self.cmdHeading = []\n #self.flightEnvX = []\n #self.flightEnvY = []\n \n self.heading = heading\n self.currentWPIndex = 0\n self.withinThreshold = False\n\n # History\n self.xs = np.array([])\n self.ys = np.array([])\n self.vxs = np.array([])\n self.vys = np.array([])\n self.headings = np.array([])\n #self.headingcmds = np.array([])\n self.ts = np.array([])\n\n self.vx = velocity * np.cos(heading)\n self.vy = velocity * np.sin(heading)\n self.dt = dt\n #self.turn_radius = self.v / self.turnrate\n def getPosition(self):\n return [self.position[0], self.position[1]]\n\n def setWaypoints(self, newwps, newradius=0.01):\n self.waypoints = newwps\n self.wpRadius = newradius\n\n def getWaypoints(self):\n return self.waypoints\n \n def getActiveWaypoint(self):\n return self.waypoints[self.currentWPIndex]\n\n def simulateWPDubins(self):\n # currentWPIndex = 0\n # withinThreshold = False\n # lastDist = sys.maxsize\n wpRadius = self.wpRadius\n activeWP = self.getActiveWaypoint()\n dist = self.distance(activeWP, (self.x, self.y))\n\n print('D: ' + str(dist) + '\\t ' + str(dist < wpRadius) + '\\t ' + str(dist > self.lastDist) + '\\t# ' + str(self.currentWPIndex) + '\\tLast: ' + str(self.lastDist))\n\n\n if (dist < wpRadius and dist > self.lastDist):\n if(self.currentWPIndex < len(self.waypoints)-1):\n self.currentWPIndex += 1\n print(\"WP Increment\")\n #update distance...\n dist = self.distance(self.getActiveWaypoint(), (self.x, self.y))\n else:\n print(\"end of list, do something\")\n\n RHeading = np.arctan2(self.y - activeWP[1], self.x - activeWP[0])\n RHeading += np.deg2rad(180)\n if(RHeading >= np.pi*2):\n RHeading -= np.pi*2\n self.update_pos(RHeading)\n\n self.lastDist = dist\n\n def distance(self, a, b):\n return np.sqrt((a[0] - b[0])**2 + (a[1] - b[1])**2)\n\n\n def update_pos(self, RequestedHeading):\n\n if self.turnRateLimited:\n theta = self.heading \n if(np.abs(RequestedHeading - theta) < self.turnrate * self.dt):\n turnrate = np.abs(RequestedHeading - theta) / self.dt\n else:\n turnrate = self.turnrate\n\n if abs(theta - RequestedHeading) < np.pi:\n if theta - RequestedHeading < 0:\n theta = theta + turnrate * self.dt\n else:\n theta = theta - turnrate * self.dt\n\n else:\n if theta - RequestedHeading > 0:\n theta = theta + turnrate * self.dt\n else:\n theta = theta - turnrate * self.dt\n # if(np.abs(RequestedHeading - theta) > self.turnrate * self.dt):\n # if theta - RequestedHeading < 0:\n # theta = theta + self.turnrate * self.dt\n # else:\n # theta = theta - self.turnrate * self.dt\n # else:\n # theta = RequestedHeading\n else:\n theta = RequestedHeading\n if(theta >= np.pi*2):\n theta -= np.pi*2\n print('Req: '+ str(np.rad2deg(RequestedHeading)) + '\\ttheta ' + str(np.rad2deg(theta)))\n # Update States\n self.t = self.t + self.dt\n self.heading = theta\n #self.cmdHeading = VF_heading\n self.update_pos_simple()\n\n def update_pos_simple(self):\n # Update States\n self.t = self.t + self.dt\n theta = self.heading\n self.vx = self.v * np.cos(theta)\n self.vy = self.v * np.sin(theta)\n self.x = self.x + self.vx * self.dt\n self.y = self.y + self.vy * self.dt\n self.position = [(self.x, self.y)] # added for CAS\n\n # Update History\n self.xs = np.append(self.xs, self.x)\n self.ys = np.append(self.ys, self.y)\n self.vxs = np.append(self.vxs, self.vx)\n self.vys = np.append(self.vys, self.vy)\n self.headings = np.append(self.headings, self.heading)\n self.ts = np.append(self.ts, self.t)\n\n",
"import numpy as np\nfrom matplotlib import pyplot as plt\n#from vectorFieldMO import *\n\ndef distance(a, b):\n return np.sqrt((a[0] - b[0])**2 + (a[1] - b[1])**2)\n\ndef getAngle(p0, p1, p2):\n # shift line intersection to (0,0)\n _p0 = ((p0[0] - p1[0]), (p0[1] - p1[1]))\n _p2 = ((p2[0] - p1[0]), (p2[1] - p1[1]))\n\n v0_angle = np.arctan2(_p0[1], _p0[0])\n if v0_angle > 180:\n v0_angle = v0_angle - 360\n \n v2_angle = np.arctan2(_p2[1], _p2[0])\n if v2_angle > 180:\n v2_angle = v2_angle - 360\n\n angle = (v0_angle + v2_angle) / 2\n\n return angle\n\n\n# https://stackoverflow.com/questions/28417604/plotting-a-line-from-a-coordinate-with-and-angle\ndef getAngleLine(point, angle, length):\n x, y = point\n\n startY = y + length * np.sin(angle)\n startX = x + length * np.cos(angle)\n\n endY = y + length * np.sin(np.pi + angle)\n endX = x + length * np.cos(np.pi + angle)\n\n return [(startX, startY), (endX, endY)]\n\ndef getBorder(wpList, uavPosition, paddingScalar):\n xlist = [pt[0] for pt in wpList]\n ylist = [pt[1] for pt in wpList]\n \n x_max = np.max(xlist)\n if uavPosition[0] > x_max:\n x_max = uavPosition[0]\n x_min = np.min(xlist)\n if uavPosition[0] < x_min:\n x_min = uavPosition[0]\n y_max = np.max(ylist)\n if uavPosition[1] > y_max:\n y_max = uavPosition[1]\n y_min = np.min(ylist)\n if uavPosition[1] < y_min:\n y_min = uavPosition[1]\n\n padding = paddingScalar * x_max\n if (padding < paddingScalar * np.abs(x_min)):\n padding = paddingScalar * np.abs(x_min)\n if (padding < paddingScalar * y_max):\n padding = paddingScalar * y_max\n if (padding < paddingScalar * np.abs(y_min)):\n padding = paddingScalar * np.abs(y_min)\n\n x_max += padding\n x_min -= padding\n y_max += padding\n y_min -= padding\n\n border_pts = [(x_max, y_max), \n (x_max, y_min),\n (x_min, y_min),\n (x_min, y_max),\n (x_max, y_max)]\n return border_pts\n\ndef lineIntersect(line1, line2):\n xdiff = (line1[0][0] - line1[1][0], line2[0][0] - line2[1][0])\n ydiff = (line1[0][1] - line1[1][1], line2[0][1] - line2[1][1])\n\n def det(a, b):\n return a[0] * b[1] - a[1] * b[0]\n\n div = det(xdiff, ydiff)\n if div == 0:\n return (np.NaN, np.NaN) \n\n d = (det(*line1), det(*line2))\n x = det(d, xdiff) / div\n y = det(d, ydiff) / div\n\n return x, y\n\ndef isBetween(pt0, intersect, pt1):\n distAB = distance(pt0, intersect)\n distBC = distance(intersect, pt1)\n distAC = distance(pt0, pt1)\n\n # triangle inequality\n return np.isclose((distAB + distBC), distAC)\n\ndef getAoEPolygon(border, divLine):\n foundIntersect = False\n AoEPolygon = []\n\n for i in range(len(border) - 1):\n intersect = lineIntersect(divLine, [border[i], border[i + 1]])\n\n if np.isclose(intersect[0], border[i][0]) and np.isclose(intersect[1], border[i][1]):\n continue\n\n if (not np.isnan(intersect[0])) and (isBetween(border[i], intersect, border[i + 1])):\n if foundIntersect:\n AoEPolygon.append(border[i])\n AoEPolygon.append(intersect)\n\n break\n else:\n foundIntersect = True\n AoEPolygon.append(intersect)\n\n elif foundIntersect:\n AoEPolygon.append(border[i])\n\n AoEPolygon.append(AoEPolygon[0])\n return AoEPolygon\n\ndef main():\n wpList = [(0,0), (1,1), (2,0), (3,0), (4,1), (4,0), (3,-1)]\n # wpList = [(0,0), (1,1), (2,0), (3,0), (3,1)]\n # wpList = [(3,1), (3,0), (2,0), (1,1), (0,0)]\n # wpList = [(2,0), (3,0), (3,1)]\n # wpList = [(0,0), (1,1), (2,0)]\n # wpList = [(0,0), (0,3), (2,5)]\n divLines = []\n border = getBorder(wpList, 0.1)\n\n wpListX = [pt[0] for pt in wpList]\n wpListY = [pt[1] for pt in wpList]\n\n borderX = [pt[0] for pt in border]\n borderY = [pt[1] for pt in border]\n\n plt.plot(wpListX, wpListY, 'k')\n plt.plot(borderX, borderY, 'c')\n plt.axis('equal')\n plt.show()\n\n # 2 lines at a time\n for i in range(len(wpList) - 2):\n plt.plot(wpListX, wpListY, 'k')\n plt.plot(borderX, borderY, 'c')\n\n print('--------------------------------')\n \n angle = getAngle(wpList[i], wpList[i + 1], wpList[i + 2])\n # avgLen = (distance(wpList[i], wpList[i + 1]) + distance(wpList[i + 1], wpList[i + 2])) / 2\n divLen = distance(border[0], border[2])\n\n divLine = getAngleLine(wpList[i + 1], angle, divLen)\n divLines.append(divLine)\n\n aoe = getAoEPolygon(border, divLine)\n print(aoe)\n\n print('--------------------------------')\n\n divX = [pt[0] for pt in divLine]\n divY = [pt[1] for pt in divLine]\n plt.plot(divX, divY, '--c')\n\n aoeX = [pt[0] for pt in aoe]\n aoeY = [pt[1] for pt in aoe]\n plt.plot(aoeX, aoeY, '--r')\n\n plt.axis('equal')\n plt.show()\n\ndef wpLineSegmentVF():\n wpList = [(0,0), (1,1), (2,0), (3,0), (4,1), (4,0), (3,-1)]\n for i in range(len(wpList) - 1):\n plt.plot([wpList[i][0], wpList[i+1][0]], [wpList[i][1], wpList[i+1][1]], 'c') # line: [i, i+1]\n\n VFLine = VectorField(G=1,H =1, name=\"Line Path\")\n NormTotal = True\n Plot_VF = True\n\n v = (wpList[i+1][0] - wpList[i][0], wpList[i+1][1] - wpList[i][1])\n delta = np.arctan2(v[1], v[0]) + np.radians(90)\n print(np.degrees(delta))\n\n VFLine.VFLine(wpList[i][0], wpList[i][1], delta)\n VFList = VectorFieldList([VFLine], NormTotal)\n VFPlotMachine.TotalPlotList(VFList,Plot_VF)\n\n plt.axis('equal')\n plt.show()\n\nif __name__ == '__main__':\n wpLineSegmentVF()\n"
] | [
[
"numpy.sqrt",
"numpy.abs",
"numpy.cos",
"numpy.rad2deg",
"numpy.sin",
"numpy.arctan2",
"numpy.deg2rad",
"numpy.append",
"numpy.array"
],
[
"numpy.radians",
"numpy.sqrt",
"numpy.abs",
"numpy.min",
"numpy.isnan",
"numpy.degrees",
"numpy.cos",
"numpy.sin",
"numpy.arctan2",
"numpy.max",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.axis",
"matplotlib.pyplot.show",
"numpy.isclose"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
lucifer2859/sac-discrete-pytorch | [
"c6f367d95bdc5cee8b3d6e5a01172bb99af5b171"
] | [
"sacd/agent/sacd.py"
] | [
"import os\nimport numpy as np\nimport torch\nfrom torch.optim import Adam\n\nfrom .base import BaseAgent\nfrom sacd.model import TwinnedQNetwork, CategoricalPolicy\nfrom sacd.utils import disable_gradients\n\n# If you want to use Prioritized Experience Replay(PER), N-step return \n# or Dueling Networks, change use_per, multi_step or dueling_net respectively.\n\nclass SacdAgent(BaseAgent):\n\n def __init__(self, env, test_env, log_dir, num_steps=100000, batch_size=64,\n lr=0.0003, memory_size=1000000, gamma=0.99, multi_step=1,\n target_entropy_ratio=0.98, start_steps=20000,\n update_interval=4, target_update_interval=8000,\n use_per=False, dueling_net=False, num_eval_steps=125000,\n max_episode_steps=27000, log_interval=10, eval_interval=1000,\n device='cuda:0', seed=0):\n\n super().__init__(\n env, test_env, log_dir, num_steps, batch_size, memory_size, gamma,\n multi_step, target_entropy_ratio, start_steps, update_interval,\n target_update_interval, use_per, num_eval_steps, max_episode_steps,\n log_interval, eval_interval, device, seed)\n\n # Define networks.\n self.policy = CategoricalPolicy(\n self.env.observation_space.shape[0], self.env.action_space.n\n ).to(self.device)\n\n self.online_critic = TwinnedQNetwork(\n self.env.observation_space.shape[0], self.env.action_space.n,\n dueling_net=dueling_net).to(device=self.device)\n\n self.target_critic = TwinnedQNetwork(\n self.env.observation_space.shape[0], self.env.action_space.n,\n dueling_net=dueling_net).to(device=self.device).eval()\n\n # Copy parameters of the learning network to the target network.\n self.target_critic.load_state_dict(self.online_critic.state_dict())\n\n # Disable gradient calculations of the target network.\n disable_gradients(self.target_critic)\n\n self.policy_optim = Adam(self.policy.parameters(), lr=lr)\n self.q1_optim = Adam(self.online_critic.Q1.parameters(), lr=lr)\n self.q2_optim = Adam(self.online_critic.Q2.parameters(), lr=lr)\n\n # Target entropy is -log(1/|A|) * ratio (= maximum entropy * ratio).\n self.target_entropy = \\\n -np.log(1.0 / self.env.action_space.n) * target_entropy_ratio\n\n # We optimize log(alpha), instead of alpha.\n self.log_alpha = torch.zeros(1, requires_grad=True, device=self.device)\n self.alpha = self.log_alpha.exp()\n self.alpha_optim = Adam([self.log_alpha], lr=lr)\n\n def explore(self, state):\n # Act with randomness.\n state = torch.ByteTensor(\n state[None, ...]).to(self.device).float() / 255.\n with torch.no_grad():\n action, _, _ = self.policy.sample(state)\n return action.item()\n\n def exploit(self, state):\n # Act without randomness.\n state = torch.ByteTensor(\n state[None, ...]).to(self.device).float() / 255.\n with torch.no_grad():\n action = self.policy.act(state)\n return action.item()\n\n def update_target(self):\n self.target_critic.load_state_dict(self.online_critic.state_dict())\n\n def calc_current_q(self, states, actions, rewards, next_states, dones):\n curr_q1, curr_q2 = self.online_critic(states)\n curr_q1 = curr_q1.gather(1, actions.long())\n curr_q2 = curr_q2.gather(1, actions.long())\n return curr_q1, curr_q2\n\n def calc_target_q(self, states, actions, rewards, next_states, dones):\n with torch.no_grad():\n _, action_probs, log_action_probs = self.policy.sample(next_states)\n next_q1, next_q2 = self.target_critic(next_states)\n next_q = (action_probs * (\n torch.min(next_q1, next_q2) - self.alpha * log_action_probs\n )).sum(dim=1, keepdim=True)\n\n assert rewards.shape == next_q.shape\n return rewards + (1.0 - dones) * self.gamma_n * next_q\n\n def calc_critic_loss(self, batch, weights):\n curr_q1, curr_q2 = self.calc_current_q(*batch)\n target_q = self.calc_target_q(*batch)\n\n # TD errors for updating priority weights\n errors = torch.abs(curr_q1.detach() - target_q)\n\n # We log means of Q to monitor training.\n mean_q1 = curr_q1.detach().mean().item()\n mean_q2 = curr_q2.detach().mean().item()\n\n # Critic loss is mean squared TD errors with priority weights.\n q1_loss = torch.mean((curr_q1 - target_q).pow(2) * weights)\n q2_loss = torch.mean((curr_q2 - target_q).pow(2) * weights)\n\n return q1_loss, q2_loss, errors, mean_q1, mean_q2\n\n def calc_policy_loss(self, batch, weights):\n states, actions, rewards, next_states, dones = batch\n\n # (Log of) probabilities to calculate expectations of Q and entropies.\n _, action_probs, log_action_probs = self.policy.sample(states)\n\n with torch.no_grad():\n # Q for every actions to calculate expectations of Q.\n q1, q2 = self.online_critic(states)\n q = torch.min(q1, q2)\n\n # Expectations of entropies.\n entropies = -torch.sum(\n action_probs * log_action_probs, dim=1, keepdim=True)\n\n # Expectations of Q.\n q = torch.sum(torch.min(q1, q2) * action_probs, dim=1, keepdim=True)\n\n # Policy objective is maximization of (Q + alpha * entropy) with\n # priority weights.\n policy_loss = (weights * (- q - self.alpha * entropies)).mean()\n\n return policy_loss, entropies.detach()\n\n def calc_entropy_loss(self, entropies, weights):\n assert not entropies.requires_grad\n\n # Intuitively, we increse alpha when entropy is less than target\n # entropy, vice versa.\n entropy_loss = -torch.mean(\n self.log_alpha * (self.target_entropy - entropies)\n * weights)\n return entropy_loss\n\n def save_models(self, save_dir):\n super().save_models(save_dir)\n self.policy.save(os.path.join(save_dir, 'policy.pth'))\n self.online_critic.save(os.path.join(save_dir, 'online_critic.pth'))\n self.target_critic.save(os.path.join(save_dir, 'target_critic.pth'))\n"
] | [
[
"torch.optim.Adam",
"torch.mean",
"numpy.log",
"torch.ByteTensor",
"torch.zeros",
"torch.min",
"torch.sum",
"torch.no_grad"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
freenowill/autoVC-WavRNN | [
"871a7ae5671e81fe4396cbc6f89a90009b01049b"
] | [
"vocoder/inference_wavrnn.py"
] | [
"from vocoder.models.fatchord_version import WaveRNN\r\nfrom vocoder import hparams as hp\r\nimport torch\r\n\r\n\r\n_model = None # type: WaveRNN\r\n\r\ndef load_model(weights_fpath, verbose=True):\r\n global _model\r\n \r\n if verbose:\r\n print(\"Building Wave-RNN\")\r\n _model = WaveRNN(\r\n rnn_dims=hp.voc_rnn_dims,\r\n fc_dims=hp.voc_fc_dims,\r\n bits=hp.bits,\r\n pad=hp.voc_pad,\r\n upsample_factors=hp.voc_upsample_factors,\r\n feat_dims=hp.num_mels,\r\n compute_dims=hp.voc_compute_dims,\r\n res_out_dims=hp.voc_res_out_dims,\r\n res_blocks=hp.voc_res_blocks,\r\n hop_length=hp.hop_length,\r\n sample_rate=hp.sample_rate,\r\n mode=hp.voc_mode\r\n ).cuda()\r\n \r\n if verbose:\r\n print(\"Loading model weights at %s\" % weights_fpath)\r\n checkpoint = torch.load(weights_fpath)\r\n _model.load_state_dict(checkpoint['model_state'])\r\n _model.eval()\r\n\r\n\r\ndef is_loaded():\r\n return _model is not None\r\n\r\n\r\ndef infer_waveform(mel, normalize=True, batched=True, target=24000, overlap=1000,\r\n progress_callback=None):\r\n \"\"\"\r\n Infers the waveform of a mel spectrogram output by the synthesizer (the format must match \r\n that of the synthesizer!)\r\n \r\n :param normalize: \r\n :param batched: \r\n :param target: \r\n :param overlap: \r\n :return: \r\n \"\"\"\r\n if _model is None:\r\n raise Exception(\"Please load Wave-RNN in memory before using it\")\r\n \r\n if normalize:\r\n mel = mel / hp.mel_max_abs_value\r\n mel = torch.from_numpy(mel[None, ...])\r\n wav = _model.generate(mel, batched, target, overlap, hp.mu_law, progress_callback)\r\n return wav\r\n"
] | [
[
"torch.from_numpy",
"torch.load"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Peyo-Supp/Master-Production-Planning-Algorithm | [
"c91bf9304bcf1ad7ecdf6729ee483a6e3de45a38"
] | [
"Discount_bracket_replenishment.py"
] | [
"import pandas as pd\nimport math as m\nimport numpy as np\n\n\"\"\"\nalgorithm that calculate the best alternative from supplier order bracket based on data provided.\n\n\"\"\"\n\n#input data here!\n# demand_in_cases =\n# order_cost =\n# cost_per_case =\n# bracket_cost = []\n# bracket_minimum = []\n# holding_rate =\n\nEOQ0 = np.sqrt((2*demand_in_cases*order_cost)/(cost_per_case*holding_rate))\nATCEOQ = demand_in_cases/EOQ0*order_cost + EOQ0/2*holding_rate*cost_per_case + demand_in_cases*cost_per_case\n\n#create a dataframe for the bracket_minimum)\nBM = np.array(bracket_minimum)\n\n\ndfBM = pd.DataFrame({'1':[BM[0]],'2':[BM[1]],'3':[BM[2]],'4':[BM[3]],'5':[BM[4]],'6':[BM[5]],'7':[BM[6]]}, index = [1])\n\n#compute EOQ for each bracket and put into its own dataframe\n\nBC = np.array(bracket_cost)\nBM = np.array(bracket_minimum)\n\nEOQ = np.sqrt((2*demand_in_cases*order_cost)/(BC*holding_rate))\n\nDfEOQ = pd.DataFrame({'1':[EOQ[0]],'2': [EOQ[1]],'3':[EOQ[2]],'4':[EOQ[3]],'5':[EOQ[4]],'6':[EOQ[5]],'6':[EOQ[6]]}, index =[1])\n\n\n#substrack the BM data frame with eoq dataframe to find which data is greater than 0\n\ncheck = (dfBM.sub(DfEOQ))\n\nc = np.array(check)\nprint(c)\n\ndef calc_atc(c,val):\n\n for i in c:\n if i<= val:\n print( 'a' )\n\n else:\n print('b')\nval = 0\ncalc_atc(c,val)\n\n\n\n\n\n"
] | [
[
"numpy.array",
"numpy.sqrt",
"pandas.DataFrame"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
teamcfe/AI-as-an-API | [
"a291fc0e6ec380139599a948f2efd58923c70784"
] | [
"app/ml.py"
] | [
"import json\nimport numpy as np\n\nfrom typing import Optional, List\nfrom pathlib import Path\nfrom dataclasses import dataclass # pip install dataclasses\n\nfrom tensorflow.keras.models import load_model\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\nfrom tensorflow.keras.preprocessing.text import tokenizer_from_json\n\nfrom . import encoders\n\n@dataclass\nclass AIModel:\n model_path: Path\n tokenizer_path: Optional[Path] = None\n metadata_path: Optional[Path] = None\n\n model = None\n tokenizer = None\n metadata = None\n\n def __post_init__(self):\n if self.model_path.exists():\n self.model = load_model(self.model_path) \n if self.tokenizer_path:\n if self.tokenizer_path.exists():\n if self.tokenizer_path.name.endswith(\"json\"): \n tokenizer_text = self.tokenizer_path.read_text()\n self.tokenizer = tokenizer_from_json(tokenizer_text)\n if self.metadata_path:\n if self.metadata_path.exists():\n if self.metadata_path.name.endswith(\"json\"): \n self.metadata = json.loads(self.metadata_path.read_text())\n\n \n def get_model(self):\n if not self.model:\n raise Exception(\"Model not implemeted\")\n return self.model\n \n def get_tokenizer(self):\n if not self.tokenizer:\n raise Exception(\"tokenizer not implemeted\")\n return self.tokenizer\n \n def get_metadata(self):\n if not self.metadata:\n raise Exception(\"metadata not implemeted\")\n return self.metadata\n\n def get_sequences_from_text(self, texts: List[str] ):\n tokenizer = self.get_tokenizer()\n sequences = tokenizer.texts_to_sequences(texts)\n return sequences\n\n def get_input_from_sequences(self, sequences):\n maxlen = self.get_metadata().get('max_sequence') or 280\n x_input = pad_sequences(sequences, maxlen=maxlen)\n return x_input\n\n def get_label_legend_inverted(self):\n legend = self.get_metadata().get('labels_legend_inverted') or {}\n if len(legend.keys()) != 2:\n raise Exception(\"You legend is incorrect\")\n return legend\n\n def get_label_pred(self, idx, val):\n legend = self.get_label_legend_inverted()\n return {\"label\": legend[str(idx)], \"confidence\": val}\n\n def get_top_pred_labled(self, preds):\n top_idx_val = np.argmax(preds)\n val = preds[top_idx_val]\n return self.get_label_pred(top_idx_val, val)\n\n def predict_text(self, query:str, include_top=True, encode_to_json=True):\n model = self.get_model()\n sequences = self.get_sequences_from_text([query])\n x_input = self.get_input_from_sequences(sequences)\n preds = model.predict(x_input)[0]\n labeled_preds = [self.get_label_pred(i, x) for i, x in enumerate(list(preds))]\n results = {\n \"predictions\": labeled_preds\n }\n if include_top:\n results['top'] = self.get_top_pred_labled(preds)\n if encode_to_json:\n results = encoders.encode_to_json(results, as_py=True)\n return results"
] | [
[
"tensorflow.keras.models.load_model",
"numpy.argmax",
"tensorflow.keras.preprocessing.text.tokenizer_from_json",
"tensorflow.keras.preprocessing.sequence.pad_sequences"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"2.2",
"2.3",
"2.4",
"2.5",
"2.6"
]
}
] |
31337mbf/MLAlgorithms | [
"3c8e16b8de3baf131395ae57edd479e59566a7c6"
] | [
"mla/rbm.py"
] | [
"# coding:utf-8\nimport logging\n\nimport numpy as np\nfrom scipy.special import expit\n\nfrom mla.base import BaseEstimator\nfrom mla.utils import batch_iterator\n\nnp.random.seed(9999)\nsigmoid = expit\n\n\"\"\"\nReferences:\nA Practical Guide to Training Restricted Boltzmann Machines https://www.cs.toronto.edu/~hinton/absps/guideTR.pdf\n\"\"\"\n\n\nclass RBM(BaseEstimator):\n y_required = False\n\n def __init__(self, n_hidden=128, learning_rate=0.1, batch_size=10, max_epochs=100):\n \"\"\"Bernoulli Restricted Boltzmann Machine (RBM)\n\n Parameters\n ----------\n\n n_hidden : int, default 128\n The number of hidden units.\n learning_rate : float, default 0.1\n batch_size : int, default 10\n max_epochs : int, default 100\n \"\"\"\n self.max_epochs = max_epochs\n self.batch_size = batch_size\n self.lr = learning_rate\n self.n_hidden = n_hidden\n\n def fit(self, X, y=None):\n self.n_visible = X.shape[1]\n self._init_weights()\n self._setup_input(X, y)\n self._train()\n\n def _init_weights(self):\n\n self.W = np.random.randn(self.n_visible, self.n_hidden) * 0.1\n\n # Bias for visible and hidden units\n self.bias_v = np.zeros(self.n_visible, dtype=np.float32)\n self.bias_h = np.zeros(self.n_hidden, dtype=np.float32)\n\n self.errors = []\n\n def _train(self):\n \"\"\"Use CD-1 training procedure, basically an exact inference for `positive_associations`,\n followed by a \"non burn-in\" block Gibbs Sampling for the `negative_associations`.\"\"\"\n\n for i in range(self.max_epochs):\n error = 0\n for batch in batch_iterator(self.X, batch_size=self.batch_size):\n positive_hidden = sigmoid(np.dot(batch, self.W) + self.bias_h)\n hidden_states = self._sample(positive_hidden) # sample hidden state h1\n positive_associations = np.dot(batch.T, positive_hidden)\n\n negative_visible = sigmoid(np.dot(hidden_states, self.W.T) + self.bias_v)\n negative_visible = self._sample(negative_visible) # use the sampled hidden state h1 to sample v1\n negative_hidden = sigmoid(np.dot(negative_visible, self.W) + self.bias_h)\n negative_associations = np.dot(negative_visible.T, negative_hidden)\n\n lr = self.lr / float(batch.shape[0])\n self.W += lr * ((positive_associations - negative_associations) / float(self.batch_size))\n self.bias_h += lr * (negative_hidden.sum(axis=0) - negative_associations.sum(axis=0))\n self.bias_v += lr * (np.asarray(batch.sum(axis=0)).squeeze() - negative_visible.sum(axis=0))\n\n error += np.sum((batch - negative_visible) ** 2)\n\n self.errors.append(error)\n logging.info(\"Iteration %s, error %s\" % (i, error))\n logging.debug(\"Weights: %s\" % self.W)\n logging.debug(\"Hidden bias: %s\" % self.bias_h)\n logging.debug(\"Visible bias: %s\" % self.bias_v)\n\n def _sample(self, X):\n return X > np.random.random_sample(size=X.shape)\n\n def _predict(self, X=None):\n return sigmoid(np.dot(X, self.W) + self.bias_h)\n"
] | [
[
"numpy.dot",
"numpy.random.seed",
"numpy.random.random_sample",
"numpy.random.randn",
"numpy.zeros",
"numpy.sum"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
kurtmaia/JointSBM | [
"516daa6249694118cca4db2a4a92e0ef7164166f"
] | [
"jointSBM.py"
] | [
"import numpy as np \nimport scipy as sp\n\nfrom numpy.linalg import inv, cholesky\nfrom scipy.linalg import eig\nfrom sklearn.metrics.cluster import normalized_mutual_info_score as nmi\nfrom sklearn.metrics.cluster import adjusted_rand_score as ari\nfrom sklearn.metrics.cluster import contingency_matrix\nfrom sklearn.cluster import KMeans\nimport random\n\nimport time\nfrom joblib import Parallel, delayed\nimport multiprocessing\nfrom tqdm import tqdm\nimport logging\n\nfrom utils.utils import *\n\n\n\ndef update_W(X,Q,deltas_,K):\n delta2_n, delta2, gamma_n = deltas_\n\n XnQn = []\n XXn = []\n for i in range(len(Q)):\n rt = np.sum(delta2)/np.sum(delta2_n[i])\n XnQn.append(np.matmul(X[i].T,Q[i]*gamma_n[i]))\n XXn.append(delta2_n[i]*gamma_n[i])\n XQ = np.sum(XnQn,axis = 0) \n denom = np.sum(XXn,axis = 0)\n\n W = np.matmul(inv(denom),XQ)\n return W\n\ndef update_xni(q,W,rt,fac,gamman,K):\n dif = W - q\n term2 = ((q*np.sqrt(fac) + q*1./np.sqrt(rt))**2).sum(axis = 1)\n dist = np.diag(np.matmul(dif,dif.T))*gamman + term2\n x = onehot_vec(np.argmin(dist),K)\n return x\n\ndef get_fac(Vn,V,K):\n x = np.eye(K) \n fac = np.nan_to_num([[(Vn - x[i,:] + x[k,:])/(V - x[i,:] + x[k,:]) for k in range(K)] for i in range(K)])\n # fac[fac<0] = 0\n gamman = fac.sum(axis=2)\n return fac, gamman\n\ndef processLoop(Qn,W,Xn,V,deltas2_n,K):\n Vn = np.diag(deltas2_n)\n rt = np.sum(V)/np.sum(Vn)\n fac,gamman = get_fac(Vn,V,K)\n for i in range(Xn.shape[0]):\n xx = Xn[i,].argmax()\n Xn[i,] = update_xni(Qn[i,],W,rt,fac[xx],gamman[xx],K)\n return Xn\n\ndef mcr(x,y):\n cm = contingency_matrix(x,y)\n return (cm.max(axis = 0).sum())*1./cm.sum()\n\ndef get_Qn(adj,K):\n if sp.sparse.issparse(adj):\n eig_decomp = sp.sparse.linalg.eigs(adj,K)\n else:\n eig_decomp = eig(adj)\n args = np.argsort(-abs(eig_decomp[0]),)[:K]\n D = (eig_decomp[0][args])\n U = (eig_decomp[1][:,args])\n return abs(np.matmul(U,np.diag(D)))\n\ndef get_counts(X):\n delta2_n = np.array([np.diag(np.sum(X[i],axis=0)) for i in range(len(X))])\n delta2 = np.sum(delta2_n,axis=0)\n\n gamma_n = np.array([np.sum(inv(delta2)*delta2_n[i]) for i in range(len(X))])\n return delta2_n, delta2, gamma_n \n\nclass jointSBM(object):\n def __init__(self, graphs, K, \\\n edgelist = False,\n tol = 1e-5, groundTruth = None,\n init = 'kmeans++', seed = 242, **kwargs):\n graphs = graphs.copy()\n if (type(graphs)!=dict):\n self.graphNames = [\"graph\"+str(g) for g in range(1,len(graphs)+1)]\n graphs = dict(zip(self.graphNames,graphs))\n else: \n self.graphNames = [k for k in graphs.keys()]\n if (groundTruth!=None):\n if (type(groundTruth)==dict):\n self.groundTruth = [groundTruth[g] for g in self.graphNames]\n # self.groundTruth = [g for k,g in groundTruth.items()]\n\n\n if np.any([g.shape[0]!=g.shape[1] for k,g in graphs.items()]):\n print(\"Converting edgelists to sparse adjacency matrices...\")\n edgelist = True\n\n if edgelist:\n self.idx2node = {}\n for gg in self.graphNames:\n graphs[gg], self.idx2node[gg] = edgelist2sparse(graphs[gg],**kwargs)\n # print(\"Converted edgelists to sparse adjacency matrices.\")\n\n self.graphs = [graphs[g] for g in self.graphNames]\n n_graphs = len(graphs)\n\n\n self.n_graphs = n_graphs\n self.n_nodes_array = [self.graphs[i].shape[0] for i in range(n_graphs)]\n self.total_nodes = np.sum(self.n_nodes_array)\n\n self.K = K\n self.tol = tol \n self.init = init \n self.seed = seed\n self.data_prepared = False\n \n def prepare_data(self):\n Q = []\n X = []\n for i in tqdm(range(self.n_graphs)):\n Qn = get_Qn(self.graphs[i],self.K)*np.sqrt(self.total_nodes*1./self.n_nodes_array[i])\n Q.append(Qn)\n X.append(self.initX(Qn))\n\n self.Q = Q\n self.X = X\n self.deltas_ = get_counts(X)\n self.data_prepared = True\n\n def initX(self, Qn):\n K = self.K\n if self.init == 'kmeans++':\n km = KMeans(n_clusters=K,random_state=self.seed).fit(Qn).labels_\n Xn = np.vstack([onehot_vec(r,K) for r in km])\n else:\n random.seed(self.seed)\n Xn = np.random.multinomial(1,[1./K]*K,size = n_nodes)\n return Xn\n\n def fit(self, printLoss = False, maxIter = 200, parallel = False, n_cores = -1):\n self.maxIter = maxIter \n self.parallel = parallel \n self.n_cores = n_cores \n if not self.data_prepared:\n self.prepare_data()\n X = self.X\n Q = self.Q\n deltas_ = self.deltas_\n K = self.K\n n_graphs = self.n_graphs\n n_nodes_array = self.n_nodes_array \n Loss = [0]\n stopValue = 1\n iter = -1\n measures = {}\n while (stopValue > self.tol and iter < self.maxIter):\n t0 = time.time()\n iter = iter + 1\n W = update_W(X,Q,deltas_,K)\n\n V = np.diag(deltas_[1])\n memberships = []\n counts_memberships = np.zeros([1,K])\n if self.parallel:\n if n_cores == -1:\n num_cores = multiprocessing.cpu_count()\n else: \n num_cores = self.n_cores\n \n X = Parallel(n_jobs=num_cores)(delayed(processLoop)(Q[n],W,X[n],V,deltas_[0][n],K) for n in range(n_graphs))\n\n for x in X:\n # memberships.append(np.argmax(x,1))\n counts_memberships += np.sum(x,0)\n else:\n for n in range(n_graphs):\n X[n] = processLoop(Q[n],W,X[n],V,deltas_[0][n],K)\n counts_memberships += np.sum(X[n],0)\n \n if (np.sum(counts_memberships==0.)>0):\n iter = 1\n logging.warning(\"Restarting...\")\n X = [np.random.multinomial(1,[1./K]*K,size = n_nodes_array[i]) for i in range(n_graphs)]\n\n memberships = [np.argmax(X[n],1) for n in range(len(X))]\n deltas_ = get_counts(X)\n \n loss = np.ndarray([n_graphs])\n for n in range(n_graphs):\n XW = np.matmul(X[n],W)\n rt = np.sum(deltas_[1])/np.sum(deltas_[0][n])\n term = np.sqrt(np.matmul(inv(deltas_[1]),deltas_[0][n])) + np.sqrt(np.eye(K)*1./rt)\n loss[n] = deltas_[2][n]*frobenius_norm(XW-Q[n])**2 + frobenius_norm(np.matmul(Q[n],term))**2\n t1 = time.time()\n Loss.append(np.sum(loss))\n if printLoss:\n print(\"Iter: {} | Loss: {}\".format(iter, Loss[iter]))\n\n stopValue = abs(Loss[iter] - Loss[iter-1])\n\n if (self.groundTruth!=None):\n measures[iter] = self.evalutate(memberships)\n measures[iter]['Time'] = t1-t0\n else:\n measures[iter] = {'Time':t1-t0}\n \n theta = estimateTheta(X,self.graphs)\n order = np.argsort(-1*np.diag(theta),)\n theta = theta[order,][:,order]\n self.theta = theta\n\n self.W = W[order,]\n\n memberships = []\n for n in range(n_graphs):\n X[n] = X[n][:,order]\n memberships.append(dict(zip(range(1,len(X[n])+1),np.argmax(X[n],1))))\n\n memberships = dict(zip(self.graphNames,memberships))\n self.memberships = memberships\n self.X = X\n self.measures = measures\n self.iter = iter\n\n return memberships, theta, W, measures\n\n def evalutate(self, memberships):\n groundTruth = self.groundTruth\n n_graphs = self.n_graphs\n individual_nmi = np.zeros([n_graphs])\n individual_ari = np.zeros([n_graphs])\n individual_mcr = np.zeros([n_graphs])\n for n in range(n_graphs):\n # print(n)\n individual_nmi[n] = nmi(memberships[n],groundTruth[n])\n individual_ari[n] = ari(memberships[n],groundTruth[n])\n individual_mcr[n] = mcr(memberships[n],groundTruth[n])\n\n trueMemberships_stacked = np.reshape(np.hstack(groundTruth),[-1])\n memberships_stacked = np.hstack(memberships)\n overall_nmi = nmi(memberships_stacked,trueMemberships_stacked)\n overall_ari = ari(memberships_stacked,trueMemberships_stacked)\n overall_mcr = mcr(memberships_stacked,trueMemberships_stacked)\n \n return {\"NMI\" : {'nmi' : np.mean(individual_nmi),'overall_nmi' : overall_nmi},\"ARI\" : {'ari' : np.mean(individual_ari),'overall_ari' : overall_ari},\"MCR\" : {'mcr' : np.mean(individual_mcr),'overall_mcr' : overall_mcr}}\n\n"
] | [
[
"numpy.diag",
"numpy.sqrt",
"sklearn.cluster.KMeans",
"numpy.ndarray",
"numpy.argmin",
"numpy.mean",
"sklearn.metrics.cluster.normalized_mutual_info_score",
"numpy.hstack",
"scipy.sparse.issparse",
"numpy.eye",
"numpy.matmul",
"sklearn.metrics.cluster.contingency_matrix",
"numpy.random.multinomial",
"numpy.argmax",
"scipy.sparse.linalg.eigs",
"numpy.zeros",
"numpy.linalg.inv",
"numpy.sum",
"scipy.linalg.eig",
"sklearn.metrics.cluster.adjusted_rand_score"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"0.13",
"0.12",
"0.14",
"0.15"
],
"tensorflow": []
}
] |
DeepPSP/cpsc2021 | [
"165790be750421eb0e0f0fe3129d03dddc250ada"
] | [
"score_2021.py"
] | [
"#!/usr/bin/env python3\n\nimport numpy as np\nimport json\nimport os\nimport sys\n\nimport scipy.io as sio\nimport wfdb\n\n\"\"\"\nWritten by: Xingyao Wang, Chengyu Liu\n School of Instrument Science and Engineering\n Southeast University, China\n [email protected]\n\"\"\"\n\nR = np.array([[1, -1, -0.5], [-2, 1, 0], [-1, 0, 1]])\n\n\nclass RefInfo:\n def __init__(self, sample_path):\n self.sample_path = sample_path\n (\n self.fs,\n self.len_sig,\n self.beat_loc,\n self.af_starts,\n self.af_ends,\n self.class_true,\n ) = self._load_ref()\n self.endpoints_true = np.dstack((self.af_starts, self.af_ends))[0, :, :]\n # self.endpoints_true = np.concatenate((self.af_starts, self.af_ends), axis=-1)\n\n if self.class_true == 1 or self.class_true == 2:\n (\n self.onset_score_range,\n self.offset_score_range,\n ) = self._gen_endpoint_score_range()\n else:\n self.onset_score_range, self.offset_score_range = None, None\n\n def _load_ref(self):\n sig, fields = wfdb.rdsamp(self.sample_path)\n ann_ref = wfdb.rdann(self.sample_path, \"atr\")\n\n fs = fields[\"fs\"]\n length = len(sig)\n sample_descrip = fields[\"comments\"]\n\n beat_loc = np.array(ann_ref.sample) # r-peak locations\n ann_note = np.array(ann_ref.aux_note) # rhythm change flag\n\n af_start_scripts = np.where((ann_note == \"(AFIB\") | (ann_note == \"(AFL\"))[0]\n af_end_scripts = np.where(ann_note == \"(N\")[0]\n\n if \"non atrial fibrillation\" in sample_descrip:\n class_true = 0\n elif \"persistent atrial fibrillation\" in sample_descrip:\n class_true = 1\n elif \"paroxysmal atrial fibrillation\" in sample_descrip:\n class_true = 2\n else:\n print(\"Error: the recording is out of range!\")\n\n return -1\n\n return fs, length, beat_loc, af_start_scripts, af_end_scripts, class_true\n\n def _gen_endpoint_score_range(self):\n \"\"\" \"\"\"\n onset_range = np.zeros((self.len_sig,), dtype=np.float)\n offset_range = np.zeros((self.len_sig,), dtype=np.float)\n for i, af_start in enumerate(self.af_starts):\n if self.class_true == 2:\n if max(af_start - 1, 0) == 0:\n onset_range[: self.beat_loc[af_start + 2]] += 1\n elif max(af_start - 2, 0) == 0:\n onset_range[\n self.beat_loc[af_start - 1] : self.beat_loc[af_start + 2]\n ] += 1\n onset_range[: self.beat_loc[af_start - 1]] += 0.5\n else:\n onset_range[\n self.beat_loc[af_start - 1] : self.beat_loc[af_start + 2]\n ] += 1\n onset_range[\n self.beat_loc[af_start - 2] : self.beat_loc[af_start - 1]\n ] += 0.5\n onset_range[\n self.beat_loc[af_start + 2] : self.beat_loc[af_start + 3]\n ] += 0.5\n elif self.class_true == 1:\n onset_range[: self.beat_loc[af_start + 2]] += 1\n onset_range[\n self.beat_loc[af_start + 2] : self.beat_loc[af_start + 3]\n ] += 0.5\n for i, af_end in enumerate(self.af_ends):\n if self.class_true == 2:\n if min(af_end + 1, len(self.beat_loc) - 1) == len(self.beat_loc) - 1:\n offset_range[self.beat_loc[af_end - 2] :] += 1\n elif min(af_end + 2, len(self.beat_loc) - 1) == len(self.beat_loc) - 1:\n offset_range[\n self.beat_loc[af_end - 2] : self.beat_loc[af_end + 1]\n ] += 1\n offset_range[self.beat_loc[af_end + 1] :] += 0.5\n else:\n offset_range[\n self.beat_loc[af_end - 2] : self.beat_loc[af_end + 1]\n ] += 1\n offset_range[\n self.beat_loc[af_end + 1] : min(\n self.beat_loc[af_end + 2], self.len_sig - 1\n )\n ] += 0.5\n offset_range[\n self.beat_loc[af_end - 3] : self.beat_loc[af_end - 2]\n ] += 0.5\n elif self.class_true == 1:\n offset_range[self.beat_loc[af_end - 2] :] += 1\n offset_range[\n self.beat_loc[af_end - 3] : self.beat_loc[af_end - 2]\n ] += 0.5\n\n return onset_range, offset_range\n\n\ndef load_ans(ans_file):\n endpoints_pred = []\n if ans_file.endswith(\".json\"):\n json_file = open(ans_file, \"r\")\n ans_dic = json.load(json_file)\n endpoints_pred = np.array(ans_dic[\"predict_endpoints\"])\n\n elif ans_file.endswith(\".mat\"):\n ans_struct = sio.loadmat(ans_file)\n endpoints_pred = ans_struct[\"predict_endpoints\"] - 1\n\n return endpoints_pred\n\n\ndef ue_calculate(endpoints_pred, endpoints_true, onset_score_range, offset_score_range):\n score = 0\n ma = len(endpoints_true)\n mr = len(endpoints_pred)\n\n if mr == 0:\n score = 0\n\n else:\n for [start, end] in endpoints_pred:\n score += onset_score_range[int(start)]\n score += offset_score_range[int(end)]\n\n score *= ma / max(ma, mr)\n\n return score\n\n\ndef ur_calculate(class_true, class_pred):\n score = R[int(class_true), int(class_pred)]\n\n return score\n\n\ndef score(data_path, ans_path):\n # AF burden estimation\n SCORE = []\n\n def is_mat_or_json(file):\n return (file.endswith(\".json\")) + (file.endswith(\".mat\"))\n\n ans_set = filter(is_mat_or_json, os.listdir(ans_path))\n # test_set = open(os.path.join(data_path, 'RECORDS'), 'r').read().splitlines()\n for i, ans_sample in enumerate(ans_set):\n sample_nam = ans_sample.split(\".\")[0]\n sample_path = os.path.join(data_path, sample_nam)\n\n endpoints_pred = load_ans(os.path.join(ans_path, ans_sample))\n TrueRef = RefInfo(sample_path)\n\n if len(endpoints_pred) == 0:\n class_pred = 0\n elif (\n len(endpoints_pred) == 1\n and np.diff(endpoints_pred)[-1] == TrueRef.len_sig - 1\n ):\n class_pred = 1\n else:\n class_pred = 2\n\n ur_score = ur_calculate(TrueRef.class_true, class_pred)\n\n if TrueRef.class_true == 1 or TrueRef.class_true == 2:\n ue_score = ue_calculate(\n endpoints_pred,\n TrueRef.endpoints_true,\n TrueRef.onset_score_range,\n TrueRef.offset_score_range,\n )\n else:\n ue_score = 0\n\n u = ur_score + ue_score\n SCORE.append(u)\n\n score_avg = np.mean(SCORE)\n\n return score_avg\n\n\nif __name__ == \"__main__\":\n TESTSET_PATH = sys.argv[1]\n RESULT_PATH = sys.argv[2]\n score_avg = score(TESTSET_PATH, RESULT_PATH)\n print(\"AF Endpoints Detection Performance: %0.4f\" % score_avg)\n\n with open(os.path.join(RESULT_PATH, \"score.txt\"), \"w\") as score_file:\n print(\"AF Endpoints Detection Performance: %0.4f\" % score_avg, file=score_file)\n\n score_file.close()\n"
] | [
[
"scipy.io.loadmat",
"numpy.dstack",
"numpy.mean",
"numpy.diff",
"numpy.array",
"numpy.where",
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"1.7",
"1.0",
"0.10",
"1.2",
"0.14",
"0.19",
"1.5",
"0.12",
"0.17",
"0.13",
"1.6",
"1.4",
"1.9",
"1.3",
"1.10",
"0.15",
"0.18",
"0.16",
"1.8"
],
"tensorflow": []
}
] |
kamal-rahimi/SentenceCorrection | [
"19138ebbdf1073f070a1982d3991de063c0d27d7"
] | [
"process_sentence.py"
] | [
"\"\"\"\nEstimates the likihood of an input senetnce and finds an order of words\nthat is most likely in the longuage model\n\"\"\"\n\nimport os\nimport argparse\nimport pickle\n\nfrom keras.models import load_model\nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras import backend as k\n\nimport numpy as np\n\nfrom itertools import permutations\n\nfrom nlp_tools import strip_punctuations\n\ndef analyze_sequence(model, words_id_order, max_sentence_words):\n \"\"\" Computes the liklihood of the input sequnce of words using the longuage model\n Args:\n model: trained longuage model object\n words_ids: inout sequnce of word ids\n max_sentence_words: maximum number of words in a senetnce\n Returns:\n p_sentence: the liklihood of inout sequnce in the longuage model\n p_words: a python array of the liklihood of each word given its predecessor words\n \"\"\"\n p_words = [1]\n p_sentence = 1\n for word_index in range(1, len(words_id_order)-1):\n seq = words_id_order[:word_index]\n x = pad_sequences([seq], maxlen=max_sentence_words-1, truncating='pre')\n y = words_id_order[word_index]\n predict_prob = model.predict(x, verbose=0)\n\n predict_prob = np.array(predict_prob).reshape(-1,)\n prob = predict_prob[y]\n p_words.append(prob)\n p_sentence = p_sentence*prob\n\n return p_sentence, p_words\n\ndef process_sentence(model_name, input_sentence, window_size, max_sentence_words = 12):\n \"\"\" analyzes the inout sentnces and reorders the word to form a senetnces which\n has the highest liklihood in the longuage model.\n\n Args:\n model: trained longuage model object\n word2id: dictionary to convert from word to id\n id2word: dictionary to convert from id to word\n window_size: word reordering search window size\n input_sentnce (text): input sentnce\n max_sentence_words: maximum number of words in a senetnce\n Returns:\n most_likely_sentence: the word reordred senetnce that has highes liklihood in the longuage model\n most_likely_word_order_prob: liklihood of the reordred sentence\n \"\"\"\n model_path = './models/' + model_name + '_model.h5'\n meta_data_path = './models/' + model_name + '_metadata.pickle'\n if (os.path.isfile(model_path) == True) and (os.path.isfile(model_path) == True):\n model = load_model(model_path)\n with open(meta_data_path,'rb') as f:\n word2id, id2word = pickle.load(f)\n else:\n print('No model with name \\\"%s\\\" is trained yet' % model_name)\n return\n\n\n input_sentence = strip_punctuations(input_sentence)\n input_sentence = input_sentence.lower()\n sentence_words = input_sentence.split()\n sentence_words_id = [word2id[word] if word in word2id else word2id['<UNK>'] for word in sentence_words]\n\n full_sentence_words_id = [word2id['<BGN>']] + sentence_words_id + [word2id['<EOS>']]\n inout_word_order_prob, _ = analyze_sequence(model, full_sentence_words_id, max_sentence_words)\n\n sentence_words_id_permutations = []\n num_iterations = max(1, len(sentence_words_id) - window_size + 1)\n for i in range(0, num_iterations):\n words_id_permutations = [ sentence_words_id[0 : i] + list(l) for l in permutations(sentence_words_id[i : window_size + i]) ]\n num_permutations = len(words_id_permutations)\n sentence_size = len(words_id_permutations[0])\n\n words_id_permutations_prob = []\n for words_id_order_index in range(0, num_permutations):\n words_id_order = list(words_id_permutations[words_id_order_index])\n words_id_order = [word2id['<BGN>']] + words_id_order\n if i == num_iterations-1:\n words_id_order = words_id_order + [word2id['<EOS>']]\n\n p_sentence, p_words = analyze_sequence(model, words_id_order, max_sentence_words)\n\n words_id_permutations_prob.append(p_sentence)\n\n most_likely_word_order_index = np.argmax(words_id_permutations_prob)\n most_likely_word_order_prob = words_id_permutations_prob[most_likely_word_order_index]\n most_likely_words_id_order = words_id_permutations[most_likely_word_order_index]\n\n sentence_words_id = most_likely_words_id_order + sentence_words_id[window_size + i : ]\n\n k.clear_session()\n\n most_likely_words_order = [id2word[id] for id in sentence_words_id]\n most_likely_sentence = ' '.join(most_likely_words_order)\n return inout_word_order_prob, most_likely_sentence, most_likely_word_order_prob\n\n\ndef main():\n\n # construct the argument parser and parse the arguments\n ap = argparse.ArgumentParser()\n ap.add_argument(\"-n\", \"--name\", type=str, default=\"English\", help=\"specify the longuage model name\")\n ap.add_argument(\"-s\", \"--sentence\", type=str, default=\"This is\", help=\"specify the longuage model name\")\n ap.add_argument(\"-w\", \"--window\", type=int, default=5, help=\"specify the window size to reorder words\")\n ap.add_argument(\"-g\", \"--gpu\", help=\"Specify to use GPU for training the model\", action='store_true')\n\n args = vars(ap.parse_args())\n model_name = args[\"name\"]\n input_sentence = args['sentence']\n window_size = args['window']\n use_gpu = args[\"gpu\"]\n\n if use_gpu:\n config_gpu()\n\n input_sentences_liklihood, corrected_sentence, corrected_sentence_liklihood = process_sentence(model_name, input_sentence, window_size)\n print('\\nInput: ')\n print(input_sentence)\n print('Liklihood:')\n print(input_sentences_liklihood)\n print('\\nCorrected: ')\n print(corrected_sentence)\n print('Liklihood:')\n print(corrected_sentence_liklihood)\n print('\\n')\n\n\nif __name__ == '__main__':\n main()\n"
] | [
[
"numpy.array",
"numpy.argmax"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
wjwyyjr/Gem5_task_graph | [
"0e233b5053d6dcd518a2ad6fddd23eaeb9c3a8ee",
"0e233b5053d6dcd518a2ad6fddd23eaeb9c3a8ee"
] | [
"my_scripts/10_03/different_memory_access/plot.py",
"my_scripts/test_0616/plot_data_iters.py"
] | [
"from io import SEEK_CUR\nfrom os import name\nfrom types import FunctionType\nimport matplotlib.pyplot as plt\nfrom matplotlib.pyplot import legend, plot, xticks\n\n## class for plot function\nclass PlotFunction():\n \"\"\"Make Data visualization Easier !\"\"\"\n def __init__(self, y_data, x_label, y_label, x_ticklabels=[], x_ticks=[], title=''):\n self.y_data=y_data\n self.x_label=x_label\n self.y_label=y_label\n self.x_ticklabels=x_ticklabels\n self.x_ticks=x_ticks\n if title == '':\n self.title=self.y_label+\" vs. \"+self.x_label\n else:\n self.title=self.y_label+\" vs. \"+self.x_label+title\n\n def plot_figs(self):\n plt.clf()\n legend_list = []\n line_type=['-x', '-*', '-^', '-o', '-s', '-<', '-v', '-D']\n plt_ptrs = []\n i = 0\n default_xticks_len = 0\n for key, value in self.y_data.items():\n legend_list.append(key)\n assert(i < len(line_type)) # aviod over the range of line_type\n plt_ptr, = plt.plot([int(x) for x in value], line_type[i])\n plt_ptrs.append(plt_ptr)\n i += 1\n\n if default_xticks_len == 0:\n default_xticks_len = len(value)\n\n plt.title(self.title)\n plt.xlabel(self.x_label)\n plt.ylabel(self.y_label)\n plt.legend(plt_ptrs, legend_list)\n ax = plt.gca()\n\n if self.x_ticklabels != []:\n ax.set_xticklabels(self.x_ticklabels)\n else:\n ax.set_xticklabels([str(x) for x in range(default_xticks_len)])\n\n if self.x_ticks != []:\n ax.set_xticks(self.x_ticks)\n else:\n ax.set_xticks([x for x in range(default_xticks_len)])\n\n plt.tight_layout()\n\n def save_figs(self, dir, filename=''):\n self.plot_figs()\n name=''\n if filename != '':\n name = filename + '.jpg'\n else:\n name = self.title + '.jpg'\n\n plt.savefig(dir + name)\n\n def plot_pie(self, dir='./', title='', legend_list=[], if_save=True):\n plt.clf()\n\n if legend_list == []:\n legend_list = ['HQM', 'Core-0', 'PE-1 PE-2', 'DDR-0', 'PE-3 PE-4 PE-5', 'PE-13', 'Core-1', \\\n 'Core-2', 'PE-6 PE-7 PE-8', 'DDR-1', 'PE-9 PE-10 PE-11 PE-12', 'Core-3']\n\n explode = [0.01] * len(self.y_data)\n plt.pie(self.y_data, explode=explode, labels=legend_list)\n plt.title(title)\n plt.tight_layout()\n if if_save:\n plt.savefig(dir+title+'.jpg')\n\n\n## System Path\ndir_path = \"/home/wj/test/Gem5_task_graph/my_STATS/10_03/different_memory_access/\"\nresult_path = dir_path+\"results.txt\"\nfig_path = dir_path+\"FIGS/\"\nlink_result_path = dir_path+\"LINK_RESULT/\"\nlog_path = dir_path + \"log\"\n\n## Parameter Setting\napp=[1, 2, 3, 4, 5]\niters=[100]\nmem_access=['10', '20', '30', '40', '50']\nmem_type = ['DDR3']\n\n## Read File -> result.txt\nwith open(result_path) as input_file:\n input_data = input_file.readlines()\n\n# use dict to store info {name: [...]}\ninput_data_dict = {}\n\nfor i in range(1, len(input_data)):\n input_data_dict[input_data[i].split()[0]] = input_data[i].strip().split()[1:]\n\nete_delay = {}\nflits = {}\nhops = {}\nlatency = {}\nnetwork_latency = {}\nqueueing_latency = {}\nfor app_num in range(1,6):\n app_name = \"App_0\" + str(app_num)\n ete_delay[app_name] = []\n flits[app_name] = []\n hops[app_name] = []\n latency[app_name] = []\n network_latency[app_name] = []\n queueing_latency[app_name] = []\n for iter in iters:\n for mc in mem_access:\n for mt in mem_type:\n filename = \"Application_0\" + str(app_num) + '_Iters_' + str(iter) + '_Memory_Access_' +\\\n str(mc) + '_Memory_Type_' + str(mt)\n ete_delay[app_name].append(input_data_dict[filename][5])\n flits[app_name].append(input_data_dict[filename][0])\n hops[app_name].append(input_data_dict[filename][1])\n latency[app_name].append(input_data_dict[filename][2])\n network_latency[app_name].append(input_data_dict[filename][3])\n queueing_latency[app_name].append(input_data_dict[filename][4])\n\np = PlotFunction(ete_delay, 'Memory Access', 'Average ETE Delay', mem_access)\np.save_figs(fig_path)\n\n\n## Read File -> log\nif 0:\n with open(log_path) as log_file:\n log_data = log_file.readlines()\n\n for app in app:\n\n ete_delay = {}\n average_ete_delay = {}\n\n for iter in iters:\n for mc in mem_access:\n for mt in mem_type:\n key_word = 'Application_0' + str(app) + '_Iters_' + str(iter) + '_Memory_Access_' +\\\n str(mc) + '_Memory_Type_' + str(mt)\n start_idx = -1\n for i in range(len(log_data)):\n if key_word in log_data[i]:\n start_idx = i + 3\n break\n assert(start_idx != -1)\n\n each_iter_data = []\n aver_data = []\n total_delay = 0\n assert(log_data[start_idx+iter-1].strip().split()[1] == str(iter-1))\n for i in range(start_idx, start_idx+iter):\n delay = log_data[i].strip().split()[-1]\n total_delay += int(delay)\n each_iter_data.append(delay)\n aver_data.append(total_delay/(i-start_idx+1))\n\n x_index = 'Memory_Access_' + mc # for legend\n ete_delay[x_index] = each_iter_data\n average_ete_delay[x_index] = aver_data\n\n x_ticklabels=['10', '20', '30', '40', '50', '60', '70', '80', '90', '100']\n x_ticks=[i*10 for i in range(1,11)]\n p = PlotFunction(ete_delay, \"Execution Iterations\", \"ETE Delay\", x_ticklabels, x_ticks, ' for_App_0'+str(app))\n p.save_figs(fig_path)\n\n p1 = PlotFunction(average_ete_delay, \"Execution Iterations\", \"Average ETE Delay\", x_ticklabels, x_ticks, ' for_App_0'+str(app))\n p1.save_figs(fig_path)\n",
"import matplotlib.pyplot as plt\n\n# read two result.txt\ndir_path = \"/home/wj/Study/gem5/my_STATS/test_20200616/\"\ntest_iters_path = dir_path+\"test_iters_512_12288_512/results.txt\"\n\nwith open(test_iters_path) as iters_file:\n iters_data = iters_file.readlines()\n\n# use dict to store info {name: [...]}\niters_data_dict = {}\nfor i in range(1, len(iters_data)):\n iters_data_dict[iters_data[i].split()[0]] = iters_data[i].strip().split()[1:]\n# print(iters_data_dict)\n\n########### Latency_vs_Iters ##########\n# five apps with different iterations\niters = ['1', '10', '20', '30', '40', '50']\niters_delay = {}\nfor app_num in range(1,6):\n app_name = \"Application_0\" + str(app_num)\n iters_delay[app_name] = []\n for iter in iters:\n filename = \"Application_0\" + str(app_num) + \"_iters\" + iter\n iters_delay[app_name].append(iters_data_dict[filename][2])\n# print(iters_delay)\n\n# plot\nline_type = ['-x', '-*', '-^', '-o', '-s']\nlegend_list = []\nplt_ptrs = []\ni = 0\nfor app_num in range(1,6):\n app_name = \"Application_0\" + str(app_num)\n legend_list.append(app_name)\n # Note ! add comma! if not, return a list with one object, else return the required object.\n plt_ptr, = plt.plot([float(x) for x in iters_delay[app_name]], line_type[i])\n plt_ptrs.append(plt_ptr)\n i += 1\n\nplt.title(\"Average Flit Latency vs. Execution Iterations (Msg Size 512_12288_512)\")\nplt.xlabel(\"Execution Iterations\", fontsize=12)\nplt.ylabel(\"Average Flit Latency (Cycle)\", fontsize=12)\nplt.legend(plt_ptrs, legend_list)\nax = plt.gca()\nax.set_xticks([0,1,2,3,4,5])\nax.set_xticklabels(iters)\nplt.savefig('Latency_vs_Iters_512_12288_512.jpg')\nplt.show()\n"
] | [
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.gca",
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.title",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.clf",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.pie",
"matplotlib.pyplot.ylabel"
],
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.gca",
"matplotlib.pyplot.title",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ruihan0495/EfficientDet | [
"f61b77343a9782d85747ced6704c35a49528934a",
"f61b77343a9782d85747ced6704c35a49528934a"
] | [
"utils/graph_funcs.py",
"eval/common.py"
] | [
"import tensorflow as tf\n############################################################\n# Miscellenous Graph Functions\n############################################################\n\ndef trim_zeros_graph(boxes, name='trim_zeros'):\n \"\"\"Often boxes are represented with matrices of shape [N, 4] and\n are padded with zeros. This removes zero boxes.\n boxes: [N, 4] matrix of boxes.\n non_zeros: [N] a 1D boolean mask identifying the rows to keep\n \"\"\"\n non_zeros = tf.cast(tf.reduce_sum(tf.abs(boxes), axis=1), tf.bool)\n boxes = tf.boolean_mask(boxes, non_zeros, name=name)\n return boxes, non_zeros\n\n\ndef batch_pack_graph(x, counts, num_rows):\n \"\"\"Picks different number of values from each row\n in x depending on the values in counts.\n \"\"\"\n outputs = []\n for i in range(num_rows):\n outputs.append(x[i, :counts[i]])\n return tf.concat(outputs, axis=0)\n\n\ndef norm_boxes_graph(boxes, shape):\n \"\"\"Converts boxes from pixel coordinates to normalized coordinates.\n boxes: [..., (y1, x1, y2, x2)] in pixel coordinates\n shape: [..., (height, width)] in pixels\n Note: In pixel coordinates (y2, x2) is outside the box. But in normalized\n coordinates it's inside the box.\n Returns:\n [..., (y1, x1, y2, x2)] in normalized coordinates\n \"\"\"\n h, w = tf.split(tf.cast(shape, tf.float32), 2)\n scale = tf.concat([h, w, h, w], axis=-1) - tf.constant(1.0)\n shift = tf.constant([0., 0., 1., 1.])\n return tf.divide(boxes - shift, scale)\n\n\ndef denorm_boxes_graph(boxes, shape):\n \"\"\"Converts boxes from normalized coordinates to pixel coordinates.\n boxes: [..., (y1, x1, y2, x2)] in normalized coordinates\n shape: [..., (height, width)] in pixels\n Note: In pixel coordinates (y2, x2) is outside the box. But in normalized\n coordinates it's inside the box.\n Returns:\n [..., (y1, x1, y2, x2)] in pixel coordinates\n \"\"\"\n h, w = tf.split(tf.cast(shape, tf.float32), 2)\n scale = tf.concat([h, w, h, w], axis=-1) - tf.constant(1.0)\n shift = tf.constant([0., 0., 1., 1.])\n return tf.cast(tf.round(tf.multiply(boxes, scale) + shift), tf.int32)\n\ndef overlaps_graph(boxes1, boxes2):\n \"\"\"Computes IoU overlaps between two sets of boxes.\n boxes1, boxes2: [N, (y1, x1, y2, x2)].\n \"\"\"\n # 1. Tile boxes2 and repeat boxes1. This allows us to compare\n # every boxes1 against every boxes2 without loops.\n # TF doesn't have an equivalent to np.repeat() so simulate it\n # using tf.tile() and tf.reshape.\n b1 = tf.reshape(tf.tile(tf.expand_dims(boxes1, 1),\n [1, 1, tf.shape(boxes2)[0]]), [-1, 4])\n b2 = tf.tile(boxes2, [tf.shape(boxes1)[0], 1])\n # 2. Compute intersections\n b1_y1, b1_x1, b1_y2, b1_x2 = tf.split(b1, 4, axis=1)\n b2_y1, b2_x1, b2_y2, b2_x2 = tf.split(b2, 4, axis=1)\n y1 = tf.maximum(b1_y1, b2_y1)\n x1 = tf.maximum(b1_x1, b2_x1)\n y2 = tf.minimum(b1_y2, b2_y2)\n x2 = tf.minimum(b1_x2, b2_x2)\n intersection = tf.maximum(x2 - x1, 0) * tf.maximum(y2 - y1, 0)\n # 3. Compute unions\n b1_area = (b1_y2 - b1_y1) * (b1_x2 - b1_x1)\n b2_area = (b2_y2 - b2_y1) * (b2_x2 - b2_x1)\n union = b1_area + b2_area - intersection\n # 4. Compute IoU and reshape to [boxes1, boxes2]\n iou = intersection / union\n overlaps = tf.reshape(iou, [tf.shape(boxes1)[0], tf.shape(boxes2)[0]])\n return overlaps\n\ndef batch_slice(inputs, graph_fn, batch_size, names=None):\n \"\"\"Splits inputs into slices and feeds each slice to a copy of the given\n computation graph and then combines the results. It allows you to run a\n graph on a batch of inputs even if the graph is written to support one\n instance only.\n inputs: list of tensors. All must have the same first dimension length\n graph_fn: A function that returns a TF tensor that's part of a graph.\n batch_size: number of slices to divide the data into.\n names: If provided, assigns names to the resulting tensors.\n \"\"\"\n if not isinstance(inputs, list):\n inputs = [inputs]\n\n outputs = []\n for i in range(batch_size):\n inputs_slice = [x[i] for x in inputs]\n output_slice = graph_fn(*inputs_slice)\n if not isinstance(output_slice, (tuple, list)):\n output_slice = [output_slice]\n outputs.append(output_slice)\n # Change outputs from a list of slices where each is\n # a list of outputs to a list of outputs and each has\n # a list of slices\n outputs = list(zip(*outputs))\n\n if names is None:\n names = [None] * len(outputs)\n\n result = [tf.stack(o, axis=0, name=n)\n for o, n in zip(outputs, names)]\n if len(result) == 1:\n result = result[0]\n\n return result\n\ndef norm_boxes_graph(boxes, shape):\n \"\"\"Converts boxes from pixel coordinates to normalized coordinates.\n boxes: [..., (y1, x1, y2, x2)] in pixel coordinates\n shape: [..., (height, width)] in pixels\n Note: In pixel coordinates (y2, x2) is outside the box. But in normalized\n coordinates it's inside the box.\n Returns:\n [..., (y1, x1, y2, x2)] in normalized coordinates\n \"\"\"\n h, w = tf.split(tf.cast(shape, tf.float32), 2)\n scale = tf.concat([h, w, h, w], axis=-1) - tf.constant(1.0)\n shift = tf.constant([0., 0., 1., 1.])\n return tf.divide(boxes - shift, scale)\n\n\ndef denorm_boxes_graph(boxes, shape):\n \"\"\"Converts boxes from normalized coordinates to pixel coordinates.\n boxes: [..., (y1, x1, y2, x2)] in normalized coordinates\n shape: [..., (height, width)] in pixels\n Note: In pixel coordinates (y2, x2) is outside the box. But in normalized\n coordinates it's inside the box.\n Returns:\n [..., (y1, x1, y2, x2)] in pixel coordinates\n \"\"\"\n h, w = tf.split(tf.cast(shape, tf.float32), 2)\n scale = tf.concat([h, w, h, w], axis=-1) - tf.constant(1.0)\n shift = tf.constant([0., 0., 1., 1.])\n return tf.cast(tf.round(tf.multiply(boxes, scale) + shift), tf.int32)",
"\"\"\"\nCopyright 2017-2018 Fizyr (https://fizyr.com)\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\n http://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\nfrom utils.compute_overlap import compute_overlap\nfrom utils.visualization import draw_detections, draw_annotations\n\nimport numpy as np\nimport cv2\nimport progressbar\n\nassert (callable(progressbar.progressbar)), \"Using wrong progressbar module, install 'progressbar2' instead.\"\n\n\ndef _compute_ap(recall, precision):\n \"\"\"\n Compute the average precision, given the recall and precision curves.\n\n Code originally from https://github.com/rbgirshick/py-faster-rcnn.\n\n Args:\n recall: The recall curve (list).\n precision: The precision curve (list).\n\n Returns:\n The average precision as computed in py-faster-rcnn.\n\n \"\"\"\n # correct AP calculation\n # first append sentinel values at the end\n mrec = np.concatenate(([0.], recall, [1.]))\n mpre = np.concatenate(([0.], precision, [0.]))\n\n # compute the precision envelope\n for i in range(mpre.size - 1, 0, -1):\n mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])\n\n # to calculate area under PR curve, look for points\n # where X axis (recall) changes value\n i = np.where(mrec[1:] != mrec[:-1])[0]\n\n # and sum (delta recall) * prec\n ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])\n return ap\n\n\ndef _get_detections(generator, model, score_threshold=0.05, max_detections=100, visualize=False):\n \"\"\"\n Get the detections from the model using the generator.\n\n The result is a list of lists such that the size is:\n all_detections[num_images][num_classes] = detections[num_class_detections, 5]\n\n Args:\n generator: The generator used to run images through the model.\n model: The model to run on the images.\n score_threshold: The score confidence threshold to use.\n max_detections: The maximum number of detections to use per image.\n save_path: The path to save the images with visualized detections to.\n\n Returns:\n A list of lists containing the detections for each image in the generator.\n\n \"\"\"\n all_detections = [[None for i in range(generator.num_classes()) if generator.has_label(i)] for j in\n range(generator.size())]\n\n for i in progressbar.progressbar(range(generator.size()), prefix='Running network: '):\n image = generator.load_image(i)\n src_image = image.copy()\n h, w = image.shape[:2]\n\n anchors = generator.anchors\n image, scale = generator.preprocess_image(image)\n\n # run network\n boxes, scores, *_, labels = model.predict_on_batch([np.expand_dims(image, axis=0)])\n boxes /= scale\n boxes[:, :, 0] = np.clip(boxes[:, :, 0], 0, w - 1)\n boxes[:, :, 1] = np.clip(boxes[:, :, 1], 0, h - 1)\n boxes[:, :, 2] = np.clip(boxes[:, :, 2], 0, w - 1)\n boxes[:, :, 3] = np.clip(boxes[:, :, 3], 0, h - 1)\n\n # select indices which have a score above the threshold\n indices = np.where(scores[0, :] > score_threshold)[0]\n\n # select those scores\n scores = scores[0][indices]\n\n # find the order with which to sort the scores\n scores_sort = np.argsort(-scores)[:max_detections]\n\n # select detections\n # (n, 4)\n image_boxes = boxes[0, indices[scores_sort], :]\n # (n, )\n image_scores = scores[scores_sort]\n # (n, )\n image_labels = labels[0, indices[scores_sort]]\n # (n, 6)\n detections = np.concatenate(\n [image_boxes, np.expand_dims(image_scores, axis=1), np.expand_dims(image_labels, axis=1)], axis=1)\n\n if visualize:\n draw_annotations(src_image, generator.load_annotations(i), label_to_name=generator.label_to_name)\n draw_detections(src_image, detections[:5, :4], detections[:5, 4], detections[:5, 5].astype(np.int32),\n label_to_name=generator.label_to_name,\n score_threshold=score_threshold)\n\n # cv2.imwrite(os.path.join(save_path, '{}.png'.format(i)), raw_image)\n cv2.namedWindow('{}'.format(i), cv2.WINDOW_NORMAL)\n cv2.imshow('{}'.format(i), src_image)\n cv2.waitKey(0)\n\n # copy detections to all_detections\n for class_id in range(generator.num_classes()):\n all_detections[i][class_id] = detections[detections[:, -1] == class_id, :-1]\n\n return all_detections\n\n\ndef _get_annotations(generator):\n \"\"\"\n Get the ground truth annotations from the generator.\n\n The result is a list of lists such that the size is:\n all_annotations[num_images][num_classes] = annotations[num_class_annotations, 5]\n\n Args:\n generator: The generator used to retrieve ground truth annotations.\n\n Returns:\n A list of lists containing the annotations for each image in the generator.\n\n \"\"\"\n all_annotations = [[None for i in range(generator.num_classes())] for j in range(generator.size())]\n\n for i in progressbar.progressbar(range(generator.size()), prefix='Parsing annotations: '):\n # load the annotations\n annotations = generator.load_annotations(i)\n\n # copy detections to all_annotations\n for label in range(generator.num_classes()):\n if not generator.has_label(label):\n continue\n\n all_annotations[i][label] = annotations['bboxes'][annotations['labels'] == label, :].copy()\n\n return all_annotations\n\n\ndef evaluate(\n generator,\n model,\n iou_threshold=0.5,\n score_threshold=0.01,\n max_detections=100,\n visualize=False,\n epoch=0\n):\n \"\"\"\n Evaluate a given dataset using a given model.\n\n Args:\n generator: The generator that represents the dataset to evaluate.\n model: The model to evaluate.\n iou_threshold: The threshold used to consider when a detection is positive or negative.\n score_threshold: The score confidence threshold to use for detections.\n max_detections: The maximum number of detections to use per image.\n visualize: Show the visualized detections or not.\n\n Returns:\n A dict mapping class names to mAP scores.\n\n \"\"\"\n # gather all detections and annotations\n all_detections = _get_detections(generator, model, score_threshold=score_threshold, max_detections=max_detections,\n visualize=visualize)\n all_annotations = _get_annotations(generator)\n average_precisions = {}\n num_tp = 0\n num_fp = 0\n\n # process detections and annotations\n for label in range(generator.num_classes()):\n if not generator.has_label(label):\n continue\n\n false_positives = np.zeros((0,))\n true_positives = np.zeros((0,))\n scores = np.zeros((0,))\n num_annotations = 0.0\n\n for i in range(generator.size()):\n detections = all_detections[i][label]\n annotations = all_annotations[i][label]\n num_annotations += annotations.shape[0]\n detected_annotations = []\n\n for d in detections:\n scores = np.append(scores, d[4])\n\n if annotations.shape[0] == 0:\n false_positives = np.append(false_positives, 1)\n true_positives = np.append(true_positives, 0)\n continue\n overlaps = compute_overlap(np.expand_dims(d, axis=0), annotations)\n assigned_annotation = np.argmax(overlaps, axis=1)\n max_overlap = overlaps[0, assigned_annotation]\n\n if max_overlap >= iou_threshold and assigned_annotation not in detected_annotations:\n false_positives = np.append(false_positives, 0)\n true_positives = np.append(true_positives, 1)\n detected_annotations.append(assigned_annotation)\n else:\n false_positives = np.append(false_positives, 1)\n true_positives = np.append(true_positives, 0)\n\n # no annotations -> AP for this class is 0 (is this correct?)\n if num_annotations == 0:\n average_precisions[label] = 0, 0\n continue\n\n # sort by score\n indices = np.argsort(-scores)\n false_positives = false_positives[indices]\n true_positives = true_positives[indices]\n\n # compute false positives and true positives\n false_positives = np.cumsum(false_positives)\n true_positives = np.cumsum(true_positives)\n\n if false_positives.shape[0] == 0:\n num_fp += 0\n else:\n num_fp += false_positives[-1]\n if true_positives.shape[0] == 0:\n num_tp += 0\n else:\n num_tp += true_positives[-1]\n\n # compute recall and precision\n recall = true_positives / num_annotations\n precision = true_positives / np.maximum(true_positives + false_positives, np.finfo(np.float64).eps)\n\n # compute average precision\n average_precision = _compute_ap(recall, precision)\n average_precisions[label] = average_precision, num_annotations\n print('num_fp={}, num_tp={}'.format(num_fp, num_tp))\n\n return average_precisions\n\n\nif __name__ == '__main__':\n from generators.pascal import PascalVocGenerator\n from model import efficientdet\n import os\n\n os.environ['CUDA_VISIBLE_DEVICES'] = '0'\n\n phi = 1\n weighted_bifpn = False\n common_args = {\n 'batch_size': 1,\n 'phi': phi,\n }\n test_generator = PascalVocGenerator(\n 'datasets/VOC2007',\n 'test',\n shuffle_groups=False,\n skip_truncated=False,\n skip_difficult=True,\n **common_args\n )\n model_path = 'checkpoints/2019-12-03/pascal_05_0.6283_1.1975_0.8029.h5'\n input_shape = (test_generator.image_size, test_generator.image_size)\n anchors = test_generator.anchors\n num_classes = test_generator.num_classes()\n model, prediction_model = efficientdet(phi=phi, num_classes=num_classes, weighted_bifpn=weighted_bifpn)\n prediction_model.load_weights(model_path, by_name=True)\n average_precisions = evaluate(test_generator, prediction_model, visualize=False)\n # compute per class average precision\n total_instances = []\n precisions = []\n for label, (average_precision, num_annotations) in average_precisions.items():\n print('{:.0f} instances of class'.format(num_annotations), test_generator.label_to_name(label),\n 'with average precision: {:.4f}'.format(average_precision))\n total_instances.append(num_annotations)\n precisions.append(average_precision)\n mean_ap = sum(precisions) / sum(x > 0 for x in total_instances)\n print('mAP: {:.4f}'.format(mean_ap))\n"
] | [
[
"tensorflow.boolean_mask",
"tensorflow.multiply",
"tensorflow.concat",
"tensorflow.constant",
"tensorflow.shape",
"tensorflow.maximum",
"tensorflow.stack",
"tensorflow.minimum",
"tensorflow.cast",
"tensorflow.expand_dims",
"tensorflow.divide",
"tensorflow.split",
"tensorflow.abs"
],
[
"numpy.expand_dims",
"numpy.maximum",
"numpy.clip",
"numpy.cumsum",
"numpy.finfo",
"numpy.concatenate",
"numpy.append",
"numpy.argmax",
"numpy.argsort",
"numpy.where",
"numpy.sum",
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"1.12",
"1.4",
"1.5",
"1.7",
"1.0",
"1.2"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
lp2333/PARL | [
"f508bc6085420431b504441c7ff129e64826603e",
"f508bc6085420431b504441c7ff129e64826603e",
"f508bc6085420431b504441c7ff129e64826603e",
"f508bc6085420431b504441c7ff129e64826603e",
"f508bc6085420431b504441c7ff129e64826603e"
] | [
"parl/env/tests/continuous_wrappers_test.py",
"examples/SAC/mujoco_agent.py",
"benchmark/torch/maml++/maml_model.py",
"examples/Baselines/Halite_competition/torch/train.py",
"benchmark/fluid/MADDPG/train.py"
] | [
"# Copyright (c) 2018 PaddlePaddle 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\nimport gym\nimport numpy as np\nimport unittest\nfrom parl.env.continuous_wrappers import ActionMappingWrapper\n\n\nclass MockEnv(gym.Env):\n def __init__(self, low, high):\n self.action_space = gym.spaces.Box(low=low, high=high, shape=(3, ))\n self._max_episode_steps = 1000\n\n def step(self, action):\n self.action = action\n\n def reset(self):\n return None\n\n\nclass TestActionMappingWrapper(unittest.TestCase):\n def test_action_mapping(self):\n origin_act = np.array([-1.0, 0.0, 1.0])\n\n env = MockEnv(0.0, 1.0)\n wrapper_env = ActionMappingWrapper(env)\n wrapper_env.step(origin_act)\n self.assertListEqual(list(env.action), [0.0, 0.5, 1.0])\n\n env = MockEnv(-2.0, 2.0)\n wrapper_env = ActionMappingWrapper(env)\n wrapper_env.step(origin_act)\n self.assertListEqual(list(env.action), [-2.0, 0.0, 2.0])\n\n env = MockEnv(-5.0, 10.0)\n wrapper_env = ActionMappingWrapper(env)\n wrapper_env.step(origin_act)\n self.assertListEqual(list(env.action), [-5.0, 2.5, 10.0])\n\n\nif __name__ == '__main__':\n unittest.main()\n",
"# Copyright (c) 2021 PaddlePaddle 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\nimport parl\nimport paddle\nimport numpy as np\n\n\nclass MujocoAgent(parl.Agent):\n def __init__(self, algorithm):\n super(MujocoAgent, self).__init__(algorithm)\n\n self.alg.sync_target(decay=0)\n\n def predict(self, obs):\n obs = paddle.to_tensor(obs.reshape(1, -1), dtype='float32')\n action = self.alg.predict(obs)\n action_numpy = action.cpu().numpy()[0]\n return action_numpy\n\n def sample(self, obs):\n obs = paddle.to_tensor(obs.reshape(1, -1), dtype='float32')\n action, _ = self.alg.sample(obs)\n action_numpy = action.cpu().numpy()[0]\n return action_numpy\n\n def learn(self, obs, action, reward, next_obs, terminal):\n terminal = np.expand_dims(terminal, -1)\n reward = np.expand_dims(reward, -1)\n\n obs = paddle.to_tensor(obs, dtype='float32')\n action = paddle.to_tensor(action, dtype='float32')\n reward = paddle.to_tensor(reward, dtype='float32')\n next_obs = paddle.to_tensor(next_obs, dtype='float32')\n terminal = paddle.to_tensor(terminal, dtype='float32')\n critic_loss, actor_loss = self.alg.learn(obs, action, reward, next_obs,\n terminal)\n return critic_loss, actor_loss\n",
"# Copyright (c) 2021 PaddlePaddle 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\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport parl\n\n\nclass MAMLModel(parl.Model):\n def __init__(self, network_dims, device):\n \"\"\"\n Builds a multi-layer perceptron. It also provides functionality for passing external parameters to be\n used at inference time.\n \n Args:\n network_dims: List, define the dimension of each linear layer.\n device: Cpu or cuda.\n \"\"\"\n super().__init__()\n\n self.network_dims = network_dims\n self.num_layers = len(network_dims) - 1\n\n self.params = list()\n\n for i in range(len(self.network_dims) - 1):\n weight = nn.Parameter(\n torch.zeros((self.network_dims[i + 1], self.network_dims[i]),\n device=device))\n torch.nn.init.kaiming_normal_(weight)\n self.params.append(weight)\n self.params.append(\n nn.Parameter(\n torch.zeros((self.network_dims[i + 1]), device=device)))\n\n def forward(self, x, params=None):\n \"\"\"\n Forward propages through the network. If any params are passed then they are used instead of stored params.\n\n Args:\n x: Input\n params: If params are None then internal parameters are used. If params are a dictionary with keys the\n same as the layer names then they will be used instead.\n\n \"\"\"\n\n if params is None:\n params = self.params\n\n assert len(params) // 2 == self.num_layers\n\n for i in range(self.num_layers):\n x = F.linear(x, params[i * 2], params[i * 2 + 1])\n\n # pass to an activation function if it's not the last layer\n if i != len(self.network_dims) - 2:\n x = F.relu(x)\n\n return x\n\n def zero_grad(self, params=None):\n if params is None:\n for param in self.params:\n if param.requires_grad and param.grad is not None:\n param.grad.zero_()\n else:\n for param in params:\n if param.requires_grad and param.grad is not None:\n param.grad.zero_()\n\n def get_weights(self):\n\n return self.params\n\n def set_weights(self, new_weights):\n self.params.clear()\n\n for weight in new_weights:\n self.params.append(weight.detach().clone())\n",
"# Copyright (c) 2021 PaddlePaddle 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\nimport os\nos.environ['PARL_BACKEND'] = 'torch'\n\nimport torch\nimport random\nimport numpy as np\nfrom config import config\nfrom rl_trainer.controller import Controller\nfrom parl.utils import logger, tensorboard\nfrom parl.utils.window_stat import WindowStat\nfrom zerosum_env import make, evaluate\nfrom zerosum_env.envs.halite.helpers import *\n\nenv_seed = config[\"seed\"]\ntorch.manual_seed(env_seed)\ntorch.cuda.manual_seed(env_seed)\ntorch.cuda.manual_seed_all(env_seed)\nnp.random.seed(env_seed)\nrandom.seed(env_seed)\n'''set up agent\nIn this training script, we only train the first agent\nIf you want to train the agent by self-play, you can also set \n player_list = [None, None]\nThen, the environment will return the observation of these two agents\nRight now, we only use\n player_list = [None, \"random\"]\nThen, the environment will only return the observation of the first agent\n'''\nplayer_list = [None, \"random\"]\n\n# recoring the index of agents being trained\nplayer_index = [i for i in range(len(player_list)) if player_list[i] == None]\nplayer_num = len(player_list)\n\n# set up agent controller\nplayers = [None] * player_num\nfor player_ind in player_index:\n players[player_ind] = Controller()\n\n\n# return action for each ship and shipyard\n# this function will be only used in testing\ndef take_action(observation, configuration):\n board = Board(observation, configuration)\n action = players[0].take_action(board, \"predict\")\n return action\n\n\n# function for testing\ndef test_agent():\n players[0].prepare_test()\n rew, _, _, errors = evaluate(\n \"halite\",\n agents=[take_action, \"random\"],\n configuration={\"randomSeed\": env_seed},\n debug=True)\n rew1, rew2 = rew[0][0], rew[0][1]\n\n if rew1 is None or rew2 is None:\n # Somthing wrong happends in your program(Sometimes the built-in evaluate function will raise\n # timeout exception if the cpu resource is limited)\n # please check the errors to see the detailed message\n print(errors[0])\n return None, None\n return rew1, rew2\n\n\ndef main():\n\n # statistic data to be recorded\n total_step = 0\n best_win_rate = 0\n best_test_rew = 0\n win_stat = WindowStat(100)\n\n # start training\n for episode in range(config[\"episodes\"]):\n\n # build self-play environment\n '''another way to build an environment without a specific seed\n env = make(\"halite\", configuration={\"size\": config[\"board_size\"]})\n '''\n env = make(\n \"halite\",\n configuration={\n \"size\": config[\"board_size\"],\n \"randomSeed\": env_seed\n })\n configuration = env.configuration\n env = env.train_selfplay(player_list)\n\n # initialize observation\n observation = env.reset()\n boards = [Board(obs, configuration) for obs in observation]\n\n # statistic data to be recorded\n episode_step = 0\n episode_halite = [0] * player_num\n episode_ship_halite = [0] * player_num\n episode_ship_num = [0] * player_num\n episode_shipyard_num = [0] * player_num\n\n # record the alive status of players\n agent_done = [False] * player_num\n\n # since we train the agent with a random agent, we also save the episode halite obtained by\n # the random agent and compute a winning rate\n random_agent_halite = 0\n\n # reset the parameters in player\n for ind, board in zip(player_index, boards):\n players[ind].prepare_train()\n\n while True:\n\n total_step += 1\n episode_step += 1\n\n # record the actions of agents\n actions = [None] * player_num\n\n # sampling actions\n for ind, board in zip(player_index, boards):\n\n # compute the action for those alive agents\n if not agent_done[ind]:\n\n actions[ind] = players[ind].take_action(board, \"sample\")\n\n # fetch data of each training agent\n player_infos, terminal = env.step(actions)\n observation_next = [infos[0] for infos in player_infos]\n rews = [infos[1] for infos in player_infos]\n dones = [infos[2] for infos in player_infos]\n boards_next = [\n Board(obs_next, configuration) for obs_next in observation_next\n ]\n\n # reset the flag of done\n for ind, done in zip(player_index, dones):\n agent_done[ind] = done\n\n boards = boards_next\n\n if terminal:\n\n # update the final state of ships and shipyards and save data\n for ind, board in zip(player_index, boards):\n players[ind].update_state(board)\n episode_ship_halite[ind] = sum(\n [ship.halite for ship in board.current_player.ships])\n episode_halite[ind] = board.current_player.halite\n episode_ship_num[ind] = len(board.current_player.ship_ids)\n episode_shipyard_num[ind] = len(\n board.current_player.shipyard_ids)\n\n random_agent_halite = boards[0].opponents[0].halite\n break\n\n # train agents\n if len(players[0].ship_buffer):\n value_loss, action_loss, entropy = players[0].train_ship_agent()\n tensorboard.add_scalar(\"train/ship_value_loss\", value_loss,\n total_step)\n tensorboard.add_scalar(\"train/ship_policy_loss\", action_loss,\n total_step)\n tensorboard.add_scalar(\"train/ship_entropy\", entropy, total_step)\n\n # snippet of code to test the agent\n '''\n # test agent\n if (episode) % config[\"test_every_episode\"] == 0:\n rew1, rew2 = test_agent()\n if rew1 is not None and rew2 is not None:\n tensorboard.add_scalar(\"test/player_rew\", rew1, episode)\n tensorboard.add_scalar(\"test/random_rew\", rew2, episode)\n # saving model\n if rew1 > best_test_rew:\n best_test_rew = rew1\n ship_model_path = os.path.join(config[\"save_path\"], 'test_ship_model_ep_%s_rew_%s.pth' % (episode, rew1))\n players[0].save(ship_model_path)\n '''\n\n # print statistic data\n for ind, player in zip(player_index, players):\n ship_rew = np.array(player.ship_rew)\n ship_len = np.array(player.ship_len)\n ship_rew = ship_rew.mean() if len(ship_rew) else None\n ship_len = ship_len.mean() if len(ship_len) else None\n\n message = \"player_id:{0}, \".format(ind)\n if ship_rew is not None:\n message += \"ship_rew:{0:.2f}, \".format(ship_rew)\n tensorboard.add_scalar(\"train/ship_rew\", ship_rew, total_step)\n if ship_len is not None:\n message += \"ship_len:{0:.2f}, \".format(ship_len)\n tensorboard.add_scalar(\"train/ship_len\", ship_len, total_step)\n\n if ship_rew is not None or ship_len is not None:\n logger.info(message)\n\n for player_ind, halite, ship_num, shipyard_num, ship_halite in zip(\n player_index, episode_halite, episode_ship_num,\n episode_shipyard_num, episode_ship_halite):\n\n win_stat.add(halite > random_agent_halite)\n\n logger.info(\n \"player_id:{0}, episode_halite:{1}, ship_num:{2}, shipyard_num:{3}, ship_halite:{4}\"\n .format(player_ind, halite, ship_num, shipyard_num,\n ship_halite))\n\n tensorboard.add_scalar(\n \"train/player{0}_environment_rew\".format(player_ind), halite,\n episode)\n tensorboard.add_scalar(\n \"train/player{0}_winning_rate\".format(player_ind),\n win_stat.mean, episode)\n\n # save the best model\n if win_stat.mean > best_win_rate:\n best_win_rate = win_stat.mean\n ship_model_path = os.path.join(\n config[\"save_path\"], 'player%s_best_ship_model_ep_%s.pth' %\n (player_ind, episode))\n players[player_ind].save(ship_model_path)\n\n # save the latest model\n ship_model_path = os.path.join(config[\"save_path\"],\n 'latest_ship_model.pth')\n players[0].save(ship_model_path)\n\n\nif __name__ == '__main__':\n main()\n",
"# Copyright (c) 2018 PaddlePaddle 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\nfrom parl.utils import check_version_for_fluid # requires parl >= 1.4.1\ncheck_version_for_fluid()\n\nimport os\nimport time\nimport argparse\nimport numpy as np\nfrom simple_model import MAModel\nfrom simple_agent import MAAgent\nimport parl\nfrom parl.env.multiagent_simple_env import MAenv\nfrom parl.utils import logger, summary\n\n\ndef run_episode(env, agents):\n obs_n = env.reset()\n total_reward = 0\n agents_reward = [0 for _ in range(env.n)]\n steps = 0\n while True:\n steps += 1\n action_n = [agent.predict(obs) for agent, obs in zip(agents, obs_n)]\n next_obs_n, reward_n, done_n, _ = env.step(action_n)\n done = all(done_n)\n terminal = (steps >= args.max_step_per_episode)\n\n # store experience\n for i, agent in enumerate(agents):\n agent.add_experience(obs_n[i], action_n[i], reward_n[i],\n next_obs_n[i], done_n[i])\n\n # compute reward of every agent\n obs_n = next_obs_n\n for i, reward in enumerate(reward_n):\n total_reward += reward\n agents_reward[i] += reward\n\n # check the end of an episode\n if done or terminal:\n break\n\n # show animation\n if args.show:\n time.sleep(0.1)\n env.render()\n\n # show model effect without training\n if args.restore and args.show:\n continue\n\n # learn policy\n for i, agent in enumerate(agents):\n critic_loss = agent.learn(agents)\n summary.add_scalar('critic_loss_%d' % i, critic_loss,\n agent.global_train_step)\n\n return total_reward, agents_reward, steps\n\n\ndef train_agent():\n env = MAenv(args.env)\n logger.info('agent num: {}'.format(env.n))\n logger.info('observation_space: {}'.format(env.observation_space))\n logger.info('action_space: {}'.format(env.action_space))\n logger.info('obs_shape_n: {}'.format(env.obs_shape_n))\n logger.info('act_shape_n: {}'.format(env.act_shape_n))\n for i in range(env.n):\n logger.info('agent {} obs_low:{} obs_high:{}'.format(\n i, env.observation_space[i].low, env.observation_space[i].high))\n logger.info('agent {} act_n:{}'.format(i, env.act_shape_n[i]))\n if ('low' in dir(env.action_space[i])):\n logger.info('agent {} act_low:{} act_high:{} act_shape:{}'.format(\n i, env.action_space[i].low, env.action_space[i].high,\n env.action_space[i].shape))\n logger.info('num_discrete_space:{}'.format(\n env.action_space[i].num_discrete_space))\n\n from gym import spaces\n from multiagent.multi_discrete import MultiDiscrete\n for space in env.action_space:\n assert (isinstance(space, spaces.Discrete)\n or isinstance(space, MultiDiscrete))\n\n agents = []\n for i in range(env.n):\n model = MAModel(env.act_shape_n[i])\n algorithm = parl.algorithms.MADDPG(\n model,\n agent_index=i,\n act_space=env.action_space,\n gamma=args.gamma,\n tau=args.tau,\n critic_lr=args.critic_lr,\n actor_lr=args.actor_lr)\n agent = MAAgent(\n algorithm,\n agent_index=i,\n obs_dim_n=env.obs_shape_n,\n act_dim_n=env.act_shape_n,\n batch_size=args.batch_size,\n speedup=(not args.restore))\n agents.append(agent)\n total_steps = 0\n total_episodes = 0\n\n episode_rewards = [] # sum of rewards for all agents\n agent_rewards = [[] for _ in range(env.n)] # individual agent reward\n final_ep_rewards = [] # sum of rewards for training curve\n final_ep_ag_rewards = [] # agent rewards for training curve\n\n if args.restore:\n # restore modle\n for i in range(len(agents)):\n model_file = args.model_dir + '/agent_' + str(i)\n if not os.path.exists(model_file):\n raise Exception(\n 'model file {} does not exits'.format(model_file))\n agents[i].restore(model_file)\n\n t_start = time.time()\n logger.info('Starting...')\n while total_episodes <= args.max_episodes:\n # run an episode\n ep_reward, ep_agent_rewards, steps = run_episode(env, agents)\n if args.show:\n print('episode {}, reward {}, steps {}'.format(\n total_episodes, ep_reward, steps))\n\n # Record reward\n total_steps += steps\n total_episodes += 1\n episode_rewards.append(ep_reward)\n for i in range(env.n):\n agent_rewards[i].append(ep_agent_rewards[i])\n\n # Keep track of final episode reward\n if total_episodes % args.stat_rate == 0:\n mean_episode_reward = np.mean(episode_rewards[-args.stat_rate:])\n final_ep_rewards.append(mean_episode_reward)\n for rew in agent_rewards:\n final_ep_ag_rewards.append(np.mean(rew[-args.stat_rate:]))\n use_time = round(time.time() - t_start, 3)\n logger.info(\n 'Steps: {}, Episodes: {}, Mean episode reward: {}, Time: {}'.\n format(total_steps, total_episodes, mean_episode_reward,\n use_time))\n t_start = time.time()\n summary.add_scalar('mean_episode_reward/episode',\n mean_episode_reward, total_episodes)\n summary.add_scalar('mean_episode_reward/steps',\n mean_episode_reward, total_steps)\n summary.add_scalar('use_time/1000episode', use_time,\n total_episodes)\n\n # save model\n if not args.restore:\n os.makedirs(os.path.dirname(args.model_dir), exist_ok=True)\n for i in range(len(agents)):\n model_name = '/agent_' + str(i)\n agents[i].save(args.model_dir + model_name)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n # Environment\n parser.add_argument(\n '--env',\n type=str,\n default='simple_speaker_listener',\n help='scenario of MultiAgentEnv')\n parser.add_argument(\n '--max_step_per_episode',\n type=int,\n default=25,\n help='maximum step per episode')\n parser.add_argument(\n '--max_episodes',\n type=int,\n default=25000,\n help='stop condition:number of episodes')\n parser.add_argument(\n '--stat_rate',\n type=int,\n default=1000,\n help='statistical interval of save model or count reward')\n # Core training parameters\n parser.add_argument(\n '--critic_lr',\n type=float,\n default=1e-3,\n help='learning rate for the critic model')\n parser.add_argument(\n '--actor_lr',\n type=float,\n default=1e-3,\n help='learning rate of the actor model')\n parser.add_argument(\n '--gamma', type=float, default=0.95, help='discount factor')\n parser.add_argument(\n '--batch_size',\n type=int,\n default=1024,\n help='number of episodes to optimize at the same time')\n parser.add_argument('--tau', type=int, default=0.01, help='soft update')\n # auto save model, optional restore model\n parser.add_argument(\n '--show', action='store_true', default=False, help='display or not')\n parser.add_argument(\n '--restore',\n action='store_true',\n default=False,\n help='restore or not, must have model_dir')\n parser.add_argument(\n '--model_dir',\n type=str,\n default='./model',\n help='directory for saving model')\n\n args = parser.parse_args()\n\n train_agent()\n"
] | [
[
"numpy.array"
],
[
"numpy.expand_dims"
],
[
"torch.nn.functional.relu",
"torch.zeros",
"torch.nn.functional.linear",
"torch.nn.init.kaiming_normal_"
],
[
"numpy.random.seed",
"torch.cuda.manual_seed",
"torch.manual_seed",
"torch.cuda.manual_seed_all",
"numpy.array"
],
[
"numpy.mean"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.