repo_name
stringlengths 6
130
| hexsha
list | file_path
list | code
list | apis
list |
---|---|---|---|---|
GeorgeMironov/albumentations | [
"fe3f36a0285bce9abb6496c410ba672f53f15be6"
] | [
"tests/test_core.py"
] | [
"from __future__ import absolute_import\n\nimport cv2\nimport numpy as np\nimport pytest\n\nfrom albumentations.core.transforms_interface import to_tuple, ImageOnlyTransform, DualTransform\nfrom albumentations.augmentations.bbox_utils import check_bboxes\nfrom albumentations.core.composition import OneOrOther, Compose, OneOf\nfrom .compat import mock, MagicMock, Mock, call\n\n\ndef test_one_or_other():\n first = MagicMock()\n second = MagicMock()\n augmentation = OneOrOther(first, second, p=1)\n image = np.ones((8, 8))\n augmentation(image=image)\n assert first.called != second.called\n\n\ndef test_compose():\n first = MagicMock()\n second = MagicMock()\n augmentation = Compose([first, second], p=1)\n image = np.ones((8, 8))\n augmentation(image=image)\n assert first.called\n assert second.called\n\n\ndef test_compose_to_tensor():\n first = MagicMock()\n second = MagicMock()\n to_tensor = MagicMock()\n augmentation = Compose([first, second], to_tensor=to_tensor, p=0)\n image = np.ones((8, 8))\n augmentation(image=image)\n assert to_tensor.called\n\n\ndef test_one_of():\n transforms = [Mock(p=1) for _ in range(10)]\n augmentation = OneOf(transforms, p=1)\n image = np.ones((8, 8))\n augmentation(image=image)\n assert len([transform for transform in transforms if transform.called]) == 1\n\n\ndef test_to_tuple():\n assert to_tuple(10) == (-10, 10)\n assert to_tuple(0.5) == (-0.5, 0.5)\n assert to_tuple((-20, 20)) == (-20, 20)\n assert to_tuple([-20, 20]) == (-20, 20)\n assert to_tuple(100, low=30) == (30, 100)\n\n\ndef test_image_only_transform(image, mask):\n height, width = image.shape[:2]\n with mock.patch.object(ImageOnlyTransform, 'apply') as mocked_apply:\n with mock.patch.object(ImageOnlyTransform, 'get_params', return_value={'interpolation': cv2.INTER_LINEAR}):\n aug = ImageOnlyTransform(p=1)\n data = aug(image=image, mask=mask)\n mocked_apply.assert_called_once_with(image, interpolation=cv2.INTER_LINEAR, cols=width, rows=height)\n assert np.array_equal(data['mask'], mask)\n\n\ndef test_dual_transform(image, mask):\n image_call = call(image, interpolation=cv2.INTER_LINEAR, cols=image.shape[1], rows=image.shape[0])\n mask_call = call(mask, interpolation=cv2.INTER_NEAREST, cols=mask.shape[1], rows=mask.shape[0])\n with mock.patch.object(DualTransform, 'apply') as mocked_apply:\n with mock.patch.object(DualTransform, 'get_params', return_value={'interpolation': cv2.INTER_LINEAR}):\n aug = DualTransform(p=1)\n aug(image=image, mask=mask)\n mocked_apply.assert_has_calls([image_call, mask_call], any_order=True)\n\n\ndef test_check_bboxes_with_correct_values():\n try:\n check_bboxes([[0.1, 0.5, 0.8, 1.0], [0.2, 0.5, 0.5, 0.6, 99]])\n except Exception as e:\n pytest.fail('Unexpected Exception {!r}'.format(e))\n\n\ndef test_check_bboxes_with_values_less_than_zero():\n with pytest.raises(ValueError) as exc_info:\n check_bboxes([[0.2, 0.5, 0.5, 0.6, 99], [-0.1, 0.5, 0.8, 1.0]])\n message = 'Expected x_min for bbox [-0.1, 0.5, 0.8, 1.0] to be in the range [0.0, 1.0], got -0.1.'\n assert str(exc_info.value) == message\n\n\ndef test_check_bboxes_with_values_greater_than_one():\n with pytest.raises(ValueError) as exc_info:\n check_bboxes([[0.2, 0.5, 1.5, 0.6, 99], [0.1, 0.5, 0.8, 1.0]])\n message = 'Expected x_max for bbox [0.2, 0.5, 1.5, 0.6, 99] to be in the range [0.0, 1.0], got 1.5.'\n assert str(exc_info.value) == message\n\n\ndef test_check_bboxes_with_end_greater_that_start():\n with pytest.raises(ValueError) as exc_info:\n check_bboxes([[0.8, 0.5, 0.7, 0.6, 99], [0.1, 0.5, 0.8, 1.0]])\n message = 'x_max is less than or equal to x_min for bbox [0.8, 0.5, 0.7, 0.6, 99].'\n assert str(exc_info.value) == message\n"
] | [
[
"numpy.array_equal",
"numpy.ones"
]
] |
scuervo91/dcapy | [
"46c9277e607baff437e5707167476d5f7e2cf80c"
] | [
"dcapy/wiener/brownian.py"
] | [
"# External Imports\nimport numpy as np \nimport pandas as pd\nfrom scipy import stats\nfrom pydantic import BaseModel, Field, Extra\nfrom typing import List, Union, Optional\nfrom datetime import date\n#Local Imports\nfrom ..dca import list_freq, converter_factor, ProbVar\nfrom ..dca import FreqEnum\n#from ..models import ChgPts\n\nclass Weiner(BaseModel):\n initial_condition: Union[float,List[float]] = Field(0)\n ti: Union[int,date] = Field(0)\n steps: int = Field(1, gt=0)\n processes: int = Field(1, gt=0)\n generator: ProbVar = Field(ProbVar())\n freq_input: FreqEnum = Field('D')\n freq_output: FreqEnum = Field('D')\n\n class Config:\n arbitrary_types_allowed = True\n validate_assignment = True\n extra = Extra.forbid\n\n def weiner_generator(self,steps:int=None,processes:int=None,interval=None, seed=None): \n for i in [steps,processes]:\n assert isinstance(i,int)\n \n if interval:\n half = (1-interval)/2\n \n min_x = half \n max_x = 1-half \n \n n_vector = np.linspace(min_x,max_x,processes)\n ppf = np.broadcast_to(n_vector,(steps,processes)).T\n \n size = None \n else:\n size = (processes,steps)\n ppf=None\n \n return self.generator.get_sample(size=size, seed=seed, ppf=ppf) \n \n def get_index_array(self, steps:int, freq_output:str):\n if isinstance(self.ti,date):\n return pd.period_range(start=self.ti,periods=steps,freq=freq_output)\n #idx = [i.to_timestamp().strftime('%Y-%m-%d') for i in pr]\n else:\n return np.arange(0,steps,1).tolist()\n\nclass Brownian(Weiner):\n drift : float = Field(0)\n \n class Config:\n arbitrary_types_allowed = True\n validate_assignment = True\n extra = Extra.forbid\n\n def generate(self,steps=None,processes=None, freq_output=None,interval=None, seed=None):\n \"\"\"brownian_motion [summary]\n\n Args:\n steps ([type]): [description]\n processes ([type]): [description]\n freq_output (str, optional): [description]. Defaults to 'D'.\n interval ([type], optional): [description]. Defaults to None.\n seed ([type], optional): [description]. Defaults to None.\n\n Returns:\n [type]: [description]\n \"\"\"\n if steps is None:\n steps = self.steps\n \n if processes is None:\n processes = self.processes \n\n if freq_output is None:\n if self.freq_output is None:\n freq_output = self.freq_input\n else:\n freq_output = self.freq_output\n \n if interval is not None:\n assert all([interval>=0,interval<=1])\n epsilon = self.weiner_generator(steps,processes,interval=interval)\n else:\n epsilon = self.weiner_generator(steps,processes, seed=seed)\n \n #Create zeros arrays for Weiner Process. Rows number of process, Columns Steps\n w = np.zeros((processes,steps))\n w[:,0] = self.initial_condition\n\n # Time Step size\n dt = converter_factor(self.freq_input,freq_output)\n\n #Drift for the Brownian Process\n mu = self.drift * dt \n\n #Weiner Process\n for n in range(processes):\n for t in range(1,steps):\n w[n,t] = w[n,t-1] + mu + (epsilon[n,t]*np.sqrt(dt))\n \n idx = self.get_index_array(steps,freq_output)\n \n return pd.DataFrame(w.T, index=idx,columns=range(processes))\n\nclass GeometricBrownian(Weiner):\n drift : float = Field(0)\n \n class Config:\n arbitrary_types_allowed = True\n validate_assignment = True\n extra = Extra.forbid\n\n def generate(self,steps=None,processes=None, freq_output=None,interval=None, seed=None):\n \"\"\"geometric_brownian_motion [summary]\n\n Args:\n steps ([type]): [description]\n processes ([type]): [description]\n freq_output (str, optional): [description]. Defaults to 'D'.\n interval ([type], optional): [description]. Defaults to None.\n seed ([type], optional): [description]. Defaults to None.\n\n Returns:\n [type]: [description]\n \"\"\"\n if steps is None:\n steps = self.steps\n \n if processes is None:\n processes = self.processes \n\n if freq_output is None:\n if self.freq_output is None:\n freq_output = self.freq_input\n else:\n freq_output = self.freq_output\n \n if interval is not None:\n assert all([interval>=0,interval<=1])\n epsilon = self.weiner_generator(steps,processes,interval=interval)\n else:\n epsilon = self.weiner_generator(steps,processes, seed=seed)\n \n #Create zeros arrays for Weiner Process. Rows number of process, Columns Steps\n w = np.zeros((processes,steps))\n w[:,0] = self.initial_condition\n \n # Time Step size\n dt = converter_factor(self.freq_input,freq_output)\n \n #Drift for the Brownian Process\n mu = self.drift * dt\n var = np.power(self.generator.kw['scale'],2) * dt\n\n \n drift = mu - var/2\n\n #Weiner Process\n for n in range(processes):\n for t in range(1,steps):\n w[n,t] = w[n,t-1]*np.exp(drift + (epsilon[n,t]*np.sqrt(dt)))\n \n idx = self.get_index_array(steps,freq_output)\n \n return pd.DataFrame(w.T, index=idx,columns=range(processes))\n\nclass MeanReversion(Weiner):\n m : float = Field(0)\n eta : float = Field(0)\n \n class Config:\n arbitrary_types_allowed = True\n validate_assignment = True\n extra = Extra.forbid\n \n def generate(self,steps=None,processes=None, freq_output=None,interval=None, seed=None):\n \"\"\"mean_reversion [summary]\n\n Args:\n steps ([type]): [description]\n processes ([type]): [description]\n freq_output (str, optional): [description]. Defaults to 'D'.\n interval ([type], optional): [description]. Defaults to None.\n seed ([type], optional): [description]. Defaults to None.\n \"\"\"\n if steps is None:\n steps = self.steps\n \n if processes is None:\n processes = self.processes \n\n if freq_output is None:\n if self.freq_output is None:\n freq_output = self.freq_input\n else:\n freq_output = self.freq_output\n \n epsilon = self.weiner_generator(steps,processes, seed=seed)\n \n #Create zeros arrays for Weiner Process. Rows number of process, Columns Steps\n w = np.zeros((processes,steps))\n w[:,0] = self.initial_condition\n \n # Time Step size\n dt = converter_factor(self.freq_input,freq_output)\n \n m = self.m \n eta = self.eta\n \n #Weiner Process\n for n in range(processes):\n for t in range(1,steps):\n w[n,t] = m * (1 - np.exp(-eta)) + (np.exp(-eta) - 1) * w[n,t-1] + epsilon[n,t] + w[n,t-1]\n\n idx = self.get_index_array(steps,freq_output)\n \n return pd.DataFrame(w.T, index=idx,columns=range(processes))"
] | [
[
"numpy.sqrt",
"numpy.linspace",
"numpy.power",
"pandas.period_range",
"numpy.arange",
"numpy.broadcast_to",
"numpy.exp",
"numpy.zeros"
]
] |
trendscenter/fsl-parser-package | [
"84e519f797cfe3c442a66ee4d48f57649f1ee994"
] | [
"fslparser/parsers.py"
] | [
"#!/usr/bin/env python3\n\n\nimport os\nimport pandas as pd\n\n\ndef parse_for_y(args, y_files, y_labels):\n \"\"\"Read contents of fsl files into a dataframe\"\"\"\n y = pd.DataFrame(index=y_labels)\n\n for file in y_files:\n if file:\n try:\n y_ = pd.read_csv(\n os.path.join(args[\"state\"][\"baseDirectory\"], file),\n sep='\\t',\n header=None,\n names=['Measure:volume', file],\n index_col=0)\n y_ = y_[~y_.index.str.contains(\"Measure:volume\")]\n y_ = y_.apply(pd.to_numeric, errors='ignore')\n y = pd.merge(\n y, y_, how='left', left_index=True, right_index=True)\n except pd.errors.EmptyDataError:\n continue\n except FileNotFoundError:\n continue\n\n y = y.T\n\n return y\n\n\ndef fsl_parser(args):\n \"\"\"Parse the freesurfer (fsl) specific inputspec.json and return the\n covariate matrix (X) as well the dependent matrix (y) as dataframes\"\"\"\n input_list = args[\"input\"]\n X_info = input_list[\"covariates\"]\n y_info = input_list[\"data\"]\n\n X_df = pd.DataFrame.from_dict(X_info).T\n\n X = X_df.apply(pd.to_numeric, errors='ignore')\n X = pd.get_dummies(X, drop_first=True)\n X = X * 1\n\n y_labels = y_info[0][\"value\"]\n y_files = X.index\n\n y = parse_for_y(args, y_files, y_labels)\n\n ixs = X.index.intersection(y.index)\n\n if ixs.empty:\n raise Exception('No common X and y files at ' +\n args[\"state\"][\"clientId\"])\n else:\n X = X.loc[ixs]\n y = y.loc[ixs]\n\n return (X, y)\n\n\n"
] | [
[
"pandas.DataFrame.from_dict",
"pandas.merge",
"pandas.DataFrame",
"pandas.get_dummies"
]
] |
Cybsloth/LightAutoML | [
"77b49ecb08b4cd655fda7564a7e55c0bf2d124da"
] | [
"lightautoml/automl/presets/base.py"
] | [
"\"\"\"AutoML presets base class.\"\"\"\n\nimport logging\nimport os\nimport shutil\n\nfrom typing import Any\nfrom typing import Iterable\nfrom typing import Optional\nfrom typing import Sequence\n\nimport torch\nimport yaml\n\nfrom ...dataset.base import LAMLDataset\nfrom ...tasks import Task\nfrom ...utils.logging import add_filehandler\nfrom ...utils.logging import set_stdout_level\nfrom ...utils.logging import verbosity_to_loglevel\nfrom ...utils.timer import PipelineTimer\nfrom ..base import AutoML\n\n\nlogger = logging.getLogger(__name__)\n\nbase_dir = os.path.dirname(__file__)\n\n\ndef upd_params(old: dict, new: dict) -> dict:\n \"\"\"Update dictonary of parameters.\n\n Args:\n old: Old parameters.\n new: Changes.\n\n Returns:\n Updated parameters.\n\n \"\"\"\n for k in new:\n if type(new[k]) is dict and k in old and type(old[k]) is dict:\n upd_params(old[k], new[k])\n else:\n old[k] = new[k]\n\n return old\n\n\nclass AutoMLPreset(AutoML):\n \"\"\"Basic class for automl preset.\n\n It's almost like AutoML, but with delayed initialization.\n Initialization starts on fit, some params are inferred from data.\n Preset should be defined via ``.create_automl`` method. Params should be set via yaml config.\n Most usefull case - end-to-end model development.\n\n Commonly _params kwargs (ex. timing_params) set via config file (config_path argument).\n If you need to change just few params, it's possible to pass it as dict of dicts, like json.\n To get available params please look on default config template. Also you can find there param description.\n To generate config template call ``SomePreset.get_config('config_path.yml')``.\n\n Example:\n >>> automl = SomePreset(Task('binary'), timeout=3600)\n >>> automl.fit_predict(data, roles={'target': 'TARGET'})\n\n Args:\n task: Task to solve.\n timeout: Timeout in seconds.\n memory_limit: Memory limit that are passed to each automl.\n cpu_limit: CPU limit that that are passed to each automl.\n gpu_ids: GPU IDs that are passed to each automl.\n verbose: Controls the verbosity: the higher, the more messages.\n <1 : messages are not displayed;\n >=1 : the computation process for layers is displayed;\n >=2 : the information about folds processing is also displayed;\n >=3 : the hyperparameters optimization process is also displayed;\n >=4 : the training process for every algorithm is displayed;\n timing_params: Timing param dict.\n config_path: Path to config file.\n **kwargs: Not used.\n\n \"\"\"\n\n _default_config_path = \"example_config.yml\"\n\n def __init__(\n self,\n task: Task,\n timeout: int = 3600,\n memory_limit: int = 16,\n cpu_limit: int = 4,\n gpu_ids: Optional[str] = \"all\",\n timing_params: Optional[dict] = None,\n config_path: Optional[str] = None,\n **kwargs: Any,\n ):\n self._set_config(config_path)\n\n for name, param in zip([\"timing_params\"], [timing_params]):\n if param is None:\n param = {}\n self.__dict__[name] = {**self.__dict__[name], **param}\n\n self.timer = PipelineTimer(timeout, **getattr(self, \"timing_params\"))\n self.memory_limit = memory_limit\n if cpu_limit == -1:\n cpu_limit = os.cpu_count()\n self.cpu_limit = cpu_limit\n self.gpu_ids = gpu_ids\n if gpu_ids == \"all\":\n self.gpu_ids = \",\".join(map(str, range(torch.cuda.device_count())))\n self.task = task\n\n def _set_config(self, path):\n self.config_path = path\n\n if path is None:\n path = os.path.join(base_dir, self._default_config_path)\n\n with open(path) as f:\n params = yaml.safe_load(f)\n\n for k in params:\n self.__dict__[k] = params[k]\n\n @classmethod\n def get_config(cls, path: Optional[str] = None) -> Optional[dict]:\n \"\"\"Create new config template.\n\n Args:\n path: Path to config.\n\n Returns:\n Config.\n\n \"\"\"\n if path is None:\n path = os.path.join(base_dir, cls._default_config_path)\n with open(path) as f:\n params = yaml.safe_load(f)\n return params\n\n else:\n shutil.copy(os.path.join(base_dir, cls._default_config_path), path)\n\n def create_automl(self, **fit_args):\n \"\"\"Abstract method - how to build automl.\n\n Here you should create all automl components,\n like readers, levels, timers, blenders.\n Method ``._initialize`` should be called in the end to create automl.\n\n Args:\n **fit_args: params that are passed to ``.fit_predict`` method.\n\n \"\"\"\n raise NotImplementedError\n\n def fit_predict(\n self,\n train_data: Any,\n roles: dict,\n train_features: Optional[Sequence[str]] = None,\n cv_iter: Optional[Iterable] = None,\n valid_data: Optional[Any] = None,\n valid_features: Optional[Sequence[str]] = None,\n verbose: int = 0,\n ) -> LAMLDataset:\n \"\"\"Fit on input data and make prediction on validation part.\n\n Args:\n train_data: Dataset to train.\n roles: Roles dict.\n train_features: Features names,\n if can't be inferred from `train_data`.\n cv_iter: Custom cv-iterator. For example,\n :class:`~lightautoml.validation.np_iterators.TimeSeriesIterator`.\n valid_data: Optional validation dataset.\n valid_features: Optional validation dataset features if can't be\n inferred from `valid_data`.\n verbose: Verbosity level that are passed to each automl.\n\n Returns:\n Dataset with predictions. Call ``.data`` to get predictions array.\n\n \"\"\"\n self.set_verbosity_level(verbose)\n\n self.create_automl(\n train_data=train_data,\n roles=roles,\n train_features=train_features,\n cv_iter=cv_iter,\n valid_data=valid_data,\n valid_features=valid_features,\n )\n logger.info(f\"Task: {self.task.name}\\n\")\n\n logger.info(\"Start automl preset with listed constraints:\")\n logger.info(f\"- time: {self.timer.timeout:.2f} seconds\")\n logger.info(f\"- CPU: {self.cpu_limit} cores\")\n logger.info(f\"- memory: {self.memory_limit} GB\\n\")\n\n self.timer.start()\n result = super().fit_predict(\n train_data,\n roles,\n train_features,\n cv_iter,\n valid_data,\n valid_features,\n verbose=verbose,\n )\n\n logger.info(\"\\x1b[1mAutoml preset training completed in {:.2f} seconds\\x1b[0m\\n\".format(self.timer.time_spent))\n logger.info(f\"Model description:\\n{self.create_model_str_desc()}\\n\")\n\n return result\n\n def create_model_str_desc(self, pref_tab_num: int = 0, split_line_len: int = 0) -> str: # noqa: D102\n prefix = \"\\t\" * pref_tab_num\n splitter = prefix + \"=\" * split_line_len + \"\\n\"\n model_stats = sorted(list(self.collect_model_stats().items()))\n\n last_lvl = model_stats[-1][0].split(\"_\")[1]\n last_lvl_models = [ms for ms in model_stats if ms[0].startswith(\"Lvl_\" + last_lvl)]\n notlast_lvl_models = [ms for ms in model_stats if not ms[0].startswith(\"Lvl_\" + last_lvl)]\n\n res = \"\"\n if len(notlast_lvl_models) > 0:\n cur_level = 0\n res += prefix + \"Models on level 0:\\n\"\n for model_stat in notlast_lvl_models:\n model_name, cnt_folds = model_stat\n level = int(model_name.split(\"_\")[1])\n if level != cur_level:\n cur_level = level\n res += \"\\n\" + prefix + \"Models on level {}:\\n\".format(cur_level)\n res += prefix + \"\\t {} averaged models {}\\n\".format(cnt_folds, model_name)\n res += \"\\n\"\n\n res += prefix + \"Final prediction for new objects (level {}) = \\n\".format(last_lvl)\n for model_stat, weight in zip(last_lvl_models, self.blender.wts):\n model_name, cnt_folds = model_stat\n res += prefix + \"\\t {:.5f} * ({} averaged models {}) +\\n\".format(weight, cnt_folds, model_name)\n\n if split_line_len == 0:\n return res[:-2]\n\n return splitter + res[:-2] + \"\\n\" + splitter\n\n @staticmethod\n def set_verbosity_level(verbose: int):\n \"\"\"Verbosity level setter.\n\n Args:\n verbose: Controls the verbosity: the higher, the more messages.\n <1 : messages are not displayed;\n >=1 : the computation process for layers is displayed;\n >=2 : the information about folds processing is also displayed;\n >=3 : the hyperparameters optimization process is also displayed;\n >=4 : the training process for every algorithm is displayed;\n\n \"\"\"\n level = verbosity_to_loglevel(verbose)\n set_stdout_level(level)\n\n logger.info(f\"Stdout logging level is {logging._levelToName[level]}.\")\n\n @staticmethod\n def set_logfile(filename: str): # noqa: D102\n add_filehandler(filename)\n"
] | [
[
"torch.cuda.device_count"
]
] |
neo-empresarial/covid-19 | [
"cef10ee79d955c9e84148c3c8da542788a1f7395"
] | [
"demos/prey-predator/prey_predator_sd/model/parts/lotka_volterra.py"
] | [
"import numpy as np\n\n## Policies\n\ndef p_reproduce_prey(params, substep, state_history, prev_state):\n born_population = prev_state['prey_population']\n born_population *= params['prey_reproduction_rate']\n born_population *= params['dt']\n return {'add_prey': born_population}\n\n\ndef p_reproduce_predators(params, substep, state_history, prev_state):\n born_population = prev_state['predator_population']\n born_population *= prev_state['prey_population'] \n born_population *= params['predator_interaction_factor']\n born_population *= params['dt']\n return {'add_predators': born_population}\n\n\ndef p_eliminate_prey(params, substep, state_history, prev_state):\n population = prev_state['prey_population']\n natural_elimination = population * params['prey_death_rate']\n \n interaction_elimination = population * prev_state['predator_population']\n interaction_elimination *= params['prey_interaction_factor']\n \n eliminated_population = natural_elimination + interaction_elimination\n eliminated_population *= params['dt']\n return {'add_prey': -1.0 * eliminated_population}\n\n\ndef p_eliminate_predators(params, substep, state_history, prev_state):\n population = prev_state['predator_population']\n eliminated_population = population * params['predator_death_rate']\n eliminated_population *= params['dt']\n return {'add_predators': -1.0 * eliminated_population}\n\n\n## SUFs\n\ndef s_prey_population(params, substep, state_history, prev_state, policy_input):\n updated_prey_population = np.ceil(prev_state['prey_population'] + policy_input['add_prey'])\n return ('prey_population', max(updated_prey_population, 0))\n\n\ndef s_predator_population(params, substep, state_history, prev_state, policy_input):\n updated_predator_population = np.ceil(prev_state['predator_population'] + policy_input['add_predators'])\n return ('predator_population', max(updated_predator_population, 0))"
] | [
[
"numpy.ceil"
]
] |
MacIver-Lab/Ergodic-Information-Harvesting | [
"6b06033852d511c682f1a38d84d6c3e0d735659b"
] | [
"SimulationCode/RunAllSims.py"
] | [
"from ErgodicHarvestingLib.SimulationMainQueue import SimulationMainQueue\nfrom datetime import datetime\nimport time\nimport warnings\nimport sys\nfrom multiprocessing import cpu_count\nfrom os import scandir\nimport numpy as np\n\n# Suppress all warnings\nnp.seterr(all=\"ignore\")\nwarnings.filterwarnings(\"ignore\")\n\nif __name__ == \"__main__\":\n # get number of parallel threads, EAFP way\n try:\n nThread = int(sys.argv[1])\n except BaseException:\n nThread = cpu_count() # default\n\n print(f\"using {nThread} threads\")\n timeStampStart0 = datetime.fromtimestamp(time.time())\n timeStampStart = datetime.fromtimestamp(time.time())\n params = []\n\n # load parameter files\n paramPath = \"./SimParameters/\"\n for f in scandir(paramPath):\n if f.is_file() and \".json\" in f.name:\n params.append(paramPath + f.name)\n # sort the file list so we have deterministic ordering\n params.sort()\n nSimJobs = len(params)\n print(f\"Submitting {nSimJobs} total simulation jobs...\")\n print(\"---------------------------------------------------------------\")\n SimulationMainQueue(params, nThread=nThread)\n\n timeStampEnd = datetime.fromtimestamp(time.time())\n timeString = timeStampEnd.strftime(\"%b-%d-%Y %T\")\n durationMinutes = (timeStampEnd - timeStampStart0).total_seconds() / 60.0\n print(\n \"All done! EOF at {0}, total time taken for all simulation(s) {1:.2f} minutes\".format(\n timeString, durationMinutes\n )\n )\n"
] | [
[
"numpy.seterr"
]
] |
wsh32/blurin8r | [
"ad251fccc2675a73c1ba5e83300440d21537503c"
] | [
"blurin8r/process.py"
] | [
"import cv2\nimport numpy as np\nfrom utils import *\n\n\ndef find_faces_haar(img, classifier_filename, scale_factor=1.3, min_neighbors=5, debug=False):\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n classifier = cv2.CascadeClassifier(classifier_filename)\n faces = classifier.detectMultiScale(gray, scale_factor, min_neighbors)\n return faces\n\n\ndef generate_yolo_net(cfg, weights, debug=False):\n net = cv2.dnn.readNetFromDarknet(cfg, weights)\n net.setPreferableBackend(cv2.dnn.DNN_BACKEND_OPENCV)\n net.setPreferableTarget(cv2.dnn.DNN_TARGET_CPU)\n return net\n\n\ndef find_faces_yolo(img, net, conf_threshold=CONF_THRESHOLD, nms_threshold=NMS_THRESHOLD):\n frame_height = img.shape[0]\n frame_width = img.shape[1]\n\n # Create a 4D blob from a frame.\n blob = cv2.dnn.blobFromImage(img, 1 / 255, (IMG_WIDTH, IMG_HEIGHT),\n [0, 0, 0], 1, crop=False)\n\n # Sets the input to the network\n net.setInput(blob)\n\n # Runs the forward pass to get output of the output layers\n outs = net.forward(get_outputs_names(net))\n\n # filter by confidence and nms\n confidences = []\n boxes = []\n final_boxes = []\n for out in outs:\n for detection in out:\n scores = detection[5:]\n class_id = np.argmax(scores)\n confidence = scores[class_id]\n if confidence > conf_threshold:\n center_x = int(detection[0] * frame_width)\n center_y = int(detection[1] * frame_height)\n width = int(detection[2] * frame_width)\n height = int(detection[3] * frame_height)\n left = int(center_x - width / 2)\n top = int(center_y - height / 2)\n confidences.append(float(confidence))\n boxes.append([left, top, width, height])\n\n # Perform non maximum suppression to eliminate redundant\n # overlapping boxes with lower confidences.\n indices = cv2.dnn.NMSBoxes(boxes, confidences, conf_threshold, nms_threshold)\n\n for i in indices:\n i = i[0]\n box = boxes[i]\n left = box[0]\n top = box[1]\n width = box[2]\n height = box[3]\n final_boxes.append(box)\n left, top, right, bottom = refined_box(left, top, width, height)\n\n return final_boxes\n\n\ndef blur_faces(img, faces, blur_value=50, max_area=None, blur_size=1, debug=False):\n blur = cv2.blur(img, (blur_value, blur_value))\n\n mask = np.zeros((np.size(img, 0), np.size(img, 1), np.size(img, 2)), dtype=np.uint8)\n for (x, y, w, h) in faces:\n if max_area is not None and max_area > 0:\n if (w * h) > max_area * np.size(img, 0) * np.size(img, 1):\n continue\n\n center_x = x + w/2\n center_y = y + h/2\n\n scaled_w = w * blur_size\n scaled_h = h * blur_size\n\n x1 = center_x - scaled_w / 2\n x2 = center_x + scaled_w / 2\n\n y1 = center_y - scaled_h / 2\n y2 = center_y + scaled_h / 2\n\n mask = cv2.rectangle(mask, (int(x1), int(y1)), (int(x2), int(y2)), (255, 255, 255), -1)\n\n out = np.where(mask==(255, 255, 255), blur, img)\n if debug:\n cv2.imshow('out', out)\n cv2.waitKey()\n return out\n\n"
] | [
[
"numpy.size",
"numpy.argmax",
"numpy.where"
]
] |
ConsVin/hls4ml | [
"4cea8ae0845b26a9b9c9295e9178ca457e897da9"
] | [
"hls4ml/model/profiling.py"
] | [
"from hls4ml.model.hls_model import HLSModel\nfrom hls4ml.model.hls_layers import IntegerPrecisionType, FixedPrecisionType\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas\nimport seaborn as sb\n\nfrom hls4ml.model.hls_model import HLSModel\n\ntry:\n from tensorflow import keras\n import qkeras\n __tf_profiling_enabled__ = True\nexcept ImportError:\n __tf_profiling_enabled__ = False\n\ntry:\n import torch\n __torch_profiling_enabled__ = True\nexcept ImportError:\n __torch_profiling_enabled__ = False\n\n\ndef array_to_summary(x, fmt='boxplot'):\n if fmt == 'boxplot':\n y = {'med' : np.median(x),\n 'q1' : np.percentile(x, 25),\n 'q3' : np.percentile(x, 75),\n 'whislo' : min(x),\n 'whishi' : max(x)\n }\n elif fmt == 'histogram':\n # Power of 2 bins covering data range\n high = np.ceil(np.log2(max(x))) + 1\n low = np.floor(np.log2(min(x))) - 1\n bits = np.arange(low, high, 1)\n bins = 2 ** bits\n h, b = np.histogram(x, bins=bins)\n h = h * 1. / float(sum(h)) # normalize\n y = {'h' : h,\n 'b' : np.log2(b)}\n return y\n\ndef boxplot(data, fmt='longform'):\n if fmt == 'longform':\n f = plt.figure() #figsize=(3, 3))\n hue = 'layer' if 'layer' in data.keys() else None\n vp = sb.boxplot(x='x', y='weight', hue=hue, data=data[data['x'] > 0], showfliers=False)\n vp.set_yticklabels(vp.get_yticklabels(), rotation=45, ha='right')\n if hue is not None:\n vp.get_legend().remove()\n vp.set_xscale('log', base=2)\n return f\n elif fmt == 'summary':\n from matplotlib.patches import Rectangle\n medianprops = dict(linestyle='-', color='k')\n f, ax = plt.subplots(1, 1)\n data.reverse()\n colors = sb.color_palette(\"Blues\", len(data))\n bp = ax.bxp(data, showfliers=False, vert=False, medianprops=medianprops)\n # add colored boxes\n for line, color in zip(bp['boxes'], colors):\n x = line.get_xdata()\n xl, xh = min(x), max(x)\n y = line.get_ydata()\n yl, yh = min(y), max(y)\n rect = Rectangle((xl, yl), (xh-xl), (yh-yl), fill=True, color=color)\n ax.add_patch(rect)\n ax.set_yticklabels([d['weight'] for d in data])\n ax.set_xscale('log', base=2)\n plt.xlabel('x')\n return f\n else:\n return None\n\ndef histogram(data, fmt='longform'):\n f = plt.figure()\n from matplotlib.ticker import MaxNLocator\n n = len(data) if fmt == 'summary' else len(data['weight'].unique())\n colors = sb.color_palette(\"husl\", n)\n if fmt == 'longform':\n for i, weight in enumerate(data['weight'].unique()):\n y = array_to_summary(data[data['weight'] == weight]['x'], fmt='histogram')\n plt.bar(y['b'][:-1], y['h'], width=1, fill=False, label=weight, edgecolor=colors[i])\n elif fmt == 'summary':\n for i, weight in enumerate(data):\n plt.bar(weight['b'][:-1], weight['h'], width=1, fill=False, label=weight['weight'], edgecolor=colors[i])\n\n plt.gca().xaxis.set_major_locator(MaxNLocator(integer=True))\n plt.xlabel('log2(x)')\n plt.ylabel('frequency')\n plt.legend()\n return f\n\nplots = {'boxplot' : boxplot,\n 'histogram' : histogram}\n\ndef types_boxplot(data, fmt='longform'):\n from matplotlib.patches import PathPatch\n from matplotlib.patches import Rectangle\n ax = plt.gca()\n f = plt.gcf()\n # Scale the data\n data['low'] = 2.**data['low']\n data['high'] = 2.**data['high']\n\n # Plot the custom precisions\n ticks = np.array([tick.get_text() for tick in plt.yticks()[1]])\n # Get the coordinates of the boxes to place the markers\n if fmt == 'longform':\n # seaborn adjusts the box positions slightly in groups\n boxes = [c.get_extents().inverse_transformed(ax.transData) for c in ax.get_children() if isinstance(c, PathPatch)]\n ys = [(box.y0 + box.y1) / 2 for box in boxes]\n ys = [(y, y) for y in ys]\n elif fmt == 'summary':\n ys = [(y, y) for y in plt.yticks()[0]]\n for irow, row in data[data['layer'] != 'model'].iterrows():\n if row['layer'] in ticks:\n iy = np.argwhere(ticks == row['layer'])[0][0] # Determine which layer in the plot\n rectangle = Rectangle((row['low'], ys[iy][0]-0.4), row['high']-row['low'], 0.8, fill=True, color='grey', alpha=0.2)\n ax.add_patch(rectangle)\n\ndef types_histogram(data, fmt='longform'):\n ax = plt.gca()\n layers = np.array(ax.get_legend_handles_labels()[1])\n colors = sb.color_palette(\"husl\", len(layers))\n ylim = ax.get_ylim()\n for irow, row in data[data['layer'] != 'model'].iterrows():\n if row['layer'] in layers:\n col = colors[np.argwhere(layers == row['layer'])[0][0]]\n plt.plot((row['low'], row['low']), ylim, '--', color=col)\n plt.plot((row['high'], row['high']), ylim, '--', color=col)\n\ntypes_plots = {'boxplot' : types_boxplot,\n 'histogram' : types_histogram}\n\ndef ap_fixed_WIF(dtype):\n from hls4ml.templates.vivado_template import VivadoBackend\n dtype = VivadoBackend.convert_precision_string(None, dtype) \n W, I, F = dtype.width, dtype.integer, dtype.fractional\n return W, I, F\n\ndef types_hlsmodel(model):\n suffix = ['w', 'b']\n data = {'layer' : [], 'low' : [], 'high' : []}\n # Plot the default precision\n default_precision = model.config.model_precision['default']\n # assumes ap_fixed\n W, I, F = ap_fixed_WIF(default_precision)\n data['layer'].append('model')\n data['low'].append(-F)\n data['high'].append(I-1)\n\n for layer in model.get_layers():\n for iw, weight in enumerate(layer.get_weights()):\n wname = '{}/{}'.format(layer.name, suffix[iw])\n T = weight.type\n if T.name != 'model':\n W, I, F = ap_fixed_WIF(T.precision)\n data['layer'].append(wname)\n data['low'].append(-F)\n data['high'].append(I-1)\n data = pandas.DataFrame(data)\n return data\n\ndef activation_types_hlsmodel(model):\n data = {'layer' : [], 'low' : [], 'high' : []}\n # Get the default precision\n default_precision = model.config.model_precision['default']\n W, I, F = ap_fixed_WIF(default_precision)\n data['layer'].append('model')\n data['low'].append(-F)\n data['high'].append(I-1)\n for layer in model.get_layers():\n T = layer.get_output_variable().type.precision\n W, I, F = ap_fixed_WIF(T)\n data['layer'].append(layer.name)\n data['low'].append(-F)\n data['high'].append(I-1)\n data = pandas.DataFrame(data)\n return data\n\ndef weights_hlsmodel(model, fmt='longform', plot='boxplot'):\n suffix = ['w', 'b']\n if fmt == 'longform':\n data = {'x' : [], 'layer' : [], 'weight' : []}\n elif fmt == 'summary':\n data = []\n for layer in model.get_layers():\n name = layer.name\n for iw, weight in enumerate(layer.get_weights()):\n l = '{}/{}'.format(name, suffix[iw])\n w = weight.data.flatten()\n w = abs(w[w != 0])\n n = len(w)\n if n == 0:\n break\n if fmt == 'longform':\n data['x'].extend(w.tolist())\n data['layer'].extend([name for i in range(len(w))])\n data['weight'].extend([l for i in range(len(w))])\n elif fmt == 'summary':\n data.append(array_to_summary(w, fmt=plot))\n data[-1]['layer'] = name\n data[-1]['weight'] = l\n\n if fmt == 'longform':\n data = pandas.DataFrame(data)\n return data\n\ndef weights_keras(model, fmt='longform', plot='boxplot'):\n suffix = ['w', 'b']\n if fmt == 'longform':\n data = {'x' : [], 'layer' : [], 'weight' : []}\n elif fmt == 'summary':\n data = []\n for layer in model.layers:\n name = layer.name\n weights = layer.get_weights()\n for i, w in enumerate(weights):\n l = '{}/{}'.format(name, suffix[i])\n w = w.flatten()\n w = abs(w[w != 0])\n n = len(w)\n if n == 0:\n break\n if fmt == 'longform':\n data['x'].extend(w.tolist())\n data['layer'].extend([name for j in range(n)])\n data['weight'].extend([l for j in range(n)])\n elif fmt == 'summary':\n data.append(array_to_summary(w, fmt=plot))\n data[-1]['layer'] = name\n data[-1]['weight'] = l\n\n if fmt == 'longform':\n data = pandas.DataFrame(data)\n return data\n\ndef activations_keras(model, X, fmt='longform', plot='boxplot'):\n # test layer by layer on data\n if fmt == 'longform':\n # return long form pandas dataframe for\n # seaborn boxplot\n data = {'x' : [], 'weight' : []}\n elif fmt == 'summary':\n # return summary statistics for matplotlib.axes.Axes.bxp\n # or histogram bin edges and heights\n data = []\n\n for layer in model.layers:\n print(\" {}\".format(layer.name))\n if not isinstance(layer, keras.layers.InputLayer):\n y = _get_output(layer, X, model.input).flatten()\n y = abs(y[y != 0])\n if fmt == 'longform':\n data['x'].extend(y.tolist())\n data['weight'].extend([layer.name for i in range(len(y))])\n elif fmt == 'summary':\n data.append(array_to_summary(y, fmt=plot))\n data[-1]['weight'] = layer.name\n\n if fmt == 'longform':\n data = pandas.DataFrame(data)\n return data\n\n\ndef weights_torch(model, fmt='longform', plot='boxplot'):\n suffix = ['w', 'b']\n if fmt == 'longform':\n data = {'x': [], 'layer': [], 'weight': []}\n elif fmt == 'summary':\n data = []\n for layer in model.children():\n if isinstance(layer, torch.nn.Linear):\n name = layer.__class__.__name__\n weights = list(layer.parameters())\n for i, w in enumerate(weights):\n l = '{}/{}'.format(name, suffix[i])\n w = weights[i].detach().numpy()\n w = w.flatten()\n w = abs(w[w != 0])\n n = len(w)\n if n == 0:\n break\n if fmt == 'longform':\n data['x'].extend(w.tolist())\n data['layer'].extend([name for _ in range(n)])\n data['weight'].extend([l for _ in range(n)])\n elif fmt == 'summary':\n data.append(array_to_summary(w, fmt=plot))\n data[-1]['layer'] = name\n data[-1]['weight'] = l\n\n if fmt == 'longform':\n data = pandas.DataFrame(data)\n return data\n\n\ndef activations_torch(model, X, fmt='longform', plot='boxplot'):\n X = torch.Tensor(X)\n if fmt == 'longform':\n data = {'x': [], 'weight': []}\n elif fmt == 'summary':\n data = []\n\n partial_model = torch.nn.Sequential\n layers = []\n for layer in model.children():\n lname = layer.__class__.__name__\n layers.append(layer)\n pm = partial_model(*layers)\n print(\" {}\".format(lname))\n y = pm(X).flatten().detach().numpy()\n y = abs(y[y != 0])\n if fmt == 'longform':\n data['x'].extend(y.tolist())\n data['weight'].extend([lname for _ in range(len(y))])\n elif fmt == 'summary':\n data.append(array_to_summary(y, fmt=plot))\n data[-1]['weight'] = lname\n\n if fmt == 'longform':\n data = pandas.DataFrame(data)\n return data\n\n\ndef numerical(model=None, hls_model=None, X=None, plot='boxplot'):\n \"\"\"\n Perform numerical profiling of a model\n\n Parameters\n ----------\n model : keras or pytorch model\n The model to profile\n hls_model : HLSModel\n The HLSModel to profile\n X : array-like, optional\n Test data on which to evaluate the model to profile activations\n Must be formatted suitably for the model.predict(X) method\n plot : str, optional\n The type of plot to produce.\n Options are: 'boxplot' (default), 'violinplot', 'histogram',\n 'FacetGrid'\n\n Returns\n -------\n tuple\n The pair of produced figures. First weights and biases,\n then activations\n \"\"\"\n wp, ap = None, None\n\n print(\"Profiling weights\")\n data = None\n if hls_model is not None and isinstance(hls_model, HLSModel):\n data = weights_hlsmodel(hls_model, fmt='summary', plot=plot)\n elif model is not None:\n if __tf_profiling_enabled__ and isinstance(model, keras.Model):\n data = weights_keras(model, fmt='summary', plot=plot)\n elif __torch_profiling_enabled__ and \\\n isinstance(model, torch.nn.Sequential):\n data = weights_torch(model, fmt='summary', plot=plot)\n if data is None:\n print(\"Only keras, PyTorch (Sequential) and HLSModel models \" +\n \"can currently be profiled\")\n return wp, ap\n\n wp = plots[plot](data, fmt='summary') # weight plot\n if isinstance(hls_model, HLSModel) and plot in types_plots:\n t_data = types_hlsmodel(hls_model)\n types_plots[plot](t_data, fmt='summary')\n\n plt.title(\"Distribution of (non-zero) weights\")\n plt.tight_layout()\n\n print(\"Profiling activations\")\n data = None\n if X is not None:\n if __tf_profiling_enabled__ and isinstance(model, keras.Model):\n data = activations_keras(model, X, fmt='summary', plot=plot)\n elif __torch_profiling_enabled__ and \\\n isinstance(model, torch.nn.Sequential):\n data = activations_torch(model, X, fmt='summary', plot=plot)\n if data is not None:\n ap = plots[plot](data, fmt='summary') # activation plot\n plt.title(\"Distribution of (non-zero) activations\")\n plt.tight_layout()\n\n if X is not None and isinstance(hls_model, HLSModel):\n t_data = activation_types_hlsmodel(hls_model)\n types_plots[plot](t_data, fmt='summary')\n\n return wp, ap\n\n\n########COMPARE OUTPUT IMPLEMENTATION########\ndef _is_ignored_layer(layer):\n \"\"\"Some layers need to be ingored during inference\"\"\"\n if isinstance(layer, (keras.layers.InputLayer,\n keras.layers.Dropout)):\n return True\n return False\n\ndef _get_output(layer, X, model_input):\n \"\"\"Get output of partial model\"\"\"\n partial_model = keras.models.Model(inputs=model_input,\n outputs=layer.output)\n y = partial_model.predict(X)\n return y\n\ndef get_ymodel_keras(keras_model, X):\n \"\"\"\n Calculate each layer's ouput and put them into a dictionary\n Params:\n ------\n keras_model: a keras model\n X : array-like\n Test data on which to evaluate the model to profile activations\n Must be formatted suitably for the model.predict(X) method\n Return:\n ------\n A dictionary in the form {\"layer_name\": ouput array of layer}\n \"\"\"\n \n ymodel = {}\n \n for layer in keras_model.layers:\n print(\"Processing {} in Keras model...\".format(layer.name))\n if not _is_ignored_layer(layer):\n #If the layer has activation integrated then separate them\n #Note that if the layer is a standalone activation layer then skip this\n if hasattr(layer, 'activation') and not (isinstance(layer,keras.layers.Activation) or isinstance(layer, qkeras.qlayers.QActivation)):\n if layer.activation:\n \n if layer.activation.__class__.__name__ == \"linear\":\n ymodel[layer.name] = _get_output(layer, X, keras_model.input)\n \n else:\n temp_activation = layer.activation\n layer.activation = None\n #Get output for layer without activation\n ymodel[layer.name] = _get_output(layer, X, keras_model.input)\n\n #Add the activation back \n layer.activation = temp_activation\n #Get ouput for activation\n ymodel[layer.name + \"_{}\".format(temp_activation.__class__.__name__)] = _get_output(layer, X, keras_model.input)\n else:\n ymodel[layer.name] = _get_output(layer, X, keras_model.input)\n else: \n ymodel[layer.name] = _get_output(layer, X, keras_model.input)\n print(\"Done taking outputs for Keras model.\")\n return ymodel\n\ndef _norm_diff(ymodel, ysim):\n \"\"\"Calculate the square root of the sum of the squares of the differences\"\"\"\n diff = {}\n \n for key in list(ysim.keys()):\n diff[key] = np.linalg.norm(ysim[key]-ymodel[key])\n \n #---Bar Plot---\n f, ax = plt.subplots()\n plt.bar(list(diff.keys()),list(diff.values()))\n plt.title(\"layer-by-layer output differences\")\n ax.set_ylabel('Norm of difference vector')\n plt.xticks(rotation=90)\n plt.tight_layout()\n return f\n\ndef _dist_diff(ymodel, ysim):\n \"\"\"\n Calculate the normalized distribution of the differences of the elements\n of the output vectors. \n If difference >= original value then the normalized difference will be set to 1,\n meaning \"very difference\".\n If difference < original value then the normalized difference would be difference/original.\n \"\"\"\n\n diff = {}\n\n for key in list(ysim.keys()):\n flattened_ysim = ysim[key].flatten()\n flattened_ymodel = np.array(ymodel[key]).flatten()\n\n diff[key] = np.absolute(flattened_ymodel - flattened_ysim) / np.linalg.norm(flattened_ymodel - flattened_ysim)\n diff_vector = np.absolute(flattened_ymodel - flattened_ysim)\n abs_ymodel = np.absolute(flattened_ymodel)\n\n normalized_diff = np.zeros(diff_vector.shape)\n normalized_diff[(diff_vector >= abs_ymodel) & (abs_ymodel>0) & (diff_vector>0)] = 1\n\n #Fill out the rest\n index = diff_vector < abs_ymodel\n normalized_diff[index] = diff_vector[index] / abs_ymodel[index]\n\n diff[key] = normalized_diff\n\n #---Box Plot---\n f, ax = plt.subplots()\n pos = np.array(range(len(list(diff.values())))) + 1 \n ax.boxplot(list(diff.values()), sym='k+', positions=pos)\n\n #--formatting\n plt.title(\"Layer-by-layer distribution of output differences\")\n ax.set_xticklabels(list(diff.keys()))\n ax.set_ylabel('Normalized difference')\n ax.set_ylabel('Percent difference.')\n plt.xticks(rotation=90)\n plt.tight_layout()\n\n return f\n\ndef compare(keras_model, hls_model, X, plot_type = \"dist_diff\"):\n \"\"\"\n Compare each layer's output in keras and hls model. Note that the hls_model should not be compiled before using this.\n Params:\n ------\n keras_model : original keras model\n hls_model : converted HLS model, with \"Trace:True\" in the configuration file.\n X: numpy array, input for the model. \n plot_type : (string) different methods to visualize the y_model and y_sim differences.\n Possible options include:\n - \"norm_diff\" : square root of the sum of the squares of the differences \n between each output vectors \n - \"dist_diff\" : The normalized distribution of the differences of the elements\n between two output vectors\n \n Return:\n ------\n plot object of the histogram depicting the difference in each layer's ouput\n \"\"\"\n \n #Take in output from both models\n #Note that each y is a dictionary with structure {\"layer_name\": flattened ouput array}\n ymodel = get_ymodel_keras(keras_model, X)\n _, ysim = hls_model.trace(X)\n \n print(\"Plotting difference...\")\n f = plt.figure()\n if plot_type == \"norm_diff\":\n f = _norm_diff(ymodel, ysim)\n elif plot_type == \"dist_diff\":\n f = _dist_diff(ymodel, ysim)\n\n return f\n"
] | [
[
"matplotlib.pyplot.legend",
"pandas.DataFrame",
"matplotlib.pyplot.plot",
"numpy.histogram",
"matplotlib.pyplot.gca",
"matplotlib.pyplot.tight_layout",
"numpy.arange",
"matplotlib.pyplot.gcf",
"numpy.zeros",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.title",
"tensorflow.keras.models.Model",
"numpy.median",
"matplotlib.patches.Rectangle",
"numpy.array",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.yticks",
"numpy.absolute",
"numpy.log2",
"torch.Tensor",
"matplotlib.pyplot.subplots",
"numpy.linalg.norm",
"numpy.percentile",
"numpy.argwhere",
"matplotlib.ticker.MaxNLocator",
"matplotlib.pyplot.bar",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.xticks"
]
] |
weiliuxm/Dassl.pytorch | [
"8084b66332623c7a2394ea1404f2d043ef415ebb"
] | [
"dassl/engine/ssl/entmin.py"
] | [
"import torch\nfrom torch.nn import functional as F\n\nfrom dassl.engine import TRAINER_REGISTRY, TrainerXU\nfrom dassl.metrics import compute_accuracy\n\n\n@TRAINER_REGISTRY.register()\nclass EntMin(TrainerXU):\n \"\"\"Entropy Minimization.\n\n http://papers.nips.cc/paper/2740-semi-supervised-learning-by-entropy-minimization.pdf.\n \"\"\"\n\n def __init__(self, cfg):\n super().__init__(cfg)\n self.lmda = cfg.TRAINER.ENTMIN.LMDA\n\n def forward_backward(self, batch_x, batch_u):\n input_x, label_x, input_u = self.parse_batch_train(batch_x, batch_u)\n\n output_x = self.model(input_x)\n loss_x = F.cross_entropy(output_x, label_x)\n\n output_u = F.softmax(self.model(input_u), 1)\n loss_u = (-output_u * torch.log(output_u + 1e-5)).sum(1).mean()\n\n loss = loss_x + loss_u * self.lmda\n\n self.model_backward_and_update(loss)\n\n loss_summary = {\n 'loss_x': loss_x.item(),\n 'acc_x': compute_accuracy(output_x, label_x)[0].item(),\n 'loss_u': loss_u.item()\n }\n\n if (self.batch_idx + 1) == self.num_batches:\n self.update_lr()\n\n return loss_summary\n"
] | [
[
"torch.nn.functional.cross_entropy",
"torch.log"
]
] |
WCMetrics/SurveyAnalysis | [
"38e387cab749c613e5f6ecc4765186ba6939233c"
] | [
"delphi-analysis.py"
] | [
"from google_auth_oauthlib import flow\nfrom google.oauth2.credentials import Credentials\nimport gspread\nimport numpy as np\nfrom sklearn.decomposition import PCA\nimport matplotlib.pyplot as plt\n\ndef getUserCredetials():\n appflow = flow.InstalledAppFlow.from_client_secrets_file(\n '/Users/almo/Development/credentials/wcmetrics.json',\n scopes=['https://www.googleapis.com/auth/spreadsheets.readonly', 'https://www.googleapis.com/auth/drive.readonly'])\n\n appflow.run_local_server()\n\n credentials = appflow.credentials\n\n f = open(\"wcmetrics_user.json\",'x')\n f.write(credentials.to_json())\n f.close()\n\n return credentials\n\ndef evaluateAgreement(a):\n agree = 0.0\n for i in a:\n if i > 3:\n agree+=1\n return agree/len(a)\n\ndef evaluateDisagreement(a):\n agree = 0.0 \n for i in a:\n if i < 3:\n agree+=1\n return agree/len(a)\n\ntry:\n credentials = Credentials.from_authorized_user_file(\"wcmetrics_user.json\")\nexcept FileNotFoundError:\n credentials= getUserCredetials()\n\ngc = gspread.authorize(credentials)\n\nworksheet = gc.open('Analisis de Calidad de Componentes Web (respuestas)').worksheet('Results Round #2')\n\n# get_all_values gives a list of rows.\nanswers= np.array(worksheet.get('D2:AV21'),int)\nmetrics = np.transpose(answers)\n\n# Statistics\nanswers_mean = np.mean(answers,axis=0)\nanswers_median = np.median(answers,axis=0)\nanswers_std = np.std(answers,axis=0)\n\nanswers_agree = np.apply_along_axis(evaluateAgreement,0,answers)\nanswers_disagree = np.apply_along_axis(evaluateDisagreement,0,answers)\n\n## Saving Data for R Scripts\nnp.save(\"answers.npy\",answers)\nnp.save(\"metrics.npy\",metrics)\nnp.save(\"answers_mean.npy\",answers_mean)\nnp.save(\"answers_median.npy\",answers_median)\nnp.save(\"answers_std.npy\",answers_std)\nnp.save(\"answers_agree.npy\",answers_agree)\nnp.save(\"answers_disagree.npy\",answers_disagree)\n\nbaseline=0\nsize_plots, ax1 = plt.subplots()\nax1.set_title('Code Size Product Quality Coverage')\nax1.boxplot([metrics[baseline+0],metrics[baseline+1],metrics[baseline+2],metrics[baseline+3],metrics[baseline+4],metrics[baseline+5],metrics[baseline+6],metrics[baseline+7]], \n labels=[\"Q1\",\"Q2\",\"Q3\",\"Q4\",\"Q5\",\"Q6\",\"Q7\",\"Q8\"])\n\nplt.show()\n\nbaseline=8\nstructure_plots, ax2 = plt.subplots()\nax2.set_title('Code Structure Product Quality Coverage')\nax2.boxplot([metrics[baseline+0],metrics[baseline+1],metrics[baseline+2],metrics[baseline+3],metrics[baseline+4],metrics[baseline+5],metrics[baseline+6],metrics[baseline+7]],\n labels=[\"Q9\",\"Q10\",\"Q11\",\"Q12\",\"Q13\",\"Q14\",\"Q15\",\"Q16\"])\n\nplt.show()\n\nbaseline=16\ndependencies_plots, ax3 = plt.subplots()\nax3.set_title('Number of Dependencies Product Quality Coverage')\nax3.boxplot([metrics[baseline+0],metrics[baseline+1],metrics[baseline+2],metrics[baseline+3],metrics[baseline+4],metrics[baseline+5],metrics[baseline+6],metrics[baseline+7]],\n labels=[\"Q17\",\"Q18\",\"Q19\",\"Q20\",\"Q21\",\"Q22\",\"Q23\",\"Q24\"])\n\nplt.show()\n\nbaseline=24\ncompleteness_plots, ax4 = plt.subplots()\nax4.set_title('Completeness Quality in Use Coverage')\nax4.boxplot([metrics[baseline+0],metrics[baseline+1],metrics[baseline+2],metrics[baseline+3],metrics[baseline+4],metrics[baseline+5],metrics[baseline+6]],\n labels=[\"Q25\",\"Q26\",\"Q27\",\"Q28\",\"Q29\",\"Q30\",\"Q31\"])\n\nplt.show()\n\nbaseline=31\nlatency_plots, ax5 = plt.subplots()\nax5.set_title('Latency Quality in Use Coverage')\nax5.boxplot([metrics[baseline+0],metrics[baseline+1],metrics[baseline+2],metrics[baseline+3],metrics[baseline+4],metrics[baseline+5],metrics[baseline+6]],\n labels=[\"Q32\",\"Q33\",\"Q34\",\"Q35\",\"Q36\",\"Q37\",\"Q38\"])\n\nplt.show()\n\nbaseline=38\nconsistency_plots, ax6 = plt.subplots()\nax6.set_title('Consistency Quality in Use Coverage')\nax6.boxplot([metrics[baseline+0],metrics[baseline+1],metrics[baseline+2],metrics[baseline+3],metrics[baseline+4],metrics[baseline+5],metrics[baseline+6]],\n labels=[\"Q39\",\"Q40\",\"Q41\",\"Q42\",\"Q43\",\"Q44\",\"Q45\"])\n\nplt.show()"
] | [
[
"numpy.median",
"matplotlib.pyplot.subplots",
"numpy.save",
"numpy.std",
"numpy.apply_along_axis",
"numpy.mean",
"numpy.transpose",
"matplotlib.pyplot.show"
]
] |
MingSun-Tse/EECE7311_Project_NST | [
"78f918771a6d725bfeac1af10af8d913508ac6f2"
] | [
"utils.py"
] | [
"import torch\nimport torch.nn as nn\nimport torch.nn.init as init\nfrom torch.utils.data import Dataset\nimport torch.nn.functional as F\nimport torchvision\nfrom torch.autograd import Variable\nfrom pprint import pprint\nimport time, math, os, sys, copy, numpy as np, shutil as sh\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\nfrom collections import OrderedDict\nimport glob\nfrom PIL import Image\nimport json, yaml\n\ndef _weights_init(m):\n if isinstance(m, nn.Linear) or isinstance(m, nn.Conv2d):\n init.kaiming_normal(m.weight)\n if m.bias is not None:\n m.bias.data.fill_(0)\n elif isinstance(m, nn.BatchNorm2d):\n if m.weight is not None:\n m.weight.data.fill_(1.0)\n m.bias.data.zero_()\n\n# refer to: https://github.com/Eric-mingjie/rethinking-network-pruning/blob/master/imagenet/l1-norm-pruning/compute_flops.py\ndef get_n_params(model):\n total = sum([param.nelement() if param.requires_grad else 0 for param in model.parameters()])\n total /= 1e6\n return total\n\n# The above 'get_n_params' requires 'param.requires_grad' to be true. In KD, for the teacher, this is not the case.\ndef get_n_params_(model):\n n_params = 0\n for _, module in model.named_modules():\n if isinstance(module, nn.Conv2d) or isinstance(module, nn.Linear): # only consider Conv2d and Linear, no BN\n n_params += module.weight.numel()\n if hasattr(module, 'bias') and type(module.bias) != type(None):\n n_params += module.bias.numel()\n return n_params\n\ndef get_n_flops(model=None, input_res=224, multiply_adds=True, n_channel=3):\n model = copy.deepcopy(model)\n\n prods = {}\n def save_hook(name):\n def hook_per(self, input, output):\n prods[name] = np.prod(input[0].shape)\n return hook_per\n\n list_1=[]\n def simple_hook(self, input, output):\n list_1.append(np.prod(input[0].shape))\n list_2={}\n def simple_hook2(self, input, output):\n list_2['names'] = np.prod(input[0].shape)\n\n\n list_conv=[]\n def conv_hook(self, input, output):\n batch_size, input_channels, input_height, input_width = input[0].size()\n output_channels, output_height, output_width = output[0].size()\n\n kernel_ops = self.kernel_size[0] * self.kernel_size[1] * (self.in_channels / self.groups)\n bias_ops = 0 if self.bias is not None else 0\n\n # params = output_channels * (kernel_ops + bias_ops) # @mst: commented since not used\n # flops = (kernel_ops * (2 if multiply_adds else 1) + bias_ops) * output_channels * output_height * output_width * batch_size\n\n num_weight_params = (self.weight.data != 0).float().sum() # @mst: this should be considering the pruned model\n # could be problematic if some weights happen to be 0.\n flops = (num_weight_params * (2 if multiply_adds else 1) + bias_ops * output_channels) * output_height * output_width * batch_size\n\n list_conv.append(flops)\n\n list_linear=[]\n def linear_hook(self, input, output):\n batch_size = input[0].size(0) if input[0].dim() == 2 else 1\n\n weight_ops = self.weight.nelement() * (2 if multiply_adds else 1)\n bias_ops = self.bias.nelement()\n\n flops = batch_size * (weight_ops + bias_ops)\n list_linear.append(flops)\n\n list_bn=[]\n def bn_hook(self, input, output):\n list_bn.append(input[0].nelement() * 2)\n\n list_relu=[]\n def relu_hook(self, input, output):\n list_relu.append(input[0].nelement())\n\n list_pooling=[]\n def pooling_hook(self, input, output):\n batch_size, input_channels, input_height, input_width = input[0].size()\n output_channels, output_height, output_width = output[0].size()\n\n kernel_ops = self.kernel_size * self.kernel_size\n bias_ops = 0\n params = 0\n flops = (kernel_ops + bias_ops) * output_channels * output_height * output_width * batch_size\n\n list_pooling.append(flops)\n\n list_upsample=[]\n\n # For bilinear upsample\n def upsample_hook(self, input, output):\n batch_size, input_channels, input_height, input_width = input[0].size()\n output_channels, output_height, output_width = output[0].size()\n\n flops = output_height * output_width * output_channels * batch_size * 12\n list_upsample.append(flops)\n\n def foo(net):\n childrens = list(net.children())\n if not childrens:\n if isinstance(net, torch.nn.Conv2d):\n net.register_forward_hook(conv_hook)\n if isinstance(net, torch.nn.Linear):\n net.register_forward_hook(linear_hook)\n if isinstance(net, torch.nn.BatchNorm2d):\n net.register_forward_hook(bn_hook)\n if isinstance(net, torch.nn.ReLU):\n net.register_forward_hook(relu_hook)\n if isinstance(net, torch.nn.MaxPool2d) or isinstance(net, torch.nn.AvgPool2d):\n net.register_forward_hook(pooling_hook)\n if isinstance(net, torch.nn.Upsample):\n net.register_forward_hook(upsample_hook)\n return\n for c in childrens:\n foo(c)\n\n if model == None:\n model = torchvision.models.alexnet()\n foo(model)\n input = Variable(torch.rand(n_channel,input_res,input_res).unsqueeze(0), requires_grad = True)\n out = model(input)\n\n\n total_flops = (sum(list_conv) + sum(list_linear)) # + sum(list_bn) + sum(list_relu) + sum(list_pooling) + sum(list_upsample))\n total_flops /= 1e9\n # print(' Number of FLOPs: %.2fG' % total_flops)\n\n return total_flops\n\n# The above version is redundant. Get a neat version as follow.\ndef get_n_flops_(model=None, img_size=224, n_channel=3, count_adds=True):\n '''Only count the FLOPs of conv and linear layers (no BN layers etc.). \n Only count the weight computation (bias not included since it is negligible)\n '''\n model = copy.deepcopy(model)\n list_conv = []\n def conv_hook(self, input, output):\n flops = np.prod(self.weight.data.shape) * output.size(2) * output.size(3) / self.groups\n list_conv.append(flops)\n\n list_linear = []\n def linear_hook(self, input, output):\n flops = np.prod(self.weight.data.shape)\n list_linear.append(flops)\n\n def register_hooks(net):\n childrens = list(net.children())\n if not childrens:\n if isinstance(net, torch.nn.Conv2d):\n net.register_forward_hook(conv_hook)\n if isinstance(net, torch.nn.Linear):\n net.register_forward_hook(linear_hook)\n return\n for c in childrens:\n register_hooks(c)\n\n register_hooks(model)\n input = Variable(torch.rand(1, n_channel, img_size, img_size))\n model(input)\n total_flops = (sum(list_conv) + sum(list_linear))\n if count_adds:\n total_flops *= 2\n return total_flops\n\n# refer to: https://github.com/alecwangcq/EigenDamage-Pytorch/blob/master/utils/common_utils.py\nclass PresetLRScheduler(object):\n \"\"\"Using a manually designed learning rate schedule rules.\n \"\"\"\n def __init__(self, decay_schedule):\n # decay_schedule is a dictionary\n # which is for specifying iteration -> lr\n self.decay_schedule = {}\n for k, v in decay_schedule.items(): # a dict, example: {\"0\":0.001, \"30\":0.00001, \"45\":0.000001}\n self.decay_schedule[int(k)] = v\n print('Using a preset learning rate schedule:')\n print(self.decay_schedule)\n\n def __call__(self, optimizer, e):\n epochs = list(self.decay_schedule.keys())\n epochs = sorted(epochs) # example: [0, 30, 45]\n lr = self.decay_schedule[epochs[-1]]\n for i in range(len(epochs) - 1):\n if epochs[i] <= e < epochs[i+1]:\n lr = self.decay_schedule[epochs[i]]\n break\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr\n return lr\n\ndef get_lr(optimizer):\n for param_group in optimizer.param_groups:\n lr = param_group['lr']\n return lr\n\ndef plot_weights_heatmap(weights, out_path):\n '''\n weights: [N, C, H, W]. Torch tensor\n averaged in dim H, W so that we get a 2-dim color map of size [N, C]\n '''\n w_abs = weights.abs()\n w_abs = w_abs.data.cpu().numpy()\n \n fig, ax = plt.subplots()\n im = ax.imshow(w_abs, cmap='jet')\n\n # make a beautiful colorbar \n divider = make_axes_locatable(ax)\n cax = divider.append_axes('right', size=0.05, pad=0.05)\n fig.colorbar(im, cax=cax, orientation='vertical')\n\n ax.set_xlabel(\"Channel\")\n ax.set_ylabel(\"Filter\")\n fig.savefig(out_path, dpi=200)\n plt.close(fig)\n\ndef strlist_to_list(sstr, ttype):\n '''\n example:\n # self.args.stage_pr = [0, 0.3, 0.3, 0.3, 0, ]\n # self.args.skip_layers = ['1.0', '2.0', '2.3', '3.0', '3.5', ]\n turn these into a list of <ttype> (float or str or int etc.)\n '''\n if not sstr:\n return sstr\n out = []\n if '[' in sstr:\n sstr = sstr.split(\"[\")[1].split(\"]\")[0]\n else:\n sstr = sstr.strip()\n for x in sstr.split(','):\n x = x.strip()\n if x:\n x = ttype(x)\n out.append(x)\n return out\n\ndef strdict_to_dict(sstr, ttype):\n '''\n '{\"1\": 0.04, \"2\": 0.04, \"4\": 0.03, \"5\": 0.02, \"7\": 0.03, }'\n '''\n if not sstr:\n return sstr\n out = {}\n if '{' in sstr:\n sstr = sstr.split(\"{\")[1].split(\"}\")[0]\n else:\n sstr = sstr.strip()\n for x in sstr.split(','):\n x = x.strip()\n if x:\n k = x.split(':')[0]\n v = ttype(x.split(':')[1].strip())\n out[k] = v\n return out\n \ndef check_path(x):\n if x:\n complete_path = glob.glob(x)\n assert(len(complete_path) == 1)\n x = complete_path[0]\n return x\n\ndef parse_prune_ratio_vgg(sstr):\n # example: [0-4:0.5, 5:0.6, 8-10:0.2]\n out = np.zeros(20) # at most 20 layers, could be problematic but enough for vgg-like cases\n sstr = sstr.split(\"[\")[1].split(\"]\")[0]\n for x in sstr.split(','):\n k = x.split(\":\")[0].strip()\n v = x.split(\":\")[1].strip()\n if k.isdigit():\n out[int(k)] = float(v)\n else:\n begin = int(k.split('-')[0].strip())\n end = int(k.split('-')[1].strip())\n out[begin : end+1] = float(v)\n return list(out)\n\n\ndef kronecker(A, B):\n return torch.einsum(\"ab,cd->acbd\", A, B).view(A.size(0) * B.size(0), A.size(1) * B.size(1))\n \n \ndef np_to_torch(x):\n '''\n np array to pytorch float tensor\n '''\n x = np.array(x)\n x= torch.from_numpy(x).float()\n return x\n\ndef kd_loss(student_scores, teacher_scores, temp=1):\n '''Knowledge distillation loss: soft target\n '''\n p = F.log_softmax(student_scores / temp, dim=1)\n q = F.softmax(teacher_scores / temp, dim=1)\n # l_kl = F.kl_div(p, q, size_average=False) / student_scores.shape[0] # previous working loss\n l_kl = F.kl_div(p, q, reduction='batchmean') # 2020-06-21 @mingsun-tse: Since 'size_average' is deprecated, \\\n # use 'reduction' instead. In probation.\n return l_kl\n\ndef test(net, test_loader):\n n_example_test = 0\n total_correct = 0\n avg_loss = 0\n is_train = net.training\n net.eval()\n with torch.no_grad():\n pred_total = []\n label_total = []\n for _, (images, labels) in enumerate(test_loader):\n n_example_test += images.size(0)\n images = images.cuda()\n labels = labels.cuda()\n output = net(images)\n avg_loss += nn.CrossEntropyLoss()(output, labels).sum()\n pred = output.data.max(1)[1]\n total_correct += pred.eq(labels.data.view_as(pred)).sum()\n pred_total.extend(list(pred.data.cpu().numpy()))\n label_total.extend(list(labels.data.cpu().numpy()))\n \n acc = float(total_correct) / n_example_test\n avg_loss /= n_example_test\n\n # get accuracy per class\n n_class = output.size(1)\n acc_test = [0] * n_class\n cnt_test = [0] * n_class\n for p, l in zip(pred_total, label_total):\n acc_test[l] += int(p == l)\n cnt_test[l] += 1\n acc_per_class = []\n for c in range(n_class):\n acc_test[c] = 0 if cnt_test[c] == 0 else acc_test[c] / float(cnt_test[c])\n acc_per_class.append(acc_test[c])\n \n # return to the train state if necessary\n if is_train:\n net.train() \n return acc, avg_loss.item(), acc_per_class\n\ndef get_project_path(ExpID):\n full_path = glob.glob(\"Experiments/*%s*\" % ExpID)\n assert(len(full_path) == 1) # There should be only ONE folder with <ExpID> in its name.\n return full_path[0]\n\ndef parse_ExpID(path):\n '''parse out the ExpID from 'path', which can be a file or directory.\n Example: Experiments/AE__ckpt_epoch_240.pth__LR1.5__originallabel__vgg13_SERVER138-20200829-202307/gen_img\n Example: Experiments/AE__ckpt_epoch_240.pth__LR1.5__originallabel__vgg13_SERVER-20200829-202307/gen_img\n '''\n return 'SERVER' + path.split('_SERVER')[1].split('/')[0]\n\ndef mkdirs(*paths):\n for p in paths:\n if not os.path.exists(p):\n os.makedirs(p)\n\nclass EMA():\n '''\n Exponential Moving Average for pytorch tensor\n '''\n def __init__(self, mu):\n self.mu = mu\n self.history = {}\n\n def __call__(self, name, x):\n '''\n Note: this func will modify x directly, no return value.\n x is supposed to be a pytorch tensor.\n '''\n if self.mu > 0:\n assert(0 < self.mu < 1)\n if name in self.history.keys():\n new_average = self.mu * self.history[name] + (1.0 - self.mu) * x.clone()\n else:\n new_average = x.clone()\n self.history[name] = new_average.clone()\n return new_average.clone()\n else:\n return x.clone()\n\n# Exponential Moving Average\nclass EMA2():\n def __init__(self, mu):\n self.mu = mu\n self.shadow = {}\n def register(self, name, value):\n self.shadow[name] = value.clone()\n def __call__(self, name, x):\n assert name in self.shadow\n new_average = (1.0 - self.mu) * x + self.mu * self.shadow[name]\n self.shadow[name] = new_average.clone()\n return new_average\n\ndef register_ema(emas):\n for net, ema in emas:\n for name, param in net.named_parameters():\n if param.requires_grad:\n ema.register(name, param.data)\n\ndef apply_ema(emas):\n for net, ema in emas:\n for name, param in net.named_parameters():\n if param.requires_grad:\n param.data = ema(name, param.data)\n\ncolors = [\"gray\", \"blue\", \"black\", \"yellow\", \"green\", \"yellowgreen\", \"gold\", \"royalblue\", \"peru\", \"purple\"]\ndef feat_visualize(ax, feat, label):\n '''\n feat: N x 2 # 2-d feature, N: number of examples\n label: N x 1\n '''\n for ix in range(len(label)):\n x = feat[ix]\n y = label[ix]\n ax.scatter(x[0], x[1], color=colors[y], marker=\".\")\n return ax\n\ndef _remove_module_in_name(name):\n ''' remove 'module.' in the module name, caused by DataParallel, if any\n '''\n module_name_parts = name.split(\".\")\n module_name_parts_new = [] \n for x in module_name_parts:\n if x != 'module':\n module_name_parts_new.append(x)\n new_name = '.'.join(module_name_parts_new)\n return new_name\n\ndef smart_weights_load(net, w_path, key=None, load_mode='exact'):\n '''\n This func is to load the weights of <w_path> into <net>.\n '''\n common_weights_keys = ['T', 'S', 'G', 'model', 'state_dict', 'state_dict_t']\n\n ckpt = torch.load(w_path, map_location=lambda storage, location: storage)\n \n # get state_dict\n if isinstance(ckpt, OrderedDict):\n state_dict = ckpt\n else:\n if key:\n state_dict = ckpt[key]\n else:\n intersection = [k for k in ckpt.keys() if k in common_weights_keys and isinstance(ckpt[k], OrderedDict)]\n if len(intersection) == 1:\n k = intersection[0]\n state_dict = ckpt[k]\n else:\n print('Error: multiple or no model keys found in ckpt: %s. Please explicitly appoint one' % intersection)\n exit(1)\n\n if load_mode == 'exact': # net and state_dict have exactly the same architecture (layer names etc. are exactly same)\n try:\n net.load_state_dict(state_dict)\n except:\n ckpt_data_parallel = False\n for k, v in state_dict.items():\n if k.startswith('module.'):\n ckpt_data_parallel = True # DataParallel was used in the ckpt\n break\n \n if ckpt_data_parallel:\n # If ckpt used DataParallel, then the reason of the load failure above should be that the <net> does not use \n # DataParallel. Therefore, remove the surfix 'module.' in ckpt.\n new_state_dict = OrderedDict()\n for k, v in state_dict.items():\n param_name = k.split(\"module.\")[-1]\n new_state_dict[param_name] = v\n else:\n # Similarly, if ckpt didn't use DataParallel, here we add the surfix 'module.'.\n new_state_dict = OrderedDict()\n for k, v in state_dict.items():\n param_name = 'module.' + k\n new_state_dict[param_name] = v\n net.load_state_dict(new_state_dict)\n\n else:\n # Here is the case that <net> and ckpt only have part of weights in common. Then load them by module name:\n # for every named module in <net>, if ckpt has a module of the same (or contextually similar) name, then they are matched and weights are loaded from ckpt to <net>.\n for name, m in net.named_modules():\n print(name)\n \n for name, m in net.named_modules():\n if name:\n print('loading weights for module \"%s\" in the network' % name)\n new_name = _remove_module_in_name(name)\n\n # find the matched module name\n matched_param_name = ''\n for k in ckpt.keys():\n new_k = _remove_module_in_name(k)\n if new_name == new_k:\n matched_param_name = k\n break\n \n # load weights\n if matched_param_name:\n m.weight.copy_(ckpt[matched_param_name])\n print(\"net module name: '%s' <- '%s' (ckpt module name)\" % (name, matched_param_name))\n else:\n print(\"Error: cannot find matched module in ckpt for module '%s' in net. Please check manually.\" % name)\n exit(1)\n \n# parse wanted value from accuracy print log\ndef parse_acc_log(line, key, type_func=float):\n line_seg = line.strip().lower().split()\n for i in range(len(line_seg)):\n if key in line_seg[i]:\n break\n if i == len(line_seg) - 1:\n return None # did not find the <key> in this line\n try:\n value = type_func(line_seg[i+1])\n except:\n value = type_func(line_seg[i+2])\n return value\n\ndef get_layer_by_index(net, index):\n cnt = -1\n for _, m in net.named_modules():\n if isinstance(m, nn.Conv2d) or isinstance(m, nn.Linear):\n cnt += 1\n if cnt == index:\n return m\n return None\n\ndef get_total_index_by_learnable_index(net, learnable_index):\n '''\n learnable_index: index when only counting learnable layers (conv or fc, no bn);\n total_index: count relu, pooling etc in.\n '''\n layer_type_considered = [nn.Conv2d, nn.ReLU, nn.LeakyReLU, nn.PReLU, \n nn.BatchNorm2d, nn.MaxPool2d, nn.AvgPool2d, nn.Linear]\n cnt_total = -1\n cnt_learnable = -1\n for _, m in net.named_modules():\n cond = [isinstance(m, x) for x in layer_type_considered]\n if any(cond):\n cnt_total += 1\n if isinstance(m, nn.Conv2d) or isinstance(m, nn.Linear):\n cnt_learnable += 1\n if cnt_learnable == learnable_index:\n return cnt_total\n return None\n\ndef cal_correlation(x, coef=False):\n '''Calculate the correlation matrix for a pytorch tensor.\n Input shape: [n_sample, n_attr]\n Output shape: [n_attr, n_attr]\n Refer to: https://github.com/pytorch/pytorch/issues/1254\n '''\n # calculate covariance matrix\n y = x - x.mean(dim=0)\n c = y.t().mm(y) / (y.size(0) - 1)\n \n if coef:\n # normalize covariance matrix\n d = torch.diag(c)\n stddev = torch.pow(d, 0.5)\n c = c.div(stddev.expand_as(c))\n c = c.div(stddev.expand_as(c).t())\n\n # clamp between -1 and 1\n # probably not necessary but numpy does it\n c = torch.clamp(c, -1.0, 1.0)\n return c\n\ndef get_class_corr(loader, model):\n model.eval().cuda()\n logits = 0\n n_batch = len(loader)\n with torch.no_grad():\n for ix, data in enumerate(loader):\n input = data[0]\n print('[%d/%d] -- forwarding' % (ix, n_batch))\n input = input.float().cuda()\n if type(logits) == int:\n logits = model(input) # [batch_size, n_class]\n else:\n logits = torch.cat([logits, model(input)], dim=0)\n # Use numpy:\n # logits -= logits.mean(dim=0)\n # logits = logits.data.cpu().numpy()\n # corr = np.corrcoef(logits, rowvar=False)\n\n # Use pytorch\n corr = cal_correlation(logits, coef=True)\n return corr\n\ndef cal_acc(logits, y):\n pred = logits.argmax(dim=1)\n acc = pred.eq(y.data.view_as(pred)).sum().float() / y.size(0)\n return acc\n\nclass Timer():\n '''Log down iteration time and predict the left time for the left iterations\n '''\n def __init__(self, total_epoch):\n self.total_epoch = total_epoch\n self.time_stamp = []\n\n def predict_finish_time(self, ave_window=3):\n self.time_stamp.append(time.time()) # update time stamp\n if len(self.time_stamp) == 1:\n return 'only one time stamp, not enough to predict'\n interval = []\n for i in range(len(self.time_stamp) - 1):\n t = self.time_stamp[i + 1] - self.time_stamp[i]\n interval.append(t)\n sec_per_epoch = np.mean(interval[-ave_window:])\n left_t = sec_per_epoch * (self.total_epoch - len(interval))\n finish_t = left_t + time.time()\n finish_t = time.strftime('%Y/%m/%d-%H:%M', time.localtime(finish_t))\n return finish_t + ' (speed: %.2fs per timing)' % sec_per_epoch\n \n def __call__(self):\n return(self.predict_finish_time())\n\nclass Dataset_npy_batch(Dataset):\n def __init__(self, npy_dir, transform, f='batch.npy'):\n self.data = np.load(os.path.join(npy_dir, f), allow_pickle=True)\n self.transform = transform\n def __getitem__(self, index):\n img = Image.fromarray(self.data[index][0])\n img = self.transform(img)\n label = self.data[index][1]\n label = torch.LongTensor([label])[0]\n return img.squeeze(0), label\n def __len__(self):\n return len(self.data)\n\ndef merge_args(args, params_json):\n '''<args> is from argparser. <params_json> is a json/yaml file.\n merge them, if there is collision, the param in <params_json> has a higher priority.\n '''\n with open(params_json) as f:\n if params_json.endswith('.json'):\n params = json.load(f)\n elif params_json.endswith('.yaml'):\n params = yaml.load(f, Loader=yaml.FullLoader)\n else:\n raise NotImplementedError\n for k, v in params.items():\n args.__dict__[k] = v\n return args\n\nclass AccuracyManager():\n def __init__(self):\n self.accuracy = pd.DataFrame()\n \n def update(self, time, acc1, acc5=None):\n acc = pd.DataFrame([[time, acc1, acc5]], columns=['time', 'acc1', 'acc5']) # time can be epoch or step\n self.accuracy = self.accuracy.append(acc, ignore_index=True)\n \n def get_best_acc(self, criterion='acc1'):\n assert criterion in ['acc1', 'acc5']\n acc = self.accuracy.sort_values(by=criterion) # ascending sort\n best = acc.iloc[-1] # the last row\n time, acc1, acc5 = best.time, best.acc1, best.acc5\n return time, acc1, acc5\n \n def get_last_acc(self):\n last = self.accuracy.iloc[-1]\n time, acc1, acc5 = last.time, last.acc1, last.acc5\n return time, acc1, acc5\n\ndef format_acc_log(acc1_set, lr, acc5=None, time_unit='Epoch'):\n '''return uniform format for the accuracy print\n '''\n acc1, acc1_time, acc1_best, acc1_best_time = acc1_set\n if acc5:\n line = 'Acc1 %.4f Acc5 %.4f @ %s %d (Best_Acc1 %.4f @ %s %d) LR %s' % (acc1, acc5, time_unit, acc1_time, acc1_best, time_unit, acc1_best_time, lr)\n else:\n line = 'Acc1 %.4f @ %s %d (Best_Acc1 %.4f @ %s %d) LR %s' % (acc1, time_unit, acc1_time, acc1_best, time_unit, acc1_best_time, lr)\n return line\n\ndef get_lambda(alpha=1.0):\n '''Return lambda'''\n if alpha > 0.:\n lam = np.random.beta(alpha, alpha)\n else:\n lam = 1.\n return lam\n\n# refer to: 2018-ICLR-mixup\n# https://github.com/facebookresearch/mixup-cifar10/blob/eaff31ab397a90fbc0a4aac71fb5311144b3608b/train.py#L119\ndef mixup_data(x, y, alpha=1.0, use_cuda=True):\n '''Returns mixed inputs, pairs of targets, and lambda'''\n if alpha > 0:\n lam = np.random.beta(alpha, alpha)\n else:\n lam = 1\n\n batch_size = x.size()[0]\n if use_cuda:\n index = torch.randperm(batch_size).cuda()\n else:\n index = torch.randperm(batch_size)\n\n mixed_x = lam * x + (1 - lam) * x[index, :]\n y_a, y_b = y, y[index]\n return mixed_x, y_a, y_b, lam\n\n\ndef mixup_criterion(criterion, pred, y_a, y_b, lam):\n return lam * criterion(pred, y_a) + (1 - lam) * criterion(pred, y_b)\n\n\ndef visualize_filter(layer, layer_id, save_dir, n_filter_plot=16, n_channel_plot=16, pick_mode='rand', plot_abs=True, prefix='', ext='.pdf'):\n '''layer is a pytorch model layer \n '''\n w = layer.weight.data.cpu().numpy() # shape: [N, C, H, W]\n if plot_abs:\n w = np.abs(w)\n n, c = w.shape[0], w.shape[1]\n n_filter_plot = min(n_filter_plot, n)\n n_channel_plot = min(n_channel_plot, c)\n if pick_mode == 'rand':\n filter_ix = np.random.permutation(n)[:n_filter_plot] # filter indexes to plot\n channel_ix = np.random.permutation(c)[:n_channel_plot] # channel indexes to plot\n else:\n filter_ix = list(range(n_filter_plot))\n channel_ix = list(range(n_channel_plot))\n \n # iteration for plotting\n for i in filter_ix:\n f_avg = np.mean(w[i], axis=0)\n fig, ax = plt.subplots()\n im = ax.imshow(f_avg, cmap='jet')\n # make a beautiful colorbar\n divider = make_axes_locatable(ax)\n cax = divider.append_axes('right', size=0.05, pad=0.05)\n fig.colorbar(im, cax=cax, orientation='vertical')\n save_path = '%s/filter_visualize__%s__layer%s__filter%s__average_cross_channel' % (save_dir, prefix, layer_id, i) # prefix is usually a net name\n fig.savefig(save_path + ext, bbox_inches='tight')\n plt.close(fig)\n\n # for j in channel_ix:\n # f = w[i][j]\n # fig, ax = plt.subplots()\n # im = ax.imshow(f, cmap='jet')\n # # make a beautiful colorbar \n # divider = make_axes_locatable(ax)\n # cax = divider.append_axes('right', size=0.05, pad=0.05)\n # fig.colorbar(im, cax=cax, orientation='vertical')\n # save_path = '%s/filter_visualize__%s__layer%s__filter%s__channel%s' % (save_dir, prefix, layer_id, i, j)\n # fig.savefig(save_path + ext, bbox_inches='tight')\n # plt.close(fig)\n\ndef visualize_feature_map(fm, layer_id, save_dir, n_channel_plot=16, pick_mode='rand', plot_abs=True, prefix='', ext='.pdf'):\n fm = fm.clone().detach()\n fm = fm.data.cpu().numpy()[0] # shape: [N, C, H, W], N is batch size. Default: batch size should be 1\n if plot_abs:\n fm = np.abs(fm)\n c = fm.shape[0]\n n_channel_plot = min(n_channel_plot, c)\n if pick_mode == 'rand':\n channel_ix = np.random.permutation(c)[:n_channel_plot] # channel indexes to plot\n else:\n channel_ix = list(range(n_channel_plot))\n \n # iteration for plotting\n fm_avg = np.mean(fm, axis=0)\n fig, ax = plt.subplots()\n im = ax.imshow(fm_avg, cmap='jet')\n # make a beautiful colorbar\n divider = make_axes_locatable(ax)\n cax = divider.append_axes('right', size=0.05, pad=0.05)\n fig.colorbar(im, cax=cax, orientation='vertical')\n save_path = '%s/featmap_visualization__%s__layer%s__average_cross_channel' % (save_dir, prefix, layer_id) # prefix is usually a net name\n fig.savefig(save_path + ext, bbox_inches='tight')\n plt.close(fig)\n\n # for j in channel_ix:\n # f = fm[j]\n # fig, ax = plt.subplots()\n # im = ax.imshow(f, cmap='jet')\n # # make a beautiful colorbar \n # divider = make_axes_locatable(ax)\n # cax = divider.append_axes('right', size=0.05, pad=0.05)\n # fig.colorbar(im, cax=cax, orientation='vertical')\n # save_path = '%s/featmap_visualization__%s__layer%s__channel%s' % (save_dir, prefix, layer_id, j)\n # fig.savefig(save_path + ext, bbox_inches='tight')\n # plt.close(fig)\n"
] | [
[
"torch.nn.functional.kl_div",
"torch.nn.functional.softmax",
"torch.load",
"torch.randperm",
"numpy.mean",
"torch.no_grad",
"torch.pow",
"torch.nn.CrossEntropyLoss",
"numpy.random.beta",
"torch.einsum",
"torch.from_numpy",
"torch.rand",
"matplotlib.pyplot.close",
"numpy.zeros",
"torch.nn.init.kaiming_normal",
"torch.LongTensor",
"torch.diag",
"numpy.array",
"numpy.abs",
"torch.nn.functional.log_softmax",
"matplotlib.pyplot.subplots",
"numpy.random.permutation",
"numpy.prod",
"torch.clamp"
]
] |
robertnishihara/arrow | [
"27f990a503f8d9370037bd12c235aae1c1378fb9"
] | [
"python/pyarrow/tests/test_convert_pandas.py"
] | [
"# -*- coding: utf-8 -*-\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. 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,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport decimal\nimport json\nimport multiprocessing as mp\nfrom collections import OrderedDict\nfrom datetime import date, datetime, time, timedelta\n\nimport numpy as np\nimport numpy.testing as npt\nimport pandas as pd\nimport pandas.util.testing as tm\nimport pytest\n\nimport pyarrow as pa\nimport pyarrow.types as patypes\nfrom pyarrow.compat import PY2\n\nfrom .pandas_examples import dataframe_with_arrays, dataframe_with_lists\n\n\ndef _alltypes_example(size=100):\n return pd.DataFrame({\n 'uint8': np.arange(size, dtype=np.uint8),\n 'uint16': np.arange(size, dtype=np.uint16),\n 'uint32': np.arange(size, dtype=np.uint32),\n 'uint64': np.arange(size, dtype=np.uint64),\n 'int8': np.arange(size, dtype=np.int16),\n 'int16': np.arange(size, dtype=np.int16),\n 'int32': np.arange(size, dtype=np.int32),\n 'int64': np.arange(size, dtype=np.int64),\n 'float32': np.arange(size, dtype=np.float32),\n 'float64': np.arange(size, dtype=np.float64),\n 'bool': np.random.randn(size) > 0,\n # TODO(wesm): Pandas only support ns resolution, Arrow supports s, ms,\n # us, ns\n 'datetime': np.arange(\"2016-01-01T00:00:00.001\", size,\n dtype='datetime64[ms]'),\n 'str': [str(x) for x in range(size)],\n 'str_with_nulls': [None] + [str(x) for x in range(size - 2)] + [None],\n 'empty_str': [''] * size\n })\n\n\ndef _check_pandas_roundtrip(df, expected=None, use_threads=False,\n expected_schema=None,\n check_dtype=True, schema=None,\n preserve_index=False,\n as_batch=False):\n klass = pa.RecordBatch if as_batch else pa.Table\n table = klass.from_pandas(df, schema=schema,\n preserve_index=preserve_index,\n nthreads=2 if use_threads else 1)\n result = table.to_pandas(use_threads=use_threads)\n\n if expected_schema:\n # all occurences of _check_pandas_roundtrip passes expected_schema\n # without the pandas generated key-value metadata, so we need to\n # add it before checking schema equality\n expected_schema = expected_schema.add_metadata(table.schema.metadata)\n assert table.schema.equals(expected_schema)\n\n if expected is None:\n expected = df\n\n tm.assert_frame_equal(result, expected, check_dtype=check_dtype,\n check_index_type=('equiv' if preserve_index\n else False))\n\n\ndef _check_series_roundtrip(s, type_=None, expected_pa_type=None):\n arr = pa.array(s, from_pandas=True, type=type_)\n\n if type_ is not None and expected_pa_type is None:\n expected_pa_type = type_\n\n if expected_pa_type is not None:\n assert arr.type == expected_pa_type\n\n result = pd.Series(arr.to_pandas(), name=s.name)\n if patypes.is_timestamp(arr.type) and arr.type.tz is not None:\n result = (result.dt.tz_localize('utc')\n .dt.tz_convert(arr.type.tz))\n\n tm.assert_series_equal(s, result)\n\n\ndef _check_array_roundtrip(values, expected=None, mask=None,\n type=None):\n arr = pa.array(values, from_pandas=True, mask=mask, type=type)\n result = arr.to_pandas()\n\n values_nulls = pd.isnull(values)\n if mask is None:\n assert arr.null_count == values_nulls.sum()\n else:\n assert arr.null_count == (mask | values_nulls).sum()\n\n if mask is None:\n tm.assert_series_equal(pd.Series(result), pd.Series(values),\n check_names=False)\n else:\n expected = pd.Series(np.ma.masked_array(values, mask=mask))\n tm.assert_series_equal(pd.Series(result), expected,\n check_names=False)\n\n\ndef _check_array_from_pandas_roundtrip(np_array, type=None):\n arr = pa.array(np_array, from_pandas=True, type=type)\n result = arr.to_pandas()\n npt.assert_array_equal(result, np_array)\n\n\nclass TestConvertMetadata(object):\n \"\"\"\n Conversion tests for Pandas metadata & indices.\n \"\"\"\n\n def test_non_string_columns(self):\n df = pd.DataFrame({0: [1, 2, 3]})\n table = pa.Table.from_pandas(df)\n assert table.column(0).name == '0'\n\n def test_from_pandas_with_columns(self):\n df = pd.DataFrame({0: [1, 2, 3], 1: [1, 3, 3], 2: [2, 4, 5]})\n\n table = pa.Table.from_pandas(df, columns=[0, 1])\n expected = pa.Table.from_pandas(df[[0, 1]])\n assert expected.equals(table)\n\n record_batch_table = pa.RecordBatch.from_pandas(df, columns=[0, 1])\n record_batch_expected = pa.RecordBatch.from_pandas(df[[0, 1]])\n assert record_batch_expected.equals(record_batch_table)\n\n def test_column_index_names_are_preserved(self):\n df = pd.DataFrame({'data': [1, 2, 3]})\n df.columns.names = ['a']\n _check_pandas_roundtrip(df, preserve_index=True)\n\n def test_multiindex_columns(self):\n columns = pd.MultiIndex.from_arrays([\n ['one', 'two'], ['X', 'Y']\n ])\n df = pd.DataFrame([(1, 'a'), (2, 'b'), (3, 'c')], columns=columns)\n _check_pandas_roundtrip(df, preserve_index=True)\n\n def test_multiindex_columns_with_dtypes(self):\n columns = pd.MultiIndex.from_arrays(\n [\n ['one', 'two'],\n pd.DatetimeIndex(['2017-08-01', '2017-08-02']),\n ],\n names=['level_1', 'level_2'],\n )\n df = pd.DataFrame([(1, 'a'), (2, 'b'), (3, 'c')], columns=columns)\n _check_pandas_roundtrip(df, preserve_index=True)\n\n def test_multiindex_columns_unicode(self):\n columns = pd.MultiIndex.from_arrays([[u'あ', u'い'], ['X', 'Y']])\n df = pd.DataFrame([(1, 'a'), (2, 'b'), (3, 'c')], columns=columns)\n _check_pandas_roundtrip(df, preserve_index=True)\n\n def test_integer_index_column(self):\n df = pd.DataFrame([(1, 'a'), (2, 'b'), (3, 'c')])\n _check_pandas_roundtrip(df, preserve_index=True)\n\n def test_index_metadata_field_name(self):\n # test None case, and strangely named non-index columns\n df = pd.DataFrame(\n [(1, 'a', 3.1), (2, 'b', 2.2), (3, 'c', 1.3)],\n index=pd.MultiIndex.from_arrays(\n [['c', 'b', 'a'], [3, 2, 1]],\n names=[None, 'foo']\n ),\n columns=['a', None, '__index_level_0__'],\n )\n t = pa.Table.from_pandas(df, preserve_index=True)\n raw_metadata = t.schema.metadata\n\n js = json.loads(raw_metadata[b'pandas'].decode('utf8'))\n\n col1, col2, col3, idx0, foo = js['columns']\n\n assert col1['name'] == 'a'\n assert col1['name'] == col1['field_name']\n\n assert col2['name'] is None\n assert col2['field_name'] == 'None'\n\n assert col3['name'] == '__index_level_0__'\n assert col3['name'] == col3['field_name']\n\n idx0_name, foo_name = js['index_columns']\n assert idx0_name == '__index_level_0__'\n assert idx0['field_name'] == idx0_name\n assert idx0['name'] is None\n\n assert foo_name == 'foo'\n assert foo['field_name'] == foo_name\n assert foo['name'] == foo_name\n\n def test_categorical_column_index(self):\n df = pd.DataFrame(\n [(1, 'a', 2.0), (2, 'b', 3.0), (3, 'c', 4.0)],\n columns=pd.Index(list('def'), dtype='category')\n )\n t = pa.Table.from_pandas(df, preserve_index=True)\n raw_metadata = t.schema.metadata\n js = json.loads(raw_metadata[b'pandas'].decode('utf8'))\n\n column_indexes, = js['column_indexes']\n assert column_indexes['name'] is None\n assert column_indexes['pandas_type'] == 'categorical'\n assert column_indexes['numpy_type'] == 'int8'\n\n md = column_indexes['metadata']\n assert md['num_categories'] == 3\n assert md['ordered'] is False\n\n def test_string_column_index(self):\n df = pd.DataFrame(\n [(1, 'a', 2.0), (2, 'b', 3.0), (3, 'c', 4.0)],\n columns=pd.Index(list('def'), name='stringz')\n )\n t = pa.Table.from_pandas(df, preserve_index=True)\n raw_metadata = t.schema.metadata\n js = json.loads(raw_metadata[b'pandas'].decode('utf8'))\n\n column_indexes, = js['column_indexes']\n assert column_indexes['name'] == 'stringz'\n assert column_indexes['name'] == column_indexes['field_name']\n assert column_indexes['pandas_type'] == ('bytes' if PY2 else 'unicode')\n assert column_indexes['numpy_type'] == 'object'\n\n md = column_indexes['metadata']\n\n if not PY2:\n assert len(md) == 1\n assert md['encoding'] == 'UTF-8'\n else:\n assert md is None or 'encoding' not in md\n\n def test_datetimetz_column_index(self):\n df = pd.DataFrame(\n [(1, 'a', 2.0), (2, 'b', 3.0), (3, 'c', 4.0)],\n columns=pd.date_range(\n start='2017-01-01', periods=3, tz='America/New_York'\n )\n )\n t = pa.Table.from_pandas(df, preserve_index=True)\n raw_metadata = t.schema.metadata\n js = json.loads(raw_metadata[b'pandas'].decode('utf8'))\n\n column_indexes, = js['column_indexes']\n assert column_indexes['name'] is None\n assert column_indexes['pandas_type'] == 'datetimetz'\n assert column_indexes['numpy_type'] == 'datetime64[ns]'\n\n md = column_indexes['metadata']\n assert md['timezone'] == 'America/New_York'\n\n def test_datetimetz_row_index(self):\n df = pd.DataFrame({\n 'a': pd.date_range(\n start='2017-01-01', periods=3, tz='America/New_York'\n )\n })\n df = df.set_index('a')\n\n _check_pandas_roundtrip(df, preserve_index=True)\n\n def test_categorical_row_index(self):\n df = pd.DataFrame({'a': [1, 2, 3], 'b': [1, 2, 3]})\n df['a'] = df.a.astype('category')\n df = df.set_index('a')\n\n _check_pandas_roundtrip(df, preserve_index=True)\n\n def test_duplicate_column_names_does_not_crash(self):\n df = pd.DataFrame([(1, 'a'), (2, 'b')], columns=list('aa'))\n with pytest.raises(ValueError):\n pa.Table.from_pandas(df)\n\n def test_dictionary_indices_boundscheck(self):\n # ARROW-1658. No validation of indices leads to segfaults in pandas\n indices = [[0, 1], [0, -1]]\n\n for inds in indices:\n arr = pa.DictionaryArray.from_arrays(inds, ['a'], safe=False)\n batch = pa.RecordBatch.from_arrays([arr], ['foo'])\n table = pa.Table.from_batches([batch, batch, batch])\n\n with pytest.raises(pa.ArrowInvalid):\n arr.to_pandas()\n\n with pytest.raises(pa.ArrowInvalid):\n table.to_pandas()\n\n def test_unicode_with_unicode_column_and_index(self):\n df = pd.DataFrame({u'あ': [u'い']}, index=[u'う'])\n\n _check_pandas_roundtrip(df, preserve_index=True)\n\n def test_mixed_unicode_column_names(self):\n df = pd.DataFrame({u'あ': [u'い'], b'a': 1}, index=[u'う'])\n\n # TODO(phillipc): Should this raise?\n with pytest.raises(AssertionError):\n _check_pandas_roundtrip(df, preserve_index=True)\n\n def test_binary_column_name(self):\n column_data = [u'い']\n key = u'あ'.encode('utf8')\n data = {key: column_data}\n df = pd.DataFrame(data)\n\n # we can't use _check_pandas_roundtrip here because our metdata\n # is always decoded as utf8: even if binary goes in, utf8 comes out\n t = pa.Table.from_pandas(df, preserve_index=True)\n df2 = t.to_pandas()\n assert df.values[0] == df2.values[0]\n assert df.index.values[0] == df2.index.values[0]\n assert df.columns[0] == key\n\n def test_multiindex_duplicate_values(self):\n num_rows = 3\n numbers = list(range(num_rows))\n index = pd.MultiIndex.from_arrays(\n [['foo', 'foo', 'bar'], numbers],\n names=['foobar', 'some_numbers'],\n )\n\n df = pd.DataFrame({'numbers': numbers}, index=index)\n\n table = pa.Table.from_pandas(df)\n result_df = table.to_pandas()\n tm.assert_frame_equal(result_df, df)\n\n def test_metadata_with_mixed_types(self):\n df = pd.DataFrame({'data': [b'some_bytes', u'some_unicode']})\n table = pa.Table.from_pandas(df)\n metadata = table.schema.metadata\n assert b'mixed' not in metadata[b'pandas']\n\n js = json.loads(metadata[b'pandas'].decode('utf8'))\n data_column = js['columns'][0]\n assert data_column['pandas_type'] == 'bytes'\n assert data_column['numpy_type'] == 'object'\n\n def test_list_metadata(self):\n df = pd.DataFrame({'data': [[1], [2, 3, 4], [5] * 7]})\n schema = pa.schema([pa.field('data', type=pa.list_(pa.int64()))])\n table = pa.Table.from_pandas(df, schema=schema)\n metadata = table.schema.metadata\n assert b'mixed' not in metadata[b'pandas']\n\n js = json.loads(metadata[b'pandas'].decode('utf8'))\n data_column = js['columns'][0]\n assert data_column['pandas_type'] == 'list[int64]'\n assert data_column['numpy_type'] == 'object'\n\n def test_decimal_metadata(self):\n expected = pd.DataFrame({\n 'decimals': [\n decimal.Decimal('394092382910493.12341234678'),\n -decimal.Decimal('314292388910493.12343437128'),\n ]\n })\n table = pa.Table.from_pandas(expected)\n metadata = table.schema.metadata\n assert b'mixed' not in metadata[b'pandas']\n\n js = json.loads(metadata[b'pandas'].decode('utf8'))\n data_column = js['columns'][0]\n assert data_column['pandas_type'] == 'decimal'\n assert data_column['numpy_type'] == 'object'\n assert data_column['metadata'] == {'precision': 26, 'scale': 11}\n\n def test_table_column_subset_metadata(self):\n # ARROW-1883\n df = pd.DataFrame({\n 'a': [1, 2, 3],\n 'b': pd.date_range(\"2017-01-01\", periods=3, tz='Europe/Brussels')})\n table = pa.Table.from_pandas(df)\n\n table_subset = table.remove_column(1)\n result = table_subset.to_pandas()\n tm.assert_frame_equal(result, df[['a']])\n\n table_subset2 = table_subset.remove_column(1)\n result = table_subset2.to_pandas()\n tm.assert_frame_equal(result, df[['a']])\n\n # non-default index\n for index in [\n pd.Index(['a', 'b', 'c'], name='index'),\n pd.date_range(\"2017-01-01\", periods=3, tz='Europe/Brussels')]:\n df = pd.DataFrame({'a': [1, 2, 3],\n 'b': [.1, .2, .3]}, index=index)\n table = pa.Table.from_pandas(df)\n\n table_subset = table.remove_column(1)\n result = table_subset.to_pandas()\n tm.assert_frame_equal(result, df[['a']])\n\n table_subset2 = table_subset.remove_column(1)\n result = table_subset2.to_pandas()\n tm.assert_frame_equal(result, df[['a']].reset_index(drop=True))\n\n def test_empty_list_metadata(self):\n # Create table with array of empty lists, forced to have type\n # list(string) in pyarrow\n c1 = [[\"test\"], [\"a\", \"b\"], None]\n c2 = [[], [], []]\n arrays = OrderedDict([\n ('c1', pa.array(c1, type=pa.list_(pa.string()))),\n ('c2', pa.array(c2, type=pa.list_(pa.string()))),\n ])\n rb = pa.RecordBatch.from_arrays(\n list(arrays.values()),\n list(arrays.keys())\n )\n tbl = pa.Table.from_batches([rb])\n\n # First roundtrip changes schema, because pandas cannot preserve the\n # type of empty lists\n df = tbl.to_pandas()\n tbl2 = pa.Table.from_pandas(df, preserve_index=True)\n md2 = json.loads(tbl2.schema.metadata[b'pandas'].decode('utf8'))\n\n # Second roundtrip\n df2 = tbl2.to_pandas()\n expected = pd.DataFrame(OrderedDict([('c1', c1), ('c2', c2)]))\n\n tm.assert_frame_equal(df2, expected)\n\n assert md2['columns'] == [\n {\n 'name': 'c1',\n 'field_name': 'c1',\n 'metadata': None,\n 'numpy_type': 'object',\n 'pandas_type': 'list[unicode]',\n },\n {\n 'name': 'c2',\n 'field_name': 'c2',\n 'metadata': None,\n 'numpy_type': 'object',\n 'pandas_type': 'list[empty]',\n },\n {\n 'name': None,\n 'field_name': '__index_level_0__',\n 'metadata': None,\n 'numpy_type': 'int64',\n 'pandas_type': 'int64',\n }\n ]\n\n\nclass TestConvertPrimitiveTypes(object):\n \"\"\"\n Conversion tests for primitive (e.g. numeric) types.\n \"\"\"\n\n def test_float_no_nulls(self):\n data = {}\n fields = []\n dtypes = [('f2', pa.float16()),\n ('f4', pa.float32()),\n ('f8', pa.float64())]\n num_values = 100\n\n for numpy_dtype, arrow_dtype in dtypes:\n values = np.random.randn(num_values)\n data[numpy_dtype] = values.astype(numpy_dtype)\n fields.append(pa.field(numpy_dtype, arrow_dtype))\n\n df = pd.DataFrame(data)\n schema = pa.schema(fields)\n _check_pandas_roundtrip(df, expected_schema=schema)\n\n def test_float_nulls(self):\n num_values = 100\n\n null_mask = np.random.randint(0, 10, size=num_values) < 3\n dtypes = [('f2', pa.float16()),\n ('f4', pa.float32()),\n ('f8', pa.float64())]\n names = ['f2', 'f4', 'f8']\n expected_cols = []\n\n arrays = []\n fields = []\n for name, arrow_dtype in dtypes:\n values = np.random.randn(num_values).astype(name)\n\n arr = pa.array(values, from_pandas=True, mask=null_mask)\n arrays.append(arr)\n fields.append(pa.field(name, arrow_dtype))\n values[null_mask] = np.nan\n\n expected_cols.append(values)\n\n ex_frame = pd.DataFrame(dict(zip(names, expected_cols)),\n columns=names)\n\n table = pa.Table.from_arrays(arrays, names)\n assert table.schema.equals(pa.schema(fields))\n result = table.to_pandas()\n tm.assert_frame_equal(result, ex_frame)\n\n def test_float_nulls_to_ints(self):\n # ARROW-2135\n df = pd.DataFrame({\"a\": [1.0, 2.0, pd.np.NaN]})\n schema = pa.schema([pa.field(\"a\", pa.int16(), nullable=True)])\n table = pa.Table.from_pandas(df, schema=schema)\n assert table[0].to_pylist() == [1, 2, None]\n tm.assert_frame_equal(df, table.to_pandas())\n\n def test_integer_no_nulls(self):\n data = OrderedDict()\n fields = []\n\n numpy_dtypes = [\n ('i1', pa.int8()), ('i2', pa.int16()),\n ('i4', pa.int32()), ('i8', pa.int64()),\n ('u1', pa.uint8()), ('u2', pa.uint16()),\n ('u4', pa.uint32()), ('u8', pa.uint64()),\n ('longlong', pa.int64()), ('ulonglong', pa.uint64())\n ]\n num_values = 100\n\n for dtype, arrow_dtype in numpy_dtypes:\n info = np.iinfo(dtype)\n values = np.random.randint(max(info.min, np.iinfo(np.int_).min),\n min(info.max, np.iinfo(np.int_).max),\n size=num_values)\n data[dtype] = values.astype(dtype)\n fields.append(pa.field(dtype, arrow_dtype))\n\n df = pd.DataFrame(data)\n schema = pa.schema(fields)\n _check_pandas_roundtrip(df, expected_schema=schema)\n\n def test_all_integer_types(self):\n # Test all Numpy integer aliases\n data = OrderedDict()\n numpy_dtypes = ['i1', 'i2', 'i4', 'i8', 'u1', 'u2', 'u4', 'u8',\n 'byte', 'ubyte', 'short', 'ushort', 'intc', 'uintc',\n 'int_', 'uint', 'longlong', 'ulonglong']\n for dtype in numpy_dtypes:\n data[dtype] = np.arange(12, dtype=dtype)\n df = pd.DataFrame(data)\n _check_pandas_roundtrip(df)\n\n # Do the same with pa.array()\n # (for some reason, it doesn't use the same code paths at all)\n for np_arr in data.values():\n arr = pa.array(np_arr)\n assert arr.to_pylist() == np_arr.tolist()\n\n def test_integer_with_nulls(self):\n # pandas requires upcast to float dtype\n\n int_dtypes = ['i1', 'i2', 'i4', 'i8', 'u1', 'u2', 'u4', 'u8']\n num_values = 100\n\n null_mask = np.random.randint(0, 10, size=num_values) < 3\n\n expected_cols = []\n arrays = []\n for name in int_dtypes:\n values = np.random.randint(0, 100, size=num_values)\n\n arr = pa.array(values, mask=null_mask)\n arrays.append(arr)\n\n expected = values.astype('f8')\n expected[null_mask] = np.nan\n\n expected_cols.append(expected)\n\n ex_frame = pd.DataFrame(dict(zip(int_dtypes, expected_cols)),\n columns=int_dtypes)\n\n table = pa.Table.from_arrays(arrays, int_dtypes)\n result = table.to_pandas()\n\n tm.assert_frame_equal(result, ex_frame)\n\n def test_array_from_pandas_type_cast(self):\n arr = np.arange(10, dtype='int64')\n\n target_type = pa.int8()\n\n result = pa.array(arr, type=target_type)\n expected = pa.array(arr.astype('int8'))\n assert result.equals(expected)\n\n def test_boolean_no_nulls(self):\n num_values = 100\n\n np.random.seed(0)\n\n df = pd.DataFrame({'bools': np.random.randn(num_values) > 0})\n field = pa.field('bools', pa.bool_())\n schema = pa.schema([field])\n _check_pandas_roundtrip(df, expected_schema=schema)\n\n def test_boolean_nulls(self):\n # pandas requires upcast to object dtype\n num_values = 100\n np.random.seed(0)\n\n mask = np.random.randint(0, 10, size=num_values) < 3\n values = np.random.randint(0, 10, size=num_values) < 5\n\n arr = pa.array(values, mask=mask)\n\n expected = values.astype(object)\n expected[mask] = None\n\n field = pa.field('bools', pa.bool_())\n schema = pa.schema([field])\n ex_frame = pd.DataFrame({'bools': expected})\n\n table = pa.Table.from_arrays([arr], ['bools'])\n assert table.schema.equals(schema)\n result = table.to_pandas()\n\n tm.assert_frame_equal(result, ex_frame)\n\n def test_float_object_nulls(self):\n arr = np.array([None, 1.5, np.float64(3.5)] * 5, dtype=object)\n df = pd.DataFrame({'floats': arr})\n expected = pd.DataFrame({'floats': pd.to_numeric(arr)})\n field = pa.field('floats', pa.float64())\n schema = pa.schema([field])\n _check_pandas_roundtrip(df, expected=expected,\n expected_schema=schema)\n\n def test_int_object_nulls(self):\n arr = np.array([None, 1, np.int64(3)] * 5, dtype=object)\n df = pd.DataFrame({'ints': arr})\n expected = pd.DataFrame({'ints': pd.to_numeric(arr)})\n field = pa.field('ints', pa.int64())\n schema = pa.schema([field])\n _check_pandas_roundtrip(df, expected=expected,\n expected_schema=schema)\n\n def test_boolean_object_nulls(self):\n arr = np.array([False, None, True] * 100, dtype=object)\n df = pd.DataFrame({'bools': arr})\n field = pa.field('bools', pa.bool_())\n schema = pa.schema([field])\n _check_pandas_roundtrip(df, expected_schema=schema)\n\n def test_all_nulls_cast_numeric(self):\n arr = np.array([None], dtype=object)\n\n def _check_type(t):\n a2 = pa.array(arr, type=t)\n assert a2.type == t\n assert a2[0].as_py() is None\n\n _check_type(pa.int32())\n _check_type(pa.float64())\n\n def test_half_floats_from_numpy(self):\n arr = np.array([1.5, np.nan], dtype=np.float16)\n a = pa.array(arr, type=pa.float16())\n x, y = a.to_pylist()\n assert isinstance(x, np.float16)\n assert x == 1.5\n assert isinstance(y, np.float16)\n assert np.isnan(y)\n\n a = pa.array(arr, type=pa.float16(), from_pandas=True)\n x, y = a.to_pylist()\n assert isinstance(x, np.float16)\n assert x == 1.5\n assert y is None\n\n\[email protected]('dtype',\n ['i1', 'i2', 'i4', 'i8', 'u1', 'u2', 'u4', 'u8'])\ndef test_array_integer_object_nulls_option(dtype):\n num_values = 100\n\n null_mask = np.random.randint(0, 10, size=num_values) < 3\n values = np.random.randint(0, 100, size=num_values, dtype=dtype)\n\n array = pa.array(values, mask=null_mask)\n\n if null_mask.any():\n expected = values.astype('O')\n expected[null_mask] = None\n else:\n expected = values\n\n result = array.to_pandas(integer_object_nulls=True)\n\n np.testing.assert_equal(result, expected)\n\n\[email protected]('dtype',\n ['i1', 'i2', 'i4', 'i8', 'u1', 'u2', 'u4', 'u8'])\ndef test_table_integer_object_nulls_option(dtype):\n num_values = 100\n\n null_mask = np.random.randint(0, 10, size=num_values) < 3\n values = np.random.randint(0, 100, size=num_values, dtype=dtype)\n\n array = pa.array(values, mask=null_mask)\n\n if null_mask.any():\n expected = values.astype('O')\n expected[null_mask] = None\n else:\n expected = values\n\n expected = pd.DataFrame({dtype: expected})\n\n table = pa.Table.from_arrays([array], [dtype])\n result = table.to_pandas(integer_object_nulls=True)\n\n tm.assert_frame_equal(result, expected)\n\n\nclass TestConvertDateTimeLikeTypes(object):\n \"\"\"\n Conversion tests for datetime- and timestamp-like types (date64, etc.).\n \"\"\"\n\n def test_timestamps_notimezone_no_nulls(self):\n df = pd.DataFrame({\n 'datetime64': np.array([\n '2007-07-13T01:23:34.123456789',\n '2006-01-13T12:34:56.432539784',\n '2010-08-13T05:46:57.437699912'],\n dtype='datetime64[ns]')\n })\n field = pa.field('datetime64', pa.timestamp('ns'))\n schema = pa.schema([field])\n _check_pandas_roundtrip(\n df,\n expected_schema=schema,\n )\n\n def test_timestamps_notimezone_nulls(self):\n df = pd.DataFrame({\n 'datetime64': np.array([\n '2007-07-13T01:23:34.123456789',\n None,\n '2010-08-13T05:46:57.437699912'],\n dtype='datetime64[ns]')\n })\n field = pa.field('datetime64', pa.timestamp('ns'))\n schema = pa.schema([field])\n _check_pandas_roundtrip(\n df,\n expected_schema=schema,\n )\n\n def test_timestamps_with_timezone(self):\n df = pd.DataFrame({\n 'datetime64': np.array([\n '2007-07-13T01:23:34.123',\n '2006-01-13T12:34:56.432',\n '2010-08-13T05:46:57.437'],\n dtype='datetime64[ms]')\n })\n df['datetime64'] = (df['datetime64'].dt.tz_localize('US/Eastern')\n .to_frame())\n _check_pandas_roundtrip(df)\n\n _check_series_roundtrip(df['datetime64'])\n\n # drop-in a null and ns instead of ms\n df = pd.DataFrame({\n 'datetime64': np.array([\n '2007-07-13T01:23:34.123456789',\n None,\n '2006-01-13T12:34:56.432539784',\n '2010-08-13T05:46:57.437699912'],\n dtype='datetime64[ns]')\n })\n df['datetime64'] = (df['datetime64'].dt.tz_localize('US/Eastern')\n .to_frame())\n\n _check_pandas_roundtrip(df)\n\n def test_python_datetime(self):\n # ARROW-2106\n date_array = [datetime.today() + timedelta(days=x) for x in range(10)]\n df = pd.DataFrame({\n 'datetime': pd.Series(date_array, dtype=object)\n })\n\n table = pa.Table.from_pandas(df)\n assert isinstance(table[0].data.chunk(0), pa.TimestampArray)\n\n result = table.to_pandas()\n expected_df = pd.DataFrame({\n 'datetime': date_array\n })\n tm.assert_frame_equal(expected_df, result)\n\n def test_python_datetime_subclass(self):\n\n class MyDatetime(datetime):\n # see https://github.com/pandas-dev/pandas/issues/21142\n nanosecond = 0.0\n\n date_array = [MyDatetime(2000, 1, 1, 1, 1, 1)]\n df = pd.DataFrame({\"datetime\": pd.Series(date_array, dtype=object)})\n\n table = pa.Table.from_pandas(df)\n assert isinstance(table[0].data.chunk(0), pa.TimestampArray)\n\n result = table.to_pandas()\n expected_df = pd.DataFrame({\"datetime\": date_array})\n\n # https://github.com/pandas-dev/pandas/issues/21142\n expected_df[\"datetime\"] = pd.to_datetime(expected_df[\"datetime\"])\n\n tm.assert_frame_equal(expected_df, result)\n\n def test_python_date_subclass(self):\n\n class MyDate(date):\n pass\n\n date_array = [MyDate(2000, 1, 1)]\n df = pd.DataFrame({\"date\": pd.Series(date_array, dtype=object)})\n\n table = pa.Table.from_pandas(df)\n assert isinstance(table[0].data.chunk(0), pa.Date32Array)\n\n result = table.to_pandas()\n expected_df = pd.DataFrame(\n {\"date\": np.array([\"2000-01-01\"], dtype=\"datetime64[ns]\")}\n )\n tm.assert_frame_equal(expected_df, result)\n\n def test_datetime64_to_date32(self):\n # ARROW-1718\n arr = pa.array([date(2017, 10, 23), None])\n c = pa.Column.from_array(\"d\", arr)\n s = c.to_pandas()\n\n arr2 = pa.Array.from_pandas(s, type=pa.date32())\n\n assert arr2.equals(arr.cast('date32'))\n\n @pytest.mark.parametrize('mask', [\n None,\n np.array([True, False, False]),\n ])\n def test_pandas_datetime_to_date64(self, mask):\n s = pd.to_datetime([\n '2018-05-10T00:00:00',\n '2018-05-11T00:00:00',\n '2018-05-12T00:00:00',\n ])\n arr = pa.Array.from_pandas(s, type=pa.date64(), mask=mask)\n\n data = np.array([\n date(2018, 5, 10),\n date(2018, 5, 11),\n date(2018, 5, 12)\n ])\n expected = pa.array(data, mask=mask, type=pa.date64())\n\n assert arr.equals(expected)\n\n @pytest.mark.parametrize('mask', [\n None,\n np.array([True, False, False])\n ])\n def test_pandas_datetime_to_date64_failures(self, mask):\n s = pd.to_datetime([\n '2018-05-10T10:24:01',\n '2018-05-11T10:24:01',\n '2018-05-12T10:24:01',\n ])\n\n expected_msg = 'Timestamp value had non-zero intraday milliseconds'\n with pytest.raises(pa.ArrowInvalid, match=expected_msg):\n pa.Array.from_pandas(s, type=pa.date64(), mask=mask)\n\n def test_date_infer(self):\n df = pd.DataFrame({\n 'date': [date(2000, 1, 1),\n None,\n date(1970, 1, 1),\n date(2040, 2, 26)]})\n table = pa.Table.from_pandas(df, preserve_index=False)\n field = pa.field('date', pa.date32())\n\n # schema's metadata is generated by from_pandas conversion\n expected_schema = pa.schema([field], metadata=table.schema.metadata)\n assert table.schema.equals(expected_schema)\n\n result = table.to_pandas()\n expected = df.copy()\n expected['date'] = pd.to_datetime(df['date'])\n tm.assert_frame_equal(result, expected)\n\n def test_date_mask(self):\n arr = np.array([date(2017, 4, 3), date(2017, 4, 4)],\n dtype='datetime64[D]')\n mask = [True, False]\n result = pa.array(arr, mask=np.array(mask))\n expected = np.array([None, date(2017, 4, 4)], dtype='datetime64[D]')\n expected = pa.array(expected, from_pandas=True)\n assert expected.equals(result)\n\n def test_date_objects_typed(self):\n arr = np.array([\n date(2017, 4, 3),\n None,\n date(2017, 4, 4),\n date(2017, 4, 5)], dtype=object)\n\n arr_i4 = np.array([17259, -1, 17260, 17261], dtype='int32')\n arr_i8 = arr_i4.astype('int64') * 86400000\n mask = np.array([False, True, False, False])\n\n t32 = pa.date32()\n t64 = pa.date64()\n\n a32 = pa.array(arr, type=t32)\n a64 = pa.array(arr, type=t64)\n\n a32_expected = pa.array(arr_i4, mask=mask, type=t32)\n a64_expected = pa.array(arr_i8, mask=mask, type=t64)\n\n assert a32.equals(a32_expected)\n assert a64.equals(a64_expected)\n\n # Test converting back to pandas\n colnames = ['date32', 'date64']\n table = pa.Table.from_arrays([a32, a64], colnames)\n table_pandas = table.to_pandas()\n\n ex_values = (np.array(['2017-04-03', '2017-04-04', '2017-04-04',\n '2017-04-05'],\n dtype='datetime64[D]')\n .astype('datetime64[ns]'))\n ex_values[1] = pd.NaT.value\n expected_pandas = pd.DataFrame({'date32': ex_values,\n 'date64': ex_values},\n columns=colnames)\n tm.assert_frame_equal(table_pandas, expected_pandas)\n\n def test_dates_from_integers(self):\n t1 = pa.date32()\n t2 = pa.date64()\n\n arr = np.array([17259, 17260, 17261], dtype='int32')\n arr2 = arr.astype('int64') * 86400000\n\n a1 = pa.array(arr, type=t1)\n a2 = pa.array(arr2, type=t2)\n\n expected = date(2017, 4, 3)\n assert a1[0].as_py() == expected\n assert a2[0].as_py() == expected\n\n @pytest.mark.xfail(reason=\"not supported ATM\",\n raises=NotImplementedError)\n def test_timedelta(self):\n # TODO(jreback): Pandas only support ns resolution\n # Arrow supports ??? for resolution\n df = pd.DataFrame({\n 'timedelta': np.arange(start=0, stop=3 * 86400000,\n step=86400000,\n dtype='timedelta64[ms]')\n })\n pa.Table.from_pandas(df)\n\n def test_pytime_from_pandas(self):\n pytimes = [time(1, 2, 3, 1356),\n time(4, 5, 6, 1356)]\n\n # microseconds\n t1 = pa.time64('us')\n\n aobjs = np.array(pytimes + [None], dtype=object)\n parr = pa.array(aobjs)\n assert parr.type == t1\n assert parr[0].as_py() == pytimes[0]\n assert parr[1].as_py() == pytimes[1]\n assert parr[2] is pa.NA\n\n # DataFrame\n df = pd.DataFrame({'times': aobjs})\n batch = pa.RecordBatch.from_pandas(df)\n assert batch[0].equals(parr)\n\n # Test ndarray of int64 values\n arr = np.array([_pytime_to_micros(v) for v in pytimes],\n dtype='int64')\n\n a1 = pa.array(arr, type=pa.time64('us'))\n assert a1[0].as_py() == pytimes[0]\n\n a2 = pa.array(arr * 1000, type=pa.time64('ns'))\n assert a2[0].as_py() == pytimes[0]\n\n a3 = pa.array((arr / 1000).astype('i4'),\n type=pa.time32('ms'))\n assert a3[0].as_py() == pytimes[0].replace(microsecond=1000)\n\n a4 = pa.array((arr / 1000000).astype('i4'),\n type=pa.time32('s'))\n assert a4[0].as_py() == pytimes[0].replace(microsecond=0)\n\n def test_arrow_time_to_pandas(self):\n pytimes = [time(1, 2, 3, 1356),\n time(4, 5, 6, 1356),\n time(0, 0, 0)]\n\n expected = np.array(pytimes[:2] + [None])\n expected_ms = np.array([x.replace(microsecond=1000)\n for x in pytimes[:2]] +\n [None])\n expected_s = np.array([x.replace(microsecond=0)\n for x in pytimes[:2]] +\n [None])\n\n arr = np.array([_pytime_to_micros(v) for v in pytimes],\n dtype='int64')\n arr = np.array([_pytime_to_micros(v) for v in pytimes],\n dtype='int64')\n\n null_mask = np.array([False, False, True], dtype=bool)\n\n a1 = pa.array(arr, mask=null_mask, type=pa.time64('us'))\n a2 = pa.array(arr * 1000, mask=null_mask,\n type=pa.time64('ns'))\n\n a3 = pa.array((arr / 1000).astype('i4'), mask=null_mask,\n type=pa.time32('ms'))\n a4 = pa.array((arr / 1000000).astype('i4'), mask=null_mask,\n type=pa.time32('s'))\n\n names = ['time64[us]', 'time64[ns]', 'time32[ms]', 'time32[s]']\n batch = pa.RecordBatch.from_arrays([a1, a2, a3, a4], names)\n arr = a1.to_pandas()\n assert (arr == expected).all()\n\n arr = a2.to_pandas()\n assert (arr == expected).all()\n\n arr = a3.to_pandas()\n assert (arr == expected_ms).all()\n\n arr = a4.to_pandas()\n assert (arr == expected_s).all()\n\n df = batch.to_pandas()\n expected_df = pd.DataFrame({'time64[us]': expected,\n 'time64[ns]': expected,\n 'time32[ms]': expected_ms,\n 'time32[s]': expected_s},\n columns=names)\n\n tm.assert_frame_equal(df, expected_df)\n\n def test_numpy_datetime64_columns(self):\n datetime64_ns = np.array([\n '2007-07-13T01:23:34.123456789',\n None,\n '2006-01-13T12:34:56.432539784',\n '2010-08-13T05:46:57.437699912'],\n dtype='datetime64[ns]')\n _check_array_from_pandas_roundtrip(datetime64_ns)\n\n datetime64_us = np.array([\n '2007-07-13T01:23:34.123456',\n None,\n '2006-01-13T12:34:56.432539',\n '2010-08-13T05:46:57.437699'],\n dtype='datetime64[us]')\n _check_array_from_pandas_roundtrip(datetime64_us)\n\n datetime64_ms = np.array([\n '2007-07-13T01:23:34.123',\n None,\n '2006-01-13T12:34:56.432',\n '2010-08-13T05:46:57.437'],\n dtype='datetime64[ms]')\n _check_array_from_pandas_roundtrip(datetime64_ms)\n\n datetime64_s = np.array([\n '2007-07-13T01:23:34',\n None,\n '2006-01-13T12:34:56',\n '2010-08-13T05:46:57'],\n dtype='datetime64[s]')\n _check_array_from_pandas_roundtrip(datetime64_s)\n\n @pytest.mark.parametrize('dtype', [pa.date32(), pa.date64()])\n def test_numpy_datetime64_day_unit(self, dtype):\n datetime64_d = np.array([\n '2007-07-13',\n None,\n '2006-01-15',\n '2010-08-19'],\n dtype='datetime64[D]')\n _check_array_from_pandas_roundtrip(datetime64_d, type=dtype)\n\n def test_array_from_pandas_date_with_mask(self):\n m = np.array([True, False, True])\n data = pd.Series([\n date(1990, 1, 1),\n date(1991, 1, 1),\n date(1992, 1, 1)\n ])\n\n result = pa.Array.from_pandas(data, mask=m)\n\n expected = pd.Series([None, date(1991, 1, 1), None])\n assert pa.Array.from_pandas(expected).equals(result)\n\n def test_fixed_offset_timezone(self):\n df = pd.DataFrame({\n 'a': [\n pd.Timestamp('2012-11-11 00:00:00+01:00'),\n pd.NaT\n ]\n })\n _check_pandas_roundtrip(df)\n _check_serialize_components_roundtrip(df)\n\n# ----------------------------------------------------------------------\n# Conversion tests for string and binary types.\n\n\nclass TestConvertStringLikeTypes(object):\n\n def test_pandas_unicode(self):\n repeats = 1000\n values = [u'foo', None, u'bar', u'mañana', np.nan]\n df = pd.DataFrame({'strings': values * repeats})\n field = pa.field('strings', pa.string())\n schema = pa.schema([field])\n\n _check_pandas_roundtrip(df, expected_schema=schema)\n\n def test_bytes_to_binary(self):\n values = [u'qux', b'foo', None, bytearray(b'barz'), 'qux', np.nan]\n df = pd.DataFrame({'strings': values})\n\n table = pa.Table.from_pandas(df)\n assert table[0].type == pa.binary()\n\n values2 = [b'qux', b'foo', None, b'barz', b'qux', np.nan]\n expected = pd.DataFrame({'strings': values2})\n _check_pandas_roundtrip(df, expected)\n\n @pytest.mark.large_memory\n def test_bytes_exceed_2gb(self):\n v1 = b'x' * 100000000\n v2 = b'x' * 147483646\n\n # ARROW-2227, hit exactly 2GB on the nose\n df = pd.DataFrame({\n 'strings': [v1] * 20 + [v2] + ['x'] * 20\n })\n arr = pa.array(df['strings'])\n assert isinstance(arr, pa.ChunkedArray)\n assert arr.num_chunks == 2\n arr = None\n\n table = pa.Table.from_pandas(df)\n assert table[0].data.num_chunks == 2\n\n def test_fixed_size_bytes(self):\n values = [b'foo', None, bytearray(b'bar'), None, None, b'hey']\n df = pd.DataFrame({'strings': values})\n schema = pa.schema([pa.field('strings', pa.binary(3))])\n table = pa.Table.from_pandas(df, schema=schema)\n assert table.schema[0].type == schema[0].type\n assert table.schema[0].name == schema[0].name\n result = table.to_pandas()\n tm.assert_frame_equal(result, df)\n\n def test_fixed_size_bytes_does_not_accept_varying_lengths(self):\n values = [b'foo', None, b'ba', None, None, b'hey']\n df = pd.DataFrame({'strings': values})\n schema = pa.schema([pa.field('strings', pa.binary(3))])\n with pytest.raises(pa.ArrowInvalid):\n pa.Table.from_pandas(df, schema=schema)\n\n def test_variable_size_bytes(self):\n s = pd.Series([b'123', b'', b'a', None])\n _check_series_roundtrip(s, type_=pa.binary())\n\n def test_binary_from_bytearray(self):\n s = pd.Series([bytearray(b'123'), bytearray(b''), bytearray(b'a'),\n None])\n # Explicitly set type\n _check_series_roundtrip(s, type_=pa.binary())\n # Infer type from bytearrays\n _check_series_roundtrip(s, expected_pa_type=pa.binary())\n\n def test_table_empty_str(self):\n values = ['', '', '', '', '']\n df = pd.DataFrame({'strings': values})\n field = pa.field('strings', pa.string())\n schema = pa.schema([field])\n table = pa.Table.from_pandas(df, schema=schema)\n\n result1 = table.to_pandas(strings_to_categorical=False)\n expected1 = pd.DataFrame({'strings': values})\n tm.assert_frame_equal(result1, expected1, check_dtype=True)\n\n result2 = table.to_pandas(strings_to_categorical=True)\n expected2 = pd.DataFrame({'strings': pd.Categorical(values)})\n tm.assert_frame_equal(result2, expected2, check_dtype=True)\n\n def test_selective_categoricals(self):\n values = ['', '', '', '', '']\n df = pd.DataFrame({'strings': values})\n field = pa.field('strings', pa.string())\n schema = pa.schema([field])\n table = pa.Table.from_pandas(df, schema=schema)\n expected_str = pd.DataFrame({'strings': values})\n expected_cat = pd.DataFrame({'strings': pd.Categorical(values)})\n\n result1 = table.to_pandas(categories=['strings'])\n tm.assert_frame_equal(result1, expected_cat, check_dtype=True)\n result2 = table.to_pandas(categories=[])\n tm.assert_frame_equal(result2, expected_str, check_dtype=True)\n result3 = table.to_pandas(categories=('strings',))\n tm.assert_frame_equal(result3, expected_cat, check_dtype=True)\n result4 = table.to_pandas(categories=tuple())\n tm.assert_frame_equal(result4, expected_str, check_dtype=True)\n\n def test_table_str_to_categorical_without_na(self):\n values = ['a', 'a', 'b', 'b', 'c']\n df = pd.DataFrame({'strings': values})\n field = pa.field('strings', pa.string())\n schema = pa.schema([field])\n table = pa.Table.from_pandas(df, schema=schema)\n\n result = table.to_pandas(strings_to_categorical=True)\n expected = pd.DataFrame({'strings': pd.Categorical(values)})\n tm.assert_frame_equal(result, expected, check_dtype=True)\n\n with pytest.raises(pa.ArrowInvalid):\n table.to_pandas(strings_to_categorical=True,\n zero_copy_only=True)\n\n def test_table_str_to_categorical_with_na(self):\n values = [None, 'a', 'b', np.nan]\n df = pd.DataFrame({'strings': values})\n field = pa.field('strings', pa.string())\n schema = pa.schema([field])\n table = pa.Table.from_pandas(df, schema=schema)\n\n result = table.to_pandas(strings_to_categorical=True)\n expected = pd.DataFrame({'strings': pd.Categorical(values)})\n tm.assert_frame_equal(result, expected, check_dtype=True)\n\n with pytest.raises(pa.ArrowInvalid):\n table.to_pandas(strings_to_categorical=True,\n zero_copy_only=True)\n\n # Regression test for ARROW-2101\n def test_array_of_bytes_to_strings(self):\n converted = pa.array(np.array([b'x'], dtype=object), pa.string())\n assert converted.type == pa.string()\n\n # Make sure that if an ndarray of bytes is passed to the array\n # constructor and the type is string, it will fail if those bytes\n # cannot be converted to utf-8\n def test_array_of_bytes_to_strings_bad_data(self):\n with pytest.raises(\n pa.lib.ArrowInvalid,\n match=\"was not a utf8 string\"):\n pa.array(np.array([b'\\x80\\x81'], dtype=object), pa.string())\n\n def test_numpy_string_array_to_fixed_size_binary(self):\n arr = np.array([b'foo', b'bar', b'baz'], dtype='|S3')\n\n converted = pa.array(arr, type=pa.binary(3))\n expected = pa.array(list(arr), type=pa.binary(3))\n assert converted.equals(expected)\n\n mask = np.array([True, False, True])\n converted = pa.array(arr, type=pa.binary(3), mask=mask)\n expected = pa.array([b'foo', None, b'baz'], type=pa.binary(3))\n assert converted.equals(expected)\n\n with pytest.raises(pa.lib.ArrowInvalid,\n match='Got bytestring of length 3 \\(expected 4\\)'):\n arr = np.array([b'foo', b'bar', b'baz'], dtype='|S3')\n pa.array(arr, type=pa.binary(4))\n\n with pytest.raises(pa.lib.ArrowInvalid,\n match='Got bytestring of length 12 \\(expected 3\\)'):\n arr = np.array([b'foo', b'bar', b'baz'], dtype='|U3')\n pa.array(arr, type=pa.binary(3))\n\n\nclass TestConvertDecimalTypes(object):\n \"\"\"\n Conversion test for decimal types.\n \"\"\"\n decimal32 = [\n decimal.Decimal('-1234.123'),\n decimal.Decimal('1234.439')\n ]\n decimal64 = [\n decimal.Decimal('-129934.123331'),\n decimal.Decimal('129534.123731')\n ]\n decimal128 = [\n decimal.Decimal('394092382910493.12341234678'),\n decimal.Decimal('-314292388910493.12343437128')\n ]\n\n @pytest.mark.parametrize(('values', 'expected_type'), [\n pytest.param(decimal32, pa.decimal128(7, 3), id='decimal32'),\n pytest.param(decimal64, pa.decimal128(12, 6), id='decimal64'),\n pytest.param(decimal128, pa.decimal128(26, 11), id='decimal128')\n ])\n def test_decimal_from_pandas(self, values, expected_type):\n expected = pd.DataFrame({'decimals': values})\n table = pa.Table.from_pandas(expected, preserve_index=False)\n field = pa.field('decimals', expected_type)\n\n # schema's metadata is generated by from_pandas conversion\n expected_schema = pa.schema([field], metadata=table.schema.metadata)\n assert table.schema.equals(expected_schema)\n\n @pytest.mark.parametrize('values', [\n pytest.param(decimal32, id='decimal32'),\n pytest.param(decimal64, id='decimal64'),\n pytest.param(decimal128, id='decimal128')\n ])\n def test_decimal_to_pandas(self, values):\n expected = pd.DataFrame({'decimals': values})\n converted = pa.Table.from_pandas(expected)\n df = converted.to_pandas()\n tm.assert_frame_equal(df, expected)\n\n def test_decimal_fails_with_truncation(self):\n data1 = [decimal.Decimal('1.234')]\n type1 = pa.decimal128(10, 2)\n with pytest.raises(pa.ArrowInvalid):\n pa.array(data1, type=type1)\n\n data2 = [decimal.Decimal('1.2345')]\n type2 = pa.decimal128(10, 3)\n with pytest.raises(pa.ArrowInvalid):\n pa.array(data2, type=type2)\n\n def test_decimal_with_different_precisions(self):\n data = [\n decimal.Decimal('0.01'),\n decimal.Decimal('0.001'),\n ]\n series = pd.Series(data)\n array = pa.array(series)\n assert array.to_pylist() == data\n assert array.type == pa.decimal128(3, 3)\n\n array = pa.array(data, type=pa.decimal128(12, 5))\n expected = [decimal.Decimal('0.01000'), decimal.Decimal('0.00100')]\n assert array.to_pylist() == expected\n\n def test_decimal_with_None_explicit_type(self):\n series = pd.Series([decimal.Decimal('3.14'), None])\n _check_series_roundtrip(series, type_=pa.decimal128(12, 5))\n\n # Test that having all None values still produces decimal array\n series = pd.Series([None] * 2)\n _check_series_roundtrip(series, type_=pa.decimal128(12, 5))\n\n def test_decimal_with_None_infer_type(self):\n series = pd.Series([decimal.Decimal('3.14'), None])\n _check_series_roundtrip(series, expected_pa_type=pa.decimal128(3, 2))\n\n def test_strided_objects(self, tmpdir):\n # see ARROW-3053\n data = {\n 'a': {0: 'a'},\n 'b': {0: decimal.Decimal('0.0')}\n }\n\n # This yields strided objects\n df = pd.DataFrame.from_dict(data)\n _check_pandas_roundtrip(df)\n\n\nclass TestListTypes(object):\n \"\"\"\n Conversion tests for list<> types.\n \"\"\"\n\n def test_column_of_arrays(self):\n df, schema = dataframe_with_arrays()\n _check_pandas_roundtrip(df, schema=schema, expected_schema=schema)\n table = pa.Table.from_pandas(df, schema=schema, preserve_index=False)\n\n # schema's metadata is generated by from_pandas conversion\n expected_schema = schema.add_metadata(table.schema.metadata)\n assert table.schema.equals(expected_schema)\n\n for column in df.columns:\n field = schema.field_by_name(column)\n _check_array_roundtrip(df[column], type=field.type)\n\n def test_column_of_arrays_to_py(self):\n # Test regression in ARROW-1199 not caught in above test\n dtype = 'i1'\n arr = np.array([\n np.arange(10, dtype=dtype),\n np.arange(5, dtype=dtype),\n None,\n np.arange(1, dtype=dtype)\n ])\n type_ = pa.list_(pa.int8())\n parr = pa.array(arr, type=type_)\n\n assert parr[0].as_py() == list(range(10))\n assert parr[1].as_py() == list(range(5))\n assert parr[2].as_py() is None\n assert parr[3].as_py() == [0]\n\n def test_column_of_lists(self):\n df, schema = dataframe_with_lists()\n _check_pandas_roundtrip(df, schema=schema, expected_schema=schema)\n table = pa.Table.from_pandas(df, schema=schema, preserve_index=False)\n\n # schema's metadata is generated by from_pandas conversion\n expected_schema = schema.add_metadata(table.schema.metadata)\n assert table.schema.equals(expected_schema)\n\n for column in df.columns:\n field = schema.field_by_name(column)\n _check_array_roundtrip(df[column], type=field.type)\n\n def test_column_of_lists_first_empty(self):\n # ARROW-2124\n num_lists = [[], [2, 3, 4], [3, 6, 7, 8], [], [2]]\n series = pd.Series([np.array(s, dtype=float) for s in num_lists])\n arr = pa.array(series)\n result = pd.Series(arr.to_pandas())\n tm.assert_series_equal(result, series)\n\n def test_column_of_lists_chunked(self):\n # ARROW-1357\n df = pd.DataFrame({\n 'lists': np.array([\n [1, 2],\n None,\n [2, 3],\n [4, 5],\n [6, 7],\n [8, 9]\n ], dtype=object)\n })\n\n schema = pa.schema([\n pa.field('lists', pa.list_(pa.int64()))\n ])\n\n t1 = pa.Table.from_pandas(df[:2], schema=schema)\n t2 = pa.Table.from_pandas(df[2:], schema=schema)\n\n table = pa.concat_tables([t1, t2])\n result = table.to_pandas()\n\n tm.assert_frame_equal(result, df)\n\n def test_column_of_lists_chunked2(self):\n data1 = [[0, 1], [2, 3], [4, 5], [6, 7], [10, 11],\n [12, 13], [14, 15], [16, 17]]\n data2 = [[8, 9], [18, 19]]\n\n a1 = pa.array(data1)\n a2 = pa.array(data2)\n\n t1 = pa.Table.from_arrays([a1], names=['a'])\n t2 = pa.Table.from_arrays([a2], names=['a'])\n\n concatenated = pa.concat_tables([t1, t2])\n\n result = concatenated.to_pandas()\n expected = pd.DataFrame({'a': data1 + data2})\n\n tm.assert_frame_equal(result, expected)\n\n def test_column_of_lists_strided(self):\n df, schema = dataframe_with_lists()\n df = pd.concat([df] * 6, ignore_index=True)\n\n arr = df['int64'].values[::3]\n assert arr.strides[0] != 8\n\n _check_array_roundtrip(arr)\n\n def test_nested_lists_all_none(self):\n data = np.array([[None, None], None], dtype=object)\n\n arr = pa.array(data)\n expected = pa.array(list(data))\n assert arr.equals(expected)\n assert arr.type == pa.list_(pa.null())\n\n data2 = np.array([None, None, [None, None],\n np.array([None, None], dtype=object)],\n dtype=object)\n arr = pa.array(data2)\n expected = pa.array([None, None, [None, None], [None, None]])\n assert arr.equals(expected)\n\n def test_nested_lists_all_empty(self):\n # ARROW-2128\n data = pd.Series([[], [], []])\n arr = pa.array(data)\n expected = pa.array(list(data))\n assert arr.equals(expected)\n assert arr.type == pa.list_(pa.null())\n\n def test_nested_list_first_empty(self):\n # ARROW-2711\n data = pd.Series([[], [u\"a\"]])\n arr = pa.array(data)\n expected = pa.array(list(data))\n assert arr.equals(expected)\n assert arr.type == pa.list_(pa.string())\n\n def test_nested_smaller_ints(self):\n # ARROW-1345, ARROW-2008, there were some type inference bugs happening\n # before\n data = pd.Series([np.array([1, 2, 3], dtype='i1'), None])\n result = pa.array(data)\n result2 = pa.array(data.values)\n expected = pa.array([[1, 2, 3], None], type=pa.list_(pa.int8()))\n assert result.equals(expected)\n assert result2.equals(expected)\n\n data3 = pd.Series([np.array([1, 2, 3], dtype='f4'), None])\n result3 = pa.array(data3)\n expected3 = pa.array([[1, 2, 3], None], type=pa.list_(pa.float32()))\n assert result3.equals(expected3)\n\n def test_infer_lists(self):\n data = OrderedDict([\n ('nan_ints', [[None, 1], [2, 3]]),\n ('ints', [[0, 1], [2, 3]]),\n ('strs', [[None, u'b'], [u'c', u'd']]),\n ('nested_strs', [[[None, u'b'], [u'c', u'd']], None])\n ])\n df = pd.DataFrame(data)\n\n expected_schema = pa.schema([\n pa.field('nan_ints', pa.list_(pa.int64())),\n pa.field('ints', pa.list_(pa.int64())),\n pa.field('strs', pa.list_(pa.string())),\n pa.field('nested_strs', pa.list_(pa.list_(pa.string())))\n ])\n\n _check_pandas_roundtrip(df, expected_schema=expected_schema)\n\n def test_infer_numpy_array(self):\n data = OrderedDict([\n ('ints', [\n np.array([0, 1], dtype=np.int64),\n np.array([2, 3], dtype=np.int64)\n ])\n ])\n df = pd.DataFrame(data)\n expected_schema = pa.schema([\n pa.field('ints', pa.list_(pa.int64()))\n ])\n\n _check_pandas_roundtrip(df, expected_schema=expected_schema)\n\n @pytest.mark.parametrize('t,data,expected', [\n (\n pa.int64,\n [[1, 2], [3], None],\n [None, [3], None]\n ),\n (\n pa.string,\n [[u'aaa', u'bb'], [u'c'], None],\n [None, [u'c'], None]\n ),\n (\n pa.null,\n [[None, None], [None], None],\n [None, [None], None]\n )\n ])\n def test_array_from_pandas_typed_array_with_mask(self, t, data, expected):\n m = np.array([True, False, True])\n\n s = pd.Series(data)\n result = pa.Array.from_pandas(s, mask=m, type=pa.list_(t()))\n\n assert pa.Array.from_pandas(expected,\n type=pa.list_(t())).equals(result)\n\n def test_empty_list_roundtrip(self):\n empty_list_array = np.empty((3,), dtype=object)\n empty_list_array.fill([])\n\n df = pd.DataFrame({'a': np.array(['1', '2', '3']),\n 'b': empty_list_array})\n tbl = pa.Table.from_pandas(df)\n\n result = tbl.to_pandas()\n\n tm.assert_frame_equal(result, df)\n\n def test_array_from_nested_arrays(self):\n df, schema = dataframe_with_arrays()\n for field in schema:\n arr = df[field.name].values\n expected = pa.array(list(arr), type=field.type)\n result = pa.array(arr)\n assert result.type == field.type # == list<scalar>\n assert result.equals(expected)\n\n\nclass TestConvertStructTypes(object):\n \"\"\"\n Conversion tests for struct types.\n \"\"\"\n\n def test_to_pandas(self):\n ints = pa.array([None, 2, 3], type=pa.int64())\n strs = pa.array([u'a', None, u'c'], type=pa.string())\n bools = pa.array([True, False, None], type=pa.bool_())\n arr = pa.StructArray.from_arrays(\n [ints, strs, bools],\n ['ints', 'strs', 'bools'])\n\n expected = pd.Series([\n {'ints': None, 'strs': u'a', 'bools': True},\n {'ints': 2, 'strs': None, 'bools': False},\n {'ints': 3, 'strs': u'c', 'bools': None},\n ])\n\n series = pd.Series(arr.to_pandas())\n tm.assert_series_equal(series, expected)\n\n def test_from_numpy(self):\n dt = np.dtype([('x', np.int32),\n (('y_title', 'y'), np.bool_)])\n ty = pa.struct([pa.field('x', pa.int32()),\n pa.field('y', pa.bool_())])\n\n data = np.array([], dtype=dt)\n arr = pa.array(data, type=ty)\n assert arr.to_pylist() == []\n\n data = np.array([(42, True), (43, False)], dtype=dt)\n arr = pa.array(data, type=ty)\n assert arr.to_pylist() == [{'x': 42, 'y': True},\n {'x': 43, 'y': False}]\n\n # With mask\n arr = pa.array(data, mask=np.bool_([False, True]), type=ty)\n assert arr.to_pylist() == [{'x': 42, 'y': True}, None]\n\n # Trivial struct type\n dt = np.dtype([])\n ty = pa.struct([])\n\n data = np.array([], dtype=dt)\n arr = pa.array(data, type=ty)\n assert arr.to_pylist() == []\n\n data = np.array([(), ()], dtype=dt)\n arr = pa.array(data, type=ty)\n assert arr.to_pylist() == [{}, {}]\n\n def test_from_numpy_nested(self):\n dt = np.dtype([('x', np.dtype([('xx', np.int8),\n ('yy', np.bool_)])),\n ('y', np.int16)])\n ty = pa.struct([pa.field('x', pa.struct([pa.field('xx', pa.int8()),\n pa.field('yy', pa.bool_())])),\n pa.field('y', pa.int16())])\n\n data = np.array([], dtype=dt)\n arr = pa.array(data, type=ty)\n assert arr.to_pylist() == []\n\n data = np.array([((1, True), 2), ((3, False), 4)], dtype=dt)\n arr = pa.array(data, type=ty)\n assert arr.to_pylist() == [{'x': {'xx': 1, 'yy': True}, 'y': 2},\n {'x': {'xx': 3, 'yy': False}, 'y': 4}]\n\n @pytest.mark.large_memory\n def test_from_numpy_large(self):\n # Exercise rechunking + nulls\n target_size = 3 * 1024**3 # 4GB\n dt = np.dtype([('x', np.float64), ('y', 'object')])\n bs = 65536 - dt.itemsize\n block = b'.' * bs\n n = target_size // (bs + dt.itemsize)\n data = np.zeros(n, dtype=dt)\n data['x'] = np.random.random_sample(n)\n data['y'] = block\n # Add implicit nulls\n data['x'][data['x'] < 0.2] = np.nan\n\n ty = pa.struct([pa.field('x', pa.float64()),\n pa.field('y', pa.binary(bs))])\n arr = pa.array(data, type=ty, from_pandas=True)\n assert arr.num_chunks == 2\n\n def iter_chunked_array(arr):\n for chunk in arr.iterchunks():\n for item in chunk:\n yield item\n\n def check(arr, data, mask=None):\n assert len(arr) == len(data)\n xs = data['x']\n ys = data['y']\n for i, obj in enumerate(iter_chunked_array(arr)):\n try:\n d = obj.as_py()\n if mask is not None and mask[i]:\n assert d is None\n else:\n x = xs[i]\n if np.isnan(x):\n assert d['x'] is None\n else:\n assert d['x'] == x\n assert d['y'] == ys[i]\n except Exception:\n print(\"Failed at index\", i)\n raise\n\n check(arr, data)\n del arr\n\n # Now with explicit mask\n mask = np.random.random_sample(n) < 0.2\n arr = pa.array(data, type=ty, mask=mask, from_pandas=True)\n assert arr.num_chunks == 2\n\n check(arr, data, mask)\n del arr\n\n def test_from_numpy_bad_input(self):\n ty = pa.struct([pa.field('x', pa.int32()),\n pa.field('y', pa.bool_())])\n dt = np.dtype([('x', np.int32),\n ('z', np.bool_)])\n\n data = np.array([], dtype=dt)\n with pytest.raises(TypeError,\n match=\"Missing field 'y'\"):\n pa.array(data, type=ty)\n data = np.int32([])\n with pytest.raises(TypeError,\n match=\"Expected struct array\"):\n pa.array(data, type=ty)\n\n\nclass TestZeroCopyConversion(object):\n \"\"\"\n Tests that zero-copy conversion works with some types.\n \"\"\"\n\n def test_zero_copy_success(self):\n result = pa.array([0, 1, 2]).to_pandas(zero_copy_only=True)\n npt.assert_array_equal(result, [0, 1, 2])\n\n def test_zero_copy_dictionaries(self):\n arr = pa.DictionaryArray.from_arrays(\n np.array([0, 0]),\n np.array([5]))\n\n result = arr.to_pandas(zero_copy_only=True)\n values = pd.Categorical([5, 5])\n\n tm.assert_series_equal(pd.Series(result), pd.Series(values),\n check_names=False)\n\n def check_zero_copy_failure(self, arr):\n with pytest.raises(pa.ArrowInvalid):\n arr.to_pandas(zero_copy_only=True)\n\n def test_zero_copy_failure_on_object_types(self):\n self.check_zero_copy_failure(pa.array(['A', 'B', 'C']))\n\n def test_zero_copy_failure_with_int_when_nulls(self):\n self.check_zero_copy_failure(pa.array([0, 1, None]))\n\n def test_zero_copy_failure_with_float_when_nulls(self):\n self.check_zero_copy_failure(pa.array([0.0, 1.0, None]))\n\n def test_zero_copy_failure_on_bool_types(self):\n self.check_zero_copy_failure(pa.array([True, False]))\n\n def test_zero_copy_failure_on_list_types(self):\n arr = pa.array([[1, 2], [8, 9]], type=pa.list_(pa.int64()))\n self.check_zero_copy_failure(arr)\n\n def test_zero_copy_failure_on_timestamp_types(self):\n arr = np.array(['2007-07-13'], dtype='datetime64[ns]')\n self.check_zero_copy_failure(pa.array(arr))\n\n\n# This function must be at the top-level for Python 2.7's multiprocessing\ndef _threaded_conversion():\n df = _alltypes_example()\n _check_pandas_roundtrip(df, use_threads=True)\n _check_pandas_roundtrip(df, use_threads=True, as_batch=True)\n\n\nclass TestConvertMisc(object):\n \"\"\"\n Miscellaneous conversion tests.\n \"\"\"\n\n type_pairs = [\n (np.int8, pa.int8()),\n (np.int16, pa.int16()),\n (np.int32, pa.int32()),\n (np.int64, pa.int64()),\n (np.uint8, pa.uint8()),\n (np.uint16, pa.uint16()),\n (np.uint32, pa.uint32()),\n (np.uint64, pa.uint64()),\n (np.float16, pa.float16()),\n (np.float32, pa.float32()),\n (np.float64, pa.float64()),\n # XXX unsupported\n # (np.dtype([('a', 'i2')]), pa.struct([pa.field('a', pa.int16())])),\n (np.object, pa.string()),\n (np.object, pa.binary()),\n (np.object, pa.binary(10)),\n (np.object, pa.list_(pa.int64())),\n ]\n\n def test_all_none_objects(self):\n df = pd.DataFrame({'a': [None, None, None]})\n _check_pandas_roundtrip(df)\n\n def test_all_none_category(self):\n df = pd.DataFrame({'a': [None, None, None]})\n df['a'] = df['a'].astype('category')\n _check_pandas_roundtrip(df)\n\n def test_empty_arrays(self):\n for dtype, pa_type in self.type_pairs:\n arr = np.array([], dtype=dtype)\n _check_array_roundtrip(arr, type=pa_type)\n\n def test_threaded_conversion(self):\n _threaded_conversion()\n\n def test_threaded_conversion_multiprocess(self):\n # Parallel conversion should work from child processes too (ARROW-2963)\n pool = mp.Pool(2)\n try:\n pool.apply(_threaded_conversion)\n finally:\n pool.close()\n pool.join()\n\n def test_category(self):\n repeats = 5\n v1 = ['foo', None, 'bar', 'qux', np.nan]\n v2 = [4, 5, 6, 7, 8]\n v3 = [b'foo', None, b'bar', b'qux', np.nan]\n df = pd.DataFrame({'cat_strings': pd.Categorical(v1 * repeats),\n 'cat_ints': pd.Categorical(v2 * repeats),\n 'cat_binary': pd.Categorical(v3 * repeats),\n 'cat_strings_ordered': pd.Categorical(\n v1 * repeats, categories=['bar', 'qux', 'foo'],\n ordered=True),\n 'ints': v2 * repeats,\n 'ints2': v2 * repeats,\n 'strings': v1 * repeats,\n 'strings2': v1 * repeats,\n 'strings3': v3 * repeats})\n _check_pandas_roundtrip(df)\n\n arrays = [\n pd.Categorical(v1 * repeats),\n pd.Categorical(v2 * repeats),\n pd.Categorical(v3 * repeats)\n ]\n for values in arrays:\n _check_array_roundtrip(values)\n\n def test_empty_category(self):\n # ARROW-2443\n df = pd.DataFrame({'cat': pd.Categorical([])})\n _check_pandas_roundtrip(df)\n\n def test_mixed_types_fails(self):\n data = pd.DataFrame({'a': ['a', 1, 2.0]})\n with pytest.raises(pa.ArrowTypeError):\n pa.Table.from_pandas(data)\n\n data = pd.DataFrame({'a': [1, True]})\n with pytest.raises(pa.ArrowTypeError):\n pa.Table.from_pandas(data)\n\n data = pd.DataFrame({'a': ['a', 1, 2.0]})\n expected_msg = 'Conversion failed for column a'\n with pytest.raises(pa.ArrowTypeError, match=expected_msg):\n pa.Table.from_pandas(data)\n\n def test_strided_data_import(self):\n cases = []\n\n columns = ['a', 'b', 'c']\n N, K = 100, 3\n random_numbers = np.random.randn(N, K).copy() * 100\n\n numeric_dtypes = ['i1', 'i2', 'i4', 'i8', 'u1', 'u2', 'u4', 'u8',\n 'f4', 'f8']\n\n for type_name in numeric_dtypes:\n cases.append(random_numbers.astype(type_name))\n\n # strings\n cases.append(np.array([tm.rands(10) for i in range(N * K)],\n dtype=object)\n .reshape(N, K).copy())\n\n # booleans\n boolean_objects = (np.array([True, False, True] * N, dtype=object)\n .reshape(N, K).copy())\n\n # add some nulls, so dtype comes back as objects\n boolean_objects[5] = None\n cases.append(boolean_objects)\n\n cases.append(np.arange(\"2016-01-01T00:00:00.001\", N * K,\n dtype='datetime64[ms]')\n .reshape(N, K).copy())\n\n strided_mask = (random_numbers > 0).astype(bool)[:, 0]\n\n for case in cases:\n df = pd.DataFrame(case, columns=columns)\n col = df['a']\n\n _check_pandas_roundtrip(df)\n _check_array_roundtrip(col)\n _check_array_roundtrip(col, mask=strided_mask)\n\n def test_all_nones(self):\n def _check_series(s):\n converted = pa.array(s)\n assert isinstance(converted, pa.NullArray)\n assert len(converted) == 3\n assert converted.null_count == 3\n assert converted[0] is pa.NA\n\n _check_series(pd.Series([None] * 3, dtype=object))\n _check_series(pd.Series([np.nan] * 3, dtype=object))\n _check_series(pd.Series([np.sqrt(-1)] * 3, dtype=object))\n\n def test_partial_schema(self):\n data = OrderedDict([\n ('a', [0, 1, 2, 3, 4]),\n ('b', np.array([-10, -5, 0, 5, 10], dtype=np.int32)),\n ('c', [-10, -5, 0, 5, 10])\n ])\n df = pd.DataFrame(data)\n\n partial_schema = pa.schema([\n pa.field('a', pa.int64()),\n pa.field('b', pa.int32())\n ])\n\n expected_schema = pa.schema([\n pa.field('a', pa.int64()),\n pa.field('b', pa.int32()),\n pa.field('c', pa.int64())\n ])\n\n _check_pandas_roundtrip(df, schema=partial_schema,\n expected_schema=expected_schema)\n\n def test_table_batch_empty_dataframe(self):\n df = pd.DataFrame({})\n _check_pandas_roundtrip(df)\n _check_pandas_roundtrip(df, as_batch=True)\n\n df2 = pd.DataFrame({}, index=[0, 1, 2])\n _check_pandas_roundtrip(df2, preserve_index=True)\n _check_pandas_roundtrip(df2, as_batch=True, preserve_index=True)\n\n def test_convert_empty_table(self):\n arr = pa.array([], type=pa.int64())\n tm.assert_almost_equal(arr.to_pandas(), np.array([], dtype=np.int64))\n arr = pa.array([], type=pa.string())\n tm.assert_almost_equal(arr.to_pandas(), np.array([], dtype=object))\n arr = pa.array([], type=pa.list_(pa.int64()))\n tm.assert_almost_equal(arr.to_pandas(), np.array([], dtype=object))\n arr = pa.array([], type=pa.struct([pa.field('a', pa.int64())]))\n tm.assert_almost_equal(arr.to_pandas(), np.array([], dtype=object))\n\n def test_non_natural_stride(self):\n \"\"\"\n ARROW-2172: converting from a Numpy array with a stride that's\n not a multiple of itemsize.\n \"\"\"\n dtype = np.dtype([('x', np.int32), ('y', np.int16)])\n data = np.array([(42, -1), (-43, 2)], dtype=dtype)\n assert data.strides == (6,)\n arr = pa.array(data['x'], type=pa.int32())\n assert arr.to_pylist() == [42, -43]\n arr = pa.array(data['y'], type=pa.int16())\n assert arr.to_pylist() == [-1, 2]\n\n def test_mixed_integer_columns(self):\n row = [[], []]\n df = pd.DataFrame(data=[row], columns=['foo', 123])\n expected_df = pd.DataFrame(data=[row], columns=['foo', '123'])\n _check_pandas_roundtrip(df, expected=expected_df, preserve_index=True)\n\n\ndef _fully_loaded_dataframe_example():\n from distutils.version import LooseVersion\n\n index = pd.MultiIndex.from_arrays([\n pd.date_range('2000-01-01', periods=5).repeat(2),\n np.tile(np.array(['foo', 'bar'], dtype=object), 5)\n ])\n\n c1 = pd.date_range('2000-01-01', periods=10)\n data = {\n 0: c1,\n 1: c1.tz_localize('utc'),\n 2: c1.tz_localize('US/Eastern'),\n 3: c1[::2].tz_localize('utc').repeat(2).astype('category'),\n 4: ['foo', 'bar'] * 5,\n 5: pd.Series(['foo', 'bar'] * 5).astype('category').values,\n 6: [True, False] * 5,\n 7: np.random.randn(10),\n 8: np.random.randint(0, 100, size=10),\n 9: pd.period_range('2013', periods=10, freq='M')\n }\n\n if LooseVersion(pd.__version__) >= '0.21':\n # There is an issue with pickling IntervalIndex in pandas 0.20.x\n data[10] = pd.interval_range(start=1, freq=1, periods=10)\n\n return pd.DataFrame(data, index=index)\n\n\[email protected]('columns', ([b'foo'], ['foo']))\ndef test_roundtrip_with_bytes_unicode(columns):\n df = pd.DataFrame(columns=columns)\n table1 = pa.Table.from_pandas(df)\n table2 = pa.Table.from_pandas(table1.to_pandas())\n assert table1.equals(table2)\n assert table1.schema.equals(table2.schema)\n assert table1.schema.metadata == table2.schema.metadata\n\n\ndef _check_serialize_components_roundtrip(df):\n ctx = pa.default_serialization_context()\n\n components = ctx.serialize(df).to_components()\n deserialized = ctx.deserialize_components(components)\n\n tm.assert_frame_equal(df, deserialized)\n\n\ndef test_serialize_deserialize_pandas():\n # ARROW-1784, serialize and deserialize DataFrame by decomposing\n # BlockManager\n df = _fully_loaded_dataframe_example()\n _check_serialize_components_roundtrip(df)\n\n\ndef _pytime_from_micros(val):\n microseconds = val % 1000000\n val //= 1000000\n seconds = val % 60\n val //= 60\n minutes = val % 60\n hours = val // 60\n return time(hours, minutes, seconds, microseconds)\n\n\ndef _pytime_to_micros(pytime):\n return (pytime.hour * 3600000000 +\n pytime.minute * 60000000 +\n pytime.second * 1000000 +\n pytime.microsecond)\n\n\ndef test_convert_unsupported_type_error_message():\n # ARROW-1454\n\n df = pd.DataFrame({\n 't1': pd.date_range('2000-01-01', periods=20),\n 't2': pd.date_range('2000-05-01', periods=20)\n })\n\n # timedelta64 as yet unsupported\n df['diff'] = df.t2 - df.t1\n\n expected_msg = 'Conversion failed for column diff with type timedelta64'\n with pytest.raises(pa.ArrowNotImplementedError, match=expected_msg):\n pa.Table.from_pandas(df)\n"
] | [
[
"pandas.to_datetime",
"pandas.Series",
"numpy.sqrt",
"numpy.random.random_sample",
"pandas.DataFrame",
"numpy.dtype",
"pandas.util.testing.assert_frame_equal",
"numpy.random.randn",
"numpy.iinfo",
"numpy.bool_",
"numpy.random.randint",
"numpy.testing.assert_equal",
"numpy.arange",
"pandas.util.testing.assert_series_equal",
"pandas.Index",
"pandas.DatetimeIndex",
"numpy.zeros",
"pandas.to_numeric",
"pandas.concat",
"pandas.interval_range",
"numpy.isnan",
"pandas.Categorical",
"numpy.int64",
"pandas.date_range",
"pandas.DataFrame.from_dict",
"numpy.array",
"pandas.isnull",
"numpy.random.seed",
"pandas.period_range",
"numpy.int32",
"pandas.MultiIndex.from_arrays",
"numpy.testing.assert_array_equal",
"pandas.util.testing.rands",
"numpy.float64",
"numpy.ma.masked_array",
"pandas.Timestamp",
"numpy.empty"
]
] |
shuaggar-sys/pandas | [
"f79468b8642be1ebc24b806117505a6fa7bf50b7"
] | [
"pandas/core/dtypes/cast.py"
] | [
"\"\"\"\nRoutines for casting.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom contextlib import suppress\nfrom datetime import datetime, timedelta\nfrom typing import (\n TYPE_CHECKING,\n Any,\n Dict,\n List,\n Optional,\n Sequence,\n Set,\n Sized,\n Tuple,\n Type,\n Union,\n cast,\n)\nimport warnings\n\nimport numpy as np\n\nfrom pandas._libs import lib, missing as libmissing, tslib\nfrom pandas._libs.tslibs import (\n NaT,\n OutOfBoundsDatetime,\n OutOfBoundsTimedelta,\n Period,\n Timedelta,\n Timestamp,\n conversion,\n iNaT,\n ints_to_pydatetime,\n tz_compare,\n)\nfrom pandas._typing import AnyArrayLike, ArrayLike, Dtype, DtypeObj, Scalar\nfrom pandas.util._exceptions import find_stack_level\nfrom pandas.util._validators import validate_bool_kwarg\n\nfrom pandas.core.dtypes.common import (\n DT64NS_DTYPE,\n POSSIBLY_CAST_DTYPES,\n TD64NS_DTYPE,\n ensure_int8,\n ensure_int16,\n ensure_int32,\n ensure_int64,\n ensure_object,\n ensure_str,\n is_bool,\n is_bool_dtype,\n is_categorical_dtype,\n is_complex,\n is_complex_dtype,\n is_datetime64_dtype,\n is_datetime64_ns_dtype,\n is_datetime64tz_dtype,\n is_dtype_equal,\n is_extension_array_dtype,\n is_float,\n is_float_dtype,\n is_integer,\n is_integer_dtype,\n is_numeric_dtype,\n is_object_dtype,\n is_scalar,\n is_sparse,\n is_string_dtype,\n is_timedelta64_dtype,\n is_timedelta64_ns_dtype,\n is_unsigned_integer_dtype,\n)\nfrom pandas.core.dtypes.dtypes import (\n DatetimeTZDtype,\n ExtensionDtype,\n IntervalDtype,\n PeriodDtype,\n)\nfrom pandas.core.dtypes.generic import (\n ABCDataFrame,\n ABCExtensionArray,\n ABCIndex,\n ABCSeries,\n)\nfrom pandas.core.dtypes.inference import is_list_like\nfrom pandas.core.dtypes.missing import is_valid_nat_for_dtype, isna, notna\n\nif TYPE_CHECKING:\n from pandas import Series\n from pandas.core.arrays import DatetimeArray, ExtensionArray\n\n_int8_max = np.iinfo(np.int8).max\n_int16_max = np.iinfo(np.int16).max\n_int32_max = np.iinfo(np.int32).max\n_int64_max = np.iinfo(np.int64).max\n\n\ndef maybe_convert_platform(values):\n \"\"\" try to do platform conversion, allow ndarray or list here \"\"\"\n if isinstance(values, (list, tuple, range)):\n values = construct_1d_object_array_from_listlike(values)\n if getattr(values, \"dtype\", None) == np.object_:\n if hasattr(values, \"_values\"):\n values = values._values\n values = lib.maybe_convert_objects(values)\n\n return values\n\n\ndef is_nested_object(obj) -> bool:\n \"\"\"\n return a boolean if we have a nested object, e.g. a Series with 1 or\n more Series elements\n\n This may not be necessarily be performant.\n\n \"\"\"\n return bool(\n isinstance(obj, ABCSeries)\n and is_object_dtype(obj.dtype)\n and any(isinstance(v, ABCSeries) for v in obj._values)\n )\n\n\ndef maybe_box_datetimelike(value: Scalar, dtype: Optional[Dtype] = None) -> Scalar:\n \"\"\"\n Cast scalar to Timestamp or Timedelta if scalar is datetime-like\n and dtype is not object.\n\n Parameters\n ----------\n value : scalar\n dtype : Dtype, optional\n\n Returns\n -------\n scalar\n \"\"\"\n if dtype == object:\n pass\n elif isinstance(value, (np.datetime64, datetime)):\n value = Timestamp(value)\n elif isinstance(value, (np.timedelta64, timedelta)):\n value = Timedelta(value)\n\n return value\n\n\ndef maybe_unbox_datetimelike(value: Scalar, dtype: DtypeObj) -> Scalar:\n \"\"\"\n Convert a Timedelta or Timestamp to timedelta64 or datetime64 for setting\n into a numpy array. Failing to unbox would risk dropping nanoseconds.\n\n Notes\n -----\n Caller is responsible for checking dtype.kind in [\"m\", \"M\"]\n \"\"\"\n if is_valid_nat_for_dtype(value, dtype):\n # GH#36541: can't fill array directly with pd.NaT\n # > np.empty(10, dtype=\"datetime64[64]\").fill(pd.NaT)\n # ValueError: cannot convert float NaN to integer\n value = dtype.type(\"NaT\", \"ns\")\n elif isinstance(value, Timestamp):\n if value.tz is None:\n value = value.to_datetime64()\n elif isinstance(value, Timedelta):\n value = value.to_timedelta64()\n\n _disallow_mismatched_datetimelike(value, dtype)\n return value\n\n\ndef _disallow_mismatched_datetimelike(value, dtype: DtypeObj):\n \"\"\"\n numpy allows np.array(dt64values, dtype=\"timedelta64[ns]\") and\n vice-versa, but we do not want to allow this, so we need to\n check explicitly\n \"\"\"\n vdtype = getattr(value, \"dtype\", None)\n if vdtype is None:\n return\n elif (vdtype.kind == \"m\" and dtype.kind == \"M\") or (\n vdtype.kind == \"M\" and dtype.kind == \"m\"\n ):\n raise TypeError(f\"Cannot cast {repr(value)} to {dtype}\")\n\n\ndef maybe_downcast_to_dtype(result, dtype: Union[str, np.dtype]):\n \"\"\"\n try to cast to the specified dtype (e.g. convert back to bool/int\n or could be an astype of float64->float32\n \"\"\"\n do_round = False\n\n if is_scalar(result):\n return result\n elif isinstance(result, ABCDataFrame):\n # occurs in pivot_table doctest\n return result\n\n if isinstance(dtype, str):\n if dtype == \"infer\":\n inferred_type = lib.infer_dtype(ensure_object(result), skipna=False)\n if inferred_type == \"boolean\":\n dtype = \"bool\"\n elif inferred_type == \"integer\":\n dtype = \"int64\"\n elif inferred_type == \"datetime64\":\n dtype = \"datetime64[ns]\"\n elif inferred_type == \"timedelta64\":\n dtype = \"timedelta64[ns]\"\n\n # try to upcast here\n elif inferred_type == \"floating\":\n dtype = \"int64\"\n if issubclass(result.dtype.type, np.number):\n do_round = True\n\n else:\n dtype = \"object\"\n\n dtype = np.dtype(dtype)\n\n elif dtype.type is Period:\n from pandas.core.arrays import PeriodArray\n\n with suppress(TypeError):\n # e.g. TypeError: int() argument must be a string, a\n # bytes-like object or a number, not 'Period\n return PeriodArray(result, freq=dtype.freq)\n\n converted = maybe_downcast_numeric(result, dtype, do_round)\n if converted is not result:\n return converted\n\n # a datetimelike\n # GH12821, iNaT is cast to float\n if dtype.kind in [\"M\", \"m\"] and result.dtype.kind in [\"i\", \"f\"]:\n if isinstance(dtype, DatetimeTZDtype):\n # convert to datetime and change timezone\n i8values = result.astype(\"i8\", copy=False)\n cls = dtype.construct_array_type()\n # equiv: DatetimeArray(i8values).tz_localize(\"UTC\").tz_convert(dtype.tz)\n result = cls._simple_new(i8values, dtype=dtype)\n else:\n result = result.astype(dtype)\n\n return result\n\n\ndef maybe_downcast_numeric(result, dtype: DtypeObj, do_round: bool = False):\n \"\"\"\n Subset of maybe_downcast_to_dtype restricted to numeric dtypes.\n\n Parameters\n ----------\n result : ndarray or ExtensionArray\n dtype : np.dtype or ExtensionDtype\n do_round : bool\n\n Returns\n -------\n ndarray or ExtensionArray\n \"\"\"\n if not isinstance(dtype, np.dtype):\n # e.g. SparseDtype has no itemsize attr\n return result\n\n def trans(x):\n if do_round:\n return x.round()\n return x\n\n if dtype.kind == result.dtype.kind:\n # don't allow upcasts here (except if empty)\n if result.dtype.itemsize <= dtype.itemsize and result.size:\n return result\n\n if is_bool_dtype(dtype) or is_integer_dtype(dtype):\n\n if not result.size:\n # if we don't have any elements, just astype it\n return trans(result).astype(dtype)\n\n # do a test on the first element, if it fails then we are done\n r = result.ravel()\n arr = np.array([r[0]])\n\n if isna(arr).any():\n # if we have any nulls, then we are done\n return result\n\n elif not isinstance(r[0], (np.integer, np.floating, int, float, bool)):\n # a comparable, e.g. a Decimal may slip in here\n return result\n\n if (\n issubclass(result.dtype.type, (np.object_, np.number))\n and notna(result).all()\n ):\n new_result = trans(result).astype(dtype)\n if new_result.dtype.kind == \"O\" or result.dtype.kind == \"O\":\n # np.allclose may raise TypeError on object-dtype\n if (new_result == result).all():\n return new_result\n else:\n if np.allclose(new_result, result, rtol=0):\n return new_result\n\n elif (\n issubclass(dtype.type, np.floating)\n and not is_bool_dtype(result.dtype)\n and not is_string_dtype(result.dtype)\n ):\n return result.astype(dtype)\n\n return result\n\n\ndef maybe_cast_result(\n result: ArrayLike, obj: Series, numeric_only: bool = False, how: str = \"\"\n) -> ArrayLike:\n \"\"\"\n Try casting result to a different type if appropriate\n\n Parameters\n ----------\n result : array-like\n Result to cast.\n obj : Series\n Input Series from which result was calculated.\n numeric_only : bool, default False\n Whether to cast only numerics or datetimes as well.\n how : str, default \"\"\n How the result was computed.\n\n Returns\n -------\n result : array-like\n result maybe casted to the dtype.\n \"\"\"\n dtype = obj.dtype\n dtype = maybe_cast_result_dtype(dtype, how)\n\n assert not is_scalar(result)\n\n if (\n is_extension_array_dtype(dtype)\n and not is_categorical_dtype(dtype)\n and dtype.kind != \"M\"\n ):\n # We have to special case categorical so as not to upcast\n # things like counts back to categorical\n cls = dtype.construct_array_type()\n result = maybe_cast_to_extension_array(cls, result, dtype=dtype)\n\n elif numeric_only and is_numeric_dtype(dtype) or not numeric_only:\n result = maybe_downcast_to_dtype(result, dtype)\n\n return result\n\n\ndef maybe_cast_result_dtype(dtype: DtypeObj, how: str) -> DtypeObj:\n \"\"\"\n Get the desired dtype of a result based on the\n input dtype and how it was computed.\n\n Parameters\n ----------\n dtype : DtypeObj\n Input dtype.\n how : str\n How the result was computed.\n\n Returns\n -------\n DtypeObj\n The desired dtype of the result.\n \"\"\"\n from pandas.core.arrays.boolean import BooleanDtype\n from pandas.core.arrays.floating import Float64Dtype\n from pandas.core.arrays.integer import Int64Dtype, _IntegerDtype\n\n if how in [\"add\", \"cumsum\", \"sum\", \"prod\"]:\n if dtype == np.dtype(bool):\n return np.dtype(np.int64)\n elif isinstance(dtype, (BooleanDtype, _IntegerDtype)):\n return Int64Dtype()\n elif how in [\"mean\", \"median\", \"var\"] and isinstance(\n dtype, (BooleanDtype, _IntegerDtype)\n ):\n return Float64Dtype()\n return dtype\n\n\ndef maybe_cast_to_extension_array(\n cls: Type[ExtensionArray], obj: ArrayLike, dtype: Optional[ExtensionDtype] = None\n) -> ArrayLike:\n \"\"\"\n Call to `_from_sequence` that returns the object unchanged on Exception.\n\n Parameters\n ----------\n cls : class, subclass of ExtensionArray\n obj : arraylike\n Values to pass to cls._from_sequence\n dtype : ExtensionDtype, optional\n\n Returns\n -------\n ExtensionArray or obj\n \"\"\"\n from pandas.core.arrays.string_ import StringArray\n from pandas.core.arrays.string_arrow import ArrowStringArray\n\n assert isinstance(cls, type), f\"must pass a type: {cls}\"\n assertion_msg = f\"must pass a subclass of ExtensionArray: {cls}\"\n assert issubclass(cls, ABCExtensionArray), assertion_msg\n\n # Everything can be converted to StringArrays, but we may not want to convert\n if (\n issubclass(cls, (StringArray, ArrowStringArray))\n and lib.infer_dtype(obj) != \"string\"\n ):\n return obj\n\n try:\n result = cls._from_sequence(obj, dtype=dtype)\n except Exception:\n # We can't predict what downstream EA constructors may raise\n result = obj\n return result\n\n\ndef maybe_upcast_putmask(result: np.ndarray, mask: np.ndarray) -> np.ndarray:\n \"\"\"\n A safe version of putmask that potentially upcasts the result.\n\n The result is replaced with the first N elements of other,\n where N is the number of True values in mask.\n If the length of other is shorter than N, other will be repeated.\n\n Parameters\n ----------\n result : ndarray\n The destination array. This will be mutated in-place if no upcasting is\n necessary.\n mask : boolean ndarray\n\n Returns\n -------\n result : ndarray\n\n Examples\n --------\n >>> arr = np.arange(1, 6)\n >>> mask = np.array([False, True, False, True, True])\n >>> result = maybe_upcast_putmask(arr, mask)\n >>> result\n array([ 1., nan, 3., nan, nan])\n \"\"\"\n if not isinstance(result, np.ndarray):\n raise ValueError(\"The result input must be a ndarray.\")\n\n # NB: we never get here with result.dtype.kind in [\"m\", \"M\"]\n\n if mask.any():\n\n # we want to decide whether place will work\n # if we have nans in the False portion of our mask then we need to\n # upcast (possibly), otherwise we DON't want to upcast (e.g. if we\n # have values, say integers, in the success portion then it's ok to not\n # upcast)\n new_dtype, _ = maybe_promote(result.dtype, np.nan)\n if new_dtype != result.dtype:\n result = result.astype(new_dtype, copy=True)\n\n np.place(result, mask, np.nan)\n\n return result\n\n\ndef maybe_promote(dtype, fill_value=np.nan):\n \"\"\"\n Find the minimal dtype that can hold both the given dtype and fill_value.\n\n Parameters\n ----------\n dtype : np.dtype or ExtensionDtype\n fill_value : scalar, default np.nan\n\n Returns\n -------\n dtype\n Upcasted from dtype argument if necessary.\n fill_value\n Upcasted from fill_value argument if necessary.\n\n Raises\n ------\n ValueError\n If fill_value is a non-scalar and dtype is not object.\n \"\"\"\n if not is_scalar(fill_value) and not is_object_dtype(dtype):\n # with object dtype there is nothing to promote, and the user can\n # pass pretty much any weird fill_value they like\n raise ValueError(\"fill_value must be a scalar\")\n\n # if we passed an array here, determine the fill value by dtype\n if isinstance(fill_value, np.ndarray):\n if issubclass(fill_value.dtype.type, (np.datetime64, np.timedelta64)):\n fill_value = fill_value.dtype.type(\"NaT\", \"ns\")\n else:\n\n # we need to change to object type as our\n # fill_value is of object type\n if fill_value.dtype == np.object_:\n dtype = np.dtype(np.object_)\n fill_value = np.nan\n\n if dtype == np.object_ or dtype.kind in [\"U\", \"S\"]:\n # We treat string-like dtypes as object, and _always_ fill\n # with np.nan\n fill_value = np.nan\n dtype = np.dtype(np.object_)\n\n # returns tuple of (dtype, fill_value)\n if issubclass(dtype.type, np.datetime64):\n if isinstance(fill_value, datetime) and fill_value.tzinfo is not None:\n # Trying to insert tzaware into tznaive, have to cast to object\n dtype = np.dtype(np.object_)\n elif is_integer(fill_value) or (is_float(fill_value) and not isna(fill_value)):\n dtype = np.dtype(np.object_)\n elif is_valid_nat_for_dtype(fill_value, dtype):\n # e.g. pd.NA, which is not accepted by Timestamp constructor\n fill_value = np.datetime64(\"NaT\", \"ns\")\n else:\n try:\n fill_value = Timestamp(fill_value).to_datetime64()\n except (TypeError, ValueError):\n dtype = np.dtype(np.object_)\n elif issubclass(dtype.type, np.timedelta64):\n if (\n is_integer(fill_value)\n or (is_float(fill_value) and not np.isnan(fill_value))\n or isinstance(fill_value, str)\n ):\n # TODO: What about str that can be a timedelta?\n dtype = np.dtype(np.object_)\n elif is_valid_nat_for_dtype(fill_value, dtype):\n # e.g pd.NA, which is not accepted by the Timedelta constructor\n fill_value = np.timedelta64(\"NaT\", \"ns\")\n else:\n try:\n fv = Timedelta(fill_value)\n except ValueError:\n dtype = np.dtype(np.object_)\n else:\n if fv is NaT:\n # NaT has no `to_timedelta64` method\n fill_value = np.timedelta64(\"NaT\", \"ns\")\n else:\n fill_value = fv.to_timedelta64()\n elif is_datetime64tz_dtype(dtype):\n if isna(fill_value):\n fill_value = NaT\n elif not isinstance(fill_value, datetime):\n dtype = np.dtype(np.object_)\n elif fill_value.tzinfo is None:\n dtype = np.dtype(np.object_)\n elif not tz_compare(fill_value.tzinfo, dtype.tz):\n # TODO: sure we want to cast here?\n dtype = np.dtype(np.object_)\n\n elif is_extension_array_dtype(dtype) and isna(fill_value):\n fill_value = dtype.na_value\n\n elif is_float(fill_value):\n if issubclass(dtype.type, np.bool_):\n dtype = np.dtype(np.object_)\n\n elif issubclass(dtype.type, np.integer):\n dtype = np.dtype(np.float64)\n\n elif dtype.kind == \"f\":\n mst = np.min_scalar_type(fill_value)\n if mst > dtype:\n # e.g. mst is np.float64 and dtype is np.float32\n dtype = mst\n\n elif dtype.kind == \"c\":\n mst = np.min_scalar_type(fill_value)\n dtype = np.promote_types(dtype, mst)\n\n elif is_bool(fill_value):\n if not issubclass(dtype.type, np.bool_):\n dtype = np.dtype(np.object_)\n\n elif is_integer(fill_value):\n if issubclass(dtype.type, np.bool_):\n dtype = np.dtype(np.object_)\n\n elif issubclass(dtype.type, np.integer):\n if not np.can_cast(fill_value, dtype):\n # upcast to prevent overflow\n mst = np.min_scalar_type(fill_value)\n dtype = np.promote_types(dtype, mst)\n if dtype.kind == \"f\":\n # Case where we disagree with numpy\n dtype = np.dtype(np.object_)\n\n elif is_complex(fill_value):\n if issubclass(dtype.type, np.bool_):\n dtype = np.dtype(np.object_)\n\n elif issubclass(dtype.type, (np.integer, np.floating)):\n mst = np.min_scalar_type(fill_value)\n dtype = np.promote_types(dtype, mst)\n\n elif dtype.kind == \"c\":\n mst = np.min_scalar_type(fill_value)\n if mst > dtype:\n # e.g. mst is np.complex128 and dtype is np.complex64\n dtype = mst\n\n elif fill_value is None or fill_value is libmissing.NA:\n # Note: we already excluded dt64/td64 dtypes above\n if is_float_dtype(dtype) or is_complex_dtype(dtype):\n fill_value = np.nan\n elif is_integer_dtype(dtype):\n dtype = np.float64\n fill_value = np.nan\n else:\n dtype = np.dtype(np.object_)\n if fill_value is not libmissing.NA:\n fill_value = np.nan\n else:\n dtype = np.dtype(np.object_)\n\n # in case we have a string that looked like a number\n if is_extension_array_dtype(dtype):\n pass\n elif issubclass(np.dtype(dtype).type, (bytes, str)):\n dtype = np.dtype(np.object_)\n\n fill_value = _ensure_dtype_type(fill_value, dtype)\n return dtype, fill_value\n\n\ndef _ensure_dtype_type(value, dtype: DtypeObj):\n \"\"\"\n Ensure that the given value is an instance of the given dtype.\n\n e.g. if out dtype is np.complex64_, we should have an instance of that\n as opposed to a python complex object.\n\n Parameters\n ----------\n value : object\n dtype : np.dtype or ExtensionDtype\n\n Returns\n -------\n object\n \"\"\"\n # Start with exceptions in which we do _not_ cast to numpy types\n if is_extension_array_dtype(dtype):\n return value\n elif dtype == np.object_:\n return value\n elif isna(value):\n # e.g. keep np.nan rather than try to cast to np.float32(np.nan)\n return value\n\n return dtype.type(value)\n\n\ndef infer_dtype_from(val, pandas_dtype: bool = False) -> Tuple[DtypeObj, Any]:\n \"\"\"\n Interpret the dtype from a scalar or array.\n\n Parameters\n ----------\n val : object\n pandas_dtype : bool, default False\n whether to infer dtype including pandas extension types.\n If False, scalar/array belongs to pandas extension types is inferred as\n object\n \"\"\"\n if not is_list_like(val):\n return infer_dtype_from_scalar(val, pandas_dtype=pandas_dtype)\n return infer_dtype_from_array(val, pandas_dtype=pandas_dtype)\n\n\ndef infer_dtype_from_scalar(val, pandas_dtype: bool = False) -> Tuple[DtypeObj, Any]:\n \"\"\"\n Interpret the dtype from a scalar.\n\n Parameters\n ----------\n pandas_dtype : bool, default False\n whether to infer dtype including pandas extension types.\n If False, scalar belongs to pandas extension types is inferred as\n object\n \"\"\"\n dtype: DtypeObj = np.dtype(object)\n\n # a 1-element ndarray\n if isinstance(val, np.ndarray):\n if val.ndim != 0:\n msg = \"invalid ndarray passed to infer_dtype_from_scalar\"\n raise ValueError(msg)\n\n dtype = val.dtype\n val = lib.item_from_zerodim(val)\n\n elif isinstance(val, str):\n\n # If we create an empty array using a string to infer\n # the dtype, NumPy will only allocate one character per entry\n # so this is kind of bad. Alternately we could use np.repeat\n # instead of np.empty (but then you still don't want things\n # coming out as np.str_!\n\n dtype = np.dtype(object)\n\n elif isinstance(val, (np.datetime64, datetime)):\n try:\n val = Timestamp(val)\n except OutOfBoundsDatetime:\n return np.dtype(object), val\n\n if val is NaT or val.tz is None:\n dtype = np.dtype(\"M8[ns]\")\n else:\n if pandas_dtype:\n dtype = DatetimeTZDtype(unit=\"ns\", tz=val.tz)\n else:\n # return datetimetz as object\n return np.dtype(object), val\n val = val.value\n\n elif isinstance(val, (np.timedelta64, timedelta)):\n try:\n val = Timedelta(val).value\n except (OutOfBoundsTimedelta, OverflowError):\n dtype = np.dtype(object)\n else:\n dtype = np.dtype(\"m8[ns]\")\n\n elif is_bool(val):\n dtype = np.dtype(np.bool_)\n\n elif is_integer(val):\n if isinstance(val, np.integer):\n dtype = np.dtype(type(val))\n else:\n dtype = np.dtype(np.int64)\n\n try:\n np.array(val, dtype=dtype)\n except OverflowError:\n dtype = np.array(val).dtype\n\n elif is_float(val):\n if isinstance(val, np.floating):\n dtype = np.dtype(type(val))\n else:\n dtype = np.dtype(np.float64)\n\n elif is_complex(val):\n dtype = np.dtype(np.complex_)\n\n elif pandas_dtype:\n if lib.is_period(val):\n dtype = PeriodDtype(freq=val.freq)\n elif lib.is_interval(val):\n subtype = infer_dtype_from_scalar(val.left, pandas_dtype=True)[0]\n dtype = IntervalDtype(subtype=subtype, closed=val.closed)\n\n return dtype, val\n\n\ndef dict_compat(d: Dict[Scalar, Scalar]) -> Dict[Scalar, Scalar]:\n \"\"\"\n Convert datetimelike-keyed dicts to a Timestamp-keyed dict.\n\n Parameters\n ----------\n d: dict-like object\n\n Returns\n -------\n dict\n\n \"\"\"\n return {maybe_box_datetimelike(key): value for key, value in d.items()}\n\n\ndef infer_dtype_from_array(\n arr, pandas_dtype: bool = False\n) -> Tuple[DtypeObj, ArrayLike]:\n \"\"\"\n Infer the dtype from an array.\n\n Parameters\n ----------\n arr : array\n pandas_dtype : bool, default False\n whether to infer dtype including pandas extension types.\n If False, array belongs to pandas extension types\n is inferred as object\n\n Returns\n -------\n tuple (numpy-compat/pandas-compat dtype, array)\n\n Notes\n -----\n if pandas_dtype=False. these infer to numpy dtypes\n exactly with the exception that mixed / object dtypes\n are not coerced by stringifying or conversion\n\n if pandas_dtype=True. datetime64tz-aware/categorical\n types will retain there character.\n\n Examples\n --------\n >>> np.asarray([1, '1'])\n array(['1', '1'], dtype='<U21')\n\n >>> infer_dtype_from_array([1, '1'])\n (dtype('O'), [1, '1'])\n \"\"\"\n if isinstance(arr, np.ndarray):\n return arr.dtype, arr\n\n if not is_list_like(arr):\n raise TypeError(\"'arr' must be list-like\")\n\n if pandas_dtype and is_extension_array_dtype(arr):\n return arr.dtype, arr\n\n elif isinstance(arr, ABCSeries):\n return arr.dtype, np.asarray(arr)\n\n # don't force numpy coerce with nan's\n inferred = lib.infer_dtype(arr, skipna=False)\n if inferred in [\"string\", \"bytes\", \"mixed\", \"mixed-integer\"]:\n return (np.dtype(np.object_), arr)\n\n arr = np.asarray(arr)\n return arr.dtype, arr\n\n\ndef maybe_infer_dtype_type(element):\n \"\"\"\n Try to infer an object's dtype, for use in arithmetic ops.\n\n Uses `element.dtype` if that's available.\n Objects implementing the iterator protocol are cast to a NumPy array,\n and from there the array's type is used.\n\n Parameters\n ----------\n element : object\n Possibly has a `.dtype` attribute, and possibly the iterator\n protocol.\n\n Returns\n -------\n tipo : type\n\n Examples\n --------\n >>> from collections import namedtuple\n >>> Foo = namedtuple(\"Foo\", \"dtype\")\n >>> maybe_infer_dtype_type(Foo(np.dtype(\"i8\")))\n dtype('int64')\n \"\"\"\n tipo = None\n if hasattr(element, \"dtype\"):\n tipo = element.dtype\n elif is_list_like(element):\n element = np.asarray(element)\n tipo = element.dtype\n return tipo\n\n\ndef maybe_upcast(\n values: np.ndarray,\n fill_value: Scalar = np.nan,\n copy: bool = False,\n) -> Tuple[np.ndarray, Scalar]:\n \"\"\"\n Provide explicit type promotion and coercion.\n\n Parameters\n ----------\n values : np.ndarray\n The array that we may want to upcast.\n fill_value : what we want to fill with\n copy : bool, default True\n If True always make a copy even if no upcast is required.\n\n Returns\n -------\n values: np.ndarray\n the original array, possibly upcast\n fill_value:\n the fill value, possibly upcast\n \"\"\"\n new_dtype, fill_value = maybe_promote(values.dtype, fill_value)\n # We get a copy in all cases _except_ (values.dtype == new_dtype and not copy)\n values = values.astype(new_dtype, copy=copy)\n\n return values, fill_value\n\n\ndef invalidate_string_dtypes(dtype_set: Set[DtypeObj]):\n \"\"\"\n Change string like dtypes to object for\n ``DataFrame.select_dtypes()``.\n \"\"\"\n non_string_dtypes = dtype_set - {np.dtype(\"S\").type, np.dtype(\"<U\").type}\n if non_string_dtypes != dtype_set:\n raise TypeError(\"string dtypes are not allowed, use 'object' instead\")\n\n\ndef coerce_indexer_dtype(indexer, categories):\n \"\"\" coerce the indexer input array to the smallest dtype possible \"\"\"\n length = len(categories)\n if length < _int8_max:\n return ensure_int8(indexer)\n elif length < _int16_max:\n return ensure_int16(indexer)\n elif length < _int32_max:\n return ensure_int32(indexer)\n return ensure_int64(indexer)\n\n\ndef astype_dt64_to_dt64tz(\n values: ArrayLike, dtype: DtypeObj, copy: bool, via_utc: bool = False\n) -> DatetimeArray:\n # GH#33401 we have inconsistent behaviors between\n # Datetimeindex[naive].astype(tzaware)\n # Series[dt64].astype(tzaware)\n # This collects them in one place to prevent further fragmentation.\n\n from pandas.core.construction import ensure_wrapped_if_datetimelike\n\n values = ensure_wrapped_if_datetimelike(values)\n values = cast(\"DatetimeArray\", values)\n aware = isinstance(dtype, DatetimeTZDtype)\n\n if via_utc:\n # Series.astype behavior\n assert values.tz is None and aware # caller is responsible for checking this\n dtype = cast(DatetimeTZDtype, dtype)\n\n if copy:\n # this should be the only copy\n values = values.copy()\n\n level = find_stack_level()\n warnings.warn(\n \"Using .astype to convert from timezone-naive dtype to \"\n \"timezone-aware dtype is deprecated and will raise in a \"\n \"future version. Use ser.dt.tz_localize instead.\",\n FutureWarning,\n stacklevel=level,\n )\n\n # FIXME: GH#33401 this doesn't match DatetimeArray.astype, which\n # goes through the `not via_utc` path\n return values.tz_localize(\"UTC\").tz_convert(dtype.tz)\n\n else:\n # DatetimeArray/DatetimeIndex.astype behavior\n\n if values.tz is None and aware:\n dtype = cast(DatetimeTZDtype, dtype)\n level = find_stack_level()\n warnings.warn(\n \"Using .astype to convert from timezone-naive dtype to \"\n \"timezone-aware dtype is deprecated and will raise in a \"\n \"future version. Use obj.tz_localize instead.\",\n FutureWarning,\n stacklevel=level,\n )\n\n return values.tz_localize(dtype.tz)\n\n elif aware:\n # GH#18951: datetime64_tz dtype but not equal means different tz\n dtype = cast(DatetimeTZDtype, dtype)\n result = values.tz_convert(dtype.tz)\n if copy:\n result = result.copy()\n return result\n\n elif values.tz is not None:\n level = find_stack_level()\n warnings.warn(\n \"Using .astype to convert from timezone-aware dtype to \"\n \"timezone-naive dtype is deprecated and will raise in a \"\n \"future version. Use obj.tz_localize(None) or \"\n \"obj.tz_convert('UTC').tz_localize(None) instead\",\n FutureWarning,\n stacklevel=level,\n )\n\n result = values.tz_convert(\"UTC\").tz_localize(None)\n if copy:\n result = result.copy()\n return result\n\n raise NotImplementedError(\"dtype_equal case should be handled elsewhere\")\n\n\ndef astype_td64_unit_conversion(\n values: np.ndarray, dtype: np.dtype, copy: bool\n) -> np.ndarray:\n \"\"\"\n By pandas convention, converting to non-nano timedelta64\n returns an int64-dtyped array with ints representing multiples\n of the desired timedelta unit. This is essentially division.\n\n Parameters\n ----------\n values : np.ndarray[timedelta64[ns]]\n dtype : np.dtype\n timedelta64 with unit not-necessarily nano\n copy : bool\n\n Returns\n -------\n np.ndarray\n \"\"\"\n if is_dtype_equal(values.dtype, dtype):\n if copy:\n return values.copy()\n return values\n\n # otherwise we are converting to non-nano\n result = values.astype(dtype, copy=False) # avoid double-copying\n result = result.astype(np.float64)\n\n mask = isna(values)\n np.putmask(result, mask, np.nan)\n return result\n\n\ndef astype_nansafe(\n arr: np.ndarray, dtype: DtypeObj, copy: bool = True, skipna: bool = False\n) -> ArrayLike:\n \"\"\"\n Cast the elements of an array to a given dtype a nan-safe manner.\n\n Parameters\n ----------\n arr : ndarray\n dtype : np.dtype or ExtensionDtype\n copy : bool, default True\n If False, a view will be attempted but may fail, if\n e.g. the item sizes don't align.\n skipna: bool, default False\n Whether or not we should skip NaN when casting as a string-type.\n\n Raises\n ------\n ValueError\n The dtype was a datetime64/timedelta64 dtype, but it had no unit.\n \"\"\"\n if arr.ndim > 1:\n # Make sure we are doing non-copy ravel and reshape.\n flags = arr.flags\n flat = arr.ravel(\"K\")\n result = astype_nansafe(flat, dtype, copy=copy, skipna=skipna)\n order = \"F\" if flags.f_contiguous else \"C\"\n return result.reshape(arr.shape, order=order)\n\n # We get here with 0-dim from sparse\n arr = np.atleast_1d(arr)\n\n # dispatch on extension dtype if needed\n if isinstance(dtype, ExtensionDtype):\n return dtype.construct_array_type()._from_sequence(arr, dtype=dtype, copy=copy)\n\n elif not isinstance(dtype, np.dtype):\n raise ValueError(\"dtype must be np.dtype or ExtensionDtype\")\n\n if arr.dtype.kind in [\"m\", \"M\"] and (\n issubclass(dtype.type, str) or dtype == object\n ):\n from pandas.core.construction import ensure_wrapped_if_datetimelike\n\n arr = ensure_wrapped_if_datetimelike(arr)\n return arr.astype(dtype, copy=copy)\n\n if issubclass(dtype.type, str):\n return lib.ensure_string_array(arr, skipna=skipna, convert_na_value=False)\n\n elif is_datetime64_dtype(arr):\n if dtype == np.int64:\n warnings.warn(\n f\"casting {arr.dtype} values to int64 with .astype(...) \"\n \"is deprecated and will raise in a future version. \"\n \"Use .view(...) instead.\",\n FutureWarning,\n # stacklevel chosen to be correct when reached via Series.astype\n stacklevel=7,\n )\n if isna(arr).any():\n raise ValueError(\"Cannot convert NaT values to integer\")\n return arr.view(dtype)\n\n # allow frequency conversions\n if dtype.kind == \"M\":\n return arr.astype(dtype)\n\n raise TypeError(f\"cannot astype a datetimelike from [{arr.dtype}] to [{dtype}]\")\n\n elif is_timedelta64_dtype(arr):\n if dtype == np.int64:\n warnings.warn(\n f\"casting {arr.dtype} values to int64 with .astype(...) \"\n \"is deprecated and will raise in a future version. \"\n \"Use .view(...) instead.\",\n FutureWarning,\n # stacklevel chosen to be correct when reached via Series.astype\n stacklevel=7,\n )\n if isna(arr).any():\n raise ValueError(\"Cannot convert NaT values to integer\")\n return arr.view(dtype)\n\n elif dtype.kind == \"m\":\n return astype_td64_unit_conversion(arr, dtype, copy=copy)\n\n raise TypeError(f\"cannot astype a timedelta from [{arr.dtype}] to [{dtype}]\")\n\n elif np.issubdtype(arr.dtype, np.floating) and np.issubdtype(dtype, np.integer):\n\n if not np.isfinite(arr).all():\n raise ValueError(\"Cannot convert non-finite values (NA or inf) to integer\")\n\n elif is_object_dtype(arr):\n\n # work around NumPy brokenness, #1987\n if np.issubdtype(dtype.type, np.integer):\n return lib.astype_intsafe(arr, dtype)\n\n # if we have a datetime/timedelta array of objects\n # then coerce to a proper dtype and recall astype_nansafe\n\n elif is_datetime64_dtype(dtype):\n from pandas import to_datetime\n\n return astype_nansafe(to_datetime(arr).values, dtype, copy=copy)\n elif is_timedelta64_dtype(dtype):\n from pandas import to_timedelta\n\n return astype_nansafe(to_timedelta(arr)._values, dtype, copy=copy)\n\n if dtype.name in (\"datetime64\", \"timedelta64\"):\n msg = (\n f\"The '{dtype.name}' dtype has no unit. Please pass in \"\n f\"'{dtype.name}[ns]' instead.\"\n )\n raise ValueError(msg)\n\n if copy or is_object_dtype(arr.dtype) or is_object_dtype(dtype):\n # Explicit copy, or required since NumPy can't view from / to object.\n return arr.astype(dtype, copy=True)\n\n return arr.astype(dtype, copy=copy)\n\n\ndef soft_convert_objects(\n values: np.ndarray,\n datetime: bool = True,\n numeric: bool = True,\n timedelta: bool = True,\n copy: bool = True,\n):\n \"\"\"\n Try to coerce datetime, timedelta, and numeric object-dtype columns\n to inferred dtype.\n\n Parameters\n ----------\n values : np.ndarray[object]\n datetime : bool, default True\n numeric: bool, default True\n timedelta : bool, default True\n copy : bool, default True\n\n Returns\n -------\n np.ndarray\n \"\"\"\n validate_bool_kwarg(datetime, \"datetime\")\n validate_bool_kwarg(numeric, \"numeric\")\n validate_bool_kwarg(timedelta, \"timedelta\")\n validate_bool_kwarg(copy, \"copy\")\n\n conversion_count = sum((datetime, numeric, timedelta))\n if conversion_count == 0:\n raise ValueError(\"At least one of datetime, numeric or timedelta must be True.\")\n\n # Soft conversions\n if datetime or timedelta:\n # GH 20380, when datetime is beyond year 2262, hence outside\n # bound of nanosecond-resolution 64-bit integers.\n try:\n values = lib.maybe_convert_objects(\n values, convert_datetime=datetime, convert_timedelta=timedelta\n )\n except (OutOfBoundsDatetime, ValueError):\n return values\n\n if numeric and is_object_dtype(values.dtype):\n converted = lib.maybe_convert_numeric(values, set(), coerce_numeric=True)\n\n # If all NaNs, then do not-alter\n values = converted if not isna(converted).all() else values\n values = values.copy() if copy else values\n\n return values\n\n\ndef convert_dtypes(\n input_array: AnyArrayLike,\n convert_string: bool = True,\n convert_integer: bool = True,\n convert_boolean: bool = True,\n convert_floating: bool = True,\n) -> Dtype:\n \"\"\"\n Convert objects to best possible type, and optionally,\n to types supporting ``pd.NA``.\n\n Parameters\n ----------\n input_array : ExtensionArray, Index, Series or np.ndarray\n convert_string : bool, default True\n Whether object dtypes should be converted to ``StringDtype()``.\n convert_integer : bool, default True\n Whether, if possible, conversion can be done to integer extension types.\n convert_boolean : bool, defaults True\n Whether object dtypes should be converted to ``BooleanDtypes()``.\n convert_floating : bool, defaults True\n Whether, if possible, conversion can be done to floating extension types.\n If `convert_integer` is also True, preference will be give to integer\n dtypes if the floats can be faithfully casted to integers.\n\n Returns\n -------\n dtype\n new dtype\n \"\"\"\n is_extension = is_extension_array_dtype(input_array.dtype)\n if (\n convert_string or convert_integer or convert_boolean or convert_floating\n ) and not is_extension:\n try:\n inferred_dtype = lib.infer_dtype(input_array)\n except ValueError:\n # Required to catch due to Period. Can remove once GH 23553 is fixed\n inferred_dtype = input_array.dtype\n\n if not convert_string and is_string_dtype(inferred_dtype):\n inferred_dtype = input_array.dtype\n\n if convert_integer:\n target_int_dtype = \"Int64\"\n\n if is_integer_dtype(input_array.dtype):\n from pandas.core.arrays.integer import INT_STR_TO_DTYPE\n\n inferred_dtype = INT_STR_TO_DTYPE.get(\n input_array.dtype.name, target_int_dtype\n )\n if not is_integer_dtype(input_array.dtype) and is_numeric_dtype(\n input_array.dtype\n ):\n inferred_dtype = target_int_dtype\n\n else:\n if is_integer_dtype(inferred_dtype):\n inferred_dtype = input_array.dtype\n\n if convert_floating:\n if not is_integer_dtype(input_array.dtype) and is_numeric_dtype(\n input_array.dtype\n ):\n from pandas.core.arrays.floating import FLOAT_STR_TO_DTYPE\n\n inferred_float_dtype = FLOAT_STR_TO_DTYPE.get(\n input_array.dtype.name, \"Float64\"\n )\n # if we could also convert to integer, check if all floats\n # are actually integers\n if convert_integer:\n arr = input_array[notna(input_array)]\n if (arr.astype(int) == arr).all():\n inferred_dtype = \"Int64\"\n else:\n inferred_dtype = inferred_float_dtype\n else:\n inferred_dtype = inferred_float_dtype\n else:\n if is_float_dtype(inferred_dtype):\n inferred_dtype = input_array.dtype\n\n if convert_boolean:\n if is_bool_dtype(input_array.dtype):\n inferred_dtype = \"boolean\"\n else:\n if isinstance(inferred_dtype, str) and inferred_dtype == \"boolean\":\n inferred_dtype = input_array.dtype\n\n else:\n inferred_dtype = input_array.dtype\n\n return inferred_dtype\n\n\ndef maybe_castable(arr: np.ndarray) -> bool:\n # return False to force a non-fastpath\n\n assert isinstance(arr, np.ndarray) # GH 37024\n\n # check datetime64[ns]/timedelta64[ns] are valid\n # otherwise try to coerce\n kind = arr.dtype.kind\n if kind == \"M\":\n return is_datetime64_ns_dtype(arr.dtype)\n elif kind == \"m\":\n return is_timedelta64_ns_dtype(arr.dtype)\n\n return arr.dtype.name not in POSSIBLY_CAST_DTYPES\n\n\ndef maybe_infer_to_datetimelike(\n value: Union[ArrayLike, Scalar], convert_dates: bool = False\n):\n \"\"\"\n we might have a array (or single object) that is datetime like,\n and no dtype is passed don't change the value unless we find a\n datetime/timedelta set\n\n this is pretty strict in that a datetime/timedelta is REQUIRED\n in addition to possible nulls/string likes\n\n Parameters\n ----------\n value : np.array / Series / Index / list-like\n convert_dates : bool, default False\n if True try really hard to convert dates (such as datetime.date), other\n leave inferred dtype 'date' alone\n\n \"\"\"\n if isinstance(value, (ABCIndex, ABCExtensionArray)):\n if not is_object_dtype(value.dtype):\n raise ValueError(\"array-like value must be object-dtype\")\n\n v = value\n\n if not is_list_like(v):\n v = [v]\n v = np.array(v, copy=False)\n\n # we only care about object dtypes\n if not is_object_dtype(v):\n return value\n\n shape = v.shape\n if v.ndim != 1:\n v = v.ravel()\n\n if not len(v):\n return value\n\n def try_datetime(v):\n # safe coerce to datetime64\n try:\n # GH19671\n # tznaive only\n v = tslib.array_to_datetime(v, require_iso8601=True, errors=\"raise\")[0]\n except ValueError:\n\n # we might have a sequence of the same-datetimes with tz's\n # if so coerce to a DatetimeIndex; if they are not the same,\n # then these stay as object dtype, xref GH19671\n from pandas import DatetimeIndex\n\n try:\n\n values, tz = conversion.datetime_to_datetime64(v)\n except (ValueError, TypeError):\n pass\n else:\n return DatetimeIndex(values).tz_localize(\"UTC\").tz_convert(tz=tz)\n except TypeError:\n # e.g. <class 'numpy.timedelta64'> is not convertible to datetime\n pass\n\n return v.reshape(shape)\n\n def try_timedelta(v):\n # safe coerce to timedelta64\n\n # will try first with a string & object conversion\n from pandas import to_timedelta\n\n try:\n td_values = to_timedelta(v)\n except (ValueError, OverflowError):\n return v.reshape(shape)\n else:\n return np.asarray(td_values).reshape(shape)\n\n inferred_type = lib.infer_datetimelike_array(ensure_object(v))\n\n if inferred_type == \"date\" and convert_dates:\n value = try_datetime(v)\n elif inferred_type == \"datetime\":\n value = try_datetime(v)\n elif inferred_type == \"timedelta\":\n value = try_timedelta(v)\n elif inferred_type == \"nat\":\n\n # if all NaT, return as datetime\n if isna(v).all():\n value = try_datetime(v)\n else:\n\n # We have at least a NaT and a string\n # try timedelta first to avoid spurious datetime conversions\n # e.g. '00:00:01' is a timedelta but technically is also a datetime\n value = try_timedelta(v)\n if lib.infer_dtype(value, skipna=False) in [\"mixed\"]:\n # cannot skip missing values, as NaT implies that the string\n # is actually a datetime\n value = try_datetime(v)\n\n return value\n\n\ndef maybe_cast_to_datetime(value, dtype: Optional[DtypeObj]):\n \"\"\"\n try to cast the array/value to a datetimelike dtype, converting float\n nan to iNaT\n \"\"\"\n from pandas.core.tools.datetimes import to_datetime\n from pandas.core.tools.timedeltas import to_timedelta\n\n if not is_list_like(value):\n raise TypeError(\"value must be listlike\")\n\n if dtype is not None:\n is_datetime64 = is_datetime64_dtype(dtype)\n is_datetime64tz = is_datetime64tz_dtype(dtype)\n is_timedelta64 = is_timedelta64_dtype(dtype)\n\n if is_datetime64 or is_datetime64tz or is_timedelta64:\n\n # Force the dtype if needed.\n msg = (\n f\"The '{dtype.name}' dtype has no unit. \"\n f\"Please pass in '{dtype.name}[ns]' instead.\"\n )\n\n if is_datetime64:\n # unpack e.g. SparseDtype\n dtype = getattr(dtype, \"subtype\", dtype)\n if not is_dtype_equal(dtype, DT64NS_DTYPE):\n\n # pandas supports dtype whose granularity is less than [ns]\n # e.g., [ps], [fs], [as]\n if dtype <= np.dtype(\"M8[ns]\"):\n if dtype.name == \"datetime64\":\n raise ValueError(msg)\n dtype = DT64NS_DTYPE\n else:\n raise TypeError(\n f\"cannot convert datetimelike to dtype [{dtype}]\"\n )\n\n elif is_timedelta64 and not is_dtype_equal(dtype, TD64NS_DTYPE):\n\n # pandas supports dtype whose granularity is less than [ns]\n # e.g., [ps], [fs], [as]\n if dtype <= np.dtype(\"m8[ns]\"):\n if dtype.name == \"timedelta64\":\n raise ValueError(msg)\n dtype = TD64NS_DTYPE\n else:\n raise TypeError(f\"cannot convert timedeltalike to dtype [{dtype}]\")\n\n if not is_sparse(value):\n value = np.array(value, copy=False)\n\n # have a scalar array-like (e.g. NaT)\n if value.ndim == 0:\n value = iNaT\n\n # we have an array of datetime or timedeltas & nulls\n elif np.prod(value.shape) or not is_dtype_equal(value.dtype, dtype):\n _disallow_mismatched_datetimelike(value, dtype)\n\n try:\n if is_datetime64:\n value = to_datetime(value, errors=\"raise\")\n # GH 25843: Remove tz information since the dtype\n # didn't specify one\n if value.tz is not None:\n value = value.tz_localize(None)\n value = value._values\n elif is_datetime64tz:\n # The string check can be removed once issue #13712\n # is solved. String data that is passed with a\n # datetime64tz is assumed to be naive which should\n # be localized to the timezone.\n is_dt_string = is_string_dtype(value.dtype)\n value = to_datetime(value, errors=\"raise\").array\n if is_dt_string:\n # Strings here are naive, so directly localize\n value = value.tz_localize(dtype.tz)\n else:\n # Numeric values are UTC at this point,\n # so localize and convert\n value = value.tz_localize(\"UTC\").tz_convert(dtype.tz)\n elif is_timedelta64:\n value = to_timedelta(value, errors=\"raise\")._values\n except OutOfBoundsDatetime:\n raise\n except (ValueError, TypeError):\n pass\n\n # coerce datetimelike to object\n elif is_datetime64_dtype(\n getattr(value, \"dtype\", None)\n ) and not is_datetime64_dtype(dtype):\n if is_object_dtype(dtype):\n if value.dtype != DT64NS_DTYPE:\n value = value.astype(DT64NS_DTYPE)\n ints = np.asarray(value).view(\"i8\")\n return ints_to_pydatetime(ints)\n\n # we have a non-castable dtype that was passed\n raise TypeError(f\"Cannot cast datetime64 to {dtype}\")\n\n else:\n\n is_array = isinstance(value, np.ndarray)\n\n # catch a datetime/timedelta that is not of ns variety\n # and no coercion specified\n if is_array and value.dtype.kind in [\"M\", \"m\"]:\n value = sanitize_to_nanoseconds(value)\n\n # only do this if we have an array and the dtype of the array is not\n # setup already we are not an integer/object, so don't bother with this\n # conversion\n elif not (\n is_array\n and not (\n issubclass(value.dtype.type, np.integer) or value.dtype == np.object_\n )\n ):\n value = maybe_infer_to_datetimelike(value)\n\n return value\n\n\ndef sanitize_to_nanoseconds(values: np.ndarray) -> np.ndarray:\n \"\"\"\n Safely convert non-nanosecond datetime64 or timedelta64 values to nanosecond.\n \"\"\"\n dtype = values.dtype\n if dtype.kind == \"M\" and dtype != DT64NS_DTYPE:\n values = conversion.ensure_datetime64ns(values)\n\n elif dtype.kind == \"m\" and dtype != TD64NS_DTYPE:\n values = conversion.ensure_timedelta64ns(values)\n\n return values\n\n\ndef find_common_type(types: List[DtypeObj]) -> DtypeObj:\n \"\"\"\n Find a common data type among the given dtypes.\n\n Parameters\n ----------\n types : list of dtypes\n\n Returns\n -------\n pandas extension or numpy dtype\n\n See Also\n --------\n numpy.find_common_type\n\n \"\"\"\n if not types:\n raise ValueError(\"no types given\")\n\n first = types[0]\n\n # workaround for find_common_type([np.dtype('datetime64[ns]')] * 2)\n # => object\n if all(is_dtype_equal(first, t) for t in types[1:]):\n return first\n\n # get unique types (dict.fromkeys is used as order-preserving set())\n types = list(dict.fromkeys(types).keys())\n\n if any(isinstance(t, ExtensionDtype) for t in types):\n for t in types:\n if isinstance(t, ExtensionDtype):\n res = t._get_common_dtype(types)\n if res is not None:\n return res\n return np.dtype(\"object\")\n\n # take lowest unit\n if all(is_datetime64_dtype(t) for t in types):\n return np.dtype(\"datetime64[ns]\")\n if all(is_timedelta64_dtype(t) for t in types):\n return np.dtype(\"timedelta64[ns]\")\n\n # don't mix bool / int or float or complex\n # this is different from numpy, which casts bool with float/int as int\n has_bools = any(is_bool_dtype(t) for t in types)\n if has_bools:\n for t in types:\n if is_integer_dtype(t) or is_float_dtype(t) or is_complex_dtype(t):\n return np.dtype(\"object\")\n\n return np.find_common_type(types, [])\n\n\ndef construct_2d_arraylike_from_scalar(\n value: Scalar, length: int, width: int, dtype: np.dtype, copy: bool\n) -> np.ndarray:\n\n shape = (length, width)\n\n if dtype.kind in [\"m\", \"M\"]:\n value = maybe_unbox_datetimelike(value, dtype)\n elif dtype == object:\n if isinstance(value, (np.timedelta64, np.datetime64)):\n # calling np.array below would cast to pytimedelta/pydatetime\n out = np.empty(shape, dtype=object)\n out.fill(value)\n return out\n\n # Attempt to coerce to a numpy array\n try:\n arr = np.array(value, dtype=dtype, copy=copy)\n except (ValueError, TypeError) as err:\n raise TypeError(\n f\"DataFrame constructor called with incompatible data and dtype: {err}\"\n ) from err\n\n if arr.ndim != 0:\n raise ValueError(\"DataFrame constructor not properly called!\")\n\n return np.full(shape, arr)\n\n\ndef construct_1d_arraylike_from_scalar(\n value: Scalar, length: int, dtype: Optional[DtypeObj]\n) -> ArrayLike:\n \"\"\"\n create a np.ndarray / pandas type of specified shape and dtype\n filled with values\n\n Parameters\n ----------\n value : scalar value\n length : int\n dtype : pandas_dtype or np.dtype\n\n Returns\n -------\n np.ndarray / pandas type of length, filled with value\n\n \"\"\"\n\n if dtype is None:\n try:\n dtype, value = infer_dtype_from_scalar(value, pandas_dtype=True)\n except OutOfBoundsDatetime:\n dtype = np.dtype(object)\n\n if is_extension_array_dtype(dtype):\n cls = dtype.construct_array_type()\n subarr = cls._from_sequence([value] * length, dtype=dtype)\n\n else:\n\n if length and is_integer_dtype(dtype) and isna(value):\n # coerce if we have nan for an integer dtype\n dtype = np.dtype(\"float64\")\n elif isinstance(dtype, np.dtype) and dtype.kind in (\"U\", \"S\"):\n # we need to coerce to object dtype to avoid\n # to allow numpy to take our string as a scalar value\n dtype = np.dtype(\"object\")\n if not isna(value):\n value = ensure_str(value)\n elif dtype.kind in [\"M\", \"m\"]:\n value = maybe_unbox_datetimelike(value, dtype)\n\n subarr = np.empty(length, dtype=dtype)\n subarr.fill(value)\n\n return subarr\n\n\ndef construct_1d_object_array_from_listlike(values: Sized) -> np.ndarray:\n \"\"\"\n Transform any list-like object in a 1-dimensional numpy array of object\n dtype.\n\n Parameters\n ----------\n values : any iterable which has a len()\n\n Raises\n ------\n TypeError\n * If `values` does not have a len()\n\n Returns\n -------\n 1-dimensional numpy array of dtype object\n \"\"\"\n # numpy will try to interpret nested lists as further dimensions, hence\n # making a 1D array that contains list-likes is a bit tricky:\n result = np.empty(len(values), dtype=\"object\")\n result[:] = values\n return result\n\n\ndef construct_1d_ndarray_preserving_na(\n values: Sequence, dtype: Optional[DtypeObj] = None, copy: bool = False\n) -> np.ndarray:\n \"\"\"\n Construct a new ndarray, coercing `values` to `dtype`, preserving NA.\n\n Parameters\n ----------\n values : Sequence\n dtype : numpy.dtype, optional\n copy : bool, default False\n Note that copies may still be made with ``copy=False`` if casting\n is required.\n\n Returns\n -------\n arr : ndarray[dtype]\n\n Examples\n --------\n >>> np.array([1.0, 2.0, None], dtype='str')\n array(['1.0', '2.0', 'None'], dtype='<U4')\n\n >>> construct_1d_ndarray_preserving_na([1.0, 2.0, None], dtype=np.dtype('str'))\n array(['1.0', '2.0', None], dtype=object)\n \"\"\"\n\n if dtype is not None and dtype.kind == \"U\":\n subarr = lib.ensure_string_array(values, convert_na_value=False, copy=copy)\n else:\n if dtype is not None:\n _disallow_mismatched_datetimelike(values, dtype)\n subarr = np.array(values, dtype=dtype, copy=copy)\n\n return subarr\n\n\ndef maybe_cast_to_integer_array(arr, dtype: Dtype, copy: bool = False):\n \"\"\"\n Takes any dtype and returns the casted version, raising for when data is\n incompatible with integer/unsigned integer dtypes.\n\n .. versionadded:: 0.24.0\n\n Parameters\n ----------\n arr : array-like\n The array to cast.\n dtype : str, np.dtype\n The integer dtype to cast the array to.\n copy: bool, default False\n Whether to make a copy of the array before returning.\n\n Returns\n -------\n ndarray\n Array of integer or unsigned integer dtype.\n\n Raises\n ------\n OverflowError : the dtype is incompatible with the data\n ValueError : loss of precision has occurred during casting\n\n Examples\n --------\n If you try to coerce negative values to unsigned integers, it raises:\n\n >>> pd.Series([-1], dtype=\"uint64\")\n Traceback (most recent call last):\n ...\n OverflowError: Trying to coerce negative values to unsigned integers\n\n Also, if you try to coerce float values to integers, it raises:\n\n >>> pd.Series([1, 2, 3.5], dtype=\"int64\")\n Traceback (most recent call last):\n ...\n ValueError: Trying to coerce float values to integers\n \"\"\"\n assert is_integer_dtype(dtype)\n\n try:\n if not hasattr(arr, \"astype\"):\n casted = np.array(arr, dtype=dtype, copy=copy)\n else:\n casted = arr.astype(dtype, copy=copy)\n except OverflowError as err:\n raise OverflowError(\n \"The elements provided in the data cannot all be \"\n f\"casted to the dtype {dtype}\"\n ) from err\n\n if np.array_equal(arr, casted):\n return casted\n\n # We do this casting to allow for proper\n # data and dtype checking.\n #\n # We didn't do this earlier because NumPy\n # doesn't handle `uint64` correctly.\n arr = np.asarray(arr)\n\n if is_unsigned_integer_dtype(dtype) and (arr < 0).any():\n raise OverflowError(\"Trying to coerce negative values to unsigned integers\")\n\n if is_float_dtype(arr) or is_object_dtype(arr):\n raise ValueError(\"Trying to coerce float values to integers\")\n\n\ndef convert_scalar_for_putitemlike(scalar: Scalar, dtype: np.dtype) -> Scalar:\n \"\"\"\n Convert datetimelike scalar if we are setting into a datetime64\n or timedelta64 ndarray.\n\n Parameters\n ----------\n scalar : scalar\n dtype : np.dtype\n\n Returns\n -------\n scalar\n \"\"\"\n if dtype.kind in [\"m\", \"M\"]:\n scalar = maybe_box_datetimelike(scalar, dtype)\n return maybe_unbox_datetimelike(scalar, dtype)\n else:\n validate_numeric_casting(dtype, scalar)\n return scalar\n\n\ndef validate_numeric_casting(dtype: np.dtype, value: Scalar) -> None:\n \"\"\"\n Check that we can losslessly insert the given value into an array\n with the given dtype.\n\n Parameters\n ----------\n dtype : np.dtype\n value : scalar\n\n Raises\n ------\n ValueError\n \"\"\"\n if (\n issubclass(dtype.type, (np.integer, np.bool_))\n and is_float(value)\n and np.isnan(value)\n ):\n raise ValueError(\"Cannot assign nan to integer series\")\n\n elif dtype.kind in [\"i\", \"u\", \"f\", \"c\"]:\n if is_bool(value) or isinstance(value, np.timedelta64):\n # numpy will cast td64 to integer if we're not careful\n raise ValueError(\n f\"Cannot assign {type(value).__name__} to float/integer series\"\n )\n elif dtype.kind == \"b\":\n if is_scalar(value) and not is_bool(value):\n raise ValueError(f\"Cannot assign {type(value).__name__} to bool series\")\n\n\ndef can_hold_element(dtype: np.dtype, element: Any) -> bool:\n \"\"\"\n Can we do an inplace setitem with this element in an array with this dtype?\n\n Parameters\n ----------\n dtype : np.dtype\n element : Any\n\n Returns\n -------\n bool\n \"\"\"\n tipo = maybe_infer_dtype_type(element)\n\n if dtype.kind in [\"i\", \"u\"]:\n if tipo is not None:\n return tipo.kind in [\"i\", \"u\"] and dtype.itemsize >= tipo.itemsize\n\n # We have not inferred an integer from the dtype\n # check if we have a builtin int or a float equal to an int\n return is_integer(element) or (is_float(element) and element.is_integer())\n\n elif dtype.kind == \"f\":\n if tipo is not None:\n return tipo.kind in [\"f\", \"i\", \"u\"]\n return lib.is_integer(element) or lib.is_float(element)\n\n elif dtype.kind == \"c\":\n if tipo is not None:\n return tipo.kind in [\"c\", \"f\", \"i\", \"u\"]\n return (\n lib.is_integer(element) or lib.is_complex(element) or lib.is_float(element)\n )\n\n elif dtype.kind == \"b\":\n if tipo is not None:\n return tipo.kind == \"b\"\n return lib.is_bool(element)\n\n elif dtype == object:\n return True\n\n raise NotImplementedError(dtype)\n"
] | [
[
"pandas.util._validators.validate_bool_kwarg",
"pandas._libs.tslibs.ints_to_pydatetime",
"pandas.core.dtypes.common.is_datetime64_dtype",
"pandas.core.dtypes.common.ensure_object",
"numpy.min_scalar_type",
"numpy.place",
"numpy.full",
"pandas.core.dtypes.common.is_float_dtype",
"pandas.core.dtypes.common.is_categorical_dtype",
"numpy.find_common_type",
"numpy.array",
"pandas.core.dtypes.common.is_bool_dtype",
"numpy.datetime64",
"pandas.core.dtypes.missing.isna",
"pandas._libs.lib.is_bool",
"pandas._libs.tslibs.conversion.datetime_to_datetime64",
"pandas._libs.tslibs.Timestamp",
"numpy.asarray",
"pandas.core.dtypes.dtypes.DatetimeTZDtype",
"numpy.promote_types",
"pandas.core.dtypes.common.is_datetime64tz_dtype",
"pandas.core.dtypes.dtypes.IntervalDtype",
"pandas._libs.lib.is_complex",
"numpy.iinfo",
"pandas._libs.tslibs.conversion.ensure_datetime64ns",
"pandas.core.dtypes.common.is_unsigned_integer_dtype",
"numpy.allclose",
"numpy.atleast_1d",
"numpy.putmask",
"pandas.core.dtypes.common.ensure_int8",
"pandas._libs.lib.ensure_string_array",
"pandas.core.dtypes.common.ensure_str",
"numpy.timedelta64",
"pandas.core.construction.ensure_wrapped_if_datetimelike",
"pandas._libs.lib.is_period",
"numpy.array_equal",
"pandas.core.dtypes.common.is_integer",
"pandas.to_timedelta",
"pandas._libs.lib.infer_dtype",
"pandas._libs.lib.item_from_zerodim",
"numpy.empty",
"numpy.can_cast",
"pandas.core.dtypes.common.is_extension_array_dtype",
"pandas.core.dtypes.common.is_dtype_equal",
"numpy.issubdtype",
"pandas.core.dtypes.missing.notna",
"pandas.core.arrays.floating.FLOAT_STR_TO_DTYPE.get",
"pandas.core.dtypes.common.is_timedelta64_ns_dtype",
"pandas.core.dtypes.common.is_numeric_dtype",
"pandas.DatetimeIndex",
"pandas.core.dtypes.common.ensure_int64",
"pandas.core.arrays.integer.Int64Dtype",
"pandas.core.dtypes.common.is_integer_dtype",
"numpy.isnan",
"pandas.core.dtypes.common.is_timedelta64_dtype",
"pandas.core.dtypes.common.is_bool",
"pandas._libs.tslibs.Timedelta",
"pandas._libs.lib.is_float",
"pandas.core.dtypes.common.is_scalar",
"pandas.core.dtypes.common.is_datetime64_ns_dtype",
"pandas.to_datetime",
"numpy.dtype",
"pandas.core.dtypes.common.is_complex_dtype",
"pandas.core.dtypes.inference.is_list_like",
"pandas._libs.lib.is_integer",
"pandas.core.dtypes.common.is_complex",
"pandas._libs.tslibs.conversion.ensure_timedelta64ns",
"pandas.core.arrays.PeriodArray",
"pandas.core.dtypes.common.is_float",
"pandas.core.dtypes.common.is_string_dtype",
"pandas._libs.lib.astype_intsafe",
"pandas._libs.tslibs.tz_compare",
"pandas.core.dtypes.common.ensure_int16",
"pandas.core.dtypes.common.is_sparse",
"pandas.core.dtypes.dtypes.PeriodDtype",
"pandas.core.dtypes.missing.is_valid_nat_for_dtype",
"pandas.core.arrays.floating.Float64Dtype",
"pandas.util._exceptions.find_stack_level",
"pandas._libs.tslib.array_to_datetime",
"numpy.isfinite",
"pandas.core.arrays.integer.INT_STR_TO_DTYPE.get",
"pandas.core.dtypes.common.is_object_dtype",
"pandas._libs.lib.maybe_convert_objects",
"pandas.core.dtypes.common.ensure_int32",
"numpy.prod",
"pandas._libs.lib.is_interval"
]
] |
Romance-Zhang/nl2sql-chinese | [
"d4b0fa9c3baa524544646bac24378fe49ae8d6c1"
] | [
"code/sqlnet/utils.py"
] | [
"import json\nfrom sqlnet.lib.dbengine import DBEngine\nimport numpy as np\nfrom tqdm import tqdm\nimport torch\nimport os\nfrom bert.modeling import BertConfig, BertModel\nimport bert.tokenization as tokenization\nfrom torch.autograd import Variable\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\ndef load_data(sql_paths, table_paths, use_small=False):\n if not isinstance(sql_paths, list):\n sql_paths = (sql_paths, )\n if not isinstance(table_paths, list):\n table_paths = (table_paths, )\n sql_data = []\n table_data = {}\n #所有的标注数据组成一个列表\n for SQL_PATH in sql_paths:\n with open(SQL_PATH, encoding='utf-8') as inf:\n for idx, line in enumerate(inf):\n sql = json.loads(line.strip())\n if use_small and idx >= 1000:\n break\n sql_data.append(sql)\n print (\"Loaded %d data from %s\" % (len(sql_data), SQL_PATH))\n #建立一个数据表的对应,id:每个数据表\n for TABLE_PATH in table_paths:\n with open(TABLE_PATH, encoding='utf-8') as inf:\n for line in inf:\n tab = json.loads(line.strip())\n table_data[tab[u'id']] = tab\n print (\"Loaded %d data from %s\" % (len(table_data), TABLE_PATH))\n #如果标注数据的table_id有对应的数据表,就放入ret_sql_data中\n ret_sql_data = []\n for sql in sql_data:\n if sql[u'table_id'] in table_data: \n ret_sql_data.append(sql) \n\n return ret_sql_data, table_data\n\ndef load_dataset(toy=False, use_small=False, mode='train'):\n print (\"Loading dataset\")\n dev_sql, dev_table = load_data('data/val/val.json', 'data/val/val.tables.json', use_small=use_small)\n dev_db = 'data/val/val.db'\n if mode == 'train':\n train_sql, train_table = load_data('data/train/train.json', 'data/train/train.tables.json', use_small=use_small)\n train_db = 'data/train/train.db'\n return train_sql, train_table, train_db, dev_sql, dev_table, dev_db\n elif mode == 'test':\n test_sql, test_table = load_data('data/test/test.json', 'data/test/test.tables.json', use_small=use_small)\n test_db = 'data/test/test.db'\n return dev_sql, dev_table, dev_db, test_sql, test_table, test_db\n\ndef conds_ques_wrong(conds,question):\n for i,cond in enumerate(conds):\n if cond[2] not in question:\n return True\n return False\n \ndef to_batch_seq(sql_data, table_data, idxes, st, ed, ret_vis_data=False):\n q_seq = []\n col_seq = []\n col_num = []\n ans_seq = []\n gt_cond_seq = []\n vis_seq = []\n sel_num_seq = []\n for i in range(st, ed):\n sql = sql_data[idxes[i]]\n sel_num = len(sql['sql']['sel'])\n sel_num_seq.append(sel_num)\n conds_num = len(sql['sql']['conds'])\n '''\n if conds_ques_wrong(sql['sql']['conds'],sql['question']):\n continue\n '''\n q_seq.append([char for char in sql['question'] if char != ' '])\n col_seq.append([[char for char in header] for header in table_data[sql['table_id']]['header']])\n col_num.append(len(table_data[sql['table_id']]['header']))\n ans_seq.append(\n (\n len(sql['sql']['agg']),\n sql['sql']['sel'],\n sql['sql']['agg'],\n conds_num,\n tuple(x[0] for x in sql['sql']['conds']),\n tuple(x[1] for x in sql['sql']['conds']),\n sql['sql']['cond_conn_op'],\n ))\n gt_cond_seq.append(sql['sql']['conds'])\n vis_seq.append((sql['question'], table_data[sql['table_id']]['header']))\n if ret_vis_data:\n return q_seq, sel_num_seq, col_seq, col_num, ans_seq, gt_cond_seq, vis_seq\n else:\n return q_seq, sel_num_seq, col_seq, col_num, ans_seq, gt_cond_seq\n\ndef to_batch_seq_test(sql_data, table_data, idxes, st, ed):\n q_seq = []\n col_seq = []\n col_num = []\n raw_seq = []\n table_ids = []\n for i in range(st, ed):\n sql = sql_data[idxes[i]]\n q_seq.append([char for char in sql['question'] if char !=' '])\n col_seq.append([[char for char in header] for header in table_data[sql['table_id']]['header']])\n col_num.append(len(table_data[sql['table_id']]['header']))\n raw_seq.append(sql['question'])\n table_ids.append(sql_data[idxes[i]]['table_id'])\n return q_seq, col_seq, col_num, raw_seq, table_ids\n\ndef to_batch_query(sql_data, idxes, st, ed):\n query_gt = []\n table_ids = []\n for i in range(st, ed):\n sql_data[idxes[i]]['sql']['conds'] = sql_data[idxes[i]]['sql']['conds']\n query_gt.append(sql_data[idxes[i]]['sql'])\n table_ids.append(sql_data[idxes[i]]['table_id'])\n return query_gt, table_ids\n\ndef epoch_train(model_bert, tokenizer,model, opt,opt_bert, batch_size, sql_data, table_data):\n model.train()\n perm=np.random.permutation(len(sql_data))\n perm = list(range(len(sql_data)))\n cum_loss = 0.0\n for st in tqdm(range(len(sql_data)//batch_size+1)):\n ed = (st+1)*batch_size if (st+1)*batch_size < len(perm) else len(perm)\n st = st * batch_size\n q_seq, gt_sel_num, col_seq, col_num, ans_seq, gt_cond_seq = to_batch_seq(sql_data, table_data, perm, st, ed)\n # q_seq: char-based sequence of question\n # gt_sel_num: number of selected columns and aggregation functions\n # col_seq: char-based column name\n # col_num: number of headers in one table\n # ans_seq: (sel, number of conds, sel list in conds, op list in conds)\n # gt_cond_seq: ground truth of conds\n gt_where_seq = model.generate_gt_where_seq_test(q_seq, gt_cond_seq)\n gt_sel_seq = [x[1] for x in ans_seq]\n score = model.forward(model_bert, tokenizer,q_seq, col_seq, col_num, gt_where=gt_where_seq, gt_cond=gt_cond_seq, gt_sel=gt_sel_seq, gt_sel_num=gt_sel_num)\n # sel_num_score, sel_col_score, sel_agg_score, cond_score, cond_rela_score\n # compute loss\n \n loss = model.loss(score, ans_seq, gt_where_seq)\n cum_loss += loss.data.cpu().numpy()*(ed - st)\n opt.zero_grad()\n opt_bert.zero_grad()\n loss.backward()\n opt.step()\n opt_bert.step()\n return cum_loss / len(sql_data)\n\ndef predict_test(model_bert, tokenizer,model, batch_size, sql_data, table_data, output_path):\n model.eval()\n perm = list(range(len(sql_data)))\n fw = open(output_path,'w')\n for st in tqdm(range(len(sql_data)//batch_size+1)):\n ed = (st+1)*batch_size if (st+1)*batch_size < len(perm) else len(perm)\n st = st * batch_size\n q_seq, col_seq, col_num, raw_q_seq, table_ids = to_batch_seq_test(sql_data, table_data, perm, st, ed)\n score = model.forward(model_bert, tokenizer, q_seq, col_seq, col_num)\n sql_preds = model.gen_query(score, q_seq, col_seq, raw_q_seq)\n for sql_pred in sql_preds:\n sql_pred = eval(str(sql_pred))\n fw.writelines(json.dumps(sql_pred, ensure_ascii=False)+'\\n')\n # fw.writelines(json.dumps(sql_pred,ensure_ascii=False).encode('utf-8')+'\\n')\n fw.close()\n\ndef get_pred(st,ed):\n f = 'data/pre_val.json'\n pred_queries = []\n with open(f, encoding='utf-8') as inf:\n for idx, line in enumerate(inf):\n sql = json.loads(line.strip())\n if idx>=st and idx<=ed:\n pred_queries.append(sql)\n inf.close()\n return pred_queries\n\ndef epoch_acc(model_bert, tokenizer, model, batch_size, sql_data, table_data, db_path, mode_type):\n engine = DBEngine(db_path)\n model.eval()\n perm = list(range(len(sql_data)))\n badcase = 0\n one_acc_num, tot_acc_num, ex_acc_num = 0.0, 0.0, 0.0\n for st in tqdm(range(len(sql_data)//batch_size+1)):\n ed = (st+1)*batch_size if (st+1)*batch_size < len(perm) else len(perm)\n st = st * batch_size\n q_seq, gt_sel_num, col_seq, col_num, ans_seq, gt_cond_seq, raw_data = \\\n to_batch_seq(sql_data, table_data, perm, st, ed, ret_vis_data=True)\n # q_seq: char-based sequence of question\n # gt_sel_num: number of selected columns and aggregation functions, new added field\n # col_seq: char-based column name\n # col_num: number of headers in one table\n # ans_seq: (sel, number of conds, sel list in conds, op list in conds)\n # gt_cond_seq: ground truth of conditions\n # raw_data: ori question, headers, sql\n query_gt, table_ids = to_batch_query(sql_data, perm, st, ed)\n # query_gt: ground truth of sql, data['sql'], containing sel, agg, conds:{sel, op, value}\n raw_q_seq = [x[0] for x in raw_data] # original question\n score = model.forward(model_bert, tokenizer, q_seq, col_seq, col_num)\n if mode_type == 1:\n pred_queries = model.gen_query(score, q_seq, col_seq, raw_q_seq)\n\n if mode_type == 2:\n pred_queries = get_pred(st,ed)\n # generate predicted format\n one_err, tot_err = model.check_acc(raw_data, pred_queries, query_gt)\n \n one_acc_num += (ed-st-one_err)\n tot_acc_num += (ed-st-tot_err)\n\n # Execution Accuracy\n for sql_gt, sql_pred, tid in zip(query_gt, pred_queries, table_ids):\n ret_gt = engine.execute(tid, sql_gt['sel'], sql_gt['agg'], sql_gt['conds'], sql_gt['cond_conn_op'])\n try:\n ret_pred = engine.execute(tid, sql_pred['sel'], sql_pred['agg'], sql_pred['conds'], sql_pred['cond_conn_op'])\n except:\n ret_pred = None\n ex_acc_num += (ret_gt == ret_pred)\n return one_acc_num / len(sql_data), tot_acc_num / len(sql_data), ex_acc_num / len(sql_data)\n\n\ndef load_word_emb(file_name):\n print ('Loading word embedding from %s'%file_name)\n f = open(file_name)\n ret = json.load(f)\n f.close()\n # ret = {}\n # with open(file_name, encoding='latin') as inf:\n # ret = json.load(inf)\n # for idx, line in enumerate(inf):\n # info = line.strip().split(' ')\n # if info[0].lower() not in ret:\n # ret[info[0]] = np.array([float(x) for x in info[1:]])\n return ret\n\n#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jul 22 18:16:08 2019\n\n@author: laiye\n\"\"\"\ndef gen_l_hpu(i_hds):\n \"\"\"\n # Treat columns as if it is a batch of natural language utterance with batch-size = # of columns * # of batch_size\n i_hds = [(17, 18), (19, 21), (22, 23), (24, 25), (26, 29), (30, 34)])\n \"\"\"\n l_hpu = []\n for i,i_hds1 in enumerate(i_hds): \n for (a,b) in i_hds1:\n l_hpu.append(b - a)\n return l_hpu\n\ndef generate_inputs(tokenizer, nlu1_tok, hds1):\n\n tokens = []\n segment_ids = []\n\n tokens.append(\"[CLS]\")\n i_st_nlu = len(tokens) # to use it later\n\n segment_ids.append(0)\n for token in nlu1_tok:\n tokens.append(token)\n segment_ids.append(0)\n i_ed_nlu = len(tokens)\n tokens.append(\"[SEP]\")\n segment_ids.append(0)\n\n i_hds = []\n # for doc\n for i, hds11 in enumerate(hds1):\n i_st_hd = len(tokens)\n sub_tok = char_tokenize(hds11[0].lower())\n tokens += sub_tok\n i_ed_hd = len(tokens)\n i_hds.append((i_st_hd, i_ed_hd))\n segment_ids += [1] * len(sub_tok)\n if i < len(hds1)-1:\n tokens.append(\"[SEP]\")\n segment_ids.append(0)\n elif i == len(hds1)-1:\n tokens.append(\"[SEP]\")\n segment_ids.append(1)\n else:\n raise EnvironmentError\n\n i_nlu = (i_st_nlu, i_ed_nlu)\n return tokens, segment_ids, i_nlu, i_hds\n\ndef char_tokenize(token):\n sub_tokens = []\n for i in range(0,len(token)):\n if token[i]!=' ':\n sub_tokens.append(token[i])\n return sub_tokens\n\ndef get_bert_output(model_bert, tokenizer, nlu_t, hds, max_seq_length):\n \"\"\"\n Here, input is toknized further by WordPiece (WP) tokenizer and fed into BERT.\n\n INPUT\n :param model_bert:\n :param tokenizer: WordPiece toknizer\n :param nlu: Question\n :param nlu_t: CoreNLP tokenized nlu.\n :param hds: Headers\n :param hs_t: None or 1st-level tokenized headers\n :param max_seq_length: max input token length\n\n OUTPUT\n tokens: BERT input tokens\n nlu_tt: WP-tokenized input natural language questions\n orig_to_tok_index: map the index of 1st-level-token to the index of 2nd-level-token\n tok_to_orig_index: inverse map.\n\n \"\"\"\n\n l_n = []\n l_hs = [] # The length of columns for each batch\n\n input_ids = []\n tokens = []\n segment_ids = []\n input_mask = []\n\n i_nlu = [] # index to retreive the position of contextual vector later.\n i_hds = []\n\n nlu_tt = []\n\n t_to_tt_idx = []\n tt_to_t_idx = []\n for b, nlu_t1 in enumerate(nlu_t):\n\n hds1 = hds[b]\n l_hs.append(len(hds1))\n\n\n # 1. 2nd tokenization using WordPiece\n tt_to_t_idx1 = [] # number indicates where sub-token belongs to in 1st-level-tokens (here, CoreNLP).\n t_to_tt_idx1 = [] # orig_to_tok_idx[i] = start index of i-th-1st-level-token in all_tokens.\n nlu_tt1 = [] # all_doc_tokens[ orig_to_tok_idx[i] ] returns first sub-token segement of i-th-1st-level-token\n for (i, token) in enumerate(nlu_t1):\n token = token.lower()\n t_to_tt_idx1.append(\n len(nlu_tt1)) # all_doc_tokens[ indicate the start position of original 'white-space' tokens.\n sub_tokens = char_tokenize(token)\n for sub_token in sub_tokens:\n tt_to_t_idx1.append(i)\n nlu_tt1.append(sub_token) # all_doc_tokens are further tokenized using WordPiece tokenizer\n nlu_tt.append(nlu_tt1)\n tt_to_t_idx.append(tt_to_t_idx1)\n t_to_tt_idx.append(t_to_tt_idx1)\n\n l_n.append(len(nlu_tt1))\n # hds1_all_tok = tokenize_hds1(tokenizer, hds1)\n\n # [CLS] nlu [SEP] col1 [SEP] col2 [SEP] ...col-n [SEP]\n # 2. Generate BERT inputs & indices.\n tokens1, segment_ids1, i_nlu1, i_hds1 = generate_inputs(tokenizer, nlu_tt1, hds1)\n input_ids1 = tokenizer.convert_tokens_to_ids(tokens1)\n\n # Input masks\n # The mask has 1 for real tokens and 0 for padding tokens. Only real\n # tokens are attended to.\n input_mask1 = [1] * len(input_ids1)\n \n # 3. Zero-pad up to the sequence length.\n while len(input_ids1) < max_seq_length:\n input_ids1.append(0)\n input_mask1.append(0)\n segment_ids1.append(0)\n input_ids1 = input_ids1[0:max_seq_length]\n input_mask1 = input_mask1[0:max_seq_length]\n segment_ids1 = segment_ids1[0:max_seq_length]\n assert len(input_ids1) == max_seq_length\n assert len(input_mask1) == max_seq_length\n assert len(segment_ids1) == max_seq_length\n\n input_ids.append(input_ids1)\n tokens.append(tokens1)\n segment_ids.append(segment_ids1)\n input_mask.append(input_mask1)\n\n i_nlu.append(i_nlu1)\n i_hds.append(i_hds1)\n # Convert to tensor\n all_input_ids = torch.tensor(input_ids, dtype=torch.long).to(device)\n all_input_mask = torch.tensor(input_mask, dtype=torch.long).to(device)\n all_segment_ids = torch.tensor(segment_ids, dtype=torch.long).to(device)\n # 4. Generate BERT output.\n all_encoder_layer, pooled_output = model_bert(all_input_ids, all_segment_ids, all_input_mask)\n # 5. generate l_hpu from i_hds\n l_hpu = gen_l_hpu(i_hds)\n return all_encoder_layer, pooled_output, tokens, i_nlu, i_hds, \\\n l_n, l_hpu, l_hs, \\\n nlu_tt, t_to_tt_idx, tt_to_t_idx\n\n\ndef get_bert(BERT_PT_PATH):\n\n bert_config_file = os.path.join(BERT_PT_PATH, 'bert_config.json')\n vocab_file = os.path.join(BERT_PT_PATH, 'vocab.txt')\n init_checkpoint = os.path.join(BERT_PT_PATH, 'pytorch_model.bin')\n\n\n bert_config = BertConfig.from_json_file(bert_config_file)\n tokenizer = tokenization.FullTokenizer(vocab_file=vocab_file)\n bert_config.print_status()\n\n model_bert = BertModel(bert_config)\n\n model_bert.load_state_dict(torch.load(init_checkpoint, map_location='cpu'))\n print(\"Load pre-trained parameters.\")\n model_bert.to(device)\n\n return model_bert, tokenizer, bert_config\n\ndef get_wemb_n(i_nlu, l_n, hS, num_hidden_layers, all_encoder_layer, num_out_layers_n):\n \"\"\"\n Get the representation of each tokens.\n \"\"\"\n bS = len(l_n)\n l_n_max = max(l_n)\n wemb_n = torch.zeros([bS, l_n_max, hS * num_out_layers_n]).to(device)\n for b in range(bS):\n # [B, max_len, dim]\n # Fill zero for non-exist part.\n l_n1 = l_n[b]\n i_nlu1 = i_nlu[b]\n for i_noln in range(num_out_layers_n):\n i_layer = num_hidden_layers - 1 - i_noln\n st = i_noln * hS\n ed = (i_noln + 1) * hS\n wemb_n[b, 0:(i_nlu1[1] - i_nlu1[0]), st:ed] = all_encoder_layer[i_layer][b, i_nlu1[0]:i_nlu1[1], :]\n return wemb_n\n\ndef get_wemb_h(i_hds, l_hpu, l_hs, hS, num_hidden_layers, all_encoder_layer, num_out_layers_h):\n \"\"\"\n As if\n [ [table-1-col-1-tok1, t1-c1-t2, ...],\n [t1-c2-t1, t1-c2-t2, ...].\n ...\n [t2-c1-t1, ...,]\n ]\n \"\"\"\n bS = len(l_hs)\n \n l_hpu_max = max(l_hpu)\n num_of_all_hds = sum(l_hs)\n wemb_h = torch.zeros([num_of_all_hds, l_hpu_max, hS * num_out_layers_h]).to(device)\n b_pu = -1\n for b, i_hds1 in enumerate(i_hds):\n for b1, i_hds11 in enumerate(i_hds1):\n b_pu += 1\n for i_nolh in range(num_out_layers_h):\n i_layer = num_hidden_layers - 1 - i_nolh\n st = i_nolh * hS\n ed = (i_nolh + 1) * hS\n if i_hds11[1] > 129:\n continue\n wemb_h[b_pu, 0:(i_hds11[1] - i_hds11[0]), st:ed] \\\n = all_encoder_layer[i_layer][b, i_hds11[0]:i_hds11[1],:]\n\n return wemb_h\n\ndef gen_ques_emb(model_bert, tokenizer,q_seq,col_seq):\n hidden_size = 768\n num_hidden_layers = 12\n max_seq_length = 130\n #nlu_t = [[\"小明今天去上学\"],[\"张巍好人\"]]\n #hds = [[['时间']],[['地点']]]\n all_encoder_layer, pooled_output, tokens, i_nlu, i_hds, \\\n l_n, l_hpu, l_hs, \\\n nlu_tt, t_to_tt_idx, tt_to_t_idx = get_bert_output(model_bert, tokenizer, q_seq, col_seq, max_seq_length)\n wemb_n = get_wemb_n(i_nlu, l_n, hidden_size, num_hidden_layers, all_encoder_layer,\n num_out_layers_n=1)\n wemb_h = get_wemb_h(i_hds, l_hpu, l_hs, hidden_size, num_hidden_layers, all_encoder_layer,\n num_out_layers_h=1)\n wemb_n = Variable(wemb_n)\n wemb_h = Variable(wemb_h)\n B = len(q_seq)\n x_len = np.zeros(B, dtype=np.int64)\n for i in range(0,len(q_seq)): \n x_len[i] = i_nlu[i][1] - i_nlu[i][0]\n \n C = 0\n for i ,i_hds1 in enumerate(i_hds):\n for (a,b) in i_hds1:\n C = C+1\n name_len = np.zeros(C,dtype=np.int64)\n \n m = 0\n num = 0\n for i ,i_hds1 in enumerate(i_hds):\n for (a,b) in i_hds1:\n num = b-a\n name_len[m] = num \n m = m+1\n col_len = gen_col_batch(col_seq)\n\n return wemb_n,x_len,wemb_h,name_len, col_len\n\ndef gen_col_batch(col_seq):\n col_len = np.zeros(len(col_seq), dtype=np.int64)\n\n names = []\n for b, one_cols in enumerate(col_seq):\n names = names + one_cols\n col_len[b] = len(one_cols)\n \n return col_len\n\ndef str_list_to_batch(str_list):\n B = len(str_list)\n\n val_len = np.zeros(B, dtype=np.int64)\n for i, one_str in enumerate(str_list):\n val_len[i] = len(one_str[0])\n return val_len\n\ndef char_base_to_raw_text(q_seq,col_seq):\n q_seq_new = []\n string = '1'\n for i,char_list in enumerate(q_seq):\n for j in range(0,len(char_list)):\n if char_list[j] != ' ':\n string = string+char_list[j]\n string = string+'2'\n q_tem = []\n q_tem.append(string)\n string = '1'\n q_seq_new.append(q_tem)\n c_seq_new = []\n for i,char_list in enumerate(col_seq):\n c_tem = []\n for j,sub_char_list in enumerate(char_list):\n c_sub_tem = []\n for k in range(0,len(sub_char_list)):\n string = string+sub_char_list[k]\n string = string+'2'\n c_sub_tem.append(string)\n c_tem.append(c_sub_tem)\n string = '1'\n c_seq_new.append(c_tem)\n \n return q_seq_new,c_seq_new\n \n \nif __name__ == '__main__':\n bert_path = 'chinese_L-12_H-768_A-12'\n model_bert, tokenizer, bert_config = get_bert(bert_path)\n \n q_seq = [['P', 'E', '(', '对', '应', '2', '0', '1', '8', '.', '1', '0', '.', '3', '1', '收', '盘', '价', ')']]\n col_seq = [[['P', 'E', '(', '对', '应', '2', '0', '1', '8', '.', '1', '0', '.', '3', '1', '收', '盘', '价', ')']]]\n q_seq,col_seq = char_base_to_raw_text(q_seq,col_seq)\n \n '''\n q_seq = [['你好啊,你帮我算一下到底有多少家公司一六年定向增发新股,并且是为了融资收购其他资产的呀']]\n col_seq = [[['时间'],['你好呀']]]\n '''\n wemb_n,x_len,wemb_h,name_len, col_len = gen_ques_emb(model_bert, tokenizer, q_seq, col_seq)\n print('que_size',wemb_n.size())\n print('x_len',x_len)\n print('head_size',wemb_h.size())\n print('name_len',name_len)\n print(col_len)\n\n\n \n"
] | [
[
"torch.load",
"torch.zeros",
"torch.tensor",
"torch.cuda.is_available",
"numpy.zeros",
"torch.autograd.Variable"
]
] |
NurmanZahin/smile_detector | [
"fde21c5d590bfc0e9b2d978d4f486b64a15b9186"
] | [
"src/inference.py"
] | [
"import numpy as np\nimport argparse\nimport cv2\nimport tensorflow as tf\nimport io\nimport logging\nimport matplotlib.pyplot as plt\n\nfrom PIL import Image\nfrom tensorflow.keras.applications.mobilenet_v2 import preprocess_input\n\nlogging.basicConfig(level=logging.INFO, format='%(asctime)s:%(levelname)s:%(name)s:%(message)s')\nlogger = logging.getLogger('inference')\nIMAGE_SIZE = (224, 224)\n\n\ndef face_detect(face_detector, img):\n \"\"\"Takes a image path as input and a face detector and outputs the grayed image and the coordinates of the face detected\"\"\"\n test_img = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)\n grayed_img = cv2.cvtColor(test_img, cv2.COLOR_BGR2GRAY)\n face_coordinates = face_detector.detectMultiScale(grayed_img, 1.1, 5)\n return grayed_img, face_coordinates\n\n\ndef extract_face(img, face_coordinates):\n \"\"\"Takes an image and face coordinates as input and crops out the face and does the mobilenet preprocessing required\"\"\"\n if len(face_coordinates)==0:\n return 'No face detected'\n for (x, y, w, h) in face_coordinates:\n extracted_face = cv2.resize(img[y:y+h, x:x+w], (224, 224))\n extracted_face = cv2.cvtColor(extracted_face, cv2.COLOR_GRAY2RGB)\n extracted_face = preprocess_input(extracted_face)\n\n return extracted_face\n\n\ndef load_input_img(img_data):\n \"\"\"Loads an image from the input file path and resize to 450, 450\"\"\"\n if isinstance(img_data, str):\n with open(img_data, 'rb') as file:\n img_bytes = file.read()\n elif isinstance(img_data, (bytes, bytearray)):\n img_bytes = img_data\n else:\n img_bytes = img_data.read()\n img = Image.open(io.BytesIO(img_bytes)).convert('RGB')\n return img\n\n\ndef classify_img(classifier, img_arr):\n \"\"\"Predicts on the input img array and returns the classification\n\n Parameters:\n ----------\n classifier: the model/classifier to be used\n imr_arr (numpy array): the preprocessed image in numpy array form\n class_names (list): the list of food names/categories\n\n Returns:\n ----------\n classification (string): the category of the image\n confidence (float): the confidence of the prediction\n \"\"\"\n labels = ('not smiling', 'smiling')\n prediction = classifier.predict(img_arr)[0]\n pred_label = np.argmax(prediction)\n confidence = prediction[pred_label]\n return labels[pred_label], confidence\n\n\ndef predict_image(img_file_path, model, face_detector):\n \"\"\"\n Takes a file path to the image as input and predicts the type of food\n\n Parameters:\n ----------\n file_path (string): file path to the image to be predicted\n img_file_path (string): file path to the image to be predicted\n class_names (list): list of strings of each food type\n\n Returns:\n food_type (string): the predicted type of food based on input image\n \"\"\"\n logger.info(f'Loading image {img_file_path}')\n loaded_img = load_input_img(img_file_path)\n grayed_img, face_coord = face_detect(face_detector, loaded_img)\n\n if len(face_coord) == 0:\n return 'Face not detected'\n\n else:\n face_extract = extract_face(grayed_img, face_coord)\n img_array = np.expand_dims(face_extract, axis=0)\n smile_type, conf = classify_img(model, img_array)\n logger.info(f'Prediction Complete')\n return smile_type, conf, face_coord\n\n\ndef visualize_classifier(img_path, smile_classifier, face_detector):\n font_scale = 1.2\n font = cv2.FONT_HERSHEY_PLAIN\n\n smile_class, conf, face_coor = predict_image(img_path, smile_classifier, face_detector)\n img = cv2.imread(img_path)\n\n msg = f'{smile_class}, {conf:.3f}'\n t_size = cv2.getTextSize(smile_class, 0, fontScale=font_scale, thickness=1)[0]\n for (x, y, w, h) in face_coor:\n cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)\n cv2.rectangle(img, (x, y), (x + t_size[0], y-t_size[1]-3), (0,0,0), -1) # filled\n cv2.putText(img, msg, (x, y-2), cv2.FONT_HERSHEY_SIMPLEX, font_scale, (255, 255, 255), 2, lineType=cv2.LINE_AA)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n plt.imshow(img)\n plt.show()\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('img_file_path', type=str)\n parser.add_argument('--model_path', type=str, default='data/models/tf_mobilenetv2.h5')\n parser.add_argument('--face_path', type=str, default='haarcascade_frontalface_default.xml')\n\n args = parser.parse_args()\n image_path = args.img_file_path\n model_path = args.model_path\n face_det_path = args.face_path\n test_model = tf.keras.models.load_model(model_path)\n face_detector = cv2.CascadeClassifier(face_det_path)\n # predict_image(image_path, test_model, face_detector)\n visualize_classifier(image_path, test_model, face_detector)\n"
] | [
[
"tensorflow.keras.models.load_model",
"matplotlib.pyplot.imshow",
"numpy.expand_dims",
"tensorflow.keras.applications.mobilenet_v2.preprocess_input",
"numpy.argmax",
"numpy.array",
"matplotlib.pyplot.show"
]
] |
ashtou/spec17-ml | [
"1c79d3f2fe242b1e5abc87e4db9e2c1485c28284"
] | [
"spec/predict/data_load_clean.py"
] | [
"#### JS to download all the urls from the page: https://www.spec.org/cpu2017/results/cpu2017.html\n#### Save the results in the corresponding text files and remove the '[' and ']' chars.\n# all_hrefs = []\n# all_csvs = document.getElementById(\"CINT2017_speeddiv\").querySelectorAll('table > tbody> tr > td > span > a[href*=\"csv\"]');console.log(all_csvs.length)\n# for(var i=0; i<all_csvs.length;i++) {all_hrefs[i] = all_csvs[i].href}\n# console.log(JSON.stringify(all_hrefs))\n####\n\n#### Python to download all the files from a list in a txt file\n# %reset -s -f\n# import os, time\n# import urllib.request\n\n# category = 'choose!!'\n# #category = 'FP_rate'\n# #category = 'FP_speed'\n# #category = 'Int_rate'\n# #category = 'Int_speed'\n\n# text_file = open(category + \".txt\", \"r\")\n# lines = text_file.read().replace('\"', '').split(',')\n# print(len(lines))\n\n# # Download the file from `url` and save it locally under `dl_file`:\n# for i in range (0, len(lines)):\n# dl_file = category+\"_CSVs/\" + lines[i].rsplit('/', 1)[1]\n# if not os.path.isfile(dl_file):\n# urllib.request.urlretrieve(lines[i], dl_file)\n# time.sleep(0.02)\n# print(\"done\")\n\n####\nimport os\nimport csv\nimport numpy as np\nimport pandas as pd\nimport re # regex\n\n# from IPython.display import display # for Jupyter\n# pd.set_option('display.max_columns', None) # show all columns when display\n# pd.set_option('display.max_rows', None)\n\n\ndef write_cvs_to_inputs(suite, data_rec, RECOM=False, RATING=None):\n \"\"\"\n Loads from SPEC 2017 results CSV files and populates the input files. \n RECOM and RATING parameters are only valid for the Recommendation part\n \"\"\"\n # for recom\n if RECOM == True:\n min_Rate, min_Time, max_Rate, max_Time = {}, {}, {}, {}\n\n cat = suite[\"name\"]\n for bench in suite[\"benchmarks\"]:\n data_rec[bench] = \"\"\n data_rec[\"t_\" + bench] = \"\"\n\n if RECOM == False:\n with open(\"data/in/input_\" + cat + \".csv\", \"w\") as csvfile:\n csvfile.write(\",\".join(data_rec.keys()) + \"\\n\")\n # for recom\n else:\n min_Rate[bench] = 10 ** 30\n max_Rate[bench] = 0\n min_Time[\"t_\" + bench] = 10 ** 30\n max_Time[\"t_\" + bench] = 0\n with open(\"data/in/recom_input_\" + cat + \".csv\", \"w\") as csvfile:\n csvfile.write(\"user,item,Rate,Time\\n\") # NO space\n\n CSVs_path = \"data/\" + cat + \"_CSVs/\"\n for f in os.listdir(CSVs_path):\n # automatically ignores commas inside \"str,str\".\n # also 'encoding' and 'errors' replace strange characters down in Notes\n with open(CSVs_path + f, encoding=\"utf-8\", errors=\"replace\") as csv_inp:\n reader = csv.reader(csv_inp)\n\n # Clear values of of the dict\n data_rec = {key: \"\" for key in data_rec}\n\n # benchmark_start = 0\n # benchmark_end = 0\n sel_bench_start = False\n sel_bench_end = False\n\n try:\n # Tip: make a list of rows to use indexes from csv.reader\n reader_list = list(reader)\n # Iterate over each row in the CSV\n # if you need the index to mark benchmark_start and end, then\n # `for i,row in enumerate(reader):``\n for ind, row in enumerate(reader_list):\n if len(row) > 0:\n if row[0] == \"Selected Results Table\":\n sel_bench_start = True\n\n if cat == \"CINT2017_speed\":\n if row[0] == \"SPECspeed2017_int_base\":\n sel_bench_end = True\n\n elif cat == \"CFP2017_speed\":\n if row[0] == \"SPECspeed2017_fp_base\":\n sel_bench_end = True\n\n elif cat == \"CINT2017_rate\":\n if row[0] == \"SPECrate2017_int_base\":\n sel_bench_end = True\n\n elif cat == \"CFP2017_rate\":\n if row[0] == \"SPECrate2017_fp_base\":\n sel_bench_end = True\n\n # Selected Benchmark Results area\n if sel_bench_start == True and sel_bench_end == False:\n # NOTE: It seems that all benchmarks on the same machine\n # are run with the same number of threads\n # Do not read empty values, let Pandas put NaN.\n # Otherwise you will add empty strings to the dataset.\n if row[0] == suite[\"benchmarks\"][0] and row[1] != \" \":\n if row[1] == \"NC\":\n break # break if Not Compliant (NC)\n try:\n data_rec[\"threads_or_copies\"] = int(row[1])\n except:\n # a case like '16/2', just mark it as NC by breaking\n break\n\n # row[2] = Base Run Time, row[3] = Base Ratio\n for bench in suite[\"benchmarks\"]:\n if row[0] == bench and row[3] != \" \":\n data_rec[\"t_\" + bench] = float(row[2])\n data_rec[bench] = float(row[3])\n\n # Hardware vendor is different from vendor\n if row[0] == \"Hardware Vendor:\" and row[1] != \" \":\n data_rec[\"hardware_vendor\"] = row[1].strip()\n # Grab the vendor and machine model name\n if row[0] == \"CPU Name\" and row[1] != \" \":\n full_name = row[1].split(\" \")\n data_rec[\"vendor\"] = full_name[0].strip()\n data_rec[\"model_name\"] = \" \".join(full_name[1:])\n\n if row[0] == \"Test sponsor:\" and row[1] != \" \":\n data_rec[\"test_sponsor\"] = row[1].strip()\n\n # Do not read empty values, let Pandas put NaN.\n # Otherwise you will add empty strings to the dataset.\n # You know you have done it right if the type of\n # max_mhz in the dataframe becomes 'float64' and not 'object'.\n # If it is object, you are probably adding a string somewhere\n if row[0].strip().startswith(\"Max MHz\") and row[1] != \" \":\n data_rec[\"max_mhz\"] = row[1]\n if row[0] == \" Nominal\" and row[1] != \" \":\n data_rec[\"nominal_mhz\"] = row[1]\n\n # form lscpu:\n if \"Architecture:\" in row[0]:\n data_rec[\"arch\"] = (\n row[0].strip().split(\"Architecture:\", 1)[1].strip()\n )\n if (\n \"CPU(s):\" in row[0]\n # only the row which contains CPU(s): xx,\n # so the first bit after the split should be empty\n and row[0].strip().split(\"CPU(s):\", 1)[0] == \"\"\n ):\n data_rec[\"cpus\"] = int(\n row[0].strip().split(\"CPU(s):\", 1)[1].strip()\n )\n if \"Thread(s) per core:\" in row[0]:\n data_rec[\"threads_per_core\"] = int(\n row[0]\n .strip()\n .split(\"Thread(s) per core:\", 1)[1]\n .strip()\n )\n if \"Core(s) per socket:\" in row[0]:\n data_rec[\"cores_per_socket\"] = int(\n row[0]\n .strip()\n .split(\"Core(s) per socket:\", 1)[1]\n .strip()\n )\n if \"Socket(s):\" in row[0]:\n data_rec[\"sockets\"] = int(\n row[0].strip().split(\"Socket(s):\", 1)[1].strip()\n )\n if \"NUMA node(s):\" in row[0]:\n data_rec[\"numas\"] = int(\n row[0].strip().split(\"NUMA node(s):\", 1)[1].strip()\n )\n\n if (\n \"NAME=\" in row[0]\n and row[0].strip().split(\"NAME=\", 1)[0].strip() == \"\"\n ): # only the row which contains the exact 'NAME=xxx'\n os_name = (\n row[0]\n .strip()\n .split(\"NAME=\", 1)[1]\n .replace('\"', \"\")\n .strip()\n )\n if os_name.startswith(\"SLE\"):\n # TODO: IMPORTANT: IN order to get rid of SLES_HPC\n # outliers, we needed to make this change\n os_name = \"SLES\"\n if os_name.startswith(\"Red Hat Enterprise Linux\"):\n os_name = \"RHEL\"\n # TODO: IMPORTANT: all the OSs in all categories are\n # RHEL Servers, we chose this name, because there are\n # a few in the CINT_SPEED that are not servers\n # and they ruin the game!\n if os_name.startswith(\"CentOS\"):\n os_name = \"CentOS\"\n data_rec[\"os_name\"] = os_name\n if (\n \"VERSION_ID=\" in row[0]\n and row[0].strip().split(\"VERSION_ID=\", 1)[0].strip() == \"\"\n ):\n os_vid = (\n row[0]\n .strip()\n .split(\"VERSION_ID=\", 1)[1]\n .replace('\"', \"\")\n .strip()\n )\n data_rec[\"os_vid\"] = os_vid\n\n if row[0] == \"Cache L1\" and row[1] != \" \":\n info = row[1].split(\" \")\n if info[1] == \"KB\" and info[2] == \"I\":\n data_rec[\"l1i_cache_kb\"] = info[0]\n elif info[1] == \"MB\" and info[2] == \"I\":\n data_rec[\"l1i_cache_kb\"] = float(info[0]) * 1024\n if info[5] == \"KB\" and info[6] == \"D\":\n data_rec[\"l1d_cache_kb\"] = info[4]\n elif info[5] == \"MB\" and info[6] == \"D\":\n data_rec[\"l1d_cache_kb\"] = float(info[4]) * 1024\n\n if row[0].strip() == \"L2\" and row[1] != \" \":\n info = row[1].strip().split(\" \")\n if info[1] == \"KB\" and info[2] == \"I+D\":\n data_rec[\"l2_cache_kb\"] = info[0]\n elif info[1] == \"MB\" and info[2] == \"I+D\":\n data_rec[\"l2_cache_kb\"] = float(info[0]) * 1024\n\n if row[0].strip() == \"L3\" and row[1] != \" \":\n info = (\n row[1].strip().split(\" \")\n ) # seen cases like ' xx MB', hence strip()\n if info[1] == \"KB\" and info[2] == \"I+D\":\n data_rec[\"l3_cache_kb\"] = info[0]\n elif info[1] == \"MB\" and info[2] == \"I+D\":\n data_rec[\"l3_cache_kb\"] = float(info[0]) * 1024\n elif info[1] == \"GB\" and info[2] == \"I+D\":\n data_rec[\"l3_cache_kb\"] = float(info[0]) * 1024 * 1024\n\n # Note: since memory info is sometimes incorrect,\n # we first check to see if meminfo is available\n if \"MemTotal:\" in row[0]:\n # 2 splits as it is in the format: xxx kB\n data_rec[\"mem_kb\"] = int(\n row[0].strip().split(\"MemTotal:\")[1].split()[0].strip()\n )\n if row[0] == \"Memory\" and row[1] != \" \":\n info = row[1].strip().split(\" \")\n if (\n data_rec[\"mem_kb\"] == \"\"\n ): # if not filled by info from meminfo\n if info[1] == \"GB\":\n data_rec[\"mem_kb\"] = float(info[0]) * 1024 * 1024\n elif info[1] == \"TB\":\n data_rec[\"mem_kb\"] = (\n float(info[0]) * 1024 * 1024 * 1024\n )\n else:\n # there is an instance like that in CFP_speed\n # where they put MB instead of GB\n data_rec[\n \"threads_or_copies\"\n ] = \"\" # Treat the case like an 'NC' case and break\n # raise ValueError('Memory not in GB, File: ', f)\n break\n # TODO: Double check the memory channels with someone!\n if len(info) > 2 and info[2] != \" \":\n data_rec[\"mem_channels\"] = info[2][1:]\n if len(info) > 5 and info[4] != \" \":\n if info[5] == \"MB\":\n data_rec[\"channel_kb\"] = float(info[4]) * 1024\n elif info[5] == \"GB\":\n data_rec[\"channel_kb\"] = (\n float(info[4]) * 1024 * 1024\n )\n elif info[5] == \"TB\":\n data_rec[\"channel_kb\"] = (\n float(info[4]) * 1024 * 1024 * 1024\n )\n\n for s in info:\n if \"-\" in s:\n m = re.search(\"-(.+?)-\", s)\n if (\n m\n ): # like above, we deal with empty records later\n found = m.group()\n try:\n # it will raise an exception if not possible\n speed = int(\n re.search(r\"\\d+\", found).group()\n )\n data_rec[\"mem_data_rate\"] = speed\n except:\n raise ValueError(\n \"Mem speed not int, File: \", f\n )\n\n if row[0] == \"Storage\" and row[1] != \" \":\n info = row[1].split(\" \")\n for i in range(len(info)):\n try:\n if (\n info[i].lower().replace(\",\", \"\") == \"gb\"\n ): # seen cases like Gb!\n data_rec[\"storage_gb\"] = float(info[i - 1])\n if \"storage_type\" in data_rec:\n data_rec[\"storage_type\"] = \" \".join(\n info[i + 1 :]\n )\n if (\n \" \".join(info[i + 1 :])\n == \"ZFS mirror on 2x 15K RPM 300 GB\"\n ): # Baeline Sun machine\n # pc100 = 100MT/s\n # https://en.wikipedia.org/wiki/CAS_latency\n data_rec[\"mem_data_rate\"] = 100\n # to avoid cases where there are two GBs,\n # one at the end of the info with nothing after!\n break\n elif info[i].lower().replace(\",\", \"\") == \"tb\":\n data_rec[\"storage_gb\"] = (\n float(info[i - 1]) * 1024\n )\n if \"storage_type\" in data_rec:\n data_rec[\"storage_type\"] = \" \".join(\n info[i + 1 :]\n )\n elif (\n \"gb\" in info[i].lower()\n ): # or if information is like xxGB\n data_rec[\"storage_gb\"] = float(\n info[i].replace(\",\", \"\")[:-2]\n )\n if \"storage_type\" in data_rec:\n data_rec[\"storage_type\"] = \" \".join(\n info[i + 1 :]\n )\n elif \"tb\" in info[i].lower():\n data_rec[\"storage_gb\"] = (\n float(info[i].replace(\",\", \"\")[:-2]) * 1024\n )\n if \"storage_type\" in data_rec:\n data_rec[\"storage_type\"] = \" \".join(\n info[i + 1 :]\n )\n except:\n # Treat the case like an 'NC' case and\n # break (seen invalid entries like: 1.92 TB GB)\n data_rec[\"threads_or_copies\"] = \"\"\n # or raise ValueError('Storage problem, File: ', f)\n break\n\n if row[0] == \"OS\" and row[1] != \" \":\n data_rec[\"os\"] = row[1].strip()\n\n if row[0] == \"Compiler\" and row[1] != \" \":\n if not \"Intel\" in row[1] and not \"AOCC\" in row[1]:\n # Treat the case like an 'NC' case,\n # NOTE: for now we just ignore a few complicated cases\n data_rec[\"threads_or_copies\"] = \"\"\n break\n # semicolon shifts the data when writing to csv\n # using DictWriter (acts as a delimiter)\n data_rec[\"compiler\"] = row[1].strip().replace(\";\", \"\")\n\n # Parallel: This field is automatically set to \"Yes\"\n # if compiler flags are used that are marked with the\n # parallel attribute, indicating that they cause\n # either automatic or explicit parallelism.\n if row[0] == \"Parallel\" and row[1] != \" \":\n data_rec[\"parallel\"] = row[1]\n\n if row[0] == \"File System\" and row[1] != \" \":\n if \"ramfs\" in row[1]:\n # Treat the case like an 'NC' case,\n # NOTE: for now we just ignore a few cases or ramfs\n data_rec[\"threads_or_copies\"] = \"\"\n break\n data_rec[\"file_system\"] = row[1]\n\n except:\n raise ValueError(\"File has a problem: \", f)\n\n if data_rec[\"threads_or_copies\"]: # if not empty as a result of 'NC'\n data_rec[\n \"file\"\n ] = f.rstrip() # some files have a space after the extension!\n if RECOM == False:\n with open(\"data/in/input_\" + cat + \".csv\", \"a\") as csvInp:\n w = csv.DictWriter(csvInp, data_rec.keys())\n # we don't need that as we have written the headers once\n # w.writeheader()\n w.writerow(data_rec)\n #####\n # recom\n else: # write to recom\n with open(\"data/in/recom_input_\" + cat + \".csv\", \"a\") as recInp:\n for bench in data_rec:\n if (\n bench in suite[\"benchmarks\"]\n ): # benchmarks are like \"users\" in recom context\n if RATING == \"log\":\n if np.log(data_rec[bench]) < min_Rate[bench]:\n min_Rate[bench] = np.log(data_rec[bench])\n if np.log(data_rec[bench]) > max_Rate[bench]:\n max_Rate[bench] = np.log(data_rec[bench])\n\n if (\n np.log(data_rec[\"t_\" + bench])\n < min_Time[\"t_\" + bench]\n ):\n min_Time[\"t_\" + bench] = np.log(\n data_rec[\"t_\" + bench]\n )\n if (\n np.log(data_rec[\"t_\" + bench])\n > max_Time[\"t_\" + bench]\n ):\n max_Time[\"t_\" + bench] = np.log(\n data_rec[\"t_\" + bench]\n )\n else:\n if data_rec[bench] < min_Rate[bench]:\n min_Rate[bench] = data_rec[bench]\n if data_rec[bench] > max_Rate[bench]:\n max_Rate[bench] = data_rec[bench]\n\n if data_rec[\"t_\" + bench] < min_Time[\"t_\" + bench]:\n min_Time[\"t_\" + bench] = data_rec[\"t_\" + bench]\n if data_rec[\"t_\" + bench] > max_Time[\"t_\" + bench]:\n max_Time[\"t_\" + bench] = data_rec[\"t_\" + bench]\n\n recInp.write(bench)\n # we need unique systems (\"items\" in recom context) and\n # the only unique field is 'file'!\n recInp.write(\",\" + data_rec[\"file\"])\n if RATING == \"log\":\n recInp.write(\",\" + str(np.log(data_rec[bench])))\n recInp.write(\n \",\" + str(np.log(data_rec[\"t_\" + bench]))\n )\n else:\n recInp.write(\",\" + str(data_rec[bench]))\n recInp.write(\",\" + str(data_rec[\"t_\" + bench]))\n recInp.write(\"\\n\")\n # only for recom, return values too, which are the min and max Rates\n # (or rating range in a recommendation context)\n if RECOM == True:\n return min_Rate, max_Rate, min_Time, max_Time\n\n\ndef remove_nan(df, cols):\n # print(df[pd.isna(df.model_name)]) #TODO: handle that?\n for col in cols:\n df = df[~pd.isna(df[col])]\n # df = df[df['threads_or_copies'] < 200]\n # print(\"size after threads: \", len(df))\n return df\n\n\ndef find_anomalies(series):\n anomalies = []\n # Set upper and lower limit to 3 standard deviation\n series_std = np.std(series)\n series_mean = np.mean(series)\n anomaly_cut_off = series_std * 3\n\n lower_limit = series_mean - anomaly_cut_off\n upper_limit = series_mean + anomaly_cut_off\n print(\"limits for anomaly: \", lower_limit, upper_limit)\n # Generate outliers\n for outlier in series:\n if outlier > upper_limit or outlier < lower_limit:\n anomalies.append(outlier)\n return anomalies\n"
] | [
[
"numpy.std",
"pandas.isna",
"numpy.mean",
"numpy.log"
]
] |
yaroslavvb/imperative | [
"d08f08b4febc9005f7d91feaeb59ca18fbbca486"
] | [
"tests/extra/histogram_ops_test.py"
] | [
"# Copyright 2015 Google Inc. 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 tensorflow.ops.histogram_ops.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport tensorflow as tf\n\n# tf-imperative replacements\ntry:\n from tensorflow.contrib import imperative\n from tensorflow.contrib.imperative.python.imperative import test_util\nexcept:\n import imperative\n from imperative import test_util\n\nenv = imperative.Env(tf)\ntf = env.tf\n\n\nclass HistogramFixedWidthTest(test_util.TensorFlowTestCase):\n\n def setUp(self):\n self.rng = np.random.RandomState(0)\n\n def test_empty_input_gives_all_zero_counts(self):\n # Bins will be:\n # (-inf, 1), [1, 2), [2, 3), [3, 4), [4, inf)\n value_range = [0.0, 5.0]\n values = []\n expected_bin_counts = [0, 0, 0, 0, 0]\n with self.test_session():\n hist = tf.histogram_fixed_width(values, value_range, nbins=5)\n\n # Hist should start \"fresh\" with every eval.\n self.assertAllClose(expected_bin_counts, hist.eval())\n self.assertAllClose(expected_bin_counts, hist.eval())\n\n def test_one_update_on_constant_input(self):\n # Bins will be:\n # (-inf, 1), [1, 2), [2, 3), [3, 4), [4, inf)\n value_range = [0.0, 5.0]\n values = [-1.0, 0.0, 1.5, 2.0, 5.0, 15]\n expected_bin_counts = [2, 1, 1, 0, 2]\n with self.test_session():\n hist = tf.histogram_fixed_width(values, value_range, nbins=5)\n\n # Hist should start \"fresh\" with every eval.\n self.assertAllClose(expected_bin_counts, hist.eval())\n self.assertAllClose(expected_bin_counts, hist.eval())\n\n def test_one_update_on_constant_2d_input(self):\n # Bins will be:\n # (-inf, 1), [1, 2), [2, 3), [3, 4), [4, inf)\n value_range = [0.0, 5.0]\n values = [[-1.0, 0.0, 1.5], [2.0, 5.0, 15]]\n expected_bin_counts = [2, 1, 1, 0, 2]\n with self.test_session():\n hist = tf.histogram_fixed_width(values, value_range, nbins=5)\n\n # Hist should start \"fresh\" with every eval.\n self.assertAllClose(expected_bin_counts, hist.eval())\n self.assertAllClose(expected_bin_counts, hist.eval())\n\n\nif __name__ == '__main__':\n tf.test.main()\n"
] | [
[
"tensorflow.histogram_fixed_width",
"numpy.random.RandomState",
"tensorflow.test.main"
]
] |
evankrause/covid-path-planning | [
"a65c29e752de9a07437cbde7e381330729ea6048"
] | [
"final_pipeline/order_path.py"
] | [
"from __future__ import print_function\nimport math\nimport sys\n\nfrom dijkstar import Graph, find_path\nfrom pandas import np\nfrom ortools.constraint_solver import routing_enums_pb2\nfrom ortools.constraint_solver import pywrapcp\n\n\n# TODO: optimize this method to get rid of the terribly slow image iterations\ndef order_path(gray_img, locs, xy_to_pixel):\n # starting location\n # TODO: pass this in dynamically\n start_loc = locs[0]\n\n # construct 2d cost map where each entry is cost to move from neighboring pixel\n h, w = np.shape(gray_img)\n\n # iterate over the entire image and build graph for dijkstra calculations\n print('Converting map into graph.')\n graph = Graph()\n # NOTE: this isn't using the values in the map yaml (0.196) for free_thresh but instead assumes\n # 0 = occupied, 205 = unknown, 254 = free\n free_thresh = 220\n diag_cost = np.sqrt(2)\n lin_cost = 1\n for py in range(1, h - 1):\n for px in range(1, w - 1):\n if gray_img[py][px] < free_thresh:\n # obstacle -- skip it\n continue\n i = py * w + px\n for py2 in range(py - 1, py + 2):\n for px2 in range(px - 1, px + 2):\n if gray_img[py2][px2] < free_thresh:\n # obstacle -- skip it\n continue\n if px == px2 and py == py2:\n # same as \"center\" pixel -- skip it\n continue\n\n i2 = py2 * w + px2\n if px == px2 or py == py2:\n # straight up or down pixel\n graph.add_edge(i, i2, lin_cost)\n else:\n # diag pixel\n graph.add_edge(i, i2, diag_cost)\n\n # perform dijkstra cost calculation for each disinfection location pair\n # to build cost array for traveling salesman problem\n print('Building cost matrix for TSP problem.')\n num_locs = len(locs)\n costs = [[0] * num_locs for i in range(num_locs)]\n for loc_i in range(num_locs):\n costs[loc_i][loc_i] = 0\n (px, py) = xy_to_pixel(locs[loc_i][0], locs[loc_i][1])\n src_i = py * w + px\n for loc_j in range(loc_i + 1, num_locs):\n (px, py) = xy_to_pixel(locs[loc_j][0], locs[loc_j][1])\n dst_i = py * w + px\n path_info = find_path(graph, src_i, dst_i)\n cost = int(round(path_info.total_cost))\n costs[loc_i][loc_j] = cost\n costs[loc_j][loc_i] = cost\n\n # find disinfection location closest to and furthest from starting location (i.e., where robot currently is)\n # this will serve as the start and end locations for the tsp problem\n print('Finding starting and ending disinfection locations.')\n (px, py) = xy_to_pixel(start_loc[0], start_loc[1])\n src_i = py * w + px\n start_i = -1\n end_i = -1\n min_cost = sys.maxsize\n max_cost = 0\n for loc_i in range(num_locs):\n (px, py) = xy_to_pixel(locs[loc_i][0], locs[loc_i][1])\n dst_i = py * w + px\n path_info = find_path(graph, src_i, dst_i)\n cost = int(round(path_info.total_cost))\n if cost < min_cost:\n min_cost = cost\n start_i = loc_i\n if cost > max_cost:\n max_cost = cost\n end_i = loc_i\n\n # feed cost array into tsp algorithm\n print('Solving TSP problem.')\n data = create_data_model(costs, start_i, end_i)\n tour = solve_tsp(data)\n\n return tour\n\n\ndef create_data_model(costs_matrix, start_index, end_index):\n \"\"\"Stores the data for the problem.\"\"\"\n data = {'distance_matrix': costs_matrix, 'num_vehicles': 1, 'starts': [start_index], 'ends': [end_index]}\n return data\n\n\ndef get_solution(manager, routing, solution):\n \"\"\"Prints solution on console.\"\"\"\n print('Objective: {} miles'.format(solution.ObjectiveValue()))\n index = routing.Start(0)\n plan_output = 'Route for vehicle 0:\\n'\n route_distance = 0\n tour = []\n while not routing.IsEnd(index):\n tour.append(manager.IndexToNode(index))\n plan_output += ' {} ->'.format(manager.IndexToNode(index))\n previous_index = index\n index = solution.Value(routing.NextVar(index))\n route_distance += routing.GetArcCostForVehicle(previous_index, index, 0)\n plan_output += ' {}\\n'.format(manager.IndexToNode(index))\n print(plan_output)\n plan_output += 'Route distance: {}miles\\n'.format(route_distance)\n\n return tour\n\n\ndef solve_tsp(data):\n # Create the routing index manager.\n manager = pywrapcp.RoutingIndexManager(len(data['distance_matrix']),\n data['num_vehicles'], data['starts'], data['ends'])\n\n # Create Routing Model.\n routing = pywrapcp.RoutingModel(manager)\n\n def distance_callback(from_index, to_index):\n \"\"\"Returns the distance between the two nodes.\"\"\"\n # Convert from routing variable Index to distance matrix NodeIndex.\n from_node = manager.IndexToNode(from_index)\n to_node = manager.IndexToNode(to_index)\n return data['distance_matrix'][from_node][to_node]\n\n transit_callback_index = routing.RegisterTransitCallback(distance_callback)\n\n # Define cost of each arc.\n routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)\n\n # Setting first solution heuristic.\n search_parameters = pywrapcp.DefaultRoutingSearchParameters()\n search_parameters.first_solution_strategy = (\n routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC)\n\n # Solve the problem.\n solution = routing.SolveWithParameters(search_parameters)\n\n # Get solution as list of ordered indices\n if solution:\n return get_solution(manager, routing, solution)\n else:\n return []\n\n\n# calculates angles between the points in the tour.\ndef calculate_orientations(locations):\n orientations = [0]\n for i in range(len(locations) - 1):\n src = locations[i]\n dest = locations[i + 1]\n angle = math.atan2(dest[1] - src[1], dest[0] - src[0])\n orientations.append(angle)\n\n return orientations\n"
] | [
[
"pandas.np.shape",
"pandas.np.sqrt"
]
] |
csinva/covid-19-analysis | [
"e7b1e82cb6b25d62a868ff61025d88e17452de28"
] | [
"viz/viz_map.py"
] | [
"from bokeh.sampledata import us_states, us_counties\nfrom bokeh.plotting import figure, show, output_notebook, output_file, save\nfrom bokeh import palettes\nfrom bokeh.models import ColorBar,HoverTool,LinearColorMapper,ColumnDataSource,FixedTicker, LogColorMapper\noutput_notebook()\nimport re\nimport numpy as np\nfrom modeling import fit_and_predict\nimport plotly.graph_objs as go\nimport plotly.figure_factory as ff\nfrom plotly.offline import plot\nfrom plotly.subplots import make_subplots\nimport json\nimport plotly.express as px\nimport plotly\nimport pandas as pd\nfrom datetime import date, datetime, timedelta\n\nfrom viz.viz_map_utils import *\n\ncredstr ='rgb(234, 51, 86)'\ncbluestr = 'rgb(57, 138, 242)'\n\ndef plot_counties(df, variable_to_distribute, variables_to_display, state=None, logcolor=False):\n \"\"\"Plots the distribution of a given variable across the given sttate\n \n Params\n ------\n df\n df is a data frame containing the county level data\n variable_to_distribute\n variable_to_distribute is the variable that you want to see across the state\n variables_to_display\n Variables to display on hovering over each county\n \n output: Bokeh plotting object\n \"\"\"\n from bokeh.sampledata.us_counties import data as counties\n \n counties = {\n code: county for code, county in counties.items()\n if county[\"state\"] == state.lower()\n }\n\n county_xs = [county[\"lons\"] for county in counties.values()]\n county_ys = [county[\"lats\"] for county in counties.values()]\n \n if variable_to_distribute in variables_to_display:\n variables_to_display.remove(variable_to_distribute)\n\n colors = palettes.RdBu11 #(n_colors)\n min_value = df[variable_to_distribute].min()\n max_value = df[variable_to_distribute].max()\n gran = (max_value - min_value) / float(len(colors))\n #print variable_to_distribute,state,min_value,max_value\n index_range = [min_value + x*gran for x in range(len(colors))]\n county_colors = []\n variable_dictionary = {}\n variable_dictionary[\"county_names\"] = [county['name'] for county in counties.values()]\n variable_dictionary[\"x\"] = county_xs\n variable_dictionary[\"y\"] = county_ys\n variable_dictionary[re.sub(\"[^\\w]\",\"\",variable_to_distribute)] = []\n for vd in variables_to_display:\n variable_dictionary[re.sub(\"[^\\w]\",\"\",vd)] = []\n for county_id in counties:\n StateCountyID = str(county_id[0]).zfill(2) + str(county_id[1]).zfill(3)\n if StateCountyID in list(df[\"countyFIPS\"].values):\n temp_var = df[df[\"countyFIPS\"] == StateCountyID][variable_to_distribute].values[0]\n# if temp_var > 0.0:\n variable_dictionary[re.sub(\"[^\\w]\",\"\",variable_to_distribute)].append(temp_var)\n for vd in variables_to_display:\n variable_dictionary[re.sub(\"[^\\w]\",\"\",vd)].append(round(float(df[df[\"countyFIPS\"] == StateCountyID][vd].values),2))\n color_idx = list(temp_var - np.array(index_range)).index(min(x for x in list(temp_var - np.array(index_range)) if x >= 0))\n county_colors.append(colors[color_idx])\n\n '''\n else:\n variable_dictionary[re.sub(\"[^\\w]\",\"\",variable_to_distribute)].append(0.0)\n county_colors.append(\"#A9A9A9\")\n for vd in variables_to_display:\n variable_dictionary[re.sub(\"[^\\w]\",\"\",vd)].append(0.0)\n '''\n else:\n variable_dictionary[re.sub(\"[^\\w]\",\"\",variable_to_distribute)].append(0.0)\n county_colors.append(\"#A9A9A9\")\n for vd in variables_to_display:\n variable_dictionary[re.sub(\"[^\\w]\",\"\",vd)].append(0.0)\n #print temp_var,counties[county_id][\"name\"]\n variable_dictionary[\"color\"] = county_colors\n source = ColumnDataSource(data = variable_dictionary)\n TOOLS = \"pan,wheel_zoom,box_zoom,reset,hover,save\"\n\n if logcolor:\n mapper = LogColorMapper(palette=colors, low=min_value, high=max_value)\n else:\n mapper = LinearColorMapper(palette=colors, low=min_value, high=max_value)\n\n color_bar = ColorBar(color_mapper=mapper, location=(0, 0), orientation='horizontal', \n title = variable_to_distribute,ticker=FixedTicker(ticks=index_range))\n\n p = figure(title=variable_to_distribute, toolbar_location=\"left\",tools=TOOLS,\n plot_width=1100, plot_height=700,x_axis_location=None, y_axis_location=None)\n\n p.patches('x', 'y', source=source, fill_alpha=0.7,fill_color='color',\n line_color=\"#884444\", line_width=2)\n\n hover = p.select_one(HoverTool)\n hover.point_policy = \"follow_mouse\"\n tool_tips = [(\"County \", \"@county_names\")]\n for key in variable_dictionary.keys():\n if key not in [\"x\",\"y\",\"color\",\"county_names\"]:\n tool_tips.append((key,\"@\"+re.sub(\"[^\\w]\",\"\",key) + \"{1.11}\"))\n hover.tooltips = tool_tips\n \n p.add_layout(color_bar, 'below')\n \n return p\n\n\n# -- Plot cumulative deaths map with slider.\n\ndef plot_cumulative_deaths_map_with_slider(df,\n target_days=np.array([0, 1, 2, 3, 4, 5, 6, 7]),\n filename=\"results/deaths.html\",\n plot_choropleth=False,\n counties_json=None,\n dark=True,\n plot_fig=True,\n auto_open=True):\n \"\"\"\n Create an interactive plot of the cumulative deaths data for counties\n across the US, with a slider to change the date.\n\n Params\n ------\n df\n A county-level dataframe, with predictions if target_days has positive numbers.\n The df must also have columns called 'countyFIPS', 'tot_deaths', 'State', 'StateName',\n 'CountyName', 'PopulationEstimate2018', 'tot_cases', '#Hospitals', 'POP_LATITUDE',\n and 'POP_LONGITUDE'.\n target_days\n Array of days to plot. 0 is the last observed day, positive numbers are predictions,\n and negative numbers are past days.\n filename\n Where to save the interactive plot html.\n plot_choropleth\n If True, plot a choropleth in addition to bubbles.\n counties_json\n A JSON object with the borders of the geographical units of interest.\n If None, will try to open geojson-counties-fips.json in the data dir of this repo.\n dark\n Whether to use a dark theme for the figure.\n plot_fig\n If True, plots the figure to a filename and possibly opens it in a browser.\n auto_open\n If True, the plot will open in a browser.\n \"\"\"\n if plot_choropleth:\n if counties_json is None:\n counties_json = json.load(open(oj(parentdir, 'data', 'geojson-counties-fips.json'), \"r\"))\n\n # TODO: note that df should have all data (preds and lat lon)\n fips = df['countyFIPS'].tolist()\n tot_deaths = df['tot_deaths']\n\n latest_date = most_recent_date_in_data(df)\n latest_date_str = str_from_date(latest_date)\n\n d = df\n\n d['text'] = 'State: ' + d['State'].astype(str) + \\\n ' (' + d['StateName'].astype(str) + ')' + '<br>' + \\\n 'County: ' + d['CountyName'].astype(str) + '<br>' + \\\n 'Population (2018): ' + d['PopulationEstimate2018'].astype(str) + '<br>' + \\\n '# Recorded Cases as of ' + latest_date_str + \": \" + \\\n d['tot_cases'].astype(str) + '<br>' + \\\n '# Recorded Deaths as of ' + latest_date_str + \": \" + \\\n tot_deaths.astype(str) + '<br>' + \\\n '# Hospitals: ' + d['#Hospitals'].astype(str)\n\n map_title='Predicted Cumulative COVID-19 Deaths ' + '<br>' + \\\n '<span style=\"font-size: 20px; color: red;\">Use the slider below the map to change date.</span>'\n \n # make main figure\n fig = make_us_map(map_title, dark)\n\n target_dates = make_target_dates(df, target_days)\n observed_cols = observed_dates_to_cols(np.array(target_dates)[target_days <= 0])\n predicted_cols = target_days_to_cols(target_days[target_days > 0])\n\n plotting_cols = observed_cols + predicted_cols\n\n # make choropleth if plotting\n # want this to happen first so bubbles overlay\n if plot_choropleth:\n add_choropleth_traces(\n fig, df, plotting_cols, counties_json\n )\n\n value_labels = []\n for i, date in enumerate(target_dates):\n if target_days[i] <= 0:\n value_label = '<b>Observed Count, ' + nice_date_str(str_from_date(date)) + ': </b>'\n else:\n value_label = '<b>Predicted Count, ' + nice_date_str(str_from_date(date)) + ': </b>'\n value_labels.append(value_label)\n\n # add Scattergeo\n add_bubble_traces(\n fig, df, plotting_cols, plot_choropleth, show_hovertext = True,\n value_labels = value_labels\n )\n\n # make first day visible\n fig.data[0].visible = True\n if plot_choropleth:\n # make bubbles visible\n fig.data[n_past_days + target_days.size].visible = True\n\n # add slider to layout\n sliders = make_slider_from_dates(target_dates, plot_choropleth)\n fig.update_layout(\n sliders=sliders\n )\n\n if plot_fig:\n plot(fig, filename=filename, config={\n 'showLink': False,\n 'showSendToCloud': False,\n 'sendData': True,\n 'responsive': True,\n 'autosizable': True,\n 'displaylogo': False\n }, auto_open = auto_open)\n fig['layout']['title']['font']['size'] = 25\n return fig\n\n\n# --- Plot hospital severity index.\n\ndef add_hopsital_severity_index_scatter_traces(fig, df, target_days, visible=False):\n def make_bubble_trace(lat, lon, text, size, color, name):\n bubble_trace = go.Scattergeo(\n visible=visible,\n lat=lat,\n lon=lon,\n text=text,\n hovertemplate='%{text}',\n name=name,\n marker = dict(\n # color is only available for circle marker :(\n size = size,\n color = color,\n line_color='rgb(40,40,40)',\n line_width=0.5\n ),\n showlegend=False\n )\n return bubble_trace\n\n colors = [\"#6E8E96\", \"#D3787D\", \"#AC3931\"]\n\n target_date_strs = [nice_date_str(str_from_date(date))\n for date in make_target_dates(df, target_days)]\n\n # add predictions\n for i in range(len(target_days)):\n for s in range(3):\n severity_col = f'Severity {target_days[i]}-day'\n surge_col = f'Surge {target_days[i]}-day'\n pred_col = f'Predicted Deaths {target_days[i]}-day'\n df_s = df[df[severity_col] == s+1]\n values = df_s[severity_col]\n surge = df_s[surge_col]\n preds = df_s[pred_col]\n lat = df_s['Latitude']\n lon = df_s['Longitude']\n text = '<b>COVID-19 Pandemic Severity Index (CPSI)</b>: ' + values.astype(str) + '<br>' + \\\n '<b>Surge Index (SUI)</b>: ' + surge.astype(str) + '<br>' + \\\n df_s['text_hospital'].tolist() + '<br>' \\\n '------ <br>' + \\\n '<b># Deaths Predicted in County, ' + target_date_strs[i] + '</b>: ' + \\\n preds.astype(str) + '<br>' + df_s['text_county'].tolist()\n bubble_trace = make_bubble_trace(\n lat, lon, text, size=s+7, color=colors[s], name=str(s+1)\n )\n fig.add_trace(bubble_trace)\n\n return None\n\n\ndef make_severity_index_sliders(dates, plot_choropleth):\n sliders = [\n {\n \"active\": 0,\n \"visible\": True,\n \"pad\": {\"t\": 50},\n \"currentvalue\": {'xanchor' : 'right'},\n 'transition': {'duration': 1000, 'easing': 'cubic-in-out'},\n \"steps\": [],\n }\n ]\n\n num_days = len(dates)\n\n # add steps for predicted days\n for i, date in enumerate(dates):\n if plot_choropleth:\n args = [\"visible\", [False] * (4*num_days)]\n else:\n args = [\"visible\", [False] * 3*num_days]\n slider_step = {\n \"args\": args,\n \"label\": nice_date_str(str_from_date(date)),\n \"method\": \"restyle\"\n }\n for s in range(3):\n slider_step['args'][1][i*3 + s] = True\n if plot_choropleth:\n slider_step['args'][1][3*num_days + i] = True\n sliders[0]['steps'].append(slider_step)\n return sliders\n\n\ndef plot_hospital_severity_slider(df, # merged hospital and county, with severity\n target_days=np.array([1, 2, 3, 4, 5, 6, 7]),\n filename=\"severity_map.html\", # no effect unless plot = True\n plot_choropleth=False,\n df_county=None,\n counties_json=None,\n dark=True,\n plot_fig=True,\n auto_open=True,\n county_filter=None):\n \"\"\"\n Create an interactive plot of the predicted hospital-level severity index\n data for hospitals across the US, with a slider to change the date.\n\n Params\n ------\n df\n A hospital-level dataframe, with predictions.\n target_days\n Array of days to plot. Unlike for plot_cumulative_deaths_map_with_slider(),\n must be only positive numbers.\n filename\n Where to save the interactive plot html.\n plot_choropleth\n If True, plot a choropleth in addition to bubbles.\n df_county\n A county-level df with predictions. Must be present if plot_choropleth is True.\n counties_json\n A JSON object with the borders of the geographical units of interest.\n If None, will try to open geojson-counties-fips.json in the data dir of this repo.\n dark\n Whether to use a dark theme for the figure.\n plot_fig\n If True, plots the figure to a filename and possibly opens it in a browser.\n auto_open\n If True, the plot will open in a browser.\n\n \"\"\"\n target_days = target_days[target_days > 0]\n\n if plot_choropleth:\n if counties_json is None:\n counties_json = json.load(open(oj(parentdir, 'data', 'geojson-counties-fips.json'), \"r\"))\n assert df_county is not None, 'df_county must be included for plotting county predictions'\n # TODO: note that df should have all data (preds and lat lon)\n d = df\n d_c = df_county\n\n if county_filter is not None: # TODO: remove this\n d = d[d['CountyName'] == county_filter]\n if plot_choropleth:\n d_c = d[d['CountyName'] == county_filter]\n\n fips = d['countyFIPS'].tolist()\n tot_deaths = d['tot_deaths']\n\n for day in target_days:\n pred_col = f'Predicted Deaths {day}-day'\n d[pred_col] = d[pred_col].astype(float).round()\n # replace missing values with string so below 'text' isn't missing\n d = d.replace(np.nan, 'Missing', regex=True)\n\n latest_date_str = d.filter(regex='#Deaths_').columns[-1].replace('#Deaths_', '')\n\n d['text_hospital'] = 'Hospital Name: ' + d['Hospital Name'].astype(str) + '<br>' + \\\n 'Hospital # Employees: ' + d['Hospital Employees'].astype(str) + '<br>' + \\\n 'Hospital Type: ' + d['Hospital Type'].astype(str) + '<br>' + \\\n 'Hospital Ownership: ' + d['Hospital Ownership'].astype(str) + '<br>' + \\\n 'Estimated # Deaths in Hospital as of ' + latest_date_str + \": \" + \\\n d['Total Deaths Hospital'].round().astype(str)\n d['text_county'] = 'County: ' + d['CountyName'].astype(str) + '<br>' + \\\n 'State: ' + d['StateName'].astype(str) + '<br>' + \\\n 'County Population (2018): ' + d['PopulationEstimate2018'].astype(str) + '<br>' + \\\n 'County # Recorded Cases as of ' + latest_date_str + \": \" + \\\n d['tot_cases'].astype(str) + '<br>' + \\\n 'County # Recorded Deaths as of ' + latest_date_str + \": \" + \\\n tot_deaths.astype(str) + '<br>' + \\\n 'County Total # Hospitals: ' + d['#Hospitals'].astype(str) + '<br>' + \\\n 'County Total # Hospital Employees: ' + d['Hospital Employees in County'].astype(str)\n\n map_title='Hospital-Level COVID-19 Pandemic Severity Index (CPSI)'\n if plot_choropleth:\n map_title = map_title + ' and Predicted Deaths'\n map_title = map_title + '<br>' + \\\n '<span style=\"font-size: 20px; color: red;\">Use the slider below the map to change date.</span>'\n\n # make main figure\n fig = make_us_map(map_title, dark)\n\n # get prediction dates\n latest_date = datetime.strptime(latest_date_str, '%m-%d-%Y').date()\n time_deltas = [timedelta(days = int(day)) for day in target_days]\n pred_dates = [latest_date + time_delta for time_delta in time_deltas]\n\n # add Scattergeo\n add_hopsital_severity_index_scatter_traces(fig, d, target_days, plot_choropleth)\n\n # make first day visible\n fig.data[0].visible = True\n fig.data[1].visible = True\n fig.data[2].visible = True\n\n # make choropleth if plotting\n if plot_choropleth:\n plotting_cols = target_days_to_cols(target_days)\n add_choropleth_traces(\n fig, d_c, plotting_cols, counties_json\n )\n # make first day choropleth visible\n fig.data[3*target_days.size].visible = True\n\n # add slider to layout\n sliders = make_severity_index_sliders(pred_dates, plot_choropleth)\n fig.update_layout(\n sliders=sliders\n )\n\n if plot_fig:\n plot(fig, filename=filename, config={\n 'showLink': False,\n 'showSendToCloud': False,\n 'sendData': True,\n 'responsive': True,\n 'autosizable': True,\n 'displaylogo': False\n }, auto_open = auto_open)\n fig['layout']['title']['font']['size'] = 25\n return fig\n\n\n# -- Plot map of daily change in deaths.\n\ndef plot_change_map():\n \"\"\"\n Plot a map of the US with the change in # of new deaths from day to day.\n new_death{t} = pred_cumulative{t} - pred_cumulative{t-1}\n change{t} = new_death{t} - new_death{t - 1}\n \"\"\"\n pass\n\n"
] | [
[
"numpy.array"
]
] |
InfuseAI/showcase | [
"54a177168c6e173580ed5c58fe97fe6018ecd06e"
] | [
"pycaret_classification/src/pycaret_classification_training.py"
] | [
"import pandas as pd\nfrom pycaret.classification import *\n\n\nclass PycaretClassificationTraining:\n def __init__(self, data_path):\n self.df = pd.read_csv(data_path)\n\n def automl_training(self, target_column, mlflow_experiment_name):\n # Initializing setup\n clf1 = setup(\n self.df,\n target=target_column,\n log_experiment=True,\n experiment_name=mlflow_experiment_name,\n silent=True,\n )\n\n # Compare the model: Compare all the classification model. EX: catboost, lightgbm, svm, etc.\n best_model = compare_models()\n\n # Tuning the best model.\n final_best = finalize_model(best_model)\n\n # Record the parameter of automl value\n best = automl(optimize=\"Recall\")\n\n def specific_training(self, model_name):\n # Create model\n particular_model = create_model(model_name)\n # Test: Predict model\n prediction = predict_model(particular_model)\n # Test: Evaluate model\n evaluate_model(particular_model)\n\n def test_model(self, model_path):\n # Part 1: Load saved model.\n saved_model = load_model(os.path.join(model_path, \"model\"))\n\n # Part 2: Arrange the testing data.\n test_data = [\n [\n \"25\",\n \"admin.\",\n \"married\",\n \"secondary\",\n \"no\",\n \"45\",\n \"no\",\n \"no\",\n \"unknown\",\n \"5\",\n \"may\",\n \"1467\",\n \"1\",\n \"-1\",\n \"0\",\n \"unknown\",\n \"yes\",\n ]\n ]\n data_unseen = pd.DataFrame(\n test_data,\n columns=[\n \"age\",\n \"job\",\n \"marital\",\n \"education\",\n \"default\",\n \"balance\",\n \"housing\",\n \"loan\",\n \"contact\",\n \"day\",\n \"month\",\n \"duration\",\n \"campaign\",\n \"pdays\",\n \"previous\",\n \"poutcome\",\n \"deposit\",\n ],\n )\n # Part 3: Use testing data to test saved model.\n prediction = predict_model(saved_model, data=data_unseen)\n"
] | [
[
"pandas.read_csv",
"pandas.DataFrame"
]
] |
bprevost/brad_demo | [
"7c071709f763627d870e2b9e55be332e6af5f4c3"
] | [
"deep/minivggnet.py"
] | [
"from tensorflow.keras import backend as K\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D\nfrom tensorflow.keras.layers import Activation\nfrom tensorflow.keras.layers import BatchNormalization\nfrom tensorflow.keras.layers import MaxPooling2D\nfrom tensorflow.keras.layers import Dropout\nfrom tensorflow.keras.layers import Flatten\nfrom tensorflow.keras.layers import Dense\n\nclass MiniVGGNet:\n @staticmethod\n def build(width, height, depth, classes):\n # Initialize the model along with the input shape to be \"channels last\"\n model = Sequential()\n inputShape = (height, width, depth)\n chanDim = -1 # Index of the channel dimension is last\n\n # Update the image shape if using \"channels first\"\n if K.image_data_format() == \"channels_first\":\n inputShape = (depth, height, width)\n chanDim = 1 # Index of the channel dimension is first\n\n # First set of CONV => RELU => CONV => RELU => POOL layers\n model.add(Conv2D(32, (3, 3), padding=\"same\", input_shape=inputShape))\n model.add(Activation(\"relu\"))\n model.add(BatchNormalization(axis=chanDim))\n model.add(Conv2D(32, (3, 3), padding=\"same\"))\n model.add(Activation(\"relu\"))\n model.add(BatchNormalization(axis=chanDim))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(Dropout(0.25))\n\n # Second set of CONV => RELU => CONV => RELU => POOL layers\n model.add(Conv2D(64, (3, 3), padding=\"same\"))\n model.add(Activation(\"relu\"))\n model.add(BatchNormalization(axis=chanDim))\n model.add(Conv2D(64, (3, 3), padding=\"same\"))\n model.add(Activation(\"relu\"))\n model.add(BatchNormalization(axis=chanDim))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(Dropout(0.25))\n\n # First (and only) set of FC => RELU layers\n model.add(Flatten())\n model.add(Dense(512))\n model.add(Activation(\"relu\"))\n model.add(BatchNormalization())\n model.add(Dropout(0.5))\n\n # Softmax classifier\n model.add(Dense(classes))\n model.add(Activation(\"softmax\"))\n\n # Return the constructed network architecture\n return model\n"
] | [
[
"tensorflow.keras.layers.Activation",
"tensorflow.keras.backend.image_data_format",
"tensorflow.keras.layers.Dense",
"tensorflow.keras.layers.Conv2D",
"tensorflow.keras.layers.BatchNormalization",
"tensorflow.keras.layers.Dropout",
"tensorflow.keras.layers.MaxPooling2D",
"tensorflow.keras.models.Sequential",
"tensorflow.keras.layers.Flatten"
]
] |
sahahn/BPt | [
"1a2967f4ca3fa070b7417a4f59a218ae171daadd"
] | [
"BPt/pipeline/BPtFeatureSelector.py"
] | [
"from sklearn.feature_selection._base import SelectorMixin\nfrom .helpers import update_mapping, check_om, proc_mapping\nfrom .ScopeObjs import ScopeTransformer\nimport numpy as np\nimport pandas as pd\n\n\nclass BPtFeatureSelector(ScopeTransformer, SelectorMixin):\n\n def _update_feat_mapping(self, X, mapping):\n\n # Need to pass along the correct mapping\n # overwrite existing out mapping\n new_out_mapping_ = {}\n\n # This is the calculated support from the base estimator\n support = self.estimator_.get_support()\n\n # Set in scope inds by if all case\n if self.inds_ is Ellipsis:\n in_scope_inds = list(range(X.shape[1]))\n else:\n in_scope_inds = self.inds_\n\n # Update inds / rest inds by current out mapping\n in_scope_inds = proc_mapping(in_scope_inds, self.out_mapping_)\n rest_inds = proc_mapping(self.rest_inds_, self.out_mapping_)\n\n # First half is for updating the index within scope\n cnt = 0\n for i, ind in enumerate(in_scope_inds):\n\n # If kept by feat selection, add, otherwise set to None\n if support[i]:\n new_out_mapping_[ind] = cnt\n cnt += 1\n else:\n new_out_mapping_[ind] = None\n\n # Next, need to update the mapping for the remaining wrapper inds\n # essentially setting them where the cnt left off, then sequentially\n # If None, will just skip\n for rem_ind in range(len(rest_inds)):\n new_out_mapping_[rest_inds[rem_ind]] = cnt\n cnt += 1\n\n # Over-write\n self.out_mapping_ = new_out_mapping_\n\n # Update the original mapping, this is the mapping which\n # will be passed to the next piece of the pipeline\n update_mapping(mapping, self.out_mapping_)\n\n # Set final out mapping\n self.out_mapping_ = mapping.copy()\n\n return self\n\n def fit(self, X, y=None, mapping=None,\n fit_index=None, **fit_params):\n\n if mapping is None:\n mapping = {}\n\n # Call parent fit\n super().fit(X, y=y, mapping=mapping,\n fit_index=fit_index,\n **fit_params)\n\n # Need to update mapping\n return self._update_feat_mapping(X, mapping)\n\n def _proc_new_names(self, feat_names, base_name=None, encoders=None):\n\n # If skip, return passed names as is\n if self.estimator_ is None:\n return feat_names\n\n # Store original passed feat names here\n self.feat_names_in_ = feat_names\n\n # Get base new names from parent class\n new_names = super()._proc_new_names(feat_names)\n\n # This feat mask corresponds to the already transformed feats\n feat_mask = self._get_support_mask()\n\n # Apply the computed mask to get the actually selected features\n return_names = np.array(new_names)[feat_mask]\n\n return list(return_names)\n\n def _get_support_mask(self):\n\n # Create full support as base support + True's for all rest inds\n # i.e., those features originally out of scope\n base_support = self.estimator_.get_support()\n rest_support = np.ones(len(self.rest_inds_), dtype='bool')\n support = np.concatenate([base_support, rest_support])\n\n return support\n\n def inverse_transform_FIs(self, fis):\n\n # Skip if skipped\n if self.estimator_ is None:\n return fis\n\n # Get data as input form\n fis_data = np.array(fis).reshape(1, -1)\n\n # Get return data from inverse transform\n return_fis_data = self.estimator_.inverse_transform(fis_data)[0]\n\n if not hasattr(self, 'feat_names_in_'):\n raise RuntimeError('_proc_new_names must be called first.')\n\n # Put in a series to return\n return_fis = pd.Series(return_fis_data,\n index=self.feat_names_in_)\n\n return return_fis\n"
] | [
[
"numpy.concatenate",
"numpy.array",
"pandas.Series"
]
] |
bjonnh/NP-Classifier | [
"9d45422a213b26747458bae24fabad7326c62c80"
] | [
"training/fingerprint_handler.py"
] | [
"import pandas as pd\r\nfrom tqdm import tqdm\r\nimport numpy as np\r\n\r\nimport rdkit\r\nfrom rdkit import Chem\r\nfrom rdkit.Chem import rdMolDescriptors\r\nfrom rdkit.Chem import Descriptors\r\nfrom rdkit.Chem import AllChem\r\nfrom rdkit import DataStructs\r\n\r\n#Fingerprint generation\r\n#(@ming if we want to use inchi as an input, inchi should be changed to SMILES and the SMILES should be standardized)\r\ndef calculate_fingerprint(smiles, radi):\r\n binary = np.zeros((2048*(radi)), int)\r\n formula = np.zeros((2048),int)\r\n mol = Chem.MolFromSmiles(smiles)\r\n \r\n mol = Chem.AddHs(mol)\r\n mol_bi = {}\r\n for r in range(radi+1):\r\n mol_fp = rdMolDescriptors.GetMorganFingerprintAsBitVect(mol, radius=r, bitInfo=mol_bi, nBits = 2048)\r\n mol_bi_QC = []\r\n for i in mol_fp.GetOnBits():\r\n num_ = len(mol_bi[i])\r\n for j in range(num_):\r\n if mol_bi[i][j][1] == r:\r\n mol_bi_QC.append(i)\r\n break\r\n\r\n if r == 0:\r\n for i in mol_bi_QC:\r\n formula[i] = len([k for k in mol_bi[i] if k[1]==0])\r\n else:\r\n for i in mol_bi_QC:\r\n binary[(2048*(r-1))+i] = len([k for k in mol_bi[i] if k[1]==r])\r\n \r\n \r\n \r\n return formula.reshape(1,2048),binary.reshape(1,4096)\r\n\r\n\r\ndef _isglycoside(smiles): #now it is expressed as boolean but can be changed to any format\r\n sugar1 = Chem.MolFromSmarts('[OX2;$([r5]1@C@C@C(O)@C1),$([r6]1@C@C@C(O)@C(O)@C1)]')\r\n sugar2 = Chem.MolFromSmarts('[OX2;$([r5]1@C(!@[OX2,NX3,SX2,FX1,ClX1,BrX1,IX1])@C@C@C1),$([r6]1@C(!@[OX2,NX3,SX2,FX1,ClX1,BrX1,IX1])@C@C@C@C1)]')\r\n sugar3 = Chem.MolFromSmarts('[OX2;$([r5]1@C(!@[OX2,NX3,SX2,FX1,ClX1,BrX1,IX1])@C@C(O)@C1),$([r6]1@C(!@[OX2,NX3,SX2,FX1,ClX1,BrX1,IX1])@C@C(O)@C(O)@C1)]')\r\n sugar4 = Chem.MolFromSmarts('[OX2;$([r5]1@C(!@[OX2H1])@C@C@C1),$([r6]1@C(!@[OX2H1])@C@C@C@C1)]')\r\n sugar5 = Chem.MolFromSmarts('[OX2;$([r5]1@[C@@](!@[OX2,NX3,SX2,FX1,ClX1,BrX1,IX1])@C@C@C1),$([r6]1@[C@@](!@[OX2,NX3,SX2,FX1,ClX1,BrX1,IX1])@C@C@C@C1)]')\r\n sugar6 = Chem.MolFromSmarts('[OX2;$([r5]1@[C@](!@[OX2,NX3,SX2,FX1,ClX1,BrX1,IX1])@C@C@C1),$([r6]1@[C@](!@[OX2,NX3,SX2,FX1,ClX1,BrX1,IX1])@C@C@C@C1)]')\r\n mol = Chem.MolFromSmiles(smiles)\r\n try:\r\n if (mol.HasSubstructMatch(sugar1) or \r\n mol.HasSubstructMatch(sugar2) or\r\n mol.HasSubstructMatch(sugar3) or\r\n mol.HasSubstructMatch(sugar4) or\r\n mol.HasSubstructMatch(sugar5) or\r\n mol.HasSubstructMatch(sugar6)) :\r\n return True \r\n else:\r\n return False \r\n except:\r\n return 'Input_error'\r\n"
] | [
[
"numpy.zeros"
]
] |
Sahil-Chavan/Vehicle_Object_Detection | [
"c3e4022f03a3c5e54f272869ee9e2f8fe1a3df96"
] | [
"app.py"
] | [
"import cv2\nimport base64\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom flask import Flask, render_template,flash,request,redirect,url_for,jsonify\nfrom functions import load_model,show_inference\n\napp = Flask(__name__)\n\napp.secret_key = \"sahilsc\"\n\nclass ClientApp:\n def __init__(self):\n self.img_path = \"inputs/input_img.png\"\n self.model = load_model()\n\[email protected](\"/\")\ndef home(): \n return render_template('home.html',title=\"Vehicle Object Detection\")\n\[email protected](\"/\",methods=['POST'])\ndef predict(): \n if request.method == 'POST' and 'imag' in request.files:\n img = request.files['imag']\n \n if img.filename=='':\n flash('Image not found')\n return redirect(url_for('home'))\n\n else:\n if img and img.filename.rsplit('.',1)[1].lower() in ['jpg','jpeg','png']:\n # Saving the image\n # img.save('static/'+img.filename)\n #read image file string data\n filestr = img.read()\n #convert string data to numpy array\n npimg = np.frombuffer(filestr, np.uint8)\n # convert numpy array to image\n img_vec = cv2.imdecode(npimg, cv2.COLOR_BGR2RGB)\n # prediction\n pred_img = show_inference(capp.model,img_vec)\n # saving the prediction\n pre_img_fname = 'static/predictions/prediction.jpg'\n cv2.imwrite(pre_img_fname,pred_img)\n\n flash('Succesfully made the predictions')\n return render_template('home.html',title=\"Vehicle Object Detection\",filename=\"predictions/prediction.jpg\")\n \n \n else:\n flash('Invalid Image format')\n return redirect(url_for('home'))\n\n else:\n return redirect(url_for('home'))\n\[email protected]('/api',methods=['POST'])\ndef api():\n img = request.files['imag']\n filestr = img.read()\n npimg = np.frombuffer(filestr, np.uint8)\n img_vec = cv2.imdecode(npimg, cv2.COLOR_BGR2RGB)\n pred_img = show_inference(capp.model,img_vec)\n pre_img_fname = 'static/predictions/prediction.jpg'\n cv2.imwrite(pre_img_fname,pred_img)\n with open(pre_img_fname, \"rb\") as f:\n b64_img = base64.b64encode(f.read())\n return jsonify({\"image\" : b64_img.decode('utf-8')})\n\n\n # return 'inside predict'\n # return render_template('home.html',title=\"Vehicle Object Detection\")\n\n\n\n\n\n\n\n\nif __name__ == '__main__':\n capp = ClientApp()\n app.run(debug=True)"
] | [
[
"numpy.frombuffer"
]
] |
chaozhong2010/Faster-RCNN_Tensorflow | [
"9e68a7f20620890018ec6e7b4596c0b5f3aa6524"
] | [
"tools/inference_result_jinnan2.py"
] | [
"# -*- coding:utf-8 -*-\r\n\r\nfrom __future__ import absolute_import\r\nfrom __future__ import print_function\r\nfrom __future__ import division\r\n\r\nimport os, sys\r\nimport tensorflow as tf\r\nimport time\r\nimport cv2\r\nimport argparse\r\nimport numpy as np\r\nimport json\r\nsys.path.append(\"../\")\r\n\r\nfrom data.io.image_preprocess import short_side_resize_for_inference_data\r\nfrom libs.configs import cfgs\r\nfrom libs.networks import build_whole_network\r\nfrom libs.box_utils import draw_box_in_img\r\nfrom help_utils import tools\r\n\r\n\r\ndef detect(det_net, inference_save_path, real_test_imgname_list):\r\n\r\n # 1. preprocess img\r\n img_plac = tf.placeholder(dtype=tf.uint8, shape=[None, None, 3]) # is RGB. not GBR\r\n img_batch = tf.cast(img_plac, tf.float32)\r\n img_batch = short_side_resize_for_inference_data(img_tensor=img_batch,\r\n target_shortside_len=cfgs.IMG_SHORT_SIDE_LEN,\r\n length_limitation=cfgs.IMG_MAX_LENGTH)\r\n img_batch = img_batch - tf.constant(cfgs.PIXEL_MEAN)\r\n img_batch = tf.expand_dims(img_batch, axis=0) # [1, None, None, 3]\r\n\r\n detection_boxes, detection_scores, detection_category = det_net.build_whole_detection_network(\r\n input_img_batch=img_batch,\r\n gtboxes_batch=None)\r\n\r\n init_op = tf.group(\r\n tf.global_variables_initializer(),\r\n tf.local_variables_initializer()\r\n )\r\n################################################################\r\n###根据checkpoint恢复最新的\r\n # restorer, restore_ckpt = det_net.get_restorer()\r\n\r\n###恢复指定的\r\n restore_ckpt = os.path.join(cfgs.TRAINED_CKPT, cfgs.VERSION) + '/voc_16000model.ckpt'\r\n restorer = tf.train.Saver()\r\n print(\"model restore from :\", restore_ckpt)\r\n print(20 * \"****\")\r\n################################################################\r\n config = tf.ConfigProto()\r\n config.gpu_options.allow_growth = True\r\n\r\n with tf.Session(config=config) as sess:\r\n sess.run(init_op)\r\n if not restorer is None:\r\n restorer.restore(sess, restore_ckpt)\r\n print('restore model')\r\n all_images_detect_result = []\r\n for i, a_img_name in enumerate(real_test_imgname_list):\r\n\r\n raw_img = cv2.imread(a_img_name)\r\n raw_h, raw_w = raw_img.shape[0], raw_img.shape[1]\r\n start = time.time()\r\n resized_img, detected_boxes, detected_scores, detected_categories = \\\r\n sess.run(\r\n [img_batch, detection_boxes, detection_scores, detection_category],\r\n feed_dict={img_plac: raw_img[:, :, ::-1]} # cv is BGR. But need RGB\r\n )\r\n end = time.time()\r\n # print(\"{} cost time : {} \".format(img_name, (end - start)))\r\n\r\n show_indices = detected_scores >= cfgs.SHOW_SCORE_THRSHOLD\r\n show_scores = detected_scores[show_indices]\r\n show_boxes = detected_boxes[show_indices]\r\n show_categories = detected_categories[show_indices]\r\n final_detections = draw_box_in_img.draw_boxes_with_label_and_scores(np.squeeze(resized_img, 0),\r\n boxes=show_boxes,\r\n labels=show_categories,\r\n scores=show_scores)\r\n nake_name = os.path.split(a_img_name)[1]\r\n print (inference_save_path + '/' + nake_name)\r\n\r\n # cv2.imwrite(inference_save_path + '/' + nake_name,\r\n # final_detections[:, :, ::-1])\r\n\r\n\r\n\r\n xmin, ymin, xmax, ymax = show_boxes[:, 0], show_boxes[:, 1], \\\r\n show_boxes[:, 2], show_boxes[:, 3]\r\n resized_h, resized_w = resized_img.shape[1], resized_img.shape[2]\r\n\r\n xmin = xmin * raw_w / resized_w\r\n xmax = xmax * raw_w / resized_w\r\n\r\n ymin = ymin * raw_h / resized_h\r\n ymax = ymax * raw_h / resized_h\r\n a_img_detect_result = []\r\n for idex in range(len(show_scores)):\r\n # label, score, bbox = a_det[0], a_det[1], a_det[2:]\r\n det_object = {\"xmin\": int(xmin[idex]),\r\n \"xmax\": int(xmax[idex]),\r\n \"ymin\": int(ymin[idex]),\r\n \"ymax\": int(ymax[idex]),\r\n \"label\": int(show_categories[idex]),\r\n \"confidence\": float(show_scores[idex])}\r\n # print (det_object)\r\n\r\n a_img_detect_result.append(det_object)\r\n image_result = {\"filename\": nake_name,\r\n \"rects\": a_img_detect_result}\r\n all_images_detect_result.append(image_result)\r\n all_images_result_dict = {\"results\": all_images_detect_result}\r\n\r\n f = open( 'result_jinlian20190314.json', 'w')\r\n json.dump(all_images_result_dict, f) # , indent=4\r\n f.close()\r\n tools.view_bar('{} image cost {}s'.format(a_img_name, (end - start)), i + 1, len(real_test_imgname_list))\r\n\r\ndef inference(test_dir, inference_save_path):\r\n\r\n test_imgname_list = [os.path.join(test_dir, img_name) for img_name in os.listdir(test_dir)\r\n if img_name.endswith(('.jpg', '.png', '.jpeg', '.tif', '.tiff'))]\r\n assert len(test_imgname_list) != 0, 'test_dir has no imgs there.' \\\r\n ' Note that, we only support img format of (.jpg, .png, and .tiff) '\r\n\r\n faster_rcnn = build_whole_network.DetectionNetwork(base_network_name=cfgs.NET_NAME,\r\n is_training=False)\r\n detect(det_net=faster_rcnn, inference_save_path=inference_save_path, real_test_imgname_list=test_imgname_list)\r\n\r\n\r\ndef parse_args():\r\n \"\"\"\r\n Parse input arguments\r\n \"\"\"\r\n # parser = argparse.ArgumentParser(description='TestImgs...U need provide the test dir')\r\n parser = argparse.ArgumentParser('TestImgs...U need provide the test dir')\r\n parser.add_argument('--data_dir', dest='data_dir',\r\n help='data path',\r\n default='./test_images', type=str)\r\n parser.add_argument('--save_dir', dest='save_dir',\r\n help='demo imgs to save',\r\n default='./test_result', type=str)\r\n parser.add_argument('--GPU', dest='GPU',\r\n help='gpu id ',\r\n default='0', type=str)\r\n\r\n # if len(sys.argv) == 1:\r\n # parser.print_help()\r\n # sys.exit(1)\r\n\r\n args = parser.parse_args()\r\n\r\n return args\r\nif __name__ == '__main__':\r\n\r\n args = parse_args()\r\n print('Called with args:')\r\n print(20 * \"--\")\r\n print(args)\r\n print(20 * \"--\")\r\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = args.GPU\r\n inference(args.data_dir,\r\n inference_save_path=args.save_dir)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n"
] | [
[
"tensorflow.constant",
"tensorflow.local_variables_initializer",
"numpy.squeeze",
"tensorflow.cast",
"tensorflow.expand_dims",
"tensorflow.placeholder",
"tensorflow.ConfigProto",
"tensorflow.global_variables_initializer",
"tensorflow.Session",
"tensorflow.train.Saver"
]
] |
dominiquesydow/dynophores | [
"16b924e266b9a1a4e20edc5d2d0a43d40c225dea"
] | [
"dynophores/tests/core/test_envpartner.py"
] | [
"\"\"\"\nUnit tests for dynophore.core.envpartner.EnvPartner class.\n\nUses fixture tests.conftest.envpartner.\n\"\"\"\n\nfrom pathlib import Path\n\nimport pytest\nimport numpy as np\n\nfrom dynophores import parsers\nfrom dynophores.core.envpartner import EnvPartner\n\nPATH_TEST_DATA = Path(__name__).parent / \"dynophores/tests/data\"\n\n\nclass TestsEnvPartner:\n \"\"\"\n Test EnvPartner class methods.\n \"\"\"\n\n def test_init(self):\n\n dynophore_dict = parsers._json_pml_to_dict(\n PATH_TEST_DATA / \"out/1KE7_dynophore.json\",\n PATH_TEST_DATA / \"out/1KE7_dynophore.pml\",\n )\n superfeature_dict = next(iter(dynophore_dict[\"superfeatures\"].values()))\n envpartner_dict = next(iter(superfeature_dict[\"envpartners\"].values()))\n envpartner = EnvPartner(**envpartner_dict)\n assert isinstance(envpartner, EnvPartner)\n assert list(envpartner.__dict__) == [\n \"id\",\n \"residue_name\",\n \"residue_number\",\n \"chain\",\n \"atom_numbers\",\n \"occurrences\",\n \"distances\",\n ]\n\n # Test class attributes - check for data types\n assert isinstance(envpartner.id, str)\n assert isinstance(envpartner.residue_name, str)\n assert isinstance(envpartner.residue_number, int)\n assert isinstance(envpartner.chain, str)\n assert isinstance(envpartner.atom_numbers[0], int)\n assert isinstance(envpartner.occurrences[0], int)\n assert isinstance(envpartner.distances[0], float)\n\n @pytest.mark.parametrize(\n \"envpartner_dict\",\n [\n {\n \"id\": \"ILE-10-A[169,171,172]\",\n \"residue_name\": \"ILE\",\n \"residue_number\": 10,\n \"chain\": \"A\",\n \"atom_numbers\": [169, 171, 172],\n \"occurrences\": np.array([0, 0, 1, 1]), # Length occurrences != distances\n \"distances\": np.array([6.0, 6.0, 3.0]),\n }\n ],\n )\n def test_init_raises(self, envpartner_dict):\n\n with pytest.raises(ValueError):\n EnvPartner(**envpartner_dict)\n\n @pytest.mark.parametrize(\"residue_id\", [\"ILE-10-A\"])\n def test_residue_id(self, envpartner, residue_id):\n \"\"\"\n Test class property.\n \"\"\"\n\n assert envpartner.residue_id == residue_id\n\n @pytest.mark.parametrize(\"n_frames\", [1002])\n def test_n_frames(self, envpartner, n_frames):\n \"\"\"\n Test class property.\n \"\"\"\n\n assert envpartner.n_frames == n_frames\n\n @pytest.mark.parametrize(\"count\", [995])\n def test_count(self, envpartner, count):\n \"\"\"\n Test class property.\n \"\"\"\n\n assert envpartner.count == count\n\n @pytest.mark.parametrize(\"frequency\", [99.3])\n def test_frequency(self, envpartner, frequency):\n \"\"\"\n Test class property.\n \"\"\"\n\n assert envpartner.frequency == frequency\n"
] | [
[
"numpy.array"
]
] |
mcmonster/tensorflow | [
"fb8a14fde29f2dc19331d73795c2ead0e8ef0e8e"
] | [
"tensorflow/contrib/distribute/python/keras_test.py"
] | [
"# Copyright 2016 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 tf.keras models using DistributionStrategy.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nfrom absl.testing import parameterized\nimport numpy as np\n\nfrom tensorflow.contrib.distribute.python import combinations\nfrom tensorflow.contrib.distribute.python import mirrored_strategy\nfrom tensorflow.contrib.distribute.python import tpu_strategy\nfrom tensorflow.python import keras\nfrom tensorflow.python.data.ops import dataset_ops\nfrom tensorflow.python.distribute import values\nfrom tensorflow.python.eager import test\nfrom tensorflow.python.estimator import keras as keras_lib\nfrom tensorflow.python.estimator import run_config as run_config_lib\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.keras import testing_utils\nfrom tensorflow.python.keras.engine import distributed_training_utils\nfrom tensorflow.python.keras.optimizer_v2 import gradient_descent as gradient_descent_keras\nfrom tensorflow.python.ops.parsing_ops import gen_parsing_ops\nfrom tensorflow.python.platform import gfile\nfrom tensorflow.python.summary.writer import writer_cache\nfrom tensorflow.python.training import gradient_descent\nfrom tensorflow.python.training import rmsprop\n\n_RANDOM_SEED = 1337\n_TRAIN_SIZE = 200\n_INPUT_SIZE = (10,)\n_NUM_CLASS = 2\n\n# Note: Please make sure the tests in this file are also covered in\n# keras_backward_compat_test for features that are supported with both APIs.\n\n\n# TODO(anjalisridhar): Add a decorator that will allow us to run these tests as\n# part of the tf.keras unit tests suite.\ndef simple_sequential_model():\n model = keras.models.Sequential()\n model.add(keras.layers.Dense(16, activation='relu', input_shape=_INPUT_SIZE))\n model.add(keras.layers.Dropout(0.1))\n model.add(keras.layers.Dense(_NUM_CLASS, activation='softmax'))\n return model\n\n\ndef simple_functional_model():\n a = keras.layers.Input(shape=_INPUT_SIZE)\n b = keras.layers.Dense(16, activation='relu')(a)\n b = keras.layers.Dropout(0.1)(b)\n b = keras.layers.Dense(_NUM_CLASS, activation='softmax')(b)\n model = keras.models.Model(inputs=[a], outputs=[b])\n return model\n\n\ndef multi_inputs_multi_outputs_model():\n input_a = keras.layers.Input(shape=(16,), name='input_a')\n input_b = keras.layers.Input(shape=(16,), name='input_b')\n input_m = keras.layers.Input(shape=(8,), dtype='string', name='input_m')\n dense = keras.layers.Dense(8, name='dense_1')\n\n interm_a = dense(input_a)\n # Read m\n interm_m = keras.layers.Lambda(gen_parsing_ops.string_to_number)(input_m)\n interm_s = keras.layers.Lambda(lambda k: k[0] * k[1])([interm_m, interm_a])\n interm_b = dense(input_b)\n merged = keras.layers.concatenate([interm_s, interm_b], name='merge')\n output_c = keras.layers.Dense(3, activation='softmax', name='dense_2')(merged)\n output_d = keras.layers.Dense(2, activation='softmax', name='dense_3')(merged)\n model = keras.models.Model(\n inputs=[input_a, input_b, input_m], outputs=[output_c, output_d])\n model.compile(\n loss='categorical_crossentropy',\n optimizer=gradient_descent.GradientDescentOptimizer(0.001),\n metrics={\n 'dense_2': 'categorical_accuracy',\n 'dense_3': 'categorical_accuracy'\n })\n return model\n\n\ndef get_ds_train_input_fn():\n np.random.seed(_RANDOM_SEED)\n (x_train, y_train), _ = testing_utils.get_test_data(\n train_samples=_TRAIN_SIZE,\n test_samples=50,\n input_shape=_INPUT_SIZE,\n num_classes=_NUM_CLASS)\n y_train = keras.utils.to_categorical(y_train)\n\n dataset = dataset_ops.Dataset.from_tensor_slices((x_train, y_train))\n dataset = dataset.batch(32)\n return dataset\n\n\ndef get_ds_test_input_fn():\n np.random.seed(_RANDOM_SEED)\n _, (x_test, y_test) = testing_utils.get_test_data(\n train_samples=_TRAIN_SIZE,\n test_samples=50,\n input_shape=_INPUT_SIZE,\n num_classes=_NUM_CLASS)\n y_test = keras.utils.to_categorical(y_test)\n\n dataset = dataset_ops.Dataset.from_tensor_slices((x_test, y_test))\n dataset = dataset.batch(32)\n return dataset\n\n\ndef get_multi_inputs_multi_outputs_data():\n (a_train, c_train), (a_test, c_test) = testing_utils.get_test_data(\n train_samples=_TRAIN_SIZE,\n test_samples=50,\n input_shape=(16,),\n num_classes=3,\n random_seed=_RANDOM_SEED)\n (b_train, d_train), (b_test, d_test) = testing_utils.get_test_data(\n train_samples=_TRAIN_SIZE,\n test_samples=50,\n input_shape=(16,),\n num_classes=2,\n random_seed=_RANDOM_SEED)\n (m_train, _), (m_test, _) = testing_utils.get_test_data(\n train_samples=_TRAIN_SIZE,\n test_samples=50,\n input_shape=(8,),\n num_classes=2,\n random_seed=_RANDOM_SEED)\n\n c_train = keras.utils.to_categorical(c_train)\n c_test = keras.utils.to_categorical(c_test)\n d_train = keras.utils.to_categorical(d_train)\n d_test = keras.utils.to_categorical(d_test)\n\n train_data = {\n 'input_a': a_train,\n 'input_b': b_train,\n 'input_m': m_train,\n 'output_c': c_train,\n 'output_d': d_train\n }\n test_data = {\n 'input_a': a_test,\n 'input_b': b_test,\n 'input_m': m_test,\n 'output_c': c_test,\n 'output_d': d_test\n }\n\n return (train_data, test_data)\n\n\ndef batch_wrapper(dataset, batch_size, distribution, repeat=None):\n if repeat:\n dataset = dataset.repeat(repeat)\n # TPUs currently require fully defined input shapes, drop_remainder ensures\n # the input will have fully defined shapes.\n if isinstance(distribution, tpu_strategy.TPUStrategy):\n return dataset.batch(batch_size, drop_remainder=True)\n else:\n return dataset.batch(batch_size)\n\n\ndef get_model():\n x = keras.layers.Input(shape=(3,), name='input')\n y = keras.layers.Dense(4, name='dense')(x)\n model = keras.Model(x, y)\n return model\n\n\ndef get_dataset(distribution):\n inputs = np.zeros((10, 3), dtype=np.float32)\n targets = np.zeros((10, 4), dtype=np.float32)\n dataset = dataset_ops.Dataset.from_tensor_slices((inputs, targets))\n dataset = dataset.repeat(100)\n dataset = batch_wrapper(dataset, 10, distribution)\n return dataset\n\n\ndef get_predict_dataset(distribution):\n inputs = np.zeros((10, 3), dtype=np.float32)\n dataset = dataset_ops.Dataset.from_tensor_slices(inputs)\n dataset = dataset.repeat(100)\n dataset = batch_wrapper(dataset, 10, distribution)\n return dataset\n\n\ndef multi_input_output_model():\n a = keras.layers.Input(shape=(3,), name='input_a')\n b = keras.layers.Input(shape=(5,), name='input_b')\n # TODO(anjalisridhar): Change the output dimension of the second Dense layer\n # once the iterator output validation issue has been fixed.\n dense_1 = keras.layers.Dense(7, name='dense_1')\n dense_2 = keras.layers.Dense(7, name='dense_2')\n c = dense_1(a)\n d = dense_2(b)\n e = keras.layers.Dropout(0.5, name='dropout')(c)\n model = keras.models.Model([a, b], [d, e])\n return model\n\n\nstrategies_minus_tpu = [\n combinations.default_strategy,\n combinations.one_device_strategy,\n combinations.mirrored_strategy_with_gpu_and_cpu,\n combinations.mirrored_strategy_with_two_gpus,\n combinations.core_mirrored_strategy_with_gpu_and_cpu,\n combinations.core_mirrored_strategy_with_two_gpus]\n\ntpu_strategies = [\n combinations.tpu_strategy, # steps_per_run=2\n combinations.tpu_strategy_one_step]\n\n\ndef strategy_minus_tpu_combinations():\n return combinations.combine(\n distribution=strategies_minus_tpu,\n mode=['graph', 'eager'])\n\n\ndef tpu_strategy_combinations():\n return combinations.combine(\n distribution=tpu_strategies,\n mode=['graph'])\n\n\ndef all_strategy_combinations():\n return strategy_minus_tpu_combinations() + tpu_strategy_combinations()\n\n\ndef all_strategy_combinations_minus_default():\n strategy_minus_default_combinations = combinations.combine(\n distribution=[\n combinations.one_device_strategy,\n combinations.mirrored_strategy_with_gpu_and_cpu,\n combinations.mirrored_strategy_with_two_gpus,\n combinations.core_mirrored_strategy_with_gpu_and_cpu,\n combinations.core_mirrored_strategy_with_two_gpus],\n mode=['graph', 'eager'])\n return strategy_minus_default_combinations + tpu_strategy_combinations()\n\n\n# TODO(priyag): Add v2 optimizers here.\ndef strategy_and_optimizer_combinations():\n return combinations.times(\n all_strategy_combinations(),\n combinations.combine(\n optimizer=[combinations.adagrad_optimizer_v1_fn,\n combinations.adam_optimizer_v1_fn,\n combinations.gradient_descent_optimizer_v1_fn,\n combinations.rmsprop_optimizer_v1_fn]))\n\n\ndef strategy_for_numpy_input_combinations():\n return combinations.combine(\n distribution=strategies_minus_tpu + tpu_strategies,\n mode=['graph'])\n\n\nclass TestEstimatorDistributionStrategy(test_util.TensorFlowTestCase,\n parameterized.TestCase):\n\n def setUp(self):\n self._base_dir = os.path.join(self.get_temp_dir(),\n 'keras_mirrored_strategy_test')\n gfile.MakeDirs(self._base_dir)\n self._config = run_config_lib.RunConfig(\n tf_random_seed=_RANDOM_SEED, model_dir=self._base_dir)\n\n def tearDown(self):\n writer_cache.FileWriterCache.clear()\n if os.path.isdir(self._base_dir):\n gfile.DeleteRecursively(self._base_dir)\n\n @combinations.generate(combinations.combine(\n distribution=[\n combinations.mirrored_strategy_with_gpu_and_cpu,\n combinations.mirrored_strategy_with_two_gpus,\n combinations.core_mirrored_strategy_with_gpu_and_cpu,\n combinations.core_mirrored_strategy_with_two_gpus],\n mode=['graph']))\n def test_train_functional_with_distribution_strategy(self, distribution):\n keras_model = simple_functional_model()\n keras_model.compile(\n loss='categorical_crossentropy',\n metrics=[keras.metrics.CategoricalAccuracy()],\n optimizer=rmsprop.RMSPropOptimizer(learning_rate=0.01))\n config = run_config_lib.RunConfig(tf_random_seed=_RANDOM_SEED,\n model_dir=self._base_dir,\n train_distribute=distribution,\n eval_distribute=distribution)\n with self.cached_session():\n est_keras = keras_lib.model_to_estimator(\n keras_model=keras_model, config=config)\n before_eval_results = est_keras.evaluate(\n input_fn=get_ds_test_input_fn, steps=1)\n est_keras.train(input_fn=get_ds_train_input_fn, steps=_TRAIN_SIZE / 16)\n after_eval_results = est_keras.evaluate(input_fn=get_ds_test_input_fn,\n steps=1)\n self.assertLess(after_eval_results['loss'], before_eval_results['loss'])\n\n writer_cache.FileWriterCache.clear()\n gfile.DeleteRecursively(self._config.model_dir)\n\n @combinations.generate(combinations.combine(\n distribution=[\n combinations.mirrored_strategy_with_gpu_and_cpu,\n combinations.mirrored_strategy_with_two_gpus,\n combinations.core_mirrored_strategy_with_gpu_and_cpu,\n combinations.core_mirrored_strategy_with_two_gpus],\n mode=['graph']))\n def test_train_sequential_with_distribution_strategy(self, distribution):\n keras_model = simple_sequential_model()\n keras_model.compile(\n loss='categorical_crossentropy',\n metrics=[keras.metrics.CategoricalAccuracy()],\n optimizer=rmsprop.RMSPropOptimizer(learning_rate=0.01))\n config = run_config_lib.RunConfig(tf_random_seed=_RANDOM_SEED,\n model_dir=self._base_dir,\n train_distribute=distribution)\n with self.cached_session():\n est_keras = keras_lib.model_to_estimator(\n keras_model=keras_model, config=config)\n before_eval_results = est_keras.evaluate(\n input_fn=get_ds_test_input_fn, steps=1)\n est_keras.train(input_fn=get_ds_train_input_fn, steps=_TRAIN_SIZE / 16)\n after_eval_results = est_keras.evaluate(input_fn=get_ds_test_input_fn,\n steps=1)\n self.assertLess(after_eval_results['loss'], before_eval_results['loss'])\n\n writer_cache.FileWriterCache.clear()\n gfile.DeleteRecursively(self._config.model_dir)\n\n @combinations.generate(combinations.combine(\n distribution=[\n combinations.mirrored_strategy_with_gpu_and_cpu,\n combinations.core_mirrored_strategy_with_gpu_and_cpu],\n mode=['graph']))\n def test_multi_inputs_multi_outputs_with_input_fn_as_dict(self, distribution):\n train_data, test_data = get_multi_inputs_multi_outputs_data()\n\n def train_input_fn():\n input_dict = {\n 'input_a': train_data['input_a'],\n 'input_b': train_data['input_b'],\n 'input_m': train_data['input_m'].astype(np.str)\n }\n output_dict = {\n 'dense_2': train_data['output_c'],\n 'dense_3': train_data['output_d']\n }\n return dataset_ops.Dataset.from_tensor_slices((input_dict,\n output_dict)).batch(16)\n\n def eval_input_fn():\n input_dict = {\n 'input_a': test_data['input_a'],\n 'input_b': test_data['input_b'],\n 'input_m': test_data['input_m'].astype(np.str)\n }\n output_dict = {\n 'dense_2': test_data['output_c'],\n 'dense_3': test_data['output_d']\n }\n return dataset_ops.Dataset.from_tensor_slices((input_dict,\n output_dict)).batch(16)\n\n self.do_test_multi_inputs_multi_outputs_with_input_fn(\n distribution, train_input_fn, eval_input_fn)\n\n def do_test_multi_inputs_multi_outputs_with_input_fn(\n self, distribution, train_input_fn, eval_input_fn):\n config = run_config_lib.RunConfig(\n tf_random_seed=_RANDOM_SEED,\n model_dir=self._base_dir,\n train_distribute=distribution)\n with self.cached_session():\n model = multi_inputs_multi_outputs_model()\n est_keras = keras_lib.model_to_estimator(keras_model=model, config=config)\n baseline_eval_results = est_keras.evaluate(\n input_fn=eval_input_fn, steps=1)\n est_keras.train(input_fn=train_input_fn, steps=_TRAIN_SIZE / 16)\n eval_results = est_keras.evaluate(input_fn=eval_input_fn, steps=1)\n self.assertLess(eval_results['loss'], baseline_eval_results['loss'])\n\n @combinations.generate(combinations.combine(\n distribution=[\n combinations.mirrored_strategy_with_gpu_and_cpu,\n combinations.core_mirrored_strategy_with_gpu_and_cpu],\n mode=['graph']))\n def test_keras_optimizer_with_distribution_strategy(self, distribution):\n keras_model = simple_sequential_model()\n keras_model.compile(\n loss='categorical_crossentropy',\n optimizer=keras.optimizers.rmsprop(lr=0.01))\n\n config = run_config_lib.RunConfig(tf_random_seed=_RANDOM_SEED,\n model_dir=self._base_dir,\n train_distribute=distribution)\n with self.cached_session():\n est_keras = keras_lib.model_to_estimator(keras_model=keras_model,\n config=config)\n with self.assertRaisesRegexp(ValueError,\n 'Only TensorFlow native optimizers are '\n 'supported with DistributionStrategy.'):\n est_keras.train(input_fn=get_ds_train_input_fn, steps=_TRAIN_SIZE / 16)\n\n writer_cache.FileWriterCache.clear()\n gfile.DeleteRecursively(self._config.model_dir)\n\n\nclass TestDistributionStrategyWithNumpyArrays(test.TestCase,\n parameterized.TestCase):\n\n @combinations.generate(strategy_for_numpy_input_combinations())\n def test_creating_var_with_numpy_arrays(self, distribution):\n with self.cached_session():\n x = np.asarray(np.random.random((64, 3)), dtype=np.float32)\n var_x = distributed_training_utils.get_var_for_numpy(distribution, x)\n val = self.evaluate(var_x.value())\n # Verify that the numpy value is copied to the variable.\n self.assertAllEqual(x, val)\n\n @combinations.generate(strategy_for_numpy_input_combinations())\n def test_calculating_input_params_no_steps_no_batch_size(self, distribution):\n # Calculate the per_replica_batch_size scaling factor for strategies\n # that use per_core_batch_size\n replica_scale_factor = 1.0\n if not distributed_training_utils.global_batch_size_supported(distribution):\n replica_scale_factor = distribution.num_replicas_in_sync\n\n with self.cached_session():\n # Input samples of different sizes\n input_20_samples = np.zeros((20, 3), dtype=np.float32)\n input_63_samples = np.zeros((63, 3), dtype=np.float32)\n input_64_samples = np.zeros((64, 3), dtype=np.float32)\n\n # Default global batch size 32 for input with 64 samples run in 2 steps\n steps, batch_size = distributed_training_utils.get_input_params(\n distribution, input_64_samples, steps=None, batch_size=None)\n self.assertEqual(batch_size, 32 // replica_scale_factor)\n self.assertEqual(steps, 2)\n\n # Computed global batch size 20 is lower than 32 if we pass less samples.\n steps, batch_size = distributed_training_utils.get_input_params(\n distribution, input_20_samples, steps=None, batch_size=None)\n self.assertEqual(batch_size, 20 // replica_scale_factor)\n self.assertEqual(steps, 1)\n\n # Default global batch size 32 cannot be used with 63 samples.\n with self.assertRaisesRegexp(ValueError, 'not divisible by batch size'):\n distributed_training_utils.get_input_params(\n distribution, input_63_samples, steps=None, batch_size=None)\n\n @combinations.generate(strategy_for_numpy_input_combinations())\n def test_calculating_input_params_with_steps_no_batch_size(self,\n distribution):\n # Calculate the per_replica_batch_size scaling factor for strategies\n # that use per_core_batch_size\n replica_scale_factor = 1.0\n if not distributed_training_utils.global_batch_size_supported(distribution):\n replica_scale_factor = distribution.num_replicas_in_sync\n\n with self.cached_session():\n # Input samples of different sizes\n input_63_samples = np.zeros((63, 3), dtype=np.float32)\n input_64_samples = np.zeros((64, 3), dtype=np.float32)\n\n # Computed global batch size is correct for number of specified 1 step\n steps, batch_size = distributed_training_utils.get_input_params(\n distribution, input_64_samples, steps=1, batch_size=None)\n self.assertEqual(batch_size, 64 // replica_scale_factor)\n self.assertEqual(steps, 1)\n\n # Computed global batch size is correct for number of specified 2 steps\n steps, batch_size = distributed_training_utils.get_input_params(\n distribution, input_64_samples, steps=2, batch_size=None)\n self.assertEqual(batch_size, 32 // replica_scale_factor)\n self.assertEqual(steps, 2)\n\n # All samples can not be consumed in specified number of steps\n with self.assertRaisesRegexp(ValueError, 'not divisible by steps'):\n distributed_training_utils.get_input_params(\n distribution, input_63_samples, steps=2, batch_size=None)\n\n # This cases is different for different strategies due to the\n # difference in supported batch size being global or per-replica.\n if replica_scale_factor == 1:\n # Computed global batch size is correct even if not sharadable\n steps, batch_size = distributed_training_utils.get_input_params(\n distribution, input_63_samples, steps=3, batch_size=None)\n self.assertEqual(batch_size, 21)\n self.assertEqual(steps, 3)\n else:\n # Computed global batch size can not be sharded across replicas\n with self.assertRaisesRegexp(ValueError, 'could not be sharded evenly '\n 'across the sync replicas'):\n distributed_training_utils.get_input_params(\n distribution, input_63_samples, steps=1, batch_size=None)\n\n @combinations.generate(strategy_for_numpy_input_combinations())\n def test_calculating_input_params_no_steps_with_batch_size(self,\n distribution):\n # Calculate the per_replica_batch_size scaling factor for strategies\n # that use per_core_batch_size\n replica_scale_factor = 1.0\n if not distributed_training_utils.global_batch_size_supported(distribution):\n replica_scale_factor = distribution.num_replicas_in_sync\n\n with self.cached_session():\n input_64_samples = np.zeros((64, 3), dtype=np.float32)\n\n # Computed steps is correct for specified batch size\n steps, batch_size = distributed_training_utils.get_input_params(\n distribution, input_64_samples, steps=None, batch_size=16)\n self.assertEqual(batch_size, 16)\n self.assertEqual(steps, 4 // replica_scale_factor)\n\n # Computed steps is correct for specified batch size\n steps, batch_size = distributed_training_utils.get_input_params(\n distribution, input_64_samples, steps=None, batch_size=32)\n self.assertEqual(batch_size, 32)\n self.assertEqual(steps, 2 // replica_scale_factor)\n\n # Number of samples is not divisible by the global batch size\n with self.assertRaisesRegexp(ValueError, 'not divisible by batch size'):\n distributed_training_utils.get_input_params(\n distribution, input_64_samples, steps=None, batch_size=20)\n\n # Number of samples is not divisible by the global batch size\n with self.assertRaisesRegexp(ValueError, 'not divisible by batch size'):\n distributed_training_utils.get_input_params(\n distribution, input_64_samples, steps=None, batch_size=3)\n\n @combinations.generate(strategy_for_numpy_input_combinations())\n def test_calculating_input_params_with_steps_with_batch_size(self,\n distribution):\n with self.cached_session():\n input_64_samples = np.zeros((64, 3), dtype=np.float32)\n\n # No change to steps and batch size if both specified and feasible\n steps, batch_size = distributed_training_utils.get_input_params(\n distribution, input_64_samples, steps=5, batch_size=3)\n self.assertEqual(batch_size, 3)\n self.assertEqual(steps, 5)\n\n # Number of samples is less than global batch size * steps\n with self.assertRaisesRegexp(ValueError, 'less than samples required'):\n distributed_training_utils.get_input_params(\n distribution, input_64_samples, steps=10, batch_size=13)\n\n @combinations.generate(strategy_for_numpy_input_combinations())\n def test_calling_model_with_numpy_arrays(self, distribution):\n with self.cached_session():\n with distribution.scope():\n model = get_model()\n optimizer = gradient_descent.GradientDescentOptimizer(0.001)\n loss = 'mse'\n metrics = ['mae']\n model.compile(optimizer, loss, metrics=metrics)\n\n inputs = np.zeros((64, 3), dtype=np.float32)\n targets = np.zeros((64, 4), dtype=np.float32)\n\n # Call fit with validation data\n model.fit(inputs, targets, epochs=1, batch_size=2, verbose=0,\n validation_data=(inputs, targets))\n\n # TODO(anjalisridhar): We need tests for when the batch size and steps are\n # smaller and results in a 0 batch_size and steps value.\n model.evaluate(inputs, targets)\n # with steps\n model.evaluate(inputs, targets, steps=2)\n # with batch_size\n model.evaluate(inputs, targets, batch_size=8)\n\n model.predict(inputs)\n # with steps\n model.predict(inputs, steps=2)\n # with batch_size\n model.predict(inputs, batch_size=8)\n\n @combinations.generate(strategy_for_numpy_input_combinations())\n def test_calling_model_with_nested_numpy_arrays(self, distribution):\n with self.cached_session():\n with distribution.scope():\n model = multi_input_output_model()\n optimizer = gradient_descent.GradientDescentOptimizer(\n learning_rate=0.001)\n loss = 'mse'\n model.compile(optimizer, loss)\n\n input_a_np = np.asarray(np.random.random((64, 3)), dtype=np.float32)\n input_b_np = np.asarray(np.random.random((64, 5)), dtype=np.float32)\n inputs = [input_a_np, input_b_np]\n\n output_d_np = np.asarray(np.random.random((64, 7)), dtype=np.float32)\n output_e_np = np.asarray(np.random.random((64, 7)), dtype=np.float32)\n targets = [output_d_np, output_e_np]\n\n # Call fit with validation data\n model.fit(inputs, targets, epochs=1, batch_size=8, verbose=0)\n\n # TODO(anjalisridhar): We need tests for when the batch size and steps are\n # smaller and results in a 0 batch_size and steps value.\n model.evaluate(inputs, targets)\n # with steps\n model.evaluate(inputs, targets, steps=2)\n # with batch_size\n model.evaluate(inputs, targets, batch_size=8)\n\n model.predict(inputs)\n # with steps\n model.predict(inputs, steps=2)\n # with batch_size\n model.predict(inputs, batch_size=8)\n\n @combinations.generate(combinations.combine(\n distribution=strategies_minus_tpu, mode=['graph']))\n def test_numpy_with_sample_weights(self, distribution):\n with self.cached_session():\n with distribution.scope():\n model = get_model()\n optimizer = rmsprop.RMSPropOptimizer(learning_rate=0.001)\n loss = 'mse'\n model.compile(optimizer, loss)\n\n inputs = np.zeros((20, 3), np.float32)\n targets = np.zeros((20, 4), np.float32)\n sample_weights = np.ones((20), np.float32)\n\n model.fit(inputs, targets, sample_weight=sample_weights, epochs=1,\n steps_per_epoch=2, verbose=1)\n\n @combinations.generate(strategy_for_numpy_input_combinations())\n def test_flatten_predict_outputs(self, distribution):\n with self.cached_session():\n with distribution.scope():\n model = multi_input_output_model()\n optimizer = gradient_descent.GradientDescentOptimizer(\n learning_rate=0.001)\n loss = 'mse'\n model.compile(optimizer, loss)\n\n # We take 6 input samples with each input having a dimension of 3 or 5.\n input_a_np = np.asarray(np.random.random((6, 3)), dtype=np.float32)\n input_b_np = np.asarray(np.random.random((6, 5)), dtype=np.float32)\n inputs = [input_a_np, input_b_np]\n\n outs = model.predict(inputs, steps=1)\n # `predict` a list that is equal in length to the number of model outputs.\n # In this test our model has two outputs and each element of `outs`\n # corresponds to all the samples of one of the model outputs.\n self.assertLen(outs, 2)\n # Each of the output samples have a dimension of 7. We should process all\n # the available input samples(6).\n self.assertAllEqual([6, 7], outs[0].shape)\n self.assertAllEqual([6, 7], outs[1].shape)\n\n\nclass TestDistributionStrategyWithDatasets(test.TestCase,\n parameterized.TestCase):\n\n @combinations.generate(all_strategy_combinations())\n def test_calling_model_on_same_dataset(self, distribution):\n with self.cached_session():\n with distribution.scope():\n model = get_model()\n optimizer = gradient_descent.GradientDescentOptimizer(0.001)\n loss = 'mse'\n metrics = ['mae', keras.metrics.CategoricalAccuracy()]\n model.compile(optimizer, loss, metrics=metrics)\n\n dataset = get_dataset(distribution)\n\n # Call fit with validation data\n model.fit(dataset, epochs=1, steps_per_epoch=2, verbose=0,\n validation_data=dataset, validation_steps=2)\n model.fit(dataset, epochs=1, steps_per_epoch=2, verbose=0,\n validation_data=dataset, validation_steps=2)\n model.predict(get_predict_dataset(distribution), steps=2)\n\n @combinations.generate(all_strategy_combinations())\n def test_model_interleaved_eval_same_as_direct_eval(self, distribution):\n with self.cached_session():\n with distribution.scope():\n user_controlled_model = get_model()\n user_controlled_model.compile(\n gradient_descent.GradientDescentOptimizer(0.001),\n loss='mse',\n metrics=['mae', keras.metrics.CategoricalAccuracy()])\n\n interleaved_model = get_model()\n interleaved_model.set_weights(user_controlled_model.get_weights())\n interleaved_model.compile(\n gradient_descent.GradientDescentOptimizer(0.001),\n loss='mse',\n metrics=['mae', keras.metrics.CategoricalAccuracy()])\n\n dataset = get_dataset(distribution)\n\n # Call fit with validation interleaved\n interleaved_output = interleaved_model.fit(\n dataset, epochs=2, steps_per_epoch=2, verbose=1,\n validation_data=dataset, validation_steps=2, shuffle=False)\n\n # Manually control the validation running after each epoch.\n user_controlled_output = []\n for _ in range(2):\n user_controlled_model.fit(\n dataset, epochs=1, steps_per_epoch=2, verbose=1, shuffle=False)\n user_controlled_output.append(\n user_controlled_model.evaluate(dataset, steps=2))\n\n self.assertEqual(interleaved_output.history['val_loss'],\n [x[0] for x in user_controlled_output])\n self.assertEqual(interleaved_output.history['val_mean_absolute_error'],\n [x[1] for x in user_controlled_output])\n self.assertEqual(interleaved_output.history['val_categorical_accuracy'],\n [x[2] for x in user_controlled_output])\n\n # TODO(priyag): Enable this test for TPU. Currently tuples/dict don't work\n # as clone_model's input_tensors argument only seems to accept list and not\n # tuples or dict.\n\n @combinations.generate(combinations.combine(\n distribution=[\n combinations.mirrored_strategy_with_gpu_and_cpu,\n combinations.core_mirrored_strategy_with_gpu_and_cpu],\n mode=['graph', 'eager']))\n def test_fit_with_tuple_and_dict_dataset_inputs(self, distribution):\n with self.cached_session():\n with distribution.scope():\n model = multi_input_output_model()\n optimizer = gradient_descent.GradientDescentOptimizer(\n learning_rate=0.001)\n loss = 'mse'\n metrics = ['mae', keras.metrics.CategoricalAccuracy()]\n model.compile(optimizer, loss, metrics=metrics)\n\n input_a_np = np.random.random((10, 3))\n input_b_np = np.random.random((10, 5))\n output_d_np = np.random.random((10, 7))\n output_e_np = np.random.random((10, 7))\n\n # Test with tuples\n dataset_tuple = dataset_ops.Dataset.from_tensor_slices((\n (input_a_np, input_b_np), (output_d_np, output_e_np)))\n dataset_tuple = dataset_tuple.repeat(100)\n dataset_tuple = dataset_tuple.batch(10)\n\n model.fit(dataset_tuple, epochs=1, steps_per_epoch=2, verbose=1)\n\n # Test with dict\n dataset_dict = dataset_ops.Dataset.from_tensor_slices((\n {'input_a': input_a_np, 'input_b': input_b_np},\n (output_d_np, output_e_np)))\n dataset_dict = dataset_dict.repeat(100)\n dataset_dict = dataset_dict.batch(10)\n\n model.fit(dataset_dict, epochs=1, steps_per_epoch=2, verbose=1)\n\n @combinations.generate(all_strategy_combinations())\n def test_fit_eval_and_predict_methods_on_dataset(self, distribution):\n with self.cached_session():\n with distribution.scope():\n model = get_model()\n optimizer = gradient_descent.GradientDescentOptimizer(0.001)\n loss = 'mse'\n metrics = ['mae', keras.metrics.CategoricalAccuracy()]\n model.compile(optimizer, loss, metrics=metrics)\n\n dataset = get_dataset(distribution)\n\n model.fit(dataset, epochs=1, steps_per_epoch=2, verbose=1)\n model.evaluate(dataset, steps=2, verbose=1)\n model.predict(get_predict_dataset(distribution), steps=2)\n\n @combinations.generate(strategy_and_optimizer_combinations())\n def test_fit_eval_and_predict_with_optimizer(self, distribution, optimizer):\n with self.cached_session():\n with distribution.scope():\n model = get_model()\n loss = 'mse'\n model.compile(optimizer(), loss)\n\n dataset = get_dataset(distribution)\n\n model.fit(dataset, epochs=1, steps_per_epoch=2, verbose=1)\n model.evaluate(dataset, steps=2, verbose=1)\n model.predict(get_predict_dataset(distribution), steps=2)\n\n @combinations.generate(strategy_minus_tpu_combinations())\n def test_dataset_with_sample_weights(self, distribution):\n with self.cached_session():\n with distribution.scope():\n model = get_model()\n optimizer = rmsprop.RMSPropOptimizer(learning_rate=0.001)\n loss = 'mse'\n model.compile(optimizer, loss)\n\n inputs = np.zeros((10, 3), np.float32)\n targets = np.zeros((10, 4), np.float32)\n sample_weights = np.ones((10), np.float32)\n dataset = dataset_ops.Dataset.from_tensor_slices((inputs, targets,\n sample_weights))\n dataset = dataset.repeat()\n dataset = dataset.batch(10)\n\n model.fit(dataset, epochs=1, steps_per_epoch=2, verbose=1)\n model.evaluate(dataset, steps=2, verbose=1)\n model.predict(dataset, steps=2)\n\n @combinations.generate(combinations.combine(\n distribution=[\n combinations.mirrored_strategy_with_gpu_and_cpu,\n combinations.core_mirrored_strategy_with_gpu_and_cpu],\n mode=['graph', 'eager']))\n # TODO(b/120943676, b/120957836): Re-enable once the validation code is\n # restored.\n def DISABLED_test_dataset_wrong_input_shape(self, distribution):\n with self.cached_session():\n with distribution.scope():\n model = get_model()\n optimizer = rmsprop.RMSPropOptimizer(learning_rate=0.001)\n loss = 'mse'\n model.compile(optimizer, loss)\n\n # Wrong input shape\n inputs = np.zeros((10, 5), dtype=np.float32)\n targets = np.zeros((10, 4), dtype=np.float32)\n dataset = dataset_ops.Dataset.from_tensor_slices((inputs, targets))\n dataset = dataset.repeat(100)\n dataset = dataset.batch(10)\n\n with self.assertRaisesRegexp(ValueError,\n 'expected input to have shape'):\n model.fit(dataset, epochs=1, steps_per_epoch=2, verbose=0)\n\n @combinations.generate(combinations.combine(\n distribution=[combinations.mirrored_strategy_with_gpu_and_cpu],\n mode=['graph', 'eager']))\n # TODO(b/120943676, b/120957836): Re-enable once the validation code is\n # restored.\n def DISABLED_test_dataset_no_batch_input_validation(self, distribution):\n with self.cached_session():\n with distribution.scope():\n model = get_model()\n optimizer = rmsprop.RMSPropOptimizer(learning_rate=0.001)\n loss = 'mse'\n model.compile(optimizer, loss)\n\n # User forgets to batch the dataset\n inputs = np.zeros((10, 3), dtype=np.float32)\n targets = np.zeros((10, 4), dtype=np.float32)\n dataset = dataset_ops.Dataset.from_tensor_slices((inputs, targets))\n dataset = dataset.repeat(100)\n\n with self.assertRaisesRegexp(ValueError, 'expected input to have shape'):\n model.fit(dataset, epochs=1, steps_per_epoch=2, verbose=0)\n\n @combinations.generate(combinations.combine(\n distribution=[combinations.tpu_strategy_one_step],\n mode=['graph']))\n def test_dataset_input_shape_fully_defined(self, distribution):\n with self.cached_session():\n with distribution.scope():\n model = get_model()\n optimizer = rmsprop.RMSPropOptimizer(learning_rate=0.001)\n loss = 'mse'\n model.compile(optimizer, loss)\n\n dataset = get_dataset(distribution)\n # Input shapes are not fully known. Batch dimension is unknown as we are\n # not using the drop_remainder argument.\n dataset = dataset.repeat(100).batch(10)\n\n with self.assertRaisesRegexp(ValueError, 'requires fully defined shapes'):\n model.fit(dataset, epochs=1, steps_per_epoch=2, verbose=0)\n\n @combinations.generate(combinations.combine(\n distribution=[\n combinations.mirrored_strategy_with_gpu_and_cpu,\n combinations.mirrored_strategy_with_two_gpus,\n combinations.core_mirrored_strategy_with_gpu_and_cpu,\n combinations.core_mirrored_strategy_with_two_gpus],\n mode=['graph', 'eager']))\n def test_learning_phase_value(self, distribution):\n # TODO(anjalisridhar): Modify this test to use Lambdas since we can compare\n # meaningful values. Currently we don't pass the learning phase if the\n # Lambda layer uses the learning phase.\n with self.cached_session():\n with distribution.scope():\n x = keras.layers.Input(shape=(1,), name='input')\n y = keras.layers.Dense(1, kernel_initializer='ones')(x)\n z = keras.layers.Dropout(0.9999)(y)\n model = keras.Model(x, z)\n initial_weights = model.get_weights()\n\n optimizer = gradient_descent.GradientDescentOptimizer(0.005)\n loss = 'mse'\n metrics = ['acc']\n model.compile(optimizer, loss, metrics=metrics)\n\n batch_size = 8\n if isinstance(distribution, mirrored_strategy.CoreMirroredStrategy):\n # CoreMirroredStrategy uses global batch size.\n batch_size = 8 * distribution.num_replicas_in_sync\n\n inputs = np.ones((10, 1), dtype=np.float32)\n targets = np.ones((10, 1), dtype=np.float32)\n dataset = dataset_ops.Dataset.from_tensor_slices((inputs, targets))\n dataset = dataset.repeat().batch(batch_size)\n hist = model.fit(dataset, epochs=1, steps_per_epoch=20, verbose=1)\n self.assertAlmostEqual(hist.history['acc'][0], 0, 0)\n\n with distribution.scope():\n model.set_weights(initial_weights)\n # TODO(psv/anjalisridhar): Enable these lines after we fix b/117431185.\n # evaluate_output = model.evaluate(dataset, steps=20)\n # self.assertAlmostEqual(evaluate_output[1], 1, 0)\n\n inputs = np.ones((10, 1), dtype=np.float32)\n predict_dataset = dataset_ops.Dataset.from_tensor_slices(inputs)\n\n predict_dataset = predict_dataset.repeat().batch(batch_size)\n output = model.predict(predict_dataset, steps=10)\n # `predict` runs for 10 steps\n ref_output = np.ones((160, 1), dtype=np.float32)\n self.assertArrayNear(output, ref_output, 1e-1)\n\n @combinations.generate(all_strategy_combinations())\n def testOptimizerWithCallbacks(self, distribution):\n with self.cached_session():\n # TODO(b/120946189): Investigate why default strategy + eager fails.\n if '_Default' in distribution.__class__.__name__:\n self.skipTest('Disable the test for default strategy.')\n with distribution.scope():\n model = get_model()\n optimizer = gradient_descent_keras.SGD(0.01)\n loss = 'mse'\n model.compile(optimizer, loss)\n\n dataset = get_dataset(distribution)\n\n def schedule(_):\n return 0.001\n\n model.fit(dataset, epochs=1, steps_per_epoch=2, verbose=0,\n callbacks=[keras.callbacks.LearningRateScheduler(schedule)])\n self.assertAllClose(0.001, keras.backend.get_value(model.optimizer.lr))\n\n\nclass TestDistributionStrategyErrorCases(test.TestCase, parameterized.TestCase):\n\n @combinations.generate(combinations.combine(\n distribution=[\n combinations.mirrored_strategy_with_gpu_and_cpu,\n combinations.core_mirrored_strategy_with_gpu_and_cpu],\n mode=['graph', 'eager']))\n def test_validating_dataset_input_tensors_with_shape_mismatch(self,\n distribution):\n with self.cached_session():\n a = constant_op.constant([1, 2], shape=(1, 2))\n b = constant_op.constant([[1, 2], [1, 2]], shape=(2, 2))\n device_map = values.ReplicaDeviceMap(('/device:CPU:0', '/device:GPU:0'))\n x = values.DistributedValues(device_map, (a, b))\n y = values.DistributedValues(device_map, (a, a))\n # Removed device and input tensor shape details from the error message\n # since the order of the device and the corresponding input tensor shape\n # is not deterministic over different runs.\n with self.assertRaisesRegexp(ValueError,\n 'Input tensor shapes do not match for '\n 'distributed tensor inputs '\n 'DistributedValues:.+'):\n with distribution.scope():\n distributed_training_utils.validate_distributed_dataset_inputs(\n distribution, x, y)\n\n @combinations.generate(combinations.combine(\n distribution=[\n combinations.mirrored_strategy_with_gpu_and_cpu,\n combinations.core_mirrored_strategy_with_gpu_and_cpu],\n mode=['graph', 'eager']))\n def test_validating_dataset_input_tensors_with_dtype_mismatch(self,\n distribution):\n with self.cached_session():\n a = constant_op.constant([1, 2], shape=(1, 2), dtype=dtypes.int32)\n b = constant_op.constant([1, 2], shape=(1, 2), dtype=dtypes.float64)\n device_map = values.ReplicaDeviceMap(('/device:CPU:0', '/device:GPU:0'))\n x = values.DistributedValues(device_map, (a, b))\n y = values.DistributedValues(device_map, (a, a))\n # Removed device and input tensor dtype details from the error message\n # since the order of the device and the corresponding input tensor dtype\n # is not deterministic over different runs.\n with self.assertRaisesRegexp(ValueError,\n 'Input tensor dtypes do not match for '\n 'distributed tensor inputs '\n 'DistributedValues:.+'):\n with distribution.scope():\n distributed_training_utils.validate_distributed_dataset_inputs(\n distribution, x, y)\n\n @combinations.generate(combinations.combine(\n distribution=[\n combinations.mirrored_strategy_with_gpu_and_cpu,\n combinations.core_mirrored_strategy_with_gpu_and_cpu],\n mode=['graph', 'eager']))\n def test_unsupported_features(self, distribution):\n with self.cached_session():\n with distribution.scope():\n model = get_model()\n optimizer = gradient_descent.GradientDescentOptimizer(0.001)\n loss = 'mse'\n metrics = ['mae']\n model.compile(optimizer, loss, metrics=metrics)\n\n dataset = get_dataset(distribution)\n\n # Test with validation split\n with self.assertRaisesRegexp(\n ValueError, '`validation_split` argument is not '\n 'supported when input `x` is a dataset or a '\n 'dataset iterator.+'):\n model.fit(dataset,\n epochs=1, steps_per_epoch=2, verbose=0,\n validation_split=0.5, validation_steps=2)\n\n # Test with sample weight.\n sample_weight = np.random.random((10,))\n with self.assertRaisesRegexp(\n ValueError, '`sample_weight` argument is not supported when input '\n '`x` is a dataset or a dataset iterator.'):\n model.fit(\n dataset,\n epochs=1,\n steps_per_epoch=2,\n verbose=0,\n sample_weight=sample_weight)\n\n # Test with not specifying the `steps` argument.\n with self.assertRaisesRegexp(\n ValueError, 'the `steps_per_epoch` argument'):\n model.fit(dataset, epochs=1, verbose=0)\n with self.assertRaisesRegexp(ValueError, 'the `steps` argument'):\n model.evaluate(dataset, verbose=0)\n\n with self.assertRaisesRegexp(ValueError, 'the `steps` argument'):\n model.predict(dataset, verbose=0)\n\n @combinations.generate(combinations.combine(\n distribution=[\n combinations.mirrored_strategy_with_gpu_and_cpu,\n combinations.core_mirrored_strategy_with_gpu_and_cpu],\n mode=['graph', 'eager']))\n def test_calling_with_unsupported_predefined_callbacks(self, distribution):\n with self.cached_session():\n with distribution.scope():\n model = get_model()\n optimizer = gradient_descent.GradientDescentOptimizer(0.001)\n loss = 'mse'\n metrics = ['mae']\n model.compile(optimizer, loss, metrics=metrics)\n\n dataset = get_dataset(distribution)\n\n def schedule(_):\n return 0.001\n with self.assertRaisesRegexp(ValueError,\n 'You must specify a Keras Optimizer V2 when '\n 'using'):\n model.fit(dataset, epochs=1, steps_per_epoch=2, verbose=0,\n callbacks=[keras.callbacks.LearningRateScheduler(schedule)])\n\n with self.assertRaisesRegexp(ValueError,\n 'You must specify a Keras Optimizer V2 when '\n 'using'):\n model.fit(dataset, epochs=1, steps_per_epoch=2, verbose=0,\n callbacks=[keras.callbacks.ReduceLROnPlateau()])\n\n\nclass TestDistributionStrategyWithLossMasking(test.TestCase,\n parameterized.TestCase):\n\n # TODO(priyag): Enable all strategies for this test. Currently it does not\n # work for TPU due to some invalid datatype.\n @combinations.generate(combinations.combine(\n distribution=[\n combinations.mirrored_strategy_with_gpu_and_cpu,\n combinations.core_mirrored_strategy_with_gpu_and_cpu],\n mode=['graph', 'eager']))\n def test_masking(self, distribution):\n with self.cached_session():\n np.random.seed(1337)\n x = np.array([[[1], [1]], [[0], [0]]])\n with distribution.scope():\n model = keras.models.Sequential()\n model.add(keras.layers.Masking(mask_value=0, input_shape=(2, 1)))\n model.add(\n keras.layers.TimeDistributed(\n keras.layers.Dense(1, kernel_initializer='one')))\n model.compile(loss='mse',\n optimizer=gradient_descent.GradientDescentOptimizer(0.01))\n y = np.array([[[1], [1]], [[1], [1]]])\n dataset = dataset_ops.Dataset.from_tensor_slices((x, y))\n dataset = dataset.repeat(100)\n dataset = dataset.batch(10)\n hist = model.fit(x=dataset, epochs=1, steps_per_epoch=2)\n self.assertEqual(hist.history['loss'][0], 0)\n\n\nclass TestDistributionStrategyWithNormalizationLayer(\n test.TestCase, parameterized.TestCase):\n\n @combinations.generate(combinations.times(\n all_strategy_combinations(),\n combinations.combine(fused=[True, False])))\n def test_batchnorm_correctness(self, distribution, fused):\n with self.cached_session():\n with distribution.scope():\n model = keras.models.Sequential()\n norm = keras.layers.BatchNormalization(\n input_shape=(10,), momentum=0.8, fused=fused)\n model.add(norm)\n model.compile(loss='mse',\n optimizer=gradient_descent.GradientDescentOptimizer(0.01))\n\n # centered on 5.0, variance 10.0\n x = np.random.normal(loc=5.0, scale=10.0, size=(1000, 10))\n x = x.astype('float32')\n dataset = dataset_ops.Dataset.from_tensor_slices((x, x))\n dataset = dataset.repeat(100)\n dataset = batch_wrapper(dataset, 32, distribution)\n\n predict_dataset = dataset_ops.Dataset.from_tensor_slices(x)\n predict_dataset = predict_dataset.repeat(100)\n predict_dataset = batch_wrapper(predict_dataset, 32, distribution)\n\n model.fit(dataset, epochs=4, verbose=0, steps_per_epoch=10)\n out = model.predict(predict_dataset, steps=2)\n out -= keras.backend.eval(norm.beta)\n out /= keras.backend.eval(norm.gamma)\n np.testing.assert_allclose(out.mean(), 0.0, atol=1e-1)\n np.testing.assert_allclose(out.std(), 1.0, atol=1e-1)\n\n\nclass TestDistributionStrategyValidation(test.TestCase,\n parameterized.TestCase):\n\n @combinations.generate(all_strategy_combinations_minus_default())\n def test_layer_outside_scope(self, distribution):\n with self.cached_session():\n with self.assertRaisesRegexp(\n ValueError, 'was not created in the distribution strategy'):\n x = keras.layers.Input(shape=(3,), name='input')\n y = keras.layers.Dense(4, name='dense')(x)\n with distribution.scope():\n model = keras.Model(x, y)\n optimizer = gradient_descent.GradientDescentOptimizer(0.001)\n loss = 'mse'\n metrics = ['mae', keras.metrics.CategoricalAccuracy()]\n model.compile(optimizer, loss, metrics=metrics)\n\n @combinations.generate(all_strategy_combinations_minus_default())\n def test_model_outside_scope(self, distribution):\n with self.cached_session():\n with self.assertRaisesRegexp(\n ValueError, 'was not created in the distribution strategy'):\n x = keras.layers.Input(shape=(3,), name='input')\n y = keras.layers.Dense(4, name='dense')(x)\n model = keras.Model(x, y)\n with distribution.scope():\n optimizer = gradient_descent.GradientDescentOptimizer(0.001)\n loss = 'mse'\n metrics = ['mae', keras.metrics.CategoricalAccuracy()]\n model.compile(optimizer, loss, metrics=metrics)\n\n @combinations.generate(all_strategy_combinations_minus_default())\n def test_loop_in_scope(self, distribution):\n with self.cached_session():\n with self.assertRaisesRegexp(\n RuntimeError, 'should not be run inside the tf.distribute.Strategy'):\n with distribution.scope():\n x = keras.layers.Input(shape=(3,), name='input')\n y = keras.layers.Dense(4, name='dense')(x)\n model = keras.Model(x, y)\n optimizer = gradient_descent.GradientDescentOptimizer(0.001)\n loss = 'mse'\n model.compile(optimizer, loss)\n input_array = np.zeros((3, 3), dtype=np.float32)\n model.predict(input_array)\n\n\nif __name__ == '__main__':\n test.main()\n"
] | [
[
"tensorflow.python.keras.layers.Lambda",
"tensorflow.python.distribute.values.ReplicaDeviceMap",
"tensorflow.python.keras.layers.Dense",
"tensorflow.python.keras.callbacks.LearningRateScheduler",
"tensorflow.python.keras.layers.BatchNormalization",
"tensorflow.python.keras.layers.concatenate",
"tensorflow.python.keras.engine.distributed_training_utils.validate_distributed_dataset_inputs",
"tensorflow.python.platform.gfile.DeleteRecursively",
"tensorflow.python.platform.gfile.MakeDirs",
"tensorflow.python.keras.callbacks.ReduceLROnPlateau",
"tensorflow.python.estimator.keras.model_to_estimator",
"tensorflow.contrib.distribute.python.combinations.combine",
"numpy.zeros",
"tensorflow.python.keras.engine.distributed_training_utils.get_input_params",
"tensorflow.python.keras.utils.to_categorical",
"tensorflow.python.data.ops.dataset_ops.Dataset.from_tensor_slices",
"tensorflow.python.eager.test.main",
"tensorflow.python.keras.Model",
"tensorflow.python.keras.optimizer_v2.gradient_descent.SGD",
"tensorflow.python.keras.layers.Masking",
"tensorflow.python.keras.models.Sequential",
"tensorflow.python.keras.layers.Dropout",
"tensorflow.python.keras.backend.get_value",
"tensorflow.python.training.rmsprop.RMSPropOptimizer",
"tensorflow.python.keras.layers.Input",
"tensorflow.python.keras.engine.distributed_training_utils.get_var_for_numpy",
"tensorflow.python.training.gradient_descent.GradientDescentOptimizer",
"numpy.array",
"tensorflow.python.distribute.values.DistributedValues",
"tensorflow.python.keras.testing_utils.get_test_data",
"numpy.random.random",
"numpy.random.seed",
"tensorflow.python.keras.backend.eval",
"tensorflow.python.keras.metrics.CategoricalAccuracy",
"numpy.ones",
"tensorflow.python.keras.optimizers.rmsprop",
"numpy.random.normal",
"tensorflow.python.keras.models.Model",
"tensorflow.python.estimator.run_config.RunConfig",
"tensorflow.python.keras.engine.distributed_training_utils.global_batch_size_supported",
"tensorflow.python.summary.writer.writer_cache.FileWriterCache.clear",
"tensorflow.python.framework.constant_op.constant"
]
] |
pvtodorov/systox | [
"746c6ed67db735c580b456a4d9daa53f4850be5b"
] | [
"process_data/process_data_genes_02.py"
] | [
"import pandas as pd\nimport os\n\n# using the merged_medianData.csv create dose-response files for each compound\n\ninfolder = '../data/processed_data/01/LISS/01/'\noutfolder = '../data/processed_data/01/LISS/02/'\n\nif not os.path.exists(outfolder):\n os.makedirs(outfolder)\n\ngeneList = pd.read_csv('../data/lists/gene_list.csv')\ngenes = geneList['Gene'].tolist()\ndata = pd.read_csv(infolder + 'merged_medianData.csv')\ndf0 = data\ncmpMetas_cols = ['CMP', 'DOSES']\ncmpMetas = pd.DataFrame(columns=cmpMetas_cols)\ncompounds = data['CMP'].unique().tolist()\ntimes = [6, 24]\ndf0 = data\ncmpMetas_cols = ['CMP', 'DOSES']\ncmpMetas = pd.DataFrame(columns=cmpMetas_cols)\ncompounds = data['CMP'].unique().tolist()\ntimes = [6, 24]\n\n# the control compounds do not have a dose responses\n# this is because there is only one 'dose' for each compound\n# the dose-response files must still be generated for future computations\ncontrol_compounds = ['DMSO_0.5pct', 'DMSO_0.1pct', 'Medium']\n\n# generate dose responses for all compounds except controls\nfor i in times:\n df1 = df0[df0['TIME'] == i]\n df1 = df1[~df1['CMP'].isin(control_compounds)]\n for j in compounds:\n df2 = df1[df1['CMP'] == j]\n df2 = df2.sort_values('DOSE', axis=0, ascending=True, inplace=False,\n kind='quicksort', na_position='last')\n tempMetas = pd.DataFrame(columns=cmpMetas_cols)\n tempMetas['CMP'] = [j]\n doses = df2['DOSE'].tolist()\n tempMetas['DOSES'] = [doses]\n cmpMetas = cmpMetas.append(tempMetas)\n dosecourse_cols = ['GENE', '1', '2', '3', '4', '5', '6']\n dosecourse = pd.DataFrame(columns=dosecourse_cols)\n for m in genes:\n dosecourseTemp = pd.DataFrame(columns=dosecourse_cols)\n dosecourseTemp['GENE'] = [m]\n geneValues = df2[m].tolist()\n geneValueDoseDict = dict(zip(['1', '2', '3', '4', '5', '6'],\n geneValues))\n for k in geneValueDoseDict:\n dosecourseTemp[k] = [geneValueDoseDict[k]]\n dosecourse = dosecourse.append(dosecourseTemp)\n file = j + '_' + str(i) + 'h'\n dosecourse.to_csv((outfolder + file + '.csv'), index=False)\n cmpMetas = cmpMetas.drop_duplicates('CMP')\n cmpMetas.to_csv(outfolder + 'cmpMetas.csv', index=False)\n\n# generate dose responses for control compounds\nfor i in times:\n df1 = df0[df0['TIME'] == i]\n for j in (control_compounds):\n df2 = df1[df1['CMP'] == j]\n df2 = df2.sort_values('DOSE', axis=0, ascending=True, inplace=False,\n kind='quicksort', na_position='last')\n dosecourse_cols = ['GENE', '1', '2', '3', '4', '5', '6']\n dosecourse = pd.DataFrame(columns=dosecourse_cols)\n dosecourse['GENE'] = genes\n for k in range(1, 7):\n dosecourse[str(k)] = df2[genes].reset_index(drop=True)\\\n .values[0].tolist()\n file = j + '_' + str(i) + 'h'\n dosecourse.to_csv((outfolder + file + '.csv'), index=False)\n"
] | [
[
"pandas.read_csv",
"pandas.DataFrame"
]
] |
jimwatt/P5-vehicledetection | [
"b90a0651056f8288ced0f09141651b5767ef89f7"
] | [
"measurement.py"
] | [
"import numpy as np\n\nclass Measurement:\n def __init__(self,x,y,sx,sy):\n self.xy = np.array([x,y])\n self.sxy = np.array([sx,sy]) "
] | [
[
"numpy.array"
]
] |
esalesky/visrep | [
"b1d9f2384d3f3e2a1e813c830581a8b0b9cda1f5"
] | [
"fairseq/data/vis_align_language_pair_dataset.py"
] | [
"# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport numpy as np\nimport torch\n\n#from . import data_utils, FairseqDataset\nfrom fairseq.data import data_utils, FairseqDataset\n\n\nimport logging\nLOG = logging.getLogger(__name__)\n\n\ndef vis_align_collate(\n samples, pad_idx, eos_idx, left_pad_source=True, left_pad_target=False,\n input_feeding=True,\n):\n if len(samples) == 0:\n return {}\n\n def merge(key, left_pad, move_eos_to_beginning=False):\n return data_utils.collate_tokens(\n [s[key] for s in samples],\n pad_idx, eos_idx, left_pad, move_eos_to_beginning,\n )\n\n def check_alignment(alignment, src_len, tgt_len):\n if alignment is None or len(alignment) == 0:\n return False\n if alignment[:, 0].max().item() >= src_len - 1 or alignment[:, 1].max().item() >= tgt_len - 1:\n LOG.info(\"| alignment size mismatch found, skipping alignment!\")\n return False\n return True\n\n def compute_alignment_weights(alignments):\n \"\"\"\n Given a tensor of shape [:, 2] containing the source-target indices\n corresponding to the alignments, a weight vector containing the\n inverse frequency of each target index is computed.\n For e.g. if alignments = [[5, 7], [2, 3], [1, 3], [4, 2]], then\n a tensor containing [1., 0.5, 0.5, 1] should be returned (since target\n index 3 is repeated twice)\n \"\"\"\n align_tgt = alignments[:, 1]\n _, align_tgt_i, align_tgt_c = torch.unique(\n align_tgt, return_inverse=True, return_counts=True)\n align_weights = align_tgt_c[align_tgt_i[np.arange(len(align_tgt))]]\n return 1. / align_weights.float()\n\n left_pad_source = False\n left_pad_target = False\n\n samples = sorted(samples, key=lambda s: s['source'].numel(), reverse=True)\n\n id = torch.LongTensor([s['id'] for s in samples])\n src_tokens = merge('source', left_pad=left_pad_source)\n src_lengths = torch.LongTensor([s['source'].numel() for s in samples])\n\n prev_output_tokens = None\n target = None\n if samples[0].get('target', None) is not None:\n target = merge('target', left_pad=left_pad_target)\n tgt_lengths = torch.LongTensor(\n [s['target'].numel() for s in samples])\n ntokens = sum(len(s['target']) for s in samples)\n\n if input_feeding:\n # we create a shifted version of targets for feeding the\n # previous output token(s) into the next decoder step\n prev_output_tokens = merge(\n 'target',\n left_pad=left_pad_target,\n move_eos_to_beginning=True,\n )\n prev_output_tokens = prev_output_tokens\n else:\n ntokens = sum(len(s['source']) for s in samples)\n\n src_embeddings_tensor = None\n if 'src_embedding' in samples[0]:\n embedding_shapes = [list(s['src_embedding'].shape)\n for s in samples]\n src_embeddings_width_tensor = torch.LongTensor(\n [s['src_embedding'].shape[0] for s in samples])\n max_shape = np.max(embedding_shapes, axis=0)\n src_embeddings_tensor = torch.zeros(\n len(samples), max_shape[0], max_shape[1]) # (batch, tstep, dim)\n for sample_idx, sample in enumerate(samples):\n sample_shape = sample['src_embedding'].shape\n np_embedding = torch.from_numpy(sample['src_embedding'])\n src_embeddings_tensor[sample_idx,\n 0:np_embedding.shape[0], :] = np_embedding\n\n image_id_list = [s['image_id'] for s in samples]\n utf8_ref_text_list = [s['utf8_ref_text'] for s in samples]\n image_list = [s['image'] for s in samples]\n\n num_channels, word_height, word_width = image_list[0][0].shape\n token_images = torch.ones(len(samples),\n len(image_list[0]), num_channels, word_height, word_width)\n for sample_idx, sample_image_list in enumerate(image_list):\n for word_idx, word_sample in enumerate(sample_image_list):\n width = word_sample.shape[2] # 32, 32, 3\n token_images[sample_idx, word_idx, :, :, :width] = word_sample\n\n batch = {\n 'id': id,\n 'nsentences': len(samples),\n 'ntokens': ntokens,\n 'net_input': {\n 'src_tokens': src_tokens,\n 'src_lengths': src_lengths,\n 'src_images': token_images,\n },\n 'image_id_list': image_id_list,\n 'utf8_ref_text_list': utf8_ref_text_list,\n 'target': target,\n }\n\n if prev_output_tokens is not None:\n batch['net_input']['prev_output_tokens'] = prev_output_tokens\n\n return batch\n\n\nclass VisAlignLanguagePairDataset(FairseqDataset):\n \"\"\"\n A pair of torch.utils.data.Datasets.\n\n Args:\n src (torch.utils.data.Dataset): source dataset to wrap\n src_sizes (List[int]): source sentence lengths\n src_dict (~fairseq.data.Dictionary): source vocabulary\n tgt (torch.utils.data.Dataset, optional): target dataset to wrap\n tgt_sizes (List[int], optional): target sentence lengths\n tgt_dict (~fairseq.data.Dictionary, optional): target vocabulary\n left_pad_source (bool, optional): pad source tensors on the left side\n (default: True).\n left_pad_target (bool, optional): pad target tensors on the left side\n (default: False).\n max_source_positions (int, optional): max number of tokens in the\n source sentence (default: 1024).\n max_target_positions (int, optional): max number of tokens in the\n target sentence (default: 1024).\n shuffle (bool, optional): shuffle dataset elements before batching\n (default: True).\n input_feeding (bool, optional): create a shifted version of the targets\n to be passed into the model for teacher forcing (default: True).\n remove_eos_from_source (bool, optional): if set, removes eos from end\n of source if it's present (default: False).\n append_eos_to_target (bool, optional): if set, appends eos to end of\n target if it's absent (default: False).\n align_dataset (torch.utils.data.Dataset, optional): dataset\n containing alignments.\n \"\"\"\n\n def __init__(\n self, src, src_sizes, src_dict,\n tgt=None, tgt_sizes=None, tgt_dict=None,\n left_pad_source=True, left_pad_target=False,\n max_source_positions=1024, max_target_positions=1024,\n shuffle=True, input_feeding=True,\n remove_eos_from_source=False, append_eos_to_target=False,\n align_dataset=None,\n ):\n if tgt_dict is not None:\n assert src_dict.pad() == tgt_dict.pad()\n assert src_dict.eos() == tgt_dict.eos()\n assert src_dict.unk() == tgt_dict.unk()\n self.src = src\n self.tgt = tgt\n self.src_sizes = np.array(src_sizes)\n self.tgt_sizes = np.array(tgt_sizes) if tgt_sizes is not None else None\n self.src_dict = src_dict\n self.tgt_dict = tgt_dict\n self.left_pad_source = left_pad_source\n self.left_pad_target = left_pad_target\n self.max_source_positions = max_source_positions\n self.max_target_positions = max_target_positions\n self.shuffle = shuffle\n self.input_feeding = input_feeding\n self.remove_eos_from_source = remove_eos_from_source\n self.append_eos_to_target = append_eos_to_target\n self.align_dataset = align_dataset\n if self.align_dataset is not None:\n assert self.tgt_sizes is not None, \"Both source and target needed when alignments are provided\"\n\n def __getitem__(self, index):\n tgt_item = self.tgt[index] if self.tgt is not None else None\n #src_item, src_embedding = self.src[index]\n\n src_metadata = self.src[index]\n src_item = src_metadata['src_item']\n\n # Append EOS to end of tgt sentence if it does not have an EOS and remove\n # EOS from end of src sentence if it exists. This is useful when we use\n # use existing datasets for opposite directions i.e., when we want to\n # use tgt_dataset as src_dataset and vice versa\n if self.append_eos_to_target:\n eos = self.tgt_dict.eos() if self.tgt_dict else self.src_dict.eos()\n if self.tgt and self.tgt[index][-1] != eos:\n tgt_item = torch.cat(\n [self.tgt[index], torch.LongTensor([eos])])\n\n if self.remove_eos_from_source:\n eos = self.src_dict.eos()\n if self.src[index][-1] == eos:\n src_item = self.src[index][:-1]\n\n # 'embedding': src_embedding,\n example = {\n 'id': index,\n 'source': src_item,\n 'target': tgt_item,\n }\n\n # 'src_item': self.tokens_list[i],\n # 'image_id': decode_metadata['image_id'],\n # 'utf8_ref_text': decode_metadata['utf8_ref_text'],\n # 'uxxxx_ref_text': decode_metadata['uxxxx_ref_text'],\n # 'image': decode_metadata['image'],\n\n if 'image_id' in src_metadata:\n example['image_id'] = src_metadata['image_id']\n\n if 'utf8_ref_text' in src_metadata:\n example['utf8_ref_text'] = src_metadata['utf8_ref_text']\n\n if 'uxxxx_ref_text' in src_metadata:\n example['uxxxx_ref_text'] = src_metadata['uxxxx_ref_text']\n\n if 'image' in src_metadata:\n example['image'] = src_metadata['image']\n\n if self.align_dataset is not None:\n example['alignment'] = self.align_dataset[index]\n\n return example\n\n def __len__(self):\n return len(self.src)\n\n def collater(self, samples):\n \"\"\"Merge a list of samples to form a mini-batch.\n\n Args:\n samples (List[dict]): samples to collate\n\n Returns:\n dict: a mini-batch with the following keys:\n\n - `id` (LongTensor): example IDs in the original input order\n - `ntokens` (int): total number of tokens in the batch\n - `net_input` (dict): the input to the Model, containing keys:\n\n - `src_tokens` (LongTensor): a padded 2D Tensor of tokens in\n the source sentence of shape `(bsz, src_len)`. Padding will\n appear on the left if *left_pad_source* is ``True``.\n - `src_lengths` (LongTensor): 1D Tensor of the unpadded\n lengths of each source sentence of shape `(bsz)`\n - `prev_output_tokens` (LongTensor): a padded 2D Tensor of\n tokens in the target sentence, shifted right by one\n position for teacher forcing, of shape `(bsz, tgt_len)`.\n This key will not be present if *input_feeding* is\n ``False``. Padding will appear on the left if\n *left_pad_target* is ``True``.\n\n - `target` (LongTensor): a padded 2D Tensor of tokens in the\n target sentence of shape `(bsz, tgt_len)`. Padding will appear\n on the left if *left_pad_target* is ``True``.\n \"\"\"\n return vis_align_collate(\n samples, pad_idx=self.src_dict.pad(), eos_idx=self.src_dict.eos(),\n left_pad_source=self.left_pad_source, left_pad_target=self.left_pad_target,\n input_feeding=self.input_feeding,\n )\n\n def num_tokens(self, index):\n \"\"\"Return the number of tokens in a sample. This value is used to\n enforce ``--max-tokens`` during batching.\"\"\"\n return max(self.src_sizes[index], self.tgt_sizes[index] if self.tgt_sizes is not None else 0)\n\n def size(self, index):\n \"\"\"Return an example's size as a float or tuple. This value is used when\n filtering a dataset with ``--max-positions``.\"\"\"\n return (self.src_sizes[index], self.tgt_sizes[index] if self.tgt_sizes is not None else 0)\n\n def ordered_indices(self):\n \"\"\"Return an ordered list of indices. Batches will be constructed based\n on this order.\"\"\"\n if self.shuffle:\n indices = np.random.permutation(len(self))\n else:\n indices = np.arange(len(self))\n if self.tgt_sizes is not None:\n indices = indices[np.argsort(\n self.tgt_sizes[indices], kind='mergesort')]\n return indices[np.argsort(self.src_sizes[indices], kind='mergesort')]\n\n @property\n def supports_prefetch(self):\n return (\n getattr(self.src, 'supports_prefetch', False)\n and (getattr(self.tgt, 'supports_prefetch', False) or self.tgt is None)\n )\n\n def prefetch(self, indices):\n self.src.prefetch(indices)\n if self.tgt is not None:\n self.tgt.prefetch(indices)\n if self.align_dataset is not None:\n self.align_dataset.prefetch(indices)\n"
] | [
[
"torch.LongTensor",
"torch.from_numpy",
"numpy.max",
"torch.unique",
"numpy.argsort",
"numpy.array"
]
] |
dstrain115/Stim | [
"82a161741c05d637fe16ea20b1d99a48b4ca4750"
] | [
"src/circuit/circuit_pybind_test.py"
] | [
"# Copyright 2021 Google LLC\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.\nfrom typing import cast\n\nimport stim\nimport pytest\nimport numpy as np\n\n\ndef test_circuit_init_num_measurements_num_qubits():\n c = stim.Circuit()\n assert c.num_qubits == c.num_measurements == 0\n assert str(c).strip() == \"\"\n\n c.append_operation(\"X\", [3])\n assert c.num_qubits == 4\n assert c.num_measurements == 0\n assert str(c).strip() == \"\"\"\nX 3\n \"\"\".strip()\n\n c.append_operation(\"M\", [0])\n assert c.num_qubits == 4\n assert c.num_measurements == 1\n assert str(c).strip() == \"\"\"\nX 3\nM 0\n \"\"\".strip()\n\n\ndef test_circuit_append_operation():\n c = stim.Circuit()\n\n with pytest.raises(IndexError, match=\"Gate not found\"):\n c.append_operation(\"NOT_A_GATE\", [0])\n with pytest.raises(ValueError, match=\"even number of targets\"):\n c.append_operation(\"CNOT\", [0])\n with pytest.raises(ValueError, match=\"takes 0\"):\n c.append_operation(\"X\", [0], 0.5)\n with pytest.raises(ValueError, match=\"invalid modifiers\"):\n c.append_operation(\"X\", [stim.target_inv(0)])\n with pytest.raises(ValueError, match=\"invalid modifiers\"):\n c.append_operation(\"X\", [stim.target_x(0)])\n with pytest.raises(IndexError, match=\"lookback\"):\n stim.target_rec(0)\n with pytest.raises(IndexError, match=\"lookback\"):\n stim.target_rec(1)\n with pytest.raises(IndexError, match=\"lookback\"):\n stim.target_rec(-2**30)\n assert stim.target_rec(-1) is not None\n assert stim.target_rec(-15) is not None\n\n c.append_operation(\"X\", [0])\n c.append_operation(\"X\", [1, 2])\n c.append_operation(\"X\", [3])\n c.append_operation(\"CNOT\", [0, 1])\n c.append_operation(\"M\", [0, stim.target_inv(1)])\n c.append_operation(\"X_ERROR\", [0], 0.25)\n c.append_operation(\"CORRELATED_ERROR\", [stim.target_x(0), stim.target_y(1)], 0.5)\n c.append_operation(\"DETECTOR\", [stim.target_rec(-1)])\n c.append_operation(\"OBSERVABLE_INCLUDE\", [stim.target_rec(-1), stim.target_rec(-2)], 5)\n assert str(c).strip() == \"\"\"\nX 0 1 2 3\nCX 0 1\nM 0 !1\nX_ERROR(0.25) 0\nE(0.5) X0 Y1\nDETECTOR rec[-1]\nOBSERVABLE_INCLUDE(5) rec[-1] rec[-2]\n \"\"\".strip()\n\n\ndef test_circuit_iadd():\n c = stim.Circuit()\n alias = c\n c.append_operation(\"X\", [1, 2])\n c2 = stim.Circuit()\n c2.append_operation(\"Y\", [3])\n c2.append_operation(\"M\", [4])\n c += c2\n assert c is alias\n assert str(c).strip() == \"\"\"\nX 1 2\nY 3\nM 4\n \"\"\".strip()\n\n c += c\n assert str(c).strip() == \"\"\"\nX 1 2\nY 3\nM 4\nX 1 2\nY 3\nM 4\n \"\"\".strip()\n assert c is alias\n\n\ndef test_circuit_add():\n c = stim.Circuit()\n c.append_operation(\"X\", [1, 2])\n c2 = stim.Circuit()\n c2.append_operation(\"Y\", [3])\n c2.append_operation(\"M\", [4])\n assert str(c + c2).strip() == \"\"\"\nX 1 2\nY 3\nM 4\n \"\"\".strip()\n\n assert str(c2 + c2).strip() == \"\"\"\nY 3\nM 4\nY 3\nM 4\n \"\"\".strip()\n\n\ndef test_circuit_mul():\n c = stim.Circuit()\n c.append_operation(\"Y\", [3])\n c.append_operation(\"M\", [4])\n assert str(c * 2) == str(2 * c) == \"\"\"\nREPEAT 2 {\n Y 3\n M 4\n}\n \"\"\".strip()\n assert str((c * 2) * 3) == \"\"\"\nREPEAT 6 {\n Y 3\n M 4\n}\n \"\"\".strip()\n expected = \"\"\"\nREPEAT 3 {\n Y 3\n M 4\n}\n \"\"\".strip()\n assert str(c * 3) == str(3 * c) == expected\n alias = c\n c *= 3\n assert alias is c\n assert str(c) == expected\n c *= 1\n assert str(c) == expected\n assert alias is c\n c *= 0\n assert str(c) == \"\"\n assert alias is c\n\n\ndef test_circuit_repr():\n v = stim.Circuit(\"\"\"\n X 0\n M 0\n \"\"\")\n r = repr(v)\n assert r == \"\"\"stim.Circuit('''\n X 0\n M 0\n''')\"\"\"\n assert eval(r, {'stim': stim}) == v\n\n\ndef test_circuit_eq():\n a = \"\"\"\n X 0\n M 0\n \"\"\"\n b = \"\"\"\n Y 0\n M 0\n \"\"\"\n assert stim.Circuit() == stim.Circuit()\n assert stim.Circuit() != stim.Circuit(a)\n assert not (stim.Circuit() != stim.Circuit())\n assert not (stim.Circuit() == stim.Circuit(a))\n assert stim.Circuit(a) == stim.Circuit(a)\n assert stim.Circuit(b) == stim.Circuit(b)\n assert stim.Circuit(a) != stim.Circuit(b)\n\n assert stim.Circuit() != None\n assert stim.Circuit != object()\n assert stim.Circuit != \"another type\"\n assert not (stim.Circuit == None)\n assert not (stim.Circuit == object())\n assert not (stim.Circuit == \"another type\")\n\n\ndef test_circuit_clear():\n c = stim.Circuit(\"\"\"\n X 0\n M 0\n \"\"\")\n c.clear()\n assert c == stim.Circuit()\n\n\ndef test_circuit_compile_sampler():\n c = stim.Circuit()\n s = c.compile_sampler()\n c.append_operation(\"M\", [0])\n assert repr(s) == \"stim.CompiledMeasurementSampler(stim.Circuit())\"\n s = c.compile_sampler()\n assert repr(s) == \"\"\"\nstim.CompiledMeasurementSampler(stim.Circuit('''\n M 0\n'''))\n \"\"\".strip()\n\n c.append_operation(\"H\", [0, 1, 2, 3, 4])\n c.append_operation(\"M\", [0, 1, 2, 3, 4])\n s = c.compile_sampler()\n r = repr(s)\n assert r == \"\"\"\nstim.CompiledMeasurementSampler(stim.Circuit('''\n M 0\n H 0 1 2 3 4\n M 0 1 2 3 4\n'''))\n \"\"\".strip() == str(stim.CompiledMeasurementSampler(c))\n\n # Check that expression can be evaluated.\n _ = eval(r, {\"stim\": stim})\n\n\ndef test_circuit_compile_detector_sampler():\n c = stim.Circuit()\n s = c.compile_detector_sampler()\n c.append_operation(\"M\", [0])\n assert repr(s) == \"stim.CompiledDetectorSampler(stim.Circuit())\"\n c.append_operation(\"DETECTOR\", [stim.target_rec(-1)])\n s = c.compile_detector_sampler()\n r = repr(s)\n assert r == \"\"\"\nstim.CompiledDetectorSampler(stim.Circuit('''\n M 0\n DETECTOR rec[-1]\n'''))\n \"\"\".strip()\n\n # Check that expression can be evaluated.\n _ = eval(r, {\"stim\": stim})\n\n\ndef test_circuit_flattened_operations():\n assert stim.Circuit('''\n H 0\n REPEAT 3 {\n X_ERROR(0.125) 1\n }\n CORRELATED_ERROR(0.25) X3 Y4 Z5\n M 0 !1\n DETECTOR rec[-1]\n ''').flattened_operations() == [\n (\"H\", [0], 0),\n (\"X_ERROR\", [1], 0.125),\n (\"X_ERROR\", [1], 0.125),\n (\"X_ERROR\", [1], 0.125),\n (\"E\", [(\"X\", 3), (\"Y\", 4), (\"Z\", 5)], 0.25),\n (\"M\", [0, (\"inv\", 1)], 0),\n (\"DETECTOR\", [(\"rec\", -1)], 0),\n ]\n\n\ndef test_copy():\n c = stim.Circuit(\"H 0\")\n c2 = c.copy()\n assert c == c2\n assert c is not c2\n\n\ndef test_hash():\n # stim.Circuit is mutable. It must not also be value-hashable.\n # Defining __hash__ requires defining a FrozenCircuit variant instead.\n with pytest.raises(TypeError, match=\"unhashable\"):\n _ = hash(stim.Circuit())\n\n\ndef test_circuit_generation():\n surface_code_circuit = stim.Circuit.generated(\n \"surface_code:rotated_memory_z\",\n distance=5,\n rounds=10)\n samples = surface_code_circuit.compile_detector_sampler().sample(5)\n assert samples.shape == (5, 24 * 10)\n assert np.count_nonzero(samples) == 0\n\n\ndef test_circuit_generation_errors():\n with pytest.raises(ValueError, match=\"Known repetition_code tasks\"):\n stim.Circuit.generated(\n \"repetition_code:UNKNOWN\",\n distance=3,\n rounds=1000)\n with pytest.raises(ValueError, match=\"Expected type to start with.\"):\n stim.Circuit.generated(\n \"UNKNOWN:memory\",\n distance=0,\n rounds=1000)\n with pytest.raises(ValueError, match=\"distance >= 2\"):\n stim.Circuit.generated(\n \"repetition_code:memory\",\n distance=1,\n rounds=1000)\n\n with pytest.raises(ValueError, match=\"0 <= after_clifford_depolarization <= 1\"):\n stim.Circuit.generated(\n \"repetition_code:memory\",\n distance=3,\n rounds=1000,\n after_clifford_depolarization=-1)\n with pytest.raises(ValueError, match=\"0 <= before_round_data_depolarization <= 1\"):\n stim.Circuit.generated(\n \"repetition_code:memory\",\n distance=3,\n rounds=1000,\n before_round_data_depolarization=-1)\n with pytest.raises(ValueError, match=\"0 <= after_reset_flip_probability <= 1\"):\n stim.Circuit.generated(\n \"repetition_code:memory\",\n distance=3,\n rounds=1000,\n after_reset_flip_probability=-1)\n with pytest.raises(ValueError, match=\"0 <= before_measure_flip_probability <= 1\"):\n stim.Circuit.generated(\n \"repetition_code:memory\",\n distance=3,\n rounds=1000,\n before_measure_flip_probability=-1)\n\n\ndef test_num_detectors():\n assert stim.Circuit().num_detectors == 0\n assert stim.Circuit(\"DETECTOR\").num_detectors == 1\n assert stim.Circuit(\"\"\"\n REPEAT 1000 {\n DETECTOR\n }\n \"\"\").num_detectors == 1000\n assert stim.Circuit(\"\"\"\n DETECTOR\n REPEAT 1000000 {\n REPEAT 1000000 {\n M 0\n DETECTOR rec[-1]\n }\n }\n \"\"\").num_detectors == 1000000**2 + 1\n\n\ndef test_num_observables():\n assert stim.Circuit().num_observables == 0\n assert stim.Circuit(\"OBSERVABLE_INCLUDE(0)\").num_observables == 1\n assert stim.Circuit(\"OBSERVABLE_INCLUDE(1)\").num_observables == 2\n assert stim.Circuit(\"\"\"\n M 0\n OBSERVABLE_INCLUDE(2)\n REPEAT 1000000 {\n REPEAT 1000000 {\n M 0\n OBSERVABLE_INCLUDE(3) rec[-1]\n }\n OBSERVABLE_INCLUDE(4)\n }\n \"\"\").num_observables == 5\n\n\ndef test_indexing_operations():\n c = stim.Circuit()\n assert len(c) == 0\n assert list(c) == []\n with pytest.raises(IndexError):\n _ = c[0]\n with pytest.raises(IndexError):\n _ = c[-1]\n\n c = stim.Circuit('X 0')\n assert len(c) == 1\n assert list(c) == [stim.CircuitInstruction('X', [stim.GateTarget(0)])]\n assert c[0] == c[-1] == stim.CircuitInstruction('X', [stim.GateTarget(0)])\n with pytest.raises(IndexError):\n _ = c[1]\n with pytest.raises(IndexError):\n _ = c[-2]\n\n c = stim.Circuit('''\n X 5 6\n REPEAT 1000 {\n H 5\n }\n M !0\n ''')\n assert len(c) == 3\n with pytest.raises(IndexError):\n _ = c[3]\n with pytest.raises(IndexError):\n _ = c[-4]\n assert list(c) == [\n stim.CircuitInstruction('X', [stim.GateTarget(5), stim.GateTarget(6)]),\n stim.CircuitRepeatBlock(1000, stim.Circuit('H 5')),\n stim.CircuitInstruction('M', [stim.GateTarget(stim.target_inv(0))]),\n ]\n\n\ndef test_slicing():\n c = stim.Circuit(\"\"\"\n H 0\n REPEAT 5 {\n X 1\n }\n Y 2\n Z 3\n \"\"\")\n assert c[:] is not c\n assert c[:] == c\n assert c[1:-1] == stim.Circuit(\"\"\"\n REPEAT 5 {\n X 1\n }\n Y 2\n \"\"\")\n assert c[::2] == stim.Circuit(\"\"\"\n H 0\n Y 2\n \"\"\")\n assert c[1::2] == stim.Circuit(\"\"\"\n REPEAT 5 {\n X 1\n }\n Z 3\n \"\"\")\n\n\ndef test_reappend_gate_targets():\n expected = stim.Circuit(\"\"\"\n MPP !X0 * X1\n CX rec[-1] 5\n \"\"\")\n c = stim.Circuit()\n c.append_operation(\"MPP\", cast(stim.CircuitInstruction, expected[0]).targets_copy())\n c.append_operation(\"CX\", cast(stim.CircuitInstruction, expected[1]).targets_copy())\n assert c == expected\n\n\ndef test_append_instructions_and_blocks():\n c = stim.Circuit()\n\n c.append_operation(\"TICK\")\n assert c == stim.Circuit(\"TICK\")\n\n with pytest.raises(ValueError, match=\"no targets\"):\n c.append_operation(\"TICK\", [1, 2, 3])\n\n c.append_operation(stim.Circuit(\"H 1\")[0])\n assert c == stim.Circuit(\"TICK\\nH 1\")\n\n c.append_operation(stim.Circuit(\"CX 1 2 3 4\")[0])\n assert c == stim.Circuit(\"\"\"\n TICK\n H 1\n CX 1 2 3 4\n \"\"\")\n\n c.append_operation((stim.Circuit(\"X 5\") * 100)[0])\n assert c == stim.Circuit(\"\"\"\n TICK\n H 1\n CX 1 2 3 4\n REPEAT 100 {\n X 5\n }\n \"\"\")\n\n c.append_operation(stim.Circuit(\"PAULI_CHANNEL_1(0.125, 0.25, 0.325) 4 5 6\")[0])\n assert c == stim.Circuit(\"\"\"\n TICK\n H 1\n CX 1 2 3 4\n REPEAT 100 {\n X 5\n }\n PAULI_CHANNEL_1(0.125, 0.25, 0.325) 4 5 6\n \"\"\")\n\n with pytest.raises(ValueError, match=\"must be a\"):\n c.append_operation(object())\n\n with pytest.raises(ValueError, match=\"targets\"):\n c.append_operation(stim.Circuit(\"H 1\")[0], [2])\n\n with pytest.raises(ValueError, match=\"arg\"):\n c.append_operation(stim.Circuit(\"H 1\")[0], [], 0.1)\n\n with pytest.raises(ValueError, match=\"targets\"):\n c.append_operation((stim.Circuit(\"H 1\") * 5)[0], [2])\n\n with pytest.raises(ValueError, match=\"arg\"):\n c.append_operation((stim.Circuit(\"H 1\") * 5)[0], [], 0.1)\n\n with pytest.raises(ValueError, match=\"repeat 0\"):\n c.append_operation(stim.CircuitRepeatBlock(0, stim.Circuit(\"H 1\")))\n"
] | [
[
"numpy.count_nonzero"
]
] |
AlexBrady/FlaskMLService | [
"7a2286a831b683c03635bd5d98da9421c44725a5"
] | [
"defenders/sdg_predict.py"
] | [
"import math\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom sklearn import metrics\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.linear_model import LinearRegression, SGDRegressor\r\nfrom sklearn.cross_validation import cross_val_score\r\nfrom sklearn.metrics import mean_squared_error\r\nfrom sklearn import svm\r\n\r\ndata = pd.read_csv('../resources/newMERGED.csv', sep=',', encoding='utf-8', index_col=0)\r\nmodel = data[['player_id', 'name', 'season', 'pos', 'round', 'team_rank', 'opponent_team_rank', 'team_pot', 'opp_pot',\r\n 'concede_pot', 'opp_concede_pot', 'prev_points', 'form_points', 'total_points',\r\n 'long_form', 'ict_form']]\r\n\r\nDefenderModal = model.loc[model['pos'] == 'Defender']\r\nDefenderModal.drop('pos', axis=1, inplace=True)\r\nDefenderModal.sort_values(['season', 'round'], ascending=True, inplace=True)\r\n# DefenderModal.to_csv('../temp/DEFENDERS.csv', sep=',', encoding='utf-8')\r\nplayers = DefenderModal[5732:]\r\n\r\nkeys = DefenderModal['round']\r\nvalues = pd.cut(DefenderModal['round'], 3, labels=[1, 2, 3])\r\ndictionary = dict(zip(keys, values))\r\nDefenderModal['round'] = values\r\n\r\nX = DefenderModal.drop(['total_points', 'season', 'long_form', 'team_pot', 'opp_concede_pot', 'player_id', 'name'], axis=1)\r\ny = DefenderModal[['total_points']]\r\n\r\nX_train = X[:5731]\r\nX_test = X[5732:]\r\ny_train = y[:5731]\r\ny_test = y[5732:]\r\n\r\nregression_model = SGDRegressor()\r\nregression_model.fit(X_train, y_train)\r\n\r\nscore = regression_model.score(X_test, y_test)\r\ny_pred = regression_model.predict(X_test)\r\n\r\ntesting = pd.concat([X_test, y_test], 1)\r\ntesting['Predicted'] = np.round(y_pred, 1)\r\ntesting['Prediction_Error'] = testing['total_points'] - testing['Predicted']\r\n# testing['Prediction_Error'] = testing['Prediction_Error'].abs()\r\ntesting['player_id'] = 0\r\ntesting['name'] = 0\r\ntesting['player_id'] = players.player_id\r\ntesting['name'] = players.name\r\n\r\nprint('Avg Error:')\r\nprint(testing.Prediction_Error.mean())\r\nprint('Modal score:')\r\nprint(regression_model.score(X_test, y_test))\r\n\r\ntesting.to_csv('../resources/predictions/DEF_sdg_predictions.csv', sep=',', encoding='utf-8')\r\n"
] | [
[
"pandas.concat",
"pandas.read_csv",
"sklearn.linear_model.SGDRegressor",
"numpy.round",
"pandas.cut"
]
] |
Midnighter/conifer-analysis | [
"4cce4a55227603668feb24079c5ab884944527b4"
] | [
"src/conifer_analysis/pipeline.py"
] | [
"# Copyright (c) 2022, Moritz E. Beber.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\n\"\"\"Provide complete dask ETL pipelines.\"\"\"\n\n\nimport numpy as np\nimport pandas as pd\n\nfrom .extract import extract_tsv\nfrom .transform import bin_confidence, tidy_conifer\n\n\nDEFAULT_BINS = np.linspace(0, 1, 51)\n\n\ndef confidence_hist(path: str, bins: np.ndarray = DEFAULT_BINS) -> pd.DataFrame:\n \"\"\"Compute confidence value bins per path and taxa and return a data frame.\"\"\"\n return (\n extract_tsv(path)\n .pipe(tidy_conifer)\n .pipe(bin_confidence, bins=bins)\n .compute()\n .droplevel(-1)\n .reset_index()\n )\n"
] | [
[
"numpy.linspace"
]
] |
jxqhhh/PytorchPointCNN | [
"a19748b9b1c89a869c0785b059b844abd1d3ffd9"
] | [
"util/vis/misc_functions.py"
] | [
"\"\"\"\nCreated on Thu Oct 21 11:09:09 2017\n\n@author: Utku Ozbulak - github.com/utkuozbulak\n\"\"\"\nimport copy\nimport os\n\nimport matplotlib.cm as mpl_color_map\nimport numpy as np\nimport torch\nfrom PIL import Image\nfrom torch.autograd import Variable\nfrom torchvision import models\n\n\ndef convert_to_grayscale(im_as_arr):\n \"\"\"\n Converts 3d image to grayscale\n\n Args:\n im_as_arr (numpy arr): RGB image with shape (D,W,H)\n\n returns:\n grayscale_im (numpy_arr): Grayscale image with shape (1,W,D)\n \"\"\"\n grayscale_im = np.sum(np.abs(im_as_arr), axis=0)\n im_max = np.percentile(grayscale_im, 99)\n im_min = np.min(grayscale_im)\n grayscale_im = (np.clip((grayscale_im - im_min) / (im_max - im_min), 0, 1))\n grayscale_im = np.expand_dims(grayscale_im, axis=0)\n return grayscale_im\n\n\ndef save_gradient_images(gradient, file_name):\n \"\"\"\n Exports the original gradient image\n\n Args:\n gradient (np arr): Numpy array of the gradient with shape (3, 224, 224)\n file_name (str): File name to be exported\n \"\"\"\n if not os.path.exists('../results'):\n os.makedirs('../results')\n # Normalize\n gradient = gradient - gradient.min()\n gradient /= gradient.max()\n # Save image\n path_to_file = os.path.join('../results', file_name + '.jpg')\n save_image(gradient, path_to_file)\n\n\ndef save_class_activation_images(org_img, activation_map, file_name):\n \"\"\"\n Saves cam activation map and activation map on the original image\n\n Args:\n org_img (PIL img): Original image\n activation_map (numpy arr): Activation map (grayscale) 0-255\n file_name (str): File name of the exported image\n \"\"\"\n if not os.path.exists('../results'):\n os.makedirs('../results')\n # Grayscale activation map\n heatmap, heatmap_on_image = apply_colormap_on_image(org_img, activation_map, 'hsv')\n # Save colored heatmap\n path_to_file = os.path.join('../results', file_name + '_Cam_Heatmap.png')\n print(np.max(heatmap))\n save_image(heatmap, path_to_file)\n # Save heatmap on iamge\n print()\n print(np.max(heatmap_on_image))\n path_to_file = os.path.join('../results', file_name + '_Cam_On_Image.png')\n save_image(heatmap_on_image, path_to_file)\n # SAve grayscale heatmap\n print()\n print(np.max(activation_map))\n path_to_file = os.path.join('../results', file_name + '_Cam_Grayscale.png')\n save_image(activation_map, path_to_file)\n\n\ndef apply_colormap_on_image(org_im, activation, colormap_name):\n \"\"\"\n Apply heatmap on image\n Args:\n org_img (PIL img): Original image\n activation_map (numpy arr): Activation map (grayscale) 0-255\n colormap_name (str): Name of the colormap\n \"\"\"\n # Get colormap\n color_map = mpl_color_map.get_cmap(colormap_name)\n no_trans_heatmap = color_map(activation)\n # Change alpha channel in colormap to make sure original image is displayed\n heatmap = copy.copy(no_trans_heatmap)\n heatmap[:, :, 3] = 0.4\n heatmap = Image.fromarray((heatmap * 255).astype(np.uint8))\n no_trans_heatmap = Image.fromarray((no_trans_heatmap * 255).astype(np.uint8))\n\n # Apply heatmap on iamge\n heatmap_on_image = Image.new(\"RGBA\", org_im.size)\n heatmap_on_image = Image.alpha_composite(heatmap_on_image, org_im.convert('RGBA'))\n heatmap_on_image = Image.alpha_composite(heatmap_on_image, heatmap)\n return no_trans_heatmap, heatmap_on_image\n\n\ndef save_image(im, path):\n \"\"\"\n Saves a numpy matrix of shape D(1 or 3) x W x H as an image\n Args:\n im_as_arr (Numpy array): Matrix of shape DxWxH\n path (str): Path to the image\n\n TODO: Streamline image saving, it is ugly.\n \"\"\"\n if isinstance(im, np.ndarray):\n if len(im.shape) == 2:\n im = np.expand_dims(im, axis=0)\n print('A')\n print(im.shape)\n if im.shape[0] == 1:\n # Converting an image with depth = 1 to depth = 3, repeating the same values\n # For some reason PIL complains when I want to save channel image as jpg without\n # additional format in the .save()\n print('B')\n im = np.repeat(im, 3, axis=0)\n print(im.shape)\n # Convert to values to range 1-255 and W,H, D\n # A bandaid fix to an issue with gradcam\n if im.shape[0] == 3 and np.max(im) == 1:\n im = im.transpose(1, 2, 0) * 255\n elif im.shape[0] == 3 and np.max(im) > 1:\n im = im.transpose(1, 2, 0)\n im = Image.fromarray(im.astype(np.uint8))\n im.save(path)\n\n\ndef preprocess_image(pil_im, resize_im=True):\n \"\"\"\n Processes image for CNNs\n\n Args:\n PIL_img (PIL_img): Image to process\n resize_im (bool): Resize to 224 or not\n returns:\n im_as_var (torch variable): Variable that contains processed float tensor\n \"\"\"\n # mean and std list for channels (Imagenet)\n mean = [0.485, 0.456, 0.406]\n std = [0.229, 0.224, 0.225]\n # Resize image\n if resize_im:\n pil_im.thumbnail((512, 512))\n im_as_arr = np.float32(pil_im)\n im_as_arr = im_as_arr.transpose(2, 0, 1) # Convert array to D,W,H\n # Normalize the channels\n for channel, _ in enumerate(im_as_arr):\n im_as_arr[channel] /= 255\n im_as_arr[channel] -= mean[channel]\n im_as_arr[channel] /= std[channel]\n # Convert to float tensor\n im_as_ten = torch.from_numpy(im_as_arr).float()\n # Add one more channel to the beginning. Tensor shape = 1,3,224,224\n im_as_ten.unsqueeze_(0)\n # Convert to Pytorch variable\n im_as_var = Variable(im_as_ten, requires_grad=True)\n return im_as_var\n\n\ndef recreate_image(im_as_var):\n \"\"\"\n Recreates images from a torch variable, sort of reverse preprocessing\n Args:\n im_as_var (torch variable): Image to recreate\n returns:\n recreated_im (numpy arr): Recreated image in array\n \"\"\"\n reverse_mean = [-0.485, -0.456, -0.406]\n reverse_std = [1 / 0.229, 1 / 0.224, 1 / 0.225]\n recreated_im = copy.copy(im_as_var.data.numpy()[0])\n for c in range(3):\n recreated_im[c] /= reverse_std[c]\n recreated_im[c] -= reverse_mean[c]\n recreated_im[recreated_im > 1] = 1\n recreated_im[recreated_im < 0] = 0\n recreated_im = np.round(recreated_im * 255)\n\n recreated_im = np.uint8(recreated_im).transpose(1, 2, 0)\n return recreated_im\n\n\ndef get_positive_negative_saliency(gradient):\n \"\"\"\n Generates positive and negative saliency maps based on the gradient\n Args:\n gradient (numpy arr): Gradient of the operation to visualize\n\n returns:\n pos_saliency ( )\n \"\"\"\n pos_saliency = (np.maximum(0, gradient) / gradient.max())\n neg_saliency = (np.maximum(0, -gradient) / -gradient.min())\n return pos_saliency, neg_saliency\n\n\ndef get_example_params(example_index):\n \"\"\"\n Gets used variables for almost all visualizations, like the image, model etc.\n\n Args:\n example_index (int): Image id to use from examples\n\n returns:\n original_image (numpy arr): Original image read from the file\n prep_img (numpy_arr): Processed image\n target_class (int): Target class for the image\n file_name_to_export (string): File name to export the visualizations\n pretrained_model(Pytorch model): Model to use for the operations\n \"\"\"\n # Pick one of the examples\n example_list = (('../input_images/snake.jpg', 56),\n ('../input_images/cat_dog.png', 243),\n ('../input_images/spider.png', 72))\n img_path = example_list[example_index][0]\n target_class = example_list[example_index][1]\n file_name_to_export = img_path[img_path.rfind('/') + 1:img_path.rfind('.')]\n # Read image\n original_image = Image.open(img_path).convert('RGB')\n # Process image\n prep_img = preprocess_image(original_image)\n # Define model\n pretrained_model = models.alexnet(pretrained=True)\n return (original_image,\n prep_img,\n target_class,\n file_name_to_export,\n pretrained_model)\n"
] | [
[
"numpy.expand_dims",
"numpy.maximum",
"numpy.abs",
"numpy.clip",
"numpy.min",
"numpy.uint8",
"torch.from_numpy",
"numpy.percentile",
"numpy.round",
"numpy.max",
"numpy.float32",
"matplotlib.cm.get_cmap",
"numpy.repeat",
"torch.autograd.Variable"
]
] |
HEEJOWOO/RDCAB-RecursivSRNet-Split-Version- | [
"198dbaaa1b1d5e45aacc6a2da19136bda50cc125"
] | [
"models.py"
] | [
"from torch import nn\nimport torch\nimport torch.nn.functional as F\nclass Scale(nn.Module):\n def __init__(self, init_value=1e-3):\n super().__init__()\n self.scale = nn.Parameter(torch.FloatTensor([init_value]))\n\n def forward(self, input):\n return input * self.scale\n \ndef mean_channels(F):\n assert(F.dim() == 4)\n spatial_sum = F.sum(3, keepdim=True).sum(2, keepdim=True)\n return spatial_sum / (F.size(2) * F.size(3))\n \ndef stdv_channels(F):\n assert(F.dim() == 4)\n F_mean = mean_channels(F)\n F_variance = (F - F_mean).pow(2).sum(3, keepdim=True).sum(2, keepdim=True) / (F.size(2) * F.size(3))\n return F_variance.pow(0.5)\n \nclass RDCAB(nn.Module):\n def __init__(self, in_channels, growth_rate):\n super(RDCAB, self).__init__()\n #Split Mechanism\n distillation_rate=0.25\n self.distilled_channels = int(in_channels * distillation_rate)\n self.remaining_channels = int(in_channels - self.distilled_channels)\n gc = growth_rate\n fc = 48\n \n self.layer1 = nn.Sequential(nn.Conv2d(in_channels + 0 * gc, gc, 3, padding=1, bias=True), nn.ReLU(inplace=True))\n self.layer2 = nn.Sequential(nn.Conv2d(in_channels + 1 * fc, gc, 3, padding=1, bias=True), nn.ReLU(inplace=True))\n self.layer3 = nn.Sequential(nn.Conv2d(in_channels + 2 * fc, gc, 3, padding=1, bias=True), nn.ReLU(inplace=True))\n self.layer4 = nn.Sequential(nn.Conv2d(in_channels + 3 * fc, gc, 3, padding=1, bias=True), nn.ReLU(inplace=True))\n self.layer5 = nn.Sequential(nn.Conv2d(in_channels + 4 * fc, gc, 3, padding=1, bias=True), nn.ReLU(inplace=True))\n self.layer6 = nn.Sequential(nn.Conv2d(in_channels + 5 * fc, gc, 3, padding=1, bias=True), nn.ReLU(inplace=True))\n self.layer7 = nn.Sequential(nn.Conv2d(in_channels + 6 * fc, gc, 3, padding=1, bias=True), nn.ReLU(inplace=True))\n self.layer8 = nn.Sequential(nn.Conv2d(in_channels + 7 * fc, gc, 3, padding=1, bias=True), nn.ReLU(inplace=True))\n #Local Feature Fusion\n self.lff = nn.Conv2d(128, 64, kernel_size=1)\n #Contrast Channle Attention \n self.contrast = stdv_channels\n # feature channel downscale and upscale --> channel weight\n self.avg_pool = nn.AdaptiveAvgPool2d(1)\n self.conv_du = nn.Sequential(\n nn.Conv2d(64, 64 // 16, 1, padding=0, bias=True),\n nn.ReLU(inplace=True),\n nn.Conv2d(64 // 16, 64, 1, padding=0, bias=True),\n nn.Sigmoid()\n )\n \n\n def forward(self, x): \n Local_Residual = x\n \n layer1 = self.layer1(x) #64->64\n distilled_c1, remaining_c1 = torch.split(layer1, (self.distilled_channels, self.remaining_channels), dim=1) # 16 48\n \n layer2 = self.layer2(torch.cat((x, remaining_c1), 1)) # 112->64\n distilled_c2, remaining_c2 = torch.split(layer2, (self.distilled_channels, self.remaining_channels), dim=1) # 16 48\n \n layer3 = self.layer3(torch.cat((x, remaining_c1, remaining_c2), 1)) # 160->48\n distilled_c3, remaining_c3 = torch.split(layer3, (self.distilled_channels, self.remaining_channels), dim=1) # 16 48\n \n layer4 = self.layer4(torch.cat((x, remaining_c1, remaining_c2, remaining_c3), 1)) #208->64\n distilled_c4, remaining_c4 = torch.split(layer4, (self.distilled_channels, self.remaining_channels), dim=1) # 16 48\n \n layer5 = self.layer5(torch.cat((x, remaining_c1, remaining_c2, remaining_c3,remaining_c4), 1)) #256->64\n distilled_c5, remaining_c5 = torch.split(layer5, (self.distilled_channels, self.remaining_channels), dim=1) # 16 48\n \n layer6 = self.layer6(torch.cat((x, remaining_c1, remaining_c2, remaining_c3,remaining_c4,remaining_c5), 1)) #304->64\n distilled_c6, remaining_c6 = torch.split(layer6, (self.distilled_channels, self.remaining_channels), dim=1) # 16 48\n \n layer7 = self.layer7(torch.cat((x, remaining_c1, remaining_c2, remaining_c3,remaining_c4,remaining_c5,remaining_c6), 1)) #352->64\n distilled_c7, remaining_c7 = torch.split(layer7, (self.distilled_channels, self.remaining_channels), dim=1) # 16 48\n \n layer8 = self.layer8(torch.cat((x, remaining_c1, remaining_c2, remaining_c3,remaining_c4,remaining_c5,remaining_c6,remaining_c7), 1)) #400->64\n distilled_c8, remaining_c8 = torch.split(layer8, (self.distilled_channels, self.remaining_channels), dim=1) # 16 48\n \n out = torch.cat([distilled_c1,distilled_c2,distilled_c3,distilled_c4,distilled_c5,distilled_c6,distilled_c7,distilled_c8], dim=1) \n x = self.lff(out)\n \n y =self.contrast(x)+self.avg_pool(x)\n y = self.conv_du(y)\n x = x*y\n x = x+Local_Residual\n return x\n\n\nclass RecursiveBlock(nn.Module):\n def __init__(self,num_channels, num_features, growth_rate, B, U):\n super(RecursiveBlock, self).__init__()\n self.U = U\n self.G0 = num_features\n self.G = growth_rate\n self.rdbs = RDCAB(self.G0, self.G) #residual dense channel attention block & Split Mechanism\n \n def forward(self, sfe2):\n global concat_LF\n x=sfe2\n local_features = []\n for i in range(self.U):\n x = self.rdbs(x)\n local_features.append(x) \n concat_LF = torch.cat(local_features, 1)\n return x\n \nclass DRRDB(nn.Module):\n def __init__(self, scale_factor, num_channels, num_features, growth_rate, B, U):\n super(DRRDB, self).__init__()\n self.B = B\n self.G0 = num_features\n self.G = growth_rate\n self.U = U\n self.scale_factor=scale_factor\n self.num_channels=num_channels\n self.sfe1 = nn.Conv2d(num_channels, num_features, kernel_size=3, padding=3 // 2)\n self.sfe2 = nn.Conv2d(num_features, num_features, kernel_size=3, padding=3 // 2)\n \n self.recursive_SR = nn.Sequential(*[RecursiveBlock(num_channels if i==0 else num_features,\n num_features,\n growth_rate, \n B, \n U) for i in range(B)])\n # Global Feature Fusion\n self.gff = nn.Sequential(\n nn.Conv2d(self.G * self.U * self.B, self.G0, kernel_size=1),\n nn.Conv2d(self.G0, self.G0, kernel_size=3, padding=3 // 2)\n )\n # Upscale & Reconstruction\n self.upscale1 = nn.Conv2d(self.G0,48,self.num_channels,padding=3//2,dilation=1)\n self.upscale1_scale=Scale(1)\n self.pixelshuffle=nn.PixelShuffle(self.scale_factor)\n def forward(self, x):\n x_up = F.interpolate(x, mode='bicubic',scale_factor=self.scale_factor)\n sfe1 = self.sfe1(x)\n sfe2 = self.sfe2(sfe1)\n\n local_global_features=[]\n for i in range(self.B):\n if i==0:\n x= self.recursive_SR(sfe2)\n local_global_features.append(concat_LF)\n\n elif i>0:\n x= self.recursive_SR(x)\n local_global_features.append(concat_LF)\n\n x = self.gff(torch.cat(local_global_features, 1)) + sfe1\n x = self.pixelshuffle(self.upscale1_scale(self.upscale1(x)))+x_up\n return x\n"
] | [
[
"torch.nn.functional.dim",
"torch.cat",
"torch.nn.Conv2d",
"torch.nn.PixelShuffle",
"torch.nn.Sigmoid",
"torch.nn.AdaptiveAvgPool2d",
"torch.FloatTensor",
"torch.nn.functional.interpolate",
"torch.split",
"torch.nn.functional.size",
"torch.nn.functional.sum",
"torch.nn.ReLU"
]
] |
slim-sst/kendryte-model-compiler | [
"ff287df871ed1fdc0dce895d63608307a94b0171"
] | [
"k210_layer.py"
] | [
"# coding=utf-8\n'''\n * Copyright 2018 Canaan 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 '''\n\nimport math\nimport numpy as np\nimport tools\n\nclass K210Conv:\n def __init__(self, weights, depth_wise_layer, eight_bit_mode, xy_shape, xw_minmax, tensor_info):\n self.weights = weights\n self.weights_shape = self.weights.shape\n self.input_shape, self.output_shape = xy_shape\n xmin, xmax, wmin, wmax = xw_minmax\n self.stride = 1\n self.depth_wise_layer = depth_wise_layer\n self.eight_bit_mode = eight_bit_mode\n\n self.x_range = xmax - xmin\n self.x_bias = xmin\n assert (self.x_range > 0)\n\n self.w_range = wmax - wmin\n self.w_bias = wmin\n assert (self.w_range > 0)\n\n if self.input_shape[1:3] != self.output_shape[1:3]:\n raise ValueError('conv2d {} should use padding=SAME'.format(tensor_info.get('name', 'noname')))\n\n if self.input_shape[1] < 4:\n tensor_height = self.input_shape[1]\n print('[error] feature map required height>4 which {} height is {}' \\\n .format(tensor_info.get('name', 'noname'), tensor_height))\n self.input_shape = list(self.input_shape)\n self.output_shape = list(self.output_shape)\n old_input_wh = self.input_shape[1:3]\n old_output_wh = self.output_shape[1:3]\n self.input_shape[1:3] = [4, 4]\n self.output_shape[1:3] = [4, 4]\n notice = 'tensor {} heigh-width MUST padding from {}x{}=>{}x{} to 4x4=>4x4 in CPU before continue.' \\\n .format(tensor_info.get('name', 'noname'), *old_input_wh, *old_output_wh)\n print('[notice] ' + ('=' * 71))\n print('[notice] ' + notice)\n print('[notice] ' + ('=' * 71))\n\n @staticmethod\n def q(value, scale, bias):\n return (value - bias) / scale\n\n def para_mult_loads(self, weights_shape, output_shape, kernel_size):\n weight_buffer_size = 2 * 9 * 4096\n weights_ich = int(weights_shape[2])\n weights_och = int(weights_shape[3])\n weight_data_size = 1 if self.eight_bit_mode else 2\n\n if self.depth_wise_layer:\n o_ch_weights_size = int(weights_shape[0]) * int(weights_shape[1]) * weight_data_size\n else:\n o_ch_weights_size = int(weights_shape[0]) * int(weights_shape[1]) * int(weights_shape[2]) * weight_data_size\n\n if int(weights_shape[0]) == 1:\n o_ch_weights_size_pad = math.ceil(o_ch_weights_size / 8) * 9\n else:\n o_ch_weights_size_pad = o_ch_weights_size\n assert (int(weights_shape[0]) == 3)\n\n if kernel_size == 3:\n load_time = math.ceil(weights_och / math.floor(4096 * 2 / weight_data_size / weights_ich))\n elif kernel_size == 1:\n load_time = math.ceil(weights_och / math.floor(4096 * 8 * 2 / weight_data_size / weights_ich))\n else:\n load_time = None\n assert (None)\n\n o_ch_num = int(output_shape[3])\n o_ch_num_coef = math.floor(weight_buffer_size / o_ch_weights_size_pad)\n\n if self.eight_bit_mode:\n half_weight_buffer_size = weight_buffer_size / 2\n while True:\n last_ch_idx = (o_ch_num - 1) % o_ch_num_coef\n last_addr_end = (last_ch_idx + 1) * o_ch_weights_size_pad\n if last_addr_end < half_weight_buffer_size:\n break\n\n o_ch_num_coef = o_ch_num_coef - 1\n load_time = math.ceil(o_ch_num / o_ch_num_coef)\n if o_ch_num_coef <= 0:\n assert ('cannot fix last_addr_end to first half part')\n\n assert (load_time <= 64)\n\n o_ch_num_coef = min(o_ch_num_coef, o_ch_num)\n para_size = o_ch_num_coef * o_ch_weights_size\n return load_time, para_size, o_ch_num_coef\n\n def to_k210(self):\n input_shape = self.input_shape\n output_shape = self.output_shape\n weights_shape = self.weights_shape\n weights = self.weights\n stride = self.stride\n\n weight_data_size = 1 if self.eight_bit_mode else 2\n kernel_size = int(weights_shape[0])\n\n # img i\n i_row_wid = int(input_shape[2])\n i_col_high = int(input_shape[1])\n coef_group = 1 if i_row_wid > 32 else (2 if i_row_wid > 16 else 4)\n row_switch_addr = math.ceil(i_row_wid / 64)\n channel_switch_addr = i_col_high * row_switch_addr\n # conv\n depth_wise_layer = 1 if self.depth_wise_layer else 0\n kernel_type = {1: 0, 3: 1}[kernel_size]\n pad_type = 0\n load_coor = 1\n\n first_stride = 0 if stride == 1 else 1\n assert (256 >= (i_col_high if first_stride == 0 else i_col_high / 2))\n\n load_time, para_size, o_ch_num_coef = self.para_mult_loads(weights_shape, output_shape, kernel_size)\n\n x_qmax = 255\n w_qmax = (1 << (8 * weight_data_size)) - 1\n bias_x, scale_x = self.x_bias, self.x_range / x_qmax\n bias_w, scale_w = self.w_bias, self.w_range / w_qmax\n\n bx_div_sx = bias_x / scale_x\n bw_div_sw = bias_w / scale_w\n\n shr_x, arg_x = tools.pow_next_log_of_2(bw_div_sw, 24)\n shr_w, arg_w = tools.pow_next_log_of_2(bx_div_sx, 24)\n arg_add = kernel_size * kernel_size * bw_div_sw * bx_div_sx\n pad_value = -bx_div_sx\n swsx = scale_w * scale_x\n\n weight_q = ((weights - bias_w) / scale_w).transpose([3, 2, 0, 1])\n para_start_addr = [int(round(item)) for item in np.reshape(weight_q, (np.product(weight_q.shape),))]\n\n return {\n 'swsx': swsx,\n 'coef_group': coef_group,\n 'channel_switch_addr': channel_switch_addr,\n 'depth_wise_layer': depth_wise_layer,\n 'o_ch_num_coef': o_ch_num_coef,\n 'i_row_wid': i_row_wid,\n 'i_col_high': i_col_high,\n 'kernel_type': kernel_type,\n 'pad_type': pad_type,\n 'first_stride': first_stride,\n 'pad_value': pad_value,\n 'load_coor': load_coor,\n 'load_time': load_time,\n 'para_size': para_size,\n 'para_start_addr': para_start_addr,\n 'row_switch_addr': row_switch_addr,\n 'shr_w': shr_w,\n 'shr_x': shr_x,\n 'arg_w': arg_w,\n 'arg_x': arg_x,\n 'arg_add': arg_add\n }\n\n\nclass K210BN:\n def __init__(self, mean, var, gamma, beta, epsilon, eight_bit_mode, tensor_info=None):\n self.mean = mean\n self.var = var\n self.gamma = gamma\n self.beta = beta\n self.epsilon = epsilon\n self.eight_bit_mode = eight_bit_mode\n self.tensor_info = tensor_info or dict()\n\n @staticmethod\n def get_bn(scale, bias):\n norm_shift, norm_mul = 15, scale\n return {\n 'norm_mul': tools.signed_to_hex(norm_mul, 24),\n 'norm_add': tools.signed_to_hex(bias, 32),\n 'norm_shift': norm_shift\n }\n\n def to_k210(self, swsx=1):\n rsqrt_var = 1.0 / np.sqrt(self.var + self.epsilon)\n\n scale = self.gamma * rsqrt_var\n bias = self.beta - self.gamma * self.mean * rsqrt_var\n\n # todo: rewrite this, make max_abs mul is +-(1<<N)\n bmax = max(abs(np.min(scale)), abs(np.max(scale)))\n brange = bmax\n sb = brange / 255\n swsxsb = swsx * sb # todo: fix this range, this is tooo small for python\n out_shift, out_mul = tools.pow_next_log_of_2_no_round(swsxsb, 15)\n\n bn_shift = 15\n act_shift = out_shift - bn_shift\n post_scale = out_mul / np.round(out_mul) * np.power(2, act_shift)\n\n scale = (scale / sb * out_mul).round().astype('int32')\n bias = (bias * post_scale).round().astype('int32')\n\n load_para = 1\n bwsx_base_addr = [\n self.get_bn(s, b)\n for s, b in zip(scale, bias)\n ]\n\n return locals()\n\n\nclass K210Act:\n def __init__(self, min_y, max_y, ty, eight_bit_mode, tensor_info=None):\n if isinstance(ty, list) or isinstance(ty, tuple):\n self.ty = ty[0]\n self.leaky_mul = ty[1]\n else:\n self.ty = ty\n self.eight_bit_mode = eight_bit_mode\n self.min_y = min_y\n self.max_y = max_y\n self.tensor_info = tensor_info or dict()\n\n @staticmethod\n def leaky_relu(x, v_mul):\n return x if x >= 0 else x * v_mul\n\n @staticmethod\n def leaky_relu_inverse(y, v_mul):\n return y if y >= 0 else y / v_mul\n\n @staticmethod\n def relu_inverse(y):\n return y\n\n @staticmethod\n def relu6_inverse(y):\n return y\n\n @staticmethod\n def leaky_table(min_y, max_y, v_mul):\n range_y = max_y - min_y\n y_table = [min_y + i * range_y / 15 for i in range(15)]\n y_table.append(max_y)\n if 0 not in y_table:\n y_table.append(0)\n y_table = sorted(y_table)\n x_table = [K210Act.leaky_relu_inverse(it, v_mul) for it in y_table]\n dydx = [(y_table[i + 1] - y_table[i]) / (x_table[i + 1] - x_table[i]) for i in range(len(y_table) - 1)]\n return zip(x_table, y_table, dydx)\n\n @staticmethod\n def relu_table(min_y, max_y):\n range_y = max_y - min_y\n y_table = [min_y + i * range_y / 15 for i in range(15)]\n y_table.append(max_y)\n if 0 not in y_table:\n y_table.append(0)\n y_table = sorted(y_table)\n x_table = [K210Act.relu_inverse(it) for it in y_table]\n dydx = [(y_table[i + 1] - y_table[i]) / (x_table[i + 1] - x_table[i]) for i in range(len(y_table) - 1)]\n return zip(x_table, y_table, dydx)\n\n @staticmethod\n def relu6_table(min_y, max_y):\n range_y = max_y - min_y\n y_table = [min_y + i * range_y / 15 for i in range(15)]\n y_table.append(max_y)\n if 0 not in y_table:\n y_table.append(0)\n y_table = sorted(y_table)\n x_table = [K210Act.relu6_inverse(it) for it in y_table]\n dydx = [(y_table[i + 1] - y_table[i]) / (x_table[i + 1] - x_table[i]) for i in range(len(y_table) - 1)]\n return zip(x_table, y_table, dydx)\n\n @staticmethod\n def linear_table(min_y, max_y):\n range_y = max_y - min_y\n y_table = [min_y + i * range_y / 15 for i in range(15)]\n if 0 not in y_table:\n y_table.append(0)\n y_table.append(max_y)\n y_table = sorted(y_table)\n return zip(y_table, y_table, [1] * (len(y_table) - 1))\n\n @staticmethod\n def find_shift(dydx):\n ret_shift = 0\n while abs(dydx) < (1 << 14) and dydx > 0:\n dydx = dydx * 2\n ret_shift = ret_shift + 1\n return ret_shift, dydx\n\n @staticmethod\n def table_to_act(act_table, min_y, max_y, eight_bit_mode, post_scale):\n def act_table_aux(x, y, dydx):\n y_scale = (max_y - min_y) / 255\n y_bias = min_y\n x_fix = x * post_scale\n y_fix = (y - y_bias) / y_scale\n dydx_fix = dydx / y_scale / post_scale\n\n yf_q = round(y_fix)\n yf_err = y_fix - yf_q\n xfy = x_fix - yf_err / dydx_fix\n return xfy, yf_q, dydx_fix\n\n act_table = [(0x800000000, 0, 0)] + [act_table_aux(x, y, dydx) for x, y, dydx in act_table]\n\n def ret_aux(x, y, dydx):\n dxss, dys = K210Act.find_shift(dydx)\n assert (dys >= 0)\n return {'x': int(round(x)), 'y': int(round(y)), 'dxs': dxss, 'dy': int(round(dys))}\n\n return [ret_aux(x, y, dydx) for x, y, dydx in act_table]\n\n def to_k210(self, post_scale):\n act_tab = None\n if self.ty == 'leaky':\n act_tab = list(K210Act.leaky_table(self.min_y, self.max_y, self.leaky_mul))\n elif self.ty == 'Relu':\n act_tab = list(K210Act.relu_table(self.min_y, self.max_y))\n elif self.ty == 'Relu6':\n act_tab = list(K210Act.relu6_table(self.min_y, self.max_y))\n elif self.ty == 'linear':\n act_tab = list(K210Act.linear_table(self.min_y, self.max_y))\n else:\n assert ValueError(self.ty, ' active is not supported.')\n\n active_tab = K210Act.table_to_act(list(act_tab), self.min_y, self.max_y, self.eight_bit_mode, post_scale)\n return {'active_addr': active_tab[:16]}\n\n\nclass K210Pool:\n def __init__(self, pool_type, size, stride, tensor_info=None):\n self.size = size\n self.stride = stride\n self.pool_type = pool_type\n self.tensor_info = tensor_info or dict()\n\n def to_k210(self):\n if self.pool_type == 'MaxPool':\n return {'pool_type': {\n (2, 2): 1,\n (4, 4): 3,\n (2, 1): 9\n }[(self.size, self.stride)]}\n elif self.pool_type == 'AvgPool':\n return {'pool_type': {\n (2, 2): 2,\n (4, 4): 4,\n (2, 1): 8\n }[(self.size, self.stride)]}\n elif self.pool_type == 'leftPool':\n return {'pool_type': {\n (2, 2): 5,\n (4, 4): 7,\n }[(self.size, self.stride)]}\n elif self.pool_type == 'rightPool':\n return {'pool_type': 6}\n else:\n return None\n\n\nclass K210Layer:\n def __init__(self, iwo_minmax, ico_shapes, conv_weights_isdw, bn_mean_var_gamma_beta_epsilon, act_type,\n pool_type_size_stride, eight_bit_mode=False, cbap_tensor_info=None, idx=-1):\n input_min, input_max, weights_min, weights_max, output_min, output_max = iwo_minmax\n input_shape, conv_shape, output_shape = ico_shapes\n conv_weights, conv_isdw = conv_weights_isdw\n conv_tensor_info, bn_tensor_info, act_tensor_info, pool_tensor_info, *_ = [\n *list(cbap_tensor_info or []), dict(), dict(), dict(), dict()\n ]\n\n output_name = pool_tensor_info.get('name') or act_tensor_info.get('name', 'noname')\n input_scale, input_bias = tools.min_max_to_scale_bias(input_min, input_max)\n output_scale, output_bias = tools.min_max_to_scale_bias(output_min, output_max)\n layer_shape_trans = [\n int(input_shape[1]), int(input_shape[2]), int(input_shape[3]),\n int(output_shape[1]), int(output_shape[2]), int(output_shape[3])\n ]\n print(\n '[layer {}]: {}'.format(idx, output_name),\n ' shape(HWC): {}x{}x{} ==> {}x{}x{}'.format(*layer_shape_trans),\n ' scale,bias: ({},{}) ==> ({},{})'.format(input_scale, input_bias, output_scale, output_bias),\n sep='\\n'\n )\n\n self.conv = K210Conv(\n conv_weights,\n conv_isdw,\n eight_bit_mode, [input_shape, conv_shape],\n [input_min, input_max, weights_min, weights_max],\n tensor_info=conv_tensor_info\n )\n\n bn_mean, bn_var, bn_gamma, bn_beta, bn_epsilon = bn_mean_var_gamma_beta_epsilon\n self.bn = K210BN(\n bn_mean,\n bn_var,\n bn_gamma,\n bn_beta,\n bn_epsilon,\n eight_bit_mode,\n tensor_info=bn_tensor_info\n )\n\n self.act = K210Act(output_min, output_max, act_type,\n eight_bit_mode=eight_bit_mode, tensor_info=act_tensor_info)\n\n if pool_type_size_stride is not None:\n pool_type, pool_size, pool_stride = pool_type_size_stride\n if pool_size == 2 and conv_shape[3] % 2 != 0:\n raise ValueError(\n \"at {} unsupport padding mode SAME of pooling\" \\\n .format(pool_tensor_info.get('name', 'noname'))\n )\n\n if conv_isdw and pool_size != 1:\n raise ValueError(\n 'not supported DepthwiseConv2d({}) followed by pooling witch pool_size is not 1.' \\\n .format(pool_tensor_info.get('name', 'noname'))\n )\n\n self.pool = K210Pool(pool_type, pool_size, pool_stride, pool_tensor_info)\n else:\n self.pool = None\n\n @staticmethod\n def batch(iter, n=1):\n l = len(iter)\n for ndx in range(0, l, n):\n yield iter[ndx:min(ndx + n, l)]\n\n def to_k210(self):\n if self.pool is not None:\n output_shape = list(self.conv.output_shape)\n output_shape[1] = int(math.floor(self.conv.output_shape[1] / self.pool.stride))\n output_shape[2] = int(math.floor(self.conv.output_shape[2] / self.pool.stride))\n else:\n output_shape = self.conv.output_shape\n\n weights_shape = self.conv.weights_shape\n input_shape = self.conv.input_shape\n i_row_wid = int(input_shape[1])\n img_data_size = 1\n\n coef_group = 1 if i_row_wid > 32 else (2 if i_row_wid > 16 else 4)\n\n # io\n i_ch_num = int(weights_shape[2])\n o_ch_num = int(output_shape[3])\n # img o\n o_row_wid = int(output_shape[2])\n o_col_high = int(output_shape[1])\n wb_group = 1 if o_row_wid > 32 else (2 if o_row_wid > 16 else 4)\n wb_row_switch_addr = math.ceil(o_row_wid / 64)\n wb_channel_switch_addr = o_col_high * wb_row_switch_addr\n channel_byte_num = o_row_wid * o_col_high\n\n int_en = 0\n image_src_addr = None\n image_dst_addr = None\n dma_total_byte = o_row_wid * o_col_high * o_ch_num\n dma_burst_size = 0xf\n send_data_out = 0\n return locals()\n\n\ndef k210_layer_post_fix(kl_args_list):\n def fix_dw_with_strde2(kl_args_list):\n def expand_wh(shape_):\n shape_1 = shape_[1] * 2\n shape_2 = shape_[2] * 2\n return [shape_[0], shape_1, shape_2, shape_[3]]\n\n ret = []\n lack_of_left_pooling = False\n for kl_args in kl_args_list:\n input_shape, conv_shape, output_shape = kl_args['ico_shapes']\n conv_weights, conv_isdw = kl_args['conv_weights_isdw']\n pool_type_size_stride = kl_args['pool_type_size_stride']\n kl_args_fixed = dict(kl_args)\n\n conv_kernel_size = int(conv_weights.shape[0])\n conv_stride = int((int(input_shape[2]) + 1) / int(conv_shape[2]))\n\n if lack_of_left_pooling:\n if not conv_isdw and conv_kernel_size == 1 and pool_type_size_stride is None:\n # fix in current layer\n input_shape = expand_wh(input_shape)\n conv_shape = expand_wh(conv_shape)\n lack_of_left_pooling = False\n kl_args_fixed['pool_type_size_stride'] = ['leftPool', 2, 2]\n kl_args_fixed['ico_shapes'] = [input_shape, conv_shape, output_shape]\n else:\n if not (conv_kernel_size == 1 and pool_type_size_stride is None):\n raise ValueError(\n 'run fix_dw_with_strde2 failed. ' +\n 'can not delay left_pooling over current layer, ' +\n 'current layer conv_kernel_size:{}, pool_type_size_stride:{}' \\\n .format(conv_kernel_size, pool_type_size_stride)\n )\n\n # delay fix in after layers\n input_shape = expand_wh(input_shape)\n conv_shape = expand_wh(conv_shape)\n output_shape = expand_wh(output_shape)\n kl_args_fixed['ico_shapes'] = [input_shape, conv_shape, output_shape]\n\n if conv_stride == 2:\n if not conv_isdw:\n if pool_type_size_stride is None:\n # fix in current layer\n conv_shape = expand_wh(conv_shape)\n kl_args_fixed['pool_type_size_stride'] = ['leftPool', 2, 2]\n kl_args_fixed['ico_shapes'] = [input_shape, conv_shape, output_shape]\n else:\n # fix later\n lack_of_left_pooling = True\n conv_shape = expand_wh(conv_shape)\n output_shape = expand_wh(output_shape)\n kl_args_fixed['ico_shapes'] = [input_shape, conv_shape, output_shape]\n else:\n # dw layer needs to fix it later\n lack_of_left_pooling = True\n conv_shape = expand_wh(conv_shape)\n output_shape = expand_wh(output_shape)\n kl_args_fixed['ico_shapes'] = [input_shape, conv_shape, output_shape]\n\n ret.append(kl_args_fixed)\n\n if lack_of_left_pooling:\n raise ValueError('run fix_dw_with_strde2 failed. no more layers for fix.')\n return ret\n\n def fix_wh_leas_than_4(kl_args_list):\n def force_pad_to_4(shape_):\n return [shape_[0], 4, 4, shape_[3]]\n\n ret = []\n for kl_args in kl_args_list:\n input_shape, conv_shape, output_shape = kl_args['ico_shapes']\n kl_args_fixed = dict(kl_args)\n\n if input_shape[1] < 4 or conv_shape[1] < 4 or output_shape[1] < 4:\n input_shape = force_pad_to_4(input_shape)\n conv_shape = force_pad_to_4(conv_shape)\n output_shape = force_pad_to_4(output_shape)\n kl_args_fixed['ico_shapes'] = [input_shape, conv_shape, output_shape]\n\n ret.append(kl_args_fixed)\n\n return ret\n\n kl_args_list = fix_wh_leas_than_4(kl_args_list)\n kl_args_list = fix_dw_with_strde2(kl_args_list)\n return kl_args_list\n"
] | [
[
"numpy.product",
"numpy.sqrt",
"numpy.min",
"numpy.power",
"numpy.round",
"numpy.max"
]
] |
jdagdelen/matscholar-web | [
"3bfc22cb1b584c5cf508bea45241a790022f39d7"
] | [
"matscholar_web/callbacks/extract_callbacks.py"
] | [
"import dash_html_components as html\nimport string\nimport os\nimport json\nimport urllib\nimport numpy as np\nfrom dash.dependencies import Input, Output, State\nfrom matscholar.rest import Rester\n\n# Get the rester and random docs on import\nrester = Rester()\nlocal_dir = os.path.dirname(__file__)\nwith open(os.path.join(local_dir, \"../static/data/sample_docs.json\"), \"r\") as f:\n sample_docs = json.load(f)\n\nlabel_mapping = {\n \"MAT\": \"Material\",\n \"APL\": \"Application\",\n \"PRO\": \"Property\",\n \"SPL\": \"Phase\",\n \"SMT\": \"Synthesis\",\n \"CMT\": \"Characterization\",\n \"DSC\": \"Descriptor\",\n \"PVL\": \"Property value\",\n \"PUT\": \"Property unit\"}\n\ndef highlight_entities(tagged_doc):\n highlighted_doc = []\n tagged_doc = [(token, tag) for sent in tagged_doc[0] for (token, tag) in sent]\n for idx, (token, tag) in enumerate(tagged_doc):\n if idx < len(tagged_doc) - 1:\n next_token_punct = True if tagged_doc[idx+1][0] in string.punctuation else False\n else:\n next_token_punct = False\n span = html.Span(token,\n className=\"highlighted {}\".format(tag),\n style={\"padding-right\": \"0px\" if next_token_punct else \"4px\",\n \"background-clip\": \"content-box\"})\n highlighted_doc.append(span)\n return highlighted_doc\n\ndef get_labels():\n return [html.Span(label_mapping[key],\n className=\"highlighted {}\".format(key),\n style={\"padding-right\": \"10px\", \"background-clip\": \"content-box\"})\n for key in label_mapping]\n\ndef bind(app):\n ### Extract App Callbacks ###\n @app.callback(\n Output(\"extract-highlighted\", \"children\"),\n [Input(\"extract-button\", \"n_clicks\")],\n [State(\"extract-textarea\", \"value\"),\n State(\"normalize-radio\", \"value\")])\n def highlight_extracted(n_clicks, text, normalize):\n if n_clicks is not None:\n # Extract highlighted\n return_type = \"normalized\" if normalize == \"yes\" else \"concatenated\"\n result = rester.get_ner_tags([text], return_type=return_type)\n tagged_doc = result[\"tags\"]\n relevance = result[\"relevance\"][0]\n highlighted = highlight_entities(tagged_doc)\n\n #Add the warning\n if not relevance:\n warning = \"WARNING!!! Our classifier has flagged this document as not relevant\" \\\n \" to inorganic materials science. Expect lower than optimum performance.\"\n else:\n warning = \"\"\n\n # Update download link\n doc = {\"sentences\": []}\n for sent in tagged_doc[0]:\n new_sent = []\n for token, tag in sent:\n new_sent.append({\n \"token\": token,\n \"tag\": tag\n })\n doc[\"sentences\"].append(new_sent)\n json_string = json.dumps(doc)\n json_string = \"data:text/csv;charset=utf-8,\" + urllib.parse.quote(json_string)\n return html.Div([html.Div(html.Label(\"Extracted Entity Tags:\")),\n html.Div(warning, style={\"padding-bottom\": \"20px\", \"color\": \"red\"}),\n html.Div(highlighted),\n html.Div(html.Label(\"Labels\"), style={\"padding-top\": \"15px\"}),\n html.Div(get_labels()),\n html.Div(html.A(\"Download entities as json\",\n id=\"entity-download-link\",\n href=json_string,\n download=\"tagged_docs.json\",\n target=\"_blank\"),\n style={\"padding-top\": \"15px\"})])\n @app.callback(\n Output('extract-textarea', 'value'),\n [Input(\"extract-random\", 'n_clicks')])\n def get_random(n_clicks):\n if n_clicks is not None:\n return np.random.choice(sample_docs)\n return \"\"\n\n"
] | [
[
"numpy.random.choice"
]
] |
dimazest/fowler.corpora | [
"ffcd6dff5af1a75b72553f9b7ce22d4186b1afce"
] | [
"fowler/corpora/bnc/corpus.py"
] | [
"import logging\n\nfrom itertools import chain, islice, count\n\nimport pandas as pd\n\nfrom chrono import Timer\nfrom more_itertools import peekable\n\nfrom .util import co_occurrences\n\nlogger = logging.getLogger(__name__)\n\n\nclass Corpus:\n\n # The peak memory usage per worker is about:\n #\n # * 3GB on the sentence similarity task based on ukWaC\n # * 3k most frequent words as context\n # * 185 target words\n #\n # * 4GB ITTF space based on ukWaC\n # * 175154 context words!\n # * 3k target words\n chunk_size = 1 * 10 ** 6\n\n def __init__(self, corpus_reader, stem, tag_first_letter, window_size_before, window_size_after):\n self.corpus_reader = corpus_reader\n\n self.stem = stem\n # TODO: `tag_first_letter` should become `shorten_tags`.\n self.tag_first_letter = tag_first_letter\n self.window_size_before = window_size_before\n self.window_size_after = window_size_after\n\n def cooccurrence(self, path, targets, context):\n \"\"\"Count word co-occurrence in a corpus file.\"\"\"\n logger.debug('Processing %s', path)\n\n def join_columns(frame, prefix):\n # Targets or contexts might be just words, not (word, POS) pairs.\n if isinstance(frame.index[0], tuple):\n return prefix, '{}_tag'.format(prefix)\n\n return (prefix, )\n\n columns = 'target', 'target_tag', 'context', 'context_tag'\n\n target_contexts = peekable(chain.from_iterable(\n co_occurrences(\n document_words,\n window_size_before=self.window_size_before,\n window_size_after=self.window_size_after,\n )\n for document_words in self.words_by_document(path)\n )\n )\n\n T = (lambda t: t) if isinstance(targets.index[0], tuple) else (lambda t: t[0])\n C = (lambda c: c) if isinstance(context.index[0], tuple) else (lambda c: c[0])\n\n first_frame, first_name = targets, 'target'\n second_frame, second_name = context, 'context'\n if len(context) < len(targets):\n first_frame, first_name, second_frame, second_name = (\n second_frame, second_name, first_frame, first_name\n )\n\n while target_contexts:\n some_target_contexts = islice(\n target_contexts,\n self.chunk_size,\n )\n\n with Timer() as timed:\n co_occurrence_pairs = list(some_target_contexts)\n\n if not co_occurrence_pairs:\n continue\n\n logger.debug(\n '%s co-occurrence pairs: %.2f seconds',\n len(co_occurrence_pairs),\n timed.elapsed,\n )\n\n pairs = pd.DataFrame(\n co_occurrence_pairs,\n columns=columns,\n )\n\n def merge(pairs, what_frame, what_name, time, suffixes=None):\n kwargs = {'suffixes': suffixes} if suffixes else {}\n with Timer() as timed:\n result = pairs.merge(\n what_frame,\n left_on=join_columns(what_frame, what_name),\n right_index=True,\n how='inner',\n **kwargs\n )\n logger.debug(\n '%s merge (%s): %.2f seconds',\n time,\n what_name,\n timed.elapsed,\n )\n\n return result\n\n pairs = merge(pairs, first_frame, first_name, 'First')\n pairs = merge(\n pairs,\n second_frame,\n second_name,\n 'Second',\n suffixes=('_' + first_name, '_' + second_name),\n )\n\n with Timer() as timed:\n counts = pairs.groupby(['id_target', 'id_context']).size()\n logger.debug(\n 'Summing up: %.2f seconds',\n timed.elapsed,\n )\n\n logger.debug(\n '%s unique co-occurrence pairs are collected. %s in total.',\n len(counts),\n counts.sum(),\n )\n\n yield counts\n\n def words_by_document(self, path):\n words_by_document = self.corpus_reader.words_by_document(path)\n\n for words in words_by_document:\n\n if self.stem:\n words = ((s, t) for _, s, t in words)\n else:\n words = ((w, t) for w, _, t in words)\n\n if self.tag_first_letter:\n words = ((n, t[0]) for n, t in words)\n\n yield words\n\n def words_iter(self, path):\n for document_words in self.words_by_document(path):\n yield from document_words\n\n def words(self, path):\n \"\"\"Count all the words from a corpus file.\"\"\"\n logger.debug('Processing %s', path)\n\n words = peekable(self.words_iter(path))\n iteration = count()\n while words:\n some_words = list(islice(words, self.chunk_size))\n\n logger.info('Computing frame #%s', next(iteration))\n\n # TODO: store all three values: ngram, stem and tag\n result = pd.DataFrame(\n some_words,\n columns=('ngram', 'tag'),\n )\n\n logger.debug('Starting groupby.')\n result = result.groupby(['ngram', 'tag']).size()\n logger.debug('Finished groupby.')\n\n yield result\n\n def dependencies(self, path):\n \"\"\"Count dependency triples.\"\"\"\n logger.debug('Processing %s', path)\n\n result = pd.DataFrame(\n (\n (h.word, h.stem, h.tag, r, d.word, d.stem, d.tag)\n for h, r, d in self.corpus_reader.dependencies_iter(path)\n ),\n columns=(\n 'head_word',\n 'head_stem',\n 'head_tag',\n 'relation',\n 'dependant_word',\n 'dependant_stem',\n 'dependant_tag',\n )\n )\n\n if self.tag_first_letter:\n raise NotImplemented('Tagging by first letter is not supported!')\n\n if self.stem:\n group_coulumns = ('head_stem', 'head_tag', 'relation', 'dependant_stem', 'dependant_tag')\n else:\n group_coulumns = ('head_word', 'head_tag', 'relation', 'dependant_word', 'dependant_tag')\n\n result['count'] = 1\n\n return result.groupby(group_coulumns).sum()\n\n def verb_subject_object(self, path):\n columns = 'verb', 'verb_stem', 'verb_tag', 'subj', 'subj_stem', 'subj_tag', 'obj', 'obj_stem', 'obj_tag'\n\n result = list(self.corpus_reader.verb_subject_object_iter(path))\n if result:\n result = pd.DataFrame(\n result,\n columns=columns,\n )\n\n if self.tag_first_letter:\n for column in 'verb_tag', 'subj_tag', 'obj_tag':\n result[column] = result[column].str.get(0)\n\n yield result.groupby(columns).size()\n"
] | [
[
"pandas.DataFrame"
]
] |
computationalgeography/lue | [
"71993169bae67a9863d7bd7646d207405dc6f767"
] | [
"source/framework/python/test/algorithm/downstream_test.py"
] | [
"import lue.framework as lfr\nimport lue_test\nimport numpy as np\n\n\ndef setUpModule():\n lue_test.start_hpx_runtime()\n\n\ndef tearDownModule():\n pass\n # lue_test.stop_hpx_runtime()\n\n\nclass DownstreamTest(lue_test.TestCase):\n\n def test_overloads(self):\n\n array_shape = (60, 40)\n partition_shape = (10, 10)\n\n direction = 1\n flow_direction = lfr.create_array(array_shape, partition_shape, np.dtype(np.uint8), direction)\n material = lfr.create_array(array_shape, partition_shape, np.dtype(np.uint64), 1)\n\n downstream = lfr.downstream(flow_direction, material)\n"
] | [
[
"numpy.dtype"
]
] |
Safeaspie/Team-Computer | [
"0c6378408fccbe1ff573267802802c8c61e20b79"
] | [
"ApplicationWithSentiment/app/src/main/python/processData.py"
] | [
"import pandas as pd\nfrom openpyxl import Workbook\nfrom time import sleep\n\nangry = pd.read_csv(\"Emotion(angry).csv\")\nhappy = pd.read_csv(\"Emotion(happy).csv\")\nsad = pd.read_csv(\"Emotion(sad).csv\")\nangry = angry[:]\nhappy = happy[:]\nsad = sad[:]\ndatas = [angry, happy, sad]\n\n#Open library for working in excel sheets\nworkbook = Workbook()\nsheet = workbook.active\n\n#Assign the labels for each piece of data\nsheet[\"A1\"] = \"Sentence\"\nsheet[\"B1\"] = \"Sentiment\"\n\n#Function for saving the excel file\ndef savebook(workbook):\n while True:\n try:\n workbook.save(filename=\"SentimentAnalysisData.xlsx\")\n break\n except:\n print(\"Currently busy trying again...\")\n sleep(5)\n\nindex = 2\nfor data in happy[\"content\"]:\n \n sheet[f\"A{index}\"] = data\n sheet[f\"B{index}\"] = \"Happy\"\n index = index + 1\n \nfor data in sad[\"content\"]:\n \n if data[0] == \"[\":\n splitup = data.split(\"', '\")\n for s in splitup:\n s = s.replace(\"[\", \"\")\n s = s.replace(\"]\", \"\")\n s = s.replace(\"(Sad Whatsapp Status\\xa0\", \"\")\n s = s.replace(\"\\\\xa0( Sad Whatsapp Status\\\\xa0\", \"\")\n s = s.replace(\"( Sad Quotes\\\\xa0\", \"\")\n s = s.replace(\"(Sad Whatsapp Status\\xa0\", \"\")\n s = s.replace(\"'\", \"\")\n s = s.replace(\"( Sad Status\\xa0\", \"\")\n s = s.replace(\"( Sad Whatsapp Status\\\\xa0\", \"\")\n s = s.replace(\"( Sad Status for Whatsapp\\\\xa0\", \"\")\n s = s.replace(\"\\\\xa0(\\\\xa0Sad Quotes\", \"\")\n sheet[f\"A{index}\"] = s\n sheet[f\"B{index}\"] = \"Sad\"\n index = index + 1\n else:\n sheet[f\"A{index}\"] = data\n sheet[f\"B{index}\"] = \"Sad\"\n index = index + 1\n\nfor data in angry[\"content\"]:\n \n if data[0] == \"[\":\n splitup = data.split(\"', '\")\n for s in splitup:\n s = s.replace(\"[\", \"\")\n s = s.replace(\"]\", \"\")\n s = s.replace(\"( Angry Whatsapp Status\\\\xa0\", \"\")\n s = s.replace(\"(\\\\xa0Angry\\\\xa0Quotes\\\\xa0\", \"\")\n s = s.replace(\"(\\\\xa0Angry Status\\\\xa0\", \"\")\n s = s.replace(\"(\\\\xa0Angry Whatsapp Status\\\\xa0\", \"\")\n s = s.replace(\"\\\\xa0( Angry Whatsapp Status\\\\xa0\", \"\")\n s = s.replace(\"\\\\xa0(\\\\xa0Anger Status for Whatsapp\\\\xa0\", \"\")\n s = s.replace(\"\\\\xa0(\\\\xa0Angry Quotes for Relationship\\\\xa0\", \"\")\n s = s.replace(\"\\\\xa0(\\\\xa0Angry Love Quotes\\\\xa0\", \"\")\n sheet[f\"A{index}\"] = s\n sheet[f\"B{index}\"] = \"Angry\"\n index = index + 1\n else:\n sheet[f\"A{index}\"] = data\n sheet[f\"B{index}\"] = \"Angry\"\n index = index + 1\n\nsavebook(workbook)"
] | [
[
"pandas.read_csv"
]
] |
premprabhat/treelite | [
"997cbfc3a8541c2ce81cd082825e5ac6879d9b96"
] | [
"tests/python/test_invalid_categorical_input.py"
] | [
"# -*- coding: utf-8 -*-\n# pylint: disable=missing-function-docstring\n\"\"\"Test whether Treelite handles invalid category values correctly\"\"\"\nimport os\n\nimport treelite\nimport treelite_runtime\nimport numpy as np\nimport pytest\nfrom treelite.contrib import _libext\n\nfrom .util import os_compatible_toolchains\n\[email protected](name='toy_model')\ndef toy_model_fixture():\n builder = treelite.ModelBuilder(num_feature=2)\n tree = treelite.ModelBuilder.Tree()\n tree[0].set_categorical_test_node(feature_id=1, left_categories=[0], default_left=True,\n left_child_key=1, right_child_key=2)\n tree[1].set_leaf_node(-1.0)\n tree[2].set_leaf_node(1.0)\n tree[0].set_root()\n builder.append(tree)\n model = builder.commit()\n\n return model\n\[email protected](name='test_data')\ndef test_data_fixture():\n categorical_column = np.array([-1, -0.6, -0.5, 0, 0.3, 0.7, 1, np.nan, np.inf, 1e10, -1e10],\n dtype=np.float32)\n dummy_column = np.zeros(categorical_column.shape[0], dtype=np.float32)\n return np.column_stack((dummy_column, categorical_column))\n\[email protected](name='ref_pred')\ndef ref_pred_fixture():\n # Negative inputs are mapped to the right child node\n # 0.3 and 0.7 are mapped to the left child node, since they get rounded toward the zero.\n # Missing value gets mapped to the left child node, since default_left=True\n # inf, 1e10, and -1e10 don't match any element of left_categories, so they get mapped to the\n # right child.\n return np.array([1, 1, 1, -1, -1, -1, 1, -1, 1, 1, 1], dtype=np.float32)\n\ndef test_gtil(toy_model, test_data, ref_pred):\n pred = treelite.gtil.predict(toy_model, test_data)\n np.testing.assert_equal(pred, ref_pred)\n\ndef test_treelite_compiled(tmpdir, toy_model, test_data, ref_pred):\n libpath = os.path.join(tmpdir, 'mylib' + _libext())\n toolchain = os_compatible_toolchains()[0]\n toy_model.export_lib(toolchain=toolchain, libpath=libpath)\n\n predictor = treelite_runtime.Predictor(libpath=libpath)\n dmat = treelite_runtime.DMatrix(test_data)\n pred = predictor.predict(dmat)\n np.testing.assert_equal(pred, ref_pred)\n"
] | [
[
"numpy.testing.assert_equal",
"numpy.array",
"numpy.zeros",
"numpy.column_stack"
]
] |
boolean5/VirtualSign | [
"bdb1ade73996049bdd12a9fedc38252c7572eed2"
] | [
"evaluate.py"
] | [
"import argparse\n\nimport numpy as np\nfrom keras.models import load_model\nfrom keras.utils import np_utils\n\nfrom utils import create_dataset\n\n# Parsing from terminal\nparser = argparse.ArgumentParser(description='Evaluate a trained model')\nparser.add_argument('model_path', help='Path of the model to be evaluated')\nparser.add_argument('test_set_path', help='Path of test set folder')\nargs = parser.parse_args()\n\ntest_set_path = args.test_set_path\nmodel_path = args.model_path\n\n# Loading\nmodel = load_model(model_path)\ntest_set = create_dataset(test_set_path, randomize=False, deletedups=False)\n\n# Data manipulation\ny_test, x_test = np.hsplit(test_set, [1])\n\n# This line is added for classes that range from 1 to 42\n# y_test = y_test - 1\ny_test = np_utils.to_categorical(y_test, 42)\nx_test = np.expand_dims(x_test, axis=2)\n\n# Evaluation\nloss, acc = model.evaluate(x_test, y_test, verbose=1)\nprint(loss, acc)\n"
] | [
[
"numpy.expand_dims",
"numpy.hsplit"
]
] |
memfagor/spectconv | [
"69002c2a95ee0113a4b117dc5ebb87044687941b"
] | [
"convbase.py"
] | [
"#!/usr/bin/env python3\n\nimport os\nimport json\nimport pandas as pd\n\n\ndef get_config(filename):\n with open(os.path.join(os.getcwd(), filename), 'r') as config_file:\n config = json.load(config_file)\n return config\n\ndef get_files_list(dir_path, extension):\n return [f for f in os.listdir(dir_path) if extension in os.path.splitext(f)[1][1:]]\n\ndef get_files_dict(dir_path, extension):\n return {str(i).zfill(3): {'filename': f, 'label': str(i)} for i, f in enumerate(get_files_list(dir_path, extension))}\n\ndef save_files_dict(data, filename):\n with open(os.path.join(os.getcwd(), filename), 'w') as list_file:\n json.dump(data, list_file, sort_keys=True, indent=4)\n\ndef normalize(target):\n max = target.max()\n min = target.min()\n if not max == min:\n result = (target - min)/(max - min)\n else:\n result = 0\n return result\n\ndef standarize(target):\n mean = target.mean()\n std = target.std()\n if not std == 0:\n result = (target - mean)/std\n else:\n result = 0\n return result\n\ndef get_file_name(file_name):\n return os.path.splitext(file_name)[0]\n\ndef get_new_extension(file_name, extension):\n return '.'.join((get_file_name(file_name), extension))\n\ndef save_to_excel(dfs, path):\n with pd.ExcelWriter(path) as writer:\n for n, df in enumerate(dfs):\n df.to_excel(writer, 'Sheet{}'.format(n+1))\n writer.save()\n\ndef tests():\n pass\n\nif __name__ == '__main__':\n tests()\n"
] | [
[
"pandas.ExcelWriter"
]
] |
yck011522/motion-planners | [
"8665bbfd6e502ebc25b68e8a34b58b459e65cfd2"
] | [
"motion_planners/trajectory/limits.py"
] | [
"import time\nimport numpy as np\n\nfrom .retime import EPSILON, get_max_velocity, poly_from_spline\nfrom ..utils import INF, elapsed_time\nfrom .retime import get_interval\n\ndef old_check_spline(spline, v_max=None, a_max=None, start_idx=None, end_idx=None):\n # TODO: be careful about time vs index (here is index)\n if (v_max is None) and (a_max is None):\n return True\n if start_idx is None:\n start_idx = 0\n if end_idx is None:\n end_idx = len(spline.x) - 1\n signs = [+1, -1]\n for i in range(start_idx, end_idx):\n t0, t1 = spline.x[i], spline.x[i + 1]\n t0, t1 = 0, (t1 - t0)\n boundary_ts = [t0, t1]\n for k in range(spline.c.shape[-1]):\n position_poly = poly_from_spline(spline, i, d=k)\n # print([position_poly(t) for t in boundary_ts])\n # print([spline(t)[k] for t in boundary_ts])\n\n if v_max is not None:\n vel_poly = position_poly.deriv(m=1)\n if any(abs(vel_poly(t)) > v_max[k] for t in boundary_ts):\n return False\n if any(not isinstance(r, complex) and (t0 <= r <= t1)\n for s in signs for r in (vel_poly + s * np.poly1d([v_max[k]])).roots):\n return False\n # a_max = None\n\n # TODO: reorder to check endpoints first\n if a_max is not None: # INF\n accel_poly = position_poly.deriv(m=2)\n # print([(accel_poly(t), a_max[k]) for t in boundary_ts])\n if any(abs(accel_poly(t)) > a_max[k] for t in boundary_ts):\n return False\n # print([accel_poly(r) for s in signs for r in (accel_poly + s*np.poly1d([a_max[k]])).roots\n # if isinstance(r, complex) and (t0 <= r <= t1)])\n if any(not isinstance(r, complex) and (t0 <= r <= t1)\n for s in signs for r in (accel_poly + s * np.poly1d([a_max[k]])).roots):\n return False\n return True\n\ndef check_spline(spline, v_max=None, a_max=None, verbose=False, **kwargs):\n if (v_max is None) and (a_max is None):\n return True\n # https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.PPoly.html#scipy.interpolate.PPoly\n # polys = [np.poly1d([spline.c[c, 0, k] for c in range(spline.c.shape[0])]) # Decreasing order\n # for k in range(spline.c.shape[-1])]\n # from numpy.polynomial.polynomial import Polynomial\n # polys = [Polynomial([spline.c[c, 0, k] for c in range(spline.c.shape[0])][-1]) # Increasing order\n # for k in range(spline.c.shape[-1])]\n\n # _, v = find_max_velocity(spline, ord=INF)\n # _, a = find_max_acceleration(spline, ord=INF)\n # print(v, v_max, a, a_max)\n # input()\n\n if v_max is not None:\n # TODO: maybe the pieces are screwing something\n t, v = find_max_velocity(spline, **kwargs)\n violation = abs(v) > get_max_velocity(v_max) + EPSILON\n if verbose: # or violation:\n print('Violation: {} | Max velocity: {:.3f}/{:.3f} (at time {:.3f})'.format(\n violation, v, get_max_velocity(v_max), t))\n if violation:\n return False\n return True\n # TODO: trusting continuous pieces to respect\n # TODO: solve for the intersection when not at a root\n # if a_max is not None:\n # t, a = find_max_acceleration(spline, **kwargs)\n # print('Max accel: {:.3f}/{:.3f} (at time {:.3f})'.format(a, get_max_velocity(a_max), t))\n # if abs(a) > get_max_velocity(a_max) + EPSILON:\n # print(t, a)\n # print(spline.x)\n # print(t in spline.x)\n # input()\n # return False\n # return True\n\n##################################################\n\ndef minimize_objective(objective, lower, upper, num=100, max_time=INF, max_iterations=100, verbose=False, **kwargs):\n # https://www.cvxpy.org/examples/basic/socp.html\n from scipy.optimize import minimize #, line_search, brute, basinhopping, minimize_scalar\n start_time = time.time()\n best_t, best_f = None, INF\n bounds = list(zip(lower, upper))\n assert num >= 1\n for iteration in range(num):\n if elapsed_time(start_time) >= max_time:\n break\n x0 = np.random.uniform(lower, upper)\n if max_iterations is None:\n t, f = x0, objective(x0)\n else:\n result = minimize(objective, x0=x0, bounds=bounds, # maxiter=max_iterations,\n **kwargs) # method=None, jac=None,\n t, f = result.x, result.fun\n if (best_t is None) or (f < best_f):\n best_t, best_f = t, f\n if verbose:\n print(iteration, x0, t, f) # objective(result.x)\n return best_t, best_f\n\ndef find_max_curve(curve, start_t=None, end_t=None, norm=INF, **kwargs):\n start_t, end_t = get_interval(curve, start_t=start_t, end_t=end_t)\n # TODO: curve(t) returns a matrix if passed a vector, which is summed by the INF norm\n objective = lambda t: -np.linalg.norm(curve(t[0]), ord=norm) # 2 | INF\n #objective = lambda t: -np.linalg.norm(curve(t[0]), norm=2)**2 # t[0]\n #accelerations_curve = positions_curve.derivative() # TODO: ValueError: failed in converting 7th argument `g' of _lbfgsb.setulb to C/Fortran array\n #grad = lambda t: np.array([-2*sum(accelerations_curve(t))])\n #result = minimize_scalar(objective, method='bounded', bounds=(start_t, end_t)) #, options={'disp': False})\n\n #print(max(-objective(t) for t in curve.x))\n best_t, best_f = minimize_objective(objective, lower=[start_t], upper=[end_t], **kwargs)\n #best_f = objective(best_t)\n best_t, best_f = best_t[0], -best_f\n return best_t, best_f\n\n##################################################\n\ndef maximize_curve(curve, start_t=None, end_t=None, discontinuity=True, ignore=set()): # fn=None\n start_t, end_t = get_interval(curve, start_t=start_t, end_t=end_t)\n #d = curve(start_t)\n derivative = curve.derivative(nu=1)\n times = list(curve.x)\n roots = derivative.roots(discontinuity=discontinuity)\n for r in roots:\n if r.shape:\n times.extend(r)\n else:\n times.append(r)\n times = sorted(t for t in times if not np.isnan(t)\n and (start_t <= t <= end_t) and (t not in ignore)) # TODO: filter repeated\n #fn = lambda t: max(np.absolute(curve(t)))\n fn = lambda t: np.linalg.norm(curve(t), ord=INF) if curve(t).shape else float(curve(t))\n #fn = max\n max_t = max(times, key=fn)\n return max_t, fn(max_t)\n\ndef exceeds_curve(curve, threshold, start_t=None, end_t=None, **kwargs):\n # TODO: joint limits\n # TODO: solve for the intersection with threshold\n max_t, max_v = maximize_curve(curve, start_t=start_t, end_t=end_t, **kwargs)\n if np.greater(max_v, threshold):\n return max_t\n return True\n\n##################################################\n\ndef find_max_velocity(positions_curve, analytical=True, **kwargs):\n velocities_curve = positions_curve.derivative(nu=1)\n if analytical:\n return maximize_curve(velocities_curve)\n else:\n return find_max_curve(velocities_curve, **kwargs)\n\n\ndef find_max_acceleration(positions_curve, **kwargs):\n # TODO: should only ever be quadratic\n accelerations_curve = positions_curve.derivative(nu=2)\n #return find_max_curve(accelerations_curve, max_iterations=None, **kwargs)\n return maximize_curve(accelerations_curve, discontinuity=True,)\n #ignore=set(positions_curve.x))\n\ndef analyze_continuity(curve, epsilon=1e-9, **kwargs):\n # TODO: explicitly check the adjacent curves\n start_t, end_t = get_interval(curve, **kwargs)\n max_t, max_error = start_t, 0.\n for i in range(1, len(curve.x)-1):\n t = curve.x[i]\n if not start_t <= t <= end_t:\n continue\n t1 = t - epsilon # TODO: check i-1\n t2 = t + epsilon # TODO: check i+1\n v1 = curve(t1)\n v2 = curve(t2)\n error = np.linalg.norm(v2 - v1, ord=INF)\n if error > max_error:\n max_t, max_error = t, error\n return max_t, max_error\n"
] | [
[
"numpy.poly1d",
"numpy.greater",
"numpy.isnan",
"numpy.linalg.norm",
"scipy.optimize.minimize",
"numpy.random.uniform"
]
] |
bthtsang/DeepClassifierNoveltyDetection | [
"cb12d5ef3064f878ff0db9d68413ad13b86538d8"
] | [
"classify_noveltydetect.py"
] | [
"import numpy as np\nimport keras.backend as K\nimport os\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\nimport joblib\nfrom light_curve import LightCurve # For using Naul's LightCurve class\nfrom keras.preprocessing.sequence import pad_sequences\nfrom sklearn.model_selection import StratifiedKFold\nfrom survey_rnngmm_classifier import main as survey_autoencoder\nfrom survey_rnngmm_classifier import preprocess, energy_loss\nfrom keras.models import Model\nfrom keras_util import parse_model_args, get_run_id\n\n# For one-hot vector conversion\nfrom sklearn.preprocessing import LabelEncoder\nfrom keras.utils import np_utils\n\n### For GMM training\nfrom gmm import GMM\nfrom autoencoder import extract_features\nfrom estimation_net import EstimationNet\nfrom keras.layers import Input, Lambda\nfrom keras.optimizers import Adam\nimport keras_util as ku\n\n### For novelty detection scores\nfrom sklearn.metrics import precision_recall_fscore_support\n\n### For RF classifier\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.ensemble import RandomForestClassifier\n\n# For generating confusion matrix\nimport itertools\nfrom sklearn.metrics import confusion_matrix\nimport seaborn as sns\nsns.set_context('paper', font_scale=1.6)\n\nSEED = 0\n\ndef plot_confusion_matrix(y, y_pred, classnames, filename=None):\n classnames = sorted(classnames)\n sns.set_style(\"whitegrid\", {'axes.grid' : False})\n cm = confusion_matrix(y, y_pred, classnames)\n valid_num = np.trace(cm)\n total_num = np.sum(cm)\n print (\"Validation Accuracy\", valid_num/total_num)\n cm = cm.astype('float') / cm.sum(axis=1)[:,np.newaxis]\n plt.imshow(cm, interpolation='nearest', cmap=plt.cm.Blues, vmin=0,\n vmax=1.0)\n plt.colorbar()\n tick_marks = np.arange(len(classnames))\n plt.xticks(tick_marks, classnames, rotation=45)\n plt.yticks(tick_marks, classnames)\n\n thresh = cm.max() / 2.\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n plt.text(j, i, \"{0:.2f}\".format(cm[i, j]),\n horizontalalignment=\"center\",\n color=\"white\" if cm[i, j] > thresh else \"black\",\n fontsize=9)\n\n plt.tight_layout()\n plt.ylabel('True label')\n plt.xlabel('Predicted label');\n if filename:\n plt.savefig(filename)\n plt.clf()\n plt.cla()\n plt.close()\n return [valid_num, total_num]\n\ndef main(args=None):\n args = parse_model_args(args)\n\n K.set_floatx('float64')\n\n run = get_run_id(**vars(args))\n log_dir = os.path.join(os.getcwd(), 'keras_logs', args.sim_type, run)\n weights_path = os.path.join(log_dir, 'weights.h5')\n\n if not os.path.exists(weights_path):\n raise FileNotFoundError(weights_path)\n\n X_fold, X_raw_fold, model, means, scales, wrong_units, args = survey_autoencoder(vars(args))\n\n print (\"log_dir\", log_dir)\n print(\"Weight matrix read...\")\n\n full = joblib.load(args.survey_files[0])\n\n # Combine subclasses\n # Resulting in five classes: RR, EC, SR, M, ROT\n for lc in full:\n if ((lc.label == 'EW') or (lc.label == 'EA') or (lc.label == 'EB')):\n lc.label = 'ECL'\n if ((lc.label == 'CWA') or (lc.label == 'CWB') or (lc.label == 'DCEP') or\n (lc.label == 'DCEPS') or (lc.label == 'RVA')):\n lc.label = \"CEPH\"\n if ((lc.label == 'DSCT') or (lc.label == 'HADS')):\n lc.label = \"DSCT\"\n if ((lc.label == 'RRD') or (lc.label == 'RRC')):\n lc.label = \"RRCD\"\n top_classes = ['SR', 'RRAB', 'RRCD', 'M', 'ROT', 'ECL', 'CEPH', 'DSCT']\n new_classes = ['VAR']\n\n top = [lc for lc in full if lc.label in top_classes]\n new = [lc for lc in full if lc.label in new_classes]\n\n # Preparation for classification probability\n classprob_pkl = joblib.load(\"./data/asassn/class_probs.pkl\")\n class_probability = dict(classprob_pkl)\n\n if args.ss_resid:\n top = [lc for lc in top if lc.ss_resid <= args.ss_resid]\n\n if args.class_prob:\n top = [lc for lc in top if float(class_probability[lc.name.split(\"/\")[-1][2:-4]]) >= 0.9]\n #top = [lc for lc in top if lc.class_prob >= args.class_prob]\n\n split = [el for lc in top for el in lc.split(args.n_min, args.n_max)]\n split_new = [el for lc in new for el in lc.split(args.n_min, args.n_max)]\n\n if args.period_fold:\n for lc in split:\n lc.period_fold()\n for lc in split_new:\n if lc.p is not None:\n lc.period_fold()\n \n X_list = [np.c_[lc.times, lc.measurements, lc.errors] for lc in split]\n classnames, indices = np.unique([lc.label for lc in split], return_inverse=True)\n y = classnames[indices]\n periods = np.array([np.log10(lc.p) for lc in split])\n periods = periods.reshape(len(split), 1)\n\n X_raw = pad_sequences(X_list, value=0., dtype='float64', padding='post')\n X, means, scales, wrong_units, X_err = preprocess(X_raw, args.m_max)\n y = y[~wrong_units]\n periods = periods[~wrong_units]\n\n train, valid = list(StratifiedKFold(n_splits=5, shuffle=True, random_state=SEED).split(X, y))[0]\n\n X_train = X[train]\n y_train = y[train]\n means_train = means[train]\n scales_train = scales[train]\n periods_train = periods[train]\n energy_dummy = np.zeros((X_train.shape[0], 1))\n\n X_valid = X[valid]\n y_valid = y[valid]\n means_valid = means[valid]\n scales_valid = scales[valid]\n periods_valid = periods[valid]\n energy_dummy_valid = np.zeros((X_valid.shape[0], 1))\n\n supports_train = np.concatenate((means_train, scales_train, periods_train), axis=1)\n supports_valid = np.concatenate((means_valid, scales_valid, periods_valid), axis=1)\n\n # New class data (VAR type)\n X_list_new = [np.c_[lc.times, lc.measurements, lc.errors] for lc in split_new]\n classnames_new, indices_new = np.unique([lc.label for lc in split_new], return_inverse=True)\n y_new = classnames_new[indices_new]\n periods_new = np.array([np.log10(lc.p) if lc.p is not None else 99.0 for lc in split_new])\n periods_new = periods_new.reshape(len(split_new), 1)\n\n X_raw_new = pad_sequences(X_list_new, value=0., dtype='float64', padding='post')\n X_new, means_new, scales_new, wrong_units_new, X_err_new = preprocess(X_raw_new, args.m_max)\n y_new = y_new[~wrong_units_new]\n periods_new = periods_new[~wrong_units_new]\n supports_new = np.concatenate((means_new, scales_new, periods_new), axis=1)\n\n ### Concatenating validation data and data from new classes for testing novelty detection\n y_new = np.concatenate((y_valid, y_new), axis=0)\n X_new = np.concatenate((X_valid, X_new), axis=0)\n supports_new = np.concatenate((supports_valid, supports_new), axis=0)\n\n num_supports_train = supports_train.shape[-1]\n num_supports_valid = supports_valid.shape[-1]\n assert(num_supports_train == num_supports_valid)\n num_additional = num_supports_train + 2 # 2 for reconstruction error\n\n ### flagging novel samples as 1, samples in superclasses 0.\n true_flags = np.array([1 if (l not in top_classes) else 0 for l in y_new])\n\n ### Making one-hot labels\n label_encoder1 = LabelEncoder()\n label_encoder1.fit(y_train)\n train_y_encoded = label_encoder1.transform(y_train)\n train_y = np_utils.to_categorical(train_y_encoded)\n\n label_encoder2 = LabelEncoder()\n label_encoder2.fit(y_valid)\n valid_y_encoded = label_encoder2.transform(y_valid)\n valid_y = np_utils.to_categorical(valid_y_encoded)\n\n label_encoder3 = LabelEncoder()\n label_encoder3.fit(y_new)\n new_y_encoded = label_encoder3.transform(y_new)\n new_y = np_utils.to_categorical(new_y_encoded)\n\n\n ### Loading trained autoencoder network\n encode_model = Model(inputs=model.input, outputs=model.get_layer('encoding').output)\n decode_model = Model(inputs=model.input, outputs=model.get_layer('time_dist').output)\n\n X_train = np.float64(X_train)\n X_valid = np.float64(X_valid)\n X_new = np.float64(X_new)\n\n # Passing samples through trained layers\n encoding_train = encode_model.predict({'main_input': X_train, 'aux_input': np.delete(X_train, 1, axis=2), 'support_input':supports_train})\n encoding_valid = encode_model.predict({'main_input': X_valid, 'aux_input': np.delete(X_valid, 1, axis=2), 'support_input':supports_valid})\n encoding_new = encode_model.predict({'main_input': X_new, 'aux_input': np.delete(X_new, 1, axis=2), 'support_input':supports_new})\n\n decoding_train = decode_model.predict({'main_input': X_train, 'aux_input': np.delete(X_train, 1, axis=2), 'support_input':supports_train})\n decoding_valid = decode_model.predict({'main_input': X_valid, 'aux_input': np.delete(X_valid, 1, axis=2), 'support_input':supports_valid})\n decoding_new = decode_model.predict({'main_input': X_new, 'aux_input': np.delete(X_new, 1, axis=2), 'support_input':supports_new})\n\n z_both_train = extract_features([X_train[:,:,1], decoding_train[:,:,0], encoding_train, supports_train])\n z_both_valid = extract_features([X_valid[:,:,1], decoding_valid[:,:,0], encoding_valid, supports_valid])\n z_both_new = extract_features([X_new[:,:,1], decoding_new[:,:,0], encoding_new, supports_new])\n\n z_both_train = K.eval(z_both_train)\n z_both_valid = K.eval(z_both_valid)\n z_both_new = K.eval(z_both_new)\n\n # Retrieve estimation network if gmm is on\n if (args.gmm_on):\n estnet_model = Model(inputs=model.input, outputs=model.get_layer('gamma').output)\n gamma_train = estnet_model.predict({'main_input': X_train, 'aux_input': np.delete(X_train, 1, axis=2), 'support_input':supports_train})\n gamma_valid = estnet_model.predict({'main_input': X_valid, 'aux_input': np.delete(X_valid, 1, axis=2), 'support_input':supports_valid})\n else:\n est_net = EstimationNet(args.estnet_size, args.num_classes, K.tanh)\n\n # Fit data to gmm if joint, train gmm if sequential\n gmm = GMM(args.num_classes, args.embedding+num_additional)\n gmm_init = gmm.init_gmm_variables()\n\n # If sequential training, create and train the estimation net\n if (not args.gmm_on):\n z_input = Input(shape=(args.embedding+num_additional,), name='z_input')\n gamma = est_net.inference(z_input, args.estnet_drop_frac)\n\n sigma_i = Lambda(lambda x: gmm.fit(x[0], x[1]),\n output_shape=(args.num_classes, args.embedding+num_additional, args.embedding+num_additional),\n name=\"sigma_i\")([z_input, gamma])\n\n energy = Lambda(lambda x: gmm.energy(x[0], x[1]), name=\"energy\")([z_input, sigma_i])\n\n # Setting up the GMM model\n model_output = [gamma, energy]\n model = Model(z_input, model_output)\n\n optimizer = Adam(lr=args.lr if not args.finetune_rate else args.finetune_rate)\n model.compile(optimizer=optimizer,\n loss=['categorical_crossentropy', energy_loss],\n metrics={'gamma':'accuracy'},\n loss_weights=[1.0, args.lambda1])\n\n # Controlling outputs\n estnet_size = args.estnet_size\n estsize = \"_\".join(str(s) for s in estnet_size)\n gmm_run = 'estnet{}_estdrop{}_l1{}'.format(estsize, int(100*args.estnet_drop_frac), args.lambda1)\n gmm_dir = os.path.join(os.getcwd(), 'keras_logs', args.sim_type, run, gmm_run)\n if (not os.path.isdir(gmm_dir)):\n os.makedirs(gmm_dir)\n\n # For classifier training only\n args.nb_epoch = args.cls_epoch\n\n history = ku.train_and_log(z_both_train, {'gamma':train_y, 'energy':energy_dummy},\n gmm_dir, model,\n validation_data=(z_both_valid,\n {'gamma':valid_y, 'energy':energy_dummy_valid},\n {'gamma':None, 'energy':None}), **vars(args))\n\n gamma_train, energy_train = model.predict(z_both_train)\n gamma_valid, energy_valid = model.predict(z_both_valid)\n\n if (not args.gmm_on):\n log_dir = gmm_dir\n\n plot_dir = os.path.join(log_dir, 'figures/')\n if (not os.path.isdir(plot_dir)):\n os.makedirs(plot_dir)\n\n # Converting to Keras variables to use Keras.backend functions\n z_both_train_K = K.variable(z_both_train)\n gamma_train_K = K.variable(gamma_train)\n\n z_both_valid_K = K.variable(z_both_valid)\n gamma_valid_K = K.variable(gamma_valid)\n\n z_both_new_K = K.variable(z_both_new)\n\n # Fitting GMM parameters only with training set\n sigma_i_train = gmm.fit(z_both_train_K, gamma_train_K)\n sigma_i_dummy = 1.0\n assert (gmm.fitted == True)\n\n # Energy calculation\n energy_train = K.eval(gmm.energy(z_both_train_K, sigma_i_train))[:, 0]\n energy_valid = K.eval(gmm.energy(z_both_valid_K, sigma_i_dummy))[:, 0]\n energy_new = K.eval(gmm.energy(z_both_new_K, sigma_i_dummy))[:, 0]\n\n energy_known = [e for i, e in enumerate(energy_new) if (true_flags[i] == 0)]\n energy_unknown = [e for i, e in enumerate(energy_new) if (true_flags[i] == 1)]\n print (\"known/unknown\", len(energy_known), len(energy_unknown))\n\n gmm_phi = K.eval(gmm.phi)\n gmm_mu = K.eval(gmm.mu)\n gmm_sigma = K.eval(gmm.sigma)\n\n np.savez(log_dir+'/gmm_parameters.npz', gmm_phi=gmm_phi, gmm_mu=gmm_mu, gmm_sigma=gmm_sigma)\n\n percentile_list = [80.0, 95.0]\n\n txtfilename = log_dir + \"/novel_detection_scores.txt\"\n txtfile = open(txtfilename, 'w')\n\n for per in percentile_list:\n new_class_energy_threshold = np.percentile(energy_train, per)\n print (f\"Energy threshold to detect new class: {new_class_energy_threshold:.2f}\")\n\n new_pred_flag = np.where(energy_new >= new_class_energy_threshold, 1, 0)\n\n prec, recall, fscore, _ = precision_recall_fscore_support(true_flags, new_pred_flag, average=\"binary\")\n \n print (f\"Detecting new using {per:.1f}% percentile\")\n print(f\" Precision = {prec:.3f}\")\n print(f\" Recall = {recall:.3f}\")\n print(f\" F1-Score = {fscore:.3f}\")\n\n txtfile.write(f\"Detecting new using {per:.1f}% percentile \\n\")\n txtfile.write(f\" Precision = {prec:.3f}\\n\")\n txtfile.write(f\" Recall = {recall:.3f}\\n\")\n txtfile.write(f\" F1-Score = {fscore:.3f}\\n\")\n txtfile.close() \n \n\n ### Make plots of energy\n nbin = 100\n fig = plt.figure()\n ax = fig.add_subplot(111)\n plt.hist(energy_train, nbin, normed=True, color='black',\n histtype='step', label='Training Set')\n plt.hist(np.isfinite(energy_unknown), nbin, normed=True, color='blue',\n histtype='step', label='Unknown Classes')\n plt.hist(energy_known, nbin, normed=True, color='green',\n histtype='step', label='Known Classes')\n plt.legend()\n plt.xlabel(r\"Energy E(z)\")\n plt.ylabel(\"Probability\")\n plt.savefig(plot_dir+'energy_histogram.pdf', dpi=300,\n bbox_inches='tight')\n plt.clf()\n plt.cla()\n plt.close()\n\n\n ### Generate confusion matrix\n le_list = list(label_encoder2.classes_)\n predicted_onehot = gamma_valid \n predicted_labels = [le_list[np.argmax(onehot, axis=None, out=None)] for onehot in predicted_onehot]\n\n corr_num, tot_num = plot_confusion_matrix(y_valid, predicted_labels, classnames,\n plot_dir+'asassn_nn_confusion.pdf')\n nn_acc = corr_num / tot_num\n\n ### Generate confusion matrix for RF\n RF_PARAM_GRID = {'n_estimators': [50, 100, 250], 'criterion': ['gini', 'entropy'],\n 'max_features': [0.05, 0.1, 0.2, 0.3], 'min_samples_leaf': [1, 2, 3]}\n rf_model = GridSearchCV(RandomForestClassifier(random_state=0), RF_PARAM_GRID)\n rf_model.fit(encoding_train, y[train])\n\n rf_train_acc = 100 * rf_model.score(encoding_train, y[train])\n rf_valid_acc = 100 * rf_model.score(encoding_valid, y[valid])\n\n plot_confusion_matrix(y[valid], rf_model.predict(encoding_valid), classnames,\n plot_dir+'asassn_rf_confusion.pdf')\n\n ### Text output\n txtfilename = log_dir + \"/classification_accuracy.txt\"\n txtfile = open(txtfilename, 'w')\n\n ### Writing results\n txtfile.write(\"===== Classification Accuracy =====\\n\")\n txtfile.write(f\"Neural Network Classifier: {nn_acc:.2f}\\n\")\n txtfile.write(\"==========================\\n\")\n txtfile.write(\"Random Forest Classifier\\n\")\n txtfile.write(f\"Training accuracy: {rf_train_acc:2.2f}%\\n\")\n txtfile.write(f\"Validation accuracy: {rf_valid_acc:2.2f}%\\n\")\n txtfile.write(f\"Best RF {rf_model.best_params_}\\n\")\n txtfile.write(\"==========================\\n\")\n txtfile.close()\n\n\nif __name__ == '__main__':\n args = main()\n"
] | [
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.imshow",
"numpy.savez",
"sklearn.metrics.confusion_matrix",
"numpy.concatenate",
"sklearn.metrics.precision_recall_fscore_support",
"sklearn.preprocessing.LabelEncoder",
"numpy.where",
"numpy.trace",
"matplotlib.pyplot.tight_layout",
"sklearn.ensemble.RandomForestClassifier",
"numpy.unique",
"sklearn.model_selection.StratifiedKFold",
"numpy.argmax",
"matplotlib.pyplot.close",
"numpy.zeros",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.savefig",
"numpy.delete",
"numpy.log10",
"numpy.array",
"numpy.sum",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.hist",
"numpy.isfinite",
"matplotlib.use",
"matplotlib.pyplot.cla",
"numpy.percentile",
"matplotlib.pyplot.colorbar",
"matplotlib.pyplot.clf",
"numpy.float64",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.yticks"
]
] |
megvii-research/tlsc | [
"b6c7c927666dc3020e8f7d25a1342fc421cf50c8"
] | [
"setup.py"
] | [
"# ------------------------------------------------------------------------\n# Copyright (c) 2021 megvii-model. All Rights Reserved.\n# ------------------------------------------------------------------------\n# Modified from BasicSR (https://github.com/xinntao/BasicSR)\n# Copyright 2018-2020 BasicSR Authors\n# ------------------------------------------------------------------------\n#!/usr/bin/env python\n\nfrom setuptools import find_packages, setup\n\nimport os\nimport subprocess\nimport sys\nimport time\nimport torch\nfrom torch.utils.cpp_extension import (BuildExtension, CppExtension,\n CUDAExtension)\n\nversion_file = 'basicsr/version.py'\n\n\ndef readme():\n return ''\n # with open('README.md', encoding='utf-8') as f:\n # content = f.read()\n # return content\n\n\ndef get_git_hash():\n\n def _minimal_ext_cmd(cmd):\n # construct minimal environment\n env = {}\n for k in ['SYSTEMROOT', 'PATH', 'HOME']:\n v = os.environ.get(k)\n if v is not None:\n env[k] = v\n # LANGUAGE is used on win32\n env['LANGUAGE'] = 'C'\n env['LANG'] = 'C'\n env['LC_ALL'] = 'C'\n out = subprocess.Popen(\n cmd, stdout=subprocess.PIPE, env=env).communicate()[0]\n return out\n\n try:\n out = _minimal_ext_cmd(['git', 'rev-parse', 'HEAD'])\n sha = out.strip().decode('ascii')\n except OSError:\n sha = 'unknown'\n\n return sha\n\n\ndef get_hash():\n if os.path.exists('.git'):\n sha = get_git_hash()[:7]\n elif os.path.exists(version_file):\n try:\n from basicsr.version import __version__\n sha = __version__.split('+')[-1]\n except ImportError:\n raise ImportError('Unable to get git version')\n else:\n sha = 'unknown'\n\n return sha\n\n\ndef write_version_py():\n content = \"\"\"# GENERATED VERSION FILE\n# TIME: {}\n__version__ = '{}'\nshort_version = '{}'\nversion_info = ({})\n\"\"\"\n sha = get_hash()\n with open('VERSION', 'r') as f:\n SHORT_VERSION = f.read().strip()\n VERSION_INFO = ', '.join(\n [x if x.isdigit() else f'\"{x}\"' for x in SHORT_VERSION.split('.')])\n VERSION = SHORT_VERSION + '+' + sha\n\n version_file_str = content.format(time.asctime(), VERSION, SHORT_VERSION,\n VERSION_INFO)\n with open(version_file, 'w') as f:\n f.write(version_file_str)\n\n\ndef get_version():\n with open(version_file, 'r') as f:\n exec(compile(f.read(), version_file, 'exec'))\n return locals()['__version__']\n\n\ndef make_cuda_ext(name, module, sources, sources_cuda=None):\n if sources_cuda is None:\n sources_cuda = []\n define_macros = []\n extra_compile_args = {'cxx': []}\n\n if torch.cuda.is_available() or os.getenv('FORCE_CUDA', '0') == '1':\n define_macros += [('WITH_CUDA', None)]\n extension = CUDAExtension\n extra_compile_args['nvcc'] = [\n '-D__CUDA_NO_HALF_OPERATORS__',\n '-D__CUDA_NO_HALF_CONVERSIONS__',\n '-D__CUDA_NO_HALF2_OPERATORS__',\n ]\n sources += sources_cuda\n else:\n print(f'Compiling {name} without CUDA')\n extension = CppExtension\n\n return extension(\n name=f'{module}.{name}',\n sources=[os.path.join(*module.split('.'), p) for p in sources],\n define_macros=define_macros,\n extra_compile_args=extra_compile_args)\n\n\ndef get_requirements(filename='requirements.txt'):\n return []\n here = os.path.dirname(os.path.realpath(__file__))\n with open(os.path.join(here, filename), 'r') as f:\n requires = [line.replace('\\n', '') for line in f.readlines()]\n return requires\n\n\nif __name__ == '__main__':\n ext_modules = []\n # if '--no_cuda_ext' in sys.argv:\n # ext_modules = []\n # sys.argv.remove('--no_cuda_ext')\n # else:\n # ext_modules = [\n # make_cuda_ext(\n # name='deform_conv_ext',\n # module='basicsr.models.ops.dcn',\n # sources=['src/deform_conv_ext.cpp'],\n # sources_cuda=[\n # 'src/deform_conv_cuda.cpp',\n # 'src/deform_conv_cuda_kernel.cu'\n # ]),\n # make_cuda_ext(\n # name='fused_act_ext',\n # module='basicsr.models.ops.fused_act',\n # sources=['src/fused_bias_act.cpp'],\n # sources_cuda=['src/fused_bias_act_kernel.cu']),\n # make_cuda_ext(\n # name='upfirdn2d_ext',\n # module='basicsr.models.ops.upfirdn2d',\n # sources=['src/upfirdn2d.cpp'],\n # sources_cuda=['src/upfirdn2d_kernel.cu']),\n # ]\n\n write_version_py()\n setup(\n name='basicsr',\n version=get_version(),\n description='Open Source Image and Video Super-Resolution Toolbox',\n long_description=readme(),\n author='Xintao Wang',\n author_email='[email protected]',\n keywords='computer vision, restoration, super resolution',\n url='https://github.com/xinntao/BasicSR',\n packages=find_packages(\n exclude=('options', 'datasets', 'experiments', 'results',\n 'tb_logger', 'wandb')),\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'License :: OSI Approved :: Apache Software License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.7',\n 'Programming Language :: Python :: 3.8',\n ],\n license='Apache License 2.0',\n setup_requires=['cython', 'numpy'],\n install_requires=get_requirements(),\n ext_modules=ext_modules,\n cmdclass={'build_ext': BuildExtension},\n zip_safe=False)\n"
] | [
[
"torch.cuda.is_available"
]
] |
nightstorm0909/pEvoNAS | [
"293963f7dd9a46d93a5bf180719e4f7220a24ea6"
] | [
"s2/consensus.py"
] | [
"import torch\n\nclass consensus:\n def __init__(self, arch_flag, population, edge2index, op_dict, op_position, topk, weighted = False):\n self.arch_flag = arch_flag\n self.population = population\n self.pop_size = population.get_population_size()\n self.population.print_population_fitness()\n self.edge2index = edge2index\n self.op_dict = op_dict\n self.op_position = op_position\n self.topk = topk\n self.weighted = weighted\n self.vote_dict = {}\n \n self.edge2index2 = {value:key for key, value in self.edge2index.items()}\n \n def vote(self, individual, ind_id, verbose=False):\n arch_param = individual.get_arch_parameters()[0].cpu()\n arch_values, indices = torch.topk(arch_param, self.topk)\n if verbose: print(indices)\n for idx, row in enumerate(indices):\n edge = self.edge2index2[idx]\n ops = []\n for col in row: ops.append(self.op_position[edge][str(col.item())])\n ops.sort()\n op_str = ','.join(ops)\n if verbose: print(','.join(ops))\n if idx in self.vote_dict.keys():\n if op_str in self.vote_dict[idx].keys():\n if self.weighted: self.vote_dict[idx][op_str]+= -(ind_id/self.pop_size)\n else: self.vote_dict[idx][op_str]+= 1\n else:\n if self.weighted: self.vote_dict[idx][op_str] = -(ind_id/self.pop_size)\n else: self.vote_dict[idx][op_str] = 1\n else:\n if self.weighted: self.vote_dict[idx] = {op_str: -(ind_id/self.pop_size)}\n else: self.vote_dict[idx] = {op_str: 1}\n if verbose: print(self.vote_dict)\n \n def sort_vote_dict(self, verbose=False):\n sorted_vote_dict = {}\n for edge, ops_dict in self.vote_dict.items():\n sorted_vote_dict[edge] = dict(sorted(ops_dict.items(), key=lambda x: x[1], reverse=True))\n if verbose: print(sorted_vote_dict)\n return sorted_vote_dict\n \n def top_votes(self, verbose=False):\n top_votes = {}\n for edge, ops_dict in self.vote_dict.items():\n score = float('-inf')\n for ops, value in ops_dict.items():\n if value > score: ops_str, score = ops, value\n top_votes[edge] = (ops_str, score)\n if verbose: print(f'{top_votes[edge]}: {score}')\n return top_votes\n \n def shrink(self):\n for pop_id, individual in enumerate(self.population.get_population()): self.vote(individual, pop_id+1)\n #sorted_vote_dict = self.sort_vote_dict()\n top_votes_dict = self.top_votes()\n print(top_votes_dict)\n \n # Shrinking the search space\n new_arch_flag = torch.zeros_like(self.arch_flag)\n for edge in top_votes_dict.keys():\n for op in top_votes_dict[edge][0].split(','):\n new_arch_flag[edge][self.op_dict[op]] = True\n return new_arch_flag\n\n def shrink_by_one_ind(self, individual, verbose=False):\n if verbose: print(individual.arch_parameters)\n self.vote(individual, 1)\n top_votes_dict = self.top_votes()\n if verbose: print(top_votes_dict)\n \n # Shrinking the search space\n new_arch_flag = torch.zeros_like(self.arch_flag)\n for edge in top_votes_dict.keys():\n for op in top_votes_dict[edge][0].split(','):\n new_arch_flag[edge][self.op_dict[op]] = True\n return new_arch_flag\n\nclass consensus3:\n def __init__(self, arch_flag, population, edge2index, op_dict, op_position, topk, weighted = False):\n self.arch_flag = arch_flag\n self.population = population\n self.pop_size = population.get_population_size()\n self.population.print_population_fitness()\n self.edge2index = edge2index\n self.op_dict = op_dict\n self.op_position = op_position\n self.topk = topk\n self.weighted = weighted\n self.vote_dict = {}\n self.vote_value_dict = {}\n\n self.edge2index2 = {value:key for key, value in self.edge2index.items()}\n\n def get_vote_value(self, arch_str, ind_id):\n if arch_str in self.vote_value_dict:\n vote_value = self.vote_value_dict[arch_str]\n else:\n vote_value = -(ind_id/self.pop_size)\n self.vote_value_dict[arch_str] = vote_value\n return vote_value\n \n def vote(self, individual, ind_id, verbose=False):\n arch_param = individual.get_arch_parameters()[0].cpu()\n arch_str = individual.genotype\n arch_values, indices = torch.topk(arch_param, self.topk)\n if verbose: print(indices)\n for idx, row in enumerate(indices):\n edge = self.edge2index2[idx]\n ops = []\n for col in row:\n ops.append(self.op_position[edge][str(col.item())])\n ops.sort()\n op_str = ','.join(ops)\n if verbose: print(','.join(ops))\n if idx in self.vote_dict.keys():\n if op_str in self.vote_dict[idx].keys():\n if self.weighted: self.vote_dict[idx][op_str]+= self.get_vote_value(arch_str=arch_str, ind_id=ind_id)\n else: self.vote_dict[idx][op_str]+= 1\n else:\n if self.weighted: self.vote_dict[idx][op_str] = self.get_vote_value(arch_str=arch_str, ind_id=ind_id)\n else: self.vote_dict[idx][op_str] = 1\n else:\n if self.weighted: self.vote_dict[idx] = {op_str: self.get_vote_value(arch_str=arch_str, ind_id=ind_id)}\n else: self.vote_dict[idx] = {op_str: 1}\n if verbose: print(self.vote_dict)\n \n def sort_vote_dict(self, verbose=False):\n sorted_vote_dict = {}\n for edge, ops_dict in self.vote_dict.items():\n sorted_vote_dict[edge] = dict(sorted(ops_dict.items(), key=lambda x: x[1], reverse=True))\n if verbose: print(sorted_vote_dict)\n return sorted_vote_dict\n \n def top_votes(self, verbose=False):\n top_votes = {}\n for edge, ops_dict in self.vote_dict.items():\n score = float('-inf')\n for ops, value in ops_dict.items():\n if value > score: ops_str, score = ops, value\n top_votes[edge] = (ops_str, score)\n if verbose: print(f'{top_votes[edge]}: {score}')\n return top_votes\n \n def shrink(self, verbose=False):\n for pop_id, individual in enumerate(self.population.get_population()):\n self.vote(individual, pop_id+1)\n top_votes_dict = self.top_votes(verbose=verbose)\n if verbose: print(top_votes_dict)\n \n # Shrinking the search space\n new_arch_flag = torch.zeros_like(self.arch_flag)\n for edge in top_votes_dict.keys():\n for op in top_votes_dict[edge][0].split(','):\n new_arch_flag[edge][self.op_dict[op]] = True\n return new_arch_flag\n"
] | [
[
"torch.topk",
"torch.zeros_like"
]
] |
VietDunghacker/VarifocalNet | [
"f57917afb3c29ceba1d3c4f824d10b9cc53aaa40"
] | [
"mmdet/models/roi_heads/bbox_heads/bbox_head.py"
] | [
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom mmcv.runner import auto_fp16, force_fp32\nfrom torch.nn.modules.utils import _pair\n\nfrom mmdet.core import build_bbox_coder, multi_apply, multiclass_nms\nfrom mmdet.models.builder import HEADS, build_loss\nfrom mmdet.models.losses import accuracy\n\n\[email protected]_module()\nclass BBoxHead(nn.Module):\n\t\"\"\"Simplest RoI head, with only two fc layers for classification and\n\tregression respectively.\"\"\"\n\n\tdef __init__(self,\n\t\t\t\t with_avg_pool=False,\n\t\t\t\t with_cls=True,\n\t\t\t\t with_reg=True,\n\t\t\t\t roi_feat_size=7,\n\t\t\t\t in_channels=256,\n\t\t\t\t num_classes=80,\n\t\t\t\t bbox_coder=dict(\n\t\t\t\t\t type='DeltaXYWHBBoxCoder',\n\t\t\t\t\t clip_border=True,\n\t\t\t\t\t target_means=[0., 0., 0., 0.],\n\t\t\t\t\t target_stds=[0.1, 0.1, 0.2, 0.2]),\n\t\t\t\t reg_class_agnostic=False,\n\t\t\t\t reg_decoded_bbox=False,\n\t\t\t\t loss_cls=dict(\n\t\t\t\t\t type='CrossEntropyLoss',\n\t\t\t\t\t use_sigmoid=False,\n\t\t\t\t\t loss_weight=1.0),\n\t\t\t\t loss_bbox=dict(\n\t\t\t\t\t type='SmoothL1Loss', beta=1.0, loss_weight=1.0)):\n\t\tsuper(BBoxHead, self).__init__()\n\t\tassert with_cls or with_reg\n\t\tself.with_avg_pool = with_avg_pool\n\t\tself.with_cls = with_cls\n\t\tself.with_reg = with_reg\n\t\tself.roi_feat_size = _pair(roi_feat_size)\n\t\tself.roi_feat_area = self.roi_feat_size[0] * self.roi_feat_size[1]\n\t\tself.in_channels = in_channels\n\t\tself.num_classes = num_classes\n\t\tself.reg_class_agnostic = reg_class_agnostic\n\t\tself.reg_decoded_bbox = reg_decoded_bbox\n\t\tself.fp16_enabled = False\n\n\t\tself.bbox_coder = build_bbox_coder(bbox_coder)\n\t\tself.loss_cls = build_loss(loss_cls)\n\t\tself.loss_bbox = build_loss(loss_bbox)\n\n\t\tin_channels = self.in_channels\n\t\tif self.with_avg_pool:\n\t\t\tself.avg_pool = nn.AvgPool2d(self.roi_feat_size)\n\t\telse:\n\t\t\tin_channels *= self.roi_feat_area\n\t\tif self.with_cls:\n\t\t\t# need to add background class\n\t\t\tself.fc_cls = nn.Linear(in_channels, num_classes + 1)\n\t\tif self.with_reg:\n\t\t\tout_dim_reg = 4 if reg_class_agnostic else 4 * num_classes\n\t\t\tself.fc_reg = nn.Linear(in_channels, out_dim_reg)\n\t\tself.debug_imgs = None\n\n\tdef init_weights(self):\n\t\t# conv layers are already initialized by ConvModule\n\t\tif self.with_cls:\n\t\t\tnn.init.normal_(self.fc_cls.weight, 0, 0.01)\n\t\t\tnn.init.constant_(self.fc_cls.bias, 0)\n\t\tif self.with_reg:\n\t\t\tnn.init.normal_(self.fc_reg.weight, 0, 0.001)\n\t\t\tnn.init.constant_(self.fc_reg.bias, 0)\n\n\t@auto_fp16()\n\tdef forward(self, x):\n\t\tif self.with_avg_pool:\n\t\t\tx = self.avg_pool(x)\n\t\tx = x.view(x.size(0), -1)\n\t\tcls_score = self.fc_cls(x) if self.with_cls else None\n\t\tbbox_pred = self.fc_reg(x) if self.with_reg else None\n\t\treturn cls_score, bbox_pred\n\n\tdef _get_target_single(self, pos_bboxes, neg_bboxes, pos_gt_bboxes,\n\t\t\t\t\t\t pos_gt_labels, cfg):\n\t\t\"\"\"Calculate the ground truth for proposals in the single image\n\t\taccording to the sampling results.\n\t\tArgs:\n\t\t\tpos_bboxes (Tensor): Contains all the positive boxes,\n\t\t\t\thas shape (num_pos, 4), the last dimension 4\n\t\t\t\trepresents [tl_x, tl_y, br_x, br_y].\n\t\t\tneg_bboxes (Tensor): Contains all the negative boxes,\n\t\t\t\thas shape (num_neg, 4), the last dimension 4\n\t\t\t\trepresents [tl_x, tl_y, br_x, br_y].\n\t\t\tpos_gt_bboxes (Tensor): Contains all the gt_boxes,\n\t\t\t\thas shape (num_gt, 4), the last dimension 4\n\t\t\t\trepresents [tl_x, tl_y, br_x, br_y].\n\t\t\tpos_gt_labels (Tensor): Contains all the gt_labels,\n\t\t\t\thas shape (num_gt).\n\t\t\tcfg (obj:`ConfigDict`): `train_cfg` of R-CNN.\n\t\tReturns:\n\t\t\tTuple[Tensor]: Ground truth for proposals\n\t\t\tin a single image. Containing the following Tensors:\n\t\t\t\t- labels(Tensor): Gt_labels for all proposals, has\n\t\t\t\t shape (num_proposals,).\n\t\t\t\t- label_weights(Tensor): Labels_weights for all\n\t\t\t\t proposals, has shape (num_proposals,).\n\t\t\t\t- bbox_targets(Tensor):Regression target for all\n\t\t\t\t proposals, has shape (num_proposals, 4), the\n\t\t\t\t last dimension 4 represents [tl_x, tl_y, br_x, br_y].\n\t\t\t\t- bbox_weights(Tensor):Regression weights for all\n\t\t\t\t proposals, has shape (num_proposals, 4).\n\t\t\"\"\"\n\t\tnum_pos = pos_bboxes.size(0)\n\t\tnum_neg = neg_bboxes.size(0)\n\t\tnum_samples = num_pos + num_neg\n\n\t\t# original implementation uses new_zeros since BG are set to be 0\n\t\t# now use empty & fill because BG cat_id = num_classes,\n\t\t# FG cat_id = [0, num_classes-1]\n\t\tlabels = pos_bboxes.new_full((num_samples, ),\n\t\t\t\t\t\t\t\t\t self.num_classes,\n\t\t\t\t\t\t\t\t\t dtype=torch.long)\n\t\tlabel_weights = pos_bboxes.new_zeros(num_samples)\n\t\tbbox_targets = pos_bboxes.new_zeros(num_samples, 4)\n\t\tbbox_weights = pos_bboxes.new_zeros(num_samples, 4)\n\t\tif num_pos > 0:\n\t\t\tlabels[:num_pos] = pos_gt_labels\n\t\t\tpos_weight = 1.0 if cfg.pos_weight <= 0 else cfg.pos_weight\n\t\t\tlabel_weights[:num_pos] = pos_weight\n\t\t\tif not self.reg_decoded_bbox:\n\t\t\t\tpos_bbox_targets = self.bbox_coder.encode(\n\t\t\t\t\tpos_bboxes, pos_gt_bboxes)\n\t\t\telse:\n\t\t\t\t# When the regression loss (e.g. `IouLoss`, `GIouLoss`)\n\t\t\t\t# is applied directly on the decoded bounding boxes, both\n\t\t\t\t# the predicted boxes and regression targets should be with\n\t\t\t\t# absolute coordinate format.\n\t\t\t\tpos_bbox_targets = pos_gt_bboxes\n\t\t\tbbox_targets[:num_pos, :] = pos_bbox_targets\n\t\t\tbbox_weights[:num_pos, :] = 1\n\t\tif num_neg > 0:\n\t\t\tlabel_weights[-num_neg:] = 1.0\n\n\t\treturn labels, label_weights, bbox_targets, bbox_weights\n\n\tdef get_targets(self,\n\t\t\t\t\tsampling_results,\n\t\t\t\t\tgt_bboxes,\n\t\t\t\t\tgt_labels,\n\t\t\t\t\trcnn_train_cfg,\n\t\t\t\t\tconcat=True):\n\t\t\"\"\"Calculate the ground truth for all samples in a batch according to\n\t\tthe sampling_results.\n\t\tAlmost the same as the implementation in bbox_head, we passed\n\t\tadditional parameters pos_inds_list and neg_inds_list to\n\t\t`_get_target_single` function.\n\t\tArgs:\n\t\t\tsampling_results (List[obj:SamplingResults]): Assign results of\n\t\t\t\tall images in a batch after sampling.\n\t\t\tgt_bboxes (list[Tensor]): Gt_bboxes of all images in a batch,\n\t\t\t\teach tensor has shape (num_gt, 4), the last dimension 4\n\t\t\t\trepresents [tl_x, tl_y, br_x, br_y].\n\t\t\tgt_labels (list[Tensor]): Gt_labels of all images in a batch,\n\t\t\t\teach tensor has shape (num_gt,).\n\t\t\trcnn_train_cfg (obj:ConfigDict): `train_cfg` of RCNN.\n\t\t\tconcat (bool): Whether to concatenate the results of all\n\t\t\t\tthe images in a single batch.\n\t\tReturns:\n\t\t\tTuple[Tensor]: Ground truth for proposals in a single image.\n\t\t\tContaining the following list of Tensors:\n\t\t\t\t- labels (list[Tensor],Tensor): Gt_labels for all\n\t\t\t\t proposals in a batch, each tensor in list has\n\t\t\t\t shape (num_proposals,) when `concat=False`, otherwise\n\t\t\t\t just a single tensor has shape (num_all_proposals,).\n\t\t\t\t- label_weights (list[Tensor]): Labels_weights for\n\t\t\t\t all proposals in a batch, each tensor in list has\n\t\t\t\t shape (num_proposals,) when `concat=False`, otherwise\n\t\t\t\t just a single tensor has shape (num_all_proposals,).\n\t\t\t\t- bbox_targets (list[Tensor],Tensor): Regression target\n\t\t\t\t for all proposals in a batch, each tensor in list\n\t\t\t\t has shape (num_proposals, 4) when `concat=False`,\n\t\t\t\t otherwise just a single tensor has shape\n\t\t\t\t (num_all_proposals, 4), the last dimension 4 represents\n\t\t\t\t [tl_x, tl_y, br_x, br_y].\n\t\t\t\t- bbox_weights (list[tensor],Tensor): Regression weights for\n\t\t\t\t all proposals in a batch, each tensor in list has shape\n\t\t\t\t (num_proposals, 4) when `concat=False`, otherwise just a\n\t\t\t\t single tensor has shape (num_all_proposals, 4).\n\t\t\"\"\"\n\t\tpos_bboxes_list = [res.pos_bboxes for res in sampling_results]\n\t\tneg_bboxes_list = [res.neg_bboxes for res in sampling_results]\n\t\tpos_gt_bboxes_list = [res.pos_gt_bboxes for res in sampling_results]\n\t\tpos_gt_labels_list = [res.pos_gt_labels for res in sampling_results]\n\t\tlabels, label_weights, bbox_targets, bbox_weights = multi_apply(\n\t\t\tself._get_target_single,\n\t\t\tpos_bboxes_list,\n\t\t\tneg_bboxes_list,\n\t\t\tpos_gt_bboxes_list,\n\t\t\tpos_gt_labels_list,\n\t\t\tcfg=rcnn_train_cfg)\n\n\t\tif concat:\n\t\t\tlabels = torch.cat(labels, 0)\n\t\t\tlabel_weights = torch.cat(label_weights, 0)\n\t\t\tbbox_targets = torch.cat(bbox_targets, 0)\n\t\t\tbbox_weights = torch.cat(bbox_weights, 0)\n\t\treturn labels, label_weights, bbox_targets, bbox_weights\n\n\t@force_fp32(apply_to=('cls_score', 'bbox_pred'))\n\tdef loss(self,\n\t\t\t cls_score,\n\t\t\t bbox_pred,\n\t\t\t rois,\n\t\t\t labels,\n\t\t\t label_weights,\n\t\t\t bbox_targets,\n\t\t\t bbox_weights,\n\t\t\t reduction_override=None):\n\t\tlosses = dict()\n\t\tif cls_score is not None:\n\t\t\tavg_factor = max(torch.sum(label_weights > 0).float().item(), 1.)\n\t\t\tif cls_score.numel() > 0:\n\t\t\t\tlosses['loss_cls'] = self.loss_cls(\n\t\t\t\t\tcls_score,\n\t\t\t\t\tlabels,\n\t\t\t\t\tlabel_weights,\n\t\t\t\t\tavg_factor=avg_factor,\n\t\t\t\t\treduction_override=reduction_override)\n\t\t\t\tlosses['acc'] = accuracy(cls_score, labels)\n\t\tif bbox_pred is not None:\n\t\t\tbg_class_ind = self.num_classes\n\t\t\t# 0~self.num_classes-1 are FG, self.num_classes is BG\n\t\t\tpos_inds = (labels >= 0) & (labels < bg_class_ind)\n\t\t\t# do not perform bounding box regression for BG anymore.\n\t\t\tif pos_inds.any():\n\t\t\t\tif self.reg_decoded_bbox:\n\t\t\t\t\t# When the regression loss (e.g. `IouLoss`,\n\t\t\t\t\t# `GIouLoss`, `DIouLoss`) is applied directly on\n\t\t\t\t\t# the decoded bounding boxes, it decodes the\n\t\t\t\t\t# already encoded coordinates to absolute format.\n\t\t\t\t\tbbox_pred = self.bbox_coder.decode(rois[:, 1:], bbox_pred)\n\t\t\t\tif self.reg_class_agnostic:\n\t\t\t\t\tpos_bbox_pred = bbox_pred.view(\n\t\t\t\t\t\tbbox_pred.size(0), 4)[pos_inds.type(torch.bool)]\n\t\t\t\telse:\n\t\t\t\t\tpos_bbox_pred = bbox_pred.view(\n\t\t\t\t\t\tbbox_pred.size(0), -1,\n\t\t\t\t\t\t4)[pos_inds.type(torch.bool),\n\t\t\t\t\t\t labels[pos_inds.type(torch.bool)]]\n\t\t\t\tlosses['loss_bbox'] = self.loss_bbox(\n\t\t\t\t\tpos_bbox_pred,\n\t\t\t\t\tbbox_targets[pos_inds.type(torch.bool)],\n\t\t\t\t\tbbox_weights[pos_inds.type(torch.bool)],\n\t\t\t\t\tavg_factor=bbox_targets.size(0),\n\t\t\t\t\treduction_override=reduction_override)\n\t\t\telse:\n\t\t\t\tlosses['loss_bbox'] = bbox_pred[pos_inds].sum()\n\t\treturn losses\n\n\t@force_fp32(apply_to=('cls_score', 'bbox_pred'))\n\tdef get_bboxes(self,\n\t\t\t\t rois,\n\t\t\t\t cls_score,\n\t\t\t\t bbox_pred,\n\t\t\t\t img_shape,\n\t\t\t\t scale_factor,\n\t\t\t\t rescale=False,\n\t\t\t\t cfg=None):\n\t\tif isinstance(cls_score, list):\n\t\t\tcls_score = sum(cls_score) / float(len(cls_score))\n\t\tscores = F.softmax(cls_score, dim=1) if cls_score is not None else None\n\n\t\tif bbox_pred is not None:\n\t\t\tbboxes = self.bbox_coder.decode(\n\t\t\t\trois[:, 1:], bbox_pred, max_shape=img_shape)\n\t\telse:\n\t\t\tbboxes = rois[:, 1:].clone()\n\t\t\tif img_shape is not None:\n\t\t\t\tbboxes[:, [0, 2]].clamp_(min=0, max=img_shape[1])\n\t\t\t\tbboxes[:, [1, 3]].clamp_(min=0, max=img_shape[0])\n\n\t\tif rescale and bboxes.size(0) > 0:\n\t\t\tif isinstance(scale_factor, float):\n\t\t\t\tbboxes /= scale_factor\n\t\t\telse:\n\t\t\t\tscale_factor = bboxes.new_tensor(scale_factor)\n\t\t\t\tbboxes = (bboxes.view(bboxes.size(0), -1, 4) /\n\t\t\t\t\t\t scale_factor).view(bboxes.size()[0], -1)\n\n\t\tif cfg is None:\n\t\t\treturn bboxes, scores\n\t\telse:\n\t\t\tdet_bboxes, det_labels = multiclass_nms(bboxes, scores,\n\t\t\t\t\t\t\t\t\t\t\t\t\tcfg.score_thr, cfg.nms,\n\t\t\t\t\t\t\t\t\t\t\t\t\tcfg.max_per_img)\n\n\t\t\treturn det_bboxes, det_labels\n\n\t@force_fp32(apply_to=('bbox_preds', ))\n\tdef refine_bboxes(self, rois, labels, bbox_preds, pos_is_gts, img_metas):\n\t\t\"\"\"Refine bboxes during training.\n\t\tArgs:\n\t\t\trois (Tensor): Shape (n*bs, 5), where n is image number per GPU,\n\t\t\t\tand bs is the sampled RoIs per image. The first column is\n\t\t\t\tthe image id and the next 4 columns are x1, y1, x2, y2.\n\t\t\tlabels (Tensor): Shape (n*bs, ).\n\t\t\tbbox_preds (Tensor): Shape (n*bs, 4) or (n*bs, 4*#class).\n\t\t\tpos_is_gts (list[Tensor]): Flags indicating if each positive bbox\n\t\t\t\tis a gt bbox.\n\t\t\timg_metas (list[dict]): Meta info of each image.\n\t\tReturns:\n\t\t\tlist[Tensor]: Refined bboxes of each image in a mini-batch.\n\t\tExample:\n\t\t\t>>> # xdoctest: +REQUIRES(module:kwarray)\n\t\t\t>>> import kwarray\n\t\t\t>>> import numpy as np\n\t\t\t>>> from mmdet.core.bbox.demodata import random_boxes\n\t\t\t>>> self = BBoxHead(reg_class_agnostic=True)\n\t\t\t>>> n_roi = 2\n\t\t\t>>> n_img = 4\n\t\t\t>>> scale = 512\n\t\t\t>>> rng = np.random.RandomState(0)\n\t\t\t>>> img_metas = [{'img_shape': (scale, scale)}\n\t\t\t...\t\t\t for _ in range(n_img)]\n\t\t\t>>> # Create rois in the expected format\n\t\t\t>>> roi_boxes = random_boxes(n_roi, scale=scale, rng=rng)\n\t\t\t>>> img_ids = torch.randint(0, n_img, (n_roi,))\n\t\t\t>>> img_ids = img_ids.float()\n\t\t\t>>> rois = torch.cat([img_ids[:, None], roi_boxes], dim=1)\n\t\t\t>>> # Create other args\n\t\t\t>>> labels = torch.randint(0, 2, (n_roi,)).long()\n\t\t\t>>> bbox_preds = random_boxes(n_roi, scale=scale, rng=rng)\n\t\t\t>>> # For each image, pretend random positive boxes are gts\n\t\t\t>>> is_label_pos = (labels.numpy() > 0).astype(np.int)\n\t\t\t>>> lbl_per_img = kwarray.group_items(is_label_pos,\n\t\t\t...\t\t\t\t\t\t\t\t img_ids.numpy())\n\t\t\t>>> pos_per_img = [sum(lbl_per_img.get(gid, []))\n\t\t\t...\t\t\t\tfor gid in range(n_img)]\n\t\t\t>>> pos_is_gts = [\n\t\t\t>>>\t torch.randint(0, 2, (npos,)).byte().sort(\n\t\t\t>>>\t\t descending=True)[0]\n\t\t\t>>>\t for npos in pos_per_img\n\t\t\t>>> ]\n\t\t\t>>> bboxes_list = self.refine_bboxes(rois, labels, bbox_preds,\n\t\t\t>>>\t\t\t\t\tpos_is_gts, img_metas)\n\t\t\t>>> print(bboxes_list)\n\t\t\"\"\"\n\t\timg_ids = rois[:, 0].long().unique(sorted=True)\n\t\tassert img_ids.numel() <= len(img_metas)\n\n\t\tbboxes_list = []\n\t\tfor i in range(len(img_metas)):\n\t\t\tinds = torch.nonzero(\n\t\t\t\trois[:, 0] == i, as_tuple=False).squeeze(dim=1)\n\t\t\tnum_rois = inds.numel()\n\n\t\t\tbboxes_ = rois[inds, 1:]\n\t\t\tlabel_ = labels[inds]\n\t\t\tbbox_pred_ = bbox_preds[inds]\n\t\t\timg_meta_ = img_metas[i]\n\t\t\tpos_is_gts_ = pos_is_gts[i]\n\n\t\t\tbboxes = self.regress_by_class(bboxes_, label_, bbox_pred_,\n\t\t\t\t\t\t\t\t\t\t img_meta_)\n\n\t\t\t# filter gt bboxes\n\t\t\tpos_keep = 1 - pos_is_gts_\n\t\t\tkeep_inds = pos_is_gts_.new_ones(num_rois)\n\t\t\tkeep_inds[:len(pos_is_gts_)] = pos_keep\n\n\t\t\tbboxes_list.append(bboxes[keep_inds.type(torch.bool)])\n\n\t\treturn bboxes_list\n\n\t@force_fp32(apply_to=('bbox_pred', ))\n\tdef regress_by_class(self, rois, label, bbox_pred, img_meta):\n\t\t\"\"\"Regress the bbox for the predicted class. Used in Cascade R-CNN.\n\t\tArgs:\n\t\t\trois (Tensor): shape (n, 4) or (n, 5)\n\t\t\tlabel (Tensor): shape (n, )\n\t\t\tbbox_pred (Tensor): shape (n, 4*(#class)) or (n, 4)\n\t\t\timg_meta (dict): Image meta info.\n\t\tReturns:\n\t\t\tTensor: Regressed bboxes, the same shape as input rois.\n\t\t\"\"\"\n\t\tassert rois.size(1) == 4 or rois.size(1) == 5, repr(rois.shape)\n\n\t\tif not self.reg_class_agnostic:\n\t\t\tlabel = label * 4\n\t\t\tinds = torch.stack((label, label + 1, label + 2, label + 3), 1)\n\t\t\tbbox_pred = torch.gather(bbox_pred, 1, inds)\n\t\tassert bbox_pred.size(1) == 4\n\n\t\tif rois.size(1) == 4:\n\t\t\tnew_rois = self.bbox_coder.decode(\n\t\t\t\trois, bbox_pred, max_shape=img_meta['img_shape'])\n\t\telse:\n\t\t\tbboxes = self.bbox_coder.decode(\n\t\t\t\trois[:, 1:], bbox_pred, max_shape=img_meta['img_shape'])\n\t\t\tnew_rois = torch.cat((rois[:, [0]], bboxes), dim=1)\n\n\t\treturn new_rois\n"
] | [
[
"torch.nn.functional.softmax",
"torch.cat",
"torch.nn.init.constant_",
"torch.gather",
"torch.sum",
"torch.nn.Linear",
"torch.nn.AvgPool2d",
"torch.nn.init.normal_",
"torch.nonzero",
"torch.nn.modules.utils._pair",
"torch.stack"
]
] |
PythonBiellaGroup/ModernDataEngineering | [
"369fcb89d119ccd1d73882e492cf7c5331087d20"
] | [
"scripts/etl-anagrafica-ospedali.py"
] | [
"import pandas as pd\nimport os\nimport numpy as np\nfrom sqlalchemy import create_engine\n\ncurrent_dir = os.getcwd()\nextract_folder = os.path.join(current_dir, \"data/ospedali.csv\")\n\n# Extract data\ndf_ospedali = pd.read_csv(extract_folder)\n\n# Transform data\n\n# ------------------------------------------------------------------------------------------------------------------------------------------\ndef drop_columns(df):\n df.drop(columns=[\"COD_SUB\"], inplace=True)\n return df\n\n\n# ------------------------------------------------------------------------------------------------------------------------------------------\ndef transf_cod_struttura(df):\n df[\"COD_SUB\"] = df[\"COD_SUB\"].astype(str)\n df[\"COD_SUB\"] = df[\"COD_SUB\"].apply(lambda x: x.zfill(2))\n df[\"COD_STRUTTURA\"] = df[\"COD_STRUTTURA\"].astype(str)\n df[\"COD_STRUTTURA\"] = df[\"COD_STRUTTURA\"].apply(lambda x: x.zfill(6))\n df[\"COD_STRUTTURA\"] = df[\"COD_STRUTTURA\"] + \"-\" + df[\"COD_SUB\"]\n return df\n\n\n# ------------------------------------------------------------------------------------------------------------------------------------------\ndef transf_ps_pediatrico(df):\n conditions = [(df[\"PS_PEDIATRICO\"] == \"X\"), (df[\"PS_PEDIATRICO\"] == \"Nan\")]\n values = [1, 0]\n df[\"PS_PEDIATRICO\"] = np.select(conditions, values)\n return df\n\n\n# ------------------------------------------------------------------------------------------------------------------------------------------\ndef transf_data_apertura_chiusura(df):\n df[\"DATA_APERTURA\"] = pd.to_datetime(df[\"DATA_APERTURA\"]).dt.date\n df[\"DATA_CHIUSURA\"] = pd.to_datetime(df[\"DATA_CHIUSURA\"]).dt.date\n df.fillna({\"DATA_CHIUSURA\": \"2999-12-31\"}, inplace=True)\n return df\n\n\n# ------------------------------------------------------------------------------------------------------------------------------------------\ndef add_descr_liv_emergenza(df):\n df[\"LIV_EMERG\"].replace(\"Senza livello emergenza\", \"SLE\", inplace=True)\n df[\"DESCR_LIV_EMERG\"] = df[\"LIV_EMERG\"]\n df[\"DESCR_LIV_EMERG\"].replace(\n {\n \"DEA-PS\": \"Dipartimento Emergenza Accettazione-Pronto Soccorso\",\n \"DEA-PS-PPI\": \"Dipartimento Emergenza Accettazione-Pronto Soccorso-Punto di Primo Intervento\",\n \"EAS-PS\": \"Emergenza Alta Specialità-Pronto Soccorso\",\n \"EAS-PS-PPI\": \"Emergenza Alta Specialità-Pronto Soccorso-Punto di Primo Intervento\",\n \"PS-PPI\": \"Pronto Soccorso-Punto di Primo Intervento\",\n \"PS\": \"Pronto Soccorso\",\n \"PPI\": \"Punto di Primo Intervento\",\n \"EAS\": \"Emergenza Alta Specialità\",\n \"SLE\": \"Senza Livello Emergenza\",\n },\n inplace=True,\n )\n return df\n\n\n# ------------------------------------------------------------------------------------------------------------------------------------------\ndef rename_columns(df):\n df.rename(\n columns={\n \"ATS\": \"COD_ATS\",\n },\n inplace=True,\n )\n return df\n\n\ntransf_cod_struttura(df_ospedali)\ntransf_ps_pediatrico(df_ospedali)\ntransf_data_apertura_chiusura(df_ospedali)\nadd_descr_liv_emergenza(df_ospedali)\ndrop_columns(df_ospedali)\nrename_columns(df_ospedali)\n\n# reorganize columns orders\ndf_ospedali = df_ospedali[\n [\n \"COD_STRUTTURA\",\n \"DENOM_STRUTTURA\",\n \"COD_ATS\",\n \"COD_ENTE\",\n \"DENOM_ENTE\",\n \"COD_TIPO_STR\",\n \"DESCR_TIPO_STR\",\n \"DATA_APERTURA\",\n \"DATA_CHIUSURA\",\n \"INDIRIZZO\",\n \"CAP\",\n \"LOCALITA\",\n \"FAX\",\n \"LIV_EMERG\",\n \"DESCR_LIV_EMERG\",\n \"PS_PEDIATRICO\",\n ]\n]\n\n# Load data\n# Write data into the table in AZURE SQL Server database\ncxn = establish_db_connection()\ntruncate_query = sqlalchemy.text(\"TRUNCATE TABLE STG_ANG_HOSPITAL\")\ncxn.execution_options(autocommit=True).execute(truncate_query)\ndf_ospedali.to_sql(\"STG_ANG_HOSPITAL\", con=cxn, if_exists=\"append\", index=False)\ncxn.dispose()\n"
] | [
[
"pandas.read_csv",
"pandas.to_datetime",
"numpy.select"
]
] |
spcornelius/symopt | [
"6f276ca07cc266af1cd58758a0cf413ab85f2591"
] | [
"symopt/solvers/scipy.py"
] | [
"from scipy.optimize import minimize\nfrom sympy import Equality\n\nfrom symopt.exceptions import IncompatibleSolverError\nfrom symopt.util import negated\n\n__all__ = []\n__all__.extend([\n 'prepare_scipy',\n 'solve_slsqp',\n 'solve_cobyla'\n])\n\n\ndef prepare_scipy(prob, *param_vals):\n \"\"\" Convert an `.OptimizationProblem` to inputs for\\\n :func:`scipy.optimize.minimize`.\n\n Parameters\n ----------\n prob : `.OptimizationProblem`\n Problem to solve\n *param_vals\n Numerical values for problem parameters, supplied with the same order\n and types as :py:attr:`prob.vars`.\n\n Returns\n -------\n (`~collections.abc.Callable`, `~collections.abc.Callable`, \\\n `list` of `dict`, `list` of `tuple`)\n Objective function callback, jacobian callback, constraint\n dictionaries, and the lower/upper bound for each variable. See\n documentation for :func:`scipy.optimize.minimize` for more details.\"\"\"\n fun = prob.obj.cb\n jac = prob.obj.grad_cb\n\n if prob.mode == 'max':\n fun = negated(fun)\n jac = negated(jac)\n\n cons = [c.as_scipy_dict(*param_vals) for c in prob.cons]\n lb, ub = prob.eval_bounds(*param_vals)\n return fun, jac, cons, list(zip(lb, ub))\n\n\ndef solve_slsqp(prob, x0, *param_vals, **kwargs):\n \"\"\" Solve an optimization problem using SciPy's SLSQP method. \"\"\"\n\n fun, jac, cons, bounds = prepare_scipy(prob, *param_vals)\n return minimize(fun, x0, args=param_vals, method='SLSQP', jac=jac,\n bounds=bounds, constraints=cons, **kwargs)\n\n\ndef solve_cobyla(prob, x0, *param_vals, **kwargs):\n \"\"\" Solve an optimization problem using SciPy's COBYLA method. \"\"\"\n\n if any(v.is_bounded for v in prob.vars):\n raise IncompatibleSolverError(\n \"COBYLA does not support explicit variable lb/ub. \"\n \"Recast as constraints.\")\n if any(c.type is Equality for c in prob.cons):\n raise IncompatibleSolverError(\n \"COBYLA supports only inequality constraints\")\n\n # COBYLA doesn't use jac or bounds\n fun, _, cons, _ = prepare_scipy(prob, *param_vals)\n return minimize(fun, x0, args=param_vals, method='COBYLA',\n constraints=cons, **kwargs)\n"
] | [
[
"scipy.optimize.minimize"
]
] |
wendychen0521/DualStyleGAN | [
"67751d90d1a23358f6cbe5d23e3475cbe2cebff2"
] | [
"refine_exstyle.py"
] | [
"import os\r\n\r\nimport numpy as np\r\nimport torch\r\nfrom torch import optim\r\nfrom util import save_image\r\nimport argparse\r\nfrom argparse import Namespace\r\nfrom torchvision import transforms\r\nfrom torch.nn import functional as F\r\nimport torchvision\r\nfrom PIL import Image\r\nfrom tqdm import tqdm\r\nimport math\r\n\r\nfrom model.dualstylegan import DualStyleGAN\r\nfrom model.stylegan import lpips\r\nfrom model.encoder.psp import pSp\r\nfrom model.encoder.criteria import id_loss\r\nimport model.contextual_loss.functional as FCX\r\nfrom model.vgg import VGG19\r\n\r\nclass TrainOptions():\r\n def __init__(self):\r\n\r\n self.parser = argparse.ArgumentParser(description=\"Refine Extrinsic Style Codes\")\r\n self.parser.add_argument(\"style\", type=str, help=\"target style type\")\r\n self.parser.add_argument(\"--model_path\", type=str, default='./checkpoint/', help=\"path of the saved models\")\r\n self.parser.add_argument(\"--ckpt\", type=str, default=None, help=\"path to the saved dualstylegan model\")\r\n self.parser.add_argument(\"--exstyle_path\", type=str, default=None, help=\"path to the saved extrinsic style codes\")\r\n self.parser.add_argument(\"--instyle_path\", type=str, default=None, help=\"path to the saved intrinsic style codes\")\r\n self.parser.add_argument(\"--data_path\", type=str, default='./data/', help=\"path of dataset\")\r\n self.parser.add_argument(\"--iter\", type=int, default=100, help=\"total training iterations\")\r\n self.parser.add_argument(\"--batch\", type=int, default=1, help=\"batch size\")\r\n self.parser.add_argument(\"--lr_color\", type=float, default=0.01, help=\"learning rate for color parts\")\r\n self.parser.add_argument(\"--lr_structure\", type=float, default=0.005, help=\"learning rate for structure parts\")\r\n self.parser.add_argument(\"--model_name\", type=str, default='refined_exstyle_code.npy', help=\"name to save the refined extrinsic style codes\")\r\n\r\n def parse(self):\r\n self.opt = self.parser.parse_args()\r\n if self.opt.ckpt is None:\r\n self.opt.ckpt = os.path.join(self.opt.model_path, self.opt.style, 'generator.pt') \r\n if self.opt.exstyle_path is None:\r\n self.opt.exstyle_path = os.path.join(self.opt.model_path, self.opt.style, 'exstyle_code.npy') \r\n if self.opt.instyle_path is None:\r\n self.opt.instyle_path = os.path.join(self.opt.model_path, self.opt.style, 'instyle_code.npy') \r\n args = vars(self.opt)\r\n print('Load options')\r\n for name, value in sorted(args.items()):\r\n print('%s: %s' % (str(name), str(value)))\r\n return self.opt\r\n\r\ndef noise_regularize(noises):\r\n loss = 0\r\n\r\n for noise in noises:\r\n size = noise.shape[2]\r\n\r\n while True:\r\n loss = (\r\n loss\r\n + (noise * torch.roll(noise, shifts=1, dims=3)).mean().pow(2)\r\n + (noise * torch.roll(noise, shifts=1, dims=2)).mean().pow(2)\r\n )\r\n\r\n if size <= 8:\r\n break\r\n\r\n noise = noise.reshape([-1, 1, size // 2, 2, size // 2, 2])\r\n noise = noise.mean([3, 5])\r\n size //= 2\r\n\r\n return loss\r\n\r\ndef noise_normalize_(noises):\r\n for noise in noises:\r\n mean = noise.mean()\r\n std = noise.std()\r\n\r\n noise.data.add_(-mean).div_(std)\r\n \r\nif __name__ == \"__main__\":\r\n device = \"cuda\"\r\n\r\n parser = TrainOptions()\r\n args = parser.parse()\r\n print('*'*50)\r\n \r\n if not os.path.exists(\"log/%s/refine_exstyle/\"%(args.style)):\r\n os.makedirs(\"log/%s/refine_exstyle/\"%(args.style))\r\n \r\n transform = transforms.Compose(\r\n [\r\n transforms.Resize(256),\r\n transforms.CenterCrop(256),\r\n transforms.ToTensor(),\r\n transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5]),\r\n ]\r\n )\r\n\r\n generator = DualStyleGAN(1024, 512, 8, 2, res_index=6).to(device)\r\n generator.eval()\r\n\r\n ckpt = torch.load(args.ckpt)\r\n generator.load_state_dict(ckpt[\"g_ema\"])\r\n noises_single = generator.make_noise()\r\n\r\n percept = lpips.PerceptualLoss(model=\"net-lin\", net=\"vgg\", use_gpu=device.startswith(\"cuda\"))\r\n vggloss = VGG19().to(device).eval()\r\n\r\n print('Load models successfully!')\r\n \r\n datapath = os.path.join(args.data_path, args.style, 'images/train')\r\n exstyles_dict = np.load(args.exstyle_path, allow_pickle='TRUE').item()\r\n instyles_dict = np.load(args.instyle_path, allow_pickle='TRUE').item()\r\n files = list(exstyles_dict.keys())\r\n\r\n dict = {}\r\n for ii in range(0,len(files),args.batch):\r\n batchfiles = files[ii:ii+args.batch]\r\n imgs = []\r\n exstyles = []\r\n instyles = []\r\n for file in batchfiles:\r\n img = transform(Image.open(os.path.join(datapath, file)).convert(\"RGB\"))\r\n imgs.append(img)\r\n exstyles.append(torch.tensor(exstyles_dict[file]))\r\n instyles.append(torch.tensor(instyles_dict[file]))\r\n imgs = torch.stack(imgs, 0).to(device)\r\n exstyles = torch.cat(exstyles, dim=0).to(device)\r\n instyles = torch.cat(instyles, dim=0).to(device)\r\n with torch.no_grad(): \r\n real_feats = vggloss(imgs)\r\n\r\n noises = []\r\n for noise in noises_single:\r\n noises.append(noise.repeat(imgs.shape[0], 1, 1, 1).normal_())\r\n for noise in noises:\r\n noise.requires_grad = True \r\n \r\n # color code\r\n exstyles_c = exstyles[:,7:].detach().clone()\r\n exstyles_c.requires_grad = True\r\n # structure code\r\n exstyles_s = exstyles[:,0:7].detach().clone()\r\n exstyles_s.requires_grad = True\r\n\r\n optimizer = optim.Adam([{'params':exstyles_c,'lr':args.lr_color}, \r\n {'params':exstyles_s,'lr':args.lr_structure}, \r\n {'params':noises,'lr':0.1}])\r\n\r\n pbar = tqdm(range(args.iter), smoothing=0.01, dynamic_ncols=False, ncols=100)\r\n \r\n for i in pbar: \r\n\r\n latent = torch.cat((exstyles_s, exstyles_c), dim=1)\r\n latent = generator.generator.style(latent.reshape(latent.shape[0]*latent.shape[1], latent.shape[2])).reshape(latent.shape)\r\n\r\n img_gen, _ = generator([instyles], latent, noise=noises, use_res=True, z_plus_latent=True)\r\n\r\n batch, channel, height, width = img_gen.shape\r\n\r\n if height > 256:\r\n factor = height // 256\r\n\r\n img_gen = img_gen.reshape(\r\n batch, channel, height // factor, factor, width // factor, factor\r\n )\r\n img_gen = img_gen.mean([3, 5])\r\n\r\n if i == 0:\r\n img_gen0 = img_gen.detach().clone()\r\n\r\n Lperc = percept(img_gen, imgs).sum()\r\n Lnoise = noise_regularize(noises)\r\n\r\n fake_feats = vggloss(img_gen)\r\n LCX = FCX.contextual_loss(fake_feats[2], real_feats[2].detach(), band_width=0.2, loss_type='cosine')\r\n\r\n loss = Lperc + LCX + 1e5 * Lnoise\r\n\r\n optimizer.zero_grad()\r\n loss.backward()\r\n optimizer.step()\r\n noise_normalize_(noises)\r\n\r\n pbar.set_description(\r\n (\r\n f\"[{ii * args.batch:03d}/{len(files):03d}]\"\r\n f\" Lperc: {Lperc.item():.3f}; Lnoise: {Lnoise.item():.3f};\"\r\n f\" LCX: {LCX.item():.3f}\" \r\n )\r\n )\r\n\r\n\r\n with torch.no_grad():\r\n latent = torch.cat((exstyles_s, exstyles_c), dim=1)\r\n for j in range(imgs.shape[0]):\r\n vis = torchvision.utils.make_grid(torch.cat([imgs[j:j+1], img_gen0[j:j+1], img_gen[j:j+1].detach()], dim=0), 3, 1)\r\n save_image(torch.clamp(vis.cpu(),-1,1), os.path.join(\"./log/%s/refine_exstyle/\"%(args.style), batchfiles[j]))\r\n dict[batchfiles[j]] = latent[j:j+1].cpu().numpy()\r\n\r\n np.save(os.path.join(args.model_path, args.style, args.model_name), dict) \r\n \r\n print('Refinement done!')\r\n "
] | [
[
"torch.optim.Adam",
"torch.roll",
"torch.cat",
"torch.load",
"torch.tensor",
"torch.no_grad",
"torch.stack",
"numpy.load"
]
] |
fadeevla/pytorch-deeplab-xception | [
"dd4e092ecc47ec94e851b36523d243a484f6c672"
] | [
"dataloaders/datasets/MFCDataset.py"
] | [
"\r\nfrom torch.utils.data import Dataset\r\nfrom torchvision import transforms\r\nfrom PIL import Image\r\nimport os\r\nfrom os.path import join\r\nimport random\r\nimport numpy as np\r\nimport sys\r\n\r\n\r\n\r\nseed = random.randrange(sys.maxsize)\r\n\r\nclass MFCDataset(Dataset):\r\n \r\n def _listdir(self, dirpath):\r\n print('dir_path=',dirpath)\r\n ll = (os.getcwd(), os.listdir())\r\n print('current_dir content/n',ll)\r\n\r\n for x in os.listdir(dirpath):\r\n if x.split('.')[-1] in self._imgexts:\r\n yield(x)\r\n def __init__(self, root, img_transform=None, mask_transform =None):\r\n self.root = root \r\n self._imgexts = ['jpg','jpeg','png']\r\n \r\n self.datapoints = [os.path.splitext(x)[0] for x in self._listdir(join(root, \"image\"))]\r\n self.endings = [os.path.splitext(x)[1] for x in self._listdir(join(root, \"image\"))]\r\n self.NUM_CLASSES = 2\r\n transforms = self.get_transforms()\r\n\r\n if img_transform is None:\r\n self.img_transform = transforms['img_transform']\r\n if mask_transform is None:\r\n self.mask_transform = transforms['mask_transform']\r\n\r\n def __len__(self):\r\n return len(self.datapoints)\r\n\r\n def get_transforms(self):\r\n img_transform = transforms.Compose([\r\n transforms.RandomVerticalFlip(),\r\n transforms.RandomHorizontalFlip(),\r\n # transforms.RandomResizedCrop(size=0),\r\n transforms.RandomRotation(180),\r\n transforms.ColorJitter(brightness=.5, contrast=.5, saturation=.5, hue=.5),\r\n transforms.RandomGrayscale(),\r\n transforms.ToTensor()\r\n ])\r\n\r\n mask_transform = transforms.Compose([\r\n transforms.RandomVerticalFlip(),\r\n transforms.RandomHorizontalFlip(),\r\n # transforms.RandomResizedCrop(size=152,interpolation=PIL.Image.NEAREST),\r\n transforms.RandomRotation(180)\r\n ])\r\n return {'img_transform' : img_transform, 'mask_transform' : mask_transform}\r\n\r\n def __getitem__(self, idx):\r\n if isinstance(idx, int) or isinstance(idx, np.int64):\r\n datapoint = self.datapoints[idx]\r\n if self.endings[idx] == \".jpg\":\r\n image = Image.open(join(self.root, \"image\",datapoint + \".jpg\"))\r\n image = image.resize((152,152), Image.BILINEAR)\r\n mask = Image.open(join(self.root, \"mask\", datapoint + \".png\"))\r\n mask = mask.resize((152,152), Image.BILINEAR) \r\n\r\n if self.endings[idx] == \".jpeg\":\r\n image = Image.open(join(self.root, \"image\",datapoint + \".jpeg\"))\r\n image = image.resize((152,152), Image.BILINEAR)\r\n mask = Image.open(join(self.root, \"mask\", \"2.png\")).convert('RGB')\r\n mask = mask.resize((152,152), Image.BILINEAR)\r\n\r\n seed = random.randrange(sys.maxsize)\r\n if self.img_transform:\r\n random.seed(seed) \r\n try:\r\n image = self.img_transform(image)\r\n except:\r\n print('exception idx=',idx)\r\n if self.mask_transform and self.endings[idx] == \".jpg\": \r\n random.seed(seed) \r\n mask = self.mask_transform(mask)\r\n try:\r\n mask = np.array(mask, dtype=np.float32)[:,:,0]\r\n except:\r\n print('idx=',idx,' datapoint=', datapoint)\r\n else:\r\n mask = np.array(mask, dtype=np.float32)[:,:,0]\r\n mask = np.zeros_like(mask)\r\n return [image, mask]\r\n elif isinstance(idx, slice):\r\n start, stop, step = idx.indices(len(self))\r\n return [self[i] for i in range(start, stop, step)]\r\n elif isinstance(idx, tuple) or isinstance(idx, list):\r\n return [self[i] for i in idx]\r\n else:\r\n raise ValueError(f'Slicing for idx is {type(idx)} is not implemented')"
] | [
[
"numpy.array",
"numpy.zeros_like"
]
] |
jatinchowdhury18/RNNAudioEffects | [
"df4de8e1549bbe1d27fc1760a35c1557039fe64f"
] | [
"hysteresis/hysteresis_drive.py"
] | [
"# %%\n# Load dependencies\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport audio_dspy as adsp\nimport scipy.signal as signal\nimport tensorflow as tf\nfrom tensorflow import keras\nimport librosa\nfrom tqdm import tqdm\nimport os\nimport random\nimport sys\n\nsys.path.append('..')\nfrom utils.utils import plot_fft, load_fma_file\nfrom utils.model import Model\nimport utils.losses as losses\n\n# %%\n# load files\nfilepath = '../Data/fma_small/'\nfiles = os.listdir(filepath)\n\nNUM_FILES = 10\nNUM_SAMPLES = 20000\nFS = 96000\nclean_data = []\nfor i in tqdm(range(NUM_FILES)):\n x = load_fma_file(files, filepath, FS, NUM_SAMPLES)\n clean_data.append(x)\n\nclean_data = np.asarray(clean_data)\nprint(np.shape(clean_data))\n\n# %%\n# look at file\nidx = 4\nplt.plot(clean_data[idx])\n\n# %%\nhyst_data = []\ndrive_data = []\nfor x in tqdm(clean_data):\n drive = random.choice([0.05, 0.25, 0.5, 0.75, 1.0])\n hyst = adsp.Hysteresis(drive, 1.0, 1.0, FS, mode='RK4')\n y = hyst.process_block(x)\n\n drive_data.append(np.ones_like(x) * drive)\n hyst_data.append(y.astype(np.float32))\n\n# %%\nidx = 4\nplt.figure()\nplt.plot(clean_data[idx])\nplt.plot(hyst_data[idx])\nplt.plot(drive_data[idx])\n\nplt.figure()\nfreqs, x_fft = plot_fft(clean_data[idx], FS)\nfreqs, y_fft = plot_fft(hyst_data[idx], FS)\nplt.semilogx(freqs, x_fft)\nplt.semilogx(freqs, y_fft)\n\n# %%\nNUM_TRAIN = 9\nNUM_VAL = 1\nx_data = np.stack((clean_data, drive_data), axis=1)\nprint(x_data.shape)\n\nx_train, x_val = np.split(x_data, [NUM_TRAIN])\ny_train, y_val = np.split(hyst_data, [NUM_TRAIN])\n\n# %%\nOUT_train = np.reshape(y_train, (NUM_TRAIN, NUM_SAMPLES, 1))\nOUT_val = np.reshape(y_val, (NUM_VAL, NUM_SAMPLES, 1))\nIN_train = np.reshape(x_train.transpose((0, 2, 1)), (NUM_TRAIN, NUM_SAMPLES, 2))\nIN_val = np.reshape(x_val.transpose((0, 2, 1)), (NUM_VAL, NUM_SAMPLES, 2))\n\nprint(np.shape(IN_train))\n\n# %%\nplt.plot(IN_train[0, :, 0])\nplt.plot(IN_train[0, :, 1])\n\nprint(IN_train.dtype)\nprint(OUT_train.dtype)\n\n# %%\ndef model_loss(target_y, predicted_y):\n return losses.esr_loss(target_y, predicted_y, losses.pre_emphasis_filter) + losses.dc_loss(target_y, predicted_y)\n\n# construct model\nmodel = Model(model_loss, optimizer=keras.optimizers.Adam(learning_rate=5.0e-4))\nmodel.model.add(keras.layers.InputLayer(input_shape=(None, 2)))\nmodel.model.add(keras.layers.GRU(units=32, return_sequences=True))\nmodel.model.add(keras.layers.Dense(1))\n\nmodel.model.summary()\n\n# %%\nmodel.train(50, IN_train, OUT_train, IN_val, OUT_val)\n\n# %%\n# plot metrics\nplt.figure()\nmodel.plot_loss()\n\nplt.figure()\nmodel.plot_error()\n\n# %%\n# Test prediction\nidx = 2\nprint(np.shape(x_data[idx]))\n\npredictions = model.model.predict(IN_train[idx].reshape(1, NUM_SAMPLES, 2)).flatten()\nprint(np.shape(predictions))\n\n# Plot the predictions along with the test data\nplt.clf()\nplt.title('Training data predicted vs actual values')\nplt.plot(hyst_data[idx], 'c', label='Actual')\nplt.plot(predictions, 'r--', label='Predicted')\nplt.legend()\nplt.xlim(1000, 4000)\nplt.xlabel('Time [samples]')\n\n# %%\nfreqs, pred_fft = plot_fft(predictions, FS)\nfreqs, target_fft = plot_fft(hyst_data[idx], FS)\n\n# Plot the predictions along with to the test data\nplt.clf()\nplt.title('Training data predicted vs actual values')\nplt.semilogx(freqs, target_fft, 'b', label='Actual')\nplt.semilogx(freqs, pred_fft, 'r--', label='Predicted')\nplt.legend()\nplt.xlim(50, 20000)\nplt.ylim(-5)\nplt.xlabel('Frequency [Hz]')\nplt.ylabel('Magnitude [dB]')\n\n# %%"
] | [
[
"matplotlib.pyplot.legend",
"numpy.split",
"numpy.asarray",
"tensorflow.keras.layers.InputLayer",
"matplotlib.pyplot.plot",
"numpy.ones_like",
"numpy.reshape",
"numpy.stack",
"tensorflow.keras.layers.GRU",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.semilogx",
"matplotlib.pyplot.title",
"matplotlib.pyplot.ylim",
"tensorflow.keras.layers.Dense",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.clf",
"numpy.shape",
"tensorflow.keras.optimizers.Adam",
"matplotlib.pyplot.xlabel"
]
] |
ireina7/zsl-seg | [
"6dc214bd418c8ca12458095e59459487c0b07893"
] | [
"src/model/util.py"
] | [
"# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport math\nimport os\nimport sys\nsys.path.append(\"..\")\nfrom src.config import *\nfrom src.util import error\n\ndef get_embeddings():\n file = [\"fasttext.txt\", \"word2vec.txt\", \"all.txt\"]\n embeddings = {}\n for i in file:\n dic = {}\n with open(path.join(path.dataset_semantic, i), \"r\") as f:\n for line in f.read().splitlines():\n name, vector = line.split(\" \")\n # if name == \"background\":\n # continue\n vector = vector.split(\",\")\n vector = list(map(float, vector))\n tmp = 0\n for x in vector:\n tmp += x ** 2\n tmp = math.sqrt(tmp)\n dic[name] = [x / tmp for x in vector]\n embeddings[i.split(\".\")[0]] = dic\n return embeddings\n #end get_embeddings\n\n\ndef get_Ws(embeddings, strong_classes):\n file = [\"fasttext\", \"word2vec\", \"all\"]\n strong_len = len(strong_classes)\n Ws = {}\n for name in file:\n lenth = 300\n if name == \"all\":\n lenth = 600\n embedding = embeddings[name]\n strong = np.zeros([strong_len, lenth], dtype=np.float)\n weak = np.zeros([20 - strong_len, lenth], dtype=np.float)\n all = np.zeros([20, lenth], dtype=np.float)\n i, j, k = 0, 0, 0\n for class_name in embedding:\n if class_name == \"background\":\n continue\n if class_name in strong_classes:\n strong[i] = embedding[class_name]\n i += 1\n else:\n weak[j] = embedding[class_name]\n j += 1\n all[k] = embedding[class_name]\n k += 1\n Ws[name + \"_strong\"] = strong\n Ws[name + \"_weak\"] = weak\n Ws[name + \"_all\"] = all\n return Ws\n #end get_Ws\n\n\n\ndef get_Ws_split(embeddings, split):\n ALL_CLASSES = [\n \"bg\", \"airplane\", \"bicycle\", \"bird\", \"boat\", \"bottle\", \"bus\", \"car\", \"cat\", \"chair\", \"cow\",\n \"table\", \"dog\", \"horse\", \"motorbike\", \"person\", \"houseplant\", \"sheep\", \"sofa\", \"train\",\n \"monitor\"\n ]\n all = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]\n split1 = [ 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]\n split2 = [1, 2, 3, 4, 5, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]\n split3 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 17, 18, 19, 20]\n split4 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ]\n strong_class = []\n if split == 1:\n strong_class = [ALL_CLASSES[x] for x in split1]\n elif split == 2:\n strong_class = [ALL_CLASSES[x] for x in split2]\n elif split == 3:\n strong_class = [ALL_CLASSES[x] for x in split3]\n elif split == 4:\n strong_class = [ALL_CLASSES[x] for x in split4]\n else:\n error('Split should be a number within [1, 4], but got {}'.format(split))\n \n\n file = [\"all\", \"fasttext\", \"word2vec\"]\n strong_len = 15\n Ws = {}\n for name in file:\n lenth = 300\n if name == \"all\":\n lenth = 600\n embedding = embeddings[name]\n strong = np.zeros([strong_len, lenth], dtype=np.float)\n weak = np.zeros([20 - strong_len, lenth], dtype=np.float)\n\n i, j = 0, 0\n for class_name in embedding:\n if class_name == \"background\":\n continue\n if class_name in strong_class:\n strong[i] = embedding[class_name]\n i += 1\n else:\n weak[j] = embedding[class_name]\n j += 1\n all = np.concatenate([strong,weak])\n\n Ws[name + \"_strong\"] = strong\n Ws[name + \"_weak\"] = weak\n Ws[name + \"_all\"] = all\n return Ws\n\n\n\n\n\ndef get_embeddings_coco():\n \"\"\"\n For future use of COCO dataset, currently not finished!\n \"\"\"\n file = [\"fasttext_coco.txt\", \"word2vec_coco.txt\", \"all_coco.txt\"]\n embeddings = {}\n for i in file:\n dic = {}\n with open(\"model/\" + i, \"r\") as f:\n for line in f.read().splitlines():\n name, vector = line.split(\" \")\n vector = vector.split(\",\")\n vector = list(map(float, vector))\n # tmp = 0\n # for x in vector:\n # tmp += x ** 2\n # tmp = math.sqrt(tmp)\n # dic[name] = [x / tmp for x in vector]\n dic[name] = vector\n embeddings[i.split(\"_\")[0]] = dic\n return embeddings\n #end get_embeddings_coco\n"
] | [
[
"numpy.concatenate",
"numpy.zeros"
]
] |
pierreolivierbonin/test_dash_app | [
"e21b78d5d8a75d9f77498900438c89da3968301c"
] | [
"Sunny Street Viz for Social Good app.py"
] | [
"import plotly.graph_objects as go\r\nimport dash\r\nimport plotly.express as px\r\nimport pandas as pd\r\nimport dash_bootstrap_components as dbc\r\nimport dash_core_components as dcc\r\nimport dash_html_components as html\r\nfrom dash.dependencies import Input, Output, State\r\n# dash bootstrap 1.0 or higher\r\n\r\ndfc = pd.read_csv(\r\n \"https://raw.githubusercontent.com/Coding-with-Adam/Dash-by-Plotly/master/Analytic_Web_Apps/VizForGood/Scatter_mapbox/Volaby-Sunny_Street-detailed-stats%202019%20-%202021%20-%20V3.csv\"\r\n)\r\ndfp = pd.read_csv(\"https://raw.githubusercontent.com/Coding-with-Adam/Dash-by-Plotly/master/Analytic_Web_Apps/VizForGood/Scatter_mapbox/Sunny%20Street%20-%20Patient%20data%203%20years.csv\")\r\n\r\n# Data Processing *********************************************************\r\n# *************************************************************************\r\ndfc[\"Activity\"] = dfc[\"Activity\"].replace(\r\n {\r\n \"Hervey Bay Neighbourhood/ Community Centre \": \"Hervey Bay Neighbourhood\",\r\n \"Maroochydore Neighbourhood Centre Community Event \": \"Maroochydore Neighbourhood Centre\",\r\n }\r\n)\r\n\r\n# create shift periods for the bottom map\r\ndfc[\"Start Time\"] = pd.to_datetime(\r\n dfc[\"Start Time\"], format=\"%I:%M %p\").dt.hour\r\ndfc[\"shift_start\"] = \"\"\r\ndfc.loc[dfc[\"Start Time\"] >= 19, \"shift_start\"] = \"night\"\r\ndfc.loc[dfc[\"Start Time\"] < 12, \"shift_start\"] = \"morning\"\r\ndfc.loc[\r\n (dfc[\"Start Time\"] >= 12) & (dfc[\"Start Time\"] < 19), \"shift_start\"\r\n] = \"afternoon\"\r\ndfc_shift = dfc.groupby([\"Latitude\", \"Longitude\", \"Activity\", \"shift_start\"])[\r\n [\"Medical Consults\"]\r\n].sum()\r\ndfc_shift.reset_index(inplace=True)\r\n\r\n# calculate average shift time for bottom histogram graph\r\navg_shift_time = round(dfc[\"Length minutes\"].mean())\r\n\r\n# re-organize dataframe for the top map\r\ndfc_gpd = dfc.groupby([\"Latitude\", \"Longitude\", \"Activity\"])[\r\n [\r\n \"Medical Consults\",\r\n \"Nurse Practitioner Consults\",\r\n \"Nursing/Paramedic Consults\",\r\n \"Conversations about health education\",\r\n \"Allied Health\",\r\n \"Referrals (Formal and informal)\",\r\n \"Patient Conversations\",\r\n \"Service provider conversations\",\r\n \"Mental health\",\r\n \"Suicide prevention/planning\",\r\n \"Substance use\",\r\n \"Medication education\",\r\n \"Patients turned away\",\r\n \"Telehealth consults that happened at Clinic\",\r\n \"Length minutes\",\r\n ]\r\n].sum()\r\ndfc_gpd.reset_index(inplace=True)\r\n\r\n# reformat time column to a proper datetime data type column\r\ndfc['activity_date'] = pd.to_datetime(\r\n dfc['Activity Date'], format='%m/%d/%Y', errors='ignore')\r\ndfc[\"year\"] = dfc['activity_date'].dt.year\r\ndfc['month'] = dfc['activity_date'].dt.month\r\ndfc[\"day\"] = dfc[\"activity_date\"].dt.day\r\n\r\nactivity_list = list(dfc[\"Activity\"].value_counts().sort_index().index)\r\nactivity_list.reverse()\r\nactivity_values = list(dfc[\"Activity\"].value_counts().sort_index().values)\r\nactivity_values.reverse()\r\n\r\ndfc[\"Activity_label\"] = dfc[\"Activity\"]\r\n# dfc.pivot_table(values='Activity', index=[\"year\"],\r\n# columns=['Activity_label'], aggfunc={\"Activity\": \"count\"}, fill_value=0)\r\nshift_byActivityDate = dfc.pivot_table(values='Activity', index=[\"activity_date\"],\r\n columns=['Activity_label'], aggfunc={\"Activity\": \"count\"}, fill_value=0).sum(axis=1).cumsum().values\r\nactivityCentre_timeline = dfc.pivot_table(values='Activity', index=[\"activity_date\"],\r\n columns=['Activity_label'], aggfunc={\"Activity\": \"count\"}, fill_value=0)\r\n\r\ndfc[\"Activity\"] = [x.strip(' ') for x in dfc[\"Activity\"]]\r\ndfc[\"Activity_label\"] = dfc[\"Activity\"]\r\n\r\nmy_dict = {}\r\nfor i in dfc[\"Activity\"].unique():\r\n my_dict[f\"{i}\"] = dfc.pivot_table(values='Activity', index=[\"activity_date\"],\r\n columns=['Activity_label'], aggfunc={\"Activity\": \"count\"}, fill_value=0)[i].values\r\n\r\n\r\noptions = [{\"label\": i, \"value\": i}\r\n for i in my_dict.keys()]\r\noptions2 = [{\"label\": i, \"value\": i}\r\n for i in dfp[\"Year\"].unique()[:3].astype(int)]\r\nfeatures = dfc.select_dtypes(exclude=[object]).columns.drop([\"Latitude\",\r\n \"Longitude\",\r\n \"activity_date\",\r\n 'year',\r\n \"month\",\r\n \"day\"])\r\ndfc[features] = dfc[features].astype('int64')\r\n\r\noptions3 = [{\"label\": i, \"value\": i}\r\n for i in dfc[features].astype(int)]\r\npivot_df = pd.pivot_table(dfc, values=dfc[features],\r\n index=[\"Latitude\", \"Longitude\"],\r\n aggfunc=\"sum\").reset_index(level=[0, 1])\r\nfeatures\r\n\r\nbarchart = go.Figure(\r\n data=[go.Bar(\r\n x=activity_values,\r\n y=activity_list,\r\n orientation='h')],\r\n layout=go.Layout(\r\n title=go.layout.Title(\r\n text=\"Distribution of Total Shifts by Activity Centre\"),\r\n title_x=0.5))\r\n\r\n\r\nbarchart_df = dfp.loc[dfp[\"Year\"] == 2019].groupby(\r\n \"Year\")[\"Ethnicity\"].value_counts(normalize=True, ascending=True)*100\r\nbarchart_df2 = dfp.loc[dfp[\"Year\"] == 2020].groupby(\r\n \"Year\")[\"Ethnicity\"].value_counts(normalize=True, ascending=True)*100\r\nbarchart_df3 = dfp.loc[dfp[\"Year\"] == 2021].groupby(\r\n \"Year\")[\"Ethnicity\"].value_counts(normalize=True, ascending=True)*100\r\nbarchart_df = barchart_df.to_frame()\r\nbarchart_df2 = barchart_df2.to_frame()\r\nbarchart_df3 = barchart_df3.to_frame()\r\n\r\nbarchart_df.rename(columns={\"Ethnicity\": \"Ethnicity_pct\"}, inplace=True)\r\nbarchart_df2.rename(columns={\"Ethnicity\": \"Ethnicity_pct\"}, inplace=True)\r\nbarchart_df3.rename(columns={\"Ethnicity\": \"Ethnicity_pct\"}, inplace=True)\r\nbarchart_df.reset_index(level=[0, 1], inplace=True)\r\nbarchart_df2.reset_index(level=[0, 1], inplace=True)\r\nbarchart_df3.reset_index(level=[0, 1], inplace=True)\r\nbarchart_df[\"Ethnicity_cnt\"] = dfp.loc[dfp[\"Year\"] == 2019].groupby(\r\n \"Year\")[\"Ethnicity\"].value_counts(ascending=True).values\r\nbarchart_df2[\"Ethnicity_cnt\"] = dfp.loc[dfp[\"Year\"] == 2020].groupby(\r\n \"Year\")[\"Ethnicity\"].value_counts(ascending=True).values\r\nbarchart_df2\r\nbarchart_df3[\"Ethnicity_cnt\"] = dfp.loc[dfp[\"Year\"] == 2021].groupby(\r\n \"Year\")[\"Ethnicity\"].value_counts(ascending=True).values\r\nbarchart_df3.shape\r\n\r\nethnicity_2019 = px.bar(barchart_df,\r\n x=barchart_df[\"Ethnicity_pct\"],\r\n y=barchart_df[\"Ethnicity\"],\r\n orientation='h',\r\n hover_data=[\"Ethnicity_cnt\"],\r\n hover_name=\"Ethnicity\",\r\n labels={})\r\nethnicity_2020 = px.bar(barchart_df2,\r\n x=barchart_df2[\"Ethnicity_pct\"],\r\n y=barchart_df2[\"Ethnicity\"],\r\n orientation='h',\r\n hover_data=[\"Ethnicity_cnt\"],\r\n hover_name=\"Ethnicity\",\r\n labels={})\r\nethnicity_2021 = px.bar(barchart_df3,\r\n x=barchart_df3[\"Ethnicity_pct\"],\r\n y=barchart_df3[\"Ethnicity\"],\r\n orientation='h',\r\n hover_data=[\"Ethnicity_cnt\"],\r\n hover_name=\"Ethnicity\",\r\n labels={})\r\n\r\n\r\napp = dash.Dash(\r\n __name__, external_stylesheets=[\r\n dbc.themes.SUPERHERO]) # , suppress_callback_exceptions=True)\r\n\r\nserver = app.server\r\n\r\n# Build Layout **\r\napp.layout = dbc.Container(\r\n [dbc.Container(\r\n [html.H1(\r\n \"Sunny Streets Dashboard\",\r\n style={\"background-color\": \"#33CCCC\",\r\n \"textAlign\": \"center\"},\r\n className=\"display-3\"),\r\n html.Img(\r\n src=\"https://raw.githubusercontent.com/pierreolivierbonin/test_dash_app/main/vfsg_logo_light.png\",\r\n style={\"maxHeight\": \"800px\",\r\n \"maxWidth\": \"400px\"}\r\n )\r\n ],\r\n className=\"p-5 bg-light rounded-1 mt-3 mb-5 h-50\",\r\n ),\r\n dbc.Row(\r\n [\r\n dbc.Col(\r\n [\r\n html.Div([\r\n\r\n html.H3(\"Question 1a:\"),\r\n html.P(\"How have the services changed since 2019?\",\r\n style={\"fontSize\": 20}),\r\n html.H5('Select one or compare across locations:',\r\n style={\"paddingRight\": \"0px\"}),\r\n html.Div([\r\n\r\n dcc.Dropdown(id='my_dropdown',\r\n value=[\"Gympie\"],\r\n options=options,\r\n multi=True,\r\n placeholder=\"Select an activity centre\")\r\n ], style={'color': '#212121', \"fontSize\": 20, \"display\": \"inline-block\", \"verticalAlign\": \"top\", \"width\": \"100%\"}),\r\n html.Div([\r\n dcc.Graph(id=\"my_graph\"\r\n )], style={\"fontSize\": 20, \"verticalAlign\": \"top\", \"width\": \"100%\", \"paddingBottom\": \"30px\"}\r\n )\r\n ]\r\n )\r\n ],\r\n width=5,\r\n ),\r\n dbc.Col([\r\n html.Div([\r\n html.H3(\"Question 1b:\"),\r\n html.P(\r\n \"How do activity centres compare in terms of total shifts?\"),\r\n html.H5('Examine the distribution:',\r\n style={\"paddingRight\": \"0px\", \"width\": \"100%\"}),\r\n dcc.Graph(id=\"my_graph2\",\r\n figure=barchart)\r\n ], style={\"fontSize\": 20, \"display\": \"inline-block\", \"verticalAlign\": \"center\", \"paddingRight\": \"0px\", \"paddingLeft\": \"0px\", \"width\": \"100%\"}),\r\n\r\n ],\r\n width=5,\r\n )\r\n ], justify=\"center\"\r\n ), dbc.Row([\r\n dbc.Col([\r\n html.H3(\"Question 2:\"),\r\n html.P(\"How have the patient demographics changed since 2019?\",\r\n style={\"fontSize\": 20}),\r\n html.H5('Select a year to examine the distribution:',\r\n style={\"paddingRight\": \"0px\"}),\r\n html.Div([\r\n dcc.Dropdown(id='my_dropdown2',\r\n value=2019,\r\n options=options2,\r\n multi=False,\r\n placeholder=\"Select a year\")\r\n ], style={'color': '#212121', \"fontSize\": 20, \"display\": \"inline-block\", \"verticalAlign\": \"top\", \"width\": \"100%\"}),\r\n html.Div([\r\n dcc.Graph(id=\"my_graph3\"\r\n )], style={\"fontSize\": 20, \"verticalAlign\": \"top\", \"width\": \"100%\", \"paddingBottom\": \"30px\"}\r\n )], width=5\r\n ),\r\n dbc.Col(\r\n [html.Br(),\r\n html.Br(),\r\n html.Br(),\r\n html.H5('Examine the geographic distribution of interventions:',\r\n style={\"paddingRight\": \"0px\"}),\r\n html.Div([\r\n dcc.Dropdown(id='my_dropdown3',\r\n value=\"Length minutes\",\r\n options=options3,\r\n multi=False,\r\n placeholder=\"Select a feature\")\r\n ], style={'color': '#212121', \"fontSize\": 20, \"display\": \"inline-block\", \"verticalAlign\": \"top\", \"width\": \"100%\"}),\r\n dcc.Graph(\r\n id=\"map2\")\r\n ],\r\n width=5,\r\n )\r\n\r\n ], justify=\"center\"\r\n )\r\n\r\n ], fluid=True)\r\n\r\n\r\n@ app.callback(\r\n Output('my_graph', 'figure'),\r\n [Input(\"my_dropdown\", \"value\")],\r\n prevent_initial_call=False\r\n)\r\ndef update_graph(option_slctd):\r\n color_palette = [\"cyan\", \"darkblue\", \"darkcyan\", \"darkgoldenrod\", \"darkgrey\", \"darkgreen\", \"darkmagenta\", \"darkolivegreen\",\r\n \"darkorange\", \"darkorchid\", \"darkred\", \"darksalmon\", \"darkseagreen\", \"darkslateblue\", \"darkslategrey\", \"darkturquoise\", \"darkviolet\", \"deeppink\", \"deepskyblue\"]\r\n date_list = activityCentre_timeline.index\r\n my_dict = {}\r\n for i in dfc[\"Activity\"].unique():\r\n my_dict[f\"{i}\"] = dfc.pivot_table(values='Activity', index=[\"activity_date\"],\r\n columns=['Activity_label'], aggfunc={\"Activity\": \"count\"}, fill_value=0)[i].values\r\n traces = []\r\n for option, color in zip(option_slctd, color_palette):\r\n traces.append(go.Scatter(x=date_list,\r\n y=my_dict[option].cumsum(),\r\n marker_color=color,\r\n name=option))\r\n fig = {\r\n 'data': traces,\r\n 'layout': {\"title\": \"Cumulative Distribution of Shifts Over Time\",\r\n \"title_x\": 0.5\r\n }\r\n }\r\n\r\n return fig\r\n\r\n\r\n@ app.callback(\r\n Output('my_graph3', 'figure'),\r\n [Input(\"my_dropdown2\", \"value\")],\r\n prevent_initial_call=False\r\n)\r\ndef update_graph(option_slctd):\r\n if option_slctd == 2019:\r\n fig1 = ethnicity_2019\r\n fig1.update_layout({\"yaxis\": {\"title\": \"\", \"visible\": True},\r\n \"xaxis\": {\"title\": \"Percentage (%)\"}})\r\n return fig1\r\n elif option_slctd == 2020:\r\n fig2 = ethnicity_2020\r\n fig2.update_layout({\"yaxis\": {\"title\": \"\", \"visible\": True},\r\n \"xaxis\": {\"title\": \"Percentage (%)\"}})\r\n return fig2\r\n elif option_slctd == 2021:\r\n fig3 = ethnicity_2021\r\n fig3.update_layout({\"yaxis\": {\"title\": \"\", \"visible\": True},\r\n \"xaxis\": {\"title\": \"Percentage (%)\"}})\r\n return fig3\r\n\r\n\r\n@ app.callback(\r\n Output('map2', 'figure'),\r\n [Input(\"my_dropdown3\", \"value\")],\r\n prevent_initial_call=False\r\n)\r\ndef update_graph(option_slctd):\r\n px.set_mapbox_access_token(open(\"myToken.mapbox_token\").read())\r\n fig = px.scatter_mapbox(pivot_df,\r\n lat=\"Latitude\",\r\n lon=\"Longitude\",\r\n hover_data={\r\n f\"{option_slctd}\": True,\r\n \"Longitude\": False,\r\n \"Latitude\": False,\r\n },\r\n color=option_slctd,\r\n size=option_slctd,\r\n size_max=30,\r\n zoom=6,\r\n labels={option_slctd: option_slctd},\r\n mapbox_style=\"dark\")\r\n fig.update_layout(margin=dict(l=0, r=0, b=0, t=0))\r\n return fig\r\n\r\n\r\nif __name__ == '__main__':\r\n app.run_server(debug=True)\r\n"
] | [
[
"pandas.read_csv",
"pandas.to_datetime",
"pandas.pivot_table"
]
] |
morristai/qlib | [
"c459f9b5378ce6bd2395593a57be70c956b6ce04"
] | [
"qlib/contrib/estimator/estimator.py"
] | [
"# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n\n# coding=utf-8\n\nimport pandas as pd\n\nimport os\nimport copy\nimport json\nimport yaml\nimport pickle\n\nimport qlib\nfrom ..evaluate import risk_analysis\nfrom ..evaluate import backtest as normal_backtest\nfrom ..evaluate import long_short_backtest\nfrom .config import ExperimentConfig\nfrom .fetcher import create_fetcher_with_config\n\nfrom ...log import get_module_logger, TimeInspector\nfrom ...utils import get_module_by_module_path, compare_dict_value\n\n\nclass Estimator(object):\n def __init__(self, config_manager, sacred_ex):\n\n # Set logger.\n self.logger = get_module_logger(\"Estimator\")\n\n # 1. Set config manager.\n self.config_manager = config_manager\n\n # 2. Set configs.\n self.ex_config = config_manager.ex_config\n self.data_config = config_manager.data_config\n self.model_config = config_manager.model_config\n self.trainer_config = config_manager.trainer_config\n self.strategy_config = config_manager.strategy_config\n self.backtest_config = config_manager.backtest_config\n\n # If experiment.mode is test or experiment.finetune is True, load the experimental results in the loader\n if self.ex_config.mode == self.ex_config.TEST_MODE or self.ex_config.finetune:\n self.compare_config_with_config_manger(self.config_manager)\n\n # 3. Set sacred_experiment.\n self.ex = sacred_ex\n\n # 4. Init data handler.\n self.data_handler = None\n self._init_data_handler()\n\n # 5. Init trainer.\n self.trainer = None\n self._init_trainer()\n\n # 6. Init strategy.\n self.strategy = None\n self._init_strategy()\n\n def _init_data_handler(self):\n handler_module = get_module_by_module_path(self.data_config.handler_module_path)\n\n # Set market\n market = self.data_config.handler_filter.get(\"market\", None)\n if market is None:\n if \"market\" in self.data_config.handler_parameters:\n self.logger.warning(\n \"Warning: The market in data.args section is deprecated. \"\n \"It only works when market is not set in data.filter section. \"\n \"It will be overridden by market in the data.filter section.\"\n )\n market = self.data_config.handler_parameters[\"market\"]\n else:\n market = \"csi500\"\n\n self.data_config.handler_parameters[\"market\"] = market\n\n data_filter_list = []\n handler_filters = self.data_config.handler_filter.get(\"filter_pipeline\", list())\n for h_filter in handler_filters:\n filter_module_path = h_filter.get(\"module_path\", \"qlib.data.filter\")\n filter_class_name = h_filter.get(\"class\", \"\")\n filter_parameters = h_filter.get(\"args\", {})\n filter_module = get_module_by_module_path(filter_module_path)\n filter_class = getattr(filter_module, filter_class_name)\n data_filter = filter_class(**filter_parameters)\n data_filter_list.append(data_filter)\n\n self.data_config.handler_parameters[\"data_filter_list\"] = data_filter_list\n handler_class = getattr(handler_module, self.data_config.handler_class)\n self.data_handler = handler_class(**self.data_config.handler_parameters)\n\n def _init_trainer(self):\n\n model_module = get_module_by_module_path(self.model_config.model_module_path)\n trainer_module = get_module_by_module_path(self.trainer_config.trainer_module_path)\n model_class = getattr(model_module, self.model_config.model_class)\n trainer_class = getattr(trainer_module, self.trainer_config.trainer_class)\n\n self.trainer = trainer_class(\n model_class,\n self.model_config.save_path,\n self.model_config.parameters,\n self.data_handler,\n self.ex,\n **self.trainer_config.parameters\n )\n\n def _init_strategy(self):\n\n module = get_module_by_module_path(self.strategy_config.strategy_module_path)\n strategy_class = getattr(module, self.strategy_config.strategy_class)\n self.strategy = strategy_class(**self.strategy_config.parameters)\n\n def run(self):\n if self.ex_config.mode == ExperimentConfig.TRAIN_MODE:\n self.trainer.train()\n elif self.ex_config.mode == ExperimentConfig.TEST_MODE:\n self.trainer.load()\n else:\n raise ValueError(\"unexpected mode: %s\" % self.ex_config.mode)\n analysis = self.backtest()\n print(analysis)\n self.logger.info(\n \"experiment id: {}, experiment name: {}\".format(self.ex.experiment.current_run._id, self.ex_config.name)\n )\n\n # Remove temp dir\n # shutil.rmtree(self.ex_config.tmp_run_dir)\n\n def backtest(self):\n TimeInspector.set_time_mark()\n # 1. Get pred and prediction score of model(s).\n pred = self.trainer.get_test_score()\n try:\n performance = self.trainer.get_test_performance()\n except NotImplementedError:\n performance = None\n # 2. Normal Backtest.\n report_normal, positions_normal = self._normal_backtest(pred)\n # 3. Long-Short Backtest.\n # Deprecated\n # long_short_reports = self._long_short_backtest(pred)\n # 4. Analyze\n analysis_df = self._analyze(report_normal)\n # 5. Save.\n self._save_backtest_result(\n pred,\n analysis_df,\n positions_normal,\n report_normal,\n # long_short_reports,\n performance,\n )\n return analysis_df\n\n def _normal_backtest(self, pred):\n TimeInspector.set_time_mark()\n if \"account\" not in self.backtest_config.normal_backtest_parameters:\n if \"account\" in self.strategy_config.parameters:\n self.logger.warning(\n \"Warning: The account in strategy section is deprecated. \"\n \"It only works when account is not set in backtest section. \"\n \"It will be overridden by account in the backtest section.\"\n )\n self.backtest_config.normal_backtest_parameters[\"account\"] = self.strategy_config.parameters[\"account\"]\n report_normal, positions_normal = normal_backtest(\n pred, strategy=self.strategy, **self.backtest_config.normal_backtest_parameters\n )\n TimeInspector.log_cost_time(\"Finished normal backtest.\")\n return report_normal, positions_normal\n\n def _long_short_backtest(self, pred):\n TimeInspector.set_time_mark()\n long_short_reports = long_short_backtest(pred, **self.backtest_config.long_short_backtest_parameters)\n TimeInspector.log_cost_time(\"Finished long-short backtest.\")\n return long_short_reports\n\n @staticmethod\n def _analyze(report_normal):\n TimeInspector.set_time_mark()\n\n analysis = dict()\n # analysis[\"pred_long\"] = risk_analysis(long_short_reports[\"long\"])\n # analysis[\"pred_short\"] = risk_analysis(long_short_reports[\"short\"])\n # analysis[\"pred_long_short\"] = risk_analysis(long_short_reports[\"long_short\"])\n analysis[\"excess_return_without_cost\"] = risk_analysis(report_normal[\"return\"] - report_normal[\"bench\"])\n analysis[\"excess_return_with_cost\"] = risk_analysis(report_normal[\"return\"] - report_normal[\"bench\"] - report_normal[\"cost\"])\n analysis_df = pd.concat(analysis) # type: pd.DataFrame\n TimeInspector.log_cost_time(\n \"Finished generating analysis,\" \" average turnover is: {0:.4f}.\".format(report_normal[\"turnover\"].mean())\n )\n return analysis_df\n\n def _save_backtest_result(self, pred, analysis, positions, report_normal, performance):\n # 1. Result dir.\n result_dir = os.path.join(self.config_manager.ex_config.tmp_run_dir, \"result\")\n if not os.path.exists(result_dir):\n os.makedirs(result_dir)\n\n self.ex.add_info(\n \"task_config\",\n json.loads(json.dumps(self.config_manager.config, default=str)),\n )\n\n # 2. Pred.\n TimeInspector.set_time_mark()\n pred_pkl_path = os.path.join(result_dir, \"pred.pkl\")\n pred.to_pickle(pred_pkl_path)\n self.ex.add_artifact(pred_pkl_path)\n TimeInspector.log_cost_time(\"Finished saving pred.pkl to: {}\".format(pred_pkl_path))\n\n # 3. Ana.\n TimeInspector.set_time_mark()\n analysis_pkl_path = os.path.join(result_dir, \"analysis.pkl\")\n analysis.to_pickle(analysis_pkl_path)\n self.ex.add_artifact(analysis_pkl_path)\n TimeInspector.log_cost_time(\"Finished saving analysis.pkl to: {}\".format(analysis_pkl_path))\n\n # 4. Pos.\n TimeInspector.set_time_mark()\n positions_pkl_path = os.path.join(result_dir, \"positions.pkl\")\n with open(positions_pkl_path, \"wb\") as fp:\n pickle.dump(positions, fp)\n self.ex.add_artifact(positions_pkl_path)\n TimeInspector.log_cost_time(\"Finished saving positions.pkl to: {}\".format(positions_pkl_path))\n\n # 5. Report normal.\n TimeInspector.set_time_mark()\n report_normal_pkl_path = os.path.join(result_dir, \"report_normal.pkl\")\n report_normal.to_pickle(report_normal_pkl_path)\n self.ex.add_artifact(report_normal_pkl_path)\n TimeInspector.log_cost_time(\"Finished saving report_normal.pkl to: {}\".format(report_normal_pkl_path))\n\n # 6. Report long short.\n # Deprecated\n # for k, name in zip(\n # [\"long\", \"short\", \"long_short\"],\n # [\"report_long.pkl\", \"report_short.pkl\", \"report_long_short.pkl\"],\n # ):\n # TimeInspector.set_time_mark()\n # pkl_path = os.path.join(result_dir, name)\n # long_short_reports[k].to_pickle(pkl_path)\n # self.ex.add_artifact(pkl_path)\n # TimeInspector.log_cost_time(\"Finished saving {} to: {}\".format(name, pkl_path))\n\n # 7. Origin test label.\n TimeInspector.set_time_mark()\n label_pkl_path = os.path.join(result_dir, \"label.pkl\")\n self.data_handler.get_origin_test_label_with_date(\n self.trainer_config.parameters[\"test_start_date\"],\n self.trainer_config.parameters[\"test_end_date\"],\n ).to_pickle(label_pkl_path)\n self.ex.add_artifact(label_pkl_path)\n TimeInspector.log_cost_time(\"Finished saving label.pkl to: {}\".format(label_pkl_path))\n\n # 8. Experiment info, save the model(s) performance here.\n TimeInspector.set_time_mark()\n cur_ex_id = self.ex.experiment.current_run._id\n exp_info = {\n \"id\": cur_ex_id,\n \"name\": self.ex_config.name,\n \"performance\": performance,\n \"observer_type\": self.ex_config.observer_type,\n }\n\n if self.ex_config.observer_type == ExperimentConfig.OBSERVER_MONGO:\n exp_info.update(\n {\n \"mongo_url\": self.ex_config.mongo_url,\n \"db_name\": self.ex_config.db_name,\n }\n )\n else:\n exp_info.update({\"dir\": self.ex_config.global_dir})\n\n with open(self.ex_config.exp_info_path, \"w\") as fp:\n json.dump(exp_info, fp, indent=4, sort_keys=True)\n self.ex.add_artifact(self.ex_config.exp_info_path)\n TimeInspector.log_cost_time(\"Finished saving ex_info to: {}\".format(self.ex_config.exp_info_path))\n\n @staticmethod\n def compare_config_with_config_manger(config_manager):\n \"\"\"Compare loader model args and current config with ConfigManage\n\n :param config_manager: ConfigManager\n :return:\n \"\"\"\n fetcher = create_fetcher_with_config(config_manager, load_form_loader=True)\n loader_mode_config = fetcher.get_experiment(\n exp_name=config_manager.ex_config.loader_name,\n exp_id=config_manager.ex_config.loader_id,\n fields=[\"task_config\"],\n )[\"task_config\"]\n with open(config_manager.config_path) as fp:\n current_config = yaml.load(fp.read())\n current_config = json.loads(json.dumps(current_config, default=str))\n\n logger = get_module_logger(\"Estimator\")\n\n loader_mode_config = copy.deepcopy(loader_mode_config)\n current_config = copy.deepcopy(current_config)\n\n # Require test_mode_config.test_start_date <= current_config.test_start_date\n loader_trainer_args = loader_mode_config.get(\"trainer\", {}).get(\"args\", {})\n cur_trainer_args = current_config.get(\"trainer\", {}).get(\"args\", {})\n loader_start_date = loader_trainer_args.pop(\"test_start_date\")\n cur_test_start_date = cur_trainer_args.pop(\"test_start_date\")\n assert (\n loader_start_date <= cur_test_start_date\n ), \"Require: loader_mode_config.test_start_date <= current_config.test_start_date\"\n\n # TODO: For the user's own extended `Trainer`, the support is not very good\n if \"RollingTrainer\" == current_config.get(\"trainer\", {}).get(\"class\", None):\n loader_period = loader_trainer_args.pop(\"rolling_period\")\n cur_period = cur_trainer_args.pop(\"rolling_period\")\n assert (\n loader_period == cur_period\n ), \"Require: loader_mode_config.rolling_period == current_config.rolling_period\"\n\n compare_section = [\"trainer\", \"model\", \"data\"]\n for section in compare_section:\n changes = compare_dict_value(loader_mode_config.get(section, {}), current_config.get(section, {}))\n if changes:\n logger.warning(\"Warning: Loader mode config and current config, `{}` are different:\\n\".format(section))\n"
] | [
[
"pandas.concat"
]
] |
rolandqli/arkouda | [
"d5bc98177c74338cea829e98cd3efa318c9aa76e"
] | [
"benchmarks/reduce.py"
] | [
"#!/usr/bin/env python3 \n\nimport time, argparse\nimport numpy as np\nimport arkouda as ak\n\nOPS = ('sum', 'prod', 'min', 'max')\n\ndef time_ak_reduce(N_per_locale, trials, dtype, random):\n print(\">>> arkouda reduce\")\n cfg = ak.get_config()\n N = N_per_locale * cfg[\"numLocales\"]\n print(\"numLocales = {}, N = {:,}\".format(cfg[\"numLocales\"], N))\n if random:\n if dtype == 'int64':\n a = ak.randint(0, 2**32, N)\n elif dtype == 'float64':\n a = ak.randint(0, 1, N, dtype=ak.float64)\n else:\n a = ak.arange(0, N, 1)\n if dtype == 'float64':\n a = 1.0 * a\n \n timings = {op: [] for op in OPS}\n results = {}\n for i in range(trials):\n for op in timings.keys():\n fxn = getattr(a, op)\n start = time.time()\n r = fxn()\n end = time.time()\n timings[op].append(end - start)\n results[op] = r\n tavg = {op: sum(t) / trials for op, t in timings.items()}\n\n for op, t in tavg.items():\n print(\"{} = {}\".format(op, results[op]))\n print(\" {} Average time = {:.4f} sec\".format(op, t))\n bytes_per_sec = (a.size * a.itemsize) / t\n print(\" {} Average rate = {:.2f} GiB/sec\".format(op, bytes_per_sec/2**30))\n\ndef time_np_reduce(N, trials, dtype, random):\n print(\">>> numpy reduce\")\n print(\"N = {:,}\".format(N))\n if random:\n if dtype == 'int64':\n a = np.random.randint(0, 2**32, N)\n elif dtype == 'float64':\n a = np.random.random(N)\n else: \n a = np.arange(0, N, 1, dtype=dtype)\n \n timings = {op: [] for op in OPS}\n results = {}\n for i in range(trials):\n for op in timings.keys():\n fxn = getattr(a, op)\n start = time.time()\n r = fxn()\n end = time.time()\n timings[op].append(end - start)\n results[op] = r\n tavg = {op: sum(t) / trials for op, t in timings.items()}\n\n for op, t in tavg.items():\n print(\"{} = {}\".format(op, results[op]))\n print(\" {} Average time = {:.4f} sec\".format(op, t))\n bytes_per_sec = (a.size * a.itemsize) / t\n print(\" {} Average rate = {:.2f} GiB/sec\".format(op, bytes_per_sec/2**30))\n\ndef check_correctness(dtype, random):\n N = 10**4\n if random:\n if dtype == 'int64':\n a = np.random.randint(0, 2**32, N)\n elif dtype == 'float64':\n a = np.random.random(N)\n else:\n if dtype == 'int64':\n a = np.arange(0, N, 1, dtype=dtype)\n elif dtype == 'float64':\n a = np.arange(1, 1+1/N, (1/N)/N, dtype=dtype)\n\n for op in OPS:\n npa = a\n aka = ak.array(a)\n fxn = getattr(npa, op)\n npr = fxn()\n fxn = getattr(aka, op)\n akr = fxn()\n assert np.isclose(npr, akr)\n\ndef create_parser():\n parser = argparse.ArgumentParser(description=\"Measure performance of reductions over arrays.\")\n parser.add_argument('hostname', help='Hostname of arkouda server')\n parser.add_argument('port', type=int, help='Port of arkouda server')\n parser.add_argument('-n', '--size', type=int, default=10**8, help='Problem size: length of array to reduce')\n parser.add_argument('-t', '--trials', type=int, default=6, help='Number of times to run the benchmark')\n parser.add_argument('-d', '--dtype', default='int64', help='Dtype of array (int64 or float64)')\n parser.add_argument('-r', '--randomize', default=False, action='store_true', help='Fill array with random values instead of range')\n parser.add_argument('--numpy', default=False, action='store_true', help='Run the same operation in NumPy to compare performance.')\n parser.add_argument('--correctness-only', default=False, action='store_true', help='Only check correctness, not performance.')\n return parser\n \nif __name__ == \"__main__\":\n import sys\n parser = create_parser()\n args = parser.parse_args()\n if args.dtype not in ('int64', 'float64'):\n raise ValueError(\"Dtype must be either int64 or float64, not {}\".format(args.dtype))\n ak.verbose = False\n ak.connect(args.hostname, args.port)\n\n if args.correctness_only:\n check_correctness(args.dtype, args.randomize)\n sys.exit(0)\n \n print(\"array size = {:,}\".format(args.size))\n print(\"number of trials = \", args.trials)\n time_ak_reduce(args.size, args.trials, args.dtype, args.randomize)\n if args.numpy:\n time_np_reduce(args.size, args.trials, args.dtype, args.randomize)\n sys.exit(0)\n"
] | [
[
"numpy.arange",
"numpy.random.random",
"numpy.random.randint",
"numpy.isclose"
]
] |
sethah/deeptennis | [
"a689c5f1d6f5ff1d665aec99b8db6262d3442c3a"
] | [
"scripts/make_tracking_video.py"
] | [
"import argparse\nfrom typing import List\n\nimport cv2\nimport numpy as np\nfrom typing import NamedTuple, Tuple\nimport logging\nimport json\nimport os\nfrom pathlib import Path\nimport tqdm\nimport shutil\n\nimport deeptennis.utils as utils\n\n\nclass Box(NamedTuple):\n score: float\n coords: np.ndarray\n name: str\n\n\ndef choose_player_boxes(boxes: List[Box],\n halfway_point: float,\n min_score: float = 0.0) -> Tuple[Box, Box]:\n top_boxes = [b for b in boxes if (b.coords[3] <= halfway_point) and (b.score > min_score)]\n bottom_boxes = [b for b in boxes if (b.coords[3] > halfway_point) and (b.score > min_score)]\n srtd_top = sorted(top_boxes, key=lambda x: -x.score)\n srtd_bottom = sorted(bottom_boxes, key=lambda x: -x.score)\n top = None if len(srtd_top) == 0 else srtd_top[0]\n bottom = None if len(srtd_bottom) == 0 else srtd_bottom[0]\n return top, bottom\n\n\ndef tennis_rectangles():\n outer_court = [0, 0, 36, 78]\n inner_court = [4.5, 0, 27, 78]\n service1 = [4.5, 18, 13.5, 21]\n service2 = [18, 18, 13.5, 21]\n service3 = [4.5, 39, 13.5, 21]\n service4 = [18, 39, 13.5, 21]\n rects = [outer_court, inner_court, service1, service2, service3, service4]\n return rects\n\n\ndef player_boxes_to_court_points(box: np.ndarray, M: np.ndarray) -> np.ndarray:\n points = np.stack([(box[:, 2] - box[:, 0]) / 2 + box[:, 0], box[:, 3], np.ones(box.shape[0])], axis=0)\n converted_points = image_point_to_court_point(points, M)\n return converted_points\n\n\ndef image_point_to_court_point(points, M, inverse=True):\n if inverse:\n M = np.linalg.inv(M)\n transf_homg_point = M.dot(points)\n transf_homg_point /= transf_homg_point[2]\n return transf_homg_point[:2, :]\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--save-path\", type=str, default=None)\n parser.add_argument(\"--tracking-path\", type=str)\n parser.add_argument(\"--frame-path\", type=str)\n\n args = parser.parse_args()\n\n save_path = Path(args.save_path)\n frame_path = Path(args.frame_path)\n tracking_path = Path(args.tracking_path)\n\n tracking_js = utils.read_json_lines(tracking_path)\n frames = sorted(frame_path.iterdir())\n\n clip_video_path = save_path / \"images\"\n clip_video_path.mkdir(parents=True, exist_ok=True)\n\n json_dict = {\n 'image_paths': [],\n 'is_action': [],\n 'top_player': {\n 'position': [],\n 'box': [],\n 'position_unwarped': [],\n 'confidence': [],\n },\n 'bottom_player': {\n 'position': [],\n 'box': [],\n 'position_unwarped': [],\n 'confidence': [],\n },\n 'court': {\n 'lower_left': [],\n 'lower_right': [],\n 'upper_right': [],\n 'upper_left': [],\n 'confidence': []\n }\n }\n for j, tracking in tqdm.tqdm(enumerate(tracking_js)):\n img_scale = np.array([640 / 512, 360 / 512])\n json_dict['image_paths'].append(str(frames[j].name))\n boxes: List[Box] = [Box(score, (np.array(coords).reshape(2, 2) * img_scale).ravel(), name) for score, coords, name in zip(tracking['box_scores'],\n tracking['box_proposals'],\n tracking['box_class'])]\n player_boxes = [box for box in boxes if box.name == 'player']\n court_boxes = [box for box in boxes if box.name == 'court']\n court_keypoints = np.array(tracking['keypoint_proposals'])\n keypoint_scores = np.array(tracking['keypoint_scores'])\n\n if len(court_boxes) > 0:\n best_court_box = max(court_boxes, key=lambda b: b.score)\n if best_court_box.score > 0.8:\n json_dict['is_action'].append(True)\n else:\n json_dict['is_action'].append(False)\n else:\n json_dict['is_action'].append(False)\n is_action = json_dict['is_action'][-1]\n if keypoint_scores.shape[0] > 0 and is_action:\n best_kp_index = keypoint_scores.sum(axis=1).argmax()\n _court = court_keypoints[best_kp_index]\n _court = _court.reshape(4, 3)[:, :2][[0, 1, 3, 2]]\n _court = _court * np.array([640 / 512, 360 / 512])\n json_dict['court']['lower_left'].append(tuple([int(x) for x in _court[0]]))\n json_dict['court']['lower_right'].append(tuple([int(x) for x in _court[1]]))\n json_dict['court']['upper_left'].append(tuple([int(x) for x in _court[2]]))\n json_dict['court']['upper_right'].append(tuple([int(x) for x in _court[3]]))\n json_dict['court']['confidence'].append(float(keypoint_scores.sum(axis=1)[best_kp_index]))\n else:\n _court = None\n json_dict['court']['lower_left'].append((-1, -1))\n json_dict['court']['lower_right'].append((-1, -1))\n json_dict['court']['upper_left'].append((-1, -1))\n json_dict['court']['upper_right'].append((-1, -1))\n json_dict['court']['confidence'].append(-1)\n\n if _court is not None:\n true_court = np.array([\n [0, 0],\n [36, 0],\n [36, 78],\n [0, 78]\n ])\n sorted_x = sorted(_court, key=lambda x: x[0])\n bottom_left = max(sorted_x[:2], key=lambda x: x[1])\n top_left = min(sorted_x[:2], key=lambda x: x[1])\n bottom_right = max(sorted_x[2:], key=lambda x: x[1])\n top_right = min(sorted_x[2:], key=lambda x: x[1])\n _court = [bottom_left, bottom_right, top_right, top_left]\n M = cv2.getPerspectiveTransform(true_court.astype(np.float32),\n np.array(_court).reshape(4, 2).astype(np.float32))\n halfway_point = image_point_to_court_point(np.array([0, 78 // 2, 1]).reshape(1, -1).T,\n M, inverse=False)\n halfway_point = halfway_point.ravel()[1]\n else:\n halfway_point = None\n top_player_box, bottom_player_box = choose_player_boxes(player_boxes, min_score=0.01,\n halfway_point=halfway_point or 360 // 2)\n if top_player_box is not None and is_action:\n x1, y1, x2, y2 = top_player_box.coords\n try:\n player_marker = player_boxes_to_court_points(top_player_box.coords.reshape(1, 4), M)\n xw1, yw1 = player_marker.ravel()\n except:\n xw1, yw1 = 0, 0\n json_dict['top_player']['box'].append([int(z) for z in [x1, y1, x2, y2]])\n json_dict['top_player']['position'].append((int((x1 + x2) / 2), int(y2)))\n json_dict['top_player']['position_unwarped'].append((int(xw1), int(yw1)))\n json_dict['top_player']['confidence'].append(top_player_box.score)\n else:\n json_dict['top_player']['box'].append([-1, -1, -1, -1])\n json_dict['top_player']['position'].append((-1, -1))\n json_dict['top_player']['position_unwarped'].append((-1, -1))\n json_dict['top_player']['confidence'].append(-1)\n if bottom_player_box is not None and is_action:\n x1, y1, x2, y2 = bottom_player_box.coords\n try:\n player_marker = player_boxes_to_court_points(bottom_player_box.coords.reshape(1, 4), M)\n xw1, yw1 = player_marker.ravel()\n except:\n xw1, yw1 = 0, 0\n json_dict['bottom_player']['box'].append([int(z) for z in [x1, y1, x2, y2]])\n json_dict['bottom_player']['position'].append((int((x1 + x2) / 2), int(y2)))\n json_dict['bottom_player']['position_unwarped'].append((int(xw1), int(yw1)))\n json_dict['bottom_player']['confidence'].append(bottom_player_box.score)\n else:\n json_dict['bottom_player']['box'].append([-1, -1, -1, -1])\n json_dict['bottom_player']['position'].append((-1, -1))\n json_dict['bottom_player']['position_unwarped'].append((-1, -1))\n json_dict['bottom_player']['confidence'].append(-1)\n with open(str(save_path / save_path.stem) + \".json\", \"w\") as f:\n json.dump(json_dict, f)\n\n for i in tqdm.tqdm(range(len(frames))):\n\n img = cv2.imread(str(frames[i]))\n if json_dict['is_action'][i]:\n # draw court\n padding = 50\n scale = 2\n img = cv2.rectangle(img, (0, 0), (36 * scale + padding, 78 * scale + padding), (255, 255, 255), cv2.FILLED)\n for rect in tennis_rectangles():\n x, y, w, h = np.int32(rect) * scale\n x += padding // 2\n y += padding // 2\n img = cv2.rectangle(img, (x, y), (x + w, y + h), color=(0, 0, 0), thickness=2)\n\n x, y = json_dict['top_player']['position_unwarped'][i]\n top_valid = (x, y) != (-1, -1)\n if top_valid:\n try:\n img = cv2.circle(img, (x * scale + padding // 2, int(78 - y) * scale + padding // 2), 5, (0, 255, 0), -1)\n except:\n pass\n x, y = json_dict['bottom_player']['position_unwarped'][i]\n bottom_valid = (x, y) != (-1, -1)\n if bottom_valid:\n try:\n img = cv2.circle(img, (x * scale + padding // 2, int(78 - y) * scale + padding // 2), 5, (0, 255, 0), -1)\n except:\n pass\n\n # draw top player box\n if top_valid:\n x1, y1, x2, y2 = json_dict['top_player']['box'][i]\n img = cv2.rectangle(img, (x1, y1), (x2, y2), color=(0, 255, 0), thickness=3)\n text = \"%0.3f\" % json_dict['top_player']['confidence'][i]\n position = (int(x1), int(y2) + 10)\n cv2.putText(img, text, position, cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255,255,255), 2, cv2.LINE_AA)\n\n if bottom_valid:\n # bottom player\n x1, y1, x2, y2 = json_dict['bottom_player']['box'][i]\n img = cv2.rectangle(img, (x1, y1), (x2, y2), color=(0, 255, 0), thickness=3)\n text = \"%0.3f\" % json_dict['bottom_player']['confidence'][i]\n position = (int(x1), int(y2) + 10)\n cv2.putText(img, text, position, cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255,255,255), 2, cv2.LINE_AA)\n\n else:\n pass\n cv2.imwrite(str(clip_video_path / (\"%05d.png\" % i)), img)\n command = f\"ffmpeg -y -r 8 -i {str(clip_video_path)}/%05d.png -c:v libx264 -q:v 2 -vf fps=8 -pix_fmt yuv420p {save_path / save_path.stem}.mp4\"\n print(command)\n os.system(command)\n # shutil.rmtree(str(clip_video_path))\n"
] | [
[
"numpy.linalg.inv",
"numpy.int32",
"numpy.array",
"numpy.ones"
]
] |
brian-j-cao/models | [
"e0ed507504b4efa6780e244677ded563b36b0ee7"
] | [
"official/projects/movinet/tools/export_saved_model.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\n# Lint as: python3\nr\"\"\"Exports models to tf.saved_model.\n\nExport example:\n\n```shell\npython3 export_saved_model.py \\\n --export_path=/tmp/movinet/ \\\n --model_id=a0 \\\n --causal=True \\\n --conv_type=\"3d\" \\\n --num_classes=600 \\\n --use_positional_encoding=False \\\n --checkpoint_path=\"\"\n```\n\nExport for TF Lite example:\n\n```shell\npython3 export_saved_model.py \\\n --model_id=a0 \\\n --causal=True \\\n --conv_type=2plus1d \\\n --se_type=2plus3d \\\n --activation=hard_swish \\\n --gating_activation=hard_sigmoid \\\n --use_positional_encoding=False \\\n --num_classes=600 \\\n --batch_size=1 \\\n --num_frames=1 \\ # Use a single frame for streaming mode\n --image_size=172 \\ # Input resolution for the model\n --bundle_input_init_states_fn=False \\\n --checkpoint_path=/path/to/checkpoint \\\n --export_path=/tmp/movinet_a0_stream\n```\n\nTo use an exported saved_model, refer to export_saved_model_test.py.\n\"\"\"\n\nfrom typing import Optional, Tuple\n\nfrom absl import app\nfrom absl import flags\nimport tensorflow as tf\n\nfrom official.projects.movinet.modeling import movinet\nfrom official.projects.movinet.modeling import movinet_model\n\nflags.DEFINE_string(\n 'export_path', '/tmp/movinet/',\n 'Export path to save the saved_model file.')\nflags.DEFINE_string(\n 'model_id', 'a0', 'MoViNet model name.')\nflags.DEFINE_bool(\n 'causal', False, 'Run the model in causal mode.')\nflags.DEFINE_string(\n 'conv_type', '3d',\n '3d, 2plus1d, or 3d_2plus1d. 3d configures the network '\n 'to use the default 3D convolution. 2plus1d uses (2+1)D convolution '\n 'with Conv2D operations and 2D reshaping (e.g., a 5x3x3 kernel becomes '\n '3x3 followed by 5x1 conv). 3d_2plus1d uses (2+1)D convolution with '\n 'Conv3D and no 2D reshaping (e.g., a 5x3x3 kernel becomes 1x3x3 '\n 'followed by 5x1x1 conv).')\nflags.DEFINE_string(\n 'se_type', '3d',\n '3d, 2d, or 2plus3d. 3d uses the default 3D spatiotemporal global average'\n 'pooling for squeeze excitation. 2d uses 2D spatial global average pooling '\n 'on each frame. 2plus3d concatenates both 3D and 2D global average '\n 'pooling.')\nflags.DEFINE_string(\n 'activation', 'swish',\n 'The main activation to use across layers.')\nflags.DEFINE_string(\n 'classifier_activation', 'swish',\n 'The classifier activation to use.')\nflags.DEFINE_string(\n 'gating_activation', 'sigmoid',\n 'The gating activation to use in squeeze-excitation layers.')\nflags.DEFINE_bool(\n 'use_positional_encoding', False,\n 'Whether to use positional encoding (only applied when causal=True).')\nflags.DEFINE_integer(\n 'num_classes', 600, 'The number of classes for prediction.')\nflags.DEFINE_integer(\n 'batch_size', None,\n 'The batch size of the input. Set to None for dynamic input.')\nflags.DEFINE_integer(\n 'num_frames', None,\n 'The number of frames of the input. Set to None for dynamic input.')\nflags.DEFINE_integer(\n 'image_size', None,\n 'The resolution of the input. Set to None for dynamic input.')\nflags.DEFINE_bool(\n 'bundle_input_init_states_fn', True,\n 'Add init_states as a function signature to the saved model.'\n 'This is not necessary if the input shape is static (e.g., for TF Lite).')\nflags.DEFINE_string(\n 'checkpoint_path', '',\n 'Checkpoint path to load. Leave blank for default initialization.')\n\nFLAGS = flags.FLAGS\n\n\ndef export_saved_model(\n model: tf.keras.Model,\n input_shape: Tuple[int, int, int, int, int],\n export_path: str = '/tmp/movinet/',\n causal: bool = False,\n bundle_input_init_states_fn: bool = True,\n checkpoint_path: Optional[str] = None) -> None:\n \"\"\"Exports a MoViNet model to a saved model.\n\n Args:\n model: the tf.keras.Model to export.\n input_shape: The 5D spatiotemporal input shape of size\n [batch_size, num_frames, image_height, image_width, num_channels].\n Set the field or a shape position in the field to None for dynamic input.\n export_path: Export path to save the saved_model file.\n causal: Run the model in causal mode.\n bundle_input_init_states_fn: Add init_states as a function signature to the\n saved model. This is not necessary if the input shape is static (e.g.,\n for TF Lite).\n checkpoint_path: Checkpoint path to load. Leave blank to keep the model's\n initialization.\n \"\"\"\n\n # Use dimensions of 1 except the channels to export faster,\n # since we only really need the last dimension to build and get the output\n # states. These dimensions can be set to `None` once the model is built.\n input_shape_concrete = [1 if s is None else s for s in input_shape]\n model.build(input_shape_concrete)\n\n # Compile model to generate some internal Keras variables.\n model.compile()\n\n if checkpoint_path:\n checkpoint = tf.train.Checkpoint(model=model)\n status = checkpoint.restore(checkpoint_path)\n status.assert_existing_objects_matched()\n\n if causal:\n # Call the model once to get the output states. Call again with `states`\n # input to ensure that the inputs with the `states` argument is built\n # with the full output state shapes.\n input_image = tf.ones(input_shape_concrete)\n _, states = model({\n **model.init_states(input_shape_concrete), 'image': input_image})\n _ = model({**states, 'image': input_image})\n\n # Create a function to explicitly set the names of the outputs\n def predict(inputs):\n outputs, states = model(inputs)\n return {**states, 'logits': outputs}\n\n specs = {\n name: tf.TensorSpec(spec.shape, name=name, dtype=spec.dtype)\n for name, spec in model.initial_state_specs(\n input_shape).items()\n }\n specs['image'] = tf.TensorSpec(\n input_shape, dtype=model.dtype, name='image')\n\n predict_fn = tf.function(predict, jit_compile=True)\n predict_fn = predict_fn.get_concrete_function(specs)\n\n init_states_fn = tf.function(model.init_states, jit_compile=True)\n init_states_fn = init_states_fn.get_concrete_function(\n tf.TensorSpec([5], dtype=tf.int32))\n\n if bundle_input_init_states_fn:\n signatures = {'call': predict_fn, 'init_states': init_states_fn}\n else:\n signatures = predict_fn\n\n tf.keras.models.save_model(\n model, export_path, signatures=signatures)\n else:\n _ = model(tf.ones(input_shape_concrete))\n tf.keras.models.save_model(model, export_path)\n\n\ndef build_and_export_saved_model(\n export_path: str = '/tmp/movinet/',\n model_id: str = 'a0',\n causal: bool = False,\n conv_type: str = '3d',\n se_type: str = '3d',\n activation: str = 'swish',\n classifier_activation: str = 'swish',\n gating_activation: str = 'sigmoid',\n use_positional_encoding: bool = False,\n num_classes: int = 600,\n input_shape: Optional[Tuple[int, int, int, int, int]] = None,\n bundle_input_init_states_fn: bool = True,\n checkpoint_path: Optional[str] = None) -> None:\n \"\"\"Builds and exports a MoViNet model to a saved model.\n\n Args:\n export_path: Export path to save the saved_model file.\n model_id: MoViNet model name.\n causal: Run the model in causal mode.\n conv_type: 3d, 2plus1d, or 3d_2plus1d. 3d configures the network\n to use the default 3D convolution. 2plus1d uses (2+1)D convolution\n with Conv2D operations and 2D reshaping (e.g., a 5x3x3 kernel becomes\n 3x3 followed by 5x1 conv). 3d_2plus1d uses (2+1)D convolution with\n Conv3D and no 2D reshaping (e.g., a 5x3x3 kernel becomes 1x3x3\n followed by 5x1x1 conv).\n se_type:\n 3d, 2d, or 2plus3d. 3d uses the default 3D spatiotemporal global average\n pooling for squeeze excitation. 2d uses 2D spatial global average pooling\n on each frame. 2plus3d concatenates both 3D and 2D global average\n pooling.\n activation: The main activation to use across layers.\n classifier_activation: The classifier activation to use.\n gating_activation: The gating activation to use in squeeze-excitation\n layers.\n use_positional_encoding: Whether to use positional encoding (only applied\n when causal=True).\n num_classes: The number of classes for prediction.\n input_shape: The 5D spatiotemporal input shape of size\n [batch_size, num_frames, image_height, image_width, num_channels].\n Set the field or a shape position in the field to None for dynamic input.\n bundle_input_init_states_fn: Add init_states as a function signature to the\n saved model. This is not necessary if the input shape is static (e.g.,\n for TF Lite).\n checkpoint_path: Checkpoint path to load. Leave blank for default\n initialization.\n \"\"\"\n\n input_specs = tf.keras.layers.InputSpec(shape=input_shape)\n\n # Override swish activation implementation to remove custom gradients\n if activation == 'swish':\n activation = 'simple_swish'\n if classifier_activation == 'swish':\n classifier_activation = 'simple_swish'\n\n backbone = movinet.Movinet(\n model_id=model_id,\n causal=causal,\n use_positional_encoding=use_positional_encoding,\n conv_type=conv_type,\n se_type=se_type,\n input_specs=input_specs,\n activation=activation,\n gating_activation=gating_activation,\n use_sync_bn=False,\n use_external_states=causal)\n model = movinet_model.MovinetClassifier(\n backbone,\n num_classes=num_classes,\n output_states=causal,\n input_specs=dict(image=input_specs),\n activation=classifier_activation)\n\n export_saved_model(\n model=model,\n input_shape=input_shape,\n export_path=export_path,\n causal=causal,\n bundle_input_init_states_fn=bundle_input_init_states_fn,\n checkpoint_path=checkpoint_path)\n\n\ndef main(_) -> None:\n input_shape = (\n FLAGS.batch_size, FLAGS.num_frames, FLAGS.image_size, FLAGS.image_size, 3)\n build_and_export_saved_model(\n export_path=FLAGS.export_path,\n model_id=FLAGS.model_id,\n causal=FLAGS.causal,\n conv_type=FLAGS.conv_type,\n se_type=FLAGS.se_type,\n activation=FLAGS.activation,\n classifier_activation=FLAGS.classifier_activation,\n gating_activation=FLAGS.gating_activation,\n use_positional_encoding=FLAGS.use_positional_encoding,\n num_classes=FLAGS.num_classes,\n input_shape=input_shape,\n bundle_input_init_states_fn=FLAGS.bundle_input_init_states_fn,\n checkpoint_path=FLAGS.checkpoint_path)\n print(' ----- Done. Saved Model is saved at {}'.format(FLAGS.export_path))\n\n\nif __name__ == '__main__':\n app.run(main)\n"
] | [
[
"tensorflow.train.Checkpoint",
"tensorflow.keras.models.save_model",
"tensorflow.ones",
"tensorflow.function",
"tensorflow.keras.layers.InputSpec",
"tensorflow.TensorSpec"
]
] |
mehta-lab/pysero | [
"c8dbdc8c98c134dd9647e691bc92eaef4301effa"
] | [
"array_analyzer/extract/image_parser.py"
] | [
"import cv2 as cv\nimport numpy as np\nimport itertools\nimport math\nimport pandas as pd\nfrom types import SimpleNamespace\nfrom scipy import spatial\n\nfrom skimage.transform import hough_circle, hough_circle_peaks\nfrom skimage.feature import canny\nfrom skimage.morphology import binary_closing, binary_dilation, selem, disk, binary_opening\nfrom skimage import measure\n\nfrom .img_processing import thresh_and_binarize\nfrom array_analyzer.transform.point_registration import icp\n\n\"\"\"\nmethod is\n# find center of well\n2) thresh and binarize from 1\n3) find well border from 2\n4) crop image from 3\n\n# find center of spots from crop\n5) thresh and binarize from 4\n6) clean spot binary from 5\n7) generate props from 6\n8) generate props dict from 7\n9) assign props dict to array from 8\n\"\"\"\n\n\ndef get_well_mask(image_,\n disk_size=3,\n segmethod='rosin'):\n \"\"\"\n Segment the well boundary and return a binary mask\n\n :param image_: np.ndarray\n :param disk_size: int\n :param segmethod: method for thresh_and_binarize\n :return: binary mask\n \"\"\"\n\n well_mask = thresh_and_binarize(image_, method=segmethod, invert=False)\n\n # Now remove small objects.\n str_elem = disk(disk_size)\n well_mask = binary_opening(well_mask, str_elem)\n\n labels = measure.label(well_mask)\n props = measure.regionprops(labels)\n\n props = select_props(props, attribute=\"area\", condition=\"greater_than\", condition_value=10 ** 5)\n well_mask[labels != props[0].label] = 0\n\n return well_mask\n\n\ndef get_well_intensity(image_, mask_):\n \"\"\"\n Return the median intensity of the masked image\n\n :param image_: np.ndarray\n :param mask_: boolean array\n :return: int\n \"\"\"\n\n well_int = np.median(image_[mask_])\n\n return well_int\n\n\ndef find_well_border(image, segmethod='bimodal', detmethod='region'):\n \"\"\"\n finds the border of the well to motivate future cropping around spots\n hough_radii are potential radii of the well in pixels\n this should be motivated based on magnification\n edge filter\n fit hough circle\n find the peak of the SINGULAR hough circle\n\n :param image: np.ndarray\n raw image, not inverted\n :param segmethod: str\n 'otsu' or 'hough'\n :return: center x, center y, radius of the one hough circle\n \"\"\"\n well_mask = thresh_and_binarize(image, method=segmethod, invert=False)\n # Now remove small objects.\n str_elem_size = 10\n str_elem = disk(str_elem_size)\n well_mask = binary_opening(well_mask, str_elem)\n # well_mask = binary_fill_holes(well_mask)\n\n if detmethod == 'region':\n labels = measure.label(well_mask)\n props = measure.regionprops(labels)\n\n # let's assume ONE circle for now (take only props[0])\n props = select_props(props, attribute=\"area\", condition=\"greater_than\", condition_value=10**5)\n props = select_props(props, attribute=\"eccentricity\", condition=\"less_than\", condition_value=0.5)\n well_mask[labels != props[0].label] = 0\n cy, cx = props[0].centroid # notice that the coordinate order is different from hough.\n radii = int((props[0].minor_axis_length + props[0].major_axis_length)/ 4 / np.sqrt(2))\n # Otsu threshold fails occasionally and leads to asymmetric region. Averaging both axes makes the segmentation robust.\n # If above files, try bounding box.\n\n elif detmethod == 'hough':\n hough_radii = [300, 400, 500, 600]\n\n well_mask = thresh_and_binarize(image, method='bimodal')\n\n edges = canny(well_mask, sigma=3)\n hough_res = hough_circle(edges, hough_radii)\n aaccums, cx, cy, radii = hough_circle_peaks(hough_res, hough_radii, total_num_peaks=1)\n cx, cy = cx[0], cy[0]\n radii = radii[0]\n else:\n cx, cy, radii = None, None, None\n\n return [cy, cx], radii, well_mask\n\n\ndef clean_spot_binary(arr, kx=10, ky=10):\n return binary_closing(arr, selem=np.ones((kx, ky)))\n\n\ndef generate_spot_background(spotmask, distance=3, annulus=5):\n \"\"\"\n \n compute an annulus around each spot to estimate background.\n \n Parameters\n ----------\n spotmask : binary mask of spots\n distance : distance from the edge of segmented spot.\n annulus : width of the annulus\n\n Returns\n -------\n spotbackgroundmask: binary mask of annuli around spots.\n \n TODO: 'comets' should be ignored, and this approach may not be robust to it.\n \"\"\"\n se_inner = selem.disk(distance, dtype=bool)\n se_outer = selem.disk(distance+annulus, dtype=bool)\n inner = binary_dilation(spotmask, se_inner)\n outer = binary_dilation(spotmask, se_outer)\n spot_background = np.bitwise_xor(inner, outer)\n\n return spot_background\n\n\ndef generate_props(mask,\n intensity_image=None,\n dataframe=False,\n properties=('label', 'centroid', 'mean_intensity',\n 'intensity_image', 'image', 'area', 'bbox')):\n \"\"\"\n converts binarized image into a list of region-properties using scikit-image\n first generates labels for the cleaned (binary_closing) binary image\n then generates regionprops on the remaining\n\n :param mask: np.ndarray\n binary version of cropped image\n :param intensity_image: np.ndarray\n intensity image corresponding to this binary\n :param dataframe: bool\n return pandas dataframe instead of list of prop objects if true\n :param tuple properties: Dataframe labels\n :return: list\n of skimage region-props object\n \"\"\"\n labels = measure.label(mask)\n if dataframe:\n props = measure.regionprops_table(\n labels,\n intensity_image=intensity_image,\n properties=properties,\n )\n props = pd.DataFrame(props)\n else:\n props = measure.regionprops(labels, intensity_image=intensity_image)\n return props\n\n\ndef select_props(props_, attribute, condition, condition_value):\n \"\"\"\n\n :param props_: RegionProps\n :param attribute: str\n a regionprop attribute\n https://scikit-image.org/docs/dev/api/skimage.measure.html#regionprops\n :param condition: str\n one of \"greater_than\", \"equals\", \"less_than\"\n :param condition_value: int, float\n the value to evaluate around\n :return:\n \"\"\"\n\n if condition == 'greater_than':\n props = [p for p in props_ if getattr(p, attribute) > condition_value]\n elif condition == 'equals':\n props = [p for p in props_ if getattr(p, attribute) == condition_value]\n elif condition == 'less_than':\n props = [p for p in props_ if getattr(p, attribute) < condition_value]\n elif condition == 'is_in':\n props = [p for p in props_ if getattr(p, attribute) in condition_value]\n else:\n props = props_\n\n return props\n\n\ndef generate_props_dict(props_, n_rows, n_cols, min_area=100, img_x_max=2048, img_y_max=2048, flag_duplicates=True):\n \"\"\"\n based on the region props, creates a dictionary of format:\n key = (centroid_x, centroid_y)\n value = region_prop object\n\n :param props_: list of region props\n approximately 36-48 of these, depending on quality of the image\n :param n_rows: int\n :param n_cols: int\n :param min_area: int\n :param img_x_max: int\n :param img_y_max: int\n :return: dict\n of format (cent_x, cent_y): prop\n \"\"\"\n\n # find minx, miny to \"zero center\" the array\n minx = img_x_max\n miny = img_y_max\n # find maxx, maxy to scale to array index values\n maxx = 0\n maxy = 0\n for prop in props_:\n if prop.area > min_area:\n if prop.centroid[0] < minx:\n minx = prop.centroid[0]\n if prop.centroid[1] < miny:\n miny = prop.centroid[1]\n if prop.centroid[0] > maxx:\n maxx = prop.centroid[0]\n if prop.centroid[1] > maxy:\n maxy = prop.centroid[1]\n\n # scaled max-x, max-y\n smaxx = maxx - minx\n smaxy = maxy - miny\n\n chk_list = []\n cent_map = {}\n for prop in props_:\n if prop.area > min_area:\n cx, cy = prop.centroid\n csx = cx - minx\n csy = cy - miny\n\n # convert the centroid position to an integer that maps to array indices\n norm_cent_x = int(round((n_rows - 1) * (csx / smaxx)))\n norm_cent_y = int(round((n_cols - 1) * (csy / smaxy)))\n\n # print(f\"\\ncentroid = {prop.centroid}\\n\\tnorm_cent = {norm_cent_x, norm_cent_y}\")\n\n chk_list.append((norm_cent_x, norm_cent_y))\n cent_map[(norm_cent_x, norm_cent_y)] = prop\n\n if flag_duplicates:\n if len(chk_list) != len(set(chk_list)):\n print(\"ERROR, DUPLICATE ENTRIES\")\n raise AttributeError(\"generate props array failed\\n\"\n \"duplicate spots found in one position\\n\")\n\n return cent_map\n\n\ndef find_fiducials_markers(props_,\n fiducial_locations,\n n_rows,\n n_cols,\n v_pitch,\n h_pitch,\n img_size,\n pix_size):\n \"\"\"\n based on the region props, creates a dictionary of format:\n key = (centroid_x, centroid_y)\n value = region_prop object\n\n :param props_: list of region props\n approximately 36-48 of these, depending on quality of the image\n :param fiducial_locations: list specifying location of fiducial markers, e.g.\n [(0,0), (0,5), (5,0)] for markers at 3 corners of 6x6 array\n :param n_rows: int\n :param n_cols: int\n :param v_pitch: float\n vertical spot center distance in mm\n :param h_pitch: float\n horizontal spot center distance in mm\n :param img_size tuple\n image size in pixels\n :param pix_size: float\n size of pix in mm\n :return: dict\n of format (cent_x, cent_y): prop for fiducials only\n NOTE (Jenny): Why input pixel size here? All you do is multiply both\n sets of coordinates with it, then divide by it.\n \"\"\"\n\n centroids_in_mm = np.array([p.centroid for p in props_]) * pix_size\n spots_x, spots_y = (centroids_in_mm[:,1], centroids_in_mm[:,0])\n\n cent_y, cent_x = np.array(img_size) / 2 * pix_size\n start_x = cent_x - h_pitch * (n_cols - 1) / 2\n start_y = cent_y - v_pitch * (n_rows - 1) / 2\n\n x_vals = np.array([f[0] for f in fiducial_locations]) * h_pitch + start_x\n y_vals = np.array([f[1] for f in fiducial_locations]) * v_pitch + start_y\n grid_x = x_vals.flatten()\n grid_y = y_vals.flatten()\n\n source = np.array([grid_x, grid_y]).T\n target = np.array([spots_x, spots_y]).T\n t_matrix = icp(source, target)\n\n grid_estimate = cv.transform(np.expand_dims(source, 0), t_matrix[:2])\n\n reg_x = grid_estimate[0, :, 0]\n reg_y = grid_estimate[0, :, 1]\n\n cent_map = {}\n for i, f in enumerate(fiducial_locations):\n cent_map[f[::-1]] = SimpleNamespace(centroid=(reg_y[i]/pix_size, reg_x[i]/pix_size))\n\n return cent_map\n\n\ndef grid_from_centroids(props_, n_rows, n_cols, grid_spacing=82):\n \"\"\"\n based on the region props, creates a dictionary of format:\n key = (centroid_x, centroid_y)\n value = region_prop object\n\n :param props_: list of region props\n approximately 36-48 of these, depending on quality of the image\n :param n_rows: int\n :param n_cols: int\n :param grid_spacing\n :return: dict\n of format (cent_x, cent_y): prop\n \"\"\"\n centroids = np.array([prop.weighted_centroid for prop in props_])\n bbox_areas = np.array([prop.bbox_area for prop in props_])\n areas = np.array([prop.area for prop in props_])\n # calculate mean bbox width for cropping undetected spots\n bbox_area_mean = np.mean(bbox_areas)\n area_mean = np.mean(areas)\n # bbox_width = bbox_height = int(np.sqrt(bbox_area_mean))\n bbox_width = bbox_height = 2 * int(0.5 * np.sqrt(area_mean / np.pi)) + 1\n\n y_min_idx = np.argmin(centroids[:, 0])\n y_min = centroids[y_min_idx, 0]\n y_max_idx = np.argmax(centroids[:, 0])\n y_max = centroids[y_max_idx, 0]\n x_min_idx = np.argmin(centroids[:, 1])\n x_min = centroids[x_min_idx, 1]\n x_max_idx = np.argmax(centroids[:, 1])\n x_max = centroids[x_max_idx, 1]\n\n margin = 0.05 * grid_spacing\n y_min_idx = 0\n y_max_idx = len(props_) - 1\n x_min_idx = 0\n x_max_idx = len(props_) - 1\n y_sort_ids = np.argsort(centroids[:, 0])\n x_sort_ids = np.argsort(centroids[:, 1])\n y_spacing = (y_max - y_min) / (n_rows - 1)\n x_spacing = (x_max - x_min) / (n_cols - 1)\n # update the x, y bound to match the expected grid_spacing\n while y_spacing - grid_spacing > margin:\n y_min_idx_new = y_min_idx + 1\n y_min_new = centroids[y_sort_ids[y_min_idx_new], 0]\n y_max_idx_new = y_max_idx - 1\n y_max_new = centroids[y_sort_ids[y_max_idx_new], 0]\n if np.abs((y_max - y_min_new) / (n_rows - 1) - grid_spacing) < \\\n np.abs((y_max_new - y_min) / (n_rows - 1) - grid_spacing):\n y_min_idx = y_min_idx_new\n y_min = y_min_new\n else:\n y_max_idx = y_max_idx_new\n y_max = y_max_new\n y_spacing = (y_max - y_min) / (n_rows - 1)\n\n while x_spacing - grid_spacing > margin:\n x_min_idx_new = x_min_idx + 1\n x_min_new = centroids[x_sort_ids[x_min_idx_new], 1]\n x_max_idx_new = x_max_idx - 1\n x_max_new = centroids[x_sort_ids[x_max_idx_new], 1]\n if np.abs((x_max - x_min_new) / (n_cols - 1) - grid_spacing) < \\\n np.abs((x_max_new - x_min) / (n_cols - 1) - grid_spacing):\n x_min_idx = x_min_idx_new\n x_min = x_min_new\n else:\n x_max_idx = x_max_idx_new\n x_max = x_max_new\n x_spacing = (x_max - x_min) / (n_cols - 1)\n # If apporach 1 fails, try nearest neighbor distance filter to remove spurious spots\n if grid_spacing - y_spacing > margin or grid_spacing - x_spacing > margin:\n # y_sort_ids = np.argsort(centroids[:, 0])\n # x_sort_ids = np.argsort(centroids[:, 1])\n dist_tree = spatial.cKDTree(centroids)\n dist, ids = dist_tree.query(centroids, k=2)\n dist = dist[:, 1]\n dist_median = np.median(dist)\n # dist_median = grid_spacing\n dist_std = 0.8 * dist.std()\n # if dist_std > 5:\n if grid_spacing - y_spacing > margin:\n y_min_idx = 0\n\n while dist[y_sort_ids[y_min_idx]] > dist_median + dist_std or \\\n dist[y_sort_ids[y_min_idx]] < dist_median - dist_std:\n y_min_idx += 1\n if y_min_idx >= len(props_) - 1:\n break\n y_min = centroids[y_sort_ids[y_min_idx], 0]\n y_max_idx = len(props_) - 1\n while dist[y_sort_ids[y_max_idx]] > dist_median + dist_std or \\\n dist[y_sort_ids[y_max_idx]] < dist_median - dist_std:\n y_max_idx -= 1\n if y_max_idx == 0:\n break\n y_max = centroids[y_sort_ids[y_max_idx], 0]\n y_spacing = (y_max - y_min) / (n_rows - 1)\n\n if grid_spacing - x_spacing > margin:\n x_min_idx = 0\n while dist[x_sort_ids[x_min_idx]] > dist_median + dist_std or \\\n dist[x_sort_ids[x_min_idx]] < dist_median - dist_std:\n x_min_idx += 1\n if x_min_idx >= len(props_) - 1:\n break\n x_min = centroids[x_sort_ids[x_min_idx], 1]\n\n x_max_idx = len(props_) - 1\n while dist[x_sort_ids[x_max_idx]] > dist_median + dist_std or \\\n dist[x_sort_ids[x_max_idx]] < dist_median - dist_std:\n x_max_idx -= 1\n if x_max_idx == 0:\n break\n x_max = centroids[x_sort_ids[x_max_idx], 1]\n x_spacing = (x_max - x_min) / (n_cols - 1)\n # scaled max-x, max-y\n y_range = y_max - y_min\n x_range = x_max - x_min\n grid_ids = list(itertools.product(range(n_rows), range(n_cols)))\n coords = np.ndarray((len(grid_ids), 2))\n for idx, grid_id in enumerate(grid_ids):\n coords[idx, :] = [grid_id[0]/(n_rows - 1) * y_range + y_min,\n grid_id[1]/(n_cols - 1) * x_range + x_min]\n return coords\n\n\ndef assign_props_to_array(arr, cent_map_):\n \"\"\"\n takes an empty array and assigns region_property objects to each position, based on print array position\n\n :param arr: np.ndarray\n of shape = print array shape\n :param cent_map_: dict\n generated by \"generate_props_array\"\n :return:\n \"\"\"\n\n for key, value in cent_map_.items():\n arr[key[0], key[1]] = value\n\n return arr\n\n\ndef assign_props_to_array_2(arr, cent_map_):\n \"\"\"\n takes an empty array and assigns region_property objects to each position, based on print array position\n deals with multiple props assigned to a position and takes only more intense images\n\n :param arr: np.ndarray\n of shape = print array shape\n :param cent_map_: dict\n generated by \"generate_props_array\"\n :return:\n \"\"\"\n\n for key, value in cent_map_.items():\n if arr[key[0], key[1]] and np.mean(value.intensity_image) > np.mean(arr[key[0], key[1]].intensity_image):\n arr[key[0], key[1]] = value\n elif not arr[key[0], key[1]]:\n arr[key[0], key[1]] = value\n else:\n pass\n\n return arr\n\n\ndef build_block_array(params_, pix_size=0.0049):\n \"\"\"\n builds a binary array of squares centered on the expected spot position\n The array dimensions are based on parsed .xml values from the print run\n\n Daheng camera: IMX226, 12 MP (4000 x 3000), 1.85 um pixel size\n SciReader camera: Camera sensor / mag => 4.9 um/pixel, 2592 x 1944 pixels = 12.701 mm x 9.525 mm.\n\n :param params_: dict\n param dictionary from \"create_xml_dict\"\n :param pix_size: float\n size of pix in mm\n :return: np.ndarray, origin\n\n \"\"\"\n\n # fix the pixel size, for now, in mm\n PIX_SIZE = pix_size\n # PIX_SIZE = 0.00185\n\n n_rows = params_['rows']\n n_cols = params_['columns']\n\n # values in mm\n v_pitch = params_['v_pitch']\n h_pitch = params_['h_pitch']\n spot_width = params_['spot_width']\n\n # values in pixels\n v_pix = v_pitch/PIX_SIZE\n h_pix = h_pitch/PIX_SIZE\n spot_pix = spot_width/PIX_SIZE\n\n # make the box 1.3x the size of the spot, unless it will cause overlap\n side = int(1.3*spot_pix if 1.3*spot_pix < v_pix-1 and 1.3*spot_pix < h_pix-1 else spot_pix)\n\n # create templates\n x_range = int(v_pix*(n_rows-1)) + side\n y_range = int(h_pix*(n_cols-1)) + side\n target = np.zeros((x_range, y_range))\n\n # center position of the origin\n origin = (side/2, side/2)\n print(origin)\n for row in range(n_rows):\n for col in range(n_cols):\n center_x = origin[0] + row * v_pix\n center_y = origin[1] + col * h_pix\n\n # check that the blank fits within the bounds of the target array\n x_min = int(center_x - side / 2) if int(center_x - side / 2) > 0 else 0\n x_max = int(center_x + side / 2) if int(center_x + side / 2) < target.shape[0] else target.shape[0]\n y_min = int(center_y - side / 2) if int(center_y - side / 2) > 0 else 0\n y_max = int(center_y + side / 2) if int(center_y + side / 2) < target.shape[1] else target.shape[1]\n\n blank = np.ones((x_max-x_min, y_max-y_min))\n\n target[x_min:x_max, y_min:y_max] = blank\n\n return target, origin\n\n\ndef build_and_place_block_array(props_array_, spot_mask_, params_, return_type='region'):\n \"\"\"\n Uses the fiducial centroid positions to build a \"block array\":\n \"block array\" is composed of (side, side) regions centered on each expected well position\n There are (rows, cols) of\n np.array of shape = (rows, cols)\n whose elements are np.ones(shape=(side, side))\n\n :param props_array_:\n :param spot_mask_:\n :param params_:\n :param return_type:\n :return:\n \"\"\"\n\n rows = params_['rows']\n cols = params_['columns']\n\n # fiducials are averaged to find x-y bounds.\n # one or both can be None, if one is None, this is handled\n # if two are None, we have to try something else\n fiduc_1 = props_array_[0][0].centroid if props_array_[0][0] else (0, 0)\n fiduc_2 = props_array_[0][cols-1].centroid if props_array_[0][cols-1] else (0, 0)\n fiduc_3 = props_array_[rows-1][0].centroid if props_array_[rows-1][0] else (0, 0)\n fiduc_4 = props_array_[rows-1][cols-1].centroid if props_array_[rows-1][cols-1] else (0, 0)\n\n # average if two else use one\n x_list_min = [fiduc_1[0], fiduc_2[0]]\n x_min = np.sum(x_list_min) / np.sum(len([v for v in x_list_min if v != 0]))\n\n y_list_min = [fiduc_1[1], fiduc_3[1]]\n y_min = np.sum(y_list_min) / np.sum(len([v for v in y_list_min if v != 0]))\n\n x_list_max = [fiduc_3[0], fiduc_4[0]]\n x_max = np.sum(x_list_max) / np.sum(len([v for v in x_list_max if v != 0]))\n\n y_list_max = [fiduc_2[1], fiduc_4[1]]\n y_max = np.sum(y_list_max) / np.sum(len([v for v in y_list_max if v != 0]))\n\n # check for NaNs - no fiducial was found\n # instead, we will use ANY spot at the boundaries to motivate the positioning\n if math.isnan(x_min):\n x_mins = [p.centroid[0] for p in props_array_[0, :] if p]\n x_min = np.average(x_mins)\n if math.isnan(y_min):\n y_mins = [p.centroid[1] for p in props_array_[:, 0] if p]\n y_min = np.average(y_mins)\n if math.isnan(x_max):\n x_maxs = [p.centroid[0] for p in props_array_[rows-1, :] if p]\n x_max = np.average(x_maxs)\n if math.isnan(y_max):\n y_maxs = [p.centroid[1] for p in props_array_[:, cols-1] if p]\n y_max = np.average(y_maxs)\n\n # build_block_array uses values in the params_ to motivate array dimensions, spacings\n # build block array\n template, temp_origin = build_block_array(params_)\n\n # center the template origin on the expected fiducial 1\n target = np.zeros(spot_mask_.shape)\n target[int(x_min-temp_origin[0]):int(x_min+template.shape[0]-temp_origin[0]),\n int(y_min-temp_origin[1]):int(y_min+template.shape[1]-temp_origin[1])] = template\n\n if return_type == 'product':\n return target*spot_mask_\n elif return_type == 'region':\n return target\n"
] | [
[
"numpy.expand_dims",
"numpy.sum",
"numpy.abs",
"numpy.sqrt",
"numpy.median",
"pandas.DataFrame",
"numpy.bitwise_xor",
"numpy.ones",
"numpy.argmax",
"numpy.mean",
"numpy.argmin",
"numpy.average",
"numpy.argsort",
"numpy.array",
"numpy.zeros",
"scipy.spatial.cKDTree"
]
] |
toujika/fairseq | [
"0e68173babf843b543d909723bd5de2b7390e375"
] | [
"generate.py"
] | [
"#!/usr/bin/env python3 -u\n# Copyright (c) 2017-present, Facebook, Inc.\n# All rights reserved.\n#\n# This source code is licensed under the license found in the LICENSE file in\n# the root directory of this source tree. An additional grant of patent rights\n# can be found in the PATENTS file in the same directory.\n\"\"\"\nTranslate pre-processed data with a trained model.\n\"\"\"\n\nimport torch\n\nfrom fairseq import bleu, data, options, progress_bar, tasks, tokenizer, utils\nfrom fairseq.meters import StopwatchMeter, TimeMeter\nfrom fairseq.sequence_generator import SequenceGenerator\nfrom fairseq.sequence_scorer import SequenceScorer\n\n\ndef main(args):\n assert args.path is not None, '--path required for generation!'\n assert not args.sampling or args.nbest == args.beam, \\\n '--sampling requires --nbest to be equal to --beam'\n assert args.replace_unk is None or args.raw_text, \\\n '--replace-unk requires a raw text dataset (--raw-text)'\n\n if args.max_tokens is None and args.max_sentences is None:\n args.max_tokens = 12000\n print(args)\n\n use_cuda = torch.cuda.is_available() and not args.cpu\n\n # Load dataset splits\n task = tasks.setup_task(args)\n task.load_dataset(args.gen_subset)\n print('| {} {} {} examples'.format(args.data, args.gen_subset, len(task.dataset(args.gen_subset))))\n\n # Set dictionaries\n src_dict = task.source_dictionary\n tgt_dict = task.target_dictionary\n\n # Load ensemble\n print('| loading model(s) from {}'.format(args.path))\n models, _ = utils.load_ensemble_for_inference(args.path.split(':'), task, model_arg_overrides=eval(args.model_overrides))\n\n # Optimize ensemble for generation\n for model in models:\n model.make_generation_fast_(\n beamable_mm_beam_size=None if args.no_beamable_mm else args.beam,\n need_attn=args.print_alignment,\n )\n if args.fp16:\n model.half()\n\n # Load alignment dictionary for unknown word replacement\n # (None if no unknown word replacement, empty if no path to align dictionary)\n align_dict = utils.load_align_dict(args.replace_unk)\n\n # Load dataset (possibly sharded)\n #from IPython.core.debugger import Pdb; Pdb().set_trace()\n itr = task.get_batch_iterator(\n dataset=task.dataset(args.gen_subset),\n max_tokens=args.max_tokens,\n max_sentences=args.max_sentences,\n max_positions=utils.resolve_max_positions(\n task.max_positions(),\n *[model.max_positions() for model in models]\n ),\n ignore_invalid_inputs=args.skip_invalid_size_inputs_valid_test,\n required_batch_size_multiple=8,\n num_shards=args.num_shards,\n shard_id=args.shard_id,\n ).next_epoch_itr(shuffle=False)\n\n # Initialize generator\n gen_timer = StopwatchMeter()\n if args.score_reference:\n translator = SequenceScorer(models, task.target_dictionary)\n else:\n translator = SequenceGenerator(\n models, task.target_dictionary, beam_size=args.beam, minlen=args.min_len,\n stop_early=(not args.no_early_stop), normalize_scores=(not args.unnormalized),\n len_penalty=args.lenpen, unk_penalty=args.unkpen,\n sampling=args.sampling, sampling_topk=args.sampling_topk, sampling_temperature=args.sampling_temperature,\n diverse_beam_groups=args.diverse_beam_groups, diverse_beam_strength=args.diverse_beam_strength,\n )\n\n if use_cuda:\n translator.cuda()\n\n # Generate and compute BLEU score\n #from IPython.core.debugger import Pdb; Pdb().set_trace()\n scorer = bleu.Scorer(tgt_dict.pad(), tgt_dict.eos(), tgt_dict.unk())\n num_sentences = 0\n has_target = True\n with progress_bar.build_progress_bar(args, itr) as t:\n if args.score_reference:\n translations = translator.score_batched_itr(t, cuda=use_cuda, timer=gen_timer)\n else:\n translations = translator.generate_batched_itr(\n t, maxlen_a=args.max_len_a, maxlen_b=args.max_len_b,\n cuda=use_cuda, timer=gen_timer, prefix_size=args.prefix_size,\n )\n\n wps_meter = TimeMeter()\n for sample_id, src_tokens, target_tokens, hypos in translations:\n # Process input and ground truth\n has_target = target_tokens is not None\n target_tokens = target_tokens.int().cpu() if has_target else None\n\n # Either retrieve the original sentences or regenerate them from tokens.\n if align_dict is not None:\n src_str = task.dataset(args.gen_subset).src.get_original_text(sample_id)\n target_str = task.dataset(args.gen_subset).tgt.get_original_text(sample_id)\n else:\n src_str = src_dict.string(src_tokens, args.remove_bpe)\n if has_target:\n target_str = tgt_dict.string(target_tokens, args.remove_bpe, escape_unk=True)\n\n if not args.quiet:\n print('S-{}\\t{}'.format(sample_id, src_str))\n if has_target:\n print('T-{}\\t{}'.format(sample_id, target_str))\n\n # Process top predictions\n for i, hypo in enumerate(hypos[:min(len(hypos), args.nbest)]):\n hypo_tokens, hypo_str, alignment = utils.post_process_prediction(\n hypo_tokens=hypo['tokens'].int().cpu(),\n src_str=src_str,\n alignment=hypo['alignment'].int().cpu() if hypo['alignment'] is not None else None,\n align_dict=align_dict,\n tgt_dict=tgt_dict,\n remove_bpe=args.remove_bpe,\n )\n\n if not args.quiet:\n print('H-{}\\t{}\\t{}'.format(sample_id, hypo['score'], hypo_str))\n print('P-{}\\t{}'.format(\n sample_id,\n ' '.join(map(\n lambda x: '{:.4f}'.format(x),\n hypo['positional_scores'].tolist(),\n ))\n ))\n\n if args.print_alignment:\n print('A-{}\\t{}'.format(\n sample_id,\n ' '.join(map(lambda x: str(utils.item(x)), alignment))\n ))\n\n # Score only the top hypothesis\n if has_target and i == 0:\n if align_dict is not None or args.remove_bpe is not None:\n # Convert back to tokens for evaluation with unk replacement and/or without BPE\n target_tokens = tokenizer.Tokenizer.tokenize(\n target_str, tgt_dict, add_if_not_exist=True)\n scorer.add(target_tokens, hypo_tokens)\n\n wps_meter.update(src_tokens.size(0))\n t.log({'wps': round(wps_meter.avg)})\n num_sentences += 1\n\n print('| Translated {} sentences ({} tokens) in {:.1f}s ({:.2f} sentences/s, {:.2f} tokens/s)'.format(\n num_sentences, gen_timer.n, gen_timer.sum, num_sentences / gen_timer.sum, 1. / gen_timer.avg))\n if has_target:\n print('| Generate {} with beam={}: {}'.format(args.gen_subset, args.beam, scorer.result_string()))\n\n\nif __name__ == '__main__':\n parser = options.get_generation_parser()\n args = options.parse_args_and_arch(parser)\n main(args)\n"
] | [
[
"torch.cuda.is_available"
]
] |
davidgolub/QuestionGeneration | [
"6b31e1a8855774230051093ca24ba0a7750a6712"
] | [
"dnn_units/lstm_attention.py"
] | [
"\"\"\"Sequence to Sequence models.\"\"\"\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nimport math\nimport torch.nn.functional as F\nimport numpy as np\nfrom helpers import torch_utils\n\n\nclass StackedAttentionLSTM(nn.Module):\n \"\"\"Deep Attention LSTM.\"\"\"\n\n def __init__(\n self,\n input_size,\n rnn_size,\n num_layers,\n batch_first=True,\n dropout=0.\n ):\n \"\"\"Initialize params.\"\"\"\n super(StackedAttentionLSTM, self).__init__()\n self.dropout = nn.Dropout(dropout)\n self.input_size = input_size\n self.rnn_size = rnn_size\n self.batch_first = batch_first\n\n self.layers = []\n for i in range(num_layers):\n layer = LSTMAttentionDot(\n input_size, rnn_size, batch_first=self.batch_first\n )\n self.add_module('layer_%d' % i, layer)\n self.layers += [layer]\n input_size = rnn_size\n\n def forward(self, input, hidden, ctx, ctx_mask=None):\n \"\"\"Propogate input through the layer.\"\"\"\n h_0, c_0 = hidden\n h_1, c_1 = [], []\n for i, layer in enumerate(self.layers):\n if ctx_mask is not None:\n ctx_mask = torch.ByteTensor(\n ctx_mask.data.cpu().numpy().astype(np.int32).tolist()\n ).cuda()\n output, (h_1_i, c_1_i) = layer(input, (h_0, c_0), ctx, ctx_mask)\n\n input = output\n\n if i != len(self.layers):\n input = self.dropout(input)\n\n h_1 += [h_1_i]\n c_1 += [c_1_i]\n\n h_1 = torch.stack(h_1)\n c_1 = torch.stack(c_1)\n\n return input, (h_1, c_1)\n\n\nclass DeepBidirectionalLSTM(nn.Module):\n r\"\"\"A Deep LSTM with the first layer being bidirectional.\"\"\"\n\n def __init__(\n self, input_size, hidden_size,\n num_layers, dropout, batch_first\n ):\n \"\"\"Initialize params.\"\"\"\n super(DeepBidirectionalLSTM, self).__init__()\n self.input_size = input_size\n self.hidden_size = hidden_size\n self.dropout = dropout\n self.batch_first = batch_first\n self.num_layers = num_layers\n\n self.bi_encoder = nn.LSTM(\n self.input_size,\n self.hidden_size // 2,\n 1,\n bidirectional=True,\n batch_first=True,\n dropout=self.dropout\n )\n\n self.encoder = nn.LSTM(\n self.hidden_size,\n self.hidden_size,\n self.num_layers - 1,\n bidirectional=False,\n batch_first=True,\n dropout=self.dropout\n )\n\n def get_state(self, input):\n \"\"\"Get cell states and hidden states.\"\"\"\n batch_size = input.size(0) \\\n if self.encoder.batch_first else input.size(1)\n h0_encoder_bi = Variable(torch.zeros(\n 2,\n batch_size,\n self.hidden_size // 2\n ))\n c0_encoder_bi = Variable(torch.zeros(\n 2,\n batch_size,\n self.hidden_size // 2\n ))\n\n h0_encoder = Variable(torch.zeros(\n self.num_layers - 1,\n batch_size,\n self.hidden_size\n ))\n\n c0_encoder = Variable(torch.zeros(\n self.num_layers - 1,\n batch_size,\n self.hidden_size\n ))\n\n return (h0_encoder_bi.cuda(), c0_encoder_bi.cuda()), \\\n (h0_encoder.cuda(), c0_encoder.cuda())\n\n def forward(self, input):\n \"\"\"Propogate input forward through the network.\"\"\"\n hidden_bi, hidden_deep = self.get_state(input)\n bilstm_output, (_, _) = self.bi_encoder(input, hidden_bi)\n return self.encoder(bilstm_output, hidden_deep)\n\n\nclass LSTMAttention(nn.Module):\n r\"\"\"A long short-term memory (LSTM) cell with attention.\"\"\"\n\n def __init__(self, input_size, hidden_size, context_size):\n \"\"\"Initialize params.\"\"\"\n super(LSTMAttention, self).__init__()\n self.input_size = input_size\n self.hidden_size = hidden_size\n self.context_size = context_size\n self.num_layers = 1\n\n self.input_weights_1 = nn.Parameter(\n torch.Tensor(4 * hidden_size, input_size)\n )\n self.hidden_weights_1 = nn.Parameter(\n torch.Tensor(4 * hidden_size, hidden_size)\n )\n self.input_bias_1 = nn.Parameter(torch.Tensor(4 * hidden_size))\n self.hidden_bias_1 = nn.Parameter(torch.Tensor(4 * hidden_size))\n\n self.input_weights_2 = nn.Parameter(\n torch.Tensor(4 * hidden_size, context_size)\n )\n self.hidden_weights_2 = nn.Parameter(\n torch.Tensor(4 * hidden_size, hidden_size)\n )\n self.input_bias_2 = nn.Parameter(torch.Tensor(4 * hidden_size))\n self.hidden_bias_2 = nn.Parameter(torch.Tensor(4 * hidden_size))\n\n self.context2attention = nn.Parameter(\n torch.Tensor(context_size, context_size)\n )\n self.bias_context2attention = nn.Parameter(torch.Tensor(context_size))\n\n self.hidden2attention = nn.Parameter(\n torch.Tensor(context_size, hidden_size)\n )\n\n self.input2attention = nn.Parameter(\n torch.Tensor(input_size, context_size)\n )\n\n self.recurrent2attention = nn.Parameter(torch.Tensor(context_size, 1))\n\n self.reset_parameters()\n\n def reset_parameters(self):\n \"\"\"Reset parameters.\"\"\"\n stdv = 1.0 / math.sqrt(self.hidden_size)\n stdv_ctx = 1.0 / math.sqrt(self.context_size)\n\n self.input_weights_1.data.uniform_(-stdv, stdv)\n self.hidden_weights_1.data.uniform_(-stdv, stdv)\n self.input_bias_1.data.fill_(0)\n self.hidden_bias_1.data.fill_(0)\n\n self.input_weights_2.data.uniform_(-stdv_ctx, stdv_ctx)\n self.hidden_weights_2.data.uniform_(-stdv, stdv)\n self.input_bias_2.data.fill_(0)\n self.hidden_bias_2.data.fill_(0)\n\n self.context2attention.data.uniform_(-stdv_ctx, stdv_ctx)\n self.bias_context2attention.data.fill_(0)\n\n self.hidden2attention.data.uniform_(-stdv_ctx, stdv_ctx)\n self.input2attention.data.uniform_(-stdv_ctx, stdv_ctx)\n\n self.recurrent2attention.data.uniform_(-stdv_ctx, stdv_ctx)\n\n def forward(self, input, hidden, ctx, ctx_mask=None):\n \"\"\"Propogate input through the network.\"\"\"\n def recurrence(input, hidden, projected_input, projected_ctx):\n \"\"\"Recurrence helper.\"\"\"\n hx, cx = hidden # n_b x hidden_dim\n\n gates = F.linear(\n input, self.input_weights_1, self.input_bias_1\n ) + F.linear(hx, self.hidden_weights_1, self.hidden_bias_1)\n ingate, forgetgate, cellgate, outgate = gates.chunk(4, 1)\n\n ingate = F.sigmoid(ingate)\n forgetgate = F.sigmoid(forgetgate)\n cellgate = F.tanh(cellgate)\n outgate = F.sigmoid(outgate)\n\n cy = (forgetgate * cx) + (ingate * cellgate)\n hy = outgate * F.tanh(cy) # n_b x hidden_dim\n\n # Attention mechanism\n\n # Project current hidden state to context size\n hidden_ctx = F.linear(hy, self.hidden2attention)\n\n # Added projected hidden state to each projected context\n hidden_ctx_sum = projected_ctx + hidden_ctx.unsqueeze(0).expand(\n projected_ctx.size()\n )\n\n # Add this to projected input at this time step\n hidden_ctx_sum = hidden_ctx_sum + \\\n projected_input.unsqueeze(0).expand(hidden_ctx_sum.size())\n\n # Non-linearity\n hidden_ctx_sum = F.tanh(hidden_ctx_sum)\n\n # Compute alignments\n alpha = torch.bmm(\n hidden_ctx_sum.transpose(0, 1),\n self.recurrent2attention.unsqueeze(0).expand(\n hidden_ctx_sum.size(1),\n self.recurrent2attention.size(0),\n self.recurrent2attention.size(1)\n )\n ).squeeze()\n alpha = F.softmax(alpha)\n weighted_context = torch.mul(\n ctx, alpha.t().unsqueeze(2).expand(ctx.size())\n ).sum(0).squeeze()\n\n gates = F.linear(\n weighted_context, self.input_weights_2, self.input_bias_2\n ) + F.linear(hy, self.hidden_weights_2, self.hidden_bias_2)\n ingate, forgetgate, cellgate, outgate = gates.chunk(4, 1)\n\n ingate = F.sigmoid(ingate)\n forgetgate = F.sigmoid(forgetgate)\n cellgate = F.tanh(cellgate)\n outgate = F.sigmoid(outgate)\n\n cy = (forgetgate * cy) + (ingate * cellgate)\n hy = outgate * F.tanh(cy) # n_b x hidden_dim\n\n return hy, cy\n\n input = input.transpose(0, 1)\n projected_ctx = torch.bmm(\n ctx,\n self.context2attention.unsqueeze(0).expand(\n ctx.size(0),\n self.context2attention.size(0),\n self.context2attention.size(1)\n ),\n )\n projected_ctx += \\\n self.bias_context2attention.unsqueeze(0).unsqueeze(0).expand(\n projected_ctx.size()\n )\n\n projected_input = torch.bmm(\n input,\n self.input2attention.unsqueeze(0).expand(\n input.size(0),\n self.input2attention.size(0),\n self.input2attention.size(1)\n ),\n )\n\n output = []\n steps = range(input.size(0))\n for i in steps:\n hidden = recurrence(\n input[i], hidden, projected_input[i], projected_ctx\n )\n output.append(hidden[0])\n\n output = torch.cat(output, 0).view(input.size(0), *output[0].size())\n\n return output, hidden\n\n\nclass SoftDotAttention(nn.Module):\n \"\"\"Soft Dot Attention.\n\n Ref: http://www.aclweb.org/anthology/D15-1166\n Adapted from PyTorch OPEN NMT.\n \"\"\"\n\n def __init__(self, dim):\n \"\"\"Initialize layer.\"\"\"\n super(SoftDotAttention, self).__init__()\n self.linear_in = nn.Linear(dim, dim, bias=False)\n self.sm = nn.Softmax()\n self.linear_out = nn.Linear(dim * 2, dim, bias=False)\n self.tanh = nn.Tanh()\n self.mask = None\n\n def forward(self, input, context, mask=None):\n \"\"\"Propogate input through the network.\n\n input: batch x dim\n context: batch x sourceL x dim\n \"\"\"\n #print(\"PRINTING INPUT SIZE\")\n #print(input.size())\n if input.size(1) == 1:\n input = input.view(-1, input.size(-1))\n target = self.linear_in(input) # batch x dim x 1\n target = target.unsqueeze(2)\n\n # Get attention\n attn = torch.bmm(context, target).squeeze(2) # batch x sourceL\n context_size = context.size()\n\n if mask is not None:\n attn = torch_utils.mask(attn, mask)\n\n attn = self.sm(attn)\n attn3 = attn.view(attn.size(0), 1, attn.size(1)) # batch x 1 x sourceL\n\n weighted_context = torch.bmm(attn3, context).squeeze(1) # batch x dim\n h_tilde = torch.cat((weighted_context, input), 1)\n\n h_tilde = self.tanh(self.linear_out(h_tilde))\n\n #print(\"DONE PRINTING INPUT SIZE\")\n return h_tilde, attn\n\nclass LSTMAttentionDot(nn.Module):\n r\"\"\"A long short-term memory (LSTM) cell with attention.\"\"\"\n\n def __init__(self, input_size, hidden_size, batch_first=True):\n \"\"\"Initialize params.\"\"\"\n super(LSTMAttentionDot, self).__init__()\n self.input_size = input_size\n self.hidden_size = hidden_size\n self.num_layers = 1\n self.batch_first = batch_first\n\n self.input_weights = nn.Linear(input_size, 4 * hidden_size)\n self.hidden_weights = nn.Linear(hidden_size, 4 * hidden_size)\n\n self.attention_layer = SoftDotAttention(hidden_size)\n\n def forward(self, input, hidden, ctx, ctx_mask=None):\n \"\"\"Propogate input through the network.\"\"\"\n def recurrence(input, hidden):\n \"\"\"Recurrence helper.\"\"\"\n hx, cx = hidden # n_b x hidden_dim\n hx_modified = self.hidden_weights(hx)\n gates = self.input_weights(input) + hx_modified\n\n \n ingate, forgetgate, cellgate, outgate = gates.chunk(4, 1)\n\n ingate_sigm = F.sigmoid(ingate)\n forgetgate_sigm = F.sigmoid(forgetgate)\n cellgate_tanh = F.tanh(cellgate)\n outgate_sigm = F.sigmoid(outgate)\n\n cy = (forgetgate_sigm * cx) + (ingate_sigm * cellgate_tanh)\n hy = outgate_sigm * F.tanh(cy) # n_b x hidden_dim\n h_tilde, alpha = self.attention_layer(hy, ctx.transpose(0, 1))\n\n return h_tilde, cy\n\n if self.batch_first:\n input = input.transpose(0, 1)\n\n output = []\n steps = range(input.size(0))\n for i in steps:\n hidden = recurrence(input[i], hidden)\n output.append(hidden[0])\n\n cat_output = torch.cat(output, 0).view(input.size(0), *output[0].size())\n\n if self.batch_first:\n output = cat_output.transpose(0, 1)\n else:\n output = cat_output\n return output, hidden\n\n\nclass Seq2Seq(nn.Module):\n \"\"\"Container module with an encoder, deocder, embeddings.\"\"\"\n\n def __init__(\n self,\n src_emb_dim,\n trg_emb_dim,\n src_vocab_size,\n trg_vocab_size,\n src_hidden_dim,\n trg_hidden_dim,\n batch_size,\n pad_token_src,\n pad_token_trg,\n bidirectional=True,\n nlayers=2,\n nlayers_trg=1,\n dropout=0.,\n ):\n \"\"\"Initialize model.\"\"\"\n super(Seq2Seq, self).__init__()\n self.src_vocab_size = src_vocab_size\n self.trg_vocab_size = trg_vocab_size\n self.src_emb_dim = src_emb_dim\n self.trg_emb_dim = trg_emb_dim\n self.src_hidden_dim = src_hidden_dim\n self.trg_hidden_dim = trg_hidden_dim\n self.batch_size = batch_size\n self.bidirectional = bidirectional\n self.nlayers = nlayers\n self.dropout = dropout\n self.num_directions = 2 if bidirectional else 1\n self.pad_token_src = pad_token_src\n self.pad_token_trg = pad_token_trg\n self.src_hidden_dim = src_hidden_dim // 2 \\\n if self.bidirectional else src_hidden_dim\n\n self.src_embedding = nn.Embedding(\n src_vocab_size,\n src_emb_dim,\n self.pad_token_src\n )\n self.trg_embedding = nn.Embedding(\n trg_vocab_size,\n trg_emb_dim,\n self.pad_token_trg\n )\n\n self.encoder = nn.LSTM(\n src_emb_dim,\n self.src_hidden_dim,\n nlayers,\n bidirectional=bidirectional,\n batch_first=True,\n dropout=self.dropout\n )\n\n self.decoder = nn.LSTM(\n trg_emb_dim,\n trg_hidden_dim,\n nlayers_trg,\n dropout=self.dropout,\n batch_first=True\n )\n\n self.encoder2decoder = nn.Linear(\n self.src_hidden_dim * self.num_directions,\n trg_hidden_dim\n )\n self.decoder2vocab = nn.Linear(trg_hidden_dim, trg_vocab_size).cuda()\n\n self.init_weights()\n\n def init_weights(self):\n \"\"\"Initialize weights.\"\"\"\n initrange = 0.1\n self.src_embedding.weight.data.uniform_(-initrange, initrange)\n self.trg_embedding.weight.data.uniform_(-initrange, initrange)\n self.encoder2decoder.bias.data.fill_(0)\n self.decoder2vocab.bias.data.fill_(0)\n\n def get_state(self, input):\n \"\"\"Get cell states and hidden states.\"\"\"\n batch_size = input.size(0) \\\n if self.encoder.batch_first else input.size(1)\n h0_encoder = Variable(torch.zeros(\n self.encoder.num_layers * self.num_directions,\n batch_size,\n self.src_hidden_dim\n ))\n c0_encoder = Variable(torch.zeros(\n self.encoder.num_layers * self.num_directions,\n batch_size,\n self.src_hidden_dim\n ))\n\n return h0_encoder.cuda(), c0_encoder.cuda()\n\n def forward(self, input_src, input_trg, ctx_mask=None, trg_mask=None):\n \"\"\"Propogate input through the network.\"\"\"\n src_emb = self.src_embedding(input_src)\n trg_emb = self.trg_embedding(input_trg)\n\n self.h0_encoder, self.c0_encoder = self.get_state(input_src)\n\n src_h, (src_h_t, src_c_t) = self.encoder(\n src_emb, (self.h0_encoder, self.c0_encoder)\n )\n\n if self.bidirectional:\n h_t = torch.cat((src_h_t[-1], src_h_t[-2]), 1)\n c_t = torch.cat((src_c_t[-1], src_c_t[-2]), 1)\n else:\n h_t = src_h_t[-1]\n c_t = src_c_t[-1]\n\n decoder_init_state = nn.Tanh()(self.encoder2decoder(h_t))\n\n trg_h, (_, _) = self.decoder(\n trg_emb,\n (\n decoder_init_state.view(\n self.decoder.num_layers,\n decoder_init_state.size(0),\n decoder_init_state.size(1)\n ),\n c_t.view(\n self.decoder.num_layers,\n c_t.size(0),\n c_t.size(1)\n )\n )\n )\n\n trg_h_reshape = trg_h.contiguous().view(\n trg_h.size(0) * trg_h.size(1),\n trg_h.size(2)\n )\n\n decoder_logit = self.decoder2vocab(trg_h_reshape)\n decoder_logit = decoder_logit.view(\n trg_h.size(0),\n trg_h.size(1),\n decoder_logit.size(1)\n )\n\n return decoder_logit\n\n def decode(self, logits):\n \"\"\"Return probability distribution over words.\"\"\"\n logits_reshape = logits.view(-1, self.trg_vocab_size)\n word_probs = F.softmax(logits_reshape)\n word_probs = word_probs.view(\n logits.size()[0], logits.size()[1], logits.size()[2]\n )\n return word_probs\n\n\nclass Seq2SeqAutoencoder(nn.Module):\n \"\"\"Container module with an encoder, deocder, embeddings.\"\"\"\n\n def __init__(\n self,\n src_emb_dim,\n trg_emb_dim,\n src_vocab_size,\n src_hidden_dim,\n trg_hidden_dim,\n batch_size,\n pad_token_src,\n bidirectional=False,\n nlayers=1,\n nlayers_trg=1,\n dropout=0.,\n ):\n \"\"\"Initialize model.\"\"\"\n super(Seq2SeqAutoencoder, self).__init__()\n self.src_vocab_size = src_vocab_size\n self.src_emb_dim = src_emb_dim\n self.trg_emb_dim = trg_emb_dim\n self.src_hidden_dim = src_hidden_dim\n self.trg_hidden_dim = trg_hidden_dim\n self.batch_size = batch_size\n self.bidirectional = bidirectional\n self.nlayers = nlayers\n self.dropout = dropout\n self.num_directions = 2 if bidirectional else 1\n self.pad_token_src = pad_token_src\n\n self.src_embedding = nn.Embedding(\n src_vocab_size,\n src_emb_dim,\n self.pad_token_src\n )\n self.trg_embedding = nn.Embedding(\n src_vocab_size,\n trg_emb_dim,\n self.pad_token_src\n )\n\n if self.bidirectional and self.nlayers > 1:\n self.encoder = DeepBidirectionalLSTM(\n self.src_emb_dim,\n self.src_hidden_dim,\n self.nlayers,\n self.dropout,\n True\n )\n\n else:\n hidden_dim = self.src_hidden_dim // 2 \\\n if self.bidirectional else self.src_hidden_dim\n self.encoder = nn.LSTM(\n src_emb_dim,\n hidden_dim,\n nlayers,\n bidirectional=bidirectional,\n batch_first=True,\n dropout=self.dropout\n )\n\n self.decoder = nn.LSTM(\n trg_emb_dim,\n trg_hidden_dim,\n nlayers_trg,\n dropout=self.dropout,\n batch_first=True\n )\n\n self.encoder2decoder = nn.Linear(\n self.src_hidden_dim,\n trg_hidden_dim\n )\n self.decoder2vocab = nn.Linear(trg_hidden_dim, src_vocab_size).cuda()\n\n self.init_weights()\n\n def init_weights(self):\n \"\"\"Initialize weights.\"\"\"\n initrange = 0.1\n self.src_embedding.weight.data.uniform_(-initrange, initrange)\n self.trg_embedding.weight.data.uniform_(-initrange, initrange)\n self.encoder2decoder.bias.data.fill_(0)\n self.decoder2vocab.bias.data.fill_(0)\n\n def get_state(self, input):\n \"\"\"Get cell states and hidden states.\"\"\"\n batch_size = input.size(0) \\\n if self.encoder.batch_first else input.size(1)\n h0_encoder = Variable(torch.zeros(\n self.encoder.num_layers * self.num_directions,\n batch_size,\n self.src_hidden_dim\n ))\n c0_encoder = Variable(torch.zeros(\n self.encoder.num_layers * self.num_directions,\n batch_size,\n self.src_hidden_dim\n ))\n\n return h0_encoder.cuda(), c0_encoder.cuda()\n\n def forward(self, input, ctx_mask=None, trg_mask=None):\n \"\"\"Propogate input through the network.\"\"\"\n src_emb = self.src_embedding(input)\n trg_emb = self.trg_embedding(input)\n\n if self.bidirectional and self.nlayers > 1:\n src_h, (src_h_t, src_c_t) = self.encoder(src_emb)\n\n else:\n self.h0_encoder, self.c0_encoder = self.get_state(input)\n\n src_h, (src_h_t, src_c_t) = self.encoder(\n src_emb, (self.h0_encoder, self.c0_encoder)\n )\n\n if self.bidirectional and self.nlayers == 1:\n h_t = torch.cat((src_h_t[-1], src_h_t[-2]), 1)\n c_t = torch.cat((src_c_t[-1], src_c_t[-2]), 1)\n else:\n h_t = src_h_t[-1]\n c_t = src_c_t[-1]\n\n decoder_init_state = nn.Tanh()(self.encoder2decoder(h_t))\n\n trg_h, (_, _) = self.decoder(\n trg_emb,\n (\n decoder_init_state.view(\n self.decoder.num_layers,\n decoder_init_state.size(0),\n decoder_init_state.size(1)\n ),\n c_t.view(\n self.decoder.num_layers,\n c_t.size(0),\n c_t.size(1)\n )\n )\n )\n trg_h_reshape = trg_h.contiguous().view(\n trg_h.size(0) * trg_h.size(1),\n trg_h.size(2)\n )\n decoder_logit = self.decoder2vocab(trg_h_reshape)\n decoder_logit = decoder_logit.view(\n trg_h.size(0),\n trg_h.size(1),\n decoder_logit.size(1)\n )\n\n return decoder_logit\n\n def decode(self, logits):\n \"\"\"Return probability distribution over words.\"\"\"\n logits_reshape = logits.view(-1, self.src_vocab_size)\n word_probs = F.softmax(logits_reshape)\n word_probs = word_probs.view(\n logits.size()[0], logits.size()[1], logits.size()[2]\n )\n return word_probs\n\n\nclass Seq2SeqAttention(nn.Module):\n \"\"\"Container module with an encoder, deocder, embeddings.\"\"\"\n\n def __init__(\n self,\n src_emb_dim,\n trg_emb_dim,\n src_vocab_size,\n trg_vocab_size,\n src_hidden_dim,\n trg_hidden_dim,\n ctx_hidden_dim,\n attention_mode,\n batch_size,\n pad_token_src,\n pad_token_trg,\n bidirectional=True,\n nlayers=2,\n nlayers_trg=2,\n dropout=0.,\n ):\n \"\"\"Initialize model.\"\"\"\n super(Seq2SeqAttention, self).__init__()\n self.src_vocab_size = src_vocab_size\n self.trg_vocab_size = trg_vocab_size\n self.src_emb_dim = src_emb_dim\n self.trg_emb_dim = trg_emb_dim\n self.src_hidden_dim = src_hidden_dim\n self.trg_hidden_dim = trg_hidden_dim\n self.ctx_hidden_dim = ctx_hidden_dim\n self.attention_mode = attention_mode\n self.batch_size = batch_size\n self.bidirectional = bidirectional\n self.nlayers = nlayers\n self.dropout = dropout\n self.num_directions = 2 if bidirectional else 1\n self.pad_token_src = pad_token_src\n self.pad_token_trg = pad_token_trg\n\n self.src_embedding = nn.Embedding(\n src_vocab_size,\n src_emb_dim,\n self.pad_token_src\n )\n self.trg_embedding = nn.Embedding(\n trg_vocab_size,\n trg_emb_dim,\n self.pad_token_trg\n )\n\n self.src_hidden_dim = src_hidden_dim // 2 \\\n if self.bidirectional else src_hidden_dim\n self.encoder = nn.LSTM(\n src_emb_dim,\n self.src_hidden_dim,\n nlayers,\n bidirectional=bidirectional,\n batch_first=True,\n dropout=self.dropout\n )\n\n self.decoder = LSTMAttentionDot(\n trg_emb_dim,\n trg_hidden_dim,\n batch_first=True\n )\n\n self.encoder2decoder = nn.Linear(\n self.src_hidden_dim * self.num_directions,\n trg_hidden_dim\n )\n self.decoder2vocab = nn.Linear(trg_hidden_dim, trg_vocab_size)\n\n self.init_weights()\n\n def init_weights(self):\n \"\"\"Initialize weights.\"\"\"\n initrange = 0.1\n self.src_embedding.weight.data.uniform_(-initrange, initrange)\n self.trg_embedding.weight.data.uniform_(-initrange, initrange)\n self.encoder2decoder.bias.data.fill_(0)\n self.decoder2vocab.bias.data.fill_(0)\n\n def get_state(self, input):\n \"\"\"Get cell states and hidden states.\"\"\"\n batch_size = input.size(0) \\\n if self.encoder.batch_first else input.size(1)\n h0_encoder = Variable(torch.zeros(\n self.encoder.num_layers * self.num_directions,\n batch_size,\n self.src_hidden_dim\n ), requires_grad=False)\n c0_encoder = Variable(torch.zeros(\n self.encoder.num_layers * self.num_directions,\n batch_size,\n self.src_hidden_dim\n ), requires_grad=False)\n\n return h0_encoder.cuda(), c0_encoder.cuda()\n\n def forward(self, input_src, input_trg, trg_mask=None, ctx_mask=None):\n \"\"\"Propogate input through the network.\"\"\"\n src_emb = self.src_embedding(input_src)\n trg_emb = self.trg_embedding(input_trg)\n\n self.h0_encoder, self.c0_encoder = self.get_state(input_src)\n\n src_h, (src_h_t, src_c_t) = self.encoder(\n src_emb, (self.h0_encoder, self.c0_encoder)\n )\n\n if self.bidirectional:\n h_t = torch.cat((src_h_t[-1], src_h_t[-2]), 1)\n c_t = torch.cat((src_c_t[-1], src_c_t[-2]), 1)\n else:\n h_t = src_h_t[-1]\n c_t = src_c_t[-1]\n decoder_init_state = nn.Tanh()(self.encoder2decoder(h_t))\n\n ctx = src_h.transpose(0, 1)\n\n trg_h, (_, _) = self.decoder(\n trg_emb,\n (decoder_init_state, c_t),\n ctx,\n ctx_mask\n )\n\n trg_h_reshape = trg_h.contiguous().view(\n trg_h.size()[0] * trg_h.size()[1],\n trg_h.size()[2]\n )\n decoder_logit = self.decoder2vocab(trg_h_reshape)\n decoder_logit = decoder_logit.view(\n trg_h.size()[0],\n trg_h.size()[1],\n decoder_logit.size()[1]\n )\n return decoder_logit\n\n def decode(self, logits):\n \"\"\"Return probability distribution over words.\"\"\"\n logits_reshape = logits.view(-1, self.trg_vocab_size)\n word_probs = F.softmax(logits_reshape)\n word_probs = word_probs.view(\n logits.size()[0], logits.size()[1], logits.size()[2]\n )\n return word_probs\n\n\nclass Seq2SeqAttentionSharedEmbedding(nn.Module):\n \"\"\"Container module with an encoder, deocder, embeddings.\"\"\"\n\n def __init__(\n self,\n emb_dim,\n vocab_size,\n src_hidden_dim,\n trg_hidden_dim,\n ctx_hidden_dim,\n attention_mode,\n batch_size,\n pad_token_src,\n pad_token_trg,\n bidirectional=True,\n nlayers=2,\n nlayers_trg=2,\n dropout=0.,\n ):\n \"\"\"Initialize model.\"\"\"\n super(Seq2SeqAttentionSharedEmbedding, self).__init__()\n self.vocab_size = vocab_size\n self.emb_dim = emb_dim\n self.src_hidden_dim = src_hidden_dim\n self.trg_hidden_dim = trg_hidden_dim\n self.ctx_hidden_dim = ctx_hidden_dim\n self.attention_mode = attention_mode\n self.batch_size = batch_size\n self.bidirectional = bidirectional\n self.nlayers = nlayers\n self.dropout = dropout\n self.num_directions = 2 if bidirectional else 1\n self.pad_token_src = pad_token_src\n self.pad_token_trg = pad_token_trg\n\n self.embedding = nn.Embedding(\n vocab_size,\n emb_dim,\n self.pad_token_src\n )\n\n self.src_hidden_dim = src_hidden_dim // 2 \\\n if self.bidirectional else src_hidden_dim\n\n self.encoder = nn.LSTM(\n emb_dim,\n self.src_hidden_dim,\n nlayers,\n bidirectional=bidirectional,\n batch_first=True,\n dropout=self.dropout\n )\n\n self.decoder = LSTMAttentionDot(\n emb_dim,\n trg_hidden_dim,\n batch_first=True\n )\n\n self.encoder2decoder = nn.Linear(\n self.src_hidden_dim * self.num_directions,\n trg_hidden_dim\n )\n self.decoder2vocab = nn.Linear(trg_hidden_dim, vocab_size)\n\n self.init_weights()\n\n def init_weights(self):\n \"\"\"Initialize weights.\"\"\"\n initrange = 0.1\n self.embedding.weight.data.uniform_(-initrange, initrange)\n self.encoder2decoder.bias.data.fill_(0)\n self.decoder2vocab.bias.data.fill_(0)\n\n def get_state(self, input):\n \"\"\"Get cell states and hidden states.\"\"\"\n batch_size = input.size(0) \\\n if self.encoder.batch_first else input.size(1)\n\n h0_encoder = Variable(torch.zeros(\n self.encoder.num_layers * self.num_directions,\n batch_size,\n self.src_hidden_dim\n ), requires_grad=False)\n\n c0_encoder = Variable(torch.zeros(\n self.encoder.num_layers * self.num_directions,\n batch_size,\n self.src_hidden_dim\n ), requires_grad=False)\n\n return h0_encoder.cuda(), c0_encoder.cuda()\n\n def forward(self, input_src, input_trg, trg_mask=None, ctx_mask=None):\n \"\"\"Propogate input through the network.\"\"\"\n src_emb = self.embedding(input_src)\n trg_emb = self.embedding(input_trg)\n\n self.h0_encoder, self.c0_encoder = self.get_state(input_src)\n\n src_h, (src_h_t, src_c_t) = self.encoder(\n src_emb, (self.h0_encoder, self.c0_encoder)\n )\n\n if self.bidirectional:\n h_t = torch.cat((src_h_t[-1], src_h_t[-2]), 1)\n c_t = torch.cat((src_c_t[-1], src_c_t[-2]), 1)\n else:\n h_t = src_h_t[-1]\n c_t = src_c_t[-1]\n\n decoder_init_state = nn.Tanh()(self.encoder2decoder(h_t))\n\n ctx = src_h.transpose(0, 1)\n\n trg_h, (_, _) = self.decoder(\n trg_emb,\n (decoder_init_state, c_t),\n ctx,\n ctx_mask\n )\n\n trg_h_reshape = trg_h.contiguous().view(\n trg_h.size()[0] * trg_h.size()[1],\n trg_h.size()[2]\n )\n\n decoder_logit = self.decoder2vocab(trg_h_reshape)\n decoder_logit = decoder_logit.view(\n trg_h.size()[0],\n trg_h.size()[1],\n decoder_logit.size()[1]\n )\n return decoder_logit\n\n def decode(self, logits):\n \"\"\"Return probability distribution over words.\"\"\"\n logits_reshape = logits.view(-1, self.vocab_size)\n word_probs = F.softmax(logits_reshape)\n word_probs = word_probs.view(\n logits.size()[0], logits.size()[1], logits.size()[2]\n )\n return word_probs\n\n\nclass Seq2SeqFastAttention(nn.Module):\n \"\"\"Container module with an encoder, deocder, embeddings.\"\"\"\n\n def __init__(\n self,\n src_emb_dim,\n trg_emb_dim,\n src_vocab_size,\n trg_vocab_size,\n src_hidden_dim,\n trg_hidden_dim,\n batch_size,\n pad_token_src,\n pad_token_trg,\n bidirectional=True,\n nlayers=2,\n nlayers_trg=2,\n dropout=0.,\n ):\n \"\"\"Initialize model.\"\"\"\n super(Seq2SeqFastAttention, self).__init__()\n self.src_vocab_size = src_vocab_size\n self.trg_vocab_size = trg_vocab_size\n self.src_emb_dim = src_emb_dim\n self.trg_emb_dim = trg_emb_dim\n self.src_hidden_dim = src_hidden_dim\n self.trg_hidden_dim = trg_hidden_dim\n self.batch_size = batch_size\n self.bidirectional = bidirectional\n self.nlayers = nlayers\n self.dropout = dropout\n self.num_directions = 2 if bidirectional else 1\n self.pad_token_src = pad_token_src\n self.pad_token_trg = pad_token_trg\n\n assert trg_hidden_dim == src_hidden_dim\n self.src_embedding = nn.Embedding(\n src_vocab_size,\n src_emb_dim,\n self.pad_token_src\n )\n self.trg_embedding = nn.Embedding(\n trg_vocab_size,\n trg_emb_dim,\n self.pad_token_trg\n )\n\n self.src_hidden_dim = src_hidden_dim // 2 \\\n if self.bidirectional else src_hidden_dim\n self.encoder = nn.LSTM(\n src_emb_dim,\n self.src_hidden_dim,\n nlayers,\n bidirectional=bidirectional,\n batch_first=True,\n dropout=self.dropout\n )\n\n self.decoder = nn.LSTM(\n trg_emb_dim,\n trg_hidden_dim,\n nlayers_trg,\n batch_first=True,\n dropout=self.dropout\n )\n\n self.encoder2decoder = nn.Linear(\n self.src_hidden_dim * self.num_directions,\n trg_hidden_dim\n )\n self.decoder2vocab = nn.Linear(2 * trg_hidden_dim, trg_vocab_size)\n\n self.init_weights()\n\n def init_weights(self):\n \"\"\"Initialize weights.\"\"\"\n initrange = 0.1\n self.src_embedding.weight.data.uniform_(-initrange, initrange)\n self.trg_embedding.weight.data.uniform_(-initrange, initrange)\n self.encoder2decoder.bias.data.fill_(0)\n self.decoder2vocab.bias.data.fill_(0)\n\n def get_state(self, input):\n \"\"\"Get cell states and hidden states.\"\"\"\n batch_size = input.size(0) \\\n if self.encoder.batch_first else input.size(1)\n h0_encoder = Variable(torch.zeros(\n self.encoder.num_layers * self.num_directions,\n batch_size,\n self.src_hidden_dim\n ), requires_grad=False)\n c0_encoder = Variable(torch.zeros(\n self.encoder.num_layers * self.num_directions,\n batch_size,\n self.src_hidden_dim\n ), requires_grad=False)\n\n return h0_encoder.cuda(), c0_encoder.cuda()\n\n def forward(self, input_src, input_trg, trg_mask=None, ctx_mask=None):\n \"\"\"Propogate input through the network.\"\"\"\n src_emb = self.src_embedding(input_src)\n trg_emb = self.trg_embedding(input_trg)\n\n self.h0_encoder, self.c0_encoder = self.get_state(input_src)\n\n src_h, (src_h_t, src_c_t) = self.encoder(\n src_emb, (self.h0_encoder, self.c0_encoder)\n ) # bsize x seqlen x dim\n\n if self.bidirectional:\n h_t = torch.cat((src_h_t[-1], src_h_t[-2]), 1)\n c_t = torch.cat((src_c_t[-1], src_c_t[-2]), 1)\n else:\n h_t = src_h_t[-1]\n c_t = src_c_t[-1]\n decoder_init_state = nn.Tanh()(self.encoder2decoder(h_t))\n\n trg_h, (_, _) = self.decoder(\n trg_emb,\n (\n decoder_init_state.view(\n self.decoder.num_layers,\n decoder_init_state.size(0),\n decoder_init_state.size(1)\n ),\n c_t.view(\n self.decoder.num_layers,\n c_t.size(0),\n c_t.size(1)\n )\n )\n ) # bsize x seqlen x dim\n\n # Fast Attention dot product\n\n # bsize x seqlen_src x seq_len_trg\n alpha = torch.bmm(src_h, trg_h.transpose(1, 2))\n # bsize x seq_len_trg x dim\n alpha = torch.bmm(alpha.transpose(1, 2), src_h)\n # bsize x seq_len_trg x (2 * dim)\n trg_h_reshape = torch.cat((trg_h, alpha), 2)\n\n trg_h_reshape = trg_h_reshape.view(\n trg_h_reshape.size(0) * trg_h_reshape.size(1),\n trg_h_reshape.size(2)\n )\n decoder_logit = self.decoder2vocab(trg_h_reshape)\n decoder_logit = decoder_logit.view(\n trg_h.size()[0],\n trg_h.size()[1],\n decoder_logit.size()[1]\n )\n return decoder_logit\n\n def decode(self, logits):\n \"\"\"Return probability distribution over words.\"\"\"\n logits_reshape = logits.view(-1, self.trg_vocab_size)\n word_probs = F.softmax(logits_reshape)\n word_probs = word_probs.view(\n logits.size()[0], logits.size()[1], logits.size()[2]\n )\n return word_probs\n\n\n"
] | [
[
"torch.nn.Softmax",
"torch.nn.Dropout",
"torch.nn.functional.softmax",
"torch.Tensor",
"torch.nn.LSTM",
"torch.cat",
"torch.zeros",
"torch.nn.Embedding",
"torch.nn.Tanh",
"torch.nn.Linear",
"torch.nn.functional.sigmoid",
"torch.bmm",
"torch.stack",
"torch.nn.functional.tanh",
"torch.nn.functional.linear"
]
] |
priyathamkat/unpaired-image-denoising | [
"de059cd0ad6bda7d615dadcdb4f7408b165cdc8e"
] | [
"src/glow/invertible_layers/additive.py"
] | [
"import torch\nimport torch.nn as nn\n\nfrom .invertible import InvertibleModule\n\ncuda_device = torch.device(\"cuda:0\")\n\n\nclass Additive(InvertibleModule):\n def __init__(self, num_channels, net_channels=128):\n super().__init__()\n assert num_channels % 2 == 0\n self.split_size = num_channels // 2\n self.net = nn.Sequential(\n nn.Conv2d(self.split_size, net_channels, 3, padding=1, bias=False),\n nn.BatchNorm2d(net_channels),\n nn.ReLU(),\n nn.Conv2d(net_channels, net_channels, 1, bias=False),\n nn.BatchNorm2d(net_channels),\n nn.ReLU(),\n nn.Conv2d(net_channels, self.split_size, 3, padding=1),\n )\n self._reset_parameters()\n\n def _reset_parameters(self):\n with torch.no_grad():\n nn.init.zeros_(self.net[-1].weight)\n nn.init.zeros_(self.net[-1].bias)\n\n def forward(self, x, log_det):\n x_a, x_b = torch.split(x, self.split_size, 1)\n s = self.net(x_b)\n\n y_a = x_a + s\n y_b = x_b\n y = torch.cat((y_a, y_b), 1)\n return y, log_det\n\n @torch.no_grad()\n def invert(self, y, log_det):\n y_a, y_b = torch.split(y, self.split_size, 1)\n s = self.net(y_b)\n\n x_a = y_a - s\n x_b = y_b\n x = torch.cat((x_a, x_b), 1)\n return x, log_det\n\n\nif __name__ == \"__main__\":\n additive = Additive(4)\n x = torch.randn(2, 4, 4, 4).to(cuda_device)\n log_det = torch.randn(1).to(cuda_device)\n x_, log_det_ = additive.invert(*additive(x, log_det))\n print(x[0, 0])\n print(x_[0, 0])\n print(torch.allclose(x, x_))\n print(torch.allclose(log_det, log_det_))\n"
] | [
[
"torch.cat",
"torch.nn.init.zeros_",
"torch.randn",
"torch.nn.Conv2d",
"torch.no_grad",
"torch.nn.BatchNorm2d",
"torch.split",
"torch.device",
"torch.allclose",
"torch.nn.ReLU"
]
] |
pleap-inc/face-match | [
"8a705e9f2a9258c66cb340cd6e16e316a7790873"
] | [
"code.py"
] | [
"import face_recognition\nimport matplotlib.pyplot as plt\nimport glob\nimport json\nimport array \nimport sys\nfrom tqdm import tqdm\n\nargs = sys.argv\n# フォルダ内の全画像ファイルのパスを取得\nfile_paths = []\n\nfiles = glob.glob(\"./tokyo_hot/*\")\nbar_analyze_img = tqdm(total = len(files))\nprint(\"____________________start appending file paths__________________\")\nfor file in files:\n file_paths.append(file)\n bar_analyze_img.update(1)\nprint(\"____________________appending file paths ends__________________\")\n# 保存されている人物の顔の画像を読み込む。\nknown_face_imgs = []\nprint(\"____________________start appending img files__________________\")\ni = 0\n\nfile_names = []\n\nfor path in file_paths:\n img = face_recognition.load_image_file(path)\n file_names.append(path)\n known_face_imgs.append(img)\n if i % 10 == 0:\n print(\"###\")\n print(\"###\", end=\"\")\n i = i + 1\n \nprint(\"\\n____________________appending img files end__________________\")\n\n# 認証する人物の顔の画像を読み込む。\nface_img_to_check = face_recognition.load_image_file(args[1])\n\n# 顔の画像から顔の領域を検出する。\n\nknown_face_locs = [] \n\nbar_analyze_img = tqdm(total = len(known_face_imgs))\n\nfor img in known_face_imgs:\n loc = face_recognition.face_locations(img, model=\"cnn\")\n # assert len(loc) == 1, \"画像から顔の検出に失敗したか、2人以上の顔が検出されました\"\n # if len(loc) == 0: \n # continue\n # print(len(loc))\n known_face_locs.append(loc)\n bar_analyze_img.update(1)\n\nface_loc_to_check = face_recognition.face_locations(face_img_to_check, model=\"cnn\")\nassert len(face_loc_to_check) == 1, \"画像から顔の検出に失敗したか、2人以上の顔が検出されました\"\n\ndef draw_face_locations(img, locations):\n fig, ax = plt.subplots()\n ax.imshow(img)\n ax.set_axis_off()\n for i, (top, right, bottom, left) in enumerate(locations):\n # 長方形を描画する。\n w, h = right - left, bottom - top\n ax.add_patch(plt.Rectangle((left, top), w, h, ec=\"r\", lw=2, fill=None))\n plt.show()\n\ndraw_face_locations(face_img_to_check, face_loc_to_check)\n\n# 顔の領域から特徴量を抽出する。\nknown_face_encodings = []\nfor img, loc in zip(known_face_imgs, known_face_locs):\n if len(loc) != 1: \n continue\n (encoding,) = face_recognition.face_encodings(img, loc)\n known_face_encodings.append(encoding)\n\n(face_encoding_to_check,) = face_recognition.face_encodings(\n face_img_to_check, face_loc_to_check\n)\n\n# 顔を認識する\nmatches = face_recognition.compare_faces(known_face_encodings, face_encoding_to_check)\nprint(matches) # [True, False, False]\n\ndists = face_recognition.face_distance(known_face_encodings, face_encoding_to_check)\nprint(dists)\nlist = []\nn = 0\n\nfor i in dists: \n if i < 0.35: \n draw_face_locations(known_face_imgs[n], known_face_locs[n])\n print(file_names[n])\n n = n + 1\n"
] | [
[
"matplotlib.pyplot.Rectangle",
"matplotlib.pyplot.show",
"matplotlib.pyplot.subplots"
]
] |
devanshusomani99/myFM | [
"d8e3d93de7c4a3dc19551c07d5f1d71d13f6abc6"
] | [
"examples/ml-10m-regression.py"
] | [
"from myfm.gibbs import MyFMOrderedProbit\nfrom typing import List, Dict, Union\nimport pandas as pd\nimport argparse\nimport pickle\nimport numpy as np\nimport myfm\nfrom myfm import RelationBlock, MyFMOrderedProbit, MyFMRegressor\nfrom myfm.utils.benchmark_data import MovieLens10MDataManager\nfrom myfm.utils.callbacks.libfm import (\n LibFMLikeCallbackBase,\n OrderedProbitCallback,\n RegressionCallback,\n)\nfrom myfm.utils.encoders import CategoryValueToSparseEncoder\nfrom scipy import sparse as sps\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\n description=\"\"\"\n This script apply the method and evaluation protocal proposed in\n \"On the Difficulty of Evaluating Baselines\" paper by Rendle et al,\n against smaller Movielens 1M dataset, using myFM.\n \"\"\",\n formatter_class=argparse.ArgumentDefaultsHelpFormatter,\n )\n\n parser.add_argument(\n \"fold_index\",\n type=int,\n help=\"which index set to use as a test within 10-fold CV.\",\n )\n parser.add_argument(\n \"-a\",\n \"--algorithm\",\n type=str,\n choices=[\"regression\", \"oprobit\"],\n default=\"regression\",\n help=\"specify the output type.\",\n )\n parser.add_argument(\n \"-i\", \"--iteration\", type=int, help=\"mcmc iteration\", default=512\n )\n parser.add_argument(\n \"-d\",\n \"--dimension\",\n type=int,\n help=\"fm embedding dimension\",\n default=128,\n )\n parser.add_argument(\n \"--stricter_protocol\",\n action=\"store_true\",\n help=\"Whether to use the \\\"stricter\\\" protocol (i.e., don't include the test set implicit information) stated in [Rendle, '19].\",\n default=True,\n )\n parser.add_argument(\n \"-f\",\n \"--feature\",\n type=str,\n choices=[\"mf\", \"svdpp\", \"timesvd\", \"timesvdpp\", \"timesvdpp_flipped\"],\n help=\"feature set used in the experiment.\",\n default=\"timesvdpp_flipped\",\n )\n args = parser.parse_args()\n\n random_seed = 42\n\n # Additional features.\n # We add\n # 1. date of evaluation as categorical variables\n # 2. \"all users who have evaluated a movie in the train set\" or\n # 3. \"all movies rated by a user\" as a feature of user/movie.\n if args.feature == \"mf\":\n use_date = False\n use_iu = False\n use_ii = False\n elif args.feature == \"svdpp\":\n use_date = False\n use_iu = True\n use_ii = False\n elif args.feature == \"timesvd\":\n use_date = True\n use_iu = False\n use_ii = False\n elif args.feature == \"timesvdpp\":\n use_date = True\n use_iu = True\n use_ii = False\n elif args.feature == \"timesvdpp_flipped\":\n use_date = True # use date info or not\n use_iu = True # use implicit user feature\n use_ii = True # use implicit item feature\n else:\n raise ValueError(\"unknown feature set specified.\")\n\n FOLD_INDEX = args.fold_index\n ITERATION = args.iteration\n DIMENSION = args.dimension\n if FOLD_INDEX < 0 or FOLD_INDEX >= 10:\n raise ValueError(\"fold_index must be in the range(10).\")\n ALGORITHM = args.algorithm\n data_manager = MovieLens10MDataManager()\n df_train, df_test = data_manager.load_rating_kfold_split(\n 10, FOLD_INDEX, random_seed\n )\n\n if ALGORITHM == \"oprobit\":\n # interpret the rating 0.5, 1.0 ... , 5.0 as class (0, 1, ... , 10)\n for df_ in [df_train, df_test]:\n df_[\"rating\"] -= 0.5\n df_[\"rating\"] *= 2\n df_[\"rating\"] = df_.rating.astype(np.int32)\n\n if args.stricter_protocol:\n implicit_data_source = df_train\n else:\n implicit_data_source = pd.concat([df_train, df_test])\n\n user_to_internal = CategoryValueToSparseEncoder[int](\n implicit_data_source.user_id.values\n )\n movie_to_internal = CategoryValueToSparseEncoder[int](\n implicit_data_source.movie_id.values\n )\n\n print(\n \"df_train.shape = {}, df_test.shape = {}\".format(df_train.shape, df_test.shape)\n )\n # treat the days of events as categorical variable\n date_encoder = CategoryValueToSparseEncoder[pd.Timestamp](\n implicit_data_source.timestamp.dt.date.values\n )\n\n def categorize_date(df):\n return date_encoder.to_sparse(df.timestamp.dt.date.values)\n\n movie_vs_watched: Dict[int, List[int]] = dict()\n user_vs_watched: Dict[int, List[int]] = dict()\n\n for row in implicit_data_source.itertuples():\n user_id = row.user_id\n movie_id = row.movie_id\n movie_vs_watched.setdefault(movie_id, list()).append(user_id)\n user_vs_watched.setdefault(user_id, list()).append(movie_id)\n\n if use_date:\n X_date_train = categorize_date(df_train)\n X_date_test = categorize_date(df_test)\n else:\n X_date_train, X_date_test = (None, None)\n\n # setup grouping\n feature_group_sizes = []\n if use_date:\n feature_group_sizes.append(\n len(date_encoder), # date\n )\n\n feature_group_sizes.append(len(user_to_internal)) # user ids\n\n if use_iu:\n # all movies which a user watched\n feature_group_sizes.append(len(movie_to_internal))\n\n feature_group_sizes.append(len(movie_to_internal)) # movie ids\n\n if use_ii:\n feature_group_sizes.append(\n len(user_to_internal) # all the users who watched a movies\n )\n\n grouping = [i for i, size in enumerate(feature_group_sizes) for _ in range(size)]\n\n def augment_user_id(user_ids: List[int]) -> sps.csr_matrix:\n X = user_to_internal.to_sparse(user_ids)\n if not use_iu:\n return X\n data: List[float] = []\n row: List[int] = []\n col: List[int] = []\n for index, user_id in enumerate(user_ids):\n watched_movies = user_vs_watched.get(user_id, [])\n normalizer = 1 / max(len(watched_movies), 1) ** 0.5\n for mid in watched_movies:\n data.append(normalizer)\n col.append(movie_to_internal[mid])\n row.append(index)\n return sps.hstack(\n [\n X,\n sps.csr_matrix(\n (data, (row, col)),\n shape=(len(user_ids), len(movie_to_internal)),\n ),\n ],\n format=\"csr\",\n )\n\n def augment_movie_id(movie_ids: List[int]):\n X = movie_to_internal.to_sparse(movie_ids)\n if not use_ii:\n return X\n\n data: List[float] = []\n row: List[int] = []\n col: List[int] = []\n\n for index, movie_id in enumerate(movie_ids):\n watched_users = movie_vs_watched.get(movie_id, [])\n normalizer = 1 / max(len(watched_users), 1) ** 0.5\n for uid in watched_users:\n data.append(normalizer)\n row.append(index)\n col.append(user_to_internal[uid])\n return sps.hstack(\n [\n X,\n sps.csr_matrix(\n (data, (row, col)),\n shape=(len(movie_ids), len(user_to_internal)),\n ),\n ]\n )\n\n # Create RelationBlock.\n train_blocks: List[RelationBlock] = []\n test_blocks: List[RelationBlock] = []\n for source, target in [(df_train, train_blocks), (df_test, test_blocks)]:\n unique_users, user_map = np.unique(source.user_id, return_inverse=True)\n target.append(RelationBlock(user_map, augment_user_id(unique_users)))\n unique_movies, movie_map = np.unique(source.movie_id, return_inverse=True)\n target.append(RelationBlock(movie_map, augment_movie_id(unique_movies)))\n\n trace_path = \"rmse_{0}_fold_{1}.csv\".format(ALGORITHM, FOLD_INDEX)\n\n callback: LibFMLikeCallbackBase\n fm: Union[MyFMRegressor, MyFMOrderedProbit]\n if ALGORITHM == \"regression\":\n fm = myfm.MyFMRegressor(rank=DIMENSION)\n callback = RegressionCallback(\n ITERATION,\n X_date_test,\n df_test.rating.values,\n X_rel_test=test_blocks,\n clip_min=0.5,\n clip_max=5.0,\n trace_path=trace_path,\n )\n else:\n fm = myfm.MyFMOrderedProbit(rank=DIMENSION)\n callback = OrderedProbitCallback(\n ITERATION,\n X_date_test,\n df_test.rating.values,\n n_class=10,\n X_rel_test=test_blocks,\n trace_path=trace_path,\n )\n fm.fit(\n X_date_train,\n df_train.rating.values,\n X_rel=train_blocks,\n grouping=grouping,\n n_iter=callback.n_iter,\n callback=callback,\n n_kept_samples=1,\n )\n with open(\n \"callback_result_{0}_fold_{1}.pkl\".format(ALGORITHM, FOLD_INDEX), \"wb\"\n ) as ofs:\n pickle.dump(callback, ofs)\n"
] | [
[
"pandas.concat",
"numpy.unique"
]
] |
hongxu-jia/tensorboard | [
"98d4dadc61fd5a0580bed808653c59fb37748893"
] | [
"tensorboard/plugins/scalar/scalars_plugin_test.py"
] | [
"# -*- coding: utf-8 -*-\n# Copyright 2017 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\"\"\"Integration tests for the Scalars Plugin.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport csv\nimport json\nimport os.path\n\nfrom six import StringIO\nfrom six.moves import xrange # pylint: disable=redefined-builtin\nimport tensorflow as tf\nfrom werkzeug import test as werkzeug_test\nfrom werkzeug import wrappers\n\nfrom tensorboard.backend import application\nfrom tensorboard.backend.event_processing import data_provider\nfrom tensorboard.backend.event_processing import (\n plugin_event_multiplexer as event_multiplexer,\n)\nfrom tensorboard.backend.event_processing import tag_types\nfrom tensorboard.plugins import base_plugin\nfrom tensorboard.plugins.scalar import scalars_plugin\nfrom tensorboard.plugins.scalar import summary\nfrom tensorboard.util import test_util\n\n\ntf.compat.v1.enable_eager_execution()\n\n\nclass ScalarsPluginTest(tf.test.TestCase):\n\n _STEPS = 9\n\n _LEGACY_SCALAR_TAG = \"ancient-values\"\n _SCALAR_TAG = \"simple-values\"\n _HISTOGRAM_TAG = \"complicated-values\"\n\n _DISPLAY_NAME = \"Walrus population\"\n _DESCRIPTION = \"the *most* valuable statistic\"\n _HTML_DESCRIPTION = \"<p>the <em>most</em> valuable statistic</p>\"\n\n _RUN_WITH_LEGACY_SCALARS = \"_RUN_WITH_LEGACY_SCALARS\"\n _RUN_WITH_SCALARS = \"_RUN_WITH_SCALARS\"\n _RUN_WITH_SCALARS_2 = \"_RUN_WITH_SCALARS_2\"\n _RUN_WITH_SCALARS_3 = \"_RUN_WITH_SCALARS_3\"\n _RUN_WITH_HISTOGRAM = \"_RUN_WITH_HISTOGRAM\"\n\n def load_plugin(self, run_names):\n logdir = self.get_temp_dir()\n for run_name in run_names:\n self.generate_run(logdir, run_name)\n multiplexer = event_multiplexer.EventMultiplexer(\n size_guidance={\n # don't truncate my test data, please\n tag_types.TENSORS: self._STEPS,\n }\n )\n multiplexer.AddRunsFromDirectory(logdir)\n multiplexer.Reload()\n\n provider = data_provider.MultiplexerDataProvider(multiplexer, logdir)\n ctx = base_plugin.TBContext(\n logdir=logdir,\n data_provider=provider,\n )\n return scalars_plugin.ScalarsPlugin(ctx)\n\n def load_server(self, run_names):\n plugin = self.load_plugin(run_names)\n wsgi_app = application.TensorBoardWSGI([plugin])\n server = werkzeug_test.Client(wsgi_app, wrappers.BaseResponse)\n return server\n\n def generate_run(self, logdir, run_name):\n subdir = os.path.join(logdir, run_name)\n with test_util.FileWriterCache.get(subdir) as writer:\n for step in xrange(self._STEPS):\n data = [1 + step, 2 + step, 3 + step]\n if run_name == self._RUN_WITH_LEGACY_SCALARS:\n summ = tf.compat.v1.summary.scalar(\n self._LEGACY_SCALAR_TAG,\n tf.reduce_mean(data),\n ).numpy()\n elif run_name == self._RUN_WITH_SCALARS:\n summ = summary.op(\n self._SCALAR_TAG,\n tf.reduce_sum(data),\n display_name=self._DISPLAY_NAME,\n description=self._DESCRIPTION,\n ).numpy()\n elif run_name == self._RUN_WITH_SCALARS_2:\n summ = summary.op(\n self._SCALAR_TAG,\n 2 * tf.reduce_sum(data),\n display_name=self._DISPLAY_NAME,\n description=self._DESCRIPTION,\n ).numpy()\n elif run_name == self._RUN_WITH_SCALARS_3:\n summ = summary.op(\n self._SCALAR_TAG,\n 3 * tf.reduce_sum(data),\n display_name=self._DISPLAY_NAME,\n description=self._DESCRIPTION,\n ).numpy()\n elif run_name == self._RUN_WITH_HISTOGRAM:\n summ = tf.compat.v1.summary.histogram(\n self._HISTOGRAM_TAG, data\n ).numpy()\n else:\n assert False, \"Invalid run name: %r\" % run_name\n writer.add_summary(summ, global_step=step)\n\n def test_index(self):\n server = self.load_server(\n [\n self._RUN_WITH_LEGACY_SCALARS,\n self._RUN_WITH_SCALARS,\n self._RUN_WITH_HISTOGRAM,\n ]\n )\n response = server.get(\"/data/plugin/scalars/tags\")\n self.assertEqual(200, response.status_code)\n self.assertEqual(\"application/json\", response.headers[\"Content-Type\"])\n self.assertEqual(\n {\n self._RUN_WITH_LEGACY_SCALARS: {\n self._LEGACY_SCALAR_TAG: {\n \"displayName\": self._LEGACY_SCALAR_TAG,\n \"description\": \"\",\n },\n },\n self._RUN_WITH_SCALARS: {\n \"%s/scalar_summary\"\n % self._SCALAR_TAG: {\n \"displayName\": self._DISPLAY_NAME,\n \"description\": self._HTML_DESCRIPTION,\n },\n },\n # _RUN_WITH_HISTOGRAM omitted: No scalar data.\n },\n json.loads(response.get_data()),\n )\n\n def test_scalars_with_legacy_scalars(self):\n server = self.load_server([self._RUN_WITH_LEGACY_SCALARS])\n response = server.get(\n \"/data/plugin/scalars/scalars\",\n query_string={\n \"run\": self._RUN_WITH_LEGACY_SCALARS,\n \"tag\": self._LEGACY_SCALAR_TAG,\n },\n )\n self.assertEqual(200, response.status_code)\n self.assertEqual(\"application/json\", response.headers[\"Content-Type\"])\n self.assertEqual(self._STEPS, len(json.loads(response.get_data())))\n\n def test_scalars_with_scalars(self):\n server = self.load_server([self._RUN_WITH_SCALARS])\n response = server.get(\n \"/data/plugin/scalars/scalars\",\n query_string={\n \"run\": self._RUN_WITH_SCALARS,\n \"tag\": \"%s/scalar_summary\" % self._SCALAR_TAG,\n },\n )\n self.assertEqual(200, response.status_code)\n self.assertEqual(\"application/json\", response.headers[\"Content-Type\"])\n self.assertEqual(self._STEPS, len(json.loads(response.get_data())))\n\n def test_scalars_with_scalars_unspecified_run(self):\n server = self.load_server([self._RUN_WITH_SCALARS])\n response = server.get(\n \"/data/plugin/scalars/scalars\",\n query_string={\"run\": None, \"tag\": \"foo_tag\"},\n )\n self.assertEqual(400, response.status_code)\n\n def test_scalars_with_scalars_unspecified_tag(self):\n server = self.load_server([self._RUN_WITH_SCALARS])\n response = server.get(\n \"/data/plugin/scalars/scalars\",\n query_string={\"run\": \"foo_run\", \"tag\": None},\n )\n self.assertEqual(400, response.status_code)\n\n def test_scalars_with_histogram(self):\n server = self.load_server([self._RUN_WITH_HISTOGRAM])\n response = server.get(\n \"/data/plugin/scalars/scalars\",\n query_string={\n \"run\": self._RUN_WITH_HISTOGRAM,\n \"tag\": \"%s/scalar_summary\" % self._HISTOGRAM_TAG,\n },\n )\n self.assertEqual(404, response.status_code)\n\n def test_scalars_multirun(self):\n server = self.load_server(\n [\n self._RUN_WITH_SCALARS,\n self._RUN_WITH_SCALARS_2,\n self._RUN_WITH_SCALARS_3,\n ]\n )\n response = server.post(\n \"/data/plugin/scalars/scalars_multirun\",\n data={\n \"tag\": \"%s/scalar_summary\" % self._SCALAR_TAG,\n \"runs\": [\n self._RUN_WITH_SCALARS,\n # skip _RUN_WITH_SCALARS_2\n self._RUN_WITH_SCALARS_3,\n self._RUN_WITH_HISTOGRAM, # no data for this tag; okay\n \"nonexistent_run\", # no data at all; okay\n ],\n },\n )\n self.assertEqual(200, response.status_code)\n self.assertEqual(\"application/json\", response.headers[\"Content-Type\"])\n data = json.loads(response.get_data())\n self.assertCountEqual(\n [self._RUN_WITH_SCALARS, self._RUN_WITH_SCALARS_3], data\n )\n self.assertLen(data[self._RUN_WITH_SCALARS], self._STEPS)\n self.assertLen(data[self._RUN_WITH_SCALARS_3], self._STEPS)\n self.assertNotEqual(\n data[self._RUN_WITH_SCALARS][0][2],\n data[self._RUN_WITH_SCALARS_3][0][2],\n )\n\n def test_scalars_multirun_single_run(self):\n # Checks for any problems with singleton arrays.\n server = self.load_server(\n [\n self._RUN_WITH_SCALARS,\n self._RUN_WITH_SCALARS_2,\n self._RUN_WITH_SCALARS_3,\n ]\n )\n response = server.post(\n \"/data/plugin/scalars/scalars_multirun\",\n data={\n \"tag\": \"%s/scalar_summary\" % self._SCALAR_TAG,\n \"runs\": [self._RUN_WITH_SCALARS],\n },\n )\n self.assertEqual(200, response.status_code)\n self.assertEqual(\"application/json\", response.headers[\"Content-Type\"])\n data = json.loads(response.get_data())\n self.assertCountEqual([self._RUN_WITH_SCALARS], data)\n self.assertLen(data[self._RUN_WITH_SCALARS], self._STEPS)\n\n def test_scalars_multirun_no_runs(self):\n server = self.load_server([self._RUN_WITH_SCALARS])\n response = server.post(\n \"/data/plugin/scalars/scalars_multirun\",\n data={\"tag\": \"%s/scalar_summary\" % self._SCALAR_TAG},\n )\n self.assertEqual(200, response.status_code)\n self.assertEqual(\"application/json\", response.headers[\"Content-Type\"])\n data = json.loads(response.get_data())\n self.assertEqual({}, data)\n\n def test_scalars_multirun_no_tag(self):\n server = self.load_server([self._RUN_WITH_SCALARS])\n response = server.post(\n \"/data/plugin/scalars/scalars_multirun\",\n data={\"runs\": [self._RUN_WITH_SCALARS, self._RUN_WITH_SCALARS_2]},\n )\n self.assertEqual(400, response.status_code)\n self.assertIn(\n \"tag must be specified\", response.get_data().decode(\"utf-8\")\n )\n\n def test_scalars_multirun_two_tags(self):\n server = self.load_server([self._RUN_WITH_SCALARS])\n response = server.post(\n \"/data/plugin/scalars/scalars_multirun\",\n data={\n \"tag\": [\"accuracy\", \"loss\"],\n \"runs\": [self._RUN_WITH_SCALARS, self._RUN_WITH_SCALARS_2],\n },\n )\n self.assertEqual(400, response.status_code)\n self.assertIn(\"exactly once\", response.get_data().decode(\"utf-8\"))\n\n def test_scalars_multirun_bad_method(self):\n server = self.load_server([self._RUN_WITH_SCALARS])\n response = server.get(\n \"/data/plugin/scalars/scalars_multirun\",\n query_string={\n \"tag\": \"%s/scalar_summary\" % self._SCALAR_TAG,\n \"runs\": [\n self._RUN_WITH_SCALARS,\n self._RUN_WITH_SCALARS_3,\n ],\n },\n )\n self.assertEqual(405, response.status_code)\n self.assertEqual(response.headers[\"Allow\"], \"POST\")\n\n def test_active_with_legacy_scalars(self):\n plugin = self.load_plugin([self._RUN_WITH_LEGACY_SCALARS])\n self.assertFalse(plugin.is_active())\n\n def test_active_with_scalars(self):\n plugin = self.load_plugin([self._RUN_WITH_SCALARS])\n self.assertFalse(plugin.is_active())\n\n def test_active_with_histogram(self):\n plugin = self.load_plugin([self._RUN_WITH_HISTOGRAM])\n self.assertFalse(plugin.is_active())\n\n def test_active_with_all(self):\n plugin = self.load_plugin(\n [\n self._RUN_WITH_LEGACY_SCALARS,\n self._RUN_WITH_SCALARS,\n self._RUN_WITH_HISTOGRAM,\n ]\n )\n self.assertFalse(plugin.is_active())\n\n def test_download_url_json(self):\n plugin = self.load_plugin([self._RUN_WITH_SCALARS])\n wsgi_app = application.TensorBoardWSGI([plugin])\n server = werkzeug_test.Client(wsgi_app, wrappers.BaseResponse)\n response = server.get(\n \"/data/plugin/scalars/scalars?run=%s&tag=%s\"\n % (\n self._RUN_WITH_SCALARS,\n \"%s/scalar_summary\" % self._SCALAR_TAG,\n )\n )\n self.assertEqual(200, response.status_code)\n self.assertEqual(\"application/json\", response.headers[\"Content-Type\"])\n payload = json.loads(response.get_data())\n self.assertEqual(len(payload), self._STEPS)\n\n def test_download_url_csv(self):\n plugin = self.load_plugin([self._RUN_WITH_SCALARS])\n wsgi_app = application.TensorBoardWSGI([plugin])\n server = werkzeug_test.Client(wsgi_app, wrappers.BaseResponse)\n response = server.get(\n \"/data/plugin/scalars/scalars?run=%s&tag=%s&format=csv\"\n % (\n self._RUN_WITH_SCALARS,\n \"%s/scalar_summary\" % self._SCALAR_TAG,\n )\n )\n self.assertEqual(200, response.status_code)\n self.assertEqual(\n \"text/csv; charset=utf-8\", response.headers[\"Content-Type\"]\n )\n payload = response.get_data()\n s = StringIO(payload.decode(\"utf-8\"))\n reader = csv.reader(s)\n self.assertEqual([\"Wall time\", \"Step\", \"Value\"], next(reader))\n self.assertEqual(len(list(reader)), self._STEPS)\n\n\nif __name__ == \"__main__\":\n tf.test.main()\n"
] | [
[
"tensorflow.reduce_mean",
"tensorflow.reduce_sum",
"tensorflow.compat.v1.enable_eager_execution",
"tensorflow.test.main",
"tensorflow.compat.v1.summary.histogram"
]
] |
JaeZheng/unet | [
"f0fac997a1ee7ce962e14d51f97f704229fc1a75"
] | [
"main.py"
] | [
"from model import *\nfrom data import *\nimport os\nfrom keras.models import load_model\nimport tensorflow as tf\nimport keras.backend.tensorflow_backend as KTF\nfrom data import meanIOU\n\n# 指定显卡\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\n# 自适应分配显存\nconfig = tf.ConfigProto()\nconfig.gpu_options.allow_growth=True\nsession = tf.Session(config=config)\nKTF.set_session(session)\n\ndata_gen_args = dict(rotation_range=0.2,\n width_shift_range=0.05,\n height_shift_range=0.05,\n shear_range=0.05,\n zoom_range=0.05,\n horizontal_flip=True,\n fill_mode='nearest')\n# data_gen_args = dict()\nmyGene = trainGenerator(1,'data/thyroid/train','image','label',data_gen_args,save_to_dir=None,target_size=(400,496))\n# myGene = my_train_data_loader(16,50,'data/thyroid/train','image','label',target_size=(128,128))\n\nmodel = unet(input_size=(128,128,1))\n\nif os.path.exists(\"unet_thyroid.hdf5.txt\"):\n os.remove(\"unet_thyroid.hdf5.txt\")\nwith open(\"unet_thyroid.hdf5.txt\",'w') as fh:\n model.summary(positions=[.3, .55, .67, 1.], print_fn=lambda x: fh.write(x + '\\n'))\n\nmodel_checkpoint = ModelCheckpoint('unet_thyroid.hdf5', monitor='loss',verbose=1, save_best_only=True)\nmodel.fit_generator(myGene,steps_per_epoch=500,epochs=50,callbacks=[model_checkpoint])\n\n# model = load_model('unet_thyroid.hdf5', custom_objects={'meanIOU':meanIOU})\n# testGene = testGenerator(\"data/thyroid/test\", num_image=59,target_size=(400,496))\n# results = model.predict_generator(testGene,59,verbose=1)\n# saveResult(\"data/thyroid/test\",results)\n\ntestGene = my_test_data_loader(59, \"data/thyroid/test\")\ncnt = 0\nfor img in testGene:\n result = predict_single_image(model, img, target_size=(128,128))\n saveSingleResult(\"data/thyroid/test\", result, cnt)\n cnt += 1\n\nimport test"
] | [
[
"tensorflow.ConfigProto",
"tensorflow.Session"
]
] |
feklee/tensorflow | [
"8e073e237ed258dac220d3cc1a177a08e43f2c0d"
] | [
"tensorflow/python/ops/array_ops.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 this file live in python/kernel_tests/array_ops_test.py\n\"\"\"Support for manipulating tensors.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numbers\nimport numpy as np\n\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.framework import common_shapes\nfrom tensorflow.python.framework import composite_tensor\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import sparse_tensor\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.framework import tensor_util\n# 'Constant' gets imported in the module 'array_ops'.\nfrom tensorflow.python.framework.constant_op import constant\nfrom tensorflow.python.ops import gen_array_ops\nfrom tensorflow.python.ops import gen_math_ops\n# go/tf-wildcard-import\n# pylint: disable=wildcard-import\nfrom tensorflow.python.ops.gen_array_ops import *\nfrom tensorflow.python.ops.gen_array_ops import reverse_v2 as reverse # pylint: disable=unused-import\nfrom tensorflow.python.types import core\nfrom tensorflow.python.util import deprecation\nfrom tensorflow.python.util import dispatch\nfrom tensorflow.python.util import nest\nfrom tensorflow.python.util import tf_decorator\nfrom tensorflow.python.util.tf_export import tf_export\n# pylint: enable=wildcard-import\n\n# Used for slicing to specify a new 1 size dimension\nnewaxis = None\ntf_export(\"newaxis\").export_constant(__name__, \"newaxis\")\n\n# We override the 'slice' for the \"slice\" op, so we keep Python's\n# existing 'slice' for later use in this module.\n_BaseSlice = slice\n\n\n@tf_export(\"reshape\", v1=[\"reshape\", \"manip.reshape\"])\ndef reshape(tensor, shape, name=None): # pylint: disable=redefined-outer-name\n r\"\"\"Reshapes a tensor.\n\n Given `tensor`, this operation returns a new `tf.Tensor` that has the same\n values as `tensor` in the same order, except with a new shape given by\n `shape`.\n\n >>> t1 = [[1, 2, 3],\n ... [4, 5, 6]]\n >>> print(tf.shape(t1).numpy())\n [2 3]\n >>> t2 = tf.reshape(t1, [6])\n >>> t2\n <tf.Tensor: shape=(6,), dtype=int32,\n numpy=array([1, 2, 3, 4, 5, 6], dtype=int32)>\n >>> tf.reshape(t2, [3, 2])\n <tf.Tensor: shape=(3, 2), dtype=int32, numpy=\n array([[1, 2],\n [3, 4],\n [5, 6]], dtype=int32)>\n\n The `tf.reshape` does not change the order of or the total number of elements\n in the tensor, and so it can reuse the underlying data buffer. This makes it\n a fast operation independent of how big of a tensor it is operating on.\n\n >>> tf.reshape([1, 2, 3], [2, 2])\n Traceback (most recent call last):\n ...\n InvalidArgumentError: Input to reshape is a tensor with 3 values, but the\n requested shape has 4\n\n To instead reorder the data to rearrange the dimensions of a tensor, see\n `tf.transpose`.\n\n >>> t = [[1, 2, 3],\n ... [4, 5, 6]]\n >>> tf.reshape(t, [3, 2]).numpy()\n array([[1, 2],\n [3, 4],\n [5, 6]], dtype=int32)\n >>> tf.transpose(t, perm=[1, 0]).numpy()\n array([[1, 4],\n [2, 5],\n [3, 6]], dtype=int32)\n\n If one component of `shape` is the special value -1, the size of that\n dimension is computed so that the total size remains constant. In particular,\n a `shape` of `[-1]` flattens into 1-D. At most one component of `shape` can\n be -1.\n\n >>> t = [[1, 2, 3],\n ... [4, 5, 6]]\n >>> tf.reshape(t, [-1])\n <tf.Tensor: shape=(6,), dtype=int32,\n numpy=array([1, 2, 3, 4, 5, 6], dtype=int32)>\n >>> tf.reshape(t, [3, -1])\n <tf.Tensor: shape=(3, 2), dtype=int32, numpy=\n array([[1, 2],\n [3, 4],\n [5, 6]], dtype=int32)>\n >>> tf.reshape(t, [-1, 2])\n <tf.Tensor: shape=(3, 2), dtype=int32, numpy=\n array([[1, 2],\n [3, 4],\n [5, 6]], dtype=int32)>\n\n `tf.reshape(t, [])` reshapes a tensor `t` with one element to a scalar.\n\n >>> tf.reshape([7], []).numpy()\n 7\n\n More examples:\n\n >>> t = [1, 2, 3, 4, 5, 6, 7, 8, 9]\n >>> print(tf.shape(t).numpy())\n [9]\n >>> tf.reshape(t, [3, 3])\n <tf.Tensor: shape=(3, 3), dtype=int32, numpy=\n array([[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]], dtype=int32)>\n\n >>> t = [[[1, 1], [2, 2]],\n ... [[3, 3], [4, 4]]]\n >>> print(tf.shape(t).numpy())\n [2 2 2]\n >>> tf.reshape(t, [2, 4])\n <tf.Tensor: shape=(2, 4), dtype=int32, numpy=\n array([[1, 1, 2, 2],\n [3, 3, 4, 4]], dtype=int32)>\n\n >>> t = [[[1, 1, 1],\n ... [2, 2, 2]],\n ... [[3, 3, 3],\n ... [4, 4, 4]],\n ... [[5, 5, 5],\n ... [6, 6, 6]]]\n >>> print(tf.shape(t).numpy())\n [3 2 3]\n >>> # Pass '[-1]' to flatten 't'.\n >>> tf.reshape(t, [-1])\n <tf.Tensor: shape=(18,), dtype=int32,\n numpy=array([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6],\n dtype=int32)>\n >>> # -- Using -1 to infer the shape --\n >>> # Here -1 is inferred to be 9:\n >>> tf.reshape(t, [2, -1])\n <tf.Tensor: shape=(2, 9), dtype=int32, numpy=\n array([[1, 1, 1, 2, 2, 2, 3, 3, 3],\n [4, 4, 4, 5, 5, 5, 6, 6, 6]], dtype=int32)>\n >>> # -1 is inferred to be 2:\n >>> tf.reshape(t, [-1, 9])\n <tf.Tensor: shape=(2, 9), dtype=int32, numpy=\n array([[1, 1, 1, 2, 2, 2, 3, 3, 3],\n [4, 4, 4, 5, 5, 5, 6, 6, 6]], dtype=int32)>\n >>> # -1 is inferred to be 3:\n >>> tf.reshape(t, [ 2, -1, 3])\n <tf.Tensor: shape=(2, 3, 3), dtype=int32, numpy=\n array([[[1, 1, 1],\n [2, 2, 2],\n [3, 3, 3]],\n [[4, 4, 4],\n [5, 5, 5],\n [6, 6, 6]]], dtype=int32)>\n\n Args:\n tensor: A `Tensor`.\n shape: A `Tensor`. Must be one of the following types: `int32`, `int64`.\n Defines the shape of the output tensor.\n name: Optional string. A name for the operation.\n\n Returns:\n A `Tensor`. Has the same type as `tensor`.\n \"\"\"\n result = gen_array_ops.reshape(tensor, shape, name)\n tensor_util.maybe_set_static_shape(result, shape)\n return result\n\n\n@tf_export(\"fill\")\ndef fill(dims, value, name=None):\n r\"\"\"Creates a tensor filled with a scalar value.\n\n See also `tf.ones`, `tf.zeros`, `tf.one_hot`, `tf.eye`.\n\n This operation creates a tensor of shape `dims` and fills it with `value`.\n\n For example:\n\n >>> tf.fill([2, 3], 9)\n <tf.Tensor: shape=(2, 3), dtype=int32, numpy=\n array([[9, 9, 9],\n [9, 9, 9]], dtype=int32)>\n\n `tf.fill` evaluates at graph runtime and supports dynamic shapes based on\n other runtime `tf.Tensors`, unlike `tf.constant(value, shape=dims)`, which\n embeds the value as a `Const` node.\n\n Args:\n dims: A 1-D sequence of non-negative numbers. Represents the shape of the\n output `tf.Tensor`. Entries should be of type: `int32`, `int64`.\n value: A value to fill the returned `tf.Tensor`.\n name: Optional string. The name of the output `tf.Tensor`.\n\n Returns:\n A `tf.Tensor` with shape `dims` and the same dtype as `value`.\n\n Raises:\n InvalidArgumentError: `dims` contains negative entries.\n NotFoundError: `dims` contains non-integer entries.\n\n @compatibility(numpy)\n Similar to `np.full`. In `numpy`, more parameters are supported. Passing a\n number argument as the shape (`np.full(5, value)`) is valid in `numpy` for\n specifying a 1-D shaped result, while TensorFlow does not support this syntax.\n @end_compatibility\n \"\"\"\n result = gen_array_ops.fill(dims, value, name=name)\n tensor_util.maybe_set_static_shape(result, dims)\n return result\n\n\n@tf_export(\"identity\")\[email protected]_dispatch_support\ndef identity(input, name=None): # pylint: disable=redefined-builtin\n r\"\"\"Return a Tensor with the same shape and contents as input.\n\n The return value is not the same Tensor as the original, but contains the same\n values. This operation is fast when used on the same device.\n\n For example:\n\n >>> a = tf.constant([0.78])\n >>> a_identity = tf.identity(a)\n >>> a.numpy()\n array([0.78], dtype=float32)\n >>> a_identity.numpy()\n array([0.78], dtype=float32)\n\n Calling `tf.identity` on a variable will make a Tensor that represents the\n value of that variable at the time it is called. This is equivalent to calling\n `<variable>.read_value()`.\n\n >>> a = tf.Variable(5)\n >>> a_identity = tf.identity(a)\n >>> a.assign_add(1)\n <tf.Variable ... shape=() dtype=int32, numpy=6>\n >>> a.numpy()\n 6\n >>> a_identity.numpy()\n 5\n\n Args:\n input: A `Tensor`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor`. Has the same type as `input`.\n \"\"\"\n if isinstance(input, composite_tensor.CompositeTensor):\n return nest.map_structure(identity, input, expand_composites=True)\n if context.executing_eagerly() and not hasattr(input, \"graph\"):\n # Make sure we get an input with handle data attached from resource\n # variables. Variables have correct handle data when graph building.\n input = ops.convert_to_tensor(input)\n ret = gen_array_ops.identity(input, name=name)\n # Propagate handle data for happier shape inference for resource variables.\n if hasattr(input, \"_handle_data\"):\n ret._handle_data = input._handle_data # pylint: disable=protected-access\n return ret\n\n\n# pylint: disable=redefined-builtin,protected-access\n@tf_export(v1=[\"expand_dims\"])\[email protected]_dispatch_support\[email protected]_args(None, \"Use the `axis` argument instead\", \"dim\")\ndef expand_dims(input, axis=None, name=None, dim=None):\n \"\"\"Returns a tensor with a length 1 axis inserted at index `axis`.\n\n Given a tensor `input`, this operation inserts a dimension of length 1 at the\n dimension index `axis` of `input`'s shape. The dimension index follows Python\n indexing rules: It's zero-based, a negative index it is counted backward\n from the end.\n\n This operation is useful to:\n\n * Add an outer \"batch\" dimension to a single element.\n * Align axes for broadcasting.\n * To add an inner vector length axis to a tensor of scalars.\n\n For example:\n\n If you have a single image of shape `[height, width, channels]`:\n\n >>> image = tf.zeros([10,10,3])\n\n You can add an outer `batch` axis by passing `axis=0`:\n\n >>> tf.expand_dims(image, axis=0).shape.as_list()\n [1, 10, 10, 3]\n\n The new axis location matches Python `list.insert(axis, 1)`:\n\n >>> tf.expand_dims(image, axis=1).shape.as_list()\n [10, 1, 10, 3]\n\n Following standard Python indexing rules, a negative `axis` counts from the\n end so `axis=-1` adds an inner most dimension:\n\n >>> tf.expand_dims(image, -1).shape.as_list()\n [10, 10, 3, 1]\n\n This operation requires that `axis` is a valid index for `input.shape`,\n following Python indexing rules:\n\n ```\n -1-tf.rank(input) <= axis <= tf.rank(input)\n ```\n\n This operation is related to:\n\n * `tf.squeeze`, which removes dimensions of size 1.\n * `tf.reshape`, which provides more flexible reshaping capability.\n * `tf.sparse.expand_dims`, which provides this functionality for\n `tf.SparseTensor`\n\n Args:\n input: A `Tensor`.\n axis: 0-D (scalar). Specifies the dimension index at which to expand the\n shape of `input`. Must be in the range `[-rank(input) - 1, rank(input)]`.\n name: The name of the output `Tensor` (optional).\n dim: 0-D (scalar). Equivalent to `axis`, to be deprecated.\n\n Returns:\n A `Tensor` with the same data as `input`, but its shape has an additional\n dimension of size 1 added.\n\n Raises:\n ValueError: if either both or neither of `dim` and `axis` are specified.\n \"\"\"\n axis = deprecation.deprecated_argument_lookup(\"axis\", axis, \"dim\", dim)\n if axis is None:\n raise ValueError(\"Must specify an axis argument to tf.expand_dims()\")\n return expand_dims_v2(input, axis, name)\n\n\n@tf_export(\"expand_dims\", v1=[])\[email protected]_dispatch_support\ndef expand_dims_v2(input, axis, name=None):\n \"\"\"Returns a tensor with a length 1 axis inserted at index `axis`.\n\n Given a tensor `input`, this operation inserts a dimension of length 1 at the\n dimension index `axis` of `input`'s shape. The dimension index follows Python\n indexing rules: It's zero-based, a negative index it is counted backward\n from the end.\n\n This operation is useful to:\n\n * Add an outer \"batch\" dimension to a single element.\n * Align axes for broadcasting.\n * To add an inner vector length axis to a tensor of scalars.\n\n For example:\n\n If you have a single image of shape `[height, width, channels]`:\n\n >>> image = tf.zeros([10,10,3])\n\n You can add an outer `batch` axis by passing `axis=0`:\n\n >>> tf.expand_dims(image, axis=0).shape.as_list()\n [1, 10, 10, 3]\n\n The new axis location matches Python `list.insert(axis, 1)`:\n\n >>> tf.expand_dims(image, axis=1).shape.as_list()\n [10, 1, 10, 3]\n\n Following standard Python indexing rules, a negative `axis` counts from the\n end so `axis=-1` adds an inner most dimension:\n\n >>> tf.expand_dims(image, -1).shape.as_list()\n [10, 10, 3, 1]\n\n This operation requires that `axis` is a valid index for `input.shape`,\n following Python indexing rules:\n\n ```\n -1-tf.rank(input) <= axis <= tf.rank(input)\n ```\n\n This operation is related to:\n\n * `tf.squeeze`, which removes dimensions of size 1.\n * `tf.reshape`, which provides more flexible reshaping capability.\n * `tf.sparse.expand_dims`, which provides this functionality for\n `tf.SparseTensor`\n\n Args:\n input: A `Tensor`.\n axis: Integer specifying the dimension index at which to expand the\n shape of `input`. Given an input of D dimensions, `axis` must be in range\n `[-(D+1), D]` (inclusive).\n name: Optional string. The name of the output `Tensor`.\n\n Returns:\n A tensor with the same data as `input`, with an additional dimension\n inserted at the index specified by `axis`.\n\n Raises:\n ValueError: If `axis` is not specified.\n InvalidArgumentError: If `axis` is out of range `[-(D+1), D]`.\n \"\"\"\n return gen_array_ops.expand_dims(input, axis, name)\n\n\n# pylint: enable=redefined-builtin,protected-access\n\n\n# Aliases for some automatically-generated names.\n# pylint: disable=protected-access\[email protected](\"2016-11-30\",\n \"This op will be removed after the deprecation date. \"\n \"Please switch to tf.setdiff1d().\")\ndef listdiff(x, y, out_idx=None, name=None):\n return gen_array_ops.list_diff(x, y, out_idx, name)\n\n\nlistdiff.__doc__ = gen_array_ops.list_diff.__doc__ + \"\\n\" + listdiff.__doc__\n\n# pylint: enable=protected-access\n\n\n# pylint: disable=undefined-variable\[email protected](\"2018-11-30\",\n \"This op will be removed after the deprecation date. \"\n \"Please switch to tf.sets.difference().\")\n@tf_export(v1=[\"setdiff1d\"])\ndef setdiff1d(x, y, index_dtype=dtypes.int32, name=None):\n \"\"\"Computes the difference between two lists of numbers or strings.\n\n Given a list x and a list y, this operation returns a list out that\n represents all values that are in x but not in y. The returned list\n out is sorted in the same order that the numbers appear in x\n (duplicates are preserved). This operation also returns a list idx\n that represents the position of each out element in x.\n\n In other words:\n\n ```python\n out[i] = x[idx[i]] for i in [0, 1, ..., len(out) - 1]\n ```\n\n Example usage:\n\n >>> x = [1, 2, 3, 4, 5, 6]\n >>> y = [1, 3, 5]\n >>> setdiff1d(x,y)\n ListDiff(out=<tf.Tensor: id=2, shape=(3,), dtype=int32,\n numpy=array([2, 4, 6], dtype=int32)>, idx=<tf.Tensor: id=3,\n shape=(3,), dtype=int32, numpy=array([1, 3, 5], dtype=int32)>)\n\n Args:\n x: A Tensor. 1-D. Values to keep.\n y: A Tensor. Must have the same type as x. 1-D. Values to remove.\n out_idx: An optional tf.DType from: tf.int32, tf.int64. Defaults to\n tf.int32.\n name: A name for the operation (optional).\n\n Returns:\n A tuple of Tensor objects (out, idx).\n out: A Tensor. Has the same type as x.\n idx: A Tensor of type out_idx.\n \"\"\"\n return gen_array_ops.list_diff(x, y, index_dtype, name)\n\n\nsetdiff1d.__doc__ = gen_array_ops.list_diff.__doc__\n\n\n@tf_export(\"broadcast_dynamic_shape\")\ndef broadcast_dynamic_shape(shape_x, shape_y):\n \"\"\"Computes the shape of a broadcast given symbolic shapes.\n\n When shape_x and shape_y are Tensors representing shapes (i.e. the result of\n calling tf.shape on another Tensor) this computes a Tensor which is the shape\n of the result of a broadcasting op applied in tensors of shapes shape_x and\n shape_y.\n\n For example, if shape_x is [1, 2, 3] and shape_y is [5, 1, 3], the result is a\n Tensor whose value is [5, 2, 3].\n\n This is useful when validating the result of a broadcasting operation when the\n tensors do not have statically known shapes.\n\n Args:\n shape_x: A rank 1 integer `Tensor`, representing the shape of x.\n shape_y: A rank 1 integer `Tensor`, representing the shape of y.\n\n Returns:\n A rank 1 integer `Tensor` representing the broadcasted shape.\n \"\"\"\n return gen_array_ops.broadcast_args(shape_x, shape_y)\n\n\n@tf_export(\"broadcast_static_shape\")\ndef broadcast_static_shape(shape_x, shape_y):\n \"\"\"Computes the shape of a broadcast given known shapes.\n\n When shape_x and shape_y are fully known TensorShapes this computes a\n TensorShape which is the shape of the result of a broadcasting op applied in\n tensors of shapes shape_x and shape_y.\n\n For example, if shape_x is [1, 2, 3] and shape_y is [5, 1, 3], the result is a\n TensorShape whose value is [5, 2, 3].\n\n This is useful when validating the result of a broadcasting operation when the\n tensors have statically known shapes.\n\n Args:\n shape_x: A `TensorShape`\n shape_y: A `TensorShape`\n\n Returns:\n A `TensorShape` representing the broadcasted shape.\n\n Raises:\n ValueError: If the two shapes can not be broadcasted.\n \"\"\"\n return common_shapes.broadcast_shape(shape_x, shape_y)\n\n\n@tf_export(\"shape\", v1=[])\ndef shape_v2(input, out_type=dtypes.int32, name=None):\n # pylint: disable=redefined-builtin\n \"\"\"Returns the shape of a tensor.\n \n See also `tf.size`, `tf.rank`.\n\n This operation returns a 1-D integer tensor representing the shape of `input`.\n This represents the minimal set of known information at definition time.\n\n For example:\n\n >>> t = tf.constant([[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]])\n >>> tf.shape(t)\n <tf.Tensor: shape=(3,), dtype=int32, numpy=array([2, 2, 3], dtype=int32)>\n >>> tf.shape(t).numpy()\n array([2, 2, 3], dtype=int32)\n\n Note: When using symbolic tensors, such as when using the Keras functional\n API, tf.shape() will return the shape of the symbolic tensor.\n\n >>> a = tf.keras.layers.Input((None, 10))\n >>> tf.shape(a)\n <tf.Tensor ... shape=(3,) dtype=int32>\n\n In these cases, using `tf.Tensor.shape` will return more informative results.\n\n >>> a.shape\n TensorShape([None, None, 10])\n\n `tf.shape` and `Tensor.shape` should be identical in eager mode. Within\n `tf.function` or within a `compat.v1` context, not all dimensions may be\n known until execution time.\n\n Args:\n input: A `Tensor` or `SparseTensor`.\n out_type: (Optional) The specified output type of the operation (`int32` or\n `int64`). Defaults to `tf.int32`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of type `out_type`.\n \"\"\"\n return shape(input, name, out_type)\n\n\n@tf_export(v1=[\"shape\"])\ndef shape(input, name=None, out_type=dtypes.int32):\n # pylint: disable=redefined-builtin\n \"\"\"Returns the shape of a tensor.\n\n This operation returns a 1-D integer tensor representing the shape of `input`.\n\n For example:\n\n ```python\n t = tf.constant([[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]])\n tf.shape(t) # [2, 2, 3]\n ```\n\n Args:\n input: A `Tensor` or `SparseTensor`.\n name: A name for the operation (optional).\n out_type: (Optional) The specified output type of the operation (`int32`\n or `int64`). Defaults to `tf.int32`.\n\n Returns:\n A `Tensor` of type `out_type`.\n \"\"\"\n return shape_internal(input, name, optimize=True, out_type=out_type)\n\n\ndef shape_internal(input, name=None, optimize=True, out_type=dtypes.int32):\n # pylint: disable=redefined-builtin\n \"\"\"Returns the shape of a tensor.\n\n Args:\n input: A `Tensor` or `SparseTensor`.\n name: A name for the operation (optional).\n optimize: if true, encode the shape as a constant when possible.\n out_type: (Optional) The specified output type of the operation (`int32` or\n `int64`). Defaults to tf.int32.\n\n Returns:\n A `Tensor` of type `out_type`.\n\n \"\"\"\n with ops.name_scope(name, \"Shape\", [input]) as name:\n if isinstance(\n input, (sparse_tensor.SparseTensor, sparse_tensor.SparseTensorValue)):\n return gen_math_ops.cast(input.dense_shape, out_type)\n else:\n if not context.executing_eagerly():\n input = ops.convert_to_tensor(input)\n input_shape = input.get_shape()\n if optimize and input_shape.is_fully_defined():\n return constant(input_shape.as_list(), out_type, name=name)\n return gen_array_ops.shape(input, name=name, out_type=out_type)\n\n\n@tf_export(\"shape_n\")\ndef shape_n(input, out_type=dtypes.int32, name=None):\n # pylint: disable=redefined-builtin\n \"\"\"Returns shape of tensors.\n\n Args:\n input: A list of at least 1 `Tensor` object with the same type.\n out_type: The specified output type of the operation (`int32` or `int64`).\n Defaults to `tf.int32`(optional).\n name: A name for the operation (optional).\n\n Returns:\n A list with the same length as `input` of `Tensor` objects with\n type `out_type`.\n \"\"\"\n\n return gen_array_ops.shape_n(input, out_type=out_type, name=name)\n\n\n@tf_export(\"size\", v1=[])\[email protected]_dispatch_support\ndef size_v2(input, out_type=dtypes.int32, name=None):\n # pylint: disable=redefined-builtin\n \"\"\"Returns the size of a tensor.\n \n See also `tf.shape`.\n\n Returns a 0-D `Tensor` representing the number of elements in `input`\n of type `out_type`. Defaults to tf.int32.\n\n For example:\n\n >>> t = tf.constant([[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]])\n >>> tf.size(t)\n <tf.Tensor: shape=(), dtype=int32, numpy=12>\n\n Args:\n input: A `Tensor` or `SparseTensor`.\n name: A name for the operation (optional).\n out_type: (Optional) The specified non-quantized numeric output type of the\n operation. Defaults to `tf.int32`.\n\n Returns:\n A `Tensor` of type `out_type`. Defaults to `tf.int32`.\n\n @compatibility(numpy)\n Equivalent to np.size()\n @end_compatibility\n \"\"\"\n\n return size(input, name, out_type)\n\n\n@tf_export(v1=[\"size\"])\[email protected]_dispatch_support\ndef size(input, name=None, out_type=dtypes.int32):\n # pylint: disable=redefined-builtin\n \"\"\"Returns the size of a tensor.\n\n Returns a 0-D `Tensor` representing the number of elements in `input`\n of type `out_type`. Defaults to tf.int32.\n\n For example:\n\n ```python\n t = tf.constant([[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]])\n tf.size(t) # 12\n ```\n\n Args:\n input: A `Tensor` or `SparseTensor`.\n name: A name for the operation (optional).\n out_type: (Optional) The specified non-quantized numeric output type of the\n operation. Defaults to `tf.int32`.\n\n Returns:\n A `Tensor` of type `out_type`. Defaults to `tf.int32`.\n\n @compatibility(numpy)\n Equivalent to np.size()\n @end_compatibility\n \"\"\"\n return size_internal(input, name, optimize=True, out_type=out_type)\n\n\ndef size_internal(input, name=None, optimize=True, out_type=dtypes.int32):\n # pylint: disable=redefined-builtin,protected-access\n \"\"\"Returns the size of a tensor.\n\n Args:\n input: A `Tensor` or `SparseTensor`.\n name: A name for the operation (optional).\n optimize: if true, encode the size as a constant when possible.\n out_type: (Optional) The specified non-quantized numeric output type of the\n operation. Defaults to `tf.int32`.\n\n Returns:\n A `Tensor` of type `out_type`. Defaults to `tf.int32`.\n \"\"\"\n if (context.executing_eagerly() and not hasattr(input, \"graph\") and\n not isinstance(\n input,\n (sparse_tensor.SparseTensor, sparse_tensor.SparseTensorValue))):\n input = ops.convert_to_tensor(input)\n np_out_type = out_type.as_numpy_dtype\n num_elements = np.prod(input._shape_tuple(), dtype=np_out_type) # pylint: disable=protected-access\n return ops.convert_to_tensor(num_elements, dtype=out_type)\n with ops.name_scope(name, \"Size\", [input]) as name:\n if isinstance(\n input, (sparse_tensor.SparseTensor, sparse_tensor.SparseTensorValue)):\n return gen_math_ops.prod(\n gen_math_ops.cast(input.dense_shape, out_type), 0, name=name)\n else:\n input = ops.convert_to_tensor(input)\n input_shape = input.get_shape()\n if optimize:\n if input_shape.is_fully_defined():\n return constant(input_shape.num_elements(), out_type, name=name)\n if input_shape.dims and any(dim == 0 for dim in input_shape.dims):\n return constant(0, out_type, name=name)\n return gen_array_ops.size(input, name=name, out_type=out_type)\n\n\n@tf_export(\"rank\")\[email protected]_dispatch_support\ndef rank(input, name=None):\n # pylint: disable=redefined-builtin\n \"\"\"Returns the rank of a tensor.\n\n See also `tf.shape`.\n\n Returns a 0-D `int32` `Tensor` representing the rank of `input`.\n\n For example:\n\n ```python\n # shape of tensor 't' is [2, 2, 3]\n t = tf.constant([[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]])\n tf.rank(t) # 3\n ```\n\n **Note**: The rank of a tensor is not the same as the rank of a matrix. The\n rank of a tensor is the number of indices required to uniquely select each\n element of the tensor. Rank is also known as \"order\", \"degree\", or \"ndims.\"\n\n Args:\n input: A `Tensor` or `SparseTensor`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of type `int32`.\n\n @compatibility(numpy)\n Equivalent to np.ndim\n @end_compatibility\n \"\"\"\n return rank_internal(input, name, optimize=True)\n\n\ndef rank_internal(input, name=None, optimize=True):\n # pylint: disable=redefined-builtin\n \"\"\"Returns the rank of a tensor.\n\n Args:\n input: A `Tensor` or `SparseTensor`.\n name: A name for the operation (optional).\n optimize: if true, encode the rank as a constant when possible.\n\n Returns:\n A `Tensor` of type `int32`.\n \"\"\"\n with ops.name_scope(name, \"Rank\", [input]) as name:\n if isinstance(\n input, (sparse_tensor.SparseTensor, sparse_tensor.SparseTensorValue)):\n return gen_array_ops.size(input.dense_shape, name=name)\n else:\n input = ops.convert_to_tensor(input)\n input_shape = input.get_shape()\n if optimize and input_shape.ndims is not None:\n return constant(input_shape.ndims, dtypes.int32, name=name)\n return gen_array_ops.rank(input, name=name)\n\n\n_SLICE_TYPE_ERROR = (\n \"Only integers, slices (`:`), ellipsis (`...`), \"\n \"tf.newaxis (`None`) and scalar tf.int32/tf.int64 tensors are valid \"\n \"indices\")\n\n_SUPPORTED_SLICE_DTYPES = (dtypes.int32, dtypes.int32_ref, dtypes.int64,\n dtypes.int64_ref)\n\n\ndef _check_index(idx):\n \"\"\"Check if a given value is a valid index into a tensor.\"\"\"\n if isinstance(idx, (numbers.Integral, tensor_shape.Dimension)):\n return\n\n # Optimistic check. Assumptions:\n # * any object with a dtype is supported\n # * any object with a dtype has a sizeable shape attribute.\n dtype = getattr(idx, \"dtype\", None)\n if (dtype is None or dtypes.as_dtype(dtype) not in _SUPPORTED_SLICE_DTYPES or\n idx.shape and len(idx.shape) == 1):\n # TODO(slebedev): IndexError seems more appropriate here, but it\n # will break `_slice_helper` contract.\n raise TypeError(_SLICE_TYPE_ERROR + \", got {!r}\".format(idx))\n\n\ndef _is_undefined_dimension(d):\n return isinstance(d, tensor_shape.Dimension) and d.value is None\n\n\ndef _slice_helper(tensor, slice_spec, var=None):\n \"\"\"Overload for Tensor.__getitem__.\n\n This operation extracts the specified region from the tensor.\n The notation is similar to NumPy with the restriction that\n currently only support basic indexing. That means that\n using a non-scalar tensor as input is not currently allowed.\n\n Some useful examples:\n\n ```python\n # Strip leading and trailing 2 elements\n foo = tf.constant([1,2,3,4,5,6])\n print(foo[2:-2].eval()) # => [3,4]\n\n # Skip every other row and reverse the order of the columns\n foo = tf.constant([[1,2,3], [4,5,6], [7,8,9]])\n print(foo[::2,::-1].eval()) # => [[3,2,1], [9,8,7]]\n\n # Use scalar tensors as indices on both dimensions\n print(foo[tf.constant(0), tf.constant(2)].eval()) # => 3\n\n # Insert another dimension\n foo = tf.constant([[1,2,3], [4,5,6], [7,8,9]])\n print(foo[tf.newaxis, :, :].eval()) # => [[[1,2,3], [4,5,6], [7,8,9]]]\n print(foo[:, tf.newaxis, :].eval()) # => [[[1,2,3]], [[4,5,6]], [[7,8,9]]]\n print(foo[:, :, tf.newaxis].eval()) # => [[[1],[2],[3]], [[4],[5],[6]],\n [[7],[8],[9]]]\n\n # Ellipses (3 equivalent operations)\n foo = tf.constant([[1,2,3], [4,5,6], [7,8,9]])\n print(foo[tf.newaxis, :, :].eval()) # => [[[1,2,3], [4,5,6], [7,8,9]]]\n print(foo[tf.newaxis, ...].eval()) # => [[[1,2,3], [4,5,6], [7,8,9]]]\n print(foo[tf.newaxis].eval()) # => [[[1,2,3], [4,5,6], [7,8,9]]]\n\n # Masks\n foo = tf.constant([[1,2,3], [4,5,6], [7,8,9]])\n print(foo[foo > 2].eval()) # => [3, 4, 5, 6, 7, 8, 9]\n ```\n\n Notes:\n - `tf.newaxis` is `None` as in NumPy.\n - An implicit ellipsis is placed at the end of the `slice_spec`\n - NumPy advanced indexing is currently not supported.\n\n Args:\n tensor: An ops.Tensor object.\n slice_spec: The arguments to Tensor.__getitem__.\n var: In the case of variable slice assignment, the Variable object to slice\n (i.e. tensor is the read-only view of this variable).\n\n Returns:\n The appropriate slice of \"tensor\", based on \"slice_spec\".\n\n Raises:\n ValueError: If a slice range is negative size.\n TypeError: If the slice indices aren't int, slice, ellipsis,\n tf.newaxis or scalar int32/int64 tensors.\n \"\"\"\n if isinstance(slice_spec, bool) or \\\n (isinstance(slice_spec, ops.Tensor) and slice_spec.dtype == dtypes.bool) or \\\n (isinstance(slice_spec, np.ndarray) and slice_spec.dtype == bool):\n return boolean_mask(tensor=tensor, mask=slice_spec)\n\n if not isinstance(slice_spec, (list, tuple)):\n slice_spec = [slice_spec]\n\n begin, end, strides = [], [], []\n index = 0\n\n new_axis_mask, shrink_axis_mask = 0, 0\n begin_mask, end_mask = 0, 0\n ellipsis_mask = 0\n for s in slice_spec:\n if isinstance(s, _BaseSlice):\n if s.start is not None and not _is_undefined_dimension(s.start):\n _check_index(s.start)\n begin.append(s.start)\n else:\n begin.append(0)\n begin_mask |= (1 << index)\n if s.stop is not None and not _is_undefined_dimension(s.stop):\n _check_index(s.stop)\n end.append(s.stop)\n else:\n end.append(0)\n end_mask |= (1 << index)\n if s.step is not None and not _is_undefined_dimension(s.step):\n _check_index(s.step)\n strides.append(s.step)\n else:\n strides.append(1)\n elif s is Ellipsis:\n begin.append(0)\n end.append(0)\n strides.append(1)\n ellipsis_mask |= (1 << index)\n elif s is newaxis:\n begin.append(0)\n end.append(0)\n strides.append(1)\n new_axis_mask |= (1 << index)\n else:\n _check_index(s)\n begin.append(s)\n end.append(s + 1)\n strides.append(1)\n shrink_axis_mask |= (1 << index)\n index += 1\n\n # stack possibly involves no tensors, so we must use op_scope correct graph.\n with ops.name_scope(\n None,\n \"strided_slice\", [tensor] + begin + end + strides,\n skip_on_eager=False) as name:\n if begin:\n packed_begin, packed_end, packed_strides = (stack(begin), stack(end),\n stack(strides))\n if (packed_begin.dtype == dtypes.int64 or\n packed_end.dtype == dtypes.int64 or\n packed_strides.dtype == dtypes.int64):\n if packed_begin.dtype != dtypes.int64:\n packed_begin = gen_math_ops.cast(packed_begin, dtypes.int64)\n if packed_end.dtype != dtypes.int64:\n packed_end = gen_math_ops.cast(packed_end, dtypes.int64)\n if packed_strides.dtype != dtypes.int64:\n packed_strides = gen_math_ops.cast(packed_strides, dtypes.int64)\n else:\n var_empty = constant([], dtype=dtypes.int32)\n packed_begin = packed_end = packed_strides = var_empty\n return strided_slice(\n tensor,\n packed_begin,\n packed_end,\n packed_strides,\n begin_mask=begin_mask,\n end_mask=end_mask,\n shrink_axis_mask=shrink_axis_mask,\n new_axis_mask=new_axis_mask,\n ellipsis_mask=ellipsis_mask,\n var=var,\n name=name)\n\n\n# pylint: disable=undefined-variable,protected-access,redefined-outer-name\n@tf_export(\"slice\")\ndef slice(input_, begin, size, name=None):\n # pylint: disable=redefined-builtin\n \"\"\"Extracts a slice from a tensor.\n\n See also `tf.strided_slice`.\n\n This operation extracts a slice of size `size` from a tensor `input_` starting\n at the location specified by `begin`. The slice `size` is represented as a\n tensor shape, where `size[i]` is the number of elements of the 'i'th dimension\n of `input_` that you want to slice. The starting location (`begin`) for the\n slice is represented as an offset in each dimension of `input_`. In other\n words, `begin[i]` is the offset into the i'th dimension of `input_` that you\n want to slice from.\n\n Note that `tf.Tensor.__getitem__` is typically a more pythonic way to\n perform slices, as it allows you to write `foo[3:7, :-2]` instead of\n `tf.slice(foo, [3, 0], [4, foo.get_shape()[1]-2])`.\n\n `begin` is zero-based; `size` is one-based. If `size[i]` is -1,\n all remaining elements in dimension i are included in the\n slice. In other words, this is equivalent to setting:\n\n `size[i] = input_.dim_size(i) - begin[i]`\n\n This operation requires that:\n\n `0 <= begin[i] <= begin[i] + size[i] <= Di for i in [0, n]`\n\n For example:\n\n ```python\n t = tf.constant([[[1, 1, 1], [2, 2, 2]],\n [[3, 3, 3], [4, 4, 4]],\n [[5, 5, 5], [6, 6, 6]]])\n tf.slice(t, [1, 0, 0], [1, 1, 3]) # [[[3, 3, 3]]]\n tf.slice(t, [1, 0, 0], [1, 2, 3]) # [[[3, 3, 3],\n # [4, 4, 4]]]\n tf.slice(t, [1, 0, 0], [2, 1, 3]) # [[[3, 3, 3]],\n # [[5, 5, 5]]]\n ```\n\n Args:\n input_: A `Tensor`.\n begin: An `int32` or `int64` `Tensor`.\n size: An `int32` or `int64` `Tensor`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` the same type as `input_`.\n \"\"\"\n return gen_array_ops._slice(input_, begin, size, name=name)\n\n\n# pylint: disable=invalid-name\n@tf_export(\"strided_slice\")\ndef strided_slice(input_,\n begin,\n end,\n strides=None,\n begin_mask=0,\n end_mask=0,\n ellipsis_mask=0,\n new_axis_mask=0,\n shrink_axis_mask=0,\n var=None,\n name=None):\n \"\"\"Extracts a strided slice of a tensor (generalized Python array indexing).\n\n See also `tf.slice`.\n\n **Instead of calling this op directly most users will want to use the\n NumPy-style slicing syntax (e.g. `tensor[..., 3:4:-1, tf.newaxis, 3]`), which\n is supported via `tf.Tensor.__getitem__` and `tf.Variable.__getitem__`.**\n The interface of this op is a low-level encoding of the slicing syntax.\n\n Roughly speaking, this op extracts a slice of size `(end-begin)/stride`\n from the given `input_` tensor. Starting at the location specified by `begin`\n the slice continues by adding `stride` to the index until all dimensions are\n not less than `end`.\n Note that a stride can be negative, which causes a reverse slice.\n\n Given a Python slice `input[spec0, spec1, ..., specn]`,\n this function will be called as follows.\n\n `begin`, `end`, and `strides` will be vectors of length n.\n n in general is not equal to the rank of the `input_` tensor.\n\n In each mask field (`begin_mask`, `end_mask`, `ellipsis_mask`,\n `new_axis_mask`, `shrink_axis_mask`) the ith bit will correspond to\n the ith spec.\n\n If the ith bit of `begin_mask` is set, `begin[i]` is ignored and\n the fullest possible range in that dimension is used instead.\n `end_mask` works analogously, except with the end range.\n\n `foo[5:,:,:3]` on a 7x8x9 tensor is equivalent to `foo[5:7,0:8,0:3]`.\n `foo[::-1]` reverses a tensor with shape 8.\n\n If the ith bit of `ellipsis_mask` is set, as many unspecified dimensions\n as needed will be inserted between other dimensions. Only one\n non-zero bit is allowed in `ellipsis_mask`.\n\n For example `foo[3:5,...,4:5]` on a shape 10x3x3x10 tensor is\n equivalent to `foo[3:5,:,:,4:5]` and\n `foo[3:5,...]` is equivalent to `foo[3:5,:,:,:]`.\n\n If the ith bit of `new_axis_mask` is set, then `begin`,\n `end`, and `stride` are ignored and a new length 1 dimension is\n added at this point in the output tensor.\n\n For example,\n `foo[:4, tf.newaxis, :2]` would produce a shape `(4, 1, 2)` tensor.\n\n If the ith bit of `shrink_axis_mask` is set, it implies that the ith\n specification shrinks the dimensionality by 1, taking on the value at index\n `begin[i]`. `end[i]` and `strides[i]` are ignored in this case. For example in\n Python one might do `foo[:, 3, :]` which would result in `shrink_axis_mask`\n equal to 2.\n\n\n NOTE: `begin` and `end` are zero-indexed.\n `strides` entries must be non-zero.\n\n\n ```python\n t = tf.constant([[[1, 1, 1], [2, 2, 2]],\n [[3, 3, 3], [4, 4, 4]],\n [[5, 5, 5], [6, 6, 6]]])\n tf.strided_slice(t, [1, 0, 0], [2, 1, 3], [1, 1, 1]) # [[[3, 3, 3]]]\n tf.strided_slice(t, [1, 0, 0], [2, 2, 3], [1, 1, 1]) # [[[3, 3, 3],\n # [4, 4, 4]]]\n tf.strided_slice(t, [1, -1, 0], [2, -3, 3], [1, -1, 1]) # [[[4, 4, 4],\n # [3, 3, 3]]]\n ```\n\n Args:\n input_: A `Tensor`.\n begin: An `int32` or `int64` `Tensor`.\n end: An `int32` or `int64` `Tensor`.\n strides: An `int32` or `int64` `Tensor`.\n begin_mask: An `int32` mask.\n end_mask: An `int32` mask.\n ellipsis_mask: An `int32` mask.\n new_axis_mask: An `int32` mask.\n shrink_axis_mask: An `int32` mask.\n var: The variable corresponding to `input_` or None\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` the same type as `input`.\n \"\"\"\n\n if strides is None:\n strides = ones_like(begin)\n\n op = gen_array_ops.strided_slice(\n input=input_,\n begin=begin,\n end=end,\n strides=strides,\n name=name,\n begin_mask=begin_mask,\n end_mask=end_mask,\n ellipsis_mask=ellipsis_mask,\n new_axis_mask=new_axis_mask,\n shrink_axis_mask=shrink_axis_mask)\n\n parent_name = name\n\n if not (var is None and isinstance(op, ops.EagerTensor)):\n\n def assign(val, name=None):\n \"\"\"Closure that holds all the arguments to create an assignment.\"\"\"\n\n if var is None:\n raise ValueError(\"Sliced assignment is only supported for variables\")\n else:\n if name is None:\n name = parent_name + \"_assign\"\n\n return var._strided_slice_assign(\n begin=begin,\n end=end,\n strides=strides,\n value=val,\n name=name,\n begin_mask=begin_mask,\n end_mask=end_mask,\n ellipsis_mask=ellipsis_mask,\n new_axis_mask=new_axis_mask,\n shrink_axis_mask=shrink_axis_mask)\n\n op.assign = assign\n return op\n\n\ndef _SliceHelperVar(var, slice_spec):\n \"\"\"Creates a slice helper object given a variable.\n\n This allows creating a sub-tensor from part of the current contents\n of a variable. See `tf.Tensor.__getitem__` for detailed examples\n of slicing.\n\n This function in addition also allows assignment to a sliced range.\n This is similar to `__setitem__` functionality in Python. However,\n the syntax is different so that the user can capture the assignment\n operation for grouping or passing to `sess.run()`.\n For example,\n\n ```python\n import tensorflow as tf\n A = tf.Variable([[1,2,3], [4,5,6], [7,8,9]], dtype=tf.float32)\n with tf.compat.v1.Session() as sess:\n sess.run(tf.compat.v1.global_variables_initializer())\n print(sess.run(A[:2, :2])) # => [[1,2], [4,5]]\n\n op = A[:2,:2].assign(22. * tf.ones((2, 2)))\n print(sess.run(op)) # => [[22, 22, 3], [22, 22, 6], [7,8,9]]\n ```\n\n Note that assignments currently do not support NumPy broadcasting\n semantics.\n\n Args:\n var: An `ops.Variable` object.\n slice_spec: The arguments to `Tensor.__getitem__`.\n\n Returns:\n The appropriate slice of \"tensor\", based on \"slice_spec\".\n As an operator. The operator also has a `assign()` method\n that can be used to generate an assignment operator.\n\n Raises:\n ValueError: If a slice range is negative size.\n TypeError: TypeError: If the slice indices aren't int, slice,\n ellipsis, tf.newaxis or int32/int64 tensors.\n\n \"\"\"\n\n return _slice_helper(var.value(), slice_spec, var)\n\n\nops.Tensor._override_operator(\"__getitem__\", _slice_helper)\n\n\n@tf_export(\"parallel_stack\")\ndef parallel_stack(values, name=\"parallel_stack\"):\n \"\"\"Stacks a list of rank-`R` tensors into one rank-`(R+1)` tensor in parallel.\n\n Requires that the shape of inputs be known at graph construction time.\n\n Packs the list of tensors in `values` into a tensor with rank one higher than\n each tensor in `values`, by packing them along the first dimension.\n Given a list of length `N` of tensors of shape `(A, B, C)`; the `output`\n tensor will have the shape `(N, A, B, C)`.\n\n For example:\n\n ```python\n x = tf.constant([1, 4])\n y = tf.constant([2, 5])\n z = tf.constant([3, 6])\n tf.parallel_stack([x, y, z]) # [[1, 4], [2, 5], [3, 6]]\n ```\n\n The difference between `stack` and `parallel_stack` is that `stack` requires\n all the inputs be computed before the operation will begin but doesn't require\n that the input shapes be known during graph construction.\n\n `parallel_stack` will copy pieces of the input into the output as they become\n available, in some situations this can provide a performance benefit.\n\n Unlike `stack`, `parallel_stack` does NOT support backpropagation.\n\n This is the opposite of unstack. The numpy equivalent is\n\n tf.parallel_stack([x, y, z]) = np.asarray([x, y, z])\n\n Args:\n values: A list of `Tensor` objects with the same shape and type.\n name: A name for this operation (optional).\n\n Returns:\n output: A stacked `Tensor` with the same type as `values`.\n \"\"\"\n with ops.name_scope(name):\n value_t = ops.convert_to_tensor(values[0])\n value_shape = ops.convert_to_tensor(value_t).get_shape()\n\n output_shape = tensor_shape.TensorShape([len(values)])\n output_shape = output_shape.concatenate(value_shape)\n # expand_dims converts concat to stack.\n return gen_array_ops.parallel_concat(\n [expand_dims(value, 0) for value in values], shape=output_shape)\n\n\n@tf_export(\"stack\")\[email protected]_dispatch_support\ndef stack(values, axis=0, name=\"stack\"):\n \"\"\"Stacks a list of rank-`R` tensors into one rank-`(R+1)` tensor.\n\n See also `tf.concat`, `tf.tile`, `tf.repeat`.\n\n Packs the list of tensors in `values` into a tensor with rank one higher than\n each tensor in `values`, by packing them along the `axis` dimension.\n Given a list of length `N` of tensors of shape `(A, B, C)`;\n\n if `axis == 0` then the `output` tensor will have the shape `(N, A, B, C)`.\n if `axis == 1` then the `output` tensor will have the shape `(A, N, B, C)`.\n Etc.\n\n For example:\n\n >>> x = tf.constant([1, 4])\n >>> y = tf.constant([2, 5])\n >>> z = tf.constant([3, 6])\n >>> tf.stack([x, y, z])\n <tf.Tensor: shape=(3, 2), dtype=int32, numpy=\n array([[1, 4],\n [2, 5],\n [3, 6]], dtype=int32)>\n >>> tf.stack([x, y, z], axis=1)\n <tf.Tensor: shape=(2, 3), dtype=int32, numpy=\n array([[1, 2, 3],\n [4, 5, 6]], dtype=int32)>\n\n This is the opposite of unstack. The numpy equivalent is `np.stack`\n\n >>> np.array_equal(np.stack([x, y, z]), tf.stack([x, y, z]))\n True\n\n Args:\n values: A list of `Tensor` objects with the same shape and type.\n axis: An `int`. The axis to stack along. Defaults to the first dimension.\n Negative values wrap around, so the valid range is `[-(R+1), R+1)`.\n name: A name for this operation (optional).\n\n Returns:\n output: A stacked `Tensor` with the same type as `values`.\n\n Raises:\n ValueError: If `axis` is out of the range [-(R+1), R+1).\n \"\"\"\n if axis == 0:\n try:\n # If the input is a constant list, it can be converted to a constant op\n return ops.convert_to_tensor(values, name=name)\n except (TypeError, ValueError):\n pass # Input list contains non-constant tensors\n\n value_shape = ops.convert_to_tensor(values[0], name=name)._shape_tuple() # pylint: disable=protected-access\n if value_shape is not None:\n expanded_num_dims = len(value_shape) + 1\n if axis < -expanded_num_dims or axis >= expanded_num_dims:\n raise ValueError(\"axis = %d not in [%d, %d)\" %\n (axis, -expanded_num_dims, expanded_num_dims))\n\n return gen_array_ops.pack(values, axis=axis, name=name)\n\n\n# pylint: disable=invalid-name\ndef _autopacking_helper(list_or_tuple, dtype, name):\n \"\"\"Converts the given list or tuple to a tensor by packing.\n\n Args:\n list_or_tuple: A (possibly nested) list or tuple containing a tensor.\n dtype: The element type of the returned tensor.\n name: A name for the returned tensor.\n\n Returns:\n A `tf.Tensor` with value equivalent to `list_or_tuple`.\n \"\"\"\n if context.executing_eagerly():\n # NOTE: Fast path when all the items are tensors, this doesn't do any type\n # checking.\n if all(isinstance(elem, core.Tensor) for elem in list_or_tuple):\n return gen_array_ops.pack(list_or_tuple, name=name)\n must_pack = False\n converted_elems = []\n with ops.name_scope(name) as scope:\n for i, elem in enumerate(list_or_tuple):\n if isinstance(elem, core.Tensor):\n if dtype is not None and elem.dtype.base_dtype != dtype:\n raise TypeError(\"Cannot convert a list containing a tensor of dtype \"\n \"%s to %s (Tensor is: %r)\" %\n (elem.dtype, dtype, elem))\n converted_elems.append(elem)\n must_pack = True\n elif isinstance(elem, (list, tuple)):\n converted_elem = _autopacking_helper(elem, dtype, str(i))\n if isinstance(converted_elem, core.Tensor):\n must_pack = True\n converted_elems.append(converted_elem)\n else:\n converted_elems.append(elem)\n if must_pack:\n elems_as_tensors = []\n for i, elem in enumerate(converted_elems):\n if isinstance(elem, core.Tensor):\n elems_as_tensors.append(elem)\n else:\n # NOTE(mrry): This is inefficient, but it enables us to\n # handle the case where the list arguments are other\n # convertible-to-tensor types, such as numpy arrays.\n elems_as_tensors.append(\n constant_op.constant(elem, dtype=dtype, name=str(i)))\n return gen_array_ops.pack(elems_as_tensors, name=scope)\n else:\n return converted_elems\n\n\ndef _get_dtype_from_nested_lists(list_or_tuple):\n \"\"\"Returns the dtype of any tensor-like object in `list_or_tuple`, if found.\n\n Args:\n list_or_tuple: A list or tuple representing an object that can be converted\n to a `tf.Tensor`.\n\n Returns:\n The dtype of any tensor-like object in `list_or_tuple`, or `None` if no\n such object exists.\n \"\"\"\n for elem in list_or_tuple:\n if isinstance(elem, core.Tensor):\n return elem.dtype.base_dtype\n elif isinstance(elem, (list, tuple)):\n maybe_dtype = _get_dtype_from_nested_lists(elem)\n if maybe_dtype is not None:\n return maybe_dtype\n return None\n\n\ndef _cast_nested_seqs_to_dtype(dtype):\n\n def _maybe_cast(elem):\n if isinstance(elem, core.Tensor):\n if dtype != elem.dtype.base_dtype:\n elem = gen_math_ops.cast(elem, dtype)\n return elem\n\n return _maybe_cast\n\n\n_NON_AUTOPACKABLE_TYPES = set(np.core.numerictypes.ScalarType)\n_NON_AUTOPACKABLE_TYPES.add(np.ndarray)\n\n\ndef _should_not_autopack(v):\n # The condition we really want is\n # any(isinstance(elem, core.Tensor))\n # but it is >5x slower due to abc.ABCMeta.__instancecheck__.\n # pylint: disable=unidiomatic-typecheck\n # TODO(slebedev): add nest.all?\n return all(type(elem) in _NON_AUTOPACKABLE_TYPES for elem in nest.flatten(v))\n # pylint: enable=unidiomatic-typecheck\n\n\ndef _autopacking_conversion_function(v, dtype=None, name=None, as_ref=False):\n \"\"\"Tensor conversion function that automatically packs arguments.\"\"\"\n if as_ref or _should_not_autopack(v):\n return NotImplemented\n inferred_dtype = _get_dtype_from_nested_lists(v)\n if inferred_dtype is None:\n # We did not find any tensor-like objects in the nested lists, so defer to\n # other conversion functions.\n return NotImplemented\n if dtype is None:\n dtype = inferred_dtype\n elif dtype != inferred_dtype:\n v = nest.map_structure(_cast_nested_seqs_to_dtype(dtype), v)\n return _autopacking_helper(v, dtype, name or \"packed\")\n\n\n# pylint: enable=invalid-name\n\n# NOTE: Register this conversion function to run *before* one that\n# assumes every element is a value.\nops.register_tensor_conversion_function((list, tuple),\n _autopacking_conversion_function, 99)\n\n\n@tf_export(\"unstack\")\ndef unstack(value, num=None, axis=0, name=\"unstack\"):\n \"\"\"Unpacks the given dimension of a rank-`R` tensor into rank-`(R-1)` tensors.\n\n Unpacks `num` tensors from `value` by chipping it along the `axis` dimension.\n If `num` is not specified (the default), it is inferred from `value`'s shape.\n If `value.shape[axis]` is not known, `ValueError` is raised.\n\n For example, given a tensor of shape `(A, B, C, D)`;\n\n If `axis == 0` then the i'th tensor in `output` is the slice\n `value[i, :, :, :]` and each tensor in `output` will have shape `(B, C, D)`.\n (Note that the dimension unpacked along is gone, unlike `split`).\n\n If `axis == 1` then the i'th tensor in `output` is the slice\n `value[:, i, :, :]` and each tensor in `output` will have shape `(A, C, D)`.\n Etc.\n\n This is the opposite of stack.\n\n Args:\n value: A rank `R > 0` `Tensor` to be unstacked.\n num: An `int`. The length of the dimension `axis`. Automatically inferred if\n `None` (the default).\n axis: An `int`. The axis to unstack along. Defaults to the first dimension.\n Negative values wrap around, so the valid range is `[-R, R)`.\n name: A name for the operation (optional).\n\n Returns:\n The list of `Tensor` objects unstacked from `value`.\n\n Raises:\n ValueError: If `num` is unspecified and cannot be inferred.\n ValueError: If `axis` is out of the range [-R, R).\n \"\"\"\n if num is None:\n value = ops.convert_to_tensor(value)\n value_shape = value.get_shape()\n if value_shape.ndims is not None:\n if axis < -value_shape.ndims or axis >= value_shape.ndims:\n raise ValueError(\"axis = %d not in [%d, %d)\" %\n (axis, -value_shape.ndims, value_shape.ndims))\n num = value_shape.dims[axis].value\n if num is None:\n raise ValueError(\"Cannot infer num from shape %s\" % value_shape)\n return gen_array_ops.unpack(value, num=num, axis=axis, name=name)\n\n\n@tf_export(\"concat\")\[email protected]_dispatch_support\ndef concat(values, axis, name=\"concat\"):\n \"\"\"Concatenates tensors along one dimension.\n\n See also `tf.tile`, `tf.stack`, `tf.repeat`.\n\n Concatenates the list of tensors `values` along dimension `axis`. If\n `values[i].shape = [D0, D1, ... Daxis(i), ...Dn]`, the concatenated\n result has shape\n\n [D0, D1, ... Raxis, ...Dn]\n\n where\n\n Raxis = sum(Daxis(i))\n\n That is, the data from the input tensors is joined along the `axis`\n dimension.\n\n The number of dimensions of the input tensors must match, and all dimensions\n except `axis` must be equal.\n\n For example:\n\n >>> t1 = [[1, 2, 3], [4, 5, 6]]\n >>> t2 = [[7, 8, 9], [10, 11, 12]]\n >>> tf.concat([t1, t2], 0)\n <tf.Tensor: shape=(4, 3), dtype=int32, numpy=\n array([[ 1, 2, 3],\n [ 4, 5, 6],\n [ 7, 8, 9],\n [10, 11, 12]], dtype=int32)>\n\n >>> tf.concat([t1, t2], 1)\n <tf.Tensor: shape=(2, 6), dtype=int32, numpy=\n array([[ 1, 2, 3, 7, 8, 9],\n [ 4, 5, 6, 10, 11, 12]], dtype=int32)>\n\n As in Python, the `axis` could also be negative numbers. Negative `axis`\n are interpreted as counting from the end of the rank, i.e.,\n `axis + rank(values)`-th dimension.\n\n For example:\n\n >>> t1 = [[[1, 2], [2, 3]], [[4, 4], [5, 3]]]\n >>> t2 = [[[7, 4], [8, 4]], [[2, 10], [15, 11]]]\n >>> tf.concat([t1, t2], -1)\n <tf.Tensor: shape=(2, 2, 4), dtype=int32, numpy=\n array([[[ 1, 2, 7, 4],\n [ 2, 3, 8, 4]],\n [[ 4, 4, 2, 10],\n [ 5, 3, 15, 11]]], dtype=int32)>\n\n Note: If you are concatenating along a new axis consider using stack.\n E.g.\n\n ```python\n tf.concat([tf.expand_dims(t, axis) for t in tensors], axis)\n ```\n\n can be rewritten as\n\n ```python\n tf.stack(tensors, axis=axis)\n ```\n\n Args:\n values: A list of `Tensor` objects or a single `Tensor`.\n axis: 0-D `int32` `Tensor`. Dimension along which to concatenate. Must be\n in the range `[-rank(values), rank(values))`. As in Python, indexing for\n axis is 0-based. Positive axis in the rage of `[0, rank(values))` refers\n to `axis`-th dimension. And negative axis refers to `axis +\n rank(values)`-th dimension.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` resulting from concatenation of the input tensors.\n \"\"\"\n if not isinstance(values, (list, tuple)):\n values = [values]\n # TODO(mrry): Change to return values?\n if len(values) == 1: # Degenerate case of one tensor.\n # Make a throwaway call to convert_to_tensor to make sure\n # that axis is of the correct type, and make sure that\n # the returned tensor is a scalar.\n # TODO(keveman): Implement a standalone type and shape checker.\n with ops.name_scope(name) as scope:\n ops.convert_to_tensor(\n axis, name=\"concat_dim\",\n dtype=dtypes.int32).get_shape().assert_has_rank(0)\n return identity(values[0], name=name)\n return gen_array_ops.concat_v2(values=values, axis=axis, name=name)\n\n\n@tf_export(v1=[\"boolean_mask\"])\ndef boolean_mask(tensor, mask, name=\"boolean_mask\", axis=None):\n \"\"\"Apply boolean mask to tensor.\n\n Numpy equivalent is `tensor[mask]`.\n\n ```python\n # 1-D example\n tensor = [0, 1, 2, 3]\n mask = np.array([True, False, True, False])\n boolean_mask(tensor, mask) # [0, 2]\n ```\n\n In general, `0 < dim(mask) = K <= dim(tensor)`, and `mask`'s shape must match\n the first K dimensions of `tensor`'s shape. We then have:\n `boolean_mask(tensor, mask)[i, j1,...,jd] = tensor[i1,...,iK,j1,...,jd]`\n where `(i1,...,iK)` is the ith `True` entry of `mask` (row-major order).\n The `axis` could be used with `mask` to indicate the axis to mask from.\n In that case, `axis + dim(mask) <= dim(tensor)` and `mask`'s shape must match\n the first `axis + dim(mask)` dimensions of `tensor`'s shape.\n\n See also: `tf.ragged.boolean_mask`, which can be applied to both dense and\n ragged tensors, and can be used if you need to preserve the masked dimensions\n of `tensor` (rather than flattening them, as `tf.boolean_mask` does).\n\n Args:\n tensor: N-D tensor.\n mask: K-D boolean tensor, K <= N and K must be known statically.\n name: A name for this operation (optional).\n axis: A 0-D int Tensor representing the axis in `tensor` to mask from. By\n default, axis is 0 which will mask from the first dimension. Otherwise K +\n axis <= N.\n\n Returns:\n (N-K+1)-dimensional tensor populated by entries in `tensor` corresponding\n to `True` values in `mask`.\n\n Raises:\n ValueError: If shapes do not conform.\n\n Examples:\n\n ```python\n # 2-D example\n tensor = [[1, 2], [3, 4], [5, 6]]\n mask = np.array([True, False, True])\n boolean_mask(tensor, mask) # [[1, 2], [5, 6]]\n ```\n \"\"\"\n\n def _apply_mask_1d(reshaped_tensor, mask, axis=None):\n \"\"\"Mask tensor along dimension 0 with a 1-D mask.\"\"\"\n indices = squeeze(where_v2(mask), axis=[1])\n return gather(reshaped_tensor, indices, axis=axis)\n\n with ops.name_scope(name, values=[tensor, mask]):\n tensor = ops.convert_to_tensor(tensor, name=\"tensor\")\n mask = ops.convert_to_tensor(mask, name=\"mask\")\n\n shape_mask = mask.get_shape()\n ndims_mask = shape_mask.ndims\n shape_tensor = tensor.get_shape()\n if ndims_mask == 0:\n raise ValueError(\"mask cannot be scalar.\")\n if ndims_mask is None:\n raise ValueError(\n \"Number of mask dimensions must be specified, even if some dimensions\"\n \" are None. E.g. shape=[None] is ok, but shape=None is not.\")\n axis = 0 if axis is None else axis\n axis_value = tensor_util.constant_value(axis)\n if axis_value is not None:\n axis = axis_value\n shape_tensor[axis:axis + ndims_mask].assert_is_compatible_with(shape_mask)\n\n leading_size = gen_math_ops.prod(shape(tensor)[axis:axis + ndims_mask], [0])\n tensor = reshape(\n tensor,\n concat([\n shape(tensor)[:axis], [leading_size],\n shape(tensor)[axis + ndims_mask:]\n ], 0))\n # TODO(yongtang): tf.reshape in C++ kernel might have set the shape\n # correctly, so the following may not be needed? It still might ben\n # possible that there are some edge case where tensor_util.constant_value\n # resolves more case than ShapeInference of tf.reshape in C++ kernel.\n if axis_value is not None:\n first_dim = shape_tensor[axis:axis + ndims_mask].num_elements()\n tensor.set_shape(\n tensor_shape.as_shape(shape_tensor[:axis]).concatenate(\n [first_dim]).concatenate(shape_tensor[axis + ndims_mask:]))\n\n mask = reshape(mask, [-1])\n return _apply_mask_1d(tensor, mask, axis)\n\n\n@tf_export(\"boolean_mask\", v1=[])\[email protected]_dispatch_support\ndef boolean_mask_v2(tensor, mask, axis=None, name=\"boolean_mask\"):\n \"\"\"Apply boolean mask to tensor.\n\n Numpy equivalent is `tensor[mask]`.\n\n ```python\n # 1-D example\n tensor = [0, 1, 2, 3]\n mask = np.array([True, False, True, False])\n boolean_mask(tensor, mask) # [0, 2]\n ```\n\n In general, `0 < dim(mask) = K <= dim(tensor)`, and `mask`'s shape must match\n the first K dimensions of `tensor`'s shape. We then have:\n `boolean_mask(tensor, mask)[i, j1,...,jd] = tensor[i1,...,iK,j1,...,jd]`\n where `(i1,...,iK)` is the ith `True` entry of `mask` (row-major order).\n The `axis` could be used with `mask` to indicate the axis to mask from.\n In that case, `axis + dim(mask) <= dim(tensor)` and `mask`'s shape must match\n the first `axis + dim(mask)` dimensions of `tensor`'s shape.\n\n See also: `tf.ragged.boolean_mask`, which can be applied to both dense and\n ragged tensors, and can be used if you need to preserve the masked dimensions\n of `tensor` (rather than flattening them, as `tf.boolean_mask` does).\n\n Args:\n tensor: N-D tensor.\n mask: K-D boolean tensor, K <= N and K must be known statically.\n axis: A 0-D int Tensor representing the axis in `tensor` to mask from. By\n default, axis is 0 which will mask from the first dimension. Otherwise K +\n axis <= N.\n name: A name for this operation (optional).\n\n Returns:\n (N-K+1)-dimensional tensor populated by entries in `tensor` corresponding\n to `True` values in `mask`.\n\n Raises:\n ValueError: If shapes do not conform.\n\n Examples:\n\n ```python\n # 2-D example\n tensor = [[1, 2], [3, 4], [5, 6]]\n mask = np.array([True, False, True])\n boolean_mask(tensor, mask) # [[1, 2], [5, 6]]\n ```\n \"\"\"\n return boolean_mask(tensor, mask, name, axis)\n\n\n@tf_export(\"sparse.mask\", v1=[\"sparse.mask\", \"sparse_mask\"])\[email protected]_endpoints(\"sparse_mask\")\ndef sparse_mask(a, mask_indices, name=None):\n \"\"\"Masks elements of `IndexedSlices`.\n\n Given an `IndexedSlices` instance `a`, returns another `IndexedSlices` that\n contains a subset of the slices of `a`. Only the slices at indices not\n specified in `mask_indices` are returned.\n\n This is useful when you need to extract a subset of slices in an\n `IndexedSlices` object.\n\n For example:\n\n ```python\n # `a` contains slices at indices [12, 26, 37, 45] from a large tensor\n # with shape [1000, 10]\n a.indices # [12, 26, 37, 45]\n tf.shape(a.values) # [4, 10]\n\n # `b` will be the subset of `a` slices at its second and third indices, so\n # we want to mask its first and last indices (which are at absolute\n # indices 12, 45)\n b = tf.sparse.mask(a, [12, 45])\n\n b.indices # [26, 37]\n tf.shape(b.values) # [2, 10]\n ```\n\n Args:\n a: An `IndexedSlices` instance.\n mask_indices: Indices of elements to mask.\n name: A name for the operation (optional).\n\n Returns:\n The masked `IndexedSlices` instance.\n \"\"\"\n with ops.name_scope(name, \"sparse_mask\", [a, mask_indices]) as name:\n indices = a.indices\n out_indices, to_gather = gen_array_ops.list_diff(indices, mask_indices)\n out_values = gather(a.values, to_gather, name=name)\n return ops.IndexedSlices(out_values, out_indices, a.dense_shape)\n\n\n@tf_export(\"unique\")\ndef unique(x, out_idx=dtypes.int32, name=None):\n \"\"\"Finds unique elements in a 1-D tensor.\n\n See also `tf.unique_with_counts`.\n\n This operation returns a tensor `y` containing all of the unique elements\n of `x` sorted in the same order that they occur in `x`. This operation\n also returns a tensor `idx` the same size as `x` that contains the index\n of each value of `x` in the unique output `y`. In other words:\n\n\n y[idx[i]] = x[i] for i in [0, 1,...,rank(x) - 1]\n\n Example usage:\n\n >>> x = tf.constant([1, 1, 2, 4, 4, 4, 7, 8, 8])\n >>> y, idx = unique(x)\n >>> y\n <tf.Tensor: id=5, shape=(5,), dtype=int32,\n numpy=array([1, 2, 4, 7, 8], dtype=int32)>\n >>> idx\n <tf.Tensor: id=6, shape=(9,), dtype=int32,\n numpy=array([0, 0, 1, 2, 2, 2, 3, 4, 4], dtype=int32)>\n\n Args:\n x: A Tensor. 1-D.\n out_idx: An optional tf.DType from: tf.int32, tf.int64. Defaults to\n tf.int32.\n name: A name for the operation (optional).\n\n Returns:\n A tuple of Tensor objects (y, idx).\n y: A Tensor. Has the same type as x.\n idx: A Tensor of type out_idx.\n\n \"\"\"\n # TODO(yongtang): switch to v2 once API deprecation\n # period (3 weeks) pass.\n # TODO(yongtang): The documentation should also\n # be updated when switch to v2.\n return gen_array_ops.unique(x, out_idx, name)\n\n\nunique.__doc__ = gen_array_ops.unique.__doc__\n\n\n@tf_export(\"unique_with_counts\")\ndef unique_with_counts(x, out_idx=dtypes.int32, name=None):\n \"\"\"Finds unique elements in a 1-D tensor.\n\n See also `tf.unique`.\n\n This operation returns a tensor `y` containing all of the unique elements\n of `x` sorted in the same order that they occur in `x`. This operation\n also returns a tensor `idx` the same size as `x` that contains the index\n of each value of `x` in the unique output `y`. Finally, it returns a\n third tensor `count` that contains the count of each element of `y`\n in `x`. In other words:\n\n y[idx[i]] = x[i] for i in [0, 1,...,rank(x) - 1]\n\n Example usage:\n\n >>> x = tf.constant([1, 1, 2, 4, 4, 4, 7, 8, 8])\n >>> y, idx, count = unique_with_counts(x)\n >>> y\n <tf.Tensor: id=8, shape=(5,), dtype=int32,\n numpy=array([1, 2, 4, 7, 8], dtype=int32)>\n >>> idx\n <tf.Tensor: id=9, shape=(9,), dtype=int32,\n numpy=array([0, 0, 1, 2, 2, 2, 3, 4, 4], dtype=int32)>\n >>> count\n <tf.Tensor: id=10, shape=(5,), dtype=int32,\n numpy=array([2, 1, 3, 1, 2], dtype=int32)>\n\n Args:\n x: A Tensor. 1-D.\n out_idx: An optional tf.DType from: tf.int32, tf.int64. Defaults to\n tf.int32.\n name: A name for the operation (optional).\n\n Returns:\n A tuple of Tensor objects (y, idx, count).\n y: A Tensor. Has the same type as x.\n idx: A Tensor of type out_idx.\n count: A Tensor of type out_idx.\n\n \"\"\"\n # TODO(yongtang): switch to v2 once API deprecation\n # period (3 weeks) pass.\n # TODO(yongtang): The documentation should also\n # be updated when switch to v2.\n return gen_array_ops.unique_with_counts(x, out_idx, name)\n\n\nunique_with_counts.__doc__ = gen_array_ops.unique_with_counts.__doc__\n\n\n@tf_export(\"split\")\ndef split(value, num_or_size_splits, axis=0, num=None, name=\"split\"):\n \"\"\"Splits a tensor `value` into a list of sub tensors.\n\n See also `tf.unstack`.\n\n If `num_or_size_splits` is an integer, then `value` is split along the\n dimension `axis` into `num_split` smaller tensors. This requires that\n `value.shape[axis]` is divisible by `num_split`.\n\n If `num_or_size_splits` is a 1-D Tensor (or list), we call it `size_splits`\n and `value` is split into `len(size_splits)` elements. The shape of the `i`-th\n element has the same size as the `value` except along dimension `axis` where\n the size is `size_splits[i]`.\n\n For example:\n\n >>> x = tf.Variable(tf.random.uniform([5, 30], -1, 1))\n\n Split `x` into 3 tensors along dimension 1\n >>> s0, s1, s2 = tf.split(x, num_or_size_splits=3, axis=1)\n >>> tf.shape(s0).numpy()\n array([ 5, 10], dtype=int32)\n\n Split `x` into 3 tensors with sizes [4, 15, 11] along dimension 1\n >>> split0, split1, split2 = tf.split(x, [4, 15, 11], 1)\n >>> tf.shape(split0).numpy()\n array([5, 4], dtype=int32)\n >>> tf.shape(split1).numpy()\n array([ 5, 15], dtype=int32)\n >>> tf.shape(split2).numpy()\n array([ 5, 11], dtype=int32)\n\n Args:\n value: The `Tensor` to split.\n num_or_size_splits: Either an integer indicating the number of splits along\n `axis` or a 1-D integer `Tensor` or Python list containing the sizes of\n each output tensor along `axis`. If a scalar, then it must evenly divide\n `value.shape[axis]`; otherwise the sum of sizes along the split axis\n must match that of the `value`.\n axis: An integer or scalar `int32` `Tensor`. The dimension along which to\n split. Must be in the range `[-rank(value), rank(value))`. Defaults to 0.\n num: Optional, used to specify the number of outputs when it cannot be\n inferred from the shape of `size_splits`.\n name: A name for the operation (optional).\n\n Returns:\n if `num_or_size_splits` is a scalar returns a list of `num_or_size_splits`\n `Tensor` objects; if `num_or_size_splits` is a 1-D Tensor returns\n `num_or_size_splits.get_shape[0]` `Tensor` objects resulting from splitting\n `value`.\n\n Raises:\n ValueError: If `num` is unspecified and cannot be inferred.\n \"\"\"\n size_splits = ops.convert_to_tensor(num_or_size_splits)\n if isinstance(num_or_size_splits,\n (numbers.Integral, tensor_shape.Dimension)):\n return gen_array_ops.split(\n axis=axis, num_split=num_or_size_splits, value=value, name=name)\n\n if size_splits._rank() == 0:\n raise ValueError(\n \"Rank-0 tensors are not supported as the num_or_size_splits argument \"\n \"to split. Argument provided: %s\" % (num_or_size_splits,))\n\n if num is None:\n size_splits_shape = size_splits._shape_tuple()\n if size_splits_shape:\n num = size_splits_shape[0]\n if num is None:\n raise ValueError(\"Cannot infer num from shape %s\" % num_or_size_splits)\n\n return gen_array_ops.split_v(\n value=value, size_splits=size_splits, axis=axis, num_split=num, name=name)\n\n\n@tf_export(\"transpose\", v1=[])\ndef transpose_v2(a, perm=None, conjugate=False, name=\"transpose\"):\n \"\"\"Transposes `a`, where `a` is a Tensor.\n\n Permutes the dimensions according to the value of `perm`.\n\n The returned tensor's dimension `i` will correspond to the input dimension\n `perm[i]`. If `perm` is not given, it is set to (n-1...0), where n is the rank\n of the input tensor. Hence by default, this operation performs a regular\n matrix transpose on 2-D input Tensors.\n\n If conjugate is `True` and `a.dtype` is either `complex64` or `complex128`\n then the values of `a` are conjugated and transposed.\n\n @compatibility(numpy)\n In `numpy` transposes are memory-efficient constant time operations as they\n simply return a new view of the same data with adjusted `strides`.\n\n TensorFlow does not support strides, so `transpose` returns a new tensor with\n the items permuted.\n @end_compatibility\n\n For example:\n\n >>> x = tf.constant([[1, 2, 3], [4, 5, 6]])\n >>> tf.transpose(x)\n <tf.Tensor: shape=(3, 2), dtype=int32, numpy=\n array([[1, 4],\n [2, 5],\n [3, 6]], dtype=int32)>\n\n Equivalently, you could call `tf.transpose(x, perm=[1, 0])`.\n\n If `x` is complex, setting conjugate=True gives the conjugate transpose:\n\n >>> x = tf.constant([[1 + 1j, 2 + 2j, 3 + 3j],\n ... [4 + 4j, 5 + 5j, 6 + 6j]])\n >>> tf.transpose(x, conjugate=True)\n <tf.Tensor: shape=(3, 2), dtype=complex128, numpy=\n array([[1.-1.j, 4.-4.j],\n [2.-2.j, 5.-5.j],\n [3.-3.j, 6.-6.j]])>\n\n 'perm' is more useful for n-dimensional tensors where n > 2:\n\n >>> x = tf.constant([[[ 1, 2, 3],\n ... [ 4, 5, 6]],\n ... [[ 7, 8, 9],\n ... [10, 11, 12]]])\n\n As above, simply calling `tf.transpose` will default to `perm=[2,1,0]`.\n\n To take the transpose of the matrices in dimension-0 (such as when you are\n transposing matrices where 0 is the batch dimesnion), you would set\n `perm=[0,2,1]`.\n\n >>> tf.transpose(x, perm=[0, 2, 1])\n <tf.Tensor: shape=(2, 3, 2), dtype=int32, numpy=\n array([[[ 1, 4],\n [ 2, 5],\n [ 3, 6]],\n [[ 7, 10],\n [ 8, 11],\n [ 9, 12]]], dtype=int32)>\n\n Note: This has a shorthand `linalg.matrix_transpose`):\n\n Args:\n a: A `Tensor`.\n perm: A permutation of the dimensions of `a`. This should be a vector.\n conjugate: Optional bool. Setting it to `True` is mathematically equivalent\n to tf.math.conj(tf.transpose(input)).\n name: A name for the operation (optional).\n\n Returns:\n A transposed `Tensor`.\n \"\"\"\n return transpose(a=a, perm=perm, name=name, conjugate=conjugate)\n\n\n@tf_export(v1=[\"transpose\"])\ndef transpose(a, perm=None, name=\"transpose\", conjugate=False):\n \"\"\"Transposes `a`.\n\n Permutes the dimensions according to `perm`.\n\n The returned tensor's dimension i will correspond to the input dimension\n `perm[i]`. If `perm` is not given, it is set to (n-1...0), where n is\n the rank of the input tensor. Hence by default, this operation performs a\n regular matrix transpose on 2-D input Tensors. If conjugate is True and\n `a.dtype` is either `complex64` or `complex128` then the values of `a`\n are conjugated and transposed.\n\n @compatibility(numpy)\n In `numpy` transposes are memory-efficient constant time operations as they\n simply return a new view of the same data with adjusted `strides`.\n\n TensorFlow does not support strides, so `transpose` returns a new tensor with\n the items permuted.\n @end_compatibility\n\n For example:\n\n ```python\n x = tf.constant([[1, 2, 3], [4, 5, 6]])\n tf.transpose(x) # [[1, 4]\n # [2, 5]\n # [3, 6]]\n\n # Equivalently\n tf.transpose(x, perm=[1, 0]) # [[1, 4]\n # [2, 5]\n # [3, 6]]\n\n # If x is complex, setting conjugate=True gives the conjugate transpose\n x = tf.constant([[1 + 1j, 2 + 2j, 3 + 3j],\n [4 + 4j, 5 + 5j, 6 + 6j]])\n tf.transpose(x, conjugate=True) # [[1 - 1j, 4 - 4j],\n # [2 - 2j, 5 - 5j],\n # [3 - 3j, 6 - 6j]]\n\n # 'perm' is more useful for n-dimensional tensors, for n > 2\n x = tf.constant([[[ 1, 2, 3],\n [ 4, 5, 6]],\n [[ 7, 8, 9],\n [10, 11, 12]]])\n\n # Take the transpose of the matrices in dimension-0\n # (this common operation has a shorthand `linalg.matrix_transpose`)\n tf.transpose(x, perm=[0, 2, 1]) # [[[1, 4],\n # [2, 5],\n # [3, 6]],\n # [[7, 10],\n # [8, 11],\n # [9, 12]]]\n ```\n\n Args:\n a: A `Tensor`.\n perm: A permutation of the dimensions of `a`.\n name: A name for the operation (optional).\n conjugate: Optional bool. Setting it to `True` is mathematically equivalent\n to tf.math.conj(tf.transpose(input)).\n\n Returns:\n A transposed `Tensor`.\n \"\"\"\n with ops.name_scope(name, \"transpose\", [a]) as name:\n if not tensor_util.is_tensor(a):\n a = ops.convert_to_tensor(a, name=\"a\")\n\n if conjugate and a.dtype.is_complex:\n transpose_fn = gen_array_ops.conjugate_transpose\n else:\n transpose_fn = gen_array_ops.transpose\n\n if perm is not None:\n return transpose_fn(a, perm, name=name)\n\n rank = a.shape.rank\n if rank is None:\n perm = gen_math_ops._range(gen_array_ops.rank(a) - 1, -1, -1)\n else:\n perm = np.arange(rank - 1, -1, -1, dtype=np.int32)\n return transpose_fn(a, perm, name=name)\n\n\n# pylint: disable=invalid-name\n@tf_export(\n \"linalg.matrix_transpose\",\n v1=[\"linalg.transpose\", \"linalg.matrix_transpose\", \"matrix_transpose\"])\[email protected]_endpoints(\"matrix_transpose\", \"linalg.transpose\")\ndef matrix_transpose(a, name=\"matrix_transpose\", conjugate=False):\n \"\"\"Transposes last two dimensions of tensor `a`.\n\n For example:\n\n ```python\n x = tf.constant([[1, 2, 3], [4, 5, 6]])\n tf.linalg.matrix_transpose(x) # [[1, 4],\n # [2, 5],\n # [3, 6]]\n\n x = tf.constant([[1 + 1j, 2 + 2j, 3 + 3j],\n [4 + 4j, 5 + 5j, 6 + 6j]])\n tf.linalg.matrix_transpose(x, conjugate=True) # [[1 - 1j, 4 - 4j],\n # [2 - 2j, 5 - 5j],\n # [3 - 3j, 6 - 6j]]\n\n # Matrix with two batch dimensions.\n # x.shape is [1, 2, 3, 4]\n # tf.linalg.matrix_transpose(x) is shape [1, 2, 4, 3]\n ```\n\n Note that `tf.matmul` provides kwargs allowing for transpose of arguments.\n This is done with minimal cost, and is preferable to using this function. E.g.\n\n ```python\n # Good! Transpose is taken at minimal additional cost.\n tf.matmul(matrix, b, transpose_b=True)\n\n # Inefficient!\n tf.matmul(matrix, tf.linalg.matrix_transpose(b))\n ```\n\n @compatibility(numpy)\n In `numpy` transposes are memory-efficient constant time operations as they\n simply return a new view of the same data with adjusted `strides`.\n\n TensorFlow does not support strides, `linalg.matrix_transpose` returns a new\n tensor with the items permuted.\n @end_compatibility\n\n Args:\n a: A `Tensor` with `rank >= 2`.\n name: A name for the operation (optional).\n conjugate: Optional bool. Setting it to `True` is mathematically equivalent\n to tf.math.conj(tf.linalg.matrix_transpose(input)).\n\n Returns:\n A transposed batch matrix `Tensor`.\n\n Raises:\n ValueError: If `a` is determined statically to have `rank < 2`.\n \"\"\"\n with ops.name_scope(name, values=[a]):\n a = ops.convert_to_tensor(a, name=\"a\")\n\n # If we know the number of dimensions (statically), we can do two things:\n # 1. Check that `a` is a (batch) matrix.\n # 2. Use a Python list for perm. This preserves static shape information\n # and avoids extra computations.\n a_shape = a.get_shape()\n ndims = a_shape.ndims\n if ndims is not None:\n if ndims < 2:\n raise ValueError(\n \"Argument 'a' should be a (batch) matrix, with rank >= 2. Found: \"\n \"%s\" % a_shape)\n perm = list(range(ndims - 2)) + [ndims - 1] + [ndims - 2]\n else:\n a_rank = rank(a)\n perm = concat(\n (gen_math_ops._range(0, a_rank - 2, 1), [a_rank - 1, a_rank - 2]), 0)\n\n return transpose(a, perm=perm, conjugate=conjugate)\n\n\n@tf_export(\"linalg.diag\", v1=[\"linalg.diag\", \"matrix_diag\"])\[email protected]_endpoints(\"matrix_diag\")\ndef matrix_diag(diagonal,\n name=\"diag\",\n k=0,\n num_rows=-1,\n num_cols=-1,\n padding_value=0,\n align=\"RIGHT_LEFT\"):\n \"\"\"Returns a batched diagonal tensor with given batched diagonal values.\n\n Returns a tensor with the contents in `diagonal` as `k[0]`-th to `k[1]`-th\n diagonals of a matrix, with everything else padded with `padding`. `num_rows`\n and `num_cols` specify the dimension of the innermost matrix of the output. If\n both are not specified, the op assumes the innermost matrix is square and\n infers its size from `k` and the innermost dimension of `diagonal`. If only\n one of them is specified, the op assumes the unspecified value is the smallest\n possible based on other criteria.\n\n Let `diagonal` have `r` dimensions `[I, J, ..., L, M, N]`. The output tensor\n has rank `r+1` with shape `[I, J, ..., L, M, num_rows, num_cols]` when only\n one diagonal is given (`k` is an integer or `k[0] == k[1]`). Otherwise, it has\n rank `r` with shape `[I, J, ..., L, num_rows, num_cols]`.\n\n The second innermost dimension of `diagonal` has double meaning. When `k` is\n scalar or `k[0] == k[1]`, `M` is part of the batch size [I, J, ..., M], and\n the output tensor is:\n\n ```\n output[i, j, ..., l, m, n]\n = diagonal[i, j, ..., l, n-max(d_upper, 0)] ; if n - m == d_upper\n padding_value ; otherwise\n ```\n\n Otherwise, `M` is treated as the number of diagonals for the matrix in the\n same batch (`M = k[1]-k[0]+1`), and the output tensor is:\n\n ```\n output[i, j, ..., l, m, n]\n = diagonal[i, j, ..., l, diag_index, index_in_diag] ; if k[0] <= d <= k[1]\n padding_value ; otherwise\n ```\n where `d = n - m`, `diag_index = k[1] - d`, and\n `index_in_diag = n - max(d, 0) + offset`.\n\n `offset` is zero except when the alignment of the diagonal is to the right.\n ```\n offset = max_diag_len - diag_len(d) ; if (`align` in {RIGHT_LEFT, RIGHT_RIGHT}\n and `d >= 0`) or\n (`align` in {LEFT_RIGHT, RIGHT_RIGHT}\n and `d <= 0`)\n 0 ; otherwise\n ```\n where `diag_len(d) = min(cols - max(d, 0), rows + min(d, 0))`.\n\n For example:\n\n ```\n # The main diagonal.\n diagonal = np.array([[1, 2, 3, 4], # Input shape: (2, 4)\n [5, 6, 7, 8]])\n tf.matrix_diag(diagonal) ==> [[[1, 0, 0, 0], # Output shape: (2, 4, 4)\n [0, 2, 0, 0],\n [0, 0, 3, 0],\n [0, 0, 0, 4]],\n [[5, 0, 0, 0],\n [0, 6, 0, 0],\n [0, 0, 7, 0],\n [0, 0, 0, 8]]]\n\n # A superdiagonal (per batch).\n diagonal = np.array([[1, 2, 3], # Input shape: (2, 3)\n [4, 5, 6]])\n tf.matrix_diag(diagonal, k = 1)\n ==> [[[0, 1, 0, 0], # Output shape: (2, 4, 4)\n [0, 0, 2, 0],\n [0, 0, 0, 3],\n [0, 0, 0, 0]],\n [[0, 4, 0, 0],\n [0, 0, 5, 0],\n [0, 0, 0, 6],\n [0, 0, 0, 0]]]\n\n # A tridiagonal band (per batch).\n diagonals = np.array([[[8, 9, 0], # Input shape: (2, 2, 3)\n [1, 2, 3],\n [0, 4, 5]],\n [[2, 3, 0],\n [6, 7, 9],\n [0, 9, 1]]])\n tf.matrix_diag(diagonals, k = (-1, 1))\n ==> [[[1, 8, 0], # Output shape: (2, 3, 3)\n [4, 2, 9],\n [0, 5, 3]],\n [[6, 2, 0],\n [9, 7, 3],\n [0, 1, 9]]]\n\n # RIGHT_LEFT alignment.\n diagonals = np.array([[[0, 8, 9], # Input shape: (2, 2, 3)\n [1, 2, 3],\n [4, 5, 0]],\n [[0, 2, 3],\n [6, 7, 9],\n [9, 1, 0]]])\n tf.matrix_diag(diagonals, k = (-1, 1), align=\"RIGHT_LEFT\")\n ==> [[[1, 8, 0], # Output shape: (2, 3, 3)\n [4, 2, 9],\n [0, 5, 3]],\n [[6, 2, 0],\n [9, 7, 3],\n [0, 1, 9]]]\n\n # Rectangular matrix.\n diagonal = np.array([1, 2]) # Input shape: (2)\n tf.matrix_diag(diagonal, k = -1, num_rows = 3, num_cols = 4)\n ==> [[0, 0, 0, 0], # Output shape: (3, 4)\n [1, 0, 0, 0],\n [0, 2, 0, 0]]\n\n # Rectangular matrix with inferred num_cols and padding_value = 9.\n tf.matrix_diag(diagonal, k = -1, num_rows = 3, padding_value = 9)\n ==> [[9, 9], # Output shape: (3, 2)\n [1, 9],\n [9, 2]]\n ```\n\n Args:\n diagonal: A `Tensor` with `rank k >= 1`.\n name: A name for the operation (optional).\n k: Diagonal offset(s). Positive value means superdiagonal, 0 refers to the\n main diagonal, and negative value means subdiagonals. `k` can be a single\n integer (for a single diagonal) or a pair of integers specifying the low\n and high ends of a matrix band. `k[0]` must not be larger than `k[1]`.\n num_rows: The number of rows of the output matrix. If it is not provided,\n the op assumes the output matrix is a square matrix and infers the matrix\n size from `d_lower`, `d_upper`, and the innermost dimension of `diagonal`.\n num_cols: The number of columns of the output matrix. If it is not provided,\n the op assumes the output matrix is a square matrix and infers the matrix\n size from `d_lower`, `d_upper`, and the innermost dimension of `diagonal`.\n padding_value: The value to fill the area outside the specified diagonal\n band with. Default is 0.\n align: Some diagonals are shorter than `max_diag_len` and need to be padded.\n `align` is a string specifying how superdiagonals and subdiagonals should\n be aligned, respectively. There are four possible alignments: \"RIGHT_LEFT\"\n (default), \"LEFT_RIGHT\", \"LEFT_LEFT\", and \"RIGHT_RIGHT\". \"RIGHT_LEFT\"\n aligns superdiagonals to the right (left-pads the row) and subdiagonals to\n the left (right-pads the row). It is the packing format LAPACK uses.\n cuSPARSE uses \"LEFT_RIGHT\", which is the opposite alignment.\n\n Returns:\n A Tensor. Has the same type as `diagonal`.\n \"\"\"\n # Special case to sidestep the tf.constant conversion error:\n # TypeError: Expected bool, got 0 of type 'int' instead.\n if hasattr(diagonal, \"dtype\") and diagonal.dtype == \"bool\":\n padding_value = bool(padding_value)\n\n return gen_array_ops.matrix_diag_v3(\n diagonal=diagonal,\n k=k,\n num_rows=num_rows,\n num_cols=num_cols,\n padding_value=padding_value,\n align=align,\n name=name)\n\n\n@tf_export(\"linalg.diag_part\", v1=[\"linalg.diag_part\", \"matrix_diag_part\"])\[email protected]_endpoints(\"matrix_diag_part\")\[email protected]_dispatch_support\ndef matrix_diag_part(\n input, # pylint:disable=redefined-builtin\n name=\"diag_part\",\n k=0,\n padding_value=0,\n align=\"RIGHT_LEFT\"):\n \"\"\"Returns the batched diagonal part of a batched tensor.\n\n Returns a tensor with the `k[0]`-th to `k[1]`-th diagonals of the batched\n `input`.\n\n Assume `input` has `r` dimensions `[I, J, ..., L, M, N]`.\n Let `max_diag_len` be the maximum length among all diagonals to be extracted,\n `max_diag_len = min(M + min(k[1], 0), N + min(-k[0], 0))`\n Let `num_diags` be the number of diagonals to extract,\n `num_diags = k[1] - k[0] + 1`.\n\n If `num_diags == 1`, the output tensor is of rank `r - 1` with shape\n `[I, J, ..., L, max_diag_len]` and values:\n\n ```\n diagonal[i, j, ..., l, n]\n = input[i, j, ..., l, n+y, n+x] ; if 0 <= n+y < M and 0 <= n+x < N,\n padding_value ; otherwise.\n ```\n where `y = max(-k[1], 0)`, `x = max(k[1], 0)`.\n\n Otherwise, the output tensor has rank `r` with dimensions\n `[I, J, ..., L, num_diags, max_diag_len]` with values:\n\n ```\n diagonal[i, j, ..., l, m, n]\n = input[i, j, ..., l, n+y, n+x] ; if 0 <= n+y < M and 0 <= n+x < N,\n padding_value ; otherwise.\n ```\n where `d = k[1] - m`, `y = max(-d, 0) - offset`, and `x = max(d, 0) - offset`.\n\n `offset` is zero except when the alignment of the diagonal is to the right.\n ```\n offset = max_diag_len - diag_len(d) ; if (`align` in {RIGHT_LEFT, RIGHT_RIGHT}\n and `d >= 0`) or\n (`align` in {LEFT_RIGHT, RIGHT_RIGHT}\n and `d <= 0`)\n 0 ; otherwise\n ```\n where `diag_len(d) = min(cols - max(d, 0), rows + min(d, 0))`.\n\n The input must be at least a matrix.\n\n For example:\n\n ```\n input = np.array([[[1, 2, 3, 4], # Input shape: (2, 3, 4)\n [5, 6, 7, 8],\n [9, 8, 7, 6]],\n [[5, 4, 3, 2],\n [1, 2, 3, 4],\n [5, 6, 7, 8]]])\n\n # A main diagonal from each batch.\n tf.linalg.diag_part(input) ==> [[1, 6, 7], # Output shape: (2, 3)\n [5, 2, 7]]\n\n # A superdiagonal from each batch.\n tf.linalg.diag_part(input, k = 1)\n ==> [[2, 7, 6], # Output shape: (2, 3)\n [4, 3, 8]]\n\n # A band from each batch.\n tf.linalg.diag_part(input, k = (-1, 2))\n ==> [[[3, 8, 0], # Output shape: (2, 4, 3)\n [2, 7, 6],\n [1, 6, 7],\n [0, 5, 8]],\n [[3, 4, 0],\n [4, 3, 8],\n [5, 2, 7],\n [0, 1, 6]]]\n\n # RIGHT_LEFT alignment.\n tf.linalg.diag_part(input, k = (-1, 2), align=\"RIGHT_LEFT\")\n ==> [[[0, 3, 8], # Output shape: (2, 4, 3)\n [2, 7, 6],\n [1, 6, 7],\n [5, 8, 0]],\n [[0, 3, 4],\n [4, 3, 8],\n [5, 2, 7],\n [1, 6, 0]]]\n\n # max_diag_len can be shorter than the main diagonal.\n tf.linalg.diag_part(input, k = (-2, -1))\n ==> [[[5, 8],\n [0, 9]],\n [[1, 6],\n [0, 5]]]\n\n # padding_value = 9\n tf.linalg.diag_part(input, k = (1, 3), padding_value = 9)\n ==> [[[4, 9, 9], # Output shape: (2, 3, 3)\n [3, 8, 9],\n [2, 7, 6]],\n [[2, 9, 9],\n [3, 4, 9],\n [4, 3, 8]]]\n\n ```\n\n Args:\n input: A `Tensor` with `rank k >= 2`.\n name: A name for the operation (optional).\n k: Diagonal offset(s). Positive value means superdiagonal, 0 refers to the\n main diagonal, and negative value means subdiagonals. `k` can be a single\n integer (for a single diagonal) or a pair of integers specifying the low\n and high ends of a matrix band. `k[0]` must not be larger than `k[1]`.\n padding_value: The value to fill the area outside the specified diagonal\n band with. Default is 0.\n align: Some diagonals are shorter than `max_diag_len` and need to be padded.\n `align` is a string specifying how superdiagonals and subdiagonals should\n be aligned, respectively. There are four possible alignments: \"RIGHT_LEFT\"\n (default), \"LEFT_RIGHT\", \"LEFT_LEFT\", and \"RIGHT_RIGHT\". \"RIGHT_LEFT\"\n aligns superdiagonals to the right (left-pads the row) and subdiagonals to\n the left (right-pads the row). It is the packing format LAPACK uses.\n cuSPARSE uses \"LEFT_RIGHT\", which is the opposite alignment.\n\n Returns:\n A Tensor containing diagonals of `input`. Has the same type as `input`.\n \"\"\"\n # Special case to sidestep the tf.constant conversion error:\n # TypeError: Expected bool, got 0 of type 'int' instead.\n if hasattr(input, \"dtype\") and input.dtype == \"bool\":\n padding_value = bool(padding_value)\n\n return gen_array_ops.matrix_diag_part_v3(\n input=input, k=k, padding_value=padding_value, align=align, name=name)\n\n\n@tf_export(\"linalg.set_diag\", v1=[\"linalg.set_diag\", \"matrix_set_diag\"])\[email protected]_endpoints(\"matrix_set_diag\")\ndef matrix_set_diag(\n input, # pylint:disable=redefined-builtin\n diagonal,\n name=\"set_diag\",\n k=0,\n align=\"RIGHT_LEFT\"):\n \"\"\"Returns a batched matrix tensor with new batched diagonal values.\n\n Given `input` and `diagonal`, this operation returns a tensor with the\n same shape and values as `input`, except for the specified diagonals of the\n innermost matrices. These will be overwritten by the values in `diagonal`.\n\n `input` has `r+1` dimensions `[I, J, ..., L, M, N]`. When `k` is scalar or\n `k[0] == k[1]`, `diagonal` has `r` dimensions `[I, J, ..., L, max_diag_len]`.\n Otherwise, it has `r+1` dimensions `[I, J, ..., L, num_diags, max_diag_len]`.\n `num_diags` is the number of diagonals, `num_diags = k[1] - k[0] + 1`.\n `max_diag_len` is the longest diagonal in the range `[k[0], k[1]]`,\n `max_diag_len = min(M + min(k[1], 0), N + min(-k[0], 0))`\n\n The output is a tensor of rank `k+1` with dimensions `[I, J, ..., L, M, N]`.\n If `k` is scalar or `k[0] == k[1]`:\n\n ```\n output[i, j, ..., l, m, n]\n = diagonal[i, j, ..., l, n-max(k[1], 0)] ; if n - m == k[1]\n input[i, j, ..., l, m, n] ; otherwise\n ```\n\n Otherwise,\n\n ```\n output[i, j, ..., l, m, n]\n = diagonal[i, j, ..., l, diag_index, index_in_diag] ; if k[0] <= d <= k[1]\n input[i, j, ..., l, m, n] ; otherwise\n ```\n where `d = n - m`, `diag_index = k[1] - d`, and\n `index_in_diag = n - max(d, 0) + offset`.\n\n `offset` is zero except when the alignment of the diagonal is to the right.\n ```\n offset = max_diag_len - diag_len(d) ; if (`align` in {RIGHT_LEFT, RIGHT_RIGHT}\n and `d >= 0`) or\n (`align` in {LEFT_RIGHT, RIGHT_RIGHT}\n and `d <= 0`)\n 0 ; otherwise\n ```\n where `diag_len(d) = min(cols - max(d, 0), rows + min(d, 0))`.\n\n For example:\n\n ```\n # The main diagonal.\n input = np.array([[[7, 7, 7, 7], # Input shape: (2, 3, 4)\n [7, 7, 7, 7],\n [7, 7, 7, 7]],\n [[7, 7, 7, 7],\n [7, 7, 7, 7],\n [7, 7, 7, 7]]])\n diagonal = np.array([[1, 2, 3], # Diagonal shape: (2, 3)\n [4, 5, 6]])\n tf.matrix_set_diag(input, diagonal)\n ==> [[[1, 7, 7, 7], # Output shape: (2, 3, 4)\n [7, 2, 7, 7],\n [7, 7, 3, 7]],\n [[4, 7, 7, 7],\n [7, 5, 7, 7],\n [7, 7, 6, 7]]]\n\n # A superdiagonal (per batch).\n tf.matrix_set_diag(input, diagonal, k = 1)\n ==> [[[7, 1, 7, 7], # Output shape: (2, 3, 4)\n [7, 7, 2, 7],\n [7, 7, 7, 3]],\n [[7, 4, 7, 7],\n [7, 7, 5, 7],\n [7, 7, 7, 6]]]\n\n # A band of diagonals.\n diagonals = np.array([[[9, 1, 0], # Diagonal shape: (2, 4, 3)\n [6, 5, 8],\n [1, 2, 3],\n [0, 4, 5]],\n [[1, 2, 0],\n [5, 6, 4],\n [6, 1, 2],\n [0, 3, 4]]])\n tf.matrix_set_diag(input, diagonals, k = (-1, 2))\n ==> [[[1, 6, 9, 7], # Output shape: (2, 3, 4)\n [4, 2, 5, 1],\n [7, 5, 3, 8]],\n [[6, 5, 1, 7],\n [3, 1, 6, 2],\n [7, 4, 2, 4]]]\n\n # RIGHT_LEFT alignment.\n diagonals = np.array([[[0, 9, 1], # Diagonal shape: (2, 4, 3)\n [6, 5, 8],\n [1, 2, 3],\n [4, 5, 0]],\n [[0, 1, 2],\n [5, 6, 4],\n [6, 1, 2],\n [3, 4, 0]]])\n tf.matrix_set_diag(input, diagonals, k = (-1, 2), align=\"RIGHT_LEFT\")\n ==> [[[1, 6, 9, 7], # Output shape: (2, 3, 4)\n [4, 2, 5, 1],\n [7, 5, 3, 8]],\n [[6, 5, 1, 7],\n [3, 1, 6, 2],\n [7, 4, 2, 4]]]\n\n ```\n\n Args:\n input: A `Tensor` with rank `k + 1`, where `k >= 1`.\n diagonal: A `Tensor` with rank `k`, when `d_lower == d_upper`, or `k + 1`,\n otherwise. `k >= 1`.\n name: A name for the operation (optional).\n k: Diagonal offset(s). Positive value means superdiagonal, 0 refers to the\n main diagonal, and negative value means subdiagonals. `k` can be a single\n integer (for a single diagonal) or a pair of integers specifying the low\n and high ends of a matrix band. `k[0]` must not be larger than `k[1]`.\n align: Some diagonals are shorter than `max_diag_len` and need to be padded.\n `align` is a string specifying how superdiagonals and subdiagonals should\n be aligned, respectively. There are four possible alignments: \"RIGHT_LEFT\"\n (default), \"LEFT_RIGHT\", \"LEFT_LEFT\", and \"RIGHT_RIGHT\". \"RIGHT_LEFT\"\n aligns superdiagonals to the right (left-pads the row) and subdiagonals to\n the left (right-pads the row). It is the packing format LAPACK uses.\n cuSPARSE uses \"LEFT_RIGHT\", which is the opposite alignment.\n \"\"\"\n return gen_array_ops.matrix_set_diag_v3(\n input=input, diagonal=diagonal, k=k, align=align, name=name)\n\n\n# pylint: enable=invalid-name\n\n\ndef _constant_if_small(value, shape, dtype, name):\n try:\n if np.prod(shape) < 1000:\n return constant(value, shape=shape, dtype=dtype, name=name)\n except TypeError:\n # Happens when shape is a Tensor, list with Tensor elements, etc.\n pass\n return None\n\n\ndef _tag_zeros_tensor(fun):\n \"\"\" Tags the result of function by setting _is_zeros_tensor attribute.\n\n This is useful to compute Hessians of fused ops such as cross_entropy.\n \"\"\"\n\n def wrapped(*args, **kwargs):\n tensor = fun(*args, **kwargs)\n tensor._is_zeros_tensor = True\n return tensor\n\n return tf_decorator.make_decorator(fun, wrapped)\n\n\n@tf_export(\"zeros\")\n@_tag_zeros_tensor\ndef zeros(shape, dtype=dtypes.float32, name=None):\n \"\"\"Creates a tensor with all elements set to zero.\n\n See also `tf.zeros_like`, `tf.ones`, `tf.fill`, `tf.eye`.\n\n This operation returns a tensor of type `dtype` with shape `shape` and\n all elements set to zero.\n\n >>> tf.zeros([3, 4], tf.int32)\n <tf.Tensor: shape=(3, 4), dtype=int32, numpy=\n array([[0, 0, 0, 0],\n [0, 0, 0, 0],\n [0, 0, 0, 0]], dtype=int32)>\n\n Args:\n shape: A `list` of integers, a `tuple` of integers, or\n a 1-D `Tensor` of type `int32`.\n dtype: The DType of an element in the resulting `Tensor`.\n name: Optional string. A name for the operation.\n\n Returns:\n A `Tensor` with all elements set to zero.\n \"\"\"\n dtype = dtypes.as_dtype(dtype).base_dtype\n with ops.name_scope(name, \"zeros\", [shape]) as name:\n if dtype == dtypes.bool:\n zero = False\n elif dtype == dtypes.string:\n zero = \"\"\n else:\n zero = 0\n\n if not isinstance(shape, ops.Tensor):\n try:\n if not context.executing_eagerly():\n # Create a constant if it won't be very big. Otherwise create a fill\n # op to prevent serialized GraphDefs from becoming too large.\n output = _constant_if_small(zero, shape, dtype, name)\n if output is not None:\n return output\n\n # Go through tensor shapes to get int64-if-needed semantics\n shape = constant_op._tensor_shape_tensor_conversion_function(\n tensor_shape.TensorShape(shape))\n except (TypeError, ValueError):\n # Happens when shape is a list with tensor elements\n shape = ops.convert_to_tensor(shape, dtype=dtypes.int32)\n if not shape._shape_tuple():\n shape = reshape(shape, [-1]) # Ensure it's a vector\n output = fill(shape, constant(zero, dtype=dtype), name=name)\n assert output.dtype.base_dtype == dtype\n return output\n\n\n@tf_export(v1=[\"zeros_like\"])\[email protected]_dispatch_support\ndef zeros_like(tensor, dtype=None, name=None, optimize=True):\n \"\"\"Creates a tensor with all elements set to zero.\n\n See also `tf.zeros`.\n\n Given a single tensor (`tensor`), this operation returns a tensor of the\n same type and shape as `tensor` with all elements set to zero. Optionally,\n you can use `dtype` to specify a new type for the returned tensor.\n\n Examples:\n\n >>> tensor = tf.constant([[1, 2, 3], [4, 5, 6]])\n >>> tf.zeros_like(tensor)\n <tf.Tensor: shape=(2, 3), dtype=int32, numpy=\n array([[0, 0, 0],\n [0, 0, 0]], dtype=int32)>\n\n >>> tf.zeros_like(tensor, dtype=tf.float32)\n <tf.Tensor: shape=(2, 3), dtype=float32, numpy=\n array([[0., 0., 0.],\n [0., 0., 0.]], dtype=float32)>\n\n Args:\n tensor: A `Tensor`.\n dtype: A type for the returned `Tensor`. Must be `float16`, `float32`,\n `float64`, `int8`, `uint8`, `int16`, `uint16`, `int32`, `int64`,\n `complex64`, `complex128`, `bool` or `string`. (optional)\n name: A name for the operation (optional).\n optimize: if `True`, attempt to statically determine the shape of `tensor`\n and encode it as a constant. (optional, defaults to `True`)\n\n Returns:\n A `Tensor` with all elements set to zero.\n \"\"\"\n return zeros_like_impl(tensor, dtype, name, optimize)\n\n\n@tf_export(\"zeros_like\", v1=[])\[email protected]_dispatch_support\ndef zeros_like_v2(\n input, # pylint: disable=redefined-builtin\n dtype=None,\n name=None):\n \"\"\"Creates a tensor with all elements set to zero.\n\n See also `tf.zeros`.\n\n Given a single tensor or array-like object (`input`), this operation returns\n a tensor of the same type and shape as `input` with all elements set to zero.\n Optionally, you can use `dtype` to specify a new type for the returned tensor.\n\n Examples:\n\n >>> tensor = tf.constant([[1, 2, 3], [4, 5, 6]])\n >>> tf.zeros_like(tensor)\n <tf.Tensor: shape=(2, 3), dtype=int32, numpy=\n array([[0, 0, 0],\n [0, 0, 0]], dtype=int32)>\n\n >>> tf.zeros_like(tensor, dtype=tf.float32)\n <tf.Tensor: shape=(2, 3), dtype=float32, numpy=\n array([[0., 0., 0.],\n [0., 0., 0.]], dtype=float32)>\n\n >>> tf.zeros_like([[1, 2, 3], [4, 5, 6]])\n <tf.Tensor: shape=(2, 3), dtype=int32, numpy=\n array([[0, 0, 0],\n [0, 0, 0]], dtype=int32)>\n\n Args:\n input: A `Tensor` or array-like object.\n dtype: A type for the returned `Tensor`. Must be `float16`, `float32`,\n `float64`, `int8`, `uint8`, `int16`, `uint16`, `int32`, `int64`,\n `complex64`, `complex128`, `bool` or `string` (optional).\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` with all elements set to zero.\n \"\"\"\n return zeros_like_impl(input, dtype, name, optimize=True)\n\n\n@_tag_zeros_tensor\ndef zeros_like_impl(tensor, dtype, name, optimize=True):\n \"\"\"Internal implementation for the v1/v2 zeros_like API calls.\"\"\"\n with ops.name_scope(name, \"zeros_like\", [tensor]) as name:\n if not tensor_util.is_tensor(tensor):\n tensor = ops.convert_to_tensor(tensor, name=\"tensor\")\n tensor_shape = tensor.shape\n tensor_dtype = tensor.dtype\n\n if context.executing_eagerly():\n if dtype is not None and dtype != tensor_dtype:\n return zeros(\n shape_internal(tensor, optimize=optimize), dtype=dtype, name=name)\n return gen_array_ops.zeros_like(tensor, name=name)\n\n # For now, variant types must be created via zeros_like; as we need to\n # pass the input variant object to the proper zeros callback.\n\n if (optimize and tensor_shape.is_fully_defined() and\n tensor_dtype != dtypes.variant):\n # We can produce a zeros tensor independent of the value of 'tensor',\n # since the shape is known statically.\n return zeros(tensor_shape, dtype=dtype or tensor_dtype, name=name)\n\n if dtype is not None and dtype != tensor_dtype and dtype != dtypes.variant:\n return zeros(\n shape_internal(tensor, optimize=optimize), dtype=dtype, name=name)\n else:\n return gen_array_ops.zeros_like(tensor, name=name)\n\n\n@tf_export(v1=[\"ones_like\"])\[email protected]_dispatch_support\ndef ones_like(tensor, dtype=None, name=None, optimize=True):\n \"\"\"Creates a tensor with all elements set to 1.\n\n See also `tf.ones`.\n\n Given a single tensor (`tensor`), this operation returns a tensor of the same\n type and shape as `tensor` with all elements set to 1. Optionally, you can\n specify a new type (`dtype`) for the returned tensor.\n\n For example:\n\n ```python\n tensor = tf.constant([[1, 2, 3], [4, 5, 6]])\n tf.ones_like(tensor) # [[1, 1, 1], [1, 1, 1]]\n ```\n\n Args:\n tensor: A `Tensor`.\n dtype: A type for the returned `Tensor`. Must be `float32`, `float64`,\n `int8`, `uint8`, `int16`, `uint16`, `int32`, `int64`, `complex64`,\n `complex128` or `bool`.\n name: A name for the operation (optional).\n optimize: if true, attempt to statically determine the shape of 'tensor' and\n encode it as a constant.\n\n Returns:\n A `Tensor` with all elements set to 1.\n \"\"\"\n return ones_like_impl(tensor, dtype, name, optimize)\n\n\n@tf_export(\"ones_like\", v1=[])\[email protected]_dispatch_support\ndef ones_like_v2(\n input, # pylint: disable=redefined-builtin\n dtype=None,\n name=None):\n \"\"\"Creates a tensor of all ones that has the same shape as the input.\n\n See also `tf.ones`.\n\n Given a single tensor (`tensor`), this operation returns a tensor of the\n same type and shape as `tensor` with all elements set to 1. Optionally,\n you can use `dtype` to specify a new type for the returned tensor.\n\n For example:\n\n >>> tensor = tf.constant([[1, 2, 3], [4, 5, 6]])\n >>> tf.ones_like(tensor)\n <tf.Tensor: shape=(2, 3), dtype=int32, numpy=\n array([[1, 1, 1],\n [1, 1, 1]], dtype=int32)>\n\n Args:\n input: A `Tensor`.\n dtype: A type for the returned `Tensor`. Must be `float16`, `float32`,\n `float64`, `int8`, `uint8`, `int16`, `uint16`, `int32`, `int64`,\n `complex64`, `complex128`, `bool` or `string`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` with all elements set to one.\n \"\"\"\n return ones_like_impl(input, dtype, name, optimize=True)\n\n\ndef ones_like_impl(tensor, dtype, name, optimize=True):\n \"\"\"Internal implementation for the v1/v2 ones_like API calls.\"\"\"\n with ops.name_scope(name, \"ones_like\", [tensor]) as name:\n tensor = ops.convert_to_tensor(tensor, name=\"tensor\")\n ones_shape = shape_internal(tensor, optimize=optimize)\n if dtype is None:\n dtype = tensor.dtype\n ret = ones(ones_shape, dtype=dtype, name=name)\n if not context.executing_eagerly():\n ret.set_shape(tensor.get_shape())\n return ret\n\n\n@tf_export(\"ones\")\ndef ones(shape, dtype=dtypes.float32, name=None):\n \"\"\"Creates a tensor with all elements set to one (1).\n\n See also `tf.ones_like`, `tf.zeros`, `tf.fill`, `tf.eye`.\n\n This operation returns a tensor of type `dtype` with shape `shape` and\n all elements set to one.\n\n >>> tf.ones([3, 4], tf.int32)\n <tf.Tensor: shape=(3, 4), dtype=int32, numpy=\n array([[1, 1, 1, 1],\n [1, 1, 1, 1],\n [1, 1, 1, 1]], dtype=int32)>\n\n Args:\n shape: A `list` of integers, a `tuple` of integers, or\n a 1-D `Tensor` of type `int32`.\n dtype: Optional DType of an element in the resulting `Tensor`. Default is\n `tf.float32`.\n name: Optional string. A name for the operation.\n\n Returns:\n A `Tensor` with all elements set to one (1).\n \"\"\"\n dtype = dtypes.as_dtype(dtype).base_dtype\n with ops.name_scope(name, \"ones\", [shape]) as name:\n one = True if dtype == dtypes.bool else 1\n if not isinstance(shape, ops.Tensor):\n try:\n if not context.executing_eagerly():\n # Create a constant if it won't be very big. Otherwise create a fill\n # op to prevent serialized GraphDefs from becoming too large.\n output = _constant_if_small(one, shape, dtype, name)\n if output is not None:\n return output\n\n # Go through tensor shapes to get int64-if-needed semantics\n shape = constant_op._tensor_shape_tensor_conversion_function(\n tensor_shape.TensorShape(shape))\n except (TypeError, ValueError):\n # Happens when shape is a list with tensor elements\n shape = ops.convert_to_tensor(shape, dtype=dtypes.int32)\n if not shape._shape_tuple():\n shape = reshape(shape, [-1]) # Ensure it's a vector\n output = fill(shape, constant(one, dtype=dtype), name=name)\n assert output.dtype.base_dtype == dtype\n return output\n\n\n@tf_export(v1=[\"placeholder\"])\ndef placeholder(dtype, shape=None, name=None):\n \"\"\"Inserts a placeholder for a tensor that will be always fed.\n\n **Important**: This tensor will produce an error if evaluated. Its value must\n be fed using the `feed_dict` optional argument to `Session.run()`,\n `Tensor.eval()`, or `Operation.run()`.\n\n For example:\n\n ```python\n x = tf.compat.v1.placeholder(tf.float32, shape=(1024, 1024))\n y = tf.matmul(x, x)\n\n with tf.compat.v1.Session() as sess:\n print(sess.run(y)) # ERROR: will fail because x was not fed.\n\n rand_array = np.random.rand(1024, 1024)\n print(sess.run(y, feed_dict={x: rand_array})) # Will succeed.\n ```\n\n @compatibility(eager)\n Placeholders are not compatible with eager execution.\n @end_compatibility\n\n Args:\n dtype: The type of elements in the tensor to be fed.\n shape: The shape of the tensor to be fed (optional). If the shape is not\n specified, you can feed a tensor of any shape.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` that may be used as a handle for feeding a value, but not\n evaluated directly.\n\n Raises:\n RuntimeError: if eager execution is enabled\n \"\"\"\n if context.executing_eagerly():\n raise RuntimeError(\"tf.placeholder() is not compatible with \"\n \"eager execution.\")\n\n return gen_array_ops.placeholder(dtype=dtype, shape=shape, name=name)\n\n\n@tf_export(v1=[\"placeholder_with_default\"])\ndef placeholder_with_default(input, shape, name=None): # pylint: disable=redefined-builtin\n \"\"\"A placeholder op that passes through `input` when its output is not fed.\n\n Args:\n input: A `Tensor`. The default value to produce when output is not fed.\n shape: A `tf.TensorShape` or list of `int`s. The (possibly partial) shape of\n the tensor.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor`. Has the same type as `input`.\n \"\"\"\n return gen_array_ops.placeholder_with_default(input, shape, name)\n\n\n@tf_export(v1=[\"sparse.placeholder\", \"sparse_placeholder\"])\[email protected]_endpoints(\"sparse_placeholder\")\ndef sparse_placeholder(dtype, shape=None, name=None):\n \"\"\"Inserts a placeholder for a sparse tensor that will be always fed.\n\n **Important**: This sparse tensor will produce an error if evaluated.\n Its value must be fed using the `feed_dict` optional argument to\n `Session.run()`, `Tensor.eval()`, or `Operation.run()`.\n\n For example:\n\n ```python\n x = tf.compat.v1.sparse.placeholder(tf.float32)\n y = tf.sparse.reduce_sum(x)\n\n with tf.compat.v1.Session() as sess:\n print(sess.run(y)) # ERROR: will fail because x was not fed.\n\n indices = np.array([[3, 2, 0], [4, 5, 1]], dtype=np.int64)\n values = np.array([1.0, 2.0], dtype=np.float32)\n shape = np.array([7, 9, 2], dtype=np.int64)\n print(sess.run(y, feed_dict={\n x: tf.compat.v1.SparseTensorValue(indices, values, shape)})) # Will\n succeed.\n print(sess.run(y, feed_dict={\n x: (indices, values, shape)})) # Will succeed.\n\n sp = tf.sparse.SparseTensor(indices=indices, values=values,\n dense_shape=shape)\n sp_value = sp.eval(session=sess)\n print(sess.run(y, feed_dict={x: sp_value})) # Will succeed.\n ```\n\n @compatibility{eager} Placeholders are not compatible with eager execution.\n\n Args:\n dtype: The type of `values` elements in the tensor to be fed.\n shape: The shape of the tensor to be fed (optional). If the shape is not\n specified, you can feed a sparse tensor of any shape.\n name: A name for prefixing the operations (optional).\n\n Returns:\n A `SparseTensor` that may be used as a handle for feeding a value, but not\n evaluated directly.\n\n Raises:\n RuntimeError: if eager execution is enabled\n \"\"\"\n if context.executing_eagerly():\n raise RuntimeError(\"`sparse_placeholder` is not compatible with \"\n \"eager execution.\")\n\n shape_name = (name + \"/shape\") if name is not None else None\n default_shape_name = (name + \"/shape_default\") if name is not None else None\n if shape is None:\n rank = None\n dense_shape = placeholder(dtypes.int64, shape=[rank], name=shape_name)\n dense_shape_default = tensor_util.constant_value_as_shape(dense_shape)\n else:\n if isinstance(shape, ops.Tensor):\n rank = shape.get_shape()[0]\n dense_shape_default = tensor_util.constant_value_as_shape(shape)\n else:\n rank = len(shape)\n # determine the shape, to override the `.shape` property of the\n # `SparseTensor`\n dense_shape_default = tensor_shape.TensorShape(\n tuple(None if dim == -1 else dim for dim in shape))\n shape = tuple(-1 if dim is None else dim for dim in shape)\n shape = ops.convert_to_tensor(\n shape, dtype=dtypes.int64, name=default_shape_name)\n\n # `dense_shape` needs to be feedable (for users that treat this as an\n # actual placeholder). `constant_value_as_shape` sets constants to\n # not-feedable. placeholder_with_default works, but blocks `SparseTensor`\n # from reading the default value back out.\n dense_shape = placeholder_with_default(\n shape, shape=shape.shape, name=shape_name)\n\n result = sparse_tensor.SparseTensor(\n values=placeholder(\n dtype,\n shape=[None],\n name=(name + \"/values\") if name is not None else None),\n indices=placeholder(\n dtypes.int64,\n shape=[None, rank],\n name=(name + \"/indices\") if name is not None else None),\n dense_shape=dense_shape)\n\n # Now the SparseTensor.shape is a list of `None`s, since it couldn't read the\n # default shape out of the placeholder. Override that\n # shape to be the value determined here, so partial shapes can be\n # propagated.\n result._dense_shape_default = dense_shape_default\n return result\n\n# pylint: enable=redefined-outer-name\n\n\n@tf_export(\"pad\", v1=[])\ndef pad_v2(tensor, paddings, mode=\"CONSTANT\", constant_values=0, name=None):\n \"\"\"Pads a tensor.\n\n This operation pads a `tensor` according to the `paddings` you specify.\n `paddings` is an integer tensor with shape `[n, 2]`, where n is the rank of\n `tensor`. For each dimension D of `input`, `paddings[D, 0]` indicates how\n many values to add before the contents of `tensor` in that dimension, and\n `paddings[D, 1]` indicates how many values to add after the contents of\n `tensor` in that dimension. If `mode` is \"REFLECT\" then both `paddings[D, 0]`\n and `paddings[D, 1]` must be no greater than `tensor.dim_size(D) - 1`. If\n `mode` is \"SYMMETRIC\" then both `paddings[D, 0]` and `paddings[D, 1]` must be\n no greater than `tensor.dim_size(D)`.\n\n The padded size of each dimension D of the output is:\n\n `paddings[D, 0] + tensor.dim_size(D) + paddings[D, 1]`\n\n For example:\n\n ```python\n t = tf.constant([[1, 2, 3], [4, 5, 6]])\n paddings = tf.constant([[1, 1,], [2, 2]])\n # 'constant_values' is 0.\n # rank of 't' is 2.\n tf.pad(t, paddings, \"CONSTANT\") # [[0, 0, 0, 0, 0, 0, 0],\n # [0, 0, 1, 2, 3, 0, 0],\n # [0, 0, 4, 5, 6, 0, 0],\n # [0, 0, 0, 0, 0, 0, 0]]\n\n tf.pad(t, paddings, \"REFLECT\") # [[6, 5, 4, 5, 6, 5, 4],\n # [3, 2, 1, 2, 3, 2, 1],\n # [6, 5, 4, 5, 6, 5, 4],\n # [3, 2, 1, 2, 3, 2, 1]]\n\n tf.pad(t, paddings, \"SYMMETRIC\") # [[2, 1, 1, 2, 3, 3, 2],\n # [2, 1, 1, 2, 3, 3, 2],\n # [5, 4, 4, 5, 6, 6, 5],\n # [5, 4, 4, 5, 6, 6, 5]]\n ```\n\n Args:\n tensor: A `Tensor`.\n paddings: A `Tensor` of type `int32`.\n mode: One of \"CONSTANT\", \"REFLECT\", or \"SYMMETRIC\" (case-insensitive)\n constant_values: In \"CONSTANT\" mode, the scalar pad value to use. Must be\n same type as `tensor`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor`. Has the same type as `tensor`.\n\n Raises:\n ValueError: When mode is not one of \"CONSTANT\", \"REFLECT\", or \"SYMMETRIC\".\n \"\"\"\n return pad(tensor, paddings, mode, name, constant_values)\n\n\n@tf_export(v1=[\"pad\"])\ndef pad(tensor, paddings, mode=\"CONSTANT\", name=None, constant_values=0): # pylint: disable=invalid-name\n \"\"\"Pads a tensor.\n\n This operation pads a `tensor` according to the `paddings` you specify.\n `paddings` is an integer tensor with shape `[n, 2]`, where n is the rank of\n `tensor`. For each dimension D of `input`, `paddings[D, 0]` indicates how\n many values to add before the contents of `tensor` in that dimension, and\n `paddings[D, 1]` indicates how many values to add after the contents of\n `tensor` in that dimension. If `mode` is \"REFLECT\" then both `paddings[D, 0]`\n and `paddings[D, 1]` must be no greater than `tensor.dim_size(D) - 1`. If\n `mode` is \"SYMMETRIC\" then both `paddings[D, 0]` and `paddings[D, 1]` must be\n no greater than `tensor.dim_size(D)`.\n\n The padded size of each dimension D of the output is:\n\n `paddings[D, 0] + tensor.dim_size(D) + paddings[D, 1]`\n\n For example:\n\n ```python\n t = tf.constant([[1, 2, 3], [4, 5, 6]])\n paddings = tf.constant([[1, 1,], [2, 2]])\n # 'constant_values' is 0.\n # rank of 't' is 2.\n tf.pad(t, paddings, \"CONSTANT\") # [[0, 0, 0, 0, 0, 0, 0],\n # [0, 0, 1, 2, 3, 0, 0],\n # [0, 0, 4, 5, 6, 0, 0],\n # [0, 0, 0, 0, 0, 0, 0]]\n\n tf.pad(t, paddings, \"REFLECT\") # [[6, 5, 4, 5, 6, 5, 4],\n # [3, 2, 1, 2, 3, 2, 1],\n # [6, 5, 4, 5, 6, 5, 4],\n # [3, 2, 1, 2, 3, 2, 1]]\n\n tf.pad(t, paddings, \"SYMMETRIC\") # [[2, 1, 1, 2, 3, 3, 2],\n # [2, 1, 1, 2, 3, 3, 2],\n # [5, 4, 4, 5, 6, 6, 5],\n # [5, 4, 4, 5, 6, 6, 5]]\n ```\n\n Args:\n tensor: A `Tensor`.\n paddings: A `Tensor` of type `int32`.\n mode: One of \"CONSTANT\", \"REFLECT\", or \"SYMMETRIC\" (case-insensitive)\n name: A name for the operation (optional).\n constant_values: In \"CONSTANT\" mode, the scalar pad value to use. Must be\n same type as `tensor`.\n\n Returns:\n A `Tensor`. Has the same type as `tensor`.\n\n Raises:\n ValueError: When mode is not one of \"CONSTANT\", \"REFLECT\", or \"SYMMETRIC\".\n \"\"\"\n\n # Convert lower/mixed case to upper for NumPy compatibility\n # NumPy uses all lower-case modes.\n mode = mode.upper()\n if mode == \"CONSTANT\":\n # TODO(rjryan): Once the forward compatibility period (3 weeks) have passed\n # remove the \"Pad\" fallback here.\n if not tensor_util.is_tensor(constant_values) and constant_values == 0:\n result = gen_array_ops.pad(tensor, paddings, name=name)\n else:\n result = gen_array_ops.pad_v2(\n tensor, paddings, constant_values, name=name)\n elif mode == \"REFLECT\":\n result = gen_array_ops.mirror_pad(\n tensor, paddings, mode=\"REFLECT\", name=name)\n elif mode == \"SYMMETRIC\":\n result = gen_array_ops.mirror_pad(\n tensor, paddings, mode=\"SYMMETRIC\", name=name)\n else:\n raise ValueError(\"Unknown padding mode: %s\" % mode)\n\n # Restore shape information where possible.\n if not context.executing_eagerly():\n paddings_constant = _get_paddings_constant(paddings)\n input_shape = (\n tensor_shape.TensorShape(tensor.shape)\n if isinstance(tensor, ops.Tensor) else result.op.inputs[0].shape)\n if (input_shape.ndims is not None and\n not result.shape.is_fully_defined() and paddings_constant is not None):\n new_shape = []\n for padding, dim in zip(paddings_constant, input_shape.as_list()):\n if padding is None or dim is None or any((x is None for x in padding)):\n new_shape.append(None)\n else:\n new_shape.append(sum(padding) + dim)\n result.set_shape(new_shape)\n\n return result\n\n\ndef _get_paddings_constant(paddings):\n \"\"\"Helper to get the constant values of the paddings arg to pad().\n\n Used under V1 graph mode to facilitate computation of the shape of the output\n tensor of `pad()`.\n\n Args:\n paddings: The same paddings arg as passed to pad(). Can be a Tensor, or\n a nested list or tuple of Tensor and/or numbers.\n\n Returns:\n A nested list or numbers or `None`, in which `None` indicates unknown\n padding size.\n \"\"\"\n if isinstance(paddings, ops.Tensor):\n return tensor_util.constant_value(paddings, partial=True)\n elif isinstance(paddings, (list, tuple)):\n return [_get_paddings_constant(x) for x in paddings]\n else:\n return paddings\n\n\n@tf_export(\"meshgrid\")\ndef meshgrid(*args, **kwargs):\n \"\"\"Broadcasts parameters for evaluation on an N-D grid.\n\n Given N one-dimensional coordinate arrays `*args`, returns a list `outputs`\n of N-D coordinate arrays for evaluating expressions on an N-D grid.\n\n Notes:\n\n `meshgrid` supports cartesian ('xy') and matrix ('ij') indexing conventions.\n When the `indexing` argument is set to 'xy' (the default), the broadcasting\n instructions for the first two dimensions are swapped.\n\n Examples:\n\n Calling `X, Y = meshgrid(x, y)` with the tensors\n\n ```python\n x = [1, 2, 3]\n y = [4, 5, 6]\n X, Y = tf.meshgrid(x, y)\n # X = [[1, 2, 3],\n # [1, 2, 3],\n # [1, 2, 3]]\n # Y = [[4, 4, 4],\n # [5, 5, 5],\n # [6, 6, 6]]\n ```\n\n Args:\n *args: `Tensor`s with rank 1.\n **kwargs:\n - indexing: Either 'xy' or 'ij' (optional, default: 'xy').\n - name: A name for the operation (optional).\n\n Returns:\n outputs: A list of N `Tensor`s with rank N.\n\n Raises:\n TypeError: When no keyword arguments (kwargs) are passed.\n ValueError: When indexing keyword argument is not one of `xy` or `ij`.\n \"\"\"\n\n indexing = kwargs.pop(\"indexing\", \"xy\")\n name = kwargs.pop(\"name\", \"meshgrid\")\n if kwargs:\n key = list(kwargs.keys())[0]\n raise TypeError(\"'{}' is an invalid keyword argument \"\n \"for this function\".format(key))\n\n if indexing not in (\"xy\", \"ij\"):\n raise ValueError(\"indexing parameter must be either 'xy' or 'ij'\")\n\n with ops.name_scope(name, \"meshgrid\", args) as name:\n ndim = len(args)\n s0 = (1,) * ndim\n\n if not ndim:\n return []\n\n # Prepare reshape by inserting dimensions with size 1 where needed\n output = []\n for i, x in enumerate(args):\n output.append(reshape(stack(x), (s0[:i] + (-1,) + s0[i + 1::])))\n # Create parameters for broadcasting each tensor to the full size\n shapes = [size(x) for x in args]\n\n output_dtype = ops.convert_to_tensor(args[0]).dtype.base_dtype\n\n if indexing == \"xy\" and ndim > 1:\n output[0] = reshape(output[0], (1, -1) + (1,) * (ndim - 2))\n output[1] = reshape(output[1], (-1, 1) + (1,) * (ndim - 2))\n shapes[0], shapes[1] = shapes[1], shapes[0]\n\n # TODO(nolivia): improve performance with a broadcast\n mult_fact = ones(shapes, output_dtype)\n return [x * mult_fact for x in output]\n\n\nNEW_AXIS = -1\nSHRINK_AXIS = -2\n\n\n# PEP-8 naming\n# pylint: disable=invalid-name,redefined-outer-name\ndef _compute_size_of_strided_dim(shrink, spec, size):\n \"\"\"Computes the size of a single strided slice dimension.\"\"\"\n\n unknown = None # Document what None means here.\n use_full_range = None # Document other use of None.\n # if this is a shrink axis (i.e. a non-range index)\n # it either will produce an error or return 1\n if shrink:\n return 1\n if size is unknown or size.value is unknown:\n return unknown\n size = size.value\n stride = spec.step\n if stride is not unknown:\n if stride == 0:\n return unknown\n stride = spec.step\n valid_range = [0, size] if stride > 0 else [-1, size - 1]\n\n # PEP-8 naming\n # pylint: disable=invalid-name\n def canonical(x, c):\n if x is use_full_range:\n return valid_range[c] if stride > 0 else valid_range[(c + 1) & 1]\n else:\n x_fwd = size + x if x < 0 else x # make negative indices positive\n return max(valid_range[0], min(valid_range[1], x_fwd))\n\n begin = canonical(spec.start, 0)\n end = canonical(spec.stop, 1)\n interval_length = end - begin\n if interval_length == 0 or ((interval_length < 0) != (stride < 0)):\n return 0\n else:\n remainder = 1 if interval_length % stride != 0 else 0\n return interval_length // stride + remainder\n else:\n return unknown # unknown because stride is unknown\n\n\ndef _TileGradShape(op):\n \"\"\"Shape function for the TileGrad op.\"\"\"\n multiples_shape = op.inputs[1].get_shape().with_rank(1)\n input_shape = op.inputs[0].get_shape().with_rank(multiples_shape[0])\n # NOTE(mrry): Represent `multiples` as a `TensorShape` because (i)\n # it is a vector of non-negative integers, and (ii) doing so allows\n # us to handle partially-known multiples.\n multiples = tensor_util.constant_value_as_shape(op.inputs[1]).with_rank(\n input_shape.ndims)\n if multiples.ndims is None:\n return [tensor_shape.unknown_shape()]\n else:\n output_dims = []\n for dim, multiple in zip(input_shape.dims, multiples.dims):\n output_dims.append(dim // multiple)\n return [tensor_shape.TensorShape(output_dims)]\n\n\n@tf_export(\"edit_distance\")\ndef edit_distance(hypothesis, truth, normalize=True, name=\"edit_distance\"):\n \"\"\"Computes the Levenshtein distance between sequences.\n\n This operation takes variable-length sequences (`hypothesis` and `truth`),\n each provided as a `SparseTensor`, and computes the Levenshtein distance.\n You can normalize the edit distance by length of `truth` by setting\n `normalize` to true.\n\n For example, given the following input:\n\n ```python\n # 'hypothesis' is a tensor of shape `[2, 1]` with variable-length values:\n # (0,0) = [\"a\"]\n # (1,0) = [\"b\"]\n hypothesis = tf.sparse.SparseTensor(\n [[0, 0, 0],\n [1, 0, 0]],\n [\"a\", \"b\"],\n (2, 1, 1))\n\n # 'truth' is a tensor of shape `[2, 2]` with variable-length values:\n # (0,0) = []\n # (0,1) = [\"a\"]\n # (1,0) = [\"b\", \"c\"]\n # (1,1) = [\"a\"]\n truth = tf.sparse.SparseTensor(\n [[0, 1, 0],\n [1, 0, 0],\n [1, 0, 1],\n [1, 1, 0]],\n [\"a\", \"b\", \"c\", \"a\"],\n (2, 2, 2))\n\n normalize = True\n ```\n\n This operation would return the following:\n\n ```python\n # 'output' is a tensor of shape `[2, 2]` with edit distances normalized\n # by 'truth' lengths.\n output ==> [[inf, 1.0], # (0,0): no truth, (0,1): no hypothesis\n [0.5, 1.0]] # (1,0): addition, (1,1): no hypothesis\n ```\n\n Args:\n hypothesis: A `SparseTensor` containing hypothesis sequences.\n truth: A `SparseTensor` containing truth sequences.\n normalize: A `bool`. If `True`, normalizes the Levenshtein distance by\n length of `truth.`\n name: A name for the operation (optional).\n\n Returns:\n A dense `Tensor` with rank `R - 1`, where R is the rank of the\n `SparseTensor` inputs `hypothesis` and `truth`.\n\n Raises:\n TypeError: If either `hypothesis` or `truth` are not a `SparseTensor`.\n \"\"\"\n if not isinstance(\n hypothesis,\n (sparse_tensor.SparseTensor, sparse_tensor.SparseTensorValue)):\n raise TypeError(\"Hypothesis must be a SparseTensor.\")\n if not isinstance(\n truth, (sparse_tensor.SparseTensor, sparse_tensor.SparseTensorValue)):\n raise TypeError(\"Truth must be a SparseTensor.\")\n\n return gen_array_ops.edit_distance(\n hypothesis.indices,\n hypothesis.values,\n hypothesis.dense_shape,\n truth.indices,\n truth.values,\n truth.dense_shape,\n normalize=normalize,\n name=name)\n\n\[email protected](\"FakeQuantWithMinMaxArgs\")\ndef _FakeQuantWithMinMaxArgsGradient(op, grad):\n \"\"\"Gradient for FakeQuantWithMinMaxArgs op.\"\"\"\n return fake_quant_with_min_max_args_gradient(\n grad,\n op.inputs[0],\n min=op.get_attr(\"min\"),\n max=op.get_attr(\"max\"),\n num_bits=op.get_attr(\"num_bits\"),\n narrow_range=op.get_attr(\"narrow_range\"))\n\n\[email protected](\"FakeQuantWithMinMaxVars\")\ndef _FakeQuantWithMinMaxVarsGradient(op, grad):\n \"\"\"Gradient for FakeQuantWithMinMaxVars op.\"\"\"\n return fake_quant_with_min_max_vars_gradient(\n grad,\n op.inputs[0],\n op.inputs[1],\n op.inputs[2],\n num_bits=op.get_attr(\"num_bits\"),\n narrow_range=op.get_attr(\"narrow_range\"))\n\n\[email protected](\"FakeQuantWithMinMaxVarsPerChannel\")\ndef _FakeQuantWithMinMaxVarsPerChannelGradient(op, grad):\n \"\"\"Gradient for FakeQuantWithMinMaxVarsPerChannel op.\"\"\"\n return fake_quant_with_min_max_vars_per_channel_gradient(\n grad,\n op.inputs[0],\n op.inputs[1],\n op.inputs[2],\n num_bits=op.get_attr(\"num_bits\"),\n narrow_range=op.get_attr(\"narrow_range\"))\n\n\n@tf_export(\"required_space_to_batch_paddings\")\ndef required_space_to_batch_paddings(input_shape,\n block_shape,\n base_paddings=None,\n name=None):\n \"\"\"Calculate padding required to make block_shape divide input_shape.\n\n This function can be used to calculate a suitable paddings argument for use\n with space_to_batch_nd and batch_to_space_nd.\n\n Args:\n input_shape: int32 Tensor of shape [N].\n block_shape: int32 Tensor of shape [N].\n base_paddings: Optional int32 Tensor of shape [N, 2]. Specifies the minimum\n amount of padding to use. All elements must be >= 0. If not specified,\n defaults to 0.\n name: string. Optional name prefix.\n\n Returns:\n (paddings, crops), where:\n\n `paddings` and `crops` are int32 Tensors of rank 2 and shape [N, 2]\n satisfying:\n\n paddings[i, 0] = base_paddings[i, 0].\n 0 <= paddings[i, 1] - base_paddings[i, 1] < block_shape[i]\n (input_shape[i] + paddings[i, 0] + paddings[i, 1]) % block_shape[i] == 0\n\n crops[i, 0] = 0\n crops[i, 1] = paddings[i, 1] - base_paddings[i, 1]\n\n Raises: ValueError if called with incompatible shapes.\n \"\"\"\n with ops.name_scope(name, \"required_space_to_batch_paddings\",\n [input_shape, block_shape]):\n input_shape = ops.convert_to_tensor(\n input_shape, dtype=dtypes.int32, name=\"input_shape\")\n block_shape = ops.convert_to_tensor(\n block_shape, dtype=dtypes.int32, name=\"block_shape\")\n\n block_shape.get_shape().assert_is_fully_defined()\n block_shape.get_shape().assert_has_rank(1)\n num_block_dims = block_shape.get_shape().dims[0].value\n if num_block_dims == 0:\n return zeros([0, 2], dtypes.int32), zeros([0, 2], dtypes.int32)\n\n input_shape.get_shape().assert_is_compatible_with([num_block_dims])\n\n if base_paddings is not None:\n base_paddings = ops.convert_to_tensor(\n base_paddings, dtype=dtypes.int32, name=\"base_paddings\")\n base_paddings.get_shape().assert_is_compatible_with([num_block_dims, 2])\n else:\n base_paddings = zeros([num_block_dims, 2], dtypes.int32)\n\n const_block_shape = tensor_util.constant_value(block_shape)\n const_input_shape = tensor_util.constant_value(input_shape)\n const_base_paddings = tensor_util.constant_value(base_paddings)\n if (const_block_shape is not None and const_input_shape is not None and\n const_base_paddings is not None):\n block_shape = const_block_shape\n input_shape = const_input_shape\n base_paddings = const_base_paddings\n\n # Use same expression for both constant and non-constant case.\n pad_start = base_paddings[:, 0]\n orig_pad_end = base_paddings[:, 1]\n full_input_shape = input_shape + pad_start + orig_pad_end\n pad_end_extra = (block_shape - full_input_shape % block_shape) % block_shape\n pad_end = orig_pad_end + pad_end_extra\n\n result_paddings = stack(\n [[pad_start[i], pad_end[i]] for i in range(num_block_dims)],\n name=\"paddings\")\n result_crops = stack([[0, pad_end_extra[i]] for i in range(num_block_dims)],\n name=\"crops\")\n return result_paddings, result_crops\n\n\n@tf_export(v1=[\"nn.space_to_batch\", \"space_to_batch\"])\[email protected]_endpoints(\"space_to_batch\")\ndef space_to_batch( # pylint: disable=missing-docstring\n input, # pylint: disable=redefined-builtin\n paddings,\n block_size=None,\n name=None,\n block_shape=None): # pylint: disable=redefined-builtin\n block_size = deprecation.deprecated_argument_lookup(\"block_shape\",\n block_shape, \"block_size\",\n block_size)\n result = space_to_batch_nd(\n input,\n paddings=paddings,\n block_shape=np.array([block_size, block_size], dtype=np.int64),\n name=name)\n result.set_shape(result.get_shape().with_rank(4))\n return result\n\n\nspace_to_batch.__doc__ = gen_array_ops.space_to_batch.__doc__\n\n\n@tf_export(\"space_to_batch\", \"nn.space_to_batch\", v1=[])\ndef space_to_batch_v2(input, block_shape, paddings, name=None): # pylint: disable=redefined-builtin\n return space_to_batch_nd(input, block_shape, paddings, name)\n\n\nspace_to_batch_v2.__doc__ = gen_array_ops.space_to_batch_nd.__doc__\n\n\n@tf_export(v1=[\"nn.space_to_depth\", \"space_to_depth\"])\[email protected]_endpoints(\"space_to_depth\")\ndef space_to_depth(input, block_size, name=None, data_format=\"NHWC\"): # pylint: disable=redefined-builtin\n return gen_array_ops.space_to_depth(input, block_size, data_format, name=name)\n\n\nspace_to_depth.__doc__ = gen_array_ops.space_to_depth.__doc__\n\n\n@tf_export(\"nn.space_to_depth\", v1=[])\ndef space_to_depth_v2(input, block_size, data_format=\"NHWC\", name=None): # pylint: disable=redefined-builtin\n return gen_array_ops.space_to_depth(input, block_size, data_format, name=name)\n\n\nspace_to_depth_v2.__doc__ = gen_array_ops.space_to_depth.__doc__\n\n\n@tf_export(v1=[\"nn.depth_to_space\", \"depth_to_space\"])\[email protected]_endpoints(\"depth_to_space\")\ndef depth_to_space(input, block_size, name=None, data_format=\"NHWC\"): # pylint: disable=redefined-builtin\n return gen_array_ops.depth_to_space(input, block_size, data_format, name=name)\n\n\ndepth_to_space.__doc__ = gen_array_ops.depth_to_space.__doc__\n\n\n@tf_export(\"nn.depth_to_space\", v1=[])\ndef depth_to_space_v2(input, block_size, data_format=\"NHWC\", name=None): # pylint: disable=redefined-builtin\n return gen_array_ops.depth_to_space(input, block_size, data_format, name=name)\n\n\ndepth_to_space_v2.__doc__ = gen_array_ops.depth_to_space.__doc__\n\n\n@tf_export(v1=[\"batch_to_space\"])\ndef batch_to_space(input, crops, block_size, name=None, block_shape=None): # pylint: disable=redefined-builtin,missing-docstring\n block_size = deprecation.deprecated_argument_lookup(\"block_shape\",\n block_shape, \"block_size\",\n block_size)\n result = batch_to_space_nd(\n input,\n crops=crops,\n block_shape=np.array([block_size, block_size], dtype=np.int64),\n name=name)\n result.set_shape(result.get_shape().with_rank(4))\n return result\n\n\nbatch_to_space.__doc__ = gen_array_ops.batch_to_space.__doc__\n\n\n@tf_export(\"batch_to_space\", v1=[])\ndef batch_to_space_v2(input, block_shape, crops, name=None): # pylint: disable=redefined-builtin\n \"\"\"BatchToSpace for N-D tensors of type T.\n\n This operation reshapes the \"batch\" dimension 0 into `M + 1` dimensions of\n shape `block_shape + [batch]`, interleaves these blocks back into the grid\n defined by the spatial dimensions `[1, ..., M]`, to obtain a result with the\n same rank as the input. The spatial dimensions of this intermediate result\n are then optionally cropped according to `crops` to produce the output. This\n is the reverse of SpaceToBatch (see `tf.space_to_batch`).\n\n Args:\n input: A N-D `Tensor` with shape `input_shape = [batch] + spatial_shape +\n remaining_shape`, where `spatial_shape` has M dimensions.\n block_shape: A 1-D `Tensor` with shape [M]. Must be one of the following\n types: `int32`, `int64`. All values must be >= 1. For backwards\n compatibility with TF 1.0, this parameter may be an int, in which case it\n is converted to\n `numpy.array([block_shape, block_shape],\n dtype=numpy.int64)`.\n crops: A 2-D `Tensor` with shape `[M, 2]`. Must be one of the\n following types: `int32`, `int64`. All values must be >= 0.\n `crops[i] = [crop_start, crop_end]` specifies the amount to crop from\n input dimension `i + 1`, which corresponds to spatial dimension `i`.\n It is required that\n `crop_start[i] + crop_end[i] <= block_shape[i] * input_shape[i + 1]`.\n This operation is equivalent to the following steps:\n 1. Reshape `input` to `reshaped` of shape: [block_shape[0], ...,\n block_shape[M-1], batch / prod(block_shape), input_shape[1], ...,\n input_shape[N-1]]\n 2. Permute dimensions of `reshaped` to produce `permuted` of shape\n [batch / prod(block_shape), input_shape[1], block_shape[0], ...,\n input_shape[M], block_shape[M-1], input_shape[M+1],\n ..., input_shape[N-1]]\n 3. Reshape `permuted` to produce `reshaped_permuted` of shape\n [batch / prod(block_shape), input_shape[1] * block_shape[0], ...,\n input_shape[M] * block_shape[M-1], input_shape[M+1], ...,\n input_shape[N-1]]\n 4. Crop the start and end of dimensions `[1, ..., M]` of\n `reshaped_permuted` according to `crops` to produce the output\n of shape:\n [batch / prod(block_shape), input_shape[1] *\n block_shape[0] - crops[0,0] - crops[0,1], ..., input_shape[M] *\n block_shape[M-1] - crops[M-1,0] - crops[M-1,1], input_shape[M+1],\n ..., input_shape[N-1]]\n Some Examples:\n (1) For the following input of shape `[4, 1, 1, 1]`,\n `block_shape = [2, 2]`, and `crops = [[0, 0], [0, 0]]`:\n ```python\n [[[[1]]],\n [[[2]]],\n [[[3]]],\n [[[4]]]]\n ```\n The output tensor has shape `[1, 2, 2, 1]` and value:\n ``` x = [[[[1], [2]],\n [[3], [4]]]] ```\n (2) For the following input of shape `[4, 1, 1, 3]`,\n `block_shape = [2, 2]`, and `crops = [[0, 0], [0, 0]]`:\n ```python\n [[[1, 2, 3]],\n [[4, 5, 6]],\n [[7, 8, 9]],\n [[10, 11, 12]]]\n ```\n The output tensor has shape `[1, 2, 2, 3]` and value:\n ```python\n x = [[[[1, 2, 3], [4, 5, 6 ]],\n [[7, 8, 9], [10, 11, 12]]]]\n ```\n (3) For the following\n input of shape `[4, 2, 2, 1]`,\n `block_shape = [2, 2]`, and `crops = [[0, 0], [0, 0]]`:\n ```python\n x = [[[[1], [3]], [[ 9], [11]]],\n [[[2], [4]], [[10], [12]]],\n [[[5], [7]], [[13], [15]]],\n [[[6], [8]], [[14], [16]]]]\n ```\n The output tensor has shape `[1, 4, 4, 1]` and value:\n ```python\n x = [[[1], [2], [ 3], [ 4]],\n [[5], [6], [ 7], [ 8]],\n [[9], [10], [11], [12]],\n [[13], [14], [15], [16]]]\n ```\n (4) For the following input of shape\n `[8, 1, 3, 1]`,\n `block_shape = [2, 2]`, and `crops = [[0, 0], [2, 0]]`:\n ```python\n x = [[[[0], [ 1], [ 3]]],\n [[[0], [ 9], [11]]],\n [[[0], [ 2], [ 4]]],\n [[[0], [10], [12]]],\n [[[0], [ 5], [ 7]]],\n [[[0], [13], [15]]],\n [[[0], [ 6], [ 8]]],\n [[[0], [14], [16]]]]\n ```\n The output tensor has shape `[2, 2, 4, 1]` and value:\n ```python\n x = [[[[ 1], [ 2], [ 3], [ 4]],\n [[ 5], [ 6], [ 7], [ 8]]],\n [[[ 9], [10], [11], [12]],\n [[13], [14], [15], [16]]]] ```\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor`. Has the same type as `input`.\n \"\"\"\n if isinstance(block_shape, int):\n block_shape = np.array([block_shape, block_shape], dtype=np.int64)\n\n return batch_to_space_nd(\n input=input, block_shape=block_shape, crops=crops, name=name)\n\n\n@tf_export(\"one_hot\")\[email protected]_dispatch_support\ndef one_hot(indices,\n depth,\n on_value=None,\n off_value=None,\n axis=None,\n dtype=None,\n name=None):\n \"\"\"Returns a one-hot tensor.\n\n See also `tf.fill`, `tf.eye`.\n\n The locations represented by indices in `indices` take value `on_value`,\n while all other locations take value `off_value`.\n\n `on_value` and `off_value` must have matching data types. If `dtype` is also\n provided, they must be the same data type as specified by `dtype`.\n\n If `on_value` is not provided, it will default to the value `1` with type\n `dtype`\n\n If `off_value` is not provided, it will default to the value `0` with type\n `dtype`\n\n If the input `indices` is rank `N`, the output will have rank `N+1`. The\n new axis is created at dimension `axis` (default: the new axis is appended\n at the end).\n\n If `indices` is a scalar the output shape will be a vector of length `depth`\n\n If `indices` is a vector of length `features`, the output shape will be:\n\n ```\n features x depth if axis == -1\n depth x features if axis == 0\n ```\n\n If `indices` is a matrix (batch) with shape `[batch, features]`, the output\n shape will be:\n\n ```\n batch x features x depth if axis == -1\n batch x depth x features if axis == 1\n depth x batch x features if axis == 0\n ```\n\n If `indices` is a RaggedTensor, the 'axis' argument must be positive and refer\n to a non-ragged axis. The output will be equivalent to applying 'one_hot' on\n the values of the RaggedTensor, and creating a new RaggedTensor from the\n result.\n\n If `dtype` is not provided, it will attempt to assume the data type of\n `on_value` or `off_value`, if one or both are passed in. If none of\n `on_value`, `off_value`, or `dtype` are provided, `dtype` will default to the\n value `tf.float32`.\n\n Note: If a non-numeric data type output is desired (`tf.string`, `tf.bool`,\n etc.), both `on_value` and `off_value` _must_ be provided to `one_hot`.\n\n For example:\n\n ```python\n indices = [0, 1, 2]\n depth = 3\n tf.one_hot(indices, depth) # output: [3 x 3]\n # [[1., 0., 0.],\n # [0., 1., 0.],\n # [0., 0., 1.]]\n\n indices = [0, 2, -1, 1]\n depth = 3\n tf.one_hot(indices, depth,\n on_value=5.0, off_value=0.0,\n axis=-1) # output: [4 x 3]\n # [[5.0, 0.0, 0.0], # one_hot(0)\n # [0.0, 0.0, 5.0], # one_hot(2)\n # [0.0, 0.0, 0.0], # one_hot(-1)\n # [0.0, 5.0, 0.0]] # one_hot(1)\n\n indices = [[0, 2], [1, -1]]\n depth = 3\n tf.one_hot(indices, depth,\n on_value=1.0, off_value=0.0,\n axis=-1) # output: [2 x 2 x 3]\n # [[[1.0, 0.0, 0.0], # one_hot(0)\n # [0.0, 0.0, 1.0]], # one_hot(2)\n # [[0.0, 1.0, 0.0], # one_hot(1)\n # [0.0, 0.0, 0.0]]] # one_hot(-1)\n\n indices = tf.ragged.constant([[0, 1], [2]])\n depth = 3\n tf.one_hot(indices, depth) # output: [2 x None x 3]\n # [[[1., 0., 0.],\n # [0., 1., 0.]],\n # [[0., 0., 1.]]]\n ```\n\n Args:\n indices: A `Tensor` of indices.\n depth: A scalar defining the depth of the one hot dimension.\n on_value: A scalar defining the value to fill in output when `indices[j]\n = i`. (default: 1)\n off_value: A scalar defining the value to fill in output when `indices[j]\n != i`. (default: 0)\n axis: The axis to fill (default: -1, a new inner-most axis).\n dtype: The data type of the output tensor.\n name: A name for the operation (optional).\n\n Returns:\n output: The one-hot tensor.\n\n Raises:\n TypeError: If dtype of either `on_value` or `off_value` don't match `dtype`\n TypeError: If dtype of `on_value` and `off_value` don't match one another\n \"\"\"\n with ops.name_scope(\n name, \"one_hot\",\n [indices, depth, on_value, off_value, axis, dtype]) as name:\n on_exists = on_value is not None\n off_exists = off_value is not None\n\n if on_exists:\n on_value = ops.convert_to_tensor(on_value, dtype_hint=dtype)\n if off_exists:\n off_value = ops.convert_to_tensor(off_value, dtype_hint=dtype)\n\n on_dtype = on_value.dtype.base_dtype if on_exists else None\n off_dtype = off_value.dtype.base_dtype if off_exists else None\n\n if on_exists or off_exists:\n if dtype is not None:\n # Ensure provided on_value and/or off_value match dtype\n if on_exists and on_dtype != dtype:\n raise TypeError(\"dtype {0} of on_value does not match \"\n \"dtype parameter {1}\".format(on_dtype, dtype))\n if off_exists and off_dtype != dtype:\n raise TypeError(\"dtype {0} of off_value does not match \"\n \"dtype parameter {1}\".format(off_dtype, dtype))\n else:\n # dtype not provided: automatically assign it\n dtype = on_dtype if on_exists else off_dtype\n elif dtype is None:\n # None of on_value, off_value, or dtype provided. Default dtype to float32\n dtype = dtypes.float32\n\n if not on_exists:\n # on_value not provided: assign to value 1 of type dtype\n on_value = ops.convert_to_tensor(1, dtype, name=\"on_value\")\n on_dtype = dtype\n if not off_exists:\n # off_value not provided: assign to value 0 of type dtype\n off_value = ops.convert_to_tensor(0, dtype, name=\"off_value\")\n off_dtype = dtype\n\n if on_dtype != off_dtype:\n raise TypeError(\"dtype {0} of on_value does not match \"\n \"dtype {1} of off_value\".format(on_dtype, off_dtype))\n\n return gen_array_ops.one_hot(indices, depth, on_value, off_value, axis,\n name)\n\n\ndef _all_dimensions(x):\n \"\"\"Returns a 1D-tensor listing all dimensions in x.\"\"\"\n # Fast path: avoid creating Rank and Range ops if ndims is known.\n if isinstance(x, ops.Tensor) and x.get_shape().ndims is not None:\n return constant_op.constant(\n np.arange(x.get_shape().ndims), dtype=dtypes.int32)\n if (isinstance(x, sparse_tensor.SparseTensor) and\n x.dense_shape.get_shape().is_fully_defined()):\n r = x.dense_shape.get_shape().dims[0].value # sparse.dense_shape is 1-D.\n return constant_op.constant(np.arange(r), dtype=dtypes.int32)\n\n # Otherwise, we rely on `range` and `rank` to do the right thing at runtime.\n return gen_math_ops._range(0, rank(x), 1)\n\n\n@tf_export(\"sequence_mask\")\ndef sequence_mask(lengths, maxlen=None, dtype=dtypes.bool, name=None):\n \"\"\"Returns a mask tensor representing the first N positions of each cell.\n\n If `lengths` has shape `[d_1, d_2, ..., d_n]` the resulting tensor `mask` has\n dtype `dtype` and shape `[d_1, d_2, ..., d_n, maxlen]`, with\n\n ```\n mask[i_1, i_2, ..., i_n, j] = (j < lengths[i_1, i_2, ..., i_n])\n ```\n\n Examples:\n\n ```python\n tf.sequence_mask([1, 3, 2], 5) # [[True, False, False, False, False],\n # [True, True, True, False, False],\n # [True, True, False, False, False]]\n\n tf.sequence_mask([[1, 3],[2,0]]) # [[[True, False, False],\n # [True, True, True]],\n # [[True, True, False],\n # [False, False, False]]]\n ```\n\n Args:\n lengths: integer tensor, all its values <= maxlen.\n maxlen: scalar integer tensor, size of last dimension of returned tensor.\n Default is the maximum value in `lengths`.\n dtype: output type of the resulting tensor.\n name: name of the op.\n\n Returns:\n A mask tensor of shape `lengths.shape + (maxlen,)`, cast to specified dtype.\n Raises:\n ValueError: if `maxlen` is not a scalar.\n \"\"\"\n with ops.name_scope(name, \"SequenceMask\", [lengths, maxlen]):\n lengths = ops.convert_to_tensor(lengths)\n\n if maxlen is None:\n maxlen = gen_math_ops._max(lengths, _all_dimensions(lengths))\n maxlen = gen_math_ops.maximum(constant(0, maxlen.dtype), maxlen)\n else:\n maxlen = ops.convert_to_tensor(maxlen)\n if maxlen.get_shape().ndims is not None and maxlen.get_shape().ndims != 0:\n raise ValueError(\"maxlen must be scalar for sequence_mask\")\n\n # The basic idea is to compare a range row vector of size maxlen:\n # [0, 1, 2, 3, 4]\n # to length as a matrix with 1 column: [[1], [3], [2]].\n # Because of broadcasting on both arguments this comparison results\n # in a matrix of size (len(lengths), maxlen)\n row_vector = gen_math_ops._range(\n constant(0, maxlen.dtype), maxlen, constant(1, maxlen.dtype))\n # Since maxlen >= max(lengths), it is safe to use maxlen as a cast\n # authoritative type. Whenever maxlen fits into tf.int32, so do the lengths.\n matrix = gen_math_ops.cast(expand_dims(lengths, -1), maxlen.dtype)\n result = row_vector < matrix\n\n if dtype is None or result.dtype.base_dtype == dtype.base_dtype:\n return result\n else:\n return gen_math_ops.cast(result, dtype)\n\n\n@tf_export(v1=[\"squeeze\"])\[email protected]_dispatch_support\[email protected]_args(None, \"Use the `axis` argument instead\",\n \"squeeze_dims\")\ndef squeeze(input, axis=None, name=None, squeeze_dims=None):\n # pylint: disable=redefined-builtin\n \"\"\"Removes dimensions of size 1 from the shape of a tensor.\n\n Given a tensor `input`, this operation returns a tensor of the same type with\n all dimensions of size 1 removed. If you don't want to remove all size 1\n dimensions, you can remove specific size 1 dimensions by specifying\n `axis`.\n\n For example:\n\n >>> # 't' is a tensor of shape [1, 2, 1, 3, 1, 1]\n >>> t = tf.ones([1, 2, 1, 3, 1, 1])\n >>> print(tf.shape(tf.squeeze(t)).numpy())\n [2 3]\n\n Or, to remove specific size 1 dimensions:\n\n >>> # 't' is a tensor of shape [1, 2, 1, 3, 1, 1]\n >>> t = tf.ones([1, 2, 1, 3, 1, 1])\n >>> print(tf.shape(tf.squeeze(t, [2, 4])).numpy())\n [1 2 3 1]\n\n Note: if `input` is a `tf.RaggedTensor`, then this operation takes `O(N)`\n time, where `N` is the number of elements in the squeezed dimensions.\n\n Args:\n input: A `Tensor`. The `input` to squeeze.\n axis: An optional list of `ints`. Defaults to `[]`. If specified, only\n squeezes the dimensions listed. The dimension index starts at 0. It is an\n error to squeeze a dimension that is not 1. Must be in the range\n `[-rank(input), rank(input))`. Must be specified if `input` is a\n `RaggedTensor`.\n name: A name for the operation (optional).\n squeeze_dims: Deprecated keyword argument that is now axis.\n\n Returns:\n A `Tensor`. Has the same type as `input`.\n Contains the same data as `input`, but has one or more dimensions of\n size 1 removed.\n\n Raises:\n ValueError: When both `squeeze_dims` and `axis` are specified.\n \"\"\"\n axis = deprecation.deprecated_argument_lookup(\"axis\", axis, \"squeeze_dims\",\n squeeze_dims)\n if np.isscalar(axis):\n axis = [axis]\n return gen_array_ops.squeeze(input, axis, name)\n\n\n@tf_export(\"squeeze\", v1=[])\[email protected]_dispatch_support\ndef squeeze_v2(input, axis=None, name=None):\n \"\"\"Removes dimensions of size 1 from the shape of a tensor.\n\n Given a tensor `input`, this operation returns a tensor of the same type with\n all dimensions of size 1 removed. If you don't want to remove all size 1\n dimensions, you can remove specific size 1 dimensions by specifying\n `axis`.\n\n For example:\n\n ```python\n # 't' is a tensor of shape [1, 2, 1, 3, 1, 1]\n tf.shape(tf.squeeze(t)) # [2, 3]\n ```\n\n Or, to remove specific size 1 dimensions:\n\n ```python\n # 't' is a tensor of shape [1, 2, 1, 3, 1, 1]\n tf.shape(tf.squeeze(t, [2, 4])) # [1, 2, 3, 1]\n ```\n\n Unlike the older op `tf.compat.v1.squeeze`, this op does not accept a\n deprecated `squeeze_dims` argument.\n\n Note: if `input` is a `tf.RaggedTensor`, then this operation takes `O(N)`\n time, where `N` is the number of elements in the squeezed dimensions.\n\n Args:\n input: A `Tensor`. The `input` to squeeze.\n axis: An optional list of `ints`. Defaults to `[]`. If specified, only\n squeezes the dimensions listed. The dimension index starts at 0. It is an\n error to squeeze a dimension that is not 1. Must be in the range\n `[-rank(input), rank(input))`. Must be specified if `input` is a\n `RaggedTensor`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor`. Has the same type as `input`.\n Contains the same data as `input`, but has one or more dimensions of\n size 1 removed.\n\n Raises:\n ValueError: The input cannot be converted to a tensor, or the specified\n axis cannot be squeezed.\n \"\"\"\n # pylint: disable=redefined-builtin\n return squeeze(input, axis, name)\n\n\n@tf_export(v1=[\"where\"])\[email protected]_dispatch_support\ndef where(condition, x=None, y=None, name=None):\n \"\"\"Return the elements, either from `x` or `y`, depending on the `condition`.\n\n If both `x` and `y` are None, then this operation returns the coordinates of\n true elements of `condition`. The coordinates are returned in a 2-D tensor\n where the first dimension (rows) represents the number of true elements, and\n the second dimension (columns) represents the coordinates of the true\n elements. Keep in mind, the shape of the output tensor can vary depending on\n how many true values there are in input. Indices are output in row-major\n order.\n\n If both non-None, `x` and `y` must have the same shape.\n The `condition` tensor must be a scalar if `x` and `y` are scalar.\n If `x` and `y` are tensors of higher rank, then `condition` must be either a\n vector with size matching the first dimension of `x`, or must have the same\n shape as `x`.\n\n The `condition` tensor acts as a mask that chooses, based on the value at each\n element, whether the corresponding element / row in the output should be taken\n from `x` (if true) or `y` (if false).\n\n If `condition` is a vector and `x` and `y` are higher rank matrices, then it\n chooses which row (outer dimension) to copy from `x` and `y`. If `condition`\n has the same shape as `x` and `y`, then it chooses which element to copy from\n `x` and `y`.\n\n Args:\n condition: A `Tensor` of type `bool`\n x: A Tensor which may have the same shape as `condition`. If `condition` is\n rank 1, `x` may have higher rank, but its first dimension must match the\n size of `condition`.\n y: A `tensor` with the same shape and type as `x`.\n name: A name of the operation (optional)\n\n Returns:\n A `Tensor` with the same type and shape as `x`, `y` if they are non-None.\n Otherwise, a `Tensor` with shape `(num_true, rank(condition))`.\n\n Raises:\n ValueError: When exactly one of `x` or `y` is non-None.\n \"\"\"\n if x is None and y is None:\n with ops.name_scope(name, \"Where\", [condition]) as name:\n condition = ops.convert_to_tensor(\n condition, preferred_dtype=dtypes.bool, name=\"condition\")\n return gen_array_ops.where(condition=condition, name=name)\n elif x is not None and y is not None:\n return gen_math_ops.select(condition=condition, x=x, y=y, name=name)\n else:\n raise ValueError(\"x and y must both be non-None or both be None.\")\n\n\n@tf_export(\"where\", v1=[\"where_v2\"])\ndef where_v2(condition, x=None, y=None, name=None):\n \"\"\"Return the elements where `condition` is `True` (multiplexing `x` and `y`).\n\n This operator has two modes: in one mode both `x` and `y` are provided, in\n another mode neither are provided. `condition` is always expected to be a\n `tf.Tensor` of type `bool`.\n\n #### Retrieving indices of `True` elements\n\n If `x` and `y` are not provided (both are None):\n\n `tf.where` will return the indices of `condition` that are `True`, in\n the form of a 2-D tensor with shape (n, d).\n (Where n is the number of matching indices in `condition`,\n and d is the number of dimensions in `condition`).\n\n Indices are output in row-major order.\n\n >>> tf.where([True, False, False, True])\n <tf.Tensor: shape=(2, 1), dtype=int64, numpy=\n array([[0],\n [3]])>\n\n >>> tf.where([[True, False], [False, True]])\n <tf.Tensor: shape=(2, 2), dtype=int64, numpy=\n array([[0, 0],\n [1, 1]])>\n\n >>> tf.where([[[True, False], [False, True], [True, True]]])\n <tf.Tensor: shape=(4, 3), dtype=int64, numpy=\n array([[0, 0, 0],\n [0, 1, 1],\n [0, 2, 0],\n [0, 2, 1]])>\n\n #### Multiplexing between `x` and `y`\n\n If `x` and `y` are provided (both have non-None values):\n\n `tf.where` will choose an output shape from the shapes of `condition`, `x`,\n and `y` that all three shapes are\n [broadcastable](https://docs.scipy.org/doc/numpy/reference/ufuncs.html) to.\n\n The `condition` tensor acts as a mask that chooses whether the corresponding\n element / row in the output should be taken from `x`\n (if the elemment in `condition is True) or `y` (if it is false).\n\n >>> tf.where([True, False, False, True], [1,2,3,4], [100,200,300,400])\n <tf.Tensor: shape=(4,), dtype=int32, numpy=array([ 1, 200, 300, 4],\n dtype=int32)>\n >>> tf.where([True, False, False, True], [1,2,3,4], [100])\n <tf.Tensor: shape=(4,), dtype=int32, numpy=array([ 1, 100, 100, 4],\n dtype=int32)>\n >>> tf.where([True, False, False, True], [1,2,3,4], 100)\n <tf.Tensor: shape=(4,), dtype=int32, numpy=array([ 1, 100, 100, 4],\n dtype=int32)>\n >>> tf.where([True, False, False, True], 1, 100)\n <tf.Tensor: shape=(4,), dtype=int32, numpy=array([ 1, 100, 100, 1],\n dtype=int32)>\n\n >>> tf.where(True, [1,2,3,4], 100)\n <tf.Tensor: shape=(4,), dtype=int32, numpy=array([1, 2, 3, 4],\n dtype=int32)>\n >>> tf.where(False, [1,2,3,4], 100)\n <tf.Tensor: shape=(4,), dtype=int32, numpy=array([100, 100, 100, 100],\n dtype=int32)>\n\n Args:\n condition: A `tf.Tensor` of type `bool`\n x: If provided, a Tensor which is of the same type as `y`, and has a shape\n broadcastable with `condition` and `y`.\n y: If provided, a Tensor which is of the same type as `y`, and has a shape\n broadcastable with `condition` and `x`.\n name: A name of the operation (optional).\n\n Returns:\n If `x` and `y` are provided:\n A `Tensor` with the same type as `x` and `y`, and shape that\n is broadcast from `condition`, `x`, and `y`.\n Otherwise, a `Tensor` with shape `(num_true, dim_size(condition))`.\n\n Raises:\n ValueError: When exactly one of `x` or `y` is non-None, or the shapes\n are not all broadcastable.\n \"\"\"\n if x is None and y is None:\n with ops.name_scope(name, \"Where\", [condition]) as name:\n condition = ops.convert_to_tensor(\n condition, preferred_dtype=dtypes.bool, name=\"condition\")\n return gen_array_ops.where(condition=condition, name=name)\n elif x is not None and y is not None:\n return gen_math_ops.select_v2(condition=condition, t=x, e=y, name=name)\n else:\n raise ValueError(\"x and y must both be non-None or both be None.\")\n\n\n# pylint: disable=redefined-builtin\n@tf_export(v1=[\"reverse_sequence\"])\[email protected]_args(None,\n \"seq_dim is deprecated, use seq_axis instead\",\n \"seq_dim\")\[email protected]_args(None,\n \"batch_dim is deprecated, use batch_axis instead\",\n \"batch_dim\")\ndef reverse_sequence(input,\n seq_lengths,\n seq_axis=None,\n batch_axis=None,\n name=None,\n seq_dim=None,\n batch_dim=None):\n \"\"\"Reverses variable length slices.\n\n This op first slices `input` along the dimension `batch_axis`, and for\n each slice `i`, reverses the first `seq_lengths[i]` elements along the\n dimension `seq_axis`.\n\n The elements of `seq_lengths` must obey `seq_lengths[i] <=\n input.dims[seq_dim]`, and `seq_lengths` must be a vector of length\n `input.dims[batch_dim]`.\n\n The output slice `i` along dimension `batch_axis` is then given by\n input slice `i`, with the first `seq_lengths[i]` slices along\n dimension `seq_axis` reversed.\n\n Example usage:\n\n >>> seq_lengths = [7, 2, 3, 5]\n >>> input = [[1, 2, 3, 4, 5, 0, 0, 0], [1, 2, 0, 0, 0, 0, 0, 0],\n ... [1, 2, 3, 4, 0, 0, 0, 0], [1, 2, 3, 4, 5, 6, 7, 8]]\n >>> output = tf.reverse_sequence(input, seq_lengths, seq_axis=1, batch_axis=0)\n >>> output\n <tf.Tensor: shape=(4, 8), dtype=int32, numpy=\n array([[0, 0, 5, 4, 3, 2, 1, 0],\n [2, 1, 0, 0, 0, 0, 0, 0],\n [3, 2, 1, 4, 0, 0, 0, 0],\n [5, 4, 3, 2, 1, 6, 7, 8]], dtype=int32)>\n\n Args:\n input: A `Tensor`. The input to reverse.\n seq_lengths: A `Tensor`. Must be one of the following types: `int32`,\n `int64`. 1-D with length `input.dims(batch_dim)` and `max(seq_lengths) <=\n input.dims(seq_dim)`\n seq_axis: An `int`. The dimension which is partially reversed.\n batch_axis: An optional `int`. Defaults to `0`. The dimension along which\n reversal is performed.\n name: A name for the operation (optional).\n\n Returns:\n A Tensor. Has the same type as input.\n \"\"\"\n seq_axis = deprecation.deprecated_argument_lookup(\"seq_axis\", seq_axis,\n \"seq_dim\", seq_dim)\n batch_axis = deprecation.deprecated_argument_lookup(\"batch_axis\", batch_axis,\n \"batch_dim\", batch_dim)\n return gen_array_ops.reverse_sequence(\n input=input,\n seq_lengths=seq_lengths,\n seq_dim=seq_axis,\n batch_dim=batch_axis,\n name=name)\n\n\n@tf_export(\"reverse_sequence\", v1=[])\ndef reverse_sequence_v2(input,\n seq_lengths,\n seq_axis=None,\n batch_axis=None,\n name=None):\n return gen_array_ops.reverse_sequence(\n input=input,\n seq_lengths=seq_lengths,\n seq_dim=seq_axis,\n batch_dim=batch_axis,\n name=name)\n\nreverse_sequence_v2.__doc__ = reverse_sequence.__doc__\n# pylint: enable=redefined-builtin\n\n\n@tf_export(v1=[\"gather\"])\[email protected]_dispatch_support\ndef gather(params,\n indices,\n validate_indices=None,\n name=None,\n axis=None,\n batch_dims=0): # pylint: disable=g-doc-args\n r\"\"\"Gather slices from params axis `axis` according to indices.\n\n Gather slices from params axis `axis` according to `indices`. `indices` must\n be an integer tensor of any dimension (usually 0-D or 1-D).\n\n For 0-D (scalar) `indices`:\n\n $$\\begin{align*}\n output[p_0, ..., p_{axis-1}, && &&& p_{axis + 1}, ..., p_{N-1}] = \\\\\n params[p_0, ..., p_{axis-1}, && indices, &&& p_{axis + 1}, ..., p_{N-1}]\n \\end{align*}$$\n\n Where *N* = `ndims(params)`.\n\n For 1-D (vector) `indices` with `batch_dims=0`:\n\n $$\\begin{align*}\n output[p_0, ..., p_{axis-1}, && &i, &&p_{axis + 1}, ..., p_{N-1}] =\\\\\n params[p_0, ..., p_{axis-1}, && indices[&i], &&p_{axis + 1}, ..., p_{N-1}]\n \\end{align*}$$\n\n In the general case, produces an output tensor where:\n\n $$\\begin{align*}\n output[p_0, &..., p_{axis-1}, &\n &i_{B}, ..., i_{M-1}, &\n p_{axis + 1}, &..., p_{N-1}] = \\\\\n params[p_0, &..., p_{axis-1}, &\n indices[p_0, ..., p_{B-1}, &i_{B}, ..., i_{M-1}], &\n p_{axis + 1}, &..., p_{N-1}]\n \\end{align*}$$\n\n Where *N* = `ndims(params)`, *M* = `ndims(indices)`, and *B* = `batch_dims`.\n Note that `params.shape[:batch_dims]` must be identical to\n `indices.shape[:batch_dims]`.\n\n The shape of the output tensor is:\n\n > `output.shape = params.shape[:axis] + indices.shape[batch_dims:] +\n > params.shape[axis + 1:]`.\n\n Note that on CPU, if an out of bound index is found, an error is returned.\n On GPU, if an out of bound index is found, a 0 is stored in the corresponding\n output value.\n\n See also `tf.gather_nd`.\n\n <div style=\"width:70%; margin:auto; margin-bottom:10px; margin-top:20px;\">\n <img style=\"width:100%\" src=\"https://www.tensorflow.org/images/Gather.png\"\n alt>\n </div>\n\n Args:\n params: The `Tensor` from which to gather values. Must be at least rank\n `axis + 1`.\n indices: The index `Tensor`. Must be one of the following types: `int32`,\n `int64`. Must be in range `[0, params.shape[axis])`.\n validate_indices: Deprecated, does nothing.\n axis: A `Tensor`. Must be one of the following types: `int32`, `int64`. The\n `axis` in `params` to gather `indices` from. Must be greater than or equal\n to `batch_dims`. Defaults to the first non-batch dimension. Supports\n negative indexes.\n batch_dims: An `integer`. The number of batch dimensions. Must be less\n than or equal to `rank(indices)`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor`. Has the same type as `params`.\n \"\"\"\n del validate_indices\n\n if axis is None:\n axis = batch_dims\n if tensor_util.constant_value(axis) != 0:\n return gen_array_ops.gather_v2(\n params, indices, axis, batch_dims=batch_dims, name=name)\n try:\n # TODO(apassos) find a less bad way of detecting resource variables\n # without introducing a circular dependency.\n return params.sparse_read(indices, name=name)\n except AttributeError:\n return gen_array_ops.gather_v2(params, indices, axis, name=name)\n\n\n@tf_export(\"gather\", v1=[])\[email protected]_dispatch_support\ndef gather_v2(params,\n indices,\n validate_indices=None,\n axis=None,\n batch_dims=0,\n name=None):\n return gather(\n params,\n indices,\n validate_indices=validate_indices,\n name=name,\n axis=axis,\n batch_dims=batch_dims)\n\n\ngather_v2.__doc__ = gather.__doc__\n\n\n@tf_export(v1=[\"batch_gather\"])\[email protected]_dispatch_support\[email protected](\n \"2017-10-25\", \"`tf.batch_gather` is deprecated, please use `tf.gather` \"\n \"with `batch_dims=-1` instead.\") # pylint: disable=missing-docstring\ndef batch_gather(params, indices, name=None):\n \"\"\"Gather slices from params according to indices with leading batch dims.\"\"\"\n with ops.name_scope(name, \"BatchGather\", [params, indices]):\n indices = ops.convert_to_tensor(indices, name=\"indices\")\n params = ops.convert_to_tensor(params, name=\"params\")\n if indices.shape.ndims is None:\n raise ValueError(\n \"batch_gather does not allow indices with unknown shape.\")\n return _batch_gather(params, indices, batch_dims=indices.shape.ndims - 1)\n\n\ndef _batch_gather(params, indices, batch_dims, axis=None):\n r\"\"\"Gather slices from params according to indices with leading batch dims.\n\n This operation assumes that the leading `batch_dims` dimensions of `indices`\n and `params` are batch dimensions; and performs a `tf.gather` operation within\n each batch. (If `batch_dims` is not specified, then it defaults to\n `rank(indices)-1`.) In the case in which `batch_dims==0`, this operation\n is equivalent to `tf.gather`.\n\n Args:\n params: A Tensor. The tensor from which to gather values.\n indices: A Tensor. Must be one of the following types: int32, int64. Index\n tensor. Must be in range `[0, params.shape[batch_dims]]`.\n batch_dims: An integer or none. The number of batch dimensions. Must be\n less than `rank(indices)`. Defaults to `rank(indices) - 1` if None.\n axis: A `Tensor`. Must be one of the following types: `int32`, `int64`. The\n `axis` in `params` to gather `indices` from. Must be greater than or equal\n to `batch_dims`. Defaults to the first non-batch dimension. Supports\n negative indexes.\n\n Returns:\n A Tensor. Has the same type as `params`.\n\n Raises:\n ValueError: if `indices` has an unknown shape.\n \"\"\"\n if batch_dims is not None and not isinstance(batch_dims, int):\n raise TypeError(\"batch_dims must be an int; got %r\" % (batch_dims,))\n indices = ops.convert_to_tensor(indices, name=\"indices\")\n params = ops.convert_to_tensor(params, name=\"params\")\n\n indices_ndims = indices.shape.ndims\n if indices_ndims is None:\n raise ValueError(\"tf.gather does not allow indices with unknown \"\n \"rank when batch_dims is specified.\")\n if batch_dims is None:\n batch_dims = indices_ndims - 1\n if batch_dims < 0:\n batch_dims += indices_ndims\n if batch_dims < 0 or batch_dims >= indices_ndims:\n raise ValueError(\"batch_dims = %d must be less than rank(indices) = %d\" %\n (batch_dims, indices_ndims))\n if params.shape.ndims is not None and batch_dims >= params.shape.ndims:\n raise ValueError(\"batch_dims = %d must be less than rank(params) = %d\" %\n (batch_dims, params.shape.ndims))\n\n # Handle axis by transposing the axis dimension to be the first non-batch\n # dimension, recursively calling batch_gather with axis=0, and then\n # transposing the result to put the pre-axis dimensions before the indices\n # dimensions.\n if axis is not None and axis != batch_dims:\n # Adjust axis to be positive.\n if not isinstance(axis, int):\n axis = tf.where(axis < 0, axis + array_ops.rank(params), axis)\n elif axis < 0 and params.shape.ndims is None:\n axis = axis + array_ops.rank(params)\n else:\n if (axis < -params.shape.ndims) or (axis >= params.shape.ndims):\n raise ValueError(\"axis (%d) out of range [%d, %d)\" %\n (axis, -params.shape.ndims, params.shape.ndims))\n if axis < 0:\n axis += params.shape.ndims\n if axis < batch_dims:\n raise ValueError(\"batch_dims = %d must be less than or equal to \"\n \"axis = %d\" % (batch_dims, axis))\n\n # Move params[axis] up to params[batch_dims].\n perm = [\n list(range(batch_dims)), [axis],\n gen_math_ops._range(batch_dims, axis, 1),\n gen_math_ops._range(axis + 1, rank(params), 1)\n ]\n params = transpose(params, concat(perm, axis=0))\n\n result = _batch_gather(params, indices, batch_dims=batch_dims)\n\n # Move the result dimensions corresponding to params[batch_dims:axis]\n # to just before the dimensions corresponding to indices[batch_dims:].\n params_start = indices_ndims + axis - batch_dims\n perm = [\n list(range(batch_dims)),\n gen_math_ops._range(indices_ndims, params_start, 1),\n list(range(batch_dims, indices_ndims)),\n gen_math_ops._range(params_start, rank(result), 1)\n ]\n return transpose(result, perm=concat(perm, axis=0))\n\n indices_shape = shape(indices)\n params_shape = shape(params)\n batch_indices = indices\n indices_dtype = indices.dtype.base_dtype\n accum_dim_value = ones((), dtype=indices_dtype)\n # Use correct type for offset index computation\n casted_params_shape = gen_math_ops.cast(params_shape, indices_dtype)\n for dim in range(batch_dims, 0, -1):\n dim_value = casted_params_shape[dim - 1]\n accum_dim_value *= casted_params_shape[dim]\n start = zeros((), dtype=indices_dtype)\n step = ones((), dtype=indices_dtype)\n dim_indices = gen_math_ops._range(start, dim_value, step)\n dim_indices *= accum_dim_value\n dim_shape = stack(\n [1] * (dim - 1) + [dim_value] + [1] * (indices_ndims - dim), axis=0)\n batch_indices += reshape(dim_indices, dim_shape)\n\n flat_indices = reshape(batch_indices, [-1])\n outer_shape = params_shape[batch_dims + 1:]\n flat_inner_shape = gen_math_ops.prod(params_shape[:batch_dims + 1], [0],\n False)\n\n flat_params = reshape(params, concat([[flat_inner_shape], outer_shape],\n axis=0))\n flat_result = gather(flat_params, flat_indices)\n result = reshape(flat_result, concat([indices_shape, outer_shape], axis=0))\n final_shape = indices.get_shape()[:batch_dims].merge_with(\n params.get_shape()[:batch_dims])\n final_shape = final_shape.concatenate(indices.get_shape().dims[batch_dims:])\n final_shape = final_shape.concatenate(params.get_shape()[batch_dims + 1:])\n result.set_shape(final_shape)\n return result\n\n\n@tf_export(v1=[\"gather_nd\", \"manip.gather_nd\"])\[email protected]_dispatch_support\n@deprecated_endpoints(\"manip.gather_nd\")\ndef gather_nd(params, indices, name=None, batch_dims=0):\n r\"\"\"Gather slices from `params` into a Tensor with shape specified by `indices`.\n\n `indices` is an K-dimensional integer tensor, best thought of as a\n (K-1)-dimensional tensor of indices into `params`, where each element defines\n a slice of `params`:\n\n output[\\\\(i_0, ..., i_{K-2}\\\\)] = params[indices[\\\\(i_0, ..., i_{K-2}\\\\)]]\n\n Whereas in `tf.gather` `indices` defines slices into the first\n dimension of `params`, in `tf.gather_nd`, `indices` defines slices into the\n first `N` dimensions of `params`, where `N = indices.shape[-1]`.\n\n The last dimension of `indices` can be at most the rank of\n `params`:\n\n indices.shape[-1] <= params.rank\n\n The last dimension of `indices` corresponds to elements\n (if `indices.shape[-1] == params.rank`) or slices\n (if `indices.shape[-1] < params.rank`) along dimension `indices.shape[-1]`\n of `params`. The output tensor has shape\n\n indices.shape[:-1] + params.shape[indices.shape[-1]:]\n\n Additionally both 'params' and 'indices' can have M leading batch\n dimensions that exactly match. In this case 'batch_dims' must be M.\n\n Note that on CPU, if an out of bound index is found, an error is returned.\n On GPU, if an out of bound index is found, a 0 is stored in the\n corresponding output value.\n\n Some examples below.\n\n Simple indexing into a matrix:\n\n ```python\n indices = [[0, 0], [1, 1]]\n params = [['a', 'b'], ['c', 'd']]\n output = ['a', 'd']\n ```\n\n Slice indexing into a matrix:\n\n ```python\n indices = [[1], [0]]\n params = [['a', 'b'], ['c', 'd']]\n output = [['c', 'd'], ['a', 'b']]\n ```\n\n Indexing into a 3-tensor:\n\n ```python\n indices = [[1]]\n params = [[['a0', 'b0'], ['c0', 'd0']],\n [['a1', 'b1'], ['c1', 'd1']]]\n output = [[['a1', 'b1'], ['c1', 'd1']]]\n\n\n indices = [[0, 1], [1, 0]]\n params = [[['a0', 'b0'], ['c0', 'd0']],\n [['a1', 'b1'], ['c1', 'd1']]]\n output = [['c0', 'd0'], ['a1', 'b1']]\n\n\n indices = [[0, 0, 1], [1, 0, 1]]\n params = [[['a0', 'b0'], ['c0', 'd0']],\n [['a1', 'b1'], ['c1', 'd1']]]\n output = ['b0', 'b1']\n ```\n\n The examples below are for the case when only indices have leading extra\n dimensions. If both 'params' and 'indices' have leading batch dimensions, use\n the 'batch_dims' parameter to run gather_nd in batch mode.\n\n Batched indexing into a matrix:\n\n ```python\n indices = [[[0, 0]], [[0, 1]]]\n params = [['a', 'b'], ['c', 'd']]\n output = [['a'], ['b']]\n ```\n\n Batched slice indexing into a matrix:\n\n ```python\n indices = [[[1]], [[0]]]\n params = [['a', 'b'], ['c', 'd']]\n output = [[['c', 'd']], [['a', 'b']]]\n ```\n\n Batched indexing into a 3-tensor:\n\n ```python\n indices = [[[1]], [[0]]]\n params = [[['a0', 'b0'], ['c0', 'd0']],\n [['a1', 'b1'], ['c1', 'd1']]]\n output = [[[['a1', 'b1'], ['c1', 'd1']]],\n [[['a0', 'b0'], ['c0', 'd0']]]]\n\n indices = [[[0, 1], [1, 0]], [[0, 0], [1, 1]]]\n params = [[['a0', 'b0'], ['c0', 'd0']],\n [['a1', 'b1'], ['c1', 'd1']]]\n output = [[['c0', 'd0'], ['a1', 'b1']],\n [['a0', 'b0'], ['c1', 'd1']]]\n\n\n indices = [[[0, 0, 1], [1, 0, 1]], [[0, 1, 1], [1, 1, 0]]]\n params = [[['a0', 'b0'], ['c0', 'd0']],\n [['a1', 'b1'], ['c1', 'd1']]]\n output = [['b0', 'b1'], ['d0', 'c1']]\n ```\n\n Examples with batched 'params' and 'indices':\n\n ```python\n batch_dims = 1\n indices = [[1], [0]]\n params = [[['a0', 'b0'], ['c0', 'd0']],\n [['a1', 'b1'], ['c1', 'd1']]]\n output = [['c0', 'd0'], ['a1', 'b1']]\n\n batch_dims = 1\n indices = [[[1]], [[0]]]\n params = [[['a0', 'b0'], ['c0', 'd0']],\n [['a1', 'b1'], ['c1', 'd1']]]\n output = [[['c0', 'd0']], [['a1', 'b1']]]\n\n batch_dims = 1\n indices = [[[1, 0]], [[0, 1]]]\n params = [[['a0', 'b0'], ['c0', 'd0']],\n [['a1', 'b1'], ['c1', 'd1']]]\n output = [['c0'], ['b1']]\n ```\n\n See also `tf.gather`.\n\n Args:\n params: A `Tensor`. The tensor from which to gather values.\n indices: A `Tensor`. Must be one of the following types: `int32`, `int64`.\n Index tensor.\n name: A name for the operation (optional).\n batch_dims: An integer or a scalar 'Tensor'. The number of batch dimensions.\n\n Returns:\n A `Tensor`. Has the same type as `params`.\n \"\"\"\n batch_dims_ = tensor_util.constant_value(batch_dims)\n if batch_dims_ is not None:\n batch_dims = int(batch_dims_)\n if batch_dims == 0:\n try:\n # TODO(apassos) find a less bad way of detecting resource variables\n # without introducing a circular dependency.\n return params.gather_nd(indices, name=name)\n except AttributeError:\n return gen_array_ops.gather_nd(params, indices, name=name)\n else:\n return batch_gather_nd(params, indices, batch_dims=batch_dims, name=name)\n\n\n@tf_export(\"gather_nd\", v1=[])\[email protected]_dispatch_support\ndef gather_nd_v2(params, indices, batch_dims=0, name=None):\n return gather_nd(params, indices, name=name, batch_dims=batch_dims)\n\n\ngather_nd_v2.__doc__ = gather_nd.__doc__\n\n\ndef batch_gather_nd(params, indices, batch_dims, name=None):\n \"\"\"gather_nd implementation with batch support.\"\"\"\n with ops.name_scope(name, \"BatchGatherND\", [params, indices]):\n indices = ops.convert_to_tensor(indices, name=\"indices\")\n params = ops.convert_to_tensor(params, name=\"params\")\n\n if not isinstance(batch_dims, int):\n raise TypeError(\"batch_dims must be an int; got %r\" % (batch_dims,))\n if batch_dims < 0:\n raise ValueError(\"tf.gather_nd does not allow negative batch_dims.\")\n params_ndims = params.shape.ndims\n indices_ndims = indices.shape.ndims\n if indices_ndims is not None and batch_dims >= indices_ndims:\n raise ValueError(\"batch_dims = %d must be less than rank(indices) = %d\" %\n (batch_dims, indices_ndims))\n if params_ndims is not None and batch_dims >= params_ndims:\n raise ValueError(\"batch_dims = %d must be less than rank(params) = %d\" %\n (batch_dims, params_ndims))\n\n expand = batch_dims == 0\n if expand:\n # Normally gather_nd will be called when batch_dims == 0.\n # But if this function is called with batch_dims = 0, e.g. for testing\n # purposes, this adds a dummy batch dimension to make batch_dims = 1.\n params = expand_dims(params, axis=0)\n indices = expand_dims(indices, axis=0)\n batch_dims = 1\n\n params_shape = shape(params)\n indices_shape = shape(indices)\n batch_shape = params_shape[:batch_dims]\n batch_size = gen_math_ops.prod(batch_shape, [0])\n index_internal_ndims = rank(indices) - batch_dims - 1\n indices_internal_shape = indices_shape[batch_dims:-1]\n\n # Assuming a 'params' with shape [b1, ..., bM, g1, ..., gN] and an 'indices'\n # with shape [b1, ..., bM, i1, ..., iK, C], where C <= N, we need to modify\n # 'indices' s.t. it has shape [i1, ..., iK, D], where D <= M + N and slices\n # to the entire 'params' tensor.\n # Assuming we have a batch of shape [B1, B2], we use meshgrid to create a\n # grid of size B1 x B2.\n batch_dim_list = unstack(batch_shape, axis=0)\n dim_ranges = [\n gen_math_ops.cast(gen_math_ops._range(0, x, 1), indices.dtype)\n for x in batch_dim_list\n ]\n mesh_list = meshgrid(*dim_ranges, indexing=\"ij\") if dim_ranges else []\n # Then we flatten and stack the tensors to form a (B1.B2) by 2 matrix.\n flat_list = [reshape(x, shape=(-1,)) for x in mesh_list]\n index_grid = transpose(stack(flat_list, axis=0))\n # We need to concatenate these batch coordinates with the internal indices.\n # concat -> index_grid [B1.B2, 2] with indices [i1, ..., iK, C]\n # So we reshape them both to [(B1.B2), i1, ..., iK, *]\n index_grid_shape = shape(index_grid)\n index_grid = reshape(\n index_grid,\n concat([\n index_grid_shape[:1],\n ones(index_internal_ndims, dtype=dtypes.int32), index_grid_shape[1:]\n ],\n axis=0))\n tile_shape = concat(((1,), indices_internal_shape, (1,)), axis=0)\n index_grid = tile(index_grid, multiples=tile_shape)\n # index_grid now has shape [(B1.B2), i1, ..., iK, 2]\n flat_shape = concat(([batch_size], indices_shape[batch_dims:]), axis=0)\n flat_indices = reshape(indices, shape=flat_shape)\n # flat_indices now has shape [(B1.B2), i1, ..., iK, C]\n indices = concat((index_grid, flat_indices), axis=-1)\n # indices has shape [(B1.B2), i1, ..., iK, 2+C]\n out = gen_array_ops.gather_nd(params, indices)\n # out has shape [(B1.B2), i1, ..., iK, N-C]. Now we reshape batch to\n # its original form.\n out_shape = shape(out)\n out = reshape(out, shape=concat((batch_shape, out_shape[1:]), axis=0))\n if expand:\n out = squeeze(out, axis=0)\n return out\n\n\n# Define quantize_v2 here in order to make name the second-to-last attribute,\n# because round_mode was added later.\n# (And also now because of 'axis' processing).\n@tf_export(v1=[\"quantize_v2\"])\[email protected](\n \"2017-10-25\",\n \"`tf.quantize_v2` is deprecated, please use `tf.quantization.quantize` \"\n \"instead.\") # pylint: disable=missing-docstring\ndef quantize_v2(\n input, # pylint: disable=redefined-builtin\n min_range,\n max_range,\n T,\n mode=\"MIN_COMBINED\",\n name=None,\n round_mode=\"HALF_AWAY_FROM_ZERO\",\n narrow_range=False,\n axis=None,\n ensure_minimum_range=0.01):\n if axis is None:\n axis = -1\n elif axis < 0:\n if input.shape.ndims is None:\n raise ValueError(\"input should have known rank to use negative axis.\")\n axis %= input.shape.ndims\n\n if ensure_minimum_range != 0.01:\n return gen_array_ops.quantize_v2(\n input,\n min_range,\n max_range,\n T=T,\n mode=mode,\n name=name,\n round_mode=round_mode,\n narrow_range=narrow_range,\n axis=axis,\n ensure_minimum_range=ensure_minimum_range)\n return gen_array_ops.quantize_v2(\n input,\n min_range,\n max_range,\n T=T,\n mode=mode,\n name=name,\n round_mode=round_mode,\n narrow_range=narrow_range,\n axis=axis)\n\n\nquantize_v2.__doc__ = \"\"\"Please use `tf.quantization.quantize` instead.\"\"\"\n\n\n# We want to expose tf.quantization.quantize instead of\n# tf.quantization.quantize; we can deprecate tf.quantization.quantize in next\n# version of TensorFlow.\n@tf_export(\"quantization.quantize\", v1=[\"quantization.quantize\", \"quantize\"])\[email protected]_endpoints(\"quantize\")\ndef quantize(\n input, # pylint: disable=redefined-builtin\n min_range,\n max_range,\n T,\n mode=\"MIN_COMBINED\",\n round_mode=\"HALF_AWAY_FROM_ZERO\",\n name=None,\n narrow_range=False,\n axis=None,\n ensure_minimum_range=0.01):\n \"\"\"Quantize the input tensor.\"\"\"\n if ensure_minimum_range != 0.01:\n return quantize_v2(\n input,\n min_range,\n max_range,\n T,\n mode=mode,\n round_mode=round_mode,\n name=name,\n narrow_range=narrow_range,\n axis=axis,\n ensure_minimum_range=ensure_minimum_range)\n return quantize_v2(\n input,\n min_range,\n max_range,\n T,\n mode=mode,\n round_mode=round_mode,\n name=name,\n narrow_range=narrow_range,\n axis=axis)\n\n\n@tf_export(\"quantization.dequantize\", v1=[\"quantization.dequantize\",\n \"dequantize\"])\[email protected]_endpoints(\"dequantize\")\ndef dequantize( # pylint: disable=missing-docstring\n input, # pylint: disable=redefined-builtin\n min_range,\n max_range,\n mode=\"MIN_COMBINED\",\n name=None,\n axis=None,\n narrow_range=False,\n dtype=dtypes.float32):\n if axis is None:\n axis = -1\n elif axis < 0:\n if input.shape.ndims is None:\n raise ValueError(\"input should have known rank to use negative axis.\")\n axis %= input.shape.ndims\n\n if axis >= 0 or narrow_range:\n return gen_array_ops.dequantize(\n input,\n min_range,\n max_range,\n mode=mode,\n name=name,\n narrow_range=narrow_range,\n axis=axis,\n dtype=dtype)\n return gen_array_ops.dequantize(\n input, min_range, max_range, mode=mode, name=name, dtype=dtype)\n\n\ndequantize.__doc__ = gen_array_ops.dequantize.__doc__\n\n\n@tf_export(\"quantization.quantize_and_dequantize\")\ndef quantize_and_dequantize(\n input, # pylint: disable=redefined-builtin\n input_min,\n input_max,\n signed_input=True,\n num_bits=8,\n range_given=False,\n round_mode=\"HALF_TO_EVEN\",\n name=None,\n narrow_range=False,\n axis=None):\n \"\"\"Quantizes then dequantizes a tensor.\n\n Args:\n input: A `Tensor` to quantize and dequantize.\n input_min: If range_given=True, the minimum input value, that needs to be\n represented in the quantized representation. If axis is specified, this\n should be a vector of minimum values for each slice along axis.\n input_max: If range_given=True, the maximum input value that needs to be\n represented in the quantized representation. If axis is specified, this\n should be a vector of maximum values for each slice along axis.\n signed_input: True if the quantization is signed or unsigned.\n num_bits: The bitwidth of the quantization.\n range_given: If true use `input_min` and `input_max` for the range of the\n input, otherwise determine min and max from the input `Tensor`.\n round_mode: Rounding mode when rounding from float values to quantized ones.\n one of ['HALF_TO_EVEN', 'HALF_UP']\n name: Optional name for the operation.\n narrow_range: If true, then the absolute value of the quantized minimum\n value is the same as the quantized maximum value, instead of 1 greater.\n i.e. for 8 bit quantization, the minimum value is -127 instead of -128.\n axis: Integer. If specified, refers to a dimension of the input tensor, such\n that quantization will be per slice along that dimension.\n\n Returns:\n A `Tensor`. Each element is the result of quantizing and dequantizing the\n corresponding element of `input`.\n \"\"\"\n if axis is None:\n axis = -1\n elif axis < 0:\n if input.shape.ndims is None:\n raise ValueError(\"input should have known rank to use negative axis.\")\n axis %= input.shape.ndims\n\n return gen_array_ops.quantize_and_dequantize_v2(\n input,\n input_min=input_min,\n input_max=input_max,\n signed_input=signed_input,\n num_bits=num_bits,\n range_given=range_given,\n round_mode=round_mode,\n narrow_range=narrow_range,\n axis=axis,\n name=name)\n\n\n@tf_export(\"searchsorted\")\ndef searchsorted(sorted_sequence,\n values,\n side=\"left\",\n out_type=dtypes.int32,\n name=None):\n \"\"\"Searches input tensor for values on the innermost dimension.\n\n A 2-D example:\n\n ```\n sorted_sequence = [[0, 3, 9, 9, 10],\n [1, 2, 3, 4, 5]]\n values = [[2, 4, 9],\n [0, 2, 6]]\n\n result = searchsorted(sorted_sequence, values, side=\"left\")\n\n result == [[1, 2, 2],\n [0, 1, 5]]\n\n result = searchsorted(sorted_sequence, values, side=\"right\")\n\n result == [[1, 2, 4],\n [0, 2, 5]]\n ```\n\n Args:\n sorted_sequence: N-D `Tensor` containing a sorted sequence.\n values: N-D `Tensor` containing the search values.\n side: 'left' or 'right'; 'left' corresponds to lower_bound and 'right' to\n upper_bound.\n out_type: The output type (`int32` or `int64`). Default is `tf.int32`.\n name: Optional name for the operation.\n\n Returns:\n An N-D `Tensor` the size of values containing the result of applying either\n lower_bound or upper_bound (depending on side) to each value. The result\n is not a global index to the entire `Tensor`, but the index in the last\n dimension.\n\n Raises:\n ValueError: If the last dimension of `sorted_sequence >= 2^31-1` elements.\n If the total size of values exceeds `2^31 - 1` elements.\n If the first `N-1` dimensions of the two tensors don't match.\n \"\"\"\n sequence_size = shape_internal(sorted_sequence)[-1]\n values_size = shape_internal(values)[-1]\n sorted_sequence_2d = reshape(sorted_sequence, [-1, sequence_size])\n values_2d = reshape(values, [-1, values_size])\n if side == \"right\":\n output = gen_array_ops.upper_bound(sorted_sequence_2d, values_2d, out_type,\n name)\n elif side == \"left\":\n output = gen_array_ops.lower_bound(sorted_sequence_2d, values_2d, out_type,\n name)\n else:\n raise ValueError(\"side must be either 'right' or 'left'. Saw: %s.\" % side)\n return reshape(output, shape_internal(values))\n\n\nquantize.__doc__ = gen_array_ops.quantize_v2.__doc__\n\n\n@tf_export(\"image.extract_patches\")\ndef extract_image_patches_v2(images, sizes, strides, rates, padding, name=None):\n r\"\"\"Extract `patches` from `images`.\n\n This op collects patches from the input image, as if applying a\n convolution. All extracted patches are stacked in the depth (last) dimension\n of the output.\n\n Specifically, the op extracts patches of shape `sizes` which are `strides`\n apart in the input image. The output is subsampled using the `rates` argument,\n in the same manner as \"atrous\" or \"dilated\" convolutions.\n\n The result is a 4D tensor which is indexed by batch, row, and column.\n `output[i, x, y]` contains a flattened patch of size `sizes[1], sizes[2]`\n which is taken from the input starting at\n `images[i, x*strides[1], y*strides[2]]`.\n\n Each output patch can be reshaped to `sizes[1], sizes[2], depth`, where\n `depth` is `images.shape[3]`.\n\n The output elements are taken from the input at intervals given by the `rate`\n argument, as in dilated convolutions.\n\n The `padding` argument has no effect on the size of each patch, it determines\n how many patches are extracted. If `VALID`, only patches which are fully\n contained in the input image are included. If `SAME`, all patches whose\n starting point is inside the input are included, and areas outside the input\n default to zero.\n\n Example:\n\n ```\n n = 10\n # images is a 1 x 10 x 10 x 1 array that contains the numbers 1 through 100\n images = [[[[x * n + y + 1] for y in range(n)] for x in range(n)]]\n\n # We generate two outputs as follows:\n # 1. 3x3 patches with stride length 5\n # 2. Same as above, but the rate is increased to 2\n tf.image.extract_patches(images=images,\n sizes=[1, 3, 3, 1],\n strides=[1, 5, 5, 1],\n rates=[1, 1, 1, 1],\n padding='VALID')\n\n # Yields:\n [[[[ 1 2 3 11 12 13 21 22 23]\n [ 6 7 8 16 17 18 26 27 28]]\n [[51 52 53 61 62 63 71 72 73]\n [56 57 58 66 67 68 76 77 78]]]]\n ```\n\n If we mark the pixels in the input image which are taken for the output with\n `*`, we see the pattern:\n\n ```\n * * * 4 5 * * * 9 10\n * * * 14 15 * * * 19 20\n * * * 24 25 * * * 29 30\n 31 32 33 34 35 36 37 38 39 40\n 41 42 43 44 45 46 47 48 49 50\n * * * 54 55 * * * 59 60\n * * * 64 65 * * * 69 70\n * * * 74 75 * * * 79 80\n 81 82 83 84 85 86 87 88 89 90\n 91 92 93 94 95 96 97 98 99 100\n ```\n\n ```\n tf.image.extract_patches(images=images,\n sizes=[1, 3, 3, 1],\n strides=[1, 5, 5, 1],\n rates=[1, 2, 2, 1],\n padding='VALID')\n\n # Yields:\n [[[[ 1 3 5 21 23 25 41 43 45]\n [ 6 8 10 26 28 30 46 48 50]]\n\n [[ 51 53 55 71 73 75 91 93 95]\n [ 56 58 60 76 78 80 96 98 100]]]]\n ```\n\n We can again draw the effect, this time using the symbols `*`, `x`, `+` and\n `o` to distinguish the patches:\n\n ```\n * 2 * 4 * x 7 x 9 x\n 11 12 13 14 15 16 17 18 19 20\n * 22 * 24 * x 27 x 29 x\n 31 32 33 34 35 36 37 38 39 40\n * 42 * 44 * x 47 x 49 x\n + 52 + 54 + o 57 o 59 o\n 61 62 63 64 65 66 67 68 69 70\n + 72 + 74 + o 77 o 79 o\n 81 82 83 84 85 86 87 88 89 90\n + 92 + 94 + o 97 o 99 o\n ```\n\n Args:\n images: A 4-D Tensor with shape `[batch, in_rows, in_cols, depth]\n sizes: The size of the extracted patches. Must be [1, size_rows, size_cols,\n 1].\n strides: A 1-D Tensor of length 4. How far the centers of two consecutive\n patches are in the images. Must be: `[1, stride_rows, stride_cols, 1]`.\n rates: A 1-D Tensor of length 4. Must be: `[1, rate_rows, rate_cols, 1]`.\n This is the input stride, specifying how far two consecutive patch samples\n are in the input. Equivalent to extracting patches with `patch_sizes_eff =\n patch_sizes + (patch_sizes - 1) * (rates - 1)`, followed by subsampling\n them spatially by a factor of `rates`. This is equivalent to `rate` in\n dilated (a.k.a. Atrous) convolutions.\n padding: The type of padding algorithm to use.\n name: A name for the operation (optional).\n\n Returns:\n A 4-D Tensor of the same type as the input.\n \"\"\"\n return gen_array_ops.extract_image_patches(images, sizes, strides, rates,\n padding, name)\n\n\n@tf_export(v1=[\"image.extract_image_patches\", \"extract_image_patches\"])\[email protected]_args(None, \"ksizes is deprecated, use sizes instead\",\n \"ksizes\")\ndef extract_image_patches( # pylint: disable=missing-docstring\n images,\n ksizes=None,\n strides=None,\n rates=None,\n padding=None,\n name=None,\n sizes=None):\n \"\"\"Extract patches from images and put them in the \"depth\" output dimension.\n\n Args:\n `images`: A `Tensor`. Must be one of the following types: `float32`,\n `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`,\n `uint16`, `half`, `uint32`, `uint64`. 4-D Tensor with shape\n `[batch, in_rows, in_cols, depth]`. `ksizes`: A list of `ints` that has\n length `>= 4`. The size of the sliding window for each\n dimension of `images`. `strides`: A list of `ints` that has length `>= 4`.\n 1-D of length 4. How far the centers of two consecutive\n patches are in the images. Must be:\n `[1, stride_rows, stride_cols, 1]`. `rates`: A list of `ints`\n that has length `>= 4`. 1-D of length 4. Must be: `[1, rate_rows, rate_cols,\n 1]`. This is the input stride, specifying how far two consecutive patch\n samples are in the input. Equivalent to extracting patches with\n `patch_sizes_eff = patch_sizes + (patch_sizes - 1) * (rates - 1)`,\n followed by subsampling them spatially by a factor of `rates`. This is\n equivalent to `rate` in dilated (a.k.a. Atrous) convolutions.\n `padding`: A `string` from: \"SAME\", \"VALID\". The type of padding algorithm\n to use.\n We specify the size-related attributes as: ``` ksizes = [1, ksize_rows,\n ksize_cols, 1] strides = [1, strides_rows, strides_cols, 1] rates = [1,\n rates_rows, rates_cols, 1]\n name: A name for the operation (optional). ```\n\n Returns:\n A Tensor. Has the same type as images.\n \"\"\"\n ksizes = deprecation.deprecated_argument_lookup(\"sizes\", sizes, \"ksizes\",\n ksizes)\n return gen_array_ops.extract_image_patches(images, ksizes, strides, rates,\n padding, name)\n\n\nextract_image_patches.__doc__ = gen_array_ops.extract_image_patches.__doc__\n\n\n@tf_export(\"fingerprint\")\ndef fingerprint(data, method=\"farmhash64\", name=None):\n r\"\"\"Generates fingerprint values.\n\n Generates fingerprint values of `data`.\n\n Fingerprint op considers the first dimension of `data` as the batch dimension,\n and `output[i]` contains the fingerprint value generated from contents in\n `data[i, ...]` for all `i`.\n\n Fingerprint op writes fingerprint values as byte arrays. For example, the\n default method `farmhash64` generates a 64-bit fingerprint value at a time.\n This 8-byte value is written out as an `tf.uint8` array of size 8, in\n little-endian order.\n\n For example, suppose that `data` has data type `tf.int32` and shape (2, 3, 4),\n and that the fingerprint method is `farmhash64`. In this case, the output\n shape is (2, 8), where 2 is the batch dimension size of `data`, and 8 is the\n size of each fingerprint value in bytes. `output[0, :]` is generated from\n 12 integers in `data[0, :, :]` and similarly `output[1, :]` is generated from\n other 12 integers in `data[1, :, :]`.\n\n Note that this op fingerprints the raw underlying buffer, and it does not\n fingerprint Tensor's metadata such as data type and/or shape. For example, the\n fingerprint values are invariant under reshapes and bitcasts as long as the\n batch dimension remain the same:\n\n ```python\n tf.fingerprint(data) == tf.fingerprint(tf.reshape(data, ...))\n tf.fingerprint(data) == tf.fingerprint(tf.bitcast(data, ...))\n ```\n\n For string data, one should expect `tf.fingerprint(data) !=\n tf.fingerprint(tf.string.reduce_join(data))` in general.\n\n Args:\n data: A `Tensor`. Must have rank 1 or higher.\n method: A `Tensor` of type `tf.string`. Fingerprint method used by this op.\n Currently available method is `farmhash64`.\n name: A name for the operation (optional).\n\n Returns:\n A two-dimensional `Tensor` of type `tf.uint8`. The first dimension equals to\n `data`'s first dimension, and the second dimension size depends on the\n fingerprint algorithm.\n \"\"\"\n return gen_array_ops.fingerprint(data, method, name)\n\n\ndef convert_to_int_tensor(tensor, name, dtype=dtypes.int32):\n \"\"\"Converts the given value to an integer Tensor.\"\"\"\n tensor = ops.convert_to_tensor(tensor, name=name, preferred_dtype=dtype)\n if tensor.dtype.is_integer:\n tensor = gen_math_ops.cast(tensor, dtype)\n else:\n raise TypeError(\"%s must be an integer tensor; dtype=%s\" %\n (name, tensor.dtype))\n return tensor\n\n\ndef get_positive_axis(axis, ndims, axis_name=\"axis\", ndims_name=\"ndims\"):\n \"\"\"Validate an `axis` parameter, and normalize it to be positive.\n\n If `ndims` is known (i.e., not `None`), then check that `axis` is in the\n range `-ndims <= axis < ndims`, and return `axis` (if `axis >= 0`) or\n `axis + ndims` (otherwise).\n If `ndims` is not known, and `axis` is positive, then return it as-is.\n If `ndims` is not known, and `axis` is negative, then report an error.\n\n Args:\n axis: An integer constant\n ndims: An integer constant, or `None`\n axis_name: The name of `axis` (for error messages).\n ndims_name: The name of `ndims` (for error messages).\n\n Returns:\n The normalized `axis` value.\n\n Raises:\n ValueError: If `axis` is out-of-bounds, or if `axis` is negative and\n `ndims is None`.\n \"\"\"\n if not isinstance(axis, int):\n raise TypeError(\"%s must be an int; got %s\" %\n (axis_name, type(axis).__name__))\n if ndims is not None:\n if 0 <= axis < ndims:\n return axis\n elif -ndims <= axis < 0:\n return axis + ndims\n else:\n raise ValueError(\"%s=%s out of bounds: expected %s<=%s<%s\" %\n (axis_name, axis, -ndims, axis_name, ndims))\n elif axis < 0:\n raise ValueError(\"%s may only be negative if %s is statically known.\" %\n (axis_name, ndims_name))\n return axis\n\n\n# This op is intended to exactly match the semantics of numpy.repeat, with\n# one exception: numpy.repeat has special (and somewhat non-intuitive) behavior\n# when axis is not specified. Rather than implement that special behavior, we\n# simply make `axis` be a required argument.\n#\n# External (OSS) `tf.repeat` feature request:\n# https://github.com/tensorflow/tensorflow/issues/8246\ndef repeat_with_axis(data, repeats, axis, name=None):\n \"\"\"Repeats elements of `data`.\n\n Args:\n data: An `N`-dimensional tensor.\n repeats: A 1-D integer tensor specifying how many times each element in\n `axis` should be repeated. `len(repeats)` must equal `data.shape[axis]`.\n Supports broadcasting from a scalar value.\n axis: `int`. The axis along which to repeat values. Must be less than\n `max(N, 1)`.\n name: A name for the operation.\n\n Returns:\n A tensor with `max(N, 1)` dimensions. Has the same shape as `data`,\n except that dimension `axis` has size `sum(repeats)`.\n\n Example usage:\n\n >>> repeat(['a', 'b', 'c'], repeats=[3, 0, 2], axis=0)\n <tf.Tensor: shape=(5,), dtype=string,\n numpy=array([b'a', b'a', b'a', b'c', b'c'], dtype=object)>\n >>> repeat([[1, 2], [3, 4]], repeats=[2, 3], axis=0)\n <tf.Tensor: shape=(5, 2), dtype=int32, numpy=\n array([[1, 2],\n [1, 2],\n [3, 4],\n [3, 4],\n [3, 4]], dtype=int32)>\n >>> repeat([[1, 2], [3, 4]], repeats=[2, 3], axis=1)\n <tf.Tensor: shape=(2, 5), dtype=int32, numpy=\n array([[1, 1, 2, 2, 2],\n [3, 3, 4, 4, 4]], dtype=int32)>\n\n \"\"\"\n if not isinstance(axis, int):\n raise TypeError(\"axis must be an int; got %s\" % type(axis).__name__)\n\n with ops.name_scope(name, \"Repeat\", [data, repeats]):\n data = ops.convert_to_tensor(data, name=\"data\")\n repeats = convert_to_int_tensor(repeats, name=\"repeats\")\n repeats.shape.with_rank_at_most(1)\n\n # If `data` is a scalar, then upgrade it to a vector.\n data = _with_nonzero_rank(data)\n data_shape = shape(data)\n\n # If `axis` is negative, then convert it to a positive value.\n axis = get_positive_axis(axis, data.shape.rank, ndims_name=\"rank(data)\")\n\n # If we know that `repeats` is a scalar, then we can just tile & reshape.\n if repeats.shape.num_elements() == 1:\n repeats = reshape(repeats, [])\n expanded = expand_dims(data, axis + 1)\n tiled = tile_one_dimension(expanded, axis + 1, repeats)\n result_shape = concat([\n data_shape[:axis], [repeats * data_shape[axis]], data_shape[axis + 1:]\n ],\n axis=0)\n return reshape(tiled, result_shape)\n\n\n # Check data Tensor shapes.\n if repeats.shape.ndims == 1:\n data.shape.dims[axis].assert_is_compatible_with(repeats.shape[0])\n\n repeats = broadcast_to(repeats, [data_shape[axis]])\n repeats_original = repeats\n\n # Broadcast the `repeats` tensor so rank(repeats) == axis + 1.\n if repeats.shape.ndims != axis + 1:\n repeats_shape = shape(repeats)\n repeats_ndims = rank(repeats)\n broadcast_shape = concat(\n [data_shape[:axis + 1 - repeats_ndims], repeats_shape], axis=0)\n repeats = broadcast_to(repeats, broadcast_shape)\n repeats.set_shape([None] * (axis + 1))\n\n # Create a \"sequence mask\" based on `repeats`, where slices across `axis`\n # contain one `True` value for each repetition. E.g., if\n # `repeats = [3, 1, 2]`, then `mask = [[1, 1, 1], [1, 0, 0], [1, 1, 0]]`.\n max_repeat = gen_math_ops.maximum(\n 0, gen_math_ops._max(repeats, _all_dimensions(repeats)))\n mask = sequence_mask(repeats, max_repeat)\n\n # Add a new dimension around each value that needs to be repeated, and\n # then tile that new dimension to match the maximum number of repetitions.\n expanded = expand_dims(data, axis + 1)\n tiled = tile_one_dimension(expanded, axis + 1, max_repeat)\n\n # Use `boolean_mask` to discard the extra repeated values. This also\n # flattens all dimensions up through `axis`.\n masked = boolean_mask(tiled, mask)\n\n # Reshape the output tensor to add the outer dimensions back.\n if axis == 0:\n result = masked\n else:\n repeated_dim_size = gen_math_ops._sum(\n repeats_original,\n axis=gen_math_ops._range(0, rank(repeats_original), 1))\n result_shape = concat(\n [data_shape[:axis], [repeated_dim_size], data_shape[axis + 1:]],\n axis=0)\n result = reshape(masked, result_shape)\n\n # Preserve shape information.\n if data.shape.ndims is not None:\n new_axis_size = 0 if repeats.shape[0] == 0 else None\n result.set_shape(data.shape[:axis].concatenate(\n [new_axis_size]).concatenate(data.shape[axis + 1:]))\n\n return result\n\n\ndef tile_one_dimension(data, axis, multiple):\n \"\"\"Tiles a single dimension of a tensor.\"\"\"\n # Assumes axis is a nonnegative int.\n if data.shape.ndims is not None:\n multiples = [1] * data.shape.ndims\n multiples[axis] = multiple\n else:\n ones_value = ones(rank(data), dtypes.int32)\n multiples = concat([ones_value[:axis], [multiple], ones_value[axis + 1:]],\n axis=0)\n return tile(data, multiples)\n\n\ndef _with_nonzero_rank(data):\n \"\"\"If `data` is scalar, then add a dimension; otherwise return as-is.\"\"\"\n if data.shape.ndims is not None:\n if data.shape.ndims == 0:\n return stack([data])\n else:\n return data\n else:\n data_shape = shape(data)\n data_ndims = rank(data)\n return reshape(data, concat([[1], data_shape], axis=0)[-data_ndims:])\n\n\n@tf_export(\"repeat\")\ndef repeat(input, repeats, axis=None, name=None): # pylint: disable=redefined-builtin\n \"\"\"Repeat elements of `input`.\n \n See also `tf.concat`, `tf.stack`, `tf.tile`.\n\n Args:\n input: An `N`-dimensional Tensor.\n repeats: An 1-D `int` Tensor. The number of repetitions for each element.\n repeats is broadcasted to fit the shape of the given axis. `len(repeats)`\n must equal `input.shape[axis]` if axis is not None.\n axis: An int. The axis along which to repeat values. By default (axis=None),\n use the flattened input array, and return a flat output array.\n name: A name for the operation.\n\n Returns:\n A Tensor which has the same shape as `input`, except along the given axis.\n If axis is None then the output array is flattened to match the flattened\n input array.\n\n Example usage:\n\n >>> repeat(['a', 'b', 'c'], repeats=[3, 0, 2], axis=0)\n <tf.Tensor: shape=(5,), dtype=string,\n numpy=array([b'a', b'a', b'a', b'c', b'c'], dtype=object)>\n\n >>> repeat([[1, 2], [3, 4]], repeats=[2, 3], axis=0)\n <tf.Tensor: shape=(5, 2), dtype=int32, numpy=\n array([[1, 2],\n [1, 2],\n [3, 4],\n [3, 4],\n [3, 4]], dtype=int32)>\n\n >>> repeat([[1, 2], [3, 4]], repeats=[2, 3], axis=1)\n <tf.Tensor: shape=(2, 5), dtype=int32, numpy=\n array([[1, 1, 2, 2, 2],\n [3, 3, 4, 4, 4]], dtype=int32)>\n\n >>> repeat(3, repeats=4)\n <tf.Tensor: shape=(4,), dtype=int32, numpy=array([3, 3, 3, 3], dtype=int32)>\n\n >>> repeat([[1,2], [3,4]], repeats=2)\n <tf.Tensor: shape=(8,), dtype=int32,\n numpy=array([1, 1, 2, 2, 3, 3, 4, 4], dtype=int32)>\n\n \"\"\"\n if axis is None:\n input = reshape(input, [-1])\n axis = 0\n return repeat_with_axis(input, repeats, axis, name)\n"
] | [
[
"tensorflow.python.ops.gen_math_ops.select_v2",
"tensorflow.python.util.tf_decorator.make_decorator",
"tensorflow.python.ops.gen_array_ops.list_diff",
"tensorflow.python.framework.ops.RegisterGradient",
"tensorflow.python.ops.gen_array_ops.strided_slice",
"tensorflow.python.ops.gen_array_ops.dequantize",
"tensorflow.python.util.tf_export.tf_export",
"tensorflow.python.ops.gen_array_ops.rank",
"tensorflow.python.ops.gen_array_ops.identity",
"tensorflow.python.ops.gen_array_ops.matrix_diag_v3",
"tensorflow.python.ops.gen_array_ops.quantize_and_dequantize_v2",
"tensorflow.python.ops.gen_array_ops.reshape",
"tensorflow.python.ops.gen_array_ops.split",
"tensorflow.python.ops.gen_array_ops.unique_with_counts",
"tensorflow.python.ops.gen_array_ops.placeholder",
"tensorflow.python.util.deprecation.deprecated_args",
"tensorflow.python.ops.gen_array_ops.extract_image_patches",
"numpy.array",
"tensorflow.python.ops.gen_array_ops.pack",
"tensorflow.python.ops.gen_array_ops.edit_distance",
"tensorflow.python.ops.gen_array_ops.size",
"tensorflow.python.util.nest.flatten",
"tensorflow.python.ops.gen_math_ops._range",
"tensorflow.python.ops.gen_array_ops.unique",
"tensorflow.python.ops.gen_array_ops.squeeze",
"tensorflow.python.ops.gen_array_ops.quantize_v2",
"tensorflow.python.ops.gen_array_ops.space_to_depth",
"tensorflow.python.ops.gen_array_ops.where",
"tensorflow.python.ops.gen_array_ops.concat_v2",
"tensorflow.python.ops.gen_array_ops.one_hot",
"tensorflow.python.framework.common_shapes.broadcast_shape",
"tensorflow.python.ops.gen_array_ops.pad",
"tensorflow.python.framework.tensor_util.maybe_set_static_shape",
"tensorflow.python.framework.dtypes.as_dtype",
"tensorflow.python.ops.gen_array_ops.matrix_set_diag_v3",
"tensorflow.python.framework.ops.Tensor._override_operator",
"tensorflow.python.framework.ops.convert_to_tensor",
"tensorflow.python.framework.tensor_shape.unknown_shape",
"numpy.isscalar",
"tensorflow.python.ops.gen_array_ops.fill",
"tensorflow.python.ops.gen_array_ops.matrix_diag_part_v3",
"tensorflow.python.ops.gen_array_ops.reverse_sequence",
"tensorflow.python.framework.tensor_util.constant_value_as_shape",
"tensorflow.python.util.deprecation.deprecated_endpoints",
"tensorflow.python.ops.gen_array_ops.split_v",
"tensorflow.python.eager.context.executing_eagerly",
"tensorflow.python.framework.ops.IndexedSlices",
"tensorflow.python.framework.tensor_util.constant_value",
"tensorflow.python.ops.gen_array_ops.depth_to_space",
"tensorflow.python.ops.gen_array_ops.lower_bound",
"tensorflow.python.framework.ops.register_tensor_conversion_function",
"tensorflow.python.ops.gen_array_ops.unpack",
"tensorflow.python.framework.tensor_util.is_tensor",
"tensorflow.python.ops.gen_array_ops.gather_nd",
"tensorflow.python.framework.tensor_shape.is_fully_defined",
"tensorflow.python.ops.gen_math_ops.cast",
"tensorflow.python.framework.ops.name_scope",
"tensorflow.python.ops.gen_array_ops.shape",
"tensorflow.python.util.deprecation.deprecated_argument_lookup",
"tensorflow.python.framework.tensor_shape.TensorShape",
"tensorflow.python.ops.gen_math_ops.select",
"tensorflow.python.ops.gen_array_ops.gather_v2",
"tensorflow.python.ops.gen_math_ops.prod",
"tensorflow.python.ops.gen_array_ops.fingerprint",
"tensorflow.python.ops.gen_array_ops.placeholder_with_default",
"tensorflow.python.ops.gen_array_ops.upper_bound",
"numpy.arange",
"tensorflow.python.util.nest.map_structure",
"tensorflow.python.ops.gen_array_ops.broadcast_args",
"tensorflow.python.util.deprecation.deprecated",
"tensorflow.python.ops.gen_array_ops.pad_v2",
"tensorflow.python.ops.gen_array_ops.zeros_like",
"tensorflow.python.ops.gen_array_ops.shape_n",
"tensorflow.python.ops.gen_array_ops._slice",
"tensorflow.python.ops.gen_array_ops.mirror_pad",
"tensorflow.python.ops.gen_array_ops.expand_dims",
"numpy.prod",
"tensorflow.python.framework.tensor_shape.as_shape",
"tensorflow.python.framework.constant_op.constant"
]
] |
thomas-li-sjtu/InterpretablePPSM | [
"72d6190c39cd80dbde562d99e813ebb1ba1be0e2"
] | [
"input_pipeline.py"
] | [
"import numpy as np\nimport tensorflow as tf\nimport os\nimport myPickle\n\nXNAME = 'X.txt'\nCMNAME = 'charmap.pickle'\nENCODING = 'ascii'\nbuffer_size = 10000\n\n# Special tokens\nMASK = 3\nEND = 2\nPAD = 0\n################\n\nMAX_MASKED = .3\n\n\n# def mask(x, xl):\n# if INCLUDE_END_SYMBOL: xl -= 1\n# k = np.random.randint(0, xl)\n# y = x[k]\n# x[k] = MASK\n# return x, [y], [k]\n\ndef mask(x_index_copy, x_len, MAX_MASKED, INCLUDE_END_SYMBOL):\n if INCLUDE_END_SYMBOL:\n x_len -= 1\n\n if MAX_MASKED == -1:\n # single missing\n masked_index = [np.random.randint(0, x_len)]\n else:\n # 随机选择mask的下标\n num_masked = int(x_len * MAX_MASKED)\n removed = []\n masked_index = np.random.randint(0, x_len, size=num_masked)\n\n # 将kk中的下标mask\n for k in masked_index:\n x_index_copy[k] = MASK\n\n return x_index_copy, [], masked_index\n\n\ndef idx2string(P, CM_):\n return ''.join([CM_[p] for p in P if p > 0 and p != END])\n\n\ndef string2idx(x, CM, MAX_LEN, CMm, INCLUDE_END_SYMBOL):\n f = lambda x: CM[x] if x in CM else CMm # 匿名函数,map函数通过此匿名函数的charmap将字符映射为数字\n x = list(map(f, x))\n if INCLUDE_END_SYMBOL:\n x += [END] # 增加结尾符\n x += [0] * (MAX_LEN - len(x)) # 将每个口令补齐到相同长度\n return np.array(x)\n\n\ndef makeIterInput(home, batch_size, MAX_MASKED, INCLUDE_END_SYMBOL, MAX_LEN=32, buffer_size=buffer_size,\n for_prediction=False):\n XPATH = os.path.join(home, XNAME) # 数据集路径\n\n CMPATH = os.path.join(home, CMNAME)\n CM = myPickle.load(CMPATH) # 导入charmap\n vocab_size = max(CM.values()) + 1 # 字典大小\n\n def G(*args):\n \"\"\"\n 生成器\n Args:\n *args:\n Returns:\n \"\"\"\n # for each chunk\n with open(XPATH, encoding=ENCODING, errors='ignore') as f:\n for x in f:\n x = x[:-1] # 去除最后的换行符\n x_len = len(x)\n\n # if not INCLUDE_END_SYMBOL: print(\"NO <END>\")\n\n if x_len > MAX_LEN - int(INCLUDE_END_SYMBOL): # 需要留下INCLUDE_END_SYMBOL长度的字符作为口令结尾\n # 口令过长\n continue\n\n x_index = string2idx(x, CM, MAX_LEN, vocab_size, INCLUDE_END_SYMBOL) # 口令在charmap下的对应下标列表,长度补全\n\n # .copy()复制新的列表——列表第一层为深拷贝\n # 随机选择部分下标将其遮盖,返回遮盖后的结果和遮盖的下标\n x_index_in, _, masked_index = mask(x_index.copy(), x_len, MAX_MASKED, INCLUDE_END_SYMBOL)\n\n prediction_mask = np.zeros(MAX_LEN, np.int32) # 对遮盖后的结果取反,获得类似[0,0,0,1,0,0]的结果\n for k in masked_index:\n prediction_mask[k] = 1\n\n xi_out = x_index\n\n yield x_index_in, prediction_mask, xi_out\n\n # 构造数据集(以管道的方式输入网络训练) 输入生成器,输出类型和输出shape,None表明shape自动生成;输出的元组由生成器的输出决定\n dataset = tf.data.Dataset.from_generator(G, (tf.int32, tf.int32, tf.int32), ((None,), (None,), (None,)))\n\n if not for_prediction:\n # 以 batch_size 打乱数据集\n dataset = dataset.shuffle(buffer_size)\n # padded_shapes = (\n # tf.TensorShape([None]),\n # tf.TensorShape([None]),\n # tf.TensorShape([None])\n # )\n # dataset = dataset.padded_batch(batch_size, padded_shapes=padded_shapes, drop_remainder=True)\n\n # 将此数据集的多个连续元素 (可能具有不同的形状) 合并到单个元素中。结果元素中的张量有一个额外的外部维度, 并填充到 padded_shapes 中的相应形状\n dataset = dataset.padded_batch(batch_size, drop_remainder=True) # 这里是源码,有错误,需要用上面的语句替代\n dataset = dataset.prefetch(buffer_size=buffer_size) # 预取数据,将生成数据的时间和使用数据的时间分离,在请求元素之前从输入数据集中预取这些元素\n\n return dataset, vocab_size + 1, CM\n"
] | [
[
"numpy.array",
"numpy.zeros",
"tensorflow.data.Dataset.from_generator",
"numpy.random.randint"
]
] |
ddh-mulder/carvana-challenge | [
"a02626b5a9e06805d1e56a6f3a676216358dbba5"
] | [
"src/nn/losses.py"
] | [
"import torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass BCELoss2d(nn.Module):\n def __init__(self, weight=None, size_average=True):\n super(BCELoss2d, self).__init__()\n self.bce_loss = nn.BCELoss(weight, size_average)\n\n def forward(self, logits, targets):\n probs = F.sigmoid(logits)\n probs_flat = probs.view(-1)\n targets_flat = targets.view(-1)\n return self.bce_loss(probs_flat, targets_flat)\n\n\nclass SoftDiceLoss(nn.Module):\n def __init__(self, weight=None, size_average=True):\n super(SoftDiceLoss, self).__init__()\n\n def forward(self, logits, targets):\n num = targets.size(0)\n probs = F.sigmoid(logits)\n m1 = probs.view(num, -1)\n m2 = targets.view(num, -1)\n intersection = (m1 * m2)\n\n score = 2. * (intersection.sum(1) + 1) / (m1.sum(1) + m2.sum(1) + 1)\n score = 1 - score.sum() / num\n return score\n\n\n# https://github.com/pytorch/pytorch/issues/1249\ndef dice_coeff(pred, target):\n smooth = 1.\n num = pred.size(0)\n m1 = pred.view(num, -1) # Flatten\n m2 = target.view(num, -1) # Flatten\n intersection = (m1 * m2).sum()\n\n return (2. * intersection + smooth) / (m1.sum() + m2.sum() + smooth)\n"
] | [
[
"torch.nn.functional.sigmoid",
"torch.nn.BCELoss"
]
] |
basiralab/Kaggle-BrainNetPrediction-Toolbox | [
"1080c2b59cea98fb72e1e24578e1796e206b5131"
] | [
"Team 8/findparams.py"
] | [
"\"\"\"\nThis code uses built-in cross validation to find the most optimal hyper parameters for each model that is used in the mapping function.\nIt is recommended but not required to run this code before running main code to get a stronger model. Please keep in mind that running\nthis code uses all the cpu cores available, and will probably take a lot of time\n\"\"\"\nimport pandas as pd\nfrom sklearn.ensemble import GradientBoostingRegressor, AdaBoostRegressor\nfrom sklearn.model_selection import RandomizedSearchCV, GridSearchCV\nfrom sklearn.feature_selection import SelectKBest, mutual_info_regression\nfrom sklearn.neighbors import KNeighborsRegressor\nfrom sklearn.pipeline import Pipeline\n\ndef create_pipeline(regressor):\n \"\"\"\n Parameters:\n regressor: Regressor object instance to be optimized.\n ---------------------------------------------------------------------\n Creates a pipeline object that can be used in RandomizedGridSearchCV.\n Pipelines consist of a feature selection algorithm SelectKBest that\n reduces the number of features to 20, and a regressor.\n \"\"\"\n return Pipeline([\n (\"selector\", SelectKBest(mutual_info_regression, k=350)),\n (\"regressor\", regressor)\n ])\n\ndef grad_params(data, label):\n \"\"\"\n Parameters:\n data: The training data that will be used for classification.\n label: The dataset that contains all the labels.\n ---------------------------------------------------------------\n This function will iterate over each of 595 labels and performs\n 3-fold cross-validation to split the training data into test\n and train groups. Then it trains the given base model (Gradient\n boosting regressor in this case) 50 times and compares the\n results. Then it chooses the best results and saves it in the\n DataFrame. After performing this for each label, the function\n writes the parameters into a csv file.\n \"\"\"\n\n param_dist = {\n \"regressor__n_estimators\": [5, 10, 25, 50], #number of base models to be trained\n \"regressor__learning_rate\": [0.01, 0.1, 0.5, 0.7, 1], #multiplies the contribution of each tree with this\n \"regressor__loss\": [\"ls\", \"lad\", \"huber\", \"quantile\"], #loss function to minimize\n \"regressor__alpha\": [0.1, 0.5, 0.9], #alpha value for huber and quantile loss functions\n \"regressor__max_depth\": [2, 3] #max depth of the base DecisionTreeRegressor\n }\n #initialize dataframe to store\n param = pd.DataFrame(index=[\"n_estimators\", \"max_depth\", \"loss\", \"learning_rate\", \"alpha\"])\n print(\"Start optimizing GradientBoostingRegressor\")\n for col in label: #iterates over the labels while training a model each time\n print(col)\n #creates pipeline\n pipeline = create_pipeline(GradientBoostingRegressor())\n #built-in cross-validation searcher\n params = RandomizedSearchCV(pipeline,\n param_distributions = param_dist,\n cv=3,\n n_iter=25,\n n_jobs=-1,\n refit = False,\n scoring = \"neg_mean_squared_error\"\n )\n params.fit(data, label[col])\n #stores best parameters\n param[col] = params.best_params_.values()\n #writes found parameters to file\n param.to_csv(\"grad_params.csv\", index_label=\"ID\")\n\ndef knr_params(data, label):\n \"\"\"\n Parameters:\n data: The training data that will be used for classification.\n label: The dataset that contains all the labels.\n ---------------------------------------------------------------\n Same as grad_params function, but this function finds optimal\n parameters for K Neighbors Regressor model.\n \"\"\"\n param_dist = {\n \"regressor__n_neighbors\": [3,5,7,10,15,20,50], #number of neighbors to use\n \"regressor__weights\": [\"uniform\", \"distance\"], #weight function to use in prediction\n \"regressor__algorithm\": [\"auto\", \"ball_tree\", \"kd_tree\", \"brute\"], #algorithm to compute nearest neighbors\n \"regressor__p\": [1, 2] #1 means manhattan distance, 2 means euclidian distance\n }\n\n param = pd.DataFrame(index=[\"algorithm\", \"n_neighbors\", \"p\", \"weights\"])\n print(\"Start optimizing KNeighborsRegression\")\n for col in y_train:\n print(col)\n #creates pipeline\n pipeline = create_pipeline(KNeighborsRegressor())\n #built-in cross-validation searcher\n params = RandomizedSearchCV(pipeline,\n param_distributions = param_dist,\n cv = 3,\n n_iter = 25,\n n_jobs = -1,\n refit = False,\n scoring = \"neg_mean_squared_error\"\n )\n params.fit(data, label[col])\n #stores best parameters\n param[col] = params.best_params_.values()\n #writes found parameters to file\n param.to_csv(\"knr_params.csv\", index_label=\"ID\")\n\ndef ada_params(data, label):\n \"\"\"\n Parameters:\n data: The training data that will be used for classification.\n label: The dataset that contains all the labels.\n ---------------------------------------------------------------\n Same as grad_params function, but this function finds optimal\n parameters for Ada Boosting Regressor model.\n \"\"\"\n param_dist = {\n \"regressor__n_estimators\": [5, 10, 25, 50],\n \"regressor__learning_rate\": [0.01, 0.05, 0.1, 0.3, 0.7, 1],\n \"regressor__loss\": [\"linear\", \"square\", \"exponential\"]\n }\n\n param = pd.DataFrame(index=[\"learning_rate\", \"loss\", \"n_estimators\"])\n print(\"Start optimizing AdaBoostingRegresion\")\n for col in y_train:\n print(col)\n #creates pipeline\n pipeline = create_pipeline(AdaBoostRegressor())\n #built-in cross-validation searcher\n params = RandomizedSearchCV(pipeline,\n param_distributions = param_dist,\n cv = 3,\n n_iter = 25,\n n_jobs = -1,\n refit = False,\n scoring = \"neg_mean_squared_error\"\n )\n params.fit(data, label[col])\n #stores best parameters\n param[col] = params.best_params_.values()\n #writes found parameters to file\n param.to_csv(\"params.csv\", index_label=\"ID\")\n\nX_train, y_train = pd.read_csv(\"data/train_t0.csv\", index_col=\"ID\"), pd.read_csv(\"data/train_t1.csv\", index_col=\"ID\")\n\ngrad_params(X_train, y_train)\n\nknr_params(X_train, y_train)\n\nada_params(X_train, y_train)"
] | [
[
"pandas.read_csv",
"sklearn.model_selection.RandomizedSearchCV",
"pandas.DataFrame",
"sklearn.ensemble.GradientBoostingRegressor",
"sklearn.neighbors.KNeighborsRegressor",
"sklearn.feature_selection.SelectKBest",
"sklearn.ensemble.AdaBoostRegressor"
]
] |
stibbs1998/admissions_internship | [
"43d0bd7152493966391418ffe21f844db4997f45"
] | [
"src/data/locate_school.py"
] | [
"############################\n############################\n\n# Import libraries\n\nimport numpy as np\nimport pandas as pd\nimport pickle as pkl\nimport operator\nimport warnings\nimport csv\nwarnings.filterwarnings('ignore')\n\n# Import a ProgressBar\n\nfrom progressbar import ProgressBar\npbar = ProgressBar()\n\n############################\n############################\n\n# Import the .csv file without HEOP or Albany Med applicants.\n\ndf = pd.read_csv('../../data/processed/CriticalPath_Data_EM_Confidential_lessNoise.csv')\n\n# Import the .csv file taken from https://ope.ed.gov/dapip/#/home.\n\nhd2017_df = pd.read_csv('../../data/external/hd2017.csv',encoding='ISO-8859-1')\n\n# Convert all of the school names to UPPER CASE. \n\nhd2017_df['INSTNM'] = hd2017_df['INSTNM'].str.upper()\n\n############################ \n############################\n\n# Get a Series of all schools which names match up perfectly to a school name we have in our .csv file.\n\nschools_in_our_df = hd2017_df[hd2017_df['INSTNM'].isin(df['College_chosen_by_non-matrics'])]\n\n# Get a Series of all schools which names do NOT match up to a school name we have in our .csv file.\n\nschools_not_in_our_df = hd2017_df[~hd2017_df['INSTNM'].isin(df['College_chosen_by_non-matrics'])]\n\nprint(schools_not_in_our_df['INSTNM'])\n# Get a list of all the schools in our .csv file with no match.\n\nnon_mapped_schools = list(set(df['College_chosen_by_non-matrics'].unique()) - set(schools_in_our_df['INSTNM']))\n\nprint(len(df['College_chosen_by_non-matrics'].unique()))\nprint(len(schools_in_our_df['INSTNM']))\n\n############################\n############################\n\n# List of common words that should not be included in the following for loop.\n\nbad_words = ['THE','OR','OF','AND','COUNTY','COLLEGE','-','STATE','UNIVERSITY','&',' ',' ','NORTH','WEST','SOUTH','EAST']\n\n# Initialize a dictionary that maps the names of the schools we have to their name in the government data file.\n# We first add all of the correctly named schools to this dictionary.\n\nmapper = dict(zip(schools_in_our_df['INSTNM'],schools_in_our_df['INSTNM']))\n\n############################\n############################\n\n# This loop breaks down each instituion name word by word from both the gov't file and our admissions data file.\n# The nested loop checks the name of each institution from the gov't file against the name from the admissions data file word-by-word.\n# For each word that matches up, a 'point' is added to the name's 'score'.\n# The highest 'score' is deemed to be closest in name to one another, and we add this as a key and value to the 'mapper' dictionary.\n# This seems to be roughly 90% reliable. If a school has a score of 0 for every other school, we ignore it for the purpose of this project.\n\nfor unknown in pbar(non_mapped_schools[1:]): # the first entry is NaN\n\n# Strip all extra spaces, hyphens and split the string into a list delimited on the spaces.\n\n\tunknown_str = unknown.replace('-',' ')\n\tunknown_str = unknown_str.replace(' ',' ')\n\tunknown_str = unknown_str.replace('\\t',' ')\n\tunknown_str = unknown_str.replace(' ',' ')\n\tunknown_str = unknown_str.replace(' ',' ').strip()\n\tunknown_str = unknown.upper().split(' ')\n\n\tscores = {} # dictionary for list of scores\n\n\tfor school in schools_not_in_our_df['INSTNM']:\n\n# Strip all extra spaces and hyphens.\n\n\t\tschool_str = school.replace('-',' ')\n\t\tschool_str = school_str.replace(' ',' ')\n\t\tschool_str = school_str.replace('\\t',' ')\n\t\tschool_str = school_str.replace(' ',' ')\n\t\tschool_str = school_str.replace(' ',' ').strip()\n\n\t\tif \"LYLE\" not in school_str: # Lyle's School of Beauty caused a ton of problems, everything is better without it.\n\n\t\t\tscores[school] = 0 # every school starts with a score of 0\n\n\t\t\tfor word in unknown_str:\n\n\t\t\t\tif word.upper() not in bad_words and word.upper() in school_str.strip().upper().split(' '):\n\n\t\t\t\t\tscores[school] += 1 # a word matched! Add a point\n\t\t\t\telif word.upper() in ['ST.','ST','SAINT'] and any(x in ['ST.','ST','SAINT'] for x in school_str.strip().upper().split(' ')):\n\t\t\t\t\tscores[school] += 1 # Saint/St/St. appears in both! close enough! Add a point\n\n\t\tschool_name = max(scores.items(), key=operator.itemgetter(1))[0] # Get the key name for the maximum value.\n\n\t\tif scores[school_name]>0: # Make sure the maximum value isn't zero.\n\n\t\t\tmapper[unknown] = school_name # Add this to the mapping dictionary.\n\n############################\n############################\n\n# Write to file.\n\nwith open('../../data/processed/college_name_mapper.csv', 'w') as csv_file:\n\twriter = csv.writer(csv_file)\n\twriter.writerow([\"CCBNM\",\"DAPIP\"])\n\tfor key, value in mapper.items():\n\t\twriter.writerow([key, value])\n\n"
] | [
[
"pandas.read_csv"
]
] |
fanhenghui/NiftyNet | [
"1f740b554dfdf06be28899658a71218c4dcc2104"
] | [
"niftynet/engine/application_factory.py"
] | [
"# -*- coding: utf-8 -*-\n\"\"\"\nLoading modules from a string representing the class name\nor a short name that matches the dictionary item defined\nin this module\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport importlib\nimport os\n\nimport tensorflow as tf\n\nfrom niftynet.utilities.util_common import \\\n damerau_levenshtein_distance as edit_distance\n\n# pylint: disable=too-few-public-methods\nSUPPORTED_APP = {\n 'net_regress':\n 'niftynet.application.regression_application.RegressionApplication',\n 'net_segment':\n 'niftynet.application.segmentation_application.SegmentationApplication',\n 'net_autoencoder':\n 'niftynet.application.autoencoder_application.AutoencoderApplication',\n 'net_gan':\n 'niftynet.application.gan_application.GANApplication',\n 'net_classify':\n 'niftynet.application.classification_application.'\n 'ClassificationApplication',\n}\n\nSUPPORTED_NETWORK = {\n # GAN\n 'simulator_gan':\n 'niftynet.network.simulator_gan.SimulatorGAN',\n 'simple_gan':\n 'niftynet.network.simple_gan.SimpleGAN',\n\n # Segmentation\n \"highres3dnet\":\n 'niftynet.network.highres3dnet.HighRes3DNet',\n \"highres3dnet_small\":\n 'niftynet.network.highres3dnet_small.HighRes3DNetSmall',\n \"highres3dnet_large\":\n 'niftynet.network.highres3dnet_large.HighRes3DNetLarge',\n \"toynet\":\n 'niftynet.network.toynet.ToyNet',\n \"unet\":\n 'niftynet.network.unet.UNet3D',\n \"vnet\":\n 'niftynet.network.vnet.VNet',\n \"dense_vnet\":\n 'niftynet.network.dense_vnet.DenseVNet',\n \"deepmedic\":\n 'niftynet.network.deepmedic.DeepMedic',\n \"scalenet\":\n 'niftynet.network.scalenet.ScaleNet',\n \"holisticnet\":\n 'niftynet.network.holistic_net.HolisticNet',\n\n # classification\n \"resnet\": 'niftynet.network.resnet.ResNet',\n\n # autoencoder\n \"vae\": 'niftynet.network.vae.VAE'\n}\n\nSUPPORTED_LOSS_GAN = {\n 'CrossEntropy': 'niftynet.layer.loss_gan.cross_entropy',\n}\n\nSUPPORTED_LOSS_SEGMENTATION = {\n \"CrossEntropy\":\n 'niftynet.layer.loss_segmentation.cross_entropy',\n \"Dice\":\n 'niftynet.layer.loss_segmentation.dice',\n \"Dice_NS\":\n 'niftynet.layer.loss_segmentation.dice_nosquare',\n \"Dice_Dense\":\n 'niftynet.layer.loss_segmentation.dice_dense',\n \"GDSC\":\n 'niftynet.layer.loss_segmentation.generalised_dice_loss',\n \"WGDL\":\n 'niftynet.layer.loss_segmentation.generalised_wasserstein_dice_loss',\n \"SensSpec\":\n 'niftynet.layer.loss_segmentation.sensitivity_specificity_loss',\n \"L1Loss\":\n 'niftynet.layer.loss_segmentation.l1_loss',\n \"L2Loss\":\n 'niftynet.layer.loss_segmentation.l2_loss',\n \"Huber\":\n 'niftynet.layer.loss_segmentation.huber_loss'\n}\n\nSUPPORTED_LOSS_REGRESSION = {\n \"L1Loss\":\n 'niftynet.layer.loss_regression.l1_loss',\n \"L2Loss\":\n 'niftynet.layer.loss_regression.l2_loss',\n \"RMSE\":\n 'niftynet.layer.loss_regression.rmse_loss',\n \"MAE\":\n 'niftynet.layer.loss_regression.mae_loss',\n \"Huber\":\n 'niftynet.layer.loss_regression.huber_loss'\n}\n\nSUPPORTED_LOSS_CLASSIFICATION = {\n \"CrossEntropy\":\n 'niftynet.layer.loss_classification.cross_entropy',\n}\n\n\nSUPPORTED_LOSS_AUTOENCODER = {\n \"VariationalLowerBound\":\n 'niftynet.layer.loss_autoencoder.variational_lower_bound',\n}\n\nSUPPORTED_OPTIMIZERS = {\n 'adam': 'niftynet.engine.application_optimiser.Adam',\n 'gradientdescent': 'niftynet.engine.application_optimiser.GradientDescent',\n 'momentum': 'niftynet.engine.application_optimiser.Momentum',\n 'nesterov': 'niftynet.engine.application_optimiser.NesterovMomentum',\n\n 'adagrad': 'niftynet.engine.application_optimiser.Adagrad',\n 'rmsprop': 'niftynet.engine.application_optimiser.RMSProp',\n}\n\nSUPPORTED_INITIALIZATIONS = {\n 'constant': 'niftynet.engine.application_initializer.Constant',\n 'zeros': 'niftynet.engine.application_initializer.Zeros',\n 'ones': 'niftynet.engine.application_initializer.Ones',\n 'uniform_scaling':\n 'niftynet.engine.application_initializer.UniformUnitScaling',\n 'orthogonal': 'niftynet.engine.application_initializer.Orthogonal',\n 'variance_scaling':\n 'niftynet.engine.application_initializer.VarianceScaling',\n 'glorot_normal':\n 'niftynet.engine.application_initializer.GlorotNormal',\n 'glorot_uniform':\n 'niftynet.engine.application_initializer.GlorotUniform',\n 'he_normal': 'niftynet.engine.application_initializer.HeNormal',\n 'he_uniform': 'niftynet.engine.application_initializer.HeUniform'\n}\n\nSUPPORTED_EVALUATIONS = {\n 'dice': 'niftynet.evaluation.segmentation_evaluations.dice',\n 'jaccard': 'niftynet.evaluation.segmentation_evaluations.jaccard',\n 'Dice': 'niftynet.evaluation.segmentation_evaluations.dice',\n 'Jaccard': 'niftynet.evaluation.segmentation_evaluations.jaccard',\n 'n_pos_ref': 'niftynet.evaluation.segmentation_evaluations.n_pos_ref',\n 'n_neg_ref': 'niftynet.evaluation.segmentation_evaluations.n_neg_ref',\n 'n_pos_seg': 'niftynet.evaluation.segmentation_evaluations.n_pos_seg',\n 'n_neg_seg': 'niftynet.evaluation.segmentation_evaluations.n_neg_seg',\n 'fp': 'niftynet.evaluation.segmentation_evaluations.fp',\n 'fn': 'niftynet.evaluation.segmentation_evaluations.fn',\n 'tp': 'niftynet.evaluation.segmentation_evaluations.tp',\n 'tn': 'niftynet.evaluation.segmentation_evaluations.tn',\n 'n_intersection': 'niftynet.evaluation.segmentation_evaluations'\n '.n_intersection',\n 'n_union': 'niftynet.evaluation.segmentation_evaluations.n_union',\n 'specificity': 'niftynet.evaluation.segmentation_evaluations.specificity',\n 'sensitivity': 'niftynet.evaluation.segmentation_evaluations.sensitivity',\n 'accuracy': 'niftynet.evaluation.segmentation_evaluations.accuracy',\n 'false_positive_rate': 'niftynet.evaluation.segmentation_evaluations'\n '.false_positive_rate',\n 'positive_predictive_values': 'niftynet.evaluation.segmentation_evaluations'\n '.positive_predictive_values',\n 'negative_predictive_values': 'niftynet.evaluation.segmentation_evaluations'\n '.negative_predictive_values',\n 'intersection_over_union': 'niftynet.evaluation.segmentation_evaluations'\n '.intersection_over_union',\n 'informedness': 'niftynet.evaluation.segmentation_evaluations.informedness',\n 'markedness': 'niftynet.evaluation.segmentation_evaluations.markedness',\n 'vol_diff': 'niftynet.evaluation.segmentation_evaluations.vol_diff',\n 'average_distance': 'niftynet.evaluation.segmentation_evaluations'\n '.average_distance',\n 'hausdorff_distance': 'niftynet.evaluation.segmentation_evaluations'\n '.hausdorff_distance',\n 'hausdorff95_distance': 'niftynet.evaluation.segmentation_evaluations'\n '.hausdorff95_distance',\n 'com_ref': 'niftynet.contrib.evaluation.segmentation_evaluations.com_ref',\n 'mse': 'niftynet.evaluation.regression_evaluations.mse',\n 'rmse': 'niftynet.evaluation.regression_evaluations.rmse',\n 'mae': 'niftynet.evaluation.regression_evaluations.mae',\n 'r2': 'niftynet.contrib.evaluation.regression_evaluations.r2',\n 'classification_accuracy': 'niftynet.evaluation.classification_evaluations'\n '.accuracy',\n 'roc_auc': 'niftynet.contrib.evaluation.classification_evaluations.roc_auc',\n 'roc': 'niftynet.contrib.evaluation.classification_evaluations.roc',\n}\n\ndef select_module(module_name, type_str, lookup_table):\n \"\"\"\n This function first tries to find the absolute module name\n by matching the static dictionary items, if not found, it\n tries to import the module by splitting the input ``module_name``\n as module name and class name to be imported.\n\n :param module_name: string that matches the keys defined in lookup_table\n or an absolute class name: module.name.ClassName\n :param type_str: type of the module (used for better error display)\n :param lookup_table: defines a set of shorthands for absolute class name\n \"\"\"\n module_name = '{}'.format(module_name)\n if module_name in lookup_table:\n module_name = lookup_table[module_name]\n module_str, class_name = None, None\n try:\n module_str, class_name = module_name.rsplit('.', 1)\n the_module = importlib.import_module(module_str)\n the_class = getattr(the_module, class_name)\n tf.logging.info('Import [%s] from %s.',\n class_name, os.path.abspath(the_module.__file__))\n return the_class\n except (AttributeError, ValueError, ImportError) as not_imported:\n # print sys.path\n tf.logging.fatal(repr(not_imported))\n # Two possibilities: a typo for a lookup table entry\n # or a non-existing module\n dists = dict((k, edit_distance(k, module_name))\n for k in list(lookup_table))\n closest = min(dists, key=dists.get)\n if dists[closest] <= 3:\n err = 'Could not import {2}: By \"{0}\", ' \\\n 'did you mean \"{1}\"?\\n \"{0}\" is ' \\\n 'not a valid option. '.format(module_name, closest, type_str)\n tf.logging.fatal(err)\n raise ValueError(err)\n else:\n if '.' not in module_name:\n err = 'Could not import {}: ' \\\n 'Incorrect module name format {}. ' \\\n 'Expected \"module.object\".'.format(type_str, module_name)\n tf.logging.fatal(err)\n raise ValueError(err)\n err = '{}: Could not import object' \\\n '\"{}\" from \"{}\"'.format(type_str, class_name, module_str)\n tf.logging.fatal(err)\n raise ValueError(err)\n\n\nclass ModuleFactory(object):\n \"\"\"\n General interface for importing a class by its name.\n \"\"\"\n SUPPORTED = None\n type_str = 'object'\n\n @classmethod\n def create(cls, name):\n \"\"\"\n import a class by name\n \"\"\"\n return select_module(name, cls.type_str, cls.SUPPORTED)\n\n\nclass ApplicationNetFactory(ModuleFactory):\n \"\"\"\n Import a network from ``niftynet.network`` or from user specified string\n \"\"\"\n SUPPORTED = SUPPORTED_NETWORK\n type_str = 'network'\n\n\nclass ApplicationFactory(ModuleFactory):\n \"\"\"\n Import an application from ``niftynet.application`` or\n from user specified string\n \"\"\"\n SUPPORTED = SUPPORTED_APP\n type_str = 'application'\n\n\nclass LossGANFactory(ModuleFactory):\n \"\"\"\n Import a GAN loss function from ``niftynet.layer`` or\n from user specified string\n \"\"\"\n SUPPORTED = SUPPORTED_LOSS_GAN\n type_str = 'GAN loss'\n\n\nclass LossSegmentationFactory(ModuleFactory):\n \"\"\"\n Import a segmentation loss function from ``niftynet.layer`` or\n from user specified string\n \"\"\"\n SUPPORTED = SUPPORTED_LOSS_SEGMENTATION\n type_str = 'segmentation loss'\n\n\nclass LossRegressionFactory(ModuleFactory):\n \"\"\"\n Import a regression loss function from ``niftynet.layer`` or\n from user specified string\n \"\"\"\n SUPPORTED = SUPPORTED_LOSS_REGRESSION\n type_str = 'regression loss'\n\n\nclass LossClassificationFactory(ModuleFactory):\n \"\"\"\n Import a classification loss function from niftynet.layer or\n from user specified string\n \"\"\"\n SUPPORTED = SUPPORTED_LOSS_CLASSIFICATION\n type_str = 'classification loss'\n\n\nclass LossAutoencoderFactory(ModuleFactory):\n \"\"\"\n Import an autoencoder loss function from ``niftynet.layer`` or\n from user specified string\n \"\"\"\n SUPPORTED = SUPPORTED_LOSS_AUTOENCODER\n type_str = 'autoencoder loss'\n\n\nclass OptimiserFactory(ModuleFactory):\n \"\"\"\n Import an optimiser from ``niftynet.engine.application_optimiser`` or\n from user specified string\n \"\"\"\n SUPPORTED = SUPPORTED_OPTIMIZERS\n type_str = 'optimizer'\n\n\nclass InitializerFactory(ModuleFactory):\n \"\"\"\n Import an initializer from ``niftynet.engine.application_initializer`` or\n from user specified string\n \"\"\"\n SUPPORTED = SUPPORTED_INITIALIZATIONS\n type_str = 'initializer'\n\n @staticmethod\n def get_initializer(name, args=None):\n \"\"\"\n wrapper for getting the initializer.\n\n :param name:\n :param args: optional parameters for the initializer\n :return:\n \"\"\"\n init_class = InitializerFactory.create(name)\n if args is None:\n args = {}\n return init_class.get_instance(args)\n\nclass EvaluationFactory(ModuleFactory):\n \"\"\"\n Import an optimiser from niftynet.engine.application_optimiser or\n from user specified string\n \"\"\"\n SUPPORTED = SUPPORTED_EVALUATIONS\n type_str = 'evaluation'\n"
] | [
[
"tensorflow.logging.fatal"
]
] |
WanglinLi595/OpenCV_Image_Process_Study | [
"02401790f06b20e3e2a14a01940f65f28de31e5b"
] | [
"test_code/test_3_11_threshold.py"
] | [
"#!/usr/bin/env python\n# coding=utf-8\n'''\n@描述: 图片简单阈值化\n@版本: V1_0\n@作者: LiWanglin\n@创建时间: 2020.02.11\n@最后编辑人: LiWanglin\n@最后编辑时间: 2020.02.11\n'''\n\nimport cv2 as cv\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nimg = cv.imread('./test_image/gradient.png',0)\nret,thresh1 = cv.threshold(img,127,255,cv.THRESH_BINARY)\nret,thresh2 = cv.threshold(img,127,255,cv.THRESH_BINARY_INV)\nret,thresh3 = cv.threshold(img,127,255,cv.THRESH_TRUNC)\nret,thresh4 = cv.threshold(img,127,255,cv.THRESH_TOZERO)\nret,thresh5 = cv.threshold(img,127,255,cv.THRESH_TOZERO_INV)\ntitles = ['Original Image','BINARY','BINARY_INV','TRUNC','TOZERO','TOZERO_INV']\nimages = [img, thresh1, thresh2, thresh3, thresh4, thresh5]\nfor i in range(6):\n plt.subplot(2,3,i+1),plt.imshow(images[i],'gray')\n plt.title(titles[i])\n plt.xticks([]),plt.yticks([])\nplt.show()"
] | [
[
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.yticks",
"matplotlib.pyplot.title",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.show"
]
] |
m2lines/subgrid | [
"3de5d14c5525a62529d43cbafccda716c74e32df"
] | [
"swm-master/swm-master/docu/matvis/scripts/forc_vis.py"
] | [
"import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import gridspec\n\nplt.rcParams['mathtext.fontset'] = 'cm'\nplt.rcParams['mathtext.rm'] = 'serif'\n\nparam = dict()\n\nparam['nx'] = 128 # number of grid points in x-direction\nparam['ny'] = 128 # number of grid points in y-direction\n\nparam['Lx'] = 3840e3 # basin width L [meters]\nparam['Ly'] = 3840e3 # north-south basin extent [meters]\n\nparam['dx'] = param['Lx'] / param['nx'] # grid spacing in x-direction\nparam['dy'] = param['Ly'] / param['ny'] # grid spacing in y-direction\n\nparam['x_T'] = np.arange(param['dx']/2.,param['Lx'],param['dx'])\nparam['y_T'] = np.arange(param['dy']/2.,param['Ly'],param['dy'])\n\n# grid vectors for u-points\nparam['x_u'] = param['x_T'][:-1] + param['dx']/2.\nparam['y_u'] = param['y_T']\n\nLx,Ly = param['Lx'],param['Ly'] # for convenience\nparam['rho'] = 1e3 # density\n\nxx_u,yy_u = np.meshgrid(param['x_u'],param['y_u'])\n\nparam['Fx0'] = 0.12 # was 0.12\nFx = param['Fx0']*(np.cos(2*np.pi*(yy_u-Ly/2)/Ly) + 2*np.sin(np.pi*(yy_u - Ly/2)/Ly))\n\n\nfig = plt.figure(figsize=(6, 4.5)) \ngs = gridspec.GridSpec(1, 2, width_ratios=[3, 1]) \nax0 = plt.subplot(gs[0])\nax1 = plt.subplot(gs[1])\n\ns = 6\nax0.quiver(xx_u[2::s,::s]/1e3,yy_u[2::s,::s]/1e3,Fx[2::s,::s],np.zeros_like(Fx)[2::s,::s], scale=6, headwidth=5)\n\nax0.set_title('a',loc='left',fontweight='bold')\nax0.set_title(r'$(F_x,F_y)$') \nax0.set_xlabel(r'$x$ [km]')\nax0.set_ylabel(r'$y$ [km]')\n\nax0.set_xlim(0,Lx/1e3)\nax0.set_ylim(0,Ly/1e3)\n\nax0.scatter(300,1920,40,'C0',label='Point A')\nax0.scatter(2880,1920,40,'C1',label='Point B')\n\nax0.legend(loc=1)\n\nax1.plot(Fx[:,0],param['y_u'],lw=1.5)\nax1.plot(np.zeros_like(param['y_u']),param['y_u'],lw=0.5,alpha=0.5,color='k')\nax1.set_title('b',loc='left',fontweight='bold')\nax1.set_title(r'$\\gamma(y)$')\nax1.set_ylim(0,Ly)\nax1.set_yticks([])\nax1.set_xticks([-0.2,0,0.2])\nax1.set_xticklabels([-0.2,0,0.2])\nax1.set_xlabel('[Pa]')\n\n\n\n\nplt.tight_layout()\nplt.savefig('/home/mkloewer/Dropbox/thesis/Chapter1/Chapter1Figs/forcing.pdf')"
] | [
[
"matplotlib.pyplot.tight_layout",
"numpy.arange",
"numpy.cos",
"matplotlib.pyplot.savefig",
"numpy.sin",
"matplotlib.pyplot.subplot",
"numpy.zeros_like",
"matplotlib.gridspec.GridSpec",
"numpy.meshgrid",
"matplotlib.pyplot.figure"
]
] |
levtelyatnikov/graph_edge_generation | [
"e1d867475bece351f9ed49fabf0505e39cf41f6b"
] | [
"models/edge_generation/bernulyEG.py"
] | [
"import torch\n\nclass GumbleSigmoid(torch.nn.Module):\n def __init__(self):\n super(GumbleSigmoid, self).__init__()\n self.temperature = torch.tensor([1], dtype=torch.float32).to(torch.device('cuda:2')) #torch.nn.Parameter(torch.Tensor([5]))\n self.eps = 10e-5\n\n def forward(self, x, tau):\n self.tau = tau\n #edge_index, edge_weights = self.sample_edges(nodes_emb=x, tau=tau)\n return self.sample_edges(nodes_emb=x, tau=tau)\n\n def calculate_prob_dist(self, nodes_emb):\n #self.temperature = torch.tensor(10.01).type_as(self.tau) - self.tau\n return torch.exp(-self.temperature * torch.sum(nodes_emb - nodes_emb.unsqueeze(1) + self.eps , dim=-1) ** 2) # temperature\n\n def sample_edges(self, nodes_emb, tau, hard=True):\n # probs = self.calculate_prob_dist(nodes_emb)\n # probs = torch.cat([probs.unsqueeze(-1), (1-probs).unsqueeze(-1)], dim=-1)\n\n # new_logits = torch.log(probs + 10e-3)\n # P = torch.nn.functional.gumbel_softmax(new_logits, tau=tau, hard=True, dim= - 1)[:,:, 0]\n #probs = probs[:, :, 0]\n\n # Probabilities for edges\n probs = torch.clamp(1 - self.calculate_prob_dist(nodes_emb), 0, 0.9999)\n logits = - torch.log(probs + self.eps)\n \n P = self.gumbel_sigmoid_adj(logits, tau=tau, hard=hard)\n \n # Get parent child list\n childer = torch.arange(P.shape[0]).repeat(P.shape[1]).to(nodes_emb.device)\n parents = torch.arange(P.shape[0]).view(-1,1).repeat((1, P.shape[1])).flatten().to(nodes_emb.device)\n edge_index = torch.stack([childer, parents])\n\n # Get weight sequence of 0, 1 for edge_list\n mask = torch.clamp((P + P.T), min=0 , max=1) #torch.clamp((P + P.T - torch.tensor([1], dtype=torch.float32).to(torch.device('cuda:2'))), min=0 , max=1)\n edge_weights = mask.view((-1, ))\n \n\n \n return edge_index, edge_weights, probs, mask, P\n \n def gumbel_sigmoid_adj(self, logits, tau, hard: bool = True): \n gumbels = (\n -torch.empty_like(\n logits,\n memory_format=torch.legacy_contiguous_format\n ).exponential_().log() # ~Gumbel(0,1)\n )\n gumbels = (logits + gumbels) / tau \n y_soft = gumbels.sigmoid()\n\n if hard:\n y_hard = (y_soft >= 0.8) * 1\n ret = y_hard - y_soft.detach() + y_soft\n else:\n ret = y_soft\n return ret\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
] | [
[
"torch.empty_like",
"torch.tensor",
"torch.log",
"torch.arange",
"torch.stack",
"torch.device",
"torch.clamp"
]
] |
SaravananM21/pyNastran | [
"d89a59a918e8d2262e3d8e6abd01abdc37046cdf"
] | [
"pyNastran/bdf/cards/test/utils.py"
] | [
"\"\"\"defines testing utils\"\"\"\nimport os\nfrom io import StringIO\nimport inspect\nfrom typing import Tuple, List, Dict\n\nimport numpy as np\nfrom cpylog import SimpleLogger\n\nfrom pyNastran.bdf.bdf import BDF, read_bdf\nfrom pyNastran.bdf.mesh_utils.delete_bad_elements import element_quality\nfrom pyNastran.bdf.mesh_utils.remove_unused import remove_unused\nfrom pyNastran.bdf.mesh_utils.convert import convert\nfrom pyNastran.bdf.mesh_utils.bdf_renumber import bdf_renumber\nfrom pyNastran.bdf.mesh_utils.mirror_mesh import bdf_mirror\nfrom pyNastran.bdf.mesh_utils.mass_properties import (\n mass_properties, mass_properties_nsm, mass_properties_breakdown)\nfrom pyNastran.bdf.mesh_utils.forces_moments import get_load_arrays, get_pressure_array\n\nfrom pyNastran.bdf.test.test_bdf import run_bdf as test_bdf\n\nfrom pyNastran.op2.tables.oug.oug_displacements import RealDisplacementArray\nfrom pyNastran.op2.op2_geom import attach_op2_results_to_bdf\n\n\ntry:\n import h5py\n IS_H5PY = True\nexcept ImportError: # pragma: no cover\n IS_H5PY = False\n\ndef save_load_deck(model: BDF, xref='standard', punch=True, run_remove_unused=True,\n run_convert=True, run_renumber=True, run_mirror=True,\n run_save_load=True, run_quality=True, write_saves=True,\n run_save_load_hdf5=True, run_mass_properties=True, run_loads=True,\n run_test_bdf=True, run_op2_writer=True, run_op2_reader=True,\n op2_log_level: str='warning') -> BDF:\n \"\"\"writes, re-reads, saves an obj, loads an obj, and returns the deck\"\"\"\n if os.path.exists('junk.bdf'):\n os.remove('junk.bdf')\n model.set_error_storage(nparse_errors=0, stop_on_parsing_error=True,\n nxref_errors=0, stop_on_xref_error=True)\n model.validate()\n model.pop_parse_errors()\n model.pop_xref_errors()\n bdf_file = StringIO()\n model.write_bdf(bdf_file, size=8, close=False)\n bdf_file.seek(0)\n model.write_bdf(bdf_file, size=16, close=False)\n bdf_file.seek(0)\n model.write_bdf(bdf_file, size=16, is_double=True, close=False)\n bdf_file.seek(0)\n\n if write_saves and model.save_file_structure:\n bdf_filenames = {0 : 'junk.bdf',}\n model.write_bdfs(bdf_filenames)\n os.remove('junk.bdf')\n\n if run_convert:\n units_to = ['m', 'kg', 's']\n units = ['ft', 'lbm', 's']\n convert(model, units_to, units)\n\n model2 = BDF(log=model.log)\n #print(bdf_file.getvalue())\n model2.read_bdf(bdf_file, punch=punch, xref=False)\n _cross_reference(model2, xref)\n\n model2.pop_parse_errors()\n model2.get_bdf_stats()\n model2.write_bdf('model2.bdf')\n if run_test_bdf:\n folder = ''\n log_error = SimpleLogger(level='error', encoding='utf-8')\n test_bdf(folder, 'model2.bdf', stop_on_failure=True,\n punch=punch,\n quiet=True, log=log_error)\n os.remove('model2.test_bdf.bdf')\n\n nelements = len(model2.elements) + len(model2.masses)\n nnodes = len(model2.nodes) + len(model2.spoints) + len(model2.epoints)\n\n _run_mass_properties(model2, nnodes, nelements, run_mass_properties=run_mass_properties)\n _run_loads(model2, nelements, run_loads=run_loads)\n\n if run_save_load:\n model2.save(obj_filename='model.obj', unxref=True)\n model3 = BDF(debug=False, log=model.log, mode='msc')\n model3.load(obj_filename='model.obj')\n os.remove('model.obj')\n else:\n model2.uncross_reference()\n model3 = model2\n\n _run_hdf5(model2, model.log, run_save_load_hdf5=run_save_load_hdf5)\n\n cross_reference(model3, xref)\n if run_renumber:\n renumber('model2.bdf', model.log)\n if run_mirror:\n # we put this under renumber to prevent modifying an\n # existing model to prevent breaking tests\n #\n # shouldn't have any effect model2.bdf\n model_mirrored = bdf_mirror('model2.bdf', plane='xz', log=model.log)[0]\n model_mirrored.write_bdf('mirrored2.bdf')\n read_bdf('mirrored2.bdf', log=model.log)\n os.remove('mirrored2.bdf')\n os.remove('model2.bdf')\n\n if model.elements and run_quality:\n element_quality(model)\n\n if run_op2_writer:\n op2_geom_model = attach_op2_results_to_bdf(model, op2_model=None)\n from pyNastran.op2.op2_geom import read_op2_geom\n\n table_name = 'OUGV1'\n node_gridtype = np.zeros((10, 2), dtype='int32')\n node_gridtype[:, 0] = np.arange(1, 11)\n data = np.zeros((1, 10, 6), dtype='float32')\n isubcase = 1\n disp = RealDisplacementArray.add_static_case(\n table_name, node_gridtype, data, isubcase, is_sort1=True)\n op2_geom_model.displacements[isubcase] = disp\n\n\n op2_filename = 'spike.op2'\n bkp_log = op2_geom_model.log\n op2_geom_model.log = SimpleLogger(level=op2_log_level, encoding='utf-8')\n op2_geom_model.write_op2(op2_filename, post=-1, endian=b'<', skips=None,\n nastran_format='nx')\n if run_op2_reader:\n unused_op2_geom = read_op2_geom(op2_filename, log=op2_geom_model.log, xref=False)\n else:\n frame = inspect.currentframe()\n call_frame = inspect.getouterframes(frame, 2)\n op2_geom_model.log.warning('skipping op2 reader for %s' % call_frame[1][3])\n op2_geom_model.log = bkp_log\n os.remove(op2_filename)\n\n if run_remove_unused:\n remove_unused(model)\n\n return model3\n\n\ndef _run_hdf5(model2, log, run_save_load_hdf5=True):\n \"\"\"helper method\"\"\"\n if run_save_load_hdf5 and IS_H5PY:\n hdf5_filename = 'test.h5'\n model2.export_hdf5_filename(hdf5_filename)\n model4 = BDF(log=model2.log)\n model4.load_hdf5_filename(hdf5_filename)\n model4.validate()\n bdf_stream = StringIO()\n model4.write_bdf(bdf_stream, encoding=None, size=8, is_double=False,\n interspersed=False, enddata=None, write_header=True, close=True)\n for key, unused_value in model2.card_count.items():\n if key == 'ENDDATA':\n continue\n if key not in model4.card_count:\n msg = 'key=%r was not loaded to hdf5\\nexpected=%s\\nactual=%s' % (\n key, model2.card_count, model4.card_count)\n #raise RuntimeError(msg)\n log.error(msg)\n os.remove(hdf5_filename)\n\ndef _run_mass_properties(model2, nnodes, nelements, run_mass_properties=True):\n \"\"\"helper method\"\"\"\n if not(run_mass_properties and nelements):\n return\n\n if nelements > 1 and nnodes == 0: # pragma: no cover\n raise RuntimeError('no nodes exist')\n mass1, cg1, inertia1 = mass_properties(model2, reference_point=None, sym_axis=None)\n mass2, cg2, inertia2 = mass_properties_nsm(model2, reference_point=None, sym_axis=None)\n #if not quiet:\n #if model2.wtmass != 1.0:\n #print('weight = %s' % (mass1 / model2.wtmass))\n #print('mass = %s' % mass1)\n #print('cg = %s' % cg1)\n #print('Ixx=%s, Iyy=%s, Izz=%s \\nIxy=%s, Ixz=%s, Iyz=%s' % tuple(inertia1))\n assert np.allclose(mass1, mass2), 'mass1=%s mass2=%s' % (mass1, mass2)\n assert np.allclose(cg1, cg2), 'mass=%s\\ncg1=%s cg2=%s' % (mass1, cg1, cg2)\n if not np.allclose(inertia1, inertia2, atol=1e-5): # pragma: no cover\n raise ValueError('mass=%s cg=%s\\ninertia1=%s\\ninertia2=%s\\ndinertia=%s' % (\n mass1, cg1, inertia1, inertia2, inertia1-inertia2))\n\n unused_mass3, unused_cg3, unused_inertia3 = mass_properties_breakdown(model2)[:3]\n #assert np.allclose(mass1, mass3), 'mass1=%s mass3=%s' % (mass1, mass3)\n #assert np.allclose(cg1, cg3), 'mass=%s\\ncg1=%s cg3=%s' % (mass1, cg1, cg3)\n\ndef _run_loads(model, nelements: int, run_loads=True):\n \"\"\"helper method\"\"\"\n if not run_loads:\n return\n assert isinstance(nelements, int), nelements\n #node_ids = None\n\n #nnodes = model.nnodes\n #node_ids = [None] * nnodes\n try:\n out = model.get_displacement_index_xyz_cp_cd(\n fdtype='float64', idtype='int32', sort_ids=True)\n except ValueError:\n return\n unused_icd_transformi, unused_icp_transformi, unused_xyz_cpi, nid_cp_cd = out\n node_ids = nid_cp_cd[:, 0]\n normals, eids, eid_map = _normals_eid_map(model, nelements, fdtype='float64')\n\n nsubcases = len(model.subcases)\n if nsubcases == 0:\n load_ids = list(set(list(model.load_combinations) + list(model.loads)))\n for load_id in sorted(load_ids):\n unused_subcase = model.case_control_deck.add_subcase(load_id)\n get_pressure_array(model, load_id, eids, stop_on_failure=True,\n fdtype='float32')\n\n load_ids = list(set(list(model.load_combinations) + list(model.loads)))\n for subcase_id in model.subcases:\n get_load_arrays(model, subcase_id, eid_map, node_ids, normals, nid_map=None,\n fdtype='float32')\n\n if nsubcases == 0:\n del model.case_control_deck\n\ndef _normals_eid_map(model: BDF, nelements: int,\n fdtype='float64') -> Tuple[np.ndarray,\n List[int],\n Dict[int, int]]:\n ieid = 0\n eids = []\n eid_map = {}\n normals = np.zeros((nelements, 3), dtype=fdtype)\n for eid, elem in model.elements.items():\n if hasattr(elem, 'Normal'):\n normals[ieid, :] = elem.Normal()\n eid_map[eid] = ieid\n eids.append(eid)\n ieid += 1\n return normals, eids, eid_map\n\ndef _cross_reference(model, xref):\n \"\"\"helper method for ``_cross_reference``\"\"\"\n if xref in [True, 'standard']:\n model.cross_reference()\n elif xref in ['safe']:\n model.safe_cross_reference()\n\ndef cross_reference(model, xref):\n \"\"\"validate we're doing xref right\"\"\"\n _cross_reference(model, xref)\n model.pop_xref_errors()\n\n model.safe_cross_reference()\n model.pop_xref_errors()\n\n _cross_reference(model, xref)\n model.pop_xref_errors()\n\n\ndef renumber(bdf_filename, log):\n bdf_filename_out = 'junk.bdf'\n #model3_copy = deepcopy(model3)\n #model3.cross_reference()\n bdf_renumber(bdf_filename, bdf_filename_out, size=8, is_double=False,\n starting_id_dict=None, round_ids=False, cards_to_skip=None, log=None,\n debug=False)\n model4 = BDF(debug=False, log=log)\n model4.read_bdf(bdf_filename_out)\n os.remove('junk.bdf')\n"
] | [
[
"numpy.arange",
"numpy.zeros",
"numpy.allclose"
]
] |
elifesciences-publications/accumulating_puffs | [
"9ebed68416284cddc85c9aeb0879b87eff5fe598"
] | [
"hardware/ni845x.py"
] | [
"import ctypes\nimport numpy as np\n\nMAX_SIZE = 1024\nDEV_SIZE = 256\n\nni845x_dll = ctypes.windll.LoadLibrary('Ni845x.dll')\n\nclass Ni845xError(Exception):\n def __init__(self, status_code):\n\n message = ctypes.create_string_buffer(MAX_SIZE)\n \n ni845x_dll.ni845xStatusToString(status_code, MAX_SIZE, message)\n \n Exception.__init__(self, message.value)\n \ndef errChk(err):\n if err:\n raise Ni845xError(err)\n\n\nclass NI845x():\n VOLTS33 = 33\n VOLTS25 = 25\n VOLTS18 = 18\n VOLTS15 = 15\n VOLTS12 = 12\n INPUT,OUTPUT = 0,1\n kNi845xI2cAddress7Bit = 0\n kNi845xI2cAddress10Bit = 1\n def __init__(self):\n \n # Determine available devices\n NextDevice = ctypes.create_string_buffer(DEV_SIZE)\n FindDeviceHandle = ctypes.c_int32()\n NumberFound = ctypes.c_int32()\n \n errChk(ni845x_dll.ni845xFindDevice(ctypes.byref(NextDevice), ctypes.byref(FindDeviceHandle), ctypes.byref(NumberFound)))\n\n if NumberFound.value != 1:\n raise Exception('Only implemented support for exactly 1 USB card. {} found.'.format(NumberFound.value))\n self._name = NextDevice\n \n self._open()\n self.config_i2c()\n self.set_io_voltage_level(self.VOLTS33)\n self.set_port_line_direction_map(self.OUTPUT*np.ones(8))\n \n def _open(self):\n self.dev_handle = ctypes.c_int32()\n errChk(ni845x_dll.ni845xOpen(ctypes.byref(self._name), ctypes.byref(self.dev_handle)))\n \n def set_port_line_direction_map(self, mapp, port=0):\n # mapp: np array or list with 8 0's or 1's\n # 0 = input, 1 = output\n port = ctypes.c_uint8(port)\n mapp = np.asarray(mapp)\n assert len(mapp)==8\n r = np.arange(7,-1,-1)\n _map = np.sum(2**r * mapp).astype(int)\n bitmap = ctypes.c_uint8(_map)\n errChk(ni845x_dll.ni845xDioSetPortLineDirectionMap(self.dev_handle, port, bitmap))\n \n def set_io_voltage_level(self, lev):\n lev = ctypes.c_uint8(lev)\n errChk(ni845x_dll.ni845xSetIoVoltageLevel(self.dev_handle, lev))\n \n def end(self):\n errChk(ni845x_dll.ni845xClose(self.dev_handle))\n errChk(ni845x_dll.ni845xI2cConfigurationClose(self.i2c_handle))\n\n def write_dio(self, line, val, port=0):\n line = ctypes.c_uint8(line)\n port = ctypes.c_uint8(port)\n val = ctypes.c_int32(val)\n errChk(ni845x_dll.ni845xDioWriteLine( self.dev_handle, port, line, val ))\n \n def config_i2c(self, size=None, address=0, clock_rate=100, timeout=2000):\n \"\"\"\n Set the ni845x I2C configuration.\n \n Parameters\n ----------\n size : Configuration address size (default 7Bit).\n address : Configuration address (default 0).\n clock_rate : Configuration clock rate in kilohertz (default 100).\n\n Returns\n -------\n None\n \"\"\"\n if size is None:\n size = self.kNi845xI2cAddress7Bit\n size = ctypes.c_int32(size)\n address = ctypes.c_uint16(address)\n clock_rate = ctypes.c_uint16(clock_rate)\n timeout = ctypes.c_uint32(timeout)\n #\n # create configuration reference\n #\n self.i2c_handle = ctypes.c_int32()\n errChk(ni845x_dll.ni845xI2cConfigurationOpen(ctypes.byref(self.i2c_handle)))\n \n #\n # configure configuration properties\n #\n errChk(ni845x_dll.ni845xI2cConfigurationSetAddressSize(self.i2c_handle, size))\n errChk(ni845x_dll.ni845xI2cConfigurationSetAddress(self.i2c_handle, address))\n errChk(ni845x_dll.ni845xI2cConfigurationSetClockRate(self.i2c_handle, clock_rate))\n errChk(ni845x_dll.ni845xSetTimeout(self.dev_handle, timeout))\n \n def write_i2c(self, data):\n \"\"\"\n Write an array of data to an I2C slave device.\n\n Parameters\n ----------\n write_data : Array of bytes to be written. Should be convertible to numpy array of\n type unsigned char.\n\n Returns\n -------\n None\n \n \"\"\"\n \n data = ctypes.create_string_buffer(data)\n nbytes = ctypes.c_int32(len(data))\n\n errChk(ni845x_dll.ni845xI2cWrite(self.dev_handle, self.i2c_handle, nbytes, ctypes.byref(data)))\n \n"
] | [
[
"numpy.asarray",
"numpy.arange",
"numpy.sum",
"numpy.ones"
]
] |
karolisjan/Project | [
"0f58b7cdf6c9b1b777c039ea4267da8e184a17d2"
] | [
"examples/utils.py"
] | [
"import matplotlib.pyplot as plt\nfrom matplotlib.patches import Rectangle\n\nfrom IPython.core.display import display, HTML\n\n# from rpy2.robjects import r, pandas2ri\n# pandas2ri.activate()\n\n\ndef toggle_code(hide_code_by_default: bool=False):\n return HTML('''\n <a id='index'></a>\n <script>\n code_show = %s; \n\n function code_toggle() {\n if (code_show){\n $('div.input').hide();\n } else {\n $('div.input').show();\n }\n code_show = !code_show\n }\n\n $( document ).ready(code_toggle);\n </script>\n\n <form action=\"javascript:code_toggle()\">\n <input type=\"submit\" value=\"Toggle Code\">\n </form>\n ''' % str(hide_code_by_default).lower())\n\n\ndef show(obj, header: str, id: str=None):\n if id is not None:\n display(HTML('<a id=\"%s\"></a>' % id))\n\n display(HTML(header))\n display(obj)\n\n\ndef plot_2D_pareto_front(\n x,\n y,\n xlabel: str=None,\n ylabel: str=None,\n figsize: tuple=None,\n marker: str='o',\n markercolor: str='black',\n edgecolor: str='black',\n markersize: int=100,\n markeralpha: float=0.5,\n linecolor: str='black',\n linewidth: int=1,\n ref_point: list=None,\n ideal_point: list=None,\n fillcolor: str='black',\n fillalpha: float=0.10,\n):\n assert len(x) == len(y)\n\n if ref_point is not None:\n assert len(ref_point) == 2\n\n if ideal_point is not None:\n assert len(ideal_point) == 2\n\n fig, axes = plt.subplots()\n if figsize is not None:\n fig.set_size_inches(figsize[0], figsize[1])\n\n x = sorted(x)\n y = sorted(y)\n\n axes.plot(\n [x[0], x[0]],\n [y[0], y[1]],\n color=linecolor,\n linewidth=linewidth\n )\n\n axes.plot(\n [x[0], x[1]],\n [y[1], y[1]],\n color=linecolor,\n linewidth=linewidth\n )\n\n axes.scatter(\n [x[0], x[1]],\n [y[0], y[1]],\n marker=marker,\n edgecolor=edgecolor,\n s=markersize,\n color=markercolor,\n alpha=markeralpha\n )\n\n if ref_point is not None:\n axes.add_patch(\n Rectangle(\n (ref_point[0], y[0]),\n x[0] - ref_point[0],\n y[1] - y[0],\n facecolor=fillcolor,\n linewidth=0,\n alpha=fillalpha\n )\n )\n\n if ref_point is not None and ideal_point is not None:\n axes.plot(\n [ref_point[0], ideal_point[0]],\n [ideal_point[1], ideal_point[1]],\n '--', \n color='black',\n linewidth=1.0\n )\n\n axes.plot(\n [ideal_point[0], ideal_point[0]],\n [ideal_point[1], ref_point[1]],\n '--', \n color='black',\n linewidth=1.0\n )\n\n for i in range(2, len(y)):\n axes.plot(\n [x[i - 1], x[i - 1]],\n [y[i - 1], y[i]],\n color=linecolor,\n linewidth=linewidth\n )\n\n axes.plot(\n [x[i - 1], x[i]],\n [y[i], y[i]],\n color=linecolor,\n linewidth=linewidth\n )\n\n axes.scatter(\n x[i],\n y[i],\n marker=marker,\n edgecolor=edgecolor,\n s=markersize,\n color=markercolor,\n alpha=markeralpha\n )\n\n if ref_point is not None:\n axes.add_patch(\n Rectangle(\n (ref_point[0], y[i - 1]),\n (x[i - 1] - ref_point[0]),\n (y[i] - y[i - 1]),\n facecolor=fillcolor,\n linewidth=0,\n alpha=fillalpha\n )\n )\n\n axes.scatter(\n x[-1],\n y[-1],\n marker=marker,\n edgecolor=edgecolor,\n s=markersize,\n color=markercolor,\n alpha=markeralpha\n )\n\n if ref_point is not None:\n axes.add_patch(\n Rectangle(\n (ref_point[0], y[-1]),\n (x[-1] - ref_point[0]),\n (ref_point[1] - y[-1]),\n facecolor=fillcolor,\n linewidth=0,\n alpha=fillalpha\n )\n )\n\n if xlabel:\n axes.set_xlabel(xlabel)\n\n if ylabel:\n axes.set_ylabel(ylabel)\n\n if ref_point is not None:\n axes.scatter(\n ref_point[0],\n ref_point[1],\n marker=marker,\n edgecolor=edgecolor,\n s=markersize,\n color='red',\n )\n\n if ideal_point is not None:\n axes.scatter(\n ideal_point[0],\n ideal_point[1],\n marker=marker,\n edgecolor=edgecolor,\n s=markersize,\n color='green'\n )\n\n if ref_point is not None and ideal_point is not None:\n axes.plot(\n [ref_point[0], ref_point[0]],\n [ref_point[1], ideal_point[1]],\n '--', \n color='black',\n linewidth=1.0\n )\n\n axes.plot(\n [ref_point[0], ideal_point[0]],\n [ref_point[1], ref_point[1]],\n '--', \n color='black',\n linewidth=1.0\n )\n\n axes.plot(\n [x[0], ref_point[0]],\n [y[0], y[0]],\n '--', \n color='black',\n linewidth=1.0\n )\n\n axes.plot(\n [x[-1], x[-1]],\n [y[-1], ref_point[1]],\n '--', \n color='black',\n linewidth=1.0\n )\n\n return fig\n\n# def product_profiles(num, model):\n\n# model.schedules[num].kg_inventory.to_csv('tmp1.csv')\n# model.schedules[num].kg_waste.to_csv('tmp2.csv')\n# model.schedules[num].kg_backlog.to_csv('tmp3.csv')\n\n# if not os.path.exists('figures'):\n# os.mkdir('figures')\n\n# r(\n# '''\n# function() {\n# library(zoo)\n \n# colors <- c(\n# rgb(146, 208, 80, max=255),\n# rgb(179, 129, 217, max=255),\n# rgb(196, 189, 151, max=255),\n# rgb(255, 0, 0, max=255)\n# )\n \n# names(colors) <- c(\"A\", \"B\", \"C\", \"D\")\n \n# kg_demand <- read.csv(\"data/kg_demand.csv\")\n# kg_demand$date <- as.yearmon(as.Date(kg_demand$date, \"%Y-%m-%d\"))\n\n# kg_inventory_target <- read.csv(\"data/kg_inventory_target.csv\")\n# kg_inventory_target$date <- as.yearmon(as.Date(kg_inventory_target$date, \"%Y-%m-%d\"))\n\n# inventory_levels <- read.csv(\"tmp1.csv\")\n# inventory_levels$date <- as.yearmon(inventory_levels$date)\n \n# waste_levels <- read.csv(\"tmp2.csv\")\n# waste_levels$date <- as.yearmon(waste_levels$date)\n \n# backlog_levels <- read.csv(\"tmp3.csv\")\n# backlog_levels$date <- as.yearmon(backlog_levels$date)\n\n# jpeg(\"figures/inventory_waste_backlog_levels.jpg\", width=16, height=8, units='in', res=720);\n\n# par(mfrow=c(2, 2))\n\n# for (i in 2:ncol(kg_demand)) {\n# bar_xcoor <- barplot(\n# t(kg_demand[, i]), \n# ylab=\"kg\", \n# ylim=c(\n# 0, \n# max(\n# max(kg_inventory_target[, i]), \n# max(inventory_levels[, i]) \n# ) + 10\n# ),\n# names.arg=format(kg_demand$date, '%b %Y'),\n# las=2,\n# col=colors[i-1],\n# legend=paste(\"Product \", colnames(kg_demand)[1:ncol(kg_demand)][i], \" demand\"),\n# args.legend=list(\n# x=\"topleft\",\n# bty=\"n\"\n# )\n# )\n\n# lines(\n# xy.coords(\n# bar_xcoor,\n# kg_inventory_target[, i]\n# ),\n# type=\"b\",\n# col=colors[i-1],\n# )\n\n# lines(\n# xy.coords(\n# bar_xcoor,\n# inventory_levels[, i]\n# ),\n# type=\"b\",\n# pch=2,\n# col=\"black\",\n# )\n \n# lines(\n# xy.coords(\n# bar_xcoor,\n# waste_levels[, i]\n# ),\n# type=\"b\",\n# pch=3,\n# col=\"black\",\n# )\n \n# lines(\n# xy.coords(\n# bar_xcoor,\n# backlog_levels[, i]\n# ),\n# type=\"b\",\n# pch=4,\n# col=\"black\",\n# )\n\n# legend(\n# \"topright\", \n# c(\n# paste(\"Product \", colnames(kg_demand)[1:ncol(kg_demand)][i], \" inventory targets\"),\n# paste(\"Product \", colnames(kg_demand)[1:ncol(kg_demand)][i], \" inventory\"),\n# paste(\"Product \", colnames(kg_demand)[1:ncol(kg_demand)][i], \" waste\"),\n# paste(\"Product \", colnames(kg_demand)[1:ncol(kg_demand)][i], \" backlog\")\n# ), \n# pch=c(1, 2, 3, 4),\n# lty=c(1, 1, 1, 1),\n# box.lty=0,\n# col=c(colors[i-1], \"black\", \"black\", \"black\"), \n# )\n# }\n\n# dev.off();\n# }\n# '''\n# )()\n\n# os.remove('tmp1.csv')\n# os.remove('tmp2.csv')\n# os.remove('tmp3.csv')\n\n# img = cv2.cvtColor(\n# cv2.imread('figures/inventory_waste_backlog_levels.jpg'), \n# cv2.COLOR_BGR2RGB\n# )\n# fig = plt.figure(figsize=(60, 60))\n\n# plt.imshow(img)\n# plt.axis('off')\n# plt.show()"
] | [
[
"matplotlib.patches.Rectangle",
"matplotlib.pyplot.subplots"
]
] |
msinkec/classla-stanfordnlp | [
"0390e2e23d9dceec6ac220a9ed0d2093b6246ba1"
] | [
"stanfordnlp/models/common/utils.py"
] | [
"\"\"\"\nUtility functions.\n\"\"\"\nimport os\nfrom collections import Counter\nimport random\nimport json\nimport unicodedata\nimport torch\n\nfrom stanfordnlp.models.common.constant import lcode2lang\nimport stanfordnlp.models.common.seq2seq_constant as constant\nimport stanfordnlp.utils.conll18_ud_eval as ud_eval\n\n# filenames\ndef get_wordvec_file(wordvec_dir, shorthand):\n \"\"\" Lookup the name of the word vectors file, given a directory and the language shorthand.\n \"\"\"\n lcode, tcode = shorthand.split('_')\n lang = lcode2lang[lcode] if lcode != 'no' else lcode2lang[shorthand]\n if lcode == 'zh':\n lang = 'ChineseT'\n return os.path.join(wordvec_dir, lang, '{}.vectors.xz'.format(\\\n lcode if lcode != 'no' else (shorthand if shorthand != 'no_nynorsklia' else 'no_nynorsk')))\n\n# training schedule\ndef get_adaptive_eval_interval(cur_dev_size, thres_dev_size, base_interval):\n \"\"\" Adjust the evaluation interval adaptively.\n If cur_dev_size <= thres_dev_size, return base_interval;\n else, linearly increase the interval (round to integer times of base interval).\n \"\"\"\n if cur_dev_size <= thres_dev_size:\n return base_interval\n else:\n alpha = round(cur_dev_size / thres_dev_size)\n return base_interval * alpha\n\n# ud utils\ndef ud_scores(gold_conllu_file, system_conllu_file):\n gold_ud = ud_eval.load_conllu_file(gold_conllu_file)\n system_ud = ud_eval.load_conllu_file(system_conllu_file)\n evaluation = ud_eval.evaluate(gold_ud, system_ud)\n\n return evaluation\n\ndef harmonic_mean(a, weights=None):\n if any([x == 0 for x in a]):\n return 0\n else:\n assert weights is None or len(weights) == len(a), 'Weights has length {} which is different from that of the array ({}).'.format(len(weights), len(a))\n if weights is None:\n return len(a) / sum([1/x for x in a])\n else:\n return sum(weights) / sum(w/x for x, w in zip(a, weights))\n\n# torch utils\ndef get_optimizer(name, parameters, lr, betas=(0.9, 0.999), eps=1e-8, momentum=0):\n if name == 'sgd':\n return torch.optim.SGD(parameters, lr=lr, momentum=momentum)\n elif name == 'adagrad':\n return torch.optim.Adagrad(parameters, lr=lr)\n elif name == 'adam':\n return torch.optim.Adam(parameters, lr=lr, betas=betas, eps=eps)\n elif name == 'adamax':\n return torch.optim.Adamax(parameters) # use default lr\n else:\n raise Exception(\"Unsupported optimizer: {}\".format(name))\n\ndef change_lr(optimizer, new_lr):\n for param_group in optimizer.param_groups:\n param_group['lr'] = new_lr\n\ndef flatten_indices(seq_lens, width):\n flat = []\n for i, l in enumerate(seq_lens):\n for j in range(l):\n flat.append(i * width + j)\n return flat\n\ndef set_cuda(var, cuda):\n if cuda:\n return var.cuda()\n return var\n\ndef keep_partial_grad(grad, topk):\n \"\"\"\n Keep only the topk rows of grads.\n \"\"\"\n assert topk < grad.size(0)\n grad.data[topk:].zero_()\n return grad\n\n# other utils\ndef ensure_dir(d, verbose=True):\n if not os.path.exists(d):\n if verbose:\n print(\"Directory {} do not exist; creating...\".format(d))\n os.makedirs(d)\n\ndef save_config(config, path, verbose=True):\n with open(path, 'w') as outfile:\n json.dump(config, outfile, indent=2)\n if verbose:\n print(\"Config saved to file {}\".format(path))\n return config\n\ndef load_config(path, verbose=True):\n with open(path) as f:\n config = json.load(f)\n if verbose:\n print(\"Config loaded from file {}\".format(path))\n return config\n\ndef print_config(config):\n info = \"Running with the following configs:\\n\"\n for k,v in config.items():\n info += \"\\t{} : {}\\n\".format(k, str(v))\n print(\"\\n\" + info + \"\\n\")\n return\n\ndef normalize_text(text):\n return unicodedata.normalize('NFD', text)\n\ndef unmap_with_copy(indices, src_tokens, vocab):\n \"\"\"\n Unmap a list of list of indices, by optionally copying from src_tokens.\n \"\"\"\n result = []\n for ind, tokens in zip(indices, src_tokens):\n words = []\n for idx in ind:\n if idx >= 0:\n words.append(vocab.id2word[idx])\n else:\n idx = -idx - 1 # flip and minus 1\n words.append(tokens[idx])\n result += [words]\n return result\n\ndef prune_decoded_seqs(seqs):\n \"\"\"\n Prune decoded sequences after EOS token.\n \"\"\"\n out = []\n for s in seqs:\n if constant.EOS in s:\n idx = s.index(constant.EOS_TOKEN)\n out += [s[:idx]]\n else:\n out += [s]\n return out\n\ndef prune_hyp(hyp):\n \"\"\"\n Prune a decoded hypothesis\n \"\"\"\n if constant.EOS_ID in hyp:\n idx = hyp.index(constant.EOS_ID)\n return hyp[:idx]\n else:\n return hyp\n\ndef prune(data_list, lens):\n assert len(data_list) == len(lens)\n nl = []\n for d, l in zip(data_list, lens):\n nl.append(d[:l])\n return nl\n\ndef sort(packed, ref, reverse=True):\n \"\"\"\n Sort a series of packed list, according to a ref list.\n Also return the original index before the sort.\n \"\"\"\n assert (isinstance(packed, tuple) or isinstance(packed, list)) and isinstance(ref, list)\n packed = [ref] + [range(len(ref))] + list(packed)\n sorted_packed = [list(t) for t in zip(*sorted(zip(*packed), reverse=reverse))]\n return tuple(sorted_packed[1:])\n\ndef unsort(sorted_list, oidx):\n \"\"\"\n Unsort a sorted list, based on the original idx.\n \"\"\"\n assert len(sorted_list) == len(oidx), \"Number of list elements must match with original indices.\"\n _, unsorted = [list(t) for t in zip(*sorted(zip(oidx, sorted_list)))]\n return unsorted\n\ndef tensor_unsort(sorted_tensor, oidx):\n \"\"\"\n Unsort a sorted tensor on its 0-th dimension, based on the original idx.\n \"\"\"\n assert sorted_tensor.size(0) == len(oidx), \"Number of list elements must match with original indices.\"\n backidx = [x[0] for x in sorted(enumerate(oidx), key=lambda x: x[1])]\n return sorted_tensor[backidx]\n"
] | [
[
"torch.optim.Adam",
"torch.optim.Adagrad",
"torch.optim.Adamax",
"torch.optim.SGD"
]
] |
allen-chiang/Time-Series-Transformer | [
"d1b9b7d4f2e674095b44af6ebdbcd0d25616f203"
] | [
"time_series_transform/io/numpy.py"
] | [
"import numpy as np\nimport pandas as pd\nfrom time_series_transform.io.base import io_base\nfrom time_series_transform.transform_core_api.base import (\n Time_Series_Data_Collection,\n Time_Series_Data\n )\n\n\nclass Numpy_IO (io_base):\n def __init__(self, time_series, timeSeriesColIx, mainCategoryColIx):\n \"\"\"\n Numpy_IO IO class for numpy data\n \n Parameters\n ----------\n time_series : Time_Series_Data or Time_Series_Data_Collection\n input data\n timeSeriesCol : str or int\n index of time period column\n mainCategoryCol : str of int\n index of category column\n \"\"\"\n super().__init__(time_series, timeSeriesColIx, mainCategoryColIx)\n if self.dictList is not None:\n self.dictList = {}\n for i in range(len(time_series.T)):\n self.dictList[i] = time_series.T[i]\n\n def from_numpy (self):\n \"\"\"\n from_numpy \n transform numpy ndArray to Time_Series_Data or Time_Series_Data_Collection\n Returns\n -------\n Time_Series_Data or Time_Series_Data_Collection\n \"\"\"\n if self.mainCategoryCol is None:\n return self.to_single()\n return self.to_collection()\n\n\n def to_numpy(self,expandTime,expandCategory,preprocessType,labelList):\n \"\"\"\n to_numpy transform Time_Series_Data or Time_Series_Data_Collection\n to numpy ndArray\n \n Parameters\n ----------\n expandCategory : bool\n whether to expand category\n expandTime : bool\n whether to expand time\n preprocessType : ['ignore','pad','remove']\n preprocess data time across categories\n labelList : list\n label list\n \n Returns\n -------\n numpy ndArray\n \"\"\"\n if isinstance(self.time_series,Time_Series_Data):\n data = self.from_single(expandTime)\n if isinstance(self.time_series,Time_Series_Data_Collection):\n data = self.from_collection(expandCategory,expandTime,preprocessType)\n for i in data:\n if isinstance(data[i],np.ndarray):\n data[i] = data[i].tolist()\n if labelList is None:\n return pd.DataFrame(data).values\n labelDict = {}\n dataDict = {}\n print(f\"label {labelList}\")\n for i in data:\n if i in labelList:\n labelDict[i] = data[i]\n continue\n dataDict[i] = data[i]\n return pd.DataFrame(dataDict).values,pd.DataFrame(labelDict).values\n\n\ndef from_numpy(numpyArray,timeSeriesCol,mainCategoryCol=None):\n \"\"\"\n from_numpy transform numpy ndArray\n to Time_Series_Data or Time_Series_Data_Collection\n \n Parameters\n ----------\n numpyArray : numpy ndArray\n input data\n timeSeriesCol : str or int\n index of time period column\n mainCategoryCol : str of int\n index of category column\n \n Returns\n -------\n Time_Series_Data or Time_Series_Data_Collection\n \n Raises\n ------\n ValueError\n invalid input data\n \"\"\"\n if not isinstance(numpyArray,np.ndarray):\n raise ValueError('input data must be numpy array')\n numpyio = Numpy_IO(numpyArray,timeSeriesCol,mainCategoryCol)\n return numpyio.from_numpy()\n\ndef to_numpy(time_series_data,expandCategory,expandTime,preprocessType,seperateLabels=False):\n \"\"\"\n to_numpy \n \n transform Time_Series_Data or Time_Series_Data_Collection\n to numpy ndArray\n \n Parameters\n ----------\n time_series_data : Time_Series_Data or Time_Series_Data_Collection\n input data\n expandCategory : bool\n whether to expand category\n expandTime : bool\n whether to expand time\n preprocessType : ['ignore','pad','remove']\n preprocess data time across categories\n seperateLabels : bool\n whether to seperate labels and data\n \n Returns\n -------\n [type]\n [description]\n \n Raises\n ------\n ValueError\n [description]\n \"\"\"\n labelsList = []\n if isinstance(time_series_data,Time_Series_Data):\n numpyio = Numpy_IO(time_series_data,time_series_data.time_seriesIx,None)\n expandCategory = None\n labelsList = list(time_series_data.labels.keys())\n elif isinstance(time_series_data,Time_Series_Data_Collection):\n numpyio = Numpy_IO(\n time_series_data,\n time_series_data._time_series_Ix,\n time_series_data._categoryIx\n )\n for i in time_series_data:\n print(time_series_data[i].labels)\n labelsList.extend(list(time_series_data[i].labels.keys()))\n labelsList = list(set(labelsList))\n else:\n raise ValueError('input data should be time_series_data or time_series_collection')\n if seperateLabels == False:\n return numpyio.to_numpy(expandTime,expandCategory,preprocessType,None)\n return numpyio.to_numpy(expandTime,expandCategory,preprocessType,labelsList)\n\n\n\n__all__= [\n 'from_numpy',\n 'to_numpy'\n]"
] | [
[
"pandas.DataFrame"
]
] |
bundie1990/aimet | [
"3cee2b286df680bc9fce301a695a1e757b5b228f"
] | [
"TrainingExtensions/torch/src/python/aimet_torch/quantsim.py"
] | [
"# /usr/bin/env python3.5\n# -*- mode: python -*-\n# =============================================================================\n# @@-COPYRIGHT-START-@@\n#\n# Copyright (c) 2019-2020, Qualcomm Innovation Center, Inc. All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# 3. Neither the name of the copyright holder nor the names of its contributors\n# may be used to endorse or promote products derived from this software\n# without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n#\n# SPDX-License-Identifier: BSD-3-Clause\n#\n# @@-COPYRIGHT-END-@@\n# =============================================================================\n\n\"\"\" Implementation for simulating models running on Quantized hardware \"\"\"\nimport os\nimport io\nimport copy\nimport pickle\nfrom typing import Tuple, List, Union, Dict\nimport json\nimport torch\nimport onnx\n\nfrom aimet_common.utils import AimetLogger\nfrom aimet_common.defs import QuantScheme\nfrom aimet_torch.quantsim_config.quantsim_config import QuantSimConfigurator\nfrom aimet_torch.qc_quantize_op import QcQuantizeStandAloneBase, QcQuantizeWrapper, QcQuantizeOpMode, \\\n QcPostTrainingWrapper\nfrom aimet_torch import torchscript_utils\nfrom aimet_torch.batch_norm_fold import PassThroughOp\nfrom aimet_torch import utils\nfrom aimet_torch import onnx_utils\nfrom aimet_torch.meta.connectedgraph_utils import create_connected_graph_with_input_shapes\nfrom aimet_torch.meta.connectedgraph import ConnectedGraph\nfrom aimet_torch.qc_quantize_recurrent import QcQuantizeRecurrent\n\nlogger = AimetLogger.get_area_logger(AimetLogger.LogAreas.Quant)\n\n\n# Types of modules which cannot be quantized\nunquantizable_modules = (QcQuantizeWrapper, QcQuantizeStandAloneBase, QcQuantizeRecurrent, PassThroughOp,\n torch.nn.Identity)\n\n# If a torch module type is in this dictionary, call the corresponding quantized module constructor instead of wrapping\n# it with QcQuantizeWrapper.\nqc_quantize_modules_dict = {\n torch.nn.RNN: QcQuantizeRecurrent,\n torch.nn.LSTM: QcQuantizeRecurrent,\n torch.nn.GRU: QcQuantizeRecurrent\n}\n\n\nclass QuantParams:\n \"\"\"\n Data type to hold quantization related params.\n \"\"\"\n def __init__(self,\n weight_bw: int = 8,\n act_bw: int = 8,\n round_mode: str = 'nearest',\n quant_scheme: Union[QuantScheme, str] = QuantScheme.post_training_tf_enhanced,\n config_file: str = None):\n \"\"\"\n Constructor\n\n :param weight_bw: Weight bitwidth (4-31) to use for quantizing layer weights. Default = 8\n :param act_bw: Activation bitwidth(4-31) to use for quantizing layer activations. Default = 8\n :param round_mode: Rounding mode. Supported options are 'nearest' or 'stochastic'\n :param quant_scheme: Quantization scheme. Supported options are 'tf_enhanced' or 'tf' or using Quant Scheme Enum\n QuantScheme.post_training_tf or QuantScheme.post_training_tf_enhanced\n :param config_file: Path to Configuration file for model quantizers\n \"\"\"\n\n self.weight_bw = weight_bw\n self.act_bw = act_bw\n self.round_mode = round_mode\n self.quant_scheme = quant_scheme\n self.config_file = config_file\n\n\nclass QuantizationSimModel:\n \"\"\"\n Implements mechanism to add quantization simulations ops to a model. This allows for off-target simulation of\n inference accuracy. Also allows the model to be fine-tuned to counter the effects of quantization.\n \"\"\"\n\n # pylint: disable=too-many-arguments\n def __init__(self, model: torch.nn.Module, input_shapes: Union[Tuple, List[Tuple]] = None,\n quant_scheme: Union[str, QuantScheme] = QuantScheme.post_training_tf_enhanced,\n rounding_mode: str = 'nearest', default_output_bw: int = 8, default_param_bw: int = 8,\n in_place: bool = False, config_file: str = None,\n dummy_input: Union[torch.Tensor, Tuple] = None):\n \"\"\"\n Constructor\n\n :param model: Model to add simulation ops to\n :param input_shapes: List of input shapes to the model\n :param quant_scheme: Quantization scheme. Supported options are 'tf_enhanced' or 'tf' or using Quant Scheme Enum\n QuantScheme.post_training_tf or QuantScheme.post_training_tf_enhanced\n :param rounding_mode: Rounding mode. Supported options are 'nearest' or 'stochastic'\n :param default_output_bw: Default bitwidth (4-31) to use for quantizing layer inputs and outputs\n :param default_param_bw: Default bitwidth (4-31) to use for quantizing layer parameters\n :param in_place: If True, then the given 'model' is modified in-place to add quant-sim nodes.\n Only suggested use of this option is when the user wants to avoid creating a copy of the model\n :param config_file: Path to Configuration file for model quantizers\n :param dummy_input: Dummy input to the model. Used to parse model graph. If the model has more than one input,\n pass a tuple. User is expected to place the tensors on the appropriate device.\n \"\"\"\n # Perform sanity checks on inputs\n QuantizationSimModel._validate_quantsim_inputs(quant_scheme, rounding_mode, default_output_bw, default_param_bw)\n # save some parameters\n if in_place:\n self.model = model\n else:\n self.model = copy.deepcopy(model)\n\n try:\n if dummy_input is not None:\n connected_graph = ConnectedGraph(self.model, dummy_input)\n else:\n if input_shapes is None:\n raise AssertionError('Must provide either input shapes or a dummy input for export')\n connected_graph = create_connected_graph_with_input_shapes(self.model, input_shapes)\n\n except (torch.jit.TracingCheckError, AssertionError):\n connected_graph = None\n\n if isinstance(quant_scheme, str):\n if quant_scheme == 'tf':\n quant_scheme = QuantScheme.post_training_tf\n elif quant_scheme == 'tf_enhanced':\n quant_scheme = QuantScheme.post_training_tf_enhanced\n self._quant_scheme = quant_scheme\n self._rounding_mode = rounding_mode\n self._default_output_bw = default_output_bw\n self._default_param_bw = default_param_bw\n\n # Add quantization layers\n self._add_quantization_wrappers(self.model)\n\n # Disable bias quantization\n self.exclude_param_from_quantization(\"bias\")\n\n self.configure_quantization_ops(connected_graph, config_file)\n\n def __str__(self):\n \"\"\"\n Pretty-printed output indicating where in the model, quantizers have been activated\n :return:\n \"\"\"\n stream = io.StringIO(newline='\\n')\n stream.write(\"-------------------------\\n\")\n stream.write(\"Quantized Model Report\\n\")\n stream.write(\"-------------------------\\n\")\n\n wrappers = [(name, module) for name, module in self.model.named_modules()\n if isinstance(module, QcQuantizeWrapper)]\n\n for name, wrapper in wrappers:\n stream.write('Layer: {}\\n'.format(name))\n\n # Inputs\n if wrapper.input_quantizer.enabled:\n stream.write(' Input: bw={}, encoding-present={}\\n'.format(wrapper.input_quantizer.bitwidth,\n bool(wrapper.input_quantizer.encoding)))\n else:\n stream.write(' Input: Unquantized\\n')\n\n # Params\n stream.write(' Params:\\n')\n for param_name, quantizer in wrapper.param_quantizers.items():\n if quantizer.enabled:\n stream.write(' {}: bw={}, encoding-present={}\\n'.format(param_name,\n quantizer.bitwidth,\n bool(quantizer.encoding)))\n else:\n stream.write(' {}: Unquantized\\n'.format(param_name))\n\n # Outputs\n if wrapper.output_quantizers[0].enabled:\n stream.write(' Output: bw={}, encoding-present={}\\n'.format(wrapper.output_quantizers[0].bitwidth,\n bool(wrapper.output_quantizers[0].encoding)))\n else:\n stream.write(' Output: Unquantized\\n')\n\n return stream.getvalue()\n\n def compute_encodings(self, forward_pass_callback, forward_pass_callback_args):\n \"\"\"\n Computes encodings for all quantization sim nodes in the model. It is also used to find initial encodings for\n Range Learning\n\n :param forward_pass_callback: A callback function that simply runs forward passes on the model. This callback\n function should use representative data for the forward pass, so the calculated encodings work for all\n data samples. This callback internally chooses the number of data samples it wants to use for calculating\n encodings.\n :param forward_pass_callback_args: These argument(s) are passed to the forward_pass_callback as-is. Up to\n the user to determine the type of this parameter. E.g. could be simply an integer representing the number\n of data samples to use. Or could be a tuple of parameters or an object representing something more complex.\n If set to None, forward_pass_callback will be invoked with no parameters.\n :return: None\n\n \"\"\"\n quantized_layers = self._get_qc_quantized_layers(self.model)\n\n for _, layer in quantized_layers:\n # Clear stats and encodings if they are present\n layer.reset_encodings()\n\n # And set the mode to analysis\n layer.set_mode(QcQuantizeOpMode.ANALYSIS)\n\n # Run forward iterations so we can collect statistics to compute the appropriate encodings\n self.model.eval()\n with torch.no_grad():\n _ = forward_pass_callback(self.model, forward_pass_callback_args)\n\n layers_with_invalid_encodings = []\n # Get the computed per-layer encodings and log them\n for name, layer in quantized_layers:\n layer.compute_encoding()\n\n # Before we return we set the mode to active - meaning ready for quantize/de-quantize\n # for layers with valid_encoding, otherwise we set to pass through\n if isinstance(layer, QcQuantizeRecurrent):\n has_invalid_encoding = self.set_mode_for_recurrent_module(layer, name)\n if has_invalid_encoding is True:\n layers_with_invalid_encodings.append(name)\n\n else:\n # By default we want to set the Quantization wrappers to ACTIVE mode\n layer.set_mode(QcQuantizeOpMode.ACTIVE)\n\n # Unless we have invalid encodings\n if (layer.output_quantizers[0].enabled and not layer.output_quantizers[0].encoding) or \\\n (layer.input_quantizer.enabled and not layer.input_quantizer.encoding):\n layers_with_invalid_encodings.append(name)\n layer.set_mode(QcQuantizeOpMode.PASSTHROUGH)\n\n if layers_with_invalid_encodings:\n logger.info('The following modules (name, input|output quantizer) did not have valid encodings and have '\n 'been set to passThrough mode: %s', layers_with_invalid_encodings)\n logger.info('This can be due to the quantizers not having been evaluated during the forward pass in '\n 'compute encodings. Evaluation is required to collect statistics needed to compute valid '\n 'encodings.\\n'\n 'As a result, the quantizers have been set to passThrough mode, meaning no quantization '\n 'noise will be simulated for these modules if they are evaluated in the future.\\n'\n 'If this is not desired, amend the forward pass to evaluate these modules, and recompute '\n 'encodings.')\n\n self._replace_wrappers_for_quantize_dequantize()\n\n @classmethod\n def set_mode_for_recurrent_module(cls, layer: QcQuantizeRecurrent, name: str):\n \"\"\"\n Sets Recurrent module to active or pass through mode based on quantizer state\n\n :param layer: Qc Quantizer layer for recurrent module\n :param name: layer name\n :return: True if the encoding is invalid\n\n \"\"\"\n is_quantizer_enabled = False\n has_invalid_encoding = False\n for quantizer_name, output_quantizer in layer.output_quantizers.items():\n if output_quantizer.enabled:\n if output_quantizer.encoding:\n encoding = output_quantizer.encoding\n logger.debug(\"Encoding for %s-%s: min=%f, max=%f, offset=%f. delta=%f, bw=%f\",\n name, quantizer_name, encoding.min, encoding.max,\n encoding.delta, encoding.offset, encoding.bw)\n is_quantizer_enabled = True\n else:\n has_invalid_encoding = True\n for quantizer_name, input_quantizer in layer.input_quantizers.items():\n if input_quantizer.enabled:\n if input_quantizer.encoding:\n encoding = input_quantizer.encoding\n logger.debug(\"Encoding for %s-%s: min=%f, max=%f, offset=%f. delta=%f, bw=%f\",\n name, quantizer_name, encoding.min, encoding.max,\n encoding.delta, encoding.offset, encoding.bw)\n is_quantizer_enabled = True\n else:\n has_invalid_encoding = True\n\n if is_quantizer_enabled is False or has_invalid_encoding is True:\n layer.set_mode(QcQuantizeOpMode.PASSTHROUGH)\n else:\n layer.set_mode(QcQuantizeOpMode.ACTIVE)\n return has_invalid_encoding\n\n def export(self, path: str, filename_prefix: str, input_shape: Union[Tuple, List[Tuple]],\n set_onnx_layer_names: bool = True, dummy_input: Union[torch.Tensor, Tuple] = None,\n use_torch_script_graph: bool = False, ):\n \"\"\"\n This method exports out the quant-sim model so it is ready to be run on-target.\n\n Specifically, the following are saved\n\n 1. The sim-model is exported to a regular PyTorch model without any simulation ops\n 2. The quantization encodings are exported to a separate JSON-formatted file that can\n then be imported by the on-target runtime (if desired)\n 3. Optionally, An equivalent model in ONNX format is exported. In addition, nodes in the ONNX model are named\n the same as the corresponding PyTorch module names. This helps with matching ONNX node to their quant\n encoding from #2.\n\n :param path: path where to store model pth and encodings\n :param filename_prefix: Prefix to use for filenames of the model pth and encodings files\n :param input_shape: shape of the model input as a tuple. If the model takes more than one input, specify this as\n a list of shapes.\n :param set_onnx_layer_names: If ONNX layer names should be set while exporting the model. Default is True\n :param dummy_input: Dummy input to the model. Used to parse model graph.\n :param use_torch_script_graph: if exporting of encoding should use torch script tensor names. Default is False\n :return: None\n\n \"\"\"\n # save the quantized model and encodings\n model_filename = filename_prefix + '.pth'\n model_path = os.path.join(path, model_filename)\n\n # Create a version of the model without any quantization ops\n model_to_export = copy.deepcopy(self.model)\n all_modules_in_model_to_export = [module for module in model_to_export.modules()]\n self._remove_quantization_wrappers(model_to_export, all_modules_in_model_to_export)\n torch.save(model_to_export, model_path)\n\n if not dummy_input:\n if input_shape is None:\n raise AssertionError('Must provide either input shape or a dummy input for export')\n dummy_input = tuple(utils.create_rand_tensors_given_shapes(input_shape,\n device=utils.get_device(model_to_export)))\n if use_torch_script_graph:\n self.export_torch_script_model_and_encodings(path, filename_prefix, model_to_export, dummy_input)\n else:\n self.export_onnx_model_and_encodings(path, filename_prefix, model_to_export,\n dummy_input, set_onnx_layer_names)\n\n def export_torch_script_model_and_encodings(self, path: str, filename_prefix: str, model: torch.nn.Module,\n dummy_input: Union[torch.Tensor, Tuple]):\n \"\"\"\n This method exports a onnx mode and the corrsponding encodings\n\n :param path: path where to store model pth and encodings\n :param filename_prefix: Prefix to use for filenames of the model pth and encodings files\n :param model: model without the quantsim ops\n :param dummy_input: Dummy input to the model. Used to parse model graph.\n :return: None\n \"\"\"\n with torch.no_grad():\n trace = torch.jit.trace(model, dummy_input)\n ts_path = os.path.join(path, filename_prefix + '.torchscript.pth')\n trace.save(ts_path)\n\n # reload the trace from the saved trace file\n trace = torch.jit.load(ts_path)\n torch_script_node_io_tensor_map, valid_param_set = \\\n torchscript_utils.get_node_to_io_tensor_names_map(model, trace, dummy_input)\n\n # Export encodings\n self._export_encodings_to_json(path, filename_prefix, torch_script_node_io_tensor_map, valid_param_set)\n\n def export_onnx_model_and_encodings(self, path: str, filename_prefix: str, model: torch.nn.Module,\n dummy_input: Union[torch.Tensor, Tuple], set_onnx_layer_names):\n \"\"\"\n This method exports a onnx model and the corresponding encodings\n\n :param path: path where to store model pth and encodings\n :param filename_prefix: Prefix to use for filenames of the model pth and encodings files\n :param model: model without the quantsim ops\n :param dummy_input: Dummy input to the model. Used to parse model graph.\n :param set_onnx_layer_names: If ONNX layer names should be set while exporting the model\n :return: None\n\n \"\"\"\n # Save model to onnx\n onnx_path = os.path.join(path, filename_prefix + '.onnx')\n torch.onnx.export(model, dummy_input, onnx_path)\n # Set the onnx layer names\n if set_onnx_layer_names:\n onnx_utils.OnnxSaver.set_node_names(onnx_path, model, dummy_input)\n onnx_model = onnx.load(onnx_path)\n onnx_node_to_io_tensor_map, valid_param_set = \\\n onnx_utils.OnnxSaver.get_onnx_node_to_io_tensor_names_map(onnx_model)\n\n # Export encodings\n self._export_encodings_to_json(path, filename_prefix, onnx_node_to_io_tensor_map, valid_param_set)\n\n def exclude_layers_from_quantization(self, layers_to_exclude: List[torch.nn.Module]):\n \"\"\"\n Excludes certain layers from being quantized-dequantized by the simulator\n :param layers_to_exclude: List of torch layers to exclude\n :return: None\n \"\"\"\n self._remove_quantization_wrappers(self.model, layers_to_exclude)\n\n def exclude_param_from_quantization(self, param_name_to_exclude: str):\n \"\"\"\n Excludes all parameters matching 'param_name' from quantization\n :param param_name_to_exclude: Name of the parameter to exclude\n :return: None\n \"\"\"\n for module in self.model.modules():\n if isinstance(module, (QcQuantizeWrapper, QcQuantizeRecurrent)):\n if param_name_to_exclude in module.param_quantizers:\n module.param_quantizers[param_name_to_exclude].enabled = False\n\n def _replace_wrappers_for_quantize_dequantize(self):\n pass\n\n @staticmethod\n def _validate_quantsim_inputs(quant_scheme: Union[str, QuantScheme], rounding_mode: str, default_output_bw: int,\n default_param_bw: int):\n \"\"\"\n Perform sanity checks on inputs to QuantSim\n :param quant_scheme: Quantization scheme. Supported options are 'tf_enhanced' or 'tf' or using Quant Scheme Enum\n QuantScheme.post_training_tf or QuantScheme.post_training_tf_enhanced\n :param rounding_mode: Rounding mode. Supported options are 'nearest' or 'stochastic'\n :param default_output_bw: Default bitwidth (4-31) to use for quantizing layer inputs and outputs\n :param default_param_bw: Default bitwidth (4-31) to use for quantizing layer parameters\n \"\"\"\n # sanity checks\n if quant_scheme not in ('tf_enhanced', 'tf') and not isinstance(quant_scheme, QuantScheme):\n raise ValueError('Parameter quantization mode is not a valid selection. Valid selections are tf, '\n 'tf_enhanced, QuantScheme.post_training_tf, QuantScheme.post_training_tf_enhanced')\n\n if rounding_mode not in ('nearest', 'stochastic'):\n raise ValueError('Parameter round mode is not a valid selection. Valid selections are nearest or '\n 'stochastic')\n\n if default_param_bw < 4 or default_param_bw > 32:\n raise ValueError('Default bitwidth for parameters must be between 4 and 32, not '+str(default_param_bw))\n\n if default_output_bw < 4 or default_output_bw > 32:\n raise ValueError('Activation bitwidth must be between 4 and 32, not '+str(default_output_bw))\n\n @staticmethod\n def _find_next_downstream_modules(op):\n downstream_modules = []\n for succeeding_op in list(op.output.consumers):\n if succeeding_op.get_module():\n downstream_modules.append(succeeding_op.get_module())\n\n elif succeeding_op.type == 'Split':\n downstream_modules += QuantizationSimModel._find_next_downstream_modules(succeeding_op)\n\n return downstream_modules\n\n def _export_encodings_to_json(self, path: str, filename_prefix: str, op_to_io_tensor_map: Dict,\n valid_param_set: set):\n \"\"\"\n Save the quantized model weight encodings\n\n :param path: path where to store model pth and encodings\n :param filename_prefix: filename to store exported weight encodings in json format\n :param op_to_io_tensor_map: Dictionary of layer to I/O tensor mapping from onnx or torch script model\n :param valid_param_set: a set of valid param input names in model\n \"\"\"\n\n # Create a dictionary to export to JSON\n activation_encodings = {}\n param_encodings = {}\n quantized_layers = self._get_qc_quantized_layers(self.model)\n\n for layer_name, layer in quantized_layers:\n self._update_encoding_dicts_for_layer(layer, layer_name, activation_encodings,\n param_encodings, op_to_io_tensor_map,\n valid_param_set)\n\n encodings_dict = {'activation_encodings': activation_encodings,\n 'param_encodings': param_encodings}\n\n # export weight encodings to output json file\n encoding_file_path = os.path.join(path, filename_prefix + '.encodings')\n with open(encoding_file_path, 'w') as encoding_fp:\n json.dump(encodings_dict, encoding_fp, sort_keys=True, indent=4)\n\n @staticmethod\n def _update_param_encodings_dict_for_layer(layer: torch.nn.Module, layer_name: str,\n param_encodings: Dict, valid_param_set: set):\n \"\"\"\n :param layer: layer as torch.nn.Module\n :param layer_name : Name of the layer\n :param param_encodings: dictionary of param encodings\n :param valid_param_set: a set of valid param input names in model\n \"\"\"\n\n disabled_param_quantizers = []\n for orig_param_name, param_quantizer in layer.param_quantizers.items():\n param_name = layer_name + '.' + orig_param_name\n if param_quantizer.enabled:\n if param_name in valid_param_set:\n encoding = utils.create_encoding_dict(param_quantizer.encoding,\n param_quantizer.use_symmetric_encodings)\n param_encodings[param_name] = [encoding]\n else:\n logger.error('Param tensor {%s} not found in valid param set', param_name)\n else:\n disabled_param_quantizers.append(orig_param_name)\n\n # retrieve the appropriate param generator\n if isinstance(layer, QcQuantizeWrapper):\n # pylint: disable=protected-access\n named_parameters = layer._module_to_wrap.named_parameters()\n else:\n named_parameters = layer.named_parameters(recurse=False)\n\n for name, param in named_parameters:\n # if the param quantizer was disabled generate encoding assuming bitwidth of 32\n if name in disabled_param_quantizers:\n param_name = layer_name + '.' + name\n param_quantizer = layer.param_quantizers[name]\n param_data = param.cpu().detach().numpy()\n encoding = utils.compute_encoding_for_given_bitwidth(param_data, 32, param_quantizer.quant_scheme,\n param_quantizer.use_symmetric_encodings)\n param_encodings[param_name] = [encoding]\n\n def _update_encoding_dicts_for_layer(self, layer: torch.nn.Module, layer_name: str, activation_encodings: Dict,\n param_encodings: Dict, op_to_io_tensor_map: Dict,\n valid_param_set: set):\n \"\"\"\n Add given layer param and activation encodings to respective dictionaries to be used for exporting encodings\n :param layer: layer as torch.nn.Module\n :param layer_name: Name of the layer\n :param activation_encodings: dictionary of activation encodings\n :param param_encodings: dictionary of param encodings\n :param op_to_io_tensor_map: ONNX or Torch Script map of layer name to it's input/output tensors\n :param valid_param_set: a set of valid param input names in model\n \"\"\"\n\n # pylint: disable=too-many-nested-blocks\n # pylint: disable=too-many-branches\n if layer_name not in op_to_io_tensor_map:\n logger.info(\"layer with name {%s} not found in model, not an issue; \"\n \"skip and continue \", layer_name)\n else:\n if isinstance(layer, QcQuantizeWrapper):\n # get activation quantizers\n if layer.input_quantizer.enabled:\n param_inputs = [layer_name + '.' + param_name for param_name in layer.param_quantizers]\n if op_to_io_tensor_map[layer_name].inputs:\n for input_tensor in op_to_io_tensor_map[layer_name].inputs:\n if input_tensor not in param_inputs:\n encoding = utils.create_encoding_dict(layer.input_quantizer.encoding,\n layer.input_quantizer.use_symmetric_encodings)\n activation_encodings[input_tensor] = [encoding]\n if layer.output_quantizers[0].enabled:\n if op_to_io_tensor_map[layer_name].outputs:\n for output_tensor in op_to_io_tensor_map[layer_name].outputs:\n encoding = utils.create_encoding_dict(layer.output_quantizers[0].encoding,\n layer.output_quantizers[0].use_symmetric_encodings)\n activation_encodings[output_tensor] = [encoding]\n\n # get param quantizers\n self._update_param_encodings_dict_for_layer(layer, layer_name, param_encodings, valid_param_set)\n\n if isinstance(layer, QcQuantizeRecurrent):\n onnx_activations_to_quantizers, onnx_params_to_quantizers = \\\n layer.get_activation_param_quantizers_for_onnx_tensors(op_to_io_tensor_map[layer_name])\n for tensor, quantizer in onnx_activations_to_quantizers.items():\n encoding = utils.create_encoding_dict(quantizer.encoding, quantizer.use_symmetric_encodings)\n activation_encodings[tensor] = [encoding]\n for tensor, quantizer in onnx_params_to_quantizers.items():\n encoding = utils.create_encoding_dict(quantizer.encoding, quantizer.use_symmetric_encodings)\n param_encodings[tensor] = [encoding]\n\n @staticmethod\n def _get_qc_quantized_layers(model) -> List[Tuple[str, QcQuantizeWrapper]]:\n quantized_layers = []\n for name, module in model.named_modules():\n if isinstance(module, (QcQuantizeWrapper, QcQuantizeRecurrent)):\n quantized_layers.append((name, module))\n return quantized_layers\n\n @staticmethod\n def _is_leaf_module(module):\n \"\"\"Utility function to determine if the given module is a leaf module - that is, does not have children modules\n :return:\n True if the module is a leaf, False otherwise\n \"\"\"\n module_list = list(module.modules())\n return bool(len(module_list) == 1)\n\n @staticmethod\n def _is_quantizable_module(module_ref):\n \"\"\" Function to check if a module is eligible for quantization.\n If the module is NOT an PyTorch module type or if the module was already\n Quantized or if the module is in the layers_to_ignore list, don't quantize.\n \"\"\"\n\n if isinstance(module_ref, unquantizable_modules):\n logger.debug(\"Module %s not quantizable\", module_ref)\n return False\n\n logger.debug(\"Module %s is quantizable\", module_ref)\n return True\n\n def _create_quantizer_module(self, module_to_quantize: torch.nn.Module) -> torch.nn.Module:\n \"\"\"Instantiates wrapper based on quant scheme\n \"\"\"\n assert self._quant_scheme in [QuantScheme.post_training_tf, QuantScheme.post_training_tf_enhanced]\n\n # Set quantizer to be a module replacer if it is in qc_quantize_modules_dict, otherwise set as\n # QcPostTrainingWrapper.\n quantizer = qc_quantize_modules_dict.get(type(module_to_quantize), QcPostTrainingWrapper)\n quantized_module = quantizer(module_to_quantize, self._default_param_bw, self._default_output_bw,\n self._rounding_mode, self._quant_scheme)\n\n return quantized_module\n\n def _add_quantization_wrappers(self, module):\n \"\"\"Recursively add quantization wrappers to all appropriate modules starting with module\n \"\"\"\n for module_name, module_ref in module.named_children():\n\n logger.debug(\"nn.Module found : %s\", module_ref)\n\n # check if the module already quantized then ignore\n if not self._is_quantizable_module(module_ref):\n continue\n\n # check if the module is leaf or not\n if self._is_leaf_module(module_ref):\n\n # Create a new QcQuantize wrapper module\n quantized_module = self._create_quantizer_module(module_ref)\n\n setattr(module, module_name, quantized_module)\n\n # recursively call children modules\n else:\n self._add_quantization_wrappers(module_ref)\n\n @classmethod\n def _remove_quantization_wrappers(cls, starting_module, list_of_modules_to_exclude):\n \"\"\"\n Recursively remove quantization wrappers from all appropriate modules starting with a given module\n :param starting_module: Module to recursive search downstream from\n :param list_of_modules_to_exclude: List of torch modules to remove quantization wrappers from (if present)\n :return: None\n \"\"\"\n for module_name, module_ref in starting_module.named_children():\n\n # If modules is in the exclude list, remove the wrapper\n if module_ref in list_of_modules_to_exclude:\n\n if isinstance(module_ref, QcQuantizeWrapper):\n # Remove the wrapper, gets auto-deleted\n # pylint: disable=protected-access\n setattr(starting_module, module_name, module_ref._module_to_wrap)\n\n elif isinstance(module_ref, QcQuantizeStandAloneBase):\n setattr(starting_module, module_name, PassThroughOp())\n\n elif isinstance(module_ref, QcQuantizeRecurrent):\n module_ref.update_params()\n setattr(starting_module, module_name, module_ref.module_to_quantize)\n\n # Recursively call children modules if present\n if not cls._is_leaf_module(module_ref):\n cls._remove_quantization_wrappers(module_ref, list_of_modules_to_exclude)\n\n def configure_quantization_ops(self, connected_graph: Union[None, ConnectedGraph], config_file: str):\n \"\"\"\n Configure inserted quantize ops using config file\n :param connected_graph: Connected graph representation of the model\n :param config_file: Configuration file to use\n \"\"\"\n if connected_graph is None:\n logger.error('A connected graph failed to be built.\\n'\n 'Unable to proceed with automatically configuring quantization ops using the config file.\\n'\n 'Please configure quantization ops manually by redefining '\n 'QuantizationSimModel.configure_quantization_ops()')\n raise AssertionError\n QuantSimConfigurator(self.model, connected_graph, config_file)\n\n def set_and_freeze_param_encodings(self, encoding_path: str):\n \"\"\"\n Set and freeze parameter encodings from encodings JSON file\n :param encoding_path: path from where to load parameter encodings file\n \"\"\"\n # Load parameter encodings file\n with open(encoding_path) as json_file:\n param_encodings = json.load(json_file)\n\n for name, quant_module in self.model.named_modules():\n if isinstance(quant_module, QcPostTrainingWrapper):\n quant_module.set_and_freeze_param_encoding(name, param_encodings)\n\n\ndef save_checkpoint(quant_sim_model: QuantizationSimModel, file_path: str):\n \"\"\"\n This API provides a way for the user to save a checkpoint of the quantized model which can\n be loaded at a later point to continue fine-tuning e.g.\n See also load_checkpoint()\n\n :param quant_sim_model: QuantizationSimModel to save checkpoint for\n :param file_path: Path to the file where you want to save the checkpoint\n :return: None\n \"\"\"\n with open(file_path, 'wb') as file:\n pickle.dump(quant_sim_model, file)\n\n\ndef load_checkpoint(file_path: str) -> QuantizationSimModel:\n \"\"\"\n Load the quantized model\n\n :param file_path: Path to the file where you want to save the checkpoint\n :return: A new instance of the QuantizationSimModel created after loading the checkpoint\n \"\"\"\n with open(file_path, 'rb') as file:\n sim = pickle.load(file)\n return sim\n"
] | [
[
"torch.onnx.export",
"torch.jit.load",
"torch.jit.trace",
"torch.no_grad",
"torch.save"
]
] |
RiverTate/vaspvis | [
"21d426be84b523d81afb9e4a9b43044f9a792b64"
] | [
"vaspvis/dos.py"
] | [
"import matplotlib.pyplot as plt\nfrom matplotlib.ticker import MaxNLocator, LogLocator\nfrom pymatgen.io.vasp.outputs import Vasprun\nfrom pymatgen.io.vasp.inputs import Poscar, Incar\nfrom pymatgen.electronic_structure.core import Spin, Orbital\nfrom pymatgen.core.periodic_table import Element\nfrom pychemia.code.vasp.doscar import VaspDoscar\nfrom scipy.ndimage.filters import gaussian_filter1d\nfrom scipy.ndimage import gaussian_filter\nfrom scipy.interpolate import interp2d\nfrom functools import reduce\nimport numpy as np\nimport pandas as pd\nfrom ase.visualize.plot import plot_atoms\nfrom pymatgen.io.ase import AseAtomsAdaptor\nimport copy\nimport time\nimport os\n\nimport matplotlib as mpl\nmpl.rcParams.update(mpl.rcParamsDefault)\n\nclass Dos:\n \"\"\"\n This class contains all the methods for contructing density of states plots from the outputs of VASP calculations.\n\n Parameters:\n folder (str): This is the folder that contains the VASP files.\n spin (str): Which spin direction to parse ('up' or 'down')\n combination_method (str): If the spin option is 'both', the combination method can either be additive or substractive\n by passing 'add' or 'sub'. It spin is passed as 'up' or 'down' this option is ignored.\n \"\"\"\n\n def __init__(\n self,\n folder,\n spin='up',\n soc_axis=None,\n combination_method=\"add\",\n sp_method='percentage',\n shift_efermi=0,\n ):\n self.folder = folder\n self.spin = spin\n self.soc_axis = soc_axis\n self.combination_method = combination_method\n self.sp_method = sp_method\n self.incar = Incar.from_file(\n os.path.join(folder, 'INCAR')\n )\n if 'LORBIT' in self.incar:\n if self.incar['LORBIT'] >= 11:\n self.lorbit = True\n else:\n self.lorbit = False\n else:\n self.lorbit = False\n\n if self.lorbit:\n if os.path.isfile(os.path.join(folder, 'dos.npy')) and os.path.isfile(os.path.join(folder, 'projected_dos.npy')):\n with open(os.path.join(folder, 'dos.npy'), 'rb') as dos_file:\n dos = np.load(dos_file)\n with open(os.path.join(folder, 'projected_dos.npy'), 'rb') as projected_dos_file:\n projected_dos = np.load(projected_dos_file)\n\n self.doscar = {\n 'total': dos,\n 'projected': projected_dos,\n }\n else:\n if self._check_f_error():\n self._fix_doscar()\n\n self.doscar = VaspDoscar.parse_doscar(os.path.join(folder, 'DOSCAR'))\n np.save(os.path.join(folder, 'dos.npy'), self.doscar['total'])\n np.save(os.path.join(folder, 'projected_dos.npy'), self.doscar['projected'])\n else:\n if os.path.isfile(os.path.join(folder, 'dos.npy')):\n with open(os.path.join(folder, 'dos.npy'), 'rb') as dos_file:\n dos = np.load(dos_file)\n\n self.doscar = {\n 'total': dos,\n }\n else:\n self.doscar = VaspDoscar.parse_doscar(os.path.join(folder, 'DOSCAR'))\n np.save(os.path.join(folder, 'dos.npy'), self.doscar['total'])\n\n self.efermi = float(os.popen(f'grep E-fermi {os.path.join(folder, \"OUTCAR\")}').read().split()[2]) + shift_efermi\n self.poscar = Poscar.from_file(\n os.path.join(folder, 'POSCAR'),\n check_for_POTCAR=False,\n read_velocities=False\n )\n self.forbitals = self._check_f_orb()\n self.color_dict = {\n 0: '#FF0000',\n 1: '#0000FF',\n 2: '#008000',\n 3: '#800080',\n 4: '#E09200',\n 5: '#FF5C77',\n 6: '#778392',\n 7: '#07C589',\n 8: '#40BAF2',\n 9: '#FF0000',\n 10: '#0000FF',\n 11: '#008000',\n 12: '#800080',\n 13: '#E09200',\n 14: '#FF5C77',\n 15: '#778392',\n }\n self.orbital_labels = {\n 0: 's',\n 1: 'p_{y}',\n 2: 'p_{x}',\n 3: 'p_{z}',\n 4: 'd_{xy}',\n 5: 'd_{yz}',\n 6: 'd_{z^{2}}',\n 7: 'd_{xz}',\n 8: 'd_{x^{2}-y^{2}}',\n 9: 'f_{y^{3}x^{2}}',\n 10: 'f_{xyz}',\n 11: 'f_{yz^{2}}',\n 12: 'f_{z^{3}}',\n 13: 'f_{xz^{2}}',\n 14: 'f_{zx^{3}}',\n 15: 'f_{x^{3}}',\n }\n self.spd_relations = {\n 's': 0,\n 'p': 1,\n 'd': 2,\n 'f': 3,\n }\n\n if 'LSORBIT' in self.incar:\n if self.incar['LSORBIT']:\n self.lsorbit = True\n else:\n self.lsorbit = False\n else:\n self.lsorbit = False\n\n if 'ISPIN' in self.incar:\n if self.incar['ISPIN'] == 2:\n self.ispin = True\n else:\n self.ispin = False\n else:\n self.ispin = False\n\n self.spin_dict = {'up': Spin.up, 'down': Spin.down}\n\n self.tdos_array = self._load_tdos()\n\n if self.lorbit:\n self.pdos_array = self._load_pdos()\n\n if self.lsorbit and self.soc_axis is not None:\n self.tdos_array[:,1] = self.pdos_array.sum(axis=1).sum(axis=1)\n\n\n def _check_f_orb(self):\n f = False\n for element in self.poscar.site_symbols:\n if element != 'H':\n E = Element(element)\n orbitals = list(E.atomic_orbitals.keys())\n for orb in orbitals:\n if 'f' in orb:\n f = True\n \n return f\n\n def _check_f_error(self):\n with open(os.path.join(self.folder, 'DOSCAR'), 'rb') as f:\n f.seek(-2, os.SEEK_END)\n while f.read(1) != b'\\n':\n f.seek(-2, os.SEEK_CUR)\n last_line = f.readline().decode()\n\n last_line_len = len(last_line.split())\n\n if last_line_len == 28:\n return True\n else:\n return False\n\n def _fix_doscar(self):\n doscar = []\n with open(os.path.join(self.folder, 'DOSCAR')) as f:\n for line in f:\n split_line = line.split()\n doscar.append(split_line)\n\n num_atoms = int(doscar[0][1])\n nedos = int(doscar[5][2])\n nedos_f = 2 * nedos\n start_inds = nedos + 7\n\n top_file = []\n\n with open(os.path.join(self.folder, 'DOSCAR')) as f:\n count = 0\n for line in f:\n top_file.append(line)\n count += 1\n if count == start_inds:\n break\n\n a = np.c_[[np.arange(0,nedos_f-1,2),np.arange(1,nedos_f,2)]].T\n a = np.c_[[a for _ in range(num_atoms)]]\n b = np.array([1] + [nedos_f for _ in range(num_atoms-1)])\n c = np.arange(num_atoms)\n d = np.arange(num_atoms)\n d[0] = 1\n inds = a + (b*c)[:,None,None] + c[:,None,None]\n inds += start_inds\n\n new_list = []\n\n for i, ind in enumerate(inds):\n inbetween_ind = np.max(ind) + 1\n for j in ind:\n new_list.append('\\t' + ' '.join(doscar[j[0]] + doscar[j[1]]))\n\n if i != inds.shape[0]-1:\n new_list.append('\\t' + ' '.join(doscar[inbetween_ind]))\n\n new_doscar = ''.join([''.join(top_file), '\\n'.join(new_list)])\n\n os.rename(os.path.join(self.folder, 'DOSCAR'), os.path.join(self.folder, 'DOSCAR_old'))\n\n with open(os.path.join(self.folder, 'DOSCAR'), 'w') as x:\n x.write(new_doscar)\n\n def _load_tdos(self):\n \"\"\"\n This function loads the total density of states into a dictionary\n\n Returns:\n tdos_dict (dict[str][np.ndarray]): Dictionary that consists or the\n energies and densities of the system.\n \"\"\"\n\n tdos = self.doscar['total']\n tdos[:,0] = tdos[:,0] - self.efermi\n\n if self.spin == 'up':\n tdos = tdos[:,:2]\n elif self.spin == 'down':\n tdos = tdos[:,[0,2]]\n tdos[:,1] = -tdos[:,1]\n elif self.spin == 'both':\n tdos_up = tdos[:,1]\n tdos_down = tdos[:,2]\n if self.combination_method == \"add\":\n tdos = np.c_[tdos[:,0], tdos_up + tdos_down]\n if self.combination_method == \"sub\":\n if self.sp_method == 'percentage':\n tdos = np.c_[tdos[:,0], (tdos_up - tdos_down) / (tdos_up + tdos_down)]\n elif self.sp_method == 'absolute':\n tdos = np.c_[tdos[:,0], tdos_up - tdos_down]\n\n return tdos\n\n\n def _load_pdos(self):\n \"\"\"\n This function loads the projected density of states into a dictionary\n of the form:\n atom index --> orbital projections\n\n Returns:\n pdos_dict (dict[int][pd.DataFrame]): Dictionary that contains a data frame\n with the orbital weights for each atom index.\n \"\"\"\n\n pdos = self.doscar['projected']\n pdos = np.transpose(pdos, axes=(1,0,2))\n\n if self.spin == 'up':\n if not self.forbitals:\n if self.lsorbit:\n if self.soc_axis is None:\n pdos = pdos[:,:,[(j*4) + 1 for j in range(9)]]\n elif self.soc_axis == 'x':\n pdos = pdos[:,:,[(j*4) + 2 for j in range(9)]]\n elif self.soc_axis == 'y':\n pdos = pdos[:,:,[(j*4) + 3 for j in range(9)]]\n elif self.soc_axis == 'z':\n pdos = pdos[:,:,[(j*4) + 4 for j in range(9)]]\n\n if self.soc_axis is not None:\n pdos_up = np.zeros(pdos.shape)\n pdos_up[np.where(pdos > 0)] = pdos[np.where(pdos > 0)]\n pdos = pdos_up\n\n elif self.ispin and not self.lsorbit:\n pdos = pdos[:,:,[(j*2) + 1 for j in range(9)]]\n else:\n pdos = pdos[:,:,1:]\n else:\n if self.lsorbit:\n if self.soc_axis is None:\n pdos = pdos[:,:,[(j*4) + 1 for j in range(16)]]\n if self.soc_axis == 'x':\n pdos = pdos[:,:,[(j*4) + 2 for j in range(16)]]\n if self.soc_axis == 'y':\n pdos = pdos[:,:,[(j*4) + 3 for j in range(16)]]\n if self.soc_axis == 'z':\n pdos = pdos[:,:,[(j*4) + 4 for j in range(16)]]\n\n if self.soc_axis is not None:\n pdos_up = np.zeros(pdos.shape)\n pdos_up[np.where(pdos > 0)] = pdos[np.where(pdos > 0)]\n pdos = pdos_up\n\n elif self.ispin and not self.lsorbit:\n pdos = pdos[:,:,[(j*2) + 1 for j in range(16)]]\n else:\n pdos = pdos[:,:,1:]\n if self.spin == 'down':\n if not self.forbitals:\n if self.lsorbit:\n if self.soc_axis is None:\n raise(\"You have selected spin='down' for a SOC calculation, but soc_axis has not been selected. Please set soc_axis to 'x', 'y', or 'z' for this function to work.\")\n elif self.soc_axis == 'x':\n pdos = pdos[:,:,[(j*4) + 2 for j in range(9)]]\n elif self.soc_axis == 'y':\n pdos = pdos[:,:,[(j*4) + 3 for j in range(9)]]\n elif self.soc_axis == 'z':\n pdos = pdos[:,:,[(j*4) + 4 for j in range(9)]]\n\n if self.soc_axis is not None:\n pdos_down = np.zeros(pdos.shape)\n pdos_down[np.where(pdos < 0)] = pdos[np.where(pdos < 0)]\n pdos = pdos_down\n\n elif self.ispin and not self.lsorbit:\n pdos = -pdos[:,:,[(j*2) + 2 for j in range(9)]]\n else:\n if self.lsorbit:\n if self.soc_axis is None:\n raise(\"You have selected spin='down' for a SOC calculation, but soc_axis has not been selected. Please set soc_axis to 'x', 'y', or 'z' for this function to work.\")\n if self.soc_axis == 'x':\n pdos = pdos[:,:,[(j*4) + 2 for j in range(16)]]\n if self.soc_axis == 'y':\n pdos = pdos[:,:,[(j*4) + 3 for j in range(16)]]\n if self.soc_axis == 'z':\n pdos = pdos[:,:,[(j*4) + 4 for j in range(16)]]\n\n if self.soc_axis is not None:\n pdos_down = np.zeros(pdos.shape)\n pdos_down[np.where(pdos < 0)] = pdos[np.where(pdos < 0)]\n pdos = pdos_down\n\n elif self.ispin and not self.lsorbit:\n pdos = -pdos[:,:,[(j*2) + 2 for j in range(16)]]\n if self.spin == 'both':\n if not self.forbitals:\n if self.lsorbit:\n if self.soc_axis is None:\n raise(\"You have selected spin='down' for a SOC calculation, but soc_axis has not been selected. Please set soc_axis to 'x', 'y', or 'z' for this function to work.\")\n elif self.soc_axis == 'x':\n pdos = pdos[:,:,[(j*4) + 2 for j in range(9)]]\n elif self.soc_axis == 'y':\n pdos = pdos[:,:,[(j*4) + 3 for j in range(9)]]\n elif self.soc_axis == 'z':\n pdos = pdos[:,:,[(j*4) + 4 for j in range(9)]]\n\n if self.soc_axis is not None:\n pdos_up = np.zeros(pdos.shape)\n pdos_up[np.where(pdos > 0)] = pdos[np.where(pdos > 0)]\n pdos_down = np.zeros(pdos.shape)\n pdos_down[np.where(pdos < 0)] = -pdos[np.where(pdos < 0)]\n\n elif self.ispin and not self.lsorbit:\n pdos_up = pdos[:,:,[(j*2) + 1 for j in range(9)]]\n pdos_down = pdos[:,:,[(j*2) + 2 for j in range(9)]]\n else:\n if self.lsorbit:\n if self.soc_axis is None:\n raise(\"You have selected spin='down' for a SOC calculation, but soc_axis has not been selected. Please set soc_axis to 'x', 'y', or 'z' for this function to work.\")\n if self.soc_axis == 'x':\n pdos = pdos[:,:,[(j*4) + 2 for j in range(16)]]\n if self.soc_axis == 'y':\n pdos = pdos[:,:,[(j*4) + 3 for j in range(16)]]\n if self.soc_axis == 'z':\n pdos = pdos[:,:,[(j*4) + 4 for j in range(16)]]\n\n if self.soc_axis is not None:\n pdos_up = np.zeros(pdos.shape)\n pdos_up[np.where(pdos > 0)] = pdos[np.where(pdos > 0)]\n pdos_down = np.zeros(pdos.shape)\n pdos_down[np.where(pdos < 0)] = -pdos[np.where(pdos < 0)]\n\n elif self.ispin and not self.lsorbit:\n pdos_up = pdos[:,:,[(j*2) + 1 for j in range(16)]]\n pdos_down = pdos[:,:,[(j*2) + 2 for j in range(16)]]\n\n if self.combination_method == 'add':\n pdos = pdos_up + pdos_down\n if self.combination_method == 'sub':\n if self.sp_method == 'percentage':\n pdos = (pdos_up - pdos_down) / (pdos_up + pdos_down)\n elif self.sp_method == 'absolute':\n pdos = pdos_up - pdos_down\n\n # tdos = self.tdos_array[:,-1]\n # summed_pdos = np.sum(np.sum(pdos, axis=1), axis=1)\n # scale_factor = np.nan_to_num(np.divide(tdos, summed_pdos))\n # pdos = np.multiply(pdos, scale_factor[:,None,None])\n\n return pdos\n\n\n def _sum_spd(self, spd):\n \"\"\"\n This function sums the weights of the s, p, and d orbitals for each atom\n and creates a dictionary of the form:\n band index --> s,p,d orbital weights\n\n Returns:\n spd_dict (dict([str][pd.DataFrame])): Dictionary that contains the summed weights for the s, p, and d orbitals for each band\n \"\"\"\n\n if not self.forbitals:\n spd_indices = [np.array([False for _ in range(9)]) for i in range(3)]\n spd_indices[0][0] = True\n spd_indices[1][1:4] = True\n spd_indices[2][4:] = True\n else:\n spd_indices = [np.array([False for _ in range(16)]) for i in range(4)]\n spd_indices[0][0] = True\n spd_indices[1][1:4] = True\n spd_indices[2][4:9] = True\n spd_indices[3][9:] = True\n\n orbital_contributions = np.sum(self.pdos_array, axis=1)\n\n spd_contributions = np.transpose(\n np.array([\n np.sum(orbital_contributions[:,ind], axis=1) for ind in spd_indices\n ]), axes=[1,0]\n )\n\n spd_contributions = spd_contributions[:,[self.spd_relations[orb] for orb in spd]]\n\n return spd_contributions\n\n\n\n def _sum_orbitals(self, orbitals):\n \"\"\"\n This function finds the weights of desired orbitals for all atoms and\n returns a dictionary of the form:\n band index --> orbital index\n\n Parameters:\n orbitals (list): List of desired orbitals. \n 0 = s\n 1 = py\n 2 = pz\n 3 = px\n 4 = dxy\n 5 = dyz\n 6 = dz2\n 7 = dxz\n 8 = dx2-y2\n 9 = fy3x2\n 10 = fxyz\n 11 = fyz2\n 12 = fz3\n 13 = fxz2\n 14 = fzx3\n 15 = fx3\n\n Returns:\n orbital_dict (dict[str][pd.DataFrame]): Dictionary that contains the projected weights of the selected orbitals.\n \"\"\"\n orbital_contributions = self.pdos_array.sum(axis=1)\n orbital_contributions = orbital_contributions[:,orbitals]\n\n return orbital_contributions\n\n def _sum_atoms(self, atoms, spd=False):\n \"\"\"\n This function finds the weights of desired atoms for all orbitals and\n returns a dictionary of the form:\n band index --> atom index\n\n Parameters:\n atoms (list): List of desired atoms where atom 0 is the first atom in\n the POSCAR file. \n\n Returns:\n atom_dict (dict[str][pd.DataFrame]): Dictionary that contains the projected\n weights of the selected atoms.\n \"\"\"\n\n if spd:\n if not self.forbitals:\n spd_indices = [np.array([False for _ in range(9)]) for i in range(3)]\n spd_indices[0][0] = True\n spd_indices[1][1:4] = True\n spd_indices[2][4:] = True\n else:\n spd_indices = [np.array([False for _ in range(16)]) for i in range(4)]\n spd_indices[0][0] = True\n spd_indices[1][1:4] = True\n spd_indices[2][4:9] = True\n spd_indices[3][9:] = True\n\n atoms_spd = np.transpose(np.array([\n np.sum(self.pdos_array[:,:,ind], axis=2) for ind in spd_indices\n ]), axes=(1,2,0))\n\n return atoms_spd\n else:\n atoms_array = self.pdos_array.sum(axis=2)\n if atoms is not None:\n atoms_array = atoms_array[:,atoms]\n\n return atoms_array\n\n def _sum_elements(self, elements, orbitals=False, spd=False, spd_options=None):\n \"\"\"\n This function sums the weights of the orbitals of specific elements within the\n calculated structure and returns a dictionary of the form:\n band index --> element label --> orbital weights for orbitals = True\n band index --> element label for orbitals = False\n This is useful for structures with many elements because manually entering indicies is\n not practical for large structures.\n\n Parameters:\n elements (list): List of element symbols to sum the weights of.\n orbitals (bool): Determines whether or not to inclue orbitals or not\n (True = keep orbitals, False = sum orbitals together )\n spd (bool): Determines whether or not to sum the s, p, and d orbitals\n\n\n Returns:\n element_dict (dict([str][str][pd.DataFrame])): Dictionary that contains the summed weights for each orbital for a given element in the structure.\n \"\"\"\n\n poscar = self.poscar\n natoms = poscar.natoms\n symbols = poscar.site_symbols\n pdos_array = self.pdos_array\n\n element_list = np.hstack(\n [[symbols[i] for j in range(natoms[i])] for i in range(len(symbols))]\n )\n\n element_indices = [np.where(np.isin(element_list, element))[0] for element in elements]\n\n element_orbitals = np.transpose(\n np.array([\n np.sum(pdos_array[:,ind,:], axis=1) for ind in element_indices\n ]), axes=(1,0,2)\n )\n\n if orbitals:\n return element_orbitals\n elif spd:\n if not self.forbitals:\n spd_indices = [np.array([False for _ in range(9)]) for i in range(3)]\n spd_indices[0][0] = True\n spd_indices[1][1:4] = True\n spd_indices[2][4:] = True\n else:\n spd_indices = [np.array([False for _ in range(16)]) for i in range(4)]\n spd_indices[0][0] = True\n spd_indices[1][1:4] = True\n spd_indices[2][4:9] = True\n spd_indices[3][9:] = True\n\n element_spd = np.transpose(np.array([\n np.sum(element_orbitals[:,:,ind], axis=2) for ind in spd_indices\n ]), axes=(1,2,0))\n\n return element_spd\n else:\n element_array = np.sum(element_orbitals, axis=2)\n\n return element_array\n\n\n def _smear(self, dos, sigma):\n \"\"\"\n This function applied a 1D gaussian filter to the density of states\n\n Parameters:\n dos (np.ndarray): Array of densities.\n sigma (float): Standard deviation used in the gaussian filter.\n\n\n Returns:\n _smeared_dos (np.ndarray): Array of _smeared densities.\n \"\"\"\n\n diff = np.diff(self.tdos_array[:,0])\n avgdiff = np.mean(diff)\n _smeared_dos = gaussian_filter1d(dos, sigma / avgdiff)\n\n return _smeared_dos\n\n def _set_density_lims(self, ax, tdensity, tenergy, erange, energyaxis, spin, partial=False, is_dict=False, idx=None, multiple=False, log_scale=False):\n energy_in_plot_index = np.where(\n (tenergy >= erange[0]) & (tenergy <= erange[1])\n )[0]\n\n tdensity = tdensity[energy_in_plot_index]\n\n if len(np.squeeze(tdensity).shape) == 1:\n density_in_plot = np.squeeze(tdensity) \n else:\n if spin == 'up' or spin == 'both':\n max_index = np.argmax(np.max(tdensity, axis=0))\n density_in_plot = tdensity[:,max_index]\n else:\n min_index = np.argmin(np.min(tdensity, axis=0))\n density_in_plot = tdensity[:,min_index]\n\n if len(ax.lines) == 0:\n if energyaxis == 'y':\n ax.set_ylim(erange)\n if spin == 'up' or spin == 'both':\n ax.set_xlim(0, np.max(density_in_plot) * 1.1)\n if log_scale:\n ax.set_xlim(np.min(density_in_plot), np.max(density_in_plot) + np.abs(np.max(density_in_plot) * 0.1))\n else:\n ax.set_xlim(0, np.max(density_in_plot) * 1.1)\n elif spin == 'down':\n ax.set_xlim(np.min(density_in_plot) * 1.1, 0)\n elif energyaxis == 'x':\n ax.set_xlim(erange)\n if spin == 'up' or spin == 'both':\n if log_scale:\n ax.set_ylim(np.min(density_in_plot), np.max(density_in_plot) + np.abs(np.max(density_in_plot) * 0.1))\n else:\n ax.set_ylim(0, np.max(density_in_plot) * 1.1)\n elif spin == 'down':\n ax.set_ylim(np.min(density_in_plot) * 1.1, 0)\n elif len(ax.lines) > 0:\n if energyaxis == 'y':\n ax.set_ylim(erange)\n xlims = ax.get_xlim()\n if xlims[0] == 0:\n if spin == 'up' or spin == 'both':\n ax.set_xlim(0, np.max(density_in_plot) * 1.1)\n elif spin == 'down':\n ax.set_xlim(np.min(density_in_plot) * 1.1, xlims[1])\n if xlims[1] == 0:\n if spin == 'up' or spin == 'both':\n ax.set_xlim(xlims[0], np.max(density_in_plot) * 1.1)\n elif spin == 'down':\n ax.set_xlim(np.min(density_in_plot) * 1.1, 0)\n elif energyaxis == 'x':\n ax.set_xlim(erange)\n ylims = ax.get_ylim()\n if ylims[0] == 0:\n if spin == 'up' or spin == 'both':\n ax.set_ylim(0, np.max(density_in_plot) * 1.1)\n elif spin == 'down':\n ax.set_ylim(np.min(density_in_plot) * 1.1, ylims[1])\n if ylims[1] == 0:\n if spin == 'up' or spin == 'both':\n ax.set_ylim(ylims[0], np.max(density_in_plot) * 1.1)\n elif spin == 'down':\n ax.set_ylim(np.min(density_in_plot) * 1.1, 0)\n\n\n # def _group_layers(self):\n # poscar = self.poscar\n # sites = poscar.structure.sites\n # zvals = np.array([site.c for site in sites])\n # unique_values = np.sort(np.unique(np.round(zvals, 3)))\n # diff = np.mean(np.diff(unique_values)) * 0.2\n#\n # grouped = False\n # groups = []\n # group_heights = []\n # zvals_copy = copy.deepcopy(zvals)\n # while not grouped:\n # if len(zvals_copy) > 0:\n # group_index = np.where(\n # np.isclose(zvals, np.min(zvals_copy), atol=diff)\n # )[0]\n # group_heights.append(np.min(zvals_copy))\n # zvals_copy = np.delete(zvals_copy, np.where(\n # np.isin(zvals_copy, zvals[group_index]))[0])\n # groups.append(group_index)\n # else:\n # grouped = True\n#\n # return groups, np.array(group_heights)\n\n def _sum_layers(self, layers, atol=None, custom_layer_inds=None):\n from vaspvis.utils import group_layers\n if custom_layer_inds is None:\n groups, _ = group_layers(self.poscar.structure, atol=atol)\n else:\n groups = custom_layer_inds\n atom_densities = self._sum_atoms(atoms=None)\n densities = np.vstack([np.sum(np.vstack(atom_densities[:,[group]]), axis=1) for group in groups])\n summed_layers = np.sum(densities[layers], axis=0)\n\n return summed_layers\n\n def _add_legend(self, ax, names, colors, fontsize=5, markersize=2):\n legend_lines = []\n legend_labels = []\n for name, color in zip(names, colors):\n legend_lines.append(plt.Line2D(\n [0],\n [0],\n marker='o',\n markersize=markersize,\n linestyle='',\n color=color\n ))\n legend_labels.append(\n f'${name}$'\n )\n\n leg = ax.get_legend()\n\n if leg is None:\n handles = legend_lines\n labels = legend_labels\n else:\n handles = [l._legmarker for l in leg.legendHandles]\n labels = [text._text for text in leg.texts]\n handles.extend(legend_lines)\n labels.extend(legend_labels)\n\n ax.legend(\n handles,\n labels,\n ncol=1,\n loc='upper left',\n fontsize=fontsize,\n bbox_to_anchor=(1, 1),\n borderaxespad=0,\n frameon=False,\n handletextpad=0.1,\n )\n\n\n def _plot_projected_general(self, ax, energy, projected_data, colors, sigma, erange, linewidth, alpha_line, alpha, fill, energyaxis, total):\n energy_in_plot_index = np.where(\n (energy >= erange[0] - 0.5) & (energy <= erange[1] + 0.5)\n )[0]\n energy = energy[energy_in_plot_index]\n projected_data = projected_data[energy_in_plot_index]\n\n if sigma > 0:\n for i in range(projected_data.shape[-1]):\n projected_data[:,i] = self._smear(\n projected_data[:,i],\n sigma=sigma,\n )\n\n if total:\n self.plot_plain(\n ax=ax,\n linewidth=linewidth,\n fill=fill,\n alpha=alpha,\n alpha_line=alpha_line,\n sigma=sigma,\n energyaxis=energyaxis,\n erange=erange,\n )\n else:\n self._set_density_lims(\n ax=ax,\n tdensity=projected_data,\n tenergy=energy,\n erange=erange,\n energyaxis=energyaxis,\n spin=self.spin,\n partial=True,\n )\n\n for i in range(projected_data.shape[-1]):\n\n pdensity = projected_data[:,i]\n\n if energyaxis == 'y':\n ax.plot(\n pdensity,\n energy,\n color=colors[i],\n linewidth=linewidth,\n alpha=alpha_line\n )\n\n if fill:\n ax.fill_betweenx(\n energy,\n pdensity,\n 0,\n color=colors[i],\n alpha=alpha,\n )\n\n if energyaxis == 'x':\n ax.plot(\n energy,\n pdensity,\n color=colors[i],\n linewidth=linewidth,\n alpha=alpha_line\n )\n\n if fill:\n ax.fill_between(\n energy,\n pdensity,\n 0,\n color=colors[i],\n alpha=alpha,\n )\n\n\n def plot_plain(self, ax, linewidth=1.5, fill=True, alpha=0.3, alpha_line=1.0, sigma=0.05, energyaxis='y', color='black', erange=[-6, 6]):\n \"\"\"\n This function plots the total density of states\n\n Parameters:\n ax (matplotlib.pyplot.axis): Axis to append the tick labels\n linewidth (float): Linewidth of lines\n fill (bool): Determines wether or not to fill underneath the plot\n alpha (float): Alpha value for the fill\n alpha_line (float): Alpha value for the line\n sigma (float): Standard deviation for gaussian filter\n energyaxis (str): Determines the axis to plot the energy on ('x' or 'y')\n color (str): Color of line\n erange (list): Energy range for the DOS plot ([lower bound, upper bound])\n \"\"\"\n\n tdos_array = self.tdos_array\n energy_in_plot_index = np.where(\n (tdos_array[:,0] >= erange[0] - 0.5) & (tdos_array[:,0] <= erange[1] + 0.5)\n )[0]\n tdos_array = tdos_array[energy_in_plot_index]\n\n if sigma > 0:\n tdensity = self._smear(\n tdos_array[:,1],\n sigma=sigma\n )\n else:\n tdensity = tdos_array[:,1]\n\n self._set_density_lims(\n ax=ax,\n tdensity=tdensity,\n tenergy=tdos_array[:,0],\n erange=erange,\n energyaxis=energyaxis,\n spin=self.spin,\n )\n\n if energyaxis == 'y':\n ax.plot(\n tdensity,\n tdos_array[:,0],\n linewidth=linewidth,\n color=color,\n alpha=alpha_line\n )\n\n if fill:\n ax.fill_betweenx(\n tdos_array[:,0],\n tdensity,\n 0,\n alpha=alpha,\n color=color,\n )\n\n if energyaxis == 'x':\n ax.plot(\n tdos_array[:,0],\n tdensity,\n linewidth=linewidth,\n color=color,\n alpha=alpha_line\n )\n\n if fill:\n ax.fill_between(\n tdos_array[:,0],\n tdensity,\n 0,\n color=color,\n alpha=alpha,\n )\n\n def plot_ldos(\n self,\n ax,\n layers,\n linewidth=1.5,\n fill=False,\n alpha=0.3,\n alpha_line=1.0,\n sigma=0.05,\n energyaxis='x',\n color='black',\n log_scale=False,\n erange=[-6, 6],\n atol=None\n ):\n \"\"\"\n This function plots the total density of states\n\n Parameters:\n ax (matplotlib.pyplot.axis): Axis to append the tick labels\n linewidth (float): Linewidth of lines\n fill (bool): Determines wether or not to fill underneath the plot\n alpha (float): Alpha value for the fill\n alpha_line (float): Alpha value for the line\n sigma (float): Standard deviation for gaussian filter\n energyaxis (str): Determines the axis to plot the energy on ('x' or 'y')\n color (str): Color of line\n erange (list): Energy range for the DOS plot ([lower bound, upper bound])\n \"\"\"\n\n # tdos_array = self._sum_layers(layers=layers)\n tdos_array = self.tdos_array\n\n if sigma > 0:\n tdensity = self._smear(\n self._sum_layers(layers=layers, atol=atol),\n sigma=sigma\n )\n else:\n tdensity = self._sum_layers(layers=layers, atol=atol)\n\n if log_scale:\n tdensity = np.log10(tdensity)\n neg_inf_loc = np.isin(tdensity, -np.inf)\n min_val = np.min(tdensity[np.logical_not(neg_inf_loc)])\n tdensity[neg_inf_loc] = min_val\n\n self._set_density_lims(\n ax=ax,\n tdensity=tdensity,\n tenergy=tdos_array[:,0],\n erange=erange,\n energyaxis=energyaxis,\n spin=self.spin,\n log_scale=log_scale,\n )\n\n if energyaxis == 'y':\n ax.plot(\n tdensity,\n tdos_array[:,0],\n linewidth=linewidth,\n color=color,\n alpha=alpha_line\n )\n\n if fill:\n ax.fill_betweenx(\n tdos_array[:,0],\n tdensity,\n 0,\n alpha=alpha,\n color=color,\n )\n\n if energyaxis == 'x':\n ax.plot(\n tdos_array[:,0],\n tdensity,\n linewidth=linewidth,\n color=color,\n alpha=alpha_line\n )\n\n if fill:\n ax.fill_between(\n tdos_array[:,0],\n tdensity,\n 0,\n color=color,\n alpha=alpha,\n )\n\n def plot_spd(self, ax, orbitals='spd', fill=True, alpha=0.3, alpha_line=1.0, linewidth=1.5, sigma=0.05, energyaxis='y', color_dict=None, legend=True, total=True, erange=[-6, 6]):\n \"\"\"\n This function plots the total density of states with the projected\n density of states for the total projections of the s, p, and d orbitals.\n\n Parameters:\n ax (matplotlib.pyplot.axis): Axis to plot on\n order (list): Order to plot the projected bands in. This feature helps to\n avoid situations where one projection completely convers the other.\n fill (bool): Determines wether or not to fill underneath the plot\n alpha (float): Alpha value for the fill\n alpha_line (float): Alpha value for the line\n linewidth (float): Linewidth of lines\n sigma (float): Standard deviation for gaussian filter\n energyaxis (str): Determines the axis to plot the energy on ('x' or 'y')\n color_dict (dict[str][str]): This option allow the colors of the s, p, and d\n orbitals to be specified. Should be in the form of:\n {'s': <s color>, 'p': <p color>, 'd': <d color>}\n legend (bool): Determines whether to draw the legend or not\n total (bool): Determines wheth to draw the total density of states or not\n erange (list): Energy range for the DOS plot ([lower bound, upper bound])\n \"\"\"\n\n projected_data = self._sum_spd(spd=orbitals)\n\n if color_dict is None:\n color_dict = {\n 0: self.color_dict[0],\n 1: self.color_dict[1],\n 2: self.color_dict[2],\n 3: self.color_dict[4],\n }\n\n colors = np.array([color_dict[self.spd_relations[i]] for i in orbitals])\n\n self._plot_projected_general(\n ax=ax,\n energy=self.tdos_array[:,0],\n projected_data=projected_data,\n colors=colors,\n sigma=sigma,\n erange=erange,\n linewidth=linewidth,\n alpha_line=alpha_line,\n alpha=alpha,\n fill=fill,\n energyaxis=energyaxis,\n total=total,\n )\n\n if legend:\n self._add_legend(ax, names=[i for i in orbitals], colors=colors)\n\n def plot_atom_orbitals(self, ax, atom_orbital_dict, fill=True, alpha=0.3, alpha_line=1.0, linewidth=1.5, sigma=0.05, energyaxis='y', color_list=None, legend=True, total=True, erange=[-6, 6]):\n \"\"\"\n This function plots the total density of states with the projected\n density of states for the projections or orbitals on individual atoms.\n\n Parameters:\n ax (matplotlib.pyplot.axis): Axis to plot on\n atom_orbital_pairs (list[list]): List of atoms orbitals pairs in the form of\n [[atom index, orbital index], [atom index, orbital index], ..]\n fill (bool): Determines wether or not to fill underneath the plot\n alpha (float): Alpha value for the fill\n alpha_line (float): Alpha value for the line\n linewidth (float): Linewidth of lines\n sigma (float): Standard deviation for gaussian filter\n energyaxis (str): Determines the axis to plot the energy on ('x' or 'y')\n color_list (list): List of colors that is the same length as the atom orbitals list\n legend (bool): Determines whether to draw the legend or not\n total (bool): Determines wheth to draw the total density of states or not\n erange (list): Energy range for the DOS plot ([lower bound, upper bound])\n \"\"\"\n\n atom_indices = list(atom_orbital_dict.keys())\n orbital_indices = list(atom_orbital_dict.values())\n number_orbitals = [len(i) for i in orbital_indices]\n atom_indices = np.repeat(atom_indices, number_orbitals)\n orbital_symbols_long = np.hstack([\n [self.orbital_labels[o] for o in orb] for orb in orbital_indices\n ])\n orbital_indices_long = np.hstack(orbital_indices)\n indices = np.vstack([atom_indices, orbital_indices_long]).T\n\n projected_data = self.pdos_array\n projected_data = np.transpose(np.array([\n projected_data[:,ind[0],ind[1]] for ind in indices\n ]), axes=(1,0))\n\n if color_list is None:\n colors = np.array([self.color_dict[i] for i in range(len(orbital_indices_long))])\n else:\n colors = color_list\n\n self._plot_projected_general(\n ax=ax,\n energy=self.tdos_array[:,0],\n projected_data=projected_data,\n colors=colors,\n sigma=sigma,\n erange=erange,\n linewidth=linewidth,\n alpha_line=alpha_line,\n alpha=alpha,\n fill=fill,\n energyaxis=energyaxis,\n total=total,\n )\n\n if legend:\n self._add_legend(\n ax,\n names=[f'{i[0]}({i[1]})' for i in zip(atom_indices, orbital_symbols_long)],\n colors=colors\n )\n\n\n def plot_orbitals(self, ax, orbitals, fill=True, alpha=0.3, alpha_line=1.0, linewidth=1.5, sigma=0.05, energyaxis='y', color_list=None, legend=True, total=True, erange=[-6, 6]):\n \"\"\"\n This function plots the total density of states with the projected\n density of states for the projections onto given orbitals\n\n Parameters:\n ax (matplotlib.pyplot.axis): Axis to plot on\n orbitals (list): List of orbitals to project onto\n fill (bool): Determines wether or not to fill underneath the plot\n alpha (float): Alpha value for the fill\n alpha_line (float): Alpha value for the line\n linewidth (float): Linewidth of lines\n sigma (float): Standard deviation for gaussian filter\n energyaxis (str): Determines the axis to plot the energy on ('x' or 'y')\n color_dict (dict[str][str]): This option allow the colors of each orbital\n specified. Should be in the form of:\n {'orbital index': <color>, 'orbital index': <color>, ...}\n legend (bool): Determines whether to draw the legend or not\n total (bool): Determines wheth to draw the total density of states or not\n erange (list): Energy range for the DOS plot ([lower bound, upper bound])\n \"\"\"\n if color_list is None:\n colors = np.array([self.color_dict[i] for i in orbitals])\n else:\n colors = color_list\n\n projected_data = self._sum_orbitals(orbitals=orbitals)\n\n self._plot_projected_general(\n ax=ax,\n energy=self.tdos_array[:,0],\n projected_data=projected_data,\n colors=colors,\n sigma=sigma,\n erange=erange,\n linewidth=linewidth,\n alpha_line=alpha_line,\n alpha=alpha,\n fill=fill,\n energyaxis=energyaxis,\n total=total,\n )\n\n if legend:\n self._add_legend(ax, names=[self.orbital_labels[i] for i in orbitals], colors=colors)\n\n\n def plot_atoms(self, ax, atoms, fill=True, alpha=0.3, alpha_line=1.0, linewidth=1.5, sigma=0.05, energyaxis='y', color_list=None, legend=True, total=True, erange=[-6, 6], sum_atoms=False):\n \"\"\"\n This function plots the total density of states with the projected density of states on the given atoms.\n\n Parameters:\n ax (matplotlib.pyplot.axis): Axis to plot on\n atoms (list): Index of atoms to plot\n fill (bool): Determines wether or not to fill underneath the plot\n alpha (float): Alpha value for the fill\n alpha_line (float): Alpha value for the line\n color_list (list): Optional list of colors of the same length as the atoms list.\n linewidth (float): Linewidth of lines\n sigma (float): Standard deviation for gaussian filter\n energyaxis (str): Determines the axis to plot the energy on ('x' or 'y')\n legend (bool): Determines whether to draw the legend or not\n total (bool): Determines wheth to draw the total density of states or not\n erange (list): Energy range for the DOS plot ([lower bound, upper bound])\n \"\"\"\n\n if color_list is None:\n colors = np.array([self.color_dict[i] for i in range(len(atoms))])\n else:\n colors = color_list\n\n projected_data = self._sum_atoms(atoms=atoms)\n\n if sum_atoms:\n projected_data = np.sum(projected_data, axis=1).reshape(-1,1)\n colors = [colors[0]]\n\n self._plot_projected_general(\n ax=ax,\n energy=self.tdos_array[:,0],\n projected_data=projected_data,\n colors=colors,\n sigma=sigma,\n erange=erange,\n linewidth=linewidth,\n alpha_line=alpha_line,\n alpha=alpha,\n fill=fill,\n energyaxis=energyaxis,\n total=total,\n )\n\n if legend:\n self._add_legend(ax, names=atoms, colors=colors)\n\n\n def plot_atom_spd(self, ax, atom_spd_dict, fill=True, alpha=0.3, alpha_line=1.0, linewidth=1.5, sigma=0.05, energyaxis='y', color_list=None, legend=True, total=True, erange=[-6, 6]):\n \"\"\"\n This function plots the total density of states with the projected\n density of states onto the s, p, and d orbitals of specified atoms. \n This is useful for supercells where there are many atoms of the same \n atom and it is inconvienient to manually list each index in the POSCAR.\n\n Parameters:\n ax (matplotlib.pyplot.axis): Axis to plot on\n atoms (list): List of atom symbols to project onto\n order (list): Order to plot the projected bands in. This feature helps to\n avoid situations where one projection completely convers the other.\n fill (bool): Determines wether or not to fill underneath the plot\n alpha (float): Alpha value for the fill\n alpha_line (float): Alpha value for the line\n linewidth (float): Linewidth of lines\n sigma (float): Standard deviation for gaussian filter\n energyaxis (str): Determines the axis to plot the energy on ('x' or 'y')\n color_dict (dict[str][str]): This option allow the colors of each atom\n specified. Should be in the form of:\n {'atom index': <color>, 'atom index': <color>, ...}\n legend (bool): Determines whether to draw the legend or not\n total (bool): Determines wheth to draw the total density of states or not\n erange (list): Energy range for the DOS plot ([lower bound, upper bound])\n \"\"\"\n\n atom_indices = list(atom_spd_dict.keys())\n orbital_symbols = list(atom_spd_dict.values())\n number_orbitals = [len(i) for i in orbital_symbols]\n atom_indices = np.repeat(atom_indices, number_orbitals)\n orbital_symbols_long = np.hstack([[o for o in orb] for orb in orbital_symbols])\n orbital_indices = np.hstack([[self.spd_relations[o] for o in orb] for orb in orbital_symbols])\n indices = np.vstack([atom_indices, orbital_indices]).T\n\n projected_data = self._sum_atoms(atoms=atom_indices, spd=True)\n projected_data = np.transpose(np.array([\n projected_data[:,ind[0],ind[1]] for ind in indices\n ]), axes=(1,0))\n\n if color_list is None:\n colors = np.array([self.color_dict[i] for i in range(len(orbital_symbols_long))])\n else:\n colors = color_list\n\n self._plot_projected_general(\n ax=ax,\n energy=self.tdos_array[:,0],\n projected_data=projected_data,\n colors=colors,\n sigma=sigma,\n erange=erange,\n linewidth=linewidth,\n alpha_line=alpha_line,\n alpha=alpha,\n fill=fill,\n energyaxis=energyaxis,\n total=total,\n )\n\n if legend:\n self._add_legend(\n ax,\n names=[f'{i[0]}({i[1]})' for i in zip(atom_indices, orbital_symbols_long)],\n colors=colors\n )\n\n def plot_elements(self, ax, elements, fill=True, alpha=0.3, alpha_line=1.0, linewidth=1.5, sigma=0.05, energyaxis='y', color_list=None, legend=True, total=True, erange=[-6, 6]):\n \"\"\"\n This function plots the total density of states with the projected\n density of states for the projection onto specified elements. This is \n useful for supercells where there are many atoms of the same element and\n it is inconvienient to manually list each index in the POSCAR.\n\n Parameters:\n ax (matplotlib.pyplot.axis): Axis to plot on\n elements (list): List of element symbols to project onto\n fill (bool): Determines wether or not to fill underneath the plot\n alpha (float): Alpha value for the fill\n alpha_line (float): Alpha value for the line\n linewidth (float): Linewidth of lines\n sigma (float): Standard deviation for gaussian filter\n energyaxis (str): Determines the axis to plot the energy on ('x' or 'y')\n color_list (list): List of colors that is the same length at the elements list\n legend (bool): Determines whether to draw the legend or not\n total (bool): Determines wheth to draw the total density of states or not\n erange (list): Energy range for the DOS plot ([lower bound, upper bound])\n \"\"\"\n\n if color_list is None:\n colors = np.array([self.color_dict[i] for i in range(len(elements))])\n else:\n colors = color_list\n\n projected_data = self._sum_elements(elements=elements)\n\n self._plot_projected_general(\n ax=ax,\n energy=self.tdos_array[:,0],\n projected_data=projected_data,\n colors=colors,\n sigma=sigma,\n erange=erange,\n linewidth=linewidth,\n alpha_line=alpha_line,\n alpha=alpha,\n fill=fill,\n energyaxis=energyaxis,\n total=total,\n )\n\n if legend:\n self._add_legend(ax, names=elements, colors=colors)\n\n def plot_element_orbitals(self, ax, element_orbital_dict, fill=True, alpha=0.3, alpha_line=1.0, linewidth=1.5, sigma=0.05, energyaxis='y', color_list=None, legend=True, total=True, erange=[-6, 6]):\n \"\"\"\n This function plots the total density of states with the projected\n density of states onto the chosen orbitals of specified elements. This is \n useful for supercells where there are many atoms of the same element and\n it is inconvienient to manually list each index in the POSCAR.\n\n Parameters:\n ax (matplotlib.pyplot.axis): Axis to plot on\n element_orbital_pairs (list[list]): List of element orbital pairs in the form of\n [[element symbol, orbital index], [element symbol, orbital index], ..]\n fill (bool): Determines wether or not to fill underneath the plot\n alpha (float): Alpha value for the fill\n alpha_line (float): Alpha value for the line\n linewidth (float): Linewidth of lines\n sigma (float): Standard deviation for gaussian filter\n energyaxis (str): Determines the axis to plot the energy on ('x' or 'y')\n color_list (list): List of colors that is the same length as the element orbitals list\n legend (bool): Determines whether to draw the legend or not\n total (bool): Determines wheth to draw the total density of states or not\n erange (list): Energy range for the DOS plot ([lower bound, upper bound])\n \"\"\"\n\n element_symbols = list(element_orbital_dict.keys())\n orbital_indices = list(element_orbital_dict.values())\n number_orbitals = [len(i) for i in orbital_indices]\n element_symbols_long = np.repeat(element_symbols, number_orbitals)\n element_indices = np.repeat(range(len(element_symbols)), number_orbitals)\n orbital_symbols_long = np.hstack([[self.orbital_labels[o] for o in orb] for orb in orbital_indices])\n orbital_indices_long = np.hstack(orbital_indices)\n indices = np.vstack([element_indices, orbital_indices_long]).T\n\n projected_data = self._sum_elements(elements=element_symbols, orbitals=True)\n projected_data = np.transpose(np.array([\n projected_data[:,ind[0],ind[1]] for ind in indices\n ]), axes=(1,0))\n\n if color_list is None:\n colors = np.array([self.color_dict[i] for i in range(len(orbital_indices_long))])\n else:\n colors = color_list\n\n self._plot_projected_general(\n ax=ax,\n energy=self.tdos_array[:,0],\n projected_data=projected_data,\n colors=colors,\n sigma=sigma,\n erange=erange,\n linewidth=linewidth,\n alpha_line=alpha_line,\n alpha=alpha,\n fill=fill,\n energyaxis=energyaxis,\n total=total,\n )\n\n if legend:\n self._add_legend(\n ax,\n names=[f'{i[0]}({i[1]})' for i in zip(element_symbols_long, orbital_symbols_long)],\n colors=colors\n )\n\n def plot_element_spd(self, ax, element_spd_dict, fill=True, alpha=0.3, alpha_line=1.0, linewidth=1.5, sigma=0.05, energyaxis='y', color_list=None, legend=True, total=True, erange=[-6, 6]):\n \"\"\"\n This function plots the total density of states with the projected\n density of states onto the s, p, and d orbitals of specified elements. \n This is useful for supercells where there are many atoms of the same \n element and it is inconvienient to manually list each index in the POSCAR.\n\n Parameters:\n ax (matplotlib.pyplot.axis): Axis to plot on\n elements (list): List of element symbols to project onto\n order (list): Order to plot the projected bands in. This feature helps to\n avoid situations where one projection completely convers the other.\n fill (bool): Determines wether or not to fill underneath the plot\n alpha (float): Alpha value for the fill\n alpha_line (float): Alpha value for the line\n linewidth (float): Linewidth of lines\n sigma (float): Standard deviation for gaussian filter\n energyaxis (str): Determines the axis to plot the energy on ('x' or 'y')\n color_dict (dict[str][str]): This option allow the colors of each element\n specified. Should be in the form of:\n {'element index': <color>, 'element index': <color>, ...}\n legend (bool): Determines whether to draw the legend or not\n total (bool): Determines wheth to draw the total density of states or not\n erange (list): Energy range for the DOS plot ([lower bound, upper bound])\n \"\"\"\n element_symbols = list(element_spd_dict.keys())\n orbital_symbols = list(element_spd_dict.values())\n number_orbitals = [len(i) for i in orbital_symbols]\n element_symbols_long = np.repeat(element_symbols, number_orbitals)\n element_indices = np.repeat(range(len(element_symbols)), number_orbitals)\n orbital_symbols_long = np.hstack([[o for o in orb] for orb in orbital_symbols])\n orbital_indices = np.hstack([[self.spd_relations[o] for o in orb] for orb in orbital_symbols])\n indices = np.vstack([element_indices, orbital_indices]).T\n\n projected_data = self._sum_elements(elements=element_symbols, spd=True)\n projected_data = np.transpose(np.array([\n projected_data[:,ind[0],ind[1]] for ind in indices\n ]), axes=(1,0))\n\n if color_list is None:\n colors = np.array([self.color_dict[i] for i in range(len(orbital_symbols_long))])\n else:\n colors = color_list\n\n self._plot_projected_general(\n ax=ax,\n energy=self.tdos_array[:,0],\n projected_data=projected_data,\n colors=colors,\n sigma=sigma,\n erange=erange,\n linewidth=linewidth,\n alpha_line=alpha_line,\n alpha=alpha,\n fill=fill,\n energyaxis=energyaxis,\n total=total,\n )\n\n if legend:\n self._add_legend(\n ax,\n names=[f'{i[0]}({i[1]})' for i in zip(element_symbols_long, orbital_symbols_long)],\n colors=colors\n )\n\n def plot_layers(\n self,\n ax,\n cmap='magma',\n sigma_energy=0.05,\n sigma_layers=0.75,\n energyaxis='y',\n erange=[-6, 6],\n lrange=None,\n antialiased=False,\n fontsize=6,\n interface_layer=None,\n interface_line_color='white',\n interface_line_width=2,\n interface_line_style='--',\n log_scale=False,\n contour=False,\n levels=10,\n min_cutoff=1e-7,\n max_cutoff=None,\n atol=None,\n custom_layer_inds=None,\n custom_cbar_label=None,\n cbar_orientation='vertical',\n show_bounds=False,\n set_bounds=None,\n ):\n \"\"\"\n This function plots a layer by layer heat map of the density\n of states.\n\n Parameters:\n ax (matplotlib.pyplot.axis): Axis to plot on\n cmap (str): Color map to use in the heat map\n sigma_energy (float): Variance for a gaussian blur with respect to the energy\n This will help smooth out spikey looking density of states\n sigma_layers (float): Variance for a gaussian blur with respect to the layers\n This will help smooth out the the pixelation that can occur between the summed\n dos with respect to the layers.\n energyaxis (str): Axis to plot the energy on. ('x' or 'y')\n erange (list): Upper and lower energy bounds for the plot.\n lrange (list): Upper and lower bounds of the layers included in the plot.\n antialiased (bool): Determines if antialiasing is used or not.\n fontsize (float): Fontsize of all the text in the group.\n interface_layer (float or None): If a value is provided, then a line will be drawn\n on the plot to identify the interface layer.\n interface_line_color (str): Color of the line drawn on the plot to mark the \n interface.\n interface_line_width (float): Line with of the line marking the interface.\n interface_line_style (str): Style of the line marking the interface.\n log_scale (bool): Determines if the color map is applied in log scale of not.\n Recommended in order to accurately view the band gap and smaller features.\n contour (bool): Determines if the color map is plotted as a contour plot instead\n of a heatmap.\n levels (int): Number of levels used in the contour plot.\n min_cutoff (float): Minimum dos value used to determine the cut off for the plot.\n This can be adjusted to better visualize the band gap of the material.\n atol (float or None): Tolarence used in the grouping of the layers.\n This value is automatically calculated if None and is usually on the order of\n 1e-3.\n custom_layer_inds (list or None): If the structure being calculated has relaxed\n atomic positions, sometimes the layer grouping algorithm can behave non-idealy.\n If this is the case, the user can input a list of list that contain the\n atomic indices in each layers of the material.\n custom_cbar_label (str or None): Custom label for the colorbar\n \"\"\"\n from vaspvis.utils import group_layers\n import matplotlib.colors as colors\n energy = self.tdos_array[:,0]\n\n ind = np.where(\n (erange[0] - 0.1 <= energy) & (energy <= erange[-1] + 0.1)\n )\n if custom_layer_inds is None:\n groups, _ = group_layers(self.poscar.structure, atol=atol)\n else:\n groups = custom_layer_inds\n\n atom_index = range(len(groups))\n energies = energy[ind]\n atom_densities = self._sum_atoms(atoms=None)[ind]\n densities = np.vstack([np.sum(np.vstack(atom_densities[:,[group]]), axis=1) for group in groups])\n densities = np.transpose(densities)\n\n if lrange is not None:\n atom_index = atom_index[lrange[0]:lrange[1]+1]\n densities = densities[:, lrange[0]:lrange[1]+1]\n\n if sigma_energy > 0:\n for i in range(densities.shape[-1]):\n densities[:,i] = self._smear(\n densities[:,i],\n sigma=sigma_energy,\n )\n if sigma_layers > 0:\n densities = gaussian_filter(densities, sigma=sigma_layers)\n\n f = interp2d(atom_index, energies, densities, kind='cubic')\n atom_index = np.arange(np.min(atom_index), np.max(atom_index), 0.1)\n densities = f(atom_index, energies)\n\n if log_scale:\n if np.min(densities) <= 0:\n neg_zero_loc = np.where(densities <= 0)\n pos_loc = np.where(densities > 0)\n min_val = np.min(densities[pos_loc])\n if min_val < min_cutoff:\n min_val = min_cutoff\n too_small_loc = np.where(densities < min_cutoff)\n densities[too_small_loc] = min_cutoff\n else:\n densities[neg_zero_loc] = min_val\n else:\n min_val = np.min(densities)\n if min_val < min_cutoff:\n min_val = min_cutoff\n\n if max_cutoff is not None:\n max_val = max_cutoff\n else:\n max_val = np.max(densities)\n \n norm = colors.LogNorm(vmin=min_val, vmax=max_val)\n else:\n if self.combination_method == \"sub\" and self.spin == \"both\":\n if set_bounds is None:\n norm_val = np.max(np.abs([np.min(densities), np.max(densities)]))\n else:\n norm_val = set_bounds\n\n norm = colors.Normalize(vmin=-norm_val, vmax=norm_val)\n else:\n norm = colors.Normalize(vmin=np.min(densities), vmax=np.max(densities))\n\n\n if log_scale:\n lev_exp = np.arange(\n np.floor(np.log10(densities.min())-1),\n np.ceil(np.log10(densities.max())+1),\n )\n if len(lev_exp) >= levels:\n pass\n else:\n if int(levels / len(lev_exp)) >= 3:\n lev_exp = np.arange(\n np.floor(np.log10(densities.min())-1),\n np.ceil(np.log10(densities.max())+1),\n 0.25,\n )\n else:\n lev_exp = np.arange(\n np.floor(np.log10(densities.min())-1),\n np.ceil(np.log10(densities.max())+1),\n 0.5,\n )\n levels = np.power(10, lev_exp)\n\n if energyaxis == 'y':\n\n if contour:\n im = ax.contourf(\n atom_index, \n energies,\n densities,\n cmap=cmap,\n levels=levels,\n norm=norm,\n )\n else:\n im = ax.pcolormesh(\n atom_index,\n energies,\n densities,\n cmap=cmap,\n shading='gouraud',\n norm=norm,\n antialiased=antialiased,\n )\n ax.xaxis.set_major_locator(MaxNLocator(integer=True))\n\n\n if interface_layer is not None:\n ax.axvline(\n x=interface_layer,\n color=interface_line_color,\n linestyle=interface_line_style,\n linewidth=interface_line_width,\n )\n\n if energyaxis == 'x':\n if contour:\n im = ax.contourf(\n energies,\n atom_index, \n densities,\n cmap=cmap,\n levels=levels,\n norm=norm,\n )\n else:\n im = ax.pcolormesh(\n energies,\n atom_index,\n np.transpose(densities),\n cmap=cmap,\n shading='gouraud',\n norm=norm,\n antialiased=antialiased,\n )\n ax.yaxis.set_major_locator(MaxNLocator(integer=True))\n\n if interface_layer is not None:\n ax.axhline(\n y=interface_layer,\n color=interface_line_color,\n linestyle=interface_line_style,\n linewidth=interface_line_width,\n )\n\n fig = plt.gcf()\n cbar = fig.colorbar(im, ax=ax, orientation=cbar_orientation)\n cbar.ax.tick_params(labelsize=fontsize)\n if custom_cbar_label is None:\n if self.combination_method == \"sub\" and self.spin == \"both\":\n cbar.set_label('Spin Polarization (arb. units)', fontsize=fontsize)\n min_val = im.norm.vmin\n max_val = im.norm.vmax\n cbar.set_ticks([min_val, max_val])\n if not show_bounds:\n cbar.set_ticklabels(['Down', 'Up'])\n else:\n cbar.set_label('Density of States', fontsize=fontsize)\n else:\n cbar.set_label(custom_cbar_label, fontsize=fontsize)\n\n def plot_structure(self, ax, rotation=[90,90,90]):\n structure = self.poscar.structure\n atoms = AseAtomsAdaptor().get_atoms(structure)\n atoms = plot_atoms(\n atoms,\n ax,\n radii=0.5,\n rotation=(f'{rotation[0]}x,{rotation[1]}y,{rotation[2]}z'),\n show_unit_cell=0\n )\n\n\nif __name__ == '__main__':\n dos = Dos(folder='../../vaspvis_data/slabdos')\n # dos._sum_layers(layers=[0,1,2,3])\n fig, ax = plt.subplots(figsize=(4,3), dpi=100)\n dos.plot_ldos(ax=ax, layers=range(10), erange=[-2,2], fill=False)\n plt.show()\n"
] | [
[
"numpy.squeeze",
"numpy.max",
"numpy.mean",
"scipy.interpolate.interp2d",
"numpy.where",
"numpy.hstack",
"numpy.arange",
"matplotlib.pyplot.gcf",
"numpy.diff",
"numpy.load",
"numpy.repeat",
"numpy.zeros",
"numpy.isin",
"numpy.logical_not",
"numpy.min",
"numpy.power",
"matplotlib.pyplot.Line2D",
"numpy.log10",
"matplotlib.rcParams.update",
"numpy.transpose",
"scipy.ndimage.filters.gaussian_filter1d",
"numpy.array",
"matplotlib.pyplot.show",
"numpy.sum",
"scipy.ndimage.gaussian_filter",
"matplotlib.pyplot.subplots",
"matplotlib.ticker.MaxNLocator",
"numpy.vstack"
]
] |
incognite-lab/myGym | [
"a093a4a0f75ba081fbcf3fef70aca14dc2078997"
] | [
"myGym/envs/base_env.py"
] | [
"import pybullet_data\nimport glob\nimport pybullet\nimport pybullet_utils.bullet_client as bc\nimport time\nimport numpy as np\nfrom gym.utils import seeding\nimport gym\nimport os\nimport inspect\nfrom myGym.envs.camera import Camera\nimport pkg_resources\ncurrentdir = pkg_resources.resource_filename(\"myGym\", \"envs\")\nrepodir = pkg_resources.resource_filename(\"myGym\", \"./\")\n\n\nclass BaseEnv(gym.Env):\n \"\"\"\n The base class for environments without rendering\n\n Parameters:\n :param gui_on: (bool) Whether or not to use PyBullet built-in GUI\n :param objects_dir_path: (str) Path to directory with URDF files for objects\n :param max_steps: (int) The maximum number of actions per episode\n :param show_bounding_boxes_gui: (bool) Whether or not to show bounding boxes in GUI\n :param changing_light_gui: (bool) Whether or not to change light in GUI\n :param shadows_on_gui: (bool) Whether or not to show shadows in GUI\n \"\"\"\n metadata = {'render.modes': [\n 'human', 'rgb_array'], 'video.frames_per_second': 50}\n\n def __init__(self,\n gui_on=True,\n objects_dir_path=pkg_resources.resource_filename(\"myGym\", \"envs/\"),\n max_steps=1024,\n show_bounding_boxes_gui=False,\n changing_light_gui=False,\n shadows_on_gui=True\n ):\n self.gui_on = gui_on\n self.max_steps = max_steps\n self.show_bounding_boxes_gui = show_bounding_boxes_gui\n self.changing_light_gui = changing_light_gui\n self.shadows_on_gui = shadows_on_gui\n\n # Set episode information\n self.episode_start_time = None\n self.episode_over = False\n self.episode_failed = False\n self.episode_reward = 0.0\n self.episode_final_reward = []\n self.episode_final_distance = []\n self.episode_number = 0\n self.episode_steps = 0\n self.episode_max_time = 300\n self.episode_info = \"\"\n\n # Set general params\n self.time_step = 1. / 240.\n self.urdf_root = pybullet_data.getDataPath()\n self.observation = {}\n\n # Set objects information\n self.objects_dir_path = objects_dir_path\n self.env_objects = []\n self.scene_objects_uids = {}\n self.all_objects_filenames = self._get_all_urdf_filenames(self.objects_dir_path)\n\n # Set GUI\n self._connect_to_physics_server()\n\n # Set env params and load models\n self._set_physics()\n self._setup_scene()\n self._set_observation_space()\n self._set_action_space()\n\n def _connect_to_physics_server(self):\n \"\"\"\n Connect to the PyBullet physics server in SHARED_MEMORY, GUI or DIRECT mode\n \"\"\"\n if self.gui_on:\n self.p = bc.BulletClient(connection_mode=pybullet.GUI)\n # if (self.p < 0):\n # self.p = bc.BulletClient(connection_mode=p.GUI)\n self._set_gui_mode()\n else:\n self.p = bc.BulletClient(connection_mode=pybullet.DIRECT)\n self.p.setPhysicsEngineParameter(enableFileCaching=0)\n\n def _set_gui_mode(self):\n \"\"\"\n Set GUI parameters: camera, shadows, extra elements\n \"\"\"\n self.p.resetDebugVisualizerCamera(3.3, 0, -41, [0.0, 0.0, 0.33])\n self.p.configureDebugVisualizer(self.p.COV_ENABLE_SHADOWS, self.shadows_on_gui)\n self.p.configureDebugVisualizer(self.p.COV_ENABLE_GUI, 0)\n\n def _set_physics(self):\n \"\"\"\n Set physics engine parameters\n \"\"\"\n self.p.setGravity(0, 0, -9.81)\n self.p.setPhysicsEngineParameter(solverResidualThreshold=0.001, numSolverIterations=150, numSubSteps=20, useSplitImpulse=1, collisionFilterMode=1, constraintSolverType=self.p.CONSTRAINT_SOLVER_LCP_DANTZIG, globalCFM=0.000001, contactBreakingThreshold=0.001)\n self.p.setTimeStep(self.time_step)\n self.p.setRealTimeSimulation(0)\n self.p.setPhysicsEngineParameter(enableConeFriction=1)\n print(self.p.getPhysicsEngineParameters())\n\n def _setup_scene(self):\n \"\"\"\n Set up scene elements (furniture, objects, robots)\n \"\"\"\n raise NotImplementedError\n\n def _set_observation_space(self):\n \"\"\"\n Set limits of observations\n \"\"\"\n raise NotImplementedError\n\n def _set_action_space(self):\n \"\"\"\n Set limits of actions\n \"\"\"\n raise NotImplementedError\n\n def _get_observation(self):\n \"\"\"\n Get info about the state of the environment\n\n Returns:\n :return observation: (object) Observation of the environment\n \"\"\"\n raise NotImplementedError\n\n def step(self, action):\n \"\"\"\n Apply action on the environment\n\n Parameters:\n :param action: (object) An action provided by the agent\n Returns:\n :return observation: (object)\n :return reward: (float)\n :return done: (bool):\n :return info: (dict):\n \"\"\"\n raise NotImplementedError\n\n def _add_scene_object_uid(self, scene_object_uid, name):\n \"\"\"\n Call this method in order to enable texturization of object\n\n Parameters:\n :param scene_object: (int)\n \"\"\"\n self.scene_objects_uids[scene_object_uid] = name\n\n def get_scene_object_uid_by_name(self, name):\n for uid, object_name in self.scene_objects_uids.items():\n if name == object_name:\n return uid\n return None\n\n def seed(self, seed=None):\n \"\"\"\n Set the seed for this env's random number generator(s)\n \"\"\"\n self.np_random, seed = seeding.np_random(seed)\n return [seed]\n\n def hard_reset(self):\n \"\"\"\n Full reset of the simulation. Delete and load again all objects and reset physics.\n \"\"\"\n self.p.resetSimulation()\n self.p.disconnect()\n self._connect_to_physics_server()\n self.scene_objects_uids = {}\n #self.episode_number = 0\n self._set_physics()\n self._setup_scene()\n\n def _restart_episode(self):\n \"\"\"\n Reset episode information and delete all objects\n \"\"\"\n self.p.removeAllUserDebugItems()\n self.episode_start_time = time.time()\n self.episode_over = False\n self.episode_failed = False\n self.episode_reward = 0.0\n self.episode_steps = 0\n\n def reset(self, hard=False):\n \"\"\"\n Reset the state of the environment\n \"\"\"\n if hard:\n self.hard_reset()\n else:\n self._remove_all_objects()\n\n self._restart_episode()\n\n def _draw_bounding_boxes(self):\n \"\"\"\n Show bounding boxes in tne PyBullet GUI\n \"\"\"\n for object in self.env_objects:\n object.draw_bounding_box()\n\n def _compute_reward(self):\n \"\"\"\n Compute reward for the agent\n \"\"\"\n return NotImplementedError\n\n def _print_episode_summary(self, info_dict={}):\n \"\"\"\n Show an extra information about the episode\n\n Parameters:\n :param info_dict: (dict) Extra info\n \"\"\"\n if self.episode_failed:\n episode_status = \"FAILURE\"\n else:\n episode_status = \"SUCCESS\"\n\n print(\"#---------Episode-Summary---------#\")\n print(\"Episode number: \" + str(self.episode_number))\n print(\"Episode's number of steps: \" + str(self.episode_steps))\n print(\"Episode status: \" + episode_status)\n print(\"Episode info: \" + self.episode_info)\n print(\"Episode reward: \" + str(self.episode_reward))\n print(\"Last step reward: \" + str(self.reward.rewards_history[-1]))\n print(\"#---------------------------------#\")\n\n for key, value in info_dict.items():\n print(key + \": \" + str(value))\n\n def _get_random_urdf_filenames(self, n, used_objects=None):\n \"\"\"\n Sample random URDF files from directory with objects URDFs\n\n Parameters:\n :param n: (int) Number of URDF's\n :param used_objects: (list) Specified subset of objects\n Returns:\n :return selected_objects_filenames: (list)\n \"\"\"\n if used_objects or (self.all_objects_filenames is None):\n all_objects_filenames = []\n for object_name in used_objects:\n if \"virtual\" in object_name:\n all_objects_filenames.append(object_name)\n for file in self.all_objects_filenames:\n if '/'+object_name+'.' in file:\n all_objects_filenames.append(file)\n else:\n # uses self.all_objects_filenames\n pass\n assert all_objects_filenames is not None\n\n selected_objects_filenames = []\n total_num_objects = len(all_objects_filenames)\n if (n <= total_num_objects):\n selected_objects = np.random.choice(\n np.arange(total_num_objects), n, replace=True)\n else:\n selected_objects = list(np.arange(total_num_objects))\n remain = n - total_num_objects\n selected_objects += list(np.random.choice(\n np.arange(total_num_objects), remain))\n for object_id in selected_objects:\n selected_objects_filenames.append(all_objects_filenames[object_id])\n return selected_objects_filenames\n\n def _get_all_urdf_filenames(self, dir):\n \"\"\"\n Get all URDF filenames from directory\n\n Parameters:\n :param dir: (int) Number of URDFs\n Returns:\n :return filenames: (list)\n \"\"\"\n list_all = []\n for (dirpath, dirnames, filenames) in os.walk(self.objects_dir_path):\n if '_old' not in dirpath and 'urdf' in dirpath:\n list_all += [os.path.join(dirpath, file) for file in filenames]\n return list_all\n\n def _remove_object(self, object):\n \"\"\"\n Totally remove object from the simulation\n\n Parameters:\n :param object: (EnvObject) Object to remove\n \"\"\"\n self.env_objects.remove(object)\n self.p.removeBody(object.uid)\n\n def _remove_all_objects(self):\n \"\"\"\n Remove all objects from simulation (not scene objects or robots)\n \"\"\"\n env_objects_copy = self.env_objects[:]\n for env_object in env_objects_copy:\n self._remove_object(env_object)\n\n def get_texturizable_objects_uids(self):\n \"\"\"\n Get all objects in the environment, on which textures can be applied\n \n Returns:\n :return texturizable_objects_uids: (list)\n \"\"\"\n return [object.get_uid() for object in self.env_objects] + list(self.scene_objects_uids.keys())\n\n def get_colorizable_objects_uids(self):\n \"\"\"\n Get all objects in the environment, which color can be changed\n\n Returns:\n :return colorizable_objects_uids: (list)\n \"\"\"\n return [object.get_uid() for object in self.env_objects] + list(self.scene_objects_uids.keys())\n\n def __del__(self):\n \"\"\"\n Disconnect from the physics server\n \"\"\"\n self.p.disconnect()\n\n\nclass CameraEnv(BaseEnv):\n \"\"\"\n The class for environments with rendering\n\n Parameters:\n :param camera_resolution: (list) The number of pixels in image (WxH)\n :param shadows_on: (bool) Whether or not to use shadows while rendering, only applies to ER_TINY_RENDERER\n :param render_on: (bool) Turn on rendering\n :param renderer: (int) self.p.ER_TINY_RENDERER (CPU) or self.p.ER_BULLET_HARDWARE_OPENGL (GPU)\n :param active_cameras: (list) Set 1 at a position(=camera number) to save images from this camera\n \"\"\"\n def __init__(self, camera_resolution=[640, 480], shadows_on=True,\n render_on=True, renderer=pybullet.ER_BULLET_HARDWARE_OPENGL,\n active_cameras=None, **kwargs):\n\n super(CameraEnv, self).__init__(**kwargs)\n\n self.camera_resolution = camera_resolution\n self.shadows_on = shadows_on\n self.render_on = render_on\n self.renderer = renderer\n self.active_cameras = active_cameras\n self.cameras = []\n\n self.set_light()\n self._set_cameras()\n\n def set_light(self, light_direction=[1, 1, 1], light_color=[0.1, 0.1, 0.1],\n light_distance=1., light_ambient=1., light_diffuse=1.,\n light_specular=1.):\n \"\"\"\n Set light parameters for rendering, doesn't affect PyBullet GUI. Appart from light_direction, all parameters only apply to ER_TINY_RENDERER.\n\n Parameters:\n :param light_direction: (list) Specifies the world position of the light source\n :param light_color: (list) Directional light color in RGB in range 0..1\n :param light_distance: (float) Distance of the light along the normalized light_direction\n :param light_ambient: (float) Light ambient coefficient in range 0..1\n :param light_diffuse: (float) Light diffuse coefficient in range 0..1\n :param light_specular: (float) Light specular coefficient in range 0..1\n \"\"\"\n self.light_direction = light_direction\n self.light_color = light_color\n self.light_distance = light_distance\n self.light_ambient = light_ambient\n self.light_diffuse = light_diffuse\n self.light_specular = light_specular\n\n def get_render_parameters(self):\n \"\"\"\n Return environment parameters for rendering, initially is intended to\n use by cameras\n\n Returns:\n :return render_parameters: (dict) Render parameters\n \"\"\"\n return {\n \"width\": self.camera_resolution[0],\n \"height\": self.camera_resolution[1],\n \"lightDirection\": self.light_direction,\n \"lightColor\": self.light_color,\n \"lightDistance\": self.light_distance,\n \"shadow\": 1 if self.shadows_on else 0,\n \"lightAmbientCoeff\": self.light_ambient,\n \"lightDiffuseCoeff\": self.light_diffuse,\n \"lightSpecularCoeff\": self.light_specular,\n \"renderer\": self.renderer\n }\n\n def _set_cameras(self):\n \"\"\"\n Set cameras available to use for rendering\n \"\"\"\n raise NotImplementedError\n\n def get_cameras(self):\n return self.cameras\n\n def add_camera(self, **kwargs):\n \"\"\"\n Add new camera to the environment\n\n Parameters:\n :param position: (list) Eye position in Cartesian world coordinates\n :prarm target_position: (list) Position of the target point\n :param up_vector: (list) Up vector of the camera\n :param up_axis_index: (int) Either 1 for Y or 2 for Z axis up\n :param yaw: (float) Yaw angle in degrees left/right around up-axis\n :param pitch: (float) Pitch in degrees up/down\n :param roll: (float) Roll in degrees around forward vector\n :param distance: (float) Distance from eye to focus point\n :param field_of_view: (float) Field of view\n :param near_plane_distance: (float) Near plane distance\n :param far_plane_distance: (float) Far plane distance\n \"\"\"\n self.cameras.append(Camera(env=self, **kwargs))\n\n def set_active_cameras(self, active_cameras):\n\n if (len(active_cameras) == len(self.cameras)):\n self.active_cameras = active_cameras\n\n def change_current_camera(self, camera_num):\n print(\"Change camera to \" + str(self.current_camera))\n self.current_camera = camera_num\n\n def render(self, mode=\"rgb_array\", camera_id=None):\n \"\"\"\n Get image (image, depth, segmentation_mask) from camera or active cameras\n\n Parameters:\n :param mode: (str) rgb_array to return RGB image\n :param camera_id: (int) Get image from specified camera\n Returns:\n :return camera_data: (dict) Key: camera_id, Value: info from camera\n \"\"\"\n if mode != \"rgb_array\":\n return np.array([])\n camera_data = {}\n if self.render_on:\n if camera_id is not None:\n camera_data[camera_id] = self.cameras[camera_id].render()\n else:\n for camera_num in range(len(self.active_cameras)):\n if self.active_cameras[camera_num]:\n camera_data[camera_num] = self.cameras[camera_num].render()\n return camera_data\n\n def project_point_to_camera_image(self, point, camera_id):\n \"\"\"\n Project 3D point in Cartesian world coordinates to 2D point in pixel space\n\n Parameters:\n :param point: (list) 3D point in Cartesian world coordinates\n :param camera_id: (int) Index of camera to project on\n\n Returns:\n :return 2d_point: (list) 2D coordinates of point on imageg\n \"\"\"\n return self.cameras[camera_id].project_point_to_image(point)\n\n def get_camera_opencv_matrix_values(self, camera_id):\n \"\"\"\n Compute values of OpenCV matrix\n\n Parameters:\n :param camera_id: (int) Index of camera to get matrix from\n Returns:\n :return values: (dict) fx, fy, cx, cy values\n \"\"\"\n return self.cameras[camera_id].get_opencv_camera_matrix_values()\n"
] | [
[
"numpy.arange",
"numpy.array"
]
] |
dmdu/rlmolecule | [
"5c9187775ef99ea6a06992788116754b1b308a8c"
] | [
"tests/alphazero/test_molecule_alphazero.py"
] | [
"import os\nfrom unittest.mock import MagicMock\n\nimport numpy as np\nimport pytest\nimport tensorflow as tf\n\nfrom rlmolecule.alphazero.alphazero import AlphaZero\nfrom rlmolecule.molecule.builder.builder import MoleculeBuilder\nfrom rlmolecule.tree_search.reward import LinearBoundedRewardFactory, RankedRewardFactory\nfrom tests.qed_optimization_problem import QEDWithMoleculePolicy\n\n\[email protected]()\ndef builder():\n return MoleculeBuilder(max_atoms=4, min_atoms=1, tryEmbedding=False, sa_score_threshold=None, stereoisomers=False)\n\n\[email protected](scope='function')\ndef game(request, engine, tmpdirname, builder):\n \"\"\"\n The scope here is function, so that the problem gets recreated for each test. Otherwise the trained policy\n network doesn't need to be loaded, since the trained model already exists in the problem.\n \"\"\"\n\n name = request.param\n\n if name == 'raw':\n reward_class = LinearBoundedRewardFactory(min_reward=0., max_reward=1.)\n noise = True\n\n elif name == 'ranked':\n reward_class = RankedRewardFactory(reward_buffer_min_size=2,\n reward_buffer_max_size=4,\n run_id=name,\n engine=engine)\n noise = True\n\n elif name == 'nonoise':\n reward_class = LinearBoundedRewardFactory(min_reward=0., max_reward=1.)\n noise = False\n\n else:\n raise RuntimeError(f\"{name} not found\")\n\n problem = QEDWithMoleculePolicy(engine,\n builder,\n features=8,\n num_heads=2,\n num_messages=1,\n run_id=name,\n min_buffer_size=0,\n reward_class=reward_class,\n policy_checkpoint_dir=tmpdirname)\n\n return AlphaZero(problem, dirichlet_noise=noise)\n\n\[email protected]('game', ['raw', 'ranked', 'nonoise'], indirect=True)\nclass TestPolicyTraining:\n def test_reward_caching(self, game):\n root = game._get_root()\n\n game.problem.get_reward = MagicMock(return_value=(1, {}))\n game.problem.initialize_run()\n\n reward1 = game.problem.reward_wrapper(root).raw_reward\n reward2 = game.problem.reward_wrapper(root).raw_reward\n\n assert reward1 == reward2\n assert game.problem.get_reward.call_count == 1\n\n def test_create_games(self, game):\n final_mols = []\n rewards = []\n\n for i in range(5):\n history, reward = game.run(num_mcts_samples=5)\n assert history[0][0].visit_count == 5\n\n from rlmolecule.sql.tables import GameStore\n stored_game = game.problem.session.query(GameStore).filter_by(id=str(game.problem.id)).one()\n assert stored_game.scaled_reward == reward.scaled_reward\n assert stored_game.raw_reward == reward.raw_reward\n\n final_mols += [history[-1][0]]\n rewards += [reward]\n\n # Make sure there's some diversity in the final molecules\n assert len(set(final_mols)) > 1\n assert len(set(rewards)) > 1\n\n def test_recent_games(self, game):\n problem = game.problem\n recent_games = list(problem.iter_recent_games())\n assert len(recent_games) == 5\n\n def test_policy_data(self, game):\n problem = game.problem\n data = problem._create_dataset()\n inputs, (rewards, visit_probs) = list(data.take(1))[0]\n assert inputs['atom'].shape[1] == visit_probs.shape[1] + 1\n assert inputs['atom'].shape[0] == problem.batch_size\n\n outputs = problem.batched_policy_model(inputs)\n assert outputs[0].shape.as_list() == rewards.shape.as_list()\n assert outputs[1].shape.as_list() == visit_probs.shape.as_list()\n\n def test_policy_model_masking(self, game):\n problem = game.problem\n data = problem._create_dataset()\n inputs, (rewards, visit_probs) = list(data.take(1))[0]\n\n inputs_for_batch_layer = tf.keras.Model(problem.batched_policy_model.inputs,\n problem.batched_policy_model.layers[-1].input)(inputs)\n\n input_mask = [inp._keras_mask for inp in inputs_for_batch_layer]\n\n outputs = problem.batched_policy_model(inputs)\n output_mask = problem.batched_policy_model.layers[-1].compute_mask(inputs_for_batch_layer, input_mask)\n\n assert output_mask[0].numpy().all(), 'no values should be masked'\n\n # make sure that the final output masks matches where there's no atoms.\n assert (output_mask[1].numpy() == ~(inputs['atom'] == 0).numpy().all(-1)[:, 1:]).all()\n\n # make sure the number of actions is consistent\n assert (input_mask[0].numpy().sum(1) - 1 == output_mask[1].numpy().sum(1)).all()\n\n def test_train_policy_model(self, game):\n problem = game.problem\n\n weights_before = problem.batched_policy_model.get_weights()[1]\n\n history = problem.train_policy_model(steps_per_epoch=10, epochs=1)\n assert np.isfinite(history.history['loss'][0])\n assert 'policy.01.index' in os.listdir(problem.policy_checkpoint_dir)\n\n weights_after = problem.batched_policy_model.get_weights()[1]\n\n assert not np.isclose(weights_before, weights_after).all()\n\n def test_load_new_policy(self, engine, game):\n problem = game.problem\n assert problem._checkpoint is None\n\n def get_root_value_pred(problem):\n root = game.get_vertex_for_state(problem.get_initial_state())\n game._evaluate([root])\n value, prior_logits = problem.policy_evaluator(problem._get_batched_policy_inputs(root))\n\n return float(value[0]), prior_logits.numpy()[1:]\n\n initial_value, initial_priors = get_root_value_pred(problem)\n\n # This should trigger the checkpoint reloading\n game.run(num_mcts_samples=5)\n assert problem._checkpoint is not None\n\n next_value, next_priors = get_root_value_pred(problem)\n\n # Make sure the policy changes the value prediction\n assert not np.isclose(initial_value, next_value)\n assert not np.isclose(initial_priors, next_priors).all()\n"
] | [
[
"tensorflow.keras.Model",
"numpy.isfinite",
"numpy.isclose"
]
] |
daniellawson9999/compositional_reinforcement_learning | [
"aa20413485d654d29cfcaad8ddb8fd07efcafc8c"
] | [
"envs/cross_maze_ant_env.py"
] | [
"\"\"\"Implements an ant whose goal is to reach a target in a maze\"\"\"\n\nimport os\n\nimport numpy as np\n\nfrom rllab.core.serializable import Serializable\n#from sac.misc.utils import PROJECT_PATH\nfrom misc.utils import PROJECT_PATH\n\nfrom .helpers import random_point_in_circle, get_random_goal_logs\nfrom .random_goal_ant_env import RandomGoalAntEnv\n\n# MODELS_PATH = os.path.abspath(\n# os.path.join(PROJECT_PATH, 'sac/mujoco_models'))\nMODELS_PATH = os.path.abspath(\n os.path.join(PROJECT_PATH, 'mujoco_models'))\n\nclass CrossMazeAntEnv(RandomGoalAntEnv, Serializable):\n \"\"\"Implements an ant whose goal is to reach a target in a maze\"\"\"\n\n FILE_PATH = os.path.join(MODELS_PATH, 'cross_maze_ant.xml')\n\n def __init__(self,\n reward_type='dense',\n terminate_at_goal=True,\n goal_reward_weight=3e-1,\n goal_radius=1,\n goal_distance=1,\n goal_angle_range=(0, 2*np.pi),\n velocity_reward_weight=0,\n ctrl_cost_coeff=1e-2,\n contact_cost_coeff=1e-3,\n survive_reward=5e-2,\n fixed_goal_position=None,\n set_goal_positions=None,\n *args,\n **kwargs):\n \n file_path = self.__class__.FILE_PATH\n kwargs.pop('file_path', None)\n self.fixed_goal_position = fixed_goal_position\n\n self.set_goal_positions = kwargs.pop('set_goal_positions', None)\n if self.set_goal_positions is None:\n self.set_goal_positions = set_goal_positions\n\n super(CrossMazeAntEnv, self).__init__(\n file_path=file_path,\n reward_type=reward_type,\n terminate_at_goal=terminate_at_goal,\n goal_reward_weight=goal_reward_weight,\n goal_radius=goal_radius,\n goal_distance=goal_distance,\n goal_angle_range=goal_angle_range,\n velocity_reward_weight=velocity_reward_weight,\n ctrl_cost_coeff=ctrl_cost_coeff,\n contact_cost_coeff=contact_cost_coeff,\n survive_reward=survive_reward,\n *args,\n **kwargs)\n self._serializable_initialized = False\n\n def reset(self, goal_position=None, *args, **kwargs):\n if self.set_goal_positions is None:\n possible_goal_positions = [[6, -6], [6, 6], [12, 0]]\n else:\n possible_goal_positions = []\n if \"left\" in self.set_goal_positions:\n possible_goal_positions.append([6, 6])\n if \"right\" in self.set_goal_positions:\n possible_goal_positions.append([6, -6])\n if \"forwards\" in self.set_goal_positions:\n possible_goal_positions.append([12, 0])\n #import pdb; pdb.set_trace()\n\n #possible_goal_positions = [[6, -6], [12, 0]] # Just right and forwards\n\n if goal_position is None:\n if self.fixed_goal_position is not None:\n goal_position = self.fixed_goal_position\n else:\n goal_position = possible_goal_positions[\n np.random.choice(len(possible_goal_positions))]\n\n observation = super(CrossMazeAntEnv, self).reset(\n goal_position=np.array(goal_position), *args, **kwargs)\n\n return observation\n\n def get_current_obs(self):\n observation = super().get_current_obs()\n\n if self.fixed_goal_position is not None:\n return observation[:-2]\n\n return observation\n\n def render(self, *args, **kwargs):\n result = super(CrossMazeAntEnv, self).render(*args, **kwargs)\n self.viewer.cam.elevation = -55\n self.viewer.cam.lookat[0] = 7\n self.viewer.cam.lookat[2] = 0\n self.viewer.cam.distance = self.model.stat.extent * 0.9\n self.viewer.cam.azimuth = 0\n self.viewer.cam.trackbodyid = 0\n\n return result\n"
] | [
[
"numpy.array"
]
] |
laurafroelich/weather_wind_power | [
"851d023960ea6b27d2c70dff86e34670bae43370"
] | [
"code/src/visualisation/weather_forecast.py"
] | [
"import plotly.graph_objs as go\nimport numpy as np\nimport ipywidgets\n\nfrom weather_wind.visualisation.geography import get_rotated_basemap, get_coastline_traces, get_country_traces\nfrom weather_wind.data_retrieval.weather_forecast import get_data_as_cube_and_lats_lons\n\n\ndef rotate_data_and_lats(grb_matrix_data, lons, degrees=180):\n lons_rotated = lons.copy()\n lons_rotated[lons >= degrees] = lons[lons >= degrees] - (2*degrees)\n\n # proper rotation obtained from: https://plot.ly/ipython-notebooks/basemap-maps/\n i_east = lons_rotated[0, :] >= 0 # indices of east lon\n i_west = lons_rotated[0, :] < 0 # indices of west lon\n\n # stack the two halves\n lons_rotated = np.hstack((lons_rotated[:, i_west], lons_rotated[:, i_east]))\n\n # Correspondingly, shift the data array\n data_rotated = np.hstack((grb_matrix_data[:, i_west], grb_matrix_data[:, i_east]))\n\n return data_rotated, lons_rotated\n\n\ndef get_widget_figure(file_path, file_name, data_type, degrees_to_rotate=180):\n grb_cube_data, lats, lons, forecast_date, issuance_date = get_data_as_cube_and_lats_lons(\n file_path, file_name, data_type)\n matrix_data = grb_cube_data['data'][10]\n data_rotated, lons_rotated = rotate_data_and_lats(matrix_data, lons)\n basemap_rotated = get_rotated_basemap()\n\n anno_text = str(forecast_date) + '<br>(issued on ' + str(issuance_date) + ')'\n # \"Data courtesy of\n # <a href='http://www.esrl.noaa.gov/psd/data/composites/day/'>\\\n # NOAA Earth System Research Laboratory</a>\"\n\n axis_style = dict(\n zeroline=False,\n showline=False,\n showgrid=False,\n ticks='',\n showticklabels=False,\n )\n\n layout1 = go.Layout(\n title=go.layout.Title(\n text=data_type,\n xref='paper',\n x=0\n ),\n showlegend=False,\n hovermode=\"closest\", # highlight closest point on hover\n margin={'t': 100, 'b': 60, 'l': 60, 'r': 0, 'pad': 8},\n xaxis=go.layout.XAxis(\n axis_style,\n range=[-degrees_to_rotate, degrees_to_rotate] # restrict y-axis to range of lon\n ),\n yaxis=go.layout.YAxis(\n axis_style,\n range=[-85, 85]\n ),\n annotations=[\n dict(\n text=anno_text,\n xref='paper',\n yref='paper',\n x=0,\n y=1,\n yanchor='bottom',\n showarrow=False,\n align='left'\n )\n ],\n autosize=False,\n width=500,\n height=400\n )\n\n traces_cc = get_coastline_traces(basemap_rotated)+get_country_traces(basemap_rotated)\n\n fw = go.FigureWidget(data=traces_cc + [go.Contour(z=data_rotated, x=lons_rotated[0, :],\n y=lats[:, 0])], layout=layout1)\n return fw\n\n\ndef get_figure_with_subplots(file_path, file_name, data_types, degrees_to_rotate=180):\n\n fw1 = get_widget_figure(file_path, file_name, data_types[0], degrees_to_rotate=degrees_to_rotate)\n fw2 = get_widget_figure(file_path, file_name, data_types[1], degrees_to_rotate=degrees_to_rotate)\n\n fig_subplots = ipywidgets.VBox([fw1, fw2], layout=ipywidgets.Layout(display='flex',\n flex_flow='column',\n align_items='center',\n width='100%'))\n return fig_subplots\n"
] | [
[
"numpy.hstack"
]
] |
gregyjames/PruferSequences | [
"da72bcafdc8f2a1c0414ac62dd49cff32070c566"
] | [
"GraphBonus.py"
] | [
"import graphClass\nimport networkx as nx\nimport matplotlib.pyplot as plt\nimport warnings\n\n#Filter all matplotlib warnings\nwarnings.filterwarnings(\"ignore\")\n\n#Find the leaf with the lowest label\ndef findLowestLeaf(G):\n #Empty array of vertexes\n vertexes = []\n #Look through every vertex of the graph\n for x in G.vertList:\n #Return the lowest number vertex with the 1 adjacent vertex (leaf)\n if len(G.getVertex(x).getAdj()) == 1:\n vertexes.append(x);\n #Return the first element of the list, thus the lowest leaf\n return sorted(vertexes)[0]\n\n#Convert a graph to a prufer sequence\ndef graphToPrufer(G):\n #Empty array to hold the sequence\n sequence = []\n graph = G\n\n while len(graph.getVertices()) > 2:\n lowest = findLowestLeaf(graph)\n sequence.append(graph.getVertex(lowest).getAdj()[0].id)\n graph.delVertex(lowest)\n return sequence\n\n#Find the lowest index in a dictionary\ndef findLowest(table, list_size):\n index = 0;\n\n for i in range(1, list_size + 1):\n if(table[i] == 1):\n index = i;\n break;\n\n table[index] = table[index] - 1;\n\n return index;\n\ndef checkForOnes(table):\n return 1 in table.values();\n\n#Convert a Prufer sequence to a Graph\ndef PruferToGraph(list):\n list_size = len(list) + 2\n table = {}\n #Create Empty Graph object\n G = nx.Graph()\n\n #Fill the empty table with values from 1..n+2 with one\n for x in range(1,list_size + 1):\n table[x] = 1\n G.add_node(x)\n\n #Fill the table with the counts from the list + 1\n for x in list:\n count = 0;\n for y in list:\n if x == y:\n count = count + 1\n table[x] = count + 1\n\n while len(list) > 0:\n #for every element in the sequence\n for x in range(1, len(list) + 1):\n #Find and remove the lowest number from the tree\n low = findLowest(table, list_size);\n G.add_edge(low, list[0])\n #Minus one count from the corresponding list element on the table\n table[list[0]] = table[list[0]] - 1;\n #Delete the item from the list\n del list[0]\n break;\n\n #The loop above leaves two vertexs remaining in the dictionary\n #This uses them to make the last edge of the graph\n last_edge_v1 = findLowest(table, list_size)\n last_edge_v2 = findLowest(table, list_size)\n G.add_edge(last_edge_v1, last_edge_v2)\n\n #Draw the graph\n nx.draw(G, with_labels=True, font_weight='bold')\n plt.show()\n return table\n\n#Build the graph from the counting trees ws\nP = graphClass.Graph()\nfor i in range(1,15):\n P.addVertex(i)\np = P.vertList[1]\nP.addEdge(9,1)\nP.addEdge(9,2)\nP.addEdge(10,3)\nP.addEdge(10,4)\nP.addEdge(11,5)\nP.addEdge(11,6)\nP.addEdge(12,7)\nP.addEdge(12,8)\nP.addEdge(13,9)\nP.addEdge(13,10)\nP.addEdge(14,11)\nP.addEdge(14,12)\nP.addEdge(15,13)\nP.addEdge(15,14)\n\n#Convert the graph into a sequence\nprufer = graphToPrufer(P)\n\n#Convert a sequence to a graph\nPruferToGraph(prufer)\n"
] | [
[
"matplotlib.pyplot.show"
]
] |
abishek-raju/EVA4B2 | [
"189f4062c85d91f43c1381087a9c89ff794e5428"
] | [
"S12/tensornet/data/datasets/tinyimagenet.py"
] | [
"import os\nimport csv\nimport random\nimport requests\nimport zipfile\nimport numpy as np\nfrom io import BytesIO\nfrom PIL import Image\nfrom torch.utils.data import Dataset\n\nfrom tensornet.data.datasets.dataset import BaseDataset\n\n\nclass TinyImageNet(BaseDataset):\n \"\"\"Load Tiny ImageNet Dataset.\"\"\"\n \n def _download(self, train=True, apply_transform=True):\n \"\"\"Download dataset.\n\n Args:\n train (bool, optional): True for training data.\n (default: True)\n apply_transform (bool, optional): True if transform\n is to be applied on the dataset. (default: True)\n \n Returns:\n Downloaded dataset.\n \"\"\"\n if not self.path.endswith('tinyimagenet'):\n self.path = os.path.join(self.path, 'tinyimagenet')\n transform = None\n if apply_transform:\n transform = self.train_transform if train else self.val_transform\n return TinyImageNetDataset(\n self.path, train=train, train_split=self.train_split, transform=transform\n )\n \n def _get_image_size(self):\n \"\"\"Return shape of data i.e. image size.\"\"\"\n return np.transpose(self.sample_data.data[0], (2, 0, 1)).shape\n \n def _get_classes(self):\n \"\"\"Return list of classes in the dataset.\"\"\"\n return self.sample_data.classes\n \n def _get_mean(self):\n \"\"\"Returns mean of the entire dataset.\"\"\"\n return tuple([0.5, 0.5, 0.5])\n \n def _get_std(self):\n \"\"\"Returns standard deviation of the entire dataset.\"\"\"\n return tuple([0.5, 0.5, 0.5])\n\n\nclass TinyImageNetDataset(Dataset):\n \"\"\"Load Tiny ImageNet Dataset.\"\"\"\n\n def __init__(self, path, train=True, train_split=0.7, download=True, random_seed=1, transform=None):\n \"\"\"Initializes the dataset for loading.\n\n Args:\n path (str): Path where dataset will be downloaded.\n train (bool, optional): True for training data. (default: True)\n train_split (float, optional): Fraction of dataset to assign\n for training. (default: 0.7)\n download (bool, optional): If True, dataset will be downloaded.\n (default: True)\n random_seed (int, optional): Random seed value. This is required\n for splitting the data into training and validation datasets.\n (default: 1)\n transform (optional): Transformations to apply on the dataset.\n (default: None)\n \"\"\"\n super(TinyImageNetDataset, self).__init__()\n \n self.path = path\n self.train = train\n self.train_split = train_split\n self.transform = transform\n self._validate_params()\n\n # Download dataset\n if download:\n self.download()\n\n self._class_ids = self._get_class_map()\n self.data, self.targets = self._load_data()\n\n self._image_indices = np.arange(len(self.targets))\n\n np.random.seed(random_seed)\n np.random.shuffle(self._image_indices)\n\n split_idx = int(len(self._image_indices) * train_split)\n self._image_indices = self._image_indices[:split_idx] if train else self._image_indices[split_idx:]\n \n def __len__(self):\n \"\"\"Returns length of the dataset.\"\"\"\n return len(self._image_indices)\n \n def __getitem__(self, index):\n \"\"\"Fetch an item from the dataset.\n\n Args:\n index (int): Index of the item to fetch.\n \n Returns:\n An image and its corresponding label.\n \"\"\"\n image_index = self._image_indices[index]\n \n image = self.data[image_index]\n if not self.transform is None:\n image = self.transform(image)\n \n return image, self.targets[image_index]\n \n def __repr__(self):\n \"\"\"Representation string for the dataset object.\"\"\"\n head = 'Dataset TinyImageNet'\n body = ['Number of datapoints: {}'.format(self.__len__())]\n if self.path is not None:\n body.append('Root location: {}'.format(self.path))\n body += [f'Split: {\"Train\" if self.train else \"Test\"}']\n if hasattr(self, 'transforms') and self.transforms is not None:\n body += [repr(self.transforms)]\n lines = [head] + [' ' * 4 + line for line in body]\n return '\\n'.join(lines)\n \n def _validate_params(self):\n \"\"\"Validate input parameters.\"\"\"\n if self.train_split > 1:\n raise ValueError('train_split must be less than 1')\n \n @property\n def classes(self):\n \"\"\"List of classes present in the dataset.\"\"\"\n return tuple(x[1]['name'] for x in sorted(\n self._class_ids.items(), key=lambda y: y[1]['id']\n ))\n \n def _get_class_map(self):\n \"\"\"Create a mapping from class id to the class name.\"\"\"\n with open(os.path.join(self.path, 'wnids.txt')) as f:\n class_ids = {x[:-1]: '' for x in f.readlines()}\n \n with open(os.path.join(self.path, 'words.txt')) as f:\n class_id = 0\n for line in csv.reader(f, delimiter='\\t'):\n if line[0] in class_ids:\n # class_ids[line[0]] = line[1].split(',')[0].lower()\n class_ids[line[0]] = {\n 'name': line[1],\n 'id': class_id\n }\n class_id += 1\n \n return class_ids\n \n def _load_image(self, image_path):\n \"\"\"Load an image from the dataset.\n\n Args:\n image_path (str): Path of the image.\n \n Returns:\n PIL object of the image.\n \"\"\"\n image = Image.open(image_path)\n\n # Convert grayscale image to RGB\n if image.mode == 'L':\n image = np.array(image)\n image = np.stack((image,) * 3, axis=-1)\n image = Image.fromarray(image.astype('uint8'), 'RGB')\n \n return image\n\n def _load_data(self):\n \"\"\"Fetch data from each data directory and store them in a list.\"\"\"\n data, targets = [], []\n\n # Fetch train dir images\n train_path = os.path.join(self.path, 'train')\n for class_dir in os.listdir(train_path):\n train_images_path = os.path.join(train_path, class_dir, 'images')\n for image in os.listdir(train_images_path):\n if image.lower().endswith('.jpeg'):\n data.append(\n self._load_image(os.path.join(train_images_path, image))\n )\n targets.append(self._class_ids[class_dir]['id'])\n \n # Fetch val dir images\n val_path = os.path.join(self.path, 'val')\n val_images_path = os.path.join(val_path, 'images')\n with open(os.path.join(val_path, 'val_annotations.txt')) as f:\n for line in csv.reader(f, delimiter='\\t'):\n data.append(\n self._load_image(os.path.join(val_images_path, line[0]))\n )\n targets.append(self._class_ids[line[1]]['id'])\n \n return data, targets\n \n def download(self):\n \"\"\"Download the data if it does not exist.\"\"\"\n if not os.path.exists(self.path):\n print('Downloading dataset...')\n r = requests.get('http://cs231n.stanford.edu/tiny-imagenet-200.zip', stream=True)\n zip_ref = zipfile.ZipFile(BytesIO(r.content))\n zip_ref.extractall(os.path.dirname(self.path))\n zip_ref.close()\n\n # Move file to appropriate location\n os.rename(\n os.path.join(os.path.dirname(self.path), 'tiny-imagenet-200'),\n self.path\n )\n print('Done.')\n else:\n print('Files already downloaded.')\n"
] | [
[
"numpy.random.seed",
"numpy.random.shuffle",
"numpy.stack",
"numpy.transpose",
"numpy.array"
]
] |
amirhosseinh77/Autonomous-Vehicle-Environment-Perception | [
"f834ea23f80eda6e33796a0b97c909b43da37eb3"
] | [
"main.py"
] | [
"from elements.yolo import YOLO, YOLO_Sign\nfrom elements.PINet import LaneDetection\nfrom elements.SGD import Inference\nfrom elements.asset import cityscape_xyz, kitti_xyz, apply_mask, ROI, kitti_xyz_dist, cityscape_xyz_dist, plot_one_box\nfrom elements.asset import horiz_lines, detect_lines\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport cv2\nfrom time import time as t\nimport datetime\nimport random\nimport sys\nfrom datetime import timedelta\nfrom SGDepth.arguments import InferenceEvaluationArguments\n\n\nopt = InferenceEvaluationArguments().parse()\n\n\nif opt.noshow and not opt.save:\n print(\"You're not getting any outputs!!\\nExit\")\n sys.exit()\n\n\ndetector = YOLO(opt.weights_detector)\n\nif opt.lane_detector_type == 'culane':\n lane_detector = LaneDetection(opt.culane_model, opt.lane_detector_type)\n print(\"CULane model loaded!\")\nif opt.lane_detector_type == 'curvelane':\n lane_detector = LaneDetection(opt.curvelane_model, opt.lane_detector_type)\n print(\"Curvelane model loaded!\")\n\ndisparity_detector = Inference(opt.disp_detector)\nsign_detector = YOLO_Sign(opt.weights_sign)\n\n#Video Writer\ncap = cv2.VideoCapture(opt.video)\nframe_count = cap.get(cv2.CAP_PROP_FRAME_COUNT)\n\nw = cap.get(cv2.CAP_PROP_FRAME_WIDTH)\nh = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)\n\nrotate = w<h\nif rotate :\n h,w = w,h\nresize = not ((w == 1280) and (h == 720))\nprint('resize ', resize)\nprint('rotate ', rotate)\n\n\nif opt.save:\n if len(opt.output_name.split('.'))==1:\n opt.output_name += '.mp4'\n output_video_folder = os.path.join('outputs/', opt.output_name.split('.')[0])\n if opt.save_frames:\n output_frames_folder = os.path.join(output_video_folder, 'frames')\n os.makedirs(output_frames_folder, exist_ok=True)\n output_video_name = os.path.join(output_video_folder, opt.output_name)\n os.makedirs(output_video_folder, exist_ok = True)\n print(output_video_folder)\n w = cap.get(cv2.CAP_PROP_FRAME_WIDTH)\n h = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)\n\n out = cv2.VideoWriter(output_video_name, \n cv2.VideoWriter_fourcc(*'mp4v'), \n opt.outputfps, (int(h), int(w)))\n\nnames = {\n 'person': 0,\n 'car' : 1,\n 'bus': 2,\n 'truck' : 3,\n 'traffic light' : 4,\n 'stop sign' : 5}\ncolors = [[random.randint(0, 255) for _ in range(3)] for _ in names]\n\nsigns = ['Taghadom', 'Chap Mamnoo', 'Rast Mamnoo', 'SL30', 'Tavaghof Mamnoo',\n 'Vorood Mamnoo', 'Mostaghom', 'SL40', 'SL50', 'SL60', 'SL70', 'SL80', 'SL100', 'No U-Turn']\ncolors_signs = [[random.randint(0, 255) for _ in range(3)] for _ in signs]\navg_fps = 0 #Average FPS\nframe_num = 0\n\nwhile(cap.isOpened()):\n \n ret, frame = cap.read()\n frame_num += 1\n if not frame_num% opt.frame_drop ==0:\n continue\n\n if ret:\n t1 = t() #Start Time\n if rotate:\n frame = cv2.rotate(frame, cv2.ROTATE_90_COUNTERCLOCKWISE)\n \n if resize:\n frame = cv2.resize(frame , (int(1280),int(720)))\n\n main_frame = frame.copy()\n yoloOutput = detector.detect(frame)\n signOutput = sign_detector.detect_sign(frame)\n disparity, seg_img = disparity_detector.inference(frame)\n \n #set the desired area to eliminate bad distances\n masked_image = ROI(main_frame)\n frame = lane_detector.Testing(frame, masked_image)\n if opt.mode != 2:\n frame = apply_mask(frame, seg_img, masked_image)\n\n for obj in yoloOutput:\n xyxy = [obj['bbox'][0][0], obj['bbox'][0][1], obj['bbox'][1][0], obj['bbox'][1][1]]\n depth = []\n if obj['label'] =='car' or obj['label'] == 'truck' or obj['label'] == 'bus':\n x_pts = (obj['bbox'][0][0]+obj['bbox'][1][0])/2\n y_pts = (obj['bbox'][0][1]+obj['bbox'][1][1])/2\n\n #ِDistance Measurement\n if np.dot(masked_image[int(y_pts), int(x_pts)], main_frame[int(y_pts), int(x_pts)]) != 0:\n Ry = 192/720\n Rx = 640/1280\n x_new, y_new =(Rx * x_pts, Ry * y_pts)\n\n cropped_img = main_frame[xyxy[1]:xyxy[3], xyxy[0]:xyxy[2]]\n cropped_disp = np.array(disparity[int(xyxy[1]*Ry):int(xyxy[3]*Ry), int(xyxy[0]*Rx):int(xyxy[2]*Rx)]) \n cropped_img = cv2.resize(cropped_img, (cropped_disp.shape[1], cropped_disp.shape[0]))\n cropped_img = cropped_img[int(cropped_img.shape[0]/2 - 20): int(cropped_img.shape[0]/2 + 20),\n int(cropped_img.shape[1]/2 - 20): int(cropped_img.shape[1]/2 + 20)]\n\n indices = np.where(cropped_img!= [0])\n coordinates = zip(indices[0], indices[1])\n\n for x,y in coordinates:\n try:\n depth.append([x, y, cropped_disp[y,x]])\n except:\n pass\n \n if opt.depth_mode == 'kitti':\n distance = kitti_xyz_dist(depth)\n else : \n distance = cityscape_xyz_dist(depth)\n\n printed_distance = np.mean(np.array(sorted(distance)[:15]))\n\n if printed_distance < 10:\n plot_one_box(xyxy, frame, printed_distance, label=obj['label'], color=colors[names[obj['label']]], line_thickness=3)\n else:\n plot_one_box(xyxy, frame, label=obj['label'], color=colors[names[obj['label']]], line_thickness=3)\n else:\n plot_one_box(xyxy, frame, label=obj['label'], color=colors[names[obj['label']]], line_thickness=3)\n else:\n plot_one_box(xyxy, frame, label=obj['label'], color=colors[names[obj['label']]], line_thickness=3)\n\n for sign in signOutput:\n xyxy = [sign['bbox'][0][0], sign['bbox'][0][1], sign['bbox'][1][0], sign['bbox'][1][1]]\n plot_one_box(xyxy, frame, label=sign[\"label\"], color=colors_signs[sign['cls']], line_thickness=3)\n \n t2 = t() #End of frame time\n fps = np.round(1 / (t2-t1) , 3) #Running FPS\n avg_fps = fps * 0.05 + 0.95 * avg_fps\n estimated_time = (frame_count - frame_num) / avg_fps\n estimated_time = str(timedelta(seconds=estimated_time)).split('.')[0]\n s = \"FPS : \"+ str(fps)\n if opt.fps:\n cv2.putText(frame, s, (40, 40), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), thickness= 2)\n \n \n #Cross Walk Lines\n frame = horiz_lines(main_frame, frame, mode = opt.mode)\n\n\n # Saving the output\n if opt.save:\n out.write(frame)\n if opt.save_frames:\n cv2.imwrite(os.path.join(output_frames_folder , '{0:04d}.jpg'.format(int(frame_num))) , frame)\n \n\n if not opt.noshow:\n cv2.imshow('frame',frame)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n else:\n break\n\n sys.stdout.write(\n \"\\r[Input Video : %s] [%d/%d Frames Processed] [FPS : %f] [ET : %s]\"\n % (\n opt.video,\n frame_num,\n frame_count,\n fps,\n estimated_time\n )\n )\n \ncap.release()\n\nif not opt.noshow:\n cv2.destroyAllWindows()\n"
] | [
[
"numpy.round",
"numpy.where"
]
] |
canturan10/satellighte | [
"09c906fdf8b538296c488d0c2d86c344007f8666"
] | [
"satellighte/module.py"
] | [
"import os\nfrom typing import Dict, List, Union\n\nimport numpy as np\nimport pytorch_lightning as pl\nimport torch\n\nfrom . import api\nfrom .core import _get_arch_cls, _get_model_dir, _parse_saved_model_name\nfrom .utils import configure_batch, convert_json\nimport torchmetrics as tm\n\n\nclass Classifier(pl.LightningModule):\n \"\"\"Generic pl.LightningModule definition for image classification\"\"\"\n\n # pylint: disable=no-member\n # pylint: disable=not-callable\n\n def __init__(\n self,\n model: torch.nn.Module,\n hparams: Dict = None,\n ):\n super().__init__()\n self.model = model\n self.__metrics = {}\n\n self.save_hyperparameters(hparams)\n self.configure_preprocess()\n\n @property\n def input_size(self):\n return self.model.config.get(\"input\").get(\"input_size\")\n\n @property\n def labels(self):\n return self.model.labels\n\n # WARNING: This function should only be used during training. not inference\n def forward(\n self,\n batch: torch.Tensor,\n ) -> torch.Tensor:\n \"\"\"\n Forward pass of the model.\n\n Args:\n batch (torch.Tensor): Batch of tensors of shape (B x C x H x W).\n\n Returns:\n torch.Tensor: Prediction of the model.\n \"\"\"\n\n # Apply preprocess with the help of registered buffer\n batch = ((batch / self.normalizer) - self.mean) / self.std\n\n with torch.no_grad():\n # Get logits from the model\n logits = self.model.forward(batch)\n\n # Apply postprocess for the logits that are returned from model and get predictions\n preds = self.model.logits_to_preds(logits)\n\n return preds\n\n @torch.jit.unused\n def predict(\n self,\n data: Union[np.ndarray, List],\n target_size: int = None,\n ):\n \"\"\"\n Perform image classification using given image or images.\n\n Args:\n data (Union[np.ndarray, List]): Numpy array or list of numpy arrays. In the form of RGB.\n target_size (int, optional): If it is not None, the image will be resized to the target size. Defaults to None.\n\n Returns:\n [type]: [description]\n \"\"\"\n\n # Converts given image or list of images to list of tensors\n batch = self.to_tensor(data)\n\n # Override target_size if input_size is given and target_size is None\n if self.input_size and (target_size is None):\n target_size = self.input_size\n\n # Configure batch for the required size\n batch = configure_batch(\n batch,\n target_size=target_size,\n adaptive_batch=target_size is None,\n )\n\n # Get predictions from the model\n preds = self.forward(batch)\n\n # Convert predictions to json format\n json_preds = convert_json(preds, self.labels)\n return json_preds\n\n @classmethod\n def build(\n cls,\n arch: str,\n config: str = None,\n hparams: Dict = {},\n **kwargs,\n ) -> pl.LightningModule:\n \"\"\"\n Build the model with given architecture and configuration.\n\n Args:\n arch (str): Model architecture name.\n config (str, optional): Model configuration. Defaults to None.\n hparams (Dict, optional): Hyperparameters. Defaults to {}.\n\n Returns:\n pl.LightningModule: Model instance with randomly initialized weights.\n \"\"\"\n\n model = cls.build_arch(arch, config=config, **kwargs)\n return cls(model, hparams=hparams)\n\n @classmethod\n def build_arch(\n cls,\n arch: str,\n config: str = None,\n **kwargs,\n ) -> torch.nn.Module:\n \"\"\"\n Build the architecture model with given configuration.\n\n Args:\n arch (str): Model architecture name.\n config (str, optional): Model configuration. Defaults to None.\n\n Returns:\n torch.nn.Module: Architecture model instance with randomly initialized weights.\n \"\"\"\n\n arch_cls = _get_arch_cls(arch)\n return arch_cls.build(config=config, **kwargs)\n\n @classmethod\n def from_pretrained(\n cls,\n model_name: str,\n version: int = None,\n hparams: Dict = {},\n ) -> pl.LightningModule:\n \"\"\"\n [summary]\n\n Args:\n model_name (str): Model name in the format of {arch}_{config}_{dataset}\n version (int, optional): Model version. Defaults to None.\n hparams (Dict, optional): Hyperparameters. Defaults to {}.\n\n Returns:\n pl.LightningModule: Model instance.\n \"\"\"\n\n model = cls.from_pretrained_arch(model_name, version=version)\n return cls(model, hparams=hparams)\n\n @classmethod\n def from_pretrained_arch(\n cls,\n model_name: str,\n version: int = None,\n ) -> torch.nn.Module:\n \"\"\"\n Get pretrained arch model from the model name.\n\n Args:\n model_name (str): Model name in the format of {arch}_{config}_{dataset}\n version (int, optional): Model version. Defaults to None.\n\n Returns:\n torch.nn.Module: Architecture model instance.\n \"\"\"\n\n # Check if version is not given then get the latest version\n if not version:\n version = api.get_model_latest_version(model_name)\n\n # Get arch name and config name from the given model_name\n arch, config, _ = _parse_saved_model_name(model_name)\n\n # Get arch class\n arch_cls = _get_arch_cls(arch)\n\n api.get_saved_model(model_name, version)\n\n # Get pretrained model pat\n model_path = os.path.join(_get_model_dir(), model_name, f\"v{version}\")\n\n return arch_cls.from_pretrained(model_path, config=config)\n\n def training_step(self, batch, batch_idx):\n batch, targets = batch\n\n # Apply preprocess with the help of registered buffer\n batch = ((batch / self.normalizer) - self.mean) / self.std\n\n # Get logits from the model\n logits = self.model.forward(batch)\n\n # Compute loss\n loss = self.model.compute_loss(\n logits,\n targets,\n hparams=self.hparams,\n )\n\n return loss\n\n def training_epoch_end(self, outputs):\n losses = {}\n for output in outputs:\n if isinstance(output, dict):\n for k, v in output.items():\n if k not in losses:\n losses[k] = []\n losses[k].append(v)\n else:\n if \"loss\" not in losses:\n losses[\"loss\"] = []\n losses[\"loss\"].append(output)\n\n for name, loss in losses.items():\n self.log(\"{}/training\".format(name), sum(loss) / len(loss))\n\n def on_validation_epoch_start(self):\n for metric in self.__metrics.values():\n metric.reset()\n\n def validation_step(self, batch, batch_idx):\n batch, targets = batch\n\n # Apply preprocess with the help of registered buffer\n batch = ((batch / self.normalizer) - self.mean) / self.std\n\n with torch.no_grad():\n # Get logits from the model\n logits = self.model.forward(batch)\n\n # Compute loss\n loss = self.model.compute_loss(\n logits,\n targets,\n hparams=self.hparams,\n )\n\n # Apply postprocess for the logits that are returned from model and get predictions\n preds = self.model.logits_to_preds(logits)\n\n for metric in self.__metrics.values():\n metric.update(preds.cpu(), targets.cpu())\n\n return loss\n\n def validation_epoch_end(self, outputs):\n losses = {}\n for output in outputs:\n if isinstance(output, dict):\n for k, v in output.items():\n if k not in losses:\n losses[k] = []\n losses[k].append(v)\n else:\n if \"loss\" not in losses:\n losses[\"loss\"] = []\n losses[\"loss\"].append(output)\n\n for name, loss in losses.items():\n self.log(\"{}/validation\".format(name), sum(loss) / len(loss))\n\n for name, metric in self.__metrics.items():\n self.log(\n \"metrics/{}\".format(name),\n metric.compute(),\n prog_bar=True,\n )\n\n def on_test_epoch_start(self):\n for metric in self.__metrics.values():\n metric.reset()\n\n def test_step(self, batch, batch_idx):\n batch, targets = batch\n\n # Apply preprocess with the help of registered buffer\n batch = ((batch / self.normalizer) - self.mean) / self.std\n\n with torch.no_grad():\n # Get logits from the model\n logits = self.model.forward(batch)\n\n # Compute loss\n loss = self.model.compute_loss(\n logits,\n targets,\n hparams=self.hparams,\n )\n\n # Apply postprocess for the logits that are returned from model and get predictions\n preds = self.model.logits_to_preds(logits)\n\n for metric in self.__metrics.values():\n metric.update(preds.cpu(), targets.cpu())\n\n def test_epoch_end(self, outputs):\n metric_results = {}\n for name, metric in self.__metrics.items():\n metric_results[name] = metric.compute()\n return metric_results\n\n def configure_optimizers(self):\n return self.model.configure_optimizers(hparams=self.hparams)\n\n def configure_preprocess(self):\n \"\"\"\n Configure preprocess for the model.\n \"\"\"\n\n # Get information from config of model\n normalized_input = self.model.config.get(\"input\", {}).get(\n \"normalized_input\", True\n )\n mean = self.model.config.get(\"input\", {}).get(\"mean\", 0.0)\n std = self.model.config.get(\"input\", {}).get(\"std\", 1.0)\n\n # Check dimension of std and mean\n if isinstance(mean, list):\n assert len(mean) == 3, \"mean dimension must be 3 not {}\".format(len(mean))\n mean = [float(m) for m in mean]\n else:\n mean = [float(mean) for _ in range(3)]\n\n if isinstance(std, list):\n assert len(std) == 3, \"std dimension must be 3 not {}\".format(len(std))\n std = [float(m) for m in std]\n else:\n std = [float(std) for _ in range(3)]\n\n # Register the tensors as a buffer\n # Now we can access self.normalizer anywhere in the module\n self.register_buffer(\n \"normalizer\",\n torch.tensor(255.0) if normalized_input else torch.tensor(1.0),\n persistent=False,\n )\n\n # Now we can access self.mean anywhere in the module\n self.register_buffer(\n \"mean\",\n torch.tensor(mean).view(-1, 1, 1).contiguous(),\n persistent=False,\n )\n\n # Now we can access self.std anywhere in the module\n self.register_buffer(\n \"std\",\n torch.tensor(std).view(-1, 1, 1).contiguous(),\n persistent=False,\n )\n\n def add_metric(self, name: str, metric: tm.Metric):\n \"\"\"Adds given metric with name key\n\n Args:\n name (str): name of the metric\n metric (tm.Metric): Metric object\n \"\"\"\n # TODO add warnings if override happens\n self.__metrics[name] = metric\n\n def get_metrics(self) -> Dict[str, tm.Metric]:\n \"\"\"Return metrics defined in the `FaceDetector` instance\n\n Returns:\n Dict[str, tm.Metric]: defined model metrics with names\n \"\"\"\n return {k: v for k, v in self.__metrics.items()}\n\n def to_tensor(self, images: Union[np.ndarray, List]) -> List[torch.Tensor]:\n \"\"\"Converts given image or list of images to list of tensors\n Args:\n images (Union[np.ndarray, List]): RGB image or list of RGB images\n Returns:\n List[torch.Tensor]: list of torch.Tensor(C x H x W)\n\n This method is taken from fastface repositories.\n `fastface.module.to_tensor`\n Here is a link for it: `github.com/borhanMorphy/fastface`\n \"\"\"\n assert isinstance(\n images, (list, np.ndarray)\n ), \"give images must be eather list of numpy arrays or numpy array\"\n\n if isinstance(images, np.ndarray):\n images = [images]\n\n batch: List[torch.Tensor] = []\n\n for img in images:\n assert (\n len(img.shape) == 3\n ), \"image shape must be channel, height\\\n , with length of 3 but found {}\".format(\n len(img.shape)\n )\n assert (\n img.shape[2] == 3\n ), \"channel size of the image must be 3 but found {}\".format(img.shape[2])\n\n batch.append(\n # h,w,c => c,h,w\n torch.tensor(img, dtype=self.dtype, device=self.device).permute(2, 0, 1)\n )\n\n return batch\n"
] | [
[
"torch.no_grad",
"torch.tensor"
]
] |
sovaso/GeneticAlgorithmForHumanoidRobotWalk | [
"b14d7a562226b32dd7b4c5f2b056cf1478700ce3"
] | [
"code/genetic_algorithm.py"
] | [
"import gym\nimport numpy as np\nimport torch\nimport time\nimport random\nfrom gym.wrappers import Monitor\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.distributions import MultivariateNormal\nimport torch.optim as optim\nimport math\nimport copy\nimport warnings\nimport pybulletgym\nfrom trpo_agent import TRPOAgent\nfrom actor import Actor\nfrom critic import Critic\nimport os\nimport json\n\n\nclass UnitResultUtil:\n \"\"\" Util class to help us keed information about one unit in the current generation \"\"\"\n\n def __init__(self, delta_a2, delta_a1, delta_a0, reward):\n \"\"\" Constructor for the unit result util class\n\n Args:\n delta_a2 (float): part of a delta function\n delta_a1 (float): part of a delta function\n delta_a0 (float): part of a delta function\n reward (float): fitness score the agent with these parameters achieved\n \"\"\"\n self.delta_a2 = delta_a2\n self.delta_a1 = delta_a1\n self.delta_a0 = delta_a0\n self.reward = reward\n\n\nclass GenerationResultUtil:\n \"\"\" Util class to help us keep all information about units in current generation \"\"\"\n\n def __init__(self, units):\n \"\"\" Constructor for the generation result util class\n\n Args:\n units (array): all units in current generation\n \"\"\"\n self.units = units\n\n def to_json(self):\n \"\"\" Converting the object to a string that is in json format and can be saved as json file\n\n Returns:\n (string): string as json format of the object\n \"\"\"\n\n return json.dumps(self, default=lambda o: o.__dict__, sort_keys=True)\n\n\nclass GeneticAlgorithm():\n \"\"\" Main class for the whole Genetic Algorithm process \"\"\"\n\n def __init__(self, number_of_agents, number_of_generations, number_of_iterations, top_limit_agents, \n mutation_chance, environment, path_to_save_results = \"../results\", starts_from = 0):\n \"\"\" Constructor for the Genetic Algorithm class \n \n Args:\n number_of_agents (integer): number of population per each generation\n number_of_generations (integer): number of generations to run ga\n number_of_iterations (integer): number of epochs to train each agent for fitness function\n top_limit_agents (integer): number of how many agents from current generation to pick to\n keep in next generation\n mutation_chance (float): chance that crossovered agent will be mutated\n environment (object): environment where the game will be played\n path_to_save_results (string): path where the results will be saved\n starts_from (int): number of generation to start with if it was already in process.\n Defaults to 0.\n \"\"\"\n\n self.number_of_agents = number_of_agents\n self.number_of_generations = number_of_generations\n self.number_of_iterations = number_of_iterations\n self.top_limit_agents = top_limit_agents\n self.mutation_chance = mutation_chance\n self.path_to_save_results = path_to_save_results\n self.environment = environment\n self.starts_from = starts_from\n\n def create_initial_population(self):\n \"\"\" Creating the first generation of the population by instancing new agents\n\n Returns:\n (array): population of agents\n \"\"\"\n\n #possible starter values for agents to pick for parameters we want to optimize\n a2_options = [10**x for x in np.random.uniform(-10, -1, self.number_of_agents)]\n a1_options = [10**x for x in np.random.uniform(-10, -1, self.number_of_agents)]\n a0_options = np.random.uniform(1, 15, self.number_of_agents)\n\n agents = []\n #for each expected agent number we create one agent\n for iter in range(self.number_of_agents):\n agent = TRPOAgent(actor=Actor(44, 17),\n critic=Critic(44, 1, 2.5e-4),\n delta_a2=a2_options[iter],\n delta_a1=a1_options[iter],\n delta_a0=a0_options[iter],\n gamma=0.99,\n cg_delta=1e-2,\n cg_iterations = 10,\n alpha=0.99,\n backtrack_steps_num=100,\n critic_epoch_num=20,\n epochs=self.number_of_iterations,\n num_of_timesteps=4800,\n max_timesteps_per_episode=1600)\n agents.append(agent)\n return agents\n\n def run_population(self, agents):\n \"\"\" Run current generation of the population to calculate their fitness function\n\n Args:\n agents (array): current generation of the population\n\n Returns:\n (array): rewards of fitness function for each agent\n \"\"\"\n\n reward_agents = []\n for agent in agents:\n cumulative_reward = agent.train(env=self.environment, return_only_rewards=True)\n reward_agents.append(cumulative_reward)\n return reward_agents\n\n def calculate_fitness_for_one_agent(self, agent):\n \"\"\" Calculating fitness function for one specific agent by training it for N iterations and\n then calculating cumulative reward it gets during that training\n\n Args:\n agent (object): one agent from the population\n\n Returns:\n (float): fitness score for that agent\n \"\"\"\n\n return self.run_population([agent])[0]\n\n def calculate_fitness_for_all_agents(self, agents):\n \"\"\" Calculating fitness function for every agent from the current generation of the\n population\n\n Args:\n agents (array): current generation of the population\n\n Returns:\n (array): fitness score for every agent\n \"\"\"\n\n fitness_scores = []\n for agent in agents:\n fitness_scores.append(self.calculate_fitness_for_one_agent(agent))\n return fitness_scores\n\n def mutate_agent(self, agent):\n \"\"\" Mutating agent in a range +/-10percent for its parameters value, with some chance\n\n Args:\n agent (object): one agent from the population\n\n Returns:\n (object): mutated agent for a new generation of the population\n \"\"\"\n\n c = random.uniform(0, 1)\n if c > self.mutation_chance:\n return agent\n child_agent = copy.deepcopy(agent)\n c2 = random.uniform(0, 1)\n child_agent.delta_a2 += 0.1 * (2*c2 - 1.0) * child_agent.delta_a2\n child_agent.delta_a1 += 0.1 * (2*c2 - 1.0) * child_agent.delta_a1\n child_agent.delta_a0 += 0.1 * (2*c2 - 1.0) * child_agent.delta_a0\n return child_agent\n\n def crossover_agents(self, first_agent, second_agent):\n \"\"\" Creating two children by taking a random uniform number C between 0 and 1 and summing\n both parent parameters by the formula: param1*C+param2(1-C) and other replacing param1\n and param2 in the formula.\n\n Args:\n first_agent (object): first parent\n second_agent (object): second parent\n\n Returns:\n (object, object): 2 children for next generation\n \"\"\"\n\n c = random.uniform(0, 1)\n first_child = copy.deepcopy(first_agent)\n second_child = copy.deepcopy(second_agent)\n first_child.delta_a2 = first_agent.delta_a2*c + (1-c)*second_agent.delta_a2\n first_child.delta_a1 = first_agent.delta_a1*c + (1-c)*second_agent.delta_a1\n first_child.delta_a0 = first_agent.delta_a0*c + (1-c)*second_agent.delta_a0\n second_child.delta_a2 = second_agent.delta_a2*c + (1-c)*first_agent.delta_a2\n second_child.delta_a1 = second_agent.delta_a1*c + (1-c)*first_agent.delta_a1\n second_child.delta_a0 = second_agent.delta_a0*c + (1-c)*first_agent.delta_a0\n return first_child, second_child\n\n def create_next_generation(self, agents, sorted_parent_indexes):\n \"\"\" Based on fitness score of current generation, take best agents from current generation\n and the rest of needed population create using crossover with the mutation\n\n Args:\n agents (array): current generation of the population\n sorted_parent_indexes (array): indices of the agents with the best fitness score\n\n Returns:\n (array): the next generation of the population\n (integer): index of elite agent in new generation\n \"\"\"\n\n children_agents = []\n #first take selected parents from sorted_parent_indexes and generate N-1 children\n for i in range((len(agents) - self.top_limit_agents) // 2):\n selected_agent_index_1, selected_agent_index_2 = self.selection_of_parents(\n sorted_parent_indexes)\n child_agent_1, child_agent_2 = self.crossover_agents(agents[selected_agent_index_1],\n agents[selected_agent_index_2])\n children_agents.append(self.mutate_agent(child_agent_1))\n children_agents.append(self.mutate_agent(child_agent_2))\n #take best agents into the next generation\n for index in sorted_parent_indexes[:self.top_limit_agents]:\n children_agents.append(agents[index])\n return children_agents\n\n def selection_of_parents(self, sorted_parent_indexes):\n \"\"\" Selecting possible parents for the crossover to create new generation and selecting them\n based on fitness function (reward from episodes) using softmax to give everyone a chance\n\n Args:\n sorted_parent_indexes (array): indexes of parents sorted by fitness function\n\n Returns:\n (int,int): indexes of two selected parents\n \"\"\"\n\n selection_util_array = np.zeros(self.number_of_agents)\n for iter in range(self.number_of_agents):\n selection_util_array[iter] = np.exp(-1 * (iter+1) * random.uniform(0, 1))\n selection_util_array /= np.sum(selection_util_array)\n parent_indexes = np.random.choice(sorted_parent_indexes, 2, p=selection_util_array)\n return parent_indexes[0], parent_indexes[1]\n\n def save_generation_results(self, agents, rewards, number_of_generation):\n \"\"\" Save information about the current generation by saving parameters and rewards of each unit\n current generation\n\n Args:\n agents (array): current generation\n rewards (array): fitness score of current generation\n number_of_generation (int): index of current generation\n \"\"\"\n agent_results = []\n for iter in range(len(agents)):\n agent_results.append(UnitResultUtil(agents[iter].delta_a2,\n agents[iter].delta_a1,\n agents[iter].delta_a0,\n rewards[iter]))\n with open(self.path_to_save_results + \"/generation_\" + str(number_of_generation) + \".json\", 'w') as f:\n json.dump(GenerationResultUtil(agent_results).to_json(), f)\n\n def read_last_generation(self):\n \"\"\" Reading last saved generation of the GA algorithm\n\n Returns:\n (array, array): agents in the last generation and their fitness scores\n \"\"\"\n\n agents, rewards = [], []\n generation_json = None\n with open(self.path_to_save_results + \"/generation_\" + str(self.starts_from-1) + \".json\") as jsonFile:\n generation_json = json.loads(json.load(jsonFile))\n jsonFile.close()\n for agent_unit in generation_json[\"units\"]:\n agent = TRPOAgent(actor=Actor(44, 17),\n critic=Critic(44, 1, 2.5e-4),\n delta_a2=agent_unit[\"delta_a2\"],\n delta_a1=agent_unit[\"delta_a1\"],\n delta_a0=agent_unit[\"delta_a0\"],\n gamma=0.99,\n cg_delta=1e-2,\n cg_iterations = 10,\n alpha=0.99,\n backtrack_steps_num=100,\n critic_epoch_num=20,\n epochs=self.number_of_iterations,\n num_of_timesteps=4800,\n max_timesteps_per_episode=1600)\n agents.append(agent)\n rewards.append(agent_unit[\"reward\"])\n return agents, rewards\n\n def run_genetic_algorithm(self):\n \"\"\" Main funtion to run the genetic algorithm \"\"\"\n\n agents = self.create_initial_population()\n for generation in range(self.number_of_generations):\n print(\"\\n=== GENERATION \" + str(generation) + \" ===\")\n if (generation < (self.starts_from-1)):\n continue\n if (self.starts_from != 0 and generation == (self.starts_from-1)):\n agents, rewards = self.read_last_generation()\n else:\n #return rewards of agents\n rewards = self.calculate_fitness_for_all_agents(agents)\n #sort by rewards\n sorted_parent_indexes = np.argsort(rewards)[::-1] \n top_rewards = []\n for best_parent in sorted_parent_indexes[:self.top_limit_agents]:\n top_rewards.append(rewards[best_parent])\n print(\"Generation \", generation, \" | Mean rewards: \", np.mean(rewards), \" | Mean of top 5: \",\n np.mean(top_rewards[:5]))\n print(\"Top \", self.top_limit_agents, \" scores\", sorted_parent_indexes[:self.top_limit_agents])\n print(\"Rewards for top: \", top_rewards)\n print(\"\")\n print(\"\")\n if (self.starts_from==0 or (self.starts_from!=0 and generation!=(self.starts_from-1))):\n #save informations about the generation\n self.save_generation_results(agents, rewards, generation)\n #setup an empty list for containing children agents\n children_agents = self.create_next_generation(agents, sorted_parent_indexes)\n #kill all agents, and replace them with their children\n agents = children_agents\n #reset each actor and critic of TRPO agent\n for agent in agents:\n agent.actor=Actor(44, 17)\n agent.critic=Critic(44, 1, 2.5e-4)\n"
] | [
[
"numpy.random.choice",
"numpy.random.uniform",
"numpy.mean",
"numpy.argsort",
"numpy.zeros",
"numpy.sum"
]
] |
jens-38/UCI-ML-API | [
"bda73d73cb5abd600b877f2f15934cb58012531a"
] | [
"UCI_ML_Functions.py"
] | [
"# Functions to read, analyze, and download from UCI ML portal\n\n# ==========================================\n# Function to read UCI ML datasets table\n# ==========================================\ndef read_dataset_table(\n url=\"https://archive.ics.uci.edu/ml/datasets.php\", msg_flag=True\n):\n \"\"\"\n Reads the table of datasets from the url: \"https://archive.ics.uci.edu/ml/datasets.html\" and process it further to clean and categorize\n \"\"\"\n import pandas as pd\n\n try:\n if msg_flag:\n print(\"Reading the dataset table from UCI ML repo...\")\n datasets = pd.read_html(url)\n if msg_flag:\n print(\"Finished reading the table!\")\n except:\n print(\"Could not read the table from UCI ML portal, Sorry!\")\n\n df = datasets[5] # Fifth entry of this table is the main datasets information\n # Rows and columns of the dataframe\n nrows = df.shape[0]\n ncols = df.shape[1]\n\n # Read the pertinent rows (skipping every alternate one) and columns\n df = df.iloc[1:nrows:2][[2, 3, 4, 5, 6, 7, 8]]\n\n # Assign column names\n df.columns = [\n \"Name\",\n \"Data Types\",\n \"Default Task\",\n \"Attribute Types\",\n \"Number of Instances\",\n \"Number of Attributes\",\n \"Year\",\n ]\n\n # Set index from 1\n df.index = [i for i in range(1, int(nrows / 2) + 1)]\n\n return df\n\n\n# ==============================================================================================\n# Function to remove entries with unknown number of samples and cleanly define task categories\n# ==============================================================================================\ndef clean_dataset_table(df, msg_flag=True):\n \"\"\"\n Accepts the raw dataset table (a DataFrame object) and returns a cleaned up version removing entries with unknown number of samples and attributes\n Also creates a 'Task' category column indicating the main machine learning task associated with the dataset\n \"\"\"\n import time\n import pandas as pd\n\n if msg_flag:\n print(\"Cleaning up the dataset table\", end=\"\")\n for i in range(11):\n time.sleep(0.2)\n print(\".\", end=\"\")\n print(\" \", end=\"\")\n print()\n print(\"Rationalizing the task categories\", end=\"\")\n for i in range(11):\n time.sleep(0.2)\n print(\".\", end=\"\")\n print(\" \", end=\"\")\n\n pd.set_option(\"mode.chained_assignment\", None)\n\n df_copy = df.copy()\n df_clean = df_copy.dropna(subset=[\"Number of Instances\"])\n df_clean[\"Number of Instances\"] = df_clean[\"Number of Instances\"].apply(int)\n\n def size_instances(n):\n if n <= 100:\n return \"Small\"\n elif n <= 1000:\n return \"Medium\"\n elif n <= 10000:\n return \"Large\"\n else:\n return \"Extra Large\"\n\n df_clean[\"Sample size\"] = df_clean[\"Number of Instances\"].apply(size_instances)\n\n def categorize_task(task):\n if len(task) > 1:\n tasks = task.split(\", \")\n else:\n tasks = list(task)\n\n if len(tasks) == 1 and tasks[0] == \"Classification\":\n return \"Classification\"\n elif \"Clustering\" in tasks:\n return \"Clustering\"\n elif \"Regression\" in tasks:\n return \"Regression\"\n elif \"Recommender-Systems\" in tasks:\n return \"Recommender Systems\"\n elif \"Causal-Discovery\" in tasks:\n return \"Causal Discovery\"\n else:\n return \"Other/Unknown\"\n\n df_clean[\"Default Task\"] = df_clean[\"Default Task\"].apply(str)\n df_clean[\"Default Task\"] = df_clean[\"Default Task\"].apply(categorize_task)\n\n if msg_flag:\n print(\"\\nFinished processing the table!\")\n\n return df_clean\n\n\n# ======================================================================================================\n# Function to build a local table (CSV file) with name, attributes, machine learning tasks, size, etc\n# ======================================================================================================\ndef build_local_table(filename=None, msg_flag=True):\n \"\"\"\n Reads through the UCI ML portal and builds a local table with information such as: \\\n name, size, ML task, data type\n filename: Optional filename that can be chosen by the user\n \"\"\"\n df_table = read_dataset_table(msg_flag=msg_flag)\n df_clean = clean_dataset_table(df_table, msg_flag=msg_flag)\n try:\n if filename != None:\n df_clean.to_csv(filename)\n else:\n df_clean.to_csv(\"UCI table.csv\")\n except:\n print(\n \"Sorry, could not create the CSV table. Please make sure to close an already opened file, \\\n or to have sufficient permission to write files in the current directory\"\n )\n\n\n# ==================================================================\n# Function to read the main page text and create list of datasets\n# ==================================================================\ndef build_dataset_list(url=\"https://archive.ics.uci.edu/ml/datasets\", msg_flag=True):\n \"\"\"\n Scrapes through the UCI ML datasets page and builds a list of all datasets.\n \"\"\"\n\n import urllib.request, urllib.parse, urllib.error\n from bs4 import BeautifulSoup\n import ssl\n import time\n\n # Ignore SSL certificate errors\n ctx = ssl.create_default_context()\n ctx.check_hostname = False\n ctx.verify_mode = ssl.CERT_NONE\n\n # Read the HTML from the URL and pass on to BeautifulSoup\n url = url\n if msg_flag:\n print(\"Opening the file connection...\")\n try:\n uh = urllib.request.urlopen(url, context=ctx)\n # print(\"HTTP status\",uh.getcode())\n html = uh.read()\n # print(f\"Reading done. Total {len(html)} characters read.\")\n except:\n print(\"Could not open the UCI ML portal successfully. Sorry!\")\n return -1\n\n soup = BeautifulSoup(html, \"html5lib\")\n\n dataset_list = []\n lst = []\n\n for link in soup.find_all(\"a\"):\n lst.append(link.attrs)\n\n if msg_flag:\n print()\n print(\"Adding datasets to the list\", end=\"\")\n\n for i in range(11):\n time.sleep(0.3)\n print(\".\", end=\"\")\n print(\" \", end=\"\")\n\n for l in lst:\n a = l[\"href\"]\n if a.find(\"/\") != -1:\n x = a.split(\"/\")\n if len(x) == 2:\n dataset_list.append(x[1])\n\n dataset_list = list(set(dataset_list))\n dataset_list = sorted(dataset_list)\n\n if msg_flag:\n print(\"\\nFinished adding datasets to the list!\")\n\n return dataset_list\n\n\n# ======================================================================================\n# Function to create dictionary of datasets' name, description, and identifier string\n# ======================================================================================\ndef build_dataset_dictionary(\n url=\"https://archive.ics.uci.edu/ml/datasets.php?format=&task=&att=&area=&numAtt=&numIns=&type=&sort=nameUp&view=list\",\n msg_flag=True,\n):\n \"\"\"\n Scrapes through the UCI ML datasets page and builds a dictionary of all datasets with names and description.\n Also stores the unique identifier corresponding to the dataset.\n This identifier string is needed by the downloader function to download the data file. Generic name won't work.\n \"\"\"\n import urllib.request, urllib.parse, urllib.error\n from bs4 import BeautifulSoup\n import ssl\n import time\n import re\n\n # Ignore SSL certificate errors\n ctx = ssl.create_default_context()\n ctx.check_hostname = False\n ctx.verify_mode = ssl.CERT_NONE\n\n url = url\n if msg_flag:\n print(\"Opening the file connection...\")\n try:\n uh = urllib.request.urlopen(url, context=ctx)\n html = uh.read()\n except:\n print(\"Could not open the UCI ML portal successfully. Sorry!\")\n return -1\n\n soup = BeautifulSoup(html, \"html5lib\")\n\n lst = []\n for tag in soup.find_all(\"p\"):\n lst.append(tag.contents)\n\n i = 0\n description_dict = {}\n\n for l in lst:\n if len(l) > 2:\n if str(l[1]).find(\"datasets/\") != -1:\n string = str(l[1])\n s = re.search('\">.*</a>', string)\n x, y = s.span()\n name = string[x + 2 : y - 4]\n desc = l[2][2:]\n tmp_list = []\n description_dict[name] = tmp_list\n description_dict[name].append(desc)\n s = re.search('\".*\"', string)\n x, y = s.span()\n identifier = string[x + 10 : y - 1]\n description_dict[name].append(identifier)\n i += 1\n if msg_flag:\n if i % 10 == 0 and i != 0:\n print(f\"Record {i} processed!\")\n\n return description_dict\n\n\n# ===============================================================\n# Function to create a DataFrame with all information together\n# ===============================================================\ndef build_full_dataframe(msg_flag=False):\n \"\"\"\n Builds a DataFrame with all information together including the url link for downloading the data.\n \"\"\"\n import pandas as pd\n import urllib.request, urllib.parse, urllib.error\n from bs4 import BeautifulSoup\n import ssl\n import time\n\n # Ignore SSL certificate errors\n ctx = ssl.create_default_context()\n ctx.check_hostname = False\n ctx.verify_mode = ssl.CERT_NONE\n\n i = 0\n d = build_dataset_dictionary(msg_flag=False)\n new_d = {}\n dataset_list = build_dataset_list(msg_flag=False)\n\n for k, v in d.items():\n a = extract_url_dataset(v[1], msg_flag=msg_flag)\n if a != None:\n desc = v[0]\n identifier = v[1]\n v[0] = k\n v[1] = desc\n v.append(identifier)\n v.append(a)\n new_d[k] = v\n i += 1\n if msg_flag:\n print(f\"Dataset processed:{k}\")\n else:\n desc = v[0]\n identifier = v[1]\n v[0] = k\n v[1] = desc\n v.append(identifier)\n v.append(\"URL not available\")\n new_d[k] = v\n if msg_flag:\n print(f\"Dataset processed:{k}\")\n if msg_flag:\n print(\"\\nTotal datasets analyzed: \", i)\n\n df_dataset = pd.DataFrame(data=new_d)\n df_dataset = df_dataset.T\n df_dataset.columns = [\"Name\", \"Abstract\", \"Identifier string\", \"Datapage URL\"]\n df_dataset.index.set_names([\"Dataset\"], inplace=True)\n\n return df_dataset\n\n\n# ================================================================================================\n# Function to build a local database (CSV file) with name and URL (of raw data page) information\n# ================================================================================================\ndef build_local_database(filename=None, msg_flag=True):\n \"\"\"\n Reads through the UCI ML portal and builds a local table with information such as: \\\n name, size, ML task, data type\n filename: Optional filename that can be chosen by the user\n \"\"\"\n df_local = build_full_dataframe(msg_flag=msg_flag)\n try:\n if filename != None:\n df_local.to_csv(filename)\n else:\n df_local.to_csv(\"UCI database.csv\")\n except:\n print(\n \"Sorry, could not create the CSV table. Please make sure to close an already opened file, \\\n or to have sufficient permission to write files in the current directory\"\n )\n\n\n# ===============================================================================\n# Function to extract abstract/description of a particular dataset by searching\n# ===============================================================================\ndef return_abstract(name, local_database=None, msg_flag=False):\n \"\"\"\n Returns one-liner description (and webpage link for further information) of a particular dataset by searching the given name.\n local_database: Name of the database (CSV file) stored locally i.e. in the same directory, which contains information about all the datasets on UCI ML repo. \n msg_flag: Controls verbosity\n \"\"\"\n\n import pandas as pd\n\n if local_database != None:\n local_df_flag = True\n df = pd.read_csv(local_database, index_col=\"Dataset\")\n else:\n local_df_flag = False\n if msg_flag:\n print(\n \"Local database not supplied.\\nBuilding the master database by crawling the website...\"\n )\n df = build_full_dataframe(msg_flag=False)\n if msg_flag:\n print(\"Done!\")\n\n # Number of rows\n nrows = df.shape[0]\n found = 0\n abstracts = []\n for r in range(nrows):\n if name in df.iloc[r][\"Name\"]:\n found += 1\n abstracts.append(\n df.iloc[r][\"Name\"]\n + \": \"\n + df.iloc[r][\"Abstract\"]\n + \". For more info, visit this link: \"\n + \"https://archive.ics.uci.edu/ml/datasets/\"\n + df.iloc[r][\"Identifier string\"]\n )\n if found == 0:\n print(\"Could not find your search term.\")\n return None\n else:\n print(\n f\"Total {found} instances found including partial match of the search term. Here they are...\\n\"\n )\n for a in abstracts:\n print(a)\n print(\"=\" * 100)\n\n\n# =============================================\n# Function to print all dataset descriptions\n# =============================================\ndef describe_all_dataset(msg_flag=False):\n \"\"\"\n Calls the build_dictionary function and prints description of all datasets from that.\n \"\"\"\n\n dict1 = build_dataset_dictionary(msg_flag=msg_flag)\n\n for k, v in dict1.items():\n print(f\"{k}: {v[0]}\")\n print(\"=\" * 100)\n\n\n# =======================================\n# Function to print all dataset names\n# =======================================\ndef print_all_datasets_names(msg_flag=False):\n \"\"\"\n Calls the build_dictionary function and prints names of all datasets from that.\n \"\"\"\n\n dict1 = build_dataset_dictionary(msg_flag=msg_flag)\n\n for key in dict1.keys():\n print(key)\n print(\"-\" * 100)\n\n\n# ==========================================\n# Function for extracting dataset page url\n# ==========================================\ndef extract_url_dataset(dataset, msg_flag=False):\n \"\"\"\n Given a dataset identifier this function extracts the URL for the page where the actual raw data resides.\n \"\"\"\n import urllib.request, urllib.parse, urllib.error\n from bs4 import BeautifulSoup\n import ssl\n import time\n\n # Ignore SSL certificate errors\n ctx = ssl.create_default_context()\n ctx.check_hostname = False\n ctx.verify_mode = ssl.CERT_NONE\n\n dataset_dict = {}\n baseurl = \"https://archive.ics.uci.edu/ml/datasets/\"\n url = baseurl + dataset\n\n try:\n uh = urllib.request.urlopen(url, context=ctx)\n html = uh.read().decode()\n soup = BeautifulSoup(html, \"html5lib\")\n if soup.text.find(\"does not appear to exist\") != -1:\n if msg_flag:\n print(f\"{dataset} not found\")\n return None\n else:\n for link in soup.find_all(\"a\"):\n if link.attrs[\"href\"].find(\"machine-learning-databases\") != -1:\n a = link.attrs[\"href\"]\n a = a[2:]\n dataurl = \"https://archive.ics.uci.edu/ml/\" + str(a)\n # print(dataurl)\n return str(dataurl)\n # dataurls.append(dataurl)\n\n # After finishing the for-loop with a-tags, the first dataurl is added to the dictionary\n # dataset_dict['dataurl']=dataurls[0]\n except:\n # print(\"Could not retrieve\")\n return None\n\n\n# ================================\n# File download helper function\n# ================================\ndef download_file(url, directory):\n \"\"\"\n Downloads a file from a given url into the given directory.\n \"\"\"\n import requests\n import os\n\n local_filename = directory + \"/\" + url.split(\"/\")[-1]\n # NOTE the stream=True parameter\n r = requests.get(url, stream=True)\n try:\n with open(local_filename, \"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 except:\n print(\"Sorry could not write this particular file!\")\n # f.flush()\n\n\n# =====================================================\n# Function for downloading the data set from a page\n# =====================================================\ndef download_dataset_url(url, directory, msg_flag=False, download_flag=True):\n \"\"\"\n Download all the files from the links in the given url.\n msg_flag: Controls verbosity.\n download_flag: Default is True. If set to False, only creates the directories but does not initiate download (for testing purpose).\n \"\"\"\n\n import urllib.request, urllib.parse, urllib.error\n from bs4 import BeautifulSoup\n import ssl\n import os\n\n if url == \"URL not available\":\n return None\n\n cwd = os.getcwd()\n directory = directory.replace(\":\", \"-\")\n local_directory = cwd + \"\\\\\" + str(directory)\n if not os.path.exists(local_directory):\n try:\n os.makedirs(local_directory)\n except:\n print(f\"Cannot create directory: {directory}\")\n\n if download_flag:\n # Ignore SSL certificate errors\n ctx = ssl.create_default_context()\n ctx.check_hostname = False\n ctx.verify_mode = ssl.CERT_NONE\n\n uh = urllib.request.urlopen(url, context=ctx)\n html = uh.read().decode()\n soup = BeautifulSoup(html, \"html5lib\")\n\n links = []\n for link in soup.find_all(\"a\"):\n links.append(link.attrs[\"href\"])\n\n links_to_download = []\n\n if \"Index\" in links:\n idx = links.index(\"Index\")\n else:\n idx = len(links) - 2\n for i in range(idx + 1, len(links)):\n links_to_download.append(url + str(links[i]))\n\n for file_url in links_to_download:\n download_file(file_url, local_directory)\n\n if msg_flag:\n print(f\"Downloaded dataset from {url}\")\n\n\n# =================================================================================================\n# User API Function for downloading a given number of datasets and storing in a local directory\n# =================================================================================================\ndef download_datasets(num=10, local_database=None, msg_flag=True, download_flag=True):\n \"\"\"\n Downloads datasets and puts them in a local directory named after the dataset.\n By default downloads first 10 datasets only. User can choose the number of dataets to be downloaded.\n msg_flag: Controls verbosity.\n\tdownload_flag: Default is True. If set to False, only creates the directories but does not initiate download (for testing purpose).\n \"\"\"\n\n import pandas as pd\n\n if local_database != None:\n local_df_flag = True\n df = pd.read_csv(local_database, index_col=\"Dataset\")\n else:\n local_df_flag = False\n if msg_flag:\n print(\n \"Local database not supplied.\\nBuilding the master database by crawling the website...\"\n )\n df = build_full_dataframe(msg_flag=False)\n if msg_flag:\n print(\"Done!\")\n\n if num < 1:\n print(\"Invalid entry for the number of datasets.\")\n else:\n for i in range(num):\n if msg_flag:\n print(f\"Downloading dataset(s) for: {df['Name'][i]}\")\n download_dataset_url(\n df[\"Datapage URL\"][i],\n df[\"Name\"][i],\n msg_flag=False,\n download_flag=download_flag,\n )\n print(\"\\nFinished downloading.\")\n\n\n# ============================================================================\n# User API function to download dataset by searching a for particular name\n# ============================================================================\ndef download_dataset_name(name, local_database=None, msg_flag=True, download_flag=True):\n \"\"\"\n Downloads a particular dataset by searching the given name.\n local_database: Name of the database (CSV file) stored locally i.e. in the same directory, which contains information about all the datasets on UCI ML repo. \n msg_flag: Controls verbosity\n download_flag: Default is True. If set to False, only creates the directories but does not initiate download (for testing purpose)\n \"\"\"\n import pandas as pd\n\n if local_database != None:\n local_df_flag = True\n df = pd.read_csv(local_database, index_col=\"Dataset\")\n else:\n local_df_flag = False\n if msg_flag:\n print(\n \"Local database not supplied.\\nBuilding the master database by crawling the website...\"\n )\n df = build_full_dataframe(msg_flag=False)\n if msg_flag:\n print(\"Done!\")\n\n urls_to_download = {}\n\n for i in df.index.values:\n if name in i:\n urls_to_download[df.loc[i][\"Name\"]] = df.loc[i][\"Datapage URL\"]\n\n if len(urls_to_download) == 0:\n print(f'Serach term \"{name}\" not found in the database. Nothing downloaded!')\n else:\n if len(urls_to_download) > 1:\n print(\n f\"{len(urls_to_download)} instances of search term found including partial match. Downloading datasets for all...\\n\"\n )\n\n for u in urls_to_download:\n if msg_flag:\n print(f\"Downloading dataset(s) for: {u}\")\n download_dataset_url(\n urls_to_download[u],\n directory=u,\n msg_flag=False,\n download_flag=download_flag,\n )\n\n print(\"\\nFinished downloading.\")\n\n\n# =========================================================\n# Function to download all datasets in a given dataframe\n# =========================================================\ndef download_all_from_dataframe(df, msg_flag=False, download_flag=True):\n \"\"\"\n Downloads all datasets which appear in the given dataframe.\n Assumes that the datapage URL information is in the dataframe.\n msg_flag: Controls verbosity\n download_flag: Default is True. If set to False, only creates the directories but does not initiate download (for testing purpose)\n \"\"\"\n\n nrows = df.shape[0]\n if download_flag == False:\n print(\"Not downloading anything, just creating empty directories.\\n\")\n for r in range(nrows):\n if msg_flag:\n print(f\"Downloading the dataset: {df.iloc[r]['Name']}\")\n download_dataset_url(\n df.iloc[r][\"Datapage URL\"], df.iloc[r][\"Name\"], download_flag=download_flag\n )\n\n\n# =======================================================\n# User API Function to download datasets based on size\n# =======================================================\ndef download_datasets_size(\n size=\"Small\",\n local_database=None,\n local_table=None,\n msg_flag=False,\n download_flag=True,\n):\n \"\"\"\n Downloads all datasets which satisfy the 'size' criteria.\n size: Size of the dataset which user wants to download. Could be any of the following: 'Small', 'Medium', 'Large','Extra Large'.\n local_database: Name of the database (CSV file) stored locally i.e. in the same directory, which contains name and URL information about all the datasets on UCI ML repo.\n local_table: Name of the database (CSV file) stored locally i.e. in the same directory, which contains features information about all the datasets on UCI ML repo i.e. number of samples, type of machine learning task to be performed with the dataset. \n msg_flag: Controls verbosity\n download_flag: Default is True. If set to False, only creates the directories but does not initiate download (for testing purpose)\n \"\"\"\n import pandas as pd\n\n assert type(size) == str\n assert str(size) in [\"Small\", \"Medium\", \"Large\", \"Extra Large\"]\n\n if local_database != None:\n local_df_flag = True\n df_local = pd.read_csv(local_database, index_col=\"Dataset\")\n df = df_local\n else:\n local_df_flag = False\n print(\n \"Local database not supplied.\\nBuilding the master database by crawling the website...\"\n )\n df = build_full_dataframe(msg_flag=False)\n print(\"Master database build done!\")\n\n if local_table != None:\n local_table_flag = True\n table_local = pd.read_csv(local_table)\n df_clean = clean_dataset_table(table_local, msg_flag=msg_flag)\n else:\n local_table_flag = False\n print(\n \"Local table not supplied.\\nBuilding the master table by reading from the website...\"\n )\n df_table = read_dataset_table(msg_flag=msg_flag)\n df_clean = clean_dataset_table(df_table, msg_flag=msg_flag)\n\n df_merged = df_clean.merge(df, on=\"Name\")\n df_filter = df_merged[df_merged[\"Sample size\"] == str(size)]\n\n download_all_from_dataframe(\n df_filter, msg_flag=msg_flag, download_flag=download_flag\n )\n\n\n# ===========================================================================\n# User API Function to download datasets based on the machine learning task\n# ===========================================================================\ndef download_datasets_task(\n task=\"Classification\",\n local_database=None,\n local_table=None,\n msg_flag=False,\n download_flag=True,\n):\n \"\"\"\n Downloads all datasets which satisfy the size criteria.\n task: Machine learning task for which user wants to download the datasets. Could be any of the following: \n\t 'Classification', \n\t\t'Recommender Systems', \n\t\t'Regression', \n\t\t'Other/Unknown', \n\t\t'Clustering', \n\t\t'Causal Discovery'.\n\tlocal_database: Name of the database (CSV file) stored locally i.e. in the same directory, which contains name and URL information about all the datasets on UCI ML repo.\n\tlocal_table: Name of the database (CSV file) stored locally i.e. in the same directory, which contains features information about all the datasets on UCI ML repo i.e. number of samples, type of machine learning task to be performed with the dataset. \n\tmsg_flag: Controls verbosity\n download_flag: Default is True. If set to False, only creates the directories but does not initiate download (for testing purpose).\n \"\"\"\n import pandas as pd\n\n if local_database != None:\n local_df_flag = True\n df = pd.read_csv(local_database, index_col=\"Dataset\")\n else:\n local_df_flag = False\n print(\n \"Local database not supplied.\\nBuilding the master database by crawling the website...\"\n )\n df = build_full_dataframe(msg_flag=False)\n print(\"Master database build done!\")\n\n if local_table != None:\n local_table_flag = True\n df_clean = pd.read_csv(local_table)\n else:\n local_table_flag = False\n print(\n \"Local table not supplied.\\nBuilding the master table by reading from the website...\"\n )\n df_table = read_dataset_table(msg_flag=msg_flag)\n df_clean = clean_dataset_table(df_table, msg_flag=msg_flag)\n\n df_merged = df_clean.merge(df, on=\"Name\")\n df_filter = df_merged[df_merged[\"Default Task\"] == str(task)]\n\n download_all_from_dataframe(\n df_filter, msg_flag=msg_flag, download_flag=download_flag\n )\n"
] | [
[
"pandas.set_option",
"pandas.read_csv",
"pandas.DataFrame",
"pandas.read_html"
]
] |
Zilleplus/MachineLearning | [
"13e4fe996386d3f66b7866cc133ae9b26a6333d6"
] | [
"HML/chapter18/simpleNeuralNetworkPolicy.py"
] | [
"import gym\nimport numpy as np\nimport tensorflow as tf\nimport tensorflow.keras as keras\n\nenv = gym.make(\"CartPole-v1\")\n\nobs = env.reset()\n\nenv.render()\n\nn_inputs = 4 # 4 states in the obs [x, \\dot{x}, \\theta, \\dot{\\theta}]\nmodel = keras.models.Sequential([\n keras.layers.Dense(units=5, activation='elu', input_shape=[n_inputs]),\n keras.layers.Dense(units=1, activation='sigmoid'),\n])\n\n\ndef play_one_step(env, obs, model, loss_fn):\n with tf.GradientTape() as tape:\n # obs.shape = (4,), obs[np.newaxis] makes it (1, 4)\n left_proba = model(obs[np.newaxis])\n action = (tf.random.uniform(shape=[1, 1]) > left_proba)\n y_target = tf.constant([[1.]]) - tf.cast(action, tf.float32)\n # y_target =\n # -1 if action==False : first action in left_proba\n # 1 if action==True : second action in left_proba\n loss = tf.reduce_mean(loss_fn(y_target, left_proba))\n grads = tape.gradient(loss, model.trainable_variables)\n obs, reward, done, info = env.step(int(action[0, 0].numpy()))\n return obs, reward, done, grads\n\n\ndef play_multiple_episodes(env, n_episodes, n_max_steps, model, loss_fn):\n all_rewards = []\n all_grads = []\n for episodes in range(n_episodes):\n current_rewards = []\n current_grads = []\n obs = env.reset()\n # play out a game\n for step in range(n_max_steps):\n obs, reward, done, grads = play_one_step(env, obs, model, loss_fn)\n current_rewards.append(reward)\n current_grads.append(grads)\n if done:\n break\n # save all the gradients of the current game\n all_rewards.append(current_rewards)\n all_grads.append(current_grads)\n return all_rewards, all_grads\n\n\ndef discount_rewards(rewards, discount_factor):\n discounted = np.array(rewards)\n # range(begin, end, step) -> so loop from the back,\n # as the current reward depends on future rewards.\n for step in range(len(rewards)-2, -1, -1):\n discounted[step] += discounted[step+1]*discount_factor\n return discounted\n\n\ndef discount_and_normalize_rewards(all_rewards, discount_factor):\n all_discounted_rewards = [discount_rewards(rewards, discount_factor)\n for rewards in all_rewards]\n flat_rewards = np.concatenate(all_discounted_rewards)\n reward_mean = flat_rewards.mean()\n reward_std = flat_rewards.std()\n return [(discounted_rewards - reward_mean)/reward_std\n for discounted_rewards in all_discounted_rewards]\n\n\nn_iterations = 150\nn_episodes_per_update = 10\nn_max_steps = 200 # max number of steps taken per time you play\ndiscount_factor = 0.95\noptimizer = keras.optimizers.Adam(lr=0.01)\nloss_fn = keras.losses.binary_crossentropy\nfor iteration in range(n_iterations):\n all_rewards, all_grads = play_multiple_episodes(\n env, n_episodes_per_update, n_max_steps, model, loss_fn)\n all_final_rewards = discount_and_normalize_rewards(\n all_rewards, discount_factor)\n all_mean_grads = []\n for var_index in range(len(model.trainable_variables)):\n mean_grads = tf.reduce_mean(\n [final_reward*all_grads[episode_index][step][var_index]\n for episode_index, final_rewards in enumerate(all_final_rewards)\n for step, final_reward in enumerate(final_rewards)], axis=0)\n optimizer.apply_gradients(zip(all_mean_grads, model.trainable_variables))\n\n\nfor i in range(10):\n obs = env.reset()\n done = False\n for i in range(1000):\n p = model.predict(obs[np.newaxis])\n print(p)\n _ = env.render()\n if done:\n print(str(i))\n break\n if p <= 0.5:\n obs, reward, done, info = env.step(0)\n else:\n obs, reward, done, info = env.step(1)\n"
] | [
[
"tensorflow.constant",
"tensorflow.keras.layers.Dense",
"tensorflow.random.uniform",
"tensorflow.cast",
"numpy.concatenate",
"tensorflow.keras.optimizers.Adam",
"numpy.array",
"tensorflow.GradientTape"
]
] |
TejasAvinashShetty/krotov | [
"e2dd0fad2f07f41004d7beef53e8ebc75b0d6d9b"
] | [
"src/krotov/objectives.py"
] | [
"import sys\nimport copy\nfrom functools import partial\n\nimport qutip\nfrom qutip.solver import Result as QutipSolverResult\nimport numpy as np\n\nfrom .structural_conversions import (\n _nested_list_shallow_copy, extract_controls, extract_controls_mapping,\n plug_in_pulse_values, control_onto_interval, discretize)\n\n__all__ = [\n 'Objective', 'summarize_qobj', 'CtrlCounter', 'gate_objectives',\n 'ensemble_objectives']\n\n\nFIX_QUTIP_932 = True\n\"\"\"Workaround for `QuTiP issue 932`_.\n\nIf True, and only when running on macOS, in :meth:`Objective.mesolve`,\nreplace any array controls with an equivalent function. This results in a\nsignficant slowdown of the propagation, as it circumvents the use of Cython.\n\n.. _QuTiP issue 932: https://github.com/qutip/qutip/issues/932\n\"\"\"\n\n\ndef _adjoint(op):\n \"\"\"Calculate adjoint of an operator in QuTiP nested-list format.\n Controls are not modified.\"\"\"\n if isinstance(op, list):\n adjoint_op = []\n for item in op:\n if isinstance(item, list):\n assert len(item) == 2\n adjoint_op.append([item[0].dag(), item[1]])\n else:\n adjoint_op.append(item.dag())\n return adjoint_op\n elif op is None:\n return None\n else:\n return op.dag()\n\n\ndef CtrlCounter():\n \"\"\"Constructor for a counter of controls.\n\n Returns a callable that returns a unique integer (starting at 1) for every\n distinct control that is passed to it. This is intended for use with\n :func:`summarize_qobj`.\n\n Example:\n\n >>> ctrl_counter = CtrlCounter()\n >>> ctrl1 = np.zeros(10)\n >>> ctrl_counter(ctrl1)\n 1\n >>> ctrl2 = np.zeros(10)\n >>> assert ctrl2 is not ctrl1\n >>> ctrl_counter(ctrl2)\n 2\n >>> ctrl_counter(ctrl1)\n 1\n >>> ctrl3 = lambda t, args: 0.0\n >>> ctrl_counter(ctrl3)\n 3\n \"\"\"\n\n counter = 0\n registry = {}\n\n def ctrl_counter(ctrl):\n nonlocal counter\n if isinstance(ctrl, np.ndarray):\n ctrl = id(ctrl)\n if ctrl not in registry:\n counter += 1\n registry[ctrl] = counter\n return registry[ctrl]\n\n return ctrl_counter\n\n\n_CTRL_COUNTER = CtrlCounter() #: internal counter for controls\n\n\nclass Objective:\n \"\"\"A single objective for optimization with Krotov's method\n\n Args:\n initial_state (qutip.Qobj): value for :attr:`initial_state`\n H (qutip.Qobj or list): value for :attr:`H`\n target (qutip.Qobj or None): value for :attr:`target`\n c_ops (list or None): value for :attr:`c_ops`\n\n Attributes:\n H (qutip.Qobj or list): The (time-dependent) Hamiltonian,\n cf. :func:`qutip.mesolve.mesolve`. This includes the control\n fields.\n initial_state (qutip.Qobj): The initial state\n target: An object describing the \"target\" of the optimization, for the\n dynamics starting from :attr:`initial_state`. Usually, this will be\n the target state (the state into which :attr:`initial_state` should\n evolve). More generally, it can be an arbitrary object meeting the\n requirements of a specific `chi_constructor` function that will be\n passed to :func:`.optimize_pulses`.\n c_ops (list or None): List of collapse operators,\n cf. :func:`~qutip.mesolve.mesolve`.\n\n Raises:\n ValueError: If any arguments have an invalid type\n \"\"\"\n\n def __init__(self, *, initial_state, H, target, c_ops=None):\n if c_ops is None:\n c_ops = []\n if not isinstance(H, (qutip.Qobj, list)):\n raise ValueError(\n \"Invalid H, must be a Qobj, or a nested list, not %s\"\n % H.__class__.__name__\n )\n self.H = H\n if not isinstance(initial_state, qutip.Qobj):\n raise ValueError(\n \"Invalid initial_state: must be Qobj, not %s\"\n % initial_state.__class__.__name__\n )\n self.initial_state = initial_state\n self.target = target\n if not isinstance(c_ops, list):\n raise ValueError(\n \"Invalid c_ops: must be a list, not %s\"\n % c_ops.__class__.__name__\n )\n self.c_ops = c_ops\n\n def __copy__(self):\n # When we use copy.copy(objective), we want a\n # semi-deep copy where nested lists in the Hamiltonian and the c_ops\n # are re-created (copy by value), but non-list elements are copied by\n # reference.\n return Objective(\n H=_nested_list_shallow_copy(self.H),\n initial_state=self.initial_state,\n target=self.target,\n c_ops=[_nested_list_shallow_copy(c) for c in self.c_ops],\n )\n\n def __eq__(self, other):\n if other.__class__ is self.__class__:\n return (self.H, self.initial_state, self.target, self.c_ops) == (\n other.H,\n other.initial_state,\n other.target,\n other.c_ops,\n )\n else:\n return NotImplemented\n\n def __ne__(self, other): # pragma: nocover\n result = self.__eq__(other)\n if result is NotImplemented:\n return NotImplemented\n else:\n return not result\n\n @property\n def adjoint(self):\n \"\"\"The :class:`Objective` containing the adjoint of all components.\n\n This does not affect the controls in :attr:`H`: these are\n assumed to be real-valued. Also, :attr:`.Objective.target` will be left\n unchanged if it is not a :class:`qutip.Qobj`.\n \"\"\"\n return Objective(\n H=_adjoint(self.H),\n initial_state=_adjoint(self.initial_state),\n target=(\n _adjoint(self.target)\n if isinstance(self.target, qutip.Qobj)\n else self.target\n ),\n c_ops=[_adjoint(op) for op in self.c_ops],\n )\n\n def mesolve(self, tlist, rho0=None, e_ops=None, **kwargs):\n \"\"\"Run :func:`qutip.mesolve.mesolve` on the system of the objective\n\n Solve the dynamics for the :attr:`H` and :attr:`c_ops` of the\n objective. If `rho0` is not given, the :attr:`initial_state` will be\n propagated. All other arguments will be passed to\n :func:`qutip.mesolve.mesolve`.\n\n Returns:\n qutip.solver.Result: Result of the propagation, see\n :func:`qutip.mesolve.mesolve` for details.\n \"\"\"\n if rho0 is None:\n rho0 = self.initial_state\n if e_ops is None:\n e_ops = []\n H = self.H\n c_ops = self.c_ops\n if FIX_QUTIP_932 and sys.platform == \"darwin\": # pragma: no cover\n # \"darwin\" = macOS; the \"pragma\" excludes from coverage analysis\n controls = extract_controls([self])\n pulses_mapping = extract_controls_mapping([self], controls)\n mapping = pulses_mapping[0] # \"first objective\" (dummy structure)\n H = _plug_in_array_controls_as_func(H, controls, mapping[0], tlist)\n c_ops = [\n _plug_in_array_controls_as_func(\n c_op, controls, mapping[ic + 1], tlist\n )\n for (ic, c_op) in enumerate(self.c_ops)\n ]\n return qutip.mesolve(\n H=H, rho0=rho0, tlist=tlist, c_ops=c_ops, e_ops=e_ops, **kwargs\n )\n\n def propagate(self, tlist, *, propagator, rho0=None, e_ops=None):\n \"\"\"Propagates the system of the objective over the entire time grid\n\n Solve the dynamics for the `H` and `c_ops` of the objective. If `rho0`\n is not given, the `initial_state` will be propagated. This is similar\n to the :meth:`mesolve` method, but instead of using\n :func:`qutip.mesolve.mesolve`, the `propagate` function is used to go\n between points on the time grid. This function is the same as what is\n passed to :func:`.optimize_pulses`. The crucial difference between this\n and :meth:`mesolve` is in the time discretization convention. While\n :meth:`mesolve` uses piecewise-constant controls centered around the\n values in `tlist` (the control field switches in the middle between two\n points in `tlist`), :meth:`propagate` uses piecewise-constant controls\n on the intervals of `tlist` (the control field switches on the points\n in `tlist`)\n\n Comparing the result of :meth:`mesolve` and :meth:`propagate` allows to\n estimate the \"time discretization error\". If the error is significant,\n a shorter time step shoud be used.\n\n Returns:\n qutip.solver.Result: Result of the propagation, using the same\n structure as :meth:`mesolve`.\n \"\"\"\n if e_ops is None:\n e_ops = []\n result = QutipSolverResult()\n result.solver = propagator.__name__\n result.times = copy.copy(tlist)\n result.states = []\n result.expect = []\n result.num_expect = len(e_ops)\n result.num_collapse = len(self.c_ops)\n for _ in e_ops:\n result.expect.append([])\n state = rho0\n if state is None:\n state = self.initial_state\n if len(e_ops) == 0:\n result.states.append(state)\n else:\n for (i, oper) in enumerate(e_ops):\n result.expect[i].append(qutip.expect(oper, state))\n controls = extract_controls([self])\n pulses_mapping = extract_controls_mapping([self], controls)\n mapping = pulses_mapping[0] # \"first objective\" (dummy structure)\n pulses = [ # defined on the tlist intervals\n control_onto_interval(discretize(control, tlist))\n for control in controls\n ]\n for time_index in range(len(tlist) - 1): # index over intervals\n H = plug_in_pulse_values(self.H, pulses, mapping[0], time_index)\n c_ops = [\n plug_in_pulse_values(c_op, pulses, mapping[ic + 1], time_index)\n for (ic, c_op) in enumerate(self.c_ops)\n ]\n dt = tlist[time_index + 1] - tlist[time_index]\n state = propagator(H, state, dt, c_ops)\n if len(e_ops) == 0:\n result.states.append(state)\n else:\n for (i, oper) in enumerate(e_ops):\n result.expect[i].append(qutip.expect(oper, state))\n return result\n\n def summarize(self, ctrl_counter=None):\n \"\"\"Return a one-line summary of the objective as a string\n\n Example:\n\n >>> from qutip import ket, tensor, sigmaz, sigmax, sigmap, identity\n >>> u1 = lambda t, args: 1.0\n >>> u2 = lambda t, args: 1.0\n >>> a1 = np.random.random(100) + 1j*np.random.random(100)\n >>> a2 = np.random.random(100) + 1j*np.random.random(100)\n >>> H = [\n ... tensor(sigmaz(), identity(2)) +\n ... tensor(identity(2), sigmaz()),\n ... [tensor(sigmax(), identity(2)), u1],\n ... [tensor(identity(2), sigmax()), u2]]\n >>> C1 = [tensor(identity(2), sigmap()), a1]\n >>> C2 = [tensor(sigmap(), identity(2)), a2]\n >>> ket00 = ket((0,0))\n >>> ket11 = ket((1,1))\n >>> obj = Objective(\n ... initial_state=ket00,\n ... target=ket11,\n ... H=H\n ... )\n >>> obj.summarize()\n '|(2⊗2)⟩ - {[Herm[2⊗2,2⊗2], [Herm[2⊗2,2⊗2], u1(t)], [Herm[2⊗2,2⊗2], u2(t)]]} - |(2⊗2)⟩'\n >>> obj = Objective(\n ... initial_state=ket00,\n ... target=ket11,\n ... H=H,\n ... c_ops=[C1, C2]\n ... )\n >>> obj.summarize()\n '|(2⊗2)⟩ - {H:[Herm[2⊗2,2⊗2], [Herm[2⊗2,2⊗2], u1(t)], [Herm[2⊗2,2⊗2], u2(t)]], c_ops:([NonHerm[2⊗2,2⊗2], u3[complex128]],[NonHerm[2⊗2,2⊗2], u4[complex128]])} - |(2⊗2)⟩'\n \"\"\"\n if ctrl_counter is None:\n ctrl_counter = _CTRL_COUNTER\n if len(self.c_ops) == 0:\n res = \"%s - {%s}\" % (\n summarize_qobj(self.initial_state, ctrl_counter),\n summarize_qobj(self.H, ctrl_counter),\n )\n else:\n res = \"%s - {H:%s, c_ops:(%s)}\" % (\n summarize_qobj(self.initial_state, ctrl_counter),\n summarize_qobj(self.H, ctrl_counter),\n \",\".join(\n [summarize_qobj(c_op, ctrl_counter) for c_op in self.c_ops]\n ),\n )\n if self.target is not None:\n if isinstance(self.target, qutip.Qobj):\n res += \" - %s\" % (summarize_qobj(self.target, ctrl_counter))\n else:\n res += \" - %r\" % self.target\n return res\n\n def __str__(self):\n return self.summarize()\n\n def __repr__(self):\n return \"%s[%s]\" % (self.__class__.__name__, self.summarize())\n\n def __getstate__(self):\n \"\"\"Return data for the pickle serialization of an objective.\n\n This may not preserve time-dependent controls, and is only to enable\n the serialization of :class:`.Result` objects.\n \"\"\"\n state = copy.copy(self.__dict__)\n # Remove the unpicklable entries.\n state['H'] = _remove_functions_from_nested_list(state['H'])\n state['c_ops'] = _remove_functions_from_nested_list(state['c_ops'])\n return state\n\n\nclass _ControlPlaceholder():\n \"\"\"Placeholder for a control function, for pickling\"\"\"\n\n def __init__(self, id):\n self.id = id\n\n def __str__(self):\n return \"u%s\" % self.id\n\n def __repr__(self):\n return \"%s(%s)\" % (self.__class__.__name__, self.id)\n\n def __eq__(self, other):\n return (self.__class__ == other.__class__) and (self.id == other.id)\n\n\ndef _remove_functions_from_nested_list(lst):\n if isinstance(lst, list):\n return [_remove_functions_from_nested_list(v) for v in lst]\n else:\n if callable(lst) and not isinstance(lst, qutip.Qobj):\n return _ControlPlaceholder(id(lst))\n else:\n return lst\n\n\ndef _plug_in_array_controls_as_func(H, controls, mapping, tlist):\n \"\"\"Convert array controls to piece-wise constant functions\n\n It uses the piece-wise constant convention of mesolve: pulses switch in the\n middle between to `tlist` points.\n\n This is a workaround for https://github.com/qutip/qutip/issues/932\n \"\"\"\n H = _nested_list_shallow_copy(H)\n T = tlist[-1]\n nt = len(tlist)\n for (control, control_mapping) in zip(controls, mapping):\n if isinstance(control, np.ndarray):\n for i in control_mapping:\n # Use the same formula that QuTiP normally passes to Cython for\n # compilation\n H[i][1] = partial(_array_as_func, array=control, T=T, nt=nt)\n else:\n continue\n return H\n\n\ndef _array_as_func(t, args, array, T, nt):\n return (\n 0 if (t > float(T)) else\n array[int(round(float(nt-1) * (t/float(T))))])\n\n\ndef summarize_qobj(obj, ctrl_counter=None):\n \"\"\"Summarize a quantum object\n\n A counter created by :func:`CtrlCounter` may be passed to distinguish\n control fields.\n\n Example:\n\n >>> ket = qutip.ket([1, 0, 1])\n >>> summarize_qobj(ket)\n '|(2⊗2⊗2)⟩'\n >>> bra = ket.dag()\n >>> summarize_qobj(bra)\n '⟨(2⊗2⊗2)|'\n >>> rho = ket * bra\n >>> summarize_qobj(rho)\n 'Herm[2⊗2⊗2,2⊗2⊗2]'\n >>> a = qutip.create(10)\n >>> summarize_qobj(a)\n 'NonHerm[10,10]'\n >>> S = qutip.to_super(a)\n >>> summarize_qobj(S)\n '[[10,10],[10,10]]'\n \"\"\"\n if ctrl_counter is None:\n ctrl_counter = _CTRL_COUNTER\n if isinstance(obj, list):\n return _summarize_qobj_nested_list(obj, ctrl_counter)\n elif callable(obj) and not isinstance(obj, qutip.Qobj):\n return 'u%d(t)' % ctrl_counter(obj)\n elif isinstance(obj, np.ndarray):\n return 'u%d[%s]' % (ctrl_counter(obj), obj.dtype.name)\n elif isinstance(obj, _ControlPlaceholder):\n return str(obj)\n elif not isinstance(obj, qutip.Qobj):\n raise TypeError(\"obj must be a Qobj, not %s\" % obj.__class__.__name__)\n if obj.type == 'ket':\n dims = \"⊗\".join([\"%d\" % d for d in obj.dims[0]])\n return '|(%s)⟩' % dims\n elif obj.type == 'bra':\n dims = \"⊗\".join([\"%d\" % d for d in obj.dims[1]])\n return '⟨(%s)|' % dims\n elif obj.type == 'oper':\n dim1 = \"⊗\".join([\"%d\" % d for d in obj.dims[0]])\n dim2 = \"⊗\".join([\"%d\" % d for d in obj.dims[1]])\n if obj.isherm:\n return 'Herm[%s,%s]' % (dim1, dim2)\n else:\n return 'NonHerm[%s,%s]' % (dim1, dim2)\n elif obj.type == 'super':\n dims = []\n for dim in obj.dims:\n dim1 = \"⊗\".join([\"%d\" % d for d in dim[0]])\n dim2 = \"⊗\".join([\"%d\" % d for d in dim[1]])\n dims.append('[%s,%s]' % (dim1, dim2))\n return '[' + \",\".join(dims) + ']'\n else:\n raise NotImplementedError(\"Unknown qobj type: %s\" % obj.type)\n\n\ndef _summarize_qobj_nested_list(lst, ctrl_counter):\n \"\"\"Summarize a nested-list time-dependent quantum object\"\"\"\n return (\n '[' +\n \", \".join([summarize_qobj(obj, ctrl_counter) for obj in lst]) +\n ']')\n\n\ndef gate_objectives(basis_states, gate, H, c_ops=None, local_invariants=False):\n r\"\"\"Construct a list of objectives for optimizing towards a quantum gate\n\n Args:\n basis_states (list[qutip.Qobj]): A list of $n$ canonical basis states\n gate: The gate to optimize for, as a $n \\times n$ matrix-like object\n (must have a `shape` attribute, and be indexable by two indices).\n Alternatively, `gate` may be the string 'perfect_entangler' or\n 'PE', to indicate the optimization for an arbitrary two-qubit\n perfect entangler.\n H (list or qutip.Qobj): The Hamiltonian for the time evolution\n c_ops (list or None): A list of collapse (Lindblad) operators, or None\n for unitary dynamics\n local_invariants (bool): If True, initialize the objectives for an\n optimization towards a two-qubit gate that is \"locally equivalent\"\n to `gate`. That is, the result of the optimization should implement\n `gate` up to single-qubit operations.\n\n Returns:\n list[Objective]: The objectives that define the optimization towards\n the gate. For a \"normal\" gate with a basis in Hilbert space, the\n objectives will have the `basis_states` as each\n :attr:`~.Objective.initial_state` and the result of applying `gate`\n to the `basis_states` as each :attr:`~.Objective.target`.\n\n For an optimization towards a perfect-entangler, or for the\n `local_invariants` of the given `gate`, each\n :attr:`~.Objective.initial_state` will be the Bell basis state\n described in \"Theorem 1\" in Y. Makhlin, Quantum Inf. Process. 1, 243\n (2002), derived from the canonical `basis_states`. The\n :attr:`~.Objective.target` will be the string 'PE' for a\n perfect-entanglers optimization, and `gate` for the local-invariants\n optimization.\n\n Raises:\n ValueError: If `gate`, `basis_states`, and `local_invariants` are\n incompatible, or `gate` is invalid (not a recognized string)\n\n .. Note::\n\n The dimension of the `basis_states` is not required to be the dimension\n of the `gate`; the `basis_states` may define a logical subspace in a\n larger Hilbert space.\n\n Examples:\n\n * A single-qubit gate::\n\n >>> from qutip import ket, tensor, sigmaz, sigmax, sigmay, identity\n >>> basis = [ket([0]), ket([1])]\n >>> gate = sigmay()\n >>> gate\n Quantum object: dims = [[2], [2]], shape = (2, 2), type = oper, isherm = True\n Qobj data =\n [[0.+0.j 0.-1.j]\n [0.+1.j 0.+0.j]]\n >>> H = [sigmaz(),[sigmax(), lambda t, args: 1.0]]\n >>> objectives = gate_objectives(basis, gate, H)\n >>> assert objectives == [\n ... Objective(\n ... initial_state=basis[0],\n ... target=(1j * basis[1]),\n ... H=H\n ... ),\n ... Objective(\n ... initial_state=basis[1],\n ... target=(-1j * basis[0]),\n ... H=H\n ... )\n ... ]\n\n * An arbitrary two-qubit perfect entangler:\n\n >>> basis = [ket(n) for n in [(0, 0), (0, 1), (1, 0), (1, 1)]]\n >>> H = [\n ... tensor(sigmaz(), identity(2)) +\n ... tensor(identity(2), sigmaz()),\n ... [tensor(sigmax(), identity(2)), lambda t, args: 1.0],\n ... [tensor(identity(2), sigmax()), lambda t, args: 1.0]]\n >>> objectives = gate_objectives(basis, 'PE', H)\n >>> from weylchamber import bell_basis\n >>> for i in range(4):\n ... assert objectives[i] == Objective(\n ... initial_state=bell_basis(basis)[i],\n ... target='PE',\n ... H=H\n ... )\n\n * A two-qubit gate, up to single-qubit operation (\"local invariants\"):\n\n >>> objectives = gate_objectives(\n ... basis, qutip.gates.cnot(), H, local_invariants=True\n ... )\n >>> for i in range(4):\n ... assert objectives[i] == Objective(\n ... initial_state=bell_basis(basis)[i],\n ... target=qutip.gates.cnot(),\n ... H=H\n ... )\n \"\"\"\n if isinstance(gate, str):\n if gate.lower().replace(' ', '_') in ['pe', 'perfect_entangler']:\n return _gate_objectives_li_pe(basis_states, 'PE', H, c_ops)\n else:\n raise ValueError(\n \"gate must be either a square matrix, or one of the strings \"\n \"'PE' or 'perfect_entangler', not '\" + gate + \"'\"\n )\n elif local_invariants:\n if not gate.shape == (4, 4):\n raise ValueError(\n \"If local_invariants is True, gate must be a 4 × 4 matrix, \"\n \"not \" + str(gate.shape)\n )\n return _gate_objectives_li_pe(basis_states, gate, H, c_ops)\n\n # \"Normal\" gate:\n\n if not gate.shape[0] == gate.shape[1] == len(basis_states):\n raise ValueError(\n \"gate must be a matrix of the same dimension as the number of \"\n \"basis states\"\n )\n target_states = [\n sum([gate[i, j] * basis_states[i] for i in range(gate.shape[0])])\n for j in range(gate.shape[1])\n ]\n return [\n Objective(\n initial_state=initial_state,\n target=target_state,\n H=H,\n c_ops=c_ops,\n )\n for (initial_state, target_state) in zip(basis_states, target_states)\n ]\n\n\ndef _gate_objectives_li_pe(basis_states, gate, H, c_ops):\n \"\"\"Objectives for two-qubit local-invariants or perfect-entangler\n optimizaton\"\"\"\n if len(basis_states) != 4:\n raise ValueError(\n \"Optimization towards a two-qubit gate requires 4 basis_states\"\n )\n # Bell states as in \"Theorem 1\" in\n # Y. Makhlin, Quantum Inf. Process. 1, 243 (2002)\n psi1 = (basis_states[0] + basis_states[3]) / np.sqrt(2)\n psi2 = (1j * basis_states[1] + 1j * basis_states[2]) / np.sqrt(2)\n psi3 = (basis_states[1] - basis_states[2]) / np.sqrt(2)\n psi4 = (1j * basis_states[0] - 1j * basis_states[3]) / np.sqrt(2)\n return [\n Objective(initial_state=psi, target=gate, H=H, c_ops=c_ops)\n for psi in [psi1, psi2, psi3, psi4]\n ]\n\n\ndef ensemble_objectives(objectives, Hs):\n \"\"\"Extend `objectives` for an \"ensemble optimization\"\n\n This creates a list of objectives for an optimization for robustness with\n respect to variations in some parameter of the Hamiltonian. The trick is to\n simply optimize over the average of multiple copies of the system\n (the `Hs`) sampling that variation. See\n Goerz, Halperin, Aytac, Koch, Whaley. Phys. Rev. A 90, 032329 (2014)\n for details.\n\n Args:\n objectives (list[Objective]): The $n$ original objectives\n Hs (list): List of $m$ variations of the original\n Hamiltonian/Liouvillian\n\n Returns:\n list[Objective]: List of $n (m+1)$ new objectives that consists of the\n original objectives, plus one copy of the original objectives per\n element of `Hs` where the `H` attribute of each objectives is\n replaced by that element.\n \"\"\"\n new_objectives = copy.copy(objectives)\n for H in Hs:\n for obj in objectives:\n new_objectives.append(\n Objective(\n H=H,\n initial_state=obj.initial_state,\n target=obj.target,\n c_ops=obj.c_ops,\n )\n )\n return new_objectives\n"
] | [
[
"numpy.sqrt"
]
] |
ZHAOZHIHAO/ClusterRouting | [
"ce0a7cbe73656956bcbfbfab53c023c1fb2bd5c6"
] | [
"src/utils.py"
] | [
"from __future__ import print_function\r\nimport numpy as np\r\nimport torch\r\nimport torch.nn.functional as F\r\nfrom torch.utils.data import DataLoader, Dataset\r\n\r\n\r\ndef train(args, model, device, train_loader, optimizer, epoch):\r\n model.train()\r\n correct = 0\r\n total_loss = 0\r\n for batch_idx, (data, target) in enumerate(train_loader):\r\n data, target = data.to(device), target.to(device)\r\n optimizer.zero_grad()\r\n output = model(data)\r\n pred = output.argmax(dim=1, keepdim=True) # get the index of the max log-probability\r\n correct += pred.eq(target.view_as(pred)).sum().item()\r\n loss = F.cross_entropy(output, target)\r\n total_loss += loss\r\n loss.backward()\r\n optimizer.step()\r\n if batch_idx % args.log_interval == 0:\r\n print('Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}'.format(\r\n epoch, batch_idx * len(data), len(train_loader.dataset),\r\n 100. * batch_idx / len(train_loader), loss.item()))\r\n acc = 100. * correct / len(train_loader.dataset)\r\n total_loss = total_loss / batch_idx\r\n print(\"Training accuracy :%0.2f\", acc)\r\n return acc, total_loss.item()\r\n\r\n\r\ndef test(model, device, test_loader):\r\n model.eval()\r\n test_loss = 0\r\n correct = 0\r\n with torch.no_grad():\r\n for data, target in test_loader:\r\n data, target = data.to(device), target.to(device)\r\n output = model(data)\r\n test_loss += F.cross_entropy(output, target, reduction='sum').item() # sum up batch loss\r\n pred = output.argmax(dim=1, keepdim=True) # get the index of the max log-probability\r\n correct += pred.eq(target.view_as(pred)).sum().item()\r\n\r\n test_loss /= len(test_loader.dataset)\r\n\r\n print('Test set: Average loss: {:.4f}, Accuracy: {}/{} ({:.2f}%)'.format(\r\n test_loss, correct, len(test_loader.dataset),\r\n 100. * correct / len(test_loader.dataset)))\r\n acc = 100. * correct / len(test_loader.dataset)\r\n return acc, test_loss\r\n\r\n\r\ndef random_split(data, labels, n_classes, n_samples_per_class):\r\n \"\"\" Creates a class-balanced validation set from a training set. \"\"\"\r\n train_X, train_Y, valid_X, valid_Y = [],[],[],[]\r\n\r\n for c in range(n_classes):\r\n # get indices of all class 'c' samples\r\n c_idx = (np.array(labels) == c).nonzero()[0]\r\n # get n unique class 'c' samples\r\n valid_samples = np.random.choice(c_idx, n_samples_per_class[c], replace=False)\r\n # get remaining samples of class 'c'\r\n train_samples = np.setdiff1d(c_idx, valid_samples)\r\n # assign class c samples to validation, and remaining to training\r\n train_X.extend(data[train_samples])\r\n train_Y.extend(labels[train_samples])\r\n valid_X.extend(data[valid_samples])\r\n valid_Y.extend(labels[valid_samples])\r\n\r\n if isinstance(data, torch.Tensor):\r\n # torch.stack transforms list of tensors to tensor\r\n return {'valid_mode_train': torch.stack(train_X), 'valid_mode_valid': torch.stack(valid_X)}, \\\r\n {'valid_mode_train': torch.stack(train_Y), 'valid_mode_valid': torch.stack(valid_Y)}\r\n else:\r\n # transforms list of np arrays to tensor\r\n return {'valid_mode_train': torch.from_numpy(np.stack(train_X)), \\\r\n 'valid_mode_valid': torch.from_numpy(np.stack(valid_X))}, \\\r\n {'valid_mode_train': torch.from_numpy(np.stack(train_Y)), \\\r\n 'valid_mode_valid': torch.from_numpy(np.stack(valid_Y))}\r\n\r\n\r\nclass CustomDataset(Dataset):\r\n \"\"\" Creates a custom pytorch dataset, mainly\r\n used for creating validation set splits. \"\"\"\r\n def __init__(self, data, labels, transform=None):\r\n # shuffle the dataset\r\n idx = np.random.permutation(data.shape[0])\r\n if isinstance(data, torch.Tensor):\r\n data = data.numpy() # to work with `ToPILImage'\r\n self.data = data[idx]\r\n self.labels = labels[idx]\r\n self.transform = transform\r\n\r\n def __len__(self):\r\n return self.data.shape[0]\r\n\r\n def __getitem__(self, idx):\r\n if self.transform:\r\n image = self.transform(self.data[idx])\r\n return image, self.labels[idx]\r\n"
] | [
[
"numpy.random.choice",
"torch.nn.functional.cross_entropy",
"numpy.setdiff1d",
"numpy.stack",
"numpy.random.permutation",
"torch.no_grad",
"torch.stack",
"numpy.array"
]
] |
emilienDespres/scikit-decide | [
"2a3dd2d93e5e6d07984e1bc02b6e969261aeefbc"
] | [
"skdecide/discrete_optimization/rcpsp_multiskill/solvers/calendar_solver_iterative.py"
] | [
"# Copyright (c) AIRBUS and its affiliates.\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nfrom __future__ import annotations\n\nimport random\nimport time\nfrom datetime import timedelta\nfrom typing import Any, Iterable, Optional, Union\n\nimport networkx as nx\nimport numpy as np\nfrom minizinc import Status\n\nfrom skdecide.discrete_optimization.generic_tools.cp_tools import (\n CPSolverName,\n ParametersCP,\n)\nfrom skdecide.discrete_optimization.generic_tools.do_problem import (\n ModeOptim,\n get_default_objective_setup,\n)\nfrom skdecide.discrete_optimization.generic_tools.lns_cp import (\n ConstraintHandler,\n SolverDO,\n)\nfrom skdecide.discrete_optimization.generic_tools.lns_mip import PostProcessSolution\nfrom skdecide.discrete_optimization.generic_tools.result_storage.result_storage import (\n ResultStorage,\n)\nfrom skdecide.discrete_optimization.rcpsp_multiskill.rcpsp_multiskill import (\n MS_RCPSPModel,\n MS_RCPSPSolution,\n schedule_solution_to_variant,\n)\nfrom skdecide.discrete_optimization.rcpsp_multiskill.solvers.cp_solvers import (\n CP_MS_MRCPSP_MZN,\n PartialSolution,\n)\nfrom skdecide.discrete_optimization.rcpsp_multiskill.solvers.ms_rcpsp_cp_lns_solver import (\n OptionNeighbor,\n build_neighbor_operator,\n)\nfrom skdecide.discrete_optimization.rcpsp_multiskill.solvers.ms_rcpsp_lp_lns_solver import (\n InitialMethodRCPSP,\n InitialSolutionMS_RCPSP,\n)\n\n\ndef get_ressource_breaks(problem_calendar: MS_RCPSPModel, solution: MS_RCPSPSolution):\n ressources = problem_calendar.resources_availability\n ressource_arrays = {}\n ressource_arrays_usage = {}\n employees_arrays = {}\n employees_arrays_usage = {}\n for r in ressources:\n ressource_arrays[r] = np.zeros(\n (len(problem_calendar.resources_availability[r]))\n )\n ressource_arrays_usage[r] = np.zeros(\n (len(problem_calendar.resources_availability[r]), len(solution.schedule))\n )\n for emp in problem_calendar.employees:\n employees_arrays[emp] = np.zeros(\n (len(problem_calendar.employees[emp].calendar_employee))\n )\n employees_arrays_usage[emp] = np.zeros(\n (\n len(problem_calendar.employees[emp].calendar_employee),\n len(solution.schedule),\n )\n )\n sorted_keys_schedule = sorted(solution.schedule.keys())\n for ji in range(len(sorted_keys_schedule)):\n j = sorted_keys_schedule[ji]\n for r in problem_calendar.mode_details[j][1]:\n if r == \"duration\":\n continue\n if r is None:\n continue\n if r == \"None\":\n continue\n if r not in ressource_arrays_usage:\n continue\n if problem_calendar.mode_details[j][1][r] == 0:\n continue\n if solution.schedule[j][\"end_time\"] == solution.schedule[j][\"start_time\"]:\n continue\n ressource_arrays_usage[r][\n int(solution.schedule[j][\"start_time\"]) : int(\n solution.schedule[j][\"end_time\"]\n ),\n ji,\n ] = 1\n ressource_arrays[r][\n int(solution.schedule[j][\"start_time\"]) : int(\n solution.schedule[j][\"end_time\"]\n )\n ] += problem_calendar.mode_details[j][1][r]\n\n for ji in range(len(sorted_keys_schedule)):\n j = sorted_keys_schedule[ji]\n emp_usage = solution.employee_usage.get(j, {})\n for emp in emp_usage:\n if len(emp_usage[emp]) > 0:\n employees_arrays_usage[emp][\n int(solution.schedule[j][\"start_time\"]) : int(\n solution.schedule[j][\"end_time\"]\n ),\n ji,\n ] = 1\n employees_arrays[emp][\n int(solution.schedule[j][\"start_time\"]) : int(\n solution.schedule[j][\"end_time\"]\n )\n ] += 1\n index_ressource = {}\n task_concerned = {}\n constraints = {}\n for r in ressource_arrays:\n index = np.argwhere(\n ressource_arrays[r] > problem_calendar.resources_availability[r]\n )\n index_ressource[r] = index\n task_concerned[r] = [\n j\n for j in range(ressource_arrays_usage[r].shape[1])\n if any(\n ressource_arrays_usage[r][ind[0], j] == 1\n for ind in index\n if problem_calendar.resources_availability[r][ind[0]] == 0\n )\n ]\n task_concerned[r] = [sorted_keys_schedule[rr] for rr in task_concerned[r]]\n constraints[r] = {}\n for t in task_concerned[r]:\n current_start = solution.schedule[t][\"start_time\"]\n first_possible_start_future = next(\n (\n st\n for st in range(\n current_start, len(problem_calendar.resources_availability[r])\n )\n if problem_calendar.resources_availability[r][st]\n >= problem_calendar.mode_details[t][1][r]\n ),\n None,\n )\n first_possible_start_before = next(\n (\n st\n for st in range(current_start, -1, -1)\n if problem_calendar.resources_availability[r][st]\n >= problem_calendar.mode_details[t][1][r]\n ),\n None,\n )\n # if first_possible_start_before is not None:\n # first_possible_start_before = \\\n # max(0,\n # first_possible_start_before-problem_calendar.mode_details[t][1][\"duration\"]+1)\n constraints[r][t] = (\n first_possible_start_before,\n first_possible_start_future,\n )\n\n index_employee = {}\n # task_concerned = {}\n constraints_employee = {}\n for emp in employees_arrays:\n index = np.argwhere(\n employees_arrays[emp]\n > 1 * problem_calendar.employees[emp].calendar_employee\n )\n\n # index_ressource[emp] = index\n task_concerned[emp] = [\n j\n for j in range(employees_arrays_usage[emp].shape[1])\n if any(\n employees_arrays_usage[emp][ind[0], j] == 1\n for ind in index\n if not problem_calendar.employees[emp].calendar_employee[ind[0]]\n )\n ]\n task_concerned[emp] = [sorted_keys_schedule[rr] for rr in task_concerned[emp]]\n constraints_employee[emp] = {}\n for t in task_concerned[emp]:\n current_start = solution.schedule[t][\"start_time\"]\n first_possible_start_future = next(\n (\n st\n for st in range(\n current_start,\n len(problem_calendar.employees[emp].calendar_employee),\n )\n if problem_calendar.employees[emp].calendar_employee[st]\n ),\n None,\n )\n first_possible_start_before = next(\n (\n st\n for st in range(current_start, -1, -1)\n if problem_calendar.employees[emp].calendar_employee[st]\n ),\n None,\n )\n\n constraints_employee[emp] = (\n first_possible_start_before,\n first_possible_start_future,\n )\n return index_ressource, constraints, constraints_employee\n\n\nclass PostProcessSolutionNonFeasible(PostProcessSolution):\n def __init__(\n self,\n problem_calendar: MS_RCPSPModel,\n problem_no_calendar: MS_RCPSPModel,\n partial_solution: PartialSolution = None,\n ):\n self.problem_calendar = problem_calendar\n self.problem_no_calendar = problem_no_calendar\n self.partial_solution = partial_solution\n if self.partial_solution is None:\n\n def check_solution(problem, solution):\n return True\n\n else:\n\n def check_solution(problem, solution):\n start_together = partial_solution.start_together\n start_at_end = partial_solution.start_at_end\n start_at_end_plus_offset = partial_solution.start_at_end_plus_offset\n start_after_nunit = partial_solution.start_after_nunit\n for (t1, t2) in start_together:\n b = (\n solution.rcpsp_schedule[t1][\"start_time\"]\n == solution.rcpsp_schedule[t2][\"start_time\"]\n )\n if not b:\n return False\n for (t1, t2) in start_at_end:\n b = (\n solution.rcpsp_schedule[t2][\"start_time\"]\n == solution.rcpsp_schedule[t1][\"end_time\"]\n )\n if not b:\n return False\n for (t1, t2, off) in start_at_end_plus_offset:\n b = (\n solution.rcpsp_schedule[t2][\"start_time\"]\n >= solution.rcpsp_schedule[t1][\"end_time\"] + off\n )\n if not b:\n return False\n for (t1, t2, off) in start_after_nunit:\n b = (\n solution.rcpsp_schedule[t2][\"start_time\"]\n >= solution.rcpsp_schedule[t1][\"start_time\"] + off\n )\n if not b:\n return False\n return True\n\n self.check_sol = check_solution\n self.graph = self.problem_calendar.compute_graph()\n self.successors = {\n n: nx.algorithms.descendants(self.graph.graph_nx, n)\n for n in self.graph.graph_nx.nodes()\n }\n self.predecessors = {\n n: nx.algorithms.descendants(self.graph.graph_nx, n)\n for n in self.graph.graph_nx.nodes()\n }\n self.immediate_predecessors = {\n n: self.graph.get_predecessors(n) for n in self.graph.nodes_name\n }\n\n def build_other_solution(self, result_storage: ResultStorage) -> ResultStorage:\n for (\n sol\n ) in (\n result_storage.list_solution_fits\n ): # [-min(2, len(result_storage.list_solution_fits)):]:\n if \"satisfy\" not in sol[0].__dict__.keys():\n rb, constraints, constraint_emp = get_ressource_breaks(\n self.problem_calendar, sol[0]\n )\n sol[0].satisfy = not (any(len(rb[r]) > 0 for r in rb))\n sol[0].satisfy = self.problem_calendar.satisfy(sol[0])\n sol[0].constraints = constraints\n if sol[0].satisfy is False:\n if self.partial_solution is None:\n s: MS_RCPSPSolution = sol[0]\n s.problem = self.problem_calendar\n solution = schedule_solution_to_variant(s)\n solution.satisfy = self.check_sol(self.problem_calendar, solution)\n solution.satisfy = self.problem_calendar.satisfy(solution)\n result_storage.list_solution_fits += [\n (\n solution,\n -self.problem_calendar.evaluate(solution)[\"makespan\"],\n )\n ]\n\n return result_storage\n\n\nclass ConstraintHandlerAddCalendarConstraint(ConstraintHandler):\n def __init__(\n self,\n problem_calendar: MS_RCPSPModel,\n problem_no_calendar: MS_RCPSPModel,\n other_constraint: ConstraintHandler,\n ):\n self.problem_calendar: MS_RCPSPModel = problem_calendar\n self.problem_no_calendar = problem_no_calendar\n self.other_constraint = other_constraint\n\n def adding_constraint_from_results_store(\n self,\n cp_solver: Union[CP_MS_MRCPSP_MZN],\n child_instance,\n result_storage: ResultStorage,\n ) -> Iterable[Any]:\n solution, fit = result_storage.get_best_solution_fit()\n solution: MS_RCPSPSolution = solution\n if \"satisfy\" in solution.__dict__.keys() and solution.satisfy:\n return self.other_constraint.adding_constraint_from_results_store(\n cp_solver,\n child_instance,\n ResultStorage(\n list_solution_fits=[(solution, fit)],\n mode_optim=result_storage.mode_optim,\n ),\n )\n ressource_breaks, constraints, constraints_employee = get_ressource_breaks(\n self.problem_calendar, solution\n )\n list_strings = []\n max_time = max([solution.schedule[x][\"end_time\"] for x in solution.schedule])\n tasks = sorted(self.problem_calendar.mode_details.keys())\n for r in constraints:\n for t in constraints[r]:\n index = tasks.index(t)\n s = None\n if isinstance(cp_solver, CP_MS_MRCPSP_MZN):\n if (\n constraints[r][t][0] is not None\n and constraints[r][t][1] is not None\n ):\n s = (\n \"\"\"constraint start[\"\"\"\n + str(index + 1)\n + \"\"\"]<=\"\"\"\n + str(constraints[r][t][0])\n + \" \\/ \"\n \"start[\"\n \"\"\n + str(index + 1)\n + \"\"\"]>=\"\"\"\n + str(constraints[r][t][1])\n + \"\"\";\\n\"\"\"\n )\n elif (\n constraints[r][t][0] is None\n and constraints[r][t][1] is not None\n ):\n s = (\n \"\"\"constraint start[\"\"\"\n + str(index + 1)\n + \"\"\"]>=\"\"\"\n + str(constraints[r][t][1])\n + \"\"\";\\n\"\"\"\n )\n elif (\n constraints[r][t][0] is not None\n and constraints[r][t][1] is None\n ):\n s = (\n \"\"\"constraint start[\"\"\"\n + str(index + 1)\n + \"\"\"]<=\"\"\"\n + str(constraints[r][t][0])\n + \"\"\";\\n\"\"\"\n )\n if s is not None:\n child_instance.add_string(s)\n list_strings += [s]\n # for r in ressource_breaks:\n # index_ressource = cp_solver.resources_index.index(r)\n # for t in range(len(self.problem_calendar.resources[r])):\n # rq = self.problem_calendar.resources[r][t]\n # if t<max_time:\n # if isinstance(cp_solver, CP_MRCPSP_MZN):\n # s = \"\"\"constraint \"\"\" + str(rq) + \"\"\">=sum( i in Act ) (\n # bool2int(start[i] <=\"\"\" + str(t) + \"\"\" /\\ \"\"\" + str(t) \\\n # + \"\"\"< start[i] + adur[i]) * arreq[\"\"\" + str(index_ressource + 1) + \"\"\",i]);\\n\"\"\"\n # elif isinstance(cp_solver, CP_RCPSP_MZN):\n # s = \"\"\"constraint \"\"\" + str(rq) + \"\"\">=sum( i in Tasks ) (\n # bool2int(s[i] <=\"\"\" + str(t) + \"\"\" /\\ \"\"\" + str(t) \\\n # + \"\"\"< s[i] + d[i]) * rr[\"\"\" + str(index_ressource + 1) + \"\"\",i]);\\n\"\"\"\n # child_instance.add_string(s)\n # list_strings += [s]\n\n for r in ressource_breaks:\n for index in ressource_breaks[r]:\n if random.random() < 0.6:\n continue\n ind = index[0]\n if r in self.problem_calendar.resources_availability:\n index_ressource = cp_solver.resources_index.index(r)\n rq = self.problem_calendar.resources_availability[r][ind]\n # if random.random() <= 0.3:\n # continue\n s = (\n \"\"\"constraint \"\"\"\n + str(rq)\n + \"\"\">=sum( i in Act ) (\n bool2int(start[i] <=\"\"\"\n + str(ind)\n + \"\"\" /\\ \"\"\"\n + str(ind)\n + \"\"\"< start[i] + adur[i]) * arreq[\"\"\"\n + str(index_ressource + 1)\n + \"\"\",i]);\\n\"\"\"\n )\n child_instance.add_string(s)\n list_strings += [s]\n\n if r in self.problem_calendar.employees:\n index_ressource = cp_solver.employees_position.index(r)\n rq = int(self.problem_calendar.employees[r].calendar_employee[ind])\n # if random.random() <= 0.3:\n # continue\n s = (\n \"\"\"constraint \"\"\"\n + str(rq)\n + \"\"\">=sum( i in Act ) (\n bool2int(start[i] <=\"\"\"\n + str(ind)\n + \"\"\" /\\ \"\"\"\n + str(ind)\n + \"\"\"< start[i] + adur[i]) * unit_used[\"\"\"\n + str(index_ressource + 1)\n + \"\"\",i]);\\n\"\"\"\n )\n child_instance.add_string(s)\n list_strings += [s]\n\n satisfiable = [\n (s, f)\n for s, f in result_storage.list_solution_fits\n if \"satisfy\" in s.__dict__.keys() and s.satisfy\n ]\n if len(satisfiable) > 0:\n res = ResultStorage(\n list_solution_fits=satisfiable, mode_optim=result_storage.mode_optim\n )\n self.other_constraint.adding_constraint_from_results_store(\n cp_solver, child_instance, res\n )\n return [\"req\"] + list_strings\n\n def remove_constraints_from_previous_iteration(\n self,\n cp_solver: CP_MS_MRCPSP_MZN,\n child_instance,\n previous_constraints: Iterable[Any],\n ):\n pass\n\n\nclass SolverWithCalendarIterative(SolverDO):\n def __init__(\n self,\n problem_calendar: MS_RCPSPModel,\n partial_solution: PartialSolution = None,\n option_neighbor: OptionNeighbor = OptionNeighbor.MIX_FAST,\n **kwargs\n ):\n self.problem_calendar = problem_calendar\n self.problem_no_calendar = self.problem_calendar.copy()\n self.problem_no_calendar = MS_RCPSPModel(\n skills_set=self.problem_calendar.skills_set,\n resources_set=self.problem_calendar.resources_set,\n non_renewable_resources=self.problem_calendar.non_renewable_resources,\n resources_availability={\n r: [int(max(self.problem_calendar.resources_availability[r]))]\n * len(self.problem_calendar.resources_availability[r])\n for r in self.problem_calendar.resources_availability\n },\n employees={\n emp: self.problem_calendar.employees[emp].copy()\n for emp in self.problem_calendar.employees\n },\n employees_availability=self.problem_calendar.employees_availability,\n mode_details=self.problem_calendar.mode_details,\n successors=self.problem_calendar.successors,\n horizon=self.problem_calendar.horizon,\n horizon_multiplier=self.problem_calendar.horizon_multiplier,\n )\n for emp in self.problem_calendar.employees:\n self.problem_no_calendar.employees[emp].calendar_employee = [\n max(self.problem_calendar.employees[emp].calendar_employee)\n ] * len(self.problem_calendar.employees[emp].calendar_employee)\n solver = CP_MS_MRCPSP_MZN(\n rcpsp_model=self.problem_no_calendar, cp_solver_name=CPSolverName.CHUFFED\n )\n solver.init_model(\n output_type=True,\n model_type=\"single\",\n partial_solution=partial_solution,\n add_calendar_constraint_unit=False,\n exact_skills_need=False,\n )\n parameters_cp = ParametersCP.default()\n parameters_cp.TimeLimit = 500\n parameters_cp.TimeLimit_iter0 = 500\n params_objective_function = get_default_objective_setup(\n problem=self.problem_no_calendar\n )\n # constraint_handler = ConstraintHandlerFixStartTime(problem=rcpsp_problem,\n # fraction_fix_start_time=0.5)\n constraint_handler = build_neighbor_operator(\n option_neighbor=option_neighbor, rcpsp_model=self.problem_no_calendar\n )\n constraint_handler = ConstraintHandlerAddCalendarConstraint(\n self.problem_calendar, self.problem_no_calendar, constraint_handler\n )\n initial_solution_provider = InitialSolutionMS_RCPSP(\n problem=self.problem_calendar,\n initial_method=InitialMethodRCPSP.PILE_CALENDAR,\n params_objective_function=params_objective_function,\n )\n self.initial_solution_provider = initial_solution_provider\n self.constraint_handler = constraint_handler\n self.params_objective_function = params_objective_function\n self.cp_solver = solver\n self.post_process_solution = PostProcessSolutionNonFeasible(\n self.problem_calendar,\n self.problem_no_calendar,\n partial_solution=partial_solution,\n )\n\n def solve(\n self,\n parameters_cp: ParametersCP,\n nb_iteration_lns: int,\n nb_iteration_no_improvement: Optional[int] = None,\n max_time_seconds: Optional[int] = None,\n skip_first_iteration: bool = False,\n **args\n ) -> ResultStorage:\n sense = self.params_objective_function.sense_function\n if max_time_seconds is None:\n max_time_seconds = 3600 * 24 # One day\n if nb_iteration_no_improvement is None:\n nb_iteration_no_improvement = 2 * nb_iteration_lns\n current_nb_iteration_no_improvement = 0\n deb_time = time.time()\n if not skip_first_iteration:\n store_lns = self.initial_solution_provider.get_starting_solution()\n store_lns = self.post_process_solution.build_other_solution(store_lns)\n store_with_all = ResultStorage(\n list(store_lns.list_solution_fits), mode_optim=store_lns.mode_optim\n )\n init_solution, objective = store_lns.get_best_solution_fit()\n best_solution = init_solution.copy()\n satisfy = self.problem_calendar.satisfy(init_solution)\n best_objective = objective\n else:\n best_objective = (\n float(\"inf\") if sense == ModeOptim.MINIMIZATION else -float(\"inf\")\n )\n best_solution = None\n constraint_iterable = {\"empty\": []}\n store_lns = None\n store_with_all = None\n constraint_to_keep = set()\n for iteration in range(nb_iteration_lns):\n try:\n print(\n \"Best feasible solution \",\n max(\n [\n f\n for s, f in store_with_all.list_solution_fits\n if \"satisfy\" in s.__dict__.keys() and s.satisfy\n ]\n ),\n )\n except:\n print(\"No Feasible solution yet\")\n with self.cp_solver.instance.branch() as child:\n if iteration == 0 and not skip_first_iteration or iteration >= 1:\n for c in constraint_to_keep:\n child.add_string(c)\n constraint_iterable = (\n self.constraint_handler.adding_constraint_from_results_store(\n cp_solver=self.cp_solver,\n child_instance=child,\n result_storage=store_lns,\n )\n )\n if constraint_iterable[0] == \"req\":\n constraint_to_keep.update(\n set([c for c in constraint_iterable[1:]])\n )\n if True:\n if iteration == 0:\n result = child.solve(\n timeout=timedelta(seconds=parameters_cp.TimeLimit_iter0),\n intermediate_solutions=parameters_cp.intermediate_solution,\n )\n else:\n result = child.solve(\n timeout=timedelta(seconds=parameters_cp.TimeLimit),\n intermediate_solutions=parameters_cp.intermediate_solution,\n )\n result_store = self.cp_solver.retrieve_solutions(\n result, parameters_cp=parameters_cp\n )\n if len(result_store.list_solution_fits) > 0:\n bsol, fit = result_store.get_best_solution_fit()\n result_store = self.post_process_solution.build_other_solution(\n result_store\n )\n bsol, fit = result_store.get_best_solution_fit()\n if sense == ModeOptim.MAXIMIZATION and fit >= best_objective:\n if fit > best_objective:\n current_nb_iteration_no_improvement = 0\n else:\n current_nb_iteration_no_improvement += 1\n best_solution = bsol\n best_objective = fit\n elif sense == ModeOptim.MAXIMIZATION:\n current_nb_iteration_no_improvement += 1\n elif sense == ModeOptim.MINIMIZATION and fit <= best_objective:\n if fit < best_objective:\n current_nb_iteration_no_improvement = 0\n else:\n current_nb_iteration_no_improvement += 1\n best_solution = bsol\n best_objective = fit\n elif sense == ModeOptim.MINIMIZATION:\n current_nb_iteration_no_improvement += 1\n if skip_first_iteration and iteration == 0:\n store_lns = result_store\n store_with_all = ResultStorage(\n list_solution_fits=list(store_lns.list_solution_fits),\n mode_optim=store_lns.mode_optim,\n )\n store_lns = result_store\n for s, f in store_lns.list_solution_fits:\n store_with_all.list_solution_fits += [(s, f)]\n for s, f in store_with_all.list_solution_fits:\n if s.satisfy:\n store_lns.list_solution_fits += [(s, f)]\n else:\n current_nb_iteration_no_improvement += 1\n if (\n skip_first_iteration\n and result.status == Status.OPTIMAL_SOLUTION\n and iteration == 0\n and best_solution.satisfy\n ):\n break\n else:\n current_nb_iteration_no_improvement += 1\n if time.time() - deb_time > max_time_seconds:\n break\n if current_nb_iteration_no_improvement > nb_iteration_no_improvement:\n break\n return store_with_all\n"
] | [
[
"numpy.argwhere"
]
] |
ColdMatter/PhotonBEC | [
"c6bcf9bdefd267c8adde0d299cf5920b010c5022"
] | [
"EMCCD/EMCCD/EMCCD_backend.py"
] | [
"'''\n\tWritten by:\t\tJoao Rodrigues\n\tLast Update: \tOctober 16th 2020\n\n'''\n\n\nimport numpy as np\nimport copy\nimport ctypes\nimport socket\nimport time\n\n########## Parameters\nif socket.gethostname() == \"ph-photonbec5\":\n\tdll_file = r\"D:\\Control\\EMCCD\\atmcd32d.dll\"\n\n\nclass EMCCD():\n\n\t##### Error Codes\n\temccd_return_codes = dict()\n\temccd_return_codes.update({20001: 'DRV_ERROR_CODES'})\n\temccd_return_codes.update({20002: 'DRV_SUCCESS'})\n\temccd_return_codes.update({20003: 'DRV_VXDNOTINSTALLED'})\n\temccd_return_codes.update({20004: 'DRV_ERROR_SCAN'})\n\temccd_return_codes.update({20005: 'DRV_ERROR_CHECK_SUM'})\n\temccd_return_codes.update({20006: 'DRV_ERROR_FILELOAD'})\n\temccd_return_codes.update({20007: 'DRV_UNKNOWN_FUNCTION'})\n\temccd_return_codes.update({20008: 'DRV_ERROR_VXD_INIT'})\n\temccd_return_codes.update({20009: 'DRV_ERROR_ADDRESS'})\n\temccd_return_codes.update({20010: 'DRV_ERROR_PAGELOCK'})\n\temccd_return_codes.update({20011: 'DRV_ERROR_PAGE_UNLOCK'})\n\temccd_return_codes.update({20012: 'DRV_ERROR_BOARDTEST'})\n\temccd_return_codes.update({20013: 'DRV_ERROR_ACK'})\n\temccd_return_codes.update({20014: 'DRV_ERROR_UP_FIFO'})\n\temccd_return_codes.update({20015: 'DRV_ERROR_PATTERN'})\n\temccd_return_codes.update({20017: 'DRV_ACQUISITION_ERRORS'})\n\temccd_return_codes.update({20018: 'DRV_ACQ_BUFFER'})\n\temccd_return_codes.update({20019: 'DRV_ACQ_DOWNFIFO_FULL'})\n\temccd_return_codes.update({20020: 'DRV_PROC_UNKNOWN_INSTRUCTION'})\n\temccd_return_codes.update({20021: 'DRV_ILLEGAL_OP_CODE'})\n\temccd_return_codes.update({20022: 'DRV_KINETIC_TIME_NOT_MET'})\n\temccd_return_codes.update({20023: 'DRV_ACCUM_TIME_NOT_MET'})\n\temccd_return_codes.update({20024: 'DRV_NO_NEW_DATA'})\n\temccd_return_codes.update({20025: 'PCI_DMA_FAIL'})\n\temccd_return_codes.update({20026: 'DRV_SPOOLERROR'})\n\temccd_return_codes.update({20027: 'DRV_SPOOLSETUPERROR'})\n\temccd_return_codes.update({20029: 'SATURATED'})\n\temccd_return_codes.update({20033: 'DRV_TEMPERATURE_CODES'})\n\temccd_return_codes.update({20034: 'DRV_TEMPERATURE_OFF'})\n\temccd_return_codes.update({20035: 'DRV_TEMP_NOT_STABILIZED'})\n\temccd_return_codes.update({20036: 'DRV_TEMPERATURE_STABILIZED'})\n\temccd_return_codes.update({20037: 'DRV_TEMPERATURE_NOT_REACHED'})\n\temccd_return_codes.update({20038: 'DRV_TEMPERATURE_OUT_RANGE'})\n\temccd_return_codes.update({20039: 'DRV_TEMPERATURE_NOT_SUPPORTED'})\n\temccd_return_codes.update({20040: 'DRV_TEMPERATURE_DRIFT'})\n\temccd_return_codes.update({20049: 'DRV_GENERAL_ERRORS'})\n\temccd_return_codes.update({20050: 'DRV_INVALID_AUX'})\n\temccd_return_codes.update({20051: 'DRV_COF_NOTLOADED'})\n\temccd_return_codes.update({20052: 'DRV_FPGAPROG'})\n\temccd_return_codes.update({20053: 'DRV_FLEXERROR'})\n\temccd_return_codes.update({20054: 'DRV_GPIBERROR'})\n\temccd_return_codes.update({20055: 'ERROR_DMA_UPLOAD'})\n\temccd_return_codes.update({20064: 'DRV_DATATYPE'})\n\temccd_return_codes.update({20065: 'DRV_DRIVER_ERRORS'})\n\temccd_return_codes.update({20066: 'DRV_P1INVALID'})\n\temccd_return_codes.update({20067: 'DRV_P2INVALID'})\n\temccd_return_codes.update({20068: 'DRV_P3INVALID'})\n\temccd_return_codes.update({20069: 'DRV_P4INVALID'})\n\temccd_return_codes.update({20070: 'DRV_INIERROR'})\n\temccd_return_codes.update({20071: 'DRV_COFERROR'})\n\temccd_return_codes.update({20072: 'DRV_ACQUIRING'})\n\temccd_return_codes.update({20073: 'DRV_IDLE'})\n\temccd_return_codes.update({20074: 'DRV_TEMPCYCLE'})\n\temccd_return_codes.update({20075: 'DRV_NOT_INITIALIZED'})\n\temccd_return_codes.update({20076: 'DRV_P5INVALID'})\n\temccd_return_codes.update({20077: 'DRV_P6INVALID'})\n\temccd_return_codes.update({20078: 'DRV_INVALID_MODE'})\n\temccd_return_codes.update({20079: 'DRV_INVALID_FILTER'})\n\temccd_return_codes.update({20080: 'DRV_I2CERRORS'})\n\temccd_return_codes.update({20081: 'DRV_DRV_I2CDEVNOTFOUND'})\n\temccd_return_codes.update({20082: 'DRV_I2CTIMEOUT'})\n\temccd_return_codes.update({20083: 'DRV_P7INVALID'})\n\temccd_return_codes.update({20089: 'DRV_USBERROR'})\n\temccd_return_codes.update({20090: 'DRV_IOCERROR'})\n\temccd_return_codes.update({20091: 'DRV_VRMVERSIONERROR'})\n\temccd_return_codes.update({20093: 'DRV_USB_INTERRUPT_ENDPOINT_ERROR'})\n\temccd_return_codes.update({20094: 'DRV_RANDOM_TRACK_ERROR'})\n\temccd_return_codes.update({20095: 'DRV_INVALID_TRIGGER_MODE'})\n\temccd_return_codes.update({20096: 'DRV_LOAD_FIRMWARE_ERROR'})\n\temccd_return_codes.update({20097: 'DRV_DIVIDE_BY_ZERO_ERROR'})\n\temccd_return_codes.update({20098: 'DRV_INVALID_RINGEXPOSURES'})\n\temccd_return_codes.update({20099: 'DRV_BINNING_ERROR'})\n\temccd_return_codes.update({20990: 'DRV_ERROR_NOCAMERA'})\n\temccd_return_codes.update({20991: 'DRV_NOT_SUPPORTED'})\n\temccd_return_codes.update({20992: 'DRV_NOT_AVAILABLE'})\n\temccd_return_codes.update({20115: 'DRV_ERROR_MAP'})\n\temccd_return_codes.update({20116: 'DRV_ERROR_UNMAP'})\n\temccd_return_codes.update({20117: 'DRV_ERROR_MDL'})\n\temccd_return_codes.update({20118: 'DRV_ERROR_UNMDL'})\n\temccd_return_codes.update({20119: 'DRV_ERROR_BUFFSIZE'})\n\temccd_return_codes.update({20121: 'DRV_ERROR_NOHANDLE'})\n\temccd_return_codes.update({20130: 'DRV_GATING_NOT_AVAILABLE'})\n\temccd_return_codes.update({20131: 'DRV_FPGA_VOLTAGE_ERROR'})\n\temccd_return_codes.update({20099: 'DRV_BINNING_ERROR'})\n\temccd_return_codes.update({20100: 'DRV_INVALID_AMPLIFIER'})\n\temccd_return_codes.update({20101: 'DRV_INVALID_COUNTCONVERT_MODE'})\n\n\t##### Camera attributes\n\tacquisition_modes = {\"single scan\":1, \"accumulate\":2, \"kinetics\":3, \"fast kinetics\":4, \"run till abort\":5}\n\toutput_amplifier_modes = {\"EMCCD\":0, \"CCD\":1}\n\tread_modes = {\"full vertical binning\":0, \"multi-track\":1, \"random-track\":2, \"single-track\":3, \"image\":4}\n\tshutter_modes = {\"fully auto\":0, \"permanently open\":1, \"permanently closed\":2, \"open for FVB series\":4, \"open for any series\":5}\n\ttrigger_modes = {\"internal\":0, \"external\":1, \"external start\":6, \"external exposure (bulb)\":7, \"external FVB EM\":9, \"software trigger\":10, \"external charge shifting\":12}\n\n\n\n\tdef __init__(self, VERBOSE=True, frontend=None):\n\t\t\n\t\tself.VERBOSE = VERBOSE\n\t\tself.frontend = frontend\n\n\t\tself.COOLER = False\n\t\tself.STABLE_TEMPERATURE = False\n\n\t\t# Loads the dll\n\t\tself.dll = ctypes.WinDLL(dll_file)\n\n\t\t# Initializes EMCCD SDK\n\t\tself.printout(message=\"Initializing SDK:\")\n\t\tdummy = ctypes.c_char()\n\t\tout = self.dll.Initialize(dummy)\n\t\tself.printout(code=out)\n\t\tif not out == 20002:\n\t\t\traise Exception(\"Could not load SDK\")\n\n\t\t# Retrives the valid range of temperatures in centrigrades to which the detector can be cooled\n\t\tself.printout(message=\"Getting sensor temperature range:\")\n\t\tTmin = ctypes.c_int()\n\t\tTmax = ctypes.c_int()\n\t\tout = self.dll.GetTemperatureRange(ctypes.pointer(Tmin), ctypes.pointer(Tmax))\n\t\tself.printout(code=out)\n\t\tif not out == 20002:\n\t\t\traise Exception(\"Could not retrive detector temperature range: \"+self.emccd_return_codes[out])\n\t\tself.Tmin = Tmin.value\n\t\tself.Tmax = Tmax.value\n\t\tself.printout(message=\"Temperature min = \"+str(self.Tmin))\n\t\tself.printout(message=\"Temperature max = \"+str(self.Tmax))\n\n\t\t# Gets horizontal shifting speeds from the camera\n\t\tself.printout(message=\"Calibrating horizontal shifting speeds\")\n\t\tself.horizontal_shifting_speeds = dict() # Shifting speeds in MHz\n\t\tfor typ in [0, 1]: # 0:electron multiplication, 1: conventional\n\t\t\tself.horizontal_shifting_speeds[typ] = dict()\n\t\t\tspeeds = ctypes.c_int()\n\t\t\tout = self.dll.GetNumberHSSpeeds(ctypes.c_int(0), ctypes.c_int(typ), ctypes.pointer(speeds))\n\t\t\tspeeds = speeds.value\n\t\t\tif out == 20002:\n\t\t\t\tfor i in range(0, speeds):\n\t\t\t\t\tspeedMHz = ctypes.c_float()\n\t\t\t\t\tout1 = self.dll.GetHSSpeed(ctypes.c_int(0), ctypes.c_int(typ), ctypes.c_int(i), ctypes.pointer(speedMHz))\n\t\t\t\t\tif out1 == 20002:\n\t\t\t\t\t\tself.horizontal_shifting_speeds[typ][i] = speedMHz.value\n\t\t\t\t\telse:\n\t\t\t\t\t\traise Exception(\"Could not retrieve horizontal shift speed: \"+self.emccd_return_codes[out1])\n\t\t\telse:\n\t\t\t\traise Exception(\"Could not retrieve number of horizontal shift speeds: \"+self.emccd_return_codes[out])\n\n\t\t# Gets vertical shifting speeds from the camera\n\t\tself.printout(message=\"Calibrating vertical shifting speeds\")\n\t\tself.vertical_shifting_speeds = dict() # Shifting speeds in microseconds per pixel shift\n\t\tspeeds = ctypes.c_int()\n\t\tout = self.dll.GetNumberVSSpeeds(ctypes.pointer(speeds))\n\t\tspeeds = speeds.value\n\t\tif out == 20002:\n\t\t\tfor i in range(0, speeds):\n\t\t\t\tspeed_ms = ctypes.c_float()\n\t\t\t\tout1 = self.dll.GetVSSpeed(ctypes.c_int(i), ctypes.pointer(speed_ms))\n\t\t\t\tif out1 == 20002:\n\t\t\t\t\tself.vertical_shifting_speeds[i] = speed_ms.value\n\t\t\t\telse:\n\t\t\t\t\traise Exception(\"Could not retrieve vertical shift speed: \"+self.emccd_return_codes[out1])\n\t\telse:\n\t\t\traise Exception(\"Could not retrieve number of vertical shift speeds: \"+self.emccd_return_codes[out])\n\n\t\t# Gets Preamp gain values\n\t\tself.printout(message=\"Calibrating pre-amp gain values\")\n\t\tself.preamp_gain_values = dict()\n\t\tgains = ctypes.c_int()\n\t\tout = self.dll.GetNumberPreAmpGains(ctypes.pointer(gains))\n\t\tgains = gains.value\n\t\tif out == 20002:\n\t\t\tfor i in range(0, gains):\n\t\t\t\tgain = ctypes.c_float()\n\t\t\t\tout1 = self.dll.GetPreAmpGain(ctypes.c_int(i), ctypes.pointer(gain))\n\t\t\t\tif out1 == 20002:\n\t\t\t\t\tself.preamp_gain_values[i] = gain.value\n\t\t\t\telse:\n\t\t\t\t\traise Exception(\"Could not retrieve pre-amp gain value: \"+self.emccd_return_codes[out1])\n\t\telse:\n\t\t\traise Exception(\"Could not retrieve number of pre-amp gains: \"+self.emccd_return_codes[out])\n\n\n\t\t# Gets the detector size, in pixels\n\t\tself.printout(message=\"Getting number of detector pixels\")\n\t\txpixels = ctypes.c_int()\n\t\typixels = ctypes.c_int()\n\t\tout = self.dll.GetDetector(ctypes.pointer(xpixels), ctypes.pointer(ypixels))\n\t\tif not out == 20002:\n\t\t\traise Exception(\"Could not retrive number of pixels: \"+self.emccd_return_codes[out])\n\t\tself.xpixels = xpixels.value\n\t\tself.ypixels = ypixels.value\n\t\tself.image_format = None\n\n\n\tdef printout(self, code=None, message=None):\n\t\t# Prints to the frontend, if it exists\n\t\tif not self.frontend is None:\n\t\t\tif not message is None:\n\t\t\t\tself.frontend.write_camera_message(message=message)\n\t\t\tif not code is None:\n\t\t\t\tself.frontend.write_camera_message(message=self.emccd_return_codes[code])\n\n\t\t# Prints to the command line\n\t\tif self.VERBOSE:\n\t\t\tif not message is None:\n\t\t\t\tprint(\"EMCCD object: \"+message)\n\t\t\tif not code is None:\n\t\t\t\tprint(\"EMCCD object: \"+self.emccd_return_codes[code])\n\n\n\n\n\tdef SetTemperature(self, temperature):\n\t\t\"\"\" \n\t\t\tSets the desired temperature of the detector. To turn the cooling ON and OFF the user\n\t\t\tmust use the CoolerON and CoolerOFF methods.\n\n\t\t\tParameters:\n\t\t\t\ttemperature (int): Desired detector temperature (in C)\n\n\t\t\"\"\"\n\t\ttemperature = int(temperature)\n\t\tif temperature<self.Tmin or temperature>self.Tmax:\n\t\t\traise Exception(\"Invalid temperature\")\n\t\tself.printout(message=\"Setting temperature to \"+str(temperature)+\" C\")\n\t\tout = self.dll.SetTemperature(ctypes.c_int(temperature))\n\t\tself.printout(code=out)\n\t\tif out == 20002:\n\t\t\tSUCCESS = True\n\t\telse:\n\t\t\tSUCCESS = False\n\t\treturn SUCCESS, copy.deepcopy(self.emccd_return_codes[out])\n\n\n\n\n\tdef CoolerON(self):\n\t\t\"\"\"\n\t\t\tSwitches ON the cooling.\n\n\t\t\"\"\"\n\n\t\tself.printout(message=\"Switching ON the cooling\")\n\t\tout = self.dll.CoolerON()\n\t\tself.printout(code=out)\n\t\tif out == 20002:\n\t\t\tSUCCESS = True\n\t\t\tself.COOLER = True\n\t\telse:\n\t\t\tSUCCESS = False\n\t\treturn SUCCESS, copy.deepcopy(self.emccd_return_codes[out])\n\n\n\n\n\tdef CoolerOFF(self):\n\t\t\"\"\"\n\t\t\tSwitches OFF the cooling.\n\n\t\t\"\"\"\n\n\t\tself.printout(message=\"Switching OFF the cooling\")\n\t\tout = self.dll.CoolerOFF()\n\t\tself.printout(code=out)\n\t\tif out == 20002:\n\t\t\tSUCCESS = True\n\t\t\tself.COOLER = False\n\t\telse:\n\t\t\tSUCCESS = False\n\t\treturn SUCCESS, copy.deepcopy(self.emccd_return_codes[out])\n\n\n\n\n\tdef StabilizeTemperature(self):\n\t\t\"\"\" \n\t\t\tWaits until detector temperature has stabilized to set point\n\n\t\t\"\"\"\n\n\t\tself.printout(message=\"Stabilizing detector temperature...\")\n\t\tcurrent_temperature_c = ctypes.c_int()\n\t\tout = self.dll.GetTemperature(ctypes.pointer(current_temperature_c))\n\t\tif out == 20037:\n\t\t\twhile out == 20037:\n\t\t\t\tself.printout(message=\" Current temperature: \"+str(current_temperature_c.value))\n\t\t\t\ttime.sleep(1)\n\t\t\t\tout = self.dll.GetTemperature(ctypes.pointer(current_temperature_c))\n\t\t\tself.printout(code=out)\n\t\tif out == 20036:\n\t\t\tSUCCESS = True\n\t\t\tself.STABLE_TEMPERATURE = True\n\t\t\tself.printout(message=\"Detector temperature has stabilized at set point\")\n\t\telse:\n\t\t\tSUCCESS = False\n\t\t\tself.STABLE_TEMPERATURE = False\n\t\treturn SUCCESS, copy.deepcopy(self.emccd_return_codes[out]), current_temperature_c.value\n\n\n\n\n\tdef SetAcquisitionMode(self, mode):\n\t\t\"\"\"\n\t\t\tSets the acquisition mode.\n\n\t\t\tParameters:\n\t\t\t\tmode (str):\t\tOption are \"single scan\", \"accumulate\", \"kinetics\", \"fast kinetics\", \"run till abort\"\n\n\t\t\"\"\"\n\n\t\tself.printout(message=\"Setting acquisition mode\")\n\t\tif not any([mode==possibility for possibility in self.acquisition_modes.keys()]):\n\t\t\traise Exception(\"Unkown acquisition mode\")\n\t\tout = self.dll.SetAcquisitionMode(ctypes.c_int(self.acquisition_modes[mode]))\n\t\tself.printout(code=out)\n\t\tif out == 20002:\n\t\t\tSUCCESS = True\n\t\telse:\n\t\t\tSUCCESS = False\n\t\treturn SUCCESS, copy.deepcopy(self.emccd_return_codes[out])\n\n\n\n\n\tdef SetOutputAmplifier(self, mode):\n\t\t\"\"\"\n\t\t\tSome EMCCD systems have the capability to use a second output amplifier. This\n\t\t\t\tfunction will set the type of output amplifier to be used when reading data from the head\n\t\t\t\tfor these systems.\n\n\n\t\t\tParameters:\n\t\t\t\tmode (str):\t\t\"EMCCD\": Standard EMCCD gain register (default)/Conventional(clara)\n\t\t\t\t\t\t\t\t\"CCD\": Conventional CCD register/Extended NIR mode(clara).\n\n\t\t\"\"\"\n\n\t\tself.printout(message=\"Setting output amplifier mode\")\n\t\tif not any([mode==possibility for possibility in self.output_amplifier_modes.keys()]):\n\t\t\traise Exception(\"Unkown output amplifier mode\")\n\t\tout = self.dll.SetOutputAmplifier(ctypes.c_int(self.output_amplifier_modes[mode]))\n\t\tself.printout(code=out)\n\t\tif out == 20002:\n\t\t\tSUCCESS = True\n\t\telse:\n\t\t\tSUCCESS = False\n\t\treturn SUCCESS, copy.deepcopy(self.emccd_return_codes[out])\n\n\n\n\n\tdef SetReadMode(self, mode):\n\t\t\"\"\"\n\t\t\tSets the read mode.\n\n\t\t\tParameters:\n\t\t\t\tmode (str):\t\tOption are \"full vertical binning\", \"multi-track\", \"random-track\", \"single-track\", \"image\"\n\n\t\t\"\"\"\n\n\t\tself.printout(message=\"Setting read mode\")\n\t\tif not any([mode==possibility for possibility in self.read_modes.keys()]):\n\t\t\traise Exception(\"Unkown read mode\")\n\t\tout = self.dll.SetReadMode(ctypes.c_int(self.read_modes[mode]))\n\t\tself.printout(code=out)\n\t\tif out == 20002:\n\t\t\tSUCCESS = True\n\t\telse:\n\t\t\tSUCCESS = False\n\t\treturn SUCCESS, copy.deepcopy(self.emccd_return_codes[out])\n\n\n\n\n\tdef SetShutter(self, typ, mode, closingtime, openingtime):\n\t\t\"\"\"\n\t\t\tThis function controls the behaviour of the shutter.\n\t\t\tThe typ parameter allows the user to control the TTL signal output to an external shutter.\n\t\t\tThe mode parameter configures whether the shutter opens and closes automatically\n\t\t\t\t(controlled by the camera) or is permanently open or permanently closed.\n\t\t\tThe opening and closing time specify the time required to open and close the shutter\n\t\t\t\t(this information is required for calculating acquisition timings - see SHUTTER TRANSFER TIME in the manual).\n\n\n\t\t\tParameters:\n\t\t\t\ttyp (int): 0: Output TTL low signal to open shutter\n\t\t\t\t\t\t\t1: Output TTL high signal to open shutter\n\n\t\t\t\tmode (str): Option are \"fully auto\", \"permanently open\", \"permanently closed\", \"open for FVB series\", \"open for any series\"\n\n\t\t\t\tclosingtime (int): time shutter takes to close (miliseconds)\n\n\t\t\t\topeningtime (int): time shutter takes to open (miliseconds)\n\n\t\t\"\"\"\n\n\t\tself.printout(message=\"Setting shutter mode\")\n\t\tif not (typ==0 or typ==1):\n\t\t\traise Exception(\"Invalid shutter TTL type\")\n\n\t\tif not any([mode==possibility for possibility in self.shutter_modes.keys()]):\n\t\t\traise Exception(\"Unkown shutter mode\")\n\t\tout = self.dll.SetShutter(\n\t\t\tctypes.c_int(typ),\n\t\t\tctypes.c_int(self.shutter_modes[mode]),\n\t\t\tctypes.c_int(closingtime),\n\t\t\tctypes.c_int(openingtime))\n\t\tself.printout(code=out)\n\t\tif out == 20002:\n\t\t\tSUCCESS = True\n\t\telse:\n\t\t\tSUCCESS = False\n\t\treturn SUCCESS, copy.deepcopy(self.emccd_return_codes[out])\n\n\n\n\n\tdef SetExposureTime(self, time):\n\t\t\"\"\"\n\t\t\tThis function will set the exposure time to the nearest valid value not less than the given\n\t\t\t\tvalue. The actual exposure time used is obtained by GetAcquisitionTimings.. Please\n\t\t\t\trefer to SECTION 5 - ACQUISITION MODES for further information.\n\n\t\t\tParameters:\n\t\t\t\ttime (float): The exposure time in seconds\n\n\t\t\"\"\"\n\n\t\tself.printout(message=\"Setting exposure time\")\n\t\tout = self.dll.SetExposureTime(ctypes.c_float(time))\n\t\tself.printout(code=out)\n\t\tif out == 20002:\n\t\t\tSUCCESS = True\n\t\telse:\n\t\t\tSUCCESS = False\n\t\treturn SUCCESS, copy.deepcopy(self.emccd_return_codes[out])\n\n\n\n\n\tdef SetTriggerMode(self, mode):\n\t\t\"\"\"\n\t\t\tThis function will set the trigger mode that the camera will operate in.\n\t\t\t\n\t\t\tParameters:\n\t\t\t\tmode (str): Options are \"internal\", \"external\", \"external start\", \"external exposure (bulb)\",\n\t\t\t\t\t\t\t\t\"external FVB EM\", \"software trigger\", \"external charge shifting\"\n\n\t\t\"\"\"\n\n\t\tself.printout(message=\"Setting trigger mode\")\n\t\tif not any([mode==possibility for possibility in self.trigger_modes.keys()]):\n\t\t\traise Exception(\"Unkown trigger mode\")\n\t\tout = self.dll.SetTriggerMode(ctypes.c_int(self.trigger_modes[mode]))\n\t\tself.printout(code=out)\n\t\tif out == 20002:\n\t\t\tSUCCESS = True\n\t\telse:\n\t\t\tSUCCESS = False\n\t\treturn SUCCESS, copy.deepcopy(self.emccd_return_codes[out])\n\n\n\n\n\tdef SetAccumulationCycleTime(self, time):\n\t\t\"\"\"\n\t\t\tThis function will set the accumulation cycle time to the nearest valid value not less than\n\t\t\t\tthe given value. The actual cycle time used is obtained by GetAcquisitionTimings. Please\n\t\t\t\trefer to SECTION 5 - ACQUISITION MODES for further information.\n\n\t\t\tParameters:\n\t\t\t\ttime (float): The accumulation cycle time in seconds\n\n\t\t\"\"\"\n\n\t\tself.printout(message=\"Setting accumulation cycle time\")\n\t\tout = self.dll.SetAccumulationCycleTime(ctypes.c_float(time))\n\t\tself.printout(code=out)\n\t\tif out == 20002:\n\t\t\tSUCCESS = True\n\t\telse:\n\t\t\tSUCCESS = False\n\t\treturn SUCCESS, copy.deepcopy(self.emccd_return_codes[out])\n\n\n\n\n\n\tdef SetNumberAccumulations(self, number):\n\t\t\"\"\"\n\t\t\tThis function will set the number of scans accumulated in memory. This will only take\n\t\t\t\teffect if the acquisition mode is either Accumulate or Kinetic Series.\n\n\t\t\tParameters:\n\t\t\t\tnumber (int): Number of scans to accumulate\n\n\t\t\"\"\"\n\n\t\tself.printout(message=\"Setting number of accumulations\")\n\t\tout = self.dll.SetNumberAccumulations(ctypes.c_int(number))\n\t\tself.printout(code=out)\n\t\tif out == 20002:\n\t\t\tSUCCESS = True\n\t\telse:\n\t\t\tSUCCESS = False\n\t\treturn SUCCESS, copy.deepcopy(self.emccd_return_codes[out])\n\n\n\n\n\tdef SetNumberKinetics(self, number):\n\t\t\"\"\"\n\t\t\tThis function will set the number of scans (possibly accumulated scans) to be taken\n\t\t\t\tduring a single acquisition sequence. This will only take effect if the acquisition mode is\n\t\t\t\tKinetic Series.\n\n\t\t\tParameters:\n\t\t\t\tnumber (int): Number of scans to store\n\n\t\t\"\"\"\n\n\t\tself.printout(message=\"Setting number of kinetic scans\")\n\t\tout = self.dll.SetNumberKinetics(ctypes.c_int(number))\n\t\tself.printout(code=out)\n\t\tif out == 20002:\n\t\t\tSUCCESS = True\n\t\telse:\n\t\t\tSUCCESS = False\n\t\treturn SUCCESS, copy.deepcopy(self.emccd_return_codes[out])\n\n\n\n\n\tdef SetKineticCycleTime(self, time):\n\t\t\"\"\"\n\t\t\tThis function will set the kinetic cycle time to the nearest valid value not less than the\n\t\t\t\tgiven value. The actual time used is obtained by GetAcquisitionTimings. Please refer to\n\t\t\t\tSECTION 5 - ACQUISITION MODES for further information.\n\n\t\t\tParameters:\n\t\t\t\ttime (float): The kinetic cycle time in seconds\n\n\t\t\"\"\"\n\n\t\tself.printout(message=\"Setting kinetic cycle time\")\n\t\tout = self.dll.SetKineticCycleTime(ctypes.c_float(time))\n\t\tself.printout(code=out)\n\t\tif out == 20002:\n\t\t\tSUCCESS = True\n\t\telse:\n\t\t\tSUCCESS = False\n\t\treturn SUCCESS, copy.deepcopy(self.emccd_return_codes[out])\n\n\n\n\n\tdef SetFrameTransferMode(self, FRAME_TRANSFER_MODE):\n\t\t\"\"\"\n\t\t\t This function will set whether an acquisition will readout in Frame Transfer Mode. If the\n\t\t\t\tacquisition mode is Single Scan or Fast Kinetics this call will have no affect.\n\n\t\t\tParameters:\n\t\t\t\tFRAME_TRANSFER_MODE (bool)\n\n\t\t\"\"\"\n\n\t\tdummy = {True: \"ON\", False: \"OFF\"}\n\t\tcommand = {True: 1, False: 0}\n\t\tself.printout(message=\"Setting frame transfer mode to \"+dummy[FRAME_TRANSFER_MODE])\n\t\tout = self.dll.SetFrameTransferMode(ctypes.c_int(command[FRAME_TRANSFER_MODE]))\n\t\tself.printout(code=out)\n\t\tif out == 20002:\n\t\t\tSUCCESS = True\n\t\telse:\n\t\t\tSUCCESS = False\n\t\treturn SUCCESS, copy.deepcopy(self.emccd_return_codes[out])\t\n\n\n\n\n\tdef SetHSSpeed(self, typ, index):\n\t\t\"\"\"\n\t\t\tThis function will set the speed at which the pixels are shifted into the output node during\n\t\t\t\tthe readout phase of an acquisition. Typically your camera will be capable of operating at\n\t\t\t\tseveral horizontal shift speeds. To get the actual speed that an index corresponds to use\n\t\t\t\tthe GetHSSpeed function. \n\t\t\tThe actual speed in MHz are stored in self.horizontal_shifting_speeds\n\n\t\t\tParameters:\n\t\t\t\ttyp (int): \tOutput amplification mode\n\t\t\t\t\t\t\tValid values: \t0: electron multiplication/Conventional(clara).\n\t\t\t\t\t\t\t\t\t\t\t1: conventional/Extended NIR mode(clara).\n\n\t\t\t\tindex (int): The index of the horizontal speed to be used\n\n\t\t\"\"\"\n\n\t\tif not (typ==0 or typ==1):\n\t\t\traise Exception(\"Invalid amplification mode\")\n\t\tif not any([index == element for element in self.horizontal_shifting_speeds[typ].keys()]):\n\t\t\traise Exception(\"Invalid horizontal shifting speed\")\n\t\tself.printout(message=\"Setting horizontal shift speed to \"+str(self.horizontal_shifting_speeds[typ][index])+\" MHz\")\n\t\tout = self.dll.SetHSSpeed(ctypes.c_int(typ), ctypes.c_int(index))\n\t\tself.printout(code=out)\n\t\tif out == 20002:\n\t\t\tSUCCESS = True\n\t\telse:\n\t\t\tSUCCESS = False\n\t\treturn SUCCESS, copy.deepcopy(self.emccd_return_codes[out])\n\n\n\n\n\tdef SetVSSpeed(self, index):\n\t\t\"\"\"\n\t\t\tThis function will set the vertical speed to be used for subsequent acquisitions\n\n\t\t\tParameters:\n\t\t\t\t\n\t\t\t\tindex (int): The index into the vertical speed table\n\n\t\t\"\"\"\n\n\t\tif not any([index == element for element in self.vertical_shifting_speeds.keys()]):\n\t\t\traise Exception(\"Invalid vertical shifting speed\")\n\t\tself.printout(message=\"Setting vertical shift speed to \"+str(self.vertical_shifting_speeds[index])+\" ms per pixel shift\")\n\t\tout = self.dll.SetVSSpeed(ctypes.c_int(index))\n\t\tself.printout(code=out)\n\t\tif out == 20002:\n\t\t\tSUCCESS = True\n\t\telse:\n\t\t\tSUCCESS = False\n\t\treturn SUCCESS, copy.deepcopy(self.emccd_return_codes[out])\n\n\n\n\n\tdef SetPreAmpGain(self, index):\n\t\t\"\"\"\n\t\t\tThis function will set the pre amp gain to be used for subsequent acquisitions. The actual gain factor that will \n\t\t\t\tbe applied can be found through a call to the GetPreAmpGain function.\n\t\t\tThe number of Pre Amp Gains available is found by calling the GetNumberPreAmpGains function.\n\n\t\t\tParameters:\n\t\t\t\tindex (int): The index into the pre amp gain table\n\t\t\"\"\"\n\n\t\tif not any([index == element for element in self.preamp_gain_values.keys()]):\n\t\t\traise Exception(\"Invalid pre-amp gain index\")\n\t\tself.printout(message=\"Setting pre-amp gain to \"+str(self.preamp_gain_values[index])+\"x\")\n\t\tout = self.dll.SetPreAmpGain(ctypes.c_int(index))\n\t\tself.printout(code=out)\n\t\tif out == 20002:\n\t\t\tSUCCESS = True\n\t\telse:\n\t\t\tSUCCESS = False\n\t\treturn SUCCESS, copy.deepcopy(self.emccd_return_codes[out])\n\n\n\n\n\tdef SetEMCCDGain(self, gain):\n\t\t\"\"\"\n\t\t\tAllows the user to change the gain value. The valid range for the gain depends on what gain mode the camera is operating in. See SetEMGainMode to set the mode and\n\t\t\t\tGetEMGainRange to get the valid range to work with. To access higher gain values (>x300) see SetEMAdvanced.\n\n\t\t\tParameters:\n\t\t\t\tgain (int): gain values\n\n\t\t\"\"\"\n\n\t\tself.printout(message=\"Setting EMCCD gain\")\n\t\tFLAG, message, info = self.GetEMGainRange()\n\t\tlowest = info[\"lowest gain setting\"]\n\t\thighest = info[\"highest gain setting\"]\n\t\tif (gain>=lowest and gain<=highest):\n\t\t\tout = self.dll.SetEMCCDGain(ctypes.c_int(int(gain)))\n\t\t\tself.printout(code=out)\n\t\t\tif out == 20002:\n\t\t\t\tSUCCESS = True\n\t\t\telse:\n\t\t\t\tSUCCESS = False\n\t\t\tcode = copy.deepcopy(self.emccd_return_codes[out])\n\t\telse:\n\t\t\tself.printout(message=\"EMCCD gain value outside allowed range. Allowed range is [{0}, {1}]\".format(lowest, highest))\n\t\t\tSUCCESS = False\n\t\t\tcode = None\n\n\t\treturn SUCCESS, code\n\n\n\n\n\tdef SetEMAdvanced(self, STATE):\n\t\t\"\"\"\n\t\t\tThis function turns on and off access to higher EM gain levels within the SDK. Typically, \n\t\t\t\toptimal signal to noise ratio and dynamic range is achieved between x1 to x300 EM Gain.\n\t\t\tHigher gains of > x300 are recommended for single photon counting only. Before using\n\t\t\t\thigher levels, you should ensure that light levels do not exceed the regime of tens of\n\t\t\t\tphotons per pixel, otherwise accelerated ageing of the sensor can occur.\n\n\t\t\tParameters:\n\t\t\t\tSTATE (bool): \tTrue: Allow access\n\t\t\t\t\t\t\t\tFalse: Don't allow access\n\n\t\t\"\"\"\n\n\t\tif not (STATE==True or STATE==False):\n\t\t\traise Exception(\"Invalid state: bool expeccted\")\n\t\tself.printout(message=\"Setting EM advanced settings to \"+str(STATE))\n\t\tmodes = {True: 1, False: 0}\n\t\tout = self.dll.SetEMAdvanced(ctypes.c_int(modes[STATE]))\n\t\tself.printout(code=out)\n\t\tif out == 20002:\n\t\t\tSUCCESS = True\n\t\telse:\n\t\t\tSUCCESS = False\n\t\treturn SUCCESS, copy.deepcopy(self.emccd_return_codes[out])\n\n\n\n\n\n\tdef SetImage(self, hbin, vbin, hstart, hend, vstart, vend):\n\t\t\"\"\"\n\t\t\tThis function will set the horizontal and vertical binning to be used when taking a full\n\t\t\tresolution image.\n\n\t\t\tParameters:\n\n\t\t\t\thbin (int)\t\t: number of pixels to bin horizontally.\n\t\t\t\tvbin (int)\t\t: number of pixels to bin vertically.\n\t\t\t\thstart (int)\t: Start column (inclusive).\n\t\t\t\thend (int)\t\t: End column (inclusive).\n\t\t\t\tvstart (int)\t: Start row (inclusive).\n\t\t\t\tvend (int)\t\t: End row (inclusive).\n\t\t\n\t\t\"\"\"\n\n\t\tself.printout(message=\"Setting image format \")\n\t\tout = self.dll.SetImage(\n\t\t\tctypes.c_int(hbin),\n\t\t\tctypes.c_int(vbin),\n\t\t\tctypes.c_int(hstart),\n\t\t\tctypes.c_int(hend),\n\t\t\tctypes.c_int(vstart),\n\t\t\tctypes.c_int(vend))\n\t\tself.printout(code=out)\n\t\tif out == 20002:\n\t\t\tSUCCESS = True\n\t\t\tself.image_format = {\"x\": int(((hend-hstart+1)/hbin)), \"y\": int(((vend-vstart+1)/vbin))}\n\t\telse:\n\t\t\tSUCCESS = False\n\t\treturn SUCCESS, copy.deepcopy(self.emccd_return_codes[out])\n\n\n\n\n\tdef GetEMGainRange(self):\n\t\t\"\"\"\n\t\t\tReturns the minimum and maximum values of the current selected EM Gain mode and temperature of the sensor.\n\n\t\t\"\"\"\n\n\t\tself.printout(message=\"Getting EM Gain range\")\n\t\tlowest_gain_setting = ctypes.c_int()\n\t\thighest_gain_setting = ctypes.c_int()\n\t\tout = self.dll.GetEMGainRange(ctypes.pointer(lowest_gain_setting), ctypes.pointer(highest_gain_setting))\n\t\tself.printout(code=out)\n\t\tif out == 20002:\n\t\t\tSUCCESS = True\n\t\telse:\n\t\t\tSUCCESS = False\n\t\tinfo = {\"lowest gain setting\": lowest_gain_setting.value, \"highest gain setting\": highest_gain_setting.value}\n\n\t\treturn SUCCESS, copy.deepcopy(self.emccd_return_codes[out]), info\n\n\n\n\tdef GetAcquisitionTimings(self):\n\t\t\"\"\"\n\t\t\tThis function will return the current \"valid\" acquisition timing information. This function\n\t\t\t\tshould be used after all the acquisitions settings have been set, e.g. SetExposureTime,\n\t\t\t\tSetKineticCycleTime and SetReadMode etc. The values returned are the actual times\n\t\t\t\tused in subsequent acquisitions.\n\t\t\tThis function is required as it is possible to set the exposure time to 20ms, accumulate\n\t\t\t\tcycle time to 30ms and then set the readout mode to full image. As it can take 250ms to\n\t\t\t\tread out an image it is not possible to have a cycle time of 30ms.\n\n\t\t\"\"\"\n\n\t\tself.printout(message=\"Getting acquisition timings:\")\n\t\texposure_time = ctypes.c_float()\n\t\taccumulate_cycle_time = ctypes.c_float()\n\t\tkinetic_cycle_time = ctypes.c_float()\n\t\tout = self.dll.GetAcquisitionTimings(\n\t\t\tctypes.pointer(exposure_time), \n\t\t\tctypes.pointer(accumulate_cycle_time),\n\t\t\tctypes.pointer(kinetic_cycle_time))\n\t\tself.printout(code=out)\n\t\tif out == 20002:\n\t\t\tSUCCESS = True\n\t\telse:\n\t\t\tSUCCESS = False\n\t\tinfo = {\"exposure time\": exposure_time.value,\n\t\t\t\t\"accumulate cycle time\": accumulate_cycle_time.value,\n\t\t\t\t\"kinetic cycle time\": kinetic_cycle_time.value}\n\n\t\treturn SUCCESS, copy.deepcopy(self.emccd_return_codes[out]), info\n\n\n\n\n\tdef GetStatus(self, VERBOSE=True):\n\t\t\"\"\"\n\t\t\tThis function will return the current status of the Andor SDK system. This function should\n\t\t\t\tbe called before an acquisition is started to ensure that it is IDLE and during an acquisition\n\t\t\t\tto monitor the process.\n\n\t\t\"\"\"\n\t\tif VERBOSE:\n\t\t\tself.printout(message=\"Getting Status\")\n\t\tstatus = ctypes.c_int()\n\t\tout = self.dll.GetStatus(ctypes.pointer(status))\n\t\tif VERBOSE:\n\t\t\tself.printout(code=out)\n\t\tif out == 20002:\n\t\t\tSUCCESS = True\n\t\t\tstatus = status.value\n\t\t\tinfo = self.emccd_return_codes[status]\n\t\telse:\n\t\t\tSUCCESS = False\n\t\t\tinfo = None\n\t\treturn SUCCESS, copy.deepcopy(self.emccd_return_codes[out]), info\n\n\n\n\n\tdef GetAcquiredData(self, VERBOSE=True):\n\t\t\"\"\"\n\t\t\tThis function will return the data from the last acquisition. The data are returned as long\n\t\t\t\tintegers (32-bit signed integers). The \"array\" must be large enough to hold the complete\n\t\t\t\tdata set.\n\n\t\t\"\"\"\n\n\t\tif not self.image_format is None:\n\t\t\tif VERBOSE:\n\t\t\t\tself.printout(message=\"Getting acquired data\")\n\t\t\tfull_size = self.image_format[\"x\"]*self.image_format[\"y\"]\n\t\t\tarray = (ctypes.c_int*full_size)()\n\t\t\tout = self.dll.GetMostRecentImage(ctypes.pointer(array), ctypes.c_ulong(full_size))\n\t\t\tif out == 20002:\n\t\t\t\tSUCCESS = True\n\t\t\t\tarray = np.array([value for value in array])\n\t\t\t\timage = np.reshape(array, (self.image_format[\"x\"], self.image_format[\"y\"]))\n\t\t\t\timage = np.transpose(np.flip(image,1))\n\t\t\telse:\n\t\t\t\tSUCCESS = False\n\t\t\t\timage = None\n\t\t\tmessage = copy.deepcopy(self.emccd_return_codes[out])\n\t\telse:\n\t\t\tself.printout(message=\"Cannot acquire data before setting image format. Use SetImage() method\")\n\t\t\tSUCCESS = False\n\t\t\tmessage = None\n\t\t\timage = None\n\t\treturn SUCCESS, message, image\n\n\n\n\tdef StartAcquisition(self):\n\t\t\"\"\"\n\t\t\tThis function starts an acquisition. The status of the acquisition can be monitored via\n\t\t\t\tGetStatus().\n\n\t\t\"\"\"\n\n\t\tself.printout(message=\"Starting Acquisition\")\n\t\tout = self.dll.StartAcquisition()\n\t\tself.printout(code=out)\n\t\tif out == 20002:\n\t\t\tSUCCESS = True\n\t\telse:\n\t\t\tSUCCESS = False\n\t\treturn SUCCESS, copy.deepcopy(self.emccd_return_codes[out])\t\n\n\n\n\tdef AbortAcquisition(self):\n\t\t\"\"\"\n\t\t\t\tThis function aborts the current acquisition if one is active.\n\n\t\t\"\"\"\n\t\tself.printout(message=\"Aborting Acquisition\")\n\t\tout = self.dll.AbortAcquisition()\n\t\tself.printout(code=out)\n\t\tif out == 20002:\n\t\t\tSUCCESS = True\n\t\telse:\n\t\t\tSUCCESS = False\n\t\treturn SUCCESS, copy.deepcopy(self.emccd_return_codes[out])\t\n\n\n\n\n\tdef ShutDown(self, temperature):\n\t\t\"\"\"\n\t\t\tShutdown procedure.\n\t\t\t1) Sets the temperature to \"temperature\". It is important not to shut down\n\t\t\t\tthe SDK while temperature if below -20 C\n\t\t\t2) Waits for temperature to stabilize around the input temperature. \n\t\t\t3) Cooler off\n\t\t\t4) Shuts down SDK\n\n\t\t\tParameters:\n\n\t\t\t\ttemperature (int): \tDesired detector temperature (in C)\n\n\t\t\"\"\"\n\n\t\tself.printout(message=\"Closing shutter\")\n\t\tself.SetShutter(typ=0, mode=\"permanently closed\", closingtime=0, openingtime=0)\n\t\tself.printout(message=\"Starting shut down procedure\")\n\t\tself.SetTemperature(temperature=temperature)\n\t\tself.StabilizeTemperature()\n\t\tself.CoolerOFF()\n\t\tself.printout(message=\"Shutting down SDK\")\n\t\tout = self.dll.ShutDown()\n\t\tself.printout(code=out)\n\t\tif out == 20002:\n\t\t\tSUCCESS = True\n\t\telse:\n\t\t\tSUCCESS = False\n\t\treturn SUCCESS, copy.deepcopy(self.emccd_return_codes[out])\t\t\n\n\n\nclass OpAcquire(EMCCD):\n\t\"\"\" \n\t\tWraps the OpAcquire functionality\n\t\"\"\"\n\n\tparam_type = dict()\n\tparam_type.update({\"mode_description\": \"str\"})\n\tparam_type.update({\"output_amplifier\": \"str\"})\n\tparam_type.update({\"frame_transfer\": \"str\"})\n\tparam_type.update({\"readout_rate\": \"float\"})\n\tparam_type.update({\"electron_multiplying_gain\": \"int\"})\n\tparam_type.update({\"vertical_clock_amplitude\": \"int\"})\n\tparam_type.update({\"preamplifier_gain\": \"int\"})\n\tparam_type.update({\"shift_speed\": \"float\"})\n\n\n\tdef __init__(self, VERBOSE=True):\n\t\tsuper().__init__(VERBOSE=VERBOSE)\n\n\n\tdef OA_Initialize(self, file=None):\n\t\t\"\"\"\n\t\t\tThis function will initialise the OptAcquire settings from a Preset file and a User defined file if it exists.\n\n\t\t\"\"\"\n\t\tself.printout(message=\"OA: Initialing OpAcquire\")\n\t\tif file == None:\n\t\t\tfile = \"MyFile.xml\"\n\t\tcfile = (ctypes.c_char*len(file))()\n\t\tout = self.dll.OA_Initialize(ctypes.pointer(cfile), ctypes.c_ulong(len(file)))\n\t\tself.printout(code=out)\n\t\tif out == 20002:\n\t\t\tSUCCESS = True\n\t\telse:\n\t\t\tSUCCESS = False\n\t\tinfo = None\n\n\t\treturn SUCCESS, copy.deepcopy(self.emccd_return_codes[out]), info\n\n\n\n\tdef OA_GetNumberOfPreSetModes(self):\n\t\t\"\"\"\n\t\t\tThis function will return the number of modes defined in the Preset file. The Preset file must exist.\n\n\t\t\"\"\"\n\t\tself.printout(message=\"OA: Getting number of OpAcquire modes.\")\n\t\tn_modes = ctypes.c_int()\n\t\tout = self.dll.OA_GetNumberOfPreSetModes(ctypes.pointer(n_modes))\n\t\tself.printout(code=out)\n\t\tif out == 20002:\n\t\t\tSUCCESS = True\n\t\t\tinfo = n_modes.value\n\t\telse:\n\t\t\tSUCCESS = False\n\t\t\tinfo = None\n\n\t\treturn SUCCESS, copy.deepcopy(self.emccd_return_codes[out]), info\n\n\n\n\tdef OA_GetPreSetModeNames(self):\n\t\t\"\"\"\n\t\t\tThis function will return the available mode names from the Preset file. The mode and the Preset file must exist.\n\t\t\tThe user must allocate enough memory for all of the acquisition parameters.\n\n\t\t\"\"\"\n\t\tself.printout(message=\"OA: Getting OpAcquire modes names\")\n\t\tSUCCESS, message, n_modes = self.OA_GetNumberOfPreSetModes()\n\t\tif SUCCESS:\n\t\t\tarray = (ctypes.c_char*(255*n_modes))()\n\t\t\tout = self.dll.OA_GetPreSetModeNames(ctypes.pointer(array))\n\t\t\tself.printout(code=out)\n\t\t\tif out == 20002:\n\t\t\t\tSUCCESS = True\n\t\t\t\tinfo = array.value.decode()\n\t\t\t\tinfo = info.split(\",\")[:-1]\n\t\t\telse:\n\t\t\t\tSUCCESS = False\n\t\t\t\tinfo = None\n\t\t\tmessage = self.emccd_return_codes[out]\n\t\telse:\n\t\t\tSUCCESS = False\n\n\t\treturn SUCCESS, message, info\n\n\n\n\tdef OA_GetNumberOfAcqParams(self, mode_name):\n\t\t\"\"\"\n\t\t\tThis function will return the parameters associated with a specified mode. The mode must be present in either the Preset file or the User defined file.\n\n\t\t\tParameters:\n\t\t\t\tmode_name (str):\tMode name\n\n\t\t\"\"\"\n\t\tself.printout(message=\"OA: Getting number of parameters associated with mode: \"+mode_name)\n\t\tmode = ctypes.c_char_p(mode_name.encode())\n\t\tn = ctypes.c_int()\n\t\tout = self.dll.OA_GetNumberOfAcqParams(mode, ctypes.pointer(n))\n\t\tself.printout(code=out)\n\t\tif out == 20002:\n\t\t\tSUCCESS = True\n\t\t\tinfo = n.value\n\t\telse:\n\t\t\tSUCCESS = False\n\t\t\tinfo = None\n\n\t\treturn SUCCESS, copy.deepcopy(self.emccd_return_codes[out]), info\n\n\n\n\tdef OA_GetModeAcqParams(self, mode_name):\n\t\t\"\"\"\n\t\t\tThis function will return all acquisition parameters associated with the specified mode. \n\t\t\tThe mode specified by the user must be in either the Preset file or the User defined file.\n\n\t\t\tParameters:\n\t\t\t\tmode_name (str):\tMode name\n\n\t\t\"\"\"\n\t\tself.printout(message=\"OA: Getting parameters for mode: \"+mode_name)\n\t\tSUCCESS, message, n_params = self.OA_GetNumberOfAcqParams(mode_name=mode_name)\n\t\tif SUCCESS is True:\n\t\t\tmode = ctypes.c_char_p(mode_name.encode())\n\t\t\tparams = (ctypes.c_char*(255*n_params))()\n\t\t\tout = self.dll.OA_GetModeAcqParams(mode, ctypes.pointer(params))\n\t\t\tself.printout(code=out)\n\t\t\tmessage = copy.deepcopy(self.emccd_return_codes[out])\n\t\t\tif out == 20002:\n\t\t\t\tSUCCESS = True\n\t\t\t\tinfo = params.value.decode()\n\t\t\t\tinfo = info.split(\",\")[:-1]\n\t\t\telse:\n\t\t\t\tSUCCESS = False\n\t\t\t\tinfo = None\n\n\t\t\treturn SUCCESS, message, info\n\n\n\n\tdef GetParamValue(self, mode_name, param_name):\n\t\t\"\"\"\n\t\t\tGrabs the value of the parameter \"param_name\", in the mode \"mode_name\"\n\n\t\t\tParameters:\n\t\t\t\tmode_name (str)\n\t\t\t\tparam_name (str)\n\t\t\n\t\t\"\"\"\n\t\tself.printout(message=\"OA: Getting parameter value\")\n\t\tSUCCESS, message, params_list = self.OA_GetModeAcqParams(mode_name=mode_name)\n\t\tif SUCCESS:\n\t\t\tif not param_name in params_list:\n\t\t\t\traise Exception(\"Invalid parameter name\")\n\t\t\telse:\n\t\t\t\tmode = ctypes.c_char_p(mode_name.encode())\n\t\t\t\tparam = ctypes.c_char_p(param_name.encode())\n\t\t\t\tparam_type = self.param_type[param_name]\n\t\t\t\tif param_type == \"str\":\n\t\t\t\t\tvalue = (ctypes.c_char*255)()\n\t\t\t\t\tout = self.dll.OA_GetString(mode, param, ctypes.pointer(value), ctypes.c_ulong(255))\n\t\t\t\telif param_type == \"int\":\n\t\t\t\t\tvalue = ctypes.c_ulong()\n\t\t\t\t\tout = self.dll.OA_GetInt(mode, param, ctypes.pointer(value))\n\t\t\t\telif param_type == \"float\":\n\t\t\t\t\tvalue = ctypes.c_float()\n\t\t\t\t\tout = self.dll.OA_GetFloat(mode, param, ctypes.pointer(value))\n\t\t\t\telse:\n\t\t\t\t\traise Exception(\"Coding error\")\n\t\t\t\tself.printout(code=out)\n\t\t\t\tmessage = copy.deepcopy(self.emccd_return_codes[out])\n\t\t\t\tif out == 20002:\n\t\t\t\t\tSUCCESS = True\n\t\t\t\t\tif param_type == \"str\":\n\t\t\t\t\t\tinfo = value.value.decode()\n\t\t\t\t\telse:\n\t\t\t\t\t\tinfo = value.value\n\t\t\t\telse:\n\t\t\t\t\tSUCCESS = False\n\t\t\t\t\tinfo = None\n\t\telse:\n\t\t\tinfo = None\n\t\treturn SUCCESS, message, info\n\n\n\n\tdef OA_EnableMode(self, mode_name):\n\t\t\"\"\"\n\t\t\tThis function will set all the parameters associated with the specified mode to be used for all subsequent acquisitions. \n\t\t\tThe mode specified by the user must be in either the Preset file or the User defined file.\n\n\t\t\tParameters:\n\t\t\t\tmode_name (str)\n\n\t\t\"\"\"\n\t\tself.printout(message=\"OA: Setting mode to: \"+mode_name)\n\t\tmode = ctypes.c_char_p(mode_name.encode())\n\n\t\tout = self.dll.OA_EnableMode(mode)\n\t\tself.printout(code=out)\n\t\tif out == 20002:\n\t\t\tSUCCESS = True\n\t\telse:\n\t\t\tSUCCESS = False\n\t\treturn SUCCESS, copy.deepcopy(self.emccd_return_codes[out])\n\n\n"
] | [
[
"numpy.reshape",
"numpy.array",
"numpy.flip"
]
] |
Sreehari-S/mask-rcnn-benchmark | [
"b4434c39fccda80575276308da86b6e944540445"
] | [
"train_net.py"
] | [
"# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\nr\"\"\"\nBasic training script for PyTorch\n\"\"\"\n\n# Set up custom environment before nearly anything else is imported\n# NOTE: this should be the first import (no not reorder)\nfrom maskrcnn_benchmark.utils.env import setup_environment # noqa F401 isort:skip\n\nimport argparse\nimport os\n\nimport torch\nfrom maskrcnn_benchmark.config import cfg\nfrom maskrcnn_benchmark.data import make_data_loader\nfrom maskrcnn_benchmark.solver import make_lr_scheduler\nfrom maskrcnn_benchmark.solver import make_optimizer\nfrom maskrcnn_benchmark.engine.inference import inference\nfrom maskrcnn_benchmark.engine.trainer import do_train\nfrom maskrcnn_benchmark.modeling.detector import build_detection_model\nfrom maskrcnn_benchmark.utils.checkpoint import DetectronCheckpointer\nfrom maskrcnn_benchmark.utils.collect_env import collect_env_info\nfrom maskrcnn_benchmark.utils.comm import synchronize, get_rank\nfrom maskrcnn_benchmark.utils.imports import import_file\nfrom maskrcnn_benchmark.utils.logger import setup_logger\nfrom maskrcnn_benchmark.utils.miscellaneous import mkdir\n\n\ndef train(cfg, local_rank, distributed):\n model = build_detection_model(cfg)\n model.eval()\n device = torch.device(cfg.MODEL.DEVICE)\n model.to(device)\n save_dir = cfg.OUTPUT_DIR\n\n checkpointer = DetectronCheckpointer(cfg, model, save_dir=save_dir)\n _ = checkpointer.load(cfg.MODEL.WEIGHT) \n\n optimizer = make_optimizer(cfg, model)\n scheduler = make_lr_scheduler(cfg, optimizer)\n\n if distributed:\n model = torch.nn.parallel.DistributedDataParallel(\n model, device_ids=[local_rank], output_device=local_rank,\n # this should be removed if we update BatchNorm stats\n broadcast_buffers=False,\n )\n\n arguments = {}\n arguments[\"iteration\"] = 0\n\n output_dir = cfg.OUTPUT_DIR\n\n save_to_disk = get_rank() == 0\n checkpointer = DetectronCheckpointer(\n cfg, model, optimizer, scheduler, output_dir, save_to_disk\n )\n extra_checkpoint_data = checkpointer.load(cfg.MODEL.WEIGHT)\n arguments.update(extra_checkpoint_data)\n\n data_loader = make_data_loader(\n cfg,\n is_train=True,\n is_distributed=distributed,\n start_iter=arguments[\"iteration\"],\n )\n\n checkpoint_period = cfg.SOLVER.CHECKPOINT_PERIOD\n total_iter = 180000 ###############################################################\n\n do_train(\n total_iter,\n model,\n data_loader,\n optimizer,\n scheduler,\n checkpointer,\n device,\n checkpoint_period,\n arguments,\n )\n\n return model\n\n\ndef run_test(cfg, model, distributed):\n if distributed:\n model = model.module\n torch.cuda.empty_cache() # TODO check if it helps\n iou_types = (\"bbox\",)\n if cfg.MODEL.MASK_ON:\n iou_types = iou_types + (\"segm\",)\n if cfg.MODEL.KEYPOINT_ON:\n iou_types = iou_types + (\"keypoints\",)\n output_folders = [None] * len(cfg.DATASETS.TEST)\n dataset_names = cfg.DATASETS.TEST\n if cfg.OUTPUT_DIR:\n for idx, dataset_name in enumerate(dataset_names):\n output_folder = os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_name)\n mkdir(output_folder)\n output_folders[idx] = output_folder\n data_loaders_val = make_data_loader(cfg, is_train=False, is_distributed=distributed)\n for output_folder, dataset_name, data_loader_val in zip(output_folders, dataset_names, data_loaders_val):\n inference(\n model,\n data_loader_val,\n dataset_name=dataset_name,\n iou_types=iou_types,\n box_only=False if cfg.MODEL.RETINANET_ON else cfg.MODEL.RPN_ONLY,\n device=cfg.MODEL.DEVICE,\n expected_results=cfg.TEST.EXPECTED_RESULTS,\n expected_results_sigma_tol=cfg.TEST.EXPECTED_RESULTS_SIGMA_TOL,\n output_folder=output_folder,\n )\n synchronize()\n\n\ndef main():\n parser = argparse.ArgumentParser(description=\"PyTorch Object Detection Training\")\n parser.add_argument(\n \"--config-file\",\n default=\"\",\n metavar=\"FILE\",\n help=\"path to config file\",\n type=str,\n )\n parser.add_argument(\"--local_rank\", type=int, default=0)\n parser.add_argument(\n \"--skip-test\",\n dest=\"skip_test\",\n help=\"Do not test the final model\",\n action=\"store_true\",\n )\n parser.add_argument(\n \"opts\",\n help=\"Modify config options using the command-line\",\n default=None,\n nargs=argparse.REMAINDER,\n )\n\n args = parser.parse_args()\n\n num_gpus = int(os.environ[\"WORLD_SIZE\"]) if \"WORLD_SIZE\" in os.environ else 1\n args.distributed = num_gpus > 1\n\n if args.distributed:\n torch.cuda.set_device(args.local_rank)\n torch.distributed.init_process_group(\n backend=\"nccl\", init_method=\"env://\"\n )\n synchronize()\n\n cfg.merge_from_file(args.config_file)\n cfg.merge_from_list(args.opts)\n cfg.freeze()\n\n output_dir = cfg.OUTPUT_DIR\n if output_dir:\n mkdir(output_dir)\n\n logger = setup_logger(\"maskrcnn_benchmark\", output_dir, get_rank())\n logger.info(\"Using {} GPUs\".format(num_gpus))\n logger.info(args)\n\n logger.info(\"Collecting env info (might take some time)\")\n logger.info(\"\\n\" + collect_env_info())\n\n logger.info(\"Loaded configuration file {}\".format(args.config_file))\n with open(args.config_file, \"r\") as cf:\n config_str = \"\\n\" + cf.read()\n logger.info(config_str)\n logger.info(\"Running with config:\\n{}\".format(cfg))\n\n model = train(cfg, args.local_rank, args.distributed)\n\n # if not args.skip_test:\n # run_test(cfg, model, args.distributed)\n\n\nif __name__ == \"__main__\":\n main()\n"
] | [
[
"torch.distributed.init_process_group",
"torch.cuda.set_device",
"torch.cuda.empty_cache",
"torch.device",
"torch.nn.parallel.DistributedDataParallel"
]
] |
sighingnow/numba | [
"ae88a6ff4a41f76e50672a1af9d9aa66c205b51b"
] | [
"numba/targets/npyimpl.py"
] | [
"\"\"\"\nImplementation of functions in the Numpy package.\n\"\"\"\n\nfrom __future__ import print_function, division, absolute_import\n\nimport math\nimport sys\nimport itertools\nfrom collections import namedtuple\n\nfrom llvmlite.llvmpy import core as lc\n\nimport numpy as np\nimport operator\n\nfrom . import builtins, callconv, ufunc_db, arrayobj\nfrom .imputils import Registry, impl_ret_new_ref, force_error_model\nfrom .. import typing, types, cgutils, numpy_support, utils\nfrom ..config import PYVERSION\nfrom ..numpy_support import ufunc_find_matching_loop, select_array_wrapper, from_dtype\nfrom ..typing import npydecl\nfrom ..extending import overload, intrinsic\n\nfrom .. import errors\n\nregistry = Registry()\nlower = registry.lower\n\n\n########################################################################\n\n# In the way we generate code, ufuncs work with scalar as well as\n# with array arguments. The following helper classes help dealing\n# with scalar and array arguments in a regular way.\n#\n# In short, the classes provide a uniform interface. The interface\n# handles the indexing of as many dimensions as the array may have.\n# For scalars, all indexing is ignored and when the value is read,\n# the scalar is returned. For arrays code for actual indexing is\n# generated and reading performs the appropriate indirection.\n\nclass _ScalarIndexingHelper(object):\n def update_indices(self, loop_indices, name):\n pass\n\n def as_values(self):\n pass\n\n\nclass _ScalarHelper(object):\n \"\"\"Helper class to handle scalar arguments (and result).\n Note that store_data is only used when generating code for\n a scalar ufunc and to write the output value.\n\n For loading, the value is directly used without having any\n kind of indexing nor memory backing it up. This is the use\n for input arguments.\n\n For storing, a variable is created in the stack where the\n value will be written.\n\n Note that it is not supported (as it is unneeded for our\n current use-cases) reading back a stored value. This class\n will always \"load\" the original value it got at its creation.\n \"\"\"\n def __init__(self, ctxt, bld, val, ty):\n self.context = ctxt\n self.builder = bld\n self.val = val\n self.base_type = ty\n intpty = ctxt.get_value_type(types.intp)\n self.shape = [lc.Constant.int(intpty, 1)]\n\n lty = ctxt.get_data_type(ty) if ty != types.boolean else lc.Type.int(1)\n self._ptr = cgutils.alloca_once(bld, lty)\n\n def create_iter_indices(self):\n return _ScalarIndexingHelper()\n\n def load_data(self, indices):\n return self.val\n\n def store_data(self, indices, val):\n self.builder.store(val, self._ptr)\n\n @property\n def return_val(self):\n return self.builder.load(self._ptr)\n\n\nclass _ArrayIndexingHelper(namedtuple('_ArrayIndexingHelper',\n ('array', 'indices'))):\n def update_indices(self, loop_indices, name):\n bld = self.array.builder\n intpty = self.array.context.get_value_type(types.intp)\n ONE = lc.Constant.int(lc.Type.int(intpty.width), 1)\n\n # we are only interested in as many inner dimensions as dimensions\n # the indexed array has (the outer dimensions are broadcast, so\n # ignoring the outer indices produces the desired result.\n indices = loop_indices[len(loop_indices) - len(self.indices):]\n for src, dst, dim in zip(indices, self.indices, self.array.shape):\n cond = bld.icmp(lc.ICMP_UGT, dim, ONE)\n with bld.if_then(cond):\n bld.store(src, dst)\n\n def as_values(self):\n \"\"\"\n The indexing helper is built using alloca for each value, so it\n actually contains pointers to the actual indices to load. Note\n that update_indices assumes the same. This method returns the\n indices as values\n \"\"\"\n bld = self.array.builder\n return [bld.load(index) for index in self.indices]\n\n\nclass _ArrayHelper(namedtuple('_ArrayHelper', ('context', 'builder',\n 'shape', 'strides', 'data',\n 'layout', 'base_type', 'ndim',\n 'return_val'))):\n \"\"\"Helper class to handle array arguments/result.\n It provides methods to generate code loading/storing specific\n items as well as support code for handling indices.\n \"\"\"\n def create_iter_indices(self):\n intpty = self.context.get_value_type(types.intp)\n ZERO = lc.Constant.int(lc.Type.int(intpty.width), 0)\n\n indices = []\n for i in range(self.ndim):\n x = cgutils.alloca_once(self.builder, lc.Type.int(intpty.width))\n self.builder.store(ZERO, x)\n indices.append(x)\n return _ArrayIndexingHelper(self, indices)\n\n def _load_effective_address(self, indices):\n return cgutils.get_item_pointer2(self.builder,\n data=self.data,\n shape=self.shape,\n strides=self.strides,\n layout=self.layout,\n inds=indices)\n\n def load_data(self, indices):\n model = self.context.data_model_manager[self.base_type]\n ptr = self._load_effective_address(indices)\n return model.load_from_data_pointer(self.builder, ptr)\n\n def store_data(self, indices, value):\n ctx = self.context\n bld = self.builder\n store_value = ctx.get_value_as_data(bld, self.base_type, value)\n assert ctx.get_data_type(self.base_type) == store_value.type\n bld.store(store_value, self._load_effective_address(indices))\n\n\ndef _prepare_argument(ctxt, bld, inp, tyinp, where='input operand'):\n \"\"\"returns an instance of the appropriate Helper (either\n _ScalarHelper or _ArrayHelper) class to handle the argument.\n using the polymorphic interface of the Helper classes, scalar\n and array cases can be handled with the same code\"\"\"\n if isinstance(tyinp, types.ArrayCompatible):\n ary = ctxt.make_array(tyinp)(ctxt, bld, inp)\n shape = cgutils.unpack_tuple(bld, ary.shape, tyinp.ndim)\n strides = cgutils.unpack_tuple(bld, ary.strides, tyinp.ndim)\n return _ArrayHelper(ctxt, bld, shape, strides, ary.data,\n tyinp.layout, tyinp.dtype, tyinp.ndim, inp)\n elif types.unliteral(tyinp) in types.number_domain | set([types.boolean]):\n return _ScalarHelper(ctxt, bld, inp, tyinp)\n else:\n raise NotImplementedError('unsupported type for {0}: {1}'.format(where, str(tyinp)))\n\n\n_broadcast_onto_sig = types.intp(types.intp, types.CPointer(types.intp),\n types.intp, types.CPointer(types.intp))\ndef _broadcast_onto(src_ndim, src_shape, dest_ndim, dest_shape):\n '''Low-level utility function used in calculating a shape for\n an implicit output array. This function assumes that the\n destination shape is an LLVM pointer to a C-style array that was\n already initialized to a size of one along all axes.\n\n Returns an integer value:\n >= 1 : Succeeded. Return value should equal the number of dimensions in\n the destination shape.\n 0 : Failed to broadcast because source shape is larger than the\n destination shape (this case should be weeded out at type\n checking).\n < 0 : Failed to broadcast onto destination axis, at axis number ==\n -(return_value + 1).\n '''\n if src_ndim > dest_ndim:\n # This check should have been done during type checking, but\n # let's be defensive anyway...\n return 0\n else:\n src_index = 0\n dest_index = dest_ndim - src_ndim\n while src_index < src_ndim:\n src_dim_size = src_shape[src_index]\n dest_dim_size = dest_shape[dest_index]\n # Check to see if we've already mutated the destination\n # shape along this axis.\n if dest_dim_size != 1:\n # If we have mutated the destination shape already,\n # then the source axis size must either be one,\n # or the destination axis size.\n if src_dim_size != dest_dim_size and src_dim_size != 1:\n return -(dest_index + 1)\n elif src_dim_size != 1:\n # If the destination size is still its initial\n dest_shape[dest_index] = src_dim_size\n src_index += 1\n dest_index += 1\n return dest_index\n\ndef _build_array(context, builder, array_ty, input_types, inputs):\n \"\"\"Utility function to handle allocation of an implicit output array\n given the target context, builder, output array type, and a list of\n _ArrayHelper instances.\n \"\"\"\n intp_ty = context.get_value_type(types.intp)\n def make_intp_const(val):\n return context.get_constant(types.intp, val)\n\n ZERO = make_intp_const(0)\n ONE = make_intp_const(1)\n\n src_shape = cgutils.alloca_once(builder, intp_ty, array_ty.ndim,\n \"src_shape\")\n dest_ndim = make_intp_const(array_ty.ndim)\n dest_shape = cgutils.alloca_once(builder, intp_ty, array_ty.ndim,\n \"dest_shape\")\n dest_shape_addrs = tuple(cgutils.gep_inbounds(builder, dest_shape, index)\n for index in range(array_ty.ndim))\n\n # Initialize the destination shape with all ones.\n for dest_shape_addr in dest_shape_addrs:\n builder.store(ONE, dest_shape_addr)\n\n # For each argument, try to broadcast onto the destination shape,\n # mutating along any axis where the argument shape is not one and\n # the destination shape is one.\n for arg_number, arg in enumerate(inputs):\n if not hasattr(arg, \"ndim\"): # Skip scalar arguments\n continue\n arg_ndim = make_intp_const(arg.ndim)\n for index in range(arg.ndim):\n builder.store(arg.shape[index],\n cgutils.gep_inbounds(builder, src_shape, index))\n arg_result = context.compile_internal(\n builder, _broadcast_onto, _broadcast_onto_sig,\n [arg_ndim, src_shape, dest_ndim, dest_shape])\n with cgutils.if_unlikely(builder,\n builder.icmp(lc.ICMP_SLT, arg_result, ONE)):\n msg = \"unable to broadcast argument %d to output array\" % (\n arg_number,)\n\n loc = errors.loc_info.get('loc', None)\n if loc is not None:\n msg += '\\nFile \"%s\", line %d, ' % (loc.filename, loc.line)\n\n context.call_conv.return_user_exc(builder, ValueError, (msg,))\n\n real_array_ty = array_ty.as_array\n\n dest_shape_tup = tuple(builder.load(dest_shape_addr)\n for dest_shape_addr in dest_shape_addrs)\n array_val = arrayobj._empty_nd_impl(context, builder, real_array_ty,\n dest_shape_tup)\n\n # Get the best argument to call __array_wrap__ on\n array_wrapper_index = select_array_wrapper(input_types)\n array_wrapper_ty = input_types[array_wrapper_index]\n try:\n # __array_wrap__(source wrapped array, out array) -> out wrapped array\n array_wrap = context.get_function('__array_wrap__',\n array_ty(array_wrapper_ty, real_array_ty))\n except NotImplementedError:\n # If it's the same priority as a regular array, assume we\n # should use the allocated array unchanged.\n if array_wrapper_ty.array_priority != types.Array.array_priority:\n raise\n out_val = array_val._getvalue()\n else:\n wrap_args = (inputs[array_wrapper_index].return_val, array_val._getvalue())\n out_val = array_wrap(builder, wrap_args)\n\n ndim = array_ty.ndim\n shape = cgutils.unpack_tuple(builder, array_val.shape, ndim)\n strides = cgutils.unpack_tuple(builder, array_val.strides, ndim)\n return _ArrayHelper(context, builder, shape, strides, array_val.data,\n array_ty.layout, array_ty.dtype, ndim,\n out_val)\n\n\ndef numpy_ufunc_kernel(context, builder, sig, args, kernel_class,\n explicit_output=True):\n # This is the code generator that builds all the looping needed\n # to execute a numpy functions over several dimensions (including\n # scalar cases).\n #\n # context - the code generation context\n # builder - the code emitter\n # sig - signature of the ufunc\n # args - the args to the ufunc\n # kernel_class - a code generating subclass of _Kernel that provides\n # explicit_output - if the output was explicit in the call\n # (ie: np.add(x,y,r))\n\n arguments = [_prepare_argument(context, builder, arg, tyarg)\n for arg, tyarg in zip(args, sig.args)]\n if not explicit_output:\n ret_ty = sig.return_type\n if isinstance(ret_ty, types.ArrayCompatible):\n output = _build_array(context, builder, ret_ty, sig.args, arguments)\n else:\n output = _prepare_argument(\n context, builder,\n lc.Constant.null(context.get_value_type(ret_ty)), ret_ty)\n arguments.append(output)\n elif context.enable_nrt:\n # Incref the output\n context.nrt.incref(builder, sig.return_type, args[-1])\n\n inputs = arguments[0:-1]\n output = arguments[-1]\n\n outer_sig = [a.base_type for a in arguments]\n #signature expects return type first, while we have it last:\n outer_sig = outer_sig[-1:] + outer_sig[:-1]\n outer_sig = typing.signature(*outer_sig)\n kernel = kernel_class(context, builder, outer_sig)\n intpty = context.get_value_type(types.intp)\n\n indices = [inp.create_iter_indices() for inp in inputs]\n\n loopshape = output.shape\n with cgutils.loop_nest(builder, loopshape, intp=intpty) as loop_indices:\n vals_in = []\n for i, (index, arg) in enumerate(zip(indices, inputs)):\n index.update_indices(loop_indices, i)\n vals_in.append(arg.load_data(index.as_values()))\n\n val_out = kernel.generate(*vals_in)\n output.store_data(loop_indices, val_out)\n out = arguments[-1].return_val\n return impl_ret_new_ref(context, builder, sig.return_type, out)\n\n\n# Kernels are the code to be executed inside the multidimensional loop.\nclass _Kernel(object):\n def __init__(self, context, builder, outer_sig):\n self.context = context\n self.builder = builder\n self.outer_sig = outer_sig\n\n def cast(self, val, fromty, toty):\n \"\"\"Numpy uses cast semantics that are different from standard Python\n (for example, it does allow casting from complex to float).\n\n This method acts as a patch to context.cast so that it allows\n complex to real/int casts.\n\n \"\"\"\n if (isinstance(fromty, types.Complex) and\n not isinstance(toty, types.Complex)):\n # attempt conversion of the real part to the specified type.\n # note that NumPy issues a warning in this kind of conversions\n newty = fromty.underlying_float\n attr = self.context.get_getattr(fromty, 'real')\n val = attr(self.context, self.builder, fromty, val, 'real')\n fromty = newty\n # let the regular cast do the rest...\n\n return self.context.cast(self.builder, val, fromty, toty)\n\n\ndef _ufunc_db_function(ufunc):\n \"\"\"Use the ufunc loop type information to select the code generation\n function from the table provided by the dict_of_kernels. The dict\n of kernels maps the loop identifier to a function with the\n following signature: (context, builder, signature, args).\n\n The loop type information has the form 'AB->C'. The letters to the\n left of '->' are the input types (specified as NumPy letter\n types). The letters to the right of '->' are the output\n types. There must be 'ufunc.nin' letters to the left of '->', and\n 'ufunc.nout' letters to the right.\n\n For example, a binary float loop resulting in a float, will have\n the following signature: 'ff->f'.\n\n A given ufunc implements many loops. The list of loops implemented\n for a given ufunc can be accessed using the 'types' attribute in\n the ufunc object. The NumPy machinery selects the first loop that\n fits a given calling signature (in our case, what we call the\n outer_sig). This logic is mimicked by 'ufunc_find_matching_loop'.\n \"\"\"\n\n class _KernelImpl(_Kernel):\n def __init__(self, context, builder, outer_sig):\n super(_KernelImpl, self).__init__(context, builder, outer_sig)\n loop = ufunc_find_matching_loop(\n ufunc, outer_sig.args + (outer_sig.return_type,))\n self.fn = ufunc_db.get_ufunc_info(ufunc).get(loop.ufunc_sig)\n self.inner_sig = typing.signature(\n *(loop.outputs + loop.inputs))\n\n if self.fn is None:\n msg = \"Don't know how to lower ufunc '{0}' for loop '{1}'\"\n raise NotImplementedError(msg.format(ufunc.__name__, loop))\n\n def generate(self, *args):\n isig = self.inner_sig\n osig = self.outer_sig\n\n cast_args = [self.cast(val, inty, outty)\n for val, inty, outty in zip(args, osig.args,\n isig.args)]\n with force_error_model(self.context, 'numpy'):\n res = self.fn(self.context, self.builder, isig, cast_args)\n dmm = self.context.data_model_manager\n res = dmm[isig.return_type].from_return(self.builder, res)\n return self.cast(res, isig.return_type, osig.return_type)\n\n return _KernelImpl\n\n\n################################################################################\n# Helper functions that register the ufuncs\n\n_kernels = {} # Temporary map from ufunc's to their kernel implementation class\n\ndef register_unary_ufunc_kernel(ufunc, kernel):\n def unary_ufunc(context, builder, sig, args):\n return numpy_ufunc_kernel(context, builder, sig, args, kernel)\n\n def unary_ufunc_no_explicit_output(context, builder, sig, args):\n return numpy_ufunc_kernel(context, builder, sig, args, kernel,\n explicit_output=False)\n\n _any = types.Any\n\n # (array or scalar, out=array)\n lower(ufunc, _any, types.Array)(unary_ufunc)\n # (array or scalar)\n lower(ufunc, _any)(unary_ufunc_no_explicit_output)\n\n _kernels[ufunc] = kernel\n\n\ndef register_binary_ufunc_kernel(ufunc, kernel):\n def binary_ufunc(context, builder, sig, args):\n return numpy_ufunc_kernel(context, builder, sig, args, kernel)\n\n def binary_ufunc_no_explicit_output(context, builder, sig, args):\n return numpy_ufunc_kernel(context, builder, sig, args, kernel,\n explicit_output=False)\n\n _any = types.Any\n\n # (array or scalar, array o scalar, out=array)\n lower(ufunc, _any, _any, types.Array)(binary_ufunc)\n # (scalar, scalar)\n lower(ufunc, _any, _any)(binary_ufunc_no_explicit_output)\n\n _kernels[ufunc] = kernel\n\n\ndef register_unary_operator_kernel(operator, kernel, inplace=False):\n assert not inplace # are there any inplace unary operators?\n def lower_unary_operator(context, builder, sig, args):\n return numpy_ufunc_kernel(context, builder, sig, args, kernel,\n explicit_output=False)\n _arr_kind = types.Array\n lower(operator, _arr_kind)(lower_unary_operator)\n\n\ndef register_binary_operator_kernel(op, kernel, inplace=False):\n def lower_binary_operator(context, builder, sig, args):\n return numpy_ufunc_kernel(context, builder, sig, args, kernel,\n explicit_output=False)\n\n def lower_inplace_operator(context, builder, sig, args):\n # The visible signature is (A, B) -> A\n # The implementation's signature (with explicit output)\n # is (A, B, A) -> A\n args = args + (args[0],)\n sig = typing.signature(sig.return_type, *sig.args + (sig.args[0],))\n return numpy_ufunc_kernel(context, builder, sig, args, kernel,\n explicit_output=True)\n\n _any = types.Any\n _arr_kind = types.Array\n formal_sigs = [(_arr_kind, _arr_kind), (_any, _arr_kind), (_arr_kind, _any)]\n for sig in formal_sigs:\n if not inplace:\n lower(op, *sig)(lower_binary_operator)\n else:\n lower(op, *sig)(lower_inplace_operator)\n\n\n\n################################################################################\n# Use the contents of ufunc_db to initialize the supported ufuncs\n\nfor ufunc in ufunc_db.get_ufuncs():\n if ufunc.nin == 1:\n register_unary_ufunc_kernel(ufunc, _ufunc_db_function(ufunc))\n elif ufunc.nin == 2:\n register_binary_ufunc_kernel(ufunc, _ufunc_db_function(ufunc))\n else:\n raise RuntimeError(\"Don't know how to register ufuncs from ufunc_db with arity > 2\")\n\n\n@lower(operator.pos, types.Array)\ndef array_positive_impl(context, builder, sig, args):\n '''Lowering function for +(array) expressions. Defined here\n (numba.targets.npyimpl) since the remaining array-operator\n lowering functions are also registered in this module.\n '''\n class _UnaryPositiveKernel(_Kernel):\n def generate(self, *args):\n [val] = args\n return val\n\n return numpy_ufunc_kernel(context, builder, sig, args,\n _UnaryPositiveKernel, explicit_output=False)\n\n\nfor _op_map in (npydecl.NumpyRulesUnaryArrayOperator._op_map,\n npydecl.NumpyRulesArrayOperator._op_map,\n ):\n for operator, ufunc_name in _op_map.items():\n ufunc = getattr(np, ufunc_name)\n kernel = _kernels[ufunc]\n if ufunc.nin == 1:\n register_unary_operator_kernel(operator, kernel)\n elif ufunc.nin == 2:\n register_binary_operator_kernel(operator, kernel)\n else:\n raise RuntimeError(\"There shouldn't be any non-unary or binary operators\")\n\nfor _op_map in (npydecl.NumpyRulesInplaceArrayOperator._op_map,\n ):\n for operator, ufunc_name in _op_map.items():\n ufunc = getattr(np, ufunc_name)\n kernel = _kernels[ufunc]\n if ufunc.nin == 1:\n register_unary_operator_kernel(operator, kernel, inplace=True)\n elif ufunc.nin == 2:\n register_binary_operator_kernel(operator, kernel, inplace=True)\n else:\n raise RuntimeError(\"There shouldn't be any non-unary or binary operators\")\n\n\n\ndel _kernels\n\n@intrinsic\ndef _make_dtype_object(typingctx, desc):\n \"\"\"Given a string or NumberClass description *desc*, returns the dtype object.\n \"\"\"\n def from_nb_type(nb_type):\n return_type = types.DType(nb_type)\n sig = return_type(desc)\n\n def codegen(context, builder, signature, args):\n # All dtype objects are dummy values in LLVM.\n # They only exist in the type level.\n return context.get_dummy_value()\n\n return sig, codegen\n\n if isinstance(desc, types.Literal):\n # Convert the str description into np.dtype then to numba type.\n nb_type = from_dtype(np.dtype(desc.literal_value))\n return from_nb_type(nb_type)\n elif isinstance(desc, types.functions.NumberClass):\n thestr = str(desc.dtype)\n # Convert the str description into np.dtype then to numba type.\n nb_type = from_dtype(np.dtype(thestr))\n return from_nb_type(nb_type)\n\n@overload(np.dtype)\ndef numpy_dtype(desc):\n \"\"\"Provide an implementation so that numpy.dtype function can be lowered.\n \"\"\"\n if isinstance(desc, (types.Literal, types.functions.NumberClass)):\n def imp(desc):\n return _make_dtype_object(desc)\n return imp\n else:\n raise TypeError('unknown dtype descriptor: {}'.format(desc))\n"
] | [
[
"numpy.dtype"
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.